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

+45 -3
View File
@@ -7,13 +7,55 @@
"maxProjectsPerMonth": 2, "maxProjectsPerMonth": 2,
"candidateMaxDistanceKm": 40, "candidateMaxDistanceKm": 40,
"candidateMinDistanceKm": 4, "candidateMinDistanceKm": 4,
"pathSlopePenalty": 40, "pathSlopePenalty": 120,
"pathWaterPenalty": 8, "pathWaterPenalty": 8,
"trainsPerLine": 2, "steepPenalty": 25,
"steepGradeFactor": 1.6,
"pathMarginRetryKm": 20,
"trainsPerLine": 1,
"wagonsPerTrain": 5, "wagonsPerTrain": 5,
"cashReserveMonths": 3, "cashReserveMonths": 3,
"revenueHorizonYears": 10, "revenueHorizonYears": 10,
"maxRejectedShare": 0.05 "maxRejectedShare": 0.05,
"maxConcurrentProjects": 2,
"evaluateTop": 6,
"pathMarginKm": 8,
"simplifyToleranceM": 120,
"stationOffsetsM": [ 300, 550, 850, 1250 ],
"depotOffsetM": 450,
"platforms": 3,
"hubPlatforms": 6,
"assumedEfficiency": 0.6,
"speedFactor": 0.55,
"dwellMinutes": 6,
"maintenanceCostShare": 0.2,
"trackUpkeepPerKmPerYear": 30000,
"maxTrainsPerLine": 2,
"addTrainWaitingTrips": 2.0,
"minCommuters": 20,
"commuterCoverage": 0.6,
"hubShare": 0.25,
"noPartsFactor": 0.5,
"townBonus": 1.8,
"townRoiFactor": 0.5,
"repayCashMonths": 12,
"planningDaySpacing": 7,
"failedMemory": 64
},
"market": {
"founderAcceptPremium": 0.4,
"holderAcceptPremium": 0.15,
"predatoryStakeTarget": 0.3,
"sharesCashShare": 0.1,
"bidMinStake": 0.25,
"bidPremium": 0.3,
"bidCashMultiple": 1.2,
"buybackCashShare": 0.5,
"knightCashMultiple": 2.0,
"issueFloatMax": 0.5,
"issueShare": 0.1,
"industryMaxCashShare": 0.25,
"industryMinMargin": 0.1
}, },
"personalities": [ "personalities": [
{ "id": "expansive", "name_it": "Espansiva", "roiThreshold": 0.08, "loanShareOfCredit": 0.8, "targetsPlayer": false, "buysShares": false, "maintenancePolicy": "standard" }, { "id": "expansive", "name_it": "Espansiva", "roiThreshold": 0.08, "loanShareOfCredit": 0.8, "targetsPlayer": false, "buysShares": false, "maintenancePolicy": "standard" },
+31 -4
View File
@@ -117,11 +117,11 @@
"border": { "name_it": "Valico", "monthlyCapacity": 1500, "duty": 0.12, "footprint": "small" } "border": { "name_it": "Valico", "monthlyCapacity": 1500, "duty": 0.12, "footprint": "small" }
}, },
"tariffs": { "tariffs": {
"freightBaseRate": 150, "freightBaseRate": 360,
"freightFixedWeight": 0.6, "freightFixedWeight": 0.6,
"freightPriceWeight": 0.4, "freightPriceWeight": 0.4,
"freightKmExponent": 0.9, "freightKmExponent": 0.9,
"paxBaseFare": 45, "paxBaseFare": 75,
"paxKmExponent": 0.85, "paxKmExponent": 0.85,
"classMultipliers": { "worker": 1.0, "staff": 3.0 }, "classMultipliers": { "worker": 1.0, "staff": 3.0 },
"lateThreshold": 1.5, "lateThreshold": 1.5,
@@ -152,7 +152,27 @@
"bidPremiumMax": 0.5, "bidPremiumMax": 0.5,
"bidDurationDays": 90, "bidDurationDays": 90,
"ransomShare": 0.51, "ransomShare": 0.51,
"receivershipDividend": 0.5 "receivershipDividend": 0.5,
"sentimentEarningsWeight": 0.4,
"sentimentCycleWeight": 1.0,
"sentimentDividendWeight": 4.0,
"sentimentSmoothingDays": 30,
"extraDividendSentimentBoost": 0.15,
"extraDividendDecayDays": 120,
"aiFloatAtStart": 0.3,
"tenderDailyShare": 0.04,
"extraDividendCashShare": 0.25,
"whiteKnightPremium": 0.05,
"ransomPremium": 0.25,
"maxDailyTradeShare": 0.05,
"secondaryMaxFloat": 0.6,
"priceHistoryMonths": 120,
"auctionDays": 30,
"auctionMinBookShare": 0.4,
"concentrationThreshold": 0.6,
"newCompetitorCooldownYears": 3,
"maxCompanies": 8,
"historyYears": 300
}, },
"industryMaintenance": { "industryMaintenance": {
"wearPerDay": 0.06, "wearPerDay": 0.06,
@@ -181,6 +201,13 @@
"npcUpgradeMargin": 0.15, "npcUpgradeMargin": 0.15,
"npcUpgradeYears": 2, "npcUpgradeYears": 2,
"npcHighMargin": 0.15, "npcHighMargin": 0.15,
"npcOverhaulBelow": 35 "npcOverhaulBelow": 35,
"partsTargetMonths": 3,
"initialPartsMonths": 6,
"maxOrderedParts": 200,
"townEffectRadiusKm": 12,
"stopHistoryLength": 12,
"ownerCashReserve": 2000000,
"purchase": { "assetShare": 0.6, "earningsMultiple": 5, "conditionWeight": 0.5 }
} }
} }
+5 -5
View File
@@ -23,7 +23,7 @@
], ],
"curveSpeedFactor": 0.65, "curveSpeedFactor": 0.65,
"costs": { "costs": {
"basePerMeter": 1200, "basePerMeter": 700,
"natural": 1.0, "natural": 1.0,
"embankmentPerM": 0.25, "embankmentPerM": 0.25,
"cuttingPerM": 0.35, "cuttingPerM": 0.35,
@@ -34,9 +34,9 @@
"land": { "basePerCell": 20000, "nearTownKm": 2.0, "nearTownMultiplier": 3.0, "fieldMultiplier": 2.0 }, "land": { "basePerCell": 20000, "nearTownKm": 2.0, "nearTownMultiplier": 3.0, "fieldMultiplier": 2.0 },
"doubleTrackMultiplier": 1.8, "doubleTrackMultiplier": 1.8,
"electrificationExtra": 0.35, "electrificationExtra": 0.35,
"stationBase": 4000000, "stationBase": 1200000,
"stationPerPlatform": 1500000, "stationPerPlatform": 400000,
"depotBySize": { "small": 6000000, "medium": 12000000, "large": 24000000 }, "depotBySize": { "small": 2000000, "medium": 4000000, "large": 8000000 },
"demolitionRefund": 0.1 "demolitionRefund": 0.1
}, },
"crews": { "crews": {
@@ -56,7 +56,7 @@
"gradientWeight": 8, "gradientWeight": 8,
"speedWeight": 0.4, "speedWeight": 0.4,
"maintenanceDriftPerDay": 0.02, "maintenanceDriftPerDay": 0.02,
"maintenanceCostPerKmPerDay": 400, "maintenanceCostPerKmPerDay": 60,
"limitBelow60": 0.6, "limitBelow60": 0.6,
"limitBelow30": 0.3, "limitBelow30": 0.3,
"failureChanceBelow30": 0.002, "failureChanceBelow30": 0.002,
+7 -7
View File
@@ -50,12 +50,12 @@
"comfortMax": 1.05 "comfortMax": 1.05
}, },
"interventions": [ "interventions": [
{ "id": "inspection", "name_it": "Ispezione", "days": 1, "costShare": 0.005, "spareParts": 0, "effect": "inspection" }, { "id": "inspection", "name_it": "Ispezione", "days": 1, "costShare": 0.001, "spareParts": 0, "effect": "inspection" },
{ "id": "service", "name_it": "Tagliando", "days": 3, "costShare": 0.03, "spareParts": 1, "effect": "service" }, { "id": "service", "name_it": "Tagliando", "days": 3, "costShare": 0.012, "spareParts": 1, "effect": "service" },
{ "id": "overhaul", "name_it": "Revisione generale", "days": 20, "costShare": 0.25, "spareParts": 5, "effect": "overhaul" }, { "id": "overhaul", "name_it": "Revisione generale", "days": 20, "costShare": 0.12, "spareParts": 5, "effect": "overhaul" },
{ "id": "repair_minor", "name_it": "Riparazione dopo guasto lieve", "days": 2, "costShare": 0.05, "spareParts": 1, "effect": "repair", "restoreTo": 80 }, { "id": "repair_minor", "name_it": "Riparazione dopo guasto lieve", "days": 2, "costShare": 0.03, "spareParts": 1, "effect": "repair", "restoreTo": 80 },
{ "id": "repair_major", "name_it": "Riparazione dopo guasto grave", "days": 7, "costShare": 0.15, "spareParts": 3, "effect": "repair", "restoreTo": 90 }, { "id": "repair_major", "name_it": "Riparazione dopo guasto grave", "days": 7, "costShare": 0.08, "spareParts": 3, "effect": "repair", "restoreTo": 90 },
{ "id": "repair_catastrophic", "name_it": "Ricostruzione dopo deragliamento", "days": 30, "costShare": 0.40, "spareParts": 8, "effect": "replace" } { "id": "repair_catastrophic", "name_it": "Ricostruzione dopo deragliamento", "days": 30, "costShare": 0.3, "spareParts": 8, "effect": "replace" }
], ],
"inspection": { "brakesTo": 100, "othersPlus": 10, "hazardFactor": 0.5, "hazardDays": 30 }, "inspection": { "brakesTo": 100, "othersPlus": 10, "hazardFactor": 0.5, "hazardDays": 30 },
"service": { "plus": 40 }, "service": { "plus": 40 },
@@ -64,7 +64,7 @@
"stallsBySize": { "small": 2, "medium": 4, "large": 8 }, "stallsBySize": { "small": 2, "medium": 4, "large": 8 },
"staffPerStall": 4, "staffPerStall": 4,
"slowdownAtHalfStaff": 2.0, "slowdownAtHalfStaff": 2.0,
"initialSpareParts": 10, "initialSpareParts": 25,
"jobsWorkersPerStall": 6, "jobsWorkersPerStall": 6,
"targetSpareParts": 40, "targetSpareParts": 40,
"maxSpareParts": 400 "maxSpareParts": 400
+12 -1
View File
@@ -90,6 +90,16 @@
"pattern": "^#[0-9a-fA-F]{6}$" "pattern": "^#[0-9a-fA-F]{6}$"
}, },
"minItems": 1 "minItems": 1
},
"market": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean"
]
}
} }
}, },
"required": [ "required": [
@@ -97,7 +107,8 @@
"planning", "planning",
"personalities", "personalities",
"companyNames", "companyNames",
"colors" "colors",
"market"
], ],
"additionalProperties": false "additionalProperties": false
} }
+4 -4
View File
@@ -7,16 +7,16 @@
"requirements": { "netWorth": 0, "connectedTownsOver": { "count": 0, "population": 0 }, "creditRating": "D" }, "requirements": { "netWorth": 0, "connectedTownsOver": { "count": 0, "population": 0 }, "creditRating": "D" },
"unlocks": { "maxLoanFactor": 1.0, "crews": 2, "trading": false, "buyIndustry": false, "ipo": false, "hostileTakeover": false, "concessions": false } }, "unlocks": { "maxLoanFactor": 1.0, "crews": 2, "trading": false, "buyIndustry": false, "ipo": false, "hostileTakeover": false, "concessions": false } },
{ "level": 2, "name_it": "Compagnia regionale", "name_en": "Regional company", { "level": 2, "name_it": "Compagnia regionale", "name_en": "Regional company",
"requirements": { "netWorth": 100000000, "connectedTownsOver": { "count": 3, "population": 1000 }, "creditRating": "BB" }, "requirements": { "netWorth": 40000000, "connectedTownsOver": { "count": 2, "population": 800 }, "creditRating": "BB" },
"unlocks": { "maxLoanFactor": 2.0, "crews": 4, "trading": true, "buyIndustry": false, "ipo": false, "hostileTakeover": false, "concessions": false } }, "unlocks": { "maxLoanFactor": 2.0, "crews": 4, "trading": true, "buyIndustry": false, "ipo": false, "hostileTakeover": false, "concessions": false } },
{ "level": 3, "name_it": "Compagnia nazionale", "name_en": "National company", { "level": 3, "name_it": "Compagnia nazionale", "name_en": "National company",
"requirements": { "netWorth": 500000000, "connectedTownsOver": { "count": 8, "population": 2000 }, "creditRating": "BBB" }, "requirements": { "netWorth": 100000000, "connectedTownsOver": { "count": 3, "population": 1000 }, "creditRating": "BBB" },
"unlocks": { "maxLoanFactor": 4.0, "crews": 8, "trading": true, "buyIndustry": true, "ipo": false, "hostileTakeover": false, "concessions": true } }, "unlocks": { "maxLoanFactor": 4.0, "crews": 8, "trading": true, "buyIndustry": true, "ipo": false, "hostileTakeover": false, "concessions": true } },
{ "level": 4, "name_it": "Grande compagnia", "name_en": "Major company", { "level": 4, "name_it": "Grande compagnia", "name_en": "Major company",
"requirements": { "netWorth": 2000000000, "connectedTownsOver": { "count": 15, "population": 3000 }, "creditRating": "A" }, "requirements": { "netWorth": 400000000, "connectedTownsOver": { "count": 6, "population": 2000 }, "creditRating": "A" },
"unlocks": { "maxLoanFactor": 8.0, "crews": 12, "trading": true, "buyIndustry": true, "ipo": true, "hostileTakeover": false, "concessions": true } }, "unlocks": { "maxLoanFactor": 8.0, "crews": 12, "trading": true, "buyIndustry": true, "ipo": true, "hostileTakeover": false, "concessions": true } },
{ "level": 5, "name_it": "Impero ferroviario", "name_en": "Railway empire", { "level": 5, "name_it": "Impero ferroviario", "name_en": "Railway empire",
"requirements": { "netWorth": 8000000000, "connectedTownsOver": { "count": 25, "population": 5000 }, "creditRating": "AA" }, "requirements": { "netWorth": 1500000000, "connectedTownsOver": { "count": 10, "population": 3500 }, "creditRating": "AA" },
"unlocks": { "maxLoanFactor": 16.0, "crews": 20, "trading": true, "buyIndustry": true, "ipo": true, "hostileTakeover": true, "concessions": true } } "unlocks": { "maxLoanFactor": 16.0, "crews": 20, "trading": true, "buyIndustry": true, "ipo": true, "hostileTakeover": true, "concessions": true } }
] ]
} }
+9 -5
View File
@@ -30,7 +30,7 @@ Regole:
| `ViaFerrea.Core.Economy` | Città, industrie, hub, mercato, compagnie, registro contabile a partita doppia, finanza. | | `ViaFerrea.Core.Economy` | Città, industrie, hub, mercato, compagnie, registro contabile a partita doppia, finanza. |
| `ViaFerrea.Core.Rail` | `TrackGeometry` (raccordi), `TrackPlanner` (profilo a 25 m, opere, costi, tempi, vincoli per era), `RailNetwork` (nodi, archi campionati, stazioni, depositi, cantieri, indice spaziale), `Pathfinder` (A* sugli archi orientati), veicoli, treni, linee, pacchetti, `LineGraph` con maschere dei carichi (ADR 0007, 0008). | | `ViaFerrea.Core.Rail` | `TrackGeometry` (raccordi), `TrackPlanner` (profilo a 25 m, opere, costi, tempi, vincoli per era), `RailNetwork` (nodi, archi campionati, stazioni, depositi, cantieri, indice spaziale), `Pathfinder` (A* sugli archi orientati), veicoli, treni, linee, pacchetti, `LineGraph` con maschere dei carichi (ADR 0007, 0008). |
| `ViaFerrea.Core.Commands` | Comandi di gioco (record immutabili) ed esiti. Sono l'unico modo di cambiare il mondo dall'esterno, anche per le IA. | | `ViaFerrea.Core.Commands` | Comandi di gioco (record immutabili) ed esiti. Sono l'unico modo di cambiare il mondo dall'esterno, anche per le IA. |
| `ViaFerrea.Core.Simulation` | `World`, `WorldContext`, `SystemPipeline` e `Systems/`, `WorldFactory`, `IndustryPlacer`, `CommandProcessor`, eventi in uscita. | | `ViaFerrea.Core.Simulation` | `World`, `WorldContext`, `SystemPipeline` e `Systems/`, `WorldFactory`, `IndustryPlacer`, `CommandProcessor` e gestori dei comandi, `Corporate` (fusioni, liquidazioni, fine partita), `Estimators` (stime condivise da IA e tooltip), `ChronicleReport`, `Ai/` (agenti delle compagnie IA, ricerca del percorso sulle celle), eventi in uscita. |
| `ViaFerrea.Core.Persistence` | `SaveWriter`/`SaveReader`, `SaveFile` (Brotli), `StateHasher`. | | `ViaFerrea.Core.Persistence` | `SaveWriter`/`SaveReader`, `SaveFile` (Brotli), `StateHasher`. |
## 3. Il tick ## 3. Il tick
@@ -43,7 +43,7 @@ Clock → Commands → Construction → Trains → Signals → Stations → Main
→ Finance → StockMarket → AiAgents (mensile) → Events → Contracts → Hash (giornaliero) → Finance → StockMarket → AiAgents (mensile) → Events → Contracts → Hash (giornaliero)
``` ```
Sistemi implementati (F1–F4), nella loro posizione: Sistemi implementati (F1–F5), nella loro posizione:
| Sistema | Frequenza | Cosa fa | | Sistema | Frequenza | Cosa fa |
|---|---|---| |---|---|---|
@@ -56,16 +56,19 @@ Sistemi implementati (F1–F4), nella loro posizione:
| `FleetMaintenanceSystem` | giorno | usura per componente in km di servizio, rischio e guasti (lieve, grave con soccorso, deragliamento), pianificatore predittivo e prenotazioni, officine con stalli, ricambi e personale, riserve, avvisi (posto di «Maintenance», ADR 0010); formule senza stato in `Fleet` | | `FleetMaintenanceSystem` | giorno | usura per componente in km di servizio, rischio e guasti (lieve, grave con soccorso, deragliamento), pianificatore predittivo e prenotazioni, officine con stalli, ricambi e personale, riserve, avvisi (posto di «Maintenance», ADR 0010); formule senza stato in `Fleet` |
| `DemandSystem` | giorno | domanda delle città (con elasticità) e input richiesti dalle industrie | | `DemandSystem` | giorno | domanda delle città (con elasticità) e input richiesti dalle industrie |
| `EmploymentSystem` | giorno/mese | servizi cittadini, lavoratori in sede, contratti a piedi e su rotaia per industrie e depositi (`IWorkplace`, abbinamento mensile sul `LineGraph`), motivi dei posti scoperti, convenzioni, pacchetti giornalieri dei pendolari, presenze e coperture (posto di «Commuting», ADR 0008 e 0010) | | `EmploymentSystem` | giorno/mese | servizi cittadini, lavoratori in sede, contratti a piedi e su rotaia per industrie e depositi (`IWorkplace`, abbinamento mensile sul `LineGraph`), motivi dei posti scoperti, convenzioni, pacchetti giornalieri dei pendolari, presenze e coperture (posto di «Commuting», ADR 0008 e 0010) |
| `IndustrySystem` | giorno/trimestre/anno | produzione, esaurimento giacimenti, salari, crescita delle industrie servite, chiusure, nascite | | `IndustrySystem` | giorno/trimestre/anno | produzione (nulla durante i fermi), esaurimento giacimenti, salari, crescita delle industrie servite, chiusure, nascite |
| `IndustryMaintenanceSystem` | giorno/mese | condizione degli impianti (usura con l'utilizzo, recupero del budget), consumo di ricambi, fermi e incidenti, revisioni e ammodernamenti in attesa di macchinari, scelte dei proprietari privati, conguaglio con il proprietario (ADR 0011) |
| `TownSystem` | giorno/mese/anno | consumo e soddisfazione, crescita, migrazione, espansione dell'abitato | | `TownSystem` | giorno/mese/anno | consumo e soddisfazione, crescita, migrazione, espansione dell'abitato |
| `MarketSystem` | giorno | prezzi globali con componente mondiale e shock, domanda insoddisfatta | | `MarketSystem` | giorno | prezzi globali con componente mondiale e shock, domanda insoddisfatta |
| `FinanceSystem` | giorno/mese/anno | costi di esercizio di veicoli, stazioni e depositi, valori di libro, cassa negativa e bancarotta, rate dei prestiti, rating, chiusura dei conti | | `FinanceSystem` | giorno/mese/anno | costi di esercizio di veicoli, stazioni e depositi, valori di libro, cassa negativa e bancarotta, rate dei prestiti, rating, livelli (`Tiers`), utile mensile nell'anello dei 12 mesi, chiusura dei conti |
| `StockMarketSystem` | giorno/mese/anno | prezzi e sentiment, valore delle partecipazioni, offerte pubbliche (adesioni, esito), controllo e utili delle controllate, amministrazione controllata del giocatore, fallimenti e aste, storico annuale, nuovi concorrenti (ADR 0012) |
| `AiSystem` | giorno/mese | agenti delle compagnie IA: progetti, stalli, offerte; una volta al mese (giorno diverso per IA) finanza, treni aggiuntivi, borsa, industrie, linee dei ricambi e nuovi progetti, tutto con i comandi (ADR 0013) |
| `HashSystem` | giorno | hash dello stato dinamico | | `HashSystem` | giorno | hash dello stato dinamico |
- Ogni sistema implementa `ISimSystem.Step(WorldContext ctx)`; i sistemi giornalieri o mensili controllano `ctx.IsNewDay` / `ctx.IsNewMonth` e ritornano subito negli altri tick: nei 239 tick su 240 lavora solo `TrainSystem`. - Ogni sistema implementa `ISimSystem.Step(WorldContext ctx)`; i sistemi giornalieri o mensili controllano `ctx.IsNewDay` / `ctx.IsNewMonth` e ritornano subito negli altri tick: nei 239 tick su 240 lavora solo `TrainSystem`.
- `SystemPipeline.Profile` misura tempo e allocazioni per sistema (usato da `bench`). - `SystemPipeline.Profile` misura tempo e allocazioni per sistema (usato da `bench`).
- `WorldContext` espone il mondo, i dati e il calendario; gli eventi in uscita (notifiche, notizie) vanno in `World.Events`, che il server svuota. - `WorldContext` espone il mondo, i dati e il calendario; gli eventi in uscita (notifiche, notizie) vanno in `World.Events`, che il server svuota.
- I comandi arrivano in una coda; il server la riempie dai socket, le IA dal proprio sistema; il sistema `Commands` la drena a inizio tick. Per il replay si registrano `(tick, comando)` in `World.CommandLog`. - I comandi arrivano in una coda; il server la riempie dai socket e il sistema `Commands` la drena a inizio tick. Le IA eseguono i loro comandi direttamente con `CommandProcessor` dal sistema `AiAgents` (stesse validazioni, esito immediato, numeri di sequenza ≥ 0x80000000, non registrati per il replay: le IA si rigiocano da sole). Per il replay si registrano `(tick, comando)` in `World.CommandLog`.
- I flussi pseudo-casuali dei sottosistemi si ottengono con `World.Stream(nome)` (derivati dalla radice con `Rng.Fork`, salvati per nome). - I flussi pseudo-casuali dei sottosistemi si ottengono con `World.Stream(nome)` (derivati dalla radice con `Rng.Fork`, salvati per nome).
## 4. Determinismo ## 4. Determinismo
@@ -98,6 +101,7 @@ Requisito: stesso seme + stessi comandi agli stessi tick ⇒ stesso hash di stat
- Definizioni salvate per id testuale e rimappate al caricamento; terreno salvato per intero. - Definizioni salvate per id testuale e rimappate al caricamento; terreno salvato per intero.
- `StateHasher` = XxHash64 di `WorldSerializer.WriteDynamic` (stato senza terreno, impostazioni ed eventi; il terreno entra con il suo hash). Dettagli: ADR 0006. - `StateHasher` = XxHash64 di `WorldSerializer.WriteDynamic` (stato senza terreno, impostazioni ed eventi; il terreno entra con il suo hash). Dettagli: ADR 0006.
- Corpo versione 2 (F4): `MaintenanceSerializer` aggiunge in coda allo stato dinamico manutenzione di veicoli e treni, officine, politiche, convenzioni e motivi dei posti scoperti; i salvataggi della versione 1 si migrano (ADR 0010). - Corpo versione 2 (F4): `MaintenanceSerializer` aggiunge in coda allo stato dinamico manutenzione di veicoli e treni, officine, politiche, convenzioni e motivi dei posti scoperti; i salvataggi della versione 1 si migrano (ADR 0010).
- Corpo versione 3 (F5): `CorporateSerializer` aggiunge manutenzione e proprietà delle industrie, libro dei soci, prezzi, controllo e storico delle compagnie, offerte, aste, fine partita e stato degli agenti IA (progetti, candidati scartati); i salvataggi precedenti si migrano (ADR 0012).
## 8. Server ## 8. Server
+22 -10
View File
@@ -77,7 +77,7 @@ costMultiplier: f64 }`
| 7 | Save | `name: string` | | 7 | Save | `name: string` |
| 8 | Load | `saveId: string` | | 8 | Load | `saveId: string` |
| 9 | NewGame | `seed: u64`, `sizeKm: i32`, `startYear: i32` (0 = predefinito), `difficultyPreset: string`, `overrides: [(key: string, value: f64)]`, `endlessFlags: u32` | | 9 | NewGame | `seed: u64`, `sizeKm: i32`, `startYear: i32` (0 = predefinito), `difficultyPreset: string`, `overrides: [(key: string, value: f64)]`, `endlessFlags: u32` |
| 10 | RequestDetail | `kind: u8` (1 cartella di manutenzione di un treno, 2 registro officina di un deposito, 3 registro degli impieghi), `target: i32` (id del treno o del deposito; ignorato per 3). Aggiunto in F4 | | 10 | RequestDetail | `kind: u8` (1 cartella di manutenzione di un treno, 2 registro officina di un deposito, 3 registro degli impieghi; dalla F5: 4 scheda di una compagnia, 5 scheda di un'industria, 6 Cronaca), `target: i32` (id del treno, del deposito, della compagnia o dell'industria; ignorato per 3 e 6). Aggiunto in F4 |
### Comandi (`Command.type`, payload in ordine) ### Comandi (`Command.type`, payload in ordine)
@@ -100,7 +100,7 @@ costMultiplier: f64 }`
| 15 | SetReserve | `train: i32`, `reserve: bool` | | 15 | SetReserve | `train: i32`, `reserve: bool` |
| 16 | SetMaintenancePolicy | `scope: u8` (0 compagnia, 1 linea, 2 treno), `target: i32`, `policy: string` | | 16 | SetMaintenancePolicy | `scope: u8` (0 compagnia, 1 linea, 2 treno), `target: i32`, `policy: string` |
| 17 | ScheduleService | `train: i32`, `intervention: string` | | 17 | ScheduleService | `train: i32`, `intervention: string` |
| 18 | OrderParts | `depot: i32`, `quantity: i32` | | 18 | OrderParts | `depot: i32`, `quantity: i32`; blocco 1 (F5): `industry: i32` (ricambi ordinati per un'industria posseduta, oltre la scorta della politica) |
| 19 | TakeLoan | `amount: Money` | | 19 | TakeLoan | `amount: Money` |
| 20 | RepayLoan | `loan: i32`, `amount: Money` | | 20 | RepayLoan | `loan: i32`, `amount: Money` |
| 21 | AcceptAgreement | `agreement: i32` | | 21 | AcceptAgreement | `agreement: i32` |
@@ -116,18 +116,20 @@ costMultiplier: f64 }`
| 31 | SellShares | `company: i32`, `shares: i64`, `minPrice: Money` | | 31 | SellShares | `company: i32`, `shares: i64`, `minPrice: Money` |
| 32 | PayDividend | `perShare: Money` | | 32 | PayDividend | `perShare: Money` |
| 33 | LaunchBid | `target: i32`, `pricePerShare: Money`, `targetShare: f64` | | 33 | LaunchBid | `target: i32`, `pricePerShare: Money`, `targetShare: f64` |
| 34 | RespondBid | `bid: i32`, `accept: bool` | | 34 | RespondBid | `bid: i32`, `accept: bool`; blocco 1 (F5): `defense: u8` (0 nessuna, 1 riacquisto, 2 dividendo straordinario, 3 cavaliere bianco), `knight: i32` |
| 35 | BuyConcession | `region: i32` | | 35 | BuyConcession | `region: i32` |
| 36 | AcceptContract | `contract: i32` | | 36 | AcceptContract | `contract: i32` |
| 37 | FundResearch | `project: string`, `amount: Money` | | 37 | FundResearch | `project: string`, `amount: Money` |
| 38 | DelegateRegion | `region: i32`, `objective: string`, `budget: Money` | | 38 | DelegateRegion | `region: i32`, `objective: string`, `budget: Money` |
| 39 | MergeCompany | `subsidiary: i32` — fusione di una controllata dopo 360 giorni di controllo (aggiunto in F5) |
`LineStop { station: i32, load: bool, unload: bool, waitFull: bool, maxWaitDays: i32 }`. Ogni payload termina con `flags`. `LineStop { station: i32, load: bool, unload: bool, waitFull: bool, maxWaitDays: i32 }`. Ogni payload termina con `flags`.
I codici coincidono con l'enum `CommandType` di Core. Dalla F4 i comandi 15–18 e 21–22 sono attivi I codici coincidono con l'enum `CommandType` di Core. Dalla F4 i comandi 15–18 e 21–22 sono attivi
(`policy`: `economy`, `standard`, `thorough`, oppure `inherit` per togliere l'eccezione di linea o (`policy`: `economy`, `standard`, `thorough`, oppure `inherit` per togliere l'eccezione di linea o
treno; `intervention`: `inspection`, `service`, `overhaul`; `OrderParts` fissa la scorta desiderata treno; `intervention`: `inspection`, `service`, `overhaul`; `OrderParts` fissa la scorta desiderata
del deposito). Fino alla loro fase i comandi 23–38 (tranne 26) rispondono `NotImplemented`. Il server del deposito). Dalla F5 sono attivi anche 25–34 e 39 (industrie, borsa, offerte, fusioni; `LaunchBid` su
imposta l'emittente in base alla sessione. una compagnia fallita è un'offerta all'asta degli attivi: prezzo per azione × azioni). Fino alla loro fase i
comandi 23–24 e 35–38 rispondono `NotImplemented`. Il server imposta l'emittente in base alla sessione.
## 5. Messaggi Server → Client ## 5. Messaggi Server → Client
@@ -147,6 +149,9 @@ imposta l'emittente in base alla sessione.
| 123 | MarketTape | `day: i64`, `shares: [SharePrice]`, `bids: [BidInfo]` | | 123 | MarketTape | `day: i64`, `shares: [SharePrice]`, `bids: [BidInfo]` |
| 124 | MaintenanceCard | `train, day: i64, condition: f32, status: u8, policy: u8, policyOverride: u8, reserve, failure: u8, failedVehicle, failedComponent: string, rescueHours: f32, nextIntervention: string, nextDueDays: f32, plannedIntervention: string, maintenanceDepot, serviceKmPerDay: f32, costThisYear: Money, costLastYear: Money, failuresThisYear, failuresTotal, coveredBy, covering, vehicles: [VehicleCard], history: [MaintenanceRecordInfo]` (su richiesta, F4) | | 124 | MaintenanceCard | `train, day: i64, condition: f32, status: u8, policy: u8, policyOverride: u8, reserve, failure: u8, failedVehicle, failedComponent: string, rescueHours: f32, nextIntervention: string, nextDueDays: f32, plannedIntervention: string, maintenanceDepot, serviceKmPerDay: f32, costThisYear: Money, costLastYear: Money, failuresThisYear, failuresTotal, coveredBy, covering, vehicles: [VehicleCard], history: [MaintenanceRecordInfo]` (su richiesta, F4) |
| 125 | WorkshopRegister | `depot, day: i64, stalls, jobsStaff, staffPresent: f32, workRate: f32, spareParts, partsTarget, partsReserved, jobs: [WorkshopJobInfo], booked: [WorkshopJobInfo]` (su richiesta, F4) | | 125 | WorkshopRegister | `depot, day: i64, stalls, jobsStaff, staffPresent: f32, workRate: f32, spareParts, partsTarget, partsReserved, jobs: [WorkshopJobInfo], booked: [WorkshopJobInfo]` (su richiesta, F4) |
| 126 | CompanyCard | `company, totalShares: i64, treasury: i64, holdings: [HoldingInfo], priceHistory: [f64] (centesimi, mensile), history: [CompanyYearInfo], annualProfit, dividendsYear, debt, marketCap: Money, controlDays: i64, auctionMin, auctionBest: Money, auctionBestBidder, auctionEndDay: i64` (su richiesta, F5) |
| 127 | IndustryCard | `industry, margin, conditionMultiplier, wearPerDay, recoveryPerDay: f32, maintenanceCostPerDay, maintenanceSpentYear: Money, partsTarget, partsPerMonth, partsOrdered, machineryRequired, upgradeCost, valuation, cash: Money, breakdownChancePerYear: f32, stops: [IndustryStopInfo]` (su richiesta, F5) |
| 128 | Chronicle | `gameOver: bool, reason: u8 (1 fallimento, 2 scalata, 3 riscatto scaduto), text, winner, day: i64, company, foundedYear, prestige: i64, history: [CompanyYearInfo], records: [RecordInfo], highlights: [string]` (alla fine della partita e su richiesta, F5) |
| 130 | CommandResult | `seq: u32`, `type: u16`, `error: u16`, `message: string`, `created: [i32]`, `tick: i64` | | 130 | CommandResult | `seq: u32`, `type: u16`, `error: u16`, `message: string`, `created: [i32]`, `tick: i64` |
| 131 | Notification | `EventInfo` | | 131 | Notification | `EventInfo` |
| 132 | Newspaper | `day: i64`, `title: string`, `articles: [(headline: string, body: string)]` | | 132 | Newspaper | `day: i64`, `title: string`, `articles: [(headline: string, body: string)]` |
@@ -155,9 +160,11 @@ imposta l'emittente in base alla sessione.
Record (ognuno chiude con `flags`): Record (ognuno chiude con `flags`):
- `EntityLists`: liste in quest'ordine di `CompanyInfo`, `TownInfo`, `IndustryInfo`, `HubInfo`, `NodeInfo`, `StationInfo`, `DepotInfo`, `LineInfo`, `VehicleInfo`, `TrainInfo`. - `EntityLists`: liste in quest'ordine di `CompanyInfo`, `TownInfo`, `IndustryInfo`, `HubInfo`, `NodeInfo`, `StationInfo`, `DepotInfo`, `LineInfo`, `VehicleInfo`, `TrainInfo`.
- `CompanyInfo { id, name, color, isPlayer, cash: Money, netWorth: Money, rating, tier: u8, bankrupt }`; blocco 1: `maintenancePolicy: u8` (0 economica, 1 standard, 2 accurata) - `CompanyInfo { id, name, color, isPlayer, cash: Money, netWorth: Money, rating, tier: u8, bankrupt }`; blocco 1: `maintenancePolicy: u8` (0 economica, 1 standard, 2 accurata);
blocco 2 (F5): `personality: string, listed, sharePriceCents: f64, sentiment: f32, founderShare: f32, controlledBy: i32, merged, receivership, receivershipUntilDay: i64, annualProfit: Money`
- `TownInfo { id, name, position: Vec2, population: i32, radiusCells: f64, satisfaction: f32, services: i32 }` - `TownInfo { id, name, position: Vec2, population: i32, radiusCells: f64, satisfaction: f32, services: i32 }`
- `IndustryInfo { id, type: string, name, position, footprintCells: i32, level: i32, closed, efficiency: f32, condition: f32, owner: i32 }` - `IndustryInfo { id, type: string, name, position, footprintCells: i32, level: i32, closed, efficiency: f32, condition: f32, owner: i32 }`;
blocco 1 (F5): `budget: u8 (0 nessuno, 1 base, 2 alto), spareParts, machinery, stoppedUntilDay: i64, stopKind: u8 (1 guasto, 2 incidente, 3 revisione, 4 ammodernamento), pendingWork: u8 (1 revisione, 2 ammodernamento), partsShort: bool`
- `HubInfo { id, kind: string, name, position }` - `HubInfo { id, kind: string, name, position }`
- `NodeInfo { id, position, heightM: f64, owner, station, depot, edges: [i32] }` - `NodeInfo { id, position, heightM: f64, owner, station, depot, edges: [i32] }`
- `StationInfo { id, owner, name, node, position, platforms: i32, waitingUnits: i32, industries: [i32], towns: [i32] }` - `StationInfo { id, owner, name, node, position, platforms: i32, waitingUnits: i32, industries: [i32], towns: [i32] }`
@@ -178,7 +185,10 @@ Record (ognuno chiude con `flags`):
- `VehicleCard { vehicle, type: string, odometerKm: f32, ageYears: f32, ageFactor: f32, components: [ComponentCard { component: string, condition: f32, wearPerDay: f32 }] }` - `VehicleCard { vehicle, type: string, odometerKm: f32, ageYears: f32, ageFactor: f32, components: [ComponentCard { component: string, condition: f32, wearPerDay: f32 }] }`
- `MaintenanceRecordInfo { day: i64, intervention: string, cost: Money, depot, parts }` - `MaintenanceRecordInfo { day: i64, intervention: string, cost: Money, depot, parts }`
- `WorkshopJobInfo { train, intervention: string, inStall, started, progress: f32, days: f32, parts, queuedDay: i64 }` - `WorkshopJobInfo { train, intervention: string, inStall, started, progress: f32, days: f32, parts, queuedDay: i64 }`
- `SharePrice { company, price: Money, change: f32, listed }`, `BidInfo { bid, bidder, target, pricePerShare: Money, targetShare: f64, expiresDay: i64 }` - `SharePrice { company, price: Money, change: f32, listed }`; blocco 1 (F5): `priceCents: f64, outstanding: i64, freeFloat: i64, founderShare: f32, controlledBy: i32`
- `BidInfo { bid, bidder, target, pricePerShare: Money, targetShare: f64, expiresDay: i64 }`; blocco 1 (F5): `state: u8, committedShare: f64, defenses: u8 (bit per difesa usata), knight: i32, accepted: bool` (la compagnia della sessione ha aderito)
- `HoldingInfo { holder: i32 (−1 fondatore, −2 mercato, altrimenti compagnia), shares: i64 }`, `CompanyYearInfo { year, netWorth, cash, revenue, profit: Money, tier: u8, trains, trackKm: f32, sharePrice: Money }`
- `IndustryStopInfo { day: i64, days, kind: u8 }`, `RecordInfo { title, value: string, year }`
- `SaveInfo { saveId, name, gameDate, sizeBytes: i64, savedUnixMs: i64, autosave }` - `SaveInfo { saveId, name, gameDate, sizeBytes: i64, savedUnixMs: i64, autosave }`
## 6. Flusso e interest management ## 6. Flusso e interest management
@@ -190,13 +200,15 @@ Record (ognuno chiude con `flags`):
- `TrainMotion` ogni 100 ms per i treni in moto con la testa nel viewport (più un chunk), una volta - `TrainMotion` ogni 100 ms per i treni in moto con la testa nel viewport (più un chunk), una volta
per quelli fermi: al massimo 10 aggiornamenti al secondo per treno. Il client avanza la testa a per quelli fermi: al massimo 10 aggiornamenti al secondo per treno. Il client avanza la testa a
velocità costante tra un moto e l'altro (fattore 60: un tick = 3 s di orologio dei treni). velocità costante tra un moto e l'altro (fattore 60: un tick = 3 s di orologio dei treni).
- `DailyDigest` a ogni giorno; `EmploymentReport` a ogni mese; `Notification` per gli eventi non - `DailyDigest` e `MarketTape` (listino delle compagnie attive e offerte in corso) a ogni giorno; `EmploymentReport` a ogni mese; `Notification` per gli eventi non
informativi della compagnia della sessione; `MaintenanceAlert` quando un treno scende sotto le soglie informativi della compagnia della sessione; `MaintenanceAlert` quando un treno scende sotto le soglie
d'avviso (40) o critica (30) e quando un'officina resta senza ricambi. d'avviso (40) o critica (30) e quando un'officina resta senza ricambi.
- Dettagli su richiesta (F4): `MaintenanceCard`, `WorkshopRegister` ed `EmploymentReport` rispondono a - Dettagli su richiesta (F4): `MaintenanceCard`, `WorkshopRegister` ed `EmploymentReport` rispondono a
`RequestDetail` per entità della compagnia della sessione (le richieste per entità altrui o `RequestDetail` per entità della compagnia della sessione (le richieste per entità altrui o
inesistenti non hanno risposta). Il client li richiede mentre il pannello è aperto (una volta al inesistenti non hanno risposta). Il client li richiede mentre il pannello è aperto (una volta al
secondo): i componenti di tutti i veicoli non viaggiano nei delta delle entità. secondo): i componenti di tutti i veicoli non viaggiano nei delta delle entità. Dalla F5 anche
`CompanyCard` (qualunque compagnia), `IndustryCard` (qualunque industria aperta) e `Chronicle`; la
Cronaca arriva da sola, una volta per sessione, quando la partita del giocatore finisce.
- Backpressure: i moti si scartano oltre 256 KB in coda; oltre 64 MB di messaggi affidabili la - Backpressure: i moti si scartano oltre 256 KB in coda; oltre 64 MB di messaggi affidabili la
sessione si chiude (il client può riprenderla). sessione si chiude (il client può riprenderla).
- Obiettivo di banda in regime: < 100 KB/s per client. - Obiettivo di banda in regime: < 100 KB/s per client.
+22 -4
View File
@@ -68,13 +68,27 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
- Accettazione F4 (rete di Valdoria con officina a Valdoria e due treni per linea): senza la linea dei ricambi la flotta scende sotto 40 al giorno 697 con 12 guasti (19,5 per milione di km di servizio); con la linea dal Porto di Levante resta sopra 73 con 3 guasti (3,2 per milione di km). - Accettazione F4 (rete di Valdoria con officina a Valdoria e due treni per linea): senza la linea dei ricambi la flotta scende sotto 40 al giorno 697 con 12 guasti (19,5 per milione di km di servizio); con la linea dal Porto di Levante resta sopra 73 con 3 guasti (3,2 per milione di km).
- 102 test. - 102 test.
### F5 — Industrie, IA, borsa e scalate
- Manutenzione degli impianti (sezione 11, ADR 0011): usura giornaliera con efficienza, intensità e difficoltà, recupero dal budget (dimezzato senza ricambi), fermi sotto 40 con storico e insoddisfazione della città vicina, incidenti gravi sotto 10 per trasformazione e manifattura, revisione e ammodernamento programmabili; ricambi e macchinari come domanda esplicita dell'industria (in treno, dal trasporto locale e per trasbordo nel bacino di una stazione servita); politica dei privati.
- Industrie possedute: `BuyIndustry` dal livello 3 con prezzo chiesto (attivi, condizione, utile, cassa), cassa di riserva, surplus e perdite al proprietario (voce «Industrie»), `SetIndustryPolicy`, `OverhaulIndustry`, `UpgradeIndustry` e `OrderParts` per l'industria.
- Livelli (`Tiers`): patrimonio netto, città collegate sopra una soglia di abitanti e rating, soglie ritarate in `tiers.json`; ritaratura economica di costi di costruzione, manutenzione e tariffe misurata con le IA (ADR 0011 §7).
- Borsa e società (sezione 12.2–12.3, ADR 0012): libro dei soci, prezzo da patrimonio e utili con sentiment ciclico, ordini con spread e limite, quotazione dal livello 4, aumento di capitale, riacquisto, dividendi ordinari e straordinari, controllo oltre il 50 % con quota dell'utile al controllante, fusione (`MergeCompany`, comando 39), offerte pubbliche condizionate con adesione del flottante, risposte delle compagnie azioniste e tre difese, esiti per difficoltà (amministrazione controllata, fine partita), aste degli attivi delle IA fallite, nuovi concorrenti quando una compagnia domina i ricavi, `GameOver` con osservatore e Cronaca finale con prestigio.
- Agenti IA (sezione 12.1, ADR 0013): pianificazione mensile con candidati (merci e pendolari), regioni collegabili, Dijkstra a 8 direzioni con pendenze, fiumi e ostacoli, semplificazione che non taglia ostacoli, `TrackPreview`, ROI con soglia della personalità; esecuzione con gli stessi comandi del giocatore (stazioni, binario, deposito, linea, treni), treni aggiuntivi, linee dei ricambi, rimedio agli stalli di capacità, liquidità, rimborso dei prestiti, borsa (partecipazioni, offerte, adesioni, difese, fusioni); tre personalità (Espansiva, Prudente, Predatoria). `viaferrea-tools simulate --trace-ai` con riepilogo per compagnia.
- Salvataggio: corpo versione 3 con sezione societaria (libro dei soci, storici, offerte, aste, stato degli agenti, fine partita) nell'hash; migrazione dei salvataggi F4.
- Protocollo: prezzi e offerte nei record (blocco 1), `CompanyCard` (126), `IndustryCard` (127), `Chronicle` (128), `RequestDetail` per compagnia, industria e cronaca, `MergeCompany` e campi nuovi di `OrderParts` e `RespondBid` (blocco 1 dei comandi).
- Server: listino quotidiano, schede di compagnia e industria su richiesta, Cronaca una volta per sessione a fine partita.
- Client: pannelli «Borsa» (listino, offerte, schede delle compagnie con soci e storico, comandi di compravendita, quotazione, offerte e difese) e scheda del proprietario dell'industria (condizione, fermi, budget, revisione, ammodernamento, acquisto), Cronaca finale; schermate in `docs/screenshots/f5-*.jpg`.
- Test di 14.5: manutenzione delle industrie (usura, fermi, ricambi, revisione, acquisto), borsa (prezzo, quotazione, controllo e fusione, scalata riuscita, esiti per difficoltà, asta dell'IA fallita, salvataggio dello stato societario), IA (comandi rifiutati ≤ 5 %, IA con capitale ×2 sopra il giocatore passivo in 10 anni, determinismo con le IA anche passando da un salvataggio).
- Accettazione F5 (`OnMagnateAnAiReachesTierThreeIn15Years`, seme 7, 128 km, «Magnate», giocatore passivo): la Società Ferroviaria Adriatica arriva al livello 3 nel 1863 (13 anni) con ₤ 2,7 milioni di patrimonio, rating BBB e 3 città sopra 1.000 abitanti collegate.
- 120 test.
## In corso ## In corso
- Nessun lavoro a metà: F4 chiusa. - Nessun lavoro a metà: F5 chiusa.
## Prossimo passo ## Prossimo passo
- F5: manutenzione delle industrie (sezione 11: condizione degli impianti, fermi, ammodernamenti, acquisto delle industrie con il pannello del proprietario), poi agenti IA, borsa, quotazione e scalate (sezione 12) con i test di 14.5 e il determinismo con le IA. - F6: hub e commercio (`BuyGoods`/`SellGoods`), eventi, storico dei prezzi, finanza completa, livelli e sblocchi nell'interfaccia, ere e obsolescenza, pannelli 06–08, tooltip «perché», tutorial, audio, bilanciamento con i bot su `simulate`, esportazione Windows con il server.
## Limiti noti ## Limiti noti
@@ -86,10 +100,12 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
- In F3 tutte le sessioni guidano la compagnia del giocatore (ADR 0009). - In F3 tutte le sessioni guidano la compagnia del giocatore (ADR 0009).
- Il bilanciamento economico è provvisorio (F6): nello scenario l'acciaieria cresce di livello ogni due trimestri finché la linea operai non satura; il prezzo del minerale sale oltre 1,5 volte il base e il margine dei trasformatori diventa negativo quando la domanda supera l'offerta delle miniere. - Il bilanciamento economico è provvisorio (F6): nello scenario l'acciaieria cresce di livello ogni due trimestri finché la linea operai non satura; il prezzo del minerale sale oltre 1,5 volte il base e il margine dei trasformatori diventa negativo quando la domanda supera l'offerta delle miniere.
- La lunghezza dei marciapiedi non è modellata; i segnali sono solo a blocco fisso (niente segnali di percorso). - La lunghezza dei marciapiedi non è modellata; i segnali sono solo a blocco fisso (niente segnali di percorso).
- Comandi ancora `NotImplemented`: commercio, industrie, borsa, concessioni, contratti, ricerca, regioni (fasi F5–F7). - Comandi ancora `NotImplemented`: commercio, concessioni, contratti, ricerca, regioni (fasi F6–F7).
- Manutenzione (ADR 0010): il viaggio verso l'officina si stima in linea d'aria; un treno rimorchiato completa il tratto in corso prima di dirigersi all'officina; con un solo treno su una linea di pendolari e un deposito senza personale la copertura cala durante gli interventi (servono riserve e personale); la mappa dei flussi dei pendolari (frecce blu, opzionale nella guida) non è ancora disegnata. - Manutenzione (ADR 0010): il viaggio verso l'officina si stima in linea d'aria; un treno rimorchiato completa il tratto in corso prima di dirigersi all'officina; con un solo treno su una linea di pendolari e un deposito senza personale la copertura cala durante gli interventi (servono riserve e personale); la mappa dei flussi dei pendolari (frecce blu, opzionale nella guida) non è ancora disegnata.
- Una rete a binario semplice con pochi binari di stazione può ancora bloccarsi se tutti i binari alle due estremità sono occupati da treni che devono incrociarsi (stallo di capacità segnalato al giocatore come «possibile stallo»): la rete dell'accettazione F4 è dimensionata di conseguenza. - Una rete a binario semplice con pochi binari di stazione può ancora bloccarsi se tutti i binari alle due estremità sono occupati da treni che devono incrociarsi (stallo di capacità segnalato al giocatore come «possibile stallo»): la rete dell'accettazione F4 è dimensionata di conseguenza.
- La manutenzione degli impianti (sezione 11) arriva in F5: fino ad allora la condizione delle industrie resta 100. - IA (ADR 0013): su mappe da 128 km in «Magnate» di solito una o due IA crescono (livello 2–3 in 15 anni) mentre le altre restano piccole o falliscono quando la regione non offre candidati con ROI sopra soglia; nel 1850 i grandi fiumi dividono la mappa in regioni fino ai ponti in ferro. Le IA non comprano ancora industrie se non dal livello 3 e non usano il commercio (F6).
- Borsa (ADR 0012): per le compagnie piccole il prezzo per azione è di pochi centesimi e il premio di un'offerta ha la granularità di un centesimo; antitrust e finanziamenti statali arrivano in F7.
- Prezzi, soglie dei livelli e taratura economica restano provvisori fino al bilanciamento della F6.
## Misure di prestazione ## Misure di prestazione
@@ -112,3 +128,5 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
| Accettazione F4 (due corse di 3 anni, 6–7 treni) | 3,7 s | F4 | | Accettazione F4 (due corse di 3 anni, 6–7 treni) | 3,7 s | F4 |
| Suite di test (102, parallela su 4 core) | ~15 s | F4 | | Suite di test (102, parallela su 4 core) | ~15 s | F4 |
| Pilota automatico del client con i pannelli F4 | ~90 s, 12 schermate | F4 | | Pilota automatico del client con i pannelli F4 | ~90 s, 12 schermate | F4 |
| Suite di test (120, parallela su 4 core, con i test lenti delle IA) | ~137 s (accettazione F5 70 s) | F5 |
| `simulate --years 15` su 128 km «Magnate» con 3 IA | ~60 s | F5 |
@@ -0,0 +1,62 @@
# ADR 0011 — Manutenzione delle industrie, industrie possedute, livelli e ritaratura economica (F5)
Stato: accettato (F5).
## Contesto
La sezione 11 fissa usura, moltiplicatore di efficienza, rischio di fermo, budget, revisione e
ammodernamento, ma non dice come i ricambi e i macchinari arrivano alle industrie, come si paga
un'industria, come si riparte la cassa tra industria e proprietario, quando un livello della
compagnia si raggiunge né quali sono le soglie. Inoltre, con i costi di F1–F2, una linea nuova non
ripagava il capitale: le IA della F5 (che usano gli stessi comandi del giocatore) fallivano tutte.
## Decisione
1. **Usura e recupero** (`IndustryMaintenanceSystem`, dopo `Industries`): ogni giorno
`c −= 0,06 × efficienza × wearIntensity × usura della difficoltà` e `c += recupero del budget`
(dimezzato se l'ultimo consumo mensile di ricambi non era coperto). L'efficienza del giorno è
l'utilizzo. Il costo del budget è la quota dei ricavi medi giornalieri (EMA a 90 giorni) e
entra nei costi dell'industria (margine).
2. **Fermi**: sotto 40 il rischio giornaliero è `0,001·exp((40 − c)/8)`; il fermo dura 5–20 giorni,
è annotato nello storico (ultimi 12) e toglie 2 punti di soddisfazione a ogni categoria della città
più vicina entro 12 km. Sotto 10, per le industrie di trasformazione e manifattura (non primarie),
è un incidente grave: 60 giorni e −0,2 % di abitanti alla città vicina. Durante un fermo l'industria
non produce né consuma e non si usura; i salari si pagano comunque.
3. **Ricambi e macchinari** sono una domanda esplicita dell'industria: scorta desiderata = consumo
mensile della politica × 3 mesi + quanto ordinato con «Ordina ricambi» (`OrderParts` con il campo
`Industry`, blocco 1 del protocollo); macchinari = quelli richiesti dal lavoro programmato. Arrivano:
in treno (le industrie sono consumatori di questi beni come gli input), dal trasporto locale di
produttori e hub vicini (3 km) e, novità, per **trasbordo nel bacino**: una stazione servita da una
linea passa ricambi e macchinari dai produttori e dagli hub del suo bacino alle officine e alle
industrie dello stesso bacino, senza treno. Le industrie partono con 6 mesi di ricambi.
4. **Revisione e ammodernamento** si programmano (comando o privati) e partono quando ci sono i
macchinari (e, per la revisione, il personale ≥ 0,8); l'ammodernamento si paga all'inizio
(`upgradeCost × livello`, dal proprietario). I privati: budget dal margine (> 15 % Alto, < 0 nessuno),
revisione sotto 35 se la cassa paga i macchinari, ammodernamento dopo due anni di margine > 15 % con
ricambi in scorta.
5. **Acquisto** (`BuyIndustry`, dal livello 3): il prezzo chiesto è
`upgradeCost × livello × 0,6 × (0,5 + 0,5·c/100) + 5 × utile annuo positivo + cassa dell'impresa`;
un'offerta più bassa è rifiutata. L'industria tiene una cassa di riserva (20.000 lire): ogni mese il
surplus va al proprietario e le perdite sono coperte da lui (voce «Industrie» del conto economico,
che entra nell'utile operativo).
6. **Livelli** (`Tiers`, ogni mese dopo il rating): si sale quando patrimonio netto, città collegate
sopra una popolazione (nel bacino di una stazione fermata di una linea con treni) e rating
raggiungono il livello successivo; non si scende. Soglie in `tiers.json` ritarate perché una
compagnia competente arrivi al livello 3 in 10–15 anni: 400.000, 1.000.000, 4.000.000 e 15.000.000
lire; 2, 3, 6 e 10 città sopra 800, 1.000, 2.000 e 3.500 abitanti; BB, BBB, A, AA. Misura con le IA in
«Magnate» su mappe da 128 km: la migliore arriva a 1–2,7 milioni in 15 anni collegando 2–3 città.
7. **Ritaratura economica** (misurata con le IA su `simulate`, rifinitura in F6): binario 7 lire al metro
(era 12), stazione 12.000 + 4.000 lire per binario (era 40.000 + 15.000), depositi 20/40/80 mila lire;
manutenzione ordinaria del binario 0,6 lire al km al giorno (era 4); tariffa merci base 2,8 (era 1,5) e
passeggeri 0,6 (era 0,45) centesimi; costi degli interventi di manutenzione dei treni ridotti
(ispezione 0,1 %, tagliando 1,2 %, revisione 12 % del prezzo); ricambi a 150 lire la cassa (erano 300);
scorta iniziale dei depositi 25 casse.
## Conseguenze
- Chi trasporta ricambi e macchinari tiene in vita il territorio: un'industria lontana da produttori e
hub e non servita decade lentamente; le reti vicine a un porto o a una fabbrica di macchinari partono
avvantaggiate.
- L'accettazione F4 resta valida con la nuova taratura (senza linea dei ricambi la flotta scende sotto 40
entro 3 anni, con la linea resta sopra 60).
- I prezzi e le soglie restano provvisori fino al bilanciamento della F6.
@@ -0,0 +1,64 @@
# ADR 0012 — Borsa, controllo, scalate, amministrazione controllata e Cronaca finale (F5)
Stato: accettato (F5).
## Contesto
La sezione 12.2–12.3 fissa azioni, formula del prezzo, quotazione, dividendi, controllo, fusione,
offerte con le difese ed esiti per difficoltà, ma non dice chi possiede le azioni di una compagnia
privata, come aderisce il mercato a un'offerta, come si riscatta il 51 %, chi compra un'IA fallita né
come la fusione e la fine partita toccano il resto del mondo.
## Decisione
1. **Libro dei soci** (`ShareRegister`): 1.000.000 di azioni divise tra fondatore (il giocatore o il
proprietario privato di un'IA), mercato (flottante), azioni proprie (non votano) e altre compagnie.
Il giocatore parte con il 100 % (il 60 % in «Ferro e sangue», quotato); le IA sono quotate dall'inizio
con il 30 % di flottante.
2. **Prezzo**: `max(patrimonio netto, 8 × utile dei 12 mesi chiusi) / azioni in circolazione × sentiment`;
il sentiment (0,8–1,3) segue con media a 30 giorni `1 + 0,4·crescita degli utili + 1·ciclo mondiale
(A·sin(2πt/T)) + 4·rendimento dei dividendi + spinta del dividendo straordinario`. Le partecipazioni
in altre compagnie entrano nel patrimonio netto al prezzo di mercato. Si scambia al prezzo ± metà
dello spread (1 %), al massimo il 5 % del capitale per ordine.
3. **Quotazione** (livello 4): il fondatore colloca fino al 40 % e il ricavato entra in cassa; chi è già
quotato può collocare altro capitale fino a un flottante del 60 % (le IA lo fanno quando la cassa
scarseggia). **Riacquisto** = comprare le proprie azioni (per conto del fondatore).
4. **Controllo**: chi supera il 50 % delle azioni in circolazione controlla; ogni mese la controllata
versa la quota dell'utile del mese al controllante (voce «Controllate», un dividendo per la
controllata); dopo 360 giorni il controllante può fonderla con `MergeCompany` (comando 39, aggiunto
in F5): liquida le minoranze al prezzo di mercato e assorbe rete, treni, linee, industrie, debiti e
cassa; la fusa resta nel mondo come compagnia cessata.
5. **Offerte pubbliche** (`LaunchBid`, livello 5 per il giocatore; le IA con cassa): premio 20–50 % sul
prezzo, durata 90 giorni, quota obiettivo. Ogni giorno aderisce una quota del flottante libero
proporzionale al premio (4 % al giorno con il premio minimo, fino all'8 %); le compagnie azioniste
aderiscono con `RespondBid` e il fondatore privato di un'IA solo con premi sopra il 40 %. L'offerta si
chiude quando le adesioni raggiungono la quota o alla scadenza: senza la quota fallisce e nessuno
vende (offerta condizionata). Difese del bersaglio (`RespondBid` con il campo `Defense`): riacquisto
del flottante con la cassa, dividendo straordinario del 25 % della cassa (rende il titolo più caro),
cavaliere bianco (un'altra compagnia compra il flottante al prezzo dell'offerta + 5 %).
6. **Il giocatore comprato** (borsa o insolvenza): «Apprendista» mai (nessuna IA supera il 50 % e le
offerte sul giocatore sono rifiutate); «Imprenditore» e «Magnate» amministrazione controllata per 3 o
1 anno: dividendo obbligatorio del 50 % dell'utile trimestrale, niente prestiti; si esce riportando il
fondatore al 51 % (riacquisto dal mercato e poi dal controllante con un premio del 25 %); alla scadenza
la partita finisce. «Ferro e sangue»: fine immediata. Insolvenza: i creditori vendono la compagnia
all'IA più ricca che ne salda i debiti (poi gli stessi esiti); senza compratori la partita finisce.
7. **IA fallite**: gli attivi vanno all'asta per 30 giorni con base al 40 % del valore di libro; si offre
con `LaunchBid` sul fallito (prezzo per azione × 1.000.000). Il vincitore paga i creditori e assorbe
gli attivi; senza offerte i treni si rottamano, le linee chiudono e binari e stazioni restano
abbandonati.
8. **Nuovi concorrenti** (12.1): a inizio anno, se una compagnia ha più del 60 % dei ricavi dei vettori,
entra una nuova IA (al massimo una ogni 3 anni, fino a 8 compagnie attive). La F7 aggiunge antitrust e
finanziamenti statali.
9. **Fine partita e Cronaca**: `World.GameOver` registra motivo, testo e vincitore; da quel momento i
comandi del giocatore sono rifiutati e il mondo prosegue (osservatore). La Cronaca finale (messaggio
128, anche su richiesta come cronaca provvisoria) riporta la storia annuale, i primati, i fatti
salienti e un prestigio semplice (100 per livello massimo + 1 per 10.000 lire di patrimonio massimo
+ 5 per anno di attività), che la F7 estende.
## Conseguenze
- Prezzi in centesimi frazionari: per una compagnia piccola un'azione vale pochi centesimi e il premio
di un'offerta ha la granularità di un centesimo (le IA non offrono quando l'arrotondamento esce dai
limiti del premio).
- Il salvataggio passa alla versione 3 (sezione societaria in coda allo stato dinamico, nell'hash); i
salvataggi precedenti ricevono un libro dei soci come in una partita nuova.
+72
View File
@@ -0,0 +1,72 @@
# ADR 0013 — Agenti IA delle compagnie concorrenti (F5)
Stato: accettato (F5).
## Contesto
La sezione 12.1 chiede agenti che usino solo i comandi del protocollo, pianifichino ogni mese con
candidati, percorso di Dijkstra sulle celle, `TrackPlanner` e ROI, con personalità diverse e vincoli
identici al giocatore. Restano aperti: come l'IA riceve gli esiti dei comandi, quali informazioni legge,
come sceglie stazioni e depositi, come tiene in vita la rete (ricambi, stalli) e come si evita che più IA
facciano la stessa linea.
## Decisione
1. **Comandi**: l'agente costruisce i record di `Commands` e li esegue con `CommandProcessor.Execute`
dal sistema `AiAgents`, con le stesse validazioni e gli stessi costi dei giocatori, ricevendo subito
l'esito (gli id creati). Nessun comando in volo tra un tick e l'altro, quindi niente da salvare oltre
allo stato dell'agente; i comandi delle IA non vanno nel registro del replay (si rigiocano da soli).
Conta emessi e rifiutati: il test di 14.5 chiede rifiutati ≤ 5 %, in pratica sono quasi zero perché
l'agente verifica prima siti e tracciati con le stesse funzioni (`TrackPreview` del comando).
2. **Informazioni**: solo ciò che vede anche il giocatore (terreno, industrie, città, hub, prezzi, rete e
treni di tutti), con gli stimatori di `Estimators` (ricavo per unità e per passeggero, durata del giro,
costi) che serviranno anche ai tooltip «perché».
3. **Pianificazione mensile** (giorno del mese diverso per IA): finanza (rimborso dei prestiti più cari
quando la cassa supera 12 mesi di costi, aumento di capitale in borsa quando scarseggia), un treno in più
sulle linee con la merce in attesa (fino a 2 per linea e nei limiti dei binari di stazione), borsa,
industrie (dal livello 3, una all'anno tra quelle servite e in utile), linea dei ricambi se un deposito
non ne riceve, altrimenti al più un nuovo progetto.
4. **Candidati**: merci da un produttore a un consumatore (industria, città con domanda, hub
d'esportazione) tra 4 e 40 km in linea d'aria, non già serviti da altre compagnie (anche con stazioni
in costruzione; la Predatoria punta invece ai produttori serviti dal giocatore); pendolari da città con
lavoratori liberi verso industrie che la compagnia serve già con le merci, entro il tempo massimo di
viaggio. Punteggio di massima = ricavo annuo stimato / costo in linea d'aria, ritoccato: ×1,3 se un capo
è una stazione propria, ×0,5 se una rete nuova non ha fonti di ricambi vicine, ×1,8 per le città quando
il livello successivo ne chiede di più. Si valutano i 6 migliori.
5. **Valutazione**: siti delle stazioni (stazione propria con il bacino giusto e binari liberi, altrimenti
punti liberi a 300–1.250 m verso l'altro capo, lontani dai binari altrui); percorso con Dijkstra a 8
direzioni in un riquadro attorno ai capi (costo = modificatore di costo del terreno, ponte per i fiumi
attraversabili con i ponti dell'epoca, penalità di pendenza e di celle troppo ripide; città, industrie,
mare, fiumi troppo larghi e binari propri esclusi), semplificazione di Douglas–Peucker che non taglia
ostacoli e rimozione dei vertici i cui raccordi non stanno al raggio minimo; piano con
`TrackPreview` (se non valido si riprova con tolleranza dimezzata). Prima della ricerca si controlla
che i capi siano nella stessa regione collegabile (componenti connesse ricalcolate quando cambiano i
ponti dell'epoca). Ricavi: merci = min(produzione, domanda) × ricavo per unità, entro la capacità dei
treni; pendolari = posti al giorno dei treni × copertura attesa (0,6). Costi annui: treni con
manutenzione, binari di stazione, deposito, manutenzione del binario. ROI = (ricavi − costi) / capitale
(come nella guida: gli interessi sono una scelta di finanziamento), confrontato con la soglia della
personalità; per i progetti che collegano città, quando il livello successivo ne chiede di più, la
soglia si dimezza.
6. **Esecuzione**: stazioni (la stazione del deposito ha 6 binari: diventa il nodo della rete), binario,
deposito piccolo con raccordo (dalla parte della fonte di ricambi), poi, a cantieri finiti, linea, treni
(locomotiva non elettrica più recente, carri adatti al bene o carrozze della classe) e assegnazione.
Prestiti entro la quota del fido della personalità (tutto il fido per comprare il primo treno di una
linea già costruita).
7. **Tenere in vita la rete**: una rete nuova lontana da hub e fabbriche di macchinari mette in conto la
linea dei ricambi (se nessuna è possibile, il candidato si scarta); ogni deposito con treni in servizio
riceve una linea dei ricambi dalla fonte più vicina; una stazione condivisa regge al massimo binari − 1
treni (stallo di capacità); se almeno due treni aspettano via libera da più dei giorni d'avviso e
nessuno è guasto in linea, quello fermo da più tempo diventa riserva (una volta ogni 60 giorni).
8. **Personalità** da `ai.json`: Espansiva (ROI 8 %, prestiti fino all'80 % del fido), Prudente (15 %,
30 %), Predatoria (10 %, 60 %, compra quote dei concorrenti quotati e in utile fino al 30 %, poi lancia
un'offerta al 30 % di premio). Tutte rispondono alle offerte sulle azioni che possiedono (aderiscono con
un premio ≥ 15 %) e si difendono da bersaglio (riacquisto, cavaliere bianco non predatorio, dividendo
straordinario), fondono le controllate dopo un anno.
## Conseguenze
- Il comportamento è riproducibile: stesso seme e stessi comandi del giocatore danno lo stesso hash anche
con le IA (test di determinismo di 14.5), e lo stato dell'agente entra nel salvataggio.
- Nel 1850 i grandi fiumi (oltre la campata dei ponti in legno) dividono la mappa in regioni: le IA
crescono nella propria regione finché i ponti in ferro (1870) aprono nuovi collegamenti.
- La qualità delle IA dipende dal bilanciamento economico: la F6 lo rifinisce con bot su `simulate`.
@@ -46,6 +46,7 @@ public enum CommandType : ushort
AcceptContract = 36, AcceptContract = 36,
FundResearch = 37, FundResearch = 37,
DelegateRegion = 38, DelegateRegion = 38,
MergeCompany = 39,
} }
/// <summary>Codici di errore stabili degli esiti dei comandi.</summary> /// <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; 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 sealed record OrderPartsCommand(DepotId Depot, int Quantity) : GameCommand
{ {
public override CommandType Type => CommandType.OrderParts; 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> /// <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; 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 sealed record RespondBidCommand(BidId Bid, bool Accept) : GameCommand
{ {
public override CommandType Type => CommandType.RespondBid; 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> /// <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; } [JsonPropertyName("$schema")] public string? Schema { get; init; }
public required int Version { get; init; } public required int Version { get; init; }
public required AiPlanningParams Planning { get; init; } public required AiPlanningParams Planning { get; init; }
public required AiMarketParams Market { get; init; }
public required List<AiPersonalityDef> Personalities { get; init; } public required List<AiPersonalityDef> Personalities { get; init; }
public required List<string> CompanyNames { get; init; } public required List<string> CompanyNames { get; init; }
public required List<string> Colors { 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 CandidateMinDistanceKm { get; init; }
public required double PathSlopePenalty { get; init; } public required double PathSlopePenalty { get; init; }
public required double PathWaterPenalty { 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 TrainsPerLine { get; init; }
public required int WagonsPerTrain { get; init; } public required int WagonsPerTrain { get; init; }
public required double CashReserveMonths { get; init; } public required double CashReserveMonths { get; init; }
public required double RevenueHorizonYears { get; init; } public required double RevenueHorizonYears { get; init; }
public required double MaxRejectedShare { 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 public sealed class AiPersonalityDef
+65
View File
@@ -377,6 +377,41 @@ public sealed class StockMarketBalance
public required int BidDurationDays { get; init; } public required int BidDurationDays { get; init; }
public required double RansomShare { get; init; } public required double RansomShare { get; init; }
public required double ReceivershipDividend { 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 public sealed class IndustryMaintenanceBalance
@@ -404,6 +439,36 @@ public sealed class IndustryMaintenanceBalance
public required int NpcUpgradeYears { get; init; } public required int NpcUpgradeYears { get; init; }
public required double NpcHighMargin { get; init; } public required double NpcHighMargin { get; init; }
public required double NpcOverhaulBelow { 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 public sealed class IndustryBudgetParams
+82 -5
View File
@@ -25,6 +25,10 @@ public enum LedgerEntry : byte
Contracts = 16, Contracts = 16,
Penalties = 17, Penalties = 17,
Other = 18, 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> /// <summary>Prestito con rata costante (ammortamento alla francese).</summary>
@@ -41,7 +45,7 @@ public sealed class Loan
/// <summary>Compagnia ferroviaria (giocatore o IA).</summary> /// <summary>Compagnia ferroviaria (giocatore o IA).</summary>
public sealed class Company public sealed class Company
{ {
public const int EntryCount = 19; public const int EntryCount = 21;
public required CompanyId Id { get; init; } public required CompanyId Id { get; init; }
public required string Name { get; set; } 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> /// <summary>Valore di mercato delle azioni di altre compagnie possedute (aggiornato ogni giorno dalla borsa).</summary>
public Money NetWorth => Cash + AssetBookValue - Debt; 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> /// <summary>Utile operativo dell'anno indicato (ricavi meno costi d'esercizio, esclusi prestiti e investimenti).</summary>
public static long OperatingProfit(long[] entries) public static long OperatingProfit(long[] entries)
{ {
long revenue = entries[(int)LedgerEntry.FreightRevenue] + entries[(int)LedgerEntry.PassengerRevenue] 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] long costs = entries[(int)LedgerEntry.RunningCosts] + entries[(int)LedgerEntry.TrackMaintenance]
+ entries[(int)LedgerEntry.FleetMaintenance] + entries[(int)LedgerEntry.Wages] + entries[(int)LedgerEntry.FleetMaintenance] + entries[(int)LedgerEntry.Wages]
+ entries[(int)LedgerEntry.Interest] + entries[(int)LedgerEntry.Penalties]; + entries[(int)LedgerEntry.Interest] + entries[(int)LedgerEntry.Penalties];
@@ -102,5 +178,6 @@ public sealed class Company
public static long Revenue(long[] entries) => public static long Revenue(long[] entries) =>
entries[(int)LedgerEntry.FreightRevenue] + entries[(int)LedgerEntry.PassengerRevenue] 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 AgreementId Id { get; init; }
public required IndustryId Industry { 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 int SeatsPerDay { get; init; }
public required Money MonthlyFee { get; init; } public required Money MonthlyFee { get; init; }
public required long ProposedDay { 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> /// <summary>Budget di manutenzione degli impianti scelto dal proprietario (guida, sezione 11).</summary>
public enum IndustryBudget : byte { None = 0, Base = 1, High = 2 } 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> /// <summary>
/// Industria: produce secondo la ricetta del suo tipo, con efficienza /// Industria: produce secondo la ricetta del suo tipo, con efficienza
/// e = min(copertura input, lavoratori, personale) × fattore di profitto × condizione impianti. /// 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; 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> /// <summary>Scorte degli input, allineate a Def.Recipe.Inputs.</summary>
public int[] InputStock { get; init; } = []; 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 public static class WorldSerializer
{ {
/// <summary>Versione del corpo del salvataggio (migrazioni in <see cref="Read"/>).</summary> /// <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> /// <summary>Scrive l'intero mondo (impostazioni, terreno, stato dinamico, eventi).</summary>
public static void Write(World w, SaveWriter s) public static void Write(World w, SaveWriter s)
@@ -235,6 +235,7 @@ public static class WorldSerializer
RailSerializer.Write(w, s); RailSerializer.Write(w, s);
MaintenanceSerializer.Write(w, s); MaintenanceSerializer.Write(w, s);
CorporateSerializer.Write(w, s);
} }
private static void WriteRecipeStock(List<RecipeItemDef> items, int[] stock, SaveWriter 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 // versione 2 (F4): manutenzione, officine, convenzioni; la versione 1 si migra
if (version >= 2) MaintenanceSerializer.Read(w, r); if (version >= 2) MaintenanceSerializer.Read(w, r);
else MaintenanceSerializer.Migrate(w); 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) 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 EdgeId Id { get; init; }
public required NodeId A { get; set; } public required NodeId A { get; set; }
public required NodeId B { 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 int TrackClass { get; set; }
public required bool DoubleTrack { get; set; } public required bool DoubleTrack { get; set; }
public required bool Electrified { get; set; } public required bool Electrified { get; set; }
@@ -196,7 +196,7 @@ public sealed class TrackEdge
public sealed class Station public sealed class Station
{ {
public required StationId Id { get; init; } 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 string Name { get; set; }
public required NodeId Node { get; init; } public required NodeId Node { get; init; }
public required Vec2 Position { get; init; } public required Vec2 Position { get; init; }
@@ -258,7 +258,7 @@ public sealed class WorkshopJob
public sealed class Depot : IWorkplace public sealed class Depot : IWorkplace
{ {
public required DepotId Id { get; init; } 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 string Name { get; set; }
public required NodeId Node { get; init; } public required NodeId Node { get; init; }
public required Vec2 Position { 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 sealed class ConstructionProject
{ {
public required int Id { get; init; } 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 ProjectKind Kind { get; init; }
public required List<EdgeId> Edges { get; init; } public required List<EdgeId> Edges { get; init; }
public required double TotalDays { get; init; } public required double TotalDays { get; init; }
+5 -2
View File
@@ -207,8 +207,11 @@ public static class TrackPlanner
string reason = !req.AllowTunnels string reason = !req.AllowTunnels
? "servirebbe una galleria o un altro tracciato" ? "servirebbe una galleria o un altro tracciato"
: "abbassa o alza il tracciato o cambia percorso"; : "abbassa o alza il tracciato o cambia percorso";
plan.Errors.Add(new PlanIssue(PlanIssueCode.GradientExceeded, // se la stima locale non supera il massimo, il conflitto nasce dall'insieme dei vincoli di quota
$"Pendenza necessaria {needed * 100:F1}% oltre il massimo {gMax * 100:F1}%: {reason}", geo[i].S)); 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); 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 VehicleId Id { get; init; }
public required VehicleDef Def { 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 required long BoughtDay { get; set; }
public TrainId Train { get; set; } = TrainId.None; public TrainId Train { get; set; } = TrainId.None;
public DepotId Depot { get; set; } = DepotId.None; public DepotId Depot { get; set; } = DepotId.None;
@@ -97,7 +97,7 @@ public struct HeldResource
public sealed class Train public sealed class Train
{ {
public required TrainId Id { get; init; } 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 required string Name { get; set; }
public List<VehicleId> Vehicles { get; } = []; public List<VehicleId> Vehicles { get; } = [];
public DepotId HomeDepot { get; set; } = DepotId.None; 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 sealed class Line
{ {
public required LineId Id { get; init; } 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 Name { get; set; }
public required string Color { get; set; } public required string Color { get; set; }
public List<LineStop> Stops { get; } = []; 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) if (!command.Issuer.IsValid || command.Issuer.Value >= w.Companies.Count)
return Result(CommandError.UnknownCompany, "Compagnia sconosciuta"); return Result(CommandError.UnknownCompany, "Compagnia sconosciuta");
var company = w.Companies[command.Issuer.Value]; var company = w.Companies[command.Issuer.Value];
if (company.Merged)
return Result(CommandError.NotAllowed, "La compagnia è stata incorporata");
if (company.Bankrupt) if (company.Bankrupt)
return Result(CommandError.Bankrupt, "La compagnia è in bancarotta"); 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 return command switch
{ {
TakeLoanCommand c => TakeLoan(w, company, c, Result), TakeLoanCommand c => TakeLoan(w, company, c, Result),
RepayLoanCommand c => RepayLoan(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), BuildTrackCommand c => RailCommandHandlers.BuildTrack(w, company, c, Reply),
BuildStationCommand c => RailCommandHandlers.BuildStation(w, company, c, Reply), BuildStationCommand c => RailCommandHandlers.BuildStation(w, company, c, Reply),
BuildDepotCommand c => RailCommandHandlers.BuildDepot(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) 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 (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); var max = FinanceSystem.MaxLoan(w, company);
if (company.Debt + c.Amount > max) if (company.Debt + c.Amount > max)
return result(CommandError.CreditLimit, $"Fido insufficiente: disponibili {(max - company.Debt).ToString()}"); 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); if (loan.Remaining.Cents <= 0) company.Loans.Remove(loan);
return result(CommandError.None, $"Rimborsati {amount}"); 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.Economy;
using ViaFerrea.Core.Map; using ViaFerrea.Core.Map;
using ViaFerrea.Core.Simulation.Systems;
namespace ViaFerrea.Core.Simulation; namespace ViaFerrea.Core.Simulation;
/// <summary>Creazione e collocazione delle industrie durante la partita (nascita per domanda insoddisfatta).</summary> /// <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; ind.OutputStock[o] = units;
w.Goods.Produced[def.Recipe.Outputs[o].GoodIndex] += 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); w.Money.Transfer(Account.External, Account.Of(ind.Id), new Money(ib.StartingCash), LedgerEntry.Other);
MarkFootprint(w, cellX, cellY, footprint, CellType.Industry); MarkFootprint(w, cellX, cellY, footprint, CellType.Industry);
return ind; return ind;
@@ -90,6 +90,7 @@ public static class MaintenanceCommandHandlers
public static CommandResult OrderParts(World w, Company company, OrderPartsCommand c, RailCommandHandlers.Reply reply) 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"); 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]; var d = w.Network.Depots[c.Depot.Value];
if (d.Owner != company.Id || !w.Network.IsAlive(d)) return reply(CommandError.NotFound, "Deposito inesistente"); 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 required ulong Seed { get; init; }
public int StartYear { get; set; } = 1850; public int StartYear { get; set; } = 1850;
public string Difficulty { get; set; } = "imprenditore"; 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 required ScenarioTerrain Terrain { get; init; }
public List<ScenarioTown> Towns { get; set; } = []; public List<ScenarioTown> Towns { get; set; } = [];
public List<ScenarioIndustry> Industries { get; set; } = []; public List<ScenarioIndustry> Industries { get; set; } = [];
@@ -104,6 +104,9 @@ public static class ScenarioLoader
StartYear = file.StartYear, StartYear = file.StartYear,
DifficultyId = file.Difficulty, DifficultyId = file.Difficulty,
PlayerCompanyName = file.Player?.Name ?? "Società Ferroviaria Valdoria", 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); var world = WorldFactory.FromMap(data, map, settings);
if (file.Player?.Cash is { } cash) if (file.Player?.Cash is { } cash)
@@ -1,4 +1,5 @@
using System.Diagnostics; using System.Diagnostics;
using ViaFerrea.Core.Simulation.Ai;
using ViaFerrea.Core.Simulation.Systems; using ViaFerrea.Core.Simulation.Systems;
namespace ViaFerrea.Core.Simulation; namespace ViaFerrea.Core.Simulation;
@@ -35,9 +36,12 @@ public sealed class SystemPipeline(IReadOnlyList<ISimSystem> systems)
new DemandSystem(), new DemandSystem(),
new EmploymentSystem(), new EmploymentSystem(),
new IndustrySystem(), new IndustrySystem(),
new IndustryMaintenanceSystem(),
new TownSystem(), new TownSystem(),
new MarketSystem(), new MarketSystem(),
new FinanceSystem(), new FinanceSystem(),
new StockMarketSystem(),
new AiSystem(),
new HashSystem(), new HashSystem(),
]); ]);
@@ -4,8 +4,9 @@ using ViaFerrea.Core.Economy;
namespace ViaFerrea.Core.Simulation.Systems; namespace ViaFerrea.Core.Simulation.Systems;
/// <summary> /// <summary>
/// Domanda giornaliera: consumo desiderato delle città (con elasticità al prezzo) e input /// Domanda giornaliera: consumo desiderato delle città (con elasticità al prezzo), input
/// richiesti dalle industrie al loro potenziale di lavoro. Alimenta D del mercato. /// richiesti dalle industrie al loro potenziale di lavoro e ricambi per gli impianti.
/// Alimenta D del mercato.
/// </summary> /// </summary>
public sealed class DemandSystem : ISimSystem public sealed class DemandSystem : ISimSystem
{ {
@@ -30,6 +31,7 @@ public sealed class DemandSystem : ISimSystem
} }
int dpm = w.Calendar.DaysPerMonth; int dpm = w.Calendar.DaysPerMonth;
var im = data.Balance.IndustryMaintenance;
foreach (var ind in w.Industries) foreach (var ind in w.Industries)
{ {
if (ind.Closed || ind.Level <= 0) if (ind.Closed || ind.Level <= 0)
@@ -37,6 +39,8 @@ public sealed class DemandSystem : ISimSystem
Array.Clear(ind.InputDemandToday); Array.Clear(ind.InputDemandToday);
continue; 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) double eLabor = Math.Min(ind.CovWorkers, ind.CovStaff) * IndustryMath.ProfitFactor(ind, data.Balance.Industry)
* IndustryMath.ConditionMultiplier(ind.Condition, data.Balance.IndustryMaintenance); * IndustryMath.ConditionMultiplier(ind.Condition, data.Balance.IndustryMaintenance);
double cycles = ind.CyclesPerDayAtFullCapacity(dpm) * eLabor; double cycles = ind.CyclesPerDayAtFullCapacity(dpm) * eLabor;
@@ -21,7 +21,7 @@ public sealed class FinanceSystem : ISimSystem
PayRunningCosts(w); PayRunningCosts(w);
foreach (var c in w.Companies) foreach (var c in w.Companies)
{ {
if (c.Bankrupt) continue; if (c.Defunct) continue;
c.NegativeCashDays = c.Cash.IsNegative ? c.NegativeCashDays + 1 : 0; c.NegativeCashDays = c.Cash.IsNegative ? c.NegativeCashDays + 1 : 0;
if (c.NegativeCashDays >= w.Difficulty.BankruptcyDays) if (c.NegativeCashDays >= w.Difficulty.BankruptcyDays)
{ {
@@ -35,8 +35,14 @@ public sealed class FinanceSystem : ISimSystem
UpdateBookValues(w); UpdateBookValues(w);
foreach (var c in w.Companies) foreach (var c in w.Companies)
{ {
if (c.Merged) continue;
if (!c.Bankrupt) PayLoans(w, c); if (!c.Bankrupt) PayLoans(w, c);
c.Rating = ComputeRating(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); Array.Clear(c.MonthEntries);
} }
} }
@@ -72,7 +78,7 @@ public sealed class FinanceSystem : ISimSystem
} }
for (int i = 0; i < w.Companies.Count; i++) 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); 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.Data;
using ViaFerrea.Core.Economy; using ViaFerrea.Core.Economy;
@@ -36,4 +37,63 @@ public static class IndustryMath
double perDay = ind.CyclesPerDayAtFullCapacity(daysPerMonth) * inputs[inputIndex].PerCycle; double perDay = ind.CyclesPerDayAtFullCapacity(daysPerMonth) * inputs[inputIndex].PerCycle;
return (int)Math.Ceiling(perDay * ind.Def.StorageDays); 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 pf = IndustryMath.ProfitFactor(ind, ib);
double mc = IndustryMath.ConditionMultiplier(ind.Condition, data.Balance.IndustryMaintenance); double mc = IndustryMath.ConditionMultiplier(ind.Condition, data.Balance.IndustryMaintenance);
double eLabor = Math.Min(ind.CovWorkers, ind.CovStaff) * pf * mc; 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 // giacimento: sotto la soglia la capacità cala linearmente, a zero l'industria chiude
double depletion = 1.0; double depletion = 1.0;
@@ -58,7 +61,7 @@ public sealed class IndustrySystem : ISimSystem
} }
double cycles = ind.CyclesPerDayAtFullCapacity(dpm) * eLabor * depletion; 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; 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 // copertura degli input di oggi: limita la produzione alle scorte disponibili
@@ -53,8 +53,17 @@ public sealed class LocalTransportSystem : ISimSystem
{ {
if (available <= 0) break; if (available <= 0) break;
var consumer = w.Industries[ci]; 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); 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 free = IndustryMath.InputCapacity(consumer, i, dpm) - consumer.InputStock[i];
int units = Math.Min(available, free); int units = Math.Min(available, free);
if (units <= 0) continue; if (units <= 0) continue;
@@ -102,6 +111,8 @@ public sealed class LocalTransportSystem : ISimSystem
{ {
if (consumer.Closed || hub.RemainingCapacity <= 0) continue; if (consumer.Closed || hub.RemainingCapacity <= 0) continue;
if (Vec2.Distance(hub.Position, consumer.Position) > lt.RadiusKm * 1000) 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; var inputs = consumer.Def.Recipe.Inputs;
for (int i = 0; i < inputs.Count; i++) 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) private static void Sell(World w, Industry producer, int outputIndex, int units, double unitPrice)
{ {
var amount = Money.FromCentsRounded(units * unitPrice); var amount = Money.FromCentsRounded(units * unitPrice);
@@ -37,10 +37,47 @@ public sealed class StationSystem : ISimSystem
foreach (var s in net.Stations) foreach (var s in net.Stations)
{ {
if (net.Nodes[s.Node.Value].Station != s.Id || !LoadsHere(w, s)) continue; 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); 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) private static bool LoadsHere(World w, Station s)
{ {
foreach (var line in w.Lines) foreach (var line in w.Lines)
@@ -131,17 +168,21 @@ public sealed class StationSystem : ISimSystem
if (o == 0) ind.ShippedToday += units; 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> /// <summary>
/// Un hub nel bacino importa i ricambi richiesti dalle officine raggiungibili sulle linee (10.2): /// Un hub nel bacino importa ricambi e macchinari richiesti dalle officine e dalle industrie
/// li spedisce verso la stazione con più bisogno, entro la capacità mensile dell'hub. /// raggiungibili sulle linee (10.2, 11): li spedisce verso la stazione con più bisogno, entro la
/// capacità mensile dell'hub.
/// </summary> /// </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; var w = ctx.World;
int good = w.Data.SparePartsGood;
var reach = graph.From(s.Id, LineGraph.GoodCargo(good)); var reach = graph.From(s.Id, LineGraph.GoodCargo(good));
if (reach.Count == 0) return; if (reach.Count == 0) return;
_candidates.Clear(); _candidates.Clear();
@@ -152,7 +193,7 @@ public sealed class StationSystem : ISimSystem
foreach (var (sid, _) in _candidates) foreach (var (sid, _) in _candidates)
{ {
var dest = w.Network.Stations[sid]; 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; if (need <= bestNeed) continue;
bestNeed = need; bestNeed = need;
best = reach[sid]; 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> /// <summary>Ricambi mancanti alle officine nel bacino della stazione (scorta desiderata − scorta).</summary>
private static int DepotNeed(World w, Station s) private static int DepotNeed(World w, Station s)
{ {
@@ -217,8 +266,15 @@ public sealed class StationSystem : ISimSystem
foreach (var id in dest.Industries) foreach (var id in dest.Industries)
{ {
var ind = w.Industries[id.Value]; 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); int i = ind.InputIndexOf(good);
if (i < 0 || ind.Closed) continue; if (i < 0) continue;
consumer = true; consumer = true;
need += IndustryMath.InputCapacity(ind, i, dpm) - ind.InputStock[i]; need += IndustryMath.InputCapacity(ind, i, dpm) - ind.InputStock[i];
} }
@@ -206,6 +206,9 @@ public static class StationWork
if (units <= 0) return 0; if (units <= 0) return 0;
var ind = w.Industries[id.Value]; var ind = w.Industries[id.Value];
if (ind.Closed) continue; 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); int i = ind.InputIndexOf(good);
if (i < 0) continue; if (i < 0) continue;
int free = IndustryMath.InputCapacity(ind, i, dpm) - ind.InputStock[i]; int free = IndustryMath.InputCapacity(ind, i, dpm) - ind.InputStock[i];
@@ -261,6 +264,34 @@ public static class StationWork
return units; 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 // ------------------------------------------------------------------ carico
/// <summary>Carica i pacchetti in attesa che viaggiano sulla linea del treno; restituisce le unità caricate.</summary> /// <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> /// <summary>Convenzioni di pendolarismo (proposte, attive e concluse di recente).</summary>
public List<CommuteAgreement> Agreements { get; } = []; 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> /// <summary>Rete ferroviaria di tutte le compagnie.</summary>
public RailNetwork Network { get; } = new(); public RailNetwork Network { get; } = new();
public List<Vehicle> Vehicles { get; } = []; public List<Vehicle> Vehicles { get; } = [];
@@ -181,6 +199,8 @@ public sealed class World
} }
foreach (var ind in Industries) foreach (var ind in Industries)
{ {
if (good == Data.SparePartsGood) sum += ind.SpareParts;
if (good == Data.MachineryGood) sum += ind.Machinery;
int i = ind.InputIndexOf(good); int i = ind.InputIndexOf(good);
if (i >= 0) sum += ind.InputStock[i]; if (i >= 0) sum += ind.InputStock[i];
int o = ind.OutputIndexOf(good); int o = ind.OutputIndexOf(good);
+31 -18
View File
@@ -116,25 +116,38 @@ public static class WorldFactory
}; };
w.Companies.Add(player); w.Companies.Add(player);
w.Money.Transfer(Account.External, Account.Of(player.Id), new Money(d.InitialCapital), LedgerEntry.Other); 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++) CreateAiCompany(w, rng);
for (int i = 0; i < d.AiCompetitors; i++) }
/// <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}"; Id = new CompanyId(w.Companies.Count),
names.Remove(name); Name = name,
var personality = data.Ai.Personalities[rng.NextInt(data.Ai.Personalities.Count)]; IsPlayer = false,
var ai = new Company AiPersonality = personality.Id,
{ Color = data.Ai.Colors[aiIndex % data.Ai.Colors.Count],
Id = new CompanyId(w.Companies.Count), BaseCredit = new Money(d.InitialCredit) * d.AiCapitalMultiplier,
Name = name, Rating = data.Balance.Finance.StartingRating,
IsPlayer = false, FoundedDay = w.Clock.Day,
AiPersonality = personality.Id, };
Color = data.Ai.Colors[i % data.Ai.Colors.Count], w.Companies.Add(ai);
BaseCredit = new Money(d.InitialCredit) * d.AiCapitalMultiplier, w.Money.Transfer(Account.External, Account.Of(ai.Id), new Money(d.InitialCapital) * d.AiCapitalMultiplier, LedgerEntry.Other);
Rating = data.Balance.Finance.StartingRating, Corporate.InitShares(w, ai, listed: true, 1 - data.Balance.StockMarket.AiFloatAtStart);
}; return ai;
w.Companies.Add(ai);
w.Money.Transfer(Account.External, Account.Of(ai.Id), new Money(d.InitialCapital) * d.AiCapitalMultiplier, LedgerEntry.Other);
}
} }
} }
@@ -41,6 +41,15 @@ public sealed class ClientWorld(GameData data)
public Dictionary<int, WorkshopRegister> Workshops { get; } = []; public Dictionary<int, WorkshopRegister> Workshops { get; } = [];
public EmploymentReport? Employment { get; private set; } 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> /// <summary>Ultimi avvisi di manutenzione, dal più recente.</summary>
public List<MaintenanceAlert> Alerts { get; } = []; public List<MaintenanceAlert> Alerts { get; } = [];
private const int AlertCapacity = 50; private const int AlertCapacity = 50;
@@ -102,6 +111,22 @@ public sealed class ClientWorld(GameData data)
Employment = m; Employment = m;
DetailVersion++; DetailVersion++;
return true; 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: case MaintenanceAlert m:
Alerts.Insert(0, m); Alerts.Insert(0, m);
if (Alerts.Count > AlertCapacity) Alerts.RemoveAt(Alerts.Count - 1); if (Alerts.Count > AlertCapacity) Alerts.RemoveAt(Alerts.Count - 1);
@@ -117,6 +142,10 @@ public sealed class ClientWorld(GameData data)
Cards.Clear(); Cards.Clear();
Workshops.Clear(); Workshops.Clear();
Employment = null; Employment = null;
Tape = null;
CompanyCards.Clear();
IndustryCards.Clear();
Chronicle = null;
Alerts.Clear(); Alerts.Clear();
Summary = m.Summary; Summary = m.Summary;
SessionId = m.SessionId; SessionId = m.SessionId;
+28 -2
View File
@@ -160,10 +160,26 @@ public static class CommandCodec
w.String(c.Objective); w.String(c.Objective);
w.Money(c.Budget); w.Money(c.Budget);
break; break;
case MergeCompanyCommand c: w.I32(c.Subsidiary.Value); break;
default: default:
throw new ProtocolException($"comando senza codifica: {command.Type}"); 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) 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.AcceptContract => new AcceptContractCommand(new ContractId(r.I32())),
CommandType.FundResearch => new FundResearchCommand(r.String(), r.Money()), CommandType.FundResearch => new FundResearchCommand(r.String(), r.Money()),
CommandType.DelegateRegion => new DelegateRegionCommand(new RegionId(r.I32()), 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}"), _ => 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; return c;
} }
+6
View File
@@ -31,6 +31,12 @@ public enum MessageId : ushort
MaintenanceCard = 124, MaintenanceCard = 124,
/// <summary>Registro officina di un deposito (F4).</summary> /// <summary>Registro officina di un deposito (F4).</summary>
WorkshopRegister = 125, 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, CommandResult = 130,
Notification = 131, Notification = 131,
Newspaper = 132, Newspaper = 132,
@@ -231,6 +231,12 @@ public enum DetailKind : byte
Workshop = 2, Workshop = 2,
/// <summary>Registro degli impieghi della compagnia (risposta EmploymentReport; Id ignorato).</summary> /// <summary>Registro degli impieghi della compagnia (risposta EmploymentReport; Id ignorato).</summary>
Employment = 3, 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> /// <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.EmploymentReport => EmploymentReport.Read(ref r),
MessageId.MaintenanceCard => MaintenanceCard.Read(ref r), MessageId.MaintenanceCard => MaintenanceCard.Read(ref r),
MessageId.WorkshopRegister => WorkshopRegister.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.MarketTape => MarketTape.Read(ref r),
MessageId.CommandResult => CommandResultMessage.Read(ref r), MessageId.CommandResult => CommandResultMessage.Read(ref r),
MessageId.Notification => Notification.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 // blocco 1 (F4): politica di manutenzione della flotta
public byte MaintenancePolicy { get; set; } = 1; 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) 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.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.String(Rating); w.U8(Tier); w.Bool(Bankrupt);
w.Flags(1); w.Flags(3);
w.U8(MaintenancePolicy); 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) public static CompanyInfo Read(ref SpanReader r)
@@ -88,6 +104,11 @@ public sealed class CompanyInfo : IWritable
}; };
byte flags = r.Flags(); byte flags = r.Flags();
if ((flags & 1) != 0) m.MaintenancePolicy = r.U8(); 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; return m;
} }
} }
@@ -129,11 +150,24 @@ public sealed class IndustryInfo : IWritable
public float Condition { get; init; } public float Condition { get; init; }
public int Owner { get; init; } = -1; 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) 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.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.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) 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(), 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(), 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; return m;
} }
} }
@@ -739,16 +739,27 @@ public sealed class SharePrice
public float Change { get; init; } public float Change { get; init; }
public bool Listed { 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) public void Write(ref SpanWriter w)
{ {
w.I32(Company); w.Money(Price); w.F32(Change); w.Bool(Listed); 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) public static SharePrice Read(ref SpanReader r)
{ {
var m = new SharePrice { Company = r.I32(), Price = r.Money(), Change = r.F32(), Listed = r.Bool() }; 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; return m;
} }
} }
@@ -762,16 +773,28 @@ public sealed class BidInfo
public double TargetShare { get; init; } public double TargetShare { get; init; }
public long ExpiresDay { 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) 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.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) 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() }; 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; return m;
} }
} }
+17
View File
@@ -619,6 +619,13 @@ public sealed class GameHost : IDisposable
} }
} }
if (_monthlyDue) s.Send(Projection.Employment(w, s.Company)); 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; _monthlyDue = false;
_dayEvents.Clear(); _dayEvents.Clear();
@@ -641,6 +648,16 @@ public sealed class GameHost : IDisposable
case DetailKind.Employment: case DetailKind.Employment:
s.Send(Projection.Employment(w, s.Company)); s.Send(Projection.Employment(w, s.Company));
break; 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, 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, 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) foreach (var t in w.Towns)
@@ -94,7 +97,9 @@ public static class Projection
e.Industries.Add(new IndustryInfo 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, 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) foreach (var h in w.Hubs)
@@ -414,4 +419,103 @@ public static class Projection
record.Write(ref w); record.Write(ref w);
return XxHash64.Hash(w.Written); 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 Dictionary<int, (long Tick, byte State)> MotionSent { get; } = [];
public bool NeedsFullState { get; set; } = true; 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) public Session(ulong id, CompanyId company)
{ {
Id = id; Id = id;
@@ -17,7 +17,7 @@ public sealed class SimulateCommand : IToolCommand
{ {
public string Name => "simulate"; 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; private static readonly CultureInfo It = CultureInfo.InvariantCulture;
@@ -30,7 +30,9 @@ public sealed class SimulateCommand : IToolCommand
string? scenario = args.String("scenario"); string? scenario = args.String("scenario");
string output = args.String("out", "kpi.csv"); string output = args.String("out", "kpi.csv");
string? savePath = args.String("save"); string? savePath = args.String("save");
bool trace = args.Flag("trace-ai");
args.EnsureAllUsed(); args.EnsureAllUsed();
if (trace) Core.Simulation.Ai.AiSystem.Trace = Console.WriteLine;
var data = GameData.LoadDefault(); var data = GameData.LoadDefault();
var total = Stopwatch.StartNew(); 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($" 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($" 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")}"); 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}"); Console.WriteLine($" KPI in {output}");
return 0; return 0;
} }
@@ -91,12 +95,22 @@ public sealed class SimulateCommand : IToolCommand
{ {
long revenue = Company.Revenue(c.LastYearEntries); long revenue = Company.Revenue(c.LastYearEntries);
double share = totalCarrier > 0 ? (double)revenue / totalCarrier : 0; 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); 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), "", 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)); 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('.', ','); private static string Dec(double v) => v.ToString("0.###", It).Replace('.', ',');
} }
+87
View File
@@ -0,0 +1,87 @@
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Persistence;
using ViaFerrea.Core.Simulation;
using ViaFerrea.Core.Simulation.Ai;
using ViaFerrea.Tests.Harness;
namespace ViaFerrea.Tests.Economy;
/// <summary>Concorrenti IA (guida 12.1, test di 14.5): comandi validi, crescita, determinismo.</summary>
public static class AiTests
{
[Test(Slow = true, Description = "Le IA agiscono solo con i comandi e ne vedono rifiutati al massimo il 5 %")]
public static void AiCommandsAreRarelyRejected()
{
var w = TestWorlds.Small(42);
w.RunYears(5);
Assert.True(w.AiStates.Count >= 2, "uno stato per ogni IA");
long issued = 0;
foreach (var s in w.AiStates)
{
issued += s.Issued;
Assert.True(s.RejectedShare <= w.Data.Ai.Planning.MaxRejectedShare,
$"{w.Company(s.Company).Name}: {s.Rejected} rifiutati su {s.Issued}");
}
Assert.True(issued > 20, $"le IA costruiscono e gestiscono la rete ({issued} comandi)");
Assert.True(w.AiStates.Any(s => s.Projects.Any(p => p.Stage == AiProjectStage.Running)), "almeno una linea in esercizio");
// i binari, i treni e le stazioni delle IA esistono davvero nel mondo
foreach (var s in w.AiStates)
{
foreach (var p in s.Projects.Where(p => p.Stage == AiProjectStage.Running))
{
Assert.True(w.Network.IsAlive(w.Network.Stations[p.StationA.Value]) || w.Company(s.Company).Defunct);
Assert.True(p.Trains.All(t => w.Trains[t.Value].Owner == s.Company || w.Company(s.Company).Merged));
}
}
}
[Test(Slow = true, Description = "Un'IA con capitale ×2 supera il giocatore passivo in 10 anni")]
public static void AiWithDoubleCapitalBeatsAPassivePlayer()
{
var w = TestWorlds.Small(42, "imprenditore", ("aiCapitalMultiplier", 2));
w.RunYears(10);
var player = w.Player;
var best = w.Companies.Where(c => !c.IsPlayer).MaxBy(c => c.NetWorth.Cents)!;
Assert.True(best.NetWorth > player.NetWorth, $"{best.Name}: {best.NetWorth} contro {player.NetWorth}");
Assert.True(best.NetWorth.Cents > w.Difficulty.InitialCapital * 2, $"{best.Name} ha fatto crescere il capitale: {best.NetWorth}");
}
[Test(Slow = true, Description = "Determinismo con le IA: stesso seme e stessi comandi, stesso hash dopo 5 anni (anche passando da un salvataggio)")]
public static void SameSeedWithAiGivesSameHash()
{
static World Make()
{
var w = TestWorlds.Small(77, "magnate");
w.Enqueue(new TakeLoanCommand(Money.FromLire(50_000)) { Issuer = w.Player.Id, Seq = 1 });
return w;
}
var a = Make();
var b = Make();
a.RunYears(2);
b.RunYears(2);
Assert.Equal(StateHasher.Compute(a), StateHasher.Compute(b));
var c = SaveFile.Load(TestData.Data, SaveFile.Save(b, "test"));
a.RunYears(3);
c.RunYears(3);
Assert.Equal(StateHasher.Compute(a), StateHasher.Compute(c));
Assert.True(a.AiStates.Sum(s => s.Issued) > 0, "le IA hanno agito");
}
[Test(Slow = true, Description = "Accettazione F5: in «Magnate», con il giocatore passivo, almeno un'IA raggiunge il livello 3 in 15 anni")]
public static void OnMagnateAnAiReachesTierThreeIn15Years()
{
var w = WorldFactory.Create(TestData.Data, new NewGameSettings { Seed = 7, SizeKm = 128, DifficultyId = "magnate" });
int best = 1;
for (int y = 0; y < 15 && best < 3; y++)
{
w.RunYears(1);
best = w.Companies.Where(c => !c.IsPlayer).Max(c => c.Tier);
}
var leader = w.Companies.Where(c => !c.IsPlayer).MaxBy(c => (c.Tier, c.NetWorth.Cents))!;
Console.WriteLine($" {leader.Name}: livello {leader.Tier} nel {w.Clock.Year}, patrimonio {leader.NetWorth}, rating {leader.Rating}, " +
$"città collegate {Core.Simulation.Systems.Tiers.ConnectedTowns(w, leader.Id, 1000)}");
Assert.True(best >= 3, $"livello massimo delle IA: {best}");
Assert.Equal(1, w.Player.Tier, "il giocatore passivo resta al livello 1");
}
}
@@ -66,9 +66,9 @@ public static class EconomyTests
public static void FreightAndPassengerTariffsFollowFormulas() public static void FreightAndPassengerTariffsFollowFormulas()
{ {
var t = TestData.Data.Balance.Tariffs; var t = TestData.Data.Balance.Tariffs;
// a prezzo base: 40 t × 150 × 1 × 20^0,9 centesimi // a prezzo base: 40 t × tariffa base × 1 × 20^0,9 centesimi
var freight = Tariffs.Freight(40, 20, 3800, 3800, 1, 1, t, 1.0); var freight = Tariffs.Freight(40, 20, 3800, 3800, 1, 1, t, 1.0);
Assert.Equal(Money.FromCentsRounded(40 * 150 * DMath.Pow(20, 0.9)), freight); Assert.Equal(Money.FromCentsRounded(40 * t.FreightBaseRate * DMath.Pow(20, 0.9)), freight);
// consegna con il doppio del tempo atteso: oltre la soglia del 50 % la tariffa cala // consegna con il doppio del tempo atteso: oltre la soglia del 50 % la tariffa cala
var late = Tariffs.Freight(40, 20, 3800, 3800, 2, 1, t, 1.0); var late = Tariffs.Freight(40, 20, 3800, 3800, 2, 1, t, 1.0);
Assert.True(late < freight && late.Cents >= freight.Cents / 2); Assert.True(late < freight && late.Cents >= freight.Cents / 2);
@@ -182,7 +182,7 @@ public static class EconomyTests
{ {
var w = TestWorlds.Small(108); var w = TestWorlds.Small(108);
ulong before = ViaFerrea.Core.Persistence.StateHasher.Compute(w); ulong before = ViaFerrea.Core.Persistence.StateHasher.Compute(w);
w.Enqueue(new OverhaulIndustryCommand(new IndustryId(0)) { Issuer = w.Player.Id, Seq = 9 }); w.Enqueue(new BuyConcessionCommand(new RegionId(0)) { Issuer = w.Player.Id, Seq = 9 });
w.Enqueue(new TakeLoanCommand(Money.FromLire(1)) { Issuer = new CompanyId(99), Seq = 10 }); w.Enqueue(new TakeLoanCommand(Money.FromLire(1)) { Issuer = new CompanyId(99), Seq = 10 });
w.Pipeline.Get<CommandSystem>().Step(w.Context); w.Pipeline.Get<CommandSystem>().Step(w.Context);
var results = w.DrainResults(); var results = w.DrainResults();
@@ -0,0 +1,206 @@
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Simulation;
using ViaFerrea.Core.Simulation.Systems;
using ViaFerrea.Tests.Harness;
namespace ViaFerrea.Tests.Economy;
/// <summary>Manutenzione degli impianti (guida, sezione 11) e industrie possedute dal giocatore.</summary>
public static class IndustryMaintenanceTests
{
private static Industry Pick(World w, IndustryKind kind) =>
w.Industries.First(i => !i.Closed && i.Level > 0 && i.Def.Kind == kind);
private static CommandResult Do(World w, GameCommand c)
{
w.Enqueue(c with { Issuer = w.Player.Id });
w.RunTicks(1);
return w.DrainResults().Last();
}
[Test]
public static void EfficiencyMultiplierFollowsTheGuide()
{
var m = TestData.Data.Balance.IndustryMaintenance;
Assert.Approx(1.0, IndustryMath.ConditionMultiplier(100, m), 1e-9);
Assert.Approx(1.0, IndustryMath.ConditionMultiplier(70, m), 1e-9);
Assert.Approx(0.75, IndustryMath.ConditionMultiplier(45, m), 1e-9);
Assert.Approx(0.5, IndustryMath.ConditionMultiplier(20, m), 1e-9);
Assert.Approx(0.3, IndustryMath.ConditionMultiplier(10, m), 1e-9);
}
[Test(Description = "Usura con l'utilizzo; il budget Alto recupera; senza ricambi il recupero si dimezza")]
public static void WearFollowsUseAndBudgetRecovers()
{
var w = TestWorlds.NoAi(301);
var m = w.Data.Balance.IndustryMaintenance;
var ind = Pick(w, IndustryKind.Primary);
w.RunDays(5);
// senza manutenzione la condizione scende con l'utilizzo
ind.Budget = IndustryBudget.None;
ind.Condition = 80;
w.RunDays(60);
double dropped = 80 - ind.Condition;
Assert.True(dropped > 0, $"usura senza budget: {dropped:F3}");
Assert.True(dropped <= m.WearPerDay * 1.2 * ind.Def.WearIntensity * w.Difficulty.WearMultiplier * 60 + 1e-6, "usura entro il massimo della formula");
// budget alto con ricambi: il recupero (0,12 al giorno) supera l'usura; senza ricambi si dimezza.
// Due finestre di 10 giorni nello stesso mese (il consumo mensile ricalcola la mancanza di ricambi).
int dpm = w.Calendar.DaysPerMonth;
w.RunDays(dpm - (int)(w.Clock.Day % dpm) + 1);
ind.Budget = IndustryBudget.High;
ind.Condition = 60;
ind.PartsShort = false;
w.RunDays(10);
double withParts = ind.Condition - 60;
Assert.True(withParts > 0, $"recupero con budget alto: {withParts:F3}");
ind.Condition = 60;
ind.PartsShort = true;
w.RunDays(10);
double withoutParts = ind.Condition - 60;
var budget = m.For(IndustryBudget.High);
Assert.Approx(budget.RecoveryPerDay * (1 - m.NoPartsRecoveryFactor) * 10, withParts - withoutParts, 0.05,
$"senza ricambi il recupero si dimezza: {withoutParts:F3} contro {withParts:F3}");
Assert.Equal(0L, w.MoneyBalanceSum());
for (int g = 0; g < w.Data.GoodCount; g++) Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"bene {w.Data.Goods[g].Id}");
}
[Test(Description = "Sotto 40 arrivano i fermi: niente produzione, storico, città colpita; sotto 10 l'incidente grave")]
public static void LowConditionBringsStopsAndAccidents()
{
var w = TestWorlds.NoAi(302);
var m = w.Data.Balance.IndustryMaintenance;
var ind = Pick(w, IndustryKind.Processing);
ind.Budget = IndustryBudget.None;
ind.Condition = 5;
bool stopped = false;
for (int d = 0; d < 720 && !stopped; d++)
{
ind.Condition = 5;
w.RunDays(1);
stopped = ind.IsStopped(w.Clock.Day);
}
Assert.True(stopped, "con condizione 5 un fermo arriva");
Assert.Equal(IndustryStop.Accident, ind.StopKind, "un'industria di trasformazione sotto 10 ha un incidente grave");
Assert.Equal(m.AccidentDays, ind.StopHistory[^1].Days);
w.RunDays(2);
Assert.Equal(0, ind.ProducedToday.Sum(), "nessuna produzione durante il fermo");
Assert.Approx(0.0, ind.Efficiency, 1e-9);
// un'industria primaria a 25 ha solo fermi per guasto da 5 a 20 giorni
var mine = Pick(w, IndustryKind.Primary);
mine.Budget = IndustryBudget.None;
bool broke = false;
for (int d = 0; d < 2000 && !broke; d++)
{
mine.Condition = 25;
w.RunDays(1);
broke = mine.IsStopped(w.Clock.Day);
}
Assert.True(broke, "a 25 il rischio giornaliero produce un fermo");
Assert.Equal(IndustryStop.Breakdown, mine.StopKind);
Assert.InRange(mine.StopHistory[^1].Days, m.BreakdownDays[0], m.BreakdownDays[1]);
// il rischio cresce al calare della condizione
Assert.True(m.BreakdownBase * DMath.Exp((m.BreakdownPivot - 10) / m.BreakdownScale) > m.BreakdownBase * DMath.Exp((m.BreakdownPivot - 30) / m.BreakdownScale));
}
[Test(Description = "Acquisto (livello 3, offerta ≥ valore), revisione che aspetta i macchinari e riporta la condizione a 100, ammodernamento di livello")]
public static void OwnedIndustryOverhaulAndUpgrade()
{
var w = TestWorlds.NoAi(303);
var m = w.Data.Balance.IndustryMaintenance;
var player = w.Player;
w.Money.Transfer(Account.External, Account.Of(player.Id), Money.FromLire(10_000_000), LedgerEntry.Other);
var ind = Pick(w, IndustryKind.Processing);
w.RunDays(3);
var locked = Do(w, new BuyIndustryCommand(ind.Id, Money.FromLire(9_000_000)));
Assert.Equal(CommandError.TierLocked, locked.Error, "l'acquisto si sblocca al livello 3");
player.Tier = 3;
var price = IndustryMath.Valuation(w, ind);
var low = Do(w, new BuyIndustryCommand(ind.Id, price - Money.FromLire(1)));
Assert.Equal(CommandError.InvalidArgument, low.Error, "offerta sotto il valore");
price = IndustryMath.Valuation(w, ind);
var cash = player.Cash;
var ok = Do(w, new BuyIndustryCommand(ind.Id, price + Money.FromLire(100)));
Assert.True(ok.Ok, ok.Message);
Assert.Equal(player.Id, ind.Owner);
Assert.True(player.Cash < cash, "l'acquisto si paga");
// revisione: aspetta i macchinari (e il personale), poi 30 giorni di fermo e condizione 100
ind.Condition = 30;
Assert.True(Do(w, new OverhaulIndustryCommand(ind.Id)).Ok);
Assert.Equal(IndustryWork.Overhaul, ind.PendingWork);
w.RunDays(5);
Assert.False(ind.IsStopped(w.Clock.Day), "senza macchinari la revisione non parte");
int need = IndustryMath.MachineryRequired(ind, m);
ind.Machinery += need;
w.Goods.Produced[w.Data.MachineryGood] += need;
ind.CovStaff = 1;
w.RunDays(2);
Assert.True(ind.IsStopped(w.Clock.Day), "con macchinari e personale la revisione parte");
Assert.Equal(IndustryStop.Overhaul, ind.StopKind);
w.RunDays(m.OverhaulDays + 1);
Assert.False(ind.IsStopped(w.Clock.Day));
Assert.True(ind.Condition > 99, $"condizione dopo la revisione: {ind.Condition:F1}");
// ammodernamento: costo in capitale e macchinari, 60 giorni, livello + 1
int level = ind.Level;
if (level < w.Data.Balance.Growth.MaxLevel)
{
Assert.True(Do(w, new UpgradeIndustryCommand(ind.Id)).Ok);
int machinery = IndustryMath.MachineryRequired(ind, m);
ind.Machinery += machinery;
w.Goods.Produced[w.Data.MachineryGood] += machinery;
var before = player.Cash;
w.RunDays(2);
Assert.Equal(IndustryStop.Upgrade, ind.StopKind);
Assert.True(player.Cash < before, "il proprietario paga l'ammodernamento");
w.RunDays(m.UpgradeDays + 1);
Assert.Equal(level + 1, ind.Level);
}
// «Ordina ricambi» crea domanda esplicita oltre la scorta della politica
Assert.True(Do(w, new OrderPartsCommand(DepotId.None, 30) { Industry = ind.Id }).Ok);
Assert.True(IndustryMath.ServiceNeed(w, ind, w.Data.SparePartsGood) >= 30);
Assert.Equal(0L, w.MoneyBalanceSum());
}
[Test(Description = "Ogni mese l'industria posseduta trattiene la riserva e versa il resto al proprietario")]
public static void OwnerReceivesTheSurplus()
{
var w = TestWorlds.NoAi(304);
var m = w.Data.Balance.IndustryMaintenance;
var ind = Pick(w, IndustryKind.Primary);
ind.Owner = w.Player.Id;
w.Money.Transfer(Account.External, Account.Of(ind.Id), Money.FromLire(500_000), LedgerEntry.Other);
var before = w.Player.Cash;
w.RunDays(w.Calendar.DaysPerMonth + 1);
Assert.Equal(m.OwnerCashReserve, ind.Cash.Cents, "l'industria trattiene la riserva");
Assert.True(w.Player.Cash > before, "il surplus va al proprietario");
Assert.True(w.Player.YearEntries[(int)LedgerEntry.Industries] > 0);
}
[Test(Description = "Proprietari privati: budget dal margine e revisione sotto 35 se la cassa basta")]
public static void NpcOwnersFollowTheirRules()
{
var w = TestWorlds.NoAi(305);
var ind = Pick(w, IndustryKind.Primary);
ind.RevenueEma = 10_000;
ind.CostEma = 5_000;
ind.Condition = 30;
w.Money.Transfer(Account.External, Account.Of(ind.Id), Money.FromLire(1_000_000), LedgerEntry.Other);
w.RunDays(w.Calendar.DaysPerMonth + 1);
Assert.Equal(IndustryWork.Overhaul, ind.PendingWork, "sotto 35 il privato programma la revisione");
// margine negativo: nessun budget
var other = w.Industries.First(i => !i.Closed && i.Level > 0 && i != ind && i.Def.Kind == IndustryKind.Primary);
other.RevenueEma = 1_000;
other.CostEma = 5_000;
w.RunDays(w.Calendar.DaysPerMonth);
Assert.True(other.Margin < 0);
Assert.Equal(IndustryBudget.None, other.Budget);
}
}
@@ -0,0 +1,285 @@
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Persistence;
using ViaFerrea.Core.Simulation;
using ViaFerrea.Core.Simulation.Systems;
using ViaFerrea.Tests.Harness;
namespace ViaFerrea.Tests.Economy;
/// <summary>Borsa, quotazione, dividendi, scalate e loro esiti (guida 12.2–12.3, test di 14.5).</summary>
public static class StockMarketTests
{
private static CommandResult Do(World w, GameCommand c, Company issuer)
{
w.Enqueue(c with { Issuer = issuer.Id });
w.RunTicks(1);
return w.DrainResults().Last();
}
private static void Give(World w, Company c, long lire) =>
w.Money.Transfer(Account.External, Account.Of(c.Id), Money.FromLire(lire), LedgerEntry.Other);
/// <summary>Le IA non devono intervenire: mondo con concorrenti ma senza agenti attivi.</summary>
private static World WithIdleAi(ulong seed, string difficulty = "imprenditore", int competitors = 2)
{
var w = TestWorlds.Small(seed, difficulty, ("aiCompetitors", competitors));
w.AiPaused = true;
return w;
}
[Test(Description = "Prezzo = max(patrimonio, 8 × utile) / azioni × sentiment, con il sentiment tra 0,8 e 1,3")]
public static void PriceFollowsFundamentals()
{
var w = WithIdleAi(401);
var sm = w.Data.Balance.StockMarket;
w.RunDays(40);
foreach (var c in w.Companies)
{
Assert.Equal(sm.Shares, c.Shares.Total);
Assert.Equal(c.Shares.Total, c.Shares.Sum());
Assert.InRange(c.Sentiment, sm.SentimentMin, sm.SentimentMax);
double fundamental = Math.Max(c.NetWorth.Cents, sm.EarningsMultiple * c.AnnualProfit) / c.Shares.Outstanding;
Assert.Approx(fundamental * c.Sentiment, c.SharePrice, fundamental * 0.05 + 0.01, c.Name);
}
Assert.False(w.Player.Listed, "il giocatore parte privato (Imprenditore)");
Assert.True(w.Companies.Where(c => !c.IsPlayer).All(c => c.Listed), "le IA sono quotate");
var iron = WithIdleAi(402, "ferro_e_sangue");
Assert.True(iron.Player.Listed, "Ferro e sangue: quotata dall'inizio");
Assert.Approx(0.6, iron.Player.Shares.FounderFraction, 1e-6);
}
[Test(Description = "Quotazione al livello 4 fino al 40 %, compravendita al prezzo con lo spread, dividendi agli azionisti")]
public static void IpoTradingAndDividends()
{
var w = WithIdleAi(403);
var player = w.Player;
var ai = w.Companies.First(c => !c.IsPlayer);
Give(w, player, 5_000_000);
w.RunDays(2);
Assert.Equal(CommandError.TierLocked, Do(w, new IpoCommand(0.3), player).Error);
player.Tier = 4;
Assert.Equal(CommandError.InvalidArgument, Do(w, new IpoCommand(0.5), player).Error, "oltre il 40 %");
var cash = player.Cash;
Assert.True(Do(w, new IpoCommand(0.3), player).Ok);
Assert.True(player.Listed);
Assert.True(player.Cash > cash, "la quotazione porta capitale");
Assert.Approx(0.7, player.Shares.FounderFraction, 1e-6);
// acquisto di azioni di un'IA: lettera = prezzo × (1 + spread/2)
long n = 20_000;
double ask = Corporate.Ask(w, ai);
cash = player.Cash;
long free = ai.Shares.Public;
var buy = Do(w, new BuySharesCommand(ai.Id, n, Money.Zero), player);
Assert.True(buy.Ok, buy.Message);
Assert.Equal(n, ai.Shares.Of(player.Id));
Assert.Equal(free - n, ai.Shares.Public);
Assert.Approx(n * ask, (cash - player.Cash).Cents, n * ask * 0.02 + 2);
w.RunDays(1);
Assert.True(player.PortfolioValue.Cents > 0, "le partecipazioni contano nel patrimonio");
var sell = Do(w, new SellSharesCommand(ai.Id, n / 2, Money.Zero), player);
Assert.True(sell.Ok, sell.Message);
Assert.Equal(n / 2, ai.Shares.Of(player.Id));
// dividendo: ogni azione in circolazione riceve l'importo; le compagnie azioniste lo incassano
var aiCash = ai.Cash;
Give(w, ai, 1_000_000);
aiCash = ai.Cash;
var holderCash = player.Cash;
Assert.True(Do(w, new PayDividendCommand(new Money(10)), ai).Ok);
Assert.Equal(aiCash.Cents - 10 * ai.Shares.Outstanding, ai.Cash.Cents);
Assert.Equal(holderCash.Cents + 10 * (n / 2), player.Cash.Cents);
Assert.True(ai.DividendRing.Sum() > 0, "i dividendi entrano nel sentiment");
Assert.Equal(0L, w.MoneyBalanceSum());
}
[Test(Description = "Scalata ostile completata quando il flottante lo consente (14.5); fallita quando non basta")]
public static void HostileTakeoverCompletesWhenTheFloatAllows()
{
var w = WithIdleAi(404);
var player = w.Player;
var target = w.Companies.First(c => !c.IsPlayer);
Give(w, player, 50_000_000);
w.RunDays(2);
// flottante del 70 %: il fondatore privato non aderisce (premio sotto la sua soglia)
long moved = target.Shares.Founder - (long)(target.Shares.Total * 0.3);
target.Shares.Founder -= moved;
target.Shares.Public += moved;
Assert.Equal(CommandError.TierLocked, Do(w, new LaunchBidCommand(target.Id, new Money(1), 0.51), player).Error);
player.Tier = 5;
long price = (long)Math.Ceiling(target.SharePrice * 1.3);
var bid = Do(w, new LaunchBidCommand(target.Id, new Money(price), 0.51), player);
Assert.True(bid.Ok, bid.Message);
bool done = false;
for (int d = 0; d < 100 && !done; d++)
{
w.RunDays(1);
done = w.Bids.Any(b => b.State != BidState.Open);
}
Assert.Equal(BidState.Succeeded, w.Bids.Single().State);
Assert.True(target.Shares.FractionOf(player.Id) >= 0.51, $"quota {target.Shares.FractionOf(player.Id):P1}");
w.RunDays(1);
Assert.Equal(player.Id, target.ControlledBy, "chi supera il 50 % controlla");
// stessa offerta su un'IA con il 30 % di flottante: le adesioni non bastano, l'offerta scade
var other = w.Companies.Last(c => !c.IsPlayer);
long p2 = (long)Math.Ceiling(other.SharePrice * 1.3);
Assert.True(Do(w, new LaunchBidCommand(other.Id, new Money(p2), 0.51), player).Ok);
w.RunDays(w.Data.Balance.StockMarket.BidDurationDays + 2);
var second = w.Bids.Single(b => b.Target == other.Id);
Assert.Equal(BidState.Failed, second.State);
Assert.Equal(0L, other.Shares.Of(player.Id));
Assert.Equal(0L, w.MoneyBalanceSum());
}
[Test(Description = "Difese del bersaglio: il riacquisto toglie flottante all'offerente, il cavaliere bianco lo compra")]
public static void TargetsCanDefend()
{
var w = WithIdleAi(405, competitors: 3);
var player = w.Player;
var target = w.Companies[1];
var knight = w.Companies[2];
Give(w, player, 50_000_000);
Give(w, knight, 50_000_000);
Give(w, target, 5_000_000);
player.Tier = 5;
w.RunDays(2);
long price = (long)Math.Ceiling(target.SharePrice * 1.3);
Assert.True(Do(w, new LaunchBidCommand(target.Id, new Money(price), 0.51), player).Ok);
var bid = w.Bids.Single();
long floatBefore = Corporate.FreeFloat(w, target);
var buyback = Do(w, new RespondBidCommand(bid.Id, false) { Defense = BidDefense.Buyback }, target);
Assert.True(buyback.Ok, buyback.Message);
Assert.True(Corporate.FreeFloat(w, target) < floatBefore, "il riacquisto riduce il flottante");
var white = Do(w, new RespondBidCommand(bid.Id, false) { Defense = BidDefense.WhiteKnight, Knight = knight.Id }, target);
if (Corporate.FreeFloat(w, target) > 0 || white.Ok) Assert.True(white.Ok || white.Error == CommandError.InsufficientFunds, white.Message);
Assert.Equal(0L, w.MoneyBalanceSum());
}
[Test(Description = "La controllata versa gli utili; dopo un anno di controllo si può fondere")]
public static void SubsidiaryPaysAndCanBeMerged()
{
var w = WithIdleAi(406);
var player = w.Player;
var sub = w.Companies[1];
Give(w, player, 50_000_000);
// il giocatore compra il 60 % dal fondatore privato (come dopo un'offerta riuscita)
long stake = (long)(sub.Shares.Total * 0.6);
sub.Shares.Founder -= stake;
sub.Shares.Add(player.Id, stake);
w.RunDays(2);
Assert.Equal(player.Id, sub.ControlledBy);
Assert.Equal(CommandError.NotAllowed, Do(w, new MergeCompanyCommand(sub.Id), player).Error, "serve un anno di controllo");
w.RunDays(w.Data.Balance.StockMarket.MergeAfterDays + 1);
int trainsBefore = w.Trains.Count(t => t.Owner == player.Id);
var merge = Do(w, new MergeCompanyCommand(sub.Id), player);
Assert.True(merge.Ok, merge.Message);
Assert.True(sub.Merged && sub.Defunct);
Assert.Equal(CommandError.NotAllowed, Do(w, new TakeLoanCommand(Money.FromLire(1000)), sub).Error, "la fusa non dà più comandi");
Assert.True(w.Trains.Count(t => t.Owner == player.Id) >= trainsBefore);
Assert.Equal(0L, w.MoneyBalanceSum());
}
/// <summary>Un'IA prende più del 50 % del giocatore quotato.</summary>
private static (World W, Company Ai) PlayerTakenOver(string difficulty)
{
var w = WithIdleAi(407, difficulty);
var player = w.Player;
var ai = w.Companies[1];
w.RunDays(2);
if (!player.Listed) Corporate.InitShares(w, player, true, 0.45);
long stake = (long)(player.Shares.Total * 0.55);
long fromPublic = Math.Min(stake, player.Shares.Public);
player.Shares.Public -= fromPublic;
player.Shares.Founder -= stake - fromPublic;
player.Shares.Add(ai.Id, stake);
w.RunDays(2);
return (w, ai);
}
[Test(Description = "Se l'IA compra il giocatore: amministrazione controllata (Imprenditore), fine immediata (Ferro e sangue), mai (Apprendista)")]
public static void PlayerTakeoverOutcomesByDifficulty()
{
// Imprenditore: amministrazione controllata per 3 anni, niente prestiti, riscatto possibile
var (w, ai) = PlayerTakenOver("imprenditore");
var player = w.Player;
Assert.True(player.Receivership, "amministrazione controllata");
Assert.True(w.GameOver is null, "la partita continua");
Assert.Equal(w.Clock.Day - 2 + 3L * w.Calendar.DaysPerYear, player.ReceivershipUntilDay, "3 anni per il riscatto");
Assert.Equal(CommandError.NotAllowed, Do(w, new TakeLoanCommand(Money.FromLire(1000)), player).Error);
Give(w, player, 100_000_000);
long max = (long)(player.Shares.Total * w.Data.Balance.StockMarket.MaxDailyTradeShare);
for (int i = 0; i < 40 && player.Receivership; i++)
{
var r = Do(w, new BuySharesCommand(player.Id, max, Money.Zero), player);
Assert.True(r.Ok, r.Message);
w.RunDays(1);
}
Assert.False(player.Receivership, $"riscatto riuscito: fondatore al {player.Shares.FounderFraction:P0}");
// Ferro e sangue: fine immediata, poi si osserva
var (w2, ai2) = PlayerTakenOver("ferro_e_sangue");
Assert.NotNull(w2.GameOver);
Assert.Equal(GameOverReason.Takeover, w2.GameOver!.Reason);
Assert.Equal(ai2.Id, w2.GameOver.Winner);
Assert.Equal(CommandError.NotAllowed, Do(w2, new TakeLoanCommand(Money.FromLire(1000)), w2.Player).Error, "osservatore");
w2.RunDays(10); // il mondo continua
// Apprendista: nessuna IA può superare il 50 % del giocatore
var w3 = WithIdleAi(408, "apprendista");
var p3 = w3.Player;
var ai3 = w3.Companies[1];
Corporate.InitShares(w3, p3, true, 0.3);
Give(w3, ai3, 100_000_000);
w3.RunDays(1);
long chunk = (long)(p3.Shares.Total * w3.Data.Balance.StockMarket.MaxDailyTradeShare);
CommandResult last = null!;
for (int i = 0; i < 20; i++) last = Do(w3, new BuySharesCommand(p3.Id, chunk, Money.Zero), ai3);
Assert.Equal(CommandError.NotAllowed, last.Error);
Assert.True(p3.Shares.FractionOf(ai3.Id) <= 0.5);
Assert.Equal(CommandError.NotAllowed, Do(w3, new LaunchBidCommand(p3.Id, new Money(1), 0.51), ai3).Error);
}
[Test(Description = "Un'IA fallita va all'asta: il giocatore se ne aggiudica gli attivi")]
public static void BankruptAiIsAuctioned()
{
var w = WithIdleAi(409);
var player = w.Player;
var ai = w.Companies[1];
Give(w, player, 10_000_000);
w.RunDays(2);
ai.Bankrupt = true;
w.RunDays(1);
var auction = w.Auctions.Single(a => a.Seller == ai.Id);
long perShare = auction.MinPriceCents / ai.Shares.Total + 1;
var offer = Do(w, new LaunchBidCommand(ai.Id, new Money(perShare), 1), player);
Assert.True(offer.Ok, offer.Message);
w.RunDays(w.Data.Balance.StockMarket.AuctionDays + 1);
Assert.True(ai.Merged, "attivi passati al compratore");
Assert.Equal(player.Id, ai.MergedInto);
Assert.Equal(0L, w.MoneyBalanceSum());
}
[Test(Description = "Offerte, soci, amministrazione controllata e storico sopravvivono al salvataggio")]
public static void CorporateStateSurvivesSaveAndLoad()
{
var w = WithIdleAi(410, "magnate");
var player = w.Player;
Give(w, player, 50_000_000);
player.Tier = 5;
w.RunDays(370);
var target = w.Companies[1];
long price = (long)Math.Ceiling(target.SharePrice * 1.3);
Assert.True(Do(w, new LaunchBidCommand(target.Id, new Money(price), 0.6), player).Ok);
w.RunDays(5);
var bytes = SaveFile.Save(w, "test");
var loaded = SaveFile.Load(TestData.Data, bytes);
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded));
w.RunDays(30);
loaded.RunDays(30);
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded));
Assert.True(player.History.Count >= 1, "storico annuale");
}
}
@@ -99,8 +99,31 @@ public static class ProtocolTests
yield return new MarketTape yield return new MarketTape
{ {
Day = 90, Day = 90,
Shares = [new SharePrice { Company = 1, Price = new Money(1234), Change = -0.02f, Listed = true }], Shares = [new SharePrice { Company = 1, Price = new Money(1234), Change = -0.02f, Listed = true, PriceCents = 1234.25, Outstanding = 990_000, FreeFloat = 300_000, FounderShare = 0.6f, ControlledBy = 2 }],
Bids = [new BidInfo { Bid = 1, Bidder = 2, Target = 0, PricePerShare = new Money(1500), TargetShare = 0.51, ExpiresDay = 180 }], Bids = [new BidInfo { Bid = 1, Bidder = 2, Target = 0, PricePerShare = new Money(1500), TargetShare = 0.51, ExpiresDay = 180, State = 1, CommittedShare = 0.42, Defenses = 3, Knight = 3, Accepted = true }],
};
yield return new CompanyCard
{
Company = 1, TotalShares = 1_000_000, Treasury = 10_000,
Holdings = [new HoldingInfo { Holder = HoldingInfo.Founder, Shares = 600_000 }, new HoldingInfo { Holder = HoldingInfo.Market, Shares = 290_000 }, new HoldingInfo { Holder = 2, Shares = 100_000 }],
PriceHistory = [12.5, 13.25, 14],
History = [new CompanyYearInfo { Year = 1851, NetWorth = new Money(500), Cash = new Money(-20), Revenue = new Money(900), Profit = new Money(-30), Tier = 2, Trains = 4, TrackKm = 12.5f, SharePrice = new Money(13) }],
AnnualProfit = new Money(-123), DividendsYear = new Money(45), Debt = new Money(678), MarketCap = new Money(9_000_000), ControlDays = 400,
AuctionMin = new Money(10), AuctionBest = new Money(20), AuctionBestBidder = 3, AuctionEndDay = 999,
};
yield return new IndustryCard
{
Industry = 4, Margin = -0.1f, ConditionMultiplier = 0.8f, WearPerDay = 0.05f, RecoveryPerDay = 0.12f, MaintenanceCostPerDay = new Money(77),
MaintenanceSpentYear = new Money(9999), PartsTarget = 9, PartsPerMonth = 3, PartsOrdered = 20, MachineryRequired = 6, UpgradeCost = new Money(3_000_000),
Valuation = new Money(4_500_000), Cash = new Money(2_000_000), BreakdownChancePerYear = 0.3f,
Stops = [new IndustryStopInfo { Day = 300, Days = 12, Kind = 1 }, new IndustryStopInfo { Day = 500, Days = 30, Kind = 3 }],
};
yield return new Chronicle
{
GameOver = true, Reason = 2, Text = "La Predatoria prende il controllo", Winner = 2, Day = 3600, Company = "Società", FoundedYear = 1850, Prestige = 1234,
History = [new CompanyYearInfo { Year = 1850, NetWorth = new Money(1), Tier = 1 }],
Records = [new RecordInfo { Title = "Patrimonio massimo", Value = "₤ 1.000.000", Year = 1855 }],
Highlights = ["Fondata nel 1850", "Livello 3 nel 1858"],
}; };
yield return new CommandResultMessage { Seq = 99, Type = (ushort)CommandType.BuildTrack, Error = 10, Message = "Pendenza eccessiva", Created = [1, 2, 3], Tick = 4000 }; yield return new CommandResultMessage { Seq = 99, Type = (ushort)CommandType.BuildTrack, Error = 10, Message = "Pendenza eccessiva", Created = [1, 2, 3], Tick = 4000 };
yield return new Notification { Event = SampleEvent() }; yield return new Notification { Event = SampleEvent() };
@@ -137,9 +160,18 @@ public static class ProtocolTests
private static EntityLists SampleEntities() => new() private static EntityLists SampleEntities() => new()
{ {
Companies = [new CompanyInfo { Id = 0, Name = "Società", Color = "#b3573e", IsPlayer = true, Cash = new Money(100), NetWorth = new Money(200), Rating = "A", Tier = 2, MaintenancePolicy = 2 }], Companies = [new CompanyInfo
{
Id = 0, Name = "Società", Color = "#b3573e", IsPlayer = true, Cash = new Money(100), NetWorth = new Money(200), Rating = "A", Tier = 2, MaintenancePolicy = 2,
Personality = "predatory", Listed = true, SharePriceCents = 22.75, Sentiment = 1.1f, FounderShare = 0.55f, ControlledBy = 2, Merged = true,
Receivership = true, ReceivershipUntilDay = 777, AnnualProfit = new Money(-5),
}],
Towns = [new TownInfo { Id = 0, Name = "Valdoria", Position = P, Population = 12400, RadiusCells = 4.5, Satisfaction = 0.6f, Services = 3 }], Towns = [new TownInfo { Id = 0, Name = "Valdoria", Position = P, Population = 12400, RadiusCells = 4.5, Satisfaction = 0.6f, Services = 3 }],
Industries = [new IndustryInfo { Id = 1, Type = "steel_mill", Name = "Acciaieria", Position = P, FootprintCells = 4, Level = 2, Efficiency = 0.83f, Condition = 97, Owner = -1 }], Industries = [new IndustryInfo
{
Id = 1, Type = "steel_mill", Name = "Acciaieria", Position = P, FootprintCells = 4, Level = 2, Efficiency = 0.83f, Condition = 97, Owner = -1,
Budget = 2, SpareParts = 5, Machinery = 3, StoppedUntilDay = 1234, StopKind = 3, PendingWork = 2, PartsShort = true,
}],
Hubs = [new HubInfo { Id = 0, Kind = "port", Name = "Porto", Position = P }], Hubs = [new HubInfo { Id = 0, Kind = "port", Name = "Porto", Position = P }],
Nodes = [new NodeInfo { Id = 3, Position = P, HeightM = 120.5, Owner = 0, Station = 1, Depot = -1, Edges = [1, 4] }], Nodes = [new NodeInfo { Id = 3, Position = P, HeightM = 120.5, Owner = 0, Station = 1, Depot = -1, Edges = [1, 4] }],
Stations = [new StationInfo { Id = 1, Owner = 0, Name = "Acciaieria", Node = 3, Position = P, Platforms = 4, WaitingUnits = 30, Industries = [1], Towns = [0] }], Stations = [new StationInfo { Id = 1, Owner = 0, Name = "Acciaieria", Node = 3, Position = P, Platforms = 4, WaitingUnits = 30, Industries = [1], Towns = [0] }],
@@ -178,6 +210,7 @@ public static class ProtocolTests
yield return new SetMaintenancePolicyCommand(MaintenanceScope.Line, 2, "thorough"); yield return new SetMaintenancePolicyCommand(MaintenanceScope.Line, 2, "thorough");
yield return new ScheduleServiceCommand(new TrainId(4), "overhaul"); yield return new ScheduleServiceCommand(new TrainId(4), "overhaul");
yield return new OrderPartsCommand(new DepotId(1), 30); yield return new OrderPartsCommand(new DepotId(1), 30);
yield return new OrderPartsCommand(DepotId.None, 25) { Industry = new IndustryId(4) };
yield return new TakeLoanCommand(Money.FromLire(50000)); yield return new TakeLoanCommand(Money.FromLire(50000));
yield return new RepayLoanCommand(new LoanId(1), new Money(999)); yield return new RepayLoanCommand(new LoanId(1), new Money(999));
yield return new AcceptAgreementCommand(new AgreementId(5)); yield return new AcceptAgreementCommand(new AgreementId(5));
@@ -194,10 +227,12 @@ public static class ProtocolTests
yield return new PayDividendCommand(new Money(12)); yield return new PayDividendCommand(new Money(12));
yield return new LaunchBidCommand(new CompanyId(1), new Money(2000), 0.51); yield return new LaunchBidCommand(new CompanyId(1), new Money(2000), 0.51);
yield return new RespondBidCommand(new BidId(1), false); yield return new RespondBidCommand(new BidId(1), false);
yield return new RespondBidCommand(new BidId(2), false) { Defense = BidDefense.WhiteKnight, Knight = new CompanyId(3) };
yield return new BuyConcessionCommand(new RegionId(2)); yield return new BuyConcessionCommand(new RegionId(2));
yield return new AcceptContractCommand(new ContractId(8)); yield return new AcceptContractCommand(new ContractId(8));
yield return new FundResearchCommand("electric_traction", Money.FromLire(20000)); yield return new FundResearchCommand("electric_traction", Money.FromLire(20000));
yield return new DelegateRegionCommand(new RegionId(1), "crescita", Money.FromLire(500000)); yield return new DelegateRegionCommand(new RegionId(1), "crescita", Money.FromLire(500000));
yield return new MergeCompanyCommand(new CompanyId(2));
} }
[Test(Description = "Ogni messaggio del protocollo ha un esemplare e sopravvive a codifica e decodifica byte per byte")] [Test(Description = "Ogni messaggio del protocollo ha un esemplare e sopravvive a codifica e decodifica byte per byte")]
@@ -1,6 +1,7 @@
using ViaFerrea.Core.Commands; using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common; using ViaFerrea.Core.Common;
using ViaFerrea.Core.Rail; using ViaFerrea.Core.Rail;
using ViaFerrea.Core.Simulation;
using ViaFerrea.Core.Simulation.Systems; using ViaFerrea.Core.Simulation.Systems;
using ViaFerrea.Tests.Harness; using ViaFerrea.Tests.Harness;
using static ViaFerrea.Tests.Rail.RailFixture; using static ViaFerrea.Tests.Rail.RailFixture;
@@ -61,7 +62,9 @@ public static class RailNetworkTests
public static void CrossingForeignTrackBuildsAnOverpass() public static void CrossingForeignTrackBuildsAnOverpass()
{ {
var f = Valdoria(); var f = Valdoria();
var rival = f.W.Companies.First(c => !c.IsPlayer).Id; // lo scenario non ha concorrenti: se ne aggiunge uno fermo (agenti sospesi)
f.W.AiPaused = true;
var rival = WorldFactory.CreateAiCompany(f.W, f.W.Stream("companies")).Id;
f.Ok(new BuildTrackCommand(new[] { K(11.0, 9.5), K(14.0, 9.5) }), rival); f.Ok(new BuildTrackCommand(new[] { K(11.0, 9.5), K(14.0, 9.5) }), rival);
var r = f.Do(new BuildTrackCommand(new[] { K(12.5, 8.8), K(12.5, 10.2) })); var r = f.Do(new BuildTrackCommand(new[] { K(12.5, 8.8), K(12.5, 10.2) }));
Assert.True(r.Ok, r.Message); Assert.True(r.Ok, r.Message);
+11
View File
@@ -9,6 +9,17 @@ public static class TestWorlds
public static World Small(ulong seed = 42, string difficulty = "imprenditore") => public static World Small(ulong seed = 42, string difficulty = "imprenditore") =>
WorldFactory.Create(TestData.Data, new NewGameSettings { Seed = seed, SizeKm = 64, DifficultyId = difficulty }); WorldFactory.Create(TestData.Data, new NewGameSettings { Seed = seed, SizeKm = 64, DifficultyId = difficulty });
/// <summary>Mondo piccolo con i ritocchi di difficoltà indicati (es. nessun concorrente IA).</summary>
public static World Small(ulong seed, string difficulty, params (string Key, double Value)[] overrides) =>
WorldFactory.Create(TestData.Data, new NewGameSettings
{
Seed = seed, SizeKm = 64, DifficultyId = difficulty,
DifficultyOverride = Core.Data.DifficultyOverrides.Apply(TestData.Data.DifficultyPreset(difficulty), overrides),
});
/// <summary>Mondo piccolo senza concorrenti IA.</summary>
public static World NoAi(ulong seed = 42, string difficulty = "imprenditore") => Small(seed, difficulty, ("aiCompetitors", 0));
public static GeneratedMap Map(ulong seed, int sizeKm) => public static GeneratedMap Map(ulong seed, int sizeKm) =>
MapGenerator.Generate(TestData.Data, new MapSpec(seed, sizeKm, TestData.Data.Balance.Time.DefaultStartYear)); MapGenerator.Generate(TestData.Data, new MapSpec(seed, sizeKm, TestData.Data.Balance.Time.DefaultStartYear));
} }
@@ -4,6 +4,7 @@
"seed": 1872, "seed": 1872,
"startYear": 1850, "startYear": 1850,
"difficulty": "imprenditore", "difficulty": "imprenditore",
"aiCompetitors": 0,
"terrain": { "terrain": {
"widthCells": 160, "widthCells": 160,
"heightCells": 120, "heightCells": 120,