using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
using UnityEngine.UI;
namespace TKS.OutGame
{
///
/// 전투 중 전리품 연출(2026-11-23 스테이지 보상 드랍 요청서 §2-2) — 적이 쓰러진 자리에서 금화 · 경험치 구슬 · (상자를 든 적이면) 상자가 튀어나와
/// 위쪽 표시칸(골드 합계 · 상자 수)으로 날아간다. 줍는 조작 없음 · 전투 진행을 멈추지 않는다.
/// 몫 = 스테이지 골드 총량을 적의 처치 몫(drop_rules kill_share_w_*)대로 나눔 · 상자 = 출전 때 미리 굴린 전리품(OutGameSession.PendingLoot)을
/// 상자 든 적 가중치(chest_carrier_w_*)로 나눔(보스 첫 클리어 확정 상자 = 보스). 지급은 여기서 하지 않는다(전투 종료 때 EconomyRules.Compute · Apply).
/// 배치 · 그림 · 시간 = 표 (코드 상수 없음 · C45) · 출정 스테이지만(컨텐츠 모드 · 서버 모드 상자 = 표시 없음).
///
public class BattleLootFx : MonoBehaviour
{
public const string Table = "UI/Battle/battle_loot";
class Fly
{
public RectTransform rt;
public Vector2 from;
public Vector2 mid;
public float t;
public float delay;
public int gold;
public int chest;
}
OutGameRoot root;
Canvas canvas;
RectTransform canvasRt;
RectTransform chip;
RectTransform goldSlot;
RectTransform chestSlot;
Text goldText;
Text chestText;
readonly Dictionary lay = new Dictionary();
readonly Dictionary goldOf = new Dictionary();
readonly Dictionary> chestOf = new Dictionary>();
readonly List flies = new List();
int topOrder;
/// 이번 판 골드 총량 · 상자 수(전부 처치하면 표시칸이 닿는 값) · 지금 표시칸 값 · 켜짐(테스트 · 캡처).
public int GoldTotal { get; private set; }
public int ChestTotal { get; private set; }
public int GoldShown { get; private set; }
public int ChestsShown { get; private set; }
public bool Active { get; private set; }
public int FlyCount
{
get { return flies.Count; }
}
public static BattleLootFx Create(OutGameRoot root, Canvas canvas)
{
var fx = canvas.gameObject.AddComponent();
fx.root = root;
fx.canvas = canvas;
fx.canvasRt = (RectTransform)canvas.transform;
fx.Load();
fx.Build();
fx.Show(false);
Unit.Died += fx.OnDied;
return fx;
}
void OnDestroy()
{
Unit.Died -= OnDied;
}
// ---------- 표 ----------
void Load()
{
lay.Clear();
var rows = UiText.Rows(Table);
if (rows == null)
{
Debug.LogWarning("[TKS] 전리품 연출 표 없음: " + Table);
return;
}
foreach (var r in rows)
{
string k, v;
if (r.TryGetValue("key", out k) && k.Length > 0 && r.TryGetValue("value", out v)) lay[k] = v.Split('|');
}
}
float N(string key, int i)
{
string[] a;
float v;
return lay.TryGetValue(key, out a) && i < a.Length && float.TryParse(a[i].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out v) ? v : 0f;
}
string S(string key, int i)
{
string[] a;
return lay.TryGetValue(key, out a) && i < a.Length ? a[i].Trim() : "";
}
// ---------- 표시칸 ----------
void Build()
{
float w = N("chip", 2), h = N("chip", 3);
chip = UiKit.Rect("LootChip", canvasRt, new Vector2(0f, 1f), new Vector2(0f, 1f), new Vector2(N("chip", 0), -N("chip", 1)), new Vector2(w, h));
UiKit.Skin(chip, S("chip_art", 0), UiKit.Col(S("chip_art", 1), UiKit.Dark));
float gi = N("gold", 1), ci = N("chest", 2), cx = N("chest", 4);
goldSlot = UiKit.Rect("GoldSlot", chip, new Vector2(0f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(h * 0.5f + 4f, 0f), new Vector2(gi, gi));
UiKit.Icon(goldSlot, S("gold", 0), new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), Vector2.zero, gi);
goldText = UiKit.Title(UiKit.Label(chip, "0", (int)N("gold", 2), UiKit.White, TextAnchor.MiddleLeft, new Vector2(0f, 0.5f), new Vector2(0f, 0.5f), new Vector2(h * 0.5f + gi * 0.5f + 10f, 0f), new Vector2(w * cx - h, h)), true);
goldText.horizontalOverflow = HorizontalWrapMode.Overflow;
chestSlot = UiKit.Rect("ChestSlot", chip, new Vector2(cx, 0.5f), new Vector2(0.5f, 0.5f), Vector2.zero, new Vector2(ci, ci));
UiKit.Icon(chestSlot, S("chest", 0), new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), Vector2.zero, ci);
chestText = UiKit.Title(UiKit.Label(chip, "0", (int)N("chest", 3), UiKit.White, TextAnchor.MiddleLeft, new Vector2(cx, 0.5f), new Vector2(0f, 0.5f), new Vector2(ci * 0.5f + 6f, 0f), new Vector2(w * (1f - cx), h)), true);
chestText.horizontalOverflow = HorizontalWrapMode.Overflow;
foreach (var g in chip.GetComponentsInChildren(true)) g.raycastTarget = false; // 전투 조작을 가로막지 않는다
}
void Show(bool on)
{
Active = on;
if (chip != null && chip.gameObject.activeSelf != on) chip.gameObject.SetActive(on);
}
void SetTexts()
{
string g = GoldShown.ToString("N0", CultureInfo.InvariantCulture);
string c = ChestsShown.ToString(CultureInfo.InvariantCulture);
if (goldText != null && goldText.text != g) goldText.text = g;
if (chestText != null && chestText.text != c) chestText.text = c;
}
void Clear()
{
foreach (var f in flies)
if (f.rt != null) Destroy(f.rt.gameObject);
flies.Clear();
goldOf.Clear();
chestOf.Clear();
GoldTotal = ChestTotal = GoldShown = ChestsShown = 0;
SetTexts();
}
// ---------- 판 시작 · 끝 ----------
/// 전투 시작(BattleManager.StageStarted) — 출정 스테이지면 적마다 골드 몫 · 상자를 나눠 둔다.
public void Begin(BattleManager bm)
{
Clear();
var s = root != null ? root.Session : null;
if (bm == null || bm.Mode != null || bm.Stage == null || s == null || s.Db.Gear == null || chip == null)
{
Show(false);
return;
}
var stage = bm.Stage;
var enemies = new List();
foreach (var u in bm.Units)
if (u.Faction == Faction.Enemy && u.IsAlive) enemies.Add(u);
if (enemies.Count == 0)
{
Show(false);
return;
}
var st = s.Save.Stage(stage.chapter, stage.stage, false, s.BattleHard);
int gold, exp;
EconomyRules.StageGoldExp(s.Db, s.Save, stage, st == null || st.clears == 0, out gold, out exp, s.BattleHard); // 하드 난이도 = 하드 기록 · 배율(2026-11-24)
var generals = new HashSet();
foreach (var en in stage.enemies)
if (en.isGeneral && !en.isBoss) generals.Add(en.name);
// 골드 = 처치 몫대로(반올림 차이는 마지막 적에 몰아 합계 = 총량)
float sum = 0f;
var w = new float[enemies.Count];
for (int i = 0; i < enemies.Count; i++)
{
w[i] = EconomyRules.KillShare(s.Db, enemies[i].IsBoss, generals.Contains(enemies[i].DisplayName));
sum += w[i];
}
int given = 0;
for (int i = 0; i < enemies.Count; i++)
{
int g = i == enemies.Count - 1 ? Mathf.Max(0, gold - given) : Mathf.Min(gold - given, Mathf.RoundToInt(gold * w[i] / Mathf.Max(0.0001f, sum)));
given += g;
goldOf[enemies[i]] = g;
}
GoldTotal = gold;
// 상자 = 출전 때 굴린 전리품 · 확정 상자 = 보스 · 나머지 = 상자 든 적 가중치로 겹치지 않게(적보다 많으면 다시 처음부터)
var loot = s.PendingLoot;
if (loot != null && loot.chapter == stage.chapter && loot.stage == stage.stage && loot.gearIds.Count > 0)
{
topOrder = 0;
foreach (var row in s.Db.Gear.chapterDrops)
foreach (var gr in row.grades) topOrder = Mathf.Max(topOrder, s.Db.Gear.OrderOf(gr));
Unit boss = enemies[enemies.Count - 1];
foreach (var u in enemies)
if (u.IsBoss) { boss = u; break; }
var rng = new System.Random(stage.chapter * 1000 + stage.stage * 31 + loot.gearIds.Count);
var pool = new List();
for (int i = 0; i < loot.gearIds.Count; i++)
{
Unit who = boss;
if (i >= loot.fixedChests)
{
if (pool.Count == 0) pool.AddRange(enemies);
float total = 0f;
foreach (var u in pool) total += EconomyRules.CarrierWeight(s.Db, u.IsBoss, generals.Contains(u.DisplayName));
float at = (float)(rng.NextDouble() * total);
who = pool[pool.Count - 1];
foreach (var u in pool)
{
float cw = EconomyRules.CarrierWeight(s.Db, u.IsBoss, generals.Contains(u.DisplayName));
if (at < cw) { who = u; break; }
at -= cw;
}
pool.Remove(who);
}
List list;
if (!chestOf.TryGetValue(who, out list)) chestOf[who] = list = new List();
list.Add(loot.gearIds[i]);
}
ChestTotal = loot.gearIds.Count;
}
Show(true);
}
/// 전투 단계 — 승리 = 아직 안 떨어진 몫(늦게 나온 적 · 연출 중)을 표시칸에 바로 더함 · 전투를 떠나면 숨김.
public void OnPhase(BattlePhase p)
{
if (!Active) return;
if (p == BattlePhase.StageClear)
{
foreach (var f in flies)
if (f.rt != null) Destroy(f.rt.gameObject);
flies.Clear();
goldOf.Clear();
chestOf.Clear();
GoldShown = GoldTotal;
ChestsShown = ChestTotal;
SetTexts();
}
else if (p == BattlePhase.Setup)
{
Clear();
Show(false);
}
}
// ---------- 처치 → 떨어짐 → 날아감 ----------
void OnDied(Unit u)
{
if (!Active || u == null || u.Faction != Faction.Enemy) return;
int gold;
bool known = goldOf.TryGetValue(u, out gold);
List chests;
chestOf.TryGetValue(u, out chests);
if (!known && chests == null) return;
goldOf.Remove(u);
chestOf.Remove(u);
Vector2 at = CanvasPoint(u.Position);
float size = N("fly", 0), reach = N("fly", 4);
if (known) Spawn(S("gold", 0), size, at, new Vector2(-reach * 0.6f, reach), 0f, gold, 0, Color.white);
if (known) Spawn(S("exp", 0), size, at, new Vector2(reach * 0.6f, reach * 0.8f), 0.05f, 0, 0, Color.white);
if (chests == null) return;
var gear = root.Session.Db.Gear;
for (int i = 0; i < chests.Count; i++)
{
var it = gear.Get(chests[i]);
bool top = it != null && topOrder > 0 && it.order >= topOrder; // 출정 최고 등급(전설) = 금빛 상자
Spawn(S("chest", top ? 1 : 0), N("fly_chest", 0), at, new Vector2((i - (chests.Count - 1) * 0.5f) * reach * 0.9f, reach * 1.5f), 0.1f + 0.08f * i, 0, 1, Color.white);
}
}
void Spawn(string icon, float size, Vector2 at, Vector2 offset, float delay, int gold, int chest, Color tint)
{
var rt = UiKit.Rect("Drop", canvasRt, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), at, new Vector2(size, size));
var img = UiKit.Icon(rt, icon, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), Vector2.zero, size);
if (img != null)
{
img.raycastTarget = false;
img.color = tint;
}
rt.localScale = Vector3.zero;
flies.Add(new Fly { rt = rt, from = at, mid = at + offset, delay = delay, gold = gold, chest = chest });
}
/// 전장 좌표 → 이 캔버스 가운데 기준 좌표.
Vector2 CanvasPoint(Vector2 world)
{
var cam = canvas.worldCamera != null ? canvas.worldCamera : Camera.main;
Vector2 local;
RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRt, RectTransformUtility.WorldToScreenPoint(cam, world), cam, out local);
return local;
}
Vector2 SlotPoint(RectTransform slot)
{
return canvasRt.InverseTransformPoint(slot.position);
}
void Update()
{
if (flies.Count == 0) return;
float pop = Mathf.Max(0.01f, N("fly", 1)), hold = N("fly", 2), go = Mathf.Max(0.01f, N("fly", 3));
float dt = Time.unscaledDeltaTime;
bool changed = false;
for (int i = flies.Count - 1; i >= 0; i--)
{
var f = flies[i];
if (f.delay > 0f)
{
f.delay -= dt;
continue;
}
f.t += dt;
if (f.t < pop)
{
float k = f.t / pop;
f.rt.localScale = Vector3.one * Mathf.Lerp(0.2f, 1.15f, k);
f.rt.anchoredPosition = Vector2.Lerp(f.from, f.mid, 1f - (1f - k) * (1f - k));
}
else if (f.t < pop + hold)
{
f.rt.localScale = Vector3.one;
f.rt.anchoredPosition = f.mid;
}
else
{
float k = Mathf.Clamp01((f.t - pop - hold) / go);
Vector2 to = SlotPoint(f.chest > 0 ? chestSlot : goldSlot);
f.rt.anchoredPosition = Vector2.Lerp(f.mid, to, k * k);
f.rt.localScale = Vector3.one * Mathf.Lerp(1f, 0.55f, k);
if (k < 1f) continue;
GoldShown = Mathf.Min(GoldTotal, GoldShown + f.gold);
ChestsShown = Mathf.Min(ChestTotal, ChestsShown + f.chest);
changed = true;
Destroy(f.rt.gameObject);
flies.RemoveAt(i);
}
}
if (changed) SetTexts();
}
}
}