using System; using System.Collections; using System.Collections.Generic; using TKS.OutGame; using UnityEngine; using UnityEngine.UI; using static TKS.ScenarioUi; namespace TKS { /// /// 시나리오 이벤트 연출(2026-11-18 PD 「연의전기의 각 시나리오 이벤트를 기획 및 제작 · 1장 도원결의부터」 · 요청서 `연의전기_이벤트_요청서.md` §4). /// 표 = scenario_event.csv(한 줄 = 명령 하나 · s_event_id 묶음 · n_order 순 차례 실행) · 이름표 = scenario_actor.csv · 머리 위 표시 = scenario_emote.csv · /// 값 = scenario_event_config.csv(C45 · 코드에 값 없음) · 말풍선 = ScenarioUi.Say(보스 등장과 같은 PD 확정 시안). /// 발동 = stage_start(판이 놓인 직후 · 학습 안내 전 · Setup = 조작 잠금) · win(승리 직후 · 결과·결말 카드 전) · 처음 깰 때만(다시 하기 = 건너뜀) · 가상 실행·연무장 모드 제외. /// 배우 = slot<N>(학습 판 배치 표 n_slot) · 영웅 id(그 판의 아군·구출 대상) · extra 로 만든 이름(연출 전용 · 끝나면 사라짐). /// 건너뛰기 = 남은 명령을 기다림 없이 끝 상태로 적용(자리 · 숨김 · 바닥 · 기절) → stage_start 는 끝에 판 유닛을 시작 자리·보임으로 되돌림(요청서 약속 3). /// public class ScenarioEvent : MonoBehaviour { static ScenarioEvent current; /// 연출 중인가(테스트·캡처 확인용). public static bool Running { get { return current != null; } } class Actor { public string key; public Unit unit; public GameObject extra; public FrameAnimator anim; public SpriteRenderer shape; public string name; public Color tag; public Vector2 Pos { get { return unit != null ? unit.Position : (Vector2)extra.transform.position; } set { if (unit != null) unit.Position = value; else extra.transform.position = new Vector3(value.x, value.y, 0f); } } public Vector2 Head { get { if (unit != null) return ScenarioUi.Head(unit); return Pos + new Vector2(0f, anim != null ? anim.TopHeight : 0.8f); } } /// 쓰러뜨릴 그림(유닛 = 아트 묶음 · 도형 유닛 = View · 연출 인물 = 그림). public Transform Body { get { if (unit != null) return unit.View == null ? unit.transform : (unit.View.Anim != null ? unit.View.Anim.transform : unit.View.transform); return anim != null ? anim.transform : extra.transform; } } public GameObject Visual { get { return unit != null ? (unit.View != null ? unit.View.gameObject : unit.gameObject) : extra; } } /// 연출 안 방향 = 앞모습(아래 좌·우)만 — 가로 성분으로 좌우만 바꾼다(위로 걸어도 뒷모습으로 돌지 않음 · 뒷모습 = face 명령 back · 2026-11-18 PD). public void Face(Vector2 dir) { if (unit != null) { if (unit.View != null) unit.View.SetFacing(new Vector2(Mathf.Abs(dir.x) > 0.01f ? Mathf.Sign(dir.x) : 0f, -1f)); return; } if (anim != null && Mathf.Abs(dir.x) > 0.01f) anim.Renderer.flipX = dir.x < 0f; } /// 뒷모습(위 좌·우) — face 명령 s_arg back · back_left · back_right 만. public void FaceBack(float x) { if (unit != null && unit.View != null) unit.View.SetFacing(new Vector2(x, 1f)); else if (anim != null && Mathf.Abs(x) > 0.01f) anim.Renderer.flipX = x < 0f; } } BattleManager battle; CameraController cc; BalanceConfig.StageDef stage; string trigger; Action onDone; List> groups; readonly TalkState st = new TalkState(); readonly Dictionary actors = new Dictionary(); readonly Dictionary startPos = new Dictionary(); // 기절 상태 = 연출 사이에 이어짐(stage_start 의 keep 기절 → 그 판 전투 동안 유지 → win 연출의 wake 가 풂) · 유닛이 사라지면 키가 null static readonly Dictionary fainted = new Dictionary(); static readonly Dictionary faintTint = new Dictionary(); static readonly HashSet faintKeep = new HashSet(); readonly List temp = new List(); Vector3 camStart; float viewStart; RectTransform root, fx; Image fade; Image captionBand; Text captionText; Button skipBtn; static readonly Color AllyTag = new Color(0.16f, 0.36f, 0.72f); static readonly Color EnemyTag = new Color(0.75f, 0.16f, 0.12f); static readonly Color ExtraTag = new Color(0.47f, 0.33f, 0.18f); static float C(string k) { return ScenarioData.EvCfg(k); } bool skip { get { return st.Skip; } } /// 켜짐 규칙 = 학습 판과 같음(Auto = 메모리 세이브인 자동 테스트·검증 캡처에서는 꺼짐 · 1-1 을 일반 전투로 쓰는 기존 테스트 보호 · 연출 확인 = ForceOn). public static TutorialMode Mode = TutorialMode.Auto; [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] static void ResetStatics() { Mode = TutorialMode.Auto; current = null; replayChapter = replayStage = 0; fainted.Clear(); faintTint.Clear(); faintKeep.Clear(); } public static bool Enabled { get { return Mode == TutorialMode.ForceOn || (Mode == TutorialMode.Auto && !SaveStore.MemoryOnly); } } /// 이 판 · 이 발동에 틀 연출이 있는가(켜짐 · 표 행 있음 · 처음 깸 · 가상 실행·연무장 아님 · slot 배우가 있으면 학습 판 배치가 켜져 있을 때만). static int replayChapter, replayStage; /// /// 다음에 이 판을 시작할 때 이미 깬 판이어도 연출을 다시 튼다(연의 전기 서장 「도원결의」 출전 = 이야기를 보러 들어옴 · 2026-11-18 PD 「결과물을 보고 피드백」). /// 다른 판이 시작되면 풀린다. /// public static void AllowReplay(int chapter, int stage) { replayChapter = chapter; replayStage = stage; } /// 시나리오 표 열쇠 — 연의 모드 전투 = (편 id, 막) · 출정 = ("", 장, 판) · 그 밖 모드 = null(표 안 씀). public static bool KeyOf(BattleManager bm, BalanceConfig.StageDef stage, out string battleId, out int chapter, out int st) { battleId = ""; chapter = stage != null ? stage.chapter : 0; st = stage != null ? stage.stage : 0; if (bm == null || stage == null) return false; if (bm.Mode == null) return true; var r = bm.Mode.rules; if (r == null || string.IsNullOrEmpty(r.ScenarioBattleId)) return false; battleId = r.ScenarioBattleId; st = r.ScenarioAct; return true; } static List> GroupsFor(BattleManager bm, BalanceConfig.StageDef stage, string trigger, int turn) { string bid; int ch, st; if (!KeyOf(bm, stage, out bid, out ch, out st)) return new List>(); return ScenarioData.Events(bid, ch, st, trigger, turn); } public static bool Wants(BattleManager bm, BalanceConfig.StageDef stage, string trigger, bool cleared, int turn = 0) { if (stage != null && trigger == "stage_start" && (stage.chapter != replayChapter || stage.stage != replayStage)) replayChapter = replayStage = 0; if (cleared && stage != null && stage.chapter == replayChapter && stage.stage == replayStage) cleared = false; if (!Enabled || Sim.Active || bm == null || stage == null || cleared) return false; var g = GroupsFor(bm, stage, trigger, turn); if (g.Count == 0) return false; foreach (var list in g) foreach (var e in list) if ((e.actor.StartsWith("slot") || e.target.StartsWith("slot")) && bm.Tutorial == null) return false; return true; } public static void Begin(BattleManager bm, BalanceConfig.StageDef stage, string trigger, Action onDone, int turn = 0) { Abort(); var cam = FindFirstObjectByType(); if (cam == null || cam.Cam == null) { onDone?.Invoke(); return; } var go = new GameObject("ScenarioEventUI"); var ev = go.AddComponent(); current = ev; ev.battle = bm; ev.cc = cam; ev.stage = stage; ev.trigger = trigger; ev.onDone = onDone; ev.groups = GroupsFor(bm, stage, trigger, turn); ev.Build(); ev.StartCoroutine(ev.Run()); } /// /// 연의 전기 유닛 기본 방향 = 앞모습(아래)으로 판 가운데 쪽을 봄(가운데 왼쪽 = 오른쪽 아래 · 오른쪽 = 왼쪽 아래) /// — 2026-11-18 PD 「연의 전기에서 유닛의 기본 방향은 좌/또는 우측 아래(윗 방향이면 뒷모습만 보여) · 뒷모습이 필요할 때만 위」. /// 시나리오 이벤트 시작 · 연의 전기 전투 시작(ScenarioRules.OnBegin)에 부른다. 전투 중 이동 방향 규칙(PD #1082)은 그대로. /// public static void FaceFrontAll(BattleManager bm) { if (bm == null || Sim.Active) return; foreach (var f in new[] { Faction.Player, Faction.Enemy }) foreach (var u in bm.AliveUnits(f)) { if (u.View == null) continue; // 가장 가까운 상대편 쪽(가로) — 없으면 판 가운데 쪽 · 2026-11-18 PD 「장비가 적들을 바라보지 않고 엉뚱한 방향」 Unit near = null; float best = float.MaxValue; foreach (var o in bm.AliveUnits(f == Faction.Player ? Faction.Enemy : Faction.Player)) { float dd = (o.Position - u.Position).sqrMagnitude; if (dd < best) { best = dd; near = o; } } float dx = near != null ? near.Position.x - u.Position.x : -u.Position.x; u.View.SetFacing(new Vector2(Mathf.Abs(dx) > 0.05f ? Mathf.Sign(dx) : (u.View.FacingLeft ? -1f : 1f), -1f)); } } Actor lastSpeaker; /// 말할 때 = 화자와 앞 화자가 서로 마주 봄(앞모습 · 가로만) · 앞 화자가 없으면 가장 가까운 상대편 쪽. void FaceTalk(Actor a) { if (a == null) return; var other = lastSpeaker != null && lastSpeaker != a && lastSpeaker.Visual != null && lastSpeaker.Visual.activeInHierarchy ? lastSpeaker : null; if (other != null) { float dx = other.Pos.x - a.Pos.x; if (Mathf.Abs(dx) > 0.05f) { a.Face(new Vector2(dx, 0f)); other.Face(new Vector2(-dx, 0f)); } } else if (a.unit != null) { Unit near = null; float best = float.MaxValue; foreach (var o in battle.AliveUnits(a.unit.Faction == Faction.Player ? Faction.Enemy : Faction.Player)) { float dd = (o.Position - a.Pos).sqrMagnitude; if (dd < best) { best = dd; near = o; } } if (near != null && Mathf.Abs(near.Position.x - a.Pos.x) > 0.05f) a.Face(new Vector2(near.Position.x - a.Pos.x, 0f)); } lastSpeaker = a; } /// 지금 실행 중인 줄(테스트·캡처 확인용 · 끝나면 int.MaxValue). public static string CurrentId = ""; public static int CurrentOrder; /// 테스트·캡처: 화면 누름 1회. public static void TapForTest() { if (current != null) current.st.Taps++; } /// 테스트: 건너뛰기 버튼. public static void SkipForTest() { if (current != null) current.st.Skip = true; } /// 진행 중 연출을 바로 치움(전투 재시작 · 월드맵 복귀). public static void Abort() { if (current == null) return; current.Cleanup(false); Destroy(current.gameObject); current = null; } // ---------- 화면 ---------- void Build() { UiLayer.Root(gameObject, cc.Cam, 460, 0.38f, UiLayer.Reference, UiRate.Event); root = (RectTransform)transform; var catcher = Full("Tap", root, null, new Color(0f, 0f, 0f, 0f)); catcher.raycastTarget = true; catcher.gameObject.AddComponent