From 9dbf9c1019b4742b7d14c41ba80762805beaea00 Mon Sep 17 00:00:00 2001
From: Tim Felgentreff <timfelgentreff@gmail.com>
Date: Fri, 8 Apr 2022 08:38:35 +0200
Subject: [PATCH] add "talking" as a tag in portrait definitions to show when
 unit is playing sound

---
 src/include/unittype.h       | 1 +
 src/sound/sound.cpp          | 8 ++++++++
 src/unit/script_unittype.cpp | 9 ++++++++-
 3 files changed, 17 insertions(+), 1 deletion(-)

diff --git a/src/include/unittype.h b/src/include/unittype.h
index 966bbb3f1..d7ae21724 100644
--- a/src/include/unittype.h
+++ b/src/include/unittype.h
@@ -549,6 +549,7 @@ public:
 	struct _portrait_ {
 		std::string *Files;
 		int Num;
+		int Talking; /// offset into portraits for talking portraits
 		Mng **Mngs;
 		mutable int CurrMng;
 		mutable int NumIterations;
diff --git a/src/sound/sound.cpp b/src/sound/sound.cpp
index 3f979b472..d78cc5cdd 100644
--- a/src/sound/sound.cpp
+++ b/src/sound/sound.cpp
@@ -304,6 +304,14 @@ void PlayUnitSound(const CUnit &unit, UnitVoiceGroup voice, bool sampleUnique)
 	}
 	SetChannelVolume(channel, CalculateVolume(false, ViewPointDistanceToUnit(unit), sound->Range));
 	SetChannelStereo(channel, CalculateStereo(unit));
+#ifdef USE_MNG
+	const CUnitType &type = *unit.Type;
+	if (type.Portrait.Num && type.Portrait.Talking) {
+		type.Portrait.Mngs[type.Portrait.CurrMng]->Reset();
+		type.Portrait.CurrMng = (MyRand() % (type.Portrait.Num - type.Portrait.Talking)) + type.Portrait.Talking;
+		type.Portrait.NumIterations = 1;
+	}
+#endif
 }
 
 /**
diff --git a/src/unit/script_unittype.cpp b/src/unit/script_unittype.cpp
index dc009b455..2b9eff898 100644
--- a/src/unit/script_unittype.cpp
+++ b/src/unit/script_unittype.cpp
@@ -589,11 +589,18 @@ static int CclDefineUnitType(lua_State *l)
 			}
 			const int subargs = lua_rawlen(l, -1);
 			type->Portrait.Num = subargs;
+			type->Portrait.Talking = 0;
 			type->Portrait.Files = new std::string[type->Portrait.Num];
 			type->Portrait.Mngs = new Mng *[type->Portrait.Num];
 			memset(type->Portrait.Mngs, 0, type->Portrait.Num * sizeof(Mng *));
 			for (int k = 0; k < subargs; ++k) {
-				type->Portrait.Files[k] = LuaToString(l, -1, k + 1);
+				const char *s = LuaToString(l, -1, k + 1);
+				if (!strcmp("talking", s)) {
+					type->Portrait.Talking = k;
+					type->Portrait.Num--;
+				} else {
+					type->Portrait.Files[k - (type->Portrait.Talking ? 1 : 0)] = s;
+				}
 			}
 #endif
 		} else if (!strcmp(value, "Costs")) {