F5: manutenzione delle industrie, livelli, borsa e scalate, agenti IA

- Sezione 11: usura e recupero degli impianti, fermi e incidenti, ricambi e macchinari come
  domanda esplicita (treno, trasporto locale, trasbordo nel bacino), revisione e ammodernamento,
  acquisto delle industrie dal livello 3, conguaglio mensile con il proprietario (ADR 0011).
- Livelli della compagnia con soglie ritarate e ritaratura economica misurata con le IA.
- Sezione 12.2–12.3: libro dei soci, prezzo con sentiment, quotazione, riacquisto, dividendi,
  controllo e fusione (comando 39), offerte pubbliche con difese, esiti per difficoltà,
  aste delle IA fallite, nuovi concorrenti, fine partita e Cronaca finale (ADR 0012).
- Sezione 12.1: agenti IA con candidati, Dijkstra sulle celle, TrackPreview e ROI, tre
  personalità, linee dei ricambi, rimedio agli stalli, borsa (ADR 0013).
- Salvataggio versione 3, protocollo (messaggi 126–128, blocchi di estensione), server,
  simulate --trace-ai; test di 14.5 su IA e borsa e accettazione F5 (120 test).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0191R7vXgtbAvSV4V8tj8uzL
This commit is contained in:
Claude committed 2026-10-12 10:36:31 +00:00
1 parent 8d2fdd79e5
commit 7879ac502d
72 files changed
+5851 -122

No files matched your search

@@ -46,6 +46,7 @@ public enum CommandType : ushort
AcceptContract = 36,
FundResearch = 37,
DelegateRegion = 38,
MergeCompany = 39,
}
/// <summary>Codici di errore stabili degli esiti dei comandi.</summary>
+25 -2
View File
@@ -26,10 +26,17 @@ public sealed record ScheduleServiceCommand(TrainId Train, string Intervention)
public override CommandType Type => CommandType.ScheduleService;
}
/// <summary>Ordina ricambi per un deposito (domanda esplicita sul grafo delle linee).</summary>
/// <summary>
/// Ordina ricambi (domanda esplicita sul grafo delle linee): per un deposito fissa la scorta
/// desiderata; con <see cref="Industry"/> valido ordina la quantità indicata oltre la scorta della
/// politica di un'industria posseduta (sezione 11).
/// </summary>
public sealed record OrderPartsCommand(DepotId Depot, int Quantity) : GameCommand
{
public override CommandType Type => CommandType.OrderParts;
/// <summary>Industria destinataria (blocco 1 del protocollo); None per i depositi.</summary>
public IndustryId Industry { get; init; } = IndustryId.None;
}
/// <summary>Accetta una convenzione di pendolarismo proposta da un'industria.</summary>
@@ -104,10 +111,26 @@ public sealed record LaunchBidCommand(CompanyId Target, Money PricePerShare, dou
public override CommandType Type => CommandType.LaunchBid;
}
/// <summary>Risposta a un'offerta pubblica (azionisti del bersaglio).</summary>
/// <summary>
/// Risposta a un'offerta pubblica: un'azionista aderisce (Accept) con tutte le sue azioni; il
/// bersaglio può difendersi (blocco 1 del protocollo) con riacquisto, dividendo straordinario o
/// cavaliere bianco (12.2).
/// </summary>
public sealed record RespondBidCommand(BidId Bid, bool Accept) : GameCommand
{
public override CommandType Type => CommandType.RespondBid;
/// <summary>Difesa del bersaglio (None per l'adesione degli azionisti).</summary>
public Economy.BidDefense Defense { get; init; }
/// <summary>Compagnia alleata chiamata come cavaliere bianco.</summary>
public CompanyId Knight { get; init; } = CompanyId.None;
}
/// <summary>Fusione di una controllata posseduta da almeno un anno (12.2); id 39, aggiunto in F5.</summary>
public sealed record MergeCompanyCommand(CompanyId Subsidiary) : GameCommand
{
public override CommandType Type => CommandType.MergeCompany;
}
/// <summary>Acquisto della concessione di una regione.</summary>
+73
View File
@@ -9,6 +9,7 @@ public sealed class AiFile
[JsonPropertyName("$schema")] public string? Schema { get; init; }
public required int Version { get; init; }
public required AiPlanningParams Planning { get; init; }
public required AiMarketParams Market { get; init; }
public required List<AiPersonalityDef> Personalities { get; init; }
public required List<string> CompanyNames { get; init; }
public required List<string> Colors { get; init; }
@@ -23,11 +24,83 @@ public sealed class AiPlanningParams
public required double CandidateMinDistanceKm { get; init; }
public required double PathSlopePenalty { get; init; }
public required double PathWaterPenalty { get; init; }
/// <summary>Costo aggiunto per cella con pendenza del terreno oltre SteepGradeFactor × pendenza massima.</summary>
public required double SteepPenalty { get; init; }
public required double SteepGradeFactor { get; init; }
/// <summary>Margine più ampio per un secondo tentativo di ricerca del percorso.</summary>
public required double PathMarginRetryKm { get; init; }
public required int TrainsPerLine { get; init; }
public required int WagonsPerTrain { get; init; }
public required double CashReserveMonths { get; init; }
public required double RevenueHorizonYears { get; init; }
public required double MaxRejectedShare { get; init; }
/// <summary>Progetti in costruzione contemporaneamente.</summary>
public required int MaxConcurrentProjects { get; init; }
/// <summary>Candidati migliori (stima in linea d'aria) valutati con percorso e piano dei binari.</summary>
public required int EvaluateTop { get; init; }
/// <summary>Margine attorno ai due estremi per la ricerca del percorso sulle celle.</summary>
public required double PathMarginKm { get; init; }
public required double SimplifyToleranceM { get; init; }
/// <summary>Distanze provate per la stazione dal centro dell'industria o dal bordo della città.</summary>
public required double[] StationOffsetsM { get; init; }
public required double DepotOffsetM { get; init; }
public required int Platforms { get; init; }
/// <summary>Binari della stazione del deposito, nodo della rete per le linee successive.</summary>
public required int HubPlatforms { get; init; }
/// <summary>Efficienza attesa delle industrie servite (stima dei volumi).</summary>
public required double AssumedEfficiency { get; init; }
/// <summary>Velocità media come quota della massima (salite, curve, frenate).</summary>
public required double SpeedFactor { get; init; }
public required double DwellMinutes { get; init; }
/// <summary>Manutenzione della flotta stimata in quota del costo d'esercizio.</summary>
public required double MaintenanceCostShare { get; init; }
public required long TrackUpkeepPerKmPerYear { get; init; }
public required int MaxTrainsPerLine { get; init; }
/// <summary>Si aggiunge un treno quando in stazione aspetta più di questi carichi pieni.</summary>
public required double AddTrainWaitingTrips { get; init; }
public required int MinCommuters { get; init; }
/// <summary>Copertura attesa dei pendolari (treni in officina, attese, scioglimenti).</summary>
public required double CommuterCoverage { get; init; }
/// <summary>Quota della capacità di un hub che una linea d'esportazione può aspettarsi.</summary>
public required double HubShare { get; init; }
/// <summary>Peso di una rete nuova senza fonti di ricambi vicine (servirà una linea apposta).</summary>
public required double NoPartsFactor { get; init; }
/// <summary>Peso delle linee che collegano una città quando il prossimo livello ne chiede.</summary>
public required double TownBonus { get; init; }
/// <summary>Riduzione della soglia di ROI per le linee che collegano città quando servono al livello.</summary>
public required double TownRoiFactor { get; init; }
/// <summary>Si rimborsano prestiti quando la cassa supera questi mesi di costi.</summary>
public required double RepayCashMonths { get; init; }
/// <summary>Distanza in giorni tra i giorni di pianificazione delle diverse IA.</summary>
public required int PlanningDaySpacing { get; init; }
/// <summary>Candidati falliti ricordati per non riprovarli.</summary>
public required int FailedMemory { get; init; }
}
/// <summary>Comportamento in borsa delle IA (12.1–12.2).</summary>
public sealed class AiMarketParams
{
/// <summary>Premio oltre il quale il proprietario privato di un'IA cede le sue azioni a un'offerta.</summary>
public required double FounderAcceptPremium { get; init; }
/// <summary>Premio oltre il quale un'IA azionista aderisce a un'offerta.</summary>
public required double HolderAcceptPremium { get; init; }
/// <summary>Quota che una Predatoria accumula nei concorrenti prima di lanciare un'offerta.</summary>
public required double PredatoryStakeTarget { get; init; }
/// <summary>Quota della cassa libera destinata ogni mese agli acquisti di azioni.</summary>
public required double SharesCashShare { get; init; }
public required double BidMinStake { get; init; }
public required double BidPremium { get; init; }
/// <summary>Cassa richiesta (multiplo del costo) per lanciare un'offerta.</summary>
public required double BidCashMultiple { get; init; }
public required double BuybackCashShare { get; init; }
/// <summary>Cassa (multiplo del costo) con cui un'IA accetta di fare da cavaliere bianco.</summary>
public required double KnightCashMultiple { get; init; }
/// <summary>Flottante massimo che un'IA raggiunge con gli aumenti di capitale.</summary>
public required double IssueFloatMax { get; init; }
/// <summary>Quota del capitale collocata a ogni aumento.</summary>
public required double IssueShare { get; init; }
public required double IndustryMaxCashShare { get; init; }
public required double IndustryMinMargin { get; init; }
}
public sealed class AiPersonalityDef
+65
View File
@@ -377,6 +377,41 @@ public sealed class StockMarketBalance
public required int BidDurationDays { get; init; }
public required double RansomShare { get; init; }
public required double ReceivershipDividend { get; init; }
/// <summary>Peso della crescita degli utili sul sentiment (crescita relativa, limitata a ±1).</summary>
public required double SentimentEarningsWeight { get; init; }
/// <summary>Peso del ciclo di mercato mondiale (A·sin(2πt/T)) sul sentiment.</summary>
public required double SentimentCycleWeight { get; init; }
/// <summary>Peso del rendimento dei dividendi degli ultimi 12 mesi sul sentiment.</summary>
public required double SentimentDividendWeight { get; init; }
public required int SentimentSmoothingDays { get; init; }
/// <summary>Spinta temporanea del dividendo straordinario (difesa), che decade linearmente.</summary>
public required double ExtraDividendSentimentBoost { get; init; }
public required int ExtraDividendDecayDays { get; init; }
/// <summary>Flottante delle compagnie IA all'inizio (quotate dall'inizio).</summary>
public required double AiFloatAtStart { get; init; }
/// <summary>Quota del flottante residuo che aderisce ogni giorno a un'offerta con il premio minimo.</summary>
public required double TenderDailyShare { get; init; }
/// <summary>Quota della cassa pagata come dividendo straordinario nella difesa.</summary>
public required double ExtraDividendCashShare { get; init; }
/// <summary>Premio del cavaliere bianco sul prezzo dell'offerta ostile.</summary>
public required double WhiteKnightPremium { get; init; }
/// <summary>Premio sul prezzo di mercato per riscattare azioni dal controllante in amministrazione controllata.</summary>
public required double RansomPremium { get; init; }
/// <summary>Massimo di azioni scambiabili al giorno da una compagnia, in quota del capitale.</summary>
public required double MaxDailyTradeShare { get; init; }
/// <summary>Flottante massimo raggiungibile con gli aumenti di capitale di chi è già quotato.</summary>
public required double SecondaryMaxFloat { get; init; }
public required int PriceHistoryMonths { get; init; }
/// <summary>Durata dell'asta degli attivi di una compagnia fallita.</summary>
public required int AuctionDays { get; init; }
/// <summary>Prezzo minimo dell'asta in quota del valore di libro degli attivi.</summary>
public required double AuctionMinBookShare { get; init; }
/// <summary>Quota di mercato oltre la quale entra un nuovo concorrente (12.1).</summary>
public required double ConcentrationThreshold { get; init; }
public required int NewCompetitorCooldownYears { get; init; }
public required int MaxCompanies { get; init; }
/// <summary>Anni di storico per compagnia conservati (Cronaca finale).</summary>
public required int HistoryYears { get; init; }
}
public sealed class IndustryMaintenanceBalance
@@ -404,6 +439,36 @@ public sealed class IndustryMaintenanceBalance
public required int NpcUpgradeYears { get; init; }
public required double NpcHighMargin { get; init; }
public required double NpcOverhaulBelow { get; init; }
/// <summary>Scorta di ricambi desiderata in mesi di consumo della politica.</summary>
public required double PartsTargetMonths { get; init; }
/// <summary>Scorta iniziale di ricambi in mesi di consumo (politica Base).</summary>
public required double InitialPartsMonths { get; init; }
/// <summary>Massimo di ricambi ordinabili oltre la scorta desiderata («Ordina ricambi»).</summary>
public required int MaxOrderedParts { get; init; }
/// <summary>Raggio entro cui un fermo o un incidente colpisce la città più vicina.</summary>
public required double TownEffectRadiusKm { get; init; }
public required int StopHistoryLength { get; init; }
/// <summary>Cassa che un'industria di una compagnia trattiene; ogni mese il resto va al proprietario (o lo chiede).</summary>
public required long OwnerCashReserve { get; init; }
public required IndustryPurchaseParams Purchase { get; init; }
public IndustryBudgetParams For(Economy.IndustryBudget budget) => Budgets[budget switch
{
Economy.IndustryBudget.None => "none",
Economy.IndustryBudget.High => "high",
_ => "base",
}];
}
/// <summary>Valutazione di un'industria in vendita (BuyIndustry).</summary>
public sealed class IndustryPurchaseParams
{
/// <summary>Quota del costo di ammodernamento cumulato riconosciuta come valore degli impianti.</summary>
public required double AssetShare { get; init; }
/// <summary>Multiplo dell'utile annuo stimato.</summary>
public required double EarningsMultiple { get; init; }
/// <summary>Peso della condizione sul valore degli impianti: valore × (1 − peso + peso·c/100).</summary>
public required double ConditionWeight { get; init; }
}
public sealed class IndustryBudgetParams
+82 -5
View File
@@ -25,6 +25,10 @@ public enum LedgerEntry : byte
Contracts = 16,
Penalties = 17,
Other = 18,
/// <summary>Conguaglio mensile con le industrie possedute (utili versati o perdite coperte).</summary>
Industries = 19,
/// <summary>Utili versati dalle compagnie controllate.</summary>
Subsidiaries = 20,
}
/// <summary>Prestito con rata costante (ammortamento alla francese).</summary>
@@ -41,7 +45,7 @@ public sealed class Loan
/// <summary>Compagnia ferroviaria (giocatore o IA).</summary>
public sealed class Company
{
public const int EntryCount = 19;
public const int EntryCount = 21;
public required CompanyId Id { get; init; }
public required string Name { get; set; }
@@ -86,14 +90,86 @@ public sealed class Company
}
}
/// <summary>Patrimonio netto = cassa + attivi a valore di libro − debiti.</summary>
public Money NetWorth => Cash + AssetBookValue - Debt;
/// <summary>Valore di mercato delle azioni di altre compagnie possedute (aggiornato ogni giorno dalla borsa).</summary>
public Money PortfolioValue { get; set; }
/// <summary>Patrimonio netto = cassa + attivi a valore di libro + partecipazioni − debiti.</summary>
public Money NetWorth => Cash + AssetBookValue + PortfolioValue - Debt;
// ------------------------------------------------------------------ borsa e controllo (12.2)
/// <summary>Libro dei soci.</summary>
public ShareRegister Shares { get; } = new();
/// <summary>Quotata in borsa (le azioni del flottante si scambiano).</summary>
public bool Listed { get; set; }
/// <summary>Prezzo per azione (centesimi, frazionario) e sentiment corrente.</summary>
public double SharePrice { get; set; }
public double Sentiment { get; set; } = 1;
/// <summary>Spinta del dividendo straordinario, che decade ogni giorno.</summary>
public double ExtraSentiment { get; set; }
/// <summary>Utile operativo degli ultimi 12 mesi chiusi (anello mensile) e indice del prossimo mese.</summary>
public long[] ProfitRing { get; } = new long[12];
public int ProfitRingIndex { get; set; }
/// <summary>Dividendi pagati negli ultimi 12 mesi (anello mensile, centesimi).</summary>
public long[] DividendRing { get; } = new long[12];
/// <summary>Utile dei 12 mesi alla chiusura dell'anno precedente (per la crescita).</summary>
public long LastAnnualProfit { get; set; }
/// <summary>Compagnia che controlla questa (oltre la soglia di controllo) e da quando.</summary>
public CompanyId ControlledBy { get; set; } = CompanyId.None;
public long ControlSinceDay { get; set; } = -1;
/// <summary>Fusa in un'altra compagnia: non esiste più come impresa autonoma.</summary>
public bool Merged { get; set; }
public CompanyId MergedInto { get; set; } = CompanyId.None;
/// <summary>Amministrazione controllata del giocatore (12.3): fino a quando e sotto chi.</summary>
public bool Receivership { get; set; }
public long ReceivershipUntilDay { get; set; } = -1;
public CompanyId ReceivershipBy { get; set; } = CompanyId.None;
/// <summary>Giorno della bancarotta (−1 se attiva) e attivi già liquidati.</summary>
public long BankruptDay { get; set; } = -1;
public bool Liquidated { get; set; }
/// <summary>Storico dei prezzi dell'azione, un valore al mese (centesimi).</summary>
public List<double> PriceHistory { get; } = [];
/// <summary>Fotografie annuali per la Cronaca finale.</summary>
public List<CompanyYear> History { get; } = [];
/// <summary>Fatti salienti (livelli, quotazione, scalate, fusioni) per la Cronaca finale.</summary>
public List<CompanyMilestone> Milestones { get; } = [];
/// <summary>Compagnia fuori gioco: fallita o fusa.</summary>
public bool Defunct => Bankrupt || Merged;
/// <summary>Utile operativo degli ultimi 12 mesi chiusi.</summary>
public long AnnualProfit
{
get
{
long sum = 0;
foreach (long p in ProfitRing) sum += p;
return sum;
}
}
/// <summary>Capitalizzazione di borsa (centesimi).</summary>
public double MarketCap => SharePrice * Shares.Outstanding;
/// <summary>Utile operativo dell'anno indicato (ricavi meno costi d'esercizio, esclusi prestiti e investimenti).</summary>
public static long OperatingProfit(long[] entries)
{
long revenue = entries[(int)LedgerEntry.FreightRevenue] + entries[(int)LedgerEntry.PassengerRevenue]
+ entries[(int)LedgerEntry.Trading] + entries[(int)LedgerEntry.Contracts];
+ entries[(int)LedgerEntry.Trading] + entries[(int)LedgerEntry.Contracts]
+ entries[(int)LedgerEntry.Industries] + entries[(int)LedgerEntry.Subsidiaries];
long costs = entries[(int)LedgerEntry.RunningCosts] + entries[(int)LedgerEntry.TrackMaintenance]
+ entries[(int)LedgerEntry.FleetMaintenance] + entries[(int)LedgerEntry.Wages]
+ entries[(int)LedgerEntry.Interest] + entries[(int)LedgerEntry.Penalties];
@@ -102,5 +178,6 @@ public sealed class Company
public static long Revenue(long[] entries) =>
entries[(int)LedgerEntry.FreightRevenue] + entries[(int)LedgerEntry.PassengerRevenue]
+ Math.Max(0, entries[(int)LedgerEntry.Trading]) + Math.Max(0, entries[(int)LedgerEntry.Contracts]);
+ Math.Max(0, entries[(int)LedgerEntry.Trading]) + Math.Max(0, entries[(int)LedgerEntry.Contracts])
+ Math.Max(0, entries[(int)LedgerEntry.Industries]) + Math.Max(0, entries[(int)LedgerEntry.Subsidiaries]);
}
+1 -1
View File
@@ -96,7 +96,7 @@ public sealed class CommuteAgreement
{
public required AgreementId Id { get; init; }
public required IndustryId Industry { get; init; }
public required CompanyId Carrier { get; init; }
public required CompanyId Carrier { get; set; }
public required int SeatsPerDay { get; init; }
public required Money MonthlyFee { get; init; }
public required long ProposedDay { get; init; }
+41
View File
@@ -6,6 +6,15 @@ namespace ViaFerrea.Core.Economy;
/// <summary>Budget di manutenzione degli impianti scelto dal proprietario (guida, sezione 11).</summary>
public enum IndustryBudget : byte { None = 0, Base = 1, High = 2 }
/// <summary>Motivo di un fermo dell'industria (sezione 11).</summary>
public enum IndustryStop : byte { None = 0, Breakdown = 1, Accident = 2, Overhaul = 3, Upgrade = 4 }
/// <summary>Lavoro programmato in attesa di macchinari (e personale, per la revisione).</summary>
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>
/// Industria: produce secondo la ricetta del suo tipo, con efficienza
/// e = min(copertura input, lavoratori, personale) × fattore di profitto × condizione impianti.
@@ -39,6 +48,38 @@ public sealed class Industry : IWorkplace
public IndustryBudget Budget { get; set; } = IndustryBudget.Base;
/// <summary>Scorta di ricambi e macchinari per la manutenzione degli impianti (sezione 11).</summary>
public int SpareParts { get; set; }
public int Machinery { get; set; }
/// <summary>Ricambi ordinati dal proprietario oltre la scorta desiderata («Ordina ricambi»).</summary>
public int PartsOrdered { get; set; }
/// <summary>Ultimo consumo mensile di ricambi non coperto: il recupero è dimezzato.</summary>
public bool PartsShort { get; set; }
/// <summary>Fermo in corso fino al giorno indicato (escluso); −1 se l'industria lavora.</summary>
public long StoppedUntilDay { get; set; } = -1;
public IndustryStop StopKind { get; set; }
/// <summary>Lavoro programmato che aspetta macchinari o personale per iniziare.</summary>
public IndustryWork PendingWork { get; set; }
/// <summary>Ultimi fermi (il più recente in coda).</summary>
public List<IndustryStopRecord> StopHistory { get; } = [];
/// <summary>Mesi consecutivi con margine sopra la soglia di ammodernamento dei privati.</summary>
public int MonthsHighMargin { get; set; }
/// <summary>Spesa di manutenzione degli impianti dell'anno corrente (centesimi).</summary>
public long MaintenanceSpentYear { get; set; }
/// <summary>Giorno d'acquisto da parte della compagnia proprietaria (−1 se privata).</summary>
public long AcquiredDay { get; set; } = -1;
/// <summary>Fermo in corso nel giorno dato.</summary>
public bool IsStopped(long day) => StoppedUntilDay > day;
/// <summary>Scorte degli input, allineate a Def.Recipe.Inputs.</summary>
public int[] InputStock { get; init; } = [];
+120
View File
@@ -0,0 +1,120 @@
using ViaFerrea.Core.Common;
namespace ViaFerrea.Core.Economy;
/// <summary>
/// Libro dei soci di una compagnia (12.2): fondatore (il giocatore o il proprietario privato
/// dell'IA), flottante sul mercato, azioni proprie riacquistate (non votano) e quote delle altre
/// compagnie. Il totale resta sempre il numero di azioni della compagnia.
/// </summary>
public sealed class ShareRegister
{
public long Total { get; set; }
public long Founder { get; set; }
public long Public { get; set; }
public long Treasury { get; set; }
/// <summary>Quote delle compagnie, indicizzate per id (cresce con le compagnie).</summary>
public long[] ByCompany { get; set; } = [];
/// <summary>Azioni in circolazione (escluse le proprie): base del controllo e del prezzo per azione.</summary>
public long Outstanding => Total - Treasury;
public long Of(CompanyId holder) => holder.IsValid && holder.Value < ByCompany.Length ? ByCompany[holder.Value] : 0;
public void Add(CompanyId holder, long shares)
{
if (holder.Value >= ByCompany.Length)
{
var grown = new long[holder.Value + 1];
Array.Copy(ByCompany, grown, ByCompany.Length);
ByCompany = grown;
}
ByCompany[holder.Value] += shares;
}
/// <summary>Quota di voto del titolare sulle azioni in circolazione.</summary>
public double FractionOf(CompanyId holder) => Outstanding > 0 ? (double)Of(holder) / Outstanding : 0;
public double FounderFraction => Outstanding > 0 ? (double)Founder / Outstanding : 0;
/// <summary>Somma dei titolari (verifica d'invarianza: deve valere Total).</summary>
public long Sum()
{
long sum = Founder + Public + Treasury;
foreach (long s in ByCompany) sum += s;
return sum;
}
}
/// <summary>Stato di un'offerta pubblica di acquisto (12.2).</summary>
public enum BidState : byte { Open = 0, Succeeded = 1, Failed = 2, Withdrawn = 3 }
/// <summary>Difese del bersaglio (RespondBid dal bersaglio).</summary>
public enum BidDefense : byte { None = 0, Buyback = 1, ExtraDividend = 2, WhiteKnight = 3 }
/// <summary>
/// Offerta pubblica di acquisto: premio sul prezzo di mercato, durata, adesioni del flottante e
/// delle compagnie azioniste; si conclude quando le adesioni bastano o alla scadenza.
/// </summary>
public sealed class TakeoverBid
{
public required BidId Id { get; init; }
public required CompanyId Bidder { get; init; }
public required CompanyId Target { get; init; }
/// <summary>Prezzo offerto per azione (centesimi).</summary>
public required long PricePerShare { get; init; }
/// <summary>Quota del capitale in circolazione che l'offerente vuole raggiungere.</summary>
public required double TargetShare { get; init; }
public required long StartDay { get; init; }
public required long EndDay { get; init; }
public BidState State { get; set; }
/// <summary>Azioni del flottante che hanno aderito (vincolate fino all'esito).</summary>
public long TenderedPublic { get; set; }
/// <summary>Azioni del fondatore che hanno aderito (solo se il fondatore è un privato che accetta).</summary>
public long TenderedFounder { get; set; }
/// <summary>Compagnie azioniste che hanno aderito con tutte le loro azioni.</summary>
public List<CompanyId> Accepted { get; } = [];
/// <summary>Difese usate dal bersaglio (bit di <see cref="BidDefense"/>).</summary>
public byte Defenses { get; set; }
/// <summary>Cavaliere bianco intervenuto, se c'è.</summary>
public CompanyId Knight { get; set; } = CompanyId.None;
public long ClosedDay { get; set; } = -1;
}
/// <summary>Asta degli attivi di una compagnia fallita (12.1): vince l'offerta più alta alla scadenza.</summary>
public sealed class Auction
{
public required CompanyId Seller { get; init; }
public required long StartDay { get; init; }
public required long EndDay { get; init; }
public required long MinPriceCents { get; init; }
public CompanyId BestBidder { get; set; } = CompanyId.None;
public long BestPriceCents { get; set; }
public bool Closed { get; set; }
}
/// <summary>Fotografia annuale di una compagnia per la Cronaca finale e i grafici.</summary>
public readonly record struct CompanyYear(int Year, long NetWorthCents, long CashCents, long RevenueCents, long ProfitCents,
int Tier, int Trains, double TrackKm, long SharePriceCents);
/// <summary>Fatto saliente della storia di una compagnia.</summary>
public readonly record struct CompanyMilestone(long Day, string Text);
/// <summary>Esito della partita del giocatore (12.3).</summary>
public enum GameOverReason : byte { None = 0, Bankruptcy = 1, Takeover = 2, ReceivershipExpired = 3 }
/// <summary>Fine della partita: il mondo prosegue in modalità osservatore.</summary>
public sealed class GameOverState
{
public required long Day { get; init; }
public required GameOverReason Reason { get; init; }
public required string Text { get; init; }
public CompanyId Winner { get; init; } = CompanyId.None;
}
@@ -0,0 +1,352 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Simulation;
using ViaFerrea.Core.Simulation.Ai;
namespace ViaFerrea.Core.Persistence;
/// <summary>
/// Stato della fase F5 (corpo del salvataggio dalla versione 3): manutenzione e proprietà delle
/// industrie, borsa, controllo e storico delle compagnie, offerte pubbliche, aste, fine partita e
/// agenti IA. I salvataggi precedenti si migrano con valori iniziali coerenti (ADR 0012).
/// </summary>
public static class CorporateSerializer
{
public static void Write(World w, SaveWriter s)
{
s.Write(w.Industries.Count);
foreach (var ind in w.Industries)
{
s.Write(ind.SpareParts);
s.Write(ind.Machinery);
s.Write(ind.PartsOrdered);
s.Write(ind.PartsShort);
s.Write(ind.StoppedUntilDay);
s.Write((byte)ind.StopKind);
s.Write((byte)ind.PendingWork);
s.Write(ind.MonthsHighMargin);
s.Write(ind.MaintenanceSpentYear);
s.Write(ind.AcquiredDay);
s.Write(ind.StopHistory.Count);
foreach (var h in ind.StopHistory)
{
s.Write(h.Day);
s.Write(h.Days);
s.Write((byte)h.Kind);
}
}
s.Write(w.Companies.Count);
foreach (var c in w.Companies)
{
var sh = c.Shares;
s.Write(sh.Total);
s.Write(sh.Founder);
s.Write(sh.Public);
s.Write(sh.Treasury);
s.Write(sh.ByCompany);
s.Write(c.Listed);
s.Write(c.SharePrice);
s.Write(c.Sentiment);
s.Write(c.ExtraSentiment);
s.Write(c.ProfitRing);
s.Write(c.ProfitRingIndex);
s.Write(c.DividendRing);
s.Write(c.LastAnnualProfit);
s.Write(c.PortfolioValue.Cents);
s.Write(c.ControlledBy.Value);
s.Write(c.ControlSinceDay);
s.Write(c.Merged);
s.Write(c.MergedInto.Value);
s.Write(c.Receivership);
s.Write(c.ReceivershipUntilDay);
s.Write(c.ReceivershipBy.Value);
s.Write(c.BankruptDay);
s.Write(c.Liquidated);
s.Write(c.PriceHistory.ToArray());
s.Write(c.History.Count);
foreach (var y in c.History)
{
s.Write(y.Year);
s.Write(y.NetWorthCents);
s.Write(y.CashCents);
s.Write(y.RevenueCents);
s.Write(y.ProfitCents);
s.Write(y.Tier);
s.Write(y.Trains);
s.Write(y.TrackKm);
s.Write(y.SharePriceCents);
}
s.Write(c.Milestones.Count);
foreach (var m in c.Milestones)
{
s.Write(m.Day);
s.Write(m.Text);
}
}
s.Write(w.Bids.Count);
foreach (var b in w.Bids)
{
s.Write(b.Id.Value);
s.Write(b.Bidder.Value);
s.Write(b.Target.Value);
s.Write(b.PricePerShare);
s.Write(b.TargetShare);
s.Write(b.StartDay);
s.Write(b.EndDay);
s.Write((byte)b.State);
s.Write(b.TenderedPublic);
s.Write(b.TenderedFounder);
s.Write(b.Accepted.Select(a => a.Value).ToArray());
s.Write(b.Defenses);
s.Write(b.Knight.Value);
s.Write(b.ClosedDay);
}
s.Write(w.Auctions.Count);
foreach (var a in w.Auctions)
{
s.Write(a.Seller.Value);
s.Write(a.StartDay);
s.Write(a.EndDay);
s.Write(a.MinPriceCents);
s.Write(a.BestBidder.Value);
s.Write(a.BestPriceCents);
s.Write(a.Closed);
}
s.Write(w.GameOver is not null);
if (w.GameOver is { } g)
{
s.Write(g.Day);
s.Write((byte)g.Reason);
s.Write(g.Text);
s.Write(g.Winner.Value);
}
s.Write(w.LastCompetitorYear);
s.Write(w.AiPaused);
s.Write(w.AiStates.Count);
foreach (var a in w.AiStates)
{
s.Write(a.Company.Value);
s.Write(a.PlanDay);
s.Write(a.Issued);
s.Write(a.Rejected);
s.Write(a.PolicySet);
s.Write(a.NextProjectId);
s.Write(a.LastIndustryYear);
s.Write(a.LastGridlockDay);
s.Write(a.Failed.ToArray());
s.Write(a.Responded.ToArray());
s.Write(a.Projects.Count);
foreach (var p in a.Projects)
{
s.Write(p.Id);
s.Write((byte)p.Kind);
s.Write(p.Good);
s.Write(p.PaxClass);
s.Write(p.Key);
s.Write(p.StationA.Value);
s.Write(p.StationB.Value);
s.Write(p.Depot.Value);
s.Write(p.Edges.Select(e => e.Value).ToArray());
s.Write(p.Line.Value);
s.Write(p.Trains.Select(t => t.Value).ToArray());
s.Write((byte)p.Stage);
s.Write(p.StartDay);
s.Write(p.CapitalCents);
s.Write(p.RevenuePerYearCents);
s.Write(p.TrainsPlanned);
s.Write(p.Loco);
s.Write(p.Car);
s.Write(p.CarsPerTrain);
s.Write(p.GrowAfterDay);
s.Write(p.SupplyFor.Value);
}
}
}
public static void Read(World w, SaveReader r)
{
int industries = r.ReadInt32();
for (int i = 0; i < industries; i++)
{
var ind = w.Industries[i];
ind.SpareParts = r.ReadInt32();
ind.Machinery = r.ReadInt32();
ind.PartsOrdered = r.ReadInt32();
ind.PartsShort = r.ReadBool();
ind.StoppedUntilDay = r.ReadInt64();
ind.StopKind = (IndustryStop)r.ReadByte();
ind.PendingWork = (IndustryWork)r.ReadByte();
ind.MonthsHighMargin = r.ReadInt32();
ind.MaintenanceSpentYear = r.ReadInt64();
ind.AcquiredDay = r.ReadInt64();
int history = r.ReadInt32();
for (int h = 0; h < history; h++) ind.StopHistory.Add(new IndustryStopRecord(r.ReadInt64(), r.ReadInt32(), (IndustryStop)r.ReadByte()));
}
int companies = r.ReadInt32();
for (int i = 0; i < companies; i++)
{
var c = w.Companies[i];
var sh = c.Shares;
sh.Total = r.ReadInt64();
sh.Founder = r.ReadInt64();
sh.Public = r.ReadInt64();
sh.Treasury = r.ReadInt64();
sh.ByCompany = r.ReadInt64Array();
c.Listed = r.ReadBool();
c.SharePrice = r.ReadDouble();
c.Sentiment = r.ReadDouble();
c.ExtraSentiment = r.ReadDouble();
CopyInto(r.ReadInt64Array(), c.ProfitRing);
c.ProfitRingIndex = r.ReadInt32();
CopyInto(r.ReadInt64Array(), c.DividendRing);
c.LastAnnualProfit = r.ReadInt64();
c.PortfolioValue = new Money(r.ReadInt64());
c.ControlledBy = new CompanyId(r.ReadInt32());
c.ControlSinceDay = r.ReadInt64();
c.Merged = r.ReadBool();
c.MergedInto = new CompanyId(r.ReadInt32());
c.Receivership = r.ReadBool();
c.ReceivershipUntilDay = r.ReadInt64();
c.ReceivershipBy = new CompanyId(r.ReadInt32());
c.BankruptDay = r.ReadInt64();
c.Liquidated = r.ReadBool();
c.PriceHistory.AddRange(r.ReadDoubleArray());
int years = r.ReadInt32();
for (int y = 0; y < years; y++)
{
c.History.Add(new CompanyYear(r.ReadInt32(), r.ReadInt64(), r.ReadInt64(), r.ReadInt64(), r.ReadInt64(),
r.ReadInt32(), r.ReadInt32(), r.ReadDouble(), r.ReadInt64()));
}
int milestones = r.ReadInt32();
for (int m = 0; m < milestones; m++) c.Milestones.Add(new CompanyMilestone(r.ReadInt64(), r.ReadRequiredString()));
}
int bids = r.ReadInt32();
for (int i = 0; i < bids; i++)
{
var b = new TakeoverBid
{
Id = new BidId(r.ReadInt32()),
Bidder = new CompanyId(r.ReadInt32()),
Target = new CompanyId(r.ReadInt32()),
PricePerShare = r.ReadInt64(),
TargetShare = r.ReadDouble(),
StartDay = r.ReadInt64(),
EndDay = r.ReadInt64(),
};
b.State = (BidState)r.ReadByte();
b.TenderedPublic = r.ReadInt64();
b.TenderedFounder = r.ReadInt64();
foreach (int a in r.ReadInt32Array()) b.Accepted.Add(new CompanyId(a));
b.Defenses = r.ReadByte();
b.Knight = new CompanyId(r.ReadInt32());
b.ClosedDay = r.ReadInt64();
w.Bids.Add(b);
}
int auctions = r.ReadInt32();
for (int i = 0; i < auctions; i++)
{
var a = new Auction
{
Seller = new CompanyId(r.ReadInt32()),
StartDay = r.ReadInt64(),
EndDay = r.ReadInt64(),
MinPriceCents = r.ReadInt64(),
};
a.BestBidder = new CompanyId(r.ReadInt32());
a.BestPriceCents = r.ReadInt64();
a.Closed = r.ReadBool();
w.Auctions.Add(a);
}
if (r.ReadBool())
{
w.GameOver = new GameOverState
{
Day = r.ReadInt64(),
Reason = (GameOverReason)r.ReadByte(),
Text = r.ReadRequiredString(),
Winner = new CompanyId(r.ReadInt32()),
};
}
w.LastCompetitorYear = r.ReadInt32();
w.AiPaused = r.ReadBool();
int states = r.ReadInt32();
for (int i = 0; i < states; i++)
{
var a = new AiState { Company = new CompanyId(r.ReadInt32()), PlanDay = r.ReadInt32() };
a.Issued = r.ReadInt64();
a.Rejected = r.ReadInt64();
a.PolicySet = r.ReadBool();
a.NextProjectId = r.ReadInt32();
a.LastIndustryYear = r.ReadInt32();
a.LastGridlockDay = r.ReadInt64();
a.Failed.AddRange(r.ReadInt64Array());
a.Responded.AddRange(r.ReadInt32Array());
int projects = r.ReadInt32();
for (int p = 0; p < projects; p++)
{
int id = r.ReadInt32();
var kind = (AiProjectKind)r.ReadByte();
int good = r.ReadInt32(), paxClass = r.ReadInt32();
long key = r.ReadInt64();
var stationA = new StationId(r.ReadInt32());
var stationB = new StationId(r.ReadInt32());
var depot = new DepotId(r.ReadInt32());
int[] edges = r.ReadInt32Array();
var line = new LineId(r.ReadInt32());
int[] trains = r.ReadInt32Array();
var stage = (AiProjectStage)r.ReadByte();
var project = new AiProject
{
Id = id, Kind = kind, Good = good, PaxClass = paxClass, Key = key,
StationA = stationA, StationB = stationB, Depot = depot, Line = line, Stage = stage,
StartDay = r.ReadInt64(),
CapitalCents = r.ReadInt64(),
RevenuePerYearCents = r.ReadInt64(),
TrainsPlanned = r.ReadInt32(),
Loco = r.ReadRequiredString(),
Car = r.ReadRequiredString(),
CarsPerTrain = r.ReadInt32(),
GrowAfterDay = r.ReadInt64(),
SupplyFor = new DepotId(r.ReadInt32()),
};
foreach (int e in edges) project.Edges.Add(new EdgeId(e));
foreach (int t in trains) project.Trains.Add(new TrainId(t));
a.Projects.Add(project);
}
w.AiStates.Add(a);
}
}
/// <summary>
/// Migrazione dei salvataggi precedenti a F5: ricambi iniziali delle industrie, libro dei soci
/// come in una partita nuova, prezzi delle azioni, agenti IA senza progetti.
/// </summary>
public static void Migrate(World w)
{
var im = w.Data.Balance.IndustryMaintenance;
foreach (var ind in w.Industries)
{
ind.SpareParts = (int)Math.Round(Simulation.Systems.IndustryMath.MonthlyPartsUse(ind, im) * im.InitialPartsMonths);
w.Goods.Produced[w.Data.SparePartsGood] += ind.SpareParts;
}
var d = w.Difficulty;
foreach (var c in w.Companies)
{
if (c.IsPlayer) Corporate.InitShares(w, c, d.PublicFromStart, d.PublicFromStart ? d.PlayerShareAtStart : 1.0);
else Corporate.InitShares(w, c, listed: true, 1 - w.Data.Balance.StockMarket.AiFloatAtStart);
}
AiSystem.EnsureStates(w);
}
private static void CopyInto(long[] source, long[] target) => Array.Copy(source, target, Math.Min(source.Length, target.Length));
}
@@ -14,7 +14,7 @@ namespace ViaFerrea.Core.Persistence;
public static class WorldSerializer
{
/// <summary>Versione del corpo del salvataggio (migrazioni in <see cref="Read"/>).</summary>
public const int BodyVersion = 2;
public const int BodyVersion = 3;
/// <summary>Scrive l'intero mondo (impostazioni, terreno, stato dinamico, eventi).</summary>
public static void Write(World w, SaveWriter s)
@@ -235,6 +235,7 @@ public static class WorldSerializer
RailSerializer.Write(w, s);
MaintenanceSerializer.Write(w, s);
CorporateSerializer.Write(w, s);
}
private static void WriteRecipeStock(List<RecipeItemDef> items, int[] stock, SaveWriter s)
@@ -673,6 +674,9 @@ public static class WorldSerializer
// versione 2 (F4): manutenzione, officine, convenzioni; la versione 1 si migra
if (version >= 2) MaintenanceSerializer.Read(w, r);
else MaintenanceSerializer.Migrate(w);
// versione 3 (F5): industrie, borsa, offerte, aste, fine partita, agenti IA
if (version >= 3) CorporateSerializer.Read(w, r);
else CorporateSerializer.Migrate(w);
}
private static void ReadRecipeStock(List<RecipeItemDef> items, int[] stock, SaveReader r)
+4 -4
View File
@@ -48,7 +48,7 @@ public sealed class TrackEdge
public required EdgeId Id { get; init; }
public required NodeId A { get; set; }
public required NodeId B { get; set; }
public required CompanyId Owner { get; init; }
public required CompanyId Owner { get; set; }
public required int TrackClass { get; set; }
public required bool DoubleTrack { get; set; }
public required bool Electrified { get; set; }
@@ -196,7 +196,7 @@ public sealed class TrackEdge
public sealed class Station
{
public required StationId Id { get; init; }
public required CompanyId Owner { get; init; }
public required CompanyId Owner { get; set; }
public required string Name { get; set; }
public required NodeId Node { get; init; }
public required Vec2 Position { get; init; }
@@ -258,7 +258,7 @@ public sealed class WorkshopJob
public sealed class Depot : IWorkplace
{
public required DepotId Id { get; init; }
public required CompanyId Owner { get; init; }
public required CompanyId Owner { get; set; }
public required string Name { get; set; }
public required NodeId Node { get; init; }
public required Vec2 Position { get; init; }
@@ -305,7 +305,7 @@ public enum ProjectKind : byte { NewTrack = 0, Renewal = 1, Upgrade = 2 }
public sealed class ConstructionProject
{
public required int Id { get; init; }
public required CompanyId Owner { get; init; }
public required CompanyId Owner { get; set; }
public required ProjectKind Kind { get; init; }
public required List<EdgeId> Edges { get; init; }
public required double TotalDays { get; init; }
+5 -2
View File
@@ -207,8 +207,11 @@ public static class TrackPlanner
string reason = !req.AllowTunnels
? "servirebbe una galleria o un altro tracciato"
: "abbassa o alza il tracciato o cambia percorso";
plan.Errors.Add(new PlanIssue(PlanIssueCode.GradientExceeded,
$"Pendenza necessaria {needed * 100:F1}% oltre il massimo {gMax * 100:F1}%: {reason}", geo[i].S));
// se la stima locale non supera il massimo, il conflitto nasce dall'insieme dei vincoli di quota
string text = needed > gMax + 1e-9
? $"Pendenza necessaria {needed * 100:F1}% oltre il massimo {gMax * 100:F1}%: {reason}"
: $"I vincoli di quota (ponti, attraversamenti, estremità) non si raccordano entro la pendenza massima del {gMax * 100:F1}%: {reason}";
plan.Errors.Add(new PlanIssue(PlanIssueCode.GradientExceeded, text, geo[i].S));
return Finish(plan, ctx, geo, terrainH, terrainH, cells);
}
}
+3 -3
View File
@@ -8,7 +8,7 @@ public sealed class Vehicle
{
public required VehicleId Id { get; init; }
public required VehicleDef Def { get; init; }
public required CompanyId Owner { get; init; }
public required CompanyId Owner { get; set; }
public required long BoughtDay { get; set; }
public TrainId Train { get; set; } = TrainId.None;
public DepotId Depot { get; set; } = DepotId.None;
@@ -97,7 +97,7 @@ public struct HeldResource
public sealed class Train
{
public required TrainId Id { get; init; }
public required CompanyId Owner { get; init; }
public required CompanyId Owner { get; set; }
public required string Name { get; set; }
public List<VehicleId> Vehicles { get; } = [];
public DepotId HomeDepot { get; set; } = DepotId.None;
@@ -216,7 +216,7 @@ public sealed record LineStop(StationId Station, bool Load = true, bool Unload =
public sealed class Line
{
public required LineId Id { get; init; }
public required CompanyId Owner { get; init; }
public required CompanyId Owner { get; set; }
public required string Name { get; set; }
public required string Color { get; set; }
public List<LineStop> Stops { get; } = [];
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,63 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Rail;
namespace ViaFerrea.Core.Simulation.Ai;
/// <summary>Tipo di progetto di un'IA: merci da un produttore a un consumatore o pendolari da una città.</summary>
public enum AiProjectKind : byte { Freight = 0, Commuter = 1 }
/// <summary>Fase di un progetto: cantieri, acquisto dei treni, esercizio o abbandono.</summary>
public enum AiProjectStage : byte { Construction = 0, Equip = 1, Running = 2, Abandoned = 3 }
/// <summary>Linea costruita (o in costruzione) da un'IA e ciò che serve a seguirla.</summary>
public sealed class AiProject
{
public required int Id { get; init; }
public required AiProjectKind Kind { get; init; }
/// <summary>Bene trasportato (merci) o −1.</summary>
public int Good { get; init; } = -1;
/// <summary>Classe dei pendolari (0 operai, 1 tecnici) per i progetti di pendolarismo.</summary>
public int PaxClass { get; init; }
public required long Key { get; init; }
public StationId StationA { get; set; } = StationId.None;
public StationId StationB { get; set; } = StationId.None;
public DepotId Depot { get; set; } = DepotId.None;
public List<EdgeId> Edges { get; } = [];
public LineId Line { get; set; } = LineId.None;
public List<TrainId> Trains { get; } = [];
public AiProjectStage Stage { get; set; }
public long StartDay { get; init; }
public long CapitalCents { get; init; }
public long RevenuePerYearCents { get; init; }
public int TrainsPlanned { get; set; }
public required string Loco { get; init; }
public required string Car { get; init; }
public int CarsPerTrain { get; init; }
/// <summary>Giorno prima del quale non si aggiungono treni (dopo uno stallo risolto).</summary>
public long GrowAfterDay { get; set; }
/// <summary>Deposito rifornito di ricambi da questa linea (progetti di supporto), o None.</summary>
public DepotId SupplyFor { get; init; } = DepotId.None;
}
/// <summary>Stato persistente dell'agente IA di una compagnia (12.1).</summary>
public sealed class AiState
{
public required CompanyId Company { get; init; }
/// <summary>Giorno del mese (0-based) in cui l'IA pianifica.</summary>
public int PlanDay { get; init; }
public long Issued { get; set; }
public long Rejected { get; set; }
public bool PolicySet { get; set; }
public int NextProjectId { get; set; }
public List<AiProject> Projects { get; } = [];
/// <summary>Chiavi dei candidati scartati (percorso o piano non validi), i più recenti in coda.</summary>
public List<long> Failed { get; } = [];
/// <summary>Offerte pubbliche a cui l'IA ha già risposto come bersaglio.</summary>
public List<int> Responded { get; } = [];
public int LastIndustryYear { get; set; } = int.MinValue;
/// <summary>Ultimo giorno in cui l'IA ha sciolto uno stallo (uno ogni tanto, non a cascata).</summary>
public long LastGridlockDay { get; set; } = -1_000_000;
/// <summary>Quota dei comandi rifiutati sul totale emesso.</summary>
public double RejectedShare => Issued == 0 ? 0 : (double)Rejected / Issued;
}
@@ -0,0 +1,49 @@
namespace ViaFerrea.Core.Simulation.Ai;
/// <summary>
/// Agenti delle compagnie IA (12.1), dopo la borsa: ogni giorno seguono progetti e offerte, una
/// volta al mese (in giorni diversi per ciascuna IA) pianificano. Le IA agiscono solo con i comandi.
/// </summary>
public sealed class AiSystem : ISimSystem
{
public string Name => "AiAgents";
/// <summary>Diagnostica facoltativa (strumenti): non influisce sulla simulazione.</summary>
public static Action<string>? Trace { get; set; }
private readonly GridPath _path = new();
public void Step(WorldContext ctx)
{
if (!ctx.IsNewDay) return;
var w = ctx.World;
if (w.AiPaused) return;
EnsureStates(w);
int dpm = w.Calendar.DaysPerMonth;
foreach (var s in w.AiStates)
{
var c = w.Company(s.Company);
if (c.Defunct) continue;
var agent = new AiAgent(w, ctx, s, _path);
agent.Daily();
if (ctx.Day % dpm == s.PlanDay) agent.Monthly();
}
}
/// <summary>Uno stato per ogni compagnia IA (anche per i nuovi concorrenti), in ordine di id.</summary>
public static void EnsureStates(World w)
{
if (w.AiStates.Count == w.Companies.Count(c => !c.IsPlayer)) return;
int dpm = w.Calendar.DaysPerMonth;
foreach (var c in w.Companies)
{
if (c.IsPlayer || w.AiStates.Any(s => s.Company == c.Id)) continue;
int index = w.AiStates.Count;
w.AiStates.Add(new AiState
{
Company = c.Id,
PlanDay = (1 + index * w.Data.Ai.Planning.PlanningDaySpacing) % dpm,
});
}
}
}
@@ -0,0 +1,381 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Map;
namespace ViaFerrea.Core.Simulation.Ai;
/// <summary>
/// Percorso di un nuovo binario per le IA (12.1): Dijkstra sulla griglia delle celle in un
/// riquadro attorno ai due estremi, con costo = costo di costruzione della cella (modificatori del
/// terreno, acqua da superare con un ponte) + penalità di pendenza; città, industrie e mare non si
/// attraversano. Il percorso si semplifica in una polilinea (Douglas–Peucker).
/// </summary>
public sealed class GridPath
{
private double[] _dist = [];
private int[] _prev = [];
private readonly PriorityQueue<int, double> _queue = new();
// regioni collegabili (componenti connesse delle celle attraversabili) per la campata dell'epoca
private int[] _region = [];
private double _regionSpan = -1;
private int _regionCells = -1;
// celle con binari della compagnia (non si incrociano a raso), ricalcolate quando cambia la rete
private bool[] _ownTrack = [];
private int _ownTrackCompany = -1;
private int _ownTrackEdges = -1;
private long _ownTrackVersion = -1;
private static double MaxSpan(World w)
{
double maxSpan = 0;
foreach (var b in w.Data.Eras.BridgeTypes)
{
if (b.From <= w.Clock.Year) maxSpan = Math.Max(maxSpan, b.MaxSpanM);
}
return maxSpan;
}
private static bool Passable(World w, int x, int y, double maxSpan, double[] riverWidths)
{
var t = w.Terrain;
switch (t.TypeAt(x, y))
{
case CellType.Sea:
case CellType.Town:
case CellType.Industry:
return false;
case CellType.Water:
int cls = t.RiverWidth[y * t.Width + x];
return cls > 0 && riverWidths[Math.Min(cls, riverWidths.Length) - 1] <= maxSpan;
default:
return true;
}
}
/// <summary>
/// Vero se i due punti stanno nella stessa regione collegabile con i ponti dell'epoca
/// (verifica rapida prima della ricerca del percorso).
/// </summary>
public bool SameRegion(World w, Vec2 a, Vec2 b)
{
var t = w.Terrain;
double span = MaxSpan(w);
if (span != _regionSpan || _regionCells != t.Width * t.Height) BuildRegions(w, span);
int ra = RegionNear(w, a), rb = RegionNear(w, b);
return ra >= 0 && ra == rb;
}
private int RegionNear(World w, Vec2 p)
{
var t = w.Terrain;
var (cx, cy) = t.CellAt(p);
for (int r = 0; r <= 2; r++)
{
for (int dy = -r; dy <= r; dy++)
{
for (int dx = -r; dx <= r; dx++)
{
int x = cx + dx, y = cy + dy;
if (!t.InBounds(x, y)) continue;
int label = _region[y * t.Width + x];
if (label >= 0) return label;
}
}
}
return -1;
}
private void BuildRegions(World w, double span)
{
var t = w.Terrain;
var riverWidths = w.Data.Construction.Profile.RiverWidthMByClass;
int n = t.Width * t.Height;
_region = new int[n];
Array.Fill(_region, -1);
var stack = new Stack<int>();
int next = 0;
for (int i = 0; i < n; i++)
{
if (_region[i] >= 0 || !Passable(w, i % t.Width, i / t.Width, span, riverWidths)) continue;
_region[i] = next;
stack.Push(i);
while (stack.Count > 0)
{
int c = stack.Pop();
int cx = c % t.Width, cy = c / t.Width;
for (int k = 0; k < 4; k++)
{
int nx = cx + (k == 0 ? 1 : k == 1 ? -1 : 0), ny = cy + (k == 2 ? 1 : k == 3 ? -1 : 0);
if (!t.InBounds(nx, ny)) continue;
int ni = ny * t.Width + nx;
if (_region[ni] >= 0 || !Passable(w, nx, ny, span, riverWidths)) continue;
_region[ni] = next;
stack.Push(ni);
}
}
next++;
}
_regionSpan = span;
_regionCells = n;
}
private void BuildOwnTrack(World w, CompanyId company)
{
var t = w.Terrain;
int n = t.Width * t.Height;
if (_ownTrack.Length != n) _ownTrack = new bool[n];
else Array.Clear(_ownTrack);
foreach (var e in w.Network.Edges)
{
if (e.Owner != company || e.State == Rail.EdgeState.Demolished) continue;
for (int i = 0; i < e.X.Length; i++)
{
var (cx, cy) = t.CellAt(new Vec2(e.X[i], e.Y[i]));
_ownTrack[cy * t.Width + cx] = true;
}
}
_ownTrackCompany = company.Value;
_ownTrackEdges = w.Network.Edges.Count;
_ownTrackVersion = w.Network.Version;
}
/// <summary>Polilinea in metri da <paramref name="from"/> a <paramref name="to"/>, o null se irraggiungibile.</summary>
public List<Vec2>? Find(World w, CompanyId company, Vec2 from, Vec2 to, double marginKm, double toleranceM, double minRadiusM)
{
var t = w.Terrain;
if (!SameRegion(w, from, to)) return null;
if (_ownTrackCompany != company.Value || _ownTrackEdges != w.Network.Edges.Count || _ownTrackVersion != w.Network.Version)
BuildOwnTrack(w, company);
var plan = w.Data.Ai.Planning;
var costs = w.Data.Construction.Costs;
var (ax, ay) = t.CellAt(from);
var (bx, by) = t.CellAt(to);
int margin = (int)Math.Ceiling(marginKm * 1000 / t.CellSizeM);
int x0 = Math.Max(0, Math.Min(ax, bx) - margin), x1 = Math.Min(t.Width - 1, Math.Max(ax, bx) + margin);
int y0 = Math.Max(0, Math.Min(ay, by) - margin), y1 = Math.Min(t.Height - 1, Math.Max(ay, by) + margin);
int bw = x1 - x0 + 1, bh = y1 - y0 + 1, n = bw * bh;
if (_dist.Length < n)
{
_dist = new double[n];
_prev = new int[n];
}
Array.Fill(_dist, double.PositiveInfinity, 0, n);
Array.Fill(_prev, -1, 0, n);
_queue.Clear();
// fiumi attraversabili con i ponti dell'epoca (larghezza dell'alveo della classe ≤ campata massima)
double maxSpan = 0;
foreach (var b in w.Data.Eras.BridgeTypes)
{
if (b.From <= w.Clock.Year) maxSpan = Math.Max(maxSpan, b.MaxSpanM);
}
var riverWidths = w.Data.Construction.Profile.RiverWidthMByClass;
// pendenza massima della trazione più permissiva disponibile: le celle più ripide costano molto
// (il pianificatore compensa solo piccoli dislivelli con trincee e rilevati)
var g = w.Data.Construction.MaxGradientByTraction;
double gMax = g.Steam;
if (w.Clock.Year >= w.Data.Eras.Eras.First(e => e.Id == "diesel").From) gMax = Math.Max(gMax, g.Diesel);
int start = (ay - y0) * bw + (ax - x0), goal = (by - y0) * bw + (bx - x0);
_dist[start] = 0;
_queue.Enqueue(start, 0);
double cs = t.CellSizeM;
ReadOnlySpan<int> dxs = [1, -1, 0, 0, 1, 1, -1, -1];
ReadOnlySpan<int> dys = [0, 0, 1, -1, 1, -1, 1, -1];
while (_queue.TryDequeue(out int cur, out double d))
{
if (d > _dist[cur]) continue;
if (cur == goal) break;
int cx = cur % bw + x0, cy = cur / bw + y0;
double hc = t.Heights[cy * t.Width + cx] / 10.0;
for (int k = 0; k < 8; k++)
{
int nx = cx + dxs[k], ny = cy + dys[k];
if (nx < x0 || nx > x1 || ny < y0 || ny > y1) continue;
int ni = (ny - y0) * bw + (nx - x0);
bool endpoint = ni == goal;
var type = t.TypeAt(nx, ny);
if (type == CellType.Water)
{
int cls = t.RiverWidth[ny * t.Width + nx];
if (cls <= 0 || riverWidths[Math.Min(cls, riverWidths.Length) - 1] > maxSpan) continue;
}
double cellCost = CellCost(type, costs, plan, endpoint);
if (double.IsPositiveInfinity(cellCost)) continue;
// i propri binari non si incrociano a raso: ci si aggancia solo vicino agli estremi
if (_ownTrack[ny * t.Width + nx] && Vec2.Distance(t.CellCenter(nx, ny), from) > 300 && Vec2.Distance(t.CellCenter(nx, ny), to) > 300) continue;
double step = k < 4 ? 1.0 : 1.41421356237;
double hn = t.Heights[ny * t.Width + nx] / 10.0;
double grade = Math.Abs(hn - hc) / (step * cs);
double steep = grade > gMax * plan.SteepGradeFactor ? plan.SteepPenalty : 0;
double nd = d + step * (cellCost + steep) + plan.PathSlopePenalty * grade * step;
if (nd >= _dist[ni]) continue;
_dist[ni] = nd;
_prev[ni] = cur;
_queue.Enqueue(ni, nd);
}
}
if (double.IsPositiveInfinity(_dist[goal]))
{
int reached = 0;
for (int i = 0; i < n; i++) if (!double.IsPositiveInfinity(_dist[i])) reached++;
AiSystem.Trace?.Invoke($" percorso: obiettivo non raggiunto, celle raggiunte {reached} su {n}, partenza {t.TypeAt(ax, ay)} arrivo {t.TypeAt(bx, by)} binari propri vicino all'arrivo {_ownTrack[by * t.Width + bx]}");
return null;
}
var cells = new List<Vec2>();
for (int c = goal; c >= 0; c = _prev[c]) cells.Add(t.CellCenter(c % bw + x0, c / bw + y0));
cells.Reverse();
cells[0] = from;
cells[^1] = to;
bool Clear(Vec2 a, Vec2 b) => SegmentClear(w, a, b, from, to, maxSpan, riverWidths);
return EnforceRadius(Simplify(cells, toleranceM, Clear), minRadiusM * 1.05, Clear);
}
/// <summary>
/// Il segmento non attraversa città, industrie, mare o fiumi troppo larghi per i ponti dell'epoca
/// (a parte i primi e gli ultimi 200 m, dove stanno le stazioni).
/// </summary>
private static bool SegmentClear(World w, Vec2 a, Vec2 b, Vec2 from, Vec2 to, double maxSpan, double[] riverWidths)
{
var t = w.Terrain;
double len = Vec2.Distance(a, b);
int steps = Math.Max(1, (int)Math.Ceiling(len / 25));
for (int i = 0; i <= steps; i++)
{
var p = Vec2.Lerp(a, b, (double)i / steps);
if (Vec2.Distance(p, from) < 200 || Vec2.Distance(p, to) < 200) continue;
var (cx, cy) = t.CellAt(p);
switch (t.TypeAt(cx, cy))
{
case CellType.Town:
case CellType.Industry:
case CellType.Sea:
return false;
case CellType.Water:
int cls = t.RiverWidth[cy * t.Width + cx];
if (cls <= 0 || riverWidths[Math.Min(cls, riverWidths.Length) - 1] > maxSpan) return false;
break;
}
}
return true;
}
/// <summary>
/// Toglie i vertici i cui raccordi al raggio minimo non entrano nei segmenti adiacenti
/// (tangente R·tan(θ/2) a ciascun estremo), finché la polilinea li ammette tutti.
/// </summary>
public static List<Vec2> EnforceRadius(List<Vec2> points, double radius, Func<Vec2, Vec2, bool>? clear = null)
{
var pts = new List<Vec2>(points);
while (pts.Count > 2)
{
int n = pts.Count;
var tangent = new double[n];
for (int i = 1; i < n - 1; i++)
{
var d1 = (pts[i] - pts[i - 1]).Normalized();
var d2 = (pts[i + 1] - pts[i]).Normalized();
double theta = Math.Abs(DMath.Atan2(Vec2.Cross(d1, d2), Math.Clamp(Vec2.Dot(d1, d2), -1, 1)));
tangent[i] = radius * DMath.Tan(theta / 2);
}
int worst = -1;
double worstExcess = 0;
for (int j = 0; j < n - 1; j++)
{
double excess = tangent[j] + tangent[j + 1] - Vec2.Distance(pts[j], pts[j + 1]);
if (excess <= worstExcess) continue;
// si toglie il vertice con il raccordo più lungo, se il segmento che resta è libero
int first = j == 0 ? 1 : j + 1 == n - 1 ? j : tangent[j] >= tangent[j + 1] ? j : j + 1;
int second = first == j ? j + 1 : j;
foreach (int k in new[] { first, second })
{
if (k <= 0 || k >= n - 1) continue;
if (clear is not null && !clear(pts[k - 1], pts[k + 1])) continue;
worstExcess = excess;
worst = k;
break;
}
}
if (worst < 0) break;
pts.RemoveAt(worst);
}
return pts;
}
/// <summary>Costo relativo di costruzione per cella (∞ = non attraversabile).</summary>
private static double CellCost(CellType type, ConstructionCosts costs, AiPlanningParams plan, bool endpoint)
{
switch (type)
{
case CellType.Sea:
return double.PositiveInfinity;
case CellType.Town:
case CellType.Industry:
return endpoint ? 1.0 : double.PositiveInfinity;
case CellType.Water:
return plan.PathWaterPenalty;
case CellType.Rock:
return costs.TerrainModifiers.GetValueOrDefault("rock", 1.0);
case CellType.Marsh:
return costs.TerrainModifiers.GetValueOrDefault("marsh", 1.0);
case CellType.Mountain:
return costs.TerrainModifiers.GetValueOrDefault("mountain", 1.0);
case CellType.Forest:
return costs.TerrainModifiers.GetValueOrDefault("forest", 1.0);
default:
return 1.0;
}
}
/// <summary>
/// Semplificazione di Douglas–Peucker (estremi conservati): un tratto si divide anche quando il
/// segmento semplificato attraverserebbe un ostacolo.
/// </summary>
public static List<Vec2> Simplify(List<Vec2> points, double tolerance, Func<Vec2, Vec2, bool>? clear = null)
{
if (points.Count <= 2) return [.. points];
var keep = new bool[points.Count];
keep[0] = keep[^1] = true;
var stack = new Stack<(int, int)>();
stack.Push((0, points.Count - 1));
while (stack.Count > 0)
{
var (a, b) = stack.Pop();
double best = -1;
int index = -1;
for (int i = a + 1; i < b; i++)
{
double d = SegmentDistance(points[i], points[a], points[b]);
if (d > best)
{
best = d;
index = i;
}
}
if (index >= 0 && (best > tolerance || (clear is not null && !clear(points[a], points[b]))))
{
keep[index] = true;
stack.Push((a, index));
stack.Push((index, b));
}
}
var result = new List<Vec2>();
for (int i = 0; i < points.Count; i++)
{
if (keep[i]) result.Add(points[i]);
}
return result;
}
private static double SegmentDistance(Vec2 p, Vec2 a, Vec2 b)
{
var ab = b - a;
double len2 = ab.LengthSquared;
if (len2 <= 0) return Vec2.Distance(p, a);
double u = Math.Clamp(Vec2.Dot(p - a, ab) / len2, 0, 1);
return Vec2.Distance(p, a + ab * u);
}
}
@@ -0,0 +1,46 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Economy;
namespace ViaFerrea.Core.Simulation;
/// <summary>Primato della Cronaca finale.</summary>
public readonly record struct ChronicleRecord(string Title, string Value, int Year);
/// <summary>
/// Cronaca finale della compagnia del giocatore (12.3): storia anno per anno (con l'anno in
/// corso), primati, fatti salienti e prestigio. Il prestigio di F5 è un punteggio semplice
/// (livelli, patrimonio massimo, anni di attività) che la F7 estende (ADR 0012).
/// </summary>
public sealed class ChronicleReport
{
public List<CompanyYear> History { get; } = [];
public List<ChronicleRecord> Records { get; } = [];
public List<string> Highlights { get; } = [];
public long Prestige { get; private set; }
public static ChronicleReport Build(World w)
{
var c = w.Player;
var report = new ChronicleReport();
report.History.AddRange(c.History);
var current = Corporate.Snapshot(w, c, w.Clock.Year, c.YearEntries);
if (report.History.Count == 0 || report.History[^1].Year != current.Year) report.History.Add(current);
var richest = report.History.MaxBy(y => y.NetWorthCents);
var best = report.History.MaxBy(y => y.ProfitCents);
var fleet = report.History.MaxBy(y => y.Trains);
var track = report.History.MaxBy(y => y.TrackKm);
report.Records.Add(new ChronicleRecord("Patrimonio netto massimo", new Money(richest.NetWorthCents).ToString(), richest.Year));
report.Records.Add(new ChronicleRecord("Anno più redditizio", new Money(best.ProfitCents).ToString(), best.Year));
report.Records.Add(new ChronicleRecord("Flotta più grande", $"{fleet.Trains} treni", fleet.Year));
report.Records.Add(new ChronicleRecord("Rete più estesa", $"{track.TrackKm:0.0} km", track.Year));
int maxTier = report.History.Max(y => y.Tier);
var tierYear = report.History.First(y => y.Tier == maxTier);
report.Records.Add(new ChronicleRecord("Livello più alto", w.Data.Tiers.Tiers[Math.Clamp(maxTier, 1, w.Data.Tiers.Tiers.Count) - 1].NameIt, tierYear.Year));
foreach (var m in c.Milestones) report.Highlights.Add($"{w.Calendar.DateOfDay(m.Day)}: {m.Text}");
int years = Math.Max(0, w.Clock.Year - w.Calendar.StartYear);
report.Prestige = 100L * maxTier + richest.NetWorthCents / 1_000_000 + 5L * years;
return report;
}
}
@@ -17,14 +17,28 @@ public static class CommandProcessor
if (!command.Issuer.IsValid || command.Issuer.Value >= w.Companies.Count)
return Result(CommandError.UnknownCompany, "Compagnia sconosciuta");
var company = w.Companies[command.Issuer.Value];
if (company.Merged)
return Result(CommandError.NotAllowed, "La compagnia è stata incorporata");
if (company.Bankrupt)
return Result(CommandError.Bankrupt, "La compagnia è in bancarotta");
if (company.IsPlayer && w.GameOver is not null)
return Result(CommandError.NotAllowed, "Partita conclusa: si osserva il mondo senza poter dare comandi");
return command switch
{
TakeLoanCommand c => TakeLoan(w, company, c, Result),
RepayLoanCommand c => RepayLoan(w, company, c, Result),
SetIndustryPolicyCommand c => SetIndustryPolicy(w, company, c, Result),
SetIndustryPolicyCommand c => IndustryCommandHandlers.SetPolicy(w, company, c, Reply),
BuyIndustryCommand c => IndustryCommandHandlers.BuyIndustry(w, company, c, Reply),
OverhaulIndustryCommand c => IndustryCommandHandlers.Overhaul(w, company, c, Reply),
UpgradeIndustryCommand c => IndustryCommandHandlers.Upgrade(w, company, c, Reply),
IpoCommand c => CorporateCommandHandlers.Ipo(w, company, c, Reply),
BuySharesCommand c => CorporateCommandHandlers.BuyShares(w, company, c, Reply),
SellSharesCommand c => CorporateCommandHandlers.SellShares(w, company, c, Reply),
PayDividendCommand c => CorporateCommandHandlers.PayDividend(w, company, c, Reply),
LaunchBidCommand c => CorporateCommandHandlers.LaunchBid(w, company, c, Reply),
RespondBidCommand c => CorporateCommandHandlers.RespondBid(w, company, c, Reply),
MergeCompanyCommand c => CorporateCommandHandlers.MergeCompany(w, company, c, ctx, Reply),
BuildTrackCommand c => RailCommandHandlers.BuildTrack(w, company, c, Reply),
BuildStationCommand c => RailCommandHandlers.BuildStation(w, company, c, Reply),
BuildDepotCommand c => RailCommandHandlers.BuildDepot(w, company, c, Reply),
@@ -52,6 +66,7 @@ public static class CommandProcessor
private static CommandResult TakeLoan(World w, Company company, TakeLoanCommand c, Func<CommandError, string, CommandResult> result)
{
if (c.Amount.Cents <= 0) return result(CommandError.InvalidArgument, "Importo non valido");
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()}");
@@ -82,13 +97,4 @@ public static class CommandProcessor
if (loan.Remaining.Cents <= 0) company.Loans.Remove(loan);
return result(CommandError.None, $"Rimborsati {amount}");
}
private static CommandResult SetIndustryPolicy(World w, Company company, SetIndustryPolicyCommand c, Func<CommandError, string, CommandResult> result)
{
if (!c.Industry.IsValid || c.Industry.Value >= w.Industries.Count) return result(CommandError.NotFound, "Industria inesistente");
var ind = w.Industries[c.Industry.Value];
if (ind.Owner != company.Id) return result(CommandError.NotAllowed, "L'industria non appartiene alla compagnia");
ind.Budget = c.Budget;
return result(CommandError.None, $"Budget di manutenzione di {ind.Name}: {c.Budget}");
}
}
+284
View File
@@ -0,0 +1,284 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Rail;
using ViaFerrea.Core.Simulation.Systems;
namespace ViaFerrea.Core.Simulation;
/// <summary>
/// Operazioni societarie (12.2–12.3): prezzo delle azioni, controllo, fusioni, liquidazioni,
/// amministrazione controllata e fine partita del giocatore (ADR 0012).
/// </summary>
public static class Corporate
{
/// <summary>Libro dei soci iniziale: il fondatore tiene la quota indicata, il resto è flottante.</summary>
public static void InitShares(World w, Company c, bool listed, double founderShare)
{
long total = w.Data.Balance.StockMarket.Shares;
c.Shares.Total = total;
c.Shares.Founder = (long)Math.Round(total * Math.Clamp(founderShare, 0, 1));
c.Shares.Public = total - c.Shares.Founder;
c.Shares.Treasury = 0;
c.Listed = listed;
c.SharePrice = FundamentalPrice(w, c);
}
/// <summary>Valore fondamentale per azione: max(patrimonio netto, multiplo × utile annuo) / azioni in circolazione.</summary>
public static double FundamentalPrice(World w, Company c)
{
var sm = w.Data.Balance.StockMarket;
double value = Math.Max(c.NetWorth.Cents, sm.EarningsMultiple * c.AnnualProfit);
long outstanding = Math.Max(1, c.Shares.Outstanding);
return Math.Max(MinPrice, value / outstanding);
}
/// <summary>Prezzo minimo per azione (centesimi): un titolo non vale mai zero.</summary>
public const double MinPrice = 0.01;
/// <summary>Prezzo d'acquisto (lettera) e di vendita (denaro) con lo spread.</summary>
public static double Ask(World w, Company c) => c.SharePrice * (1 + w.Data.Balance.StockMarket.Spread / 2);
public static double BidPrice(World w, Company c) => c.SharePrice * (1 - w.Data.Balance.StockMarket.Spread / 2);
/// <summary>Titolare che controlla la compagnia (oltre la soglia), o None (fondatore o nessuno).</summary>
public static CompanyId Controller(World w, Company c)
{
double control = w.Data.Balance.StockMarket.ControlShare;
for (int i = 0; i < c.Shares.ByCompany.Length; i++)
{
if (i != c.Id.Value && c.Shares.FractionOf(new CompanyId(i)) > control) return new CompanyId(i);
}
return CompanyId.None;
}
/// <summary>Azioni del flottante non vincolate da offerte in corso.</summary>
public static long FreeFloat(World w, Company c)
{
long tendered = 0;
foreach (var b in w.Bids)
{
if (b.State == BidState.Open && b.Target == c.Id) tendered += b.TenderedPublic;
}
return Math.Max(0, c.Shares.Public - tendered);
}
/// <summary>
/// Fusione (12.2): il controllante liquida le minoranze al prezzo di mercato e assorbe attivi,
/// debiti e cassa della controllata, che cessa di esistere come impresa autonoma.
/// </summary>
public static void Merge(WorldContext ctx, Company parent, Company sub)
{
var w = ctx.World;
double price = sub.SharePrice;
// liquidazione delle minoranze: flottante e fondatore al mercato (conto Esterno), altre compagnie a sé
long external = sub.Shares.Public + sub.Shares.Founder;
PayFromParent(w, parent, Account.External, external * price);
for (int i = 0; i < sub.Shares.ByCompany.Length; i++)
{
long held = sub.Shares.ByCompany[i];
if (held == 0 || i == parent.Id.Value || i == sub.Id.Value) continue;
PayFromParent(w, parent, Account.Of(new CompanyId(i)), held * price);
sub.Shares.ByCompany[i] = 0;
}
TransferAssets(w, sub, parent);
sub.Merged = true;
sub.MergedInto = parent.Id;
sub.ControlledBy = CompanyId.None;
sub.Listed = false;
sub.Shares.Public = 0;
sub.Shares.Founder = 0;
sub.Shares.Treasury = 0;
Array.Clear(sub.Shares.ByCompany);
sub.Shares.Add(parent.Id, 0);
sub.Shares.ByCompany[parent.Id.Value] = sub.Shares.Total;
CloseBidsOn(w, sub.Id);
Milestone(w, parent, $"incorpora {sub.Name}");
Milestone(w, sub, $"incorporata da {parent.Name}");
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Info,
$"{parent.Name} incorpora {sub.Name}: rete, treni e debiti passano alla capogruppo", EntityKind.Company, sub.Id.Value, parent.Id));
}
private static void PayFromParent(World w, Company parent, Account to, double cents)
{
var amount = Money.FromCentsRounded(cents);
if (amount.Cents > 0) w.Money.Transfer(Account.Of(parent.Id), to, amount, LedgerEntry.Shares);
}
/// <summary>Passa a un'altra compagnia tutto ciò che appartiene a <paramref name="from"/>.</summary>
public static void TransferAssets(World w, Company from, Company to)
{
var net = w.Network;
foreach (var n in net.Nodes) if (n.Owner == from.Id) n.Owner = to.Id;
foreach (var e in net.Edges) if (e.Owner == from.Id) e.Owner = to.Id;
foreach (var s in net.Stations) if (s.Owner == from.Id) s.Owner = to.Id;
foreach (var d in net.Depots) if (d.Owner == from.Id) d.Owner = to.Id;
foreach (var p in net.Projects) if (p.Owner == from.Id) p.Owner = to.Id;
foreach (var v in w.Vehicles) if (v.Owner == from.Id) v.Owner = to.Id;
foreach (var t in w.Trains) if (t.Owner == from.Id) t.Owner = to.Id;
foreach (var l in w.Lines) if (l.Owner == from.Id) l.Owner = to.Id;
foreach (var i in w.Industries) if (i.Owner == from.Id) i.Owner = to.Id;
foreach (var c in w.Commutes) if (c.Carrier == from.Id) c.Carrier = to.Id;
foreach (var a in w.Agreements) if (a.Carrier == from.Id) a.Carrier = to.Id;
to.Loans.AddRange(from.Loans);
from.Loans.Clear();
// partecipazioni in altre compagnie
foreach (var other in w.Companies)
{
long held = other.Shares.Of(from.Id);
if (held == 0 || other.Id == from.Id) continue;
other.Shares.ByCompany[from.Id.Value] = 0;
if (other.Id == to.Id) other.Shares.Treasury += held; // azioni proprie riacquistate
else other.Shares.Add(to.Id, held);
}
if (from.Cash.Cents != 0) w.Money.Transfer(Account.Of(from.Id), Account.Of(to.Id), from.Cash, LedgerEntry.Other);
w.LineGraphs.Touch();
FinanceSystem.UpdateBookValues(w);
}
/// <summary>
/// Liquidazione senza compratori: i treni si fermano e si rottamano, le linee chiudono, i
/// pendolari perdono il vettore; binari e stazioni restano come rete abbandonata.
/// </summary>
public static void Liquidate(WorldContext ctx, Company c)
{
var w = ctx.World;
foreach (var t in w.Trains)
{
if (t.Owner != c.Id || t.Removed) continue;
TrainSystem.ReleaseAll(w.Network, t);
foreach (var p in t.Cargo)
{
if (p.Kind == PacketKind.Freight) w.Goods.Decayed[p.Good] += p.Units;
}
t.Cargo.Clear();
t.Removed = true;
t.Line = LineId.None;
}
foreach (var v in w.Vehicles)
{
if (v.Owner != c.Id || v.Sold) continue;
v.Sold = true;
}
foreach (var l in w.Lines)
{
if (l.Owner == c.Id) l.Removed = true;
}
foreach (var d in w.Network.Depots)
{
if (d.Owner != c.Id) continue;
d.Jobs.Clear();
}
foreach (var s in w.Network.Stations)
{
if (s.Owner != c.Id) continue;
foreach (var p in s.Waiting)
{
if (p.Kind == PacketKind.Freight) w.Goods.Decayed[p.Good] += p.Units;
}
s.Waiting.Clear();
Array.Clear(s.Incoming);
}
foreach (var com in w.Commutes)
{
if (com.Carrier == c.Id) com.Carrier = CompanyId.None;
}
foreach (var a in w.Agreements)
{
if (a.Carrier == c.Id && a.State <= AgreementState.Active) a.State = AgreementState.Broken;
}
c.Liquidated = true;
c.Listed = false;
w.LineGraphs.Touch();
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Warning,
$"{c.Name}: nessun compratore all'asta, treni rottamati e linee chiuse", EntityKind.Company, c.Id.Value, c.Id));
}
/// <summary>Chiude come fallite le offerte in corso che coinvolgono la compagnia.</summary>
public static void CloseBidsOn(World w, CompanyId company)
{
foreach (var b in w.Bids)
{
if (b.State != BidState.Open || (b.Target != company && b.Bidder != company)) continue;
b.State = BidState.Failed;
b.ClosedDay = w.Clock.Day;
}
}
/// <summary>Fine della partita del giocatore: la compagnia resta nel mondo, il giocatore diventa osservatore.</summary>
public static void EndGame(WorldContext ctx, GameOverReason reason, string text, CompanyId winner)
{
var w = ctx.World;
if (w.GameOver is not null) return;
w.GameOver = new GameOverState { Day = ctx.Day, Reason = reason, Text = text, Winner = winner };
Milestone(w, w.Player, $"fine della partita: {text}");
RecordYear(w, w.Player);
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Critical, $"Fine della partita: {text}",
EntityKind.Company, w.Player.Id.Value, w.Player.Id));
}
/// <summary>
/// Il giocatore è passato sotto il controllo di un'IA (borsa o insolvenza): esito secondo la
/// difficoltà (12.3). Con «Apprendista» non succede mai.
/// </summary>
public static void PlayerTakenOver(WorldContext ctx, Company controller)
{
var w = ctx.World;
var player = w.Player;
var d = w.Difficulty;
switch (d.PlayerTakeover)
{
case TakeoverRule.Disabled:
return;
case TakeoverRule.Immediate:
EndGame(ctx, GameOverReason.Takeover, $"{controller.Name} ha preso il controllo di {player.Name}", controller.Id);
return;
default:
if (player.Receivership) return;
player.Receivership = true;
player.ReceivershipBy = controller.Id;
player.ReceivershipUntilDay = ctx.Day + (long)d.TakeoverRansomYears * w.Calendar.DaysPerYear;
Milestone(w, player, $"in amministrazione controllata da {controller.Name}");
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Critical,
$"{player.Name} in amministrazione controllata da {controller.Name}: dividendo obbligatorio del " +
$"{w.Data.Balance.StockMarket.ReceivershipDividend * 100:0} %, niente nuovi prestiti; {d.TakeoverRansomYears} anni per riacquistare il " +
$"{w.Data.Balance.StockMarket.RansomShare * 100:0} %", EntityKind.Company, player.Id.Value, player.Id));
return;
}
}
/// <summary>Annota la fotografia dell'anno in corso della compagnia (Cronaca finale).</summary>
public static void RecordYear(World w, Company c) => AddYear(w, c, Snapshot(w, c, w.Clock.Year, c.YearEntries));
/// <summary>Aggiunge (o sostituisce, se è lo stesso anno) una fotografia annuale nello storico.</summary>
public static void AddYear(World w, Company c, CompanyYear snapshot)
{
if (c.History.Count > 0 && c.History[^1].Year == snapshot.Year) c.History[^1] = snapshot;
else c.History.Add(snapshot);
int max = w.Data.Balance.StockMarket.HistoryYears;
while (c.History.Count > max) c.History.RemoveAt(0);
}
/// <summary>Fotografia di una compagnia con le voci del conto economico indicate.</summary>
public static CompanyYear Snapshot(World w, Company c, int year, long[] entries)
{
double km = 0;
foreach (var e in w.Network.Edges)
{
if (e.Owner == c.Id && e.State != EdgeState.Demolished) km += e.Length / 1000;
}
int trains = 0;
foreach (var t in w.Trains)
{
if (t.Owner == c.Id && !t.Removed) trains++;
}
return new CompanyYear(year, c.NetWorth.Cents, c.Cash.Cents, Company.Revenue(entries), Company.OperatingProfit(entries),
c.Tier, trains, km, (long)Math.Round(c.SharePrice));
}
/// <summary>Annota un fatto saliente nella storia della compagnia (al massimo 60, i più recenti).</summary>
public static void Milestone(World w, Company c, string text)
{
c.Milestones.Add(new CompanyMilestone(w.Clock.Day, text));
while (c.Milestones.Count > 60) c.Milestones.RemoveAt(0);
}
}
@@ -0,0 +1,280 @@
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Simulation.Systems;
namespace ViaFerrea.Core.Simulation;
/// <summary>
/// Comandi di borsa (12.2): quotazione, compravendita di azioni, dividendi, offerte pubbliche con le
/// difese del bersaglio, aste delle compagnie fallite e fusione delle controllate (ADR 0012).
/// </summary>
public static class CorporateCommandHandlers
{
public static CommandResult Ipo(World w, Company company, IpoCommand c, RailCommandHandlers.Reply reply)
{
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»");
// 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)
return reply(CommandError.InvalidArgument, company.Listed
? $"Il flottante non può superare il {sm.SecondaryMaxFloat * 100:0} % del capitale"
: $"Si può offrire fino al {sm.IpoMaxShare * 100:0} % del capitale");
long shares = (long)Math.Round(company.Shares.Total * c.FloatShare);
shares = Math.Min(shares, company.Shares.Founder);
if (shares <= 0) return reply(CommandError.InvalidArgument, "Nessuna azione da offrire");
// il collocamento avviene al prezzo di denaro: il ricavato entra in cassa come aumento di capitale
company.SharePrice = Math.Max(company.SharePrice, Corporate.FundamentalPrice(w, company));
var proceeds = Money.FromCentsRounded(shares * Corporate.BidPrice(w, company));
company.Shares.Founder -= shares;
company.Shares.Public += shares;
bool first = !company.Listed;
company.Listed = true;
Corporate.Milestone(w, company, first ? $"si quota in borsa ({c.FloatShare * 100:0} %)" : $"aumento di capitale ({c.FloatShare * 100:0} %)");
w.Money.Transfer(Account.External, Account.Of(company.Id), proceeds, LedgerEntry.Shares);
w.Events.Add(new GameEvent(w.Clock.Day, EventKind.Company, EventSeverity.Opportunity,
first ? $"{company.Name} si quota in borsa: collocato il {c.FloatShare * 100:0} % per {proceeds}"
: $"{company.Name} colloca un altro {c.FloatShare * 100:0} % del capitale per {proceeds}",
EntityKind.Company, company.Id.Value, company.Id));
return reply(CommandError.None, $"Collocate {shares:N0} azioni per {proceeds}");
}
public static CommandResult BuyShares(World w, Company company, BuySharesCommand c, RailCommandHandlers.Reply reply)
{
var sm = w.Data.Balance.StockMarket;
if (!TryCompany(w, c.Company, out var target) || target.Defunct) return reply(CommandError.NotFound, "Compagnia inesistente");
if (c.Shares <= 0) return reply(CommandError.InvalidArgument, "Numero di azioni non valido");
long maxDaily = (long)(target.Shares.Total * sm.MaxDailyTradeShare);
if (c.Shares > maxDaily) return reply(CommandError.InvalidArgument, $"Al massimo {maxDaily:N0} azioni per ordine");
double ask = Corporate.Ask(w, target);
if (c.MaxPrice.Cents > 0 && ask > c.MaxPrice.Cents) return reply(CommandError.InvalidArgument, $"Prezzo di mercato {Money.FromCentsRounded(ask)} sopra il limite");
if (target.Id == company.Id) return Buyback(w, company, c.Shares, ask, reply);
if (!target.Listed) return reply(CommandError.NotAllowed, $"{target.Name} non è quotata");
long free = Corporate.FreeFloat(w, target);
if (free < c.Shares) return reply(CommandError.NotAllowed, $"Sul mercato ci sono solo {free:N0} azioni di {target.Name}");
if (target.IsPlayer && w.Difficulty.PlayerTakeover == TakeoverRule.Disabled
&& (double)(target.Shares.Of(company.Id) + c.Shares) / target.Shares.Outstanding > sm.ControlShare)
return reply(CommandError.NotAllowed, "Con questa difficoltà nessuno può controllare la compagnia del giocatore");
var cost = Money.FromCentsRounded(c.Shares * ask);
if (company.Cash < cost) return reply(CommandError.InsufficientFunds, $"Servono {cost}");
w.Money.Transfer(Account.Of(company.Id), Account.External, cost, LedgerEntry.Shares);
target.Shares.Public -= c.Shares;
target.Shares.Add(company.Id, c.Shares);
return reply(CommandError.None, $"Acquistate {c.Shares:N0} azioni di {target.Name} per {cost} ({target.Shares.FractionOf(company.Id) * 100:0.0} %)");
}
/// <summary>
/// Riacquisto di azioni proprie per conto del fondatore: dal flottante e, in amministrazione
/// controllata, dal controllante con il premio di riscatto (12.3).
/// </summary>
private static CommandResult Buyback(World w, Company company, long shares, double ask, RailCommandHandlers.Reply reply)
{
var sm = w.Data.Balance.StockMarket;
long fromFloat = Math.Min(shares, Corporate.FreeFloat(w, company));
long fromController = 0;
if (company.Receivership && company.ReceivershipBy.IsValid)
fromController = Math.Min(shares - fromFloat, company.Shares.Of(company.ReceivershipBy));
if (fromFloat + fromController <= 0) return reply(CommandError.NotAllowed, "Nessuna azione propria disponibile da riacquistare");
double ransom = ask * (1 + sm.RansomPremium);
var costFloat = Money.FromCentsRounded(fromFloat * ask);
var costController = Money.FromCentsRounded(fromController * ransom);
if (company.Cash < costFloat + costController) return reply(CommandError.InsufficientFunds, $"Servono {costFloat + costController}");
if (fromFloat > 0)
{
w.Money.Transfer(Account.Of(company.Id), Account.External, costFloat, LedgerEntry.Shares);
company.Shares.Public -= fromFloat;
company.Shares.Founder += fromFloat;
}
if (fromController > 0)
{
w.Money.Transfer(Account.Of(company.Id), Account.Of(company.ReceivershipBy), costController, LedgerEntry.Shares);
company.Shares.ByCompany[company.ReceivershipBy.Value] -= fromController;
company.Shares.Founder += fromController;
}
return reply(CommandError.None,
$"Riacquistate {fromFloat + fromController:N0} azioni per {costFloat + costController}: il fondatore ha ora il {company.Shares.FounderFraction * 100:0.0} %");
}
public static CommandResult SellShares(World w, Company company, SellSharesCommand c, RailCommandHandlers.Reply reply)
{
if (!TryCompany(w, c.Company, out var target) || target.Defunct) return reply(CommandError.NotFound, "Compagnia inesistente");
if (target.Id == company.Id) return reply(CommandError.NotAllowed, "Per collocare azioni proprie serve la quotazione");
if (c.Shares <= 0 || c.Shares > target.Shares.Of(company.Id)) return reply(CommandError.InvalidArgument, "Azioni insufficienti");
long maxDaily = (long)(target.Shares.Total * w.Data.Balance.StockMarket.MaxDailyTradeShare);
if (c.Shares > maxDaily) return reply(CommandError.InvalidArgument, $"Al massimo {maxDaily:N0} azioni per ordine");
double bid = Corporate.BidPrice(w, target);
if (c.MinPrice.Cents > 0 && bid < c.MinPrice.Cents) return reply(CommandError.InvalidArgument, $"Prezzo di mercato {Money.FromCentsRounded(bid)} sotto il limite");
var proceeds = Money.FromCentsRounded(c.Shares * bid);
target.Shares.ByCompany[company.Id.Value] -= c.Shares;
target.Shares.Public += c.Shares;
w.Money.Transfer(Account.External, Account.Of(company.Id), proceeds, LedgerEntry.Shares);
return reply(CommandError.None, $"Vendute {c.Shares:N0} azioni di {target.Name} per {proceeds}");
}
public static CommandResult PayDividend(World w, Company company, PayDividendCommand c, RailCommandHandlers.Reply reply)
{
if (c.PerShare.Cents <= 0) return reply(CommandError.InvalidArgument, "Dividendo non valido");
var total = new Money(c.PerShare.Cents * company.Shares.Outstanding);
if (company.Cash < total) return reply(CommandError.InsufficientFunds, $"Servono {total}");
Dividends.Distribute(w, company, total);
return reply(CommandError.None, $"Distribuiti {total} di dividendi ({c.PerShare} per azione)");
}
public static CommandResult LaunchBid(World w, Company company, LaunchBidCommand c, RailCommandHandlers.Reply reply)
{
var sm = w.Data.Balance.StockMarket;
if (!TryCompany(w, c.Target, out var target)) return reply(CommandError.NotFound, "Compagnia inesistente");
if (target.Id == company.Id) return reply(CommandError.InvalidArgument, "Non si può lanciare un'offerta su sé stessi");
// compagnia fallita: l'offerta è un'offerta all'asta degli attivi (prezzo × azioni)
var auction = w.Auctions.FirstOrDefault(a => a.Seller == target.Id && !a.Closed);
if (auction is not null) return AuctionBid(w, company, target, auction, c, reply);
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»");
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");
if (target.ControlledBy == company.Id) return reply(CommandError.NotAllowed, $"{target.Name} è già controllata");
if (w.Bids.Any(b => b.State == BidState.Open && b.Target == target.Id))
return reply(CommandError.NotAllowed, $"C'è già un'offerta in corso su {target.Name}");
double premium = c.PricePerShare.Cents / Math.Max(Corporate.MinPrice, target.SharePrice) - 1;
if (premium < sm.BidPremiumMin - 1e-9 || premium > sm.BidPremiumMax + 1e-9)
return reply(CommandError.InvalidArgument,
$"Il premio deve stare tra il {sm.BidPremiumMin * 100:0} e il {sm.BidPremiumMax * 100:0} % sul prezzo di mercato ({Money.FromCentsRounded(target.SharePrice)})");
double current = target.Shares.FractionOf(company.Id);
if (!(c.TargetShare > current) || c.TargetShare > 1) return reply(CommandError.InvalidArgument, "Quota obiettivo non valida");
long needed = (long)Math.Ceiling(c.TargetShare * target.Shares.Outstanding) - target.Shares.Of(company.Id);
var cost = new Money(needed * c.PricePerShare.Cents);
if (company.Cash < cost) return reply(CommandError.InsufficientFunds, $"Servono {cost} per l'offerta");
var bid = new TakeoverBid
{
Id = new BidId(w.NextIds.Bid++),
Bidder = company.Id,
Target = target.Id,
PricePerShare = c.PricePerShare.Cents,
TargetShare = c.TargetShare,
StartDay = w.Clock.Day,
EndDay = w.Clock.Day + sm.BidDurationDays,
};
w.Bids.Add(bid);
w.Events.Add(new GameEvent(w.Clock.Day, EventKind.Company, EventSeverity.Critical,
$"{company.Name} lancia un'offerta pubblica su {target.Name}: {c.PricePerShare} per azione (+{premium * 100:0} %) fino al {c.TargetShare * 100:0} %",
EntityKind.Company, target.Id.Value, company.Id));
return reply(CommandError.None, $"Offerta lanciata su {target.Name} per {sm.BidDurationDays} giorni", bid.Id.Value);
}
private static CommandResult AuctionBid(World w, Company company, Company seller, Auction a, LaunchBidCommand c, RailCommandHandlers.Reply reply)
{
long offer = checked(c.PricePerShare.Cents * seller.Shares.Total);
if (offer < a.MinPriceCents) return reply(CommandError.InvalidArgument, $"Base d'asta {new Money(a.MinPriceCents)}");
if (offer <= a.BestPriceCents) return reply(CommandError.InvalidArgument, $"Serve più di {new Money(a.BestPriceCents)}");
if (company.Cash.Cents < offer) return reply(CommandError.InsufficientFunds, $"Servono {new Money(offer)}");
a.BestBidder = company.Id;
a.BestPriceCents = offer;
return reply(CommandError.None, $"Offerta di {new Money(offer)} per gli attivi di {seller.Name} (chiusura al giorno {a.EndDay})");
}
public static CommandResult RespondBid(World w, Company company, RespondBidCommand c, RailCommandHandlers.Reply reply)
{
var bid = w.Bids.FirstOrDefault(b => b.Id == c.Bid);
if (bid is null || bid.State != BidState.Open) return reply(CommandError.NotFound, "Offerta inesistente o conclusa");
var target = w.Company(bid.Target);
if (company.Id == bid.Target) return Defend(w, company, bid, c, reply);
if (company.Id == bid.Bidder) return reply(CommandError.NotAllowed, "L'offerente non può aderire alla propria offerta");
long held = target.Shares.Of(company.Id);
if (held <= 0) return reply(CommandError.NotAllowed, $"La compagnia non possiede azioni di {target.Name}");
if (!c.Accept)
{
bid.Accepted.Remove(company.Id);
return reply(CommandError.None, "Adesione ritirata");
}
if (!bid.Accepted.Contains(company.Id)) bid.Accepted.Add(company.Id);
return reply(CommandError.None, $"Aderito all'offerta con {held:N0} azioni di {target.Name}");
}
/// <summary>Difese del bersaglio (12.2): riacquisto, dividendo straordinario, cavaliere bianco.</summary>
private static CommandResult Defend(World w, Company target, TakeoverBid bid, RespondBidCommand c, RailCommandHandlers.Reply reply)
{
var sm = w.Data.Balance.StockMarket;
switch (c.Defense)
{
case BidDefense.Buyback:
{
double ask = Corporate.Ask(w, target);
long free = Corporate.FreeFloat(w, target);
long affordable = (long)Math.Floor(Math.Max(0, target.Cash.Cents) / Math.Max(Corporate.MinPrice, ask));
long shares = Math.Min(free, affordable);
if (shares <= 0) return reply(CommandError.InsufficientFunds, "Nessuna azione riacquistabile con la cassa disponibile");
var cost = Money.FromCentsRounded(shares * ask);
w.Money.Transfer(Account.Of(target.Id), Account.External, cost, LedgerEntry.Shares);
target.Shares.Public -= shares;
target.Shares.Founder += shares;
bid.Defenses |= 1 << (int)BidDefense.Buyback;
return reply(CommandError.None, $"Riacquistate {shares:N0} azioni dal mercato per {cost}");
}
case BidDefense.ExtraDividend:
{
var total = Money.FromCentsRounded(Math.Max(0, target.Cash.Cents) * sm.ExtraDividendCashShare);
if (total.Cents <= 0) return reply(CommandError.InsufficientFunds, "Cassa insufficiente per un dividendo straordinario");
Dividends.Distribute(w, target, total);
target.ExtraSentiment += sm.ExtraDividendSentimentBoost;
bid.Defenses |= 1 << (int)BidDefense.ExtraDividend;
return reply(CommandError.None, $"Dividendo straordinario di {total}: il titolo diventa più caro");
}
case BidDefense.WhiteKnight:
{
if (!TryCompany(w, c.Knight, out var knight) || knight.Defunct || knight.Id == bid.Bidder || knight.Id == target.Id)
return reply(CommandError.InvalidArgument, "Cavaliere bianco non valido");
if (!knight.IsPlayer && w.Data.Ai.Personalities.FirstOrDefault(p => p.Id == knight.AiPersonality)?.TargetsPlayer == true && target.IsPlayer)
return reply(CommandError.NotAllowed, $"{knight.Name} rifiuta di fare da cavaliere bianco");
double price = bid.PricePerShare * (1 + sm.WhiteKnightPremium);
long free = Corporate.FreeFloat(w, target);
long affordable = (long)Math.Floor(Math.Max(0, knight.Cash.Cents) / price);
long shares = Math.Min(free, affordable);
if (shares <= 0) return reply(CommandError.InsufficientFunds, $"{knight.Name} non ha cassa sufficiente");
var cost = Money.FromCentsRounded(shares * price);
w.Money.Transfer(Account.Of(knight.Id), Account.External, cost, LedgerEntry.Shares);
target.Shares.Public -= shares;
target.Shares.Add(knight.Id, shares);
bid.Knight = knight.Id;
bid.Defenses |= 1 << (int)BidDefense.WhiteKnight;
w.Events.Add(new GameEvent(w.Clock.Day, EventKind.Company, EventSeverity.Info,
$"{knight.Name} interviene come cavaliere bianco e compra {shares:N0} azioni di {target.Name}", EntityKind.Company, target.Id.Value, knight.Id));
return reply(CommandError.None, $"{knight.Name} compra {shares:N0} azioni dal mercato");
}
default:
bid.Defenses |= 1 << (int)BidDefense.None;
return reply(CommandError.None, "Offerta respinta: il consiglio invita gli azionisti a non aderire");
}
}
public static CommandResult MergeCompany(World w, Company company, MergeCompanyCommand c, WorldContext ctx, RailCommandHandlers.Reply reply)
{
var sm = w.Data.Balance.StockMarket;
if (!TryCompany(w, c.Subsidiary, out var sub) || sub.Defunct) return reply(CommandError.NotFound, "Compagnia inesistente");
if (sub.ControlledBy != company.Id) return reply(CommandError.NotAllowed, $"{sub.Name} non è controllata dalla compagnia");
if (w.Clock.Day - sub.ControlSinceDay < sm.MergeAfterDays)
return reply(CommandError.NotAllowed, $"La fusione è possibile dopo {sm.MergeAfterDays} giorni di controllo");
double minority = (sub.Shares.Outstanding - sub.Shares.Of(company.Id)) * sub.SharePrice;
if (company.Cash.Cents < minority) return reply(CommandError.InsufficientFunds, $"Servono {Money.FromCentsRounded(minority)} per liquidare le minoranze");
if (sub.IsPlayer && w.GameOver is null)
return reply(CommandError.NotAllowed, "La compagnia del giocatore non si può incorporare finché la partita è in corso");
Corporate.Merge(ctx, company, sub);
return reply(CommandError.None, $"{sub.Name} incorporata");
}
private static bool TryCompany(World w, CompanyId id, out Company c)
{
c = null!;
if (!id.IsValid || id.Value >= w.Companies.Count) return false;
c = w.Companies[id.Value];
return true;
}
}
@@ -0,0 +1,91 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
namespace ViaFerrea.Core.Simulation;
/// <summary>
/// Stimatori economici condivisi da IA e tooltip «perché» (12.1): ricavi per unità e per viaggio,
/// tempi di giro, costi di costruzione ed esercizio. Leggono solo informazioni pubbliche.
/// </summary>
public static class Estimators
{
/// <summary>Ricavo per unità di merce su <paramref name="km"/> al prezzo globale corrente (centesimi).</summary>
public static double FreightPerUnit(World w, int good, double km)
{
var t = w.Data.Balance.Tariffs;
double priceFactor = t.FreightFixedWeight + t.FreightPriceWeight * w.Market.GlobalPrice[good] / w.Data.Goods[good].BasePrice;
return t.FreightBaseRate * priceFactor * DMath.Pow(Math.Max(km, 0.1), t.FreightKmExponent) * w.Difficulty.TariffMultiplier;
}
/// <summary>Ricavo per passeggero su <paramref name="km"/> nella classe indicata (centesimi).</summary>
public static double PassengerPerTrip(World w, PaxClass cls, double km)
{
var t = w.Data.Balance.Tariffs;
double mult = t.ClassMultipliers[cls == PaxClass.Staff ? "staff" : "worker"];
return t.PaxBaseFare * DMath.Pow(Math.Max(km, 0.1), t.PaxKmExponent) * mult * w.Difficulty.TariffMultiplier;
}
/// <summary>Durata di un giro completo (andata e ritorno con le soste) in giorni di calendario.</summary>
public static double RoundTripDays(World w, double km, double maxSpeedKmh)
{
var p = w.Data.Ai.Planning;
double minutes = 2 * km / Math.Max(1, maxSpeedKmh * p.SpeedFactor) * 60 + 2 * p.DwellMinutes;
return w.Calendar.TrainMinutesToDays(minutes);
}
/// <summary>Costo d'esercizio annuo di un treno con la manutenzione stimata.</summary>
public static double TrainCostPerYear(World w, VehicleDef loco, VehicleDef car, int cars) =>
(loco.RunningCostPerYear + car.RunningCostPerYear * cars) * (1 + w.Data.Ai.Planning.MaintenanceCostShare);
public static long TrainPrice(VehicleDef loco, VehicleDef car, int cars) => loco.Price + car.Price * cars;
/// <summary>Costo di una stazione con i binari indicati per la compagnia.</summary>
public static long StationCost(World w, Company c, int platforms) =>
(long)((w.Data.Construction.Costs.StationBase + w.Data.Construction.Costs.StationPerPlatform * platforms) * RailCommandHandlers.CostMultiplier(w, c));
public static long DepotCost(World w, Company c, string size) =>
(long)(w.Data.Construction.Costs.DepotBySize[size] * RailCommandHandlers.CostMultiplier(w, c));
/// <summary>Costo di massima di un binario in linea d'aria (senza opere), per ordinare i candidati.</summary>
public static long RoughTrackCost(World w, Company c, double km) =>
(long)(w.Data.Construction.Costs.BasePerMeter * 1000 * km * RailCommandHandlers.CostMultiplier(w, c));
/// <summary>Locomotiva più recente non elettrica disponibile nell'anno.</summary>
public static VehicleDef? BestLocomotive(World w, int year)
{
VehicleDef? best = null;
foreach (var v in w.Data.Vehicles)
{
if (v.Kind != VehicleKind.Locomotive || v.EraFrom > year || (v.EraTo is { } to && year > to)) continue;
if (v.Traction is Traction.Electric or Traction.HighSpeed) continue;
if (best is null || v.EraFrom > best.EraFrom) best = v;
}
return best;
}
/// <summary>Carro più economico che trasporta il bene nell'anno.</summary>
public static VehicleDef? WagonFor(World w, int good, int year)
{
VehicleDef? best = null;
foreach (var v in w.Data.Vehicles)
{
if (v.Kind != VehicleKind.Wagon || v.EraFrom > year || (v.EraTo is { } to && year > to)) continue;
if (Array.IndexOf(v.GoodIndices, good) < 0) continue;
if (best is null || v.Price < best.Price) best = v;
}
return best;
}
/// <summary>Carrozza della classe indicata disponibile nell'anno.</summary>
public static VehicleDef? CoachFor(World w, PaxClass cls, int year)
{
VehicleDef? best = null;
foreach (var v in w.Data.Vehicles)
{
if (v.Kind != VehicleKind.Coach || v.Class != cls || v.EraFrom > year || (v.EraTo is { } to && year > to)) continue;
if (best is null || v.Price < best.Price) best = v;
}
return best;
}
}
@@ -0,0 +1,111 @@
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Simulation.Systems;
namespace ViaFerrea.Core.Simulation;
/// <summary>Comandi delle industrie possedute (sezione 11): acquisto, budget, revisione, ammodernamento, ricambi.</summary>
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»");
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}");
if (ind.Level <= 0) return reply(CommandError.NotAllowed, $"{ind.Name} è inattiva e non è in vendita");
var price = IndustryMath.Valuation(w, ind);
if (c.Offer < price) return reply(CommandError.InvalidArgument, $"Offerta troppo bassa: i proprietari chiedono almeno {price}");
if (company.Cash < c.Offer) return reply(CommandError.InsufficientFunds, "Cassa insufficiente");
w.Money.Transfer(Account.Of(company.Id), Account.External, c.Offer, LedgerEntry.IndustryPurchase);
ind.Owner = company.Id;
ind.AcquiredDay = w.Clock.Day;
ind.MonthsHighMargin = 0;
w.Events.Add(new GameEvent(w.Clock.Day, EventKind.Industry, EventSeverity.Info,
$"{company.Name} acquista {ind.Name} per {c.Offer}", EntityKind.Industry, ind.Id.Value, company.Id));
return reply(CommandError.None, $"{ind.Name} acquistata per {c.Offer}", ind.Id.Value);
}
public static CommandResult SetPolicy(World w, Company company, SetIndustryPolicyCommand c, RailCommandHandlers.Reply reply)
{
if (!TryOwned(w, company, c.Industry, out var ind, out var error)) return reply(error.Error, error.Message);
if (c.Budget > IndustryBudget.High) return reply(CommandError.InvalidArgument, "Budget non valido");
ind.Budget = c.Budget;
var b = w.Data.Balance.IndustryMaintenance.For(c.Budget);
return reply(CommandError.None,
$"{ind.Name}: budget {BudgetName(c.Budget)} (recupero {b.RecoveryPerDay:0.00} punti al giorno, {b.CostShareOfRevenue * 100:0} % dei ricavi, {b.SparePartsPerLevelPerMonth * ind.Level} ricambi al mese)");
}
public static CommandResult Overhaul(World w, Company company, OverhaulIndustryCommand c, RailCommandHandlers.Reply reply)
{
if (!TryOwned(w, company, c.Industry, out var ind, out var error)) return reply(error.Error, error.Message);
if (ind.Level <= 0) return reply(CommandError.NotAllowed, $"{ind.Name} è inattiva");
if (ind.IsStopped(w.Clock.Day)) return reply(CommandError.NotAllowed, $"{ind.Name} è già ferma");
if (ind.PendingWork != IndustryWork.None) return reply(CommandError.NotAllowed, $"{ind.Name} ha già un lavoro programmato");
var m = w.Data.Balance.IndustryMaintenance;
ind.PendingWork = IndustryWork.Overhaul;
int need = IndustryMath.MachineryRequired(ind, m);
return reply(CommandError.None,
$"{ind.Name}: revisione programmata ({m.OverhaulDays} giorni di fermo); servono {need} macchinari (in scorta {ind.Machinery}) e personale almeno all'{m.OverhaulMinStaffCoverage * 100:0} %");
}
public static CommandResult Upgrade(World w, Company company, UpgradeIndustryCommand c, RailCommandHandlers.Reply reply)
{
if (!TryOwned(w, company, c.Industry, out var ind, out var error)) return reply(error.Error, error.Message);
if (ind.Level <= 0) return reply(CommandError.NotAllowed, $"{ind.Name} è inattiva");
if (ind.Level >= w.Data.Balance.Growth.MaxLevel) return reply(CommandError.NotAllowed, $"{ind.Name} è già al livello massimo");
if (ind.IsStopped(w.Clock.Day)) return reply(CommandError.NotAllowed, $"{ind.Name} è ferma");
if (ind.PendingWork != IndustryWork.None) return reply(CommandError.NotAllowed, $"{ind.Name} ha già un lavoro programmato");
var cost = IndustryMaintenanceSystem.UpgradeCost(ind);
if (company.Cash < cost) return reply(CommandError.InsufficientFunds, $"Servono {cost} per l'ammodernamento");
var m = w.Data.Balance.IndustryMaintenance;
ind.PendingWork = IndustryWork.Upgrade;
int need = IndustryMath.MachineryRequired(ind, m);
return reply(CommandError.None,
$"{ind.Name}: ammodernamento al livello {ind.Level + 1} programmato ({cost}, {m.UpgradeDays} giorni); servono {need} macchinari (in scorta {ind.Machinery})");
}
public static CommandResult OrderParts(World w, Company company, OrderPartsCommand c, RailCommandHandlers.Reply reply)
{
if (!TryOwned(w, company, c.Industry, out var ind, out var error)) return reply(error.Error, error.Message);
int max = w.Data.Balance.IndustryMaintenance.MaxOrderedParts;
if (c.Quantity < 0 || c.Quantity > max) return reply(CommandError.InvalidArgument, $"Ordine tra 0 e {max} unità");
ind.PartsOrdered = c.Quantity;
string unit = w.Data.Goods[w.Data.SparePartsGood].Unit;
return reply(CommandError.None,
$"{ind.Name}: ordinati {c.Quantity} {unit} di ricambi oltre la scorta della politica (scorta attuale {ind.SpareParts})");
}
public static string BudgetName(IndustryBudget b) => b switch
{
IndustryBudget.None => "Nessuno",
IndustryBudget.High => "Alto",
_ => "Base",
};
private static bool TryIndustry(World w, IndustryId id, out Industry ind)
{
ind = null!;
if (!id.IsValid || id.Value >= w.Industries.Count) return false;
ind = w.Industries[id.Value];
return true;
}
private static bool TryOwned(World w, Company company, IndustryId id, out Industry ind, out (CommandError Error, string Message) error)
{
error = default;
if (!TryIndustry(w, id, out ind) || ind.Closed)
{
error = (CommandError.NotFound, "Industria inesistente");
return false;
}
if (ind.Owner != company.Id)
{
error = (CommandError.NotAllowed, "L'industria non appartiene alla compagnia");
return false;
}
return true;
}
}
@@ -3,6 +3,8 @@ using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Map;
using ViaFerrea.Core.Simulation.Systems;
namespace ViaFerrea.Core.Simulation;
/// <summary>Creazione e collocazione delle industrie durante la partita (nascita per domanda insoddisfatta).</summary>
@@ -47,6 +49,10 @@ public static class IndustryPlacer
ind.OutputStock[o] = units;
w.Goods.Produced[def.Recipe.Outputs[o].GoodIndex] += units;
}
// scorta iniziale di ricambi per la manutenzione degli impianti (sezione 11)
var im = w.Data.Balance.IndustryMaintenance;
ind.SpareParts = (int)Math.Round(IndustryMath.MonthlyPartsUse(ind, im) * im.InitialPartsMonths);
w.Goods.Produced[w.Data.SparePartsGood] += ind.SpareParts;
w.Money.Transfer(Account.External, Account.Of(ind.Id), new Money(ib.StartingCash), LedgerEntry.Other);
MarkFootprint(w, cellX, cellY, footprint, CellType.Industry);
return ind;
@@ -90,6 +90,7 @@ public static class MaintenanceCommandHandlers
public static CommandResult OrderParts(World w, Company company, OrderPartsCommand c, RailCommandHandlers.Reply reply)
{
if (c.Industry.IsValid) return IndustryCommandHandlers.OrderParts(w, company, c, reply);
if (!c.Depot.IsValid || c.Depot.Value >= w.Network.Depots.Count) return reply(CommandError.NotFound, "Deposito inesistente");
var d = w.Network.Depots[c.Depot.Value];
if (d.Owner != company.Id || !w.Network.IsAlive(d)) return reply(CommandError.NotFound, "Deposito inesistente");
@@ -14,6 +14,8 @@ public sealed class ScenarioFile
public required ulong Seed { get; init; }
public int StartYear { get; set; } = 1850;
public string Difficulty { get; set; } = "imprenditore";
/// <summary>Numero di concorrenti IA (sostituisce quello della difficoltà; null = come la difficoltà).</summary>
public int? AiCompetitors { get; set; }
public required ScenarioTerrain Terrain { get; init; }
public List<ScenarioTown> Towns { get; set; } = [];
public List<ScenarioIndustry> Industries { get; set; } = [];
@@ -104,6 +104,9 @@ public static class ScenarioLoader
StartYear = file.StartYear,
DifficultyId = file.Difficulty,
PlayerCompanyName = file.Player?.Name ?? "Società Ferroviaria Valdoria",
DifficultyOverride = file.AiCompetitors is { } ai
? DifficultyOverrides.Apply(data.DifficultyPreset(file.Difficulty), [("aiCompetitors", ai)])
: null,
};
var world = WorldFactory.FromMap(data, map, settings);
if (file.Player?.Cash is { } cash)
@@ -1,4 +1,5 @@
using System.Diagnostics;
using ViaFerrea.Core.Simulation.Ai;
using ViaFerrea.Core.Simulation.Systems;
namespace ViaFerrea.Core.Simulation;
@@ -35,9 +36,12 @@ public sealed class SystemPipeline(IReadOnlyList<ISimSystem> systems)
new DemandSystem(),
new EmploymentSystem(),
new IndustrySystem(),
new IndustryMaintenanceSystem(),
new TownSystem(),
new MarketSystem(),
new FinanceSystem(),
new StockMarketSystem(),
new AiSystem(),
new HashSystem(),
]);
@@ -4,8 +4,9 @@ using ViaFerrea.Core.Economy;
namespace ViaFerrea.Core.Simulation.Systems;
/// <summary>
/// Domanda giornaliera: consumo desiderato delle città (con elasticità al prezzo) e input
/// richiesti dalle industrie al loro potenziale di lavoro. Alimenta D del mercato.
/// Domanda giornaliera: consumo desiderato delle città (con elasticità al prezzo), input
/// richiesti dalle industrie al loro potenziale di lavoro e ricambi per gli impianti.
/// Alimenta D del mercato.
/// </summary>
public sealed class DemandSystem : ISimSystem
{
@@ -30,6 +31,7 @@ public sealed class DemandSystem : ISimSystem
}
int dpm = w.Calendar.DaysPerMonth;
var im = data.Balance.IndustryMaintenance;
foreach (var ind in w.Industries)
{
if (ind.Closed || ind.Level <= 0)
@@ -37,6 +39,8 @@ public sealed class DemandSystem : ISimSystem
Array.Clear(ind.InputDemandToday);
continue;
}
// ricambi per la manutenzione degli impianti (sezione 11)
market.DemandToday[data.SparePartsGood] += (double)IndustryMath.MonthlyPartsUse(ind, im) / dpm;
double eLabor = Math.Min(ind.CovWorkers, ind.CovStaff) * IndustryMath.ProfitFactor(ind, data.Balance.Industry)
* IndustryMath.ConditionMultiplier(ind.Condition, data.Balance.IndustryMaintenance);
double cycles = ind.CyclesPerDayAtFullCapacity(dpm) * eLabor;
@@ -21,7 +21,7 @@ public sealed class FinanceSystem : ISimSystem
PayRunningCosts(w);
foreach (var c in w.Companies)
{
if (c.Bankrupt) continue;
if (c.Defunct) continue;
c.NegativeCashDays = c.Cash.IsNegative ? c.NegativeCashDays + 1 : 0;
if (c.NegativeCashDays >= w.Difficulty.BankruptcyDays)
{
@@ -35,8 +35,14 @@ public sealed class FinanceSystem : ISimSystem
UpdateBookValues(w);
foreach (var c in w.Companies)
{
if (c.Merged) continue;
if (!c.Bankrupt) PayLoans(w, c);
c.Rating = ComputeRating(w, c);
if (!c.Bankrupt) Tiers.Evaluate(ctx, c);
// utile del mese chiuso nell'anello dei 12 mesi (borsa, 12.2); il nuovo mese parte senza dividendi
c.ProfitRing[c.ProfitRingIndex] = Company.OperatingProfit(c.MonthEntries);
c.ProfitRingIndex = (c.ProfitRingIndex + 1) % c.ProfitRing.Length;
c.DividendRing[c.ProfitRingIndex] = 0;
Array.Clear(c.MonthEntries);
}
}
@@ -72,7 +78,7 @@ public sealed class FinanceSystem : ISimSystem
}
for (int i = 0; i < w.Companies.Count; i++)
{
if (_running[i] <= 0 || w.Companies[i].Bankrupt) continue;
if (_running[i] <= 0 || w.Companies[i].Defunct) continue;
w.Money.Transfer(Account.Of(w.Companies[i].Id), Account.External, Money.FromCentsRounded(_running[i]), LedgerEntry.RunningCosts);
}
}
@@ -0,0 +1,236 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
namespace ViaFerrea.Core.Simulation.Systems;
/// <summary>
/// Manutenzione degli impianti (guida, sezione 11): usura giornaliera con l'utilizzo, recupero e
/// costo del budget del proprietario, consumo mensile di ricambi, fermi per guasto e incidenti,
/// revisioni e ammodernamenti che aspettano i macchinari, decisioni dei proprietari privati e
/// conguaglio mensile della cassa delle industrie possedute da una compagnia (ADR 0011).
/// </summary>
public sealed class IndustryMaintenanceSystem : ISimSystem
{
public string Name => "IndustryMaintenance";
public void Step(WorldContext ctx)
{
if (!ctx.IsNewDay) return;
var w = ctx.World;
var m = w.Data.Balance.IndustryMaintenance;
var rng = w.Stream("industry-maintenance");
foreach (var ind in w.Industries)
{
if (ind.Closed) continue;
Daily(ctx, ind, m, rng);
}
if (ctx.IsNewMonth && ctx.Day > 0)
{
foreach (var ind in w.Industries)
{
if (ind.Closed) continue;
ConsumeParts(w, ind, m);
if (!ind.Owner.IsValid) NpcOwner(w, ind, m);
else SettleWithOwner(w, ind, m);
}
}
if (ctx.IsNewYear)
{
foreach (var ind in w.Industries) ind.MaintenanceSpentYear = 0;
}
}
private static void Daily(WorldContext ctx, Industry ind, IndustryMaintenanceBalance m, Rng rng)
{
var w = ctx.World;
if (ind.StoppedUntilDay >= 0 && !ind.IsStopped(ctx.Day)) EndStop(ctx, ind);
if (ind.PendingWork != IndustryWork.None && !ind.IsStopped(ctx.Day)) TryStartWork(ctx, ind, m);
if (ind.Level <= 0) return;
// usura con l'utilizzo e recupero del budget (dimezzato senza ricambi)
var budget = m.For(ind.Budget);
double wear = m.WearPerDay * Math.Max(0, ind.Efficiency) * ind.Def.WearIntensity * w.Difficulty.WearMultiplier;
double recovery = budget.RecoveryPerDay * (ind.PartsShort ? m.NoPartsRecoveryFactor : 1.0);
ind.Condition = Math.Clamp(ind.Condition - wear + recovery, 0, 100);
// costo del budget: quota dei ricavi medi giornalieri
if (budget.CostShareOfRevenue > 0 && ind.RevenueEma > 0)
{
var cost = Money.FromCentsRounded(ind.RevenueEma * budget.CostShareOfRevenue);
w.Money.Transfer(Account.Of(ind.Id), Account.External, cost, LedgerEntry.Other);
ind.PurchasesToday += cost.Cents;
ind.MaintenanceSpentYear += cost.Cents;
}
// rischio di fermo sotto la soglia
if (ind.IsStopped(ctx.Day) || ind.Condition >= m.BreakdownPivot) return;
double hazard = m.BreakdownBase * DMath.Exp((m.BreakdownPivot - ind.Condition) / m.BreakdownScale);
if (rng.NextDouble() >= hazard) return;
var town = NearestTown(w, ind, m.TownEffectRadiusKm);
if (ind.Condition < m.AccidentBelow && ind.Def.Kind != IndustryKind.Primary)
{
Stop(w, ind, IndustryStop.Accident, m.AccidentDays, m);
string where = "";
if (town is not null)
{
int lost = (int)Math.Round(town.Population * m.AccidentPopulationLoss);
town.Population = Math.Max(0, town.Population - lost);
where = $"; {town.Name} perde {lost} abitanti";
}
ctx.Emit(EventKind.Industry, EventSeverity.Critical,
$"Incidente grave a {ind.Name}: impianti fermi per {m.AccidentDays} giorni{where}", EntityKind.Industry, ind.Id.Value);
return;
}
int days = m.BreakdownDays[0] + rng.NextInt(m.BreakdownDays[1] - m.BreakdownDays[0] + 1);
Stop(w, ind, IndustryStop.Breakdown, days, m);
if (town is not null)
{
for (int c = 0; c < Town.CategoryCount; c++)
town.Satisfaction[c] = Math.Max(0, town.Satisfaction[c] - m.BreakdownTownSatisfaction);
}
ctx.Emit(EventKind.Industry, EventSeverity.Warning,
$"Guasto agli impianti di {ind.Name} (condizione {ind.Condition:0}): fermo di {days} giorni", EntityKind.Industry, ind.Id.Value);
}
/// <summary>Ferma l'industria per i giorni indicati e lo annota nello storico.</summary>
public static void Stop(World w, Industry ind, IndustryStop kind, int days, IndustryMaintenanceBalance m)
{
long today = w.Clock.Day;
ind.StoppedUntilDay = Math.Max(ind.StoppedUntilDay, today + days);
ind.StopKind = kind;
ind.StopHistory.Add(new IndustryStopRecord(today, days, kind));
while (ind.StopHistory.Count > m.StopHistoryLength) ind.StopHistory.RemoveAt(0);
}
private static void EndStop(WorldContext ctx, Industry ind)
{
var kind = ind.StopKind;
ind.StoppedUntilDay = -1;
ind.StopKind = IndustryStop.None;
switch (kind)
{
case IndustryStop.Overhaul:
ind.Condition = 100;
ctx.Emit(EventKind.Industry, EventSeverity.Info, $"{ind.Name}: revisione conclusa, impianti come nuovi", EntityKind.Industry, ind.Id.Value);
break;
case IndustryStop.Upgrade:
int max = ctx.World.Data.Balance.Growth.MaxLevel;
ind.Level = Math.Min(max, ind.Level + 1);
ind.Condition = Math.Max(ind.Condition, 100);
ctx.Emit(EventKind.Industry, EventSeverity.Opportunity, $"{ind.Name}: ammodernamento concluso, ora al livello {ind.Level}", EntityKind.Industry, ind.Id.Value);
break;
}
}
/// <summary>Avvia la revisione o l'ammodernamento quando ci sono macchinari, personale e cassa.</summary>
private static void TryStartWork(WorldContext ctx, Industry ind, IndustryMaintenanceBalance m)
{
var w = ctx.World;
int machinery = IndustryMath.MachineryRequired(ind, m);
if (ind.Machinery < machinery) return;
if (ind.PendingWork == IndustryWork.Overhaul)
{
if (ind.CovStaff < m.OverhaulMinStaffCoverage) return;
ConsumeMachinery(w, ind, machinery);
ind.PendingWork = IndustryWork.None;
Stop(w, ind, IndustryStop.Overhaul, m.OverhaulDays, m);
ctx.Emit(EventKind.Industry, EventSeverity.Info, $"{ind.Name}: inizia la revisione programmata ({m.OverhaulDays} giorni)", EntityKind.Industry, ind.Id.Value);
return;
}
if (ind.Level >= w.Data.Balance.Growth.MaxLevel)
{
ind.PendingWork = IndustryWork.None;
return;
}
var cost = UpgradeCost(ind);
var payer = ind.Owner.IsValid ? Account.Of(ind.Owner) : Account.Of(ind.Id);
var cash = ind.Owner.IsValid ? w.Company(ind.Owner).Cash : ind.Cash;
if (cash < cost) return;
w.Money.Transfer(payer, Account.External, cost, ind.Owner.IsValid ? LedgerEntry.IndustryPurchase : LedgerEntry.Other);
ConsumeMachinery(w, ind, machinery);
ind.PendingWork = IndustryWork.None;
Stop(w, ind, IndustryStop.Upgrade, m.UpgradeDays, m);
ctx.Emit(EventKind.Industry, EventSeverity.Info, $"{ind.Name}: inizia l'ammodernamento al livello {ind.Level + 1} ({m.UpgradeDays} giorni)", EntityKind.Industry, ind.Id.Value);
}
/// <summary>Costo in capitale dell'ammodernamento al livello successivo.</summary>
public static Money UpgradeCost(Industry ind) => new(ind.Def.UpgradeCost * Math.Max(1, ind.Level));
private static void ConsumeMachinery(World w, Industry ind, int units)
{
ind.Machinery -= units;
w.Goods.Consumed[w.Data.MachineryGood] += units;
}
/// <summary>Consumo mensile di ricambi della politica: senza scorta sufficiente il recupero si dimezza.</summary>
private static void ConsumeParts(World w, Industry ind, IndustryMaintenanceBalance m)
{
int need = IndustryMath.MonthlyPartsUse(ind, m);
int used = Math.Min(need, ind.SpareParts);
ind.SpareParts -= used;
w.Goods.Consumed[w.Data.SparePartsGood] += used;
ind.PartsShort = used < need;
if (ind.PartsOrdered > 0)
{
// i ricambi ordinati arrivati restano in scorta: l'ordine si riduce di quanto consegnato
int target = IndustryMath.PartsTarget(ind, m);
if (ind.SpareParts >= target) ind.PartsOrdered = 0;
}
}
/// <summary>Proprietario privato (NPC): budget dal margine, revisione sotto soglia, ammodernamento se conviene.</summary>
private static void NpcOwner(World w, Industry ind, IndustryMaintenanceBalance m)
{
double margin = ind.Margin;
ind.Budget = margin > m.NpcHighMargin ? IndustryBudget.High : margin < 0 ? IndustryBudget.None : IndustryBudget.Base;
ind.MonthsHighMargin = margin > m.NpcUpgradeMargin ? ind.MonthsHighMargin + 1 : 0;
if (ind.PendingWork != IndustryWork.None || ind.IsStopped(w.Clock.Day) || ind.Level <= 0) return;
double machineryPrice = w.Market.GlobalPrice[w.Data.MachineryGood];
if (ind.Condition < m.NpcOverhaulBelow)
{
double cost = machineryPrice * m.OverhaulMachineryPerLevel * ind.Level;
if (ind.Cash.Cents >= cost) ind.PendingWork = IndustryWork.Overhaul;
return;
}
if (ind.MonthsHighMargin >= m.NpcUpgradeYears * w.Calendar.MonthsPerYear && ind.Level < w.Data.Balance.Growth.MaxLevel
&& ind.SpareParts >= IndustryMath.PartsTarget(ind, m) && !ind.PartsShort)
{
double cost = machineryPrice * m.UpgradeMachineryPerLevel * ind.Level + UpgradeCost(ind).Cents;
if (ind.Cash.Cents >= cost)
{
ind.PendingWork = IndustryWork.Upgrade;
ind.MonthsHighMargin = 0;
}
}
}
/// <summary>
/// Industria di una compagnia: trattiene la cassa di riserva e versa il resto al proprietario,
/// che ne copre le perdite (voce «Industrie» del conto economico).
/// </summary>
private static void SettleWithOwner(World w, Industry ind, IndustryMaintenanceBalance m)
{
var owner = w.Company(ind.Owner);
long delta = ind.Cash.Cents - m.OwnerCashReserve;
if (delta > 0) w.Money.Transfer(Account.Of(ind.Id), Account.Of(owner.Id), new Money(delta), LedgerEntry.Industries);
else if (delta < 0 && !owner.Bankrupt) w.Money.Transfer(Account.Of(owner.Id), Account.Of(ind.Id), new Money(-delta), LedgerEntry.Industries);
}
/// <summary>Città più vicina entro il raggio (al bordo), o null.</summary>
public static Town? NearestTown(World w, Industry ind, double radiusKm)
{
Town? best = null;
double bestKm = radiusKm;
foreach (var t in w.Towns)
{
double km = w.TownEdgeDistanceKm(t, ind.Position);
if (km <= bestKm)
{
bestKm = km;
best = t;
}
}
return best;
}
}
@@ -1,3 +1,4 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
@@ -36,4 +37,63 @@ public static class IndustryMath
double perDay = ind.CyclesPerDayAtFullCapacity(daysPerMonth) * inputs[inputIndex].PerCycle;
return (int)Math.Ceiling(perDay * ind.Def.StorageDays);
}
/// <summary>Ricambi consumati al mese dalla politica corrente: unità per livello.</summary>
public static int MonthlyPartsUse(Industry ind, IndustryMaintenanceBalance m) =>
ind.Level <= 0 || ind.Closed ? 0 : m.For(ind.Budget).SparePartsPerLevelPerMonth * ind.Level;
/// <summary>Scorta di ricambi desiderata: mesi di consumo della politica più quanto ordinato dal proprietario.</summary>
public static int PartsTarget(Industry ind, IndustryMaintenanceBalance m) =>
ind.Closed ? 0 : (int)Math.Ceiling(MonthlyPartsUse(ind, m) * m.PartsTargetMonths) + ind.PartsOrdered;
/// <summary>Macchinari richiesti dal lavoro programmato (revisione o ammodernamento).</summary>
public static int MachineryRequired(Industry ind, IndustryMaintenanceBalance m) => ind.PendingWork switch
{
IndustryWork.Overhaul => m.OverhaulMachineryPerLevel * Math.Max(1, ind.Level),
IndustryWork.Upgrade => m.UpgradeMachineryPerLevel * Math.Max(1, ind.Level),
_ => 0,
};
/// <summary>
/// Bisogno di ricambi o macchinari per la manutenzione degli impianti (domanda esplicita: scorta
/// desiderata − scorta); 0 per gli altri beni e per le industrie chiuse.
/// </summary>
public static int ServiceNeed(World w, Industry ind, int good)
{
if (ind.Closed) return 0;
var m = w.Data.Balance.IndustryMaintenance;
if (good == w.Data.SparePartsGood) return Math.Max(0, PartsTarget(ind, m) - ind.SpareParts);
if (good == w.Data.MachineryGood) return Math.Max(0, MachineryRequired(ind, m) - ind.Machinery);
return 0;
}
/// <summary>Riceve ricambi o macchinari pagandoli al prezzo indicato; restituisce le unità prese.</summary>
public static int ReceiveService(World w, Industry ind, int good, int units, double unitPrice)
{
int take = Math.Min(units, ServiceNeed(w, ind, good));
if (take <= 0) return 0;
if (good == w.Data.SparePartsGood) ind.SpareParts += take;
else ind.Machinery += take;
var cost = Common.Money.FromCentsRounded(take * unitPrice);
w.Money.Transfer(Account.Of(ind.Id), Account.External, cost, LedgerEntry.Other);
ind.PurchasesToday += cost.Cents;
ind.MaintenanceSpentYear += cost.Cents;
ind.LastServedDay = w.Clock.Day;
return take;
}
/// <summary>Utile annuo stimato dell'industria (ricavi − costi medi giornalieri × giorni dell'anno).</summary>
public static double AnnualProfit(World w, Industry ind) => (ind.RevenueEma - ind.CostEma) * w.Calendar.DaysPerYear;
/// <summary>
/// Prezzo di vendita di un'industria: quota del costo cumulato degli impianti (pesato dalla
/// condizione) + multiplo dell'utile annuo positivo + cassa dell'impresa.
/// </summary>
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));
}
}
@@ -42,6 +42,9 @@ public sealed class IndustrySystem : ISimSystem
double pf = IndustryMath.ProfitFactor(ind, ib);
double mc = IndustryMath.ConditionMultiplier(ind.Condition, data.Balance.IndustryMaintenance);
double eLabor = Math.Min(ind.CovWorkers, ind.CovStaff) * pf * mc;
// fermo per guasto, incidente, revisione o ammodernamento: nessuna produzione (sezione 11)
bool stopped = ind.IsStopped(ctx.Day);
if (stopped) eLabor = 0;
// giacimento: sotto la soglia la capacità cala linearmente, a zero l'industria chiude
double depletion = 1.0;
@@ -58,7 +61,7 @@ public sealed class IndustrySystem : ISimSystem
}
double cycles = ind.CyclesPerDayAtFullCapacity(dpm) * eLabor * depletion;
for (int o = 0; o < recipe.Outputs.Count; o++)
for (int o = 0; o < recipe.Outputs.Count && !stopped; o++)
w.Market.CapacityToday[recipe.Outputs[o].GoodIndex] += ind.CyclesPerDayAtFullCapacity(dpm) * depletion * recipe.Outputs[o].PerCycle;
// copertura degli input di oggi: limita la produzione alle scorte disponibili
@@ -53,8 +53,17 @@ public sealed class LocalTransportSystem : ISimSystem
{
if (available <= 0) break;
var consumer = w.Industries[ci];
if (consumer.Closed) continue;
int serviced = IndustryMath.ReceiveService(w, consumer, good, available, w.Market.GlobalPrice[good]);
if (serviced > 0)
{
producer.OutputStock[o] -= serviced;
available -= serviced;
Sell(w, producer, o, serviced, sellPrice);
if (available <= 0) break;
}
int i = consumer.InputIndexOf(good);
if (i < 0 || consumer.Closed) continue;
if (i < 0) continue;
int free = IndustryMath.InputCapacity(consumer, i, dpm) - consumer.InputStock[i];
int units = Math.Min(available, free);
if (units <= 0) continue;
@@ -102,6 +111,8 @@ public sealed class LocalTransportSystem : ISimSystem
{
if (consumer.Closed || hub.RemainingCapacity <= 0) continue;
if (Vec2.Distance(hub.Position, consumer.Position) > lt.RadiusKm * 1000) continue;
ImportService(w, hub, consumer, w.Data.SparePartsGood, lt);
ImportService(w, hub, consumer, w.Data.MachineryGood, lt);
var inputs = consumer.Def.Recipe.Inputs;
for (int i = 0; i < inputs.Count; i++)
{
@@ -119,6 +130,17 @@ public sealed class LocalTransportSystem : ISimSystem
}
}
/// <summary>Un hub vicino vende ricambi o macchinari a un'industria che ne ha bisogno (sezione 11).</summary>
private static void ImportService(World w, Hub hub, Industry consumer, int good, LocalTransportBalance lt)
{
int units = Math.Min(Math.Min(lt.MaxUnitsPerDay, IndustryMath.ServiceNeed(w, consumer, good)), hub.RemainingCapacity);
if (units <= 0) return;
units = IndustryMath.ReceiveService(w, consumer, good, units, hub.SellPrice(w.Market.GlobalPrice[good]));
hub.UsedThisMonth += units;
hub.ImportedThisMonth[good] += units;
w.Goods.Imported[good] += units;
}
private static void Sell(World w, Industry producer, int outputIndex, int units, double unitPrice)
{
var amount = Money.FromCentsRounded(units * unitPrice);
@@ -37,10 +37,47 @@ public sealed class StationSystem : ISimSystem
foreach (var s in net.Stations)
{
if (net.Nodes[s.Node.Value].Station != s.Id || !LoadsHere(w, s)) continue;
LocalService(w, s, w.Data.SparePartsGood);
LocalService(w, s, w.Data.MachineryGood);
CollectFreight(ctx, s);
}
}
/// <summary>
/// Trasbordo nel bacino (ADR 0011): una stazione servita passa ricambi e macchinari dai produttori
/// e dagli hub del suo bacino alle officine e alle industrie dello stesso bacino, senza treno.
/// </summary>
private static void LocalService(World w, Station s, int good)
{
if (ServiceNeed(w, s, good) <= 0) return;
foreach (var id in s.Industries)
{
var producer = w.Industries[id.Value];
int o = producer.OutputIndexOf(good);
if (producer.Closed || o < 0 || producer.OutputStock[o] <= 0) continue;
int offered = producer.OutputStock[o];
int sold = offered - StationWork.DeliverService(w, s, good, offered, w.Market.GlobalPrice[good]);
if (sold <= 0) continue;
producer.OutputStock[o] -= sold;
var sale = Money.FromCentsRounded(sold * w.Market.GlobalPrice[good]);
w.Money.Transfer(Account.External, Account.Of(producer.Id), sale, LedgerEntry.Other);
producer.SalesToday += sale.Cents;
producer.LastServedDay = w.Clock.Day;
if (o == 0) producer.ShippedToday += sold;
}
foreach (var id in s.Hubs)
{
var hub = w.Hubs[id.Value];
int units = Math.Min(ServiceNeed(w, s, good), hub.RemainingCapacity);
if (units <= 0) continue;
int delivered = units - StationWork.DeliverService(w, s, good, units, hub.SellPrice(w.Market.GlobalPrice[good]));
if (delivered <= 0) continue;
hub.UsedThisMonth += delivered;
hub.ImportedThisMonth[good] += delivered;
w.Goods.Imported[good] += delivered;
}
}
private static bool LoadsHere(World w, Station s)
{
foreach (var line in w.Lines)
@@ -131,17 +168,21 @@ public sealed class StationSystem : ISimSystem
if (o == 0) ind.ShippedToday += units;
}
}
if (s.Hubs.Count > 0) ImportSpareParts(ctx, s, graph);
if (s.Hubs.Count > 0)
{
ImportServiceGood(ctx, s, graph, w.Data.SparePartsGood);
ImportServiceGood(ctx, s, graph, w.Data.MachineryGood);
}
}
/// <summary>
/// Un hub nel bacino importa i ricambi richiesti dalle officine raggiungibili sulle linee (10.2):
/// li spedisce verso la stazione con più bisogno, entro la capacità mensile dell'hub.
/// Un hub nel bacino importa ricambi e macchinari richiesti dalle officine e dalle industrie
/// raggiungibili sulle linee (10.2, 11): li spedisce verso la stazione con più bisogno, entro la
/// capacità mensile dell'hub.
/// </summary>
private void ImportSpareParts(WorldContext ctx, Station s, LineGraph graph)
private void ImportServiceGood(WorldContext ctx, Station s, LineGraph graph, int good)
{
var w = ctx.World;
int good = w.Data.SparePartsGood;
var reach = graph.From(s.Id, LineGraph.GoodCargo(good));
if (reach.Count == 0) return;
_candidates.Clear();
@@ -152,7 +193,7 @@ public sealed class StationSystem : ISimSystem
foreach (var (sid, _) in _candidates)
{
var dest = w.Network.Stations[sid];
int need = DepotNeed(w, dest) - dest.Incoming[good];
int need = ServiceNeed(w, dest, good) - dest.Incoming[good];
if (need <= bestNeed) continue;
bestNeed = need;
best = reach[sid];
@@ -187,6 +228,14 @@ public sealed class StationSystem : ISimSystem
}
}
/// <summary>Ricambi o macchinari mancanti a officine e industrie nel bacino della stazione.</summary>
private static int ServiceNeed(World w, Station s, int good)
{
int need = good == w.Data.SparePartsGood ? DepotNeed(w, s) : 0;
foreach (var id in s.Industries) need += IndustryMath.ServiceNeed(w, w.Industries[id.Value], good);
return need;
}
/// <summary>Ricambi mancanti alle officine nel bacino della stazione (scorta desiderata − scorta).</summary>
private static int DepotNeed(World w, Station s)
{
@@ -217,8 +266,15 @@ public sealed class StationSystem : ISimSystem
foreach (var id in dest.Industries)
{
var ind = w.Industries[id.Value];
if (ind.Closed) continue;
int service = IndustryMath.ServiceNeed(w, ind, good);
if (service > 0)
{
consumer = true;
need += service;
}
int i = ind.InputIndexOf(good);
if (i < 0 || ind.Closed) continue;
if (i < 0) continue;
consumer = true;
need += IndustryMath.InputCapacity(ind, i, dpm) - ind.InputStock[i];
}
@@ -206,6 +206,9 @@ public static class StationWork
if (units <= 0) return 0;
var ind = w.Industries[id.Value];
if (ind.Closed) continue;
// ricambi e macchinari per gli impianti (sezione 11)
units -= IndustryMath.ReceiveService(w, ind, good, units, w.Market.GlobalPrice[good]);
if (units <= 0) return 0;
int i = ind.InputIndexOf(good);
if (i < 0) continue;
int free = IndustryMath.InputCapacity(ind, i, dpm) - ind.InputStock[i];
@@ -261,6 +264,34 @@ public static class StationWork
return units;
}
/// <summary>
/// Consegna ricambi o macchinari solo alle officine e alle industrie del bacino che ne hanno
/// bisogno (manutenzione); le industrie pagano <paramref name="industryPrice"/>, le officine il
/// prezzo globale. Restituisce le unità rimaste.
/// </summary>
public static int DeliverService(World w, Station s, int good, int units, double industryPrice)
{
foreach (var id in s.Industries)
{
if (units <= 0) return 0;
units -= IndustryMath.ReceiveService(w, w.Industries[id.Value], good, units, industryPrice);
}
if (good != w.Data.SparePartsGood) return units;
foreach (var id in s.Depots)
{
if (units <= 0) return 0;
var depot = w.Network.Depots[id.Value];
if (!w.Network.IsAlive(depot)) continue;
int take = Math.Min(units, Math.Max(0, depot.PartsTarget - depot.SpareParts));
if (take <= 0) continue;
depot.SpareParts += take;
units -= take;
var cost = Money.FromCentsRounded(take * w.Market.GlobalPrice[good]);
w.Money.Transfer(Account.Of(depot.Owner), Account.External, cost, LedgerEntry.FleetMaintenance);
}
return units;
}
// ------------------------------------------------------------------ carico
/// <summary>Carica i pacchetti in attesa che viaggiano sulla linea del treno; restituisce le unità caricate.</summary>
@@ -0,0 +1,424 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
namespace ViaFerrea.Core.Simulation.Systems;
/// <summary>
/// Borsa e vita societaria (12.1–12.3), una volta al giorno: prezzi e sentiment, valore delle
/// partecipazioni, offerte pubbliche (adesioni, esito), controllo e utili delle controllate,
/// amministrazione controllata del giocatore, fallimenti con asta degli attivi, storico annuale
/// e nuovi concorrenti quando il mercato è troppo concentrato (ADR 0012).
/// </summary>
public sealed class StockMarketSystem : ISimSystem
{
public string Name => "StockMarket";
public void Step(WorldContext ctx)
{
if (!ctx.IsNewDay) return;
var w = ctx.World;
UpdatePrices(w, ctx);
UpdatePortfolios(w);
ProcessBids(ctx);
UpdateControl(ctx);
HandleBankruptcies(ctx);
ProcessAuctions(ctx);
Receivership(ctx);
if (ctx.IsNewMonth && ctx.Day > 0)
{
foreach (var c in w.Companies)
{
if (c.Defunct) continue;
c.PriceHistory.Add(c.SharePrice);
while (c.PriceHistory.Count > w.Data.Balance.StockMarket.PriceHistoryMonths) c.PriceHistory.RemoveAt(0);
PaySubsidiaryProfit(w, c);
}
}
if (ctx.IsNewYear && ctx.Day > 0)
{
foreach (var c in w.Companies)
{
if (c.Merged) continue;
RecordPreviousYear(w, c);
c.LastAnnualProfit = c.AnnualProfit;
}
NewCompetitors(ctx);
}
w.Bids.RemoveAll(b => b.State != BidState.Open && ctx.Day - b.ClosedDay > w.Data.Balance.StockMarket.BidDurationDays);
}
// ------------------------------------------------------------------ prezzi
private static void UpdatePrices(World w, WorldContext ctx)
{
var sm = w.Data.Balance.StockMarket;
var mb = w.Data.Balance.Market;
double years = (double)ctx.Day / w.Calendar.DaysPerYear;
double cycle = mb.World.Amplitude * w.Difficulty.MarketVolatilityMultiplier * DMath.Sin(DMath.TwoPi * years / mb.World.PeriodYears);
foreach (var c in w.Companies)
{
if (c.Defunct) continue;
double fundamental = Corporate.FundamentalPrice(w, c);
long annual = c.AnnualProfit;
double baseline = Math.Max(Math.Max(Math.Abs(c.LastAnnualProfit), c.NetWorth.Cents * 0.05), 1);
double growth = Math.Clamp((annual - c.LastAnnualProfit) / baseline, -1, 1);
long dividends = 0;
foreach (long d in c.DividendRing) dividends += d;
double cap = Math.Max(1, fundamental * c.Shares.Outstanding);
double yield = Math.Clamp(dividends / cap, 0, 0.5);
double target = 1 + sm.SentimentEarningsWeight * growth + sm.SentimentCycleWeight * cycle + sm.SentimentDividendWeight * yield + c.ExtraSentiment;
target = Math.Clamp(target, sm.SentimentMin, sm.SentimentMax);
c.Sentiment = Ema.Step(c.Sentiment, target, sm.SentimentSmoothingDays);
c.ExtraSentiment = Math.Max(0, c.ExtraSentiment - sm.ExtraDividendSentimentBoost / sm.ExtraDividendDecayDays);
c.SharePrice = Math.Max(Corporate.MinPrice, fundamental * c.Sentiment);
}
}
private static void UpdatePortfolios(World w)
{
foreach (var holder in w.Companies)
{
double value = 0;
foreach (var c in w.Companies)
{
if (c.Id == holder.Id || c.Defunct) continue;
long held = c.Shares.Of(holder.Id);
if (held > 0) value += held * c.SharePrice;
}
holder.PortfolioValue = Money.FromCentsRounded(value);
}
}
// ------------------------------------------------------------------ offerte pubbliche
private static void ProcessBids(WorldContext ctx)
{
var w = ctx.World;
var sm = w.Data.Balance.StockMarket;
foreach (var bid in w.Bids)
{
if (bid.State != BidState.Open) continue;
var target = w.Company(bid.Target);
var bidder = w.Company(bid.Bidder);
if (target.Defunct || bidder.Defunct)
{
Close(w, bid, BidState.Failed);
continue;
}
// il flottante aderisce in proporzione al premio sul prezzo di mercato
double premium = bid.PricePerShare / Math.Max(Corporate.MinPrice, target.SharePrice) - 1;
double rate = premium <= 0 ? 0 : sm.TenderDailyShare * Math.Clamp(premium / sm.BidPremiumMin, 0, 2);
long free = Corporate.FreeFloat(w, target);
long tender = (long)Math.Ceiling(free * rate);
bid.TenderedPublic += Math.Min(free, tender);
// il proprietario privato di un'IA vende tutto solo a un premio molto alto
if (!target.IsPlayer && bid.TenderedFounder == 0 && premium >= w.Data.Ai.Market.FounderAcceptPremium)
bid.TenderedFounder = target.Shares.Founder;
if (Committed(w, bid) >= Needed(bid, target)) Settle(ctx, bid);
else if (ctx.Day >= bid.EndDay)
{
Close(w, bid, BidState.Failed);
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Info,
$"Offerta di {bidder.Name} su {target.Name} scaduta: adesioni insufficienti", EntityKind.Company, target.Id.Value, bidder.Id));
}
}
}
/// <summary>Azioni che l'offerente avrebbe a esito positivo: già sue + adesioni.</summary>
public static long Committed(World w, TakeoverBid bid)
{
var target = w.Company(bid.Target);
long sum = target.Shares.Of(bid.Bidder) + bid.TenderedPublic + bid.TenderedFounder;
foreach (var holder in bid.Accepted) sum += target.Shares.Of(holder);
return sum;
}
/// <summary>Azioni da raggiungere: la quota obiettivo delle azioni in circolazione.</summary>
public static long Needed(TakeoverBid bid, Company target) =>
(long)Math.Ceiling(bid.TargetShare * target.Shares.Outstanding);
private static void Settle(WorldContext ctx, TakeoverBid bid)
{
var w = ctx.World;
var target = w.Company(bid.Target);
var bidder = w.Company(bid.Bidder);
long bought = bid.TenderedPublic + bid.TenderedFounder;
foreach (var holder in bid.Accepted) bought += target.Shares.Of(holder);
var cost = Money.FromCentsRounded((double)bought * bid.PricePerShare);
if (bidder.Cash < cost)
{
Close(w, bid, BidState.Failed);
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Warning,
$"Offerta di {bidder.Name} su {target.Name} fallita: cassa insufficiente al pagamento", EntityKind.Company, target.Id.Value, bidder.Id));
return;
}
var price = (double)bid.PricePerShare;
long fromMarket = bid.TenderedPublic + bid.TenderedFounder;
w.Money.Transfer(Account.Of(bidder.Id), Account.External, Money.FromCentsRounded(fromMarket * price), LedgerEntry.Shares);
target.Shares.Public -= bid.TenderedPublic;
target.Shares.Founder -= bid.TenderedFounder;
target.Shares.Add(bidder.Id, fromMarket);
foreach (var holder in bid.Accepted)
{
long held = target.Shares.Of(holder);
if (held <= 0) continue;
w.Money.Transfer(Account.Of(bidder.Id), Account.Of(holder), Money.FromCentsRounded(held * price), LedgerEntry.Shares);
target.Shares.ByCompany[holder.Value] = 0;
target.Shares.Add(bidder.Id, held);
}
Close(w, bid, BidState.Succeeded);
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Critical,
$"{bidder.Name} conclude l'offerta su {target.Name}: ora possiede il {target.Shares.FractionOf(bidder.Id) * 100:0.0} %",
EntityKind.Company, target.Id.Value, bidder.Id));
}
private static void Close(World w, TakeoverBid bid, BidState state)
{
bid.State = state;
bid.ClosedDay = w.Clock.Day;
}
// ------------------------------------------------------------------ controllo
private static void UpdateControl(WorldContext ctx)
{
var w = ctx.World;
foreach (var c in w.Companies)
{
if (c.Defunct) continue;
var controller = Corporate.Controller(w, c);
if (controller == c.ControlledBy) continue;
c.ControlledBy = controller;
c.ControlSinceDay = controller.IsValid ? ctx.Day : -1;
if (!controller.IsValid) continue;
var parent = w.Company(controller);
Corporate.Milestone(w, parent, $"prende il controllo di {c.Name}");
Corporate.Milestone(w, c, $"passa sotto il controllo di {parent.Name}");
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Critical,
$"{parent.Name} prende il controllo di {c.Name}", EntityKind.Company, c.Id.Value, parent.Id));
if (c.IsPlayer) Corporate.PlayerTakenOver(ctx, parent);
}
}
/// <summary>La controllata versa al controllante la sua quota dell'utile operativo del mese chiuso.</summary>
private static void PaySubsidiaryProfit(World w, Company c)
{
if (!c.ControlledBy.IsValid || c.Bankrupt) return;
int last = (c.ProfitRingIndex + 11) % 12;
long profit = c.ProfitRing[last];
if (profit <= 0) return;
var amount = Money.FromCentsRounded(profit * c.Shares.FractionOf(c.ControlledBy));
amount = Money.Min(amount, Money.Max(Money.Zero, c.Cash));
if (amount.Cents <= 0) return;
// per la controllata è una distribuzione (dividendo), per il controllante un ricavo del gruppo
w.Money.Transfer(Account.Of(c.Id), Account.External, amount, LedgerEntry.Dividends);
w.Money.Transfer(Account.External, Account.Of(c.ControlledBy), amount, LedgerEntry.Subsidiaries);
}
// ------------------------------------------------------------------ amministrazione controllata (12.3)
private static void Receivership(WorldContext ctx)
{
var w = ctx.World;
var player = w.Player;
if (!player.Receivership || w.GameOver is not null) return;
var sm = w.Data.Balance.StockMarket;
if (player.Shares.FounderFraction >= sm.RansomShare)
{
player.Receivership = false;
player.ReceivershipBy = CompanyId.None;
player.ReceivershipUntilDay = -1;
Corporate.Milestone(w, player, "esce dall'amministrazione controllata");
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Opportunity,
$"{player.Name} esce dall'amministrazione controllata: il fondatore ha di nuovo il {player.Shares.FounderFraction * 100:0} %",
EntityKind.Company, player.Id.Value, player.Id));
return;
}
if (ctx.Day >= player.ReceivershipUntilDay)
{
var by = player.ReceivershipBy.IsValid ? w.Company(player.ReceivershipBy) : null;
Corporate.EndGame(ctx, GameOverReason.ReceivershipExpired,
$"scaduti i termini per il riscatto: {player.Name} passa definitivamente a {by?.Name ?? "un concorrente"}", player.ReceivershipBy);
return;
}
// dividendo obbligatorio: a ogni trimestre la quota dell'utile del trimestre va agli azionisti
if (ctx.IsNewQuarter && ctx.Day > 0)
{
long quarter = 0;
for (int k = 1; k <= 3; k++) quarter += player.ProfitRing[(player.ProfitRingIndex + 12 - k) % 12];
if (quarter <= 0) return;
var total = Money.FromCentsRounded(quarter * sm.ReceivershipDividend);
total = Money.Min(total, Money.Max(Money.Zero, player.Cash));
if (total.Cents > 0) Dividends.Distribute(w, player, total);
}
}
// ------------------------------------------------------------------ fallimenti e aste
private static void HandleBankruptcies(WorldContext ctx)
{
var w = ctx.World;
var sm = w.Data.Balance.StockMarket;
foreach (var c in w.Companies)
{
if (!c.Bankrupt || c.Merged || c.BankruptDay >= 0) continue;
c.BankruptDay = ctx.Day;
Corporate.CloseBidsOn(w, c.Id);
if (c.IsPlayer)
{
PlayerInsolvency(ctx, c);
continue;
}
FinanceSystem.UpdateBookValues(w);
long min = (long)(c.AssetBookValue.Cents * sm.AuctionMinBookShare);
w.Auctions.Add(new Auction { Seller = c.Id, StartDay = ctx.Day, EndDay = ctx.Day + sm.AuctionDays, MinPriceCents = Math.Max(1, min) });
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Opportunity,
$"Asta degli attivi di {c.Name}: base d'asta {new Money(Math.Max(1, min))}, chiusura tra {sm.AuctionDays} giorni",
EntityKind.Company, c.Id.Value, c.Id));
}
}
/// <summary>
/// Insolvenza del giocatore (12.3): i creditori vendono la compagnia al miglior offerente tra le IA
/// (che ne salda i debiti e ne prende il controllo); senza compratori o con «Apprendista» la partita finisce.
/// </summary>
private static void PlayerInsolvency(WorldContext ctx, Company player)
{
var w = ctx.World;
if (w.Difficulty.PlayerTakeover == TakeoverRule.Disabled || w.GameOver is not null)
{
Corporate.EndGame(ctx, GameOverReason.Bankruptcy, $"{player.Name} fallisce dopo {player.NegativeCashDays} giorni di cassa negativa", CompanyId.None);
return;
}
long price = Math.Max(0, player.Debt.Cents - player.Cash.Cents);
Company? buyer = null;
foreach (var c in w.Companies)
{
if (c.IsPlayer || c.Defunct || c.Cash.Cents < price) continue;
if (buyer is null || c.Cash > buyer.Cash) buyer = c;
}
if (buyer is null)
{
Corporate.EndGame(ctx, GameOverReason.Bankruptcy, $"{player.Name} fallisce: nessun concorrente rileva i debiti", CompanyId.None);
return;
}
// il compratore salda i debiti, riporta la cassa a zero e riceve tutte le azioni
foreach (var loan in player.Loans)
{
w.Money.Transfer(Account.Of(buyer.Id), Account.External, loan.Remaining, LedgerEntry.Shares);
}
player.Loans.Clear();
if (player.Cash.IsNegative) w.Money.Transfer(Account.Of(buyer.Id), Account.Of(player.Id), -player.Cash, LedgerEntry.Shares);
var shares = player.Shares;
shares.Founder = 0;
shares.Public = 0;
shares.Treasury = 0;
Array.Clear(shares.ByCompany);
shares.Add(buyer.Id, shares.Total);
player.Bankrupt = false;
player.BankruptDay = -1;
player.NegativeCashDays = 0;
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Critical,
$"I creditori vendono {player.Name} a {buyer.Name}, che ne salda i debiti", EntityKind.Company, player.Id.Value, buyer.Id));
player.ControlledBy = buyer.Id;
player.ControlSinceDay = ctx.Day;
Corporate.PlayerTakenOver(ctx, buyer);
}
private static void ProcessAuctions(WorldContext ctx)
{
var w = ctx.World;
foreach (var a in w.Auctions)
{
if (a.Closed || ctx.Day < a.EndDay) continue;
a.Closed = true;
var seller = w.Company(a.Seller);
if (a.BestBidder.IsValid && !w.Company(a.BestBidder).Defunct && w.Company(a.BestBidder).Cash.Cents >= a.BestPriceCents)
{
var buyer = w.Company(a.BestBidder);
// il prezzo va ai creditori: i debiti del fallito si estinguono, gli attivi passano al compratore
w.Money.Transfer(Account.Of(buyer.Id), Account.External, new Money(a.BestPriceCents), LedgerEntry.IndustryPurchase);
seller.Loans.Clear();
if (seller.Cash.IsNegative) w.Money.Transfer(Account.External, Account.Of(seller.Id), -seller.Cash, LedgerEntry.Other);
Corporate.TransferAssets(w, seller, buyer);
seller.Merged = true;
seller.MergedInto = buyer.Id;
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Info,
$"{buyer.Name} si aggiudica all'asta gli attivi di {seller.Name} per {new Money(a.BestPriceCents)}", EntityKind.Company, seller.Id.Value, buyer.Id));
}
else
{
Corporate.Liquidate(ctx, seller);
}
}
w.Auctions.RemoveAll(a => a.Closed && ctx.Day - a.EndDay > w.Data.Balance.StockMarket.AuctionDays);
}
// ------------------------------------------------------------------ storico e concorrenza
private static void RecordPreviousYear(World w, Company c) =>
Corporate.AddYear(w, c, Corporate.Snapshot(w, c, w.Clock.Year - 1, c.LastYearEntries));
/// <summary>
/// Nuovi concorrenti (12.1): se una compagnia supera la soglia di concentrazione dei ricavi
/// dell'anno, entra una nuova IA (al massimo una ogni pochi anni e fino al numero massimo).
/// </summary>
private static void NewCompetitors(WorldContext ctx)
{
var w = ctx.World;
var sm = w.Data.Balance.StockMarket;
if (ctx.Year - w.LastCompetitorYear < sm.NewCompetitorCooldownYears) return;
int active = 0;
long total = 0, best = 0;
Company? leader = null;
foreach (var c in w.Companies)
{
if (c.Defunct) continue;
active++;
long r = Company.Revenue(c.LastYearEntries);
total += r;
if (r > best)
{
best = r;
leader = c;
}
}
if (leader is null || total <= 0 || active >= sm.MaxCompanies || w.Companies.Count >= sm.MaxCompanies * 2) return;
double share = (double)best / total;
if (share <= sm.ConcentrationThreshold) return;
var entrant = WorldFactory.CreateAiCompany(w, w.Stream("companies"));
w.LastCompetitorYear = ctx.Year;
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Warning,
$"Entra nel mercato {entrant.Name}: {leader.Name} controlla il {share * 100:0} % dei trasporti", EntityKind.Company, entrant.Id.Value, entrant.Id));
}
}
/// <summary>Distribuzione dei dividendi agli azionisti (12.2).</summary>
public static class Dividends
{
/// <summary>
/// Paga <paramref name="total"/> agli azionisti in proporzione alle azioni in circolazione:
/// fondatore e flottante ricevono dal conto Esterno, le compagnie azioniste in cassa.
/// </summary>
public static void Distribute(World w, Company payer, Money total)
{
var shares = payer.Shares;
long outstanding = shares.Outstanding;
if (outstanding <= 0 || total.Cents <= 0) return;
double perShare = (double)total.Cents / outstanding;
long paid = 0;
for (int i = 0; i < shares.ByCompany.Length; i++)
{
long held = shares.ByCompany[i];
if (held <= 0 || i == payer.Id.Value) continue;
var amount = Money.FromCentsRounded(held * perShare);
w.Money.Transfer(Account.Of(payer.Id), Account.Of(new CompanyId(i)), amount, LedgerEntry.Dividends);
paid += amount.Cents;
}
var rest = new Money(total.Cents - paid);
if (rest.Cents > 0) w.Money.Transfer(Account.Of(payer.Id), Account.External, rest, LedgerEntry.Dividends);
payer.DividendRing[payer.ProfitRingIndex] += total.Cents;
}
}
@@ -0,0 +1,77 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
namespace ViaFerrea.Core.Simulation.Systems;
/// <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).
/// </summary>
public static class Tiers
{
/// <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;
/// <summary>Promuove la compagnia se soddisfa i requisiti del livello successivo.</summary>
public static void Evaluate(WorldContext ctx, Company c)
{
var w = ctx.World;
var tiers = w.Data.Tiers.Tiers;
while (c.Tier < tiers.Count && Meets(w, c, tiers[c.Tier].Requirements))
{
var next = tiers[c.Tier];
c.Tier = next.Level;
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));
}
}
/// <summary>Requisiti di un livello soddisfatti dalla compagnia.</summary>
public static bool Meets(World w, Company c, TierRequirements req) =>
c.NetWorth.Cents >= req.NetWorth
&& c.Rating <= req.CreditRating
&& ConnectedTowns(w, c.Id, req.ConnectedTownsOver.Population) >= req.ConnectedTownsOver.Count;
/// <summary>
/// Città con almeno <paramref name="minPopulation"/> abitanti collegate dalla compagnia: nel bacino
/// di una sua stazione fermata di una linea con almeno un treno.
/// </summary>
public static int ConnectedTowns(World w, CompanyId company, int minPopulation)
{
var served = ServedStations(w, company);
var towns = new bool[w.Towns.Count];
int count = 0;
foreach (var s in w.Network.Stations)
{
if (s.Owner != company || !served[s.Id.Value] || !w.Network.IsAlive(s)) continue;
foreach (var t in s.Towns)
{
if (towns[t.Value] || w.Towns[t.Value].Population < minPopulation) continue;
towns[t.Value] = true;
count++;
}
}
return count;
}
/// <summary>Stazioni della compagnia fermate di una linea con almeno un treno assegnato.</summary>
public static bool[] ServedStations(World w, CompanyId company)
{
var lineHasTrain = new bool[w.Lines.Count];
foreach (var t in w.Trains)
{
if (t.Owner == company && t.Line.IsValid && !t.Removed) lineHasTrain[t.Line.Value] = true;
}
var served = new bool[w.Network.Stations.Count];
foreach (var l in w.Lines)
{
if (l.Owner != company || l.Removed || !lineHasTrain[l.Id.Value]) continue;
foreach (var stop in l.Stops) served[stop.Station.Value] = true;
}
return served;
}
}
+20
View File
@@ -60,6 +60,24 @@ public sealed class World
/// <summary>Convenzioni di pendolarismo (proposte, attive e concluse di recente).</summary>
public List<CommuteAgreement> Agreements { get; } = [];
/// <summary>Offerte pubbliche di acquisto (in corso e concluse di recente).</summary>
public List<TakeoverBid> Bids { get; } = [];
/// <summary>Aste degli attivi delle compagnie fallite.</summary>
public List<Auction> Auctions { get; } = [];
/// <summary>Fine della partita del giocatore (null finché gioca): poi si osserva il mondo.</summary>
public GameOverState? GameOver { get; set; }
/// <summary>Stato degli agenti delle compagnie IA, in ordine di compagnia.</summary>
public List<Ai.AiState> AiStates { get; } = [];
/// <summary>Agenti IA sospesi (le compagnie IA esistono ma non agiscono): test e scenari didattici.</summary>
public bool AiPaused { get; set; }
/// <summary>Ultimo anno in cui è entrato un nuovo concorrente (12.1).</summary>
public int LastCompetitorYear { get; set; } = int.MinValue;
/// <summary>Rete ferroviaria di tutte le compagnie.</summary>
public RailNetwork Network { get; } = new();
public List<Vehicle> Vehicles { get; } = [];
@@ -181,6 +199,8 @@ public sealed class World
}
foreach (var ind in Industries)
{
if (good == Data.SparePartsGood) sum += ind.SpareParts;
if (good == Data.MachineryGood) sum += ind.Machinery;
int i = ind.InputIndexOf(good);
if (i >= 0) sum += ind.InputStock[i];
int o = ind.OutputIndexOf(good);
+31 -18
View File
@@ -116,25 +116,38 @@ public static class WorldFactory
};
w.Companies.Add(player);
w.Money.Transfer(Account.External, Account.Of(player.Id), new Money(d.InitialCapital), LedgerEntry.Other);
Corporate.InitShares(w, player, d.PublicFromStart, d.PublicFromStart ? d.PlayerShareAtStart : 1.0);
var names = data.Ai.CompanyNames.ToList();
for (int i = 0; i < d.AiCompetitors; i++)
for (int i = 0; i < d.AiCompetitors; i++) CreateAiCompany(w, rng);
}
/// <summary>
/// Crea una compagnia IA con nome e personalità estratti dal flusso indicato, capitale e fido
/// della difficoltà (× capitale IA) e flottante iniziale in borsa (12.1–12.2).
/// </summary>
public static Company CreateAiCompany(World w, Rng rng)
{
var data = w.Data;
var d = w.Difficulty;
var used = new HashSet<string>(w.Companies.Select(c => c.Name), StringComparer.Ordinal);
var names = data.Ai.CompanyNames.Where(n => !used.Contains(n)).ToList();
int aiIndex = w.Companies.Count(c => !c.IsPlayer);
string name = names.Count > 0 ? names[rng.NextInt(names.Count)] : $"Compagnia {aiIndex + 1}";
var personality = data.Ai.Personalities[rng.NextInt(data.Ai.Personalities.Count)];
var ai = new Company
{
string name = names.Count > 0 ? names[rng.NextInt(names.Count)] : $"Compagnia {i + 1}";
names.Remove(name);
var personality = data.Ai.Personalities[rng.NextInt(data.Ai.Personalities.Count)];
var ai = new Company
{
Id = new CompanyId(w.Companies.Count),
Name = name,
IsPlayer = false,
AiPersonality = personality.Id,
Color = data.Ai.Colors[i % data.Ai.Colors.Count],
BaseCredit = new Money(d.InitialCredit) * d.AiCapitalMultiplier,
Rating = data.Balance.Finance.StartingRating,
};
w.Companies.Add(ai);
w.Money.Transfer(Account.External, Account.Of(ai.Id), new Money(d.InitialCapital) * d.AiCapitalMultiplier, LedgerEntry.Other);
}
Id = new CompanyId(w.Companies.Count),
Name = name,
IsPlayer = false,
AiPersonality = personality.Id,
Color = data.Ai.Colors[aiIndex % data.Ai.Colors.Count],
BaseCredit = new Money(d.InitialCredit) * d.AiCapitalMultiplier,
Rating = data.Balance.Finance.StartingRating,
FoundedDay = w.Clock.Day,
};
w.Companies.Add(ai);
w.Money.Transfer(Account.External, Account.Of(ai.Id), new Money(d.InitialCapital) * d.AiCapitalMultiplier, LedgerEntry.Other);
Corporate.InitShares(w, ai, listed: true, 1 - data.Balance.StockMarket.AiFloatAtStart);
return ai;
}
}
@@ -41,6 +41,15 @@ public sealed class ClientWorld(GameData data)
public Dictionary<int, WorkshopRegister> Workshops { get; } = [];
public EmploymentReport? Employment { get; private set; }
/// <summary>Dati della F5: listino di borsa, schede di compagnie e industrie, Cronaca finale.</summary>
public MarketTape? Tape { get; private set; }
public Dictionary<int, CompanyCard> CompanyCards { get; } = [];
public Dictionary<int, IndustryCard> IndustryCards { get; } = [];
public Chronicle? Chronicle { get; private set; }
/// <summary>Contatore dei listini ricevuti (per aggiornare il pannello della borsa).</summary>
public int TapeVersion { get; private set; }
/// <summary>Ultimi avvisi di manutenzione, dal più recente.</summary>
public List<MaintenanceAlert> Alerts { get; } = [];
private const int AlertCapacity = 50;
@@ -102,6 +111,22 @@ public sealed class ClientWorld(GameData data)
Employment = m;
DetailVersion++;
return true;
case MarketTape m:
Tape = m;
TapeVersion++;
return true;
case CompanyCard m:
CompanyCards[m.Company] = m;
DetailVersion++;
return true;
case IndustryCard m:
IndustryCards[m.Industry] = m;
DetailVersion++;
return true;
case Chronicle m:
Chronicle = m;
DetailVersion++;
return true;
case MaintenanceAlert m:
Alerts.Insert(0, m);
if (Alerts.Count > AlertCapacity) Alerts.RemoveAt(Alerts.Count - 1);
@@ -117,6 +142,10 @@ public sealed class ClientWorld(GameData data)
Cards.Clear();
Workshops.Clear();
Employment = null;
Tape = null;
CompanyCards.Clear();
IndustryCards.Clear();
Chronicle = null;
Alerts.Clear();
Summary = m.Summary;
SessionId = m.SessionId;
+28 -2
View File
@@ -160,10 +160,26 @@ public static class CommandCodec
w.String(c.Objective);
w.Money(c.Budget);
break;
case MergeCompanyCommand c: w.I32(c.Subsidiary.Value); break;
default:
throw new ProtocolException($"comando senza codifica: {command.Type}");
}
w.Flags(0);
// blocco 1 (F5): industria destinataria dei ricambi, difesa del bersaglio di un'offerta
switch (command)
{
case OrderPartsCommand c when c.Industry.IsValid:
w.Flags(1);
w.I32(c.Industry.Value);
break;
case RespondBidCommand c when c.Defense != BidDefense.None || c.Knight.IsValid:
w.Flags(1);
w.U8((byte)c.Defense);
w.I32(c.Knight.Value);
break;
default:
w.Flags(0);
break;
}
}
public static GameCommand Read(CommandType type, ref SpanReader r)
@@ -208,9 +224,19 @@ public static class CommandCodec
CommandType.AcceptContract => new AcceptContractCommand(new ContractId(r.I32())),
CommandType.FundResearch => new FundResearchCommand(r.String(), r.Money()),
CommandType.DelegateRegion => new DelegateRegionCommand(new RegionId(r.I32()), r.String(), r.Money()),
CommandType.MergeCompany => new MergeCompanyCommand(new CompanyId(r.I32())),
_ => throw new ProtocolException($"tipo di comando sconosciuto: {(ushort)type}"),
};
r.Flags();
byte flags = r.Flags();
if ((flags & 1) != 0)
{
c = c switch
{
OrderPartsCommand op => op with { Industry = new IndustryId(r.I32()) },
RespondBidCommand rb => rb with { Defense = Enum<BidDefense>(r.U8(), 3), Knight = new CompanyId(r.I32()) },
_ => c,
};
}
return c;
}
+6
View File
@@ -31,6 +31,12 @@ public enum MessageId : ushort
MaintenanceCard = 124,
/// <summary>Registro officina di un deposito (F4).</summary>
WorkshopRegister = 125,
/// <summary>Scheda di una compagnia: soci, storico, prezzi (F5).</summary>
CompanyCard = 126,
/// <summary>Scheda del proprietario di un'industria: manutenzione, fermi, valore (F5).</summary>
IndustryCard = 127,
/// <summary>Cronaca finale della partita del giocatore (F5).</summary>
Chronicle = 128,
CommandResult = 130,
Notification = 131,
Newspaper = 132,
@@ -231,6 +231,12 @@ public enum DetailKind : byte
Workshop = 2,
/// <summary>Registro degli impieghi della compagnia (risposta EmploymentReport; Id ignorato).</summary>
Employment = 3,
/// <summary>Scheda di una compagnia (risposta CompanyCard, F5).</summary>
Company = 4,
/// <summary>Scheda del proprietario di un'industria (risposta IndustryCard, F5).</summary>
Industry = 5,
/// <summary>Cronaca finale (risposta Chronicle, F5; Id ignorato).</summary>
Chronicle = 6,
}
/// <summary>Chiede al server un dettaglio che non viaggia con le entità (aggiunto in F4).</summary>
@@ -0,0 +1,266 @@
using ViaFerrea.Core.Common;
namespace ViaFerrea.Protocol.Messages;
// Messaggi della fase F5: scheda di una compagnia (soci e storico), scheda del proprietario di
// un'industria, Cronaca finale. Arrivano solo su richiesta (RequestDetail) o, la Cronaca, alla fine
// della partita del giocatore.
/// <summary>Quota di un titolare nel libro dei soci (Holder = id compagnia, −1 fondatore, −2 mercato).</summary>
public sealed class HoldingInfo
{
public const int Founder = -1;
public const int Market = -2;
public int Holder { get; init; }
public long Shares { get; init; }
public void Write(ref SpanWriter w)
{
w.I32(Holder); w.I64(Shares);
w.Flags(0);
}
public static HoldingInfo Read(ref SpanReader r)
{
var m = new HoldingInfo { Holder = r.I32(), Shares = r.I64() };
r.Flags();
return m;
}
}
/// <summary>Anno di storia di una compagnia (grafici della scheda e della Cronaca).</summary>
public sealed class CompanyYearInfo
{
public int Year { get; init; }
public Money NetWorth { get; init; }
public Money Cash { get; init; }
public Money Revenue { get; init; }
public Money Profit { get; init; }
public byte Tier { get; init; }
public int Trains { get; init; }
public float TrackKm { get; init; }
public Money SharePrice { get; init; }
public void Write(ref SpanWriter w)
{
w.I32(Year); w.Money(NetWorth); w.Money(Cash); w.Money(Revenue); w.Money(Profit); w.U8(Tier); w.I32(Trains); w.F32(TrackKm); w.Money(SharePrice);
w.Flags(0);
}
public static CompanyYearInfo Read(ref SpanReader r)
{
var m = new CompanyYearInfo
{
Year = r.I32(), NetWorth = r.Money(), Cash = r.Money(), Revenue = r.Money(), Profit = r.Money(), Tier = r.U8(), Trains = r.I32(),
TrackKm = r.F32(), SharePrice = r.Money(),
};
r.Flags();
return m;
}
}
/// <summary>Scheda di una compagnia (borsa e controllo, 12.2).</summary>
public sealed class CompanyCard : IMessage
{
public MessageId Id => MessageId.CompanyCard;
public int Company { get; init; }
public long TotalShares { get; init; }
public long Treasury { get; init; }
public List<HoldingInfo> Holdings { get; init; } = [];
/// <summary>Prezzo dell'azione a fine mese (centesimi), il più recente in coda.</summary>
public List<double> PriceHistory { get; init; } = [];
public List<CompanyYearInfo> History { get; init; } = [];
public Money AnnualProfit { get; init; }
public Money DividendsYear { get; init; }
public Money Debt { get; init; }
public Money MarketCap { get; init; }
/// <summary>Giorni di controllo da parte del titolare di maggioranza (−1 se nessuno).</summary>
public long ControlDays { get; init; } = -1;
/// <summary>Asta in corso degli attivi (compagnia fallita): base, miglior offerta, chiusura.</summary>
public Money AuctionMin { get; init; }
public Money AuctionBest { get; init; }
public int AuctionBestBidder { get; init; } = -1;
public long AuctionEndDay { get; init; } = -1;
public void Write(ref SpanWriter w)
{
w.I32(Company); w.I64(TotalShares); w.I64(Treasury);
w.Count(Holdings.Count);
foreach (var h in Holdings) h.Write(ref w);
w.Count(PriceHistory.Count);
foreach (double p in PriceHistory) w.F64(p);
w.Count(History.Count);
foreach (var y in History) y.Write(ref w);
w.Money(AnnualProfit); w.Money(DividendsYear); w.Money(Debt); w.Money(MarketCap); w.I64(ControlDays);
w.Money(AuctionMin); w.Money(AuctionBest); w.I32(AuctionBestBidder); w.I64(AuctionEndDay);
w.Flags(0);
}
public static CompanyCard Read(ref SpanReader r)
{
int company = r.I32();
long total = r.I64(), treasury = r.I64();
var holdings = new List<HoldingInfo>();
for (int n = r.Count(), i = 0; i < n; i++) holdings.Add(HoldingInfo.Read(ref r));
var prices = new List<double>();
for (int n = r.Count(), i = 0; i < n; i++) prices.Add(r.F64());
var history = new List<CompanyYearInfo>();
for (int n = r.Count(), i = 0; i < n; i++) history.Add(CompanyYearInfo.Read(ref r));
var m = new CompanyCard
{
Company = company, TotalShares = total, Treasury = treasury, Holdings = holdings, PriceHistory = prices, History = history,
AnnualProfit = r.Money(), DividendsYear = r.Money(), Debt = r.Money(), MarketCap = r.Money(), ControlDays = r.I64(),
AuctionMin = r.Money(), AuctionBest = r.Money(), AuctionBestBidder = r.I32(), AuctionEndDay = r.I64(),
};
r.Flags();
return m;
}
}
/// <summary>Fermo passato o in corso di un'industria.</summary>
public sealed class IndustryStopInfo
{
public long Day { get; init; }
public int Days { get; init; }
public byte Kind { get; init; }
public void Write(ref SpanWriter w)
{
w.I64(Day); w.I32(Days); w.U8(Kind);
w.Flags(0);
}
public static IndustryStopInfo Read(ref SpanReader r)
{
var m = new IndustryStopInfo { Day = r.I64(), Days = r.I32(), Kind = r.U8() };
r.Flags();
return m;
}
}
/// <summary>Scheda del proprietario di un'industria (sezione 11).</summary>
public sealed class IndustryCard : IMessage
{
public MessageId Id => MessageId.IndustryCard;
public int Industry { get; init; }
public float Margin { get; init; }
public float ConditionMultiplier { get; init; }
/// <summary>Usura e recupero giornalieri attuali (punti di condizione).</summary>
public float WearPerDay { get; init; }
public float RecoveryPerDay { get; init; }
public Money MaintenanceCostPerDay { get; init; }
public Money MaintenanceSpentYear { get; init; }
public int PartsTarget { get; init; }
public int PartsPerMonth { get; init; }
public int PartsOrdered { get; init; }
public int MachineryRequired { get; init; }
public Money UpgradeCost { get; init; }
/// <summary>Prezzo chiesto dai proprietari privati (per BuyIndustry).</summary>
public Money Valuation { get; init; }
public Money Cash { get; init; }
public float BreakdownChancePerYear { get; init; }
public List<IndustryStopInfo> Stops { get; init; } = [];
public void Write(ref SpanWriter w)
{
w.I32(Industry); w.F32(Margin); w.F32(ConditionMultiplier); w.F32(WearPerDay); w.F32(RecoveryPerDay);
w.Money(MaintenanceCostPerDay); w.Money(MaintenanceSpentYear); w.I32(PartsTarget); w.I32(PartsPerMonth); w.I32(PartsOrdered);
w.I32(MachineryRequired); w.Money(UpgradeCost); w.Money(Valuation); w.Money(Cash); w.F32(BreakdownChancePerYear);
w.Count(Stops.Count);
foreach (var s in Stops) s.Write(ref w);
w.Flags(0);
}
public static IndustryCard Read(ref SpanReader r)
{
var m = new IndustryCard
{
Industry = r.I32(), Margin = r.F32(), ConditionMultiplier = r.F32(), WearPerDay = r.F32(), RecoveryPerDay = r.F32(),
MaintenanceCostPerDay = r.Money(), MaintenanceSpentYear = r.Money(), PartsTarget = r.I32(), PartsPerMonth = r.I32(), PartsOrdered = r.I32(),
MachineryRequired = r.I32(), UpgradeCost = r.Money(), Valuation = r.Money(), Cash = r.Money(), BreakdownChancePerYear = r.F32(),
};
for (int n = r.Count(), i = 0; i < n; i++) m.Stops.Add(IndustryStopInfo.Read(ref r));
r.Flags();
return m;
}
}
/// <summary>Primato della Cronaca finale (descrizione e valore già formattati in italiano).</summary>
public sealed class RecordInfo
{
public string Title { get; init; } = "";
public string Value { get; init; } = "";
public int Year { get; init; }
public void Write(ref SpanWriter w)
{
w.String(Title); w.String(Value); w.I32(Year);
w.Flags(0);
}
public static RecordInfo Read(ref SpanReader r)
{
var m = new RecordInfo { Title = r.String(), Value = r.String(), Year = r.I32() };
r.Flags();
return m;
}
}
/// <summary>
/// Cronaca finale (12.3): storia della compagnia del giocatore, grafici, primati e prestigio.
/// Dopo la Cronaca il giocatore può continuare come osservatore o iniziare una Nuova partita+.
/// </summary>
public sealed class Chronicle : IMessage
{
public MessageId Id => MessageId.Chronicle;
public bool GameOver { get; init; }
/// <summary>Motivo (GameOverReason): 1 fallimento, 2 scalata, 3 riscatto scaduto.</summary>
public byte Reason { get; init; }
public string Text { get; init; } = "";
public int Winner { get; init; } = -1;
public long Day { get; init; }
public string Company { get; init; } = "";
public int FoundedYear { get; init; }
public long Prestige { get; init; }
public List<CompanyYearInfo> History { get; init; } = [];
public List<RecordInfo> Records { get; init; } = [];
/// <summary>Fatti salienti della compagnia, dal più vecchio.</summary>
public List<string> Highlights { get; init; } = [];
public void Write(ref SpanWriter w)
{
w.Bool(GameOver); w.U8(Reason); w.String(Text); w.I32(Winner); w.I64(Day); w.String(Company); w.I32(FoundedYear); w.I64(Prestige);
w.Count(History.Count);
foreach (var y in History) y.Write(ref w);
w.Count(Records.Count);
foreach (var rec in Records) rec.Write(ref w);
w.Count(Highlights.Count);
foreach (var h in Highlights) w.String(h);
w.Flags(0);
}
public static Chronicle Read(ref SpanReader r)
{
bool over = r.Bool();
byte reason = r.U8();
string text = r.String();
int winner = r.I32();
long day = r.I64();
string company = r.String();
int founded = r.I32();
long prestige = r.I64();
var history = new List<CompanyYearInfo>();
for (int n = r.Count(), i = 0; i < n; i++) history.Add(CompanyYearInfo.Read(ref r));
var records = new List<RecordInfo>();
for (int n = r.Count(), i = 0; i < n; i++) records.Add(RecordInfo.Read(ref r));
var highlights = new List<string>();
for (int n = r.Count(), i = 0; i < n; i++) highlights.Add(r.String());
r.Flags();
return new Chronicle
{
GameOver = over, Reason = reason, Text = text, Winner = winner, Day = day, Company = company, FoundedYear = founded,
Prestige = prestige, History = history, Records = records, Highlights = highlights,
};
}
}
@@ -28,6 +28,9 @@ public static class MessageCodec
MessageId.EmploymentReport => EmploymentReport.Read(ref r),
MessageId.MaintenanceCard => MaintenanceCard.Read(ref r),
MessageId.WorkshopRegister => WorkshopRegister.Read(ref r),
MessageId.CompanyCard => CompanyCard.Read(ref r),
MessageId.IndustryCard => IndustryCard.Read(ref r),
MessageId.Chronicle => Chronicle.Read(ref r),
MessageId.MarketTape => MarketTape.Read(ref r),
MessageId.CommandResult => CommandResultMessage.Read(ref r),
MessageId.Notification => Notification.Read(ref r),
+42 -3
View File
@@ -71,12 +71,28 @@ public sealed class CompanyInfo : IWritable
// blocco 1 (F4): politica di manutenzione della flotta
public byte MaintenancePolicy { get; set; } = 1;
// blocco 2 (F5): borsa, controllo, stato societario
public string Personality { get; set; } = "";
public bool Listed { get; set; }
/// <summary>Prezzo per azione in centesimi (frazionario).</summary>
public double SharePriceCents { get; set; }
public float Sentiment { get; set; } = 1;
/// <summary>Quota del fondatore sulle azioni in circolazione.</summary>
public float FounderShare { get; set; } = 1;
public int ControlledBy { get; set; } = -1;
public bool Merged { get; set; }
public bool Receivership { get; set; }
public long ReceivershipUntilDay { get; set; } = -1;
public Money AnnualProfit { get; set; }
public void Write(ref SpanWriter w)
{
w.I32(Id); w.String(Name); w.String(Color); w.Bool(IsPlayer); w.Money(Cash); w.Money(NetWorth);
w.String(Rating); w.U8(Tier); w.Bool(Bankrupt);
w.Flags(1);
w.Flags(3);
w.U8(MaintenancePolicy);
w.String(Personality); w.Bool(Listed); w.F64(SharePriceCents); w.F32(Sentiment); w.F32(FounderShare);
w.I32(ControlledBy); w.Bool(Merged); w.Bool(Receivership); w.I64(ReceivershipUntilDay); w.Money(AnnualProfit);
}
public static CompanyInfo Read(ref SpanReader r)
@@ -88,6 +104,11 @@ public sealed class CompanyInfo : IWritable
};
byte flags = r.Flags();
if ((flags & 1) != 0) m.MaintenancePolicy = r.U8();
if ((flags & 2) != 0)
{
m.Personality = r.String(); m.Listed = r.Bool(); m.SharePriceCents = r.F64(); m.Sentiment = r.F32(); m.FounderShare = r.F32();
m.ControlledBy = r.I32(); m.Merged = r.Bool(); m.Receivership = r.Bool(); m.ReceivershipUntilDay = r.I64(); m.AnnualProfit = r.Money();
}
return m;
}
}
@@ -129,11 +150,24 @@ public sealed class IndustryInfo : IWritable
public float Condition { get; init; }
public int Owner { get; init; } = -1;
// blocco 1 (F5): manutenzione degli impianti (sezione 11)
/// <summary>Budget di manutenzione: 0 nessuno, 1 base, 2 alto.</summary>
public byte Budget { get; set; } = 1;
public int SpareParts { get; set; }
public int Machinery { get; set; }
/// <summary>Giorno di fine del fermo in corso (−1 se lavora) e motivo (IndustryStop).</summary>
public long StoppedUntilDay { get; set; } = -1;
public byte StopKind { get; set; }
/// <summary>Lavoro programmato in attesa (IndustryWork).</summary>
public byte PendingWork { get; set; }
public bool PartsShort { get; set; }
public void Write(ref SpanWriter w)
{
w.I32(Id); w.String(Type); w.String(Name); w.Vec2(Position); w.I32(FootprintCells); w.I32(Level); w.Bool(Closed);
w.F32(Efficiency); w.F32(Condition); w.I32(Owner);
w.Flags(0);
w.Flags(1);
w.U8(Budget); w.I32(SpareParts); w.I32(Machinery); w.I64(StoppedUntilDay); w.U8(StopKind); w.U8(PendingWork); w.Bool(PartsShort);
}
public static IndustryInfo Read(ref SpanReader r)
@@ -143,7 +177,12 @@ public sealed class IndustryInfo : IWritable
Id = r.I32(), Type = r.String(), Name = r.String(), Position = r.Vec2(), FootprintCells = r.I32(), Level = r.I32(), Closed = r.Bool(),
Efficiency = r.F32(), Condition = r.F32(), Owner = r.I32(),
};
r.Flags();
byte flags = r.Flags();
if ((flags & 1) != 0)
{
m.Budget = r.U8(); m.SpareParts = r.I32(); m.Machinery = r.I32(); m.StoppedUntilDay = r.I64(); m.StopKind = r.U8();
m.PendingWork = r.U8(); m.PartsShort = r.Bool();
}
return m;
}
}
@@ -739,16 +739,27 @@ public sealed class SharePrice
public float Change { get; init; }
public bool Listed { get; init; }
// blocco 1 (F5): prezzo esatto, capitalizzazione, flottante libero, quota del fondatore
public double PriceCents { get; set; }
public long Outstanding { get; set; }
public long FreeFloat { get; set; }
public float FounderShare { get; set; }
public int ControlledBy { get; set; } = -1;
public void Write(ref SpanWriter w)
{
w.I32(Company); w.Money(Price); w.F32(Change); w.Bool(Listed);
w.Flags(0);
w.Flags(1);
w.F64(PriceCents); w.I64(Outstanding); w.I64(FreeFloat); w.F32(FounderShare); w.I32(ControlledBy);
}
public static SharePrice Read(ref SpanReader r)
{
var m = new SharePrice { Company = r.I32(), Price = r.Money(), Change = r.F32(), Listed = r.Bool() };
r.Flags();
if ((r.Flags() & 1) != 0)
{
m.PriceCents = r.F64(); m.Outstanding = r.I64(); m.FreeFloat = r.I64(); m.FounderShare = r.F32(); m.ControlledBy = r.I32();
}
return m;
}
}
@@ -762,16 +773,28 @@ public sealed class BidInfo
public double TargetShare { get; init; }
public long ExpiresDay { get; init; }
// blocco 1 (F5): stato, quota già impegnata (azioni dell'offerente + adesioni), difese, cavaliere bianco
public byte State { get; set; }
public double CommittedShare { get; set; }
public byte Defenses { get; set; }
public int Knight { get; set; } = -1;
/// <summary>Vero se la compagnia della sessione ha già aderito.</summary>
public bool Accepted { get; set; }
public void Write(ref SpanWriter w)
{
w.I32(Bid); w.I32(Bidder); w.I32(Target); w.Money(PricePerShare); w.F64(TargetShare); w.I64(ExpiresDay);
w.Flags(0);
w.Flags(1);
w.U8(State); w.F64(CommittedShare); w.U8(Defenses); w.I32(Knight); w.Bool(Accepted);
}
public static BidInfo Read(ref SpanReader r)
{
var m = new BidInfo { Bid = r.I32(), Bidder = r.I32(), Target = r.I32(), PricePerShare = r.Money(), TargetShare = r.F64(), ExpiresDay = r.I64() };
r.Flags();
if ((r.Flags() & 1) != 0)
{
m.State = r.U8(); m.CommittedShare = r.F64(); m.Defenses = r.U8(); m.Knight = r.I32(); m.Accepted = r.Bool();
}
return m;
}
}
+17
View File
@@ -619,6 +619,13 @@ public sealed class GameHost : IDisposable
}
}
if (_monthlyDue) s.Send(Projection.Employment(w, s.Company));
// listino di borsa del giorno (12.2) e, a fine partita, la Cronaca finale una volta per sessione
s.Send(Projection.Tape(w, s.Company));
if (w.GameOver is not null && !s.ChronicleSent)
{
s.Send(Projection.Chronicle(w));
s.ChronicleSent = true;
}
}
_monthlyDue = false;
_dayEvents.Clear();
@@ -641,6 +648,16 @@ public sealed class GameHost : IDisposable
case DetailKind.Employment:
s.Send(Projection.Employment(w, s.Company));
break;
case DetailKind.Company:
if (m.Target >= 0 && m.Target < w.Companies.Count) s.Send(Projection.CompanyCard(w, w.Companies[m.Target]));
break;
case DetailKind.Industry:
if (m.Target >= 0 && m.Target < w.Industries.Count && !w.Industries[m.Target].Closed)
s.Send(Projection.IndustryCard(w, w.Industries[m.Target]));
break;
case DetailKind.Chronicle:
s.Send(Projection.Chronicle(w));
break;
}
}
+105 -1
View File
@@ -79,6 +79,9 @@ public static class Projection
{
Id = c.Id.Value, Name = c.Name, Color = c.Color, IsPlayer = c.IsPlayer, Cash = c.Cash, NetWorth = c.NetWorth,
Rating = c.Rating.ToString(), Tier = (byte)c.Tier, Bankrupt = c.Bankrupt, MaintenancePolicy = (byte)c.MaintenancePolicy,
Personality = c.AiPersonality ?? "", Listed = c.Listed, SharePriceCents = Math.Round(c.SharePrice, 2), Sentiment = (float)c.Sentiment,
FounderShare = (float)c.Shares.FounderFraction, ControlledBy = c.ControlledBy.Value, Merged = c.Merged,
Receivership = c.Receivership, ReceivershipUntilDay = c.ReceivershipUntilDay, AnnualProfit = new Money(c.AnnualProfit),
});
}
foreach (var t in w.Towns)
@@ -94,7 +97,9 @@ public static class Projection
e.Industries.Add(new IndustryInfo
{
Id = i.Id.Value, Type = i.Def.Id, Name = i.Name, Position = i.Position, FootprintCells = i.FootprintCells, Level = i.Level,
Closed = i.Closed, Efficiency = (float)i.Efficiency, Condition = (float)i.Condition, Owner = i.Owner.IsValid ? i.Owner.Value : -1,
Closed = i.Closed, Efficiency = (float)i.Efficiency, Condition = (float)Math.Round(i.Condition, 1), Owner = i.Owner.IsValid ? i.Owner.Value : -1,
Budget = (byte)i.Budget, SpareParts = i.SpareParts, Machinery = i.Machinery, StoppedUntilDay = i.StoppedUntilDay,
StopKind = (byte)i.StopKind, PendingWork = (byte)i.PendingWork, PartsShort = i.PartsShort,
});
}
foreach (var h in w.Hubs)
@@ -414,4 +419,103 @@ public static class Projection
record.Write(ref w);
return XxHash64.Hash(w.Written);
}
// ------------------------------------------------------------------ F5: borsa, industrie, Cronaca
/// <summary>Listino del giorno: prezzi delle compagnie attive e offerte pubbliche in corso.</summary>
public static MarketTape Tape(World w, CompanyId viewer)
{
var tape = new MarketTape { Day = w.Clock.Day };
foreach (var c in w.Companies)
{
if (c.Defunct) continue;
double last = c.PriceHistory.Count > 0 ? c.PriceHistory[^1] : c.SharePrice;
tape.Shares.Add(new SharePrice
{
Company = c.Id.Value, Price = Money.FromCentsRounded(c.SharePrice), Change = last > 0 ? (float)(c.SharePrice / last - 1) : 0,
Listed = c.Listed, PriceCents = Math.Round(c.SharePrice, 4), Outstanding = c.Shares.Outstanding, FreeFloat = Corporate.FreeFloat(w, c),
FounderShare = (float)c.Shares.FounderFraction, ControlledBy = c.ControlledBy.Value,
});
}
foreach (var b in w.Bids)
{
if (b.State != BidState.Open) continue;
var target = w.Company(b.Target);
tape.Bids.Add(new BidInfo
{
Bid = b.Id.Value, Bidder = b.Bidder.Value, Target = b.Target.Value, PricePerShare = new Money(b.PricePerShare), TargetShare = b.TargetShare,
ExpiresDay = b.EndDay, State = (byte)b.State,
CommittedShare = target.Shares.Outstanding > 0 ? (double)StockMarketSystem.Committed(w, b) / target.Shares.Outstanding : 0,
Defenses = b.Defenses, Knight = b.Knight.Value, Accepted = b.Accepted.Contains(viewer),
});
}
return tape;
}
private static CompanyYearInfo YearInfo(CompanyYear y) => new()
{
Year = y.Year, NetWorth = new Money(y.NetWorthCents), Cash = new Money(y.CashCents), Revenue = new Money(y.RevenueCents),
Profit = new Money(y.ProfitCents), Tier = (byte)y.Tier, Trains = y.Trains, TrackKm = (float)y.TrackKm, SharePrice = new Money(y.SharePriceCents),
};
/// <summary>Scheda di una compagnia: libro dei soci, prezzi mensili, storico annuale, asta.</summary>
public static CompanyCard CompanyCard(World w, Company c)
{
var holdings = new List<HoldingInfo>
{
new() { Holder = HoldingInfo.Founder, Shares = c.Shares.Founder },
new() { Holder = HoldingInfo.Market, Shares = c.Shares.Public },
};
for (int i = 0; i < c.Shares.ByCompany.Length; i++)
{
if (c.Shares.ByCompany[i] > 0) holdings.Add(new HoldingInfo { Holder = i, Shares = c.Shares.ByCompany[i] });
}
long dividends = 0;
foreach (long d in c.DividendRing) dividends += d;
var auction = w.Auctions.FirstOrDefault(a => a.Seller == c.Id && !a.Closed);
return new CompanyCard
{
Company = c.Id.Value, TotalShares = c.Shares.Total, Treasury = c.Shares.Treasury, Holdings = holdings,
PriceHistory = [.. c.PriceHistory], History = c.History.Select(YearInfo).ToList(),
AnnualProfit = new Money(c.AnnualProfit), DividendsYear = new Money(dividends), Debt = c.Debt, MarketCap = Money.FromCentsRounded(c.MarketCap),
ControlDays = c.ControlledBy.IsValid ? w.Clock.Day - c.ControlSinceDay : -1,
AuctionMin = new Money(auction?.MinPriceCents ?? 0), AuctionBest = new Money(auction?.BestPriceCents ?? 0),
AuctionBestBidder = auction?.BestBidder.Value ?? -1, AuctionEndDay = auction?.EndDay ?? -1,
};
}
/// <summary>Scheda del proprietario di un'industria (sezione 11).</summary>
public static IndustryCard IndustryCard(World w, Industry ind)
{
var m = w.Data.Balance.IndustryMaintenance;
var budget = m.For(ind.Budget);
double wear = m.WearPerDay * Math.Max(0, ind.Efficiency) * ind.Def.WearIntensity * w.Difficulty.WearMultiplier;
double recovery = budget.RecoveryPerDay * (ind.PartsShort ? m.NoPartsRecoveryFactor : 1);
double hazard = ind.Condition >= m.BreakdownPivot ? 0 : m.BreakdownBase * DMath.Exp((m.BreakdownPivot - ind.Condition) / m.BreakdownScale);
double perYear = 1 - DMath.Pow(1 - Math.Min(1, hazard), w.Calendar.DaysPerYear);
return new IndustryCard
{
Industry = ind.Id.Value, Margin = (float)ind.Margin, ConditionMultiplier = (float)IndustryMath.ConditionMultiplier(ind.Condition, m),
WearPerDay = (float)wear, RecoveryPerDay = (float)recovery, MaintenanceCostPerDay = Money.FromCentsRounded(ind.RevenueEma * budget.CostShareOfRevenue),
MaintenanceSpentYear = new Money(ind.MaintenanceSpentYear), PartsTarget = IndustryMath.PartsTarget(ind, m), PartsPerMonth = IndustryMath.MonthlyPartsUse(ind, m),
PartsOrdered = ind.PartsOrdered, MachineryRequired = IndustryMath.MachineryRequired(ind, m), UpgradeCost = IndustryMaintenanceSystem.UpgradeCost(ind),
Valuation = IndustryMath.Valuation(w, ind), Cash = ind.Cash, BreakdownChancePerYear = (float)perYear,
Stops = ind.StopHistory.Select(h => new IndustryStopInfo { Day = h.Day, Days = h.Days, Kind = (byte)h.Kind }).ToList(),
};
}
/// <summary>Cronaca finale (o provvisoria, se la partita è in corso) della compagnia del giocatore.</summary>
public static Chronicle Chronicle(World w)
{
var report = ChronicleReport.Build(w);
return new Chronicle
{
GameOver = w.GameOver is not null, Reason = (byte)(w.GameOver?.Reason ?? GameOverReason.None), Text = w.GameOver?.Text ?? "",
Winner = w.GameOver?.Winner.Value ?? -1, Day = w.GameOver?.Day ?? w.Clock.Day, Company = w.Player.Name,
FoundedYear = w.Calendar.StartYear, Prestige = report.Prestige,
History = report.History.Select(YearInfo).ToList(),
Records = report.Records.Select(r => new RecordInfo { Title = r.Title, Value = r.Value, Year = r.Year }).ToList(),
Highlights = report.Highlights,
};
}
}
+3
View File
@@ -38,6 +38,9 @@ public sealed class Session
public Dictionary<int, (long Tick, byte State)> MotionSent { get; } = [];
public bool NeedsFullState { get; set; } = true;
/// <summary>Cronaca finale già inviata a questa sessione.</summary>
public bool ChronicleSent { get; set; }
public Session(ulong id, CompanyId company)
{
Id = id;
@@ -17,7 +17,7 @@ public sealed class SimulateCommand : IToolCommand
{
public string Name => "simulate";
public string Usage => "simulate --seed <n> --years <n> [--size 128] [--difficulty imprenditore] [--scenario <file>] [--out kpi.csv] [--save <file>]";
public string Usage => "simulate --seed <n> --years <n> [--size 128] [--difficulty imprenditore] [--scenario <file>] [--out kpi.csv] [--save <file>] [--trace-ai]";
private static readonly CultureInfo It = CultureInfo.InvariantCulture;
@@ -30,7 +30,9 @@ public sealed class SimulateCommand : IToolCommand
string? scenario = args.String("scenario");
string output = args.String("out", "kpi.csv");
string? savePath = args.String("save");
bool trace = args.Flag("trace-ai");
args.EnsureAllUsed();
if (trace) Core.Simulation.Ai.AiSystem.Trace = Console.WriteLine;
var data = GameData.LoadDefault();
var total = Stopwatch.StartNew();
@@ -65,6 +67,8 @@ public sealed class SimulateCommand : IToolCommand
Console.WriteLine($" data finale {world.Clock.Date}, hash {world.LastStateHash:x16}");
Console.WriteLine($" popolazione {Core.Common.Money.GroupThousands((ulong)world.Towns.Sum(t => (long)t.Population))}, industrie aperte {world.Industries.Count(i => !i.Closed)} su {world.Industries.Count}");
Console.WriteLine($" invarianti: denaro {(world.MoneyBalanceSum() == 0 ? "ok" : "ROTTO")}, merci {(Enumerable.Range(0, data.GoodCount).All(g => world.TotalStock(g) == world.Goods.ExpectedStock(g)) ? "ok" : "ROTTO")}");
foreach (var c in world.Companies)
Console.WriteLine($" {c.Name}: patrimonio {c.NetWorth}, cassa {c.Cash}, livello {c.Tier}, rating {c.Rating}, azione {c.SharePrice / 100:0.00} lire{AiNote(world, c)}{(c.Defunct ? " (fuori gioco)" : "")}");
Console.WriteLine($" KPI in {output}");
return 0;
}
@@ -91,12 +95,22 @@ public sealed class SimulateCommand : IToolCommand
{
long revenue = Company.Revenue(c.LastYearEntries);
double share = totalCarrier > 0 ? (double)revenue / totalCarrier : 0;
string note = $"{(c.IsPlayer ? "giocatore" : c.AiPersonality)}, rating {c.Rating}, livello {c.Tier}{(c.Bankrupt ? ", bancarotta" : "")}";
string note = $"{(c.IsPlayer ? "giocatore" : c.AiPersonality)}, rating {c.Rating}, livello {c.Tier}{(c.Bankrupt ? ", bancarotta" : "")}{(c.Merged ? ", fusa" : "")}{AiNote(w, c)}";
bool fleet = w.Trains.Any(t => !t.Removed && t.Owner == c.Id && t.Vehicles.Count > 0);
csv.AppendLine(string.Join(';', year.ToString(It), c.Name, "", "", "", "", population.ToString(It), "",
fleet ? Dec(Fleet.FleetCondition(w, c.Id)) : "", "", Dec(c.Cash.Lire), Dec(c.NetWorth.Lire), Dec(share), note));
}
}
/// <summary>Diagnostica dell'agente IA: progetti, treni, comandi rifiutati.</summary>
private static string AiNote(World w, Company c)
{
var s = w.AiStates.FirstOrDefault(a => a.Company == c.Id);
if (s is null) return "";
int running = s.Projects.Count(p => p.Stage == Core.Simulation.Ai.AiProjectStage.Running);
int trains = w.Trains.Count(t => !t.Removed && t.Owner == c.Id);
return $", progetti {running}/{s.Projects.Count}, treni {trains}, città collegate {Tiers.ConnectedTowns(w, c.Id, 1000)} (≥1000) {Tiers.ConnectedTowns(w, c.Id, 2000)} (≥2000), comandi {s.Issued} (rifiutati {s.RejectedShare * 100:0.0} %)";
}
private static string Dec(double v) => v.ToString("0.###", It).Replace('.', ',');
}