ThreeKingdomsSlingshot/Assets/Scripts/Runtime/Tutorial/TutorialDirector.cs

917 lines
38 KiB
C#
Raw Normal View History

using System.Collections.Generic;
using TKS.OutGame;
using UnityEngine;
namespace TKS
{
/// <summary>
/// 1장 학습 판 안내 진행(개발 요청서 C5 · 2026-11-12) — tutorial_guide.csv 를 n_step 순서대로:
/// 앞 단계가 닫힌 뒤 e_trigger 가 맞으면 띄우고, b_lock 1 이면 가리킨 것만 누를 수 있다. 안내는 그 판을 처음 할 때만(클리어 기록) · fail 카드는 매번.
/// 닫힘 = 카드: 탭 · 끌기: 그 행동이 끝남 · 강조·띠: tutorial_config guide_auto_close_sec 뒤 또는 탭 · 누름: 대상을 누름.
/// 끌기 단계 바로 다음이 unit_select 단계면 「조준 안내」 — 그 유닛을 잡고 있는 동안 그 문구·대상을 보여 주고, 쏘면 둘 다 끝난다(손을 떼어 취소하면 끌기 안내로 돌아감).
/// 그 밖: 남은 턴 칩(턴 제한 판) · 안내가 가리키는 함정 보이기(1-7) · 클리어 결말 카드(첫 클리어) · 편성 화면 안내(before_battle).
/// 전장 조작 막기 = SlingshotInput 이 BlocksInput · AllowPress · SnapAim · AllowShot 을 물어본다. 가상 실행(Sim.Active) 중에는 아무 사건도 받지 않는다.
/// </summary>
public class TutorialDirector : MonoBehaviour
{
public static TutorialDirector Current { get; private set; }
const float MinCardSec = 0.35f; // 카드가 뜨자마자 닫히지 않게
const float MinTapSec = 0.2f;
const float HolePad = 18f;
struct Evt
{
public GuideTrigger trig;
public int turn;
public Unit unit;
}
BattleManager battle;
Camera cam;
CameraController camCtrl;
TutorialGuideUI ui;
TutorialPlan plan;
bool guideOn;
bool firstPlay;
readonly List<TutorialGuideRow> steps = new List<TutorialGuideRow>();
readonly List<TutorialGuideRow> failSteps = new List<TutorialGuideRow>();
readonly Queue<TutorialGuideRow> overlay = new Queue<TutorialGuideRow>(); // 결말 · 실패 · 편성 화면 안내
readonly List<Evt> happened = new List<Evt>();
readonly Dictionary<int, GimmickInstance> gimmicks = new Dictionary<int, GimmickInstance>();
readonly HashSet<string> beforeShown = new HashSet<string>();
string beforeChecked = "";
int index;
TutorialGuideRow active;
bool activeOverlay;
TutorialGuideRow hint; // 끌기 안내 중 유닛을 잡았을 때의 조준 안내(다음 단계)
float shownAt;
bool aiming;
bool fired;
bool movedCamera;
bool swallow;
Unit lastActor;
BattlePhase lastPhase = BattlePhase.Setup;
bool bossHold;
bool bossDone;
RectTransform skillButton;
public TutorialPlan Plan
{
get { return plan; }
}
public bool GuideOn
{
get { return guideOn; }
}
public TutorialGuideRow ActiveStep
{
get { return active; }
}
/// <summary>조준 안내가 떠 있으면 그 단계.</summary>
public TutorialGuideRow HintStep
{
get { return hint; }
}
public int StepIndex
{
get { return index; }
}
public int StepCount
{
get { return steps.Count; }
}
public TutorialGuideUI Ui
{
get { return ui; }
}
public static TutorialDirector Ensure(BattleManager bm)
{
if (Current != null && Current.battle == bm) return Current;
var go = new GameObject("TutorialDirector");
go.transform.SetParent(bm.transform, false);
var d = go.AddComponent<TutorialDirector>();
d.Init(bm);
return d;
}
void Init(BattleManager bm)
{
Current = this;
battle = bm;
cam = Camera.main;
camCtrl = cam != null ? cam.GetComponent<CameraController>() : null;
if (cam != null) ui = TutorialGuideUI.Create(transform, cam);
bm.PhaseChanged += OnPhase;
bm.UnitActing += OnUnitActing;
bm.Changed += RefreshTurnChip;
}
void OnDestroy()
{
if (Current == this) Current = null;
if (battle == null) return;
battle.PhaseChanged -= OnPhase;
battle.UnitActing -= OnUnitActing;
battle.Changed -= RefreshTurnChip;
}
/// <summary>
/// 잠금 끌기 안내가 맞춰 쏘는 세기(최대 거리 대비): 판별 값 `drag_lock_shot_pull_&lt;장&gt;_&lt;판&gt;` 이 표에 있으면 그 값 · 없으면 공통 `drag_lock_shot_pull`
/// (PD 2026-11-16 병종 물리 조정 — 1-2 는 장비를 4.1 밀어야 하고 1-8 은 적을 불길 띠 안에 세워야 해서 한 값으로 맞출 수 없다).
/// </summary>
float ShotPull()
{
float all = Num("drag_lock_shot_pull", 1f);
return plan != null && plan.Row != null ? Num("drag_lock_shot_pull_" + plan.Row.chapter + "_" + plan.Row.stage, all) : all;
}
float Num(string key, float fallback)
{
var db = plan != null ? plan.Db : TutorialTables.Db;
return db != null ? db.Num(key, fallback) : fallback;
}
// ---------- 판 시작 ----------
/// <summary>전투 시작(BattleManager.Begin · 유닛·기믹 배치 뒤 · 첫 턴 전). p = 그 판의 학습 판 계획(null = 일반 판).</summary>
public void BeginStage(TutorialPlan p)
{
plan = p;
steps.Clear();
failSteps.Clear();
overlay.Clear();
happened.Clear();
gimmicks.Clear();
index = 0;
active = null;
hint = null;
activeOverlay = aiming = fired = movedCamera = swallow = false;
bossHold = bossDone = false;
lastActor = null;
lastPhase = BattlePhase.Setup;
guideOn = false;
RefreshInfo();
RefreshTurnChip();
if (p == null || ui == null) return;
firstPlay = !TutorialRules.Cleared(p.Row.chapter, p.Row.stage);
var rows = p.Db.Guide(p.Row.chapter, p.Row.stage);
foreach (var g in rows)
{
if (g.trigger == GuideTrigger.Fail) failSteps.Add(g);
else if (g.trigger != GuideTrigger.BeforeBattle && firstPlay) steps.Add(g);
}
guideOn = steps.Count > 0;
// 배치 표 기믹 슬롯 ↔ 전장 기믹(같은 id · 같은 자리)
var layer = battle.Gimmicks;
if (layer != null)
{
foreach (var r in p.Layout)
{
if (r.side != TutSide.Gimmick) continue;
foreach (var g in layer.Items)
{
if (g.Id != r.gimmickId || Vector2.Distance(g.Shape.Center, r.pos) > 0.05f || gimmicks.ContainsValue(g)) continue;
gimmicks[r.slot] = g;
break;
}
}
}
// 안내가 가리키는 함정은 이 판에서 자리를 보여 준다(1-7 「이번만 함정 자리를 보여 줍니다」 · 클리어 뒤 다시 해도 같음)
foreach (var g in rows)
{
foreach (var slot in g.Target.AllSlots())
{
GimmickInstance gi;
if (gimmicks.TryGetValue(slot, out gi) && gi.Zone == GimmickZone.Trap && gi.View != null && gi.View.Body != null) gi.View.Body.gameObject.SetActive(true);
}
}
happened.Add(new Evt { trig = GuideTrigger.StageStart });
}
/// <summary>보스 등장 연출(C2)이 시작될 때 부른다 — 끝나면 NotifyBossIntroEnd. 부르지 않으면 첫 아군 턴에 boss_intro_end 로 본다.</summary>
public void HoldBossIntro()
{
bossHold = true;
}
public void NotifyBossIntroEnd()
{
if (bossDone) return;
bossHold = false;
bossDone = true;
Add(GuideTrigger.BossIntroEnd, battle.TurnNumber, null);
TryAdvance();
}
// ---------- 전투 사건 ----------
void Add(GuideTrigger trig, int turn, Unit u)
{
if (!guideOn) return;
happened.Add(new Evt { trig = trig, turn = turn, unit = u });
}
void OnPhase(BattlePhase p)
{
if (Sim.Active) return;
var prev = lastPhase;
lastPhase = p;
RefreshTurnChip();
if (p == BattlePhase.Setup)
{
BeginStage(null); // 전투 없음(월드맵·로비)
return;
}
if (plan == null) return;
int turn = battle.TurnNumber;
if (prev == BattlePhase.Resolving)
{
Add(GuideTrigger.ActionEnd, turn, lastActor);
if (active != null && !activeOverlay && active.mode == GuideMode.Drag && fired) CloseActive(false, true);
}
switch (p)
{
case BattlePhase.PlayerTurn:
if (prev != BattlePhase.Resolving)
{
Add(GuideTrigger.TurnStart, turn, null);
if (!bossHold && !bossDone)
{
bossDone = true;
Add(GuideTrigger.BossIntroEnd, turn, null);
}
}
break;
case BattlePhase.EnemyTurn:
Add(GuideTrigger.EnemyTurn, turn, null);
// 잠기지 않은 끌기·누름 안내는 아군 턴이 끝나면 닫는다
if (active != null && !activeOverlay && !active.locked && (active.mode == GuideMode.Drag || active.mode == GuideMode.Tap)) CloseActive(false, false);
break;
case BattlePhase.StageClear:
EndGuide();
if (firstPlay && !string.IsNullOrEmpty(plan.Row.clearKo))
overlay.Enqueue(new TutorialGuideRow { chapter = plan.Row.chapter, stage = plan.Row.stage, mode = GuideMode.Popup, locked = true, textKo = plan.Row.clearKo });
break;
case BattlePhase.Defeat:
EndGuide();
foreach (var f in failSteps) overlay.Enqueue(f);
break;
}
TryAdvance();
}
void OnUnitActing(Unit u)
{
if (Sim.Active || u == null) return;
lastActor = u;
if (u.Faction != Faction.Player || active == null || activeOverlay) return;
if (active.mode == GuideMode.Drag && u == FromUnit(active))
{
fired = true;
aiming = false;
RefreshInfo();
}
else if (!active.locked && active.mode == GuideMode.Tap) CloseActive(false, false);
}
/// <summary>유닛을 골랐다(SlingshotInput.Select).</summary>
public void OnSelect(Unit u)
{
if (u == null || plan == null || !guideOn) return;
bool canAct = u.Faction == Faction.Player && battle.CanAct(u);
if (canAct) Add(GuideTrigger.UnitSelect, battle.TurnNumber, u);
if (active != null && !activeOverlay)
{
if (active.mode == GuideMode.Tap && active.Target.kind == GuideTargetKind.Slots && IsTargetUnit(active, u)) CloseActive(false, false);
else if (active.mode == GuideMode.Drag && canAct && !fired && u == FromUnit(active))
{
aiming = true;
hint = NextAimHint();
RefreshInfo();
}
}
TryAdvance();
}
/// <summary>당기다가 쏘지 않고 손을 뗐다.</summary>
public void OnAimCancelled()
{
if (!aiming) return;
aiming = false;
hint = null;
RefreshInfo();
}
/// <summary>스킬 버튼을 눌렀다.</summary>
public void NotifySkillTap()
{
if (active == null || activeOverlay) return;
if (active.Target.kind == GuideTargetKind.Ui && active.Target.ui == "skill" && (active.mode == GuideMode.Tap || active.mode == GuideMode.Highlight)) CloseActive(false, false);
}
void EndGuide()
{
active = null;
hint = null;
activeOverlay = aiming = fired = false;
index = steps.Count;
RefreshInfo();
}
// ---------- 단계 진행 ----------
TutorialGuideRow NextAimHint()
{
return index + 1 < steps.Count && steps[index + 1].trigger == GuideTrigger.UnitSelect ? steps[index + 1] : null;
}
static bool NeedsPlayerTurn(TutorialGuideRow s)
{
return s.locked || s.mode == GuideMode.Popup || s.mode == GuideMode.Drag || s.mode == GuideMode.Tap;
}
/// <summary>그 단계의 조건을 채운 사건 위치(없으면 −1 · after_step = −2).</summary>
int Match(TutorialGuideRow s)
{
if (s.trigger == GuideTrigger.AfterStep) return -2;
Unit want = null;
if (s.trigger == GuideTrigger.UnitSelect && s.Target.kind == GuideTargetKind.Slots)
{
foreach (var slot in s.Target.slots)
{
var r = plan.SlotRow(slot);
if (r != null && r.side == TutSide.Ally) want = plan.UnitAt(slot);
}
}
for (int i = 0; i < happened.Count; i++)
{
var e = happened[i];
if (e.trig != s.trigger) continue;
if (s.turn > 0 && e.turn != s.turn && s.trigger != GuideTrigger.StageStart && s.trigger != GuideTrigger.BossIntroEnd) continue;
if (want != null && e.unit != want) continue;
return i;
}
return -1;
}
/// <summary>턴이 지나 더는 일어날 수 없는 단계(건너뜀).</summary>
bool Stale(TutorialGuideRow s)
{
if (s.turn <= 0 || battle.TurnNumber <= s.turn) return false;
return s.trigger == GuideTrigger.ActionEnd || s.trigger == GuideTrigger.EnemyTurn || s.trigger == GuideTrigger.TurnStart || s.trigger == GuideTrigger.UnitSelect;
}
void TryAdvance()
{
if (active != null || ui == null) return;
if (overlay.Count > 0)
{
Show(overlay.Dequeue(), true);
return;
}
if (!guideOn || plan == null) return;
var ph = battle.Phase;
if (ph == BattlePhase.Setup || ph == BattlePhase.StageClear || ph == BattlePhase.Defeat) return;
while (index < steps.Count)
{
var s = steps[index];
int at = Match(s);
if (at != -1)
{
if (NeedsPlayerTurn(s) && ph != BattlePhase.PlayerTurn) return; // 아군 턴까지 기다림
if (at >= 0) happened.RemoveRange(0, at + 1);
Show(s, false);
return;
}
if (!Stale(s)) return;
index++;
}
}
void Show(TutorialGuideRow s, bool isOverlay)
{
active = s;
activeOverlay = isOverlay;
hint = null;
aiming = fired = false;
shownAt = Time.unscaledTime;
FocusCamera(s);
RefreshInfo();
}
/// <summary>byTap = 화면을 눌러 닫음(그 누름이 전장 조작으로 새지 않게) · byAction = 끌기 안내의 행동이 끝나 닫힘.</summary>
void CloseActive(bool byTap, bool byAction)
{
var row = active;
if (row == null) return;
bool wasOverlay = activeOverlay;
bool hadHint = !wasOverlay && row.mode == GuideMode.Drag && byAction && NextAimHint() != null;
active = null;
hint = null;
activeOverlay = aiming = fired = false;
if (!wasOverlay) index += hadHint ? 2 : 1; // 조준 안내는 끌기와 함께 끝난다
if (byTap && (row.locked || row.mode == GuideMode.Popup)) swallow = true;
RefreshInfo();
TryAdvance();
if (active == null && movedCamera) RestoreCamera();
}
/// <summary>테스트·검증 캡처: 화면을 누른 것처럼 지금 안내(카드 · 강조 · 띠)를 닫는다.</summary>
public void TapForTest()
{
if (active == null) return;
if (active.mode == GuideMode.Popup || ((active.mode == GuideMode.Highlight || active.mode == GuideMode.Bar) && !WaitsForSkill(active))) CloseActive(false, false);
}
// ---------- 입력(SlingshotInput 이 물어봄) ----------
/// <summary>화면 누름을 전장 조작·결과 넘기기로 보내지 않는다(카드 · 잠긴 강조·띠 · 방금 탭으로 닫은 누름).</summary>
public bool BlocksInput
{
get
{
if (swallow) return true;
if (active == null) return false;
if (active.mode == GuideMode.Popup) return true;
return active.locked && (active.mode == GuideMode.Highlight || active.mode == GuideMode.Bar) && !WaitsForSkill(active);
}
}
/// <summary>잠금 안내가 떠 있다(가리킨 것만 누를 수 있다 · 화면 끌기·확대 막힘).</summary>
public bool Locked
{
get { return active != null && active.locked; }
}
static bool WaitsForSkill(TutorialGuideRow s)
{
return s.locked && s.mode == GuideMode.Highlight && s.Target.kind == GuideTargetKind.Ui && s.Target.ui == "skill";
}
/// <summary>잠금 안내 중 이 누름을 받아도 되는가 — under = 누른 자리의 아군 유닛(없으면 null).</summary>
public bool AllowPress(Vector2 screen, Unit under)
{
if (active == null || !active.locked) return true;
bool overSkill = OverSkillButton(screen);
switch (active.mode)
{
case GuideMode.Drag:
return !fired && !overSkill && under != null && under == FromUnit(active);
case GuideMode.Tap:
if (active.Target.kind == GuideTargetKind.Ui) return active.Target.ui == "skill" && overSkill;
return !overSkill && under != null && IsTargetUnit(active, under);
case GuideMode.Highlight:
return WaitsForSkill(active) && overSkill;
}
return false;
}
/// <summary>
/// 잠긴 끌기 안내 — 조준이 목표 방향에서 허용 각도 안이고 최소 당김(drag_lock_min_pull)을 넘으면 목표 방향 · 정해진 세기(drag_lock_shot_pull)로 맞춘다.
/// 안내한 결과가 그대로 나오게 하고, 화면 아래쪽 유닛은 끝까지 당길 자리가 모자라도 진행되게 한다(조준 화살표도 맞춘 값으로 보인다).
/// </summary>
public Vector2 SnapAim(Unit u, Vector2 target)
{
if (active == null || !active.locked || active.mode != GuideMode.Drag || u == null || u != FromUnit(active)) return target;
Vector2 want = DragPoint(active) - u.Position;
Vector2 aim = target - u.Position;
if (want.sqrMagnitude < 1e-4f || aim.sqrMagnitude < 1e-4f) return target;
if (Vector2.Angle(want, aim) > Num("drag_lock_angle_deg", 0f)) return target;
float max = SkillMods.SlingMax(u);
if (aim.magnitude < max * Num("drag_lock_min_pull", 0f) - 0.01f) return target; // 덜 당김 = 그대로 보여 주고 발사는 거부
return battle.Board.ClampInside(u.Position + want.normalized * max * Mathf.Clamp01(ShotPull()), u.Radius);
}
/// <summary>이 발사를 허용하는가 — 잠긴 끌기 안내 = 그 유닛 · 목표 방향 · 최소 당김 이상 / 그 밖의 잠금 안내 = 발사 불가.</summary>
public bool AllowShot(Unit u, Vector2 target)
{
if (active == null || !active.locked) return true;
if (active.mode != GuideMode.Drag || u == null || u != FromUnit(active)) return false;
Vector2 want = DragPoint(active) - u.Position;
Vector2 aim = target - u.Position;
if (want.sqrMagnitude < 1e-4f || aim.sqrMagnitude < 1e-4f) return false;
if (Vector2.Angle(want, aim) > Num("drag_lock_angle_deg", 0f) + 0.5f) return false;
Vector2 full = battle.Board.ClampInside(u.Position + aim.normalized * SkillMods.SlingMax(u), u.Radius);
return aim.magnitude >= Vector2.Distance(full, u.Position) * Num("drag_lock_min_pull", 0f) - 0.02f;
}
bool OverSkillButton(Vector2 screen)
{
var rt = SkillButton;
return rt != null && rt.gameObject.activeInHierarchy && RectTransformUtility.RectangleContainsScreenPoint(rt, screen, cam);
}
RectTransform SkillButton
{
get
{
if (skillButton == null && battle.Hud != null)
{
var t = battle.Hud.transform.Find("Info/SkillButton");
skillButton = t as RectTransform;
}
return skillButton;
}
}
// ---------- 대상 ----------
Unit FromUnit(TutorialGuideRow s)
{
return plan != null && s.Target.kind == GuideTargetKind.Drag ? plan.UnitAt(s.Target.from) : null;
}
/// <summary>끌기 안내의 쏠 곳(대상 슬롯의 지금 자리 또는 전장 좌표 점).</summary>
Vector2 DragPoint(TutorialGuideRow s)
{
var t = s.Target;
if (t.to <= 0) return t.point;
Vector2 p;
return SlotCenter(t.to, out p) ? p : t.point;
}
bool IsTargetUnit(TutorialGuideRow s, Unit u)
{
if (plan == null || s.Target.kind != GuideTargetKind.Slots) return false;
foreach (var slot in s.Target.slots)
if (plan.UnitAt(slot) == u) return true;
return false;
}
bool SlotCenter(int slot, out Vector2 p)
{
p = Vector2.zero;
if (plan == null) return false;
var u = plan.UnitAt(slot);
if (u != null)
{
p = u.Position;
return u.IsAlive;
}
GimmickInstance g;
if (gimmicks.TryGetValue(slot, out g) && !g.Removed)
{
p = g.Shape.Center;
return true;
}
var r = plan.SlotRow(slot);
if (r == null) return false;
p = r.pos;
return r.side == TutSide.Gimmick; // 배치 자리(기믹 연결이 없을 때)
}
/// <summary>그 단계가 가리키는 전장 대상의 사각(전장 좌표 가운데·반 크기 · round = 유닛·원 기믹).</summary>
void WorldTargets(TutorialGuideRow s, List<Vector2> centers, List<Vector2> halves, List<bool> rounds)
{
if (plan == null) return;
var t = s.Target;
var slots = new List<int>();
if (t.kind == GuideTargetKind.Slots) slots.AddRange(t.slots);
else if (t.kind == GuideTargetKind.Drag)
{
slots.Add(t.from);
if (t.to > 0) slots.Add(t.to);
}
foreach (var slot in slots)
{
var u = plan.UnitAt(slot);
if (u != null)
{
if (!u.IsAlive) continue;
if (u.View != null && u.View.HasArt)
{
// 그림(발 = −0.55 R · 키 = ArtHeight) 전체를 감싼다
float h = u.ArtHeight + 0.3f;
centers.Add(u.Position + new Vector2(0f, -u.Radius * 0.55f + u.ArtHeight * 0.5f));
halves.Add(new Vector2(Mathf.Max(u.Radius * 1.5f, h * 0.42f), h * 0.5f));
}
else
{
centers.Add(u.Position);
halves.Add(Vector2.one * u.Radius * 1.5f);
}
rounds.Add(true);
continue;
}
GimmickInstance g;
if (!gimmicks.TryGetValue(slot, out g) || g.Removed) continue;
bool circle = g.Shape.Type == GimmickShapeType.Circle;
centers.Add(g.Shape.Center);
halves.Add(circle ? Vector2.one * g.Shape.R * 1.25f : g.Shape.Size * 0.5f + Vector2.one * 0.15f);
rounds.Add(circle);
}
}
/// <summary>UI 대상(남은 턴 · 스킬 버튼 · 편성 화면 출전 칸)의 캔버스 사각.</summary>
bool UiTarget(TutorialGuideRow s, out Rect rect)
{
rect = new Rect();
if (s.Target.kind != GuideTargetKind.Ui || ui == null) return false;
switch (s.Target.ui)
{
case "turn":
if (!ui.TurnChipVisible) return false;
rect = ui.UiRect(ui.TurnChip);
return true;
case "skill":
var sb = SkillButton;
if (sb == null || !sb.gameObject.activeInHierarchy) return false;
rect = ui.UiRect(sb);
return true;
case "lineup":
var root = OutGameRoot.Instance;
if (root == null || root.Formation == null || root.Formation.Rt == null) return false;
bool any = false;
foreach (var rt in root.Formation.Rt.GetComponentsInChildren<RectTransform>(false))
{
string n = rt.name;
if (n.Length != 5 || !n.StartsWith("Slot") || !char.IsDigit(n[4])) continue;
var r = ui.UiRect(rt);
rect = any ? Rect.MinMaxRect(Mathf.Min(rect.xMin, r.xMin), Mathf.Min(rect.yMin, r.yMin), Mathf.Max(rect.xMax, r.xMax), Mathf.Max(rect.yMax, r.yMax)) : r;
any = true;
}
return any;
}
return false;
}
// ---------- 카메라 ----------
readonly List<Vector2> tmpC = new List<Vector2>();
readonly List<Vector2> tmpH = new List<Vector2>();
readonly List<bool> tmpR = new List<bool>();
/// <summary>대상이 화면 밖이면 대상들의 가운데로 화면을 옮긴다.</summary>
void FocusCamera(TutorialGuideRow s)
{
if (camCtrl == null || plan == null) return;
tmpC.Clear();
tmpH.Clear();
tmpR.Clear();
WorldTargets(s, tmpC, tmpH, tmpR);
if (s.Target.kind == GuideTargetKind.Drag && s.Target.to <= 0)
{
tmpC.Add(s.Target.point);
tmpH.Add(Vector2.one * 0.5f);
}
if (tmpC.Count == 0) return;
Vector2 min = tmpC[0] - tmpH[0], max = tmpC[0] + tmpH[0];
for (int i = 1; i < tmpC.Count; i++)
{
min = Vector2.Min(min, tmpC[i] - tmpH[i]);
max = Vector2.Max(max, tmpC[i] + tmpH[i]);
}
var view = camCtrl.ViewRect;
float mx = view.width * 0.08f, myTop = view.height * 0.16f, myBottom = view.height * 0.22f; // 위 턴 띠 · 아래 유닛 판 뒤로 가지 않게
if (min.x >= view.xMin + mx && max.x <= view.xMax - mx && min.y >= view.yMin + myBottom && max.y <= view.yMax - myTop) return;
camCtrl.StopFollow();
camCtrl.FocusOn((min + max) * 0.5f - new Vector2(0f, (myBottom - myTop) * 0.5f)); // 쓸 수 있는 화면(위·아래 판 사이)의 가운데에 오게
movedCamera = true;
}
/// <summary>아군(구출 대상 제외) 쪽으로 화면을 되돌린다(GameBootstrap 의 아군 턴 초점과 같은 식).</summary>
void RestoreCamera()
{
movedCamera = false;
if (camCtrl == null || battle.Phase != BattlePhase.PlayerTurn) return;
Vector2 sum = Vector2.zero;
int n = 0;
foreach (var p in battle.AliveUnits(Faction.Player))
{
if (p.Npc) continue;
sum += p.Position;
n++;
}
if (n > 0) camCtrl.FocusOn(sum / n + new Vector2(0f, battle.Config.cameraViewHeight * 0.2f));
}
// ---------- 표시 ----------
/// <summary>띠·카드·누름 막이(단계가 바뀔 때만).</summary>
void RefreshInfo()
{
if (ui == null) return;
if (active == null)
{
ui.SetBar("");
ui.SetCard("");
ui.SetBlocker(false);
return;
}
if (active.mode == GuideMode.Popup)
{
ui.SetBar("");
ui.SetCard(active.textKo);
ui.SetBlocker(true);
return;
}
ui.SetCard("");
ui.SetBar(fired ? "" : (hint != null ? hint.textKo : active.textKo));
ui.SetBlocker(active.locked && (active.mode == GuideMode.Highlight || active.mode == GuideMode.Bar) && !WaitsForSkill(active));
}
void RefreshTurnChip()
{
if (ui == null) return;
var ph = battle.Phase;
bool on = plan != null && plan.TurnLimit > 0 && (ph == BattlePhase.PlayerTurn || ph == BattlePhase.Resolving || ph == BattlePhase.EnemyTurn);
ui.SetTurnsLeft(on ? "남은 턴 " + Mathf.Max(0, plan.TurnLimit - battle.TurnNumber + 1) : "");
}
void Update()
{
if (ui == null) return;
if (swallow && !Input.GetMouseButton(0) && !Input.GetMouseButtonUp(0)) swallow = false;
PollBeforeBattle();
if (active != null)
{
float age = Time.unscaledTime - shownAt;
bool down = Input.GetMouseButtonDown(0);
switch (active.mode)
{
case GuideMode.Popup:
if (down && age > MinCardSec) CloseActive(true, false);
break;
case GuideMode.Highlight:
case GuideMode.Bar:
if (WaitsForSkill(active)) break;
if (down && age > MinTapSec) CloseActive(true, false);
else if (age > Num("guide_auto_close_sec", 1.5f)) CloseActive(false, false);
break;
case GuideMode.Drag:
case GuideMode.Tap:
// 가리킨 유닛이 쓰러졌거나 이번 턴에 더 움직일 수 없으면 건너뛴다(잠금에 갇히지 않게)
if (!activeOverlay && !fired && battle.Phase == BattlePhase.PlayerTurn && !TargetUsable(active)) CloseActive(false, false);
break;
}
}
else TryAdvance();
Draw();
}
bool TargetUsable(TutorialGuideRow s)
{
if (s.mode == GuideMode.Drag)
{
var u = FromUnit(s);
return u != null && u.IsAlive && battle.CanAct(u);
}
if (s.Target.kind != GuideTargetKind.Slots) return true;
foreach (var slot in s.Target.slots)
{
var u = plan.UnitAt(slot);
if (u != null && u.IsAlive) return true;
}
return false;
}
void Draw()
{
ui.BeginFrame();
var row = active;
if (row != null && !(row.mode == GuideMode.Drag && fired))
{
var shown = hint ?? row;
float pulse = 1f + 0.06f * Mathf.Sin(Time.unscaledTime * 6f);
tmpC.Clear();
tmpH.Clear();
tmpR.Clear();
WorldTargets(shown, tmpC, tmpH, tmpR);
var rects = new List<Rect>();
for (int i = 0; i < tmpC.Count; i++) rects.Add(ui.WorldRect(tmpC[i], tmpH[i]));
Rect uiRect;
bool hasUi = UiTarget(shown, out uiRect);
if (hasUi)
{
rects.Add(uiRect);
tmpR.Add(false);
}
bool dim = row.mode == GuideMode.Popup || (row.mode == GuideMode.Highlight && !aiming);
if (dim)
{
if (rects.Count == 0) ui.Dim(Num("dim_alpha", 0.5f), null);
else
{
var hole = rects[0];
for (int i = 1; i < rects.Count; i++)
hole = Rect.MinMaxRect(Mathf.Min(hole.xMin, rects[i].xMin), Mathf.Min(hole.yMin, rects[i].yMin), Mathf.Max(hole.xMax, rects[i].xMax), Mathf.Max(hole.yMax, rects[i].yMax));
ui.Dim(Num("dim_alpha", 0.5f), Rect.MinMaxRect(hole.xMin - HolePad, hole.yMin - HolePad, hole.xMax + HolePad, hole.yMax + HolePad));
}
}
for (int i = 0; i < rects.Count; i++) ui.Frame(rects[i], tmpR[i], pulse);
// 띠·카드가 가리키는 대상(과 당기는 손가락)을 덮지 않게 자리를 고른다
if (row.mode == GuideMode.Popup)
{
if (rects.Count == 0) ui.PlaceCard(0);
else
{
float cy = 0f;
foreach (var r in rects) cy += r.center.y;
ui.PlaceCard(cy / rects.Count > -150f ? -1 : 1);
}
}
else
{
bool low = row.mode == GuideMode.Drag; // 끄는 손가락은 화면 아래쪽의 유닛에서 출발한다
foreach (var r in rects)
if (r.yMin < ui.BarZoneTop) low = true;
ui.PlaceBar(low);
}
if (row.mode == GuideMode.Drag) DrawDrag(row);
else if (row.mode == GuideMode.Tap && rects.Count > 0)
{
float press = 0.5f + 0.5f * Mathf.Sin(Time.unscaledTime * 6f);
ui.Finger(rects[0].center, press, 1f);
}
}
ui.EndFrame();
}
void DrawDrag(TutorialGuideRow row)
{
var u = FromUnit(row);
if (u == null || !u.IsAlive) return;
Vector2 to = DragPoint(row);
Vector2 dir = to - u.Position;
if (dir.sqrMagnitude < 1e-4f) return;
dir.Normalize();
if (row.Target.to <= 0)
{
var r = ui.WorldRect(to, Vector2.one * u.Radius);
ui.AimEnd(r.center, Mathf.Max(r.width, r.height)); // 점 목표 = 조준선 끝 고리(슬롯 목표는 테두리가 이미 있다)
}
if (aiming) return; // 유닛을 잡고 있는 동안 = 손가락 숨김(조준 화살표가 보인다)
// 게이지 조작(PD 2026-11-16): 손가락은 유닛에서 목표 쪽으로 끈다(끈 거리는 방향만 정하므로 목표를 넘지 않게)
float pull = Mathf.Min(SkillMods.SlingMax(u) * Num("finger_pull_ratio", 1f), Vector2.Distance(to, u.Position));
Vector2 a = ui.ToCanvas(u.Position);
Vector2 b = ClampToward(a, ui.ToCanvas(u.Position + dir * pull), ui.SafeRect);
float cycle = Mathf.Max(0.3f, Num("finger_cycle_sec", 1.6f));
float t = ((Time.unscaledTime - shownAt) % cycle) / cycle;
// 0~0.15 누름 · ~0.7 끌기 · ~0.85 멈춤 · ~1 놓음
float k = t < 0.15f ? 0f : t < 0.7f ? Mathf.SmoothStep(0f, 1f, (t - 0.15f) / 0.55f) : 1f;
float alpha = t < 0.08f ? t / 0.08f : t > 0.88f ? 1f - (t - 0.88f) / 0.12f : 1f;
Vector2 p = Vector2.Lerp(a, b, k);
if (k > 0.02f) ui.Line(a, p, alpha);
ui.Finger(p, t < 0.85f ? 1f : 0f, alpha);
}
/// <summary>b 가 범위 밖이면 a 쪽으로 당겨 범위 안에 넣는다(a 가 밖이면 그대로).</summary>
static Vector2 ClampToward(Vector2 a, Vector2 b, Rect r)
{
if (r.Contains(b) || !r.Contains(a)) return b;
float lo = 0f, hi = 1f;
for (int i = 0; i < 12; i++)
{
float mid = (lo + hi) * 0.5f;
if (r.Contains(Vector2.Lerp(a, b, mid))) lo = mid;
else hi = mid;
}
return Vector2.Lerp(a, b, lo);
}
// ---------- 편성 화면 안내(before_battle) ----------
/// <summary>전투 밖에서 편성 화면이 열려 있으면, 다음에 깰 판의 before_battle 안내를 한 번 띄운다(그 판을 깨기 전 · 앱을 켠 동안 1회).</summary>
void PollBeforeBattle()
{
if (active != null || overlay.Count > 0 || battle.Phase != BattlePhase.Setup || !TutorialRules.Enabled) return;
var root = OutGameRoot.Instance;
if (root == null || root.Formation == null || root.Formation.Rt == null || !root.Formation.Rt.gameObject.activeInHierarchy) return;
var db = TutorialTables.Db;
if (db == null || battle.Config == null) return;
BalanceConfig.StageDef next = null;
foreach (var st in battle.Config.stages)
{
if (TutorialRules.Cleared(st.chapter, st.stage)) continue;
next = st;
break;
}
if (next == null) return;
string key = next.chapter + "-" + next.stage;
if (key == beforeChecked) return;
beforeChecked = key;
if (!beforeShown.Add(key)) return;
foreach (var g in db.Guide(next.chapter, next.stage))
if (g.trigger == GuideTrigger.BeforeBattle) overlay.Enqueue(g);
TryAdvance();
}
}
}