using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using NUnit.Framework; using TKS.OutGame; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.TestTools; namespace TKS.Tests { /// /// 슬링샷 충돌 손맛 실측(PD 2026-11-20 「당구·알까기처럼 각도·힘 조절로 튕기고 밀치는 재미」) — 판정이 아니라 측정 도구(Explicit): /// 정해 둔 장면(정면 · 반 두께 · 얇게 · 약하게 · 뭉친 적 · 창병 · 기병 · 궁병 이동 · 아군 · 벽)을 실제 속도로 쏘고 /// 유닛마다 이동 거리 · 방향(쏜 방향 기준 각도) · 최고 속도 · 움직인 시간 · 궤적을 Temp/SlingProbe/<라벨>.json 으로 남긴다. /// 라벨 = Temp/SlingProbe/label.txt(없으면 run) · 그림 = shots.txt 에 장면 이름을 적으면 그 장면만 0.08초마다 화면 캡처. /// public class SlingFeelRunner : MonoBehaviour { BattleManager bm; BalanceConfig cfg; /// Play 중 에디터 명령(script eval)으로 부른다: 전투 장면을 열고 실측을 끝까지 돌린 뒤 Temp/SlingProbe/done.txt 를 남긴다. public static void Launch() { var go = new GameObject("SlingFeelRunner"); DontDestroyOnLoad(go); go.AddComponent().StartCoroutine(go.GetComponent().LaunchRoutine()); } /// 실제 스테이지를 자동으로 플레이(아군도 적 AI 판단으로 쏨) — 멈춤·오류·유닛 이동량을 Temp/SlingProbe/battle_장_판.txt 로 남긴다. public static void LaunchBattle(int chapter, int stage, int turns) { var go = new GameObject("SlingFeelRunner"); DontDestroyOnLoad(go); var r = go.AddComponent(); r.StartCoroutine(r.BattleRoutine(chapter, stage, turns)); } IEnumerator BattleRoutine(int chapter, int stage, int turns) { Directory.CreateDirectory(Dir); string done = Path.Combine(Dir, "done.txt"); if (File.Exists(done)) File.Delete(done); var log = new List(); int errors = 0; Application.LogCallback onLog = (msg, stack, type) => { if (type != LogType.Error && type != LogType.Exception) return; errors++; if (errors <= 8) log.Add("ERROR " + msg + " | " + (stack ?? "").Split('\n')[0]); }; Application.logMessageReceived += onLog; WorldProgress.Reset(); SaveStore.UseMemory(true); SceneManager.LoadScene("Battle"); yield return null; yield return null; bm = BattleManager.Instance; var wm = WorldMapScreen.Instance; if (wm != null && wm.HasData) wm.EnterStage(chapter, stage); yield return null; Time.timeScale = 4f; float t0 = Time.realtimeSinceStartup; while (bm.Phase != BattlePhase.PlayerTurn && Time.realtimeSinceStartup - t0 < 30f) yield return null; log.Add("start phase=" + bm.Phase + " players=" + bm.AliveCount(Faction.Player) + " enemies=" + bm.AliveCount(Faction.Enemy)); bool stuck = false; int actions = 0, movedActions = 0; float pushSum = 0f, pushMax = 0f; for (int turn = 1; turn <= turns && !stuck; turn++) { int guard = 0; while (bm.Phase == BattlePhase.PlayerTurn && guard++ < 24) { Unit u = null; foreach (var c in bm.AliveUnits(Faction.Player)) if (bm.CanAct(c)) { u = c; break; } if (u == null) { bm.OnEmptyTap(); break; } var target = EnemyAI.Decide(u, bm.AliveUnits(Faction.Enemy), 1f, float.PositiveInfinity, bm.Rng, bm.Board, bm.Config); if (!target.HasValue) break; var before = new Dictionary(); foreach (var x in bm.Units) if (x != null && x.IsAlive) before[x] = x.Position; if (!bm.RequestPlayerAction(u, target.Value)) break; float w0 = Time.realtimeSinceStartup; while (bm.Phase == BattlePhase.Resolving) { if (Time.realtimeSinceStartup - w0 > 20f) { stuck = true; break; } yield return null; } if (stuck) { log.Add("STUCK resolving · " + u.DisplayName); break; } actions++; float best = 0f; int movedOthers = 0; foreach (var kv in before) { if (kv.Key == null || kv.Key == u) continue; float d = Vector2.Distance(kv.Key.Position, kv.Value); if (d > 0.05f) { movedOthers++; pushSum += d; best = Mathf.Max(best, d); } } if (movedOthers > 0) movedActions++; pushMax = Mathf.Max(pushMax, best); log.Add("t" + turn + " " + u.Type + " " + u.DisplayName + " → 밀린 유닛 " + movedOthers + " · 최대 " + F(best) + " | " + bm.LastMessage); if (bm.Phase == BattlePhase.StageClear || bm.Phase == BattlePhase.Defeat) break; } float e0 = Time.realtimeSinceStartup; while (bm.Phase == BattlePhase.EnemyTurn || bm.Phase == BattlePhase.Resolving) { if (Time.realtimeSinceStartup - e0 > 40f) { stuck = true; break; } yield return null; } if (stuck) log.Add("STUCK enemy turn " + turn + " phase=" + bm.Phase); log.Add("turn " + turn + " end · phase=" + bm.Phase + " players=" + bm.AliveCount(Faction.Player) + " enemies=" + bm.AliveCount(Faction.Enemy)); if (bm.Phase == BattlePhase.StageClear || bm.Phase == BattlePhase.Defeat) break; } // 겹친 유닛(충돌 처리 뒤에도 몸이 포개진 쌍) 점검 int overlaps = 0; var alive = new List(); foreach (var x in bm.Units) if (x != null && x.IsAlive) alive.Add(x); for (int i = 0; i < alive.Count; i++) for (int j = i + 1; j < alive.Count; j++) if (Vector2.Distance(alive[i].Position, alive[j].Position) < (alive[i].Radius + alive[j].Radius) * 0.8f) overlaps++; log.Insert(0, "SUMMARY stage " + chapter + "-" + stage + " · 행동 " + actions + " · 다른 유닛이 밀린 행동 " + movedActions + " · 밀린 거리 합 " + F(pushSum) + " · 최대 " + F(pushMax) + " · 오류 " + errors + " · 멈춤 " + (stuck ? "있음" : "없음") + " · 겹친 쌍 " + overlaps + " · 끝 phase=" + bm.Phase); Application.logMessageReceived -= onLog; Time.timeScale = 1f; File.WriteAllLines(Path.Combine(Dir, "battle_" + chapter + "_" + stage + ".txt"), log.ToArray(), new UTF8Encoding(false)); File.WriteAllText(done, "ok"); Destroy(gameObject); } /// 원거리 화살표 끝 규칙의 조준 표시 확인: 궁병을 짧게(적에 닿기 전) · 길게(적에 닿게) 끄는 상태를 만들어 화면을 찍고 판정을 Temp/SlingProbe/aim_tip.txt 로 남긴다. public static void LaunchAim() { var go = new GameObject("SlingFeelRunner"); DontDestroyOnLoad(go); var r = go.AddComponent(); r.StartCoroutine(r.AimRoutine()); } IEnumerator AimRoutine() { Directory.CreateDirectory(Dir); string done = Path.Combine(Dir, "done.txt"); if (File.Exists(done)) File.Delete(done); yield return SetUp(); yield return Fresh(); var log = new List(); var cam = Camera.main; Vector2 c = cam != null ? (Vector2)cam.transform.position : Vector2.zero; var arc = bm.SpawnUnit(UnitType.Archer, Faction.Player, c + new Vector2(0f, -4f), "궁병"); var foe = bm.SpawnUnit(UnitType.Infantry, Faction.Enemy, c + new Vector2(1f, 2f), "적"); yield return null; var sling = bm.Sling; var tp = typeof(SlingshotInput); var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic; sling.Select(arc); tp.GetField("dragging", flags).SetValue(sling, true); tp.GetField("aimArmed", flags).SetValue(sling, true); var hold = tp.GetMethod("OnHold", flags); Vector2 dir = ((Vector2)foe.Position - (Vector2)arc.Position).normalized; log.Add("RangedTip=" + AimRules.RangedTip + " · 사거리 " + F(SkillMods.Range(arc)) + " · 이동 범위 " + F(SkillMods.SlingMax(arc)) + " · 적까지 " + F(Vector2.Distance(arc.Position, foe.Position))); float[] pulls = { 1.6f, 3.6f }; // 손가락을 유닛에서 뗀 거리(월드) — 짧게 · 길게 for (int i = 0; i < pulls.Length; i++) { Vector2 finger = (Vector2)arc.Position + dir * pulls[i]; for (int k = 0; k < 3; k++) { hold.Invoke(sling, new object[] { finger }); yield return null; } var tip = tp.GetField("tipTarget", flags).GetValue(sling) as Unit; Vector2 t = (Vector2)tp.GetField("currentTarget", flags).GetValue(sling); float aimLen = Vector2.Distance(t, arc.Position); bool move = sling.ReleaseMovesOnly(arc, ref t); log.Add("끌기 " + F(pulls[i]) + " → 조준 거리 " + F(aimLen) + " · 강조된 적 " + (tip != null ? tip.DisplayName : "없음") + " · 놓으면 " + (move ? "이동(" + F(Vector2.Distance(t, arc.Position)) + ")" : "사격")); ScreenCapture.CaptureScreenshot(Path.Combine(Dir, "aim_tip_" + i + ".png")); yield return null; yield return null; } sling.HidePreview(); File.WriteAllLines(Path.Combine(Dir, "aim_tip.txt"), log.ToArray(), new UTF8Encoding(false)); File.WriteAllText(done, "ok"); Destroy(gameObject); } /// /// 조준 중 카메라 확인(PD 2026-11-21 「전장이 한눈에」): 실제 스테이지에서 다음 유닛에 초점 → 누름 → 30 % · 100 % 당김을 입력 코드 그대로 밟아 /// 화면을 찍고(cam_장_판_단계.png) 화면 높이 · 정보창에 가려지지 않은 곳에 보이는 적 수를 Temp/SlingProbe/cam_장_판.txt 로 남긴다. /// public static void LaunchCam(int chapter, int stage, int skipTurns) { var go = new GameObject("SlingFeelRunner"); DontDestroyOnLoad(go); var r = go.AddComponent(); r.StartCoroutine(r.CamRoutine(chapter, stage, skipTurns)); } IEnumerator CamRoutine(int chapter, int stage, int skipTurns) { Directory.CreateDirectory(Dir); string done = Path.Combine(Dir, "done.txt"); if (File.Exists(done)) File.Delete(done); WorldProgress.Reset(); SaveStore.UseMemory(true); SceneManager.LoadScene("Battle"); yield return null; yield return null; bm = BattleManager.Instance; var wm = WorldMapScreen.Instance; if (wm != null && wm.HasData) wm.EnterStage(chapter, stage); yield return null; float t0 = Time.realtimeSinceStartup; while (bm.Phase != BattlePhase.PlayerTurn && Time.realtimeSinceStartup - t0 < 30f) yield return null; // 몇 턴 자동으로 진행해 서로 다가선 장면을 만든다 Time.timeScale = 4f; for (int turn = 0; turn < skipTurns; turn++) { int guard = 0; while (bm.Phase == BattlePhase.PlayerTurn && guard++ < 12) { Unit a = null; foreach (var c in bm.AliveUnits(Faction.Player)) if (bm.CanAct(c)) { a = c; break; } if (a == null) { bm.OnEmptyTap(); break; } var tg = EnemyAI.Decide(a, bm.AliveUnits(Faction.Enemy), 1f, float.PositiveInfinity, bm.Rng, bm.Board, bm.Config); if (!tg.HasValue || !bm.RequestPlayerAction(a, tg.Value)) break; while (bm.Phase == BattlePhase.Resolving) yield return null; } float e0 = Time.realtimeSinceStartup; while ((bm.Phase == BattlePhase.EnemyTurn || bm.Phase == BattlePhase.Resolving) && Time.realtimeSinceStartup - e0 < 40f) yield return null; } Time.timeScale = 1f; var log = new List(); var sling = bm.Sling; var tp = typeof(SlingshotInput); var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic; var cam = Camera.main; var ctrl = cam.GetComponent(); sling.Select(null); tp.GetField("lastActor", flags).SetValue(sling, null); tp.GetMethod("FocusNext", flags).Invoke(sling, null); // 행동이 끝난 뒤와 같은 흐름: 다음 유닛 초점 + 선택 yield return new WaitForSecondsRealtime(1.2f); Unit u = tp.GetField("selected", flags).GetValue(sling) as Unit; if (u == null || bm.Phase != BattlePhase.PlayerTurn) { File.WriteAllText(done, "ERROR 선택된 유닛 없음 · phase " + bm.Phase); Destroy(gameObject); yield break; } System.Func state = () => { float h = ctrl.ViewHeight, w = h * cam.aspect; Vector2 c = cam.transform.position; int seen = 0, all = 0; foreach (var e in bm.AliveUnits(Faction.Enemy)) { all++; Vector2 p = e.Position; if (Mathf.Abs(p.x - c.x) <= w * 0.5f - 0.3f && p.y >= c.y - h * 0.5f + h * 0.09f + 0.3f && p.y <= c.y + h * 0.5f - h * 0.25f - 0.3f) seen++; } return "화면 높이 " + F(h) + " · 보이는 적 " + seen + "/" + all + " · 유닛 화면 위치(아래에서) " + F((u.Position.y - (c.y - h * 0.5f)) / h); }; log.Add(u.Type + " " + u.DisplayName + " · 평소: " + state()); ScreenCapture.CaptureScreenshot(Path.Combine(Dir, "cam_" + chapter + "_" + stage + "_0.png")); yield return null; yield return null; // 누름(입력 코드 그대로) → 적 쪽으로 30 % · 100 % 당김 Vector2 screen = cam.WorldToScreenPoint(new Vector3(u.Position.x, u.Position.y, 0f)); tp.GetMethod("OnPress", flags).Invoke(sling, new object[] { screen }); tp.GetField("aimArmed", flags).SetValue(sling, true); yield return new WaitForSecondsRealtime(0.6f); Unit near = null; foreach (var e in bm.AliveUnits(Faction.Enemy)) if (near == null || Vector2.Distance(e.Position, u.Position) < Vector2.Distance(near.Position, u.Position)) near = e; Vector2 dir = near != null ? ((Vector2)near.Position - (Vector2)u.Position).normalized : Vector2.up; var hold = tp.GetMethod("OnHold", flags); float gain = IbUi.Num("drag_gain", 2f), start = u.Radius * bm.Config.aimStartRadiusRatio; int shot = 1; foreach (var k in new[] { 0.3f, 1f }) { Vector2 finger = (Vector2)u.Position + dir * (start + sling.AimMax(u) * k / gain); float until = Time.realtimeSinceStartup + 1.0f; while (Time.realtimeSinceStartup < until) { hold.Invoke(sling, new object[] { finger }); yield return null; } log.Add("당김 " + Mathf.RoundToInt(k * 100f) + " %: " + state()); ScreenCapture.CaptureScreenshot(Path.Combine(Dir, "cam_" + chapter + "_" + stage + "_" + shot + ".png")); shot++; yield return null; yield return null; } // 당김을 다시 줄이면 가까워지는가 · 놓은 뒤 평소 높이로 돌아오는가(PD 2026-11-21 「한번 줌아웃 되면 고정되어 불편」) { Vector2 finger = (Vector2)u.Position + dir * (start + sling.AimMax(u) * 0.3f / gain); float until = Time.realtimeSinceStartup + 1.0f; while (Time.realtimeSinceStartup < until) { hold.Invoke(sling, new object[] { finger }); yield return null; } log.Add("다시 30 % 로 줄임: " + state()); float baseH = (float)tp.GetField("pullBaseH", flags).GetValue(sling); Vector2 us = cam.WorldToScreenPoint(new Vector3(u.Position.x, u.Position.y, 0f)); Vector2 rel = us + (finger - (Vector2)u.Position) * (cam.pixelHeight / Mathf.Max(0.01f, baseH)); tp.GetMethod("OnRelease", flags).Invoke(sling, new object[] { rel }); yield return new WaitForSecondsRealtime(0.6f); log.Add("놓고 0.6초 뒤: 화면 높이 " + F(ctrl.ViewHeight)); yield return new WaitForSecondsRealtime(3.0f); log.Add("놓고 3.6초 뒤: 화면 높이 " + F(ctrl.ViewHeight) + " · phase " + bm.Phase); } sling.HidePreview(); File.WriteAllLines(Path.Combine(Dir, "cam_" + chapter + "_" + stage + ".txt"), log.ToArray(), new UTF8Encoding(false)); File.WriteAllText(done, "ok"); Destroy(gameObject); } /// /// 적 AI 감사(PD 2026-11-21 「같은 편을 타겟팅 · 공격 가능한데 공격하지 않음」): 스테이지를 자동으로 진행하며 아군 차례가 올 때마다 「지금 적이 움직인다면」을 전원 평가해 /// 공격할 수 있었는데 최선이 공격이 아닌 경우 · 최선이 같은 편을 해치는 경우 · 차선 무작위 선택(정확도 미달)에서 생기는 헛수를 센다 → Temp/SlingProbe/ai_라벨.txt 에 누적. /// public static void LaunchAi(string label, int chapter, int stage, int turns) { var go = new GameObject("SlingFeelRunner"); DontDestroyOnLoad(go); var r = go.AddComponent(); r.StartCoroutine(r.AiRoutine(label, chapter, stage, turns)); } bool CanHit(Unit e, List players) { bool ranged = UnitTypeInfo.IsRanged(e.Type); float reach = ranged ? SkillMods.Range(e) : SkillMods.SlingMax(e); foreach (var p in players) { Vector2 v = p.Position - e.Position; float d = v.magnitude; if (d < 1e-3f || d - e.Radius * Combat.CastRadiusScale - p.Radius > reach) continue; float hd; var first = Combat.FirstUnitOnPath(e, e.Position, v / d, d, out hd); if (first == p && Combat.FreeTravel(e, e.Position, v / d, d, false, false) >= hd - 0.05f) return true; // 장애물·벽에 먼저 막히지 않음 } return false; } IEnumerator AiRoutine(string label, int chapter, int stage, int turns) { Directory.CreateDirectory(Dir); string done = Path.Combine(Dir, "done.txt"); if (File.Exists(done)) File.Delete(done); WorldProgress.Reset(); SaveStore.UseMemory(true); SceneManager.LoadScene("Battle"); yield return null; yield return null; bm = BattleManager.Instance; var wm = WorldMapScreen.Instance; if (wm != null && wm.HasData) wm.EnterStage(chapter, stage); yield return null; float t0 = Time.realtimeSinceStartup; while (bm.Phase != BattlePhase.PlayerTurn && Time.realtimeSinceStartup - t0 < 30f) yield return null; Time.timeScale = 6f; int evals = 0, can = 0, bestAtk = 0, missed = 0, bestOwn = 0, bestBump = 0, picks = 0, pickNoAtk = 0, pickOwn = 0, pickBump = 0, idleFar = 0; float dmgSum = 0f, msSum = 0f, msMax = 0f; int candSum = 0; var examples = new List(); float acc = bm.Stage.aiAccuracy, aggro = bm.Stage.aiAggroRange; for (int turn = 1; turn <= turns; turn++) { if (bm.Phase != BattlePhase.PlayerTurn) break; // 감사: 지금 장면에서 적 전원 평가(가상 실행 · 상태는 되돌려짐) var players = bm.AliveUnits(Faction.Player); int enemyCount = bm.AliveCount(Faction.Enemy); foreach (var e in bm.AliveUnits(Faction.Enemy)) { float nd = float.MaxValue; foreach (var p in players) nd = Mathf.Min(nd, Vector2.Distance(e.Position, p.Position)); if (nd > aggro) { idleFar++; continue; } List list; var best = TacticalAI.Evaluate(bm, e, enemyCount, out list); if (best == null) continue; evals++; msSum += best.Ms; msMax = Mathf.Max(msMax, best.Ms); candSum += best.Candidates; bool canHit = CanHit(e, players); if (canHit) can++; bool atk = best.PlayerDmg > 0f; if (atk) { bestAtk++; dmgSum += best.PlayerDmg; } if (canHit && !atk) { missed++; if (examples.Count < 6) examples.Add("놓침 t" + turn + " " + e.Type + " " + e.DisplayName + " @" + e.Position + " 최선=" + best.Why + " 점수 " + F(best.Score)); } if (best.OwnDmg > 0f) { bestOwn++; if (examples.Count < 6) examples.Add("같은 편 피해 t" + turn + " " + e.Type + " " + e.DisplayName + " 최선=" + best.Why + " 같은 편 피해 " + best.OwnDmg); } if (best.AllyBumps > 0) bestBump++; // 정확도 미달일 때 고르는 차선(게임의 Choose 와 같은 거르기 → 상위 3) var pool = new List(); foreach (var x in list) if (best.PlayerDmg > 0f ? x.PlayerDmg > 0f : x.AllyBumps == 0) pool.Add(x); if (pool.Count == 0) pool = list; int n = Mathf.Min(3, pool.Count); for (int i = 0; i < n; i++) { picks++; if (canHit && pool[i].PlayerDmg <= 0f) pickNoAtk++; if (pool[i].OwnDmg > 0f) pickOwn++; if (pool[i].AllyBumps > 0) pickBump++; } } // 한 턴 진행(아군 = 자동) int guard = 0; while (bm.Phase == BattlePhase.PlayerTurn && guard++ < 12) { Unit a = null; foreach (var c in bm.AliveUnits(Faction.Player)) if (bm.CanAct(c)) { a = c; break; } if (a == null) { bm.OnEmptyTap(); break; } var tg = EnemyAI.Decide(a, bm.AliveUnits(Faction.Enemy), 1f, float.PositiveInfinity, bm.Rng, bm.Board, bm.Config); if (!tg.HasValue || !bm.RequestPlayerAction(a, tg.Value)) break; while (bm.Phase == BattlePhase.Resolving) yield return null; } float e0 = Time.realtimeSinceStartup; while ((bm.Phase == BattlePhase.EnemyTurn || bm.Phase == BattlePhase.Resolving) && Time.realtimeSinceStartup - e0 < 60f) yield return null; } Time.timeScale = 1f; var sb = new StringBuilder(); sb.Append("stage ").Append(chapter).Append('-').Append(stage).Append(" 정확도 ").Append(F(acc)).Append(" 교전범위 ").Append(F(aggro)) .Append(" | 평가 ").Append(evals).Append(" · 교전 밖 대기 ").Append(idleFar) .Append(" | 공격 가능 ").Append(can).Append(" · 최선이 공격 ").Append(bestAtk).Append(" · 놓침 ").Append(missed) .Append(" | 최선이 같은 편 피해 ").Append(bestOwn).Append(" · 같은 편 밀침 ").Append(bestBump) .Append(" | 차선 ").Append(picks).Append(" 중 헛수 ").Append(pickNoAtk).Append(" · 같은 편 피해 ").Append(pickOwn).Append(" · 같은 편 밀침 ").Append(pickBump) .Append(" | 최선 평균 피해 ").Append(F(bestAtk > 0 ? dmgSum / bestAtk : 0f)).Append(" · 평가 시간 평균 ").Append(F(evals > 0 ? msSum / evals : 0f)).Append("ms 최대 ").Append(F(msMax)) .Append("ms · 후보 평균 ").Append(F(evals > 0 ? (float)candSum / evals : 0f)).Append(" · 끝 ").Append(bm.Phase).Append('\n'); foreach (var x in examples) sb.Append(" ").Append(x).Append('\n'); File.AppendAllText(Path.Combine(Dir, "ai_" + label + ".txt"), sb.ToString(), new UTF8Encoding(false)); File.WriteAllText(done, "ok"); Destroy(gameObject); } IEnumerator LaunchRoutine() { Directory.CreateDirectory(Dir); string done = Path.Combine(Dir, "done.txt"); if (File.Exists(done)) File.Delete(done); yield return SetUp(); string err = ""; var it = Measure(); while (true) { bool more; try { more = it.MoveNext(); } catch (System.Exception e) { err = e.ToString(); break; } if (!more) break; yield return it.Current; } Time.timeScale = 1f; File.WriteAllText(done, err.Length > 0 ? "ERROR " + err : "ok"); Destroy(gameObject); } class Track { public Unit U; public string Name; public Vector2 Start; public List Samples = new List(); // x · y · 시각 } public IEnumerator SetUp() { WorldProgress.Reset(); SaveStore.UseMemory(true); SceneManager.LoadScene("Battle"); yield return null; yield return null; bm = BattleManager.Instance; var wm = WorldMapScreen.Instance; if (wm != null && wm.HasData) wm.EnterStage(0, 0); yield return null; cfg = bm.Config; Time.timeScale = 1f; } IEnumerator Fresh() { bm.StopAllCoroutines(); bm.ClearUnits(); bm.ForcePhase(BattlePhase.PlayerTurn); yield return null; yield return null; } static string Dir { get { return Path.Combine(Path.GetDirectoryName(Application.dataPath), "Temp", "SlingProbe"); } } static string F(float v) { return v.ToString("0.###", CultureInfo.InvariantCulture); } struct Spawn { public UnitType Type; public Faction Side; public Vector2 Pos; public string Name; } static Spawn S(UnitType t, Faction f, float x, float y, string n) { return new Spawn { Type = t, Side = f, Pos = new Vector2(x, y), Name = n }; } IEnumerator Shot(StringBuilder sb, HashSet capture, string id, string desc, Vector2 aimDir, float launchRatio, bool moveOnly, params Spawn[] spawns) { yield return Fresh(); var tracks = new List(); foreach (var s in spawns) { var u = bm.SpawnUnit(s.Type, s.Side, s.Pos, s.Name); tracks.Add(new Track { U = u, Name = s.Name, Start = s.Pos }); } yield return null; var actor = tracks[0].U; aimDir = aimDir.normalized; float launch = SkillMods.SlingMax(actor) * launchRatio; Vector2 target = actor.Position + aimDir * launch; bool shoot = capture.Contains(id); if (shoot) { var cam = Camera.main; if (cam != null) { Vector2 c = actor.Position + aimDir * 3f; cam.transform.position = new Vector3(c.x, c.y, cam.transform.position.z); } } var o = new ActionOutcome(); bool done = false; float t0 = Time.time; bm.StartCoroutine(Run(actor, target, moveOnly, o, () => done = true)); int frame = 0; float nextShot = 0f; int shotNo = 0; float settle = -1f; while (true) { float t = Time.time - t0; foreach (var tr in tracks) { if (tr.U == null) continue; Vector2 p = tr.U.transform.position; tr.Samples.Add(new Vector3(p.x, p.y, t)); } if (shoot && t >= nextShot && shotNo < 40) { ScreenCapture.CaptureScreenshot(Path.Combine(Dir, id + "_" + shotNo.ToString("00") + ".png")); shotNo++; nextShot += 0.08f; } if (done) { if (settle < 0f) settle = t; if (t - settle > 0.25f) break; } if (++frame > 3000) break; yield return null; } sb.Append(" {\"id\":\"").Append(id).Append("\",\"desc\":\"").Append(desc).Append("\",\"launch\":").Append(F(launch)) .Append(",\"aim\":[").Append(F(aimDir.x)).Append(',').Append(F(aimDir.y)).Append("],\"attacked\":").Append(o.Attacked.Count) .Append(",\"chains\":").Append(o.Chains).Append(",\"dmg\":").Append(o.DamageDealt).Append(",\"time\":").Append(F(settle)) .Append(",\"notes\":\"").Append(string.Join(" / ", o.Notes).Replace("\"", "'")).Append("\",\"units\":[\n"); for (int i = 0; i < tracks.Count; i++) { var tr = tracks[i]; var sm = tr.Samples; Vector2 end = sm.Count > 0 ? (Vector2)sm[sm.Count - 1] : tr.Start; Vector2 disp = end - tr.Start; float path = 0f, vmax = 0f, tFirst = -1f, tLast = -1f; for (int k = 1; k < sm.Count; k++) { float d = Vector2.Distance(sm[k], sm[k - 1]); float dt = sm[k].z - sm[k - 1].z; if (d > 1e-4f) { path += d; if (tFirst < 0f) tFirst = sm[k - 1].z; tLast = sm[k].z; if (dt > 1e-5f) vmax = Mathf.Max(vmax, d / dt); } } float ang = disp.sqrMagnitude > 1e-6f ? Vector2.SignedAngle(aimDir, disp) : 0f; sb.Append(" {\"name\":\"").Append(tr.Name).Append("\",\"side\":\"").Append(tr.U != null ? tr.U.Faction.ToString() : "?") .Append("\",\"alive\":").Append(tr.U != null && tr.U.IsAlive ? "true" : "false") .Append(",\"start\":[").Append(F(tr.Start.x)).Append(',').Append(F(tr.Start.y)).Append("],\"end\":[").Append(F(end.x)).Append(',').Append(F(end.y)) .Append("],\"disp\":").Append(F(disp.magnitude)).Append(",\"angle\":").Append(F(ang)).Append(",\"path\":").Append(F(path)) .Append(",\"vmax\":").Append(F(vmax)).Append(",\"t0\":").Append(F(tFirst)).Append(",\"t1\":").Append(F(tLast)).Append(",\"pts\":["); int step = Mathf.Max(1, sm.Count / 60); bool first = true; for (int k = 0; k < sm.Count; k += step) { if (!first) sb.Append(','); first = false; sb.Append('[').Append(F(sm[k].x)).Append(',').Append(F(sm[k].y)).Append(',').Append(F(sm[k].z)).Append(']'); } sb.Append("]}").Append(i < tracks.Count - 1 ? ",\n" : "\n"); } sb.Append(" ]},\n"); } IEnumerator Run(Unit u, Vector2 target, bool moveOnly, ActionOutcome o, System.Action onDone) { yield return bm.ResolveForTest(u, target, moveOnly, o); onDone(); } public IEnumerator Measure() { Directory.CreateDirectory(Dir); string labelFile = Path.Combine(Dir, "label.txt"); string label = File.Exists(labelFile) ? File.ReadAllText(labelFile).Trim() : "run"; var capture = new HashSet(); string shotsFile = Path.Combine(Dir, "shots.txt"); if (File.Exists(shotsFile)) foreach (var l in File.ReadAllLines(shotsFile)) if (l.Trim().Length > 0) capture.Add(l.Trim()); var only = new HashSet(); string onlyFile = Path.Combine(Dir, "only.txt"); if (File.Exists(onlyFile)) foreach (var l in File.ReadAllLines(onlyFile)) if (l.Trim().Length > 0) only.Add(l.Trim()); var sb = new StringBuilder(); sb.Append("{\"label\":\"").Append(label).Append("\",\"shots\":[\n"); Vector2 up = Vector2.up; const UnitType I = UnitType.Infantry, C = UnitType.Cavalry, A = UnitType.Archer, P = UnitType.Spear, T = UnitType.Strategist; const Faction Me = Faction.Player, Foe = Faction.Enemy; System.Func on = id => only.Count == 0 || only.Contains(id); // 보병 → 적 보병: 두께(정면 · 반 · 얇게) · 세기(가득 · 절반) · 거리(먼 적) if (on("inf_full")) yield return Shot(sb, capture, "inf_full", "보병 정면 가득", up, 1f, false, S(I, Me, 0f, -3f, "보병"), S(I, Foe, 0f, 0f, "적")); if (on("inf_half")) yield return Shot(sb, capture, "inf_half", "보병 반 두께 가득", up, 1f, false, S(I, Me, 0f, -3f, "보병"), S(I, Foe, 0.45f, 0f, "적")); if (on("inf_thin")) yield return Shot(sb, capture, "inf_thin", "보병 얇게 가득", up, 1f, false, S(I, Me, 0f, -3f, "보병"), S(I, Foe, 0.72f, 0f, "적")); if (on("inf_soft")) yield return Shot(sb, capture, "inf_soft", "보병 정면 절반 세기", up, 0.5f, false, S(I, Me, 0f, -3f, "보병"), S(I, Foe, 0f, 0f, "적")); if (on("inf_far")) yield return Shot(sb, capture, "inf_far", "보병 정면 가득 · 먼 적(6)", up, 1f, false, S(I, Me, 0f, -3f, "보병"), S(I, Foe, 0f, 3f, "적")); // 뭉친 적(삼각 배치) · 두 번째 적으로 꺾어 치기(캐롬) if (on("inf_rack")) yield return Shot(sb, capture, "inf_rack", "보병 → 뭉친 적 3", up, 1f, false, S(I, Me, 0f, -3f, "보병"), S(I, Foe, 0f, 0f, "적1"), S(I, Foe, -0.5f, 0.9f, "적2"), S(I, Foe, 0.5f, 0.9f, "적3")); if (on("inf_carom")) yield return Shot(sb, capture, "inf_carom", "보병 반 두께 → 옆 적", up, 1f, false, S(I, Me, 0f, -3f, "보병"), S(I, Foe, 0.45f, 0f, "적1"), S(I, Foe, -2.2f, 0.9f, "적2")); // 아군을 쳐서 적에게 보내기 if (on("inf_ally")) yield return Shot(sb, capture, "inf_ally", "보병 → 아군 → 적", up, 1f, false, S(I, Me, 0f, -3f, "보병"), S(I, Me, 0f, 0f, "아군"), S(I, Foe, 0f, 2f, "적")); // 벽 앞의 적 if (on("inf_wall")) yield return Shot(sb, capture, "inf_wall", "보병 정면 · 벽 앞 적", up, 1f, false, S(I, Me, 0f, 11f, "보병"), S(I, Foe, 0f, 14f, "적")); // 창병 if (on("spear_full")) yield return Shot(sb, capture, "spear_full", "창병 정면 가득", up, 1f, false, S(P, Me, 0f, -3f, "창병"), S(I, Foe, 0f, 0f, "적")); if (on("spear_half")) yield return Shot(sb, capture, "spear_half", "창병 반 두께 가득", up, 1f, false, S(P, Me, 0f, -3f, "창병"), S(I, Foe, 0.45f, 0f, "적")); if (on("vs_spear")) yield return Shot(sb, capture, "vs_spear", "보병 → 적 창병 정면", up, 1f, false, S(I, Me, 0f, -3f, "보병"), S(P, Foe, 0f, 0f, "적창병")); // 기병: 아군 통과 · 적 둘(왼쪽 치우침 · 오른쪽 치우침 · 정면) if (on("cav_pass")) yield return Shot(sb, capture, "cav_pass", "기병 관통(아군 1 · 적 3)", up, 1f, false, S(C, Me, 0f, -4f, "기병"), S(I, Me, 0f, -2.4f, "아군"), S(I, Foe, 0.4f, -0.5f, "적우"), S(I, Foe, -0.4f, 1.5f, "적좌"), S(I, Foe, 0f, 3.5f, "적정면")); // 궁병 · 책사 이동(공격 없이) if (on("arc_full")) yield return Shot(sb, capture, "arc_full", "궁병 이동 정면", up, 1f, true, S(A, Me, 0f, -3f, "궁병"), S(I, Foe, 0f, 0f, "적")); if (on("arc_half")) yield return Shot(sb, capture, "arc_half", "궁병 이동 반 두께", up, 1f, true, S(A, Me, 0f, -3f, "궁병"), S(I, Foe, 0.45f, 0f, "적")); if (on("str_full")) yield return Shot(sb, capture, "str_full", "책사 이동 정면", up, 1f, true, S(T, Me, 0f, -3f, "책사"), S(I, Foe, 0f, 0f, "적")); // 적 궁병의 사격(화살 그림 확인 · only.txt 에 적었을 때만) if (only.Contains("foe_arrow")) yield return Shot(sb, capture, "foe_arrow", "적 궁병 사격", Vector2.down, 0.8f, false, S(A, Foe, 0f, 3f, "적궁병"), S(I, Me, 0f, -2f, "아군")); if (on("arc_ally")) yield return Shot(sb, capture, "arc_ally", "궁병 이동 → 아군", up, 1f, true, S(A, Me, 0f, -3f, "궁병"), S(I, Me, 0f, 0f, "아군")); // 연의 전기 2막 안내 샷(scenario_guide taoyuan 2-5 「유비가 튕겨 나가며 창병 둘을 한 번에」 · 배치 = scenario_layout 메모의 2턴 자리) Vector2 act2Aim = new Vector2(3.25f, 0.19f) - new Vector2(-1.4f, -6.73f); foreach (var k in new[] { 0.6f, 0.8f, 1f }) { string id = "act2_lb_" + Mathf.RoundToInt(k * 100f); if (on(id)) yield return Shot(sb, capture, id, "2막 유비 튕김 세기 " + k, act2Aim, k, false, S(I, Me, -1.4f, -6.73f, "유비"), S(P, Foe, -0.3f, -3.3f, "창병1"), S(P, Foe, 2.4f, -3.6f, "창병2")); } if (sb[sb.Length - 2] == ',') sb.Remove(sb.Length - 2, 1); sb.Append("]}\n"); File.WriteAllText(Path.Combine(Dir, label + ".json"), sb.ToString(), new UTF8Encoding(false)); Debug.Log("[SlingFeelProbe] " + label + ".json"); } } }