Files
Rail_Enterprise/tests/RailEnterprise.Tests/Economy/IndustryOutlookTests.cs
T
Alby96andClaude Opus 5.5 0667a4a544 F6: scheda industria e connessione, correzioni della revisione
Correzioni dalla revisione della scheda industria e della schermata di
connessione.

- Dati di altre compagnie: la forza lavoro della scheda mostra solo i
  contratti a piedi, quelli della compagnia della sessione e, se
  l'industria è sua, quelli di tutti i vettori, come il Registro degli
  impieghi. Lo stesso filtro vale per provenienze, conteggio e viaggio
  medio.
- Prezzo: «prezzo medio realizzato» mescolava una media mobile dei
  ricavi con i totali del trimestre in corso. Al suo posto c'è il prezzo
  di vendita, cioè il prezzo globale del giorno (SalePrice).
- Avvisi del server: hanno il giorno −1, così il rifiuto di Load o
  NewGame non si confonde più con gli eventi del mondo che arrivano
  mentre si aspetta il Welcome.
- Schermata di connessione:
  - all'apertura avvia la strada scelta l'ultima volta;
  - cambiando strada chiude la sessione dell'altra;
  - senza sessione «Connetti e riprendi» la apre;
  - il cambio di lingua passa la sessione alla schermata nuova;
  - la scelta del salvataggio si tiene per id;
  - Load e nuova partita chiedono conferma;
  - stato del server su 3×2 con la versione del protocollo, salvataggi
    su tre colonne, «Attivo da» che avanza.
- Scheda dell'industria:
  - collegamenti e nodi non collegati sono leggibili;
  - testo per l'industria inattiva;
  - revisione e ammodernamento disabilitati, con il motivo, quando il
    server li rifiuterebbe;
  - l'esito dell'acquisto compare accanto al pulsante;
  - le righe lunghe vanno a capo;
  - «in sede» al posto di «al lavoro ora».
- Gli avvisi dei comandi compaiono anche sulle schermate a tutto
  schermo.
- Pilota automatico:
  - la schermata 20 sta su un suo CanvasLayer sopra l'interfaccia;
  - 12 e 12b sono ora la scheda a tutto schermo.
- Test: pendolari di altri vettori nascosti, Load rifiutato via
  WebSocket, Welcome senza ServerInfo. 202 test, 183 senza i lenti.

Refs #42.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 14:29:14 +01:00

320 lines
17 KiB
C#

using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Economy;
using RailEnterprise.Core.Persistence;
using RailEnterprise.Core.Rail;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Core.Simulation.Systems;
using RailEnterprise.Protocol;
using RailEnterprise.Protocol.Messages;
using RailEnterprise.Server;
using RailEnterprise.Tests.Harness;
using RailEnterprise.Tests.Rail;
namespace RailEnterprise.Tests.Economy;
/// <summary>Scheda dell'industria dell'immagine 07 (F6, ADR 0021): catena produttiva, coperture, limite, crescita.</summary>
public static class IndustryOutlookTests
{
private static int GoodIndex(World w, string id) => w.Data.Goods.First(g => g.Id == id).Index;
/// <summary>Valdoria con la rete merci miniere → acciaieria, un treno sulla linea e 40 giorni di servizio.</summary>
private static (RailFixture F, int Line, int MillStation) ServedValdoria()
{
var f = RailFixture.Valdoria();
var (mine, mill, depot) = f.BuildFreightNetwork();
int train = f.Train(depot, "Merci 1", ("loco_steam_1850", 1), ("wagon_hopper", 4));
int line = f.Ok(new CreateLineCommand("Linea 1", "#e0a526", new[] { new LineStop(new StationId(mine)), new LineStop(new StationId(mill)) }));
f.Ok(new AssignTrainCommand(new TrainId(train), new LineId(line)));
f.W.RunDays(40);
return (f, line, mill);
}
[Test(Description = "Scheda dell'acciaieria di Valdoria: input, output, fornitore collegato dalla linea, clienti, stazione che serve; nessun effetto sul mondo")]
public static void SheetOfTheSteelMill()
{
var (f, line, millStation) = ServedValdoria();
var w = f.W;
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
ulong hash = StateHasher.Compute(w);
var r = IndustryOutlook.Build(w, steel, f.Me);
Assert.Equal(hash, StateHasher.Compute(w), "la scheda non cambia il mondo");
int dpm = w.Calendar.DaysPerMonth;
Assert.Equal(steel.Level, r.Level);
Assert.Equal(w.Data.Balance.Growth.MaxLevel, r.MaxLevel);
Assert.Equal(steel.Efficiency, r.Efficiency);
Assert.Equal(steel.Def.StorageDays, r.StorageDays);
Assert.Equal(w.Data.Balance.Industry.CoverageWindowDays, r.CoverageWindowDays);
// input nell'ordine della ricetta: fabbisogno a piena capacità e consumo al ritmo attuale
Assert.Equal(2, r.Inputs.Count);
int ore = GoodIndex(w, "iron_ore");
Assert.Equal(ore, r.Inputs[0].Good);
Assert.Equal(GoodIndex(w, "coal"), r.Inputs[1].Good);
double cyclesMonth = (double)steel.Def.Capacity(steel.Level) / steel.Def.Recipe.Outputs[0].PerCycle;
Assert.Approx(cyclesMonth * 2, r.Inputs[0].FullMonth, 1e-9);
Assert.Approx(cyclesMonth * 1, r.Inputs[1].FullMonth, 1e-9);
Assert.Approx(r.Inputs[0].FullMonth * steel.Efficiency, r.Inputs[0].CurrentMonth, 1e-9);
Assert.Equal(steel.InputStock[0], r.Inputs[0].Stock);
Assert.Equal(IndustryMath.InputCapacity(steel, 0, dpm), r.Inputs[0].Storage);
// output: capacità del livello, produzione al ritmo attuale, magazzino
Assert.Equal(1, r.Outputs.Count);
Assert.Approx(steel.Def.Capacity(steel.Level), r.Outputs[0].FullMonth, 1e-9);
Assert.Approx(r.Outputs[0].FullMonth * steel.Efficiency, r.Outputs[0].CurrentMonth, 1e-9);
Assert.Equal(IndustryMath.OutputCapacity(steel, 0, dpm), r.Outputs[0].Storage);
if (r.Outputs[0].CurrentMonth > 0)
{
double perDay = r.Outputs[0].CurrentMonth / dpm;
Assert.Approx(Math.Max(0, r.Outputs[0].Storage - r.Outputs[0].Stock) / perDay, r.Outputs[0].Days, 1e-9);
}
// il primo fornitore di minerale è la miniera di Rocca Bruna, collegata dalla linea
int perGood = w.Data.Balance.Industry.Outlook.PartnersPerGood;
var suppliers = r.Inputs[0].Partners;
Assert.True(suppliers.Count is > 0 && suppliers.Count <= perGood, $"fornitori {suppliers.Count}");
var mine = w.Industries.First(i => i.Def.Id == "iron_mine");
Assert.Equal(ChainPartnerKind.Industry, suppliers[0].Kind);
Assert.Equal(mine.Id.Value, suppliers[0].Target);
Assert.Equal(line, suppliers[0].Line.Value);
Assert.Equal(w.Market.GlobalPrice[ore], suppliers[0].Price);
double mineMonth = mine.CyclesPerDayAtFullCapacity(dpm) * dpm * mine.Efficiency;
Assert.Approx(mineMonth, suppliers[0].MonthlyUnits, 1e-9);
// dopo i collegati, i più vicini
for (int i = 1; i < suppliers.Count; i++)
{
if (suppliers[i - 1].Line.IsValid == suppliers[i].Line.IsValid)
Assert.True(suppliers[i - 1].DistanceKm <= suppliers[i].DistanceKm, "ordinati per distanza");
else Assert.True(suppliers[i - 1].Line.IsValid, "prima i collegati");
}
// clienti dell'acciaio: la fabbrica di attrezzi al prezzo locale dell'ADR 0004 e il porto, non collegati
var customers = r.Outputs[0].Partners;
Assert.True(customers.Count is > 0 && customers.Count <= perGood, $"clienti {customers.Count}");
Assert.True(customers.All(c => !c.Line.IsValid), "nessun cliente collegato");
var tools = w.Industries.First(i => i.Def.Id == "tool_factory");
var toolsEntry = customers.FirstOrDefault(c => c.Kind == ChainPartnerKind.Industry && c.Target == tools.Id.Value);
Assert.True(toolsEntry.Kind == ChainPartnerKind.Industry && toolsEntry.Target == tools.Id.Value, "la fabbrica di attrezzi compra acciaio");
int steelGood = GoodIndex(w, "steel");
int slot = tools.InputIndexOf(steelGood);
double local = Market.LocalPrice(w.Market.GlobalPrice[steelGood], IndustryMath.InputCapacity(tools, slot, dpm), tools.InputStock[slot], w.Data.Balance.LocalPrice);
Assert.Equal(local, toolsEntry.Price);
if (customers.FirstOrDefault(c => c.Kind == ChainPartnerKind.Hub) is { Kind: ChainPartnerKind.Hub } port)
Assert.Equal(w.Hubs[port.Target].BuyPrice(w.Market.GlobalPrice[steelGood]), port.Price);
// servita dalla stazione dell'acciaieria con la linea della compagnia
Assert.True(r.ServingStations.Contains(new StationId(millStation)), "stazione dell'acciaieria");
Assert.Equal(line, r.ServingLine.Value);
// per un'altra compagnia nessuna linea collega
var other = IndustryOutlook.Build(w, steel, CompanyId.None);
Assert.False(other.ServingLine.IsValid);
Assert.True(other.Inputs[0].Partners.All(p => !p.Line.IsValid), "senza compagnia nessun collegamento");
// crescita: punteggio del trimestre dalla stessa funzione della crescita trimestrale
var g = w.Data.Balance.Growth;
Assert.Equal(IndustryMath.GrowthScore(steel, g), r.Growth.Current);
Assert.Equal(g.UpgradeThreshold, r.Growth.UpgradeThreshold);
Assert.Equal(g.DowngradeThreshold, r.Growth.DowngradeThreshold);
Assert.Equal(steel.QuarterDays, r.Growth.QuarterDay);
Assert.Equal(g.QuarterDays, r.Growth.QuarterDays);
Assert.True(r.Growth.Served, "servita da un vettore");
// acquisto: dei privati, livello e avanzamento dai dati (ADR 0018)
var tier = w.Data.Tiers.Tiers.First(t => t.Unlocks.BuyIndustry);
Assert.True(r.ForSale);
Assert.False(r.BuyUnlocked);
Assert.Equal(tier.Level, r.BuyTier);
Assert.Approx(ClimbOutlook.Requirements(w, w.Player, tier).Progress, r.BuyProgress, 1e-12);
Assert.Approx(IndustryMath.AnnualProfit(w, steel), r.AnnualProfit.Cents, 1);
// prezzo di vendita: il prezzo globale del giorno del prodotto (ADR 0004)
Assert.Equal(w.Market.GlobalPrice[steelGood], r.SalePrice);
}
[Test(Description = "La scheda non mostra i pendolari portati da altri vettori, come il Registro degli impieghi; li mostra solo se l'industria è della compagnia")]
public static void WorkforceHidesOtherCarriers()
{
var (f, line, _) = ServedValdoria();
var w = f.W;
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
var rival = new CompanyId(f.Me.Value + 1);
var before = IndustryOutlook.Workforce(w, steel, PaxClass.Worker, f.Me);
var town = w.Towns.First();
var contract = new CommuteContract
{
Id = new ContractId(w.NextIds.Contract++), Town = town.Id, Workplace = WorkplaceRef.Of(steel.Id), Category = PaxClass.Worker,
Headcount = 120, Carrier = rival, ExpectedMinutes = 400, Coverage = 0.9,
};
contract.Route.Add(new LineId(line));
w.Commutes.Add(contract);
// per la compagnia del giocatore il contratto del rivale non c'è: né provenienza né viaggio medio
var mine = IndustryOutlook.Workforce(w, steel, PaxClass.Worker, f.Me);
Assert.False(mine.Sources.Any(x => x.Carrier == rival), "nessuna provenienza del rivale");
Assert.Equal(before.SourceCount, mine.SourceCount);
Assert.Equal(before.AverageMinutes, mine.AverageMinutes);
var sheet = Projection.IndustryCard(w, steel, f.Me).Sheet!;
Assert.False(sheet.Workers.Sources.Any(x => x.Carrier == rival.Value), "nemmeno nel messaggio");
// il rivale vede il suo contratto
var theirs = IndustryOutlook.Workforce(w, steel, PaxClass.Worker, rival);
Assert.True(theirs.Sources.Any(x => x.Carrier == rival && x.Headcount == 120 && x.Town == town.Id), "il vettore vede i suoi pendolari");
Assert.True(theirs.AverageMinutes > 0, "viaggio medio dai suoi contratti");
// l'industria della compagnia mostra i pendolari di tutti i vettori
steel.Owner = f.Me;
var owned = IndustryOutlook.Workforce(w, steel, PaxClass.Worker, f.Me);
Assert.True(owned.Sources.Any(x => x.Carrier == rival), "il proprietario vede tutti i vettori");
Assert.Equal(before.SourceCount + 1, owned.SourceCount);
}
[Test(Description = "Forza lavoro della scheda: presenti, quota in sede, posti scoperti e provenienze dai contratti di pendolarismo")]
public static void WorkforceComesFromTheCommuteContracts()
{
var (f, _, _) = ServedValdoria();
var w = f.W;
var ib = w.Data.Balance.Industry;
foreach (var ind in w.Industries.Where(i => !i.Closed))
{
foreach (var cls in new[] { PaxClass.Worker, PaxClass.Staff })
{
var o = IndustryOutlook.Workforce(w, ind, cls, f.Me);
bool staff = cls == PaxClass.Staff;
int jobs = staff ? ind.JobsStaff : ind.JobsWorkers;
double present = staff ? ind.StaffPresent : ind.WorkersPresent;
Assert.Equal(jobs, o.Jobs);
Assert.Equal(present, o.Present);
Assert.Approx(jobs * (staff ? ib.OnSiteStaffShare : ib.OnSiteWorkerShare), o.OnSite, 1e-9);
Assert.Equal((int)Math.Max(0, Math.Round(jobs - present, MidpointRounding.AwayFromZero)), o.Missing);
var contracts = w.Commutes.Where(c => c.Workplace == WorkplaceRef.Of(ind.Id) && c.Category == cls && c.Headcount > 0 && IndustryOutlook.Visible(c, ind, f.Me)).ToList();
Assert.True(o.Sources.Count <= ib.Outlook.WorkforceSources && o.Sources.Count <= o.SourceCount, "provenienze entro il limite");
if (o.SourceCount <= ib.Outlook.WorkforceSources)
Assert.Equal(contracts.Sum(c => c.Headcount), o.Sources.Sum(s => s.Headcount));
for (int i = 1; i < o.Sources.Count; i++) Assert.True(o.Sources[i - 1].Headcount >= o.Sources[i].Headcount, "dalle più numerose");
var rail = contracts.Where(c => !c.Walking).ToList();
if (rail.Count == 0) Assert.Equal(-1.0, o.AverageMinutes);
else Assert.Approx(rail.Sum(c => c.ExpectedMinutes * c.Headcount) / rail.Sum(c => c.Headcount), o.AverageMinutes, 1e-9);
}
}
}
[Test(Description = "Il limite dell'efficienza è il fattore più basso sotto 1; fermo e livello 0 hanno la precedenza")]
public static void LimitIsTheLowestFactor()
{
var f = RailFixture.Valdoria();
var w = f.W;
w.RunDays(2);
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
var m = w.Data.Balance.IndustryMaintenance;
steel.CovInput = 1;
steel.CovWorkers = 1;
steel.CovStaff = 1;
steel.RevenueEma = 100;
steel.CostEma = 100;
steel.Condition = 100;
Assert.Equal(IndustryLimit.None, IndustryOutlook.Factors(w, steel).Limit);
steel.CovStaff = 0.4;
steel.CovWorkers = 0.6;
Assert.Equal(IndustryLimit.Staff, IndustryOutlook.Factors(w, steel).Limit);
steel.CovInput = 0.3;
Assert.Equal(IndustryLimit.Inputs, IndustryOutlook.Factors(w, steel).Limit);
// impianti sotto il 20 %: mc al minimo, sotto le coperture
steel.CovInput = 0.9;
steel.Condition = 10;
var factors = IndustryOutlook.Factors(w, steel);
Assert.Equal(m.EfficiencyBelow20, factors.ConditionMultiplier);
Assert.Equal(m.EfficiencyBelow20 < 0.4 ? IndustryLimit.Condition : IndustryLimit.Staff, factors.Limit);
// margine negativo: fattore di profitto sotto 1
steel.Condition = 100;
steel.CovStaff = 1;
steel.CovWorkers = 1;
steel.CovInput = 1;
steel.RevenueEma = 0;
steel.CostEma = 100;
Assert.Equal(IndustryLimit.Profit, IndustryOutlook.Factors(w, steel).Limit);
Assert.Equal(IndustryMath.ProfitFactor(steel, w.Data.Balance.Industry), IndustryOutlook.Factors(w, steel).ProfitFactor);
// fermo e livello 0
steel.StoppedUntilDay = w.Clock.Day + 5;
Assert.Equal(IndustryLimit.Stopped, IndustryOutlook.Factors(w, steel).Limit);
steel.StoppedUntilDay = -1;
steel.Level = 0;
Assert.Equal(IndustryLimit.Dormant, IndustryOutlook.Factors(w, steel).Limit);
// senza input (miniera) l'input non è mai il limite; giacimento sotto la soglia
var mine = w.Industries.First(i => i.Def.Id == "iron_mine");
mine.CovInput = 0;
mine.CovWorkers = 1;
mine.CovStaff = 1;
mine.RevenueEma = 100;
mine.CostEma = 100;
mine.Condition = 100;
Assert.Equal(IndustryLimit.None, IndustryOutlook.Factors(w, mine).Limit);
var site = w.Sites[mine.Site.Value];
site.ReserveTonnes = site.InitialReserveTonnes * w.Data.Balance.Industry.DepletionStartFraction / 2;
var depleted = IndustryOutlook.Factors(w, mine);
Assert.Equal(IndustryLimit.Depletion, depleted.Limit);
Assert.Approx(0.5, depleted.Depletion, 1e-9);
Assert.Approx(site.ReserveFraction, depleted.ReserveFraction, 1e-12);
}
[Test(Description = "Il punteggio di crescita trimestrale pesa quota trasportata, copertura e redditività come in balance.json")]
public static void GrowthScoreUsesTheWeights()
{
var f = RailFixture.Valdoria();
var w = f.W;
var g = w.Data.Balance.Growth;
var ind = w.Industries.First(i => i.Def.Id == "steel_mill");
ind.QuarterProduced = 200;
ind.QuarterShipped = 150;
ind.QuarterCoverageSum = 30;
ind.QuarterDays = 60;
ind.RevenueEma = 300;
ind.CostEma = 100;
var s = IndustryMath.GrowthScore(ind, g);
Assert.Approx(0.75, s.Shipped, 1e-12);
Assert.Approx(0.5, s.Coverage, 1e-12);
Assert.Approx((ind.Margin + 1) / 2, s.Profit, 1e-12);
Assert.Approx(g.WeightShipped * 0.75 + g.WeightCoverage * 0.5 + g.WeightProfit * s.Profit, s.Score, 1e-12);
// spedito oltre il prodotto (scorte vecchie): la quota resta 1
ind.QuarterShipped = 500;
Assert.Equal(1.0, IndustryMath.GrowthScore(ind, g).Shipped);
ind.QuarterProduced = 0;
ind.QuarterDays = 0;
Assert.Equal(0.0, IndustryMath.GrowthScore(ind, g).Shipped);
Assert.Equal(0.0, IndustryMath.GrowthScore(ind, g).Coverage);
}
[Test(Description = "La scheda viaggia nel blocco 1 di IndustryCard e torna identica; senza blocco il lettore la lascia vuota")]
public static void SheetRoundTripsInTheIndustryCard()
{
var (f, line, _) = ServedValdoria();
var w = f.W;
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
var card = Projection.IndustryCard(w, steel, f.Me);
Assert.True(card.Sheet is not null, "scheda nel blocco 1");
var decoded = (IndustryCard)Frame.Decode(Frame.Encode(card));
var sheet = decoded.Sheet!;
Assert.True(Frame.Encode(card).AsSpan().SequenceEqual(Frame.Encode(decoded)), "stessi byte");
Assert.Equal((byte)steel.Level, sheet.Level);
Assert.Equal(2, sheet.Inputs.Count);
Assert.Equal(line, sheet.ServingLine);
Assert.Equal(line, sheet.Inputs[0].Partners[0].Line);
Assert.Equal((float)steel.Efficiency, sheet.Efficiency);
Assert.Equal(card.Valuation, decoded.Valuation);
Assert.Equal(steel.JobsWorkers, sheet.Workers.Jobs);
// un messaggio senza blocco (server F5) si legge con la scheda assente
var old = new IndustryCard { Industry = 3, Valuation = new Money(100) };
var back = (IndustryCard)Frame.Decode(Frame.Encode(old));
Assert.True(back.Sheet is null, "nessuna scheda");
Assert.Equal(new Money(100), back.Valuation);
}
}