First Commit
This commit is contained in:
commit
eed6b79efc
2836 files changed
+948481
No files matched your search
@@ -0,0 +1,180 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
public enum GameMode { None, Career, Free }
|
||||
|
||||
/// <summary>
|
||||
/// Главный менеджер игры и экономики перекупа.
|
||||
/// isDiplomaVersion = true — «Дипломный проект»: бюджет, ДВС и жидкости, диагностика, торг, магазин, склад «Куфар», продажа с прибылью.
|
||||
/// isDiplomaVersion = false — «Курсовая работа»: авторынок, GPS, мойка, колеса с домкратом, кузовной ремонт и тест-драйв.
|
||||
/// </summary>
|
||||
public class GameEconomyManager : MonoBehaviour
|
||||
{
|
||||
public static GameEconomyManager Instance { get; private set; }
|
||||
|
||||
[Header("Версия проекта")]
|
||||
[Tooltip("true — полный Дипломный проект, false — базовая Курсовая работа")]
|
||||
public bool isDiplomaVersion = true;
|
||||
|
||||
[Header("Экономика")]
|
||||
[SerializeField] private float startCapitalUsd = 5000f;
|
||||
[SerializeField] private float bynPerUsd = 3.27f;
|
||||
[SerializeField] private float autosalonGoalUsd = 25000f;
|
||||
|
||||
[Header("Гараж игрока")]
|
||||
public Transform garageCenter;
|
||||
public float garageRadius = 24f;
|
||||
public Transform garageCarSpot;
|
||||
public Transform deliveryPoint;
|
||||
public Transform playerSpawnPoint;
|
||||
|
||||
public GameMode Mode { get; private set; } = GameMode.None;
|
||||
public float Money { get; private set; }
|
||||
public int DealsCompleted { get; private set; }
|
||||
public float TotalProfit { get; private set; }
|
||||
public bool AutosalonOpened { get; private set; }
|
||||
public float AutosalonGoal => autosalonGoalUsd;
|
||||
public float StartCapital => startCapitalUsd;
|
||||
|
||||
/// <summary>Свободный режим: деньги не ограничены.</summary>
|
||||
public bool Unlimited => Mode != GameMode.Career;
|
||||
public bool DiplomaFeatures => isDiplomaVersion;
|
||||
|
||||
public event Action<float> OnMoneyChanged;
|
||||
public event Action OnAutosalonOpened;
|
||||
|
||||
private readonly List<string> history = new List<string>();
|
||||
public IReadOnlyList<string> History => history;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
if (Instance != null && Instance != this)
|
||||
{
|
||||
Destroy(this);
|
||||
return;
|
||||
}
|
||||
Instance = this;
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
if (Instance == this) Instance = null;
|
||||
}
|
||||
|
||||
public void StartGame(GameMode mode)
|
||||
{
|
||||
Mode = mode;
|
||||
Money = mode == GameMode.Career ? startCapitalUsd : 0f;
|
||||
DealsCompleted = 0;
|
||||
TotalProfit = 0f;
|
||||
AutosalonOpened = false;
|
||||
history.Clear();
|
||||
OnMoneyChanged?.Invoke(Money);
|
||||
}
|
||||
|
||||
public string FormatMoney(float usd)
|
||||
{
|
||||
string sign = usd < 0 ? "-" : "";
|
||||
float a = Mathf.Abs(usd);
|
||||
return $"{sign}${a:N0} ({sign}{a * bynPerUsd:N0} BYN)";
|
||||
}
|
||||
|
||||
public string FormatShort(float usd) => (usd < 0 ? "-$" : "$") + Mathf.Abs(usd).ToString("N0");
|
||||
|
||||
public bool CanAfford(float usd) => Unlimited || Money + 0.01f >= usd;
|
||||
|
||||
/// <summary>Списать деньги. Затраты автоматически записываются на машину (для отчета о прибыли).</summary>
|
||||
public bool TrySpend(float usd, string reason, CarOwnership forCar = null, bool attributeToCar = true)
|
||||
{
|
||||
if (usd <= 0f) return true;
|
||||
if (!CanAfford(usd))
|
||||
{
|
||||
GameHUD.Notify($"Недостаточно средств! Нужно {FormatShort(usd)}, на счету {FormatShort(Money)}", GameUI.Red);
|
||||
ProceduralAudioManager.Instance?.Play(SfxId.Error);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!Unlimited)
|
||||
{
|
||||
Money -= usd;
|
||||
OnMoneyChanged?.Invoke(Money);
|
||||
}
|
||||
|
||||
if (attributeToCar)
|
||||
{
|
||||
if (forCar == null) forCar = FindCarForExpense();
|
||||
if (forCar != null) forCar.AddExpense(usd, reason);
|
||||
}
|
||||
|
||||
history.Add($"−{FormatShort(usd)} {reason}");
|
||||
ProceduralAudioManager.Instance?.Play(SfxId.Cash);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Earn(float usd, string reason)
|
||||
{
|
||||
if (usd <= 0f) return;
|
||||
if (!Unlimited)
|
||||
{
|
||||
Money += usd;
|
||||
OnMoneyChanged?.Invoke(Money);
|
||||
}
|
||||
history.Add($"+{FormatShort(usd)} {reason}");
|
||||
ProceduralAudioManager.Instance?.Play(SfxId.Cash);
|
||||
CheckAutosalonGoal();
|
||||
}
|
||||
|
||||
public void RegisterDeal(float profit)
|
||||
{
|
||||
DealsCompleted++;
|
||||
TotalProfit += profit;
|
||||
CheckAutosalonGoal();
|
||||
}
|
||||
|
||||
private void CheckAutosalonGoal()
|
||||
{
|
||||
if (AutosalonOpened || Mode != GameMode.Career) return;
|
||||
if (Money >= autosalonGoalUsd)
|
||||
{
|
||||
AutosalonOpened = true;
|
||||
OnAutosalonOpened?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsInGarage(Vector3 worldPos)
|
||||
{
|
||||
if (garageCenter == null) return true;
|
||||
Vector3 d = worldPos - garageCenter.position;
|
||||
d.y = 0f;
|
||||
return d.magnitude <= garageRadius;
|
||||
}
|
||||
|
||||
/// <summary>Машина игрока, на которую списываются расходы (ближайшая к гаражу купленная).</summary>
|
||||
public CarOwnership FindCarForExpense()
|
||||
{
|
||||
CarOwnership best = null;
|
||||
float bestDist = float.MaxValue;
|
||||
Vector3 center = garageCenter != null ? garageCenter.position : Vector3.zero;
|
||||
|
||||
foreach (CarOwnership c in CarOwnership.All)
|
||||
{
|
||||
if (c == null || !c.isOwned) continue;
|
||||
float d = Vector3.Distance(c.transform.position, center);
|
||||
if (d < bestDist)
|
||||
{
|
||||
bestDist = d;
|
||||
best = c;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
public Vector3 GetDeliveryPosition(int index = 0)
|
||||
{
|
||||
Vector3 basePos = deliveryPoint != null ? deliveryPoint.position : (garageCenter != null ? garageCenter.position + Vector3.up : Vector3.up);
|
||||
Vector3 right = deliveryPoint != null ? deliveryPoint.right : Vector3.right;
|
||||
int slot = index % 5;
|
||||
return basePos + right * ((slot - 2) * 0.45f) + Vector3.up * (0.25f + (index / 5) * 0.35f);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8f574617d139dfa43963e53d3955d024
|
||||
@@ -0,0 +1,57 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// Единая блокировка управления игроком при открытых окнах (меню, планшет, торг, склад, радиальное меню).
|
||||
/// Пока хотя бы одно окно держит блокировку — курсор свободен, а ходьба, обзор, луч и инструменты отключены.
|
||||
/// </summary>
|
||||
public static class GameInputLock
|
||||
{
|
||||
private static readonly HashSet<object> owners = new HashSet<object>();
|
||||
|
||||
public static bool IsLocked => owners.Count > 0;
|
||||
|
||||
/// <summary>Кадр, в котором было закрыто последнее окно (чтобы Esc не открывал паузу в том же кадре).</summary>
|
||||
public static int LastUnlockFrame { get; private set; } = -1;
|
||||
public static bool WasJustUnlocked => LastUnlockFrame == Time.frameCount || LastUnlockFrame == Time.frameCount - 1;
|
||||
|
||||
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
|
||||
private static void ResetStatics()
|
||||
{
|
||||
owners.Clear();
|
||||
}
|
||||
|
||||
/// <summary>Сброс при загрузке сцены (окна прошлой сцены уничтожены).</summary>
|
||||
public static void ClearAll()
|
||||
{
|
||||
owners.Clear();
|
||||
ApplyCursor();
|
||||
}
|
||||
|
||||
public static bool IsLockedBy(object owner) => owner != null && owners.Contains(owner);
|
||||
|
||||
/// <summary>Заблокирован ли ввод кем-то кроме указанного владельца.</summary>
|
||||
public static bool IsLockedByOther(object owner)
|
||||
{
|
||||
if (owners.Count == 0) return false;
|
||||
if (owners.Count == 1 && owner != null && owners.Contains(owner)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void Set(object owner, bool locked)
|
||||
{
|
||||
if (owner == null) return;
|
||||
bool changed = locked ? owners.Add(owner) : owners.Remove(owner);
|
||||
if (changed && !locked) LastUnlockFrame = Time.frameCount;
|
||||
if (changed) ApplyCursor();
|
||||
}
|
||||
|
||||
public static void Lock(object owner) => Set(owner, true);
|
||||
public static void Unlock(object owner) => Set(owner, false);
|
||||
|
||||
public static void ApplyCursor()
|
||||
{
|
||||
Cursor.lockState = IsLocked ? CursorLockMode.None : CursorLockMode.Locked;
|
||||
Cursor.visible = IsLocked;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3f9215cff0aeb7d4b954a9f41519c9a0
|
||||
@@ -0,0 +1,206 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// Общий стиль резервного интерфейса OnGUI (асфальтово-индустриальная палитра #16181D).
|
||||
/// Все окна рисуются в виртуальном разрешении высотой 1080 px и масштабируются под любой экран,
|
||||
/// поэтому интерфейс гарантированно отображается даже при пустых ссылках в Инспекторе.
|
||||
/// </summary>
|
||||
public static class GameUI
|
||||
{
|
||||
public const float RefHeight = 1080f;
|
||||
|
||||
public static readonly Color Bg = Hex("16181D");
|
||||
public static readonly Color PanelColor = Hex("1E2128");
|
||||
public static readonly Color PanelLight = Hex("2A2E37");
|
||||
public static readonly Color Accent = Hex("F2A93B");
|
||||
public static readonly Color Green = Hex("4CD07D");
|
||||
public static readonly Color Red = Hex("E5534B");
|
||||
public static readonly Color Blue = Hex("4FA3F7");
|
||||
public static readonly Color TextColor = Hex("E8E9EB");
|
||||
public static readonly Color Muted = Hex("9AA0A6");
|
||||
|
||||
private static bool initialized;
|
||||
private static readonly Dictionary<string, Texture2D> texCache = new Dictionary<string, Texture2D>();
|
||||
|
||||
public static GUIStyle Panel, PanelSolid, Title, Header, Label, LabelCenter, Small, SmallCenter, Button, ButtonAccent, ButtonDanger, ButtonTab, ButtonTabActive, Badge;
|
||||
|
||||
public static float Scale => Screen.height / RefHeight;
|
||||
public static float VirtualWidth => Screen.width / Mathf.Max(Scale, 0.01f);
|
||||
public static float VirtualHeight => RefHeight;
|
||||
|
||||
public static Color Hex(string hex)
|
||||
{
|
||||
ColorUtility.TryParseHtmlString("#" + hex, out Color c);
|
||||
return c;
|
||||
}
|
||||
|
||||
/// <summary>Вызывать в начале каждого OnGUI: включает масштабирование и стили.</summary>
|
||||
public static void Begin(int depth = 0)
|
||||
{
|
||||
EnsureStyles();
|
||||
GUI.depth = depth;
|
||||
float s = Scale;
|
||||
GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(s, s, 1f));
|
||||
}
|
||||
|
||||
public static Vector2 MouseVirtual()
|
||||
{
|
||||
Vector2 m = Event.current != null ? Event.current.mousePosition : Vector2.zero;
|
||||
return m;
|
||||
}
|
||||
|
||||
private static void EnsureStyles()
|
||||
{
|
||||
if (initialized && Panel != null && Panel.normal.background != null) return;
|
||||
initialized = true;
|
||||
|
||||
Panel = new GUIStyle(GUI.skin.box)
|
||||
{
|
||||
normal = { background = Rounded(PanelColor.WithAlpha(0.96f), Hex("3A3F4A"), 12, 2) },
|
||||
border = new RectOffset(14, 14, 14, 14),
|
||||
padding = new RectOffset(20, 20, 18, 18)
|
||||
};
|
||||
|
||||
PanelSolid = new GUIStyle(Panel)
|
||||
{
|
||||
normal = { background = Rounded(Bg, Hex("2F333C"), 12, 2) }
|
||||
};
|
||||
|
||||
Badge = new GUIStyle(GUI.skin.box)
|
||||
{
|
||||
normal = { background = Rounded(Hex("101216").WithAlpha(0.82f), Hex("2F333C"), 10, 1), textColor = TextColor },
|
||||
border = new RectOffset(12, 12, 12, 12),
|
||||
padding = new RectOffset(12, 12, 6, 6),
|
||||
fontSize = 18,
|
||||
alignment = TextAnchor.MiddleLeft,
|
||||
richText = true
|
||||
};
|
||||
|
||||
Title = new GUIStyle(GUI.skin.label)
|
||||
{
|
||||
fontSize = 42, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleCenter,
|
||||
normal = { textColor = TextColor }, richText = true, wordWrap = true
|
||||
};
|
||||
|
||||
Header = new GUIStyle(GUI.skin.label)
|
||||
{
|
||||
fontSize = 26, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleLeft,
|
||||
normal = { textColor = Accent }, richText = true, wordWrap = true
|
||||
};
|
||||
|
||||
Label = new GUIStyle(GUI.skin.label)
|
||||
{
|
||||
fontSize = 19, alignment = TextAnchor.UpperLeft, wordWrap = true, richText = true,
|
||||
normal = { textColor = TextColor }
|
||||
};
|
||||
|
||||
LabelCenter = new GUIStyle(Label) { alignment = TextAnchor.MiddleCenter };
|
||||
|
||||
Small = new GUIStyle(Label) { fontSize = 16, normal = { textColor = Muted } };
|
||||
SmallCenter = new GUIStyle(Small) { alignment = TextAnchor.MiddleCenter };
|
||||
|
||||
Button = MakeButton(Hex("2E333D"), Hex("3B414D"), Hex("4A5160"), TextColor);
|
||||
ButtonAccent = MakeButton(Hex("C9862A"), Accent, Hex("FFC266"), Hex("16181D"));
|
||||
ButtonDanger = MakeButton(Hex("8E2F2A"), Red, Hex("FF7A70"), Color.white);
|
||||
ButtonTab = MakeButton(Hex("23262E"), Hex("2E333D"), Hex("3B414D"), Muted);
|
||||
ButtonTabActive = MakeButton(Hex("3B414D"), Hex("444B59"), Hex("4A5160"), Accent);
|
||||
}
|
||||
|
||||
private static GUIStyle MakeButton(Color normal, Color hover, Color active, Color text)
|
||||
{
|
||||
return new GUIStyle(GUI.skin.button)
|
||||
{
|
||||
fontSize = 19,
|
||||
fontStyle = FontStyle.Bold,
|
||||
alignment = TextAnchor.MiddleCenter,
|
||||
wordWrap = true,
|
||||
richText = true,
|
||||
border = new RectOffset(10, 10, 10, 10),
|
||||
padding = new RectOffset(12, 12, 6, 6),
|
||||
normal = { background = Rounded(normal, null, 8, 0), textColor = text },
|
||||
hover = { background = Rounded(hover, null, 8, 0), textColor = text },
|
||||
active = { background = Rounded(active, null, 8, 0), textColor = text },
|
||||
focused = { background = Rounded(normal, null, 8, 0), textColor = text }
|
||||
};
|
||||
}
|
||||
|
||||
public static Color WithAlpha(this Color c, float a) { c.a = a; return c; }
|
||||
|
||||
public static GUIStyle WithCenter(this GUIStyle s) => new GUIStyle(s) { alignment = TextAnchor.MiddleCenter };
|
||||
|
||||
public static Texture2D Solid(Color c)
|
||||
{
|
||||
string key = "s" + ColorUtility.ToHtmlStringRGBA(c);
|
||||
if (texCache.TryGetValue(key, out Texture2D t) && t != null) return t;
|
||||
t = new Texture2D(1, 1, TextureFormat.RGBA32, false) { hideFlags = HideFlags.HideAndDontSave };
|
||||
t.SetPixel(0, 0, c);
|
||||
t.Apply();
|
||||
texCache[key] = t;
|
||||
return t;
|
||||
}
|
||||
|
||||
/// <summary>Текстура скругленного прямоугольника для 9-slice фона окон и кнопок.</summary>
|
||||
public static Texture2D Rounded(Color fill, Color? border, int radius, int borderWidth)
|
||||
{
|
||||
string key = $"r{ColorUtility.ToHtmlStringRGBA(fill)}_{(border.HasValue ? ColorUtility.ToHtmlStringRGBA(border.Value) : "n")}_{radius}_{borderWidth}";
|
||||
if (texCache.TryGetValue(key, out Texture2D cached) && cached != null) return cached;
|
||||
|
||||
int size = radius * 2 + 4;
|
||||
Texture2D tex = new Texture2D(size, size, TextureFormat.RGBA32, false)
|
||||
{
|
||||
hideFlags = HideFlags.HideAndDontSave,
|
||||
wrapMode = TextureWrapMode.Clamp,
|
||||
filterMode = FilterMode.Bilinear
|
||||
};
|
||||
|
||||
for (int y = 0; y < size; y++)
|
||||
{
|
||||
for (int x = 0; x < size; x++)
|
||||
{
|
||||
float cx = Mathf.Clamp(x + 0.5f, radius, size - radius);
|
||||
float cy = Mathf.Clamp(y + 0.5f, radius, size - radius);
|
||||
float d = Vector2.Distance(new Vector2(x + 0.5f, y + 0.5f), new Vector2(cx, cy));
|
||||
float alpha = Mathf.Clamp01(radius - d + 0.5f);
|
||||
Color c = fill;
|
||||
if (border.HasValue && borderWidth > 0 && d > radius - borderWidth - 0.5f)
|
||||
c = border.Value;
|
||||
c.a *= alpha;
|
||||
tex.SetPixel(x, y, c);
|
||||
}
|
||||
}
|
||||
tex.Apply();
|
||||
texCache[key] = tex;
|
||||
return tex;
|
||||
}
|
||||
|
||||
public static void DrawRect(Rect r, Color c)
|
||||
{
|
||||
GUI.DrawTexture(r, Solid(c));
|
||||
}
|
||||
|
||||
public static void ProgressBar(Rect r, float value01, Color fill, string caption = null)
|
||||
{
|
||||
DrawRect(r, Hex("0E1013"));
|
||||
Rect f = new Rect(r.x + 2, r.y + 2, Mathf.Max(0f, (r.width - 4) * Mathf.Clamp01(value01)), r.height - 4);
|
||||
DrawRect(f, fill);
|
||||
if (!string.IsNullOrEmpty(caption))
|
||||
GUI.Label(r, caption, SmallCenter);
|
||||
}
|
||||
|
||||
/// <summary>Кнопка со звуком нажатия.</summary>
|
||||
public static bool Btn(Rect r, string text, GUIStyle style = null)
|
||||
{
|
||||
bool pressed = GUI.Button(r, text, style ?? Button);
|
||||
if (pressed) ProceduralAudioManager.Instance?.PlayUi();
|
||||
return pressed;
|
||||
}
|
||||
|
||||
public static string Money(float usd)
|
||||
{
|
||||
GameEconomyManager eco = GameEconomyManager.Instance;
|
||||
return eco != null ? eco.FormatMoney(usd) : $"${usd:N0}";
|
||||
}
|
||||
|
||||
public static string Check(bool ok) => ok ? "<color=#4CD07D>●</color>" : "<color=#E5534B>●</color>";
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 31f032666548afa4397485bd3185817c
|
||||
@@ -0,0 +1,229 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// Справочник данных деталей, канистр и материалов (Resources/Perekup/PartCatalog).
|
||||
/// Создается автонастройкой «Arcade Simulator → Auto-Setup». Если ассета нет — используются
|
||||
/// безопасные процедурные значения по умолчанию, чтобы игра никогда не падала с NullReference.
|
||||
/// </summary>
|
||||
[CreateAssetMenu(fileName = "PartCatalog", menuName = "Car System/Part Catalog")]
|
||||
public class PartCatalog : ScriptableObject
|
||||
{
|
||||
[Header("Подкапотные агрегаты")]
|
||||
public CarPartData battery;
|
||||
public CarPartData sparkPlugs;
|
||||
public CarPartData airFilter;
|
||||
public CarPartData oilFilter;
|
||||
public CarPartData radiator;
|
||||
public CarPartData alternator;
|
||||
public CarPartData fuelFilter;
|
||||
|
||||
[Header("Кузов и ходовая")]
|
||||
public CarPartData wheel;
|
||||
public CarPartData hood;
|
||||
public CarPartData door;
|
||||
public CarPartData trunk;
|
||||
public CarPartData fender;
|
||||
public CarPartData bumperFront;
|
||||
public CarPartData bumperBack;
|
||||
|
||||
[Header("Канистры технических жидкостей")]
|
||||
public GameObject canisterEngineOil;
|
||||
public GameObject canisterCoolant;
|
||||
public GameObject canisterBrakeFluid;
|
||||
public GameObject canisterWasherFluid;
|
||||
|
||||
[Header("Материалы")]
|
||||
public Material ghost;
|
||||
public Material carPaint;
|
||||
public List<NamedMaterial> materials = new List<NamedMaterial>();
|
||||
|
||||
[Serializable]
|
||||
public class NamedMaterial
|
||||
{
|
||||
public string key;
|
||||
public Material material;
|
||||
}
|
||||
|
||||
private static PartCatalog cached;
|
||||
private static readonly Dictionary<string, Material> runtimeMaterials = new Dictionary<string, Material>();
|
||||
|
||||
public static PartCatalog Instance
|
||||
{
|
||||
get
|
||||
{
|
||||
if (cached != null) return cached;
|
||||
cached = Resources.Load<PartCatalog>("Perekup/PartCatalog");
|
||||
if (cached == null)
|
||||
{
|
||||
cached = CreateInstance<PartCatalog>();
|
||||
cached.hideFlags = HideFlags.DontSave;
|
||||
}
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Сброс кэша после создания/изменения ассета каталога автонастройкой.</summary>
|
||||
public static void ResetCache()
|
||||
{
|
||||
cached = null;
|
||||
particleMaterial = null;
|
||||
dirtOverlay = null;
|
||||
runtimeMaterials.Clear();
|
||||
}
|
||||
|
||||
public CarPartData GetEngineData(EnginePartType type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case EnginePartType.Battery: return battery;
|
||||
case EnginePartType.SparkPlugs: return sparkPlugs;
|
||||
case EnginePartType.AirFilter: return airFilter;
|
||||
case EnginePartType.OilFilter: return oilFilter;
|
||||
case EnginePartType.Radiator: return radiator;
|
||||
case EnginePartType.Alternator: return alternator;
|
||||
case EnginePartType.FuelFilter: return fuelFilter;
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
|
||||
public GameObject GetCanister(FluidType type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case FluidType.EngineOil: return canisterEngineOil;
|
||||
case FluidType.Coolant: return canisterCoolant;
|
||||
case FluidType.BrakeFluid: return canisterBrakeFluid;
|
||||
case FluidType.WasherFluid: return canisterWasherFluid;
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Материал по ключу (metal, black, battery, red, blue, yellow, white, rubber, copper, steam...).</summary>
|
||||
public Material GetMaterial(string key, Color fallbackColor)
|
||||
{
|
||||
foreach (NamedMaterial nm in materials)
|
||||
if (nm != null && nm.key == key && nm.material != null)
|
||||
return nm.material;
|
||||
|
||||
if (runtimeMaterials.TryGetValue(key, out Material m) && m != null) return m;
|
||||
m = CreateLitMaterial(fallbackColor);
|
||||
m.name = "Runtime_" + key;
|
||||
runtimeMaterials[key] = m;
|
||||
return m;
|
||||
}
|
||||
|
||||
private static Material particleMaterial;
|
||||
private static Material dirtOverlay;
|
||||
|
||||
/// <summary>Материал слоя грязи (прозрачная текстура подтеков/пыли), из каталога или процедурный.</summary>
|
||||
public static Material DirtOverlayMaterial
|
||||
{
|
||||
get
|
||||
{
|
||||
if (dirtOverlay != null) return dirtOverlay;
|
||||
foreach (NamedMaterial nm in Instance.materials)
|
||||
if (nm != null && nm.key == "dirt_overlay" && nm.material != null) return dirtOverlay = nm.material;
|
||||
|
||||
dirtOverlay = CreateLitMaterial(Color.white, 0.05f);
|
||||
dirtOverlay.name = "Runtime_DirtOverlay";
|
||||
Texture2D tex = GenerateDirtTexture(256);
|
||||
if (dirtOverlay.HasProperty("_BaseMap")) dirtOverlay.SetTexture("_BaseMap", tex);
|
||||
dirtOverlay.mainTexture = tex;
|
||||
MakeTransparent(dirtOverlay);
|
||||
return dirtOverlay;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Процедурная текстура грязи: землистые разводы и брызги снизу с альфа-каналом.</summary>
|
||||
public static Texture2D GenerateDirtTexture(int size)
|
||||
{
|
||||
Texture2D t = new Texture2D(size, size, TextureFormat.RGBA32, true) { name = "Tex_Dirt", wrapMode = TextureWrapMode.Repeat };
|
||||
Color mud = new Color(0.33f, 0.27f, 0.19f);
|
||||
Color dust = new Color(0.55f, 0.5f, 0.42f);
|
||||
for (int y = 0; y < size; y++)
|
||||
{
|
||||
for (int x = 0; x < size; x++)
|
||||
{
|
||||
float u = x / (float)size, v = y / (float)size;
|
||||
float n1 = Mathf.PerlinNoise(u * 6f + 3.1f, v * 6f + 7.7f);
|
||||
float n2 = Mathf.PerlinNoise(u * 22f + 11.3f, v * 22f + 1.9f);
|
||||
float n3 = Mathf.PerlinNoise(u * 60f, v * 60f);
|
||||
float a = Mathf.Clamp01(0.35f + n1 * 0.55f + (n2 - 0.5f) * 0.5f + (n3 - 0.5f) * 0.25f);
|
||||
Color c = Color.Lerp(mud, dust, n2);
|
||||
c.a = a;
|
||||
t.SetPixel(x, y, c);
|
||||
}
|
||||
}
|
||||
t.Apply();
|
||||
return t;
|
||||
}
|
||||
|
||||
/// <summary>Общий материал частиц (вода, пар, масло, краска) с поддержкой цвета вершин.</summary>
|
||||
public static Material ParticleMaterial
|
||||
{
|
||||
get
|
||||
{
|
||||
if (particleMaterial != null) return particleMaterial;
|
||||
Material fromCatalog = null;
|
||||
foreach (NamedMaterial nm in Instance.materials)
|
||||
if (nm != null && nm.key == "fx_particle" && nm.material != null) fromCatalog = nm.material;
|
||||
if (fromCatalog != null) return particleMaterial = fromCatalog;
|
||||
|
||||
Shader sh = Shader.Find("Universal Render Pipeline/Particles/Unlit") ?? Shader.Find("Particles/Standard Unlit") ?? Shader.Find("Sprites/Default");
|
||||
particleMaterial = new Material(sh) { name = "Runtime_Particles" };
|
||||
MakeTransparent(particleMaterial);
|
||||
return particleMaterial;
|
||||
}
|
||||
}
|
||||
|
||||
public static Material CreateLitMaterial(Color color, float smoothness = 0.35f, float metallic = 0f)
|
||||
{
|
||||
Shader sh = Shader.Find("Universal Render Pipeline/Lit") ?? Shader.Find("Standard");
|
||||
Material m = new Material(sh);
|
||||
if (m.HasProperty("_BaseColor")) m.SetColor("_BaseColor", color);
|
||||
m.color = color;
|
||||
if (m.HasProperty("_Smoothness")) m.SetFloat("_Smoothness", smoothness);
|
||||
if (m.HasProperty("_Metallic")) m.SetFloat("_Metallic", metallic);
|
||||
return m;
|
||||
}
|
||||
|
||||
public static Material CreateUnlitMaterial(Color color, bool transparent = false)
|
||||
{
|
||||
Shader sh = Shader.Find("Universal Render Pipeline/Unlit") ?? Shader.Find("Unlit/Color");
|
||||
Material m = new Material(sh);
|
||||
if (m.HasProperty("_BaseColor")) m.SetColor("_BaseColor", color);
|
||||
m.color = color;
|
||||
if (transparent) MakeTransparent(m);
|
||||
return m;
|
||||
}
|
||||
|
||||
public static void MakeTransparent(Material m)
|
||||
{
|
||||
if (m == null) return;
|
||||
if (m.HasProperty("_Surface"))
|
||||
{
|
||||
m.SetFloat("_Surface", 1f);
|
||||
m.SetFloat("_Blend", 0f);
|
||||
m.SetOverrideTag("RenderType", "Transparent");
|
||||
m.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
|
||||
m.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
|
||||
m.SetInt("_ZWrite", 0);
|
||||
m.EnableKeyword("_SURFACE_TYPE_TRANSPARENT");
|
||||
m.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
|
||||
}
|
||||
}
|
||||
|
||||
public static Material CreateEmissiveMaterial(Color baseColor, Color emission)
|
||||
{
|
||||
Material m = CreateLitMaterial(baseColor, 0.6f);
|
||||
if (m.HasProperty("_EmissionColor"))
|
||||
{
|
||||
m.EnableKeyword("_EMISSION");
|
||||
m.SetColor("_EmissionColor", emission);
|
||||
m.globalIlluminationFlags = MaterialGlobalIlluminationFlags.RealtimeEmissive;
|
||||
}
|
||||
return m;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6c7c67713f6f6c34f893fa402dadbd17
|
||||
Reference in new issue
Block a user