using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using TKS.OutGame;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace TKS.Tests
{
///
/// 장애물 튕김 거리 실측(PD 2026-11-26 「장애물에 부딪히면 튕기는 거리가 매우 줄어드는 느낌」) — 판정이 아니라 측정 도구(Play 중 script eval):
/// TKS.Tests.BounceFeelRunner.Launch("라벨"); → Temp/SlingProbe/bounce_<라벨>.txt
/// 장면마다 쏜 거리(슬링 최대) · 부딪히기까지 간 거리 · 부딪힌 뒤 되돌아 움직인 거리(튕김)를 적는다 — 적 유닛 · 맵 경계(벽) · 성벽 기믹 · 목책 기믹 · 병종별.
///
public class BounceFeelRunner : MonoBehaviour
{
BattleManager bm;
string label = "run";
public static void Launch(string label)
{
var go = new GameObject("BounceFeelRunner");
DontDestroyOnLoad(go);
var r = go.AddComponent();
r.label = string.IsNullOrEmpty(label) ? "run" : label;
r.StartCoroutine(r.Routine());
}
static string Dir
{
get { return Path.Combine(Path.GetDirectoryName(Application.dataPath), "Temp", "SlingProbe"); }
}
///
/// 충돌 연출 캡처(PD 2026-11-26 「Feel 로 적과 부딪힐 때 좀 더 임팩트 있게」): 보병 → 적 보병 정면 1회를 부딪히기 전후 0.03 초(실시간) 간격으로 찍어
/// Temp/SlingProbe/impact_<라벨>_NN.png 로 남긴다(유닛 둘을 크게 · 끝 = impact_done.txt).
///
public static void LaunchImpactCapture(string label)
{
var go = new GameObject("ImpactCaptureRunner");
DontDestroyOnLoad(go);
var r = go.AddComponent();
r.label = string.IsNullOrEmpty(label) ? "run" : label;
r.StartCoroutine(r.ImpactRoutine());
}
IEnumerator ImpactRoutine()
{
Directory.CreateDirectory(Dir);
string done = Path.Combine(Dir, "impact_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(0, 0);
yield return null;
Time.timeScale = 1f;
bm.StopAllCoroutines();
bm.ClearUnits();
if (bm.Gimmicks != null) bm.Gimmicks.Clear();
bm.ForcePhase(BattlePhase.PlayerTurn);
yield return null;
yield return null;
var u = bm.SpawnUnit(UnitType.Infantry, Faction.Player, new Vector2(0f, -2.4f), "보병", 1f, 1f, false, "shu_infantry"); // 그림 유닛(Feel 연출은 그림에 붙음)
var e = bm.SpawnUnit(UnitType.Infantry, Faction.Enemy, new Vector2(0f, 0f), "적", 1f, 1f, false, "hgj_infantry");
e.MaxHp = e.Hp = 99999;
yield return new WaitForSecondsRealtime(0.5f);
var o = new ActionOutcome();
bool fin = false;
bm.StartCoroutine(Run(u, u.Position + Vector2.up * SkillMods.SlingMax(u), o, () => fin = true));
var main = Camera.main;
var go = new GameObject("ImpactCam");
var cam = go.AddComponent();
cam.CopyFrom(main);
cam.transform.position = new Vector3(0f, 0.4f, main.transform.position.z);
cam.orthographicSize = 3.2f;
var rt = new RenderTexture(540, 720, 24);
cam.targetTexture = rt;
var tex = new Texture2D(rt.width, rt.height, TextureFormat.RGB24, false);
float t0 = Time.realtimeSinceStartup;
int n = 0;
while (n < 24 && Time.realtimeSinceStartup - t0 < 3f)
{
cam.Render();
RenderTexture.active = rt;
tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
tex.Apply();
File.WriteAllBytes(Path.Combine(Dir, "impact_" + label + "_" + n.ToString("00") + ".png"), tex.EncodeToPNG());
RenderTexture.active = null;
n++;
float next = Time.realtimeSinceStartup + 0.03f;
while (Time.realtimeSinceStartup < next) yield return null;
}
while (!fin) yield return null;
Destroy(rt);
Destroy(tex);
Destroy(go);
File.WriteAllText(done, label + " frames " + n + " · " + string.Join(" / ", o.Notes), new UTF8Encoding(false));
Destroy(gameObject);
}
static string F(float v)
{
return v.ToString("0.00", CultureInfo.InvariantCulture);
}
IEnumerator Routine()
{
Directory.CreateDirectory(Dir);
string done = Path.Combine(Dir, "bounce_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(0, 0);
yield return null;
Time.timeScale = 1f;
var sb = new StringBuilder();
sb.Append("# bounce feel · ").Append(label).Append(" · 칸 = 월드 단위\n");
sb.Append("# 장면 | 병종 | 쏜 거리 | 부딪히기까지 | 부딪힌 뒤 튕김 | 비율(튕김 ÷ (쏜 거리 − 간 거리)) | 기록\n");
float bottom, top;
bm.Board.EdgesAt(0f, out bottom, out top);
foreach (var t in new[] { UnitType.Infantry, UnitType.Cavalry, UnitType.Spear, UnitType.Archer, UnitType.Strategist })
foreach (var gap in new[] { 1f, 2.5f })
{
if (!UnitTypeInfo.IsRanged(t)) yield return Shot(sb, "적 유닛", t, gap, null, true); // 궁 · 책 = 적이 있으면 쏨(이동 아님)
yield return Shot(sb, "성벽 기믹", t, gap, "wall", false);
yield return Shot(sb, "목책 기믹", t, gap, "palisade", false);
yield return Shot(sb, "맵 경계", t, gap, "#edge", false, top);
}
// 장애물에 맞고 튕겨 나가는 길에 아래 경계 — 그 전 = 경계 앞에서 멈춤 · 지금 = 경계에서 다시 반사(연쇄 쿠션)
foreach (var t in new[] { UnitType.Infantry, UnitType.Cavalry, UnitType.Archer })
yield return Shot(sb, "성벽 → 아래 경계", t, 1f, "wall", false, 0f, bottom + 1.1f);
File.WriteAllText(Path.Combine(Dir, "bounce_" + label + ".txt"), sb.ToString(), new UTF8Encoding(false));
File.WriteAllText(done, label, new UTF8Encoding(false));
Destroy(gameObject);
}
/// 유닛을 위로 슬링 최대로 쏜다 — gap = 유닛 몸 끝에서 장애물 면까지 빈 거리.
IEnumerator Shot(StringBuilder sb, string what, UnitType type, float gap, string gim, bool foe, float top = 0f, float startY = -3f)
{
bm.StopAllCoroutines();
bm.ClearUnits();
var layer = bm.Gimmicks;
if (layer != null) layer.Clear();
bm.ForcePhase(BattlePhase.PlayerTurn);
yield return null;
yield return null;
Vector2 start = new Vector2(0f, startY);
if (gim == "#edge") start = new Vector2(0f, top - 0.6f - gap); // 위 목책 경계 아래
var u = bm.SpawnUnit(type, Faction.Player, start, "쏘는 " + type);
float face = start.y + u.Radius + gap;
if (foe)
{
var e = bm.SpawnUnit(UnitType.Infantry, Faction.Enemy, new Vector2(0f, face + 0.5f), "적");
e.MaxHp = e.Hp = 99999;
}
else if (gim != null && gim != "#edge" && layer != null)
{
if (gim == "palisade") layer.Spawn(gim, GimmickShape.Circle(new Vector2(0f, face + 0.6f), 0.6f), null, 99999); // 부서지지 않게(튕김만 잰다)
else layer.Spawn(gim, GimmickShape.Box(new Vector2(0f, face + 0.4f), new Vector2(6f, 0.8f)));
}
Physics2D.SyncTransforms();
yield return null;
u.Position = start;
float launch = SkillMods.SlingMax(u);
var o = new ActionOutcome();
bool fin = false;
var path = new List { u.Position };
bm.StartCoroutine(Run(u, start + Vector2.up * launch, o, () => fin = true));
int frame = 0;
while (!fin && ++frame < 3000)
{
path.Add(u.transform.position);
yield return null;
}
path.Add(u.Position);
int peak = 0;
for (int i = 1; i < path.Count; i++)
if (path[i].y > path[peak].y) peak = i;
float before = path[peak].y - start.y, after = 0f;
float lowest = start.y;
foreach (var q in path) lowest = Mathf.Min(lowest, q.y);
for (int i = peak + 1; i < path.Count; i++) after += Vector2.Distance(path[i - 1], path[i]);
float left = Mathf.Max(0.001f, launch - before);
sb.Append(what).Append(" | ").Append(type).Append(" | ").Append(F(launch)).Append(" | ").Append(F(before)).Append(" | ").Append(F(after))
.Append(" | ").Append(F(after / left)).Append(" | 끝 y ").Append(F(u.Position.y)).Append(" · 가장 아래 y ").Append(F(lowest)).Append(" | ").Append(string.Join(" / ", o.Notes)).Append('\n');
}
IEnumerator Run(Unit u, Vector2 target, ActionOutcome o, System.Action onDone)
{
yield return bm.ResolveForTest(u, target, false, o);
onDone();
}
}
}