diff --git a/.gitignore b/.gitignore index 3f2f4f5..b729424 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,6 @@ Spritegenerator/mixamo/ Spiel/*.dll _Archiv/Spritegenerator-output/ _Archiv/3D-Erstversuch/ + +# Stimmen fuer Ansager/Sprechchor (tools/get_voices.py, ca. 240 MB) +Assets/Voices/ diff --git a/Assets/Audio/music_oath.mp3 b/Assets/Audio/music_oath.mp3 new file mode 100644 index 0000000..06ec2d7 Binary files /dev/null and b/Assets/Audio/music_oath.mp3 differ diff --git a/Assets/Models/foe_hoplomachus.gim b/Assets/Models/foe_hoplomachus.gim index fe2ac7e..5a65504 100644 Binary files a/Assets/Models/foe_hoplomachus.gim and b/Assets/Models/foe_hoplomachus.gim differ diff --git a/Core/AppSettings.cs b/Core/AppSettings.cs index fab8b9f..c4acfd6 100644 --- a/Core/AppSettings.cs +++ b/Core/AppSettings.cs @@ -39,6 +39,9 @@ namespace GladiatorIdle /// Weniger Bewegung: keine Partikel, schwebenden Zahlen, Kamera-Ruck, Kampf-Clips. public static bool ReduceMotion { get; set; } + /// Name des Spielers ausrufen (Ansager, Sprechchor). + public static bool NameCalls { get; set; } = true; + /// Kantenglättung (MSAA 4×). public static bool AntiAlias { get; set; } = true; @@ -90,6 +93,7 @@ namespace GladiatorIdle case "muted": Muted = val == "1"; break; case "reducemotion": ReduceMotion = val == "1"; break; case "antialias": AntiAlias = val == "1"; break; + case "namecalls": NameCalls = val == "1"; break; case "bloom": Bloom = val == "1"; break; case "framelimit": if (int.TryParse(val, out int fl)) FrameLimit = Math.Clamp(fl, 0, 2); break; case "textscale": if (int.TryParse(val, out int ts)) TextScale = Math.Clamp(ts, 1, 3); break; @@ -123,6 +127,7 @@ namespace GladiatorIdle $"muted={(Muted ? 1 : 0)}\n" + $"reducemotion={(ReduceMotion ? 1 : 0)}\n" + $"antialias={(AntiAlias ? 1 : 0)}\n" + + $"namecalls={(NameCalls ? 1 : 0)}\n" + $"bloom={(Bloom ? 1 : 0)}\n" + $"framelimit={FrameLimit}\n" + $"textscale={TextScale}\n" + diff --git a/Core/NameVoice.cs b/Core/NameVoice.cs new file mode 100644 index 0000000..4503c2e --- /dev/null +++ b/Core/NameVoice.cs @@ -0,0 +1,478 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; +using GladiatorIdle.Gfx; + +namespace GladiatorIdle +{ + /// + /// Der Name des Spielers als Klang: Ansager (ganzer Satz mit Arena-Hall) und Sprechchor + /// (der Name von vielen Stimmen im Takt gerufen, mit Klatschen). Gesprochen von einer + /// Piper-Stimme (sherpa-onnx, offline) aus Assets/Voices/<de|en|es>. Erzeugt im + /// Hintergrund, auf der Platte zwischengespeichert. Fehlt etwas, bleibt es still. + /// + internal static class NameVoice + { + public enum Kind { Name, Enter, Win, Chant, Oath } + + /// Rede nach der Erstellung: Text je Satz und Startzeit (s) jedes Satzes in der fertigen Aufnahme. + public static string[] OathLines { get; private set; } = Array.Empty(); + public static float[] OathTimes { get; private set; } = Array.Empty(); + + const int RATE = 44100; + static readonly object _lock = new(); + static readonly Dictionary<(string, string, Kind), float[]> _ready = new(); + static readonly Dictionary _tts = new(); + static readonly Dictionary _sid = new(); // Sprecher (Gefühlslage) je Sprache, aus voice.txt + static string _name = "", _lang = ""; + static long _lastCall; + + /// Stimmen vorhanden? + public static bool Available => VoiceDir(L.Current.ToString().ToLowerInvariant()) != null; + + static string? VoiceDir(string lang) + { + if (Assets.RootDir is not string root) return null; + string d = Path.Combine(root, "Voices", lang); + return File.Exists(Path.Combine(d, "model.onnx")) ? d : null; + } + + /// Vorab gesprochene Rede der Kriegerstimme (tools/make_oath_voice.py): Assets/Voices/oath/<lang>. + static string? OathDir(string lang) + { + if (Assets.RootDir is not string root) return null; + string d = Path.Combine(root, "Voices", "oath", lang); + return File.Exists(Path.Combine(d, "line1.wav")) ? d : null; + } + + /// Gibt es eine Rede (vorab gesprochen oder aus der Piper-Stimme)? + public static bool OathAvailable => OathDir(LangCode) != null || Available; + + static string LangCode => L.Current switch { L.Lang.De => "de", L.Lang.Es => "es", _ => "en" }; + + /// Für diesen Namen (und die aktuelle Sprache) alle Klänge im Hintergrund vorbereiten. + public static void Prepare(string name) + { + name = name.Trim(); + string lang = LangCode; + if (name.Length == 0) return; + lock (_lock) { if (_name == name && _lang == lang) return; _name = name; _lang = lang; } + string enter = string.Format(L.t("announce.enter"), name), win = string.Format(L.t("announce.win"), name); + var oathLines = string.Format(L.t("oath.text"), name).Split('|', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + lock (_lock) { OathLines = oathLines; OathTimes = Array.Empty(); } + // eigener Faden mit niedriger Priorität: das Spiel läuft flüssig weiter + var worker = new System.Threading.Thread(() => + { + try + { + var sw = System.Diagnostics.Stopwatch.StartNew(); + // zuerst die Rede (kommt direkt nach der Erstellung) + var (oath, times) = LoadOath(lang, name, oathLines); + if (oath == null) (oath, times) = MakeOath(lang, oathLines); + if (oath != null) lock (_lock) { _ready[(name, lang, Kind.Oath)] = oath; OathTimes = times; } + foreach (var (kind, text) in new[] { (Kind.Name, name + "!"), (Kind.Enter, enter), (Kind.Win, win) }) + { + var pcm = Cached(lang, kind, text) ?? Make(lang, kind, text); + if (pcm == null) return; + lock (_lock) _ready[(name, lang, kind)] = pcm; + } + var chant = Cached(lang, Kind.Chant, name) ?? MakeChant(lang, name); + if (chant != null) lock (_lock) _ready[(name, lang, Kind.Chant)] = chant; + if (DevShot.Active) DevShot.Log($"namevoice: '{name}' ({lang}) ready in {sw.ElapsedMilliseconds} ms"); + } + catch (Exception e) { if (DevShot.Active) DevShot.Log("namevoice failed: " + e.Message); } + }) { IsBackground = true, Priority = System.Threading.ThreadPriority.BelowNormal }; + worker.Start(); + } + + /// Fertigen Klang abholen (Stereo 44,1 kHz) oder null, solange er noch entsteht. + public static float[]? Get(Kind kind) + { + lock (_lock) return _ready.TryGetValue((_name, _lang, kind), out var d) ? d : null; + } + + /// Abspielen, höchstens ein Namensruf alle Sekunden. + public static void Play(Kind kind, float gain = 1f, double minGap = 20) + { + if (!AppSettings.NameCalls) return; + long now = Environment.TickCount64; + if (kind != Kind.Name && now - _lastCall < minGap * 1000) return; + _lastCall = now; + SoundManager.PlayPcm("name_" + kind.ToString().ToLowerInvariant(), Get(kind), gain); + } + + // ── Erzeugen ──────────────────────────────────────────────── + + static SherpaOnnx.OfflineTts? Tts(string lang) + { + lock (_tts) + { + if (_tts.TryGetValue(lang, out var t)) return t; + t = null; + if (VoiceDir(lang) is string dir) + { + var config = new SherpaOnnx.OfflineTtsConfig(); + config.Model.Vits.Model = Path.Combine(dir, "model.onnx"); + config.Model.Vits.Tokens = Path.Combine(dir, "tokens.txt"); + config.Model.Vits.DataDir = Path.Combine(dir, "espeak-ng-data"); + config.Model.NumThreads = 1; + config.Model.Provider = "cpu"; + config.Model.Debug = 0; + config.MaxNumSentences = 1; + t = new SherpaOnnx.OfflineTts(config); + int sid = 0; + string vt = Path.Combine(dir, "voice.txt"); + if (File.Exists(vt)) + foreach (var line in File.ReadAllLines(vt)) + if (line.StartsWith("sid=") && int.TryParse(line[4..], out int v)) sid = v; + _sid[lang] = sid; + } + return _tts[lang] = t; + } + } + + /// Text sprechen: Mono bei der Rate der Stimme → Mono 44,1 kHz. + static float[]? Speak(string lang, string text, float speed) + { + var tts = Tts(lang); + if (tts == null) return null; + int sid; lock (_tts) sid = _sid.GetValueOrDefault(lang); + var audio = tts.Generate(text, speed, sid); + if (DevShot.Active) DevShot.Log($"namevoice: tts '{text}' rate {audio.SampleRate} samples {audio.Samples?.Length ?? -1} (tts rate {tts.SampleRate})"); + if (audio.Samples == null || audio.Samples.Length == 0) return null; + return Resample(audio.Samples, audio.SampleRate > 0 ? audio.SampleRate : tts.SampleRate, RATE); + } + + static float[]? Make(string lang, Kind kind, string text) + { + var mono = Speak(lang, text, kind == Kind.Name ? 0.95f : 0.92f); + if (mono == null) return null; + // Ansager: etwas tiefer, Arena-Hall; Name allein: trocken, kurzer Raum + if (kind != Kind.Name) mono = Resample(mono, RATE, (int)(RATE * Math.Pow(2, 2 / 12.0))); // −2 Halbtöne (länger abgespielt) + mono = Trim(mono); + var wet = Reverb(mono, kind == Kind.Name ? 0.08f : 0.22f, kind == Kind.Name ? 0.25f : 0.5f); + var st = Stereo(Normalize(wet, 0.8f), 0.08f); + Save(lang, kind, text, st); + return st; + } + + /// Rede: Satz für Satz, langsam und etwas tiefer, mit Pausen und Hall; liefert die Startzeiten. + static (float[]? Pcm, float[] Times) MakeOath(string lang, string[] lines) + { + var parts = new List(); + var times = new float[lines.Length]; + int pos = 0, gap = (int)(0.55 * RATE); + for (int i = 0; i < lines.Length; i++) + { + var mono = Speak(lang, lines[i], 0.86f); + if (mono == null) return (null, times); + mono = Grit(Trim(Resample(mono, RATE, (int)(RATE * Math.Pow(2, 2.5 / 12.0))))); // −2,5 Halbtöne, rau + times[i] = pos / (float)RATE; + parts.Add(mono); + if (DevShot.Active && DevShot.Dir != null) WriteWav(Path.Combine(DevShot.Dir, $"voice_{lang}_oath_part{i}.wav"), Stereo(Normalize(mono, 0.8f), 0)); + pos += mono.Length + gap; + } + var all = new float[pos]; + int at = 0; + foreach (var m in parts) { Array.Copy(m, 0, all, at, m.Length); at += m.Length + gap; } + var wet = Reverb(all, 0.24f, 0.62f); // weite Arena + var st = Stereo(Normalize(wet, 0.85f), 0.07f); + if (DevShot.Active && DevShot.Dir != null) WriteWav(Path.Combine(DevShot.Dir, $"voice_{lang}_oath.wav"), st); + return (st, times); + } + + /// Dateiname eines Namens wie in tools/make_oath_voice.py: klein, ohne Akzente, nur a–z. + static string OathKey(string name) + { + var sb = new StringBuilder(); + foreach (char c in name.ToLowerInvariant().Normalize(NormalizationForm.FormD)) + if (c >= 'a' && c <= 'z') sb.Append(c); + return sb.ToString(); + } + + /// Rede aus den vorab gesprochenen Sätzen der Kriegerstimme. Erster Satz: eigene Aufnahme des + /// Namens, sonst „Mein Name ist“ + der Name aus der Piper-Stimme (tief und rau angeglichen). + static (float[]? Pcm, float[] Times) LoadOath(string lang, string name, string[] lines) + { + var times = new float[lines.Length]; + if (OathDir(lang) is not string dir || lines.Length < 2) return (null, times); + var parts = new float[lines.Length][]; + for (int i = 1; i < lines.Length; i++) + if ((parts[i] = ReadWav(Path.Combine(dir, $"line{i}.wav"))!) == null) return (null, times); + string key = OathKey(name); + var first = key.Length > 0 ? ReadWav(Path.Combine(dir, "names", key + ".wav")) : null; + if (first == null && ReadWav(Path.Combine(dir, "prefix.wav")) is float[] prefix) + { + first = prefix; + if (Speak(lang, name + ".", 0.86f) is float[] said) + { + said = Grit(Trim(Resample(said, RATE, (int)(RATE * Math.Pow(2, 3 / 12.0))))); // −3 Halbtöne wie die Vorlage + said = Normalize(said, Peak(prefix) * 0.95f); + first = new float[prefix.Length + (int)(0.06 * RATE) + said.Length]; + Array.Copy(prefix, first, prefix.Length); + Array.Copy(said, 0, first, first.Length - said.Length, said.Length); + } + } + parts[0] = first ?? Array.Empty(); // ganz ohne: der erste Satz bleibt Untertitel + int gap = (int)(0.5 * RATE), pos = 0; + for (int i = 0; i < parts.Length; i++) { times[i] = pos / (float)RATE; pos += parts[i].Length + (parts[i].Length > 0 ? gap : (int)(2.2 * RATE)); } + var all = new float[pos]; + int at = 0; + for (int i = 0; i < parts.Length; i++) { Array.Copy(parts[i], 0, all, at, parts[i].Length); at += parts[i].Length + (parts[i].Length > 0 ? gap : (int)(2.2 * RATE)); } + var wet = Reverb(all, 0.2f, 0.5f); // Arena-Hall + var st = Stereo(Normalize(wet, 0.9f), 0.06f); + if (DevShot.Active && DevShot.Dir != null) WriteWav(Path.Combine(DevShot.Dir, $"voice_{lang}_oath.wav"), st); + return (st, times); + } + + static float Peak(float[] x) { float m = 0; foreach (var v in x) m = Math.Max(m, Math.Abs(v)); return m; } + + /// 16-Bit-PCM-WAV (Mono oder Stereo) → Mono 44,1 kHz; null, wenn es fehlt oder unlesbar ist. + static float[]? ReadWav(string path) + { + try + { + if (!File.Exists(path)) return null; + using var r = new BinaryReader(File.OpenRead(path)); + if (new string(r.ReadChars(4)) != "RIFF") return null; + r.ReadInt32(); + if (new string(r.ReadChars(4)) != "WAVE") return null; + int channels = 1, rate = RATE, bits = 16; + while (r.BaseStream.Position + 8 <= r.BaseStream.Length) + { + string id = new string(r.ReadChars(4)); int size = r.ReadInt32(); + if (id == "fmt ") + { + r.ReadInt16(); channels = r.ReadInt16(); rate = r.ReadInt32(); r.ReadInt32(); r.ReadInt16(); bits = r.ReadInt16(); + r.BaseStream.Seek(size - 16, SeekOrigin.Current); + } + else if (id == "data") + { + if (bits != 16) return null; + int n = Math.Min(size, (int)(r.BaseStream.Length - r.BaseStream.Position)) / 2 / channels; + var mono = new float[n]; + for (int i = 0; i < n; i++) + { + float sum = 0; + for (int c = 0; c < channels; c++) sum += r.ReadInt16() / 32768f; + mono[i] = sum / channels; + } + return rate == RATE ? mono : Resample(mono, rate, RATE); + } + else r.BaseStream.Seek(size + (size & 1), SeekOrigin.Current); + } + } + catch { } + return null; + } + + /// Sprechchor: viele Stimmen rufen den Namen dreimal im Takt, dazu Klatschen und Hall. + static float[]? MakeChant(string lang, string name) + { + var shout = Speak(lang, name + "!", 0.9f); + if (shout == null) return null; + shout = Trim(shout); + var rng = new Random(name.GetHashCode()); + int beat = shout.Length + (int)(0.45 * RATE); + int total = beat * 3 + (int)(1.4 * RATE); + var l = new float[total]; var r = new float[total]; + const int VOICES = 14; + for (int v = 0; v < VOICES; v++) + { + double semi = v == 0 ? 0 : -2 + 5 * rng.NextDouble(); // Stimme 0: klare Vorsängerin + var voice = Resample(shout, RATE, (int)(RATE * Math.Pow(2, -semi / 12))); // Tonhöhe + if (v > 0) voice = LowPass(voice, 0.35f + 0.4f * (float)rng.NextDouble()); + float g = v == 0 ? 3.2f : 0.4f + 0.4f * (float)rng.NextDouble(), pan = v == 0 ? 0.5f : (float)rng.NextDouble(); + for (int rep = 0; rep < 3; rep++) + { + int start = rep * beat + (v == 0 ? 0 : (int)(rng.NextDouble() * 0.05 * RATE)); + float lg = g * (rep == 2 ? 1.15f : 1f); // der dritte Ruf am lautesten + for (int i = 0; i < voice.Length && start + i < total; i++) + { + l[start + i] += voice[i] * lg * (1 - pan); + r[start + i] += voice[i] * lg * pan; + } + } + } + // Klatschen: kurze Rauschstöße auf die Silben des Namens (Anfang und Mitte) und am Ende + for (int rep = 0; rep < 3; rep++) + foreach (double at in new[] { 0.0, 0.5, 1.0 }) + { + int c0 = rep * beat + (int)(at * shout.Length); + for (int k = 0; k < 14; k++) + { + int s0 = c0 + (int)(rng.NextDouble() * 0.06 * RATE); + float cg = 0.12f + 0.12f * (float)rng.NextDouble(), cp = (float)rng.NextDouble(); + for (int i = 0; i < 0.03 * RATE && s0 + i < total; i++) + { + float env = MathF.Exp(-i / (0.006f * RATE)); + float n = ((float)rng.NextDouble() * 2 - 1) * env * cg; + l[s0 + i] += n * (1 - cp); r[s0 + i] += n * cp; + } + } + } + l = Reverb(l, 0.3f, 0.55f); r = Reverb(r, 0.3f, 0.57f); + var st = new float[total * 2]; + float peak = 1e-4f; + for (int i = 0; i < total; i++) peak = MathF.Max(peak, MathF.Max(MathF.Abs(l[i]), MathF.Abs(r[i]))); + for (int i = 0; i < total; i++) + { + float fade = i > total - RATE ? (total - i) / (float)RATE : 1; + st[i * 2] = l[i] / peak * 0.85f * fade; st[i * 2 + 1] = r[i] / peak * 0.85f * fade; + } + Save(lang, Kind.Chant, name, st); + return st; + } + + // ── Klangbausteine ────────────────────────────────────────── + + static float[] Resample(float[] src, int from, int to) + { + if (from == to) return src; + int n = (int)((long)src.Length * to / from); + var dst = new float[n]; + double step = (double)from / to; + for (int i = 0; i < n; i++) + { + double p = i * step; int a = (int)p; float f = (float)(p - a); + float x0 = src[Math.Min(a, src.Length - 1)], x1 = src[Math.Min(a + 1, src.Length - 1)]; + dst[i] = x0 + (x1 - x0) * f; + } + return dst; + } + + /// Kehlige, kräftige Stimme: weiche Sättigung (Kraft), mehr Tiefe, Höhen etwas gedämpft. + static float[] Grit(float[] x) + { + var n = Normalize(x, 1f); + var low = LowPass(n, 0.06f); + var y = new float[n.Length]; + const float DRIVE = 2.4f; + float norm = MathF.Tanh(DRIVE); + for (int i = 0; i < n.Length; i++) + { + float sat = MathF.Tanh(n[i] * DRIVE) / norm; + y[i] = 0.55f * sat + 0.45f * n[i] + 0.6f * low[i]; + } + return LowPass(y, 0.7f); + } + + static float[] LowPass(float[] x, float k) + { + var y = new float[x.Length]; float s = 0; + for (int i = 0; i < x.Length; i++) { s += (x[i] - s) * k; y[i] = s; } + return y; + } + + /// Hall aus vier Kammfiltern (verschiedene Längen) – genug für Arena-Weite. + static float[] Reverb(float[] x, float mix, float feedback) + { + int[] delays = { 1557, 1617, 1491, 1422 }; + int tail = (int)(1.2 * RATE); + var y = new float[x.Length + tail]; + var wet = new float[y.Length]; + foreach (int d0 in delays) + { + int d = d0 * 2; + var buf = new float[y.Length]; + for (int i = 0; i < y.Length; i++) + { + float input = i < x.Length ? x[i] : 0; + float prev = i >= d ? buf[i - d] : 0; + buf[i] = input + prev * feedback; + wet[i] += prev * 0.25f; + } + } + for (int i = 0; i < y.Length; i++) y[i] = (i < x.Length ? x[i] : 0) * (1 - mix * 0.5f) + wet[i] * mix; + return y; + } + + static float[] Trim(float[] x) + { + int a = 0, b = x.Length - 1; + while (a < b && MathF.Abs(x[a]) < 0.01f) a++; + while (b > a && MathF.Abs(x[b]) < 0.01f) b--; + var y = new float[b - a + 1]; + Array.Copy(x, a, y, 0, y.Length); + return y; + } + + static float[] Normalize(float[] x, float to) + { + float peak = 1e-4f; + foreach (var v in x) peak = MathF.Max(peak, MathF.Abs(v)); + var y = new float[x.Length]; + for (int i = 0; i < x.Length; i++) y[i] = x[i] / peak * to; + return y; + } + + /// Mono → Stereo (leicht verbreitert). + static float[] Stereo(float[] x, float width) + { + var y = new float[x.Length * 2]; + int off = (int)(0.012 * RATE); + for (int i = 0; i < x.Length; i++) + { + float d = i >= off ? x[i - off] : 0; + y[i * 2] = x[i] * (1 - width) + d * width; + y[i * 2 + 1] = x[i]; + } + return y; + } + + // ── Zwischenspeicher auf der Platte (rohe Float-Stereo-Daten) ── + + static string CacheFile(string lang, Kind kind, string text) + { + var hash = Convert.ToHexString(SHA1.HashData(Encoding.UTF8.GetBytes($"{lang}|{kind}|{text}|v2")))[..16]; + return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "GladiatorIdle", "voice", hash + ".pcm"); + } + + static float[]? Cached(string lang, Kind kind, string text) + { + if (DevShot.Active) return null; + try + { + string f = CacheFile(lang, kind, text); + if (!File.Exists(f)) return null; + var bytes = File.ReadAllBytes(f); + var data = new float[bytes.Length / 4]; + Buffer.BlockCopy(bytes, 0, data, 0, bytes.Length); + return data; + } + catch { return null; } + } + + static void Save(string lang, Kind kind, string text, float[] data) + { + if (DevShot.Active) + { + if (DevShot.Dir != null) WriteWav(Path.Combine(DevShot.Dir, $"voice_{lang}_{kind}.wav".ToLowerInvariant()), data); + return; + } + try + { + string f = CacheFile(lang, kind, text); + Directory.CreateDirectory(Path.GetDirectoryName(f)!); + var bytes = new byte[data.Length * 4]; + Buffer.BlockCopy(data, 0, bytes, 0, bytes.Length); + File.WriteAllBytes(f, bytes); + } + catch { /* nur für diese Sitzung */ } + } + + /// Testläufe: Stereo-Float als 16-Bit-WAV (zum Anhören und Prüfen). + public static void WriteWav(string path, float[] st) + { + using var w = new BinaryWriter(File.Create(path)); + int bytes = st.Length * 2; + w.Write(Encoding.ASCII.GetBytes("RIFF")); w.Write(36 + bytes); w.Write(Encoding.ASCII.GetBytes("WAVEfmt ")); + w.Write(16); w.Write((short)1); w.Write((short)2); w.Write(RATE); w.Write(RATE * 4); w.Write((short)4); w.Write((short)16); + w.Write(Encoding.ASCII.GetBytes("data")); w.Write(bytes); + foreach (var s in st) w.Write((short)Math.Clamp(s * 32767, -32768, 32767)); + } + } +} diff --git a/Core/SoundManager.cs b/Core/SoundManager.cs index f450811..6c59c6e 100644 --- a/Core/SoundManager.cs +++ b/Core/SoundManager.cs @@ -378,6 +378,16 @@ namespace GladiatorIdle }); } + /// Fertige Stereo-Daten (44,1 kHz) abspielen – Namensrufe; Lautstärke der Erzählstimme. + public static void PlayPcm(string name, float[]? data, float gain = 1f) + { + if (DevShot.SoundLog) DevShot.Log($"sound: want {name}" + (data == null ? " (not ready)" : "")); + if (!_enabled || data == null || VoiceLevel <= 0.001f) return; + var mixer = Mixer; + if (mixer == null) return; + mixer.AddMixerInput(new ClipVoice(data, gain * VoiceLevel / Math.Max(0.05f, SfxLevel))); + } + /// Clip dekodiert als 44,1 kHz Stereo-Float, gecacht. MP3 aus Assets/Audio, sonst Fallback-WAV. static float[]? Clip(string name, byte[]? fallback) { diff --git a/Languages/de.json b/Languages/de.json index 4ea3b0a..c225d14 100644 --- a/Languages/de.json +++ b/Languages/de.json @@ -620,5 +620,10 @@ "missio.toast.mercy": "Gnade gegen die Menge: +{0} Ruhm, aber sie murrt", "missio.toast.against": "Die Menge buht – ihre Gunst sinkt", "duel.charge": "Ansturm!", - "exp.skip": "Klick oder Leertaste: alles sofort zeigen" + "exp.skip": "Klick oder Leertaste: alles sofort zeigen", + "announce.enter": "In die Arena: {0}!", + "announce.win": "Der Sieg gehört {0}!", + "settings.namecalls": "Ansager und Publikum rufen deinen Namen", + "oath.text": "Mein Name ist {0}.|Einst war ich ein freier Mann – Sohn meines Dorfes, Bruder meiner Kameraden.|Man hat mir alles genommen: mein Zuhause, meine Familie, meine Freiheit.|Heute bin ich nur ein Sklave im Sand dieser Arena.|Doch hört mich an: Ich werde kämpfen, bis Rom meinen Namen ruft –|und dann hole ich mir zurück, was mir gehört!", + "oath.skip": "Klick oder Leertaste: überspringen" } diff --git a/Languages/en.json b/Languages/en.json index 563d752..14f1d52 100644 --- a/Languages/en.json +++ b/Languages/en.json @@ -620,5 +620,10 @@ "missio.toast.mercy": "Mercy against the crowd: +{0} fame, but they grumble", "missio.toast.against": "The crowd boos – their favour drops", "duel.charge": "Charge!", - "exp.skip": "Click or press Space: show everything" + "exp.skip": "Click or press Space: show everything", + "announce.enter": "Into the arena: {0}!", + "announce.win": "Victory for {0}!", + "settings.namecalls": "Announcer and crowd call your name", + "oath.text": "My name is {0}.|Once I was a free man – son of my village, brother to my comrades.|They took everything from me: my home, my family, my freedom.|Today I am only a slave in the sand of this arena.|But hear me: I will fight until Rome calls my name –|and then I will take back what is mine!", + "oath.skip": "Click or Space: skip" } diff --git a/Languages/es.json b/Languages/es.json index 6f094df..eeb88f4 100644 --- a/Languages/es.json +++ b/Languages/es.json @@ -620,5 +620,10 @@ "missio.toast.mercy": "Clemencia contra la multitud: +{0} fama, pero murmura", "missio.toast.against": "La multitud abuchea: su favor baja", "duel.charge": "¡Embestida!", - "exp.skip": "Clic o Espacio: mostrar todo" + "exp.skip": "Clic o Espacio: mostrar todo", + "announce.enter": "¡A la arena: {0}!", + "announce.win": "¡La victoria es de {0}!", + "settings.namecalls": "El anunciador y el público gritan tu nombre", + "oath.text": "Mi nombre es {0}.|Una vez fui un hombre libre: hijo de mi aldea, hermano de mis compañeros.|Me lo quitaron todo: mi hogar, mi familia, mi libertad.|Hoy solo soy un esclavo en la arena de este anfiteatro.|Pero escuchadme: lucharé hasta que Roma grite mi nombre…|¡y entonces recuperaré lo que es mío!", + "oath.skip": "Clic o Espacio: saltar" } diff --git a/Mono/Arena/ArenaSet.cs b/Mono/Arena/ArenaSet.cs index 0bb6178..b8925de 100644 --- a/Mono/Arena/ArenaSet.cs +++ b/Mono/Arena/ArenaSet.cs @@ -53,6 +53,8 @@ namespace GladiatorIdle.Arena { // Mauer: Kreisbogen um (CX, ·, ZC); vorderster Punkt bei z = ZC − R const float CX = Camera.W / 2, ZC = 2400, R = 3800, WALL_H = 300, BACK_R = 6500; + /// Innenkreis der Arena (für die Kamera). + public static (Vector2 Center, float R) Ring => (new Vector2(CX, ZC), R); // Ränge hinter der Mauer: Stufen (Höhe, Tiefe), Säulenreihe obenauf const float ROW_H = 64, ROW_D = 118, COL_H = 330; static float Floor => Stage.FloorY; @@ -107,7 +109,7 @@ namespace GladiatorIdle.Arena if (Assets.Sprite("tex_gate", "jpg") is Texture2D gate) _parts.Add(BuildGates(gate)); _parts.Add(BuildProps()); _banners = new Part { Tex = Assets.Sprite("tex_banner", "jpg"), Tint = _look.Banner.ToVector3() * 1.15f }; - foreach (var a in new[] { -50f, -14f, 14f, 50f }) _bannerAt.Add((a, a * 0.13f)); + foreach (var a in new[] { -50f, -14f, 14f, 50f, 85f, -85f, 150f, -150f }) _bannerAt.Add((a, a * 0.13f)); foreach (var p in _parts) p.Freeze(); _backdrop.Freeze(); @@ -115,6 +117,9 @@ namespace GladiatorIdle.Arena if (Assets.Sprite($"spectator_{i}") is Texture2D idle) _fanTex.Add((idle, Assets.Sprite($"spectator_{i}_cheer") ?? idle)); _fanFx = new AlphaTestEffect(Assets.Device) { VertexColorEnabled = true, ReferenceAlpha = 110, AlphaFunction = CompareFunction.Greater }; if (_fanTex.Count > 0 && _rows > 0) SeatFans(arena); + // Stufen aller Texturen jetzt rechnen, nicht beim ersten Jubel mitten im Kampf (Ruckler) + foreach (var (calmTex, cheerTex) in _fanTex) { Assets.Mipmapped(calmTex); Assets.Mipmapped(cheerTex); } + foreach (var part in _parts) if (part.Tex != null && part.Tex != Assets.Pixel) Assets.Mipmapped(part.Tex); _fanV = new VertexPositionColorTexture[_fanTex.Count * 2][]; _fanN = new int[_fanV.Length]; for (int i = 0; i < _fanV.Length; i++) @@ -137,14 +142,14 @@ namespace GladiatorIdle.Arena "marble" => (new Color(222, 214, 202), new Color(168, 156, 148)), _ => (new Color(186, 172, 150), new Color(132, 120, 104)), }; - const int SEG = 80; + const int SEG = 180; for (int i = 0; i < _rows; i++) { float yLow = i == 0 ? Floor - WALL_H - 14 : RowTop(i - 1), yTop = RowTop(i), r0 = RowR(i), r1 = r0 + ROW_D; var shade = (i % 2 == 0) ? 1f : 0.94f; for (int k = 0; k < SEG; k++) { - float d0 = -78 + 156f * k / SEG, d1 = -78 + 156f * (k + 1) / SEG; + float d0 = -180 + 360f * k / SEG, d1 = -180 + 360f * (k + 1) / SEG; var z0 = Vector2.Zero; p.Quad(OnWall(d0, r0, yTop), OnWall(d1, r0, yTop), OnWall(d1, r0, yLow), OnWall(d0, r0, yLow), Inward((d0 + d1) / 2), riser * shade, z0, z0, z0, z0); p.Quad(OnWall(d0, r1, yTop), OnWall(d1, r1, yTop), OnWall(d1, r0, yTop), OnWall(d0, r0, yTop), -Vector3.UnitY, tread * shade, z0, z0, z0, z0); @@ -161,17 +166,17 @@ namespace GladiatorIdle.Arena float h = _rows > 0 ? COL_H : COL_H + 160; var stone = _look.Wall == "marble" ? new Color(226, 218, 204) : _look.Wall == "wood" ? new Color(206, 196, 178) : new Color(196, 184, 162); float step = _look.Wall == "marble" ? 4.5f : 6; - for (float a = -78; a <= 78.01f; a += step) + for (float a = -180; a < 179.99f; a += step) { var c = OnWall(a, r, baseY); p.Cylinder(c, 24, h, stone, 12); p.Cylinder(c, 34, 18, stone * 0.9f, 10); // Basis p.Cylinder(c + new Vector3(0, -h + 20, 0), 32, 20, stone * 0.9f, 10); // Kapitell } - const int SEG = 80; + const int SEG = 180; for (int k = 0; k < SEG; k++) { - float d0 = -78 + 156f * k / SEG, d1 = -78 + 156f * (k + 1) / SEG; + float d0 = -180 + 360f * k / SEG, d1 = -180 + 360f * (k + 1) / SEG; var z0 = Vector2.Zero; float top = baseY - h, n = (d0 + d1) / 2; // Gebälk vorn und oben @@ -192,7 +197,7 @@ namespace GladiatorIdle.Arena { float r = RowR(i) + ROW_D * 0.42f; float step = MathHelper.ToDegrees(gap / r); - for (float a = -77; a <= 77; a += step * (0.8f + 0.4f * (float)rng.NextDouble())) + for (float a = -180; a < 179; a += step * (0.8f + 0.4f * (float)rng.NextDouble())) { if (rng.NextDouble() < 0.1) continue; // freier Platz float rad = MathHelper.ToRadians(a); @@ -270,18 +275,21 @@ namespace GladiatorIdle.Arena Part BuildBackdrop() { var p = new Part { Lit = false, Mirror = true, Fog = false, Tint = Vector3.Lerp(new Vector3(_look.BackdropLight), _look.Fog, 0.18f) }; - const float SPAN = 30, EXTRA = 60; + const float SPAN = 30, EXTRA = 180; float width = BACK_R * MathHelper.ToRadians(2 * SPAN), height = width * 9 / 16; // Bildzeile "Horizon" (dort beginnt der gemalte Boden) liegt knapp unter der Mauerkrone float wallTop = HorizonY(); float top = wallTop - _look.Horizon * height; - const int SEG = 40; + const int SEG = 120; for (int i = 0; i < SEG; i++) { float d0 = -EXTRA + 2 * EXTRA * i / SEG, d1 = -EXTRA + 2 * EXTRA * (i + 1) / SEG; float u0 = (d0 + SPAN) / (2 * SPAN), u1 = (d1 + SPAN) / (2 * SPAN); p.Quad(OnWall(d0, BACK_R, top), OnWall(d1, BACK_R, top), OnWall(d1, BACK_R, top + height), OnWall(d0, BACK_R, top + height), Inward((d0 + d1) / 2), Color.White, new Vector2(u0, 0), new Vector2(u1, 0), new Vector2(u1, 1), new Vector2(u0, 1)); + // Himmel: oberste Zeile des Bildes weit nach oben gezogen + p.Quad(OnWall(d0, BACK_R, top - height * 2.5f), OnWall(d1, BACK_R, top - height * 2.5f), OnWall(d1, BACK_R, top), OnWall(d0, BACK_R, top), + Inward((d0 + d1) / 2), Color.White, new Vector2(u0, 0), new Vector2(u1, 0), new Vector2(u1, 0.004f), new Vector2(u0, 0.004f)); } return p; } @@ -299,8 +307,8 @@ namespace GladiatorIdle.Arena Part BuildFloor() { var p = new Part { Tex = Assets.Sprite("tex_sand", "jpg"), Wrap = true, Tint = _look.Sand * new Vector3(0.86f, 0.88f, 0.98f) }; - const int NX = 40, NZ = 16; - float x0 = CX - 5200, x1 = CX + 5200, z0 = -(R - ZC) - 900, z1 = 900; + const int NX = 40, NZ = 40; + float x0 = CX - 5200, x1 = CX + 5200, z0 = -(R - ZC) - 900, z1 = ZC + R + 900; // rundum bis hinter die Kamera Vector3 Pt(int i, int k) => new(x0 + (x1 - x0) * i / NX, Floor, z0 + (z1 - z0) * k / NZ); Color Shade(Vector3 v) { @@ -330,8 +338,8 @@ namespace GladiatorIdle.Arena { var tint = _look.Wall == "wood" ? new Vector3(1.05f, 0.82f, 0.62f) : Vector3.One; // Holz wärmer als die graue Vorlage var p = new Part { Tex = Assets.Sprite(WallTex, "jpg"), Wrap = true, Tint = tint }; - const int SEG = 72; - const float FROM = -75, TO = 75; + const int SEG = 170; + const float FROM = -180, TO = 180; // rundum (Kinofahrten drehen bis 360°) float tile = WALL_H * 3; // Textur 3:1 for (int i = 0; i < SEG; i++) { @@ -348,10 +356,10 @@ namespace GladiatorIdle.Arena { var p = new Part { Tex = Assets.Pixel }; var col = _look.Wall switch { "wood" => new Color(92, 66, 44), "marble" => new Color(214, 196, 150), _ => new Color(196, 184, 160) }; - const int SEG = 72; + const int SEG = 170; for (int i = 0; i < SEG; i++) { - float d0 = -75 + 150f * i / SEG, d1 = -75 + 150f * (i + 1) / SEG; + float d0 = -180 + 360f * i / SEG, d1 = -180 + 360f * (i + 1) / SEG; var z0 = Vector2.Zero; float y = Floor - WALL_H; p.Quad(OnWall(d0, R + 30, y - 14), OnWall(d1, R + 30, y - 14), OnWall(d1, R - 26, y - 14), OnWall(d0, R - 26, y - 14), @@ -366,7 +374,7 @@ namespace GladiatorIdle.Arena Part BuildGates(Texture2D gate) { var p = new Part { Tex = gate }; - var at = _look.Wall == "marble" ? new[] { -30f, 0f, 30f } : new[] { -30f, 30f }; + var at = _look.Wall == "marble" ? new[] { -30f, 0f, 30f, 180f, -120f, 120f } : new[] { -30f, 30f, 180f, -120f, 120f }; foreach (float a in at) { float half = MathHelper.ToDegrees(130 / R); // 260 breit diff --git a/Mono/Arena/Camera.cs b/Mono/Arena/Camera.cs index 687fa8c..0b476aa 100644 --- a/Mono/Arena/Camera.cs +++ b/Mono/Arena/Camera.cs @@ -37,14 +37,94 @@ namespace GladiatorIdle.Arena float k = 1 - MathF.Exp(-dt * 3.5f); if (FocusX is float fx) { targetZoom = 1.4f; target = new Vector2(fx, H / 2 + 30); k = 1 - MathF.Exp(-dt * 1.2f); } if (FollowX is float fw) { targetZoom = FollowZoom; target = new Vector2(fw, H / 2 + 40); k = 1 - MathF.Exp(-dt * 4f); } // Reise: ohne Begrenzung + if (CineWeight > 0.01f) { target = Vector2.Lerp(target, new Vector2(CinePivot.X + CineFrameX, CinePivot.Y), CineWeight); targetZoom = MathHelper.Lerp(targetZoom, 1, CineWeight); } Center += (target - Center) * k; Zoom += (targetZoom - Zoom) * k; _trauma = MathF.Max(0, _trauma - dt * 1.7f); _punch *= MathF.Exp(-dt * 9f); if (calm) { _trauma = 0; _punch = 0; } UpdateYaw(dt, calm); + UpdateCine(dt, calm); } + // ── Kinokamera: Fahrten um einen Drehpunkt (360°), Neigung (Untersicht), Heranfahren ── + + /// Schlüsselbild einer Fahrt: Zeit (s), Drehung (Grad, beliebig, auch über 360), Neigung + /// (Grad, negativ = von unten nach oben), Heranfahren (Design-Pixel näher). + public readonly record struct Key(float T, float Yaw, float Pitch, float Dolly); + + /// Drehpunkt der Fahrt (Weltpunkt, meist Brust eines Kämpfers); setzt die Szene jedes Bild. + public Vector3 CinePivot; + /// Bildlage des Drehpunkts: + schiebt ihn nach links (Platz für Tafeln rechts). + public float CineFrameX; + public float CineYaw { get; private set; } + public float CinePitch { get; private set; } + public float CineDolly { get; private set; } + /// 0 = normale Seitenansicht, 1 = ganz in der Fahrt (Ein- und Ausblenden weich). + public float CineWeight { get; private set; } + Key[]? _shot; float _shotT, _orbitSpeed; bool _orbit; Key _orbitKey; + + /// Fahrt aus Schlüsselbildern; danach weich zurück zur Seitenansicht. + public void Shot(params Key[] keys) { if (keys.Length > 0) { _shot = keys; _shotT = 0; _orbit = false; } } + + /// Fortlaufende Umrundung (Grad/s) mit fester Neigung und Nähe, bis . + public void Orbit(float degPerSec, float pitch, float dolly) + { + _orbit = true; _shot = null; _orbitSpeed = degPerSec; + _orbitKey = new Key(0, CineWeight > 0.01f ? CineYaw : 0, pitch, dolly); + } + + public void StopCine() { _shot = null; _orbit = false; } + public bool CineActive => _shot != null || _orbit; + + void UpdateCine(float dt, bool calm) + { + if (calm) { _shot = null; _orbit = false; CineWeight = 0; return; } + float target = 0; + if (_orbit) + { + _orbitKey = _orbitKey with { Yaw = _orbitKey.Yaw + _orbitSpeed * dt }; + Blend(_orbitKey, dt); + target = 1; + } + else if (_shot is { } keys) + { + _shotT += dt; + int i = 0; + while (i < keys.Length - 1 && _shotT > keys[i + 1].T) i++; + Key a = keys[i], b = keys[Math.Min(i + 1, keys.Length - 1)]; + float k = b.T > a.T ? MathHelper.Clamp((_shotT - a.T) / (b.T - a.T), 0, 1) : 1; + k = k * k * (3 - 2 * k); + CineYaw = MathHelper.Lerp(a.Yaw, b.Yaw, k); CinePitch = MathHelper.Lerp(a.Pitch, b.Pitch, k); CineDolly = MathHelper.Lerp(a.Dolly, b.Dolly, k); + if (_shotT > keys[^1].T) _shot = null; + target = 1; + CineWeight = 1; + } + if (target == 0) + { + // zurück: Winkel auf den nächsten Vollkreis, Neigung und Nähe auf 0 + float home = MathF.Round(CineYaw / 360) * 360; + float k = 1 - MathF.Exp(-dt * 3.2f); + CineYaw += (home - CineYaw) * k; CinePitch -= CinePitch * k; CineDolly -= CineDolly * k; + if (MathF.Abs(CineYaw - home) < 0.3f && MathF.Abs(CinePitch) < 0.2f && MathF.Abs(CineDolly) < 2) { CineYaw = 0; CinePitch = 0; CineDolly = 0; CineWeight = 0; } + else CineWeight = 1; + } + } + + void Blend(Key to, float dt) + { + float k = CineWeight < 1 ? 1 - MathF.Exp(-dt * 3f) : 1; + CineYaw += (to.Yaw - CineYaw) * (_orbit && CineWeight >= 1 ? 1 : k); + CinePitch += (to.Pitch - CinePitch) * k; CineDolly += (to.Dolly - CineDolly) * k; + CineWeight = 1; + } + + /// Wie sichtbar die Kampfebene (2D-Effekte) gerade ist: 1 von vorn, 0 von der Seite. + public float PlaneAlpha => MathHelper.Clamp((MathF.Abs(MathF.Cos(MathHelper.ToRadians(Yaw + CineYaw))) - 0.35f) / 0.4f, 0, 1); + /// Publikum im Vordergrund (Bildschirm-Ebene) nur in der Seitenansicht. + public float FrontAlpha => 1 - CineWeight; // während einer Fahrt tritt das Publikum im Vordergrund ganz zurück + static float WrapDeg(float d) { d %= 360; return d > 180 ? d - 360 : d < -180 ? d + 360 : d; } + /// Kameraverschiebung durch Rütteln (Design-Pixel). Vector2 ShakeOffset() { @@ -104,15 +184,58 @@ namespace GladiatorIdle.Arena public Matrix View3() { var pivot = new Vector3(Center.X, 0, 0); - return Matrix.CreateTranslation(-pivot) * Matrix.CreateRotationY(MathHelper.ToRadians(Yaw)) * Matrix.CreateTranslation(pivot) - * Matrix.CreateTranslation(-Center.X, -EyeY, -DIST); + var view = Matrix.CreateTranslation(-pivot) * Matrix.CreateRotationY(MathHelper.ToRadians(Yaw)) * Matrix.CreateTranslation(pivot); + if (CineWeight > 0.001f) + { + // Kinofahrt: um den Drehpunkt drehen und neigen, dann heranfahren + var cp = new Vector3(Center.X, CinePivot.Y, CinePivot.Z); + view *= Matrix.CreateTranslation(-cp) * Matrix.CreateRotationY(MathHelper.ToRadians(CineYaw)) + * Matrix.CreateRotationX(MathHelper.ToRadians(CinePitch)) * Matrix.CreateTranslation(cp) + * Matrix.CreateTranslation(0, 0, CineDolly - FitPull); + } + return view * Matrix.CreateTranslation(-Center.X, -EyeNow, -DIST); } + /// Augenhöhe mit Fahrt: wandert zum Drehpunkt, damit das Heranfahren auf ihn zielt. + float EyeNow => MathHelper.Lerp(EyeY, CinePivot.Y, CineWeight * 0.85f); + + /// Sicherung: so weit fährt die Kamera gerade zurück, damit alle Figuren im Bild bleiben. + public float FitPull { get; private set; } + + /// Figuren im Bild halten: ragt ein Punkt (Kopf, Füße) aus dem sicheren Bereich, zieht die + /// Kamera schnell auf; ist genug Platz, kehrt sie langsam zur geplanten Nähe zurück. + public void KeepInView(ReadOnlySpan points, float screenScale, Vector2 offset, int vpW, int vpH, float dt) + { + if (CineWeight < 0.01f && FitPull <= 0) return; + var vp = View3() * Proj3(screenScale, offset, vpW, vpH); + float worst = 0; + foreach (var pt in points) + { + var c = Vector4.Transform(new Vector4(pt, 1), vp); + if (c.W <= 1e-3f) { worst = MathF.Max(worst, 1); continue; } // hinter der Kamera + float x = c.X / c.W, y = c.Y / c.W; + worst = MathF.Max(worst, MathF.Max(MathF.Abs(x) - 0.78f, MathF.Abs(y) - 0.76f)); + } + if (worst > 0) FitPull += (900 + 6000 * worst) * dt; + else if (worst < -0.08f) FitPull = MathF.Max(0, FitPull - 260 * dt); + FitPull = MathF.Min(FitPull, CineDolly + 1400); // höchstens etwas weiter weg als die Seitenansicht + // nie hinter die Arenamauer: steht die Kamera außerhalb des Rings, fährt sie wieder heran + if (Ring is { } ring && CineWeight > 0.01f) + { + var eye = Matrix.Invert(View3()).Translation; + float d = Vector2.Distance(new Vector2(eye.X, eye.Z), ring.Center); + if (d > ring.R - 260) FitPull -= (d - (ring.R - 260)) + 1; + } + } + + /// Ring der Arena (Mitte x/z, Radius): die Kinokamera bleibt innen. + public (Vector2 Center, float R)? Ring; + /// Kameraraum → Bildschirm (Clip): erst perspektivisch zurück in Design-Pixel der Ebene z = 0, /// dann dieselbe 2D-Abbildung wie (Zoom, Wackeln, Stoß), dann Pixel → Clip. public Matrix Proj3(float screenScale, Vector2 offset, int vpW, int vpH) { - float ex = Center.X, ey = EyeY, d = DIST; + float ex = Center.X, ey = EyeNow, d = DIST; float a = -FAR / (d * (FAR - NEAR)), b = -NEAR * FAR / (d * (FAR - NEAR)); // Zeilen-Vektor-Form: (x, y, z, 1) → (X, Y, Z, W) mit W = −z/d (z = 0 der Welt ⇒ W = 1) var p = new Matrix( diff --git a/Mono/Arena/CreatorScene.cs b/Mono/Arena/CreatorScene.cs index 930eacc..7e067e4 100644 --- a/Mono/Arena/CreatorScene.cs +++ b/Mono/Arena/CreatorScene.cs @@ -65,9 +65,10 @@ namespace GladiatorIdle.Arena /// Getippte Zeichen (vom Fenster) für den Namen. public void OnText(char c, Keys key) { - if (key == Keys.Back) { if (Name.Length > 0) Name = Name[..^1]; return; } + if (key == Keys.Back) { if (Name.Length > 0) Name = Name[..^1]; _typedAt = _t; return; } if (key == Keys.Enter) return; if (!char.IsControl(c) && Name.Length < 18) Name += c; + _typedAt = _t; } // ── Takt ──────────────────────────────────────────────────── @@ -168,8 +169,13 @@ namespace GladiatorIdle.Arena _thumbClass = Class; _thumbTint = Tint; _thumbsDirty = false; } + double _typedAt = -1; + void DrawNameField(SpriteBatch sb) { + // nach ~1 s Tipp-Pause: Stimme für Name und Schwur im Hintergrund vorbereiten + if (_typedAt >= 0 && _t - _typedAt > 1.0 && Name.Trim().Length > 0) { NameVoice.Prepare(Name); _typedAt = -1; } + var r = new RectangleF(170, 968, 600, 68); D.Text(sb, Assets.SansBold, 20, L.t("create.name"), new Vector2(r.X, r.Y - 22), D.Sand); Ui.Panel(sb, r, D.Gold); diff --git a/Mono/Arena/Crowd.cs b/Mono/Arena/Crowd.cs index 054aeed..55de100 100644 --- a/Mono/Arena/Crowd.cs +++ b/Mono/Arena/Crowd.cs @@ -123,8 +123,12 @@ namespace GladiatorIdle.Arena } /// Zeichnen in der Vordergrund-Ebene (eigene Kamera-Matrix mit Parallaxe). + /// Deckkraft (Kinofahrt: das Publikum im Vordergrund tritt zurück). + public float Alpha = 1; + public void Draw(SpriteBatch sb, bool calm) { + if (Alpha <= 0.01f) return; foreach (var f in _fans) { // jubelnd: Fäuste im eigenen Takt hoch und runter (Wechsel der Bilder) @@ -139,7 +143,7 @@ namespace GladiatorIdle.Arena float scale = f.H / tex.Height; float bottom = f.H > 260 ? Camera.H + 175 : Camera.H + 70; var pos = new Vector2(f.X, bottom - bob); - var c = new Color(f.Shade * 1.1f, f.Shade * 0.9f, f.Shade * 0.75f); + var c = new Color(f.Shade * 1.1f, f.Shade * 0.9f, f.Shade * 0.75f) * Alpha; sb.Draw(tex, pos, null, c, calm ? 0 : f.Tilt, new Vector2(tex.Width / 2f, tex.Height), new Vector2(scale / MathF.Sqrt(stretch), scale * stretch * breathe), f.Mirror ? SpriteEffects.FlipHorizontally : SpriteEffects.None, 0); @@ -149,7 +153,7 @@ namespace GladiatorIdle.Arena { float a = MathF.Min(1, p.Life * 1.5f); float flip = MathF.Abs(MathF.Cos(p.Angle * 1.7f)); // dreht sich in der Luft - sb.Draw(Assets.Disc, p.Pos, null, p.Color * a, p.Angle, new Vector2(64), new Vector2(p.Size / 128f, p.Size * (0.35f + 0.65f * flip) / 128f / 1.6f), + sb.Draw(Assets.Disc, p.Pos, null, p.Color * (a * Alpha), p.Angle, new Vector2(64), new Vector2(p.Size / 128f, p.Size * (0.35f + 0.65f * flip) / 128f / 1.6f), SpriteEffects.None, 0); } } diff --git a/Mono/Arena/DuelScene.cs b/Mono/Arena/DuelScene.cs index 806f36f..5e52a22 100644 --- a/Mono/Arena/DuelScene.cs +++ b/Mono/Arena/DuelScene.cs @@ -43,7 +43,31 @@ namespace GladiatorIdle.Arena { enum Phase { Intro, Countdown, Fight, End } - const float COUNTDOWN = 2.2f, SPREAD = 1.3f; + const float SPREAD = 1.3f; + float COUNTDOWN => _calm ? 2.2f : 3.4f; // mit Kinofahrt etwas länger + + // ── Kinofahrten: worum sich die Kamera dreht ── + enum Pivot { Mid, Player, PlayerHead, Enemy, Winner } + Pivot _pivot; + Vector3 PivotPos() => _pivot switch + { + Pivot.Player => new Vector3(_pv.X, Stage.FloorY - Stage.FigH * 0.55f, 0), + Pivot.PlayerHead => new Vector3(_pv.X, Stage.FloorY - Stage.FigH * 0.86f, 0), + Pivot.Enemy => new Vector3(_ev.X, Stage.FloorY - Stage.FigH * 0.55f, 0), + Pivot.Winner => new Vector3(Won ? _pv.X : _ev.X, Stage.FloorY - Stage.FigH * 0.55f, 0), + _ => new Vector3((_pv.X + _ev.X) / 2, Stage.FloorY - Stage.FigH * 0.5f, 0), + }; + + /// Fahrt ab dem jetzigen Stand der Kamera (weicher Übergang). + void Cine(Pivot pivot, params Camera.Key[] keys) + { + if (_calm) return; + _pivot = pivot; + var all = new Camera.Key[keys.Length + 1]; + all[0] = new Camera.Key(0, _cam.CineYaw, _cam.CinePitch, _cam.CineDolly); + Array.Copy(keys, 0, all, 1, keys.Length); + _cam.Shot(all); + } readonly GameState _game; readonly Enemy _enemy; @@ -55,7 +79,8 @@ namespace GladiatorIdle.Arena readonly Texture2D? _backdrop; // Standbild für das Champion-Intro readonly ArenaSet _set; // 3D-Kulisse: Sand, Mauer, Tore, Feuer, fernes Gemälde BasicEffect? _plane; // 2D-Effekte auf der Kampfebene (z = 0) durch die 3D-Kamera - bool _wasFury; + bool _wasFury, _announced; + Matrix _v3, _p3; int _vw = 1, _vh = 1; float _scale = 1; Vector2 _offset; readonly bool _calm = AppSettings.ReduceMotion; readonly AbilityBar _bar = new(); @@ -209,6 +234,7 @@ namespace GladiatorIdle.Arena string arena = Art.Arena(ArenaDef.All[game.Arena]); _backdrop = Assets.Sprite(arena, "jpg"); _set = ArenaSet.Get(game.Arena, arena, _calm); + _cam.Ring = ArenaSet.Ring; _cam.Center = new Vector2(Camera.W / 2, Camera.H / 2 + 40); _cam.Zoom = 1.45f; // Auftakt: nah, dann fährt die Kamera auf _crowd.Excite(0.5f); @@ -255,6 +281,15 @@ namespace GladiatorIdle.Arena } return; case Phase.Countdown: + if (!_announced) + { + _announced = true; + NameVoice.Play(NameVoice.Kind.Enter, 1f, 8); // „Gladiator Spartacus!“ + if (_enemy.IsChampion) // Champion: von unten nah heran, dann hoch und zurück + Cine(Pivot.Enemy, new(0.01f, -35, -24, 1700), new(1.7f, -55, -16, 1550), new(COUNTDOWN, 0, 0, 0)); + else if (_tut == TutStep.Off) // volle Umrundung beider Kämpfer + Cine(Pivot.Mid, new(0.01f, -320, 5, 1100), new(2.7f, -20, 2, 600), new(COUNTDOWN, 0, 0, 0)); + } int n = 3 - (int)(_phaseTime / (COUNTDOWN / 3)); if (n != _countShown) { _countShown = n; if (n >= 1) SoundManager.PlayTick(); } if (_phaseTime >= COUNTDOWN) @@ -275,10 +310,12 @@ namespace GladiatorIdle.Arena _phase = Phase.End; _phaseTime = 0; Won = Duel.PlayerWon; // Gnadenstoß: nicht in der Einführung und nicht gegen Legenden _missio = !TutorialRan && _enemy.Display == null; + if (Won && !_missio) NameVoice.Play(NameVoice.Kind.Chant, 1f, 0); _crowdMercy = Duel.DamageToPlayer >= Duel.Player.MaxHp * 0.3 || Duel.Time >= 25; // tapferer Gegner if (!Won) _spared = Duel.PlayerParries >= 2 || Duel.Enemy.Hp <= Duel.Enemy.MaxHp * 0.5 || Duel.Time >= 30; _cam.FocusX = Won ? _pv.X : _ev.X; - if (!_calm) _cam.HoldYaw(Won ? 24 : -24); // langsame Fahrt um den Sieger + // Kinomoment: Kamera kippt nach unten, Nahansicht auf den Sieger über dem Gefallenen + Cine(Pivot.Winner, new(0.6f, Won ? 35 : -35, -20, 1500), new(2.8f, Won ? 70 : -70, -17, 1450)); if (Won) SoundManager.PlayVictory(); else SoundManager.PlayDefeat(); } break; @@ -296,7 +333,16 @@ namespace GladiatorIdle.Arena if (_ev.Update(dt, realDt, Duel.Enemy, Spread(Duel.Enemy.X), _calm)) { _fx.Dust(new Vector2(_ev.X, Stage.FloorY), 2, 30, 30, 40); SoundManager.PlayStep(); } StateSounds(); FuryUpdate(realDt); + _cam.CinePivot = PivotPos(); _cam.Update(realDt, _pv.X, _ev.X, _calm); + _crowd.Alpha = _cam.FrontAlpha; + // beide Kämpfer immer ganz im Bild (Kopf und Füße) + float head = Stage.FloorY - Stage.FigH * 1.08f, feet = Stage.FloorY + 12; + Span pts = stackalloc Vector3[] + { + new(_pv.X - 60, head, 0), new(_pv.X + 60, feet, 0), new(_ev.X - 60, head, 0), new(_ev.X + 60, feet, 0), + }; + _cam.KeepInView(pts, _scale, _offset, _vw, _vh, realDt); _fx.Motes(_calm ? 0 : 60, Camera.W, Camera.H); _fx.Update(dt > 0 ? dt : realDt * 0.15f); _crowd.Update(realDt); @@ -318,7 +364,8 @@ namespace GladiatorIdle.Arena { var pl = Duel.Player; bool fury = pl.State == DuelState.Super; - if (fury && !_wasFury && !_calm) _cam.Pulse(-22, 1.6f); // Kinomoment: die Kamera schwenkt herum und zurück + if (fury && !_wasFury) // Kinomoment: aufs Gesicht, dann zurück zur Hiebserie + Cine(Pivot.PlayerHead, new(0.3f, -28 * _pv.Facing, -9, 1750), new(0.75f, -34 * _pv.Facing, -7, 1700), new(1.15f, 0, 0, 0)); _wasFury = fury; _furyDark += ((fury ? 1f : 0f) - _furyDark) * (1 - MathF.Exp(-realDt * (fury ? 7 : 2.5f))); if (fury && _phase == Phase.Fight) _cam.FocusX = (_pv.X + _ev.X) / 2; @@ -498,7 +545,7 @@ namespace GladiatorIdle.Arena break; case DuelEventType.Leap: _fx.Dust(new Vector2(_pv.X, Stage.FloorY), 10, 90, 50, 70); - if (!_calm) { _cam.Lift(140); _cam.Pulse(10f * (float)Duel.Player.Facing, 1.0f); } // Kamera steigt mit + if (!_calm) { _cam.Lift(140); Cine(Pivot.Player, new(0.35f, 14f * (float)Duel.Player.Facing, -12, 450), new(0.95f, 0, 0, 0)); } // Untersicht folgt dem Sprung _crowd.Excite(0.15f); break; case DuelEventType.Super: @@ -585,6 +632,8 @@ namespace GladiatorIdle.Arena var p3 = _cam.Proj3(scale, offset, vw, vh); _plane ??= new BasicEffect(gd) { TextureEnabled = true, VertexColorEnabled = true, LightingEnabled = false }; _plane.World = Matrix.Identity; _plane.View = v3; _plane.Projection = p3; + _plane.Alpha = _cam.PlaneAlpha; // Kinofahrt: 2D-Effekte nicht von der Kante zeigen + _v3 = v3; _p3 = p3; _vw = vw; _vh = vh; _scale = scale; _offset = offset; void Plane(BlendState blend) => sb.Begin(SpriteSortMode.Deferred, blend, SamplerState.LinearClamp, DepthStencilState.None, RasterizerState.CullNone, _plane); var ui = Matrix.CreateScale(scale) * Matrix.CreateTranslation(offset.X, offset.Y, 0); @@ -691,12 +740,9 @@ namespace GladiatorIdle.Arena if (_screenFlash > 0) D.Rect(sb, new RectangleF(0, 0, Camera.W, Camera.H), _flashColor * (_screenFlash * 0.5f)); sb.End(); - // Zahlen über den Köpfen (Kampfebene) und HUD (Bildschirm) - Plane(BlendState.AlphaBlend); - foreach (var f in _floaters) if (!f.Big) DrawFloater(sb, f); - sb.End(); + // Zahlen über den Köpfen (an der Welt-Stelle, aber am Bildschirm gezeichnet: auch beim Schwenk lesbar) und HUD sb.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, null, null, null, ui); - foreach (var f in _floaters) if (f.Big) DrawFloater(sb, f); + foreach (var f in _floaters) DrawFloater(sb, f); DrawHud(sb); sb.End(); _bar.Draw(gd, sb, ui); @@ -745,6 +791,13 @@ namespace GladiatorIdle.Arena float pop = f.Big ? 1 + 0.6f * MathF.Max(0, 1 - f.Age * 6) : 1 + 0.5f * MathF.Max(0, 1 - f.Age * 8); float a = MathHelper.Clamp((1 - k) * 2.5f, 0, 1); var pos = f.Pos - new Vector2(0, f.Big ? 0 : 110 * MathF.Sqrt(k)); + if (!f.Big) + { + // Weltpunkt der Kampfebene → Bildschirm → Design-Pixel + var px = _cam.ToPixel(new Vector3(pos, 0), _v3, _p3, _vw, _vh, out float w); + pos = (px - _offset) / _scale; + pop /= MathF.Max(0.6f, w); + } D.Text(sb, f.Big ? Assets.Serif : Assets.SansBold, f.Size, f.Text, pos, f.Color * a, Align.Center, pop); } @@ -824,6 +877,7 @@ namespace GladiatorIdle.Arena void MissioUpdate(float realDt, Input input) { + if (_missioT == 0 && !_calm) { _pivot = Pivot.Mid; _cam.Orbit(Won ? 42 : -42, -8, 1350); } // die Ränge rundum _missioT += realDt; bool wantMercy = Won ? _crowdMercy : _spared == true; float target = wantMercy ? 0.12f : 0.88f; @@ -870,10 +924,13 @@ namespace GladiatorIdle.Arena { if (_decidedAt >= 0) return; _decidedAt = _missioT; + float y0 = _cam.CineYaw; + Cine(Pivot.Winner, new(1.2f, y0 + 50, -22, 1550), new(5f, y0 + 120, -18, 1480)); // Heldenblick von unten if (!Won) { if (mercy) SoundManager.PlayCheer(); else SoundManager.PlayBoo(); return; } _mercy = mercy; bool match = mercy == _crowdMercy; - if (match) { _crowd.Wave(); SoundManager.PlayCheer(); } else SoundManager.PlayBoo(); + if (match) { _crowd.Wave(); SoundManager.PlayCheer(); NameVoice.Play(_enemy.IsChampion ? NameVoice.Kind.Win : NameVoice.Kind.Chant, 1f, 0); } + else SoundManager.PlayBoo(); if (!mercy) { _pv.HoldClip = "powerup"; _cam.Shake(0.35f); SoundManager.PlayFury(); } // Kampfschrei, keine Tötung Big(L.t(mercy ? "missio.mitte" : "missio.iugula"), mercy ? D.Gold : new Color(255, 120, 70)); } diff --git a/Mono/Arena/FreedomScene.cs b/Mono/Arena/FreedomScene.cs index c52465a..ff244ac 100644 --- a/Mono/Arena/FreedomScene.cs +++ b/Mono/Arena/FreedomScene.cs @@ -55,7 +55,8 @@ namespace GladiatorIdle.Arena SoundManager.PlayMusic("music_freedom", loop: true); _fx.Calm = AppSettings.ReduceMotion; _stage.Cam.FocusX = 800; // Held links, Platz für die Bilanz rechts - _stage.Cam.HoldYaw(-16); + _stage.Cam.Orbit(18, -8, 1250); + _stage.Cam.CineFrameX = 600; // Gladiator links, die Bilanz rechts // langsam um den freien Gladiator, leicht von unten } void Next(Phase p) @@ -63,6 +64,7 @@ namespace GladiatorIdle.Arena if (p != Phase.Clip) SoundManager.StopVoice(); _phase = p; _phaseT = 0; SoundManager.PlayClick(); + if (p == Phase.Summary) NameVoice.Play(NameVoice.Kind.Chant, 1f, 0); // die Arena ruft den Namen if (p == Phase.Summary && !AppSettings.ReduceMotion) { // Goldregen zum Auftakt der Bilanz @@ -81,7 +83,10 @@ namespace GladiatorIdle.Arena _ui.Begin(input, ui); _dummy.StateTime += dt; _hero.Update(dt, dt, _dummy, HERO_X, AppSettings.ReduceMotion); + _stage.Cam.CinePivot = new Vector3(HERO_X, Stage.FloorY - Stage.FigH * 0.55f, 0); _stage.Cam.Update(dt, HERO_X, HERO_X, AppSettings.ReduceMotion); + Span pts = stackalloc Vector3[] { new(HERO_X - 80, Stage.FloorY - Stage.FigH * 1.1f, 0), new(HERO_X + 80, Stage.FloorY + 12, 0) }; + _stage.Cam.KeepInView(pts, _stage.LastScale, _stage.LastOffset, _stage.LastW, _stage.LastH, dt); _fx.Motes(AppSettings.ReduceMotion ? 0 : 40, Camera.W, Camera.H); _fx.Update(dt); if (_phase == Phase.Clip) diff --git a/Mono/Arena/HubScene.Homecoming.cs b/Mono/Arena/HubScene.Homecoming.cs index f4ceeb8..f72e0d6 100644 --- a/Mono/Arena/HubScene.Homecoming.cs +++ b/Mono/Arena/HubScene.Homecoming.cs @@ -39,7 +39,7 @@ namespace GladiatorIdle.Arena // Ankunft: Pose und Ton einmal if (before < HomeWalk && _homeT >= HomeWalk) { - if (rep.Success) { _dummy.Set(DuelState.Victory); SoundManager.PlayVictory(); SoundManager.PlayCheer(); _crowd.Wave(); } + if (rep.Success) { _dummy.Set(DuelState.Victory); SoundManager.PlayVictory(); SoundManager.PlayCheer(); _crowd.Wave(); NameVoice.Play(NameVoice.Kind.Chant, 0.6f); } else { _dummy.Set(DuelState.Stunned); _dummy.StunLeft = 99; SoundManager.PlayDefeat(); } } _dummy.StateTime += dt; diff --git a/Mono/Arena/HubScene.Journey.cs b/Mono/Arena/HubScene.Journey.cs index 5ce6297..31c3641 100644 --- a/Mono/Arena/HubScene.Journey.cs +++ b/Mono/Arena/HubScene.Journey.cs @@ -102,6 +102,8 @@ namespace GladiatorIdle.Arena _jStone.Box(new Vector3(0, floor - 95, 0), new Vector3(40, 12, 36), new Color(150, 144, 132)); _jStone.Freeze(); _jProps.Clear(); + foreach (var k in land.Props) if (Assets.Sprite(k) is Texture2D t) Assets.Mipmapped(t); // vorab, kein Ruckler + foreach (var m in new[] { _jGround, _jPath }) if (m?.Tex != null) Assets.Mipmapped(m.Tex); } /// Licht nach Tageszeit (0 Morgen … 0,25 Mittag … 0,5 Abend … 0,75 Nacht … 1 Morgen). diff --git a/Mono/Arena/HubScene.cs b/Mono/Arena/HubScene.cs index 32718e1..660ea3c 100644 --- a/Mono/Arena/HubScene.cs +++ b/Mono/Arena/HubScene.cs @@ -111,7 +111,16 @@ namespace GladiatorIdle.Arena _game.Tick(dt); // Training, Einnahmen, Erholung float heroX = Homecoming ? UpdateHomecoming(dt, input) : HERO_X; // Heimkehr: läuft von links herein _hero.Update(dt, dt, _dummy, heroX, AppSettings.ReduceMotion); + _stage.Cam.CinePivot = new Vector3(HERO_X, Stage.FloorY - Stage.FigH * 0.55f, 0); + if ((_cineIn -= dt) <= 0 && _drawerK < 0.02f && _overlay == Overlay.None && !Modal) + { + _cineIn = 25; + _stage.Cam.Shot(new Camera.Key(0, 0, 0, 0), new Camera.Key(3, 38, -6, 900), new Camera.Key(6.5f, 0, 0, 0)); // sanfte Fahrt um den Gladiator + } _stage.Cam.Update(dt, Camera.W / 2 - 1800, Camera.W / 2 + 1800, AppSettings.ReduceMotion); // weiter weg, ruhige Drift + _crowd.Alpha = _stage.Cam.FrontAlpha; + Span pts = stackalloc Vector3[] { new(HERO_X - 80, Stage.FloorY - Stage.FigH * 1.1f, 0), new(HERO_X + 80, Stage.FloorY + 12, 0) }; + _stage.Cam.KeepInView(pts, _stage.LastScale, _stage.LastOffset, _stage.LastW, _stage.LastH, dt); _lastDt = dt; UpdateAdventure(); _crowd.Update(dt); @@ -133,6 +142,7 @@ namespace GladiatorIdle.Arena public bool DrawerOpen => _drawer != Drawer.None; float _lastDt = 1 / 60f; + float _cineIn = 12; /// Testlauf: Schublade öffnen ("none", "gladiator", "skills", "ludus", "expedition", "hall"), sofort ganz offen. public void DevOpen(string d) diff --git a/Mono/Arena/OathScene.cs b/Mono/Arena/OathScene.cs new file mode 100644 index 0000000..3f44c6f --- /dev/null +++ b/Mono/Arena/OathScene.cs @@ -0,0 +1,158 @@ +using System; +using GladiatorIdle.Gfx; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Input; +using D = GladiatorIdle.Gfx.Draw; + +namespace GladiatorIdle.Arena +{ + /// + /// Schwur nach der Erstellung: der neue Gladiator steht in einer kleinen Arena, die Kamera fährt + /// von unten langsam hoch und um ihn herum, er spricht seine Rede mit dem eigenen Namen + /// (, Untertitel je Satz). Beim letzten Satz reckt er die Waffe, + /// das Publikum ruft seinen Namen. Klick, Leertaste oder Esc überspringt. + /// + internal sealed class OathScene + { + readonly GameState _game; + readonly Stage3D _stage = new(1, AppSettings.ReduceMotion); + readonly FighterView _hero; + readonly DuelFighter _dummy = new() { IsPlayer = true, Facing = 1, MaxHp = 1, Hp = 1 }; + readonly Particles _fx = new(); + const float HERO_X = 960, WAIT = 3.4f, SILENT_LINE = 3.2f, PRELUDE = 1.8f; + float _t, _start = -1, _length, _endAt = -1; + int _shown = -1; + bool _voiced, _cheered; + float[] _times = Array.Empty(); + string[] _lines = Array.Empty(); + + public bool Done { get; private set; } + + public OathScene(GameState game) + { + _game = game; + string hero = Art.Hero(game.Class, game.Look.Preset); + _hero = Assets.Has(hero) ? new FighterView(hero, 0, game.Look.Color) : new FighterView(Art.Fighter(game.Class), 0, -1, game.Look.Color); + _fx.Calm = AppSettings.ReduceMotion; + _stage.Cam.CinePivot = new Vector3(HERO_X, Stage.FloorY - Stage.FigH * 0.6f, 0); + // Atmosphäre: schwere Trommeln und Bläser, Publikum in der Ferne; die Rede setzt nach dem Vorspiel ein + SoundManager.StopAll(); + SoundManager.PlayMusic("music_oath", loop: false); + SoundManager.PlayAmbience("amb_crowd"); + } + + /// Testläufe: Zeit der Rede setzen (Aufnahmen). + public float Time => _start < 0 ? -1 : _t - _start; + + void Begin() + { + _lines = NameVoice.OathLines; + var pcm = AppSettings.Narration ? NameVoice.Get(NameVoice.Kind.Oath) : null; + if (pcm != null && NameVoice.OathTimes.Length == _lines.Length) + { + _times = NameVoice.OathTimes; + _length = pcm.Length / 2f / 44100f; + SoundManager.PlayPcm("oath", pcm); + _voiced = true; + } + else + { + // ohne Stimme: nur Untertitel + _times = new float[_lines.Length]; + for (int i = 0; i < _times.Length; i++) _times[i] = i * SILENT_LINE; + _length = _lines.Length * SILENT_LINE; + } + _start = _t; + // Kamera: nah von unten, langsam hoch und herum, am Ende aufziehen + _stage.Cam.Shot(new Camera.Key(0, -25, -24, 1750), new Camera.Key(_length * 0.55f, 35, -13, 1450), + new Camera.Key(_length + 0.6f, 85, -6, 900), new Camera.Key(_length + 4, 110, -4, 700)); + } + + public void Update(float dt, Input input) + { + _t += dt; + if (_start < 0 && _t >= PRELUDE && (NameVoice.Get(NameVoice.Kind.Oath) != null || _t > WAIT || !NameVoice.OathAvailable)) Begin(); + float s = Time; + if (s >= 0) + { + int line = 0; + while (line < _times.Length - 1 && s >= _times[line + 1]) line++; + if (line != _shown) _shown = line; + // letzter Satz: Waffe hoch, Menge jubelt, danach ruft sie den Namen + if (_lines.Length > 0 && line == _lines.Length - 1 && _dummy.State != DuelState.Victory) _dummy.Set(DuelState.Victory); + if (!_cheered && s >= _length + 0.2f) + { + _cheered = true; + SoundManager.PlayCheer(); + NameVoice.Play(NameVoice.Kind.Chant, 1f, 0); + _endAt = _t + 4.2f; + } + } + _dummy.StateTime += dt; + _hero.Update(dt, dt, _dummy, HERO_X, AppSettings.ReduceMotion); + _stage.Cam.CinePivot = new Vector3(HERO_X, Stage.FloorY - Stage.FigH * 0.6f, 0); + _stage.Cam.Update(dt, HERO_X, HERO_X, AppSettings.ReduceMotion); + Span pts = stackalloc Vector3[] { new(HERO_X - 90, Stage.FloorY - Stage.FigH * 1.1f, 0), new(HERO_X + 90, Stage.FloorY + 12, 0) }; + _stage.Cam.KeepInView(pts, _stage.LastScale, _stage.LastOffset, _stage.LastW, _stage.LastH, dt); + _fx.Motes(AppSettings.ReduceMotion ? 0 : 50, Camera.W, Camera.H); + _fx.Update(dt); + if (_endAt > 0 && _t >= _endAt) Done = true; + if (input.LeftClick || input.Pressed(Keys.Space) || input.Pressed(Keys.Escape) || input.Pressed(Keys.Enter)) + { + if (_voiced) SoundManager.CutEffects(); // Rede weich ausblenden + Done = true; + } + } + + public void Draw(GraphicsDevice gd, SpriteBatch sb, BasicEffect fx, float scale, Vector2 offset) + { + D.UiScale = scale; + var ui = Matrix.CreateScale(scale) * Matrix.CreateTranslation(offset.X, offset.Y, 0); + _stage.Prepare(gd, scale, offset); + _stage.DrawSet(gd, sb, _t, _cheered ? 1f : 0.35f); + _stage.Shadows(gd, sb, 0, _hero); + _stage.FloorLight(sb, HERO_X, 900, 0.25f); + Stage3D.BeginFigures(gd); + _stage.Use(_hero); + _hero.DrawBody(gd, fx, _dummy, AppSettings.ReduceMotion); + + sb.Begin(SpriteSortMode.Deferred, BlendState.Additive, SamplerState.LinearClamp, null, null, null, ui); + _fx.DrawAdd(sb); + sb.End(); + sb.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, null, null, null, ui); + // Kinobalken oben und unten + float bar = Camera.H * 0.09f; + D.Rect(sb, new RectangleF(0, 0, Camera.W, bar), Color.Black); + D.Rect(sb, new RectangleF(0, Camera.H - bar, Camera.W, bar), Color.Black); + float s = Time; + if (s >= 0 && _shown >= 0 && _shown < _lines.Length && s < _length + 0.4f) + { + float since = s - _times[_shown]; + float a = MathHelper.Clamp(since / 0.35f, 0, 1); + D.Glow(sb, new Vector2(Camera.W / 2, Camera.H - 170), new Vector2(1900, 230), Color.Black * (0.55f * a)); + // mittig, bei Bedarf in zwei Zeilen (am Leerzeichen nahe der Mitte geteilt) + string text = _lines[_shown]; + var col = new Color(250, 238, 210) * a; + if (D.Measure(Assets.Serif, 38, text).X <= 1600) + D.Text(sb, Assets.Serif, 38, text, new Vector2(Camera.W / 2, Camera.H - 170), col, Align.Center); + else + { + int mid = text.Length / 2, cut = text.LastIndexOf(' ', mid); + int after = text.IndexOf(' ', mid); + if (cut < 0 || (after >= 0 && after - mid < mid - cut)) cut = after; + if (cut < 0) cut = mid; + D.Text(sb, Assets.Serif, 38, text[..cut].Trim(), new Vector2(Camera.W / 2, Camera.H - 196), col, Align.Center); + D.Text(sb, Assets.Serif, 38, text[cut..].Trim(), new Vector2(Camera.W / 2, Camera.H - 146), col, Align.Center); + } + } + if (_cheered) + { + float k = MathHelper.Clamp((s - _length - 0.2f) / 0.6f, 0, 1); + D.Text(sb, Assets.Serif, 110, _game.Name.ToUpperInvariant(), new Vector2(Camera.W / 2, Camera.H * 0.3f), D.Gold * k, Align.Center, 1 + 0.25f * (1 - k)); + } + D.Text(sb, Assets.Sans, 17, L.t("oath.skip"), new Vector2(Camera.W - 40, Camera.H - bar / 2), D.Dim, Align.Right); + sb.End(); + } + } +} diff --git a/Mono/Arena/SettingsOverlay.cs b/Mono/Arena/SettingsOverlay.cs index 847f720..8c0506c 100644 --- a/Mono/Arena/SettingsOverlay.cs +++ b/Mono/Arena/SettingsOverlay.cs @@ -62,6 +62,8 @@ namespace GladiatorIdle.Arena () => { AppSettings.Muted = !AppSettings.Muted; if (!AppSettings.Muted) SoundManager.StartAmbient(); }); y += 56; Toggle(sb, x, y, w, L.t("settings.narration"), AppSettings.Narration, () => AppSettings.Narration = !AppSettings.Narration); + y += 56; + Toggle(sb, x, y, w, L.t("settings.namecalls"), AppSettings.NameCalls, () => AppSettings.NameCalls = !AppSettings.NameCalls); // Anzeige y += 80; diff --git a/Mono/Arena/Stage3D.cs b/Mono/Arena/Stage3D.cs index 3165c34..f7152e7 100644 --- a/Mono/Arena/Stage3D.cs +++ b/Mono/Arena/Stage3D.cs @@ -22,7 +22,11 @@ namespace GladiatorIdle.Arena public Matrix Proj3 { get; private set; } readonly bool _calm; BasicEffect? _plane; - int _vw, _vh; float _scale = 1; + int _vw = 1920, _vh = 1080; float _scale = 1; + public Vector2 LastOffset { get; private set; } + public float LastScale => _scale; + public int LastW => _vw; + public int LastH => _vh; public Stage3D(int arena, bool calm) { @@ -30,6 +34,7 @@ namespace GladiatorIdle.Arena Arena = arena; Set = ArenaSet.Get(arena, Art.Arena(ArenaDef.All[Math.Clamp(arena, 0, ArenaDef.All.Length - 1)]), calm); Cam.Center = new Vector2(Camera.W / 2, Camera.H / 2 + 40); + Cam.Ring = ArenaSet.Ring; } /// Andere Arena (Aufstieg): Kulisse neu bauen. @@ -43,11 +48,12 @@ namespace GladiatorIdle.Arena /// Matrizen für dieses Bild. public void Prepare(GraphicsDevice gd, float scale, Vector2 offset) { - _vw = gd.Viewport.Width; _vh = gd.Viewport.Height; _scale = scale; + _vw = gd.Viewport.Width; _vh = gd.Viewport.Height; _scale = scale; LastOffset = offset; View3 = Cam.View3(); Proj3 = Cam.Proj3(scale, offset, _vw, _vh); _plane ??= new BasicEffect(gd) { TextureEnabled = true, VertexColorEnabled = true, LightingEnabled = false }; _plane.World = Matrix.Identity; _plane.View = View3; _plane.Projection = Proj3; + _plane.Alpha = Cam.PlaneAlpha; // 2D-Effekte der Kampfebene nicht von der Kante zeigen } /// Kulisse (Tiefe und Stencil frisch), Feuer als Licht. diff --git a/Mono/ArenaGame.cs b/Mono/ArenaGame.cs index cddd6ac..29b2b03 100644 --- a/Mono/ArenaGame.cs +++ b/Mono/ArenaGame.cs @@ -29,6 +29,7 @@ namespace GladiatorIdle DuelScene? _scene; ModelTestScene? _model; // --model3d: 3D-Test FreedomScene? _freedom; // Freiheit: Clip, Bilanz, Götter + OathScene? _oath; // Schwur des neuen Gladiators nach der Erstellung OfflineReport? _welcome; // was offline passiert ist (beim Weiterspielen gezeigt) LeaderboardScene? _board; // Bestenliste (aus dem Menü) bool _nextLife; // nächste Erstellung behält das Profil (Legenden, Götter) @@ -38,6 +39,7 @@ namespace GladiatorIdle static readonly bool DevAdventureRun = Array.IndexOf(Environment.GetCommandLineArgs(), "--adventure") >= 0; static readonly bool DevBoardRun = Array.IndexOf(Environment.GetCommandLineArgs(), "--leaderboard") >= 0; static readonly bool DevTutorialRun = Array.IndexOf(Environment.GetCommandLineArgs(), "--tutorial") >= 0; + static readonly bool DevOathRun = Array.IndexOf(Environment.GetCommandLineArgs(), "--oath") >= 0; static readonly bool Model3DTest = Array.IndexOf(Environment.GetCommandLineArgs(), "--model3d") >= 0; SettingsOverlay _settings = null!; bool _paused; @@ -143,9 +145,21 @@ namespace GladiatorIdle // eigener Spielstand fürs neue Spiel; vorhandenen laden und Abwesenheit nachrechnen GameState.SaveFile = "arena.json"; if (Model3DTest) { _model = new ModelTestScene(GraphicsDevice); return; } + var nvArgs = Environment.GetCommandLineArgs(); + int nv = Array.IndexOf(nvArgs, "--namevoice"); + if (nv >= 0 && nv + 1 < nvArgs.Length) + { + NameVoice.Prepare(nvArgs[nv + 1]); + System.Threading.Tasks.Task.Run(() => + { + for (int i = 0; i < 300 && NameVoice.Get(NameVoice.Kind.Chant) == null; i++) System.Threading.Thread.Sleep(100); + Exit(); + }); + } if (!DevShot.Active && GameState.Load(out var savedUtc) is GameState loaded) { _game = loaded; + NameVoice.Prepare(_game.Name); // Ansager und Sprechchor im Hintergrund vorbereiten var away = _game.ApplyOffline((DateTime.UtcNow - savedUtc).TotalSeconds); if (away.Seconds >= 120) _welcome = away; // im Hub als erstes Fenster ToMenu(); @@ -156,7 +170,7 @@ namespace GladiatorIdle void ToMenu() { - _hub = null; _scene = null; _creator = null; _intro = null; _freedom = null; _board = null; _paused = false; _nextLife = false; + _hub = null; _scene = null; _creator = null; _intro = null; _freedom = null; _board = null; _oath = null; _paused = false; _nextLife = false; _menu = new MenuScene(_game != null, _game?.Freedoms ?? 0); SoundManager.StopAmbience(); } @@ -188,9 +202,17 @@ namespace GladiatorIdle int da = Array.IndexOf(cmd, "--duelarena"); if (da >= 0 && da + 1 < cmd.Length && int.TryParse(cmd[da + 1], out int arenaN)) _game.DevArena(arenaN); _game.Save(); + NameVoice.Prepare(_game.Name); _creator = null; + // Schwur des neuen Gladiators (in Testläufen nur mit --oath) + if (!DevShot.Active || DevOathRun) { _oath = new OathScene(_game); _devTime = 0; return; } + OpenHub(); + } + + void OpenHub() + { var sw = Stopwatch.StartNew(); - _hub = new HubScene(_game); + _hub = new HubScene(_game!); DevShot.Log($"timing: hub created in {sw.ElapsedMilliseconds} ms"); } @@ -292,6 +314,7 @@ namespace GladiatorIdle } readonly Stopwatch _updWatch = new(); + double _lastUpd, _lastDraw; double _updMs; Matrix UiMatrix(out float s, out Vector2 off) @@ -333,6 +356,16 @@ namespace GladiatorIdle if (DevShot.Active) DevBoard(dt); if (_board != null && _board.Done) ToMenu(); } + else if (_oath != null) + { + _oath.Update(dt, input); + if (DevShot.Active) + { + _devTime += dt; + for (int i = 0; i < 18; i++) if (_oath.Time > 0.3f + i * 1.5f && _shots.Add($"o_{i:00}")) { _capture = $"o_{i:00}"; break; } + } + if (_oath.Done) { _oath = null; OpenHub(); if (DevOathRun) Exit(); } + } else if (_freedom != null) { _freedom.Update(dt, input, ui); @@ -407,6 +440,7 @@ namespace GladiatorIdle } base.Update(gameTime); _updMs += _updWatch.Elapsed.TotalMilliseconds; + _lastUpd = _updWatch.Elapsed.TotalMilliseconds; } /// Pause-Menü in der Arena: Weiter / Einstellungen / Hauptmenü / Beenden. @@ -618,6 +652,14 @@ namespace GladiatorIdle if (Perf) { PerfStep(); return; } void Shot(string name) { if (_shots.Add(name)) _capture = name; } if (_scene.InIntro) { if (_devTime > 2.5) Shot("m_champintro"); return; } + if (CineRun) + { + // Bildserien der Kinofahrten: Countdown, Raserei, K.o./Missio + for (int i = 0; i < 12; i++) if (_devTime > 0.15 + i * 0.28) Shot($"cine_a_{i:00}"); + if (d.Player.State == DuelState.Super) for (int i = 0; i < 5; i++) if (d.Player.StateTime > 0.1 + i * 0.25) Shot($"cine_b_{i}"); + if (_scene.Over && !_shots.Contains("cine_c_ko")) Shot("cine_c_ko"); + for (int i = 0; i < 12; i++) if (_scene.MissioTime > 0.4 + i * 0.7) Shot($"cine_d_{i:00}"); + } if (_scene.Tutorial != DuelScene.TutStep.Off) { Shot("t_" + _scene.Tutorial.ToString().ToLowerInvariant()); } if (_devTime > 0.5) Shot("m_countdown"); if (d.Time > 0.6) Shot("m_fight"); @@ -649,6 +691,7 @@ namespace GladiatorIdle /// --perf: 15 s Kampf ohne Aufnahmen, Bildzeiten messen (Mittel, 95. Perzentil). static readonly bool Perf = Array.IndexOf(Environment.GetCommandLineArgs(), "--perf") >= 0; static readonly bool Record = Array.IndexOf(Environment.GetCommandLineArgs(), "--record") >= 0; + static readonly bool CineRun = Array.IndexOf(Environment.GetCommandLineArgs(), "--cine") >= 0; readonly System.Collections.Generic.List _times = new(); int _gcStart = -1, _duelsStarted; @@ -658,6 +701,7 @@ namespace GladiatorIdle { if (_gcStart < 0) { _gcStart = GC.CollectionCount(0); _duelDraw = 0; _duelFrames = 0; } _times.Add(_lastFrameMs); + if (_lastFrameMs > 30) DevShot.Log($"perf spike {_lastFrameMs:0} ms (upd {_lastUpd:0.0}, draw {_lastDraw:0.0}, gc {GC.CollectionCount(0)}/{GC.CollectionCount(1)}/{GC.CollectionCount(2)}) at {_devTime:0.00}s duel t={_scene!.Duel.Time:0.00} over={_scene.Over} phase-missio={_scene.MissioTime:0.00}"); } // nach jedem Kampf sofort ein neuer: misst auch den Ruckler beim Duellstart if (_scene!.Over) { var o = _offer!; EndDuel(); StartDuel(o); _duelsStarted++; } @@ -698,6 +742,7 @@ namespace GladiatorIdle Gfx.Draw.UiScale = scale; if (_model != null) _model.Draw(gd, _sb, scale, offset); else if (_freedom != null) _freedom.Draw(gd, _sb, _fx, scale, offset); + else if (_oath != null) _oath.Draw(gd, _sb, _fx, scale, offset); else if (_board != null) _board.Draw(_sb, scale, offset); else if (_intro != null) _intro.Draw(_sb, scale, offset); else if (_menu != null) _menu.Draw(_sb, scale, offset); @@ -709,7 +754,7 @@ namespace GladiatorIdle if (_paused && !_settings.Open) DrawPause(_sb, ui); } // weicher Wechsel zwischen Bildschirmen: neues Bild kommt kurz aus dem Schwarz - object? now = (object?)_model ?? _freedom ?? (object?)_board ?? _intro ?? (object?)_menu ?? _creator ?? (object?)_scene ?? _hub; + object? now = (object?)_model ?? _freedom ?? (object?)_oath ?? (object?)_board ?? _intro ?? (object?)_menu ?? _creator ?? (object?)_scene ?? _hub; if (!ReferenceEquals(now, _shown)) { _shown = now; _fadeIn = 0; } _fadeIn = Math.Min(1, _fadeIn + gameTime.ElapsedGameTime.TotalSeconds / 0.3); if (_fadeIn < 1) @@ -736,6 +781,7 @@ namespace GladiatorIdle _sb.End(); } _drawMs += _drawWatch.Elapsed.TotalMilliseconds; _frames++; + _lastDraw = _drawWatch.Elapsed.TotalMilliseconds; if (capturing) { } // Bilder mit Aufnahme (PNG speichern) nicht mitzählen else if (_scene != null) { _duelDraw += _drawWatch.Elapsed.TotalMilliseconds; _duelFrames++; } else if (_hub != null) { _hubDraw += _drawWatch.Elapsed.TotalMilliseconds; _hubFrames++; } diff --git a/Mono/Gfx/Model3D.cs b/Mono/Gfx/Model3D.cs index dc30594..685e505 100644 --- a/Mono/Gfx/Model3D.cs +++ b/Mono/Gfx/Model3D.cs @@ -176,6 +176,7 @@ namespace GladiatorIdle.Gfx for (int k = 0; k < clip.Data.Length; k++) clip.Data[k] = r.ReadSingle(); Clips.Add(clip); } + NormalizeRoots(Path.GetFileNameWithoutExtension(path)); if (v2 && r.ReadInt32() is int texLen && texLen > 0) { // PNG ohne Grafikkarte entpacken (auch im Hintergrund), Stufen gegen Flimmern klein/weit weg @@ -205,6 +206,36 @@ namespace GladiatorIdle.Gfx public Clip? Find(string name) => Clips.Find(c => c.Name == name); + /// Bewegungen, die mit einer anderen Figur geladen wurden, haben die Hüfte (Wurzel-Knochen) in + /// anderer Höhe oder anderem Maßstab – die Figur schwebt oder versinkt. Je Clip die Wurzel-Bewegung + /// gemeinsam skalieren, sodass ihre Höhe zu den übrigen Clips der Figur passt. + void NormalizeRoots(string name) + { + int nb = _names.Length; + for (int bone = 0; bone < nb; bone++) + { + if (_parent[bone] >= 0 || Clips.Count < 3) continue; + // Bezug: Mittelwert der Hüfthöhe im ersten Bild über alle Clips (die meisten passen zusammen) + var ys = Clips.Select(c => MathF.Abs(c.Data[bone * 10 + 1])).Where(y => y > 1e-4f).OrderBy(y => y).ToArray(); + if (ys.Length == 0) continue; + float median = ys[ys.Length / 2]; + // Ausreißer (Faktor > 2): gemeinsamen Faktor nehmen, damit echte Unterschiede (Ducken) bleiben + var odd = Clips.Where(c => { float y = MathF.Abs(c.Data[bone * 10 + 1]); return y > 1e-4f && (y > median * 2 || y < median / 2); }).ToList(); + if (odd.Count == 0) continue; + var ratios = odd.Select(c => median / MathF.Abs(c.Data[bone * 10 + 1])).OrderBy(k => k).ToArray(); + float k = ratios[ratios.Length / 2]; + foreach (var clip in odd) + { + for (int f = 0; f < clip.Frames; f++) + { + int o = (f * nb + bone) * 10; + clip.Data[o] *= k; clip.Data[o + 1] *= k; clip.Data[o + 2] *= k; + } + if (DevShot.Active) DevShot.Log($"root {name}/{clip.Name}: hips scaled x{k:0.###} (median {median:0.###})"); + } + } + } + /// Teamfarbe (Index in Appearance.Colors), -1 = Originalfarben. /// Hautton dunkler (0 = unverändert, 1 = dunkle Haut, −1 = helle, blasse Haut): für Aussehen-Vorlagen mit dunkler Haut, solange /// sie das Modell einer anderen Vorlage nutzen. Haut erkannt an Farbton (Orange/Rosa), mittlerer diff --git a/Mono/Gfx/PostFx.cs b/Mono/Gfx/PostFx.cs index a1366fb..ca471b0 100644 --- a/Mono/Gfx/PostFx.cs +++ b/Mono/Gfx/PostFx.cs @@ -22,8 +22,8 @@ namespace GladiatorIdle.Gfx AlphaBlendFunction = BlendFunction.Add, AlphaSourceBlend = Blend.Zero, AlphaDestinationBlend = Blend.One, }; - static RenderTarget2D Make(GraphicsDevice gd, int w, int h, int msaa, DepthFormat depth) => - new(gd, Math.Max(1, w), Math.Max(1, h), false, SurfaceFormat.Color, depth, msaa, RenderTargetUsage.PreserveContents); + static RenderTarget2D Make(GraphicsDevice gd, int w, int h, int msaa, DepthFormat depth, RenderTargetUsage use) => + new(gd, Math.Max(1, w), Math.Max(1, h), false, SurfaceFormat.Color, depth, msaa, use); /// Zeichnen in die Zwischenfläche beginnen (Größe wie der Bildschirm). public void Begin(GraphicsDevice gd, int w, int h, bool antiAlias) @@ -32,10 +32,11 @@ namespace GladiatorIdle.Gfx if (_scene == null || _scene.Width != w || _scene.Height != h || _msaa != msaa) { _scene?.Dispose(); _a?.Dispose(); _b?.Dispose(); _c?.Dispose(); - _scene = Make(gd, w, h, msaa, DepthFormat.Depth24Stencil8); - _a = Make(gd, w / 4, h / 4, 0, DepthFormat.None); - _b = Make(gd, w / 8, h / 8, 0, DepthFormat.None); - _c = Make(gd, w / 16, h / 16, 0, DepthFormat.None); + // die Szene behält ihren Inhalt (Zielwechsel während des Zeichnens), die Stufen nicht + _scene = Make(gd, w, h, msaa, DepthFormat.Depth24Stencil8, RenderTargetUsage.PreserveContents); + _a = Make(gd, w / 4, h / 4, 0, DepthFormat.None, RenderTargetUsage.DiscardContents); + _b = Make(gd, w / 8, h / 8, 0, DepthFormat.None, RenderTargetUsage.DiscardContents); + _c = Make(gd, w / 16, h / 16, 0, DepthFormat.None, RenderTargetUsage.DiscardContents); _msaa = msaa; } gd.SetRenderTarget(_scene); @@ -48,9 +49,13 @@ namespace GladiatorIdle.Gfx if (bloom > 0) { // ¼: verkleinern, dann Schwelle abziehen (nur Helles bleibt) - Blit(gd, sb, _scene, _a!, BlendState.Opaque, Color.White); - sb.Begin(SpriteSortMode.Immediate, Subtract); - sb.Draw(Assets.Pixel, new Rectangle(0, 0, _a!.Width, _a.Height), new Color(threshold, threshold, threshold, 0f)); + // ¼ und Schwelle in einem Durchgang (ein Zielwechsel) + gd.SetRenderTarget(_a); + sb.Begin(SpriteSortMode.Deferred, BlendState.Opaque, SamplerState.LinearClamp); + sb.Draw(_scene, new Rectangle(0, 0, _a!.Width, _a.Height), Color.White); + sb.End(); + sb.Begin(SpriteSortMode.Deferred, Subtract); + sb.Draw(Assets.Pixel, new Rectangle(0, 0, _a.Width, _a.Height), new Color(threshold, threshold, threshold, 0f)); sb.End(); // ⅛ und 1/16: weiter verkleinern = weicher Blit(gd, sb, _a, _b!, BlendState.Opaque, Color.White); @@ -58,7 +63,7 @@ namespace GladiatorIdle.Gfx } gd.SetRenderTarget(output); int w = output?.Width ?? gd.PresentationParameters.BackBufferWidth, h = output?.Height ?? gd.PresentationParameters.BackBufferHeight; - sb.Begin(SpriteSortMode.Immediate, BlendState.Opaque, SamplerState.PointClamp); + sb.Begin(SpriteSortMode.Deferred, BlendState.Opaque, SamplerState.PointClamp); sb.Draw(_scene, new Rectangle(0, 0, w, h), Color.White); sb.End(); if (bloom > 0) @@ -75,8 +80,7 @@ namespace GladiatorIdle.Gfx static void Blit(GraphicsDevice gd, SpriteBatch sb, Texture2D from, RenderTarget2D to, BlendState blend, Color c) { gd.SetRenderTarget(to); - gd.Clear(Color.Black); - sb.Begin(SpriteSortMode.Immediate, blend, SamplerState.LinearClamp); + sb.Begin(SpriteSortMode.Deferred, blend, SamplerState.LinearClamp); sb.Draw(from, new Rectangle(0, 0, to.Width, to.Height), c); sb.End(); } diff --git a/Mono/GladiatorMono.csproj b/Mono/GladiatorMono.csproj index 9e3437c..fc5bcab 100644 --- a/Mono/GladiatorMono.csproj +++ b/Mono/GladiatorMono.csproj @@ -16,7 +16,7 @@ - + @@ -27,6 +27,7 @@ + diff --git a/README.md b/README.md index 2ac4cc1..1c89681 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Von Michael Media. Idee, Technik und Regeln: `CLAUDE.md`. | `Game/` | Spiellogik (Gladiator, Duell, Ausrüstung, Fähigkeiten, Balance) | | `Core/` | Ton, Sprache, Einstellungen, Testläufe (DevShot), Credits | | `Languages/` | Texte en/de/es | -| `Assets/` | `Sprites` (Bilder), `Video` (Clips), `Models` (3D-Figuren `.gim`), `Audio` | +| `Assets/` | `Sprites` (Bilder), `Video` (Clips), `Models` (3D-Figuren `.gim`), `Audio`, `Voices` (Stimmen für Ansager und Sprechchor mit dem Namen des Spielers – nicht in git, laden mit `py -3.12 tools/get_voices.py`) | | `Spritegenerator/` | Daten und Skripte für Bilder, Clips, Ton und 3D-Figuren (Werkzeuge in `_Tools`) | | `docs/`, `tools/` | Plan, Übersetzungsprüfung | | `_Archiv/` | Altes, nicht mehr genutzt (siehe `_Archiv/README.md`) | diff --git a/build-release.bat b/build-release.bat index c293604..9be1d6f 100644 --- a/build-release.bat +++ b/build-release.bat @@ -37,6 +37,8 @@ copy /y "publish\*.dll" "publish\zip\" >nul robocopy "Assets\Sprites" "publish\zip\Assets\Sprites" /e /njh /njs /ndl /nfl /nc /ns /xf .gitkeep >nul robocopy "Assets\Video" "publish\zip\Assets\Video" /e /njh /njs /ndl /nfl /nc /ns /xf .gitkeep >nul robocopy "Assets\Models" "publish\zip\Assets\Models" /e /njh /njs /ndl /nfl /nc /ns /xf .gitkeep >nul +rem Stimmen fuer Ansager/Sprechchor (tools\get_voices.py) +robocopy "Assets\Voices" "publish\zip\Assets\Voices" /e /njh /njs /ndl /nfl /nc /ns >nul powershell -NoProfile -Command "Compress-Archive -Path 'publish\zip\*' -DestinationPath 'Spiel\GladiatorIdle.zip' -Force" rem Zwischenstand des Bauens wieder weg (entsteht jedes Mal neu) rmdir /s /q "publish" diff --git a/tools/get_voices.py b/tools/get_voices.py new file mode 100644 index 0000000..a7d6bb5 --- /dev/null +++ b/tools/get_voices.py @@ -0,0 +1,51 @@ +"""Stimmen für den Ansager/Sprechchor (Namen des Spielers) herunterladen. + +Piper-Stimmen (VITS) im Format von sherpa-onnx, offline im Spiel genutzt (Core/NameVoice.cs). +Ziel: Assets/Voices// (model.onnx, tokens.txt, espeak-ng-data/) – nicht in git. + + py -3.12 tools/get_voices.py fehlende Stimmen laden + py -3.12 tools/get_voices.py --force alle neu +""" +import os +import shutil +import sys +import tarfile +import tempfile +import urllib.request + +BASE = "https://github.com/k2-fsa/sherpa-onnx/releases/download/tts-models/" +# (Archiv, Sprecher-Nummer): Deutsch mit Gefühlslagen – 1 = wütend, klingt am ehesten nach Arena +VOICES = { + "de": ("vits-piper-de_DE-thorsten_emotional-medium", 1), + "en": ("vits-piper-en_US-ryan-high", 0), + "es": ("vits-piper-es_ES-miro-high", 0), +} +DEST = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "Assets", "Voices") + + +def fetch(lang, name, sid, force): + out = os.path.join(DEST, lang) + have = os.path.join(out, "voice.txt") + if os.path.exists(have) and open(have).readline().strip() == name and not force: + print(f"{lang}: vorhanden"); return + with tempfile.TemporaryDirectory() as tmp: + archive = os.path.join(tmp, name + ".tar.bz2") + print(f"{lang}: lade {name} …", flush=True) + urllib.request.urlretrieve(BASE + name + ".tar.bz2", archive) + with tarfile.open(archive, "r:bz2") as t: + t.extractall(tmp, filter="data") + src = os.path.join(tmp, name) + if os.path.exists(out): shutil.rmtree(out) + os.makedirs(out) + onnx = [f for f in os.listdir(src) if f.endswith(".onnx")][0] + shutil.copy(os.path.join(src, onnx), os.path.join(out, "model.onnx")) + shutil.copy(os.path.join(src, "tokens.txt"), os.path.join(out, "tokens.txt")) + shutil.copytree(os.path.join(src, "espeak-ng-data"), os.path.join(out, "espeak-ng-data")) + open(os.path.join(out, "voice.txt"), "w").write(f"{name}\nsid={sid}\n") + size = sum(os.path.getsize(os.path.join(d, f)) for d, _, fs in os.walk(out) for f in fs) + print(f"{lang}: fertig ({size / 1e6:.0f} MB)") + + +if __name__ == "__main__": + for lang, (name, sid) in VOICES.items(): + fetch(lang, name, sid, "--force" in sys.argv) diff --git a/tools/make_oath_voice.py b/tools/make_oath_voice.py new file mode 100644 index 0000000..1cdef49 --- /dev/null +++ b/tools/make_oath_voice.py @@ -0,0 +1,165 @@ +"""Die Rede nach der Erstellung mit der Kriegerstimme vorab sprechen (Chatterbox, Referenz +_Tools/ComfyGen/voice_refs/warrior.wav), jeden Satz mit Whisper geprüft (bester Versuch gewinnt). + +Ziel: Assets/Voices/oath// + line1.wav … line5.wav Sätze ohne Namen (Text aus Languages/.json, "oath.text") + names/.wav erster Satz „Mein Name ist X.“ für häufige Namen (NAMES) + prefix.wav „Mein Name ist“ allein – für Namen ohne eigene Aufnahme +Das Spiel (Core/NameVoice.cs) setzt daraus die Rede zusammen; Hall und Mischung macht es selbst. + + _Tools\\ComfyGen\\.venv-tts\\Scripts\\python.exe tools/make_oath_voice.py fehlende erzeugen + … make_oath_voice.py --force alles neu + … make_oath_voice.py --lang de --names 0 nur Deutsch, keine Namen +""" +import argparse, difflib, json, os, re, unicodedata +import numpy as np +import soundfile as sf +import torch +import torchaudio as ta + +ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +REF = os.path.join(ROOT, "..", "_Tools", "ComfyGen", "voice_refs", "warrior.wav") +DEST = os.path.join(ROOT, "Assets", "Voices", "oath") + +# Häufige Namen für Gladiatoren: römisch/legendär und gängige Vornamen (de/en/es) +# Die ersten zuerst (mit --names N nur die häufigsten) +TOP = "Spartacus Maximus Marcus Lucius Crixus Michael Alex Max Thomas Daniel David Lukas Leon Paul Peter John James Chris Mike Carlos Juan Pablo Diego Jose Luis Hector Achilles Leonidas Titus Brutus".split() +NAMES = """Spartacus Maximus Crixus Flamma Priscus Verus Carpophorus Commodus Marcus Lucius Gaius Titus Quintus +Decimus Tiberius Julius Brutus Cassius Severus Aurelius Octavius Felix Atticus Cato Nero Hector Achilles Ajax +Leonidas Ares Mars Thor Odin Ragnar Conan Arthur Attila Hannibal Varus Magnus Rufus Drusus Gallus +Michael Michi Max Alex Alexander Paul Peter Thomas Daniel David Jan Lukas Leon Finn Jonas Tim Tom Ben Noah +Elias Luca Kevin Dennis Marco Sven Stefan Markus Florian Tobias Simon Sebastian Christian Andreas Martin +Patrick Robert Kai Nico Erik Viktor Ivan Igor Oliver Liam Ethan Lucas Mateo Adrian Hugo Mario Leo John James +Jack Ryan Chris Mike Steve Sam Carlos Juan Pedro Diego Pablo Javier Miguel Antonio Jose Luis Sergio Raul +Alejandro Manuel Fernando Rafael""".split() +NAMES = TOP + [n for n in NAMES if n not in TOP] + +WHISPER_LANG = {"de": "de", "en": "en", "es": "es"} + + +def key(name): + """Dateiname wie im Spiel (NameVoice.OathKey): klein, ohne Akzente, nur a–z.""" + s = unicodedata.normalize("NFD", name.lower()) + return "".join(c for c in s if "a" <= c <= "z") + + +def norm(t): + s = unicodedata.normalize("NFD", t.lower()) + s = "".join(c for c in s if not unicodedata.combining(c)) + return " ".join(re.sub(r"[^a-zß ]", " ", s).split()) + + +def lines_of(lang): + with open(os.path.join(ROOT, "Languages", lang + ".json"), encoding="utf-8") as f: + return [p.strip() for p in json.load(f)["oath.text"].split("|") if p.strip()] + + +class Voice: + def __init__(self): + from chatterbox.mtl_tts import ChatterboxMultilingualTTS + from faster_whisper import WhisperModel + self.tts = ChatterboxMultilingualTTS.from_pretrained(device="cuda" if torch.cuda.is_available() else "cpu") + self.whisper = WhisperModel("small", device="cpu", compute_type="int8") + self.sr = self.tts.sr + + def hear(self, wav, lang, words=False): + pcm = ta.functional.resample(torch.from_numpy(wav)[None], self.sr, 16000)[0].numpy().astype("float32") + segs, _ = self.whisper.transcribe(pcm, language=WHISPER_LANG[lang], beam_size=5, word_timestamps=words) + segs = list(segs) + return " ".join(s.text for s in segs), [w for s in segs for w in (s.words or [])] + + def say(self, text, lang, tries=4, seed=21): + """Bester von mehreren Versuchen (Whisper-Ähnlichkeit, zu lang = Gebrabbel).""" + best = (-9.0, None, "") + for attempt in range(tries): + torch.manual_seed(seed + attempt) + wav = self.tts.generate(text, language_id=lang, audio_prompt_path=REF, + exaggeration=0.95, temperature=0.8, cfg_weight=0.0)[0].cpu().numpy() + wav = trim(wav) + heard, _ = self.hear(wav, lang) + score = difflib.SequenceMatcher(None, norm(text), norm(heard)).ratio() + if len(wav) / self.sr > len(text) / 7 + 2: score -= 0.4 + if score > best[0]: best = (score, wav, heard) + if score > 0.95: break + return best + + +def trim(a, thr=0.01): + nz = np.where(np.abs(a) > thr)[0] + if len(nz) == 0: return a + a = a[max(0, nz[0] - 240):nz[-1] + 1200] + return a + + +def save(path, a, sr): + os.makedirs(os.path.dirname(path), exist_ok=True) + a = a / (np.abs(a).max() + 1e-6) * 0.9 + sf.write(path, a.astype(np.float32), sr, subtype="PCM_16") + + +def cut_after_name(v, wav, lang, n_prefix): + """Gebrabbel nach dem Namen abschneiden (Ende des Namenworts laut Whisper + kurzer Ausklang).""" + _, words = v.hear(wav, lang, words=True) + if len(words) > n_prefix + 1: + end = min(len(wav), int((words[n_prefix].end + 0.18) * v.sr)) + wav = wav[:end] + return wav + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--lang", default="de,en,es") + ap.add_argument("--names", type=int, default=len(NAMES), help="wie viele Namen (0 = keine)") + ap.add_argument("--tries", type=int, default=3, help="Versuche je Name") + ap.add_argument("--force", action="store_true") + ap.add_argument("--fix", default="", help="vorhandene Namen nachträglich kürzen: lang:Name,lang:Name") + args = ap.parse_args() + v = Voice() + if args.fix == "all": # alle vorhandenen Namen + args.fix = ",".join(f"{l}:{f[:-4]}" for l in args.lang.split(",") + for f in sorted(os.listdir(os.path.join(DEST, l, "names")))) + for item in filter(None, args.fix.split(",")): + lang, name = item.split(":") + p = os.path.join(DEST, lang, "names", key(name) + ".wav") + wav, sr = sf.read(p, dtype="float32") + before = len(wav) + wav = cut_after_name(v, wav, lang, len(lines_of(lang)[0].split("{0}")[0].split())) + if len(wav) < before: + save(p, wav, sr) + print(f"fixed {item}: {before / sr:.2f}s -> {len(wav) / sr:.2f}s", flush=True) + if args.fix: return + for lang in args.lang.split(","): + out = os.path.join(DEST, lang) + lines = lines_of(lang) + # Sätze 2…6 (ohne Namen) + for i, text in enumerate(lines[1:], 1): + p = os.path.join(out, f"line{i}.wav") + if os.path.exists(p) and not args.force: continue + score, wav, heard = v.say(text, lang) + save(p, wav, v.sr) + print(f"{lang} line{i}: {score:.2f} '{heard.strip()}'", flush=True) + # „Mein Name ist“ allein: aus einem ganzen Satz an der Wortgrenze vor dem Namen geschnitten + p = os.path.join(out, "prefix.wav") + if not os.path.exists(p) or args.force: + n_prefix = len(lines[0].split("{0}")[0].split()) + for seed in range(31, 41): + score, wav, _ = v.say(lines[0].replace("{0}", "Spartacus"), lang, tries=1, seed=seed) + _, words = v.hear(wav, lang, words=True) + if score > 0.85 and len(words) > n_prefix: + cut = (words[n_prefix - 1].end + words[n_prefix].start) / 2 + save(p, wav[:int(cut * v.sr)], v.sr) + print(f"{lang} prefix: {score:.2f} cut {cut:.2f}s", flush=True) + break + # erster Satz mit Namen + for name in NAMES[:args.names]: + p = os.path.join(out, "names", key(name) + ".wav") + if os.path.exists(p) and not args.force: continue + score, wav, heard = v.say(lines[0].replace("{0}", name), lang, tries=args.tries) + wav = cut_after_name(v, wav, lang, len(lines[0].split("{0}")[0].split())) + save(p, wav, v.sr) + print(f"{lang} {name}: {score:.2f} '{heard.strip()}'", flush=True) + print("done") + + +if __name__ == "__main__": + main()