using RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Rail;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Core.Simulation.Systems;
namespace RailEnterprise.Core.Economy;
///
/// Fattore che limita l'efficienza dell'industria (e = min(copertura input, lavoratori, personale) ×
/// pf × mc × giacimento × eventi, guida 6.3): il più basso sotto 1, nell'ordine dell'enum a parità.
///
public enum IndustryLimit : byte
{
/// Nessun fattore sotto 1: l'industria lavora a piena capacità.
None = 0,
Inputs = 1,
Workers = 2,
Staff = 3,
/// Fattore di profitto (margine negativo).
Profit = 4,
/// Condizione degli impianti sotto la soglia del rendimento pieno.
Condition = 5,
/// Giacimento sotto la soglia di esaurimento.
Depletion = 6,
/// Evento del mondo sulla capacità (incidente).
Event = 7,
/// Fermo in corso (guasto, incidente, revisione, ammodernamento).
Stopped = 8,
/// Livello 0 (dormiente) o industria chiusa.
Dormant = 9,
}
/// Tipo di nodo della catena produttiva.
public enum ChainPartnerKind : byte { Industry = 0, Hub = 1, Town = 2 }
///
/// Fornitore o cliente di un bene nella catena produttiva: unità al mese (produzione attuale del
/// fornitore, fabbisogno a piena capacità del cliente, capacità mensile dell'hub, domanda della
/// città), prezzo (centesimi per unità: prezzo globale per chi vende al mercato, prezzo locale
/// dell'ADR 0004 per l'industria che compra, prezzo dell'hub con il dazio), linea della compagnia che
/// collega i due (None se nessuna) e distanza in linea d'aria.
///
public readonly record struct ChainPartner(ChainPartnerKind Kind, int Target, double MonthlyUnits, double Price, LineId Line, double DistanceKm);
///
/// Un input o un output dell'industria al livello attuale: quantità al mese a piena efficienza e al
/// ritmo attuale, scorta e capienza del magazzino, giorni di scorta (input, al ritmo dei presenti) o
/// giorni prima che il magazzino si riempia (output, al ritmo attuale; oltre si perde la merce);
/// −1 se il ritmo è nullo. Partner: fornitori (input) o clienti (output).
///
public sealed class IndustryFlow
{
public required int Good { get; init; }
public required double FullMonth { get; init; }
public required double CurrentMonth { get; init; }
public required int Stock { get; init; }
public required int Storage { get; init; }
public required double Days { get; init; }
/// Input che limita l'efficienza (quello con meno giorni di scorta quando il limite sono gli input).
public required bool Limiting { get; init; }
public required List Partners { get; init; }
}
/// Provenienza dei lavoratori (o del personale): città, linea del primo tratto, vettore, minuti di viaggio.
public readonly record struct WorkforceSource(TownId Town, int Headcount, double Coverage, LineId Line, CompanyId Carrier, double Minutes, bool Walking);
/// Lavoratori o personale qualificato dell'industria.
public sealed class WorkforceOutlook
{
public required int Jobs { get; init; }
public required double Present { get; init; }
/// Persone in sede: posti coperti da chi vive negli alloggi dell'industria (posti × quota in sede).
public required double OnSite { get; init; }
/// Copertura media su coverageWindowDays (entra nell'efficienza).
public required double Coverage { get; init; }
/// Posti scoperti oggi (posti − presenti, arrotondato).
public required int Missing { get; init; }
public required UncoveredReason Reason { get; init; }
public required LineId ReasonLine { get; init; }
/// Viaggio medio in treno (minuti, pesato sulle persone) dei contratti visibili; −1 se nessuno.
public required double AverageMinutes { get; init; }
/// Provenienze più numerose (al massimo industry.outlook.workforceSources).
public required List Sources { get; init; }
/// Provenienze visibili in tutto (anche quelle non elencate).
public required int SourceCount { get; init; }
}
/// Crescita trimestrale (guida 6.3): punteggio del trimestre in corso, soglie e trimestri.
public sealed class GrowthOutlook
{
public required double LastScore { get; init; }
public required GrowthScoreParts Current { get; init; }
public required double UpgradeThreshold { get; init; }
public required double DowngradeThreshold { get; init; }
public required int UpgradeQuarters { get; init; }
public required int QuartersAbove { get; init; }
/// Giorni del trimestre già contati e lunghezza del trimestre.
public required int QuarterDay { get; init; }
public required int QuarterDays { get; init; }
/// Servita da un vettore nel trimestre: solo allora il livello cambia (ADR 0004).
public required bool Served { get; init; }
public required int MaxLevel { get; init; }
}
/// Scheda dell'industria per la compagnia della sessione (immagine di riferimento 07, ADR 0021).
public sealed class IndustryOutlookReport
{
public required IndustryId Industry { get; init; }
public required int Level { get; init; }
public required int MaxLevel { get; init; }
public required double Efficiency { get; init; }
public required IndustryLimit Limit { get; init; }
public required double CovInput { get; init; }
public required double CovWorkers { get; init; }
public required double CovStaff { get; init; }
public required int CoverageWindowDays { get; init; }
public required double ProfitFactor { get; init; }
public required double ConditionMultiplier { get; init; }
public required double Depletion { get; init; }
public required double EventCapacity { get; init; }
/// Riserva residua del giacimento (0–1); −1 se l'industria non è esauribile.
public required double ReserveFraction { get; init; }
public required int StorageDays { get; init; }
public required List Inputs { get; init; }
public required List Outputs { get; init; }
public required WorkforceOutlook Workers { get; init; }
public required WorkforceOutlook Staff { get; init; }
///
/// Prezzo di vendita del prodotto (centesimi): il prezzo globale del giorno, quello a cui le
/// industrie vendono al mercato (ADR 0004); −1 senza prodotti o con più prodotti.
///
public required double SalePrice { get; init; }
public required Money AnnualProfit { get; init; }
public required GrowthOutlook Growth { get; init; }
/// Stazioni (di qualunque compagnia) che servono l'industria con una linea con treni.
public required List ServingStations { get; init; }
/// Linea della compagnia della sessione che serve l'industria (id più basso), None se nessuna.
public required LineId ServingLine { get; init; }
/// Dei privati e attiva: si può comprare (dal livello che sblocca l'acquisto).
public required bool ForSale { get; init; }
public required bool BuyUnlocked { get; init; }
public required int BuyTier { get; init; }
/// Avanzamento verso il livello che sblocca l'acquisto (ADR 0018); 1 se sbloccato.
public required double BuyProgress { get; init; }
}
///
/// Scheda dell'industria (ADR 0021): legge il mondo e non scrive nulla, come MarketOutlook e
/// ClimbOutlook. Catena produttiva con fornitori e clienti per bene, coperture, forza lavoro con le
/// provenienze, produzione e magazzino, fattore limitante, crescita trimestrale e acquisto.
///
public static class IndustryOutlook
{
public static IndustryOutlookReport Build(World w, Industry ind, CompanyId company)
{
var data = w.Data;
var ib = data.Balance.Industry;
var g = data.Balance.Growth;
int dpm = w.Calendar.DaysPerMonth;
long today = w.Clock.Day;
var recipe = ind.Def.Recipe;
var factors = Factors(w, ind);
var links = new LineLinks(w, company);
var mine = links.Serving(ind);
// ritmo dei presenti senza la copertura degli input (giorni di scorta) e ritmo effettivo
double cyclesFull = ind.Closed ? 0 : ind.CyclesPerDayAtFullCapacity(dpm);
double labour = factors.Stopped || ind.Closed
? 0
: Math.Min(ind.CovWorkers, ind.CovStaff) * factors.ProfitFactor * factors.ConditionMultiplier * factors.Depletion * factors.EventCapacity;
double efficiency = ind.Closed ? 0 : ind.Efficiency;
int limiting = -1;
if (factors.Limit == IndustryLimit.Inputs)
{
double least = double.MaxValue;
for (int i = 0; i < recipe.Inputs.Count; i++)
{
double perDay = cyclesFull * recipe.Inputs[i].PerCycle * labour;
double days = perDay > 0 ? ind.InputStock[i] / perDay : double.MaxValue;
if (limiting < 0 || days < least)
{
least = days;
limiting = i;
}
}
}
var inputs = new List(recipe.Inputs.Count);
for (int i = 0; i < recipe.Inputs.Count; i++)
{
int good = recipe.Inputs[i].GoodIndex;
double full = cyclesFull * recipe.Inputs[i].PerCycle * dpm;
double perDay = cyclesFull * recipe.Inputs[i].PerCycle * labour;
inputs.Add(new IndustryFlow
{
Good = good, FullMonth = full, CurrentMonth = full * efficiency, Stock = ind.InputStock[i],
Storage = IndustryMath.InputCapacity(ind, i, dpm), Days = perDay > 0 ? ind.InputStock[i] / perDay : -1,
Limiting = i == limiting, Partners = Suppliers(w, ind, good, links, mine),
});
}
var outputs = new List(recipe.Outputs.Count);
for (int o = 0; o < recipe.Outputs.Count; o++)
{
int good = recipe.Outputs[o].GoodIndex;
double full = cyclesFull * recipe.Outputs[o].PerCycle * dpm;
double perDay = full * efficiency / dpm;
int storage = IndustryMath.OutputCapacity(ind, o, dpm);
outputs.Add(new IndustryFlow
{
Good = good, FullMonth = full, CurrentMonth = full * efficiency, Stock = ind.OutputStock[o], Storage = storage,
Days = perDay > 0 ? Math.Max(0, storage - ind.OutputStock[o]) / perDay : -1,
Limiting = false, Partners = Customers(w, ind, good, links, mine),
});
}
// prezzo di vendita: le industrie vendono al prezzo globale del giorno (ADR 0004). Una media dei
// ricavi mescolerebbe la media mobile dei ricavi con i totali del trimestre in corso
double salePrice = recipe.Outputs.Count == 1 ? w.Market.GlobalPrice[recipe.Outputs[0].GoodIndex] : -1;
var buyTier = data.Tiers.Tiers.FirstOrDefault(t => t.Unlocks.BuyIndustry);
var owner = company.IsValid && company.Value < w.Companies.Count ? w.Companies[company.Value] : null;
bool buyUnlocked = owner is not null && Tiers.Unlocks(w, owner).BuyIndustry;
double buyProgress = buyUnlocked ? 1 : owner is not null && buyTier is not null ? ClimbOutlook.Requirements(w, owner, buyTier).Progress : 0;
return new IndustryOutlookReport
{
Industry = ind.Id,
Level = ind.Level,
MaxLevel = g.MaxLevel,
Efficiency = efficiency,
Limit = factors.Limit,
CovInput = ind.CovInput,
CovWorkers = ind.CovWorkers,
CovStaff = ind.CovStaff,
CoverageWindowDays = ib.CoverageWindowDays,
ProfitFactor = factors.ProfitFactor,
ConditionMultiplier = factors.ConditionMultiplier,
Depletion = factors.Depletion,
EventCapacity = factors.EventCapacity,
ReserveFraction = factors.ReserveFraction,
StorageDays = ind.Def.StorageDays,
Inputs = inputs,
Outputs = outputs,
Workers = Workforce(w, ind, PaxClass.Worker, company),
Staff = Workforce(w, ind, PaxClass.Staff, company),
SalePrice = salePrice,
AnnualProfit = Money.FromCentsRounded(IndustryMath.AnnualProfit(w, ind)),
Growth = new GrowthOutlook
{
LastScore = ind.LastScore,
Current = IndustryMath.GrowthScore(ind, g),
UpgradeThreshold = g.UpgradeThreshold,
DowngradeThreshold = g.DowngradeThreshold,
UpgradeQuarters = g.UpgradeQuarters,
QuartersAbove = ind.QuartersAboveUpgrade,
QuarterDay = ind.QuarterDays,
QuarterDays = g.QuarterDays,
Served = ind.ServedWithin(today, g.QuarterDays),
MaxLevel = g.MaxLevel,
},
ServingStations = ServingStations(w, ind),
ServingLine = mine.Count > 0 ? mine[0].Id : LineId.None,
ForSale = !ind.Owner.IsValid && !ind.Closed && ind.Level > 0,
BuyUnlocked = buyUnlocked,
BuyTier = buyTier?.Level ?? 0,
BuyProgress = buyProgress,
};
}
/// Fattori dell'efficienza dell'industria e quello che la limita.
public readonly record struct EfficiencyFactors(
double ProfitFactor, double ConditionMultiplier, double Depletion, double EventCapacity, double ReserveFraction, bool Stopped, IndustryLimit Limit);
///
/// Fattori dell'efficienza come li usa la produzione (IndustrySystem): coperture medie, fattore di
/// profitto, condizione degli impianti, giacimento, eventi; il limite è il fattore più basso sotto 1
/// (a parità nell'ordine di ), Fermo se l'industria è ferma, Dormiente al
/// livello 0 o chiusa.
///
public static EfficiencyFactors Factors(World w, Industry ind)
{
var data = w.Data;
double pf = IndustryMath.ProfitFactor(ind, data.Balance.Industry);
double mc = IndustryMath.ConditionMultiplier(ind.Condition, data.Balance.IndustryMaintenance);
double depletion = 1;
double reserve = -1;
if (ind.Def.Depletable && ind.Site.IsValid)
{
reserve = w.Sites[ind.Site.Value].ReserveFraction;
double start = data.Balance.Industry.DepletionStartFraction;
if (reserve < start) depletion = Math.Max(0, reserve) / start;
}
double capacity = w.WorldEvents.IndustryCapacity(ind.Id);
bool stopped = ind.IsStopped(w.Clock.Day);
IndustryLimit limit;
if (ind.Closed || ind.Level <= 0) limit = IndustryLimit.Dormant;
else if (stopped) limit = IndustryLimit.Stopped;
else
{
limit = IndustryLimit.None;
double least = 1;
void Consider(IndustryLimit kind, double value)
{
if (value < least)
{
least = value;
limit = kind;
}
}
if (ind.Def.Recipe.Inputs.Count > 0) Consider(IndustryLimit.Inputs, ind.CovInput);
if (ind.JobsWorkers > 0) Consider(IndustryLimit.Workers, ind.CovWorkers);
if (ind.JobsStaff > 0) Consider(IndustryLimit.Staff, ind.CovStaff);
Consider(IndustryLimit.Profit, pf);
Consider(IndustryLimit.Condition, mc);
Consider(IndustryLimit.Depletion, depletion);
Consider(IndustryLimit.Event, capacity);
}
return new EfficiencyFactors(pf, mc, depletion, capacity, reserve, stopped, limit);
}
///
/// Lavoratori o personale: presenti, persone in sede, posti scoperti con il motivo e provenienze per
/// città e linea. Come il Registro degli impieghi (Projection.Employment), la compagnia vede i
/// contratti a piedi e quelli che trasporta lei; quelli degli altri vettori solo se l'industria è
/// sua. Presenti e copertura restano quelli dell'industria.
///
public static WorkforceOutlook Workforce(World w, Industry ind, PaxClass cls, CompanyId company)
{
var ib = w.Data.Balance.Industry;
bool staff = cls == PaxClass.Staff;
int jobs = staff ? ind.JobsStaff : ind.JobsWorkers;
double present = staff ? ind.StaffPresent : ind.WorkersPresent;
var me = WorkplaceRef.Of(ind.Id);
// contratti raggruppati per città, primo tratto, vettore e modo (a piedi o in treno), nell'ordine dei contratti
var groups = new List<(TownId Town, LineId Line, CompanyId Carrier, bool Walking, int Headcount, double CoverageSum, double MinutesSum)>();
double railPeople = 0, railMinutes = 0;
foreach (var c in w.Commutes)
{
if (c.Workplace != me || c.Category != cls || c.Headcount <= 0) continue;
if (!Visible(c, ind, company)) continue;
var line = c.Route.Count > 0 ? c.Route[0] : LineId.None;
int at = groups.FindIndex(x => x.Town == c.Town && x.Line == line && x.Carrier == c.Carrier && x.Walking == c.Walking);
if (at < 0)
{
groups.Add((c.Town, line, c.Carrier, c.Walking, 0, 0, 0));
at = groups.Count - 1;
}
var gr = groups[at];
groups[at] = gr with
{
Headcount = gr.Headcount + c.Headcount,
CoverageSum = gr.CoverageSum + c.Coverage * c.Headcount,
MinutesSum = gr.MinutesSum + c.ExpectedMinutes * c.Headcount,
};
if (!c.Walking)
{
railPeople += c.Headcount;
railMinutes += c.ExpectedMinutes * c.Headcount;
}
}
var sources = groups
.Select(x => new WorkforceSource(x.Town, x.Headcount, x.CoverageSum / x.Headcount, x.Line, x.Carrier, x.MinutesSum / x.Headcount, x.Walking))
.OrderByDescending(s => s.Headcount).ThenBy(s => s.Town.Value).ThenBy(s => s.Line.Value).ThenBy(s => s.Carrier.Value).ThenBy(s => s.Walking)
.Take(ib.Outlook.WorkforceSources).ToList();
return new WorkforceOutlook
{
Jobs = jobs,
Present = present,
OnSite = EmploymentSystem.OnSite(jobs, staff ? ib.OnSiteStaffShare : ib.OnSiteWorkerShare),
Coverage = staff ? ind.CovStaff : ind.CovWorkers,
Missing = (int)Math.Max(0, Math.Round(jobs - present, MidpointRounding.AwayFromZero)),
Reason = staff ? ind.StaffReason : ind.WorkersReason,
ReasonLine = staff ? ind.StaffReasonLine : ind.WorkersReasonLine,
AverageMinutes = railPeople > 0 ? railMinutes / railPeople : -1,
Sources = sources,
SourceCount = groups.Count,
};
}
/// Contratto che la compagnia può vedere: a piedi, trasportato da lei, o verso una sua industria.
public static bool Visible(CommuteContract c, Industry ind, CompanyId company) =>
c.Walking || (company.IsValid && (c.Carrier == company || ind.Owner == company));
///
/// Fornitori di un input: industrie attive che producono il bene (unità al mese al ritmo attuale,
/// prezzo globale: le industrie vendono al mercato, ADR 0004) e hub (capacità mensile, prezzo
/// d'importazione). Prima i collegati da una linea della compagnia, poi i più vicini.
///
private static List Suppliers(World w, Industry ind, int good, LineLinks links, List mine)
{
int dpm = w.Calendar.DaysPerMonth;
double pg = w.Market.GlobalPrice[good];
var all = new List();
foreach (var other in w.Industries)
{
if (other.Id == ind.Id || other.Closed || other.Level <= 0) continue;
int o = other.OutputIndexOf(good);
if (o < 0) continue;
double month = other.CyclesPerDayAtFullCapacity(dpm) * other.Def.Recipe.Outputs[o].PerCycle * dpm * other.Efficiency;
all.Add(new ChainPartner(ChainPartnerKind.Industry, other.Id.Value, month, pg, links.Link(mine, ChainPartnerKind.Industry, other.Id.Value), Km(ind.Position, other.Position)));
}
foreach (var h in w.Hubs)
all.Add(new ChainPartner(ChainPartnerKind.Hub, h.Id.Value, h.MonthlyCapacity, h.SellPrice(pg), links.Link(mine, ChainPartnerKind.Hub, h.Id.Value), Km(ind.Position, h.Position)));
return Pick(w, all);
}
///
/// Clienti di un output: industrie attive che lo consumano (fabbisogno al mese a piena capacità,
/// prezzo locale dell'ADR 0004 come «Dove conviene vendere»), hub (prezzo d'esportazione) e città con
/// domanda del bene (domanda al mese, prezzo globale). Prima i collegati, poi i più vicini.
///
private static List Customers(World w, Industry ind, int good, LineLinks links, List mine)
{
int dpm = w.Calendar.DaysPerMonth;
double pg = w.Market.GlobalPrice[good];
var lp = w.Data.Balance.LocalPrice;
var all = new List();
foreach (var other in w.Industries)
{
if (other.Id == ind.Id || other.Closed || other.Level <= 0) continue;
int i = other.InputIndexOf(good);
if (i < 0) continue;
double month = other.CyclesPerDayAtFullCapacity(dpm) * other.Def.Recipe.Inputs[i].PerCycle * dpm;
double price = Market.LocalPrice(pg, IndustryMath.InputCapacity(other, i, dpm), other.InputStock[i], lp);
all.Add(new ChainPartner(ChainPartnerKind.Industry, other.Id.Value, month, price, links.Link(mine, ChainPartnerKind.Industry, other.Id.Value), Km(ind.Position, other.Position)));
}
foreach (var h in w.Hubs)
all.Add(new ChainPartner(ChainPartnerKind.Hub, h.Id.Value, h.MonthlyCapacity, h.BuyPrice(pg), links.Link(mine, ChainPartnerKind.Hub, h.Id.Value), Km(ind.Position, h.Position)));
foreach (var t in w.Towns)
{
if (t.DemandToday.Length <= good || t.DemandToday[good] <= 0) continue;
all.Add(new ChainPartner(ChainPartnerKind.Town, t.Id.Value, t.DemandToday[good] * dpm, pg, links.Link(mine, ChainPartnerKind.Town, t.Id.Value), Km(ind.Position, t.Position)));
}
return Pick(w, all);
}
/// Prima i collegati (per linea), poi i più vicini; a parità tipo e id; al massimo partnersPerGood.
private static List Pick(World w, List all) =>
all.OrderBy(p => p.Line.IsValid ? 0 : 1).ThenBy(p => p.DistanceKm).ThenBy(p => p.Kind).ThenBy(p => p.Target)
.Take(w.Data.Balance.Industry.Outlook.PartnersPerGood).ToList();
private static double Km(Vec2 a, Vec2 b) => Vec2.Distance(a, b) / 1000;
/// Stazioni vive (di qualunque compagnia) con l'industria nel bacino e fermata di una linea con treni.
public static List ServingStations(World w, Industry ind)
{
var lineHasTrain = new bool[w.Lines.Count];
foreach (var t in w.Trains)
{
if (!t.Removed && t.Line.IsValid && t.Line.Value < lineHasTrain.Length) lineHasTrain[t.Line.Value] = true;
}
var served = new bool[w.Network.Stations.Count];
foreach (var l in w.Lines)
{
if (l.Removed || !lineHasTrain[l.Id.Value]) continue;
foreach (var stop in l.Stops)
{
int s = stop.Station.Value;
if (s >= 0 && s < served.Length) served[s] = true;
}
}
var result = new List();
foreach (var s in w.Network.Stations)
{
if (served[s.Id.Value] && w.Network.IsAlive(s) && s.Industries.Contains(ind.Id)) result.Add(s.Id);
}
return result;
}
///
/// Linee della compagnia con almeno un treno e ciò che raggiungono: industrie, hub e città nel
/// bacino delle loro fermate (stazioni vive). Una linea collega due nodi se li raggiunge entrambi.
///
private sealed class LineLinks
{
private readonly List<(Line Line, HashSet Industries, HashSet Hubs, HashSet Towns)> _lines = [];
public LineLinks(World w, CompanyId company)
{
if (!company.IsValid) return;
var lineHasTrain = new bool[w.Lines.Count];
foreach (var t in w.Trains)
{
if (t.Owner == company && !t.Removed && t.Line.IsValid && t.Line.Value < lineHasTrain.Length) lineHasTrain[t.Line.Value] = true;
}
foreach (var l in w.Lines)
{
if (l.Owner != company || l.Removed || !lineHasTrain[l.Id.Value]) continue;
var industries = new HashSet();
var hubs = new HashSet();
var towns = new HashSet();
foreach (var stop in l.Stops)
{
int s = stop.Station.Value;
if (s < 0 || s >= w.Network.Stations.Count) continue;
var station = w.Network.Stations[s];
if (!w.Network.IsAlive(station)) continue;
foreach (var i in station.Industries) industries.Add(i.Value);
foreach (var h in station.Hubs) hubs.Add(h.Value);
foreach (var t in station.Towns) towns.Add(t.Value);
}
_lines.Add((l, industries, hubs, towns));
}
}
/// Linee che raggiungono l'industria, per id crescente.
public List Serving(Industry ind) => _lines.Where(x => x.Industries.Contains(ind.Id.Value)).Select(x => x.Line).ToList();
/// Prima linea (id più basso) tra quelle dell'industria che raggiunge anche il nodo indicato.
public LineId Link(List serving, ChainPartnerKind kind, int target)
{
foreach (var line in serving)
{
var entry = _lines.First(x => ReferenceEquals(x.Line, line));
var set = kind switch
{
ChainPartnerKind.Industry => entry.Industries,
ChainPartnerKind.Hub => entry.Hubs,
_ => entry.Towns,
};
if (set.Contains(target)) return line.Id;
}
return LineId.None;
}
}
}