Gladiator Idle (MonoGame) – Spiel mit 3D-Gladiatoren
Nur was zum Bauen und Starten nötig ist: Mono/ (Spiel), Game/, Core/, Languages/, Assets/ (Bilder, Clips, 3D-Figuren, Ton), build-release.bat. Bauen: build-release.bat → Spiel\GladiatorIdle.exe Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
129
Core/AppSettings.cs
Normal file
129
Core/AppSettings.cs
Normal file
@@ -0,0 +1,129 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
|
||||
namespace GladiatorIdle
|
||||
{
|
||||
/// <summary>
|
||||
/// Dauerhafte Spieler-Einstellungen (%AppData%\GladiatorIdle\settings.txt, key=value).
|
||||
/// </summary>
|
||||
internal static class AppSettings
|
||||
{
|
||||
/// Stufen der Lautstärke-Knöpfe (Einstellungen)
|
||||
public static readonly int[] VolumeSteps = { 0, 25, 50, 75, 100 };
|
||||
|
||||
/// Gespeicherte Lautstärke (und Stummschaltung) an den SoundManager geben.
|
||||
public static void ApplyVolumes()
|
||||
{
|
||||
SoundManager.MusicLevel = MusicVolume / 100f;
|
||||
SoundManager.SfxLevel = SfxVolume / 100f;
|
||||
SoundManager.VoiceLevel = VoiceVolume / 100f;
|
||||
// Testläufe bleiben stumm (Program schaltet den Ton dort ab)
|
||||
if (!DevShot.Active && SoundManager.Enabled == Muted) SoundManager.Enabled = !Muted;
|
||||
}
|
||||
|
||||
public static bool Fullscreen { get; set; } = true;
|
||||
|
||||
/// Lautstärke in Prozent (0–100): Musik, Soundeffekte und Erzählstimme getrennt.
|
||||
public static int MusicVolume { get; set; } = 100;
|
||||
public static int SfxVolume { get; set; } = 100;
|
||||
public static int VoiceVolume { get; set; } = 100;
|
||||
|
||||
/// Aller Ton aus (Taste M / Schalter in den Einstellungen); bleibt über Neustarts.
|
||||
public static bool Muted { get; set; }
|
||||
|
||||
/// Textgröße im Spiel: 1 = 100 %, 2 = 115 %, 3 = 130 %.
|
||||
public static int TextScale { get; set; } = 1;
|
||||
|
||||
/// Weniger Bewegung: keine Partikel, schwebenden Zahlen, Kamera-Ruck, Kampf-Clips.
|
||||
public static bool ReduceMotion { get; set; }
|
||||
|
||||
/// Tipps im Spiel (Sprechblasen bei neuen Bereichen).
|
||||
public static bool Hints { get; set; } = true;
|
||||
|
||||
/// Film-Zwischenszene beim Aufstieg in eine neue Arena (Kapitel).
|
||||
public static bool ChapterScenes { get; set; } = true;
|
||||
|
||||
/// Champion-Kämpfe automatisch austragen statt selbst in Echtzeit.
|
||||
public static bool AutoChampion { get; set; }
|
||||
|
||||
/// Erzählstimme (liest Intro und Kapitel vor).
|
||||
public static bool Narration { get; set; } = true;
|
||||
|
||||
/// Tipps, die schon gezeigt wurden (jeder kommt nur einmal).
|
||||
public static HashSet<string> HintsSeen { get; } = new();
|
||||
|
||||
static string FilePath => Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"GladiatorIdle", "settings.txt");
|
||||
|
||||
public static void Load()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(FilePath)) return;
|
||||
foreach (string line in File.ReadAllLines(FilePath))
|
||||
{
|
||||
var parts = line.Split('=', 2);
|
||||
if (parts.Length != 2) continue;
|
||||
string key = parts[0].Trim(), val = parts[1].Trim();
|
||||
switch (key)
|
||||
{
|
||||
case "fullscreen": Fullscreen = val == "1"; break;
|
||||
case "hints": Hints = val == "1"; break;
|
||||
case "narration": Narration = val == "1"; break;
|
||||
case "chapterscenes": ChapterScenes = val == "1"; break;
|
||||
case "autochampion": AutoChampion = val == "1"; break;
|
||||
case "musicvol": if (int.TryParse(val, out int mv)) MusicVolume = Math.Clamp(mv, 0, 100); break;
|
||||
case "sfxvol": if (int.TryParse(val, out int sv)) SfxVolume = Math.Clamp(sv, 0, 100); break;
|
||||
case "voicevol": if (int.TryParse(val, out int vv)) VoiceVolume = Math.Clamp(vv, 0, 100); break;
|
||||
case "muted": Muted = val == "1"; break;
|
||||
case "reducemotion": ReduceMotion = val == "1"; break;
|
||||
case "textscale": if (int.TryParse(val, out int ts)) TextScale = Math.Clamp(ts, 1, 3); break;
|
||||
case "hintsseen":
|
||||
foreach (var id in val.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
HintsSeen.Add(id);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { /* kaputte Datei → Standardwerte */ }
|
||||
Narration = VoiceVolume > 0;
|
||||
}
|
||||
|
||||
public static void Save()
|
||||
{
|
||||
// Testläufe (--shot/--playtest) dürfen die Einstellungen des Spielers nie ändern
|
||||
if (DevShot.Active) return;
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!);
|
||||
File.WriteAllText(FilePath,
|
||||
$"fullscreen={(Fullscreen ? 1 : 0)}\n" +
|
||||
$"hints={(Hints ? 1 : 0)}\n" +
|
||||
$"narration={(Narration ? 1 : 0)}\n" +
|
||||
$"chapterscenes={(ChapterScenes ? 1 : 0)}\n" +
|
||||
$"autochampion={(AutoChampion ? 1 : 0)}\n" +
|
||||
$"musicvol={MusicVolume}\n" +
|
||||
$"sfxvol={SfxVolume}\n" +
|
||||
$"voicevol={VoiceVolume}\n" +
|
||||
$"muted={(Muted ? 1 : 0)}\n" +
|
||||
$"reducemotion={(ReduceMotion ? 1 : 0)}\n" +
|
||||
$"textscale={TextScale}\n" +
|
||||
$"hintsseen={string.Join(",", HintsSeen.OrderBy(x => x))}\n");
|
||||
}
|
||||
catch { /* nicht speicherbar → nur für diese Sitzung */ }
|
||||
}
|
||||
|
||||
/// Gespeicherten Fortschritt löschen (Spielstand, gesehene Tipps). Einstellungen bleiben.
|
||||
/// Testläufe löschen nichts.
|
||||
public static void ResetProgress()
|
||||
{
|
||||
if (DevShot.Active) { DevShot.Log("reset progress (skipped in test)"); return; }
|
||||
HintsSeen.Clear();
|
||||
GameState.DeleteSave();
|
||||
Save();
|
||||
}
|
||||
}
|
||||
}
|
||||
19
Core/Credits.cs
Normal file
19
Core/Credits.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
namespace GladiatorIdle
|
||||
{
|
||||
/// Urheber und Kontakt (Einstellungen, Startseite, Lebenskarte).
|
||||
internal static class Credits
|
||||
{
|
||||
public const string COPYRIGHT = "© 2026 Michael Media"; // i18n-ok
|
||||
public const string MAIL = "infomichaelmedia1@gmail.com"; // i18n-ok
|
||||
public const string DISCORD = "https://discord.gg/Ej4JPmCZva"; // i18n-ok
|
||||
|
||||
/// Link im Standardprogramm öffnen (Browser, Mailprogramm).
|
||||
public static void Open(string url)
|
||||
{
|
||||
try { System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo { FileName = url, UseShellExecute = true }); }
|
||||
catch { }
|
||||
}
|
||||
|
||||
public static string MailLink => $"mailto:{MAIL}?subject={System.Uri.EscapeDataString("Gladiator Idle – Feedback")}";
|
||||
}
|
||||
}
|
||||
101
Core/DevShot.cs
Normal file
101
Core/DevShot.cs
Normal file
@@ -0,0 +1,101 @@
|
||||
using System;
|
||||
using System.Drawing;
|
||||
using System.IO;
|
||||
|
||||
namespace GladiatorIdle
|
||||
{
|
||||
/// <summary>
|
||||
/// Entwickler-Werkzeug: <c>GladiatorIdle.exe --shot <ordner></c> überspringt das Intro,
|
||||
/// öffnet die Fenster unsichtbar, speichert Screenshots und beendet sich.
|
||||
/// Testläufe speichern nie Einstellungen oder Spielstände.
|
||||
/// </summary>
|
||||
internal static partial class DevShot
|
||||
{
|
||||
public static string? Dir { get; private set; }
|
||||
public static bool Active => Dir != null;
|
||||
|
||||
/// --playtest: statt Screenshots spielt ein Bot durch die Arenen.
|
||||
public static bool Playtest { get; private set; }
|
||||
|
||||
/// --size BxH: Client-Größe des Fensters (mit --windowed), z. B. 1280x720.
|
||||
public static Size? WindowSize { get; private set; }
|
||||
|
||||
/// --full: zusätzlich Intro und Zwischenszenen aufnehmen.
|
||||
public static bool Full { get; private set; }
|
||||
|
||||
/// --soundlog: Tonabläufe testen (sehr leise, jedes Abspielen steht im Log).
|
||||
public static bool SoundLog { get; private set; }
|
||||
|
||||
/// --fastforward H: so viele Stunden Offline-Zeit simulieren (Balance-Test).
|
||||
public static double FastForwardHours { get; private set; }
|
||||
|
||||
/// Bot (--playtest): Treffsicherheit beim Timing-Schlag (0 = nur idle, 1 = fast perfekt),
|
||||
/// höchstens so viele Spielstunden je Leben, so viele Leben hintereinander, Klasse.
|
||||
public static double Skill { get; private set; } = 0.6;
|
||||
public static double Hours { get; private set; } = 48;
|
||||
public static int Runs { get; private set; } = 2;
|
||||
public static GladiatorClass Class { get; private set; } = GladiatorClass.Murmillo;
|
||||
|
||||
/// --sim H: Spielstand für Screenshots so viele Stunden mit dem Bot vorspielen.
|
||||
public static double SimHours { get; private set; } = 0.5;
|
||||
|
||||
/// --dueltest (mit --playtest): Echtzeit-Duelle per Bot (Siegquote je Kampfkraft-Verhältnis).
|
||||
public static bool DuelTest { get; private set; }
|
||||
|
||||
public static string Name { get; private set; } = "Spartacus"; // i18n-ok
|
||||
public static L.Lang? Lang { get; private set; }
|
||||
|
||||
public static void Parse(string[] args)
|
||||
{
|
||||
int i = Array.IndexOf(args, "--shot");
|
||||
int p = Array.IndexOf(args, "--playtest");
|
||||
if (p >= 0) { i = p; Playtest = true; }
|
||||
Full = Array.IndexOf(args, "--full") >= 0;
|
||||
SoundLog = Array.IndexOf(args, "--soundlog") >= 0;
|
||||
DuelTest = Array.IndexOf(args, "--dueltest") >= 0;
|
||||
// --calm: "Effekte reduzieren" nur für diesen Lauf (wird nicht gespeichert)
|
||||
if (Array.IndexOf(args, "--calm") >= 0) AppSettings.ReduceMotion = true;
|
||||
// --windowed: Fenstermodus nur für diesen Lauf
|
||||
if (Array.IndexOf(args, "--windowed") >= 0) AppSettings.Fullscreen = false;
|
||||
int s = Array.IndexOf(args, "--size");
|
||||
if (s >= 0 && s + 1 < args.Length)
|
||||
{
|
||||
var wh = args[s + 1].Split('x');
|
||||
if (wh.Length == 2 && int.TryParse(wh[0], out int w) && int.TryParse(wh[1], out int h))
|
||||
WindowSize = new Size(w, h);
|
||||
}
|
||||
int n = Array.IndexOf(args, "--name");
|
||||
if (n >= 0 && n + 1 < args.Length) Name = args[n + 1];
|
||||
// --lang en|de|es: Sprache nur für diesen Lauf (lang.txt bleibt unverändert)
|
||||
int la = Array.IndexOf(args, "--lang");
|
||||
if (la >= 0 && la + 1 < args.Length && Enum.TryParse<L.Lang>(args[la + 1], true, out var lang)) Lang = lang;
|
||||
double? Num(string flag)
|
||||
{
|
||||
int k = Array.IndexOf(args, flag);
|
||||
return k >= 0 && k + 1 < args.Length && double.TryParse(args[k + 1],
|
||||
System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double v) ? v : null;
|
||||
}
|
||||
if (Num("--fastforward") is double ff) FastForwardHours = ff;
|
||||
if (Num("--sim") is double sim) SimHours = sim;
|
||||
if (Num("--skill") is double skill) Skill = Math.Clamp(skill, 0, 1);
|
||||
if (Num("--hours") is double hrs) Hours = hrs;
|
||||
if (Num("--runs") is double runs) Runs = Math.Max(1, (int)runs);
|
||||
int c = Array.IndexOf(args, "--class");
|
||||
if (c >= 0 && c + 1 < args.Length && Enum.TryParse<GladiatorClass>(args[c + 1], true, out var cls)) Class = cls;
|
||||
if (i >= 0 && i + 1 < args.Length)
|
||||
{
|
||||
Dir = args[i + 1];
|
||||
Directory.CreateDirectory(Dir);
|
||||
}
|
||||
}
|
||||
|
||||
static readonly object _logLock = new();
|
||||
|
||||
public static void Log(string msg)
|
||||
{
|
||||
if (Dir == null) return;
|
||||
lock (_logLock) // Ton-Ereignisse kommen aus Hintergrund-Threads
|
||||
File.AppendAllText(Path.Combine(Dir, "log.txt"), $"{DateTime.Now:HH:mm:ss.fff} {msg}\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
165
Core/LocalizationManager.cs
Normal file
165
Core/LocalizationManager.cs
Normal file
@@ -0,0 +1,165 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace GladiatorIdle
|
||||
{
|
||||
/// <summary>
|
||||
/// JSON-basierte Lokalisierung.
|
||||
/// Sprachdateien liegen in Languages/{lang}.json neben der EXE.
|
||||
/// Fallback: Englisch → danach der rohe Key.
|
||||
///
|
||||
/// Neue Sprache hinzufügen: JSON-Datei in Languages/ ablegen (z.B. de.json).
|
||||
/// Neuer Feature-String: immer zuerst in en.json eintragen, dann in allen anderen Sprachen.
|
||||
/// </summary>
|
||||
public static class L
|
||||
{
|
||||
public enum Lang { En, De, Es }
|
||||
|
||||
public static Lang Current { get; private set; } = Lang.En;
|
||||
|
||||
static Dictionary<string, string> _strings = new();
|
||||
|
||||
static string SettingsPath => Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"GladiatorIdle", "lang.txt");
|
||||
|
||||
static string LangFolder =>
|
||||
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Languages");
|
||||
|
||||
/// <summary>Wurde schon einmal eine Sprache gewählt? (sonst Sprachauswahl vor dem Intro)</summary>
|
||||
public static bool HasSavedLanguage => File.Exists(SettingsPath);
|
||||
|
||||
/// <summary>Einmalig beim App-Start aufrufen — lädt gespeicherte Sprachpräferenz.</summary>
|
||||
public static void Load()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(SettingsPath) &&
|
||||
Enum.TryParse<Lang>(File.ReadAllText(SettingsPath).Trim(), out var saved))
|
||||
Current = saved;
|
||||
}
|
||||
catch { }
|
||||
LoadFile();
|
||||
}
|
||||
|
||||
/// <summary>Sprache wechseln, Präferenz speichern, Strings neu laden.</summary>
|
||||
public static void Set(Lang lang)
|
||||
{
|
||||
Current = lang;
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(SettingsPath)!);
|
||||
File.WriteAllText(SettingsPath, lang.ToString());
|
||||
}
|
||||
catch { }
|
||||
LoadFile();
|
||||
}
|
||||
|
||||
/// <summary>Gespeicherte Sprache (kann im laufenden Spiel von <see cref="Current"/> abweichen).</summary>
|
||||
public static Lang Saved
|
||||
{
|
||||
get
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(SettingsPath) && Enum.TryParse<Lang>(File.ReadAllText(SettingsPath).Trim(), out var s))
|
||||
return s;
|
||||
}
|
||||
catch { }
|
||||
return Current;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sprache nur speichern, gilt ab dem nächsten Start der Startseite (mitten im
|
||||
/// Leben würden sonst alte und neue Texte gemischt).</summary>
|
||||
public static void SaveForNextStart(Lang lang)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(SettingsPath)!);
|
||||
File.WriteAllText(SettingsPath, lang.ToString());
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
/// <summary>Sprache nur für diese Sitzung (Testläufe), nichts wird gespeichert.</summary>
|
||||
public static void UseForSession(Lang lang)
|
||||
{
|
||||
Current = lang;
|
||||
LoadFile();
|
||||
}
|
||||
|
||||
/// <summary>Gespeicherte, aber noch nicht aktive Sprache jetzt laden (z. B. beim Neustart).</summary>
|
||||
public static void ApplySaved()
|
||||
{
|
||||
if (DevShot.Lang != null) return; // Testlauf mit --lang
|
||||
var s = Saved;
|
||||
if (s != Current) { Current = s; LoadFile(); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lokalisierten String zurückgeben.
|
||||
/// Fallback: Englisch → Key selbst (fehlende Keys werden im Debug geloggt).
|
||||
/// </summary>
|
||||
public static string t(string key)
|
||||
{
|
||||
if (_strings.TryGetValue(key, out var val)) return val;
|
||||
|
||||
#if DEBUG
|
||||
try { File.AppendAllText("missing_translations.txt", $"[{Current}] MISSING: {key}\n"); }
|
||||
catch { }
|
||||
#endif
|
||||
// Fallback: roher Key (sichtbar als Warnung im Spiel)
|
||||
return $"[{key}]";
|
||||
}
|
||||
|
||||
static void LoadFile()
|
||||
{
|
||||
_strings = LoadDictionary("en");
|
||||
string langName = Current.ToString().ToLower();
|
||||
|
||||
if (langName == "en") return;
|
||||
|
||||
foreach (var kv in LoadDictionary(langName))
|
||||
_strings[kv.Key] = kv.Value;
|
||||
}
|
||||
|
||||
static Dictionary<string, string> LoadDictionary(string langName)
|
||||
{
|
||||
string? json = LoadEmbedded(langName);
|
||||
|
||||
if (json == null)
|
||||
{
|
||||
string file = Path.Combine(LangFolder, langName + ".json");
|
||||
if (File.Exists(file))
|
||||
try { json = File.ReadAllText(file); } catch { }
|
||||
}
|
||||
|
||||
if (json == null) return new Dictionary<string, string>();
|
||||
|
||||
try
|
||||
{
|
||||
return JsonSerializer.Deserialize<Dictionary<string, string>>(json)
|
||||
?? new Dictionary<string, string>();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return new Dictionary<string, string>();
|
||||
}
|
||||
}
|
||||
|
||||
static string? LoadEmbedded(string langName)
|
||||
{
|
||||
// Embedded Resource Name: GladiatorIdle.Languages.{lang}.json
|
||||
string resName = $"GladiatorIdle.Languages.{langName}.json";
|
||||
var asm = Assembly.GetExecutingAssembly();
|
||||
using var stream = asm.GetManifestResourceStream(resName);
|
||||
if (stream == null) return null;
|
||||
using var reader = new StreamReader(stream);
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
}
|
||||
}
|
||||
664
Core/SoundManager.cs
Normal file
664
Core/SoundManager.cs
Normal file
@@ -0,0 +1,664 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using NAudio.Wave;
|
||||
using NAudio.Wave.SampleProviders;
|
||||
|
||||
namespace GladiatorIdle
|
||||
{
|
||||
/// <summary>
|
||||
/// Ein NAudio-Mixer für alle Sounds: Effekte überlagern sich statt sich gegenseitig
|
||||
/// abzuwürgen, Musik läuft auf eigenem Kanal mit Crossfade.
|
||||
/// Clips kommen aus Assets/Audio/<name>.mp3 (eingebettet); fehlt einer, spielt der
|
||||
/// synthetische Ton von früher. StopAll() bricht sofort alles ab (Game Over / Neustart).
|
||||
/// </summary>
|
||||
public static class SoundManager
|
||||
{
|
||||
static bool _enabled = true;
|
||||
public static bool Enabled
|
||||
{
|
||||
get => _enabled;
|
||||
set { _enabled = value; if (!value) StopAll(); }
|
||||
}
|
||||
|
||||
/// Lautstärke 0–1 (Einstellungen). Wirkt sofort, auch auf laufende Musik.
|
||||
public static float MusicLevel { get; set; } = 1f;
|
||||
public static float SfxLevel { get; set; } = 1f;
|
||||
public static float VoiceLevel { get; set; } = 1f; // Erzählstimme
|
||||
|
||||
const int SAMPLE_RATE = 22050; // synthetische Fallback-Töne
|
||||
const float MUSIC_VOLUME = 0.55f;
|
||||
static readonly WaveFormat MixFormat = WaveFormat.CreateIeeeFloatWaveFormat(44100, 2);
|
||||
|
||||
// ── Synthetische Fallbacks (einmalig beim Start generiert) ───
|
||||
static readonly byte[] _wavClick = BuildClick();
|
||||
static readonly byte[] _wavTick = BuildTick(1150f);
|
||||
static readonly byte[] _wavAmbient = BuildAmbientLoop();
|
||||
static readonly byte[] _wavGood = BuildGoodChime();
|
||||
static readonly byte[] _wavBad = BuildBadChime();
|
||||
static readonly byte[] _wavPurchase = BuildPurchaseBlip();
|
||||
static readonly byte[] _wavMilestone = BuildMilestoneMelody();
|
||||
static readonly byte[] _wavStart = BuildStartMelody();
|
||||
static readonly byte[] _wavAchievement = BuildAchievementFanfare();
|
||||
static readonly byte[] _wavLevelUp = BuildLevelUpSound();
|
||||
static readonly byte[] _wavDefeat = BuildGameOverMelody();
|
||||
static readonly byte[] _wavHit = Note(140f, 0.07f, 0.45f);
|
||||
static readonly byte[] _wavBlock = Note(620f, 0.05f, 0.30f);
|
||||
static readonly byte[] _wavGong = Note(98f, 1.6f, 0.30f);
|
||||
|
||||
// ── Öffentliche API ──────────────────────────────────────────
|
||||
// Fehlt der Clip in Assets/Audio, spielt der synthetische Ton.
|
||||
public static void PlayClick() => Play("sfx_click", _wavClick, cooldownMs: 120);
|
||||
public static void PlayTick() => Play("sfx_tick", _wavTick, cooldownMs: 80);
|
||||
// Töne, die im Sekundentakt kommen (Training, Schläge, Siege), sind leiser gemischt
|
||||
public static void PlayTrain() => Play("sfx_train", _wavTick, cooldownMs: 60, gain: 0.5f); // Trainings-Klick
|
||||
public static void PlayCoins() => Play("sfx_coins", _wavPurchase, cooldownMs: 150, gain: 0.6f);
|
||||
public static void PlayPurchase() => Play("sfx_purchase", _wavPurchase);
|
||||
public static void PlayHit() => Play("sfx_hit", _wavHit, cooldownMs: 60, gain: 0.4f); // Schwerthieb
|
||||
public static void PlayBlock() => Play("sfx_block", _wavBlock, cooldownMs: 60, gain: 0.45f); // Schild
|
||||
public static void PlayCheer() => Play("sfx_crowd_cheer", _wavGood, cooldownMs: 800, gain: 0.7f);
|
||||
public static void PlayBoo() => Play("sfx_crowd_boo", _wavBad, cooldownMs: 800, gain: 0.6f);
|
||||
public static void PlayGong() => Play("sfx_gong", _wavGong); // Kampfbeginn
|
||||
public static void PlayVictory() => Play("sfx_victory", _wavMilestone);
|
||||
public static void PlayDefeat() => Play("sfx_defeat", _wavDefeat);
|
||||
public static void PlayLevelUp() => Play("sfx_levelup", _wavLevelUp);
|
||||
public static void PlayUnlock() => Play("sfx_unlock", _wavLevelUp);
|
||||
public static void PlayAchievement() => Play("sfx_achievement", _wavAchievement);
|
||||
public static void PlayStart() => Play("sfx_start", _wavStart);
|
||||
public static void PlayTip() => Play("sfx_tip", _wavGood, cooldownMs: 400);
|
||||
public static void PlayGoodEvent() => Play("sfx_good", _wavGood); // Probeton (Einstellungen)
|
||||
public static void PlayChapterSting() => Play("sting_chapter", _wavMilestone);
|
||||
|
||||
// ── Erzählstimme (Intro) ─────────────────────────────────────
|
||||
// Eigene Spur: immer nur ein Satz gleichzeitig, eigene Lautstärke (VoiceLevel).
|
||||
// Solange gesprochen wird, wird die Musik weich leiser ("Ducking").
|
||||
|
||||
const float DUCK_LEVEL = 0.35f;
|
||||
static VoiceClip? _voice;
|
||||
static float _duck = 1f;
|
||||
|
||||
/// Satz aus Assets/Audio/voice_<sprache>_<key>.mp3 vorlesen (Punkte im Key → _).
|
||||
/// Dekodiert im Hintergrund (vorher am besten per PreloadVoice), der Aufrufer ruckelt nie.
|
||||
/// Vorher und nachher Ruhe: die Stimme wartet, bis laufende Effekte verklungen sind
|
||||
/// (höchstens VOICE_WAIT_MAX_MS, danach werden sie ausgeblendet), dann eine kurze Pause;
|
||||
/// solange sie spricht und kurz danach startet kein neuer Effekt.
|
||||
public static void PlayVoice(string key)
|
||||
{
|
||||
if (!_enabled || !AppSettings.Narration || VoiceLevel <= 0.001f) return;
|
||||
string name = VoiceName(key);
|
||||
if (!HasClip(name)) return;
|
||||
long ver = Interlocked.Read(ref _sfxVersion);
|
||||
long gen = Interlocked.Increment(ref _voiceGen);
|
||||
Interlocked.Exchange(ref _voice, null)?.Stop(); // ein früherer Satz endet jetzt
|
||||
_voicePending = true; // Musik wird schon in der Pause leiser
|
||||
Interlocked.Exchange(ref _quietUntil, long.MaxValue); // ab jetzt keine neuen Effekte
|
||||
Task.Run(async () =>
|
||||
{
|
||||
var data = Clip(name, null);
|
||||
// gerade erst angestoßene Effekte sich anmelden lassen (sie dekodieren noch)
|
||||
for (int i = 0; i < 20 && Volatile.Read(ref _pendingSfx) > 0; i++) await Task.Delay(20);
|
||||
long busy = Interlocked.Read(ref _effectsBusyUntil) - Environment.TickCount64;
|
||||
await Task.Delay((int)Math.Clamp(busy, 0, VOICE_WAIT_MAX_MS));
|
||||
// langer Nachklang (Kapitel-Gong): weich ausblenden, dann erst die Pause
|
||||
bool cutTail = busy > VOICE_WAIT_MAX_MS && Interlocked.Read(ref _voiceGen) == gen;
|
||||
if (cutTail) Interlocked.Increment(ref _effectsCut);
|
||||
await Task.Delay(VOICE_PRE_MS + (cutTail ? CUT_FADE_MS : 0));
|
||||
|
||||
var mixer = Mixer;
|
||||
bool current = Interlocked.Read(ref _voiceGen) == gen;
|
||||
if (data == null || mixer == null || !current || Interlocked.Read(ref _sfxVersion) != ver)
|
||||
{
|
||||
if (current) { _voicePending = false; Interlocked.Exchange(ref _quietUntil, 0); }
|
||||
if (DevShot.SoundLog) DevShot.Log($"sound: voice {key} cancelled");
|
||||
return;
|
||||
}
|
||||
long ms = (long)(data.Length / 2f / MixFormat.SampleRate * 1000);
|
||||
Interlocked.Exchange(ref _quietUntil, Environment.TickCount64 + ms + VOICE_POST_MS);
|
||||
var v = new VoiceClip(data);
|
||||
Interlocked.Exchange(ref _voice, v)?.Stop();
|
||||
_voicePending = false;
|
||||
mixer.AddMixerInput(v);
|
||||
if (DevShot.SoundLog)
|
||||
DevShot.Log($"sound: voice {key} {ms} ms (waited for effects {Math.Max(0, busy)} ms{(busy > VOICE_WAIT_MAX_MS ? ", cut" : "")})");
|
||||
});
|
||||
if (DevShot.SoundLog) DevShot.Log($"sound: voice {key} requested");
|
||||
}
|
||||
|
||||
const int VOICE_PRE_MS = 250, VOICE_POST_MS = 350, VOICE_WAIT_MAX_MS = 1500, CUT_FADE_MS = 300;
|
||||
static long _voiceGen, _quietUntil, _effectsBusyUntil;
|
||||
static int _pendingSfx;
|
||||
static volatile bool _voicePending;
|
||||
|
||||
/// Wann der zuletzt gestartete Effekt verklingt (für die Ruhe vor der Stimme).
|
||||
static void NoteEffectEnd(long endMs)
|
||||
{
|
||||
long cur;
|
||||
do { cur = Interlocked.Read(ref _effectsBusyUntil); if (endMs <= cur) return; }
|
||||
while (Interlocked.CompareExchange(ref _effectsBusyUntil, endMs, cur) != cur);
|
||||
}
|
||||
|
||||
/// Sätze schon dekodieren, damit sie auf den Punkt starten.
|
||||
public static void PreloadVoice(IEnumerable<string> keys)
|
||||
{
|
||||
if (!_enabled || !AppSettings.Narration) return;
|
||||
var names = keys.Select(VoiceName).Where(HasClip).ToArray();
|
||||
Task.Run(() => { foreach (var n in names) Clip(n, null); });
|
||||
}
|
||||
|
||||
// ── Atmosphäre (Geräuschkulisse unter einer Szene) ──────────
|
||||
const float AMBIENCE_GAIN = 0.45f;
|
||||
static AmbienceVoice? _ambience;
|
||||
|
||||
/// Geräuschkulisse (Assets/Audio/<name>.mp3) weich ein- und ausgeblendet unter
|
||||
/// Musik und Stimme; ersetzt eine laufende weich. Fehlt der Clip: nichts.
|
||||
public static void PlayAmbience(string name)
|
||||
{
|
||||
if (!_enabled || SfxLevel <= 0.001f || !HasClip(name)) return;
|
||||
long ver = Interlocked.Read(ref _sfxVersion);
|
||||
Task.Run(() =>
|
||||
{
|
||||
var data = Clip(name, null);
|
||||
var mixer = Mixer;
|
||||
if (data == null || mixer == null || Interlocked.Read(ref _sfxVersion) != ver) return;
|
||||
var a = new AmbienceVoice(data);
|
||||
Interlocked.Exchange(ref _ambience, a)?.Stop();
|
||||
mixer.AddMixerInput(a);
|
||||
});
|
||||
}
|
||||
|
||||
public static void StopAmbience() => Interlocked.Exchange(ref _ambience, null)?.Stop();
|
||||
|
||||
/// Clips schon dekodieren (Intro), damit sie auf den Punkt starten.
|
||||
public static void Preload(IEnumerable<string> names)
|
||||
{
|
||||
if (!_enabled) return;
|
||||
var list = names.Where(HasClip).ToArray();
|
||||
Task.Run(() => { foreach (var n in list) Clip(n, null); });
|
||||
}
|
||||
|
||||
/// Clip-Name der Erzählstimme für einen Text-Key in der aktuellen Sprache.
|
||||
public static string VoiceName(string key) =>
|
||||
$"voice_{L.Current.ToString().ToLowerInvariant()}_{key.Replace('.', '_')}";
|
||||
|
||||
/// Länge eines Satzes in Sekunden (dekodiert ihn dafür; 0 = fehlt/kaputt). Für Tests.
|
||||
public static float VoiceSeconds(string key) =>
|
||||
(Clip(VoiceName(key), null)?.Length ?? 0) / 2f / MixFormat.SampleRate;
|
||||
|
||||
/// Satz abbrechen (auch einen, der noch auf seine Ruhe wartet); Effekte sind sofort wieder frei.
|
||||
public static void StopVoice()
|
||||
{
|
||||
Interlocked.Increment(ref _voiceGen);
|
||||
_voicePending = false;
|
||||
Interlocked.Exchange(ref _quietUntil, 0);
|
||||
Interlocked.Exchange(ref _voice, null)?.Stop();
|
||||
}
|
||||
|
||||
static long _effectsCut;
|
||||
|
||||
/// Laufende Effekte, Stimme und Geräuschkulisse kurz ausblenden (Musik läuft weiter) und
|
||||
/// noch dekodierende verwerfen — vor einer Zwischenszene, damit nichts übereinander liegt.
|
||||
public static void CutEffects()
|
||||
{
|
||||
Interlocked.Increment(ref _effectsCut);
|
||||
Interlocked.Increment(ref _sfxVersion);
|
||||
Interlocked.Exchange(ref _effectsBusyUntil, Environment.TickCount64 + CUT_FADE_MS);
|
||||
StopVoice();
|
||||
StopAmbience();
|
||||
}
|
||||
|
||||
/// Länge eines Effekt-Clips in Sekunden (0 = fehlt).
|
||||
public static float ClipSeconds(string name) =>
|
||||
HasClip(name) ? (Clip(name, null)?.Length ?? 0) / 2f / MixFormat.SampleRate : 0f;
|
||||
|
||||
/// So lange nach PlayVoice beginnt der Satz frühestens (Ruhe davor), wenn vorher
|
||||
/// ein Effekt von <paramref name="effectSeconds"/> Länge gestartet wurde.
|
||||
public static float VoiceDelay(float effectSeconds) =>
|
||||
Math.Min(effectSeconds, VOICE_WAIT_MAX_MS / 1000f) + VOICE_PRE_MS / 1000f
|
||||
+ (effectSeconds * 1000 > VOICE_WAIT_MAX_MS ? CUT_FADE_MS / 1000f : 0f);
|
||||
|
||||
/// Liest gerade die Erzählstimme? (Musik wird dann gedämpft.)
|
||||
static bool VoiceActive => _voicePending || _voice is { Done: false };
|
||||
|
||||
/// Gibt es den Clip als Datei? (Musik je Lebensphase nur, wenn vorhanden.)
|
||||
public static bool HasClip(string name) =>
|
||||
typeof(SoundManager).Assembly.GetManifestResourceInfo($"GladiatorIdle.Assets.Audio.{name}.mp3") != null;
|
||||
|
||||
/// <summary>Hintergrundmusik starten. Ohne Argument: zuletzt gewählter Track.</summary>
|
||||
public static void StartAmbient(string? track = null)
|
||||
{
|
||||
if (track != null) _track = track;
|
||||
PlayMusic(_track, loop: true);
|
||||
}
|
||||
|
||||
public static void StopAmbient()
|
||||
{
|
||||
Interlocked.Increment(ref _musicVersion);
|
||||
lock (_musicLock) { _music?.FadeOut(0.8f); _music = null; }
|
||||
}
|
||||
|
||||
/// <summary>Musik-Track mit Crossfade wechseln (Intro: loop = false).</summary>
|
||||
public static void PlayMusic(string name, bool loop)
|
||||
{
|
||||
if (!_enabled) return;
|
||||
long ver = Interlocked.Increment(ref _musicVersion);
|
||||
byte[]? fallback = name is "music_menu" or "music_ludus" ? _wavAmbient : null;
|
||||
Task.Run(() =>
|
||||
{
|
||||
var data = Clip(name, fallback);
|
||||
var mixer = Mixer;
|
||||
if (data == null || mixer == null) return;
|
||||
lock (_musicLock)
|
||||
{
|
||||
if (Interlocked.Read(ref _musicVersion) != ver || !_enabled) return;
|
||||
if (_music != null && _music.Name == name) return; // läuft schon
|
||||
_music?.FadeOut(1.5f);
|
||||
_music = new MusicVoice(name, data, loop, MUSIC_VOLUME, fadeInSec: 1.5f);
|
||||
mixer.AddMixerInput(_music);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stoppt sofort alle Kanäle und verwirft alle ausstehenden Tasks.
|
||||
/// Aufruf bei Game Over und Neustart.
|
||||
/// </summary>
|
||||
public static void StopAll()
|
||||
{
|
||||
Interlocked.Increment(ref _musicVersion);
|
||||
Interlocked.Increment(ref _sfxVersion);
|
||||
Interlocked.Increment(ref _voiceGen); // wartender Satz startet nicht mehr
|
||||
_voicePending = false;
|
||||
Interlocked.Exchange(ref _quietUntil, 0);
|
||||
Interlocked.Exchange(ref _effectsBusyUntil, 0);
|
||||
_voice = null;
|
||||
_ambience = null;
|
||||
lock (_musicLock) _music = null;
|
||||
lock (_outLock) _mixer?.RemoveAllMixerInputs();
|
||||
}
|
||||
|
||||
/// <summary>Audio-Ausgabe freigeben (beim Programmende).</summary>
|
||||
public static void Shutdown()
|
||||
{
|
||||
lock (_outLock)
|
||||
{
|
||||
_out?.Stop();
|
||||
_out?.Dispose();
|
||||
_out = null;
|
||||
_mixer = null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Mixer ────────────────────────────────────────────────────
|
||||
|
||||
static MixingSampleProvider? _mixer;
|
||||
static IWavePlayer? _out;
|
||||
static bool _outFailed;
|
||||
static readonly object _outLock = new();
|
||||
|
||||
static MusicVoice? _music;
|
||||
static string _track = "music_menu";
|
||||
static long _musicVersion;
|
||||
static readonly object _musicLock = new();
|
||||
|
||||
static long _sfxVersion;
|
||||
static readonly Dictionary<string, long> _lastPlayed = new();
|
||||
static readonly Dictionary<string, float[]?> _clips = new();
|
||||
|
||||
static MixingSampleProvider? Mixer
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_outLock)
|
||||
{
|
||||
if (_mixer != null || _outFailed) return _mixer;
|
||||
try
|
||||
{
|
||||
var mixer = new MixingSampleProvider(MixFormat) { ReadFully = true };
|
||||
var output = new WaveOutEvent { DesiredLatency = 120 };
|
||||
output.Init(mixer);
|
||||
output.Play();
|
||||
_mixer = mixer;
|
||||
_out = output;
|
||||
}
|
||||
catch { _outFailed = true; } // kein Audiogerät → stumm weiterspielen
|
||||
return _mixer;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void Play(string name, byte[] fallback, long cooldownMs = 0, float gain = 1f)
|
||||
{
|
||||
if (!_enabled || SfxLevel <= 0.001f) return;
|
||||
if (Environment.TickCount64 < Interlocked.Read(ref _quietUntil)) // Erzählstimme: Ruhe
|
||||
{
|
||||
if (DevShot.SoundLog) DevShot.Log($"sound: skip {name} (voice quiet)");
|
||||
return;
|
||||
}
|
||||
if (cooldownMs > 0)
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
lock (_lastPlayed)
|
||||
{
|
||||
if (_lastPlayed.TryGetValue(name, out long last) && now - last < cooldownMs) return;
|
||||
_lastPlayed[name] = now;
|
||||
}
|
||||
}
|
||||
long ver = Interlocked.Read(ref _sfxVersion);
|
||||
Interlocked.Increment(ref _pendingSfx);
|
||||
Task.Run(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var data = Clip(name, fallback);
|
||||
var mixer = Mixer;
|
||||
if (data == null || mixer == null || Interlocked.Read(ref _sfxVersion) != ver) return;
|
||||
long len = (long)(data.Length / 2f / MixFormat.SampleRate * 1000);
|
||||
NoteEffectEnd(Environment.TickCount64 + len);
|
||||
mixer.AddMixerInput(new ClipVoice(data, gain));
|
||||
if (DevShot.SoundLog) DevShot.Log($"sound: sfx {name} {len} ms");
|
||||
}
|
||||
finally { Interlocked.Decrement(ref _pendingSfx); }
|
||||
});
|
||||
}
|
||||
|
||||
/// Clip dekodiert als 44,1 kHz Stereo-Float, gecacht. MP3 aus Assets/Audio, sonst Fallback-WAV.
|
||||
static float[]? Clip(string name, byte[]? fallback)
|
||||
{
|
||||
lock (_clips)
|
||||
if (_clips.TryGetValue(name, out var cached)) return cached;
|
||||
|
||||
float[]? data = null;
|
||||
try
|
||||
{
|
||||
using var res = typeof(SoundManager).Assembly
|
||||
.GetManifestResourceStream($"GladiatorIdle.Assets.Audio.{name}.mp3");
|
||||
if (res != null)
|
||||
{
|
||||
var ms = new MemoryStream();
|
||||
res.CopyTo(ms);
|
||||
ms.Position = 0;
|
||||
using var reader = new Mp3FileReader(ms);
|
||||
data = Decode(reader);
|
||||
}
|
||||
else if (fallback != null)
|
||||
{
|
||||
using var reader = new WaveFileReader(new MemoryStream(fallback));
|
||||
data = Decode(reader);
|
||||
}
|
||||
}
|
||||
catch { data = null; }
|
||||
|
||||
lock (_clips) _clips[name] = data;
|
||||
return data;
|
||||
}
|
||||
|
||||
static float[] Decode(WaveStream reader)
|
||||
{
|
||||
ISampleProvider sp = reader.ToSampleProvider();
|
||||
if (sp.WaveFormat.Channels == 1) sp = new MonoToStereoSampleProvider(sp);
|
||||
if (sp.WaveFormat.SampleRate != MixFormat.SampleRate)
|
||||
sp = new WdlResamplingSampleProvider(sp, MixFormat.SampleRate);
|
||||
|
||||
var all = new List<float>();
|
||||
var buf = new float[MixFormat.SampleRate * 2];
|
||||
int n;
|
||||
while ((n = sp.Read(buf, 0, buf.Length)) > 0)
|
||||
for (int i = 0; i < n; i++) all.Add(buf[i]);
|
||||
return all.ToArray();
|
||||
}
|
||||
|
||||
/// Einmaliger Effekt; liefert 0 am Ende → Mixer entfernt ihn.
|
||||
sealed class ClipVoice : ISampleProvider
|
||||
{
|
||||
readonly float[] _data;
|
||||
readonly long _cut = Interlocked.Read(ref _effectsCut);
|
||||
int _pos;
|
||||
readonly float _gain;
|
||||
float _fade = 1f;
|
||||
public ClipVoice(float[] data, float gain = 1f) { _data = data; _gain = gain; }
|
||||
public WaveFormat WaveFormat => MixFormat;
|
||||
|
||||
public int Read(float[] buffer, int offset, int count)
|
||||
{
|
||||
int n = Math.Min(count, _data.Length - _pos);
|
||||
bool cut = Interlocked.Read(ref _effectsCut) != _cut;
|
||||
if (n <= 0 || (cut && _fade <= 0)) return 0;
|
||||
float lv = SfxLevel * _gain;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
if (cut) _fade = Math.Max(0, _fade - 1f / (MixFormat.SampleRate * 2 * CUT_FADE_MS / 1000f)); // weich ausblenden
|
||||
buffer[offset + i] = _data[_pos + i] * lv * _fade;
|
||||
}
|
||||
_pos += n;
|
||||
return n;
|
||||
}
|
||||
}
|
||||
|
||||
/// Satz der Erzählstimme; kann vorzeitig (weich) beendet werden.
|
||||
sealed class VoiceClip : ISampleProvider
|
||||
{
|
||||
readonly float[] _data;
|
||||
int _pos;
|
||||
volatile bool _stop;
|
||||
float _fade = 1f;
|
||||
public VoiceClip(float[] data) => _data = data;
|
||||
public WaveFormat WaveFormat => MixFormat;
|
||||
public bool Done => _stop || _pos >= _data.Length;
|
||||
public void Stop() => _stop = true;
|
||||
|
||||
public int Read(float[] buffer, int offset, int count)
|
||||
{
|
||||
int n = Math.Min(count, _data.Length - _pos);
|
||||
if (n <= 0 || (_stop && _fade <= 0)) return 0;
|
||||
float lv = VoiceLevel;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
if (_stop) _fade = Math.Max(0, _fade - 1f / 4410f); // 50 ms ausblenden
|
||||
buffer[offset + i] = _data[_pos + i] * lv * _fade;
|
||||
}
|
||||
_pos += n;
|
||||
return n;
|
||||
}
|
||||
}
|
||||
|
||||
/// Geräuschkulisse: 0,6 s einblenden, zum Clip-Ende (oder bei Stop) 0,8 s ausblenden.
|
||||
sealed class AmbienceVoice : ISampleProvider
|
||||
{
|
||||
const int FADE_IN = 44100 * 2 * 6 / 10, FADE_OUT = 44100 * 2 * 8 / 10; // Samples (Stereo)
|
||||
readonly float[] _data;
|
||||
int _pos, _stopAt = int.MaxValue;
|
||||
public AmbienceVoice(float[] data) => _data = data;
|
||||
public WaveFormat WaveFormat => MixFormat;
|
||||
public void Stop() => _stopAt = Math.Min(_stopAt, _pos);
|
||||
|
||||
public int Read(float[] buffer, int offset, int count)
|
||||
{
|
||||
int end = Math.Min(_data.Length, _stopAt == int.MaxValue ? _data.Length : _stopAt + FADE_OUT);
|
||||
int n = Math.Min(count, end - _pos);
|
||||
if (n <= 0) return 0;
|
||||
float lv = SfxLevel * AMBIENCE_GAIN;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
int p = _pos + i;
|
||||
float env = Math.Min(1f, p / (float)FADE_IN);
|
||||
env = Math.Min(env, (end - p) / (float)FADE_OUT);
|
||||
buffer[offset + i] = _data[p] * lv * Math.Max(0f, env);
|
||||
}
|
||||
_pos += n;
|
||||
return n;
|
||||
}
|
||||
}
|
||||
|
||||
/// Musik mit Loop und Lautstärke-Rampe (Ein-/Ausblenden, Crossfade).
|
||||
sealed class MusicVoice : ISampleProvider
|
||||
{
|
||||
readonly float[] _data;
|
||||
readonly bool _loop;
|
||||
int _pos;
|
||||
float _vol, _target, _step;
|
||||
volatile bool _fadingOut;
|
||||
|
||||
public string Name { get; }
|
||||
public WaveFormat WaveFormat => MixFormat;
|
||||
|
||||
public MusicVoice(string name, float[] data, bool loop, float volume, float fadeInSec)
|
||||
{
|
||||
Name = name; _data = data; _loop = loop; _target = volume;
|
||||
_step = volume / Math.Max(1f, fadeInSec * MixFormat.SampleRate);
|
||||
}
|
||||
|
||||
public void FadeOut(float sec)
|
||||
{
|
||||
_step = Math.Max(_vol, 0.001f) / Math.Max(1f, sec * MixFormat.SampleRate);
|
||||
_target = 0;
|
||||
_fadingOut = true;
|
||||
}
|
||||
|
||||
public int Read(float[] buffer, int offset, int count)
|
||||
{
|
||||
if (_fadingOut && _vol <= 0) return 0;
|
||||
for (int i = 0; i < count; i += 2)
|
||||
{
|
||||
if (_pos >= _data.Length)
|
||||
{
|
||||
if (!_loop)
|
||||
{
|
||||
if (i == 0) return 0;
|
||||
Array.Clear(buffer, offset + i, count - i);
|
||||
return count;
|
||||
}
|
||||
_pos = 0;
|
||||
}
|
||||
_vol = _vol < _target ? Math.Min(_target, _vol + _step) : Math.Max(_target, _vol - _step);
|
||||
// Ducking: ~0,3 s leiser werden, ~0,8 s zurück
|
||||
float duckTarget = VoiceActive ? DUCK_LEVEL : 1f;
|
||||
_duck = _duck > duckTarget ? Math.Max(duckTarget, _duck - 1f / 13000f)
|
||||
: Math.Min(duckTarget, _duck + 1f / 35000f);
|
||||
float v = _vol * MusicLevel * _duck;
|
||||
buffer[offset + i] = _data[_pos] * v;
|
||||
buffer[offset + i + 1] = _data[_pos + 1] * v;
|
||||
_pos += 2;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Melodie-Generatoren (Fallback) ───────────────────────────
|
||||
|
||||
static byte[] BuildStartMelody() => Sequence(
|
||||
Note(261.6f, 0.12f), Note(329.6f, 0.12f),
|
||||
Note(392.0f, 0.12f), Note(523.3f, 0.25f));
|
||||
|
||||
static byte[] BuildMilestoneMelody() => Sequence(
|
||||
Note(659.3f, 0.10f), Note(783.9f, 0.10f), Note(1046.5f, 0.25f));
|
||||
|
||||
static byte[] BuildGoodChime() => Sequence(
|
||||
Note(523.3f, 0.08f), Note(659.3f, 0.18f));
|
||||
|
||||
static byte[] BuildBadChime() => Sequence(
|
||||
Note(330.0f, 0.10f), Note(220.0f, 0.22f));
|
||||
|
||||
static byte[] BuildPurchaseBlip() => Sequence(
|
||||
Note(880.0f, 0.06f), Note(1108.7f, 0.10f));
|
||||
|
||||
static byte[] BuildGameOverMelody() => Sequence(
|
||||
Note(392.0f, 0.18f), Note(329.6f, 0.18f),
|
||||
Note(261.6f, 0.18f), Note(220.0f, 0.40f));
|
||||
|
||||
static byte[] BuildTick(float freq) => Sequence(Note(freq, 0.04f, 0.05f));
|
||||
|
||||
static byte[] BuildAchievementFanfare() => Sequence(
|
||||
Note(523.3f, 0.07f, 0.30f), Note(659.3f, 0.07f, 0.30f),
|
||||
Note(783.9f, 0.07f, 0.30f), Note(1046.5f, 0.14f, 0.35f),
|
||||
Note(1318.5f, 0.28f, 0.30f));
|
||||
|
||||
|
||||
static byte[] BuildLevelUpSound() => Sequence(
|
||||
Note(392.0f, 0.08f, 0.28f), Note(523.3f, 0.08f, 0.28f),
|
||||
Note(659.3f, 0.08f, 0.28f), Note(784.0f, 0.24f, 0.32f));
|
||||
|
||||
static byte[] BuildClick() => Sequence(Note(900.0f, 0.03f, 0.12f));
|
||||
|
||||
|
||||
static byte[] BuildAmbientLoop()
|
||||
{
|
||||
// 8-sekündiger weicher Ambient-Pad (A-Moll Klang, sehr leise)
|
||||
int total = SAMPLE_RATE * 8;
|
||||
int fadeLen = SAMPLE_RATE * 2;
|
||||
float[] freqs = { 110f, 146.8f, 165f, 220f, 261.6f };
|
||||
float[] vols = { 0.08f, 0.06f, 0.05f, 0.06f, 0.04f };
|
||||
var samples = new short[total];
|
||||
for (int i = 0; i < total; i++)
|
||||
{
|
||||
double t = (double)i / SAMPLE_RATE;
|
||||
double wave = 0;
|
||||
for (int k = 0; k < freqs.Length; k++)
|
||||
wave += Math.Sin(2 * Math.PI * freqs[k] * t) * vols[k];
|
||||
double env = 1.0;
|
||||
if (i < fadeLen) env = (double)i / fadeLen;
|
||||
if (i > total - fadeLen) env = (double)(total - i) / fadeLen;
|
||||
samples[i] = (short)(wave * env * 32767 * 0.35);
|
||||
}
|
||||
return SamplesToWav(samples);
|
||||
}
|
||||
|
||||
|
||||
// ── PCM-Generierung ──────────────────────────────────────────
|
||||
|
||||
static short[] GenerateSamples(float freq, float durationSec, float volume = 0.35f)
|
||||
{
|
||||
int total = (int)(SAMPLE_RATE * durationSec);
|
||||
int fadeLen = Math.Min(total / 8, 400);
|
||||
var samples = new short[total];
|
||||
for (int i = 0; i < total; i++)
|
||||
{
|
||||
double t = (double)i / SAMPLE_RATE;
|
||||
double wave = Math.Sin(2 * Math.PI * freq * t);
|
||||
double env = 1.0;
|
||||
if (i < fadeLen) env = (double)i / fadeLen;
|
||||
if (i > total - fadeLen) env = (double)(total - i) / fadeLen;
|
||||
samples[i] = (short)(wave * env * volume * 32767);
|
||||
}
|
||||
return samples;
|
||||
}
|
||||
|
||||
static byte[] Note(float freq, float duration, float volume = 0.35f)
|
||||
=> SamplesToWav(GenerateSamples(freq, duration, volume));
|
||||
|
||||
static byte[] Sequence(params byte[][] notes)
|
||||
{
|
||||
using var ms = new MemoryStream();
|
||||
foreach (var wav in notes) ms.Write(wav, 44, wav.Length - 44);
|
||||
return SamplesToWav(BytesToShorts(ms.ToArray()));
|
||||
}
|
||||
|
||||
static byte[] SamplesToWav(short[] samples)
|
||||
{
|
||||
const int ch = 1, bps = 16;
|
||||
int byteRate = SAMPLE_RATE * ch * bps / 8;
|
||||
int align = ch * bps / 8;
|
||||
int dataSize = samples.Length * align;
|
||||
using var ms = new MemoryStream(44 + dataSize);
|
||||
using var bw = new BinaryWriter(ms);
|
||||
bw.Write(new[]{'R','I','F','F'}); bw.Write(36 + dataSize);
|
||||
bw.Write(new[]{'W','A','V','E'});
|
||||
bw.Write(new[]{'f','m','t',' '}); bw.Write(16);
|
||||
bw.Write((short)1); bw.Write((short)ch);
|
||||
bw.Write(SAMPLE_RATE); bw.Write(byteRate);
|
||||
bw.Write((short)align); bw.Write((short)bps);
|
||||
bw.Write(new[]{'d','a','t','a'}); bw.Write(dataSize);
|
||||
foreach (short s in samples) bw.Write(s);
|
||||
return ms.ToArray();
|
||||
}
|
||||
|
||||
static short[] BytesToShorts(byte[] bytes)
|
||||
{
|
||||
var s = new short[bytes.Length / 2];
|
||||
for (int i = 0; i < s.Length; i++) s[i] = BitConverter.ToInt16(bytes, i * 2);
|
||||
return s;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user