using System.Collections.Generic; using System.Globalization; using System.Text; using UnityEngine; namespace TKS { /// /// 소리 재생 창구(2026-11-20 사운드 1차 적용 · 개발요청_사운드_2026-11-20 §2-1). /// 표 = Resources/Audio/sound_events.csv(s_key · e_bus · s_clips · f_vol · f_pitch_min · f_pitch_max · f_min_gap) — 파일 · 음량 · 높낮이 · 간격은 전부 표에서 읽는다(C45). /// 가상 실행(Sim.Active) · Play 가 아닐 때 = 재생하지 않음 · 표에 없는 이름 · 못 찾은 파일 = 경고 1번만(오류 로그 없음). /// 재생 장치 = 씬이 바뀌어도 남는 오브젝트 1개(SoundPlayer · 효과음 소스 묶음 + 배경음악 소스 2개 겹쳐 넘기기). /// public static class Sound { public const string Root = "Audio/"; const string TableFile = "sound_events"; const string PrefSfx = "tks_sound_sfx", PrefBgm = "tks_sound_bgm", PrefMute = "tks_sound_mute"; const string PrefSfxOn = "tks_sound_sfx_on", PrefBgmOn = "tks_sound_bgm_on"; // 설정 팝업 켜기/끄기(2026-11-25 · 음량 값은 그대로 둔다) public class Ev { public string key, bus; public string[] clips; public float vol = 1f, pitchMin = 1f, pitchMax = 1f, gap; } static Dictionary table; static readonly Dictionary clipCache = new Dictionary(); static readonly Dictionary lastAt = new Dictionary(); static readonly Dictionary rise = new Dictionary(); static readonly HashSet warned = new HashSet(); static SoundPlayer player; static int uiFrame = -1; static bool prefsLoaded; static float sfxVol = 1f, bgmVol = 1f; static bool mute; static bool sfxOn = true, bgmOn = true; /// 켜면 실제로 재생한 소리 이름을 에 쌓는다(자동 시험 · 캡처용). public static bool Trace; public static readonly List Traced = new List(); /// Play 진입마다 정적 값 초기화(도메인 리로드를 끈 설정 대비 · BattleEvents.ResetStatics 와 같은 방식). [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] static void ResetStatics() { table = null; clipCache.Clear(); lastAt.Clear(); rise.Clear(); warned.Clear(); player = null; uiFrame = -1; prefsLoaded = false; Trace = false; Traced.Clear(); } // ---------- 음량(PlayerPrefs 저장) ---------- static void LoadPrefs() { if (prefsLoaded) return; prefsLoaded = true; sfxVol = PlayerPrefs.GetFloat(PrefSfx, 1f); bgmVol = PlayerPrefs.GetFloat(PrefBgm, 1f); mute = PlayerPrefs.GetInt(PrefMute, 0) != 0; sfxOn = PlayerPrefs.GetInt(PrefSfxOn, 1) != 0; bgmOn = PlayerPrefs.GetInt(PrefBgmOn, 1) != 0; } /// 효과음 켜기/끄기(설정 팝업 · 끄면 음량 값은 남겨 두고 소리만 0). public static bool SfxOn { get { LoadPrefs(); return sfxOn; } set { LoadPrefs(); sfxOn = value; PlayerPrefs.SetInt(PrefSfxOn, value ? 1 : 0); } } /// 배경음 켜기/끄기(설정 팝업 · 배경음 재생기는 매 프레임 이 값을 읽어 바로 반영). public static bool BgmOn { get { LoadPrefs(); return bgmOn; } set { LoadPrefs(); bgmOn = value; PlayerPrefs.SetInt(PrefBgmOn, value ? 1 : 0); } } /// 실제로 쓰는 효과음 배율 = 전체 음소거 · 켜기 · 음량. public static float SfxLevel { get { LoadPrefs(); return mute || !sfxOn ? 0f : sfxVol; } } /// 실제로 쓰는 배경음 배율 = 전체 음소거 · 켜기 · 음량. public static float BgmLevel { get { LoadPrefs(); return mute || !bgmOn ? 0f : bgmVol; } } public static float SfxVolume { get { LoadPrefs(); return sfxVol; } set { LoadPrefs(); sfxVol = Mathf.Clamp01(value); PlayerPrefs.SetFloat(PrefSfx, sfxVol); } } public static float BgmVolume { get { LoadPrefs(); return bgmVol; } set { LoadPrefs(); bgmVol = Mathf.Clamp01(value); PlayerPrefs.SetFloat(PrefBgm, bgmVol); } } public static bool Mute { get { LoadPrefs(); return mute; } set { LoadPrefs(); mute = value; PlayerPrefs.SetInt(PrefMute, value ? 1 : 0); } } // ---------- 표 ---------- /// 표를 다음 재생 때 다시 읽는다(전투 시작마다 · 다른 표와 같은 방식 = Play 켠 채 교체 확인). public static void Reload() { table = null; } /// Resources/Audio/ 아래 표(# 주석 줄 제외) → 줄 목록 · 오류는 경고 1번. public static List> ReadTable(string file) { var text = StageTable.ResourceText(Root + file); if (text == null) { WarnOnce("table:" + file, "Resources/" + Root + file + ".csv 없음"); return new List>(); } if (text.Length > 0 && text[0] == '') text = text.Substring(1); var sb = new StringBuilder(text.Length); foreach (var line in text.Replace("\r", "").Split('\n')) { if (line.StartsWith("#")) continue; sb.Append(line).Append('\n'); } var errors = new List(); var rows = StageTable.ReadCsv(sb.ToString(), file + ".csv", errors); foreach (var e in errors) WarnOnce("row:" + e, e); return rows; } static Dictionary Table { get { if (table != null) return table; table = new Dictionary(); foreach (var r in ReadTable(TableFile)) { string key = Get(r, "s_key"); if (key.Length == 0) continue; var ev = new Ev { key = key, bus = Get(r, "e_bus"), clips = Get(r, "s_clips").Split(new[] { ';' }, System.StringSplitOptions.RemoveEmptyEntries), vol = Num(r, "f_vol", 1f), pitchMin = Num(r, "f_pitch_min", 1f), pitchMax = Num(r, "f_pitch_max", 1f), gap = Num(r, "f_min_gap", 0f), }; for (int i = 0; i < ev.clips.Length; i++) ev.clips[i] = ev.clips[i].Trim(); table[key] = ev; } return table; } } static string Get(Dictionary r, string k) { string v; return r.TryGetValue(k, out v) && v != null ? v.Trim() : ""; } static float Num(Dictionary r, string k, float def) { float v; return float.TryParse(Get(r, k), NumberStyles.Float, CultureInfo.InvariantCulture, out v) ? v : def; } /// 표의 모든 소리 이름(시험용). public static List Keys() { return new List(Table.Keys); } public static Ev Find(string key) { Ev ev; return key != null && Table.TryGetValue(key, out ev) ? ev : null; } public static bool Has(string key) { return Find(key) != null; } /// Resources/Audio/ 아래 경로(확장자 없음)의 소리 파일 · 없으면 null. public static AudioClip LoadClip(string path) { AudioClip c; if (clipCache.TryGetValue(path, out c) && c != null) return c; c = Resources.Load(Root + path); if (c != null) clipCache[path] = c; return c; } static void WarnOnce(string id, string msg) { if (!warned.Add(id)) return; Debug.LogWarning("[Sound] " + msg); } static bool Blocked { get { return Sim.Active || !Application.isPlaying; } } static Ev Resolve(string key, out AudioClip clip) { clip = null; var ev = Find(key); if (ev == null) { WarnOnce("key:" + key, "표에 없는 소리 이름 「" + key + "」"); return null; } if (ev.clips.Length == 0) return null; // 빈 칸 = 소리 없음 string path = ev.clips[ev.clips.Length == 1 ? 0 : rng.Next(ev.clips.Length)]; clip = LoadClip(path); if (clip == null) { WarnOnce("clip:" + path, "소리 파일 없음 「" + key + "」 → Resources/" + Root + path); return null; } return ev; } /// 소리 전용 난수(게임의 UnityEngine.Random 흐름을 건드리지 않음 = 소리 훅이 전투 결과 · 시험을 바꾸지 않게). static readonly System.Random rng = new System.Random(); static float Pitch(Ev ev) { float lo = Mathf.Min(ev.pitchMin, ev.pitchMax), hi = Mathf.Max(ev.pitchMin, ev.pitchMax); return lo + (float)rng.NextDouble() * (hi - lo); } static bool GapOk(Ev ev) { float now = Time.unscaledTime, last; if (ev.gap > 0f && lastAt.TryGetValue(ev.key, out last) && now - last < ev.gap) return false; lastAt[ev.key] = now; return true; } static SoundPlayer Player { get { if (player == null) player = SoundPlayer.Create(); return player; } } static void Record(string key) { if (Trace) Traced.Add(key); } // ---------- 재생 ---------- /// 효과음 재생(표 e_bus = jingle 이면 · bgm 이면 ). 반환 = 실제로 재생했는가. public static bool Play(string key) { if (Blocked || string.IsNullOrEmpty(key)) return false; var f = Find(key); if (f != null && f.bus == "bgm") return Bgm(key); if (f != null && f.bus == "jingle") return Jingle(key); AudioClip clip; var ev = Resolve(key, out clip); if (ev == null || !GapOk(ev)) return false; if (ev.bus == "ui") uiFrame = Time.frameCount; Player.PlaySfx(clip, ev.vol, Pitch(ev), 0f); Record(key); return true; } /// UI 소리 — 같은 프레임에 이미 UI 소리가 났으면 건너뜀(탭 → 화면 전환처럼 한 번 누름에 소리 하나). public static bool PlayUi(string key) { if (uiFrame == Time.frameCount) return false; return Play(key); } /// UI 소리가 이 프레임에 났는가(공통 버튼 중계가 ui_click 을 낼지 판단). public static bool UiPlayedThisFrame { get { return uiFrame == Time.frameCount; } } /// 배경음악을 잠깐 낮추고 재생(승리 · 패배 · 명장 등용 ★3). public static bool Jingle(string key) { if (Blocked || string.IsNullOrEmpty(key)) return false; AudioClip clip; var ev = Resolve(key, out clip); if (ev == null || !GapOk(ev)) return false; Player.PlaySfx(clip, ev.vol, Pitch(ev), clip.length); Record(key); return true; } /// 배경음악(같은 이름이 이미 나오는 중이면 그대로 · 바뀌면 겹쳐 넘김). public static bool Bgm(string key) { if (Blocked || string.IsNullOrEmpty(key)) return false; if (player != null && player.BgmKey == key) return false; AudioClip clip; var ev = Resolve(key, out clip); if (ev == null) return false; Player.PlayBgm(key, clip, ev.vol); Record(key); return true; } public static void StopBgm() { if (player != null) player.PlayBgm(null, null, 0f); } /// on 이 거짓 → 참으로 바뀌는 순간에만 재생(게이지 치명타 구간 진입 · 명장 등용 문 열림). public static void Rise(string key, bool on) { bool was; rise.TryGetValue(key, out was); rise[key] = on; if (on && !was) Play(key); } /// 지금 나오는 배경음악 이름(없으면 null · 시험용). public static string CurrentBgm { get { return player != null ? player.BgmKey : null; } } } }