568 lines
25 KiB
C#
568 lines
25 KiB
C#
using System.Collections.Generic;
|
|||
|
|
using UnityEngine;
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// Подкапотное пространство автомобиля: находит съемные агрегаты ДВС и бачки жидкостей,
|
||
|
|
/// при отсутствии отдельных мешей в модели генерирует аккуратный 3D моторный отсек под капотом,
|
||
|
|
/// моделирует запуск двигателя, мощность, тормоза, перегрев и коды ошибок OBD.
|
||
|
|
/// </summary>
|
||
|
|
[DisallowMultipleComponent]
|
||
|
|
public class EngineBayManager : MonoBehaviour
|
||
|
|
{
|
||
|
|
[Header("Автонастройка")]
|
||
|
|
[Tooltip("Достраивать недостающие узлы (АКБ, свечи, фильтры, радиатор, генератор, бачки) процедурно")]
|
||
|
|
public bool autoBuildMissing = true;
|
||
|
|
public Transform engineBayRoot;
|
||
|
|
|
||
|
|
[Header("Перегрев")]
|
||
|
|
[SerializeField] private float overheatDelay = 30f;
|
||
|
|
|
||
|
|
private CarFluids fluids;
|
||
|
|
private bool built;
|
||
|
|
private float overheatTimer;
|
||
|
|
private float steamTimer;
|
||
|
|
private ParticleSystem steam;
|
||
|
|
|
||
|
|
public bool EngineRunning { get; private set; }
|
||
|
|
public bool IsOverheating => overheatTimer >= overheatDelay;
|
||
|
|
public CarFluids Fluids => fluids != null ? fluids : (fluids = GetComponent<CarFluids>());
|
||
|
|
|
||
|
|
private static bool Diploma => GameEconomyManager.Instance == null || GameEconomyManager.Instance.DiplomaFeatures;
|
||
|
|
|
||
|
|
private void Awake()
|
||
|
|
{
|
||
|
|
fluids = GetComponent<CarFluids>();
|
||
|
|
if (fluids == null) fluids = gameObject.AddComponent<CarFluids>();
|
||
|
|
EnsureBuilt();
|
||
|
|
}
|
||
|
|
|
||
|
|
public void EnsureBuilt()
|
||
|
|
{
|
||
|
|
if (built) return;
|
||
|
|
built = true;
|
||
|
|
BuildEngineBay(transform, autoBuildMissing);
|
||
|
|
if (fluids == null) fluids = GetComponent<CarFluids>();
|
||
|
|
if (fluids != null) fluids.InitializeCaps();
|
||
|
|
CreateSteamEffect();
|
||
|
|
}
|
||
|
|
|
||
|
|
// ===================== ПОСТРОЕНИЕ ОТСЕКА =====================
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// Находит существующие подкапотные детали по данным/именам и добавляет им EnginePart,
|
||
|
|
/// а недостающие узлы генерирует под капотом. Вызывается и из Editor-автонастройки, и в рантайме.
|
||
|
|
/// </summary>
|
||
|
|
public static void BuildEngineBay(Transform car, bool buildMissing)
|
||
|
|
{
|
||
|
|
PartCatalog cat = PartCatalog.Instance;
|
||
|
|
HashSet<EnginePartType> present = new HashSet<EnginePartType>();
|
||
|
|
|
||
|
|
foreach (EnginePart ep in car.GetComponentsInChildren<EnginePart>(true))
|
||
|
|
present.Add(ep.partType);
|
||
|
|
|
||
|
|
// 1. Существующие CarPart с данными агрегатов
|
||
|
|
foreach (CarPart part in car.GetComponentsInChildren<CarPart>(true))
|
||
|
|
{
|
||
|
|
if (part.GetComponent<EnginePart>() != null) continue;
|
||
|
|
if (TryDetectType(part.Data, part.name, cat, out EnginePartType type) && !present.Contains(type))
|
||
|
|
{
|
||
|
|
EnginePart ep = part.gameObject.AddComponent<EnginePart>();
|
||
|
|
ep.partType = type;
|
||
|
|
ep.SetAsNew();
|
||
|
|
if (part.Data == null) part.SetData(cat.GetEngineData(type), EnginePartFactory.GetMass(type));
|
||
|
|
present.Add(type);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// 2. Меши агрегатов без CarPart (например, covet_Alternator) превращаем в съемные детали
|
||
|
|
foreach (MeshRenderer r in car.GetComponentsInChildren<MeshRenderer>(true))
|
||
|
|
{
|
||
|
|
if (r.GetComponent<CarPart>() != null || r.GetComponentInParent<CarPart>() != null) continue;
|
||
|
|
string n = r.name.ToLowerInvariant();
|
||
|
|
EnginePartType type;
|
||
|
|
if (n.Contains("alternator")) type = EnginePartType.Alternator;
|
||
|
|
else if (n.Contains("battery")) type = EnginePartType.Battery;
|
||
|
|
else continue;
|
||
|
|
if (present.Contains(type)) continue;
|
||
|
|
|
||
|
|
GameObject go = r.gameObject;
|
||
|
|
go.layer = EnginePartFactory.InteractLayer;
|
||
|
|
if (go.GetComponent<Collider>() == null)
|
||
|
|
{
|
||
|
|
BoxCollider bc = go.AddComponent<BoxCollider>();
|
||
|
|
bc.isTrigger = true;
|
||
|
|
}
|
||
|
|
CarPart cp = go.AddComponent<CarPart>();
|
||
|
|
cp.SetData(cat.GetEngineData(type), EnginePartFactory.GetMass(type));
|
||
|
|
EnginePart ep = go.AddComponent<EnginePart>();
|
||
|
|
ep.partType = type;
|
||
|
|
ep.SetAsNew();
|
||
|
|
present.Add(type);
|
||
|
|
}
|
||
|
|
|
||
|
|
if (!buildMissing) return;
|
||
|
|
|
||
|
|
// 3. Геометрия моторного отсека в координатах машины
|
||
|
|
ComputeBayFrame(car, out Vector3 center, out float width, out float length, out float yTop, out float panY);
|
||
|
|
|
||
|
|
Transform bay = car.Find("Engine_Bay");
|
||
|
|
if (bay == null)
|
||
|
|
{
|
||
|
|
bay = new GameObject("Engine_Bay").transform;
|
||
|
|
bay.SetParent(car, false);
|
||
|
|
bay.localPosition = Vector3.zero;
|
||
|
|
bay.localRotation = Quaternion.identity;
|
||
|
|
}
|
||
|
|
|
||
|
|
float zFront = center.z + length * 0.5f;
|
||
|
|
float zRear = center.z - length * 0.5f;
|
||
|
|
float cx = center.x;
|
||
|
|
|
||
|
|
void Make(EnginePartType t, Vector3 p)
|
||
|
|
{
|
||
|
|
if (present.Contains(t)) return;
|
||
|
|
EnginePartFactory.CreatePart(t, bay, p, Quaternion.identity, width);
|
||
|
|
present.Add(t);
|
||
|
|
}
|
||
|
|
|
||
|
|
Make(EnginePartType.Battery, new Vector3(cx - width * 0.34f, yTop - 0.17f, zRear + length * 0.36f));
|
||
|
|
Make(EnginePartType.SparkPlugs, new Vector3(cx, yTop - 0.15f, center.z - length * 0.04f));
|
||
|
|
Make(EnginePartType.AirFilter, new Vector3(cx + width * 0.30f, yTop - 0.12f, zRear + length * 0.38f));
|
||
|
|
Make(EnginePartType.Radiator, new Vector3(cx, yTop - 0.27f, zFront - 0.03f));
|
||
|
|
Make(EnginePartType.Alternator, new Vector3(cx + width * 0.14f, yTop - 0.33f, zFront - length * 0.32f));
|
||
|
|
Make(EnginePartType.OilFilter, new Vector3(cx - width * 0.12f, yTop - 0.40f, center.z));
|
||
|
|
|
||
|
|
// Бачки и горловины технических жидкостей
|
||
|
|
HashSet<FluidType> caps = new HashSet<FluidType>();
|
||
|
|
foreach (Transform t in car.GetComponentsInChildren<Transform>(true))
|
||
|
|
{
|
||
|
|
string n = t.name.ToLowerInvariant().Replace(" ", "");
|
||
|
|
if (n.Contains("oilcap")) caps.Add(FluidType.EngineOil);
|
||
|
|
else if (n.Contains("coolantcap") || n.Contains("radcap") || n.Contains("radiatorcap")) caps.Add(FluidType.Coolant);
|
||
|
|
else if (n.Contains("washerfluidcap") || n.Contains("washercap")) caps.Add(FluidType.WasherFluid);
|
||
|
|
else if (n.Contains("brakefluidcap") || n.Contains("brakecap")) caps.Add(FluidType.BrakeFluid);
|
||
|
|
}
|
||
|
|
|
||
|
|
if (!caps.Contains(FluidType.EngineOil))
|
||
|
|
EnginePartFactory.CreateReservoir(FluidType.EngineOil, bay, new Vector3(cx + 0.1f, yTop - 0.09f, center.z + length * 0.12f));
|
||
|
|
if (!caps.Contains(FluidType.Coolant))
|
||
|
|
EnginePartFactory.CreateReservoir(FluidType.Coolant, bay, new Vector3(cx + width * 0.36f, yTop - 0.15f, zFront - length * 0.26f));
|
||
|
|
if (!caps.Contains(FluidType.BrakeFluid))
|
||
|
|
EnginePartFactory.CreateReservoir(FluidType.BrakeFluid, bay, new Vector3(cx - width * 0.30f, yTop - 0.10f, zRear + 0.07f));
|
||
|
|
if (!caps.Contains(FluidType.WasherFluid))
|
||
|
|
EnginePartFactory.CreateReservoir(FluidType.WasherFluid, bay, new Vector3(cx - width * 0.36f, yTop - 0.17f, zFront - length * 0.14f));
|
||
|
|
|
||
|
|
if (car.GetComponentInChildren<OilDipstick>(true) == null)
|
||
|
|
EnginePartFactory.CreateDipstick(bay, new Vector3(cx - 0.17f, yTop - 0.07f, center.z + length * 0.08f));
|
||
|
|
|
||
|
|
if (car.GetComponentInChildren<OilDrainPlug>(true) == null)
|
||
|
|
EnginePartFactory.CreateOilPan(bay, new Vector3(cx, panY, center.z - length * 0.1f), width);
|
||
|
|
}
|
||
|
|
|
||
|
|
private static bool TryDetectType(CarPartData data, string objName, PartCatalog cat, out EnginePartType type)
|
||
|
|
{
|
||
|
|
type = EnginePartType.Battery;
|
||
|
|
if (data != null)
|
||
|
|
{
|
||
|
|
if (data == cat.battery) { type = EnginePartType.Battery; return true; }
|
||
|
|
if (data == cat.sparkPlugs) { type = EnginePartType.SparkPlugs; return true; }
|
||
|
|
if (data == cat.airFilter) { type = EnginePartType.AirFilter; return true; }
|
||
|
|
if (data == cat.oilFilter) { type = EnginePartType.OilFilter; return true; }
|
||
|
|
if (data == cat.radiator) { type = EnginePartType.Radiator; return true; }
|
||
|
|
if (data == cat.alternator) { type = EnginePartType.Alternator; return true; }
|
||
|
|
if (data == cat.fuelFilter) { type = EnginePartType.FuelFilter; return true; }
|
||
|
|
}
|
||
|
|
|
||
|
|
string n = ((data != null ? data.name + " " + data.partName : "") + " " + objName).ToLowerInvariant();
|
||
|
|
if (n.Contains("battery") || n.Contains("аккумул")) { type = EnginePartType.Battery; return true; }
|
||
|
|
if (n.Contains("spark") || n.Contains("свеч")) { type = EnginePartType.SparkPlugs; return true; }
|
||
|
|
if (n.Contains("airfilter") || n.Contains("воздушн") || n.Contains("carburettor")) { type = EnginePartType.AirFilter; return true; }
|
||
|
|
if (n.Contains("oilfilter") || n.Contains("масляный фильтр")) { type = EnginePartType.OilFilter; return true; }
|
||
|
|
if (n.Contains("fuelfilter") || n.Contains("fuilfilter") || n.Contains("топлив")) { type = EnginePartType.FuelFilter; return true; }
|
||
|
|
if (n.Contains("radiator") || n.Contains("радиатор")) { type = EnginePartType.Radiator; return true; }
|
||
|
|
if (n.Contains("alternator") || n.Contains("генератор")) { type = EnginePartType.Alternator; return true; }
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
|
||
|
|
/// <summary>Рассчитывает зону моторного отсека под капотом в локальных координатах машины.</summary>
|
||
|
|
public static void ComputeBayFrame(Transform car, out Vector3 center, out float width, out float length, out float yTop, out float panY)
|
||
|
|
{
|
||
|
|
Bounds carB = LocalRendererBounds(car, car, null);
|
||
|
|
Transform hood = null;
|
||
|
|
foreach (CarPart p in car.GetComponentsInChildren<CarPart>(true))
|
||
|
|
{
|
||
|
|
string n = (p.name + " " + (p.Data != null ? p.Data.partName : "")).ToLowerInvariant();
|
||
|
|
if ((n.Contains("hood") || n.Contains("капот")) && !n.Contains("scoop"))
|
||
|
|
{
|
||
|
|
hood = p.transform;
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
if (hood == null)
|
||
|
|
{
|
||
|
|
foreach (CarPart p in car.GetComponentsInChildren<CarPart>(true))
|
||
|
|
if (p.name.ToLowerInvariant().Contains("hood")) { hood = p.transform; break; }
|
||
|
|
}
|
||
|
|
|
||
|
|
float groundY = carB.min.y;
|
||
|
|
WheelCollider[] wcs = car.GetComponentsInChildren<WheelCollider>(true);
|
||
|
|
if (wcs.Length > 0)
|
||
|
|
{
|
||
|
|
float sum = 0f;
|
||
|
|
foreach (WheelCollider wc in wcs)
|
||
|
|
sum += car.InverseTransformPoint(wc.transform.position).y - wc.radius;
|
||
|
|
groundY = sum / wcs.Length;
|
||
|
|
}
|
||
|
|
|
||
|
|
if (hood != null)
|
||
|
|
{
|
||
|
|
Bounds hb = LocalRendererBounds(car, hood, null);
|
||
|
|
width = Mathf.Clamp(hb.size.x * 0.82f, 0.9f, 1.5f);
|
||
|
|
length = Mathf.Clamp(hb.size.z * 0.82f, 0.6f, 1.3f);
|
||
|
|
center = new Vector3(hb.center.x, 0f, hb.center.z - hb.size.z * 0.02f);
|
||
|
|
yTop = hb.min.y + Mathf.Min(0.06f, hb.size.y * 0.3f) - 0.03f;
|
||
|
|
}
|
||
|
|
else
|
||
|
|
{
|
||
|
|
width = Mathf.Clamp(carB.size.x * 0.62f, 0.9f, 1.5f);
|
||
|
|
length = Mathf.Clamp(carB.size.z * 0.24f, 0.6f, 1.2f);
|
||
|
|
center = new Vector3(carB.center.x, 0f, carB.max.z - length * 0.5f - 0.3f);
|
||
|
|
yTop = groundY + carB.size.y * 0.62f;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Капот не должен «проваливаться» ниже уровня колес
|
||
|
|
yTop = Mathf.Max(yTop, groundY + 0.62f);
|
||
|
|
panY = groundY + 0.2f;
|
||
|
|
}
|
||
|
|
|
||
|
|
public static Bounds LocalRendererBounds(Transform space, Transform root, Transform exclude)
|
||
|
|
{
|
||
|
|
bool has = false;
|
||
|
|
Bounds result = new Bounds(Vector3.zero, Vector3.zero);
|
||
|
|
foreach (MeshFilter mf in root.GetComponentsInChildren<MeshFilter>(true))
|
||
|
|
{
|
||
|
|
if (mf.sharedMesh == null) continue;
|
||
|
|
if (exclude != null && mf.transform.IsChildOf(exclude)) continue;
|
||
|
|
Renderer r = mf.GetComponent<Renderer>();
|
||
|
|
if (r == null || !r.enabled) 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 p = space.InverseTransformPoint(mf.transform.TransformPoint(corner));
|
||
|
|
if (!has) { result = new Bounds(p, Vector3.zero); has = true; }
|
||
|
|
else result.Encapsulate(p);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return result;
|
||
|
|
}
|
||
|
|
|
||
|
|
private void CreateSteamEffect()
|
||
|
|
{
|
||
|
|
if (steam != null || !Application.isPlaying) return;
|
||
|
|
ComputeBayFrame(transform, out Vector3 center, out _, out _, out float yTop, out _);
|
||
|
|
|
||
|
|
GameObject pObj = new GameObject("EngineSteam");
|
||
|
|
pObj.transform.SetParent(transform, false);
|
||
|
|
pObj.transform.localPosition = new Vector3(center.x, yTop + 0.05f, center.z);
|
||
|
|
pObj.transform.localRotation = Quaternion.LookRotation(Vector3.up);
|
||
|
|
|
||
|
|
steam = pObj.AddComponent<ParticleSystem>();
|
||
|
|
var main = steam.main;
|
||
|
|
main.startLifetime = 2.2f;
|
||
|
|
main.startSpeed = 1.4f;
|
||
|
|
main.startSize = new ParticleSystem.MinMaxCurve(0.35f, 0.8f);
|
||
|
|
main.startColor = new Color(0.95f, 0.95f, 0.95f, 0.45f);
|
||
|
|
main.simulationSpace = ParticleSystemSimulationSpace.World;
|
||
|
|
main.playOnAwake = false;
|
||
|
|
main.maxParticles = 300;
|
||
|
|
var emission = steam.emission;
|
||
|
|
emission.rateOverTime = 35f;
|
||
|
|
var shape = steam.shape;
|
||
|
|
shape.shapeType = ParticleSystemShapeType.Box;
|
||
|
|
shape.scale = new Vector3(0.6f, 0.6f, 0.05f);
|
||
|
|
var sol = steam.sizeOverLifetime;
|
||
|
|
sol.enabled = true;
|
||
|
|
sol.size = new ParticleSystem.MinMaxCurve(1f, AnimationCurve.Linear(0f, 0.6f, 1f, 2.2f));
|
||
|
|
var col = steam.colorOverLifetime;
|
||
|
|
col.enabled = true;
|
||
|
|
Gradient g = new Gradient();
|
||
|
|
g.SetKeys(new[] { new GradientColorKey(Color.white, 0f), new GradientColorKey(Color.white, 1f) },
|
||
|
|
new[] { new GradientAlphaKey(0.5f, 0f), new GradientAlphaKey(0f, 1f) });
|
||
|
|
col.color = g;
|
||
|
|
pObj.GetComponent<ParticleSystemRenderer>().sharedMaterial = PartCatalog.ParticleMaterial;
|
||
|
|
steam.Stop();
|
||
|
|
}
|
||
|
|
|
||
|
|
// ===================== СОСТОЯНИЕ АГРЕГАТОВ =====================
|
||
|
|
|
||
|
|
public EnginePart GetPart(EnginePartType type)
|
||
|
|
{
|
||
|
|
foreach (EnginePart ep in GetComponentsInChildren<EnginePart>(false))
|
||
|
|
if (ep.partType == type && ep.IsInstalled) return ep;
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
|
||
|
|
public List<EnginePart> InstalledParts()
|
||
|
|
{
|
||
|
|
List<EnginePart> list = new List<EnginePart>();
|
||
|
|
foreach (EnginePart ep in GetComponentsInChildren<EnginePart>(false))
|
||
|
|
if (ep.IsInstalled) list.Add(ep);
|
||
|
|
return list;
|
||
|
|
}
|
||
|
|
|
||
|
|
public bool TryStart(out string reason)
|
||
|
|
{
|
||
|
|
reason = string.Empty;
|
||
|
|
if (!Diploma)
|
||
|
|
{
|
||
|
|
EngineRunning = true;
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
|
||
|
|
EnginePart battery = GetPart(EnginePartType.Battery);
|
||
|
|
EnginePart plugs = GetPart(EnginePartType.SparkPlugs);
|
||
|
|
|
||
|
|
if (battery == null)
|
||
|
|
reason = "Двигатель не заводится! Нет аккумулятора — установите АКБ под капотом";
|
||
|
|
else if (battery.charge < 20f)
|
||
|
|
reason = "Двигатель не заводится! Аккумулятор разряжен. Проверьте аккумулятор и свечи под капотом";
|
||
|
|
else if (plugs == null)
|
||
|
|
reason = "Двигатель не заводится! Нет свечей зажигания. Проверьте аккумулятор и свечи под капотом";
|
||
|
|
else if (plugs.condition < 5f)
|
||
|
|
reason = "Двигатель не заводится! Свечи зажигания убиты";
|
||
|
|
|
||
|
|
if (!string.IsNullOrEmpty(reason))
|
||
|
|
{
|
||
|
|
EngineRunning = false;
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Пуск стартером немного садит АКБ
|
||
|
|
battery.charge = Mathf.Max(0f, battery.charge - 1.5f);
|
||
|
|
EngineRunning = true;
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
|
||
|
|
public void StopEngine() => EngineRunning = false;
|
||
|
|
|
||
|
|
/// <summary>Коэффициент мощности двигателя 0.4–1.0 (свечи, воздушный фильтр, масло, перегрев).</summary>
|
||
|
|
public float PowerMultiplier
|
||
|
|
{
|
||
|
|
get
|
||
|
|
{
|
||
|
|
if (!Diploma) return 1f;
|
||
|
|
float m = 1f;
|
||
|
|
|
||
|
|
EnginePart plugs = GetPart(EnginePartType.SparkPlugs);
|
||
|
|
if (plugs != null && plugs.condition < 30f) m *= 0.7f;
|
||
|
|
|
||
|
|
EnginePart air = GetPart(EnginePartType.AirFilter);
|
||
|
|
if (air == null || air.condition < 30f) m *= 0.8f;
|
||
|
|
|
||
|
|
CarFluids f = Fluids;
|
||
|
|
if (f != null && (f.EngineOil.FillPercent < 0.15f || f.EngineOil.quality < 0.2f)) m *= 0.5f;
|
||
|
|
|
||
|
|
if (IsOverheating) m *= 0.65f;
|
||
|
|
return Mathf.Clamp(m, 0.4f, 1f);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// <summary>Коэффициент тормозного усилия 0.35–1.0 по уровню тормозной жидкости.</summary>
|
||
|
|
public float BrakeMultiplier
|
||
|
|
{
|
||
|
|
get
|
||
|
|
{
|
||
|
|
if (!Diploma) return 1f;
|
||
|
|
CarFluids f = Fluids;
|
||
|
|
if (f == null) return 1f;
|
||
|
|
float level = f.BrakeFluid.FillPercent;
|
||
|
|
return level < 0.3f ? 0.4f : 1f;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
public bool IsMisfiring
|
||
|
|
{
|
||
|
|
get
|
||
|
|
{
|
||
|
|
EnginePart plugs = GetPart(EnginePartType.SparkPlugs);
|
||
|
|
return Diploma && plugs != null && plugs.condition < 30f;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
public bool OilKnocking => Diploma && Fluids != null && (Fluids.EngineOil.FillPercent < 0.15f || Fluids.EngineOil.quality < 0.2f);
|
||
|
|
|
||
|
|
public float MaxSpeedLimit => IsOverheating ? 45f : float.MaxValue;
|
||
|
|
|
||
|
|
public bool BatteryWarning
|
||
|
|
{
|
||
|
|
get
|
||
|
|
{
|
||
|
|
EnginePart b = GetPart(EnginePartType.Battery);
|
||
|
|
EnginePart a = GetPart(EnginePartType.Alternator);
|
||
|
|
return b == null || b.charge < 20f || a == null || a.condition < 30f;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
public bool OilWarning => Fluids != null && (Fluids.EngineOil.FillPercent < 0.25f || Fluids.EngineOil.quality < 0.2f);
|
||
|
|
public bool TempWarning => IsOverheating || (Fluids != null && Fluids.Coolant.FillPercent < 0.25f);
|
||
|
|
public bool BrakeWarning => Fluids != null && Fluids.BrakeFluid.FillPercent < 0.3f;
|
||
|
|
|
||
|
|
/// <summary>Коды ошибок для OBD-сканера.</summary>
|
||
|
|
public List<string> GetObdCodes()
|
||
|
|
{
|
||
|
|
List<string> codes = new List<string>();
|
||
|
|
EnginePart plugs = GetPart(EnginePartType.SparkPlugs);
|
||
|
|
EnginePart battery = GetPart(EnginePartType.Battery);
|
||
|
|
EnginePart alt = GetPart(EnginePartType.Alternator);
|
||
|
|
EnginePart air = GetPart(EnginePartType.AirFilter);
|
||
|
|
EnginePart rad = GetPart(EnginePartType.Radiator);
|
||
|
|
CarFluids f = Fluids;
|
||
|
|
|
||
|
|
if (plugs == null) codes.Add("P0300 — Пропуски зажигания (свечи отсутствуют)");
|
||
|
|
else if (plugs.condition < 30f) codes.Add($"P0300 — Пропуски зажигания в цилиндрах (свечи {Mathf.RoundToInt(plugs.condition)}%)");
|
||
|
|
|
||
|
|
if (f != null && (f.EngineOil.FillPercent < 0.25f || f.EngineOil.quality < 0.2f))
|
||
|
|
codes.Add($"P0520 — Низкое давление масла (уровень {Mathf.RoundToInt(f.EngineOil.FillPercent * 100f)}%, состояние {Mathf.RoundToInt(f.EngineOil.quality * 100f)}%)");
|
||
|
|
|
||
|
|
if (IsOverheating || (f != null && f.Coolant.FillPercent < 0.25f))
|
||
|
|
codes.Add($"P0217 — Перегрев охлаждающей жидкости (уровень ОЖ {Mathf.RoundToInt((f != null ? f.Coolant.FillPercent : 0f) * 100f)}%)");
|
||
|
|
if (rad == null || rad.condition < 30f)
|
||
|
|
codes.Add("P0128 — Неисправность системы охлаждения (радиатор течет)");
|
||
|
|
|
||
|
|
if (battery == null) codes.Add("P0562 — Низкое напряжение бортсети (АКБ отсутствует)");
|
||
|
|
else if (battery.charge < 30f) codes.Add($"P0562 — Низкое напряжение бортсети (заряд АКБ {Mathf.RoundToInt(battery.charge)}%)");
|
||
|
|
|
||
|
|
if (alt == null || alt.condition < 30f) codes.Add("P0620 — Неисправность цепи генератора (нет зарядки)");
|
||
|
|
if (air == null || air.condition < 30f) codes.Add("P0101 — Расходомер воздуха: забит воздушный фильтр");
|
||
|
|
|
||
|
|
if (f != null && f.BrakeFluid.FillPercent < 0.3f)
|
||
|
|
codes.Add($"C1241 — Низкий уровень тормозной жидкости ({Mathf.RoundToInt(f.BrakeFluid.FillPercent * 100f)}%)");
|
||
|
|
|
||
|
|
return codes;
|
||
|
|
}
|
||
|
|
|
||
|
|
/// <summary>Подкапотное пространство готово к продаже: агрегаты > 80%, жидкости > 85%.</summary>
|
||
|
|
public bool IsReadyForSale(List<string> issues)
|
||
|
|
{
|
||
|
|
bool ok = true;
|
||
|
|
foreach (EnginePartType t in new[] { EnginePartType.Battery, EnginePartType.SparkPlugs, EnginePartType.AirFilter, EnginePartType.OilFilter, EnginePartType.Radiator, EnginePartType.Alternator })
|
||
|
|
{
|
||
|
|
EnginePart p = GetPart(t);
|
||
|
|
bool hadOne = HasSlotFor(t);
|
||
|
|
if (!hadOne) continue;
|
||
|
|
if (p == null)
|
||
|
|
{
|
||
|
|
ok = false;
|
||
|
|
issues?.Add($"Не установлен: {EnginePart.GetDisplayName(t)}");
|
||
|
|
}
|
||
|
|
else if (!p.IsHealthy)
|
||
|
|
{
|
||
|
|
ok = false;
|
||
|
|
issues?.Add($"{p.DisplayName}: {p.ShortStatus}");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return ok;
|
||
|
|
}
|
||
|
|
|
||
|
|
public bool AreFluidsFresh(List<string> issues)
|
||
|
|
{
|
||
|
|
CarFluids f = Fluids;
|
||
|
|
if (f == null) return true;
|
||
|
|
bool ok = true;
|
||
|
|
foreach (CarFluids.FluidReservoir r in f.All)
|
||
|
|
{
|
||
|
|
bool good = r.fluidType == FluidType.WasherFluid ? r.FillPercent >= 0.85f : r.IsGood;
|
||
|
|
if (!good)
|
||
|
|
{
|
||
|
|
ok = false;
|
||
|
|
issues?.Add($"{r.title}: {Mathf.RoundToInt(r.FillPercent * 100f)}% / состояние {Mathf.RoundToInt(r.quality * 100f)}%");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return ok;
|
||
|
|
}
|
||
|
|
|
||
|
|
private bool HasSlotFor(EnginePartType t)
|
||
|
|
{
|
||
|
|
foreach (EnginePart ep in GetComponentsInChildren<EnginePart>(true))
|
||
|
|
if (ep.partType == t) return true;
|
||
|
|
foreach (CarPartMountZone z in GetComponentsInChildren<CarPartMountZone>(true))
|
||
|
|
{
|
||
|
|
CarPartData d = z.TargetData;
|
||
|
|
if (d != null && d == PartCatalog.Instance.GetEngineData(t)) return true;
|
||
|
|
}
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
|
||
|
|
// ===================== СИМУЛЯЦИЯ =====================
|
||
|
|
|
||
|
|
public void SetRunning(bool running) => EngineRunning = running;
|
||
|
|
|
||
|
|
private void Update()
|
||
|
|
{
|
||
|
|
if (!Diploma)
|
||
|
|
{
|
||
|
|
overheatTimer = 0f;
|
||
|
|
UpdateSteam(false);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
float dt = Time.deltaTime;
|
||
|
|
CarFluids f = Fluids;
|
||
|
|
|
||
|
|
if (EngineRunning)
|
||
|
|
{
|
||
|
|
EnginePart battery = GetPart(EnginePartType.Battery);
|
||
|
|
EnginePart alt = GetPart(EnginePartType.Alternator);
|
||
|
|
if (battery != null)
|
||
|
|
{
|
||
|
|
if (alt != null && alt.condition >= 30f)
|
||
|
|
battery.charge = Mathf.Min(100f, battery.charge + 0.25f * dt);
|
||
|
|
else
|
||
|
|
battery.charge = Mathf.Max(0f, battery.charge - 0.35f * dt);
|
||
|
|
|
||
|
|
if (battery.charge <= 0.5f)
|
||
|
|
{
|
||
|
|
EngineRunning = false;
|
||
|
|
GameHUD.Notify("Двигатель заглох: аккумулятор полностью разряжен (неисправен генератор)", GameUI.Red);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
EnginePart rad = GetPart(EnginePartType.Radiator);
|
||
|
|
if (f != null)
|
||
|
|
{
|
||
|
|
if (rad == null || rad.condition < 30f)
|
||
|
|
f.Leak(FluidType.Coolant, 0.015f * dt);
|
||
|
|
|
||
|
|
bool coolingBad = f.Coolant.FillPercent < 0.25f || rad == null;
|
||
|
|
overheatTimer = coolingBad ? overheatTimer + dt : Mathf.Max(0f, overheatTimer - dt * 3f);
|
||
|
|
|
||
|
|
f.EngineOil.quality = Mathf.Max(0f, f.EngineOil.quality - 0.0003f * dt);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
else
|
||
|
|
{
|
||
|
|
overheatTimer = Mathf.Max(0f, overheatTimer - dt * 2f);
|
||
|
|
}
|
||
|
|
|
||
|
|
if (IsOverheating) steamTimer = 8f;
|
||
|
|
else if (steamTimer > 0f) steamTimer -= dt;
|
||
|
|
UpdateSteam(steamTimer > 0f);
|
||
|
|
}
|
||
|
|
|
||
|
|
private void UpdateSteam(bool on)
|
||
|
|
{
|
||
|
|
if (steam == null) return;
|
||
|
|
if (on && !steam.isPlaying) steam.Play();
|
||
|
|
else if (!on && steam.isPlaying) steam.Stop();
|
||
|
|
if (on || ProceduralAudioManager.Existing != null)
|
||
|
|
ProceduralAudioManager.Instance?.SetLoop(this, LoopId.Steam, on, steam.transform.position, 0.5f);
|
||
|
|
}
|
||
|
|
|
||
|
|
private void OnDisable()
|
||
|
|
{
|
||
|
|
if (ProceduralAudioManager.Existing != null)
|
||
|
|
ProceduralAudioManager.Existing.SetLoop(this, LoopId.Steam, false, Vector3.zero);
|
||
|
|
}
|
||
|
|
}
|