Le spiegazioni ora si ricompongono davvero dai termini mostrati e il tooltip resta coerente con il pannello su cui sta. Core: - prezzo globale: termini Dtot, Stot, η, rmin, rmax e formula del rapporto D/S = clamp(Dtot/Stot, rmin, rmax) con gli scambi con il mondo; - condizione del treno: la stima viene da Fleet.ConditionDue (estratta da Fleet.Dues senza cambiare l'aritmetica), con condizione e usura del componente che la dà, distinto dal più debole; - tariffe merci e passeggeri riservate alla compagnia della linea; - efficienza: la condizione mostrata è quella da cui viene mc (salvata in EfficiencyTerms prima della manutenzione), formula con «lavoro». Client: - WhyTooltip chiede la spiegazione a ogni apertura e poi al più una volta al secondo per valore (per chiave), mostrando la cache come in aggiornamento; passa al sostituto quando il pannello ricostruisce il controllo sotto il puntatore, invece di chiudersi e lampeggiare; - prezzi come la scheda dell'industria, importi piccoli con i centesimi, condizione per difetto in percentuale, componente accanto al numero; - misura del riquadro dopo l'impaginazione (niente salti di lato); - cassa della barra dalle entità e nota quando il numero mostrato non è quello spiegato; nel Mercato il suggerimento nativo della riga non copre più il tooltip del prezzo. Refs #44. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
457 lines
28 KiB
C#
457 lines
28 KiB
C#
using System.Text.Json.Nodes;
|
||
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.Scenarios;
|
||
using RailEnterprise.Core.Simulation.Systems;
|
||
using RailEnterprise.Protocol;
|
||
using RailEnterprise.Protocol.Messages;
|
||
using RailEnterprise.Server;
|
||
using RailEnterprise.Tests.Harness;
|
||
using RailEnterprise.Tests.Rail;
|
||
using RailEnterprise.Tests.Scenarios;
|
||
using RailEnterprise.Tests.Server;
|
||
|
||
namespace RailEnterprise.Tests.Economy;
|
||
|
||
/// <summary>
|
||
/// Tooltip «perché» (F6, issue #44, ADR 0024): ogni spiegazione dà lo stesso numero del motore e i suoi
|
||
/// termini lo ricompongono con la formula dichiarata; le spiegazioni non cambiano il mondo, viaggiano nel
|
||
/// protocollo e il server le manda su richiesta.
|
||
/// </summary>
|
||
public static class ExplanationTests
|
||
{
|
||
private static int GoodIndex(World w, string id) => w.Data.Goods.First(g => g.Id == id).Index;
|
||
|
||
/// <summary>Valdoria con la linea merci miniera → acciaieria, un treno e 40 giorni di servizio.</summary>
|
||
private static (RailFixture F, int Line, int Train) ServedValdoria(int days = 40)
|
||
{
|
||
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(days);
|
||
return (f, line, train);
|
||
}
|
||
|
||
private static double V(Explanation e, string symbol)
|
||
{
|
||
var t = e.Term(symbol);
|
||
Assert.True(t is not null, $"{e.Title}: manca il termine {symbol}");
|
||
return t!.Value;
|
||
}
|
||
|
||
private static void Available(Explanation e)
|
||
{
|
||
Assert.True(e.Available, $"{e.Title} disponibile");
|
||
Assert.True(e.Title.Length > 0 && e.Formula.Length > 0, $"{e.Title}: titolo e formula");
|
||
}
|
||
|
||
[Test(Description = "Prezzo globale: valore uguale al motore per ogni bene e termini che ricompongono il passo α·Pg′ + (1 − α)·Pg₋₁; anche dopo un caricamento")]
|
||
public static void GlobalPriceMatchesTheMarketStep()
|
||
{
|
||
var (f, _, _) = ServedValdoria();
|
||
var w = f.W;
|
||
void Check(World world, string when)
|
||
{
|
||
int stepped = 0;
|
||
for (int g = 0; g < world.Data.GoodCount; g++)
|
||
{
|
||
var e = Explanations.GlobalPrice(world, new ExplainTarget(ExplainSubject.GlobalPrice, g));
|
||
Available(e);
|
||
Assert.Equal(world.Market.GlobalPrice[g], e.Value, $"{when}: prezzo di {world.Data.Goods[g].Id}");
|
||
if (e.Term("Pg′") is null) continue;
|
||
stepped++;
|
||
double prev = V(e, "Pg₋₁"), target = V(e, "Pg′"), alpha = V(e, "α");
|
||
Assert.Equal(e.Value, alpha * target + (1 - alpha) * prev, $"{when}: passo del prezzo di {world.Data.Goods[g].Id}");
|
||
Assert.Equal(target, DMath.Clamp(prev * (1 + V(e, "k") * (V(e, "D/S") - 1)), V(e, "Pmin"), V(e, "Pmax")), $"{when}: prezzo obiettivo");
|
||
Assert.True(V(e, "D") >= 0 && V(e, "S") >= 0 && V(e, "V") > 0, $"{when}: domanda, offerta e volume mondiale");
|
||
// il rapporto viene da D, S e dagli scambi con il mondo: Dtot = D + V·(Pw/Pg₋₁)^η, Stot = S + V·(Pg₋₁/Pw)^η
|
||
double pw = V(e, "Pw"), v = V(e, "V"), eta = V(e, "η");
|
||
Assert.Equal(V(e, "D") + v * DMath.Pow(pw / prev, eta), V(e, "Dtot"), $"{when}: domanda con il mondo");
|
||
Assert.Equal(V(e, "S") + v * DMath.Pow(prev / pw, eta), V(e, "Stot"), $"{when}: offerta con il mondo");
|
||
Assert.Equal(DMath.Clamp(V(e, "Dtot") / Math.Max(1e-9, V(e, "Stot")), V(e, "rmin"), V(e, "rmax")), V(e, "D/S"), $"{when}: rapporto limitato");
|
||
}
|
||
Assert.True(stepped > 0, $"{when}: almeno un bene in commercio");
|
||
}
|
||
Check(w, "dopo 40 giorni");
|
||
var loaded = SaveFile.Load(TestData.Data, SaveFile.Save(w, "test"));
|
||
Check(loaded, "dopo il caricamento");
|
||
loaded.RunTicks(7);
|
||
Check(loaded, "a metà giornata");
|
||
|
||
// prima del primo passo il prezzo è quello base
|
||
var fresh = RailFixture.Valdoria().W;
|
||
var e0 = Explanations.GlobalPrice(fresh, new ExplainTarget(ExplainSubject.GlobalPrice, 0));
|
||
Assert.Equal((double)fresh.Data.Goods[0].BasePrice, e0.Value);
|
||
Assert.Equal((double)fresh.Data.Goods[0].BasePrice, V(e0, "Pb"));
|
||
}
|
||
|
||
[Test(Description = "Prezzo locale: al consumatore e al produttore lo stesso numero di TradingMath e della vendita, con Pl = Pg·clamp(1 + λ·squilibrio)")]
|
||
public static void LocalPriceMatchesTradingMath()
|
||
{
|
||
var (f, _, _) = ServedValdoria();
|
||
var w = f.W;
|
||
var lp = w.Data.Balance.LocalPrice;
|
||
int ore = GoodIndex(w, "iron_ore");
|
||
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
|
||
var mine = w.Industries.First(i => i.Def.Id == "iron_mine");
|
||
var buyer = Explanations.LocalPrice(w, new ExplainTarget(ExplainSubject.LocalPrice, ore, steel.Id.Value));
|
||
Available(buyer);
|
||
int input = steel.InputIndexOf(ore);
|
||
Assert.Equal(TradingMath.ConsumerPrice(w, steel, input, steel.InputStock[input]), buyer.Value);
|
||
var seller = Explanations.LocalPrice(w, new ExplainTarget(ExplainSubject.LocalPrice, ore, mine.Id.Value));
|
||
int output = mine.OutputIndexOf(ore);
|
||
Assert.Equal(TradingMath.ProducerPrice(w, mine, output, mine.OutputStock[output]), seller.Value);
|
||
foreach (var e in new[] { buyer, seller })
|
||
{
|
||
double dl = V(e, "Dl"), sl = V(e, "Sl");
|
||
double imbalance = (dl - sl) / (dl + sl + V(e, "ε"));
|
||
Assert.Equal(imbalance, V(e, "(Dl − Sl)/(Dl + Sl + ε)"));
|
||
double factor = Math.Clamp(1 + V(e, "λ") * imbalance, 1 - V(e, "δ"), 1 + V(e, "δ"));
|
||
Assert.Equal(factor, V(e, "f"));
|
||
Assert.Equal(e.Value, V(e, "Pg") * factor);
|
||
Assert.Equal(w.Market.GlobalPrice[ore], V(e, "Pg"));
|
||
}
|
||
Assert.Equal(lp.Lambda, V(buyer, "λ"));
|
||
// nessun prezzo locale per un bene che l'industria non tratta
|
||
var none = Explanations.LocalPrice(w, new ExplainTarget(ExplainSubject.LocalPrice, GoodIndex(w, "grain"), mine.Id.Value));
|
||
Assert.False(none.Available);
|
||
}
|
||
|
||
[Test(Description = "Tariffe di una linea: merci e passeggeri uguali a Tariffs del motore, termini che le ricompongono e tf a due volte il tempo atteso")]
|
||
public static void TariffsMatchTheEngine()
|
||
{
|
||
var (f, lineId, trainId) = ServedValdoria();
|
||
var w = f.W;
|
||
var t = w.Data.Balance.Tariffs;
|
||
int ore = GoodIndex(w, "iron_ore");
|
||
var line = w.Lines[lineId];
|
||
var stretch = Explanations.Stretch(w, line)!.Value;
|
||
double km = Vec2.Distance(stretch.From.Position, stretch.To.Position) / 1000;
|
||
var freight = Explanations.FreightTariff(w, new ExplainTarget(ExplainSubject.FreightTariff, lineId, ore), f.Me);
|
||
Available(freight);
|
||
double expected = V(freight, "giorni");
|
||
Assert.True(expected > 0, "la linea porta il minerale: tempo atteso noto");
|
||
Assert.Equal(km, V(freight, "km"));
|
||
var def = w.Data.Goods[ore];
|
||
Assert.Equal((double)Tariffs.Freight(1, km, w.Market.GlobalPrice[ore], def.BasePrice, expected, expected, t, w.Difficulty.TariffMultiplier).Cents, freight.Value);
|
||
double priceFactor = V(freight, "a") + V(freight, "b") * V(freight, "Pg") / V(freight, "Pb");
|
||
Assert.Equal(priceFactor, V(freight, "a + b·Pg/Pb"));
|
||
Assert.Equal(DMath.Pow(km, V(freight, "e")), V(freight, "km^e"));
|
||
Assert.Equal(1.0, V(freight, "tf"));
|
||
double cents = V(freight, "u") * V(freight, "Tb") * priceFactor * V(freight, "km^e") * V(freight, "tf") * V(freight, "d");
|
||
Assert.Equal((double)Money.FromCentsRounded(cents).Cents, freight.Value);
|
||
Assert.Equal(Tariffs.LatenessFactor(2 * expected, expected, t), V(freight, "tf 2×"));
|
||
Assert.True(V(freight, "tariffa 2×") < freight.Value, "in ritardo la tariffa scende");
|
||
|
||
var pax = Explanations.PassengerTariff(w, new ExplainTarget(ExplainSubject.PassengerTariff, lineId, 0), f.Me);
|
||
Available(pax);
|
||
double comfort = Fleet.Comfort(w, w.Trains[trainId], PaxClass.Worker);
|
||
Assert.Equal(comfort, V(pax, "comfort"));
|
||
double paxDays = V(pax, "giorni");
|
||
var engine = Tariffs.Passenger(1, km, PaxClass.Worker, paxDays, paxDays, t, w.Difficulty.TariffMultiplier) * comfort;
|
||
Assert.Equal((double)engine.Cents, pax.Value);
|
||
double paxCents = V(pax, "p") * V(pax, "Tp") * V(pax, "km^e") * V(pax, "classe") * V(pax, "tf") * V(pax, "d");
|
||
Assert.Equal((double)Money.FromCentsRounded(paxCents).Cents, V(pax, "senza comfort"));
|
||
Assert.Equal(pax.Value, (double)(new Money((long)V(pax, "senza comfort")) * V(pax, "comfort")).Cents);
|
||
var staff = Explanations.PassengerTariff(w, new ExplainTarget(ExplainSubject.PassengerTariff, lineId, 1), f.Me);
|
||
Assert.Equal(t.ClassMultipliers["staff"], V(staff, "classe"));
|
||
Assert.False(Explanations.FreightTariff(w, new ExplainTarget(ExplainSubject.FreightTariff, 999, ore), f.Me).Available, "linea inesistente");
|
||
// la linea di un'altra compagnia non si spiega (tempi attesi e comfort sono della sua rete)
|
||
var rival = new CompanyId(f.Me.Value + 1);
|
||
Assert.False(Explanations.Build(w, rival, new ExplainTarget(ExplainSubject.FreightTariff, lineId, ore)).Available, "tariffa merci di una linea altrui");
|
||
Assert.False(Explanations.Build(w, rival, new ExplainTarget(ExplainSubject.PassengerTariff, lineId, 0)).Available, "tariffa passeggeri di una linea altrui");
|
||
Assert.False(Explanations.Build(w, CompanyId.None, new ExplainTarget(ExplainSubject.FreightTariff, lineId, ore)).Available, "spettatore");
|
||
}
|
||
|
||
[Test(Description = "Efficienza dell'industria: i termini dell'ultima produzione ricompongono ind.Efficiency; dopo un caricamento arrivano con il giorno dopo")]
|
||
public static void IndustryEfficiencyMatchesProduction()
|
||
{
|
||
var (f, _, _) = ServedValdoria();
|
||
var w = f.W;
|
||
foreach (var ind in w.Industries.Where(i => !i.Closed))
|
||
{
|
||
var e = Explanations.IndustryEfficiency(w, new ExplainTarget(ExplainSubject.IndustryEfficiency, ind.Id.Value));
|
||
Available(e);
|
||
Assert.Equal(ind.Efficiency, e.Value, ind.Name);
|
||
// ritmo del lavoro: min(cL, cP) × pf × mc, zero solo se l'industria era ferma
|
||
double labour = Math.Min(V(e, "cL"), V(e, "cP")) * V(e, "pf") * V(e, "mc");
|
||
if (V(e, "lavoro") != 0 || labour == 0) Assert.Equal(labour, V(e, "lavoro"), $"{ind.Name}: ritmo del lavoro");
|
||
else Assert.True(e.Notes.Count > 0, $"{ind.Name}: ferma, lo dice la nota");
|
||
Assert.Equal(e.Value, V(e, "lavoro") * V(e, "cI") * V(e, "g") * V(e, "ev"), $"{ind.Name}: prodotto dei fattori");
|
||
// la condizione mostrata è quella da cui viene mc, non quella dopo la manutenzione dello stesso tick
|
||
Assert.Equal(IndustryMath.ConditionMultiplier(V(e, "condizione"), w.Data.Balance.IndustryMaintenance), V(e, "mc"), $"{ind.Name}: mc dalla condizione");
|
||
}
|
||
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
|
||
Assert.Equal(IndustryOutlook.Build(w, steel, f.Me).Efficiency, Explanations.IndustryEfficiency(w, new ExplainTarget(ExplainSubject.IndustryEfficiency, steel.Id.Value)).Value,
|
||
"lo stesso numero della scheda");
|
||
|
||
var loaded = SaveFile.Load(TestData.Data, SaveFile.Save(w, "test"));
|
||
var after = Explanations.IndustryEfficiency(loaded, new ExplainTarget(ExplainSubject.IndustryEfficiency, steel.Id.Value));
|
||
Assert.Equal(steel.Efficiency, after.Value, "valore salvato");
|
||
Assert.Equal(0, after.Terms.Count);
|
||
Assert.Equal(1, after.Notes.Count);
|
||
loaded.RunDays(1);
|
||
var next = Explanations.IndustryEfficiency(loaded, new ExplainTarget(ExplainSubject.IndustryEfficiency, steel.Id.Value));
|
||
Assert.True(next.Terms.Count > 0, "termini della produzione del giorno dopo");
|
||
Assert.Equal(loaded.Industries[steel.Id.Value].Efficiency, next.Value);
|
||
}
|
||
|
||
[Test(Description = "Punteggio di crescita e crescita delle città: le stesse funzioni del motore e i pesi che ricompongono il valore")]
|
||
public static void GrowthMatchesTheEngine()
|
||
{
|
||
var (f, _, _) = ServedValdoria();
|
||
var w = f.W;
|
||
var g = w.Data.Balance.Growth;
|
||
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
|
||
var e = Explanations.IndustryGrowth(w, new ExplainTarget(ExplainSubject.IndustryGrowth, steel.Id.Value));
|
||
Available(e);
|
||
Assert.Equal(IndustryMath.GrowthScore(steel, g).Score, e.Value);
|
||
Assert.Equal(IndustryOutlook.Build(w, steel, f.Me).Growth.Current.Score, e.Value, "lo stesso numero della scheda");
|
||
Assert.Equal(e.Value, V(e, "ws") * V(e, "quota") + V(e, "wc") * V(e, "copertura") + V(e, "wr") * V(e, "redditività"));
|
||
Assert.Equal(Math.Clamp((steel.Margin + 1) / 2, 0, 1), V(e, "redditività"));
|
||
|
||
var tb = w.Data.Balance.Town;
|
||
foreach (var town in w.Towns)
|
||
{
|
||
var t = Explanations.TownGrowth(w, new ExplainTarget(ExplainSubject.TownGrowth, town.Id.Value));
|
||
Available(t);
|
||
Assert.Equal(TownSystem.GrowthOf(town, tb).Growth, t.Value, town.Name);
|
||
double raw = V(t, "g₀") + V(t, "ws") * (V(t, "s") - V(t, "s₀")) + V(t, "wo") * (V(t, "o") - V(t, "o₀"));
|
||
Assert.Equal(raw, V(t, "g grezza"), $"{town.Name}: crescita grezza");
|
||
Assert.Equal(t.Value, Math.Clamp(raw, -V(t, "gmax"), V(t, "gmax")), $"{town.Name}: limite");
|
||
Assert.Equal(town.LastGrowth, V(t, "ultimo mese"));
|
||
}
|
||
}
|
||
|
||
[Test(Description = "Condizione del treno: il componente più debole, il rischio di guasto del controllo giornaliero con 1/h e la stima del pianificatore")]
|
||
public static void TrainConditionMatchesTheFleet()
|
||
{
|
||
var (f, _, trainId) = ServedValdoria(120);
|
||
var w = f.W;
|
||
var train = w.Trains[trainId];
|
||
var e = Explanations.TrainCondition(w, new ExplainTarget(ExplainSubject.TrainCondition, trainId), f.Me);
|
||
Available(e);
|
||
Assert.Equal(Fleet.TrainCondition(w, train), e.Value);
|
||
Assert.Equal(e.Value, V(e, "c"));
|
||
var fp = w.Data.Maintenance.Failure;
|
||
double c = V(e, "c rischio");
|
||
double h = c < V(e, "c₀") ? V(e, "h₀") * DMath.Exp(V(e, "k") * (V(e, "c₀") - c) / V(e, "σ")) : V(e, "h₀") / V(e, "div");
|
||
Assert.Equal(Fleet.Hazard(c, fp), h);
|
||
Assert.Equal(h * V(e, "ispezione"), V(e, "h"));
|
||
Assert.Equal(Fleet.DailyHazard(w, train, w.Clock.Day).Hazard, V(e, "h"));
|
||
Assert.Equal(1 / V(e, "h"), V(e, "1/h"));
|
||
Assert.Equal(Fleet.Dues(w, train).Condition, V(e, "stima"), "stima del pianificatore");
|
||
Stima(e);
|
||
|
||
// la stima viene dal componente con meno giorni all'obiettivo, non dal più debole: freni a 60 che calano
|
||
// di 2 al giorno contro il motore a 55 che cala di 0,1
|
||
var loco = w.Vehicles[train.Vehicles[0].Value];
|
||
var comps = Fleet.ComponentsOf(w.Data, loco.Def);
|
||
int brakes = Fleet.ComponentIndex(comps, Fleet.Brakes), engine = Fleet.ComponentIndex(comps, Fleet.Engine);
|
||
Assert.True(brakes >= 0 && engine >= 0, "la locomotiva ha freni e motore");
|
||
foreach (var id in train.Vehicles)
|
||
{
|
||
var v = w.Vehicles[id.Value];
|
||
for (int j = 0; j < v.Components.Length; j++)
|
||
{
|
||
v.Components[j] = 90;
|
||
if (j < v.WearEma.Length) v.WearEma[j] = 0.01;
|
||
}
|
||
}
|
||
loco.Components[brakes] = 60;
|
||
loco.WearEma[brakes] = 2;
|
||
loco.Components[engine] = 55;
|
||
loco.WearEma[engine] = 0.1;
|
||
var split = Explanations.TrainCondition(w, new ExplainTarget(ExplainSubject.TrainCondition, trainId), f.Me);
|
||
Assert.Equal(55.0, V(split, "c"), "il più debole è il motore");
|
||
Assert.Equal(Fleet.Engine, split.Term("c")!.Text);
|
||
Assert.Equal(60.0, V(split, "cs"), "la stima viene dai freni");
|
||
Assert.Equal(Fleet.Brakes, split.Term("cs")!.Text);
|
||
Assert.Equal(2.0, V(split, "usura"));
|
||
Assert.Equal(Fleet.Dues(w, train).Condition, V(split, "stima"));
|
||
Stima(split);
|
||
|
||
// un treno di un'altra compagnia non si spiega
|
||
var other = Explanations.Build(w, new CompanyId(f.Me.Value + 1), new ExplainTarget(ExplainSubject.TrainCondition, trainId));
|
||
Assert.False(other.Available);
|
||
}
|
||
|
||
/// <summary>La stima del pianificatore ricomposta dai termini: (cs − obiettivo)/usura − margine, −margine all'obiettivo.</summary>
|
||
private static void Stima(Explanation e)
|
||
{
|
||
if (e.Term("stima") is null) return;
|
||
double cs = V(e, "cs"), target = V(e, "obiettivo"), margin = V(e, "margine");
|
||
double expected = cs <= target ? -margin : (cs - target) / V(e, "usura") - margin;
|
||
Assert.Equal(expected, V(e, "stima"), "stima ricomposta dai termini");
|
||
}
|
||
|
||
[Test(Description = "Valore del veicolo: valore di libro e rivendita di Obsolescence, con la curva del residuo nuovo e superato")]
|
||
public static void VehicleValueMatchesObsolescence()
|
||
{
|
||
var json = JsonNode.Parse(File.ReadAllText(ScenarioHelper.PathOf("valdoria")))!;
|
||
json["startYear"] = 1878;
|
||
var s = ScenarioLoader.Load(TestData.Data, json.ToJsonString());
|
||
var f = new RailFixture(s.World, s);
|
||
var w = f.W;
|
||
int depot = f.Ok(new BuildDepotCommand(RailFixture.K(2.6, 4.4), "small", "Deposito di prova"));
|
||
int old = f.Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1)).Created[0];
|
||
int fresh = f.Do(new BuyVehicleCommand("loco_steam_1878", new DepotId(depot), 1)).Created[0];
|
||
w.RunDays(400);
|
||
var floor = w.Data.Balance.Finance.BookValueFloor;
|
||
foreach (int id in new[] { old, fresh })
|
||
{
|
||
var v = w.Vehicles[id];
|
||
var e = Explanations.VehicleValue(w, new ExplainTarget(ExplainSubject.VehicleValue, id), f.Me);
|
||
Available(e);
|
||
Assert.Equal((double)Obsolescence.BookValueCents(w, v), e.Value, v.Def.Id);
|
||
Assert.Equal((double)Obsolescence.ResaleValue(w, v).Cents, V(e, "rivendita"));
|
||
double r = e.Term("perdita") is null
|
||
? Math.Max(floor, 1 - V(e, "età") / V(e, "vita"))
|
||
: Math.Max(floor, (1 - V(e, "perdita")) * (1 - (V(e, "età") + (V(e, "velocità") - 1) * V(e, "anni superato")) / V(e, "vita")));
|
||
Assert.Equal(V(e, "r"), r, $"{v.Def.Id}: residuo");
|
||
Assert.Equal(e.Value, (double)(long)(V(e, "prezzo") * r), $"{v.Def.Id}: valore di libro");
|
||
Assert.Equal(V(e, "rivendita"), (double)(new Money((long)V(e, "prezzo")) * (r * V(e, "condizione"))).Cents, $"{v.Def.Id}: rivendita");
|
||
}
|
||
var superseded = Explanations.VehicleValue(w, new ExplainTarget(ExplainSubject.VehicleValue, old), f.Me);
|
||
Assert.True(superseded.Term("perdita") is not null, "il modello del 1850 è superato");
|
||
Assert.Equal("loco_steam_1878", w.Data.Vehicles.First(d => d.NameIt == superseded.Term("successore")!.Text).Id);
|
||
Assert.True(Explanations.VehicleValue(w, new ExplainTarget(ExplainSubject.VehicleValue, fresh), f.Me).Term("perdita") is null, "il modello del 1878 non è superato");
|
||
}
|
||
|
||
[Test(Description = "Rating, avanzamento del livello e cassa: gli stessi numeri di FinanceOutlook, ClimbOutlook e della compagnia, ricomposti dai termini")]
|
||
public static void CompanyValuesMatchTheOutlooks()
|
||
{
|
||
var (f, _, _) = ServedValdoria(75);
|
||
var w = f.W;
|
||
var c = w.Company(f.Me);
|
||
var rating = Explanations.Build(w, f.Me, new ExplainTarget(ExplainSubject.Rating));
|
||
Available(rating);
|
||
var explain = FinanceOutlook.Explain(w, c);
|
||
Assert.Equal(explain.Score, rating.Value);
|
||
Assert.Equal(c.Rating.ToString(), rating.ValueText);
|
||
Assert.Equal(FinanceSystem.MarginComponent(V(rating, "margine")), V(rating, "cm"));
|
||
Assert.Equal(FinanceSystem.LeverageComponent(V(rating, "leva")), V(rating, "cl"));
|
||
Assert.Equal(rating.Value, V(rating, "pm") * V(rating, "cm") + V(rating, "pl") * V(rating, "cl"));
|
||
|
||
var tier = Explanations.Build(w, f.Me, new ExplainTarget(ExplainSubject.TierProgress));
|
||
Available(tier);
|
||
var req = ClimbOutlook.Requirements(w, c, w.Data.Tiers.Tiers[c.Tier]);
|
||
Assert.Equal(req.Progress, tier.Value);
|
||
Assert.Equal(DMath.Clamp(V(tier, "patrimonio") / V(tier, "soglia"), 0, 1), V(tier, "fP"));
|
||
Assert.Equal(DMath.Clamp(V(tier, "città") / V(tier, "richieste"), 0, 1), V(tier, "fC"));
|
||
double progress = (V(tier, "fP") + V(tier, "fC") + V(tier, "fR")) / 3;
|
||
if (!(req.NetWorthMet && req.TownsMet && req.RatingMet)) progress = Math.Min(progress, V(tier, "tetto"));
|
||
Assert.Equal(tier.Value, progress);
|
||
|
||
var cash = Explanations.Build(w, f.Me, new ExplainTarget(ExplainSubject.Cash));
|
||
Available(cash);
|
||
Assert.Equal((double)c.Cash.Cents, cash.Value);
|
||
Assert.Equal(V(cash, "flusso"), V(cash, "ricavi") + V(cash, "costi") + V(cash, "capitale"));
|
||
Assert.Equal(cash.Value, V(cash, "inizio") + V(cash, "flusso"));
|
||
Assert.True(V(cash, "ricavi") > 0, "la linea incassa noli nel mese");
|
||
}
|
||
|
||
[Test(Description = "Le spiegazioni non cambiano il mondo e si proiettano nel protocollo (ExplanationReport) senza perdere nulla; RequestDetail porta il bersaglio nel blocco 1")]
|
||
public static void ExplanationsAreReadOnlyAndRoundTrip()
|
||
{
|
||
var (f, line, train) = ServedValdoria();
|
||
var w = f.W;
|
||
int ore = GoodIndex(w, "iron_ore");
|
||
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
|
||
int vehicle = w.Trains[train].Vehicles[0].Value;
|
||
var targets = new[]
|
||
{
|
||
new ExplainTarget(ExplainSubject.GlobalPrice, ore), new ExplainTarget(ExplainSubject.LocalPrice, ore, steel.Id.Value),
|
||
new ExplainTarget(ExplainSubject.FreightTariff, line, ore), new ExplainTarget(ExplainSubject.PassengerTariff, line, 1),
|
||
new ExplainTarget(ExplainSubject.IndustryEfficiency, steel.Id.Value), new ExplainTarget(ExplainSubject.IndustryGrowth, steel.Id.Value),
|
||
new ExplainTarget(ExplainSubject.TownGrowth, 0), new ExplainTarget(ExplainSubject.TrainCondition, train),
|
||
new ExplainTarget(ExplainSubject.Rating), new ExplainTarget(ExplainSubject.TierProgress),
|
||
new ExplainTarget(ExplainSubject.VehicleValue, vehicle), new ExplainTarget(ExplainSubject.Cash),
|
||
};
|
||
Assert.Equal(Enum.GetValues<ExplainSubject>().Length - 1, targets.Length, "un bersaglio per ogni soggetto");
|
||
ulong hash = StateHasher.Compute(w);
|
||
foreach (var target in targets)
|
||
{
|
||
var e = Explanations.Build(w, f.Me, target);
|
||
Available(e);
|
||
Assert.True(e.Terms.Count > 0 || e.Notes.Count > 0, $"{target.Subject}: termini o note");
|
||
var report = Projection.Explanation(w, f.Me, (byte)target.Subject, target.A, target.B);
|
||
var back = (ExplanationReport)Frame.Decode(Frame.Encode(report));
|
||
Assert.Equal((byte)target.Subject, back.Subject);
|
||
Assert.Equal(target.A, back.Target);
|
||
Assert.Equal(target.B, back.Arg);
|
||
Assert.Equal(e.Value, back.Value, $"{target.Subject}: valore");
|
||
Assert.Equal(e.Title, back.Title);
|
||
Assert.Equal(e.Formula, back.Formula);
|
||
Assert.Equal(e.ValueText, back.ValueText);
|
||
Assert.Equal((byte)e.Unit, back.Unit);
|
||
Assert.Equal(e.Terms.Count, back.Terms.Count);
|
||
for (int i = 0; i < e.Terms.Count; i++)
|
||
{
|
||
Assert.Equal(e.Terms[i].Symbol, back.Terms[i].Symbol);
|
||
Assert.Equal(e.Terms[i].Label, back.Terms[i].Label);
|
||
Assert.Equal(e.Terms[i].Value, back.Terms[i].Value);
|
||
Assert.Equal((byte)e.Terms[i].Unit, back.Terms[i].Unit);
|
||
Assert.Equal(e.Terms[i].Text, back.Terms[i].Text);
|
||
}
|
||
Assert.SequenceEqual(e.Notes, back.Notes);
|
||
}
|
||
Assert.Equal(hash, StateHasher.Compute(w), "le spiegazioni non cambiano il mondo");
|
||
var missing = Projection.Explanation(w, f.Me, (byte)ExplainSubject.IndustryEfficiency, 9999, -1);
|
||
Assert.False(missing.Available);
|
||
|
||
// richiesta: il bersaglio viaggia nel blocco 1; una richiesta senza blocco si legge con soggetto 0
|
||
var request = (RequestDetail)Frame.Decode(Frame.Encode(new RequestDetail { Kind = DetailKind.Explain, Target = 4, Subject = (byte)ExplainSubject.LocalPrice, Arg = 9 }));
|
||
Assert.Equal(DetailKind.Explain, request.Kind);
|
||
Assert.Equal(4, request.Target);
|
||
Assert.Equal((byte)ExplainSubject.LocalPrice, request.Subject);
|
||
Assert.Equal(9, request.Arg);
|
||
var plain = (RequestDetail)Frame.Decode(Frame.Encode(new RequestDetail { Kind = DetailKind.Market, Target = 0 }));
|
||
Assert.Equal((byte)0, plain.Subject);
|
||
Assert.Equal(-1, plain.Arg);
|
||
}
|
||
|
||
[Test(Description = "F6 in rete: la spiegazione arriva su richiesta (si aspetta la risposta, non una vecchia), con il prezzo del motore; un bersaglio inesistente risponde «non disponibile»")]
|
||
public static void ExplanationOnRequest() => RunOnRequest().GetAwaiter().GetResult();
|
||
|
||
private static async Task RunOnRequest()
|
||
{
|
||
var scenario = ScenarioHelper.Load("valdoria");
|
||
int coal = scenario.World.Data.Goods.First(g => g.Id == "coal").Index;
|
||
await using var server = ServerFixture.Start(scenario.World);
|
||
await using var client = await TestClient.ConnectAsync(server);
|
||
var w = client.World;
|
||
await client.WaitUntil(() => w.LastDigest is { Day: >= 2 }, "due giorni di partita");
|
||
|
||
var key = ((byte)ExplainSubject.GlobalPrice, coal, -1);
|
||
Assert.False(w.Explanations.ContainsKey(key), "il server non manda spiegazioni da solo");
|
||
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Explain, Target = coal, Subject = (byte)ExplainSubject.GlobalPrice, Arg = -1 });
|
||
var first = await client.WaitFor(() => w.Explanations.GetValueOrDefault(key), "spiegazione del prezzo");
|
||
Assert.True(first.Available, "disponibile");
|
||
Assert.Equal("Prezzo globale", first.Title);
|
||
Assert.True(first.Day >= 2, $"giorno {first.Day}");
|
||
Assert.True(first.Terms.Count > 0 && first.Formula.Length > 0, "formula e termini");
|
||
Assert.True(first.Value > 0, "prezzo positivo");
|
||
|
||
// una seconda richiesta: si aspetta la risposta nuova, non quella già in cache
|
||
await client.WaitUntil(() => w.LastDigest!.Day > first.Day, "un giorno dopo");
|
||
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Explain, Target = coal, Subject = (byte)ExplainSubject.GlobalPrice, Arg = -1 });
|
||
var second = await client.WaitFor(() => w.Explanations.TryGetValue(key, out var e) && !ReferenceEquals(e, first) ? e : null, "spiegazione nuova");
|
||
Assert.True(second.Day > first.Day, "spiegazione di un giorno dopo");
|
||
if (w.LastDigest!.Day == second.Day)
|
||
Assert.Equal(w.LastDigest.Prices[coal].Cents, Money.FromCentsRounded(second.Value).Cents, "lo stesso prezzo del resoconto del giorno");
|
||
|
||
var missingKey = ((byte)ExplainSubject.TrainCondition, 999, -1);
|
||
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Explain, Target = 999, Subject = (byte)ExplainSubject.TrainCondition, Arg = -1 });
|
||
var missing = await client.WaitFor(() => w.Explanations.GetValueOrDefault(missingKey), "spiegazione non disponibile");
|
||
Assert.False(missing.Available, "treno inesistente");
|
||
}
|
||
}
|