F6: tooltip perché sui valori calcolati dal server
Ogni valore importante dei pannelli spiega al passaggio del mouse da dove viene: formula, termini con i valori di oggi e note, calcolati dal Core e mandati dal server, perché il client non deve rifare né ricomporre formule. - Core: modello comune Explanation ed Explanations, pure funzioni che chiamano le stesse funzioni del motore; estratte senza cambiare l'aritmetica (hash invariati) Market.NextPrice e LocalPriceTerms, Tariffs.FreightTerms e PassengerTerms, TownSystem.GrowthOf, Fleet.DailyHazard, GameClock.YearsAt; Industry.LastEfficiency transitorio (né salvato né nell'hash). - Protocollo: RequestDetail kind 11 con un blocco 1 (subject, arg) ed ExplanationReport 137; il server risponde sempre, anche con available falso. Nessun campo nei delta, formato dei salvataggi invariato. - Client: WhyTooltip comune (palette 05, apertura dopo 0,45 s, «in arrivo…» finché la spiegazione manca) su barra superiore, Mercato, Scalata, Finanze, scheda industria, Treni e Officine; testi in strings.csv. - ADR 0024, PROTOCOL.md, ARCHITECTURE.md, STATE.md; 10 test nuovi in Economy/ExplanationTests.cs con uguaglianza esatta ai valori del motore. Refs #44. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
767661957b
commit
19a3dd3af1
33 files changed
+2089
-64
No files matched your search
@@ -0,0 +1,93 @@
|
||||
namespace RailEnterprise.Core.Economy;
|
||||
|
||||
/// <summary>
|
||||
/// Valore che il tooltip «perché» sa spiegare (ADR 0024). <see cref="ExplainTarget.A"/> e
|
||||
/// <see cref="ExplainTarget.B"/> dicono di quale oggetto: il significato è scritto accanto a ogni voce.
|
||||
/// </summary>
|
||||
public enum ExplainSubject : byte
|
||||
{
|
||||
None = 0,
|
||||
/// <summary>Prezzo globale di un bene (A = bene).</summary>
|
||||
GlobalPrice = 1,
|
||||
/// <summary>Prezzo locale di un bene in un'industria (A = bene, B = industria).</summary>
|
||||
LocalPrice = 2,
|
||||
/// <summary>Tariffa merci della tratta più lunga di una linea (A = linea, B = bene).</summary>
|
||||
FreightTariff = 3,
|
||||
/// <summary>Tariffa passeggeri della tratta più lunga di una linea (A = linea, B = 0 lavoratori, 1 personale).</summary>
|
||||
PassengerTariff = 4,
|
||||
/// <summary>Efficienza di un'industria (A = industria).</summary>
|
||||
IndustryEfficiency = 5,
|
||||
/// <summary>Punteggio di crescita del trimestre in corso di un'industria (A = industria).</summary>
|
||||
IndustryGrowth = 6,
|
||||
/// <summary>Crescita mensile di una città (A = città).</summary>
|
||||
TownGrowth = 7,
|
||||
/// <summary>Condizione di un treno con il rischio di guasto e la stima del pianificatore (A = treno).</summary>
|
||||
TrainCondition = 8,
|
||||
/// <summary>Rating della compagnia della sessione.</summary>
|
||||
Rating = 9,
|
||||
/// <summary>Avanzamento verso il prossimo livello della compagnia della sessione.</summary>
|
||||
TierProgress = 10,
|
||||
/// <summary>Valore di libro e rivendita di un veicolo (A = veicolo).</summary>
|
||||
VehicleValue = 11,
|
||||
/// <summary>Cassa della compagnia della sessione con i movimenti del mese.</summary>
|
||||
Cash = 12,
|
||||
}
|
||||
|
||||
/// <summary>Unità di un valore spiegato: dice al client come formattarlo, come nei pannelli.</summary>
|
||||
public enum ExplainUnit : byte
|
||||
{
|
||||
/// <summary>Numero puro (due decimali).</summary>
|
||||
Number = 0,
|
||||
/// <summary>Importo in centesimi (si mostra come Money).</summary>
|
||||
Money = 1,
|
||||
/// <summary>Prezzo per unità in centesimi frazionari.</summary>
|
||||
Price = 2,
|
||||
/// <summary>Frazione mostrata in percentuale.</summary>
|
||||
Percent = 3,
|
||||
/// <summary>Moltiplicatore («× 0,85»).</summary>
|
||||
Factor = 4,
|
||||
Km = 5,
|
||||
Days = 6,
|
||||
/// <summary>Quantità (unità, persone, città).</summary>
|
||||
Units = 7,
|
||||
/// <summary>Condizione 0–100.</summary>
|
||||
Condition = 8,
|
||||
Years = 9,
|
||||
/// <summary>Valore testuale: conta <see cref="ExplanationTerm.Text"/> (rating, nomi, anni).</summary>
|
||||
Text = 10,
|
||||
}
|
||||
|
||||
/// <summary>Bersaglio di una spiegazione: il valore e l'oggetto (−1 dove non serve).</summary>
|
||||
public readonly record struct ExplainTarget(ExplainSubject Subject, int A = -1, int B = -1);
|
||||
|
||||
/// <summary>
|
||||
/// Termine della formula: simbolo come compare nella formula, etichetta in italiano (chiave di traduzione
|
||||
/// del client), valore con l'unità e, per i valori testuali, il testo.
|
||||
/// </summary>
|
||||
public sealed record ExplanationTerm(string Symbol, string Label, double Value, ExplainUnit Unit, string Text = "");
|
||||
|
||||
/// <summary>
|
||||
/// Spiegazione di un valore calcolato dal motore (ADR 0024): titolo e nome dell'oggetto, valore con la sua
|
||||
/// unità (lo stesso numero del motore), formula in testo, termini con i valori di oggi e note. Titolo,
|
||||
/// formula, etichette e note sono testi italiani fissi che il client traduce; i numeri stanno nei termini.
|
||||
/// </summary>
|
||||
public sealed class Explanation
|
||||
{
|
||||
public required ExplainTarget Target { get; init; }
|
||||
public required long Day { get; init; }
|
||||
/// <summary>Falso se il bersaglio non esiste o non è visibile alla compagnia: titolo e note dicono perché.</summary>
|
||||
public required bool Available { get; init; }
|
||||
public required string Title { get; init; }
|
||||
/// <summary>Nome dell'oggetto (bene, industria, città, linea, treno, veicolo, compagnia); vuoto se non serve.</summary>
|
||||
public required string Name { get; init; }
|
||||
public required double Value { get; init; }
|
||||
public required ExplainUnit Unit { get; init; }
|
||||
/// <summary>Testo del valore quando non è un numero (il rating); vuoto altrimenti.</summary>
|
||||
public string ValueText { get; init; } = "";
|
||||
public required string Formula { get; init; }
|
||||
public required List<ExplanationTerm> Terms { get; init; }
|
||||
public required List<string> Notes { get; init; }
|
||||
|
||||
/// <summary>Termine con il simbolo indicato (il primo); null se manca.</summary>
|
||||
public ExplanationTerm? Term(string symbol) => Terms.FirstOrDefault(t => t.Symbol == symbol);
|
||||
}
|
||||
@@ -0,0 +1,632 @@
|
||||
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>
|
||||
/// Spiegazioni «perché» dei valori principali (ADR 0024): pure funzioni del mondo, come i quadri dei pannelli.
|
||||
/// Ogni spiegazione chiama le stesse funzioni che usa il motore (passo del prezzo, prezzo locale, tariffe,
|
||||
/// termini dell'ultima produzione, punteggio di crescita, crescita della città, rischio di guasto, rating,
|
||||
/// requisiti del livello, curva del valore dei veicoli), quindi il valore finale è lo stesso numero del
|
||||
/// motore e i termini lo ricompongono con la formula dichiarata. Titoli, formule, etichette e note sono
|
||||
/// testi italiani fissi (chiavi di traduzione del client); i numeri viaggiano nei termini.
|
||||
/// </summary>
|
||||
public static class Explanations
|
||||
{
|
||||
/// <summary>Spiegazione del valore per la compagnia indicata (quella della sessione).</summary>
|
||||
public static Explanation Build(World w, CompanyId company, ExplainTarget target)
|
||||
{
|
||||
var c = company.IsValid && company.Value < w.Companies.Count ? w.Companies[company.Value] : null;
|
||||
return target.Subject switch
|
||||
{
|
||||
ExplainSubject.GlobalPrice => GlobalPrice(w, target),
|
||||
ExplainSubject.LocalPrice => LocalPrice(w, target),
|
||||
ExplainSubject.FreightTariff => FreightTariff(w, target),
|
||||
ExplainSubject.PassengerTariff => PassengerTariff(w, target),
|
||||
ExplainSubject.IndustryEfficiency => IndustryEfficiency(w, target),
|
||||
ExplainSubject.IndustryGrowth => IndustryGrowth(w, target),
|
||||
ExplainSubject.TownGrowth => TownGrowth(w, target),
|
||||
ExplainSubject.TrainCondition => TrainCondition(w, target, company),
|
||||
ExplainSubject.Rating => c is null ? Missing(w, target, "Rating") : Rating(w, target, c),
|
||||
ExplainSubject.TierProgress => c is null ? Missing(w, target, "Avanzamento del livello") : TierProgress(w, target, c),
|
||||
ExplainSubject.VehicleValue => VehicleValue(w, target, company),
|
||||
ExplainSubject.Cash => c is null ? Missing(w, target, "Cassa") : Cash(w, target, c),
|
||||
_ => Missing(w, target, ""),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Spiegazione assente: bersaglio inesistente, chiuso o di un'altra compagnia.</summary>
|
||||
public static Explanation Missing(World w, ExplainTarget target, string title) => new()
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = false, Title = title, Name = "", Value = 0, Unit = ExplainUnit.Number,
|
||||
Formula = "", Terms = [], Notes = ["Valore non disponibile."],
|
||||
};
|
||||
|
||||
private static ExplanationTerm T(string symbol, string label, double value, ExplainUnit unit, string text = "") => new(symbol, label, value, unit, text);
|
||||
|
||||
// ------------------------------------------------------------------ prezzi
|
||||
|
||||
/// <summary>
|
||||
/// Prezzo globale di oggi rifatto con <see cref="Market.NextPrice"/> dagli stessi ingressi del passo di
|
||||
/// MarketSystem: prezzo di ieri dallo storico, finestre di domanda e offerta (invariate dal passo),
|
||||
/// shock e anni al tick del passo (il primo tick del giorno dell'ultimo passo eseguito).
|
||||
/// </summary>
|
||||
public static Explanation GlobalPrice(World w, ExplainTarget target)
|
||||
{
|
||||
int g = target.A;
|
||||
if (g < 0 || g >= w.Data.GoodCount) return Missing(w, target, "Prezzo globale");
|
||||
var def = w.Data.Goods[g];
|
||||
var m = w.Data.Balance.Market;
|
||||
var market = w.Market;
|
||||
double pg = market.GlobalPrice[g];
|
||||
var cal = w.Calendar;
|
||||
var terms = new List<ExplanationTerm>();
|
||||
var notes = new List<string>();
|
||||
const string formula = "Pg = α·Pg′ + (1 − α)·Pg₋₁; Pg′ = clamp(Pg₋₁·(1 + k·(D/S − 1)), Pmin, Pmax)";
|
||||
long stepTick = w.Clock.Tick == 0 ? -1 : (w.Clock.Tick - 1) / cal.TicksPerDay * cal.TicksPerDay;
|
||||
int stepYear = stepTick < 0 ? cal.StartYear : cal.StartYear + (int)(stepTick / cal.TicksPerDay / cal.DaysPerYear);
|
||||
if (stepTick < 0 || def.Era > stepYear)
|
||||
{
|
||||
terms.Add(T("Pb", "Prezzo base", def.BasePrice, ExplainUnit.Price));
|
||||
notes.Add(stepTick < 0 ? "Prezzo iniziale: il prezzo base del bene." : "Bene non ancora in commercio: il prezzo resta quello di partenza.");
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Prezzo globale", Name = def.NameIt,
|
||||
Value = pg, Unit = ExplainUnit.Price, Formula = formula, Terms = terms, Notes = notes,
|
||||
};
|
||||
}
|
||||
var history = market.PriceHistory[g];
|
||||
double previous = history.Count >= 2 ? history.Ago(1) : def.BasePrice;
|
||||
double volatility = w.Difficulty.MarketVolatilityMultiplier;
|
||||
double years = w.Clock.YearsAt(stepTick);
|
||||
var step = Market.NextPrice(m, def.BasePrice, previous, market.Demand[g].Sum, market.Supply[g].Sum, market.Demand[g].Count,
|
||||
volatility, years, market.Shock[g]);
|
||||
terms.Add(T("Pg₋₁", "Prezzo di ieri", step.Previous, ExplainUnit.Price));
|
||||
terms.Add(T("Pb", "Prezzo base", step.BasePrice, ExplainUnit.Price));
|
||||
terms.Add(T("D", "Domanda della regione (finestra)", step.Demand, ExplainUnit.Units));
|
||||
terms.Add(T("S", "Offerta della regione (finestra)", step.Supply, ExplainUnit.Units));
|
||||
terms.Add(T("Pw", "Prezzo mondiale", step.WorldPrice, ExplainUnit.Price));
|
||||
terms.Add(T("V", "Scambi con il resto del mondo", step.WorldVolume, ExplainUnit.Units));
|
||||
terms.Add(T("D/S", "Rapporto domanda / offerta (con il mondo)", step.Ratio, ExplainUnit.Factor));
|
||||
terms.Add(T("k", "Sensibilità al rapporto", m.K, ExplainUnit.Number));
|
||||
terms.Add(T("Pmin", "Prezzo minimo", m.MinPriceFactor * def.BasePrice, ExplainUnit.Price));
|
||||
terms.Add(T("Pmax", "Prezzo massimo", m.MaxPriceFactor * def.BasePrice, ExplainUnit.Price));
|
||||
terms.Add(T("Pg′", "Prezzo obiettivo", step.Target, ExplainUnit.Price));
|
||||
terms.Add(T("α", "Peso del giorno", m.Alpha, ExplainUnit.Number));
|
||||
notes.Add("D e S comprendono gli scambi con il resto del mondo al prezzo mondiale, che segue il ciclo economico e gli shock.");
|
||||
if (Math.Abs(step.Price - pg) > 1e-9 * Math.Max(1, pg)) notes.Add("Il prezzo è cambiato dopo l'ultimo passo del mercato.");
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Prezzo globale", Name = def.NameIt,
|
||||
Value = pg, Unit = ExplainUnit.Price, Formula = formula, Terms = terms, Notes = notes,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Prezzo locale della prossima unità in un'industria (ADR 0004 §3): al consumatore con
|
||||
/// <see cref="TradingMath.ConsumerPrice"/> (Dl = capienza dell'ingresso, Sl = scorta), altrimenti al
|
||||
/// produttore con <see cref="TradingMath.ProducerPrice"/> (Dl = spazio libero, Sl = giacenza).
|
||||
/// </summary>
|
||||
public static Explanation LocalPrice(World w, ExplainTarget target)
|
||||
{
|
||||
int g = target.A, id = target.B;
|
||||
if (g < 0 || g >= w.Data.GoodCount || id < 0 || id >= w.Industries.Count) return Missing(w, target, "Prezzo locale");
|
||||
var ind = w.Industries[id];
|
||||
int dpm = w.Calendar.DaysPerMonth;
|
||||
int input = ind.InputIndexOf(g), output = ind.OutputIndexOf(g);
|
||||
if (ind.Closed || (input < 0 && output < 0)) return Missing(w, target, "Prezzo locale");
|
||||
var lp = w.Data.Balance.LocalPrice;
|
||||
double pg = w.Market.GlobalPrice[g];
|
||||
LocalPriceStep step;
|
||||
double value;
|
||||
var notes = new List<string>();
|
||||
if (input >= 0)
|
||||
{
|
||||
int stock = ind.InputStock[input];
|
||||
value = TradingMath.ConsumerPrice(w, ind, input, stock);
|
||||
step = Market.LocalPriceTerms(pg, IndustryMath.InputCapacity(ind, input, dpm), stock, lp);
|
||||
notes.Add("Prezzo a cui l'industria compra la prossima unità: Dl è la scorta desiderata dell'ingresso, Sl la scorta.");
|
||||
}
|
||||
else
|
||||
{
|
||||
int stock = ind.OutputStock[output];
|
||||
value = TradingMath.ProducerPrice(w, ind, output, stock);
|
||||
step = Market.LocalPriceTerms(pg, Math.Max(0, IndustryMath.OutputCapacity(ind, output, dpm) - stock), stock, lp);
|
||||
notes.Add("Prezzo a cui l'industria vende la prossima unità: Dl è lo spazio libero del magazzino, Sl la giacenza.");
|
||||
}
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Prezzo locale", Name = $"{w.Data.Goods[g].NameIt} · {ind.Name}",
|
||||
Value = value, Unit = ExplainUnit.Price,
|
||||
Formula = "Pl = Pg·clamp(1 + λ·(Dl − Sl)/(Dl + Sl + ε), 1 − δ, 1 + δ)",
|
||||
Terms =
|
||||
[
|
||||
T("Pg", "Prezzo globale", step.GlobalPrice, ExplainUnit.Price),
|
||||
T("Dl", "Domanda locale", step.LocalDemand, ExplainUnit.Units),
|
||||
T("Sl", "Offerta locale", step.LocalSupply, ExplainUnit.Units),
|
||||
T("λ", "Peso dello squilibrio", lp.Lambda, ExplainUnit.Number),
|
||||
T("ε", "Correzione per scorte nulle", lp.Epsilon, ExplainUnit.Number),
|
||||
T("δ", "Scarto massimo dal prezzo globale", lp.MaxDeviation, ExplainUnit.Percent),
|
||||
T("(Dl − Sl)/(Dl + Sl + ε)", "Squilibrio locale", step.Imbalance, ExplainUnit.Number),
|
||||
T("f", "Fattore locale", step.Factor, ExplainUnit.Factor),
|
||||
],
|
||||
Notes = notes,
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ tariffe
|
||||
|
||||
/// <summary>
|
||||
/// Tratta di una linea: dalla prima fermata a quella più lontana in linea d'aria (la distanza della
|
||||
/// tariffa è quella in linea d'aria tra le stazioni, come alla consegna). Null se la linea non ha due
|
||||
/// fermate distinte vive.
|
||||
/// </summary>
|
||||
public static (Station From, Station To, double Km)? Stretch(World w, Line line)
|
||||
{
|
||||
var net = w.Network;
|
||||
Station? from = null, to = null;
|
||||
double best = -1;
|
||||
foreach (var stop in line.Stops)
|
||||
{
|
||||
if (!stop.Station.IsValid || stop.Station.Value >= net.Stations.Count) continue;
|
||||
var s = net.Stations[stop.Station.Value];
|
||||
if (!net.IsAlive(s)) continue;
|
||||
if (from is null)
|
||||
{
|
||||
from = s;
|
||||
continue;
|
||||
}
|
||||
double d = Vec2.Distance(from.Position, s.Position);
|
||||
if (d > best)
|
||||
{
|
||||
best = d;
|
||||
to = s;
|
||||
}
|
||||
}
|
||||
if (from is null || to is null || best <= 0) return null;
|
||||
return (from, to, best / 1000);
|
||||
}
|
||||
|
||||
private static Line? LiveLine(World w, int id) =>
|
||||
id >= 0 && id < w.Lines.Count && w.Lines[id] is { Removed: false } l ? l : null;
|
||||
|
||||
/// <summary>Tempo atteso della tratta per il carico (giorni), 0 se nessun treno la collega.</summary>
|
||||
private static double ExpectedDays(World w, Line line, Station from, Station to, ulong cargo)
|
||||
{
|
||||
var reach = w.LineGraphs.For(w, line.Owner).From(from.Id, cargo);
|
||||
return reach.TryGetValue(to.Id.Value, out var conn) ? w.Calendar.TrainMinutesToDays(conn.Minutes) : 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tariffa merci per una unità sulla tratta della linea con <see cref="Tariffs.FreightTerms"/>: puntuale
|
||||
/// (tf = 1 alla consegna nel tempo atteso) e, per confronto, a due volte il tempo atteso.
|
||||
/// </summary>
|
||||
public static Explanation FreightTariff(World w, ExplainTarget target)
|
||||
{
|
||||
var line = LiveLine(w, target.A);
|
||||
int g = target.B;
|
||||
if (line is null || g < 0 || g >= w.Data.GoodCount || Stretch(w, line) is not { } stretch) return Missing(w, target, "Tariffa merci");
|
||||
var t = w.Data.Balance.Tariffs;
|
||||
var def = w.Data.Goods[g];
|
||||
double pg = w.Market.GlobalPrice[g];
|
||||
double expected = ExpectedDays(w, line, stretch.From, stretch.To, LineGraph.GoodCargo(g));
|
||||
double diff = w.Difficulty.TariffMultiplier;
|
||||
var terms = Tariffs.FreightTerms(1, stretch.Km, pg, def.BasePrice, expected, expected, t, diff);
|
||||
var late = Tariffs.FreightTerms(1, stretch.Km, pg, def.BasePrice, 2 * expected, expected, t, diff);
|
||||
var notes = new List<string> { "Tariffa di una unità consegnata nel tempo atteso; tf scende dopo la soglia di ritardo fino al minimo." };
|
||||
if (expected <= 0) notes.Add("Nessun treno della linea collega la tratta con questo bene: il tempo atteso non è noto e tf vale 1.");
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Tariffa merci",
|
||||
Name = $"{line.Name}: {stretch.From.Name} → {stretch.To.Name} · {def.NameIt}",
|
||||
Value = terms.Fare.Cents, Unit = ExplainUnit.Money,
|
||||
Formula = "tariffa = u × Tb × (a + b·Pg/Pb) × km^e × tf × d",
|
||||
Terms =
|
||||
[
|
||||
T("u", "Unità", 1, ExplainUnit.Units),
|
||||
T("Tb", "Tariffa base", t.FreightBaseRate, ExplainUnit.Price),
|
||||
T("a", "Quota fissa", t.FreightFixedWeight, ExplainUnit.Number),
|
||||
T("b", "Quota legata al prezzo", t.FreightPriceWeight, ExplainUnit.Number),
|
||||
T("Pg", "Prezzo globale", pg, ExplainUnit.Price),
|
||||
T("Pb", "Prezzo base", def.BasePrice, ExplainUnit.Price),
|
||||
T("a + b·Pg/Pb", "Fattore del prezzo", terms.PriceFactor, ExplainUnit.Factor),
|
||||
T("km", "Distanza in linea d'aria", stretch.Km, ExplainUnit.Km),
|
||||
T("e", "Esponente della distanza", t.FreightKmExponent, ExplainUnit.Number),
|
||||
T("km^e", "Fattore della distanza", terms.KmFactor, ExplainUnit.Factor),
|
||||
T("tf", "Puntualità", terms.Lateness, ExplainUnit.Factor),
|
||||
T("d", "Moltiplicatore della difficoltà", diff, ExplainUnit.Factor),
|
||||
T("giorni", "Tempo atteso", expected, ExplainUnit.Days),
|
||||
T("soglia", "Soglia di ritardo (volte il tempo atteso)", t.LateThreshold, ExplainUnit.Factor),
|
||||
T("tf min", "Puntualità minima", t.LateFactorMin, ExplainUnit.Factor),
|
||||
T("tf 2×", "Puntualità a due volte il tempo atteso", late.Lateness, ExplainUnit.Factor),
|
||||
T("tariffa 2×", "Tariffa a due volte il tempo atteso", late.Fare.Cents, ExplainUnit.Money),
|
||||
],
|
||||
Notes = notes,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tariffa passeggeri per un posto sulla tratta della linea con <see cref="Tariffs.PassengerTerms"/>, poi
|
||||
/// × comfort delle carrozze del primo treno della linea (come alla consegna: due arrotondamenti al centesimo).
|
||||
/// </summary>
|
||||
public static Explanation PassengerTariff(World w, ExplainTarget target)
|
||||
{
|
||||
var line = LiveLine(w, target.A);
|
||||
if (line is null || target.B is < 0 or > 1 || Stretch(w, line) is not { } stretch) return Missing(w, target, "Tariffa passeggeri");
|
||||
var cls = target.B == 1 ? PaxClass.Staff : PaxClass.Worker;
|
||||
var t = w.Data.Balance.Tariffs;
|
||||
double expected = ExpectedDays(w, line, stretch.From, stretch.To, LineGraph.PaxCargo(cls));
|
||||
double diff = w.Difficulty.TariffMultiplier;
|
||||
var train = w.Trains.Where(tr => !tr.Removed && tr.Line == line.Id).OrderBy(tr => tr.Id.Value).FirstOrDefault();
|
||||
double comfort = train is null ? 1.0 : Fleet.Comfort(w, train, cls);
|
||||
var terms = Tariffs.PassengerTerms(1, stretch.Km, cls, expected, expected, t, diff);
|
||||
var fare = terms.Fare * comfort;
|
||||
var late = Tariffs.PassengerTerms(1, stretch.Km, cls, 2 * expected, expected, t, diff).Fare * comfort;
|
||||
var notes = new List<string> { "Tariffa di un posto consegnato nel tempo atteso; tf scende dopo la soglia di ritardo fino al minimo." };
|
||||
if (train is null) notes.Add("Nessun treno sulla linea: il comfort delle carrozze vale 1.");
|
||||
if (expected <= 0) notes.Add("Nessun treno della linea collega la tratta per questa classe: il tempo atteso non è noto e tf vale 1.");
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true,
|
||||
Title = cls == PaxClass.Staff ? "Tariffa del personale" : "Tariffa dei lavoratori",
|
||||
Name = $"{line.Name}: {stretch.From.Name} → {stretch.To.Name}",
|
||||
Value = fare.Cents, Unit = ExplainUnit.Money,
|
||||
Formula = "tariffa = p × Tp × km^e × classe × tf × d × comfort",
|
||||
Terms =
|
||||
[
|
||||
T("p", "Posti", 1, ExplainUnit.Units),
|
||||
T("Tp", "Tariffa base per posto", t.PaxBaseFare, ExplainUnit.Price),
|
||||
T("km", "Distanza in linea d'aria", stretch.Km, ExplainUnit.Km),
|
||||
T("e", "Esponente della distanza", t.PaxKmExponent, ExplainUnit.Number),
|
||||
T("km^e", "Fattore della distanza", terms.KmFactor, ExplainUnit.Factor),
|
||||
T("classe", "Moltiplicatore della classe", terms.ClassFactor, ExplainUnit.Factor),
|
||||
T("tf", "Puntualità", terms.Lateness, ExplainUnit.Factor),
|
||||
T("d", "Moltiplicatore della difficoltà", diff, ExplainUnit.Factor),
|
||||
T("comfort", "Comfort delle carrozze", comfort, ExplainUnit.Factor),
|
||||
T("senza comfort", "Tariffa prima del comfort", terms.Fare.Cents, ExplainUnit.Money),
|
||||
T("giorni", "Tempo atteso", expected, ExplainUnit.Days),
|
||||
T("soglia", "Soglia di ritardo (volte il tempo atteso)", t.LateThreshold, ExplainUnit.Factor),
|
||||
T("tf min", "Puntualità minima", t.LateFactorMin, ExplainUnit.Factor),
|
||||
T("tariffa 2×", "Tariffa a due volte il tempo atteso", late.Cents, ExplainUnit.Money),
|
||||
],
|
||||
Notes = notes,
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ industrie e città
|
||||
|
||||
/// <summary>
|
||||
/// Efficienza dell'industria con i termini dell'ultima produzione (<see cref="Industry.LastEfficiency"/>):
|
||||
/// e = min(cL, cP) × pf × mc (0 se ferma) × cI × g × ev, lo stesso prodotto di IndustrySystem.
|
||||
/// </summary>
|
||||
public static Explanation IndustryEfficiency(World w, ExplainTarget target)
|
||||
{
|
||||
if (target.A < 0 || target.A >= w.Industries.Count) return Missing(w, target, "Efficienza");
|
||||
var ind = w.Industries[target.A];
|
||||
var terms = new List<ExplanationTerm>();
|
||||
var notes = new List<string>();
|
||||
double value = ind.Closed ? 0 : ind.Efficiency;
|
||||
if (ind.Closed) notes.Add("Industria chiusa.");
|
||||
else if (ind.LastEfficiency is not { } e) notes.Add("I termini arrivano con la prossima produzione giornaliera (dopo un caricamento non sono salvati).");
|
||||
else
|
||||
{
|
||||
terms.Add(T("cL", "Copertura dei lavoratori (media mobile)", e.CovWorkers, ExplainUnit.Percent));
|
||||
terms.Add(T("cP", "Copertura del personale (media mobile)", e.CovStaff, ExplainUnit.Percent));
|
||||
terms.Add(T("pf", "Fattore di profitto", e.ProfitFactor, ExplainUnit.Factor));
|
||||
terms.Add(T("mc", "Condizione degli impianti", e.ConditionMultiplier, ExplainUnit.Factor));
|
||||
terms.Add(T("lavoro", "Ritmo del lavoro", e.Labour, ExplainUnit.Factor));
|
||||
terms.Add(T("cI", "Copertura degli ingressi di oggi", e.CovInputToday, ExplainUnit.Percent));
|
||||
terms.Add(T("g", "Giacimento", e.Depletion, ExplainUnit.Factor));
|
||||
terms.Add(T("ev", "Eventi in corso", e.EventCapacity, ExplainUnit.Factor));
|
||||
terms.Add(T("margine", "Margine (media mobile)", ind.Margin, ExplainUnit.Percent));
|
||||
terms.Add(T("condizione", "Condizione degli impianti (0–100)", ind.Condition, ExplainUnit.Condition));
|
||||
if (e.Stopped) notes.Add("Industria ferma (guasto, incidente, revisione o ammodernamento): il ritmo del lavoro è zero.");
|
||||
if (ind.Level <= 0) notes.Add("Livello 0: l'industria è inattiva.");
|
||||
}
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Efficienza", Name = ind.Name,
|
||||
Value = value, Unit = ExplainUnit.Percent,
|
||||
Formula = "e = min(cL, cP) × pf × mc × cI × g × ev",
|
||||
Terms = terms, Notes = notes,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Punteggio di crescita del trimestre in corso con <see cref="IndustryMath.GrowthScore"/>.</summary>
|
||||
public static Explanation IndustryGrowth(World w, ExplainTarget target)
|
||||
{
|
||||
if (target.A < 0 || target.A >= w.Industries.Count || w.Industries[target.A].Closed) return Missing(w, target, "Punteggio di crescita");
|
||||
var ind = w.Industries[target.A];
|
||||
var g = w.Data.Balance.Growth;
|
||||
var parts = IndustryMath.GrowthScore(ind, g);
|
||||
var notes = new List<string>
|
||||
{
|
||||
"Sopra la soglia di crescita per i trimestri richiesti il livello sale; sotto la soglia di calo scende.",
|
||||
};
|
||||
bool served = ind.ServedWithin(w.Clock.Day, g.QuarterDays);
|
||||
if (!served) notes.Add("Non servita da un vettore nel trimestre: il livello non cambia.");
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Punteggio di crescita", Name = ind.Name,
|
||||
Value = parts.Score, Unit = ExplainUnit.Percent,
|
||||
Formula = "punteggio = ws·quota + wc·copertura + wr·redditività",
|
||||
Terms =
|
||||
[
|
||||
T("quota", "Quota trasportata", parts.Shipped, ExplainUnit.Percent),
|
||||
T("spedite", "Unità spedite nel trimestre", ind.QuarterShipped, ExplainUnit.Units),
|
||||
T("prodotte", "Unità prodotte nel trimestre", ind.QuarterProduced, ExplainUnit.Units),
|
||||
T("copertura", "Copertura media", parts.Coverage, ExplainUnit.Percent),
|
||||
T("giorni", "Giorni del trimestre", ind.QuarterDays, ExplainUnit.Days),
|
||||
T("redditività", "Redditività (margine + 1)/2", parts.Profit, ExplainUnit.Percent),
|
||||
T("margine", "Margine (media mobile)", ind.Margin, ExplainUnit.Percent),
|
||||
T("ws", "Peso della quota", g.WeightShipped, ExplainUnit.Number),
|
||||
T("wc", "Peso della copertura", g.WeightCoverage, ExplainUnit.Number),
|
||||
T("wr", "Peso della redditività", g.WeightProfit, ExplainUnit.Number),
|
||||
T("soglia su", "Soglia di crescita", g.UpgradeThreshold, ExplainUnit.Percent),
|
||||
T("soglia giù", "Soglia di calo", g.DowngradeThreshold, ExplainUnit.Percent),
|
||||
T("trimestri", "Trimestri sopra soglia", ind.QuartersAboveUpgrade, ExplainUnit.Units),
|
||||
T("richiesti", "Trimestri richiesti", g.UpgradeQuarters, ExplainUnit.Units),
|
||||
],
|
||||
Notes = notes,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Crescita del prossimo mese della città con lo stato di oggi (<see cref="TownSystem.GrowthOf"/>).</summary>
|
||||
public static Explanation TownGrowth(World w, ExplainTarget target)
|
||||
{
|
||||
if (target.A < 0 || target.A >= w.Towns.Count) return Missing(w, target, "Crescita della città");
|
||||
var town = w.Towns[target.A];
|
||||
var tb = w.Data.Balance.Town;
|
||||
var g = TownSystem.GrowthOf(town, tb);
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Crescita della città", Name = town.Name,
|
||||
Value = g.Growth, Unit = ExplainUnit.Percent,
|
||||
Formula = "g = g₀ + ws·(s − s₀) + wo·(o − o₀), limitata a ±gmax",
|
||||
Terms =
|
||||
[
|
||||
T("g₀", "Crescita di base", tb.BaseGrowth, ExplainUnit.Percent),
|
||||
T("s", "Soddisfazione", g.Satisfaction, ExplainUnit.Percent),
|
||||
T("s₀", "Soddisfazione neutra", tb.SatisfactionPivot, ExplainUnit.Percent),
|
||||
T("ws", "Peso della soddisfazione", tb.SatisfactionWeight, ExplainUnit.Number),
|
||||
T("o", "Occupati per abitante", g.Employment, ExplainUnit.Percent),
|
||||
T("o₀", "Occupazione neutra", tb.EmploymentPivot, ExplainUnit.Percent),
|
||||
T("wo", "Peso dell'occupazione", tb.EmploymentWeight, ExplainUnit.Number),
|
||||
T("g grezza", "Crescita prima del limite", g.RawGrowth, ExplainUnit.Percent),
|
||||
T("gmax", "Crescita massima al mese", tb.MaxMonthlyGrowth, ExplainUnit.Percent),
|
||||
T("abitanti", "Abitanti", town.Population, ExplainUnit.Units),
|
||||
T("dopo", "Abitanti dopo il mese", g.Population, ExplainUnit.Units),
|
||||
T("ultimo mese", "Crescita dell'ultimo mese", town.LastGrowth, ExplainUnit.Percent),
|
||||
],
|
||||
Notes = ["Stima con lo stato di oggi: la crescita si applica all'inizio del mese."],
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ flotta
|
||||
|
||||
/// <summary>
|
||||
/// Condizione del treno (il componente più debole, <see cref="Fleet.TrainCondition"/>), rischio di guasto
|
||||
/// del giorno (<see cref="Fleet.DailyHazard"/>, lo stesso del controllo dei guasti) con i giorni attesi al
|
||||
/// guasto, e stima del pianificatore (<see cref="Fleet.Dues"/>) se il componente si consuma.
|
||||
/// </summary>
|
||||
public static Explanation TrainCondition(World w, ExplainTarget target, CompanyId company)
|
||||
{
|
||||
if (target.A < 0 || target.A >= w.Trains.Count || w.Trains[target.A] is not { Removed: false } t || t.Owner != company || t.Vehicles.Count == 0)
|
||||
return Missing(w, target, "Condizione del treno");
|
||||
var m = w.Data.Maintenance;
|
||||
double condition = Fleet.TrainCondition(w, t);
|
||||
var (weakest, comp, low) = Fleet.Weakest(w, t);
|
||||
var (hazard, hv, hc) = Fleet.DailyHazard(w, t, w.Clock.Day);
|
||||
var terms = new List<ExplanationTerm>();
|
||||
var notes = new List<string>();
|
||||
if (weakest is not null && comp >= 0)
|
||||
{
|
||||
var comps = Fleet.ComponentsOf(w.Data, weakest.Def);
|
||||
terms.Add(T("c", "Componente più debole", low, ExplainUnit.Condition, comp < comps.Count ? comps[comp].Id : ""));
|
||||
terms.Add(T("veicolo", "Veicolo", weakest.Id.Value, ExplainUnit.Text, weakest.Def.NameIt));
|
||||
double rate = comp < weakest.WearEma.Length ? weakest.WearEma[comp] : 0;
|
||||
terms.Add(T("usura", "Usura al giorno (media mobile)", rate, ExplainUnit.Condition));
|
||||
}
|
||||
if (hv is not null && hc >= 0)
|
||||
{
|
||||
var f = m.Failure;
|
||||
double ch = hv.Components[hc];
|
||||
terms.Add(T("c rischio", "Componente più a rischio", ch, ExplainUnit.Condition, hc < Fleet.ComponentsOf(w.Data, hv.Def).Count ? Fleet.ComponentsOf(w.Data, hv.Def)[hc].Id : ""));
|
||||
terms.Add(T("h₀", "Rischio di base al giorno", f.H0, ExplainUnit.Percent));
|
||||
terms.Add(T("c₀", "Condizione di soglia", f.Pivot, ExplainUnit.Condition));
|
||||
terms.Add(T("k", "Pendenza del rischio", f.Slope, ExplainUnit.Number));
|
||||
terms.Add(T("σ", "Scala della condizione", f.Scale, ExplainUnit.Number));
|
||||
terms.Add(T("div", "Riduzione sopra soglia", f.HealthyDivisor, ExplainUnit.Number));
|
||||
bool inspected = w.Clock.Day < hv.HazardReducedUntilDay;
|
||||
terms.Add(T("ispezione", "Fattore dopo un'ispezione", inspected ? m.Inspection.HazardFactor : 1, ExplainUnit.Factor));
|
||||
terms.Add(T("h", "Rischio di guasto al giorno", hazard, ExplainUnit.Percent));
|
||||
if (hazard > 0) terms.Add(T("1/h", "Giorni attesi al prossimo guasto", 1 / hazard, ExplainUnit.Days));
|
||||
}
|
||||
var dues = Fleet.Dues(w, t);
|
||||
if (dues.Condition < double.MaxValue)
|
||||
{
|
||||
terms.Add(T("obiettivo", "Condizione obiettivo del pianificatore", m.Planner.TargetCondition, ExplainUnit.Condition));
|
||||
terms.Add(T("margine", "Margine del pianificatore", m.Planner.MarginDays, ExplainUnit.Days));
|
||||
terms.Add(T("stima", "Giorni all'intervento sulla condizione", dues.Condition, ExplainUnit.Days));
|
||||
}
|
||||
else notes.Add("Nessuna stima del pianificatore: i componenti non si sono ancora consumati.");
|
||||
notes.Add("Il guasto è estratto ogni giorno con il rischio h: 1/h è il numero medio di giorni prima del prossimo.");
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Condizione del treno", Name = t.Name,
|
||||
Value = condition, Unit = ExplainUnit.Condition,
|
||||
Formula = "c = min(componenti); h = h₀·exp(k·(c₀ − c)/σ) sotto c₀, altrimenti h₀/div; stima = (c − obiettivo)/usura − margine",
|
||||
Terms = terms, Notes = notes,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Valore di libro (prezzo × residuo, <see cref="Obsolescence.BookValueCents"/>) e rivendita
|
||||
/// (<see cref="Obsolescence.ResaleValue"/>) di un veicolo della compagnia.
|
||||
/// </summary>
|
||||
public static Explanation VehicleValue(World w, ExplainTarget target, CompanyId company)
|
||||
{
|
||||
if (target.A < 0 || target.A >= w.Vehicles.Count || w.Vehicles[target.A] is not { Sold: false } v || v.Owner != company)
|
||||
return Missing(w, target, "Valore del veicolo");
|
||||
var o = w.Data.Obsolescence;
|
||||
double dpy = w.Calendar.DaysPerYear;
|
||||
double age = (w.Clock.Day - v.BoughtDay) / dpy;
|
||||
double residual = Obsolescence.Residual(w, v);
|
||||
long book = Obsolescence.BookValueCents(w, v);
|
||||
var resale = Obsolescence.ResaleValue(w, v);
|
||||
bool superseded = w.Clock.Day >= Obsolescence.SupersededDay(w.Calendar, v.Def);
|
||||
var terms = new List<ExplanationTerm>
|
||||
{
|
||||
T("prezzo", "Prezzo di listino", v.Def.Price, ExplainUnit.Money),
|
||||
T("età", "Età", age, ExplainUnit.Years),
|
||||
T("vita", "Vita utile", v.Def.LifeYears, ExplainUnit.Years),
|
||||
};
|
||||
var notes = new List<string>();
|
||||
string formula;
|
||||
if (superseded)
|
||||
{
|
||||
terms.Add(T("dal", "Superato dal", Obsolescence.SupersededYear(v.Def) ?? 0, ExplainUnit.Text, (Obsolescence.SupersededYear(v.Def) ?? 0).ToString(System.Globalization.CultureInfo.InvariantCulture)));
|
||||
terms.Add(T("anni superato", "Anni da superato", Obsolescence.YearsSuperseded(w, v), ExplainUnit.Years));
|
||||
terms.Add(T("perdita", "Perdita immediata", o.ImmediateValueLoss, ExplainUnit.Percent));
|
||||
terms.Add(T("velocità", "Ammortamento più rapido", o.DepreciationSpeed, ExplainUnit.Factor));
|
||||
var next = Obsolescence.Recommended(v.Def, w.Clock.Year);
|
||||
if (next is not null) terms.Add(T("successore", "Successore consigliato", 0, ExplainUnit.Text, next.NameIt));
|
||||
formula = "r = max(rmin, (1 − perdita)·(1 − (età + (velocità − 1)·anni superato)/vita)); valore = prezzo·r; rivendita = prezzo·r·condizione";
|
||||
notes.Add("Modello superato: perde subito una quota del valore e si ammortizza più in fretta.");
|
||||
}
|
||||
else formula = "r = max(rmin, 1 − età/vita); valore = prezzo·r; rivendita = prezzo·r·condizione";
|
||||
terms.Add(T("rmin", "Valore minimo", w.Data.Balance.Finance.BookValueFloor, ExplainUnit.Percent));
|
||||
terms.Add(T("r", "Quota residua del valore", residual, ExplainUnit.Percent));
|
||||
terms.Add(T("condizione", "Condizione media dei componenti", Obsolescence.AverageCondition(v), ExplainUnit.Percent));
|
||||
terms.Add(T("rivendita", "Rivendita", resale.Cents, ExplainUnit.Money));
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Valore del veicolo", Name = v.Def.NameIt,
|
||||
Value = book, Unit = ExplainUnit.Money, Formula = formula, Terms = terms, Notes = notes,
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ compagnia
|
||||
|
||||
/// <summary>Rating con <see cref="FinanceOutlook.Explain"/>: le misure dell'ultimo calcolo, componenti e punteggio.</summary>
|
||||
public static Explanation Rating(World w, ExplainTarget target, Company c)
|
||||
{
|
||||
var r = FinanceOutlook.Explain(w, c);
|
||||
var terms = new List<ExplanationTerm>
|
||||
{
|
||||
T("margine", "Margine (utile operativo / ricavi, 12 mesi)", r.Margin, ExplainUnit.Percent),
|
||||
T("cm", "Componente del margine", r.MarginComponent, ExplainUnit.Number),
|
||||
T("leva", "Debiti / patrimonio netto", r.Leverage, ExplainUnit.Factor),
|
||||
T("cl", "Componente della leva", r.LeverageComponent, ExplainUnit.Number),
|
||||
T("pm", "Peso del margine", r.MarginWeight, ExplainUnit.Number),
|
||||
T("pl", "Peso della leva", r.LeverageWeight, ExplainUnit.Number),
|
||||
};
|
||||
var notes = new List<string>();
|
||||
if (r.Initial) notes.Add("Rating iniziale: le misure sono quelle di oggi, il primo calcolo è a inizio mese.");
|
||||
if (r.MarginNeutral) notes.Add("Margine neutro finché la finestra non ha abbastanza mesi con ricavi.");
|
||||
if (r.Bankrupt) notes.Add("Compagnia in bancarotta: il rating è D.");
|
||||
if (r.Next is { } next)
|
||||
{
|
||||
terms.Add(T("gradino", "Gradino sopra", 0, ExplainUnit.Text, next.ToString()));
|
||||
terms.Add(T("soglia", "Punteggio del gradino sopra", r.NextThreshold, ExplainUnit.Number));
|
||||
if (r.NextAlreadyMet) notes.Add("Il punteggio vale già il gradino sopra: il rating cambia al prossimo calcolo mensile.");
|
||||
else if (!r.Bankrupt)
|
||||
{
|
||||
if (r.MarginReachable) terms.Add(T("margine necessario", "Margine che basta, a leva invariata", r.MarginNeeded, ExplainUnit.Percent));
|
||||
if (r.LeverageReachable) terms.Add(T("leva massima", "Leva che basta, a margine invariato", r.LeverageMax, ExplainUnit.Factor));
|
||||
if (r.DebtToRepay.Cents > 0) terms.Add(T("rimborso", "Debito da rimborsare per la leva che basta", r.DebtToRepay.Cents, ExplainUnit.Money));
|
||||
}
|
||||
}
|
||||
else notes.Add("Rating più alto.");
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Rating", Name = c.Name,
|
||||
Value = r.Score, Unit = ExplainUnit.Number, ValueText = r.Rating.ToString(),
|
||||
Formula = "punteggio = pm·clamp(0,5 + margine, 0, 1) + pl·1/(1 + leva)",
|
||||
Terms = terms, Notes = notes,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Avanzamento verso il prossimo livello con <see cref="ClimbOutlook.Requirements"/>.</summary>
|
||||
public static Explanation TierProgress(World w, ExplainTarget target, Company c)
|
||||
{
|
||||
var tiers = w.Data.Tiers.Tiers;
|
||||
if (c.Tier >= tiers.Count)
|
||||
{
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Avanzamento del livello", Name = c.Name,
|
||||
Value = 1, Unit = ExplainUnit.Percent, Formula = "", Terms = [], Notes = ["Livello più alto."],
|
||||
};
|
||||
}
|
||||
var req = ClimbOutlook.Requirements(w, c, tiers[c.Tier]);
|
||||
var notes = new List<string>();
|
||||
if (!(req.NetWorthMet && req.TownsMet && req.RatingMet)) notes.Add("Finché un requisito manca l'avanzamento resta sotto il 100%.");
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Avanzamento del livello", Name = c.Name,
|
||||
Value = req.Progress, Unit = ExplainUnit.Percent,
|
||||
Formula = "avanzamento = (fP + fC + fR)/3; fP = min(1, patrimonio/soglia); fC = min(1, città/richieste); fR = 1 − gradini mancanti/n",
|
||||
Terms =
|
||||
[
|
||||
T("patrimonio", "Patrimonio netto", req.NetWorth.Cents, ExplainUnit.Money),
|
||||
T("soglia", "Patrimonio richiesto", req.NetWorthRequired.Cents, ExplainUnit.Money),
|
||||
T("fP", "Frazione del patrimonio", req.NetWorthFraction, ExplainUnit.Percent),
|
||||
T("città", "Città collegate", req.Towns, ExplainUnit.Units),
|
||||
T("richieste", "Città richieste", req.TownsRequired, ExplainUnit.Units),
|
||||
T("abitanti", "Abitanti minimi per città", req.TownPopulation, ExplainUnit.Units),
|
||||
T("fC", "Frazione delle città", req.TownsFraction, ExplainUnit.Percent),
|
||||
T("rating", "Rating", 0, ExplainUnit.Text, req.Rating.ToString()),
|
||||
T("rating richiesto", "Rating richiesto", 0, ExplainUnit.Text, req.RatingRequired.ToString()),
|
||||
T("n", "Gradini per lo zero", w.Data.Tiers.RatingProgressSteps, ExplainUnit.Number),
|
||||
T("fR", "Frazione del rating", req.RatingFraction, ExplainUnit.Percent),
|
||||
T("tetto", "Tetto con un requisito mancante", ClimbOutlook.ProgressCap, ExplainUnit.Percent),
|
||||
],
|
||||
Notes = notes,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cassa con i movimenti del mese in corso per sezione del conto economico (<see cref="FinanceOutlook.Columns"/>):
|
||||
/// cassa a inizio mese + ricavi + costi + investimenti e finanziamenti (con segno).
|
||||
/// </summary>
|
||||
public static Explanation Cash(World w, ExplainTarget target, Company c)
|
||||
{
|
||||
var month = FinanceOutlook.Columns(w, c)[0];
|
||||
long revenue = 0, costs = 0, capital = 0;
|
||||
for (int i = 0; i < month.Entries.Length; i++)
|
||||
{
|
||||
switch (LedgerEntries.Section((LedgerEntry)i))
|
||||
{
|
||||
case IncomeSection.Revenue: revenue += month.Entries[i]; break;
|
||||
case IncomeSection.Cost: costs += month.Entries[i]; break;
|
||||
default: capital += month.Entries[i]; break;
|
||||
}
|
||||
}
|
||||
var notes = new List<string> { "Le voci del mese sono nel pannello «Finanze»." };
|
||||
var terms = new List<ExplanationTerm>
|
||||
{
|
||||
T("inizio", "Cassa a inizio mese", c.Cash.Cents - month.CashFlow.Cents, ExplainUnit.Money),
|
||||
T("ricavi", "Ricavi del mese", revenue, ExplainUnit.Money),
|
||||
T("costi", "Costi del mese", costs, ExplainUnit.Money),
|
||||
T("capitale", "Investimenti e finanziamenti del mese", capital, ExplainUnit.Money),
|
||||
T("flusso", "Flusso di cassa del mese", month.CashFlow.Cents, ExplainUnit.Money),
|
||||
};
|
||||
if (c.Cash.Cents < 0)
|
||||
{
|
||||
terms.Add(T("giorni", "Giorni di cassa negativa", c.NegativeCashDays, ExplainUnit.Days));
|
||||
terms.Add(T("limite", "Giorni che portano alla bancarotta", w.Difficulty.BankruptcyDays, ExplainUnit.Days));
|
||||
notes.Add("Con la cassa negativa per troppi giorni di fila la compagnia fallisce.");
|
||||
}
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Cassa", Name = c.Name,
|
||||
Value = c.Cash.Cents, Unit = ExplainUnit.Money,
|
||||
Formula = "cassa = cassa a inizio mese + ricavi + costi + investimenti e finanziamenti",
|
||||
Terms = terms, Notes = notes,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,14 @@ public enum IndustryWork : byte { None = 0, Overhaul = 1, Upgrade = 2 }
|
||||
/// <summary>Fermo concluso o in corso, per lo storico del pannello del proprietario.</summary>
|
||||
public readonly record struct IndustryStopRecord(long Day, int Days, IndustryStop Kind);
|
||||
|
||||
/// <summary>
|
||||
/// Termini dell'efficienza dell'ultima produzione giornaliera (IndustrySystem), conservati per la spiegazione
|
||||
/// del valore (ADR 0024): e = min(lavoratori, personale) × pf × mc (0 se ferma) × copertura degli input di oggi
|
||||
/// × giacimento × eventi. Non si salvano: dopo un caricamento mancano fino alla produzione del giorno dopo.
|
||||
/// </summary>
|
||||
public readonly record struct EfficiencyTerms(long Day, double CovWorkers, double CovStaff, double ProfitFactor, double ConditionMultiplier,
|
||||
bool Stopped, double Labour, double CovInputToday, double Depletion, double EventCapacity, double Efficiency);
|
||||
|
||||
/// <summary>
|
||||
/// Industria: produce secondo la ricetta del suo tipo, con efficienza
|
||||
/// e = min(copertura input, lavoratori, personale) × fattore di profitto × condizione impianti.
|
||||
@@ -97,6 +105,9 @@ public sealed class Industry : IWorkplace
|
||||
/// <summary>Efficienza dell'ultimo giorno.</summary>
|
||||
public double Efficiency { get; set; }
|
||||
|
||||
/// <summary>Termini dell'ultima produzione (non salvati, fuori dall'hash; ADR 0024).</summary>
|
||||
public EfficiencyTerms? LastEfficiency { get; set; }
|
||||
|
||||
/// <summary>Lavoratori e personale presenti oggi (quota in sede + pendolari arrivati), frazionari.</summary>
|
||||
public double WorkersPresent { get; set; }
|
||||
public double StaffPresent { get; set; }
|
||||
|
||||
@@ -59,14 +59,37 @@ public sealed class Market
|
||||
public static double WorldFactor(MarketBalance m, double volatility, double yearsElapsed, double shock) =>
|
||||
m.World.Amplitude * volatility * DMath.Sin(DMath.TwoPi * yearsElapsed / m.World.PeriodYears) + shock;
|
||||
|
||||
/// <summary>
|
||||
/// Passo giornaliero del prezzo globale (guida 6.3, ADR 0004), senza stato: lo usa MarketSystem e lo
|
||||
/// rifà la spiegazione del prezzo (ADR 0024) con gli stessi ingressi. <paramref name="pg"/> è il prezzo
|
||||
/// di ieri, <paramref name="demand"/> e <paramref name="supply"/> le somme della finestra di 30 giorni,
|
||||
/// <paramref name="windowCount"/> i giorni presenti nella finestra.
|
||||
/// </summary>
|
||||
public static GlobalPriceStep NextPrice(MarketBalance m, double pb, double pg, double demand, double supply, int windowCount,
|
||||
double volatility, double years, double shock)
|
||||
{
|
||||
double pw = pb * Math.Max(m.World.PriceFloor, 1 + WorldFactor(m, volatility, years, shock));
|
||||
double v = Math.Max(m.World.BaselinePerDay * windowCount, m.World.VolumeShare * (demand + supply) / 2);
|
||||
double dTot = demand + v * DMath.Pow(pw / pg, m.World.Elasticity);
|
||||
double sTot = supply + v * DMath.Pow(pg / pw, m.World.Elasticity);
|
||||
double ratio = DMath.Clamp(dTot / Math.Max(1e-9, sTot), m.RatioMin, m.RatioMax);
|
||||
double target = DMath.Clamp(pg * (1 + m.K * (ratio - 1)), m.MinPriceFactor * pb, m.MaxPriceFactor * pb);
|
||||
double next = m.Alpha * target + (1 - m.Alpha) * pg;
|
||||
return new GlobalPriceStep(pg, pb, pw, demand, supply, v, dTot, sTot, ratio, target, next);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Prezzo locale al nodo: Pl = Pg·(1 + λ·(Dl − Sl)/(Dl + Sl + ε)), entro ±maxDeviation.
|
||||
/// </summary>
|
||||
public static double LocalPrice(double globalPrice, double localDemand, double localSupply, LocalPriceBalance p)
|
||||
public static double LocalPrice(double globalPrice, double localDemand, double localSupply, LocalPriceBalance p) =>
|
||||
LocalPriceTerms(globalPrice, localDemand, localSupply, p).Price;
|
||||
|
||||
/// <summary>Prezzo locale con i suoi termini: squilibrio (Dl − Sl)/(Dl + Sl + ε) e fattore limitato.</summary>
|
||||
public static LocalPriceStep LocalPriceTerms(double globalPrice, double localDemand, double localSupply, LocalPriceBalance p)
|
||||
{
|
||||
double imbalance = (localDemand - localSupply) / (localDemand + localSupply + p.Epsilon);
|
||||
double factor = Math.Clamp(1 + p.Lambda * imbalance, 1 - p.MaxDeviation, 1 + p.MaxDeviation);
|
||||
return globalPrice * factor;
|
||||
return new LocalPriceStep(globalPrice, localDemand, localSupply, imbalance, factor, globalPrice * factor);
|
||||
}
|
||||
|
||||
internal void Restore(RollingWindow[] demand, RollingWindow[] supply, RollingWindow[] history)
|
||||
@@ -77,6 +100,23 @@ public sealed class Market
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Termini di un passo del prezzo globale: prezzo di ieri, base, prezzo mondiale Pw = Pb·max(pavimento, 1 + W(t)),
|
||||
/// domanda e offerta della finestra, volume mondiale V, domanda e offerta con il resto del mondo, rapporto
|
||||
/// limitato, prezzo obiettivo Pg′ e prezzo nuovo α·Pg′ + (1 − α)·Pg.
|
||||
/// </summary>
|
||||
public readonly record struct GlobalPriceStep(double Previous, double BasePrice, double WorldPrice, double Demand, double Supply,
|
||||
double WorldVolume, double DemandTotal, double SupplyTotal, double Ratio, double Target, double Price);
|
||||
|
||||
/// <summary>Termini del prezzo locale: Pg, Dl, Sl, squilibrio, fattore limitato e prezzo.</summary>
|
||||
public readonly record struct LocalPriceStep(double GlobalPrice, double LocalDemand, double LocalSupply, double Imbalance, double Factor, double Price);
|
||||
|
||||
/// <summary>
|
||||
/// Termini di una tariffa: fattore del prezzo (merci; 1 per i passeggeri), fattore della distanza km^esponente,
|
||||
/// classe (passeggeri; 1 per le merci), puntualità tf, centesimi non arrotondati e tariffa arrotondata.
|
||||
/// </summary>
|
||||
public readonly record struct TariffTerms(double PriceFactor, double KmFactor, double ClassFactor, double Lateness, double Cents, Money Fare);
|
||||
|
||||
/// <summary>Tariffe del vettore (guida 6.3).</summary>
|
||||
public static class Tariffs
|
||||
{
|
||||
@@ -85,24 +125,36 @@ public static class Tariffs
|
||||
/// tf scende linearmente da 1 a 0,5 quando la consegna supera del 50 % il tempo atteso.
|
||||
/// </summary>
|
||||
public static Money Freight(int units, double km, double globalPrice, double basePrice, double actualDays, double expectedDays,
|
||||
TariffBalance t, double difficultyMultiplier) =>
|
||||
FreightTerms(units, km, globalPrice, basePrice, actualDays, expectedDays, t, difficultyMultiplier).Fare;
|
||||
|
||||
/// <summary>Tariffa merci con i suoi termini (la formula di <see cref="Freight"/>, una sola fonte).</summary>
|
||||
public static TariffTerms FreightTerms(int units, double km, double globalPrice, double basePrice, double actualDays, double expectedDays,
|
||||
TariffBalance t, double difficultyMultiplier)
|
||||
{
|
||||
if (units <= 0 || km <= 0) return Money.Zero;
|
||||
double priceFactor = t.FreightFixedWeight + t.FreightPriceWeight * globalPrice / basePrice;
|
||||
double cents = units * t.FreightBaseRate * priceFactor * DMath.Pow(km, t.FreightKmExponent)
|
||||
* LatenessFactor(actualDays, expectedDays, t) * difficultyMultiplier;
|
||||
return Money.FromCentsRounded(cents);
|
||||
double kmFactor = km > 0 ? DMath.Pow(km, t.FreightKmExponent) : 0;
|
||||
double tf = LatenessFactor(actualDays, expectedDays, t);
|
||||
if (units <= 0 || km <= 0) return new TariffTerms(priceFactor, kmFactor, 1, tf, 0, Money.Zero);
|
||||
double cents = units * t.FreightBaseRate * priceFactor * kmFactor * tf * difficultyMultiplier;
|
||||
return new TariffTerms(priceFactor, kmFactor, 1, tf, cents, Money.FromCentsRounded(cents));
|
||||
}
|
||||
|
||||
/// <summary>Passeggeri: posti × tariffa base × km^0,85 × classe × puntualità × difficoltà.</summary>
|
||||
public static Money Passenger(int pax, double km, PaxClass paxClass, double actualDays, double expectedDays,
|
||||
TariffBalance t, double difficultyMultiplier, double comfort = 1.0) =>
|
||||
PassengerTerms(pax, km, paxClass, actualDays, expectedDays, t, difficultyMultiplier, comfort).Fare;
|
||||
|
||||
/// <summary>Tariffa passeggeri con i suoi termini (la formula di <see cref="Passenger"/>, una sola fonte).</summary>
|
||||
public static TariffTerms PassengerTerms(int pax, double km, PaxClass paxClass, double actualDays, double expectedDays,
|
||||
TariffBalance t, double difficultyMultiplier, double comfort = 1.0)
|
||||
{
|
||||
if (pax <= 0 || km <= 0) return Money.Zero;
|
||||
double cls = t.ClassMultipliers[paxClass == PaxClass.Staff ? "staff" : "worker"];
|
||||
double cents = pax * t.PaxBaseFare * DMath.Pow(km, t.PaxKmExponent) * cls
|
||||
* LatenessFactor(actualDays, expectedDays, t) * difficultyMultiplier * comfort;
|
||||
return Money.FromCentsRounded(cents);
|
||||
double kmFactor = km > 0 ? DMath.Pow(km, t.PaxKmExponent) : 0;
|
||||
double tf = LatenessFactor(actualDays, expectedDays, t);
|
||||
if (pax <= 0 || km <= 0) return new TariffTerms(1, kmFactor, cls, tf, 0, Money.Zero);
|
||||
double cents = pax * t.PaxBaseFare * kmFactor * cls * tf * difficultyMultiplier * comfort;
|
||||
return new TariffTerms(1, kmFactor, cls, tf, cents, Money.FromCentsRounded(cents));
|
||||
}
|
||||
|
||||
/// <summary>Fattore di puntualità: 1 entro la soglia, poi cala fino al minimo.</summary>
|
||||
|
||||
@@ -47,6 +47,33 @@ public static class Fleet
|
||||
public static double Hazard(double condition, FailureParams f) =>
|
||||
condition < f.Pivot ? f.H0 * DMath.Exp(f.Slope * (f.Pivot - condition) / f.Scale) : f.H0 / f.HealthyDivisor;
|
||||
|
||||
/// <summary>
|
||||
/// Rischio giornaliero di guasto del treno nel giorno indicato: il più alto tra i componenti di tutti i
|
||||
/// veicoli (<see cref="Hazard"/>, ridotto dopo un'ispezione), con il veicolo e il componente che lo danno
|
||||
/// (il primo a parità). Lo usa il controllo dei guasti e la spiegazione della condizione (ADR 0024).
|
||||
/// </summary>
|
||||
public static (double Hazard, Vehicle? Vehicle, int Component) DailyHazard(World w, Train t, long day)
|
||||
{
|
||||
var m = w.Data.Maintenance;
|
||||
double best = -1;
|
||||
Vehicle? bv = null;
|
||||
int bc = -1;
|
||||
foreach (var id in t.Vehicles)
|
||||
{
|
||||
var v = w.Vehicles[id.Value];
|
||||
for (int j = 0; j < v.Components.Length; j++)
|
||||
{
|
||||
double h = Hazard(v.Components[j], m.Failure);
|
||||
if (day < v.HazardReducedUntilDay) h *= m.Inspection.HazardFactor;
|
||||
if (h <= best) continue;
|
||||
best = h;
|
||||
bv = v;
|
||||
bc = j;
|
||||
}
|
||||
}
|
||||
return (best, bv, bc);
|
||||
}
|
||||
|
||||
/// <summary>Fattore d'età: 1 fino alla vita utile, poi +0,5 ogni 5 anni, meno le riduzioni delle revisioni (minimo 1).</summary>
|
||||
public static double AgeFactor(World w, Vehicle v) => AgeFactor(w.Data.Maintenance.Wear, v, w.Clock.Day, w.Calendar.DaysPerYear);
|
||||
|
||||
|
||||
@@ -120,22 +120,7 @@ public sealed class FleetMaintenanceSystem : ISimSystem
|
||||
{
|
||||
var w = ctx.World;
|
||||
var m = w.Data.Maintenance;
|
||||
double best = -1;
|
||||
Vehicle? bv = null;
|
||||
int bc = -1;
|
||||
foreach (var id in t.Vehicles)
|
||||
{
|
||||
var v = w.Vehicles[id.Value];
|
||||
for (int j = 0; j < v.Components.Length; j++)
|
||||
{
|
||||
double h = Fleet.Hazard(v.Components[j], m.Failure);
|
||||
if (ctx.Day < v.HazardReducedUntilDay) h *= m.Inspection.HazardFactor;
|
||||
if (h <= best) continue;
|
||||
best = h;
|
||||
bv = v;
|
||||
bc = j;
|
||||
}
|
||||
}
|
||||
var (best, bv, bc) = Fleet.DailyHazard(w, t, ctx.Day);
|
||||
if (bv is null) return;
|
||||
var rng = w.Stream("fleet");
|
||||
if (rng.NextDouble() >= best) return;
|
||||
|
||||
@@ -112,6 +112,8 @@ public sealed class IndustrySystem : ISimSystem
|
||||
site.ReserveTonnes = Math.Max(0, site.ReserveTonnes - extracted);
|
||||
}
|
||||
ind.Efficiency = eLabor * covInToday * depletion * capacity;
|
||||
// termini di oggi per la spiegazione dell'efficienza (ADR 0024): non entrano nel salvataggio né nell'hash
|
||||
ind.LastEfficiency = new EfficiencyTerms(ctx.Day, ind.CovWorkers, ind.CovStaff, pf, mc, stopped, eLabor, covInToday, depletion, capacity, ind.Efficiency);
|
||||
|
||||
// salari giornalieri ai presenti
|
||||
double wages = (ind.WorkersPresent * ib.WagePerWorkerPerMonth + ind.StaffPresent * ib.WagePerStaffPerMonth) / dpm;
|
||||
|
||||
@@ -55,15 +55,9 @@ public sealed class MarketSystem : ISimSystem
|
||||
market.CapacityToday[g] = 0;
|
||||
continue;
|
||||
}
|
||||
double pw = pb * Math.Max(m.World.PriceFloor, 1 + Market.WorldFactor(m, volatility, years, market.Shock[g]));
|
||||
double d = market.Demand[g].Sum;
|
||||
double s = market.Supply[g].Sum;
|
||||
double v = Math.Max(m.World.BaselinePerDay * market.Demand[g].Count, m.World.VolumeShare * (d + s) / 2);
|
||||
double dTot = d + v * DMath.Pow(pw / pg, m.World.Elasticity);
|
||||
double sTot = s + v * DMath.Pow(pg / pw, m.World.Elasticity);
|
||||
double ratio = DMath.Clamp(dTot / Math.Max(1e-9, sTot), m.RatioMin, m.RatioMax);
|
||||
double target = DMath.Clamp(pg * (1 + m.K * (ratio - 1)), m.MinPriceFactor * pb, m.MaxPriceFactor * pb);
|
||||
pg = m.Alpha * target + (1 - m.Alpha) * pg;
|
||||
// una sola formula per il passo del prezzo: la rifà anche la spiegazione del prezzo (ADR 0024)
|
||||
pg = Market.NextPrice(m, pb, pg, market.Demand[g].Sum, market.Supply[g].Sum, market.Demand[g].Count,
|
||||
volatility, years, market.Shock[g]).Price;
|
||||
market.GlobalPrice[g] = pg;
|
||||
market.PriceHistory[g].Add(pg);
|
||||
|
||||
|
||||
@@ -5,6 +5,9 @@ using RailEnterprise.Core.Map;
|
||||
|
||||
namespace RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
/// <summary>Termini della crescita mensile di una città: servizi, soddisfazione, occupati per abitante, g grezza e limitata, popolazione nuova.</summary>
|
||||
public readonly record struct TownGrowthTerms(int Services, double Satisfaction, double Employment, double RawGrowth, double Growth, int Population);
|
||||
|
||||
/// <summary>
|
||||
/// Città: consumo giornaliero e soddisfazione per categoria, crescita mensile, espansione
|
||||
/// dell'abitato e migrazione annuale verso le città meglio servite (guida 6.3).
|
||||
@@ -70,22 +73,34 @@ public sealed class TownSystem : ISimSystem
|
||||
town.WorkDissatisfaction *= 1.0 - 1.0 / tb.WorkDissatisfactionDecayDays;
|
||||
}
|
||||
|
||||
private static void Grow(WorldContext ctx, Town town)
|
||||
/// <summary>
|
||||
/// Crescita mensile della città dallo stato attuale (guida 6.3): servizi, soddisfazione, occupati per
|
||||
/// abitante, g = base + ps·(soddisfazione − perno) + po·(occupati/popolazione − perno), limitata a ±max,
|
||||
/// e popolazione che ne risulta. La usa la crescita del mese e la spiegazione del valore (ADR 0024).
|
||||
/// </summary>
|
||||
public static TownGrowthTerms GrowthOf(Town town, TownBalance tb)
|
||||
{
|
||||
var tb = ctx.Data.Balance.Town;
|
||||
int services = town.Population / Math.Max(1, tb.BaseServicesPerPopulation);
|
||||
for (int c = 0; c < Town.CategoryCount; c++)
|
||||
{
|
||||
if (town.CategoryActive[c] && town.Satisfaction[c] >= tb.ServicesSatisfactionThreshold) services++;
|
||||
}
|
||||
town.Services = services;
|
||||
double sat = town.OverallSatisfaction;
|
||||
double employment = town.Population > 0 ? (double)(town.EmployedWorkers + town.EmployedStaff) / town.Population : 0;
|
||||
double g = tb.BaseGrowth + tb.SatisfactionWeight * (sat - tb.SatisfactionPivot) + tb.EmploymentWeight * (employment - tb.EmploymentPivot);
|
||||
g = Math.Clamp(g, -tb.MaxMonthlyGrowth, tb.MaxMonthlyGrowth);
|
||||
town.LastGrowth = g;
|
||||
double raw = tb.BaseGrowth + tb.SatisfactionWeight * (sat - tb.SatisfactionPivot) + tb.EmploymentWeight * (employment - tb.EmploymentPivot);
|
||||
double g = Math.Clamp(raw, -tb.MaxMonthlyGrowth, tb.MaxMonthlyGrowth);
|
||||
int population = Math.Clamp((int)Math.Round(town.Population * (1 + g)), 0, tb.MaxPopulation);
|
||||
return new TownGrowthTerms(services, sat, employment, raw, g, population);
|
||||
}
|
||||
|
||||
private static void Grow(WorldContext ctx, Town town)
|
||||
{
|
||||
var tb = ctx.Data.Balance.Town;
|
||||
var growth = GrowthOf(town, tb);
|
||||
town.Services = growth.Services;
|
||||
town.LastGrowth = growth.Growth;
|
||||
int before = town.Population;
|
||||
town.Population = Math.Clamp((int)Math.Round(town.Population * (1 + g)), 0, tb.MaxPopulation);
|
||||
town.Population = growth.Population;
|
||||
if (before < tb.PopulationMilestone && town.Population >= tb.PopulationMilestone)
|
||||
ctx.Emit(EventKind.Town, EventSeverity.Info, $"{town.Name} supera i {Money.GroupThousands((ulong)tb.PopulationMilestone)} abitanti", EntityKind.Town, town.Id.Value);
|
||||
}
|
||||
|
||||
@@ -27,7 +27,10 @@ public sealed class GameClock(Calendar calendar)
|
||||
public int Year => Calendar.StartYear + (int)(Day / Calendar.DaysPerYear);
|
||||
|
||||
/// <summary>Anni (frazionari) trascorsi dall'inizio: usato dal ciclo economico mondiale.</summary>
|
||||
public double YearsElapsed => (double)Tick / ((long)Calendar.TicksPerDay * Calendar.DaysPerYear);
|
||||
public double YearsElapsed => YearsAt(Tick);
|
||||
|
||||
/// <summary>Anni (frazionari) trascorsi al tick indicato: la stessa misura di <see cref="YearsElapsed"/>.</summary>
|
||||
public double YearsAt(long tick) => (double)tick / ((long)Calendar.TicksPerDay * Calendar.DaysPerYear);
|
||||
|
||||
/// <summary>Avanza di un tick.</summary>
|
||||
public void Advance() => Tick++;
|
||||
|
||||
@@ -59,6 +59,15 @@ public sealed class ClientWorld(GameData data)
|
||||
/// <summary>Quadro del rinnovo della flotta (F6, ADR 0020), su richiesta: lo usano i pannelli Treni e Officine.</summary>
|
||||
public FleetReport? Fleet { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Spiegazioni «perché» ricevute (F6, ADR 0024), per soggetto e argomenti: l'ultima di ciascun valore. Il
|
||||
/// tooltip la mostra e la richiede di nuovo quando è di un giorno passato.
|
||||
/// </summary>
|
||||
public Dictionary<(byte Subject, int Target, int Arg), ExplanationReport> Explanations { get; } = [];
|
||||
|
||||
/// <summary>Contatore delle spiegazioni ricevute (separato dai dettagli: non ricostruisce i pannelli).</summary>
|
||||
public int ExplanationVersion { 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; }
|
||||
|
||||
@@ -161,6 +170,10 @@ public sealed class ClientWorld(GameData data)
|
||||
Fleet = m;
|
||||
DetailVersion++;
|
||||
return true;
|
||||
case ExplanationReport m:
|
||||
Explanations[m.Key] = m;
|
||||
ExplanationVersion++;
|
||||
return true;
|
||||
case SaveList m:
|
||||
Saves = m;
|
||||
DetailVersion++;
|
||||
@@ -188,6 +201,7 @@ public sealed class ClientWorld(GameData data)
|
||||
Climb = null;
|
||||
Finance = null;
|
||||
Fleet = null;
|
||||
Explanations.Clear();
|
||||
Alerts.Clear();
|
||||
Summary = m.Summary;
|
||||
Server = m.Server;
|
||||
|
||||
@@ -49,6 +49,8 @@ public enum MessageId : ushort
|
||||
FinanceReport = 135,
|
||||
/// <summary>Quadro del rinnovo della flotta: ere, veicoli superati, successori, valori (F6).</summary>
|
||||
FleetReport = 136,
|
||||
/// <summary>Spiegazione «perché» di un valore: formula, termini con i valori di oggi, note (F6, ADR 0024).</summary>
|
||||
ExplanationReport = 137,
|
||||
}
|
||||
|
||||
/// <summary>Messaggio del protocollo: si serializza a mano, campo per campo.</summary>
|
||||
|
||||
@@ -245,26 +245,52 @@ public enum DetailKind : byte
|
||||
Finance = 9,
|
||||
/// <summary>Quadro del rinnovo della flotta (risposta FleetReport, F6, ADR 0020; Id ignorato).</summary>
|
||||
Fleet = 10,
|
||||
/// <summary>
|
||||
/// Spiegazione «perché» di un valore (risposta ExplanationReport, F6, ADR 0024): Target è il primo argomento,
|
||||
/// soggetto e secondo argomento viaggiano nel blocco 1 della richiesta.
|
||||
/// </summary>
|
||||
Explain = 11,
|
||||
}
|
||||
|
||||
/// <summary>Chiede al server un dettaglio che non viaggia con le entità (aggiunto in F4).</summary>
|
||||
/// <summary>
|
||||
/// Chiede al server un dettaglio che non viaggia con le entità (aggiunto in F4). Blocco 1 (F6, ADR 0024):
|
||||
/// soggetto della spiegazione (ExplainSubject del Core) e secondo argomento, solo per <see cref="DetailKind.Explain"/>.
|
||||
/// </summary>
|
||||
public sealed class RequestDetail : IMessage
|
||||
{
|
||||
public MessageId Id => MessageId.RequestDetail;
|
||||
public DetailKind Kind { get; init; }
|
||||
public int Target { get; init; }
|
||||
/// <summary>Soggetto della spiegazione (0 = nessuno: niente blocco 1).</summary>
|
||||
public byte Subject { get; init; }
|
||||
/// <summary>Secondo argomento della spiegazione (−1 se non serve).</summary>
|
||||
public int Arg { get; init; } = -1;
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.U8((byte)Kind);
|
||||
w.I32(Target);
|
||||
w.Flags(0);
|
||||
bool block1 = Subject != 0;
|
||||
w.Flags(block1 ? (byte)1 : (byte)0);
|
||||
if (block1)
|
||||
{
|
||||
w.U8(Subject);
|
||||
w.I32(Arg);
|
||||
}
|
||||
}
|
||||
|
||||
public static RequestDetail Read(ref SpanReader r)
|
||||
{
|
||||
var m = new RequestDetail { Kind = (DetailKind)r.U8(), Target = r.I32() };
|
||||
r.Flags();
|
||||
return m;
|
||||
var kind = (DetailKind)r.U8();
|
||||
int target = r.I32();
|
||||
byte flags = r.Flags();
|
||||
byte subject = 0;
|
||||
int arg = -1;
|
||||
if ((flags & 1) != 0)
|
||||
{
|
||||
subject = r.U8();
|
||||
arg = r.I32();
|
||||
}
|
||||
return new RequestDetail { Kind = kind, Target = target, Subject = subject, Arg = arg };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
namespace RailEnterprise.Protocol.Messages;
|
||||
|
||||
// Messaggi della fase F6: tooltip «perché» (ADR 0024). La spiegazione di un valore arriva su richiesta
|
||||
// (RequestDetail con DetailKind.Explain, bersaglio nel blocco 1 della richiesta) ed è calcolata dal server
|
||||
// con Explanations del Core: il client la mostra com'è, senza rifare formule né valori.
|
||||
|
||||
/// <summary>
|
||||
/// Termine di una spiegazione: simbolo nella formula, etichetta (testo italiano fisso, chiave di traduzione),
|
||||
/// valore, unità (ExplainUnit del Core: 0 numero, 1 importo in centesimi, 2 prezzo in centesimi, 3 percentuale,
|
||||
/// 4 fattore, 5 km, 6 giorni, 7 unità, 8 condizione 0–100, 9 anni, 10 testo) e testo per i valori testuali.
|
||||
/// </summary>
|
||||
public sealed class ExplanationTermInfo
|
||||
{
|
||||
public string Symbol { get; init; } = "";
|
||||
public string Label { get; init; } = "";
|
||||
public double Value { get; init; }
|
||||
public byte Unit { get; init; }
|
||||
public string Text { get; init; } = "";
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.String(Symbol); w.String(Label); w.F64(Value); w.U8(Unit); w.String(Text);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static ExplanationTermInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new ExplanationTermInfo { Symbol = r.String(), Label = r.String(), Value = r.F64(), Unit = r.U8(), Text = r.String() };
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Spiegazione di un valore per la compagnia della sessione (F6, ADR 0024): bersaglio (soggetto e due
|
||||
/// argomenti, come nella richiesta), giorno, disponibilità, titolo e nome dell'oggetto, valore con unità e
|
||||
/// testo, formula, termini e note. Il valore è lo stesso numero del motore.
|
||||
/// </summary>
|
||||
public sealed class ExplanationReport : IMessage
|
||||
{
|
||||
public MessageId Id => MessageId.ExplanationReport;
|
||||
public long Day { get; init; }
|
||||
public byte Subject { get; init; }
|
||||
public int Target { get; init; } = -1;
|
||||
public int Arg { get; init; } = -1;
|
||||
public bool Available { get; init; }
|
||||
public string Title { get; init; } = "";
|
||||
public string Name { get; init; } = "";
|
||||
public double Value { get; init; }
|
||||
public byte Unit { get; init; }
|
||||
public string ValueText { get; init; } = "";
|
||||
public string Formula { get; init; } = "";
|
||||
public List<ExplanationTermInfo> Terms { get; init; } = [];
|
||||
public List<string> Notes { get; init; } = [];
|
||||
|
||||
/// <summary>Chiave della cache del client: soggetto e argomenti.</summary>
|
||||
public (byte Subject, int Target, int Arg) Key => (Subject, Target, Arg);
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I64(Day); w.U8(Subject); w.I32(Target); w.I32(Arg); w.Bool(Available);
|
||||
w.String(Title); w.String(Name); w.F64(Value); w.U8(Unit); w.String(ValueText); w.String(Formula);
|
||||
w.Count(Terms.Count);
|
||||
foreach (var t in Terms) t.Write(ref w);
|
||||
w.Count(Notes.Count);
|
||||
foreach (var n in Notes) w.String(n);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static ExplanationReport Read(ref SpanReader r)
|
||||
{
|
||||
long day = r.I64();
|
||||
byte subject = r.U8();
|
||||
int target = r.I32(), arg = r.I32();
|
||||
bool available = r.Bool();
|
||||
string title = r.String(), name = r.String();
|
||||
double value = r.F64();
|
||||
byte unit = r.U8();
|
||||
string valueText = r.String(), formula = r.String();
|
||||
var terms = new List<ExplanationTermInfo>();
|
||||
for (int n = r.Count(), i = 0; i < n; i++) terms.Add(ExplanationTermInfo.Read(ref r));
|
||||
var notes = new List<string>();
|
||||
for (int n = r.Count(), i = 0; i < n; i++) notes.Add(r.String());
|
||||
var m = new ExplanationReport
|
||||
{
|
||||
Day = day, Subject = subject, Target = target, Arg = arg, Available = available, Title = title, Name = name,
|
||||
Value = value, Unit = unit, ValueText = valueText, Formula = formula, Terms = terms, Notes = notes,
|
||||
};
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,7 @@ public static class MessageCodec
|
||||
MessageId.ClimbReport => ClimbReport.Read(ref r),
|
||||
MessageId.FinanceReport => FinanceReport.Read(ref r),
|
||||
MessageId.FleetReport => FleetReport.Read(ref r),
|
||||
MessageId.ExplanationReport => ExplanationReport.Read(ref r),
|
||||
MessageId.MarketTape => MarketTape.Read(ref r),
|
||||
MessageId.CommandResult => CommandResultMessage.Read(ref r),
|
||||
MessageId.Notification => Notification.Read(ref r),
|
||||
|
||||
@@ -692,6 +692,10 @@ public sealed class GameHost : IDisposable
|
||||
case DetailKind.Fleet:
|
||||
if (s.Company.IsValid && s.Company.Value < w.Companies.Count) s.Send(Projection.FleetRenewal(w, s.Company));
|
||||
break;
|
||||
case DetailKind.Explain:
|
||||
// risponde sempre, anche per un bersaglio che non c'è (Available = false): il tooltip smette di aspettare
|
||||
s.Send(Projection.Explanation(w, s.Company, m.Subject, m.Target, m.Arg));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -690,6 +690,19 @@ public static class Projection
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Spiegazione «perché» di un valore per la compagnia della sessione (Explanations, ADR 0024).</summary>
|
||||
public static ExplanationReport Explanation(World w, CompanyId company, byte subject, int target, int arg)
|
||||
{
|
||||
var e = Explanations.Build(w, company, new ExplainTarget((ExplainSubject)subject, target, arg));
|
||||
return new ExplanationReport
|
||||
{
|
||||
Day = e.Day, Subject = subject, Target = target, Arg = arg, Available = e.Available, Title = e.Title, Name = e.Name,
|
||||
Value = e.Value, Unit = (byte)e.Unit, ValueText = e.ValueText, Formula = e.Formula,
|
||||
Terms = e.Terms.Select(t => new ExplanationTermInfo { Symbol = t.Symbol, Label = t.Label, Value = t.Value, Unit = (byte)t.Unit, Text = t.Text }).ToList(),
|
||||
Notes = e.Notes,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Evento del mondo in corso → record del protocollo (ADR 0017).</summary>
|
||||
public static WorldEventInfo WorldEvent(ActiveWorldEvent e) => new()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user