F6: scheda industria e schermata di connessione definitive

La scheda dell'industria e la schermata di connessione si allineano alle
immagini di riferimento 07 e 09. I dati che mancavano li calcola il Core
con una funzione pura, e viaggiano in blocchi compatibili del protocollo.
Il formato dei salvataggi non cambia (ADR 0021).

- IndustryOutlook calcola la scheda in sola lettura:
  - fattori dell'efficienza e quello che la limita;
  - ingressi e uscite al mese, con giorni di scorta o di magazzino;
  - fornitori e clienti con prezzo, distanza e linea che li collega;
  - forza lavoro dai contratti dei pendolari;
  - punteggio di crescita del trimestre con le soglie;
  - prezzo medio, utile annuo, stazioni che la servono, sblocco
    dell'acquisto.
  IndustryMath.GrowthScore è ora l'unica formula del punteggio e la usa
  anche IndustrySystem: gli hash non cambiano. Nuovi parametri in
  balance.json, industry.outlook.
- Protocollo:
  - IndustryCard: blocco 1 IndustrySheetInfo;
  - Welcome: blocco 1 ServerInfo (versione, sistema, Docker, tempo di
    attività, passo del ciclo, client collegati);
  - ClientWorld conserva lo stato del server e l'elenco dei salvataggi.
- Client:
  - IndustryPanel a tutto schermo, con tre schede, il grafo della
    catena, impianti e crescita, e i comandi del proprietario;
  - ConnectScreen sostituisce MenuScreen: server locale o in rete,
    stato del server, partite salvate, «Connetti e riprendi» e «Nuova
    partita sul server» su una sessione di prova;
  - testi in strings.csv;
  - pilota automatico: schermate 19_scheda_industria e 20_connessione.
- Test:
  - IndustryOutlookTests;
  - scheda e stato del server via WebSocket;
  - campioni del protocollo con i blocchi nuovi.
  200 test, 181 senza i lenti.

Refs #42.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-08 14:04:28 +01:00
1 parent 7eec322202
commit 45462bf9ec
28 files changed
+2810 -329

No files matched your search

@@ -243,6 +243,17 @@ public sealed class IndustryBalance
public required Dictionary<string, int> FootprintCells { get; init; }
public required double DepletionStartFraction { get; init; }
public required long StartingCash { get; init; }
/// <summary>Scheda dell'industria (IndustryOutlook, ADR 0021).</summary>
public required IndustryOutlookBalance Outlook { get; init; }
}
/// <summary>Parametri della scheda dell'industria (IndustryOutlook, ADR 0021).</summary>
public sealed class IndustryOutlookBalance
{
/// <summary>Fornitori o clienti elencati per ogni bene della catena produttiva (prima i collegati, poi i più vicini).</summary>
public required int PartnersPerGood { get; init; }
/// <summary>Provenienze dei lavoratori (e del personale) elencate nella scheda, dalle più numerose.</summary>
public required int WorkforceSources { get; init; }
}
public sealed class GrowthBalance
@@ -186,6 +186,8 @@ public static class DataValidator
if (b.Map.Industries.InitialLevels.Length != 2 || b.Map.Industries.InitialLevels[0] > b.Map.Industries.InitialLevels[1])
Err("balance.json", "map.industries.initialLevels deve essere [min, max]");
RequireKeys("balance.json", "industry.footprintCells", b.Industry.FootprintCells.Keys, SizeKeys, errors);
if (b.Industry.Outlook.PartnersPerGood < 1) Err("balance.json", "industry.outlook.partnersPerGood deve essere almeno 1");
if (b.Industry.Outlook.WorkforceSources < 1) Err("balance.json", "industry.outlook.workforceSources deve essere almeno 1");
RequireKeys("balance.json", "tariffs.classMultipliers", b.Tariffs.ClassMultipliers.Keys, ["worker", "staff"], errors);
RequireKeys("balance.json", "finance.ratingSpreads", b.Finance.RatingSpreads.Keys, Enum.GetNames<CreditRating>(), errors);
if (b.Finance.RatingByScore.Length != 9) Err("balance.json", "finance.ratingByScore deve avere 9 soglie (AAA … C)");
@@ -0,0 +1,515 @@
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;
/// <summary>
/// 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à.
/// </summary>
public enum IndustryLimit : byte
{
/// <summary>Nessun fattore sotto 1: l'industria lavora a piena capacità.</summary>
None = 0,
Inputs = 1,
Workers = 2,
Staff = 3,
/// <summary>Fattore di profitto (margine negativo).</summary>
Profit = 4,
/// <summary>Condizione degli impianti sotto la soglia del rendimento pieno.</summary>
Condition = 5,
/// <summary>Giacimento sotto la soglia di esaurimento.</summary>
Depletion = 6,
/// <summary>Evento del mondo sulla capacità (incidente).</summary>
Event = 7,
/// <summary>Fermo in corso (guasto, incidente, revisione, ammodernamento).</summary>
Stopped = 8,
/// <summary>Livello 0 (dormiente) o industria chiusa.</summary>
Dormant = 9,
}
/// <summary>Tipo di nodo della catena produttiva.</summary>
public enum ChainPartnerKind : byte { Industry = 0, Hub = 1, Town = 2 }
/// <summary>
/// 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.
/// </summary>
public readonly record struct ChainPartner(ChainPartnerKind Kind, int Target, double MonthlyUnits, double Price, LineId Line, double DistanceKm);
/// <summary>
/// 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).
/// </summary>
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; }
/// <summary>Input che limita l'efficienza (quello con meno giorni di scorta quando il limite sono gli input).</summary>
public required bool Limiting { get; init; }
public required List<ChainPartner> Partners { get; init; }
}
/// <summary>Provenienza dei lavoratori (o del personale): città, linea del primo tratto, vettore, minuti di viaggio.</summary>
public readonly record struct WorkforceSource(TownId Town, int Headcount, double Coverage, LineId Line, CompanyId Carrier, double Minutes, bool Walking);
/// <summary>Lavoratori o personale qualificato dell'industria.</summary>
public sealed class WorkforceOutlook
{
public required int Jobs { get; init; }
public required double Present { get; init; }
/// <summary>Quota coperta da chi vive in sede (alloggi dell'industria).</summary>
public required double OnSite { get; init; }
/// <summary>Copertura media su coverageWindowDays (entra nell'efficienza).</summary>
public required double Coverage { get; init; }
/// <summary>Posti scoperti oggi (posti − presenti, arrotondato).</summary>
public required int Missing { get; init; }
public required UncoveredReason Reason { get; init; }
public required LineId ReasonLine { get; init; }
/// <summary>Viaggio medio in treno (minuti, pesato sulle persone); −1 senza pendolari in treno.</summary>
public required double AverageMinutes { get; init; }
/// <summary>Provenienze più numerose (al massimo industry.outlook.workforceSources).</summary>
public required List<WorkforceSource> Sources { get; init; }
/// <summary>Provenienze in tutto (anche quelle non elencate).</summary>
public required int SourceCount { get; init; }
}
/// <summary>Crescita trimestrale (guida 6.3): punteggio del trimestre in corso, soglie e trimestri.</summary>
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; }
/// <summary>Giorni del trimestre già contati e lunghezza del trimestre.</summary>
public required int QuarterDay { get; init; }
public required int QuarterDays { get; init; }
/// <summary>Servita da un vettore nel trimestre: solo allora il livello cambia (ADR 0004).</summary>
public required bool Served { get; init; }
public required int MaxLevel { get; init; }
}
/// <summary>Scheda dell'industria per la compagnia della sessione (immagine di riferimento 07, ADR 0021).</summary>
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; }
/// <summary>Riserva residua del giacimento (0–1); −1 se l'industria non è esauribile.</summary>
public required double ReserveFraction { get; init; }
public required int StorageDays { get; init; }
public required List<IndustryFlow> Inputs { get; init; }
public required List<IndustryFlow> Outputs { get; init; }
public required WorkforceOutlook Workers { get; init; }
public required WorkforceOutlook Staff { get; init; }
/// <summary>Ricavo medio per unità del prodotto (centesimi); −1 se non stimabile (nessuna vendita o più prodotti).</summary>
public required double AveragePrice { get; init; }
public required Money AnnualProfit { get; init; }
public required GrowthOutlook Growth { get; init; }
/// <summary>Stazioni (di qualunque compagnia) che servono l'industria con una linea con treni.</summary>
public required List<StationId> ServingStations { get; init; }
/// <summary>Linea della compagnia della sessione che serve l'industria (id più basso), None se nessuna.</summary>
public required LineId ServingLine { get; init; }
/// <summary>Dei privati e attiva: si può comprare (dal livello che sblocca l'acquisto).</summary>
public required bool ForSale { get; init; }
public required bool BuyUnlocked { get; init; }
public required int BuyTier { get; init; }
/// <summary>Avanzamento verso il livello che sblocca l'acquisto (ADR 0018); 1 se sbloccato.</summary>
public required double BuyProgress { get; init; }
}
/// <summary>
/// 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.
/// </summary>
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<IndustryFlow>(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<IndustryFlow>(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),
});
}
// ricavo medio per unità: ricavi medi giornalieri / unità spedite al giorno nel trimestre (un solo prodotto)
double averagePrice = -1;
if (recipe.Outputs.Count == 1 && ind.QuarterShipped > 0 && ind.QuarterDays > 0)
averagePrice = ind.RevenueEma * ind.QuarterDays / ind.QuarterShipped;
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),
Staff = Workforce(w, ind, PaxClass.Staff),
AveragePrice = averagePrice,
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,
};
}
/// <summary>Fattori dell'efficienza dell'industria e quello che la limita.</summary>
public readonly record struct EfficiencyFactors(
double ProfitFactor, double ConditionMultiplier, double Depletion, double EventCapacity, double ReserveFraction, bool Stopped, IndustryLimit Limit);
/// <summary>
/// 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 <see cref="IndustryLimit"/>), Fermo se l'industria è ferma, Dormiente al
/// livello 0 o chiusa.
/// </summary>
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);
}
/// <summary>Lavoratori o personale: presenti, quota in sede, posti scoperti con il motivo e provenienze per città e linea.</summary>
public static WorkforceOutlook Workforce(World w, Industry ind, PaxClass cls)
{
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;
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,
};
}
/// <summary>
/// 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.
/// </summary>
private static List<ChainPartner> Suppliers(World w, Industry ind, int good, LineLinks links, List<Line> mine)
{
int dpm = w.Calendar.DaysPerMonth;
double pg = w.Market.GlobalPrice[good];
var all = new List<ChainPartner>();
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);
}
/// <summary>
/// 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.
/// </summary>
private static List<ChainPartner> Customers(World w, Industry ind, int good, LineLinks links, List<Line> mine)
{
int dpm = w.Calendar.DaysPerMonth;
double pg = w.Market.GlobalPrice[good];
var lp = w.Data.Balance.LocalPrice;
var all = new List<ChainPartner>();
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);
}
/// <summary>Prima i collegati (per linea), poi i più vicini; a parità tipo e id; al massimo partnersPerGood.</summary>
private static List<ChainPartner> Pick(World w, List<ChainPartner> 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;
/// <summary>Stazioni vive (di qualunque compagnia) con l'industria nel bacino e fermata di una linea con treni.</summary>
public static List<StationId> 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<StationId>();
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;
}
/// <summary>
/// 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.
/// </summary>
private sealed class LineLinks
{
private readonly List<(Line Line, HashSet<int> Industries, HashSet<int> Hubs, HashSet<int> 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<int>();
var hubs = new HashSet<int>();
var towns = new HashSet<int>();
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));
}
}
/// <summary>Linee che raggiungono l'industria, per id crescente.</summary>
public List<Line> Serving(Industry ind) => _lines.Where(x => x.Industries.Contains(ind.Id.Value)).Select(x => x.Line).ToList();
/// <summary>Prima linea (id più basso) tra quelle dell'industria che raggiunge anche il nodo indicato.</summary>
public LineId Link(List<Line> 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;
}
}
}
@@ -4,6 +4,9 @@ using RailEnterprise.Core.Economy;
namespace RailEnterprise.Core.Simulation.Systems;
/// <summary>Componenti del punteggio di crescita trimestrale (quota trasportata, copertura, redditività) e punteggio.</summary>
public readonly record struct GrowthScoreParts(double Shipped, double Coverage, double Profit, double Score);
/// <summary>Formule dell'industria condivise da più sistemi (guida 6.3 e 11).</summary>
public static class IndustryMath
{
@@ -20,6 +23,20 @@ public static class IndustryMath
return m.EfficiencyAt20 + (1.0 - m.EfficiencyAt20) * t;
}
/// <summary>
/// Punteggio di crescita del trimestre (guida 6.3) dalle statistiche accumulate finora:
/// 0,5·quota trasportata + 0,3·copertura media + 0,2·redditività, con i pesi di balance.json.
/// Lo usa la crescita trimestrale e, a trimestre in corso, la scheda dell'industria.
/// </summary>
public static GrowthScoreParts GrowthScore(Industry ind, GrowthBalance g)
{
double shipped = ind.QuarterProduced > 0 ? Math.Min(1.0, (double)ind.QuarterShipped / ind.QuarterProduced) : 0;
double coverage = ind.QuarterDays > 0 ? ind.QuarterCoverageSum / ind.QuarterDays : 0;
double profit = Math.Clamp((ind.Margin + 1) / 2, 0, 1);
double score = g.WeightShipped * shipped + g.WeightCoverage * coverage + g.WeightProfit * profit;
return new GrowthScoreParts(shipped, coverage, profit, score);
}
/// <summary>Capienza del magazzino di un output (unità) al livello corrente.</summary>
public static int OutputCapacity(Industry ind, int outputIndex, int daysPerMonth)
{
@@ -138,10 +138,7 @@ public sealed class IndustrySystem : ISimSystem
foreach (var ind in w.Industries)
{
if (ind.Closed) continue;
double shipped = ind.QuarterProduced > 0 ? Math.Min(1.0, (double)ind.QuarterShipped / ind.QuarterProduced) : 0;
double coverage = ind.QuarterDays > 0 ? ind.QuarterCoverageSum / ind.QuarterDays : 0;
double profit = Math.Clamp((ind.Margin + 1) / 2, 0, 1);
double score = g.WeightShipped * shipped + g.WeightCoverage * coverage + g.WeightProfit * profit;
double score = IndustryMath.GrowthScore(ind, g).Score;
ind.LastScore = score;
ind.QuarterProduced = 0;
ind.QuarterShipped = 0;