Files

637 lines
27 KiB
C#

using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Ноутбук гаража [K]: вкладка «Магазин запчастей и жидкостей» (выдача на стол в гараже или на кассе АЗС)
/// и вкладка «Склад запчастей / Продажа на Куфар» со снятыми деталями, их состоянием, зарядкой АКБ и продажей.
/// </summary>
public class GarageWarehouseUI : MonoBehaviour
{
private enum Tab { Shop, Warehouse }
private class ShopItem
{
public string title;
public string category;
public float price;
public System.Action<Vector3> spawn;
}
[SerializeField] private KeyCode openKey = KeyCode.K;
[SerializeField] private float wheelPrice = 85f;
[SerializeField] private float chargePrice = 8f;
[Tooltip("Необязательно: укажите свой объект стола выдачи, если хотите переопределить точку из GameEconomyManager")]
[SerializeField] private Transform deliveryTableOverride;
public static GarageWarehouseUI Instance { get; private set; }
private bool isOpen;
private Tab tab = Tab.Shop;
private Vector2 scroll;
private int deliveryIndex;
private Transform customDelivery;
private string statusLine;
private readonly List<ShopItem> items = new List<ShopItem>();
private Transform player;
private void Awake() => Instance = this;
private void OnDestroy() { if (Instance == this) Instance = null; }
private void Update()
{
if (isOpen)
{
if (Input.GetKeyDown(KeyCode.Escape) || Input.GetKeyDown(openKey)) Close();
return;
}
if (!Input.GetKeyDown(openKey) || GameInputLock.IsLocked || VehicleInteraction.Current != null) return;
MainMenuAndBootManager menu = MainMenuAndBootManager.Instance;
if (menu != null && !menu.IsPlaying) return;
GameEconomyManager eco = GameEconomyManager.Instance;
if (eco != null && !eco.DiplomaFeatures)
{
GameHUD.Notify("Магазин и склад «Куфар» доступны в Дипломной версии", GameUI.Muted);
return;
}
if (ShopCounter.PlayerNearby != null)
{
Open(ShopCounter.PlayerNearby.DeliveryPoint);
return;
}
if (PlayerPos(out Vector3 p) && eco != null && !eco.IsInGarage(p))
{
GameHUD.Notify("Ноутбук магазина и склада находится в гараже (или на кассе АЗС)", GameUI.Accent);
return;
}
Open(null);
}
private bool PlayerPos(out Vector3 pos)
{
if (player == null)
{
PlayerMovement pm = FindAnyObjectByType<PlayerMovement>();
if (pm != null) player = pm.transform;
}
pos = player != null ? player.position : Vector3.zero;
return player != null;
}
public void Open(Transform deliveryOverride)
{
customDelivery = deliveryOverride;
isOpen = true;
statusLine = deliveryOverride != null ? "Заказы выдаются на кассе магазина автохимии" : "Заказы выдаются на стол выдачи в гараже";
GameInputLock.Lock(this);
ProceduralAudioManager.Instance?.Play(SfxId.Notification);
}
private void Close()
{
isOpen = false;
GameInputLock.Unlock(this);
}
private Vector3 NextDeliveryPos()
{
int i = deliveryIndex++;
Transform table = customDelivery != null ? customDelivery : deliveryTableOverride;
if (table != null)
{
int slot = i % 5;
return table.position + table.right * ((slot - 2) * 0.45f) + Vector3.up * (0.15f + (i / 5 % 3) * 0.30f);
}
GameEconomyManager eco = GameEconomyManager.Instance;
return eco != null ? eco.GetDeliveryPosition(i % 15) : Vector3.up;
}
// ===================== ПОИСК ОРИГИНАЛЬНЫХ ДЕТАЛЕЙ АВТО =====================
private List<(Transform root, string title)> CollectTargetCars()
{
var result = new List<(Transform root, string title)>();
var seen = new HashSet<Transform>();
Vector3 refPos = customDelivery != null
? customDelivery.position
: (GameEconomyManager.Instance != null && GameEconomyManager.Instance.garageCenter != null
? GameEconomyManager.Instance.garageCenter.position
: (PlayerPos(out Vector3 pp) ? pp : Vector3.zero));
var owned = new List<CarOwnership>();
foreach (CarOwnership car in CarOwnership.All)
if (car != null && car.isOwned) owned.Add(car);
owned.Sort((a, b) => Vector3.Distance(a.transform.position, refPos).CompareTo(Vector3.Distance(b.transform.position, refPos)));
foreach (CarOwnership car in owned)
{
if (seen.Add(car.transform))
result.Add((car.transform, string.IsNullOrEmpty(car.carTitle) ? car.name : car.carTitle));
}
var vehicles = new List<VehicleInteraction>(FindObjectsByType<VehicleInteraction>(FindObjectsSortMode.None));
vehicles.Sort((a, b) => Vector3.Distance(a.transform.position, refPos).CompareTo(Vector3.Distance(b.transform.position, refPos)));
float garageRad = GameEconomyManager.Instance != null ? GameEconomyManager.Instance.garageRadius : 30f;
foreach (VehicleInteraction v in vehicles)
{
if (v == null || seen.Contains(v.transform)) continue;
if (result.Count > 0 && Vector3.Distance(v.transform.position, refPos) > garageRad) continue;
CarOwnership own = v.GetComponent<CarOwnership>();
string title = (own != null && !string.IsNullOrEmpty(own.carTitle)) ? own.carTitle : v.gameObject.name.Replace("(Clone)", "").Trim();
seen.Add(v.transform);
result.Add((v.transform, title));
}
return result;
}
private EnginePart FindDetailedEngineTemplate(EnginePartType type)
{
var cars = CollectTargetCars();
foreach (var (root, _) in cars)
{
foreach (EnginePart ep in root.GetComponentsInChildren<EnginePart>(true))
if (ep.partType == type) return ep;
foreach (CarPartMountZone z in root.GetComponentsInChildren<CarPartMountZone>(true))
{
if (z.TargetPart == null) continue;
EnginePart ep = z.TargetPart.GetComponent<EnginePart>();
if (ep != null && ep.partType == type) return ep;
}
}
foreach (EnginePart ep in FindObjectsByType<EnginePart>(FindObjectsInactive.Include, FindObjectsSortMode.None))
if (ep.partType == type) return ep;
return null;
}
private void SpawnEnginePartForShop(EnginePartType type, Vector3 pos)
{
EnginePart template = FindDetailedEngineTemplate(type);
if (template == null)
{
EnginePartFactory.CreatePart(type, null, pos, Quaternion.identity, 0.6f, true);
return;
}
CloneDetailedPart(template.gameObject, pos);
}
/// <summary>
/// Ставит объект так, чтобы визуальный низ его мешей оказался ровно в точке targetPos (независимо от пивота FBX).
/// </summary>
private static void PlaceBottomAt(GameObject go, Vector3 targetPos)
{
if (go == null) return;
bool hasBounds = false;
Bounds worldBounds = default;
foreach (MeshFilter mf in go.GetComponentsInChildren<MeshFilter>(true))
{
if (mf.sharedMesh == null || mf.GetComponent<Renderer>() == null) continue;
Bounds mb = mf.sharedMesh.bounds;
Vector3 e = mb.extents;
for (int i = 0; i < 8; i++)
{
Vector3 corner = mb.center + new Vector3(
i % 2 == 0 ? -e.x : e.x,
(i / 2) % 2 == 0 ? -e.y : e.y,
i / 4 == 0 ? -e.z : e.z);
Vector3 wp = mf.transform.TransformPoint(corner);
if (!hasBounds) { worldBounds = new Bounds(wp, Vector3.zero); hasBounds = true; }
else worldBounds.Encapsulate(wp);
}
}
if (hasBounds)
{
Vector3 currentBottom = new Vector3(worldBounds.center.x, worldBounds.min.y, worldBounds.center.z);
go.transform.position += (targetPos + Vector3.up * 0.05f) - currentBottom;
}
else
{
go.transform.position = targetPos + Vector3.up * 0.05f;
}
Rigidbody rb = go.GetComponent<Rigidbody>();
if (rb != null)
{
rb.position = go.transform.position;
rb.rotation = go.transform.rotation;
rb.linearVelocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
}
Physics.SyncTransforms();
}
/// <summary>
/// Создаёт чистую новую копию детализированной 3D-детали с авто и ставит её точно на стол выдачи.
/// </summary>
private static GameObject CloneDetailedPart(GameObject template, Vector3 spawnPos)
{
Vector3 worldScale = template.transform.lossyScale;
Quaternion rot = template.transform.rotation;
GameObject tempHolder = new GameObject("_ShopCloneTemp");
tempHolder.SetActive(false);
GameObject clone = Instantiate(template, tempHolder.transform);
clone.SetActive(false);
clone.transform.SetParent(null, false);
Destroy(tempHolder);
// Убираем старые Rigidbody, скопированные с детали на полу, чтобы физика не тянула клон назад
foreach (Rigidbody oldRb in clone.GetComponentsInChildren<Rigidbody>(true))
DestroyImmediate(oldRb);
clone.name = template.name.Replace("_New", "") + "_New";
clone.transform.localScale = worldScale;
clone.transform.rotation = rot;
clone.transform.position = spawnPos;
Material dirtMat = PartCatalog.DirtOverlayMaterial;
if (dirtMat != null)
{
foreach (Renderer r in clone.GetComponentsInChildren<Renderer>(true))
{
Material[] mats = r.sharedMaterials;
int count = 0;
for (int i = 0; i < mats.Length; i++)
if (mats[i] != dirtMat) count++;
if (count != mats.Length)
{
Material[] clean = new Material[count];
int k = 0;
for (int i = 0; i < mats.Length; i++)
if (mats[i] != dirtMat) clean[k++] = mats[i];
r.sharedMaterials = clean;
}
}
}
int layer = EnginePartFactory.InteractLayer;
if (layer >= 0)
{
foreach (Transform t in clone.GetComponentsInChildren<Transform>(true))
t.gameObject.layer = layer;
}
if (clone.GetComponent<Collider>() == null)
{
BoxCollider bc = clone.AddComponent<BoxCollider>();
Bounds lb = EnginePartFactory.LocalBounds(clone.transform);
bc.center = lb.center;
bc.size = Vector3.Max(lb.size, Vector3.one * 0.08f);
}
// Выравниваем визуальный низ модели на стол выдачи ДО активации и создания нового Rigidbody
PlaceBottomAt(clone, spawnPos);
clone.SetActive(true);
CarPartAnimator anim = clone.GetComponent<CarPartAnimator>();
if (anim != null) anim.ResetToClosed();
EnginePart ep = clone.GetComponent<EnginePart>();
if (ep != null) ep.SetAsNew();
CarPartVisuals visuals = clone.GetComponent<CarPartVisuals>();
if (visuals != null)
{
visuals.SetDamage(0f);
visuals.SetDirt(0f);
visuals.SetHiddenRepaint(false);
}
CarWheelCondition wc = clone.GetComponent<CarWheelCondition>();
if (wc != null) wc.ApplyState(CarWheelCondition.TireState.Normal);
CarPart cp = clone.GetComponent<CarPart>();
if (cp != null) cp.InitializeAsLoosePart();
// Повторно синхронизируем позицию с новым Rigidbody
PlaceBottomAt(clone, spawnPos);
return clone;
}
// ===================== МАГАЗИН =====================
private void BuildShop()
{
items.Clear();
var engineTypes = new List<EnginePartType>
{
EnginePartType.Battery,
EnginePartType.SparkPlugs,
EnginePartType.AirFilter,
EnginePartType.OilFilter,
EnginePartType.Radiator,
EnginePartType.Alternator
};
if (FindDetailedEngineTemplate(EnginePartType.FuelFilter) != null)
engineTypes.Add(EnginePartType.FuelFilter);
foreach (EnginePartType t in engineTypes)
{
EnginePartType type = t;
CarPartData d = PartCatalog.Instance.GetEngineData(type);
float price = d != null && d.basePrice > 0f ? d.basePrice : EnginePart.GetDefaultPrice(type);
items.Add(new ShopItem
{
title = EnginePart.GetDisplayName(type) + " (новый)",
category = "Подкапотные агрегаты",
price = price,
spawn = pos => SpawnEnginePartForShop(type, pos)
});
}
foreach (FluidType t in new[] { FluidType.EngineOil, FluidType.Coolant, FluidType.BrakeFluid, FluidType.WasherFluid })
{
FluidType type = t;
items.Add(new ShopItem
{
title = FluidCanister.GetDefaultTitle(type),
category = "Автохимия и жидкости",
price = CanisterPrice(type),
spawn = pos => SpawnCanister(type, pos)
});
}
foreach (var (carRoot, carTitle) in CollectTargetCars())
{
CarPart wheelTemplate = null;
foreach (CarPart p in carRoot.GetComponentsInChildren<CarPart>(true))
{
if (!p.IsWheel) continue;
if (wheelTemplate == null || (p.State == PartState.Installed && p.gameObject.activeInHierarchy))
wheelTemplate = p;
}
if (wheelTemplate != null)
{
CarPart template = wheelTemplate;
items.Add(new ShopItem
{
title = $"Колесо в сборе — {carTitle}",
category = "Колеса",
price = wheelPrice,
spawn = pos => CarWheelCondition.CreateSpareFrom(template, pos)
});
}
HashSet<CarPart> listedBody = new HashSet<CarPart>();
foreach (CarPartMountZone z in carRoot.GetComponentsInChildren<CarPartMountZone>(true))
{
CarPart target = z.TargetPart;
if (target == null || target.IsWheel || target.GetComponent<EnginePart>() != null) continue;
if (!listedBody.Add(target)) continue;
CarPart t2 = target;
items.Add(new ShopItem
{
title = $"{t2.DisplayName} (новая) — {carTitle}",
category = "Кузовные панели",
price = t2.Data != null ? t2.Data.basePrice : 150f,
spawn = pos =>
{
if (!t2.gameObject.activeInHierarchy)
{
t2.SpawnAsNewPart(pos);
PlaceBottomAt(t2.gameObject, pos);
}
else
{
CloneDetailedPart(t2.gameObject, pos);
}
}
});
}
}
}
private static float CanisterPrice(FluidType t)
{
switch (t)
{
case FluidType.EngineOil: return 38f;
case FluidType.Coolant: return 22f;
case FluidType.BrakeFluid: return 12f;
default: return 6f;
}
}
public static FluidCanister SpawnCanister(FluidType type, Vector3 pos)
{
GameObject prefab = PartCatalog.Instance.GetCanister(type);
GameObject go;
if (prefab != null)
{
go = Instantiate(prefab, pos, Quaternion.identity);
}
else
{
go = new GameObject("Canister_" + type);
go.transform.position = pos;
EnginePartFactory.Prim(PrimitiveType.Cube, go.transform, "Body", Vector3.zero, new Vector3(0.2f, 0.28f, 0.12f),
PartCatalog.Instance.GetMaterial("canister_" + type, FluidCanister.GetDefaultColor(type)));
BoxCollider bc = go.AddComponent<BoxCollider>();
bc.size = new Vector3(0.2f, 0.3f, 0.12f);
go.AddComponent<FluidCanister>();
}
go.layer = EnginePartFactory.InteractLayer;
FluidCanister can = go.GetComponent<FluidCanister>();
if (can == null) can = go.AddComponent<FluidCanister>();
can.Configure(type, FluidCanister.GetDefaultTitle(type), FluidCanister.GetDefaultLiters(type), FluidCanister.GetDefaultColor(type));
Rigidbody rb = go.GetComponent<Rigidbody>();
if (rb == null) rb = go.AddComponent<Rigidbody>();
rb.mass = 4f;
rb.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative;
PlaceBottomAt(go, pos);
return can;
}
private void BuyItem(ShopItem item)
{
GameEconomyManager eco = GameEconomyManager.Instance;
if (eco != null && !eco.TrySpend(item.price, item.title)) return;
item.spawn?.Invoke(NextDeliveryPos());
statusLine = $"Куплено: {item.title}. Заберите заказ на столе выдачи.";
GameHUD.Notify($"Куплено: {item.title} — {GameUI.Money(item.price)}", GameUI.Green);
}
// ===================== СКЛАД =====================
private List<Component> CollectWarehouse()
{
List<Component> list = new List<Component>();
GameEconomyManager eco = GameEconomyManager.Instance;
Vector3 center = customDelivery != null ? customDelivery.position : (eco != null && eco.garageCenter != null ? eco.garageCenter.position : Vector3.zero);
float radius = customDelivery != null ? 15f : (eco != null ? eco.garageRadius : 30f);
foreach (CarPart p in FindObjectsByType<CarPart>(FindObjectsSortMode.None))
{
if (p.State != PartState.Dropped || !p.gameObject.activeInHierarchy) continue;
if (Vector3.Distance(p.transform.position, center) > radius) continue;
list.Add(p);
}
foreach (FluidCanister c in FindObjectsByType<FluidCanister>(FindObjectsSortMode.None))
{
if (c.State != FluidCanister.CanisterState.OnGround) continue;
if (Vector3.Distance(c.transform.position, center) > radius) continue;
list.Add(c);
}
return list;
}
private static float KufarPrice(CarPart p)
{
float basePrice = p.Data != null && p.Data.basePrice > 0f ? p.Data.basePrice : 40f;
EnginePart ep = p.GetComponent<EnginePart>();
if (ep != null) basePrice = ep.BasePrice;
if (p.IsWheel) basePrice = 85f;
return Mathf.Max(3f, Mathf.Round(basePrice * (p.ConditionPercent / 100f) * 0.5f));
}
// ===================== ОТРИСОВКА =====================
private void OnGUI()
{
if (!isOpen) return;
GameUI.Begin(-10);
float w = GameUI.VirtualWidth;
float h = GameUI.VirtualHeight;
GameUI.DrawRect(new Rect(0, 0, w, h), GameUI.Bg.WithAlpha(0.55f));
Rect r = new Rect(w * 0.5f - 640, h * 0.5f - 440, 1280, 880);
GUI.Box(r, GUIContent.none, GameUI.PanelSolid);
GUI.Label(new Rect(r.x + 30, r.y + 16, 700, 44), "НОУТБУК ГАРАЖА", GameUI.Header);
GameEconomyManager eco = GameEconomyManager.Instance;
if (eco != null)
GUI.Label(new Rect(r.xMax - 560, r.y + 22, 530, 34), eco.Unlimited ? "Свободный режим: деньги не ограничены" : $"На счету: <color=#4CD07D>{eco.FormatMoney(eco.Money)}</color>", GameUI.Label);
if (GameUI.Btn(new Rect(r.x + 30, r.y + 70, 400, 50), "Магазин запчастей и жидкостей", tab == Tab.Shop ? GameUI.ButtonTabActive : GameUI.ButtonTab)) { tab = Tab.Shop; scroll = Vector2.zero; }
if (GameUI.Btn(new Rect(r.x + 440, r.y + 70, 400, 50), "Склад запчастей / Продажа на Куфар", tab == Tab.Warehouse ? GameUI.ButtonTabActive : GameUI.ButtonTab)) { tab = Tab.Warehouse; scroll = Vector2.zero; }
Rect view = new Rect(r.x + 30, r.y + 136, r.width - 60, r.height - 240);
if (tab == Tab.Shop) DrawShop(view);
else DrawWarehouse(view);
GUI.Label(new Rect(r.x + 30, r.yMax - 84, r.width - 300, 60), statusLine, GameUI.Small);
if (GameUI.Btn(new Rect(r.xMax - 240, r.yMax - 80, 210, 54), "ЗАКРЫТЬ [K]")) Close();
}
private void DrawShop(Rect view)
{
BuildShop();
float rowH = 50f;
int categories = 0;
string last = null;
foreach (ShopItem i in items) if (i.category != last) { categories++; last = i.category; }
float contentH = items.Count * rowH + categories * 42f + 10f;
scroll = GUI.BeginScrollView(view, scroll, new Rect(0, 0, view.width - 24, contentH));
float y = 0f;
last = null;
foreach (ShopItem item in items)
{
if (item.category != last)
{
last = item.category;
GUI.Label(new Rect(0, y + 6, view.width, 32), $"<color=#F2A93B><b>{item.category}</b></color>", GameUI.Label);
y += 42f;
}
GameUI.DrawRect(new Rect(0, y, view.width - 30, rowH - 6), GameUI.PanelLight.WithAlpha(0.5f));
GUI.Label(new Rect(14, y + 10, view.width - 420, 32), item.title, GameUI.Label);
GUI.Label(new Rect(view.width - 400, y + 10, 160, 32), GameUI.Money(item.price).Split(' ')[0], GameUI.Label);
if (GameUI.Btn(new Rect(view.width - 220, y + 4, 180, rowH - 14), "Купить", GameUI.ButtonAccent))
BuyItem(item);
y += rowH;
}
GUI.EndScrollView();
}
private void DrawWarehouse(Rect view)
{
List<Component> stock = CollectWarehouse();
float rowH = 52f;
GUI.Label(new Rect(view.x + 14, view.y - 4, 500, 30), "<b>Наименование детали</b>", GameUI.Small);
GUI.Label(new Rect(view.x + view.width - 760, view.y - 4, 180, 30), "<b>Состояние (%)</b>", GameUI.Small);
Rect inner = new Rect(view.x, view.y + 30, view.width, view.height - 30);
scroll = GUI.BeginScrollView(inner, scroll, new Rect(0, 0, inner.width - 24, Mathf.Max(inner.height, stock.Count * rowH + 10)));
float y = 0f;
if (stock.Count == 0)
GUI.Label(new Rect(10, 10, inner.width - 40, 60), "Склад пуст. Снятые детали, колеса и канистры, лежащие в гараже, появятся здесь.", GameUI.Small);
foreach (Component c in stock)
{
if (c == null) continue;
GameUI.DrawRect(new Rect(0, y, inner.width - 30, rowH - 6), GameUI.PanelLight.WithAlpha(0.5f));
if (c is CarPart part)
{
EnginePart ep = part.GetComponent<EnginePart>();
GUI.Label(new Rect(14, y + 11, inner.width - 800, 32), part.DisplayName, GameUI.Label);
string cond = ep != null ? ep.ShortStatus : $"{Mathf.RoundToInt(part.ConditionPercent)}%";
GUI.Label(new Rect(inner.width - 760, y + 11, 220, 32), cond, GameUI.Label);
if (ep != null && ep.partType == EnginePartType.Battery && ep.charge < 99f)
{
if (GameUI.Btn(new Rect(inner.width - 520, y + 4, 220, rowH - 14), $"Зарядить (${chargePrice:F0})"))
{
if (GameEconomyManager.Instance == null || GameEconomyManager.Instance.TrySpend(chargePrice, "Зарядка АКБ"))
{
ep.charge = 100f;
statusLine = "Аккумулятор заряжен зарядным устройством до 100%";
}
}
}
else if (ep != null && ep.partType == EnginePartType.AirFilter && ep.condition < 70f)
{
if (GameUI.Btn(new Rect(inner.width - 520, y + 4, 220, rowH - 14), "Очистить (продуть)"))
{
ep.condition = 70f;
statusLine = "Воздушный фильтр продут компрессором: 70%";
}
}
float price = KufarPrice(part);
if (GameUI.Btn(new Rect(inner.width - 280, y + 4, 240, rowH - 14), $"Продать на Куфар ${price:F0}", GameUI.ButtonAccent))
{
GameEconomyManager.Instance?.Earn(price, $"Куфар: {part.DisplayName}");
statusLine = $"Продано на Куфар: {part.DisplayName} за ${price:F0}";
part.HideAsSold();
}
}
else if (c is FluidCanister can)
{
GUI.Label(new Rect(14, y + 11, inner.width - 800, 32), can.FluidName, GameUI.Label);
GUI.Label(new Rect(inner.width - 760, y + 11, 220, 32), $"{can.CurrentLiters:F1} л ({Mathf.RoundToInt(can.Fill01 * 100f)}%)", GameUI.Label);
float price = Mathf.Max(1f, Mathf.Round(CanisterPrice(can.Type) * can.Fill01 * 0.5f));
if (GameUI.Btn(new Rect(inner.width - 280, y + 4, 240, rowH - 14), $"Продать на Куфар ${price:F0}", GameUI.ButtonAccent))
{
GameEconomyManager.Instance?.Earn(price, $"Куфар: {can.FluidName}");
Destroy(can.gameObject);
}
}
y += rowH;
}
GUI.EndScrollView();
}
}