[Scummvm-git-logs] scummvm master -> 72c0bd37837557520f267d6f341266eda3835dee

bluegr noreply at scummvm.org
Mon Nov 16 08:59:30 UTC 2026


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

Summary:
3380d63d85 NANCY: NANCY27: Fix the default channel of Sound records
927a0250b0 NANCY: NANCY26: Match text tags regardless of case
41b6b60f05 NANCY: NANCY26: Give the names of inventory items in capitals
bf97e4f60d VIDEO: Let other decoders use the audio tracks of Bink videos
75694532f3 VIDEO: Add a decoder for Bink 2 (revision 'f') videos
c41c492951 NANCY: NANCY29: Play Bink 2 movies
afdad61c5d NANCY: NANCY29: Read the longer tree names of XSheets
8502574e38 NANCY: NANCY29: Add Rect:Align
47452cde9b NANCY: NANCY29: Add Brain:Contains
7dcf74a220 NANCY: NANCY29: Add the new Game and Scene functions
091c4dea00 NANCY: NANCY29: Add the new sound channels
259eb7d874 NANCY: NANCY29: Add the new fields of Sound records
8326519054 NANCY: NANCY29: Let Inventory:Add put an item in front of the others
8cb320cc42 NANCY: NANCY29: Add the items the player wears on the face
93a138218f NANCY: NANCY29: Add the OverlayCombiner record
745a500beb NANCY: NANCY29: Add the animators of records
65f552eaaf NANCY: NANCY29: Add the achievements
17a7008d3e NANCY: NANCY29: Add detection entry
36f5265e45 VIDEO: BINK2: Add revision 'g' (KB2g)
57b525aee3 VIDEO: BINK2: Keep the sources of motion blocks inside the frame
294f61036b NANCY: NANCY30: Play the movies named .bk2
4dc65065f9 NANCY: NANCY30: Read the images marked as type 4
8fa2c6e179 NANCY: NANCY19: Don't decode looping movies of one frame again
05a968cc74 NANCY: NANCY30: Open Lua's debug library and add table.keysort
a5603ecdcf NANCY: NANCY30: Add Brain:FilteredNames
5ba20bc629 NANCY: NANCY30: Add the smaller additions to the script API
3279c17d3f NANCY: NANCY30: Show the first frame of a movie as an overlay
9f7ac74ee9 NANCY: NANCY30: Add Overlay:DefaultRects
c03e6bfd98 NANCY: NANCY30: Make the onScreen rect of Movie records optional
b9b52dd1b0 NANCY: NANCY30: Tell Sound records when an instance has ended
6594d1aaf4 NANCY: NANCY30: Add the tiles of Hotspot records
b0f000a723 NANCY: NANCY30: Add the steps of Slider records
8dabdf1129 NANCY: NANCY30: Call the OnDone function of animator stages
4de0658edf NANCY: NANCY30: Add the achievements
3b80ed37f4 NANCY: NANCY30: Add detection entry
a6e60bab49 NANCY: NANCY26: Let records answer the records that message them
a5175ff0c3 NANCY: NANCY30: Place .bk2 movies at the rect stored in them
a05e38091e NANCY: NANCY19: Cache the frames of panoramas
fd942ba007 NANCY: NANCY30: Let buttons react to the right mouse button
1610c6b320 NANCY: Use Steam achievements only for Nancy28
127aad8af7 NANCY: NANCY31: Add a few script functions
ef33f6f386 NANCY: NANCY31: Implement ar:Detach()
b4e465459e NANCY: NANCY31: Allow overlays to be drawn more than once
5b2472da1f NANCY: NANCY31: Add the allowSlide field of hotspots
800d365045 NANCY: NANCY31: Add the isLeft field of buttons
1f628f51e0 NANCY: NANCY31: Allow changing the group of radio buttons
ea755db3f6 NANCY: NANCY31: Add Scene.isGCThrottled
48f7736428 NANCY: NANCY31: Add the achievements
1bc75db0a8 NANCY: NANCY31: Add detection entry
20eb8227b6 VIDEO: BINK2: Convert the colors with the full range
0ddff740b7 NANCY: NANCY26: Keep the caches of the scripts in the game state
34d67d1a73 NANCY: NANCY30: Place images at the rect stored in them
00dfb1a39b NANCY: Don't seek when the frame of a movie is set
17f2b62a73 NANCY: NANCY21: Redraw particles only when they move
12f28ce17f NANCY: NANCY19: Only let boot scripts use the Init objects
96439b1f0f NANCY: NANCY32: Read XSheets from loose .cif files
7a052aec89 NANCY: NANCY32: Use 2D matrices
b264b3127a NANCY: NANCY32: Use points in place of vectors
be3cf59b3f NANCY: NANCY32: Add the polar track of the animator
bc556c646f NANCY: NANCY32: Let keys press hotspots
5399bca9b0 NANCY: NANCY32: Add new particle stages
d0301f1335 NANCY: NANCY32: Take the cursors of items from InventoryInit
ae7b542ffa NANCY: NANCY32: Add Scene:Lock and Scene:Unlock
41b17af4da NANCY: NANCY32: Add the achievements
72c0bd3783 NANCY: NANCY32: Add detection entry


Commit: 3380d63d85ccd0419aaf35e9151db684d77b8d60
    https://github.com/scummvm/scummvm/commit/3380d63d85ccd0419aaf35e9151db684d77b8d60
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:56:30+02:00

Commit Message:
NANCY: NANCY27: Fix the default channel of Sound records

A Sound record without a channel plays on FX1. Nancy27 and Nancy28 moved
FX1 to channel 11.

Changed paths:
    engines/nancy/script/records.cpp


diff --git a/engines/nancy/script/records.cpp b/engines/nancy/script/records.cpp
index a3cfb684904..e412d97ff86 100644
--- a/engines/nancy/script/records.cpp
+++ b/engines/nancy/script/records.cpp
@@ -1950,9 +1950,15 @@ void SoundRecord::readTable(int tableIndex) {
 }
 
 SoundRecord::SoundRecord(SceneContext &context) : Record(context, "ND.SoundAR") {
-	// FX1, which Nancy22 and Nancy23 have further up
+	// FX1, which moves with the channel tables
 	const GameType gameType = g_nancy->getGameType();
-	_channel = (gameType >= kGameTypeNancy22 && gameType <= kGameTypeNancy23) ? 16 : 14;
+	if (gameType >= kGameTypeNancy27) {
+		_channel = 11;
+	} else if (gameType >= kGameTypeNancy22 && gameType <= kGameTypeNancy23) {
+		_channel = 16;
+	} else {
+		_channel = 14;
+	}
 }
 
 void SoundRecord::readChannelType(int index) {


Commit: 927a0250b0562ccfe07fa7cb8b7f12d3e8d37c67
    https://github.com/scummvm/scummvm/commit/927a0250b0562ccfe07fa7cb8b7f12d3e8d37c67
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:56:38+02:00

Commit Message:
NANCY: NANCY26: Match text tags regardless of case

The original matches the tags in texts without regard to case, so <C0>
is the same as <c0>. Nancy29 writes some of them in capitals, which
were shown as text, e.g. "<C0>Mom?" at the start of a new game.

Changed paths:
    engines/nancy/script/v5/bitmaptext.cpp


diff --git a/engines/nancy/script/v5/bitmaptext.cpp b/engines/nancy/script/v5/bitmaptext.cpp
index 4510ccdeb3d..a16db9f3fb4 100644
--- a/engines/nancy/script/v5/bitmaptext.cpp
+++ b/engines/nancy/script/v5/bitmaptext.cpp
@@ -109,9 +109,11 @@ static const BitmapFont::Face *getFace(const BitmapFont *font, bool isBold, bool
 	return &font->faces[style];
 }
 
+// Tags are matched regardless of case, as in the original: <C0> is <c0>
+
 // Reads the number of a tag like <c12>; returns false when it is something else
 static bool readTagNumber(const Common::String &text, uint &pos, char letter, int &number) {
-	if (pos + 3 > text.size() || text[pos] != '<' || text[pos + 1] != letter || !Common::isDigit(text[pos + 2])) {
+	if (pos + 3 > text.size() || text[pos] != '<' || tolower((byte)text[pos + 1]) != letter || !Common::isDigit(text[pos + 2])) {
 		return false;
 	}
 
@@ -132,7 +134,7 @@ static bool readTagNumber(const Common::String &text, uint &pos, char letter, in
 
 static bool readTag(const Common::String &text, uint &pos, const char *tag) {
 	const uint length = strlen(tag);
-	if (pos + length > text.size() || strncmp(text.c_str() + pos, tag, length) != 0) {
+	if (pos + length > text.size() || scumm_strnicmp(text.c_str() + pos, tag, length) != 0) {
 		return false;
 	}
 


Commit: 41b6b60f050b7cac17274afeeac739b795f39e4e
    https://github.com/scummvm/scummvm/commit/41b6b60f050b7cac17274afeeac739b795f39e4e
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:56:42+02:00

Commit Message:
NANCY: NANCY26: Give the names of inventory items in capitals

The original turns the name of an item into capitals when it is added
to the inventory, so Inventory.current and Inventory.inHand give names
in capitals, whatever the scripts defined them as. The scripts of
Nancy29 look items up by those names. Without this, the key card in
scene 2215 couldn't be picked up from the inventory.

Changed paths:
    engines/nancy/script/v5/gamefunctions.cpp


diff --git a/engines/nancy/script/v5/gamefunctions.cpp b/engines/nancy/script/v5/gamefunctions.cpp
index b0b0d34ffc7..89908b51793 100644
--- a/engines/nancy/script/v5/gamefunctions.cpp
+++ b/engines/nancy/script/v5/gamefunctions.cpp
@@ -606,6 +606,14 @@ static const luaL_Reg kInventoryFunctions[] = {
 	{ nullptr, nullptr }
 };
 
+// The original stores inventory item names in capitals, however the scripts
+// defined them, and the scripts look the items up by these names
+static void pushItemName(lua_State *L, const Common::String &name) {
+	Common::String upperName = name;
+	upperName.toUppercase();
+	lua_pushstring(L, upperName.c_str());
+}
+
 static bool pushInventoryField(lua_State *L, const Common::String &key) {
 	for (const luaL_Reg *function = kInventoryFunctions; function->name; ++function) {
 		if (key == function->name) {
@@ -620,12 +628,12 @@ static bool pushInventoryField(lua_State *L, const Common::String &key) {
 		const Common::Array<int16> &order = NancySceneState.getInventoryOrder();
 		lua_createtable(L, order.size(), 0);
 		for (uint i = 0; inventory && i < order.size(); ++i) {
-			lua_pushstring(L, inventory->items[order[i]].name.c_str());
+			pushItemName(L, inventory->items[order[i]].name);
 			lua_rawseti(L, -2, i + 1);
 		}
 	} else if (key == "inHand") {
 		const int16 heldItem = NancySceneState.getHeldItem();
-		lua_pushstring(L, inventory && heldItem >= 0 && (uint)heldItem < inventory->items.size() ? inventory->items[heldItem].name.c_str() : "");
+		pushItemName(L, inventory && heldItem >= 0 && (uint)heldItem < inventory->items.size() ? inventory->items[heldItem].name : Common::String());
 	} else if (key == "currentChangeCount") {
 		lua_pushinteger(L, NancySceneState.getInventoryChangeCount());
 	} else if (key == "inHandChangeCount") {


Commit: bf97e4f60d9716e39aec3a45efbc8b59fe957153
    https://github.com/scummvm/scummvm/commit/bf97e4f60d9716e39aec3a45efbc8b59fe957153
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:56:51+02:00

Commit Message:
VIDEO: Let other decoders use the audio tracks of Bink videos

Bink 2 videos have the same audio as Bink 1 videos. The audio track of
the Bink decoder is now public and sets itself up from the rate and the
flags of the track, so that the Bink 2 decoder can use it as well.

Changed paths:
    video/bink_decoder.cpp
    video/bink_decoder.h


diff --git a/video/bink_decoder.cpp b/video/bink_decoder.cpp
index 55574f53a3e..5b01eb7f5ff 100644
--- a/video/bink_decoder.cpp
+++ b/video/bink_decoder.cpp
@@ -65,6 +65,7 @@ namespace Video {
 
 BinkDecoder::BinkDecoder() {
 	_bink = 0;
+	_audioTrackCount = 0;
 }
 
 BinkDecoder::~BinkDecoder() {
@@ -111,24 +112,20 @@ bool BinkDecoder::loadStream(Common::SeekableReadStream *stream) {
 	addTrack(new BinkVideoTrack(width, height, frameCount,
 			Common::Rational(frameRateNum, frameRateDen), (id == kBIKhID || id == kBIKiID), videoFlags & kVideoFlagAlpha, id));
 
-	uint32 audioTrackCount = _bink->readUint32LE();
+	_audioTrackCount = _bink->readUint32LE();
 
-	if (audioTrackCount > 0) {
-		_audioTracks.resize(audioTrackCount);
-
-		_bink->skip(4 * audioTrackCount);
+	if (_audioTrackCount > 0) {
+		_bink->skip(4 * _audioTrackCount);
 
 		// Reading audio track properties
-		for (uint32 i = 0; i < audioTrackCount; i++) {
-			AudioInfo &track = _audioTracks[i];
-
-			track.sampleRate = _bink->readUint16LE();
-			track.flags      = _bink->readUint16LE();
+		for (uint32 i = 0; i < _audioTrackCount; i++) {
+			uint16 sampleRate = _bink->readUint16LE();
+			uint16 flags      = _bink->readUint16LE();
 
-			initAudioTrack(track);
+			addTrack(new BinkAudioTrack(sampleRate, flags, getSoundType()));
 		}
 
-		_bink->skip(4 * audioTrackCount);
+		_bink->skip(4 * _audioTrackCount);
 	}
 
 	// Reading video frame properties
@@ -156,7 +153,7 @@ void BinkDecoder::close() {
 	delete _bink;
 	_bink = 0;
 
-	_audioTracks.clear();
+	_audioTrackCount = 0;
 	_frames.clear();
 }
 
@@ -173,9 +170,7 @@ void BinkDecoder::readNextPacket() {
 
 	uint32 frameSize = frame.size;
 
-	for (uint32 i = 0; i < _audioTracks.size(); i++) {
-		AudioInfo &audio = _audioTracks[i];
-
+	for (uint32 i = 0; i < _audioTrackCount; i++) {
 		uint32 audioPacketLength = _bink->readUint32LE();
 
 		frameSize -= 4;
@@ -186,19 +181,9 @@ void BinkDecoder::readNextPacket() {
 		if (audioPacketLength >= 4) {
 			// Get our track - audio index plus one as the first track is video
 			BinkAudioTrack *audioTrack = (BinkAudioTrack *)getTrack(i + 1);
-			uint32 audioPacketStart = _bink->pos();
-			uint32 audioPacketEnd   = _bink->pos() + audioPacketLength;
-
-			//                  Number of samples in bytes
-			audio.sampleCount = _bink->readUint32LE() / (2 * audio.channels);
+			uint32 audioPacketEnd = _bink->pos() + audioPacketLength;
 
-			audio.bits = new Common::BitStream32LELSB(new Common::SeekableSubReadStream(_bink,
-					audioPacketStart + 4, audioPacketEnd), DisposeAfterUse::YES);
-
-			audioTrack->decodePacket();
-
-			delete audio.bits;
-			audio.bits = 0;
+			audioTrack->decodePacket(*_bink, audioPacketLength);
 
 			_bink->seek(audioPacketEnd);
 
@@ -350,7 +335,7 @@ bool BinkDecoder::seekIntern(const Audio::Timestamp &time) {
 	findNextVideoTrack();
 
 	// Seek the audio tracks
-	for (uint32 i = 0; i < _audioTracks.size(); i++) {
+	for (uint32 i = 0; i < _audioTrackCount; i++) {
 		BinkAudioTrack *audioTrack = (BinkAudioTrack *)getTrack(i + 1);
 		audioTrack->seek(videoTrack->getFrameTime(keyFrame));
 	}
@@ -364,7 +349,7 @@ bool BinkDecoder::seekIntern(const Audio::Timestamp &time) {
 		decodeNextFrame();
 
 	// Skip decoded audio between the keyframe and the target frame
-	for (uint32 i = 0; i < _audioTracks.size(); i++) {
+	for (uint32 i = 0; i < _audioTrackCount; i++) {
 		BinkAudioTrack *audioTrack = (BinkAudioTrack *)getTrack(i + 1);
 		int rate = audioTrack->getRate();
 
@@ -1494,21 +1479,36 @@ void BinkDecoder::BinkVideoTrack::IDCTPut(DecodeContext &ctx, int32 *block) {
 	}
 }
 
-BinkDecoder::BinkAudioTrack::BinkAudioTrack(BinkDecoder::AudioInfo &audio, Audio::Mixer::SoundType soundType) :
-		AudioTrack(soundType),
-		_audioInfo(&audio) {
+BinkDecoder::BinkAudioTrack::BinkAudioTrack(uint16 sampleRate, uint16 flags, Audio::Mixer::SoundType soundType) :
+		AudioTrack(soundType) {
+	_audioInfo = new AudioInfo();
+	_audioInfo->sampleRate = sampleRate;
+	_audioInfo->flags      = flags;
+
+	initAudioTrack(*_audioInfo);
+
 	_audioStream = Audio::makeQueuingAudioStream(_audioInfo->outSampleRate, _audioInfo->outChannels == 2);
 }
 
 BinkDecoder::BinkAudioTrack::~BinkAudioTrack() {
 	delete _audioStream;
+	delete _audioInfo;
 }
 
 Audio::AudioStream *BinkDecoder::BinkAudioTrack::getAudioStream() const {
 	return _audioStream;
 }
 
-void BinkDecoder::BinkAudioTrack::decodePacket() {
+void BinkDecoder::BinkAudioTrack::decodePacket(Common::SeekableReadStream &stream, uint32 size) {
+	uint32 audioPacketStart = stream.pos();
+	uint32 audioPacketEnd   = stream.pos() + size;
+
+	//                         Number of samples in bytes
+	_audioInfo->sampleCount = stream.readUint32LE() / (2 * _audioInfo->channels);
+
+	_audioInfo->bits = new Common::BitStream32LELSB(new Common::SeekableSubReadStream(&stream,
+			audioPacketStart + 4, audioPacketEnd), DisposeAfterUse::YES);
+
 	int outSize = _audioInfo->frameLen * _audioInfo->channels;
 
 	while (_audioInfo->bits->pos() < _audioInfo->bits->size()) {
@@ -1530,6 +1530,9 @@ void BinkDecoder::BinkAudioTrack::decodePacket() {
 		if (_audioInfo->bits->pos() & 0x1F) // next data block starts at a 32-byte boundary
 			_audioInfo->bits->skip(32 - (_audioInfo->bits->pos() & 0x1F));
 	}
+
+	delete _audioInfo->bits;
+	_audioInfo->bits = 0;
 }
 
 void BinkDecoder::BinkAudioTrack::audioBlock(int16 *out) {
@@ -1744,8 +1747,6 @@ void BinkDecoder::initAudioTrack(AudioInfo &audio) {
 		audio.rdft = new Math::RDFT(frameLenBits, Math::RDFT::DFT_C2R);
 	else if (audio.codec == kAudioCodecDCT)
 		audio.dct  = new Math::DCT(frameLenBits, Math::DCT::DCT_III);
-
-	addTrack(new BinkAudioTrack(audio, getSoundType()));
 }
 
 } // End of namespace Video
diff --git a/video/bink_decoder.h b/video/bink_decoder.h
index c2aae3fdc90..a3c545ed4e3 100644
--- a/video/bink_decoder.h
+++ b/video/bink_decoder.h
@@ -343,13 +343,16 @@ private:
 		void IDCTAdd(DecodeContext &ctx, int32 *block);
 	};
 
+public:
+	/** An audio track, which Bink 2 videos have as well. */
 	class BinkAudioTrack : public AudioTrack {
 	public:
-		BinkAudioTrack(AudioInfo &audio, Audio::Mixer::SoundType soundType);
+		/** The rate and the flags of the track, as the header of the video has them. */
+		BinkAudioTrack(uint16 sampleRate, uint16 flags, Audio::Mixer::SoundType soundType);
 		~BinkAudioTrack();
 
-		/** Decode an audio packet. */
-		void decodePacket();
+		/** Decode the audio packet of size bytes at the position of the stream. */
+		void decodePacket(Common::SeekableReadStream &stream, uint32 size);
 
 		bool seek(const Audio::Timestamp &time) override;
 		bool isSeekable() const override { return true; }
@@ -377,12 +380,13 @@ private:
 		static void floatToInt16Interleave(int16 *dst, const float **src, uint32 length, uint8 channels);
 	};
 
+private:
 	Common::SeekableReadStream *_bink;
 
-	Common::Array<AudioInfo> _audioTracks; ///< All audio tracks.
+	uint32 _audioTrackCount;               ///< The number of audio tracks.
 	Common::Array<VideoFrame> _frames;      ///< All video frames.
 
-	void initAudioTrack(AudioInfo &audio);
+	static void initAudioTrack(AudioInfo &audio);
 };
 
 } // End of namespace Video


Commit: 75694532f33485dd657c6a82a9c464ed804bb3a9
    https://github.com/scummvm/scummvm/commit/75694532f33485dd657c6a82a9c464ed804bb3a9
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:56:54+02:00

Commit Message:
VIDEO: Add a decoder for Bink 2 (revision 'f') videos

This plays Bink 2 videos of revision 'f' (KB2f). It is based on the
Bink 2 decoder written for FFmpeg by Konstantin Shishkov and Paul B
Mahol, which was never merged there.

What that decoder lacked was taken from RAD's own decoder: the
deblocking, which blurs the blocks that only have a DC into their
neighbors and smooths the edges between blocks, and the exact rounding
of the IDCT and of the motion compensation. The frames it decodes are
the same as those of RAD's decoder, pixel for pixel.

The audio tracks are decoded like those of Bink 1 videos.

Changed paths:
  A video/bink2_decoder.cpp
  A video/bink2_decoder.h
    video/module.mk


diff --git a/video/bink2_decoder.cpp b/video/bink2_decoder.cpp
new file mode 100644
index 00000000000..98175e866dc
--- /dev/null
+++ b/video/bink2_decoder.cpp
@@ -0,0 +1,1492 @@
+/* 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/>.
+ *
+ */
+
+// Based on the Bink 2 decoder written for FFmpeg by
+// Konstantin Shishkov and Paul B Mahol, which was never merged there,
+// with what it lacked taken from RAD's own decoder.
+
+#include "common/scummsys.h"
+
+#ifdef USE_BINK
+
+#include "common/compression/huffman.h"
+#include "common/endian.h"
+#include "common/stream.h"
+#include "common/textconsole.h"
+#include "common/util.h"
+
+#include "graphics/surface.h"
+#include "graphics/yuv_to_rgb.h"
+
+#include "image/codecs/codec.h"
+
+#include "video/bink2_decoder.h"
+
+namespace Video {
+
+static constexpr uint32 kKB2fID = MKTAG('K', 'B', '2', 'f');
+
+static constexpr uint32 kVideoFlagAlpha = 0x00100000;
+
+// Frame flags: block flags for deblocking follow the slice offsets. The ones
+// for rows and columns of blocks, when left out, also leave their edges
+// unfiltered. The low byte is the strength of the blur.
+static constexpr uint32 kFrameFlagBlockFlags = 0x10000;
+static constexpr uint32 kFrameFlagNoRowFlags = 0x8000;
+static constexpr uint32 kFrameFlagNoColFlags = 0x4000;
+
+// Border around the luma planes; half of it around the chroma ones
+static constexpr int kBorder = 32;
+
+// The original rounds with a hair under a half
+static constexpr float kAlmostHalf = 0.49999991f;
+
+static constexpr uint32 kQuantCodes[16] = {
+	0x01, 0x02, 0x04, 0x08, 0x10, 0x30, 0x50, 0x70,
+	0x00, 0x20, 0x40, 0x60, 0x80, 0xA0, 0xC0, 0xE0
+};
+
+static constexpr uint8 kQuantLengths[16] = {
+	1, 2, 3, 4, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8
+};
+
+static constexpr uint32 kACValueCodes[2][13] = {
+	{ 0x04, 0x01, 0x02, 0x00, 0x08, 0x18, 0xF8, 0x178, 0x138, 0x38, 0x1B8, 0x78, 0xB8 },
+	{ 0x0A, 0x01, 0x04, 0x08, 0x06, 0x00, 0x02, 0x1A, 0x2A, 0x16A, 0x1EA, 0x6A, 0xEA }
+};
+
+static constexpr uint8 kACValueLengths[2][13] = {
+	{ 3, 1, 2, 4, 5, 6, 8, 9, 9, 9, 9, 9, 9 },
+	{ 6, 1, 3, 4, 3, 4, 4, 5, 7, 9, 9, 9, 9 }
+};
+
+static constexpr uint32 kACSkipCodes[2][14] = {
+	{ 0x00, 0x01, 0x0D, 0x15, 0x45, 0x85, 0xA5, 0x165, 0x65, 0x1E5, 0xE5, 0x25, 0x03, 0x05 },
+	{ 0x00, 0x01, 0x03, 0x07, 0x1F, 0x1B, 0x0F, 0x2F, 0x5B, 0xDB, 0x1DB, 0x3B, 0x05, 0x0B }
+};
+
+static constexpr uint8 kACSkipLengths[2][14] = {
+	{ 1, 3, 4, 5, 7, 8, 8, 9, 9, 9, 9, 8, 2, 8 },
+	{ 1, 3, 4, 4, 5, 7, 6, 6, 8, 9, 9, 6, 3, 5 }
+};
+
+// How many coefficients a skip symbol jumps over (11: read 6 bits; 62: to the end)
+static constexpr byte kACSkips[14] = {
+	0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 62, 0
+};
+
+// How many coefficients follow a skip symbol before the next one
+static constexpr byte kACNextSkips[14] = {
+	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7
+};
+
+static constexpr float kDCQuant[16] = {
+	4, 4, 4, 4, 4, 6, 7, 8, 10, 12, 16, 24, 32, 48, 64, 128
+};
+
+static constexpr byte kDCQuantBits[16] = {
+	1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 6
+};
+
+static constexpr float kACQuant[16] = {
+	1.0f, 2.0f, 2.5f, 3.0f, 3.5f, 4.0f, 6.0f, 7.0f, 8.0f, 12.0f, 16.0f, 24.0f, 32.0f, 48.0f, 64.0f, 128.0f
+};
+
+static constexpr float kLumaIntraQmat[64] = {
+	0.125f,    0.190718f, 0.16332f,  0.235175f, 0.3f,      0.392847f, 0.345013f, 0.210373f,
+	0.208056f, 0.288582f, 0.317145f, 0.387359f, 0.450788f, 0.790098f, 0.562995f, 0.263095f,
+	0.228649f, 0.294491f, 0.341421f, 0.460907f, 0.653281f, 0.731424f, 0.60988f,  0.252336f,
+	0.205778f, 0.346585f, 0.422498f, 0.501223f, 0.749621f, 1.004719f, 0.636379f, 0.251428f,
+	0.225f,    0.381436f, 0.604285f, 0.823113f, 0.85f,     1.070509f, 0.69679f,  0.265553f,
+	0.235708f, 0.476783f, 0.70576f,  0.739104f, 0.795516f, 0.802512f, 0.600616f, 0.249289f,
+	0.331483f, 0.600528f, 0.689429f, 0.692062f, 0.69679f,  0.643138f, 0.43934f,  0.188511f,
+	0.248309f, 0.440086f, 0.42807f,  0.397419f, 0.386259f, 0.270966f, 0.192244f, 0.094199f
+};
+
+static constexpr float kLumaInterQmat[64] = {
+	0.125f,    0.17338f,  0.16332f,  0.146984f, 0.128475f, 0.106393f, 0.077046f, 0.043109f,
+	0.17338f,  0.240485f, 0.226532f, 0.203873f, 0.1782f,   0.147571f, 0.109474f, 0.062454f,
+	0.16332f,  0.226532f, 0.219321f, 0.202722f, 0.181465f, 0.149711f, 0.112943f, 0.062584f,
+	0.146984f, 0.203873f, 0.202722f, 0.201647f, 0.183731f, 0.153976f, 0.11711f,  0.065335f,
+	0.128475f, 0.1782f,   0.181465f, 0.183731f, 0.177088f, 0.155499f, 0.120267f, 0.068016f,
+	0.106393f, 0.147571f, 0.149711f, 0.153976f, 0.155499f, 0.145756f, 0.116636f, 0.068495f,
+	0.077046f, 0.109474f, 0.112943f, 0.11711f,  0.120267f, 0.116636f, 0.098646f, 0.060141f,
+	0.043109f, 0.062454f, 0.062584f, 0.065335f, 0.068016f, 0.068495f, 0.060141f, 0.038853f
+};
+
+static constexpr float kChromaQmat[64] = {
+	0.125f,      0.17338f,    0.217761f,   0.383793f,   0.6875f,     0.54016501f, 0.37207201f, 0.18968099f,
+	0.17338f,    0.28056601f, 0.32721299f, 0.74753499f, 0.95358998f, 0.74923098f, 0.51607901f, 0.26309499f,
+	0.217761f,   0.32721299f, 0.66387498f, 1.056244f,   0.89826202f, 0.70576f,    0.48613599f, 0.24783f,
+	0.383793f,   0.74753499f, 1.056244f,   0.95059502f, 0.80841398f, 0.635167f,   0.437511f,   0.223041f,
+	0.6875f,     0.95358998f, 0.89826202f, 0.80841398f, 0.6875f,     0.54016501f, 0.37207201f, 0.18968099f,
+	0.54016501f, 0.74923098f, 0.70576f,    0.635167f,   0.54016501f, 0.42440501f, 0.292335f,   0.149031f,
+	0.37207201f, 0.51607901f, 0.48613599f, 0.437511f,   0.37207201f, 0.292335f,   0.201364f,   0.102655f,
+	0.18968099f, 0.26309499f, 0.24783f,    0.223041f,   0.18968099f, 0.149031f,   0.102655f,   0.052333001f
+};
+
+static constexpr byte kLumaScan[64] = {
+	 0,  2,  1,  8,  9, 17, 10, 16,
+	24,  3, 18, 25, 32, 11, 33, 26,
+	 4, 40, 19, 12, 27, 41, 34,  5,
+	20, 48,  6, 28, 15, 42, 23, 35,
+	21, 13, 14,  7, 31, 43, 49, 36,
+	22, 56, 39, 50, 30, 44, 29, 51,
+	57, 47, 58, 59, 63, 61, 55, 38,
+	52, 62, 45, 37, 60, 46, 54, 53
+};
+
+static constexpr byte kChromaScan[64] = {
+	 0,  1,  8,  2,  9, 16, 10, 17,
+	 3, 24, 11, 18, 25, 13, 14,  4,
+	15,  5,  6,  7, 12, 19, 20, 21,
+	22, 23, 26, 27, 28, 29, 30, 31,
+	32, 33, 34, 35, 36, 37, 38, 39,
+	40, 41, 42, 43, 44, 45, 46, 47,
+	48, 49, 50, 51, 52, 53, 54, 55,
+	56, 57, 58, 59, 60, 61, 62, 63
+};
+
+// The 8x8 blocks of a 32x32 luma macroblock in coding order, as x + 4 * y
+static constexpr byte kLumaBlockPos[16] = {
+	0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15
+};
+
+static inline byte clipPixel(int value) {
+	return (byte)CLIP(value, 0, 255);
+}
+
+// The kind of an intra block, by its number of AC coefficients, and its DC
+static uint16 makeBlockWord(int coefCount, float dc) {
+	const int kind = coefCount == 0 ? 7 : (coefCount < 4 ? 6 : (coefCount < 8 ? 5 : 4));
+	return (uint16)((kind << 13) | ((int)(dc + kAlmostHalf) & 0x1FFF));
+}
+
+static inline int countBits4(uint32 value) {
+	return (value & 1) + ((value >> 1) & 1) + ((value >> 2) & 1) + ((value >> 3) & 1);
+}
+
+static inline int median(int a, int b, int c) {
+	return MAX(MIN(a, b), MIN(MAX(a, b), c));
+}
+
+// Predicts from three neighbors, as a + b - c bounded by them
+static inline float predictMedian(float a, float b, float c) {
+	return MIN(MAX(c + b - a, MIN(a, MIN(b, c))), MAX(a, MAX(b, c)));
+}
+
+// Predicts from two neighbors
+static inline float predictMedian2(float a, float b) {
+	return MIN(MAX(a, b), MAX(MIN(a, b), 2 * a - b));
+}
+
+static void idct1D(float *block, int step) {
+	const float t00 =  block[2 * step] + block[6 * step];
+	const float t01 = (block[2 * step] - block[6 * step]) * 1.4142135f - t00;
+	const float t02 =  block[0 * step] + block[4 * step];
+	const float t03 =  block[0 * step] - block[4 * step];
+	const float t04 =  block[3 * step] + block[5 * step];
+	const float t05 =  block[3 * step] - block[5 * step];
+	const float t06 =  block[1 * step] + block[7 * step];
+	const float t07 =  block[1 * step] - block[7 * step];
+	const float t08 = t02 + t00;
+	const float t09 = t02 - t00;
+	const float t10 = t03 + t01;
+	const float t11 = t03 - t01;
+	const float t12 = t06 + t04;
+	const float t13 = (t06 - t04) * 1.4142135f;
+	const float t14 = (t07 - t05) * 1.847759f;
+	const float t15 = t05 * 2.613126f + t14 - t12;
+	const float t16 = t13 - t15;
+	const float t17 = t07 * 1.0823922f - t14 + t16;
+
+	block[0 * step] = t08 + t12;
+	block[1 * step] = t10 + t15;
+	block[2 * step] = t11 + t16;
+	block[3 * step] = t09 - t17;
+	block[4 * step] = t09 + t17;
+	block[5 * step] = t11 - t16;
+	block[6 * step] = t10 - t15;
+	block[7 * step] = t08 - t12;
+}
+
+// Puts the block in place, or adds it to what is there. The DC comes with a
+// bias of 512.5, rounding included, as in the original.
+static void idct(byte *dst, int pitch, float *block, float dc, bool isAdded) {
+	block[0] = (dc + 4100.0f) * 0.125f;
+
+	for (int i = 0; i < 8; i++)
+		idct1D(block + i, 8);
+
+	for (int i = 0; i < 8; i++) {
+		idct1D(block, 1);
+
+		for (int j = 0; j < 8; j++) {
+			const int value = (int)block[j] - 512;
+			dst[j] = clipPixel(isAdded ? dst[j] + value : value);
+		}
+
+		block += 8;
+		dst += pitch;
+	}
+}
+
+// Adds a residue that has only a DC
+static void addFlat(byte *dst, int pitch, float dc) {
+	const int value = (int)(dc * 0.125f + kAlmostHalf);
+	for (int j = 0; j < 8; j++, dst += pitch)
+		for (int i = 0; i < 8; i++)
+			dst[i] = clipPixel(dst[i] + value);
+}
+
+static void copyBlock(byte *dst, const byte *src, int pitch, int width, int height) {
+	for (int i = 0; i < height; i++) {
+		memcpy(dst, src, width);
+		dst += pitch;
+		src += pitch;
+	}
+}
+
+// Half pixel luma filter, over the pixels step apart around src[0] and src[step]
+template<typename T>
+static inline int lumaFilter(const T *src, int step) {
+	return ((((src[0] + src[step]) * 19) >> 1) - (src[-step] + src[2 * step]) * 2 + ((src[-2 * step] + src[3 * step]) >> 1) + 8) >> 4;
+}
+
+// A 16x16 luma block at a half pixel position: mode bit 0 for x, bit 1 for y
+static void lumaBlock(byte *dst, const byte *src, int pitch, int mode) {
+	switch (mode) {
+	case 0:
+		copyBlock(dst, src, pitch, 16, 16);
+		break;
+	case 1:
+		for (int j = 0; j < 16; j++) {
+			for (int i = 0; i < 16; i++)
+				dst[i] = clipPixel(lumaFilter(src + i, 1));
+			dst += pitch;
+			src += pitch;
+		}
+		break;
+	case 2:
+		for (int j = 0; j < 16; j++) {
+			for (int i = 0; i < 16; i++)
+				dst[i] = clipPixel(lumaFilter(src + i, pitch));
+			dst += pitch;
+			src += pitch;
+		}
+		break;
+	default: {
+		// The first pass is not clipped
+		int16 temp[21 * 16];
+
+		src -= 2 * pitch;
+		for (int j = 0; j < 21; j++) {
+			for (int i = 0; i < 16; i++)
+				temp[j * 16 + i] = lumaFilter(src + i, 1);
+			src += pitch;
+		}
+
+		for (int j = 0; j < 16; j++) {
+			for (int i = 0; i < 16; i++)
+				dst[i] = clipPixel(lumaFilter(temp + (j + 2) * 16 + i, 16));
+			dst += pitch;
+		}
+		break;
+	}
+	}
+}
+
+// Quarter pixel chroma filter, between a and b
+static inline int chromaFilter(int a, int b, int fraction) {
+	switch (fraction) {
+	case 1:
+		return (6 * a + 2 * b + 4) >> 3;
+	case 2:
+		return (a + b + 1) >> 1;
+	default:
+		return (2 * a + 6 * b + 4) >> 3;
+	}
+}
+
+// An 8x8 chroma block at a quarter pixel position: mode bits 0-1 for x, 2-3 for y
+static void chromaBlock(byte *dst, const byte *src, int pitch, int mode) {
+	const int fractionX = mode & 3;
+	const int fractionY = mode >> 2;
+
+	if (!fractionX && !fractionY) {
+		copyBlock(dst, src, pitch, 8, 8);
+	} else if (!fractionY) {
+		for (int j = 0; j < 8; j++) {
+			for (int i = 0; i < 8; i++)
+				dst[i] = clipPixel(chromaFilter(src[i], src[i + 1], fractionX));
+			dst += pitch;
+			src += pitch;
+		}
+	} else if (!fractionX) {
+		for (int j = 0; j < 8; j++) {
+			for (int i = 0; i < 8; i++)
+				dst[i] = clipPixel(chromaFilter(src[i], src[i + pitch], fractionY));
+			dst += pitch;
+			src += pitch;
+		}
+	} else {
+		// Both ways at once, rounded once
+		const int x1 = 2 * fractionX;
+		const int x0 = 8 - x1;
+		const int y1 = 2 * fractionY;
+		const int y0 = 8 - y1;
+
+		for (int j = 0; j < 8; j++) {
+			for (int i = 0; i < 8; i++) {
+				const int top = x0 * src[i] + x1 * src[i + 1];
+				const int bottom = x0 * src[i + pitch] + x1 * src[i + pitch + 1];
+				dst[i] = clipPixel((y0 * top + y1 * bottom + 32) >> 6);
+			}
+			dst += pitch;
+			src += pitch;
+		}
+	}
+}
+
+// Eight times the average of an 8x8 block, as the coder takes it
+static int averageBlock(const byte *src, int pitch) {
+	int sum = 0;
+
+	for (int i = 0; i < 8; i++) {
+		const int a = (src[i + 0 * pitch] + src[i + 1 * pitch] + 1) >> 1;
+		const int b = (src[i + 2 * pitch] + src[i + 3 * pitch] + 1) >> 1;
+		const int c = (src[i + 4 * pitch] + src[i + 5 * pitch] + 1) >> 1;
+		const int d = (src[i + 6 * pitch] + src[i + 7 * pitch] + 1) >> 1;
+		const int e = (a + b + 1) >> 1;
+		const int f = (c + d + 1) >> 1;
+		sum += (e + f + 1) >> 1;
+	}
+
+	return sum;
+}
+
+// Masks for the edge filter, by code: bit 0 changes p0, bit 1 p1 and p0,
+// bit 2 q0, bit 3 q0 and q1. Code 15 (two blocks with only a DC, which the
+// blur already smoothed) changes nothing.
+static void filterEdge(byte *p, int step, int code) {
+	if (code == 15 || code == 0)
+		return;
+
+	const int d = p[0] - p[-step];
+	const int outer = (2 * d + 8) >> 4;
+	const int inner = (4 * d + 8) >> 4;
+
+	if (code & 2)
+		p[-2 * step] = clipPixel(p[-2 * step] + outer);
+	if (code & 3)
+		p[-step] = clipPixel(p[-step] + inner);
+	if (code & 12)
+		p[0] = clipPixel(p[0] - inner);
+	if (code & 8)
+		p[step] = clipPixel(p[step] - outer);
+}
+
+static inline int16 asInt16(int value) {
+	return (int16)(uint16)value;
+}
+
+// The weights of the DCs around a block drawn from its DC alone, over its
+// pixels: of the top left one, of the top one and of its own. The other
+// corners and sides are mirrored.
+static constexpr float kBlurCorner[8][8] = {
+	{ 0.024111325f, 0.017566822f, 0.011538992f, 0.006372279f, 0.0024111324f, 0.0f, 0.0f, 0.0f },
+	{ 0.017566822f, 0.012675668f, 0.008197851f, 0.004408928f, 0.0015844585f, 0.0f, 0.0f, 0.0f },
+	{ 0.011538992f, 0.008197851f, 0.0051667127f, 0.0026522458f, 0.0008611188f, 0.0f, 0.0f, 0.0f },
+	{ 0.006372279f, 0.004408928f, 0.0026522458f, 0.0012400111f, 0.00031000277f, 0.0f, 0.0f, 0.0f },
+	{ 0.0024111324f, 0.0015844585f, 0.0008611188f, 0.00031000277f, 0.0f, 0.0f, 0.0f, 0.0f },
+	{ 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f },
+	{ 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f },
+	{ 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }
+};
+
+static constexpr float kBlurEdge[8][8] = {
+	{ 0.030828051f, 0.037372556f, 0.043400384f, 0.046155967f, 0.046155967f, 0.043400384f, 0.037372556f, 0.030828051f },
+	{ 0.022595756f, 0.027486911f, 0.031964727f, 0.034169193f, 0.034169193f, 0.031964727f, 0.027486911f, 0.022595756f },
+	{ 0.014983467f, 0.018324608f, 0.021355746f, 0.023009093f, 0.023009093f, 0.021355746f, 0.018324608f, 0.014983467f },
+	{ 0.008404519f, 0.01036787f, 0.012124552f, 0.013226784f, 0.013226784f, 0.012124552f, 0.01036787f, 0.008404519f },
+	{ 0.0032722512f, 0.0040989253f, 0.004822265f, 0.005373381f, 0.005373381f, 0.004822265f, 0.0040989253f, 0.0032722512f },
+	{ 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f },
+	{ 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f },
+	{ 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }
+};
+
+static constexpr float kBlurCenter[8][8] = {
+	{ 0.039267015f, 0.04749931f, 0.055111602f, 0.058418296f, 0.058418296f, 0.055111602f, 0.04749931f, 0.039267015f },
+	{ 0.04749931f, 0.057384953f, 0.06654726f, 0.07040507f, 0.07040507f, 0.06654726f, 0.057384953f, 0.04749931f },
+	{ 0.055111602f, 0.06654726f, 0.07715624f, 0.08156517f, 0.08156517f, 0.07715624f, 0.06654726f, 0.055111602f },
+	{ 0.058418296f, 0.07040507f, 0.08156517f, 0.0859741f, 0.0859741f, 0.08156517f, 0.07040507f, 0.058418296f },
+	{ 0.058418296f, 0.07040507f, 0.08156517f, 0.0859741f, 0.0859741f, 0.08156517f, 0.07040507f, 0.058418296f },
+	{ 0.055111602f, 0.06654726f, 0.07715624f, 0.08156517f, 0.08156517f, 0.07715624f, 0.06654726f, 0.055111602f },
+	{ 0.04749931f, 0.057384953f, 0.06654726f, 0.07040507f, 0.07040507f, 0.06654726f, 0.057384953f, 0.04749931f },
+	{ 0.039267015f, 0.04749931f, 0.055111602f, 0.058418296f, 0.058418296f, 0.055111602f, 0.04749931f, 0.039267015f }
+};
+
+
+Bink2Decoder::Bink2Decoder() : _stream(nullptr), _audioTrackCount(0) {
+}
+
+Bink2Decoder::~Bink2Decoder() {
+	close();
+}
+
+bool Bink2Decoder::isBink2(Common::SeekableReadStream &stream) {
+	const int64 pos = stream.pos();
+	const uint32 id = stream.readUint32BE();
+	stream.seek(pos);
+	return id == kKB2fID;
+}
+
+// The container is the one of Bink videos
+bool Bink2Decoder::loadStream(Common::SeekableReadStream *stream) {
+	close();
+
+	if (stream->readUint32BE() != kKB2fID) {
+		delete stream;
+		return false;
+	}
+
+	const uint32 fileSize   = stream->readUint32LE() + 8;
+	const uint32 frameCount = stream->readUint32LE();
+	const uint32 largestFrameSize = stream->readUint32LE();
+	stream->skip(4);
+	const uint32 width  = stream->readUint32LE();
+	const uint32 height = stream->readUint32LE();
+	const uint32 frameRateNum = stream->readUint32LE();
+	const uint32 frameRateDen = stream->readUint32LE();
+	const uint32 videoFlags = stream->readUint32LE();
+	_audioTrackCount = stream->readUint32LE();
+
+	if (frameCount == 0 || largestFrameSize > fileSize || frameRateNum == 0 || frameRateDen == 0) {
+		warning("Bink2Decoder: Bad header");
+		delete stream;
+		return false;
+	}
+
+	addTrack(new Bink2VideoTrack(width, height, videoFlags, frameCount, Common::Rational(frameRateNum, frameRateDen)));
+
+	// The maximum packet sizes, then the rate and the flags of each track,
+	// then their IDs
+	stream->skip(_audioTrackCount * 4);
+	for (uint32 i = 0; i < _audioTrackCount; i++) {
+		const uint16 sampleRate = stream->readUint16LE();
+		const uint16 flags = stream->readUint16LE();
+		addTrack(new BinkDecoder::BinkAudioTrack(sampleRate, flags, getSoundType()));
+	}
+	stream->skip(_audioTrackCount * 4);
+
+	_frames.resize(frameCount);
+	for (uint32 i = 0; i < frameCount; i++) {
+		const uint32 offset = stream->readUint32LE();
+		_frames[i].offset = offset & ~1;
+		_frames[i].isKeyFrame = (offset & 1) != 0;
+		if (i != 0)
+			_frames[i - 1].size = _frames[i].offset - _frames[i - 1].offset;
+	}
+	_frames[frameCount - 1].size = stream->size() - _frames[frameCount - 1].offset;
+
+	_stream = stream;
+	return true;
+}
+
+void Bink2Decoder::close() {
+	VideoDecoder::close();
+
+	delete _stream;
+	_stream = nullptr;
+	_frames.clear();
+	_audioTrackCount = 0;
+}
+
+void Bink2Decoder::readNextPacket() {
+	Bink2VideoTrack *track = (Bink2VideoTrack *)getTrack(0);
+	if (track->endOfTrack())
+		return;
+
+	const Frame &frame = _frames[track->getCurFrame() + 1];
+	if (!_stream->seek(frame.offset))
+		error("Bink2Decoder: Bad seek");
+
+	// The audio packets come first
+	uint32 size = frame.size;
+	for (uint32 i = 0; i < _audioTrackCount; i++) {
+		const uint32 audioSize = _stream->readUint32LE();
+		if (audioSize + 4 > size)
+			error("Bink2Decoder: Audio packet too big for the frame");
+
+		const int64 audioEnd = _stream->pos() + audioSize;
+		if (audioSize >= 4)
+			((BinkDecoder::BinkAudioTrack *)getTrack(i + 1))->decodePacket(*_stream, audioSize);
+		_stream->seek(audioEnd);
+		size -= audioSize + 4;
+	}
+
+	track->decodePacket(*_stream, size, frame.isKeyFrame);
+}
+
+uint32 Bink2Decoder::findKeyFrame(uint32 frame) const {
+	for (int i = frame; i >= 0; i--) {
+		if (_frames[i].isKeyFrame)
+			return i;
+	}
+
+	return frame;
+}
+
+// From the key frame before, decoding the frames in between
+bool Bink2Decoder::seekIntern(const Audio::Timestamp &time) {
+	Bink2VideoTrack *track = (Bink2VideoTrack *)getTrack(0);
+	const uint32 frame = track->getFrameAtTime(time);
+	const uint32 keyFrame = findKeyFrame(frame);
+
+	track->setCurFrame((int)keyFrame - 1);
+	for (uint32 i = 0; i < _audioTrackCount; i++)
+		((BinkDecoder::BinkAudioTrack *)getTrack(i + 1))->seek(track->getFrameTime(keyFrame));
+
+	if (frame == keyFrame)
+		return true;
+
+	while (track->getCurFrame() < (int)frame - 1)
+		readNextPacket();
+
+	// The audio of the frames in between isn't played
+	for (uint32 i = 0; i < _audioTrackCount; i++) {
+		BinkDecoder::BinkAudioTrack *audioTrack = (BinkDecoder::BinkAudioTrack *)getTrack(i + 1);
+		const int rate = audioTrack->getRate();
+		audioTrack->skipSamples(track->getFrameTime(frame - 1).convertToFramerate(rate) -
+			track->getFrameTime(keyFrame).convertToFramerate(rate));
+	}
+
+	return true;
+}
+
+VideoDecoder::AudioTrack *Bink2Decoder::getAudioTrack(int index) {
+	// Counted from the first audio track, which follows the video one
+	Track *track = getTrack(index + 1);
+	if (!track || track->getTrackType() != Track::kTrackTypeAudio)
+		return nullptr;
+
+	return (AudioTrack *)track;
+}
+
+Bink2Decoder::Bink2VideoTrack::Bink2VideoTrack(uint32 width, uint32 height, uint32 flags, uint32 frameCount, const Common::Rational &frameRate) :
+		_width(width), _height(height), _frameCount(frameCount), _curFrameNumber(-1), _frameRate(frameRate),
+		_surface(nullptr), _curFrame(0), _comp(0), _mbPos(0) {
+	_pixelFormat = Image::Codec::getDefaultYUVFormat();
+
+	_alignedWidth  = (width  + 31) & ~31;
+	_alignedHeight = (height + 31) & ~31;
+	_hasAlpha = (flags & kVideoFlagAlpha) != 0;
+	_numPlanes = _hasAlpha ? 4 : 3;
+
+	for (int plane = 0; plane < 4; plane++) {
+		const bool isChroma = plane == 1 || plane == 2;
+		const int border = isChroma ? kBorder / 2 : kBorder;
+		const int width2  = (isChroma ? _alignedWidth  / 2 : _alignedWidth)  + 2 * border;
+		const int height2 = (isChroma ? _alignedHeight / 2 : _alignedHeight) + 2 * border;
+
+		_pitches[plane] = width2;
+		_planeSizes[plane] = width2 * height2;
+
+		for (int frame = 0; frame < 2; frame++) {
+			if (plane < _numPlanes) {
+				_buffers[frame][plane] = new byte[_planeSizes[plane]];
+				_planes[frame][plane] = _buffers[frame][plane] + border * width2 + border;
+			} else {
+				_buffers[frame][plane] = nullptr;
+				_planes[frame][plane] = nullptr;
+			}
+		}
+	}
+
+	// One more column than there are macroblocks: the first macroblock of a
+	// row looks at the one to its upper right, which a narrow video lacks
+	const uint32 columns = _alignedWidth / 32 + 1;
+	for (int i = 0; i < 2; i++) {
+		_dcRows[i].resize(columns);
+		memset(_dcRows[i].data(), 0, columns * sizeof(DCPredict));
+		_mvRows[i].resize(columns);
+		memset(_mvRows[i].data(), 0, columns * sizeof(MotionVectors));
+	}
+
+	for (int plane = 0; plane < 4; plane++) {
+		const int size = (plane == 1 || plane == 2) ? 16 : 8;
+		_blockColumns[plane] = _alignedWidth / size;
+		_blockWords[plane].resize(_blockColumns[plane] * (_alignedHeight / size));
+	}
+	_blockVectors.resize((_alignedWidth / 16) * (_alignedHeight / 16) * 2);
+	_frameFlags = 0;
+	_mbX = _mbY = 0;
+
+	_currentDC = _dcRows[0].data();
+	_prevDC = _dcRows[1].data();
+	_currentMV = _mvRows[0].data();
+	_prevMV = _mvRows[1].data();
+
+	_quantHuffman = new Huffman(0, 16, kQuantCodes, kQuantLengths);
+	for (int i = 0; i < 2; i++) {
+		_acValueHuffman[i] = new Huffman(0, 13, kACValueCodes[i], kACValueLengths[i]);
+		_acSkipHuffman[i] = new Huffman(0, 14, kACSkipCodes[i], kACSkipLengths[i]);
+	}
+
+	memset(_block, 0, sizeof(_block));
+
+	reset();
+}
+
+Bink2Decoder::Bink2VideoTrack::~Bink2VideoTrack() {
+	if (_surface) {
+		_surface->free();
+		delete _surface;
+	}
+
+	for (int frame = 0; frame < 2; frame++)
+		for (int plane = 0; plane < 4; plane++)
+			delete[] _buffers[frame][plane];
+
+	delete _quantHuffman;
+	for (int i = 0; i < 2; i++) {
+		delete _acValueHuffman[i];
+		delete _acSkipHuffman[i];
+	}
+}
+
+bool Bink2Decoder::Bink2VideoTrack::setOutputPixelFormat(const Graphics::PixelFormat &format) {
+	if (format.bytesPerPixel != 2 && format.bytesPerPixel != 4)
+		return false;
+
+	_pixelFormat = format;
+	return true;
+}
+
+bool Bink2Decoder::Bink2VideoTrack::rewind() {
+	if (!VideoTrack::rewind())
+		return false;
+
+	_curFrameNumber = -1;
+	reset();
+	return true;
+}
+
+void Bink2Decoder::Bink2VideoTrack::decodePacket(Common::SeekableReadStream &stream, uint32 size, bool isKeyFrame) {
+	decodeFrame(stream, size, isKeyFrame);
+	convertFrame();
+	_curFrameNumber++;
+}
+
+void Bink2Decoder::Bink2VideoTrack::convertFrame() {
+	if (!_surface) {
+		// Even-sized, as the conversion goes two pixels at a time
+		_surface = new Graphics::Surface();
+		_surface->create((_width + 1) & ~1, (_height + 1) & ~1, _pixelFormat);
+		_surface->w = _width;
+		_surface->h = _height;
+	}
+
+	const int surfaceWidth = (_width + 1) & ~1;
+	const int surfaceHeight = (_height + 1) & ~1;
+	if (_hasAlpha) {
+		YUVToRGBMan.convert420Alpha(_surface, Graphics::YUVToRGBManager::kScaleITU, _planes[_curFrame][0], _planes[_curFrame][1], _planes[_curFrame][2], _planes[_curFrame][3],
+				surfaceWidth, surfaceHeight, _pitches[0], _pitches[1]);
+	} else {
+		YUVToRGBMan.convert420(_surface, Graphics::YUVToRGBManager::kScaleITU, _planes[_curFrame][0], _planes[_curFrame][1], _planes[_curFrame][2],
+				surfaceWidth, surfaceHeight, _pitches[0], _pitches[1]);
+	}
+}
+
+void Bink2Decoder::Bink2VideoTrack::reset() {
+	static constexpr byte kBlack[4] = { 0, 128, 128, 255 };
+
+	for (int frame = 0; frame < 2; frame++)
+		for (int plane = 0; plane < _numPlanes; plane++)
+			memset(_buffers[frame][plane], kBlack[plane], _planeSizes[plane]);
+}
+
+void Bink2Decoder::Bink2VideoTrack::decodeFrame(Common::SeekableReadStream &stream, uint32 size, bool isKeyFrame) {
+	// The bit streams read whole 32-bit words, so pad the data with zeros
+	_packet.resize(size + 8);
+	memset(_packet.data() + size, 0, 8);
+	if (stream.read(_packet.data(), size) != size) {
+		warning("Bink2Decoder: Could not read a frame of %u bytes", size);
+		return;
+	}
+
+	// The frame flags, then the offset of the second slice
+	if (size < 8) {
+		warning("Bink2Decoder: Frame of %u bytes is too small", size);
+		return;
+	}
+
+	const uint32 frameFlags  = READ_LE_UINT32(_packet.data());
+	const uint32 sliceOffset = READ_LE_UINT32(_packet.data() + 4);
+	if (sliceOffset < 8 || sliceOffset > size) {
+		warning("Bink2Decoder: Bad slice offset %u in a frame of %u bytes", sliceOffset, size);
+		return;
+	}
+
+	// Revision 'f' always has two slices
+	const int sliceHeight = (_height / 2 + 16) & ~31;
+
+	Common::BitStreamMemoryStream stream1(_packet.data() + 8, (sliceOffset - 8 + 3) & ~3);
+	BitStream bits1(stream1);
+
+	// Flags of the rows and columns of blocks, which are not needed
+	if (frameFlags & kFrameFlagBlockFlags) {
+		if (!(frameFlags & kFrameFlagNoRowFlags))
+			skipBlockFlags(bits1, (((_height + 15) & ~15) >> 3) - 1);
+		if (!(frameFlags & kFrameFlagNoColFlags))
+			skipBlockFlags(bits1, (((_width + 15) & ~15) >> 3) - 1);
+	}
+
+	decodeSlice(bits1, isKeyFrame, 0, sliceHeight);
+
+	Common::BitStreamMemoryStream stream2(_packet.data() + sliceOffset, (size - sliceOffset + 3) & ~3);
+	BitStream bits2(stream2);
+	decodeSlice(bits2, isKeyFrame, sliceHeight, _alignedHeight);
+
+	_frameFlags = frameFlags;
+	deblock();
+
+	_curFrame ^= 1;
+}
+
+// Reads past one flag per row or column of 8x8 blocks: stored, or in runs
+void Bink2Decoder::Bink2VideoTrack::skipBlockFlags(BitStream &bits, int size) {
+	if (!bits.getBit()) {
+		bits.skip(size);
+		return;
+	}
+
+	int flagsLeft = size;
+	int mode = 0;
+
+	while (flagsLeft > 0) {
+		if (!bits.getBit()) {
+			// The flag, unless it flips, and four more stored
+			if (mode != 3)
+				bits.getBit();
+			mode = 2;
+
+			if (flagsLeft < 5) {
+				bits.skip(flagsLeft - 1);
+				flagsLeft = 0;
+			} else {
+				bits.skip(4);
+				flagsLeft -= 5;
+			}
+		} else {
+			// A run of the flag, unless it flips
+			const int lengthBits = flagsLeft < 4 ? 2 : (flagsLeft < 16 ? 4 : 5);
+			int count = lengthBits + 1;
+
+			if (mode != 3) {
+				count++;
+				bits.getBit();
+			}
+
+			count = MIN(count, flagsLeft);
+			flagsLeft -= count;
+
+			if (flagsLeft > 0) {
+				const int extra = bits.getBits(lengthBits);
+				flagsLeft -= extra;
+				mode = extra == (1 << lengthBits) - 1 ? 1 : 3;
+			}
+		}
+	}
+}
+
+void Bink2Decoder::Bink2VideoTrack::decodeSlice(BitStream &bits, bool isKeyFrame, int start, int end) {
+	const int dstFrame = _curFrame ^ 1;
+
+	byte *dst[4];
+	const byte *src[4];
+	for (int plane = 0; plane < 4; plane++) {
+		const bool isChroma = plane == 1 || plane == 2;
+
+		if (plane < _numPlanes) {
+			dst[plane] = _planes[dstFrame][plane] + (isChroma ? start / 2 : start) * _pitches[plane];
+			src[plane] = _planes[_curFrame][plane];
+		} else {
+			dst[plane] = nullptr;
+			src[plane] = nullptr;
+		}
+	}
+
+	memset(_prevMV, 0, _mvRows[0].size() * sizeof(MotionVectors));
+
+	for (int y = start; y < end; y += 32) {
+		// Y, the two chroma planes in the order they are coded, A
+		uint32 intraCBP[4] = { 0, 0, 0, 0 };
+		uint32 interCBP[4] = { 0, 0, 0, 0 };
+		int intraQ[4] = { 8, 8, 8, 8 };
+		int interQ[4] = { 8, 8, 8, 8 };
+
+		memset(_currentMV, 0, _mvRows[0].size() * sizeof(MotionVectors));
+
+		for (int x = 0; x < (int)_width; x += 32) {
+			MotionVectors mv;
+			memset(&mv, 0, sizeof(mv));
+
+			const int type = isKeyFrame ? (int)kBlockIntra : (int)bits.getBits<2>();
+
+			_mbPos = x / 32;
+			_mbX = x;
+			_mbY = y;
+			_currentDC[_mbPos].blockType = type;
+
+			int flags = 0;
+			if (y == start)
+				flags |= kFlagTop;
+			if (x == 0)
+				flags |= kFlagLeft;
+
+			bool isValid = true;
+
+			switch (type) {
+			case kBlockIntra:
+				// The DCs of the neighbors that were not intra come from their pixels
+				if (!(flags & (kFlagTop | kFlagLeft)) && _prevDC[_mbPos - 1].blockType != kBlockIntra)
+					averageNeighbor(x - 32, -32, dst, _prevDC[_mbPos - 1]);
+				if (!(flags & kFlagLeft) && _currentDC[_mbPos - 1].blockType != kBlockIntra)
+					averageNeighbor(x - 32, 0, dst, _currentDC[_mbPos - 1]);
+				if ((flags & kFlagLeft) && !(flags & kFlagTop) && _prevDC[_mbPos + 1].blockType != kBlockIntra)
+					averageNeighbor(x + 32, -32, dst, _prevDC[_mbPos + 1]);
+				if (!(flags & kFlagTop) && _prevDC[_mbPos].blockType != kBlockIntra)
+					averageNeighbor(x, -32, dst, _prevDC[_mbPos]);
+
+				predictMotionVectors(flags, mv);
+
+				_comp = 0;
+				isValid = decodeLuma(bits, true, intraCBP[0], intraQ[0], dst[0] + x, _pitches[0], flags);
+				_comp = 1;
+				isValid = isValid && decodeChroma(bits, true, intraCBP[1], intraQ[1], dst[2] + x / 2, _pitches[2], flags);
+				_comp = 2;
+				isValid = isValid && decodeChroma(bits, true, intraCBP[2], intraQ[2], dst[1] + x / 2, _pitches[1], flags);
+				if (_hasAlpha) {
+					_comp = 3;
+					isValid = isValid && decodeLuma(bits, true, intraCBP[3], intraQ[3], dst[3] + x, _pitches[3], flags);
+				}
+				break;
+			case kBlockSkip:
+				copyBlock(dst[0] + x, src[0] + x + y * _pitches[0], _pitches[0], 32, 32);
+				copyBlock(dst[1] + x / 2, src[1] + x / 2 + y / 2 * _pitches[1], _pitches[1], 16, 16);
+				copyBlock(dst[2] + x / 2, src[2] + x / 2 + y / 2 * _pitches[2], _pitches[2], 16, 16);
+				if (_hasAlpha)
+					copyBlock(dst[3] + x, src[3] + x + y * _pitches[3], _pitches[3], 32, 32);
+				break;
+			default:
+				// Motion, or motion with a residue
+				decodeMotionVectors(bits, flags, mv);
+				predictMotionVectors(flags, mv);
+
+				compensateLuma(x, y, dst[0], src[0], _pitches[0]);
+				compensateChroma(x / 2, y / 2, dst[2], src[2], _pitches[2]);
+				compensateChroma(x / 2, y / 2, dst[1], src[1], _pitches[1]);
+				if (_hasAlpha)
+					compensateLuma(x, y, dst[3], src[3], _pitches[3]);
+
+				if (type == kBlockResidue) {
+					_comp = 0;
+					isValid = decodeLuma(bits, false, interCBP[0], interQ[0], dst[0] + x, _pitches[0], flags);
+					_comp = 1;
+					isValid = isValid && decodeChroma(bits, false, interCBP[1], interQ[1], dst[2] + x / 2, _pitches[2], flags);
+					_comp = 2;
+					isValid = isValid && decodeChroma(bits, false, interCBP[2], interQ[2], dst[1] + x / 2, _pitches[1], flags);
+					if (_hasAlpha) {
+						_comp = 3;
+						isValid = isValid && decodeLuma(bits, false, interCBP[3], interQ[3], dst[3] + x, _pitches[3], flags);
+					}
+				}
+				break;
+			}
+
+			if (type != kBlockIntra) {
+				for (int plane = 0; plane < _numPlanes; plane++) {
+					const int size = (plane == 1 || plane == 2) ? 2 : 4;
+					for (int j = 0; j < size; j++)
+						for (int i = 0; i < size; i++)
+							setBlockWord(plane, x / (32 / size) + i, y / (32 / size) + j, 0);
+				}
+			}
+			for (int i = 0; i < 4; i++) {
+				int *vector = &_blockVectors[((y / 16 + (i >> 1)) * (_alignedWidth / 16) + x / 16 + (i & 1)) * 2];
+				const bool isMoved = type == kBlockMotion || type == kBlockResidue;
+				vector[0] = isMoved ? _currentMV[_mbPos].v[i][0] : 0;
+				vector[1] = isMoved ? _currentMV[_mbPos].v[i][1] : 0;
+			}
+
+			if (!isValid) {
+				warning("Bink2Decoder: Bad quantizer at macroblock %d, %d", x, y);
+				return;
+			}
+		}
+
+		for (int plane = 0; plane < _numPlanes; plane++) {
+			const bool isChroma = plane == 1 || plane == 2;
+			dst[plane] += (isChroma ? 16 : 32) * _pitches[plane];
+		}
+
+		SWAP(_currentMV, _prevMV);
+		SWAP(_currentDC, _prevDC);
+	}
+}
+
+int Bink2Decoder::Bink2VideoTrack::decodeDeltaQ(BitStream &bits) {
+	int dq = _quantHuffman->getSymbol(bits);
+
+	if (dq && bits.getBit())
+		dq = -dq;
+
+	return dq;
+}
+
+// Which 8x8 blocks have coefficients (bits 0-15) and which of those use the
+// second set of codes (bits 16-31), from the ones of the previous macroblock
+uint32 Bink2Decoder::Bink2VideoTrack::decodeLumaCBP(BitStream &bits, uint32 prevCBP) {
+	uint32 low;
+
+	if (bits.getBit()) {
+		if (bits.getBit())
+			return prevCBP;
+		low = prevCBP & 0xFFFF;
+	} else {
+		low = 0;
+		uint32 nibble = (prevCBP >> 4) & 0xF;
+		for (int i = 0; i < 4; i++) {
+			if (!bits.getBit())
+				nibble = bits.getBits<4>();
+			low |= nibble << (i * 4);
+		}
+	}
+
+	uint32 high = 0;
+	uint32 cbp = low;
+	uint32 nibble = (prevCBP >> 20) & 0xF;
+	for (int i = 0; i < 4; i++) {
+		const int count = countBits4(cbp);
+
+		if (count == 0) {
+			nibble = 0;
+		} else if (count == 1 || !bits.getBit()) {
+			nibble = 0;
+			for (uint32 j = 1; j < 16; j <<= 1) {
+				if ((j & cbp) && bits.getBit())
+					nibble |= j;
+			}
+		}
+
+		nibble &= cbp;
+		high = (high >> 4) | (nibble << 28);
+		cbp >>= 4;
+	}
+
+	return high | low;
+}
+
+uint32 Bink2Decoder::Bink2VideoTrack::decodeChromaCBP(BitStream &bits, uint32 prevCBP) {
+	uint32 low;
+
+	if (bits.getBit()) {
+		if (bits.getBit())
+			return prevCBP;
+		low = prevCBP & 0xF;
+	} else {
+		low = bits.getBits<4>();
+	}
+
+	uint32 high = 0;
+	const int count = countBits4(low);
+	if (count) {
+		if (count != 1 && bits.getBit())
+			return low | (((prevCBP >> 16) & low) << 16);
+
+		for (uint32 j = 1; j < 16; j <<= 1) {
+			if ((j & low) && bits.getBit())
+				high |= j;
+		}
+	}
+
+	return low | (high << 16);
+}
+
+// The DCs of the 16 luma or 4 chroma blocks of the macroblock, from the
+// differences read and the blocks to the left and above
+void Bink2Decoder::Bink2VideoTrack::predictDC(bool isLuma, float minDC, float maxDC, int flags, float base, const float tdc[16]) {
+	const float *leftTop = _prevDC[MAX(_mbPos - 1, 0)].dc[_comp];
+	const float *top     = _prevDC[_mbPos].dc[_comp];
+	const float *left    = _currentDC[MAX(_mbPos - 1, 0)].dc[_comp];
+	float *dc = _currentDC[_mbPos].dc[_comp];
+
+	const bool hasTop  = !(flags & kFlagTop);
+	const bool hasLeft = !(flags & kFlagLeft);
+
+	float first;
+	if (hasTop && hasLeft)
+		first = isLuma ? predictMedian(leftTop[15], left[5], top[10]) : predictMedian(leftTop[3], left[1], top[2]);
+	else if (hasTop)
+		first = isLuma ? predictMedian2(top[10], top[11]) : predictMedian2(top[2], top[3]);
+	else if (hasLeft)
+		first = isLuma ? predictMedian2(left[5], left[7]) : predictMedian2(left[1], left[3]);
+	else
+		first = base;
+
+	dc[0] = CLIP(first + tdc[0], minDC, maxDC);
+
+	if (!isLuma) {
+		dc[1] = CLIP((hasTop ? predictMedian(top[2], dc[0], top[3]) : dc[0]) + tdc[1], minDC, maxDC);
+		dc[2] = CLIP((hasLeft ? predictMedian(left[1], left[3], dc[0]) : predictMedian2(dc[0], dc[1])) + tdc[2], minDC, maxDC);
+		dc[3] = CLIP(predictMedian(dc[0], dc[2], dc[1]) + tdc[3], minDC, maxDC);
+		return;
+	}
+
+	dc[1]  = CLIP((hasTop ? predictMedian(top[10], dc[0], top[11]) : dc[0]) + tdc[1], minDC, maxDC);
+	dc[2]  = CLIP((hasLeft ? predictMedian(left[5], left[7], dc[0]) : predictMedian2(dc[0], dc[1])) + tdc[2], minDC, maxDC);
+	dc[3]  = CLIP(predictMedian(dc[0], dc[2], dc[1]) + tdc[3], minDC, maxDC);
+	dc[4]  = CLIP((hasTop ? predictMedian(top[11], dc[1], top[14]) : predictMedian2(dc[1], dc[3])) + tdc[4], minDC, maxDC);
+	dc[5]  = CLIP((hasTop ? predictMedian(top[14], dc[4], top[15]) : dc[4]) + tdc[5], minDC, maxDC);
+	dc[6]  = CLIP(predictMedian(dc[1], dc[3], dc[4]) + tdc[6], minDC, maxDC);
+	dc[7]  = CLIP(predictMedian(dc[4], dc[6], dc[5]) + tdc[7], minDC, maxDC);
+	dc[8]  = CLIP((hasLeft ? predictMedian(left[7], left[13], dc[2]) : predictMedian2(dc[2], dc[3])) + tdc[8], minDC, maxDC);
+	dc[9]  = CLIP(predictMedian(dc[2], dc[8], dc[3]) + tdc[9], minDC, maxDC);
+	dc[10] = CLIP((hasLeft ? predictMedian(left[13], left[15], dc[8]) : predictMedian2(dc[8], dc[9])) + tdc[10], minDC, maxDC);
+	dc[11] = CLIP(predictMedian(dc[8], dc[10], dc[9]) + tdc[11], minDC, maxDC);
+	dc[12] = CLIP(predictMedian(dc[3], dc[9], dc[6]) + tdc[12], minDC, maxDC);
+	dc[13] = CLIP(predictMedian(dc[6], dc[12], dc[7]) + tdc[13], minDC, maxDC);
+	dc[14] = CLIP(predictMedian(dc[9], dc[11], dc[12]) + tdc[14], minDC, maxDC);
+	dc[15] = CLIP(predictMedian(dc[12], dc[14], dc[13]) + tdc[15], minDC, maxDC);
+}
+
+void Bink2Decoder::Bink2VideoTrack::decodeDC(BitStream &bits, bool isLuma, int q, int minDC, int maxDC, int flags) {
+	const int count = isLuma ? 16 : 4;
+	float tdc[16] = {};
+
+	int dcBits = bits.getBits<3>();
+	if (dcBits == 7)
+		dcBits += bits.getBits<2>();
+
+	if (dcBits) {
+		for (int j = 0; j < count; j += 4) {
+			for (int i = 0; i < 4; i++)
+				tdc[i + j] = (float)bits.getBits(dcBits);
+
+			for (int i = 0; i < 4; i++) {
+				if (tdc[i + j] != 0.0f && bits.getBit())
+					tdc[i + j] = -tdc[i + j];
+			}
+		}
+	}
+
+	// The first intra macroblock of a slice has more bits for its first DC,
+	// which starts from 1024 when there are any
+	float base = 0.0f;
+	if ((flags & kFlagTop) && (flags & kFlagLeft) && minDC >= 0) {
+		const int usedBits = kDCQuantBits[q] + dcBits;
+
+		if (usedBits < 10) {
+			base = 1024.0f;
+			int value = bits.getBits(10 - usedBits);
+
+			if (value) {
+				value <<= dcBits;
+				if (bits.getBit())
+					value = -value;
+			}
+
+			tdc[0] += value;
+		}
+	}
+
+	for (int i = 0; i < count; i++)
+		tdc[i] *= kDCQuant[q];
+
+	predictDC(isLuma, minDC, maxDC, flags, base, tdc);
+}
+
+// The AC coefficients of four 8x8 blocks, for the ones set in the low bits of cbp
+void Bink2Decoder::Bink2VideoTrack::decodeAC(BitStream &bits, const byte *scan, uint32 cbp, float q, const float *qmat) {
+	for (int i = 0; i < 4; i++, cbp >>= 1) {
+		memset(_block[i], 0, sizeof(_block[i]));
+		_coefCounts[i] = 0;
+
+		if (!(cbp & 1))
+			continue;
+
+		const int table = (cbp & 0x10000) ? 1 : 0;
+		int next = 0;
+		int index = 1;
+
+		while (index < 64) {
+			int value = _acValueHuffman[table]->getSymbol(bits);
+
+			if (value) {
+				if (value >= 4) {
+					const int extraBits = value - 3;
+					value = bits.getBits(extraBits) + (1 << extraBits) + 2;
+				}
+
+				if (bits.getBit())
+					value = -value;
+				_coefCounts[i]++;
+			}
+
+			_block[i][scan[index]] = value * (qmat[scan[index]] * q);
+
+			if (index > 62)
+				break;
+
+			index++;
+			next--;
+
+			if (next < 1) {
+				const int skip = _acSkipHuffman[table]->getSymbol(bits);
+				int run = kACSkips[skip];
+
+				next = kACNextSkips[skip];
+				if (run == 11)
+					run = bits.getBits<6>();
+
+				index += run;
+			}
+		}
+	}
+}
+
+bool Bink2Decoder::Bink2VideoTrack::decodeLuma(BitStream &bits, bool isIntra, uint32 &prevCBP, int &prevQ, byte *dst, int pitch, int flags) {
+	const uint32 cbp = prevCBP = decodeLumaCBP(bits, prevCBP);
+
+	const int q = prevQ + decodeDeltaQ(bits);
+	if (q < 0 || q >= 16)
+		return false;
+	prevQ = q;
+
+	// The differences of a residue are not predicted from the neighbors
+	if (isIntra)
+		decodeDC(bits, true, q, 0, 2047, flags);
+	else
+		decodeDC(bits, true, q, -1023, 1023, kFlagTop | kFlagLeft);
+
+	const float *dc = _currentDC[_mbPos].dc[_comp];
+
+	for (int i = 0; i < 4; i++) {
+		decodeAC(bits, kLumaScan, cbp >> (4 * i), kACQuant[q], isIntra ? kLumaIntraQmat : kLumaInterQmat);
+
+		const bool isFlat = !isIntra && !(_coefCounts[0] | _coefCounts[1] | _coefCounts[2] | _coefCounts[3]);
+		for (int j = 0; j < 4; j++) {
+			const int pos = kLumaBlockPos[i * 4 + j];
+			byte *blockDst = dst + (pos & 3) * 8 + (pos >> 2) * 8 * pitch;
+
+			if (isIntra)
+				setBlockWord(_comp == 0 ? 0 : 3, _mbX / 8 + (pos & 3), _mbY / 8 + (pos >> 2), makeBlockWord(_coefCounts[j], dc[i * 4 + j]));
+			if (isFlat) {
+				addFlat(blockDst, pitch, dc[i * 4 + j]);
+				continue;
+			}
+			idct(blockDst, pitch, _block[j], dc[i * 4 + j], !isIntra);
+		}
+	}
+
+	return true;
+}
+
+bool Bink2Decoder::Bink2VideoTrack::decodeChroma(BitStream &bits, bool isIntra, uint32 &prevCBP, int &prevQ, byte *dst, int pitch, int flags) {
+	const uint32 cbp = prevCBP = decodeChromaCBP(bits, prevCBP);
+
+	const int q = prevQ + decodeDeltaQ(bits);
+	if (q < 0 || q >= 16)
+		return false;
+	prevQ = q;
+
+	if (isIntra)
+		decodeDC(bits, false, q, 0, 2047, flags);
+	else
+		decodeDC(bits, false, q, -1023, 1023, kFlagTop | kFlagLeft);
+
+	decodeAC(bits, kChromaScan, cbp, kACQuant[q], kChromaQmat);
+
+	const float *dc = _currentDC[_mbPos].dc[_comp];
+
+	const bool isFlat = !isIntra && !(_coefCounts[0] | _coefCounts[1] | _coefCounts[2] | _coefCounts[3]);
+	for (int j = 0; j < 4; j++) {
+		byte *blockDst = dst + (j & 1) * 8 + (j >> 1) * 8 * pitch;
+		if (isIntra)
+			setBlockWord(_comp == 1 ? 2 : 1, _mbX / 16 + (j & 1), _mbY / 16 + (j >> 1), makeBlockWord(_coefCounts[j], dc[j]));
+		if (isFlat) {
+			addFlat(blockDst, pitch, dc[j]);
+			continue;
+		}
+		idct(blockDst, pitch, _block[j], dc[j], !isIntra);
+	}
+
+	return true;
+}
+
+// The differences of the four motion vectors, in half luma pixels
+void Bink2Decoder::Bink2VideoTrack::decodeMotionVectors(BitStream &bits, int flags, MotionVectors &mv) {
+	for (int i = 0; i < 2; i++) {
+		int valueBits = bits.getBits<3>();
+		if (valueBits == 7)
+			valueBits += bits.getBits<2>();
+
+		if (valueBits) {
+			for (int j = 0; j < 4; j++)
+				mv.v[j][i] = bits.getBits(valueBits);
+
+			for (int j = 0; j < 4; j++) {
+				if (mv.v[j][i] && bits.getBit())
+					mv.v[j][i] = -mv.v[j][i];
+			}
+		}
+
+		// The first macroblock of a slice has an offset for all four
+		int offset = 0;
+		if ((flags & kFlagTop) && (flags & kFlagLeft)) {
+			offset = bits.getBits<5>() * 16;
+			if (offset && bits.getBit())
+				offset = -offset;
+		}
+
+		for (int j = 0; j < 4; j++)
+			mv.v[j][i] += offset;
+	}
+}
+
+void Bink2Decoder::Bink2VideoTrack::predictMotionVectors(int flags, const MotionVectors &mv) {
+	MotionVectors &cur = _currentMV[_mbPos];
+	const MotionVectors &left    = _currentMV[MAX(_mbPos - 1, 0)];
+	const MotionVectors &leftTop = _prevMV[MAX(_mbPos - 1, 0)];
+	const MotionVectors &top     = _prevMV[_mbPos];
+
+	for (int i = 0; i < 2; i++) {
+		if (!(flags & kFlagTop)) {
+			if (flags & kFlagLeft)
+				cur.v[0][i] = mv.v[0][i] + median(top.v[0][i], top.v[2][i], top.v[3][i]);
+			else
+				cur.v[0][i] = mv.v[0][i] + median(leftTop.v[3][i], top.v[2][i], left.v[1][i]);
+
+			cur.v[1][i] = mv.v[1][i] + median(top.v[2][i], top.v[3][i], cur.v[0][i]);
+			cur.v[2][i] = mv.v[2][i] + median(top.v[2][i], cur.v[0][i], cur.v[1][i]);
+			cur.v[3][i] = mv.v[3][i] + median(cur.v[0][i], cur.v[1][i], cur.v[2][i]);
+		} else if (flags & kFlagLeft) {
+			for (int j = 0; j < 4; j++)
+				cur.v[j][i] = mv.v[j][i];
+		} else {
+			cur.v[0][i] = mv.v[0][i] + median(left.v[0][i], left.v[1][i], left.v[3][i]);
+			cur.v[2][i] = mv.v[2][i] + median(left.v[1][i], left.v[3][i], cur.v[0][i]);
+			cur.v[1][i] = mv.v[1][i] + median(left.v[1][i], cur.v[0][i], cur.v[2][i]);
+			cur.v[3][i] = mv.v[3][i] + median(cur.v[0][i], cur.v[1][i], cur.v[2][i]);
+		}
+	}
+}
+
+// Four 16x16 blocks. One that points out of the frame is left as it is.
+void Bink2Decoder::Bink2VideoTrack::compensateLuma(int x, int y, byte *dst, const byte *src, int pitch) {
+	const MotionVectors &mv = _currentMV[_mbPos];
+
+	for (int i = 0; i < 4; i++) {
+		const int blockX = x + (i & 1) * 16;
+		const int blockY = y + (i >> 1) * 16;
+		const int srcX = (mv.v[i][0] >> 1) + blockX;
+		const int srcY = (mv.v[i][1] >> 1) + blockY;
+
+		if (srcX < 0 || srcX >= (int)_width || srcY < 0 || srcY >= (int)_height)
+			continue;
+
+		const int mode = (mv.v[i][0] & 1) | ((mv.v[i][1] & 1) << 1);
+		lumaBlock(dst + blockX + (i >> 1) * 16 * pitch, src + srcX + srcY * pitch, pitch, mode);
+	}
+}
+
+// Four 8x8 blocks, with the luma vectors in quarter chroma pixels
+void Bink2Decoder::Bink2VideoTrack::compensateChroma(int x, int y, byte *dst, const byte *src, int pitch) {
+	const MotionVectors &mv = _currentMV[_mbPos];
+
+	for (int i = 0; i < 4; i++) {
+		const int blockX = x + (i & 1) * 8;
+		const int blockY = y + (i >> 1) * 8;
+		const int srcX = (mv.v[i][0] >> 2) + blockX;
+		const int srcY = (mv.v[i][1] >> 2) + blockY;
+
+		if (srcX < 0 || srcX >= (int)_width / 2 || srcY < 0 || srcY >= (int)_height / 2)
+			continue;
+
+		const int mode = (mv.v[i][0] & 3) | ((mv.v[i][1] & 3) << 2);
+		chromaBlock(dst + blockX + (i >> 1) * 8 * pitch, src + srcX + srcY * pitch, pitch, mode);
+	}
+}
+
+void Bink2Decoder::Bink2VideoTrack::averageNeighbor(int x, int y, byte *const dst[4], DCPredict &predict) {
+	for (int i = 0; i < 16; i++) {
+		const int pos = kLumaBlockPos[i];
+		const int offset = x + (pos & 3) * 8 + (y + (pos >> 2) * 8) * _pitches[0];
+
+		predict.dc[0][i] = (float)averageBlock(dst[0] + offset, _pitches[0]);
+		if (_hasAlpha)
+			predict.dc[3][i] = (float)averageBlock(dst[3] + offset, _pitches[3]);
+	}
+
+	// The chroma planes in the order they are coded
+	for (int i = 0; i < 4; i++) {
+		const int chromaX = x / 2 + (i & 1) * 8;
+		const int chromaY = y / 2 + (i >> 1) * 8;
+
+		predict.dc[1][i] = (float)averageBlock(dst[2] + chromaX + chromaY * _pitches[2], _pitches[2]);
+		predict.dc[2][i] = (float)averageBlock(dst[1] + chromaX + chromaY * _pitches[1], _pitches[1]);
+	}
+}
+
+void Bink2Decoder::Bink2VideoTrack::setBlockWord(int plane, int x, int y, uint16 word) {
+	_blockWords[plane][y * _blockColumns[plane] + x] = word;
+}
+
+// A block with only a DC is drawn from the DCs around it: each neighbor that
+// is such a block too, with a DC closer than the threshold, pulls the pixels
+// near it toward its own DC.
+void Bink2Decoder::Bink2VideoTrack::blurBlock(int plane, int x, int y, int threshold) {
+	const int columns = _blockColumns[plane];
+	const int rows = (int)_blockWords[plane].size() / columns;
+	const uint16 center = _blockWords[plane][y * columns + x];
+
+	uint16 words[3][3];
+	for (int j = 0; j < 3; j++) {
+		for (int i = 0; i < 3; i++) {
+			const int nx = x + i - 1;
+			const int ny = y + j - 1;
+			words[j][i] = (nx >= 0 && nx < columns && ny >= 0 && ny < rows) ? _blockWords[plane][ny * columns + nx] : 0;
+		}
+	}
+
+	// Compared as signed 16-bit words, the kinds of block included
+	float values[3][3];
+	const int16 c = asInt16(center);
+	for (int j = 0; j < 3; j++) {
+		for (int i = 0; i < 3; i++) {
+			const int16 n = asInt16(words[j][i]);
+			const int16 difference = asInt16(MAX(n, c) - MIN(n, c));
+			values[j][i] = (threshold > difference) ? (float)(words[j][i] & 0x1FFF) : -1.0f;
+		}
+	}
+	values[1][1] = (float)(center & 0x1FFF);
+
+	// The sides that differ take the center's DC, the corners their side's
+	for (int j = 0; j < 3; j += 2)
+		if (values[j][1] < 0.0f)
+			values[j][1] = values[1][1];
+	for (int i = 0; i < 3; i += 2)
+		if (values[1][i] < 0.0f)
+			values[1][i] = values[1][1];
+	for (int j = 0; j < 3; j += 2)
+		for (int i = 0; i < 3; i += 2)
+			if (values[j][i] < 0.0f)
+				values[j][i] = values[1][i];
+
+	const int pitch = _pitches[plane];
+	byte *dst = _planes[_curFrame ^ 1][plane] + y * 8 * pitch + x * 8;
+
+	for (int py = 0; py < 8; py++) {
+		for (int px = 0; px < 8; px++) {
+			// In the original's order
+			float sum = values[0][0] * kBlurCorner[py][px];
+			sum += values[1][0] * kBlurEdge[px][py];
+			sum += values[2][0] * kBlurCorner[7 - py][px];
+			sum += values[0][1] * kBlurEdge[py][px];
+			sum += values[1][1] * kBlurCenter[py][px];
+			sum += values[2][1] * kBlurEdge[7 - py][px];
+			sum += values[0][2] * kBlurCorner[py][7 - px];
+			sum += values[1][2] * kBlurEdge[7 - px][py];
+			sum += values[2][2] * kBlurCorner[7 - py][7 - px];
+			sum += kAlmostHalf;
+			dst[py * pitch + px] = clipPixel((int)sum);
+		}
+	}
+}
+
+// Smooths the edges between the blocks of a plane, the ones between columns
+// or between rows, by the kinds of blocks on both sides: blocks with fewer
+// AC coefficients get more of their pixels changed. Between two blocks that
+// are not intra, it is done when their motion vectors differ.
+void Bink2Decoder::Bink2VideoTrack::filterEdges(int plane, bool isVertical) {
+	const int columns = _blockColumns[plane];
+	const int rows = (int)_blockWords[plane].size() / columns;
+	const int pitch = _pitches[plane];
+	const int shift = (plane == 1 || plane == 2) ? 0 : 1;
+	const int vectorColumns = _alignedWidth / 16;
+	byte *base = _planes[_curFrame ^ 1][plane];
+
+	for (int y = isVertical ? 0 : 1; y < rows; y++) {
+		for (int x = isVertical ? 1 : 0; x < columns; x++) {
+			const int ax = isVertical ? x - 1 : x;
+			const int ay = isVertical ? y : y - 1;
+			const uint16 a = _blockWords[plane][ay * columns + ax];
+			const uint16 b = _blockWords[plane][y * columns + x];
+
+			int code;
+			if (((a ^ b) & 0x8000) || (b & 0x8000)) {
+				code = ((a >> 13) & 3) | (((b >> 13) & 3) << 2);
+			} else {
+				const int *va = &_blockVectors[((ay >> shift) * vectorColumns + (ax >> shift)) * 2];
+				const int *vb = &_blockVectors[((y >> shift) * vectorColumns + (x >> shift)) * 2];
+				if ((uint32)(va[0] - vb[0] + 1) <= 2 && (uint32)(va[1] - vb[1] + 1) <= 2)
+					continue;
+				code = 0xA;
+			}
+
+			byte *p = base + y * 8 * pitch + x * 8;
+			for (int i = 0; i < 8; i++) {
+				if (isVertical)
+					filterEdge(p + i * pitch, 1, code);
+				else
+					filterEdge(p + i, pitch, code);
+			}
+		}
+	}
+}
+
+void Bink2Decoder::Bink2VideoTrack::deblock() {
+	const int threshold = (_frameFlags & 0xFF) * 8;
+
+	// The blocks with only a DC, all of them first
+
+	for (int plane = 0; plane < _numPlanes; plane++) {
+		const int columns = _blockColumns[plane];
+		const int rows = (int)_blockWords[plane].size() / columns;
+		for (int y = 0; y < rows; y++)
+			for (int x = 0; x < columns; x++)
+				if ((_blockWords[plane][y * columns + x] >> 13) == 7)
+					blurBlock(plane, x, y, threshold);
+	}
+
+	// The alpha plane does not have its edges filtered
+	for (int plane = 0; plane < 3; plane++) {
+		if (!(_frameFlags & kFrameFlagNoColFlags))
+			filterEdges(plane, true);
+		if (!(_frameFlags & kFrameFlagNoRowFlags))
+			filterEdges(plane, false);
+	}
+}
+
+} // End of namespace Video
+
+#endif // USE_BINK
diff --git a/video/bink2_decoder.h b/video/bink2_decoder.h
new file mode 100644
index 00000000000..ace7992b969
--- /dev/null
+++ b/video/bink2_decoder.h
@@ -0,0 +1,244 @@
+/* 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/>.
+ *
+ */
+
+// Based on the Bink 2 decoder written for FFmpeg by
+// Konstantin Shishkov and Paul B Mahol, which was never merged there,
+// with what it lacked taken from RAD's own decoder.
+
+#include "common/scummsys.h"
+
+#ifdef USE_BINK
+
+#ifndef VIDEO_BINK2_DECODER_H
+#define VIDEO_BINK2_DECODER_H
+
+#include "common/array.h"
+#include "common/bitstream.h"
+#include "common/rational.h"
+
+#include "graphics/pixelformat.h"
+
+#include "video/bink_decoder.h"
+#include "video/video_decoder.h"
+
+namespace Common {
+class SeekableReadStream;
+template <class BITSTREAM>
+class Huffman;
+}
+
+namespace Graphics {
+struct Surface;
+}
+
+namespace Video {
+
+/**
+ * Decoder for Bink 2 videos of revision 'f' (KB2f).
+ *
+ * Video decoder used in engines:
+ *  - nancy
+ */
+class Bink2Decoder : public VideoDecoder {
+public:
+	Bink2Decoder();
+	~Bink2Decoder() override;
+
+	bool loadStream(Common::SeekableReadStream *stream) override;
+	void close() override;
+
+	/** Whether the stream starts like a file this decoder plays. */
+	static bool isBink2(Common::SeekableReadStream &stream);
+
+protected:
+	void readNextPacket() override;
+	bool supportsAudioTrackSwitching() const override { return true; }
+	AudioTrack *getAudioTrack(int index) override;
+	bool seekIntern(const Audio::Timestamp &time) override;
+
+private:
+	struct Frame {
+		uint32 offset;
+		uint32 size;
+		bool isKeyFrame;
+	};
+
+	/**
+	 * A frame is made of 32x32 macroblocks of YUV 4:2:0 and optional alpha,
+	 * coded with a float DCT and half pixel (luma) or quarter pixel (chroma)
+	 * motion compensation. Once decoded, its blocks with only a DC are blurred
+	 * into their neighbors and the edges between blocks smoothed, as RAD's own
+	 * decoder does.
+	 */
+	class Bink2VideoTrack : public FixedRateVideoTrack {
+	public:
+		Bink2VideoTrack(uint32 width, uint32 height, uint32 flags, uint32 frameCount, const Common::Rational &frameRate);
+		~Bink2VideoTrack() override;
+
+		uint16 getWidth() const override { return _width; }
+		uint16 getHeight() const override { return _height; }
+		Graphics::PixelFormat getPixelFormat() const override { return _pixelFormat; }
+		bool setOutputPixelFormat(const Graphics::PixelFormat &format) override;
+		int getCurFrame() const override { return _curFrameNumber; }
+		int getFrameCount() const override { return _frameCount; }
+		const Graphics::Surface *decodeNextFrame() override { return _surface; }
+		bool isSeekable() const override { return true; }
+		bool seek(const Audio::Timestamp &) override { return true; }
+		bool rewind() override;
+
+		void setCurFrame(int frame) { _curFrameNumber = frame; }
+
+		/** Decode the next size bytes of the stream, a video packet, into the next frame. */
+		void decodePacket(Common::SeekableReadStream &stream, uint32 size, bool isKeyFrame);
+
+	protected:
+		Common::Rational getFrameRate() const override { return _frameRate; }
+
+	private:
+		typedef Common::BitStreamMemory32LELSB BitStream;
+		typedef Common::Huffman<BitStream> Huffman;
+
+		enum BlockType {
+			kBlockIntra   = 0,
+			kBlockSkip    = 1,
+			kBlockMotion  = 2,
+			kBlockResidue = 3
+		};
+
+		// Macroblock edge flags
+		enum {
+			kFlagLeft     = 0x20, // first macroblock of a row
+			kFlagTop      = 0x80  // first row of a slice
+		};
+
+		struct DCPredict {
+			float dc[4][16];
+			int blockType;
+		};
+
+		struct MotionVectors {
+			int v[4][2];
+		};
+
+		uint32 _width;
+		uint32 _height;
+		uint32 _alignedWidth;
+		uint32 _alignedHeight;
+		bool _hasAlpha;
+
+		int _frameCount;
+		int _curFrameNumber;
+		Common::Rational _frameRate;
+
+		Graphics::PixelFormat _pixelFormat;
+		Graphics::Surface *_surface;
+
+		// Two frames with a border around each plane, for motion vectors
+		// that reach past the edges
+		byte *_buffers[2][4];
+		byte *_planes[2][4];
+		int _pitches[4];
+		uint32 _planeSizes[4];
+		int _numPlanes;
+		int _curFrame;
+
+		Common::Array<byte> _packet;
+
+		// Per macroblock column, for the current and the previous row
+		Common::Array<DCPredict> _dcRows[2];
+		Common::Array<MotionVectors> _mvRows[2];
+		DCPredict *_currentDC;
+		DCPredict *_prevDC;
+		MotionVectors *_currentMV;
+		MotionVectors *_prevMV;
+
+		int _comp;
+		int _mbPos;
+
+		float _block[4][64];
+		int _coefCounts[4];
+
+		// Per 8x8 block of each plane: the kind of block in the top three bits
+		// (0 not intra, then 4 to 7 for intra ones with fewer AC coefficients),
+		// and its DC in the others. Per 16x16 luma block: the motion vector.
+		Common::Array<uint16> _blockWords[4];
+		int _blockColumns[4];
+		Common::Array<int> _blockVectors;
+		int _mbX;
+		int _mbY;
+		uint32 _frameFlags;
+
+		Huffman *_quantHuffman;
+		Huffman *_acValueHuffman[2];
+		Huffman *_acSkipHuffman[2];
+
+		/** Clear both frames to black. */
+		void reset();
+
+		void decodeFrame(Common::SeekableReadStream &stream, uint32 size, bool isKeyFrame);
+		void decodeSlice(BitStream &bits, bool isKeyFrame, int start, int end);
+
+		void skipBlockFlags(BitStream &bits, int size);
+
+		int decodeDeltaQ(BitStream &bits);
+		uint32 decodeLumaCBP(BitStream &bits, uint32 prevCBP);
+		uint32 decodeChromaCBP(BitStream &bits, uint32 prevCBP);
+
+		void predictDC(bool isLuma, float minDC, float maxDC, int flags, float base, const float tdc[16]);
+		void decodeDC(BitStream &bits, bool isLuma, int q, int minDC, int maxDC, int flags);
+		void decodeAC(BitStream &bits, const byte *scan, uint32 cbp, float q, const float *qmat);
+
+		bool decodeLuma(BitStream &bits, bool isIntra, uint32 &prevCBP, int &prevQ, byte *dst, int pitch, int flags);
+		bool decodeChroma(BitStream &bits, bool isIntra, uint32 &prevCBP, int &prevQ, byte *dst, int pitch, int flags);
+
+		void decodeMotionVectors(BitStream &bits, int flags, MotionVectors &mv);
+		void predictMotionVectors(int flags, const MotionVectors &mv);
+		// x and y are in the plane; dst points at the row of the macroblock
+		void compensateLuma(int x, int y, byte *dst, const byte *src, int pitch);
+		void compensateChroma(int x, int y, byte *dst, const byte *src, int pitch);
+
+		// The DCs of a macroblock that was not coded as intra, from its pixels.
+		// x is in luma pixels, y in luma rows from the current row.
+		void averageNeighbor(int x, int y, byte *const dst[4], DCPredict &predict);
+
+		void setBlockWord(int plane, int x, int y, uint16 word);
+
+		// After a frame is decoded
+		void deblock();
+		void blurBlock(int plane, int x, int y, int threshold);
+		void filterEdges(int plane, bool isVertical);
+
+		// Into the output surface
+		void convertFrame();
+	};
+
+	Common::SeekableReadStream *_stream;
+	Common::Array<Frame> _frames;
+	uint32 _audioTrackCount;
+
+	uint32 findKeyFrame(uint32 frame) const;
+};
+
+} // End of namespace Video
+
+#endif // VIDEO_BINK2_DECODER_H
+
+#endif // USE_BINK
diff --git a/video/module.mk b/video/module.mk
index d4592b10f75..eeeb675dc6e 100644
--- a/video/module.mk
+++ b/video/module.mk
@@ -21,7 +21,8 @@ MODULE_OBJS := \
 
 ifdef USE_BINK
 MODULE_OBJS += \
-	bink_decoder.o
+	bink_decoder.o \
+	bink2_decoder.o
 endif
 
 ifdef USE_COKTEL_DECODER


Commit: c41c492951b0307ed2d8a2b7230b1ec7ebb2b699
    https://github.com/scummvm/scummvm/commit/c41c492951b0307ed2d8a2b7230b1ec7ebb2b699
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:56:55+02:00

Commit Message:
NANCY: NANCY29: Play Bink 2 movies

Nancy29 has movies in both versions of Bink. The movie player will pick
the correct decoder from the header of each movie file

Changed paths:
    engines/nancy/movieplayer.cpp


diff --git a/engines/nancy/movieplayer.cpp b/engines/nancy/movieplayer.cpp
index 21a24ce7365..a777657a586 100644
--- a/engines/nancy/movieplayer.cpp
+++ b/engines/nancy/movieplayer.cpp
@@ -23,6 +23,7 @@
 #include "common/system.h"
 
 #include "video/bink_decoder.h"
+#include "video/bink2_decoder.h"
 
 #include "engines/nancy/nancy.h"
 #include "engines/nancy/resource/video.h"
@@ -104,7 +105,12 @@ bool MoviePlayer::loadFile(const Common::Path &name, byte videoPlaytype, bool bi
 	}
 
 	if (_videoType == kVideoPlaytypeBink) {
-		_decoder.reset(new Video::BinkDecoder());
+		// Nancy29 has movies in both versions of Bink
+		Common::File file;
+		if (file.open(bikPath) && Video::Bink2Decoder::isBink2(file))
+			_decoder.reset(new Video::Bink2Decoder());
+		else
+			_decoder.reset(new Video::BinkDecoder());
 	} else {
 		_decoder.reset(new AVFDecoder(bidirectionalCache ? AVFDecoder::kLoadBidirectional : AVFDecoder::kLoadForward));
 	}


Commit: afdad61c5df062d26fb8055ad2179a6c7bd9b579
    https://github.com/scummvm/scummvm/commit/afdad61c5df062d26fb8055ad2179a6c7bd9b579
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:56:57+02:00

Commit Message:
NANCY: NANCY29: Read the longer tree names of XSheets

Nancy29 has 64 bytes for each tree name of an XSheet, instead of 33.

Changed paths:
    engines/nancy/resource/xsheetfile.cpp


diff --git a/engines/nancy/resource/xsheetfile.cpp b/engines/nancy/resource/xsheetfile.cpp
index 64980ea3909..a0c1bd320ca 100644
--- a/engines/nancy/resource/xsheetfile.cpp
+++ b/engines/nancy/resource/xsheetfile.cpp
@@ -31,6 +31,7 @@ namespace Nancy {
 
 static const uint kXSheetFrameCountOffset = 0x22;
 static const uint kXSheetNameSize = 33;
+static const uint kNancy29XSheetNameSize = 64;
 static const uint kXSheetCelRecordSize = 140;
 
 bool XSheetFile::load(const Common::String &name) {
@@ -57,12 +58,14 @@ bool XSheetFile::load(const Common::String &name) {
 		// as many trees as there can be
 		numTrees = MIN<uint>(xsheet->readUint16LE(), kMaxTrees);
 
+		// Nancy29 makes room for longer names
+		const uint nameSize = g_nancy->getGameType() >= kGameTypeNancy29 ? kNancy29XSheetNameSize : kXSheetNameSize;
 		treeNames.resize(numTrees);
 		for (Common::String &treeName : treeNames) {
-			readFilename(*xsheet, treeName);
+			treeName = xsheet->readString('\0', nameSize);
 		}
 
-		xsheet->skip((kMaxTrees - numTrees) * kXSheetNameSize);
+		xsheet->skip((kMaxTrees - numTrees) * nameSize);
 
 		if (g_nancy->getGameType() >= kGameTypeNancy15) {
 			// Nancy20 lines the rectangles up on four bytes


Commit: 8502574e383585a601356a910d7d1b2e79236c94
    https://github.com/scummvm/scummvm/commit/8502574e383585a601356a910d7d1b2e79236c94
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:00+02:00

Commit Message:
NANCY: NANCY29: Add Rect:Align

It moves a rectangle so that a side or the middle of it lines up with
the same one of another rectangle, or with a point.

Changed paths:
    engines/nancy/script/types.cpp


diff --git a/engines/nancy/script/types.cpp b/engines/nancy/script/types.cpp
index 1a2998d0c64..0888d553e6e 100644
--- a/engines/nancy/script/types.cpp
+++ b/engines/nancy/script/types.cpp
@@ -348,6 +348,48 @@ static int rectRightBottomSet(lua_State *L) {
 	return 1;
 }
 
+// rect:Align(target, horizontal, vertical), Nancy29: moves the rectangle so
+// that a side or the middle of it lines up with the same one of another
+// rectangle, or with a point. The sides are "left", "center" or "right", and
+// "top", "center" or "bottom". Middles and points are rounded to whole pixels.
+static int alignOffset(lua_State *L, int index, const char *const names[3], int32 start, int32 end, double middle,
+		bool isPoint, double point, int32 targetStart, int32 targetEnd, double targetMiddle) {
+	const char *name = luaL_checkstring(L, index);
+	if (strcmp(name, names[0]) == 0) {
+		return (isPoint ? (int32)roundCoordinate(point) : targetStart) - start;
+	} else if (strcmp(name, names[1]) == 0) {
+		return (int32)roundCoordinate(isPoint ? point : targetMiddle) - (int32)roundCoordinate(middle);
+	} else if (strcmp(name, names[2]) == 0) {
+		return (isPoint ? (int32)roundCoordinate(point) : targetEnd) - end;
+	}
+
+	luaL_argerror(L, index, Common::String::format("Expected '%s', '%s' or '%s'", names[0], names[1], names[2]).c_str());
+	return 0;
+}
+
+static int rectAlign(lua_State *L) {
+	static const char *const kHorizontalNames[] = { "left", "center", "right" };
+	static const char *const kVerticalNames[] = { "top", "center", "bottom" };
+
+	ScriptRect rect = checkRect(L, 1);
+	const ScriptRect *target = testRect(L, 2);
+	double x = 0.0;
+	double y = 0.0;
+	if (!target && !readPointCoordinates(L, 2, x, y)) {
+		luaL_argerror(L, 2, "Expected a Rect or a Point");
+	}
+
+	const ScriptRect targetRect = target ? *target : ScriptRect();
+	const int32 dx = alignOffset(L, 3, kHorizontalNames, rect.left, rect.right, rect.left + rect.width() * 0.5f,
+		!target, x, targetRect.left, targetRect.right, targetRect.left + targetRect.width() * 0.5f);
+	const int32 dy = alignOffset(L, 4, kVerticalNames, rect.top, rect.bottom, rect.top + rect.height() * 0.5f,
+		!target, y, targetRect.top, targetRect.bottom, targetRect.top + targetRect.height() * 0.5f);
+
+	rect.translate(dx, dy);
+	pushRect(L, rect);
+	return 1;
+}
+
 static int rectToString(lua_State *L) {
 	const ScriptRect &rect = checkRect(L, 1);
 	lua_pushstring(L, Common::String::format("R(%d, %d, %d, %d)", rect.left, rect.top, rect.right, rect.bottom).c_str());
@@ -386,6 +428,7 @@ static const luaL_Reg kRectFunctions[] = {
 	{ "LeftTopSet", rectLeftTopSet },
 	{ "LeftBottomSet", rectLeftBottomSet },
 	{ "RightBottomSet", rectRightBottomSet },
+	{ "Align", rectAlign },
 	{ nullptr, nullptr }
 };
 


Commit: 47452cde9bbe0c8c0e4917f68215e9d8c8ff87b1
    https://github.com/scummvm/scummvm/commit/47452cde9bbe0c8c0e4917f68215e9d8c8ff87b1
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:02+02:00

Commit Message:
NANCY: NANCY29: Add Brain:Contains

It tells whether the Brain has a condition by the given name.

Changed paths:
    engines/nancy/script/v5/brain.cpp


diff --git a/engines/nancy/script/v5/brain.cpp b/engines/nancy/script/v5/brain.cpp
index 0c01146c790..ddba3128715 100644
--- a/engines/nancy/script/v5/brain.cpp
+++ b/engines/nancy/script/v5/brain.cpp
@@ -309,6 +309,12 @@ static int brainAllNames(lua_State *L) {
 	return 1;
 }
 
+// Brain:Contains(name), Nancy29: whether there is a condition by the name
+static int brainContains(lua_State *L) {
+	lua_pushboolean(L, getBrain(L).exists(luaL_checkstring(L, 2)));
+	return 1;
+}
+
 // Nancy27
 static int brainIsAutoUpdated(lua_State *L) {
 	const Common::String name = checkLogicName(L, 2);
@@ -397,6 +403,7 @@ void registerBrainAPI(lua_State *L) {
 		{ "__index", brainIndex },
 		{ "__newindex", brainNewIndex },
 		{ "AllNames", brainAllNames },
+		{ "Contains", brainContains },
 		{ "IsAutoUpdated", brainIsAutoUpdated },
 		{ "IsCached", brainIsCached },
 		{ "IsWritable", brainIsWritable },


Commit: 7dcf74a220200eaa6d878af55b0c534e0de8b43d
    https://github.com/scummvm/scummvm/commit/7dcf74a220200eaa6d878af55b0c534e0de8b43d
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:05+02:00

Commit Message:
NANCY: NANCY29: Add the new Game and Scene functions

Game:ToClipboard, Game.accurateTime and Game.debugMode, which the cheat
tools use, and Scene:GetStreamInVP.

Changed paths:
    engines/nancy/script/v5/gamefunctions.cpp


diff --git a/engines/nancy/script/v5/gamefunctions.cpp b/engines/nancy/script/v5/gamefunctions.cpp
index 89908b51793..2ce4f013229 100644
--- a/engines/nancy/script/v5/gamefunctions.cpp
+++ b/engines/nancy/script/v5/gamefunctions.cpp
@@ -48,6 +48,7 @@
 #include "engines/nancy/script/v5/gamefunctions.h"
 #include "engines/nancy/script/v5/messaging.h"
 #include "engines/nancy/script/v5/scriptinput.h"
+#include "engines/nancy/script/v5/streamtree.h"
 
 #include "engines/nancy/state/scene.h"
 
@@ -411,8 +412,15 @@ static int gameGetScriptNameRange(lua_State *L) {
 	return 1;
 }
 
+// Game:ToClipboard(text), Nancy29: for the cheat tools
+static int gameToClipboard(lua_State *L) {
+	g_system->setTextInClipboard(Common::U32String(luaL_checkstring(L, 2)));
+	return 0;
+}
+
 static const luaL_Reg kGameFunctions[] = {
 	{ "SetScriptNameFilter", gameSetScriptNameFilter },
+	{ "ToClipboard", gameToClipboard },
 	{ "GetScriptNameRange", gameGetScriptNameRange },
 	{ "Save", gameSave },
 	{ "Load", gameLoad },
@@ -435,8 +443,14 @@ static bool pushGameField(lua_State *L, const Common::String &key) {
 
 	if (key == "isWindowed") {
 		lua_pushboolean(L, !g_system->getFeatureState(OSystem::kFeatureFullscreenMode));
-	} else if (key == "time") {
+	} else if (key == "time" || key == "accurateTime") {
+		// Nancy29 adds accurateTime, which includes fractions of a second.
+		// Our time includes them already, so both give the same value
 		lua_pushnumber(L, NancySceneState._timers.lastTotalTime.getTotalMilliseconds() / 1000.0);
+	} else if (key == "debugMode") {
+		// Nancy29: the DebugOutput setting of the game's INI file, which the
+		// release has switched off. The cheat tools need it for the inspector.
+		lua_pushboolean(L, false);
 	} else if (key == "buildNumber") {
 		const ScriptBootData *boot = GetEngineData(ScriptBootData);
 		lua_pushstring(L, boot ? boot->buildNumber.c_str() : "");
@@ -792,6 +806,15 @@ static int sceneIsStreamRunning(lua_State *L) {
 	return 1;
 }
 
+// Scene:GetStreamInVP(stream), Nancy29: whether the stream is drawn inside
+// the viewport rather than on the whole screen. Returns true for a stream
+// that isn't running.
+static int sceneGetStreamInVP(lua_State *L) {
+	const StreamNodeState *state = NancySceneState.getStreams().getNodeState(luaL_checkstring(L, 2));
+	lua_pushboolean(L, !state || state->isInViewport);
+	return 1;
+}
+
 // Log:Warn(text) and Log:Warn(location, text)
 static int logWarn(lua_State *L) {
 	if (lua_gettop(L) >= 3) {
@@ -927,6 +950,7 @@ void registerNancy26GameAPI(lua_State *L) {
 
 	static const luaL_Reg kSceneFunctions[] = {
 		{ "IsStreamRunning", sceneIsStreamRunning },
+		{ "GetStreamInVP", sceneGetStreamInVP },
 		{ nullptr, nullptr }
 	};
 


Commit: 091c4dea00ef81a3591144cc37f6d2d404e51fe5
    https://github.com/scummvm/scummvm/commit/091c4dea00ef81a3591144cc37f6d2d404e51fe5
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:06+02:00

Commit Message:
NANCY: NANCY29: Add the new sound channels

Nancy29 has 32 sound channels: a new music channel for the medley,
which AllExceptTheme leaves alone as well as the theme, and a ninth
effects channel. The channels after them move up, so a Sound record
without a channel plays on channel 12, which is FX1 now.

Changed paths:
    engines/nancy/nancy.cpp
    engines/nancy/script/gameapi.cpp
    engines/nancy/script/records.cpp


diff --git a/engines/nancy/nancy.cpp b/engines/nancy/nancy.cpp
index 19e772a0e9d..0e08c43a770 100644
--- a/engines/nancy/nancy.cpp
+++ b/engines/nancy/nancy.cpp
@@ -1267,6 +1267,15 @@ void NancyEngine::populateStaticData() {
 		sci.sfxChannels = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 };
 		sci.speechChannels = { 26, 27, 28, 29 };
 	}
+
+	if (getGameType() >= kGameTypeNancy29) {
+		// Nancy29 has four music channels, eight for ambience, sixteen for
+		// effects and four for voices
+		sci.numChannels = 32;
+		sci.musicChannels = { 0, 1, 2, 3 };
+		sci.sfxChannels = { 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 };
+		sci.speechChannels = { 28, 29, 30, 31 };
+	}
 }
 
 Common::Error NancyEngine::synchronize(Common::Serializer &ser) {
diff --git a/engines/nancy/script/gameapi.cpp b/engines/nancy/script/gameapi.cpp
index abe26029e61..3e544618344 100644
--- a/engines/nancy/script/gameapi.cpp
+++ b/engines/nancy/script/gameapi.cpp
@@ -1084,6 +1084,7 @@ static const char *const kSoundChannelType = "ND.SoundChannel";
 
 enum SoundChannelID {
 	kNumSoundChannels		= 30,
+	kNancy29NumSoundChannels	= 32,
 
 	// These stand for every channel of a kind
 	kChannelAll				= 0x21,
@@ -1153,8 +1154,22 @@ static const SoundChannelName kNancy27SoundChannelNames[] = {
 	{ "AllFX", kChannelAllFX }, { "AllAmbient", kChannelAllAmbient }, { "AllVoice", kChannelAllVoice }
 };
 
+// Nancy29 adds a channel for music, the medley, which AllExceptTheme leaves
+// alone as well, and a ninth one for effects
+static const SoundChannelName kNancy29SoundChannelNames[] = {
+	{ "Theme", 0 }, { "Medley", 1 }, { "UIMusic", 2 }, { "EngineMusic", 3 },
+	{ "Ambient1", 4 }, { "Ambient2", 5 }, { "Ambient3", 6 }, { "Ambient4", 7 },
+	{ "Ambient5", 8 }, { "Ambient6", 9 }, { "Ambient7", 10 }, { "Ambient8", 11 },
+	{ "FX1", 12 }, { "FX2", 13 }, { "FX3", 14 }, { "FX4", 15 }, { "FX5", 16 }, { "FX6", 17 }, { "FX7", 18 }, { "FX8", 19 }, { "FX9", 20 },
+	{ "InvFX", 21 }, { "PhoneFX", 22 }, { "PhoneFX2", 23 }, { "PhoneFX3", 24 }, { "PhoneFX4", 25 }, { "UIFX", 26 }, { "EngineFX", 27 },
+	{ "NPCVoice", 28 }, { "PlayerVoice", 29 }, { "UIVoice", 30 }, { "EngineVoice", 31 },
+	{ "All", kChannelAll }, { "AllExceptTheme", kChannelAllExceptTheme }, { "AllMusic", kChannelAllMusic },
+	{ "AllFX", kChannelAllFX }, { "AllAmbient", kChannelAllAmbient }, { "AllVoice", kChannelAllVoice }
+};
+
 // Where the channels of each kind begin, and the end of the last kind
 struct SoundChannelLayout {
+	uint16 firstAfterTheme;	// the first one AllExceptTheme stands for
 	uint16 firstMusic;
 	uint16 firstGlobal;
 	uint16 firstAmbient;
@@ -1163,10 +1178,11 @@ struct SoundChannelLayout {
 	uint16 end;
 };
 
-static const SoundChannelLayout kSoundChannelLayout = { 0, 6, 6, 14, 24, kNumSoundChannels };
-static const SoundChannelLayout kNancy22SoundChannelLayout = { 0, 3, 8, 16, 26, kNumSoundChannels };
-static const SoundChannelLayout kNancy24SoundChannelLayout = { 0, 3, 6, 14, 26, kNumSoundChannels };
-static const SoundChannelLayout kNancy27SoundChannelLayout = { 0, 3, 3, 11, 26, kNumSoundChannels };
+static const SoundChannelLayout kSoundChannelLayout = { 1, 0, 6, 6, 14, 24, kNumSoundChannels };
+static const SoundChannelLayout kNancy22SoundChannelLayout = { 1, 0, 3, 8, 16, 26, kNumSoundChannels };
+static const SoundChannelLayout kNancy24SoundChannelLayout = { 1, 0, 3, 6, 14, 26, kNumSoundChannels };
+static const SoundChannelLayout kNancy27SoundChannelLayout = { 1, 0, 3, 3, 11, 26, kNumSoundChannels };
+static const SoundChannelLayout kNancy29SoundChannelLayout = { 2, 0, 4, 4, 12, 28, kNancy29NumSoundChannels };
 
 static const SoundChannelLayout &getSoundChannelLayout() {
 	if (g_nancy->getGameType() <= kGameTypeNancy21) {
@@ -1175,9 +1191,11 @@ static const SoundChannelLayout &getSoundChannelLayout() {
 		return kNancy22SoundChannelLayout;
 	} else if (g_nancy->getGameType() <= kGameTypeNancy26) {
 		return kNancy24SoundChannelLayout;
+	} else if (g_nancy->getGameType() <= kGameTypeNancy28) {
+		return kNancy27SoundChannelLayout;
 	}
 
-	return kNancy27SoundChannelLayout;
+	return kNancy29SoundChannelLayout;
 }
 
 void pushSoundChannel(lua_State *L, uint16 channel) {
@@ -1213,7 +1231,14 @@ bool isVoicePlaying() {
 }
 
 static bool findSoundChannel(const char *name, uint16 &result) {
-	if (g_nancy->getGameType() >= kGameTypeNancy27) {
+	if (g_nancy->getGameType() >= kGameTypeNancy29) {
+		for (const SoundChannelName &channel : kNancy29SoundChannelNames) {
+			if (scumm_stricmp(channel.name, name) == 0) {
+				result = channel.channel;
+				return true;
+			}
+		}
+	} else if (g_nancy->getGameType() >= kGameTypeNancy27) {
 		for (const SoundChannelName &channel : kNancy27SoundChannelNames) {
 			if (scumm_stricmp(channel.name, name) == 0) {
 				result = channel.channel;
@@ -1272,7 +1297,7 @@ static void getChannelRange(uint16 channel, uint16 &first, uint16 &last) {
 		last = layout.end - 1;
 		break;
 	case kChannelAllExceptTheme:
-		first = 1;
+		first = layout.firstAfterTheme;
 		last = layout.end - 1;
 		break;
 	case kChannelAllMusic:
diff --git a/engines/nancy/script/records.cpp b/engines/nancy/script/records.cpp
index e412d97ff86..fb4f78428d3 100644
--- a/engines/nancy/script/records.cpp
+++ b/engines/nancy/script/records.cpp
@@ -1952,7 +1952,9 @@ void SoundRecord::readTable(int tableIndex) {
 SoundRecord::SoundRecord(SceneContext &context) : Record(context, "ND.SoundAR") {
 	// FX1, which moves with the channel tables
 	const GameType gameType = g_nancy->getGameType();
-	if (gameType >= kGameTypeNancy27) {
+	if (gameType >= kGameTypeNancy29) {
+		_channel = 12;
+	} else if (gameType >= kGameTypeNancy27) {
 		_channel = 11;
 	} else if (gameType >= kGameTypeNancy22 && gameType <= kGameTypeNancy23) {
 		_channel = 16;


Commit: 259eb7d87464d01672cbbe09808e1799ecaeff3b
    https://github.com/scummvm/scummvm/commit/259eb7d87464d01672cbbe09808e1799ecaeff3b
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:09+02:00

Commit Message:
NANCY: NANCY29: Add the new fields of Sound records

Nancy29 replaces the channelType of Sound records with the group, and
adds a pitch and a random variance of the volume and the pitch, picked
anew for each play. A record can also play its sound with
sound:PlayInstance(), on no channel, so that the sound can play over
itself.

Changed paths:
    engines/nancy/script/records.cpp
    engines/nancy/script/records.h
    engines/nancy/sound.cpp
    engines/nancy/sound.h


diff --git a/engines/nancy/script/records.cpp b/engines/nancy/script/records.cpp
index fb4f78428d3..fa825c3f1d6 100644
--- a/engines/nancy/script/records.cpp
+++ b/engines/nancy/script/records.cpp
@@ -1926,7 +1926,8 @@ bool AnimOverlayRecord::setField(const Common::String &key) {
 void SoundRecord::readTable(int tableIndex) {
 	lua_State *L = getLua();
 
-	if (pushField(L, tableIndex, "channel")) {
+	const bool hasChannel = pushField(L, tableIndex, "channel");
+	if (hasChannel) {
 		_channel = checkSoundChannel(L, -1);
 		lua_pop(L, 1);
 	}
@@ -1935,9 +1936,20 @@ void SoundRecord::readTable(int tableIndex) {
 	readField(L, tableIndex, "loop", _isLooping);
 	readField(L, tableIndex, "useCC", _usesCaption);
 
-	lua_getfield(L, tableIndex, "channelType");
-	readChannelType(-1);
-	lua_pop(L, 1);
+	if (g_nancy->getGameType() >= kGameTypeNancy29) {
+		// Nancy29 renames channelType to group. A record that only plays
+		// instances has no channel.
+		readField(L, tableIndex, "volumeVariance", _volumeVariance);
+		readField(L, tableIndex, "pitch", _pitch);
+		readField(L, tableIndex, "pitchVariance", _pitchVariance);
+		if (!readField(L, tableIndex, "group", _group) && !hasChannel) {
+			luaL_error(L, "Sound AR must have either 'channel' or 'group' defined.");
+		}
+	} else {
+		lua_getfield(L, tableIndex, "channelType");
+		readChannelType(-1);
+		lua_pop(L, 1);
+	}
 
 	if (pushField(L, tableIndex, "sounds")) {
 		readStringList(L, -1, _names);
@@ -1947,6 +1959,8 @@ void SoundRecord::readTable(int tableIndex) {
 	if (_names.empty()) {
 		luaL_error(L, "sounds must have one or more fields in its table");
 	}
+
+	pickVariation();
 }
 
 SoundRecord::SoundRecord(SceneContext &context) : Record(context, "ND.SoundAR") {
@@ -1963,6 +1977,43 @@ SoundRecord::SoundRecord(SceneContext &context) : Record(context, "ND.SoundAR")
 	}
 }
 
+// The value, changed at random by up to the variance either way
+static double vary(double value, double variance) {
+	const double random = g_nancy->_randomSource->getRandomNumber(0xFFFF) / (double)0xFFFF;
+	return value + (random * 2.0 - 1.0) * variance;
+}
+
+void SoundRecord::pickVariation() {
+	_playVolume = CLIP(vary(_volume, _volumeVariance), 0.0, 1.0);
+	_playPitch = MAX(vary(_pitch, _pitchVariance), 0.01);
+}
+
+bool SoundRecord::getGroupType(Audio::Mixer::SoundType &type) const {
+	const Common::String &group = g_nancy->getGameType() >= kGameTypeNancy29 ? _group : _channelType;
+	if (group.equalsIgnoreCase("VOICE")) {
+		type = Audio::Mixer::kSpeechSoundType;
+	} else if (group.equalsIgnoreCase("MUSIC")) {
+		type = Audio::Mixer::kMusicSoundType;
+	} else if (group.equalsIgnoreCase("EFFECTS")) {
+		type = Audio::Mixer::kSFXSoundType;
+	} else {
+		return false;
+	}
+
+	return true;
+}
+
+void SoundRecord::playInstance() {
+	Audio::Mixer::SoundType type;
+	if (!getGroupType(type)) {
+		luaL_error(getLua(), "Sound AR cannot play an instance because its 'group' field is not a valid group");
+	}
+
+	const Common::String &name = _names[g_nancy->_randomSource->getRandomNumber(_names.size() - 1)];
+	const double volume = CLIP(vary(_volume, _volumeVariance), 0.0, 1.0);
+	g_nancy->_sound->playInstance(name, type, (uint16)(volume * 100.0), MAX(vary(_pitch, _pitchVariance), 0.01));
+}
+
 void SoundRecord::readChannelType(int index) {
 	lua_State *L = getLua();
 
@@ -2025,29 +2076,34 @@ void SoundRecord::runOnce() {
 		return;
 	}
 
+	// Nancy29 varies the volume and the pitch from play to play
+	const bool isVaried = g_nancy->getGameType() >= kGameTypeNancy29;
+
 	_sound = SoundDescription();
 	_sound.name = _names[g_nancy->_randomSource->getRandomNumber(_names.size() - 1)];
 	_sound.channelID = _channel;
 	_sound.numLoops = _isLooping ? 0 : 1;
-	_sound.volume = (uint16)CLIP<int>((int)(_volume * 100.0), 0, 100);
+	_sound.volume = (uint16)CLIP<int>((int)((isVaried ? _playVolume : _volume) * 100.0), 0, 100);
 
 	g_nancy->_sound->loadSound(_sound);
-	if (_channelType == "VOICE") {
-		g_nancy->_sound->playSound(_channel, Audio::Mixer::kSpeechSoundType);
-	} else if (_channelType == "MUSIC") {
-		g_nancy->_sound->playSound(_channel, Audio::Mixer::kMusicSoundType);
-	} else if (_channelType == "EFFECTS") {
-		g_nancy->_sound->playSound(_channel, Audio::Mixer::kSFXSoundType);
+	Audio::Mixer::SoundType type;
+	if (getGroupType(type)) {
+		g_nancy->_sound->playSound(_channel, type);
 	} else {
 		g_nancy->_sound->playSound(_sound);
 	}
 
+	const double pitch = isVaried ? _playPitch : 1.0;
+	if (pitch != 1.0) {
+		g_nancy->_sound->setRate(_channel, (uint32)(g_nancy->_sound->getBaseRate(_channel) * pitch));
+	}
+
 	_isPlaying = g_nancy->_sound->isSoundPlaying(_sound);
 	_wasPreempted = false;
 	_channelSerial = g_nancy->_sound->getChannelSerial(_channel);
 
 	// The record is done once the sound has played through, whether it loops or not
-	_duration = _isPlaying ? g_nancy->_sound->getLength(_sound).msecs() / 1000.0 : 0.0;
+	_duration = _isPlaying ? g_nancy->_sound->getLength(_sound).msecs() / 1000.0 / pitch : 0.0;
 	_endTime = getContext().getTime() + _duration;
 
 #ifdef ENABLE_NANCY_V5
@@ -2117,6 +2173,7 @@ bool SoundRecord::prepareReset() {
 	_endTime = 0.0;
 	_wasPreempted = false;
 	_isPlaying = false;
+	pickVariation();
 	return true;
 }
 
@@ -2131,8 +2188,18 @@ bool SoundRecord::setField(const Common::String &key) {
 		}
 
 		_channel = checkSoundChannel(L, 3);
-	} else if (key == "channelType") {
+	} else if (key == "channelType" && g_nancy->getGameType() < kGameTypeNancy29) {
 		readChannelType(3);
+	} else if (key == "group") {
+		_group = lua_isnil(L, 3) ? Common::String() : Common::String(luaL_checkstring(L, 3));
+	} else if (key == "volumeVariance") {
+		_volumeVariance = luaL_checknumber(L, 3);
+	} else if (key == "pitch") {
+		_pitch = luaL_checknumber(L, 3);
+	} else if (key == "pitchVariance") {
+		_pitchVariance = luaL_checknumber(L, 3);
+	} else if (key == "PlayInstance") {
+		luaL_error(L, "Field 'PlayInstance' of sound AR is not settable");
 	} else if (key == "volume") {
 		_volume = luaL_checknumber(L, 3);
 	} else if (key == "useCC") {
@@ -2169,6 +2236,12 @@ bool SoundRecord::getPlayingChannel(uint16 &channel) const {
 	return true;
 }
 
+// sound:PlayInstance(), Nancy29
+static int soundPlayInstance(lua_State *L) {
+	((SoundRecord *)checkRecord(L, 1))->playInstance();
+	return 0;
+}
+
 void SoundRecord::stopIfPlaying() {
 	if (_isPlaying && g_nancy->_sound->getChannelSerial(_channel) == _channelSerial) {
 		g_nancy->_sound->stopSound(_sound);
@@ -2182,8 +2255,22 @@ bool SoundRecord::getField(const Common::String &key) {
 		lua_pushcfunction(L, soundStopIfPlaying);
 	} else if (key == "channel") {
 		pushSoundChannel(L, _channel);
-	} else if (key == "channelType") {
+	} else if (key == "channelType" && g_nancy->getGameType() < kGameTypeNancy29) {
 		lua_pushstring(L, getChannelType());
+	} else if (key == "PlayInstance") {
+		lua_pushcfunction(L, soundPlayInstance);
+	} else if (key == "group") {
+		if (_group.empty()) {
+			lua_pushnil(L);
+		} else {
+			lua_pushstring(L, _group.c_str());
+		}
+	} else if (key == "volumeVariance") {
+		lua_pushnumber(L, _volumeVariance);
+	} else if (key == "pitch") {
+		lua_pushnumber(L, _pitch);
+	} else if (key == "pitchVariance") {
+		lua_pushnumber(L, _pitchVariance);
 	} else if (key == "volume") {
 		lua_pushnumber(L, _volume);
 	} else if (key == "loop") {
diff --git a/engines/nancy/script/records.h b/engines/nancy/script/records.h
index 7942b88796e..c29ba4f8417 100644
--- a/engines/nancy/script/records.h
+++ b/engines/nancy/script/records.h
@@ -26,6 +26,8 @@
 #include "common/ptr.h"
 #include "common/rect.h"
 
+#include "audio/mixer.h"
+
 #include "engines/nancy/commontypes.h"
 #include "engines/nancy/movieplayer.h"
 #include "engines/nancy/renderobject.h"
@@ -381,6 +383,10 @@ public:
 	// The channel the sound of the record plays on, while it does
 	bool getPlayingChannel(uint16 &channel) const;
 
+	// Nancy29: plays one of the sounds once, without a channel, so that it can
+	// overlap other sounds. The group of the record selects its volume setting.
+	void playInstance();
+
 protected:
 	void readTable(int tableIndex) override;
 	void runOnce() override;
@@ -400,10 +406,24 @@ private:
 #endif
 	const char *getChannelType() const;
 
+	// The volume setting that the group or the channelType selects. Returns
+	// false when the sound uses the setting of its channel.
+	bool getGroupType(Audio::Mixer::SoundType &type) const;
+
+	// Nancy29: picks the volume and the pitch of the next play, each one changed
+	// at random by up to its variance
+	void pickVariation();
+
 	Common::Array<Common::String> _names;
 	uint16 _channel;	// FX1 unless the table says otherwise
 	Common::String _channelType;	// empty for the one of the channel
+	Common::String _group;			// Nancy29: "Voice", "Music" or "Effects"
 	double _volume = 1.0;
+	double _volumeVariance = 0.0;	// Nancy29
+	double _pitch = 1.0;			// Nancy29: 2 plays twice as fast
+	double _pitchVariance = 0.0;
+	double _playVolume = 1.0;
+	double _playPitch = 1.0;
 	bool _isLooping = false;
 	bool _usesCaption = true;
 
diff --git a/engines/nancy/sound.cpp b/engines/nancy/sound.cpp
index 234bf20d260..b7aa846ecdc 100644
--- a/engines/nancy/sound.cpp
+++ b/engines/nancy/sound.cpp
@@ -577,6 +577,12 @@ void SoundManager::stopAllSounds() {
 	for (uint i = 0; i < _channels.size(); ++i) {
 		stopSound(i);
 	}
+
+	for (Audio::SoundHandle &handle : _instances) {
+		_mixer->stopHandle(handle);
+	}
+
+	_instances.clear();
 }
 
 byte SoundManager::getVolume(uint16 channelID) {
@@ -759,6 +765,33 @@ Audio::Timestamp SoundManager::getLength(const Common::String &chunkName) {
 	return getLength(_commonSounds[chunkName]);
 }
 
+void SoundManager::playInstance(const Common::String &soundName, Audio::Mixer::SoundType type, uint16 volume, double pitch) {
+	for (uint i = 0; i < _instances.size(); ) {
+		if (_mixer->isSoundHandleActive(_instances[i])) {
+			++i;
+		} else {
+			_instances.remove_at(i);
+		}
+	}
+
+	Common::SeekableReadStream *file = SearchMan.createReadStreamForMember(Common::Path(soundName + ".his"));
+	if (!file) {
+		warning("Sound %s file failed to open", soundName.c_str());
+		return;
+	}
+
+	Audio::SeekableAudioStream *stream = makeHISStream(file, DisposeAfterUse::YES);
+	if (!stream) {
+		return;
+	}
+
+	const uint32 rate = stream->getRate();
+	Audio::SoundHandle handle;
+	_mixer->playStream(type, &handle, stream, -1, (int)getAdjustedVolume(volume) * 255 / 100, 0, DisposeAfterUse::YES);
+	_mixer->setChannelRate(handle, (uint32)(rate * pitch));
+	_instances.push_back(handle);
+}
+
 Audio::Timestamp SoundManager::getFileLength(const Common::String &soundName) {
 	if (soundName == "silence") {
 		return Audio::Timestamp();
diff --git a/engines/nancy/sound.h b/engines/nancy/sound.h
index c9564cf0809..bd8fd686ceb 100644
--- a/engines/nancy/sound.h
+++ b/engines/nancy/sound.h
@@ -129,6 +129,11 @@ public:
 	void setRate(const SoundDescription &description, uint32 rate);
 	void setRate(const Common::String &chunkName, uint32 rate);
 
+	// Nancy29: plays a sound once, without a channel, so that several copies of
+	// it can overlap. The volume goes from 0 to 100, and a pitch of 2 plays the
+	// sound twice as fast.
+	void playInstance(const Common::String &soundName, Audio::Mixer::SoundType type, uint16 volume, double pitch);
+
 	Audio::Timestamp getLength(uint16 channelID);
 	Audio::Timestamp getLength(const SoundDescription &description);
 	Audio::Timestamp getLength(const Common::String &chunkName);
@@ -192,6 +197,7 @@ protected:
 
 	Common::Array<Channel> _channels;
 	Common::HashMap<Common::String, SoundDescription> _commonSounds;
+	Common::Array<Audio::SoundHandle> _instances;	// Nancy29: the sounds started by playInstance()
 
 	bool _shouldRecalculate;
 


Commit: 8326519054d09e2bc6521a75c895be1bba3692ea
    https://github.com/scummvm/scummvm/commit/8326519054d09e2bc6521a75c895be1bba3692ea
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:10+02:00

Commit Message:
NANCY: NANCY29: Let Inventory:Add put an item in front of the others

Nancy29 scripts can add an item at the "beginning" or the "end" of the
inventory.

Changed paths:
    engines/nancy/script/v5/gamefunctions.cpp
    engines/nancy/state/scene.cpp
    engines/nancy/state/scene.h


diff --git a/engines/nancy/script/v5/gamefunctions.cpp b/engines/nancy/script/v5/gamefunctions.cpp
index 2ce4f013229..6f837590eaf 100644
--- a/engines/nancy/script/v5/gamefunctions.cpp
+++ b/engines/nancy/script/v5/gamefunctions.cpp
@@ -539,10 +539,22 @@ static const INVD::Item &checkItem(lua_State *L, int index) {
 	return *item;
 }
 
+// Inventory:Add(name), and in Nancy29 Inventory:Add(name, "end" or "beginning")
 static int inventoryAdd(lua_State *L) {
 	const INVD::Item &item = checkItem(L, 2);
+
+	bool isAddedToFront = false;
+	if (g_nancy->getGameType() >= kGameTypeNancy29 && lua_gettop(L) >= 3) {
+		const Common::String where = luaL_checkstring(L, 3);
+		if (where == "beginning") {
+			isAddedToFront = true;
+		} else if (where != "end") {
+			return luaL_error(L, "Inventory:Add second parameter, if specified, is expected to be \"end\" or \"beginning\"");
+		}
+	}
+
 	if (!NancySceneState.hasItem(item.id)) {
-		NancySceneState.addItemToInventory(item.id);
+		NancySceneState.addItemToInventory(item.id, isAddedToFront);
 	}
 
 	return 0;
diff --git a/engines/nancy/state/scene.cpp b/engines/nancy/state/scene.cpp
index b299b4e1ca8..ec0ca2c9121 100644
--- a/engines/nancy/state/scene.cpp
+++ b/engines/nancy/state/scene.cpp
@@ -522,7 +522,7 @@ byte Scene::getPlayerTOD() const {
 	}
 }
 
-void Scene::addItemToInventory(int16 id) {
+void Scene::addItemToInventory(int16 id, bool isAddedToFront) {
 	if (id == -1) {
 		return;
 	}
@@ -564,7 +564,7 @@ void Scene::addItemToInventory(int16 id) {
 					break;
 				}
 			}
-			if (addToBack) {
+			if (addToBack && !isAddedToFront) {
 				order.push_back(id);
 			} else {
 				order.insert_at(0, id);
diff --git a/engines/nancy/state/scene.h b/engines/nancy/state/scene.h
index ce79bb8cffd..10b9081fd5d 100644
--- a/engines/nancy/state/scene.h
+++ b/engines/nancy/state/scene.h
@@ -208,7 +208,8 @@ public:
 	void requestSleep() { _timers.sleepRequested = true; }
 	void setPlayerDay(int16 day);
 
-	void addItemToInventory(int16 id);
+	// Nancy29 scripts can put an item in front of the others
+	void addItemToInventory(int16 id, bool isAddedToFront = false);
 
 	// Nancy10 and up: the items, in the order the inventory shows them
 	const Common::Array<int16> &getInventoryOrder() { return _inventoryBox.getOrder(); }


Commit: 8cb320cc42ae5d17711113bd8a0915ee6f851d58
    https://github.com/scummvm/scummvm/commit/8cb320cc42ae5d17711113bd8a0915ee6f851d58
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:12+02:00

Commit Message:
NANCY: NANCY29: Add the items the player wears on the face

Nancy29 items are used either in the hand or on the face, like Nancy's
glasses. The scripts set and read the item on the face with
Inventory.onFace, which is stored in saved games. The Brain flags of an
item can force it in place or disable it, and are checked every frame.
Inventory:EquipPoint, Inventory:IsEquipped and Inventory:IsEnabled give
the scripts this information.

Changed paths:
    engines/nancy/enginedata.h
    engines/nancy/puzzledata.cpp
    engines/nancy/puzzledata.h
    engines/nancy/script/v5/bootobjects.cpp
    engines/nancy/script/v5/gamefunctions.cpp
    engines/nancy/script/v5/gamefunctions.h
    engines/nancy/state/scene.cpp


diff --git a/engines/nancy/enginedata.h b/engines/nancy/enginedata.h
index 23edc766dba..cfe80f88a86 100644
--- a/engines/nancy/enginedata.h
+++ b/engines/nancy/enginedata.h
@@ -973,6 +973,12 @@ struct INVD : public EngineData {
 		int16 valueIndex = 0;
 		Common::String valueName;	// Nancy19+ names the value instead
 		Common::Rect sourceRect;
+
+		// Nancy29: where the player uses the item ("hand" or "face"), and the
+		// Brain flags that force it there or disable it
+		Common::String equipPoint;
+		Common::String forceOnFlag;
+		Common::String forceOffFlag;
 	};
 
 	INVD() {}
diff --git a/engines/nancy/puzzledata.cpp b/engines/nancy/puzzledata.cpp
index f10923b8f68..c423a75abdd 100644
--- a/engines/nancy/puzzledata.cpp
+++ b/engines/nancy/puzzledata.cpp
@@ -1112,6 +1112,10 @@ void BrainData::synchronize(Common::Serializer &ser) {
 	}
 }
 
+void EquippedItemData::synchronize(Common::Serializer &ser) {
+	ser.syncString(faceItem);
+}
+
 void ScriptPictureData::synchronize(Common::Serializer &ser) {
 	uint16 numPictures = pictures.size();
 	ser.syncAsUint16LE(numPictures);
@@ -1190,6 +1194,8 @@ PuzzleData *makePuzzleData(const uint32 tag) {
 		return new ScriptJournalData();
 	case BrainData::getTag():
 		return new BrainData();
+	case EquippedItemData::getTag():
+		return new EquippedItemData();
 	case ScriptPictureData::getTag():
 		return new ScriptPictureData();
 	case StreamData::getTag():
diff --git a/engines/nancy/puzzledata.h b/engines/nancy/puzzledata.h
index 25a721bec2b..763ce48f246 100644
--- a/engines/nancy/puzzledata.h
+++ b/engines/nancy/puzzledata.h
@@ -753,6 +753,15 @@ struct BrainData : public PuzzleData {
 	Common::HashMap<Common::String, bool, Common::IgnoreCase_Hash, Common::IgnoreCase_EqualTo> results;
 };
 
+// Nancy29: the inventory item the player wears on the face, like Nancy's
+// glasses. Empty when there is none.
+struct EquippedItemData : public PuzzleData {
+	static constexpr uint32 getTag() { return MKTAG('E', 'Q', 'I', 'P'); }
+	virtual void synchronize(Common::Serializer &ser);
+
+	Common::String faceItem;
+};
+
 // Nancy21. The pictures the camera of the cell phone took, as PNG files, which
 // the scripts show from the "LOADSAVE" tree
 struct ScriptPictureData : public PuzzleData {
diff --git a/engines/nancy/script/v5/bootobjects.cpp b/engines/nancy/script/v5/bootobjects.cpp
index a8156e4b15c..50f73d4638e 100644
--- a/engines/nancy/script/v5/bootobjects.cpp
+++ b/engines/nancy/script/v5/bootobjects.cpp
@@ -35,6 +35,25 @@
 namespace Nancy {
 namespace Script {
 
+// Nancy29 gives every item a table with where the player uses it ("hand" or
+// "face"), and the Brain flags that force it there or disable it
+static void readNancy29Item(lua_State *L, const Common::String &name, INVD::Item &item) {
+	lua_getfield(L, 2, name.c_str());
+	const int itemTable = lua_gettop(L);
+	luaL_checktype(L, itemTable, LUA_TTABLE);
+
+	readField(L, itemTable, "equipPoint", item.equipPoint);
+	if (item.equipPoint != "hand" && item.equipPoint != "face") {
+		luaL_error(L, "Item %s has unknown equip point %s", name.c_str(), item.equipPoint.c_str());
+	}
+
+	readField(L, itemTable, "forceOnFlag", item.forceOnFlag);
+	readField(L, itemTable, "forceOffFlag", item.forceOffFlag);
+	item.kind = UI::NDUI::InvButton::kItemPickUp;
+
+	lua_pop(L, 1);
+}
+
 // Nancy26 gives every item the scene that shows it, or nothing. The pictures
 // of the items are cursors.
 int createNancy26Inventory(lua_State *L, INVD &inventory) {
@@ -46,10 +65,14 @@ int createNancy26Inventory(lua_State *L, INVD &inventory) {
 		item.id = (int16)inventory.items.size();
 		item.name = name;
 
-		Common::String sceneName;
-		readField(L, 2, name.c_str(), sceneName);
-		item.sceneName = Common::Path(sceneName);
-		item.kind = sceneName.empty() ? UI::NDUI::InvButton::kItemPickUp : UI::NDUI::InvButton::kItemView;
+		if (g_nancy->getGameType() >= kGameTypeNancy29) {
+			readNancy29Item(L, name, item);
+		} else {
+			Common::String sceneName;
+			readField(L, 2, name.c_str(), sceneName);
+			item.sceneName = Common::Path(sceneName);
+			item.kind = sceneName.empty() ? UI::NDUI::InvButton::kItemPickUp : UI::NDUI::InvButton::kItemView;
+		}
 
 		inventory.items.push_back(item);
 	}
diff --git a/engines/nancy/script/v5/gamefunctions.cpp b/engines/nancy/script/v5/gamefunctions.cpp
index 6f837590eaf..87a45d981b6 100644
--- a/engines/nancy/script/v5/gamefunctions.cpp
+++ b/engines/nancy/script/v5/gamefunctions.cpp
@@ -34,6 +34,7 @@
 #include "engines/nancy/enginedata.h"
 #include "engines/nancy/graphics.h"
 #include "engines/nancy/nancy.h"
+#include "engines/nancy/puzzledata.h"
 #include "engines/nancy/sound.h"
 
 #include "engines/nancy/resource/resource.h"
@@ -539,6 +540,124 @@ static const INVD::Item &checkItem(lua_State *L, int index) {
 	return *item;
 }
 
+// Nancy29: the player uses an item either in the hand or on the face. An item
+// can only be equipped if it is in the inventory, belongs to that place and is
+// enabled. A place can't change while its item is forced there by a Brain flag.
+
+enum EquipPoint {
+	kEquipHand,
+	kEquipFace
+};
+
+static const char *const kEquipPointNames[] = { "hand", "face" };
+
+static EquippedItemData &getEquippedItems() {
+	return *(EquippedItemData *)NancySceneState.getPuzzleData(EquippedItemData::getTag());
+}
+
+static bool isItemEnabled(int16 id) {
+	const Common::Array<bool> &isEnabled = getGameState().isItemEnabled;
+	return id < 0 || (uint)id >= isEnabled.size() || isEnabled[id];
+}
+
+static bool isItemForcedOn(int16 id) {
+	const Common::Array<bool> &isForcedOn = getGameState().isItemForcedOn;
+	return id >= 0 && (uint)id < isForcedOn.size() && isForcedOn[id];
+}
+
+static int16 getEquippedItem(EquipPoint point) {
+	if (point == kEquipHand) {
+		return NancySceneState.getHeldItem();
+	}
+
+	const INVD::Item *item = findItem(getEquippedItems().faceItem);
+	return item ? item->id : -1;
+}
+
+// Returns whether the item ended up there. An id of -1 removes the item that
+// is there.
+static bool setEquippedItem(EquipPoint point, int16 id) {
+	const int16 current = getEquippedItem(point);
+	if (id == current) {
+		return true;
+	}
+
+	if (current != -1 && isItemForcedOn(current)) {
+		return false;
+	}
+
+	const INVD *inventory = GetEngineData(INVD);
+	if (id != -1 && (!inventory || NancySceneState.hasItem(id) != g_nancy->_true || !isItemEnabled(id) ||
+			inventory->items[id].equipPoint != kEquipPointNames[point])) {
+		return false;
+	}
+
+	if (point == kEquipHand) {
+		NancySceneState.setHeldItem(id);
+	} else {
+		getEquippedItems().faceItem = id == -1 ? Common::String() : inventory->items[id].name;
+		++getGameState().faceItemChangeCount;
+	}
+
+	return true;
+}
+
+void updateEquippedItems() {
+	const INVD *inventory = GetEngineData(INVD);
+	BrainLogic *brain = (BrainLogic *)const_cast<EngineData *>(g_nancy->getEngineData("BrainLogic"));
+	if (!inventory || !brain) {
+		return;
+	}
+
+	ScriptGameState &state = getGameState();
+	state.isItemEnabled.resize(inventory->items.size(), true);
+	state.isItemForcedOn.resize(inventory->items.size(), false);
+
+	const Common::Array<int16> order = NancySceneState.getInventoryOrder();
+	for (int16 id : order) {
+		const INVD::Item &item = inventory->items[id];
+		if (!item.forceOnFlag.empty()) {
+			state.isItemForcedOn[id] = brain->getValue(item.forceOnFlag);
+		}
+
+		bool isForcedOff = false;
+		if (!item.forceOffFlag.empty()) {
+			isForcedOff = brain->getValue(item.forceOffFlag);
+		}
+
+		if (state.isItemForcedOn[id] && isForcedOff) {
+			warning("Force on flag %s and force off flag %s are both true at the same time",
+				item.forceOnFlag.c_str(), item.forceOffFlag.c_str());
+		}
+
+		state.isItemEnabled[id] = !isForcedOff;
+	}
+
+	// Remove items that have been disabled, and equip items that are forced
+	// in place
+	for (uint point = kEquipHand; point <= kEquipFace; ++point) {
+		const int16 current = getEquippedItem((EquipPoint)point);
+		if (current != -1 && !isItemEnabled(current)) {
+			setEquippedItem((EquipPoint)point, -1);
+		}
+
+		int16 forced = -1;
+		for (int16 id : order) {
+			if (!isItemForcedOn(id) || inventory->items[id].equipPoint != kEquipPointNames[point]) {
+				continue;
+			}
+
+			if (forced != -1) {
+				warning("Forcing item %s on %s when item %s is already forced there", inventory->items[id].name.c_str(),
+					kEquipPointNames[point], inventory->items[forced].name.c_str());
+			}
+
+			setEquippedItem((EquipPoint)point, id);
+			forced = id;
+		}
+	}
+}
+
 // Inventory:Add(name), and in Nancy29 Inventory:Add(name, "end" or "beginning")
 static int inventoryAdd(lua_State *L) {
 	const INVD::Item &item = checkItem(L, 2);
@@ -562,7 +681,13 @@ static int inventoryAdd(lua_State *L) {
 
 static int inventoryRemove(lua_State *L) {
 	const INVD::Item &item = checkItem(L, 2);
-	if (NancySceneState.getHeldItem() == item.id) {
+	if (g_nancy->getGameType() >= kGameTypeNancy29) {
+		for (uint point = kEquipHand; point <= kEquipFace; ++point) {
+			if (getEquippedItem((EquipPoint)point) == item.id) {
+				setEquippedItem((EquipPoint)point, -1);
+			}
+		}
+	} else if (NancySceneState.getHeldItem() == item.id) {
 		NancySceneState.setHeldItem(-1);
 	}
 
@@ -620,6 +745,30 @@ static int inventoryAll(lua_State *L) {
 	return 1;
 }
 
+// Inventory:EquipPoint(name), Nancy29: "hand" or "face", or "" for an
+// unknown item
+static int inventoryEquipPoint(lua_State *L) {
+	const INVD::Item *item = findItem(luaL_checkstring(L, 2));
+	lua_pushstring(L, item ? item->equipPoint.c_str() : "");
+	return 1;
+}
+
+// Inventory:IsEquipped(name), Nancy29: whether the item is in the hand or on
+// the face
+static int inventoryIsEquipped(lua_State *L) {
+	const INVD::Item *item = findItem(luaL_checkstring(L, 2));
+	lua_pushboolean(L, item && (getEquippedItem(kEquipHand) == item->id || getEquippedItem(kEquipFace) == item->id));
+	return 1;
+}
+
+// Inventory:IsEnabled(name), Nancy29: whether the item can be used, i.e. its
+// Brain flag doesn't disable it
+static int inventoryIsEnabled(lua_State *L) {
+	const INVD::Item *item = findItem(luaL_checkstring(L, 2));
+	lua_pushboolean(L, item && isItemEnabled(item->id));
+	return 1;
+}
+
 static const luaL_Reg kInventoryFunctions[] = {
 	{ "Add", inventoryAdd },
 	{ "Remove", inventoryRemove },
@@ -629,6 +778,9 @@ static const luaL_Reg kInventoryFunctions[] = {
 	{ "IsViewable", inventoryIsViewable },
 	{ "Scene", inventoryScene },
 	{ "All", inventoryAll },
+	{ "EquipPoint", inventoryEquipPoint },
+	{ "IsEquipped", inventoryIsEquipped },
+	{ "IsEnabled", inventoryIsEnabled },
 	{ nullptr, nullptr }
 };
 
@@ -664,6 +816,11 @@ static bool pushInventoryField(lua_State *L, const Common::String &key) {
 		lua_pushinteger(L, NancySceneState.getInventoryChangeCount());
 	} else if (key == "inHandChangeCount") {
 		lua_pushinteger(L, NancySceneState.getHeldItemChangeCount());
+	} else if (key == "onFace") {
+		// Nancy29
+		pushItemName(L, getEquippedItems().faceItem);
+	} else if (key == "onFaceChangeCount") {
+		lua_pushinteger(L, getGameState().faceItemChangeCount);
 	} else {
 		return false;
 	}
@@ -673,8 +830,20 @@ static bool pushInventoryField(lua_State *L, const Common::String &key) {
 
 // Inventory.inHand = name, or "" to put it away. Nancy27 also puts it away
 // with nil.
+// Nancy29 also sets Inventory.onFace. Both ignore an item that can't go there,
+// and the scripts check this by reading the value back.
 static int inventoryNewIndex(lua_State *L) {
 	const Common::String key = luaL_checkstring(L, 2);
+	if (g_nancy->getGameType() >= kGameTypeNancy29 && (key == "inHand" || key == "onFace")) {
+		const Common::String name = lua_isnil(L, 3) ? "" : luaL_checkstring(L, 3);
+		const INVD::Item *item = findItem(name);
+		if (name.empty() || item) {
+			setEquippedItem(key == "inHand" ? kEquipHand : kEquipFace, item ? item->id : -1);
+		}
+
+		return 0;
+	}
+
 	if (key != "inHand") {
 		return luaL_error(L, "Inventory does not have a settable field %s", key.c_str());
 	}
diff --git a/engines/nancy/script/v5/gamefunctions.h b/engines/nancy/script/v5/gamefunctions.h
index 57579b74aaf..24b97c36fb3 100644
--- a/engines/nancy/script/v5/gamefunctions.h
+++ b/engines/nancy/script/v5/gamefunctions.h
@@ -61,8 +61,19 @@ struct ScriptGameState : public EngineData {
 	// gives once
 	Common::Array<Common::String> achievementIds;
 	bool hasAchievementIds = false;
+
+	// Nancy29, indexed by item id: whether each item is enabled, and whether
+	// its Brain flag forces it in the hand or on the face. The item worn on
+	// the face is stored in the EquippedItemData of the scene.
+	Common::Array<bool> isItemEnabled;
+	Common::Array<bool> isItemForcedOn;
+	uint faceItemChangeCount = 0;
 };
 
+// Nancy29: applies the Brain flags of the inventory items, which equip them
+// in the hand or on the face, or remove them from there. Called every frame.
+void updateEquippedItems();
+
 // What Nancy26 adds to the objects of the earlier games: the saved games and
 // settings in Game, the inventory by the names of the items, Flags:All(),
 // Key:IsDown(), the volume of the groups of sounds and more. Fields that mean
diff --git a/engines/nancy/state/scene.cpp b/engines/nancy/state/scene.cpp
index ec0ca2c9121..1ffb7060242 100644
--- a/engines/nancy/state/scene.cpp
+++ b/engines/nancy/state/scene.cpp
@@ -54,6 +54,9 @@
 #include "engines/nancy/script/records.h"
 #include "engines/nancy/script/scenecontext.h"
 #endif
+#ifdef ENABLE_NANCY_V5
+#include "engines/nancy/script/v5/gamefunctions.h"
+#endif
 
 namespace Common {
 DECLARE_SINGLETON(Nancy::State::Scene);
@@ -2473,6 +2476,12 @@ void Scene::run() {
 		return;
 	}
 
+#ifdef ENABLE_NANCY_V5
+	if (g_nancy->getGameType() >= kGameTypeNancy29) {
+		Script::updateEquippedItems();
+	}
+#endif
+
 	_streams.process();
 
 	// The scenes of a loaded game have all started by now


Commit: 93a138218f31229f07f2b1f8d903d0ef0e88af64
    https://github.com/scummvm/scummvm/commit/93a138218f31229f07f2b1f8d903d0ef0e88af64
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:20+02:00

Commit Message:
NANCY: NANCY29: Add the OverlayCombiner record

It shows the colors of a part of one image with the transparency of a
part of another, e.g. a photo cut to the shape of a frame.

Changed paths:
  A engines/nancy/script/v5/overlaycombiner.cpp
  A engines/nancy/script/v5/overlaycombiner.h
    engines/nancy/module.mk
    engines/nancy/script/record.h
    engines/nancy/script/records.cpp
    engines/nancy/script/records.h


diff --git a/engines/nancy/module.mk b/engines/nancy/module.mk
index 5d3cb646956..84a07e21b70 100644
--- a/engines/nancy/module.mk
+++ b/engines/nancy/module.mk
@@ -246,6 +246,7 @@ MODULE_OBJS += \
   script/v5/cliptransformer.o \
   script/v5/gamefunctions.o \
   script/v5/messaging.o \
+  script/v5/overlaycombiner.o \
   script/v5/recordnode.o \
   script/v5/scriptinput.o \
   script/v5/streamtree.o \
diff --git a/engines/nancy/script/record.h b/engines/nancy/script/record.h
index a7919c9d92d..210f07f8858 100644
--- a/engines/nancy/script/record.h
+++ b/engines/nancy/script/record.h
@@ -64,8 +64,9 @@ enum RecordType {
 	kRecordRadioButton	= 19,
 	kRecordCheckBox		= 20,
 	kRecordSlider		= 21,
+	kRecordOverlayCombiner	= 22,	// Nancy29
 
-	kNumRecordTypes		= 22
+	kNumRecordTypes		= 23
 };
 
 // What the player does that records get told about
diff --git a/engines/nancy/script/records.cpp b/engines/nancy/script/records.cpp
index fa825c3f1d6..fe7ac3e1d8c 100644
--- a/engines/nancy/script/records.cpp
+++ b/engines/nancy/script/records.cpp
@@ -53,6 +53,7 @@
 #ifdef ENABLE_NANCY_V5
 #include "engines/nancy/script/v5/cliptransformer.h"
 #include "engines/nancy/script/v5/messaging.h"
+#include "engines/nancy/script/v5/overlaycombiner.h"
 #include "engines/nancy/script/v5/streamtree.h"
 #include "engines/nancy/script/v5/textrecord.h"
 #include "engines/nancy/script/v5/widgets.h"
@@ -93,7 +94,8 @@ static const RecordKindNames kRecordKindNames[kNumRecordTypes] = {
 	{ "EditBox", "ND.EditBoxAR" },
 	{ "RadioButton", "ND.RadioButton" },
 	{ "CheckBox", "ND.CheckBox" },
-	{ "Slider", "ND.Slider" }
+	{ "Slider", "ND.Slider" },
+	{ "OverlayCombiner", "ND.OverlayCombiner" }
 };
 
 const char *getRecordKindName(RecordType type) {
@@ -130,6 +132,8 @@ Record *makeRecord(RecordType type, SceneContext &context) {
 		return new SliderRecord(context);
 	case kRecordEditBox:
 		return new EditBoxRecord(context);
+	case kRecordOverlayCombiner:
+		return new OverlayCombinerRecord(context);
 #endif
 	case kRecordSummary:
 		return new SummaryRecord(context);
@@ -245,7 +249,7 @@ static const uint32 kNoModColor = 0xFFFFFFFF;
 // that turns or resizes the picture has it drawn anew, into the area its corners
 // end up around, and so does a color the picture gets multiplied with, which
 // can darken it or make it see-through.
-static void placePicture(RecordGraphic &graphic, Graphics::ManagedSurface &image, const Common::Rect &source, const ScriptRect &dest, const ScriptMatrix &transform, uint32 modColor) {
+void placePicture(RecordGraphic &graphic, Graphics::ManagedSurface &image, const Common::Rect &source, const ScriptRect &dest, const ScriptMatrix &transform, uint32 modColor) {
 	const int kLimit = 16000;
 
 	const bool isMovedOnly = transform.isTranslation();
@@ -1300,7 +1304,7 @@ bool loadTreeImage(const Common::String &name, const Common::String &treeName, G
 // Overlays get their pictures from the image cache of the resource manager,
 // and hold on to the cached picture while they use it. Saved pictures aren't
 // cached: every record has its own.
-static bool loadCachedImage(const Common::String &name, const Common::String &treeName, Common::SharedPtr<Graphics::ManagedSurface> &cached, Graphics::ManagedSurface &image) {
+bool loadCachedImage(const Common::String &name, const Common::String &treeName, Common::SharedPtr<Graphics::ManagedSurface> &cached, Graphics::ManagedSurface &image) {
 	if (treeName.equalsIgnoreCase(kPictureTreeName) || treeName.equalsIgnoreCase(kSaveFileTreeName)) {
 		image.free();
 		cached.reset();
diff --git a/engines/nancy/script/records.h b/engines/nancy/script/records.h
index c29ba4f8417..219a713a2f8 100644
--- a/engines/nancy/script/records.h
+++ b/engines/nancy/script/records.h
@@ -92,6 +92,15 @@ protected:
 	bool isViewportRelative() const override;
 };
 
+// Shows a part of an image where the record's transform places it. The part
+// is redrawn when the transform rotates or scales it, or when it is tinted.
+void placePicture(RecordGraphic &graphic, Graphics::ManagedSurface &image, const Common::Rect &source, const ScriptRect &dest, const ScriptMatrix &transform, uint32 modColor);
+
+// Gets an image from the resource manager's cache, and keeps a reference to it
+// in cached while the record uses it. Images from picture trees that aren't
+// cached are loaded directly.
+bool loadCachedImage(const Common::String &name, const Common::String &treeName, Common::SharedPtr<Graphics::ManagedSurface> &cached, Graphics::ManagedSurface &image);
+
 // The first record of every scene, which names the area the scene belongs to
 // and its background. A background with more than one frame is a node the
 // player can turn around in.
diff --git a/engines/nancy/script/v5/overlaycombiner.cpp b/engines/nancy/script/v5/overlaycombiner.cpp
new file mode 100644
index 00000000000..62cb6f83bb3
--- /dev/null
+++ b/engines/nancy/script/v5/overlaycombiner.cpp
@@ -0,0 +1,228 @@
+/* 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/textconsole.h"
+
+#include "engines/nancy/graphics.h"
+#include "engines/nancy/nancy.h"
+
+#include "engines/nancy/script/luabind.h"
+#include "engines/nancy/script/types.h"
+
+#include "engines/nancy/script/v5/overlaycombiner.h"
+
+namespace Nancy {
+namespace Script {
+
+static void readRequiredRect(lua_State *L, int tableIndex, const char *name, ScriptRect &rect) {
+	if (!pushField(L, tableIndex, name)) {
+		luaL_error(L, "OverlayCombiner ARs must have an '%s' field", name);
+	}
+
+	rect = checkRect(L, -1);
+	lua_pop(L, 1);
+}
+
+static void readRequiredName(lua_State *L, int tableIndex, const char *name, Common::String &value) {
+	if (!readField(L, tableIndex, name, value)) {
+		luaL_error(L, "OverlayCombiner ARs must have an '%s' field", name);
+	}
+}
+
+void OverlayCombinerRecord::readTable(int tableIndex) {
+	lua_State *L = getLua();
+
+	readRequiredRect(L, tableIndex, "rgbSource", _rgbSource);
+	readRequiredRect(L, tableIndex, "alphaSource", _alphaSource);
+	readRequiredRect(L, tableIndex, "onScreen", _dest);
+	readRequiredName(L, tableIndex, "rgbOvl", _rgbImageName);
+	readField(L, tableIndex, "rgbTree", _rgbTreeName);
+	readRequiredName(L, tableIndex, "alphaOvl", _alphaImageName);
+	readField(L, tableIndex, "alphaTree", _alphaTreeName);
+
+	if (pushField(L, tableIndex, "modColor")) {
+		_modColor = checkColor(L, -1) | 0xFF000000;
+		lua_pop(L, 1);
+	}
+
+	readField(L, tableIndex, "invertAlpha", _isAlphaInverted);
+
+	_graphic.init();
+	_graphic.setVisible(false);
+	onZChanged();
+	_graphic.registerGraphics();
+}
+
+// The images are only kept loaded while they are being combined
+void OverlayCombinerRecord::combine() {
+	_isCombined = true;
+	_hasPicture = false;
+	_isPlacementStale = true;
+
+	if (_rgbSource.width() != _alphaSource.width() || _rgbSource.height() != _alphaSource.height()) {
+		warning("OverlayCombiner: Sources are not the same size, RGB: %s, Alpha: %s", _rgbImageName.c_str(), _alphaImageName.c_str());
+		return;
+	}
+
+	Common::SharedPtr<Graphics::ManagedSurface> rgbCached;
+	Common::SharedPtr<Graphics::ManagedSurface> alphaCached;
+	Graphics::ManagedSurface rgbImage;
+	Graphics::ManagedSurface alphaImage;
+	if (!loadCachedImage(_rgbImageName, _rgbTreeName, rgbCached, rgbImage) ||
+			!loadCachedImage(_alphaImageName, _alphaTreeName, alphaCached, alphaImage)) {
+		warning("OverlayCombiner: Could not load %s or %s", _rgbImageName.c_str(), _alphaImageName.c_str());
+		return;
+	}
+
+	const Common::Rect rgbSource = _rgbSource.toRect();
+	const Common::Rect alphaSource = _alphaSource.toRect();
+	if (!Common::Rect(rgbImage.w, rgbImage.h).contains(rgbSource) || !Common::Rect(alphaImage.w, alphaImage.h).contains(alphaSource)) {
+		warning("OverlayCombiner: Either %s or %s were too large to lock for reading", _rgbImageName.c_str(), _alphaImageName.c_str());
+		return;
+	}
+
+	_image.create(rgbSource.width(), rgbSource.height(), g_nancy->_graphics->getTransparentPixelFormat());
+	for (int y = 0; y < _image.h; ++y) {
+		for (int x = 0; x < _image.w; ++x) {
+			byte alpha, red, green, blue;
+			rgbImage.format.colorToARGB(rgbImage.getPixel(rgbSource.left + x, rgbSource.top + y), alpha, red, green, blue);
+
+			byte maskAlpha, maskRed, maskGreen, maskBlue;
+			alphaImage.format.colorToARGB(alphaImage.getPixel(alphaSource.left + x, alphaSource.top + y), maskAlpha, maskRed, maskGreen, maskBlue);
+			if (_isAlphaInverted) {
+				maskAlpha = 255 - maskAlpha;
+			}
+
+			_image.setPixel(x, y, _image.format.ARGBToColor(alpha * maskAlpha >> 8, red, green, blue));
+		}
+	}
+
+	_hasPicture = true;
+}
+
+void OverlayCombinerRecord::place() {
+	_isPlacementStale = false;
+	_isDrawn = false;
+	if (!_hasPicture) {
+		return;
+	}
+
+	if (_dest.width() != _image.w || _dest.height() != _image.h) {
+		warning("OverlayCombiner: Source and dest are not the same size");
+		return;
+	}
+
+	placePicture(_graphic, _image, Common::Rect(_image.w, _image.h), _dest, getTransform(), takeModColor(_modColor));
+	_isDrawn = true;
+}
+
+void OverlayCombinerRecord::onTransformChanged() {
+	_isPlacementStale = true;
+}
+
+void OverlayCombinerRecord::onZChanged() {
+	_graphic.setScriptZ(getZ(), getContext());
+}
+
+void OverlayCombinerRecord::registerGraphics() {
+	_graphic.registerGraphics();
+}
+
+void OverlayCombinerRecord::updateGraphics() {
+	if (isShown()) {
+		if (!_isCombined) {
+			combine();
+		}
+
+		if (_isPlacementStale || hasAlphaChanged()) {
+			place();
+		}
+	}
+
+	_graphic.setClipRect(getScreenClip());
+	_graphic.setVisible(isShown() && _isDrawn, false);
+}
+
+bool OverlayCombinerRecord::getField(const Common::String &key) {
+	lua_State *L = getLua();
+
+	if (key == "rgbOvl") {
+		lua_pushstring(L, _rgbImageName.c_str());
+	} else if (key == "rgbTree") {
+		lua_pushstring(L, _rgbTreeName.c_str());
+	} else if (key == "rgbSource") {
+		pushRect(L, _rgbSource);
+	} else if (key == "alphaOvl") {
+		lua_pushstring(L, _alphaImageName.c_str());
+	} else if (key == "alphaTree") {
+		lua_pushstring(L, _alphaTreeName.c_str());
+	} else if (key == "alphaSource") {
+		pushRect(L, _alphaSource);
+	} else if (key == "onScreen") {
+		pushRect(L, _dest);
+	} else if (key == "invertAlpha") {
+		lua_pushboolean(L, _isAlphaInverted);
+	} else if (key == "modColor") {
+		pushColor(L, _modColor);
+	} else {
+		return false;
+	}
+
+	return true;
+}
+
+// Changing the images or their source parts combines them again. Changing
+// where or how the picture is shown places it again.
+bool OverlayCombinerRecord::setField(const Common::String &key) {
+	lua_State *L = getLua();
+
+	if (key == "rgbOvl") {
+		_rgbImageName = luaL_checkstring(L, 3);
+	} else if (key == "rgbTree") {
+		_rgbTreeName = luaL_checkstring(L, 3);
+	} else if (key == "rgbSource") {
+		_rgbSource = checkRect(L, 3);
+	} else if (key == "alphaOvl") {
+		_alphaImageName = luaL_checkstring(L, 3);
+	} else if (key == "alphaTree") {
+		_alphaTreeName = luaL_checkstring(L, 3);
+	} else if (key == "alphaSource") {
+		_alphaSource = checkRect(L, 3);
+	} else if (key == "invertAlpha") {
+		_isAlphaInverted = lua_toboolean(L, 3) != 0;
+	} else if (key == "onScreen") {
+		_dest = checkRect(L, 3);
+		_isPlacementStale = true;
+		return true;
+	} else if (key == "modColor") {
+		_modColor = checkColor(L, 3) | 0xFF000000;
+		_isPlacementStale = true;
+		return true;
+	} else {
+		return false;
+	}
+
+	_isCombined = false;
+	return true;
+}
+
+} // End of namespace Script
+} // End of namespace Nancy
diff --git a/engines/nancy/script/v5/overlaycombiner.h b/engines/nancy/script/v5/overlaycombiner.h
new file mode 100644
index 00000000000..79c71fea226
--- /dev/null
+++ b/engines/nancy/script/v5/overlaycombiner.h
@@ -0,0 +1,83 @@
+/* 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 NANCY_SCRIPT_V5_OVERLAYCOMBINER_H
+#define NANCY_SCRIPT_V5_OVERLAYCOMBINER_H
+
+#include "engines/nancy/script/records.h"
+
+namespace Nancy {
+namespace Script {
+
+// Nancy29: shows the colors of a part of one image with the transparency of a
+// part of another, e.g. a photo cut to the shape of a frame:
+//
+//   AR:OverlayCombiner({ rgbOvl = "Photo_OVL", rgbSource = Rect:New(0, 0, 100, 80),
+//       alphaOvl = "Frame_OVL", alphaSource = Rect:New(0, 0, 100, 80),
+//       onScreen = Rect:New(200, 100, 300, 180), invertAlpha = false })
+//
+// The alpha of each pixel is the alpha of the first image times the alpha of
+// the second one, or times its inverse when invertAlpha is set. Both source
+// parts and onScreen must have the same size, otherwise nothing is shown.
+class OverlayCombinerRecord : public Record {
+public:
+	OverlayCombinerRecord(SceneContext &context) : Record(context, "ND.OverlayCombiner") {}
+
+	RecordType getType() const override { return kRecordOverlayCombiner; }
+
+	void updateGraphics() override;
+	void registerGraphics() override;
+
+protected:
+	void readTable(int tableIndex) override;
+	void onZChanged() override;
+	bool hasTransform() const override { return true; }
+	void onTransformChanged() override;
+	bool getField(const Common::String &key) override;
+	bool setField(const Common::String &key) override;
+
+private:
+	// Combines the two images into the picture, after a field has changed
+	void combine();
+	void place();
+
+	Common::String _rgbImageName;
+	Common::String _rgbTreeName;
+	ScriptRect _rgbSource;
+	Common::String _alphaImageName;
+	Common::String _alphaTreeName;
+	ScriptRect _alphaSource;
+	ScriptRect _dest;
+	bool _isAlphaInverted = false;
+	uint32 _modColor = 0xFFFFFFFF;	// its alpha is always opaque
+
+	Graphics::ManagedSurface _image;	// the combined picture
+	bool _hasPicture = false;	// the images were combined successfully
+	bool _isDrawn = false;		// _hasPicture, and onScreen has the size of the picture
+	bool _isCombined = false;
+	bool _isPlacementStale = false;
+	RecordGraphic _graphic;
+};
+
+} // End of namespace Script
+} // End of namespace Nancy
+
+#endif // NANCY_SCRIPT_V5_OVERLAYCOMBINER_H


Commit: 745a500beb7cc18c31139c2f77297bab46e267ee
    https://github.com/scummvm/scummvm/commit/745a500beb7cc18c31139c2f77297bab46e267ee
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:21+02:00

Commit Message:
NANCY: NANCY29: Add the animators of records

Nancy29 moves, rotates, scales and fades every record with its animator,
which replaces the blend stages of the earlier games. An animator is a
list of stages, each with tracks for the alpha, the scale, the rotation
and the translation. Each track blends from one value to the next.

Changed paths:
  A engines/nancy/script/v5/animator.cpp
  A engines/nancy/script/v5/animator.h
    engines/nancy/module.mk
    engines/nancy/script/record.h
    engines/nancy/script/v5/gamefunctions.cpp
    engines/nancy/script/v5/recordnode.cpp
    engines/nancy/script/v5/recordnode.h


diff --git a/engines/nancy/module.mk b/engines/nancy/module.mk
index 84a07e21b70..6f900a60cec 100644
--- a/engines/nancy/module.mk
+++ b/engines/nancy/module.mk
@@ -240,6 +240,7 @@ MODULE_OBJS += \
 # Nancy26 and newer, whose UI is made of records as well
 ifdef ENABLE_NANCY_V5
 MODULE_OBJS += \
+  script/v5/animator.o \
   script/v5/bitmaptext.o \
   script/v5/bootobjects.o \
   script/v5/brain.o \
diff --git a/engines/nancy/script/record.h b/engines/nancy/script/record.h
index 210f07f8858..2ee60d84201 100644
--- a/engines/nancy/script/record.h
+++ b/engines/nancy/script/record.h
@@ -35,6 +35,7 @@ struct NancyInput;
 
 namespace Script {
 
+class Animator;
 class BlendStages;
 class GraphNode;
 class SceneContext;
@@ -254,6 +255,13 @@ public:
 	// Nancy26: the record's own transform changed, by its stages or a script
 	virtual void onLocalTransformChanged();
 
+	// Nancy29: the animator that moves, rotates, scales and fades the record,
+	// and the transform and the alpha that the record gets from it
+	Animator *getAnimator() const;
+	double getLocalAlpha() const;
+	void setAnimatedTransform(const ScriptMatrix &transform);
+	void setAnimatedAlpha(double alpha);
+
 	// Nancy26: the records the mouse can be over, which take the clicks. The
 	// point is in the coordinates of the screen. A button is 0 for the left one
 	// and 1 for the right one.
diff --git a/engines/nancy/script/v5/animator.cpp b/engines/nancy/script/v5/animator.cpp
new file mode 100644
index 00000000000..7c184977034
--- /dev/null
+++ b/engines/nancy/script/v5/animator.cpp
@@ -0,0 +1,732 @@
+/* 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/textconsole.h"
+#include "common/util.h"
+
+#include "engines/nancy/script/luabind.h"
+#include "engines/nancy/script/record.h"
+
+#include "engines/nancy/script/v5/animator.h"
+
+namespace Nancy {
+namespace Script {
+
+// A blend takes at least this long
+static const double kMinBlendTime = 0.001;
+
+// AnimatorTrack
+
+AnimatorTrack::AnimatorTrack(AnimatorStage &stage, Kind kind, double x, double y) :
+		_stage(stage),
+		_kind(kind) {
+	const double value[2] = { x, y };
+	setCurrent(value);
+}
+
+const char *AnimatorTrack::getTypeName(Kind kind) {
+	switch (kind) {
+	case kAlpha:
+		return "ND.AnimatorAlphaTrack";
+	case kScale:
+		return "ND.AnimatorScaleTrack";
+	case kRotation:
+		return "ND.AnimatorRotationTrack";
+	default:
+		return "ND.AnimatorTranslationTrack";
+	}
+}
+
+void AnimatorTrack::setCurrent(const double value[2]) {
+	_start[0] = value[0];
+	_start[1] = value[1];
+	setValue(value);
+}
+
+void AnimatorTrack::setValue(const double value[2]) {
+	_current[0] = value[0];
+	_current[1] = value[1];
+
+	_matrix = ScriptMatrix();
+	switch (_kind) {
+	case kScale:
+		_matrix.m[0][0] = value[0];
+		_matrix.m[1][1] = value[1];
+		break;
+	case kRotation:
+		// D3DXMatrixRotationZ
+		_matrix.m[0][0] = cos(value[0]);
+		_matrix.m[0][1] = sin(value[0]);
+		_matrix.m[1][0] = -sin(value[0]);
+		_matrix.m[1][1] = cos(value[0]);
+		break;
+	case kTranslation:
+		_matrix.m[3][0] = value[0];
+		_matrix.m[3][1] = value[1];
+		break;
+	default:
+		break;
+	}
+}
+
+double AnimatorTrack::getDuration() const {
+	double duration = 0.0;
+	for (const Blend &blend : _blends) {
+		duration += blend.duration;
+	}
+
+	return duration;
+}
+
+void AnimatorTrack::finishFirstBlend() {
+	const Blend blend = _blends.front();
+	_blends.remove_at(0);
+	setCurrent(blend.target);
+
+	if (_blends.empty()) {
+		_stage.onTrackFinished();
+	}
+}
+
+// Only one blend advances per frame. Time left over when it ends isn't passed
+// on to the next one.
+bool AnimatorTrack::advance(double seconds) {
+	if (_blends.empty()) {
+		return false;
+	}
+
+	Blend &blend = _blends.front();
+	const double time = blend.time + seconds;
+	if (blend.duration <= time) {
+		finishFirstBlend();
+		return true;
+	}
+
+	double progress = CLIP(time / blend.duration, 0.0, 1.0);
+	if (blend.kind == kSlerp) {
+		progress = sin((progress - 0.5) * M_PI) * 0.5 + 0.5;
+	}
+
+	double value[2];
+	for (int i = 0; i < 2; ++i) {
+		value[i] = _start[i] + (blend.target[i] - _start[i]) * progress;
+	}
+
+	setValue(value);
+	blend.time = time;
+	return true;
+}
+
+void AnimatorTrack::set(const double value[2]) {
+	setCurrent(value);
+	_stage.onTrackSet(_kind);
+}
+
+void AnimatorTrack::addBlend(BlendKind kind, double delay, double duration, const double target[2]) {
+	if (delay != 0.0) {
+		Blend wait;
+		wait.duration = MAX(delay, kMinBlendTime);
+		for (int i = 0; i < 2; ++i) {
+			wait.target[i] = _blends.empty() ? _current[i] : _blends.back().target[i];
+		}
+
+		_blends.push_back(wait);
+	}
+
+	Blend blend;
+	blend.kind = kind;
+	blend.duration = MAX(duration, kMinBlendTime);
+	blend.target[0] = target[0];
+	blend.target[1] = target[1];
+	_blends.push_back(blend);
+}
+
+void AnimatorTrack::stopBlending() {
+	if (_blends.empty()) {
+		return;
+	}
+
+	_blends.clear();
+	setCurrent(_current);
+	_stage.onTrackStopped();
+}
+
+void AnimatorTrack::finishBlending() {
+	if (_blends.empty()) {
+		return;
+	}
+
+	const Blend last = _blends.back();
+	_blends.clear();
+	setCurrent(last.target);
+	_stage.onTrackStopped();
+}
+
+void AnimatorTrack::readValue(lua_State *L, int index, double value[2]) const {
+	if (_kind == kAlpha || _kind == kRotation) {
+		value[0] = luaL_checknumber(L, index);
+		value[1] = 0.0;
+		return;
+	}
+
+	if (lua_isnumber(L, index)) {
+		value[0] = lua_tonumber(L, index);
+		value[1] = luaL_checknumber(L, index + 1);
+		return;
+	}
+
+	if (!lua_istable(L, index) && !lua_isuserdata(L, index)) {
+		luaL_argerror(L, index, "expected a point, a vector or two numbers");
+	}
+
+	lua_getfield(L, index, "x");
+	lua_getfield(L, index, "y");
+	if (!lua_isnumber(L, -2) || !lua_isnumber(L, -1)) {
+		luaL_argerror(L, index, "Table must have 'x' and 'y' fields");
+	}
+
+	value[0] = lua_tonumber(L, -2);
+	value[1] = lua_tonumber(L, -1);
+	lua_pop(L, 2);
+}
+
+// Scales and translations are returned as vectors
+void AnimatorTrack::pushValue(lua_State *L) const {
+	if (_kind == kAlpha || _kind == kRotation) {
+		lua_pushnumber(L, _current[0]);
+	} else {
+		pushVector(L, ScriptVector(_current[0], _current[1], 0.0));
+	}
+}
+
+// AnimatorStage
+
+AnimatorStage::AnimatorStage(Animator &animator, uint index, double alpha) :
+		_animator(animator),
+		_index(index) {
+	_tracks[AnimatorTrack::kAlpha] = new AnimatorTrack(*this, AnimatorTrack::kAlpha, alpha, 0.0);
+	_tracks[AnimatorTrack::kScale] = new AnimatorTrack(*this, AnimatorTrack::kScale, 1.0, 1.0);
+	_tracks[AnimatorTrack::kRotation] = new AnimatorTrack(*this, AnimatorTrack::kRotation, 0.0, 0.0);
+	_tracks[AnimatorTrack::kTranslation] = new AnimatorTrack(*this, AnimatorTrack::kTranslation, 0.0, 0.0);
+}
+
+AnimatorStage::~AnimatorStage() {
+	for (AnimatorTrack *track : _tracks) {
+		delete track;
+	}
+}
+
+bool AnimatorStage::isBlending() const {
+	for (const AnimatorTrack *track : _tracks) {
+		if (track->isBlending()) {
+			return true;
+		}
+	}
+
+	return false;
+}
+
+double AnimatorStage::getDuration() const {
+	double duration = 0.0;
+	for (const AnimatorTrack *track : _tracks) {
+		duration = MAX(duration, track->getDuration());
+	}
+
+	return duration;
+}
+
+bool AnimatorStage::advance(double seconds) {
+	bool isBlending = false;
+	for (AnimatorTrack *track : _tracks) {
+		isBlending |= track->advance(seconds);
+	}
+
+	return isBlending;
+}
+
+void AnimatorStage::stopBlending() {
+	for (AnimatorTrack *track : _tracks) {
+		track->stopBlending();
+	}
+}
+
+void AnimatorStage::finishBlending() {
+	for (AnimatorTrack *track : _tracks) {
+		track->finishBlending();
+	}
+}
+
+void AnimatorStage::updateMatrix() {
+	_matrix = _tracks[AnimatorTrack::kScale]->getMatrix() *
+		_tracks[AnimatorTrack::kRotation]->getMatrix() *
+		_tracks[AnimatorTrack::kTranslation]->getMatrix();
+}
+
+// The alpha track only changes the record's alpha, the others only its
+// transform
+void AnimatorStage::onTrackSet(AnimatorTrack::Kind kind) {
+	if (kind == AnimatorTrack::kAlpha) {
+		_animator.updateAlpha();
+	} else {
+		_animator.updateTransform();
+	}
+}
+
+// Updates both the transform and the alpha of the record to where the track
+// ended up
+void AnimatorStage::onTrackStopped() {
+	_animator.updateTransform();
+	_animator.updateAlpha();
+	onTrackFinished();
+}
+
+void AnimatorStage::onTrackFinished() {
+	if (!isBlending()) {
+		_animator.onStageDone(_index);
+	}
+}
+
+// Animator
+
+Animator::Animator(Record &owner) : _owner(owner) {
+	createStage();
+}
+
+Animator::~Animator() {
+	for (AnimatorStage *stage : _stages) {
+		delete stage;
+	}
+}
+
+AnimatorStage *Animator::getStage(uint index) const {
+	return index >= 1 && index <= _stages.size() ? _stages[index - 1] : nullptr;
+}
+
+void Animator::createStage() {
+	_stages.push_back(new AnimatorStage(*this, _stages.size() + 1, _owner.getLocalAlpha()));
+}
+
+// The record keeps its current transform and alpha until something changes
+// them
+void Animator::removeAllStages() {
+	for (AnimatorStage *stage : _stages) {
+		delete stage;
+	}
+
+	_stages.clear();
+}
+
+bool Animator::isBlending() const {
+	for (const AnimatorStage *stage : _stages) {
+		if (stage->isBlending()) {
+			return true;
+		}
+	}
+
+	return false;
+}
+
+double Animator::getDuration() const {
+	double duration = 0.0;
+	for (const AnimatorStage *stage : _stages) {
+		duration = MAX(duration, stage->getDuration());
+	}
+
+	return duration;
+}
+
+void Animator::stopBlending() {
+	for (uint i = 0; i < _stages.size(); ++i) {
+		_stages[i]->stopBlending();
+	}
+}
+
+void Animator::finishBlending() {
+	for (uint i = 0; i < _stages.size(); ++i) {
+		_stages[i]->finishBlending();
+	}
+}
+
+// While any track is blending, the record gets both the transform and the
+// alpha of the stages
+void Animator::advance(double seconds) {
+	bool isBlending = false;
+	for (AnimatorStage *stage : _stages) {
+		isBlending |= stage->advance(seconds);
+	}
+
+	if (isBlending) {
+		updateTransform();
+		updateAlpha();
+	}
+
+	callDoneFunctions();
+}
+
+void Animator::updateTransform() {
+	ScriptMatrix transform;
+	for (AnimatorStage *stage : _stages) {
+		stage->updateMatrix();
+		transform = transform * stage->getMatrix();
+	}
+
+	_owner.setAnimatedTransform(transform);
+}
+
+void Animator::updateAlpha() {
+	double alpha = 1.0;
+	for (const AnimatorStage *stage : _stages) {
+		alpha *= stage->getAlpha();
+	}
+
+	_owner.setAnimatedAlpha(CLIP(alpha, 0.0, 1.0));
+}
+
+void Animator::onStageDone(uint index) {
+	_doneStages.push_back(index);
+}
+
+void Animator::callDoneFunctions() {
+	const Common::Array<uint> doneStages = _doneStages;
+	_doneStages.clear();
+
+	for (uint index : doneStages) {
+		_owner.callFunction(Common::String::format("Stage%uDone", index).c_str());
+	}
+}
+
+// The Lua objects of the animator, its stages and their tracks. Each one
+// identifies the record, the stage and the track, and keeps the record alive
+// while the scripts hold a reference to it.
+
+struct AnimatorRef {
+	Record *record;
+	uint stage;		// 0 for the animator
+	int track;		// -1 for the animator or a stage
+};
+
+static const char *const kAnimatorType = "ND.Animator";
+static const char *const kAnimatorStageType = "ND.AnimatorStage";
+
+static void pushRef(lua_State *L, Record &record, const char *typeName, uint stage, int track) {
+	AnimatorRef *ref = (AnimatorRef *)pushUserData(L, sizeof(AnimatorRef), typeName);
+	ref->record = &record;
+	ref->stage = stage;
+	ref->track = track;
+
+	lua_createtable(L, 1, 0);
+	record.push();
+	lua_rawseti(L, -2, 1);
+	lua_setfenv(L, -2);
+}
+
+void Animator::push(lua_State *L) {
+	pushRef(L, _owner, kAnimatorType, 0, -1);
+}
+
+static Animator &getAnimator(lua_State *L, const AnimatorRef &ref) {
+	Animator *animator = ref.record->getAnimator();
+	if (!animator) {
+		luaL_error(L, "The AR has no animator");
+	}
+
+	return *animator;
+}
+
+static Animator &checkAnimator(lua_State *L) {
+	return getAnimator(L, *(AnimatorRef *)checkUserData(L, 1, kAnimatorType));
+}
+
+// A stage object always refers to the same stage number. It can't be used
+// after RemoveAllStages() has removed that stage.
+static AnimatorStage &getStage(lua_State *L, const AnimatorRef &ref) {
+	AnimatorStage *stage = getAnimator(L, ref).getStage(ref.stage);
+	if (!stage) {
+		luaL_error(L, "Stage %u of the animator was removed", ref.stage);
+	}
+
+	return *stage;
+}
+
+static AnimatorStage &checkStage(lua_State *L) {
+	return getStage(L, *(AnimatorRef *)checkUserData(L, 1, kAnimatorStageType));
+}
+
+static AnimatorTrack &checkTrack(lua_State *L) {
+	const AnimatorRef *ref = nullptr;
+	for (int kind = AnimatorTrack::kAlpha; !ref && kind <= AnimatorTrack::kTranslation; ++kind) {
+		ref = (const AnimatorRef *)testUserData(L, 1, AnimatorTrack::getTypeName((AnimatorTrack::Kind)kind));
+	}
+
+	if (!ref) {
+		luaL_typerror(L, 1, "ND.AnimatorTrack");
+	}
+
+	return getStage(L, *ref).getTrack((AnimatorTrack::Kind)ref->track);
+}
+
+// The functions that the animator, its stages and their tracks all have.
+// Stopping or finishing the blends calls the Done functions of the stages.
+
+static int animatorGetDuration(lua_State *L) {
+	lua_pushnumber(L, checkAnimator(L).getDuration());
+	return 1;
+}
+
+static int animatorIsBlending(lua_State *L) {
+	lua_pushboolean(L, checkAnimator(L).isBlending());
+	return 1;
+}
+
+static int animatorStopBlending(lua_State *L) {
+	Animator &animator = checkAnimator(L);
+	animator.stopBlending();
+	animator.callDoneFunctions();
+	return 0;
+}
+
+static int animatorFinishBlending(lua_State *L) {
+	Animator &animator = checkAnimator(L);
+	animator.finishBlending();
+	animator.callDoneFunctions();
+	return 0;
+}
+
+static int animatorCreateStage(lua_State *L) {
+	checkAnimator(L).createStage();
+	return 0;
+}
+
+static int animatorRemoveAllStages(lua_State *L) {
+	checkAnimator(L).removeAllStages();
+	return 0;
+}
+
+// animator[n] is stage n, or nil
+static int animatorIndex(lua_State *L) {
+	if (lua_type(L, 2) != LUA_TNUMBER) {
+		return indexFunctions(L);
+	}
+
+	const AnimatorRef &ref = *(AnimatorRef *)checkUserData(L, 1, kAnimatorType);
+	const int index = (int)lua_tointeger(L, 2);
+	if (index < 1 || !getAnimator(L, ref).getStage(index)) {
+		lua_pushnil(L);
+	} else {
+		pushRef(L, *ref.record, kAnimatorStageType, index, -1);
+	}
+
+	return 1;
+}
+
+static int stageGetDuration(lua_State *L) {
+	lua_pushnumber(L, checkStage(L).getDuration());
+	return 1;
+}
+
+static int stageIsBlending(lua_State *L) {
+	lua_pushboolean(L, checkStage(L).isBlending());
+	return 1;
+}
+
+static int stageStopBlending(lua_State *L) {
+	AnimatorStage &stage = checkStage(L);
+	Animator &animator = stage.getAnimator();
+	stage.stopBlending();
+	animator.callDoneFunctions();
+	return 0;
+}
+
+static int stageFinishBlending(lua_State *L) {
+	AnimatorStage &stage = checkStage(L);
+	Animator &animator = stage.getAnimator();
+	stage.finishBlending();
+	animator.callDoneFunctions();
+	return 0;
+}
+
+static bool findTrackKind(const char *name, AnimatorTrack::Kind &kind) {
+	static const char *const kTrackNames[] = { "a", "s", "r", "t" };
+	for (uint i = 0; i < ARRAYSIZE(kTrackNames); ++i) {
+		if (strcmp(name, kTrackNames[i]) == 0) {
+			kind = (AnimatorTrack::Kind)i;
+			return true;
+		}
+	}
+
+	return false;
+}
+
+// stage.a, stage.s, stage.r and stage.t are its tracks
+static int stageIndex(lua_State *L) {
+	AnimatorTrack::Kind kind;
+	if (lua_type(L, 2) != LUA_TSTRING || !findTrackKind(lua_tostring(L, 2), kind)) {
+		return indexFunctions(L);
+	}
+
+	const AnimatorRef &ref = *(AnimatorRef *)checkUserData(L, 1, kAnimatorStageType);
+	getStage(L, ref);
+	pushRef(L, *ref.record, AnimatorTrack::getTypeName(kind), ref.stage, kind);
+	return 1;
+}
+
+// stage.t = value sets a track to a value
+static int stageNewIndex(lua_State *L) {
+	static const char *const kTrackDescriptions[] = { "Alpha", "Scale", "Rotation", "Translation" };
+
+	AnimatorStage &stage = checkStage(L);
+	AnimatorTrack::Kind kind;
+	if (!findTrackKind(luaL_checkstring(L, 2), kind)) {
+		return luaL_error(L, "Cannot set field '%s' of an animator stage", lua_tostring(L, 2));
+	}
+
+	AnimatorTrack &track = stage.getTrack(kind);
+	if (track.isBlending()) {
+		return luaL_error(L, "%s Track on Stage %u is in the midst of blending. It cannot be overridden.",
+			kTrackDescriptions[kind], stage.getIndex());
+	}
+
+	double value[2];
+	track.readValue(L, 3, value);
+	track.set(value);
+	return 0;
+}
+
+// track:AddBlendLerp([delay, ]duration, value), and the same for AddBlendSlerp.
+// The first number is a delay if another number follows the duration (alpha
+// and rotation tracks), or follows the first number (scale and translation
+// tracks).
+static int addBlend(lua_State *L, AnimatorTrack::BlendKind kind) {
+	AnimatorTrack &track = checkTrack(L);
+	const bool hasOneNumber = track.getKind() == AnimatorTrack::kAlpha || track.getKind() == AnimatorTrack::kRotation;
+	const bool hasDelay = lua_type(L, hasOneNumber ? 4 : 3) == LUA_TNUMBER;
+
+	double delay = 0.0;
+	double duration = 0.0;
+	double target[2];
+	if (hasDelay) {
+		delay = luaL_checknumber(L, 2);
+		duration = luaL_checknumber(L, 3);
+		track.readValue(L, 4, target);
+	} else {
+		duration = luaL_checknumber(L, 2);
+		track.readValue(L, 3, target);
+	}
+
+	track.addBlend(kind, delay, duration, target);
+	return 0;
+}
+
+static int trackAddBlendLerp(lua_State *L) {
+	return addBlend(L, AnimatorTrack::kLerp);
+}
+
+static int trackAddBlendSlerp(lua_State *L) {
+	return addBlend(L, AnimatorTrack::kSlerp);
+}
+
+static int trackGet(lua_State *L) {
+	checkTrack(L).pushValue(L);
+	return 1;
+}
+
+static int trackSet(lua_State *L) {
+	AnimatorTrack &track = checkTrack(L);
+	if (track.isBlending()) {
+		return luaL_error(L, "Cannot set a track's value while it's blending");
+	}
+
+	double value[2];
+	track.readValue(L, 2, value);
+	track.set(value);
+	return 0;
+}
+
+static int trackGetDuration(lua_State *L) {
+	lua_pushnumber(L, checkTrack(L).getDuration());
+	return 1;
+}
+
+static int trackIsBlending(lua_State *L) {
+	lua_pushboolean(L, checkTrack(L).isBlending());
+	return 1;
+}
+
+static int trackStopBlending(lua_State *L) {
+	AnimatorTrack &track = checkTrack(L);
+	Animator &animator = track.getStage().getAnimator();
+	track.stopBlending();
+	animator.callDoneFunctions();
+	return 0;
+}
+
+static int trackFinishBlending(lua_State *L) {
+	AnimatorTrack &track = checkTrack(L);
+	Animator &animator = track.getStage().getAnimator();
+	track.finishBlending();
+	animator.callDoneFunctions();
+	return 0;
+}
+
+void Animator::registerTypes(lua_State *L) {
+	static const luaL_Reg kAnimatorFunctions[] = {
+		{ "__index", animatorIndex },
+		{ "CreateStage", animatorCreateStage },
+		{ "RemoveAllStages", animatorRemoveAllStages },
+		{ "GetDuration", animatorGetDuration },
+		{ "IsBlending", animatorIsBlending },
+		{ "StopBlending", animatorStopBlending },
+		{ "FinishBlending", animatorFinishBlending },
+		{ nullptr, nullptr }
+	};
+
+	static const luaL_Reg kStageFunctions[] = {
+		{ "__index", stageIndex },
+		{ "__newindex", stageNewIndex },
+		{ "GetDuration", stageGetDuration },
+		{ "IsBlending", stageIsBlending },
+		{ "StopBlending", stageStopBlending },
+		{ "FinishBlending", stageFinishBlending },
+		{ nullptr, nullptr }
+	};
+
+	static const luaL_Reg kTrackFunctions[] = {
+		{ "__index", indexFunctions },
+		{ "AddBlendLerp", trackAddBlendLerp },
+		{ "AddBlendSlerp", trackAddBlendSlerp },
+		{ "Get", trackGet },
+		{ "Set", trackSet },
+		{ "GetDuration", trackGetDuration },
+		{ "IsBlending", trackIsBlending },
+		{ "StopBlending", trackStopBlending },
+		{ "FinishBlending", trackFinishBlending },
+		{ nullptr, nullptr }
+	};
+
+	registerType(L, kAnimatorType, kAnimatorFunctions);
+	registerType(L, kAnimatorStageType, kStageFunctions);
+	for (int kind = AnimatorTrack::kAlpha; kind <= AnimatorTrack::kTranslation; ++kind) {
+		registerType(L, AnimatorTrack::getTypeName((AnimatorTrack::Kind)kind), kTrackFunctions);
+	}
+}
+
+} // End of namespace Script
+} // End of namespace Nancy
diff --git a/engines/nancy/script/v5/animator.h b/engines/nancy/script/v5/animator.h
new file mode 100644
index 00000000000..e8d104211c2
--- /dev/null
+++ b/engines/nancy/script/v5/animator.h
@@ -0,0 +1,211 @@
+/* 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 NANCY_SCRIPT_V5_ANIMATOR_H
+#define NANCY_SCRIPT_V5_ANIMATOR_H
+
+#include "common/array.h"
+
+#include "engines/nancy/script/mathtypes.h"
+
+struct lua_State;
+
+namespace Nancy {
+namespace Script {
+
+class Record;
+class AnimatorStage;
+
+// Nancy29 moves, rotates, scales and fades every record with its animator,
+// which replaces the blend stages of the earlier games:
+//
+//   ar.animator[1].t:AddBlendSlerp(0.5, Point:New(500, 500))
+//   ar.animator[1].r:AddBlendLerp(1, 2, math.pi)  -- waits 1s, rotates for 2s
+//
+// An animator is a list of stages, numbered from 1, and starts with one stage.
+// Each stage has four tracks: a (alpha), s (scale), r (rotation) and t
+// (translation). A track plays the blends added to it one after the other,
+// each one moving it to a target value. A lerp blend moves at a constant
+// speed, while a "slerp" blend starts and ends slowly. When all tracks of a
+// stage have finished blending, the record's "Stage<n>Done" function is
+// called.
+//
+// The record's transform is the product of the transforms of the stages, in
+// order, and each stage scales, then rotates, then translates. The record's
+// alpha is the product of the alphas of the stages. Both are updated whenever
+// a stage changes or blends.
+class AnimatorTrack {
+public:
+	enum Kind {
+		kAlpha,
+		kScale,
+		kRotation,
+		kTranslation
+	};
+
+	enum BlendKind {
+		kLerp,
+		kSlerp
+	};
+
+	AnimatorTrack(AnimatorStage &stage, Kind kind, double x, double y);
+
+	Kind getKind() const { return _kind; }
+	AnimatorStage &getStage() const { return _stage; }
+
+	bool isBlending() const { return !_blends.empty(); }
+
+	// The total duration of the blends, counting the current one in full
+	double getDuration() const;
+
+	// The current value. Alpha and rotation tracks have a single value, in x.
+	double getX() const { return _current[0]; }
+	double getY() const { return _current[1]; }
+	const ScriptMatrix &getMatrix() const { return _matrix; }
+
+	// Advances the current blend. Returns whether the track is blending.
+	bool advance(double seconds);
+
+	// Sets the track to a value. A blend that is underway continues from it.
+	void set(const double value[2]);
+
+	// Adds a blend after the others. A delay is added before it as a blend
+	// that keeps the value the track will have by then.
+	void addBlend(BlendKind kind, double delay, double duration, const double target[2]);
+
+	// Ends all blends, leaving the track at its current value (stop) or at
+	// the target of the last blend (finish)
+	void stopBlending();
+	void finishBlending();
+
+	// Reads a value for this kind of track from the stack: a number, a point,
+	// a vector, a table with x and y, or two numbers
+	void readValue(lua_State *L, int index, double value[2]) const;
+	void pushValue(lua_State *L) const;
+
+	static const char *getTypeName(Kind kind);
+
+private:
+	struct Blend {
+		BlendKind kind = kLerp;
+		double duration = 0.0;
+		double time = 0.0;
+		double target[2] = { 0.0, 0.0 };
+	};
+
+	// Sets the current value, which is also where the next blend starts from
+	void setValue(const double value[2]);
+	void setCurrent(const double value[2]);
+	void finishFirstBlend();
+
+	AnimatorStage &_stage;
+	Kind _kind;
+	double _start[2];
+	double _current[2];
+	ScriptMatrix _matrix;
+	Common::Array<Blend> _blends;
+};
+
+class Animator;
+
+class AnimatorStage {
+public:
+	AnimatorStage(Animator &animator, uint index, double alpha);
+	~AnimatorStage();
+
+	Animator &getAnimator() const { return _animator; }
+
+	// Numbered from 1
+	uint getIndex() const { return _index; }
+
+	AnimatorTrack &getTrack(AnimatorTrack::Kind kind) const { return *_tracks[kind]; }
+
+	const ScriptMatrix &getMatrix() const { return _matrix; }
+	double getAlpha() const { return _tracks[AnimatorTrack::kAlpha]->getX(); }
+
+	bool isBlending() const;
+	double getDuration() const;
+	bool advance(double seconds);
+	void stopBlending();
+	void finishBlending();
+
+	// Scales, then rotates, then translates
+	void updateMatrix();
+
+	// Called when a track was set to a value, when a script stopped or
+	// finished its blends, or when its last blend ended
+	void onTrackSet(AnimatorTrack::Kind kind);
+	void onTrackStopped();
+	void onTrackFinished();
+
+private:
+	Animator &_animator;
+	uint _index;
+	AnimatorTrack *_tracks[4];
+	ScriptMatrix _matrix;
+};
+
+class Animator {
+public:
+	// The alpha track of each new stage starts at the record's own localAlpha
+	Animator(Record &owner);
+	~Animator();
+
+	Record &getOwner() const { return _owner; }
+
+	uint getNumStages() const { return _stages.size(); }
+	AnimatorStage *getStage(uint index) const;	// numbered from 1; null if missing
+
+	void createStage();
+	void removeAllStages();
+
+	bool isBlending() const;
+	double getDuration() const;
+	void stopBlending();
+	void finishBlending();
+
+	// Advances the blends, and passes the results to the record
+	void advance(double seconds);
+
+	// Sets the record's transform or alpha to the product of the stages
+	void updateTransform();
+	void updateAlpha();
+
+	// A stage finished its blends. Its "Stage<n>Done" function is called
+	// later, once the stages aren't being iterated, as it can change them.
+	void onStageDone(uint index);
+	void callDoneFunctions();
+
+	// The Lua objects through which the scripts access the animator, its
+	// stages and their tracks
+	void push(lua_State *L);
+	static void registerTypes(lua_State *L);
+
+private:
+	Record &_owner;
+	Common::Array<AnimatorStage *> _stages;
+	Common::Array<uint> _doneStages;
+};
+
+} // End of namespace Script
+} // End of namespace Nancy
+
+#endif // NANCY_SCRIPT_V5_ANIMATOR_H
diff --git a/engines/nancy/script/v5/gamefunctions.cpp b/engines/nancy/script/v5/gamefunctions.cpp
index 87a45d981b6..d0cd259cba1 100644
--- a/engines/nancy/script/v5/gamefunctions.cpp
+++ b/engines/nancy/script/v5/gamefunctions.cpp
@@ -44,6 +44,7 @@
 #include "engines/nancy/script/records.h"
 #include "engines/nancy/script/scenecontext.h"
 #include "engines/nancy/script/types.h"
+#include "engines/nancy/script/v5/animator.h"
 #include "engines/nancy/script/v5/brain.h"
 
 #include "engines/nancy/script/v5/gamefunctions.h"
@@ -1168,6 +1169,7 @@ void registerNancy26GameAPI(lua_State *L) {
 	registerGlobal(L, "Achievements", kAchievementsType, kAchievementsFunctions);
 
 	registerBrainAPI(L);
+	Animator::registerTypes(L);
 }
 
 } // End of namespace Script
diff --git a/engines/nancy/script/v5/recordnode.cpp b/engines/nancy/script/v5/recordnode.cpp
index 411d5f671aa..3e752b68123 100644
--- a/engines/nancy/script/v5/recordnode.cpp
+++ b/engines/nancy/script/v5/recordnode.cpp
@@ -21,6 +21,8 @@
 
 // The parts of Record that make every record of Nancy26 a node of a tree
 
+#include "engines/nancy/nancy.h"
+
 #include "engines/nancy/script/graphnode.h"
 #include "engines/nancy/script/luabind.h"
 #include "engines/nancy/script/luastate.h"
@@ -29,6 +31,7 @@
 #include "engines/nancy/script/transformer.h"
 #include "engines/nancy/script/types.h"
 
+#include "engines/nancy/script/v5/animator.h"
 #include "engines/nancy/script/v5/cliptransformer.h"
 #include "engines/nancy/script/v5/messaging.h"
 #include "engines/nancy/script/v5/recordnode.h"
@@ -52,6 +55,7 @@ void Record::destroyNodeState() {
 
 	deregisterAliases(this);
 	forgetInputRecord(this);
+	delete _nodeState->animator;
 	delete _nodeState;
 	_nodeState = nullptr;
 }
@@ -221,6 +225,27 @@ void Record::onStagesChanged() {
 	onLocalTransformChanged();
 }
 
+Animator *Record::getAnimator() const {
+	return _nodeState ? _nodeState->animator : nullptr;
+}
+
+double Record::getLocalAlpha() const {
+	return _nodeState ? _nodeState->localAlpha : 1.0;
+}
+
+void Record::setAnimatedTransform(const ScriptMatrix &transform) {
+	if (transform != _transform) {
+		_transform = transform;
+		onLocalTransformChanged();
+	}
+}
+
+void Record::setAnimatedAlpha(double alpha) {
+	if (_nodeState) {
+		_nodeState->localAlpha = alpha;
+	}
+}
+
 void Record::onLocalTransformChanged() {
 	if (hasTransform()) {
 		onTransformChanged();
@@ -276,6 +301,10 @@ void Record::readNodeFields(int tableIndex) {
 		_transform = checkMatrix(L, -1);
 		lua_pop(L, 1);
 	}
+
+	if (g_nancy->getGameType() >= kGameTypeNancy29) {
+		_nodeState->animator = new Animator(*this);
+	}
 }
 
 // An "active" function sets all three flags every frame. The record gets
@@ -333,6 +362,10 @@ void Record::updateNode(double sceneTime, double elapsedTime) {
 		_stages->advance(elapsedTime);
 	}
 
+	if (_nodeState->animator) {
+		_nodeState->animator->advance(elapsedTime);
+	}
+
 	if (isScripted()) {
 		lua_pushnumber(L, sceneTime);
 		lua_pushnumber(L, elapsedTime);
@@ -493,6 +526,8 @@ bool Record::getNodeField(const Common::String &key) {
 		lua_pushcfunction(L, recordDeregisterAlias);
 	} else if (key == "ResetInactive") {
 		lua_pushcfunction(L, recordResetInactive);
+	} else if (key == "animator" && _nodeState->animator) {
+		_nodeState->animator->push(L);
 	} else if (BlendStages::pushFunction(L, key)) {
 		return true;
 	} else if (_stages && _stages->getField(L, key)) {
@@ -546,7 +581,8 @@ bool Record::setNodeField(const Common::String &key) {
 		return true;
 	} else if (key == "enabled" || key == "visible" || key == "paused" || key == "alpha" ||
 			key == "transform" || key == "invTransform" || key == "localInvTransform" ||
-			key == "blendedTransform" || key == "name" || key == "uniqueAlias" || key == "done") {
+			key == "blendedTransform" || key == "name" || key == "uniqueAlias" || key == "done" ||
+			key == "animator") {
 		luaL_error(L, "Cannot set field '%s' of an AR", key.c_str());
 	} else {
 		return false;
diff --git a/engines/nancy/script/v5/recordnode.h b/engines/nancy/script/v5/recordnode.h
index 3286f5f2c16..2c89b208ee7 100644
--- a/engines/nancy/script/v5/recordnode.h
+++ b/engines/nancy/script/v5/recordnode.h
@@ -27,6 +27,8 @@
 namespace Nancy {
 namespace Script {
 
+class Animator;
+
 // Nancy26 makes every record a node of a tree: it is enabled, visible and
 // paused by its own say and by what the Transformers above it say, and can be
 // see-through. Messages reach it by its names. Records of the other games
@@ -43,6 +45,8 @@ struct RecordNodeState {
 	Common::String localName;
 	Common::String uniqueAlias;	// "AR<number>", which no other record has
 
+	Animator *animator = nullptr;	// Nancy29
+
 	// "active" stands for enabled, visible and not paused
 	bool isActive() const { return localEnabled && localVisible && !localPaused; }
 };


Commit: 65f552eaaf8f313023824ecf0bf80549f35efa91
    https://github.com/scummvm/scummvm/commit/65f552eaaf8f313023824ecf0bf80549f35efa91
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:27+02:00

Commit Message:
NANCY: NANCY29: Add the achievements

Even the Steam release of Nancy29 doesn't use Steam for its
achievements. The game keeps them in a file of its own.

Changed paths:
    engines/nancy/metaengine.cpp


diff --git a/engines/nancy/metaengine.cpp b/engines/nancy/metaengine.cpp
index 0d11f904288..9cd86a0db63 100644
--- a/engines/nancy/metaengine.cpp
+++ b/engines/nancy/metaengine.cpp
@@ -243,14 +243,20 @@ void NancyMetaEngine::registerDefaultSettings(const Common::String &target) cons
 	ConfMan.registerDefault("originalsaveload", true);
 }
 
-// Nancy28 has the achievements of its Steam release, the only one there is
+// Nancy28 uses the achievements of its Steam release, its only release.
+// Nancy29 keeps its achievements in a file instead of using Steam.
 Common::AchievementsPlatform NancyMetaEngine::getAchievementsPlatform(const Common::String &target) const {
+	if (ConfMan.get("gameid", target) == "nancy29") {
+		return Common::UNK_ACHIEVEMENTS;
+	}
+
 	return Common::STEAM_ACHIEVEMENTS;
 }
 
 const Common::AchievementDescriptionList *NancyMetaEngine::getAchievementDescriptionList() const {
 	static const Common::AchievementDescriptionList achievementDescriptionList[] = {
 		{ "nancy28", Common::STEAM_ACHIEVEMENTS, "226820" },
+		{ "nancy29", Common::UNK_ACHIEVEMENTS, "nancy29" },
 		ACHIEVEMENT_DESC_TABLE_END_MARKER
 	};
 


Commit: 17a7008d3ed4e896de4625b11d194fe2607375e4
    https://github.com/scummvm/scummvm/commit/17a7008d3ed4e896de4625b11d194fe2607375e4
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:30+02:00

Commit Message:
NANCY: NANCY29: Add detection entry

Set to unstable, as the game now starts and can be played

Changed paths:
    engines/nancy/detection_tables.h


diff --git a/engines/nancy/detection_tables.h b/engines/nancy/detection_tables.h
index 4244e04cd8e..baf076c73f8 100644
--- a/engines/nancy/detection_tables.h
+++ b/engines/nancy/detection_tables.h
@@ -936,6 +936,14 @@ static const ADGameDescription gameDescriptions[] = {
 		ADGF_UNSTABLE | ADGF_DROPPLATFORM,
 		NANCY_GUIOPTIONS
 	},
+	{ // MD5 by bluegr
+		"nancy29", nullptr,
+		AD_ENTRY1s("ciftree.dat", "6b90e2634f4c162a21996a2e1c57bc36", 220400655),
+		Common::EN_ANY,
+		Common::kPlatformWindows,
+		ADGF_UNSTABLE | ADGF_DROPPLATFORM,
+		NANCY_GUIOPTIONS
+	},
 
 	// Do not delete
 	AD_TABLE_END_MARKER


Commit: 36f5265e459b1708de7ee10e72e8b69e2288e955
    https://github.com/scummvm/scummvm/commit/36f5265e459b1708de7ee10e72e8b69e2288e955
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:31+02:00

Commit Message:
VIDEO: BINK2: Add revision 'g' (KB2g)

Most movies of Nancy30 use revision 'g' of Bink 2, which works with
integers where revision 'f' uses floats. Its bitstream is decoded as in
the FFmpeg patch's decoder. The rest was checked against RAD's own
decoder, which this one now matches pixel for pixel:
- frames always start with an 8-byte header, and videos below 128 rows
  have a single slice
- blocks with only a DC are blurred into their neighbors with integer
  weights
- the edges between the 8x8 blocks of a residue are smoothed before the
  residue is added to the picture

Changed paths:
    video/bink2_decoder.cpp
    video/bink2_decoder.h


diff --git a/video/bink2_decoder.cpp b/video/bink2_decoder.cpp
index 98175e866dc..81f733b0560 100644
--- a/video/bink2_decoder.cpp
+++ b/video/bink2_decoder.cpp
@@ -43,6 +43,7 @@
 namespace Video {
 
 static constexpr uint32 kKB2fID = MKTAG('K', 'B', '2', 'f');
+static constexpr uint32 kKB2gID = MKTAG('K', 'B', '2', 'g');
 
 static constexpr uint32 kVideoFlagAlpha = 0x00100000;
 
@@ -53,6 +54,10 @@ static constexpr uint32 kFrameFlagBlockFlags = 0x10000;
 static constexpr uint32 kFrameFlagNoRowFlags = 0x8000;
 static constexpr uint32 kFrameFlagNoColFlags = 0x4000;
 
+// Revision 'g': a luma CBP without blocks is not followed by the bit that
+// says which set of codes they use
+static constexpr uint32 kFrameFlagNoEmptyCBPFlag = 0x40000;
+
 // Border around the luma planes; half of it around the chroma ones
 static constexpr int kBorder = 32;
 
@@ -170,14 +175,202 @@ static constexpr byte kLumaBlockPos[16] = {
 	0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15
 };
 
+// Revision 'g'
+
+static constexpr byte kScanG[64] = {
+	 0,  8,  1,  2,  9, 16, 24, 17,
+	10,  3,  4, 11, 18, 25, 32, 40,
+	33, 26, 19, 12,  5,  6, 13, 20,
+	27, 34, 41, 48, 56, 49, 42, 35,
+	28, 21, 14,  7, 15, 22, 29, 36,
+	43, 50, 57, 58, 51, 44, 37, 30,
+	23, 31, 38, 45, 52, 59, 60, 53,
+	46, 39, 47, 54, 61, 62, 55, 63
+};
+
+static constexpr uint32 kACSkipCodesG[2][14] = {
+	{ 0x01, 0x00, 0x04, 0x2C, 0x6C, 0x0C, 0x4C, 0xAC, 0xEC, 0x12C, 0x16C, 0x1AC, 0x02, 0x1C },
+	{ 0x01, 0x04, 0x00, 0x08, 0x02, 0x32, 0x0A, 0x12, 0x3A, 0x7A, 0xFA, 0x72, 0x06, 0x1A }
+};
+
+static constexpr uint8 kACSkipLengthsG[2][14] = {
+	{ 1, 3, 4, 9, 9, 7, 7, 9, 8, 9, 9, 9, 2, 5 },
+	{ 1, 3, 4, 4, 5, 7, 5, 6, 7, 8, 8, 7, 3, 6 }
+};
+
+static constexpr uint32 kMotionCodesG[16] = {
+	0x01, 0x06, 0x0C, 0x1C, 0x18, 0x38, 0x58, 0x78, 0x68, 0x48, 0x28, 0x08, 0x14, 0x04, 0x02, 0x00
+};
+
+static constexpr uint8 kMotionLengthsG[16] = {
+	1, 3, 5, 5, 7, 7, 7, 7, 7, 7, 7, 7, 5, 5, 3, 4
+};
+
+// How many coefficients a skip symbol jumps over (11: read 6 bits; 64: to the end)
+static constexpr byte kACSkipsG[14] = {
+	0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 64, 0
+};
+
+// The chroma blocks a macroblock codes when it repeats the previous ones, by them
+static constexpr byte kChromaCBPG[16] = {
+	0x00, 0x00, 0x00, 0x0F, 0x00, 0x0F, 0x0F, 0x0F, 0x00, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F
+};
+
+// The step of the DC differences by quantizer, in 1/1024
+static constexpr int kDCStepG[37] = {
+	1024, 1218, 1448, 1722, 2048, 2435, 2896, 3444,
+	4096, 4871, 5793, 6889, 8192, 9742, 11585, 13777,
+	16384, 19484, 23170, 27555, 32768, 38968, 46341, 55109,
+	65536, 77936, 92682, 110218, 131072, 155872, 185364, 220436,
+	262144, 311744, 370728, 440872, 524288
+};
+
+// The dequantization matrices: the weight that each of the 64 coefficients
+// of a block is multiplied by, coarser for the higher frequencies, in fixed
+// point with 7 fractional bits. Quantizer q picks the matrix by q & 3 and
+// doubles the weights every 4 steps (1 << (q >> 2)). The DC doesn't use them.
+static constexpr uint16 kLumaIntraQmatG[4][64] = {
+	{
+		 1024,  1432,  1506,  1181,  1843,  2025,  5271,  8592,
+		 1313,  1669,  1630,  1672,  2625,  3442,  8023, 12794,
+		 1076,  1755,  1808,  1950,  3980,  4875,  8813, 11909,
+		 1350,  1868,  2127,  2016,  4725,  4450,  7712,  9637,
+		 2458,  3103,  4303,  4303,  6963,  6835, 11079, 13365,
+		 3375,  5704,  5052,  6049,  9198,  7232, 10725,  9834,
+		 5486,  7521,  7797,  7091, 11079, 10016, 13559, 12912,
+		 7279,  7649,  7020,  6097,  9189,  9047, 12661, 13768
+	},
+	{
+		 1218,  1703,  1791,  1405,  2192,  2408,  6268, 10218,
+		 1561,  1985,  1938,  1988,  3122,  4093,  9541, 15215,
+		 1279,  2087,  2150,  2319,  4733,  5798, 10481, 14162,
+		 1606,  2222,  2530,  2398,  5619,  5292,  9171, 11460,
+		 2923,  3690,  5117,  5118,  8281,  8128, 13176, 15894,
+		 4014,  6783,  6008,  7194, 10938,  8600, 12755, 11694,
+		 6524,  8944,  9272,  8433, 13176, 11911, 16125, 15354,
+		 8657,  9096,  8348,  7250, 10927, 10759, 15056, 16373
+	},
+	{
+		 1448,  2025,  2130,  1671,  2607,  2864,  7454, 12151,
+		 1856,  2360,  2305,  2364,  3713,  4867, 11346, 18094,
+		 1521,  2482,  2557,  2758,  5628,  6894, 12464, 16841,
+		 1909,  2642,  3008,  2852,  6683,  6293, 10906, 13629,
+		 3476,  4388,  6085,  6086,  9847,  9666, 15668, 18901,
+		 4773,  8066,  7145,  8555, 13007, 10227, 15168, 13907,
+		 7758, 10637, 11026, 10028, 15668, 14165, 19175, 18259,
+		10294, 10817,  9927,  8622, 12995, 12794, 17905, 19470
+	},
+	{
+		 1722,  2408,  2533,  1987,  3100,  3406,  8864, 14450,
+		 2208,  2807,  2741,  2811,  4415,  5788, 13493, 21517,
+		 1809,  2951,  3041,  3280,  6693,  8199, 14822, 20028,
+		 2271,  3142,  3578,  3391,  7947,  7484, 12969, 16207,
+		 4133,  5218,  7236,  7238, 11711, 11495, 18633, 22478,
+		 5677,  9592,  8497, 10174, 15469, 12162, 18038, 16538,
+		 9226, 12649, 13112, 11926, 18633, 16845, 22804, 21715,
+		12242, 12864, 11806, 10254, 15454, 15215, 21293, 23155
+	}
+};
+
+static constexpr uint16 kChromaIntraQmatG[4][64] = {
+	{
+		 1024,  1193,  1434,  2203,  5632,  4641,  5916,  6563,
+		 1193,  1622,  1811,  3606,  6563,  5408,  6894,  7649,
+		 1434,  1811,  3515,  4875,  5916,  4875,  6215,  6894,
+		 2203,  3606,  4875,  3824,  4641,  3824,  4875,  5408,
+		 5632,  6563,  5916,  4641,  5632,  4641,  5916,  6563,
+		 4641,  5408,  4875,  3824,  4641,  3824,  4875,  5408,
+		 5916,  6894,  6215,  4875,  5916,  4875,  6215,  6894,
+		 6563,  7649,  6894,  5408,  6563,  5408,  6894,  7649
+	},
+	{
+		 1218,  1419,  1706,  2620,  6698,  5519,  7035,  7805,
+		 1419,  1929,  2153,  4288,  7805,  6432,  8199,  9096,
+		 1706,  2153,  4180,  5798,  7035,  5798,  7390,  8199,
+		 2620,  4288,  5798,  4548,  5519,  4548,  5798,  6432,
+		 6698,  7805,  7035,  5519,  6698,  5519,  7035,  7805,
+		 5519,  6432,  5798,  4548,  5519,  4548,  5798,  6432,
+		 7035,  8199,  7390,  5798,  7035,  5798,  7390,  8199,
+		 7805,  9096,  8199,  6432,  7805,  6432,  8199,  9096
+	},
+	{
+		 1448,  1688,  2028,  3116,  7965,  6563,  8367,  9282,
+		 1688,  2294,  2561,  5099,  9282,  7649,  9750, 10817,
+		 2028,  2561,  4971,  6894,  8367,  6894,  8789,  9750,
+		 3116,  5099,  6894,  5408,  6563,  5408,  6894,  7649,
+		 7965,  9282,  8367,  6563,  7965,  6563,  8367,  9282,
+		 6563,  7649,  6894,  5408,  6563,  5408,  6894,  7649,
+		 8367,  9750,  8789,  6894,  8367,  6894,  8789,  9750,
+		 9282, 10817,  9750,  7649,  9282,  7649,  9750, 10817
+	},
+	{
+		 1722,  2007,  2412,  3706,  9472,  7805,  9950, 11038,
+		 2007,  2729,  3045,  6064, 11038,  9096, 11595, 12864,
+		 2412,  3045,  5912,  8199,  9950,  8199, 10452, 11595,
+		 3706,  6064,  8199,  6432,  7805,  6432,  8199,  9096,
+		 9472, 11038,  9950,  7805,  9472,  7805,  9950, 11038,
+		 7805,  9096,  8199,  6432,  7805,  6432,  8199,  9096,
+		 9950, 11595, 10452,  8199,  9950,  8199, 10452, 11595,
+		11038, 12864, 11595,  9096, 11038,  9096, 11595, 12864
+	}
+};
+
+static constexpr uint16 kInterQmatG[4][64] = {
+	{
+		 1024,  1193,  1076,   844,  1052,   914,  1225,  1492,
+		 1193,  1391,  1254,   983,  1227,  1065,  1463,  1816,
+		 1076,  1254,  1161,   936,  1195,  1034,  1444,  1741,
+		  844,   983,   936,   811,  1055,   927,  1305,  1584,
+		 1052,  1227,  1195,  1055,  1451,  1336,  1912,  2354,
+		  914,  1065,  1034,   927,  1336,  1313,  1945,  2486,
+		 1225,  1463,  1444,  1305,  1912,  1945,  3044,  4039,
+		 1492,  1816,  1741,  1584,  2354,  2486,  4039,  5679
+	},
+	{
+		 1218,  1419,  1279,  1003,  1252,  1087,  1457,  1774,
+		 1419,  1654,  1491,  1169,  1459,  1267,  1739,  2159,
+		 1279,  1491,  1381,  1113,  1421,  1230,  1717,  2070,
+		 1003,  1169,  1113,   965,  1254,  1103,  1552,  1884,
+		 1252,  1459,  1421,  1254,  1725,  1589,  2274,  2799,
+		 1087,  1267,  1230,  1103,  1589,  1562,  2313,  2956,
+		 1457,  1739,  1717,  1552,  2274,  2313,  3620,  4803,
+		 1774,  2159,  2070,  1884,  2799,  2956,  4803,  6753
+	},
+	{
+		 1448,  1688,  1521,  1193,  1488,  1293,  1732,  2110,
+		 1688,  1967,  1773,  1391,  1735,  1507,  2068,  2568,
+		 1521,  1773,  1642,  1323,  1690,  1462,  2042,  2462,
+		 1193,  1391,  1323,  1147,  1492,  1311,  1845,  2241,
+		 1488,  1735,  1690,  1492,  2052,  1889,  2704,  3328,
+		 1293,  1507,  1462,  1311,  1889,  1857,  2751,  3515,
+		 1732,  2068,  2042,  1845,  2704,  2751,  4306,  5712,
+		 2110,  2568,  2462,  2241,  3328,  3515,  5712,  8031
+	},
+	{
+		 1722,  2007,  1809,  1419,  1770,  1537,  2060,  2509,
+		 2007,  2339,  2108,  1654,  2063,  1792,  2460,  3054,
+		 1809,  2108,  1953,  1574,  2010,  1739,  2428,  2928,
+		 1419,  1654,  1574,  1364,  1774,  1559,  2195,  2664,
+		 1770,  2063,  2010,  1774,  2440,  2247,  3216,  3958,
+		 1537,  1792,  1739,  1559,  2247,  2209,  3271,  4181,
+		 2060,  2460,  2428,  2195,  3216,  3271,  5120,  6793,
+		 2509,  3054,  2928,  2664,  3958,  4181,  6793,  9550
+	}
+};
+
 static inline byte clipPixel(int value) {
 	return (byte)CLIP(value, 0, 255);
 }
 
-// The kind of an intra block, by its number of AC coefficients, and its DC
+// The kind of a block, by its number of AC coefficients: blocks with fewer
+// get more of their pixels changed by the deblocking
+static int getBlockKind(int coefCount) {
+	return coefCount == 0 ? 7 : (coefCount < 4 ? 6 : (coefCount < 8 ? 5 : 4));
+}
+
+// The kind of an intra block and its DC
 static uint16 makeBlockWord(int coefCount, float dc) {
-	const int kind = coefCount == 0 ? 7 : (coefCount < 4 ? 6 : (coefCount < 8 ? 5 : 4));
-	return (uint16)((kind << 13) | ((int)(dc + kAlmostHalf) & 0x1FFF));
+	return (uint16)((getBlockKind(coefCount) << 13) | ((int)(dc + kAlmostHalf) & 0x1FFF));
 }
 
 static inline int countBits4(uint32 value) {
@@ -456,14 +649,15 @@ bool Bink2Decoder::isBink2(Common::SeekableReadStream &stream) {
 	const int64 pos = stream.pos();
 	const uint32 id = stream.readUint32BE();
 	stream.seek(pos);
-	return id == kKB2fID;
+	return id == kKB2fID || id == kKB2gID;
 }
 
 // The container is the one of Bink videos
 bool Bink2Decoder::loadStream(Common::SeekableReadStream *stream) {
 	close();
 
-	if (stream->readUint32BE() != kKB2fID) {
+	const uint32 id = stream->readUint32BE();
+	if (id != kKB2fID && id != kKB2gID) {
 		delete stream;
 		return false;
 	}
@@ -485,7 +679,7 @@ bool Bink2Decoder::loadStream(Common::SeekableReadStream *stream) {
 		return false;
 	}
 
-	addTrack(new Bink2VideoTrack(width, height, videoFlags, frameCount, Common::Rational(frameRateNum, frameRateDen)));
+	addTrack(new Bink2VideoTrack((char)(id & 0xFF), width, height, videoFlags, frameCount, Common::Rational(frameRateNum, frameRateDen)));
 
 	// The maximum packet sizes, then the rate and the flags of each track,
 	// then their IDs
@@ -591,8 +785,8 @@ VideoDecoder::AudioTrack *Bink2Decoder::getAudioTrack(int index) {
 	return (AudioTrack *)track;
 }
 
-Bink2Decoder::Bink2VideoTrack::Bink2VideoTrack(uint32 width, uint32 height, uint32 flags, uint32 frameCount, const Common::Rational &frameRate) :
-		_width(width), _height(height), _frameCount(frameCount), _curFrameNumber(-1), _frameRate(frameRate),
+Bink2Decoder::Bink2VideoTrack::Bink2VideoTrack(char revision, uint32 width, uint32 height, uint32 flags, uint32 frameCount, const Common::Rational &frameRate) :
+		_revision(revision), _width(width), _height(height), _frameCount(frameCount), _curFrameNumber(-1), _frameRate(frameRate),
 		_surface(nullptr), _curFrame(0), _comp(0), _mbPos(0) {
 	_pixelFormat = Image::Codec::getDefaultYUVFormat();
 
@@ -629,6 +823,10 @@ Bink2Decoder::Bink2VideoTrack::Bink2VideoTrack(uint32 width, uint32 height, uint
 		memset(_dcRows[i].data(), 0, columns * sizeof(DCPredict));
 		_mvRows[i].resize(columns);
 		memset(_mvRows[i].data(), 0, columns * sizeof(MotionVectors));
+		_intDCRows[i].resize(columns);
+		memset(_intDCRows[i].data(), 0, columns * sizeof(IntDCPredict));
+		_quantRows[i].resize(columns);
+		memset(_quantRows[i].data(), 0, columns * sizeof(QuantPredict));
 	}
 
 	for (int plane = 0; plane < 4; plane++) {
@@ -644,14 +842,21 @@ Bink2Decoder::Bink2VideoTrack::Bink2VideoTrack(uint32 width, uint32 height, uint
 	_prevDC = _dcRows[1].data();
 	_currentMV = _mvRows[0].data();
 	_prevMV = _mvRows[1].data();
+	_currentIntDC = _intDCRows[0].data();
+	_prevIntDC = _intDCRows[1].data();
+	_currentQuant = _quantRows[0].data();
+	_prevQuant = _quantRows[1].data();
 
 	_quantHuffman = new Huffman(0, 16, kQuantCodes, kQuantLengths);
 	for (int i = 0; i < 2; i++) {
 		_acValueHuffman[i] = new Huffman(0, 13, kACValueCodes[i], kACValueLengths[i]);
 		_acSkipHuffman[i] = new Huffman(0, 14, kACSkipCodes[i], kACSkipLengths[i]);
+		_gACSkipHuffman[i] = new Huffman(0, 14, kACSkipCodesG[i], kACSkipLengthsG[i]);
 	}
+	_gMotionHuffman = new Huffman(0, 16, kMotionCodesG, kMotionLengthsG);
 
 	memset(_block, 0, sizeof(_block));
+	memset(_intBlock, 0, sizeof(_intBlock));
 
 	reset();
 }
@@ -670,7 +875,9 @@ Bink2Decoder::Bink2VideoTrack::~Bink2VideoTrack() {
 	for (int i = 0; i < 2; i++) {
 		delete _acValueHuffman[i];
 		delete _acSkipHuffman[i];
+		delete _gACSkipHuffman[i];
 	}
+	delete _gMotionHuffman;
 }
 
 bool Bink2Decoder::Bink2VideoTrack::setOutputPixelFormat(const Graphics::PixelFormat &format) {
@@ -733,23 +940,29 @@ void Bink2Decoder::Bink2VideoTrack::decodeFrame(Common::SeekableReadStream &stre
 		return;
 	}
 
-	// The frame flags, then the offset of the second slice
-	if (size < 8) {
+	// Revision 'f' always has two slices, 'g' one for videos below 128 rows
+	const int numSlices = (_revision == 'g' && _alignedHeight < 128) ? 1 : 2;
+	const uint32 headerSize = 8;
+
+	// The frame flags, then the offset of the second slice, 0 without one
+	if (size < headerSize) {
 		warning("Bink2Decoder: Frame of %u bytes is too small", size);
 		return;
 	}
 
 	const uint32 frameFlags  = READ_LE_UINT32(_packet.data());
-	const uint32 sliceOffset = READ_LE_UINT32(_packet.data() + 4);
-	if (sliceOffset < 8 || sliceOffset > size) {
+	const uint32 sliceOffset = numSlices == 2 ? READ_LE_UINT32(_packet.data() + 4) : size;
+	if (sliceOffset < headerSize || sliceOffset > size) {
 		warning("Bink2Decoder: Bad slice offset %u in a frame of %u bytes", sliceOffset, size);
 		return;
 	}
 
-	// Revision 'f' always has two slices
-	const int sliceHeight = (_height / 2 + 16) & ~31;
+	int sliceHeight = (int)_alignedHeight;
+	if (numSlices == 2)
+		sliceHeight = (int)(_revision == 'g' ? (_height / 2) & ~31 : (_height / 2 + 16) & ~31);
+	_frameFlags = frameFlags;
 
-	Common::BitStreamMemoryStream stream1(_packet.data() + 8, (sliceOffset - 8 + 3) & ~3);
+	Common::BitStreamMemoryStream stream1(_packet.data() + headerSize, (sliceOffset - headerSize + 3) & ~3);
 	BitStream bits1(stream1);
 
 	// Flags of the rows and columns of blocks, which are not needed
@@ -760,14 +973,24 @@ void Bink2Decoder::Bink2VideoTrack::decodeFrame(Common::SeekableReadStream &stre
 			skipBlockFlags(bits1, (((_width + 15) & ~15) >> 3) - 1);
 	}
 
-	decodeSlice(bits1, isKeyFrame, 0, sliceHeight);
+	if (_revision == 'g') {
+		decodeSliceG(bits1, isKeyFrame, 0, sliceHeight);
+		if (numSlices == 2) {
+			Common::BitStreamMemoryStream stream2(_packet.data() + sliceOffset, (size - sliceOffset + 3) & ~3);
+			BitStream bits2(stream2);
+			decodeSliceG(bits2, isKeyFrame, sliceHeight, _alignedHeight);
+		}
 
-	Common::BitStreamMemoryStream stream2(_packet.data() + sliceOffset, (size - sliceOffset + 3) & ~3);
-	BitStream bits2(stream2);
-	decodeSlice(bits2, isKeyFrame, sliceHeight, _alignedHeight);
+		deblock();
+	} else {
+		decodeSlice(bits1, isKeyFrame, 0, sliceHeight);
 
-	_frameFlags = frameFlags;
-	deblock();
+		Common::BitStreamMemoryStream stream2(_packet.data() + sliceOffset, (size - sliceOffset + 3) & ~3);
+		BitStream bits2(stream2);
+		decodeSlice(bits2, isKeyFrame, sliceHeight, _alignedHeight);
+
+		deblock();
+	}
 
 	_curFrame ^= 1;
 }
@@ -923,20 +1146,7 @@ void Bink2Decoder::Bink2VideoTrack::decodeSlice(BitStream &bits, bool isKeyFrame
 				break;
 			}
 
-			if (type != kBlockIntra) {
-				for (int plane = 0; plane < _numPlanes; plane++) {
-					const int size = (plane == 1 || plane == 2) ? 2 : 4;
-					for (int j = 0; j < size; j++)
-						for (int i = 0; i < size; i++)
-							setBlockWord(plane, x / (32 / size) + i, y / (32 / size) + j, 0);
-				}
-			}
-			for (int i = 0; i < 4; i++) {
-				int *vector = &_blockVectors[((y / 16 + (i >> 1)) * (_alignedWidth / 16) + x / 16 + (i & 1)) * 2];
-				const bool isMoved = type == kBlockMotion || type == kBlockResidue;
-				vector[0] = isMoved ? _currentMV[_mbPos].v[i][0] : 0;
-				vector[1] = isMoved ? _currentMV[_mbPos].v[i][1] : 0;
-			}
+			storeDeblockInfo(type);
 
 			if (!isValid) {
 				warning("Bink2Decoder: Bad quantizer at macroblock %d, %d", x, y);
@@ -1357,10 +1567,693 @@ void Bink2Decoder::Bink2VideoTrack::averageNeighbor(int x, int y, byte *const ds
 	}
 }
 
+// Revision 'g'
+
+// Counts the bits that differ from stop, up to len of them
+static int getUnary(Common::BitStreamMemory32LELSB &bits, int stop, int len) {
+	int count = 0;
+	while (count < len && (int)bits.getBit() != stop)
+		count++;
+
+	return count;
+}
+
+static inline int predictMedianInt(int a, int b, int c) {
+	return MIN(MAX(c + b - a, MIN(a, MIN(b, c))), MAX(a, MAX(b, c)));
+}
+
+static inline int predictMedian2Int(int a, int b) {
+	return MIN(MAX(a, b), MAX(MIN(a, b), 2 * a - b));
+}
+
+static void idct1DG(int16 *block, int step, int shift) {
+	const int t00 = block[3 * step] + block[5 * step];
+	const int t01 = block[3 * step] - block[5 * step];
+	const int t02 = block[2 * step] + (block[2 * step] >> 2) + (block[6 * step] >> 1);
+	const int t03 = (block[2 * step] >> 1) - (block[6 * step] + (block[6 * step] >> 2));
+	const int t0 = block[0 * step] + block[4 * step] + t02;
+	const int t1 = block[0 * step] + block[4 * step] - t02;
+	const int t2 = block[0 * step] - block[4 * step];
+	const int t3 = block[1 * step] + t00;
+	const int t4 = block[1 * step] - t00;
+	const int t5 = t01 + block[7 * step];
+	const int t6 = t01 - block[7 * step];
+	const int t7 = t4 + (t6 - (t6 >> 2) - (t6 >> 4));
+	const int t8 = (t4 - (t4 >> 2) - (t4 >> 4)) - t6;
+	const int t9 = (t3 + (t3 >> 2) - (t3 >> 4)) + (t5 >> 2);
+	const int t10 = (t3 >> 2) - (t5 + (t5 >> 2) - (t5 >> 4));
+	const int t11 = t2 + t03;
+	const int t12 = t2 - t03;
+
+	block[0 * step] = (int16)((t0 + t9) >> shift);
+	block[1 * step] = (int16)((t11 + t7) >> shift);
+	block[2 * step] = (int16)((t12 + t8) >> shift);
+	block[3 * step] = (int16)((t1 + t10) >> shift);
+	block[4 * step] = (int16)((t1 - t10) >> shift);
+	block[5 * step] = (int16)((t12 - t8) >> shift);
+	block[6 * step] = (int16)((t11 - t7) >> shift);
+	block[7 * step] = (int16)((t0 - t9) >> shift);
+}
+
+// The DC goes in with a bias of 4, rounding included. The block comes out
+// transposed.
+static void idctG(int16 *block, int dc) {
+	block[0] = (int16)(dc * 8 + 32);
+
+	for (int i = 0; i < 8; i++)
+		idct1DG(block + i, 8, 0);
+	for (int i = 0; i < 8; i++)
+		idct1DG(block + i * 8, 1, 6);
+}
+
+static void putBlockG(byte *dst, int pitch, const int16 *block) {
+	for (int j = 0; j < 8; j++) {
+		for (int i = 0; i < 8; i++)
+			dst[i] = clipPixel(block[i * 8 + j]);
+		dst += pitch;
+	}
+}
+
+static void copyResidueG(int16 *dst, int pitch, const int16 *block) {
+	for (int j = 0; j < 8; j++) {
+		for (int i = 0; i < 8; i++)
+			dst[i] = block[i * 8 + j];
+		dst += pitch;
+	}
+}
+
+// The edges between the blocks of a residue are smoothed before it is added,
+// on the side of each block with few AC coefficients: the nearest of its
+// differences when it has fewer than 8, the two nearest with fewer than 4.
+// Not between two blocks with only DCs that are close.
+static void filterResidueEdgeG(int16 *p, int step, int lineStep, uint16 a, uint16 b) {
+	if ((a | b) < 0x2000)
+		return;
+
+	if ((a & b) >= 0x6000) {
+		const int difference = (int)(a ^ 0x800) - (int)(b ^ 0x800);
+		if ((uint32)(difference + 0x20) <= 0x40)
+			return;
+	}
+
+	const int kindA = a >> 13;
+	const int kindB = b >> 13;
+
+	for (int i = 0; i < 8; i++, p += lineStep) {
+		const int d = asInt16(p[0] - p[-step]);
+		const int outer = asInt16(d + 4) >> 3;
+		const int inner = asInt16(d + 2) >> 2;
+
+		if (kindA >= 2)
+			p[-2 * step] = asInt16(p[-2 * step] + outer);
+		if (kindA >= 1)
+			p[-step] = asInt16(p[-step] + inner);
+		if (kindB >= 1)
+			p[0] = asInt16(p[0] - inner);
+		if (kindB >= 2)
+			p[step] = asInt16(p[step] - outer);
+	}
+}
+
+// For blocks of size x size 8x8 blocks, with their words as x + size * y
+static void filterResidueG(int16 *residue, int size, const uint16 *words, uint32 frameFlags) {
+	const int pitch = size * 8;
+
+	if (!(frameFlags & kFrameFlagNoColFlags))
+		for (int y = 0; y < size; y++)
+			for (int x = 1; x < size; x++)
+				filterResidueEdgeG(residue + y * 8 * pitch + x * 8, 1, pitch, words[y * size + x - 1], words[y * size + x]);
+
+	if (!(frameFlags & kFrameFlagNoRowFlags))
+		for (int y = 1; y < size; y++)
+			for (int x = 0; x < size; x++)
+				filterResidueEdgeG(residue + y * 8 * pitch + x * 8, pitch, 1, words[(y - 1) * size + x], words[y * size + x]);
+}
+
+static void addResidueG(byte *dst, int pitch, const int16 *residue, int size) {
+	for (int j = 0; j < size; j++) {
+		for (int i = 0; i < size; i++)
+			dst[i] = clipPixel(dst[i] + residue[j * size + i]);
+		dst += pitch;
+	}
+}
+
+// The kind of a residue block, as its deblocking sees it, and its DC
+static uint16 makeResidueWordG(int coefCount, int dc) {
+	return (uint16)(((getBlockKind(coefCount) & 3) << 13) | (dc & 0xFFF));
+}
+
+void Bink2Decoder::Bink2VideoTrack::decodeSliceG(BitStream &bits, bool isKeyFrame, int start, int end) {
+	const int dstFrame = _curFrame ^ 1;
+	const uint32 columns = _quantRows[0].size();
+
+	byte *dst[4];
+	const byte *src[4];
+	for (int plane = 0; plane < 4; plane++) {
+		const bool isChroma = plane == 1 || plane == 2;
+
+		if (plane < _numPlanes) {
+			dst[plane] = _planes[dstFrame][plane] + (isChroma ? start / 2 : start) * _pitches[plane];
+			src[plane] = _planes[_curFrame][plane];
+		} else {
+			dst[plane] = nullptr;
+			src[plane] = nullptr;
+		}
+	}
+
+	memset(_prevQuant, 0, columns * sizeof(QuantPredict));
+	memset(_prevMV, 0, _mvRows[0].size() * sizeof(MotionVectors));
+
+	for (int y = start; y < end; y += 32) {
+		// The order in which the kinds of macroblock were last used
+		int typeOrder[4] = { kBlockMotion, kBlockResidue, kBlockSkip, kBlockIntra };
+
+		// Y, the two chroma planes in the order they are coded, A
+		uint32 intraCBP[4] = { 0, 0, 0, 0 };
+		uint32 interCBP[4] = { 0, 0, 0, 0 };
+
+		memset(_currentQuant, 0, columns * sizeof(QuantPredict));
+		memset(_currentMV, 0, _mvRows[0].size() * sizeof(MotionVectors));
+
+		for (int x = 0; x < (int)_width; x += 32) {
+			const int type = isKeyFrame ? (int)kBlockIntra : decodeBlockTypeG(bits, typeOrder);
+			QuantPredict &quant = _currentQuant[x / 32];
+			MotionVectors mv;
+			memset(&mv, 0, sizeof(mv));
+			int mvCount = 0;
+
+			_mbPos = x / 32;
+			_mbX = x;
+			_mbY = y;
+			_currentIntDC[_mbPos].blockType = type;
+
+			int flags = 0;
+			if (y == start)
+				flags |= kFlagTop;
+			if (x == 0)
+				flags |= kFlagLeft;
+
+			switch (type) {
+			case kBlockIntra:
+				// The DCs of the neighbors that were not intra come from their pixels
+				if (!(flags & (kFlagTop | kFlagLeft)) && _prevIntDC[_mbPos - 1].blockType != kBlockIntra)
+					averageNeighborG(x - 32, -32, dst, _prevIntDC[_mbPos - 1]);
+				if (!(flags & kFlagLeft) && _currentIntDC[_mbPos - 1].blockType != kBlockIntra)
+					averageNeighborG(x - 32, 0, dst, _currentIntDC[_mbPos - 1]);
+				if ((flags & kFlagLeft) && !(flags & kFlagTop) && _prevIntDC[_mbPos + 1].blockType != kBlockIntra)
+					averageNeighborG(x + 32, -32, dst, _prevIntDC[_mbPos + 1]);
+				if (!(flags & kFlagTop) && _prevIntDC[_mbPos].blockType != kBlockIntra)
+					averageNeighborG(x, -32, dst, _prevIntDC[_mbPos]);
+
+				predictMotionVectorsG(flags, mv, mvCount);
+				quant.interQ = predictQuant(false, flags);
+				quant.intraQ = predictQuant(true, flags) + decodeDeltaQG(bits);
+				if (quant.intraQ < 0 || quant.intraQ >= 37) {
+					warning("Bink2Decoder: Bad quantizer at macroblock %d, %d", x, y);
+					return;
+				}
+
+				_comp = 0;
+				decodeLumaG(bits, true, intraCBP[0], quant.intraQ, dst[0] + x, _pitches[0], flags);
+				_comp = 1;
+				decodeChromaG(bits, true, intraCBP[1], quant.intraQ, dst[2] + x / 2, _pitches[2], flags);
+				_comp = 2;
+				decodeChromaG(bits, true, intraCBP[2], quant.intraQ, dst[1] + x / 2, _pitches[1], flags);
+				if (_hasAlpha) {
+					_comp = 3;
+					decodeLumaG(bits, true, intraCBP[3], quant.intraQ, dst[3] + x, _pitches[3], flags);
+				}
+				break;
+			case kBlockSkip:
+				quant.interQ = predictQuant(false, flags);
+				quant.intraQ = predictQuant(true, flags);
+				copyBlock(dst[0] + x, src[0] + x + y * _pitches[0], _pitches[0], 32, 32);
+				copyBlock(dst[1] + x / 2, src[1] + x / 2 + y / 2 * _pitches[1], _pitches[1], 16, 16);
+				copyBlock(dst[2] + x / 2, src[2] + x / 2 + y / 2 * _pitches[2], _pitches[2], 16, 16);
+				if (_hasAlpha)
+					copyBlock(dst[3] + x, src[3] + x + y * _pitches[3], _pitches[3], 32, 32);
+				break;
+			default:
+				// Motion, or motion with a residue
+				quant.intraQ = predictQuant(true, flags);
+				if (type == kBlockMotion)
+					quant.interQ = predictQuant(false, flags);
+
+				mvCount = decodeMotionVectorsG(bits, mv);
+				predictMotionVectorsG(flags, mv, mvCount);
+
+				if (type == kBlockResidue) {
+					quant.interQ = predictQuant(false, flags) + decodeDeltaQG(bits);
+					if (quant.interQ < 0 || quant.interQ >= 37) {
+						warning("Bink2Decoder: Bad quantizer at macroblock %d, %d", x, y);
+						return;
+					}
+				}
+
+				compensateLuma(x, y, dst[0], src[0], _pitches[0]);
+				compensateChroma(x / 2, y / 2, dst[2], src[2], _pitches[2]);
+				compensateChroma(x / 2, y / 2, dst[1], src[1], _pitches[1]);
+				if (_hasAlpha)
+					compensateLuma(x, y, dst[3], src[3], _pitches[3]);
+
+				if (type == kBlockResidue) {
+					_comp = 0;
+					decodeLumaG(bits, false, interCBP[0], quant.interQ, dst[0] + x, _pitches[0], flags);
+
+					// The chroma planes can be left out
+					if (bits.getBit()) {
+						_comp = 1;
+						decodeChromaG(bits, false, interCBP[1], quant.interQ, dst[2] + x / 2, _pitches[2], flags);
+						_comp = 2;
+						decodeChromaG(bits, false, interCBP[2], quant.interQ, dst[1] + x / 2, _pitches[1], flags);
+					} else {
+						interCBP[1] = 0;
+						interCBP[2] = 0;
+					}
+
+					if (_hasAlpha) {
+						_comp = 3;
+						decodeLumaG(bits, false, interCBP[3], quant.interQ, dst[3] + x, _pitches[3], flags);
+					}
+				}
+				break;
+			}
+
+			storeDeblockInfo(type);
+		}
+
+		for (int plane = 0; plane < _numPlanes; plane++) {
+			const bool isChroma = plane == 1 || plane == 2;
+			dst[plane] += (isChroma ? 16 : 32) * _pitches[plane];
+		}
+
+		SWAP(_currentMV, _prevMV);
+		SWAP(_currentQuant, _prevQuant);
+		SWAP(_currentIntDC, _prevIntDC);
+	}
+}
+
+// The kinds of macroblock are coded by how recently they were used
+int Bink2Decoder::Bink2VideoTrack::decodeBlockTypeG(BitStream &bits, int lru[4]) {
+	int type = lru[0];
+
+	switch (getUnary(bits, 1, 3)) {
+	case 1:
+		type = lru[1];
+		SWAP(lru[0], lru[1]);
+		break;
+	case 2:
+		type = lru[3];
+		SWAP(lru[2], lru[3]);
+		break;
+	case 3:
+		type = lru[2];
+		SWAP(lru[1], lru[2]);
+		break;
+	default:
+		break;
+	}
+
+	return type;
+}
+
+int Bink2Decoder::Bink2VideoTrack::decodeDeltaQG(BitStream &bits) {
+	int dq = getUnary(bits, 1, 4);
+
+	if (dq == 3)
+		dq += bits.getBit();
+	else if (dq == 4)
+		dq += bits.getBits<5>() + 1;
+
+	if (dq && bits.getBit())
+		dq = -dq;
+
+	return dq;
+}
+
+// From the macroblocks to the left and above; the first one of a slice starts at 16
+int Bink2Decoder::Bink2VideoTrack::predictQuant(bool isIntra, int flags) const {
+	const QuantPredict &top = _prevQuant[_mbPos];
+	const QuantPredict &left = _currentQuant[MAX(_mbPos - 1, 0)];
+	const QuantPredict &leftTop = _prevQuant[MAX(_mbPos - 1, 0)];
+
+	if ((flags & kFlagTop) && (flags & kFlagLeft))
+		return 16;
+	if (flags & kFlagTop)
+		return isIntra ? left.intraQ : left.interQ;
+	if (flags & kFlagLeft)
+		return isIntra ? top.intraQ : top.interQ;
+
+	return isIntra ? median(top.intraQ, left.intraQ, leftTop.intraQ) : median(top.interQ, left.interQ, leftTop.interQ);
+}
+
+// Which 8x8 blocks have coefficients (bits 0-15), and whether they use the
+// second set of skip codes (bits 16-31)
+uint32 Bink2Decoder::Bink2VideoTrack::decodeLumaCBPG(BitStream &bits, uint32 prevCBP) {
+	uint32 ones = 0;
+	for (int i = 0; i < 16; i++) {
+		if (prevCBP & (1 << i))
+			ones++;
+	}
+
+	// Mostly set ones are coded inverted
+	uint32 mask = 0;
+	if (ones > 7) {
+		ones = 16 - ones;
+		mask = 0xFFFF;
+	}
+
+	uint32 cbp = 0;
+	if (!bits.getBit()) {
+		if (ones < 4) {
+			for (int j = 0; j < 16; j += 4) {
+				if (!bits.getBit())
+					cbp |= bits.getBits<4>() << j;
+			}
+		} else {
+			cbp = bits.getBits<16>();
+		}
+	}
+
+	cbp ^= mask;
+	if (!(_frameFlags & kFrameFlagNoEmptyCBPFlag) || cbp) {
+		if (bits.getBit())
+			cbp |= cbp << 16;
+	}
+
+	return cbp;
+}
+
+uint32 Bink2Decoder::Bink2VideoTrack::decodeChromaCBPG(BitStream &bits, uint32 prevCBP) {
+	uint32 cbp = (prevCBP & 0xF0000) | kChromaCBPG[prevCBP & 0xF];
+
+	if (!bits.getBit()) {
+		cbp = bits.getBits<4>();
+		if (bits.getBit())
+			cbp |= cbp << 16;
+	}
+
+	return cbp;
+}
+
+void Bink2Decoder::Bink2VideoTrack::predictDCG(bool isLuma, int minDC, int maxDC, int flags, const int tdc[16]) {
+	const int *leftTop = _prevIntDC[MAX(_mbPos - 1, 0)].dc[_comp];
+	const int *top     = _prevIntDC[_mbPos].dc[_comp];
+	const int *left    = _currentIntDC[MAX(_mbPos - 1, 0)].dc[_comp];
+	int *dc = _currentIntDC[_mbPos].dc[_comp];
+
+	const bool hasTop  = !(flags & kFlagTop);
+	const bool hasLeft = !(flags & kFlagLeft);
+
+	int first;
+	if (hasTop && hasLeft)
+		first = isLuma ? predictMedianInt(leftTop[15], left[5], top[10]) : predictMedianInt(leftTop[3], left[1], top[2]);
+	else if (hasTop)
+		first = isLuma ? predictMedian2Int(top[10], top[11]) : predictMedian2Int(top[2], top[3]);
+	else if (hasLeft)
+		first = isLuma ? predictMedian2Int(left[5], left[7]) : predictMedian2Int(left[1], left[3]);
+	else
+		first = minDC < 0 ? 0 : 1024;
+
+	dc[0] = CLIP(first + tdc[0], minDC, maxDC);
+
+	if (!isLuma) {
+		dc[1] = CLIP((hasTop ? predictMedianInt(top[2], dc[0], top[3]) : dc[0]) + tdc[1], minDC, maxDC);
+		dc[2] = CLIP((hasLeft ? predictMedianInt(left[1], left[3], dc[0]) : predictMedian2Int(dc[0], dc[1])) + tdc[2], minDC, maxDC);
+		dc[3] = CLIP(predictMedianInt(dc[0], dc[2], dc[1]) + tdc[3], minDC, maxDC);
+		return;
+	}
+
+	dc[1]  = CLIP((hasTop ? predictMedianInt(top[10], dc[0], top[11]) : dc[0]) + tdc[1], minDC, maxDC);
+	dc[2]  = CLIP((hasLeft ? predictMedianInt(left[5], left[7], dc[0]) : predictMedian2Int(dc[0], dc[1])) + tdc[2], minDC, maxDC);
+	dc[3]  = CLIP(predictMedianInt(dc[0], dc[2], dc[1]) + tdc[3], minDC, maxDC);
+	dc[4]  = CLIP((hasTop ? predictMedianInt(top[11], dc[1], top[14]) : predictMedian2Int(dc[1], dc[3])) + tdc[4], minDC, maxDC);
+	dc[5]  = CLIP((hasTop ? predictMedianInt(top[14], dc[4], top[15]) : dc[4]) + tdc[5], minDC, maxDC);
+	dc[6]  = CLIP(predictMedianInt(dc[1], dc[3], dc[4]) + tdc[6], minDC, maxDC);
+	dc[7]  = CLIP(predictMedianInt(dc[4], dc[6], dc[5]) + tdc[7], minDC, maxDC);
+	dc[8]  = CLIP((hasLeft ? predictMedianInt(left[7], left[13], dc[2]) : predictMedian2Int(dc[2], dc[3])) + tdc[8], minDC, maxDC);
+	dc[9]  = CLIP(predictMedianInt(dc[2], dc[8], dc[3]) + tdc[9], minDC, maxDC);
+	dc[10] = CLIP((hasLeft ? predictMedianInt(left[13], left[15], dc[8]) : predictMedian2Int(dc[8], dc[9])) + tdc[10], minDC, maxDC);
+	dc[11] = CLIP(predictMedianInt(dc[8], dc[10], dc[9]) + tdc[11], minDC, maxDC);
+	dc[12] = CLIP(predictMedianInt(dc[3], dc[9], dc[6]) + tdc[12], minDC, maxDC);
+	dc[13] = CLIP(predictMedianInt(dc[6], dc[12], dc[7]) + tdc[13], minDC, maxDC);
+	dc[14] = CLIP(predictMedianInt(dc[9], dc[11], dc[12]) + tdc[14], minDC, maxDC);
+	dc[15] = CLIP(predictMedianInt(dc[12], dc[14], dc[13]) + tdc[15], minDC, maxDC);
+}
+
+void Bink2Decoder::Bink2VideoTrack::decodeDCG(BitStream &bits, bool isLuma, int q, int minDC, int maxDC, int flags) {
+	const int count = isLuma ? 16 : 4;
+	const int step = kDCStepG[MAX(q, 8)];
+	int tdc[16] = {};
+
+	if (bits.getBit()) {
+		for (int i = 0; i < count; i++) {
+			int value = getUnary(bits, 0, 12);
+
+			if (value > 3)
+				value = (1 << (value - 3)) + bits.getBits(value - 3) + 2;
+			if (value && bits.getBit())
+				value = -value;
+
+			tdc[i] = (value * step + 0x200) >> 10;
+		}
+	}
+
+	predictDCG(isLuma, minDC, maxDC, flags, tdc);
+}
+
+// The AC coefficients of four 8x8 blocks, for the ones set in the low bits of cbp
+void Bink2Decoder::Bink2VideoTrack::decodeACG(BitStream &bits, uint32 cbp, int q, const uint16 qmat[4][64]) {
+	memset(_intBlock, 0, sizeof(_intBlock));
+	memset(_coefCounts, 0, sizeof(_coefCounts));
+
+	if (!(cbp & 0xF))
+		return;
+
+	Huffman *skipHuffman = _gACSkipHuffman[(cbp & 0xFFFF0000) ? 1 : 0];
+	const int scale = 1 << (q >> 2);
+
+	for (int i = 0; i < 4; i++, cbp >>= 1) {
+		if (!(cbp & 1))
+			continue;
+
+		int next = 0;
+		int index = 1;
+		while (index < 64) {
+			next--;
+			if (next < 1) {
+				const int skip = skipHuffman->getSymbol(bits);
+				int run = kACSkipsG[skip];
+
+				next = kACNextSkips[skip];
+				if (run == 11)
+					run = bits.getBits<6>();
+
+				index += run;
+				if (index >= 64)
+					break;
+			}
+
+			int value = getUnary(bits, 0, 12) + 1;
+			if (value > 3)
+				value = bits.getBits(value - 3) + (1 << (value - 3)) + 2;
+			if (bits.getBit())
+				value = -value;
+
+			const byte pos = kScanG[index];
+			_intBlock[i][pos] = (int16)((value * qmat[q & 3][pos] * scale + 64) >> 7);
+			_coefCounts[i]++;
+			index++;
+		}
+	}
+}
+
+void Bink2Decoder::Bink2VideoTrack::decodeLumaG(BitStream &bits, bool isIntra, uint32 &prevCBP, int q, byte *dst, int pitch, int flags) {
+	const uint32 cbp = prevCBP = decodeLumaCBPG(bits, prevCBP);
+
+	// The differences of a residue are not predicted from the neighbors
+	if (isIntra)
+		decodeDCG(bits, true, q, 0, 2047, flags);
+	else
+		decodeDCG(bits, true, q, -1023, 1023, kFlagTop | kFlagLeft);
+
+	const int *dc = _currentIntDC[_mbPos].dc[_comp];
+	uint16 residueWords[16];
+
+	for (int i = 0; i < 4; i++) {
+		decodeACG(bits, cbp >> (4 * i), q, isIntra ? kLumaIntraQmatG : kInterQmatG);
+
+		for (int j = 0; j < 4; j++) {
+			const int pos = kLumaBlockPos[i * 4 + j];
+			idctG(_intBlock[j], dc[i * 4 + j]);
+
+			if (isIntra) {
+				const int plane = _comp == 0 ? 0 : 3;
+				const int blockIndex = (_mbY / 8 + (pos >> 2)) * _blockColumns[plane] + _mbX / 8 + (pos & 3);
+				_blockWords[plane][blockIndex] = makeBlockWord(_coefCounts[j], (float)dc[i * 4 + j]);
+				putBlockG(dst + (pos & 3) * 8 + (pos >> 2) * 8 * pitch, pitch, _intBlock[j]);
+			} else {
+				residueWords[pos] = makeResidueWordG(_coefCounts[j], dc[i * 4 + j]);
+				copyResidueG(_residue + (pos & 3) * 8 + (pos >> 2) * 8 * 32, 32, _intBlock[j]);
+			}
+		}
+	}
+
+	if (!isIntra) {
+		filterResidueG(_residue, 4, residueWords, _frameFlags);
+		addResidueG(dst, pitch, _residue, 32);
+	}
+}
+
+void Bink2Decoder::Bink2VideoTrack::decodeChromaG(BitStream &bits, bool isIntra, uint32 &prevCBP, int q, byte *dst, int pitch, int flags) {
+	const uint32 cbp = prevCBP = decodeChromaCBPG(bits, prevCBP);
+
+	if (isIntra)
+		decodeDCG(bits, false, q, 0, 2047, flags);
+	else
+		decodeDCG(bits, false, q, -1023, 1023, kFlagTop | kFlagLeft);
+
+	decodeACG(bits, cbp, q, isIntra ? kChromaIntraQmatG : kInterQmatG);
+
+	const int *dc = _currentIntDC[_mbPos].dc[_comp];
+	uint16 residueWords[4];
+
+	for (int j = 0; j < 4; j++) {
+		idctG(_intBlock[j], dc[j]);
+
+		if (isIntra) {
+			const int plane = _comp == 1 ? 2 : 1;
+			const int blockIndex = (_mbY / 16 + (j >> 1)) * _blockColumns[plane] + _mbX / 16 + (j & 1);
+			_blockWords[plane][blockIndex] = makeBlockWord(_coefCounts[j], (float)dc[j]);
+			putBlockG(dst + (j & 1) * 8 + (j >> 1) * 8 * pitch, pitch, _intBlock[j]);
+		} else {
+			residueWords[j] = makeResidueWordG(_coefCounts[j], dc[j]);
+			copyResidueG(_residue + (j & 1) * 8 + (j >> 1) * 8 * 16, 16, _intBlock[j]);
+		}
+	}
+
+	if (!isIntra) {
+		filterResidueG(_residue, 2, residueWords, _frameFlags);
+		addResidueG(dst, pitch, _residue, 16);
+	}
+}
+
+// One motion vector for the whole macroblock, or four. Returns how many.
+int Bink2Decoder::Bink2VideoTrack::decodeMotionVectorsG(BitStream &bits, MotionVectors &mv) {
+	const int count = bits.getBit() ? 1 : 4;
+
+	for (int i = 0; i < 2; i++) {
+		for (int j = 0; j < count; j++) {
+			int value = _gMotionHuffman->getSymbol(bits);
+
+			if (value == 15) {
+				const int valueBits = getUnary(bits, 1, 12) + 4;
+				value = bits.getBits(valueBits) + (1 << valueBits) - 1;
+				value = (value & 1) ? -(value >> 1) - 1 : value >> 1;
+			} else if (value >= 8) {
+				value -= 15;
+			}
+
+			mv.v[j][i] = value;
+		}
+	}
+
+	return count;
+}
+
+void Bink2Decoder::Bink2VideoTrack::predictMotionVectorsG(int flags, const MotionVectors &mv, int count) {
+	MotionVectors &cur = _currentMV[_mbPos];
+	const MotionVectors &left    = _currentMV[MAX(_mbPos - 1, 0)];
+	const MotionVectors &leftTop = _prevMV[MAX(_mbPos - 1, 0)];
+	const MotionVectors &top     = _prevMV[_mbPos];
+
+	for (int i = 0; i < 2; i++) {
+		if (count == 1) {
+			int value = mv.v[0][i];
+			if (!(flags & kFlagTop)) {
+				if (flags & kFlagLeft)
+					value += median(top.v[0][i], top.v[2][i], top.v[3][i]);
+				else
+					value += median(leftTop.v[3][i], top.v[2][i], left.v[1][i]);
+			} else if (!(flags & kFlagLeft)) {
+				value += median(left.v[0][i], left.v[1][i], left.v[3][i]);
+			}
+
+			for (int j = 0; j < 4; j++)
+				cur.v[j][i] = value;
+			continue;
+		}
+
+		if (!(flags & kFlagTop)) {
+			if (flags & kFlagLeft)
+				cur.v[0][i] = mv.v[0][i] + median(top.v[0][i], top.v[2][i], top.v[3][i]);
+			else
+				cur.v[0][i] = mv.v[0][i] + median(top.v[2][i], leftTop.v[3][i], left.v[1][i]);
+
+			cur.v[1][i] = mv.v[1][i] + median(top.v[2][i], top.v[3][i], cur.v[0][i]);
+			if (flags & kFlagLeft)
+				cur.v[2][i] = mv.v[2][i] + median(top.v[2][i], cur.v[0][i], cur.v[1][i]);
+			else
+				cur.v[2][i] = mv.v[2][i] + median(left.v[1][i], left.v[3][i], cur.v[0][i]);
+			cur.v[3][i] = mv.v[3][i] + median(cur.v[0][i], cur.v[1][i], cur.v[2][i]);
+		} else if (flags & kFlagLeft) {
+			cur.v[0][i] = mv.v[0][i];
+			cur.v[1][i] = mv.v[1][i] + mv.v[0][i];
+			cur.v[2][i] = mv.v[2][i] + mv.v[0][i];
+			cur.v[3][i] = mv.v[3][i] + median(cur.v[0][i], cur.v[1][i], cur.v[2][i]);
+		} else {
+			cur.v[0][i] = mv.v[0][i] + median(left.v[0][i], left.v[1][i], left.v[3][i]);
+			cur.v[2][i] = mv.v[2][i] + median(left.v[1][i], left.v[3][i], cur.v[0][i]);
+			cur.v[1][i] = mv.v[1][i] + median(left.v[1][i], cur.v[0][i], cur.v[2][i]);
+			cur.v[3][i] = mv.v[3][i] + median(cur.v[0][i], cur.v[1][i], cur.v[2][i]);
+		}
+	}
+}
+
+void Bink2Decoder::Bink2VideoTrack::averageNeighborG(int x, int y, byte *const dst[4], IntDCPredict &predict) {
+	for (int i = 0; i < 16; i++) {
+		const int pos = kLumaBlockPos[i];
+		const int offset = x + (pos & 3) * 8 + (y + (pos >> 2) * 8) * _pitches[0];
+
+		predict.dc[0][i] = averageBlock(dst[0] + offset, _pitches[0]);
+		if (_hasAlpha)
+			predict.dc[3][i] = averageBlock(dst[3] + offset, _pitches[3]);
+	}
+
+	// The chroma planes in the order they are coded
+	for (int i = 0; i < 4; i++) {
+		const int chromaX = x / 2 + (i & 1) * 8;
+		const int chromaY = y / 2 + (i >> 1) * 8;
+
+		predict.dc[1][i] = averageBlock(dst[2] + chromaX + chromaY * _pitches[2], _pitches[2]);
+		predict.dc[2][i] = averageBlock(dst[1] + chromaX + chromaY * _pitches[1], _pitches[1]);
+	}
+}
+
 void Bink2Decoder::Bink2VideoTrack::setBlockWord(int plane, int x, int y, uint16 word) {
 	_blockWords[plane][y * _blockColumns[plane] + x] = word;
 }
 
+// The blocks of a macroblock that is not intra have a word of 0, and the
+// vectors of the ones that did not move are 0
+void Bink2Decoder::Bink2VideoTrack::storeDeblockInfo(int type) {
+	if (type != kBlockIntra) {
+		for (int plane = 0; plane < _numPlanes; plane++) {
+			const int size = (plane == 1 || plane == 2) ? 2 : 4;
+			for (int j = 0; j < size; j++)
+				for (int i = 0; i < size; i++)
+					setBlockWord(plane, _mbX / (32 / size) + i, _mbY / (32 / size) + j, 0);
+		}
+	}
+
+	for (int i = 0; i < 4; i++) {
+		int *vector = &_blockVectors[((_mbY / 16 + (i >> 1)) * (_alignedWidth / 16) + _mbX / 16 + (i & 1)) * 2];
+		const bool isMoved = type == kBlockMotion || type == kBlockResidue;
+		vector[0] = isMoved ? _currentMV[_mbPos].v[i][0] : 0;
+		vector[1] = isMoved ? _currentMV[_mbPos].v[i][1] : 0;
+	}
+}
+
 // A block with only a DC is drawn from the DCs around it: each neighbor that
 // is such a block too, with a DC closer than the threshold, pulls the pixels
 // near it toward its own DC.
@@ -1378,6 +2271,11 @@ void Bink2Decoder::Bink2VideoTrack::blurBlock(int plane, int x, int y, int thres
 		}
 	}
 
+	if (_revision == 'g') {
+		blurBlockG(plane, x, y, words, threshold);
+		return;
+	}
+
 	// Compared as signed 16-bit words, the kinds of block included
 	float values[3][3];
 	const int16 c = asInt16(center);
@@ -1423,6 +2321,68 @@ void Bink2Decoder::Bink2VideoTrack::blurBlock(int plane, int x, int y, int thres
 	}
 }
 
+// The weights of revision 'g', in 16-bit fixed point: of the side of a pixel
+// toward the edge it is near, and of the other one
+static constexpr int kBlurNearWeightsG[4] = { 0x6800, 0x4800, 0x3000, 0x1C00 };
+static constexpr int kBlurFarShiftsG[4] = { 0, 7, 5, 4 };
+
+static int blurWeightG(int near, int far, int pos) {
+	const int weighted = asInt16((near * kBlurNearWeightsG[pos]) >> 16);
+	return pos == 0 ? weighted : weighted + (far >> kBlurFarShiftsG[pos]);
+}
+
+// Of the differences to the left (or top) and right (or bottom) DCs
+static int blurOffsetG(int first, int second, int pos) {
+	return pos < 4 ? blurWeightG(first, second, pos) : blurWeightG(second, first, 7 - pos);
+}
+
+// Revision 'g' does the same in 16-bit integers: each row of DCs is spread
+// over the 8 columns, then the 3 rows over the 8 rows of pixels, with DCs
+// that are 8 times the pixel values
+void Bink2Decoder::Bink2VideoTrack::blurBlockG(int plane, int x, int y, const uint16 words[3][3], int threshold) {
+	const int16 c = asInt16(words[1][1]);
+
+	int values[3][3];
+	for (int j = 0; j < 3; j++) {
+		for (int i = 0; i < 3; i++) {
+			const int16 difference = MAX(asInt16(c - words[j][i]), asInt16(words[j][i] - c));
+			values[j][i] = (threshold > difference) ? (words[j][i] & 0x1FFF) : -1;
+		}
+	}
+	values[1][1] = c & 0x1FFF;
+
+	for (int j = 0; j < 3; j += 2)
+		if (values[j][1] < 0)
+			values[j][1] = values[1][1];
+	for (int i = 0; i < 3; i += 2)
+		if (values[1][i] < 0)
+			values[1][i] = values[1][1];
+	for (int j = 0; j < 3; j += 2)
+		for (int i = 0; i < 3; i += 2)
+			if (values[j][i] < 0)
+				values[j][i] = values[1][i];
+
+	// Rounded by the 4 added before the 3 bits are shifted out
+	int rows[3][8];
+	for (int j = 0; j < 3; j++) {
+		const int left = asInt16(values[j][0] - values[j][1]);
+		const int right = asInt16(values[j][2] - values[j][1]);
+		for (int i = 0; i < 8; i++)
+			rows[j][i] = asInt16(values[j][1] + 4 + blurOffsetG(left, right, i));
+	}
+
+	const int pitch = _pitches[plane];
+	byte *dst = _planes[_curFrame ^ 1][plane] + y * 8 * pitch + x * 8;
+
+	for (int i = 0; i < 8; i++) {
+		const int middle = rows[1][i];
+		const int top = asInt16(rows[0][i] - middle);
+		const int bottom = asInt16(rows[2][i] - middle);
+		for (int j = 0; j < 8; j++)
+			dst[j * pitch + i] = clipPixel(asInt16(middle + blurOffsetG(top, bottom, j)) >> 3);
+	}
+}
+
 // Smooths the edges between the blocks of a plane, the ones between columns
 // or between rows, by the kinds of blocks on both sides: blocks with fewer
 // AC coefficients get more of their pixels changed. Between two blocks that
diff --git a/video/bink2_decoder.h b/video/bink2_decoder.h
index ace7992b969..636cb0fc3b2 100644
--- a/video/bink2_decoder.h
+++ b/video/bink2_decoder.h
@@ -52,7 +52,7 @@ struct Surface;
 namespace Video {
 
 /**
- * Decoder for Bink 2 videos of revision 'f' (KB2f).
+ * Decoder for Bink 2 videos of revisions 'f' and 'g' (KB2f, KB2g).
  *
  * Video decoder used in engines:
  *  - nancy
@@ -90,7 +90,7 @@ private:
 	 */
 	class Bink2VideoTrack : public FixedRateVideoTrack {
 	public:
-		Bink2VideoTrack(uint32 width, uint32 height, uint32 flags, uint32 frameCount, const Common::Rational &frameRate);
+		Bink2VideoTrack(char revision, uint32 width, uint32 height, uint32 flags, uint32 frameCount, const Common::Rational &frameRate);
 		~Bink2VideoTrack() override;
 
 		uint16 getWidth() const override { return _width; }
@@ -138,6 +138,20 @@ private:
 			int v[4][2];
 		};
 
+		// Revision 'g' predicts integer DCs, and the quantizers from the
+		// macroblocks around
+		struct IntDCPredict {
+			int dc[4][16];
+			int blockType;
+		};
+
+		struct QuantPredict {
+			int intraQ;
+			int interQ;
+		};
+
+		char _revision;
+
 		uint32 _width;
 		uint32 _height;
 		uint32 _alignedWidth;
@@ -190,6 +204,18 @@ private:
 		Huffman *_acValueHuffman[2];
 		Huffman *_acSkipHuffman[2];
 
+		// Revision 'g'
+		Common::Array<IntDCPredict> _intDCRows[2];
+		Common::Array<QuantPredict> _quantRows[2];
+		IntDCPredict *_currentIntDC;
+		IntDCPredict *_prevIntDC;
+		QuantPredict *_currentQuant;
+		QuantPredict *_prevQuant;
+		int16 _intBlock[4][64];
+		int16 _residue[32 * 32];
+		Huffman *_gACSkipHuffman[2];
+		Huffman *_gMotionHuffman;
+
 		/** Clear both frames to black. */
 		void reset();
 
@@ -220,10 +246,28 @@ private:
 		void averageNeighbor(int x, int y, byte *const dst[4], DCPredict &predict);
 
 		void setBlockWord(int plane, int x, int y, uint16 word);
+		void storeDeblockInfo(int type);
+
+		// Revision 'g'
+		void decodeSliceG(BitStream &bits, bool isKeyFrame, int start, int end);
+		int decodeBlockTypeG(BitStream &bits, int lru[4]);
+		int decodeDeltaQG(BitStream &bits);
+		uint32 decodeLumaCBPG(BitStream &bits, uint32 prevCBP);
+		uint32 decodeChromaCBPG(BitStream &bits, uint32 prevCBP);
+		void predictDCG(bool isLuma, int minDC, int maxDC, int flags, const int tdc[16]);
+		void decodeDCG(BitStream &bits, bool isLuma, int q, int minDC, int maxDC, int flags);
+		void decodeACG(BitStream &bits, uint32 cbp, int q, const uint16 qmat[4][64]);
+		void decodeLumaG(BitStream &bits, bool isIntra, uint32 &prevCBP, int q, byte *dst, int pitch, int flags);
+		void decodeChromaG(BitStream &bits, bool isIntra, uint32 &prevCBP, int q, byte *dst, int pitch, int flags);
+		int decodeMotionVectorsG(BitStream &bits, MotionVectors &mv);
+		void predictMotionVectorsG(int flags, const MotionVectors &mv, int count);
+		void averageNeighborG(int x, int y, byte *const dst[4], IntDCPredict &predict);
+		int predictQuant(bool isIntra, int flags) const;
 
 		// After a frame is decoded
 		void deblock();
 		void blurBlock(int plane, int x, int y, int threshold);
+		void blurBlockG(int plane, int x, int y, const uint16 words[3][3], int threshold);
 		void filterEdges(int plane, bool isVertical);
 
 		// Into the output surface


Commit: 57b525aee362396b6c25a03f1b8e4082d2d6dfff
    https://github.com/scummvm/scummvm/commit/57b525aee362396b6c25a03f1b8e4082d2d6dfff
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:32+02:00

Commit Message:
VIDEO: BINK2: Keep the sources of motion blocks inside the frame

The Bink 2 decoder of Nancy30 and later moves the source of a moving
block back inside the frame when its motion vector points past an edge
or too close to it. Nancy29's older decoder skips such blocks instead,
and Nancy29 keeps doing so. Without this, the bottom rows of some
Nancy30 movies showed wrong pixels.

Changed paths:
    engines/nancy/movieplayer.cpp
    video/bink2_decoder.cpp
    video/bink2_decoder.h


diff --git a/engines/nancy/movieplayer.cpp b/engines/nancy/movieplayer.cpp
index a777657a586..cea3a025d6d 100644
--- a/engines/nancy/movieplayer.cpp
+++ b/engines/nancy/movieplayer.cpp
@@ -105,10 +105,11 @@ bool MoviePlayer::loadFile(const Common::Path &name, byte videoPlaytype, bool bi
 	}
 
 	if (_videoType == kVideoPlaytypeBink) {
-		// Nancy29 has movies in both versions of Bink
+		// Nancy29 has movies in both versions of Bink. Its Bink 2 decoder is
+		// older than the one of the later games.
 		Common::File file;
 		if (file.open(bikPath) && Video::Bink2Decoder::isBink2(file))
-			_decoder.reset(new Video::Bink2Decoder());
+			_decoder.reset(new Video::Bink2Decoder(g_nancy->getGameType() == kGameTypeNancy29));
 		else
 			_decoder.reset(new Video::BinkDecoder());
 	} else {
diff --git a/video/bink2_decoder.cpp b/video/bink2_decoder.cpp
index 81f733b0560..e15efa26eb6 100644
--- a/video/bink2_decoder.cpp
+++ b/video/bink2_decoder.cpp
@@ -638,7 +638,7 @@ static constexpr float kBlurCenter[8][8] = {
 };
 
 
-Bink2Decoder::Bink2Decoder() : _stream(nullptr), _audioTrackCount(0) {
+Bink2Decoder::Bink2Decoder(bool skipOutsideBlocks) : _stream(nullptr), _audioTrackCount(0), _skipOutsideBlocks(skipOutsideBlocks) {
 }
 
 Bink2Decoder::~Bink2Decoder() {
@@ -679,7 +679,7 @@ bool Bink2Decoder::loadStream(Common::SeekableReadStream *stream) {
 		return false;
 	}
 
-	addTrack(new Bink2VideoTrack((char)(id & 0xFF), width, height, videoFlags, frameCount, Common::Rational(frameRateNum, frameRateDen)));
+	addTrack(new Bink2VideoTrack((char)(id & 0xFF), _skipOutsideBlocks, width, height, videoFlags, frameCount, Common::Rational(frameRateNum, frameRateDen)));
 
 	// The maximum packet sizes, then the rate and the flags of each track,
 	// then their IDs
@@ -785,8 +785,8 @@ VideoDecoder::AudioTrack *Bink2Decoder::getAudioTrack(int index) {
 	return (AudioTrack *)track;
 }
 
-Bink2Decoder::Bink2VideoTrack::Bink2VideoTrack(char revision, uint32 width, uint32 height, uint32 flags, uint32 frameCount, const Common::Rational &frameRate) :
-		_revision(revision), _width(width), _height(height), _frameCount(frameCount), _curFrameNumber(-1), _frameRate(frameRate),
+Bink2Decoder::Bink2VideoTrack::Bink2VideoTrack(char revision, bool skipOutsideBlocks, uint32 width, uint32 height, uint32 flags, uint32 frameCount, const Common::Rational &frameRate) :
+		_revision(revision), _skipOutsideBlocks(skipOutsideBlocks && revision == 'f'), _width(width), _height(height), _frameCount(frameCount), _curFrameNumber(-1), _frameRate(frameRate),
 		_surface(nullptr), _curFrame(0), _comp(0), _mbPos(0) {
 	_pixelFormat = Image::Codec::getDefaultYUVFormat();
 
@@ -1511,39 +1511,63 @@ void Bink2Decoder::Bink2VideoTrack::predictMotionVectors(int flags, const Motion
 	}
 }
 
-// Four 16x16 blocks. One that points out of the frame is left as it is.
-void Bink2Decoder::Bink2VideoTrack::compensateLuma(int x, int y, byte *dst, const byte *src, int pitch) {
+// A source position in half pixels, moved back into the frame with room for
+// the filter taps of a half pixel. As in the original, the limits are
+// compared without a sign, so a negative position goes to the far end.
+static int clampSourcePosition(int pos, int limit) {
+	const bool isHalf = (pos & 1) != 0;
+	const uint32 low = isHalf ? 4 : 0;
+	const uint32 high = (uint32)limit - (isHalf ? 42 : 32);
+
+	if ((uint32)pos - low > high)
+		return (uint32)pos < low ? (int)low : (int)high;
+	return pos;
+}
+
+// Where the 16x16 luma block of a macroblock is taken from, in half pixels
+void Bink2Decoder::Bink2VideoTrack::getSourcePosition(int x, int y, int block, int &posX, int &posY) const {
 	const MotionVectors &mv = _currentMV[_mbPos];
 
+	posX = mv.v[block][0] + (x + (block & 1) * 16) * 2;
+	posY = mv.v[block][1] + (y + (block >> 1) * 16) * 2;
+
+	if (!_skipOutsideBlocks) {
+		posX = clampSourcePosition(posX, (int)_width * 2);
+		posY = clampSourcePosition(posY, (int)_height * 2);
+	}
+}
+
+// Four 16x16 blocks. With older decoders, one that starts outside the frame
+// is left as it is.
+void Bink2Decoder::Bink2VideoTrack::compensateLuma(int x, int y, byte *dst, const byte *src, int pitch) {
 	for (int i = 0; i < 4; i++) {
-		const int blockX = x + (i & 1) * 16;
-		const int blockY = y + (i >> 1) * 16;
-		const int srcX = (mv.v[i][0] >> 1) + blockX;
-		const int srcY = (mv.v[i][1] >> 1) + blockY;
+		int posX, posY;
+		getSourcePosition(x, y, i, posX, posY);
+		const int srcX = posX >> 1;
+		const int srcY = posY >> 1;
 
-		if (srcX < 0 || srcX >= (int)_width || srcY < 0 || srcY >= (int)_height)
+		if (_skipOutsideBlocks && (srcX < 0 || srcX >= (int)_width || srcY < 0 || srcY >= (int)_height))
 			continue;
 
-		const int mode = (mv.v[i][0] & 1) | ((mv.v[i][1] & 1) << 1);
-		lumaBlock(dst + blockX + (i >> 1) * 16 * pitch, src + srcX + srcY * pitch, pitch, mode);
+		const int mode = (posX & 1) | ((posY & 1) << 1);
+		lumaBlock(dst + x + (i & 1) * 16 + (i >> 1) * 16 * pitch, src + srcX + srcY * pitch, pitch, mode);
 	}
 }
 
 // Four 8x8 blocks, with the luma vectors in quarter chroma pixels
 void Bink2Decoder::Bink2VideoTrack::compensateChroma(int x, int y, byte *dst, const byte *src, int pitch) {
-	const MotionVectors &mv = _currentMV[_mbPos];
-
 	for (int i = 0; i < 4; i++) {
-		const int blockX = x + (i & 1) * 8;
-		const int blockY = y + (i >> 1) * 8;
-		const int srcX = (mv.v[i][0] >> 2) + blockX;
-		const int srcY = (mv.v[i][1] >> 2) + blockY;
+		// The luma position in half pixels is the chroma one in quarters
+		int posX, posY;
+		getSourcePosition(x * 2, y * 2, i, posX, posY);
+		const int srcX = posX >> 2;
+		const int srcY = posY >> 2;
 
-		if (srcX < 0 || srcX >= (int)_width / 2 || srcY < 0 || srcY >= (int)_height / 2)
+		if (_skipOutsideBlocks && (srcX < 0 || srcX >= (int)_width / 2 || srcY < 0 || srcY >= (int)_height / 2))
 			continue;
 
-		const int mode = (mv.v[i][0] & 3) | ((mv.v[i][1] & 3) << 2);
-		chromaBlock(dst + blockX + (i >> 1) * 8 * pitch, src + srcX + srcY * pitch, pitch, mode);
+		const int mode = (posX & 3) | ((posY & 3) << 2);
+		chromaBlock(dst + x + (i & 1) * 8 + (i >> 1) * 8 * pitch, src + srcX + srcY * pitch, pitch, mode);
 	}
 }
 
diff --git a/video/bink2_decoder.h b/video/bink2_decoder.h
index 636cb0fc3b2..4912470f9ce 100644
--- a/video/bink2_decoder.h
+++ b/video/bink2_decoder.h
@@ -59,7 +59,13 @@ namespace Video {
  */
 class Bink2Decoder : public VideoDecoder {
 public:
-	Bink2Decoder();
+	/**
+	 * @param skipOutsideBlocks  Play revision 'f' as RAD's older decoders do
+	 *                           (Nancy29): a motion block whose source starts
+	 *                           outside the frame is skipped, where newer ones
+	 *                           move its source back into the frame.
+	 */
+	explicit Bink2Decoder(bool skipOutsideBlocks = false);
 	~Bink2Decoder() override;
 
 	bool loadStream(Common::SeekableReadStream *stream) override;
@@ -90,7 +96,7 @@ private:
 	 */
 	class Bink2VideoTrack : public FixedRateVideoTrack {
 	public:
-		Bink2VideoTrack(char revision, uint32 width, uint32 height, uint32 flags, uint32 frameCount, const Common::Rational &frameRate);
+		Bink2VideoTrack(char revision, bool skipOutsideBlocks, uint32 width, uint32 height, uint32 flags, uint32 frameCount, const Common::Rational &frameRate);
 		~Bink2VideoTrack() override;
 
 		uint16 getWidth() const override { return _width; }
@@ -151,6 +157,7 @@ private:
 		};
 
 		char _revision;
+		bool _skipOutsideBlocks;
 
 		uint32 _width;
 		uint32 _height;
@@ -238,6 +245,7 @@ private:
 		void decodeMotionVectors(BitStream &bits, int flags, MotionVectors &mv);
 		void predictMotionVectors(int flags, const MotionVectors &mv);
 		// x and y are in the plane; dst points at the row of the macroblock
+		void getSourcePosition(int x, int y, int block, int &posX, int &posY) const;
 		void compensateLuma(int x, int y, byte *dst, const byte *src, int pitch);
 		void compensateChroma(int x, int y, byte *dst, const byte *src, int pitch);
 
@@ -277,6 +285,7 @@ private:
 	Common::SeekableReadStream *_stream;
 	Common::Array<Frame> _frames;
 	uint32 _audioTrackCount;
+	bool _skipOutsideBlocks;
 
 	uint32 findKeyFrame(uint32 frame) const;
 };


Commit: 294f61036bc8cab9a95c110b61a508976f3dd1fa
    https://github.com/scummvm/scummvm/commit/294f61036bc8cab9a95c110b61a508976f3dd1fa
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:34+02:00

Commit Message:
NANCY: NANCY30: Play the movies named .bk2

Nancy30 names some of its Bink 2 movies .bk2 instead of .bik, e.g. the
idle animations of the characters. They are played when there is no
.bik of the same name.

Changed paths:
    engines/nancy/movieplayer.cpp


diff --git a/engines/nancy/movieplayer.cpp b/engines/nancy/movieplayer.cpp
index cea3a025d6d..6a61dc4564c 100644
--- a/engines/nancy/movieplayer.cpp
+++ b/engines/nancy/movieplayer.cpp
@@ -89,7 +89,12 @@ bool MoviePlayer::loadFile(const Common::Path &name, byte videoPlaytype, bool bi
 	unregisterMovie();
 
 	const Common::Path avfPath = name.append(".avf");
-	const Common::Path bikPath = name.append(".bik");
+	Common::Path bikPath = name.append(".bik");
+
+	// Nancy30 names some of its Bink 2 movies .bk2
+	if (!Common::File::exists(bikPath) && Common::File::exists(name.append(".bk2"))) {
+		bikPath = name.append(".bk2");
+	}
 
 	// Use the requested container, the other one only if its file is missing.
 	const byte preferred = resolvePlaytype(videoPlaytype);


Commit: 4dc65065f919e4a3c8cc972bc0b4a43b71eec775
    https://github.com/scummvm/scummvm/commit/4dc65065f919e4a3c8cc972bc0b4a43b71eec775
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:35+02:00

Commit Message:
NANCY: NANCY30: Read the images marked as type 4

Nancy30 marks about half of its images with type 4 in Ciftree.dat,
which the earlier games use for empty entries. They are images like any
other, e.g. the train overlay of scene 1205, which failed to load.

Changed paths:
    engines/nancy/resource/cif.cpp


diff --git a/engines/nancy/resource/cif.cpp b/engines/nancy/resource/cif.cpp
index c169ea62a47..40d49f9846a 100644
--- a/engines/nancy/resource/cif.cpp
+++ b/engines/nancy/resource/cif.cpp
@@ -145,6 +145,12 @@ static bool syncCifFileNancy18(Common::Serializer &ser, CifInfo &info) {
 	ser.syncAsUint32LE(hasAlpha);
 	ser.syncAsUint32LE(info.size);
 
+	// Nancy30 marks a part of its images with type 4, and they are images
+	// like any other
+	if (ser.isLoading() && info.type == CifInfo::kResTypeEmpty && info.size && g_nancy->getGameType() >= kGameTypeNancy30) {
+		info.type = CifInfo::kResTypeImage;
+	}
+
 	if (info.type == CifInfo::kResTypeImage) {
 		info.depth = hasAlpha ? 32 : 24;
 	} else {


Commit: 8fa2c6e1795d5e0cc8f28bbd7729b3d246de8a21
    https://github.com/scummvm/scummvm/commit/8fa2c6e1795d5e0cc8f28bbd7729b3d246de8a21
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:37+02:00

Commit Message:
NANCY: NANCY19: Don't decode looping movies of one frame again

Nancy30 shows the stills of its opening as looping movies of a single
frame. Each loop decoded that frame again, every time the game updated,
which made the opening slow.

Changed paths:
    engines/nancy/script/records.cpp


diff --git a/engines/nancy/script/records.cpp b/engines/nancy/script/records.cpp
index fe7ac3e1d8c..5f8a35cee48 100644
--- a/engines/nancy/script/records.cpp
+++ b/engines/nancy/script/records.cpp
@@ -2723,6 +2723,12 @@ void MovieRecord::run(double sceneTime, double elapsedTime) {
 	// Another time through
 	++_numPlayed;
 	if (_numLoops == 0 || _numPlayed < _numLoops) {
+		// Nancy30 shows still pictures as looping movies of one frame, which would
+		// be decoded again every time through
+		if (_firstFrame == _lastFrame && _player.getCurrentFrame() == _firstFrame) {
+			return;
+		}
+
 		_player.playRange(_firstFrame, _lastFrame);
 		drawFrame();
 		return;


Commit: 05a968cc748dd6550f50b5e1186418c7a3cbab73
    https://github.com/scummvm/scummvm/commit/05a968cc748dd6550f50b5e1186418c7a3cbab73
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:39+02:00

Commit Message:
NANCY: NANCY30: Open Lua's debug library and add table.keysort

Nancy30 opens Lua's debug library for its scripts. Introspection_SC
reads the local variables and upvalues of a calling function with it,
and Lambda_SC uses that to compile functions from strings that see the
variables of the code that made them. The new collection scripts (Dict,
List, Set, View) filter and sort with these functions.

table.keysort sorts the keys of a table, by parts that are numbers or
strings, and gives them in an array.

Changed paths:
    engines/nancy/script/luastate.cpp


diff --git a/engines/nancy/script/luastate.cpp b/engines/nancy/script/luastate.cpp
index 842cdc31058..486c02fe6af 100644
--- a/engines/nancy/script/luastate.cpp
+++ b/engines/nancy/script/luastate.cpp
@@ -19,6 +19,7 @@
  *
  */
 
+#include "common/array.h"
 #include "common/random.h"
 #include "common/stream.h"
 #include "common/textconsole.h"
@@ -137,6 +138,114 @@ static int tableSort(lua_State *L) {
 	return 1;
 }
 
+// One part of a sort key of table.keysort(). Nils go first, then numbers,
+// then strings; other values count as nil.
+struct KeySortPart {
+	int type = LUA_TNIL;
+	lua_Number number = 0;
+	const char *string = nullptr;
+};
+
+struct KeySortEntry {
+	Common::Array<KeySortPart> parts;
+	int index = 0;
+};
+
+// Reads the value on top of the stack and pops it. The strings stay valid while
+// the table they are in is on the stack.
+static KeySortPart readKeySortPart(lua_State *L) {
+	KeySortPart part;
+	part.type = lua_type(L, -1);
+	if (part.type == LUA_TNUMBER) {
+		part.number = lua_tonumber(L, -1);
+	} else if (part.type == LUA_TSTRING) {
+		part.string = lua_tostring(L, -1);
+	} else {
+		part.type = LUA_TNIL;
+	}
+
+	lua_pop(L, 1);
+	return part;
+}
+
+static int compareKeySortParts(const KeySortPart &a, const KeySortPart &b, bool ignoreCase) {
+	static const int kOrder[] = { 0, 0, 0, 1, 2 };	// by Lua type: nil, -, -, number, string
+	if (kOrder[a.type] != kOrder[b.type]) {
+		return kOrder[a.type] < kOrder[b.type] ? -1 : 1;
+	}
+
+	if (a.type == LUA_TNUMBER) {
+		return a.number < b.number ? -1 : (a.number > b.number ? 1 : 0);
+	}
+
+	if (a.type == LUA_TSTRING) {
+		return ignoreCase ? scumm_stricmp(a.string, b.string) : strcmp(a.string, b.string);
+	}
+
+	return 0;
+}
+
+// Keys compare part by part; a key that runs out of parts first goes first
+static bool keySortsBefore(const KeySortEntry &a, const KeySortEntry &b, bool ignoreCase) {
+	for (uint i = 0; i < a.parts.size(); ++i) {
+		if (i >= b.parts.size()) {
+			return false;
+		}
+
+		const int result = compareKeySortParts(a.parts[i], b.parts[i], ignoreCase);
+		if (result != 0) {
+			return result < 0;
+		}
+	}
+
+	return a.parts.size() < b.parts.size();
+}
+
+// Nancy30's table.keysort(keys, count[, ignoreCase]) sorts the keys 1 to count
+// of the table and gives back their indices in order. A key is a number, a
+// string or an array of them; equal keys keep their order. List:Sort() moves
+// the items of a list with it.
+static int tableKeySort(lua_State *L) {
+	luaL_checktype(L, 1, LUA_TTABLE);
+	const int count = luaL_checkint(L, 2);
+	const bool ignoreCase = lua_gettop(L) > 2 && lua_toboolean(L, 3);
+
+	Common::Array<KeySortEntry> entries;
+	for (int i = 1; i <= count; ++i) {
+		KeySortEntry entry;
+		entry.index = i;
+
+		lua_rawgeti(L, 1, i);
+		if (lua_istable(L, -1)) {
+			const int numParts = lua_objlen(L, -1);
+			for (int j = 1; j <= numParts; ++j) {
+				lua_rawgeti(L, -1, j);
+				entry.parts.push_back(readKeySortPart(L));
+			}
+
+			lua_pop(L, 1);
+		} else {
+			entry.parts.push_back(readKeySortPart(L));
+		}
+
+		// An insertion sort, which keeps equal keys in their order
+		uint position = entries.size();
+		while (position > 0 && keySortsBefore(entry, entries[position - 1], ignoreCase)) {
+			--position;
+		}
+
+		entries.insert_at(position, entry);
+	}
+
+	lua_createtable(L, count > 0 ? count : 0, 0);
+	for (uint i = 0; i < entries.size(); ++i) {
+		lua_pushinteger(L, entries[i].index);
+		lua_rawseti(L, -2, i + 1);
+	}
+
+	return 1;
+}
+
 // Nancy20's math.isnan(number)
 static int mathIsNaN(lua_State *L) {
 	const lua_Number number = luaL_checknumber(L, 1);
@@ -270,6 +379,18 @@ LuaState::LuaState(SceneContext *context) {
 		setLibraryFunction(_state, LUA_STRLIBNAME, "comparenocase", stringCompareNoCase);
 	}
 
+	// Nancy30 has the debug library. Introspection_SC reads the local variables
+	// and upvalues of a calling function with debug.getlocal, debug.getinfo and
+	// debug.getupvalue. Lambda_SC compiles functions from strings that see the
+	// variables of the code that made them, which it gets from
+	// Introspection_SC, and adds debug.traceback to the error when one doesn't
+	// compile. The collection scripts (Dict, List, Set, View) use these
+	// lambdas, e.g. to filter and sort.
+	if (g_nancy->getGameType() >= kGameTypeNancy30) {
+		openLibrary(_state, luaopen_debug, LUA_DBLIBNAME);
+		setLibraryFunction(_state, LUA_TABLIBNAME, "keysort", tableKeySort);
+	}
+
 	removeGlobal(_state, "collectgarbage");
 	removeGlobal(_state, "dofile");
 	removeGlobal(_state, "load");


Commit: a5603ecdcf37933709ecb13b5d41101cf4f2aa15
    https://github.com/scummvm/scummvm/commit/a5603ecdcf37933709ecb13b5d41101cf4f2aa15
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:41+02:00

Commit Message:
NANCY: NANCY30: Add Brain:FilteredNames

The Brain holds the game's conditions, such as Got_INV_Chip_BR.
Brain:FilteredNames(prefix, suffix) gives the names of the ones that
start with the prefix and end with the suffix, whatever their case, as
an array of names in capitals.

Changed paths:
    engines/nancy/script/v5/brain.cpp


diff --git a/engines/nancy/script/v5/brain.cpp b/engines/nancy/script/v5/brain.cpp
index ddba3128715..f0e72a23578 100644
--- a/engines/nancy/script/v5/brain.cpp
+++ b/engines/nancy/script/v5/brain.cpp
@@ -20,6 +20,7 @@
  */
 
 #include "common/textconsole.h"
+#include "common/util.h"
 
 #include "engines/nancy/nancy.h"
 #include "engines/nancy/puzzledata.h"
@@ -309,6 +310,30 @@ static int brainAllNames(lua_State *L) {
 	return 1;
 }
 
+// Brain:FilteredNames(prefix, suffix), Nancy30: an array of the names, in
+// capitals, that start with the prefix and end with the suffix, in any case.
+// The exe only checks that a name is as long as the longer of the two.
+static int brainFilteredNames(lua_State *L) {
+	Common::String prefix = luaL_checkstring(L, 2);
+	Common::String suffix = luaL_checkstring(L, 3);
+	prefix.toUppercase();
+	suffix.toUppercase();
+	const uint minLength = MAX(prefix.size(), suffix.size());
+
+	lua_newtable(L);
+	int count = 0;
+	for (const Common::String &name : getBrain(L).getNames()) {
+		Common::String upperName = name;
+		upperName.toUppercase();
+		if (upperName.size() >= minLength && upperName.hasPrefix(prefix) && upperName.hasSuffix(suffix)) {
+			lua_pushstring(L, upperName.c_str());
+			lua_rawseti(L, -2, ++count);
+		}
+	}
+
+	return 1;
+}
+
 // Brain:Contains(name), Nancy29: whether there is a condition by the name
 static int brainContains(lua_State *L) {
 	lua_pushboolean(L, getBrain(L).exists(luaL_checkstring(L, 2)));
@@ -404,6 +429,7 @@ void registerBrainAPI(lua_State *L) {
 		{ "__newindex", brainNewIndex },
 		{ "AllNames", brainAllNames },
 		{ "Contains", brainContains },
+		{ "FilteredNames", brainFilteredNames },
 		{ "IsAutoUpdated", brainIsAutoUpdated },
 		{ "IsCached", brainIsCached },
 		{ "IsWritable", brainIsWritable },


Commit: 5ba20bc62909bed396f637993a7bd2f367b0c98f
    https://github.com/scummvm/scummvm/commit/5ba20bc62909bed396f637993a7bd2f367b0c98f
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:43+02:00

Commit Message:
NANCY: NANCY30: Add the smaller additions to the script API

- Game.isSidecar and Game.hasSidecar are always false. They tell whether
  the game runs with Sidecar, a developers' tool that starts and stops
  it. Game.exeName, the name of the exe that Sidecar starts again, is
  empty.
- Game:ShowLink(url, true) opens the URL it is given, instead of looking
  it up in the autotext entries
- point.len is the distance of a point from the origin
- Key.BACKTICK

Changed paths:
    engines/nancy/script/gameapi.cpp
    engines/nancy/script/types.cpp
    engines/nancy/script/v5/gamefunctions.cpp


diff --git a/engines/nancy/script/gameapi.cpp b/engines/nancy/script/gameapi.cpp
index 3e544618344..0c1c6eb537a 100644
--- a/engines/nancy/script/gameapi.cpp
+++ b/engines/nancy/script/gameapi.cpp
@@ -387,6 +387,7 @@ static const KeyName kKeyNames[] = {
 	{ "CTRL", Common::KEYCODE_LCTRL },
 	{ "SHIFT", Common::KEYCODE_LSHIFT },
 	{ "BACKSPACE", Common::KEYCODE_BACKSPACE },	// Nancy20
+	{ "BACKTICK", Common::KEYCODE_BACKQUOTE },	// Nancy30
 	{ "NUMPAD0", Common::KEYCODE_KP0 },
 	{ "NUMPAD1", Common::KEYCODE_KP1 },
 	{ "NUMPAD2", Common::KEYCODE_KP2 },
@@ -448,13 +449,16 @@ static const luaL_Reg kKeyFunctions[] = {
 static const uint kDifficultyJunior = 0;
 static const uint kDifficultySenior = 2;
 
-// Game:ShowLink(key), Nancy25: opens the URL in the autotext entry for the
-// key in a web browser. Returns whether it was opened.
+// Game:ShowLink(key[, isDirect]), Nancy25: opens the URL in the autotext entry
+// for the key in a web browser. Returns whether it was opened. Nancy30 takes
+// the key as the URL itself when isDirect is set.
 static int gameShowLink(lua_State *L) {
 	const char *key = luaL_checkstring(L, 2);
 
 	Common::String url;
-	if (!findText(key, url)) {
+	if (lua_gettop(L) > 2 && lua_toboolean(L, 3)) {
+		url = key;
+	} else if (!findText(key, url)) {
 		return luaL_error(L, "Autotext '%s' not found", key);
 	}
 
diff --git a/engines/nancy/script/types.cpp b/engines/nancy/script/types.cpp
index 0888d553e6e..da7cac9dd2d 100644
--- a/engines/nancy/script/types.cpp
+++ b/engines/nancy/script/types.cpp
@@ -549,6 +549,9 @@ static int pointIndex(lua_State *L) {
 		lua_pushnumber(L, point.x);
 	} else if (key == "y") {
 		lua_pushnumber(L, point.y);
+	} else if (key == "len") {
+		// Nancy30: the distance from the origin
+		lua_pushnumber(L, sqrt(point.x * point.x + point.y * point.y));
 	} else {
 		return indexFunctions(L);
 	}
diff --git a/engines/nancy/script/v5/gamefunctions.cpp b/engines/nancy/script/v5/gamefunctions.cpp
index d0cd259cba1..2a64e9a1757 100644
--- a/engines/nancy/script/v5/gamefunctions.cpp
+++ b/engines/nancy/script/v5/gamefunctions.cpp
@@ -453,6 +453,14 @@ static bool pushGameField(lua_State *L, const Common::String &key) {
 		// Nancy29: the DebugOutput setting of the game's INI file, which the
 		// release has switched off. The cheat tools need it for the inspector.
 		lua_pushboolean(L, false);
+	} else if (key == "isSidecar" || key == "hasSidecar") {
+		// Nancy30: whether the exe runs as, or next to, the developers' Sidecar
+		// tool, which starts and stops the game. Never in the release.
+		lua_pushboolean(L, false);
+	} else if (key == "exeName") {
+		// Nancy30: the name of the exe file, which only Sidecar_Main_SC uses
+		// to start the game again
+		lua_pushstring(L, "");
 	} else if (key == "buildNumber") {
 		const ScriptBootData *boot = GetEngineData(ScriptBootData);
 		lua_pushstring(L, boot ? boot->buildNumber.c_str() : "");


Commit: 3279c17d3f49affd0724dc8490d4d667ab711a67
    https://github.com/scummvm/scummvm/commit/3279c17d3f49affd0724dc8490d4d667ab711a67
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:44+02:00

Commit Message:
NANCY: NANCY30: Show the first frame of a movie as an overlay

Overlays whose picture is named like a movie (ending in _BG, _ANIM or
_CNV) show the first frame of that movie, e.g. the close-ups of the
inventory pages.

Changed paths:
    engines/nancy/script/records.cpp


diff --git a/engines/nancy/script/records.cpp b/engines/nancy/script/records.cpp
index 5f8a35cee48..fa350a86260 100644
--- a/engines/nancy/script/records.cpp
+++ b/engines/nancy/script/records.cpp
@@ -1301,6 +1301,31 @@ bool loadTreeImage(const Common::String &name, const Common::String &treeName, G
 #endif
 }
 
+// Nancy30 takes the picture of an overlay from the first frame of a movie
+// when its name says it's one: a background, an animation or a conversation
+static bool isMovieName(const Common::String &name) {
+	if (g_nancy->getGameType() < kGameTypeNancy30) {
+		return false;
+	}
+
+	Common::String upperName = name;
+	upperName.toUppercase();
+	return upperName.hasSuffix("_BG") || upperName.hasSuffix("_ANIM") || upperName.hasSuffix("_CNV");
+}
+
+static bool loadMovieFrame(const Common::String &name, Graphics::ManagedSurface &image) {
+	MoviePlayer player;
+	if (!player.loadFile(Common::Path(name))) {
+		return false;
+	}
+
+	player.goToFrame(0);
+	image.create(player.getWidth(), player.getHeight(), g_nancy->_graphics->getInputPixelFormat(32));
+	image.clear(image.format.ARGBToColor(255, 0, 0, 0));
+	player.drawFrame(image, Common::Point(0, 0));
+	return true;
+}
+
 // Overlays get their pictures from the image cache of the resource manager,
 // and hold on to the cached picture while they use it. Saved pictures aren't
 // cached: every record has its own.
@@ -1311,6 +1336,12 @@ bool loadCachedImage(const Common::String &name, const Common::String &treeName,
 		return loadTreeImage(name, treeName, image);
 	}
 
+	if (isMovieName(name)) {
+		image.free();
+		cached.reset();
+		return loadMovieFrame(name, image);
+	}
+
 	cached = g_nancy->_resource->loadCachedImage(name, treeName);
 	if (!cached) {
 		return false;


Commit: 9f7ac74ee9d561fb415cef0a2c119b0daa01d59f
    https://github.com/scummvm/scummvm/commit/9f7ac74ee9d561fb415cef0a2c119b0daa01d59f
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:46+02:00

Commit Message:
NANCY: NANCY30: Add Overlay:DefaultRects

overlay:DefaultRects() shows the whole picture of an overlay at the top
left of the screen, dropping the source and destination rects it had.

Changed paths:
    engines/nancy/script/records.cpp
    engines/nancy/script/records.h


diff --git a/engines/nancy/script/records.cpp b/engines/nancy/script/records.cpp
index fa350a86260..a2ebc706731 100644
--- a/engines/nancy/script/records.cpp
+++ b/engines/nancy/script/records.cpp
@@ -1622,6 +1622,22 @@ int drawOverlay(lua_State *L) {
 	return 0;
 }
 
+void OverlayRecord::setDefaultRects() {
+	_source = ScriptRect(0, 0, _image.w, _image.h);
+	_dest = _source;
+	_hasDestTable = false;
+	applyRects();
+}
+
+static int overlayDefaultRects(lua_State *L) {
+	OverlayRecord *record = dynamic_cast<OverlayRecord *>(checkRecord(L, 1));
+	if (record) {
+		record->setDefaultRects();
+	}
+
+	return 0;
+}
+
 bool OverlayRecord::getField(const Common::String &key) {
 	lua_State *L = getLua();
 
@@ -1639,6 +1655,8 @@ bool OverlayRecord::getField(const Common::String &key) {
 		lua_pushstring(L, _imageName.c_str());
 	} else if (key == "tree") {
 		lua_pushstring(L, _treeName.c_str());
+	} else if (key == "DefaultRects") {
+		lua_pushcfunction(L, overlayDefaultRects);
 	} else {
 		return false;
 	}
diff --git a/engines/nancy/script/records.h b/engines/nancy/script/records.h
index 219a713a2f8..8f95e8ca249 100644
--- a/engines/nancy/script/records.h
+++ b/engines/nancy/script/records.h
@@ -291,6 +291,10 @@ public:
 	// transform and modColor.
 	void drawCopy(int tableIndex);
 
+	// Nancy30: ar:DefaultRects() shows the whole picture at the top left, as
+	// when neither the source nor onScreen was given
+	void setDefaultRects();
+
 protected:
 	void readTable(int tableIndex) override;
 	void onZChanged() override;


Commit: c03e6bfd981ea3268bb7f37cee6fb2d6a8b9ef29
    https://github.com/scummvm/scummvm/commit/c03e6bfd981ea3268bb7f37cee6fb2d6a8b9ef29
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:48+02:00

Commit Message:
NANCY: NANCY30: Make the onScreen rect of Movie records optional

A movie without an onScreen rect, or with an empty one, is shown whole
at the top left of the screen.

Changed paths:
    engines/nancy/script/records.cpp


diff --git a/engines/nancy/script/records.cpp b/engines/nancy/script/records.cpp
index a2ebc706731..003aedbb0ff 100644
--- a/engines/nancy/script/records.cpp
+++ b/engines/nancy/script/records.cpp
@@ -2579,17 +2579,26 @@ void MovieRecord::readTable(int tableIndex) {
 		luaL_error(L, "MovieAR must be created with a movie parameter");
 	}
 
-	if (!pushField(L, tableIndex, "onScreen")) {
+	// Nancy30 shows the whole movie at the top left without an onScreen, or
+	// with an empty one
+	const bool hasDest = pushField(L, tableIndex, "onScreen");
+	if (!hasDest && g_nancy->getGameType() < kGameTypeNancy30) {
 		luaL_error(L, "MovieAR must be created with an 'onScreen' parameter");
 	}
 
-	_dest = checkRect(L, -1);
-	lua_pop(L, 1);
+	if (hasDest) {
+		_dest = checkRect(L, -1);
+		lua_pop(L, 1);
+	}
 
 	if (!_player.loadFile(Common::Path(_name))) {
 		luaL_error(L, "Could not load movie %s", _name.c_str());
 	}
 
+	if (g_nancy->getGameType() >= kGameTypeNancy30 && _dest.isEmpty()) {
+		_dest = ScriptRect(0, 0, _player.getWidth(), _player.getHeight());
+	}
+
 	_firstFrame = 0;
 	_lastFrame = _player.getFrameCount() - 1;
 	readField(L, tableIndex, "firstFrame", _firstFrame);


Commit: b9b52dd1b0a1e6294d245d6c4065d2dc4fcb60db
    https://github.com/scummvm/scummvm/commit/b9b52dd1b0a1e6294d245d6c4065d2dc4fcb60db
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:49+02:00

Commit Message:
NANCY: NANCY30: Tell Sound records when an instance has ended

Sounds started with Sound:PlayInstance play beside the record's own.
When one of them ends, the record's OnInstanceDone function is called.
This is checked every frame, even while the record is inactive. A
"silence" instance ends at once.

Changed paths:
    engines/nancy/script/record.cpp
    engines/nancy/script/record.h
    engines/nancy/script/records.cpp
    engines/nancy/script/records.h
    engines/nancy/sound.cpp
    engines/nancy/sound.h


diff --git a/engines/nancy/script/record.cpp b/engines/nancy/script/record.cpp
index 19b918ab0e0..4409a32c159 100644
--- a/engines/nancy/script/record.cpp
+++ b/engines/nancy/script/record.cpp
@@ -235,6 +235,8 @@ void Record::onObjectCollected() {
 }
 
 void Record::update(double sceneTime, double elapsedTime) {
+	onFrame();
+
 #ifdef ENABLE_NANCY_V5
 	if (_nodeState) {
 		updateNode(sceneTime, elapsedTime);
diff --git a/engines/nancy/script/record.h b/engines/nancy/script/record.h
index 2ee60d84201..711e15832fc 100644
--- a/engines/nancy/script/record.h
+++ b/engines/nancy/script/record.h
@@ -337,6 +337,9 @@ protected:
 	// What the record does when no script took its place
 	virtual void runOnce() {}
 	virtual void run(double sceneTime, double elapsedTime) {}
+
+	// Called every frame, whether the record is active or not
+	virtual void onFrame() {}
 	virtual void onActivation() {}
 	virtual void onDeactivation() {}
 	virtual void onZChanged() {}
diff --git a/engines/nancy/script/records.cpp b/engines/nancy/script/records.cpp
index 003aedbb0ff..db096094996 100644
--- a/engines/nancy/script/records.cpp
+++ b/engines/nancy/script/records.cpp
@@ -2064,7 +2064,26 @@ void SoundRecord::playInstance() {
 
 	const Common::String &name = _names[g_nancy->_randomSource->getRandomNumber(_names.size() - 1)];
 	const double volume = CLIP(vary(_volume, _volumeVariance), 0.0, 1.0);
-	g_nancy->_sound->playInstance(name, type, (uint16)(volume * 100.0), MAX(vary(_pitch, _pitchVariance), 0.01));
+	Audio::SoundHandle handle;
+	if (g_nancy->_sound->playInstance(name, type, (uint16)(volume * 100.0), MAX(vary(_pitch, _pitchVariance), 0.01), handle)) {
+		_instances.push_back(handle);
+	}
+}
+
+void SoundRecord::onFrame() {
+	uint numDone = 0;
+	for (uint i = 0; i < _instances.size(); ) {
+		if (g_nancy->_sound->isInstancePlaying(_instances[i])) {
+			++i;
+		} else {
+			_instances.remove_at(i);
+			++numDone;
+		}
+	}
+
+	for (uint i = 0; i < numDone; ++i) {
+		callFunction("OnInstanceDone");
+	}
 }
 
 void SoundRecord::readChannelType(int index) {
diff --git a/engines/nancy/script/records.h b/engines/nancy/script/records.h
index 8f95e8ca249..3c5cae565f9 100644
--- a/engines/nancy/script/records.h
+++ b/engines/nancy/script/records.h
@@ -398,12 +398,14 @@ public:
 
 	// Nancy29: plays one of the sounds once, without a channel, so that it can
 	// overlap other sounds. The group of the record selects its volume setting.
+	// Nancy30 calls OnInstanceDone when one of them has ended.
 	void playInstance();
 
 protected:
 	void readTable(int tableIndex) override;
 	void runOnce() override;
 	void run(double sceneTime, double elapsedTime) override;
+	void onFrame() override;
 	bool prepareReset() override;
 	bool getField(const Common::String &key) override;
 	bool setField(const Common::String &key) override;
@@ -438,6 +440,7 @@ private:
 	double _playVolume = 1.0;
 	double _playPitch = 1.0;
 	bool _isLooping = false;
+	Common::Array<Audio::SoundHandle> _instances;	// the ones playInstance() started
 	bool _usesCaption = true;
 
 	SoundDescription _sound;
diff --git a/engines/nancy/sound.cpp b/engines/nancy/sound.cpp
index b7aa846ecdc..21eead0909b 100644
--- a/engines/nancy/sound.cpp
+++ b/engines/nancy/sound.cpp
@@ -765,7 +765,7 @@ Audio::Timestamp SoundManager::getLength(const Common::String &chunkName) {
 	return getLength(_commonSounds[chunkName]);
 }
 
-void SoundManager::playInstance(const Common::String &soundName, Audio::Mixer::SoundType type, uint16 volume, double pitch) {
+bool SoundManager::playInstance(const Common::String &soundName, Audio::Mixer::SoundType type, uint16 volume, double pitch, Audio::SoundHandle &handle) {
 	for (uint i = 0; i < _instances.size(); ) {
 		if (_mixer->isSoundHandleActive(_instances[i])) {
 			++i;
@@ -774,22 +774,32 @@ void SoundManager::playInstance(const Common::String &soundName, Audio::Mixer::S
 		}
 	}
 
+	// Silence is played, and over at once
+	if (soundName == "silence") {
+		handle = Audio::SoundHandle();
+		return true;
+	}
+
 	Common::SeekableReadStream *file = SearchMan.createReadStreamForMember(Common::Path(soundName + ".his"));
 	if (!file) {
 		warning("Sound %s file failed to open", soundName.c_str());
-		return;
+		return false;
 	}
 
 	Audio::SeekableAudioStream *stream = makeHISStream(file, DisposeAfterUse::YES);
 	if (!stream) {
-		return;
+		return false;
 	}
 
 	const uint32 rate = stream->getRate();
-	Audio::SoundHandle handle;
 	_mixer->playStream(type, &handle, stream, -1, (int)getAdjustedVolume(volume) * 255 / 100, 0, DisposeAfterUse::YES);
 	_mixer->setChannelRate(handle, (uint32)(rate * pitch));
 	_instances.push_back(handle);
+	return true;
+}
+
+bool SoundManager::isInstancePlaying(const Audio::SoundHandle &handle) const {
+	return _mixer->isSoundHandleActive(handle);
 }
 
 Audio::Timestamp SoundManager::getFileLength(const Common::String &soundName) {
diff --git a/engines/nancy/sound.h b/engines/nancy/sound.h
index bd8fd686ceb..18dbae7fde4 100644
--- a/engines/nancy/sound.h
+++ b/engines/nancy/sound.h
@@ -131,8 +131,9 @@ public:
 
 	// Nancy29: plays a sound once, without a channel, so that several copies of
 	// it can overlap. The volume goes from 0 to 100, and a pitch of 2 plays the
-	// sound twice as fast.
-	void playInstance(const Common::String &soundName, Audio::Mixer::SoundType type, uint16 volume, double pitch);
+	// sound twice as fast. Returns false when the sound couldn't be played.
+	bool playInstance(const Common::String &soundName, Audio::Mixer::SoundType type, uint16 volume, double pitch, Audio::SoundHandle &handle);
+	bool isInstancePlaying(const Audio::SoundHandle &handle) const;
 
 	Audio::Timestamp getLength(uint16 channelID);
 	Audio::Timestamp getLength(const SoundDescription &description);


Commit: 6594d1aaf42d6fb4a7d54dc2bf472419655db6c4
    https://github.com/scummvm/scummvm/commit/6594d1aaf42d6fb4a7d54dc2bf472419655db6c4
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:51+02:00

Commit Message:
NANCY: NANCY30: Add the tiles of Hotspot records

A hotspot with a tileSize splits its rect into tiles of that size.
While the mouse is over it, or holds it down, cursorTile tells which
tile the mouse is on, counting from 1, and OnTileChanged is called when
that changes.

Used by the star puzzle of scene 2032.

Changed paths:
    engines/nancy/script/v5/scriptinput.cpp
    engines/nancy/script/v5/widgets.cpp
    engines/nancy/script/v5/widgets.h


diff --git a/engines/nancy/script/v5/scriptinput.cpp b/engines/nancy/script/v5/scriptinput.cpp
index 86399080b42..634b8362076 100644
--- a/engines/nancy/script/v5/scriptinput.cpp
+++ b/engines/nancy/script/v5/scriptinput.cpp
@@ -424,6 +424,8 @@ void handleNancy26Input(NancyInput &input) {
 			record->callFunction("OnNewFrame");
 		} else if (hasMoved && record->getType() == kRecordSummary) {
 			record->sendMouseMove(state.mouse, true);
+		} else if (hasMoved && record->getType() == kRecordHotspot) {
+			static_cast<HotspotRecord *>(record)->onMouseMoved(state.mouse);
 		}
 	}
 
diff --git a/engines/nancy/script/v5/widgets.cpp b/engines/nancy/script/v5/widgets.cpp
index 78d79b0f9ab..ae8ce0c3aa1 100644
--- a/engines/nancy/script/v5/widgets.cpp
+++ b/engines/nancy/script/v5/widgets.cpp
@@ -133,6 +133,39 @@ void HotspotRecord::readTable(int tableIndex) {
 		_source = checkRect(L, -1);
 		lua_pop(L, 1);
 	}
+
+	if (pushField(L, tableIndex, "tileSize")) {
+		readPointCoordinates(L, -1, _tileSize[0], _tileSize[1]);
+		lua_pop(L, 1);
+	}
+}
+
+void HotspotRecord::onMouseMoved(const Common::Point32 &mouse) {
+	updateCursorTile(&mouse);
+}
+
+// The tile is where the mouse is in the rect of the hotspot, before the
+// hotspot was moved, divided by the tile size. Without a mouse, there is none.
+void HotspotRecord::updateCursorTile(const Common::Point32 *mouse) {
+	bool hasTile = false;
+	Common::Point32 tile;
+	if (mouse && _tileSize[0] > 0.0 && _tileSize[1] > 0.0 && (_isMouseOver || isDown())) {
+		double x = mouse->x;
+		double y = mouse->y;
+		getTransform().inverse().transformPoint(x, y);
+
+		hasTile = true;
+		tile.x = (int32)floor((x - _onScreen.left) / _tileSize[0]) + 1;
+		tile.y = (int32)floor((y - _onScreen.top) / _tileSize[1]) + 1;
+	}
+
+	if (hasTile == _hasCursorTile && (!hasTile || tile == _cursorTile)) {
+		return;
+	}
+
+	_hasCursorTile = hasTile;
+	_cursorTile = tile;
+	callFunction("OnTileChanged");
 }
 
 bool HotspotRecord::hitTest(const Common::Point32 &point) const {
@@ -228,6 +261,7 @@ void HotspotRecord::releaseRegion(int button) {
 	_pressedButton = -1;
 
 	if (!_isMouseOver) {
+		updateCursorTile(nullptr);
 		callFunction("OnLoseMouseFocus");
 		if (_widget) {
 			_widget->onHotspotUp(button, false);
@@ -315,6 +349,14 @@ bool HotspotRecord::getField(const Common::String &key) {
 		lua_pushstring(L, _tooltip.c_str());
 	} else if (key == "tooltipManager") {
 		lua_pushstring(L, _tooltipManager.c_str());
+	} else if (key == "tileSize") {
+		pushPoint(L, Common::Point32((int32)_tileSize[0], (int32)_tileSize[1]));
+	} else if (key == "cursorTile") {
+		if (_hasCursorTile) {
+			pushPoint(L, _cursorTile);
+		} else {
+			lua_pushnil(L);
+		}
 	} else {
 		return false;
 	}
@@ -366,6 +408,11 @@ bool HotspotRecord::setField(const Common::String &key) {
 		if (_isMouseOver) {
 			sendTooltip(true);
 		}
+	} else if (key == "tileSize") {
+		readPointCoordinates(L, 3, _tileSize[0], _tileSize[1]);
+		updateCursorTile(&getScriptMousePoint());
+	} else if (key == "cursorTile") {
+		luaL_error(L, "Cannot set 'cursorTile' field of a hotspot");
 	} else {
 		return false;
 	}
diff --git a/engines/nancy/script/v5/widgets.h b/engines/nancy/script/v5/widgets.h
index c62a04eaf9b..d0a19b88db3 100644
--- a/engines/nancy/script/v5/widgets.h
+++ b/engines/nancy/script/v5/widgets.h
@@ -63,6 +63,9 @@ public:
 	bool isDown() const { return _pressedButton >= 0; }
 	const ScriptRect &getOnScreen() const { return _onScreen; }
 
+	// Nancy30: the mouse moved, which can put it over another tile
+	void onMouseMoved(const Common::Point32 &mouse);
+
 protected:
 	void readTable(int tableIndex) override;
 	bool prepareReset() override;
@@ -81,6 +84,7 @@ private:
 	void pushCursorField(const Cursor &cursor);
 	void fire();
 	void sendTooltip(bool isShown);
+	void updateCursorTile(const Common::Point32 *mouse);
 
 	ScriptRect _onScreen;
 	Common::String _sceneName;
@@ -108,6 +112,13 @@ private:
 	// mouse is over the hotspot
 	Common::String _tooltip;
 	Common::String _tooltipManager = "Tooltip";
+
+	// Nancy30. A hotspot with a tile size splits its rect into tiles, and
+	// knows the one the mouse is over, counting from 1, while the mouse is
+	// over it or holds it down. OnTileChanged is called when that changes.
+	double _tileSize[2] = { 0.0, 0.0 };
+	bool _hasCursorTile = false;
+	Common::Point32 _cursorTile;
 };
 
 // Nancy26: catches the player's input in a part of the screen, so whatever is


Commit: b0f000a7231076812e0522bb484c20a50f5db7eb
    https://github.com/scummvm/scummvm/commit/b0f000a7231076812e0522bb484c20a50f5db7eb
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:53+02:00

Commit Message:
NANCY: NANCY30: Add the steps of Slider records

The knob of a slider with a knobStep stops only at multiples of it, the
nearest one to where it is dragged.

Used by the depth gauge of the submarine puzzle, which has 3 levels.

Changed paths:
    engines/nancy/script/v5/widgets.cpp
    engines/nancy/script/v5/widgets.h


diff --git a/engines/nancy/script/v5/widgets.cpp b/engines/nancy/script/v5/widgets.cpp
index ae8ce0c3aa1..2db769018ed 100644
--- a/engines/nancy/script/v5/widgets.cpp
+++ b/engines/nancy/script/v5/widgets.cpp
@@ -753,6 +753,11 @@ void SliderRecord::readTable(int tableIndex) {
 		lua_pop(L, 1);
 	}
 
+	if (pushField(L, tableIndex, "knobStep")) {
+		readPoint(L, -1, _knobStep);
+		lua_pop(L, 1);
+	}
+
 	if (pushField(L, tableIndex, "knobPos")) {
 		readPoint(L, -1, _knobPos);
 		lua_pop(L, 1);
@@ -785,9 +790,19 @@ Common::Point32 SliderRecord::getKnobMax() const {
 	return Common::Point32(MAX<int>(0, _knobArea.width() - knobSize.x), MAX<int>(0, _knobArea.height() - knobSize.y));
 }
 
+// The nearest multiple of the step, halves rounded up
+static int32 snapToStep(int32 value, int32 step) {
+	if (step <= 0) {
+		return value;
+	}
+
+	return (int32)floor((double)value / step + 0.5) * step;
+}
+
 void SliderRecord::setKnobPos(const Common::Point32 &pos, bool callsScripts) {
 	const Common::Point32 knobMax = getKnobMax();
-	const Common::Point32 newPos(CLIP<int>(pos.x, 0, knobMax.x), CLIP<int>(pos.y, 0, knobMax.y));
+	const Common::Point32 newPos(snapToStep(CLIP<int>(pos.x, 0, knobMax.x), _knobStep.x),
+		snapToStep(CLIP<int>(pos.y, 0, knobMax.y), _knobStep.y));
 
 	const bool hasMoved = newPos.x != _knobPos.x || newPos.y != _knobPos.y;
 	_knobPos = newPos;
@@ -891,6 +906,8 @@ bool SliderRecord::getField(const Common::String &key) {
 		pushPoint(L, _knobPos);
 	} else if (key == "knobMax") {
 		pushPoint(L, getKnobMax());
+	} else if (key == "knobStep") {
+		pushPoint(L, _knobStep);
 	} else if (key == "percent") {
 		const Common::Point32 knobMax = getKnobMax();
 		pushVector(L, ScriptVector(knobMax.x > 0 ? (double)_knobPos.x / knobMax.x : 0.0,
@@ -916,6 +933,8 @@ bool SliderRecord::setField(const Common::String &key) {
 	} else if (key == "knobArea") {
 		_knobArea = checkRect(L, 3);
 		setKnobPos(_knobPos, false);
+	} else if (key == "knobStep") {
+		luaL_error(L, "Cannot set field 'knobStep' of a slider AR");
 	} else {
 		return WidgetRecord::setField(key);
 	}
diff --git a/engines/nancy/script/v5/widgets.h b/engines/nancy/script/v5/widgets.h
index d0a19b88db3..9bd65597d90 100644
--- a/engines/nancy/script/v5/widgets.h
+++ b/engines/nancy/script/v5/widgets.h
@@ -231,6 +231,7 @@ private:
 	ScriptRect _scrollArea;
 	Common::Point32 _scrollAmount;
 	Common::Point32 _knobPos;
+	Common::Point32 _knobStep = Common::Point32(1, 1);	// Nancy30: the knob stops at multiples of it
 	Common::Point32 _dragOffset;	// from the knob to the mouse, while dragged
 	bool _isDragging = false;
 };


Commit: 8dabdf11297ce246eb2fba8309f1aa2009e0098f
    https://github.com/scummvm/scummvm/commit/8dabdf11297ce246eb2fba8309f1aa2009e0098f
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:55+02:00

Commit Message:
NANCY: NANCY30: Call the OnDone function of animator stages

In Nancy30, an animator stage that finishes calls its own OnDone
function, with the stage, instead of the record's Stage<n>Done. Scripts
can also store their own fields in a stage, as they do for OnDone.

Used by the animation that opens the cell phone, and by many puzzles.

Changed paths:
    engines/nancy/script/v5/animator.cpp
    engines/nancy/script/v5/animator.h


diff --git a/engines/nancy/script/v5/animator.cpp b/engines/nancy/script/v5/animator.cpp
index 7c184977034..b6bfdd46230 100644
--- a/engines/nancy/script/v5/animator.cpp
+++ b/engines/nancy/script/v5/animator.cpp
@@ -22,8 +22,12 @@
 #include "common/textconsole.h"
 #include "common/util.h"
 
+#include "engines/nancy/nancy.h"
+
 #include "engines/nancy/script/luabind.h"
+#include "engines/nancy/script/luastate.h"
 #include "engines/nancy/script/record.h"
+#include "engines/nancy/script/scenecontext.h"
 
 #include "engines/nancy/script/v5/animator.h"
 
@@ -232,6 +236,27 @@ AnimatorStage::~AnimatorStage() {
 	for (AnimatorTrack *track : _tracks) {
 		delete track;
 	}
+
+	// Drops what scripts stored in the stage, the way the exe keeps it: in the
+	// registry, under the stage
+	lua_State *L = _animator.getOwner().getContext().getLua();
+	lua_pushlightuserdata(L, this);
+	lua_pushnil(L);
+	lua_rawset(L, LUA_REGISTRYINDEX);
+}
+
+void AnimatorStage::pushFields(lua_State *L) {
+	lua_pushlightuserdata(L, this);
+	lua_rawget(L, LUA_REGISTRYINDEX);
+	if (lua_istable(L, -1)) {
+		return;
+	}
+
+	lua_pop(L, 1);
+	lua_newtable(L);
+	lua_pushlightuserdata(L, this);
+	lua_pushvalue(L, -2);
+	lua_rawset(L, LUA_REGISTRYINDEX);
 }
 
 bool AnimatorStage::isBlending() const {
@@ -404,12 +429,35 @@ void Animator::onStageDone(uint index) {
 	_doneStages.push_back(index);
 }
 
+static void pushStageRef(lua_State *L, Record &record, uint stage);
+
 void Animator::callDoneFunctions() {
 	const Common::Array<uint> doneStages = _doneStages;
 	_doneStages.clear();
 
 	for (uint index : doneStages) {
-		_owner.callFunction(Common::String::format("Stage%uDone", index).c_str());
+		if (g_nancy->getGameType() < kGameTypeNancy30) {
+			_owner.callFunction(Common::String::format("Stage%uDone", index).c_str());
+			continue;
+		}
+
+		// Nancy30: stage.OnDone(stage)
+		AnimatorStage *stage = getStage(index);
+		if (!stage) {
+			continue;
+		}
+
+		lua_State *L = _owner.getContext().getLua();
+		stage->pushFields(L);
+		lua_getfield(L, -1, "OnDone");
+		lua_remove(L, -2);
+		if (!lua_isfunction(L, -1)) {
+			lua_pop(L, 1);
+			continue;
+		}
+
+		pushStageRef(L, _owner, index);
+		LuaState::call(L, 1, 0, "Error running the OnDone of an animator stage");
 	}
 }
 
@@ -438,6 +486,10 @@ static void pushRef(lua_State *L, Record &record, const char *typeName, uint sta
 	lua_setfenv(L, -2);
 }
 
+static void pushStageRef(lua_State *L, Record &record, uint stage) {
+	pushRef(L, record, kAnimatorStageType, stage, -1);
+}
+
 void Animator::push(lua_State *L) {
 	pushRef(L, _owner, kAnimatorType, 0, -1);
 }
@@ -575,11 +627,21 @@ static bool findTrackKind(const char *name, AnimatorTrack::Kind &kind) {
 	return false;
 }
 
-// stage.a, stage.s, stage.r and stage.t are its tracks
+// stage.a, stage.s, stage.r and stage.t are its tracks. In Nancy30, other
+// names give what scripts stored in the stage.
 static int stageIndex(lua_State *L) {
 	AnimatorTrack::Kind kind;
 	if (lua_type(L, 2) != LUA_TSTRING || !findTrackKind(lua_tostring(L, 2), kind)) {
-		return indexFunctions(L);
+		indexFunctions(L);
+		if (lua_isnil(L, -1) && g_nancy->getGameType() >= kGameTypeNancy30) {
+			lua_pop(L, 1);
+			checkStage(L).pushFields(L);
+			lua_pushvalue(L, 2);
+			lua_rawget(L, -2);
+			lua_remove(L, -2);
+		}
+
+		return 1;
 	}
 
 	const AnimatorRef &ref = *(AnimatorRef *)checkUserData(L, 1, kAnimatorStageType);
@@ -588,14 +650,23 @@ static int stageIndex(lua_State *L) {
 	return 1;
 }
 
-// stage.t = value sets a track to a value
+// stage.t = value sets a track to a value. Nancy30 stores anything else in
+// the stage, like its OnDone function.
 static int stageNewIndex(lua_State *L) {
 	static const char *const kTrackDescriptions[] = { "Alpha", "Scale", "Rotation", "Translation" };
 
 	AnimatorStage &stage = checkStage(L);
 	AnimatorTrack::Kind kind;
 	if (!findTrackKind(luaL_checkstring(L, 2), kind)) {
-		return luaL_error(L, "Cannot set field '%s' of an animator stage", lua_tostring(L, 2));
+		if (g_nancy->getGameType() < kGameTypeNancy30) {
+			return luaL_error(L, "Cannot set field '%s' of an animator stage", lua_tostring(L, 2));
+		}
+
+		stage.pushFields(L);
+		lua_pushvalue(L, 2);
+		lua_pushvalue(L, 3);
+		lua_rawset(L, -3);
+		return 0;
 	}
 
 	AnimatorTrack &track = stage.getTrack(kind);
diff --git a/engines/nancy/script/v5/animator.h b/engines/nancy/script/v5/animator.h
index e8d104211c2..c8d3a348194 100644
--- a/engines/nancy/script/v5/animator.h
+++ b/engines/nancy/script/v5/animator.h
@@ -46,7 +46,8 @@ class AnimatorStage;
 // each one moving it to a target value. A lerp blend moves at a constant
 // speed, while a "slerp" blend starts and ends slowly. When all tracks of a
 // stage have finished blending, the record's "Stage<n>Done" function is
-// called.
+// called. Nancy30 calls the stage's own OnDone function instead, which
+// scripts store in the stage like any other field (ar.animator[1].OnDone).
 //
 // The record's transform is the product of the transforms of the stages, in
 // order, and each stage scales, then rotates, then translates. The record's
@@ -156,6 +157,9 @@ public:
 	void onTrackStopped();
 	void onTrackFinished();
 
+	// Nancy30: pushes the table of what scripts stored in the stage
+	void pushFields(lua_State *L);
+
 private:
 	Animator &_animator;
 	uint _index;
@@ -189,8 +193,8 @@ public:
 	void updateTransform();
 	void updateAlpha();
 
-	// A stage finished its blends. Its "Stage<n>Done" function is called
-	// later, once the stages aren't being iterated, as it can change them.
+	// A stage finished its blends. Its Done function is called later, once
+	// the stages aren't being iterated, as it can change them.
 	void onStageDone(uint index);
 	void callDoneFunctions();
 


Commit: 4de0658edf9825ef40ac6bdbf6c36a5136eac443
    https://github.com/scummvm/scummvm/commit/4de0658edf9825ef40ac6bdbf6c36a5136eac443
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:57+02:00

Commit Message:
NANCY: NANCY30: Add the achievements

Like Nancy29, Nancy30 keeps its achievements in a file of its own
instead of using Steam.

Changed paths:
    engines/nancy/metaengine.cpp


diff --git a/engines/nancy/metaengine.cpp b/engines/nancy/metaengine.cpp
index 9cd86a0db63..8680b51edd9 100644
--- a/engines/nancy/metaengine.cpp
+++ b/engines/nancy/metaengine.cpp
@@ -244,9 +244,10 @@ void NancyMetaEngine::registerDefaultSettings(const Common::String &target) cons
 }
 
 // Nancy28 uses the achievements of its Steam release, its only release.
-// Nancy29 keeps its achievements in a file instead of using Steam.
+// Nancy29 and Nancy30 keep their achievements in a file instead of using Steam.
 Common::AchievementsPlatform NancyMetaEngine::getAchievementsPlatform(const Common::String &target) const {
-	if (ConfMan.get("gameid", target) == "nancy29") {
+	const Common::String gameId = ConfMan.get("gameid", target);
+	if (gameId == "nancy29" || gameId == "nancy30") {
 		return Common::UNK_ACHIEVEMENTS;
 	}
 
@@ -257,6 +258,7 @@ const Common::AchievementDescriptionList *NancyMetaEngine::getAchievementDescrip
 	static const Common::AchievementDescriptionList achievementDescriptionList[] = {
 		{ "nancy28", Common::STEAM_ACHIEVEMENTS, "226820" },
 		{ "nancy29", Common::UNK_ACHIEVEMENTS, "nancy29" },
+		{ "nancy30", Common::UNK_ACHIEVEMENTS, "nancy30" },
 		ACHIEVEMENT_DESC_TABLE_END_MARKER
 	};
 


Commit: 3b80ed37f47368d4476351d0048326629d3cda6a
    https://github.com/scummvm/scummvm/commit/3b80ed37f47368d4476351d0048326629d3cda6a
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:57:59+02:00

Commit Message:
NANCY: NANCY30: Add detection entry

Marked as unstable, as the game starts and is playable

Changed paths:
    engines/nancy/detection_tables.h


diff --git a/engines/nancy/detection_tables.h b/engines/nancy/detection_tables.h
index baf076c73f8..fd2d49f9e3b 100644
--- a/engines/nancy/detection_tables.h
+++ b/engines/nancy/detection_tables.h
@@ -944,6 +944,14 @@ static const ADGameDescription gameDescriptions[] = {
 		ADGF_UNSTABLE | ADGF_DROPPLATFORM,
 		NANCY_GUIOPTIONS
 	},
+	{ // MD5 by bluegr
+		"nancy30", nullptr,
+		AD_ENTRY1s("ciftree.dat", "3bb107b4d494bcee2ec61066632757af", 198488111),
+		Common::EN_ANY,
+		Common::kPlatformWindows,
+		ADGF_UNSTABLE | ADGF_DROPPLATFORM,
+		NANCY_GUIOPTIONS
+	},
 
 	// Do not delete
 	AD_TABLE_END_MARKER


Commit: a6e60bab494e55270b61962436ab7f39f0ad1c30
    https://github.com/scummvm/scummvm/commit/a6e60bab494e55270b61962436ab7f39f0ad1c30
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:01+02:00

Commit Message:
NANCY: NANCY26: Let records answer the records that message them

Every record has a unique name, which ar:Send passes on as the sender.
That name is now registered like the names that scripts give, so the
receiver can send its answer back to it.

Nancy31's Xenia in scene 1015 didn't show without this: her idle
animations only start once the record that runs them answers.

Changed paths:
    engines/nancy/script/v5/recordnode.cpp


diff --git a/engines/nancy/script/v5/recordnode.cpp b/engines/nancy/script/v5/recordnode.cpp
index 3e752b68123..9da55e4ec31 100644
--- a/engines/nancy/script/v5/recordnode.cpp
+++ b/engines/nancy/script/v5/recordnode.cpp
@@ -43,9 +43,11 @@ namespace Script {
 void Record::createNodeState() {
 	_nodeState = new RecordNodeState();
 
-	// Every record goes by a name of its own
+	// Every record goes by a name of its own, which messages can be sent to:
+	// a record that sends gives this name, and the receiver can answer it
 	static uint s_numRecords = 0;
 	_nodeState->uniqueAlias = Common::String::format("AR%u", ++s_numRecords);
+	registerAlias(_nodeState->uniqueAlias, this);
 }
 
 void Record::destroyNodeState() {


Commit: a5175ff0c302ac7526820d80f0d009b7e988d3aa
    https://github.com/scummvm/scummvm/commit/a5175ff0c302ac7526820d80f0d009b7e988d3aa
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:03+02:00

Commit Message:
NANCY: NANCY30: Place .bk2 movies at the rect stored in them

A .bk2 movie ends with the rect it is shown at, after the Bink data. A
Movie record without an onScreen now shows the movie there, using the
part of the frames of the same size at their top left. The idle
animations of the characters in Nancy30 and Nancy31 rely on this, and
were placed at the top left of the viewport instead.

Changed paths:
    engines/nancy/movieplayer.cpp
    engines/nancy/movieplayer.h
    engines/nancy/script/records.cpp


diff --git a/engines/nancy/movieplayer.cpp b/engines/nancy/movieplayer.cpp
index 6a61dc4564c..34be00d7ce4 100644
--- a/engines/nancy/movieplayer.cpp
+++ b/engines/nancy/movieplayer.cpp
@@ -109,6 +109,7 @@ bool MoviePlayer::loadFile(const Common::Path &name, byte videoPlaytype, bool bi
 		return false;
 	}
 
+	_hasEmbeddedDest = false;
 	if (_videoType == kVideoPlaytypeBink) {
 		// Nancy29 has movies in both versions of Bink. Its Bink 2 decoder is
 		// older than the one of the later games.
@@ -117,6 +118,12 @@ bool MoviePlayer::loadFile(const Common::Path &name, byte videoPlaytype, bool bi
 			_decoder.reset(new Video::Bink2Decoder(g_nancy->getGameType() == kGameTypeNancy29));
 		else
 			_decoder.reset(new Video::BinkDecoder());
+
+		if (file.isOpen() && bikPath.baseName().hasSuffixIgnoreCase(".bk2") && file.size() >= 16) {
+			file.seek(-16, SEEK_END);
+			readExclusiveRect(file, _embeddedDest);
+			_hasEmbeddedDest = !file.err() && !_embeddedDest.isEmpty();
+		}
 	} else {
 		_decoder.reset(new AVFDecoder(bidirectionalCache ? AVFDecoder::kLoadBidirectional : AVFDecoder::kLoadForward));
 	}
diff --git a/engines/nancy/movieplayer.h b/engines/nancy/movieplayer.h
index 67b8c3fb0aa..e7578b0b799 100644
--- a/engines/nancy/movieplayer.h
+++ b/engines/nancy/movieplayer.h
@@ -91,6 +91,11 @@ public:
 	uint16 getHeight() const;
 	void addFrameTime(uint16 timeToAdd);	// AVF only, no-op otherwise
 
+	// Nancy30: a .bk2 movie ends with the rect it is shown at when the script
+	// gives none, after the Bink data
+	bool hasEmbeddedDest() const { return _hasEmbeddedDest; }
+	const Common::Rect &getEmbeddedDest() const { return _embeddedDest; }
+
 	// Sets the volume of the movie's audio track, as a percentage (0 - 100).
 	void setVolume(byte percent);
 
@@ -137,6 +142,8 @@ private:
 
 	Common::ScopedPtr<Video::VideoDecoder> _decoder;
 	byte _videoType = kVideoPlaytypeAVF;
+	bool _hasEmbeddedDest = false;
+	Common::Rect _embeddedDest;
 
 	// Name this movie was loaded with; used by findLoadedMovie().
 	Common::Path _loadedName;
diff --git a/engines/nancy/script/records.cpp b/engines/nancy/script/records.cpp
index db096094996..e116c83ebd0 100644
--- a/engines/nancy/script/records.cpp
+++ b/engines/nancy/script/records.cpp
@@ -2598,8 +2598,8 @@ void MovieRecord::readTable(int tableIndex) {
 		luaL_error(L, "MovieAR must be created with a movie parameter");
 	}
 
-	// Nancy30 shows the whole movie at the top left without an onScreen, or
-	// with an empty one
+	// Without an onScreen, or with an empty one, Nancy30 shows a .bk2 movie at
+	// the rect stored in its file, and any other movie whole at the top left
 	const bool hasDest = pushField(L, tableIndex, "onScreen");
 	if (!hasDest && g_nancy->getGameType() < kGameTypeNancy30) {
 		luaL_error(L, "MovieAR must be created with an 'onScreen' parameter");
@@ -2614,8 +2614,14 @@ void MovieRecord::readTable(int tableIndex) {
 		luaL_error(L, "Could not load movie %s", _name.c_str());
 	}
 
+	bool isEmbeddedDest = false;
 	if (g_nancy->getGameType() >= kGameTypeNancy30 && _dest.isEmpty()) {
-		_dest = ScriptRect(0, 0, _player.getWidth(), _player.getHeight());
+		if (_player.hasEmbeddedDest()) {
+			_dest = ScriptRect(_player.getEmbeddedDest());
+			isEmbeddedDest = true;
+		} else {
+			_dest = ScriptRect(0, 0, _player.getWidth(), _player.getHeight());
+		}
 	}
 
 	_firstFrame = 0;
@@ -2628,7 +2634,10 @@ void MovieRecord::readTable(int tableIndex) {
 	// The whole of every frame, unless a part of it is asked for
 	// An empty source, like Nancy26's (-1, -1, -1, -1), shows the whole movie
 	_source = ScriptRect(0, 0, _player.getWidth(), _player.getHeight());
-	if (pushField(L, tableIndex, "source")) {
+	if (isEmbeddedDest) {
+		// The frames can be larger than the stored rect; their top left part shows
+		_source = ScriptRect(0, 0, _dest.width(), _dest.height());
+	} else if (pushField(L, tableIndex, "source")) {
 		if (!checkRect(L, -1).isEmpty()) {
 			_source = checkRect(L, -1);
 		}


Commit: a05e38091e968018ccf18ef024b682264bbc8755
    https://github.com/scummvm/scummvm/commit/a05e38091e968018ccf18ef024b682264bbc8755
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:04+02:00

Commit Message:
NANCY: NANCY19: Cache the frames of panoramas

The Lua scenes turn around by stepping through the frames of their
background. Turning right decoded each frame again from the keyframe
before it, which made turning slow. A background with several frames
now has its frames cached from the moment the scene starts, like the
panorama scenes of the earlier games.

Changed paths:
    engines/nancy/movieplayer.cpp
    engines/nancy/movieplayer.h
    engines/nancy/script/records.cpp
    engines/nancy/ui/viewport.h


diff --git a/engines/nancy/movieplayer.cpp b/engines/nancy/movieplayer.cpp
index 34be00d7ce4..ecb1e2156ad 100644
--- a/engines/nancy/movieplayer.cpp
+++ b/engines/nancy/movieplayer.cpp
@@ -84,6 +84,19 @@ byte MoviePlayer::resolvePlaytype(byte videoPlaytype) {
 	return g_nancy->getGameType() >= kGameTypeNancy10 ? kVideoPlaytypeBink : kVideoPlaytypeAVF;
 }
 
+// The AVF decoder caches frames itself, so only the Bink path needs ours
+void MoviePlayer::enableFrameCache() {
+	if (_useFrameCache || !_decoder || _videoType != kVideoPlaytypeBink) {
+		return;
+	}
+
+	_useFrameCache = true;
+	_frameCache.resize(_decoder->getFrameCount());
+	_cacheFillNext = 0;
+	_cacheLoader.reset(new BinkCacheLoader(*this));
+	g_nancy->addDeferredLoader(_cacheLoader);
+}
+
 bool MoviePlayer::loadFile(const Common::Path &name, byte videoPlaytype, bool bidirectionalCache, bool screenFormat) {
 	freeFrameCache();
 	unregisterMovie();
@@ -153,13 +166,8 @@ bool MoviePlayer::loadFile(const Common::Path &name, byte videoPlaytype, bool bi
 		}
 	}
 
-	// The AVF decoder caches frames itself, so only the Bink path needs ours.
-	_useFrameCache = bidirectionalCache && _videoType == kVideoPlaytypeBink;
-	if (_useFrameCache) {
-		_frameCache.resize(_decoder->getFrameCount());
-		_cacheFillNext = 0;
-		_cacheLoader.reset(new BinkCacheLoader(*this));
-		g_nancy->addDeferredLoader(_cacheLoader);
+	if (bidirectionalCache) {
+		enableFrameCache();
 	}
 
 	_loadedName = name;
diff --git a/engines/nancy/movieplayer.h b/engines/nancy/movieplayer.h
index e7578b0b799..15c8574b6b7 100644
--- a/engines/nancy/movieplayer.h
+++ b/engines/nancy/movieplayer.h
@@ -65,6 +65,8 @@ public:
 	// format instead of the input format; only for opaque videos, since the
 	// transparent color is defined in the input format.
 	bool loadFile(const Common::Path &name, byte videoPlaytype = kVideoPlaytypeAuto, bool bidirectionalCache = false, bool screenFormat = false);
+	// Turns on that cache for a movie that is already loaded
+	void enableFrameCache();
 	bool isVideoLoaded() const;
 	void close();
 	Video::VideoDecoder *getDecoder() { return _decoder.get(); }
@@ -150,9 +152,10 @@ private:
 
 	// Decoded-frame cache for the Bink path (AVF caches internally). Bink seeking
 	// re-decodes from the previous keyframe, so caching keeps panorama scrubbing
-	// fast. Enabled only when loadFile() is asked for a bidirectional cache; the
-	// whole cache is then filled forward (the fast direction) in spare time by a
-	// deferred loader, so even the first turn is smooth.
+	// fast. Enabled when loadFile() is asked for a bidirectional cache, or by
+	// enableFrameCache(); the whole cache is then filled forward (the fast
+	// direction) in spare time by a deferred loader, so even the first turn is
+	// smooth.
 	bool _useFrameCache = false;
 	Common::Array<Graphics::Surface> _frameCache;
 	Common::SharedPtr<DeferredLoader> _cacheLoader;
diff --git a/engines/nancy/script/records.cpp b/engines/nancy/script/records.cpp
index e116c83ebd0..a7fa1657b54 100644
--- a/engines/nancy/script/records.cpp
+++ b/engines/nancy/script/records.cpp
@@ -560,10 +560,17 @@ void SummaryRecord::registerGraphics() {
 	}
 }
 
+// Only turning changes the frame of the background, so a background of several
+// frames is a panorama. Its frames are cached from the start, as in the
+// panorama scenes of the earlier games.
 void SummaryRecord::setBackground(UI::Viewport *background) {
 	_background = background;
 	_numFrames = background ? background->getFrameCount() : 0;
 	_frame = getContext().getFrame();
+
+	if (_numFrames > 1) {
+		_background->enableFrameCache();
+	}
 }
 
 void SummaryRecord::setFrame(uint frame) {
diff --git a/engines/nancy/ui/viewport.h b/engines/nancy/ui/viewport.h
index ee9d5524b27..7d51a85ba9e 100644
--- a/engines/nancy/ui/viewport.h
+++ b/engines/nancy/ui/viewport.h
@@ -67,6 +67,8 @@ public:
 	void scrollDown(uint delta);
 
 	uint16 getFrameCount() const { return _decoder.getFrameCount(); }
+	// For a background the player turns around in, from Nancy19 on
+	void enableFrameCache() { _decoder.enableFrameCache(); }
 	uint16 getCurFrame() const { return _currentFrame; }
 	uint16 getCurVerticalScroll() const { return _drawSurface.getOffsetFromOwner().y; }
 	uint16 getMaxScroll() const;


Commit: fd942ba00747ccfb3d44a92ae8509ad639e52f2b
    https://github.com/scummvm/scummvm/commit/fd942ba00747ccfb3d44a92ae8509ad639e52f2b
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:06+02:00

Commit Message:
NANCY: NANCY30: Let buttons react to the right mouse button

A button whose hotspot watches the right mouse button now calls its
OnDown and OnUp functions for that button too. Check boxes and radio
buttons still only react to the left one.

Changed paths:
    engines/nancy/script/v5/widgets.cpp


diff --git a/engines/nancy/script/v5/widgets.cpp b/engines/nancy/script/v5/widgets.cpp
index 2db769018ed..c001acd33c4 100644
--- a/engines/nancy/script/v5/widgets.cpp
+++ b/engines/nancy/script/v5/widgets.cpp
@@ -606,8 +606,10 @@ void WidgetRecord::onHotspotOver(bool isOver) {
 	updateState();
 }
 
+// A plain button also takes presses of the right button, when its hotspot
+// watches that button
 void WidgetRecord::onHotspotDown(int button) {
-	if (button != 0) {
+	if (button != 0 && _type != kRecordButton) {
 		return;
 	}
 
@@ -627,7 +629,7 @@ void WidgetRecord::onHotspotDown(int button) {
 }
 
 void WidgetRecord::onHotspotUp(int button, bool isOver) {
-	if (button != 0) {
+	if (button != 0 && _type != kRecordButton) {
 		return;
 	}
 


Commit: 1610c6b32048c4233d4d21734d546fd88a911c79
    https://github.com/scummvm/scummvm/commit/1610c6b32048c4233d4d21734d546fd88a911c79
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:08+02:00

Commit Message:
NANCY: Use Steam achievements only for Nancy28

Nancy28 is the only game with achievements on Steam. The other games
with achievements keep them in a file, so they no longer have to be
listed one by one.

Changed paths:
    engines/nancy/metaengine.cpp


diff --git a/engines/nancy/metaengine.cpp b/engines/nancy/metaengine.cpp
index 8680b51edd9..6944b0c7256 100644
--- a/engines/nancy/metaengine.cpp
+++ b/engines/nancy/metaengine.cpp
@@ -243,15 +243,14 @@ void NancyMetaEngine::registerDefaultSettings(const Common::String &target) cons
 	ConfMan.registerDefault("originalsaveload", true);
 }
 
-// Nancy28 uses the achievements of its Steam release, its only release.
-// Nancy29 and Nancy30 keep their achievements in a file instead of using Steam.
+// Nancy28 is the only game with Steam achievements. The other games with
+// achievements keep them in a file.
 Common::AchievementsPlatform NancyMetaEngine::getAchievementsPlatform(const Common::String &target) const {
-	const Common::String gameId = ConfMan.get("gameid", target);
-	if (gameId == "nancy29" || gameId == "nancy30") {
-		return Common::UNK_ACHIEVEMENTS;
+	if (ConfMan.get("gameid", target) == "nancy28") {
+		return Common::STEAM_ACHIEVEMENTS;
 	}
 
-	return Common::STEAM_ACHIEVEMENTS;
+	return Common::UNK_ACHIEVEMENTS;
 }
 
 const Common::AchievementDescriptionList *NancyMetaEngine::getAchievementDescriptionList() const {


Commit: 127aad8af76f007c00e71d57078dd341984e2159
    https://github.com/scummvm/scummvm/commit/127aad8af76f007c00e71d57078dd341984e2159
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:10+02:00

Commit Message:
NANCY: NANCY31: Add a few script functions

- Log:Format and Log:Stack write down a text made with string.format,
  and Log:Stack adds the traceback of the script that called it
- Autotext:SafeGet returns the text of a key, or a note that the key
  is missing
- Point:Dot returns the dot product of two points, and
  Point:Normalized the point scaled to a length of 1

Changed paths:
    engines/nancy/script/gameapi.cpp
    engines/nancy/script/types.cpp


diff --git a/engines/nancy/script/gameapi.cpp b/engines/nancy/script/gameapi.cpp
index 0c1c6eb537a..efe5160f049 100644
--- a/engines/nancy/script/gameapi.cpp
+++ b/engines/nancy/script/gameapi.cpp
@@ -2365,6 +2365,57 @@ static int logAssert(lua_State *L) {
 	return 0;
 }
 
+// Formats the parameters from index 2 on with string.format, and leaves the
+// text, or the error when formatting failed, on the stack
+static bool formatLogText(lua_State *L) {
+	const int top = lua_gettop(L);
+	lua_getglobal(L, "string");
+	lua_getfield(L, -1, "format");
+	lua_remove(L, -2);
+	for (int i = 2; i <= top; ++i) {
+		lua_pushvalue(L, i);
+	}
+
+	return lua_pcall(L, top - 1, 1, 0) == 0;
+}
+
+// Log:Format(format, ...), Nancy31: writes down the text string.format makes
+static int logFormat(lua_State *L) {
+	if (!formatLogText(L)) {
+		debugC(1, kDebugScene, "Script warning: Log:Format: Failed string format: %s", lua_tostring(L, -1));
+		return 0;
+	}
+
+	luaL_where(L, 1);
+	debugC(1, kDebugScene, "Script: %s%s", lua_tostring(L, -1), lua_tostring(L, -2));
+	return 0;
+}
+
+// Log:Stack(format, ...), Nancy31: writes down the formatted text with the
+// stack traceback of the script that called it
+static int logStack(lua_State *L) {
+	if (!formatLogText(L)) {
+		debugC(1, kDebugScene, "Script warning: Log:Stack: Failed string format: %s", lua_tostring(L, -1));
+		return 0;
+	}
+
+	const int textIndex = lua_gettop(L);
+	lua_getglobal(L, "debug");
+	if (lua_istable(L, -1)) {
+		lua_getfield(L, -1, "traceback");
+		lua_remove(L, -2);
+		lua_pushvalue(L, textIndex);
+		lua_pushinteger(L, 2);
+		if (lua_pcall(L, 2, 1, 0) != 0) {
+			debugC(1, kDebugScene, "Script warning: Log:Stack: Failed debug traceback: %s", lua_tostring(L, -1));
+			return 0;
+		}
+	}
+
+	debugC(1, kDebugScene, "Script: %s", lua_isstring(L, -1) ? lua_tostring(L, -1) : lua_tostring(L, textIndex));
+	return 0;
+}
+
 // Log:Watch(function) and Log:Clear() are for the debug console of the original,
 // which isn't there
 static int logWatch(lua_State *L) {
@@ -2408,6 +2459,8 @@ static const luaL_Reg kLogFunctions[] = {
 	{ "Clear", logClear },
 	{ "ShowWarning", logShowWarning },
 	{ "AddManager", logAddManager },
+	{ "Format", logFormat },
+	{ "Stack", logStack },
 	{ nullptr, nullptr }
 };
 
@@ -2498,8 +2551,21 @@ static int autotextShowCC(lua_State *L) {
 	return 1;
 }
 
+// Autotext:SafeGet(key), Nancy31: the text of a key, or a note that it is missing
+static int autotextSafeGet(lua_State *L) {
+	const char *key = luaL_checkstring(L, 2);
+	Common::String text;
+	if (!findText(key, text)) {
+		text = Common::String::format("Missing autotext: '%s'", key);
+	}
+
+	lua_pushstring(L, text.c_str());
+	return 1;
+}
+
 static const luaL_Reg kAutotextFunctions[] = {
 	{ "__index", autotextIndex },
+	{ "SafeGet", autotextSafeGet },
 	{ "ShowCC", autotextShowCC },
 	{ "RemoveCC", autotextRemoveCC },
 	{ nullptr, nullptr }
diff --git a/engines/nancy/script/types.cpp b/engines/nancy/script/types.cpp
index da7cac9dd2d..2cdca654b00 100644
--- a/engines/nancy/script/types.cpp
+++ b/engines/nancy/script/types.cpp
@@ -639,6 +639,26 @@ static int pointFloored(lua_State *L) {
 	return 1;
 }
 
+// Point:Dot(point) and Point:Normalized(), Nancy31. A point at the origin stays there.
+static int pointDot(lua_State *L) {
+	const PointValue &a = checkPoint(L, 1);
+	const PointValue &b = checkPoint(L, 2);
+	lua_pushnumber(L, a.x * b.x + a.y * b.y);
+	return 1;
+}
+
+static int pointNormalized(lua_State *L) {
+	PointValue point = checkPoint(L, 1);
+	const float length = sqrt(point.x * point.x + point.y * point.y);
+	if (length != 0.0f) {
+		point.x /= length;
+		point.y /= length;
+	}
+
+	pushPointValue(L, point);
+	return 1;
+}
+
 static int pointNegate(lua_State *L) {
 	const PointValue &point = checkPoint(L, 1);
 	pushPointValue(L, PointValue(-point.x, -point.y));
@@ -669,6 +689,8 @@ static const luaL_Reg kPointFunctions[] = {
 	{ "__concat", concatToStrings },
 	{ "Rounded", pointRounded },
 	{ "Floored", pointFloored },
+	{ "Dot", pointDot },
+	{ "Normalized", pointNormalized },
 	{ nullptr, nullptr }
 };
 


Commit: ef33f6f386fd902ff508fde7df8d14db42726d63
    https://github.com/scummvm/scummvm/commit/ef33f6f386fd902ff508fde7df8d14db42726d63
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:11+02:00

Commit Message:
NANCY: NANCY31: Implement ar:Detach()

A record that is attached to a Transformer moves with it. ar:Detach()
takes a record off its Transformer again, e.g. when the scripts put a
record back into their pool of unused ones.

Changed paths:
    engines/nancy/script/v5/recordnode.cpp


diff --git a/engines/nancy/script/v5/recordnode.cpp b/engines/nancy/script/v5/recordnode.cpp
index 9da55e4ec31..fc6d462c454 100644
--- a/engines/nancy/script/v5/recordnode.cpp
+++ b/engines/nancy/script/v5/recordnode.cpp
@@ -455,6 +455,12 @@ static int recordResetInactive(lua_State *L) {
 	return 0;
 }
 
+// ar:Detach(), Nancy31: takes the record away from the Transformer it is attached to
+static int recordDetach(lua_State *L) {
+	checkRecord(L, 1)->setParentNode(nullptr);
+	return 0;
+}
+
 int Record::getNodeScriptField(const Common::String &key) {
 	lua_State *L = getLua();
 
@@ -528,6 +534,8 @@ bool Record::getNodeField(const Common::String &key) {
 		lua_pushcfunction(L, recordDeregisterAlias);
 	} else if (key == "ResetInactive") {
 		lua_pushcfunction(L, recordResetInactive);
+	} else if (key == "Detach") {
+		lua_pushcfunction(L, recordDetach);
 	} else if (key == "animator" && _nodeState->animator) {
 		_nodeState->animator->push(L);
 	} else if (BlendStages::pushFunction(L, key)) {
@@ -584,7 +592,7 @@ bool Record::setNodeField(const Common::String &key) {
 	} else if (key == "enabled" || key == "visible" || key == "paused" || key == "alpha" ||
 			key == "transform" || key == "invTransform" || key == "localInvTransform" ||
 			key == "blendedTransform" || key == "name" || key == "uniqueAlias" || key == "done" ||
-			key == "animator") {
+			key == "animator" || key == "Detach") {
 		luaL_error(L, "Cannot set field '%s' of an AR", key.c_str());
 	} else {
 		return false;


Commit: b4e465459eedcb715d0127fc7d6c9c55ab2bf6af
    https://github.com/scummvm/scummvm/commit/b4e465459eedcb715d0127fc7d6c9c55ab2bf6af
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:12+02:00

Commit Message:
NANCY: NANCY31: Allow overlays to be drawn more than once

ar:Copy() leaves a copy of an Overlay record's current picture on the
screen, which stays when the overlay changes or is hidden.
ar:DeleteCopy() and ar:GetCopies() remove and list the copies.

Used for the digits of number displays and the seeds puzzle.

Changed paths:
    engines/nancy/script/records.cpp
    engines/nancy/script/records.h


diff --git a/engines/nancy/script/records.cpp b/engines/nancy/script/records.cpp
index a7fa1657b54..4be7b0f144b 100644
--- a/engines/nancy/script/records.cpp
+++ b/engines/nancy/script/records.cpp
@@ -1495,10 +1495,20 @@ void OverlayRecord::applyRects() {
 
 void OverlayRecord::onZChanged() {
 	_graphic.setScriptZ(getZ(), getContext());
+#ifdef ENABLE_NANCY_V5
+	if (_hasCopyGraphic) {
+		_copyGraphic.setScriptZ(getZ(), getContext());
+	}
+#endif
 }
 
 void OverlayRecord::registerGraphics() {
 	_graphic.registerGraphics();
+#ifdef ENABLE_NANCY_V5
+	if (_hasCopyGraphic) {
+		_copyGraphic.registerGraphics();
+	}
+#endif
 }
 
 void OverlayRecord::updateGraphics() {
@@ -1522,6 +1532,18 @@ void OverlayRecord::updateGraphics() {
 		_attachment.setVisible(_isAttachmentDrawn, false);
 		_isAttachmentDrawn = false;
 	}
+
+#ifdef ENABLE_NANCY_V5
+	// The copies show even while the overlay itself is hidden
+	if (_hasCopyGraphic) {
+		if (_areCopiesStale) {
+			applyCopies();
+		}
+
+		_copyGraphic.setClipRect(getScreenClip());
+		_copyGraphic.setVisible(getContext().isStreamVisible() && _freeCopies.size() < _copies.size(), false);
+	}
+#endif
 }
 
 // What a script draws by itself goes over everything else the scene shows
@@ -1645,6 +1667,163 @@ static int overlayDefaultRects(lua_State *L) {
 	return 0;
 }
 
+#ifdef ENABLE_NANCY_V5
+// Returns the index of the copy, counting from 0
+int OverlayRecord::addCopy() {
+	Copy copy;
+	copy.source = _source;
+	copy.dest = _dest;
+	copy.modColor = _modColor;
+	copy.alpha = getAlpha();
+	copy.transform = getTransform();
+
+	uint index;
+	if (_freeCopies.empty()) {
+		index = _copies.size();
+		_copies.push_back(copy);
+	} else {
+		index = _freeCopies.back();
+		_freeCopies.pop_back();
+		_copies[index] = copy;
+	}
+
+	if (!_hasCopyGraphic) {
+		_hasCopyGraphic = true;
+		_copyGraphic.init();
+		_copyGraphic.setVisible(false);
+		_copyGraphic.setScriptZ(getZ(), getContext());
+		_copyGraphic.registerGraphics();
+	}
+
+	_areCopiesStale = true;
+	return index;
+}
+
+void OverlayRecord::deleteCopy(int index) {
+	if (index < 0 || index >= (int)_copies.size() || !_copies[index].isUsed) {
+		return;
+	}
+
+	_copies[index].isUsed = false;
+	_freeCopies.push_back(index);
+	_areCopiesStale = true;
+}
+
+// A table of the copies by their index, each with its source, onScreen,
+// modColor, alpha and transform
+void OverlayRecord::pushCopies() {
+	lua_State *L = getLua();
+
+	lua_newtable(L);
+	for (uint i = 0; i < _copies.size(); ++i) {
+		const Copy &copy = _copies[i];
+		if (!copy.isUsed) {
+			continue;
+		}
+
+		lua_pushinteger(L, i);
+		lua_newtable(L);
+		pushRect(L, copy.source);
+		lua_setfield(L, -2, "source");
+		pushRect(L, copy.dest);
+		lua_setfield(L, -2, "onScreen");
+		pushColor(L, copy.modColor);
+		lua_setfield(L, -2, "modColor");
+		lua_pushnumber(L, copy.alpha);
+		lua_setfield(L, -2, "alpha");
+		pushMatrix(L, copy.transform);
+		lua_setfield(L, -2, "transform");
+		lua_settable(L, -3);
+	}
+}
+
+// The copies are drawn into one surface that covers them all
+void OverlayRecord::applyCopies() {
+	_areCopiesStale = false;
+
+	Common::Array<const Copy *> shown;
+	for (const Copy &copy : _copies) {
+		if (copy.isUsed) {
+			shown.push_back(&copy);
+		}
+	}
+
+	Common::Array<RecordGraphic> pictures(shown.size());
+	Common::Array<bool> areKeyed(shown.size());
+	Common::Rect area;
+	bool hasArea = false;
+	for (uint i = 0; i < shown.size(); ++i) {
+		const Copy &copy = *shown[i];
+		Common::Rect source = copy.source.toRect();
+		source.clip(Common::Rect(_image.w, _image.h));
+		areKeyed[i] = false;
+		if (source.isEmpty()) {
+			continue;
+		}
+
+		uint32 modColor = copy.modColor;
+		if (copy.alpha < 1.0) {
+			const uint32 a = (uint32)CLIP<double>((modColor >> 24) * copy.alpha + 0.5, 0.0, 255.0);
+			modColor = (a << 24) | (modColor & 0xFFFFFF);
+		}
+
+		placePicture(pictures[i], _image, source, copy.dest, copy.transform, modColor);
+		areKeyed[i] = copy.transform.isTranslation() && modColor == kNoModColor;
+		if (!hasArea) {
+			area = pictures[i].getScreenPositionRaw();
+			hasArea = true;
+		} else {
+			area.extend(pictures[i].getScreenPositionRaw());
+		}
+	}
+
+	if (!hasArea) {
+		_copyGraphic._drawSurface.free();
+		return;
+	}
+
+	Graphics::ManagedSurface &out = _copyGraphic._drawSurface;
+	out.create(MAX<int>(area.width(), 1), MAX<int>(area.height(), 1), g_nancy->_graphics->getTransparentPixelFormat());
+	out.clear(0);
+	_copyGraphic.setTransparent(false);
+	for (uint i = 0; i < pictures.size(); ++i) {
+		blendPicture(out, pictures[i], areKeyed[i], Common::Point(area.left, area.top));
+	}
+
+	_copyGraphic.moveTo(area);
+	_copyGraphic.setNeedsRedraw(true);
+}
+
+static int overlayCopy(lua_State *L) {
+	OverlayRecord *record = dynamic_cast<OverlayRecord *>(checkRecord(L, 1));
+	if (!record) {
+		return luaL_typerror(L, 1, "ND.Overlay");
+	}
+
+	lua_pushinteger(L, record->addCopy());
+	return 1;
+}
+
+static int overlayDeleteCopy(lua_State *L) {
+	OverlayRecord *record = dynamic_cast<OverlayRecord *>(checkRecord(L, 1));
+	if (record) {
+		record->deleteCopy(luaL_checkint(L, 2));
+	}
+
+	return 0;
+}
+
+static int overlayGetCopies(lua_State *L) {
+	OverlayRecord *record = dynamic_cast<OverlayRecord *>(checkRecord(L, 1));
+	if (!record) {
+		return luaL_typerror(L, 1, "ND.Overlay");
+	}
+
+	record->pushCopies();
+	return 1;
+}
+#endif
+
 bool OverlayRecord::getField(const Common::String &key) {
 	lua_State *L = getLua();
 
@@ -1664,6 +1843,14 @@ bool OverlayRecord::getField(const Common::String &key) {
 		lua_pushstring(L, _treeName.c_str());
 	} else if (key == "DefaultRects") {
 		lua_pushcfunction(L, overlayDefaultRects);
+#ifdef ENABLE_NANCY_V5
+	} else if (key == "Copy") {
+		lua_pushcfunction(L, overlayCopy);
+	} else if (key == "DeleteCopy") {
+		lua_pushcfunction(L, overlayDeleteCopy);
+	} else if (key == "GetCopies") {
+		lua_pushcfunction(L, overlayGetCopies);
+#endif
 	} else {
 		return false;
 	}
@@ -1685,6 +1872,9 @@ bool OverlayRecord::setPicture(const Common::String &imageName) {
 	_image = Common::move(image);
 	_cachedImage = cached;
 	_imageName = imageName;
+#ifdef ENABLE_NANCY_V5
+	_areCopiesStale = true;
+#endif
 	return true;
 }
 
diff --git a/engines/nancy/script/records.h b/engines/nancy/script/records.h
index 3c5cae565f9..ac085976a22 100644
--- a/engines/nancy/script/records.h
+++ b/engines/nancy/script/records.h
@@ -295,6 +295,14 @@ public:
 	// when neither the source nor onScreen was given
 	void setDefaultRects();
 
+#ifdef ENABLE_NANCY_V5
+	// Nancy31: ar:Copy() keeps showing the picture as it is now, even after the
+	// overlay changes or hides, until ar:DeleteCopy(index) takes it away
+	int addCopy();
+	void deleteCopy(int index);
+	void pushCopies();
+#endif
+
 protected:
 	void readTable(int tableIndex) override;
 	void onZChanged() override;
@@ -310,6 +318,25 @@ private:
 	void applyRects();
 	bool setPicture(const Common::String &imageName);
 
+#ifdef ENABLE_NANCY_V5
+	struct Copy {
+		ScriptRect source;
+		ScriptRect dest;
+		uint32 modColor = 0xFFFFFFFF;
+		double alpha = 1.0;
+		ScriptMatrix transform;
+		bool isUsed = true;
+	};
+
+	void applyCopies();
+
+	Common::Array<Copy> _copies;
+	Common::Array<uint> _freeCopies;	// the slots of deleted copies, reused last one first
+	RecordGraphic _copyGraphic;			// all the copies, drawn into one surface
+	bool _hasCopyGraphic = false;
+	bool _areCopiesStale = false;
+#endif
+
 	Common::SharedPtr<Graphics::ManagedSurface> _cachedImage;	// kept while the record uses it
 	Graphics::ManagedSurface _image;	// the cached picture, or a saved one
 	Common::String _imageName;


Commit: 5b2472da1f57f94636e2e5462c931a55c7af6ba5
    https://github.com/scummvm/scummvm/commit/5b2472da1f57f94636e2e5462c931a55c7af6ba5
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:14+02:00

Commit Message:
NANCY: NANCY31: Add the allowSlide field of hotspots

When allowSlide is set, dragging the mouse away from a hotspot while
holding the button cancels its click. Used by the lists that are
scrolled by dragging.

Changed paths:
    engines/nancy/script/v5/widgets.cpp
    engines/nancy/script/v5/widgets.h


diff --git a/engines/nancy/script/v5/widgets.cpp b/engines/nancy/script/v5/widgets.cpp
index c001acd33c4..d4568a04ba9 100644
--- a/engines/nancy/script/v5/widgets.cpp
+++ b/engines/nancy/script/v5/widgets.cpp
@@ -138,9 +138,18 @@ void HotspotRecord::readTable(int tableIndex) {
 		readPointCoordinates(L, -1, _tileSize[0], _tileSize[1]);
 		lua_pop(L, 1);
 	}
+
+	readField(L, tableIndex, "allowSlide", _allowsSlide);
+	readField(L, tableIndex, "slideDistance", _slideDistance);
 }
 
 void HotspotRecord::onMouseMoved(const Common::Point32 &mouse) {
+	if (_allowsSlide && isDown() && !_hasSlid) {
+		const double dx = (double)mouse.x - _pressPoint.x;
+		const double dy = (double)mouse.y - _pressPoint.y;
+		_hasSlid = sqrt(dx * dx + dy * dy) >= _slideDistance;
+	}
+
 	updateCursorTile(&mouse);
 }
 
@@ -169,6 +178,10 @@ void HotspotRecord::updateCursorTile(const Common::Point32 *mouse) {
 }
 
 bool HotspotRecord::hitTest(const Common::Point32 &point) const {
+	if (_hasSlid && isDown()) {
+		return false;
+	}
+
 	double x = point.x;
 	double y = point.y;
 	getTransform().inverse().transformPoint(x, y);
@@ -243,6 +256,8 @@ bool HotspotRecord::pressRegion(int button) {
 	}
 
 	_pressedButton = button;
+	_pressPoint = getScriptMousePoint();
+	_hasSlid = false;
 	callFunction(button == 0 ? "OnLeftDown" : "OnRightDown");
 	if (_widget) {
 		_widget->onHotspotDown(button);
@@ -357,6 +372,10 @@ bool HotspotRecord::getField(const Common::String &key) {
 		} else {
 			lua_pushnil(L);
 		}
+	} else if (key == "allowSlide") {
+		lua_pushboolean(L, _allowsSlide);
+	} else if (key == "slideDistance") {
+		lua_pushnumber(L, _slideDistance);
 	} else {
 		return false;
 	}
@@ -413,6 +432,10 @@ bool HotspotRecord::setField(const Common::String &key) {
 		updateCursorTile(&getScriptMousePoint());
 	} else if (key == "cursorTile") {
 		luaL_error(L, "Cannot set 'cursorTile' field of a hotspot");
+	} else if (key == "allowSlide") {
+		_allowsSlide = lua_toboolean(L, 3) != 0;
+	} else if (key == "slideDistance") {
+		_slideDistance = luaL_checknumber(L, 3);
 	} else {
 		return false;
 	}
diff --git a/engines/nancy/script/v5/widgets.h b/engines/nancy/script/v5/widgets.h
index 9bd65597d90..89b61fef827 100644
--- a/engines/nancy/script/v5/widgets.h
+++ b/engines/nancy/script/v5/widgets.h
@@ -119,6 +119,14 @@ private:
 	double _tileSize[2] = { 0.0, 0.0 };
 	bool _hasCursorTile = false;
 	Common::Point32 _cursorTile;
+
+	// Nancy31. A hotspot that allows sliding stops being under the mouse once
+	// the mouse moved slideDistance away from where it was pressed, so letting
+	// go of the button doesn't click it, e.g. when the press scrolls a list
+	bool _allowsSlide = false;
+	double _slideDistance = 5.0;
+	Common::Point32 _pressPoint;
+	bool _hasSlid = false;
 };
 
 // Nancy26: catches the player's input in a part of the screen, so whatever is


Commit: 800d365045966f7e8d06ec8107db5bab544b7fdc
    https://github.com/scummvm/scummvm/commit/800d365045966f7e8d06ec8107db5bab544b7fdc
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:15+02:00

Commit Message:
NANCY: NANCY31: Add the isLeft field of buttons

isLeft tells the scripts whether a button was last pressed with the
left or the right mouse button.

Changed paths:
    engines/nancy/script/v5/widgets.cpp
    engines/nancy/script/v5/widgets.h


diff --git a/engines/nancy/script/v5/widgets.cpp b/engines/nancy/script/v5/widgets.cpp
index d4568a04ba9..3ba375797b8 100644
--- a/engines/nancy/script/v5/widgets.cpp
+++ b/engines/nancy/script/v5/widgets.cpp
@@ -636,6 +636,8 @@ void WidgetRecord::onHotspotDown(int button) {
 		return;
 	}
 
+	_isLeftDown = button == 0;
+
 	switch (_type) {
 	case kRecordCheckBox:
 		setSelected(!_isSelected, true);
@@ -718,6 +720,9 @@ bool WidgetRecord::getField(const Common::String &key) {
 	} else if (key == "groupName") {
 		lua_pushstring(L, _groupName.c_str());
 		return true;
+	} else if (key == "isLeft" && _type == kRecordButton) {
+		lua_pushboolean(L, _isLeftDown);
+		return true;
 	} else {
 		return ClipTransformerRecord::getField(key);
 	}
@@ -740,6 +745,8 @@ bool WidgetRecord::setField(const Common::String &key) {
 	} else if (key == "disabledColor") {
 		_disabledColor = checkColor(L, 3);
 		_wasEnabled = !isNodeEnabled();
+	} else if (key == "isLeft" && _type == kRecordButton) {
+		luaL_error(L, "Cannot set field 'isLeft' of a button AR");
 	} else if (key == "isSelected") {
 		setSelected(lua_toboolean(L, 3) != 0, false);
 	} else {
diff --git a/engines/nancy/script/v5/widgets.h b/engines/nancy/script/v5/widgets.h
index 89b61fef827..f7b41cbc475 100644
--- a/engines/nancy/script/v5/widgets.h
+++ b/engines/nancy/script/v5/widgets.h
@@ -206,6 +206,7 @@ protected:
 	bool _isSelected = false;
 	Common::String _groupName;	// of a radio button
 	bool _wasEnabled = true;
+	bool _isLeftDown = true;	// Nancy31: the last press of a button was with the left button
 };
 
 // Nancy26: a knob that the mouse drags around the knob area, or the wheel moves


Commit: 1f628f51e00cf6083fd2a7d2eabecff0219c4046
    https://github.com/scummvm/scummvm/commit/1f628f51e00cf6083fd2a7d2eabecff0219c4046
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:16+02:00

Commit Message:
NANCY: NANCY31: Allow changing the group of radio buttons

Scripts can now set the groupName of a radio button. If the button is
selected, it is deselected first.

Changed paths:
    engines/nancy/script/v5/widgets.cpp


diff --git a/engines/nancy/script/v5/widgets.cpp b/engines/nancy/script/v5/widgets.cpp
index 3ba375797b8..c408615c951 100644
--- a/engines/nancy/script/v5/widgets.cpp
+++ b/engines/nancy/script/v5/widgets.cpp
@@ -749,6 +749,10 @@ bool WidgetRecord::setField(const Common::String &key) {
 		luaL_error(L, "Cannot set field 'isLeft' of a button AR");
 	} else if (key == "isSelected") {
 		setSelected(lua_toboolean(L, 3) != 0, false);
+	} else if (key == "groupName" && _type == kRecordRadioButton) {
+		// Nancy31: a selected radio button gets deselected when it changes groups
+		setSelected(false, true);
+		_groupName = luaL_checkstring(L, 3);
 	} else {
 		return ClipTransformerRecord::setField(key);
 	}


Commit: ea755db3f6197b2da0e1fc1e97ee40c52a702bee
    https://github.com/scummvm/scummvm/commit/ea755db3f6197b2da0e1fc1e97ee40c52a702bee
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:17+02:00

Commit Message:
NANCY: NANCY31: Add Scene.isGCThrottled

>From Nancy20 on, Lua collects garbage only once a frame. Setting
Scene.isGCThrottled to false lets Lua collect it whenever it needs to.
Only a debug scene that the game never loads uses it.

Changed paths:
    engines/nancy/script/gameapi.cpp
    engines/nancy/script/scenecontext.cpp
    engines/nancy/script/scenecontext.h


diff --git a/engines/nancy/script/gameapi.cpp b/engines/nancy/script/gameapi.cpp
index efe5160f049..33335600135 100644
--- a/engines/nancy/script/gameapi.cpp
+++ b/engines/nancy/script/gameapi.cpp
@@ -1434,6 +1434,8 @@ static int sceneIndex(lua_State *L) {
 		lua_pushinteger(L, context->getFrame());
 	} else if (key == "streamName") {
 		lua_pushstring(L, context->getStreamName().c_str());
+	} else if (key == "isGCThrottled") {
+		lua_pushboolean(L, context->isGCThrottled());
 	} else {
 		return indexFunctions(L);
 	}
@@ -1450,6 +1452,12 @@ static int sceneNewIndex(lua_State *L) {
 	SceneContext *context = checkContext(L);
 	const char *key = luaL_checkstring(L, 2);
 
+	// Nancy31
+	if (strcmp(key, "isGCThrottled") == 0) {
+		context->setGCThrottled(lua_toboolean(L, 3) != 0);
+		return 0;
+	}
+
 	if (!lua_isfunction(L, 3)) {
 		return luaL_error(L, "Can only set functions to the Scene object");
 	}
diff --git a/engines/nancy/script/scenecontext.cpp b/engines/nancy/script/scenecontext.cpp
index 6f5aceb757a..7c20fa4a2bc 100644
--- a/engines/nancy/script/scenecontext.cpp
+++ b/engines/nancy/script/scenecontext.cpp
@@ -487,6 +487,13 @@ void SceneContext::renderAttachment() {
 	callSceneFunction("RenderAttachment", 1);
 }
 
+void SceneContext::setGCThrottled(bool isThrottled) {
+	if (isThrottled != _isGCThrottled) {
+		_isGCThrottled = isThrottled;
+		lua_gc(getLua(), isThrottled ? LUA_GCSTOP : LUA_GCRESTART, 0);
+	}
+}
+
 void SceneContext::runFrame(double elapsedTime) {
 	lua_State *L = getLua();
 
@@ -500,9 +507,12 @@ void SceneContext::runFrame(double elapsedTime) {
 	// Nancy20 collects what the scripts let go of once a frame, and only then.
 	// That takes out the records that belonged to the scripts.
 	if (g_nancy->getGameType() >= kGameTypeNancy20) {
-		lua_gc(L, LUA_GCRESTART, 0);
-		lua_gc(L, LUA_GCCOLLECT, 0);
-		lua_gc(L, LUA_GCSTOP, 0);
+		if (_isGCThrottled) {
+			lua_gc(L, LUA_GCRESTART, 0);
+			lua_gc(L, LUA_GCCOLLECT, 0);
+			lua_gc(L, LUA_GCSTOP, 0);
+		}
+
 		deleteDroppedRecords();
 	}
 
diff --git a/engines/nancy/script/scenecontext.h b/engines/nancy/script/scenecontext.h
index 3a11c2b5877..0ff01643bb2 100644
--- a/engines/nancy/script/scenecontext.h
+++ b/engines/nancy/script/scenecontext.h
@@ -134,6 +134,11 @@ public:
 	double getTime() const { return _time; }
 	double getElapsedTime() const { return _elapsedTime; }	// of the last frame
 
+	// Nancy31: whether Lua only collects garbage once a frame, as it always
+	// does from Nancy20 on, or whenever it likes
+	bool isGCThrottled() const { return _isGCThrottled; }
+	void setGCThrottled(bool isThrottled);
+
 	// Enhancement: skips the movies that are playing. They are played through
 	// a frame at a time, without their sounds, so that everything the scripts
 	// tie to them still happens. Returns false when there is nothing to skip.
@@ -233,6 +238,7 @@ private:
 
 	double _time = 0.0;
 	double _elapsedTime = 0.0;
+	bool _isGCThrottled = true;
 	bool _hasRunOnce = false;
 	bool _makesUI = false;
 	bool _isSkipping = false;


Commit: 48f7736428515dfde49d0ec1fdbf256d1a66e199
    https://github.com/scummvm/scummvm/commit/48f7736428515dfde49d0ec1fdbf256d1a66e199
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:18+02:00

Commit Message:
NANCY: NANCY31: Add the achievements

Like Nancy29 and Nancy30, the game keeps its achievements in a file.

Changed paths:
    engines/nancy/metaengine.cpp


diff --git a/engines/nancy/metaengine.cpp b/engines/nancy/metaengine.cpp
index 6944b0c7256..647aae9d7a0 100644
--- a/engines/nancy/metaengine.cpp
+++ b/engines/nancy/metaengine.cpp
@@ -258,6 +258,7 @@ const Common::AchievementDescriptionList *NancyMetaEngine::getAchievementDescrip
 		{ "nancy28", Common::STEAM_ACHIEVEMENTS, "226820" },
 		{ "nancy29", Common::UNK_ACHIEVEMENTS, "nancy29" },
 		{ "nancy30", Common::UNK_ACHIEVEMENTS, "nancy30" },
+		{ "nancy31", Common::UNK_ACHIEVEMENTS, "nancy31" },
 		ACHIEVEMENT_DESC_TABLE_END_MARKER
 	};
 


Commit: 1bc75db0a859e3dd816a4f1d887b415097fee849
    https://github.com/scummvm/scummvm/commit/1bc75db0a859e3dd816a4f1d887b415097fee849
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:19+02:00

Commit Message:
NANCY: NANCY31: Add detection entry

Marked as unstable, as the game starts and is playable, but hasn't
been played through yet.

Changed paths:
    engines/nancy/detection_tables.h


diff --git a/engines/nancy/detection_tables.h b/engines/nancy/detection_tables.h
index fd2d49f9e3b..5dbac6a52b4 100644
--- a/engines/nancy/detection_tables.h
+++ b/engines/nancy/detection_tables.h
@@ -952,6 +952,14 @@ static const ADGameDescription gameDescriptions[] = {
 		ADGF_UNSTABLE | ADGF_DROPPLATFORM,
 		NANCY_GUIOPTIONS
 	},
+	{ // MD5 by bluegr
+		"nancy31", nullptr,
+		AD_ENTRY1s("ciftree.dat", "7bf7132f5a54bff1392759850202bf09", 276599945),
+		Common::EN_ANY,
+		Common::kPlatformWindows,
+		ADGF_UNSTABLE | ADGF_DROPPLATFORM,
+		NANCY_GUIOPTIONS
+	},
 
 	// Do not delete
 	AD_TABLE_END_MARKER


Commit: 20eb8227b615f41d7acf0e2b9ada232edd0cdd15
    https://github.com/scummvm/scummvm/commit/20eb8227b615f41d7acf0e2b9ada232edd0cdd15
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:20+02:00

Commit Message:
VIDEO: BINK2: Convert the colors with the full range

Bink 2 videos use the full range of luminance. Converted with the TV
range, they were darker than the pictures that the Nancy games draw
over them, e.g. at the lighthouse in scene 2022 of Nancy32.

Changed paths:
    video/bink2_decoder.cpp


diff --git a/video/bink2_decoder.cpp b/video/bink2_decoder.cpp
index e15efa26eb6..73da8c9bc08 100644
--- a/video/bink2_decoder.cpp
+++ b/video/bink2_decoder.cpp
@@ -912,13 +912,15 @@ void Bink2Decoder::Bink2VideoTrack::convertFrame() {
 		_surface->h = _height;
 	}
 
+	// Bink 2 keeps the full range of luminance: the pictures the games draw
+	// over the frames only match them that way
 	const int surfaceWidth = (_width + 1) & ~1;
 	const int surfaceHeight = (_height + 1) & ~1;
 	if (_hasAlpha) {
-		YUVToRGBMan.convert420Alpha(_surface, Graphics::YUVToRGBManager::kScaleITU, _planes[_curFrame][0], _planes[_curFrame][1], _planes[_curFrame][2], _planes[_curFrame][3],
+		YUVToRGBMan.convert420Alpha(_surface, Graphics::YUVToRGBManager::kScaleFull, _planes[_curFrame][0], _planes[_curFrame][1], _planes[_curFrame][2], _planes[_curFrame][3],
 				surfaceWidth, surfaceHeight, _pitches[0], _pitches[1]);
 	} else {
-		YUVToRGBMan.convert420(_surface, Graphics::YUVToRGBManager::kScaleITU, _planes[_curFrame][0], _planes[_curFrame][1], _planes[_curFrame][2],
+		YUVToRGBMan.convert420(_surface, Graphics::YUVToRGBManager::kScaleFull, _planes[_curFrame][0], _planes[_curFrame][1], _planes[_curFrame][2],
 				surfaceWidth, surfaceHeight, _pitches[0], _pitches[1]);
 	}
 }


Commit: 0ddff740b7cfe3aa9ae27b0b4235b92ed3143856
    https://github.com/scummvm/scummvm/commit/0ddff740b7cfe3aa9ae27b0b4235b92ed3143856
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:21+02:00

Commit Message:
NANCY: NANCY26: Keep the caches of the scripts in the game state

The pictures of the bitmap fonts, the names of the records, the input
state and the record counter were static variables. They are now freed
with the engine.

Changed paths:
    engines/nancy/script/v5/bitmaptext.cpp
    engines/nancy/script/v5/gamefunctions.h
    engines/nancy/script/v5/messaging.cpp
    engines/nancy/script/v5/recordnode.cpp
    engines/nancy/script/v5/scriptinput.cpp


diff --git a/engines/nancy/script/v5/bitmaptext.cpp b/engines/nancy/script/v5/bitmaptext.cpp
index a16db9f3fb4..576eba2f2d9 100644
--- a/engines/nancy/script/v5/bitmaptext.cpp
+++ b/engines/nancy/script/v5/bitmaptext.cpp
@@ -28,6 +28,7 @@
 #include "engines/nancy/resource/resource.h"
 
 #include "engines/nancy/script/v5/bitmaptext.h"
+#include "engines/nancy/script/v5/gamefunctions.h"
 
 namespace Nancy {
 namespace Script {
@@ -65,13 +66,16 @@ static uint32 findFontColor(int id) {
 	return 0xFFFFFFFF;
 }
 
-// The pictures of the letters, kept once loaded
+// The pictures of the letters, kept by the game state once loaded
 static const Graphics::ManagedSurface *getFaceImage(const Common::Path &name) {
-	typedef Common::HashMap<Common::Path, Common::SharedPtr<Graphics::ManagedSurface>, Common::Path::IgnoreCase_Hash, Common::Path::IgnoreCase_EqualTo> ImageMap;
-	static ImageMap s_images;
+	ScriptGameState *state = (ScriptGameState *)const_cast<EngineData *>(g_nancy->getEngineData("ScriptGameState"));
+	if (!state) {
+		return nullptr;
+	}
 
-	ImageMap::iterator it = s_images.find(name);
-	if (it != s_images.end()) {
+	ScriptGameState::FontImageMap &images = state->fontImages;
+	ScriptGameState::FontImageMap::iterator it = images.find(name);
+	if (it != images.end()) {
 		return it->_value.get();
 	}
 
@@ -82,7 +86,7 @@ static const Graphics::ManagedSurface *getFaceImage(const Common::Path &name) {
 		image->convertToInPlace(g_nancy->_graphics->getTransparentPixelFormat());
 	}
 
-	s_images.setVal(name, image);
+	images.setVal(name, image);
 	return image.get();
 }
 
diff --git a/engines/nancy/script/v5/gamefunctions.h b/engines/nancy/script/v5/gamefunctions.h
index 24b97c36fb3..7aa7119fa32 100644
--- a/engines/nancy/script/v5/gamefunctions.h
+++ b/engines/nancy/script/v5/gamefunctions.h
@@ -23,6 +23,14 @@
 #define NANCY_SCRIPT_V5_GAMEFUNCTIONS_H
 
 #include "common/array.h"
+#include "common/hash-str.h"
+#include "common/hashmap.h"
+#include "common/keyboard.h"
+#include "common/path.h"
+#include "common/ptr.h"
+#include "common/rect.h"
+
+#include "graphics/managed_surface.h"
 
 #include "engines/nancy/enginedata.h"
 
@@ -31,6 +39,8 @@ struct lua_State;
 namespace Nancy {
 namespace Script {
 
+class Record;
+
 // Nancy26. What the Game and Sound objects of the scripts keep while the game
 // runs, across new games
 struct ScriptGameState : public EngineData {
@@ -68,6 +78,36 @@ struct ScriptGameState : public EngineData {
 	Common::Array<bool> isItemEnabled;
 	Common::Array<bool> isItemForcedOn;
 	uint faceItemChangeCount = 0;
+
+	// The pictures of the letters of the fonts made of pictures, kept once loaded
+	typedef Common::HashMap<Common::Path, Common::SharedPtr<Graphics::ManagedSurface>, Common::Path::IgnoreCase_Hash, Common::Path::IgnoreCase_EqualTo> FontImageMap;
+	FontImageMap fontImages;
+
+	// Nancy26: the records by the names they go by for messages, shared by
+	// the scenes of all the streams
+	typedef Common::HashMap<Common::String, Record *, Common::IgnoreCase_Hash, Common::IgnoreCase_EqualTo> AliasMap;
+	AliasMap aliases;
+
+	// How many records were made, which numbers their own names
+	uint numRecords = 0;
+
+	// Nancy26: where the player's input is, for the records (see scriptinput.h)
+	struct InputState {
+		Common::Point32 mouse;
+		bool hasMouse = false;
+		Record *hovered = nullptr;
+		Record *pressed[2] = { nullptr, nullptr };
+
+		uint32 lastClickTime[2] = { 0, 0 };
+		Common::Point32 lastClickPoint[2];
+		bool isDoubleClick[2] = { false, false };
+
+		uint16 heldMoveKeys = 0;
+		bool isEscHeld = false;
+		Common::Array<Common::KeyCode> keysToRelease;
+	};
+
+	InputState input;
 };
 
 // Nancy29: applies the Brain flags of the inventory items, which equip them
diff --git a/engines/nancy/script/v5/messaging.cpp b/engines/nancy/script/v5/messaging.cpp
index eb93f6a1b46..4a2b964b639 100644
--- a/engines/nancy/script/v5/messaging.cpp
+++ b/engines/nancy/script/v5/messaging.cpp
@@ -30,21 +30,28 @@
 #include "engines/nancy/script/scenecontext.h"
 #include "engines/nancy/script/types.h"
 
+#include "engines/nancy/script/v5/gamefunctions.h"
 #include "engines/nancy/script/v5/messaging.h"
 
 namespace Nancy {
 namespace Script {
 
-typedef Common::HashMap<Common::String, Record *, Common::IgnoreCase_Hash, Common::IgnoreCase_EqualTo> AliasMap;
+typedef ScriptGameState::AliasMap AliasMap;
 
-// The names are shared by the scenes of all the streams
-static AliasMap &getAliases() {
-	static AliasMap s_aliases;
-	return s_aliases;
+// The names are shared by the scenes of all the streams, and kept by the game
+// state; null before it is there
+static AliasMap *getAliases() {
+	ScriptGameState *state = (ScriptGameState *)const_cast<EngineData *>(g_nancy->getEngineData("ScriptGameState"));
+	return state ? &state->aliases : nullptr;
 }
 
 bool registerAlias(const Common::String &alias, Record *record) {
-	AliasMap &aliases = getAliases();
+	AliasMap *found = getAliases();
+	if (!found) {
+		return false;
+	}
+
+	AliasMap &aliases = *found;
 	AliasMap::iterator it = aliases.find(alias);
 	if (it != aliases.end() && it->_value != record) {
 		// The scene a stream goes to is loaded while the one it leaves is still
@@ -61,15 +68,24 @@ bool registerAlias(const Common::String &alias, Record *record) {
 }
 
 void deregisterAlias(const Common::String &alias, Record *record) {
-	AliasMap &aliases = getAliases();
-	AliasMap::iterator it = aliases.find(alias);
-	if (it != aliases.end() && it->_value == record) {
-		aliases.erase(it);
+	AliasMap *aliases = getAliases();
+	if (!aliases) {
+		return;
+	}
+
+	AliasMap::iterator it = aliases->find(alias);
+	if (it != aliases->end() && it->_value == record) {
+		aliases->erase(it);
 	}
 }
 
 void deregisterAliases(Record *record) {
-	AliasMap &aliases = getAliases();
+	AliasMap *found = getAliases();
+	if (!found) {
+		return;
+	}
+
+	AliasMap &aliases = *found;
 	Common::Array<Common::String> names;
 	for (AliasMap::iterator it = aliases.begin(); it != aliases.end(); ++it) {
 		if (it->_value == record) {
@@ -83,9 +99,13 @@ void deregisterAliases(Record *record) {
 }
 
 Record *findAlias(const Common::String &alias) {
-	AliasMap &aliases = getAliases();
-	AliasMap::iterator it = aliases.find(alias);
-	return it != aliases.end() ? it->_value : nullptr;
+	AliasMap *aliases = getAliases();
+	if (!aliases) {
+		return nullptr;
+	}
+
+	AliasMap::iterator it = aliases->find(alias);
+	return it != aliases->end() ? it->_value : nullptr;
 }
 
 // What the exe copies: numbers, texts, booleans and nil as they are, tables
diff --git a/engines/nancy/script/v5/recordnode.cpp b/engines/nancy/script/v5/recordnode.cpp
index fc6d462c454..eaa02332cd3 100644
--- a/engines/nancy/script/v5/recordnode.cpp
+++ b/engines/nancy/script/v5/recordnode.cpp
@@ -33,6 +33,7 @@
 
 #include "engines/nancy/script/v5/animator.h"
 #include "engines/nancy/script/v5/cliptransformer.h"
+#include "engines/nancy/script/v5/gamefunctions.h"
 #include "engines/nancy/script/v5/messaging.h"
 #include "engines/nancy/script/v5/recordnode.h"
 #include "engines/nancy/script/v5/scriptinput.h"
@@ -45,8 +46,9 @@ void Record::createNodeState() {
 
 	// Every record goes by a name of its own, which messages can be sent to:
 	// a record that sends gives this name, and the receiver can answer it
-	static uint s_numRecords = 0;
-	_nodeState->uniqueAlias = Common::String::format("AR%u", ++s_numRecords);
+	ScriptGameState *state = (ScriptGameState *)const_cast<EngineData *>(g_nancy->getEngineData("ScriptGameState"));
+	assert(state);
+	_nodeState->uniqueAlias = Common::String::format("AR%u", ++state->numRecords);
 	registerAlias(_nodeState->uniqueAlias, this);
 }
 
diff --git a/engines/nancy/script/v5/scriptinput.cpp b/engines/nancy/script/v5/scriptinput.cpp
index 634b8362076..5db81c67059 100644
--- a/engines/nancy/script/v5/scriptinput.cpp
+++ b/engines/nancy/script/v5/scriptinput.cpp
@@ -31,6 +31,7 @@
 #include "engines/nancy/script/records.h"
 #include "engines/nancy/script/scenecontext.h"
 
+#include "engines/nancy/script/v5/gamefunctions.h"
 #include "engines/nancy/script/v5/scriptinput.h"
 #include "engines/nancy/script/v5/widgets.h"
 
@@ -42,24 +43,19 @@ namespace Script {
 static const uint32 kDoubleClickTime = 500;	// milliseconds
 static const int kDoubleClickDistance = 4;
 
-struct InputState {
-	Common::Point32 mouse;
-	bool hasMouse = false;
-	Record *hovered = nullptr;
-	Record *pressed[2] = { nullptr, nullptr };
-
-	uint32 lastClickTime[2] = { 0, 0 };
-	Common::Point32 lastClickPoint[2];
-	bool isDoubleClick[2] = { false, false };
+typedef ScriptGameState::InputState InputState;
 
-	uint16 heldMoveKeys = 0;
-	bool isEscHeld = false;
-	Common::Array<Common::KeyCode> keysToRelease;
-};
+// Returns the input state, which the game state keeps, or null when there
+// is no game state yet
+static InputState *findState() {
+	ScriptGameState *state = (ScriptGameState *)const_cast<EngineData *>(g_nancy->getEngineData("ScriptGameState"));
+	return state ? &state->input : nullptr;
+}
 
 static InputState &getState() {
-	static InputState s_state;
-	return s_state;
+	InputState *state = findState();
+	assert(state);
+	return *state;
 }
 
 const Common::Point32 &getScriptMousePoint() {
@@ -71,7 +67,12 @@ bool isDoubleClick(int button) {
 }
 
 void forgetInputRecord(Record *record) {
-	InputState &state = getState();
+	InputState *found = findState();
+	if (!found) {
+		return;
+	}
+
+	InputState &state = *found;
 	if (state.hovered == record) {
 		state.hovered = nullptr;
 	}


Commit: 34d67d1a73005bda9c3ccfe99922600dd6c3c583
    https://github.com/scummvm/scummvm/commit/34d67d1a73005bda9c3ccfe99922600dd6c3c583
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:23+02:00

Commit Message:
NANCY: NANCY30: Place images at the rect stored in them

Images of resource type 4 end with the rect they are shown at, after
the PNG data. An overlay without an onScreen now shows its image
there, e.g. the open door in scene 2008 of Nancy32.

Changed paths:
    engines/nancy/resource/cif.cpp
    engines/nancy/resource/cif.h
    engines/nancy/resource/resource.cpp
    engines/nancy/resource/resource.h
    engines/nancy/script/records.cpp
    engines/nancy/script/records.h


diff --git a/engines/nancy/resource/cif.cpp b/engines/nancy/resource/cif.cpp
index 40d49f9846a..37a9980f14a 100644
--- a/engines/nancy/resource/cif.cpp
+++ b/engines/nancy/resource/cif.cpp
@@ -149,6 +149,7 @@ static bool syncCifFileNancy18(Common::Serializer &ser, CifInfo &info) {
 	// like any other
 	if (ser.isLoading() && info.type == CifInfo::kResTypeEmpty && info.size && g_nancy->getGameType() >= kGameTypeNancy30) {
 		info.type = CifInfo::kResTypeImage;
+		info.hasEmbeddedDest = true;
 	}
 
 	if (info.type == CifInfo::kResTypeImage) {
diff --git a/engines/nancy/resource/cif.h b/engines/nancy/resource/cif.h
index 116b1f14f6e..677dad876f2 100644
--- a/engines/nancy/resource/cif.h
+++ b/engines/nancy/resource/cif.h
@@ -57,6 +57,10 @@ struct CifInfo {
 	uint32 compressedSize = 0, size = 0;
 	Common::Rect src, dest; // Used when drawing conversation cels
 
+	// Nancy30: the PNG of an image of type 4 is followed by the rect it is
+	// shown at by default
+	bool hasEmbeddedDest = false;
+
 	uint32 dataOffset = 0;
 };
 
diff --git a/engines/nancy/resource/resource.cpp b/engines/nancy/resource/resource.cpp
index cffa2792d98..ae72a90af01 100644
--- a/engines/nancy/resource/resource.cpp
+++ b/engines/nancy/resource/resource.cpp
@@ -153,6 +153,16 @@ bool ResourceManager::loadImage(const Common::Path &name, Graphics::ManagedSurfa
 		return false;
 	}
 
+	// Nancy30: the 16 bytes after the PNG of some images are where they go
+	if (info.hasEmbeddedDest && stream->size() >= 16) {
+		stream->seek(-16, SEEK_END);
+		info.dest.left = stream->readSint32LE();
+		info.dest.top = stream->readSint32LE();
+		info.dest.right = stream->readSint32LE();
+		info.dest.bottom = stream->readSint32LE();
+		stream->seek(0);
+	}
+
 	// Load the src/dest rects when requested
 	if (outSrc) {
 		*outSrc = info.src;
@@ -251,21 +261,30 @@ bool ResourceManager::loadImage(const Common::Path &name, Graphics::ManagedSurfa
 // How many pictures the image cache keeps decoded
 static const uint kImageCacheSize = 16;
 
-Common::SharedPtr<Graphics::ManagedSurface> ResourceManager::loadCachedImage(const Common::String &name, const Common::String &treeName) {
+Common::SharedPtr<Graphics::ManagedSurface> ResourceManager::loadCachedImage(const Common::String &name, const Common::String &treeName, Common::Rect *outDest) {
 	const Common::String key = treeName + "/" + name;
 	++_imageCacheUses;
 
 	ImageCache::iterator found = _imageCache.find(key);
 	if (found != _imageCache.end()) {
 		found->_value.lastUse = _imageCacheUses;
+		if (outDest) {
+			*outDest = found->_value.dest;
+		}
+
 		return found->_value.image;
 	}
 
 	Common::SharedPtr<Graphics::ManagedSurface> image(new Graphics::ManagedSurface());
-	if (!loadImage(Common::Path(name), *image, treeName)) {
+	Common::Rect dest;
+	if (!loadImage(Common::Path(name), *image, treeName, nullptr, &dest)) {
 		return Common::SharedPtr<Graphics::ManagedSurface>();
 	}
 
+	if (outDest) {
+		*outDest = dest;
+	}
+
 	// The picture used longest ago leaves the cache. Whoever still uses it
 	// keeps it until they are done with it.
 	if (_imageCache.size() >= kImageCacheSize) {
@@ -281,6 +300,7 @@ Common::SharedPtr<Graphics::ManagedSurface> ResourceManager::loadCachedImage(con
 
 	CachedImage &cached = _imageCache[key];
 	cached.image = image;
+	cached.dest = dest;
 	cached.lastUse = _imageCacheUses;
 	return image;
 }
diff --git a/engines/nancy/resource/resource.h b/engines/nancy/resource/resource.h
index 1ab762e1f78..d140aab6071 100644
--- a/engines/nancy/resource/resource.h
+++ b/engines/nancy/resource/resource.h
@@ -52,7 +52,7 @@ public:
 	// the phone, so decoding a picture each time was slow. The cache keeps the
 	// pictures it loaded last decoded, and hands the same one to everyone who
 	// asks for it. Null when there is no such picture.
-	Common::SharedPtr<Graphics::ManagedSurface> loadCachedImage(const Common::String &name, const Common::String &treeName);
+	Common::SharedPtr<Graphics::ManagedSurface> loadCachedImage(const Common::String &name, const Common::String &treeName, Common::Rect *outDest = nullptr);
 
 	// Loads a single IFF file. These can either be inside standalone .cif files, or embedded inside a ciftree
 	IFF *loadIFF(const Common::Path &name);
@@ -94,6 +94,7 @@ private:
 	// longest ago makes room.
 	struct CachedImage {
 		Common::SharedPtr<Graphics::ManagedSurface> image;
+		Common::Rect dest;
 		uint32 lastUse = 0;
 	};
 
diff --git a/engines/nancy/script/records.cpp b/engines/nancy/script/records.cpp
index 4be7b0f144b..bc031ee0303 100644
--- a/engines/nancy/script/records.cpp
+++ b/engines/nancy/script/records.cpp
@@ -1336,7 +1336,11 @@ static bool loadMovieFrame(const Common::String &name, Graphics::ManagedSurface
 // Overlays get their pictures from the image cache of the resource manager,
 // and hold on to the cached picture while they use it. Saved pictures aren't
 // cached: every record has its own.
-bool loadCachedImage(const Common::String &name, const Common::String &treeName, Common::SharedPtr<Graphics::ManagedSurface> &cached, Graphics::ManagedSurface &image) {
+bool loadCachedImage(const Common::String &name, const Common::String &treeName, Common::SharedPtr<Graphics::ManagedSurface> &cached, Graphics::ManagedSurface &image, Common::Rect *outDest) {
+	if (outDest) {
+		*outDest = Common::Rect();
+	}
+
 	if (treeName.equalsIgnoreCase(kPictureTreeName) || treeName.equalsIgnoreCase(kSaveFileTreeName)) {
 		image.free();
 		cached.reset();
@@ -1349,7 +1353,7 @@ bool loadCachedImage(const Common::String &name, const Common::String &treeName,
 		return loadMovieFrame(name, image);
 	}
 
-	cached = g_nancy->_resource->loadCachedImage(name, treeName);
+	cached = g_nancy->_resource->loadCachedImage(name, treeName, outDest);
 	if (!cached) {
 		return false;
 	}
@@ -1371,21 +1375,24 @@ void OverlayRecord::readTable(int tableIndex) {
 	Common::String treeName;
 	readField(L, tableIndex, "tree", treeName);
 
-	if (!loadCachedImage(imageName, treeName, _cachedImage, _image)) {
+	Common::Rect defaultDest;
+	if (!loadCachedImage(imageName, treeName, _cachedImage, _image, &defaultDest)) {
 		luaL_error(L, "Could not load overlay %s", imageName.c_str());
 	}
 
 	_imageName = imageName;
 	_treeName = treeName;
+	_defaultDest = defaultDest;
 
-	// Both default to the whole image
+	// Both default to the whole image. From Nancy30 on, an image can say
+	// where it goes.
 	_source = ScriptRect(0, 0, _image.w, _image.h);
 	if (pushField(L, tableIndex, "source")) {
 		_source = checkRect(L, -1);
 		lua_pop(L, 1);
 	}
 
-	_dest = _source;
+	_dest = _defaultDest.isEmpty() ? _source : _defaultDest;
 	if (pushField(L, tableIndex, "onScreen")) {
 		readDest(-1);
 		lua_pop(L, 1);
@@ -1653,7 +1660,7 @@ int drawOverlay(lua_State *L) {
 
 void OverlayRecord::setDefaultRects() {
 	_source = ScriptRect(0, 0, _image.w, _image.h);
-	_dest = _source;
+	_dest = _defaultDest.isEmpty() ? _source : _defaultDest;
 	_hasDestTable = false;
 	applyRects();
 }
diff --git a/engines/nancy/script/records.h b/engines/nancy/script/records.h
index ac085976a22..ac4907731f0 100644
--- a/engines/nancy/script/records.h
+++ b/engines/nancy/script/records.h
@@ -99,7 +99,8 @@ void placePicture(RecordGraphic &graphic, Graphics::ManagedSurface &image, const
 // Gets an image from the resource manager's cache, and keeps a reference to it
 // in cached while the record uses it. Images from picture trees that aren't
 // cached are loaded directly.
-bool loadCachedImage(const Common::String &name, const Common::String &treeName, Common::SharedPtr<Graphics::ManagedSurface> &cached, Graphics::ManagedSurface &image);
+// outDest gets the rect a Nancy30 image is shown at by default, or an empty one
+bool loadCachedImage(const Common::String &name, const Common::String &treeName, Common::SharedPtr<Graphics::ManagedSurface> &cached, Graphics::ManagedSurface &image, Common::Rect *outDest = nullptr);
 
 // The first record of every scene, which names the area the scene belongs to
 // and its background. A background with more than one frame is a node the
@@ -291,8 +292,9 @@ public:
 	// transform and modColor.
 	void drawCopy(int tableIndex);
 
-	// Nancy30: ar:DefaultRects() shows the whole picture at the top left, as
-	// when neither the source nor onScreen was given
+	// Nancy30: ar:DefaultRects() shows the whole picture where the image says
+	// it goes (or at the top left), as when neither the source nor onScreen
+	// was given
 	void setDefaultRects();
 
 #ifdef ENABLE_NANCY_V5
@@ -343,6 +345,7 @@ private:
 	Common::String _treeName;
 	ScriptRect _source;
 	ScriptRect _dest;
+	ScriptRect _defaultDest;	// Nancy30: the rect stored in the image; empty if it has none
 	bool _hasDestTable = false;					// Nancy24: onScreen is a table of rects
 	Common::Array<ScriptRect> _tableDests;		// what it had when last drawn
 	uint32 _modColor = 0xFFFFFFFF;	// what the colors of the picture get multiplied with


Commit: 00dfb1a39b352f6a67296b8717b6e69899034082
    https://github.com/scummvm/scummvm/commit/00dfb1a39b352f6a67296b8717b6e69899034082
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:25+02:00

Commit Message:
NANCY: Don't seek when the frame of a movie is set

Setting the frame of a Bink movie decoded it again from the keyframe
before it. The frame that shows is now kept, and one a few frames
ahead is decoded forward to. Puzzles of Nancy12 and Nancy14 and the
Lua games set frames; the character animations of Nancy32 set the
next frame every frame, which made the game slow.

Changed paths:
    engines/nancy/movieplayer.cpp
    engines/nancy/movieplayer.h


diff --git a/engines/nancy/movieplayer.cpp b/engines/nancy/movieplayer.cpp
index ecb1e2156ad..65084d31f92 100644
--- a/engines/nancy/movieplayer.cpp
+++ b/engines/nancy/movieplayer.cpp
@@ -142,6 +142,7 @@ bool MoviePlayer::loadFile(const Common::Path &name, byte videoPlaytype, bool bi
 	}
 
 	_currentSurface = nullptr;
+	_currentFrame = -1;
 
 	if (!_decoder->loadFile(_videoType == kVideoPlaytypeAVF ? avfPath : bikPath)) {
 		_decoder.reset();
@@ -182,6 +183,7 @@ bool MoviePlayer::isVideoLoaded() const {
 
 void MoviePlayer::close() {
 	_currentSurface = nullptr;
+	_currentFrame = -1;
 	freeFrameCache();
 	unregisterMovie();
 	if (_decoder) {
@@ -220,6 +222,9 @@ bool MoviePlayer::fillNextCacheFrame() {
 	}
 	++_cacheFillNext;
 
+	// The decoder's picture no longer shows the frame goToFrame() went to
+	_currentFrame = -1;
+
 	return _cacheFillNext >= _frameCache.size();
 }
 
@@ -311,6 +316,7 @@ const Graphics::Surface *MoviePlayer::decodeNextFrame(int frameNr) {
 
 void MoviePlayer::storeCurrentFrame() {
 	_currentSurface = _decoder->decodeNextFrame();
+	_currentFrame = _decoder->getCurFrame();
 }
 
 void MoviePlayer::goToFrame(int frameNr) {
@@ -323,8 +329,23 @@ void MoviePlayer::goToFrame(int frameNr) {
 	}
 	_rangePlaying = false;
 	_decoder->setReverse(false);
-	_decoder->seekToFrame(frameNr);
-	storeCurrentFrame();
+
+	if (_videoType == kVideoPlaytypeAVF) {
+		_decoder->seekToFrame(frameNr);
+		storeCurrentFrame();
+		return;
+	}
+
+	// Nancy32's fidgets set the frame of their movies one frame after the
+	// other, and seeking decodes again from the keyframe before the frame.
+	// The frame that already shows stays, and one a little ahead is decoded
+	// forward to.
+	if (frameNr == _currentFrame && _currentSurface) {
+		return;
+	}
+
+	_currentSurface = decodeNextFrame(frameNr);
+	_currentFrame = frameNr;
 }
 
 // How long a frame shows, from the length of the movie unless another frame
diff --git a/engines/nancy/movieplayer.h b/engines/nancy/movieplayer.h
index 15c8574b6b7..24199baf495 100644
--- a/engines/nancy/movieplayer.h
+++ b/engines/nancy/movieplayer.h
@@ -167,6 +167,7 @@ private:
 	// Simple frame-range player state. _currentSurface points at the decoder's
 	// last-decoded frame (owned by it, valid until the next decode).
 	const Graphics::Surface *_currentSurface = nullptr;
+	int _currentFrame = -1;	// the frame it shows
 	int _rangeLast = 0;
 	int _step = 1;
 	bool _rangePlaying = false;


Commit: 17f2b62a73cde4938a10fc7f9c530bcf5dfea7bf
    https://github.com/scummvm/scummvm/commit/17f2b62a73cde4938a10fc7f9c530bcf5dfea7bf
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:26+02:00

Commit Message:
NANCY: NANCY21: Redraw particles only when they move

Particles move 30 times a second, but their canvas was cleared and
redrawn every frame. It is now redrawn after the particles moved, and
only the area drawn last time is cleared.

Changed paths:
    engines/nancy/script/particles.cpp
    engines/nancy/script/particles.h


diff --git a/engines/nancy/script/particles.cpp b/engines/nancy/script/particles.cpp
index cf90544d4ce..66db467bc16 100644
--- a/engines/nancy/script/particles.cpp
+++ b/engines/nancy/script/particles.cpp
@@ -861,6 +861,7 @@ void ParticleRecord::simulate(double seconds) {
 
 void ParticleRecord::step() {
 	_spawnTime += 1.0 / kStepsPerSecond;
+	_hasStepped = true;
 
 	// A record that makes no particles keeps no time toward the next one
 	int numSpawned = 0;
@@ -1095,6 +1096,14 @@ void ParticleRecord::updateGraphics() {
 		return;
 	}
 
+	const ScriptMatrix transform = getTransform();
+	if (_canvas && _canvas->isVisible() && !_hasStepped && transform == _drawnTransform) {
+		return;
+	}
+
+	_hasStepped = false;
+	_drawnTransform = transform;
+
 	if (!_canvas) {
 		const Common::Rect bounds = RecordGraphic::getDrawArea();
 
@@ -1109,11 +1118,13 @@ void ParticleRecord::updateGraphics() {
 		_image.convertToInPlace(_canvas->_drawSurface.format);
 	}
 
-	_canvas->_drawSurface.clear(0);
+	if (!_drawnArea.isEmpty()) {
+		_canvas->_drawSurface.fillRect(_drawnArea, 0);
+	}
 
-	const ScriptMatrix transform = getTransform();
+	_drawnArea = Common::Rect();
 	for (uint i = 0; i < _count; ++i) {
-		drawParticle(_particles[(_first + i) % _particles.size()], transform);
+		drawParticle(_particles[(_first + i) % _particles.size()], transform, _drawnArea);
 	}
 
 	_canvas->setVisible(true);
@@ -1163,7 +1174,7 @@ static bool narrowSpan(double start, double step, int &first, int &last) {
 
 // A particle is a square of a part of the image, sized, turned and moved into
 // place, then seen through the projection
-void ParticleRecord::drawParticle(const Particle &particle, const ScriptMatrix &transform) {
+void ParticleRecord::drawParticle(const Particle &particle, const ScriptMatrix &transform, Common::Rect &drawnArea) {
 	if (particle.width <= 0.0 || particle.height <= 0.0 || (particle.color >> 24) == 0) {
 		return;
 	}
@@ -1213,6 +1224,13 @@ void ParticleRecord::drawParticle(const Particle &particle, const ScriptMatrix &
 		return;
 	}
 
+	const Common::Rect area(minX, minY, maxX + 1, maxY + 1);
+	if (drawnArea.isEmpty()) {
+		drawnArea = area;
+	} else {
+		drawnArea.extend(area);
+	}
+
 	// Both pictures are in the 32 bit format with alpha, so their pixels are read
 	// directly; that is a lot quicker for the thousands of particles of smoke
 	const Graphics::PixelFormat &format = target.format;
diff --git a/engines/nancy/script/particles.h b/engines/nancy/script/particles.h
index a9755b89ce3..602385b49f3 100644
--- a/engines/nancy/script/particles.h
+++ b/engines/nancy/script/particles.h
@@ -120,7 +120,7 @@ private:
 	void grow();
 	void dropOldestBatch();
 	void runStages(uint first, uint count, bool isSpawn);
-	void drawParticle(const Particle &particle, const ScriptMatrix &transform);
+	void drawParticle(const Particle &particle, const ScriptMatrix &transform, Common::Rect &drawnArea);
 
 	Graphics::ManagedSurface _image;
 	Common::Array<Particle> _particles;	// used as a ring, which grows when full
@@ -145,6 +145,14 @@ private:
 	double _fastForward = 0.0;	// seconds to run through when the record starts
 
 	RecordGraphic *_canvas = nullptr;
+
+	// The particles only move with the steps of the simulation, 30 a second,
+	// while the screen gets drawn 60 times a second. The canvas is drawn anew
+	// only when they moved or the record's transform changed, and only the
+	// part of it that was drawn on gets cleared.
+	bool _hasStepped = false;
+	ScriptMatrix _drawnTransform;
+	Common::Rect _drawnArea;
 };
 
 // The stages scripts get back from a record by name


Commit: 12f28ce17f02adfda5f2c66cdd91bb0269c03a1f
    https://github.com/scummvm/scummvm/commit/12f28ce17f02adfda5f2c66cdd91bb0269c03a1f
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:27+02:00

Commit Message:
NANCY: NANCY19: Only let boot scripts use the Init objects

InventoryInit and the other Init objects now only exist while the boot
scripts run. Nancy32's inventory screen includes the boot script of
the items, which only calls InventoryInit when it exists.

Changed paths:
    engines/nancy/script/api.cpp


diff --git a/engines/nancy/script/api.cpp b/engines/nancy/script/api.cpp
index 43c54590c35..0a5e74471c3 100644
--- a/engines/nancy/script/api.cpp
+++ b/engines/nancy/script/api.cpp
@@ -26,6 +26,7 @@
 #include "engines/nancy/script/convo.h"
 #include "engines/nancy/script/graphnode.h"
 #include "engines/nancy/script/luabind.h"
+#include "engines/nancy/script/luastate.h"
 #include "engines/nancy/script/mathtypes.h"
 #include "engines/nancy/script/particles.h"
 #include "engines/nancy/script/physics.h"
@@ -85,7 +86,13 @@ void registerAPI(lua_State *L) {
 	registerTypes(L);
 	registerMathTypes(L);
 	registerRefAPI(L);
-	registerBootAPI(L);
+
+	// The "Init" objects are only there for the boot scripts. Nancy32's inventory
+	// screen includes the boot script of the items, which checks for them.
+	if (!LuaState::getContext(L)) {
+		registerBootAPI(L);
+	}
+
 	registerInventoryAPI(L);
 	registerGameAPI(L);
 	registerGraphNodeAPI(L);


Commit: 96439b1f0f564b96dfe24703d9a34c8e8ed41924
    https://github.com/scummvm/scummvm/commit/96439b1f0f564b96dfe24703d9a34c8e8ed41924
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:28+02:00

Commit Message:
NANCY: NANCY32: Read XSheets from loose .cif files

Nancy32 has no ciftree: all its files are loose .cif files, which
images and scripts were already read from.

Changed paths:
    engines/nancy/resource/xsheetfile.cpp


diff --git a/engines/nancy/resource/xsheetfile.cpp b/engines/nancy/resource/xsheetfile.cpp
index a0c1bd320ca..c921a51ee82 100644
--- a/engines/nancy/resource/xsheetfile.cpp
+++ b/engines/nancy/resource/xsheetfile.cpp
@@ -25,6 +25,7 @@
 
 #include "engines/nancy/nancy.h"
 #include "engines/nancy/util.h"
+#include "engines/nancy/resource/cif.h"
 #include "engines/nancy/resource/xsheetfile.h"
 
 namespace Nancy {
@@ -35,7 +36,15 @@ static const uint kNancy29XSheetNameSize = 64;
 static const uint kXSheetCelRecordSize = 140;
 
 bool XSheetFile::load(const Common::String &name) {
-	Common::SeekableReadStream *xsheet = SearchMan.createReadStreamForMember(Common::Path(name));
+	// Nancy32 has no tree, only loose .cif files
+	Common::SeekableReadStream *xsheet = SearchMan.createReadStreamForMember(Common::Path(name + ".cif"));
+	if (xsheet) {
+		CifFile cifFile(xsheet, Common::Path(name)); // takes ownership of the stream
+		xsheet = cifFile.createReadStream();
+	} else {
+		xsheet = SearchMan.createReadStreamForMember(Common::Path(name));
+	}
+
 	if (!xsheet) {
 		warning("Could not open XSheet file %s", name.c_str());
 		return false;


Commit: 7a052aec894821e66310e9bbbe97ec8a21bd0f40
    https://github.com/scummvm/scummvm/commit/7a052aec894821e66310e9bbbe97ec8a21bd0f40
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:30+02:00

Commit Message:
NANCY: NANCY32: Use 2D matrices

Nancy32's matrices are SRTs: a scale, a rotation and a translation.
Two of them combine part by part: the scales multiply, the rotations
add up, and the second moves the translation of the first. Matrix:New
takes these five numbers, and Matrix:Rotate is new.

Changed paths:
    engines/nancy/script/mathtypes.cpp
    engines/nancy/script/mathtypes.h
    engines/nancy/script/particles.cpp
    engines/nancy/script/transformer.cpp
    engines/nancy/script/v5/animator.cpp


diff --git a/engines/nancy/script/mathtypes.cpp b/engines/nancy/script/mathtypes.cpp
index 28d76976feb..9dc23ab299d 100644
--- a/engines/nancy/script/mathtypes.cpp
+++ b/engines/nancy/script/mathtypes.cpp
@@ -58,7 +58,34 @@ ScriptMatrix::ScriptMatrix() {
 	}
 }
 
+// Nancy32 combines and undoes SRTs part by part
+static bool combinesAsSRTs(const ScriptMatrix &a, const ScriptMatrix &b) {
+	return a.isSRT && b.isSRT && g_nancy->getGameType() >= kGameTypeNancy32;
+}
+
+ScriptMatrix ScriptMatrix::makeSRT(double scaleX, double scaleY, double rotation, double x, double y) {
+	ScriptMatrix matrix;
+	matrix.scaleX = scaleX;
+	matrix.scaleY = scaleY;
+	matrix.rotation = rotation;
+
+	const double cosine = cos(rotation);
+	const double sine = sin(rotation);
+	matrix.m[0][0] = scaleX * cosine;
+	matrix.m[0][1] = scaleY * sine;
+	matrix.m[1][0] = -scaleX * sine;
+	matrix.m[1][1] = scaleY * cosine;
+	matrix.m[3][0] = x;
+	matrix.m[3][1] = y;
+	return matrix;
+}
+
 bool ScriptMatrix::operator==(const ScriptMatrix &other) const {
+	if (combinesAsSRTs(*this, other)) {
+		return scaleX == other.scaleX && scaleY == other.scaleY && rotation == other.rotation &&
+			m[3][0] == other.m[3][0] && m[3][1] == other.m[3][1];
+	}
+
 	for (int row = 0; row < 4; ++row) {
 		for (int column = 0; column < 4; ++column) {
 			if (m[row][column] != other.m[row][column]) {
@@ -71,7 +98,15 @@ bool ScriptMatrix::operator==(const ScriptMatrix &other) const {
 }
 
 ScriptMatrix ScriptMatrix::operator*(const ScriptMatrix &other) const {
+	if (combinesAsSRTs(*this, other)) {
+		double x = m[3][0];
+		double y = m[3][1];
+		other.transformPoint(x, y);
+		return makeSRT(scaleX * other.scaleX, scaleY * other.scaleY, rotation + other.rotation, x, y);
+	}
+
 	ScriptMatrix result;
+	result.isSRT = false;
 
 	for (int row = 0; row < 4; ++row) {
 		for (int column = 0; column < 4; ++column) {
@@ -563,9 +598,23 @@ ScriptMatrix &checkMatrix(lua_State *L, int index) {
 	return *(ScriptMatrix *)checkUserData(L, index, kMatrixType);
 }
 
-// Matrix:New(sixteen numbers, row by row)
+// Matrix:New(sixteen numbers, row by row). Nancy32: Matrix:New(scaleX, scaleY,
+// rotation, x, y), an SRT, or Matrix:New(matrix), a copy.
 static int matrixNew(lua_State *L) {
+	const int numArgs = lua_gettop(L) - 1;
+	if (numArgs == 5) {
+		pushMatrix(L, ScriptMatrix::makeSRT(luaL_checknumber(L, 2), luaL_checknumber(L, 3),
+			luaL_checknumber(L, 4), luaL_checknumber(L, 5), luaL_checknumber(L, 6)));
+		return 1;
+	}
+
+	if (numArgs == 1) {
+		pushMatrix(L, checkMatrix(L, 2));
+		return 1;
+	}
+
 	ScriptMatrix matrix;
+	matrix.isSRT = false;
 	for (int i = 0; i < 16; ++i) {
 		matrix.m[i / 4][i % 4] = luaL_checknumber(L, i + 2);
 	}
@@ -574,16 +623,21 @@ static int matrixNew(lua_State *L) {
 	return 1;
 }
 
-// Matrix:Translate(x, y, z)
+// Matrix:Translate(x, y, z). Nancy32 has no z.
 static int matrixTranslate(lua_State *L) {
-	ScriptMatrix matrix;
-	matrix.m[3][0] = luaL_checknumber(L, 2);
-	matrix.m[3][1] = luaL_checknumber(L, 3);
-	matrix.m[3][2] = luaL_checknumber(L, 4);
+	ScriptMatrix matrix = ScriptMatrix::makeSRT(1.0, 1.0, 0.0, luaL_checknumber(L, 2), luaL_checknumber(L, 3));
+	matrix.m[3][2] = luaL_optnumber(L, 4, 0.0);
+	matrix.isSRT = matrix.m[3][2] == 0.0;
 	pushMatrix(L, matrix);
 	return 1;
 }
 
+// Matrix:Rotate(angle), Nancy32: a turn by the angle in radians
+static int matrixRotate(lua_State *L) {
+	pushMatrix(L, ScriptMatrix::makeSRT(1.0, 1.0, luaL_checknumber(L, 2), 0.0, 0.0));
+	return 1;
+}
+
 // Matrix:Perspective(fovy, aspectRatio, zNear, zFar), Nancy21: the projection of a
 // camera looking down the z axis, for the particles
 static int matrixPerspective(lua_State *L) {
@@ -595,6 +649,7 @@ static int matrixPerspective(lua_State *L) {
 	const double yScale = 1.0 / tan(fovy / 2.0);
 
 	ScriptMatrix matrix;
+	matrix.isSRT = false;
 	matrix.m[0][0] = yScale / aspectRatio;
 	matrix.m[1][1] = yScale;
 	matrix.m[2][2] = zFar / (zFar - zNear);
@@ -605,12 +660,11 @@ static int matrixPerspective(lua_State *L) {
 	return 1;
 }
 
-// Matrix:Scale(x, y, z)
+// Matrix:Scale(x, y, z). Nancy32 has no z.
 static int matrixScale(lua_State *L) {
-	ScriptMatrix matrix;
-	matrix.m[0][0] = luaL_checknumber(L, 2);
-	matrix.m[1][1] = luaL_checknumber(L, 3);
-	matrix.m[2][2] = luaL_checknumber(L, 4);
+	ScriptMatrix matrix = ScriptMatrix::makeSRT(luaL_checknumber(L, 2), luaL_checknumber(L, 3), 0.0, 0.0, 0.0);
+	matrix.m[2][2] = luaL_optnumber(L, 4, 1.0);
+	matrix.isSRT = matrix.m[2][2] == 1.0;
 	pushMatrix(L, matrix);
 	return 1;
 }
@@ -639,6 +693,7 @@ static int matrixRotateAngle(lua_State *L) {
 	}
 
 	ScriptMatrix matrix;
+	matrix.isSRT = false;
 	matrix.m[first][first] = cosine;
 	matrix.m[first][second] = sine;
 	matrix.m[second][first] = -sine;
@@ -652,6 +707,7 @@ static int matrixRotateAngle(lua_State *L) {
 // turn, which goes in the same direction as RotateAngle
 static ScriptMatrix makeRotation(const double v[3], double outer, double diagonal, double turn) {
 	ScriptMatrix matrix;
+	matrix.isSRT = false;
 	for (int row = 0; row < 3; ++row) {
 		for (int column = 0; column < 3; ++column) {
 			matrix.m[row][column] = outer * v[row] * v[column];
@@ -738,6 +794,7 @@ static int matrixNewIndex(lua_State *L) {
 		matrix.m[row][i] = vector.v[i];
 	}
 
+	matrix.isSRT = false;
 	return 0;
 }
 
@@ -755,6 +812,7 @@ static int matrixTranspose(lua_State *L) {
 	const ScriptMatrix &matrix = checkMatrix(L, 1);
 
 	ScriptMatrix result;
+	result.isSRT = false;
 	for (int row = 0; row < 4; ++row) {
 		for (int column = 0; column < 4; ++column) {
 			result.m[row][column] = matrix.m[column][row];
@@ -766,8 +824,20 @@ static int matrixTranspose(lua_State *L) {
 }
 
 ScriptMatrix ScriptMatrix::inverse() const {
+	// Nancy32 undoes the scale and the rotation, and then the translation with them
+	if (combinesAsSRTs(*this, *this)) {
+		ScriptMatrix result = makeSRT(1.0 / scaleX, 1.0 / scaleY, -rotation, 0.0, 0.0);
+		double x = m[3][0];
+		double y = m[3][1];
+		result.transformPoint(x, y);
+		result.m[3][0] = -x;
+		result.m[3][1] = -y;
+		return result;
+	}
+
 	ScriptMatrix work = *this;
 	ScriptMatrix result;
+	result.isSRT = false;
 
 	for (int column = 0; column < 4; ++column) {
 		// The row with the largest value in this column goes on the diagonal
@@ -879,6 +949,7 @@ static const luaL_Reg kMatrixHelperFunctions[] = {
 	{ "Translate", matrixTranslate },
 	{ "Scaling", matrixScale },
 	{ "Scale", matrixScale },
+	{ "Rotate", matrixRotate },
 	{ "Perspective", matrixPerspective },
 	{ "RotationAngle", matrixRotateAngle },
 	{ "RotateAngle", matrixRotateAngle },
diff --git a/engines/nancy/script/mathtypes.h b/engines/nancy/script/mathtypes.h
index 37a1a059ba1..89ae4fb2075 100644
--- a/engines/nancy/script/mathtypes.h
+++ b/engines/nancy/script/mathtypes.h
@@ -47,11 +47,27 @@ struct ScriptVector {
 
 // Four rows of four. Vectors are rows, so the offset a matrix moves things by is
 // its last row, and a product does what its left side does first.
+//
+// Nancy32 replaced the matrices with SRTs (scale, rotation, translation) in two
+// dimensions. An SRT rotates a point, then scales it, then translates it. Two
+// of them combine part by part: the scales multiply, the rotations add up, and
+// the second one moves the translation of the first. That only comes out as the
+// product of their matrices when they scale the same along both axes, so a
+// matrix also keeps the parts it was made from.
 struct ScriptMatrix {
 	double m[4][4];
 
+	// The parts of the matrix as an SRT. The translation is m[3][0] and m[3][1].
+	// A matrix that was filled in some other way isn't an SRT.
+	bool isSRT = true;
+	double scaleX = 1.0;
+	double scaleY = 1.0;
+	double rotation = 0.0;	// in radians
+
 	ScriptMatrix();	// the identity
 
+	static ScriptMatrix makeSRT(double scaleX, double scaleY, double rotation, double x, double y);
+
 	bool operator==(const ScriptMatrix &other) const;
 	bool operator!=(const ScriptMatrix &other) const { return !(*this == other); }
 	ScriptMatrix operator*(const ScriptMatrix &other) const;
diff --git a/engines/nancy/script/particles.cpp b/engines/nancy/script/particles.cpp
index 66db467bc16..8c4ecea589a 100644
--- a/engines/nancy/script/particles.cpp
+++ b/engines/nancy/script/particles.cpp
@@ -1180,6 +1180,7 @@ void ParticleRecord::drawParticle(const Particle &particle, const ScriptMatrix &
 	}
 
 	ScriptMatrix place;
+	place.isSRT = false;
 	const double c = cos(particle.angle);
 	const double s = sin(particle.angle);
 	const double width = particle.width * particle.scale;
diff --git a/engines/nancy/script/transformer.cpp b/engines/nancy/script/transformer.cpp
index d9951829cea..1d0d8e0a9d5 100644
--- a/engines/nancy/script/transformer.cpp
+++ b/engines/nancy/script/transformer.cpp
@@ -82,19 +82,14 @@ ScriptMatrix BlendStages::makeMatrix(StageKind kind, const double value[2]) {
 
 	switch (kind) {
 	case kTranslation:
-		matrix.m[3][0] = value[0];
-		matrix.m[3][1] = value[1];
+		matrix = ScriptMatrix::makeSRT(1.0, 1.0, 0.0, value[0], value[1]);
 		break;
 	case kRotation:
 		// D3DXMatrixRotationZ
-		matrix.m[0][0] = cos(value[0]);
-		matrix.m[0][1] = sin(value[0]);
-		matrix.m[1][0] = -sin(value[0]);
-		matrix.m[1][1] = cos(value[0]);
+		matrix = ScriptMatrix::makeSRT(1.0, 1.0, value[0], 0.0, 0.0);
 		break;
 	case kScale:
-		matrix.m[0][0] = value[0];
-		matrix.m[1][1] = value[1];
+		matrix = ScriptMatrix::makeSRT(value[0], value[1], 0.0, 0.0, 0.0);
 		break;
 	case kAlpha:
 		break;
diff --git a/engines/nancy/script/v5/animator.cpp b/engines/nancy/script/v5/animator.cpp
index b6bfdd46230..e0b9d44e8e8 100644
--- a/engines/nancy/script/v5/animator.cpp
+++ b/engines/nancy/script/v5/animator.cpp
@@ -72,19 +72,14 @@ void AnimatorTrack::setValue(const double value[2]) {
 	_matrix = ScriptMatrix();
 	switch (_kind) {
 	case kScale:
-		_matrix.m[0][0] = value[0];
-		_matrix.m[1][1] = value[1];
+		_matrix = ScriptMatrix::makeSRT(value[0], value[1], 0.0, 0.0, 0.0);
 		break;
 	case kRotation:
 		// D3DXMatrixRotationZ
-		_matrix.m[0][0] = cos(value[0]);
-		_matrix.m[0][1] = sin(value[0]);
-		_matrix.m[1][0] = -sin(value[0]);
-		_matrix.m[1][1] = cos(value[0]);
+		_matrix = ScriptMatrix::makeSRT(1.0, 1.0, value[0], 0.0, 0.0);
 		break;
 	case kTranslation:
-		_matrix.m[3][0] = value[0];
-		_matrix.m[3][1] = value[1];
+		_matrix = ScriptMatrix::makeSRT(1.0, 1.0, 0.0, value[0], value[1]);
 		break;
 	default:
 		break;


Commit: b264b3127a0970643730732caf209650f21a893e
    https://github.com/scummvm/scummvm/commit/b264b3127a0970643730732caf209650f21a893e
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:31+02:00

Commit Message:
NANCY: NANCY32: Use points in place of vectors

Nancy32 has no vectors: the animator tracks return points, particle
fields take points, and Rect:Transform returns two points. Points
also get TransformCoord, TransformNormal and Norm.

Changed paths:
    engines/nancy/script/mathtypes.cpp
    engines/nancy/script/particles.cpp
    engines/nancy/script/types.cpp
    engines/nancy/script/types.h
    engines/nancy/script/v5/animator.cpp


diff --git a/engines/nancy/script/mathtypes.cpp b/engines/nancy/script/mathtypes.cpp
index 9dc23ab299d..69b7072c3ba 100644
--- a/engines/nancy/script/mathtypes.cpp
+++ b/engines/nancy/script/mathtypes.cpp
@@ -1299,8 +1299,14 @@ static const luaL_Reg kPathHelperFunctions[] = {
 	{ nullptr, nullptr }
 };
 
+// A number rounded half away from zero, as Nancy32 rounds the corners of a rect
+static double roundAwayFromZero(double value) {
+	return value < 0.0 ? ceil(value - 0.5) : floor(value + 0.5);
+}
+
 // rect:Transform(matrix). Nancy22 moves all four corners, and gives the
-// smallest and the largest of them as two vectors.
+// smallest and the largest of them as two vectors. Nancy32 rounds them, and
+// gives them as two points.
 static int rectTransform(lua_State *L) {
 	const ScriptRect &rect = checkRect(L, 1);
 	const ScriptMatrix &matrix = checkMatrix(L, 2);
@@ -1310,6 +1316,28 @@ static int rectTransform(lua_State *L) {
 		return 1;
 	}
 
+	if (g_nancy->getGameType() >= kGameTypeNancy32) {
+		const double corners[4][2] = {
+			{ (double)rect.left, (double)rect.top }, { (double)rect.right, (double)rect.top },
+			{ (double)rect.left, (double)rect.bottom }, { (double)rect.right, (double)rect.bottom }
+		};
+
+		double minimum[2] = { 1e300, 1e300 };
+		double maximum[2] = { -1e300, -1e300 };
+		for (const double *corner : corners) {
+			double point[2] = { corner[0], corner[1] };
+			matrix.transformPoint(point[0], point[1]);
+			for (int i = 0; i < 2; ++i) {
+				minimum[i] = MIN(minimum[i], point[i]);
+				maximum[i] = MAX(maximum[i], point[i]);
+			}
+		}
+
+		pushPointCoordinates(L, roundAwayFromZero(minimum[0]), roundAwayFromZero(minimum[1]));
+		pushPointCoordinates(L, roundAwayFromZero(maximum[0]), roundAwayFromZero(maximum[1]));
+		return 2;
+	}
+
 	const double corners[4][2] = {
 		{ (double)rect.left, (double)rect.top }, { (double)rect.right, (double)rect.top },
 		{ (double)rect.left, (double)rect.bottom }, { (double)rect.right, (double)rect.bottom }
@@ -1336,6 +1364,30 @@ static int rectTransform(lua_State *L) {
 	return 2;
 }
 
+// point:TransformCoord(matrix) and point:TransformNormal(matrix), Nancy32: the
+// point moved by the matrix, without the offset for TransformNormal
+static int pointTransformCoord(lua_State *L) {
+	double x, y;
+	if (!readPointCoordinates(L, 1, x, y)) {
+		return luaL_typerror(L, 1, "ND.Point");
+	}
+
+	checkMatrix(L, 2).transformPoint(x, y);
+	pushPointCoordinates(L, x, y);
+	return 1;
+}
+
+static int pointTransformNormal(lua_State *L) {
+	double x, y;
+	if (!readPointCoordinates(L, 1, x, y)) {
+		return luaL_typerror(L, 1, "ND.Point");
+	}
+
+	const ScriptMatrix &matrix = checkMatrix(L, 2);
+	pushPointCoordinates(L, x * matrix.m[0][0] + y * matrix.m[1][0], x * matrix.m[0][1] + y * matrix.m[1][1]);
+	return 1;
+}
+
 void registerMathTypes(lua_State *L) {
 	registerType(L, kVectorType, kVectorFunctions);
 	registerGlobal(L, "Vector", kVectorHelperType, kVectorHelperFunctions);
@@ -1349,11 +1401,18 @@ void registerMathTypes(lua_State *L) {
 	registerType(L, kPathType, kPathFunctions);
 	registerGlobal(L, "Path", kPathHelperType, kPathHelperFunctions);
 
-	// Rectangles can be moved by a matrix as well
+	// Rectangles and points can be moved by a matrix as well
 	luaL_getmetatable(L, "ND.Rect");
 	lua_pushcfunction(L, rectTransform);
 	lua_setfield(L, -2, "Transform");
 	lua_pop(L, 1);
+
+	luaL_getmetatable(L, "ND.Point");
+	lua_pushcfunction(L, pointTransformCoord);
+	lua_setfield(L, -2, "TransformCoord");
+	lua_pushcfunction(L, pointTransformNormal);
+	lua_setfield(L, -2, "TransformNormal");
+	lua_pop(L, 1);
 }
 
 } // End of namespace Script
diff --git a/engines/nancy/script/particles.cpp b/engines/nancy/script/particles.cpp
index 8c4ecea589a..05ae211605a 100644
--- a/engines/nancy/script/particles.cpp
+++ b/engines/nancy/script/particles.cpp
@@ -135,21 +135,40 @@ public:
 	}
 };
 
+// Reads a vector into the given one. Nancy32 has no vectors, and gives points
+// instead, which are at no depth.
+static bool readVectorValue(lua_State *L, int index, double *out, int size) {
+	const ScriptVector *vector = testVector(L, index);
+	if (vector) {
+		for (int i = 0; i < size; ++i) {
+			out[i] = vector->v[i];
+		}
+
+		return true;
+	}
+
+	double x, y;
+	if (!readPointCoordinates(L, index, x, y)) {
+		return false;
+	}
+
+	for (int i = 0; i < size; ++i) {
+		out[i] = i == 0 ? x : (i == 1 ? y : 0.0);
+	}
+
+	return true;
+}
+
 // Reads a vector field of the stage's table into the given one
 static bool readVectorField(lua_State *L, int tableIndex, const char *name, double *out, int size) {
 	if (!pushField(L, tableIndex, name)) {
 		return false;
 	}
 
-	const ScriptVector *vector = testVector(L, -1);
-	if (!vector) {
+	if (!readVectorValue(L, -1, out, size)) {
 		luaL_error(L, "field %s must be a vector", name);
 	}
 
-	for (int i = 0; i < size; ++i) {
-		out[i] = vector->v[i];
-	}
-
 	lua_pop(L, 1);
 	return true;
 }
@@ -525,15 +544,10 @@ public:
 			return false;
 		}
 
-		const ScriptVector *vector = testVector(L, -1);
-		if (!vector) {
+		if (!readVectorValue(L, -1, corner, 3)) {
 			luaL_typerror(L, -1, "Vector");
 		}
 
-		for (int i = 0; i < 3; ++i) {
-			corner[i] = vector->v[i];
-		}
-
 		return true;
 	}
 
@@ -661,15 +675,13 @@ public:
 
 	bool setField(lua_State *L, const Common::String &key) override {
 		if (key == "position") {
-			const ScriptVector *vector = testVector(L, -1);
-			if (!vector) {
+			double position[3];
+			if (!readVectorValue(L, -1, position, 3)) {
 				luaL_typerror(L, -1, "Vector");
 			}
 
 			memcpy(_position[0], _position[1], sizeof(_position[0]));
-			for (int i = 0; i < 3; ++i) {
-				_position[1][i] = vector->v[i];
-			}
+			memcpy(_position[1], position, sizeof(position));
 		} else if (key == "scale") {
 			_scale[0] = _scale[1];
 			_scale[1] = luaL_checknumber(L, -1);
diff --git a/engines/nancy/script/types.cpp b/engines/nancy/script/types.cpp
index 2cdca654b00..d43310f9580 100644
--- a/engines/nancy/script/types.cpp
+++ b/engines/nancy/script/types.cpp
@@ -460,6 +460,10 @@ void pushPoint(lua_State *L, const Common::Point32 &point) {
 	pushPointValue(L, PointValue(point.x, point.y));
 }
 
+void pushPointCoordinates(lua_State *L, double x, double y) {
+	pushPointValue(L, hasFractionalPoints() ? PointValue(x, y) : PointValue((int32)x, (int32)y));
+}
+
 static PointValue &checkPoint(lua_State *L, int index) {
 	return *(PointValue *)checkUserData(L, index, kPointType);
 }
@@ -639,7 +643,8 @@ static int pointFloored(lua_State *L) {
 	return 1;
 }
 
-// Point:Dot(point) and Point:Normalized(), Nancy31. A point at the origin stays there.
+// Point:Dot(point) and Point:Normalized(), Nancy31, which Nancy32 also calls
+// Point:Norm(). A point at the origin stays there.
 static int pointDot(lua_State *L) {
 	const PointValue &a = checkPoint(L, 1);
 	const PointValue &b = checkPoint(L, 2);
@@ -691,6 +696,7 @@ static const luaL_Reg kPointFunctions[] = {
 	{ "Floored", pointFloored },
 	{ "Dot", pointDot },
 	{ "Normalized", pointNormalized },
+	{ "Norm", pointNormalized },
 	{ nullptr, nullptr }
 };
 
diff --git a/engines/nancy/script/types.h b/engines/nancy/script/types.h
index 855797e92f4..bcc96cc2a28 100644
--- a/engines/nancy/script/types.h
+++ b/engines/nancy/script/types.h
@@ -69,6 +69,9 @@ ScriptRect &checkRect(lua_State *L, int index);
 
 void pushPoint(lua_State *L, const Common::Point32 &point);
 
+// A point that keeps the fractions of its coordinates when the game has them
+void pushPointCoordinates(lua_State *L, double x, double y);
+
 // Reads anything that has an x and a y: a point, a vector or a table.
 // Returns false when the value has neither.
 bool readPoint(lua_State *L, int index, Common::Point32 &point);
diff --git a/engines/nancy/script/v5/animator.cpp b/engines/nancy/script/v5/animator.cpp
index e0b9d44e8e8..e03e5b392ba 100644
--- a/engines/nancy/script/v5/animator.cpp
+++ b/engines/nancy/script/v5/animator.cpp
@@ -207,10 +207,13 @@ void AnimatorTrack::readValue(lua_State *L, int index, double value[2]) const {
 	lua_pop(L, 2);
 }
 
-// Scales and translations are returned as vectors
+// Scales and translations are returned as vectors, and as points from
+// Nancy32 on, which has no vectors
 void AnimatorTrack::pushValue(lua_State *L) const {
 	if (_kind == kAlpha || _kind == kRotation) {
 		lua_pushnumber(L, _current[0]);
+	} else if (g_nancy->getGameType() >= kGameTypeNancy32) {
+		pushPointCoordinates(L, _current[0], _current[1]);
 	} else {
 		pushVector(L, ScriptVector(_current[0], _current[1], 0.0));
 	}


Commit: be3cf59b3f88b210f433611f41fce3c581fc4bcf
    https://github.com/scummvm/scummvm/commit/be3cf59b3f88b210f433611f41fce3c581fc4bcf
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:33+02:00

Commit Message:
NANCY: NANCY32: Add the polar track of the animator

Track p of an animator stage moves the record by a radius and an
angle, after the other tracks. The pieces of the wheel puzzle move
around the wheel with it.

Changed paths:
    engines/nancy/script/v5/animator.cpp
    engines/nancy/script/v5/animator.h


diff --git a/engines/nancy/script/v5/animator.cpp b/engines/nancy/script/v5/animator.cpp
index e03e5b392ba..14fc758c46f 100644
--- a/engines/nancy/script/v5/animator.cpp
+++ b/engines/nancy/script/v5/animator.cpp
@@ -54,6 +54,8 @@ const char *AnimatorTrack::getTypeName(Kind kind) {
 		return "ND.AnimatorScaleTrack";
 	case kRotation:
 		return "ND.AnimatorRotationTrack";
+	case kPolar:
+		return "ND.AnimatorPolarTrack";
 	default:
 		return "ND.AnimatorTranslationTrack";
 	}
@@ -81,6 +83,9 @@ void AnimatorTrack::setValue(const double value[2]) {
 	case kTranslation:
 		_matrix = ScriptMatrix::makeSRT(1.0, 1.0, 0.0, value[0], value[1]);
 		break;
+	case kPolar:
+		_matrix = ScriptMatrix::makeSRT(1.0, 1.0, 0.0, value[0] * cos(value[1]), value[0] * sin(value[1]));
+		break;
 	default:
 		break;
 	}
@@ -228,6 +233,7 @@ AnimatorStage::AnimatorStage(Animator &animator, uint index, double alpha) :
 	_tracks[AnimatorTrack::kScale] = new AnimatorTrack(*this, AnimatorTrack::kScale, 1.0, 1.0);
 	_tracks[AnimatorTrack::kRotation] = new AnimatorTrack(*this, AnimatorTrack::kRotation, 0.0, 0.0);
 	_tracks[AnimatorTrack::kTranslation] = new AnimatorTrack(*this, AnimatorTrack::kTranslation, 0.0, 0.0);
+	_tracks[AnimatorTrack::kPolar] = new AnimatorTrack(*this, AnimatorTrack::kPolar, 0.0, 0.0);
 }
 
 AnimatorStage::~AnimatorStage() {
@@ -300,7 +306,8 @@ void AnimatorStage::finishBlending() {
 void AnimatorStage::updateMatrix() {
 	_matrix = _tracks[AnimatorTrack::kScale]->getMatrix() *
 		_tracks[AnimatorTrack::kRotation]->getMatrix() *
-		_tracks[AnimatorTrack::kTranslation]->getMatrix();
+		_tracks[AnimatorTrack::kTranslation]->getMatrix() *
+		_tracks[AnimatorTrack::kPolar]->getMatrix();
 }
 
 // The alpha track only changes the record's alpha, the others only its
@@ -522,7 +529,7 @@ static AnimatorStage &checkStage(lua_State *L) {
 
 static AnimatorTrack &checkTrack(lua_State *L) {
 	const AnimatorRef *ref = nullptr;
-	for (int kind = AnimatorTrack::kAlpha; !ref && kind <= AnimatorTrack::kTranslation; ++kind) {
+	for (int kind = AnimatorTrack::kAlpha; !ref && kind < AnimatorTrack::kNumKinds; ++kind) {
 		ref = (const AnimatorRef *)testUserData(L, 1, AnimatorTrack::getTypeName((AnimatorTrack::Kind)kind));
 	}
 
@@ -614,7 +621,7 @@ static int stageFinishBlending(lua_State *L) {
 }
 
 static bool findTrackKind(const char *name, AnimatorTrack::Kind &kind) {
-	static const char *const kTrackNames[] = { "a", "s", "r", "t" };
+	static const char *const kTrackNames[] = { "a", "s", "r", "t", "p" };
 	for (uint i = 0; i < ARRAYSIZE(kTrackNames); ++i) {
 		if (strcmp(name, kTrackNames[i]) == 0) {
 			kind = (AnimatorTrack::Kind)i;
@@ -625,8 +632,8 @@ static bool findTrackKind(const char *name, AnimatorTrack::Kind &kind) {
 	return false;
 }
 
-// stage.a, stage.s, stage.r and stage.t are its tracks. In Nancy30, other
-// names give what scripts stored in the stage.
+// stage.a, stage.s, stage.r and stage.t are its tracks, and in Nancy32 stage.p.
+// In Nancy30, other names give what scripts stored in the stage.
 static int stageIndex(lua_State *L) {
 	AnimatorTrack::Kind kind;
 	if (lua_type(L, 2) != LUA_TSTRING || !findTrackKind(lua_tostring(L, 2), kind)) {
@@ -651,7 +658,7 @@ static int stageIndex(lua_State *L) {
 // stage.t = value sets a track to a value. Nancy30 stores anything else in
 // the stage, like its OnDone function.
 static int stageNewIndex(lua_State *L) {
-	static const char *const kTrackDescriptions[] = { "Alpha", "Scale", "Rotation", "Translation" };
+	static const char *const kTrackDescriptions[] = { "Alpha", "Scale", "Rotation", "Translation", "Polar" };
 
 	AnimatorStage &stage = checkStage(L);
 	AnimatorTrack::Kind kind;
@@ -792,7 +799,7 @@ void Animator::registerTypes(lua_State *L) {
 
 	registerType(L, kAnimatorType, kAnimatorFunctions);
 	registerType(L, kAnimatorStageType, kStageFunctions);
-	for (int kind = AnimatorTrack::kAlpha; kind <= AnimatorTrack::kTranslation; ++kind) {
+	for (int kind = AnimatorTrack::kAlpha; kind < AnimatorTrack::kNumKinds; ++kind) {
 		registerType(L, AnimatorTrack::getTypeName((AnimatorTrack::Kind)kind), kTrackFunctions);
 	}
 }
diff --git a/engines/nancy/script/v5/animator.h b/engines/nancy/script/v5/animator.h
index c8d3a348194..10038d84b12 100644
--- a/engines/nancy/script/v5/animator.h
+++ b/engines/nancy/script/v5/animator.h
@@ -42,24 +42,27 @@ class AnimatorStage;
 //
 // An animator is a list of stages, numbered from 1, and starts with one stage.
 // Each stage has four tracks: a (alpha), s (scale), r (rotation) and t
-// (translation). A track plays the blends added to it one after the other,
-// each one moving it to a target value. A lerp blend moves at a constant
-// speed, while a "slerp" blend starts and ends slowly. When all tracks of a
-// stage have finished blending, the record's "Stage<n>Done" function is
-// called. Nancy30 calls the stage's own OnDone function instead, which
-// scripts store in the stage like any other field (ar.animator[1].OnDone).
+// (translation). Nancy32 adds p (polar), a translation by a radius and an
+// angle. A track plays the blends added to it one after the other, each one
+// moving it to a target value. A lerp blend moves at a constant speed, while a
+// "slerp" blend starts and ends slowly. When all tracks of a stage have
+// finished blending, the record's "Stage<n>Done" function is called. Nancy30
+// calls the stage's own OnDone function instead, which scripts store in the
+// stage like any other field (ar.animator[1].OnDone).
 //
 // The record's transform is the product of the transforms of the stages, in
-// order, and each stage scales, then rotates, then translates. The record's
-// alpha is the product of the alphas of the stages. Both are updated whenever
-// a stage changes or blends.
+// order, and each stage scales, then rotates, then translates (then moves by
+// its polar track). The record's alpha is the product of the alphas of the
+// stages. Both are updated whenever a stage changes or blends.
 class AnimatorTrack {
 public:
 	enum Kind {
 		kAlpha,
 		kScale,
 		kRotation,
-		kTranslation
+		kTranslation,
+		kPolar,		// Nancy32: the radius in x, the angle in radians in y
+		kNumKinds
 	};
 
 	enum BlendKind {
@@ -148,7 +151,7 @@ public:
 	void stopBlending();
 	void finishBlending();
 
-	// Scales, then rotates, then translates
+	// Scales, then rotates, then translates, then moves by the polar track
 	void updateMatrix();
 
 	// Called when a track was set to a value, when a script stopped or
@@ -163,7 +166,7 @@ public:
 private:
 	Animator &_animator;
 	uint _index;
-	AnimatorTrack *_tracks[4];
+	AnimatorTrack *_tracks[AnimatorTrack::kNumKinds];
 	ScriptMatrix _matrix;
 };
 


Commit: bc556c646facde8d4323039e2c61e0b4110c88c9
    https://github.com/scummvm/scummvm/commit/bc556c646facde8d4323039e2c61e0b4110c88c9
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:34+02:00

Commit Message:
NANCY: NANCY32: Let keys press hotspots

Hotspots can be given keys with AddKey. Holding one down presses the
hotspot, and letting it go clicks it. Puzzles use this for their
keyboard controls.

Changed paths:
    engines/nancy/input.cpp
    engines/nancy/input.h
    engines/nancy/script/v5/scriptinput.cpp
    engines/nancy/script/v5/scriptinput.h
    engines/nancy/script/v5/widgets.cpp
    engines/nancy/script/v5/widgets.h


diff --git a/engines/nancy/input.cpp b/engines/nancy/input.cpp
index 713a7c6716f..8d239d17e4a 100644
--- a/engines/nancy/input.cpp
+++ b/engines/nancy/input.cpp
@@ -19,6 +19,7 @@
  *
  */
 
+#include "common/algorithm.h"
 #include "common/translation.h"
 #include "common/system.h"
 
@@ -45,6 +46,10 @@ void InputManager::processEvents() {
 	while (g_nancy->getEventManager()->pollEvent(event)) {
 		switch (event.type) {
 		case EVENT_KEYDOWN:
+			if (!isKeyHeld(event.kbd.keycode)) {
+				_heldKeys.push_back(event.kbd.keycode);
+			}
+
 			// A held esc key repeats; once its press was taken away, so are the repeats
 			if (event.kbd.keycode == KEYCODE_ESCAPE) {
 				_isEscEaten &= event.kbdRepeat;
@@ -56,6 +61,15 @@ void InputManager::processEvents() {
 			// Push all keyboard events into an array and let getInput() callers handle them
 			_otherKbdInput.push_back(event.kbd);
 			_inputBeginState = g_nancy->getState();
+			break;
+		case EVENT_KEYUP:
+			for (uint i = 0; i < _heldKeys.size(); ++i) {
+				if (_heldKeys[i] == event.kbd.keycode) {
+					_heldKeys.remove_at(i);
+					break;
+				}
+			}
+
 			break;
 		case EVENT_WHEELUP:
 			_inputs |= NancyInput::kMouseWheelUp;
@@ -149,6 +163,10 @@ void InputManager::processEvents() {
 	}
 }
 
+bool InputManager::isKeyHeld(Common::KeyCode key) const {
+	return Common::find(_heldKeys.begin(), _heldKeys.end(), key) != _heldKeys.end();
+}
+
 NancyInput InputManager::getInput() const {
 	NancyInput ret;
 
diff --git a/engines/nancy/input.h b/engines/nancy/input.h
index b49ade0616c..4c07fef8a5d 100644
--- a/engines/nancy/input.h
+++ b/engines/nancy/input.h
@@ -102,6 +102,9 @@ public:
 	void processEvents();
 
 	NancyInput getInput() const;
+
+	// Nancy32: whether a key that isn't bound to an action is held down
+	bool isKeyHeld(Common::KeyCode key) const;
 	void forceCleanInput();
 	// Takes away an esc press that skipped something, so nothing else sees it,
 	// in this frame or later ones, until the key gets pressed again
@@ -117,6 +120,7 @@ public:
 private:
 	uint16 _inputs;
 	Common::Array<Common::KeyState> _otherKbdInput;
+	Common::Array<Common::KeyCode> _heldKeys;
 	bool _mouseEnabled;
 	bool _isEscEaten;
 	NancyState::NancyState _inputBeginState;
diff --git a/engines/nancy/script/v5/scriptinput.cpp b/engines/nancy/script/v5/scriptinput.cpp
index 5db81c67059..2c091611e01 100644
--- a/engines/nancy/script/v5/scriptinput.cpp
+++ b/engines/nancy/script/v5/scriptinput.cpp
@@ -398,6 +398,21 @@ static const MoveKey kMoveKeys[] = {
 	{ NancyInput::kMoveDown, Common::KEYCODE_DOWN }
 };
 
+bool isScriptKeyHeld(Common::KeyCode key) {
+	const InputState &state = getState();
+	for (const MoveKey &moveKey : kMoveKeys) {
+		if (moveKey.key == key) {
+			return (state.heldMoveKeys & moveKey.input) != 0;
+		}
+	}
+
+	if (key == Common::KEYCODE_ESCAPE) {
+		return state.isEscHeld;
+	}
+
+	return g_nancy->_input->isKeyHeld(key);
+}
+
 void handleNancy26Input(NancyInput &input) {
 	InputState &state = getState();
 
diff --git a/engines/nancy/script/v5/scriptinput.h b/engines/nancy/script/v5/scriptinput.h
index aa30c69b19a..6085d0bafb7 100644
--- a/engines/nancy/script/v5/scriptinput.h
+++ b/engines/nancy/script/v5/scriptinput.h
@@ -22,6 +22,8 @@
 #ifndef NANCY_SCRIPT_V5_SCRIPTINPUT_H
 #define NANCY_SCRIPT_V5_SCRIPTINPUT_H
 
+#include "common/keyboard.h"
+
 #include "engines/nancy/script/types.h"
 
 namespace Nancy {
@@ -49,6 +51,9 @@ bool isDoubleClick(int button);
 // A record that goes away can't keep the mouse
 void forgetInputRecord(Record *record);
 
+// Nancy32: whether a key is held down
+bool isScriptKeyHeld(Common::KeyCode key);
+
 } // End of namespace Script
 } // End of namespace Nancy
 
diff --git a/engines/nancy/script/v5/widgets.cpp b/engines/nancy/script/v5/widgets.cpp
index c408615c951..fb1f603a7f0 100644
--- a/engines/nancy/script/v5/widgets.cpp
+++ b/engines/nancy/script/v5/widgets.cpp
@@ -19,6 +19,7 @@
  *
  */
 
+#include "common/algorithm.h"
 #include "common/events.h"
 #include "common/system.h"
 
@@ -301,6 +302,112 @@ void HotspotRecord::fire() {
 	finish();
 }
 
+void HotspotRecord::addKey(Common::KeyCode key) {
+	if (Common::find(_keys.begin(), _keys.end(), key) == _keys.end()) {
+		_keys.push_back(key);
+	}
+}
+
+void HotspotRecord::removeKey(Common::KeyCode key) {
+	Common::Array<Common::KeyCode>::iterator found = Common::find(_keys.begin(), _keys.end(), key);
+	if (found == _keys.end()) {
+		return;
+	}
+
+	_keys.erase(found);
+	if (_keys.empty()) {
+		loseKeyFocus();
+	}
+}
+
+// Any key that makes it this far gives the hotspot the key focus. It doesn't
+// take the key, so the records behind it get it as well.
+bool HotspotRecord::handleKey(Common::KeyCode key, uint16 ascii) {
+	if (!_keys.empty()) {
+		_hasKeyFocus = true;
+	}
+
+	return false;
+}
+
+void HotspotRecord::loseKeyFocus() {
+	_hasKeyFocus = false;
+	if (_isKeyDown) {
+		_isKeyDown = false;
+		callFunction("OnLoseKeyFocus");
+	}
+}
+
+// Every frame, a hotspot with the key focus looks at whether one of its keys
+// is held down, and gets pressed or released when that changes
+void HotspotRecord::onFrame() {
+	if (_keys.empty() || !_hasKeyFocus) {
+		return;
+	}
+
+	if (!isNodeEnabled() || (_pressedButton >= 0 && !_isKeyDown)) {
+		loseKeyFocus();
+		return;
+	}
+
+	bool isHeld = false;
+	for (Common::KeyCode key : _keys) {
+		if (isScriptKeyHeld(key)) {
+			isHeld = true;
+			break;
+		}
+	}
+
+	if (isHeld == _isKeyDown) {
+		return;
+	}
+
+	_isKeyDown = isHeld;
+	if (isHeld) {
+		callFunction("OnKeyDown");
+		if (_widget) {
+			_widget->onHotspotDown(kKeyButton);
+		}
+	} else {
+		callFunction("OnKeyUp");
+		if (_widget) {
+			_widget->onHotspotUp(kKeyButton, true);
+		} else {
+			fire();
+		}
+	}
+}
+
+// hotspot:AddKey(key) and hotspot:RemoveKey(key), Nancy32. A string of one
+// letter or digit stands for its key.
+static Common::KeyCode checkHotspotKey(lua_State *L, int index) {
+	if (lua_type(L, index) == LUA_TSTRING) {
+		const char *name = lua_tostring(L, index);
+		return name[0] != 0 && name[1] == 0 ? (Common::KeyCode)tolower(name[0]) : Common::KEYCODE_INVALID;
+	}
+
+	return checkKey(L, index);
+}
+
+static HotspotRecord *checkHotspot(lua_State *L) {
+	HotspotRecord *record = dynamic_cast<HotspotRecord *>(checkRecord(L, 1));
+	if (!record) {
+		luaL_typerror(L, 1, "ND.Hotspot");
+	}
+
+	return record;
+}
+
+static int hotspotAddKey(lua_State *L) {
+	checkHotspot(L)->addKey(checkHotspotKey(L, 2));
+	return 0;
+}
+
+static int hotspotRemoveKey(lua_State *L) {
+	checkHotspot(L)->removeKey(checkHotspotKey(L, 2));
+	return 0;
+}
+
 bool HotspotRecord::getRegionCursor(uint &cursorType, bool &isHot) const {
 	const Cursor *cursor = &_cursor;
 	if (_pressedButton >= 0) {
@@ -376,6 +483,10 @@ bool HotspotRecord::getField(const Common::String &key) {
 		lua_pushboolean(L, _allowsSlide);
 	} else if (key == "slideDistance") {
 		lua_pushnumber(L, _slideDistance);
+	} else if (key == "AddKey") {
+		lua_pushcfunction(L, hotspotAddKey);
+	} else if (key == "RemoveKey") {
+		lua_pushcfunction(L, hotspotRemoveKey);
 	} else {
 		return false;
 	}
@@ -436,6 +547,8 @@ bool HotspotRecord::setField(const Common::String &key) {
 		_allowsSlide = lua_toboolean(L, 3) != 0;
 	} else if (key == "slideDistance") {
 		_slideDistance = luaL_checknumber(L, 3);
+	} else if (key == "AddKey" || key == "RemoveKey") {
+		luaL_error(L, "Cannot set '%s' field of a hotspot", key.c_str());
 	} else {
 		return false;
 	}
@@ -636,7 +749,10 @@ void WidgetRecord::onHotspotDown(int button) {
 		return;
 	}
 
-	_isLeftDown = button == 0;
+	// A key leaves it at the last mouse button
+	if (button != HotspotRecord::kKeyButton) {
+		_isLeftDown = button == 0;
+	}
 
 	switch (_type) {
 	case kRecordCheckBox:
diff --git a/engines/nancy/script/v5/widgets.h b/engines/nancy/script/v5/widgets.h
index f7b41cbc475..1d11e52118a 100644
--- a/engines/nancy/script/v5/widgets.h
+++ b/engines/nancy/script/v5/widgets.h
@@ -40,6 +40,8 @@ class WidgetRecord;
 // A hotspot calls OnLeftDown and OnLeftUp (or the right ones) of its scripts,
 // and OnMouseOver, OnMouseLeave and OnLoseMouseFocus. Once it was clicked, it
 // changes the scene when it has one, and is done.
+// Nancy32 can also press a hotspot with keys, which call OnKeyDown and
+// OnKeyUp; letting go of the key clicks it.
 // The shape is a rect, or the part of a Ref image that isn't see-through or has
 // a color; the rect and the source then lay the image over the screen.
 class HotspotRecord : public Record {
@@ -66,12 +68,22 @@ public:
 	// Nancy30: the mouse moved, which can put it over another tile
 	void onMouseMoved(const Common::Point32 &mouse);
 
+	// Nancy32: the keys that press the hotspot
+	void addKey(Common::KeyCode key);
+	void removeKey(Common::KeyCode key);
+	bool handleKey(Common::KeyCode key, uint16 ascii) override;
+
+	// What the widgets of a hotspot get told about its keys, in place of a
+	// mouse button
+	static const int kKeyButton = 2;
+
 protected:
 	void readTable(int tableIndex) override;
 	bool prepareReset() override;
 	bool hasTransform() const override { return true; }
 	bool getField(const Common::String &key) override;
 	bool setField(const Common::String &key) override;
+	void onFrame() override;
 
 private:
 	struct Cursor {
@@ -83,6 +95,7 @@ private:
 	void readCursorField(int valueIndex, Cursor &cursor);
 	void pushCursorField(const Cursor &cursor);
 	void fire();
+	void loseKeyFocus();
 	void sendTooltip(bool isShown);
 	void updateCursorTile(const Common::Point32 *mouse);
 
@@ -127,6 +140,13 @@ private:
 	double _slideDistance = 5.0;
 	Common::Point32 _pressPoint;
 	bool _hasSlid = false;
+
+	// Nancy32. A hotspot with keys gets the key focus when a key press makes
+	// it as far down as the hotspot, by keyZ. From then on, holding one of its
+	// keys presses it, until it is disabled or the mouse holds it down.
+	Common::Array<Common::KeyCode> _keys;
+	bool _hasKeyFocus = false;
+	bool _isKeyDown = false;
 };
 
 // Nancy26: catches the player's input in a part of the screen, so whatever is


Commit: 5399bca9b0e8acd222edbdd77dc88afa836d452c
    https://github.com/scummvm/scummvm/commit/5399bca9b0e8acd222edbdd77dc88afa836d452c
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:36+02:00

Commit Message:
NANCY: NANCY32: Add new particle stages

Rotate spins the particles. RadialPosition, RadialVelocity and
RadialForce place, move and push them relative to a center, and
ScaleFade grows or shrinks them. The snow uses them.

Changed paths:
    engines/nancy/script/particles.cpp
    engines/nancy/script/particles.h


diff --git a/engines/nancy/script/particles.cpp b/engines/nancy/script/particles.cpp
index 05ae211605a..b93b3aadd9d 100644
--- a/engines/nancy/script/particles.cpp
+++ b/engines/nancy/script/particles.cpp
@@ -725,6 +725,190 @@ private:
 	double _alpha[2] = { 1.0, 1.0 };
 };
 
+// "rotate", Nancy32: the particles start turning at a speed between "min" and
+// "max" a step. Every step, the speed drops by the factor "drag", and goes up or
+// down by "turbulence".
+class ParticleRotateStage : public ParticleStage {
+public:
+	ParticleRotateStage(ParticleRecord &record, lua_State *L, int tableIndex) : ParticleStage(record) {
+		readField(L, tableIndex, "min", _min);
+		readField(L, tableIndex, "max", _max);
+		readField(L, tableIndex, "drag", _drag);
+		readField(L, tableIndex, "turbulence", _turbulence);
+	}
+
+	void update(uint first, uint count) override {
+		for (uint i = first; i < first + count; ++i) {
+			Particle &particle = _record.getParticle(i);
+			particle.angle += particle.angularSpeed;
+
+			const double push = g_nancy->_randomSource->getRandomBit() ? -_turbulence : _turbulence;
+			particle.angularSpeed = particle.angularSpeed * _drag + push;
+		}
+	}
+
+protected:
+	void initParticles(uint first, uint count) override {
+		for (uint i = first; i < first + count; ++i) {
+			_record.getParticle(i).angularSpeed = lerp(_min, _max, randomFraction());
+		}
+	}
+
+private:
+	double _min = 0.0;
+	double _max = 0.0;
+	double _drag = 0.0;
+	double _turbulence = 0.0;
+};
+
+// Reads a point field of the stage's table
+static void readPointField(lua_State *L, int tableIndex, const char *name, double &x, double &y) {
+	if (pushField(L, tableIndex, name)) {
+		readPointCoordinates(L, -1, x, y);
+		lua_pop(L, 1);
+	}
+}
+
+// "radialPosition", Nancy32: a place around "center", at a distance between
+// min.x and max.x, and at an angle between min.y and max.y
+class ParticleRadialPositionStage : public ParticleStage {
+public:
+	ParticleRadialPositionStage(ParticleRecord &record, lua_State *L, int tableIndex) : ParticleStage(record) {
+		readPicked(L, tableIndex);
+		readPointField(L, tableIndex, "center", _center[0], _center[1]);
+		readPointField(L, tableIndex, "min", _minRadius, _minAngle);
+		readPointField(L, tableIndex, "max", _maxRadius, _maxAngle);
+	}
+
+protected:
+	void initParticles(uint first, uint count) override {
+		const double range = _maxRadius - _minRadius;
+		const double share = range / _maxRadius;
+
+		for (uint i = first; i < first + count; ++i) {
+			const double radius = sqrt(randomFraction() * share) * range + _minRadius;
+			const double angle = lerp(_minAngle, _maxAngle, randomFraction());
+
+			Particle &particle = _record.getParticle(i);
+			particle.position[0] = _center[0] + radius * cos(angle);
+			particle.position[1] = _center[1] + radius * sin(angle);
+			particle.position[2] = 0.0;
+		}
+	}
+
+private:
+	double _center[2] = { 1.0, 1.0 };
+	double _minRadius = 0.0;
+	double _minAngle = 0.0;
+	double _maxRadius = 0.0;
+	double _maxAngle = 0.0;
+};
+
+// The direction from a center to a particle, which is nothing at the center
+static void getDirection(const Particle &particle, const double center[2], double &x, double &y) {
+	x = particle.position[0] - center[0];
+	y = particle.position[1] - center[1];
+
+	const double length = sqrt(x * x + y * y);
+	if (length != 0.0) {
+		x /= length;
+		y /= length;
+	}
+}
+
+// "radialVelocity", Nancy32: the particles move away from "center" at a speed
+// between minSpeed and maxSpeed, in units a second
+class ParticleRadialVelocityStage : public ParticleStage {
+public:
+	ParticleRadialVelocityStage(ParticleRecord &record, lua_State *L, int tableIndex) : ParticleStage(record) {
+		readPicked(L, tableIndex);
+		readPointField(L, tableIndex, "center", _center[0], _center[1]);
+		readField(L, tableIndex, "minSpeed", _minSpeed);
+		readField(L, tableIndex, "maxSpeed", _maxSpeed);
+	}
+
+protected:
+	void initParticles(uint first, uint count) override {
+		for (uint i = first; i < first + count; ++i) {
+			Particle &particle = _record.getParticle(i);
+
+			double x, y;
+			getDirection(particle, _center, x, y);
+
+			const double speed = lerp(_minSpeed, _maxSpeed, randomFraction()) / kStepsPerSecond;
+			particle.velocity[0] = x * speed;
+			particle.velocity[1] = y * speed;
+			particle.velocity[2] = 0.0;
+		}
+	}
+
+private:
+	double _center[2] = { 0.0, 0.0 };
+	double _minSpeed = 0.0;
+	double _maxSpeed = 0.0;
+};
+
+// "radialForce", Nancy32: pushes the particles away from "center" by "factor",
+// in units a second squared; a negative factor pulls them in
+class ParticleRadialForceStage : public ParticleStage {
+public:
+	ParticleRadialForceStage(ParticleRecord &record, lua_State *L, int tableIndex) : ParticleStage(record) {
+		readPointField(L, tableIndex, "center", _center[0], _center[1]);
+		if (readField(L, tableIndex, "factor", _factor)) {
+			_factor /= kStepsPerSecond * kStepsPerSecond;
+		}
+	}
+
+	void update(uint first, uint count) override {
+		for (uint i = first; i < first + count; ++i) {
+			Particle &particle = _record.getParticle(i);
+
+			double x, y;
+			getDirection(particle, _center, x, y);
+			particle.acceleration[0] += x * _factor;
+			particle.acceleration[1] += y * _factor;
+		}
+	}
+
+private:
+	double _center[2] = { 0.0, 0.0 };
+	double _factor = 0.0;
+};
+
+// "scaleFade", Nancy32: the particles grow or shrink from "scale1" to "scale2"
+// once they are "start" into their life, over "duration" of it
+class ParticleScaleFadeStage : public ParticleStage {
+public:
+	ParticleScaleFadeStage(ParticleRecord &record, lua_State *L, int tableIndex) : ParticleStage(record) {
+		readField(L, tableIndex, "start", _start);
+		readField(L, tableIndex, "duration", _duration);
+		readField(L, tableIndex, "scale1", _fromScale);
+		readField(L, tableIndex, "scale2", _toScale);
+	}
+
+	void update(uint first, uint count) override {
+		// The oldest particles come first, so the ones after one that hasn't
+		// started changing haven't either
+		for (uint i = first; i < first + count; ++i) {
+			Particle &particle = _record.getParticle(i);
+			const double fraction = (particle.life - _start) / _duration;
+			if (fraction < 0.0) {
+				break;
+			}
+
+			if (fraction <= 1.0) {
+				particle.scale = lerp(_fromScale, _toScale, fraction);
+			}
+		}
+	}
+
+private:
+	double _start = 0.0;
+	double _duration = 1.0;
+	double _fromScale = 0.0;
+	double _toScale = 1.0;
+};
+
 // TODO: The "script" and "revolve" stages, which no script uses
 static ParticleStage *makeStage(ParticleRecord &record, lua_State *L, int tableIndex, const Common::String &name) {
 	if (name == "positionPerspective") {
@@ -753,6 +937,16 @@ static ParticleStage *makeStage(ParticleRecord &record, lua_State *L, int tableI
 		return new ParticleTurbulenceStage(record, L, tableIndex);
 	} else if (name == "path") {
 		return new ParticlePathStage(record, L, tableIndex);
+	} else if (name == "rotate") {
+		return new ParticleRotateStage(record, L, tableIndex);
+	} else if (name == "radialPosition") {
+		return new ParticleRadialPositionStage(record, L, tableIndex);
+	} else if (name == "radialVelocity") {
+		return new ParticleRadialVelocityStage(record, L, tableIndex);
+	} else if (name == "radialForce") {
+		return new ParticleRadialForceStage(record, L, tableIndex);
+	} else if (name == "scaleFade") {
+		return new ParticleScaleFadeStage(record, L, tableIndex);
 	}
 
 	luaL_error(L, "Stage name '%s' does not match a known stage", name.c_str());
@@ -1005,7 +1199,12 @@ static const char *const kParticleStageKinds[][2] = {
 	{ "AddSources", "sources" },
 	{ "AddTurbulence", "turbulence" },
 	{ "AddVelocity", "velocity" },
-	{ "AddPath", "path" }
+	{ "AddPath", "path" },
+	{ "AddRotate", "rotate" },
+	{ "AddRadialPosition", "radialPosition" },
+	{ "AddRadialVelocity", "radialVelocity" },
+	{ "AddRadialForce", "radialForce" },
+	{ "AddScaleFade", "scaleFade" }
 };
 
 bool ParticleRecord::getField(const Common::String &key) {
diff --git a/engines/nancy/script/particles.h b/engines/nancy/script/particles.h
index 602385b49f3..d9c4f0c0eb4 100644
--- a/engines/nancy/script/particles.h
+++ b/engines/nancy/script/particles.h
@@ -44,6 +44,7 @@ struct Particle {
 	double acceleration[3] = { 0.0, 0.0, 0.0 };
 	double life = 0.0;			// from 0 when made to 1 when gone
 	double angle = 0.0;
+	double angularSpeed = 0.0;	// Nancy32, in radians a step
 	double scale = 1.0;
 	double width = 0.0;			// of the part of the image it shows
 	double height = 0.0;


Commit: d0301f133526cbeff9c76b87c7e97f5092c824e9
    https://github.com/scummvm/scummvm/commit/d0301f133526cbeff9c76b87c7e97f5092c824e9
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:38+02:00

Commit Message:
NANCY: NANCY32: Take the cursors of items from InventoryInit

The items in InventoryInit now give the picture, source rect and
hotspot of their cursor, which Cursors_SC used to.

Changed paths:
    engines/nancy/script/bootapi.cpp
    engines/nancy/script/v5/bootobjects.cpp
    engines/nancy/script/v5/bootobjects.h


diff --git a/engines/nancy/script/bootapi.cpp b/engines/nancy/script/bootapi.cpp
index a24dcdeb75d..fc0badcb3cc 100644
--- a/engines/nancy/script/bootapi.cpp
+++ b/engines/nancy/script/bootapi.cpp
@@ -340,7 +340,7 @@ static int inventoryCreate(lua_State *L) {
 
 #ifdef ENABLE_NANCY_V5
 	if (g_nancy->getGameType() >= kGameTypeNancy26) {
-		return createNancy26Inventory(L, inventory);
+		return createNancy26Inventory(L, inventory, *s_tables->boot);
 	}
 #endif
 
diff --git a/engines/nancy/script/v5/bootobjects.cpp b/engines/nancy/script/v5/bootobjects.cpp
index 50f73d4638e..73285368c6c 100644
--- a/engines/nancy/script/v5/bootobjects.cpp
+++ b/engines/nancy/script/v5/bootobjects.cpp
@@ -35,9 +35,37 @@
 namespace Nancy {
 namespace Script {
 
+// Nancy32 gives every item its cursor: the part "reg" of the picture "ovl",
+// with its hotspot at "activePt". It becomes a cursor named like the item, as
+// the earlier games name theirs.
+static void readNancy32ItemCursor(lua_State *L, int itemTable, const Common::String &name, ScriptBootData &boot) {
+	Common::String imageName;
+	if (!readField(L, itemTable, "ovl", imageName)) {
+		return;
+	}
+
+	ScriptBootData::Cursor cursor;
+	cursor.name = name;
+	cursor.imageName = Common::Path(imageName);
+
+	if (pushField(L, itemTable, "reg")) {
+		cursor.sources[0] = cursor.sources[1] = checkRect(L, -1).toRect();
+		lua_pop(L, 1);
+	}
+
+	Common::Point32 hotspot;
+	if (pushField(L, itemTable, "activePt")) {
+		readPoint(L, -1, hotspot);
+		lua_pop(L, 1);
+	}
+
+	cursor.hotspots[0] = cursor.hotspots[1] = Common::Point(hotspot.x, hotspot.y);
+	boot.cursors.push_back(cursor);
+}
+
 // Nancy29 gives every item a table with where the player uses it ("hand" or
 // "face"), and the Brain flags that force it there or disable it
-static void readNancy29Item(lua_State *L, const Common::String &name, INVD::Item &item) {
+static void readNancy29Item(lua_State *L, const Common::String &name, INVD::Item &item, ScriptBootData &boot) {
 	lua_getfield(L, 2, name.c_str());
 	const int itemTable = lua_gettop(L);
 	luaL_checktype(L, itemTable, LUA_TTABLE);
@@ -51,12 +79,14 @@ static void readNancy29Item(lua_State *L, const Common::String &name, INVD::Item
 	readField(L, itemTable, "forceOffFlag", item.forceOffFlag);
 	item.kind = UI::NDUI::InvButton::kItemPickUp;
 
+	readNancy32ItemCursor(L, itemTable, name, boot);
+
 	lua_pop(L, 1);
 }
 
 // Nancy26 gives every item the scene that shows it, or nothing. The pictures
 // of the items are cursors.
-int createNancy26Inventory(lua_State *L, INVD &inventory) {
+int createNancy26Inventory(lua_State *L, INVD &inventory, ScriptBootData &boot) {
 	Common::Array<Common::String> names;
 	getSortedKeys(L, 2, names);
 
@@ -66,7 +96,7 @@ int createNancy26Inventory(lua_State *L, INVD &inventory) {
 		item.name = name;
 
 		if (g_nancy->getGameType() >= kGameTypeNancy29) {
-			readNancy29Item(L, name, item);
+			readNancy29Item(L, name, item, boot);
 		} else {
 			Common::String sceneName;
 			readField(L, 2, name.c_str(), sceneName);
diff --git a/engines/nancy/script/v5/bootobjects.h b/engines/nancy/script/v5/bootobjects.h
index 046fdd8583b..c40cdc20e1d 100644
--- a/engines/nancy/script/v5/bootobjects.h
+++ b/engines/nancy/script/v5/bootobjects.h
@@ -31,7 +31,7 @@ namespace Script {
 
 // Nancy26's forms of InventoryInit:Create and CursorInit:Create, and the
 // FontsInit:Create the file of a font made of pictures calls
-int createNancy26Inventory(lua_State *L, INVD &inventory);
+int createNancy26Inventory(lua_State *L, INVD &inventory, ScriptBootData &boot);
 int createNancy26Cursors(lua_State *L, ScriptBootData &boot);
 int createBitmapFont(lua_State *L, ScriptBootData::BitmapFont &font);
 


Commit: ae7b542ffa3bcc0ce2a62e24f15e4f03f00a0965
    https://github.com/scummvm/scummvm/commit/ae7b542ffa3bcc0ce2a62e24f15e4f03f00a0965
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:39+02:00

Commit Message:
NANCY: NANCY32: Add Scene:Lock and Scene:Unlock

Scene:Lock disables the input to all the streams of the viewport,
until Scene:Unlock. Puzzles lock the scene while they show that they
were solved.

Changed paths:
    engines/nancy/script/scenecontext.cpp
    engines/nancy/script/scenecontext.h
    engines/nancy/script/v5/gamefunctions.cpp
    engines/nancy/state/scenestream.cpp
    engines/nancy/state/scenestream.h


diff --git a/engines/nancy/script/scenecontext.cpp b/engines/nancy/script/scenecontext.cpp
index 7c20fa4a2bc..46dca4ffc39 100644
--- a/engines/nancy/script/scenecontext.cpp
+++ b/engines/nancy/script/scenecontext.cpp
@@ -61,6 +61,17 @@ SceneContext::SceneContext(const Common::String &streamName, const Common::Strin
 	_lua = new LuaState(this);
 }
 
+#ifdef ENABLE_NANCY_V5
+// Nancy32's Scene:Lock() disables the streams of the viewport
+bool SceneContext::isStreamEnabled() const {
+	if (!_streamState) {
+		return true;
+	}
+
+	return _streamState->isEnabled && !(_streamState->isInViewport && NancySceneState.getStreams().isViewportLocked());
+}
+#endif
+
 // Nancy26 draws whole streams over each other, so the z of a record only counts
 // within the band of its stream
 int32 SceneContext::getZOffset() const {
diff --git a/engines/nancy/script/scenecontext.h b/engines/nancy/script/scenecontext.h
index 0ff01643bb2..f021f1a9e57 100644
--- a/engines/nancy/script/scenecontext.h
+++ b/engines/nancy/script/scenecontext.h
@@ -122,7 +122,7 @@ public:
 	void onBandChanged();
 
 	// Nancy26: what the stream of the scene says about all its records
-	bool isStreamEnabled() const { return !_streamState || _streamState->isEnabled; }
+	bool isStreamEnabled() const;
 	bool isStreamVisible() const { return !_streamState || _streamState->isVisible; }
 	bool isStreamPaused() const { return _streamState && _streamState->isPaused; }
 #endif
diff --git a/engines/nancy/script/v5/gamefunctions.cpp b/engines/nancy/script/v5/gamefunctions.cpp
index 2a64e9a1757..ff96598d7e5 100644
--- a/engines/nancy/script/v5/gamefunctions.cpp
+++ b/engines/nancy/script/v5/gamefunctions.cpp
@@ -996,6 +996,18 @@ static int sceneIsStreamRunning(lua_State *L) {
 	return 1;
 }
 
+// Scene:Lock() and Scene:Unlock(), Nancy32: keep the player's input from the
+// viewport, e.g. while a puzzle shows that it was solved
+static int sceneLock(lua_State *L) {
+	NancySceneState.getStreams().setViewportLocked(true);
+	return 0;
+}
+
+static int sceneUnlock(lua_State *L) {
+	NancySceneState.getStreams().setViewportLocked(false);
+	return 0;
+}
+
 // Scene:GetStreamInVP(stream), Nancy29: whether the stream is drawn inside
 // the viewport rather than on the whole screen. Returns true for a stream
 // that isn't running.
@@ -1141,6 +1153,8 @@ void registerNancy26GameAPI(lua_State *L) {
 	static const luaL_Reg kSceneFunctions[] = {
 		{ "IsStreamRunning", sceneIsStreamRunning },
 		{ "GetStreamInVP", sceneGetStreamInVP },
+		{ "Lock", sceneLock },
+		{ "Unlock", sceneUnlock },
 		{ nullptr, nullptr }
 	};
 
diff --git a/engines/nancy/state/scenestream.cpp b/engines/nancy/state/scenestream.cpp
index e0083145918..a100bc458cb 100644
--- a/engines/nancy/state/scenestream.cpp
+++ b/engines/nancy/state/scenestream.cpp
@@ -765,6 +765,9 @@ void SceneStreamManager::clear() {
 	_streams.clear();
 	_mainStreamChildren.clear();
 	_environment.clear();
+#ifdef ENABLE_NANCY_V5
+	_isViewportLocked = false;
+#endif
 
 	if (g_nancy->getGameType() >= kGameTypeNancy17) {
 		// The main stream
diff --git a/engines/nancy/state/scenestream.h b/engines/nancy/state/scenestream.h
index edd4d21a49f..797372f9ec0 100644
--- a/engines/nancy/state/scenestream.h
+++ b/engines/nancy/state/scenestream.h
@@ -260,6 +260,11 @@ public:
 	// Nancy26: what a stream says about its records; null for no such stream
 	Script::StreamNodeState *getNodeState(const Common::String &name);
 
+	// Nancy32: Scene:Lock() disables all the streams of the viewport, until
+	// Scene:Unlock(), while the ones of the UI go on
+	void setViewportLocked(bool isLocked) { _isViewportLocked = isLocked; }
+	bool isViewportLocked() const { return _isViewportLocked; }
+
 	// Nancy26: the streams in the order they get drawn in, the main one as null
 	void getDrawOrder(Common::Array<SceneStream *> &streams) const;
 
@@ -326,6 +331,7 @@ private:
 
 	Script::StreamNodeState _mainNodeState;
 	uint32 _numBegun = 0;
+	bool _isViewportLocked = false;
 #endif
 	ViewTransform _mainStreamViewTransform;
 };


Commit: 41b17af4da2652e61005d92e87ab03fe686d1146
    https://github.com/scummvm/scummvm/commit/41b17af4da2652e61005d92e87ab03fe686d1146
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:40+02:00

Commit Message:
NANCY: NANCY32: Add the achievements

The achievements of Nancy32 are kept in a file, like the ones of
Nancy29 to Nancy31.

Changed paths:
    engines/nancy/metaengine.cpp


diff --git a/engines/nancy/metaengine.cpp b/engines/nancy/metaengine.cpp
index 647aae9d7a0..176fb33a193 100644
--- a/engines/nancy/metaengine.cpp
+++ b/engines/nancy/metaengine.cpp
@@ -259,6 +259,7 @@ const Common::AchievementDescriptionList *NancyMetaEngine::getAchievementDescrip
 		{ "nancy29", Common::UNK_ACHIEVEMENTS, "nancy29" },
 		{ "nancy30", Common::UNK_ACHIEVEMENTS, "nancy30" },
 		{ "nancy31", Common::UNK_ACHIEVEMENTS, "nancy31" },
+		{ "nancy32", Common::UNK_ACHIEVEMENTS, "nancy32" },
 		ACHIEVEMENT_DESC_TABLE_END_MARKER
 	};
 


Commit: 72c0bd37837557520f267d6f341266eda3835dee
    https://github.com/scummvm/scummvm/commit/72c0bd37837557520f267d6f341266eda3835dee
Author: Filippos Karapetis (bluegr at gmail.com)
Date: 2026-11-16T10:58:41+02:00

Commit Message:
NANCY: NANCY32: Add detection entry

The game has no ciftree, so it is detected by one of its loose .cif
files.

Changed paths:
    engines/nancy/detection_tables.h


diff --git a/engines/nancy/detection_tables.h b/engines/nancy/detection_tables.h
index 5dbac6a52b4..db7ad7ed7cd 100644
--- a/engines/nancy/detection_tables.h
+++ b/engines/nancy/detection_tables.h
@@ -960,6 +960,14 @@ static const ADGameDescription gameDescriptions[] = {
 		ADGF_UNSTABLE | ADGF_DROPPLATFORM,
 		NANCY_GUIOPTIONS
 	},
+	{ // MD5 by bluegr. The game has no ciftree, only loose .cif files
+		"nancy32", nullptr,
+		AD_ENTRY1s("InventoryInit_SC.cif", "387280ac49ad84d0db85440e7bd54353", 6096),
+		Common::EN_ANY,
+		Common::kPlatformWindows,
+		ADGF_UNSTABLE | ADGF_DROPPLATFORM,
+		NANCY_GUIOPTIONS
+	},
 
 	// Do not delete
 	AD_TABLE_END_MARKER




More information about the Scummvm-git-logs mailing list