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:
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;
|
||||
|
||||
@@ -56,6 +56,12 @@ public sealed class ClientWorld(GameData data)
|
||||
/// <summary>Quadro delle finanze (F6), su richiesta: lo usa il pannello «Finanze».</summary>
|
||||
public FinanceReport? Finance { get; private set; }
|
||||
|
||||
/// <summary>Stato del server dall'ultimo Welcome (F6, ADR 0021): versione, sistema, attività, tick, sessioni.</summary>
|
||||
public ServerInfo? Server { get; private set; }
|
||||
|
||||
/// <summary>Ultimo elenco dei salvataggi del server (risposta a ListSaves e a Save); resta valido anche dopo un nuovo Welcome.</summary>
|
||||
public SaveList? Saves { get; private set; }
|
||||
|
||||
/// <summary>Contatore dei listini ricevuti (per aggiornare il pannello della borsa).</summary>
|
||||
public int TapeVersion { get; private set; }
|
||||
|
||||
@@ -148,6 +154,10 @@ public sealed class ClientWorld(GameData data)
|
||||
Finance = m;
|
||||
DetailVersion++;
|
||||
return true;
|
||||
case SaveList m:
|
||||
Saves = m;
|
||||
DetailVersion++;
|
||||
return true;
|
||||
case MaintenanceAlert m:
|
||||
Alerts.Insert(0, m);
|
||||
if (Alerts.Count > AlertCapacity) Alerts.RemoveAt(Alerts.Count - 1);
|
||||
@@ -172,6 +182,7 @@ public sealed class ClientWorld(GameData data)
|
||||
Finance = null;
|
||||
Alerts.Clear();
|
||||
Summary = m.Summary;
|
||||
Server = m.Server;
|
||||
SessionId = m.SessionId;
|
||||
Tick = m.Summary.Tick;
|
||||
Speed = m.Summary.Speed;
|
||||
|
||||
@@ -161,6 +161,8 @@ public sealed class IndustryCard : IMessage
|
||||
public Money Cash { get; init; }
|
||||
public float BreakdownChancePerYear { get; init; }
|
||||
public List<IndustryStopInfo> Stops { get; init; } = [];
|
||||
/// <summary>Blocco 1 (F6, ADR 0021): scheda dell'immagine 07 per la compagnia della sessione; null se assente.</summary>
|
||||
public IndustrySheetInfo? Sheet { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
@@ -169,7 +171,8 @@ public sealed class IndustryCard : IMessage
|
||||
w.I32(MachineryRequired); w.Money(UpgradeCost); w.Money(Valuation); w.Money(Cash); w.F32(BreakdownChancePerYear);
|
||||
w.Count(Stops.Count);
|
||||
foreach (var s in Stops) s.Write(ref w);
|
||||
w.Flags(0);
|
||||
w.Flags((byte)(Sheet is not null ? 1 : 0));
|
||||
Sheet?.Write(ref w);
|
||||
}
|
||||
|
||||
public static IndustryCard Read(ref SpanReader r)
|
||||
@@ -181,9 +184,18 @@ public sealed class IndustryCard : IMessage
|
||||
MachineryRequired = r.I32(), UpgradeCost = r.Money(), Valuation = r.Money(), Cash = r.Money(), BreakdownChancePerYear = r.F32(),
|
||||
};
|
||||
for (int n = r.Count(), i = 0; i < n; i++) m.Stops.Add(IndustryStopInfo.Read(ref r));
|
||||
r.Flags();
|
||||
byte flags = r.Flags();
|
||||
if ((flags & 1) != 0) m = m.With(IndustrySheetInfo.Read(ref r));
|
||||
return m;
|
||||
}
|
||||
|
||||
private IndustryCard With(IndustrySheetInfo sheet) => new()
|
||||
{
|
||||
Industry = Industry, Margin = Margin, ConditionMultiplier = ConditionMultiplier, WearPerDay = WearPerDay, RecoveryPerDay = RecoveryPerDay,
|
||||
MaintenanceCostPerDay = MaintenanceCostPerDay, MaintenanceSpentYear = MaintenanceSpentYear, PartsTarget = PartsTarget, PartsPerMonth = PartsPerMonth,
|
||||
PartsOrdered = PartsOrdered, MachineryRequired = MachineryRequired, UpgradeCost = UpgradeCost, Valuation = Valuation, Cash = Cash,
|
||||
BreakdownChancePerYear = BreakdownChancePerYear, Stops = Stops, Sheet = sheet,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Primato della Cronaca finale (descrizione e valore già formattati in italiano).</summary>
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
using RailEnterprise.Core.Common;
|
||||
|
||||
namespace RailEnterprise.Protocol.Messages;
|
||||
|
||||
// Blocchi della fase F6 (ADR 0021): scheda dell'industria dell'immagine di riferimento 07 (blocco 1 di
|
||||
// IndustryCard, calcolato dal server con IndustryOutlook) e stato del server per la schermata di
|
||||
// connessione dell'immagine 09 (blocco 1 di Welcome). Il client li mostra come arrivano.
|
||||
|
||||
/// <summary>
|
||||
/// Fornitore o cliente nella catena produttiva. Kind: 0 industria, 1 hub, 2 città (ChainPartnerKind);
|
||||
/// unità al mese, prezzo in centesimi per unità, linea della compagnia che collega (−1 nessuna), km in linea d'aria.
|
||||
/// </summary>
|
||||
public sealed class ChainPartnerInfo
|
||||
{
|
||||
public byte Kind { get; init; }
|
||||
public int Target { get; init; }
|
||||
public float MonthlyUnits { get; init; }
|
||||
public double Price { get; init; }
|
||||
public int Line { get; init; } = -1;
|
||||
public float DistanceKm { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.U8(Kind); w.I32(Target); w.F32(MonthlyUnits); w.F64(Price); w.I32(Line); w.F32(DistanceKm);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static ChainPartnerInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new ChainPartnerInfo { Kind = r.U8(), Target = r.I32(), MonthlyUnits = r.F32(), Price = r.F64(), Line = r.I32(), DistanceKm = r.F32() };
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Input o output dell'industria: al mese a piena efficienza (fabbisogno o capacità) e al ritmo attuale,
|
||||
/// scorta, capienza, giorni (di scorta per un input, prima del magazzino pieno per un output; −1 senza
|
||||
/// ritmo), input limitante, fornitori o clienti.
|
||||
/// </summary>
|
||||
public sealed class IndustryFlowInfo
|
||||
{
|
||||
public int Good { get; init; }
|
||||
public float FullMonth { get; init; }
|
||||
public float CurrentMonth { get; init; }
|
||||
public int Stock { get; init; }
|
||||
public int Storage { get; init; }
|
||||
public float Days { get; init; } = -1;
|
||||
public bool Limiting { get; init; }
|
||||
public List<ChainPartnerInfo> Partners { get; init; } = [];
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I32(Good); w.F32(FullMonth); w.F32(CurrentMonth); w.I32(Stock); w.I32(Storage); w.F32(Days); w.Bool(Limiting);
|
||||
w.Count(Partners.Count);
|
||||
foreach (var p in Partners) p.Write(ref w);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static IndustryFlowInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new IndustryFlowInfo { Good = r.I32(), FullMonth = r.F32(), CurrentMonth = r.F32(), Stock = r.I32(), Storage = r.I32(), Days = r.F32(), Limiting = r.Bool() };
|
||||
for (int n = r.Count(), i = 0; i < n; i++) m.Partners.Add(ChainPartnerInfo.Read(ref r));
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Provenienza dei lavoratori o del personale: città, persone, copertura, linea del primo tratto (−1 a piedi), vettore, minuti.</summary>
|
||||
public sealed class WorkforceSourceInfo
|
||||
{
|
||||
public int Town { get; init; }
|
||||
public int Headcount { get; init; }
|
||||
public float Coverage { get; init; }
|
||||
public int Line { get; init; } = -1;
|
||||
public int Carrier { get; init; } = -1;
|
||||
public float Minutes { get; init; }
|
||||
public bool Walking { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I32(Town); w.I32(Headcount); w.F32(Coverage); w.I32(Line); w.I32(Carrier); w.F32(Minutes); w.Bool(Walking);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static WorkforceSourceInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new WorkforceSourceInfo { Town = r.I32(), Headcount = r.I32(), Coverage = r.F32(), Line = r.I32(), Carrier = r.I32(), Minutes = r.F32(), Walking = r.Bool() };
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lavoratori o personale: posti, presenti, quota in sede, copertura media, posti scoperti, motivo
|
||||
/// (UncoveredReason) e linea del motivo, viaggio medio in treno (−1 senza), provenienze elencate e in tutto.
|
||||
/// </summary>
|
||||
public sealed class WorkforceInfo
|
||||
{
|
||||
public int Jobs { get; init; }
|
||||
public float Present { get; init; }
|
||||
public float OnSite { get; init; }
|
||||
public float Coverage { get; init; }
|
||||
public int Missing { get; init; }
|
||||
public byte Reason { get; init; }
|
||||
public int ReasonLine { get; init; } = -1;
|
||||
public float AverageMinutes { get; init; } = -1;
|
||||
public int SourceCount { get; init; }
|
||||
public List<WorkforceSourceInfo> Sources { get; init; } = [];
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I32(Jobs); w.F32(Present); w.F32(OnSite); w.F32(Coverage); w.I32(Missing); w.U8(Reason); w.I32(ReasonLine); w.F32(AverageMinutes); w.I32(SourceCount);
|
||||
w.Count(Sources.Count);
|
||||
foreach (var s in Sources) s.Write(ref w);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static WorkforceInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new WorkforceInfo
|
||||
{
|
||||
Jobs = r.I32(), Present = r.F32(), OnSite = r.F32(), Coverage = r.F32(), Missing = r.I32(), Reason = r.U8(), ReasonLine = r.I32(),
|
||||
AverageMinutes = r.F32(), SourceCount = r.I32(),
|
||||
};
|
||||
for (int n = r.Count(), i = 0; i < n; i++) m.Sources.Add(WorkforceSourceInfo.Read(ref r));
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Blocco 1 di IndustryCard (F6, ADR 0021): scheda dell'immagine 07 calcolata da IndustryOutlook per la
|
||||
/// compagnia della sessione. Limit come IndustryLimit del Core (0 nessuno, 1 input, 2 lavoratori,
|
||||
/// 3 personale, 4 profitto, 5 impianti, 6 giacimento, 7 evento, 8 fermo, 9 dormiente).
|
||||
/// </summary>
|
||||
public sealed class IndustrySheetInfo
|
||||
{
|
||||
public byte Level { get; init; }
|
||||
public byte MaxLevel { get; init; }
|
||||
public float Efficiency { get; init; }
|
||||
public byte Limit { get; init; }
|
||||
public float CovInput { get; init; }
|
||||
public float CovWorkers { get; init; }
|
||||
public float CovStaff { get; init; }
|
||||
public int CoverageWindowDays { get; init; }
|
||||
public float ProfitFactor { get; init; }
|
||||
public float Depletion { get; init; }
|
||||
public float EventCapacity { get; init; }
|
||||
/// <summary>Riserva residua del giacimento (0–1), −1 se non esauribile.</summary>
|
||||
public float ReserveFraction { get; init; } = -1;
|
||||
public int StorageDays { get; init; }
|
||||
public List<IndustryFlowInfo> Inputs { get; init; } = [];
|
||||
public List<IndustryFlowInfo> Outputs { get; init; } = [];
|
||||
public WorkforceInfo Workers { get; init; } = new();
|
||||
public WorkforceInfo Staff { get; init; } = new();
|
||||
/// <summary>Ricavo medio per unità del prodotto (centesimi), −1 se non stimabile.</summary>
|
||||
public double AveragePrice { get; init; } = -1;
|
||||
public Money AnnualProfit { get; init; }
|
||||
/// <summary>Crescita trimestrale: ultimo punteggio, componenti e punteggio del trimestre in corso, soglie, trimestri.</summary>
|
||||
public float LastScore { get; init; }
|
||||
public float Shipped { get; init; }
|
||||
public float Coverage { get; init; }
|
||||
public float Profit { get; init; }
|
||||
public float Score { get; init; }
|
||||
public float UpgradeThreshold { get; init; }
|
||||
public float DowngradeThreshold { get; init; }
|
||||
public byte UpgradeQuarters { get; init; }
|
||||
public byte QuartersAbove { get; init; }
|
||||
public int QuarterDay { get; init; }
|
||||
public int QuarterDays { get; init; }
|
||||
public bool Served { get; init; }
|
||||
/// <summary>Stazioni (di qualunque compagnia) che servono l'industria; linea della compagnia della sessione (−1 nessuna).</summary>
|
||||
public List<int> ServingStations { get; init; } = [];
|
||||
public int ServingLine { get; init; } = -1;
|
||||
/// <summary>Acquisto: dei privati e attiva, sbloccato dal livello, livello che lo sblocca e avanzamento verso di esso.</summary>
|
||||
public bool ForSale { get; init; }
|
||||
public bool BuyUnlocked { get; init; }
|
||||
public byte BuyTier { get; init; }
|
||||
public float BuyProgress { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.U8(Level); w.U8(MaxLevel); w.F32(Efficiency); w.U8(Limit); w.F32(CovInput); w.F32(CovWorkers); w.F32(CovStaff); w.I32(CoverageWindowDays);
|
||||
w.F32(ProfitFactor); w.F32(Depletion); w.F32(EventCapacity); w.F32(ReserveFraction); w.I32(StorageDays);
|
||||
w.Count(Inputs.Count);
|
||||
foreach (var f in Inputs) f.Write(ref w);
|
||||
w.Count(Outputs.Count);
|
||||
foreach (var f in Outputs) f.Write(ref w);
|
||||
Workers.Write(ref w);
|
||||
Staff.Write(ref w);
|
||||
w.F64(AveragePrice); w.Money(AnnualProfit);
|
||||
w.F32(LastScore); w.F32(Shipped); w.F32(Coverage); w.F32(Profit); w.F32(Score); w.F32(UpgradeThreshold); w.F32(DowngradeThreshold);
|
||||
w.U8(UpgradeQuarters); w.U8(QuartersAbove); w.I32(QuarterDay); w.I32(QuarterDays); w.Bool(Served);
|
||||
w.Count(ServingStations.Count);
|
||||
foreach (int s in ServingStations) w.I32(s);
|
||||
w.I32(ServingLine); w.Bool(ForSale); w.Bool(BuyUnlocked); w.U8(BuyTier); w.F32(BuyProgress);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static IndustrySheetInfo Read(ref SpanReader r)
|
||||
{
|
||||
byte level = r.U8(), maxLevel = r.U8();
|
||||
float efficiency = r.F32();
|
||||
byte limit = r.U8();
|
||||
float covInput = r.F32(), covWorkers = r.F32(), covStaff = r.F32();
|
||||
int window = r.I32();
|
||||
float pf = r.F32(), depletion = r.F32(), eventCapacity = r.F32(), reserve = r.F32();
|
||||
int storageDays = r.I32();
|
||||
var inputs = new List<IndustryFlowInfo>();
|
||||
for (int n = r.Count(), i = 0; i < n; i++) inputs.Add(IndustryFlowInfo.Read(ref r));
|
||||
var outputs = new List<IndustryFlowInfo>();
|
||||
for (int n = r.Count(), i = 0; i < n; i++) outputs.Add(IndustryFlowInfo.Read(ref r));
|
||||
var workers = WorkforceInfo.Read(ref r);
|
||||
var staff = WorkforceInfo.Read(ref r);
|
||||
double averagePrice = r.F64();
|
||||
var profit = r.Money();
|
||||
float last = r.F32(), shipped = r.F32(), coverage = r.F32(), profitShare = r.F32(), score = r.F32(), up = r.F32(), down = r.F32();
|
||||
byte upQuarters = r.U8(), above = r.U8();
|
||||
int quarterDay = r.I32(), quarterDays = r.I32();
|
||||
bool served = r.Bool();
|
||||
var stations = new List<int>();
|
||||
for (int n = r.Count(), i = 0; i < n; i++) stations.Add(r.I32());
|
||||
var m = new IndustrySheetInfo
|
||||
{
|
||||
Level = level, MaxLevel = maxLevel, Efficiency = efficiency, Limit = limit, CovInput = covInput, CovWorkers = covWorkers, CovStaff = covStaff,
|
||||
CoverageWindowDays = window, ProfitFactor = pf, Depletion = depletion, EventCapacity = eventCapacity, ReserveFraction = reserve, StorageDays = storageDays,
|
||||
Inputs = inputs, Outputs = outputs, Workers = workers, Staff = staff, AveragePrice = averagePrice, AnnualProfit = profit,
|
||||
LastScore = last, Shipped = shipped, Coverage = coverage, Profit = profitShare, Score = score, UpgradeThreshold = up, DowngradeThreshold = down,
|
||||
UpgradeQuarters = upQuarters, QuartersAbove = above, QuarterDay = quarterDay, QuarterDays = quarterDays, Served = served, ServingStations = stations,
|
||||
ServingLine = r.I32(), ForSale = r.Bool(), BuyUnlocked = r.Bool(), BuyTier = r.U8(), BuyProgress = r.F32(),
|
||||
};
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Blocco 1 di Welcome (F6, ADR 0021): stato del server per la schermata di connessione (immagine 09):
|
||||
/// versione del gioco, sistema operativo, container, secondi di attività, durata del tick (ms), sessioni
|
||||
/// collegate e massime, server locale (figlio del client).
|
||||
/// </summary>
|
||||
public sealed class ServerInfo
|
||||
{
|
||||
public string Version { get; init; } = "";
|
||||
public string Os { get; init; } = "";
|
||||
public bool Container { get; init; }
|
||||
public long UptimeSeconds { get; init; }
|
||||
public float TickMs { get; init; }
|
||||
public int Sessions { get; init; }
|
||||
public int MaxSessions { get; init; }
|
||||
public bool Local { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.String(Version); w.String(Os); w.Bool(Container); w.I64(UptimeSeconds); w.F32(TickMs); w.I32(Sessions); w.I32(MaxSessions); w.Bool(Local);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static ServerInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new ServerInfo
|
||||
{
|
||||
Version = r.String(), Os = r.String(), Container = r.Bool(), UptimeSeconds = r.I64(), TickMs = r.F32(), Sessions = r.I32(), MaxSessions = r.I32(), Local = r.Bool(),
|
||||
};
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,8 @@ public sealed class Welcome : IMessage
|
||||
public required WorldSummary Summary { get; init; }
|
||||
public ulong DataHash { get; init; }
|
||||
public string Difficulty { get; init; } = "";
|
||||
/// <summary>Blocco 1 (F6, ADR 0021): stato del server per la schermata di connessione; null se assente.</summary>
|
||||
public ServerInfo? Server { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
@@ -20,14 +22,19 @@ public sealed class Welcome : IMessage
|
||||
Summary.Write(ref w);
|
||||
w.U64(DataHash);
|
||||
w.String(Difficulty);
|
||||
w.Flags(0);
|
||||
w.Flags((byte)(Server is not null ? 1 : 0));
|
||||
Server?.Write(ref w);
|
||||
}
|
||||
|
||||
public static Welcome Read(ref SpanReader r)
|
||||
{
|
||||
var m = new Welcome { SessionId = r.U64(), Summary = WorldSummary.Read(ref r), DataHash = r.U64(), Difficulty = r.String() };
|
||||
r.Flags();
|
||||
return m;
|
||||
ulong session = r.U64();
|
||||
var summary = WorldSummary.Read(ref r);
|
||||
ulong hash = r.U64();
|
||||
string difficulty = r.String();
|
||||
byte flags = r.Flags();
|
||||
var server = (flags & 1) != 0 ? ServerInfo.Read(ref r) : null;
|
||||
return new Welcome { SessionId = session, Summary = summary, DataHash = hash, Difficulty = difficulty, Server = server };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -198,6 +198,21 @@ public sealed class GameHost : IDisposable
|
||||
Summary = Projection.Summary(_world, _world.Companies[s.Company.Value], _speed),
|
||||
DataHash = _data.Hash,
|
||||
Difficulty = _world.Difficulty.Id,
|
||||
Server = ServerStatus(),
|
||||
};
|
||||
|
||||
/// <summary>Stato del server per la schermata di connessione (blocco 1 del Welcome, ADR 0021).</summary>
|
||||
private ServerInfo ServerStatus() => new()
|
||||
{
|
||||
Version = GameVersion,
|
||||
Os = System.Runtime.InteropServices.RuntimeInformation.OSDescription,
|
||||
// le immagini .NET ufficiali impostano DOTNET_RUNNING_IN_CONTAINER
|
||||
Container = string.Equals(Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER"), "true", StringComparison.OrdinalIgnoreCase),
|
||||
UptimeSeconds = NowMs / 1000,
|
||||
TickMs = _config.TickMs,
|
||||
Sessions = _sessions.Values.Count(x => x.Connected),
|
||||
MaxSessions = _config.MaxSessions,
|
||||
Local = _config.Local,
|
||||
};
|
||||
|
||||
private void Handle(Session s, IMessage message)
|
||||
@@ -653,7 +668,7 @@ public sealed class GameHost : IDisposable
|
||||
break;
|
||||
case DetailKind.Industry:
|
||||
if (m.Target >= 0 && m.Target < w.Industries.Count && !w.Industries[m.Target].Closed)
|
||||
s.Send(Projection.IndustryCard(w, w.Industries[m.Target]));
|
||||
s.Send(Projection.IndustryCard(w, w.Industries[m.Target], s.Company));
|
||||
break;
|
||||
case DetailKind.Chronicle:
|
||||
s.Send(Projection.Chronicle(w));
|
||||
|
||||
@@ -485,8 +485,8 @@ public static class Projection
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Scheda del proprietario di un'industria (sezione 11).</summary>
|
||||
public static IndustryCard IndustryCard(World w, Industry ind)
|
||||
/// <summary>Scheda del proprietario di un'industria (sezione 11) con la scheda dell'immagine 07 per la compagnia (blocco 1, ADR 0021).</summary>
|
||||
public static IndustryCard IndustryCard(World w, Industry ind, CompanyId company)
|
||||
{
|
||||
var m = w.Data.Balance.IndustryMaintenance;
|
||||
var budget = m.For(ind.Budget);
|
||||
@@ -502,6 +502,45 @@ public static class Projection
|
||||
PartsOrdered = ind.PartsOrdered, MachineryRequired = IndustryMath.MachineryRequired(ind, m), UpgradeCost = IndustryMaintenanceSystem.UpgradeCost(ind),
|
||||
Valuation = IndustryMath.Valuation(w, ind), Cash = ind.Cash, BreakdownChancePerYear = (float)perYear,
|
||||
Stops = ind.StopHistory.Select(h => new IndustryStopInfo { Day = h.Day, Days = h.Days, Kind = (byte)h.Kind }).ToList(),
|
||||
Sheet = IndustrySheet(IndustryOutlook.Build(w, ind, company)),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Scheda dell'industria dell'immagine 07 (IndustryOutlook, ADR 0021).</summary>
|
||||
public static IndustrySheetInfo IndustrySheet(IndustryOutlookReport r)
|
||||
{
|
||||
static IndustryFlowInfo Flow(IndustryFlow f) => new()
|
||||
{
|
||||
Good = f.Good, FullMonth = (float)f.FullMonth, CurrentMonth = (float)f.CurrentMonth, Stock = f.Stock, Storage = f.Storage, Days = (float)f.Days,
|
||||
Limiting = f.Limiting,
|
||||
Partners = f.Partners.Select(p => new ChainPartnerInfo
|
||||
{
|
||||
Kind = (byte)p.Kind, Target = p.Target, MonthlyUnits = (float)p.MonthlyUnits, Price = p.Price, Line = p.Line.Value, DistanceKm = (float)p.DistanceKm,
|
||||
}).ToList(),
|
||||
};
|
||||
static WorkforceInfo Work(WorkforceOutlook o) => new()
|
||||
{
|
||||
Jobs = o.Jobs, Present = (float)o.Present, OnSite = (float)o.OnSite, Coverage = (float)o.Coverage, Missing = o.Missing, Reason = (byte)o.Reason,
|
||||
ReasonLine = o.ReasonLine.Value, AverageMinutes = (float)o.AverageMinutes, SourceCount = o.SourceCount,
|
||||
Sources = o.Sources.Select(x => new WorkforceSourceInfo
|
||||
{
|
||||
Town = x.Town.Value, Headcount = x.Headcount, Coverage = (float)x.Coverage, Line = x.Line.Value, Carrier = x.Carrier.Value, Minutes = (float)x.Minutes, Walking = x.Walking,
|
||||
}).ToList(),
|
||||
};
|
||||
var g = r.Growth;
|
||||
return new IndustrySheetInfo
|
||||
{
|
||||
Level = (byte)Math.Clamp(r.Level, 0, 255), MaxLevel = (byte)Math.Clamp(r.MaxLevel, 0, 255), Efficiency = (float)r.Efficiency, Limit = (byte)r.Limit,
|
||||
CovInput = (float)r.CovInput, CovWorkers = (float)r.CovWorkers, CovStaff = (float)r.CovStaff, CoverageWindowDays = r.CoverageWindowDays,
|
||||
ProfitFactor = (float)r.ProfitFactor, Depletion = (float)r.Depletion, EventCapacity = (float)r.EventCapacity, ReserveFraction = (float)r.ReserveFraction,
|
||||
StorageDays = r.StorageDays, Inputs = r.Inputs.Select(Flow).ToList(), Outputs = r.Outputs.Select(Flow).ToList(),
|
||||
Workers = Work(r.Workers), Staff = Work(r.Staff), AveragePrice = r.AveragePrice, AnnualProfit = r.AnnualProfit,
|
||||
LastScore = (float)g.LastScore, Shipped = (float)g.Current.Shipped, Coverage = (float)g.Current.Coverage, Profit = (float)g.Current.Profit,
|
||||
Score = (float)g.Current.Score, UpgradeThreshold = (float)g.UpgradeThreshold, DowngradeThreshold = (float)g.DowngradeThreshold,
|
||||
UpgradeQuarters = (byte)Math.Clamp(g.UpgradeQuarters, 0, 255), QuartersAbove = (byte)Math.Clamp(g.QuartersAbove, 0, 255),
|
||||
QuarterDay = g.QuarterDay, QuarterDays = g.QuarterDays, Served = g.Served,
|
||||
ServingStations = r.ServingStations.Select(s => s.Value).ToList(), ServingLine = r.ServingLine.Value,
|
||||
ForSale = r.ForSale, BuyUnlocked = r.BuyUnlocked, BuyTier = (byte)Math.Clamp(r.BuyTier, 0, 255), BuyProgress = (float)r.BuyProgress,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user