F6: livelli e sblocchi visibili, pannello La tua scalata

I livelli esistevano dalla F5 ma il giocatore li vedeva solo come distintivo
e come rifiuti con nomi scritti a mano. Ora il motore espone un quadro della
scalata e il client lo mostra come l'immagine di riferimento 08.

- ClimbOutlook (Core, sola lettura): livelli con gli sblocchi letti dai dati,
  giorno in cui sono stati raggiunti, requisiti del prossimo livello con
  valore, soglia, frazione e avanzamento (media delle tre frazioni, ora
  anche nel Mercato globale), stato patrimoniale, conto economico, prestiti,
  storico del patrimonio dalla Cronaca.
- Stato patrimoniale con una sola fonte: FinanceSystem.BookValues scompone il
  valore contabile per voce e AssetBookValue ne e' la somma, cosi' il pannello
  somma al centesimo al patrimonio netto del motore. Le industrie possedute
  entrano nel patrimonio (impianti piu' cassa, senza avviamento): prima
  comprarle bruciava patrimonio.
- Notizia di promozione con gli sblocchi ottenuti; rifiuti dei comandi
  bloccati con il livello che serve e il suo nome dai dati (compravendita,
  industrie, quotazione, scalate, concessioni, fido).
- Salvataggio versione 6 (BalanceSheetSerializer) con voci e giorni dei
  livelli nell'hash; le versioni 1-5 si migrano con lo stesso patrimonio.
- Protocollo: DetailKind.Climb (8) e ClimbReport (134), su richiesta.
- Client: pannello ClimbPanel a tutto schermo, pulsante Scalata, livello e
  avanzamento nella barra superiore, schermata nel pilota automatico.
- Test: Economy/ClimbTests.cs e quadro via WebSocket (170 test verdi).

Decisioni in docs/adr/0018-scalata-e-livelli.md.

Refs #38.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-08 12:12:44 +01:00
1 parent a61bf1dc27
commit d473e21708
37 files changed
+2060 -70

No files matched your search

@@ -191,6 +191,10 @@ public static class DataValidator
}
RequireKeys("construction.json", "crews.metersPerDay", c.Crews.MetersPerDay.Keys, WorkKeys, errors);
if (c.Crews.CrewsByTier.Length != 5) Err("construction.json", "crews.crewsByTier deve avere 5 valori");
// le squadre per livello stanno in due file: il cantiere usa construction.json, il pannello della scalata
// le mostra tra gli sblocchi; devono coincidere (ADR 0018)
else if (!d.Tiers.Tiers.Select(t => t.Unlocks.Crews).SequenceEqual(c.Crews.CrewsByTier))
Err("tiers.json", "unlocks.crews deve coincidere con crews.crewsByTier di construction.json");
RequireKeys("construction.json", "costs.depotBySize", c.Costs.DepotBySize.Keys, SizeKeys, errors);
foreach (string k in c.Costs.TerrainModifiers.Keys)
{
@@ -0,0 +1,276 @@
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Core.Simulation.Systems;
namespace RailEnterprise.Core.Economy;
/// <summary>
/// Requisiti di un livello per una compagnia: per ciascuno il valore attuale, la soglia, se è
/// soddisfatto e la frazione raggiunta (0–1), più l'avanzamento complessivo (media delle tre frazioni).
/// </summary>
public sealed class RequirementProgress
{
public required int Level { get; init; }
public required Money NetWorth { get; init; }
public required Money NetWorthRequired { get; init; }
public required double NetWorthFraction { get; init; }
public required bool NetWorthMet { get; init; }
public required int Towns { get; init; }
public required int TownsRequired { get; init; }
public required int TownPopulation { get; init; }
public required double TownsFraction { get; init; }
public required bool TownsMet { get; init; }
public required CreditRating Rating { get; init; }
public required CreditRating RatingRequired { get; init; }
public required double RatingFraction { get; init; }
public required bool RatingMet { get; init; }
/// <summary>Media delle frazioni dei tre requisiti: 1 solo quando sono tutti soddisfatti.</summary>
public required double Progress { get; init; }
public bool AllMet => NetWorthMet && TownsMet && RatingMet;
}
/// <summary>Un livello di tiers.json visto dalla compagnia: requisiti, se e quando è stato raggiunto, sblocchi.</summary>
public sealed class TierOutlook
{
public required int Level { get; init; }
public required string NameIt { get; init; }
public required string NameEn { get; init; }
public required TierRequirements Requirements { get; init; }
public required bool Reached { get; init; }
/// <summary>Giorno in cui è stato raggiunto (fondazione per il livello 1; −1 se non raggiunto o sconosciuto).</summary>
public required long ReachedDay { get; init; }
/// <summary>Sblocchi che il livello aggiunge al precedente (<see cref="Tiers.NewUnlocks"/>).</summary>
public required List<TierUnlock> Unlocks { get; init; }
}
/// <summary>Voce degli attivi non monetari dello stato patrimoniale.</summary>
public readonly record struct AssetLine(AssetCategory Category, Money Value);
/// <summary>
/// Stato patrimoniale della compagnia: attivi per voce (dal valore contabile del motore),
/// partecipazioni, cassa; debiti (prestiti e scoperto di cassa). Il patrimonio netto è quello del
/// motore (<see cref="Company.NetWorth"/>): Totale attivo − Totale debiti.
/// </summary>
public sealed class BalanceSheet
{
public required List<AssetLine> Assets { get; init; }
/// <summary>Azioni di altre compagnie al prezzo di mercato.</summary>
public required Money Portfolio { get; init; }
/// <summary>Cassa positiva (lo scoperto va tra i debiti).</summary>
public required Money Cash { get; init; }
public required Money TotalAssets { get; init; }
public required Money Loans { get; init; }
/// <summary>Tasso medio dei prestiti pesato sul residuo (0 senza prestiti).</summary>
public required double LoansRate { get; init; }
/// <summary>Scoperto di cassa (cassa negativa), tra gli altri debiti.</summary>
public required Money Overdraft { get; init; }
public required Money TotalLiabilities { get; init; }
public required Money NetWorth { get; init; }
}
/// <summary>Righe del conto economico del pannello: raggruppano le voci del registro.</summary>
public enum IncomeLineKind : byte
{
/// <summary>Tariffe passeggeri e noli merci.</summary>
Fares = 0,
/// <summary>Commercio in proprio, contratti, industrie possedute, controllate.</summary>
OtherIncome = 1,
/// <summary>Costi d'esercizio, salari, penali.</summary>
OperatingCosts = 2,
/// <summary>Manutenzione dei binari e della flotta.</summary>
Maintenance = 3,
Interest = 4,
}
public readonly record struct IncomeLine(IncomeLineKind Kind, Money Value);
/// <summary>Conto economico di un anno (le righe sommano esattamente all'utile operativo del motore).</summary>
public sealed class IncomeStatement
{
public required int Year { get; init; }
/// <summary>Anno in corso (fino a oggi) invece dell'ultimo anno chiuso.</summary>
public required bool Partial { get; init; }
public required List<IncomeLine> Lines { get; init; }
public required Money Profit { get; init; }
}
public readonly record struct LoanOutlook(LoanId Id, Money Remaining, double AnnualRate, int MonthsLeft);
/// <summary>Patrimonio netto a un giorno della partita.</summary>
public readonly record struct NetWorthPoint(long Day, Money Value);
public sealed class ClimbOutlookReport
{
public required long Day { get; init; }
public required CompanyId Company { get; init; }
public required long FoundedDay { get; init; }
/// <summary>Capitale iniziale della difficoltà (quello del giocatore).</summary>
public required Money InitialCapital { get; init; }
public required int Tier { get; init; }
/// <summary>Livello successivo (0 all'ultimo livello).</summary>
public required int NextTier { get; init; }
public required List<TierOutlook> Tiers { get; init; }
/// <summary>Requisiti del livello successivo (null all'ultimo livello).</summary>
public required RequirementProgress? Next { get; init; }
public required BalanceSheet Balance { get; init; }
public required IncomeStatement Income { get; init; }
public required List<LoanOutlook> Loans { get; init; }
public required Money MaxLoan { get; init; }
public required Money LoanAvailable { get; init; }
public required double NewLoanRate { get; init; }
/// <summary>In amministrazione controllata i prestiti non si possono chiedere.</summary>
public required bool LoansAllowed { get; init; }
/// <summary>Patrimonio netto: fondazione, fine di ogni anno dello storico, oggi.</summary>
public required List<NetWorthPoint> History { get; init; }
}
/// <summary>
/// Quadro della scalata per il pannello «La tua scalata» (ADR 0018): pura funzione del mondo, come
/// <see cref="MarketOutlook"/>. Livelli e sblocchi da tiers.json, requisiti del prossimo livello con
/// l'avanzamento, stato patrimoniale dalle voci del valore contabile del motore, conto economico
/// dell'ultimo anno, prestiti e storico del patrimonio netto (lo storico annuale della Cronaca).
/// </summary>
public static class ClimbOutlook
{
public static ClimbOutlookReport Build(World w, CompanyId company)
{
var c = w.Company(company);
var tiers = w.Data.Tiers.Tiers;
var list = new List<TierOutlook>(tiers.Count);
foreach (var t in tiers)
{
list.Add(new TierOutlook
{
Level = t.Level, NameIt = t.NameIt, NameEn = t.NameEn, Requirements = t.Requirements,
Reached = c.Tier >= t.Level,
ReachedDay = t.Level <= 1 ? c.FoundedDay : c.Tier >= t.Level ? c.TierReachedDay[Math.Min(t.Level, c.TierReachedDay.Length) - 1] : -1,
Unlocks = Simulation.Systems.Tiers.NewUnlocks(w, c, t.Level),
});
}
var max = FinanceSystem.MaxLoan(w, c);
return new ClimbOutlookReport
{
Day = w.Clock.Day,
Company = c.Id,
FoundedDay = c.FoundedDay,
InitialCapital = new Money(w.Difficulty.InitialCapital),
Tier = c.Tier,
NextTier = c.Tier < tiers.Count ? tiers[c.Tier].Level : 0,
Tiers = list,
Next = c.Tier < tiers.Count ? Requirements(w, c, tiers[c.Tier]) : null,
Balance = Balance(c),
Income = Income(w, c),
Loans = c.Loans.Select(l => new LoanOutlook(l.Id, l.Remaining, l.AnnualRate, l.MonthsLeft)).ToList(),
MaxLoan = max,
LoanAvailable = Money.Max(Money.Zero, max - c.Debt),
NewLoanRate = FinanceSystem.LoanRate(w, c),
LoansAllowed = !c.Receivership,
History = History(w, c),
};
}
/// <summary>
/// Requisiti di un livello per la compagnia, con gli stessi confronti di <see cref="Simulation.Systems.Tiers.Meets"/>.
/// Frazioni: patrimonio / soglia e città / città richieste (limitate a 1; 1 se la soglia è zero); per il
/// rating i gradini risaliti dalla D rispetto a quelli richiesti. L'avanzamento è la loro media.
/// </summary>
public static RequirementProgress Requirements(World w, Company c, TierDef tier)
{
var req = tier.Requirements;
int towns = Simulation.Systems.Tiers.ConnectedTowns(w, c.Id, req.ConnectedTownsOver.Population);
double worth = req.NetWorth <= 0 ? 1 : DMath.Clamp((double)c.NetWorth.Cents / req.NetWorth, 0, 1);
double townsFraction = req.ConnectedTownsOver.Count <= 0 ? 1 : DMath.Clamp((double)towns / req.ConnectedTownsOver.Count, 0, 1);
int worst = w.Data.Tiers.RatingScale.Count - 1;
int steps = worst - (int)req.CreditRating;
double rating = c.Rating <= req.CreditRating || steps <= 0 ? 1 : DMath.Clamp((double)(worst - (int)c.Rating) / steps, 0, 1);
bool worthMet = c.NetWorth.Cents >= req.NetWorth, townsMet = towns >= req.ConnectedTownsOver.Count, ratingMet = c.Rating <= req.CreditRating;
// una frazione arrotondata a 1 non basta: l'avanzamento è 1 solo con tutti i requisiti soddisfatti
double progress = (worth + townsFraction + rating) / 3;
if (!(worthMet && townsMet && ratingMet)) progress = Math.Min(progress, 0.999);
return new RequirementProgress
{
Level = tier.Level,
NetWorth = c.NetWorth, NetWorthRequired = new Money(req.NetWorth), NetWorthFraction = worth, NetWorthMet = worthMet,
Towns = towns, TownsRequired = req.ConnectedTownsOver.Count, TownPopulation = req.ConnectedTownsOver.Population,
TownsFraction = townsFraction, TownsMet = townsMet,
Rating = c.Rating, RatingRequired = req.CreditRating, RatingFraction = rating, RatingMet = ratingMet,
Progress = progress,
};
}
/// <summary>Stato patrimoniale dalle voci del motore: somma esattamente al patrimonio netto.</summary>
public static BalanceSheet Balance(Company c)
{
var assets = new List<AssetLine>(AssetCategories.Count);
for (int k = 0; k < AssetCategories.Count; k++) assets.Add(new AssetLine((AssetCategory)k, new Money(c.BookValues[k])));
var cash = Money.Max(Money.Zero, c.Cash);
var overdraft = Money.Max(Money.Zero, -c.Cash);
var total = c.AssetBookValue + c.PortfolioValue + cash;
var loans = c.Debt;
double rate = 0;
if (loans.Cents > 0)
{
double weighted = 0;
foreach (var l in c.Loans) weighted += (double)l.Remaining.Cents * l.AnnualRate;
rate = weighted / loans.Cents;
}
return new BalanceSheet
{
Assets = assets, Portfolio = c.PortfolioValue, Cash = cash, TotalAssets = total,
Loans = loans, LoansRate = rate, Overdraft = overdraft, TotalLiabilities = loans + overdraft,
NetWorth = total - loans - overdraft,
};
}
/// <summary>
/// Conto economico dell'ultimo anno chiuso (o dell'anno in corso, per una compagnia fondata
/// quest'anno): righe raggruppate dalle voci del registro; l'utile è <see cref="Company.OperatingProfit"/>.
/// </summary>
public static IncomeStatement Income(World w, Company c)
{
long yearStart = (long)(w.Clock.Year - w.Calendar.StartYear) * w.Calendar.DaysPerYear;
bool closed = w.Clock.Year > w.Calendar.StartYear && c.FoundedDay < yearStart;
var e = closed ? c.LastYearEntries : c.YearEntries;
long Sum(params LedgerEntry[] keys)
{
long s = 0;
foreach (var k in keys) s += e[(int)k];
return s;
}
var lines = new List<IncomeLine>
{
new(IncomeLineKind.Fares, new Money(Sum(LedgerEntry.FreightRevenue, LedgerEntry.PassengerRevenue))),
new(IncomeLineKind.OtherIncome, new Money(Sum(LedgerEntry.Trading, LedgerEntry.Contracts, LedgerEntry.Industries, LedgerEntry.Subsidiaries))),
new(IncomeLineKind.OperatingCosts, new Money(Sum(LedgerEntry.RunningCosts, LedgerEntry.Wages, LedgerEntry.Penalties))),
new(IncomeLineKind.Maintenance, new Money(Sum(LedgerEntry.TrackMaintenance, LedgerEntry.FleetMaintenance))),
new(IncomeLineKind.Interest, new Money(Sum(LedgerEntry.Interest))),
};
return new IncomeStatement
{
Year = closed ? w.Clock.Year - 1 : w.Clock.Year,
Partial = !closed,
Lines = lines,
Profit = new Money(Company.OperatingProfit(e)),
};
}
/// <summary>
/// Patrimonio netto nel tempo: il capitale iniziale alla fondazione, la fotografia di fine anno
/// dello storico (al primo giorno dell'anno dopo) e il valore di oggi.
/// </summary>
public static List<NetWorthPoint> History(World w, Company c)
{
var points = new List<NetWorthPoint> { new(c.FoundedDay, new Money(w.Difficulty.InitialCapital)) };
long today = w.Clock.Day;
foreach (var y in c.History)
{
long day = (long)(y.Year + 1 - w.Calendar.StartYear) * w.Calendar.DaysPerYear;
if (day <= points[^1].Day || day >= today) continue;
points.Add(new NetWorthPoint(day, new Money(y.NetWorthCents)));
}
if (today > points[^1].Day) points.Add(new NetWorthPoint(today, c.NetWorth));
else points[^1] = new NetWorthPoint(points[^1].Day, c.NetWorth);
return points;
}
}
+42 -2
View File
@@ -31,6 +31,26 @@ public enum LedgerEntry : byte
Subsidiaries = 20,
}
/// <summary>Voci dello stato patrimoniale per gli attivi non monetari (ADR 0018).</summary>
public enum AssetCategory : byte
{
/// <summary>Binari e opere (ponti, gallerie), ammortizzati.</summary>
Track = 0,
/// <summary>Stazioni e depositi, al costo.</summary>
Stations = 1,
/// <summary>Veicoli, ammortizzati.</summary>
Vehicles = 2,
/// <summary>Industrie possedute: impianti e cassa dell'impresa.</summary>
Industries = 3,
/// <summary>Merce propria in magazzino e in viaggio, al prezzo globale.</summary>
Goods = 4,
}
public static class AssetCategories
{
public const int Count = 5;
}
/// <summary>Prestito con rata costante (ammortamento alla francese).</summary>
public sealed class Loan
{
@@ -77,8 +97,28 @@ public sealed class Company
/// <summary>Movimenti dell'anno precedente per voce (per rating e borsa).</summary>
public long[] LastYearEntries { get; } = new long[EntryCount];
/// <summary>Valore contabile degli attivi non monetari (binari, stazioni, veicoli), aggiornato mensilmente.</summary>
public Money AssetBookValue { get; set; }
/// <summary>
/// Valore contabile degli attivi non monetari per voce (<see cref="AssetCategory"/>, centesimi),
/// aggiornato ogni mese da <c>FinanceSystem.UpdateBookValues</c> (ADR 0018).
/// </summary>
public long[] BookValues { get; } = new long[AssetCategories.Count];
/// <summary>Valore contabile degli attivi non monetari: somma delle voci di <see cref="BookValues"/>.</summary>
public Money AssetBookValue
{
get
{
long sum = 0;
foreach (long v in BookValues) sum += v;
return new Money(sum);
}
}
/// <summary>
/// Giorno in cui la compagnia ha raggiunto ciascun livello (indice livello − 1; −1 se non
/// raggiunto o sconosciuto). Il livello 1 non si annota: vale dalla fondazione (ADR 0018).
/// </summary>
public long[] TierReachedDay { get; } = [-1, -1, -1, -1, -1];
public Money Debt
{
@@ -60,7 +60,7 @@ public sealed class TradingProgress
public required bool Unlocked { get; init; }
/// <summary>Livello che sblocca il commercio (0 se nessuno).</summary>
public required int Level { get; init; }
/// <summary>Minimo tra le frazioni dei requisiti numerici (patrimonio, città collegate), in [0, 1].</summary>
/// <summary>Avanzamento verso il livello (media delle frazioni dei tre requisiti, ADR 0018), in [0, 1].</summary>
public required double Fraction { get; init; }
public required Money NetWorth { get; init; }
public required Money NetWorthRequired { get; init; }
@@ -413,24 +413,22 @@ public static class MarketOutlook
Rating = c?.Rating ?? CreditRating.D, RatingRequired = r?.CreditRating ?? CreditRating.D, RatingMet = false,
};
}
var req = target.Requirements;
int towns = Tiers.ConnectedTowns(w, c.Id, req.ConnectedTownsOver.Population);
double worth = req.NetWorth <= 0 ? 1 : DMath.Clamp((double)c.NetWorth.Cents / req.NetWorth, 0, 1);
double townsFraction = req.ConnectedTownsOver.Count <= 0 ? 1 : DMath.Clamp((double)towns / req.ConnectedTownsOver.Count, 0, 1);
// stessi requisiti e stesso avanzamento del pannello «La tua scalata» (ADR 0018)
var progress = ClimbOutlook.Requirements(w, c, target);
bool unlocked = Tiers.Unlocks(w, c).Trading;
return new TradingProgress
{
Unlocked = unlocked,
Level = target.Level,
Fraction = unlocked ? 1 : Math.Min(worth, townsFraction),
NetWorth = c.NetWorth,
NetWorthRequired = new Money(req.NetWorth),
TownsConnected = towns,
TownsRequired = req.ConnectedTownsOver.Count,
TownPopulation = req.ConnectedTownsOver.Population,
Rating = c.Rating,
RatingRequired = req.CreditRating,
RatingMet = c.Rating <= req.CreditRating,
Fraction = unlocked ? 1 : progress.Progress,
NetWorth = progress.NetWorth,
NetWorthRequired = progress.NetWorthRequired,
TownsConnected = progress.Towns,
TownsRequired = progress.TownsRequired,
TownPopulation = progress.TownPopulation,
Rating = progress.Rating,
RatingRequired = progress.RatingRequired,
RatingMet = progress.RatingMet,
};
}
}
@@ -0,0 +1,92 @@
using RailEnterprise.Core.Economy;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Core.Simulation.Systems;
namespace RailEnterprise.Core.Persistence;
/// <summary>
/// Stato patrimoniale delle compagnie (corpo del salvataggio dalla versione 6, ADR 0018): valore
/// contabile degli attivi per voce (<see cref="AssetCategory"/>) e giorno in cui ogni livello è stato
/// raggiunto. Entra nell'hash giornaliero con lo stato dinamico. Le versioni precedenti salvano solo
/// il totale degli attivi: <see cref="Migrate"/> lo ripartisce senza cambiarlo.
/// </summary>
public static class BalanceSheetSerializer
{
public static void Write(World w, SaveWriter s)
{
s.Write(w.Companies.Count);
foreach (var c in w.Companies)
{
s.Write(c.BookValues);
s.Write(c.TierReachedDay);
}
}
public static void Read(World w, SaveReader r)
{
int n = r.ReadInt32();
if (n != w.Companies.Count) throw new InvalidDataException($"Stato patrimoniale di {n} compagnie su {w.Companies.Count}");
foreach (var c in w.Companies)
{
CopyInto(r.ReadInt64Array(), c.BookValues);
CopyInto(r.ReadInt64Array(), c.TierReachedDay);
}
}
/// <summary>
/// Migrazione dalle versioni 1–5: il totale salvato (letto nella voce dei binari) si ripartisce in
/// proporzione alla scomposizione calcolata al giorno del caricamento, con il resto dell'arrotondamento
/// sulla voce più grande; il totale, e quindi il patrimonio netto, non cambia fino al ricalcolo del
/// mese. I giorni dei livelli si ricostruiscono dai fatti salienti («diventa «nome»») e, in mancanza,
/// dallo storico annuale (primo giorno dell'anno in cui il livello compare).
/// </summary>
public static void Migrate(World w)
{
var live = FinanceSystem.BookValues(w);
for (int i = 0; i < w.Companies.Count; i++)
{
var c = w.Companies[i];
long total = c.AssetBookValue.Cents;
Array.Clear(c.BookValues);
long liveSum = 0;
foreach (long v in live[i]) liveSum += v;
if (total != 0 && liveSum > 0)
{
long assigned = 0;
int largest = 0;
for (int k = 0; k < AssetCategories.Count; k++)
{
c.BookValues[k] = (long)((Int128)total * live[i][k] / liveSum);
assigned += c.BookValues[k];
if (live[i][k] > live[i][largest]) largest = k;
}
c.BookValues[largest] += total - assigned;
}
else
{
c.BookValues[(int)AssetCategory.Track] = total;
}
RebuildTierDays(w, c);
}
}
private static void RebuildTierDays(World w, Company c)
{
Array.Fill(c.TierReachedDay, -1L);
var tiers = w.Data.Tiers.Tiers;
for (int level = 2; level <= Math.Min(c.Tier, c.TierReachedDay.Length); level++)
{
string text = $"diventa «{tiers[level - 1].NameIt}»";
long day = c.Milestones.FirstOrDefault(m => m.Text == text, new CompanyMilestone(-1, "")).Day;
if (day < 0)
{
int year = c.History.FirstOrDefault(y => y.Tier >= level, new CompanyYear(int.MinValue, 0, 0, 0, 0, 0, 0, 0, 0)).Year;
if (year != int.MinValue) day = Math.Max(0, (long)(year - w.Calendar.StartYear) * w.Calendar.DaysPerYear);
}
c.TierReachedDay[level - 1] = day;
}
}
private static void CopyInto(long[] source, long[] target) =>
Array.Copy(source, target, Math.Min(source.Length, target.Length));
}
@@ -14,7 +14,7 @@ namespace RailEnterprise.Core.Persistence;
public static class WorldSerializer
{
/// <summary>Versione del corpo del salvataggio (migrazioni in <see cref="Read"/>).</summary>
public const int BodyVersion = 5;
public const int BodyVersion = 6;
/// <summary>Scrive l'intero mondo (impostazioni, terreno, stato dinamico, eventi).</summary>
public static void Write(World w, SaveWriter s) => Write(w, s, BodyVersion);
@@ -247,6 +247,7 @@ public static class WorldSerializer
if (version >= 3) CorporateSerializer.Write(w, s);
if (version >= 4) TradingSerializer.Write(w, s);
if (version >= 5) EventSerializer.Write(w, s);
if (version >= 6) BalanceSheetSerializer.Write(w, s);
}
private static void WriteRecipeStock(List<RecipeItemDef> items, int[] stock, SaveWriter s)
@@ -641,7 +642,8 @@ public static class WorldSerializer
CopyInto(r.ReadInt64Array(), c.MonthEntries);
CopyInto(r.ReadInt64Array(), c.YearEntries);
CopyInto(r.ReadInt64Array(), c.LastYearEntries);
c.AssetBookValue = new Money(r.ReadInt64());
// totale degli attivi: dalla versione 6 lo sostituisce la scomposizione per voce (BalanceSheetSerializer)
c.BookValues[(int)AssetCategory.Track] = r.ReadInt64();
int loans = r.ReadInt32();
for (int k = 0; k < loans; k++)
{
@@ -707,6 +709,9 @@ public static class WorldSerializer
else TradingSerializer.Migrate(w);
// versione 5 (F6): eventi del mondo in corso; prima nessun evento attivo
if (version >= 5) EventSerializer.Read(w, r);
// versione 6 (F6): stato patrimoniale per voce e giorni dei livelli raggiunti
if (version >= 6) BalanceSheetSerializer.Read(w, r);
else BalanceSheetSerializer.Migrate(w);
}
private static void ReadRecipeStock(List<RecipeItemDef> items, int[] stock, SaveReader r)
@@ -62,6 +62,9 @@ public static class CommandProcessor
BuyGoodsCommand c => TradingCommandHandlers.Buy(w, company, c, Reply),
SellGoodsCommand c => TradingCommandHandlers.Sell(w, company, c, Reply),
ShipGoodsCommand c => TradingCommandHandlers.Ship(w, company, c, ctx, Reply),
// le concessioni (F7) si rifiutano prima per il livello, poi perché non ancora disponibili
BuyConcessionCommand when !Tiers.Unlocks(w, company).Concessions =>
Result(CommandError.TierLocked, Tiers.LockedText(w, "Le concessioni", u => u.Concessions, plural: true)),
_ => Result(CommandError.NotImplemented, $"Comando {command.Type} non ancora disponibile"),
};
}
@@ -72,7 +75,7 @@ public static class CommandProcessor
if (company.Receivership) return result(CommandError.NotAllowed, "In amministrazione controllata non si possono chiedere prestiti");
var max = FinanceSystem.MaxLoan(w, company);
if (company.Debt + c.Amount > max)
return result(CommandError.CreditLimit, $"Fido insufficiente: disponibili {(max - company.Debt).ToString()}");
return result(CommandError.CreditLimit, LoanLimitText(w, company, max));
var fb = w.Data.Balance.Finance;
var loan = new Loan
{
@@ -88,6 +91,18 @@ public static class CommandProcessor
return result(CommandError.None, $"Prestito di {c.Amount} al {loan.AnnualRate * 100:F1}% per {loan.TermMonths / 12} anni");
}
/// <summary>
/// Rifiuto per fido insufficiente: quanto resta disponibile e, se un livello successivo alza il
/// fattore del fido, quale livello serve e a quanto porta il fido (ADR 0018).
/// </summary>
public static string LoanLimitText(World w, Company company, Money max)
{
string text = $"Fido insufficiente: disponibili {Money.Max(Money.Zero, max - company.Debt)} su {max}";
var current = Tiers.Def(w, company.Tier);
var next = w.Data.Tiers.Tiers.FirstOrDefault(t => t.Level > current.Level && t.Unlocks.MaxLoanFactor > current.Unlocks.MaxLoanFactor);
return next is null ? text : $"{text}; il livello {next.Level}, «{next.NameIt}», porta il fido a {Tiers.LoanLimit(company, next)}";
}
private static CommandResult RepayLoan(World w, Company company, RepayLoanCommand c, Func<CommandError, string, CommandResult> result)
{
var loan = company.Loans.FirstOrDefault(l => l.Id == c.Loan);
@@ -16,7 +16,7 @@ public static class CorporateCommandHandlers
{
var sm = w.Data.Balance.StockMarket;
if (company.IsPlayer && !company.Listed && !Tiers.Unlocks(w, company).Ipo)
return reply(CommandError.TierLocked, "La quotazione si sblocca al livello «Grande compagnia»");
return reply(CommandError.TierLocked, Tiers.LockedText(w, "La quotazione in borsa", u => u.Ipo));
// prima quotazione fino a ipoMaxShare; per chi è già quotato un aumento di capitale fino al flottante massimo
double limit = company.Listed ? sm.SecondaryMaxFloat - (double)company.Shares.Public / company.Shares.Total : sm.IpoMaxShare;
if (!(c.FloatShare > 0) || c.FloatShare > limit + 1e-9)
@@ -137,7 +137,7 @@ public static class CorporateCommandHandlers
if (target.Defunct) return reply(CommandError.NotAllowed, $"{target.Name} non è più attiva");
if (company.IsPlayer && !Tiers.Unlocks(w, company).HostileTakeover)
return reply(CommandError.TierLocked, "Le scalate ostili si sbloccano al livello «Impero ferroviario»");
return reply(CommandError.TierLocked, Tiers.LockedText(w, "Le scalate ostili", u => u.HostileTakeover, plural: true));
if (!target.Listed) return reply(CommandError.NotAllowed, $"{target.Name} non è quotata");
if (target.IsPlayer && w.Difficulty.PlayerTakeover == TakeoverRule.Disabled)
return reply(CommandError.NotAllowed, "Con questa difficoltà la compagnia del giocatore non è scalabile");
@@ -11,7 +11,7 @@ public static class IndustryCommandHandlers
public static CommandResult BuyIndustry(World w, Company company, BuyIndustryCommand c, RailCommandHandlers.Reply reply)
{
if (!Tiers.Unlocks(w, company).BuyIndustry)
return reply(CommandError.TierLocked, "L'acquisto di industrie si sblocca al livello «Compagnia nazionale»");
return reply(CommandError.TierLocked, Tiers.LockedText(w, "L'acquisto di industrie", u => u.BuyIndustry));
if (!TryIndustry(w, c.Industry, out var ind) || ind.Closed) return reply(CommandError.NotFound, "Industria inesistente");
if (ind.Owner == company.Id) return reply(CommandError.NotAllowed, $"{ind.Name} è già della compagnia");
if (ind.Owner.IsValid) return reply(CommandError.NotAllowed, $"{ind.Name} appartiene a {w.Company(ind.Owner).Name}");
@@ -23,11 +23,7 @@ public sealed class ConstructionSystem : ISimSystem
}
/// <summary>Squadre disponibili per una compagnia secondo il livello.</summary>
public static int Crews(World w, Company c)
{
var byTier = w.Data.Construction.Crews.CrewsByTier;
return byTier[Math.Clamp(c.Tier, 1, byTier.Length) - 1];
}
public static int Crews(World w, Company c) => Tiers.Crews(w, c.Tier);
private static void Projects(WorldContext ctx, World w)
{
@@ -85,46 +85,66 @@ public sealed class FinanceSystem : ISimSystem
/// <summary>
/// Valore contabile degli attivi: binari e veicoli ammortizzati, stazioni e depositi al costo,
/// merce della compagnia (magazzini e spedizioni in viaggio) al prezzo globale (ADR 0016).
/// industrie possedute (impianti e cassa dell'impresa, ADR 0018), merce della compagnia
/// (magazzini e spedizioni in viaggio) al prezzo globale (ADR 0016). Scrive le voci in
/// <see cref="Company.BookValues"/>: il patrimonio netto le somma.
/// </summary>
public static void UpdateBookValues(World w)
{
var values = BookValues(w);
for (int i = 0; i < w.Companies.Count; i++) Array.Copy(values[i], w.Companies[i].BookValues, AssetCategories.Count);
}
/// <summary>
/// Stato patrimoniale degli attivi non monetari di ogni compagnia, per voce
/// (<see cref="AssetCategory"/>), calcolato al giorno corrente. Unica fonte del valore contabile.
/// </summary>
public static long[][] BookValues(World w)
{
var fb = w.Data.Balance.Finance;
var values = new long[w.Companies.Count];
var values = new long[w.Companies.Count][];
for (int i = 0; i < values.Length; i++) values[i] = new long[AssetCategories.Count];
const int track = (int)AssetCategory.Track, stations = (int)AssetCategory.Stations, vehicles = (int)AssetCategory.Vehicles,
industries = (int)AssetCategory.Industries, goods = (int)AssetCategory.Goods;
double daysPerYear = w.Calendar.DaysPerYear;
long today = w.Clock.Day;
foreach (var e in w.Network.Edges)
{
if (e.State == Rail.EdgeState.Demolished) continue;
double age = (today - e.BuiltDay) / daysPerYear;
values[e.Owner.Value] += (long)(e.BuildCostCents * Math.Max(fb.BookValueFloor, 1 - age / fb.DepreciationYearsTrack));
values[e.Owner.Value][track] += (long)(e.BuildCostCents * Math.Max(fb.BookValueFloor, 1 - age / fb.DepreciationYearsTrack));
}
foreach (var s in w.Network.Stations)
{
if (w.Network.Nodes[s.Node.Value].Station == s.Id) values[s.Owner.Value] += s.BuildCostCents;
if (w.Network.Nodes[s.Node.Value].Station == s.Id) values[s.Owner.Value][stations] += s.BuildCostCents;
}
foreach (var d in w.Network.Depots)
{
if (w.Network.Nodes[d.Node.Value].Depot == d.Id) values[d.Owner.Value] += d.BuildCostCents;
if (w.Network.Nodes[d.Node.Value].Depot == d.Id) values[d.Owner.Value][stations] += d.BuildCostCents;
}
foreach (var v in w.Vehicles)
{
if (v.Sold) continue;
double age = (today - v.BoughtDay) / daysPerYear;
values[v.Owner.Value] += (long)(v.Def.Price * Math.Max(fb.BookValueFloor, 1 - age / v.Def.LifeYears));
values[v.Owner.Value][vehicles] += (long)(v.Def.Price * Math.Max(fb.BookValueFloor, 1 - age / v.Def.LifeYears));
}
foreach (var ind in w.Industries)
{
if (ind.Closed || !ind.Owner.IsValid || ind.Owner.Value >= values.Length) continue;
values[ind.Owner.Value][industries] += IndustryMath.BookValue(w, ind).Cents;
}
var prices = w.Market.GlobalPrice;
foreach (var s in w.Network.Stations)
{
if (!s.Owner.IsValid || s.Owner.Value >= values.Length) continue;
for (int g = 0; g < s.Stock.Length; g++) values[s.Owner.Value] += (long)(s.Stock[g] * prices[g]);
values[s.Owner.Value] += OwnedGoodsValue(s.Waiting, prices);
for (int g = 0; g < s.Stock.Length; g++) values[s.Owner.Value][goods] += (long)(s.Stock[g] * prices[g]);
values[s.Owner.Value][goods] += OwnedGoodsValue(s.Waiting, prices);
}
foreach (var t in w.Trains)
{
if (!t.Removed && t.Owner.IsValid && t.Owner.Value < values.Length) values[t.Owner.Value] += OwnedGoodsValue(t.Cargo, prices);
if (!t.Removed && t.Owner.IsValid && t.Owner.Value < values.Length) values[t.Owner.Value][goods] += OwnedGoodsValue(t.Cargo, prices);
}
for (int i = 0; i < w.Companies.Count; i++) w.Companies[i].AssetBookValue = new Money(values[i]);
return values;
}
private static long OwnedGoodsValue(List<Rail.Packet> packets, double[] prices)
@@ -192,11 +212,7 @@ public sealed class FinanceSystem : ISimSystem
}
/// <summary>Fido massimo della compagnia secondo il livello raggiunto.</summary>
public static Money MaxLoan(World w, Company c)
{
var tier = w.Data.Tiers.Tiers[Math.Clamp(c.Tier, 1, w.Data.Tiers.Tiers.Count) - 1];
return c.BaseCredit * tier.Unlocks.MaxLoanFactor;
}
public static Money MaxLoan(World w, Company c) => Tiers.LoanLimit(c, Tiers.Def(w, c.Tier));
/// <summary>Tasso annuo per un nuovo prestito: base della difficoltà + spread del rating.</summary>
public static double LoanRate(World w, Company c) =>
@@ -92,8 +92,21 @@ public static class IndustryMath
public static Common.Money Valuation(World w, Industry ind)
{
var p = w.Data.Balance.IndustryMaintenance.Purchase;
double plant = ind.Def.UpgradeCost * Math.Max(1, ind.Level) * p.AssetShare * (1 - p.ConditionWeight + p.ConditionWeight * ind.Condition / 100);
double earnings = Math.Max(0, AnnualProfit(w, ind)) * p.EarningsMultiple;
return Common.Money.FromCentsRounded(plant + earnings + Math.Max(0, ind.Cash.Cents));
return Common.Money.FromCentsRounded(PlantValue(w, ind) + earnings + Math.Max(0, ind.Cash.Cents));
}
/// <summary>Valore degli impianti nel prezzo d'acquisto: costo d'ammodernamento × livello × quota, secondo le condizioni.</summary>
public static double PlantValue(World w, Industry ind)
{
var p = w.Data.Balance.IndustryMaintenance.Purchase;
return ind.Def.UpgradeCost * Math.Max(1, ind.Level) * p.AssetShare * (1 - p.ConditionWeight + p.ConditionWeight * ind.Condition / 100);
}
/// <summary>
/// Valore contabile di un'industria per il proprietario (ADR 0018): il prezzo d'acquisto senza
/// l'avviamento (multiplo degli utili), cioè impianti più cassa dell'impresa.
/// </summary>
public static Common.Money BookValue(World w, Industry ind) =>
Common.Money.FromCentsRounded(PlantValue(w, ind) + Math.Max(0, ind.Cash.Cents));
}
@@ -4,16 +4,36 @@ using RailEnterprise.Core.Economy;
namespace RailEnterprise.Core.Simulation.Systems;
/// <summary>Sblocco di un livello (ADR 0018): tipo e valore (fido in centesimi, numero di squadre).</summary>
public enum UnlockKind : byte
{
/// <summary>Fido massimo (valore: centesimi per la compagnia).</summary>
LoanLimit = 0,
/// <summary>Squadre di cantiere (valore: numero).</summary>
Crews = 1,
Trading = 2,
BuyIndustry = 3,
Ipo = 4,
HostileTakeover = 5,
Concessions = 6,
}
public readonly record struct TierUnlock(UnlockKind Kind, long Value);
/// <summary>
/// Livelli della compagnia (tiers.json): ogni mese, dopo il rating, una compagnia che soddisfa i
/// requisiti del livello successivo (patrimonio netto, città collegate sopra una popolazione,
/// rating) sale di un livello. Il livello non scende: gli sblocchi restano acquisiti (ADR 0011).
/// Al passaggio la notizia elenca gli sblocchi ottenuti (ADR 0018).
/// </summary>
public static class Tiers
{
/// <summary>Definizione del livello indicato (limitato tra 1 e l'ultimo).</summary>
public static TierDef Def(World w, int level) =>
w.Data.Tiers.Tiers[Math.Clamp(level, 1, w.Data.Tiers.Tiers.Count) - 1];
/// <summary>Sblocchi del livello attuale della compagnia.</summary>
public static TierUnlocks Unlocks(World w, Company c) =>
w.Data.Tiers.Tiers[Math.Clamp(c.Tier, 1, w.Data.Tiers.Tiers.Count) - 1].Unlocks;
public static TierUnlocks Unlocks(World w, Company c) => Def(w, c.Tier).Unlocks;
/// <summary>Promuove la compagnia se soddisfa i requisiti del livello successivo.</summary>
public static void Evaluate(WorldContext ctx, Company c)
@@ -24,12 +44,84 @@ public static class Tiers
{
var next = tiers[c.Tier];
c.Tier = next.Level;
c.TierReachedDay[next.Level - 1] = ctx.Day;
Corporate.Milestone(w, c, $"diventa «{next.NameIt}»");
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Opportunity,
$"{c.Name} diventa «{next.NameIt}» (livello {next.Level})", EntityKind.Company, c.Id.Value, c.Id));
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Opportunity, PromotionText(w, c, next.Level),
EntityKind.Company, c.Id.Value, c.Id));
}
}
/// <summary>Testo della notizia di promozione con gli sblocchi ottenuti.</summary>
public static string PromotionText(World w, Company c, int level)
{
var def = Def(w, level);
var unlocks = NewUnlocks(w, c, level);
string text = $"{c.Name} diventa «{def.NameIt}» (livello {def.Level})";
return unlocks.Count == 0 ? text : $"{text}: sblocca {string.Join(", ", unlocks.Select(UnlockLabel))}";
}
/// <summary>
/// Sblocchi che il livello aggiunge al precedente, nell'ordine di <see cref="UnlockKind"/>: per il
/// primo livello la dotazione di partenza (fido e squadre). Tutto viene da tiers.json e dalle
/// squadre di construction.json; il fido è quello della compagnia (fido iniziale × fattore).
/// </summary>
public static List<TierUnlock> NewUnlocks(World w, Company c, int level)
{
var def = Def(w, level);
var u = def.Unlocks;
var prev = def.Level > 1 ? Def(w, def.Level - 1) : null;
var p = prev?.Unlocks;
var list = new List<TierUnlock>();
if (p is null || u.MaxLoanFactor > p.MaxLoanFactor) list.Add(new TierUnlock(UnlockKind.LoanLimit, LoanLimit(c, def).Cents));
int crews = Crews(w, def.Level);
if (prev is null || crews > Crews(w, prev.Level)) list.Add(new TierUnlock(UnlockKind.Crews, crews));
if (u.Trading && p?.Trading != true) list.Add(new TierUnlock(UnlockKind.Trading, 0));
if (u.BuyIndustry && p?.BuyIndustry != true) list.Add(new TierUnlock(UnlockKind.BuyIndustry, 0));
if (u.Ipo && p?.Ipo != true) list.Add(new TierUnlock(UnlockKind.Ipo, 0));
if (u.HostileTakeover && p?.HostileTakeover != true) list.Add(new TierUnlock(UnlockKind.HostileTakeover, 0));
if (u.Concessions && p?.Concessions != true) list.Add(new TierUnlock(UnlockKind.Concessions, 0));
return list;
}
/// <summary>Fido massimo della compagnia a un livello: fido iniziale × fattore del livello.</summary>
public static Money LoanLimit(Company c, TierDef def) => c.BaseCredit * def.Unlocks.MaxLoanFactor;
/// <summary>Squadre di cantiere a un livello (construction.json, le stesse di ConstructionSystem).</summary>
public static int Crews(World w, int level)
{
var byTier = w.Data.Construction.Crews.CrewsByTier;
return byTier[Math.Clamp(level, 1, byTier.Length) - 1];
}
/// <summary>Etichetta italiana di uno sblocco (per le notizie del motore).</summary>
public static string UnlockLabel(TierUnlock u) => u.Kind switch
{
UnlockKind.LoanLimit => $"fido fino a {new Money(u.Value).ToString("short")}",
UnlockKind.Crews => $"{u.Value} squadre di cantiere",
UnlockKind.Trading => "compravendita in proprio",
UnlockKind.BuyIndustry => "acquisto di industrie",
UnlockKind.Ipo => "quotazione in borsa",
UnlockKind.HostileTakeover => "scalate ostili",
UnlockKind.Concessions => "concessioni",
_ => u.Kind.ToString(),
};
/// <summary>Primo livello di tiers.json che ha lo sblocco indicato (null se nessuno).</summary>
public static TierDef? FirstUnlocking(World w, Func<TierUnlocks, bool> unlock) =>
w.Data.Tiers.Tiers.FirstOrDefault(t => unlock(t.Unlocks));
/// <summary>
/// Testo di rifiuto per una funzione bloccata dal livello: «{funzione} si sblocca al livello N,
/// «nome»» dai dati, oppure «{funzione} non è disponibile» se nessun livello la sblocca.
/// </summary>
public static string LockedText(World w, string feature, Func<TierUnlocks, bool> unlock, bool plural = false)
{
var tier = FirstUnlocking(w, unlock);
return tier is null
? $"{feature} {(plural ? "non sono disponibili" : "non è disponibile")}"
: $"{feature} {(plural ? "si sbloccano" : "si sblocca")} al livello {tier.Level}, «{tier.NameIt}»";
}
/// <summary>Requisiti di un livello soddisfatti dalla compagnia.</summary>
public static bool Meets(World w, Company c, TierRequirements req) =>
c.NetWorth.Cents >= req.NetWorth
@@ -230,10 +230,7 @@ public static class TradingCommandHandlers
s = null!;
if (needsUnlock && !Tiers.Unlocks(w, company).Trading)
{
var tier = w.Data.Tiers.Tiers.FirstOrDefault(t => t.Unlocks.Trading);
error = (CommandError.TierLocked, tier is null
? "La compravendita in proprio non è disponibile"
: $"La compravendita in proprio si sblocca al livello «{tier.NameIt}»");
error = (CommandError.TierLocked, Tiers.LockedText(w, "La compravendita in proprio", u => u.Trading));
return false;
}
if (!TryOwnStation(w, company, station, out s, out error)) return false;
@@ -50,6 +50,9 @@ public sealed class ClientWorld(GameData data)
/// <summary>Quadro del mercato globale (F6), su richiesta.</summary>
public MarketReport? Market { get; private set; }
/// <summary>Quadro della scalata (F6), su richiesta: lo usano il pannello «La tua scalata» e la barra superiore.</summary>
public ClimbReport? Climb { get; private set; }
/// <summary>Contatore dei listini ricevuti (per aggiornare il pannello della borsa).</summary>
public int TapeVersion { get; private set; }
@@ -134,6 +137,10 @@ public sealed class ClientWorld(GameData data)
Market = m;
DetailVersion++;
return true;
case ClimbReport m:
Climb = m;
DetailVersion++;
return true;
case MaintenanceAlert m:
Alerts.Insert(0, m);
if (Alerts.Count > AlertCapacity) Alerts.RemoveAt(Alerts.Count - 1);
@@ -154,6 +161,7 @@ public sealed class ClientWorld(GameData data)
IndustryCards.Clear();
Chronicle = null;
Market = null;
Climb = null;
Alerts.Clear();
Summary = m.Summary;
SessionId = m.SessionId;
+2
View File
@@ -43,6 +43,8 @@ public enum MessageId : ushort
Notification = 131,
Newspaper = 132,
SaveList = 133,
/// <summary>Quadro della scalata: livelli, sblocchi, requisiti, stato patrimoniale (F6).</summary>
ClimbReport = 134,
}
/// <summary>Messaggio del protocollo: si serializza a mano, campo per campo.</summary>
@@ -239,6 +239,8 @@ public enum DetailKind : byte
Chronicle = 6,
/// <summary>Quadro del mercato globale (risposta MarketReport, F6; Id ignorato).</summary>
Market = 7,
/// <summary>Quadro della scalata (risposta ClimbReport, F6; Id ignorato).</summary>
Climb = 8,
}
/// <summary>Chiede al server un dettaglio che non viaggia con le entità (aggiunto in F4).</summary>
@@ -0,0 +1,276 @@
using RailEnterprise.Core.Common;
namespace RailEnterprise.Protocol.Messages;
// Messaggi della fase F6: pannello «La tua scalata» (immagine di riferimento 08). Il quadro arriva su
// richiesta (RequestDetail con DetailKind.Climb) ed è calcolato dal server con ClimbOutlook (ADR 0018):
// il client lo mostra com'è, senza logica di gioco.
/// <summary>Sblocco di un livello: Kind come UnlockKind del Core (0 fido, 1 squadre, 2 compravendita, 3 acquisto di industrie, 4 quotazione, 5 scalate ostili, 6 concessioni).</summary>
public sealed class UnlockInfo
{
public const byte LoanLimit = 0, Crews = 1, Trading = 2, BuyIndustry = 3, Ipo = 4, HostileTakeover = 5, Concessions = 6;
public byte Kind { get; init; }
/// <summary>Fido in centesimi (LoanLimit) o numero di squadre (Crews); 0 per gli altri.</summary>
public long Value { get; init; }
public void Write(ref SpanWriter w)
{
w.U8(Kind); w.I64(Value);
w.Flags(0);
}
public static UnlockInfo Read(ref SpanReader r)
{
var m = new UnlockInfo { Kind = r.U8(), Value = r.I64() };
r.Flags();
return m;
}
}
/// <summary>Livello di tiers.json visto dalla compagnia: requisiti, raggiunto e quando, sblocchi che aggiunge.</summary>
public sealed class TierInfo
{
public byte Level { get; init; }
public string NameIt { get; init; } = "";
public string NameEn { get; init; } = "";
public Money NetWorthRequired { get; init; }
public int TownsRequired { get; init; }
public int TownPopulation { get; init; }
public string RatingRequired { get; init; } = "";
public bool Reached { get; init; }
/// <summary>Giorno in cui è stato raggiunto (fondazione per il livello 1; −1 se non raggiunto o sconosciuto).</summary>
public long ReachedDay { get; init; } = -1;
public List<UnlockInfo> Unlocks { get; init; } = [];
public void Write(ref SpanWriter w)
{
w.U8(Level); w.String(NameIt); w.String(NameEn); w.Money(NetWorthRequired); w.I32(TownsRequired); w.I32(TownPopulation);
w.String(RatingRequired); w.Bool(Reached); w.I64(ReachedDay);
w.Count(Unlocks.Count);
foreach (var u in Unlocks) u.Write(ref w);
w.Flags(0);
}
public static TierInfo Read(ref SpanReader r)
{
var m = new TierInfo
{
Level = r.U8(), NameIt = r.String(), NameEn = r.String(), NetWorthRequired = r.Money(), TownsRequired = r.I32(), TownPopulation = r.I32(),
RatingRequired = r.String(), Reached = r.Bool(), ReachedDay = r.I64(),
};
for (int n = r.Count(), i = 0; i < n; i++) m.Unlocks.Add(UnlockInfo.Read(ref r));
r.Flags();
return m;
}
}
/// <summary>Voce dello stato patrimoniale o del conto economico: Kind secondo la tabella del messaggio, valore con segno.</summary>
public sealed class AmountInfo
{
public byte Kind { get; init; }
public Money Value { get; init; }
public void Write(ref SpanWriter w)
{
w.U8(Kind); w.Money(Value);
w.Flags(0);
}
public static AmountInfo Read(ref SpanReader r)
{
var m = new AmountInfo { Kind = r.U8(), Value = r.Money() };
r.Flags();
return m;
}
}
/// <summary>Prestito in corso: residuo, tasso annuo, mesi restanti.</summary>
public sealed class LoanInfo
{
public int Loan { get; init; }
public Money Remaining { get; init; }
public float AnnualRate { get; init; }
public int MonthsLeft { get; init; }
public void Write(ref SpanWriter w)
{
w.I32(Loan); w.Money(Remaining); w.F32(AnnualRate); w.I32(MonthsLeft);
w.Flags(0);
}
public static LoanInfo Read(ref SpanReader r)
{
var m = new LoanInfo { Loan = r.I32(), Remaining = r.Money(), AnnualRate = r.F32(), MonthsLeft = r.I32() };
r.Flags();
return m;
}
}
/// <summary>Patrimonio netto a un giorno della partita.</summary>
public sealed class NetWorthPointInfo
{
public long Day { get; init; }
public Money Value { get; init; }
public void Write(ref SpanWriter w)
{
w.I64(Day); w.Money(Value);
w.Flags(0);
}
public static NetWorthPointInfo Read(ref SpanReader r)
{
var m = new NetWorthPointInfo { Day = r.I64(), Value = r.Money() };
r.Flags();
return m;
}
}
/// <summary>
/// Quadro della scalata per la compagnia della sessione (F6, ADR 0018): livelli con requisiti e
/// sblocchi, requisiti del prossimo livello con l'avanzamento, stato patrimoniale per voce (somma al
/// patrimonio netto del motore), conto economico, prestiti e storico del patrimonio netto.
/// </summary>
public sealed class ClimbReport : IMessage
{
/// <summary>Voci degli attivi (Assets[].Kind), come AssetCategory del Core.</summary>
public const byte AssetTrack = 0, AssetStations = 1, AssetVehicles = 2, AssetIndustries = 3, AssetGoods = 4;
/// <summary>Righe del conto economico (Income[].Kind), come IncomeLineKind del Core.</summary>
public const byte IncomeFares = 0, IncomeOther = 1, IncomeOperating = 2, IncomeMaintenance = 3, IncomeInterest = 4;
public MessageId Id => MessageId.ClimbReport;
public long Day { get; init; }
public int Company { get; init; }
public long FoundedDay { get; init; }
public Money InitialCapital { get; init; }
public byte Tier { get; init; }
/// <summary>Livello successivo (0 all'ultimo livello: i requisiti che seguono sono vuoti).</summary>
public byte NextTier { get; init; }
public List<TierInfo> Tiers { get; init; } = [];
/// <summary>Requisiti del livello successivo: valore attuale, soglia, frazione (0–1) e se è soddisfatto.</summary>
public Money NetWorth { get; init; }
public Money NetWorthRequired { get; init; }
public float NetWorthFraction { get; init; }
public bool NetWorthMet { get; init; }
public int Towns { get; init; }
public int TownsRequired { get; init; }
public int TownPopulation { get; init; }
public float TownsFraction { get; init; }
public bool TownsMet { get; init; }
public string Rating { get; init; } = "";
public string RatingRequired { get; init; } = "";
public float RatingFraction { get; init; }
public bool RatingMet { get; init; }
/// <summary>Avanzamento complessivo verso il livello successivo (media delle tre frazioni).</summary>
public float Progress { get; init; }
/// <summary>Stato patrimoniale: attivi per voce, partecipazioni, cassa; prestiti (tasso medio), scoperto.</summary>
public List<AmountInfo> Assets { get; init; } = [];
public Money Portfolio { get; init; }
public Money Cash { get; init; }
public Money TotalAssets { get; init; }
public Money Loans { get; init; }
public float LoansRate { get; init; }
public Money Overdraft { get; init; }
public Money TotalLiabilities { get; init; }
public Money BalanceNetWorth { get; init; }
/// <summary>Conto economico dell'anno indicato (Partial se è l'anno in corso fino a oggi).</summary>
public int IncomeYear { get; init; }
public bool IncomePartial { get; init; }
public List<AmountInfo> Income { get; init; } = [];
public Money Profit { get; init; }
public List<LoanInfo> LoanList { get; init; } = [];
public Money MaxLoan { get; init; }
public Money LoanAvailable { get; init; }
public float NewLoanRate { get; init; }
public bool LoansAllowed { get; init; } = true;
public List<NetWorthPointInfo> History { get; init; } = [];
public void Write(ref SpanWriter w)
{
w.I64(Day); w.I32(Company); w.I64(FoundedDay); w.Money(InitialCapital); w.U8(Tier); w.U8(NextTier);
w.Count(Tiers.Count);
foreach (var t in Tiers) t.Write(ref w);
w.Money(NetWorth); w.Money(NetWorthRequired); w.F32(NetWorthFraction); w.Bool(NetWorthMet);
w.I32(Towns); w.I32(TownsRequired); w.I32(TownPopulation); w.F32(TownsFraction); w.Bool(TownsMet);
w.String(Rating); w.String(RatingRequired); w.F32(RatingFraction); w.Bool(RatingMet); w.F32(Progress);
w.Count(Assets.Count);
foreach (var a in Assets) a.Write(ref w);
w.Money(Portfolio); w.Money(Cash); w.Money(TotalAssets); w.Money(Loans); w.F32(LoansRate); w.Money(Overdraft);
w.Money(TotalLiabilities); w.Money(BalanceNetWorth);
w.I32(IncomeYear); w.Bool(IncomePartial);
w.Count(Income.Count);
foreach (var i in Income) i.Write(ref w);
w.Money(Profit);
w.Count(LoanList.Count);
foreach (var l in LoanList) l.Write(ref w);
w.Money(MaxLoan); w.Money(LoanAvailable); w.F32(NewLoanRate); w.Bool(LoansAllowed);
w.Count(History.Count);
foreach (var p in History) p.Write(ref w);
w.Flags(0);
}
public static ClimbReport Read(ref SpanReader r)
{
long day = r.I64();
int company = r.I32();
long founded = r.I64();
var capital = r.Money();
byte tier = r.U8(), next = r.U8();
var tiers = new List<TierInfo>();
for (int n = r.Count(), i = 0; i < n; i++) tiers.Add(TierInfo.Read(ref r));
var worth = r.Money();
var worthRequired = r.Money();
float worthFraction = r.F32();
bool worthMet = r.Bool();
int towns = r.I32(), townsRequired = r.I32(), townPopulation = r.I32();
float townsFraction = r.F32();
bool townsMet = r.Bool();
string rating = r.String(), ratingRequired = r.String();
float ratingFraction = r.F32();
bool ratingMet = r.Bool();
float progress = r.F32();
var assets = new List<AmountInfo>();
for (int n = r.Count(), i = 0; i < n; i++) assets.Add(AmountInfo.Read(ref r));
var portfolio = r.Money();
var cash = r.Money();
var totalAssets = r.Money();
var loans = r.Money();
float loansRate = r.F32();
var overdraft = r.Money();
var totalLiabilities = r.Money();
var balanceWorth = r.Money();
int incomeYear = r.I32();
bool partial = r.Bool();
var income = new List<AmountInfo>();
for (int n = r.Count(), i = 0; i < n; i++) income.Add(AmountInfo.Read(ref r));
var profit = r.Money();
var loanList = new List<LoanInfo>();
for (int n = r.Count(), i = 0; i < n; i++) loanList.Add(LoanInfo.Read(ref r));
var maxLoan = r.Money();
var available = r.Money();
float newRate = r.F32();
bool allowed = r.Bool();
var history = new List<NetWorthPointInfo>();
for (int n = r.Count(), i = 0; i < n; i++) history.Add(NetWorthPointInfo.Read(ref r));
r.Flags();
return new ClimbReport
{
Day = day, Company = company, FoundedDay = founded, InitialCapital = capital, Tier = tier, NextTier = next, Tiers = tiers,
NetWorth = worth, NetWorthRequired = worthRequired, NetWorthFraction = worthFraction, NetWorthMet = worthMet,
Towns = towns, TownsRequired = townsRequired, TownPopulation = townPopulation, TownsFraction = townsFraction, TownsMet = townsMet,
Rating = rating, RatingRequired = ratingRequired, RatingFraction = ratingFraction, RatingMet = ratingMet, Progress = progress,
Assets = assets, Portfolio = portfolio, Cash = cash, TotalAssets = totalAssets, Loans = loans, LoansRate = loansRate,
Overdraft = overdraft, TotalLiabilities = totalLiabilities, BalanceNetWorth = balanceWorth,
IncomeYear = incomeYear, IncomePartial = partial, Income = income, Profit = profit,
LoanList = loanList, MaxLoan = maxLoan, LoanAvailable = available, NewLoanRate = newRate, LoansAllowed = allowed,
History = history,
};
}
}
@@ -32,6 +32,7 @@ public static class MessageCodec
MessageId.IndustryCard => IndustryCard.Read(ref r),
MessageId.Chronicle => Chronicle.Read(ref r),
MessageId.MarketReport => MarketReport.Read(ref r),
MessageId.ClimbReport => ClimbReport.Read(ref r),
MessageId.MarketTape => MarketTape.Read(ref r),
MessageId.CommandResult => CommandResultMessage.Read(ref r),
MessageId.Notification => Notification.Read(ref r),
+3
View File
@@ -661,6 +661,9 @@ public sealed class GameHost : IDisposable
case DetailKind.Market:
s.Send(Projection.Market(w, s.Company));
break;
case DetailKind.Climb:
if (s.Company.IsValid && s.Company.Value < w.Companies.Count) s.Send(Projection.Climb(w, s.Company));
break;
}
}
+36
View File
@@ -553,6 +553,42 @@ public static class Projection
};
}
/// <summary>Quadro della scalata per la compagnia della sessione (ClimbOutlook, ADR 0018).</summary>
public static ClimbReport Climb(World w, CompanyId company)
{
var report = ClimbOutlook.Build(w, company);
var next = report.Next;
var balance = report.Balance;
var income = report.Income;
return new ClimbReport
{
Day = report.Day, Company = report.Company.Value, FoundedDay = report.FoundedDay, InitialCapital = report.InitialCapital,
Tier = (byte)report.Tier, NextTier = (byte)report.NextTier,
Tiers = report.Tiers.Select(t => new TierInfo
{
Level = (byte)t.Level, NameIt = t.NameIt, NameEn = t.NameEn, NetWorthRequired = new Money(t.Requirements.NetWorth),
TownsRequired = t.Requirements.ConnectedTownsOver.Count, TownPopulation = t.Requirements.ConnectedTownsOver.Population,
RatingRequired = t.Requirements.CreditRating.ToString(), Reached = t.Reached, ReachedDay = t.ReachedDay,
Unlocks = t.Unlocks.Select(u => new UnlockInfo { Kind = (byte)u.Kind, Value = u.Value }).ToList(),
}).ToList(),
NetWorth = next?.NetWorth ?? w.Company(company).NetWorth, NetWorthRequired = next?.NetWorthRequired ?? Money.Zero,
NetWorthFraction = (float)(next?.NetWorthFraction ?? 1), NetWorthMet = next?.NetWorthMet ?? true,
Towns = next?.Towns ?? 0, TownsRequired = next?.TownsRequired ?? 0, TownPopulation = next?.TownPopulation ?? 0,
TownsFraction = (float)(next?.TownsFraction ?? 1), TownsMet = next?.TownsMet ?? true,
Rating = w.Company(company).Rating.ToString(), RatingRequired = next?.RatingRequired.ToString() ?? "",
RatingFraction = (float)(next?.RatingFraction ?? 1), RatingMet = next?.RatingMet ?? true, Progress = (float)(next?.Progress ?? 1),
Assets = balance.Assets.Select(a => new AmountInfo { Kind = (byte)a.Category, Value = a.Value }).ToList(),
Portfolio = balance.Portfolio, Cash = balance.Cash, TotalAssets = balance.TotalAssets, Loans = balance.Loans,
LoansRate = (float)balance.LoansRate, Overdraft = balance.Overdraft, TotalLiabilities = balance.TotalLiabilities,
BalanceNetWorth = balance.NetWorth,
IncomeYear = income.Year, IncomePartial = income.Partial,
Income = income.Lines.Select(l => new AmountInfo { Kind = (byte)l.Kind, Value = l.Value }).ToList(), Profit = income.Profit,
LoanList = report.Loans.Select(l => new LoanInfo { Loan = l.Id.Value, Remaining = l.Remaining, AnnualRate = (float)l.AnnualRate, MonthsLeft = l.MonthsLeft }).ToList(),
MaxLoan = report.MaxLoan, LoanAvailable = report.LoanAvailable, NewLoanRate = (float)report.NewLoanRate, LoansAllowed = report.LoansAllowed,
History = report.History.Select(p => new NetWorthPointInfo { Day = p.Day, Value = p.Value }).ToList(),
};
}
/// <summary>Evento del mondo in corso → record del protocollo (ADR 0017).</summary>
public static WorldEventInfo WorldEvent(ActiveWorldEvent e) => new()
{