Compare commits
32
Commits
a61bf1dc27
..
v0.7.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
27fc1e920e | ||
|
|
5acb8d6d2b | ||
|
|
f275c67688 | ||
|
|
b0191e4b93 | ||
|
|
67a3dd05f9 | ||
|
|
3d394c01d3 | ||
|
|
4bea03ab6b | ||
|
|
69416e7db8 | ||
|
|
4beedd2e75 | ||
|
|
19a3dd3af1 | ||
|
|
1579f63287 | ||
|
|
64209afd5f | ||
|
|
2e781bbba2 | ||
|
|
767661957b | ||
|
|
fe97cf4616 | ||
|
|
0667a4a544 | ||
|
|
c84c16605e | ||
|
|
4ce3912f03 | ||
|
|
b7737455c6 | ||
|
|
ebe4308e75 | ||
|
|
e1d47fff54 | ||
|
|
e75c8e1586 | ||
|
|
45462bf9ec | ||
|
|
f7c286bf1d | ||
|
|
b1ee6879a7 | ||
|
|
7eec322202 | ||
|
|
8b3a9bdb9c | ||
|
|
1f8830337a | ||
|
|
9bf64b9286 | ||
|
|
c041afd8f7 | ||
|
|
2e5215c570 | ||
|
|
d473e21708 |
No files matched your search
@@ -9,7 +9,7 @@ La specifica vincolante è `docs/GUIDA.md`; lo stato dei lavori è in `docs/STAT
|
||||
scripts/build.sh # check-nuget + build Release della soluzione
|
||||
scripts/test.sh [filtri] # build + validate-data + tutti i test (--skip-slow, --serial)
|
||||
dotnet run --project tests/RailEnterprise.Tests -- --list
|
||||
dotnet run --project src/RailEnterprise.Tools -- <comando> # validate-data, genmap, profile, simulate, bench, replay
|
||||
dotnet run --project src/RailEnterprise.Tools -- <comando> # validate-data, genmap, profile, simulate, balance, bench, replay
|
||||
```
|
||||
|
||||
## Regole non negoziabili
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<!-- Impostazioni comuni a tutti i progetti .NET di Rail Enterprise (il client Godot ha il proprio). -->
|
||||
<PropertyGroup>
|
||||
<!-- Unica fonte della versione: letta anche da scripts/publish-image.sh e dal protocollo. -->
|
||||
<Version>0.6.0</Version>
|
||||
<Version>0.7.0</Version>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<LangVersion>latest</LangVersion>
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
keys,it,en
|
||||
a piena capacità,,at full capacity
|
||||
Abitanti,,Population
|
||||
Accetta,,Accept
|
||||
Acquista,,Buy
|
||||
Aderisci con le tue azioni,,Tender your shares
|
||||
adesso,,just now
|
||||
Aggiorna,,Refresh
|
||||
al giorno,,per day
|
||||
Alto,,High
|
||||
Ambra,,Amber
|
||||
Amministrazione controllata,,Receivership
|
||||
@@ -20,23 +23,29 @@ Assegna,,Assign
|
||||
Asta degli attivi,,Asset auction
|
||||
Attendi il pieno alla prima fermata (max 2 giorni),,Wait for full load at the first stop (max 2 days)
|
||||
Attiva,,Active
|
||||
Attivo da,,Up for
|
||||
automatico,,automatic
|
||||
Avvio del server locale…,,Starting the local server…
|
||||
Azioni proprie (non votano),,Treasury shares (no vote)
|
||||
Base,,Base
|
||||
Base d'asta,,Reserve price
|
||||
bastano per,,enough for
|
||||
Binari,,Track
|
||||
Binari di stazione,,Platforms
|
||||
Blu,,Blue
|
||||
Budget di manutenzione,,Maintenance budget
|
||||
C'è già un'offerta in corso su questa compagnia: la trovi nell'elenco a sinistra.,,There is already a bid on this company: see the list on the left.
|
||||
Cantiere,,Construction
|
||||
Capacità ridotta da un evento,,Capacity reduced by an event
|
||||
Capitalizz.,,Market cap
|
||||
Capitalizzazione,,Market cap
|
||||
Caricamento di,,Loading
|
||||
Carico,,Load
|
||||
Cartella di manutenzione,,Maintenance record
|
||||
Cartella in arrivo dal server…,,Record on its way from the server…
|
||||
Cassa,,Cash
|
||||
Cassa dell'industria,,Industry cash
|
||||
Catena produttiva,,Production chain
|
||||
Cavaliere bianco,,White knight
|
||||
Celeste,,Light blue
|
||||
"Chi offre di più alla chiusura compra treni, binari, stazioni e industrie della compagnia fallita.",,"The highest bidder at closing buys the bankrupt company's trains, track, stations and industries."
|
||||
@@ -334,10 +343,18 @@ capacità mancante da,,capacity short for
|
||||
carica,,load
|
||||
cavaliere bianco,,white knight
|
||||
città senza servizi per il personale,,towns without services for staff
|
||||
Client collegati,,Connected clients
|
||||
Collo di bottiglia,,Bottleneck
|
||||
Condizione degli impianti,,Plant condition
|
||||
Connetti a un server,,Connect to a server
|
||||
Connetti e riprendi,,Connect and resume
|
||||
consumo,,use
|
||||
controlla la compagnia,,controls the company
|
||||
controllata da,,controlled by
|
||||
copertura,,coverage
|
||||
Copertura degli ingressi,,Input coverage
|
||||
Crea una linea verso questa industria,,Build a line to this industry
|
||||
Creazione della nuova partita sul server…,,Creating the new game on the server…
|
||||
da,,from
|
||||
degli utili come dividendo e non puoi chiedere prestiti.,,of profits as dividends and cannot take new loans.
|
||||
dei ricavi,,of revenue
|
||||
@@ -346,28 +363,44 @@ del capitale per ordine.,,of the capital per order.
|
||||
della cassa (il titolo sale); cavaliere bianco: un'alleata compra il flottante al prezzo dell'offerta più il,,of cash (the share price rises); white knight: an ally buys the free float at the bid price plus
|
||||
delle azioni entro il,,of the shares by
|
||||
di,,of
|
||||
Disponibile al livello,,Available at level
|
||||
dividendo straordinario,,extra dividend
|
||||
Dove gira il motore di gioco?,,Where does the game engine run?
|
||||
durata,,duration
|
||||
e altre,,and
|
||||
e il,,and
|
||||
e personale sufficiente,,and enough staff
|
||||
Fai un'offerta di acquisto,,Make a purchase offer
|
||||
fallita,,bankrupt
|
||||
"fallita, attivi all'asta",,"bankrupt, assets at auction"
|
||||
Fattore di redditività,,Profitability factor
|
||||
ferma,,stopped
|
||||
ferma fino al,,stopped until
|
||||
fermo in linea,,stranded on the line
|
||||
fermo in salita,,stalled on grade
|
||||
Forza lavoro,,Workforce
|
||||
g,,d
|
||||
Giacimento residuo,,Remaining reserve
|
||||
Gioca in locale,,Play locally
|
||||
giorni,,days
|
||||
giorni di fermo,,days of shutdown
|
||||
giorni di produzione,,days of production
|
||||
giorni e liquida le minoranze al prezzo di mercato.,,days and buys out the minorities at market price.
|
||||
giorni e offre un premio tra il,,days and offers a premium between
|
||||
giorni fa,,days ago
|
||||
giorno,,day
|
||||
gli impianti rendono pieno; sotto calano fino a,,plants run at full output; below they drop to
|
||||
guasto,,broken down
|
||||
guasto lieve,,minor failure
|
||||
hub mercato mondiale,,world market hub
|
||||
i lavoratori,,workers
|
||||
il fondatore ha,,the founder holds
|
||||
"Il mondo vive sempre in un server: sul tuo computer, avviato insieme al gioco, oppure in rete, dove la partita continua anche a gioco chiuso.",,"The world always lives in a server: on your computer, started together with the game, or on the network, where the game goes on even when the client is closed."
|
||||
il personale qualificato,,skilled staff
|
||||
Il server ha chiuso la connessione,,The server closed the connection
|
||||
Il server non ha risposto,,The server did not respond
|
||||
impegnato,,committed
|
||||
Impianti e crescita,,Plant and growth
|
||||
in arrivo,,arriving
|
||||
in attesa,,waiting
|
||||
in attesa di via libera,,waiting for clearance
|
||||
@@ -378,19 +411,33 @@ in officina,,in the workshop
|
||||
in scorta,,in stock
|
||||
in servizio,,in service
|
||||
in stazione,,at station
|
||||
inattiva,,inactive
|
||||
incasso stimato,,estimated proceeds
|
||||
intervento prenotato,,intervention booked
|
||||
L'industria è tua: gli utili entrano nel conto economico della compagnia.,,The industry is yours: its profits go into the company's income statement.
|
||||
la fusione è possibile dopo,,the merger is possible after
|
||||
la tua compagnia,,your company
|
||||
large,Grande,Large
|
||||
Latenza,,Latency
|
||||
lavoratori,,workers
|
||||
lavori,,jobs
|
||||
le città raggiungibili non hanno lavoratori liberi,,reachable towns have no free workers
|
||||
limitata da un evento,,limited by an event
|
||||
limitata dagli impianti,,limited by the plant
|
||||
limitata dai lavoratori,,limited by workers
|
||||
limitata dal giacimento,,limited by the reserve
|
||||
limitata dal personale,,limited by staff
|
||||
limitata dalla redditività,,limited by profitability
|
||||
limitata dalle materie prime,,limited by raw materials
|
||||
linea,,line
|
||||
livello,,level
|
||||
Livello massimo raggiunto,,Maximum level reached
|
||||
locale,,local
|
||||
macchinari,,machinery
|
||||
macchinari per il prossimo lavoro,,machinery for the next job
|
||||
macchinari per livello,,machinery per level
|
||||
Mancano,,Missing
|
||||
Mappa,,Map
|
||||
medium,Medio,Medium
|
||||
mesi,,months
|
||||
mila km,,thousand km
|
||||
@@ -498,22 +545,55 @@ in 30 giorni,,in 30 days
|
||||
lug,,Jul
|
||||
mag,,May
|
||||
mar,,Mar
|
||||
Materie prime in ingresso,,Incoming raw materials
|
||||
mese,,month
|
||||
mesi e previsione a,,months and forecast for
|
||||
minuti fa,,minutes ago
|
||||
Moltiplicatore di resa,,Output multiplier
|
||||
"nei magazzini delle industrie e nelle stazioni, divise per la domanda mensile della mappa",,"in industry storage and at stations, divided by the map's monthly demand"
|
||||
Nessun cliente nella regione,,No customer in the region
|
||||
Nessun posto per i lavoratori,,No jobs for workers
|
||||
Nessun posto per il personale,,No jobs for staff
|
||||
Nessun vettore la serve: il livello resta fermo finché una linea non la collega.,,No carrier serves it: the level stays put until a line connects it.
|
||||
Nessuna produzione,,No production
|
||||
nessuna stazione la serve,,no station serves it
|
||||
nessuna tua stazione servita da una linea con treni ha questa destinazione nel bacino,,none of your stations served by a line with trains has this destination in its catchment
|
||||
non collegata,,not connected
|
||||
non collegato,,not connected
|
||||
Non collegato,,Not connected
|
||||
nov,,Nov
|
||||
Nuova partita sul server,,New game on the server
|
||||
oggi,,today
|
||||
ore fa,,hours ago
|
||||
ott,,Oct
|
||||
Partita in corso,,Current game
|
||||
perde un livello,,it loses a level
|
||||
Personale qualificato,,Skilled staff
|
||||
persone: portale in treno dalle città vicine.,,people: bring them by train from nearby towns.
|
||||
presenti,,present
|
||||
prev.,,fcst.
|
||||
prezzo mondiale in calo,,world price falling
|
||||
prezzo mondiale in rialzo,,world price rising
|
||||
Produzione,,Production
|
||||
proprietari privati,,private owners
|
||||
provenienze,,more origins
|
||||
Punteggio di crescita,,Growth score
|
||||
quota mondiale dagli hub,,world share through the hubs
|
||||
recupero,,recovery
|
||||
rispetto al ciclo per circa,,compared with the cycle for about
|
||||
Scegli un'industria nell'elenco in alto.,,Choose an industry from the list above.
|
||||
Scheda dell'industria,,Industry sheet
|
||||
scorta,,stock
|
||||
serve,,needs
|
||||
"Server su questo computer, avviato e chiuso con il gioco. Le partite restano qui.",,"Server on this computer, started and stopped with the game. Games stay here."
|
||||
servita dalla stazione,,served by station
|
||||
servita dalla tua linea,,served by your line
|
||||
set,,Sep
|
||||
Sistema,,System
|
||||
sopra,,above
|
||||
sotto,,below
|
||||
spedito,,shipped
|
||||
tick al secondo,,ticks per second
|
||||
unità/mese,,units/month
|
||||
è più alto del,,is higher by
|
||||
è più basso del,,is lower by
|
||||
@@ -550,3 +630,486 @@ entro,,within
|
||||
fino al,,until
|
||||
da domani,,from tomorrow
|
||||
dal,,from
|
||||
La tua scalata,,Your climb
|
||||
Stato patrimoniale,,Balance sheet
|
||||
Chiedi un prestito,,Request a loan
|
||||
In attesa del quadro dal server…,,Waiting for the report from the server…
|
||||
Fido fino a,,Credit up to
|
||||
squadre di cantiere,,construction crews
|
||||
Acquisto di industrie,,Industry purchases
|
||||
Scalate ai concorrenti,,Takeovers of rivals
|
||||
Concessioni,,Concessions
|
||||
fondata nel,,founded in
|
||||
con,,with
|
||||
magazzino,,storage
|
||||
Partite salvate sul server,,Games saved on the server
|
||||
verso,,towards
|
||||
raggiunta nel,,reached in
|
||||
raggiunta,,reached
|
||||
avanzamento,,progress
|
||||
patrimonio,,net worth
|
||||
Lo storico cresce anno dopo anno,,The history grows year by year
|
||||
a,,to
|
||||
in,,in
|
||||
anno,,year
|
||||
Hai raggiunto il livello più alto,,You have reached the highest tier
|
||||
Per diventare,,To become
|
||||
Patrimonio netto di,,Net worth of
|
||||
città oltre,,towns over
|
||||
collegata su,,connected out of
|
||||
collegate su,,connected out of
|
||||
merci su linea,,goods on a line
|
||||
Rating creditizio,,Credit rating
|
||||
attuale,,current
|
||||
Binari e opere,,Track and structures
|
||||
Stazioni e depositi,,Stations and depots
|
||||
Materiale rotabile,,Rolling stock
|
||||
Industrie possedute,,Owned industries
|
||||
magazzino pieno,,storage full
|
||||
Merce propria,,Own goods
|
||||
Nessun fornitore nella regione,,No supplier in the region
|
||||
"Non consuma materie prime: estrae, coltiva o raccoglie da sé.",,"It consumes no raw materials: it mines, farms or gathers on its own."
|
||||
Partecipazioni,,Shareholdings
|
||||
"Server dedicato in rete, per esempio in Docker su un NAS. Più giocatori, partita sempre accesa.",,"Dedicated server on the network, for example in Docker on a NAS. Several players, the game is always on."
|
||||
Totale attivo,,Total assets
|
||||
Prestiti al,,Loans at
|
||||
Prestiti,,Loans
|
||||
Scoperto di cassa,,Overdraft
|
||||
Conto economico,,Income statement
|
||||
(finora),,(so far)
|
||||
Ricavi da tariffe e noli,,Fares and freight revenue
|
||||
Altri ricavi,,Other income
|
||||
Costi operativi,,Operating costs
|
||||
Interessi,,Interest
|
||||
Utile netto,,Net profit
|
||||
Rimborsa,,Repay
|
||||
Fido disponibile,,Available credit
|
||||
su,,of
|
||||
al,,at
|
||||
In amministrazione controllata non si possono chiedere prestiti,,Loans cannot be requested under receivership
|
||||
livello più alto,,highest tier
|
||||
prossimo,,next
|
||||
Clic per aprire «La tua scalata»,,Click to open «Your climb»
|
||||
Scalata,,Climb
|
||||
Mesi,,Months
|
||||
Anni,,Years
|
||||
patrimonio netto,,net worth
|
||||
Bancarotta dichiarata,,Bankruptcy declared
|
||||
La compagnia non ha riportato la cassa sopra zero entro il limite della difficoltà.,,The company did not bring its cash back above zero within the difficulty limit.
|
||||
in corso,,in progress
|
||||
finora,,so far
|
||||
utile,,profit
|
||||
Utile annuo stimato,,Estimated annual profit
|
||||
Valore stimato,,Estimated value
|
||||
Voce,,Item
|
||||
Utile operativo,,Operating profit
|
||||
Flusso di cassa,,Cash flow
|
||||
I mesi e gli anni chiusi compaiono qui man mano che passano.,,Closed months and years appear here as they go by.
|
||||
"L'utile operativo comprende ricavi e costi d'esercizio; investimenti, prestiti e azioni cambiano solo la cassa.",,"Operating profit includes revenue and operating costs; investments, loans and shares only change cash."
|
||||
Costi,,Costs
|
||||
Investimenti e finanziamenti,,Investments and financing
|
||||
Noli merci,,Freight fares
|
||||
Biglietti passeggeri,,Passenger tickets
|
||||
Commercio in proprio,,Own trading
|
||||
Contratti,,Contracts
|
||||
Controllate,,Subsidiaries
|
||||
Dividendi incassati,,Dividends received
|
||||
Esercizio dei treni,,Train operation
|
||||
Manutenzione dei treni,,Train maintenance
|
||||
Manutenzione dei binari,,Track maintenance
|
||||
Stipendi,,Wages
|
||||
Dazi,,Duties
|
||||
Magazzini,,Storage
|
||||
Penali,,Penalties
|
||||
Costruzioni,,Construction
|
||||
Acquisto di treni,,Train purchases
|
||||
ultimo trimestre,,last quarter
|
||||
usura,,wear
|
||||
Vendita di treni,,Train sales
|
||||
Prestiti ricevuti,,Loans received
|
||||
Prestiti rimborsati,,Loans repaid
|
||||
Azioni,,Shares
|
||||
Dividendi pagati,,Dividends paid
|
||||
Altro,,Other
|
||||
Rating iniziale: il primo calcolo arriva a inizio mese. Le misure qui sotto sono quelle di oggi.,,Initial rating: the first calculation comes at the start of the month. The measures below are today's.
|
||||
Calcolato a inizio mese sugli ultimi,,Calculated at the start of the month over the last
|
||||
mese chiuso,,closed month
|
||||
mesi chiusi,,closed months
|
||||
Punteggio,,Score
|
||||
Margine (utile / ricavi),,Margin (profit / revenue)
|
||||
patrimonio non positivo,,non-positive equity
|
||||
Leva (debiti / patrimonio netto),,Leverage (debt / net worth)
|
||||
In bancarotta il rating è D finché la situazione non si risolve.,,While bankrupt the rating is D until the situation is resolved.
|
||||
È il rating più alto: i prestiti costano il minimo.,,This is the highest rating: loans cost the least.
|
||||
serve migliorare insieme margine e leva,,margin and leverage must improve together
|
||||
oppure,,or
|
||||
Punteggio da,,Score from
|
||||
Tasso,,Rate
|
||||
componente,,component
|
||||
peso,,weight
|
||||
Nessun prestito in corso.,,No loans outstanding.
|
||||
Residuo,,Outstanding
|
||||
fisso,,fixed
|
||||
Rata mensile,,Monthly payment
|
||||
interessi,,interest
|
||||
pieno tra,,full in
|
||||
Ricorda questo server,,Remember this server
|
||||
scadenza,,maturity
|
||||
Estingui,,Pay off
|
||||
La cassa è tornata positiva,,Cash is back above zero
|
||||
"Dopo {0} di cassa negativa il conto alla rovescia della bancarotta si azzera domani.",,"After {0} of negative cash, the bankruptcy countdown resets tomorrow."
|
||||
Cassa negativa da oggi: bancarotta tra {0},,Cash negative since today: bankruptcy in {0}
|
||||
Cassa negativa da {0}: bancarotta tra {1},,Cash negative for {0}: bankruptcy in {1}
|
||||
"Scoperto {0}. Il limite della difficoltà è di {1}; riporta la cassa sopra zero con un prestito, vendendo treni o riducendo i costi.",,"Overdraft {0}. The difficulty limit is {1}; bring cash back above zero with a loan, by selling trains or by cutting costs."
|
||||
neutro,,neutral
|
||||
"Il margine conta da quando ci sono almeno {0} mesi chiusi con ricavi (ora {1}): fino ad allora vale 0, così i primi incassi non fanno crollare il rating.",,"The margin counts once there are at least {0} closed months with revenue (now {1}): until then it is 0, so the first takings do not sink the rating."
|
||||
"Il punteggio {0} vale già {1}: il rating si aggiorna al prossimo calcolo mensile, a inizio mese.",,"The score {0} is already worth {1}: the rating is updated at the next monthly calculation, at the start of the month."
|
||||
Simulazione,,Simulation
|
||||
trimestri sale,,quarters it rises
|
||||
un margine di almeno {0},,a margin of at least {0}
|
||||
una leva non oltre {0},,leverage no higher than {0}
|
||||
una leva non oltre {0} (rimborsando {1}),,leverage no higher than {0} (by repaying {1})
|
||||
"una leva non oltre {0} (servirebbe rimborsare {1}, più di quanto la cassa consenta oggi)",,"leverage no higher than {0} (it would take repaying {1}, more than cash allows today)"
|
||||
Per il gradino {0} serve un punteggio di {1}: {2}.,,To reach {0} you need a score of {1}: {2}.
|
||||
In bancarotta non si possono chiedere prestiti,,Loans cannot be requested while bankrupt
|
||||
Fido disponibile {0} su {1}. Tasso di un nuovo prestito: {2} fisso (base {3} + rating {4} {5}) per {6} anni.,,Available credit {0} of {1}. Rate of a new loan: {2} fixed (base {3} + rating {4} {5}) for {6} years.
|
||||
Avanti,,Next
|
||||
Salta passo,,Skip step
|
||||
Chiudi tutorial,,Close tutorial
|
||||
Tutorial,,Tutorial
|
||||
Riduci o espandi il riquadro del tutorial,,Collapse or expand the tutorial box
|
||||
Passo {0} di {1},,Step {0} of {1}
|
||||
Fine,,Finish
|
||||
Fatto,,Done
|
||||
Il tutorial si riapre con F1 o dalla schermata iniziale,,Reopen the tutorial with F1 or from the start screen
|
||||
Mostra il tutorial,,Show the tutorial
|
||||
Tutorial non disponibile: {0},,Tutorial not available: {0}
|
||||
Avvio della partita di prova del tutorial…,,Starting the tutorial practice game…
|
||||
Guida passo per passo alla prima linea: si chiude quando vuoi e si riapre con F1,,Step-by-step guide to your first line: close it whenever you like and reopen it with F1
|
||||
"Nuova partita locale di prova con il tutorial dal primo passo: la tua partita locale resta com'è",,"New practice local game with the tutorial from the first step: your own local game stays as it is"
|
||||
Benvenuto in Rail Enterprise,,Welcome to Rail Enterprise
|
||||
"Guidi una compagnia ferroviaria: costruisci binari e stazioni, trasporti merci e pendolari e fai crescere il patrimonio fino a dominare il mercato. Questo tutorial ti accompagna nella prima linea; puoi saltare un passo o chiuderlo quando vuoi.",,"You run a railway company: build track and stations, carry goods and commuters and grow your net worth until you dominate the market. This tutorial walks you through your first line; you can skip a step or close it whenever you like."
|
||||
Muovi la mappa,,Move the map
|
||||
Trascina con il tasto destro (o usa WASD e le frecce) per spostarti e gira la rotella per lo zoom. Cerca una città e un'industria vicine: saranno le due stazioni della prima linea.,,Drag with the right mouse button (or use WASD and the arrow keys) to move and turn the wheel to zoom. Look for a town and an industry close to each other: they will be the two stations of your first line.
|
||||
Il tempo,,Time
|
||||
"In alto scegli la velocità del gioco: II mette in pausa, 1× – 8× accelerano. Anche la barra spaziatrice mette in pausa e riprende. Cambia la velocità per proseguire.",,"At the top you choose the game speed: II pauses, 1× – 8× speed it up. The space bar also pauses and resumes. Change the speed to continue."
|
||||
Costruisci due stazioni,,Build two stations
|
||||
Apri lo strumento Stazione e fai clic sulla mappa vicino a un'industria e poi vicino a una città. Il cerchio è il bacino di utenza: le merci e i passeggeri arrivano solo da lì.,,Open the Station tool and click the map near an industry and then near a town. The circle is the catchment area: goods and passengers only come from inside it.
|
||||
Costruisci un deposito,,Build a depot
|
||||
"Con lo strumento Deposito posa un deposito vicino a una delle stazioni. Nel deposito si comprano i veicoli, si compongono i treni e si fanno le manutenzioni.",,"With the Depot tool place a depot near one of the stations. In the depot you buy vehicles, compose trains and carry out maintenance."
|
||||
Lo strumento Binari,,The Track tool
|
||||
Apri lo strumento Binari: scegli la classe del binario e se ammettere ponti e gallerie.,,Open the Track tool: choose the track class and whether to allow bridges and tunnels.
|
||||
Guarda il profilo e le opere,,Look at the profile and the structures
|
||||
"Fai clic sulla prima stazione e muovi il mouse verso la seconda: il profilo mostra il terreno e la quota del binario. Sotto compaiono rilevati, trincee, ponti e gallerie con lunghezza, pendenza, costo e giorni di cantiere. Se attraversi un fiume vedrai il ponte.",,"Click the first station and move the mouse towards the second: the profile shows the terrain and the height of the track. Below it you see embankments, cuttings, bridges and tunnels with length, gradient, cost and days of work. If you cross a river you will see the bridge."
|
||||
Costruisci il binario,,Build the track
|
||||
"Aggiungi punti con altri clic per evitare salite ripide, poi premi Costruisci (o Invio). Il costo viene addebitato subito e il cantiere parte.",,"Add points with more clicks to avoid steep climbs, then press Build (or Enter). The cost is charged at once and construction starts."
|
||||
Collega il deposito,,Connect the depot
|
||||
"Il deposito deve essere raccordato alla linea: traccia un breve binario dal deposito alla stazione più vicina. Se è già collegato, premi Salta passo.",,"The depot must be connected to the line: lay a short track from the depot to the nearest station. If it is already connected, press Skip step."
|
||||
Attendi i cantieri,,Wait for construction
|
||||
I cantieri richiedono giorni di gioco: accelera il tempo e osserva il tratteggio dei lavori che diventa binario.,,Construction takes game days: speed up time and watch the dashed works turn into track.
|
||||
Compra una locomotiva,,Buy a locomotive
|
||||
"Apri Treni, scegli il deposito e una locomotiva dal catalogo, poi premi Compra veicoli.",,"Open Trains, choose the depot and a locomotive from the catalogue, then press Buy vehicles."
|
||||
Compra i carri,,Buy the wagons
|
||||
Ora compra qualche carro per la merce dell'industria (o carrozze per i pendolari): ogni carro accetta solo alcune merci.,,Now buy a few wagons for the industry's goods (or coaches for commuters): each wagon only accepts certain goods.
|
||||
Componi il treno,,Compose the train
|
||||
"Seleziona nell'elenco del deposito la locomotiva e i carri, nell'ordine in cui li vuoi, dai un nome al treno e premi Componi.",,"In the depot list select the locomotive and the wagons in the order you want, name the train and press Compose."
|
||||
Crea una linea,,Create a line
|
||||
Apri Linee e fai clic sulle due stazioni in ordine: sono le fermate. Scegli nome e colore e premi Crea linea.,,Open Lines and click the two stations in order: they are the stops. Choose a name and a colour and press Create line.
|
||||
Assegna il treno alla linea,,Assign the train to the line
|
||||
"Torna in Treni, seleziona il treno, scegli la linea e premi Assegna: il treno esce dal deposito e comincia il servizio.",,"Go back to Trains, select the train, choose the line and press Assign: the train leaves the depot and starts service."
|
||||
Il Mercato globale,,The Global market
|
||||
"Apri il Mercato: prezzi, offerta e domanda di ogni bene, la previsione e dove conviene vendere. Ti dice quali linee rendono di più.",,"Open the Market: prices, supply and demand of every good, the forecast and where it pays to sell. It tells you which lines earn the most."
|
||||
Le Finanze,,Finances
|
||||
"Apri le Finanze: conto economico per voce, rating e prestiti. Un prestito ben speso costruisce linee; troppi debiti abbassano il rating e alzano il tasso.",,"Open Finances: income statement by item, rating and loans. A well-spent loan builds lines; too much debt lowers the rating and raises the rate."
|
||||
"Apri la Scalata (o fai clic sul livello in alto): i livelli della compagnia, che cosa sbloccano e che cosa manca per salire.",,"Open the Climb (or click the tier at the top): the company tiers, what they unlock and what is missing to move up."
|
||||
Qualche consiglio,,A few tips
|
||||
Collega industrie che producono a chi consuma la loro merce e porta i lavoratori dalle città alle industrie. Tieni d'occhio le Officine: un treno trascurato si guasta. Controlla cassa e rating prima di indebitarti. Buon viaggio! Puoi riaprire il tutorial con F1.,,Connect producing industries to those that consume their goods and bring workers from towns to industries. Keep an eye on the Workshops: a neglected train breaks down. Check cash and rating before borrowing. Have a good journey! You can reopen the tutorial with F1.
|
||||
Verifica connessione,,Test connection
|
||||
Versione,,Version
|
||||
Versione del gioco,,Game version
|
||||
viaggio medio,,average trip
|
||||
Sostituire la partita?,,Replace the game?
|
||||
Sostituisci la partita,,Replace the game
|
||||
Il server sostituirà la partita in corso ({0}) con il salvataggio «{1}» per tutti i client collegati ({2}). Quello che non è stato salvato andrà perso.,,The server will replace the current game ({0}) with the save «{1}» for every connected client ({2}). Anything not saved will be lost.
|
||||
Il server sostituirà la partita in corso ({0}) con una partita nuova per tutti i client collegati ({1}). Quello che non è stato salvato andrà perso.,,The server will replace the current game ({0}) with a new game for every connected client ({1}). Anything not saved will be lost.
|
||||
Server raggiungibile,,Server reachable
|
||||
Server locale spento: «Connetti e riprendi» lo avvia,,Local server off: «Connect and resume» starts it
|
||||
protocollo,,protocol
|
||||
in sede,,on site
|
||||
Prezzo di vendita,,Selling price
|
||||
Offerta inviata…,,Offer sent…
|
||||
Industria inattiva: non è in vendita finché non riprende a produrre.,,Inactive industry: not for sale until it starts producing again.
|
||||
L'industria è ferma: riprova a fermo finito.,,The industry is stopped: try again when the stop is over.
|
||||
C'è già un lavoro in programma.,,Work is already scheduled.
|
||||
Rinnovo della flotta,,Fleet renewal
|
||||
Rinnova i veicoli superati,,Renew superseded vehicles
|
||||
Rinnova,,Renew
|
||||
Era,,Era
|
||||
Prossima era,,Next era
|
||||
Valore della flotta,,Fleet value
|
||||
Nessun veicolo superato,,No superseded vehicles
|
||||
Quadro della flotta in arrivo dal server…,,Fleet overview coming from the server…
|
||||
Cassa insufficiente.,,Not enough cash.
|
||||
In produzione fino al {0}.,,In production until {0}.
|
||||
"Rinnovo: {0} veicoli superati, spesa netta {1} dopo le rivendite.",,"Renewal: {0} superseded vehicles, net cost {1} after resale."
|
||||
Seleziona i veicoli da vendere,,Select the vehicles to sell
|
||||
Superato dal {0}.,,Superseded since {0}.
|
||||
"Superato dal {0}: successore {1} ({2} kW, {3} km/h, {4}).",,"Superseded since {0}: successor {1} ({2} kW, {3} km/h, {4})."
|
||||
da rinnovare,,to renew
|
||||
e altri {0} veicoli superati,,and {0} more superseded vehicles
|
||||
fuori produzione,,out of production
|
||||
manutenzione ×{0:0.##},,maintenance ×{0:0.##}
|
||||
rivendita {0},,resale {0}
|
||||
"successore {0} ({1} kW, {2} km/h, {3})",,"successor {0} ({1} kW, {2} km/h, {3})"
|
||||
superato,,superseded
|
||||
superato dal {0},,superseded since {0}
|
||||
valore {0},,value {0}
|
||||
"{0}: {1} veicoli da rinnovare, spesa netta {2}",,"{0}: {1} vehicles to renew, net cost {2}"
|
||||
rinnovo prenotato,,renewal booked
|
||||
Rinnovo già prenotato.,,Renewal already booked.
|
||||
Audio,,Audio
|
||||
Volume generale,,Master volume
|
||||
Musica,,Music
|
||||
Ambiente,,Ambience
|
||||
Effetti,,Effects
|
||||
Interfaccia,,Interface
|
||||
Muto,,Mute
|
||||
Il tasto M attiva e toglie il muto durante la partita.,,The M key toggles mute during the game.
|
||||
Audio (M: muto),,Audio (M: mute)
|
||||
Perché questo valore,,Why this value
|
||||
in arrivo…,,on its way…
|
||||
aggiornamento in arrivo…,,update on its way…
|
||||
Il numero sul pannello è di inizio giornata; qui c'è quello di adesso.,,The number on the panel is from the start of the day; this is the current one.
|
||||
motore,,engine
|
||||
freni,,brakes
|
||||
cassa,,body
|
||||
Valore non disponibile.,,Value not available.
|
||||
Avanzamento del livello,,Level progress
|
||||
Prezzo globale,,Global price
|
||||
Prezzo base,,Base price
|
||||
Prezzo iniziale: il prezzo base del bene.,,Starting price: the good's base price.
|
||||
Bene non ancora in commercio: il prezzo resta quello di partenza.,,Good not yet on the market: the price stays at its starting value.
|
||||
Prezzo di ieri,,Yesterday's price
|
||||
Domanda della regione (finestra),,Regional demand (window)
|
||||
Offerta della regione (finestra),,Regional supply (window)
|
||||
Prezzo mondiale,,World price
|
||||
Scambi con il resto del mondo,,Trade with the rest of the world
|
||||
Rapporto domanda / offerta (con il mondo, limitato),,"Demand / supply ratio (with the world, bounded)"
|
||||
Elasticità degli scambi con il mondo,,Elasticity of trade with the world
|
||||
Domanda con il resto del mondo,,Demand including the rest of the world
|
||||
Offerta con il resto del mondo,,Supply including the rest of the world
|
||||
Rapporto minimo,,Minimum ratio
|
||||
Rapporto massimo,,Maximum ratio
|
||||
Sensibilità al rapporto,,Sensitivity to the ratio
|
||||
Prezzo minimo,,Minimum price
|
||||
Prezzo massimo,,Maximum price
|
||||
Prezzo obiettivo,,Target price
|
||||
Peso del giorno,,Weight of the day
|
||||
"D e S sono la domanda e l'offerta della regione; Dtot e Stot aggiungono gli scambi con il resto del mondo al prezzo mondiale, che segue il ciclo economico e gli shock.",,"D and S are the regional demand and supply; Dtot and Stot add trade with the rest of the world at the world price, which follows the business cycle and shocks."
|
||||
Il prezzo è cambiato dopo l'ultimo passo del mercato.,,The price changed after the last market step.
|
||||
Prezzo locale,,Local price
|
||||
"Prezzo a cui l'industria compra la prossima unità: Dl è la scorta desiderata dell'ingresso, Sl la scorta.",,"Price at which the industry buys the next unit: Dl is the desired input stock, Sl the stock."
|
||||
"Prezzo a cui l'industria vende la prossima unità: Dl è lo spazio libero del magazzino, Sl la giacenza.",,"Price at which the industry sells the next unit: Dl is the free warehouse space, Sl the stock on hand."
|
||||
Domanda locale,,Local demand
|
||||
Offerta locale,,Local supply
|
||||
Peso dello squilibrio,,Weight of the imbalance
|
||||
Correzione per scorte nulle,,Correction for empty stock
|
||||
Scarto massimo dal prezzo globale,,Maximum deviation from the global price
|
||||
Squilibrio locale,,Local imbalance
|
||||
Fattore locale,,Local factor
|
||||
Tariffa merci,,Freight fare
|
||||
Tariffa di una unità consegnata nel tempo atteso; tf scende dopo la soglia di ritardo fino al minimo.,,Fare for one unit delivered in the expected time; tf falls after the lateness threshold down to the minimum.
|
||||
Nessun treno della linea collega la tratta con questo bene: il tempo atteso non è noto e tf vale 1.,,No train on the line links the stretch with this good: the expected time is unknown and tf is 1.
|
||||
tariffa = u × Tb × (a + b·Pg/Pb) × km^e × tf × d,,fare = u × Tb × (a + b·Pg/Pb) × km^e × tf × d
|
||||
Unità,,Units
|
||||
Tariffa base,,Base fare
|
||||
Quota fissa,,Fixed part
|
||||
Quota legata al prezzo,,Price-linked part
|
||||
Fattore del prezzo,,Price factor
|
||||
Distanza in linea d'aria,,Straight-line distance
|
||||
Esponente della distanza,,Distance exponent
|
||||
Fattore della distanza,,Distance factor
|
||||
Puntualità,,Punctuality
|
||||
Moltiplicatore della difficoltà,,Difficulty multiplier
|
||||
Tempo atteso,,Expected time
|
||||
soglia,,threshold
|
||||
Soglia di ritardo (volte il tempo atteso),,Lateness threshold (times the expected time)
|
||||
Puntualità minima,,Minimum punctuality
|
||||
Puntualità a due volte il tempo atteso,,Punctuality at twice the expected time
|
||||
tariffa 2×,,fare 2×
|
||||
Tariffa a due volte il tempo atteso,,Fare at twice the expected time
|
||||
Tariffa passeggeri,,Passenger fare
|
||||
Tariffa di un posto consegnato nel tempo atteso; tf scende dopo la soglia di ritardo fino al minimo.,,Fare for one seat delivered in the expected time; tf falls after the lateness threshold down to the minimum.
|
||||
Nessun treno sulla linea: il comfort delle carrozze vale 1.,,No train on the line: carriage comfort is 1.
|
||||
Nessun treno della linea collega la tratta per questa classe: il tempo atteso non è noto e tf vale 1.,,No train on the line links the stretch for this class: the expected time is unknown and tf is 1.
|
||||
Tariffa del personale,,Staff fare
|
||||
Tariffa dei lavoratori,,Workers' fare
|
||||
tariffa = p × Tp × km^e × classe × tf × d × comfort,,fare = p × Tp × km^e × class × tf × d × comfort
|
||||
Posti,,Seats
|
||||
Tariffa base per posto,,Base fare per seat
|
||||
classe,,class
|
||||
Moltiplicatore della classe,,Class multiplier
|
||||
Comfort delle carrozze,,Carriage comfort
|
||||
senza comfort,,no comfort
|
||||
Tariffa prima del comfort,,Fare before comfort
|
||||
Industria chiusa.,,Industry closed.
|
||||
I termini arrivano con la prossima produzione giornaliera (dopo un caricamento non sono salvati).,,"The terms arrive with the next daily production (they are not saved, so they are missing after a load)."
|
||||
Copertura dei lavoratori (media mobile),,Worker coverage (moving average)
|
||||
Copertura del personale (media mobile),,Staff coverage (moving average)
|
||||
Fattore di profitto,,Profit factor
|
||||
lavoro,,work
|
||||
Ritmo del lavoro,,Work pace
|
||||
Copertura degli ingressi di oggi,,Today's input coverage
|
||||
Giacimento,,Deposit
|
||||
margine,,margin
|
||||
Margine (media mobile),,Margin (moving average)
|
||||
condizione,,condition
|
||||
Condizione degli impianti alla produzione (0–100),,Plant condition at production (0–100)
|
||||
"lavoro = min(cL, cP) × pf × mc (0 se ferma); e = lavoro × cI × g × ev",,"work = min(cL, cP) × pf × mc (0 if stopped); e = work × cI × g × ev"
|
||||
"Industria ferma (guasto, incidente, revisione o ammodernamento): il ritmo del lavoro è zero.",,"Industry stopped (failure, accident, overhaul or upgrade): the work pace is zero."
|
||||
Livello 0: l'industria è inattiva.,,Level 0: the industry is inactive.
|
||||
Sopra la soglia di crescita per i trimestri richiesti il livello sale; sotto la soglia di calo scende.,,Above the growth threshold for the required quarters the level rises; below the decline threshold it falls.
|
||||
Non servita da un vettore nel trimestre: il livello non cambia.,,Not served by a carrier this quarter: the level does not change.
|
||||
punteggio = ws·quota + wc·copertura + wr·redditività,,score = ws·share + wc·coverage + wr·profitability
|
||||
quota,,share
|
||||
Quota trasportata,,Share carried
|
||||
spedite,,shipped
|
||||
Unità spedite nel trimestre,,Units shipped in the quarter
|
||||
prodotte,,produced
|
||||
Unità prodotte nel trimestre,,Units produced in the quarter
|
||||
Copertura media,,Average coverage
|
||||
Giorni del trimestre,,Days in the quarter
|
||||
redditività,,profitability
|
||||
Redditività (margine + 1)/2,,Profitability (margin + 1)/2
|
||||
Peso della quota,,Weight of the share
|
||||
Peso della copertura,,Weight of the coverage
|
||||
Peso della redditività,,Weight of the profitability
|
||||
soglia su,,threshold up
|
||||
Soglia di crescita,,Growth threshold
|
||||
soglia giù,,threshold down
|
||||
Soglia di calo,,Decline threshold
|
||||
trimestri,,quarters
|
||||
Trimestri sopra soglia,,Quarters above threshold
|
||||
richiesti,,required
|
||||
Trimestri richiesti,,Quarters required
|
||||
Crescita della città,,Town growth
|
||||
"g = g₀ + ws·(s − s₀) + wo·(o − o₀), limitata a ±gmax",,"g = g₀ + ws·(s − s₀) + wo·(o − o₀), capped at ±gmax"
|
||||
Crescita di base,,Base growth
|
||||
Soddisfazione neutra,,Neutral satisfaction
|
||||
Peso della soddisfazione,,Weight of satisfaction
|
||||
Occupati per abitante,,Employed per inhabitant
|
||||
Occupazione neutra,,Neutral employment
|
||||
Peso dell'occupazione,,Weight of employment
|
||||
g grezza,,raw g
|
||||
Crescita prima del limite,,Growth before the cap
|
||||
Crescita massima al mese,,Maximum growth per month
|
||||
dopo,,after
|
||||
Abitanti dopo il mese,,Population after the month
|
||||
ultimo mese,,last month
|
||||
Crescita dell'ultimo mese,,Last month's growth
|
||||
Stima con lo stato di oggi: la crescita si applica all'inizio del mese.,,Estimate from today's state: growth is applied at the start of the month.
|
||||
Condizione del treno,,Train condition
|
||||
Componente più debole,,Weakest component
|
||||
veicolo,,vehicle
|
||||
Veicolo,,Vehicle
|
||||
Usura al giorno del componente (media mobile),,Component wear per day (moving average)
|
||||
Componente che dà la stima,,Component driving the estimate
|
||||
Veicolo del componente della stima,,Vehicle of the estimate component
|
||||
veicolo cs,,vehicle cs
|
||||
Il componente è già all'obiettivo o sotto: la stima vale −margine.,,The component is already at or below the target: the estimate is −margin.
|
||||
c rischio,,c risk
|
||||
Componente più a rischio,,Component most at risk
|
||||
Rischio di base al giorno,,Base risk per day
|
||||
Condizione di soglia,,Threshold condition
|
||||
Pendenza del rischio,,Risk slope
|
||||
Scala della condizione,,Condition scale
|
||||
Riduzione sopra soglia,,Reduction above threshold
|
||||
ispezione,,inspection
|
||||
Fattore dopo un'ispezione,,Factor after an inspection
|
||||
Rischio di guasto al giorno,,Failure risk per day
|
||||
Giorni attesi al prossimo guasto,,Expected days to the next failure
|
||||
Condizione obiettivo del pianificatore,,Planner's target condition
|
||||
Margine del pianificatore,,Planner's margin
|
||||
stima,,estimate
|
||||
Giorni all'intervento sulla condizione,,Days to condition-based maintenance
|
||||
Nessuna stima del pianificatore: i componenti non si sono ancora consumati.,,No planner estimate: the components have not worn yet.
|
||||
Il guasto è estratto ogni giorno con il rischio h: 1/h è il numero medio di giorni prima del prossimo.,,A failure is drawn every day with risk h: 1/h is the average number of days before the next one.
|
||||
"c = min(componenti); h = h₀·exp(k·(c₀ − c)/σ) sotto c₀, altrimenti h₀/div; stima = min sui componenti di (cs − obiettivo)/usura − margine",,"c = min(components); h = h₀·exp(k·(c₀ − c)/σ) below c₀, otherwise h₀/div; estimate = min over components of (cs − target)/wear − margin"
|
||||
Valore del veicolo,,Vehicle value
|
||||
prezzo,,price
|
||||
Prezzo di listino,,List price
|
||||
età,,age
|
||||
Età,,Age
|
||||
vita,,life
|
||||
Vita utile,,Useful life
|
||||
Superato dal,,Superseded since
|
||||
anni superato,,years superseded
|
||||
Anni da superato,,Years since superseded
|
||||
perdita,,loss
|
||||
Perdita immediata,,Immediate loss
|
||||
velocità,,speed
|
||||
Ammortamento più rapido,,Faster depreciation
|
||||
successore,,successor
|
||||
Successore consigliato,,Recommended successor
|
||||
"r = max(rmin, (1 − perdita)·(1 − (età + (velocità − 1)·anni superato)/vita)); valore = prezzo·r; rivendita = prezzo·r·condizione",,"r = max(rmin, (1 − loss)·(1 − (age + (speed − 1)·years superseded)/life)); value = price·r; resale = price·r·condition"
|
||||
Modello superato: perde subito una quota del valore e si ammortizza più in fretta.,,Superseded model: it loses part of its value at once and depreciates faster.
|
||||
"r = max(rmin, 1 − età/vita); valore = prezzo·r; rivendita = prezzo·r·condizione",,"r = max(rmin, 1 − age/life); value = price·r; resale = price·r·condition"
|
||||
Valore minimo,,Minimum value
|
||||
Quota residua del valore,,Remaining share of value
|
||||
Condizione media dei componenti,,Average component condition
|
||||
rivendita,,resale
|
||||
Rivendita,,Resale
|
||||
"Margine (utile operativo / ricavi, 12 mesi)",,"Margin (operating profit / revenue, 12 months)"
|
||||
Componente del margine,,Margin component
|
||||
leva,,leverage
|
||||
Debiti / patrimonio netto,,Debt / net worth
|
||||
Componente della leva,,Leverage component
|
||||
Peso del margine,,Weight of the margin
|
||||
Peso della leva,,Weight of the leverage
|
||||
"Rating iniziale: le misure sono quelle di oggi, il primo calcolo è a inizio mese.",,"Initial rating: the measures are today's, the first calculation is at the start of the month."
|
||||
Margine neutro finché la finestra non ha abbastanza mesi con ricavi.,,Neutral margin until the window has enough months with revenue.
|
||||
Compagnia in bancarotta: il rating è D.,,Company bankrupt: the rating is D.
|
||||
gradino,,step
|
||||
Gradino sopra,,Next step up
|
||||
Punteggio del gradino sopra,,Score of the next step up
|
||||
Il punteggio vale già il gradino sopra: il rating cambia al prossimo calcolo mensile.,,The score already earns the next step up: the rating changes at the next monthly calculation.
|
||||
margine necessario,,margin needed
|
||||
"Margine che basta, a leva invariata",,"Margin that is enough, with leverage unchanged"
|
||||
leva massima,,max leverage
|
||||
"Leva che basta, a margine invariato",,"Leverage that is enough, with margin unchanged"
|
||||
rimborso,,repayment
|
||||
Debito da rimborsare per la leva che basta,,Debt to repay to reach that leverage
|
||||
Rating più alto.,,Highest rating.
|
||||
"punteggio = pm·clamp(0,5 + margine, 0, 1) + pl·1/(1 + leva)",,"score = pm·clamp(0.5 + margin, 0, 1) + pl·1/(1 + leverage)"
|
||||
Livello più alto.,,Highest level.
|
||||
Finché un requisito manca l'avanzamento resta sotto il 100%.,,"While a requirement is missing, progress stays below 100%."
|
||||
"avanzamento = (fP + fC + fR)/3; fP = min(1, patrimonio/soglia); fC = min(1, città/richieste); fR = 1 − gradini mancanti/n",,"progress = (fP + fC + fR)/3; fP = min(1, net worth/threshold); fC = min(1, cities/wanted); fR = 1 − missing steps/n"
|
||||
Patrimonio richiesto,,Net worth required
|
||||
Frazione del patrimonio,,Net worth fraction
|
||||
città,,cities
|
||||
Città collegate,,Towns connected
|
||||
Città richieste,,Towns required
|
||||
Abitanti minimi per città,,Minimum population per town
|
||||
Frazione delle città,,Towns fraction
|
||||
rating richiesto,,rating required
|
||||
Rating richiesto,,Rating required
|
||||
Gradini per lo zero,,Steps to zero
|
||||
Frazione del rating,,Rating fraction
|
||||
tetto,,cap
|
||||
Tetto con un requisito mancante,,Cap with a requirement missing
|
||||
Le voci del mese sono nel pannello «Finanze».,,The month's items are in the «Finances» panel.
|
||||
inizio,,start
|
||||
Cassa a inizio mese,,Cash at the start of the month
|
||||
ricavi,,revenue
|
||||
Ricavi del mese,,Revenue this month
|
||||
costi,,costs
|
||||
Costi del mese,,Costs this month
|
||||
capitale,,capital
|
||||
Investimenti e finanziamenti del mese,,Investment and financing this month
|
||||
flusso,,flow
|
||||
Flusso di cassa del mese,,Cash flow this month
|
||||
Giorni di cassa negativa,,Days of negative cash
|
||||
limite,,limit
|
||||
Giorni che portano alla bancarotta,,Days that lead to bankruptcy
|
||||
Con la cassa negativa per troppi giorni di fila la compagnia fallisce.,,With negative cash for too many days in a row the company goes bankrupt.
|
||||
cassa = cassa a inizio mese + ricavi + costi + investimenti e finanziamenti,,cash = cash at start of month + revenue + costs + investment and financing
|
||||
|
@@ -0,0 +1,142 @@
|
||||
{
|
||||
"version": 1,
|
||||
"steps": [
|
||||
{
|
||||
"id": "welcome",
|
||||
"title": "Benvenuto in Rail Enterprise",
|
||||
"text": "Guidi una compagnia ferroviaria: costruisci binari e stazioni, trasporti merci e pendolari e fai crescere il patrimonio fino a dominare il mercato. Questo tutorial ti accompagna nella prima linea; puoi saltare un passo o chiuderlo quando vuoi."
|
||||
},
|
||||
{
|
||||
"id": "map",
|
||||
"title": "Muovi la mappa",
|
||||
"text": "Trascina con il tasto destro (o usa WASD e le frecce) per spostarti e gira la rotella per lo zoom. Cerca una città e un'industria vicine: saranno le due stazioni della prima linea.",
|
||||
"highlight": "map",
|
||||
"done": { "all": [ { "counter": "mapPan", "increase": 0.5 }, { "counter": "mapZoom", "increase": 0.5 } ] }
|
||||
},
|
||||
{
|
||||
"id": "time",
|
||||
"title": "Il tempo",
|
||||
"text": "In alto scegli la velocità del gioco: II mette in pausa, 1× – 8× accelerano. Anche la barra spaziatrice mette in pausa e riprende. Cambia la velocità per proseguire.",
|
||||
"highlight": "topbar:speed",
|
||||
"done": { "counter": "speedChanges", "increase": 1 }
|
||||
},
|
||||
{
|
||||
"id": "stations",
|
||||
"title": "Costruisci due stazioni",
|
||||
"text": "Apri lo strumento Stazione e fai clic sulla mappa vicino a un'industria e poi vicino a una città. Il cerchio è il bacino di utenza: le merci e i passeggeri arrivano solo da lì.",
|
||||
"highlight": "toolbar:station",
|
||||
"done": { "counter": "stations", "atLeast": 2 }
|
||||
},
|
||||
{
|
||||
"id": "depot",
|
||||
"title": "Costruisci un deposito",
|
||||
"text": "Con lo strumento Deposito posa un deposito vicino a una delle stazioni. Nel deposito si comprano i veicoli, si compongono i treni e si fanno le manutenzioni.",
|
||||
"highlight": "toolbar:depot",
|
||||
"done": { "counter": "depots", "atLeast": 1 }
|
||||
},
|
||||
{
|
||||
"id": "track-tool",
|
||||
"title": "Lo strumento Binari",
|
||||
"text": "Apri lo strumento Binari: scegli la classe del binario e se ammettere ponti e gallerie.",
|
||||
"highlight": "toolbar:track",
|
||||
"done": { "panel": "track" }
|
||||
},
|
||||
{
|
||||
"id": "track-profile",
|
||||
"title": "Guarda il profilo e le opere",
|
||||
"text": "Fai clic sulla prima stazione e muovi il mouse verso la seconda: il profilo mostra il terreno e la quota del binario. Sotto compaiono rilevati, trincee, ponti e gallerie con lunghezza, pendenza, costo e giorni di cantiere. Se attraversi un fiume vedrai il ponte.",
|
||||
"highlight": "track:profile",
|
||||
"fallback": "toolbar:track",
|
||||
"done": { "counter": "trackPreviews", "increase": 1 }
|
||||
},
|
||||
{
|
||||
"id": "track-build",
|
||||
"title": "Costruisci il binario",
|
||||
"text": "Aggiungi punti con altri clic per evitare salite ripide, poi premi Costruisci (o Invio). Il costo viene addebitato subito e il cantiere parte.",
|
||||
"highlight": "track:build",
|
||||
"fallback": "toolbar:track",
|
||||
"done": { "counter": "cmd:BuildTrack", "increase": 1 }
|
||||
},
|
||||
{
|
||||
"id": "depot-link",
|
||||
"title": "Collega il deposito",
|
||||
"text": "Il deposito deve essere raccordato alla linea: traccia un breve binario dal deposito alla stazione più vicina. Se è già collegato, premi Salta passo.",
|
||||
"highlight": "track:build",
|
||||
"fallback": "toolbar:track",
|
||||
"done": { "counter": "cmd:BuildTrack", "increase": 1 }
|
||||
},
|
||||
{
|
||||
"id": "construction",
|
||||
"title": "Attendi i cantieri",
|
||||
"text": "I cantieri richiedono giorni di gioco: accelera il tempo e osserva il tratteggio dei lavori che diventa binario.",
|
||||
"highlight": "topbar:speed",
|
||||
"done": { "all": [ { "counter": "edges", "atLeast": 1 }, { "counter": "edgesBuilding", "atMost": 0 } ] }
|
||||
},
|
||||
{
|
||||
"id": "locomotive",
|
||||
"title": "Compra una locomotiva",
|
||||
"text": "Apri Treni, scegli il deposito e una locomotiva dal catalogo, poi premi Compra veicoli.",
|
||||
"highlight": "trains:buy",
|
||||
"fallback": "toolbar:trains",
|
||||
"done": { "counter": "locomotives", "atLeast": 1 }
|
||||
},
|
||||
{
|
||||
"id": "cars",
|
||||
"title": "Compra i carri",
|
||||
"text": "Ora compra qualche carro per la merce dell'industria (o carrozze per i pendolari): ogni carro accetta solo alcune merci.",
|
||||
"highlight": "trains:buy",
|
||||
"fallback": "toolbar:trains",
|
||||
"done": { "counter": "cars", "atLeast": 1 }
|
||||
},
|
||||
{
|
||||
"id": "compose",
|
||||
"title": "Componi il treno",
|
||||
"text": "Seleziona nell'elenco del deposito la locomotiva e i carri, nell'ordine in cui li vuoi, dai un nome al treno e premi Componi.",
|
||||
"highlight": "trains:compose",
|
||||
"fallback": "toolbar:trains",
|
||||
"done": { "counter": "trains", "atLeast": 1 }
|
||||
},
|
||||
{
|
||||
"id": "line",
|
||||
"title": "Crea una linea",
|
||||
"text": "Apri Linee e fai clic sulle due stazioni in ordine: sono le fermate. Scegli nome e colore e premi Crea linea.",
|
||||
"highlight": "lines:create",
|
||||
"fallback": "toolbar:lines",
|
||||
"done": { "counter": "lines", "atLeast": 1 }
|
||||
},
|
||||
{
|
||||
"id": "assign",
|
||||
"title": "Assegna il treno alla linea",
|
||||
"text": "Torna in Treni, seleziona il treno, scegli la linea e premi Assegna: il treno esce dal deposito e comincia il servizio.",
|
||||
"highlight": "trains:assign",
|
||||
"fallback": "toolbar:trains",
|
||||
"done": { "counter": "trainsOnLine", "atLeast": 1 }
|
||||
},
|
||||
{
|
||||
"id": "market",
|
||||
"title": "Il Mercato globale",
|
||||
"text": "Apri il Mercato: prezzi, offerta e domanda di ogni bene, la previsione e dove conviene vendere. Ti dice quali linee rendono di più.",
|
||||
"highlight": "toolbar:market",
|
||||
"done": { "panel": "market" }
|
||||
},
|
||||
{
|
||||
"id": "finance",
|
||||
"title": "Le Finanze",
|
||||
"text": "Apri le Finanze: conto economico per voce, rating e prestiti. Un prestito ben speso costruisce linee; troppi debiti abbassano il rating e alzano il tasso.",
|
||||
"highlight": "toolbar:finance",
|
||||
"done": { "panel": "finance" }
|
||||
},
|
||||
{
|
||||
"id": "climb",
|
||||
"title": "La tua scalata",
|
||||
"text": "Apri la Scalata (o fai clic sul livello in alto): i livelli della compagnia, che cosa sbloccano e che cosa manca per salire.",
|
||||
"highlight": "toolbar:climb",
|
||||
"done": { "panel": "climb" }
|
||||
},
|
||||
{
|
||||
"id": "tips",
|
||||
"title": "Qualche consiglio",
|
||||
"text": "Collega industrie che producono a chi consuma la loro merce e porta i lavoratori dalle città alle industrie. Tieni d'occhio le Officine: un treno trascurato si guasta. Controlla cassa e rating prima di indebitarti. Buon viaggio! Puoi riaprire il tutorial con F1."
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -6,7 +6,7 @@ runnable=true
|
||||
dedicated_server=false
|
||||
custom_features=""
|
||||
export_filter="all_resources"
|
||||
include_filter="data/*.json, data/schema/*.json, assets/i18n/*.csv, assets/fonts/*.ttf, assets/fonts/OFL.txt"
|
||||
include_filter="data/*.json, data/schema/*.json, assets/i18n/*.csv, assets/tutorial/*.json, assets/fonts/*.ttf, assets/fonts/OFL.txt"
|
||||
exclude_filter=""
|
||||
export_path="export/windows/RailEnterprise.exe"
|
||||
encryption_include_filters=""
|
||||
@@ -36,7 +36,7 @@ runnable=true
|
||||
dedicated_server=false
|
||||
custom_features=""
|
||||
export_filter="all_resources"
|
||||
include_filter="data/*.json, data/schema/*.json, assets/i18n/*.csv, assets/fonts/*.ttf, assets/fonts/OFL.txt"
|
||||
include_filter="data/*.json, data/schema/*.json, assets/i18n/*.csv, assets/tutorial/*.json, assets/fonts/*.ttf, assets/fonts/OFL.txt"
|
||||
exclude_filter=""
|
||||
export_path="export/linux/RailEnterprise.x86_64"
|
||||
encrypt_pck=false
|
||||
|
||||
@@ -209,13 +209,14 @@ public partial class AutoPilot : Node
|
||||
var anchor = MapScale.V(near);
|
||||
var industry = World.Industries.Values.Where(i => !i.Closed && i.Owner < 0 && i.Level > 0)
|
||||
.OrderBy(i => MapScale.V(i.Position).DistanceTo(anchor)).ThenBy(i => i.Id).First();
|
||||
// dalla F6 la scheda dell'industria è a tutto schermo (immagine 07): 12 è la scheda di
|
||||
// un'industria dei privati con l'avviso dell'acquisto rifiutato, 12b la stessa scheda in fondo
|
||||
// (impianti, crescita, storico dei fermi). La mappa non si vede: niente centratura né zoom
|
||||
_game.OpenIndustry(industry.Id);
|
||||
await Until(() => World.IndustryCards.ContainsKey(industry.Id), "scheda dell'industria", 30);
|
||||
// al livello iniziale il server rifiuta l'acquisto: il messaggio compare sulla mappa
|
||||
// al livello iniziale il server rifiuta l'acquisto: l'avviso compare in alto sopra la scheda
|
||||
var buy = await Do(new BuyIndustryCommand(new IndustryId(industry.Id), World.IndustryCards[industry.Id].Valuation));
|
||||
GD.Print($"autopilot: acquisto di {industry.Name}: {buy.Message}");
|
||||
_game.Map.CenterOn(MapScale.V(industry.Position));
|
||||
_game.Map.SetZoom(0.3f);
|
||||
await Shot("12_industria", 40);
|
||||
_game.ScrollPanel(1);
|
||||
await Shot("12b_industria_scorte", 20);
|
||||
@@ -240,9 +241,47 @@ public partial class AutoPilot : Node
|
||||
await Until(() => World.Market is not null, "quadro del mercato", 30);
|
||||
await Shot("16_mercato", 40);
|
||||
|
||||
// La tua scalata (immagine 08): livelli, sblocchi, requisiti, stato patrimoniale
|
||||
_game.OpenClimb();
|
||||
await Until(() => World.Climb is not null, "quadro della scalata", 30);
|
||||
await Shot("17_scalata", 40);
|
||||
|
||||
// Finanze: conto economico per voce, rating spiegato, prestiti
|
||||
_game.OpenFinance();
|
||||
await Until(() => World.Finance is not null, "quadro delle finanze", 30);
|
||||
await Shot("18_finanze", 40);
|
||||
|
||||
// Cronaca provvisoria
|
||||
_game.OpenChronicle();
|
||||
await Until(() => _game.ChronicleVisible, "cronaca", 30);
|
||||
await Shot("15_cronaca", 30);
|
||||
_game.CloseChronicle();
|
||||
|
||||
// F6, scheda dell'industria (immagine 07): un'industria di trasformazione vicino alla linea,
|
||||
// con catena produttiva, forza lavoro e crescita
|
||||
var processing = World.Industries.Values
|
||||
.Where(i => !i.Closed && i.Level > 0 && World.Data.Industries.FirstOrDefault(d => d.Id == i.Type)?.Recipe.Inputs.Count > 0)
|
||||
.OrderBy(i => MapScale.V(i.Position).DistanceTo(anchor)).ThenBy(i => i.Id).FirstOrDefault() ?? industry;
|
||||
_game.OpenIndustry(processing.Id);
|
||||
await Until(() => World.IndustryCards.TryGetValue(processing.Id, out var c) && c.Sheet is not null, "scheda completa dell'industria", 30);
|
||||
_game.ScrollPanel(0);
|
||||
await Shot("19_scheda_industria", 40);
|
||||
|
||||
// F6, schermata di connessione (immagine 09) sopra la partita: sessione di prova sul server
|
||||
// locale con il suo stato e l'elenco dei salvataggi (uno appena fatto)
|
||||
Session.Send(new Save { Name = "Collaudo" });
|
||||
var launcher = Session.LocalServer ?? throw new InvalidOperationException("collaudo senza server locale");
|
||||
// livello proprio sopra l'interfaccia della partita (CanvasLayer 1–3): sul livello 0 la
|
||||
// schermata finirebbe sotto la scheda a tutto schermo e trasformata dalla camera della mappa
|
||||
_game.CloseTools();
|
||||
var layer = new CanvasLayer { Layer = 10 };
|
||||
_game.AddChild(layer);
|
||||
var connect = new ConnectScreen(World.Data, remember: false, autoStart: false);
|
||||
layer.AddChild(connect);
|
||||
await Frame();
|
||||
await connect.ProbeRemote(new Uri($"ws://127.0.0.1:{launcher.Port}/ws"), launcher.Token);
|
||||
await Until(() => connect.Loaded, "stato del server e salvataggi", 30);
|
||||
await Shot("20_connessione", 30);
|
||||
layer.QueueFree();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,643 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.Map;
|
||||
using RailEnterprise.Client.Net;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Map;
|
||||
using RailEnterprise.Core.Rail;
|
||||
using RailEnterprise.Protocol;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
|
||||
namespace RailEnterprise.Client.Audio;
|
||||
|
||||
/// <summary>
|
||||
/// Regia dell'audio, figlia di <c>Main</c> per tutta la vita del client: bus e volumi, effetti
|
||||
/// dell'interfaccia (clic di ogni pulsante, esito dei comandi), notifiche, cantieri completati,
|
||||
/// treni in moto vicini al centro della telecamera (rotolamento, motore, sbuffi), ambiente dal
|
||||
/// terreno sotto la telecamera e musica per era. Non decide nulla del gioco: reagisce a ciò che il
|
||||
/// client riceve (esiti, notifiche, <c>DailyDigest</c>, moti dei treni) e alla vista.
|
||||
/// I suoni si sintetizzano all'avvio su un altro thread (<see cref="Synth"/>, <see cref="MusicComposer"/>);
|
||||
/// nel ciclo per fotogramma non si alloca (elenchi preparati, nessuna LINQ).
|
||||
/// </summary>
|
||||
public partial class AudioManager : Node
|
||||
{
|
||||
/// <summary>Unica istanza (nulla prima dell'avvio del client).</summary>
|
||||
public static AudioManager? Instance { get; private set; }
|
||||
|
||||
/// <summary>Volumi e muto attuali (anche con l'audio disattivato, per il pannello).</summary>
|
||||
public AudioSettings Settings { get; private set; } = new();
|
||||
|
||||
/// <summary>Cambio di volumi o muto (per aggiornare il pannello e l'icona della barra).</summary>
|
||||
public event Action? SettingsChanged;
|
||||
|
||||
private readonly bool _enabled;
|
||||
private Task<SoundBank>? _bankTask;
|
||||
private bool _loaded;
|
||||
|
||||
// suoni singoli
|
||||
private AudioStreamWav? _click, _confirm, _error, _build, _chuff;
|
||||
private readonly Callable _clickCallable;
|
||||
private readonly AudioStreamWav?[] _notify = new AudioStreamWav?[3];
|
||||
private AudioStreamWav[] _birds = [];
|
||||
private AudioStreamWav? _diesel, _hum;
|
||||
|
||||
// riproduttori polifonici per bus e nomi dei bus già pronti (niente StringName per chiamata)
|
||||
private readonly StringName _busUi = AudioBuses.Ui, _busSfx = AudioBuses.Sfx, _busAmbience = AudioBuses.Ambience;
|
||||
private AudioStreamPlaybackPolyphonic? _ui, _sfx, _ambience;
|
||||
|
||||
// ambiente: vento, acqua, mare, città
|
||||
private const int AmbienceLoops = 4;
|
||||
private static readonly float[] AmbienceLevel = [0.55f, 0.6f, 0.6f, 0.5f];
|
||||
private readonly AudioStreamPlayer[] _ambiencePlayers = new AudioStreamPlayer[AmbienceLoops];
|
||||
private readonly float[] _ambienceGain = new float[AmbienceLoops];
|
||||
private readonly float[] _ambienceTarget = new float[AmbienceLoops];
|
||||
private float _birdsChance;
|
||||
private float _sinceAmbience = 1, _birdTimer = 3;
|
||||
|
||||
// treni
|
||||
private sealed class TrainChannel
|
||||
{
|
||||
public int Train = -1;
|
||||
public Traction Traction;
|
||||
public float Gain, Target, ChuffTimer;
|
||||
public bool Kept;
|
||||
public required AudioStreamPlayer Rumble { get; init; }
|
||||
public required AudioStreamPlayer Engine { get; init; }
|
||||
}
|
||||
|
||||
private readonly TrainChannel[] _channels = new TrainChannel[AudioMix.TrainChannels];
|
||||
private readonly int[] _nearIds = new int[AudioMix.TrainChannels];
|
||||
private readonly float[] _nearDistances = new float[AudioMix.TrainChannels];
|
||||
|
||||
/// <summary>
|
||||
/// Età massima (ms) dell'ultimo moto di un treno perché suoni: il server manda i moti dei treni
|
||||
/// in marcia ogni 100 ms; un moto più vecchio è di un treno fermo in stazione (durante la sosta
|
||||
/// non arrivano moti) o uscito dalla zona sottoscritta, e non va più ascoltato.
|
||||
/// </summary>
|
||||
private const long StaleMotionMs = 500;
|
||||
|
||||
// musica: due riproduttori per la dissolvenza incrociata
|
||||
private const float MusicLevel = 0.6f;
|
||||
private const float FadeSeconds = 3f;
|
||||
private readonly AudioStreamPlayer[] _music = new AudioStreamPlayer[2];
|
||||
private readonly float[] _musicGain = new float[2];
|
||||
private int _activeMusic;
|
||||
private int _musicEra = -1;
|
||||
private readonly Dictionary<int, AudioStreamWav> _themes = [];
|
||||
private readonly HashSet<int> _failedThemes = [];
|
||||
private Task<float[]>? _composing;
|
||||
private int _composingEra;
|
||||
private string[] _eraIds = ["steam"];
|
||||
private int[] _eraFroms = [0];
|
||||
|
||||
// partita in corso
|
||||
private GameSession? _session;
|
||||
private MapView? _map;
|
||||
private Dictionary<string, VehicleDef> _vehicles = [];
|
||||
private SynthRng _rng = new(0xA0D10);
|
||||
private ulong _lastUiMs, _lastNotifyMs;
|
||||
private bool _settingsDirty;
|
||||
|
||||
// pannello delle impostazioni
|
||||
private CanvasLayer? _overlay;
|
||||
private AudioSettingsPanel? _panel;
|
||||
|
||||
/// <param name="enabled">Falso nel pilota automatico e senza schermo: niente sintesi né riproduzione, Master muto.</param>
|
||||
public AudioManager(bool enabled)
|
||||
{
|
||||
_enabled = enabled;
|
||||
Name = "AudioManager";
|
||||
_clickCallable = Callable.From(PlayClick);
|
||||
}
|
||||
|
||||
public AudioManager() : this(true)
|
||||
{
|
||||
}
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
Instance = this;
|
||||
AudioBuses.Ensure();
|
||||
Settings = AudioSettings.Load();
|
||||
ApplySettings();
|
||||
if (!_enabled) return;
|
||||
_bankTask = Task.Run(SoundBank.Create);
|
||||
GetTree().NodeAdded += OnNodeAdded;
|
||||
}
|
||||
|
||||
public override void _ExitTree()
|
||||
{
|
||||
if (Instance == this) Instance = null;
|
||||
Unbind();
|
||||
// chiusura della finestra con un volume appena cambiato: si salva comunque
|
||||
SaveSettings();
|
||||
}
|
||||
|
||||
/// <summary>Ere di eras.json (id e anno d'inizio, crescenti): scelgono il tema musicale.</summary>
|
||||
public void SetEras(IReadOnlyList<EraDef> eras)
|
||||
{
|
||||
if (eras.Count == 0) return;
|
||||
_eraIds = new string[eras.Count];
|
||||
_eraFroms = new int[eras.Count];
|
||||
for (int i = 0; i < eras.Count; i++)
|
||||
{
|
||||
_eraIds[i] = eras[i].Id;
|
||||
_eraFroms[i] = eras[i].From;
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ impostazioni
|
||||
|
||||
private void ApplySettings()
|
||||
{
|
||||
Settings.Apply();
|
||||
// senza audio (collaudo, server senza schermo) il Master resta muto, senza toccare il file
|
||||
if (!_enabled) AudioServer.SetBusMute(0, true);
|
||||
}
|
||||
|
||||
/// <summary>Cambia il volume di un bus (indice in <see cref="AudioBuses.All"/>) e lo applica subito.</summary>
|
||||
public void SetVolume(int bus, float value)
|
||||
{
|
||||
Settings.Volumes[bus] = Math.Clamp(value, 0, 1);
|
||||
_settingsDirty = true;
|
||||
ApplySettings();
|
||||
SettingsChanged?.Invoke();
|
||||
}
|
||||
|
||||
public void SetMuted(bool muted)
|
||||
{
|
||||
Settings.Muted = muted;
|
||||
_settingsDirty = true;
|
||||
ApplySettings();
|
||||
SettingsChanged?.Invoke();
|
||||
}
|
||||
|
||||
public void ToggleMute()
|
||||
{
|
||||
SetMuted(!Settings.Muted);
|
||||
SaveSettings();
|
||||
}
|
||||
|
||||
/// <summary>Scrive volumi e muto in <c>user://settings.cfg</c> se sono cambiati dall'ultimo salvataggio.</summary>
|
||||
public void SaveSettings()
|
||||
{
|
||||
if (!_settingsDirty) return;
|
||||
_settingsDirty = false;
|
||||
Settings.Save();
|
||||
}
|
||||
|
||||
/// <summary>Apre il pannello «Audio» sopra a tutto (menu o partita).</summary>
|
||||
public void ShowSettings()
|
||||
{
|
||||
if (_panel is not null && IsInstanceValid(_panel)) return;
|
||||
if (_overlay is null)
|
||||
{
|
||||
_overlay = new CanvasLayer { Layer = 50 };
|
||||
AddChild(_overlay);
|
||||
}
|
||||
_panel = new AudioSettingsPanel(this);
|
||||
_panel.TreeExited += () => _panel = null;
|
||||
_overlay.AddChild(_panel);
|
||||
}
|
||||
|
||||
public override void _UnhandledKeyInput(InputEvent e)
|
||||
{
|
||||
if (e is InputEventKey { Pressed: true, Echo: false, Keycode: Key.M } key && !key.CtrlPressed && !key.AltPressed && !key.MetaPressed)
|
||||
{
|
||||
ToggleMute();
|
||||
GetViewport().SetInputAsHandled();
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ partita
|
||||
|
||||
/// <summary>Collega la partita: messaggi della sessione e vista della mappa.</summary>
|
||||
public void Bind(GameSession session, MapView map)
|
||||
{
|
||||
Unbind();
|
||||
_session = session;
|
||||
_map = map;
|
||||
_vehicles = session.World.Data.Vehicles.ToDictionary(v => v.Id);
|
||||
SetEras(session.World.Data.Eras.Eras);
|
||||
session.MessageApplied += OnMessage;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Scollega la partita (ritorno al menu): treni e ambiente sfumano. Con «only» scollega solo
|
||||
/// se è ancora quella sessione (la schermata vecchia esce dall'albero dopo l'arrivo della nuova).
|
||||
/// </summary>
|
||||
public void Unbind(GameSession? only = null)
|
||||
{
|
||||
if (only is not null && !ReferenceEquals(only, _session)) return;
|
||||
if (_session is not null) _session.MessageApplied -= OnMessage;
|
||||
_session = null;
|
||||
_map = null;
|
||||
}
|
||||
|
||||
private void OnMessage(IMessage message)
|
||||
{
|
||||
if (!_loaded) return;
|
||||
switch (message)
|
||||
{
|
||||
case CommandResultMessage r:
|
||||
PlayUi(r.Ok ? _confirm : _error, r.Ok ? 0.7f : 0.85f);
|
||||
break;
|
||||
case Notification n:
|
||||
Notify(n.Event);
|
||||
break;
|
||||
case DailyDigest d:
|
||||
int me = _session?.World.Summary?.CompanyId ?? -1;
|
||||
for (int i = 0; i < d.Events.Count; i++)
|
||||
{
|
||||
var e = d.Events[i];
|
||||
if (e.Kind == ConstructionEventKind && e.Company == me && me >= 0)
|
||||
{
|
||||
Play(_sfx, _build, 0.8f, 1, _busSfx);
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Codice di EventKind.Construction nel protocollo (cantiere completato, sempre informativo).</summary>
|
||||
private const byte ConstructionEventKind = 5;
|
||||
|
||||
private void Notify(EventInfo e)
|
||||
{
|
||||
int me = _session?.World.Summary?.CompanyId ?? -1;
|
||||
if (e.Company >= 0 && e.Company != me) return;
|
||||
int level = e.Severity switch { 3 => 2, 2 => 1, _ => 0 };
|
||||
ulong now = Time.GetTicksMsec();
|
||||
// più notizie insieme: una sola campanella (le critiche suonano sempre)
|
||||
if (level < 2 && now - _lastNotifyMs < 600) return;
|
||||
_lastNotifyMs = now;
|
||||
Play(_ui, _notify[level], level == 2 ? 0.9f : 0.75f, 1, _busUi);
|
||||
}
|
||||
|
||||
private void OnNodeAdded(Node node)
|
||||
{
|
||||
// un pulsante staccato e riattaccato (MarketPanel lo fa a ogni resoconto) è già collegato
|
||||
if (node is BaseButton button && !button.IsConnected(BaseButton.SignalName.Pressed, _clickCallable))
|
||||
button.Connect(BaseButton.SignalName.Pressed, _clickCallable);
|
||||
}
|
||||
|
||||
private void PlayClick() => PlayUi(_click, 0.6f);
|
||||
|
||||
private void PlayUi(AudioStreamWav? stream, float gain)
|
||||
{
|
||||
ulong now = Time.GetTicksMsec();
|
||||
if (stream == _click && now - _lastUiMs < 40) return;
|
||||
_lastUiMs = now;
|
||||
Play(_ui, stream, gain, 1, _busUi);
|
||||
}
|
||||
|
||||
private static void Play(AudioStreamPlaybackPolyphonic? playback, AudioStreamWav? stream, float gain, float pitch, StringName bus)
|
||||
{
|
||||
if (playback is null || stream is null || gain <= 0.001f) return;
|
||||
playback.PlayStream(stream, 0, AudioMix.LinearToDb(gain), pitch, AudioServer.PlaybackType.Default, bus);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ caricamento
|
||||
|
||||
/// <summary>Campioni di tutti gli effetti e degli anelli, sintetizzati fuori dal thread principale.</summary>
|
||||
private sealed class SoundBank
|
||||
{
|
||||
public required float[] Click, Confirm, Error, Construction, Chuff, Rumble, Diesel, Hum, Wind, River, Sea, City;
|
||||
public required float[][] Notify, Birds;
|
||||
|
||||
public static SoundBank Create() => new()
|
||||
{
|
||||
Click = Synth.Click(), Confirm = Synth.Confirm(), Error = Synth.Error(), Construction = Synth.BuildComplete(),
|
||||
Chuff = Synth.Chuff(), Rumble = Synth.RailRumbleLoop(),
|
||||
Diesel = Synth.DieselDroneLoop(), Hum = Synth.ElectricHumLoop(), Wind = Synth.WindLoop(), River = Synth.RiverLoop(),
|
||||
Sea = Synth.SeaLoop(), City = Synth.CityLoop(),
|
||||
Notify = [Synth.Notify(0), Synth.Notify(1), Synth.Notify(2)],
|
||||
Birds = [Synth.Bird(0), Synth.Bird(1), Synth.Bird(2)],
|
||||
};
|
||||
}
|
||||
|
||||
private static AudioStreamWav Wav(float[] samples, bool loop = false)
|
||||
{
|
||||
var w = new AudioStreamWav
|
||||
{
|
||||
Format = AudioStreamWav.FormatEnum.Format16Bits,
|
||||
MixRate = Synth.Rate,
|
||||
Stereo = false,
|
||||
Data = AudioMix.ToPcm16(samples),
|
||||
};
|
||||
if (loop)
|
||||
{
|
||||
w.LoopMode = AudioStreamWav.LoopModeEnum.Forward;
|
||||
w.LoopBegin = 0;
|
||||
w.LoopEnd = samples.Length;
|
||||
}
|
||||
return w;
|
||||
}
|
||||
|
||||
private AudioStreamPlayer Player(string bus, AudioStream? stream = null)
|
||||
{
|
||||
var p = new AudioStreamPlayer { Bus = bus, Stream = stream };
|
||||
AddChild(p);
|
||||
return p;
|
||||
}
|
||||
|
||||
private AudioStreamPlaybackPolyphonic? Polyphonic(string bus, int voices)
|
||||
{
|
||||
var p = Player(bus, new AudioStreamPolyphonic { Polyphony = voices });
|
||||
p.Play();
|
||||
return p.GetStreamPlayback() as AudioStreamPlaybackPolyphonic;
|
||||
}
|
||||
|
||||
private void Load(SoundBank bank)
|
||||
{
|
||||
_click = Wav(bank.Click);
|
||||
_confirm = Wav(bank.Confirm);
|
||||
_error = Wav(bank.Error);
|
||||
_build = Wav(bank.Construction);
|
||||
_chuff = Wav(bank.Chuff);
|
||||
for (int i = 0; i < _notify.Length; i++) _notify[i] = Wav(bank.Notify[i]);
|
||||
_birds = bank.Birds.Select(b => Wav(b)).ToArray();
|
||||
_diesel = Wav(bank.Diesel, loop: true);
|
||||
_hum = Wav(bank.Hum, loop: true);
|
||||
var rumble = Wav(bank.Rumble, loop: true);
|
||||
|
||||
_ui = Polyphonic(AudioBuses.Ui, 8);
|
||||
_sfx = Polyphonic(AudioBuses.Sfx, 16);
|
||||
_ambience = Polyphonic(AudioBuses.Ambience, 4);
|
||||
float[][] loops = [bank.Wind, bank.River, bank.Sea, bank.City];
|
||||
for (int i = 0; i < AmbienceLoops; i++)
|
||||
{
|
||||
var p = Player(AudioBuses.Ambience, Wav(loops[i], loop: true));
|
||||
p.VolumeLinear = 0;
|
||||
_ambiencePlayers[i] = p;
|
||||
}
|
||||
for (int i = 0; i < _channels.Length; i++)
|
||||
{
|
||||
var r = Player(AudioBuses.Sfx, rumble);
|
||||
var e = Player(AudioBuses.Sfx);
|
||||
r.VolumeLinear = e.VolumeLinear = 0;
|
||||
_channels[i] = new TrainChannel { Rumble = r, Engine = e };
|
||||
}
|
||||
for (int i = 0; i < _music.Length; i++) _music[i] = Player(AudioBuses.Music);
|
||||
_loaded = true;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ ciclo
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
if (!_enabled) return;
|
||||
if (!_loaded)
|
||||
{
|
||||
if (_bankTask is not { IsCompleted: true }) return;
|
||||
if (_bankTask.IsCompletedSuccessfully) Load(_bankTask.Result);
|
||||
else
|
||||
{
|
||||
GD.PrintErr($"Audio: sintesi non riuscita: {_bankTask.Exception?.GetBaseException().Message}");
|
||||
_bankTask = null;
|
||||
return;
|
||||
}
|
||||
}
|
||||
float dt = (float)Math.Min(delta, 0.1);
|
||||
UpdateMusic(dt);
|
||||
UpdateAmbience(dt);
|
||||
UpdateTrains(dt);
|
||||
}
|
||||
|
||||
private int WantedEra()
|
||||
{
|
||||
var w = _session?.World;
|
||||
if (w?.Calendar is null) return 0;
|
||||
return AudioMix.EraIndex(w.Year, _eraFroms);
|
||||
}
|
||||
|
||||
private void UpdateMusic(float dt)
|
||||
{
|
||||
int want = WantedEra();
|
||||
if (_composing is { IsCompleted: true })
|
||||
{
|
||||
if (_composing.IsCompletedSuccessfully) _themes[_composingEra] = Wav(_composing.Result, loop: true);
|
||||
else
|
||||
{
|
||||
_failedThemes.Add(_composingEra);
|
||||
GD.PrintErr($"Audio: tema dell'era non composto: {_composing.Exception?.GetBaseException().Message}");
|
||||
}
|
||||
_composing = null;
|
||||
}
|
||||
if (want != _musicEra)
|
||||
{
|
||||
if (_themes.TryGetValue(want, out var theme))
|
||||
{
|
||||
// dissolvenza incrociata: il nuovo tema entra sull'altro riproduttore
|
||||
_activeMusic = 1 - _activeMusic;
|
||||
var p = _music[_activeMusic];
|
||||
p.Stream = theme;
|
||||
_musicGain[_activeMusic] = 0;
|
||||
p.VolumeLinear = 0;
|
||||
p.Play();
|
||||
_musicEra = want;
|
||||
}
|
||||
else if (_composing is null && !_failedThemes.Contains(want))
|
||||
{
|
||||
int era = want;
|
||||
string id = _eraIds[Math.Clamp(era, 0, _eraIds.Length - 1)];
|
||||
_composingEra = era;
|
||||
_composing = Task.Run(() => MusicComposer.Compose(era, id));
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < _music.Length; i++)
|
||||
{
|
||||
float target = i == _activeMusic && _musicEra >= 0 ? 1 : 0;
|
||||
_musicGain[i] = AudioMix.Approach(_musicGain[i], target, 1 / FadeSeconds, dt);
|
||||
_music[i].VolumeLinear = _musicGain[i] * MusicLevel;
|
||||
if (_musicGain[i] <= 0 && i != _activeMusic && _music[i].Playing) _music[i].Stop();
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateAmbience(float dt)
|
||||
{
|
||||
_sinceAmbience += dt;
|
||||
if (_sinceAmbience >= 0.25f)
|
||||
{
|
||||
_sinceAmbience = 0;
|
||||
var gains = _map is not null && _session?.World.Terrain is { } terrain
|
||||
? AudioMix.Ambience(_map.Zoom, SampleTerrain(terrain, _map.VisibleRect()))
|
||||
: default;
|
||||
_ambienceTarget[0] = gains.Wind;
|
||||
_ambienceTarget[1] = gains.Water;
|
||||
_ambienceTarget[2] = gains.Sea;
|
||||
_ambienceTarget[3] = gains.City;
|
||||
_birdsChance = gains.Birds;
|
||||
}
|
||||
for (int i = 0; i < AmbienceLoops; i++)
|
||||
{
|
||||
_ambienceGain[i] = AudioMix.Approach(_ambienceGain[i], _ambienceTarget[i], 0.5f, dt);
|
||||
var p = _ambiencePlayers[i];
|
||||
p.VolumeLinear = _ambienceGain[i] * AmbienceLevel[i];
|
||||
if (_ambienceGain[i] > 0 && !p.Playing) p.Play(_rng.Next01() * 4);
|
||||
else if (_ambienceGain[i] <= 0 && p.Playing) p.Stop();
|
||||
}
|
||||
if (_birdsChance > 0.05f && _birds.Length > 0)
|
||||
{
|
||||
_birdTimer -= dt;
|
||||
if (_birdTimer <= 0)
|
||||
{
|
||||
Play(_ambience, _birds[_rng.Next(_birds.Length)], _birdsChance * 0.45f, _rng.Range(0.9f, 1.15f), _busAmbience);
|
||||
_birdTimer = _rng.Range(1.5f, 6f) / (0.3f + _birdsChance);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Frazioni del terreno su una griglia 8×8 della vista (allargata di un quarto per sentire l'acqua vicina).</summary>
|
||||
private static TerrainMix SampleTerrain(Terrain t, Rect2 view)
|
||||
{
|
||||
const int grid = 8;
|
||||
view = view.Grow(Math.Max(view.Size.X, view.Size.Y) * 0.125f);
|
||||
int river = 0, lake = 0, sea = 0, town = 0, forest = 0, open = 0, total = 0;
|
||||
for (int gy = 0; gy < grid; gy++)
|
||||
{
|
||||
for (int gx = 0; gx < grid; gx++)
|
||||
{
|
||||
double x = view.Position.X + (gx + 0.5) / grid * view.Size.X;
|
||||
double y = view.Position.Y + (gy + 0.5) / grid * view.Size.Y;
|
||||
int cx = (int)Math.Floor(x / t.CellSizeM), cy = (int)Math.Floor(y / t.CellSizeM);
|
||||
if (!t.InBounds(cx, cy)) continue;
|
||||
int i = t.Index(cx, cy);
|
||||
total++;
|
||||
switch ((CellType)t.Types[i])
|
||||
{
|
||||
case CellType.Water when t.RiverWidth[i] > 0: river++; break;
|
||||
case CellType.Water: lake++; break;
|
||||
case CellType.Sea: sea++; break;
|
||||
case CellType.Town or CellType.Industry: town++; break;
|
||||
case CellType.Forest: forest++; break;
|
||||
default: open++; break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (total == 0) return default;
|
||||
float k = 1f / total;
|
||||
return new TerrainMix { River = river * k, Lake = lake * k, Sea = sea * k, Town = town * k, Forest = forest * k, Open = open * k };
|
||||
}
|
||||
|
||||
private void UpdateTrains(float dt)
|
||||
{
|
||||
var w = _session?.World;
|
||||
var map = _map;
|
||||
int count = 0;
|
||||
Vector2 center = default;
|
||||
float zoom = 1, radius = 1;
|
||||
if (w is not null && map is not null && _session is { } session && w.Speed > 0)
|
||||
{
|
||||
center = map.Camera.GetScreenCenterPosition();
|
||||
zoom = map.Zoom;
|
||||
radius = map.GetViewportRect().Size.Length() / 2;
|
||||
long now = (long)Time.GetTicksMsec();
|
||||
foreach (var (id, head) in map.Trains.Heads)
|
||||
{
|
||||
if (!w.Motions.TryGetValue(id, out var m) || m.State != (byte)TrainState.Moving || m.Speed < 0.5f) continue;
|
||||
if (!session.MotionReceivedMs.TryGetValue(id, out long at) || now - at > StaleMotionMs) continue;
|
||||
// oltre il raggio non si sentirebbe: niente canale (eviterebbe Play e Stop a ogni fotogramma)
|
||||
float distance = head.DistanceTo(center) * zoom;
|
||||
if (distance >= radius) continue;
|
||||
count = AudioMix.InsertNearest(_nearIds, _nearDistances, count, id, distance);
|
||||
}
|
||||
}
|
||||
// i canali restano ai loro treni finché sono tra i più vicini; gli altri sfumano
|
||||
foreach (var ch in _channels) ch.Kept = ch.Train >= 0 && Contains(_nearIds, count, ch.Train);
|
||||
for (int k = 0; k < count; k++)
|
||||
{
|
||||
int id = _nearIds[k];
|
||||
if (HasChannel(id)) continue;
|
||||
foreach (var ch in _channels)
|
||||
{
|
||||
if (ch.Train >= 0 && (ch.Kept || ch.Gain > 0.01f)) continue;
|
||||
Assign(ch, id, w!);
|
||||
ch.Kept = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
foreach (var ch in _channels)
|
||||
{
|
||||
float speed = 0;
|
||||
if (ch.Kept && w is not null && map is not null && w.Motions.TryGetValue(ch.Train, out var m) && map.Trains.Heads.TryGetValue(ch.Train, out var head))
|
||||
{
|
||||
speed = m.Speed;
|
||||
ch.Target = AudioMix.TrainGain(head.DistanceTo(center) * zoom, radius, speed, zoom);
|
||||
}
|
||||
else ch.Target = 0;
|
||||
ch.Gain = AudioMix.Approach(ch.Gain, ch.Target, 2.5f, dt);
|
||||
if (ch.Train < 0) continue;
|
||||
if (ch.Gain <= 0 && ch.Target <= 0)
|
||||
{
|
||||
ch.Train = -1;
|
||||
ch.Rumble.Stop();
|
||||
ch.Engine.Stop();
|
||||
continue;
|
||||
}
|
||||
if (speed > 0)
|
||||
{
|
||||
ch.Rumble.PitchScale = AudioMix.RumblePitch(speed);
|
||||
ch.Engine.PitchScale = AudioMix.EnginePitch(speed);
|
||||
}
|
||||
ch.Rumble.VolumeLinear = ch.Gain * 0.7f;
|
||||
bool steam = ch.Traction == Traction.Steam;
|
||||
ch.Engine.VolumeLinear = steam ? 0 : ch.Gain * 0.45f;
|
||||
if (steam && speed > 0 && ch.Gain > 0.02f)
|
||||
{
|
||||
ch.ChuffTimer -= dt;
|
||||
if (ch.ChuffTimer <= 0)
|
||||
{
|
||||
Play(_sfx, _chuff, ch.Gain * 0.9f, _rng.Range(0.92f, 1.08f), _busSfx);
|
||||
ch.ChuffTimer = Math.Max(ch.ChuffTimer, 0) + AudioMix.ChuffInterval(speed);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool Contains(int[] ids, int count, int id)
|
||||
{
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
if (ids[i] == id) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool HasChannel(int train)
|
||||
{
|
||||
foreach (var ch in _channels)
|
||||
{
|
||||
if (ch.Train == train) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void Assign(TrainChannel ch, int train, Protocol.Client.ClientWorld w)
|
||||
{
|
||||
ch.Train = train;
|
||||
ch.Traction = TractionOf(train, w);
|
||||
ch.Gain = 0;
|
||||
ch.ChuffTimer = _rng.Next01() * 0.2f;
|
||||
ch.Rumble.VolumeLinear = 0;
|
||||
ch.Rumble.Play(_rng.Next01() * 1.5f);
|
||||
ch.Engine.VolumeLinear = 0;
|
||||
if (ch.Traction == Traction.Steam) ch.Engine.Stop();
|
||||
else
|
||||
{
|
||||
ch.Engine.Stream = ch.Traction == Traction.Diesel ? _diesel : _hum;
|
||||
ch.Engine.Play(_rng.Next01() * 0.9f);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Trazione della prima locomotiva del treno (vapore se non si sa).</summary>
|
||||
private Traction TractionOf(int train, Protocol.Client.ClientWorld w)
|
||||
{
|
||||
if (!w.Trains.TryGetValue(train, out var info)) return Traction.Steam;
|
||||
foreach (int vid in info.Vehicles)
|
||||
{
|
||||
if (w.Vehicles.TryGetValue(vid, out var v) && _vehicles.TryGetValue(v.Type, out var def) && def.Kind == VehicleKind.Locomotive && def.Traction is { } traction) return traction;
|
||||
}
|
||||
return Traction.Steam;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
namespace RailEnterprise.Client.Audio;
|
||||
|
||||
/// <summary>Frazioni del terreno sotto la telecamera (somma 1 sui campioni letti).</summary>
|
||||
public struct TerrainMix
|
||||
{
|
||||
public float River;
|
||||
public float Lake;
|
||||
public float Sea;
|
||||
public float Town;
|
||||
public float Forest;
|
||||
public float Open;
|
||||
}
|
||||
|
||||
/// <summary>Guadagni lineari (0–1) dei quattro anelli d'ambiente e probabilità relativa degli uccelli.</summary>
|
||||
public readonly record struct AmbienceGains(float Wind, float Water, float Sea, float City, float Birds);
|
||||
|
||||
/// <summary>
|
||||
/// Miscelazione dell'audio senza dipendenze da Godot: guadagni dell'ambiente dal terreno e dallo
|
||||
/// zoom, volume e intonazione dei treni dalla distanza sullo schermo e dalla velocità, scelta dei
|
||||
/// treni più vicini senza allocazioni, ere dall'anno, dissolvenze e conversione in PCM. Le costanti
|
||||
/// sono di resa sonora del client, non della simulazione.
|
||||
/// </summary>
|
||||
public static class AudioMix
|
||||
{
|
||||
/// <summary>Zoom (pixel per metro) sotto il quale si sente quasi solo il vento della vista d'insieme.</summary>
|
||||
public const float FarZoom = 0.02f;
|
||||
/// <summary>Zoom da cui ambiente e treni sono al massimo.</summary>
|
||||
public const float NearZoom = 0.5f;
|
||||
/// <summary>Canali dei treni: al più tanti treni suonano insieme.</summary>
|
||||
public const int TrainChannels = 3;
|
||||
/// <summary>Velocità (m/s) a cui il rotolamento è al massimo.</summary>
|
||||
public const float FullSpeedMs = 25f;
|
||||
/// <summary>Sbuffi al secondo da fermo (al passo) e alla velocità <see cref="ChuffFullSpeedMs"/>.</summary>
|
||||
public const float ChuffMinRate = 1.2f, ChuffMaxRate = 10f;
|
||||
/// <summary>Velocità (m/s, circa 110 km/h) a cui gli sbuffi sono più fitti.</summary>
|
||||
public const float ChuffFullSpeedMs = 30f;
|
||||
|
||||
public static float Clamp01(float x) => x < 0 ? 0 : x > 1 ? 1 : x;
|
||||
|
||||
public static float SmoothStep(float x)
|
||||
{
|
||||
x = Clamp01(x);
|
||||
return x * x * (3 - 2 * x);
|
||||
}
|
||||
|
||||
/// <summary>Vicinanza della telecamera (0 = vista d'insieme, 1 = da vicino) su scala logaritmica dello zoom.</summary>
|
||||
public static float Closeness(float zoom)
|
||||
{
|
||||
if (zoom <= 0) return 0;
|
||||
return SmoothStep((MathF.Log(zoom) - MathF.Log(FarZoom)) / (MathF.Log(NearZoom) - MathF.Log(FarZoom)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ambiente: il vento c'è sempre (più forte da lontano), acqua, mare e città seguono la
|
||||
/// frazione del terreno visibile e si attenuano allontanandosi; gli uccelli solo da vicino in
|
||||
/// campagna e nei boschi.
|
||||
/// </summary>
|
||||
public static AmbienceGains Ambience(float zoom, in TerrainMix t)
|
||||
{
|
||||
float close = Closeness(zoom);
|
||||
float wind = 0.35f + 0.35f * (1 - close) + 0.15f * t.Open;
|
||||
float water = Clamp01((t.River * 3 + t.Lake * 1.5f) * (0.25f + 0.75f * close));
|
||||
float sea = Clamp01(t.Sea * 1.6f * (0.45f + 0.55f * close));
|
||||
float city = Clamp01(t.Town * 4 * (0.15f + 0.85f * close));
|
||||
float birds = Clamp01((t.Forest + t.Open * 0.6f) * close * close * (1 - t.Town * 2));
|
||||
// l'acqua e la città coprono un po' il vento
|
||||
wind *= 1 - 0.4f * MathF.Max(sea, city);
|
||||
return new AmbienceGains(Clamp01(wind), water, sea, city, birds);
|
||||
}
|
||||
|
||||
/// <summary>Volume di un treno: vicinanza al centro dello schermo, velocità e zoom.</summary>
|
||||
/// <param name="distancePx">Distanza in pixel dal centro dello schermo.</param>
|
||||
/// <param name="radiusPx">Raggio oltre il quale non si sente (di solito metà della diagonale).</param>
|
||||
public static float TrainGain(float distancePx, float radiusPx, float speedMs, float zoom)
|
||||
{
|
||||
if (radiusPx <= 0) return 0;
|
||||
float near = 1 - Clamp01(distancePx / radiusPx);
|
||||
float speed = Clamp01(speedMs / FullSpeedMs);
|
||||
return near * near * (0.25f + 0.75f * speed) * (0.15f + 0.85f * Closeness(zoom));
|
||||
}
|
||||
|
||||
/// <summary>Intonazione del rotolamento: più rapido e acuto con la velocità.</summary>
|
||||
public static float RumblePitch(float speedMs) => 0.55f + 1.0f * Clamp01(speedMs / FullSpeedMs);
|
||||
|
||||
/// <summary>Intonazione del motore (diesel o elettrico) con la velocità.</summary>
|
||||
public static float EnginePitch(float speedMs) => 0.8f + 0.5f * Clamp01(speedMs / FullSpeedMs);
|
||||
|
||||
/// <summary>
|
||||
/// Secondi tra due sbuffi della vaporiera alla velocità data: la frequenza cresce in modo lineare
|
||||
/// da <see cref="ChuffMinRate"/> a <see cref="ChuffMaxRate"/> fino a <see cref="ChuffFullSpeedMs"/>,
|
||||
/// così segue la velocità su tutto l'esercizio normale. È una resa sonora, non il passo reale della
|
||||
/// ruota: sullo schermo il tempo dei treni corre decine di volte più veloce e gli sbuffi reali
|
||||
/// sarebbero un ronzio continuo.
|
||||
/// </summary>
|
||||
public static float ChuffInterval(float speedMs) => 1f / (ChuffMinRate + (ChuffMaxRate - ChuffMinRate) * Clamp01(speedMs / ChuffFullSpeedMs));
|
||||
|
||||
/// <summary>
|
||||
/// Inserisce un candidato nell'elenco ordinato dei più vicini (al più ids.Length): nessuna
|
||||
/// allocazione, gli elenchi sono preparati una volta sola. Restituisce il nuovo conteggio.
|
||||
/// </summary>
|
||||
public static int InsertNearest(int[] ids, float[] distances, int count, int id, float distance)
|
||||
{
|
||||
int capacity = ids.Length;
|
||||
if (count == capacity && distance >= distances[capacity - 1]) return count;
|
||||
int i = Math.Min(count, capacity - 1);
|
||||
while (i > 0 && distances[i - 1] > distance)
|
||||
{
|
||||
ids[i] = ids[i - 1];
|
||||
distances[i] = distances[i - 1];
|
||||
i--;
|
||||
}
|
||||
ids[i] = id;
|
||||
distances[i] = distance;
|
||||
return Math.Min(count + 1, capacity);
|
||||
}
|
||||
|
||||
/// <summary>Era dell'anno: l'ultima il cui inizio («from» di eras.json, crescente) non è dopo l'anno.</summary>
|
||||
public static int EraIndex(int year, IReadOnlyList<int> froms)
|
||||
{
|
||||
int index = 0;
|
||||
for (int i = 0; i < froms.Count; i++)
|
||||
{
|
||||
if (froms[i] <= year) index = i;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
/// <summary>Avvicina un valore al bersaglio con velocità costante (unità al secondo).</summary>
|
||||
public static float Approach(float current, float target, float ratePerSecond, float dt)
|
||||
{
|
||||
float step = ratePerSecond * dt;
|
||||
return current < target ? MathF.Min(target, current + step) : MathF.Max(target, current - step);
|
||||
}
|
||||
|
||||
/// <summary>Lineare → decibel, con −80 dB come silenzio.</summary>
|
||||
public static float LinearToDb(float linear) => linear <= 0.0001f ? -80f : 20f * MathF.Log10(linear);
|
||||
|
||||
/// <summary>Campioni in [−1, 1] → PCM a 16 bit little-endian (formato di AudioStreamWAV).</summary>
|
||||
public static byte[] ToPcm16(float[] samples)
|
||||
{
|
||||
var bytes = new byte[samples.Length * 2];
|
||||
for (int i = 0; i < samples.Length; i++)
|
||||
{
|
||||
short s = (short)Math.Clamp((int)MathF.Round(samples[i] * 32767f), short.MinValue, short.MaxValue);
|
||||
bytes[2 * i] = (byte)s;
|
||||
bytes[2 * i + 1] = (byte)(s >> 8);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using Godot;
|
||||
|
||||
namespace RailEnterprise.Client.Audio;
|
||||
|
||||
/// <summary>Bus audio del client: Master e quattro bus che vi confluiscono.</summary>
|
||||
public static class AudioBuses
|
||||
{
|
||||
public const string Master = "Master";
|
||||
public const string Music = "Music";
|
||||
public const string Ambience = "Ambience";
|
||||
public const string Sfx = "Sfx";
|
||||
public const string Ui = "Ui";
|
||||
|
||||
/// <summary>Nell'ordine dei cursori delle impostazioni.</summary>
|
||||
public static readonly string[] All = [Master, Music, Ambience, Sfx, Ui];
|
||||
|
||||
/// <summary>
|
||||
/// Crea i bus che mancano (idempotente: chiamarla più volte non ne aggiunge altri) e un
|
||||
/// limitatore sul Master, così la somma di musica, ambiente ed effetti non satura.
|
||||
/// </summary>
|
||||
public static void Ensure()
|
||||
{
|
||||
foreach (string name in All)
|
||||
{
|
||||
if (name == Master || AudioServer.GetBusIndex(name) >= 0) continue;
|
||||
int index = AudioServer.BusCount;
|
||||
AudioServer.AddBus(index);
|
||||
AudioServer.SetBusName(index, name);
|
||||
AudioServer.SetBusSend(index, Master);
|
||||
}
|
||||
bool limited = false;
|
||||
for (int i = 0; i < AudioServer.GetBusEffectCount(0); i++)
|
||||
{
|
||||
if (AudioServer.GetBusEffect(0, i) is AudioEffectHardLimiter) limited = true;
|
||||
}
|
||||
if (!limited) AudioServer.AddBusEffect(0, new AudioEffectHardLimiter { CeilingDb = -0.5f });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Volumi per bus (0–1) e muto generale, salvati nella sezione «audio» di
|
||||
/// <c>user://settings.cfg</c> (lo stesso file della lingua e del server).
|
||||
/// </summary>
|
||||
public sealed class AudioSettings
|
||||
{
|
||||
public const string Path = "user://settings.cfg";
|
||||
private const string Section = "audio";
|
||||
|
||||
private static readonly float[] Defaults = [0.8f, 0.55f, 0.7f, 0.8f, 0.7f];
|
||||
|
||||
/// <summary>Volumi nell'ordine di <see cref="AudioBuses.All"/>.</summary>
|
||||
public float[] Volumes { get; } = (float[])Defaults.Clone();
|
||||
|
||||
public bool Muted { get; set; }
|
||||
|
||||
public static AudioSettings Load()
|
||||
{
|
||||
var s = new AudioSettings();
|
||||
var cfg = new ConfigFile();
|
||||
if (cfg.Load(Path) != Error.Ok) return s;
|
||||
for (int i = 0; i < AudioBuses.All.Length; i++)
|
||||
{
|
||||
float v = (float)(double)cfg.GetValue(Section, Key(i), Defaults[i]);
|
||||
s.Volumes[i] = Math.Clamp(v, 0, 1);
|
||||
}
|
||||
s.Muted = (bool)cfg.GetValue(Section, "muted", false);
|
||||
return s;
|
||||
}
|
||||
|
||||
public void Save()
|
||||
{
|
||||
var cfg = new ConfigFile();
|
||||
cfg.Load(Path);
|
||||
for (int i = 0; i < AudioBuses.All.Length; i++) cfg.SetValue(Section, Key(i), Volumes[i]);
|
||||
cfg.SetValue(Section, "muted", Muted);
|
||||
cfg.Save(Path);
|
||||
}
|
||||
|
||||
private static string Key(int i) => AudioBuses.All[i].ToLowerInvariant();
|
||||
|
||||
/// <summary>Applica volumi e muto ai bus (il cursore segue il volume percepito: guadagno = valore²).</summary>
|
||||
public void Apply()
|
||||
{
|
||||
for (int i = 0; i < AudioBuses.All.Length; i++)
|
||||
{
|
||||
int bus = AudioServer.GetBusIndex(AudioBuses.All[i]);
|
||||
if (bus >= 0) AudioServer.SetBusVolumeDb(bus, AudioMix.LinearToDb(Volumes[i] * Volumes[i]));
|
||||
}
|
||||
AudioServer.SetBusMute(0, Muted);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
|
||||
namespace RailEnterprise.Client.Audio;
|
||||
|
||||
/// <summary>
|
||||
/// Pannello «Audio» sopra a tutto: un cursore per bus (generale, musica, ambiente, effetti,
|
||||
/// interfaccia) e il muto generale. I cambi si sentono subito; quando il pannello esce dall'albero
|
||||
/// (anche chiudendo la finestra del gioco) si salvano in <c>user://settings.cfg</c>. Esc o un clic
|
||||
/// sinistro fuori chiudono.
|
||||
/// </summary>
|
||||
public partial class AudioSettingsPanel : Control
|
||||
{
|
||||
private readonly AudioManager _audio;
|
||||
private readonly List<(HSlider Slider, Label Value)> _rows = [];
|
||||
private readonly CheckBox _mute = new() { Text = T("Muto") };
|
||||
|
||||
private static readonly string[] Captions = ["Volume generale", "Musica", "Ambiente", "Effetti", "Interfaccia"];
|
||||
|
||||
public AudioSettingsPanel(AudioManager audio) => _audio = audio;
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect);
|
||||
UiTheme.Apply(this);
|
||||
var shade = new ColorRect { Color = new Color(0, 0, 0, 0.5f), MouseFilter = MouseFilterEnum.Stop };
|
||||
shade.SetAnchorsPreset(LayoutPreset.FullRect);
|
||||
shade.GuiInput += e =>
|
||||
{
|
||||
// solo il clic sinistro: la rotella e il tasto destro arrivano anch'essi come pressioni
|
||||
if (e is InputEventMouseButton { Pressed: true, ButtonIndex: MouseButton.Left }) Close();
|
||||
};
|
||||
AddChild(shade);
|
||||
var center = new CenterContainer { MouseFilter = MouseFilterEnum.Ignore };
|
||||
center.SetAnchorsPreset(LayoutPreset.FullRect);
|
||||
AddChild(center);
|
||||
var panel = new PanelContainer { CustomMinimumSize = new Vector2(440, 0) };
|
||||
center.AddChild(panel);
|
||||
var col = new VBoxContainer();
|
||||
col.AddThemeConstantOverride("separation", 12);
|
||||
panel.AddChild(col);
|
||||
col.AddChild(UiTheme.TitleLabel(T("Audio"), 34));
|
||||
|
||||
for (int i = 0; i < Captions.Length; i++)
|
||||
{
|
||||
int bus = i;
|
||||
var row = new HBoxContainer();
|
||||
row.AddThemeConstantOverride("separation", 12);
|
||||
var caption = UiTheme.Text(T(Captions[i]), 14, Palette.TextSecondary);
|
||||
caption.CustomMinimumSize = new Vector2(150, 0);
|
||||
row.AddChild(caption);
|
||||
var slider = new HSlider
|
||||
{
|
||||
MinValue = 0, MaxValue = 1, Step = 0.05, SizeFlagsHorizontal = SizeFlags.ExpandFill,
|
||||
SizeFlagsVertical = SizeFlags.ShrinkCenter, Value = _audio.Settings.Volumes[i],
|
||||
};
|
||||
var value = UiTheme.Text("", 14, bold: true);
|
||||
value.CustomMinimumSize = new Vector2(48, 0);
|
||||
value.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
slider.ValueChanged += v => _audio.SetVolume(bus, (float)v);
|
||||
row.AddChild(slider);
|
||||
row.AddChild(value);
|
||||
col.AddChild(row);
|
||||
_rows.Add((slider, value));
|
||||
}
|
||||
_mute.ButtonPressed = _audio.Settings.Muted;
|
||||
_mute.Toggled += on => _audio.SetMuted(on);
|
||||
col.AddChild(_mute);
|
||||
var hint = UiTheme.Text(T("Il tasto M attiva e toglie il muto durante la partita."), 13, Palette.TextSecondary);
|
||||
hint.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
col.AddChild(hint);
|
||||
var close = UiTheme.Primary(T("Chiudi"));
|
||||
close.Pressed += Close;
|
||||
col.AddChild(close);
|
||||
_audio.SettingsChanged += Refresh;
|
||||
Refresh();
|
||||
}
|
||||
|
||||
public override void _ExitTree()
|
||||
{
|
||||
_audio.SettingsChanged -= Refresh;
|
||||
_audio.SaveSettings();
|
||||
}
|
||||
|
||||
private void Refresh()
|
||||
{
|
||||
for (int i = 0; i < _rows.Count; i++)
|
||||
{
|
||||
_rows[i].Slider.SetValueNoSignal(_audio.Settings.Volumes[i]);
|
||||
_rows[i].Value.Text = $"{Math.Round(_audio.Settings.Volumes[i] * 100):0} %";
|
||||
}
|
||||
_mute.SetPressedNoSignal(_audio.Settings.Muted);
|
||||
}
|
||||
|
||||
public override void _Input(InputEvent e)
|
||||
{
|
||||
if (e is InputEventKey { Pressed: true, Keycode: Key.Escape })
|
||||
{
|
||||
Close();
|
||||
GetViewport().SetInputAsHandled();
|
||||
}
|
||||
}
|
||||
|
||||
private void Close()
|
||||
{
|
||||
if (IsQueuedForDeletion()) return;
|
||||
QueueFree();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
namespace RailEnterprise.Client.Audio;
|
||||
|
||||
/// <summary>
|
||||
/// Temi musicali procedurali per era, senza dipendenze da Godot. Ogni era ha uno stile (tempo,
|
||||
/// metro, scala, timbri: valzer da carillon e fisarmonica per il vapore, organo e basso che
|
||||
/// cammina per il diesel, vibrafono e archi per l'elettrico, arpeggi a impulsi per l'alta
|
||||
/// velocità); progressione, arpeggio e melodia escono da un seme fisso (hash dell'id dell'era),
|
||||
/// quindi lo stesso tema a ogni avvio. Forma in 16 battute: introduzione (accompagnamento),
|
||||
/// melodia, melodia variata, coda; le code delle note rientrano dall'inizio, così l'anello si
|
||||
/// ripete senza scatti. Uscita mono a <see cref="Synth.Rate"/> Hz.
|
||||
/// </summary>
|
||||
public static class MusicComposer
|
||||
{
|
||||
public const int Bars = 16;
|
||||
|
||||
public enum Timbre { MusicBox, Accordion, Organ, Vibraphone, Strings, Pulse, Saw, SoftBass, PluckBass }
|
||||
|
||||
public enum Comping { Held, Waltz }
|
||||
|
||||
/// <summary>Stile di un'era.</summary>
|
||||
public sealed record Style(int Bpm, int BeatsPerBar, int[] Scale, int RootMidi, Timbre Pad, Comping Comping,
|
||||
Timbre Arp, int ArpPerBeat, Timbre Lead, Timbre Bass, bool WalkingBass, float Swing);
|
||||
|
||||
private static readonly int[] Major = [0, 2, 4, 5, 7, 9, 11];
|
||||
private static readonly int[] Mixolydian = [0, 2, 4, 5, 7, 9, 10];
|
||||
private static readonly int[] Dorian = [0, 2, 3, 5, 7, 9, 10];
|
||||
|
||||
/// <summary>Progressioni per grado della scala (0 = primo grado), una battuta per accordo.</summary>
|
||||
private static readonly int[][] Progressions =
|
||||
[
|
||||
[0, 3, 4, 0], [0, 5, 3, 4], [0, 4, 5, 3], [1, 4, 0, 5], [5, 3, 0, 4], [0, 3, 1, 4],
|
||||
];
|
||||
|
||||
/// <summary>Stile dell'era per posizione nell'elenco di eras.json (le ere oltre la quarta riprendono il ciclo).</summary>
|
||||
public static Style StyleFor(int eraIndex) => (Math.Max(0, eraIndex) % 4) switch
|
||||
{
|
||||
0 => new Style(116, 3, Major, 62, Timbre.Accordion, Comping.Waltz, Timbre.MusicBox, 0, Timbre.MusicBox, Timbre.SoftBass, false, 0),
|
||||
1 => new Style(96, 4, Mixolydian, 60, Timbre.Organ, Comping.Held, Timbre.Vibraphone, 1, Timbre.Organ, Timbre.PluckBass, true, 0.18f),
|
||||
2 => new Style(104, 4, Major, 65, Timbre.Strings, Comping.Held, Timbre.Vibraphone, 2, Timbre.Vibraphone, Timbre.SoftBass, false, 0),
|
||||
_ => new Style(124, 4, Dorian, 57, Timbre.Saw, Comping.Held, Timbre.Pulse, 4, Timbre.Saw, Timbre.SoftBass, false, 0),
|
||||
};
|
||||
|
||||
/// <summary>Seme fisso del tema: hash dell'id dell'era e della sua posizione.</summary>
|
||||
public static ulong Seed(int eraIndex, string eraId) => SynthRng.Hash(eraId) ^ ((ulong)(eraIndex + 1) * 0x9E3779B97F4A7C15UL);
|
||||
|
||||
/// <summary>Durata dell'anello in secondi.</summary>
|
||||
public static float LengthSeconds(Style style) => Bars * style.BeatsPerBar * 60f / style.Bpm;
|
||||
|
||||
// ------------------------------------------------------------------ timbri
|
||||
|
||||
private sealed class Voice
|
||||
{
|
||||
/// <summary>Ampiezza della n-esima armonica in Harmonics[n−1].</summary>
|
||||
public required float[] Harmonics { get; init; }
|
||||
public float Attack { get; init; } = 0.005f;
|
||||
/// <summary>Decadimento verso il sostegno (s).</summary>
|
||||
public float Decay { get; init; } = 0.3f;
|
||||
public float Sustain { get; init; }
|
||||
public float Release { get; init; } = 0.1f;
|
||||
/// <summary>Copie leggermente scordate (coro).</summary>
|
||||
public float[] Detune { get; init; } = [0];
|
||||
public float TremoloHz { get; init; }
|
||||
public float TremoloDepth { get; init; }
|
||||
public float VibratoDepth { get; init; }
|
||||
|
||||
// tabelle per numero di armoniche tenute (una per registro, costruite al primo uso)
|
||||
private readonly Dictionary<int, float[]> _tables = [];
|
||||
|
||||
/// <summary>
|
||||
/// Forma d'onda per una nota alla frequenza data, con le sole armoniche sotto
|
||||
/// <see cref="MaxHarmonicShare"/> della frequenza di campionamento: quelle oltre Nyquist
|
||||
/// tornerebbero indietro come toni stonati.
|
||||
/// </summary>
|
||||
public float[] TableFor(float frequency)
|
||||
{
|
||||
int n = Math.Clamp((int)(MaxHarmonicShare * Synth.Rate / frequency), 1, Harmonics.Length);
|
||||
if (!_tables.TryGetValue(n, out var table))
|
||||
{
|
||||
table = Table(Harmonics, n);
|
||||
_tables[n] = table;
|
||||
}
|
||||
return table;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Frazione della frequenza di campionamento sotto cui stanno le armoniche (margine per vibrato e coro).</summary>
|
||||
private const float MaxHarmonicShare = 0.45f;
|
||||
|
||||
private const int TableSize = 2048;
|
||||
|
||||
/// <summary>Forma d'onda di un periodo dalla somma delle prime «count» armoniche (ampiezza della n-esima in harmonics[n−1]).</summary>
|
||||
private static float[] Table(float[] harmonics, int count)
|
||||
{
|
||||
var t = new float[TableSize];
|
||||
for (int i = 0; i < TableSize; i++)
|
||||
{
|
||||
float x = MathF.PI * 2 * i / TableSize;
|
||||
float v = 0;
|
||||
for (int h = 0; h < count; h++) v += harmonics[h] * MathF.Sin(x * (h + 1));
|
||||
t[i] = v;
|
||||
}
|
||||
Synth.Normalize(t, 1);
|
||||
return t;
|
||||
}
|
||||
|
||||
private static float[] SawHarmonics(int n)
|
||||
{
|
||||
var h = new float[n];
|
||||
for (int i = 0; i < n; i++) h[i] = 1f / (i + 1);
|
||||
return h;
|
||||
}
|
||||
|
||||
private static float[] PulseHarmonics(int n, float duty)
|
||||
{
|
||||
var h = new float[n];
|
||||
for (int i = 0; i < n; i++) h[i] = MathF.Abs(MathF.Sin(MathF.PI * (i + 1) * duty)) / (i + 1);
|
||||
return h;
|
||||
}
|
||||
|
||||
private static Voice VoiceFor(Timbre timbre) => timbre switch
|
||||
{
|
||||
Timbre.MusicBox => new Voice { Harmonics = [1, 0.1f, 0.35f, 0, 0.12f], Attack = 0.002f, Decay = 0.7f, Sustain = 0, Release = 0.6f },
|
||||
Timbre.Accordion => new Voice { Harmonics = [1, 0.5f, 0.6f, 0.3f, 0.25f, 0.15f], Attack = 0.03f, Decay = 0.2f, Sustain = 0.8f, Release = 0.08f, Detune = [0, 0.004f], TremoloHz = 5, TremoloDepth = 0.12f },
|
||||
Timbre.Organ => new Voice { Harmonics = [1, 0.8f, 0.6f, 0.4f, 0, 0.3f, 0, 0.2f], Attack = 0.01f, Decay = 0.1f, Sustain = 0.9f, Release = 0.06f, TremoloHz = 6, TremoloDepth = 0.1f },
|
||||
Timbre.Vibraphone => new Voice { Harmonics = [1, 0, 0, 0.25f], Attack = 0.003f, Decay = 1.1f, Sustain = 0, Release = 0.8f, TremoloHz = 5, TremoloDepth = 0.3f },
|
||||
Timbre.Strings => new Voice { Harmonics = SawHarmonics(8), Attack = 0.3f, Decay = 0.5f, Sustain = 0.85f, Release = 0.35f, Detune = [-0.003f, 0, 0.003f], VibratoDepth = 0.003f },
|
||||
Timbre.Pulse => new Voice { Harmonics = PulseHarmonics(9, 0.25f), Attack = 0.004f, Decay = 0.22f, Sustain = 0, Release = 0.15f },
|
||||
Timbre.Saw => new Voice { Harmonics = SawHarmonics(10), Attack = 0.08f, Decay = 0.4f, Sustain = 0.7f, Release = 0.25f, Detune = [-0.005f, 0.005f], VibratoDepth = 0.002f },
|
||||
Timbre.PluckBass => new Voice { Harmonics = [1, 0.5f, 0.25f, 0.1f], Attack = 0.005f, Decay = 0.35f, Sustain = 0.15f, Release = 0.08f },
|
||||
_ => new Voice { Harmonics = [1, 0.3f, 0.1f], Attack = 0.01f, Decay = 0.4f, Sustain = 0.6f, Release = 0.1f },
|
||||
};
|
||||
|
||||
private static float Frequency(float midi) => 440f * MathF.Pow(2, (midi - 69) / 12f);
|
||||
|
||||
/// <summary>Suona una nota nell'anello (con la coda che rientra dall'inizio).</summary>
|
||||
private static void Note(float[] loop, Voice v, float startS, float durS, float midi, float gain)
|
||||
{
|
||||
int rate = Synth.Rate;
|
||||
float f = Frequency(midi);
|
||||
var table = v.TableFor(f);
|
||||
int start = (int)(startS * rate);
|
||||
float total = durS + v.Release;
|
||||
int samples = Math.Min(loop.Length, (int)(total * rate));
|
||||
foreach (float detune in v.Detune)
|
||||
{
|
||||
float inc = f * (1 + detune) * TableSize / rate;
|
||||
float phase = (detune + 0.5f) * 97 % TableSize;
|
||||
float g = gain / v.Detune.Length;
|
||||
for (int i = 0; i < samples; i++)
|
||||
{
|
||||
float t = i / (float)rate;
|
||||
float env = t < v.Attack ? t / v.Attack : v.Sustain + (1 - v.Sustain) * MathF.Exp(-(t - v.Attack) / v.Decay);
|
||||
if (t > durS)
|
||||
{
|
||||
// rilascio dal livello raggiunto alla fine della nota
|
||||
float atEnd = durS < v.Attack ? durS / v.Attack : v.Sustain + (1 - v.Sustain) * MathF.Exp(-(durS - v.Attack) / v.Decay);
|
||||
env = atEnd * MathF.Max(0, 1 - (t - durS) / v.Release);
|
||||
}
|
||||
if (v.TremoloDepth > 0) env *= 1 - v.TremoloDepth * (0.5f + 0.5f * MathF.Sin(MathF.PI * 2 * v.TremoloHz * t));
|
||||
float step = v.VibratoDepth > 0 ? inc * (1 + v.VibratoDepth * MathF.Sin(MathF.PI * 2 * 5.5f * t)) : inc;
|
||||
phase += step;
|
||||
if (phase >= TableSize) phase -= TableSize;
|
||||
int i0 = (int)phase;
|
||||
float frac = phase - i0;
|
||||
float s = table[i0] + (table[(i0 + 1) & (TableSize - 1)] - table[i0]) * frac;
|
||||
loop[(start + i) % loop.Length] += s * env * g;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Altezza MIDI del grado della scala (i gradi oltre la scala salgono d'ottava).</summary>
|
||||
private static int Degree(Style s, int degree)
|
||||
{
|
||||
int n = s.Scale.Length;
|
||||
int octave = (int)Math.Floor(degree / (double)n);
|
||||
int d = degree - octave * n;
|
||||
return s.RootMidi + s.Scale[d] + 12 * octave;
|
||||
}
|
||||
|
||||
/// <summary>Compone e sintetizza il tema dell'era: campioni mono in [−1, 1].</summary>
|
||||
public static float[] Compose(int eraIndex, string eraId)
|
||||
{
|
||||
var style = StyleFor(eraIndex);
|
||||
var rng = new SynthRng(Seed(eraIndex, eraId));
|
||||
float beat = 60f / style.Bpm;
|
||||
float bar = beat * style.BeatsPerBar;
|
||||
var loop = new float[(int)(LengthSeconds(style) * Synth.Rate)];
|
||||
var progression = Progressions[rng.Next(Progressions.Length)];
|
||||
var pad = VoiceFor(style.Pad);
|
||||
var arp = VoiceFor(style.Arp);
|
||||
var lead = VoiceFor(style.Lead);
|
||||
var bass = VoiceFor(style.Bass);
|
||||
bool arpDown = rng.Next(2) == 0;
|
||||
|
||||
// motivo di quattro battute: un ritmo per battuta (in ottavi) e gradi vicini all'accordo
|
||||
int eighths = style.BeatsPerBar * 2;
|
||||
var motif = new List<(int Bar, int Eighth, int Length, int Degree)>();
|
||||
int current = 7 + progression[0];
|
||||
for (int b = 0; b < 4; b++)
|
||||
{
|
||||
int chord = progression[b];
|
||||
int e = 0;
|
||||
while (e < eighths)
|
||||
{
|
||||
int len = rng.Next(4) switch { 0 => 1, 1 or 2 => 2, _ => 3 };
|
||||
len = Math.Min(len, eighths - e);
|
||||
if (rng.Next(5) == 0 && e > 0)
|
||||
{
|
||||
e += len; // pausa
|
||||
continue;
|
||||
}
|
||||
bool strong = e % (style.BeatsPerBar == 3 ? 6 : 4) == 0;
|
||||
if (strong)
|
||||
{
|
||||
// sui tempi forti una nota dell'accordo vicina alla precedente
|
||||
int best = current, bestD = int.MaxValue;
|
||||
for (int k = -1; k <= 2; k++)
|
||||
{
|
||||
foreach (int ct in new[] { 0, 2, 4 })
|
||||
{
|
||||
int cand = chord + ct + 7 * k;
|
||||
int dist = Math.Abs(cand - current);
|
||||
if (cand >= 4 && cand <= 13 && dist < bestD)
|
||||
{
|
||||
bestD = dist;
|
||||
best = cand;
|
||||
}
|
||||
}
|
||||
}
|
||||
current = best;
|
||||
}
|
||||
else current = Math.Clamp(current + rng.Next(5) - 2, 4, 13);
|
||||
motif.Add((b, e, len, current));
|
||||
e += len;
|
||||
}
|
||||
}
|
||||
// l'ultima nota del motivo torna sulla tonica
|
||||
if (motif.Count > 0) motif[^1] = motif[^1] with { Degree = 7 };
|
||||
|
||||
for (int barIndex = 0; barIndex < Bars; barIndex++)
|
||||
{
|
||||
int chord = progression[barIndex % 4];
|
||||
float t0 = barIndex * bar;
|
||||
int[] tones = [Degree(style, chord), Degree(style, chord + 2), Degree(style, chord + 4)];
|
||||
|
||||
// accompagnamento
|
||||
if (style.Comping == Comping.Waltz)
|
||||
{
|
||||
for (int k = 1; k < style.BeatsPerBar; k++)
|
||||
foreach (int m in tones) Note(loop, pad, t0 + k * beat, beat * 0.55f, m, 0.11f);
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (int m in tones) Note(loop, pad, t0, bar * 0.95f, m, 0.12f);
|
||||
}
|
||||
|
||||
// basso: fondamentale (e quinta) o basso che cammina sulle note dell'accordo
|
||||
int root = Degree(style, chord) - 24;
|
||||
if (style.WalkingBass)
|
||||
{
|
||||
int next = Degree(style, progression[(barIndex + 1) % 4]) - 24;
|
||||
int[] walk = [root, root + (tones[1] - tones[0]), root + 7, next + (next > root ? -1 : 1)];
|
||||
for (int k = 0; k < style.BeatsPerBar; k++) Note(loop, bass, t0 + k * beat, beat * 0.9f, walk[k % walk.Length], 0.32f);
|
||||
}
|
||||
else if (style.Comping == Comping.Waltz) Note(loop, bass, t0, beat * 0.9f, root, 0.34f);
|
||||
else
|
||||
{
|
||||
Note(loop, bass, t0, beat * 1.8f, root, 0.32f);
|
||||
Note(loop, bass, t0 + 2 * beat, beat * 1.8f, root + 7, 0.26f);
|
||||
}
|
||||
|
||||
// arpeggio (in introduzione e coda più presente)
|
||||
if (style.ArpPerBeat > 0)
|
||||
{
|
||||
int steps = style.BeatsPerBar * style.ArpPerBeat;
|
||||
float step = beat / style.ArpPerBeat;
|
||||
float gain = barIndex is < 4 or >= 12 ? 0.13f : 0.08f;
|
||||
for (int k = 0; k < steps; k++)
|
||||
{
|
||||
int idx = arpDown ? 3 - k % 4 : k % 4;
|
||||
int m = idx < 3 ? tones[idx] + 12 : tones[0] + 24;
|
||||
float swing = style.Swing > 0 && k % 2 == 1 ? style.Swing * step : 0;
|
||||
Note(loop, arp, t0 + k * step + swing, step * 0.8f, m, gain);
|
||||
}
|
||||
}
|
||||
|
||||
// melodia nelle battute 4–11 (la seconda volta un'ottava sopra le ultime due battute)
|
||||
if (barIndex is >= 4 and < 12)
|
||||
{
|
||||
int motifBar = barIndex % 4;
|
||||
bool variation = barIndex >= 8;
|
||||
foreach (var n in motif)
|
||||
{
|
||||
if (n.Bar != motifBar) continue;
|
||||
float eighth = beat / 2;
|
||||
float swing = style.Swing > 0 && n.Eighth % 2 == 1 ? style.Swing * eighth : 0;
|
||||
int midi = Degree(style, n.Degree) + (variation && motifBar >= 2 ? 12 : 0);
|
||||
Note(loop, lead, t0 + n.Eighth * eighth + swing, n.Length * eighth * 0.92f, midi, 0.2f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// un po' di spazio: due echi smorzati sull'anello, poi limitazione morbida
|
||||
Echo(loop, 0.27f, 0.22f);
|
||||
Echo(loop, 0.41f, 0.15f);
|
||||
Synth.Normalize(loop, 1);
|
||||
for (int i = 0; i < loop.Length; i++) loop[i] = MathF.Tanh(loop[i] * 1.2f) * 0.7f;
|
||||
return loop;
|
||||
}
|
||||
|
||||
/// <summary>Eco con retroazione su un anello (due giri per la continuità all'inizio).</summary>
|
||||
private static void Echo(float[] loop, float delayS, float feedback)
|
||||
{
|
||||
int d = Math.Max(1, (int)(delayS * Synth.Rate));
|
||||
var lp = Biquad.LowPass(2500, 0.7f, Synth.Rate);
|
||||
var wet = new float[loop.Length];
|
||||
for (int pass = 0; pass < 2; pass++)
|
||||
{
|
||||
for (int i = 0; i < loop.Length; i++)
|
||||
{
|
||||
int j = (i - d + loop.Length) % loop.Length;
|
||||
wet[i] = lp.Process(loop[j] + wet[j] * feedback) * feedback;
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < loop.Length; i++) loop[i] += wet[i];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
|
||||
namespace RailEnterprise.Client.Audio;
|
||||
|
||||
/// <summary>Altoparlante nella barra superiore: apre il pannello «Audio»; barrato quando il muto è attivo.</summary>
|
||||
public partial class SpeakerButton : Button
|
||||
{
|
||||
public SpeakerButton()
|
||||
{
|
||||
Flat = true;
|
||||
CustomMinimumSize = new Vector2(40, 40);
|
||||
TooltipText = T("Audio (M: muto)");
|
||||
Pressed += () => AudioManager.Instance?.ShowSettings();
|
||||
MouseEntered += QueueRedraw;
|
||||
MouseExited += QueueRedraw;
|
||||
}
|
||||
|
||||
public override void _EnterTree()
|
||||
{
|
||||
if (AudioManager.Instance is { } audio) audio.SettingsChanged += QueueRedraw;
|
||||
}
|
||||
|
||||
public override void _ExitTree()
|
||||
{
|
||||
if (AudioManager.Instance is { } audio) audio.SettingsChanged -= QueueRedraw;
|
||||
}
|
||||
|
||||
public override void _Draw()
|
||||
{
|
||||
bool muted = AudioManager.Instance?.Settings.Muted ?? false;
|
||||
var col = IsHovered() ? Palette.AmberLight : muted ? Palette.TextSecondary : Palette.Text;
|
||||
var c = Size / 2;
|
||||
const float w = 2f;
|
||||
// cassa e cono
|
||||
DrawColoredPolygon([c + new Vector2(-10, -4), c + new Vector2(-5, -4), c + new Vector2(1, -10), c + new Vector2(1, 10), c + new Vector2(-5, 4), c + new Vector2(-10, 4)], col);
|
||||
if (muted)
|
||||
{
|
||||
DrawLine(c + new Vector2(5, -5), c + new Vector2(13, 5), Palette.Danger, w);
|
||||
DrawLine(c + new Vector2(13, -5), c + new Vector2(5, 5), Palette.Danger, w);
|
||||
}
|
||||
else
|
||||
{
|
||||
DrawArc(c + new Vector2(1, 0), 6, -0.9f, 0.9f, 10, col, w);
|
||||
DrawArc(c + new Vector2(1, 0), 11, -0.9f, 0.9f, 14, col, w);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,554 @@
|
||||
namespace RailEnterprise.Client.Audio;
|
||||
|
||||
/// <summary>
|
||||
/// Generatore pseudo-casuale xorshift64* per la sintesi dei suoni. Non è il <c>Rng</c> della
|
||||
/// simulazione: serve solo a rendere ripetibili rumori, variazioni e temi musicali del client.
|
||||
/// </summary>
|
||||
public struct SynthRng
|
||||
{
|
||||
private ulong _s;
|
||||
|
||||
public SynthRng(ulong seed) => _s = seed == 0 ? 0x9E3779B97F4A7C15UL : seed;
|
||||
|
||||
public ulong NextU64()
|
||||
{
|
||||
_s ^= _s >> 12;
|
||||
_s ^= _s << 25;
|
||||
_s ^= _s >> 27;
|
||||
return _s * 2685821657736338717UL;
|
||||
}
|
||||
|
||||
/// <summary>Numero in [0, 1).</summary>
|
||||
public float Next01() => (NextU64() >> 40) * (1f / (1 << 24));
|
||||
|
||||
/// <summary>Numero in [−1, 1).</summary>
|
||||
public float NextSigned() => Next01() * 2f - 1f;
|
||||
|
||||
/// <summary>Intero in [0, n).</summary>
|
||||
public int Next(int n) => (int)((NextU64() >> 33) % (ulong)n);
|
||||
|
||||
/// <summary>Numero in [a, b).</summary>
|
||||
public float Range(float a, float b) => a + (b - a) * Next01();
|
||||
|
||||
/// <summary>FNV-1a a 64 bit di una stringa: semi fissi derivati da un identificatore (per esempio l'id dell'era).</summary>
|
||||
public static ulong Hash(string text)
|
||||
{
|
||||
ulong h = 14695981039346656037UL;
|
||||
foreach (char c in text)
|
||||
{
|
||||
h ^= c;
|
||||
h *= 1099511628211UL;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Filtro biquadratico (formule RBJ): passa-basso, passa-alto, passa-banda a guadagno di picco unitario.</summary>
|
||||
public struct Biquad
|
||||
{
|
||||
private float _b0, _b1, _b2, _a1, _a2, _z1, _z2;
|
||||
|
||||
private static Biquad Make(float b0, float b1, float b2, float a0, float a1, float a2) =>
|
||||
new() { _b0 = b0 / a0, _b1 = b1 / a0, _b2 = b2 / a0, _a1 = a1 / a0, _a2 = a2 / a0 };
|
||||
|
||||
private static (float Cos, float Alpha) W(float freq, float q, int rate)
|
||||
{
|
||||
float w0 = 2 * MathF.PI * Math.Clamp(freq, 1, rate * 0.45f) / rate;
|
||||
return (MathF.Cos(w0), MathF.Sin(w0) / (2 * q));
|
||||
}
|
||||
|
||||
public static Biquad LowPass(float freq, float q, int rate)
|
||||
{
|
||||
var (c, a) = W(freq, q, rate);
|
||||
return Make((1 - c) / 2, 1 - c, (1 - c) / 2, 1 + a, -2 * c, 1 - a);
|
||||
}
|
||||
|
||||
public static Biquad HighPass(float freq, float q, int rate)
|
||||
{
|
||||
var (c, a) = W(freq, q, rate);
|
||||
return Make((1 + c) / 2, -(1 + c), (1 + c) / 2, 1 + a, -2 * c, 1 - a);
|
||||
}
|
||||
|
||||
public static Biquad BandPass(float freq, float q, int rate)
|
||||
{
|
||||
var (c, a) = W(freq, q, rate);
|
||||
return Make(a, 0, -a, 1 + a, -2 * c, 1 - a);
|
||||
}
|
||||
|
||||
/// <summary>Cambia i coefficienti mantenendo lo stato (filtri a frequenza variabile).</summary>
|
||||
public void Retune(Biquad coefficients)
|
||||
{
|
||||
_b0 = coefficients._b0;
|
||||
_b1 = coefficients._b1;
|
||||
_b2 = coefficients._b2;
|
||||
_a1 = coefficients._a1;
|
||||
_a2 = coefficients._a2;
|
||||
}
|
||||
|
||||
public float Process(float x)
|
||||
{
|
||||
float y = _b0 * x + _z1;
|
||||
_z1 = _b1 * x - _a1 * y + _z2;
|
||||
_z2 = _b2 * x - _a2 * y;
|
||||
return y;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sintesi procedurale di tutti gli effetti del gioco, senza dipendenze da Godot: ogni funzione
|
||||
/// restituisce campioni mono in virgola mobile a <see cref="Rate"/> Hz, da convertire in PCM a
|
||||
/// 16 bit con <see cref="AudioMix.ToPcm16"/>. Gli anelli («Loop») si ripetono senza scatti: i
|
||||
/// filtri girano due volte sullo stesso rumore (la seconda passata parte dallo stato della fine),
|
||||
/// le modulazioni hanno un numero intero di periodi nell'anello e le code degli eventi brevi
|
||||
/// rientrano dall'inizio. Semi fissi: stesso suono a ogni avvio.
|
||||
/// </summary>
|
||||
public static class Synth
|
||||
{
|
||||
/// <summary>Frequenza di campionamento di tutti i suoni (Hz).</summary>
|
||||
public const int Rate = 22050;
|
||||
|
||||
private const float Tau = MathF.PI * 2;
|
||||
|
||||
public static float[] Buffer(float seconds) => new float[Math.Max(1, (int)(seconds * Rate))];
|
||||
|
||||
/// <summary>Inviluppo attacco lineare e decadimento esponenziale.</summary>
|
||||
public static float Env(float t, float attack, float decay) =>
|
||||
t < 0 ? 0 : t < attack ? t / attack : MathF.Exp(-(t - attack) / decay);
|
||||
|
||||
/// <summary>Porta il picco al valore indicato.</summary>
|
||||
public static void Normalize(float[] buffer, float peak)
|
||||
{
|
||||
float max = 0;
|
||||
foreach (float s in buffer) max = Math.Max(max, Math.Abs(s));
|
||||
if (max < 1e-6f) return;
|
||||
float k = peak / max;
|
||||
for (int i = 0; i < buffer.Length; i++) buffer[i] *= k;
|
||||
}
|
||||
|
||||
/// <summary>Sfuma gli ultimi millisecondi di un suono singolo (niente scatto alla fine).</summary>
|
||||
public static void FadeOut(float[] buffer, float seconds = 0.01f)
|
||||
{
|
||||
int n = Math.Min(buffer.Length, (int)(seconds * Rate));
|
||||
for (int i = 0; i < n; i++) buffer[buffer.Length - 1 - i] *= i / (float)n;
|
||||
}
|
||||
|
||||
/// <summary>Rumore bianco ripetibile.</summary>
|
||||
public static float[] Noise(int length, ulong seed)
|
||||
{
|
||||
var rng = new SynthRng(seed);
|
||||
var n = new float[length];
|
||||
for (int i = 0; i < length; i++) n[i] = rng.NextSigned();
|
||||
return n;
|
||||
}
|
||||
|
||||
/// <summary>Filtra un anello due volte: la seconda passata riparte dallo stato della fine della prima.</summary>
|
||||
public static float[] LoopFilter(float[] input, Biquad filter)
|
||||
{
|
||||
var output = new float[input.Length];
|
||||
for (int pass = 0; pass < 2; pass++)
|
||||
{
|
||||
for (int i = 0; i < input.Length; i++) output[i] = filter.Process(input[i]);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
/// <summary>Rumore marrone in anello: integrazione con perdita del rumore bianco, due passate.</summary>
|
||||
public static float[] BrownLoop(int length, ulong seed, float leak)
|
||||
{
|
||||
var white = Noise(length, seed);
|
||||
var brown = new float[length];
|
||||
float acc = 0;
|
||||
for (int pass = 0; pass < 2; pass++)
|
||||
{
|
||||
for (int i = 0; i < length; i++)
|
||||
{
|
||||
acc = acc * leak + white[i] * (1 - leak) * 10;
|
||||
brown[i] = acc;
|
||||
}
|
||||
}
|
||||
return brown;
|
||||
}
|
||||
|
||||
/// <summary>Somma un suono breve nell'anello a partire da «at» campioni, con la coda che rientra dall'inizio.</summary>
|
||||
public static void MixWrapped(float[] loop, float[] sound, int at, float gain)
|
||||
{
|
||||
for (int i = 0; i < sound.Length; i++) loop[(at + i) % loop.Length] += sound[i] * gain;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ interfaccia
|
||||
|
||||
/// <summary>Clic dell'interfaccia: un colpetto secco e brillante.</summary>
|
||||
public static float[] Click()
|
||||
{
|
||||
var b = Buffer(0.035f);
|
||||
var noise = Noise(b.Length, 11);
|
||||
var hp = Biquad.HighPass(2500, 0.7f, Rate);
|
||||
for (int i = 0; i < b.Length; i++)
|
||||
{
|
||||
float t = i / (float)Rate;
|
||||
b[i] = MathF.Sin(Tau * 1800 * t) * MathF.Exp(-t / 0.006f) * 0.6f + hp.Process(noise[i]) * MathF.Exp(-t / 0.003f) * 0.5f;
|
||||
}
|
||||
Normalize(b, 0.5f);
|
||||
FadeOut(b, 0.005f);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Nota con armoniche (ampiezze in «harmonics», la prima è la fondamentale) e decadimento esponenziale.</summary>
|
||||
private static void Tone(float[] b, float start, float freq, float decay, float gain, float[] harmonics)
|
||||
{
|
||||
int s0 = (int)(start * Rate);
|
||||
for (int i = s0; i < b.Length; i++)
|
||||
{
|
||||
float t = (i - s0) / (float)Rate;
|
||||
float env = Env(t, 0.005f, decay);
|
||||
if (env < 1e-4f && t > 0.01f) break;
|
||||
float v = 0;
|
||||
for (int h = 0; h < harmonics.Length; h++)
|
||||
{
|
||||
float f = freq * (h + 1);
|
||||
if (harmonics[h] != 0 && f < Rate * 0.45f) v += harmonics[h] * MathF.Sin(Tau * f * t);
|
||||
}
|
||||
b[i] += v * env * gain;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Esito positivo di un comando: due note ascendenti (la, mi).</summary>
|
||||
public static float[] Confirm()
|
||||
{
|
||||
var b = Buffer(0.32f);
|
||||
float[] h = [1, 0.3f];
|
||||
Tone(b, 0, 880, 0.09f, 1, h);
|
||||
Tone(b, 0.07f, 1318.5f, 0.11f, 0.9f, h);
|
||||
Normalize(b, 0.42f);
|
||||
FadeOut(b);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Comando rifiutato: due note scure discendenti.</summary>
|
||||
public static float[] Error()
|
||||
{
|
||||
var b = Buffer(0.38f);
|
||||
float[] h = [1, 0, 0.33f, 0, 0.2f];
|
||||
Tone(b, 0, 330, 0.12f, 1, h);
|
||||
Tone(b, 0.1f, 247, 0.14f, 1, h);
|
||||
var lp = Biquad.LowPass(1800, 0.7f, Rate);
|
||||
for (int i = 0; i < b.Length; i++) b[i] = lp.Process(b[i]);
|
||||
Normalize(b, 0.45f);
|
||||
FadeOut(b);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Campana in modulazione di frequenza (portante f, modulante 1,4·f, indice che decade).</summary>
|
||||
private static void Bell(float[] b, float start, float freq, float gain, float decay = 0.6f)
|
||||
{
|
||||
int s0 = (int)(start * Rate);
|
||||
for (int i = s0; i < b.Length; i++)
|
||||
{
|
||||
float t = (i - s0) / (float)Rate;
|
||||
float index = 2.5f * MathF.Exp(-t / 0.3f);
|
||||
b[i] += MathF.Sin(Tau * freq * t + index * MathF.Sin(Tau * freq * 1.4f * t)) * Env(t, 0.003f, decay) * gain;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Notifica: 0 = informazione o opportunità, 1 = avviso, 2 = critica.</summary>
|
||||
public static float[] Notify(int level)
|
||||
{
|
||||
float[] b;
|
||||
switch (level)
|
||||
{
|
||||
case <= 0:
|
||||
b = Buffer(1.0f);
|
||||
Bell(b, 0, 1046.5f, 1);
|
||||
Bell(b, 0.12f, 1568f, 0.6f);
|
||||
break;
|
||||
case 1:
|
||||
b = Buffer(1.2f);
|
||||
Bell(b, 0, 784f, 1, 0.7f);
|
||||
Bell(b, 0.18f, 622.3f, 1, 0.7f);
|
||||
break;
|
||||
default:
|
||||
// tre impulsi dissonanti: si distinguono anche sopra la musica
|
||||
b = Buffer(1.0f);
|
||||
float[] h = [1, 0, 0.33f, 0, 0.2f];
|
||||
for (int k = 0; k < 3; k++)
|
||||
{
|
||||
Tone(b, k * 0.22f, 523.3f, 0.09f, 0.8f, h);
|
||||
Tone(b, k * 0.22f, 554.4f, 0.09f, 0.6f, h);
|
||||
}
|
||||
break;
|
||||
}
|
||||
Normalize(b, 0.55f);
|
||||
FadeOut(b);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Cantiere completato: due colpi metallici e un arpeggio maggiore.</summary>
|
||||
public static float[] BuildComplete()
|
||||
{
|
||||
var b = Buffer(1.5f);
|
||||
var noise = Noise(b.Length, 23);
|
||||
foreach (var (at, gain) in new[] { (0f, 1f), (0.16f, 0.7f) })
|
||||
{
|
||||
int s0 = (int)(at * Rate);
|
||||
var bp = Biquad.BandPass(2500, 4, Rate);
|
||||
for (int i = s0; i < b.Length; i++)
|
||||
{
|
||||
float t = (i - s0) / (float)Rate;
|
||||
float metal = MathF.Sin(Tau * 420 * t + 3 * MathF.Exp(-t / 0.08f) * MathF.Sin(Tau * 420 * 2.76f * t));
|
||||
b[i] += (bp.Process(noise[i]) * 2 * Env(t, 0.001f, 0.04f) + metal * Env(t, 0.002f, 0.25f)) * gain * 0.6f;
|
||||
}
|
||||
}
|
||||
float[] pluck = [1, 0.4f, 0.15f];
|
||||
float[] notes = [523.3f, 659.3f, 784f, 1046.5f];
|
||||
for (int k = 0; k < notes.Length; k++) Tone(b, 0.32f + k * 0.08f, notes[k], k == notes.Length - 1 ? 0.35f : 0.15f, 0.7f, pluck);
|
||||
Normalize(b, 0.55f);
|
||||
FadeOut(b, 0.05f);
|
||||
return b;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ treni
|
||||
|
||||
/// <summary>Fischio a vapore all'arrivo: accordo 4:5:6 con salita d'intonazione, vibrato e soffio.</summary>
|
||||
public static float[] SteamWhistle()
|
||||
{
|
||||
var b = Buffer(1.35f);
|
||||
var noise = Noise(b.Length, 31);
|
||||
var bp = Biquad.BandPass(1500, 1.2f, Rate);
|
||||
float[] freqs = [520, 650, 780];
|
||||
float[] phase = new float[freqs.Length];
|
||||
for (int i = 0; i < b.Length; i++)
|
||||
{
|
||||
float t = i / (float)Rate;
|
||||
float amp = t < 0.06f ? t / 0.06f : t < 1.05f ? 1 : MathF.Max(0, 1 - (t - 1.05f) / 0.3f);
|
||||
float bend = 0.94f + 0.06f * MathF.Min(1, t / 0.08f) - (t > 1.0f ? 0.03f * (t - 1.0f) : 0);
|
||||
float vib = 1 + 0.004f * MathF.Sin(Tau * 5.5f * t);
|
||||
float v = 0;
|
||||
for (int k = 0; k < freqs.Length; k++)
|
||||
{
|
||||
phase[k] += Tau * freqs[k] * bend * vib / Rate;
|
||||
v += MathF.Sin(phase[k]) / (k + 1.5f);
|
||||
}
|
||||
b[i] = (v + bp.Process(noise[i]) * 0.25f) * amp;
|
||||
}
|
||||
Normalize(b, 0.6f);
|
||||
FadeOut(b);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Tromba bitonale delle locomotive diesel ed elettriche.</summary>
|
||||
public static float[] Horn()
|
||||
{
|
||||
var b = Buffer(0.95f);
|
||||
float[] freqs = [311.1f, 370f];
|
||||
var lp = Biquad.LowPass(2500, 0.7f, Rate);
|
||||
for (int i = 0; i < b.Length; i++)
|
||||
{
|
||||
float t = i / (float)Rate;
|
||||
float amp = t < 0.03f ? t / 0.03f : t < 0.78f ? 1 : MathF.Max(0, 1 - (t - 0.78f) / 0.15f);
|
||||
float v = 0;
|
||||
foreach (float f in freqs)
|
||||
{
|
||||
for (int h = 1; h <= 6; h++) v += MathF.Sin(Tau * f * h * t) / h;
|
||||
}
|
||||
b[i] = lp.Process(v) * amp;
|
||||
}
|
||||
Normalize(b, 0.55f);
|
||||
FadeOut(b);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Sbuffo del vapore: rumore filtrato a banda con un tonfo grave.</summary>
|
||||
public static float[] Chuff()
|
||||
{
|
||||
var b = Buffer(0.17f);
|
||||
var noise = Noise(b.Length, 41);
|
||||
var bp = Biquad.BandPass(900, 0.8f, Rate);
|
||||
var lp = Biquad.LowPass(2500, 0.7f, Rate);
|
||||
for (int i = 0; i < b.Length; i++)
|
||||
{
|
||||
float t = i / (float)Rate;
|
||||
b[i] = lp.Process(bp.Process(noise[i])) * Env(t, 0.004f, 0.05f) + MathF.Sin(Tau * 70 * t) * Env(t, 0.002f, 0.04f) * 0.5f;
|
||||
}
|
||||
Normalize(b, 0.6f);
|
||||
FadeOut(b, 0.02f);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Rotolamento in anello (1,6 s a intonazione 1): rumore grave e il «tu-tum» dei carrelli sui giunti.</summary>
|
||||
public static float[] RailRumbleLoop()
|
||||
{
|
||||
int n = (int)(1.6f * Rate);
|
||||
var loop = LoopFilter(BrownLoop(n, 53, 0.995f), Biquad.LowPass(300, 0.7f, Rate));
|
||||
Normalize(loop, 0.5f);
|
||||
var clack = Buffer(0.08f);
|
||||
var cn = Noise(clack.Length, 59);
|
||||
var bp = Biquad.BandPass(1800, 2, Rate);
|
||||
for (int i = 0; i < clack.Length; i++)
|
||||
{
|
||||
float t = i / (float)Rate;
|
||||
clack[i] = bp.Process(cn[i]) * 1.5f * Env(t, 0.001f, 0.012f) + MathF.Sin(Tau * 90 * t) * Env(t, 0.002f, 0.03f) * 0.6f;
|
||||
}
|
||||
MixWrapped(loop, clack, (int)(0.20f * Rate), 0.8f);
|
||||
MixWrapped(loop, clack, (int)(0.32f * Rate), 0.7f);
|
||||
MixWrapped(loop, clack, (int)(1.00f * Rate), 0.75f);
|
||||
MixWrapped(loop, clack, (int)(1.12f * Rate), 0.65f);
|
||||
Normalize(loop, 0.6f);
|
||||
return loop;
|
||||
}
|
||||
|
||||
/// <summary>Motore diesel in anello (1 s): 48 Hz con armoniche e scoppi a 8 Hz.</summary>
|
||||
public static float[] DieselDroneLoop()
|
||||
{
|
||||
int n = Rate;
|
||||
var b = new float[n];
|
||||
var noise = LoopFilter(Noise(n, 61), Biquad.LowPass(900, 0.7f, Rate));
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
float t = i / (float)Rate;
|
||||
float v = 0;
|
||||
for (int h = 1; h <= 10; h++) v += MathF.Sin(Tau * 48 * h * t) / h;
|
||||
float firing = 0.7f + 0.3f * MathF.Sin(Tau * 8 * t);
|
||||
b[i] = v * firing * 0.5f + noise[i] * 0.4f;
|
||||
}
|
||||
Normalize(b, 0.6f);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Ronzio elettrico in anello (1 s): 100, 200 e 300 Hz e un fischio dei motori.</summary>
|
||||
public static float[] ElectricHumLoop()
|
||||
{
|
||||
int n = Rate;
|
||||
var b = new float[n];
|
||||
var hiss = LoopFilter(Noise(n, 67), Biquad.LowPass(3000, 0.7f, Rate));
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
float t = i / (float)Rate;
|
||||
b[i] = 0.4f * MathF.Sin(Tau * 100 * t) + 0.2f * MathF.Sin(Tau * 200 * t) + 0.25f * MathF.Sin(Tau * 300 * t)
|
||||
+ 0.06f * MathF.Sin(Tau * 1150 * t) * (0.6f + 0.4f * MathF.Sin(Tau * t)) + hiss[i] * 0.12f;
|
||||
}
|
||||
Normalize(b, 0.5f);
|
||||
return b;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ ambiente
|
||||
|
||||
/// <summary>Vento e campagna in anello (8 s): rumore con passa-basso mobile e raffiche.</summary>
|
||||
public static float[] WindLoop()
|
||||
{
|
||||
const float seconds = 8;
|
||||
int n = (int)(seconds * Rate);
|
||||
var white = Noise(n, 71);
|
||||
var b = new float[n];
|
||||
var f = Biquad.LowPass(400, 0.9f, Rate);
|
||||
for (int pass = 0; pass < 2; pass++)
|
||||
{
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
float t = i / (float)Rate;
|
||||
float g = 0.55f + 0.25f * MathF.Sin(Tau * t / seconds) + 0.2f * MathF.Sin(Tau * 3 * t / seconds + 1.3f);
|
||||
if ((i & 127) == 0) f.Retune(Biquad.LowPass(250 + 550 * g, 0.9f, Rate));
|
||||
b[i] = f.Process(white[i]) * g;
|
||||
}
|
||||
}
|
||||
Normalize(b, 0.5f);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Acqua di fiume in anello (6 s): rumore a banda con un gorgoglio lento e bolle.</summary>
|
||||
public static float[] RiverLoop()
|
||||
{
|
||||
const float seconds = 6;
|
||||
int n = (int)(seconds * Rate);
|
||||
var main = LoopFilter(Noise(n, 73), Biquad.BandPass(1200, 0.7f, Rate));
|
||||
var mod = LoopFilter(Noise(n, 79), Biquad.LowPass(6, 0.7f, Rate));
|
||||
Normalize(mod, 1);
|
||||
var b = new float[n];
|
||||
for (int i = 0; i < n; i++) b[i] = main[i] * (0.6f + 0.4f * mod[i]);
|
||||
Normalize(b, 1);
|
||||
var rng = new SynthRng(83);
|
||||
var bubble = Buffer(0.05f);
|
||||
for (int k = 0; k < 60; k++)
|
||||
{
|
||||
float f0 = rng.Range(400, 1000);
|
||||
for (int i = 0; i < bubble.Length; i++)
|
||||
{
|
||||
float t = i / (float)Rate;
|
||||
bubble[i] = MathF.Sin(Tau * f0 * (1 + 4 * t) * t) * Env(t, 0.002f, 0.012f);
|
||||
}
|
||||
MixWrapped(b, bubble, rng.Next(n), rng.Range(0.1f, 0.3f));
|
||||
}
|
||||
Normalize(b, 0.45f);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Mare in anello (10 s): due onde con risacca e schiuma.</summary>
|
||||
public static float[] SeaLoop()
|
||||
{
|
||||
const float seconds = 10;
|
||||
int n = (int)(seconds * Rate);
|
||||
var low = LoopFilter(Noise(n, 89), Biquad.LowPass(700, 0.7f, Rate));
|
||||
var foam = LoopFilter(Noise(n, 97), Biquad.HighPass(3000, 0.7f, Rate));
|
||||
var b = new float[n];
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
float t = i / (float)Rate;
|
||||
float s = 0.5f + 0.5f * MathF.Sin(Tau * 2 * t / seconds - MathF.PI / 2);
|
||||
float swell = 0.35f + 0.65f * s * s;
|
||||
b[i] = low[i] * swell + foam[i] * swell * swell * 0.3f;
|
||||
}
|
||||
Normalize(b, 0.5f);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Città in anello (8 s): brusio grave, voci lontane e qualche colpo di carri e porte.</summary>
|
||||
public static float[] CityLoop()
|
||||
{
|
||||
const float seconds = 8;
|
||||
int n = (int)(seconds * Rate);
|
||||
var rumble = LoopFilter(BrownLoop(n, 101, 0.996f), Biquad.LowPass(200, 0.7f, Rate));
|
||||
Normalize(rumble, 1);
|
||||
var murmur = LoopFilter(Noise(n, 103), Biquad.BandPass(500, 1, Rate));
|
||||
Normalize(murmur, 1);
|
||||
var mod = LoopFilter(Noise(n, 107), Biquad.LowPass(3, 0.7f, Rate));
|
||||
Normalize(mod, 1);
|
||||
var b = new float[n];
|
||||
for (int i = 0; i < n; i++) b[i] = rumble[i] * 0.5f + murmur[i] * (0.2f + 0.15f * mod[i]);
|
||||
var rng = new SynthRng(109);
|
||||
var knock = Buffer(0.06f);
|
||||
for (int k = 0; k < 24; k++)
|
||||
{
|
||||
var kn = Noise(knock.Length, 200 + (ulong)k);
|
||||
var bp = Biquad.BandPass(rng.Range(1500, 3000), 3, Rate);
|
||||
float decay = rng.Range(0.01f, 0.03f);
|
||||
for (int i = 0; i < knock.Length; i++) knock[i] = bp.Process(kn[i]) * 3 * Env(i / (float)Rate, 0.001f, decay);
|
||||
MixWrapped(b, knock, rng.Next(n), rng.Range(0.2f, 0.5f));
|
||||
}
|
||||
Normalize(b, 0.45f);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Cinguettio (varianti per numero): due–quattro brevi glissati acuti.</summary>
|
||||
public static float[] Bird(int variant)
|
||||
{
|
||||
var rng = new SynthRng(300 + (ulong)variant);
|
||||
int chirps = 2 + rng.Next(3);
|
||||
float chirp = rng.Range(0.05f, 0.08f);
|
||||
float gap = rng.Range(0.03f, 0.07f);
|
||||
var b = Buffer(chirps * (chirp + gap) + 0.02f);
|
||||
float f0 = rng.Range(2800, 3600), f1 = f0 * rng.Range(1.15f, 1.45f);
|
||||
if (rng.Next(2) == 0) (f0, f1) = (f1, f0);
|
||||
for (int k = 0; k < chirps; k++)
|
||||
{
|
||||
int s0 = (int)(k * (chirp + gap) * Rate);
|
||||
float phase = 0;
|
||||
for (int i = 0; i < (int)(chirp * Rate) && s0 + i < b.Length; i++)
|
||||
{
|
||||
float u = i / (chirp * Rate);
|
||||
phase += Tau * (f0 + (f1 - f0) * u) / Rate;
|
||||
b[s0 + i] += MathF.Sin(phase) * MathF.Sin(MathF.PI * u);
|
||||
}
|
||||
}
|
||||
Normalize(b, 0.5f);
|
||||
return b;
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ using static RailEnterprise.Client.App.Localization;
|
||||
namespace RailEnterprise.Client.Hud;
|
||||
|
||||
/// <summary>Strumenti e pannelli della barra sinistra (immagine 01).</summary>
|
||||
public enum Tool { None, Track, Station, Signal, Depot, Trains, Lines, Maintenance, Employment, Industries, Market, Companies, Finance, Demolish }
|
||||
public enum Tool { None, Track, Station, Signal, Depot, Trains, Lines, Maintenance, Employment, Industries, Market, Companies, Climb, Finance, Demolish }
|
||||
|
||||
/// <summary>
|
||||
/// Barra degli strumenti a sinistra: icone disegnate in codice con l'etichetta sotto. I pulsanti
|
||||
@@ -37,7 +37,7 @@ public partial class Toolbar : PanelContainer
|
||||
{
|
||||
(Tool.Track, "Binari"), (Tool.Station, "Stazione"), (Tool.Signal, "Segnali"), (Tool.Depot, "Deposito"),
|
||||
(Tool.Trains, "Treni"), (Tool.Lines, "Linee"), (Tool.Maintenance, "Officine"), (Tool.Employment, "Impieghi"),
|
||||
(Tool.Industries, "Industrie"), (Tool.Market, "Mercato"), (Tool.Companies, "Compagnie"), (Tool.Finance, "Finanze"),
|
||||
(Tool.Industries, "Industrie"), (Tool.Market, "Mercato"), (Tool.Companies, "Compagnie"), (Tool.Climb, "Scalata"), (Tool.Finance, "Finanze"),
|
||||
(Tool.Demolish, "Demolisci"),
|
||||
})
|
||||
{
|
||||
@@ -48,6 +48,9 @@ public partial class Toolbar : PanelContainer
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Pulsante di uno strumento (per l'evidenziazione del tutorial).</summary>
|
||||
public Control? ButtonFor(Tool tool) => _buttons.GetValueOrDefault(tool);
|
||||
|
||||
public void Select(Tool tool)
|
||||
{
|
||||
Current = tool;
|
||||
@@ -159,6 +162,13 @@ public partial class Toolbar : PanelContainer
|
||||
DrawPolyline([c + new Vector2(-11, 8), c + new Vector2(-4, 0), c + new Vector2(2, 5), c + new Vector2(11, -7)], col, w);
|
||||
DrawLine(c + new Vector2(-11, 11), c + new Vector2(11, 11), col, w);
|
||||
break;
|
||||
case Tool.Climb:
|
||||
// gradini che salgono verso una bandierina
|
||||
DrawPolyline([c + new Vector2(-11, 11), c + new Vector2(-11, 5), c + new Vector2(-4, 5), c + new Vector2(-4, -1),
|
||||
c + new Vector2(3, -1), c + new Vector2(3, -7), c + new Vector2(10, -7), c + new Vector2(10, 11), c + new Vector2(-11, 11)], col, w);
|
||||
DrawLine(c + new Vector2(10, -7), c + new Vector2(10, -13), col, w);
|
||||
DrawColoredPolygon([c + new Vector2(10, -13), c + new Vector2(4, -11), c + new Vector2(10, -9)], col);
|
||||
break;
|
||||
case Tool.Finance:
|
||||
DrawArc(c + new Vector2(0, -7), 9, 0, MathF.Tau, 24, col, w);
|
||||
DrawLine(c + new Vector2(-9, -7), c + new Vector2(-9, 7), col, w);
|
||||
|
||||
@@ -1,16 +1,26 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
using RailEnterprise.Client.Net;
|
||||
using RailEnterprise.Client.Panels;
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
|
||||
namespace RailEnterprise.Client.Hud;
|
||||
|
||||
/// <summary>Barra superiore (immagine 01): compagnia e livello, data, velocità, cassa, patrimonio, rating, stato del server.</summary>
|
||||
/// <summary>Barra superiore (immagine 01): compagnia e livello, data, velocità, cassa, patrimonio, rating, stato del server, audio.</summary>
|
||||
public partial class TopBar : PanelContainer
|
||||
{
|
||||
private GameSession? _session;
|
||||
private readonly Label _company = UiTheme.TitleLabel("", 30);
|
||||
private readonly PanelContainer _tier = UiTheme.Badge("");
|
||||
private readonly Label _climb = UiTheme.Text("", 12, Palette.TextSecondary);
|
||||
private long _climbRequestedMonth = long.MinValue;
|
||||
private double _sinceClimbRequest = double.MaxValue;
|
||||
|
||||
/// <summary>Clic sul livello: apre «La tua scalata».</summary>
|
||||
public event Action? ClimbRequested;
|
||||
private readonly Label _date = UiTheme.Text("", 17, bold: true);
|
||||
private readonly Label _cash = UiTheme.Text("", 20, Palette.AmberLight, bold: true);
|
||||
private readonly Label _worth = UiTheme.Text("", 20, bold: true);
|
||||
@@ -18,6 +28,14 @@ public partial class TopBar : PanelContainer
|
||||
private readonly Label _server = UiTheme.Text("", 14);
|
||||
private readonly ColorRect _serverDot = new() { CustomMinimumSize = new Vector2(10, 10) };
|
||||
private readonly List<Button> _speeds = [];
|
||||
private VBoxContainer? _tierBox;
|
||||
private HBoxContainer? _speedBox;
|
||||
|
||||
/// <summary>Pulsanti della velocità (per l'evidenziazione del tutorial).</summary>
|
||||
public Control? SpeedBox => _speedBox;
|
||||
|
||||
/// <summary>Livello e avanzamento (per l'evidenziazione del tutorial).</summary>
|
||||
public Control? TierBox => _tierBox;
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
@@ -28,8 +46,20 @@ public partial class TopBar : PanelContainer
|
||||
AddChild(row);
|
||||
row.AddChild(new Logo { CustomMinimumSize = new Vector2(40, 40) });
|
||||
row.AddChild(_company);
|
||||
var tierBox = new CenterContainer();
|
||||
tierBox.AddChild(_tier);
|
||||
// livello attuale e avanzamento verso il prossimo (dal quadro della scalata): un clic apre il pannello
|
||||
var tierBox = new VBoxContainer { Alignment = BoxContainer.AlignmentMode.Center, MouseFilter = MouseFilterEnum.Stop };
|
||||
tierBox.AddThemeConstantOverride("separation", 2);
|
||||
tierBox.MouseDefaultCursorShape = CursorShape.PointingHand;
|
||||
var badgeRow = new HBoxContainer();
|
||||
badgeRow.AddChild(_tier);
|
||||
tierBox.AddChild(badgeRow);
|
||||
tierBox.AddChild(_climb);
|
||||
tierBox.GuiInput += e =>
|
||||
{
|
||||
if (e is InputEventMouseButton { Pressed: true, ButtonIndex: MouseButton.Left }) ClimbRequested?.Invoke();
|
||||
};
|
||||
_tier.MouseFilter = MouseFilterEnum.Pass;
|
||||
_climb.MouseFilter = MouseFilterEnum.Pass;
|
||||
row.AddChild(tierBox);
|
||||
row.AddChild(new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill });
|
||||
row.AddChild(_date);
|
||||
@@ -44,10 +74,17 @@ public partial class TopBar : PanelContainer
|
||||
speeds.AddChild(b);
|
||||
}
|
||||
row.AddChild(speeds);
|
||||
_speedBox = speeds;
|
||||
row.AddChild(new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill });
|
||||
row.AddChild(Stat(T("Cassa"), _cash));
|
||||
row.AddChild(Stat(T("Patrimonio netto"), _worth));
|
||||
row.AddChild(Stat(T("Rating"), _rating));
|
||||
// tooltip «perché» (ADR 0024): cassa con i movimenti del mese, rating, avanzamento del livello
|
||||
// la cassa della barra è quella dell'ultimo aggiornamento delle entità (inizio giornata o dopo un comando),
|
||||
// la spiegazione è di adesso: se differiscono il tooltip lo dice
|
||||
WhyTooltip.Attach(_cash, () => new ExplainTarget(ExplainSubject.Cash), shown: () => ShownCash()?.Cents);
|
||||
WhyTooltip.Attach(_rating, () => new ExplainTarget(ExplainSubject.Rating));
|
||||
WhyTooltip.Attach(tierBox, () => new ExplainTarget(ExplainSubject.TierProgress), T("Clic per aprire «La tua scalata»"));
|
||||
var chip = new PanelContainer();
|
||||
chip.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, Palette.Border, 16, 12));
|
||||
var chipRow = new HBoxContainer();
|
||||
@@ -60,6 +97,9 @@ public partial class TopBar : PanelContainer
|
||||
var chipCenter = new CenterContainer();
|
||||
chipCenter.AddChild(chip);
|
||||
row.AddChild(chipCenter);
|
||||
var audio = new CenterContainer();
|
||||
audio.AddChild(new Audio.SpeakerButton());
|
||||
row.AddChild(audio);
|
||||
}
|
||||
|
||||
private static VBoxContainer Stat(string caption, Label value)
|
||||
@@ -76,6 +116,17 @@ public partial class TopBar : PanelContainer
|
||||
|
||||
public void Bind(GameSession session) => _session = session;
|
||||
|
||||
/// <summary>
|
||||
/// Cassa mostrata: quella della compagnia nelle entità, aggiornata a inizio giornata e dopo ogni comando
|
||||
/// (un prestito, un acquisto), altrimenti quella del resoconto del giorno.
|
||||
/// </summary>
|
||||
private Money? ShownCash()
|
||||
{
|
||||
var w = _session?.World;
|
||||
if (w?.Summary is null) return null;
|
||||
return w.Companies.GetValueOrDefault(w.Summary.CompanyId)?.Cash ?? w.LastDigest?.Cash;
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
var w = _session?.World;
|
||||
@@ -83,9 +134,24 @@ public partial class TopBar : PanelContainer
|
||||
var me = w.Companies.GetValueOrDefault(w.Summary.CompanyId);
|
||||
_company.Text = me?.Name ?? w.Summary.CompanyName;
|
||||
int tier = Math.Clamp(me?.Tier ?? 1, 1, w.Data.Tiers.Tiers.Count);
|
||||
((Label)_tier.GetChild(0)).Text = TranslationServer.GetLocale().StartsWith("en") ? w.Data.Tiers.Tiers[tier - 1].NameEn : w.Data.Tiers.Tiers[tier - 1].NameIt;
|
||||
((Label)_tier.GetChild(0)).Text = $"{tier} · {Fmt.Tier(w, tier)}";
|
||||
// il quadro della scalata si chiede una volta al mese di gioco (il pannello lo chiede ogni giorno), e
|
||||
// di nuovo dopo 5 s se manca: uno stato completo (ripresa della sessione, nuova partita) lo azzera
|
||||
_sinceClimbRequest += delta;
|
||||
long month = w.Calendar is { } cal ? Fmt.Today(w) / cal.DaysPerMonth : 0;
|
||||
if ((month != _climbRequestedMonth || (w.Climb is null && _sinceClimbRequest > 5)) && _session!.IsOpen)
|
||||
{
|
||||
_climbRequestedMonth = month;
|
||||
_sinceClimbRequest = 0;
|
||||
_session.Send(new RequestDetail { Kind = DetailKind.Climb, Target = 0 });
|
||||
}
|
||||
var climb = w.Climb;
|
||||
bool top = tier >= w.Data.Tiers.Tiers.Count;
|
||||
_climb.Text = top ? T("livello più alto")
|
||||
: climb is not null && climb.Tier == tier ? $"{Fmt.Progress(climb.Progress)} {T("verso")} {Fmt.Tier(w, tier + 1)}"
|
||||
: $"{T("prossimo")}: {Fmt.Tier(w, tier + 1)}";
|
||||
_date.Text = w.LastDigest?.Date ?? w.Summary.Date;
|
||||
_cash.Text = (w.LastDigest?.Cash ?? me?.Cash ?? default).ToString();
|
||||
_cash.Text = (ShownCash() ?? default).ToString();
|
||||
_worth.Text = (w.LastDigest?.NetWorth ?? me?.NetWorth ?? default).ToString("short");
|
||||
_rating.Text = w.LastDigest?.Rating ?? me?.Rating ?? "—";
|
||||
byte speed = _session!.RequestedSpeed ?? w.LastDigest?.Speed ?? w.Speed;
|
||||
|
||||
@@ -1,23 +1,32 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
using RailEnterprise.Client.Audio;
|
||||
using RailEnterprise.Client.Net;
|
||||
using RailEnterprise.Client.Screens;
|
||||
using RailEnterprise.Client.Tutorial;
|
||||
using RailEnterprise.Core.Data;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
|
||||
namespace RailEnterprise.Client;
|
||||
|
||||
/// <summary>
|
||||
/// Nodo radice: tema e traduzioni, dati del gioco, passaggio tra menu, collegamento e partita;
|
||||
/// Nodo radice: tema e traduzioni, dati del gioco, passaggio tra schermata di connessione e partita;
|
||||
/// alla chiusura termina la sessione e l'eventuale server locale.
|
||||
/// </summary>
|
||||
public partial class Main : Node
|
||||
{
|
||||
private const string SettingsPath = "user://settings.cfg";
|
||||
// cartelle del server locale: la partita del giocatore (la apre la schermata di connessione), la
|
||||
// partita di prova del tutorial e quella del collaudo (queste due ripartono sempre da una partita nuova)
|
||||
private const string LocalDataDir = "user://server";
|
||||
private const string TutorialDataDir = "user://tutorial-server";
|
||||
private const string AutopilotDataDir = "user://autopilot-server";
|
||||
private GameData? _data;
|
||||
private Node? _screen;
|
||||
private GameSession? _session;
|
||||
private string? _autopilot;
|
||||
// tutorial della partita che si apre: casella «Mostra il tutorial» e pulsante «Tutorial» (dal primo passo)
|
||||
private bool _tutorialRequested, _tutorialRestart;
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
@@ -27,21 +36,27 @@ public partial class Main : Node
|
||||
Localization.Load(locale);
|
||||
GetWindow().Theme = UiTheme.Build();
|
||||
GetWindow().Title = "Rail Enterprise";
|
||||
var args = OS.GetCmdlineUserArgs();
|
||||
int i = Array.IndexOf(args, "--autopilot");
|
||||
// audio: niente nel pilota automatico e senza schermo (non rallenta il collaudo)
|
||||
var audio = new AudioManager(enabled: i < 0 && DisplayServer.GetName() != "headless");
|
||||
AddChild(audio);
|
||||
try
|
||||
{
|
||||
_data = GodotDataSource.LoadGameData();
|
||||
audio.SetEras(_data.Eras.Eras);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
GD.PrintErr($"Dati del gioco non validi: {e.Message}");
|
||||
}
|
||||
ShowMenu(_data is null ? T("Dati del gioco non trovati o non validi.") : "");
|
||||
var args = OS.GetCmdlineUserArgs();
|
||||
int i = Array.IndexOf(args, "--autopilot");
|
||||
if (i >= 0 && _data is not null)
|
||||
_autopilot = i + 1 < args.Length ? args[i + 1] : ProjectSettings.GlobalizePath("user://autopilot");
|
||||
// nel collaudo la schermata di connessione non avvia un suo server: lo avvia StartLocal qui sotto
|
||||
ShowMenu(_data is null ? T("Dati del gioco non trovati o non validi.") : "", autoStart: _autopilot is null);
|
||||
if (_autopilot is not null)
|
||||
{
|
||||
// collaudo: mappa piccola e seme fisso per il server locale
|
||||
_autopilot = i + 1 < args.Length ? args[i + 1] : ProjectSettings.GlobalizePath("user://autopilot");
|
||||
System.Environment.SetEnvironmentVariable("RE_MAP_SIZE", "64");
|
||||
System.Environment.SetEnvironmentVariable("RE_SEED", "3");
|
||||
System.Environment.SetEnvironmentVariable("RE_AUTOSAVE_MIN", "0");
|
||||
@@ -56,95 +71,133 @@ public partial class Main : Node
|
||||
AddChild(screen);
|
||||
}
|
||||
|
||||
private void ShowMenu(string status = "")
|
||||
/// <summary>Schermata iniziale e di connessione (immagine 09): server locale o in rete, stato, salvataggi.</summary>
|
||||
/// <param name="autoStart">Avvia subito la strada scelta l'ultima volta (server locale o in rete).</param>
|
||||
/// <param name="handover">Sessione di prova della schermata precedente, ripresa così com'è (cambio di lingua).</param>
|
||||
private void ShowMenu(string status = "", bool autoStart = true, GameSession? handover = null)
|
||||
{
|
||||
var menu = new MenuScreen();
|
||||
menu.LocalGame += StartLocal;
|
||||
menu.ConnectToServer += ShowConnect;
|
||||
menu.LanguageChanged += code =>
|
||||
if (_data is null)
|
||||
{
|
||||
// senza dati non si può aprire nessuna sessione: resta solo il messaggio
|
||||
var label = UiTheme.Text(status, 16, Palette.Danger);
|
||||
label.SetAnchorsAndOffsetsPreset(Control.LayoutPreset.Center);
|
||||
Swap(label);
|
||||
return;
|
||||
}
|
||||
// chi aggiorna con una partita locale già salvata non è alla prima partita: casella spenta
|
||||
if (!TutorialSettings.Played && HasLocalSaves()) TutorialSettings.Played = true;
|
||||
var screen = new ConnectScreen(_data, autoStart: autoStart, handover: handover);
|
||||
screen.PlayRequested += session =>
|
||||
{
|
||||
SetTutorial(screen.ShowTutorial, restart: false);
|
||||
ShowGame(session, screen.GameScope);
|
||||
};
|
||||
screen.TutorialRequested += async () =>
|
||||
{
|
||||
// la partita di prova ha un suo server: quello della sessione di prova della schermata si chiude
|
||||
var trial = screen.TakeSession();
|
||||
if (trial is not null) await trial.DisposeAsync();
|
||||
SetTutorial(true, restart: true);
|
||||
StartLocal(tutorial: true);
|
||||
};
|
||||
screen.AudioRequested += () => AudioManager.Instance?.ShowSettings();
|
||||
screen.LanguageChanged += code =>
|
||||
{
|
||||
var cfg = new ConfigFile();
|
||||
cfg.Load(SettingsPath);
|
||||
cfg.SetValue("ui", "locale", code);
|
||||
cfg.Save(SettingsPath);
|
||||
TranslationServer.SetLocale(code);
|
||||
ShowMenu();
|
||||
};
|
||||
Swap(menu);
|
||||
if (status.Length > 0) menu.SetStatus(status);
|
||||
}
|
||||
|
||||
private void ShowConnect()
|
||||
{
|
||||
var screen = new ConnectScreen();
|
||||
screen.Back += () => ShowMenu();
|
||||
screen.ConnectRequested += async (uri, token, label) =>
|
||||
{
|
||||
if (_data is null) return;
|
||||
screen.SetStatus(T("Collegamento in corso…"), busy: true);
|
||||
try
|
||||
{
|
||||
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
|
||||
var session = await GameSession.ConnectAsync(_data, uri, token, label, cts.Token);
|
||||
ShowGame(session);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
screen.SetStatus($"{T("Collegamento non riuscito")}: {e.Message}", busy: false);
|
||||
}
|
||||
// la schermata si ricrea con i testi nuovi: la sessione di prova (e il server locale) passa a lei
|
||||
ShowMenu(handover: screen.TakeSession());
|
||||
};
|
||||
Swap(screen);
|
||||
if (status.Length > 0) screen.SetStatus(status, error: true);
|
||||
}
|
||||
|
||||
private async void StartLocal()
|
||||
private void SetTutorial(bool requested, bool restart)
|
||||
{
|
||||
_tutorialRequested = requested;
|
||||
_tutorialRestart = restart;
|
||||
}
|
||||
|
||||
/// <summary>Vero se la partita locale del giocatore ha già dei salvataggi (file <c>.vfsave</c> del server).</summary>
|
||||
private static bool HasLocalSaves()
|
||||
{
|
||||
try
|
||||
{
|
||||
string saves = System.IO.Path.Combine(ProjectSettings.GlobalizePath(LocalDataDir), "saves");
|
||||
return Directory.Exists(saves) && Directory.EnumerateFiles(saves, "*.vfsave").Any();
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Server locale da zero e subito in partita, senza la schermata di connessione: il collaudo e la partita
|
||||
/// di prova del tutorial, ciascuno nella sua cartella; la partita del giocatore non si tocca.
|
||||
/// </summary>
|
||||
/// <param name="tutorial">pulsante «Tutorial»: partita di prova nuova, con il tutorial dal primo passo</param>
|
||||
private async void StartLocal(bool tutorial = false)
|
||||
{
|
||||
if (_data is null) return;
|
||||
string? server = LocalServerLauncher.FindServer();
|
||||
if (server is null)
|
||||
{
|
||||
ShowMenu(T("Server locale non trovato: compila src/RailEnterprise.Server o imposta RE_SERVER_PATH."));
|
||||
ShowMenu(T("Server locale non trovato: compila src/RailEnterprise.Server o imposta RE_SERVER_PATH."), autoStart: false);
|
||||
return;
|
||||
}
|
||||
if (_screen is MenuScreen menu) menu.SetStatus(T("Avvio del server locale…"));
|
||||
if (tutorial && _screen is ConnectScreen connect) connect.SetStatus(T("Avvio della partita di prova del tutorial…"));
|
||||
var launcher = new LocalServerLauncher();
|
||||
try
|
||||
{
|
||||
string dataDir = ProjectSettings.GlobalizePath(_autopilot is null ? "user://server" : "user://autopilot-server");
|
||||
// il collaudo parte sempre da una partita nuova
|
||||
if (_autopilot is not null && Directory.Exists(dataDir)) Directory.Delete(dataDir, true);
|
||||
string dataDir = ProjectSettings.GlobalizePath(tutorial ? TutorialDataDir : AutopilotDataDir);
|
||||
if (Directory.Exists(dataDir)) Directory.Delete(dataDir, true);
|
||||
int port = await launcher.StartAsync(server, dataDir, TimeSpan.FromSeconds(60));
|
||||
var session = await GameSession.ConnectAsync(_data, new Uri($"ws://127.0.0.1:{port}/ws"), launcher.Token, T("Partita locale"));
|
||||
session.LocalServer = launcher;
|
||||
ShowGame(session);
|
||||
ShowGame(session, tutorial ? "tutorial" : "autopilot");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
launcher.Dispose();
|
||||
ShowMenu($"{T("Partita locale non avviata")}: {e.Message}");
|
||||
ShowMenu($"{T("Partita locale non avviata")}: {e.Message}", autoStart: false);
|
||||
}
|
||||
}
|
||||
|
||||
private void ShowGame(GameSession session)
|
||||
/// <param name="scope">origine della partita (locale, tutorial, server in rete) per la voce del tutorial</param>
|
||||
private void ShowGame(GameSession session, string scope)
|
||||
{
|
||||
_session = session;
|
||||
var game = new GameScreen(session);
|
||||
game.Exit += async () =>
|
||||
{
|
||||
// prima si chiude la partita (e il server locale), poi la schermata di connessione ne
|
||||
// avvia uno nuovo: due server sulla stessa cartella dei salvataggi non convivono
|
||||
var s = _session;
|
||||
_session = null;
|
||||
ShowMenu();
|
||||
if (s is not null) await s.DisposeAsync();
|
||||
ShowMenu();
|
||||
};
|
||||
Swap(game);
|
||||
// il pilota automatico non mostra il tutorial: le sue schermate di partita restano quelle di sempre
|
||||
if (_autopilot is not null) game.AddChild(new AutoPilot(game, _autopilot));
|
||||
else
|
||||
{
|
||||
game.AddChild(new TutorialController(game, scope, _tutorialRequested, _tutorialRestart));
|
||||
TutorialSettings.Played = true;
|
||||
_tutorialRestart = false;
|
||||
}
|
||||
}
|
||||
|
||||
public override void _Notification(int what)
|
||||
{
|
||||
if (what == NotificationWMCloseRequest && _session is not null)
|
||||
{
|
||||
_session.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(3));
|
||||
_session = null;
|
||||
}
|
||||
if (what != NotificationWMCloseRequest) return;
|
||||
// anche la sessione di prova della schermata di connessione chiude il suo server locale
|
||||
var session = _session ?? (_screen as ConnectScreen)?.TakeSession();
|
||||
_session = null;
|
||||
session?.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(3));
|
||||
}
|
||||
}
|
||||
@@ -134,9 +134,13 @@ public sealed class GameSession : IAsyncDisposable
|
||||
/// <summary>Ultima velocità chiesta da questo client (mostrata finché il resoconto non la conferma).</summary>
|
||||
public byte? RequestedSpeed { get; private set; }
|
||||
|
||||
/// <summary>Velocità chieste finora da questo client (il tutorial non conta i cambi fatti da altri giocatori).</summary>
|
||||
public int SpeedRequests { get; private set; }
|
||||
|
||||
public void SetSpeed(byte speed)
|
||||
{
|
||||
RequestedSpeed = speed;
|
||||
SpeedRequests++;
|
||||
Send(new SetSpeed { Speed = speed });
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,470 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
using RailEnterprise.Client.Net;
|
||||
using RailEnterprise.Core.Commands;
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Protocol.Client;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
using ExplainSubject = RailEnterprise.Core.Economy.ExplainSubject;
|
||||
using ExplainTarget = RailEnterprise.Core.Economy.ExplainTarget;
|
||||
|
||||
namespace RailEnterprise.Client.Panels;
|
||||
|
||||
/// <summary>
|
||||
/// «La tua scalata» a tutto schermo (immagine di riferimento 08): in alto il binario dei livelli con
|
||||
/// il treno che avanza verso il prossimo, sotto ogni stazione il nome, quando è stato raggiunto (o
|
||||
/// l'avanzamento, o il patrimonio richiesto) e gli sblocchi; a sinistra lo storico del patrimonio
|
||||
/// netto con i livelli raggiunti e i requisiti del prossimo livello; a destra lo stato patrimoniale,
|
||||
/// il conto economico e i prestiti. Tutti i numeri arrivano dal server (ClimbReport, ADR 0018): il
|
||||
/// pannello li chiede all'apertura, a ogni nuovo giorno e dopo un prestito, e li mostra com'è.
|
||||
/// </summary>
|
||||
public partial class ClimbPanel : VBoxContainer
|
||||
{
|
||||
private readonly GameSession _session;
|
||||
private readonly Label _subtitle = UiTheme.Text("", 14, Palette.TextSecondary);
|
||||
private readonly Label _worth = UiTheme.Text("", 30, Palette.AmberLight, bold: true);
|
||||
private readonly TierTrack _track = new();
|
||||
private readonly HBoxContainer _stations = PanelKit.Row(8);
|
||||
private readonly Label _historyCaption = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
private readonly SeriesChart _chart = new(250);
|
||||
private readonly Label _nextTitle = UiTheme.Text("", 16, bold: true);
|
||||
private readonly HBoxContainer _requirements = PanelKit.Row(24);
|
||||
private readonly VBoxContainer _balance = PanelKit.Column(6);
|
||||
private readonly Label _incomeTitle = UiTheme.Text("", 20, bold: true);
|
||||
private readonly VBoxContainer _income = PanelKit.Column(6);
|
||||
private readonly SpinBox _amount = new() { MinValue = 1_000, MaxValue = 100_000_000, Step = 1_000, Value = 50_000, Prefix = "₤", CustomMinimumSize = new Vector2(150, 0) };
|
||||
private readonly Button _borrow = new() { Text = "", CustomMinimumSize = new Vector2(0, 48), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
private readonly Button _repay = new() { Text = "", CustomMinimumSize = new Vector2(0, 48), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
private readonly Label _status = UiTheme.Text("", 12, Palette.TextSecondary);
|
||||
private ClimbReport? _shown;
|
||||
private long _requestedDay = long.MinValue;
|
||||
private double _sinceRequest = double.MaxValue;
|
||||
|
||||
public event Action? CloseRequested;
|
||||
|
||||
public ClimbPanel(GameSession session)
|
||||
{
|
||||
_session = session;
|
||||
AddThemeConstantOverride("separation", 16);
|
||||
SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||
|
||||
var header = PanelKit.Row(24);
|
||||
var titles = PanelKit.Column(0);
|
||||
titles.AddChild(UiTheme.TitleLabel(T("La tua scalata"), 44));
|
||||
titles.AddChild(_subtitle);
|
||||
header.AddChild(titles);
|
||||
var worth = PanelKit.Column(0);
|
||||
worth.SizeFlagsHorizontal = SizeFlags.ShrinkEnd;
|
||||
worth.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||||
var worthCaption = UiTheme.Text(T("Patrimonio netto"), 13, Palette.TextSecondary);
|
||||
worthCaption.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
_worth.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
worth.AddChild(worthCaption);
|
||||
worth.AddChild(_worth);
|
||||
header.AddChild(worth);
|
||||
var close = new Button { Text = T("Torna alla mappa"), SizeFlagsVertical = SizeFlags.ShrinkCenter, CustomMinimumSize = new Vector2(170, 48) };
|
||||
close.Pressed += () => CloseRequested?.Invoke();
|
||||
header.AddChild(close);
|
||||
AddChild(header);
|
||||
|
||||
// binario dei livelli
|
||||
var trackCard = Card();
|
||||
var trackCol = (VBoxContainer)trackCard.GetChild(0);
|
||||
trackCol.AddChild(_track);
|
||||
// tooltip «perché» dell'avanzamento verso il prossimo livello (ADR 0024)
|
||||
WhyTooltip.Attach(_track, () => new ExplainTarget(ExplainSubject.TierProgress));
|
||||
WhyTooltip.Attach(_nextTitle, () => new ExplainTarget(ExplainSubject.TierProgress));
|
||||
trackCol.AddChild(_stations);
|
||||
AddChild(trackCard);
|
||||
|
||||
var body = PanelKit.Row(20);
|
||||
body.SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||
AddChild(body);
|
||||
|
||||
var left = Column(body, 1.15f);
|
||||
var historyHeader = PanelKit.Row(8);
|
||||
var historyTitle = UiTheme.Text(T("Patrimonio netto"), 20, bold: true);
|
||||
historyTitle.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
historyHeader.AddChild(historyTitle);
|
||||
_historyCaption.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||||
historyHeader.AddChild(_historyCaption);
|
||||
left.AddChild(historyHeader);
|
||||
left.AddChild(_chart);
|
||||
left.AddChild(_nextTitle);
|
||||
left.AddChild(_requirements);
|
||||
|
||||
var right = Column(body, 0.85f);
|
||||
right.AddChild(UiTheme.Text(T("Stato patrimoniale"), 20, bold: true));
|
||||
right.AddChild(_balance);
|
||||
right.AddChild(new Control { CustomMinimumSize = new Vector2(0, 6) });
|
||||
right.AddChild(_incomeTitle);
|
||||
right.AddChild(_income);
|
||||
right.AddChild(new Control { SizeFlagsVertical = SizeFlags.ExpandFill });
|
||||
var loanRow = PanelKit.Row(10);
|
||||
loanRow.AddChild(_amount);
|
||||
loanRow.AddChild(_borrow);
|
||||
loanRow.AddChild(_repay);
|
||||
right.AddChild(loanRow);
|
||||
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
right.AddChild(_status);
|
||||
_borrow.Text = T("Chiedi un prestito");
|
||||
_borrow.Pressed += Borrow;
|
||||
_repay.Pressed += Repay;
|
||||
_amount.ValueChanged += _ => UpdateLoanButtons();
|
||||
|
||||
_subtitle.Text = T("In attesa del quadro dal server…");
|
||||
}
|
||||
|
||||
private static PanelContainer Card()
|
||||
{
|
||||
var card = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
card.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 12, 24));
|
||||
card.AddChild(PanelKit.Column(10));
|
||||
return card;
|
||||
}
|
||||
|
||||
private static VBoxContainer Column(HBoxContainer body, float ratio)
|
||||
{
|
||||
var frame = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ExpandFill, SizeFlagsStretchRatio = ratio };
|
||||
frame.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 12, 24));
|
||||
var scroll = new ScrollContainer { HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled, SizeFlagsVertical = SizeFlags.ExpandFill };
|
||||
frame.AddChild(scroll);
|
||||
var margin = new MarginContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ExpandFill };
|
||||
margin.AddThemeConstantOverride("margin_right", 10);
|
||||
scroll.AddChild(margin);
|
||||
var col = PanelKit.Column(12);
|
||||
col.SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||
margin.AddChild(col);
|
||||
body.AddChild(frame);
|
||||
return col;
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
var w = _session.World;
|
||||
_sinceRequest += delta;
|
||||
// il quadro si chiede all'apertura e a ogni nuovo giorno (di nuovo dopo 5 s se non arriva)
|
||||
long today = Fmt.Today(w);
|
||||
if (today != _requestedDay || (w.Climb is null && _sinceRequest > 5)) Request(today);
|
||||
if (w.Climb is { } report && !ReferenceEquals(report, _shown)) Refresh(w, report);
|
||||
}
|
||||
|
||||
private void Request(long day)
|
||||
{
|
||||
_requestedDay = day;
|
||||
_sinceRequest = 0;
|
||||
_session.Send(new RequestDetail { Kind = DetailKind.Climb, Target = 0 });
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ dati di comodo (solo lettura)
|
||||
|
||||
private static int YearOf(ClientWorld w, long day) =>
|
||||
w.Calendar is { } c ? c.DateOfDay(Math.Max(0, day)).Year : 0;
|
||||
|
||||
private static string TierName(TierInfo t) =>
|
||||
TranslationServer.GetLocale().StartsWith("en") ? t.NameEn : t.NameIt;
|
||||
|
||||
private static string Short(Money m) => m.ToString("short");
|
||||
|
||||
/// <summary>Sblocco nella lingua dell'interfaccia (i valori arrivano dal server).</summary>
|
||||
public static string UnlockText(UnlockInfo u) => u.Kind switch
|
||||
{
|
||||
UnlockInfo.LoanLimit => $"{T("Fido fino a")} {Short(new Money(u.Value))}",
|
||||
UnlockInfo.Crews => $"{u.Value} {T("squadre di cantiere")}",
|
||||
UnlockInfo.Trading => T("Compravendita in proprio"),
|
||||
UnlockInfo.BuyIndustry => T("Acquisto di industrie"),
|
||||
UnlockInfo.Ipo => T("Quotazione in borsa"),
|
||||
UnlockInfo.HostileTakeover => T("Scalate ai concorrenti"),
|
||||
UnlockInfo.Concessions => T("Concessioni"),
|
||||
_ => "",
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ aggiornamento
|
||||
|
||||
private void Refresh(ClientWorld w, ClimbReport report)
|
||||
{
|
||||
_shown = report;
|
||||
string company = Fmt.Company(w, report.Company);
|
||||
_subtitle.Text = $"{company}, {T("fondata nel")} {YearOf(w, report.FoundedDay)} {T("con")} {report.InitialCapital}";
|
||||
_worth.Text = report.BalanceNetWorth.ToString();
|
||||
RefreshTrack(w, report);
|
||||
RefreshHistory(w, report);
|
||||
RefreshRequirements(report);
|
||||
RefreshBalance(report);
|
||||
RefreshIncome(report);
|
||||
UpdateLoanButtons();
|
||||
}
|
||||
|
||||
private void RefreshTrack(ClientWorld w, ClimbReport report)
|
||||
{
|
||||
var next = report.Tiers.FirstOrDefault(t => t.Level == report.NextTier);
|
||||
_track.Set(report.Tiers.Count, report.Tier, report.NextTier > 0 ? report.Progress : 1,
|
||||
next is null ? "" : $"{Fmt.Progress(report.Progress)} {T("verso")} {TierName(next)}");
|
||||
foreach (var c in _stations.GetChildren()) c.QueueFree();
|
||||
foreach (var t in report.Tiers)
|
||||
{
|
||||
bool current = t.Level == report.Tier, isNext = t.Level == report.NextTier;
|
||||
var col = PanelKit.Column(2);
|
||||
col.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
var name = UiTheme.TitleLabel(TierName(t), 30, current ? Palette.AmberLight : t.Reached || isNext ? Palette.Text : Palette.TextSecondary);
|
||||
name.HorizontalAlignment = HorizontalAlignment.Center;
|
||||
col.AddChild(name);
|
||||
string status = t.Level == 1 ? $"{T("dal")} {YearOf(w, t.ReachedDay)}"
|
||||
: t.Reached ? (t.ReachedDay >= 0 ? $"{T("raggiunta nel")} {YearOf(w, t.ReachedDay)}" : T("raggiunta"))
|
||||
: isNext ? $"{T("avanzamento")} {Fmt.Progress(report.Progress)}"
|
||||
: $"{T("patrimonio")} {Short(t.NetWorthRequired)}";
|
||||
var statusLabel = UiTheme.Text(status, 14, current ? Palette.AmberLight : Palette.Text, bold: true);
|
||||
statusLabel.HorizontalAlignment = HorizontalAlignment.Center;
|
||||
col.AddChild(statusLabel);
|
||||
col.AddChild(new Control { CustomMinimumSize = new Vector2(0, 8) });
|
||||
foreach (var u in t.Unlocks)
|
||||
{
|
||||
var l = UiTheme.Text(UnlockText(u), 13, Palette.TextSecondary);
|
||||
l.HorizontalAlignment = HorizontalAlignment.Center;
|
||||
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
col.AddChild(l);
|
||||
}
|
||||
_stations.AddChild(col);
|
||||
}
|
||||
}
|
||||
|
||||
private void RefreshHistory(ClientWorld w, ClimbReport report)
|
||||
{
|
||||
var values = report.History.Select(p => (double)p.Value.Cents).ToList();
|
||||
var labels = report.History.Select(p => YearOf(w, p.Day).ToString()).ToList();
|
||||
_chart.Show(values, labels, v => new Money((long)v).ToString("short"), SeriesChart.Style.Line, Palette.Amber, T("Lo storico cresce anno dopo anno"));
|
||||
// i livelli raggiunti si segnano sul punto dell'anno della promozione (un punto per anno di
|
||||
// calendario, l'ultimo è oggi); in mancanza sul primo punto dopo la promozione
|
||||
var markers = new List<(int Index, string Label)>();
|
||||
foreach (var t in report.Tiers.Where(t => t.Level > 1 && t.Reached && t.ReachedDay >= 0))
|
||||
{
|
||||
int year = YearOf(w, t.ReachedDay);
|
||||
int index = report.History.FindIndex(p => YearOf(w, p.Day) == year);
|
||||
if (index < 0) index = report.History.FindIndex(p => p.Day >= t.ReachedDay);
|
||||
if (index >= 0) markers.Add((index, TierName(t)));
|
||||
}
|
||||
_chart.SetMarkers(markers);
|
||||
if (report.History.Count >= 2)
|
||||
{
|
||||
var first = report.History[0];
|
||||
var last = report.History[^1];
|
||||
int years = Math.Max(0, YearOf(w, last.Day) - YearOf(w, first.Day));
|
||||
_historyCaption.Text = $"{T("da")} {first.Value} {T("a")} {Short(last.Value)} {T("in")} {years} {(years == 1 ? T("anno") : T("anni"))}";
|
||||
}
|
||||
else _historyCaption.Text = "";
|
||||
}
|
||||
|
||||
private void RefreshRequirements(ClimbReport report)
|
||||
{
|
||||
foreach (var c in _requirements.GetChildren()) c.QueueFree();
|
||||
var next = report.Tiers.FirstOrDefault(t => t.Level == report.NextTier);
|
||||
if (next is null)
|
||||
{
|
||||
_nextTitle.Text = T("Hai raggiunto il livello più alto");
|
||||
return;
|
||||
}
|
||||
_nextTitle.Text = $"{T("Per diventare")} {TierName(next)}";
|
||||
_requirements.AddChild(Requirement($"{T("Patrimonio netto di")} {Short(report.NetWorthRequired)}", report.NetWorthFraction, report.NetWorthMet,
|
||||
$"{Short(report.NetWorth)}, {Fmt.Progress(report.NetWorthFraction)}"));
|
||||
_requirements.AddChild(Requirement($"{report.TownsRequired} {T("città oltre")} {Fmt.Number(report.TownPopulation, 0)} {T("abitanti")}",
|
||||
report.TownsFraction, report.TownsMet, $"{report.Towns} {(report.Towns == 1 ? T("collegata su") : T("collegate su"))} {report.TownsRequired}"));
|
||||
_requirements.AddChild(Requirement($"{T("Rating creditizio")} {report.RatingRequired}", report.RatingFraction, report.RatingMet,
|
||||
$"{T("attuale")} {report.Rating}"));
|
||||
}
|
||||
|
||||
private static Control Requirement(string caption, float fraction, bool met, string value)
|
||||
{
|
||||
var col = PanelKit.Column(6);
|
||||
col.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
col.AddChild(UiTheme.Text(caption, 14));
|
||||
var color = met ? Palette.Ok : Palette.Amber;
|
||||
var bar = new ProgressBar { MinValue = 0, MaxValue = 1, Step = 0.001, Value = Math.Clamp(fraction, 0, 1), ShowPercentage = false, CustomMinimumSize = new Vector2(0, 8) };
|
||||
bar.AddThemeStyleboxOverride("background", UiTheme.Box(Palette.Border, Palette.Border, 4, 0));
|
||||
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(color, color, 4, 0));
|
||||
col.AddChild(bar);
|
||||
col.AddChild(UiTheme.Text((met ? "✓ " : "") + value, 13, met ? Palette.Ok : Palette.TextSecondary));
|
||||
WhyTooltip.Attach(col, () => new ExplainTarget(ExplainSubject.TierProgress));
|
||||
return col;
|
||||
}
|
||||
|
||||
private static string AssetName(byte kind) => kind switch
|
||||
{
|
||||
ClimbReport.AssetTrack => T("Binari e opere"),
|
||||
ClimbReport.AssetStations => T("Stazioni e depositi"),
|
||||
ClimbReport.AssetVehicles => T("Materiale rotabile"),
|
||||
ClimbReport.AssetIndustries => T("Industrie possedute"),
|
||||
ClimbReport.AssetGoods => T("Merce propria"),
|
||||
_ => "",
|
||||
};
|
||||
|
||||
private void RefreshBalance(ClimbReport report)
|
||||
{
|
||||
foreach (var c in _balance.GetChildren()) c.QueueFree();
|
||||
foreach (var a in report.Assets)
|
||||
{
|
||||
// le voci di base si vedono sempre, industrie e merce solo se ci sono
|
||||
bool always = a.Kind is ClimbReport.AssetTrack or ClimbReport.AssetStations or ClimbReport.AssetVehicles;
|
||||
if (always || a.Value.Cents != 0) _balance.AddChild(Line(AssetName(a.Kind), a.Value.ToString()));
|
||||
}
|
||||
if (report.Portfolio.Cents != 0) _balance.AddChild(Line(T("Partecipazioni"), report.Portfolio.ToString()));
|
||||
_balance.AddChild(Line(T("Cassa"), report.Cash.ToString()));
|
||||
_balance.AddChild(PanelKit.Separator());
|
||||
_balance.AddChild(Line(T("Totale attivo"), report.TotalAssets.ToString(), bold: true));
|
||||
string loans = report.Loans.Cents > 0 ? $"{T("Prestiti al")} {Fmt.Pct(report.LoansRate, 1)}" : T("Prestiti");
|
||||
_balance.AddChild(Line(loans, report.Loans.ToString()));
|
||||
if (report.Overdraft.Cents > 0) _balance.AddChild(Line(T("Scoperto di cassa"), report.Overdraft.ToString(), color: Palette.Danger));
|
||||
_balance.AddChild(Line(T("Patrimonio netto"), report.BalanceNetWorth.ToString(), bold: true, color: Palette.AmberLight));
|
||||
}
|
||||
|
||||
private void RefreshIncome(ClimbReport report)
|
||||
{
|
||||
_incomeTitle.Text = $"{T("Conto economico")} {report.IncomeYear}{(report.IncomePartial ? " " + T("(finora)") : "")}";
|
||||
foreach (var c in _income.GetChildren()) c.QueueFree();
|
||||
foreach (var i in report.Income)
|
||||
{
|
||||
string name = i.Kind switch
|
||||
{
|
||||
ClimbReport.IncomeFares => T("Ricavi da tariffe e noli"),
|
||||
ClimbReport.IncomeOther => T("Altri ricavi"),
|
||||
ClimbReport.IncomeOperating => T("Costi operativi"),
|
||||
ClimbReport.IncomeMaintenance => T("Manutenzione"),
|
||||
ClimbReport.IncomeInterest => T("Interessi"),
|
||||
_ => "",
|
||||
};
|
||||
if (i.Kind == ClimbReport.IncomeOther && i.Value.Cents == 0) continue;
|
||||
// i costi si mostrano in valore assoluto: l'etichetta dice già che sono costi
|
||||
bool cost = i.Kind is ClimbReport.IncomeOperating or ClimbReport.IncomeMaintenance or ClimbReport.IncomeInterest;
|
||||
var value = cost ? new Money(Math.Abs(i.Value.Cents)) : i.Value;
|
||||
_income.AddChild(Line(name, value.ToString()));
|
||||
}
|
||||
_income.AddChild(PanelKit.Separator());
|
||||
_income.AddChild(Line(T("Utile netto"), report.Profit.ToString(), bold: true, color: report.Profit.IsNegative ? Palette.Danger : Palette.AmberLight));
|
||||
}
|
||||
|
||||
private static Control Line(string caption, string value, bool bold = false, Color? color = null)
|
||||
{
|
||||
var row = PanelKit.Row(8);
|
||||
var c = UiTheme.Text(caption, 14, bold ? Palette.Text : Palette.TextSecondary, bold);
|
||||
c.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
var v = UiTheme.Text(value, 14, color ?? Palette.Text, bold);
|
||||
v.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
row.AddChild(c);
|
||||
row.AddChild(v);
|
||||
return row;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ prestiti (comandi al server)
|
||||
|
||||
/// <summary>Prestito da rimborsare per primo: quello con il tasso più alto (scelta dell'interfaccia).</summary>
|
||||
private LoanInfo? LoanToRepay() => _shown?.LoanList.OrderByDescending(l => l.AnnualRate).ThenBy(l => l.Loan).FirstOrDefault();
|
||||
|
||||
private Money Amount => Money.FromLire((long)_amount.Value);
|
||||
|
||||
private void UpdateLoanButtons()
|
||||
{
|
||||
var report = _shown;
|
||||
var loan = LoanToRepay();
|
||||
var repay = loan is null ? Amount : Money.Min(Amount, loan.Remaining);
|
||||
_repay.Text = $"{T("Rimborsa")} {repay}";
|
||||
_repay.Disabled = loan is null;
|
||||
_borrow.Disabled = report is null || !report.LoansAllowed;
|
||||
bool bankrupt = report is not null && _session.World.Companies.TryGetValue(report.Company, out var me) && me.Bankrupt;
|
||||
_borrow.TooltipText = report is null ? "" : report.LoansAllowed
|
||||
? $"{T("Fido disponibile")} {report.LoanAvailable} {T("su")} {report.MaxLoan}, {T("al")} {Fmt.Pct(report.NewLoanRate, 1)}"
|
||||
: bankrupt ? T("In bancarotta non si possono chiedere prestiti") : T("In amministrazione controllata non si possono chiedere prestiti");
|
||||
}
|
||||
|
||||
private void Borrow() =>
|
||||
_session.Command(new TakeLoanCommand(Amount), r =>
|
||||
{
|
||||
_status.Text = r.Message;
|
||||
Request(Fmt.Today(_session.World));
|
||||
});
|
||||
|
||||
private void Repay()
|
||||
{
|
||||
var loan = LoanToRepay();
|
||||
if (loan is null) return;
|
||||
_session.Command(new RepayLoanCommand(new LoanId(loan.Loan), Money.Min(Amount, loan.Remaining)), r =>
|
||||
{
|
||||
_status.Text = r.Message;
|
||||
Request(Fmt.Today(_session.World));
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Binario dei livelli (immagine 08): rotaie e traversine da una stazione all'altra, ambra fino al
|
||||
/// treno, cerchi pieni per i livelli raggiunti, anello per quello attuale, il treno e la sua etichetta.
|
||||
/// </summary>
|
||||
private sealed partial class TierTrack : Control
|
||||
{
|
||||
private int _count = 5, _tier = 1;
|
||||
private float _progress;
|
||||
private string _label = "";
|
||||
|
||||
public TierTrack()
|
||||
{
|
||||
CustomMinimumSize = new Vector2(0, 112);
|
||||
MouseFilter = MouseFilterEnum.Ignore;
|
||||
}
|
||||
|
||||
public void Set(int count, int tier, float progress, string label)
|
||||
{
|
||||
_count = Math.Max(1, count);
|
||||
_tier = Math.Clamp(tier, 1, _count);
|
||||
_progress = Math.Clamp(progress, 0, 1);
|
||||
_label = label;
|
||||
QueueRedraw();
|
||||
}
|
||||
|
||||
private float X(int level) => (level - 0.5f) * Size.X / _count;
|
||||
|
||||
public override void _Draw()
|
||||
{
|
||||
const float y = 78;
|
||||
float x0 = X(1), x1 = X(_count);
|
||||
float trainX = _tier >= _count ? x1 : X(_tier) + (X(_tier + 1) - X(_tier)) * _progress;
|
||||
var dim = Palette.Rails.Lerp(Palette.Border, 0.4f);
|
||||
// traversine, poi le due rotaie
|
||||
for (float x = x0; x <= x1; x += 12)
|
||||
DrawLine(new Vector2(x, y - 9), new Vector2(x, y + 9), x <= trainX ? Palette.WithAlpha(Palette.Amber, 0.45f) : Palette.Border, 3);
|
||||
foreach (float dy in new[] { -5f, 5f })
|
||||
{
|
||||
DrawLine(new Vector2(x0, y + dy), new Vector2(trainX, y + dy), Palette.Amber, 3);
|
||||
if (trainX < x1) DrawLine(new Vector2(trainX, y + dy), new Vector2(x1, y + dy), dim, 3);
|
||||
}
|
||||
for (int level = 1; level <= _count; level++)
|
||||
{
|
||||
var c = new Vector2(X(level), y);
|
||||
bool reached = level <= _tier;
|
||||
if (level == _tier)
|
||||
{
|
||||
DrawCircle(c, 32, Palette.Panel);
|
||||
DrawArc(c, 31, 0, MathF.Tau, 48, Palette.Amber, 2.5f, true);
|
||||
}
|
||||
DrawCircle(c, 21, reached ? Palette.Amber : Palette.Panel);
|
||||
DrawArc(c, 21, 0, MathF.Tau, 40, reached ? Palette.AppBackground : Palette.Border.Lerp(Palette.TextSecondary, 0.35f), 3, true);
|
||||
}
|
||||
if (_label.Length > 0 && _tier < _count) DrawTrain(new Vector2(trainX, y - 16));
|
||||
}
|
||||
|
||||
/// <summary>Locomotiva stilizzata con l'etichetta dell'avanzamento sopra.</summary>
|
||||
private void DrawTrain(Vector2 at)
|
||||
{
|
||||
var body = Palette.AmberLight;
|
||||
DrawRect(new Rect2(at.X - 30, at.Y - 22, 46, 20), body);
|
||||
DrawRect(new Rect2(at.X + 10, at.Y - 34, 20, 32), body);
|
||||
DrawRect(new Rect2(at.X - 24, at.Y - 32, 8, 10), body);
|
||||
foreach (float dx in new[] { -18f, -2f, 14f })
|
||||
{
|
||||
DrawCircle(new Vector2(at.X + dx, at.Y + 4), 6, Palette.AppBackground);
|
||||
DrawArc(new Vector2(at.X + dx, at.Y + 4), 6, 0, MathF.Tau, 16, body, 2.5f, true);
|
||||
}
|
||||
var font = UiTheme.BodyBold;
|
||||
var dims = font.GetStringSize(_label, HorizontalAlignment.Left, -1, 15);
|
||||
float x = Math.Clamp(at.X - dims.X / 2, 4, Size.X - dims.X - 4);
|
||||
DrawString(font, new Vector2(x, at.Y - 44), _label, HorizontalAlignment.Left, -1, 15, Palette.AmberLight);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,491 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.Net;
|
||||
using RailEnterprise.Core.Commands;
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Protocol.Client;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
using RailEnterprise.Client.App;
|
||||
|
||||
namespace RailEnterprise.Client.Panels;
|
||||
|
||||
/// <summary>
|
||||
/// «Finanze» a tutto schermo (palette 05, stile del pannello 08): a sinistra il conto economico per
|
||||
/// voce con le colonne del mese in corso, dei mesi chiusi e dell'anno (o degli anni chiusi); a destra
|
||||
/// il rating con la sua spiegazione, i prestiti con rimborso e richiesta, e, se la cassa è negativa, la
|
||||
/// barra dei giorni che restano prima della bancarotta. Tutti i numeri arrivano dal server
|
||||
/// (FinanceReport, ADR 0019): il pannello li chiede all'apertura, a ogni nuovo giorno e dopo un
|
||||
/// comando, e li mostra com'è, senza calcolare utili, rating o rate.
|
||||
/// </summary>
|
||||
public partial class FinancePanel : VBoxContainer
|
||||
{
|
||||
/// <summary>Mesi chiusi e anni chiusi mostrati accanto alla colonna in corso.</summary>
|
||||
private const int ClosedColumns = 5;
|
||||
|
||||
private readonly GameSession _session;
|
||||
private readonly Label _subtitle = UiTheme.Text("", 14, Palette.TextSecondary);
|
||||
private readonly Label _cash = UiTheme.Text("", 30, Palette.AmberLight, bold: true);
|
||||
private readonly PanelContainer _danger = new() { SizeFlagsHorizontal = SizeFlags.ExpandFill, Visible = false };
|
||||
private readonly Label _dangerText = UiTheme.Text("", 15, Palette.Danger, bold: true);
|
||||
private readonly ProgressBar _dangerBar = new() { MinValue = 0, MaxValue = 1, Step = 0.001, ShowPercentage = false, CustomMinimumSize = new Vector2(0, 10) };
|
||||
private readonly Label _dangerDetail = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
private readonly Button _months = new() { Text = "", ToggleMode = true, ButtonPressed = true, CustomMinimumSize = new Vector2(90, 36) };
|
||||
private readonly Button _years = new() { Text = "", ToggleMode = true, CustomMinimumSize = new Vector2(90, 36) };
|
||||
private readonly GridContainer _table = new() { SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
private readonly Label _tableNote = UiTheme.Text("", 12, Palette.TextSecondary);
|
||||
private readonly Label _rating = UiTheme.TitleLabel("", 56, Palette.AmberLight);
|
||||
private readonly Label _ratingCaption = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
private readonly VBoxContainer _ratingBody = PanelKit.Column(6);
|
||||
private readonly VBoxContainer _loans = PanelKit.Column(8);
|
||||
private readonly Label _credit = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
private readonly SpinBox _amount = new() { MinValue = 1_000, MaxValue = 100_000_000, Step = 1_000, Value = 50_000, Prefix = "₤", CustomMinimumSize = new Vector2(150, 0) };
|
||||
private readonly Button _borrow = new() { Text = "", CustomMinimumSize = new Vector2(0, 44), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
private readonly Label _status = UiTheme.Text("", 12, Palette.TextSecondary);
|
||||
private FinanceReport? _shown;
|
||||
private long _requestedDay = long.MinValue;
|
||||
private double _sinceRequest = double.MaxValue;
|
||||
|
||||
public event Action? CloseRequested;
|
||||
|
||||
public FinancePanel(GameSession session)
|
||||
{
|
||||
_session = session;
|
||||
AddThemeConstantOverride("separation", 16);
|
||||
SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||
|
||||
var header = PanelKit.Row(24);
|
||||
var titles = PanelKit.Column(0);
|
||||
titles.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
titles.AddChild(UiTheme.TitleLabel(T("Finanze"), 44));
|
||||
titles.AddChild(_subtitle);
|
||||
header.AddChild(titles);
|
||||
var cash = PanelKit.Column(0);
|
||||
cash.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||||
var cashCaption = UiTheme.Text(T("Cassa"), 13, Palette.TextSecondary);
|
||||
cashCaption.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
_cash.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
cash.AddChild(cashCaption);
|
||||
cash.AddChild(_cash);
|
||||
WhyTooltip.Attach(_cash, () => new ExplainTarget(ExplainSubject.Cash), shown: () => _session.World.Finance?.Cash.Cents);
|
||||
header.AddChild(cash);
|
||||
var close = new Button { Text = T("Torna alla mappa"), SizeFlagsVertical = SizeFlags.ShrinkCenter, CustomMinimumSize = new Vector2(170, 48) };
|
||||
close.Pressed += () => CloseRequested?.Invoke();
|
||||
header.AddChild(close);
|
||||
AddChild(header);
|
||||
|
||||
// barra della cassa negativa: giorni passati sul limite della difficoltà
|
||||
_danger.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Danger, 12, 18));
|
||||
var dangerCol = PanelKit.Column(8);
|
||||
dangerCol.AddChild(_dangerText);
|
||||
_dangerBar.AddThemeStyleboxOverride("background", UiTheme.Box(Palette.Border, Palette.Border, 5, 0));
|
||||
_dangerBar.AddThemeStyleboxOverride("fill", UiTheme.Box(Palette.Danger, Palette.Danger, 5, 0));
|
||||
dangerCol.AddChild(_dangerBar);
|
||||
_dangerDetail.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
dangerCol.AddChild(_dangerDetail);
|
||||
_danger.AddChild(dangerCol);
|
||||
AddChild(_danger);
|
||||
|
||||
var body = PanelKit.Row(20);
|
||||
body.SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||
AddChild(body);
|
||||
|
||||
// conto economico
|
||||
var left = Column(body, 1.35f);
|
||||
var incomeHeader = PanelKit.Row(8);
|
||||
var incomeTitle = UiTheme.Text(T("Conto economico"), 20, bold: true);
|
||||
incomeTitle.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
incomeHeader.AddChild(incomeTitle);
|
||||
var group = new ButtonGroup();
|
||||
_months.ButtonGroup = group;
|
||||
_years.ButtonGroup = group;
|
||||
_months.Text = T("Mesi");
|
||||
_years.Text = T("Anni");
|
||||
_months.Pressed += () => RefreshTable(_shown);
|
||||
_years.Pressed += () => RefreshTable(_shown);
|
||||
incomeHeader.AddChild(_months);
|
||||
incomeHeader.AddChild(_years);
|
||||
left.AddChild(incomeHeader);
|
||||
_table.AddThemeConstantOverride("h_separation", 18);
|
||||
_table.AddThemeConstantOverride("v_separation", 6);
|
||||
left.AddChild(_table);
|
||||
_tableNote.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
left.AddChild(_tableNote);
|
||||
|
||||
// rating e prestiti
|
||||
var right = Column(body, 0.9f);
|
||||
right.AddChild(UiTheme.Text(T("Rating creditizio"), 20, bold: true));
|
||||
var ratingRow = PanelKit.Row(16);
|
||||
ratingRow.AddChild(_rating);
|
||||
WhyTooltip.Attach(_rating, () => new ExplainTarget(ExplainSubject.Rating));
|
||||
_ratingCaption.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||||
_ratingCaption.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
_ratingCaption.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
ratingRow.AddChild(_ratingCaption);
|
||||
right.AddChild(ratingRow);
|
||||
right.AddChild(_ratingBody);
|
||||
right.AddChild(PanelKit.Separator());
|
||||
right.AddChild(UiTheme.Text(T("Prestiti"), 20, bold: true));
|
||||
right.AddChild(_loans);
|
||||
_credit.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
right.AddChild(_credit);
|
||||
var loanRow = PanelKit.Row(10);
|
||||
loanRow.AddChild(_amount);
|
||||
loanRow.AddChild(_borrow);
|
||||
right.AddChild(loanRow);
|
||||
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
right.AddChild(_status);
|
||||
_borrow.Text = T("Chiedi un prestito");
|
||||
_borrow.Pressed += Borrow;
|
||||
_amount.ValueChanged += _ => RefreshLoans(_shown);
|
||||
|
||||
_subtitle.Text = T("In attesa del quadro dal server…");
|
||||
}
|
||||
|
||||
private static VBoxContainer Column(HBoxContainer body, float ratio)
|
||||
{
|
||||
var frame = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ExpandFill, SizeFlagsStretchRatio = ratio };
|
||||
frame.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 12, 24));
|
||||
var scroll = new ScrollContainer { HorizontalScrollMode = ScrollContainer.ScrollMode.Auto, SizeFlagsVertical = SizeFlags.ExpandFill };
|
||||
frame.AddChild(scroll);
|
||||
var margin = new MarginContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ExpandFill };
|
||||
margin.AddThemeConstantOverride("margin_right", 10);
|
||||
scroll.AddChild(margin);
|
||||
var col = PanelKit.Column(12);
|
||||
col.SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||
margin.AddChild(col);
|
||||
body.AddChild(frame);
|
||||
return col;
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
var w = _session.World;
|
||||
_sinceRequest += delta;
|
||||
// il quadro si chiede all'apertura e a ogni nuovo giorno (di nuovo dopo 5 s se non arriva)
|
||||
long today = Fmt.Today(w);
|
||||
if (today != _requestedDay || (w.Finance is null && _sinceRequest > 5)) Request(today);
|
||||
if (w.Finance is { } report && !ReferenceEquals(report, _shown)) Refresh(w, report);
|
||||
}
|
||||
|
||||
private void Request(long day)
|
||||
{
|
||||
_requestedDay = day;
|
||||
_sinceRequest = 0;
|
||||
_session.Send(new RequestDetail { Kind = DetailKind.Finance, Target = 0 });
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ aggiornamento
|
||||
|
||||
private void Refresh(ClientWorld w, FinanceReport report)
|
||||
{
|
||||
_shown = report;
|
||||
_subtitle.Text = $"{Fmt.Company(w, report.Company)} · {Fmt.Date(w, report.Day)} · {T("patrimonio netto")} {report.NetWorth}";
|
||||
_cash.Text = report.Cash.ToString();
|
||||
_cash.AddThemeColorOverride("font_color", report.Cash.IsNegative ? Palette.Danger : Palette.AmberLight);
|
||||
RefreshDanger(report);
|
||||
RefreshTable(report);
|
||||
RefreshRating(report);
|
||||
RefreshLoans(report);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Barra della cassa negativa. Il motore conta i giorni una volta al giorno, quindi dopo un prestito il
|
||||
/// contatore può restare indietro di un giorno rispetto alla cassa: il conto alla rovescia si mostra solo
|
||||
/// con la cassa davvero negativa (scoperto) o in bancarotta.
|
||||
/// </summary>
|
||||
private void RefreshDanger(FinanceReport r)
|
||||
{
|
||||
bool overdraft = r.Overdraft.Cents > 0;
|
||||
bool recovering = !overdraft && !r.Bankrupt && r.NegativeCashDays > 0;
|
||||
_danger.Visible = overdraft || r.Bankrupt || recovering;
|
||||
_dangerBar.Visible = overdraft || r.Bankrupt;
|
||||
if (!_danger.Visible) return;
|
||||
_dangerBar.Value = r.BankruptcyDays > 0 ? Math.Clamp((double)r.NegativeCashDays / r.BankruptcyDays, 0, 1) : 1;
|
||||
if (r.Bankrupt)
|
||||
{
|
||||
_dangerText.Text = T("Bancarotta dichiarata");
|
||||
_dangerDetail.Text = T("La compagnia non ha riportato la cassa sopra zero entro il limite della difficoltà.");
|
||||
return;
|
||||
}
|
||||
if (recovering)
|
||||
{
|
||||
_dangerText.Text = T("La cassa è tornata positiva");
|
||||
_dangerDetail.Text = string.Format(T("Dopo {0} di cassa negativa il conto alla rovescia della bancarotta si azzera domani."), Days(r.NegativeCashDays));
|
||||
return;
|
||||
}
|
||||
int left = Math.Max(0, r.BankruptcyDays - r.NegativeCashDays);
|
||||
_dangerText.Text = r.NegativeCashDays == 0
|
||||
? string.Format(T("Cassa negativa da oggi: bancarotta tra {0}"), Days(r.BankruptcyDays))
|
||||
: string.Format(T("Cassa negativa da {0}: bancarotta tra {1}"), Days(r.NegativeCashDays), Days(left));
|
||||
_dangerDetail.Text = string.Format(T("Scoperto {0}. Il limite della difficoltà è di {1}; riporta la cassa sopra zero con un prestito, vendendo treni o riducendo i costi."),
|
||||
r.Overdraft, Days(r.BankruptcyDays));
|
||||
}
|
||||
|
||||
private static string Days(int n) => n == 1 ? $"1 {T("giorno")}" : $"{n} {T("giorni")}";
|
||||
|
||||
// ------------------------------------------------------------------ conto economico
|
||||
|
||||
private static string[] MonthNames() =>
|
||||
[T("gen"), T("feb"), T("mar"), T("apr"), T("mag"), T("giu"), T("lug"), T("ago"), T("set"), T("ott"), T("nov"), T("dic")];
|
||||
|
||||
/// <summary>Colonne da mostrare: il mese in corso e i mesi chiusi, poi l'anno in corso; oppure l'anno in corso e gli anni chiusi.</summary>
|
||||
private List<IncomeColumnInfo> ShownColumns(FinanceReport r)
|
||||
{
|
||||
if (_years.ButtonPressed)
|
||||
{
|
||||
return r.Columns.Where(c => c.Kind == IncomeColumnInfo.CurrentYear)
|
||||
.Concat(r.Columns.Where(c => c.Kind == IncomeColumnInfo.ClosedYear).Take(ClosedColumns)).ToList();
|
||||
}
|
||||
return r.Columns.Where(c => c.Kind == IncomeColumnInfo.CurrentMonth)
|
||||
.Concat(r.Columns.Where(c => c.Kind == IncomeColumnInfo.ClosedMonth).Take(ClosedColumns))
|
||||
.Concat(r.Columns.Where(c => c.Kind == IncomeColumnInfo.CurrentYear)).ToList();
|
||||
}
|
||||
|
||||
private static string ColumnTitle(IncomeColumnInfo c)
|
||||
{
|
||||
string month = c.Month is >= 1 and <= 12 ? MonthNames()[c.Month - 1] : "";
|
||||
return c.Kind switch
|
||||
{
|
||||
IncomeColumnInfo.CurrentMonth => $"{month} {c.Year}\n{T("in corso")}",
|
||||
IncomeColumnInfo.ClosedMonth => $"{month} {c.Year}\n ",
|
||||
IncomeColumnInfo.CurrentYear => $"{c.Year}\n{T("finora")}",
|
||||
_ => $"{c.Year}\n ",
|
||||
};
|
||||
}
|
||||
|
||||
private void RefreshTable(FinanceReport? r)
|
||||
{
|
||||
foreach (var c in _table.GetChildren()) c.QueueFree();
|
||||
if (r is null) return;
|
||||
var columns = ShownColumns(r);
|
||||
_table.Columns = columns.Count + 1;
|
||||
Cell(T("Voce"), Palette.TextSecondary, bold: true, left: true);
|
||||
foreach (var c in columns)
|
||||
Cell(ColumnTitle(c), c.Kind is IncomeColumnInfo.CurrentMonth or IncomeColumnInfo.CurrentYear ? Palette.AmberLight : Palette.TextSecondary, bold: true);
|
||||
|
||||
foreach (byte section in new[] { FinanceLineInfo.SectionRevenue, FinanceLineInfo.SectionCost, FinanceLineInfo.SectionCapital })
|
||||
{
|
||||
// le voci sempre a zero nelle colonne mostrate non occupano righe
|
||||
var lines = r.Lines.Where(l => l.Section == section && columns.Any(c => c.Value(l.Kind).Cents != 0)).ToList();
|
||||
if (lines.Count == 0) continue;
|
||||
Cell(SectionName(section), Palette.Amber, bold: true, left: true);
|
||||
foreach (var _ in columns) Cell("", Palette.Text);
|
||||
foreach (var line in lines)
|
||||
{
|
||||
Cell(EntryName((LedgerEntry)line.Kind), Palette.Text, left: true, indent: true);
|
||||
foreach (var c in columns)
|
||||
{
|
||||
var v = c.Value(line.Kind);
|
||||
Cell(v.Cents == 0 ? "—" : v.ToString(), v.IsNegative ? Palette.Danger : v.Cents == 0 ? Palette.TextSecondary : Palette.Text);
|
||||
}
|
||||
}
|
||||
if (section == FinanceLineInfo.SectionCost)
|
||||
{
|
||||
Cell(T("Utile operativo"), Palette.Text, bold: true, left: true);
|
||||
foreach (var c in columns) Cell(c.Profit.ToString(), c.Profit.IsNegative ? Palette.Danger : Palette.AmberLight, bold: true);
|
||||
}
|
||||
}
|
||||
Cell(T("Flusso di cassa"), Palette.Text, bold: true, left: true);
|
||||
foreach (var c in columns) Cell(c.CashFlow.ToString(), c.CashFlow.IsNegative ? Palette.Danger : Palette.Ok, bold: true);
|
||||
_tableNote.Text = columns.Count <= 1
|
||||
? T("I mesi e gli anni chiusi compaiono qui man mano che passano.")
|
||||
: T("L'utile operativo comprende ricavi e costi d'esercizio; investimenti, prestiti e azioni cambiano solo la cassa.");
|
||||
}
|
||||
|
||||
private void Cell(string text, Color color, bool bold = false, bool left = false, bool indent = false)
|
||||
{
|
||||
var l = UiTheme.Text(indent ? " " + text : text, 14, color, bold);
|
||||
l.HorizontalAlignment = left ? HorizontalAlignment.Left : HorizontalAlignment.Right;
|
||||
if (left) l.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
else l.CustomMinimumSize = new Vector2(110, 0);
|
||||
_table.AddChild(l);
|
||||
}
|
||||
|
||||
private static string SectionName(byte section) => section switch
|
||||
{
|
||||
FinanceLineInfo.SectionRevenue => T("Ricavi"),
|
||||
FinanceLineInfo.SectionCost => T("Costi"),
|
||||
_ => T("Investimenti e finanziamenti"),
|
||||
};
|
||||
|
||||
/// <summary>Nome della voce del registro nella lingua dell'interfaccia.</summary>
|
||||
public static string EntryName(LedgerEntry e) => e switch
|
||||
{
|
||||
LedgerEntry.FreightRevenue => T("Noli merci"),
|
||||
LedgerEntry.PassengerRevenue => T("Biglietti passeggeri"),
|
||||
LedgerEntry.Trading => T("Commercio in proprio"),
|
||||
LedgerEntry.Contracts => T("Contratti"),
|
||||
LedgerEntry.Industries => T("Industrie possedute"),
|
||||
LedgerEntry.Subsidiaries => T("Controllate"),
|
||||
LedgerEntry.DividendsReceived => T("Dividendi incassati"),
|
||||
LedgerEntry.RunningCosts => T("Esercizio dei treni"),
|
||||
LedgerEntry.StationUpkeep => T("Stazioni e depositi"),
|
||||
LedgerEntry.FleetMaintenance => T("Manutenzione dei treni"),
|
||||
LedgerEntry.TrackMaintenance => T("Manutenzione dei binari"),
|
||||
LedgerEntry.Wages => T("Stipendi"),
|
||||
LedgerEntry.Interest => T("Interessi"),
|
||||
LedgerEntry.Duties => T("Dazi"),
|
||||
LedgerEntry.Storage => T("Magazzini"),
|
||||
LedgerEntry.Penalties => T("Penali"),
|
||||
LedgerEntry.Construction => T("Costruzioni"),
|
||||
LedgerEntry.VehiclePurchase => T("Acquisto di treni"),
|
||||
LedgerEntry.VehicleSale => T("Vendita di treni"),
|
||||
LedgerEntry.IndustryPurchase => T("Acquisto di industrie"),
|
||||
LedgerEntry.LoanTaken => T("Prestiti ricevuti"),
|
||||
LedgerEntry.LoanRepaid => T("Prestiti rimborsati"),
|
||||
LedgerEntry.Shares => T("Azioni"),
|
||||
LedgerEntry.Dividends => T("Dividendi pagati"),
|
||||
_ => T("Altro"),
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ rating
|
||||
|
||||
private static string Ratio(double value) => Fmt.Number(value, 2);
|
||||
|
||||
private void RefreshRating(FinanceReport r)
|
||||
{
|
||||
_rating.Text = r.Rating;
|
||||
_ratingCaption.Text = r.RatingInitial
|
||||
? T("Rating iniziale: il primo calcolo arriva a inizio mese. Le misure qui sotto sono quelle di oggi.")
|
||||
: $"{T("Calcolato a inizio mese sugli ultimi")} {r.RatingMonths} {(r.RatingMonths == 1 ? T("mese chiuso") : T("mesi chiusi"))}. "
|
||||
+ $"{T("Punteggio")} {Ratio(r.Score)}.";
|
||||
foreach (var c in _ratingBody.GetChildren()) c.QueueFree();
|
||||
|
||||
_ratingBody.AddChild(Measure(T("Margine (utile / ricavi)"), r.MarginNeutral ? T("neutro") : Fmt.Pct(r.Margin, 1), r.MarginWeight, r.MarginComponent));
|
||||
if (r.MarginNeutral)
|
||||
_ratingBody.AddChild(Note(string.Format(T("Il margine conta da quando ci sono almeno {0} mesi chiusi con ricavi (ora {1}): fino ad allora vale 0, così i primi incassi non fanno crollare il rating."),
|
||||
r.MinRevenueMonths, r.RevenueMonths)));
|
||||
string leverage = r.LeverageUnbounded ? T("patrimonio non positivo") : Ratio(r.Leverage);
|
||||
_ratingBody.AddChild(Measure(T("Leva (debiti / patrimonio netto)"), leverage, r.LeverageWeight, r.LeverageComponent));
|
||||
|
||||
if (r.Bankrupt)
|
||||
{
|
||||
_ratingBody.AddChild(Note(T("In bancarotta il rating è D finché la situazione non si risolve.")));
|
||||
}
|
||||
else if (r.NextRating.Length == 0)
|
||||
{
|
||||
_ratingBody.AddChild(Note(T("È il rating più alto: i prestiti costano il minimo.")));
|
||||
}
|
||||
else if (r.NextAlreadyMet)
|
||||
{
|
||||
_ratingBody.AddChild(Note(string.Format(T("Il punteggio {0} vale già {1}: il rating si aggiorna al prossimo calcolo mensile, a inizio mese."),
|
||||
Ratio(r.Score), r.ScoreRating)));
|
||||
}
|
||||
else
|
||||
{
|
||||
var ways = new List<string>();
|
||||
if (r.MarginReachable) ways.Add(string.Format(T("un margine di almeno {0}"), Fmt.Pct(r.MarginNeeded, 1)));
|
||||
if (r.LeverageReachable)
|
||||
{
|
||||
string way = r.DebtToRepay.Cents <= 0 ? T("una leva non oltre {0}")
|
||||
: r.RepayAffordable ? T("una leva non oltre {0} (rimborsando {1})")
|
||||
: T("una leva non oltre {0} (servirebbe rimborsare {1}, più di quanto la cassa consenta oggi)");
|
||||
ways.Add(string.Format(way, Ratio(r.LeverageMax), r.DebtToRepay));
|
||||
}
|
||||
string how = ways.Count == 0 ? T("serve migliorare insieme margine e leva") : string.Join($" {T("oppure")} ", ways);
|
||||
_ratingBody.AddChild(Note(string.Format(T("Per il gradino {0} serve un punteggio di {1}: {2}."), r.NextRating, Ratio(r.NextThreshold), how)));
|
||||
}
|
||||
|
||||
// soglie e tassi per rating
|
||||
var grid = new GridContainer { Columns = 3 };
|
||||
grid.AddThemeConstantOverride("h_separation", 24);
|
||||
grid.AddChild(UiTheme.Text(T("Rating"), 12, Palette.TextSecondary, bold: true));
|
||||
grid.AddChild(UiTheme.Text(T("Punteggio da"), 12, Palette.TextSecondary, bold: true));
|
||||
grid.AddChild(UiTheme.Text(T("Tasso"), 12, Palette.TextSecondary, bold: true));
|
||||
foreach (var t in r.Thresholds)
|
||||
{
|
||||
bool current = t.Rating == r.Rating;
|
||||
var color = current ? Palette.AmberLight : Palette.TextSecondary;
|
||||
grid.AddChild(UiTheme.Text(t.Rating, 12, color, current));
|
||||
grid.AddChild(UiTheme.Text(Ratio(t.MinScore), 12, color, current));
|
||||
grid.AddChild(UiTheme.Text(Fmt.Pct(t.LoanRate, 1), 12, color, current));
|
||||
}
|
||||
_ratingBody.AddChild(grid);
|
||||
}
|
||||
|
||||
private static Control Measure(string caption, string value, float weight, float component)
|
||||
{
|
||||
var col = PanelKit.Column(4);
|
||||
var row = PanelKit.Row(8);
|
||||
var c = UiTheme.Text(caption, 14, Palette.Text);
|
||||
c.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
row.AddChild(c);
|
||||
row.AddChild(UiTheme.Text(value, 14, Palette.Text, bold: true));
|
||||
col.AddChild(row);
|
||||
var bar = new ProgressBar { MinValue = 0, MaxValue = 1, Step = 0.001, Value = Math.Clamp(component, 0, 1), ShowPercentage = false, CustomMinimumSize = new Vector2(0, 6) };
|
||||
bar.AddThemeStyleboxOverride("background", UiTheme.Box(Palette.Border, Palette.Border, 3, 0));
|
||||
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(Palette.Amber, Palette.Amber, 3, 0));
|
||||
col.AddChild(bar);
|
||||
col.AddChild(UiTheme.Text($"{T("componente")} {Ratio(component)} × {T("peso")} {Ratio(weight)}", 12, Palette.TextSecondary));
|
||||
return col;
|
||||
}
|
||||
|
||||
private static Label Note(string text)
|
||||
{
|
||||
var l = UiTheme.Text(text, 13, Palette.Text);
|
||||
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
return l;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ prestiti (comandi al server)
|
||||
|
||||
private Money Amount => Money.FromLire((long)_amount.Value);
|
||||
|
||||
private void RefreshLoans(FinanceReport? r)
|
||||
{
|
||||
foreach (var c in _loans.GetChildren()) c.QueueFree();
|
||||
if (r is null) return;
|
||||
var w = _session.World;
|
||||
if (r.LoanList.Count == 0) _loans.AddChild(UiTheme.Text(T("Nessun prestito in corso."), 13, Palette.TextSecondary));
|
||||
foreach (var loan in r.LoanList)
|
||||
{
|
||||
var card = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
card.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, Palette.Border, 8, 12));
|
||||
var col = PanelKit.Column(4);
|
||||
var head = PanelKit.Row(8);
|
||||
var title = UiTheme.Text($"{T("Residuo")} {loan.Remaining} {T("su")} {loan.Principal}", 14, Palette.Text, bold: true);
|
||||
title.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
head.AddChild(title);
|
||||
head.AddChild(UiTheme.Text($"{Fmt.Pct(loan.AnnualRate, 1)} {T("fisso")}", 14, Palette.AmberLight, bold: true));
|
||||
col.AddChild(head);
|
||||
col.AddChild(UiTheme.Text(
|
||||
$"{T("Rata mensile")} {loan.Payment} ({T("interessi")} {loan.NextInterest}) · {loan.MonthsLeft} {T("mesi")} · {T("scadenza")} {Fmt.Date(w, loan.MaturityDay)}",
|
||||
12, Palette.TextSecondary));
|
||||
var buttons = PanelKit.Row(8);
|
||||
var part = Money.Min(Amount, loan.Remaining);
|
||||
var repay = new Button { Text = $"{T("Rimborsa")} {part}", CustomMinimumSize = new Vector2(0, 34), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
repay.Disabled = part >= loan.Remaining;
|
||||
int id = loan.Loan;
|
||||
repay.Pressed += () => Repay(id, part);
|
||||
var all = new Button { Text = $"{T("Estingui")} ({loan.Remaining})", CustomMinimumSize = new Vector2(0, 34), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
var remaining = loan.Remaining;
|
||||
all.Pressed += () => Repay(id, remaining);
|
||||
buttons.AddChild(repay);
|
||||
buttons.AddChild(all);
|
||||
col.AddChild(buttons);
|
||||
card.AddChild(col);
|
||||
_loans.AddChild(card);
|
||||
}
|
||||
|
||||
_borrow.Disabled = !r.LoansAllowed || r.LoanAvailable.Cents <= 0;
|
||||
_credit.Text = r.Bankrupt ? T("In bancarotta non si possono chiedere prestiti")
|
||||
: r.Receivership ? T("In amministrazione controllata non si possono chiedere prestiti")
|
||||
: string.Format(T("Fido disponibile {0} su {1}. Tasso di un nuovo prestito: {2} fisso (base {3} + rating {4} {5}) per {6} anni."),
|
||||
r.LoanAvailable, r.MaxLoan, Fmt.Pct(r.NewLoanRate, 1), Fmt.Pct(r.BaseRate, 1), r.Rating, Fmt.Pct(r.Spread, 1), r.LoanTermMonths / 12);
|
||||
}
|
||||
|
||||
private void Borrow() =>
|
||||
_session.Command(new TakeLoanCommand(Amount), r =>
|
||||
{
|
||||
_status.Text = r.Message;
|
||||
Request(Fmt.Today(_session.World));
|
||||
});
|
||||
|
||||
private void Repay(int loan, Money amount) =>
|
||||
_session.Command(new RepayLoanCommand(new LoanId(loan), amount), r =>
|
||||
{
|
||||
_status.Text = r.Message;
|
||||
Request(Fmt.Today(_session.World));
|
||||
});
|
||||
}
|
||||
@@ -26,6 +26,12 @@ public static class Fmt
|
||||
/// <summary>Quota (0–1) in percentuale («12,4%»).</summary>
|
||||
public static string Pct(double fraction, int decimals = 1) => Number(fraction * 100, decimals) + "%";
|
||||
|
||||
/// <summary>
|
||||
/// Avanzamento (0–1) in percentuale intera per difetto («99%»): il 100 % compare solo quando la
|
||||
/// frazione è piena, cioè con il requisito o il livello davvero raggiunto (ADR 0018).
|
||||
/// </summary>
|
||||
public static string Progress(double fraction) => Number(Math.Floor(Math.Clamp(fraction, 0, 1) * 100 + 1e-9), 0) + "%";
|
||||
|
||||
/// <summary>Variazione con il segno («+1,2%», «−0,8%»).</summary>
|
||||
public static string Change(double fraction) => (fraction > 0 ? "+" : "") + Pct(fraction);
|
||||
|
||||
|
||||
@@ -11,21 +11,39 @@ using static RailEnterprise.Client.App.Localization;
|
||||
namespace RailEnterprise.Client.Panels;
|
||||
|
||||
/// <summary>
|
||||
/// Industrie (sezione 11): elenco delle industrie della regione e pannello del proprietario
|
||||
/// dell'industria scelta: condizione degli impianti con il moltiplicatore di efficienza, budget di
|
||||
/// manutenzione, scorta di ricambi e macchinari, storico dei fermi, «Fermo programmato»,
|
||||
/// «Ammoderna», «Ordina ricambi»; per le industrie dei privati il prezzo chiesto e «Acquista».
|
||||
/// La scheda del proprietario arriva su richiesta dal server (IndustryCard).
|
||||
/// Scheda dell'industria a tutto schermo (immagine di riferimento 07, sezione 11): in alto nome,
|
||||
/// livello, proprietà, stazione che la serve, valore stimato e l'anello dell'efficienza con il
|
||||
/// fattore che la limita; sotto tre schede (materie prime in ingresso, forza lavoro, produzione), il
|
||||
/// grafo della catena produttiva con fornitori, città dei pendolari e clienti, e la scheda «Impianti
|
||||
/// e crescita» con condizione, punteggio trimestrale e soglie, comandi del proprietario e storico dei
|
||||
/// fermi. Tutti i numeri arrivano dal server nella scheda (IndustryCard, blocco 1: ADR 0021); il
|
||||
/// pannello li chiede una volta al secondo e li mostra com'è.
|
||||
/// </summary>
|
||||
public partial class IndustryPanel : VBoxContainer
|
||||
{
|
||||
private readonly GameSession _session;
|
||||
private readonly ItemList _list = new() { CustomMinimumSize = new Vector2(0, 150) };
|
||||
private readonly OptionButton _chooser = new() { CustomMinimumSize = new Vector2(320, 44), FitToLongestItem = false };
|
||||
private readonly List<int> _ids = [];
|
||||
private readonly VBoxContainer _header = PanelKit.Column(8);
|
||||
private readonly Label _title = UiTheme.TitleLabel("", 44);
|
||||
private readonly Label _subtitle = UiTheme.Text("", 15, Palette.TextSecondary);
|
||||
private readonly Label _ownerLine = UiTheme.Text("", 14, Palette.TextSecondary);
|
||||
private readonly Label _valuation = UiTheme.Text("", 26, Palette.AmberLight, bold: true);
|
||||
private readonly EfficiencyRing _ring = new();
|
||||
private readonly Label _limit = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
private readonly VBoxContainer _notices = PanelKit.Column(6);
|
||||
private readonly ScrollContainer _scroll = new() { HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled, SizeFlagsVertical = SizeFlags.ExpandFill };
|
||||
private readonly VBoxContainer _inputs = PanelKit.Column(8);
|
||||
private readonly VBoxContainer _workforce = PanelKit.Column(8);
|
||||
private readonly VBoxContainer _production = PanelKit.Column(8);
|
||||
private readonly ChainGraph _graph = new();
|
||||
private readonly VBoxContainer _chainFooter = PanelKit.Column(8);
|
||||
private readonly VBoxContainer _plants = PanelKit.Column(8);
|
||||
private readonly VBoxContainer _controls = PanelKit.Column(8);
|
||||
private readonly VBoxContainer _details = PanelKit.Column(6);
|
||||
private readonly VBoxContainer _history = PanelKit.Column(4);
|
||||
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
/// <summary>Esito dell'offerta di acquisto, accanto al pulsante (la scheda è a tutto schermo e la mappa è nascosta).</summary>
|
||||
private readonly Label _buyStatus = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
private Button? _overhaul, _upgrade;
|
||||
private readonly List<Button> _budgetButtons = [];
|
||||
private SpinBox? _partsOrder;
|
||||
private int _industry = -1;
|
||||
@@ -33,25 +51,110 @@ public partial class IndustryPanel : VBoxContainer
|
||||
private int _entityVersion = -1, _detailVersion = -1;
|
||||
private double _request, _sinceRefresh;
|
||||
|
||||
/// <summary>«Torna alla mappa».</summary>
|
||||
public event Action? CloseRequested;
|
||||
|
||||
/// <summary>«Crea una linea verso questa industria»: strumento binari centrato sull'industria.</summary>
|
||||
public event Action<int>? PlanLineRequested;
|
||||
|
||||
public IndustryPanel(GameSession session)
|
||||
{
|
||||
_session = session;
|
||||
AddThemeConstantOverride("separation", 10);
|
||||
AddChild(UiTheme.TitleLabel(T("Industrie"), 34));
|
||||
var help = UiTheme.Text(T("Scegli un'industria nell'elenco o sulla mappa. Gli impianti si consumano con l'uso: il budget di manutenzione, i ricambi e i macchinari portati in treno li tengono in salute."), 13, Palette.TextSecondary);
|
||||
help.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
AddChild(help);
|
||||
AddChild(_list);
|
||||
AddChild(PanelKit.Separator());
|
||||
AddChild(_header);
|
||||
AddChild(_controls);
|
||||
AddChild(_details);
|
||||
AddThemeConstantOverride("separation", 14);
|
||||
SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||
|
||||
// barra di navigazione: ritorno alla mappa e scelta dell'industria
|
||||
var nav = PanelKit.Row(12);
|
||||
var back = new Button { Text = "‹ " + T("Mappa"), CustomMinimumSize = new Vector2(120, 44) };
|
||||
back.Pressed += () => CloseRequested?.Invoke();
|
||||
nav.AddChild(back);
|
||||
nav.AddChild(_chooser);
|
||||
_chooser.ItemSelected += i => Select(_ids[(int)i]);
|
||||
var hint = UiTheme.Text(T("Scheda dell'industria"), 13, Palette.TextSecondary);
|
||||
hint.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||||
nav.AddChild(hint);
|
||||
AddChild(nav);
|
||||
|
||||
// intestazione: nome, livello, proprietà, valore ed efficienza
|
||||
var header = PanelKit.Row(24);
|
||||
var titles = PanelKit.Column(2);
|
||||
titles.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
_title.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
|
||||
titles.AddChild(_title);
|
||||
titles.AddChild(_subtitle);
|
||||
_ownerLine.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
titles.AddChild(_ownerLine);
|
||||
header.AddChild(titles);
|
||||
var value = PanelKit.Column(0);
|
||||
value.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||||
var valueCaption = UiTheme.Text(T("Valore stimato"), 13, Palette.TextSecondary);
|
||||
valueCaption.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
_valuation.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
value.AddChild(valueCaption);
|
||||
value.AddChild(_valuation);
|
||||
header.AddChild(value);
|
||||
var ring = PanelKit.Column(2);
|
||||
ring.AddChild(_ring);
|
||||
// tooltip «perché» dell'efficienza con i termini dell'ultima produzione (ADR 0024)
|
||||
WhyTooltip.Attach(_ring, () => _industry >= 0 ? new ExplainTarget(ExplainSubject.IndustryEfficiency, _industry) : null);
|
||||
_limit.HorizontalAlignment = HorizontalAlignment.Center;
|
||||
_limit.CustomMinimumSize = new Vector2(150, 0);
|
||||
_limit.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
ring.AddChild(_limit);
|
||||
header.AddChild(ring);
|
||||
AddChild(header);
|
||||
AddChild(_notices);
|
||||
|
||||
// corpo scorrevole: tre schede, poi catena produttiva e impianti
|
||||
AddChild(_scroll);
|
||||
var margin = new MarginContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
margin.AddThemeConstantOverride("margin_right", 10);
|
||||
_scroll.AddChild(margin);
|
||||
var body = PanelKit.Column(18);
|
||||
margin.AddChild(body);
|
||||
|
||||
var cards = PanelKit.Row(18);
|
||||
cards.AddChild(Card(T("Materie prime in ingresso"), _inputs, 1));
|
||||
cards.AddChild(Card(T("Forza lavoro"), _workforce, 1));
|
||||
cards.AddChild(Card(T("Produzione"), _production, 1));
|
||||
body.AddChild(cards);
|
||||
|
||||
var lower = PanelKit.Row(18);
|
||||
var chain = PanelKit.Column(10);
|
||||
var legend = PanelKit.Row(16);
|
||||
foreach (var (text, color) in new[] { (T("merci su linea"), Palette.Amber), (T("lavoratori"), Palette.Workers), (T("personale"), Palette.Staff), (T("non collegato"), Palette.TextSecondary) })
|
||||
legend.AddChild(UiTheme.Text("— " + text, 12, color));
|
||||
chain.AddChild(legend);
|
||||
_graph.IndustryClicked += Select;
|
||||
chain.AddChild(_graph);
|
||||
chain.AddChild(_chainFooter);
|
||||
_buyStatus.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
chain.AddChild(_buyStatus);
|
||||
lower.AddChild(Card(T("Catena produttiva"), chain, 1.6f));
|
||||
var plants = PanelKit.Column(10);
|
||||
plants.AddChild(_plants);
|
||||
plants.AddChild(_controls);
|
||||
plants.AddChild(_history);
|
||||
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
AddChild(_status);
|
||||
_list.ItemSelected += i => Select(_ids[(int)i]);
|
||||
plants.AddChild(_status);
|
||||
lower.AddChild(Card(T("Impianti e crescita"), plants, 1));
|
||||
body.AddChild(lower);
|
||||
|
||||
RefreshList();
|
||||
}
|
||||
|
||||
/// <summary>Scheda con titolo e contenuto, larga in proporzione al rapporto dato.</summary>
|
||||
private static PanelContainer Card(string title, Control content, float ratio)
|
||||
{
|
||||
var card = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsStretchRatio = ratio };
|
||||
card.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 12, 22));
|
||||
var col = PanelKit.Column(12);
|
||||
col.AddChild(UiTheme.Text(title, 19, bold: true));
|
||||
col.AddChild(content);
|
||||
card.AddChild(col);
|
||||
return card;
|
||||
}
|
||||
|
||||
/// <summary>Industria mostrata (−1 se nessuna).</summary>
|
||||
public int Industry => _industry;
|
||||
|
||||
@@ -60,11 +163,20 @@ public partial class IndustryPanel : VBoxContainer
|
||||
if (id == _industry) return;
|
||||
_industry = id;
|
||||
_status.Text = "";
|
||||
_buyStatus.Text = "";
|
||||
_scroll.ScrollVertical = 0;
|
||||
SyncSelection();
|
||||
Request();
|
||||
Refresh();
|
||||
}
|
||||
|
||||
/// <summary>Scorre il corpo della scheda (0 in cima, 1 in fondo).</summary>
|
||||
public void ScrollTo(double fraction)
|
||||
{
|
||||
var bar = _scroll.GetVScrollBar();
|
||||
_scroll.ScrollVertical = (int)Math.Round((bar.MaxValue - bar.Page) * Math.Clamp(fraction, 0, 1));
|
||||
}
|
||||
|
||||
private void Request()
|
||||
{
|
||||
if (_industry >= 0) _session.Send(new RequestDetail { Kind = DetailKind.Industry, Target = _industry });
|
||||
@@ -84,10 +196,12 @@ public partial class IndustryPanel : VBoxContainer
|
||||
if ((w.EntityVersion != _entityVersion || w.DetailVersion != _detailVersion) && _sinceRefresh >= 0.25) Refresh();
|
||||
}
|
||||
|
||||
private void Result(CommandResultMessage r)
|
||||
private void Result(CommandResultMessage r) => Show(_status, r);
|
||||
|
||||
private void Show(Label label, CommandResultMessage r)
|
||||
{
|
||||
_status.Text = r.Message;
|
||||
_status.AddThemeColorOverride("font_color", r.Ok ? Palette.TextSecondary : Palette.Danger);
|
||||
label.Text = r.Message;
|
||||
label.AddThemeColorOverride("font_color", r.Ok ? Palette.TextSecondary : Palette.Danger);
|
||||
Request();
|
||||
}
|
||||
|
||||
@@ -98,10 +212,17 @@ public partial class IndustryPanel : VBoxContainer
|
||||
if (w.EntityVersion != _entityVersion) RefreshList();
|
||||
_entityVersion = w.EntityVersion;
|
||||
_detailVersion = w.DetailVersion;
|
||||
foreach (var c in _header.GetChildren()) c.QueueFree();
|
||||
foreach (var c in _details.GetChildren()) c.QueueFree();
|
||||
foreach (var box in new[] { _notices, _inputs, _workforce, _production, _chainFooter, _plants, _history })
|
||||
foreach (var c in box.GetChildren()) c.QueueFree();
|
||||
if (_industry < 0 || !w.Industries.TryGetValue(_industry, out var ind))
|
||||
{
|
||||
_title.Text = T("Industrie");
|
||||
_subtitle.Text = T("Scegli un'industria nell'elenco in alto.");
|
||||
_ownerLine.Text = "";
|
||||
_valuation.Text = "";
|
||||
_limit.Text = "";
|
||||
_ring.Set(0, Palette.Amber);
|
||||
_graph.Visible = false;
|
||||
BuildControls(null);
|
||||
return;
|
||||
}
|
||||
@@ -109,12 +230,24 @@ public partial class IndustryPanel : VBoxContainer
|
||||
BuildHeader(w, ind, card);
|
||||
BuildControls(ind);
|
||||
UpdateControls(ind, card);
|
||||
BuildDetails(w, ind, card);
|
||||
var sheet = card?.Sheet;
|
||||
if (card is null || sheet is null)
|
||||
{
|
||||
_graph.Visible = false;
|
||||
foreach (var box in new[] { _inputs, _workforce, _production, _plants })
|
||||
box.AddChild(UiTheme.Text(T("Scheda in arrivo dal server…"), 13, Palette.TextSecondary));
|
||||
return;
|
||||
}
|
||||
BuildInputs(w, sheet);
|
||||
BuildWorkforce(w, sheet);
|
||||
BuildProduction(w, card, sheet);
|
||||
BuildChain(w, ind, card, sheet);
|
||||
BuildPlants(w, ind, card, sheet);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ elenco
|
||||
|
||||
/// <summary>Elenco: si ricostruisce solo se cambiano le industrie o il loro ordine, altrimenti si aggiornano i testi.</summary>
|
||||
/// <summary>Selettore: si ricostruisce solo se cambiano le industrie o il loro ordine, altrimenti si aggiornano i testi.</summary>
|
||||
private void RefreshList()
|
||||
{
|
||||
var w = _session.World;
|
||||
@@ -126,7 +259,7 @@ public partial class IndustryPanel : VBoxContainer
|
||||
if (!same)
|
||||
{
|
||||
_ids.Clear();
|
||||
_list.Clear();
|
||||
_chooser.Clear();
|
||||
}
|
||||
for (int n = 0; n < ordered.Count; n++)
|
||||
{
|
||||
@@ -137,13 +270,12 @@ public partial class IndustryPanel : VBoxContainer
|
||||
if (!same)
|
||||
{
|
||||
_ids.Add(ind.Id);
|
||||
_list.AddItem(text);
|
||||
_chooser.AddItem(text, n);
|
||||
}
|
||||
else if (_list.GetItemText(n) != text)
|
||||
else if (_chooser.GetItemText(n) != text)
|
||||
{
|
||||
_list.SetItemText(n, text);
|
||||
_chooser.SetItemText(n, text);
|
||||
}
|
||||
_list.SetItemCustomFgColor(n, ind.Owner == me ? Palette.AmberLight : MaintenancePanel.ConditionColor((int)ind.Condition));
|
||||
}
|
||||
if (!same) SyncSelection();
|
||||
}
|
||||
@@ -151,175 +283,392 @@ public partial class IndustryPanel : VBoxContainer
|
||||
private void SyncSelection()
|
||||
{
|
||||
int index = _ids.IndexOf(_industry);
|
||||
if (index < 0)
|
||||
{
|
||||
_list.DeselectAll();
|
||||
return;
|
||||
}
|
||||
if (!_list.IsSelected(index)) _list.Select(index);
|
||||
_list.EnsureCurrentIsVisible();
|
||||
if (index >= 0 && _chooser.Selected != index) _chooser.Select(index);
|
||||
if (index < 0) _chooser.Select(-1);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ scheda
|
||||
// ------------------------------------------------------------------ intestazione
|
||||
|
||||
private void BuildHeader(ClientWorld w, IndustryInfo ind, IndustryCard? card)
|
||||
{
|
||||
int me = w.Summary?.CompanyId ?? 0;
|
||||
var title = UiTheme.TitleLabel(ind.Name, 30);
|
||||
title.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
_header.AddChild(title);
|
||||
var def = w.Data.Industries.FirstOrDefault(d => d.Id == ind.Type);
|
||||
_header.AddChild(UiTheme.Text($"{def?.NameIt ?? ind.Type} · {T("livello")} {ind.Level}", 14, Palette.TextSecondary));
|
||||
string owner = ind.Owner == me ? T("La tua compagnia") : ind.Owner < 0 ? T("Proprietari privati") : Fmt.Company(w, ind.Owner);
|
||||
_header.AddChild(PanelKit.Pair(T("Proprietà"), PanelKit.Value(owner)));
|
||||
var sheet = card?.Sheet;
|
||||
_title.Text = ind.Name;
|
||||
string level = sheet is null ? $"{T("Livello")} {ind.Level}" : $"{T("Livello")} {sheet.Level} {T("di")} {sheet.MaxLevel}";
|
||||
_subtitle.Text = $"{TypeName(w, ind.Type)} · {level}";
|
||||
string owner = ind.Owner == me ? T("la tua compagnia") : ind.Owner < 0 ? T("proprietari privati") : Fmt.Company(w, ind.Owner);
|
||||
string served = "";
|
||||
if (sheet is not null)
|
||||
{
|
||||
var names = sheet.ServingStations.Select(s => w.Stations.TryGetValue(s, out var st) ? st.Name : $"#{s}").Take(3).ToList();
|
||||
served = names.Count == 0
|
||||
? " · " + T("nessuna stazione la serve")
|
||||
: $" · {T("servita dalla stazione")} {string.Join(", ", names)}" +
|
||||
(sheet.ServingLine >= 0 && w.Lines.TryGetValue(sheet.ServingLine, out var line) ? $" ({T("linea")} {line.Name})" : "");
|
||||
}
|
||||
_ownerLine.Text = $"{T("Proprietà")}: {owner}{served}";
|
||||
_valuation.Text = card?.Valuation.ToString() ?? "—";
|
||||
float e = sheet?.Efficiency ?? ind.Efficiency;
|
||||
var limit = sheet is null ? IndustryLimit.None : (IndustryLimit)sheet.Limit;
|
||||
_ring.Set(e, limit is IndustryLimit.None ? Palette.Ok : e < 0.35f ? Palette.Danger : Palette.Amber);
|
||||
_limit.Text = sheet is null ? T("Efficienza") : $"{T("Efficienza")} · {LimitText(limit)}";
|
||||
|
||||
long today = Fmt.Today(w);
|
||||
if (ind.StoppedUntilDay >= today)
|
||||
_header.AddChild(UiTheme.Notice($"{StopName(ind.StopKind)}: {T("ferma fino al")} {Fmt.Date(w, ind.StoppedUntilDay)} ({ind.StoppedUntilDay - today + 1} {T("giorni")})"));
|
||||
_notices.AddChild(UiTheme.Notice($"{StopName(ind.StopKind)}: {T("ferma fino al")} {Fmt.Date(w, ind.StoppedUntilDay)} ({ind.StoppedUntilDay - today + 1} {T("giorni")})"));
|
||||
else if (ind.PendingWork != 0)
|
||||
_header.AddChild(UiTheme.Notice($"{WorkName(ind.PendingWork)}: {T("attende")} {card?.MachineryRequired ?? 0} {T("macchinari")} ({T("in scorta")} {ind.Machinery})" +
|
||||
_notices.AddChild(UiTheme.Notice($"{WorkName(ind.PendingWork)}: {T("attende")} {card?.MachineryRequired ?? 0} {T("macchinari")} ({T("in scorta")} {ind.Machinery})" +
|
||||
(ind.PendingWork == 1 ? " " + T("e personale sufficiente") : "")));
|
||||
if (ind.PartsShort)
|
||||
_header.AddChild(Wrapped(T("⚠ Ricambi esauriti: il recupero degli impianti si dimezza. Portali in treno da una fabbrica di macchinari o da un porto."), 13, Palette.Danger));
|
||||
|
||||
var stats = PanelKit.Row(8);
|
||||
stats.AddChild(PanelKit.Stat(T("Condizione"), ColoredValue($"{Fmt.Number(ind.Condition, 0)}%", MaintenancePanel.ConditionColor((int)ind.Condition))));
|
||||
stats.AddChild(PanelKit.Stat(T("Resa impianti"), PanelKit.Value(card is null ? "—" : "×" + Fmt.Number(card.ConditionMultiplier, 2))));
|
||||
stats.AddChild(PanelKit.Stat(T("Efficienza"), PanelKit.Value(Fmt.Pct(ind.Efficiency, 0))));
|
||||
_header.AddChild(stats);
|
||||
var bar = new ProgressBar { MaxValue = 100, Value = ind.Condition, ShowPercentage = false, CustomMinimumSize = new Vector2(0, 10) };
|
||||
var color = MaintenancePanel.ConditionColor((int)ind.Condition);
|
||||
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(color, color, 4, 0));
|
||||
_header.AddChild(bar);
|
||||
var m = w.Data.Balance.IndustryMaintenance;
|
||||
_header.AddChild(Wrapped($"{T("Sopra il")} {Fmt.Number(m.EfficiencyFullAbove, 0)}% {T("gli impianti rendono pieno; sotto calano fino a")} ×{Fmt.Number(m.EfficiencyAt20, 1)} {T("al 20% e si fermano più spesso.")}", 12, Palette.TextSecondary));
|
||||
_notices.AddChild(Wrapped(T("⚠ Ricambi esauriti: il recupero degli impianti si dimezza. Portali in treno da una fabbrica di macchinari o da un porto."), 13, Palette.Danger));
|
||||
}
|
||||
|
||||
/// <summary>Comandi del proprietario o dell'acquirente: si ricostruiscono solo se cambia l'industria o il proprietario.</summary>
|
||||
// ------------------------------------------------------------------ tre schede
|
||||
|
||||
private void BuildInputs(ClientWorld w, IndustrySheetInfo s)
|
||||
{
|
||||
if (s.Inputs.Count == 0)
|
||||
{
|
||||
_inputs.AddChild(Wrapped(T("Non consuma materie prime: estrae, coltiva o raccoglie da sé."), 13, Palette.TextSecondary));
|
||||
}
|
||||
foreach (var f in s.Inputs)
|
||||
{
|
||||
string unit = Unit(w, f.Good);
|
||||
_inputs.AddChild(FlowHeader(GoodName(w, f.Good), $"{Fmt.Number(f.CurrentMonth, 0)} / {Fmt.Number(f.FullMonth, 0)} {unit} {T("al mese")}"));
|
||||
_inputs.AddChild(Bar(f.FullMonth <= 0 ? 0 : f.CurrentMonth / f.FullMonth, f.Limiting ? Palette.Danger : Palette.Amber));
|
||||
string days = f.Days < 0 ? "" : $" · {T("bastano per")} {Fmt.Number(f.Days, 0)} {T("giorni")}";
|
||||
_inputs.AddChild(Wrapped($"{T("scorta")} {f.Stock} / {f.Storage} {unit}{days}", 12, f.Limiting ? Palette.Danger : Palette.TextSecondary));
|
||||
foreach (var p in f.Partners) _inputs.AddChild(PartnerLine(w, p, f.Good, unit, supplier: true));
|
||||
if (f.Partners.Count == 0) _inputs.AddChild(UiTheme.Text(T("Nessun fornitore nella regione"), 12, Palette.TextSecondary));
|
||||
_inputs.AddChild(PanelKit.Separator());
|
||||
}
|
||||
if (s.Inputs.Count > 0)
|
||||
_inputs.AddChild(PanelKit.Pair($"{T("Copertura degli ingressi")} ({s.CoverageWindowDays} {T("giorni")})", ColoredValue(Fmt.Pct(s.CovInput, 0), CoverageColor(s.CovInput))));
|
||||
}
|
||||
|
||||
private void BuildWorkforce(ClientWorld w, IndustrySheetInfo s)
|
||||
{
|
||||
WorkforceBlock(w, s.Workers, s.CovWorkers, s.CoverageWindowDays, staff: false);
|
||||
_workforce.AddChild(PanelKit.Separator());
|
||||
WorkforceBlock(w, s.Staff, s.CovStaff, s.CoverageWindowDays, staff: true);
|
||||
var limit = (IndustryLimit)s.Limit;
|
||||
if (limit is IndustryLimit.Workers or IndustryLimit.Staff)
|
||||
{
|
||||
var wf = limit == IndustryLimit.Staff ? s.Staff : s.Workers;
|
||||
string who = limit == IndustryLimit.Staff ? T("il personale qualificato") : T("i lavoratori");
|
||||
_workforce.AddChild(UiTheme.Notice($"{T("Collo di bottiglia")}: {who}. {T("Mancano")} {wf.Missing} {T("persone: portale in treno dalle città vicine.")}"));
|
||||
}
|
||||
}
|
||||
|
||||
private void WorkforceBlock(ClientWorld w, WorkforceInfo f, float coverage30, int window, bool staff)
|
||||
{
|
||||
var color = staff ? Palette.Staff : Palette.Workers;
|
||||
if (f.Jobs <= 0)
|
||||
{
|
||||
_workforce.AddChild(UiTheme.Text(staff ? T("Nessun posto per il personale") : T("Nessun posto per i lavoratori"), 13, Palette.TextSecondary));
|
||||
return;
|
||||
}
|
||||
_workforce.AddChild(FlowHeader(staff ? T("Personale qualificato") : T("Lavoratori"), $"{Fmt.Number(f.Present, 0)} / {f.Jobs} {T("presenti")}", color));
|
||||
_workforce.AddChild(Bar(f.Jobs <= 0 ? 0 : f.Present / f.Jobs, color));
|
||||
string minutes = f.AverageMinutes < 0 ? "" : $" · {T("viaggio medio")} {Fmt.Number(f.AverageMinutes, 0)} min";
|
||||
// OnSite sono i posti coperti da chi vive negli alloggi dell'industria, non i presenti
|
||||
_workforce.AddChild(Wrapped($"{T("copertura")} {window} {T("giorni")} {Fmt.Pct(coverage30, 0)} · {T("in sede")} {Fmt.Number(f.OnSite, 0)}{minutes}", 12, Palette.TextSecondary));
|
||||
if (f.Missing > 0)
|
||||
{
|
||||
string reason = EmploymentPanel.ReasonText(w, f.Reason, f.ReasonLine, staff);
|
||||
_workforce.AddChild(Wrapped($"{T("Mancano")} {f.Missing}" + (reason.Length > 0 ? " · " + reason : ""), 12, Palette.Amber));
|
||||
}
|
||||
foreach (var src in f.Sources)
|
||||
{
|
||||
string town = w.Towns.TryGetValue(src.Town, out var t) ? t.Name : $"#{src.Town}";
|
||||
string via = src.Walking ? T("a piedi") : src.Line >= 0 && w.Lines.TryGetValue(src.Line, out var line) ? line.Name : Fmt.Company(w, src.Carrier);
|
||||
string time = src.Walking || src.Minutes <= 0 ? "" : $" · {Fmt.Number(src.Minutes, 0)} min";
|
||||
_workforce.AddChild(Wrapped($"• {src.Headcount} {T("da")} {town} · {via}{time} · {Fmt.Pct(src.Coverage, 0)}", 12, color));
|
||||
}
|
||||
if (f.SourceCount > f.Sources.Count)
|
||||
_workforce.AddChild(Wrapped($"{T("e altre")} {f.SourceCount - f.Sources.Count} {T("provenienze")}", 12, Palette.TextSecondary));
|
||||
}
|
||||
|
||||
private void BuildProduction(ClientWorld w, IndustryCard card, IndustrySheetInfo s)
|
||||
{
|
||||
foreach (var f in s.Outputs)
|
||||
{
|
||||
string unit = Unit(w, f.Good);
|
||||
_production.AddChild(FlowHeader(GoodName(w, f.Good), $"{Fmt.Number(f.CurrentMonth, 0)} / {Fmt.Number(f.FullMonth, 0)} {unit} {T("al mese")}"));
|
||||
_production.AddChild(Bar(f.FullMonth <= 0 ? 0 : f.CurrentMonth / f.FullMonth, Palette.Amber));
|
||||
string full = f.Days < 0 ? "" : f.Days <= 0 ? " · " + T("magazzino pieno") : $" · {T("pieno tra")} {Fmt.Number(f.Days, 0)} {T("giorni")}";
|
||||
_production.AddChild(Wrapped($"{T("magazzino")} {f.Stock} / {f.Storage} {unit}{full}", 12, f.Days == 0 ? Palette.Danger : Palette.TextSecondary));
|
||||
foreach (var p in f.Partners) _production.AddChild(PartnerLine(w, p, f.Good, unit, supplier: false));
|
||||
if (f.Partners.Count == 0) _production.AddChild(UiTheme.Text(T("Nessun cliente nella regione"), 12, Palette.TextSecondary));
|
||||
_production.AddChild(PanelKit.Separator());
|
||||
}
|
||||
if (s.Outputs.Count == 0) _production.AddChild(UiTheme.Text(T("Nessuna produzione"), 13, Palette.TextSecondary));
|
||||
_production.AddChild(PanelKit.Pair(T("Magazzino"), PanelKit.Value($"{s.StorageDays} {T("giorni di produzione")}")));
|
||||
var sale = PanelKit.Pair(T("Prezzo di vendita"), PanelKit.Value(s.SalePrice < 0 ? "—" : Fmt.PricePrecise(s.SalePrice)));
|
||||
// le industrie vendono al prezzo globale del giorno (ADR 0004): si spiega quello
|
||||
if (s.SalePrice >= 0 && s.Outputs.Count == 1)
|
||||
{
|
||||
int good = s.Outputs[0].Good;
|
||||
WhyTooltip.Attach(sale, () => new ExplainTarget(ExplainSubject.GlobalPrice, good));
|
||||
}
|
||||
_production.AddChild(sale);
|
||||
_production.AddChild(PanelKit.Pair(T("Utile annuo stimato"), ColoredValue(s.AnnualProfit.ToString(), s.AnnualProfit.Cents < 0 ? Palette.Danger : Palette.Text)));
|
||||
_production.AddChild(PanelKit.Pair(T("Margine"), ColoredValue(Fmt.Pct(card.Margin, 0), card.Margin < 0 ? Palette.Danger : Palette.Text)));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ catena produttiva
|
||||
|
||||
private void BuildChain(ClientWorld w, IndustryInfo ind, IndustryCard card, IndustrySheetInfo s)
|
||||
{
|
||||
var left = new List<ChainNode>();
|
||||
foreach (var f in s.Inputs)
|
||||
foreach (var p in f.Partners.Take(2))
|
||||
left.Add(new ChainNode(PartnerName(w, p), $"{GoodName(w, f.Good)} · {Fmt.Number(p.MonthlyUnits, 0)} {Unit(w, f.Good)}/{T("mese")}", p.Line >= 0 ? ChainEdge.Goods : ChainEdge.Unlinked, PartnerIndustry(p)));
|
||||
foreach (var (wf, staff) in new[] { (s.Workers, false), (s.Staff, true) })
|
||||
foreach (var src in wf.Sources.Take(staff ? 1 : 2))
|
||||
left.Add(new ChainNode(w.Towns.TryGetValue(src.Town, out var t) ? t.Name : $"#{src.Town}",
|
||||
$"{src.Headcount} {(staff ? T("tecnici") : T("lavoratori"))}", staff ? ChainEdge.Staff : ChainEdge.Workers));
|
||||
var right = new List<ChainNode>();
|
||||
foreach (var f in s.Outputs)
|
||||
foreach (var p in f.Partners.Take(3))
|
||||
right.Add(new ChainNode(PartnerName(w, p), $"{GoodName(w, f.Good)} · {Fmt.PricePrecise(p.Price)}", p.Line >= 0 ? ChainEdge.Goods : ChainEdge.Unlinked, PartnerIndustry(p)));
|
||||
string outputs = string.Join(", ", s.Outputs.Select(f => GoodName(w, f.Good)));
|
||||
_graph.Set(left, new ChainNode(ind.Name, $"{T("Livello")} {s.Level} · {outputs}", ChainEdge.Goods), right);
|
||||
_graph.Visible = true;
|
||||
|
||||
// azioni della catena: linea verso l'industria e offerta di acquisto
|
||||
var actions = PanelKit.Row(10);
|
||||
var plan = UiTheme.Primary(T("Crea una linea verso questa industria"));
|
||||
plan.CustomMinimumSize = new Vector2(0, 44);
|
||||
int id = ind.Id;
|
||||
plan.Pressed += () => PlanLineRequested?.Invoke(id);
|
||||
actions.AddChild(plan);
|
||||
int me = w.Summary?.CompanyId ?? 0;
|
||||
if (ind.Owner != me)
|
||||
{
|
||||
var buy = new Button { Text = T("Fai un'offerta di acquisto"), CustomMinimumSize = new Vector2(0, 44) };
|
||||
buy.Disabled = !(s.ForSale && s.BuyUnlocked);
|
||||
buy.Pressed += () =>
|
||||
{
|
||||
_buyStatus.Text = T("Offerta inviata…");
|
||||
_buyStatus.AddThemeColorOverride("font_color", Palette.TextSecondary);
|
||||
_session.Command(new BuyIndustryCommand(new IndustryId(id), card.Valuation), r => Show(_buyStatus, r));
|
||||
};
|
||||
actions.AddChild(buy);
|
||||
}
|
||||
_chainFooter.AddChild(actions);
|
||||
if (ind.Owner == me)
|
||||
_chainFooter.AddChild(Wrapped(T("L'industria è tua: gli utili entrano nel conto economico della compagnia."), 12, Palette.TextSecondary));
|
||||
else if (ind.Owner < 0 && !s.ForSale)
|
||||
_chainFooter.AddChild(Wrapped(T("Industria inattiva: non è in vendita finché non riprende a produrre."), 12, Palette.TextSecondary));
|
||||
else if (!s.ForSale)
|
||||
_chainFooter.AddChild(UiTheme.Text($"{T("Appartiene a")} {Fmt.Company(w, ind.Owner)}: {T("non è in vendita.")}", 12, Palette.TextSecondary));
|
||||
else if (!s.BuyUnlocked)
|
||||
_chainFooter.AddChild(UiTheme.Text($"{T("Disponibile al livello")} «{Fmt.Tier(w, s.BuyTier)}» ({T("avanzamento")} {Fmt.Progress(s.BuyProgress)})", 12, Palette.TextSecondary));
|
||||
else
|
||||
_chainFooter.AddChild(UiTheme.Text($"{T("Prezzo chiesto dai proprietari")}: {card.Valuation}", 12, Palette.TextSecondary));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ impianti e crescita
|
||||
|
||||
private void BuildPlants(ClientWorld w, IndustryInfo ind, IndustryCard card, IndustrySheetInfo s)
|
||||
{
|
||||
var condColor = MaintenancePanel.ConditionColor((int)ind.Condition);
|
||||
_plants.AddChild(PanelKit.Pair(T("Condizione degli impianti"), ColoredValue($"{Fmt.Number(ind.Condition, 0)}%", condColor)));
|
||||
_plants.AddChild(Bar(ind.Condition / 100f, condColor));
|
||||
_plants.AddChild(PanelKit.Pair(T("Moltiplicatore di resa"), PanelKit.Value("×" + Fmt.Number(card.ConditionMultiplier, 2))));
|
||||
_plants.AddChild(Wrapped($"{T("usura")} −{Fmt.Number(card.WearPerDay, 3)} · {T("recupero")} +{Fmt.Number(card.RecoveryPerDay, 3)} {T("al giorno")}", 12, Palette.TextSecondary));
|
||||
_plants.AddChild(PanelKit.Pair(T("Rischio di fermo in un anno"), ColoredValue(Fmt.Pct(card.BreakdownChancePerYear, 0),
|
||||
card.BreakdownChancePerYear > 0.5f ? Palette.Danger : card.BreakdownChancePerYear > 0.1f ? Palette.Amber : Palette.Text)));
|
||||
if (s.ProfitFactor < 1) _plants.AddChild(PanelKit.Pair(T("Fattore di redditività"), PanelKit.Value("×" + Fmt.Number(s.ProfitFactor, 2))));
|
||||
if (s.ReserveFraction >= 0)
|
||||
_plants.AddChild(PanelKit.Pair(T("Giacimento residuo"), ColoredValue(Fmt.Pct(s.ReserveFraction, 0), s.Depletion < 1 ? Palette.Amber : Palette.Text)));
|
||||
if (s.EventCapacity < 1) _plants.AddChild(PanelKit.Pair(T("Capacità ridotta da un evento"), ColoredValue("×" + Fmt.Number(s.EventCapacity, 2), Palette.Amber)));
|
||||
|
||||
// crescita trimestrale: punteggio in corso, soglie, componenti
|
||||
_plants.AddChild(PanelKit.Separator());
|
||||
var scoreHeader = FlowHeader(T("Punteggio di crescita"), $"{Fmt.Number(s.Score, 2)} · {T("giorno")} {s.QuarterDay} {T("di")} {s.QuarterDays}");
|
||||
_plants.AddChild(scoreHeader);
|
||||
var bar = new ScoreBar();
|
||||
bar.Set(s.Score, s.LastScore, s.DowngradeThreshold, s.UpgradeThreshold);
|
||||
int scored = _industry;
|
||||
WhyTooltip.Attach(scoreHeader, () => new ExplainTarget(ExplainSubject.IndustryGrowth, scored));
|
||||
WhyTooltip.Attach(bar, () => new ExplainTarget(ExplainSubject.IndustryGrowth, scored));
|
||||
_plants.AddChild(bar);
|
||||
_plants.AddChild(Wrapped($"{T("sotto")} {Fmt.Number(s.DowngradeThreshold, 2)} {T("perde un livello")} · {T("sopra")} {Fmt.Number(s.UpgradeThreshold, 2)} {T("per")} {s.UpgradeQuarters} {T("trimestri sale")} ({s.QuartersAbove}/{s.UpgradeQuarters})", 12, Palette.TextSecondary));
|
||||
var g = w.Data.Balance.Growth;
|
||||
_plants.AddChild(Wrapped($"{T("spedito")} {Fmt.Pct(s.Shipped, 0)} ×{Fmt.Number(g.WeightShipped, 1)} · {T("copertura")} {Fmt.Pct(s.Coverage, 0)} ×{Fmt.Number(g.WeightCoverage, 1)} · {T("utile")} {Fmt.Pct(s.Profit, 0)} ×{Fmt.Number(g.WeightProfit, 1)}", 12, Palette.TextSecondary));
|
||||
if (s.LastScore >= 0) _plants.AddChild(UiTheme.Text($"{T("ultimo trimestre")} {Fmt.Number(s.LastScore, 2)}", 12, Palette.TextSecondary));
|
||||
if (!s.Served)
|
||||
_plants.AddChild(Wrapped(T("Nessun vettore la serve: il livello resta fermo finché una linea non la collega."), 12, Palette.Amber));
|
||||
else if (s.Level >= s.MaxLevel)
|
||||
_plants.AddChild(UiTheme.Text(T("Livello massimo raggiunto"), 12, Palette.Ok));
|
||||
|
||||
int me = w.Summary?.CompanyId ?? 0;
|
||||
if (ind.Owner == me)
|
||||
{
|
||||
_plants.AddChild(PanelKit.Separator());
|
||||
_plants.AddChild(PanelKit.Pair(T("Manutenzione al giorno"), PanelKit.Value(card.MaintenanceCostPerDay.ToString())));
|
||||
_plants.AddChild(PanelKit.Pair(T("Spesa di manutenzione nell'anno"), PanelKit.Value(card.MaintenanceSpentYear.ToString())));
|
||||
_plants.AddChild(PanelKit.Pair(T("Cassa dell'industria"), PanelKit.Value(card.Cash.ToString())));
|
||||
_plants.AddChild(PanelKit.Pair(T("Costo dell'ammodernamento"), PanelKit.Value(card.UpgradeCost.ToString())));
|
||||
_plants.AddChild(StockRow(T("Ricambi"), ind.SpareParts, card.PartsTarget + card.PartsOrdered, ind.PartsShort ? Palette.Danger : Palette.Amber));
|
||||
_plants.AddChild(Wrapped($"{T("scorta della politica")} {card.PartsTarget} · {T("ordinati in più")} {card.PartsOrdered} · {T("consumo")} {card.PartsPerMonth} {T("al mese")}", 12, Palette.TextSecondary));
|
||||
_plants.AddChild(StockRow(T("Macchinari"), ind.Machinery, card.MachineryRequired, Palette.Workers));
|
||||
}
|
||||
|
||||
_history.AddChild(PanelKit.Separator());
|
||||
_history.AddChild(UiTheme.Text(T("Storico dei fermi"), 14, bold: true));
|
||||
if (card.Stops.Count == 0) _history.AddChild(UiTheme.Text(T("Nessun fermo finora"), 13, Palette.TextSecondary));
|
||||
foreach (var stop in Enumerable.Reverse(card.Stops).Take(6))
|
||||
_history.AddChild(UiTheme.Text($"{Fmt.Date(w, stop.Day)} · {StopName(stop.Kind)} · {stop.Days} {T("giorni")}", 13, stop.Kind is 1 or 2 ? Palette.Amber : Palette.TextSecondary));
|
||||
}
|
||||
|
||||
/// <summary>Comandi del proprietario: si ricostruiscono solo se cambia l'industria o il proprietario.</summary>
|
||||
private void BuildControls(IndustryInfo? ind)
|
||||
{
|
||||
var key = ind is null ? (-1, -1) : (ind.Id, ind.Owner);
|
||||
int me = _session.World.Summary?.CompanyId ?? 0;
|
||||
var key = ind is null || ind.Owner != me ? (-1, -1) : (ind.Id, ind.Owner);
|
||||
if (key == _controlsKey) return;
|
||||
_controlsKey = key;
|
||||
foreach (var c in _controls.GetChildren()) c.QueueFree();
|
||||
_budgetButtons.Clear();
|
||||
_partsOrder = null;
|
||||
if (ind is null) return;
|
||||
_overhaul = _upgrade = null;
|
||||
if (ind is null || ind.Owner != me) return;
|
||||
var w = _session.World;
|
||||
int me = w.Summary?.CompanyId ?? 0;
|
||||
int id = ind.Id;
|
||||
if (ind.Owner == me)
|
||||
_controls.AddChild(PanelKit.Separator());
|
||||
_controls.AddChild(UiTheme.Text(T("Budget di manutenzione"), 14, bold: true));
|
||||
var row = PanelKit.Row(6);
|
||||
var group = new ButtonGroup();
|
||||
foreach (var (budget, label) in new[] { (IndustryBudget.None, T("Nessuno")), (IndustryBudget.Base, T("Base")), (IndustryBudget.High, T("Alto")) })
|
||||
{
|
||||
_controls.AddChild(UiTheme.Text(T("Budget di manutenzione"), 14, bold: true));
|
||||
var row = PanelKit.Row(6);
|
||||
var group = new ButtonGroup();
|
||||
foreach (var (budget, label) in new[] { (IndustryBudget.None, T("Nessuno")), (IndustryBudget.Base, T("Base")), (IndustryBudget.High, T("Alto")) })
|
||||
{
|
||||
var p = w.Data.Balance.IndustryMaintenance.For(budget);
|
||||
var b = new Button { Text = label, ToggleMode = true, ButtonGroup = group, SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
b.TooltipText = $"{T("Recupero")} {Fmt.Number(p.RecoveryPerDay, 2)} {T("punti al giorno")} · {Fmt.Pct(p.CostShareOfRevenue, 0)} {T("dei ricavi")} · {p.SparePartsPerLevelPerMonth} {T("ricambi al mese per livello")}";
|
||||
b.Pressed += () => _session.Command(new SetIndustryPolicyCommand(new IndustryId(id), budget), Result);
|
||||
_budgetButtons.Add(b);
|
||||
row.AddChild(b);
|
||||
}
|
||||
_controls.AddChild(row);
|
||||
var p = w.Data.Balance.IndustryMaintenance.For(budget);
|
||||
var b = new Button { Text = label, ToggleMode = true, ButtonGroup = group, SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
b.TooltipText = $"{T("Recupero")} {Fmt.Number(p.RecoveryPerDay, 2)} {T("punti al giorno")} · {Fmt.Pct(p.CostShareOfRevenue, 0)} {T("dei ricavi")} · {p.SparePartsPerLevelPerMonth} {T("ricambi al mese per livello")}";
|
||||
b.Pressed += () => _session.Command(new SetIndustryPolicyCommand(new IndustryId(id), budget), Result);
|
||||
_budgetButtons.Add(b);
|
||||
row.AddChild(b);
|
||||
}
|
||||
_controls.AddChild(row);
|
||||
|
||||
var order = PanelKit.Row(6);
|
||||
var caption = UiTheme.Text(T("Ricambi extra"), 13, Palette.TextSecondary);
|
||||
caption.TooltipText = T("Ricambi da ordinare oltre la scorta della politica: diventano domanda esplicita sulle tue linee.");
|
||||
caption.MouseFilter = MouseFilterEnum.Pass;
|
||||
order.AddChild(caption);
|
||||
_partsOrder = new SpinBox { MinValue = 0, MaxValue = w.Data.Balance.IndustryMaintenance.MaxOrderedParts, SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
order.AddChild(_partsOrder);
|
||||
var orderButton = new Button { Text = T("Ordina ricambi") };
|
||||
orderButton.Pressed += () => _session.Command(new OrderPartsCommand(DepotId.None, (int)(_partsOrder?.Value ?? 0)) { Industry = new IndustryId(id) }, Result);
|
||||
order.AddChild(orderButton);
|
||||
_controls.AddChild(order);
|
||||
var order = PanelKit.Row(6);
|
||||
var caption = UiTheme.Text(T("Ricambi extra"), 13, Palette.TextSecondary);
|
||||
caption.TooltipText = T("Ricambi da ordinare oltre la scorta della politica: diventano domanda esplicita sulle tue linee.");
|
||||
caption.MouseFilter = MouseFilterEnum.Pass;
|
||||
order.AddChild(caption);
|
||||
_partsOrder = new SpinBox { MinValue = 0, MaxValue = w.Data.Balance.IndustryMaintenance.MaxOrderedParts, SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
order.AddChild(_partsOrder);
|
||||
var orderButton = new Button { Text = T("Ordina ricambi") };
|
||||
orderButton.Pressed += () => _session.Command(new OrderPartsCommand(DepotId.None, (int)(_partsOrder?.Value ?? 0)) { Industry = new IndustryId(id) }, Result);
|
||||
order.AddChild(orderButton);
|
||||
_controls.AddChild(order);
|
||||
|
||||
var actions = PanelKit.Row(6);
|
||||
var m = w.Data.Balance.IndustryMaintenance;
|
||||
var overhaul = new Button { Text = T("Fermo programmato"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
overhaul.TooltipText = $"{T("Revisione")}: {m.OverhaulDays} {T("giorni di fermo")}, {m.OverhaulMachineryPerLevel} {T("macchinari per livello")}, {T("personale almeno al")} {Fmt.Pct(m.OverhaulMinStaffCoverage, 0)}; {T("riporta la condizione a 100.")}";
|
||||
overhaul.Pressed += () => _session.Command(new OverhaulIndustryCommand(new IndustryId(id)), Result);
|
||||
actions.AddChild(overhaul);
|
||||
var upgrade = UiTheme.Primary(T("Ammoderna"));
|
||||
upgrade.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
upgrade.TooltipText = $"{T("Ammodernamento di livello")}: {m.UpgradeDays} {T("giorni di fermo")}, {m.UpgradeMachineryPerLevel} {T("macchinari per livello")}";
|
||||
upgrade.Pressed += () => _session.Command(new UpgradeIndustryCommand(new IndustryId(id)), Result);
|
||||
actions.AddChild(upgrade);
|
||||
_controls.AddChild(actions);
|
||||
}
|
||||
else if (ind.Owner < 0)
|
||||
{
|
||||
_controls.AddChild(UiTheme.Text(T("In vendita"), 14, bold: true));
|
||||
var price = PanelKit.Value("—");
|
||||
price.Name = "Price";
|
||||
_controls.AddChild(PanelKit.Pair(T("Prezzo chiesto dai proprietari"), price));
|
||||
var buy = UiTheme.Primary(T("Acquista"));
|
||||
buy.Pressed += () =>
|
||||
{
|
||||
if (_session.World.IndustryCards.TryGetValue(id, out var c))
|
||||
_session.Command(new BuyIndustryCommand(new IndustryId(id), c.Valuation), Result);
|
||||
else
|
||||
Request();
|
||||
};
|
||||
_controls.AddChild(buy);
|
||||
if (Fmt.UnlockTier(w, u => u.BuyIndustry) is { } tier)
|
||||
_controls.AddChild(Wrapped($"{T("L'acquisto di industrie si sblocca al livello")} «{Fmt.Tier(w, tier)}».", 12, Palette.TextSecondary));
|
||||
}
|
||||
else
|
||||
{
|
||||
_controls.AddChild(Wrapped($"{T("Appartiene a")} {Fmt.Company(w, ind.Owner)}: {T("non è in vendita.")}", 13, Palette.TextSecondary));
|
||||
}
|
||||
var actions = PanelKit.Row(6);
|
||||
var m = w.Data.Balance.IndustryMaintenance;
|
||||
var overhaul = new Button { Text = T("Fermo programmato"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
overhaul.TooltipText = $"{T("Revisione")}: {m.OverhaulDays} {T("giorni di fermo")}, {m.OverhaulMachineryPerLevel} {T("macchinari per livello")}, {T("personale almeno al")} {Fmt.Pct(m.OverhaulMinStaffCoverage, 0)}; {T("riporta la condizione a 100.")}";
|
||||
overhaul.Pressed += () => _session.Command(new OverhaulIndustryCommand(new IndustryId(id)), Result);
|
||||
overhaul.SetMeta(BaseTooltip, overhaul.TooltipText);
|
||||
actions.AddChild(overhaul);
|
||||
_overhaul = overhaul;
|
||||
var upgrade = UiTheme.Primary(T("Ammoderna"));
|
||||
upgrade.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
upgrade.TooltipText = $"{T("Ammodernamento di livello")}: {m.UpgradeDays} {T("giorni di fermo")}, {m.UpgradeMachineryPerLevel} {T("macchinari per livello")}";
|
||||
upgrade.Pressed += () => _session.Command(new UpgradeIndustryCommand(new IndustryId(id)), Result);
|
||||
upgrade.SetMeta(BaseTooltip, upgrade.TooltipText);
|
||||
actions.AddChild(upgrade);
|
||||
_upgrade = upgrade;
|
||||
_controls.AddChild(actions);
|
||||
}
|
||||
|
||||
private void UpdateControls(IndustryInfo ind, IndustryCard? card)
|
||||
{
|
||||
for (int i = 0; i < _budgetButtons.Count; i++) _budgetButtons[i].SetPressedNoSignal(i == ind.Budget);
|
||||
if (_partsOrder is not null && card is not null && !_partsOrder.GetLineEdit().HasFocus()) _partsOrder.SetValueNoSignal(card.PartsOrdered);
|
||||
if (_controls.FindChild("Price", true, false) is Label price) price.Text = card?.Valuation.ToString() ?? "—";
|
||||
|
||||
// revisione e ammodernamento: il server li rifiuta durante un fermo, con un lavoro già in
|
||||
// programma o (l'ammodernamento) al livello massimo; il pulsante lo dice prima
|
||||
string busy = ind.StoppedUntilDay >= Fmt.Today(_session.World) ? T("L'industria è ferma: riprova a fermo finito.")
|
||||
: ind.PendingWork != 0 ? T("C'è già un lavoro in programma.") : "";
|
||||
var sheet = card?.Sheet;
|
||||
string top = sheet is not null && sheet.Level >= sheet.MaxLevel ? T("Livello massimo raggiunto") : "";
|
||||
Gate(_overhaul, busy);
|
||||
Gate(_upgrade, busy.Length > 0 ? busy : top);
|
||||
}
|
||||
|
||||
private void BuildDetails(ClientWorld w, IndustryInfo ind, IndustryCard? card)
|
||||
private const string BaseTooltip = "base_tooltip";
|
||||
|
||||
/// <summary>Abilita il pulsante, o lo disabilita con il motivo in testa al suggerimento.</summary>
|
||||
private static void Gate(Button? button, string reason)
|
||||
{
|
||||
if (card is null)
|
||||
{
|
||||
_details.AddChild(UiTheme.Text(T("Scheda in arrivo dal server…"), 13, Palette.TextSecondary));
|
||||
return;
|
||||
}
|
||||
int me = w.Summary?.CompanyId ?? 0;
|
||||
_details.AddChild(UiTheme.Text(T("Impianti"), 14, bold: true));
|
||||
_details.AddChild(PanelKit.Pair(T("Usura al giorno"), PanelKit.Value("−" + Fmt.Number(card.WearPerDay, 3))));
|
||||
_details.AddChild(PanelKit.Pair(T("Recupero al giorno"), PanelKit.Value("+" + Fmt.Number(card.RecoveryPerDay, 3))));
|
||||
_details.AddChild(PanelKit.Pair(T("Rischio di fermo in un anno"), ColoredValue(Fmt.Pct(card.BreakdownChancePerYear, 0),
|
||||
card.BreakdownChancePerYear > 0.5f ? Palette.Danger : card.BreakdownChancePerYear > 0.1f ? Palette.Amber : Palette.Text)));
|
||||
_details.AddChild(PanelKit.Pair(T("Margine"), ColoredValue(Fmt.Pct(card.Margin, 0), card.Margin < 0 ? Palette.Danger : Palette.Text)));
|
||||
|
||||
if (ind.Owner == me)
|
||||
{
|
||||
_details.AddChild(PanelKit.Pair(T("Manutenzione al giorno"), PanelKit.Value(card.MaintenanceCostPerDay.ToString())));
|
||||
_details.AddChild(PanelKit.Pair(T("Spesa di manutenzione nell'anno"), PanelKit.Value(card.MaintenanceSpentYear.ToString())));
|
||||
_details.AddChild(PanelKit.Pair(T("Cassa dell'industria"), PanelKit.Value(card.Cash.ToString())));
|
||||
_details.AddChild(PanelKit.Pair(T("Costo dell'ammodernamento"), PanelKit.Value(card.UpgradeCost.ToString())));
|
||||
}
|
||||
|
||||
_details.AddChild(PanelKit.Separator());
|
||||
_details.AddChild(UiTheme.Text(T("Scorte"), 14, bold: true));
|
||||
_details.AddChild(StockRow(T("Ricambi"), ind.SpareParts, card.PartsTarget + card.PartsOrdered, ind.PartsShort ? Palette.Danger : Palette.Amber));
|
||||
_details.AddChild(UiTheme.Text($"{T("scorta della politica")} {card.PartsTarget} · {T("ordinati in più")} {card.PartsOrdered} · {T("consumo")} {card.PartsPerMonth} {T("al mese")}", 12, Palette.TextSecondary));
|
||||
_details.AddChild(StockRow(T("Macchinari"), ind.Machinery, card.MachineryRequired, Palette.Workers));
|
||||
_details.AddChild(UiTheme.Text($"{T("servono")} {card.MachineryRequired} {T("macchinari per il prossimo lavoro")}", 12, Palette.TextSecondary));
|
||||
|
||||
_details.AddChild(PanelKit.Separator());
|
||||
_details.AddChild(UiTheme.Text(T("Storico dei fermi"), 14, bold: true));
|
||||
if (card.Stops.Count == 0) _details.AddChild(UiTheme.Text(T("Nessun fermo finora"), 13, Palette.TextSecondary));
|
||||
foreach (var s in Enumerable.Reverse(card.Stops).Take(8))
|
||||
{
|
||||
var l = UiTheme.Text($"{Fmt.Date(w, s.Day)} · {StopName(s.Kind)} · {s.Days} {T("giorni")}", 13, s.Kind is 1 or 2 ? Palette.Amber : Palette.TextSecondary);
|
||||
_details.AddChild(l);
|
||||
}
|
||||
if (button is null) return;
|
||||
button.Disabled = reason.Length > 0;
|
||||
string tip = button.GetMeta(BaseTooltip, "").AsString();
|
||||
button.TooltipText = reason.Length > 0 ? reason + "\n" + tip : tip;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ pezzi
|
||||
|
||||
private static HBoxContainer FlowHeader(string name, string value, Color? color = null)
|
||||
{
|
||||
var row = PanelKit.Row(8);
|
||||
var l = UiTheme.Text(name, 15, color, bold: true);
|
||||
l.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
row.AddChild(l);
|
||||
row.AddChild(UiTheme.Text(value, 14, bold: true));
|
||||
return row;
|
||||
}
|
||||
|
||||
private static ProgressBar Bar(float fraction, Color color)
|
||||
{
|
||||
var bar = new ProgressBar { MaxValue = 1, Step = 0.001, Value = Math.Clamp(fraction, 0, 1), ShowPercentage = false, CustomMinimumSize = new Vector2(0, 10) };
|
||||
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(color, color, 4, 0));
|
||||
return bar;
|
||||
}
|
||||
|
||||
private static Control PartnerLine(ClientWorld w, ChainPartnerInfo p, int good, string unit, bool supplier)
|
||||
{
|
||||
string link = p.Line >= 0 && w.Lines.TryGetValue(p.Line, out var line)
|
||||
? $"{T("linea")} {line.Name}"
|
||||
: $"{T("non collegata")} · {Fmt.Number(p.DistanceKm, 1)} km";
|
||||
string amount = (ChainPartnerKind)p.Kind == ChainPartnerKind.Hub ? "" : $" · {Fmt.Number(p.MonthlyUnits, 0)} {unit}/{T("mese")}";
|
||||
string text = $"{(supplier ? "←" : "→")} {PartnerName(w, p)}{amount} · {Fmt.PricePrecise(p.Price)} · {link}";
|
||||
var label = Wrapped(text, 12, p.Line >= 0 ? Palette.AmberLight : Palette.TextSecondary);
|
||||
// prezzo del partner spiegato dal server: locale per le industrie che comprano, globale per chi vende e per
|
||||
// le città; quello degli hub è il prezzo mondiale con il dazio, senza spiegazione
|
||||
var kind = (ChainPartnerKind)p.Kind;
|
||||
int target = p.Target;
|
||||
if (kind == ChainPartnerKind.Industry && !supplier) WhyTooltip.Attach(label, () => new ExplainTarget(ExplainSubject.LocalPrice, good, target));
|
||||
else if (kind != ChainPartnerKind.Hub) WhyTooltip.Attach(label, () => new ExplainTarget(ExplainSubject.GlobalPrice, good));
|
||||
return label;
|
||||
}
|
||||
|
||||
private static string PartnerName(ClientWorld w, ChainPartnerInfo p) => (ChainPartnerKind)p.Kind switch
|
||||
{
|
||||
ChainPartnerKind.Industry => w.Industries.TryGetValue(p.Target, out var i) ? i.Name : $"#{p.Target}",
|
||||
ChainPartnerKind.Hub => w.Hubs.TryGetValue(p.Target, out var h) ? h.Name : $"#{p.Target}",
|
||||
_ => w.Towns.TryGetValue(p.Target, out var t) ? t.Name : $"#{p.Target}",
|
||||
};
|
||||
|
||||
private static int PartnerIndustry(ChainPartnerInfo p) => (ChainPartnerKind)p.Kind == ChainPartnerKind.Industry ? p.Target : -1;
|
||||
|
||||
private static bool English => TranslationServer.GetLocale().StartsWith("en");
|
||||
|
||||
private static string GoodName(ClientWorld w, int good) =>
|
||||
good >= 0 && good < w.Data.Goods.Count ? (English ? w.Data.Goods[good].NameEn : w.Data.Goods[good].NameIt) : $"#{good}";
|
||||
|
||||
private static string Unit(ClientWorld w, int good) => good >= 0 && good < w.Data.Goods.Count ? w.Data.Goods[good].Unit : "";
|
||||
|
||||
private static string TypeName(ClientWorld w, string type)
|
||||
{
|
||||
var def = w.Data.Industries.FirstOrDefault(d => d.Id == type);
|
||||
return def is null ? type : English ? def.NameEn : def.NameIt;
|
||||
}
|
||||
|
||||
private static Color CoverageColor(float coverage) => coverage >= 0.9f ? Palette.Ok : coverage >= 0.5f ? Palette.Amber : Palette.Danger;
|
||||
|
||||
private static Control StockRow(string caption, int have, int target, Color color)
|
||||
{
|
||||
var row = PanelKit.Row(8);
|
||||
@@ -335,6 +684,21 @@ public partial class IndustryPanel : VBoxContainer
|
||||
|
||||
// ------------------------------------------------------------------ testi
|
||||
|
||||
/// <summary>Fattore che limita l'efficienza (IndustryLimit) nella lingua dell'interfaccia.</summary>
|
||||
public static string LimitText(IndustryLimit limit) => limit switch
|
||||
{
|
||||
IndustryLimit.None => T("a piena capacità"),
|
||||
IndustryLimit.Inputs => T("limitata dalle materie prime"),
|
||||
IndustryLimit.Workers => T("limitata dai lavoratori"),
|
||||
IndustryLimit.Staff => T("limitata dal personale"),
|
||||
IndustryLimit.Profit => T("limitata dalla redditività"),
|
||||
IndustryLimit.Condition => T("limitata dagli impianti"),
|
||||
IndustryLimit.Depletion => T("limitata dal giacimento"),
|
||||
IndustryLimit.Event => T("limitata da un evento"),
|
||||
IndustryLimit.Stopped => T("ferma"),
|
||||
_ => T("inattiva"),
|
||||
};
|
||||
|
||||
public static string StopName(byte kind) => kind switch
|
||||
{
|
||||
1 => T("Guasto"),
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
|
||||
namespace RailEnterprise.Client.Panels;
|
||||
|
||||
/// <summary>Anello dell'efficienza (immagine 07, in alto a destra): arco ambra sulla percentuale.</summary>
|
||||
public partial class EfficiencyRing : Control
|
||||
{
|
||||
private float _value;
|
||||
private Color _color = Palette.Amber;
|
||||
|
||||
public EfficiencyRing() => CustomMinimumSize = new Vector2(112, 112);
|
||||
|
||||
public void Set(float value, Color color)
|
||||
{
|
||||
_value = Math.Clamp(value, 0, 1);
|
||||
_color = color;
|
||||
QueueRedraw();
|
||||
}
|
||||
|
||||
public override void _Draw()
|
||||
{
|
||||
var c = Size / 2;
|
||||
float r = Math.Min(Size.X, Size.Y) / 2 - 8;
|
||||
DrawArc(c, r, 0, Mathf.Tau, 64, Palette.Inner, 10, true);
|
||||
if (_value > 0) DrawArc(c, r, -Mathf.Pi / 2, -Mathf.Pi / 2 + Mathf.Tau * _value, 64, _color, 10, true);
|
||||
string text = Fmt.Pct(_value, 0);
|
||||
var font = UiTheme.BodyBold;
|
||||
const int size = 24;
|
||||
var s = font.GetStringSize(text, HorizontalAlignment.Left, -1, size);
|
||||
DrawString(font, new Vector2(c.X - s.X / 2, c.Y + s.Y / 4), text, HorizontalAlignment.Left, -1, size, Palette.Text);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Barra del punteggio di crescita: il riempimento è il punteggio del trimestre in corso, le tacche
|
||||
/// sono le soglie di declassamento (rossa) e di promozione (verde), la lineetta l'ultimo trimestre.
|
||||
/// </summary>
|
||||
public partial class ScoreBar : Control
|
||||
{
|
||||
private float _score, _last = -1, _down, _up;
|
||||
|
||||
public ScoreBar() => CustomMinimumSize = new Vector2(0, 26);
|
||||
|
||||
public void Set(float score, float last, float down, float up)
|
||||
{
|
||||
(_score, _last, _down, _up) = (Math.Clamp(score, 0, 1), last, down, up);
|
||||
QueueRedraw();
|
||||
}
|
||||
|
||||
public override void _Draw()
|
||||
{
|
||||
float h = 12, y = 7, w = Size.X;
|
||||
DrawRect(new Rect2(0, y, w, h), Palette.Inner);
|
||||
var fill = _score >= _up ? Palette.Ok : _score < _down ? Palette.Danger : Palette.Amber;
|
||||
DrawRect(new Rect2(0, y, w * _score, h), fill);
|
||||
DrawLine(new Vector2(w * _down, 2), new Vector2(w * _down, y + h + 5), Palette.Danger, 2);
|
||||
DrawLine(new Vector2(w * _up, 2), new Vector2(w * _up, y + h + 5), Palette.Ok, 2);
|
||||
if (_last >= 0) DrawLine(new Vector2(w * Math.Clamp(_last, 0, 1), y - 3), new Vector2(w * Math.Clamp(_last, 0, 1), y + h + 3), Palette.Text, 2);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Come si disegna un collegamento della catena produttiva (legenda dell'immagine 07).</summary>
|
||||
public enum ChainEdge
|
||||
{
|
||||
/// <summary>Merci su una linea della compagnia: linea piena ambra.</summary>
|
||||
Goods,
|
||||
/// <summary>Lavoratori pendolari: tratteggio blu.</summary>
|
||||
Workers,
|
||||
/// <summary>Personale qualificato: puntinato azzurro.</summary>
|
||||
Staff,
|
||||
/// <summary>Partner possibile ma non collegato: tratteggio grigio.</summary>
|
||||
Unlinked,
|
||||
}
|
||||
|
||||
/// <summary>Nodo del grafo: titolo, riga secondaria, stile del collegamento, industria da aprire (−1 se nessuna).</summary>
|
||||
public sealed record ChainNode(string Title, string Subtitle, ChainEdge Edge, int Industry = -1);
|
||||
|
||||
/// <summary>
|
||||
/// Grafo della catena produttiva: fornitori e città dei pendolari a sinistra, l'industria al centro,
|
||||
/// clienti a destra. I nodi delle industrie si aprono con un clic.
|
||||
/// </summary>
|
||||
public partial class ChainGraph : Control
|
||||
{
|
||||
private const float NodeW = 210, NodeH = 50, Gap = 10;
|
||||
private readonly List<(Rect2 Rect, ChainNode Node)> _hits = [];
|
||||
private List<ChainNode> _left = [], _right = [];
|
||||
private ChainNode? _center;
|
||||
|
||||
public event Action<int>? IndustryClicked;
|
||||
|
||||
public ChainGraph()
|
||||
{
|
||||
CustomMinimumSize = new Vector2(0, 260);
|
||||
MouseFilter = MouseFilterEnum.Stop;
|
||||
}
|
||||
|
||||
public void Set(List<ChainNode> left, ChainNode center, List<ChainNode> right)
|
||||
{
|
||||
(_left, _center, _right) = (left, center, right);
|
||||
int rows = Math.Max(3, Math.Max(left.Count, right.Count));
|
||||
CustomMinimumSize = new Vector2(0, rows * (NodeH + Gap) + 10);
|
||||
QueueRedraw();
|
||||
}
|
||||
|
||||
public override void _Draw()
|
||||
{
|
||||
_hits.Clear();
|
||||
if (_center is null) return;
|
||||
float w = Size.X, h = Size.Y;
|
||||
float nodeW = Math.Min(NodeW, (w - 80) / 3);
|
||||
var centerRect = new Rect2(w / 2 - nodeW / 2, h / 2 - NodeH * 0.7f, nodeW, NodeH * 1.4f);
|
||||
var leftRects = Column(_left, 0, nodeW, h);
|
||||
var rightRects = Column(_right, w - nodeW, nodeW, h);
|
||||
for (int i = 0; i < _left.Count; i++)
|
||||
Edge(new Vector2(leftRects[i].End.X, leftRects[i].GetCenter().Y), new Vector2(centerRect.Position.X, centerRect.GetCenter().Y), _left[i].Edge);
|
||||
for (int i = 0; i < _right.Count; i++)
|
||||
Edge(new Vector2(centerRect.End.X, centerRect.GetCenter().Y), new Vector2(rightRects[i].Position.X, rightRects[i].GetCenter().Y), _right[i].Edge);
|
||||
for (int i = 0; i < _left.Count; i++) Node(leftRects[i], _left[i], false);
|
||||
for (int i = 0; i < _right.Count; i++) Node(rightRects[i], _right[i], false);
|
||||
Node(centerRect, _center, true);
|
||||
}
|
||||
|
||||
private static List<Rect2> Column(List<ChainNode> nodes, float x, float width, float height)
|
||||
{
|
||||
float total = nodes.Count * NodeH + Math.Max(0, nodes.Count - 1) * Gap;
|
||||
float y = (height - total) / 2;
|
||||
var rects = new List<Rect2>(nodes.Count);
|
||||
foreach (var _ in nodes)
|
||||
{
|
||||
rects.Add(new Rect2(x, y, width, NodeH));
|
||||
y += NodeH + Gap;
|
||||
}
|
||||
return rects;
|
||||
}
|
||||
|
||||
private void Edge(Vector2 from, Vector2 to, ChainEdge edge)
|
||||
{
|
||||
switch (edge)
|
||||
{
|
||||
case ChainEdge.Goods:
|
||||
DrawLine(from, to, Palette.Amber, 3, true);
|
||||
break;
|
||||
case ChainEdge.Workers:
|
||||
DrawDashedLine(from, to, Palette.Workers, 2.5f, 10);
|
||||
break;
|
||||
case ChainEdge.Staff:
|
||||
DrawDashedLine(from, to, Palette.Staff, 2.5f, 3);
|
||||
break;
|
||||
default:
|
||||
// grigio leggibile sul fondo della scheda (il bordo dei pannelli sparirebbe)
|
||||
DrawDashedLine(from, to, Palette.TextSecondary, 2, 8);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void Node(Rect2 rect, ChainNode node, bool center)
|
||||
{
|
||||
bool unlinked = !center && node.Edge == ChainEdge.Unlinked;
|
||||
var border = center ? Palette.Amber : node.Edge switch
|
||||
{
|
||||
ChainEdge.Goods => Palette.AmberDark,
|
||||
ChainEdge.Workers => Palette.Workers,
|
||||
ChainEdge.Staff => Palette.Staff,
|
||||
_ => Palette.Inner,
|
||||
};
|
||||
DrawStyleBox(UiTheme.Box(center ? Palette.AmberDark : Palette.Inner, border, 8, 0), rect);
|
||||
// partner non collegato: bordo tratteggiato grigio, come «Opportunità non collegata» nell'immagine 07
|
||||
if (unlinked) DashedRect(rect.Grow(-1), Palette.TextSecondary);
|
||||
var font = UiTheme.BodyBold;
|
||||
float width = rect.Size.X - 16;
|
||||
DrawString(font, rect.Position + new Vector2(8, center ? 26 : 20), node.Title, HorizontalAlignment.Left, width, center ? 16 : 14,
|
||||
center ? Palette.AmberLight : Palette.Text);
|
||||
DrawString(UiTheme.Body, rect.Position + new Vector2(8, center ? 48 : 39), node.Subtitle, HorizontalAlignment.Left, width, 12, Palette.TextSecondary);
|
||||
if (node.Industry >= 0) _hits.Add((rect, node));
|
||||
}
|
||||
|
||||
private void DashedRect(Rect2 r, Color color)
|
||||
{
|
||||
var (a, b, c, d) = (r.Position, new Vector2(r.End.X, r.Position.Y), r.End, new Vector2(r.Position.X, r.End.Y));
|
||||
DrawDashedLine(a, b, color, 1.5f, 6);
|
||||
DrawDashedLine(b, c, color, 1.5f, 6);
|
||||
DrawDashedLine(c, d, color, 1.5f, 6);
|
||||
DrawDashedLine(d, a, color, 1.5f, 6);
|
||||
}
|
||||
|
||||
public override void _GuiInput(InputEvent e)
|
||||
{
|
||||
if (e is not InputEventMouseButton { Pressed: true, ButtonIndex: MouseButton.Left } click) return;
|
||||
foreach (var (rect, node) in _hits)
|
||||
{
|
||||
if (!rect.HasPoint(click.Position)) continue;
|
||||
IndustryClicked?.Invoke(node.Industry);
|
||||
AcceptEvent();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,9 @@ public partial class LinesPanel : VBoxContainer
|
||||
|
||||
public event Action? StopsChanged;
|
||||
|
||||
/// <summary>Pulsante «Crea linea» (per l'evidenziazione del tutorial).</summary>
|
||||
public Control? CreateButton { get; }
|
||||
|
||||
public LinesPanel(GameSession session)
|
||||
{
|
||||
_session = session;
|
||||
@@ -54,6 +57,7 @@ public partial class LinesPanel : VBoxContainer
|
||||
RefreshStops();
|
||||
};
|
||||
row.AddChild(create);
|
||||
CreateButton = create;
|
||||
row.AddChild(clear);
|
||||
AddChild(row);
|
||||
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
|
||||
@@ -3,15 +3,19 @@ using RailEnterprise.Client.App;
|
||||
using RailEnterprise.Client.Net;
|
||||
using RailEnterprise.Core.Commands;
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
using ExplainSubject = RailEnterprise.Core.Economy.ExplainSubject;
|
||||
using ExplainTarget = RailEnterprise.Core.Economy.ExplainTarget;
|
||||
|
||||
namespace RailEnterprise.Client.Panels;
|
||||
|
||||
/// <summary>
|
||||
/// Officine (sezione 10.3): politica della flotta, avvisi, flotta ordinata per condizione con la
|
||||
/// mappa di calore, cartella di manutenzione del treno scelto, depositi con il Registro officina e
|
||||
/// la scorta di ricambi. Le cartelle e i registri arrivano su richiesta dal server.
|
||||
/// la scorta di ricambi, rinnovo della flotta (ere e obsolescenza, ADR 0020). Le cartelle, i registri
|
||||
/// e il quadro della flotta arrivano su richiesta dal server: età, successori e valori non si calcolano qui.
|
||||
/// </summary>
|
||||
public partial class MaintenancePanel : VBoxContainer
|
||||
{
|
||||
@@ -29,12 +33,19 @@ public partial class MaintenancePanel : VBoxContainer
|
||||
private readonly VBoxContainer _workshop = PanelKit.Column(8);
|
||||
private readonly VBoxContainer _workshopDetails = PanelKit.Column(6);
|
||||
private readonly HBoxContainer _orderRow = PanelKit.Row();
|
||||
private readonly VBoxContainer _fleet = PanelKit.Column(6);
|
||||
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
private readonly List<int> _trainIds = [];
|
||||
private readonly List<int> _depotIds = [];
|
||||
private int _train = -1, _depot = -1;
|
||||
private int _entityVersion = -1, _detailVersion = -1;
|
||||
private double _request;
|
||||
private long _fleetDay = long.MinValue;
|
||||
private double _sinceFleet = double.MaxValue;
|
||||
// quadro della flotta mostrato: la sezione si ricostruisce solo quando ne arriva uno nuovo, così i
|
||||
// pulsanti «Rinnova» non si ricreano sotto il cursore a ogni aggiornamento della cartella
|
||||
private FleetReport? _fleetShown;
|
||||
private bool _fleetBuilt;
|
||||
private bool _updating;
|
||||
|
||||
public event Action<bool>? HeatMapToggled;
|
||||
@@ -69,6 +80,9 @@ public partial class MaintenancePanel : VBoxContainer
|
||||
AddChild(_workshop);
|
||||
AddChild(_workshopDetails);
|
||||
AddChild(_orderRow);
|
||||
AddChild(PanelKit.Separator());
|
||||
AddChild(UiTheme.Text(T("Rinnovo della flotta"), 14, bold: true));
|
||||
AddChild(_fleet);
|
||||
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
AddChild(_status);
|
||||
|
||||
@@ -113,10 +127,26 @@ public partial class MaintenancePanel : VBoxContainer
|
||||
if (_depot >= 0) _session.Send(new RequestDetail { Kind = DetailKind.Workshop, Target = _depot });
|
||||
}
|
||||
var w = _session.World;
|
||||
// quadro della flotta: all'apertura e a ogni nuovo giorno; di nuovo dopo 5 s se non arriva
|
||||
_sinceFleet += delta;
|
||||
long today = Fmt.Today(w);
|
||||
if (today != _fleetDay || (w.Fleet is null && _sinceFleet > 5)) RequestFleet(today);
|
||||
if (w.EntityVersion != _entityVersion || w.DetailVersion != _detailVersion) Refresh();
|
||||
}
|
||||
|
||||
private void Result(CommandResultMessage r) => _status.Text = r.Message;
|
||||
private void RequestFleet(long day)
|
||||
{
|
||||
_fleetDay = day;
|
||||
_sinceFleet = 0;
|
||||
_session.Send(new RequestDetail { Kind = DetailKind.Fleet, Target = 0 });
|
||||
}
|
||||
|
||||
private void Result(CommandResultMessage r)
|
||||
{
|
||||
_status.Text = r.Message;
|
||||
// un rinnovo prenotato o completato cambia il quadro della flotta
|
||||
RequestFleet(Fmt.Today(_session.World));
|
||||
}
|
||||
|
||||
private void Refresh()
|
||||
{
|
||||
@@ -160,6 +190,7 @@ public partial class MaintenancePanel : VBoxContainer
|
||||
|
||||
BuildCard();
|
||||
BuildWorkshop();
|
||||
if (!_fleetBuilt || !ReferenceEquals(w.Fleet, _fleetShown)) BuildFleet();
|
||||
}
|
||||
|
||||
private string DueText(TrainInfo t)
|
||||
@@ -181,7 +212,10 @@ public partial class MaintenancePanel : VBoxContainer
|
||||
_card.AddChild(UiTheme.TitleLabel(T("Cartella di manutenzione") + " · " + t.Name, 22));
|
||||
var card = w.Cards.GetValueOrDefault(_train);
|
||||
var stats = PanelKit.Row();
|
||||
stats.AddChild(PanelKit.Stat(T("Condizione"), PanelKit.Value($"{Math.Floor(card?.Condition ?? t.Condition):0}%")));
|
||||
var condition = PanelKit.Stat(T("Condizione"), PanelKit.Value($"{Math.Floor(card?.Condition ?? t.Condition):0}%"));
|
||||
int trainId = _train;
|
||||
WhyTooltip.Attach(condition, () => new ExplainTarget(ExplainSubject.TrainCondition, trainId));
|
||||
stats.AddChild(condition);
|
||||
stats.AddChild(PanelKit.Stat(T("Guasti nell'anno"), PanelKit.Value($"{card?.FailuresThisYear ?? 0}")));
|
||||
stats.AddChild(PanelKit.Stat(T("Costi dell'anno"), PanelKit.Value((card?.CostThisYear ?? Money.Zero).ToString())));
|
||||
_card.AddChild(stats);
|
||||
@@ -212,6 +246,12 @@ public partial class MaintenancePanel : VBoxContainer
|
||||
{
|
||||
var def = w.Data.Vehicles.FirstOrDefault(d => d.Id == v.Type);
|
||||
_cardDetails.AddChild(UiTheme.Text($"{def?.NameIt ?? v.Type} #{v.Vehicle} · {v.OdometerKm / 1000:0.#} {T("mila km")} · {v.AgeYears:0.#} {T("anni")}", 13, bold: true));
|
||||
if (w.Fleet?.Vehicles.FirstOrDefault(f => f.Vehicle == v.Vehicle) is { } info)
|
||||
{
|
||||
var value = UiTheme.Text(VehicleOutlook(info), 12, info.Superseded ? Palette.Amber : Palette.TextSecondary);
|
||||
value.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
_cardDetails.AddChild(value);
|
||||
}
|
||||
foreach (var c in v.Components)
|
||||
{
|
||||
var row = PanelKit.Row(6);
|
||||
@@ -261,8 +301,98 @@ public partial class MaintenancePanel : VBoxContainer
|
||||
actions.AddChild(b);
|
||||
}
|
||||
_cardControls.AddChild(actions);
|
||||
// rinnovo: l'intervento con effetto «renew» dei dati, vende i veicoli superati e compra i successori
|
||||
if (w.Data.Maintenance.Interventions.FirstOrDefault(i => i.Effect == InterventionEffect.Renew) is { } renewal)
|
||||
{
|
||||
var renew = new Button { Text = renewal.NameIt };
|
||||
renew.Pressed += () => _session.Command(new ScheduleServiceCommand(new TrainId(_train), renewal.Id), Result);
|
||||
_cardControls.AddChild(renew);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ rinnovo della flotta
|
||||
|
||||
/// <summary>Riga di obsolescenza di un veicolo: superato, successore con prestazioni e prezzo, valori, costo di manutenzione.</summary>
|
||||
private string VehicleOutlook(FleetVehicleInfo v)
|
||||
{
|
||||
var parts = new List<string>();
|
||||
if (v.Superseded)
|
||||
{
|
||||
parts.Add(string.Format(T("superato dal {0}"), v.SupersededYear));
|
||||
var next = _session.World.Data.Vehicles.FirstOrDefault(d => d.Id == v.Successor);
|
||||
if (next is not null)
|
||||
parts.Add(string.Format(T("successore {0} ({1} kW, {2} km/h, {3})"), next.NameIt, next.PowerKw, next.MaxSpeedKmh, new Money(next.Price)));
|
||||
}
|
||||
if (!v.InProduction) parts.Add(T("fuori produzione"));
|
||||
parts.Add(string.Format(T("valore {0}"), v.BookValue));
|
||||
parts.Add(string.Format(T("rivendita {0}"), v.Resale));
|
||||
if (v.MaintenanceFactor > 1.001f) parts.Add(string.Format(T("manutenzione ×{0:0.##}"), v.MaintenanceFactor));
|
||||
return string.Join(" · ", parts);
|
||||
}
|
||||
|
||||
private void BuildFleet()
|
||||
{
|
||||
foreach (var c in _fleet.GetChildren()) c.QueueFree();
|
||||
var w = _session.World;
|
||||
var report = w.Fleet;
|
||||
_fleetShown = report;
|
||||
_fleetBuilt = true;
|
||||
if (report is null)
|
||||
{
|
||||
_fleet.AddChild(UiTheme.Text(T("Quadro della flotta in arrivo dal server…"), 13, Palette.TextSecondary));
|
||||
return;
|
||||
}
|
||||
_fleet.AddChild(PanelKit.Pair(T("Era"), PanelKit.Value(EraName(report.Era))));
|
||||
if (report.NextEra.Length > 0)
|
||||
_fleet.AddChild(PanelKit.Pair(T("Prossima era"), PanelKit.Value($"{EraName(report.NextEra)} · {report.NextEraYear}")));
|
||||
_fleet.AddChild(PanelKit.Pair(T("Valore della flotta"), PanelKit.Value(report.BookValueTotal.ToString())));
|
||||
var superseded = report.Vehicles.Where(v => v.Superseded).ToList();
|
||||
if (superseded.Count == 0)
|
||||
{
|
||||
_fleet.AddChild(UiTheme.Text(T("Nessun veicolo superato"), 13, Palette.TextSecondary));
|
||||
return;
|
||||
}
|
||||
foreach (var v in superseded.Take(8))
|
||||
{
|
||||
var def = w.Data.Vehicles.FirstOrDefault(d => d.Id == v.Type);
|
||||
string where = v.Train >= 0 && w.Trains.TryGetValue(v.Train, out var t) ? t.Name
|
||||
: v.Depot >= 0 && w.Depots.TryGetValue(v.Depot, out var d) ? d.Name : "";
|
||||
_fleet.AddChild(UiTheme.Text($"{def?.NameIt ?? v.Type} #{v.Vehicle} · {where} · {v.AgeYears:0.#}/{v.LifeYears} {T("anni")}", 13, bold: true));
|
||||
var line = UiTheme.Text(VehicleOutlook(v), 12, Palette.Amber);
|
||||
line.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
_fleet.AddChild(line);
|
||||
}
|
||||
if (superseded.Count > 8)
|
||||
_fleet.AddChild(UiTheme.Text(string.Format(T("e altri {0} veicoli superati"), superseded.Count - 8), 12, Palette.TextSecondary));
|
||||
foreach (var r in report.Trains)
|
||||
{
|
||||
string name = w.Trains.TryGetValue(r.Train, out var t) ? t.Name : $"#{r.Train}";
|
||||
var row = PanelKit.Row(6);
|
||||
var text = UiTheme.Text(string.Format(T("{0}: {1} veicoli da rinnovare, spesa netta {2}"), name, r.Vehicles, r.NetCost), 13,
|
||||
r.Affordable ? Palette.Text : Palette.Danger);
|
||||
text.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
text.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
row.AddChild(text);
|
||||
if (r.Booked)
|
||||
{
|
||||
// rinnovo già prenotato: niente pulsante, ripremerlo rifarebbe la prenotazione
|
||||
row.AddChild(UiTheme.Text(T("rinnovo prenotato"), 13, Palette.TextSecondary));
|
||||
}
|
||||
else
|
||||
{
|
||||
int train = r.Train;
|
||||
string intervention = report.RenewalIntervention;
|
||||
var button = new Button { Text = T("Rinnova") };
|
||||
button.Pressed += () => _session.Command(new ScheduleServiceCommand(new TrainId(train), intervention), Result);
|
||||
row.AddChild(button);
|
||||
}
|
||||
_fleet.AddChild(row);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Nome italiano dell'era dal suo id in eras.json (il quadro della flotta manda l'id).</summary>
|
||||
private string EraName(string id) => _session.World.Data.Eras.Eras.FirstOrDefault(e => e.Id == id)?.NameIt ?? id;
|
||||
|
||||
// ------------------------------------------------------------------ registro officina
|
||||
|
||||
private void BuildWorkshop()
|
||||
|
||||
@@ -5,6 +5,8 @@ using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Protocol.Client;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
using ExplainSubject = RailEnterprise.Core.Economy.ExplainSubject;
|
||||
using ExplainTarget = RailEnterprise.Core.Economy.ExplainTarget;
|
||||
|
||||
namespace RailEnterprise.Client.Panels;
|
||||
|
||||
@@ -102,6 +104,8 @@ public partial class MarketPanel : VBoxContainer
|
||||
_goodChange.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
price.AddChild(_goodPrice);
|
||||
price.AddChild(_goodChange);
|
||||
// tooltip «perché» del prezzo globale del bene scelto (ADR 0024)
|
||||
WhyTooltip.Attach(_goodPrice, () => _selected >= 0 ? new ExplainTarget(ExplainSubject.GlobalPrice, _selected) : null);
|
||||
top.AddChild(price);
|
||||
center.AddChild(top);
|
||||
center.AddChild(_chart);
|
||||
@@ -424,14 +428,27 @@ public partial class MarketPanel : VBoxContainer
|
||||
var price = UiTheme.Text(PerUnit(w, g.Good, p.Price), 14, bold: true);
|
||||
price.CustomMinimumSize = new Vector2(110, 0);
|
||||
row.AddChild(price);
|
||||
// prezzo locale dell'industria spiegato dal server; gli hub comprano al prezzo mondiale meno il dazio
|
||||
if (p.Kind != SellPlaceInfo.Hub)
|
||||
{
|
||||
int good = g.Good, target = p.Target;
|
||||
WhyTooltip.Attach(price, () => new ExplainTarget(ExplainSubject.LocalPrice, good, target));
|
||||
}
|
||||
var line = UiTheme.Text(p.Line >= 0 ? LineName(w, p.Line) : T("non collegato"), 14, p.Line >= 0 ? Palette.TextSecondary : Palette.Amber);
|
||||
line.CustomMinimumSize = new Vector2(130, 0);
|
||||
line.ClipText = true;
|
||||
line.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
|
||||
row.AddChild(line);
|
||||
box.TooltipText = p.Line >= 0
|
||||
// il suggerimento della riga sta sul nome e sulla linea, non sul riquadro: sul prezzo c'è il tooltip «perché»,
|
||||
// e il suggerimento nativo di un antenato gli comparirebbe sopra
|
||||
string tip = p.Line >= 0
|
||||
? $"{name}: {T("servita dalla tua linea")} {LineName(w, p.Line)}"
|
||||
: $"{name}: {T("nessuna tua stazione servita da una linea con treni ha questa destinazione nel bacino")}";
|
||||
foreach (var l in new[] { label, line })
|
||||
{
|
||||
l.TooltipText = tip;
|
||||
l.MouseFilter = MouseFilterEnum.Pass;
|
||||
}
|
||||
return box;
|
||||
}
|
||||
|
||||
@@ -523,7 +540,7 @@ public partial class MarketPanel : VBoxContainer
|
||||
}
|
||||
col.AddChild(Wrapped($"{T("Compra merci all'origine e rivendile dove il prezzo è più alto. Si sblocca al livello")} {tier}.", 13, Palette.Text));
|
||||
col.AddChild(Bar(report.TradingProgress, Palette.Amber));
|
||||
col.AddChild(UiTheme.Text($"{T("Avanzamento verso")} {tier}: {Fmt.Pct(report.TradingProgress, 0)}", 12, Palette.TextSecondary));
|
||||
col.AddChild(UiTheme.Text($"{T("Avanzamento verso")} {tier}: {Fmt.Progress(report.TradingProgress)}", 12, Palette.TextSecondary));
|
||||
// merce già in magazzino (per esempio ereditata da una fusione): si vende e si spedisce anche senza lo sblocco
|
||||
if (report.Warehouses.Any(h => h.Incoming > 0 || h.Goods.Any(g => g.Units > 0)))
|
||||
{
|
||||
|
||||
@@ -21,6 +21,7 @@ public partial class SeriesChart : Control
|
||||
private string _empty = "";
|
||||
private IReadOnlyList<double> _forecast = [], _low = [], _high = [];
|
||||
private string _todayLabel = "", _forecastLabel = "";
|
||||
private IReadOnlyList<(int Index, string Label)> _markers = [];
|
||||
|
||||
public SeriesChart(float height = 150)
|
||||
{
|
||||
@@ -38,6 +39,17 @@ public partial class SeriesChart : Control
|
||||
_color = color;
|
||||
_empty = empty;
|
||||
_forecast = _low = _high = [];
|
||||
_markers = [];
|
||||
QueueRedraw();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Segni sulla serie a linea (dopo <see cref="Show"/>): un punto con l'etichetta sopra, per
|
||||
/// esempio i livelli raggiunti nello storico del patrimonio (immagine 08).
|
||||
/// </summary>
|
||||
public void SetMarkers(IReadOnlyList<(int Index, string Label)> markers)
|
||||
{
|
||||
_markers = markers;
|
||||
QueueRedraw();
|
||||
}
|
||||
|
||||
@@ -118,6 +130,19 @@ public partial class SeriesChart : Control
|
||||
DrawColoredPolygon(fill.ToArray(), Palette.WithAlpha(_color, 0.18f));
|
||||
DrawPolyline(points, _color, 2.5f, true);
|
||||
if (f > 0) DrawForecast(area, points[^1], step, Y, font, fontSize);
|
||||
foreach (var (index, label) in _markers)
|
||||
{
|
||||
if (index < 0 || index >= n) continue;
|
||||
var p = points[index];
|
||||
bool atEnd = index == n - 1;
|
||||
DrawCircle(p, 5, Palette.AmberLight);
|
||||
DrawArc(p, 5, 0, MathF.Tau, 16, Palette.AppBackground, 1.5f, true);
|
||||
var dims = font.GetStringSize(label, HorizontalAlignment.Left, -1, 12);
|
||||
// sull'ultimo punto (che ha sopra il suo valore) l'etichetta va a sinistra, alla sua altezza
|
||||
float mx = atEnd ? Math.Max(area.Position.X, p.X - dims.X - 10) : Math.Clamp(p.X - dims.X / 2, area.Position.X, Size.X - dims.X - 4);
|
||||
float my = atEnd ? p.Y + 16 : p.Y - 12 < area.Position.Y + 10 ? p.Y + 20 : p.Y - 12;
|
||||
DrawString(font, new Vector2(mx, my), label, HorizontalAlignment.Left, -1, 12, Palette.AmberLight);
|
||||
}
|
||||
DrawCircle(points[^1], 4, Palette.AmberLight);
|
||||
string last = _format(_values[^1]);
|
||||
var lastDims = font.GetStringSize(last, HorizontalAlignment.Left, -1, 12);
|
||||
|
||||
@@ -77,41 +77,3 @@ public partial class HelpPanel : VBoxContainer
|
||||
AddChild(l);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Conti della compagnia e prestiti.</summary>
|
||||
public partial class FinancePanel : VBoxContainer
|
||||
{
|
||||
private readonly GameSession _session;
|
||||
private readonly Label _cash = PanelKit.Value();
|
||||
private readonly Label _worth = PanelKit.Value();
|
||||
private readonly Label _rating = PanelKit.Value();
|
||||
private readonly SpinBox _loan = new() { MinValue = 10_000, MaxValue = 10_000_000, Step = 10_000, Value = 100_000, Prefix = "₤", SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
|
||||
public FinancePanel(GameSession session)
|
||||
{
|
||||
_session = session;
|
||||
AddThemeConstantOverride("separation", 10);
|
||||
AddChild(UiTheme.TitleLabel(T("Finanze"), 34));
|
||||
AddChild(PanelKit.Pair(T("Cassa"), _cash));
|
||||
AddChild(PanelKit.Pair(T("Patrimonio netto"), _worth));
|
||||
AddChild(PanelKit.Pair(T("Rating"), _rating));
|
||||
AddChild(PanelKit.Separator());
|
||||
AddChild(UiTheme.Text(T("Prestito"), 14, bold: true));
|
||||
AddChild(_loan);
|
||||
var take = UiTheme.Primary(T("Chiedi il prestito"));
|
||||
take.Pressed += () => _session.Command(new TakeLoanCommand(Money.FromLire((long)_loan.Value)), r => _status.Text = r.Message);
|
||||
AddChild(take);
|
||||
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
AddChild(_status);
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
var w = _session.World;
|
||||
var me = w.Summary is null ? null : w.Companies.GetValueOrDefault(w.Summary.CompanyId);
|
||||
_cash.Text = (w.LastDigest?.Cash ?? me?.Cash ?? default).ToString();
|
||||
_worth.Text = (w.LastDigest?.NetWorth ?? me?.NetWorth ?? default).ToString();
|
||||
_rating.Text = w.LastDigest?.Rating ?? me?.Rating ?? "—";
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,9 @@ public partial class TrackPanel : VBoxContainer
|
||||
public Button Build { get; } = UiTheme.Primary(T("Costruisci"));
|
||||
public Button Cancel { get; } = new() { Text = T("Annulla") };
|
||||
|
||||
/// <summary>Grafico del profilo (per l'evidenziazione del tutorial).</summary>
|
||||
public Control Chart => _chart;
|
||||
|
||||
public event Action? OptionsChanged;
|
||||
|
||||
public TrackPanel(ClientWorld world)
|
||||
|
||||
@@ -7,12 +7,17 @@ using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Rail;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
using ExplainSubject = RailEnterprise.Core.Economy.ExplainSubject;
|
||||
using ExplainTarget = RailEnterprise.Core.Economy.ExplainTarget;
|
||||
|
||||
namespace RailEnterprise.Client.Panels;
|
||||
|
||||
/// <summary>
|
||||
/// Treni: acquisto dei veicoli in un deposito, composizione, assegnazione alle linee, rientro.
|
||||
/// Ogni azione è un comando; la lista si aggiorna con i delta del server.
|
||||
/// Treni: acquisto dei veicoli in un deposito, composizione, assegnazione alle linee, rientro, vendita
|
||||
/// dei veicoli liberi e rinnovo dei treni con veicoli superati. Ogni azione è un comando; la lista si
|
||||
/// aggiorna con i delta del server. Catalogo, obsolescenza, successori e valori di rivendita vengono dal
|
||||
/// quadro della flotta (FleetReport, ADR 0020), chiesto all'apertura, a ogni nuovo giorno e dopo i comandi:
|
||||
/// il pannello non calcola nulla.
|
||||
/// </summary>
|
||||
public partial class TrainsPanel : VBoxContainer
|
||||
{
|
||||
@@ -20,10 +25,12 @@ public partial class TrainsPanel : VBoxContainer
|
||||
private readonly OptionButton _depot = new();
|
||||
private readonly OptionButton _vehicle = new();
|
||||
private readonly SpinBox _count = new() { MinValue = 1, MaxValue = 12, Value = 1 };
|
||||
private readonly Label _modelInfo = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
private readonly ItemList _inDepot = new() { SelectMode = ItemList.SelectModeEnum.Multi, CustomMinimumSize = new Vector2(0, 120) };
|
||||
private readonly LineEdit _name = new() { PlaceholderText = T("Nome del treno") };
|
||||
private readonly ItemList _trains = new() { CustomMinimumSize = new Vector2(0, 140) };
|
||||
private readonly OptionButton _line = new();
|
||||
private readonly Label _renewInfo = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
private readonly List<int> _depotIds = [];
|
||||
private readonly List<VehicleDef> _catalog = [];
|
||||
@@ -31,9 +38,17 @@ public partial class TrainsPanel : VBoxContainer
|
||||
private readonly List<int> _trainIds = [];
|
||||
private readonly List<int> _lineIds = [];
|
||||
private int _version = -1;
|
||||
private FleetReport? _fleetShown;
|
||||
private long _requestedDay = long.MinValue;
|
||||
private double _sinceRequest = double.MaxValue;
|
||||
|
||||
public event Action<int>? TrainSelected;
|
||||
|
||||
/// <summary>Pulsanti di acquisto, composizione e assegnazione (per l'evidenziazione del tutorial).</summary>
|
||||
public Control? BuyButton { get; }
|
||||
public Control? ComposeButton { get; }
|
||||
public Control? AssignButton { get; }
|
||||
|
||||
public TrainsPanel(GameSession session)
|
||||
{
|
||||
_session = session;
|
||||
@@ -46,40 +61,78 @@ public partial class TrainsPanel : VBoxContainer
|
||||
buy.AddChild(_vehicle);
|
||||
buy.AddChild(_count);
|
||||
AddChild(buy);
|
||||
_modelInfo.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
AddChild(_modelInfo);
|
||||
var buyButton = UiTheme.Primary(T("Compra veicoli"));
|
||||
buyButton.Pressed += Buy;
|
||||
AddChild(buyButton);
|
||||
BuyButton = buyButton;
|
||||
AddChild(UiTheme.Text(T("Veicoli liberi nel deposito (selezione multipla, in ordine)"), 13, Palette.TextSecondary));
|
||||
AddChild(_inDepot);
|
||||
// «perché»: valore del veicolo sotto il puntatore (residuo, valore contabile, rivendita)
|
||||
WhyTooltip.Attach(_inDepot, () => HoveredId(_inDepot, _vehicleIds) is int v and >= 0
|
||||
? new ExplainTarget(ExplainSubject.VehicleValue, v)
|
||||
: null);
|
||||
var compose = PanelKit.Row();
|
||||
_name.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
compose.AddChild(_name);
|
||||
var composeButton = new Button { Text = T("Componi") };
|
||||
composeButton.Pressed += Compose;
|
||||
compose.AddChild(composeButton);
|
||||
ComposeButton = composeButton;
|
||||
var sellButton = new Button { Text = T("Vendi") };
|
||||
sellButton.Pressed += Sell;
|
||||
compose.AddChild(sellButton);
|
||||
AddChild(compose);
|
||||
AddChild(PanelKit.Separator());
|
||||
AddChild(UiTheme.Text(T("Treni della compagnia"), 14, bold: true));
|
||||
AddChild(_trains);
|
||||
WhyTooltip.Attach(_trains, () => HoveredId(_trains, _trainIds) is int t and >= 0
|
||||
? new ExplainTarget(ExplainSubject.TrainCondition, t)
|
||||
: null);
|
||||
var assign = PanelKit.Row();
|
||||
_line.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
assign.AddChild(_line);
|
||||
var assignButton = new Button { Text = T("Assegna") };
|
||||
assignButton.Pressed += Assign;
|
||||
assign.AddChild(assignButton);
|
||||
AssignButton = assignButton;
|
||||
AddChild(assign);
|
||||
var home = new Button { Text = T("Manda al deposito") };
|
||||
home.Pressed += SendHome;
|
||||
AddChild(home);
|
||||
var renew = new Button { Text = T("Rinnova i veicoli superati") };
|
||||
renew.Pressed += Renew;
|
||||
AddChild(renew);
|
||||
_renewInfo.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
AddChild(_renewInfo);
|
||||
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
AddChild(_status);
|
||||
_depot.ItemSelected += _ => Refresh(force: true);
|
||||
_trains.ItemSelected += i => TrainSelected?.Invoke(_trainIds[(int)i]);
|
||||
_vehicle.ItemSelected += _ => ShowModel();
|
||||
_trains.ItemSelected += i =>
|
||||
{
|
||||
TrainSelected?.Invoke(_trainIds[(int)i]);
|
||||
ShowRenewal();
|
||||
};
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
if (_session.World.EntityVersion != _version) Refresh(force: false);
|
||||
var w = _session.World;
|
||||
_sinceRequest += delta;
|
||||
// quadro della flotta: all'apertura e a ogni nuovo giorno; di nuovo dopo 5 s se non arriva
|
||||
long today = Fmt.Today(w);
|
||||
if (today != _requestedDay || (w.Fleet is null && _sinceRequest > 5)) RequestFleet(today);
|
||||
bool fleetChanged = !ReferenceEquals(w.Fleet, _fleetShown);
|
||||
if (w.EntityVersion != _version || fleetChanged) Refresh(force: fleetChanged);
|
||||
}
|
||||
|
||||
private void RequestFleet(long day)
|
||||
{
|
||||
_requestedDay = day;
|
||||
_sinceRequest = 0;
|
||||
_session.Send(new RequestDetail { Kind = DetailKind.Fleet, Target = 0 });
|
||||
}
|
||||
|
||||
private int Company => _session.World.Summary?.CompanyId ?? 0;
|
||||
@@ -87,7 +140,9 @@ public partial class TrainsPanel : VBoxContainer
|
||||
private void Refresh(bool force)
|
||||
{
|
||||
var w = _session.World;
|
||||
var fleet = w.Fleet;
|
||||
_version = w.EntityVersion;
|
||||
_fleetShown = fleet;
|
||||
int selectedDepot = _depot.Selected >= 0 && _depot.Selected < _depotIds.Count ? _depotIds[_depot.Selected] : -1;
|
||||
_depotIds.Clear();
|
||||
_depot.Clear();
|
||||
@@ -101,16 +156,33 @@ public partial class TrainsPanel : VBoxContainer
|
||||
|
||||
if (_catalog.Count == 0 || force)
|
||||
{
|
||||
int keep = _vehicle.Selected;
|
||||
string? keep = _vehicle.Selected >= 0 && _vehicle.Selected < _catalog.Count ? _catalog[_vehicle.Selected].Id : null;
|
||||
_catalog.Clear();
|
||||
_vehicle.Clear();
|
||||
foreach (var def in w.Data.Vehicles.Where(v => v.EraFrom <= w.Year && (v.EraTo is null || v.EraTo >= w.Year)))
|
||||
if (fleet is not null)
|
||||
{
|
||||
_catalog.Add(def);
|
||||
_vehicle.AddItem($"{def.NameIt} — {new Money(def.Price)}");
|
||||
// catalogo del server: solo i modelli in produzione, i superati segnati con il successore
|
||||
foreach (var m in fleet.Models)
|
||||
{
|
||||
if (Def(m.Type) is not { } def) continue;
|
||||
_catalog.Add(def);
|
||||
string mark = m.Superseded ? $" · {T("superato")}" + (m.Successor.Length > 0 ? $" → {Def(m.Successor)?.NameIt ?? m.Successor}" : "") : "";
|
||||
_vehicle.AddItem($"{def.NameIt} — {new Money(def.Price)}{mark}");
|
||||
}
|
||||
}
|
||||
_vehicle.Selected = keep >= 0 && keep < _catalog.Count ? keep : 0;
|
||||
else
|
||||
{
|
||||
// in attesa del quadro del server: i modelli dell'anno, senza segni
|
||||
foreach (var def in w.Data.Vehicles.Where(v => v.EraFrom <= w.Year && (v.EraTo is null || v.EraTo >= w.Year)))
|
||||
{
|
||||
_catalog.Add(def);
|
||||
_vehicle.AddItem($"{def.NameIt} — {new Money(def.Price)}");
|
||||
}
|
||||
}
|
||||
int index = keep is null ? -1 : _catalog.FindIndex(d => d.Id == keep);
|
||||
_vehicle.Selected = index >= 0 ? index : _catalog.Count > 0 ? 0 : -1;
|
||||
}
|
||||
ShowModel();
|
||||
|
||||
int depot = _depot.Selected >= 0 ? _depotIds[_depot.Selected] : -1;
|
||||
_vehicleIds.Clear();
|
||||
@@ -118,18 +190,25 @@ public partial class TrainsPanel : VBoxContainer
|
||||
foreach (var v in w.Vehicles.Values.Where(v => v.Owner == Company && v.Depot == depot && v.Train < 0).OrderBy(v => v.Id))
|
||||
{
|
||||
_vehicleIds.Add(v.Id);
|
||||
var def = w.Data.Vehicles.FirstOrDefault(d => d.Id == v.Type);
|
||||
_inDepot.AddItem($"{def?.NameIt ?? v.Type} #{v.Id}");
|
||||
var info = fleet?.Vehicles.FirstOrDefault(x => x.Vehicle == v.Id);
|
||||
string extra = info is null
|
||||
? ""
|
||||
: (info.Superseded ? $" · {T("superato")}" : "") + " · " + string.Format(T("rivendita {0}"), info.Resale);
|
||||
_inDepot.AddItem($"{Def(v.Type)?.NameIt ?? v.Type} #{v.Id}{extra}");
|
||||
if (info is { Superseded: true }) _inDepot.SetItemCustomFgColor(_inDepot.ItemCount - 1, Palette.Amber);
|
||||
}
|
||||
|
||||
var selectedTrain = _trains.GetSelectedItems() is { Length: > 0 } sel ? _trainIds[sel[0]] : -1;
|
||||
var selectedTrain = SelectedTrain;
|
||||
_trainIds.Clear();
|
||||
_trains.Clear();
|
||||
foreach (var t in w.Trains.Values.Where(t => t.Owner == Company).OrderBy(t => t.Id))
|
||||
{
|
||||
_trainIds.Add(t.Id);
|
||||
string line = t.Line >= 0 && w.Lines.TryGetValue(t.Line, out var l) ? l.Name : T("senza linea");
|
||||
_trains.AddItem($"{t.Name} · {StateName((TrainState)t.State)} · {line}");
|
||||
var renewal = fleet?.Trains.FirstOrDefault(r => r.Train == t.Id);
|
||||
string mark = renewal is null ? "" : " · " + (renewal.Booked ? T("rinnovo prenotato") : T("da rinnovare"));
|
||||
_trains.AddItem($"{t.Name} · {StateName((TrainState)t.State)} · {line}{mark}");
|
||||
if (renewal is { Booked: false }) _trains.SetItemCustomFgColor(_trains.ItemCount - 1, Palette.Amber);
|
||||
}
|
||||
int ti = _trainIds.IndexOf(selectedTrain);
|
||||
if (ti >= 0) _trains.Select(ti);
|
||||
@@ -146,6 +225,40 @@ public partial class TrainsPanel : VBoxContainer
|
||||
}
|
||||
int li = _lineIds.IndexOf(selectedLine);
|
||||
_line.Selected = li >= 0 ? li : Math.Min(1, _lineIds.Count - 1);
|
||||
ShowRenewal();
|
||||
}
|
||||
|
||||
private VehicleDef? Def(string id) => _session.World.Data.Vehicles.FirstOrDefault(v => v.Id == id);
|
||||
|
||||
/// <summary>Modello scelto nel catalogo: superato o no, successore con prestazioni e prezzo, ultimo anno di produzione.</summary>
|
||||
private void ShowModel()
|
||||
{
|
||||
var fleet = _session.World.Fleet;
|
||||
if (fleet is null || _vehicle.Selected < 0 || _vehicle.Selected >= _catalog.Count) { _modelInfo.Text = ""; return; }
|
||||
var model = fleet.Models.FirstOrDefault(m => m.Type == _catalog[_vehicle.Selected].Id);
|
||||
if (model is null) { _modelInfo.Text = ""; return; }
|
||||
var parts = new List<string>();
|
||||
if (model.Superseded)
|
||||
{
|
||||
var next = Def(model.Successor);
|
||||
parts.Add(next is null
|
||||
? string.Format(T("Superato dal {0}."), model.SupersededYear)
|
||||
: string.Format(T("Superato dal {0}: successore {1} ({2} kW, {3} km/h, {4})."),
|
||||
model.SupersededYear, next.NameIt, next.PowerKw, next.MaxSpeedKmh, new Money(next.Price)));
|
||||
}
|
||||
if (model.LastYear > 0) parts.Add(string.Format(T("In produzione fino al {0}."), model.LastYear));
|
||||
_modelInfo.Text = string.Join(" ", parts);
|
||||
}
|
||||
|
||||
/// <summary>Rinnovo del treno scelto: veicoli superati e spesa netta calcolati dal server.</summary>
|
||||
private void ShowRenewal()
|
||||
{
|
||||
int train = SelectedTrain;
|
||||
var renewal = train >= 0 ? _session.World.Fleet?.Trains.FirstOrDefault(r => r.Train == train) : null;
|
||||
_renewInfo.Text = renewal is null
|
||||
? ""
|
||||
: string.Format(T("Rinnovo: {0} veicoli superati, spesa netta {1} dopo le rivendite."), renewal.Vehicles, renewal.NetCost)
|
||||
+ (renewal.Booked ? " " + T("Rinnovo già prenotato.") : renewal.Affordable ? "" : " " + T("Cassa insufficiente."));
|
||||
}
|
||||
|
||||
public static string StateName(TrainState s) => s switch
|
||||
@@ -160,7 +273,12 @@ public partial class TrainsPanel : VBoxContainer
|
||||
_ => s.ToString(),
|
||||
};
|
||||
|
||||
private void Result(CommandResultMessage r) => _status.Text = r.Message;
|
||||
private void Result(CommandResultMessage r)
|
||||
{
|
||||
_status.Text = r.Message;
|
||||
// acquisti, vendite e rinnovi cambiano il quadro della flotta
|
||||
RequestFleet(Fmt.Today(_session.World));
|
||||
}
|
||||
|
||||
private void Buy()
|
||||
{
|
||||
@@ -177,7 +295,21 @@ public partial class TrainsPanel : VBoxContainer
|
||||
_session.Command(new ComposeTrainCommand(new DepotId(_depotIds[_depot.Selected]), selected, name), Result);
|
||||
}
|
||||
|
||||
private int SelectedTrain => _trains.GetSelectedItems() is { Length: > 0 } sel ? _trainIds[sel[0]] : -1;
|
||||
private void Sell()
|
||||
{
|
||||
var selected = _inDepot.GetSelectedItems().OrderBy(i => i).Select(i => _vehicleIds[i]).ToList();
|
||||
if (selected.Count == 0) { _status.Text = T("Seleziona i veicoli da vendere"); return; }
|
||||
foreach (int id in selected) _session.Command(new SellVehicleCommand(new VehicleId(id)), Result);
|
||||
}
|
||||
|
||||
/// <summary>Identificativo della voce sotto il puntatore, -1 se il puntatore non è su una voce.</summary>
|
||||
private static int HoveredId(ItemList list, List<int> ids)
|
||||
{
|
||||
int i = list.GetItemAtPosition(list.GetLocalMousePosition(), true);
|
||||
return i >= 0 && i < ids.Count ? ids[i] : -1;
|
||||
}
|
||||
|
||||
private int SelectedTrain => _trains.GetSelectedItems() is { Length: > 0 } sel && sel[0] < _trainIds.Count ? _trainIds[sel[0]] : -1;
|
||||
|
||||
private void Assign()
|
||||
{
|
||||
@@ -192,4 +324,13 @@ public partial class TrainsPanel : VBoxContainer
|
||||
if (train < 0 || _depot.Selected < 0) { _status.Text = T("Seleziona un treno e un deposito"); return; }
|
||||
_session.Command(new SendToDepotCommand(new TrainId(train), new DepotId(_depotIds[_depot.Selected])), Result);
|
||||
}
|
||||
|
||||
private void Renew()
|
||||
{
|
||||
int train = SelectedTrain;
|
||||
if (train < 0) { _status.Text = T("Seleziona un treno"); return; }
|
||||
string intervention = _session.World.Fleet?.RenewalIntervention ?? "";
|
||||
if (intervention.Length == 0) { _status.Text = T("Quadro della flotta in arrivo dal server…"); return; }
|
||||
_session.Command(new ScheduleServiceCommand(new TrainId(train), intervention), Result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
using RailEnterprise.Client.Net;
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
|
||||
namespace RailEnterprise.Client.Panels;
|
||||
|
||||
/// <summary>
|
||||
/// Tooltip «perché» comune (F6, ADR 0024): sopra un valore dei pannelli, dopo un breve ritardo, mostra la
|
||||
/// spiegazione calcolata dal server (titolo, valore, formula, termini con i valori di adesso, note) nello stile
|
||||
/// della palette 05. Il client non calcola nulla: a ogni apertura chiede la spiegazione (RequestDetail con
|
||||
/// DetailKind.Explain) e poi, finché il puntatore resta, al più una volta al secondo per valore; intanto mostra
|
||||
/// quella in cache con «aggiornamento in arrivo…» (o «in arrivo…» se manca). Un solo tooltip per schermata, su
|
||||
/// un suo CanvasLayer sopra l'interfaccia; i pannelli lo agganciano con <see cref="Attach"/>. Se il controllo
|
||||
/// sotto il puntatore viene ricostruito (i pannelli rifanno le righe a ogni scheda), il tooltip passa al
|
||||
/// sostituto con la stessa spiegazione senza chiudersi.
|
||||
/// </summary>
|
||||
public partial class WhyTooltip : PanelContainer
|
||||
{
|
||||
/// <summary>Tooltip della schermata di gioco (null fuori partita: gli agganci restano muti).</summary>
|
||||
public static WhyTooltip? Instance { get; private set; }
|
||||
|
||||
/// <summary>Ritardo prima dell'apertura (secondi).</summary>
|
||||
private const double OpenDelay = 0.45;
|
||||
/// <summary>Intervallo minimo tra due richieste della stessa spiegazione (millisecondi).</summary>
|
||||
private const ulong RequestIntervalMs = 1000;
|
||||
/// <summary>Tempo per trovare il sostituto di un controllo ricostruito prima di chiudere (secondi).</summary>
|
||||
private const double ReplaceGrace = 0.3;
|
||||
private const float MaxWidth = 440;
|
||||
|
||||
/// <summary>Aggancio di un controllo: bersaglio, suggerimento e, se serve, il valore che il controllo mostra.</summary>
|
||||
private sealed record Hook(Control Control, Func<ExplainTarget?> Target, string Hint, Func<double?>? Shown);
|
||||
|
||||
/// <summary>Agganci dei controlli nell'albero, per ritrovare il sostituto di un controllo ricostruito.</summary>
|
||||
private static readonly List<Hook> Hooks = [];
|
||||
|
||||
private readonly GameSession _session;
|
||||
private readonly VBoxContainer _body = new();
|
||||
private Hook? _hook;
|
||||
/// <summary>Il controllo agganciato è stato tolto o sta per esserlo: si cerca il sostituto sotto il puntatore.</summary>
|
||||
private bool _lost;
|
||||
private double _lostFor;
|
||||
private (byte Subject, int Target, int Arg) _key;
|
||||
private bool _hasKey;
|
||||
private double _wait;
|
||||
/// <summary>Spiegazione in cache all'apertura: finché non ne arriva un'altra si mostra come in aggiornamento.</summary>
|
||||
private ExplanationReport? _baseline;
|
||||
private bool _fresh;
|
||||
private ExplanationReport? _shown;
|
||||
private bool _shownFresh;
|
||||
private bool _dirty = true;
|
||||
private bool _settling;
|
||||
/// <summary>Per valore: istante dell'ultima richiesta e spiegazione in cache in quel momento.</summary>
|
||||
private readonly Dictionary<(byte, int, int), (ulong At, ExplanationReport? Before)> _requests = [];
|
||||
|
||||
public WhyTooltip(GameSession session)
|
||||
{
|
||||
_session = session;
|
||||
Visible = false;
|
||||
MouseFilter = MouseFilterEnum.Ignore;
|
||||
TopLevel = true;
|
||||
AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Amber, 8, 14));
|
||||
_body.AddThemeConstantOverride("separation", 6);
|
||||
_body.MouseFilter = MouseFilterEnum.Ignore;
|
||||
AddChild(_body);
|
||||
}
|
||||
|
||||
public override void _EnterTree() => Instance = this;
|
||||
|
||||
public override void _ExitTree()
|
||||
{
|
||||
if (Instance == this) Instance = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Aggancia il tooltip a un controllo: al passaggio del mouse chiede a <paramref name="target"/> quale valore
|
||||
/// spiegare (null: nessuna spiegazione per ora). Il controllo riceve il mouse senza fermare i clic dei genitori.
|
||||
/// <paramref name="hint"/> (già tradotto) compare in fondo, per esempio che un clic apre un pannello.
|
||||
/// <paramref name="shown"/> dà il numero che il controllo mostra (nell'unità della spiegazione), quando può
|
||||
/// essere di un altro momento della giornata: se differisce da quello spiegato il tooltip lo dice.
|
||||
/// </summary>
|
||||
public static void Attach(Control control, Func<ExplainTarget?> target, string hint = "", Func<double?>? shown = null)
|
||||
{
|
||||
var hook = new Hook(control, target, hint, shown);
|
||||
if (control.MouseFilter == MouseFilterEnum.Ignore) control.MouseFilter = MouseFilterEnum.Pass;
|
||||
control.MouseEntered += () => Instance?.Enter(hook);
|
||||
control.MouseExited += () => Instance?.Leave(hook);
|
||||
control.TreeEntered += () =>
|
||||
{
|
||||
if (!Hooks.Contains(hook)) Hooks.Add(hook);
|
||||
};
|
||||
control.TreeExiting += () => Hooks.Remove(hook);
|
||||
if (control.IsInsideTree()) Hooks.Add(hook);
|
||||
}
|
||||
|
||||
private static (byte, int, int)? KeyOf(Hook hook) =>
|
||||
hook.Target() is { Subject: not ExplainSubject.None } t ? ((byte)t.Subject, t.A, t.B) : null;
|
||||
|
||||
private void Enter(Hook hook)
|
||||
{
|
||||
if (_hook == hook)
|
||||
{
|
||||
_lost = false;
|
||||
return;
|
||||
}
|
||||
// il sostituto di un controllo ricostruito, con la stessa spiegazione: il tooltip resta aperto
|
||||
if (_hook is not null && _hasKey && KeyOf(hook) == _key)
|
||||
{
|
||||
Adopt(hook);
|
||||
return;
|
||||
}
|
||||
_hook = hook;
|
||||
_lost = false;
|
||||
_lostFor = 0;
|
||||
_wait = 0;
|
||||
_hasKey = false;
|
||||
_shown = null;
|
||||
_dirty = true;
|
||||
Visible = false;
|
||||
}
|
||||
|
||||
private void Leave(Hook hook)
|
||||
{
|
||||
if (_hook != hook) return;
|
||||
// tolto dall'albero o in via di liberazione: il pannello lo sta ricostruendo, si cerca il sostituto
|
||||
if (Doomed(hook.Control)) _lost = true;
|
||||
else Close();
|
||||
}
|
||||
|
||||
private void Adopt(Hook hook)
|
||||
{
|
||||
_hook = hook;
|
||||
_lost = false;
|
||||
_lostFor = 0;
|
||||
}
|
||||
|
||||
private void Close()
|
||||
{
|
||||
_hook = null;
|
||||
_lost = false;
|
||||
_hasKey = false;
|
||||
Visible = false;
|
||||
}
|
||||
|
||||
/// <summary>Il controllo non c'è più o sta per essere liberato (lui o un suo antenato).</summary>
|
||||
private static bool Doomed(Control c)
|
||||
{
|
||||
if (!IsInstanceValid(c) || !c.IsInsideTree()) return true;
|
||||
for (Node? n = c; n is not null; n = n.GetParent())
|
||||
{
|
||||
if (n.IsQueuedForDeletion()) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Il controllo agganciato, vivo e visibile, sotto il puntatore con la stessa spiegazione (il più piccolo).</summary>
|
||||
private Hook? Replacement()
|
||||
{
|
||||
Hook? best = null;
|
||||
float area = float.MaxValue;
|
||||
foreach (var h in Hooks)
|
||||
{
|
||||
var c = h.Control;
|
||||
if (Doomed(c) || !c.IsVisibleInTree()) continue;
|
||||
var rect = c.GetGlobalRect();
|
||||
if (!rect.HasPoint(c.GetGlobalMousePosition())) continue;
|
||||
if (_hasKey && KeyOf(h) != _key) continue;
|
||||
float a = rect.Size.X * rect.Size.Y;
|
||||
if (a >= area) continue;
|
||||
area = a;
|
||||
best = h;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
if (_hook is null) return;
|
||||
var control = _hook.Control;
|
||||
if (_lost || Doomed(control))
|
||||
{
|
||||
if (Replacement() is { } next) Adopt(next);
|
||||
else
|
||||
{
|
||||
_lostFor += delta;
|
||||
if (_lostFor > ReplaceGrace) Close();
|
||||
return;
|
||||
}
|
||||
control = _hook.Control;
|
||||
}
|
||||
else if (!control.IsVisibleInTree() || !control.GetGlobalRect().HasPoint(control.GetGlobalMousePosition()))
|
||||
{
|
||||
// nascosto, oppure il puntatore è uscito senza che il controllo l'abbia mai saputo (sostituto adottato)
|
||||
Close();
|
||||
return;
|
||||
}
|
||||
_wait += delta;
|
||||
if (_wait < OpenDelay) return;
|
||||
if (_hook.Target() is not { Subject: not ExplainSubject.None } t)
|
||||
{
|
||||
Visible = false;
|
||||
return;
|
||||
}
|
||||
var key = ((byte)t.Subject, t.A, t.B);
|
||||
var w = _session.World;
|
||||
var e = w.Explanations.GetValueOrDefault(key);
|
||||
ulong now = Time.GetTicksMsec();
|
||||
_requests.TryGetValue(key, out var last);
|
||||
bool recent = last.At > 0 && now - last.At < RequestIntervalMs;
|
||||
if (!_hasKey || key != _key)
|
||||
{
|
||||
_hasKey = true;
|
||||
_key = key;
|
||||
// quella in cache vale solo se è la risposta a una richiesta di meno di un secondo fa
|
||||
_fresh = e is not null && recent && !ReferenceEquals(e, last.Before);
|
||||
_baseline = e;
|
||||
_shown = null;
|
||||
_dirty = true;
|
||||
}
|
||||
if (!_fresh && e is not null && !ReferenceEquals(e, _baseline)) _fresh = true;
|
||||
// a ogni apertura e poi al più una volta al secondo per valore, finché il puntatore resta
|
||||
if (!recent && _session.IsOpen)
|
||||
{
|
||||
if (_requests.Count > 64) Prune(now);
|
||||
_requests[key] = (now, e);
|
||||
_session.Send(new RequestDetail { Kind = DetailKind.Explain, Target = t.A, Subject = (byte)t.Subject, Arg = t.B });
|
||||
}
|
||||
if (_dirty || !ReferenceEquals(e, _shown) || _fresh != _shownFresh)
|
||||
{
|
||||
_dirty = false;
|
||||
_shown = e;
|
||||
_shownFresh = _fresh;
|
||||
Rebuild(w, e, t);
|
||||
// il riquadro si misura al prossimo fotogramma, a impaginazione fatta: niente salti di lato
|
||||
_settling = true;
|
||||
return;
|
||||
}
|
||||
if (_settling)
|
||||
{
|
||||
_settling = false;
|
||||
Size = Vector2.Zero;
|
||||
}
|
||||
Place();
|
||||
Visible = true;
|
||||
}
|
||||
|
||||
private void Prune(ulong now)
|
||||
{
|
||||
foreach (var k in _requests.Where(r => now - r.Value.At >= RequestIntervalMs).Select(r => r.Key).ToList()) _requests.Remove(k);
|
||||
}
|
||||
|
||||
/// <summary>Vicino al puntatore, in basso a destra, dentro la finestra.</summary>
|
||||
private void Place()
|
||||
{
|
||||
var view = GetViewportRect().Size;
|
||||
var mouse = GetViewport().GetMousePosition();
|
||||
var size = GetCombinedMinimumSize();
|
||||
Size = size;
|
||||
float x = mouse.X + 18, y = mouse.Y + 22;
|
||||
if (x + size.X > view.X - 8) x = Math.Max(8, mouse.X - size.X - 12);
|
||||
if (y + size.Y > view.Y - 8) y = Math.Max(8, mouse.Y - size.Y - 12);
|
||||
Position = new Vector2(x, y);
|
||||
}
|
||||
|
||||
private void Rebuild(Protocol.Client.ClientWorld w, ExplanationReport? e, ExplainTarget t)
|
||||
{
|
||||
// via subito dall'albero: la misura del riquadro non deve contare i figli vecchi
|
||||
foreach (var child in _body.GetChildren())
|
||||
{
|
||||
_body.RemoveChild(child);
|
||||
child.QueueFree();
|
||||
}
|
||||
Content(w, e, t);
|
||||
if (_hook?.Hint is { Length: > 0 } hint) _body.AddChild(UiTheme.Text(hint, 12, Palette.Amber));
|
||||
}
|
||||
|
||||
private void Content(Protocol.Client.ClientWorld w, ExplanationReport? e, ExplainTarget t)
|
||||
{
|
||||
if (e is null)
|
||||
{
|
||||
_body.AddChild(UiTheme.Text(T("Perché questo valore"), 13, Palette.TextSecondary, bold: true));
|
||||
_body.AddChild(UiTheme.Text(T("in arrivo…"), 14, Palette.TextSecondary));
|
||||
return;
|
||||
}
|
||||
var head = UiTheme.Text(e.Title.Length > 0 ? T(e.Title) : T("Perché questo valore"), 15, Palette.AmberLight, bold: true);
|
||||
_body.AddChild(head);
|
||||
string name = SubjectName(w, e, t);
|
||||
if (name.Length > 0) _body.AddChild(Wrapped(name, 13, Palette.TextSecondary));
|
||||
if (!e.Available)
|
||||
{
|
||||
foreach (var n in e.Notes) _body.AddChild(Wrapped(T(n), 13, Palette.TextSecondary));
|
||||
return;
|
||||
}
|
||||
var subject = (ExplainSubject)e.Subject;
|
||||
string value = Format(e.Value, e.Unit, subject, headline: true);
|
||||
_body.AddChild(UiTheme.TitleLabel(e.ValueText.Length > 0 ? $"{e.ValueText} ({value})" : value, 28, Palette.Text));
|
||||
if (e.Formula.Length > 0)
|
||||
{
|
||||
var box = new PanelContainer { MouseFilter = MouseFilterEnum.Ignore };
|
||||
box.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, Palette.Border, 6, 10));
|
||||
box.AddChild(Wrapped(T(e.Formula), 13, Palette.Text));
|
||||
_body.AddChild(box);
|
||||
}
|
||||
if (e.Terms.Count > 0)
|
||||
{
|
||||
var grid = new GridContainer { Columns = 3, MouseFilter = MouseFilterEnum.Ignore };
|
||||
grid.AddThemeConstantOverride("h_separation", 10);
|
||||
grid.AddThemeConstantOverride("v_separation", 3);
|
||||
foreach (var term in e.Terms)
|
||||
{
|
||||
// i simboli che sono parole (soglia, quota, prezzo…) si traducono, le lettere restano come nella formula
|
||||
var symbol = UiTheme.Text(term.Symbol.Length >= 3 ? T(term.Symbol) : term.Symbol, 13, Palette.Amber, bold: true);
|
||||
var label = UiTheme.Text(T(term.Label), 13, Palette.TextSecondary);
|
||||
label.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
// un termine numerico può portare anche un testo (il componente del veicolo): si mostrano entrambi
|
||||
string text = term.Unit == (byte)ExplainUnit.Text ? Translated(term.Text)
|
||||
: term.Text.Length > 0 ? $"{Format(term.Value, term.Unit, subject)} · {Translated(term.Text)}"
|
||||
: Format(term.Value, term.Unit, subject);
|
||||
var v = UiTheme.Text(text, 13, bold: true);
|
||||
v.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
foreach (var l in new[] { symbol, label, v }) l.MouseFilter = MouseFilterEnum.Ignore;
|
||||
grid.AddChild(symbol);
|
||||
grid.AddChild(label);
|
||||
grid.AddChild(v);
|
||||
}
|
||||
_body.AddChild(grid);
|
||||
}
|
||||
foreach (var n in e.Notes) _body.AddChild(Wrapped(T(n), 12, Palette.TextSecondary));
|
||||
if (_hook?.Shown?.Invoke() is { } shown && Format(shown, e.Unit, subject, headline: true) != value)
|
||||
_body.AddChild(Wrapped(T("Il numero sul pannello è di inizio giornata; qui c'è quello di adesso."), 12, Palette.TextSecondary));
|
||||
if (!_fresh) _body.AddChild(UiTheme.Text(T("aggiornamento in arrivo…"), 12, Palette.TextSecondary));
|
||||
}
|
||||
|
||||
/// <summary>Nome dell'oggetto: i beni nella lingua dell'interfaccia, il resto com'è (nomi propri dal server).</summary>
|
||||
private static string SubjectName(Protocol.Client.ClientWorld w, ExplanationReport e, ExplainTarget t)
|
||||
{
|
||||
bool en = TranslationServer.GetLocale().StartsWith("en");
|
||||
string Good(int g) => g >= 0 && g < w.Data.Goods.Count ? (en ? w.Data.Goods[g].NameEn : w.Data.Goods[g].NameIt) : "";
|
||||
return t.Subject switch
|
||||
{
|
||||
ExplainSubject.GlobalPrice => Good(t.A),
|
||||
ExplainSubject.LocalPrice => w.Industries.TryGetValue(t.B, out var ind) ? $"{Good(t.A)} · {ind.Name}" : e.Name,
|
||||
_ => e.Name,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Testi dei valori testuali: componenti dei veicoli tradotti, il resto (rating, nomi, anni) com'è.</summary>
|
||||
private static string Translated(string text) => text switch
|
||||
{
|
||||
"engine" => T("motore"),
|
||||
"brakes" => T("freni"),
|
||||
"body" => T("cassa"),
|
||||
_ => text,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Formato del valore secondo l'unità, con gli arrotondamenti dei pannelli: prezzi come la scheda
|
||||
/// dell'industria (<see cref="Fmt.PricePrecise"/>), importi sotto ₤ 1.000 con i centesimi (tariffe), la
|
||||
/// condizione per difetto con il segno di percentuale come le officine (intera nel valore principale, con
|
||||
/// un decimale nei termini).
|
||||
/// </summary>
|
||||
public static string Format(double v, byte unit, ExplainSubject subject, bool headline = false)
|
||||
{
|
||||
if (double.IsPositiveInfinity(v)) return "∞";
|
||||
if (double.IsNegativeInfinity(v)) return "−∞";
|
||||
if (double.IsNaN(v)) return "—";
|
||||
return (ExplainUnit)unit switch
|
||||
{
|
||||
ExplainUnit.Money => new Money((long)Math.Round(v)).ToString(Math.Abs(v) < 100_000 ? "it2" : "it"),
|
||||
ExplainUnit.Price => Fmt.PricePrecise(v),
|
||||
// l'avanzamento si legge per difetto come nella barra superiore e nella scalata (ADR 0018)
|
||||
ExplainUnit.Percent => subject == ExplainSubject.TierProgress ? Fmt.Progress(v) : Fmt.Pct(v, Math.Abs(v) < 0.01 && v != 0 ? 3 : 1),
|
||||
ExplainUnit.Factor => "× " + Fmt.Number(v, 3),
|
||||
ExplainUnit.Km => Fmt.Number(v, 1) + " km",
|
||||
ExplainUnit.Days => Fmt.Number(v, 1) + " " + T("giorni"),
|
||||
ExplainUnit.Units => Fmt.Number(v, Math.Abs(v - Math.Round(v)) < 1e-9 ? 0 : 1),
|
||||
ExplainUnit.Condition => headline
|
||||
? Fmt.Number(Math.Floor(v + 1e-9), 0) + "%"
|
||||
: Fmt.Number(Math.Floor(v * 10 + 1e-9) / 10, 1) + "%",
|
||||
ExplainUnit.Years => Fmt.Number(v, 1) + " " + T("anni"),
|
||||
_ => Fmt.Number(v, Math.Abs(v) < 0.01 && v != 0 ? 5 : 3),
|
||||
};
|
||||
}
|
||||
|
||||
private static Label Wrapped(string text, int size, Color color)
|
||||
{
|
||||
var l = UiTheme.Text(text, size, color);
|
||||
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
l.CustomMinimumSize = new Vector2(MaxWidth - 40, 0);
|
||||
l.MouseFilter = MouseFilterEnum.Ignore;
|
||||
return l;
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,102 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
using RailEnterprise.Client.Net;
|
||||
using RailEnterprise.Client.Panels;
|
||||
using RailEnterprise.Client.Tutorial;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
using RailEnterprise.Protocol;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
|
||||
namespace RailEnterprise.Client.Screens;
|
||||
|
||||
/// <summary>
|
||||
/// Collegamento a un server (immagine 09 non fornita: palette e componenti dell'immagine 05).
|
||||
/// Ricorda indirizzo e token in user://settings.cfg.
|
||||
/// Schermata iniziale e di connessione (immagine di riferimento 09): a sinistra la mappa decorativa
|
||||
/// con il titolo, a destra «Dove gira il motore di gioco?» con le due strade (server locale figlio
|
||||
/// del gioco o server in rete), indirizzo e token, lo stato del server (versione e protocollo,
|
||||
/// sistema, tempo di attività, tick al secondo, latenza, client collegati), le partite salvate sul
|
||||
/// server e i pulsanti per riprendere o iniziare. All'apertura la schermata avvia il server locale o
|
||||
/// verifica il server in rete ricordato, con una sessione di prova che legge lo stato e l'elenco dei
|
||||
/// salvataggi; «Connetti e riprendi» la passa alla partita (e se non c'è ancora la apre). Nessuna
|
||||
/// logica di gioco: carica, nuova partita ed elenco sono richieste al server (Load, NewGame,
|
||||
/// ListSaves). Caricare o creare una partita sostituisce il mondo per tutti: si chiede conferma. Sotto i
|
||||
/// pulsanti la casella «Mostra il tutorial» (attiva alla prima partita) vale per la partita che si apre, e
|
||||
/// «Tutorial» apre una partita locale di prova sempre nuova, separata da quella del giocatore (ADR 0023).
|
||||
/// </summary>
|
||||
public partial class ConnectScreen : Control
|
||||
{
|
||||
private const string SettingsPath = "user://settings.cfg";
|
||||
private readonly LineEdit _address = new() { PlaceholderText = "unraid.lan:7400" };
|
||||
private readonly LineEdit _token = new() { Secret = true, PlaceholderText = T("Token del server") };
|
||||
private readonly Label _status = UiTheme.Text("", 14, Palette.TextSecondary);
|
||||
private readonly Button _connect = UiTheme.Primary(T("Collegati"));
|
||||
private const double SavesRefreshS = 5;
|
||||
private const double WelcomeTimeoutS = 30;
|
||||
/// <summary>Metadato della riga «Partita in corso» nell'elenco dei salvataggi.</summary>
|
||||
private const string CurrentGame = "";
|
||||
private readonly GameData _data;
|
||||
private readonly bool _remember, _autoStart;
|
||||
private GameSession? _handover;
|
||||
private readonly LineEdit _address = new() { PlaceholderText = "unraid.lan:7400", SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
private readonly LineEdit _token = new() { Secret = true, PlaceholderText = T("Token del server"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
private readonly CheckBox _rememberBox = new() { Text = T("Ricorda questo server"), ButtonPressed = true };
|
||||
private readonly Button _probe = new() { Text = T("Verifica connessione"), CustomMinimumSize = new Vector2(0, 40) };
|
||||
private readonly VBoxContainer _remoteFields = new();
|
||||
private readonly Button _localCard = new() { ToggleMode = true, CustomMinimumSize = new Vector2(0, 112), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
private readonly Button _remoteCard = new() { ToggleMode = true, CustomMinimumSize = new Vector2(0, 112), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
private readonly ColorRect _dot = new() { CustomMinimumSize = new Vector2(12, 12), SizeFlagsVertical = SizeFlags.ShrinkCenter };
|
||||
private readonly Label _stateTitle = UiTheme.Text("", 16, bold: true);
|
||||
/// <summary>Stato del server in tre colonne per due righe, didascalia sopra il valore (immagine 09).</summary>
|
||||
private readonly GridContainer _stateGrid = new() { Columns = 3 };
|
||||
private readonly List<(Label Caption, Label Value)> _stateCells = [];
|
||||
/// <summary>Partite salvate in tre colonne: nome, data di gioco, quanto tempo fa.</summary>
|
||||
private readonly Tree _saves = new()
|
||||
{
|
||||
Columns = 3, HideRoot = true, SelectMode = Tree.SelectModeEnum.Row, CustomMinimumSize = new Vector2(0, 150), SizeFlagsVertical = SizeFlags.ExpandFill,
|
||||
};
|
||||
private readonly Button _resume = UiTheme.Primary(T("Connetti e riprendi"));
|
||||
private readonly Button _newGame = new() { Text = T("Nuova partita sul server") };
|
||||
private readonly CheckBox _showTutorial = new() { Text = T("Mostra il tutorial") };
|
||||
private readonly Button _tutorial = new() { Text = T("Tutorial") };
|
||||
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
private readonly ConfirmationDialog _confirm = new() { Title = T("Sostituire la partita?"), DialogAutowrap = true, MinSize = new Vector2I(520, 0) };
|
||||
private Action? _onConfirm;
|
||||
private GameSession? _session;
|
||||
private bool _busy, _local, _closed, _resumeAfterConnect;
|
||||
private double _sinceSaves = double.MaxValue;
|
||||
private SaveList? _shownSaves;
|
||||
/// <summary>Riga scelta nell'elenco, per id del salvataggio (CurrentGame per la partita in corso): l'elenco si riordina a ogni aggiornamento.</summary>
|
||||
private string _selectedSave = CurrentGame;
|
||||
private Action<IMessage>? _awaitingWelcome;
|
||||
private double _waiting;
|
||||
/// <summary>Stato del server mostrato e istante in cui è arrivato: il tempo di attività avanza da lì.</summary>
|
||||
private ServerInfo? _infoSeen;
|
||||
private double _infoAt;
|
||||
|
||||
public event Action<Uri, string, string>? ConnectRequested;
|
||||
public event Action? Back;
|
||||
/// <summary>La sessione di prova diventa la partita: la schermata non la chiude più.</summary>
|
||||
public event Action<GameSession>? PlayRequested;
|
||||
public event Action<string>? LanguageChanged;
|
||||
/// <summary>Apre il pannello delle impostazioni audio.</summary>
|
||||
public event Action? AudioRequested;
|
||||
/// <summary>Pulsante «Tutorial»: Main apre la partita di prova del tutorial.</summary>
|
||||
public event Action? TutorialRequested;
|
||||
|
||||
/// <summary>Casella «Mostra il tutorial» per la partita che si apre.</summary>
|
||||
public bool ShowTutorial => _showTutorial.ButtonPressed;
|
||||
|
||||
/// <summary>Origine della partita per la voce del tutorial: il server locale o l'indirizzo del server in rete.</summary>
|
||||
public string GameScope => _local ? "local" : "remote_" + _address.Text.Trim();
|
||||
|
||||
/// <param name="remember">Falso per l'anteprima del collaudo: non legge né scrive le impostazioni.</param>
|
||||
/// <param name="autoStart">Avvia subito il server locale o verifica il server ricordato (falso nel collaudo).</param>
|
||||
/// <param name="handover">Sessione di prova di una schermata precedente (cambio di lingua): la si riprende così com'è.</param>
|
||||
public ConnectScreen(GameData data, bool remember = true, bool autoStart = true, GameSession? handover = null)
|
||||
{
|
||||
_data = data;
|
||||
_remember = remember;
|
||||
_autoStart = autoStart;
|
||||
_handover = handover;
|
||||
}
|
||||
|
||||
/// <summary>Stato e salvataggi sono arrivati dal server (serve al collaudo).</summary>
|
||||
public bool Loaded => _session?.World.Server is not null && _shownSaves is not null;
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
@@ -27,67 +106,710 @@ public partial class ConnectScreen : Control
|
||||
var bg = new ColorRect { Color = Palette.AppBackground };
|
||||
bg.SetAnchorsPreset(LayoutPreset.FullRect);
|
||||
AddChild(bg);
|
||||
var center = new CenterContainer();
|
||||
center.SetAnchorsPreset(LayoutPreset.FullRect);
|
||||
AddChild(center);
|
||||
var panel = new PanelContainer { CustomMinimumSize = new Vector2(480, 0) };
|
||||
center.AddChild(panel);
|
||||
var col = new VBoxContainer();
|
||||
col.AddThemeConstantOverride("separation", 12);
|
||||
panel.AddChild(col);
|
||||
col.AddChild(UiTheme.TitleLabel(T("Collegati a un server"), 40));
|
||||
col.AddChild(UiTheme.Text(T("Indirizzo (host:porta)"), 13, Palette.TextSecondary));
|
||||
col.AddChild(_address);
|
||||
col.AddChild(UiTheme.Text(T("Token"), 13, Palette.TextSecondary));
|
||||
col.AddChild(_token);
|
||||
var row = new HBoxContainer();
|
||||
row.AddThemeConstantOverride("separation", 10);
|
||||
_connect.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
_connect.Pressed += Submit;
|
||||
row.AddChild(_connect);
|
||||
var back = new Button { Text = T("Indietro") };
|
||||
back.Pressed += () => Back?.Invoke();
|
||||
row.AddChild(back);
|
||||
col.AddChild(row);
|
||||
var split = new HBoxContainer();
|
||||
split.SetAnchorsPreset(LayoutPreset.FullRect);
|
||||
split.AddThemeConstantOverride("separation", 0);
|
||||
AddChild(split);
|
||||
|
||||
// sinistra: mappa decorativa con il titolo
|
||||
var left = new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsStretchRatio = 1.1f, ClipContents = true };
|
||||
var backdrop = new ConnectBackdrop();
|
||||
backdrop.SetAnchorsPreset(LayoutPreset.FullRect);
|
||||
left.AddChild(backdrop);
|
||||
// titolo in basso a sinistra, sopra il velo della mappa
|
||||
var brand = new VBoxContainer { Alignment = BoxContainer.AlignmentMode.End };
|
||||
brand.AnchorLeft = 0;
|
||||
brand.AnchorRight = 1;
|
||||
brand.AnchorTop = 1;
|
||||
brand.AnchorBottom = 1;
|
||||
brand.OffsetLeft = 56;
|
||||
brand.OffsetRight = -56;
|
||||
brand.OffsetTop = -280;
|
||||
brand.OffsetBottom = -56;
|
||||
brand.AddThemeConstantOverride("separation", 6);
|
||||
brand.AddChild(UiTheme.TitleLabel("RAIL ENTERPRISE", 76, Palette.AmberLight));
|
||||
brand.AddChild(UiTheme.Text(T("Gestionale ferroviario dall'alto"), 20, Palette.Text));
|
||||
brand.AddChild(UiTheme.Text($"{T("Versione del gioco")} {ClientVersion}", 13, Palette.TextSecondary));
|
||||
left.AddChild(brand);
|
||||
split.AddChild(left);
|
||||
|
||||
// destra: dove gira il motore
|
||||
var right = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsStretchRatio = 0.9f };
|
||||
right.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 0, 40));
|
||||
split.AddChild(right);
|
||||
var scroll = new ScrollContainer { HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled };
|
||||
right.AddChild(scroll);
|
||||
var col = PanelKit.Column(14);
|
||||
col.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
col.SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||
scroll.AddChild(col);
|
||||
col.AddChild(UiTheme.TitleLabel(T("Dove gira il motore di gioco?"), 38));
|
||||
var lead = UiTheme.Text(T("Il mondo vive sempre in un server: sul tuo computer, avviato insieme al gioco, oppure in rete, dove la partita continua anche a gioco chiuso."), 14, Palette.TextSecondary);
|
||||
lead.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
col.AddChild(lead);
|
||||
|
||||
var modes = PanelKit.Row(12);
|
||||
var group = new ButtonGroup();
|
||||
ModeCard(_localCard, group, T("Gioca in locale"), T("Server su questo computer, avviato e chiuso con il gioco. Le partite restano qui."));
|
||||
ModeCard(_remoteCard, group, T("Connetti a un server"), T("Server dedicato in rete, per esempio in Docker su un NAS. Più giocatori, partita sempre accesa."));
|
||||
_localCard.Pressed += () => SetMode(local: true, start: true);
|
||||
_remoteCard.Pressed += () => SetMode(local: false, start: true);
|
||||
modes.AddChild(_localCard);
|
||||
modes.AddChild(_remoteCard);
|
||||
col.AddChild(modes);
|
||||
|
||||
// indirizzo e token del server in rete
|
||||
_remoteFields.AddThemeConstantOverride("separation", 8);
|
||||
var fields = PanelKit.Row(10);
|
||||
var addressCol = PanelKit.Column(4);
|
||||
addressCol.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
addressCol.AddChild(UiTheme.Text(T("Indirizzo (host:porta)"), 13, Palette.TextSecondary));
|
||||
addressCol.AddChild(_address);
|
||||
var tokenCol = PanelKit.Column(4);
|
||||
tokenCol.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
tokenCol.AddChild(UiTheme.Text(T("Token"), 13, Palette.TextSecondary));
|
||||
tokenCol.AddChild(_token);
|
||||
fields.AddChild(addressCol);
|
||||
fields.AddChild(tokenCol);
|
||||
_remoteFields.AddChild(fields);
|
||||
var probeRow = PanelKit.Row(10);
|
||||
_rememberBox.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
probeRow.AddChild(_rememberBox);
|
||||
_probe.Pressed += SubmitRemote;
|
||||
probeRow.AddChild(_probe);
|
||||
_remoteFields.AddChild(probeRow);
|
||||
_token.TextSubmitted += _ => SubmitRemote();
|
||||
col.AddChild(_remoteFields);
|
||||
|
||||
// stato del server
|
||||
var state = new PanelContainer();
|
||||
state.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, Palette.Border, 10, 18));
|
||||
var stateCol = PanelKit.Column(12);
|
||||
var stateHead = PanelKit.Row(10);
|
||||
stateHead.AddChild(_dot);
|
||||
stateHead.AddChild(_stateTitle);
|
||||
stateCol.AddChild(stateHead);
|
||||
_stateGrid.AddThemeConstantOverride("h_separation", 24);
|
||||
_stateGrid.AddThemeConstantOverride("v_separation", 12);
|
||||
for (int i = 0; i < 6; i++)
|
||||
{
|
||||
var cell = PanelKit.Column(2);
|
||||
cell.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
var caption = UiTheme.Text("", 12, Palette.TextSecondary);
|
||||
var value = UiTheme.Text("", 14, bold: true);
|
||||
value.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
cell.AddChild(caption);
|
||||
cell.AddChild(value);
|
||||
_stateGrid.AddChild(cell);
|
||||
_stateCells.Add((caption, value));
|
||||
}
|
||||
stateCol.AddChild(_stateGrid);
|
||||
state.AddChild(stateCol);
|
||||
col.AddChild(state);
|
||||
|
||||
// partite salvate sul server: nome, data di gioco, quanto tempo fa
|
||||
col.AddChild(UiTheme.Text(T("Partite salvate sul server"), 17, bold: true));
|
||||
_saves.SetColumnExpand(0, true);
|
||||
_saves.SetColumnExpandRatio(0, 3);
|
||||
_saves.SetColumnExpand(1, true);
|
||||
_saves.SetColumnExpandRatio(1, 2);
|
||||
_saves.SetColumnExpand(2, true);
|
||||
_saves.SetColumnExpandRatio(2, 1);
|
||||
_saves.ItemSelected += () =>
|
||||
{
|
||||
if (_saves.GetSelected() is { } item) _selectedSave = item.GetMetadata(0).AsString();
|
||||
};
|
||||
_saves.ItemActivated += Resume;
|
||||
col.AddChild(_saves);
|
||||
var actions = PanelKit.Row(10);
|
||||
_resume.CustomMinimumSize = new Vector2(0, 48);
|
||||
_resume.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
_resume.Pressed += Resume;
|
||||
actions.AddChild(_resume);
|
||||
_newGame.CustomMinimumSize = new Vector2(0, 48);
|
||||
_newGame.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
_newGame.Pressed += NewGameOnServer;
|
||||
actions.AddChild(_newGame);
|
||||
col.AddChild(actions);
|
||||
var tutorialRow = PanelKit.Row(10);
|
||||
_showTutorial.ButtonPressed = !TutorialSettings.Played;
|
||||
_showTutorial.TooltipText = T("Guida passo per passo alla prima linea: si chiude quando vuoi e si riapre con F1");
|
||||
_showTutorial.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
tutorialRow.AddChild(_showTutorial);
|
||||
_tutorial.TooltipText = T("Nuova partita locale di prova con il tutorial dal primo passo: la tua partita locale resta com'è");
|
||||
_tutorial.CustomMinimumSize = new Vector2(160, 40);
|
||||
_tutorial.Pressed += () =>
|
||||
{
|
||||
if (_busy) return;
|
||||
// da qui la schermata non avvia né riprende altro: Main apre la partita di prova
|
||||
_busy = true;
|
||||
_tutorial.Disabled = true;
|
||||
TutorialRequested?.Invoke();
|
||||
};
|
||||
tutorialRow.AddChild(_tutorial);
|
||||
col.AddChild(tutorialRow);
|
||||
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
col.AddChild(_status);
|
||||
col.AddChild(UiTheme.Notice(T("La connessione non è cifrata: per Internet usa un reverse proxy con TLS (wss://).")));
|
||||
|
||||
var cfg = new ConfigFile();
|
||||
if (cfg.Load(SettingsPath) == Error.Ok)
|
||||
// piede: lingua, audio, uscita, avviso sulla cifratura
|
||||
var foot = PanelKit.Row(8);
|
||||
foreach (var (code, label) in new[] { ("it", "Italiano"), ("en", "English") })
|
||||
{
|
||||
_address.Text = (string)cfg.GetValue("server", "address", "");
|
||||
_token.Text = (string)cfg.GetValue("server", "token", "");
|
||||
var b = new Button { Text = label, ToggleMode = true, ButtonPressed = TranslationServer.GetLocale().StartsWith(code) };
|
||||
b.Pressed += () => LanguageChanged?.Invoke(code);
|
||||
foot.AddChild(b);
|
||||
}
|
||||
_token.TextSubmitted += _ => Submit();
|
||||
var audio = new Button { Text = T("Audio") };
|
||||
audio.Pressed += () => AudioRequested?.Invoke();
|
||||
foot.AddChild(audio);
|
||||
foot.AddChild(new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill });
|
||||
var quit = new Button { Text = T("Esci"), CustomMinimumSize = new Vector2(100, 0) };
|
||||
quit.Pressed += () => GetTree().Quit();
|
||||
foot.AddChild(quit);
|
||||
col.AddChild(foot);
|
||||
var notice = UiTheme.Text(T("La connessione non è cifrata: per Internet usa un reverse proxy con TLS (wss://)."), 12, Palette.TextSecondary);
|
||||
notice.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
col.AddChild(notice);
|
||||
|
||||
// conferma prima di sostituire la partita sul server
|
||||
_confirm.OkButtonText = T("Sostituisci la partita");
|
||||
_confirm.CancelButtonText = T("Annulla");
|
||||
_confirm.Confirmed += () =>
|
||||
{
|
||||
var action = _onConfirm;
|
||||
_onConfirm = null;
|
||||
action?.Invoke();
|
||||
};
|
||||
_confirm.Canceled += () => _onConfirm = null;
|
||||
AddChild(_confirm);
|
||||
|
||||
bool remote = false;
|
||||
if (_remember)
|
||||
{
|
||||
var cfg = new ConfigFile();
|
||||
if (cfg.Load(SettingsPath) == Error.Ok)
|
||||
{
|
||||
_address.Text = (string)cfg.GetValue("server", "address", "");
|
||||
_token.Text = (string)cfg.GetValue("server", "token", "");
|
||||
remote = (string)cfg.GetValue("server", "mode", "local") == "remote";
|
||||
}
|
||||
}
|
||||
if (_handover is not null)
|
||||
{
|
||||
// cambio di lingua: la sessione di prova (e il suo server locale) passa a questa schermata
|
||||
var session = _handover;
|
||||
_handover = null;
|
||||
SetMode(local: session.LocalServer is not null, start: false);
|
||||
Attach(session);
|
||||
}
|
||||
else
|
||||
{
|
||||
// all'apertura si avvia la strada scelta l'ultima volta, come nell'immagine 09
|
||||
SetMode(local: !remote, start: _autoStart);
|
||||
}
|
||||
ShowState();
|
||||
}
|
||||
|
||||
public void SetStatus(string text, bool busy)
|
||||
private static void ModeCard(Button card, ButtonGroup group, string title, string text)
|
||||
{
|
||||
_status.Text = text;
|
||||
_connect.Disabled = busy;
|
||||
card.ButtonGroup = group;
|
||||
card.AddThemeStyleboxOverride("normal", UiTheme.Box(Palette.Inner, Palette.Border, 10, 0));
|
||||
card.AddThemeStyleboxOverride("hover", UiTheme.Box(Palette.Inner, Palette.AmberDark, 10, 0));
|
||||
card.AddThemeStyleboxOverride("pressed", UiTheme.Box(Palette.AmberDark, Palette.Amber, 10, 0));
|
||||
card.AddThemeStyleboxOverride("hover_pressed", UiTheme.Box(Palette.AmberDark, Palette.Amber, 10, 0));
|
||||
card.AddThemeStyleboxOverride("disabled", UiTheme.Box(Palette.Inner, Palette.Border, 10, 0));
|
||||
var margin = new MarginContainer { MouseFilter = MouseFilterEnum.Ignore };
|
||||
margin.SetAnchorsPreset(LayoutPreset.FullRect);
|
||||
foreach (var side in new[] { "left", "right", "top", "bottom" }) margin.AddThemeConstantOverride("margin_" + side, 16);
|
||||
var col = PanelKit.Column(6);
|
||||
col.MouseFilter = MouseFilterEnum.Ignore;
|
||||
var t = UiTheme.Text(title, 17, Palette.AmberLight, bold: true);
|
||||
var d = UiTheme.Text(text, 12, Palette.TextSecondary);
|
||||
d.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
t.MouseFilter = d.MouseFilter = MouseFilterEnum.Ignore;
|
||||
col.AddChild(t);
|
||||
col.AddChild(d);
|
||||
margin.AddChild(col);
|
||||
card.AddChild(margin);
|
||||
}
|
||||
|
||||
private void Submit()
|
||||
private static string ClientVersion =>
|
||||
typeof(ConnectScreen).Assembly.GetName().Version?.ToString(3) ?? "0.0.0";
|
||||
|
||||
// ------------------------------------------------------------------ modalità e sessione di prova
|
||||
|
||||
/// <summary>La sessione di prova è della strada scelta: server locale figlio del gioco o server in rete.</summary>
|
||||
private bool SessionMatchesMode => _session is not null && (_session.LocalServer is not null) == _local;
|
||||
|
||||
/// <summary>
|
||||
/// Cambia strada. La sessione dell'altra strada si chiude (e con lei il server locale), così
|
||||
/// «Connetti e riprendi» non apre mai la partita della strada non scelta. Con start si avvia il
|
||||
/// server locale o si verifica il server in rete indicato.
|
||||
/// </summary>
|
||||
private void SetMode(bool local, bool start)
|
||||
{
|
||||
_local = local;
|
||||
_localCard.SetPressedNoSignal(local);
|
||||
_remoteCard.SetPressedNoSignal(!local);
|
||||
_remoteFields.Visible = !local;
|
||||
if (_session is not null && !SessionMatchesMode)
|
||||
{
|
||||
_ = Release();
|
||||
SetStatus("");
|
||||
}
|
||||
if (_remember)
|
||||
{
|
||||
var cfg = new ConfigFile();
|
||||
cfg.Load(SettingsPath);
|
||||
cfg.SetValue("server", "mode", local ? "local" : "remote");
|
||||
cfg.Save(SettingsPath);
|
||||
}
|
||||
if (start && _session is null && !_busy)
|
||||
{
|
||||
if (local) _ = StartLocal();
|
||||
else if (_address.Text.Trim().Length > 0) SubmitRemote();
|
||||
}
|
||||
ShowState();
|
||||
}
|
||||
|
||||
/// <summary>Avvia il server locale figlio del gioco e apre la sessione di prova.</summary>
|
||||
private async Task StartLocal()
|
||||
{
|
||||
if (_busy) return;
|
||||
string? server = LocalServerLauncher.FindServer();
|
||||
if (server is null)
|
||||
{
|
||||
_resumeAfterConnect = false;
|
||||
SetStatus(T("Server locale non trovato: compila src/RailEnterprise.Server o imposta RE_SERVER_PATH."), error: true);
|
||||
return;
|
||||
}
|
||||
await Release();
|
||||
_busy = true;
|
||||
SetStatus(T("Avvio del server locale…"));
|
||||
ShowState();
|
||||
var launcher = new LocalServerLauncher();
|
||||
try
|
||||
{
|
||||
int port = await launcher.StartAsync(server, ProjectSettings.GlobalizePath("user://server"), TimeSpan.FromSeconds(60));
|
||||
var session = await GameSession.ConnectAsync(_data, new Uri($"ws://127.0.0.1:{port}/ws"), launcher.Token, T("Partita locale"));
|
||||
session.LocalServer = launcher;
|
||||
_busy = false;
|
||||
if (!Adopt(session, local: true)) return;
|
||||
SetStatus("");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
launcher.Dispose();
|
||||
_busy = false;
|
||||
_resumeAfterConnect = false;
|
||||
if (!_closed) SetStatus($"{T("Partita locale non avviata")}: {e.Message}", error: true);
|
||||
}
|
||||
if (!_closed) ShowState();
|
||||
}
|
||||
|
||||
private void SubmitRemote()
|
||||
{
|
||||
string address = _address.Text.Trim();
|
||||
if (address.Length == 0)
|
||||
{
|
||||
SetStatus(T("Indica l'indirizzo del server"), false);
|
||||
_resumeAfterConnect = false;
|
||||
SetStatus(T("Indica l'indirizzo del server"), error: true);
|
||||
return;
|
||||
}
|
||||
string url = address.Contains("://") ? address : $"ws://{address}";
|
||||
if (!url.EndsWith("/ws", StringComparison.Ordinal)) url = url.TrimEnd('/') + "/ws";
|
||||
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
|
||||
{
|
||||
SetStatus(T("Indirizzo non valido"), false);
|
||||
_resumeAfterConnect = false;
|
||||
SetStatus(T("Indirizzo non valido"), error: true);
|
||||
return;
|
||||
}
|
||||
var cfg = new ConfigFile();
|
||||
cfg.Load(SettingsPath);
|
||||
cfg.SetValue("server", "address", address);
|
||||
cfg.SetValue("server", "token", _token.Text);
|
||||
cfg.Save(SettingsPath);
|
||||
ConnectRequested?.Invoke(uri, _token.Text, uri.Host);
|
||||
if (_remember)
|
||||
{
|
||||
var cfg = new ConfigFile();
|
||||
cfg.Load(SettingsPath);
|
||||
cfg.SetValue("server", "address", _rememberBox.ButtonPressed ? address : "");
|
||||
cfg.SetValue("server", "token", _rememberBox.ButtonPressed ? _token.Text : "");
|
||||
cfg.Save(SettingsPath);
|
||||
}
|
||||
_ = ProbeRemote(uri, _token.Text);
|
||||
}
|
||||
|
||||
/// <summary>Collega la sessione di prova a un server in rete (dal pulsante o dal collaudo).</summary>
|
||||
public async Task ProbeRemote(Uri uri, string token)
|
||||
{
|
||||
if (_busy) return;
|
||||
SetMode(local: false, start: false);
|
||||
await Release();
|
||||
_busy = true;
|
||||
SetStatus(T("Collegamento in corso…"));
|
||||
ShowState();
|
||||
try
|
||||
{
|
||||
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
|
||||
var session = await GameSession.ConnectAsync(_data, uri, token, uri.Host, cts.Token);
|
||||
_busy = false;
|
||||
if (!Adopt(session, local: false)) return;
|
||||
SetStatus("");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_busy = false;
|
||||
_resumeAfterConnect = false;
|
||||
if (!_closed) SetStatus($"{T("Collegamento non riuscito")}: {e.Message}", error: true);
|
||||
}
|
||||
if (!_closed) ShowState();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Prende la sessione appena aperta, se la schermata è ancora aperta e sulla stessa strada;
|
||||
/// altrimenti la chiude (con il suo server locale). Con «Connetti e riprendi» in attesa si entra
|
||||
/// subito in partita.
|
||||
/// </summary>
|
||||
private bool Adopt(GameSession session, bool local)
|
||||
{
|
||||
if (_closed || _local != local)
|
||||
{
|
||||
_resumeAfterConnect = false;
|
||||
_ = session.DisposeAsync();
|
||||
return false;
|
||||
}
|
||||
Attach(session);
|
||||
if (_resumeAfterConnect)
|
||||
{
|
||||
_resumeAfterConnect = false;
|
||||
Play();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void Attach(GameSession session)
|
||||
{
|
||||
_session = session;
|
||||
_shownSaves = null;
|
||||
_sinceSaves = double.MaxValue;
|
||||
_session.MessageApplied += OnMessage;
|
||||
}
|
||||
|
||||
/// <summary>Chiude la sessione di prova (e il server locale, se è suo).</summary>
|
||||
private async Task Release()
|
||||
{
|
||||
var s = _session;
|
||||
_session = null;
|
||||
_shownSaves = null;
|
||||
_awaitingWelcome = null;
|
||||
if (s is null) return;
|
||||
s.MessageApplied -= OnMessage;
|
||||
await s.DisposeAsync();
|
||||
}
|
||||
|
||||
/// <summary>Consegna la sessione di prova a chi la chiede (Main: partita, cambio di lingua, chiusura del gioco).</summary>
|
||||
public GameSession? TakeSession()
|
||||
{
|
||||
var s = _session;
|
||||
if (s is not null) s.MessageApplied -= OnMessage;
|
||||
_session = null;
|
||||
_awaitingWelcome = null;
|
||||
return s;
|
||||
}
|
||||
|
||||
public override void _ExitTree()
|
||||
{
|
||||
// una connessione ancora in corso si chiude da sola quando arriva (Adopt)
|
||||
_closed = true;
|
||||
if (_session is not null) _ = Release();
|
||||
}
|
||||
|
||||
private void OnMessage(IMessage m) => _awaitingWelcome?.Invoke(m);
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
if (_session is null) return;
|
||||
_session.Poll();
|
||||
if (_session is null) return; // Play durante Poll: la sessione è passata alla partita
|
||||
if (!_session.IsOpen)
|
||||
{
|
||||
SetStatus(T("Il server ha chiuso la connessione"), error: true);
|
||||
_ = Release();
|
||||
ShowState();
|
||||
return;
|
||||
}
|
||||
_sinceSaves += delta;
|
||||
if (_awaitingWelcome is not null && (_waiting += delta) > WelcomeTimeoutS)
|
||||
{
|
||||
_awaitingWelcome = null;
|
||||
SetStatus(T("Il server non ha risposto"), error: true);
|
||||
}
|
||||
if (_sinceSaves >= SavesRefreshS && _awaitingWelcome is null)
|
||||
{
|
||||
_sinceSaves = 0;
|
||||
_session.Send(new ListSaves());
|
||||
}
|
||||
if (!ReferenceEquals(_session.World.Saves, _shownSaves)) ShowSaves();
|
||||
ShowState();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ azioni
|
||||
|
||||
private void Resume()
|
||||
{
|
||||
if (_busy || _awaitingWelcome is not null) return;
|
||||
if (_session is null)
|
||||
{
|
||||
// nessuna sessione ancora: «Connetti e riprendi» apre la strada scelta ed entra in partita
|
||||
_resumeAfterConnect = true;
|
||||
if (_local) _ = StartLocal();
|
||||
else SubmitRemote();
|
||||
return;
|
||||
}
|
||||
if (!SessionMatchesMode) return;
|
||||
string id = _selectedSave;
|
||||
var save = _shownSaves?.Saves.FirstOrDefault(s => s.SaveId == id);
|
||||
if (id == CurrentGame || save is null)
|
||||
{
|
||||
Play();
|
||||
return;
|
||||
}
|
||||
Confirm(string.Format(T("Il server sostituirà la partita in corso ({0}) con il salvataggio «{1}» per tutti i client collegati ({2}). Quello che non è stato salvato andrà perso."),
|
||||
CurrentGameText(), save.Name, ConnectedText()), () =>
|
||||
{
|
||||
if (_session is null || _awaitingWelcome is not null) return;
|
||||
SetStatus($"{T("Caricamento di")} {save.Name}…");
|
||||
AwaitWelcome();
|
||||
_session.Send(new Load { SaveId = id });
|
||||
});
|
||||
}
|
||||
|
||||
private void NewGameOnServer()
|
||||
{
|
||||
if (_session is null || _awaitingWelcome is not null || !SessionMatchesMode) return;
|
||||
Confirm(string.Format(T("Il server sostituirà la partita in corso ({0}) con una partita nuova per tutti i client collegati ({1}). Quello che non è stato salvato andrà perso."),
|
||||
CurrentGameText(), ConnectedText()), () =>
|
||||
{
|
||||
if (_session is null || _awaitingWelcome is not null) return;
|
||||
var summary = _session.World.Summary;
|
||||
SetStatus(T("Creazione della nuova partita sul server…"));
|
||||
AwaitWelcome();
|
||||
// il seme lo sceglie il client: la generazione resta deterministica sul server
|
||||
_session.Send(new NewGame { Seed = (ulong)Time.GetUnixTimeFromSystem() ^ (summary?.Seed ?? 0), SizeKm = summary?.SizeKm ?? 0, DifficultyPreset = _session.Difficulty });
|
||||
});
|
||||
}
|
||||
|
||||
private void Confirm(string text, Action action)
|
||||
{
|
||||
_onConfirm = action;
|
||||
_confirm.DialogText = text;
|
||||
_confirm.PopupCentered();
|
||||
}
|
||||
|
||||
private string CurrentGameText()
|
||||
{
|
||||
var summary = _session?.World.Summary;
|
||||
return summary is null ? "—" : $"{summary.CompanyName}, {summary.Date}";
|
||||
}
|
||||
|
||||
private string ConnectedText()
|
||||
{
|
||||
var info = _session?.World.Server;
|
||||
return info is null ? "?" : info.Sessions.ToString();
|
||||
}
|
||||
|
||||
/// <summary>Dopo Load o NewGame il server rimanda il Welcome a tutti: allora si entra in partita.</summary>
|
||||
private void AwaitWelcome()
|
||||
{
|
||||
_awaitingWelcome = m =>
|
||||
{
|
||||
if (m is Welcome)
|
||||
{
|
||||
_awaitingWelcome = null;
|
||||
Play();
|
||||
}
|
||||
else if (m is Notification { Event.Day: < 0 } note)
|
||||
{
|
||||
// caricamento o creazione rifiutati: l'avviso del server ha il giorno −1; gli eventi
|
||||
// del mondo (giorno della partita) arrivano anche qui e non interrompono l'attesa
|
||||
_awaitingWelcome = null;
|
||||
SetStatus(note.Event.Text, error: true);
|
||||
}
|
||||
};
|
||||
_waiting = 0;
|
||||
}
|
||||
|
||||
private void Play()
|
||||
{
|
||||
var s = TakeSession();
|
||||
if (s is not null) PlayRequested?.Invoke(s);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ stato
|
||||
|
||||
public void SetStatus(string text, bool error = false)
|
||||
{
|
||||
_status.Text = text;
|
||||
_status.AddThemeColorOverride("font_color", error ? Palette.Danger : Palette.TextSecondary);
|
||||
}
|
||||
|
||||
private void ShowState()
|
||||
{
|
||||
var info = _session?.World.Server;
|
||||
var summary = _session?.World.Summary;
|
||||
double now = Time.GetTicksMsec() / 1000.0;
|
||||
if (!ReferenceEquals(info, _infoSeen))
|
||||
{
|
||||
_infoSeen = info;
|
||||
_infoAt = now;
|
||||
}
|
||||
string title;
|
||||
Color dot;
|
||||
if (_busy)
|
||||
{
|
||||
title = _local ? T("Avvio del server locale…") : T("Collegamento in corso…");
|
||||
dot = Palette.Amber;
|
||||
}
|
||||
else if (_session is not null)
|
||||
{
|
||||
title = $"{T("Server raggiungibile")} · {_session.ServerLabel}";
|
||||
dot = Palette.Ok;
|
||||
}
|
||||
else
|
||||
{
|
||||
title = _local ? T("Server locale spento: «Connetti e riprendi» lo avvia") : T("Non collegato");
|
||||
dot = Palette.TextSecondary;
|
||||
}
|
||||
_stateTitle.Text = title;
|
||||
_dot.Color = dot;
|
||||
var cells = new (string, string)[]
|
||||
{
|
||||
(T("Versione"), info is null ? "—" : $"{info.Version}, {T("protocollo")} {Frame.ProtocolVersion}"),
|
||||
(T("Sistema"), info is null ? "—" : info.Os + (info.Container ? " · Docker" : "") + (info.Local ? " · " + T("locale") : "")),
|
||||
(T("Attivo da"), info is null ? "—" : Uptime(info.UptimeSeconds + (long)(now - _infoAt))),
|
||||
(T("Simulazione"), info is null || info.TickMs <= 0 ? "—" : $"{Fmt.Number(1000 / info.TickMs, 0)} {T("tick al secondo")}" + (summary is null ? "" : $" · {summary.Date}")),
|
||||
(T("Latenza"), _session is null || _session.LatencyMs <= 0 ? "—" : $"{Fmt.Number(_session.LatencyMs, 0)} ms"),
|
||||
(T("Client collegati"), info is null ? "—" : $"{info.Sessions} / {info.MaxSessions}"),
|
||||
};
|
||||
for (int i = 0; i < cells.Length && i < _stateCells.Count; i++)
|
||||
{
|
||||
_stateCells[i].Caption.Text = cells[i].Item1;
|
||||
_stateCells[i].Value.Text = cells[i].Item2;
|
||||
}
|
||||
bool ready = SessionMatchesMode && !_busy && _awaitingWelcome is null;
|
||||
// senza sessione «Connetti e riprendi» apre la connessione; «Nuova partita» vuole il server collegato
|
||||
_resume.Disabled = _busy || _awaitingWelcome is not null || (_session is not null && !ready);
|
||||
_newGame.Disabled = !ready;
|
||||
_probe.Disabled = _busy;
|
||||
_tutorial.Disabled = _busy;
|
||||
_localCard.Disabled = _busy;
|
||||
_remoteCard.Disabled = _busy;
|
||||
}
|
||||
|
||||
/// <summary>Elenco ricostruito a ogni aggiornamento: la riga scelta si ritrova per id, non per posizione.</summary>
|
||||
private void ShowSaves()
|
||||
{
|
||||
var w = _session!.World;
|
||||
_shownSaves = w.Saves;
|
||||
_saves.Clear();
|
||||
var root = _saves.CreateItem();
|
||||
var current = _saves.CreateItem(root);
|
||||
current.SetText(0, $"{T("Partita in corso")} · {w.Summary?.CompanyName ?? ""}");
|
||||
current.SetText(1, w.Summary?.Date ?? "");
|
||||
current.SetText(2, T("in corso"));
|
||||
current.SetMetadata(0, CurrentGame);
|
||||
current.SetCustomColor(2, Palette.Ok);
|
||||
TreeItem selected = current;
|
||||
double now = Time.GetUnixTimeFromSystem();
|
||||
foreach (var s in (_shownSaves?.Saves ?? []).OrderByDescending(s => s.SavedUnixMs).ThenBy(s => s.SaveId, StringComparer.Ordinal))
|
||||
{
|
||||
var item = _saves.CreateItem(root);
|
||||
item.SetText(0, s.Autosave ? $"{s.Name} ({T("automatico")})" : s.Name);
|
||||
item.SetText(1, s.GameDate);
|
||||
item.SetText(2, Ago(now - s.SavedUnixMs / 1000.0));
|
||||
item.SetMetadata(0, s.SaveId);
|
||||
for (int c = 1; c < 3; c++) item.SetCustomColor(c, Palette.TextSecondary);
|
||||
if (s.SaveId == _selectedSave) selected = item;
|
||||
}
|
||||
// salvataggio scelto sparito dall'elenco: si torna alla partita in corso
|
||||
_selectedSave = selected.GetMetadata(0).AsString();
|
||||
selected.Select(0);
|
||||
}
|
||||
|
||||
private static string Uptime(long seconds)
|
||||
{
|
||||
if (seconds < 3600) return $"{Math.Max(1, seconds / 60)} min";
|
||||
if (seconds < 86_400) return $"{seconds / 3600} h {seconds % 3600 / 60} min";
|
||||
return $"{seconds / 86_400} {T("giorni")} {seconds % 86_400 / 3600} h";
|
||||
}
|
||||
|
||||
private static string Ago(double seconds)
|
||||
{
|
||||
if (seconds < 90) return T("adesso");
|
||||
if (seconds < 3600) return $"{(int)(seconds / 60)} {T("minuti fa")}";
|
||||
if (seconds < 86_400) return $"{(int)(seconds / 3600)} {T("ore fa")}";
|
||||
return $"{(int)(seconds / 86_400)} {T("giorni fa")}";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mappa decorativa della schermata iniziale: pianura, un fiume, una linea a doppio binario con
|
||||
/// stazioni e i tetti dei paesi, disegnati in codice con la palette della mappa (immagine 05) e
|
||||
/// velati verso il basso per il titolo. Solo grafica: nessun dato di gioco.
|
||||
/// </summary>
|
||||
public partial class ConnectBackdrop : Control
|
||||
{
|
||||
public override void _Draw()
|
||||
{
|
||||
var size = Size;
|
||||
DrawRect(new Rect2(Vector2.Zero, size), Palette.Plain);
|
||||
// colline e boschi a macchie, posizioni fisse in frazioni della superficie
|
||||
foreach (var (x, y, r, c) in new[] { (0.15f, 0.2f, 0.16f, Palette.Hill), (0.7f, 0.15f, 0.2f, Palette.Highland), (0.85f, 0.55f, 0.14f, Palette.Undergrowth),
|
||||
(0.3f, 0.6f, 0.12f, Palette.Undergrowth), (0.55f, 0.35f, 0.07f, Palette.Canopy), (0.1f, 0.45f, 0.06f, Palette.Canopy), (0.62f, 0.72f, 0.05f, Palette.Canopy) })
|
||||
DrawCircle(new Vector2(x * size.X, y * size.Y), r * Math.Max(size.X, size.Y), c);
|
||||
// fiume
|
||||
var river = new Vector2[] { new(0.62f, 0f), new(0.58f, 0.18f), new(0.66f, 0.36f), new(0.6f, 0.55f), new(0.7f, 0.78f), new(0.66f, 1f) };
|
||||
DrawPolyline(river.Select(p => p * size).ToArray(), Palette.Banks, 30, true);
|
||||
DrawPolyline(river.Select(p => p * size).ToArray(), Palette.Water, 20, true);
|
||||
// linea ferroviaria: massicciata, traversine, rotaie
|
||||
var rail = new Vector2[] { new(-0.05f, 0.42f), new(0.25f, 0.38f), new(0.48f, 0.44f), new(0.75f, 0.4f), new(1.05f, 0.3f) };
|
||||
var pts = rail.Select(p => p * size).ToArray();
|
||||
DrawPolyline(pts, Palette.Ballast, 16, true);
|
||||
for (int i = 0; i < pts.Length - 1; i++)
|
||||
{
|
||||
var a = pts[i];
|
||||
var b = pts[i + 1];
|
||||
var dir = (b - a).Normalized();
|
||||
var n = new Vector2(-dir.Y, dir.X) * 7;
|
||||
for (float t = 0; t < a.DistanceTo(b); t += 9)
|
||||
{
|
||||
var p = a + dir * t;
|
||||
DrawLine(p - n, p + n, Palette.Sleepers, 3);
|
||||
}
|
||||
}
|
||||
foreach (float off in new[] { -3.5f, 3.5f })
|
||||
DrawPolyline(pts.Select((p, i) => p + Normal(pts, i) * off).ToArray(), Palette.Rails, 1.5f, true);
|
||||
// stazioni e paesi
|
||||
foreach (var (x, y) in new[] { (0.25f, 0.38f), (0.75f, 0.4f) })
|
||||
{
|
||||
var c = new Vector2(x * size.X, y * size.Y);
|
||||
DrawRect(new Rect2(c - new Vector2(22, 26), new Vector2(44, 14)), Palette.Panel);
|
||||
for (int k = 0; k < 9; k++)
|
||||
{
|
||||
var roof = c + new Vector2((k % 3 - 1) * 26 + (k * 7 % 5), 28 + k / 3 * 20);
|
||||
DrawRect(new Rect2(roof, new Vector2(16, 12)), k % 4 == 0 ? Palette.IndustrialRoof : Palette.TileRoof);
|
||||
}
|
||||
}
|
||||
// velo verso il basso per leggere il titolo
|
||||
var veil = new Color[] { Palette.WithAlpha(Palette.AppBackground, 0.15f), Palette.WithAlpha(Palette.AppBackground, 0.15f), Palette.WithAlpha(Palette.AppBackground, 0.92f), Palette.WithAlpha(Palette.AppBackground, 0.92f) };
|
||||
DrawPolygon([new Vector2(0, size.Y * 0.35f), new Vector2(size.X, size.Y * 0.35f), new Vector2(size.X, size.Y), new Vector2(0, size.Y)], veil);
|
||||
}
|
||||
|
||||
private static Vector2 Normal(Vector2[] pts, int i)
|
||||
{
|
||||
var dir = (pts[Math.Min(i + 1, pts.Length - 1)] - pts[Math.Max(i - 1, 0)]).Normalized();
|
||||
return new Vector2(-dir.Y, dir.X);
|
||||
}
|
||||
|
||||
public override void _Notification(int what)
|
||||
{
|
||||
if (what == NotificationResized) QueueRedraw();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
using RailEnterprise.Client.Audio;
|
||||
using RailEnterprise.Client.Hud;
|
||||
using RailEnterprise.Client.Map;
|
||||
using RailEnterprise.Client.Net;
|
||||
@@ -43,6 +44,9 @@ public partial class GameScreen : Node
|
||||
private IndustryPanel? _industryPanel;
|
||||
private CompaniesPanel? _companies;
|
||||
private MarketPanel? _market;
|
||||
private ClimbPanel? _climb;
|
||||
private FinancePanel? _finance;
|
||||
private TrainsPanel? _trainsPanel;
|
||||
// pannelli a tutto schermo (Compagnie e borsa, Mercato globale): coprono mappa e pannello destro, la barra resta
|
||||
private readonly PanelContainer _full = new() { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, Visible = false };
|
||||
private Control? _mapArea;
|
||||
@@ -69,6 +73,12 @@ public partial class GameScreen : Node
|
||||
public GameSession Session => _session;
|
||||
public MapView Map => _map;
|
||||
|
||||
/// <summary>Strumento o pannello aperto dalla barra.</summary>
|
||||
public Tool CurrentTool => _tool;
|
||||
|
||||
/// <summary>Anteprime del tracciato mostrate finora (il tutorial le usa per «guarda il profilo»).</summary>
|
||||
public int TrackPreviews { get; private set; }
|
||||
|
||||
/// <summary>Seleziona uno strumento come dalla barra (anche per il pilota automatico).</summary>
|
||||
public void UseTool(Tool tool) => _toolbar.Select(tool);
|
||||
|
||||
@@ -96,7 +106,7 @@ public partial class GameScreen : Node
|
||||
_maintenance?.SelectDepot(depot);
|
||||
}
|
||||
|
||||
/// <summary>Apre il pannello Industrie sull'industria indicata (scheda del proprietario).</summary>
|
||||
/// <summary>Apre la scheda dell'industria a tutto schermo (immagine 07) sull'industria indicata.</summary>
|
||||
public void OpenIndustry(int industry)
|
||||
{
|
||||
if (_tool != Tool.Industries) _toolbar.Select(Tool.Industries);
|
||||
@@ -117,6 +127,21 @@ public partial class GameScreen : Node
|
||||
if (good >= 0) _market?.Select(good);
|
||||
}
|
||||
|
||||
/// <summary>Apre «La tua scalata» a tutto schermo (dal pulsante o dal livello nella barra superiore).</summary>
|
||||
public void OpenClimb()
|
||||
{
|
||||
if (_tool != Tool.Climb) _toolbar.Select(Tool.Climb);
|
||||
}
|
||||
|
||||
/// <summary>Chiude lo strumento o la schermata a tutto schermo aperta e torna alla mappa.</summary>
|
||||
public void CloseTools() => _toolbar.Select(Tool.None);
|
||||
|
||||
/// <summary>Apre le «Finanze» a tutto schermo: conto economico, rating e prestiti.</summary>
|
||||
public void OpenFinance()
|
||||
{
|
||||
if (_tool != Tool.Finance) _toolbar.Select(Tool.Finance);
|
||||
}
|
||||
|
||||
/// <summary>Dal Mercato globale: strumento binari con la mappa centrata sull'hub da collegare.</summary>
|
||||
private void PlanLineToHub(int hub)
|
||||
{
|
||||
@@ -128,6 +153,17 @@ public partial class GameScreen : Node
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Dalla scheda dell'industria: strumento binari con la mappa centrata sull'industria da collegare.</summary>
|
||||
private void PlanLineToIndustry(int industry)
|
||||
{
|
||||
_toolbar.Select(Tool.Track);
|
||||
if (_session.World.Industries.TryGetValue(industry, out var ind))
|
||||
{
|
||||
_map.CenterOn(MapScale.V(ind.Position));
|
||||
_map.SetZoom(0.3f);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Chiede al server la Cronaca (provvisoria a partita in corso) e la mostra all'arrivo.</summary>
|
||||
public void OpenChronicle()
|
||||
{
|
||||
@@ -147,6 +183,11 @@ public partial class GameScreen : Node
|
||||
/// <summary>Scorre il pannello laterale (0 = in cima, 1 = in fondo).</summary>
|
||||
public void ScrollPanel(double fraction)
|
||||
{
|
||||
if (_industryPanel is not null)
|
||||
{
|
||||
_industryPanel.ScrollTo(fraction);
|
||||
return;
|
||||
}
|
||||
var bar = _scroll.GetVScrollBar();
|
||||
_scroll.ScrollVertical = (int)Math.Round((bar.MaxValue - bar.Page) * Math.Clamp(fraction, 0, 1));
|
||||
}
|
||||
@@ -180,12 +221,7 @@ public partial class GameScreen : Node
|
||||
var mapArea = new Control { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, MouseFilter = Control.MouseFilterEnum.Ignore };
|
||||
middle.AddChild(mapArea);
|
||||
_mapArea = mapArea;
|
||||
_toasts.SetAnchorsPreset(Control.LayoutPreset.TopWide);
|
||||
_toasts.OffsetLeft = 16;
|
||||
_toasts.OffsetRight = -16;
|
||||
_toasts.OffsetTop = 12;
|
||||
_toasts.MouseFilter = Control.MouseFilterEnum.Ignore;
|
||||
mapArea.AddChild(_toasts);
|
||||
var side = new PanelContainer { CustomMinimumSize = new Vector2(440, 0) };
|
||||
side.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 0, 18));
|
||||
middle.AddChild(side);
|
||||
@@ -211,13 +247,23 @@ public partial class GameScreen : Node
|
||||
sideCol.AddChild(miniHeader);
|
||||
sideCol.AddChild(_minimap);
|
||||
root.AddChild(_ticker);
|
||||
// avvisi sopra tutta l'interfaccia, in alto sull'area visibile: la mappa o la schermata a
|
||||
// tutto schermo (con la mappa nascosta un avviso dentro di lei non si vedrebbe)
|
||||
hud.AddChild(_toasts);
|
||||
|
||||
BuildDisconnectedOverlay(hud);
|
||||
AddChild(_overlay);
|
||||
// tooltip «perché» sopra tutta l'interfaccia (ADR 0024)
|
||||
var why = new CanvasLayer { Layer = 10 };
|
||||
AddChild(why);
|
||||
var whyTooltip = new WhyTooltip(_session);
|
||||
UiTheme.Apply(whyTooltip);
|
||||
why.AddChild(whyTooltip);
|
||||
|
||||
_map.Bind(_session);
|
||||
_minimap.Bind(_session.World, _map);
|
||||
_top.Bind(_session);
|
||||
_top.ClimbRequested += OpenClimb;
|
||||
_toolbar.Selected += SelectTool;
|
||||
_map.Clicked += OnMapClicked;
|
||||
_map.Hovered += OnMapHovered;
|
||||
@@ -225,13 +271,18 @@ public partial class GameScreen : Node
|
||||
_session.MessageApplied += OnMessage;
|
||||
_session.Notified += e => _ticker.Add(e);
|
||||
_session.CommandFailed += r => Toast(r.Message, error: true);
|
||||
AudioManager.Instance?.Bind(_session, _map);
|
||||
SelectTool(Tool.None);
|
||||
SendViewport(force: true);
|
||||
// il Registro degli impieghi alimenta anche le schede di industrie e città
|
||||
_session.Send(new RequestDetail { Kind = DetailKind.Employment, Target = 0 });
|
||||
}
|
||||
|
||||
public override void _ExitTree() => _session.MessageApplied -= OnMessage;
|
||||
public override void _ExitTree()
|
||||
{
|
||||
_session.MessageApplied -= OnMessage;
|
||||
AudioManager.Instance?.Unbind(_session);
|
||||
}
|
||||
|
||||
/// <summary>Codice di EventKind.World nel protocollo (notizie degli eventi del mondo, ADR 0017).</summary>
|
||||
private const byte WorldEventKind = 10;
|
||||
@@ -319,6 +370,7 @@ public partial class GameScreen : Node
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
PlaceToasts();
|
||||
_session.Poll();
|
||||
_disconnected.Visible = !_session.IsOpen;
|
||||
UpdateChronicle();
|
||||
@@ -393,8 +445,11 @@ public partial class GameScreen : Node
|
||||
_industryPanel = null;
|
||||
_companies = null;
|
||||
_market = null;
|
||||
_climb = null;
|
||||
_finance = null;
|
||||
_trainsPanel = null;
|
||||
foreach (var c in _full.GetChildren()) c.QueueFree();
|
||||
bool full = tool is Tool.Companies or Tool.Market;
|
||||
bool full = tool is Tool.Companies or Tool.Market or Tool.Climb or Tool.Finance or Tool.Industries;
|
||||
_full.Visible = full;
|
||||
if (_mapArea is not null) _mapArea.Visible = !full;
|
||||
if (_side is not null) _side.Visible = !full;
|
||||
@@ -421,7 +476,7 @@ public partial class GameScreen : Node
|
||||
panel = new HelpPanel(T("Demolisci"), T("Clic su una stazione, un deposito o un binario libero per demolirlo; si recupera una parte del costo."));
|
||||
break;
|
||||
case Tool.Trains:
|
||||
var trains = new TrainsPanel(_session);
|
||||
var trains = _trainsPanel = new TrainsPanel(_session);
|
||||
trains.TrainSelected += id =>
|
||||
{
|
||||
_map.Trains.SelectedTrain = id;
|
||||
@@ -448,7 +503,11 @@ public partial class GameScreen : Node
|
||||
panel = new EmploymentPanel(_session);
|
||||
break;
|
||||
case Tool.Industries:
|
||||
panel = _industryPanel = new IndustryPanel(_session);
|
||||
_industryPanel = new IndustryPanel(_session);
|
||||
_industryPanel.CloseRequested += () => _toolbar.Select(Tool.None);
|
||||
_industryPanel.PlanLineRequested += PlanLineToIndustry;
|
||||
_full.AddChild(_industryPanel);
|
||||
panel = NewInfoPanel();
|
||||
break;
|
||||
case Tool.Companies:
|
||||
_companies = new CompaniesPanel(_session);
|
||||
@@ -464,8 +523,17 @@ public partial class GameScreen : Node
|
||||
_full.AddChild(_market);
|
||||
panel = NewInfoPanel();
|
||||
break;
|
||||
case Tool.Climb:
|
||||
_climb = new ClimbPanel(_session);
|
||||
_climb.CloseRequested += () => _toolbar.Select(Tool.None);
|
||||
_full.AddChild(_climb);
|
||||
panel = NewInfoPanel();
|
||||
break;
|
||||
case Tool.Finance:
|
||||
panel = new FinancePanel(_session);
|
||||
_finance = new FinancePanel(_session);
|
||||
_finance.CloseRequested += () => _toolbar.Select(Tool.None);
|
||||
_full.AddChild(_finance);
|
||||
panel = NewInfoPanel();
|
||||
break;
|
||||
default:
|
||||
panel = NewInfoPanel();
|
||||
@@ -567,6 +635,7 @@ public partial class GameScreen : Node
|
||||
try
|
||||
{
|
||||
_plan = _session.World.PreviewTrack(TrackCommand(pts, 0));
|
||||
TrackPreviews++;
|
||||
_trackPanel.Show(_plan);
|
||||
_trackPanel.SetStatus("");
|
||||
}
|
||||
@@ -734,6 +803,37 @@ public partial class GameScreen : Node
|
||||
return null;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ tutorial
|
||||
|
||||
/// <summary>
|
||||
/// Controllo dell'interfaccia che corrisponde a un elemento del tutorial (vedi
|
||||
/// <c>TutorialScript.KnownTargets</c>); null se in questo momento non c'è (pannello chiuso).
|
||||
/// </summary>
|
||||
public Control? TutorialTarget(string id) => id switch
|
||||
{
|
||||
"map" => _mapArea,
|
||||
"side" => _side,
|
||||
"full" => _full,
|
||||
"topbar:speed" => _top.SpeedBox,
|
||||
"topbar:tier" => _top.TierBox,
|
||||
"track:profile" => _trackPanel?.Chart,
|
||||
"track:build" => _trackPanel?.Build,
|
||||
"trains:buy" => _trainsPanel?.BuyButton,
|
||||
"trains:compose" => _trainsPanel?.ComposeButton,
|
||||
"trains:assign" => _trainsPanel?.AssignButton,
|
||||
"lines:create" => _linesPanel?.CreateButton,
|
||||
_ when id.StartsWith("toolbar:", StringComparison.Ordinal)
|
||||
&& Enum.TryParse<Tool>(id["toolbar:".Length..], ignoreCase: true, out var tool) => _toolbar.ButtonFor(tool),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>Area libera per il riquadro del tutorial: la mappa, o il pannello a tutto schermo se aperto.</summary>
|
||||
public Rect2 TutorialArea()
|
||||
{
|
||||
if (_mapArea is { } map && map.IsVisibleInTree()) return map.GetGlobalRect();
|
||||
return _full.Visible ? _full.GetGlobalRect() : new Rect2();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ Cronaca finale e osservatore
|
||||
|
||||
/// <summary>Mostra la Cronaca quando arriva: subito se la partita è finita, oppure se l'ha chiesta il giocatore.</summary>
|
||||
@@ -765,7 +865,8 @@ public partial class GameScreen : Node
|
||||
_chronicleScreen = screen;
|
||||
}
|
||||
|
||||
private void CloseChronicle()
|
||||
/// <summary>Chiude la Cronaca se è aperta.</summary>
|
||||
public void CloseChronicle()
|
||||
{
|
||||
_chronicleScreen?.QueueFree();
|
||||
_chronicleScreen = null;
|
||||
@@ -790,8 +891,19 @@ public partial class GameScreen : Node
|
||||
Toast($"{T("Nuova partita+ in preparazione")}: {(TranslationServer.GetLocale().StartsWith("en") ? next.NameEn : next.NameIt)}");
|
||||
}
|
||||
|
||||
/// <summary>Messaggio temporaneo in alto sulla mappa.</summary>
|
||||
private void Toast(string text, bool error = false)
|
||||
/// <summary>Allinea gli avvisi in cima all'area visibile: la mappa o la schermata a tutto schermo.</summary>
|
||||
private void PlaceToasts()
|
||||
{
|
||||
if (_toasts.GetChildCount() == 0) return;
|
||||
Control? area = _full.Visible ? _full : _mapArea;
|
||||
if (area is null) return;
|
||||
var rect = area.GetGlobalRect();
|
||||
_toasts.Position = rect.Position + new Vector2(16, 12);
|
||||
_toasts.Size = new Vector2(Math.Max(0, rect.Size.X - 32), 0);
|
||||
}
|
||||
|
||||
/// <summary>Messaggio temporaneo in alto sull'area visibile (mappa o schermata a tutto schermo); lo usa anche il tutorial.</summary>
|
||||
public void Toast(string text, bool error = false)
|
||||
{
|
||||
var notice = UiTheme.Notice(text);
|
||||
if (error) notice.AddThemeStyleboxOverride("panel", UiTheme.Box(new Color("3a1c16"), Palette.Danger, 8, 12));
|
||||
@@ -801,5 +913,6 @@ public partial class GameScreen : Node
|
||||
if (IsInstanceValid(notice)) notice.QueueFree();
|
||||
};
|
||||
while (_toasts.GetChildCount() > 4) _toasts.GetChild(0).QueueFree();
|
||||
PlaceToasts();
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
|
||||
namespace RailEnterprise.Client.Screens;
|
||||
|
||||
/// <summary>Menu iniziale: partita locale (server figlio), collegamento a un server, lingua, uscita.</summary>
|
||||
public partial class MenuScreen : Control
|
||||
{
|
||||
public event Action? LocalGame;
|
||||
public event Action? ConnectToServer;
|
||||
public event Action<string>? LanguageChanged;
|
||||
private readonly Label _status = UiTheme.Text("", 14, Palette.TextSecondary);
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
// già nell'albero: ancore e margini insieme, altrimenti la schermata resterebbe grande zero
|
||||
SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect);
|
||||
UiTheme.Apply(this);
|
||||
var bg = new ColorRect { Color = Palette.AppBackground };
|
||||
bg.SetAnchorsPreset(LayoutPreset.FullRect);
|
||||
AddChild(bg);
|
||||
var center = new CenterContainer();
|
||||
center.SetAnchorsPreset(LayoutPreset.FullRect);
|
||||
AddChild(center);
|
||||
var col = new VBoxContainer { CustomMinimumSize = new Vector2(440, 0) };
|
||||
col.AddThemeConstantOverride("separation", 14);
|
||||
center.AddChild(col);
|
||||
col.AddChild(UiTheme.TitleLabel("Rail Enterprise", 96));
|
||||
col.AddChild(UiTheme.Text(T("Gestionale ferroviario dall'alto"), 18, Palette.TextSecondary));
|
||||
col.AddChild(new Control { CustomMinimumSize = new Vector2(0, 20) });
|
||||
var local = UiTheme.Primary(T("Partita locale"));
|
||||
local.CustomMinimumSize = new Vector2(0, 48);
|
||||
local.Pressed += () => LocalGame?.Invoke();
|
||||
col.AddChild(local);
|
||||
var remote = new Button { Text = T("Collegati a un server"), CustomMinimumSize = new Vector2(0, 48) };
|
||||
remote.Pressed += () => ConnectToServer?.Invoke();
|
||||
col.AddChild(remote);
|
||||
var lang = new HBoxContainer();
|
||||
lang.AddThemeConstantOverride("separation", 8);
|
||||
foreach (var (code, label) in new[] { ("it", "Italiano"), ("en", "English") })
|
||||
{
|
||||
var b = new Button { Text = label, ToggleMode = true, ButtonPressed = TranslationServer.GetLocale().StartsWith(code) };
|
||||
b.Pressed += () => LanguageChanged?.Invoke(code);
|
||||
lang.AddChild(b);
|
||||
}
|
||||
col.AddChild(lang);
|
||||
var quit = new Button { Text = T("Esci"), CustomMinimumSize = new Vector2(0, 40) };
|
||||
quit.Pressed += () => GetTree().Quit();
|
||||
col.AddChild(quit);
|
||||
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
col.AddChild(_status);
|
||||
}
|
||||
|
||||
public void SetStatus(string text) => _status.Text = text;
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
uid://b5eyw35w2vo7l
|
||||
@@ -0,0 +1,181 @@
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
|
||||
namespace RailEnterprise.Client.Tutorial;
|
||||
|
||||
/// <summary>Stato del tutorial di una partita.</summary>
|
||||
public enum TutorialStatus
|
||||
{
|
||||
/// <summary>In corso su un passo.</summary>
|
||||
Active,
|
||||
/// <summary>Tutti i passi completati o saltati.</summary>
|
||||
Completed,
|
||||
/// <summary>Chiuso dal giocatore prima della fine.</summary>
|
||||
Closed,
|
||||
}
|
||||
|
||||
/// <summary>Cosa fare all'apertura di una partita (vedi <see cref="TutorialMachine.Plan"/>).</summary>
|
||||
public enum TutorialLaunch
|
||||
{
|
||||
/// <summary>Nessun tutorial.</summary>
|
||||
Hidden,
|
||||
/// <summary>Dal primo passo.</summary>
|
||||
StartFresh,
|
||||
/// <summary>Dal passo salvato.</summary>
|
||||
Resume,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Avanzamento salvato nelle impostazioni del client (una voce per partita): passo corrente e stato.
|
||||
/// Il testo è <c>active:<id></c>, <c>completed</c> o <c>closed</c>.
|
||||
/// </summary>
|
||||
public readonly record struct TutorialProgress(string? StepId, TutorialStatus Status)
|
||||
{
|
||||
public string Encode() => Status switch
|
||||
{
|
||||
TutorialStatus.Active => "active:" + (StepId ?? ""),
|
||||
TutorialStatus.Completed => "completed",
|
||||
_ => "closed",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Chiave della partita nelle impostazioni: origine (<paramref name="scope"/>: partita locale, partita di
|
||||
/// prova del tutorial, server remoto) e i dati del Welcome che non cambiano durante una partita (seme,
|
||||
/// lato della mappa, anno d'inizio, regione, compagnia del giocatore). Non usa l'impronta del terreno né
|
||||
/// la data: cambiano giocando (città che crescono, industrie che aprono e chiudono), e la stessa partita
|
||||
/// ricaricata non ritroverebbe la sua voce. Solo lettere minuscole, cifre e trattini bassi.
|
||||
/// </summary>
|
||||
public static string GameKey(string scope, ulong seed, int sizeKm, int startYear, string regionId, int companyId) =>
|
||||
Clean($"g_{scope}_{seed:x16}_{sizeKm}_{startYear}_{regionId}_{companyId}");
|
||||
|
||||
/// <summary>Chiave della partita dal riepilogo del Welcome (vedi l'altra forma).</summary>
|
||||
public static string GameKey(string scope, WorldSummary s) => GameKey(scope, s.Seed, s.SizeKm, s.StartYear, s.RegionId, s.CompanyId);
|
||||
|
||||
private static string Clean(string text) =>
|
||||
string.Create(text.Length, text, (span, t) =>
|
||||
{
|
||||
for (int i = 0; i < t.Length; i++) span[i] = char.IsAsciiLetterOrDigit(t[i]) ? char.ToLowerInvariant(t[i]) : '_';
|
||||
});
|
||||
|
||||
/// <summary>Legge una voce salvata; null se vuota o non riconosciuta.</summary>
|
||||
public static TutorialProgress? Decode(string? text)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text)) return null;
|
||||
text = text.Trim();
|
||||
if (text == "completed") return new TutorialProgress(null, TutorialStatus.Completed);
|
||||
if (text == "closed") return new TutorialProgress(null, TutorialStatus.Closed);
|
||||
if (text.StartsWith("active:", StringComparison.Ordinal))
|
||||
{
|
||||
string id = text["active:".Length..];
|
||||
return new TutorialProgress(id.Length > 0 ? id : null, TutorialStatus.Active);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Macchina a stati dei passi: un passo alla volta, completato quando la sua condizione è vera sui fatti
|
||||
/// osservati (<see cref="Update"/>), oppure con Avanti (passi informativi), Salta passo o Chiudi. I contatori
|
||||
/// con <c>increase</c> si confrontano con i fatti di quando il passo precedente si è completato da sé (così
|
||||
/// un'azione arrivata subito dopo conta per il passo nuovo), oppure, dopo Avanti, Salta, una ripresa o una
|
||||
/// ripartenza, con i fatti al primo aggiornamento del passo. Non decide regole di gioco: guarda soltanto ciò
|
||||
/// che il client ha già ricevuto.
|
||||
/// </summary>
|
||||
public sealed class TutorialMachine
|
||||
{
|
||||
private TutorialFacts? _baseline;
|
||||
|
||||
public TutorialMachine(TutorialScript script)
|
||||
{
|
||||
if (script.Steps.Count == 0) throw new ArgumentException("Copione del tutorial senza passi", nameof(script));
|
||||
Script = script;
|
||||
}
|
||||
|
||||
public TutorialScript Script { get; }
|
||||
|
||||
/// <summary>Indice del passo corrente (uguale al numero di passi a tutorial completato).</summary>
|
||||
public int Index { get; private set; }
|
||||
|
||||
public TutorialStatus Status { get; private set; } = TutorialStatus.Active;
|
||||
|
||||
public TutorialStep? Current => Status == TutorialStatus.Active && Index < Script.Steps.Count ? Script.Steps[Index] : null;
|
||||
|
||||
public bool IsLast => Index == Script.Steps.Count - 1;
|
||||
|
||||
/// <summary>Avanzamento da salvare.</summary>
|
||||
public TutorialProgress Progress => new(Current?.Id, Status);
|
||||
|
||||
/// <summary>
|
||||
/// Decide se mostrare il tutorial all'apertura di una partita. <paramref name="restart"/> (pulsante «Tutorial»
|
||||
/// della schermata di connessione) riparte sempre dal primo passo; un tutorial in corso in quella partita si riprende; uno
|
||||
/// completato o chiuso resta nascosto, a meno che il giocatore l'abbia chiesto con la casella «Mostra il
|
||||
/// tutorial» (attiva da sé solo alla prima partita: spuntarla dopo è una richiesta esplicita, e una
|
||||
/// partita nuova con lo stesso seme ha la stessa chiave di una vecchia); senza voce salvata si mostra solo
|
||||
/// se chiesto.
|
||||
/// </summary>
|
||||
public static TutorialLaunch Plan(bool requested, bool restart, TutorialProgress? saved)
|
||||
{
|
||||
if (restart) return TutorialLaunch.StartFresh;
|
||||
if (saved is { Status: TutorialStatus.Active }) return TutorialLaunch.Resume;
|
||||
return requested ? TutorialLaunch.StartFresh : TutorialLaunch.Hidden;
|
||||
}
|
||||
|
||||
/// <summary>Riparte dal primo passo.</summary>
|
||||
public void Restart() => GoTo(0);
|
||||
|
||||
/// <summary>Riprende da un avanzamento salvato; un passo che non c'è più fa ripartire dall'inizio.</summary>
|
||||
public void Restore(TutorialProgress progress)
|
||||
{
|
||||
switch (progress.Status)
|
||||
{
|
||||
case TutorialStatus.Active:
|
||||
GoTo(Math.Max(0, Script.IndexOf(progress.StepId)));
|
||||
break;
|
||||
case TutorialStatus.Completed:
|
||||
Index = Script.Steps.Count;
|
||||
Status = TutorialStatus.Completed;
|
||||
break;
|
||||
default:
|
||||
Status = TutorialStatus.Closed;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Valuta il passo corrente sui fatti; se la condizione è vera passa al successivo e restituisce true.</summary>
|
||||
public bool Update(TutorialFacts facts)
|
||||
{
|
||||
if (Current is not { } step) return false;
|
||||
_baseline ??= facts.Clone();
|
||||
if (step.Done is null || !step.Done.IsMet(facts, _baseline)) return false;
|
||||
Advance();
|
||||
// la base del passo nuovo sono i fatti di adesso, non quelli del suo primo aggiornamento: un comando
|
||||
// riuscito arrivato prima di quell'aggiornamento conta per il passo nuovo
|
||||
if (Status == TutorialStatus.Active) _baseline = facts.Clone();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Avanti: chiude un passo informativo (sugli altri equivale a <see cref="Skip"/>).</summary>
|
||||
public void Next() => Advance();
|
||||
|
||||
/// <summary>Salta il passo corrente.</summary>
|
||||
public void Skip() => Advance();
|
||||
|
||||
/// <summary>Chiude il tutorial; si potrà riaprire con F1 o dalla schermata iniziale.</summary>
|
||||
public void Close()
|
||||
{
|
||||
if (Status == TutorialStatus.Active) Status = TutorialStatus.Closed;
|
||||
_baseline = null;
|
||||
}
|
||||
|
||||
private void Advance()
|
||||
{
|
||||
if (Status != TutorialStatus.Active) return;
|
||||
GoTo(Index + 1);
|
||||
}
|
||||
|
||||
private void GoTo(int index)
|
||||
{
|
||||
_baseline = null;
|
||||
Index = Math.Clamp(index, 0, Script.Steps.Count);
|
||||
Status = Index >= Script.Steps.Count ? TutorialStatus.Completed : TutorialStatus.Active;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using RailEnterprise.Core.Commands;
|
||||
|
||||
namespace RailEnterprise.Client.Tutorial;
|
||||
|
||||
/// <summary>
|
||||
/// Copione del tutorial guidato (<c>assets/tutorial/tutorial.json</c>, ADR 0023): l'elenco ordinato dei
|
||||
/// passi. È un file dati del client, non del motore: non cambia regole né salvataggi. Questa classe e le
|
||||
/// altre di <c>Tutorial/Logic</c> non dipendono da Godot e si provano nel harness dei test.
|
||||
/// </summary>
|
||||
public sealed class TutorialScript
|
||||
{
|
||||
/// <summary>Versione del formato del file (oggi 1).</summary>
|
||||
public int Version { get; init; } = 1;
|
||||
|
||||
public List<TutorialStep> Steps { get; init; } = [];
|
||||
|
||||
/// <summary>Indice del passo con l'id indicato, -1 se non c'è.</summary>
|
||||
public int IndexOf(string? id) => id is null ? -1 : Steps.FindIndex(s => s?.Id == id);
|
||||
|
||||
/// <summary>Legge il copione dal testo JSON (commenti e virgole finali ammessi, campi sconosciuti rifiutati).</summary>
|
||||
public static TutorialScript Parse(string json) =>
|
||||
JsonSerializer.Deserialize(json, TutorialJsonContext.Default.TutorialScript)
|
||||
?? throw new JsonException("Copione del tutorial vuoto");
|
||||
|
||||
/// <summary>
|
||||
/// Elementi dell'interfaccia che un passo può evidenziare. Il client li risolve nei controlli
|
||||
/// (<c>GameScreen.TutorialTarget</c>); se un elemento non è visibile in quel momento si usa il
|
||||
/// ripiego del passo, altrimenti non si evidenzia nulla.
|
||||
/// </summary>
|
||||
public static readonly IReadOnlyList<string> KnownTargets = BuildTargets();
|
||||
|
||||
private static List<string> BuildTargets()
|
||||
{
|
||||
var list = new List<string> { "map", "side", "full", "topbar:speed", "topbar:tier", "track:profile", "track:build", "trains:buy", "trains:compose", "trains:assign", "lines:create" };
|
||||
foreach (string panel in TutorialFacts.KnownPanels)
|
||||
{
|
||||
if (panel != TutorialFacts.NoPanel) list.Add("toolbar:" + panel);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Controlla il copione: elenco e passi presenti (il JSON ammette <c>null</c>), id unici, testi presenti,
|
||||
/// elementi, contatori e pannelli noti. Restituisce gli errori in italiano.
|
||||
/// </summary>
|
||||
public List<string> Validate()
|
||||
{
|
||||
var errors = new List<string>();
|
||||
if (Version != 1) errors.Add($"versione {Version} non supportata");
|
||||
if (Steps is null)
|
||||
{
|
||||
errors.Add("elenco dei passi mancante");
|
||||
return errors;
|
||||
}
|
||||
if (Steps.Count == 0) errors.Add("nessun passo");
|
||||
var ids = new HashSet<string>(StringComparer.Ordinal);
|
||||
for (int i = 0; i < Steps.Count; i++)
|
||||
{
|
||||
var step = Steps[i];
|
||||
if (step is null)
|
||||
{
|
||||
errors.Add($"passo n. {i + 1} nullo");
|
||||
continue;
|
||||
}
|
||||
string where = $"passo «{step.Id}»";
|
||||
if (string.IsNullOrWhiteSpace(step.Id)) errors.Add("passo senza id");
|
||||
else if (!ids.Add(step.Id)) errors.Add($"{where}: id ripetuto");
|
||||
if (string.IsNullOrWhiteSpace(step.Title)) errors.Add($"{where}: titolo vuoto");
|
||||
if (string.IsNullOrWhiteSpace(step.Text)) errors.Add($"{where}: testo vuoto");
|
||||
if (step.Highlight is { } h && !KnownTargets.Contains(h)) errors.Add($"{where}: elemento da evidenziare sconosciuto «{h}»");
|
||||
if (step.Fallback is { } f && !KnownTargets.Contains(f)) errors.Add($"{where}: ripiego sconosciuto «{f}»");
|
||||
if (step.Fallback is not null && step.Highlight is null) errors.Add($"{where}: ripiego senza elemento principale");
|
||||
step.Done?.Validate(where, errors);
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Passo del tutorial: testi (chiavi di traduzione), elemento da evidenziare, condizione di completamento.</summary>
|
||||
public sealed class TutorialStep
|
||||
{
|
||||
public required string Id { get; init; }
|
||||
|
||||
/// <summary>Chiave del titolo per <c>T()</c> (testo italiano).</summary>
|
||||
public required string Title { get; init; }
|
||||
|
||||
/// <summary>Chiave del testo per <c>T()</c> (testo italiano).</summary>
|
||||
public required string Text { get; init; }
|
||||
|
||||
/// <summary>Elemento dell'interfaccia da evidenziare (vedi <see cref="TutorialScript.KnownTargets"/>), facoltativo.</summary>
|
||||
public string? Highlight { get; init; }
|
||||
|
||||
/// <summary>Elemento da evidenziare quando il principale non è visibile (per esempio il pulsante che apre il pannello).</summary>
|
||||
public string? Fallback { get; init; }
|
||||
|
||||
/// <summary>Condizione osservabile che completa il passo; senza condizione il passo è informativo (pulsante Avanti).</summary>
|
||||
public TutorialCondition? Done { get; init; }
|
||||
|
||||
[JsonIgnore]
|
||||
public bool IsInformative => Done is null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Condizione di completamento, valutata su fatti semplici che il client osserva (<see cref="TutorialFacts"/>).
|
||||
/// Ha una sola forma tra: contatore (<c>counter</c> con <c>atLeast</c>, <c>atMost</c> e/o <c>increase</c>),
|
||||
/// pannello aperto (<c>panel</c>), tutte (<c>all</c>) o almeno una (<c>any</c>) di altre condizioni.
|
||||
/// <c>increase</c> confronta il contatore con il suo valore all'inizio del passo.
|
||||
/// </summary>
|
||||
public sealed class TutorialCondition
|
||||
{
|
||||
public string? Counter { get; init; }
|
||||
public double? AtLeast { get; init; }
|
||||
public double? AtMost { get; init; }
|
||||
public double? Increase { get; init; }
|
||||
public string? Panel { get; init; }
|
||||
public List<TutorialCondition>? All { get; init; }
|
||||
public List<TutorialCondition>? Any { get; init; }
|
||||
|
||||
/// <summary>Vera se i fatti di adesso soddisfano la condizione; <paramref name="baseline"/> sono i fatti all'inizio del passo.</summary>
|
||||
public bool IsMet(TutorialFacts now, TutorialFacts baseline)
|
||||
{
|
||||
if (All is not null) return All.TrueForAll(c => c.IsMet(now, baseline));
|
||||
if (Any is not null) return Any.Exists(c => c.IsMet(now, baseline));
|
||||
if (Panel is not null) return now.Panel == Panel;
|
||||
if (Counter is null) return false;
|
||||
double value = now.Get(Counter);
|
||||
if (AtLeast is { } min && value < min) return false;
|
||||
if (AtMost is { } max && value > max) return false;
|
||||
if (Increase is { } inc && value - baseline.Get(Counter) < inc) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
internal void Validate(string where, List<string> errors)
|
||||
{
|
||||
int forms = (Counter is not null ? 1 : 0) + (Panel is not null ? 1 : 0) + (All is not null ? 1 : 0) + (Any is not null ? 1 : 0);
|
||||
if (forms != 1)
|
||||
{
|
||||
errors.Add($"{where}: la condizione deve avere una sola forma tra counter, panel, all e any");
|
||||
return;
|
||||
}
|
||||
if (Counter is not null)
|
||||
{
|
||||
if (AtLeast is null && AtMost is null && Increase is null) errors.Add($"{where}: contatore «{Counter}» senza atLeast, atMost o increase");
|
||||
if (!TutorialFacts.IsKnownCounter(Counter)) errors.Add($"{where}: contatore sconosciuto «{Counter}»");
|
||||
}
|
||||
else if (AtLeast is not null || AtMost is not null || Increase is not null)
|
||||
{
|
||||
errors.Add($"{where}: atLeast, atMost e increase valgono solo con counter");
|
||||
}
|
||||
if (Panel is not null && !TutorialFacts.KnownPanels.Contains(Panel)) errors.Add($"{where}: pannello sconosciuto «{Panel}»");
|
||||
foreach (var list in new[] { All, Any })
|
||||
{
|
||||
if (list is null) continue;
|
||||
if (list.Count == 0) errors.Add($"{where}: elenco di condizioni vuoto");
|
||||
foreach (var c in list)
|
||||
{
|
||||
if (c is null) errors.Add($"{where}: condizione nulla");
|
||||
else c.Validate(where, errors);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Fatti osservati dal client: contatori (entità della compagnia, comandi riusciti, azioni sulla mappa) e pannello aperto.</summary>
|
||||
public sealed class TutorialFacts
|
||||
{
|
||||
/// <summary>Pannello «nessuno» (barra degli strumenti senza selezione).</summary>
|
||||
public const string NoPanel = "none";
|
||||
|
||||
/// <summary>Prefisso dei contatori dei comandi riusciti: <c>cmd:</c> + nome di <see cref="CommandType"/>.</summary>
|
||||
public const string CommandPrefix = "cmd:";
|
||||
|
||||
/// <summary>Pannelli della barra degli strumenti, con i nomi in minuscolo dell'enumerazione <c>Hud.Tool</c>.</summary>
|
||||
public static readonly IReadOnlyList<string> KnownPanels =
|
||||
[
|
||||
NoPanel, "track", "station", "signal", "depot", "trains", "lines", "maintenance", "employment", "industries", "market", "companies", "climb", "finance", "demolish",
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Contatori osservati: entità della compagnia nella copia locale (stazioni, depositi, archi, archi in
|
||||
/// funzione, archi in cantiere, locomotive, carri e carrozze, treni, linee, treni in linea), azioni del
|
||||
/// giocatore sulla mappa (spostamento in schermate, zoom in unità logaritmiche, cambi di velocità) e
|
||||
/// anteprime valide del tracciato.
|
||||
/// </summary>
|
||||
public static readonly IReadOnlyList<string> KnownCounters =
|
||||
[
|
||||
"stations", "depots", "edges", "edgesActive", "edgesBuilding", "locomotives", "cars", "trains", "lines", "trainsOnLine",
|
||||
"mapPan", "mapZoom", "speedChanges", "trackPreviews",
|
||||
];
|
||||
|
||||
public Dictionary<string, double> Counters { get; } = new(StringComparer.Ordinal);
|
||||
|
||||
public string Panel { get; set; } = NoPanel;
|
||||
|
||||
public double Get(string counter) => Counters.TryGetValue(counter, out double v) ? v : 0;
|
||||
|
||||
public void Set(string counter, double value) => Counters[counter] = value;
|
||||
|
||||
public void Add(string counter, double amount) => Counters[counter] = Get(counter) + amount;
|
||||
|
||||
/// <summary>Nome del contatore di un tipo di comando riuscito.</summary>
|
||||
public static string CommandCounter(CommandType type) => CommandPrefix + type;
|
||||
|
||||
public static bool IsKnownCounter(string name) =>
|
||||
KnownCounters.Contains(name)
|
||||
|| (name.StartsWith(CommandPrefix, StringComparison.Ordinal) && Enum.TryParse<CommandType>(name[CommandPrefix.Length..], ignoreCase: false, out var t)
|
||||
&& Enum.IsDefined(t) && t.ToString() == name[CommandPrefix.Length..]);
|
||||
|
||||
public TutorialFacts Clone()
|
||||
{
|
||||
var copy = new TutorialFacts { Panel = Panel };
|
||||
foreach (var (k, v) in Counters) copy.Counters[k] = v;
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, PropertyNameCaseInsensitive = true,
|
||||
UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow, ReadCommentHandling = JsonCommentHandling.Skip,
|
||||
AllowTrailingCommas = true)]
|
||||
[JsonSerializable(typeof(TutorialScript))]
|
||||
internal sealed partial class TutorialJsonContext : JsonSerializerContext;
|
||||
@@ -0,0 +1,312 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.Screens;
|
||||
using RailEnterprise.Core.Commands;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Rail;
|
||||
using RailEnterprise.Protocol;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
|
||||
namespace RailEnterprise.Client.Tutorial;
|
||||
|
||||
/// <summary>
|
||||
/// Collega il tutorial alla partita: raccoglie i fatti che il client osserva (entità della compagnia nella
|
||||
/// copia locale, esiti dei comandi, pannello aperto, camera, velocità chiesta da questo client, anteprime del
|
||||
/// tracciato), fa avanzare <see cref="TutorialMachine"/>, aggiorna <see cref="TutorialOverlay"/> e salva
|
||||
/// l'avanzamento per partita. Non invia comandi e non decide regole. F1 riapre o nasconde il tutorial.
|
||||
/// </summary>
|
||||
public partial class TutorialController : Node
|
||||
{
|
||||
private const string ScriptPath = "res://assets/tutorial/tutorial.json";
|
||||
private const double FactsInterval = 0.2;
|
||||
|
||||
private readonly GameScreen _game;
|
||||
private readonly string _scope;
|
||||
private bool _requested;
|
||||
private bool _restart;
|
||||
private readonly CanvasLayer _layer = new() { Layer = 3 };
|
||||
private readonly TutorialOverlay _overlay = new();
|
||||
private readonly TutorialFacts _facts = new();
|
||||
private readonly Dictionary<string, VehicleKind> _vehicleKinds = [];
|
||||
private TutorialMachine? _machine;
|
||||
private string? _loadError;
|
||||
private string _gameKey = "";
|
||||
private bool _visible;
|
||||
private int _shownIndex = -1;
|
||||
// controllo già portato in vista nel suo contenitore a scorrimento per il passo mostrato
|
||||
private Control? _scrolledTo;
|
||||
private double _sinceFacts = FactsInterval;
|
||||
private Vector2? _lastCamera;
|
||||
private float _lastZoom;
|
||||
private int _lastSpeedRequests;
|
||||
|
||||
/// <param name="scope">origine della partita (locale, tutorial, server remoto) per la chiave dell'avanzamento</param>
|
||||
/// <param name="requested">casella «Mostra il tutorial» della schermata di connessione</param>
|
||||
/// <param name="restart">pulsante «Tutorial» della schermata di connessione: dal primo passo anche se già fatto</param>
|
||||
public TutorialController(GameScreen game, string scope, bool requested, bool restart)
|
||||
{
|
||||
_game = game;
|
||||
_scope = scope;
|
||||
_requested = requested;
|
||||
_restart = restart;
|
||||
}
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
try
|
||||
{
|
||||
using var file = Godot.FileAccess.Open(ScriptPath, Godot.FileAccess.ModeFlags.Read)
|
||||
?? throw new FileNotFoundException(ScriptPath);
|
||||
var script = TutorialScript.Parse(file.GetAsText());
|
||||
var errors = script.Validate();
|
||||
if (errors.Count > 0) throw new InvalidDataException(string.Join("; ", errors));
|
||||
_machine = new TutorialMachine(script);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_loadError = e.Message;
|
||||
GD.PushWarning($"Tutorial non disponibile: {e.Message}");
|
||||
// chi l'ha chiesto deve saperlo: altrimenti vedrebbe una partita normale senza spiegazioni
|
||||
if (_requested || _restart) ReportUnavailable();
|
||||
return;
|
||||
}
|
||||
foreach (var v in _game.Session.World.Data.Vehicles) _vehicleKinds[v.Id] = v.Kind;
|
||||
AddChild(_layer);
|
||||
_layer.AddChild(_overlay);
|
||||
_overlay.NextPressed += () => Act(m => m.Next());
|
||||
_overlay.SkipPressed += () => Act(m => m.Skip());
|
||||
_overlay.ClosePressed += () => Act(m => m.Close());
|
||||
_game.Session.MessageApplied += OnMessage;
|
||||
_lastSpeedRequests = _game.Session.SpeedRequests;
|
||||
OpenForGame();
|
||||
}
|
||||
|
||||
public override void _ExitTree() => _game.Session.MessageApplied -= OnMessage;
|
||||
|
||||
private void ReportUnavailable() => _game.Toast(string.Format(T("Tutorial non disponibile: {0}"), _loadError), error: true);
|
||||
|
||||
/// <summary>All'avvio e a ogni Welcome (nuova partita, caricamento): chiave della partita e piano di apertura.</summary>
|
||||
private void OpenForGame()
|
||||
{
|
||||
if (_machine is null || _game.Session.World.Summary is not { } s) return;
|
||||
_gameKey = TutorialProgress.GameKey(_scope, s);
|
||||
var saved = TutorialSettings.Read(_gameKey);
|
||||
switch (TutorialMachine.Plan(_requested, _restart, saved))
|
||||
{
|
||||
case TutorialLaunch.StartFresh:
|
||||
_machine.Restart();
|
||||
Save();
|
||||
_visible = true;
|
||||
break;
|
||||
case TutorialLaunch.Resume:
|
||||
_machine.Restore(saved!.Value);
|
||||
_visible = true;
|
||||
break;
|
||||
default:
|
||||
if (saved is { } p) _machine.Restore(p);
|
||||
else _machine.Close();
|
||||
_visible = false;
|
||||
break;
|
||||
}
|
||||
// casella e pulsante della schermata di connessione valgono per la partita aperta, non per le successive (Nuova partita+)
|
||||
_requested = _restart = false;
|
||||
_lastCamera = null;
|
||||
_shownIndex = -1;
|
||||
Refresh();
|
||||
}
|
||||
|
||||
private void OnMessage(IMessage message)
|
||||
{
|
||||
switch (message)
|
||||
{
|
||||
case Welcome:
|
||||
OpenForGame();
|
||||
break;
|
||||
case CommandResultMessage { Ok: true } r:
|
||||
_facts.Add(TutorialFacts.CommandCounter((CommandType)r.Type), 1);
|
||||
// subito, non al prossimo giro: due esiti ravvicinati contano per due passi diversi
|
||||
Evaluate();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void Act(Action<TutorialMachine> action)
|
||||
{
|
||||
if (_machine is null) return;
|
||||
action(_machine);
|
||||
Save();
|
||||
if (_machine.Status != TutorialStatus.Active) _visible = false;
|
||||
Refresh();
|
||||
}
|
||||
|
||||
private void Save()
|
||||
{
|
||||
if (_machine is not null && _gameKey.Length > 0) TutorialSettings.Save(_gameKey, _machine.Progress);
|
||||
}
|
||||
|
||||
public override void _UnhandledKeyInput(InputEvent e)
|
||||
{
|
||||
if (e is not InputEventKey { Pressed: true, Echo: false, Keycode: Key.F1 }) return;
|
||||
if (_machine is null)
|
||||
{
|
||||
if (_loadError is not null) ReportUnavailable();
|
||||
return;
|
||||
}
|
||||
if (_visible)
|
||||
{
|
||||
// F1 nasconde soltanto: il tutorial in corso resta salvato
|
||||
_visible = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
// riapre dal passo salvato, o dall'inizio se era chiuso o completato
|
||||
if (_machine.Status != TutorialStatus.Active) _machine.Restart();
|
||||
_visible = true;
|
||||
_shownIndex = -1;
|
||||
Save();
|
||||
}
|
||||
Refresh();
|
||||
GetViewport().SetInputAsHandled();
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
if (_machine is null) return;
|
||||
TrackCameraAndSpeed();
|
||||
_sinceFacts += delta;
|
||||
if (_sinceFacts >= FactsInterval)
|
||||
{
|
||||
_sinceFacts = 0;
|
||||
CollectWorldFacts();
|
||||
Evaluate();
|
||||
}
|
||||
Refresh();
|
||||
}
|
||||
|
||||
/// <summary>Valuta il passo corrente sui fatti raccolti; se si completa salva e mostra «Fatto».</summary>
|
||||
private void Evaluate()
|
||||
{
|
||||
if (_machine is null || !_visible) return;
|
||||
string? title = _machine.Current is { } step ? T(step.Title) : null;
|
||||
if (!_machine.Update(_facts)) return;
|
||||
Save();
|
||||
if (title is not null) _overlay.Flash(title);
|
||||
// completato l'ultimo passo il riquadro si chiude
|
||||
if (_machine.Status != TutorialStatus.Active) _visible = false;
|
||||
}
|
||||
|
||||
/// <summary>Spostamento della camera (in schermate), zoom (in logaritmi) e velocità chieste da questo client, sommati.</summary>
|
||||
private void TrackCameraAndSpeed()
|
||||
{
|
||||
var map = _game.Map;
|
||||
var camera = map.Camera.Position;
|
||||
float zoom = map.Zoom;
|
||||
if (_lastCamera is { } last && zoom > 0 && _lastZoom > 0)
|
||||
{
|
||||
if (Math.Abs(zoom - _lastZoom) > 1e-6)
|
||||
{
|
||||
// lo zoom attorno al cursore sposta anche la camera: non è uno spostamento
|
||||
_facts.Add("mapZoom", Math.Abs(Math.Log(zoom / _lastZoom)));
|
||||
}
|
||||
else
|
||||
{
|
||||
float screen = map.GetViewportRect().Size.X / zoom;
|
||||
if (screen > 0) _facts.Add("mapPan", camera.DistanceTo(last) / screen);
|
||||
}
|
||||
}
|
||||
_lastCamera = camera;
|
||||
_lastZoom = zoom;
|
||||
|
||||
// solo le richieste di questo client: un altro giocatore che cambia la velocità del server non conta
|
||||
int requests = _game.Session.SpeedRequests;
|
||||
if (requests != _lastSpeedRequests) _facts.Add("speedChanges", requests - _lastSpeedRequests);
|
||||
_lastSpeedRequests = requests;
|
||||
}
|
||||
|
||||
/// <summary>Entità della compagnia nella copia locale, pannello aperto, anteprime del tracciato.</summary>
|
||||
private void CollectWorldFacts()
|
||||
{
|
||||
var w = _game.Session.World;
|
||||
int me = w.Summary?.CompanyId ?? -1;
|
||||
int edges = 0, active = 0, locos = 0, cars = 0, trains = 0, onLine = 0;
|
||||
foreach (var e in w.Edges.Values)
|
||||
{
|
||||
if (e.Owner != me) continue;
|
||||
edges++;
|
||||
if (e.State == (byte)EdgeState.Active) active++;
|
||||
}
|
||||
foreach (var v in w.Vehicles.Values)
|
||||
{
|
||||
if (v.Owner != me || !_vehicleKinds.TryGetValue(v.Type, out var kind)) continue;
|
||||
if (kind == VehicleKind.Locomotive) locos++;
|
||||
else cars++;
|
||||
}
|
||||
foreach (var t in w.Trains.Values)
|
||||
{
|
||||
if (t.Owner != me) continue;
|
||||
trains++;
|
||||
if (t.Line >= 0) onLine++;
|
||||
}
|
||||
_facts.Set("stations", w.Stations.Values.Count(s => s.Owner == me));
|
||||
_facts.Set("depots", w.Depots.Values.Count(d => d.Owner == me));
|
||||
_facts.Set("edges", edges);
|
||||
_facts.Set("edgesActive", active);
|
||||
// i cantieri sono gli archi non ancora in funzione (dismessi compresi: non bloccano un tutorial nuovo)
|
||||
_facts.Set("edgesBuilding", w.Edges.Values.Count(e => e.Owner == me && e.State == (byte)EdgeState.UnderConstruction));
|
||||
_facts.Set("locomotives", locos);
|
||||
_facts.Set("cars", cars);
|
||||
_facts.Set("trains", trains);
|
||||
_facts.Set("lines", w.Lines.Values.Count(l => l.Owner == me));
|
||||
_facts.Set("trainsOnLine", onLine);
|
||||
_facts.Set("trackPreviews", _game.TrackPreviews);
|
||||
_facts.Panel = _game.CurrentTool.ToString().ToLowerInvariant();
|
||||
}
|
||||
|
||||
/// <summary>Testi del passo corrente, posizione del riquadro ed elemento evidenziato.</summary>
|
||||
private void Refresh()
|
||||
{
|
||||
if (_machine is null) return;
|
||||
bool show = _visible && _machine.Current is not null && !_game.ChronicleVisible && _game.Session.IsOpen;
|
||||
_overlay.Visible = show;
|
||||
if (!show) return;
|
||||
var step = _machine.Current!;
|
||||
if (_shownIndex != _machine.Index)
|
||||
{
|
||||
_shownIndex = _machine.Index;
|
||||
_scrolledTo = null;
|
||||
_overlay.ShowStep(_machine.Index + 1, _machine.Script.Steps.Count, T(step.Title), T(step.Text), step.IsInformative, _machine.IsLast);
|
||||
}
|
||||
_overlay.Area = _game.TutorialArea();
|
||||
Rect2? target = null;
|
||||
if (step.Highlight is { } h) target = VisibleRect(_game.TutorialTarget(h));
|
||||
if (target is null && step.Fallback is { } f) target = VisibleRect(_game.TutorialTarget(f));
|
||||
_overlay.Target = target;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rettangolo visibile di un controllo, ritagliato dai contenitori a scorrimento che lo contengono (barra
|
||||
/// degli strumenti, pannello destro); null se il controllo non c'è o è del tutto fuori vista, così si usa
|
||||
/// il ripiego e il contorno non finisce su ciò che sta sotto. La prima volta in un passo il controllo
|
||||
/// coperto dallo scorrimento si porta in vista.
|
||||
/// </summary>
|
||||
private Rect2? VisibleRect(Control? c)
|
||||
{
|
||||
if (c is null || !IsInstanceValid(c) || !c.IsVisibleInTree() || c.Size.X <= 0) return null;
|
||||
if (_scrolledTo != c)
|
||||
{
|
||||
_scrolledTo = c;
|
||||
for (var p = c.GetParent(); p is not null; p = p.GetParent())
|
||||
{
|
||||
if (p is ScrollContainer scroll) scroll.EnsureControlVisible(c);
|
||||
}
|
||||
}
|
||||
var rect = c.GetGlobalRect();
|
||||
for (var p = c.GetParent(); p is not null; p = p.GetParent())
|
||||
{
|
||||
if (p is not ScrollContainer scroll) continue;
|
||||
rect = rect.Intersection(scroll.GetGlobalRect());
|
||||
if (rect.Size.X < 1 || rect.Size.Y < 1) return null;
|
||||
}
|
||||
return rect;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
|
||||
namespace RailEnterprise.Client.Tutorial;
|
||||
|
||||
/// <summary>
|
||||
/// Interfaccia del tutorial: riquadro ancorato in basso a sinistra dell'area della mappa (non modale, non
|
||||
/// copre barra degli strumenti né pannello destro) e contorno ambra animato attorno all'elemento da
|
||||
/// guardare. Tutto ciò che non è il riquadro lascia passare il mouse.
|
||||
/// </summary>
|
||||
public partial class TutorialOverlay : Control
|
||||
{
|
||||
private const float BoxWidth = 400;
|
||||
private const float Margin = 16;
|
||||
|
||||
private readonly PanelContainer _box = new();
|
||||
private readonly Label _counter = UiTheme.Text("", 12, Palette.TextSecondary);
|
||||
private readonly Label _title = UiTheme.TitleLabel("", 26, Palette.AmberLight);
|
||||
private readonly Label _text = UiTheme.Text("", 14);
|
||||
private readonly Label _done = UiTheme.Text("", 13, Palette.Ok, bold: true);
|
||||
private readonly ProgressBar _progress = new() { ShowPercentage = false, CustomMinimumSize = new Vector2(0, 4) };
|
||||
private readonly VBoxContainer _body = new();
|
||||
private readonly Button _next = UiTheme.Primary(T("Avanti"));
|
||||
private readonly Button _skip = new() { Text = T("Salta passo") };
|
||||
private readonly Button _close = new() { Text = T("Chiudi tutorial") };
|
||||
private readonly Button _collapse = new() { Text = "–", Flat = true, CustomMinimumSize = new Vector2(28, 24) };
|
||||
private readonly HighlightFrame _frame = new();
|
||||
private double _doneTimer;
|
||||
private bool _collapsed;
|
||||
|
||||
public event Action? NextPressed;
|
||||
public event Action? SkipPressed;
|
||||
public event Action? ClosePressed;
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect);
|
||||
MouseFilter = MouseFilterEnum.Ignore;
|
||||
UiTheme.Apply(this);
|
||||
AddChild(_frame);
|
||||
// i pulsanti non prendono il fuoco: Invio e spazio restano alla partita (Costruisci, pausa) e non
|
||||
// ripremono l'ultimo pulsante del tutorial
|
||||
foreach (var b in new[] { _next, _skip, _close, _collapse }) b.FocusMode = FocusModeEnum.None;
|
||||
|
||||
_box.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Amber, 10, 16));
|
||||
_box.CustomMinimumSize = new Vector2(BoxWidth, 0);
|
||||
AddChild(_box);
|
||||
var col = new VBoxContainer();
|
||||
col.AddThemeConstantOverride("separation", 8);
|
||||
_box.AddChild(col);
|
||||
|
||||
var header = new HBoxContainer();
|
||||
header.AddThemeConstantOverride("separation", 8);
|
||||
header.AddChild(UiTheme.Badge(T("Tutorial")));
|
||||
_counter.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
_counter.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||||
header.AddChild(_counter);
|
||||
_collapse.TooltipText = T("Riduci o espandi il riquadro del tutorial");
|
||||
_collapse.Pressed += () => SetCollapsed(!_collapsed);
|
||||
header.AddChild(_collapse);
|
||||
col.AddChild(header);
|
||||
|
||||
_progress.AddThemeStyleboxOverride("fill", UiTheme.Box(Palette.Amber, Palette.Amber, 2, 0));
|
||||
_progress.AddThemeStyleboxOverride("background", UiTheme.Box(Palette.Border, Palette.Border, 2, 0));
|
||||
col.AddChild(_progress);
|
||||
_title.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
col.AddChild(_title);
|
||||
|
||||
_body.AddThemeConstantOverride("separation", 10);
|
||||
col.AddChild(_body);
|
||||
_text.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
_body.AddChild(_text);
|
||||
_done.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
_done.Visible = false;
|
||||
_body.AddChild(_done);
|
||||
var buttons = new HBoxContainer();
|
||||
buttons.AddThemeConstantOverride("separation", 8);
|
||||
buttons.AddChild(_next);
|
||||
buttons.AddChild(_skip);
|
||||
buttons.AddChild(new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill });
|
||||
buttons.AddChild(_close);
|
||||
_body.AddChild(buttons);
|
||||
_next.Pressed += () => NextPressed?.Invoke();
|
||||
_skip.Pressed += () => SkipPressed?.Invoke();
|
||||
_close.Pressed += () => ClosePressed?.Invoke();
|
||||
_close.TooltipText = T("Il tutorial si riapre con F1 o dalla schermata iniziale");
|
||||
}
|
||||
|
||||
/// <summary>Mostra un passo: numero, titolo e testo già tradotti; Avanti solo per i passi informativi.</summary>
|
||||
public void ShowStep(int number, int count, string title, string text, bool informative, bool last)
|
||||
{
|
||||
_counter.Text = string.Format(T("Passo {0} di {1}"), number, count);
|
||||
_progress.MaxValue = count;
|
||||
_progress.Value = number - 1;
|
||||
_title.Text = title;
|
||||
_text.Text = text;
|
||||
_next.Visible = informative;
|
||||
_next.Text = last ? T("Fine") : T("Avanti");
|
||||
_skip.Visible = !informative;
|
||||
}
|
||||
|
||||
/// <summary>Breve conferma del passo appena completato.</summary>
|
||||
public void Flash(string completedTitle)
|
||||
{
|
||||
_done.Text = $"✓ {T("Fatto")}: {completedTitle}";
|
||||
_done.Visible = true;
|
||||
_doneTimer = 2.5;
|
||||
}
|
||||
|
||||
/// <summary>Area libera in cui ancorare il riquadro (rettangolo globale della mappa o del pannello a tutto schermo).</summary>
|
||||
public Rect2 Area { get; set; }
|
||||
|
||||
/// <summary>Elemento da evidenziare (rettangolo globale), null per nessuno.</summary>
|
||||
public Rect2? Target
|
||||
{
|
||||
get => _frame.Target;
|
||||
set => _frame.Target = value;
|
||||
}
|
||||
|
||||
private void SetCollapsed(bool collapsed)
|
||||
{
|
||||
_collapsed = collapsed;
|
||||
_body.Visible = !collapsed;
|
||||
_collapse.Text = collapsed ? "+" : "–";
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
if (_doneTimer > 0)
|
||||
{
|
||||
_doneTimer -= delta;
|
||||
if (_doneTimer <= 0) _done.Visible = false;
|
||||
}
|
||||
// in basso a sinistra dell'area libera; la larghezza si adatta alle finestre strette
|
||||
var area = Area.Size == Vector2.Zero ? GetViewportRect() : Area;
|
||||
float width = Math.Min(BoxWidth, Math.Max(240, area.Size.X - 2 * Margin));
|
||||
_box.CustomMinimumSize = new Vector2(width, 0);
|
||||
_box.Size = new Vector2(width, 0);
|
||||
var size = _box.GetCombinedMinimumSize();
|
||||
_box.Size = size;
|
||||
_box.Position = new Vector2(area.Position.X + Margin, area.End.Y - Margin - size.Y);
|
||||
}
|
||||
|
||||
/// <summary>Contorno ambra che pulsa attorno all'elemento evidenziato; non intercetta il mouse.</summary>
|
||||
private sealed partial class HighlightFrame : Control
|
||||
{
|
||||
private double _time;
|
||||
|
||||
public Rect2? Target { get; set; }
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect);
|
||||
MouseFilter = MouseFilterEnum.Ignore;
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
_time += delta;
|
||||
QueueRedraw();
|
||||
}
|
||||
|
||||
public override void _Draw()
|
||||
{
|
||||
if (Target is not { } t || t.Size.X <= 0 || t.Size.Y <= 0) return;
|
||||
float pulse = 0.5f + 0.5f * MathF.Sin((float)_time * 4f);
|
||||
float grow = 3 + 3 * pulse;
|
||||
var rect = t.Grow(grow);
|
||||
rect.Position -= GetGlobalRect().Position;
|
||||
var glow = new StyleBoxFlat { BgColor = Palette.WithAlpha(Palette.Amber, 0.06f + 0.06f * pulse), BorderColor = Palette.WithAlpha(Palette.AmberLight, 0.35f + 0.45f * pulse) };
|
||||
glow.SetBorderWidthAll(3);
|
||||
glow.SetCornerRadiusAll(10);
|
||||
DrawStyleBox(glow, rect);
|
||||
var outer = new StyleBoxFlat { BgColor = new Color(0, 0, 0, 0), BorderColor = Palette.WithAlpha(Palette.Amber, 0.25f * (1 - pulse)) };
|
||||
outer.SetBorderWidthAll(2);
|
||||
outer.SetCornerRadiusAll(14);
|
||||
DrawStyleBox(outer, rect.Grow(6 + 4 * pulse));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using Godot;
|
||||
|
||||
namespace RailEnterprise.Client.Tutorial;
|
||||
|
||||
/// <summary>
|
||||
/// Stato del tutorial nelle impostazioni del client (<c>user://settings.cfg</c>, sezione <c>tutorial</c>):
|
||||
/// se il giocatore ha già aperto una partita (la casella «Mostra il tutorial» è attiva solo alla prima)
|
||||
/// e l'avanzamento di ogni partita, con la chiave di <see cref="TutorialProgress.GameKey"/>.
|
||||
/// </summary>
|
||||
public static class TutorialSettings
|
||||
{
|
||||
private const string Path = "user://settings.cfg";
|
||||
private const string Section = "tutorial";
|
||||
|
||||
/// <summary>Vero dopo la prima partita aperta.</summary>
|
||||
public static bool Played
|
||||
{
|
||||
get => (bool)Load().GetValue(Section, "played", false);
|
||||
set => Write(cfg => cfg.SetValue(Section, "played", value));
|
||||
}
|
||||
|
||||
public static TutorialProgress? Read(string gameKey) =>
|
||||
TutorialProgress.Decode((string)Load().GetValue(Section, gameKey, ""));
|
||||
|
||||
public static void Save(string gameKey, TutorialProgress progress) =>
|
||||
Write(cfg => cfg.SetValue(Section, gameKey, progress.Encode()));
|
||||
|
||||
private static ConfigFile Load()
|
||||
{
|
||||
var cfg = new ConfigFile();
|
||||
cfg.Load(Path);
|
||||
return cfg;
|
||||
}
|
||||
|
||||
private static void Write(Action<ConfigFile> change)
|
||||
{
|
||||
// si rilegge il file ogni volta: le altre impostazioni (lingua) restano com'erano
|
||||
var cfg = Load();
|
||||
change(cfg);
|
||||
var error = cfg.Save(Path);
|
||||
if (error != Error.Ok) GD.PushWarning($"Impostazioni del tutorial non salvate: {error}");
|
||||
}
|
||||
}
|
||||
+24
-3
@@ -36,11 +36,12 @@
|
||||
"commuterCoverage": 0.6,
|
||||
"hubShare": 0.25,
|
||||
"noPartsFactor": 0.5,
|
||||
"townBonus": 1.8,
|
||||
"townRoiFactor": 0.5,
|
||||
"townBonus": 3.0,
|
||||
"townRoiFactor": 0.35,
|
||||
"repayCashMonths": 12,
|
||||
"planningDaySpacing": 7,
|
||||
"failedMemory": 64
|
||||
"failedMemory": 64,
|
||||
"partsDeferYears": 3.0
|
||||
},
|
||||
"market": {
|
||||
"founderAcceptPremium": 0.4,
|
||||
@@ -57,11 +58,31 @@
|
||||
"industryMaxCashShare": 0.25,
|
||||
"industryMinMargin": 0.1
|
||||
},
|
||||
"renewal": {
|
||||
"minSupersededYears": 3,
|
||||
"minAgeShareOfLife": 0.5,
|
||||
"cashReserveMultiple": 2.0,
|
||||
"maxTrainsPerMonth": 1
|
||||
},
|
||||
"trading": {
|
||||
"enabled": true,
|
||||
"minMargin": 0.25,
|
||||
"priceSlack": 0.06,
|
||||
"minSellPriceShare": 0.9,
|
||||
"maxUnits": 150,
|
||||
"maxTradesPerMonth": 2,
|
||||
"cashShare": 0.15,
|
||||
"cashReserveMultiple": 2.0
|
||||
},
|
||||
"personalities": [
|
||||
{ "id": "expansive", "name_it": "Espansiva", "roiThreshold": 0.08, "loanShareOfCredit": 0.8, "targetsPlayer": false, "buysShares": false, "maintenancePolicy": "standard" },
|
||||
{ "id": "prudent", "name_it": "Prudente", "roiThreshold": 0.15, "loanShareOfCredit": 0.3, "targetsPlayer": false, "buysShares": false, "maintenancePolicy": "standard" },
|
||||
{ "id": "predatory", "name_it": "Predatoria", "roiThreshold": 0.10, "loanShareOfCredit": 0.6, "targetsPlayer": true, "buysShares": true, "maintenancePolicy": "standard" }
|
||||
],
|
||||
"bots": [
|
||||
{ "id": "bot_competent", "name_it": "Bot competente", "roiThreshold": 0.10, "loanShareOfCredit": 0.6, "targetsPlayer": false, "buysShares": false, "maintenancePolicy": "standard" },
|
||||
{ "id": "bot_prudent", "name_it": "Bot prudente", "roiThreshold": 0.18, "loanShareOfCredit": 0.25, "targetsPlayer": false, "buysShares": false, "maintenancePolicy": "thorough" }
|
||||
],
|
||||
"companyNames": [
|
||||
"Strade Ferrate del Nord", "Società Ferroviaria Adriatica", "Compagnia delle Valli", "Ferrovie Meridionali",
|
||||
"Società Anonima delle Strade Ferrate", "Ferrovia Alta Valle", "Compagnia Lombardo-Veneta", "Rete del Litorale"
|
||||
|
||||
+9
-3
@@ -47,7 +47,7 @@
|
||||
"maxPriceFactor": 3.0,
|
||||
"ratioMin": 0.2,
|
||||
"ratioMax": 5.0,
|
||||
"world": { "amplitude": 0.12, "periodYears": 6, "volumeShare": 0.5, "baselinePerDay": 4.0, "elasticity": 1.0,
|
||||
"world": { "amplitude": 0.12, "periodYears": 6, "volumeShare": 1.0, "baselinePerDay": 4.0, "elasticity": 2.5,
|
||||
"shockChancePerYear": 0.25, "shockMin": 0.08, "shockMax": 0.30, "shockDecayDays": 150, "priceFloor": 0.05 },
|
||||
"historyDays": 720,
|
||||
"outlook": { "historyMonths": 24, "changeDays": 30, "forecastMonths": 4, "forecastBandPerMonth": 0.03, "sellPlaces": 3, "eventThreshold": 0.05 }
|
||||
@@ -67,7 +67,8 @@
|
||||
"initialStockDays": 10,
|
||||
"footprintCells": { "small": 2, "medium": 3, "large": 4 },
|
||||
"depletionStartFraction": 0.20,
|
||||
"startingCash": 2000000
|
||||
"startingCash": 2000000,
|
||||
"outlook": { "partnersPerGood": 3, "workforceSources": 4 }
|
||||
},
|
||||
"growth": {
|
||||
"quarterDays": 90,
|
||||
@@ -139,7 +140,12 @@
|
||||
"loanStep": 5000000,
|
||||
"startingRating": "BB",
|
||||
"depreciationYearsTrack": 50,
|
||||
"bookValueFloor": 0.1
|
||||
"bookValueFloor": 0.1,
|
||||
"incomeMonths": 12,
|
||||
"incomeYears": 10,
|
||||
"bankruptcyWarningDaysLeft": [ 30, 14, 7, 3, 1 ],
|
||||
"ratingMinRevenueMonths": 3,
|
||||
"negativeCashNoticeDays": 3
|
||||
},
|
||||
"stockMarket": {
|
||||
"shares": 1000000,
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
{ "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.03, "spareParts": 1, "effect": "repair", "restoreTo": 80 },
|
||||
{ "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.3, "spareParts": 8, "effect": "replace" }
|
||||
{ "id": "repair_catastrophic", "name_it": "Ricostruzione dopo deragliamento", "days": 30, "costShare": 0.3, "spareParts": 8, "effect": "replace" },
|
||||
{ "id": "renewal", "name_it": "Rinnovo dei veicoli superati", "days": 4, "costShare": 0.005, "spareParts": 0, "effect": "renew" }
|
||||
],
|
||||
"inspection": { "brakesTo": 100, "othersPlus": 10, "hazardFactor": 0.5, "hazardDays": 30 },
|
||||
"service": { "plus": 40 },
|
||||
|
||||
+353
-11
@@ -12,16 +12,225 @@
|
||||
},
|
||||
"planning": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": [
|
||||
"number",
|
||||
"integer",
|
||||
"boolean",
|
||||
"array",
|
||||
"object",
|
||||
"string"
|
||||
]
|
||||
}
|
||||
"properties": {
|
||||
"intervalDays": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"maxCandidates": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"maxProjectsPerMonth": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"candidateMaxDistanceKm": {
|
||||
"type": "number",
|
||||
"exclusiveMinimum": 0
|
||||
},
|
||||
"candidateMinDistanceKm": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"pathSlopePenalty": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"pathWaterPenalty": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"steepPenalty": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"steepGradeFactor": {
|
||||
"type": "number",
|
||||
"exclusiveMinimum": 0
|
||||
},
|
||||
"pathMarginRetryKm": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"trainsPerLine": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"wagonsPerTrain": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"cashReserveMonths": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"revenueHorizonYears": {
|
||||
"type": "number",
|
||||
"exclusiveMinimum": 0
|
||||
},
|
||||
"maxRejectedShare": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"maxConcurrentProjects": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"evaluateTop": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"pathMarginKm": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"simplifyToleranceM": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"stationOffsetsM": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"items": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
}
|
||||
},
|
||||
"depotOffsetM": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"platforms": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"hubPlatforms": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"assumedEfficiency": {
|
||||
"type": "number",
|
||||
"exclusiveMinimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"speedFactor": {
|
||||
"type": "number",
|
||||
"exclusiveMinimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"dwellMinutes": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"maintenanceCostShare": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"trackUpkeepPerKmPerYear": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"maxTrainsPerLine": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"addTrainWaitingTrips": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"minCommuters": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"commuterCoverage": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"hubShare": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"noPartsFactor": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"townBonus": {
|
||||
"type": "number",
|
||||
"minimum": 1,
|
||||
"maximum": 10
|
||||
},
|
||||
"townRoiFactor": {
|
||||
"type": "number",
|
||||
"exclusiveMinimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"repayCashMonths": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"planningDaySpacing": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"failedMemory": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"partsDeferYears": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 10
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"intervalDays",
|
||||
"maxCandidates",
|
||||
"maxProjectsPerMonth",
|
||||
"candidateMaxDistanceKm",
|
||||
"candidateMinDistanceKm",
|
||||
"pathSlopePenalty",
|
||||
"pathWaterPenalty",
|
||||
"steepPenalty",
|
||||
"steepGradeFactor",
|
||||
"pathMarginRetryKm",
|
||||
"trainsPerLine",
|
||||
"wagonsPerTrain",
|
||||
"cashReserveMonths",
|
||||
"revenueHorizonYears",
|
||||
"maxRejectedShare",
|
||||
"maxConcurrentProjects",
|
||||
"evaluateTop",
|
||||
"pathMarginKm",
|
||||
"simplifyToleranceM",
|
||||
"stationOffsetsM",
|
||||
"depotOffsetM",
|
||||
"platforms",
|
||||
"hubPlatforms",
|
||||
"assumedEfficiency",
|
||||
"speedFactor",
|
||||
"dwellMinutes",
|
||||
"maintenanceCostShare",
|
||||
"trackUpkeepPerKmPerYear",
|
||||
"maxTrainsPerLine",
|
||||
"addTrainWaitingTrips",
|
||||
"minCommuters",
|
||||
"commuterCoverage",
|
||||
"hubShare",
|
||||
"noPartsFactor",
|
||||
"townBonus",
|
||||
"townRoiFactor",
|
||||
"repayCashMonths",
|
||||
"planningDaySpacing",
|
||||
"failedMemory",
|
||||
"partsDeferYears"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"personalities": {
|
||||
"type": "array",
|
||||
@@ -74,6 +283,57 @@
|
||||
},
|
||||
"minItems": 3
|
||||
},
|
||||
"bots": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"pattern": "^[a-z][a-z0-9_]*$"
|
||||
},
|
||||
"name_it": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"roiThreshold": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"loanShareOfCredit": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"targetsPlayer": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"buysShares": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"maintenancePolicy": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"economy",
|
||||
"standard",
|
||||
"thorough"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"name_it",
|
||||
"roiThreshold",
|
||||
"loanShareOfCredit",
|
||||
"targetsPlayer",
|
||||
"buysShares",
|
||||
"maintenancePolicy"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"minItems": 1
|
||||
},
|
||||
"companyNames": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
@@ -91,6 +351,85 @@
|
||||
},
|
||||
"minItems": 1
|
||||
},
|
||||
"renewal": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"minSupersededYears": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"minAgeShareOfLife": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"cashReserveMultiple": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"maxTrainsPerMonth": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"minSupersededYears",
|
||||
"minAgeShareOfLife",
|
||||
"cashReserveMultiple",
|
||||
"maxTrainsPerMonth"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"trading": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enabled": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"minMargin": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 5
|
||||
},
|
||||
"priceSlack": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"minSellPriceShare": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 3
|
||||
},
|
||||
"maxUnits": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"maxTradesPerMonth": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"cashShare": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"cashReserveMultiple": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"enabled",
|
||||
"minMargin",
|
||||
"priceSlack",
|
||||
"minSellPriceShare",
|
||||
"maxUnits",
|
||||
"maxTradesPerMonth",
|
||||
"cashShare",
|
||||
"cashReserveMultiple"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"market": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
@@ -108,7 +447,10 @@
|
||||
"personalities",
|
||||
"companyNames",
|
||||
"colors",
|
||||
"market"
|
||||
"market",
|
||||
"renewal",
|
||||
"trading",
|
||||
"bots"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -242,16 +242,68 @@
|
||||
},
|
||||
"world": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": [
|
||||
"number",
|
||||
"integer",
|
||||
"boolean",
|
||||
"array",
|
||||
"object",
|
||||
"string"
|
||||
]
|
||||
}
|
||||
"properties": {
|
||||
"amplitude": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 0.5
|
||||
},
|
||||
"periodYears": {
|
||||
"type": "number",
|
||||
"exclusiveMinimum": 0
|
||||
},
|
||||
"volumeShare": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 10
|
||||
},
|
||||
"baselinePerDay": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"elasticity": {
|
||||
"type": "number",
|
||||
"exclusiveMinimum": 0,
|
||||
"maximum": 10
|
||||
},
|
||||
"shockChancePerYear": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"shockMin": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"shockMax": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"shockDecayDays": {
|
||||
"type": "number",
|
||||
"exclusiveMinimum": 0
|
||||
},
|
||||
"priceFloor": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"amplitude",
|
||||
"periodYears",
|
||||
"volumeShare",
|
||||
"baselinePerDay",
|
||||
"elasticity",
|
||||
"shockChancePerYear",
|
||||
"shockMin",
|
||||
"shockMax",
|
||||
"shockDecayDays",
|
||||
"priceFloor"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"historyDays": {
|
||||
"type": "integer",
|
||||
|
||||
@@ -160,7 +160,8 @@
|
||||
"service",
|
||||
"overhaul",
|
||||
"repair",
|
||||
"replace"
|
||||
"replace",
|
||||
"renew"
|
||||
]
|
||||
},
|
||||
"restoreTo": {
|
||||
|
||||
@@ -31,6 +31,10 @@
|
||||
"maxItems": 10,
|
||||
"uniqueItems": true
|
||||
},
|
||||
"ratingProgressSteps": {
|
||||
"type": "number",
|
||||
"exclusiveMinimum": 0
|
||||
},
|
||||
"tiers": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
@@ -152,6 +156,7 @@
|
||||
"required": [
|
||||
"version",
|
||||
"ratingScale",
|
||||
"ratingProgressSteps",
|
||||
"tiers"
|
||||
],
|
||||
"additionalProperties": false
|
||||
|
||||
@@ -10,6 +10,32 @@
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"obsolescence": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"immediateValueLoss": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 0.9
|
||||
},
|
||||
"depreciationSpeed": {
|
||||
"type": "number",
|
||||
"minimum": 1,
|
||||
"maximum": 10
|
||||
},
|
||||
"maintenanceCostFactor": {
|
||||
"type": "number",
|
||||
"minimum": 1,
|
||||
"maximum": 10
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"immediateValueLoss",
|
||||
"depreciationSpeed",
|
||||
"maintenanceCostFactor"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"vehicles": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
@@ -45,6 +71,10 @@
|
||||
"minimum": 1800,
|
||||
"maximum": 2300
|
||||
},
|
||||
"successor": {
|
||||
"type": "string",
|
||||
"pattern": "^[a-z][a-z0-9_]*$"
|
||||
},
|
||||
"powerKw": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
@@ -152,6 +182,7 @@
|
||||
},
|
||||
"required": [
|
||||
"version",
|
||||
"obsolescence",
|
||||
"vehicles"
|
||||
],
|
||||
"additionalProperties": false
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
"$schema": "schema/tiers.schema.json",
|
||||
"version": 1,
|
||||
"ratingScale": [ "AAA", "AA", "A", "BBB", "BB", "B", "CCC", "CC", "C", "D" ],
|
||||
"ratingProgressSteps": 2.5,
|
||||
"tiers": [
|
||||
{ "level": 1, "name_it": "Compagnia locale", "name_en": "Local company",
|
||||
"requirements": { "netWorth": 0, "connectedTownsOver": { "count": 0, "population": 0 }, "creditRating": "D" },
|
||||
|
||||
+6
-5
@@ -1,17 +1,18 @@
|
||||
{
|
||||
"$schema": "schema/vehicles.schema.json",
|
||||
"version": 1,
|
||||
"obsolescence": { "immediateValueLoss": 0.15, "depreciationSpeed": 2.0, "maintenanceCostFactor": 1.5 },
|
||||
"vehicles": [
|
||||
{ "id": "loco_steam_1850", "kind": "locomotive", "name_it": "Ardita 2-6-0", "name_en": "Ardita 2-6-0",
|
||||
"eraFrom": 1850, "eraTo": 1905, "powerKw": 300, "tractiveEffortKn": 70, "maxSpeedKmh": 60, "massT": 38, "lengthM": 16,
|
||||
"eraFrom": 1850, "eraTo": 1905, "successor": "loco_steam_1878", "powerKw": 300, "tractiveEffortKn": 70, "maxSpeedKmh": 60, "massT": 38, "lengthM": 16,
|
||||
"price": 1800000, "runningCostPerYear": 240000, "lifeYears": 25, "traction": "steam",
|
||||
"components": { "engine": 1.0, "wheelsets": 0.8, "brakes": 1.0, "electrics": 0.6 } },
|
||||
{ "id": "loco_steam_1878", "kind": "locomotive", "name_it": "Vittoria 2-8-0", "name_en": "Vittoria 2-8-0",
|
||||
"eraFrom": 1878, "eraTo": 1935, "powerKw": 650, "tractiveEffortKn": 110, "maxSpeedKmh": 70, "massT": 62, "lengthM": 18,
|
||||
"eraFrom": 1878, "eraTo": 1935, "successor": "loco_steam_1902", "powerKw": 650, "tractiveEffortKn": 110, "maxSpeedKmh": 70, "massT": 62, "lengthM": 18,
|
||||
"price": 3200000, "runningCostPerYear": 380000, "lifeYears": 30, "traction": "steam",
|
||||
"components": { "engine": 1.0, "wheelsets": 0.9, "brakes": 1.0, "electrics": 0.6 } },
|
||||
{ "id": "loco_steam_1902", "kind": "locomotive", "name_it": "Freccia 4-6-2", "name_en": "Freccia 4-6-2",
|
||||
"eraFrom": 1902, "eraTo": 1945, "powerKw": 1150, "tractiveEffortKn": 95, "maxSpeedKmh": 110, "massT": 88, "lengthM": 21,
|
||||
"eraFrom": 1902, "eraTo": 1945, "successor": "loco_diesel_1925", "powerKw": 1150, "tractiveEffortKn": 95, "maxSpeedKmh": 110, "massT": 88, "lengthM": 21,
|
||||
"price": 5600000, "runningCostPerYear": 560000, "lifeYears": 30, "traction": "steam",
|
||||
"components": { "engine": 1.1, "wheelsets": 1.0, "brakes": 1.0, "electrics": 0.6 } },
|
||||
{ "id": "loco_diesel_1925", "kind": "locomotive", "name_it": "Aquila D1", "name_en": "Aquila D1",
|
||||
@@ -19,7 +20,7 @@
|
||||
"price": 7500000, "runningCostPerYear": 420000, "lifeYears": 30, "traction": "diesel",
|
||||
"components": { "engine": 0.9, "wheelsets": 0.8, "brakes": 0.9, "electrics": 0.9 } },
|
||||
{ "id": "loco_electric_1950", "kind": "locomotive", "name_it": "Saetta E50", "name_en": "Saetta E50",
|
||||
"eraFrom": 1950, "eraTo": 2010, "powerKw": 3200, "tractiveEffortKn": 260, "maxSpeedKmh": 160, "massT": 84, "lengthM": 18,
|
||||
"eraFrom": 1950, "eraTo": 2010, "successor": "loco_highspeed_1990", "powerKw": 3200, "tractiveEffortKn": 260, "maxSpeedKmh": 160, "massT": 84, "lengthM": 18,
|
||||
"price": 14000000, "runningCostPerYear": 520000, "lifeYears": 35, "traction": "electric",
|
||||
"components": { "engine": 0.7, "wheelsets": 0.9, "brakes": 0.9, "electrics": 1.2 } },
|
||||
{ "id": "loco_highspeed_1990", "kind": "locomotive", "name_it": "Lampo AV", "name_en": "Lampo HS",
|
||||
@@ -43,7 +44,7 @@
|
||||
"capacity": 16, "wagonType": "box", "goods": [ "food", "goods", "tools", "spare_parts", "livestock", "grain" ],
|
||||
"components": { "axles": 1.0, "brakes": 1.0, "body": 1.0 } },
|
||||
{ "id": "coach_worker", "kind": "coach", "name_it": "Carrozza operai", "name_en": "Workers' coach",
|
||||
"eraFrom": 1850, "maxSpeedKmh": 100, "massT": 18, "lengthM": 14, "price": 220000, "runningCostPerYear": 20000, "lifeYears": 40,
|
||||
"eraFrom": 1850, "successor": "coach_modern", "maxSpeedKmh": 100, "massT": 18, "lengthM": 14, "price": 220000, "runningCostPerYear": 20000, "lifeYears": 40,
|
||||
"paxCapacity": 60, "class": "worker",
|
||||
"components": { "axles": 1.0, "brakes": 1.0, "body": 1.0 } },
|
||||
{ "id": "coach_staff", "kind": "coach", "name_it": "Carrozza tecnici", "name_en": "Staff coach",
|
||||
|
||||
+13
-8
@@ -8,7 +8,7 @@ Questo documento descrive come è fatto il codice. Va aggiornato a ogni fase: le
|
||||
RailEnterprise.Core (net10.0; net8.0) simulazione deterministica, dati, mappa, economia, rete, salvataggi
|
||||
RailEnterprise.Protocol (net10.0; net8.0) frame binari, messaggi, SpanWriter/SpanReader → Core
|
||||
RailEnterprise.Server (net10.0, Web SDK) Kestrel, WebSocket, GameLoop, API HTTP, autosave → Core, Protocol
|
||||
RailEnterprise.Tools (net10.0) railenterprise-tools: validate-data, genmap, profile, simulate, bench, smoke, replay → Core, Protocol
|
||||
RailEnterprise.Tools (net10.0) railenterprise-tools: validate-data, genmap, profile, simulate, balance, bench, smoke, replay → Core, Protocol
|
||||
RailEnterprise.Tests (net10.0) harness interno, test di unità, scenari → Core, Protocol, Server
|
||||
client/RailEnterprise.Client (Godot .NET) rendering, input, UI; anteprime con Core → Core, Protocol
|
||||
```
|
||||
@@ -40,7 +40,7 @@ Regole:
|
||||
```
|
||||
Clock → Commands → Construction → Trains → Signals → Stations → Maintenance (treni)
|
||||
→ Demand (giornaliero) → Commuting → Industries → IndustryMaintenance → Towns → Market
|
||||
→ Finance → StockMarket → AiAgents (mensile) → Events → Contracts → Hash (giornaliero)
|
||||
→ Finance → StockMarket → AiAgents (mensile) → Events → Eras (annuale) → Contracts → Hash (giornaliero)
|
||||
```
|
||||
|
||||
Sistemi implementati (F1–F5), nella loro posizione:
|
||||
@@ -60,16 +60,17 @@ Sistemi implementati (F1–F5), nella loro posizione:
|
||||
| `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 |
|
||||
| `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, livelli (`Tiers`), utile mensile nell'anello dei 12 mesi, chiusura dei conti |
|
||||
| `FinanceSystem` | giorno/mese/anno | costi di esercizio dei veicoli (`RunningCosts`) e di stazioni e depositi (`StationUpkeep`), stipendi del personale presente nei depositi (`Wages`), valori di libro per voce (`BookValues`, ADR 0018), cassa negativa con gli avvisi e bancarotta ai giorni della difficoltà, rate dei prestiti a tasso fisso, chiusura del mese nel conto economico per voce (`IncomeMonths`, `IncomeYears`) e nell'anello dei 12 mesi, rating da margine (12 mesi) e leva (debiti / patrimonio) con le misure conservate, livelli (`Tiers`), chiusura dei conti (ADR 0019) |
|
||||
| `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) |
|
||||
| `EventSystem` | giorno | eventi del mondo (F6, ADR 0017): chiude quelli scaduti, estrae i nuovi dal catalogo `events.json` con il flusso «events» e la frequenza della difficoltà, notizie d'inizio e di fine (posto di «Events») |
|
||||
| `EraSystem` | anno | novità tecnologiche (F6, ADR 0020): il 1° gennaio, dai dati, la notizia dell'era che inizia, di trazioni, veicoli, ponti, gallerie, binari, segnali, elettrificazione, merci e industrie introdotti, dei modelli superati e di quelli fuori produzione (`EventKind.Technology`), annotata nella Cronaca; senza stato |
|
||||
| `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`.
|
||||
- `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.
|
||||
- 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 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). Il bot giocatore del banco di bilanciamento (`World.PlayerBot`, ADR 0025) usa lo stesso agente per la compagnia del giocatore, prima delle IA, e non è salvato. 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).
|
||||
|
||||
## 4. Determinismo
|
||||
@@ -92,8 +93,8 @@ Requisito: stesso seme + stessi comandi agli stessi tick ⇒ stesso hash di stat
|
||||
|
||||
## 6. Economia e contabilità
|
||||
|
||||
- Entità in `RailEnterprise.Core.Economy`: `Town`, `Industry`, `Hub`, `ResourceSite`, `Company` (con `Loan`), `CommuteContract`, `Market`, `Tariffs`; `MarketOutlook` (F6, ADR 0015) è l'analisi in sola lettura per il pannello «Mercato globale»: storico mensile, previsione dalla componente mondiale, destinazioni di vendita, hub, evento in corso, avanzamento verso il commercio.
|
||||
- Ogni movimento di denaro passa dal registro (`MoneyLedger.Transfer`) tra conti: compagnie, industrie e il conto `Esterno` (famiglie, clienti delle tariffe, mercato mondiale). La somma di tutti i saldi è sempre zero: è l'invariante «denaro» dei test. Le voci del conto economico delle compagnie (`LedgerEntry`) si accumulano per mese e per anno.
|
||||
- Entità in `RailEnterprise.Core.Economy`: `Town`, `Industry`, `Hub`, `ResourceSite`, `Company` (con `Loan`), `CommuteContract`, `Market`, `Tariffs`; `MarketOutlook` (F6, ADR 0015) è l'analisi in sola lettura per il pannello «Mercato globale»: storico mensile, previsione dalla componente mondiale, destinazioni di vendita, hub, evento in corso, avanzamento verso il commercio. `ClimbOutlook` (F6, ADR 0018) è l'analisi in sola lettura per «La tua scalata»: livelli con gli sblocchi dai dati (`Tiers.NewUnlocks`), requisiti del prossimo livello con l'avanzamento (media delle tre frazioni, usata anche dal Mercato globale), stato patrimoniale per voce che somma al patrimonio netto del motore, conto economico, prestiti, storico del patrimonio dalla Cronaca. `FinanceOutlook` (F6, ADR 0019) è l'analisi in sola lettura per il pannello «Finanze»: conto economico per voce (mese in corso, mesi chiusi, anno in corso, anni chiusi) che somma all'utile operativo del motore, spiegazione del rating (misure, componenti, soglie, cosa serve per salire), prestiti con rata e scadenza, fido, giorni di cassa negativa sul limite della difficoltà. `IndustryOutlook` (F6, ADR 0021) è l'analisi in sola lettura per la scheda dell'industria: fattori dell'efficienza e quello che la limita, ingressi e uscite al mese con giorni di scorta o di magazzino, fornitori e clienti con prezzo e linea che li collega, forza lavoro dai contratti dei pendolari, punteggio di crescita del trimestre (`IndustryMath.GrowthScore`, la stessa formula del motore) con le soglie, sblocco dell'acquisto. `FleetOutlook` (F6, ADR 0020) è il quadro in sola lettura del rinnovo della flotta: era in corso e prossima, veicoli con età, superato, successore consigliato, valore di libro, rivendita e fattore di manutenzione, catalogo dei modelli in produzione, treni da rinnovare con la spesa netta. `Explanations` (F6, ADR 0024) costruisce le spiegazioni «perché» (`Explanation`: formula, termini con i valori di oggi, note) di prezzo globale e locale, tariffe, efficienza e crescita delle industrie, crescita delle città, condizione dei treni, rating, avanzamento del livello, valore dei veicoli e cassa, chiamando le stesse funzioni del motore (`Market.NextPrice` e `LocalPriceTerms`, `Tariffs.FreightTerms` e `PassengerTerms`, `TownSystem.GrowthOf`, `Fleet.DailyHazard` e `ConditionDue`, `Industry.LastEfficiency` registrato da `IndustrySystem`, transitorio): il valore spiegato è lo stesso numero del motore. Produzione, obsolescenza e valore dei veicoli vengono da `Simulation.Systems.Obsolescence` (senza stato, dai dati, dal calendario e dal giorno d'acquisto): è l'unica fonte del valore per il patrimonio (`FinanceSystem.BookValues`), `SellVehicle`, il rinnovo in officina (intervento «renewal», effetto `renew`) e i costi di manutenzione dei modelli superati.
|
||||
- Ogni movimento di denaro passa dal registro (`MoneyLedger.Transfer`) tra conti: compagnie, industrie e il conto `Esterno` (famiglie, clienti delle tariffe, mercato mondiale). La somma di tutti i saldi è sempre zero: è l'invariante «denaro» dei test. Le voci del conto economico delle compagnie (`LedgerEntry`) si accumulano per mese e per anno; `LedgerEntries` ne fissa l'ordine e le sezioni (ricavi, costi, investimenti e finanziamenti) e `Company.OperatingProfit` è la somma di ricavi e costi (ADR 0019). Un trasferimento può usare voci diverse per chi paga e chi incassa (dividendi pagati e incassati).
|
||||
- Ogni unità di merce sta in un magazzino tracciato (industrie, città, magazzini delle compagnie nelle stazioni, pacchetti in stazione e a bordo dei treni) e `GoodsCounters` registra prodotto, consumato, deperito, importato, esportato: giacenza = prodotto + importato − consumato − deperito − esportato. È l'invariante «merci».
|
||||
- Compravendita in proprio (F6, ADR 0016): `TradingCommandHandlers` esegue `BuyGoods`, `SellGoods` e `ShipGoods` con il prezzo locale marginale di `Systems/TradingMath` (unità per unità, controparti ordinate per prezzo). La merce comprata sta in `Station.Stock`; quella spedita viaggia in pacchetti con `Packet.Owned`, senza tariffa né consumatore, ed entra nel magazzino della stazione d'arrivo. Gli scambi con le industrie passano dal registro sulla voce «Commercio», quelli con gli hub contano come importazione ed esportazione; `StationSystem` addebita ogni mese la giacenza dei magazzini.
|
||||
- Eventi del mondo (F6, ADR 0017): `World.WorldEvents` (`WorldEventState`) è l'unica sorgente dei loro effetti. I sistemi chiedono un moltiplicatore per entità (1 senza eventi): `IndustryCapacity` in `IndustrySystem` e nella domanda di input di `DemandSystem`, `TownDemand` in `DemandSystem.TownDemand`, `Attendance` nelle presenze dei pendolari di `EmploymentSystem`, `EdgeSpeed` in `TrainSystem` ed `EdgeWear` nell'usura del binario di `ConstructionSystem` (traffico del giorno prima). Contano solo gli eventi in vigore nel giorno dell'orologio, [inizio, fine). Nessuno stato di base viene modificato: a evento finito il moltiplicatore torna 1. Le stime dei candidati delle IA leggono i valori senza eventi.
|
||||
@@ -108,6 +109,8 @@ Requisito: stesso seme + stessi comandi agli stessi tick ⇒ stesso hash di stat
|
||||
- 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).
|
||||
- Corpo versione 4 (F6): `TradingSerializer` aggiunge i magazzini delle compagnie nelle stazioni (beni per id testuale) e gli id dei pacchetti di merce propria in stazione e a bordo; i salvataggi precedenti si caricano con i magazzini vuoti. `WorldSerializer.Write(w, s, versione)` scrive un corpo di una versione precedente per i test di migrazione (ADR 0016).
|
||||
- Corpo versione 5 (F6): `EventSerializer` aggiunge il prossimo id e gli eventi del mondo attivi (tipo e bene per id testuale, bersaglio, giorni, intensità; la zona si ricalcola dal catalogo); le impostazioni salvano `eventFrequencyMultiplier`. I salvataggi precedenti si caricano senza eventi e con la frequenza del preset (ADR 0017).
|
||||
- Corpo versione 6 (F6): `BalanceSheetSerializer` aggiunge per ogni compagnia il valore contabile per voce (`AssetCategory`) e il giorno in cui ha raggiunto ogni livello. I salvataggi precedenti ripartiscono il totale salvato in proporzione alle voci calcolate al caricamento (stesso patrimonio netto) e ricostruiscono i giorni dai fatti salienti o dallo storico (ADR 0018).
|
||||
- Corpo versione 7 (F6): `FinanceSerializer` aggiunge per ogni compagnia i mesi e gli anni chiusi per voce del registro e le misure dell'ultimo calcolo del rating. I salvataggi precedenti partono senza mesi chiusi, con l'ultimo anno chiuso dal registro e la spiegazione del rating sulle misure del giorno fino al primo calcolo mensile (ADR 0019).
|
||||
|
||||
## 8. Server
|
||||
|
||||
@@ -122,10 +125,12 @@ Requisito: stesso seme + stessi comandi agli stessi tick ⇒ stesso hash di stat
|
||||
## 9. Client
|
||||
|
||||
- Progetto Godot 4.7 .NET in `client/RailEnterprise.Client` (fuori dalla soluzione), compilato con `Godot.NET.Sdk`; referenzia Core e Protocol (net8.0). I file dati e gli schemi si copiano in `res://data` a ogni build.
|
||||
- `Main` → `MenuScreen` / `ConnectScreen` / `GameScreen`. `LocalServerLauncher` avvia il server come processo figlio per la partita locale.
|
||||
- `Main` → `ConnectScreen` (immagine 09: server locale o in rete, stato dal blocco `ServerInfo` del `Welcome`, partite salvate, riprendi o nuova partita su una sessione di prova che poi diventa la partita) → `GameScreen`. `LocalServerLauncher` avvia il server come processo figlio per la partita locale.
|
||||
- `GameSession` applica i messaggi a `ClientWorld` (Protocol) sul thread principale; i comandi sono l'unico modo di cambiare il mondo; le anteprime del tracciato usano `TrackPreview` di Core.
|
||||
- `MapView` (Node2D + Camera2D): `TerrainLayer` (texture per chunk con fasce, ombreggiatura, sponde e curve di livello; shader per le rive), `EntityLayer` (case, industrie, stazioni, depositi, alberi in MultiMesh), `TrackLayer` (massicciata, traversine, rotaie, opere, cantieri, segnali), `TrainLayer` (veicoli interpolati, fumo, avvisi), `ToolOverlay`; `LabelLayer` disegna le etichette in coordinate schermo.
|
||||
- HUD: `TopBar`, `Toolbar`, pannello destro (pannelli degli strumenti e schede) con `Minimap`, `Ticker`. Pannelli: binari con profilo, stazione, deposito, treni, linee, officine (politica della flotta, avvisi, flotta per condizione, cartella di manutenzione, Registro officina, scorta di ricambi, mappa di calore), impieghi (Registro degli impieghi e convenzioni), mercato, finanze, scheda dell'entità (con manutenzione del treno, lavoratori dell'industria, dove lavorano gli abitanti, avvisi degli eventi in corso). Sopra la minimappa il riquadro «Eventi in corso» (`WorldEventsBox`, testi in `WorldEventText`) elenca gli eventi del mondo del `DailyDigest`; il Mercato globale mostra quelli sulla domanda di un bene.
|
||||
- HUD: `TopBar` (con l'altoparlante dell'audio), `Toolbar`, pannello destro (pannelli degli strumenti e schede) con `Minimap`, `Ticker`. Pannelli: binari con profilo, stazione, deposito, treni, linee, officine (politica della flotta, avvisi, flotta per condizione, cartella di manutenzione, Registro officina, scorta di ricambi, mappa di calore), impieghi (Registro degli impieghi e convenzioni), mercato, finanze; a tutto schermo «Compagnie e borsa», «Mercato globale» (`MarketPanel`, immagine 06) e «La tua scalata» (`ClimbPanel`, immagine 08: binario dei livelli, storico del patrimonio con `SeriesChart` e i livelli segnati, requisiti, stato patrimoniale, conto economico, prestiti), che si apre anche dal livello nella `TopBar`, e la scheda dell'industria (`IndustryPanel`, immagine 07: ingressi, forza lavoro, produzione, grafo della catena `ChainGraph`, impianti e crescita, dati da `IndustryOutlook` nel blocco 1 di `IndustryCard`); scheda dell'entità (con manutenzione del treno, lavoratori dell'industria, dove lavorano gli abitanti, avvisi degli eventi in corso). Sopra la minimappa il riquadro «Eventi in corso» (`WorldEventsBox`, testi in `WorldEventText`) elenca gli eventi del mondo del `DailyDigest`; il Mercato globale mostra quelli sulla domanda di un bene. Il tooltip «perché» (`WhyTooltip`, uno per la schermata di gioco su un suo `CanvasLayer`, ADR 0024) si aggancia ai valori di barra superiore, Mercato globale, Scalata, Finanze, scheda dell'industria, Treni e Officine: mostra la spiegazione ricevuta dal server (`ExplanationReport`, in cache in `ClientWorld.Explanations`), la chiede a ogni apertura e poi al più una volta al secondo per valore, e resta aperto quando il pannello ricostruisce il controllo sotto il puntatore.
|
||||
- Audio (`scripts/Audio/`, ADR 0022): `AudioManager`, figlio di `Main` con `AudioManager.Instance`, crea i bus `Music`, `Ambience`, `Sfx`, `Ui` (`AudioBuses.Ensure`, idempotente), applica i volumi di `AudioSettings` (`user://settings.cfg`, sezione `audio`) e reagisce a ciò che il client riceve: clic dei pulsanti (segnale `node_added`), esiti dei comandi, `Notification`, cantieri completati nel `DailyDigest`, treni visibili in moto vicini al centro (`TrainLayer.Heads`, al più 3 canali, solo con un moto recente in `GameSession.MotionReceivedMs`), terreno e zoom della vista per l'ambiente, anno corrente per il tema dell'era. I suoni si sintetizzano su un altro thread con classi senza Godot: `Synth` (effetti e anelli senza scatti), `MusicComposer` (temi per era da un seme fisso), `AudioMix` (miscelazione, scelta dei treni senza allocazioni, PCM). Pannello `AudioSettingsPanel` (dalla schermata di connessione e da `SpeakerButton` nella `TopBar`), tasto M per il muto; nel pilota automatico l'audio è spento.
|
||||
- Tutorial (ADR 0023): copione `assets/tutorial/tutorial.json`; logica pura senza Godot in `scripts/Tutorial/Logic` (`TutorialScript` con validazione, `TutorialFacts`, condizioni, `TutorialMachine`, `TutorialProgress`), compilata anche dal progetto dei test; `TutorialController` raccoglie i fatti osservati (entità della compagnia in `ClientWorld`, esiti riusciti dei comandi, strumento aperto, camera, velocità chieste da questo client con `GameSession.SpeedRequests`, anteprime del tracciato) e salva l'avanzamento per partita in `user://settings.cfg` (chiave da origine e dati fissi del Welcome); `TutorialOverlay` disegna il riquadro non modale e il contorno sull'elemento che `GameScreen.TutorialTarget` risolve. Si avvia dalla schermata di connessione («Mostra il tutorial» per la partita che si apre; «Tutorial» apre una partita di prova nuova in `user://tutorial-server`), F1 lo nasconde o lo riapre; non c'è nel pilota automatico.
|
||||
- Collaudo: pilota automatico (`-- --autopilot cartella`, `scripts/client-autopilot.sh`) con schermate.
|
||||
|
||||
## 10. Prestazioni
|
||||
|
||||
+32
-6
@@ -51,7 +51,7 @@ offset tipo campo
|
||||
|
||||
```
|
||||
Client → Hello { protocolVersion: u16, clientVersion: string, token: string, resumeSessionId: u64, dataHash: u64 }
|
||||
Server → Welcome { sessionId: u64, summary: WorldSummary, dataHash: u64, difficulty: string }
|
||||
Server → Welcome { sessionId: u64, summary: WorldSummary, dataHash: u64, difficulty: string }; blocco 1 (F6): server: ServerInfo
|
||||
| Reject { code: u16, reason: string }
|
||||
```
|
||||
|
||||
@@ -59,6 +59,13 @@ Server → Welcome { sessionId: u64, summary: WorldSummary, dataHash: u64, diffi
|
||||
- `dataHash` ≠ 0 deve coincidere con l'hash dei dati del server.
|
||||
- Codici di `Reject`: 1 versione del protocollo, 2 token errato, 3 dati diversi, 4 server pieno, 5 nessuna partita.
|
||||
- `Welcome` può arrivare di nuovo durante la sessione (nuova partita o caricamento): il client azzera la copia del mondo.
|
||||
- Blocco 1 del `Welcome` (F6, ADR 0021): stato del server per la schermata di connessione (immagine 09), calcolato
|
||||
all'invio del `Welcome`.
|
||||
|
||||
`ServerInfo { version: string (versione del server), os: string (sistema operativo), container: bool (in Docker),
|
||||
uptimeSeconds: i64 (da quando il processo è attivo), tickMs: f32 (passo del ciclo di gioco: 1000 / tickMs tick al
|
||||
secondo), sessions: i32 (client collegati, compreso chi riceve il messaggio), maxSessions: i32, local: bool (server
|
||||
figlio del gioco) }`. La latenza non viaggia: il client la misura con `Ping`/`Pong`.
|
||||
|
||||
`WorldSummary { seed: u64, sizeKm: i32, startYear: i32, tick: i64, date: string, companyId: i32, companyName: string,
|
||||
regionId: string, widthCells: i32, heightCells: i32, cellSizeM: f64, chunkCells: i32, speed: u8, terrainHash: u64,
|
||||
@@ -77,7 +84,7 @@ costMultiplier: f64 }`
|
||||
| 7 | Save | `name: string` |
|
||||
| 8 | Load | `saveId: string` |
|
||||
| 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; dalla F5: 4 scheda di una compagnia, 5 scheda di un'industria, 6 Cronaca; dalla F6: 7 quadro del mercato globale), `target: i32` (id del treno, del deposito, della compagnia o dell'industria; ignorato per 3, 6 e 7). 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; dalla F6: 7 quadro del mercato globale, 8 quadro della scalata, 9 quadro delle finanze, 10 quadro del rinnovo della flotta, 11 spiegazione «perché» di un valore), `target: i32` (id del treno, del deposito, della compagnia o dell'industria; per 11 il primo argomento del soggetto; ignorato per 3, 6, 7, 8, 9 e 10); blocco 1 (F6, solo con `subject` ≠ 0): `subject: u8` (soggetto della spiegazione, ADR 0024: 1 prezzo globale, 2 prezzo locale, 3 tariffa merci, 4 tariffa passeggeri, 5 efficienza dell'industria, 6 punteggio di crescita, 7 crescita della città, 8 condizione del treno, 9 rating, 10 avanzamento del livello, 11 valore del veicolo, 12 cassa), `arg: i32` (secondo argomento: industria per 2, bene per 3, 0 lavoratori o 1 personale per 4; −1 se non serve). Aggiunto in F4 |
|
||||
|
||||
### Comandi (`Command.type`, payload in ordine)
|
||||
|
||||
@@ -99,7 +106,7 @@ costMultiplier: f64 }`
|
||||
| 14 | SendToDepot | `train: i32`, `depot: i32` |
|
||||
| 15 | SetReserve | `train: i32`, `reserve: bool` |
|
||||
| 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` (id di `maintenance.json`; dalla F6 anche «renewal», il rinnovo dei veicoli superati: in officina si vendono e si sostituiscono con il successore consigliato, ADR 0020) |
|
||||
| 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` |
|
||||
| 20 | RepayLoan | `loan: i32`, `amount: Money` |
|
||||
@@ -153,13 +160,17 @@ loro fase i comandi 35–38 rispondono `NotImplemented`. Il server imposta l'emi
|
||||
| 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) |
|
||||
| 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) |
|
||||
| 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); blocco 1 (F6): `sheet: IndustrySheetInfo`, la scheda dell'immagine 07 calcolata dal Core (`IndustryOutlook`) per la compagnia della sessione (ADR 0021) |
|
||||
| 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) |
|
||||
| 129 | MarketReport | `day: i64, index: f32 (100 = prezzi base), indexChange: f32, goods: [GoodMarketInfo], hubs: [HubMarketInfo], eventGood: i32 (−1 nessuno), eventShock: f32 (con segno, frazione del prezzo base), eventMonths: f32, tradingUnlocked: bool, tradingTier: u8, tradingProgress: f32, netWorth, netWorthRequired: Money, townsConnected, townsRequired, townPopulation: i32, rating, ratingRequired: string, ratingMet: bool`; blocco 1: `warehouses: [WarehouseInfo]` (magazzini della compagnia, solo se ne ha; ADR 0016); blocco 2: `goodEvents: [WorldEventInfo]` (eventi del mondo sulla domanda di un bene, mostrati come «evento in corso»; ADR 0017). I due blocchi sono indipendenti: `flags` bit 0 e bit 1, in quest'ordine (su richiesta, F6; ADR 0015) |
|
||||
| 130 | CommandResult | `seq: u32`, `type: u16`, `error: u16`, `message: string`, `created: [i32]`, `tick: i64` |
|
||||
| 131 | Notification | `EventInfo` |
|
||||
| 132 | Newspaper | `day: i64`, `title: string`, `articles: [(headline: string, body: string)]` |
|
||||
| 133 | SaveList | `saves: [SaveInfo]` |
|
||||
| 134 | ClimbReport | `day: i64, company: i32, foundedDay: i64, initialCapital: Money, tier: u8, nextTier: u8 (0 all'ultimo livello), tiers: [TierInfo]`; requisiti del prossimo livello: `netWorth, netWorthRequired: Money, netWorthFraction: f32, netWorthMet: bool, towns, townsRequired, townPopulation: i32, townsFraction: f32, townsMet: bool, rating, ratingRequired: string, ratingFraction: f32, ratingMet: bool, progress: f32` (media delle tre frazioni); stato patrimoniale: `assets: [AmountInfo]` (kind 0 binari e opere, 1 stazioni e depositi, 2 veicoli, 3 industrie possedute, 4 merce propria), `portfolio, cash (positiva), totalAssets, loans: Money, loansRate: f32 (medio), overdraft (scoperto), totalLiabilities, balanceNetWorth: Money` (= totalAssets − totalLiabilities = patrimonio netto del motore); conto economico: `incomeYear: i32, incomePartial: bool, income: [AmountInfo]` (kind 0 tariffe e noli, 1 altri ricavi, 2 costi operativi, 3 manutenzione, 4 interessi; con segno), `profit: Money`; prestiti: `loanList: [LoanInfo], maxLoan, loanAvailable: Money, newLoanRate: f32, loansAllowed: bool`; `history: [NetWorthPointInfo]` (fondazione, fine di ogni anno, oggi) (su richiesta, F6; ADR 0018) |
|
||||
| 135 | FinanceReport | `day: i64, company: i32, cash, netWorth, loans, overdraft: Money`; conto economico: `lines: [FinanceLineInfo]` (voci in ordine di presentazione), `columns: [IncomeColumnInfo]` (mese in corso, mesi chiusi dal più recente, anno in corso, anni chiusi dal più recente); rating: `rating: string, ratingInitial: bool, ratingMonths, revenueMonths: u8, marginNeutral: bool (margine 0 finché la finestra non è piena e ha meno di minRevenueMonths mesi con ricavi), minRevenueMonths: u8, margin, leverage: f32, leverageUnbounded: bool, marginWeight, leverageWeight, marginComponent, leverageComponent, score: f32, thresholds: [RatingThresholdInfo], nextRating: string ("" ad AAA), nextThreshold: f32, nextAlreadyMet: bool (il punteggio basta già: rating scoreRating al prossimo calcolo mensile, obiettivi a zero), scoreRating: string, marginNeeded: f32, marginReachable: bool, leverageMax: f32 (sempre finita), leverageReachable: bool, debtToRepay: Money, repayAffordable: bool (il rimborso non supera la cassa né il residuo dei prestiti; lo scoperto non si rimborsa)`; prestiti: `loanList: [FinanceLoanInfo], maxLoan, loanAvailable: Money, newLoanRate, baseRate, spread: f32, loanTermMonths: i32, loanStep: Money, loansAllowed: bool`; bancarotta: `negativeCashDays, bankruptcyDays: i32, bankrupt, receivership: bool` (su richiesta, F6; ADR 0019) |
|
||||
| 136 | FleetReport | `day: i64, company, year: i32, era, nextEra: string (id di eras.json; nextEra "" all'ultima), nextEraYear: i32 (0 all'ultima), renewalIntervention: string (id per `ScheduleService`), bookValueTotal: Money (coincide con la voce «veicoli» dello stato patrimoniale), vehicles: [FleetVehicleInfo] (veicoli non venduti della compagnia, per id), models: [VehicleModelInfo] (solo i modelli in produzione nell'anno, nell'ordine di vehicles.json), trains: [RenewalTrainInfo] (treni con veicoli da rinnovare)` (su richiesta, F6; ADR 0020) |
|
||||
| 137 | ExplanationReport | `day: i64, subject: u8, target, arg: i32` (come nella richiesta), `available: bool` (falso per un bersaglio inesistente, chiuso o di un'altra compagnia), `title, name: string, value: f64, unit: u8` (ExplainUnit: 0 numero, 1 importo in centesimi, 2 prezzo in centesimi, 3 percentuale, 4 fattore, 5 km, 6 giorni, 7 unità, 8 condizione 0–100, 9 anni, 10 testo), `valueText, formula: string, terms: [ExplanationTermInfo], notes: [string]`; titolo, formula, etichette e note sono testi italiani fissi (chiavi di traduzione), il valore è lo stesso numero del motore (su richiesta, F6; ADR 0024) |
|
||||
|
||||
Record (ognuno chiude con `flags`):
|
||||
|
||||
@@ -180,7 +191,7 @@ Record (ognuno chiude con `flags`):
|
||||
3 guasto lieve, 4 fermo in linea, 5 rimorchiato), `reserve: bool`, `policy: u8` (255 = ereditata), `nextIntervention: string`,
|
||||
`nextDueDays: i32`, `maintenanceDepot: i32`
|
||||
- `EdgeInfo { id, owner, a, b, trackClass: u8, doubleTrack, electrified, state: u8, condition: f32, structureCondition: f32, progress: f32, samples: [(s, x, y, h, ground: f64, kind: u8, speedLimitKmh: f64)], signals: [f64] }`
|
||||
- `EventInfo { day: i64, kind: u8, severity: u8, text, entity: u8, entityIndex: i32, company: i32 }`; `kind` 10 = evento del mondo (inizio e fine, F6)
|
||||
- `EventInfo { day: i64, kind: u8, severity: u8, text, entity: u8, entityIndex: i32, company: i32 }`; `kind` 10 = evento del mondo (inizio e fine, F6), 11 = novità tecnologiche dell'anno (era che inizia, modelli introdotti, superati e fuori produzione; F6, ADR 0020); `day` −1 = avviso del server alla sola sessione che ha chiesto `Load` o `NewGame` e se l'è visto rifiutare (gli eventi del mondo hanno sempre il giorno della partita, ≥ 0)
|
||||
- `WorldEventInfo { id: i32, type: string (id di events.json), entity: u8 (1 città, 2 industria, 7 deposito), entityIndex: i32, good: i32 (−1 se nessuno), startDay: i64 (dopo `day` per un evento estratto oggi, che inizia domani), endDay: i64 (primo giorno senza l'evento: il server lo toglie quel mattino), severity: u8, effects: [f32] }`: `effects` sono i moltiplicatori nell'ordine degli effetti del tipo nel catalogo (ADR 0017)
|
||||
- `EmploymentRow { industry, jobsWorkers, jobsStaff, workersPresent: f32, staffPresent: f32, reason, sources: [EmploymentSource { town, homeStation, line, category: u8, headcount, coverage: f32 }] }`;
|
||||
blocco 1: `kind: u8` (0 industria, 1 deposito: `industry` è allora l'id del deposito), `workersReason: u8`, `staffReason: u8`
|
||||
@@ -196,8 +207,19 @@ Record (ognuno chiude con `flags`):
|
||||
- `IndustryStopInfo { day: i64, days, kind: u8 }`, `RecordInfo { title, value: string, year }`
|
||||
- `SaveInfo { saveId, name, gameDate, sizeBytes: i64, savedUnixMs: i64, autosave }`
|
||||
- `GoodMarketInfo { good, available, price: f64 (centesimi), change: f32 (30 giorni), supplyMonth, demandMonth, worldSupplyMonth, worldDemandMonth, stockUnits: f64, stockMonths: f32 (−1 senza domanda), history: [PricePointInfo { day: i64, price: f64 }] (un campione per mese, l'ultimo è oggi), forecast: [ForecastInfo { months: u8, price, low, high: f64 }], sellPlaces: [SellPlaceInfo { kind: u8 (0 industria, 1 hub), target, price: f64, line: i32 (−1 non collegato) }] }`
|
||||
- `TierInfo { level: u8, nameIt, nameEn: string, netWorthRequired: Money, townsRequired, townPopulation: i32, ratingRequired: string, reached: bool, reachedDay: i64 (fondazione per il livello 1; −1 se non raggiunto o sconosciuto), unlocks: [UnlockInfo] }`; `UnlockInfo { kind: u8 (0 fido, 1 squadre di cantiere, 2 compravendita in proprio, 3 acquisto di industrie, 4 quotazione, 5 scalate ostili, 6 concessioni), value: i64 (fido in centesimi o numero di squadre; 0 per gli altri) }`: gli sblocchi che il livello aggiunge al precedente
|
||||
- `AmountInfo { kind: u8, value: Money }`, `LoanInfo { loan, remaining: Money, annualRate: f32, monthsLeft: i32 }`, `NetWorthPointInfo { day: i64, value: Money }`
|
||||
- `LedgerEntry` (voce del registro, u8): 0 FreightRevenue (noli merci), 1 PassengerRevenue (biglietti), 2 Construction (costruzioni), 3 VehiclePurchase (acquisto di treni), 4 VehicleSale (vendita di treni), 5 RunningCosts (esercizio dei treni), 6 TrackMaintenance (manutenzione dei binari), 7 FleetMaintenance (manutenzione dei treni), 8 Wages (stipendi), 9 Interest (interessi), 10 LoanTaken (prestiti ricevuti), 11 LoanRepaid (prestiti rimborsati), 12 Trading (commercio in proprio), 13 IndustryPurchase (acquisto di industrie), 14 Dividends (dividendi pagati), 15 Shares (azioni), 16 Contracts (contratti), 17 Penalties (penali), 18 Other (altro), 19 Industries (industrie possedute), 20 Subsidiaries (controllate), 21 StationUpkeep (stazioni e depositi), 22 Storage (magazzini), 23 Duties (dazi), 24 DividendsReceived (dividendi incassati). Sezione: ricavi 0, 1, 12, 16, 19, 20, 24; costi 5–9, 17, 21–23; investimenti e finanziamenti gli altri (ADR 0019)
|
||||
- `FinanceLineInfo { kind: u8 (LedgerEntry), section: u8 (0 ricavi, 1 costi, 2 investimenti e finanziamenti) }`, `IncomeColumnInfo { kind: u8 (0 mese in corso, 1 mese chiuso, 2 anno in corso, 3 anno chiuso), year: i32, month: u8 (1–12, 0 per gli anni), values: [AmountInfo] (solo le voci diverse da zero, kind = LedgerEntry, con segno), profit: Money (utile operativo del motore), cashFlow: Money }`, `RatingThresholdInfo { rating: string, minScore, loanRate: f32 }`, `FinanceLoanInfo { loan: i32, principal, remaining: Money, annualRate: f32 (fisso), monthsLeft: i32, payment, nextInterest: Money, maturityDay: i64 }`
|
||||
- `HubMarketInfo { hub, kind: u8 (0 porto, 1 valico), monthlyCapacity, duty: f32, usedThisMonth, line: i32 (−1 non collegato) }`
|
||||
- `FleetVehicleInfo { vehicle: i32, type: string, train, depot: i32 (−1 se nessuno), ageYears: f32, lifeYears: i32, condition: f32 (media dei componenti, 0–1), inProduction, superseded: bool, supersededYear: i32 (0 senza successore), successor: string (consigliato, "" se non superato o senza successore in produzione), bookValue, resale: Money, maintenanceFactor: f32 }`, `VehicleModelInfo { type: string, superseded: bool, supersededYear: i32, successor: string, lastYear: i32 (ultimo anno di produzione, 0 se non previsto) }`, `RenewalTrainInfo { train, vehicles: i32, netCost: Money (successori − rivendite + lavoro, può essere negativa), affordable: bool (la cassa basta al netto degli altri rinnovi prenotati), booked: bool (rinnovo già prenotato, non ancora avviato) }`
|
||||
- `WarehouseInfo { station, capacity, incoming: i32 (merce propria in viaggio verso la stazione), goods: [WarehouseGoodInfo] }` (stazioni vive della compagnia)
|
||||
- `IndustrySheetInfo { level, maxLevel: u8, efficiency: f32, limit: u8 (fattore più basso sotto 1: 0 nessuno, 1 materie prime, 2 lavoratori, 3 personale, 4 redditività, 5 impianti, 6 giacimento, 7 evento, 8 ferma, 9 inattiva), covInput, covWorkers, covStaff: f32 (coperture medie mobili), coverageWindowDays: i32 (finestra delle coperture), profitFactor, depletion, eventCapacity: f32, reserveFraction: f32 (−1 senza giacimento), storageDays: i32, inputs: [IndustryFlowInfo], outputs: [IndustryFlowInfo], workers: WorkforceInfo, staff: WorkforceInfo, salePrice: f64 (prezzo di vendita del prodotto in centesimi: il prezzo globale del giorno, a cui le industrie vendono al mercato, ADR 0004; −1 senza prodotti o con più prodotti), annualProfit: Money (utile annuo stimato dalle medie mobili), lastScore, shipped, coverage, profit, score: f32 (punteggio di crescita del trimestre in corso e componenti), upgradeThreshold, downgradeThreshold: f32, upgradeQuarters, quartersAbove: u8, quarterDay, quarterDays: i32, served: bool (servita da un vettore: solo allora cambia livello), servingStations: [i32], servingLine: i32 (−1 nessuna), forSale, buyUnlocked: bool, buyTier: u8, buyProgress: f32 }`
|
||||
- `IndustryFlowInfo { good: i32, fullMonth: f32 (a piena capacità, unità al mese), currentMonth: f32 (all'efficienza di oggi), stock, storage: i32, days: f32 (ingressi: giorni di scorta; uscite: giorni al magazzino pieno; −1 senza consumo o produzione), limiting: bool (l'ingresso che limita), partners: [ChainPartnerInfo] }`
|
||||
- `ChainPartnerInfo { kind: u8 (0 industria, 1 hub, 2 città), target: i32, monthlyUnits: f32 (produzione o fabbisogno mensile del partner), price: f64 (centesimi: prezzo globale, locale o dell'hub), line: i32 (linea della compagnia con treni che serve entrambi; −1 non collegato), distanceKm: f32 }`: fornitori per gli ingressi, clienti per le uscite, prima i collegati poi i più vicini, al massimo `industry.outlook.partnersPerGood`
|
||||
- `WorkforceInfo { jobs: i32, present: f32, onSite: f32 (persone in sede: posti coperti da chi vive negli alloggi dell'industria), coverage: f32, missing: i32, reason: u8 (come `EmploymentRow`), reasonLine: i32, averageMinutes: f32 (−1 senza pendolari in treno visibili), sourceCount: i32, sources: [WorkforceSourceInfo] }` (al massimo `industry.outlook.workforceSources` provenienze). Come nel Registro degli impieghi, provenienze, `sourceCount` e `averageMinutes` contano solo i contratti a piedi, quelli trasportati dalla compagnia della sessione e, se l'industria è sua, quelli di tutti i vettori
|
||||
- `WorkforceSourceInfo { town, headcount: i32, coverage: f32, line: i32, carrier: i32, minutes: f32, walking: bool }`
|
||||
- `ExplanationTermInfo { symbol, label: string, value: f64, unit: u8 (ExplainUnit), text: string (valore testuale con unit 10: rating, nome, componente) }`: un termine della formula con il valore di oggi
|
||||
- `WarehouseGoodInfo { good, units: i32 (in magazzino), buyPrice: f64 (centesimi, prossima unità; −1 nessun venditore), buyUnits: i32, sellPrice: f64 (−1 nessun compratore), sellUnits: i32 }` (beni in magazzino o scambiabili nel bacino)
|
||||
|
||||
## 6. Flusso e interest management
|
||||
@@ -219,7 +241,11 @@ Record (ognuno chiude con `flags`):
|
||||
`CompanyCard` (qualunque compagnia), `IndustryCard` (qualunque industria aperta) e `Chronicle`; la
|
||||
Cronaca arriva da sola, una volta per sessione, quando la partita del giocatore finisce. Dalla F6
|
||||
`MarketReport` (quadro del mercato globale per la compagnia della sessione), che il pannello chiede
|
||||
all'apertura e a ogni nuovo giorno; il server non lo manda da solo.
|
||||
all'apertura e a ogni nuovo giorno; il server non lo manda da solo. Così anche `ClimbReport` (quadro della scalata), che il pannello chiede all'apertura, a ogni nuovo giorno e dopo un prestito, e la barra superiore una volta al mese, e `FinanceReport` (quadro delle finanze), che il pannello «Finanze» chiede all'apertura, a ogni nuovo giorno e dopo un prestito o un rimborso, e `FleetReport` (quadro del rinnovo della flotta), che i pannelli Treni e Officine chiedono all'apertura, a ogni nuovo giorno e dopo i loro comandi.
|
||||
Infine `ExplanationReport` (tooltip «perché», ADR 0024): il client lo chiede con `RequestDetail` kind 11
|
||||
quando il puntatore resta su un valore: a ogni apertura del tooltip e poi, finché il puntatore resta, al
|
||||
più una richiesta al secondo per valore; il server risponde sempre, anche con `available` falso
|
||||
(bersaglio inesistente o, per tariffe, treni, veicoli, rating, livello e cassa, di un'altra compagnia).
|
||||
- Backpressure: i moti si scartano oltre 256 KB in coda; oltre 64 MB di messaggi affidabili la
|
||||
sessione si chiude (il client può riprenderla).
|
||||
- Obiettivo di banda in regime: < 100 KB/s per client.
|
||||
+129
-21
@@ -65,7 +65,7 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
|
||||
- Protocollo: riepilogo di manutenzione nei record (blocco 1), `RequestDetail` (10), `MaintenanceCard` (124), `WorkshopRegister` (125), `EmploymentReport` con depositi, motivi e convenzioni, `MaintenanceAlert` dagli avvisi.
|
||||
- Client: pannelli «Officine» (politica della flotta, avvisi, flotta per condizione, cartella di manutenzione con componenti e storico, Registro officina, scorta di ricambi, mappa di calore della condizione) e «Impieghi» (Registro degli impieghi con convenzioni da accettare o rifiutare); schede di treno, industria e città con i dati nuovi; schermate in `docs/screenshots/f4-*.jpg`.
|
||||
- Test di 14.5 su manutenzione (rischio monotono, usura monotona nei fattori, condizione che non sale senza interventi, tagliando/revisione/ispezione con la condizione attesa, pianificatore sopra 30 con politica Standard e ricambi) e pendolarismo; guasto grave con soccorso e riserva, deragliamento, ricambi dal porto, politiche, salvataggio a metà officina, convenzioni, registro, dettagli via WebSocket.
|
||||
- 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). Dopo la taratura del mercato della F6 (ADR 0025): senza la linea 39, sotto 40 dal giorno 731, 10 guasti (18,9 per milione di km); con la linea 73 e 3 guasti.
|
||||
- 102 test.
|
||||
|
||||
### F5 — Industrie, IA, borsa e scalate
|
||||
@@ -82,20 +82,7 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
|
||||
- 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.
|
||||
|
||||
### Infrastruttura — nome, CI e rilasci (novembre 2026)
|
||||
- Nuovo nome «Rail Enterprise» ovunque: namespace e progetti `RailEnterprise.*`, `RailEnterprise.sln`, `railenterprise-tools`, variabili `RE_*`, intestazioni dei file `RESV`/`RECL`, immagine `rail-enterprise-server` (ADR 0014).
|
||||
- Gitea Actions: `ci.yml` (PR e `main`: zero NuGet, build, dati, test, server Windows, client, immagine con healthcheck), `release.yml` (tag `v*`: gioco desktop Windows con server in `server/`, server Windows e Linux, `SHA256SUMS`, immagine `:<versione>` e `:latest`), `nightly.yml` (`:nightly`).
|
||||
- Modelli di PR e issue in `.gitea/`; issue, milestone F0–F7 e progetto «Roadmap» su Gitea con tutto il lavoro svolto; Wiki con guida e schermate.
|
||||
- Immagini di riferimento 06–09 aggiunte in `reference/`.
|
||||
- Primo rilascio **v0.5.0** (7/11/2026): CI verde, release Gitea con server Windows/Linux e immagine `rail-enterprise-server:0.5.0`/`latest`; collaudo `smoke` contro il server reale superato (ponte di 175 m, scarto 0,00 m). Il gioco desktop di v0.5.0 però parte senza codice C#: mancava la soluzione `client/RailEnterprise.Client/RailEnterprise.Client.sln` che Godot richiede per esportare. Aggiunta la soluzione e un controllo che fa fallire il rilascio senza assembly; correzione in **v0.5.1**.
|
||||
- **v0.5.1** (7/11/2026): il gioco desktop scaricato dalla release funziona. Il pilota automatico (`RailEnterprise.exe -- --autopilot <cartella>`) avvia il server incluso, costruisce linea, ponte e treni e salva le 17 schermate; esce con codice 0. Restava un difetto: `strings.csv` non era nel gioco esportato (avviso «Traduzioni non trovate», inglese assente), corretto con l'importatore «keep».
|
||||
- Test instabile sotto carico (issue #24): `BuildLineWithBridgeOverTheNetworkAndWatchTheTrain` (scarto 884 m una volta sul runner). Causa nel test: `TestClient.WaitUntil` ingoiava il tempo scaduto (`ContinueWith(_ => true)`), quindi se il moto dell'ultimo tick non arrivava in 10 s il test confrontava un moto vecchio (il run fallito durò 19 s invece di 7). Il moto non arriva quando la pausa coglie il treno fermo: il server rimanda solo i moti dei treni in marcia. Ora `WaitUntil` fa fallire il test allo scadere e la pausa si ripete finché il treno è in marcia; 24 esecuzioni dei test del server su 24 verdi con 8 processi in parallelo.
|
||||
- `MaintenanceDetailsOnRequest` falliva a volte per un difetto del test: leggeva il registro degli impieghi che il server manda da solo a inizio mese (giorno 0, prima dell'officina) invece della risposta alla richiesta; in locale falliva 2 volte su 4, dopo la correzione 6 su 6 verdi.
|
||||
- **v0.6.0** (7/11/2026): prima versione con i pezzi della F6: Mercato globale (ADR 0015), compravendita in proprio (ADR 0016) ed eventi del mondo (ADR 0017). Il gioco scaricato dalla release passa il pilota automatico (18 schermate, codice 0): il pannello «Mercato globale» si disegna come l'immagine 06, con storico, previsione e banda, offerta, domanda, scorte, «Dove conviene vendere», hub, evento e riquadro della compravendita bloccato al livello 1 (`docs/screenshots/f6-mercato-globale.jpg`). Il riquadro «Eventi in corso» non compare nelle schermate perché nei primi tre mesi della partita del pilota non scatta nessun evento.
|
||||
|
||||
## In corso
|
||||
|
||||
### F6 — Economia completa, eventi, rifinitura
|
||||
### F6 — Economia completa, eventi, rifinitura (completata il 15/11/2026, v0.7.0)
|
||||
- **Mercato globale (issue #29, ADR 0015)**:
|
||||
- storico dei prezzi a 24 mesi (`market.historyDays` 720); i salvataggi con lo storico di 360 giorni si migrano al caricamento con `RollingWindow.Extended`, senza cambiare formato;
|
||||
- `MarketOutlook` (Core, sola lettura): storico mensile (un campione per mese di calendario), variazione a 30 giorni, offerta e domanda mensili con la quota mondiale, scorte in mesi, indice materie prime, previsione a 4 mesi dalla componente mondiale con banda, «Dove conviene vendere» (industrie al prezzo locale dell'ADR 0004 e hub) con la linea che collega, hub, evento in corso, avanzamento verso la compravendita in proprio; parametri in `balance.json` (`market.outlook`);
|
||||
@@ -121,30 +108,147 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
|
||||
- le IA non reagiscono agli eventi: ne subiscono gli effetti attraverso i sistemi, ma stimano i candidati sui valori senza eventi (domanda delle città, posti scoperti, efficienza delle industrie di trasformazione; ADR 0017 §9);
|
||||
- correzioni della revisione: un evento è in vigore nei giorni [inizio, fine) per tutti (sistemi giornalieri, treni a ogni tick, usura del traffico del giorno prima) ed esce dall'elenco il mattino del primo giorno libero con la notizia di fine; nessuna sovrapposizione di zone tra due maltempi o tra due eventi sulla domanda dello stesso bene; `{until}` è l'ultimo giorno; client: conto alla rovescia dalla durata a 1 e «da domani» per gli eventi estratti oggi, avviso anche nelle città della zona e nel Registro officina del deposito, notiziario senza doppioni (dal resoconto solo le notizie di fine, le altre arrivano come `Notification`);
|
||||
- test (`Simulation/EventTests.cs`, 19): catalogo e validazione, effetti di ogni tipo e loro fine, solo la zona per domanda e maltempo, treni rallentati, officina senza personale, durata, niente doppioni né zone sovrapposte, giorni del maltempo per treni, usura e resoconto con il conto alla rovescia, presenti senza eventi per l'IA, frequenza 0, stesso seme stessi eventi, salvataggio con eventi attivi, migrazione dalla versione 4, un anno di eventi frequenti con gli invarianti (lento), eventi nel `DailyDigest` e nel `MarketReport`. 162 test (144 senza i lenti).
|
||||
- Restano della F6: finanza completa, livelli e sblocchi nell'interfaccia, ere e obsolescenza, pannelli 07–08, tooltip «perché», tutorial, audio, bilanciamento con i bot.
|
||||
- **Livelli e sblocchi visibili, «La tua scalata» (issue #38, ADR 0018)**:
|
||||
- `ClimbOutlook` (Core, sola lettura): livelli con gli sblocchi letti dai dati (`Tiers.NewUnlocks`: fido, squadre di cantiere, compravendita, acquisto di industrie, quotazione, scalate, concessioni), quando sono stati raggiunti, requisiti del prossimo livello con valore, soglia, frazione e avanzamento complessivo (media delle tre frazioni, ora anche nel Mercato globale al posto del minimo dell'ADR 0015), stato patrimoniale, conto economico dell'ultimo anno chiuso, prestiti, storico del patrimonio netto dalla Cronaca;
|
||||
- stato patrimoniale per voce con una sola fonte: `FinanceSystem.BookValues` (binari e opere, stazioni e depositi, veicoli, industrie possedute, merce propria) scritto ogni mese in `Company.BookValues`; `AssetBookValue` ne è la somma e la scomposizione (con partecipazioni, cassa, prestiti e scoperto) somma al centesimo al patrimonio netto del motore; le industrie possedute entrano nel patrimonio al valore degli impianti più la loro cassa (prezzo d'acquisto senza avviamento);
|
||||
- notizia di promozione con gli sblocchi ottenuti e giorno annotato (`Company.TierReachedDay`); rifiuti con il livello che serve e il suo nome dai dati (compravendita, acquisto di industrie, quotazione, scalate ostili, concessioni, fido insufficiente con il livello che alza il fido); il validatore pretende squadre per livello uguali in `tiers.json` e `construction.json`;
|
||||
- salvataggio: corpo versione 6 (`BalanceSheetSerializer`) con voci e giorni dei livelli nell'hash; le versioni 1–5 ripartiscono il totale salvato (stesso patrimonio netto) e ricostruiscono i giorni dai fatti salienti o dallo storico;
|
||||
- protocollo: `DetailKind.Climb` (8) e `ClimbReport` (134); server: quadro su richiesta; `ClientWorld.Climb`;
|
||||
- client: pannello «La tua scalata» a tutto schermo come l'immagine 08 (`ClimbPanel`: binario dei livelli con il treno e l'avanzamento, sblocchi sotto ogni livello, storico del patrimonio con i livelli segnati in `SeriesChart`, «Per diventare…» con tre barre, stato patrimoniale, conto economico, «Chiedi un prestito» e «Rimborsa»), pulsante «Scalata» nella barra degli strumenti, livello e avanzamento nella barra superiore (un clic apre il pannello), testi in `strings.csv`, schermata `17_scalata` nel pilota automatico;
|
||||
- test (`Economy/ClimbTests.cs`, 7, più il quadro via WebSocket in `ServerTests`): requisiti coerenti con `Tiers.Meets` e avanzamento, sblocchi dai dati, stato patrimoniale con industria, merce, prestito e scoperto che somma al patrimonio netto, notizia di promozione con gli sblocchi, rifiuti con il livello, salvataggio versione 6 e migrazione dalla 5, proiezione e round-trip di `ClimbReport`. 170 test (152 senza i lenti).
|
||||
- **Finanza completa (issue #39, ADR 0019)**:
|
||||
- analisi delle lacune nell'ADR: prestiti, fido per livello, rate, rating mensile e bancarotta ai giorni di `difficulty.json` c'erano già; mancavano stipendi delle compagnie, finestra di 12 mesi e leva su patrimonio nel rating, misure conservate, conto economico per voce mensile e annuale, voci separate per stazioni, dazi, magazzini e dividendi incassati, avvisi prima della bancarotta, quadro nel protocollo e pannello definitivo;
|
||||
- prestiti a tasso fisso (base della difficoltà + spread del rating all'accensione: niente spirale rating → rata → utile), rimborso anticipato parziale (stessa durata, rata più bassa) e totale senza penale, messaggi con tasso, rata, residuo e cassa disponibile;
|
||||
- rating ogni mese da margine = utile operativo / ricavi sugli ultimi 12 mesi chiusi e leva = (prestiti + scoperto) / patrimonio netto; punteggio, misure e mesi della finestra in `Company`; margine neutro finché la finestra non è piena e ha meno di `finance.ratingMinRevenueMonths` (3) mesi con ricavi, minimo senza ricavi e in perdita; `FinanceOutlook.Explain` dice componenti, soglie con il tasso per rating, gradino sopra, margine che basta, leva massima e debito da rimborsare (se la cassa basta), oppure che il punteggio vale già il gradino sopra;
|
||||
- voci nuove del registro: `StationUpkeep` (21), `Storage` (22), `Duties` (23), `DividendsReceived` (24, ora nell'utile); `LedgerEntries` fissa ordine e sezioni; stipendi giornalieri del personale presente nei depositi alle paghe delle industrie (`Wages`);
|
||||
- conto economico per voce: ultimi 12 mesi chiusi e 10 anni chiusi (`finance.incomeMonths`, `incomeYears`), ogni colonna con l'utile operativo e il flusso di cassa del motore;
|
||||
- avvisi di cassa negativa dopo `finance.negativeCashNoticeDays` (3) giorni di fila e a 30, 14, 7, 3, 1 giorni dal limite (`finance.bankruptcyWarningDaysLeft`, validati), notizia di rientro solo dopo il primo avviso, esito dell'ADR 0012 invariato; la quota dei trasporti dei nuovi concorrenti usa `Company.TransportRevenue` (tariffe, noli, contratti);
|
||||
- salvataggio: corpo versione 7 (`FinanceSerializer`) con mesi, anni e misure del rating nell'hash; le versioni 1–6 partono senza mesi chiusi, con l'ultimo anno dal registro;
|
||||
- protocollo: `DetailKind.Finance` (9) e `FinanceReport` (135); server: quadro su richiesta; `ClientWorld.Finance`;
|
||||
- client: pannello «Finanze» a tutto schermo (`FinancePanel`): conto economico con «Mesi» e «Anni», rating con misure e «per salire…», soglie e tassi, prestiti con rata, interessi, scadenza, «Rimborsa» ed «Estingui», richiesta con fido e tasso, barra dei giorni di cassa negativa solo con lo scoperto; frasi intere con segnaposto in `strings.csv`; schermata `18_finanze` nel pilota automatico (non provata qui: manca l'editor);
|
||||
- IA invariate: usano gli stessi comandi di prestito; accettazione F5 (un'IA al livello 3 in 15 anni) e F4 (35 / 20 guasti senza la linea, 75 / 2 con la linea) invariate;
|
||||
- test (`Economy/FinanceTests.cs`, 19, più il quadro via WebSocket in `ServerTests` e il round-trip di `FinanceReport`): tasso per rating e fisso, fido dal livello e rifiuti, interessi e quota capitale sul registro, rimborso parziale e totale, rating dalle due misure e leva infinita, spiegazione che porta al gradino sopra e rimborso possibile con la cassa, punteggio che basta già (senza infiniti), margine neutro ai primi incassi, finestra di 12 mesi, conto economico che somma all'utile, stipendi dei depositi, dazi, magazzini, dividendi incassati nell'utile, avvisi e bancarotta ai giorni di ogni preset (lento), rientro e oscillazioni senza notizie, quota dei trasporti senza dividendi, salvataggio versione 7 e migrazione dalla 6, determinismo con gli invarianti, proiezione. 194 test (175 senza i lenti).
|
||||
- **Ere e obsolescenza dei veicoli (issue #41, ADR 0020)**:
|
||||
- analisi delle lacune nell'ADR: ere, sblocchi per anno, rifiuto d'acquisto fuori produzione, valore di libro per età e `SellVehicle` c'erano già; mancavano notizie d'era e Cronaca, successori e modelli superati, una sola fonte del valore, costi di manutenzione dei superati, un modo di sostituire i veicoli di un treno, il quadro della flotta, la vendita nel client e l'aggiornamento dei modelli dei progetti delle IA;
|
||||
- `vehicles.json`: campo `successor` (stessa categoria, introdotto dopo, validato) e blocco `obsolescence` (perdita immediata 15 %, ammortamento 2 volte più rapido, manutenzione × 1,5 per i superati); catena vapore 1850 → 1878 → 1902 → diesel 1925, elettrica 1950 → alta velocità 1990, carrozza operai → moderna;
|
||||
- `Obsolescence` (senza stato): in produzione, superato dal 1° gennaio dell'anno del successore, successore consigliato, curva del valore, valore di libro (patrimonio) e rivendita (× condizione) da una sola fonte, fattore della manutenzione in `Fleet.CostOf`;
|
||||
- rinnovo con l'intervento «renewal» di `maintenance.json` (effetto `renew`) prenotato con `ScheduleService`: in officina, all'avvio dei lavori, i veicoli superati si vendono e il successore entra nella stessa posizione; nessun comando nuovo; rifiuto senza veicoli superati o con la spesa netta oltre la cassa meno i rinnovi già prenotati; all'avvio piano e cassa si ricontrollano e, se non bastano, il rinnovo si annulla con un avviso senza scoperto; la ricostruzione dopo un deragliamento non rende nuovo nel patrimonio un modello fuori produzione;
|
||||
- `EraSystem`: il 1° gennaio la notizia (`EventKind.Technology` = 11) dell'era che inizia e delle novità dell'anno lette dai dati (trazioni, veicoli, ponti, gallerie, binari, segnali, elettrificazione, merci, industrie, superati, fuori produzione), annotata nella Cronaca; una volta sola anche attraverso un salvataggio;
|
||||
- salvataggio invariato (corpo versione 7): nessuno stato nuovo, «renewal» in coda agli interventi;
|
||||
- IA: i modelli dei progetti superati passano al successore se non peggiora trazione, potenza e velocità, quelli fuori produzione al migliore dell'anno (che scarta i superati); ogni mese al massimo un treno in linea con veicoli superati da 3 anni o a metà vita va al rinnovo se il treno non peggiora e se resta in cassa libera il doppio della riserva (`ai.json`, `renewal`); la spesa dei rinnovi prenotati resta impegnata per borsa, industrie, progetti e treni;
|
||||
- protocollo: `DetailKind.Fleet` (10) e `FleetReport` (136); server: quadro su richiesta; `ClientWorld.Fleet`;
|
||||
- client: Treni con il catalogo dal server (fuori produzione nascosti, superati segnati con il successore, prestazioni e prezzo del successore), rivendita e «superato» sui veicoli liberi, «Vendi», treni «da rinnovare» e «Rinnova i veicoli superati» con la spesa netta; Officine con la riga di obsolescenza nella cartella, il pulsante del rinnovo e la sezione «Rinnovo della flotta» (nome dell'era, «rinnovo prenotato» al posto di «Rinnova», righe ricostruite solo all'arrivo di un nuovo quadro); testi in `strings.csv` (non provato in Godot: manca l'editor);
|
||||
- accettazione F4 (35 / 20 guasti senza la linea, 75 / 2 con la linea) e F5 invariate;
|
||||
- test (`Economy/ErasTests.cs`, 16, più il round-trip di `FleetReport`): sblocchi per anno, validazione dei successori, notizia d'era una volta anche attraverso un salvataggio, fuori produzione non acquistabile, curva del valore e rivendita, manutenzione dei superati, valore di libro uguale al patrimonio, rinnovo in officina con gli invarianti, determinismo e salvataggio con un rinnovo in corso, quadro e round-trip, cassa ricontrollata all'avvio e impegnata tra prenotazioni, rinnovo annullato con il piano vuoto, ricostruzione di un modello fuori produzione, Cronaca di un anno con soli fuori produzione, scelte delle IA, un'IA che rinnova (lento).
|
||||
- **Audio (issue #46, ADR 0022)**:
|
||||
- solo client, nessun file audio: effetti, anelli e temi sintetizzati in memoria all'avvio su un altro thread da classi senza dipendenze da Godot (`Synth`, `MusicComposer`, `AudioMix` in `scripts/Audio/`), semi fissi, PCM a 16 bit in `AudioStreamWav`;
|
||||
- bus `Master`, `Music`, `Ambience`, `Sfx`, `Ui` creati da codice in modo idempotente, limitatore sul Master; volumi per bus e muto generale nella sezione `audio` di `user://settings.cfg`; pannello «Audio» dalla schermata di connessione e dall'altoparlante nella barra superiore, tasto M per il muto;
|
||||
- `AudioManager` (figlio di `Main`): clic di ogni pulsante, conferma ed errore dagli esiti dei comandi, campanelle per opportunità, avvisi e notizie critiche, «cantiere completato» dal `DailyDigest`; fino a 3 treni in moto vicini al centro dello schermo con rotolamento, motore diesel o ronzio elettrico e sbuffi del vapore modulati dalla velocità (solo con un moto ricevuto da meno di 500 ms ed entro metà della diagonale dello schermo); ambiente (vento e uccelli in campagna, fiume e lago, mare, città) dalla griglia del terreno visibile e dallo zoom; tema per era dall'anno corrente con dissolvenza incrociata di 3 s;
|
||||
- nel pilota automatico e senza schermo niente sintesi e Master muto; testi in `strings.csv`;
|
||||
- nessun test nel harness (il client non è referenziato): le funzioni pure sono state provate a parte (nessun NaN, picchi entro i limiti, anelli senza salti, temi identici a ogni composizione; circa 0,1 s per gli effetti, 0,1–0,4 s per tema). Non ascoltato: qui manca l'editor. 194 test (175 senza i lenti), invariati.
|
||||
- **Scheda dell'industria e schermata di connessione (issue #42, ADR 0021)**:
|
||||
- `IndustryOutlook` (Core, sola lettura): la scheda dell'immagine 07 è calcolata con le stesse formule del motore. Contiene:
|
||||
- i fattori dell'efficienza e il fattore che la limita (`IndustryLimit`);
|
||||
- per ogni ingresso e uscita: quantità al mese a piena capacità e attuale, scorta, capienza, giorni di scorta o al magazzino pieno;
|
||||
- fornitori e clienti (industrie, hub, città) con fabbisogno o produzione mensile, prezzo (globale, locale o dell'hub), distanza e la linea della compagnia che li collega;
|
||||
- forza lavoro dai contratti dei pendolari: posti, presenti, al lavoro, mancanti, motivo, provenienze, viaggio medio;
|
||||
- crescita: punteggio del trimestre in corso con le componenti, soglie, trimestri sopra soglia, servita o no;
|
||||
- prezzo di vendita (prezzo globale del giorno), utile annuo stimato, stazioni e linea che la servono, sblocco dell'acquisto con l'avanzamento.
|
||||
La forza lavoro mostra solo i contratti a piedi, quelli della compagnia della sessione e, se l'industria è sua, quelli di tutti i vettori (come il Registro degli impieghi).
|
||||
`IndustryMath.GrowthScore` è ora l'unica formula del punteggio (anche per `IndustrySystem.Quarter`, hash invariati). Parametri di presentazione in `balance.json → industry.outlook` (`partnersPerGood` 3, `workforceSources` 4).
|
||||
- protocollo:
|
||||
- blocco 1 di `IndustryCard`: `IndustrySheetInfo` con `IndustryFlowInfo`, `ChainPartnerInfo`, `WorkforceInfo`, `WorkforceSourceInfo`;
|
||||
- blocco 1 del `Welcome`: `ServerInfo` con versione, sistema, Docker, tempo di attività, passo del ciclo, client collegati e massimi, locale;
|
||||
- `ClientWorld.Server` e `ClientWorld.Saves` (risposta a `ListSaves` e `Save`).
|
||||
Server: scheda per qualunque industria richiesta, calcolata per la compagnia della sessione.
|
||||
- client:
|
||||
- scheda dell'industria a tutto schermo come l'immagine 07 (`IndustryPanel`):
|
||||
- selettore dell'industria, intestazione con livello su massimo, proprietà, stazione e linea, valore stimato, anello dell'efficienza con il fattore che la limita;
|
||||
- schede «Materie prime in ingresso», «Forza lavoro» con il collo di bottiglia, «Produzione»;
|
||||
- grafo «Catena produttiva» (`ChainGraph`: merci su linea, lavoratori, personale, non collegato; i nodi delle industrie si aprono), «Crea una linea verso questa industria» e «Fai un'offerta di acquisto» o il livello che la sblocca con l'avanzamento;
|
||||
- «Impianti e crescita» con condizione, resa, rischio di fermo, barra del punteggio con le soglie, comandi del proprietario e storico dei fermi;
|
||||
- schermata iniziale e di connessione come l'immagine 09 (`ConnectScreen`, al posto di `MenuScreen`):
|
||||
- mappa decorativa con il titolo e «Dove gira il motore di gioco?»;
|
||||
- «Gioca in locale» e «Connetti a un server» con indirizzo, token e «Ricorda questo server»;
|
||||
- all'apertura avvia la strada scelta l'ultima volta (server locale, o verifica del server ricordato); cambiando strada la sessione dell'altra si chiude; senza sessione «Connetti e riprendi» la apre ed entra in partita; il cambio di lingua passa la sessione alla schermata nuova;
|
||||
- nel piede lingua, «Audio» (il pannello dell'ADR 0022, come nel vecchio menu) ed «Esci»;
|
||||
- stato del server in tre colonne: versione e protocollo, sistema, attivo da (avanza sul client), tick al secondo, latenza, client collegati;
|
||||
- «Partite salvate sul server» in tre colonne (nome, data di gioco, quanto tempo fa), scelta tenuta per id; «Connetti e riprendi» (`Load` e attesa del `Welcome`), «Nuova partita sul server», entrambe con conferma perché sostituiscono il mondo per tutti; il rifiuto si riconosce dal giorno −1 dell'avviso del server;
|
||||
- gli avvisi in alto (esiti dei comandi) compaiono anche sulle schermate a tutto schermo; l'esito dell'offerta di acquisto compare accanto al pulsante;
|
||||
- testi in `strings.csv`; pilota automatico: `12_industria` e `12b_industria_scorte` sono ora la scheda a tutto schermo di un'industria dei privati (in cima con l'avviso dell'acquisto rifiutato, e in fondo), non più la mappa con il pannello laterale; `19_scheda_industria` e `20_connessione` (la schermata su un suo `CanvasLayer` sopra l'interfaccia) in coda (non provate qui: manca l'editor).
|
||||
- test:
|
||||
- `Economy/IndustryOutlookTests.cs`, 6: scheda dell'acciaieria servita (fornitore collegato, clienti al prezzo locale e all'hub, stazione e linea, crescita, sblocco, prezzo di vendita, hash invariato), forza lavoro dai contratti, pendolari di altri vettori nascosti (visibili al vettore e al proprietario), fattore limitante per ogni causa, pesi del punteggio, round-trip nella `IndustryCard` e carta vecchia senza scheda;
|
||||
- `ServerTests`: scheda via WebSocket attesa come risposta nuova, `ServerInfo` nel `Welcome`, elenco dei salvataggi dopo `Save`, `Load` rifiutato con l'avviso del server al giorno −1;
|
||||
- campioni del protocollo con i blocchi nuovi; `Welcome` senza blocco 1 (server F5) con stato del server assente nella copia locale.
|
||||
Con le ere e l'audio: 218 test (198 senza i lenti).
|
||||
- **Tooltip «perché» (issue #44, ADR 0024)**:
|
||||
- Core: modello comune `Explanation` (soggetto e argomenti, valore con unità, formula, termini con i valori di oggi, note) e `Explanations`, pure funzioni del mondo che chiamano le stesse funzioni del motore; estratte senza cambiare l'aritmetica (hash invariati) `Market.NextPrice` e `LocalPriceTerms`, `Tariffs.FreightTerms` e `PassengerTerms`, `TownSystem.GrowthOf`, `Fleet.DailyHazard`, `Fleet.ConditionDue` (stima del pianificatore con il componente che la dà), `GameClock.YearsAt`; `IndustrySystem` registra i termini dell'ultima produzione in `Industry.LastEfficiency`, con la condizione da cui viene mc (transitorio: né salvato né nell'hash);
|
||||
- spiegazioni: prezzo globale (passo del mercato rifatto), prezzo locale, tariffa merci e passeggeri (una unità puntuale sulla tratta più lunga, con la tariffa a due volte il tempo atteso), efficienza e punteggio di crescita dell'industria, crescita della città (stima del prossimo mese), condizione del treno (componente più debole, rischio di guasto, stima del pianificatore), rating, avanzamento del livello, valore del veicolo, cassa;
|
||||
- protocollo: `RequestDetail` kind 11 con il blocco 1 (`subject`, `arg`) e `ExplanationReport` (137); il server risponde sempre, con `available` falso per un bersaglio che non c'è o, per tariffe, treni, veicoli e valori della compagnia, di un'altra compagnia; nessun campo nei delta, formato dei salvataggi invariato;
|
||||
- client: `WhyTooltip` comune nello stile della palette 05, su un suo `CanvasLayer`, si apre dopo 0,45 s, chiede la spiegazione a ogni apertura e poi al più una volta al secondo per valore, intanto mostra quella in cache («aggiornamento in arrivo…») o «in arrivo…»; resta aperto quando il pannello ricostruisce il controllo sotto il puntatore; agganciato a barra superiore (cassa, rating, livello), Mercato globale (prezzo globale, prezzi locali), Scalata (avanzamento, requisiti), Finanze (cassa, rating), scheda dell'industria (efficienza, prezzo di vendita, punteggio, prezzi dei partner), Treni (valore dei veicoli in deposito, condizione dei treni), Officine (condizione); testi in `strings.csv` (non provato in Godot: manca l'editor);
|
||||
- test: `Economy/ExplanationTests.cs`, 10: ogni valore spiegato uguale per uguaglianza esatta a quello del motore (prezzo globale e locale, tariffe, efficienza, crescite, condizione, valore dei veicoli, rating, avanzamento, cassa) e ricomposto dai termini con la formula dichiarata (rapporto D/S dagli scambi con il mondo, stima dal componente che la dà anche quando non è il più debole), linee di altre compagnie non spiegate, spiegazioni in sola lettura con hash invariato e round-trip, spiegazione su richiesta via WebSocket; campioni del protocollo con il blocco 1 della richiesta e `ExplanationReport`.
|
||||
Con il tooltip: 228 test (208 senza i lenti).
|
||||
- **Tutorial guidato della prima partita (issue #45, ADR 0023)**:
|
||||
- copione nel client (`assets/tutorial/tutorial.json`, esportato con il gioco): 19 passi con chiavi di testo per `T()`, elemento da evidenziare con ripiego e condizione osservabile: benvenuto, mappa e zoom, velocità, due stazioni, deposito, strumento Binari, profilo e opere, costruzione, raccordo del deposito, cantieri finiti, locomotiva, carri, composizione, linea, assegnazione, Mercato globale, Finanze, La tua scalata, consigli;
|
||||
- condizioni solo su ciò che il client riceve o fa: entità della compagnia in `ClientWorld`, esiti riusciti dei comandi (`cmd:<CommandType>`), pannello aperto, camera, velocità chiesta da questo client, anteprime del tracciato; nessun comando inviato, nessuna regola; logica pura senza Godot in `scripts/Tutorial/Logic` (copione con validazione, fatti, condizioni `counter`/`panel`/`all`/`any` con `atLeast`, `atMost`, `increase`, `TutorialMachine`, `TutorialProgress`); `increase` conta dal completamento del passo precedente e gli esiti dei comandi si valutano subito;
|
||||
- interfaccia: riquadro non modale in basso a sinistra della mappa (riducibile, non copre barra degli strumenti né pannello destro), contorno ambra animato sull'elemento (ritagliato dai contenitori a scorrimento, che lo portano in vista; del tutto nascosto si usa il ripiego), pulsanti che non prendono il fuoco (Invio e spazio restano alla partita), Avanti per i passi informativi, Salta passo, Chiudi tutorial, «Fatto: …» al completamento; F1 nasconde o riapre; nella schermata di connessione (`ConnectScreen`, sotto «Connetti e riprendi») la casella «Mostra il tutorial» (attiva alla prima partita, vale per la partita che si apre) e il pulsante «Tutorial» (partita locale di prova sempre nuova in `user://tutorial-server`, separata da quella del giocatore, dal primo passo); con una partita locale già salvata la casella parte spenta; tutorial non caricabile: avviso nella partita;
|
||||
- avanzamento per partita in `user://settings.cfg` (sezione `tutorial`, chiave da origine della partita, seme, lato della mappa, anno d'inizio, regione e compagnia del Welcome, mai l'impronta del terreno che cambia giocando): si riprende dopo il caricamento, chiuso o completato resta nascosto salvo la casella spuntata; il pilota automatico non crea il tutorial (schermate invariate); Core, Protocol, Server e salvataggi invariati;
|
||||
- testi italiani e inglesi in `strings.csv`; test (`Client/TutorialTests.cs`, 10, sulla logica collegata al progetto dei test): copione reale valido e completo, traduzioni presenti, pannelli allineati a `Hud.Tool` ed elementi risolti da `GameScreen`, condizioni con la base del passo, avanzamento, salta e chiudi, codifica e ripresa, piano di apertura, chiave stabile con un'impronta del terreno diversa e separata per origine, base del passo al completamento del precedente, validazione dei copioni sbagliati (anche con `null`), prima partita simulata che percorre tutto il copione. 228 test (208 senza i lenti); interfaccia non provata in Godot (qui manca l'editor).
|
||||
- bilanciamento con i bot su `simulate` (issue #47, ADR 0025):
|
||||
- obiettivi O1–O14 scritti nell'ADR prima della taratura, ciascuno con il suo motivo nella guida; verificati anche sui semi 4–9, mai usati nella taratura;
|
||||
- `railenterprise-tools balance` (semi × difficoltà × bot × anni, in parallelo, rapporto deterministico): `rapporto.txt` con gli obiettivi e la sintesi (livelli per anno, patrimonio, rating, fallimenti, interessi, prezzi/base min/medio/max, margini dei trasformatori, coperture, ampliamenti, crescita delle città, veicoli superati, mesi senza reti nuove in attesa dei ricambi, affari di compravendita), `anni.csv` (anni chiusi, dicembre compreso), `mesi.csv`, `prezzi.csv`, `esecuzioni.csv`, `tempi.txt`; `simulate --bot <id>`;
|
||||
- bot giocatore (`PlayerBot`): l'agente delle IA con le personalità di `ai.json → bots` (`bot_competent`, `bot_prudent`) alla guida della compagnia del giocatore; pianifica per primo; non salvato e fuori dall'hash (il formato dei salvataggi non cambia);
|
||||
- le IA (e i bot) usano la compravendita in proprio (supera ADR 0016 §9): vendita delle scorte, arbitraggio nel bacino o verso le stazioni raggiungibili dalle linee merci, con margine minimo, tetti, prezzi limite e un budget mensile per tutti gli affari in `ai.json → trading`;
|
||||
- agente corretto: un trasformatore è una fonte solo con gli input alimentati (prima i bot fallivano su linee che si svuotavano finite le scorte iniziali); la linea dei ricambi di una rete nuova esce dal budget iniziale se l'utile la ripaga prima che finisca la dotazione del deposito (stimata dai tagliandi dei treni) e comunque entro `planning.partsDeferYears` (3 anni); in attesa di quella linea l'agente non apre reti nuove, al più per `partsDeferYears`;
|
||||
- dati: `market.world.volumeShare` 0,5 → 1,0 ed `elasticity` 1,0 → 2,5; `planning.townBonus` 1,8 → 3,0 e `townRoiFactor` 0,5 → 0,35; limiti espliciti negli schemi per tutti i valori di `planning` e `market.world`;
|
||||
- risultato sulla matrice predefinita (24 esecuzioni da 12 anni): obiettivi raggiunti da 4 a 7 su 13 (O3 non valutabile: il bot non costruisce in «Magnate» e «Ferro e sangue»); livello 2 del bot competente in «Imprenditore» al 4° anno (mediana, prima 7°); nessun fallimento dei bot nelle partite giocate in «Apprendista» e «Imprenditore»; medie partita-bene fuori da 0,7–1,6 da 113 a 3 su 180; mesi-bene nella fascia in «Imprenditore» dal 35 % al 93,5 %. Sui semi 4–9 (48 esecuzioni) 7 su 13: O1 non tiene (livello 2 al 4° anno in 3 semi su 6, poi 8°, 10°, mai), O11 sì (56 %). Restano aperti O1 sui semi di verifica, O6–O7 (beni lavorati sopra 1,6 nelle difficoltà basse), O8 (margini dei trasformatori che vendono positivi nel 62 % dei mesi, prima della taratura 75 %: i prezzi più bassi dei beni lavorati li hanno assottigliati), O9–O10 (servono linee pendolari), O11 sui semi 1–3 e in «Ferro e sangue»;
|
||||
- correzioni della revisione (ADR 0025, sezione omonima): trasformatori «che vendono» con vendite nell'ultimo trimestre (non `RevenueEma > 0`), O6 per partita, O7 per difficoltà con la fascia della volatilità, O3–O5 sulle sole partite giocate, O11 sulle IA del 3° anno, interessi di dicembre, obiettivi del mondo su una partita per seme e difficoltà, mediana sui due valori centrali con un numero pari di semi, budget della compravendita mensile, blocco dei ricambi limitato alle reti nuove e nel tempo, rinvio della linea dei ricambi legato alla dotazione (sui semi di verifica la regola di prima faceva fallire il bot nel seme 9);
|
||||
- accettazione F4 legata al mercato attraverso la produzione e i guasti: flotta minima senza linea 39 (sotto 40 dal giorno 731), 10 guasti; con la linea 73 e 3 guasti; con altre elasticità 42 (1,0), 43 (2,0), 41 (3,0): un'unità di margine (ADR 0025);
|
||||
- test: `Balance/BalanceTests.cs`, 5: rapporto deterministico con due mondi in parallelo, determinismo con quattro mondi da 128 km in parallelo, livello 2 e compravendita (lento), bot che gioca con i comandi e non entra nel salvataggio, compravendita dell'agente nello scenario, banco ridotto lento sui semi 4–9 («Imprenditore», 6 anni) su O5, O12–O14 e almeno un livello 2; `DataTests.SchemaBoundsTheBalanceTuning`; `EconomyTests.PriceRisesWhenDemandExceedsSupply` con soglia 1,25 (il mondo assorbe parte dello squilibrio).
|
||||
Con il bilanciamento: 244 test (222 senza i lenti), suite completa ~5 minuti.
|
||||
- L'export Windows con il server in `server/` è nei rilasci dalla v0.5.1; la fase si chiude con il rilascio v0.7.0.
|
||||
|
||||
### Infrastruttura — nome, CI e rilasci (novembre 2026)
|
||||
- Nuovo nome «Rail Enterprise» ovunque: namespace e progetti `RailEnterprise.*`, `RailEnterprise.sln`, `railenterprise-tools`, variabili `RE_*`, intestazioni dei file `RESV`/`RECL`, immagine `rail-enterprise-server` (ADR 0014).
|
||||
- Gitea Actions: `ci.yml` (PR e `main`: zero NuGet, build, dati, test, server Windows, client, immagine con healthcheck), `release.yml` (tag `v*`: gioco desktop Windows con server in `server/`, server Windows e Linux, `SHA256SUMS`, immagine `:<versione>` e `:latest`), `nightly.yml` (`:nightly`).
|
||||
- Modelli di PR e issue in `.gitea/`; issue, milestone F0–F7 e progetto «Roadmap» su Gitea con tutto il lavoro svolto; Wiki con guida e schermate.
|
||||
- Immagini di riferimento 06–09 aggiunte in `reference/`.
|
||||
- Primo rilascio **v0.5.0** (7/11/2026): CI verde, release Gitea con server Windows/Linux e immagine `rail-enterprise-server:0.5.0`/`latest`; collaudo `smoke` contro il server reale superato (ponte di 175 m, scarto 0,00 m). Il gioco desktop di v0.5.0 però parte senza codice C#: mancava la soluzione `client/RailEnterprise.Client/RailEnterprise.Client.sln` che Godot richiede per esportare. Aggiunta la soluzione e un controllo che fa fallire il rilascio senza assembly; correzione in **v0.5.1**.
|
||||
- **v0.5.1** (7/11/2026): il gioco desktop scaricato dalla release funziona. Il pilota automatico (`RailEnterprise.exe -- --autopilot <cartella>`) avvia il server incluso, costruisce linea, ponte e treni e salva le 17 schermate; esce con codice 0. Restava un difetto: `strings.csv` non era nel gioco esportato (avviso «Traduzioni non trovate», inglese assente), corretto con l'importatore «keep».
|
||||
- Test instabile sotto carico (issue #24): `BuildLineWithBridgeOverTheNetworkAndWatchTheTrain` (scarto 884 m una volta sul runner). Causa nel test: `TestClient.WaitUntil` ingoiava il tempo scaduto (`ContinueWith(_ => true)`), quindi se il moto dell'ultimo tick non arrivava in 10 s il test confrontava un moto vecchio (il run fallito durò 19 s invece di 7). Il moto non arriva quando la pausa coglie il treno fermo: il server rimanda solo i moti dei treni in marcia. Ora `WaitUntil` fa fallire il test allo scadere e la pausa si ripete finché il treno è in marcia; 24 esecuzioni dei test del server su 24 verdi con 8 processi in parallelo.
|
||||
- `MaintenanceDetailsOnRequest` falliva a volte per un difetto del test: leggeva il registro degli impieghi che il server manda da solo a inizio mese (giorno 0, prima dell'officina) invece della risposta alla richiesta; in locale falliva 2 volte su 4, dopo la correzione 6 su 6 verdi.
|
||||
- **v0.6.0** (7/11/2026): prima versione con i pezzi della F6: Mercato globale (ADR 0015), compravendita in proprio (ADR 0016) ed eventi del mondo (ADR 0017). Il gioco scaricato dalla release passa il pilota automatico (18 schermate, codice 0): il pannello «Mercato globale» si disegna come l'immagine 06, con storico, previsione e banda, offerta, domanda, scorte, «Dove conviene vendere», hub, evento e riquadro della compravendita bloccato al livello 1 (`docs/screenshots/f6-mercato-globale.jpg`). Il riquadro «Eventi in corso» non compare nelle schermate perché nei primi tre mesi della partita del pilota non scatta nessun evento.
|
||||
- **v0.7.0** (15/11/2026): chiude la F6: scalata e livelli (ADR 0018), finanza completa (0019), ere e obsolescenza (0020), scheda industria e connessione (0021), audio (0022), tutorial (0023), tooltip «perché» (0024), bilanciamento con i bot (0025).
|
||||
|
||||
## In corso
|
||||
|
||||
### F7 — Grafica 3D, interfaccia e progressione
|
||||
- Pianificata il 9/11/2026 (milestone «F7 Grafica 3D, interfaccia e progressione», ombrello #68, issue #54–#67): client 3D in Unity 6, mappa procedurale realistica, conti per linea e personale di bordo, porti e aeroporti cargo, partenza dal 1825 a scelta, obiettivi e sblocchi. Il gioco infinito diventa F8 (#22). Nessun lavoro ancora iniziato.
|
||||
|
||||
## Prossimo passo
|
||||
|
||||
- F6: finanza completa, livelli e sblocchi nell'interfaccia, ere e obsolescenza, pannelli 07–08, tooltip «perché», tutorial, audio, bilanciamento con i bot su `simulate`.
|
||||
- F7 (ombrello #68): si parte da #54, fondamenta del client Unity 6 (ADR 0026, codice condiviso, regole su dipendenze e vista). In parallelo, nel Core: #56 generatore di mappa più realistico, #62 conto per linea, #65 progressione storica dal 1825.
|
||||
- Poi F8, gioco infinito (#22).
|
||||
|
||||
## Limiti noti
|
||||
|
||||
- Godot non è eseguibile nell'ambiente cloud: il client potrà essere compilato con `Godot.NET.Sdk` ma non avviato né esportato qui.
|
||||
- Senza vettori il mondo è in lento declino: le città perdono circa l'1 % di abitanti l'anno e le industrie lavorano a circa il 15–30 % (voluto, ADR 0004).
|
||||
- Il client non è stato provato su Windows né esportato (servono i template di esportazione di Godot); la partita locale usa il server compilato dal repository o `RE_SERVER_PATH`.
|
||||
- Nella vista d'insieme i fiumi larghi una cella mostrano ancora gradini. Le immagini di riferimento 06–09 sono arrivate (novembre 2026): il Mercato globale è allineato alla 06 (F6, non ancora provato in Godot: qui manca l'editor); Industria, Scalata e la schermata di connessione vanno allineati in F6.
|
||||
- Nella vista d'insieme i fiumi larghi una cella mostrano ancora gradini. Le immagini di riferimento 06–09 sono arrivate (novembre 2026): il Mercato globale è allineato alla 06, la scheda dell'industria alla 07, «La tua scalata» alla 08 e la schermata di connessione alla 09 (F6, non ancora provati in Godot: qui manca l'editor). Della 07 mancano le quantità consegnate su ogni collegamento della catena (il motore non le registra: si mostrano produzione o fabbisogno del partner, prezzo e linea) e quantità diverse per ingresso (il consumo segue la ricetta); lo stato del server nella 09 è quello del collegamento (ADR 0021): «Client collegati» resta quello del `Welcome` e «Attivo da» avanza con l'orologio del client; il server non salva prima di `Load` o `NewGame` (la conferma lo dice).
|
||||
- Compravendita in proprio (ADR 0016): la quotazione nel pannello non considera la cassa delle industrie compratrici; una spedizione tiene occupato lo spazio di destinazione per tutto il viaggio; se una linea sparisce durante il viaggio la merce si ferma nel magazzino della stazione dove si trova anche oltre la capacità; un treno che lascia la linea in viaggio lascia la merce propria alla prossima fermata senza percorrere il tratto; la merce in attesa in stazione scade come le altre merci (la scadenza riparte a ogni trasbordo); il riquadro non è ancora stato provato in Godot (qui manca l'editor).
|
||||
- Eventi del mondo (ADR 0017): le medie mobili (coperture a 30 giorni, margini) si riprendono gradualmente dopo un evento; il maltempo prende un arco per intero secondo il suo punto medio; la notizia di fine arriva la sera dell'ultimo giorno; il riquadro mostra al massimo quattro eventi; le IA non reagiscono; client non ancora provato in Godot (qui manca l'editor).
|
||||
- Audio (ADR 0022): suoni mono senza panoramica; timbri semplici di sintesi, da tarare all'ascolto (non ancora provati in Godot: qui manca l'editor); niente fischio all'arrivo in stazione: il client non riceve moti `Loading` (all'arrivo il server non manda moti), serve una modifica del protocollo con una decisione a parte.
|
||||
- Mercato globale (ADR 0015): la previsione segue solo la componente mondiale (ciclo e shock), non domanda e offerta della mappa; «Dove conviene vendere» dà il prezzo alla destinazione, senza il costo del trasporto.
|
||||
- Scalata (ADR 0018): il livello non scende; lo storico del patrimonio ha un punto all'anno (più la fondazione e oggi); il capitale iniziale mostrato è quello della difficoltà; il valore contabile si aggiorna a inizio mese, mentre cassa, partecipazioni e debiti sono del giorno; i salvataggi delle versioni 1–5 ripartiscono il totale degli attivi in proporzione alle voci del giorno di caricamento fino al ricalcolo del mese; il pannello non è ancora stato provato in Godot (qui manca l'editor).
|
||||
- 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.
|
||||
- Bilanciamento (ADR 0025): sui semi di verifica 4–9 il bot competente in «Imprenditore» arriva al livello 2 al 4° anno in 3 semi su 6 e poi all'8°, al 10° o mai (O1 non tiene fuori dai semi della taratura); i beni lavorati (acciaio, legname, materiali edili, manufatti) restano a lungo sopra 1,6 volte il base in «Apprendista» e «Imprenditore» (93 % dei mesi-bene nella fascia contro il 95 %); i trasformatori che vendono hanno margine positivo solo nel 62–75 % dei mesi, più sottile di prima della taratura perché i beni lavorati costano meno; con le sole linee merci le industrie servite lavorano a circa 0,36 (copertura dei lavoratori 0,36) e le città calano dello 0,9 % l'anno; in «Ferro e sangue» (e quasi sempre in «Magnate») il bot non trova una prima rete sopra la soglia del ROI, quindi O3 non è valutabile, e poche IA partono entro il 3° anno; l'accettazione F4 ha un'unità di margine e oscilla con i parametri del mercato (42 / 43 / 39 / 41 con elasticità 1 / 2 / 2,5 / 3); le linee urbane che servono al livello passano anche con un ROI sotto il tasso dei prestiti; nello scenario l'acciaieria cresce ancora ogni due trimestri finché la linea operai non satura (sulla mappa generata 0,3 ampliamenti per industria servita all'anno).
|
||||
- La lunghezza dei marciapiedi non è modellata; i segnali sono solo a blocco fisso (niente segnali di percorso).
|
||||
- Comandi ancora `NotImplemented`: 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.
|
||||
- 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.
|
||||
- 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 la compravendita in proprio (ADR 0016: da aggiungere ai candidati degli agenti con il bilanciamento della F6).
|
||||
- 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; la compravendita in proprio (ADR 0025) guarda solo i venditori del bacino delle proprie stazioni e i compratori raggiungibili dalle linee merci, senza costruire linee apposta; costruiscono di rado linee pendolari.
|
||||
- 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
|
||||
|
||||
@@ -169,3 +273,7 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
|
||||
| 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 |
|
||||
| `balance` matrice predefinita (24 esecuzioni da 12 anni su 128 km, 12 in parallelo) | 543 s; 184 s per esecuzione in media, 411 s la più lunga | F6 |
|
||||
| `balance --seeds 4,5,6,7,8,9` (48 esecuzioni da 12 anni su 128 km, 12 in parallelo) | 597 s; 124 s per esecuzione in media, 330 s la più lunga | F6 |
|
||||
| Suite di test (244, parallela su 12 core, con i lenti) | ~5 minuti | F6 |
|
||||
| `balance --difficulties imprenditore --years 8` (6 esecuzioni) | ~85 s | F6 |
|
||||
@@ -69,7 +69,8 @@ né come migrare i salvataggi con lo storico di un anno.
|
||||
(oggi il 2, «Compagnia regionale»). Se la compagnia ce l'ha è «sbloccata»; altrimenti l'avanzamento
|
||||
è il minimo tra le frazioni dei requisiti numerici (patrimonio netto / richiesto, città collegate /
|
||||
richieste, entrambe limitate a 1); il rating è soddisfatto o no e si mostra a parte, perché non ha
|
||||
una frazione sensata.
|
||||
una frazione sensata. *Sostituito dall'ADR 0018 §2: l'avanzamento è la media delle tre frazioni
|
||||
(patrimonio, città, rating), la stessa del pannello «La tua scalata».*
|
||||
|
||||
## Conseguenze
|
||||
|
||||
|
||||
@@ -95,7 +95,7 @@ invarianti.
|
||||
«Compravendita in proprio» del pannello, quando sbloccato, sceglie stazione, quantità e
|
||||
destinazione per la merce selezionata e manda i comandi con un tetto del 10 % sopra (o un minimo
|
||||
del 10 % sotto) il prezzo mostrato: è una scelta d'interfaccia, il server ricalcola tutto.
|
||||
9. **IA.** Le compagnie IA non commerciano ancora: i loro candidati restano linee e treni (ADR 0013).
|
||||
9. **IA.** Le compagnie IA non commerciano ancora: i loro candidati restano linee e treni (ADR 0013). *Superato dall'ADR 0025: le IA commerciano con una regola mensile deterministica (`ai.json → trading`).*
|
||||
|
||||
## Conseguenze
|
||||
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
# ADR 0018 — Scalata: livelli e sblocchi visibili, stato patrimoniale per voce (F6)
|
||||
|
||||
Stato: accettato (F6, issue #38).
|
||||
|
||||
## Contesto
|
||||
|
||||
Il motore ha i livelli dalla F5 (ADR 0011 §6: `tiers.json`, `Tiers`, promozione mensile dopo il rating,
|
||||
nessuna retrocessione), ma il giocatore li vedeva solo come distintivo nella barra e come rifiuti dei comandi
|
||||
con il nome del livello scritto a mano. La F6 chiede il pannello «La tua scalata» dell'immagine di
|
||||
riferimento 08: binario dei livelli con il treno che avanza, sblocchi di ogni livello, storico del
|
||||
patrimonio netto con i livelli raggiunti, requisiti del prossimo livello, stato patrimoniale, conto
|
||||
economico e prestiti. La guida non dice come scomporre il patrimonio netto, come misurare l'avanzamento,
|
||||
né come valutare le industrie possedute, che finora non entravano nel patrimonio.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Quadro come pura funzione del mondo.** `ClimbOutlook` (Core, `Economy/ClimbOutlook.cs`) legge il
|
||||
mondo e non scrive nulla, come `MarketOutlook` (ADR 0015). Il server lo proietta in `ClimbReport` (134)
|
||||
su richiesta (`RequestDetail` con `DetailKind.Climb` = 8); il client lo mostra com'è. Il pannello lo
|
||||
chiede all'apertura, a ogni nuovo giorno e dopo un comando di prestito; la barra superiore una volta
|
||||
al mese di gioco, per l'avanzamento accanto al livello.
|
||||
2. **Requisiti e avanzamento.** Per il prossimo livello: patrimonio netto, città collegate sopra la
|
||||
popolazione (lo stesso `Tiers.ConnectedTowns`) e rating, con valore attuale, soglia, soddisfatto o no
|
||||
(gli stessi confronti di `Tiers.Meets`) e frazione: patrimonio/soglia e città/città richieste limitate
|
||||
a 1; per il rating 1 − gradini mancanti / `ratingProgressSteps` di `tiers.json` (2,5), limitata tra 0
|
||||
e 1 (1 se soddisfatto: un gradino sotto vale il 60 %, tre o più lo 0 %). **L'avanzamento complessivo è
|
||||
la media delle tre frazioni**: con lo stato dell'immagine 08 (65 % di patrimonio, 1 città su 2, BBB
|
||||
verso A) le frazioni sono 0,65, 0,5 e 0,6 e l'avanzamento il 58 %, come nell'immagine. Misurare il
|
||||
rating dalla D (prima scelta) dava l'86 % per un solo gradino mancante e il 67 % complessivo, e gonfiava
|
||||
l'avanzamento fin dall'inizio. L'avanzamento vale 1 solo con tutti e tre i requisiti soddisfatti
|
||||
(altrimenti al massimo 0,999), e il client mostra queste percentuali per difetto, quindi il 100 %
|
||||
compare solo a requisito o livello raggiunto. Il quadro del Mercato globale usa la stessa funzione:
|
||||
l'ADR 0015 §12 (minimo dei requisiti numerici) è sostituito, così i due pannelli mostrano lo stesso numero.
|
||||
3. **Sblocchi dai dati.** `Tiers.NewUnlocks` elenca ciò che un livello aggiunge al precedente, nell'ordine
|
||||
di `UnlockKind`: fido massimo (fido iniziale × `maxLoanFactor`, se cresce), squadre di cantiere (se
|
||||
crescono), compravendita in proprio, acquisto di industrie, quotazione, scalate ostili, concessioni (le
|
||||
funzioni che passano da `false` a `true`); il livello 1 elenca la dotazione di partenza (fido e squadre).
|
||||
Le concessioni non si annunciano finché il comando non esiste (F7, `Tiers.ConcessionsAvailable`): il
|
||||
gioco non promette uno sblocco che non funziona. Il validatore pretende che gli sblocchi non diminuiscano
|
||||
salendo di livello (`maxLoanFactor` non decrescente, le funzioni non tornano `false`), come presumono
|
||||
notizie, rifiuti e pannello (ADR 0011: gli sblocchi restano acquisiti).
|
||||
Le squadre per livello stanno in due file (`construction.json`, usato dal cantiere, e `tiers.json`): il
|
||||
validatore ora pretende che coincidano. Nessun testo di regola è scritto a mano: il Core ha solo le
|
||||
etichette italiane degli sblocchi, il client le sue chiavi di traduzione.
|
||||
4. **Notizia di promozione.** Il passaggio di livello esisteva già; il testo ora elenca gli sblocchi
|
||||
ottenuti: «X diventa «Compagnia regionale» (livello 2): sblocca fido fino a …, 4 squadre di
|
||||
cantiere, compravendita in proprio» (il fido è quello della compagnia). Il livello non scende (ADR 0011): nessuna notizia di retrocessione.
|
||||
5. **Rifiuti con il livello.** I comandi bloccati dal livello dicono quale livello serve e come si chiama,
|
||||
dai dati (`Tiers.LockedText`): compravendita in proprio, acquisto di industrie, quotazione, scalate
|
||||
ostili e concessioni (che fino alla F7 sono «non ancora disponibili»: prima del livello il rifiuto è per
|
||||
il livello e dice che si sbloccheranno lì, dopo resta «non ancora disponibili»). Il fido insufficiente dice quanto resta su quanto e quale livello alza il
|
||||
fido e a quanto.
|
||||
6. **Stato patrimoniale per voce, una sola fonte.** `FinanceSystem.BookValues` calcola il valore contabile
|
||||
per compagnia e per voce (`AssetCategory`: binari e opere, stazioni e depositi, veicoli, industrie
|
||||
possedute, merce propria); `UpdateBookValues` (ogni mese, come prima) le scrive in `Company.BookValues`
|
||||
e `AssetBookValue` ne è la somma. Il patrimonio netto del motore resta cassa + attivi + partecipazioni −
|
||||
debiti; il pannello lo scompone in attivi per voce, partecipazioni, cassa positiva, prestiti (con il
|
||||
tasso medio pesato sul residuo) e scoperto di cassa (la cassa negativa), e la somma coincide al
|
||||
centesimo con `Company.NetWorth`.
|
||||
7. **Industrie possedute nel patrimonio.** Finora comprare un'industria toglieva il prezzo dalla cassa
|
||||
senza aggiungere nulla agli attivi. Ora entrano al valore contabile `IndustryMath.BookValue`: la parte
|
||||
del prezzo d'acquisto (ADR 0011 §5) senza l'avviamento, cioè impianti (`PlantValue`: costo
|
||||
d'ammodernamento × livello × quota, secondo le condizioni) più la cassa dell'impresa. Gli impianti
|
||||
contano al livello attuale: un'industria inattiva (livello 0), che non si può vendere, vale solo la sua
|
||||
cassa (il prezzo d'acquisto conta invece almeno un livello, come prima). Comprare costa
|
||||
quindi al patrimonio solo l'avviamento (il multiplo degli utili), e il rating e il prezzo dell'azione
|
||||
vedono gli impianti. Il prezzo di vendita (`Valuation`) non cambia.
|
||||
8. **Salvataggio versione 6.** Le voci non si possono ricostruire al caricamento (dipendono dal giorno del
|
||||
calcolo mensile e da attivi venduti o demoliti dopo), quindi il corpo versione 6
|
||||
(`BalanceSheetSerializer`, in coda allo stato dinamico e nell'hash) salva per ogni compagnia le voci e il
|
||||
giorno in cui ogni livello è stato raggiunto (`Company.TierReachedDay`, annotato da `Tiers.Evaluate`;
|
||||
il livello 1 vale dalla fondazione). Le versioni 1–5 salvano solo il totale: la migrazione lo ripartisce
|
||||
in proporzione alle voci calcolate al giorno del caricamento (resto dell'arrotondamento sulla voce più
|
||||
grande, tutto sui binari se non c'è nulla da ripartire), quindi il patrimonio netto non cambia fino al
|
||||
ricalcolo del mese; i giorni dei livelli si ricostruiscono dai fatti salienti («diventa «nome»») o, in
|
||||
mancanza, dalla prima fotografia dello storico con quel livello: quella dell'anno Y si scatta il primo
|
||||
giorno di Y+1, dopo la chiusura del mese che può aver promosso la compagnia, quindi si usa quel giorno
|
||||
(tra la fondazione e oggi).
|
||||
9. **Storico del patrimonio.** Nessuno stato nuovo: si riusa lo storico annuale della Cronaca
|
||||
(`Company.History`, fotografia di fine anno al primo giorno dell'anno dopo), preceduto dal capitale
|
||||
iniziale della difficoltà alla fondazione e seguito dal valore di oggi, che prende il posto della
|
||||
fotografia del primo giorno dell'anno in corso: un punto per anno di calendario, etichettato con il suo
|
||||
anno. I livelli raggiunti si segnano sul punto dell'anno della promozione, anche sull'ultimo (oggi).
|
||||
10. **Conto economico.** L'ultimo anno chiuso (o l'anno in corso fino a oggi, per una compagnia fondata
|
||||
quest'anno), con le voci del registro raggruppate in tariffe e noli, altri ricavi (commercio, contratti,
|
||||
industrie, controllate), costi operativi (esercizio, salari, penali), manutenzione (binari e flotta) e
|
||||
interessi: le righe sommano esattamente a `Company.OperatingProfit` («Utile netto» nel pannello).
|
||||
11. **Prestiti dal pannello.** «Chiedi un prestito» e «Rimborsa» mandano i comandi esistenti (`TakeLoan`,
|
||||
`RepayLoan`); il pannello rimborsa per primo il prestito con il tasso più alto (scelta dell'interfaccia:
|
||||
il server limita comunque l'importo al residuo e alla cassa).
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Le compagnie che possiedono industrie (giocatore dal livello 3, IA dal livello 3) hanno un patrimonio
|
||||
netto più alto di prima: salgono di livello un po' prima e il loro titolo vale di più. Le soglie restano
|
||||
provvisorie fino al bilanciamento della F6.
|
||||
- Il quadro della scalata costa poco (cinque livelli, una scansione di stazioni e treni per le città
|
||||
collegate) e si calcola solo su richiesta.
|
||||
- Il salvataggio cresce di 10 numeri per compagnia; l'hash giornaliero include le voci e i giorni dei
|
||||
livelli.
|
||||
@@ -0,0 +1,144 @@
|
||||
# ADR 0019 — Finanza completa: prestiti per rating, conto economico per voce, bancarotta (F6)
|
||||
|
||||
Stato: accettato (F6, issue #39).
|
||||
|
||||
## Contesto
|
||||
|
||||
La guida (§6.3) chiede cassa, prestiti con tasso = base + spread per rating, manutenzione, stipendi,
|
||||
interessi; rating da utile/ricavi e debito/patrimonio; bancarotta con la cassa sotto zero per i giorni
|
||||
previsti dalla difficoltà; patrimonio netto = attivo a valore di libro − debiti. Prima di scrivere codice
|
||||
si è confrontato il motore con la guida.
|
||||
|
||||
### Analisi delle lacune
|
||||
|
||||
C'era già, e resta com'era:
|
||||
|
||||
- `TakeLoan` / `RepayLoan`: tasso = `baseInterestRate` della difficoltà + `ratingSpreads[rating]`
|
||||
(`balance.json`), fissato all'accensione; fido = fido iniziale × `maxLoanFactor` del livello
|
||||
(`tiers.json`, ADR 0011 §6); rate mensili alla francese su `loanTermMonths` con interessi e quota
|
||||
capitale sul registro (`Interest`, `LoanRepaid`); rimborso parziale e totale limitato al residuo.
|
||||
- Rating ricalcolato ogni mese da un punteggio pesato (`profitMarginWeight`, `leverageWeight`) con le
|
||||
soglie `ratingByScore`; D in bancarotta.
|
||||
- Bancarotta dopo `Difficulty.BankruptcyDays` giorni di fila con la cassa negativa: il numero viene da
|
||||
`difficulty.json` (180 / 90 / 60 / 30) e si può sovrascrivere nelle impostazioni della partita; gli
|
||||
esiti per il giocatore e per le IA sono quelli dell'ADR 0012 (`StockMarketSystem.HandleBankruptcies`,
|
||||
`PlayerInsolvency`).
|
||||
- Patrimonio netto = attivo a valore di libro (ADR 0018) + partecipazioni + cassa − prestiti.
|
||||
- Manutenzione dei binari e della flotta sulle loro voci.
|
||||
|
||||
Mancava o era sbagliato:
|
||||
|
||||
1. il rating usava l'anno in corso (o l'anno chiuso nei primi mesi), non una finestra mobile, e la leva
|
||||
era debiti / attivo invece di debiti / patrimonio; le misure non restavano da nessuna parte, quindi il
|
||||
client non poteva spiegare il rating;
|
||||
2. le compagnie non pagavano stipendi: la voce `Wages` la usavano solo le industrie, e il personale dei
|
||||
depositi (tecnici e operai, ADR 0009) lavorava gratis;
|
||||
3. `RunningCosts` mescolava l'esercizio dei treni con quello di stazioni e depositi; giacenze dei
|
||||
magazzini e dazi degli hub erano dentro `Trading`; i dividendi incassati da un'altra compagnia finivano
|
||||
su `Dividends`, la voce dei dividendi pagati, fuori dall'utile;
|
||||
4. il conto economico esisteva solo come anno in corso e ultimo anno chiuso, senza mesi né storico;
|
||||
5. nessun avviso prima della bancarotta: solo la notizia finale;
|
||||
6. nessun quadro delle finanze nel protocollo; il pannello del client mostrava cassa, patrimonio, rating
|
||||
e un campo per chiedere un prestito;
|
||||
7. i messaggi dei prestiti erano asciutti («Cassa insufficiente») e la percentuale usava il punto.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Tasso fisso.** Il tasso di un prestito resta quello dell'accensione: base della difficoltà + spread
|
||||
del rating di quel giorno. Un tasso variabile renderebbe la rata imprevedibile e farebbe di ogni
|
||||
declassamento una spirale (rating giù → rate su → utile giù → rating giù) proprio quando la compagnia è
|
||||
in difficoltà; con il tasso fisso il rating decide il prezzo del debito *nuovo*, che è l'incentivo
|
||||
che la guida chiede, e la rata mostrata al momento della richiesta resta quella. Rimborsare in anticipo
|
||||
è sempre possibile e senza penale: chi ha migliorato il rating può estinguere e richiedere.
|
||||
Il rimborso parziale lascia la durata invariata e ricalcola la rata.
|
||||
2. **Rating spiegabile.** Ogni mese, dopo il pagamento delle rate e la chiusura del mese:
|
||||
- *margine* = utile operativo / ricavi sugli ultimi 12 mesi chiusi (`finance.incomeMonths`; meno se la
|
||||
compagnia è più giovane), con i ricavi = tariffe e noli più le altre voci di ricavo solo se positive.
|
||||
Finché la finestra non è piena e ha meno di `finance.ratingMinRevenueMonths` (3) mesi con ricavi il
|
||||
margine è neutro (0): senza questa soglia i mesi d'avvio con soli costi davano margine 0 e il primo
|
||||
incasso, piccolo rispetto a quei costi, faceva perdere tre o quattro gradini per un mese, proprio
|
||||
quando un prestito nuovo avrebbe fissato lo spread peggiore per dieci anni. Con la finestra piena (o
|
||||
con abbastanza mesi di ricavi) conta il margine vero; senza ricavi e in perdita il margine è il minimo
|
||||
(−100 %, componente nulla);
|
||||
- *leva* = debiti / patrimonio netto, con debiti = prestiti + scoperto di cassa; 0 senza debiti, infinita
|
||||
con patrimonio non positivo;
|
||||
- punteggio = `profitMarginWeight` × clamp(0,5 + margine, 0, 1) + `leverageWeight` × 1 / (1 + leva)
|
||||
(0 con leva infinita); rating = primo gradino di `ratingByScore` non superiore al punteggio, D sotto
|
||||
l'ultimo o in bancarotta.
|
||||
|
||||
Il motore conserva margine, leva, punteggio e mesi della finestra (`Company.RatingMargin`,
|
||||
`RatingLeverage`, `RatingScore`, `RatingMonths`). `FinanceOutlook.Explain` ne ricava, senza scrivere
|
||||
nulla, le componenti, le soglie con il tasso di un nuovo prestito per ogni rating, il gradino sopra, il
|
||||
margine che basterebbe da solo a raggiungerlo, la leva massima e il debito da rimborsare per arrivarci
|
||||
(a patrimonio invariato) con l'indicazione se quel rimborso è possibile oggi: si rimborsa con la cassa,
|
||||
quindi non oltre la cassa positiva né il residuo dei prestiti, e lo scoperto non si rimborsa. Se il
|
||||
punteggio raggiunge già il gradino sopra (rating iniziale dei dati, o D rimasto da una bancarotta
|
||||
risolta fino al calcolo successivo) la spiegazione lo dice («vale già A, si aggiorna a inizio mese»)
|
||||
senza obiettivi già raggiunti e senza leve infinite sul filo. Il client legge «BBB perché…, per il
|
||||
gradino A serve…» senza calcolare nulla.
|
||||
Prima del primo calcolo mensile (partita nuova o salvataggio migrato) il rating è quello iniziale dei
|
||||
dati e la spiegazione usa le misure del giorno.
|
||||
3. **Voci nuove del registro.** `StationUpkeep` (21, esercizio di binari di stazione e depositi, separato
|
||||
da `RunningCosts` che resta ai treni), `Storage` (22, giacenze dei magazzini), `Duties` (23, dazi degli
|
||||
hub: all'importazione la quota dazio del prezzo pagato, all'esportazione l'incasso al lordo e il dazio a
|
||||
parte, con lo stesso netto di prima), `DividendsReceived` (24, dividendi incassati da un'altra
|
||||
compagnia). `Ledger.Transfer` accetta voci diverse per chi paga e chi incassa. Il valore numerico delle
|
||||
voci esistenti non cambia, quindi i salvataggi restano leggibili.
|
||||
4. **Stipendi del personale dei depositi.** Ogni giorno la compagnia paga a tecnici e operai *presenti* nei
|
||||
suoi depositi le stesse paghe delle industrie (`industry.wagePerStaffPerMonth`, `wagePerWorkerPerMonth`)
|
||||
divise per i giorni del mese, sulla voce `Wages`. Nessun parametro nuovo: il mercato del lavoro è uno
|
||||
solo (ADR 0009). I posti scoperti non costano.
|
||||
5. **Utile operativo.** Ricavi: noli merci, biglietti, commercio in proprio, contratti, industrie
|
||||
possedute, controllate, dividendi incassati. Costi: esercizio dei treni, stazioni e depositi,
|
||||
manutenzione dei treni e dei binari, stipendi, interessi, dazi, magazzini, penali. Fuori dall'utile
|
||||
(investimenti e finanziamenti): costruzioni, acquisto e vendita di treni, acquisto di industrie,
|
||||
prestiti ricevuti e rimborsati, azioni, dividendi pagati, altro. I dividendi incassati ora entrano
|
||||
nell'utile (sono un reddito della compagnia), quelli pagati restano fuori. `LedgerEntries` (Core) fissa
|
||||
ordine e sezioni; `Company.OperatingProfit` ne è la somma, usata da rating, borsa, scalata e pannello.
|
||||
La quota dei trasporti che fa entrare un nuovo concorrente (12.1) usa invece `Company.TransportRevenue`
|
||||
(tariffe, noli e contratti): dividendi incassati, commercio in proprio, industrie e controllate non
|
||||
sono trasporto e non devono far sembrare una compagnia dominante.
|
||||
6. **Conto economico per voce.** A ogni chiusura di mese il registro del mese entra in
|
||||
`Company.IncomeMonths` (ultimi `finance.incomeMonths` = 12), a ogni chiusura d'anno quello dell'anno in
|
||||
`Company.IncomeYears` (ultimi `finance.incomeYears` = 10). Il quadro (`FinanceOutlook`) mostra il mese in
|
||||
corso, i mesi chiusi, l'anno in corso e gli anni chiusi, ogni colonna con l'utile operativo e il flusso
|
||||
di cassa del motore: le righe sommano al centesimo all'utile perché sono le stesse voci del registro.
|
||||
7. **Avvisi di bancarotta.** Dopo `finance.negativeCashNoticeDays` (3) giorni di fila di cassa negativa
|
||||
una notizia (avviso) dice lo scoperto e i giorni al limite della difficoltà; poi una notizia a 30, 14,
|
||||
7, 3 e 1 giorno dal limite (`finance.bankruptcyWarningDaysLeft`, l'ultima critica); se la cassa torna
|
||||
positiva dopo almeno quei giorni una notizia dice che il conto alla rovescia si azzera; al limite la
|
||||
notizia della bancarotta. Una cassa che oscilla intorno a zero (costi giornalieri contro incassi) azzera
|
||||
il conto ogni volta senza riempire le notizie. Il pannello mostra il conto alla rovescia solo con la
|
||||
cassa davvero negativa: dopo un prestito che la riporta sopra zero dice che il conto si azzera domani
|
||||
(il motore conta i giorni una volta al giorno). L'esito resta quello dell'ADR 0012.
|
||||
8. **Salvataggio versione 7.** `FinanceSerializer` in coda allo stato dinamico, nell'hash: mesi e anni
|
||||
chiusi (voci allungate a zero se in futuro se ne aggiungono) e misure del rating. Le versioni 1–6 si
|
||||
caricano con zero mesi chiusi (la finestra si riempie dal mese dopo), l'ultimo anno chiuso ricavato dal
|
||||
registro come primo anno dello storico e `RatingMonths` = 0; il rating salvato resta.
|
||||
9. **Protocollo e client.** `DetailKind.Finance` (9) e `FinanceReport` (135) su richiesta; il pannello
|
||||
«Finanze» diventa a tutto schermo: conto economico per voce con «Mesi» (mese in corso, cinque mesi
|
||||
chiusi, anno in corso) e «Anni» (anno in corso, cinque anni chiusi), rating con misure, componenti,
|
||||
soglie e «per salire…», prestiti con rata, interessi, scadenza, «Rimborsa» ed «Estingui», richiesta con
|
||||
il fido e il tasso, barra rossa dei giorni di cassa negativa sul limite.
|
||||
10. **Messaggi.** Accensione: «Prestito di X al 6,0% fisso (base … + rating BB …) per 10 anni: rata mensile
|
||||
Y»; rimborso: «Rimborsati X: restano R, nuova rata mensile P» o «… prestito estinto»; rifiuto: «Cassa
|
||||
insufficiente: per rimborsare X ci sono Y in cassa». Percentuali con la virgola.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Le compagnie con depositi pagano gli stipendi e hanno utili un po' più bassi; il rating guarda fino a
|
||||
12 mesi e la leva sul patrimonio. Nei primi mesi il margine non conta finché non ci sono tre mesi con
|
||||
ricavi, quindi all'avvio il rating dipende dalla leva; da lì in poi la finestra cresce mese per mese e il
|
||||
rating si muove più dei mesi successivi, quando la finestra è piena. Le IA usano gli
|
||||
stessi prestiti e lo stesso rating (nessun cambiamento nel loro codice); le soglie restano provvisorie
|
||||
fino al bilanciamento della F6.
|
||||
- Il salvataggio cresce di circa 22 mesi × 25 voci per compagnia; l'hash giornaliero li include.
|
||||
- Il quadro delle finanze si calcola solo su richiesta.
|
||||
|
||||
## Limiti
|
||||
|
||||
- Niente ammortamento a conto economico: il valore di libro scende (ADR 0018) ma la perdita di valore non
|
||||
è una voce dell'utile. Niente imposte.
|
||||
- Il tasso non dipende dalla durata e la durata è una sola (`loanTermMonths`).
|
||||
- I mesi chiusi prima della versione 7 non si recuperano: dopo una migrazione il rating usa la finestra
|
||||
dal primo mese chiuso dopo il caricamento.
|
||||
@@ -0,0 +1,169 @@
|
||||
# ADR 0020 — Ere e obsolescenza dei veicoli (F6)
|
||||
|
||||
Stato: accettato (F6, issue #41).
|
||||
|
||||
## Contesto
|
||||
|
||||
La guida (§13) chiede che la tecnologia avanzi per ere: ponti, gallerie, binari, segnali, trazioni e
|
||||
veicoli si sbloccano con l'anno, i modelli vecchi escono di produzione e quelli superati perdono valore
|
||||
e costano di più da mantenere, così che rinnovare la flotta diventi una scelta. Le ere continue e la
|
||||
ricerca (§13.2) sono della F7: il modello di questa fase deve permetterle senza riscritture. Prima di
|
||||
scrivere codice si è confrontato il motore con la guida.
|
||||
|
||||
### Analisi delle lacune
|
||||
|
||||
C'era già, e resta com'era:
|
||||
|
||||
- ere con l'anno d'inizio in `eras.json`; `TrackPlanner` vi legge tipi di ponte, limiti delle gallerie,
|
||||
classi di binario ed elettrificazione; i segnali hanno l'anno; merci e industrie hanno l'era;
|
||||
- `BuyVehicle` rifiuta i modelli non ancora introdotti o fuori produzione (`EraFrom` / `EraTo` di
|
||||
`vehicles.json`, rifiuto `EraLocked`); `Estimators` fa scegliere alle IA solo modelli disponibili;
|
||||
il catalogo del client filtrava i modelli dell'anno dai dati;
|
||||
- valore di libro dei veicoli in `FinanceSystem.BookValues` (ADR 0018): prezzo × max(minimo, 1 − età / vita);
|
||||
- `SellVehicle` (9) per i veicoli liberi in deposito, con un valore di rivendita calcolato a parte (stessa
|
||||
formula × condizione media);
|
||||
- costo di manutenzione che cresce oltre la vita utile (`ageFactor` di `maintenance.json`).
|
||||
|
||||
Mancava:
|
||||
|
||||
1. qualsiasi notizia del passaggio d'era o delle novità dell'anno, e quindi nulla nella Cronaca;
|
||||
2. il legame tra un modello e il suo successore: nessun modello era «superato», il valore scendeva con la
|
||||
sola età e la manutenzione non cambiava con l'obsolescenza;
|
||||
3. una fonte unica del valore: patrimonio e rivendita avevano due formule;
|
||||
4. un modo di sostituire i veicoli di un treno: non c'è un comando che scompone un treno e `SellVehicle`
|
||||
rifiuta i veicoli composti, quindi un treno superato si poteva solo tenere;
|
||||
5. un quadro della flotta per il client (età, superato, successore, valori);
|
||||
6. il pulsante di vendita nel client;
|
||||
7. per le IA: i modelli dei progetti restavano quelli scelti all'apertura e, fuori produzione, ogni
|
||||
`BuyVehicle` del progetto sarebbe stato rifiutato.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Obsolescenza senza stato.** Tutto discende dai dati, dal calendario e dal giorno d'acquisto del
|
||||
veicolo (`Vehicle.BoughtDay`): `Obsolescence` (Core, statica) dice se un modello è in produzione,
|
||||
se è superato, da quale anno, qual è il successore consigliato, il residuo del valore, il valore di
|
||||
libro, la rivendita e il moltiplicatore della manutenzione. Nessun campo nuovo nel mondo.
|
||||
- In produzione: `eraFrom` ≤ anno ≤ `eraTo` (estremo compreso, come già in `BuyVehicle`).
|
||||
- Successore: nuovo campo `successor` di `vehicles.json`. Il validatore pretende un modello esistente,
|
||||
della stessa categoria (tipo, tipo di carro, classe dei passeggeri), introdotto dopo e che non chieda
|
||||
l'elettrificazione se il modello d'origine non la chiede. Catena attuale: vapore 1850 → 1878 → 1902 →
|
||||
diesel 1925; elettrica 1950 → alta velocità 1990; carrozza operai → carrozza moderna (1950).
|
||||
- Superato: dal 1° gennaio dell'anno d'introduzione del successore.
|
||||
- Successore consigliato: il più recente della catena già introdotto e ancora in produzione (la catena
|
||||
si percorre anche oltre un modello uscito di produzione).
|
||||
2. **Curva del valore.** Con età e anni da superato in anni di calendario, vita utile del modello e il
|
||||
minimo `finance.bookValueFloor` (0,1):
|
||||
- modello non superato: r = max(minimo, 1 − età / vita), come prima;
|
||||
- superato: r = max(minimo, (1 − `immediateValueLoss`) × (1 − (età + (`depreciationSpeed` − 1) × anni da
|
||||
superato) / vita)), cioè un gradino del 15 % all'arrivo del successore e poi un ammortamento due
|
||||
volte più rapido. Gli anni da superato partono dall'acquisto se il veicolo è stato comprato dopo.
|
||||
|
||||
Parametri nel nuovo blocco `obsolescence` di `vehicles.json` (con schema e intervalli validati).
|
||||
Esempio: una vaporiera del 1850 (vita 25 anni) comprata nel 1850 vale nel 1877 il minimo del 10 %;
|
||||
comprata nel 1870 vale nel 1878 il 68 % (1 − 8/25) un giorno prima e il 57,8 % il 1° gennaio.
|
||||
3. **Una sola fonte del valore.** Valore di libro = prezzo × r (centesimi, troncato) in
|
||||
`FinanceSystem.BookValues`, quindi nel patrimonio netto; rivendita = prezzo × r × condizione media dei
|
||||
componenti in `SellVehicle` e nel rinnovo; il quadro della flotta legge le stesse funzioni e il suo
|
||||
totale coincide con la voce «veicoli» dello stato patrimoniale calcolata lo stesso giorno.
|
||||
4. **Manutenzione dei superati.** `Fleet.CostOf` pesa il prezzo di ogni veicolo superato per
|
||||
`maintenanceCostFactor` (1,5): un intervento costa di più quanto più la composizione è superata. Il
|
||||
fattore tocca solo il costo in denaro, non la durata né i ricambi né l'usura. L'accettazione F4
|
||||
(Valdoria, 1850, nessun modello superato nei tre anni) resta identica.
|
||||
5. **Rinnovo con un intervento dei dati, non con un comando nuovo.** In `maintenance.json` l'intervento
|
||||
«renewal» (effetto nuovo `renew`, 4 giorni, lavoro pari allo 0,5 % dei prezzi di listino pesati dei veicoli del
|
||||
treno per il fattore della politica, nessun ricambio) si prenota con
|
||||
il comando esistente `ScheduleService` (17). In officina, **all'avvio dei lavori** (quando il treno
|
||||
prende uno stallo e si paga il lavoro), ogni veicolo superato del treno con un successore in produzione
|
||||
si vende al valore di rivendita (voce «vendita di treni») e nella stessa posizione della composizione
|
||||
entra un veicolo nuovo del successore consigliato (voce «acquisto di treni», componenti nuovi); il treno
|
||||
ricalcola prestazioni e grafo della linea e i giorni d'officina sono la messa in servizio; al
|
||||
completamento torna in linea. Il comando si rifiuta senza veicoli da rinnovare («nessun veicolo
|
||||
superato da rinnovare») e con una spesa netta (successori − rivendite + lavoro) maggiore della cassa
|
||||
meno la spesa già impegnata dagli altri rinnovi prenotati e non ancora avviati
|
||||
(`Obsolescence.Committed`). All'avvio piano, spesa e cassa si ricontrollano: tra prenotazione e avvio
|
||||
l'anno può cambiare il piano (un successore esce di produzione, altri veicoli diventano superati) e la
|
||||
cassa può essersi spesa altrove. Se il piano è vuoto o la cassa non basta, il rinnovo si annulla senza
|
||||
pagare nulla, il treno esce dall'officina e una notizia di avviso lo dice; così la cassa non va mai in
|
||||
scoperto per un rinnovo. Il piano pagato è quello del giorno dell'avvio, che può includere veicoli
|
||||
diventati superati dopo la prenotazione: salvare il piano prenotato vorrebbe dire stato nuovo nel
|
||||
salvataggio, e il controllo della cassa all'avvio basta a evitare spese non coperte. I veicoli liberi si vendono con
|
||||
`SellVehicle`, com'era. Così il rinnovo eredita prenotazione, coda, stalli, personale e notizie
|
||||
dell'officina (ADR 0009), il client non ha un comando in più e il protocollo dei comandi non cambia.
|
||||
Il validatore pretende esattamente un intervento con effetto `renew`.
|
||||
6. **Notizie d'era e novità (`EraSystem`).** Nel sistema `Eras`, dopo gli eventi del mondo e prima
|
||||
dell'hash, il 1° gennaio di ogni anno (non il giorno della fondazione) una notizia
|
||||
(`EventKind.Technology` = 11, opportunità, per tutte le compagnie) dice l'era che inizia e le novità
|
||||
lette dai dati: trazioni, veicoli introdotti («locomotiva …» per le locomotive), tipi di ponte con la
|
||||
campata, limiti delle gallerie, classi di binario, segnali, elettrificazione, merci e industrie; poi i
|
||||
modelli che diventano superati con il successore e quelli usciti di produzione. Nessun elenco è scritto
|
||||
a mano. La Cronaca del giocatore annota «inizia l'Era …» o «novità del …». Il sistema non ha stato: la
|
||||
notizia nasce nel tick del cambio d'anno e il mondo si salva tra due tick, quindi esce una volta sola
|
||||
anche attraverso un salvataggio.
|
||||
7. **Niente versione 8 del salvataggio.** Non c'è stato nuovo: superato, valori e notizie si ricavano da
|
||||
dati, calendario e `BoughtDay`, che già si salva. L'intervento «renewal» è in coda all'elenco, quindi
|
||||
gli indici degli interventi salvati (lavori in officina, storico) restano validi. Il corpo resta alla
|
||||
versione 7 e l'hash non cambia per i mondi senza modelli superati.
|
||||
8. **Quadro della flotta.** `FleetOutlook` (Core, sola lettura): era in corso e prossima, veicoli della
|
||||
compagnia (età, vita, condizione, in produzione, superato e da quando, successore consigliato, valore
|
||||
di libro, rivendita, fattore di manutenzione), catalogo dei soli modelli in produzione con il segno dei
|
||||
superati e l'ultimo anno di produzione, treni da rinnovare con la spesa netta, se la cassa basta al
|
||||
netto degli altri rinnovi prenotati e se il rinnovo è già prenotato (il client mostra «rinnovo
|
||||
prenotato» al posto di «Rinnova»). `era` e `nextEra` sono id di `eras.json`; il client mostra il nome. Protocollo: `DetailKind.Fleet` (10) e `FleetReport` (136) su richiesta, `ClientWorld.Fleet`.
|
||||
9. **Client.** Nessun calcolo: il pannello Treni prende il catalogo dal quadro (nasconde i fuori
|
||||
produzione, segna i superati con il successore e, per il modello scelto, prestazioni e prezzo del
|
||||
successore e l'ultimo anno di produzione), mostra «superato · rivendita X» sui veicoli liberi, ha
|
||||
«Vendi» (`SellVehicle`) e «Rinnova i veicoli superati» con la spesa netta, e segna i treni «da
|
||||
rinnovare»; il pannello Officine aggiunge alla cartella la riga di obsolescenza di ogni veicolo, il
|
||||
pulsante del rinnovo, e la sezione «Rinnovo della flotta» (era, prossima era, valore della flotta,
|
||||
veicoli superati con successore, valori e manutenzione, treni da rinnovare con «Rinnova»). Il quadro si
|
||||
chiede all'apertura, a ogni nuovo giorno e dopo i comandi. Testi in `strings.csv`.
|
||||
10. **IA.** Due regole deterministiche:
|
||||
- all'acquisto per un progetto, un modello superato passa al successore consigliato se questo non ha
|
||||
sforzo di trazione, potenza o velocità inferiori (`Obsolescence.NoWorseThan`), così i treni
|
||||
aggiuntivi non nascono superati per poi essere rinnovati dopo pochi anni; un modello uscito di
|
||||
produzione senza un tale successore passa al migliore dell'anno (`Estimators`), che a sua volta
|
||||
scarta i carri e le carrozze superati con un successore in produzione non peggiore (dal 1950 le
|
||||
linee passeggeri nuove hanno la carrozza moderna);
|
||||
- ogni mese, dopo la crescita delle linee, al massimo `renewal.maxTrainsPerMonth` (1) treni in linea,
|
||||
sani e non in officina, in ordine di id, si mandano al rinnovo se almeno un veicolo è superato da
|
||||
`minSupersededYears` (3) anni o ha `minAgeShareOfLife` (50 %) della vita, se il rinnovo non
|
||||
peggiora il treno (sforzo di trazione, potenza, velocità massima e rapporto potenza/massa almeno
|
||||
quelli di oggi: `Obsolescence.KeepsPerformance`) e se dopo la spesa (successori − rivendite +
|
||||
lavoro) resta in cassa libera `cashReserveMultiple` (2) volte la riserva dell'agente. Parametri nel
|
||||
blocco `renewal` di `ai.json`. La cassa libera è la cassa meno la spesa impegnata dai rinnovi
|
||||
prenotati e non ancora avviati: la usano anche borsa, acquisto d'industrie, nuovi progetti e treni,
|
||||
così lo stesso mese non spende due volte la stessa cassa.
|
||||
11. **F7.** Le ere continue e la ricerca aggiungeranno modelli e successori ai dati o anticiperanno
|
||||
`eraFrom` per compagnia: `Obsolescence` ed `EraSystem` leggono solo dati e anno, quindi basterà
|
||||
passare loro l'anno «tecnologico» della compagnia al posto di quello del calendario.
|
||||
|
||||
12. **Ricostruzione dopo un deragliamento.** L'intervento «replace» rimette i componenti a nuovo, ma
|
||||
l'età contabile (`BoughtDay`) riparte solo se il modello è ancora in produzione: un modello che non si
|
||||
compra più non torna nuovo nel patrimonio per il 45 % del prezzo; l'usura riparte comunque da capo
|
||||
(il fattore d'età torna a 1). Un modello superato ma ancora in produzione si comporta come uno nuovo
|
||||
comprato oggi, che `BuyVehicle` consente.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Il patrimonio netto scende di più per chi tiene modelli superati; la scalata e il rating lo vedono.
|
||||
- Rinnovare costa il prezzo dei successori meno la rivendita: un treno vecchio vale poco, quindi il
|
||||
rinnovo è una spesa vera, che il pannello mostra prima della prenotazione.
|
||||
- Ogni 1° gennaio con novità c'è una notizia in più; gli anni senza novità non ne hanno.
|
||||
- Accettazione F4 invariata (35 / 20 guasti senza la linea, 75 / 2 con la linea): nel 1850–1853 nessun
|
||||
modello è superato. Accettazione F5 invariata.
|
||||
|
||||
## Limiti
|
||||
|
||||
- Il rinnovo sostituisce solo i veicoli con un successore in produzione; un modello senza successore
|
||||
(diesel, carri merci) invecchia con la sola età.
|
||||
- La rivendita non dipende dal mercato dell'usato (domanda, numero di veicoli in vendita).
|
||||
- La manutenzione dei superati costa di più ma non si guasta più spesso: il fattore tocca il prezzo, non
|
||||
l'usura.
|
||||
- Le IA rinnovano solo treni in linea e non vendono i veicoli liberi in deposito.
|
||||
- Il successore è unico per modello: niente rami (per esempio vapore → diesel o elettrica).
|
||||
- Il successore non è sempre migliore in tutto, e la scelta è voluta: la Vittoria 2-8-0 (110 kN) passa
|
||||
alla Freccia 4-6-2 (95 kN, ma 1150 kW e 110 km/h); la Freccia passa all'Aquila D1 (950 kW, 100 km/h,
|
||||
ma 180 kN, costo d'esercizio minore e trazione diesel che resta in produzione fino al 1975); la carrozza
|
||||
moderna porta più posti con più massa. Il giocatore vede prestazioni e prezzo del successore prima di
|
||||
rinnovare; le IA non rinnovano e non cambiano modello quando il treno peggiorerebbe.
|
||||
- Il piano del rinnovo è quello del giorno dell'avvio, non quello della prenotazione (vedi il punto 5).
|
||||
@@ -0,0 +1,108 @@
|
||||
# ADR 0021 — Scheda dell'industria e schermata di connessione (F6)
|
||||
|
||||
Stato: accettato (F6, issue #42).
|
||||
|
||||
## Contesto
|
||||
|
||||
Le immagini di riferimento 07 (industria) e 09 (connessione) sono vincolanti. Per entrambe il client
|
||||
aveva soltanto una prima versione:
|
||||
|
||||
- un pannello laterale con l'elenco delle industrie e i comandi del proprietario (F5);
|
||||
- un menu più un modulo «indirizzo e token» costruito quando l'immagine 09 non c'era ancora.
|
||||
|
||||
L'immagine 07 chiede dati che il client non riceveva:
|
||||
|
||||
- la catena produttiva con fornitori e clienti;
|
||||
- le coperture di materie prime, lavoratori e personale sulla finestra di 30 giorni;
|
||||
- produzione e magazzino in giorni;
|
||||
- il fattore che limita l'efficienza;
|
||||
- il punteggio di crescita trimestrale con le soglie;
|
||||
- la stazione e la linea che servono l'industria;
|
||||
- lo stato dello sblocco «acquisto di industrie».
|
||||
|
||||
L'immagine 09 chiede lo stato del server: versione, sistema, tempo di attività, tick, latenza e client
|
||||
collegati. Chiede anche le partite salvate sul server.
|
||||
|
||||
Il client non contiene logica di gioco e il formato dei salvataggi non deve cambiare.
|
||||
|
||||
## Decisione
|
||||
|
||||
### Scheda dell'industria: calcolo nel Core, su richiesta
|
||||
|
||||
1. `Core/Economy/IndustryOutlook.Build(world, industry, company)` è una funzione pura: legge il mondo e
|
||||
non lo cambia, e il test verifica che l'hash di stato resti uguale. Calcola, con le stesse formule
|
||||
del motore:
|
||||
- i fattori dell'efficienza (`Factors`: redditività, impianti, giacimento, evento, fermo) e il
|
||||
fattore che la limita (`IndustryLimit`), cioè il più basso sotto 1 nell'ordine dell'enumerazione;
|
||||
un'industria chiusa o al livello 0 è «inattiva», una ferma è «ferma»;
|
||||
- per ogni ingresso e uscita: quantità al mese a piena capacità e all'efficienza di oggi, scorta,
|
||||
capienza, giorni di scorta (ingressi) o giorni al magazzino pieno (uscite), più i partner:
|
||||
- fornitori: industrie che producono il bene, al prezzo globale, e hub che lo importano, al
|
||||
prezzo di vendita dell'hub;
|
||||
- clienti: industrie che consumano il bene, al prezzo locale (`Market.LocalPrice`), hub
|
||||
d'esportazione al prezzo d'acquisto dell'hub, e città con domanda del bene, al prezzo globale;
|
||||
- la linea che collega: la linea della compagnia, con treni, il cui bacino tocca sia l'industria
|
||||
sia il partner;
|
||||
- l'ordine: prima i collegati, poi per distanza;
|
||||
- la forza lavoro: posti, presenti, persone in sede, copertura, mancanti, motivo e provenienze,
|
||||
dai contratti dei pendolari (`World.Commutes`) raggruppati per città, linea e vettore. Come il
|
||||
Registro degli impieghi, la compagnia vede i contratti a piedi, quelli che trasporta lei e, se
|
||||
l'industria è sua, quelli di tutti i vettori: i dati degli altri vettori non escono;
|
||||
- la crescita: il punteggio del trimestre in corso e le sue componenti. `IndustryMath.GrowthScore`
|
||||
è ora l'unica formula: la usa anche `IndustrySystem.Quarter`, con aritmetica identica (test di
|
||||
determinismo invariati). Calcola anche le soglie, i trimestri sopra soglia e se un vettore serve
|
||||
l'industria (solo allora il livello cambia);
|
||||
- prezzo di vendita del prodotto: il prezzo globale del giorno, a cui le industrie vendono al
|
||||
mercato (ADR 0004). Una stima dai ricavi (`RevenueEma × QuarterDays / QuarterShipped`) mescolerebbe
|
||||
una media mobile con i totali del trimestre in corso e sbaglierebbe a inizio trimestre o quando
|
||||
la produzione cambia;
|
||||
- utile annuo dalle medie mobili, stazioni che servono l'industria e avanzamento verso il livello
|
||||
che sblocca l'acquisto (`ClimbOutlook`).
|
||||
2. I nuovi parametri di presentazione stanno in `balance.json → industry.outlook`:
|
||||
- `partnersPerGood` (3): partner per bene;
|
||||
- `workforceSources` (4): provenienze dei pendolari.
|
||||
Il validatore li vuole entrambi ≥ 1.
|
||||
3. Il server manda la scheda nel blocco 1 di `IndustryCard` (`IndustrySheetInfo`, PROTOCOL.md §5). La
|
||||
manda per ogni industria richiesta, per la compagnia della sessione: la scheda si apre su qualunque
|
||||
industria, non solo sulle proprie. Un client vecchio ignora il blocco; un server vecchio non lo
|
||||
manda, e il client mostra «Scheda in arrivo».
|
||||
4. Il client mostra la scheda a tutto schermo, come «Mercato» e «La tua scalata». Il pannello laterale
|
||||
delle industrie non c'è più: un selettore in alto sceglie l'industria. I comandi del proprietario
|
||||
restano quelli della F5:
|
||||
- budget, ricambi extra, «Fermo programmato», «Ammoderna»;
|
||||
- per le industrie dei privati, «Fai un'offerta di acquisto» al prezzo di stima, attivo solo con lo
|
||||
sblocco.
|
||||
«Crea una linea verso questa industria» apre lo strumento binari centrato sull'industria.
|
||||
|
||||
### Schermata di connessione: stato nel `Welcome`, salvataggi con `ListSaves`
|
||||
|
||||
5. Il `Welcome` ha un blocco 1 `ServerInfo`: versione, sistema, Docker sì/no, tempo di attività, passo
|
||||
del ciclo, sessioni collegate e massime, locale sì/no. La latenza la misura il client con il ping.
|
||||
6. La schermata iniziale e quella di connessione diventano una sola (immagine 09); `MenuScreen` è
|
||||
rimossa. A sinistra c'è una mappa decorativa disegnata in codice con la palette della mappa; a
|
||||
destra le due strade:
|
||||
- «Gioca in locale» avvia il server figlio;
|
||||
- «Connetti a un server» usa indirizzo e token, con «Ricorda questo server».
|
||||
Entrambe aprono una sessione di prova che mostra lo stato e l'elenco «Partite salvate sul server»
|
||||
(`ListSaves` ogni 5 s).
|
||||
«Connetti e riprendi» entra nella partita in corso, oppure manda `Load` del salvataggio scelto e
|
||||
aspetta il nuovo `Welcome`. «Nuova partita sul server» manda `NewGame` con la difficoltà della
|
||||
partita. In entrambi i casi la sessione di prova diventa la partita.
|
||||
7. Il collaudo (`--autopilot`) aggiunge in coda due schermate senza rinumerare le altre:
|
||||
- `19_scheda_industria`: un'industria di trasformazione vicino alla linea;
|
||||
- `20_connessione`: la schermata sopra la partita, con una sessione di prova sul server locale
|
||||
dopo un salvataggio.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Nessuno stato nuovo nel mondo e nessun cambio del formato dei salvataggi. La scheda è calcolata
|
||||
quando la si chiede, a costo proporzionale al numero di industrie, città e linee.
|
||||
- Il motore non registra i flussi reali per collegamento. La catena mostra perciò, per ogni partner:
|
||||
la sua produzione o il suo fabbisogno mensile, il prezzo e la linea che lo collega. Non mostra le
|
||||
tonnellate effettivamente consegnate su quel collegamento, come invece fa l'immagine 07.
|
||||
- Il consumo di materie prime segue la ricetta: tutti gli ingressi hanno la stessa frazione «attuale /
|
||||
piena». La differenza tra ingressi la danno i giorni di scorta e l'ingresso che limita.
|
||||
- La «linea che collega» è solo una linea ferroviaria della compagnia con treni. Il trasporto locale
|
||||
su strada e le linee delle altre compagnie non compaiono nella catena; restano nei numeri.
|
||||
- Lo stato del server è quello del momento del `Welcome`: «client collegati» non si aggiorna finché la
|
||||
sessione resta aperta.
|
||||
@@ -0,0 +1,75 @@
|
||||
# ADR 0022 — Audio del client: bus, volumi, suoni sintetizzati, ambiente e musica per era (F6)
|
||||
|
||||
Stato: accettato (F6, issue #46).
|
||||
|
||||
## Contesto
|
||||
|
||||
La roadmap della F6 (guida §16, punto 14) chiede «audio» senza altri dettagli. Il client non contiene
|
||||
logica di gioco (§14.3) e il repository non ha file audio; scaricarne durante la build o includere file
|
||||
con licenze incerte non è accettabile. Godot non è eseguibile nell'ambiente di sviluppo, quindi i suoni
|
||||
non si possono ascoltare qui: il codice deve essere verificabile almeno nella parte di sintesi.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Tutto sintetizzato nel client, niente file audio.** `Synth` (effetti e anelli) e `MusicComposer`
|
||||
(temi) sono classi C# senza dipendenze da Godot in `client/RailEnterprise.Client/scripts/Audio/`;
|
||||
producono campioni mono a 22 050 Hz convertiti in PCM a 16 bit (`AudioMix.ToPcm16`) e caricati in
|
||||
`AudioStreamWav` in memoria. Semi fissi (xorshift64* `SynthRng`, FNV-1a dell'id dell'era): stessi
|
||||
suoni e stessi temi a ogni avvio. Nessuna licenza da documentare.
|
||||
2. **Bus**: `Master`, `Music`, `Ambience`, `Sfx`, `Ui`, creati da codice all'avvio (`AudioBuses.Ensure`,
|
||||
idempotente: un bus esistente non si duplica) con un `AudioEffectHardLimiter` sul Master; niente
|
||||
`default_bus_layout.tres`, così il progetto resta senza risorse da importare con l'editor.
|
||||
3. **Impostazioni**: volume per bus (0–1, guadagno = valore², cioè circa il volume percepito) e muto
|
||||
generale nella sezione `audio` di `user://settings.cfg`, lo stesso file di lingua e server. Pannello
|
||||
«Audio» sopra a tutto (dal menu e dall'altoparlante nella barra superiore; si chiude con Esc, «Chiudi»
|
||||
o un clic sinistro fuori); il tasto **M** attiva e toglie il muto (solo se nessun campo di testo ha il
|
||||
fuoco: è un input non gestito). I cambi si salvano quando il pannello esce dall'albero e all'uscita
|
||||
di `AudioManager`, anche chiudendo la finestra con il pannello aperto (solo se qualcosa è cambiato).
|
||||
4. **`AudioManager`** è un figlio di `Main` (non un autoload: nessuna modifica a `project.godot`), con
|
||||
`AudioManager.Instance`. Reagisce solo a ciò che il client riceve già:
|
||||
- clic di ogni `BaseButton` (agganciato dal segnale `node_added` dell'albero: i pannelli non cambiano;
|
||||
un pulsante staccato e riattaccato non si ricollega, si controlla `IsConnected`);
|
||||
- `CommandResultMessage`: conferma o errore;
|
||||
- `Notification`: campanella per opportunità, avviso, critica (una sola ogni 0,6 s, le critiche sempre);
|
||||
- `DailyDigest`: «cantiere completato» se c'è un evento `Construction` della compagnia del giocatore
|
||||
(gli eventi informativi arrivano solo dal resoconto, non come `Notification`);
|
||||
- vista: fino a 3 treni in moto tra quelli disegnati (`TrainLayer.Heads`), i più vicini al centro
|
||||
dello schermo ed entro metà della diagonale (oltre non si sentirebbero), hanno un canale con
|
||||
rotolamento (intonazione dalla velocità), motore diesel o ronzio elettrico, e sbuffi per il vapore
|
||||
da 1,2 al secondo al passo a 10 al secondo a 30 m/s (circa 110 km/h), in modo lineare: è una resa
|
||||
sonora, non il passo della ruota, perché sullo schermo il tempo dei treni corre decine di volte più
|
||||
veloce e non dipende dalla velocità di gioco; il volume scende con la distanza in pixel e
|
||||
allontanando lo zoom; in pausa tacciono. Un treno suona solo se il suo ultimo moto ha meno di
|
||||
500 ms (il server li manda ogni 100 ms ai treni in marcia): durante la sosta in stazione il server
|
||||
non manda moti e l'ultimo ricevuto, ancora `Moving` con la velocità di frenata, resterebbe
|
||||
nel mondo del client; lo stesso per un treno uscito dalla zona sottoscritta;
|
||||
- ambiente: ogni 0,25 s una griglia 8×8 sulla vista (allargata di un quarto) conta fiume, lago, mare,
|
||||
città e industrie, bosco, campagna; `AudioMix.Ambience` ne ricava i guadagni di vento, acqua, mare e
|
||||
città con lo zoom (da lontano quasi solo vento) e la probabilità degli uccelli da vicino in campagna;
|
||||
- musica: l'era viene dall'anno corrente (`ClientWorld.Year`) e da `eras.json`; al cambio d'era il tema
|
||||
nuovo entra con una dissolvenza incrociata di 3 s su due riproduttori; nel menu suona il tema della
|
||||
prima era. Le tabelle d'onda dei temi tengono per ogni nota solo le armoniche sotto il 45 % della
|
||||
frequenza di campionamento (una tabella per numero di armoniche), così le note acute non
|
||||
ripiegano oltre Nyquist.
|
||||
5. **Prestazioni**: la sintesi gira su un altro thread (`Task.Run`: circa 0,1 s per gli effetti, 0,1–0,4 s
|
||||
per tema, solo quando serve); nel ciclo per fotogramma niente LINQ né allocazioni (elenchi dei treni
|
||||
preparati, `StringName` dei bus già pronti, un riproduttore polifonico per bus per i suoni brevi).
|
||||
6. **Pilota automatico e server senza schermo**: `AudioManager` non sintetizza né riproduce nulla e il
|
||||
Master resta muto, senza scrivere il file delle impostazioni.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Il client non ha file audio e la build non scarica nulla; il timbro dei suoni è semplice (sintesi
|
||||
additiva, FM, rumore filtrato) e si può cambiare solo nel codice.
|
||||
- I suoni sono mono, senza panoramica destra–sinistra: i treni si distinguono per volume, non per lato.
|
||||
- Le costanti di resa sonora (livelli, zoom di riferimento, numero di canali) stanno in `AudioMix` e in
|
||||
`AudioManager`: sono del client, non della simulazione, e non vanno in `data/*.json`.
|
||||
- **Niente fischio né tromba all'arrivo in stazione.** All'arrivo il server svuota il percorso del
|
||||
treno e `Projection.Motion` non produce moti per un treno senza percorso: il client non riceve mai
|
||||
un moto `Loading`, quindi il passaggio `Moving` → `Loading` non è osservabile. Dedurre l'arrivo nel
|
||||
client (moti che smettono di arrivare) sarebbe logica di gioco. Il fischio tornerà quando il protocollo
|
||||
manderà lo stato del treno fermo (decisione e issue a parte, perché tocca il server);
|
||||
`Synth.SteamWhistle` e `Synth.Horn` restano pronti per allora, ma non si sintetizzano all'avvio.
|
||||
- Nessun test nel harness: le classi pure sono nel progetto Godot, che il harness non referenzia; sono
|
||||
state provate a parte (nessun NaN, picchi entro i limiti, anelli senza salti, temi identici a ogni
|
||||
composizione). Nessun ascolto possibile qui.
|
||||
@@ -0,0 +1,88 @@
|
||||
# ADR 0023 — Tutorial guidato della prima partita (F6)
|
||||
|
||||
Stato: accettato (F6, issue #45).
|
||||
|
||||
## Contesto
|
||||
|
||||
La guida (§16, F6) chiede un tutorial senza dire come farlo. Il client non contiene logica di gioco
|
||||
(§14.3): un tutorial che controllasse le regole (per esempio «la stazione è nel posto giusto») le
|
||||
duplicherebbe. Il formato dei salvataggi, il motore, il protocollo e il server non devono cambiare per una
|
||||
funzione che riguarda solo l'esperienza del giocatore. Il pilota automatico del collaudo deve continuare a
|
||||
produrre le stesse schermate.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Copione come file dati del client.** I passi stanno in
|
||||
`client/RailEnterprise.Client/assets/tutorial/tutorial.json` (esportato con il gioco: filtro
|
||||
`assets/tutorial/*.json` nei preset), letto con il generatore di sorgente di System.Text.Json (campi
|
||||
sconosciuti rifiutati, nessun pacchetto). Ogni passo ha `id`, chiavi `title` e `text` per `T()` (il
|
||||
testo italiano, tradotto in `strings.csv` come il resto dell'interfaccia), l'elemento da evidenziare
|
||||
(`highlight`) con un ripiego facoltativo (`fallback`, di solito il pulsante che apre il pannello) e la
|
||||
condizione di completamento (`done`); senza condizione il passo è informativo e si chiude con Avanti.
|
||||
2. **Condizioni osservabili, nessuna regola.** Una condizione è una sola forma tra: contatore
|
||||
(`counter` con `atLeast`, `atMost` e/o `increase`), pannello aperto (`panel`), `all` e `any`.
|
||||
`increase` confronta con i fatti di quando il passo precedente si è completato da sé (dopo Avanti,
|
||||
Salta, una ripresa o una ripartenza con il primo aggiornamento del passo), e gli esiti dei comandi si
|
||||
valutano appena arrivano: due binari costruiti a pochi istanti l'uno dall'altro contano per due passi. I contatori vengono solo da ciò che
|
||||
il client riceve o fa già: entità della compagnia nella copia locale `ClientWorld` (stazioni, depositi,
|
||||
archi, archi in cantiere, locomotive, carri e carrozze, treni, linee, treni in linea, con il tipo dei
|
||||
veicoli dai dati), esiti riusciti dei comandi (`CommandResultMessage`: `cmd:` + nome di `CommandType`),
|
||||
spostamento della camera in schermate e zoom in logaritmi, velocità chieste da questo client (non i
|
||||
cambi decisi da altri giocatori sullo stesso server), anteprime del tracciato
|
||||
mostrate; il pannello è lo strumento aperto nella barra (`Hud.Tool` in minuscolo). Il tutorial non invia
|
||||
comandi e non decide se un'azione è buona: il server resta autorevole e i rifiuti arrivano come sempre.
|
||||
3. **Logica pura separata.** `scripts/Tutorial/Logic` (copione, validazione, fatti, condizioni,
|
||||
`TutorialMachine`, `TutorialProgress`) non dipende da Godot; il progetto dei test la compila per
|
||||
collegamento e la prova (`tests/RailEnterprise.Tests/Client/TutorialTests.cs`). La parte Godot è
|
||||
`TutorialController` (raccoglie i fatti ogni 0,2 s e a ogni esito di un comando, fa avanzare la
|
||||
macchina, salva) e `TutorialOverlay`. Un copione mancante o non valido si segnala nella partita (a chi
|
||||
ha chiesto il tutorial e a F1), non solo nel registro.
|
||||
4. **Sequenza.** Benvenuto; muovi la mappa e lo zoom; velocità; due stazioni; deposito; strumento Binari;
|
||||
profilo e opere (anteprima del tracciato, con ponti e gallerie nel riepilogo); costruisci; collega il
|
||||
deposito; attendi i cantieri; locomotiva; carri; componi; linea; assegna; Mercato globale; Finanze; La
|
||||
tua scalata; consigli. I conteggi delle entità sono assoluti (un tutorial ripreso non chiede di rifare
|
||||
ciò che c'è già), i passi del binario contano i comandi riusciti dall'inizio del passo.
|
||||
5. **Interfaccia.** Riquadro non modale ancorato in basso a sinistra dell'area della mappa (o del pannello
|
||||
a tutto schermo, se aperto): non copre barra degli strumenti, barra superiore né pannello destro, si
|
||||
riduce a una riga. Numero del passo, barra d'avanzamento, titolo, testo, «Fatto: …» per un istante,
|
||||
pulsanti Avanti (solo informativi; «Fine» all'ultimo), Salta passo, Chiudi tutorial. Contorno ambra che
|
||||
pulsa attorno all'elemento (pulsante della barra, velocità, livello, profilo, pulsanti dei pannelli
|
||||
Treni e Linee, mappa), ritagliato dai contenitori a scorrimento (barra degli strumenti, pannello
|
||||
destro): la prima volta in un passo l'elemento si porta in vista, e se resta del tutto nascosto si
|
||||
evidenzia il ripiego. I pulsanti del riquadro non prendono il fuoco: Invio e spazio restano alla partita
|
||||
(Costruisci, pausa). Colori e caratteri da `Palette`/`UiTheme` (immagine 05). Il riquadro si nasconde
|
||||
con la Cronaca aperta e a connessione persa; F1 lo nasconde o lo riapre.
|
||||
6. **Avvio e stato.** Nella schermata di connessione (`ConnectScreen`, immagine 09, ADR 0021), sotto
|
||||
«Connetti e riprendi» e «Nuova partita sul server», la casella «Mostra il tutorial» vale per la partita
|
||||
che si apre ed è attiva finché non se n'è aperta una (impostazione `tutorial/played`, scritta anche
|
||||
quando la partita locale ha già dei salvataggi: chi aggiorna non riceve il tutorial nella partita in
|
||||
corso). «Connetti e riprendi» apre come sempre la partita del server; il pulsante «Tutorial» chiude la
|
||||
sessione di prova della schermata e apre invece una partita locale di prova sempre nuova in
|
||||
`user://tutorial-server` (svuotata a ogni avvio, come quella del collaudo), con il tutorial dal primo
|
||||
passo, e lascia intatta la partita del giocatore. L'avanzamento sta in
|
||||
`user://settings.cfg`, sezione `tutorial`, una voce per partita con chiave
|
||||
`g_<origine>_<seme>_<lato>_<anno d'inizio>_<regione>_<compagnia>` (origine `local`, `tutorial` o
|
||||
`remote_<host>_<porta>`; il resto dal Welcome) e valore `active:<passo>`, `completed` o `closed`. La
|
||||
chiave usa solo dati che non cambiano durante la partita: non l'impronta del terreno, che il server
|
||||
ricalcola e che cambia quando le città si allargano o le industrie nascono e chiudono. Aprendo una
|
||||
partita: un tutorial in corso si riprende dal passo salvato (anche dopo un caricamento), uno chiuso o
|
||||
completato resta nascosto a meno che il giocatore spunti la casella (una partita nuova con lo stesso
|
||||
seme ha la stessa chiave di una vecchia), senza voce si mostra solo se richiesto; la richiesta della schermata
|
||||
vale per la partita aperta, non per una Nuova partita+.
|
||||
7. **Pilota automatico.** Con `--autopilot` il tutorial non si crea: le schermate della partita nel
|
||||
collaudo non cambiano; quella di connessione mostra in più la riga del tutorial.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Nessun cambiamento a Core, Protocol, Server né al formato dei salvataggi. Nel client: punti d'aggancio
|
||||
in `GameScreen` (`TutorialTarget`, `TutorialArea`, `CurrentTool`, `TrackPreviews`) e proprietà di sola
|
||||
lettura su `Toolbar`, `TopBar`, `TrackPanel`, `TrainsPanel`, `LinesPanel`.
|
||||
- Un nuovo passo si aggiunge nel JSON e in `strings.csv`; i test controllano copione, traduzioni, pannelli
|
||||
allineati a `Hud.Tool` ed elementi risolti da `GameScreen`.
|
||||
- Limiti: il tutorial non verifica che il deposito sia davvero raccordato (il passo dice di saltarlo se lo
|
||||
è già); due partite con la stessa origine, lo stesso seme, la stessa mappa e la stessa compagnia
|
||||
condividono la voce; riaperto con F1 o con la casella in una partita già avviata, il tutorial riparte
|
||||
dal primo passo e i passi già soddisfatti si completano uno dopo l'altro (i due del binario chiedono una
|
||||
costruzione o Salta passo); i
|
||||
pulsanti dei pannelli si evidenziano solo a pannello aperto (prima si evidenzia il pulsante della barra);
|
||||
interfaccia non ancora provata in Godot (qui manca l'editor).
|
||||
@@ -0,0 +1,98 @@
|
||||
# ADR 0024 — Tooltip «perché»: spiegazioni dei valori calcolate dal server (F6)
|
||||
|
||||
Stato: accettato (F6, issue #44).
|
||||
|
||||
## Contesto
|
||||
|
||||
La roadmap della F6 chiede che ogni valore importante mostri, al passaggio del mouse, *perché* vale
|
||||
quello che vale: la formula applicata e i suoi termini con i valori di oggi. Il client non contiene
|
||||
logica di gioco (§14.3): non può rifare le formule, e non deve nemmeno ricomporle da campi sparsi dei
|
||||
quadri, altrimenti la spiegazione e il valore del motore possono divergere. Il formato dei salvataggi
|
||||
non cambia.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Un modello comune nel Core** (`Economy/Explanation.cs`): `ExplainTarget(Subject, A, B)` dice quale
|
||||
valore spiegare, `Explanation` porta giorno, disponibilità, titolo, nome dell'oggetto, valore con
|
||||
unità (`ExplainUnit`) e testo, formula, termini (`ExplanationTerm`: simbolo, etichetta, valore, unità,
|
||||
testo) e note. Soggetti:
|
||||
|
||||
| Soggetto | A | B | Valore |
|
||||
|---|---|---|---|
|
||||
| 1 GlobalPrice | bene | — | prezzo globale di oggi |
|
||||
| 2 LocalPrice | bene | industria | prezzo della prossima unità (al consumatore se il bene è un ingresso, altrimenti al produttore) |
|
||||
| 3 FreightTariff | linea | bene | tariffa di una unità sulla tratta più lunga |
|
||||
| 4 PassengerTariff | linea | 0 lavoratori, 1 personale | tariffa di un posto sulla tratta più lunga |
|
||||
| 5 IndustryEfficiency | industria | — | efficienza dell'ultima produzione |
|
||||
| 6 IndustryGrowth | industria | — | punteggio di crescita del trimestre |
|
||||
| 7 TownGrowth | città | — | crescita stimata del prossimo mese |
|
||||
| 8 TrainCondition | treno | — | condizione del componente più debole |
|
||||
| 9 Rating | — | — | punteggio del rating (testo: la lettera) |
|
||||
| 10 TierProgress | — | — | avanzamento verso il prossimo livello |
|
||||
| 11 VehicleValue | veicolo | — | valore contabile (con rivendita) |
|
||||
| 12 Cash | — | — | cassa |
|
||||
|
||||
2. **Una sola fonte per ogni numero.** `Explanations` (pure funzioni del mondo, come i quadri dei
|
||||
pannelli) chiama le stesse funzioni del motore; dove la formula stava in linea nel sistema, la si è
|
||||
estratta in una funzione che il sistema ora usa, senza cambiare l'ordine delle operazioni (hash delle
|
||||
partite invariati):
|
||||
- `Market.NextPrice` (passo del prezzo globale, usato da `MarketSystem`) e `Market.LocalPriceTerms`
|
||||
(usato da `LocalPrice`);
|
||||
- `Tariffs.FreightTerms` / `PassengerTerms` (usati da `Freight` / `Passenger`);
|
||||
- `TownSystem.GrowthOf` (usato da `Grow`), `Fleet.DailyHazard` (usato da
|
||||
`FleetMaintenanceSystem.CheckFailure`), `Fleet.ConditionDue` (usato da `Fleet.Dues`: la stima del
|
||||
pianificatore con il componente che la dà, che non è per forza il più debole), `GameClock.YearsAt`;
|
||||
- per gli altri valori bastano le funzioni già esistenti: `IndustryMath.GrowthScore`,
|
||||
`FinanceOutlook.Explain`, `ClimbOutlook.Requirements`, `Obsolescence`,
|
||||
`TradingMath.ConsumerPrice` / `ProducerPrice`.
|
||||
I termini ricompongono il valore con la formula dichiarata: il prezzo globale mostra anche domanda e
|
||||
offerta con il resto del mondo (`Dtot`, `Stot`), l'elasticità e i limiti del rapporto D/S.
|
||||
I test (`Economy/ExplanationTests.cs`) confrontano per uguaglianza esatta il valore di ogni
|
||||
spiegazione con quello del motore.
|
||||
3. **Efficienza: termini transitori.** `IndustrySystem` registra i termini dell'ultima produzione in
|
||||
`Industry.LastEfficiency` (giorno, coperture, fattori, la condizione degli impianti da cui viene mc,
|
||||
letta prima della manutenzione dello stesso tick, efficienza). Non è salvato né entra nell'hash:
|
||||
dopo un caricamento la spiegazione dice che i termini arrivano con la prossima produzione.
|
||||
4. **Prezzo globale ricostruito.** Il passo del mercato avviene all'ultimo tick eseguito, quindi la
|
||||
spiegazione rifà `Market.NextPrice` con il prezzo di ieri dallo storico, le finestre di domanda e
|
||||
offerta (invariate dal passo), lo shock corrente e gli anni a quel tick. Se il risultato non coincide
|
||||
con il prezzo di oggi una nota lo dice.
|
||||
5. **Convenzioni per i valori stimati.** La crescita della città è la stima del prossimo mese con lo stato
|
||||
di oggi (la crescita si applica a inizio mese). Le tariffe sono di una unità (o un posto) consegnata
|
||||
puntuale sulla tratta dalla prima fermata a quella più lontana in linea d'aria, con in più tf e la
|
||||
tariffa a due volte il tempo atteso; il comfort è quello del primo treno della linea. La cassa a
|
||||
inizio mese è ricavata come cassa − flusso del mese in corso. Gli hub non hanno spiegazione.
|
||||
6. **Protocollo: la via dei dettagli su richiesta.** Nessun campo nuovo nei delta: `RequestDetail` con
|
||||
`kind` 11 (`Explain`) e un blocco 1 (`subject: u8, arg: i32`, scritto solo se `subject` ≠ 0;
|
||||
`target` è A, `arg` è B). Il server risponde sempre con `ExplanationReport` (id 137), anche per un
|
||||
bersaglio inesistente, chiuso o di un'altra compagnia (`available` falso, nota «Valore non
|
||||
disponibile.»), così il tooltip smette di aspettare. Sono riservati alla compagnia della sessione
|
||||
(uno spettatore non li riceve): tariffe di una linea, condizione di un treno, valore di un veicolo,
|
||||
rating, avanzamento del livello, cassa. Prezzi, industrie e città sono pubblici come nei quadri. Un server vecchio non conosce il kind 11 e non
|
||||
risponde; un lettore vecchio ignora il blocco della richiesta.
|
||||
7. **Testi.** Titoli, formule, etichette, note e i simboli che sono parole sono testi italiani fissi:
|
||||
il client li traduce con `T()` (chiavi in `strings.csv`); i numeri viaggiano solo nei termini.
|
||||
8. **Client.** `WhyTooltip` è un solo controllo per la schermata di gioco, su un `CanvasLayer` sopra
|
||||
l'interfaccia, nello stile della palette 05. I pannelli lo agganciano con `WhyTooltip.Attach(controllo,
|
||||
bersaglio, suggerimento, valore mostrato)`; si apre dopo 0,45 s e chiede la spiegazione a ogni
|
||||
apertura e poi, finché il puntatore resta, al più una volta al secondo per valore (molti valori
|
||||
cambiano dentro la giornata: cassa, condizione, prezzi locali). Intanto mostra quella in cache con
|
||||
«aggiornamento in arrivo…», o «in arrivo…» se manca. Se il pannello ricostruisce il controllo sotto il
|
||||
puntatore (le schede si rifanno a ogni secondo), il tooltip passa al sostituto con la stessa
|
||||
spiegazione senza chiudersi. Dove il pannello mostra un numero di un altro momento (la cassa della
|
||||
barra superiore e delle Finanze) il tooltip, se differisce, dice che quello spiegato è di adesso.
|
||||
Prezzi con i decimali della scheda dell'industria, importi sotto ₤ 1.000 con i centesimi, condizione
|
||||
per difetto in percentuale come nelle Officine. Agganci: barra
|
||||
superiore (cassa, rating, livello), Mercato (prezzo globale, prezzi locali), Scalata (avanzamento e
|
||||
requisiti), Finanze (cassa, rating), scheda industria (efficienza, prezzo di vendita, punteggio di
|
||||
crescita, prezzi dei partner), Treni (valore dei veicoli in deposito, condizione dei treni), Officine
|
||||
(condizione del treno).
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Il valore spiegato e quello mostrato dal pannello vengono dalla stessa funzione del motore.
|
||||
- Una formula nuova del motore che si vuole spiegare va estratta in una funzione condivisa, non copiata.
|
||||
- Limiti: dopo un caricamento l'efficienza non ha termini fino alla produzione del giorno dopo; le
|
||||
tariffe e le crescite di città non hanno ancora un aggancio nei pannelli Linee e Info (il Core e il
|
||||
protocollo le servono già); il tooltip non è stato provato dentro Godot, che non gira nell'ambiente di
|
||||
sviluppo (il client compila senza avvisi).
|
||||
@@ -0,0 +1,247 @@
|
||||
# ADR 0025 — Bilanciamento con i bot su simulate (F6)
|
||||
|
||||
Stato: accettato (F6, issue #47), rivisto dopo la revisione (sezione «Correzioni della revisione»).
|
||||
|
||||
## Contesto
|
||||
|
||||
La sezione 16 chiede per la F6 il «bilanciamento con bot su `simulate`». Fino a qui prezzi, soglie dei
|
||||
livelli e taratura economica erano provvisori (STATE, «Limiti noti»): il prezzo del minerale saliva oltre
|
||||
1,5 volte il base, il margine dei trasformatori diventava negativo quando la domanda superava l'offerta
|
||||
delle miniere, l'acciaieria dello scenario cresceva di livello ogni due trimestri, e in molte partite due
|
||||
IA su tre non costruivano nulla. Mancavano un banco di prova ripetibile, obiettivi scritti prima di
|
||||
toccare i numeri e la compravendita in proprio delle IA (ADR 0016 §9).
|
||||
|
||||
## Obiettivi (scritti prima della taratura)
|
||||
|
||||
Gli obiettivi si misurano sulla matrice predefinita del banco (semi 1, 2, 3; le quattro difficoltà; bot
|
||||
competente e prudente; 12 anni su 128 km) e si verificano sui semi 4–9, mai usati nella taratura. Ognuno ha
|
||||
un motivo nella guida. Le regole di misura in corsivo sono state precisate dopo la revisione (vedi sotto):
|
||||
non cambiano le soglie, tolgono i modi in cui un obiettivo passava senza misurare nulla.
|
||||
|
||||
| Id | Obiettivo | Perché |
|
||||
|---|---|---|
|
||||
| O1 | Bot competente in «Imprenditore»: livello 2 tra il 3° e il 6° anno (mediana dei semi; *con un numero pari di semi entrambi i valori centrali*) | La difficoltà predefinita (7) deve dare il primo sblocco (fido, squadre, compravendita) dopo le prime linee, non subito e non mai |
|
||||
| O2 | Bot competente in «Apprendista»: livello 2 entro il 5° anno (mediana, *come O1*) | Capitale doppio, tariffe ×1,15, costi ×0,8: la scalata deve essere più facile |
|
||||
| O3 | Patrimonio finale mediano del bot competente non crescente da «Apprendista» a «Ferro e sangue» (*solo partite in cui il bot ha almeno una linea; «non valutabile» se in una difficoltà non ne ha mai*) | La tabella della sezione 7 peggiora ogni parametro salendo: la difficoltà deve contare |
|
||||
| O4 | Nessun fallimento del bot prudente in «Apprendista» e «Imprenditore» (*solo partite giocate*) | Un giocatore prudente non deve finire in bancarotta (12.3: in «Apprendista» non si perde mai) |
|
||||
| O5 | Nessun fallimento del bot competente in «Apprendista» e «Imprenditore» (*solo partite giocate*) | Le stime dei tooltip (gli stessi `Estimators` delle IA) devono essere affidabili |
|
||||
| O6 | Media di ogni bene *in ogni partita* entro 0,7–1,6 volte il prezzo base | 6.3: il prezzo segue il ciclo mondiale (A = 0,12) con gli squilibri della mappa; i limiti 0,3–3 sono di sicurezza, non lo stato normale |
|
||||
| O7 | *In ogni difficoltà* almeno il 95 % dei mesi-bene entro 0,7–1,6 volte il base, *fascia allargata in proporzione alla volatilità del mercato della difficoltà quando è oltre 1* | Come O6, mese per mese: gli shock (fino a 0,3 × volatilità) possono uscire per poco; in «Magnate» e «Ferro e sangue» la sezione 7 moltiplica A e shock per 1,3 e 1,6 e il solo prezzo mondiale arriva a 1,67 volte il base |
|
||||
| O8 | Margine medio dei trasformatori che vendono positivo in almeno l'80 % dei mesi (*che vendono = almeno un giorno con vendite nell'ultimo trimestre*) | 6.3: `pf = clamp(1 + 0,5·margine)`: con margini negativi le industrie servite rendono meno proprio quando il trasporto funziona. Si escludono i trasformatori senza vendite, il cui margine va a −1 per costruzione |
|
||||
| O9 | Efficienza media delle industrie servite almeno 0,6 nella seconda metà della partita | ADR 0004 §5: un'industria isolata parte da circa 0,3; servirla deve almeno raddoppiarla |
|
||||
| O10 | Popolazione in «Imprenditore» con il bot: crescita media annua almeno −0,5 % | ADR 0004: senza vettori il mondo perde circa l'1 % l'anno; con bot e IA il declino deve almeno dimezzarsi |
|
||||
| O11 | Almeno la metà delle IA con una linea in esercizio entro il 3° anno (*sulle IA presenti alla fine del 3° anno*) | 12.1: concorrenti che giocano davvero |
|
||||
| O12 | Bot competente in «Imprenditore»: interessi entro il 20 % dei ricavi dei trasporti (*anno chiuso, dicembre compreso*) | 6.3: il debito è uno strumento, non una rendita della banca |
|
||||
| O13 | Comandi rifiutati di bot e IA al massimo il 5 % | 14.5 |
|
||||
| O14 | Invarianti di denaro e merci in ogni esecuzione | 14.5 |
|
||||
|
||||
*Gli obiettivi del mondo (O6–O11) si contano su una partita per seme e difficoltà* (quella del bot
|
||||
competente): le due partite dei bot con lo stesso seme condividono mappa e IA e, se il bot non costruisce,
|
||||
sono quasi lo stesso mondo.
|
||||
|
||||
Restano vere le accettazioni: F2 (acciaieria di Valdoria da meno del 40 % a oltre l'80 % in 2 anni), F4
|
||||
(`MaintenanceAcceptanceTests`), F5 (un'IA al livello 3 in 15 anni in «Magnate», seme 7).
|
||||
|
||||
## Decisione
|
||||
|
||||
### Banco di prova
|
||||
|
||||
- `railenterprise-tools balance [--seeds 1,2,3] [--difficulties …] [--bots bot_competent,bot_prudent|nessuno]
|
||||
[--years 12] [--size 128] [--threads n] [--out bilanciamento]` fa giocare, per ogni combinazione seme ×
|
||||
difficoltà × bot, la compagnia del giocatore a un **bot giocatore** insieme alle IA, giorno per giorno, e
|
||||
scrive `rapporto.txt` (obiettivi O1–O14 e sintesi per difficoltà e bot), `anni.csv` (per compagnia e anno
|
||||
chiuso: livello, patrimonio, rating, cassa, debito, interessi, ricavi dei trasporti, utile operativo, treni,
|
||||
linee), `mesi.csv` (prezzi/base, margini dei trasformatori, coperture, efficienza delle servite, popolazione,
|
||||
quota di veicoli superati), `prezzi.csv`, `esecuzioni.csv` (anno di ogni livello, fallimenti, comandi
|
||||
rifiutati, IA al 3° anno, mesi senza reti nuove in attesa dei ricambi, affari di compravendita, hash
|
||||
finale) e `tempi.txt`. L'anno si campiona dopo il primo giorno dell'anno successivo, che chiude il bilancio
|
||||
con rate e interessi di dicembre (`LastYearEntries`); la partita dura quindi un giorno in più degli anni
|
||||
chiesti. Le esecuzioni girano in parallelo ma il rapporto segue l'ordine della matrice e non contiene
|
||||
tempi: stesso seme, stesso rapporto (test, anche con più mondi insieme). `simulate --bot <id>` gioca una
|
||||
partita con il bot.
|
||||
- Il bot giocatore (`PlayerBot`) è l'agente delle IA (stessi comandi, stesse stime) con una personalità di
|
||||
`ai.json → bots` (`bot_competent`: ROI 10 %, fido al 60 %, manutenzione standard; `bot_prudent`: ROI 18 %,
|
||||
fido al 25 %, manutenzione accurata). Pianifica lo stesso giorno della prima IA ma prima di lei, come un
|
||||
giocatore che costruisce dal primo giorno. È uno strumento di prova: non entra nel salvataggio né nell'hash
|
||||
(ne entrano gli effetti, che passano tutti dai comandi), quindi il formato dei salvataggi non cambia. I
|
||||
contatori diagnostici dell'agente (`AiState.PartsBlockedMonths`, `Trades`) non sono salvati.
|
||||
- Tempi della matrice predefinita (24 esecuzioni da 12 anni su 128 km, 12 in parallelo): 543 s in tutto,
|
||||
184 s per esecuzione in media, 411 s la più lunga (il codice di prima della taratura: 571 / 180 / 444 s).
|
||||
Semi di verifica 4–9 (48 esecuzioni): 597 s, 124 s in media.
|
||||
|
||||
### Compravendita delle IA (supera ADR 0016 §9)
|
||||
|
||||
Ogni mese, dopo i progetti, l'agente (IA o bot) vende le scorte dei propri magazzini se il miglior acquirente
|
||||
del bacino paga almeno `minSellPriceShare` del prezzo globale; se il livello sblocca la compravendita, cerca
|
||||
per ogni stazione e bene il venditore più economico del bacino e il compratore migliore nello stesso bacino
|
||||
o in una stazione raggiungibile dalle sue linee merci (`LineGraph`); un affare vale se il margine
|
||||
(vendita − acquisto)/acquisto è almeno `minMargin`. Quantità: al più `maxUnits`, la merce disponibile, lo
|
||||
spazio del magazzino, quanto ricevono i compratori e il budget del mese, la quota `cashShare` della cassa
|
||||
oltre `cashReserveMultiple` volte la riserva, che vale per tutti gli affari del mese insieme (ogni acquisto
|
||||
lo riduce di quanto è costato). Gli affari si ordinano per utile (poi stazione, bene, destinazione) e se ne
|
||||
fanno al più `maxTradesPerMonth`, uno per stazione e bene, con prezzo massimo e minimo a ±`priceSlack` dalla
|
||||
quotazione; nello stesso bacino si rivende subito (solo alle industrie se nel bacino c'è un hub, che compra e
|
||||
vende con la stessa capacità mensile, e ricontrollando lo spazio dei compratori, che due stazioni vicine
|
||||
possono condividere), altrimenti si spedisce. Parametri in `ai.json → trading`; il validatore chiede
|
||||
`minMargin > 2·priceSlack`.
|
||||
|
||||
### Regole dell'agente corrette con il banco
|
||||
|
||||
1. **Trasformatori senza input** (causa dei fallimenti dei bot): una linea che parte da un'industria di
|
||||
trasformazione ne stimava la produzione con l'efficienza del giorno, alta all'inizio per scorte e copertura
|
||||
iniziali; finite le scorte l'impianto si fermava e la linea non incassava più nulla. Ora un trasformatore è
|
||||
una fonte solo se ogni suo input è alimentato (una stazione in esercizio lo serve, o un produttore di quel
|
||||
bene è nel raggio del trasporto locale).
|
||||
2. **Linea dei ricambi rimandata**: una rete nuova lontana dai ricambi metteva subito nel budget anche la linea
|
||||
dei ricambi (spesso più cara della linea stessa) e in «Imprenditore» il bot non costruiva mai. Ora la linea
|
||||
dei ricambi entra sempre nel ROI ma esce dal budget iniziale se l'utile atteso la ripaga prima che finisca
|
||||
la dotazione iniziale del deposito, e comunque entro `planning.partsDeferYears` (3 anni). La durata della
|
||||
dotazione si stima dai tagliandi dei treni previsti: `initialSpareParts` (25) diviso per veicoli × tagliandi
|
||||
all'anno (360 / (180 giorni × `intervalFactor` della politica)) × ricambi del tagliando; per un treno di
|
||||
locomotiva e 5 carri sono 12 ricambi l'anno con la politica standard (circa 2 anni) e 17 con quella accurata
|
||||
(circa 1,5 anni); riparazioni e revisioni non sono contate, quindi la stima è per eccesso. Finché un deposito
|
||||
in esercizio aspetta la sua linea e la cassa non basta, l'agente non apre reti nuove (progetti con un
|
||||
deposito nuovo); le linee che partono da un deposito esistente restano possibili. Il blocco vale al più
|
||||
`partsDeferYears` dall'apertura della rete; poi l'agente torna a espandersi come prima. Il banco conta i
|
||||
mesi di blocco: nella matrice predefinita 0–8 per il bot competente in «Imprenditore», al più 49 in tutto
|
||||
per le tre IA di «Apprendista» in 12 anni.
|
||||
|
||||
### Taratura dei dati
|
||||
|
||||
| File | Valore | Prima | Dopo | Motivo |
|
||||
|---|---|---|---|---|
|
||||
| `balance.json` | `market.world.volumeShare` | 0,5 | 1,0 | il resto del mondo scambia quanto la mappa: gli squilibri locali spostano meno il prezzo (O6, O7) |
|
||||
| `balance.json` | `market.world.elasticity` | 1,0 | 2,5 | domanda e offerta del mondo reagiscono di più al prezzo e lo riportano verso il ciclo; vedi «Accettazione F4» per il legame con la flotta |
|
||||
| `ai.json` | `planning.townBonus` | 1,8 | 3,0 | quando il livello successivo chiede città collegate, le linee verso le città passano davanti alle merci (O1) |
|
||||
| `ai.json` | `planning.townRoiFactor` | 0,5 | 0,35 | idem: soglia del ROI delle linee urbane al 35 % di quella della personalità |
|
||||
| `ai.json` | `planning.partsDeferYears` | — | 3,0 | nuovo, regola 2 |
|
||||
| `ai.json` | `trading`, `bots` | — | nuovi | compravendita e bot giocatore |
|
||||
|
||||
Tutti i valori di `ai.json → planning` e `balance.json → market.world` hanno ora proprietà esplicite con
|
||||
limiti negli schemi (per esempio `elasticity` > 0, `volumeShare` 0–10, `townRoiFactor` in (0, 1],
|
||||
`partsDeferYears` 0–10) e il validatore controlla `candidateMinDistanceKm < candidateMaxDistanceKm` e
|
||||
`shockMin ≤ shockMax`.
|
||||
|
||||
**Linee urbane sotto il tasso dei prestiti.** Con `townRoiFactor` 0,35 la soglia delle linee verso le città,
|
||||
quando servono al livello, scende al 3,5 % per il bot competente e al 2,8 % per l'IA espansiva, sotto il tasso
|
||||
base dei prestiti (5 %, 7 %, 9 %), ed `Execute` prende a prestito quanto manca: un progetto finanziato a debito
|
||||
può rendere meno del suo interesse. È voluto: il valore di queste linee è lo sblocco del livello (fido, squadre,
|
||||
compravendita), che il ROI non misura. Una soglia minima al tasso del prestito è stata provata: sui semi 1–3 il
|
||||
bot competente in «Imprenditore» non arriva più al livello 2 entro 6 anni nel seme 3 (prima al 3°) e O1 cade.
|
||||
|
||||
Restano com'erano i valori fissati dalla guida (capitale e fido iniziali, moltiplicatori di difficoltà, k, α,
|
||||
A, T, limiti 0,3–3, formula del costo dei binari) e le soglie dei livelli.
|
||||
|
||||
### Accettazione F4 ed elasticità del mondo
|
||||
|
||||
La flotta senza ricambi dell'accettazione F4 (soglia: sotto 40 entro 3 anni) dipende dal mercato attraverso la
|
||||
produzione: i prezzi mondiali cambiano margini e fattore di profitto delle industrie di Valdoria, quindi i carichi
|
||||
e le attese dei treni, i km percorsi, l'usura e il momento dei guasti (estratti a caso). Il legame non è
|
||||
monotono: con il mondo a volume pieno la flotta minima senza linea è 42 con elasticità 1,0, 43 con 2,0, 39 con
|
||||
2,5 e 41 con 3,0. Fra i valori provati solo 2,5 tiene verde la F4, con un'unità di margine: un ritocco del
|
||||
mercato o degli agenti può farla uscire per caso. Una scelta con margine (37 o meno) non esiste tra i valori
|
||||
provati; renderla indipendente dal mercato (come lo scenario fa già con gli eventi, ADR 0017 §8) è una modifica
|
||||
dello scenario dell'accettazione da decidere a parte.
|
||||
|
||||
### Prima e dopo
|
||||
|
||||
«Prima» è il codice e i dati di prima della taratura misurati con il banco di adesso; «dopo» la matrice
|
||||
predefinita (semi 1–3, quattro difficoltà, due bot, 12 anni, 128 km); «verifica» gli stessi parametri sui
|
||||
semi 4–9.
|
||||
|
||||
| Metrica | Prima | Dopo (semi 1–3) | Verifica (semi 4–9) |
|
||||
|---|---|---|---|
|
||||
| O1 livello 2 del bot competente in «Imprenditore» (anni dei semi) | mai / 5 / 7, mediana 7: no | 4 / 8 / 3, mediana 4: sì | 4 / 8 / 10 / 4 / 4 / mai, mediana 4–8, 3 su 6 nella fascia: no |
|
||||
| O2 livello 2 del bot competente in «Apprendista» | mediana 1: sì | 2 / 2 / 7, mediana 2: sì | 1 / 4 / 3 / 3 / 3 / 6, mediana 3: sì |
|
||||
| O3 patrimonio finale mediano del bot competente (Appr. / Impr. / Magn. / Ferro) | ₤ 1.987.362 / 389.784 / — / —: non valutabile | ₤ 4.722.732 / 1.680.803 / — / —: non valutabile | ₤ 2.848.486 / 2.011.836 / 399.208 / —: non valutabile |
|
||||
| Partite in cui il bot costruisce (competente / prudente; su 12 per bot, 24 nella verifica) | 5 / 2 | 6 / 3 | 13 / 10 |
|
||||
| O4 fallimenti del bot prudente (Appr. e Impr., partite giocate) | 1 su 2 | 0 su 3 | 0 su 10 |
|
||||
| O5 fallimenti del bot competente (Appr. e Impr., partite giocate) | 1 su 5 | 0 su 6 | 0 su 12 |
|
||||
| O6 medie partita-bene fuori 0,7–1,6 (peggiori) | 113 su 180 (minerale 0,31 – alimentari 2,96) | 3 su 180 (minerale 0,70 – materiali edili 1,45) | 8 su 360 (minerale 0,69 – manufatti 1,46) |
|
||||
| O6 media sull'insieme delle partite, bene più basso e più alto | 0,38 (grano) – 2,77 (alimentari) | 0,77 (bestiame) – 1,42 (materiali edili) | 0,77 (grano) – 1,42 (manufatti) |
|
||||
| Minerale di ferro / base in «Imprenditore» (min / medio / max) | 0,30 / 0,68 / 1,69 | 0,55 / 0,83 / 1,20 | 0,53 / 0,82 / 1,27 |
|
||||
| Acciaio / base in «Imprenditore» (min / medio / max) | 1,05 / 2,31 / 3,00 | 1,03 / 1,39 / 1,82 | 0,95 / 1,31 / 1,70 |
|
||||
| O7 mesi-bene nella fascia (Appr. / Impr. / Magn. / Ferro) | 34,2 / 35,3 / 41,5 / 49,2 % | 94,1 / 93,5 / 98,9 / 99,7 % | 95,0 / 92,8 / 98,4 / 99,6 % |
|
||||
| O8 mesi con margine medio positivo dei trasformatori che vendono | 74,9 % (margine +0,239) | 61,7 % (margine +0,017) | 74,7 % (margine +0,171) |
|
||||
| O9 efficienza delle industrie servite, seconda metà | 0,326 | 0,357 | 0,358 |
|
||||
| Coperture medie input / lavoratori / personale («Imprenditore», bot competente) | 0,80 / 0,36 / 0,43 | 0,80 / 0,36 / 0,43 | 0,79 / 0,35 / 0,42 |
|
||||
| Ampliamenti per industria servita all'anno («Imprenditore», bot competente) | 0,31 | 0,32 | 0,35 |
|
||||
| O10 crescita annua delle città in «Imprenditore» | −0,9 % | −0,9 % | −0,9 % |
|
||||
| O11 IA con una linea entro il 3° anno | 42,4 % (14 su 33) | 39,4 % (13 su 33) | 56,1 % (37 su 66) |
|
||||
| O12 interessi / ricavi dei trasporti del bot competente in «Imprenditore» | 5,8 % | 4,3 % | 4,3 % |
|
||||
| O13 comandi rifiutati di bot e IA | 2,7 % (167 su 6.248) | 0,1 % (9 su 6.749) | 0,1 % (15 su 14.794) |
|
||||
| O14 invarianti di denaro e merci | rispettati | rispettati | rispettati |
|
||||
| Veicoli superati alla fine dei 12 anni | 0 % | 0 % | 0 % |
|
||||
| Obiettivi raggiunti (O3 non valutabile) | 4 su 13 | 7 su 13 | 7 su 13 |
|
||||
|
||||
Raggiunti dopo la taratura: O1, O2, O4, O5, O12, O13, O14 sui semi 1–3; O2, O4, O5, O11, O12, O13, O14 sui semi
|
||||
di verifica.
|
||||
|
||||
### Obiettivi non raggiunti (restano aperti)
|
||||
|
||||
- **O1 sui semi di verifica**: il livello 2 arriva al 4° anno in 3 semi su 6, poi all'8°, al 10° o mai; sui
|
||||
semi della taratura la mediana poggiava su una partita (4 / 8 / 3). La taratura di `townBonus` e
|
||||
`townRoiFactor` non generalizza abbastanza: la scalata dipende molto dalla mappa.
|
||||
- **O3**: in «Ferro e sangue» (e in «Magnate» sui semi 1–3) il bot non costruisce mai: con ₤ 150.000 e
|
||||
₤ 100.000 e i costi ×1,25 e ×1,5 nessuna prima rete supera il ROI della personalità. L'obiettivo non si
|
||||
può valutare finché il bot non gioca in ogni difficoltà.
|
||||
- **O6, O7**: i beni lavorati (acciaio, legname, materiali edili, manufatti) stanno a lungo sopra 1,6 volte il
|
||||
base in «Apprendista» e «Imprenditore», e il minerale scende a 0,7 in qualche partita; un'elasticità più alta
|
||||
li rientrerebbe ma la F4 non lo permette (sopra).
|
||||
- **O8**: misurato sui trasformatori che hanno venduto nell'ultimo trimestre, il margine è peggiorato con la
|
||||
taratura (da +0,24 a +0,02 di media sui semi 1–3): prima i beni lavorati costavano 2–3 volte il base e i
|
||||
trasformatori che vendevano guadagnavano molto; riportati i prezzi verso il base, il margine resta sottile
|
||||
e negativo in quasi 4 mesi su 10. La conclusione della prima versione («logistica, non prezzo», 5,6 % dei
|
||||
mesi con margine −0,70) veniva da una misura sbagliata (RevenueEma > 0, che dopo la prima vendita non torna
|
||||
più a zero e contava i trasformatori fermi da anni). Correggerlo vuol dire ritoccare prezzi base o ricette dei
|
||||
beni lavorati, una decisione a parte.
|
||||
- **O9, O10**: con le sole linee merci l'efficienza resta limitata dai lavoratori (copertura 0,36): servono
|
||||
linee pendolari, che bot e IA costruiscono di rado; la crescita delle città resta quella senza vettori.
|
||||
- **O11** sui semi 1–3 (39 %) e in «Ferro e sangue» (2 IA su 15 entro il 3° anno sui semi 1–3, 8 su 30 su quelli
|
||||
di verifica).
|
||||
- La crescita dell'acciaieria dello scenario «ogni due trimestri» non si ripete sulla mappa generata (0,3
|
||||
ampliamenti per industria servita all'anno); il punteggio di crescita della sezione 6 resta com'è.
|
||||
|
||||
## Correzioni della revisione
|
||||
|
||||
- O8 contava come «trasformatori che vendono» quelli con `RevenueEma > 0`: una media mobile esponenziale non
|
||||
torna più a zero dopo la prima vendita. Il banco ricava ogni giorno le vendite dalla media mobile e conta i
|
||||
trasformatori con vendite nell'ultimo trimestre (`growth.quarterDays`), come `ServedWithin` per le servite.
|
||||
- La taratura era stata fatta e verificata sugli stessi tre semi: ora la verifica gira anche sui semi 4–9, il
|
||||
rapporto dà gli anni di ogni seme e quanti stanno nella fascia, e con un numero pari di semi la mediana vale
|
||||
solo se vale per i due valori centrali. Il test lento usa i semi 4–9.
|
||||
- O6 si misura per partita e bene (la peggiore media), come dice l'obiettivo; la media sull'insieme resta nel
|
||||
rapporto.
|
||||
- Gli interessi di dicembre mancavano: l'anno si campiona dopo il giorno che chiude il bilancio.
|
||||
- O3–O5 contavano anche le partite in cui il bot non costruisce: ora solo quelle giocate, e O3 è «non
|
||||
valutabile» se in una difficoltà il bot non gioca mai (prima passava perché il capitale iniziale decresce con
|
||||
la difficoltà).
|
||||
- O7 era misurato su tutte le difficoltà insieme con la stessa fascia, mentre la sezione 7 moltiplica la
|
||||
volatilità del mercato in «Magnate» e «Ferro e sangue»: ora per difficoltà, con la fascia allargata.
|
||||
- O11 divideva per le IA della fine partita (anche i concorrenti nati dopo il 3° anno) e mostrava «no» per
|
||||
partite più corte di 3 anni: ora divide per le IA presenti alla fine del 3° anno e dice «non eseguito».
|
||||
- Gli obiettivi del mondo contavano due volte le partite dei due bot con lo stesso seme: ora una per seme e
|
||||
difficoltà.
|
||||
- Il test di determinismo confrontava un solo mondo con uno o due thread: ora due mondi in parallelo (veloce) e
|
||||
quattro mondi da 128 km su due difficoltà per 3 anni con quattro thread, con un bot al livello 2 nel primo
|
||||
anno e 28 affari di compravendita (lento).
|
||||
- I valori di taratura non avevano limiti negli schemi: ora sì (sopra).
|
||||
- Il blocco per la linea dei ricambi fermava ogni progetto nuovo, senza limite di tempo: ora ferma solo le reti
|
||||
nuove ed entro `partsDeferYears`. La giustificazione dei 3 anni («la dotazione regge») non era vera: ora il
|
||||
rinvio è legato alla durata stimata della dotazione. Sui semi di verifica la regola di prima faceva fallire il
|
||||
bot competente nel seme 9 di «Imprenditore» (deposito senza ricambi, flotta ferma, ricavi a zero dal 4° anno);
|
||||
ora quel bot non costruisce.
|
||||
- Il budget della compravendita valeva per ogni affare: ora per il mese.
|
||||
- Il numero delle esecuzioni della matrice predefinita era scritto 72: sono 24.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Il banco fa parte della verifica: il test lento `BalanceTests.BenchMeetsTheMainGoals` (semi 4–9,
|
||||
«Imprenditore», bot competente, 6 anni) controlla O5, O12, O13 e O14 e che almeno un bot arrivi al livello 2;
|
||||
`ParallelRunsWithTradingGiveTheSameReport` (lento) e `SameSeedGivesTheSameReport` controllano il determinismo
|
||||
del rapporto con più mondi in parallelo.
|
||||
- `EconomyTests.PriceRisesWhenDemandExceedsSupply` chiedeva un aumento di 1,5 volte in 120 giorni senza
|
||||
offerta; con il mondo a volume pieno ed elasticità 2,5 l'aumento è circa 1,36: la soglia passa a 1,25 (resta
|
||||
la verifica che lo squilibrio alzi il prezzo).
|
||||
- Restano vere le accettazioni F2, F4 (flotta senza ricambi a 39, sotto 40 dal giorno 731, 10 guasti; con la
|
||||
linea 73 e 3 guasti) e F5 (un'IA al livello 3 nel 1861 in «Magnate», seme 7).
|
||||
@@ -10,7 +10,16 @@ public sealed class AiFile
|
||||
public required int Version { get; init; }
|
||||
public required AiPlanningParams Planning { get; init; }
|
||||
public required AiMarketParams Market { get; init; }
|
||||
/// <summary>Rinnovo dei treni con veicoli superati (F6, ADR 0020).</summary>
|
||||
public required AiRenewalParams Renewal { get; init; }
|
||||
/// <summary>Compravendita in proprio delle IA (F6, ADR 0016 §9 e ADR 0025).</summary>
|
||||
public required AiTradingParams Trading { get; init; }
|
||||
public required List<AiPersonalityDef> Personalities { get; init; }
|
||||
/// <summary>
|
||||
/// Personalità dei «bot giocatore» del banco di bilanciamento (ADR 0025): guidano la compagnia del
|
||||
/// giocatore con lo stesso agente delle IA; non si assegnano mai alle compagnie IA.
|
||||
/// </summary>
|
||||
public required List<AiPersonalityDef> Bots { get; init; }
|
||||
public required List<string> CompanyNames { get; init; }
|
||||
public required List<string> Colors { get; init; }
|
||||
}
|
||||
@@ -75,6 +84,51 @@ public sealed class AiPlanningParams
|
||||
public required int PlanningDaySpacing { get; init; }
|
||||
/// <summary>Candidati falliti ricordati per non riprovarli.</summary>
|
||||
public required int FailedMemory { get; init; }
|
||||
/// <summary>
|
||||
/// Una rete nuova lontana dai ricambi parte senza la sua linea dei ricambi (che si costruisce dopo, con
|
||||
/// i ricavi) solo se l'utile atteso la ripaga entro questi anni; altrimenti la linea entra subito nel
|
||||
/// budget (ADR 0025). Zero: sempre subito.
|
||||
/// </summary>
|
||||
public required double PartsDeferYears { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rinnovo della flotta delle IA (ADR 0020): ogni mese al più <see cref="MaxTrainsPerMonth"/> treni in
|
||||
/// servizio con un veicolo superato vanno in officina per il rinnovo, se il veicolo è superato da almeno
|
||||
/// <see cref="MinSupersededYears"/> anni o ha già consumato <see cref="MinAgeShareOfLife"/> della vita
|
||||
/// utile, e se dopo la spesa netta (successori − rivendite) la cassa resta sopra
|
||||
/// <see cref="CashReserveMultiple"/> volte la riserva dell'IA.
|
||||
/// </summary>
|
||||
public sealed class AiRenewalParams
|
||||
{
|
||||
public required double MinSupersededYears { get; init; }
|
||||
public required double MinAgeShareOfLife { get; init; }
|
||||
public required double CashReserveMultiple { get; init; }
|
||||
public required int MaxTrainsPerMonth { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Compravendita in proprio delle IA (ADR 0016 §9, ADR 0025): una volta al mese, dal livello che la sblocca,
|
||||
/// l'agente vende la merce dei propri magazzini ai compratori del bacino che pagano almeno
|
||||
/// <see cref="MinSellPriceShare"/> del prezzo globale e cerca le occasioni migliori: comprare dai produttori
|
||||
/// (o dagli hub) del bacino di una sua stazione e vendere nella stessa stazione o in una raggiungibile con le
|
||||
/// sue linee, quando il margine atteso sulla prossima unità supera <see cref="MinMargin"/>. Al più
|
||||
/// <see cref="MaxTradesPerMonth"/> operazioni da <see cref="MaxUnits"/> unità, con al più
|
||||
/// <see cref="CashShare"/> della cassa libera oltre <see cref="CashReserveMultiple"/> volte la riserva.
|
||||
/// </summary>
|
||||
public sealed class AiTradingParams
|
||||
{
|
||||
public required bool Enabled { get; init; }
|
||||
/// <summary>Margine minimo atteso (vendita − acquisto) / acquisto sulla prossima unità.</summary>
|
||||
public required double MinMargin { get; init; }
|
||||
/// <summary>Scarto ammesso sul prezzo della prossima unità: tetto d'acquisto e minimo di vendita.</summary>
|
||||
public required double PriceSlack { get; init; }
|
||||
/// <summary>Si vende la merce in magazzino solo a chi paga almeno questa quota del prezzo globale.</summary>
|
||||
public required double MinSellPriceShare { get; init; }
|
||||
public required int MaxUnits { get; init; }
|
||||
public required int MaxTradesPerMonth { get; init; }
|
||||
public required double CashShare { get; init; }
|
||||
public required double CashReserveMultiple { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Comportamento in borsa delle IA (12.1–12.2).</summary>
|
||||
|
||||
@@ -243,6 +243,17 @@ public sealed class IndustryBalance
|
||||
public required Dictionary<string, int> FootprintCells { get; init; }
|
||||
public required double DepletionStartFraction { get; init; }
|
||||
public required long StartingCash { get; init; }
|
||||
/// <summary>Scheda dell'industria (IndustryOutlook, ADR 0021).</summary>
|
||||
public required IndustryOutlookBalance Outlook { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Parametri della scheda dell'industria (IndustryOutlook, ADR 0021).</summary>
|
||||
public sealed class IndustryOutlookBalance
|
||||
{
|
||||
/// <summary>Fornitori o clienti elencati per ogni bene della catena produttiva (prima i collegati, poi i più vicini).</summary>
|
||||
public required int PartnersPerGood { get; init; }
|
||||
/// <summary>Provenienze dei lavoratori (e del personale) elencate nella scheda, dalle più numerose.</summary>
|
||||
public required int WorkforceSources { get; init; }
|
||||
}
|
||||
|
||||
public sealed class GrowthBalance
|
||||
@@ -390,6 +401,25 @@ public sealed class FinanceBalance
|
||||
public required CreditRating StartingRating { get; init; }
|
||||
public required int DepreciationYearsTrack { get; init; }
|
||||
public required double BookValueFloor { get; init; }
|
||||
/// <summary>Mesi chiusi conservati per voce: conto economico mensile e finestra del rating (ADR 0019).</summary>
|
||||
public required int IncomeMonths { get; init; }
|
||||
/// <summary>Anni chiusi conservati per voce nel conto economico annuale (ADR 0019).</summary>
|
||||
public required int IncomeYears { get; init; }
|
||||
/// <summary>
|
||||
/// Giorni mancanti alla bancarotta in cui la compagnia riceve un avviso, in ordine decrescente
|
||||
/// (oltre al primo avviso dopo <see cref="NegativeCashNoticeDays"/> giorni, ADR 0019).
|
||||
/// </summary>
|
||||
public required int[] BankruptcyWarningDaysLeft { get; init; }
|
||||
/// <summary>
|
||||
/// Mesi chiusi con ricavi che servono, finché la finestra del rating non è piena, perché il margine
|
||||
/// conti: prima il margine è neutro (0), così i primi incassi non fanno crollare il rating (ADR 0019).
|
||||
/// </summary>
|
||||
public required int RatingMinRevenueMonths { get; init; }
|
||||
/// <summary>
|
||||
/// Giorni di cassa negativa di fila prima del primo avviso; il rientro si annuncia solo dopo almeno
|
||||
/// altrettanti giorni, così una cassa che oscilla intorno a zero non riempie le notizie (ADR 0019).
|
||||
/// </summary>
|
||||
public required int NegativeCashNoticeDays { get; init; }
|
||||
}
|
||||
|
||||
public sealed class StockMarketBalance
|
||||
|
||||
@@ -97,6 +97,23 @@ public static class DataValidator
|
||||
break;
|
||||
}
|
||||
}
|
||||
// successori (ADR 0020): stessa categoria, introdotti dopo, senza richiedere la linea elettrificata in più
|
||||
var vehicleById = new Dictionary<string, VehicleDef>(StringComparer.Ordinal);
|
||||
foreach (var v in d.Vehicles) vehicleById.TryAdd(v.Id, v);
|
||||
bool Electric(VehicleDef v) => v.Traction is { } tr && d.Eras.Tractions.Any(x => x.Id == tr && x.NeedsElectrification);
|
||||
foreach (var v in d.Vehicles)
|
||||
{
|
||||
if (v.Successor is not { } sid) continue;
|
||||
if (!vehicleById.TryGetValue(sid, out var next))
|
||||
{
|
||||
Err("vehicles.json", $"{v.Id}: successore sconosciuto «{sid}»");
|
||||
continue;
|
||||
}
|
||||
if (next.Kind != v.Kind || next.WagonType != v.WagonType || next.Class != v.Class)
|
||||
Err("vehicles.json", $"{v.Id}: il successore «{sid}» non è della stessa categoria");
|
||||
if (next.EraFrom <= v.EraFrom) Err("vehicles.json", $"{v.Id}: il successore «{sid}» deve essere introdotto dopo");
|
||||
if (Electric(next) && !Electric(v)) Err("vehicles.json", $"{v.Id}: il successore «{sid}» richiede la linea elettrificata");
|
||||
}
|
||||
foreach (var g in d.Goods)
|
||||
{
|
||||
bool carried = d.Vehicles.Any(v => v.Kind == VehicleKind.Wagon && v.WagonType == g.Wagon && (v.Goods?.Contains(g.Id) ?? false));
|
||||
@@ -136,6 +153,22 @@ public static class DataValidator
|
||||
if (!levels.SequenceEqual(Enumerable.Range(1, levels.Count))) Err("tiers.json", "i livelli devono essere 1, 2, 3, 4, 5 in ordine");
|
||||
Increasing("tiers.json", "requirements.netWorth", d.Tiers.Tiers.Select(t => (double)t.Requirements.NetWorth), errors, strictFromSecond: true);
|
||||
if (!d.Tiers.RatingScale.SequenceEqual(Enum.GetValues<CreditRating>())) Err("tiers.json", "ratingScale deve elencare i rating da AAA a D");
|
||||
if (!(d.Tiers.RatingProgressSteps > 0)) Err("tiers.json", "ratingProgressSteps deve essere positivo");
|
||||
// gli sblocchi restano acquisiti salendo (ADR 0011): notizie, rifiuti e pannello lo presumono (ADR 0018)
|
||||
var unlocks = d.Tiers.Tiers.Select(t => t.Unlocks).ToList();
|
||||
for (int i = 1; i < unlocks.Count; i++)
|
||||
{
|
||||
var (prev, cur) = (unlocks[i - 1], unlocks[i]);
|
||||
if (cur.MaxLoanFactor < prev.MaxLoanFactor) Err("tiers.json", $"unlocks.maxLoanFactor non può scendere dal livello {i} al livello {i + 1}");
|
||||
foreach (var (name, had, has) in new[]
|
||||
{
|
||||
("trading", prev.Trading, cur.Trading), ("buyIndustry", prev.BuyIndustry, cur.BuyIndustry), ("ipo", prev.Ipo, cur.Ipo),
|
||||
("hostileTakeover", prev.HostileTakeover, cur.HostileTakeover), ("concessions", prev.Concessions, cur.Concessions),
|
||||
})
|
||||
{
|
||||
if (had && !has) Err("tiers.json", $"unlocks.{name} non può tornare falso dal livello {i} al livello {i + 1}");
|
||||
}
|
||||
}
|
||||
|
||||
// --- difficoltà
|
||||
Unique("difficulty.json", d.Difficulty.Presets.Select(p => p.Id), errors);
|
||||
@@ -170,10 +203,24 @@ public static class DataValidator
|
||||
if (b.Map.Industries.InitialLevels.Length != 2 || b.Map.Industries.InitialLevels[0] > b.Map.Industries.InitialLevels[1])
|
||||
Err("balance.json", "map.industries.initialLevels deve essere [min, max]");
|
||||
RequireKeys("balance.json", "industry.footprintCells", b.Industry.FootprintCells.Keys, SizeKeys, errors);
|
||||
if (b.Industry.Outlook.PartnersPerGood < 1) Err("balance.json", "industry.outlook.partnersPerGood deve essere almeno 1");
|
||||
if (b.Industry.Outlook.WorkforceSources < 1) Err("balance.json", "industry.outlook.workforceSources deve essere almeno 1");
|
||||
RequireKeys("balance.json", "tariffs.classMultipliers", b.Tariffs.ClassMultipliers.Keys, ["worker", "staff"], errors);
|
||||
RequireKeys("balance.json", "finance.ratingSpreads", b.Finance.RatingSpreads.Keys, Enum.GetNames<CreditRating>(), errors);
|
||||
if (b.Finance.RatingByScore.Length != 9) Err("balance.json", "finance.ratingByScore deve avere 9 soglie (AAA … C)");
|
||||
Increasing("balance.json", "finance.ratingByScore (decrescente)", Enumerable.Reverse(b.Finance.RatingByScore), errors);
|
||||
if (b.Finance.IncomeMonths < 1 || b.Finance.IncomeMonths > 120) Err("balance.json", "finance.incomeMonths deve stare tra 1 e 120");
|
||||
if (b.Finance.IncomeYears < 1 || b.Finance.IncomeYears > 100) Err("balance.json", "finance.incomeYears deve stare tra 1 e 100");
|
||||
if (b.Finance.RatingMinRevenueMonths < 1 || b.Finance.RatingMinRevenueMonths > b.Finance.IncomeMonths)
|
||||
Err("balance.json", "finance.ratingMinRevenueMonths deve stare tra 1 e finance.incomeMonths");
|
||||
if (b.Finance.NegativeCashNoticeDays < 1) Err("balance.json", "finance.negativeCashNoticeDays deve essere almeno 1");
|
||||
if (b.Finance.ProfitMarginWeight <= 0 || b.Finance.LeverageWeight <= 0) Err("balance.json", "finance.profitMarginWeight e finance.leverageWeight devono essere positivi");
|
||||
for (int i = 0; i < b.Finance.BankruptcyWarningDaysLeft.Length; i++)
|
||||
{
|
||||
if (b.Finance.BankruptcyWarningDaysLeft[i] < 1) Err("balance.json", "finance.bankruptcyWarningDaysLeft: i giorni devono essere almeno 1");
|
||||
if (i > 0 && b.Finance.BankruptcyWarningDaysLeft[i] >= b.Finance.BankruptcyWarningDaysLeft[i - 1])
|
||||
Err("balance.json", "finance.bankruptcyWarningDaysLeft deve essere strettamente decrescente");
|
||||
}
|
||||
RequireKeys("balance.json", "industryMaintenance.budgets", b.IndustryMaintenance.Budgets.Keys, ["none", "base", "high"], errors);
|
||||
if (b.IndustryMaintenance.BreakdownDays.Length != 2) Err("balance.json", "industryMaintenance.breakdownDays deve essere [min, max]");
|
||||
if (b.Growth.MaxLevel > 5 || b.Growth.MaxLevel < 1) Err("balance.json", "growth.maxLevel deve stare tra 1 e 5");
|
||||
@@ -191,6 +238,10 @@ public static class DataValidator
|
||||
}
|
||||
RequireKeys("construction.json", "crews.metersPerDay", c.Crews.MetersPerDay.Keys, WorkKeys, errors);
|
||||
if (c.Crews.CrewsByTier.Length != 5) Err("construction.json", "crews.crewsByTier deve avere 5 valori");
|
||||
// le squadre per livello stanno in due file: il cantiere usa construction.json, il pannello della scalata
|
||||
// le mostra tra gli sblocchi; devono coincidere (ADR 0018)
|
||||
else if (!d.Tiers.Tiers.Select(t => t.Unlocks.Crews).SequenceEqual(c.Crews.CrewsByTier))
|
||||
Err("tiers.json", "unlocks.crews deve coincidere con crews.crewsByTier di construction.json");
|
||||
RequireKeys("construction.json", "costs.depotBySize", c.Costs.DepotBySize.Keys, SizeKeys, errors);
|
||||
foreach (string k in c.Costs.TerrainModifiers.Keys)
|
||||
{
|
||||
@@ -217,10 +268,20 @@ public static class DataValidator
|
||||
{
|
||||
if (i.Effect == InterventionEffect.Repair && i.RestoreTo is null) Err("maintenance.json", $"{i.Id}: una riparazione richiede restoreTo");
|
||||
}
|
||||
if (m.Interventions.Count(i => i.Effect == InterventionEffect.Renew) != 1)
|
||||
Err("maintenance.json", "serve esattamente un intervento con effetto «renew» (rinnovo dei veicoli superati)");
|
||||
RequireKeys("maintenance.json", "depots.stallsBySize", m.Depots.StallsBySize.Keys, SizeKeys, errors);
|
||||
|
||||
// --- IA, contratti, regioni
|
||||
Unique("ai.json", d.Ai.Personalities.Select(p => p.Id), errors);
|
||||
// personalità delle IA e dei bot giocatore (ADR 0025) in un solo spazio di nomi
|
||||
Unique("ai.json", d.Ai.Personalities.Select(p => p.Id).Concat(d.Ai.Bots.Select(p => p.Id)), errors);
|
||||
if (d.Ai.Trading.MinMargin <= 2 * d.Ai.Trading.PriceSlack)
|
||||
Err("ai.json", "trading.minMargin deve superare il doppio di trading.priceSlack (ogni unità scambiata resta in margine)");
|
||||
// i limiti dei singoli valori di taratura (planning, market.world) sono negli schemi (ADR 0025)
|
||||
if (d.Ai.Planning.CandidateMinDistanceKm >= d.Ai.Planning.CandidateMaxDistanceKm)
|
||||
Err("ai.json", "planning.candidateMinDistanceKm deve essere minore di candidateMaxDistanceKm");
|
||||
if (d.Balance.Market.World.ShockMin > d.Balance.Market.World.ShockMax)
|
||||
Err("balance.json", "market.world.shockMin non può superare shockMax");
|
||||
Unique("contracts.json", d.Contracts.Templates.Select(t => t.Id), errors);
|
||||
foreach (var t in d.Contracts.Templates)
|
||||
{
|
||||
|
||||
@@ -28,7 +28,8 @@ public enum IronmanRule { No, Optional, Yes }
|
||||
|
||||
public enum DepletionRate { Slow, Normal, Fast }
|
||||
|
||||
public enum InterventionEffect { Inspection, Service, Overhaul, Repair, Replace }
|
||||
/// <summary>Effetto di un intervento; Renew sostituisce i veicoli superati con il successore consigliato (ADR 0020).</summary>
|
||||
public enum InterventionEffect { Inspection, Service, Overhaul, Repair, Replace, Renew }
|
||||
|
||||
public enum MaintenancePolicy { Economy, Standard, Thorough }
|
||||
|
||||
|
||||
@@ -23,6 +23,8 @@ public sealed class GameData
|
||||
public required IReadOnlyList<GoodDef> Goods { get; init; }
|
||||
public required IReadOnlyList<IndustryDef> Industries { get; init; }
|
||||
public required IReadOnlyList<VehicleDef> Vehicles { get; init; }
|
||||
/// <summary>Obsolescenza dei modelli superati (vehicles.json, ADR 0020).</summary>
|
||||
public required ObsolescenceParams Obsolescence { get; init; }
|
||||
public required ErasFile Eras { get; init; }
|
||||
public required TiersFile Tiers { get; init; }
|
||||
public required BalanceFile Balance { get; init; }
|
||||
@@ -114,6 +116,7 @@ public sealed class GameData
|
||||
Goods = goods!.Goods,
|
||||
Industries = industries!.Industries,
|
||||
Vehicles = vehicles!.Vehicles,
|
||||
Obsolescence = vehicles.Obsolescence,
|
||||
Eras = eras!,
|
||||
Tiers = tiers!,
|
||||
Balance = balance!,
|
||||
@@ -197,6 +200,7 @@ public sealed class GameData
|
||||
_vehicleIndex[def.Id] = i;
|
||||
def.GoodIndices = def.Goods?.Select(g => _goodIndex[g]).ToArray() ?? [];
|
||||
}
|
||||
foreach (var def in Vehicles) def.SuccessorDef = def.Successor is { } succ ? Vehicles[_vehicleIndex[succ]] : null;
|
||||
for (int i = 0; i < Eras.TrackClasses.Count; i++) Eras.TrackClasses[i].Index = i;
|
||||
for (int i = 0; i < Events.Events.Count; i++)
|
||||
{
|
||||
|
||||
@@ -8,6 +8,11 @@ public sealed class TiersFile
|
||||
[JsonPropertyName("$schema")] public string? Schema { get; init; }
|
||||
public required int Version { get; init; }
|
||||
public required List<CreditRating> RatingScale { get; init; }
|
||||
/// <summary>
|
||||
/// Gradini di rating sotto quello richiesto a cui l'avanzamento del requisito vale zero (ADR 0018):
|
||||
/// la frazione è 1 − gradini mancanti / questo valore, limitata tra 0 e 1.
|
||||
/// </summary>
|
||||
public required double RatingProgressSteps { get; init; }
|
||||
public required List<TierDef> Tiers { get; init; }
|
||||
}
|
||||
|
||||
|
||||
@@ -7,9 +7,24 @@ public sealed class VehiclesFile
|
||||
{
|
||||
[JsonPropertyName("$schema")] public string? Schema { get; init; }
|
||||
public required int Version { get; init; }
|
||||
/// <summary>Parametri dell'obsolescenza dei modelli superati (F6, ADR 0020).</summary>
|
||||
public required ObsolescenceParams Obsolescence { get; init; }
|
||||
public required List<VehicleDef> Vehicles { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Obsolescenza di un modello superato da un successore (ADR 0020): dal 1° gennaio dell'anno in cui il
|
||||
/// successore entra in produzione il valore perde subito <see cref="ImmediateValueLoss"/> e poi si
|
||||
/// ammortizza <see cref="DepreciationSpeed"/> volte più in fretta; gli interventi di manutenzione
|
||||
/// costano <see cref="MaintenanceCostFactor"/> volte tanto.
|
||||
/// </summary>
|
||||
public sealed class ObsolescenceParams
|
||||
{
|
||||
public required double ImmediateValueLoss { get; init; }
|
||||
public required double DepreciationSpeed { get; init; }
|
||||
public required double MaintenanceCostFactor { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Modello di veicolo: locomotiva, carro merci o carrozza.</summary>
|
||||
public sealed class VehicleDef
|
||||
{
|
||||
@@ -17,8 +32,15 @@ public sealed class VehicleDef
|
||||
public required VehicleKind Kind { get; init; }
|
||||
[JsonPropertyName("name_it")] public required string NameIt { get; init; }
|
||||
[JsonPropertyName("name_en")] public required string NameEn { get; init; }
|
||||
/// <summary>Anno di introduzione: da quest'anno il modello si può comprare.</summary>
|
||||
public required int EraFrom { get; init; }
|
||||
/// <summary>Ultimo anno di produzione (assente: sempre in produzione); dall'anno dopo non si compra più.</summary>
|
||||
public int? EraTo { get; init; }
|
||||
/// <summary>
|
||||
/// Modello che lo sostituisce (stessa categoria, introdotto dopo): dall'anno di introduzione del
|
||||
/// successore questo modello è «superato» (ADR 0020).
|
||||
/// </summary>
|
||||
public string? Successor { get; init; }
|
||||
public double PowerKw { get; init; }
|
||||
public double TractiveEffortKn { get; init; }
|
||||
public required double MaxSpeedKmh { get; init; }
|
||||
@@ -39,6 +61,8 @@ public sealed class VehicleDef
|
||||
public PaxClass? Class { get; init; }
|
||||
|
||||
[JsonIgnore] public int Index { get; internal set; }
|
||||
/// <summary>Successore risolto (null se il modello non ne ha).</summary>
|
||||
[JsonIgnore] public VehicleDef? SuccessorDef { get; internal set; }
|
||||
/// <summary>Indici dei beni trasportabili (carri).</summary>
|
||||
[JsonIgnore] public int[] GoodIndices { get; internal set; } = [];
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
namespace RailEnterprise.Core.Economy;
|
||||
|
||||
/// <summary>
|
||||
/// Requisiti di un livello per una compagnia: per ciascuno il valore attuale, la soglia, se è
|
||||
/// soddisfatto e la frazione raggiunta (0–1), più l'avanzamento complessivo (media delle tre frazioni).
|
||||
/// </summary>
|
||||
public sealed class RequirementProgress
|
||||
{
|
||||
public required int Level { get; init; }
|
||||
public required Money NetWorth { get; init; }
|
||||
public required Money NetWorthRequired { get; init; }
|
||||
public required double NetWorthFraction { get; init; }
|
||||
public required bool NetWorthMet { get; init; }
|
||||
public required int Towns { get; init; }
|
||||
public required int TownsRequired { get; init; }
|
||||
public required int TownPopulation { get; init; }
|
||||
public required double TownsFraction { get; init; }
|
||||
public required bool TownsMet { get; init; }
|
||||
public required CreditRating Rating { get; init; }
|
||||
public required CreditRating RatingRequired { get; init; }
|
||||
public required double RatingFraction { get; init; }
|
||||
public required bool RatingMet { get; init; }
|
||||
/// <summary>Media delle frazioni dei tre requisiti: 1 solo quando sono tutti soddisfatti.</summary>
|
||||
public required double Progress { get; init; }
|
||||
public bool AllMet => NetWorthMet && TownsMet && RatingMet;
|
||||
}
|
||||
|
||||
/// <summary>Un livello di tiers.json visto dalla compagnia: requisiti, se e quando è stato raggiunto, sblocchi.</summary>
|
||||
public sealed class TierOutlook
|
||||
{
|
||||
public required int Level { get; init; }
|
||||
public required string NameIt { get; init; }
|
||||
public required string NameEn { get; init; }
|
||||
public required TierRequirements Requirements { get; init; }
|
||||
public required bool Reached { get; init; }
|
||||
/// <summary>Giorno in cui è stato raggiunto (fondazione per il livello 1; −1 se non raggiunto o sconosciuto).</summary>
|
||||
public required long ReachedDay { get; init; }
|
||||
/// <summary>Sblocchi che il livello aggiunge al precedente (<see cref="Tiers.NewUnlocks"/>).</summary>
|
||||
public required List<TierUnlock> Unlocks { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Voce degli attivi non monetari dello stato patrimoniale.</summary>
|
||||
public readonly record struct AssetLine(AssetCategory Category, Money Value);
|
||||
|
||||
/// <summary>
|
||||
/// Stato patrimoniale della compagnia: attivi per voce (dal valore contabile del motore),
|
||||
/// partecipazioni, cassa; debiti (prestiti e scoperto di cassa). Il patrimonio netto è quello del
|
||||
/// motore (<see cref="Company.NetWorth"/>): Totale attivo − Totale debiti.
|
||||
/// </summary>
|
||||
public sealed class BalanceSheet
|
||||
{
|
||||
public required List<AssetLine> Assets { get; init; }
|
||||
/// <summary>Azioni di altre compagnie al prezzo di mercato.</summary>
|
||||
public required Money Portfolio { get; init; }
|
||||
/// <summary>Cassa positiva (lo scoperto va tra i debiti).</summary>
|
||||
public required Money Cash { get; init; }
|
||||
public required Money TotalAssets { get; init; }
|
||||
public required Money Loans { get; init; }
|
||||
/// <summary>Tasso medio dei prestiti pesato sul residuo (0 senza prestiti).</summary>
|
||||
public required double LoansRate { get; init; }
|
||||
/// <summary>Scoperto di cassa (cassa negativa), tra gli altri debiti.</summary>
|
||||
public required Money Overdraft { get; init; }
|
||||
public required Money TotalLiabilities { get; init; }
|
||||
public required Money NetWorth { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Righe del conto economico del pannello: raggruppano le voci del registro.</summary>
|
||||
public enum IncomeLineKind : byte
|
||||
{
|
||||
/// <summary>Tariffe passeggeri e noli merci.</summary>
|
||||
Fares = 0,
|
||||
/// <summary>Commercio in proprio, contratti, industrie possedute, controllate, dividendi incassati.</summary>
|
||||
OtherIncome = 1,
|
||||
/// <summary>Costi d'esercizio (treni, stazioni e depositi), salari, penali, dazi, magazzini.</summary>
|
||||
OperatingCosts = 2,
|
||||
/// <summary>Manutenzione dei binari e della flotta.</summary>
|
||||
Maintenance = 3,
|
||||
Interest = 4,
|
||||
}
|
||||
|
||||
public readonly record struct IncomeLine(IncomeLineKind Kind, Money Value);
|
||||
|
||||
/// <summary>Conto economico di un anno (le righe sommano esattamente all'utile operativo del motore).</summary>
|
||||
public sealed class IncomeStatement
|
||||
{
|
||||
public required int Year { get; init; }
|
||||
/// <summary>Anno in corso (fino a oggi) invece dell'ultimo anno chiuso.</summary>
|
||||
public required bool Partial { get; init; }
|
||||
public required List<IncomeLine> Lines { get; init; }
|
||||
public required Money Profit { get; init; }
|
||||
}
|
||||
|
||||
public readonly record struct LoanOutlook(LoanId Id, Money Remaining, double AnnualRate, int MonthsLeft);
|
||||
|
||||
/// <summary>Patrimonio netto a un giorno della partita.</summary>
|
||||
public readonly record struct NetWorthPoint(long Day, Money Value);
|
||||
|
||||
public sealed class ClimbOutlookReport
|
||||
{
|
||||
public required long Day { get; init; }
|
||||
public required CompanyId Company { get; init; }
|
||||
public required long FoundedDay { get; init; }
|
||||
/// <summary>Capitale iniziale della difficoltà (quello del giocatore).</summary>
|
||||
public required Money InitialCapital { get; init; }
|
||||
public required int Tier { get; init; }
|
||||
/// <summary>Livello successivo (0 all'ultimo livello).</summary>
|
||||
public required int NextTier { get; init; }
|
||||
public required List<TierOutlook> Tiers { get; init; }
|
||||
/// <summary>Requisiti del livello successivo (null all'ultimo livello).</summary>
|
||||
public required RequirementProgress? Next { get; init; }
|
||||
public required BalanceSheet Balance { get; init; }
|
||||
public required IncomeStatement Income { get; init; }
|
||||
public required List<LoanOutlook> Loans { get; init; }
|
||||
public required Money MaxLoan { get; init; }
|
||||
public required Money LoanAvailable { get; init; }
|
||||
public required double NewLoanRate { get; init; }
|
||||
/// <summary>In bancarotta o in amministrazione controllata i prestiti non si possono chiedere (come in <see cref="FinanceOutlook"/>).</summary>
|
||||
public required bool LoansAllowed { get; init; }
|
||||
/// <summary>Patrimonio netto: fondazione, fine di ogni anno dello storico, oggi.</summary>
|
||||
public required List<NetWorthPoint> History { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Quadro della scalata per il pannello «La tua scalata» (ADR 0018): pura funzione del mondo, come
|
||||
/// <see cref="MarketOutlook"/>. Livelli e sblocchi da tiers.json, requisiti del prossimo livello con
|
||||
/// l'avanzamento, stato patrimoniale dalle voci del valore contabile del motore, conto economico
|
||||
/// dell'ultimo anno, prestiti e storico del patrimonio netto (lo storico annuale della Cronaca).
|
||||
/// </summary>
|
||||
public static class ClimbOutlook
|
||||
{
|
||||
public static ClimbOutlookReport Build(World w, CompanyId company)
|
||||
{
|
||||
var c = w.Company(company);
|
||||
var tiers = w.Data.Tiers.Tiers;
|
||||
var list = new List<TierOutlook>(tiers.Count);
|
||||
foreach (var t in tiers)
|
||||
{
|
||||
list.Add(new TierOutlook
|
||||
{
|
||||
Level = t.Level, NameIt = t.NameIt, NameEn = t.NameEn, Requirements = t.Requirements,
|
||||
Reached = c.Tier >= t.Level,
|
||||
ReachedDay = t.Level <= 1 ? c.FoundedDay : c.Tier >= t.Level ? c.TierReachedDay[Math.Min(t.Level, c.TierReachedDay.Length) - 1] : -1,
|
||||
Unlocks = Simulation.Systems.Tiers.NewUnlocks(w, c, t.Level),
|
||||
});
|
||||
}
|
||||
var max = FinanceSystem.MaxLoan(w, c);
|
||||
return new ClimbOutlookReport
|
||||
{
|
||||
Day = w.Clock.Day,
|
||||
Company = c.Id,
|
||||
FoundedDay = c.FoundedDay,
|
||||
InitialCapital = new Money(w.Difficulty.InitialCapital),
|
||||
Tier = c.Tier,
|
||||
NextTier = c.Tier < tiers.Count ? tiers[c.Tier].Level : 0,
|
||||
Tiers = list,
|
||||
Next = c.Tier < tiers.Count ? Requirements(w, c, tiers[c.Tier]) : null,
|
||||
Balance = Balance(c),
|
||||
Income = Income(w, c),
|
||||
Loans = c.Loans.Select(l => new LoanOutlook(l.Id, l.Remaining, l.AnnualRate, l.MonthsLeft)).ToList(),
|
||||
MaxLoan = max,
|
||||
LoanAvailable = Money.Max(Money.Zero, max - c.Debt),
|
||||
NewLoanRate = FinanceSystem.LoanRate(w, c),
|
||||
LoansAllowed = !c.Receivership && !c.Bankrupt,
|
||||
History = History(w, c),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Requisiti di un livello per la compagnia, con gli stessi confronti di <see cref="Simulation.Systems.Tiers.Meets"/>.
|
||||
/// Frazioni: patrimonio / soglia e città / città richieste (limitate a 1; 1 se la soglia è zero); per il
|
||||
/// rating 1 − gradini mancanti / <see cref="TiersFile.RatingProgressSteps"/> (limitata tra 0 e 1).
|
||||
/// L'avanzamento è la loro media, sotto 1 finché un requisito manca (<see cref="ProgressCap"/>).
|
||||
/// </summary>
|
||||
public static RequirementProgress Requirements(World w, Company c, TierDef tier)
|
||||
{
|
||||
var req = tier.Requirements;
|
||||
int towns = Simulation.Systems.Tiers.ConnectedTowns(w, c.Id, req.ConnectedTownsOver.Population);
|
||||
double worth = req.NetWorth <= 0 ? 1 : DMath.Clamp((double)c.NetWorth.Cents / req.NetWorth, 0, 1);
|
||||
double townsFraction = req.ConnectedTownsOver.Count <= 0 ? 1 : DMath.Clamp((double)towns / req.ConnectedTownsOver.Count, 0, 1);
|
||||
double rating = RatingFraction(w, c.Rating, req.CreditRating);
|
||||
bool worthMet = c.NetWorth.Cents >= req.NetWorth, townsMet = towns >= req.ConnectedTownsOver.Count, ratingMet = c.Rating <= req.CreditRating;
|
||||
double progress = (worth + townsFraction + rating) / 3;
|
||||
if (!(worthMet && townsMet && ratingMet)) progress = Math.Min(progress, ProgressCap);
|
||||
return new RequirementProgress
|
||||
{
|
||||
Level = tier.Level,
|
||||
NetWorth = c.NetWorth, NetWorthRequired = new Money(req.NetWorth), NetWorthFraction = worth, NetWorthMet = worthMet,
|
||||
Towns = towns, TownsRequired = req.ConnectedTownsOver.Count, TownPopulation = req.ConnectedTownsOver.Population,
|
||||
TownsFraction = townsFraction, TownsMet = townsMet,
|
||||
Rating = c.Rating, RatingRequired = req.CreditRating, RatingFraction = rating, RatingMet = ratingMet,
|
||||
Progress = progress,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tetto dell'avanzamento finché un requisito manca: una frazione arrotondata a 1 non basta, il pieno
|
||||
/// arriva solo con tutti i requisiti soddisfatti. Non è un parametro di gioco (non cambia la promozione,
|
||||
/// che segue <see cref="Simulation.Systems.Tiers.Meets"/>): il client mostra le percentuali per difetto,
|
||||
/// quindi sotto il tetto legge al massimo «99%».
|
||||
/// </summary>
|
||||
public const double ProgressCap = 0.999;
|
||||
|
||||
/// <summary>
|
||||
/// Frazione del requisito di rating: 1 se soddisfatto, altrimenti 1 − gradini mancanti /
|
||||
/// ratingProgressSteps di tiers.json, limitata tra 0 e 1 (immagine 08: un gradino sotto vale il 60 %).
|
||||
/// </summary>
|
||||
public static double RatingFraction(World w, CreditRating current, CreditRating required)
|
||||
{
|
||||
if (current <= required) return 1;
|
||||
int missing = (int)current - (int)required;
|
||||
return DMath.Clamp(1 - missing / w.Data.Tiers.RatingProgressSteps, 0, 1);
|
||||
}
|
||||
|
||||
/// <summary>Stato patrimoniale dalle voci del motore: somma esattamente al patrimonio netto.</summary>
|
||||
public static BalanceSheet Balance(Company c)
|
||||
{
|
||||
var assets = new List<AssetLine>(AssetCategories.Count);
|
||||
for (int k = 0; k < AssetCategories.Count; k++) assets.Add(new AssetLine((AssetCategory)k, new Money(c.BookValues[k])));
|
||||
var cash = Money.Max(Money.Zero, c.Cash);
|
||||
var overdraft = Money.Max(Money.Zero, -c.Cash);
|
||||
var total = c.AssetBookValue + c.PortfolioValue + cash;
|
||||
var loans = c.Debt;
|
||||
double rate = 0;
|
||||
if (loans.Cents > 0)
|
||||
{
|
||||
double weighted = 0;
|
||||
foreach (var l in c.Loans) weighted += (double)l.Remaining.Cents * l.AnnualRate;
|
||||
rate = weighted / loans.Cents;
|
||||
}
|
||||
return new BalanceSheet
|
||||
{
|
||||
Assets = assets, Portfolio = c.PortfolioValue, Cash = cash, TotalAssets = total,
|
||||
Loans = loans, LoansRate = rate, Overdraft = overdraft, TotalLiabilities = loans + overdraft,
|
||||
NetWorth = total - loans - overdraft,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Conto economico dell'ultimo anno chiuso (o dell'anno in corso, per una compagnia fondata
|
||||
/// quest'anno): righe raggruppate dalle voci del registro; l'utile è <see cref="Company.OperatingProfit"/>.
|
||||
/// </summary>
|
||||
public static IncomeStatement Income(World w, Company c)
|
||||
{
|
||||
long yearStart = (long)(w.Clock.Year - w.Calendar.StartYear) * w.Calendar.DaysPerYear;
|
||||
bool closed = w.Clock.Year > w.Calendar.StartYear && c.FoundedDay < yearStart;
|
||||
var e = closed ? c.LastYearEntries : c.YearEntries;
|
||||
long Sum(params LedgerEntry[] keys)
|
||||
{
|
||||
long s = 0;
|
||||
foreach (var k in keys) s += e[(int)k];
|
||||
return s;
|
||||
}
|
||||
var lines = new List<IncomeLine>
|
||||
{
|
||||
new(IncomeLineKind.Fares, new Money(Sum(LedgerEntry.FreightRevenue, LedgerEntry.PassengerRevenue))),
|
||||
new(IncomeLineKind.OtherIncome, new Money(Sum(LedgerEntry.Trading, LedgerEntry.Contracts, LedgerEntry.Industries, LedgerEntry.Subsidiaries,
|
||||
LedgerEntry.DividendsReceived))),
|
||||
new(IncomeLineKind.OperatingCosts, new Money(Sum(LedgerEntry.RunningCosts, LedgerEntry.StationUpkeep, LedgerEntry.Wages, LedgerEntry.Penalties,
|
||||
LedgerEntry.Duties, LedgerEntry.Storage))),
|
||||
new(IncomeLineKind.Maintenance, new Money(Sum(LedgerEntry.TrackMaintenance, LedgerEntry.FleetMaintenance))),
|
||||
new(IncomeLineKind.Interest, new Money(Sum(LedgerEntry.Interest))),
|
||||
};
|
||||
return new IncomeStatement
|
||||
{
|
||||
Year = closed ? w.Clock.Year - 1 : w.Clock.Year,
|
||||
Partial = !closed,
|
||||
Lines = lines,
|
||||
Profit = new Money(Company.OperatingProfit(e)),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Patrimonio netto nel tempo: il capitale iniziale alla fondazione, la fotografia di fine anno
|
||||
/// dello storico (al primo giorno dell'anno dopo) e il valore di oggi. La fotografia del primo giorno
|
||||
/// dell'anno in corso lascia il posto a oggi: un punto per anno di calendario, come l'immagine 08.
|
||||
/// </summary>
|
||||
public static List<NetWorthPoint> History(World w, Company c)
|
||||
{
|
||||
var points = new List<NetWorthPoint> { new(c.FoundedDay, new Money(w.Difficulty.InitialCapital)) };
|
||||
long today = w.Clock.Day;
|
||||
long yearStart = (long)(w.Clock.Year - w.Calendar.StartYear) * w.Calendar.DaysPerYear;
|
||||
foreach (var y in c.History)
|
||||
{
|
||||
long day = (long)(y.Year + 1 - w.Calendar.StartYear) * w.Calendar.DaysPerYear;
|
||||
if (day <= points[^1].Day || day >= yearStart) continue;
|
||||
points.Add(new NetWorthPoint(day, new Money(y.NetWorthCents)));
|
||||
}
|
||||
if (today > points[^1].Day) points.Add(new NetWorthPoint(today, c.NetWorth));
|
||||
else points[^1] = new NetWorthPoint(points[^1].Day, c.NetWorth);
|
||||
return points;
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,86 @@ public enum LedgerEntry : byte
|
||||
Industries = 19,
|
||||
/// <summary>Utili versati dalle compagnie controllate.</summary>
|
||||
Subsidiaries = 20,
|
||||
/// <summary>Esercizio dei binari di stazione e dei depositi (prima dentro <see cref="RunningCosts"/>, ADR 0019).</summary>
|
||||
StationUpkeep = 21,
|
||||
/// <summary>Giacenza della merce nei magazzini della compagnia (prima dentro <see cref="Trading"/>, ADR 0019).</summary>
|
||||
Storage = 22,
|
||||
/// <summary>Dazi sugli scambi in proprio con gli hub (prima dentro <see cref="Trading"/>, ADR 0019).</summary>
|
||||
Duties = 23,
|
||||
/// <summary>Dividendi incassati dalle azioni di altre compagnie (ADR 0019); <see cref="Dividends"/> resta per quelli pagati.</summary>
|
||||
DividendsReceived = 24,
|
||||
}
|
||||
|
||||
/// <summary>Sezione del conto economico di una voce del registro (ADR 0019).</summary>
|
||||
public enum IncomeSection : byte
|
||||
{
|
||||
/// <summary>Ricavi d'esercizio: entrano nell'utile operativo.</summary>
|
||||
Revenue = 0,
|
||||
/// <summary>Costi d'esercizio: entrano nell'utile operativo.</summary>
|
||||
Cost = 1,
|
||||
/// <summary>Investimenti e finanziamenti: muovono la cassa ma non l'utile operativo.</summary>
|
||||
Capital = 2,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Classificazione delle voci del registro (ADR 0019): unica fonte dell'utile operativo, dei ricavi del
|
||||
/// rating e delle righe del conto economico del pannello delle finanze.
|
||||
/// </summary>
|
||||
public static class LedgerEntries
|
||||
{
|
||||
/// <summary>Voci nell'ordine del conto economico: ricavi, costi, investimenti e finanziamenti.</summary>
|
||||
public static readonly LedgerEntry[] Ordered =
|
||||
[
|
||||
LedgerEntry.FreightRevenue, LedgerEntry.PassengerRevenue, LedgerEntry.Trading, LedgerEntry.Contracts,
|
||||
LedgerEntry.Industries, LedgerEntry.Subsidiaries, LedgerEntry.DividendsReceived,
|
||||
LedgerEntry.RunningCosts, LedgerEntry.StationUpkeep, LedgerEntry.FleetMaintenance, LedgerEntry.TrackMaintenance,
|
||||
LedgerEntry.Wages, LedgerEntry.Interest, LedgerEntry.Duties, LedgerEntry.Storage, LedgerEntry.Penalties,
|
||||
LedgerEntry.Construction, LedgerEntry.VehiclePurchase, LedgerEntry.VehicleSale, LedgerEntry.IndustryPurchase,
|
||||
LedgerEntry.LoanTaken, LedgerEntry.LoanRepaid, LedgerEntry.Shares, LedgerEntry.Dividends, LedgerEntry.Other,
|
||||
];
|
||||
|
||||
public static IncomeSection Section(LedgerEntry e) => e switch
|
||||
{
|
||||
LedgerEntry.FreightRevenue or LedgerEntry.PassengerRevenue or LedgerEntry.Trading or LedgerEntry.Contracts
|
||||
or LedgerEntry.Industries or LedgerEntry.Subsidiaries or LedgerEntry.DividendsReceived => IncomeSection.Revenue,
|
||||
LedgerEntry.RunningCosts or LedgerEntry.StationUpkeep or LedgerEntry.FleetMaintenance or LedgerEntry.TrackMaintenance
|
||||
or LedgerEntry.Wages or LedgerEntry.Interest or LedgerEntry.Duties or LedgerEntry.Storage or LedgerEntry.Penalties => IncomeSection.Cost,
|
||||
_ => IncomeSection.Capital,
|
||||
};
|
||||
|
||||
/// <summary>Vero per le voci che entrano nell'utile operativo (ricavi e costi d'esercizio).</summary>
|
||||
public static bool Operating(LedgerEntry e) => Section(e) != IncomeSection.Capital;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Movimenti per voce di un mese o di un anno chiuso (ADR 0019): <see cref="Month"/> 1–12 per un mese,
|
||||
/// 0 per un anno intero.
|
||||
/// </summary>
|
||||
public sealed class IncomeRecord
|
||||
{
|
||||
public required int Year { get; init; }
|
||||
public required int Month { get; init; }
|
||||
public required long[] Entries { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Voci dello stato patrimoniale per gli attivi non monetari (ADR 0018).</summary>
|
||||
public enum AssetCategory : byte
|
||||
{
|
||||
/// <summary>Binari e opere (ponti, gallerie), ammortizzati.</summary>
|
||||
Track = 0,
|
||||
/// <summary>Stazioni e depositi, al costo.</summary>
|
||||
Stations = 1,
|
||||
/// <summary>Veicoli, ammortizzati.</summary>
|
||||
Vehicles = 2,
|
||||
/// <summary>Industrie possedute: impianti e cassa dell'impresa.</summary>
|
||||
Industries = 3,
|
||||
/// <summary>Merce propria in magazzino e in viaggio, al prezzo globale.</summary>
|
||||
Goods = 4,
|
||||
}
|
||||
|
||||
public static class AssetCategories
|
||||
{
|
||||
public const int Count = 5;
|
||||
}
|
||||
|
||||
/// <summary>Prestito con rata costante (ammortamento alla francese).</summary>
|
||||
@@ -45,7 +125,7 @@ public sealed class Loan
|
||||
/// <summary>Compagnia ferroviaria (giocatore o IA).</summary>
|
||||
public sealed class Company
|
||||
{
|
||||
public const int EntryCount = 21;
|
||||
public const int EntryCount = 25;
|
||||
|
||||
public required CompanyId Id { get; init; }
|
||||
public required string Name { get; set; }
|
||||
@@ -77,8 +157,44 @@ public sealed class Company
|
||||
/// <summary>Movimenti dell'anno precedente per voce (per rating e borsa).</summary>
|
||||
public long[] LastYearEntries { get; } = new long[EntryCount];
|
||||
|
||||
/// <summary>Valore contabile degli attivi non monetari (binari, stazioni, veicoli), aggiornato mensilmente.</summary>
|
||||
public Money AssetBookValue { get; set; }
|
||||
/// <summary>Mesi chiusi per voce, dal più vecchio (al massimo finance.incomeMonths, ADR 0019).</summary>
|
||||
public List<IncomeRecord> IncomeMonths { get; } = [];
|
||||
|
||||
/// <summary>Anni chiusi per voce, dal più vecchio (al massimo finance.incomeYears, ADR 0019).</summary>
|
||||
public List<IncomeRecord> IncomeYears { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Misure dell'ultimo calcolo del rating (ADR 0019): margine = utile operativo / ricavi dei mesi della
|
||||
/// finestra, leva = debiti / patrimonio netto (+∞ con patrimonio non positivo e debiti), punteggio
|
||||
/// pesato e numero di mesi della finestra (0 prima del primo calcolo).
|
||||
/// </summary>
|
||||
public double RatingMargin { get; set; }
|
||||
public double RatingLeverage { get; set; }
|
||||
public double RatingScore { get; set; }
|
||||
public int RatingMonths { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Valore contabile degli attivi non monetari per voce (<see cref="AssetCategory"/>, centesimi),
|
||||
/// aggiornato ogni mese da <c>FinanceSystem.UpdateBookValues</c> (ADR 0018).
|
||||
/// </summary>
|
||||
public long[] BookValues { get; } = new long[AssetCategories.Count];
|
||||
|
||||
/// <summary>Valore contabile degli attivi non monetari: somma delle voci di <see cref="BookValues"/>.</summary>
|
||||
public Money AssetBookValue
|
||||
{
|
||||
get
|
||||
{
|
||||
long sum = 0;
|
||||
foreach (long v in BookValues) sum += v;
|
||||
return new Money(sum);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Giorno in cui la compagnia ha raggiunto ciascun livello (indice livello − 1; −1 se non
|
||||
/// raggiunto o sconosciuto). Il livello 1 non si annota: vale dalla fondazione (ADR 0018).
|
||||
/// </summary>
|
||||
public long[] TierReachedDay { get; } = [-1, -1, -1, -1, -1];
|
||||
|
||||
public Money Debt
|
||||
{
|
||||
@@ -164,20 +280,41 @@ public sealed class Company
|
||||
/// <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 dei movimenti indicati: somma delle voci di ricavo e di costo d'esercizio
|
||||
/// (<see cref="LedgerEntries.Operating"/>), esclusi prestiti, investimenti e capitale.
|
||||
/// </summary>
|
||||
public static long OperatingProfit(long[] entries)
|
||||
{
|
||||
long revenue = entries[(int)LedgerEntry.FreightRevenue] + entries[(int)LedgerEntry.PassengerRevenue]
|
||||
+ entries[(int)LedgerEntry.Trading] + entries[(int)LedgerEntry.Contracts]
|
||||
+ entries[(int)LedgerEntry.Industries] + entries[(int)LedgerEntry.Subsidiaries];
|
||||
long costs = entries[(int)LedgerEntry.RunningCosts] + entries[(int)LedgerEntry.TrackMaintenance]
|
||||
+ entries[(int)LedgerEntry.FleetMaintenance] + entries[(int)LedgerEntry.Wages]
|
||||
+ entries[(int)LedgerEntry.Interest] + entries[(int)LedgerEntry.Penalties];
|
||||
return revenue + costs; // i costi sono già negativi
|
||||
long sum = 0;
|
||||
for (int i = 0; i < entries.Length && i < EntryCount; i++)
|
||||
{
|
||||
if (LedgerEntries.Operating((LedgerEntry)i)) sum += entries[i]; // i costi sono già negativi
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
public static long Revenue(long[] entries) =>
|
||||
entries[(int)LedgerEntry.FreightRevenue] + entries[(int)LedgerEntry.PassengerRevenue]
|
||||
+ Math.Max(0, entries[(int)LedgerEntry.Trading]) + Math.Max(0, entries[(int)LedgerEntry.Contracts])
|
||||
+ Math.Max(0, entries[(int)LedgerEntry.Industries]) + Math.Max(0, entries[(int)LedgerEntry.Subsidiaries]);
|
||||
/// <summary>
|
||||
/// Ricavi dei trasporti: tariffe merci e passeggeri e contratti con le industrie (se positivi). Misura la
|
||||
/// quota dei trasporti dei nuovi concorrenti (12.1), senza commercio in proprio, industrie, controllate
|
||||
/// e dividendi incassati, che non sono trasporto.
|
||||
/// </summary>
|
||||
public static long TransportRevenue(long[] entries) =>
|
||||
entries[(int)LedgerEntry.FreightRevenue] + entries[(int)LedgerEntry.PassengerRevenue] + Math.Max(0, entries[(int)LedgerEntry.Contracts]);
|
||||
|
||||
/// <summary>
|
||||
/// Ricavi d'esercizio: tariffe merci e passeggeri come sono, le altre voci di ricavo solo se positive
|
||||
/// (commercio, contratti, industrie, controllate, dividendi incassati).
|
||||
/// </summary>
|
||||
public static long Revenue(long[] entries)
|
||||
{
|
||||
long sum = entries[(int)LedgerEntry.FreightRevenue] + entries[(int)LedgerEntry.PassengerRevenue];
|
||||
for (int i = 0; i < entries.Length && i < EntryCount; i++)
|
||||
{
|
||||
var e = (LedgerEntry)i;
|
||||
if (e is LedgerEntry.FreightRevenue or LedgerEntry.PassengerRevenue || LedgerEntries.Section(e) != IncomeSection.Revenue) continue;
|
||||
sum += Math.Max(0, entries[i]);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
namespace RailEnterprise.Core.Economy;
|
||||
|
||||
/// <summary>
|
||||
/// Valore che il tooltip «perché» sa spiegare (ADR 0024). <see cref="ExplainTarget.A"/> e
|
||||
/// <see cref="ExplainTarget.B"/> dicono di quale oggetto: il significato è scritto accanto a ogni voce.
|
||||
/// </summary>
|
||||
public enum ExplainSubject : byte
|
||||
{
|
||||
None = 0,
|
||||
/// <summary>Prezzo globale di un bene (A = bene).</summary>
|
||||
GlobalPrice = 1,
|
||||
/// <summary>Prezzo locale di un bene in un'industria (A = bene, B = industria).</summary>
|
||||
LocalPrice = 2,
|
||||
/// <summary>Tariffa merci della tratta più lunga di una linea (A = linea, B = bene).</summary>
|
||||
FreightTariff = 3,
|
||||
/// <summary>Tariffa passeggeri della tratta più lunga di una linea (A = linea, B = 0 lavoratori, 1 personale).</summary>
|
||||
PassengerTariff = 4,
|
||||
/// <summary>Efficienza di un'industria (A = industria).</summary>
|
||||
IndustryEfficiency = 5,
|
||||
/// <summary>Punteggio di crescita del trimestre in corso di un'industria (A = industria).</summary>
|
||||
IndustryGrowth = 6,
|
||||
/// <summary>Crescita mensile di una città (A = città).</summary>
|
||||
TownGrowth = 7,
|
||||
/// <summary>Condizione di un treno con il rischio di guasto e la stima del pianificatore (A = treno).</summary>
|
||||
TrainCondition = 8,
|
||||
/// <summary>Rating della compagnia della sessione.</summary>
|
||||
Rating = 9,
|
||||
/// <summary>Avanzamento verso il prossimo livello della compagnia della sessione.</summary>
|
||||
TierProgress = 10,
|
||||
/// <summary>Valore di libro e rivendita di un veicolo (A = veicolo).</summary>
|
||||
VehicleValue = 11,
|
||||
/// <summary>Cassa della compagnia della sessione con i movimenti del mese.</summary>
|
||||
Cash = 12,
|
||||
}
|
||||
|
||||
/// <summary>Unità di un valore spiegato: dice al client come formattarlo, come nei pannelli.</summary>
|
||||
public enum ExplainUnit : byte
|
||||
{
|
||||
/// <summary>Numero puro (due decimali).</summary>
|
||||
Number = 0,
|
||||
/// <summary>Importo in centesimi (si mostra come Money).</summary>
|
||||
Money = 1,
|
||||
/// <summary>Prezzo per unità in centesimi frazionari.</summary>
|
||||
Price = 2,
|
||||
/// <summary>Frazione mostrata in percentuale.</summary>
|
||||
Percent = 3,
|
||||
/// <summary>Moltiplicatore («× 0,85»).</summary>
|
||||
Factor = 4,
|
||||
Km = 5,
|
||||
Days = 6,
|
||||
/// <summary>Quantità (unità, persone, città).</summary>
|
||||
Units = 7,
|
||||
/// <summary>Condizione 0–100.</summary>
|
||||
Condition = 8,
|
||||
Years = 9,
|
||||
/// <summary>Valore testuale: conta <see cref="ExplanationTerm.Text"/> (rating, nomi, anni).</summary>
|
||||
Text = 10,
|
||||
}
|
||||
|
||||
/// <summary>Bersaglio di una spiegazione: il valore e l'oggetto (−1 dove non serve).</summary>
|
||||
public readonly record struct ExplainTarget(ExplainSubject Subject, int A = -1, int B = -1);
|
||||
|
||||
/// <summary>
|
||||
/// Termine della formula: simbolo come compare nella formula, etichetta in italiano (chiave di traduzione
|
||||
/// del client), valore con l'unità e, per i valori testuali, il testo.
|
||||
/// </summary>
|
||||
public sealed record ExplanationTerm(string Symbol, string Label, double Value, ExplainUnit Unit, string Text = "");
|
||||
|
||||
/// <summary>
|
||||
/// Spiegazione di un valore calcolato dal motore (ADR 0024): titolo e nome dell'oggetto, valore con la sua
|
||||
/// unità (lo stesso numero del motore), formula in testo, termini con i valori di oggi e note. Titolo,
|
||||
/// formula, etichette e note sono testi italiani fissi che il client traduce; i numeri stanno nei termini.
|
||||
/// </summary>
|
||||
public sealed class Explanation
|
||||
{
|
||||
public required ExplainTarget Target { get; init; }
|
||||
public required long Day { get; init; }
|
||||
/// <summary>Falso se il bersaglio non esiste o non è visibile alla compagnia: titolo e note dicono perché.</summary>
|
||||
public required bool Available { get; init; }
|
||||
public required string Title { get; init; }
|
||||
/// <summary>Nome dell'oggetto (bene, industria, città, linea, treno, veicolo, compagnia); vuoto se non serve.</summary>
|
||||
public required string Name { get; init; }
|
||||
public required double Value { get; init; }
|
||||
public required ExplainUnit Unit { get; init; }
|
||||
/// <summary>Testo del valore quando non è un numero (il rating); vuoto altrimenti.</summary>
|
||||
public string ValueText { get; init; } = "";
|
||||
public required string Formula { get; init; }
|
||||
public required List<ExplanationTerm> Terms { get; init; }
|
||||
public required List<string> Notes { get; init; }
|
||||
|
||||
/// <summary>Termine con il simbolo indicato (il primo); null se manca.</summary>
|
||||
public ExplanationTerm? Term(string symbol) => Terms.FirstOrDefault(t => t.Symbol == symbol);
|
||||
}
|
||||
@@ -0,0 +1,644 @@
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Rail;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
namespace RailEnterprise.Core.Economy;
|
||||
|
||||
/// <summary>
|
||||
/// Spiegazioni «perché» dei valori principali (ADR 0024): pure funzioni del mondo, come i quadri dei pannelli.
|
||||
/// Ogni spiegazione chiama le stesse funzioni che usa il motore (passo del prezzo, prezzo locale, tariffe,
|
||||
/// termini dell'ultima produzione, punteggio di crescita, crescita della città, rischio di guasto, rating,
|
||||
/// requisiti del livello, curva del valore dei veicoli), quindi il valore finale è lo stesso numero del
|
||||
/// motore e i termini lo ricompongono con la formula dichiarata. Titoli, formule, etichette e note sono
|
||||
/// testi italiani fissi (chiavi di traduzione del client); i numeri viaggiano nei termini.
|
||||
/// </summary>
|
||||
public static class Explanations
|
||||
{
|
||||
/// <summary>Spiegazione del valore per la compagnia indicata (quella della sessione).</summary>
|
||||
public static Explanation Build(World w, CompanyId company, ExplainTarget target)
|
||||
{
|
||||
var c = company.IsValid && company.Value < w.Companies.Count ? w.Companies[company.Value] : null;
|
||||
return target.Subject switch
|
||||
{
|
||||
ExplainSubject.GlobalPrice => GlobalPrice(w, target),
|
||||
ExplainSubject.LocalPrice => LocalPrice(w, target),
|
||||
ExplainSubject.FreightTariff => FreightTariff(w, target, company),
|
||||
ExplainSubject.PassengerTariff => PassengerTariff(w, target, company),
|
||||
ExplainSubject.IndustryEfficiency => IndustryEfficiency(w, target),
|
||||
ExplainSubject.IndustryGrowth => IndustryGrowth(w, target),
|
||||
ExplainSubject.TownGrowth => TownGrowth(w, target),
|
||||
ExplainSubject.TrainCondition => TrainCondition(w, target, company),
|
||||
ExplainSubject.Rating => c is null ? Missing(w, target, "Rating") : Rating(w, target, c),
|
||||
ExplainSubject.TierProgress => c is null ? Missing(w, target, "Avanzamento del livello") : TierProgress(w, target, c),
|
||||
ExplainSubject.VehicleValue => VehicleValue(w, target, company),
|
||||
ExplainSubject.Cash => c is null ? Missing(w, target, "Cassa") : Cash(w, target, c),
|
||||
_ => Missing(w, target, ""),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Spiegazione assente: bersaglio inesistente, chiuso o di un'altra compagnia.</summary>
|
||||
public static Explanation Missing(World w, ExplainTarget target, string title) => new()
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = false, Title = title, Name = "", Value = 0, Unit = ExplainUnit.Number,
|
||||
Formula = "", Terms = [], Notes = ["Valore non disponibile."],
|
||||
};
|
||||
|
||||
private static ExplanationTerm T(string symbol, string label, double value, ExplainUnit unit, string text = "") => new(symbol, label, value, unit, text);
|
||||
|
||||
// ------------------------------------------------------------------ prezzi
|
||||
|
||||
/// <summary>
|
||||
/// Prezzo globale di oggi rifatto con <see cref="Market.NextPrice"/> dagli stessi ingressi del passo di
|
||||
/// MarketSystem: prezzo di ieri dallo storico, finestre di domanda e offerta (invariate dal passo),
|
||||
/// shock e anni al tick del passo (il primo tick del giorno dell'ultimo passo eseguito).
|
||||
/// </summary>
|
||||
public static Explanation GlobalPrice(World w, ExplainTarget target)
|
||||
{
|
||||
int g = target.A;
|
||||
if (g < 0 || g >= w.Data.GoodCount) return Missing(w, target, "Prezzo globale");
|
||||
var def = w.Data.Goods[g];
|
||||
var m = w.Data.Balance.Market;
|
||||
var market = w.Market;
|
||||
double pg = market.GlobalPrice[g];
|
||||
var cal = w.Calendar;
|
||||
var terms = new List<ExplanationTerm>();
|
||||
var notes = new List<string>();
|
||||
const string formula = "Pg = α·Pg′ + (1 − α)·Pg₋₁; Pg′ = clamp(Pg₋₁·(1 + k·(D/S − 1)), Pmin, Pmax); "
|
||||
+ "D/S = clamp(Dtot/Stot, rmin, rmax); Dtot = D + V·(Pw/Pg₋₁)^η; Stot = S + V·(Pg₋₁/Pw)^η";
|
||||
long stepTick = w.Clock.Tick == 0 ? -1 : (w.Clock.Tick - 1) / cal.TicksPerDay * cal.TicksPerDay;
|
||||
int stepYear = stepTick < 0 ? cal.StartYear : cal.StartYear + (int)(stepTick / cal.TicksPerDay / cal.DaysPerYear);
|
||||
if (stepTick < 0 || def.Era > stepYear)
|
||||
{
|
||||
terms.Add(T("Pb", "Prezzo base", def.BasePrice, ExplainUnit.Price));
|
||||
notes.Add(stepTick < 0 ? "Prezzo iniziale: il prezzo base del bene." : "Bene non ancora in commercio: il prezzo resta quello di partenza.");
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Prezzo globale", Name = def.NameIt,
|
||||
Value = pg, Unit = ExplainUnit.Price, Formula = formula, Terms = terms, Notes = notes,
|
||||
};
|
||||
}
|
||||
var history = market.PriceHistory[g];
|
||||
double previous = history.Count >= 2 ? history.Ago(1) : def.BasePrice;
|
||||
double volatility = w.Difficulty.MarketVolatilityMultiplier;
|
||||
double years = w.Clock.YearsAt(stepTick);
|
||||
var step = Market.NextPrice(m, def.BasePrice, previous, market.Demand[g].Sum, market.Supply[g].Sum, market.Demand[g].Count,
|
||||
volatility, years, market.Shock[g]);
|
||||
terms.Add(T("Pg₋₁", "Prezzo di ieri", step.Previous, ExplainUnit.Price));
|
||||
terms.Add(T("Pb", "Prezzo base", step.BasePrice, ExplainUnit.Price));
|
||||
terms.Add(T("D", "Domanda della regione (finestra)", step.Demand, ExplainUnit.Units));
|
||||
terms.Add(T("S", "Offerta della regione (finestra)", step.Supply, ExplainUnit.Units));
|
||||
terms.Add(T("Pw", "Prezzo mondiale", step.WorldPrice, ExplainUnit.Price));
|
||||
terms.Add(T("V", "Scambi con il resto del mondo", step.WorldVolume, ExplainUnit.Units));
|
||||
terms.Add(T("η", "Elasticità degli scambi con il mondo", m.World.Elasticity, ExplainUnit.Number));
|
||||
terms.Add(T("Dtot", "Domanda con il resto del mondo", step.DemandTotal, ExplainUnit.Units));
|
||||
terms.Add(T("Stot", "Offerta con il resto del mondo", step.SupplyTotal, ExplainUnit.Units));
|
||||
terms.Add(T("rmin", "Rapporto minimo", m.RatioMin, ExplainUnit.Factor));
|
||||
terms.Add(T("rmax", "Rapporto massimo", m.RatioMax, ExplainUnit.Factor));
|
||||
terms.Add(T("D/S", "Rapporto domanda / offerta (con il mondo, limitato)", step.Ratio, ExplainUnit.Factor));
|
||||
terms.Add(T("k", "Sensibilità al rapporto", m.K, ExplainUnit.Number));
|
||||
terms.Add(T("Pmin", "Prezzo minimo", m.MinPriceFactor * def.BasePrice, ExplainUnit.Price));
|
||||
terms.Add(T("Pmax", "Prezzo massimo", m.MaxPriceFactor * def.BasePrice, ExplainUnit.Price));
|
||||
terms.Add(T("Pg′", "Prezzo obiettivo", step.Target, ExplainUnit.Price));
|
||||
terms.Add(T("α", "Peso del giorno", m.Alpha, ExplainUnit.Number));
|
||||
notes.Add("D e S sono la domanda e l'offerta della regione; Dtot e Stot aggiungono gli scambi con il resto del mondo al prezzo mondiale, che segue il ciclo economico e gli shock.");
|
||||
if (Math.Abs(step.Price - pg) > 1e-9 * Math.Max(1, pg)) notes.Add("Il prezzo è cambiato dopo l'ultimo passo del mercato.");
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Prezzo globale", Name = def.NameIt,
|
||||
Value = pg, Unit = ExplainUnit.Price, Formula = formula, Terms = terms, Notes = notes,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Prezzo locale della prossima unità in un'industria (ADR 0004 §3): al consumatore con
|
||||
/// <see cref="TradingMath.ConsumerPrice"/> (Dl = capienza dell'ingresso, Sl = scorta), altrimenti al
|
||||
/// produttore con <see cref="TradingMath.ProducerPrice"/> (Dl = spazio libero, Sl = giacenza).
|
||||
/// </summary>
|
||||
public static Explanation LocalPrice(World w, ExplainTarget target)
|
||||
{
|
||||
int g = target.A, id = target.B;
|
||||
if (g < 0 || g >= w.Data.GoodCount || id < 0 || id >= w.Industries.Count) return Missing(w, target, "Prezzo locale");
|
||||
var ind = w.Industries[id];
|
||||
int dpm = w.Calendar.DaysPerMonth;
|
||||
int input = ind.InputIndexOf(g), output = ind.OutputIndexOf(g);
|
||||
if (ind.Closed || (input < 0 && output < 0)) return Missing(w, target, "Prezzo locale");
|
||||
var lp = w.Data.Balance.LocalPrice;
|
||||
double pg = w.Market.GlobalPrice[g];
|
||||
LocalPriceStep step;
|
||||
double value;
|
||||
var notes = new List<string>();
|
||||
if (input >= 0)
|
||||
{
|
||||
int stock = ind.InputStock[input];
|
||||
value = TradingMath.ConsumerPrice(w, ind, input, stock);
|
||||
step = Market.LocalPriceTerms(pg, IndustryMath.InputCapacity(ind, input, dpm), stock, lp);
|
||||
notes.Add("Prezzo a cui l'industria compra la prossima unità: Dl è la scorta desiderata dell'ingresso, Sl la scorta.");
|
||||
}
|
||||
else
|
||||
{
|
||||
int stock = ind.OutputStock[output];
|
||||
value = TradingMath.ProducerPrice(w, ind, output, stock);
|
||||
step = Market.LocalPriceTerms(pg, Math.Max(0, IndustryMath.OutputCapacity(ind, output, dpm) - stock), stock, lp);
|
||||
notes.Add("Prezzo a cui l'industria vende la prossima unità: Dl è lo spazio libero del magazzino, Sl la giacenza.");
|
||||
}
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Prezzo locale", Name = $"{w.Data.Goods[g].NameIt} · {ind.Name}",
|
||||
Value = value, Unit = ExplainUnit.Price,
|
||||
Formula = "Pl = Pg·clamp(1 + λ·(Dl − Sl)/(Dl + Sl + ε), 1 − δ, 1 + δ)",
|
||||
Terms =
|
||||
[
|
||||
T("Pg", "Prezzo globale", step.GlobalPrice, ExplainUnit.Price),
|
||||
T("Dl", "Domanda locale", step.LocalDemand, ExplainUnit.Units),
|
||||
T("Sl", "Offerta locale", step.LocalSupply, ExplainUnit.Units),
|
||||
T("λ", "Peso dello squilibrio", lp.Lambda, ExplainUnit.Number),
|
||||
T("ε", "Correzione per scorte nulle", lp.Epsilon, ExplainUnit.Number),
|
||||
T("δ", "Scarto massimo dal prezzo globale", lp.MaxDeviation, ExplainUnit.Percent),
|
||||
T("(Dl − Sl)/(Dl + Sl + ε)", "Squilibrio locale", step.Imbalance, ExplainUnit.Number),
|
||||
T("f", "Fattore locale", step.Factor, ExplainUnit.Factor),
|
||||
],
|
||||
Notes = notes,
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ tariffe
|
||||
|
||||
/// <summary>
|
||||
/// Tratta di una linea: dalla prima fermata a quella più lontana in linea d'aria (la distanza della
|
||||
/// tariffa è quella in linea d'aria tra le stazioni, come alla consegna). Null se la linea non ha due
|
||||
/// fermate distinte vive.
|
||||
/// </summary>
|
||||
public static (Station From, Station To, double Km)? Stretch(World w, Line line)
|
||||
{
|
||||
var net = w.Network;
|
||||
Station? from = null, to = null;
|
||||
double best = -1;
|
||||
foreach (var stop in line.Stops)
|
||||
{
|
||||
if (!stop.Station.IsValid || stop.Station.Value >= net.Stations.Count) continue;
|
||||
var s = net.Stations[stop.Station.Value];
|
||||
if (!net.IsAlive(s)) continue;
|
||||
if (from is null)
|
||||
{
|
||||
from = s;
|
||||
continue;
|
||||
}
|
||||
double d = Vec2.Distance(from.Position, s.Position);
|
||||
if (d > best)
|
||||
{
|
||||
best = d;
|
||||
to = s;
|
||||
}
|
||||
}
|
||||
if (from is null || to is null || best <= 0) return null;
|
||||
return (from, to, best / 1000);
|
||||
}
|
||||
|
||||
/// <summary>Linea viva della compagnia della sessione (null per una linea rimossa o di un'altra compagnia).</summary>
|
||||
private static Line? LiveLine(World w, int id, CompanyId company) =>
|
||||
id >= 0 && id < w.Lines.Count && w.Lines[id] is { Removed: false } l && l.Owner == company ? l : null;
|
||||
|
||||
/// <summary>Tempo atteso della tratta per il carico (giorni), 0 se nessun treno la collega.</summary>
|
||||
private static double ExpectedDays(World w, Line line, Station from, Station to, ulong cargo)
|
||||
{
|
||||
var reach = w.LineGraphs.For(w, line.Owner).From(from.Id, cargo);
|
||||
return reach.TryGetValue(to.Id.Value, out var conn) ? w.Calendar.TrainMinutesToDays(conn.Minutes) : 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tariffa merci per una unità sulla tratta della linea con <see cref="Tariffs.FreightTerms"/>: puntuale
|
||||
/// (tf = 1 alla consegna nel tempo atteso) e, per confronto, a due volte il tempo atteso.
|
||||
/// </summary>
|
||||
public static Explanation FreightTariff(World w, ExplainTarget target, CompanyId company)
|
||||
{
|
||||
var line = LiveLine(w, target.A, company);
|
||||
int g = target.B;
|
||||
if (line is null || g < 0 || g >= w.Data.GoodCount || Stretch(w, line) is not { } stretch) return Missing(w, target, "Tariffa merci");
|
||||
var t = w.Data.Balance.Tariffs;
|
||||
var def = w.Data.Goods[g];
|
||||
double pg = w.Market.GlobalPrice[g];
|
||||
double expected = ExpectedDays(w, line, stretch.From, stretch.To, LineGraph.GoodCargo(g));
|
||||
double diff = w.Difficulty.TariffMultiplier;
|
||||
var terms = Tariffs.FreightTerms(1, stretch.Km, pg, def.BasePrice, expected, expected, t, diff);
|
||||
var late = Tariffs.FreightTerms(1, stretch.Km, pg, def.BasePrice, 2 * expected, expected, t, diff);
|
||||
var notes = new List<string> { "Tariffa di una unità consegnata nel tempo atteso; tf scende dopo la soglia di ritardo fino al minimo." };
|
||||
if (expected <= 0) notes.Add("Nessun treno della linea collega la tratta con questo bene: il tempo atteso non è noto e tf vale 1.");
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Tariffa merci",
|
||||
Name = $"{line.Name}: {stretch.From.Name} → {stretch.To.Name} · {def.NameIt}",
|
||||
Value = terms.Fare.Cents, Unit = ExplainUnit.Money,
|
||||
Formula = "tariffa = u × Tb × (a + b·Pg/Pb) × km^e × tf × d",
|
||||
Terms =
|
||||
[
|
||||
T("u", "Unità", 1, ExplainUnit.Units),
|
||||
T("Tb", "Tariffa base", t.FreightBaseRate, ExplainUnit.Price),
|
||||
T("a", "Quota fissa", t.FreightFixedWeight, ExplainUnit.Number),
|
||||
T("b", "Quota legata al prezzo", t.FreightPriceWeight, ExplainUnit.Number),
|
||||
T("Pg", "Prezzo globale", pg, ExplainUnit.Price),
|
||||
T("Pb", "Prezzo base", def.BasePrice, ExplainUnit.Price),
|
||||
T("a + b·Pg/Pb", "Fattore del prezzo", terms.PriceFactor, ExplainUnit.Factor),
|
||||
T("km", "Distanza in linea d'aria", stretch.Km, ExplainUnit.Km),
|
||||
T("e", "Esponente della distanza", t.FreightKmExponent, ExplainUnit.Number),
|
||||
T("km^e", "Fattore della distanza", terms.KmFactor, ExplainUnit.Factor),
|
||||
T("tf", "Puntualità", terms.Lateness, ExplainUnit.Factor),
|
||||
T("d", "Moltiplicatore della difficoltà", diff, ExplainUnit.Factor),
|
||||
T("giorni", "Tempo atteso", expected, ExplainUnit.Days),
|
||||
T("soglia", "Soglia di ritardo (volte il tempo atteso)", t.LateThreshold, ExplainUnit.Factor),
|
||||
T("tf min", "Puntualità minima", t.LateFactorMin, ExplainUnit.Factor),
|
||||
T("tf 2×", "Puntualità a due volte il tempo atteso", late.Lateness, ExplainUnit.Factor),
|
||||
T("tariffa 2×", "Tariffa a due volte il tempo atteso", late.Fare.Cents, ExplainUnit.Money),
|
||||
],
|
||||
Notes = notes,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tariffa passeggeri per un posto sulla tratta della linea con <see cref="Tariffs.PassengerTerms"/>, poi
|
||||
/// × comfort delle carrozze del primo treno della linea (come alla consegna: due arrotondamenti al centesimo).
|
||||
/// </summary>
|
||||
public static Explanation PassengerTariff(World w, ExplainTarget target, CompanyId company)
|
||||
{
|
||||
var line = LiveLine(w, target.A, company);
|
||||
if (line is null || target.B is < 0 or > 1 || Stretch(w, line) is not { } stretch) return Missing(w, target, "Tariffa passeggeri");
|
||||
var cls = target.B == 1 ? PaxClass.Staff : PaxClass.Worker;
|
||||
var t = w.Data.Balance.Tariffs;
|
||||
double expected = ExpectedDays(w, line, stretch.From, stretch.To, LineGraph.PaxCargo(cls));
|
||||
double diff = w.Difficulty.TariffMultiplier;
|
||||
var train = w.Trains.Where(tr => !tr.Removed && tr.Line == line.Id).OrderBy(tr => tr.Id.Value).FirstOrDefault();
|
||||
double comfort = train is null ? 1.0 : Fleet.Comfort(w, train, cls);
|
||||
var terms = Tariffs.PassengerTerms(1, stretch.Km, cls, expected, expected, t, diff);
|
||||
var fare = terms.Fare * comfort;
|
||||
var late = Tariffs.PassengerTerms(1, stretch.Km, cls, 2 * expected, expected, t, diff).Fare * comfort;
|
||||
var notes = new List<string> { "Tariffa di un posto consegnato nel tempo atteso; tf scende dopo la soglia di ritardo fino al minimo." };
|
||||
if (train is null) notes.Add("Nessun treno sulla linea: il comfort delle carrozze vale 1.");
|
||||
if (expected <= 0) notes.Add("Nessun treno della linea collega la tratta per questa classe: il tempo atteso non è noto e tf vale 1.");
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true,
|
||||
Title = cls == PaxClass.Staff ? "Tariffa del personale" : "Tariffa dei lavoratori",
|
||||
Name = $"{line.Name}: {stretch.From.Name} → {stretch.To.Name}",
|
||||
Value = fare.Cents, Unit = ExplainUnit.Money,
|
||||
Formula = "tariffa = p × Tp × km^e × classe × tf × d × comfort",
|
||||
Terms =
|
||||
[
|
||||
T("p", "Posti", 1, ExplainUnit.Units),
|
||||
T("Tp", "Tariffa base per posto", t.PaxBaseFare, ExplainUnit.Price),
|
||||
T("km", "Distanza in linea d'aria", stretch.Km, ExplainUnit.Km),
|
||||
T("e", "Esponente della distanza", t.PaxKmExponent, ExplainUnit.Number),
|
||||
T("km^e", "Fattore della distanza", terms.KmFactor, ExplainUnit.Factor),
|
||||
T("classe", "Moltiplicatore della classe", terms.ClassFactor, ExplainUnit.Factor),
|
||||
T("tf", "Puntualità", terms.Lateness, ExplainUnit.Factor),
|
||||
T("d", "Moltiplicatore della difficoltà", diff, ExplainUnit.Factor),
|
||||
T("comfort", "Comfort delle carrozze", comfort, ExplainUnit.Factor),
|
||||
T("senza comfort", "Tariffa prima del comfort", terms.Fare.Cents, ExplainUnit.Money),
|
||||
T("giorni", "Tempo atteso", expected, ExplainUnit.Days),
|
||||
T("soglia", "Soglia di ritardo (volte il tempo atteso)", t.LateThreshold, ExplainUnit.Factor),
|
||||
T("tf min", "Puntualità minima", t.LateFactorMin, ExplainUnit.Factor),
|
||||
T("tariffa 2×", "Tariffa a due volte il tempo atteso", late.Cents, ExplainUnit.Money),
|
||||
],
|
||||
Notes = notes,
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ industrie e città
|
||||
|
||||
/// <summary>
|
||||
/// Efficienza dell'industria con i termini dell'ultima produzione (<see cref="Industry.LastEfficiency"/>):
|
||||
/// lavoro = min(cL, cP) × pf × mc (0 se ferma), e = lavoro × cI × g × ev, lo stesso prodotto di IndustrySystem.
|
||||
/// </summary>
|
||||
public static Explanation IndustryEfficiency(World w, ExplainTarget target)
|
||||
{
|
||||
if (target.A < 0 || target.A >= w.Industries.Count) return Missing(w, target, "Efficienza");
|
||||
var ind = w.Industries[target.A];
|
||||
var terms = new List<ExplanationTerm>();
|
||||
var notes = new List<string>();
|
||||
double value = ind.Closed ? 0 : ind.Efficiency;
|
||||
if (ind.Closed) notes.Add("Industria chiusa.");
|
||||
else if (ind.LastEfficiency is not { } e) notes.Add("I termini arrivano con la prossima produzione giornaliera (dopo un caricamento non sono salvati).");
|
||||
else
|
||||
{
|
||||
terms.Add(T("cL", "Copertura dei lavoratori (media mobile)", e.CovWorkers, ExplainUnit.Percent));
|
||||
terms.Add(T("cP", "Copertura del personale (media mobile)", e.CovStaff, ExplainUnit.Percent));
|
||||
terms.Add(T("pf", "Fattore di profitto", e.ProfitFactor, ExplainUnit.Factor));
|
||||
terms.Add(T("mc", "Condizione degli impianti", e.ConditionMultiplier, ExplainUnit.Factor));
|
||||
terms.Add(T("lavoro", "Ritmo del lavoro", e.Labour, ExplainUnit.Factor));
|
||||
terms.Add(T("cI", "Copertura degli ingressi di oggi", e.CovInputToday, ExplainUnit.Percent));
|
||||
terms.Add(T("g", "Giacimento", e.Depletion, ExplainUnit.Factor));
|
||||
terms.Add(T("ev", "Eventi in corso", e.EventCapacity, ExplainUnit.Factor));
|
||||
terms.Add(T("margine", "Margine (media mobile)", ind.Margin, ExplainUnit.Percent));
|
||||
// la condizione da cui viene mc: la manutenzione dello stesso tick la cambia subito dopo la produzione
|
||||
terms.Add(T("condizione", "Condizione degli impianti alla produzione (0–100)", e.Condition, ExplainUnit.Condition));
|
||||
if (e.Stopped) notes.Add("Industria ferma (guasto, incidente, revisione o ammodernamento): il ritmo del lavoro è zero.");
|
||||
if (ind.Level <= 0) notes.Add("Livello 0: l'industria è inattiva.");
|
||||
}
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Efficienza", Name = ind.Name,
|
||||
Value = value, Unit = ExplainUnit.Percent,
|
||||
Formula = "lavoro = min(cL, cP) × pf × mc (0 se ferma); e = lavoro × cI × g × ev",
|
||||
Terms = terms, Notes = notes,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Punteggio di crescita del trimestre in corso con <see cref="IndustryMath.GrowthScore"/>.</summary>
|
||||
public static Explanation IndustryGrowth(World w, ExplainTarget target)
|
||||
{
|
||||
if (target.A < 0 || target.A >= w.Industries.Count || w.Industries[target.A].Closed) return Missing(w, target, "Punteggio di crescita");
|
||||
var ind = w.Industries[target.A];
|
||||
var g = w.Data.Balance.Growth;
|
||||
var parts = IndustryMath.GrowthScore(ind, g);
|
||||
var notes = new List<string>
|
||||
{
|
||||
"Sopra la soglia di crescita per i trimestri richiesti il livello sale; sotto la soglia di calo scende.",
|
||||
};
|
||||
bool served = ind.ServedWithin(w.Clock.Day, g.QuarterDays);
|
||||
if (!served) notes.Add("Non servita da un vettore nel trimestre: il livello non cambia.");
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Punteggio di crescita", Name = ind.Name,
|
||||
Value = parts.Score, Unit = ExplainUnit.Percent,
|
||||
Formula = "punteggio = ws·quota + wc·copertura + wr·redditività",
|
||||
Terms =
|
||||
[
|
||||
T("quota", "Quota trasportata", parts.Shipped, ExplainUnit.Percent),
|
||||
T("spedite", "Unità spedite nel trimestre", ind.QuarterShipped, ExplainUnit.Units),
|
||||
T("prodotte", "Unità prodotte nel trimestre", ind.QuarterProduced, ExplainUnit.Units),
|
||||
T("copertura", "Copertura media", parts.Coverage, ExplainUnit.Percent),
|
||||
T("giorni", "Giorni del trimestre", ind.QuarterDays, ExplainUnit.Days),
|
||||
T("redditività", "Redditività (margine + 1)/2", parts.Profit, ExplainUnit.Percent),
|
||||
T("margine", "Margine (media mobile)", ind.Margin, ExplainUnit.Percent),
|
||||
T("ws", "Peso della quota", g.WeightShipped, ExplainUnit.Number),
|
||||
T("wc", "Peso della copertura", g.WeightCoverage, ExplainUnit.Number),
|
||||
T("wr", "Peso della redditività", g.WeightProfit, ExplainUnit.Number),
|
||||
T("soglia su", "Soglia di crescita", g.UpgradeThreshold, ExplainUnit.Percent),
|
||||
T("soglia giù", "Soglia di calo", g.DowngradeThreshold, ExplainUnit.Percent),
|
||||
T("trimestri", "Trimestri sopra soglia", ind.QuartersAboveUpgrade, ExplainUnit.Units),
|
||||
T("richiesti", "Trimestri richiesti", g.UpgradeQuarters, ExplainUnit.Units),
|
||||
],
|
||||
Notes = notes,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Crescita del prossimo mese della città con lo stato di oggi (<see cref="TownSystem.GrowthOf"/>).</summary>
|
||||
public static Explanation TownGrowth(World w, ExplainTarget target)
|
||||
{
|
||||
if (target.A < 0 || target.A >= w.Towns.Count) return Missing(w, target, "Crescita della città");
|
||||
var town = w.Towns[target.A];
|
||||
var tb = w.Data.Balance.Town;
|
||||
var g = TownSystem.GrowthOf(town, tb);
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Crescita della città", Name = town.Name,
|
||||
Value = g.Growth, Unit = ExplainUnit.Percent,
|
||||
Formula = "g = g₀ + ws·(s − s₀) + wo·(o − o₀), limitata a ±gmax",
|
||||
Terms =
|
||||
[
|
||||
T("g₀", "Crescita di base", tb.BaseGrowth, ExplainUnit.Percent),
|
||||
T("s", "Soddisfazione", g.Satisfaction, ExplainUnit.Percent),
|
||||
T("s₀", "Soddisfazione neutra", tb.SatisfactionPivot, ExplainUnit.Percent),
|
||||
T("ws", "Peso della soddisfazione", tb.SatisfactionWeight, ExplainUnit.Number),
|
||||
T("o", "Occupati per abitante", g.Employment, ExplainUnit.Percent),
|
||||
T("o₀", "Occupazione neutra", tb.EmploymentPivot, ExplainUnit.Percent),
|
||||
T("wo", "Peso dell'occupazione", tb.EmploymentWeight, ExplainUnit.Number),
|
||||
T("g grezza", "Crescita prima del limite", g.RawGrowth, ExplainUnit.Percent),
|
||||
T("gmax", "Crescita massima al mese", tb.MaxMonthlyGrowth, ExplainUnit.Percent),
|
||||
T("abitanti", "Abitanti", town.Population, ExplainUnit.Units),
|
||||
T("dopo", "Abitanti dopo il mese", g.Population, ExplainUnit.Units),
|
||||
T("ultimo mese", "Crescita dell'ultimo mese", town.LastGrowth, ExplainUnit.Percent),
|
||||
],
|
||||
Notes = ["Stima con lo stato di oggi: la crescita si applica all'inizio del mese."],
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ flotta
|
||||
|
||||
/// <summary>
|
||||
/// Condizione del treno (il componente più debole, <see cref="Fleet.TrainCondition"/>), rischio di guasto
|
||||
/// del giorno (<see cref="Fleet.DailyHazard"/>, lo stesso del controllo dei guasti) con i giorni attesi al
|
||||
/// guasto, e stima del pianificatore (<see cref="Fleet.Dues"/>) se il componente si consuma.
|
||||
/// </summary>
|
||||
public static Explanation TrainCondition(World w, ExplainTarget target, CompanyId company)
|
||||
{
|
||||
if (target.A < 0 || target.A >= w.Trains.Count || w.Trains[target.A] is not { Removed: false } t || t.Owner != company || t.Vehicles.Count == 0)
|
||||
return Missing(w, target, "Condizione del treno");
|
||||
var m = w.Data.Maintenance;
|
||||
double condition = Fleet.TrainCondition(w, t);
|
||||
var (weakest, comp, low) = Fleet.Weakest(w, t);
|
||||
var (hazard, hv, hc) = Fleet.DailyHazard(w, t, w.Clock.Day);
|
||||
var terms = new List<ExplanationTerm>();
|
||||
var notes = new List<string>();
|
||||
if (weakest is not null && comp >= 0)
|
||||
{
|
||||
var comps = Fleet.ComponentsOf(w.Data, weakest.Def);
|
||||
terms.Add(T("c", "Componente più debole", low, ExplainUnit.Condition, comp < comps.Count ? comps[comp].Id : ""));
|
||||
terms.Add(T("veicolo", "Veicolo", weakest.Id.Value, ExplainUnit.Text, weakest.Def.NameIt));
|
||||
}
|
||||
if (hv is not null && hc >= 0)
|
||||
{
|
||||
var f = m.Failure;
|
||||
double ch = hv.Components[hc];
|
||||
terms.Add(T("c rischio", "Componente più a rischio", ch, ExplainUnit.Condition, hc < Fleet.ComponentsOf(w.Data, hv.Def).Count ? Fleet.ComponentsOf(w.Data, hv.Def)[hc].Id : ""));
|
||||
terms.Add(T("h₀", "Rischio di base al giorno", f.H0, ExplainUnit.Percent));
|
||||
terms.Add(T("c₀", "Condizione di soglia", f.Pivot, ExplainUnit.Condition));
|
||||
terms.Add(T("k", "Pendenza del rischio", f.Slope, ExplainUnit.Number));
|
||||
terms.Add(T("σ", "Scala della condizione", f.Scale, ExplainUnit.Number));
|
||||
terms.Add(T("div", "Riduzione sopra soglia", f.HealthyDivisor, ExplainUnit.Number));
|
||||
bool inspected = w.Clock.Day < hv.HazardReducedUntilDay;
|
||||
terms.Add(T("ispezione", "Fattore dopo un'ispezione", inspected ? m.Inspection.HazardFactor : 1, ExplainUnit.Factor));
|
||||
terms.Add(T("h", "Rischio di guasto al giorno", hazard, ExplainUnit.Percent));
|
||||
if (hazard > 0) terms.Add(T("1/h", "Giorni attesi al prossimo guasto", 1 / hazard, ExplainUnit.Days));
|
||||
}
|
||||
// la stima viene dal componente con meno giorni all'obiettivo, che non è per forza il più debole
|
||||
var due = Fleet.ConditionDue(w, t);
|
||||
if (due.Vehicle is { } dv && due.Days < double.MaxValue)
|
||||
{
|
||||
var dcomps = Fleet.ComponentsOf(w.Data, dv.Def);
|
||||
terms.Add(T("cs", "Componente che dà la stima", due.Condition, ExplainUnit.Condition, due.Component < dcomps.Count ? dcomps[due.Component].Id : ""));
|
||||
if (dv != weakest) terms.Add(T("veicolo cs", "Veicolo del componente della stima", dv.Id.Value, ExplainUnit.Text, dv.Def.NameIt));
|
||||
terms.Add(T("usura", "Usura al giorno del componente (media mobile)", due.Rate, ExplainUnit.Number));
|
||||
terms.Add(T("obiettivo", "Condizione obiettivo del pianificatore", m.Planner.TargetCondition, ExplainUnit.Condition));
|
||||
terms.Add(T("margine", "Margine del pianificatore", m.Planner.MarginDays, ExplainUnit.Days));
|
||||
terms.Add(T("stima", "Giorni all'intervento sulla condizione", due.Days, ExplainUnit.Days));
|
||||
if (due.Condition <= m.Planner.TargetCondition) notes.Add("Il componente è già all'obiettivo o sotto: la stima vale −margine.");
|
||||
}
|
||||
else notes.Add("Nessuna stima del pianificatore: i componenti non si sono ancora consumati.");
|
||||
notes.Add("Il guasto è estratto ogni giorno con il rischio h: 1/h è il numero medio di giorni prima del prossimo.");
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Condizione del treno", Name = t.Name,
|
||||
Value = condition, Unit = ExplainUnit.Condition,
|
||||
Formula = "c = min(componenti); h = h₀·exp(k·(c₀ − c)/σ) sotto c₀, altrimenti h₀/div; stima = min sui componenti di (cs − obiettivo)/usura − margine",
|
||||
Terms = terms, Notes = notes,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Valore di libro (prezzo × residuo, <see cref="Obsolescence.BookValueCents"/>) e rivendita
|
||||
/// (<see cref="Obsolescence.ResaleValue"/>) di un veicolo della compagnia.
|
||||
/// </summary>
|
||||
public static Explanation VehicleValue(World w, ExplainTarget target, CompanyId company)
|
||||
{
|
||||
if (target.A < 0 || target.A >= w.Vehicles.Count || w.Vehicles[target.A] is not { Sold: false } v || v.Owner != company)
|
||||
return Missing(w, target, "Valore del veicolo");
|
||||
var o = w.Data.Obsolescence;
|
||||
double dpy = w.Calendar.DaysPerYear;
|
||||
double age = (w.Clock.Day - v.BoughtDay) / dpy;
|
||||
double residual = Obsolescence.Residual(w, v);
|
||||
long book = Obsolescence.BookValueCents(w, v);
|
||||
var resale = Obsolescence.ResaleValue(w, v);
|
||||
bool superseded = w.Clock.Day >= Obsolescence.SupersededDay(w.Calendar, v.Def);
|
||||
var terms = new List<ExplanationTerm>
|
||||
{
|
||||
T("prezzo", "Prezzo di listino", v.Def.Price, ExplainUnit.Money),
|
||||
T("età", "Età", age, ExplainUnit.Years),
|
||||
T("vita", "Vita utile", v.Def.LifeYears, ExplainUnit.Years),
|
||||
};
|
||||
var notes = new List<string>();
|
||||
string formula;
|
||||
if (superseded)
|
||||
{
|
||||
terms.Add(T("dal", "Superato dal", Obsolescence.SupersededYear(v.Def) ?? 0, ExplainUnit.Text, (Obsolescence.SupersededYear(v.Def) ?? 0).ToString(System.Globalization.CultureInfo.InvariantCulture)));
|
||||
terms.Add(T("anni superato", "Anni da superato", Obsolescence.YearsSuperseded(w, v), ExplainUnit.Years));
|
||||
terms.Add(T("perdita", "Perdita immediata", o.ImmediateValueLoss, ExplainUnit.Percent));
|
||||
terms.Add(T("velocità", "Ammortamento più rapido", o.DepreciationSpeed, ExplainUnit.Factor));
|
||||
var next = Obsolescence.Recommended(v.Def, w.Clock.Year);
|
||||
if (next is not null) terms.Add(T("successore", "Successore consigliato", 0, ExplainUnit.Text, next.NameIt));
|
||||
formula = "r = max(rmin, (1 − perdita)·(1 − (età + (velocità − 1)·anni superato)/vita)); valore = prezzo·r; rivendita = prezzo·r·condizione";
|
||||
notes.Add("Modello superato: perde subito una quota del valore e si ammortizza più in fretta.");
|
||||
}
|
||||
else formula = "r = max(rmin, 1 − età/vita); valore = prezzo·r; rivendita = prezzo·r·condizione";
|
||||
terms.Add(T("rmin", "Valore minimo", w.Data.Balance.Finance.BookValueFloor, ExplainUnit.Percent));
|
||||
terms.Add(T("r", "Quota residua del valore", residual, ExplainUnit.Percent));
|
||||
terms.Add(T("condizione", "Condizione media dei componenti", Obsolescence.AverageCondition(v), ExplainUnit.Percent));
|
||||
terms.Add(T("rivendita", "Rivendita", resale.Cents, ExplainUnit.Money));
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Valore del veicolo", Name = v.Def.NameIt,
|
||||
Value = book, Unit = ExplainUnit.Money, Formula = formula, Terms = terms, Notes = notes,
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ compagnia
|
||||
|
||||
/// <summary>Rating con <see cref="FinanceOutlook.Explain"/>: le misure dell'ultimo calcolo, componenti e punteggio.</summary>
|
||||
public static Explanation Rating(World w, ExplainTarget target, Company c)
|
||||
{
|
||||
var r = FinanceOutlook.Explain(w, c);
|
||||
var terms = new List<ExplanationTerm>
|
||||
{
|
||||
T("margine", "Margine (utile operativo / ricavi, 12 mesi)", r.Margin, ExplainUnit.Percent),
|
||||
T("cm", "Componente del margine", r.MarginComponent, ExplainUnit.Number),
|
||||
T("leva", "Debiti / patrimonio netto", r.Leverage, ExplainUnit.Factor),
|
||||
T("cl", "Componente della leva", r.LeverageComponent, ExplainUnit.Number),
|
||||
T("pm", "Peso del margine", r.MarginWeight, ExplainUnit.Number),
|
||||
T("pl", "Peso della leva", r.LeverageWeight, ExplainUnit.Number),
|
||||
};
|
||||
var notes = new List<string>();
|
||||
if (r.Initial) notes.Add("Rating iniziale: le misure sono quelle di oggi, il primo calcolo è a inizio mese.");
|
||||
if (r.MarginNeutral) notes.Add("Margine neutro finché la finestra non ha abbastanza mesi con ricavi.");
|
||||
if (r.Bankrupt) notes.Add("Compagnia in bancarotta: il rating è D.");
|
||||
if (r.Next is { } next)
|
||||
{
|
||||
terms.Add(T("gradino", "Gradino sopra", 0, ExplainUnit.Text, next.ToString()));
|
||||
terms.Add(T("soglia", "Punteggio del gradino sopra", r.NextThreshold, ExplainUnit.Number));
|
||||
if (r.NextAlreadyMet) notes.Add("Il punteggio vale già il gradino sopra: il rating cambia al prossimo calcolo mensile.");
|
||||
else if (!r.Bankrupt)
|
||||
{
|
||||
if (r.MarginReachable) terms.Add(T("margine necessario", "Margine che basta, a leva invariata", r.MarginNeeded, ExplainUnit.Percent));
|
||||
if (r.LeverageReachable) terms.Add(T("leva massima", "Leva che basta, a margine invariato", r.LeverageMax, ExplainUnit.Factor));
|
||||
if (r.DebtToRepay.Cents > 0) terms.Add(T("rimborso", "Debito da rimborsare per la leva che basta", r.DebtToRepay.Cents, ExplainUnit.Money));
|
||||
}
|
||||
}
|
||||
else notes.Add("Rating più alto.");
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Rating", Name = c.Name,
|
||||
Value = r.Score, Unit = ExplainUnit.Number, ValueText = r.Rating.ToString(),
|
||||
Formula = "punteggio = pm·clamp(0,5 + margine, 0, 1) + pl·1/(1 + leva)",
|
||||
Terms = terms, Notes = notes,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Avanzamento verso il prossimo livello con <see cref="ClimbOutlook.Requirements"/>.</summary>
|
||||
public static Explanation TierProgress(World w, ExplainTarget target, Company c)
|
||||
{
|
||||
var tiers = w.Data.Tiers.Tiers;
|
||||
if (c.Tier >= tiers.Count)
|
||||
{
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Avanzamento del livello", Name = c.Name,
|
||||
Value = 1, Unit = ExplainUnit.Percent, Formula = "", Terms = [], Notes = ["Livello più alto."],
|
||||
};
|
||||
}
|
||||
var req = ClimbOutlook.Requirements(w, c, tiers[c.Tier]);
|
||||
var notes = new List<string>();
|
||||
if (!(req.NetWorthMet && req.TownsMet && req.RatingMet)) notes.Add("Finché un requisito manca l'avanzamento resta sotto il 100%.");
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Avanzamento del livello", Name = c.Name,
|
||||
Value = req.Progress, Unit = ExplainUnit.Percent,
|
||||
Formula = "avanzamento = (fP + fC + fR)/3; fP = min(1, patrimonio/soglia); fC = min(1, città/richieste); fR = 1 − gradini mancanti/n",
|
||||
Terms =
|
||||
[
|
||||
T("patrimonio", "Patrimonio netto", req.NetWorth.Cents, ExplainUnit.Money),
|
||||
T("soglia", "Patrimonio richiesto", req.NetWorthRequired.Cents, ExplainUnit.Money),
|
||||
T("fP", "Frazione del patrimonio", req.NetWorthFraction, ExplainUnit.Percent),
|
||||
T("città", "Città collegate", req.Towns, ExplainUnit.Units),
|
||||
T("richieste", "Città richieste", req.TownsRequired, ExplainUnit.Units),
|
||||
T("abitanti", "Abitanti minimi per città", req.TownPopulation, ExplainUnit.Units),
|
||||
T("fC", "Frazione delle città", req.TownsFraction, ExplainUnit.Percent),
|
||||
T("rating", "Rating", 0, ExplainUnit.Text, req.Rating.ToString()),
|
||||
T("rating richiesto", "Rating richiesto", 0, ExplainUnit.Text, req.RatingRequired.ToString()),
|
||||
T("n", "Gradini per lo zero", w.Data.Tiers.RatingProgressSteps, ExplainUnit.Number),
|
||||
T("fR", "Frazione del rating", req.RatingFraction, ExplainUnit.Percent),
|
||||
T("tetto", "Tetto con un requisito mancante", ClimbOutlook.ProgressCap, ExplainUnit.Percent),
|
||||
],
|
||||
Notes = notes,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cassa con i movimenti del mese in corso per sezione del conto economico (<see cref="FinanceOutlook.Columns"/>):
|
||||
/// cassa a inizio mese + ricavi + costi + investimenti e finanziamenti (con segno).
|
||||
/// </summary>
|
||||
public static Explanation Cash(World w, ExplainTarget target, Company c)
|
||||
{
|
||||
var month = FinanceOutlook.Columns(w, c)[0];
|
||||
long revenue = 0, costs = 0, capital = 0;
|
||||
for (int i = 0; i < month.Entries.Length; i++)
|
||||
{
|
||||
switch (LedgerEntries.Section((LedgerEntry)i))
|
||||
{
|
||||
case IncomeSection.Revenue: revenue += month.Entries[i]; break;
|
||||
case IncomeSection.Cost: costs += month.Entries[i]; break;
|
||||
default: capital += month.Entries[i]; break;
|
||||
}
|
||||
}
|
||||
var notes = new List<string> { "Le voci del mese sono nel pannello «Finanze»." };
|
||||
var terms = new List<ExplanationTerm>
|
||||
{
|
||||
T("inizio", "Cassa a inizio mese", c.Cash.Cents - month.CashFlow.Cents, ExplainUnit.Money),
|
||||
T("ricavi", "Ricavi del mese", revenue, ExplainUnit.Money),
|
||||
T("costi", "Costi del mese", costs, ExplainUnit.Money),
|
||||
T("capitale", "Investimenti e finanziamenti del mese", capital, ExplainUnit.Money),
|
||||
T("flusso", "Flusso di cassa del mese", month.CashFlow.Cents, ExplainUnit.Money),
|
||||
};
|
||||
if (c.Cash.Cents < 0)
|
||||
{
|
||||
terms.Add(T("giorni", "Giorni di cassa negativa", c.NegativeCashDays, ExplainUnit.Days));
|
||||
terms.Add(T("limite", "Giorni che portano alla bancarotta", w.Difficulty.BankruptcyDays, ExplainUnit.Days));
|
||||
notes.Add("Con la cassa negativa per troppi giorni di fila la compagnia fallisce.");
|
||||
}
|
||||
return new Explanation
|
||||
{
|
||||
Target = target, Day = w.Clock.Day, Available = true, Title = "Cassa", Name = c.Name,
|
||||
Value = c.Cash.Cents, Unit = ExplainUnit.Money,
|
||||
Formula = "cassa = cassa a inizio mese + ricavi + costi + investimenti e finanziamenti",
|
||||
Terms = terms, Notes = notes,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
using System.Globalization;
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
namespace RailEnterprise.Core.Economy;
|
||||
|
||||
/// <summary>Colonna del conto economico: mese in corso, mese chiuso, anno in corso o anno chiuso.</summary>
|
||||
public enum IncomeColumnKind : byte
|
||||
{
|
||||
CurrentMonth = 0,
|
||||
Month = 1,
|
||||
CurrentYear = 2,
|
||||
Year = 3,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Movimenti per voce di un periodo (<see cref="Company.EntryCount"/> valori, indice = <see cref="LedgerEntry"/>),
|
||||
/// con l'utile operativo del motore e il flusso di cassa (somma di tutte le voci).
|
||||
/// </summary>
|
||||
public sealed class IncomeColumn
|
||||
{
|
||||
public required IncomeColumnKind Kind { get; init; }
|
||||
public required int Year { get; init; }
|
||||
/// <summary>Mese 1–12 per le colonne mensili, 0 per quelle annuali.</summary>
|
||||
public required int Month { get; init; }
|
||||
public required long[] Entries { get; init; }
|
||||
/// <summary>Utile operativo: <see cref="Company.OperatingProfit"/> sulle stesse voci.</summary>
|
||||
public required Money Profit { get; init; }
|
||||
/// <summary>Variazione della cassa nel periodo: somma di tutte le voci, investimenti e finanziamenti compresi.</summary>
|
||||
public required Money CashFlow { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Soglia di un rating: punteggio minimo e tasso di un nuovo prestito con quel rating.</summary>
|
||||
public readonly record struct RatingThreshold(CreditRating Rating, double MinScore, double LoanRate);
|
||||
|
||||
/// <summary>
|
||||
/// Spiegazione del rating (ADR 0019): le due misure conservate dal motore all'ultimo calcolo, le
|
||||
/// componenti e il punteggio, le soglie, e cosa servirebbe per il gradino sopra.
|
||||
/// </summary>
|
||||
public sealed class RatingExplanation
|
||||
{
|
||||
public required CreditRating Rating { get; init; }
|
||||
/// <summary>Vero prima del primo calcolo mensile: il rating è quello iniziale dei dati e le misure sono di oggi.</summary>
|
||||
public required bool Initial { get; init; }
|
||||
public required bool Bankrupt { get; init; }
|
||||
/// <summary>Mesi chiusi nella finestra del margine (fino a finance.incomeMonths).</summary>
|
||||
public required int Months { get; init; }
|
||||
/// <summary>Mesi della finestra con ricavi.</summary>
|
||||
public required int RevenueMonths { get; init; }
|
||||
/// <summary>
|
||||
/// Margine neutro (0) perché la finestra non è piena e ha meno di <see cref="MinRevenueMonths"/> mesi
|
||||
/// con ricavi (avvio della compagnia).
|
||||
/// </summary>
|
||||
public required bool MarginNeutral { get; init; }
|
||||
/// <summary>Mesi con ricavi che servono perché il margine conti prima che la finestra sia piena (finance.ratingMinRevenueMonths).</summary>
|
||||
public required int MinRevenueMonths { get; init; }
|
||||
public required double Margin { get; init; }
|
||||
/// <summary>Debiti / patrimonio netto (+∞ con patrimonio non positivo e debiti: <see cref="LeverageUnbounded"/>).</summary>
|
||||
public required double Leverage { get; init; }
|
||||
public bool LeverageUnbounded => double.IsPositiveInfinity(Leverage);
|
||||
public required double MarginWeight { get; init; }
|
||||
public required double LeverageWeight { get; init; }
|
||||
public required double MarginComponent { get; init; }
|
||||
public required double LeverageComponent { get; init; }
|
||||
public required double Score { get; init; }
|
||||
/// <summary>Soglie da AAA a C (sotto l'ultima è D).</summary>
|
||||
public required List<RatingThreshold> Thresholds { get; init; }
|
||||
/// <summary>Gradino sopra (null ad AAA) e punteggio che richiede.</summary>
|
||||
public required CreditRating? Next { get; init; }
|
||||
public required double NextThreshold { get; init; }
|
||||
/// <summary>Rating che corrisponde al punteggio (D in bancarotta).</summary>
|
||||
public required CreditRating ScoreRating { get; init; }
|
||||
/// <summary>
|
||||
/// Il punteggio raggiunge già il gradino sopra: il rating mostrato è quello iniziale o di un calcolo
|
||||
/// precedente e cambia al prossimo calcolo mensile. Margine e leva necessari non si calcolano.
|
||||
/// </summary>
|
||||
public required bool NextAlreadyMet { get; init; }
|
||||
/// <summary>Margine che basterebbe da solo, a leva invariata (se raggiungibile).</summary>
|
||||
public required double MarginNeeded { get; init; }
|
||||
public required bool MarginReachable { get; init; }
|
||||
/// <summary>Debiti/patrimonio massimo che basterebbe da solo, a margine invariato (se raggiungibile).</summary>
|
||||
public required double LeverageMax { get; init; }
|
||||
public required bool LeverageReachable { get; init; }
|
||||
/// <summary>Debiti da rimborsare oggi per scendere sotto <see cref="LeverageMax"/> (0 se già sotto o irraggiungibile).</summary>
|
||||
public required Money DebtToRepay { get; init; }
|
||||
/// <summary>
|
||||
/// Il rimborso di <see cref="DebtToRepay"/> si può fare oggi: non supera la cassa disponibile né il
|
||||
/// residuo dei prestiti (lo scoperto non si rimborsa, si copre solo riportando la cassa sopra zero).
|
||||
/// </summary>
|
||||
public required bool RepayAffordable { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Prestito in corso con rata e scadenza.</summary>
|
||||
public sealed class LoanDetail
|
||||
{
|
||||
public required LoanId Id { get; init; }
|
||||
public required Money Principal { get; init; }
|
||||
public required Money Remaining { get; init; }
|
||||
/// <summary>Tasso annuo fissato all'accensione.</summary>
|
||||
public required double AnnualRate { get; init; }
|
||||
public required int MonthsLeft { get; init; }
|
||||
/// <summary>Rata mensile costante sul residuo e i mesi restanti (alla francese).</summary>
|
||||
public required Money Payment { get; init; }
|
||||
/// <summary>Interessi della prossima rata.</summary>
|
||||
public required Money NextInterest { get; init; }
|
||||
/// <summary>Giorno dell'ultima rata (primo giorno del mese).</summary>
|
||||
public required long MaturityDay { get; init; }
|
||||
}
|
||||
|
||||
public sealed class FinanceOutlookReport
|
||||
{
|
||||
public required long Day { get; init; }
|
||||
public required CompanyId Company { get; init; }
|
||||
public required Money Cash { get; init; }
|
||||
public required Money NetWorth { get; init; }
|
||||
/// <summary>Residuo dei prestiti.</summary>
|
||||
public required Money Loans { get; init; }
|
||||
/// <summary>Cassa negativa (scoperto), tra i debiti del rating.</summary>
|
||||
public required Money Overdraft { get; init; }
|
||||
/// <summary>Voci del conto economico nell'ordine di presentazione, con la loro sezione.</summary>
|
||||
public required List<(LedgerEntry Entry, IncomeSection Section)> Lines { get; init; }
|
||||
/// <summary>Mese in corso, mesi chiusi dal più recente, anno in corso, anni chiusi dal più recente.</summary>
|
||||
public required List<IncomeColumn> Columns { get; init; }
|
||||
public required RatingExplanation Rating { get; init; }
|
||||
public required List<LoanDetail> LoanList { get; init; }
|
||||
public required Money MaxLoan { get; init; }
|
||||
public required Money LoanAvailable { get; init; }
|
||||
/// <summary>Tasso di un nuovo prestito: base della difficoltà + spread del rating.</summary>
|
||||
public required double NewLoanRate { get; init; }
|
||||
public required double BaseRate { get; init; }
|
||||
public required double Spread { get; init; }
|
||||
public required int LoanTermMonths { get; init; }
|
||||
public required Money LoanStep { get; init; }
|
||||
public required bool LoansAllowed { get; init; }
|
||||
public required int NegativeCashDays { get; init; }
|
||||
/// <summary>Giorni di cassa negativa che portano alla bancarotta (difficulty.json, bankruptcyDays).</summary>
|
||||
public required int BankruptcyDays { get; init; }
|
||||
public required bool Bankrupt { get; init; }
|
||||
public required bool Receivership { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Quadro delle finanze per il pannello «Finanze» (ADR 0019): pura funzione del mondo, come
|
||||
/// <see cref="ClimbOutlook"/>. Conto economico per voce (mese in corso, mesi chiusi, anno in corso, anni
|
||||
/// chiusi) dalle stesse voci del registro che danno l'utile operativo, prestiti con rata e scadenza,
|
||||
/// spiegazione del rating dalle misure conservate dal motore, conto alla rovescia della bancarotta.
|
||||
/// </summary>
|
||||
public static class FinanceOutlook
|
||||
{
|
||||
public static FinanceOutlookReport Build(World w, CompanyId company)
|
||||
{
|
||||
var c = w.Company(company);
|
||||
var fb = w.Data.Balance.Finance;
|
||||
var max = FinanceSystem.MaxLoan(w, c);
|
||||
return new FinanceOutlookReport
|
||||
{
|
||||
Day = w.Clock.Day,
|
||||
Company = c.Id,
|
||||
Cash = c.Cash,
|
||||
NetWorth = c.NetWorth,
|
||||
Loans = c.Debt,
|
||||
Overdraft = Money.Max(Money.Zero, -c.Cash),
|
||||
Lines = LedgerEntries.Ordered.Select(e => (e, LedgerEntries.Section(e))).ToList(),
|
||||
Columns = Columns(w, c),
|
||||
Rating = Explain(w, c),
|
||||
LoanList = c.Loans.Select(l => Detail(w, l)).ToList(),
|
||||
MaxLoan = max,
|
||||
LoanAvailable = Money.Max(Money.Zero, max - c.Debt),
|
||||
NewLoanRate = FinanceSystem.LoanRate(w, c),
|
||||
BaseRate = w.Difficulty.BaseInterestRate,
|
||||
Spread = fb.RatingSpreads[c.Rating.ToString()],
|
||||
LoanTermMonths = fb.LoanTermMonths,
|
||||
LoanStep = new Money(fb.LoanStep),
|
||||
LoansAllowed = !c.Receivership && !c.Bankrupt,
|
||||
NegativeCashDays = c.NegativeCashDays,
|
||||
BankruptcyDays = w.Difficulty.BankruptcyDays,
|
||||
Bankrupt = c.Bankrupt,
|
||||
Receivership = c.Receivership,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Colonne del conto economico: mese in corso, mesi chiusi (dal più recente), anno in corso, anni chiusi.</summary>
|
||||
public static List<IncomeColumn> Columns(World w, Company c)
|
||||
{
|
||||
var today = w.Calendar.DateOfDay(w.Clock.Day);
|
||||
var list = new List<IncomeColumn> { Column(IncomeColumnKind.CurrentMonth, today.Year, today.Month, c.MonthEntries) };
|
||||
for (int i = c.IncomeMonths.Count - 1; i >= 0; i--)
|
||||
list.Add(Column(IncomeColumnKind.Month, c.IncomeMonths[i].Year, c.IncomeMonths[i].Month, c.IncomeMonths[i].Entries));
|
||||
list.Add(Column(IncomeColumnKind.CurrentYear, today.Year, 0, c.YearEntries));
|
||||
for (int i = c.IncomeYears.Count - 1; i >= 0; i--)
|
||||
list.Add(Column(IncomeColumnKind.Year, c.IncomeYears[i].Year, 0, c.IncomeYears[i].Entries));
|
||||
return list;
|
||||
}
|
||||
|
||||
private static IncomeColumn Column(IncomeColumnKind kind, int year, int month, long[] source)
|
||||
{
|
||||
var entries = new long[Company.EntryCount];
|
||||
Array.Copy(source, entries, Math.Min(source.Length, entries.Length));
|
||||
long flow = 0;
|
||||
foreach (long v in entries) flow += v;
|
||||
return new IncomeColumn
|
||||
{
|
||||
Kind = kind, Year = year, Month = month, Entries = entries,
|
||||
Profit = new Money(Company.OperatingProfit(entries)), CashFlow = new Money(flow),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Prestito con la rata sul residuo e la scadenza al primo giorno del mese dell'ultima rata.</summary>
|
||||
public static LoanDetail Detail(World w, Loan l)
|
||||
{
|
||||
int dpm = w.Calendar.DaysPerMonth;
|
||||
long monthStart = w.Clock.Day / dpm * dpm;
|
||||
return new LoanDetail
|
||||
{
|
||||
Id = l.Id, Principal = l.Principal, Remaining = l.Remaining, AnnualRate = l.AnnualRate, MonthsLeft = l.MonthsLeft,
|
||||
Payment = FinanceSystem.MonthlyPayment(l.Remaining, l.AnnualRate, l.MonthsLeft),
|
||||
NextInterest = Money.FromCentsRounded(l.Remaining.Cents * l.AnnualRate / 12),
|
||||
MaturityDay = monthStart + (long)Math.Max(0, l.MonthsLeft) * dpm,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Spiegazione del rating con le misure dell'ultimo calcolo mensile (prima del primo calcolo, quelle di
|
||||
/// oggi). Per il gradino sopra: il margine che basterebbe a leva invariata, il debiti/patrimonio massimo
|
||||
/// a margine invariato e quanto debito rimborsare oggi per arrivarci (a patrimonio invariato: il
|
||||
/// rimborso toglie lo stesso importo da cassa e debiti). Se il punteggio raggiunge già il gradino sopra
|
||||
/// (rating iniziale o rimasto da un calcolo precedente) lo dice e non calcola obiettivi già raggiunti.
|
||||
/// </summary>
|
||||
public static RatingExplanation Explain(World w, Company c)
|
||||
{
|
||||
var fb = w.Data.Balance.Finance;
|
||||
bool initial = c.RatingMonths == 0;
|
||||
var live = FinanceSystem.Measures(w, c);
|
||||
double margin = initial ? live.Margin : c.RatingMargin;
|
||||
double leverage = initial ? live.Leverage : c.RatingLeverage;
|
||||
double cm = FinanceSystem.MarginComponent(margin), cl = FinanceSystem.LeverageComponent(leverage);
|
||||
double score = fb.ProfitMarginWeight * cm + fb.LeverageWeight * cl;
|
||||
var thresholds = new List<RatingThreshold>(fb.RatingByScore.Length);
|
||||
for (int i = 0; i < fb.RatingByScore.Length; i++)
|
||||
thresholds.Add(new RatingThreshold((CreditRating)i, fb.RatingByScore[i], FinanceSystem.LoanRate(w, (CreditRating)i)));
|
||||
|
||||
CreditRating? next = c.Rating > CreditRating.AAA ? c.Rating - 1 : null;
|
||||
double target = next is { } n ? fb.RatingByScore[(int)n] : 0;
|
||||
var scoreRating = c.Bankrupt ? CreditRating.D : FinanceSystem.RatingOf(w, score);
|
||||
bool alreadyMet = next is not null && !c.Bankrupt && score >= target;
|
||||
double marginNeeded = 0, leverageMax = 0;
|
||||
bool marginOk = false, leverageOk = false, affordable = false;
|
||||
var repay = Money.Zero;
|
||||
if (next is not null && !c.Bankrupt && !alreadyMet)
|
||||
{
|
||||
// punteggio sotto la soglia: needCm > cm ≥ 0 e needCl > cl ≥ 0, quindi niente infiniti
|
||||
// pesoMargine·clamp(0,5 + m) + pesoLeva·cl = soglia → m
|
||||
double needCm = (target - fb.LeverageWeight * cl) / fb.ProfitMarginWeight;
|
||||
marginOk = needCm <= 1;
|
||||
marginNeeded = needCm - 0.5;
|
||||
// pesoMargine·cm + pesoLeva / (1 + ℓ) = soglia → ℓ
|
||||
double needCl = (target - fb.ProfitMarginWeight * cm) / fb.LeverageWeight;
|
||||
leverageOk = needCl <= 1;
|
||||
leverageMax = leverageOk ? 1 / needCl - 1 : 0;
|
||||
if (leverageOk && live.Equity > 0)
|
||||
{
|
||||
repay = new Money(Math.Max(0, live.Debt - (long)Math.Floor(leverageMax * live.Equity)));
|
||||
// si rimborsano i prestiti con la cassa: non oltre la cassa positiva né oltre il residuo
|
||||
long repayable = Math.Min(c.Debt.Cents, Math.Max(0, c.Cash.Cents));
|
||||
affordable = repay.Cents <= repayable;
|
||||
}
|
||||
}
|
||||
return new RatingExplanation
|
||||
{
|
||||
Rating = c.Rating, Initial = initial, Bankrupt = c.Bankrupt,
|
||||
Months = initial ? live.Months : c.RatingMonths,
|
||||
RevenueMonths = live.RevenueMonths, MarginNeutral = live.MarginNeutral, MinRevenueMonths = fb.RatingMinRevenueMonths,
|
||||
Margin = margin, Leverage = leverage,
|
||||
MarginWeight = fb.ProfitMarginWeight, LeverageWeight = fb.LeverageWeight,
|
||||
MarginComponent = cm, LeverageComponent = cl, Score = score,
|
||||
Thresholds = thresholds, Next = next, NextThreshold = target, ScoreRating = scoreRating, NextAlreadyMet = alreadyMet,
|
||||
MarginNeeded = marginNeeded, MarginReachable = marginOk,
|
||||
LeverageMax = leverageMax, LeverageReachable = leverageOk, DebtToRepay = repay, RepayAffordable = affordable,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Tasso in percentuale all'italiana con un decimale («6,5%»).</summary>
|
||||
public static string Percent(double rate) =>
|
||||
(rate * 100).ToString("0.0", CultureInfo.InvariantCulture).Replace('.', ',') + "%";
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
namespace RailEnterprise.Core.Economy;
|
||||
|
||||
/// <summary>
|
||||
/// Stato di un veicolo per il rinnovo della flotta: età, condizione media, superato o no, successore
|
||||
/// consigliato, valore di libro e di rivendita, moltiplicatore dei costi di manutenzione.
|
||||
/// </summary>
|
||||
public sealed record FleetVehicleLine(
|
||||
VehicleId Id, VehicleDef Def, TrainId Train, DepotId Depot, double AgeYears, double Condition,
|
||||
bool InProduction, bool Superseded, int? SupersededYear, VehicleDef? Successor,
|
||||
Money BookValue, Money ResaleValue, double MaintenanceFactor);
|
||||
|
||||
/// <summary>Modello in produzione nell'anno, come lo mostra il catalogo d'acquisto: superato o no e successore consigliato.</summary>
|
||||
public sealed record VehicleModelLine(VehicleDef Def, bool Superseded, int? SupersededYear, VehicleDef? Successor, int? LastYear);
|
||||
|
||||
/// <summary>
|
||||
/// Treno con veicoli da rinnovare: quanti, spesa netta del rinnovo (successori − rivendite + lavoro), se la
|
||||
/// cassa basta al netto degli altri rinnovi prenotati e se il rinnovo è già prenotato (in viaggio o in coda all'officina).
|
||||
/// </summary>
|
||||
public sealed record RenewalTrainLine(TrainId Train, int Vehicles, Money NetCost, bool Affordable, bool Booked);
|
||||
|
||||
/// <summary>
|
||||
/// Quadro del rinnovo della flotta (F6, ADR 0020), in sola lettura: era in corso e prossima, veicoli
|
||||
/// della compagnia con età, obsolescenza, successore e valori, catalogo dei modelli in produzione e
|
||||
/// treni da rinnovare. Tutto viene da <see cref="Obsolescence"/>: lo stesso valore del patrimonio e
|
||||
/// della rivendita. Il client lo mostra com'è.
|
||||
/// </summary>
|
||||
public sealed class FleetOutlook
|
||||
{
|
||||
public required long Day { get; init; }
|
||||
public required int Year { get; init; }
|
||||
public required CompanyId Company { get; init; }
|
||||
public required EraDef Era { get; init; }
|
||||
public required EraDef? NextEra { get; init; }
|
||||
/// <summary>Veicoli non venduti della compagnia, in ordine di id.</summary>
|
||||
public required List<FleetVehicleLine> Vehicles { get; init; }
|
||||
/// <summary>Modelli in produzione nell'anno, nell'ordine di vehicles.json (i fuori produzione non ci sono).</summary>
|
||||
public required List<VehicleModelLine> Models { get; init; }
|
||||
/// <summary>Treni della compagnia con almeno un veicolo da rinnovare, in ordine di id.</summary>
|
||||
public required List<RenewalTrainLine> Trains { get; init; }
|
||||
/// <summary>Somma dei valori di libro: coincide con la voce «veicoli» dello stato patrimoniale calcolata oggi.</summary>
|
||||
public Money BookValueTotal => new(Vehicles.Sum(v => v.BookValue.Cents));
|
||||
|
||||
public static FleetOutlook Build(World w, CompanyId company)
|
||||
{
|
||||
var d = w.Data;
|
||||
int year = w.Clock.Year;
|
||||
double daysPerYear = w.Calendar.DaysPerYear;
|
||||
var vehicles = new List<FleetVehicleLine>();
|
||||
foreach (var v in w.Vehicles)
|
||||
{
|
||||
if (v.Sold || v.Owner != company) continue;
|
||||
bool superseded = Obsolescence.IsSuperseded(v.Def, year);
|
||||
vehicles.Add(new FleetVehicleLine(
|
||||
v.Id, v.Def, v.Train, v.Depot, (w.Clock.Day - v.BoughtDay) / daysPerYear, Obsolescence.AverageCondition(v),
|
||||
Obsolescence.InProduction(v.Def, year), superseded, Obsolescence.SupersededYear(v.Def),
|
||||
superseded ? Obsolescence.Recommended(v.Def, year) : null,
|
||||
new Money(Obsolescence.BookValueCents(w, v)), Obsolescence.ResaleValue(w, v),
|
||||
Obsolescence.MaintenanceCostFactor(d, v.Def, year)));
|
||||
}
|
||||
var models = new List<VehicleModelLine>();
|
||||
foreach (var def in d.Vehicles)
|
||||
{
|
||||
if (!Obsolescence.InProduction(def, year)) continue;
|
||||
bool superseded = Obsolescence.IsSuperseded(def, year);
|
||||
models.Add(new VehicleModelLine(def, superseded, Obsolescence.SupersededYear(def),
|
||||
superseded ? Obsolescence.Recommended(def, year) : null, def.EraTo));
|
||||
}
|
||||
var trains = new List<RenewalTrainLine>();
|
||||
var c = company.IsValid && company.Value < w.Companies.Count ? w.Companies[company.Value] : null;
|
||||
// la cassa disponibile per un rinnovo esclude la spesa impegnata dagli altri già prenotati
|
||||
var committed = Obsolescence.Committed(w, company);
|
||||
foreach (var t in w.Trains)
|
||||
{
|
||||
if (t.Removed || t.Owner != company) continue;
|
||||
var plan = Obsolescence.RenewalPlan(w, t);
|
||||
if (plan.Count == 0) continue;
|
||||
var net = Obsolescence.RenewalCost(w, t, plan);
|
||||
var available = c is null ? Money.Zero : c.Cash - (committed - Obsolescence.Commitment(w, t));
|
||||
trains.Add(new RenewalTrainLine(t.Id, plan.Count, net, c is not null && (!net.IsPositive || available >= net),
|
||||
Obsolescence.RenewalBooked(w, t)));
|
||||
}
|
||||
return new FleetOutlook
|
||||
{
|
||||
Day = w.Clock.Day, Year = year, Company = company,
|
||||
Era = EraSystem.CurrentEra(d, year), NextEra = EraSystem.NextEra(d, year),
|
||||
Vehicles = vehicles, Models = models, Trains = trains,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,15 @@ public enum IndustryWork : byte { None = 0, Overhaul = 1, Upgrade = 2 }
|
||||
/// <summary>Fermo concluso o in corso, per lo storico del pannello del proprietario.</summary>
|
||||
public readonly record struct IndustryStopRecord(long Day, int Days, IndustryStop Kind);
|
||||
|
||||
/// <summary>
|
||||
/// Termini dell'efficienza dell'ultima produzione giornaliera (IndustrySystem), conservati per la spiegazione
|
||||
/// del valore (ADR 0024): lavoro = min(lavoratori, personale) × pf × mc (0 se ferma); e = lavoro × copertura degli
|
||||
/// input di oggi × giacimento × eventi. <c>Condition</c> è la condizione degli impianti da cui viene mc, letta prima
|
||||
/// della manutenzione dello stesso tick. Non si salvano: dopo un caricamento mancano fino alla produzione del giorno dopo.
|
||||
/// </summary>
|
||||
public readonly record struct EfficiencyTerms(long Day, double CovWorkers, double CovStaff, double ProfitFactor, double Condition, double ConditionMultiplier,
|
||||
bool Stopped, double Labour, double CovInputToday, double Depletion, double EventCapacity, double Efficiency);
|
||||
|
||||
/// <summary>
|
||||
/// Industria: produce secondo la ricetta del suo tipo, con efficienza
|
||||
/// e = min(copertura input, lavoratori, personale) × fattore di profitto × condizione impianti.
|
||||
@@ -97,6 +106,9 @@ public sealed class Industry : IWorkplace
|
||||
/// <summary>Efficienza dell'ultimo giorno.</summary>
|
||||
public double Efficiency { get; set; }
|
||||
|
||||
/// <summary>Termini dell'ultima produzione (non salvati, fuori dall'hash; ADR 0024).</summary>
|
||||
public EfficiencyTerms? LastEfficiency { get; set; }
|
||||
|
||||
/// <summary>Lavoratori e personale presenti oggi (quota in sede + pendolari arrivati), frazionari.</summary>
|
||||
public double WorkersPresent { get; set; }
|
||||
public double StaffPresent { get; set; }
|
||||
|
||||
@@ -0,0 +1,527 @@
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Rail;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
namespace RailEnterprise.Core.Economy;
|
||||
|
||||
/// <summary>
|
||||
/// Fattore che limita l'efficienza dell'industria (e = min(copertura input, lavoratori, personale) ×
|
||||
/// pf × mc × giacimento × eventi, guida 6.3): il più basso sotto 1, nell'ordine dell'enum a parità.
|
||||
/// </summary>
|
||||
public enum IndustryLimit : byte
|
||||
{
|
||||
/// <summary>Nessun fattore sotto 1: l'industria lavora a piena capacità.</summary>
|
||||
None = 0,
|
||||
Inputs = 1,
|
||||
Workers = 2,
|
||||
Staff = 3,
|
||||
/// <summary>Fattore di profitto (margine negativo).</summary>
|
||||
Profit = 4,
|
||||
/// <summary>Condizione degli impianti sotto la soglia del rendimento pieno.</summary>
|
||||
Condition = 5,
|
||||
/// <summary>Giacimento sotto la soglia di esaurimento.</summary>
|
||||
Depletion = 6,
|
||||
/// <summary>Evento del mondo sulla capacità (incidente).</summary>
|
||||
Event = 7,
|
||||
/// <summary>Fermo in corso (guasto, incidente, revisione, ammodernamento).</summary>
|
||||
Stopped = 8,
|
||||
/// <summary>Livello 0 (dormiente) o industria chiusa.</summary>
|
||||
Dormant = 9,
|
||||
}
|
||||
|
||||
/// <summary>Tipo di nodo della catena produttiva.</summary>
|
||||
public enum ChainPartnerKind : byte { Industry = 0, Hub = 1, Town = 2 }
|
||||
|
||||
/// <summary>
|
||||
/// Fornitore o cliente di un bene nella catena produttiva: unità al mese (produzione attuale del
|
||||
/// fornitore, fabbisogno a piena capacità del cliente, capacità mensile dell'hub, domanda della
|
||||
/// città), prezzo (centesimi per unità: prezzo globale per chi vende al mercato, prezzo locale
|
||||
/// dell'ADR 0004 per l'industria che compra, prezzo dell'hub con il dazio), linea della compagnia che
|
||||
/// collega i due (None se nessuna) e distanza in linea d'aria.
|
||||
/// </summary>
|
||||
public readonly record struct ChainPartner(ChainPartnerKind Kind, int Target, double MonthlyUnits, double Price, LineId Line, double DistanceKm);
|
||||
|
||||
/// <summary>
|
||||
/// Un input o un output dell'industria al livello attuale: quantità al mese a piena efficienza e al
|
||||
/// ritmo attuale, scorta e capienza del magazzino, giorni di scorta (input, al ritmo dei presenti) o
|
||||
/// giorni prima che il magazzino si riempia (output, al ritmo attuale; oltre si perde la merce);
|
||||
/// −1 se il ritmo è nullo. Partner: fornitori (input) o clienti (output).
|
||||
/// </summary>
|
||||
public sealed class IndustryFlow
|
||||
{
|
||||
public required int Good { get; init; }
|
||||
public required double FullMonth { get; init; }
|
||||
public required double CurrentMonth { get; init; }
|
||||
public required int Stock { get; init; }
|
||||
public required int Storage { get; init; }
|
||||
public required double Days { get; init; }
|
||||
/// <summary>Input che limita l'efficienza (quello con meno giorni di scorta quando il limite sono gli input).</summary>
|
||||
public required bool Limiting { get; init; }
|
||||
public required List<ChainPartner> Partners { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Provenienza dei lavoratori (o del personale): città, linea del primo tratto, vettore, minuti di viaggio.</summary>
|
||||
public readonly record struct WorkforceSource(TownId Town, int Headcount, double Coverage, LineId Line, CompanyId Carrier, double Minutes, bool Walking);
|
||||
|
||||
/// <summary>Lavoratori o personale qualificato dell'industria.</summary>
|
||||
public sealed class WorkforceOutlook
|
||||
{
|
||||
public required int Jobs { get; init; }
|
||||
public required double Present { get; init; }
|
||||
/// <summary>Persone in sede: posti coperti da chi vive negli alloggi dell'industria (posti × quota in sede).</summary>
|
||||
public required double OnSite { get; init; }
|
||||
/// <summary>Copertura media su coverageWindowDays (entra nell'efficienza).</summary>
|
||||
public required double Coverage { get; init; }
|
||||
/// <summary>Posti scoperti oggi (posti − presenti, arrotondato).</summary>
|
||||
public required int Missing { get; init; }
|
||||
public required UncoveredReason Reason { get; init; }
|
||||
public required LineId ReasonLine { get; init; }
|
||||
/// <summary>Viaggio medio in treno (minuti, pesato sulle persone) dei contratti visibili; −1 se nessuno.</summary>
|
||||
public required double AverageMinutes { get; init; }
|
||||
/// <summary>Provenienze più numerose (al massimo industry.outlook.workforceSources).</summary>
|
||||
public required List<WorkforceSource> Sources { get; init; }
|
||||
/// <summary>Provenienze visibili in tutto (anche quelle non elencate).</summary>
|
||||
public required int SourceCount { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Crescita trimestrale (guida 6.3): punteggio del trimestre in corso, soglie e trimestri.</summary>
|
||||
public sealed class GrowthOutlook
|
||||
{
|
||||
public required double LastScore { get; init; }
|
||||
public required GrowthScoreParts Current { get; init; }
|
||||
public required double UpgradeThreshold { get; init; }
|
||||
public required double DowngradeThreshold { get; init; }
|
||||
public required int UpgradeQuarters { get; init; }
|
||||
public required int QuartersAbove { get; init; }
|
||||
/// <summary>Giorni del trimestre già contati e lunghezza del trimestre.</summary>
|
||||
public required int QuarterDay { get; init; }
|
||||
public required int QuarterDays { get; init; }
|
||||
/// <summary>Servita da un vettore nel trimestre: solo allora il livello cambia (ADR 0004).</summary>
|
||||
public required bool Served { get; init; }
|
||||
public required int MaxLevel { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Scheda dell'industria per la compagnia della sessione (immagine di riferimento 07, ADR 0021).</summary>
|
||||
public sealed class IndustryOutlookReport
|
||||
{
|
||||
public required IndustryId Industry { get; init; }
|
||||
public required int Level { get; init; }
|
||||
public required int MaxLevel { get; init; }
|
||||
public required double Efficiency { get; init; }
|
||||
public required IndustryLimit Limit { get; init; }
|
||||
public required double CovInput { get; init; }
|
||||
public required double CovWorkers { get; init; }
|
||||
public required double CovStaff { get; init; }
|
||||
public required int CoverageWindowDays { get; init; }
|
||||
public required double ProfitFactor { get; init; }
|
||||
public required double ConditionMultiplier { get; init; }
|
||||
public required double Depletion { get; init; }
|
||||
public required double EventCapacity { get; init; }
|
||||
/// <summary>Riserva residua del giacimento (0–1); −1 se l'industria non è esauribile.</summary>
|
||||
public required double ReserveFraction { get; init; }
|
||||
public required int StorageDays { get; init; }
|
||||
public required List<IndustryFlow> Inputs { get; init; }
|
||||
public required List<IndustryFlow> Outputs { get; init; }
|
||||
public required WorkforceOutlook Workers { get; init; }
|
||||
public required WorkforceOutlook Staff { get; init; }
|
||||
/// <summary>
|
||||
/// Prezzo di vendita del prodotto (centesimi): il prezzo globale del giorno, quello a cui le
|
||||
/// industrie vendono al mercato (ADR 0004); −1 senza prodotti o con più prodotti.
|
||||
/// </summary>
|
||||
public required double SalePrice { get; init; }
|
||||
public required Money AnnualProfit { get; init; }
|
||||
public required GrowthOutlook Growth { get; init; }
|
||||
/// <summary>Stazioni (di qualunque compagnia) che servono l'industria con una linea con treni.</summary>
|
||||
public required List<StationId> ServingStations { get; init; }
|
||||
/// <summary>Linea della compagnia della sessione che serve l'industria (id più basso), None se nessuna.</summary>
|
||||
public required LineId ServingLine { get; init; }
|
||||
/// <summary>Dei privati e attiva: si può comprare (dal livello che sblocca l'acquisto).</summary>
|
||||
public required bool ForSale { get; init; }
|
||||
public required bool BuyUnlocked { get; init; }
|
||||
public required int BuyTier { get; init; }
|
||||
/// <summary>Avanzamento verso il livello che sblocca l'acquisto (ADR 0018); 1 se sbloccato.</summary>
|
||||
public required double BuyProgress { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Scheda dell'industria (ADR 0021): legge il mondo e non scrive nulla, come MarketOutlook e
|
||||
/// ClimbOutlook. Catena produttiva con fornitori e clienti per bene, coperture, forza lavoro con le
|
||||
/// provenienze, produzione e magazzino, fattore limitante, crescita trimestrale e acquisto.
|
||||
/// </summary>
|
||||
public static class IndustryOutlook
|
||||
{
|
||||
public static IndustryOutlookReport Build(World w, Industry ind, CompanyId company)
|
||||
{
|
||||
var data = w.Data;
|
||||
var ib = data.Balance.Industry;
|
||||
var g = data.Balance.Growth;
|
||||
int dpm = w.Calendar.DaysPerMonth;
|
||||
long today = w.Clock.Day;
|
||||
var recipe = ind.Def.Recipe;
|
||||
var factors = Factors(w, ind);
|
||||
var links = new LineLinks(w, company);
|
||||
var mine = links.Serving(ind);
|
||||
|
||||
// ritmo dei presenti senza la copertura degli input (giorni di scorta) e ritmo effettivo
|
||||
double cyclesFull = ind.Closed ? 0 : ind.CyclesPerDayAtFullCapacity(dpm);
|
||||
double labour = factors.Stopped || ind.Closed
|
||||
? 0
|
||||
: Math.Min(ind.CovWorkers, ind.CovStaff) * factors.ProfitFactor * factors.ConditionMultiplier * factors.Depletion * factors.EventCapacity;
|
||||
double efficiency = ind.Closed ? 0 : ind.Efficiency;
|
||||
|
||||
int limiting = -1;
|
||||
if (factors.Limit == IndustryLimit.Inputs)
|
||||
{
|
||||
double least = double.MaxValue;
|
||||
for (int i = 0; i < recipe.Inputs.Count; i++)
|
||||
{
|
||||
double perDay = cyclesFull * recipe.Inputs[i].PerCycle * labour;
|
||||
double days = perDay > 0 ? ind.InputStock[i] / perDay : double.MaxValue;
|
||||
if (limiting < 0 || days < least)
|
||||
{
|
||||
least = days;
|
||||
limiting = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
var inputs = new List<IndustryFlow>(recipe.Inputs.Count);
|
||||
for (int i = 0; i < recipe.Inputs.Count; i++)
|
||||
{
|
||||
int good = recipe.Inputs[i].GoodIndex;
|
||||
double full = cyclesFull * recipe.Inputs[i].PerCycle * dpm;
|
||||
double perDay = cyclesFull * recipe.Inputs[i].PerCycle * labour;
|
||||
inputs.Add(new IndustryFlow
|
||||
{
|
||||
Good = good, FullMonth = full, CurrentMonth = full * efficiency, Stock = ind.InputStock[i],
|
||||
Storage = IndustryMath.InputCapacity(ind, i, dpm), Days = perDay > 0 ? ind.InputStock[i] / perDay : -1,
|
||||
Limiting = i == limiting, Partners = Suppliers(w, ind, good, links, mine),
|
||||
});
|
||||
}
|
||||
var outputs = new List<IndustryFlow>(recipe.Outputs.Count);
|
||||
for (int o = 0; o < recipe.Outputs.Count; o++)
|
||||
{
|
||||
int good = recipe.Outputs[o].GoodIndex;
|
||||
double full = cyclesFull * recipe.Outputs[o].PerCycle * dpm;
|
||||
double perDay = full * efficiency / dpm;
|
||||
int storage = IndustryMath.OutputCapacity(ind, o, dpm);
|
||||
outputs.Add(new IndustryFlow
|
||||
{
|
||||
Good = good, FullMonth = full, CurrentMonth = full * efficiency, Stock = ind.OutputStock[o], Storage = storage,
|
||||
Days = perDay > 0 ? Math.Max(0, storage - ind.OutputStock[o]) / perDay : -1,
|
||||
Limiting = false, Partners = Customers(w, ind, good, links, mine),
|
||||
});
|
||||
}
|
||||
|
||||
// prezzo di vendita: le industrie vendono al prezzo globale del giorno (ADR 0004). Una media dei
|
||||
// ricavi mescolerebbe la media mobile dei ricavi con i totali del trimestre in corso
|
||||
double salePrice = recipe.Outputs.Count == 1 ? w.Market.GlobalPrice[recipe.Outputs[0].GoodIndex] : -1;
|
||||
|
||||
var buyTier = data.Tiers.Tiers.FirstOrDefault(t => t.Unlocks.BuyIndustry);
|
||||
var owner = company.IsValid && company.Value < w.Companies.Count ? w.Companies[company.Value] : null;
|
||||
bool buyUnlocked = owner is not null && Tiers.Unlocks(w, owner).BuyIndustry;
|
||||
double buyProgress = buyUnlocked ? 1 : owner is not null && buyTier is not null ? ClimbOutlook.Requirements(w, owner, buyTier).Progress : 0;
|
||||
|
||||
return new IndustryOutlookReport
|
||||
{
|
||||
Industry = ind.Id,
|
||||
Level = ind.Level,
|
||||
MaxLevel = g.MaxLevel,
|
||||
Efficiency = efficiency,
|
||||
Limit = factors.Limit,
|
||||
CovInput = ind.CovInput,
|
||||
CovWorkers = ind.CovWorkers,
|
||||
CovStaff = ind.CovStaff,
|
||||
CoverageWindowDays = ib.CoverageWindowDays,
|
||||
ProfitFactor = factors.ProfitFactor,
|
||||
ConditionMultiplier = factors.ConditionMultiplier,
|
||||
Depletion = factors.Depletion,
|
||||
EventCapacity = factors.EventCapacity,
|
||||
ReserveFraction = factors.ReserveFraction,
|
||||
StorageDays = ind.Def.StorageDays,
|
||||
Inputs = inputs,
|
||||
Outputs = outputs,
|
||||
Workers = Workforce(w, ind, PaxClass.Worker, company),
|
||||
Staff = Workforce(w, ind, PaxClass.Staff, company),
|
||||
SalePrice = salePrice,
|
||||
AnnualProfit = Money.FromCentsRounded(IndustryMath.AnnualProfit(w, ind)),
|
||||
Growth = new GrowthOutlook
|
||||
{
|
||||
LastScore = ind.LastScore,
|
||||
Current = IndustryMath.GrowthScore(ind, g),
|
||||
UpgradeThreshold = g.UpgradeThreshold,
|
||||
DowngradeThreshold = g.DowngradeThreshold,
|
||||
UpgradeQuarters = g.UpgradeQuarters,
|
||||
QuartersAbove = ind.QuartersAboveUpgrade,
|
||||
QuarterDay = ind.QuarterDays,
|
||||
QuarterDays = g.QuarterDays,
|
||||
Served = ind.ServedWithin(today, g.QuarterDays),
|
||||
MaxLevel = g.MaxLevel,
|
||||
},
|
||||
ServingStations = ServingStations(w, ind),
|
||||
ServingLine = mine.Count > 0 ? mine[0].Id : LineId.None,
|
||||
ForSale = !ind.Owner.IsValid && !ind.Closed && ind.Level > 0,
|
||||
BuyUnlocked = buyUnlocked,
|
||||
BuyTier = buyTier?.Level ?? 0,
|
||||
BuyProgress = buyProgress,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Fattori dell'efficienza dell'industria e quello che la limita.</summary>
|
||||
public readonly record struct EfficiencyFactors(
|
||||
double ProfitFactor, double ConditionMultiplier, double Depletion, double EventCapacity, double ReserveFraction, bool Stopped, IndustryLimit Limit);
|
||||
|
||||
/// <summary>
|
||||
/// Fattori dell'efficienza come li usa la produzione (IndustrySystem): coperture medie, fattore di
|
||||
/// profitto, condizione degli impianti, giacimento, eventi; il limite è il fattore più basso sotto 1
|
||||
/// (a parità nell'ordine di <see cref="IndustryLimit"/>), Fermo se l'industria è ferma, Dormiente al
|
||||
/// livello 0 o chiusa.
|
||||
/// </summary>
|
||||
public static EfficiencyFactors Factors(World w, Industry ind)
|
||||
{
|
||||
var data = w.Data;
|
||||
double pf = IndustryMath.ProfitFactor(ind, data.Balance.Industry);
|
||||
double mc = IndustryMath.ConditionMultiplier(ind.Condition, data.Balance.IndustryMaintenance);
|
||||
double depletion = 1;
|
||||
double reserve = -1;
|
||||
if (ind.Def.Depletable && ind.Site.IsValid)
|
||||
{
|
||||
reserve = w.Sites[ind.Site.Value].ReserveFraction;
|
||||
double start = data.Balance.Industry.DepletionStartFraction;
|
||||
if (reserve < start) depletion = Math.Max(0, reserve) / start;
|
||||
}
|
||||
double capacity = w.WorldEvents.IndustryCapacity(ind.Id);
|
||||
bool stopped = ind.IsStopped(w.Clock.Day);
|
||||
IndustryLimit limit;
|
||||
if (ind.Closed || ind.Level <= 0) limit = IndustryLimit.Dormant;
|
||||
else if (stopped) limit = IndustryLimit.Stopped;
|
||||
else
|
||||
{
|
||||
limit = IndustryLimit.None;
|
||||
double least = 1;
|
||||
void Consider(IndustryLimit kind, double value)
|
||||
{
|
||||
if (value < least)
|
||||
{
|
||||
least = value;
|
||||
limit = kind;
|
||||
}
|
||||
}
|
||||
if (ind.Def.Recipe.Inputs.Count > 0) Consider(IndustryLimit.Inputs, ind.CovInput);
|
||||
if (ind.JobsWorkers > 0) Consider(IndustryLimit.Workers, ind.CovWorkers);
|
||||
if (ind.JobsStaff > 0) Consider(IndustryLimit.Staff, ind.CovStaff);
|
||||
Consider(IndustryLimit.Profit, pf);
|
||||
Consider(IndustryLimit.Condition, mc);
|
||||
Consider(IndustryLimit.Depletion, depletion);
|
||||
Consider(IndustryLimit.Event, capacity);
|
||||
}
|
||||
return new EfficiencyFactors(pf, mc, depletion, capacity, reserve, stopped, limit);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lavoratori o personale: presenti, persone in sede, posti scoperti con il motivo e provenienze per
|
||||
/// città e linea. Come il Registro degli impieghi (Projection.Employment), la compagnia vede i
|
||||
/// contratti a piedi e quelli che trasporta lei; quelli degli altri vettori solo se l'industria è
|
||||
/// sua. Presenti e copertura restano quelli dell'industria.
|
||||
/// </summary>
|
||||
public static WorkforceOutlook Workforce(World w, Industry ind, PaxClass cls, CompanyId company)
|
||||
{
|
||||
var ib = w.Data.Balance.Industry;
|
||||
bool staff = cls == PaxClass.Staff;
|
||||
int jobs = staff ? ind.JobsStaff : ind.JobsWorkers;
|
||||
double present = staff ? ind.StaffPresent : ind.WorkersPresent;
|
||||
var me = WorkplaceRef.Of(ind.Id);
|
||||
// contratti raggruppati per città, primo tratto, vettore e modo (a piedi o in treno), nell'ordine dei contratti
|
||||
var groups = new List<(TownId Town, LineId Line, CompanyId Carrier, bool Walking, int Headcount, double CoverageSum, double MinutesSum)>();
|
||||
double railPeople = 0, railMinutes = 0;
|
||||
foreach (var c in w.Commutes)
|
||||
{
|
||||
if (c.Workplace != me || c.Category != cls || c.Headcount <= 0) continue;
|
||||
if (!Visible(c, ind, company)) continue;
|
||||
var line = c.Route.Count > 0 ? c.Route[0] : LineId.None;
|
||||
int at = groups.FindIndex(x => x.Town == c.Town && x.Line == line && x.Carrier == c.Carrier && x.Walking == c.Walking);
|
||||
if (at < 0)
|
||||
{
|
||||
groups.Add((c.Town, line, c.Carrier, c.Walking, 0, 0, 0));
|
||||
at = groups.Count - 1;
|
||||
}
|
||||
var gr = groups[at];
|
||||
groups[at] = gr with
|
||||
{
|
||||
Headcount = gr.Headcount + c.Headcount,
|
||||
CoverageSum = gr.CoverageSum + c.Coverage * c.Headcount,
|
||||
MinutesSum = gr.MinutesSum + c.ExpectedMinutes * c.Headcount,
|
||||
};
|
||||
if (!c.Walking)
|
||||
{
|
||||
railPeople += c.Headcount;
|
||||
railMinutes += c.ExpectedMinutes * c.Headcount;
|
||||
}
|
||||
}
|
||||
var sources = groups
|
||||
.Select(x => new WorkforceSource(x.Town, x.Headcount, x.CoverageSum / x.Headcount, x.Line, x.Carrier, x.MinutesSum / x.Headcount, x.Walking))
|
||||
.OrderByDescending(s => s.Headcount).ThenBy(s => s.Town.Value).ThenBy(s => s.Line.Value).ThenBy(s => s.Carrier.Value).ThenBy(s => s.Walking)
|
||||
.Take(ib.Outlook.WorkforceSources).ToList();
|
||||
return new WorkforceOutlook
|
||||
{
|
||||
Jobs = jobs,
|
||||
Present = present,
|
||||
OnSite = EmploymentSystem.OnSite(jobs, staff ? ib.OnSiteStaffShare : ib.OnSiteWorkerShare),
|
||||
Coverage = staff ? ind.CovStaff : ind.CovWorkers,
|
||||
Missing = (int)Math.Max(0, Math.Round(jobs - present, MidpointRounding.AwayFromZero)),
|
||||
Reason = staff ? ind.StaffReason : ind.WorkersReason,
|
||||
ReasonLine = staff ? ind.StaffReasonLine : ind.WorkersReasonLine,
|
||||
AverageMinutes = railPeople > 0 ? railMinutes / railPeople : -1,
|
||||
Sources = sources,
|
||||
SourceCount = groups.Count,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Contratto che la compagnia può vedere: a piedi, trasportato da lei, o verso una sua industria.</summary>
|
||||
public static bool Visible(CommuteContract c, Industry ind, CompanyId company) =>
|
||||
c.Walking || (company.IsValid && (c.Carrier == company || ind.Owner == company));
|
||||
|
||||
/// <summary>
|
||||
/// Fornitori di un input: industrie attive che producono il bene (unità al mese al ritmo attuale,
|
||||
/// prezzo globale: le industrie vendono al mercato, ADR 0004) e hub (capacità mensile, prezzo
|
||||
/// d'importazione). Prima i collegati da una linea della compagnia, poi i più vicini.
|
||||
/// </summary>
|
||||
private static List<ChainPartner> Suppliers(World w, Industry ind, int good, LineLinks links, List<Line> mine)
|
||||
{
|
||||
int dpm = w.Calendar.DaysPerMonth;
|
||||
double pg = w.Market.GlobalPrice[good];
|
||||
var all = new List<ChainPartner>();
|
||||
foreach (var other in w.Industries)
|
||||
{
|
||||
if (other.Id == ind.Id || other.Closed || other.Level <= 0) continue;
|
||||
int o = other.OutputIndexOf(good);
|
||||
if (o < 0) continue;
|
||||
double month = other.CyclesPerDayAtFullCapacity(dpm) * other.Def.Recipe.Outputs[o].PerCycle * dpm * other.Efficiency;
|
||||
all.Add(new ChainPartner(ChainPartnerKind.Industry, other.Id.Value, month, pg, links.Link(mine, ChainPartnerKind.Industry, other.Id.Value), Km(ind.Position, other.Position)));
|
||||
}
|
||||
foreach (var h in w.Hubs)
|
||||
all.Add(new ChainPartner(ChainPartnerKind.Hub, h.Id.Value, h.MonthlyCapacity, h.SellPrice(pg), links.Link(mine, ChainPartnerKind.Hub, h.Id.Value), Km(ind.Position, h.Position)));
|
||||
return Pick(w, all);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clienti di un output: industrie attive che lo consumano (fabbisogno al mese a piena capacità,
|
||||
/// prezzo locale dell'ADR 0004 come «Dove conviene vendere»), hub (prezzo d'esportazione) e città con
|
||||
/// domanda del bene (domanda al mese, prezzo globale). Prima i collegati, poi i più vicini.
|
||||
/// </summary>
|
||||
private static List<ChainPartner> Customers(World w, Industry ind, int good, LineLinks links, List<Line> mine)
|
||||
{
|
||||
int dpm = w.Calendar.DaysPerMonth;
|
||||
double pg = w.Market.GlobalPrice[good];
|
||||
var lp = w.Data.Balance.LocalPrice;
|
||||
var all = new List<ChainPartner>();
|
||||
foreach (var other in w.Industries)
|
||||
{
|
||||
if (other.Id == ind.Id || other.Closed || other.Level <= 0) continue;
|
||||
int i = other.InputIndexOf(good);
|
||||
if (i < 0) continue;
|
||||
double month = other.CyclesPerDayAtFullCapacity(dpm) * other.Def.Recipe.Inputs[i].PerCycle * dpm;
|
||||
double price = Market.LocalPrice(pg, IndustryMath.InputCapacity(other, i, dpm), other.InputStock[i], lp);
|
||||
all.Add(new ChainPartner(ChainPartnerKind.Industry, other.Id.Value, month, price, links.Link(mine, ChainPartnerKind.Industry, other.Id.Value), Km(ind.Position, other.Position)));
|
||||
}
|
||||
foreach (var h in w.Hubs)
|
||||
all.Add(new ChainPartner(ChainPartnerKind.Hub, h.Id.Value, h.MonthlyCapacity, h.BuyPrice(pg), links.Link(mine, ChainPartnerKind.Hub, h.Id.Value), Km(ind.Position, h.Position)));
|
||||
foreach (var t in w.Towns)
|
||||
{
|
||||
if (t.DemandToday.Length <= good || t.DemandToday[good] <= 0) continue;
|
||||
all.Add(new ChainPartner(ChainPartnerKind.Town, t.Id.Value, t.DemandToday[good] * dpm, pg, links.Link(mine, ChainPartnerKind.Town, t.Id.Value), Km(ind.Position, t.Position)));
|
||||
}
|
||||
return Pick(w, all);
|
||||
}
|
||||
|
||||
/// <summary>Prima i collegati (per linea), poi i più vicini; a parità tipo e id; al massimo partnersPerGood.</summary>
|
||||
private static List<ChainPartner> Pick(World w, List<ChainPartner> all) =>
|
||||
all.OrderBy(p => p.Line.IsValid ? 0 : 1).ThenBy(p => p.DistanceKm).ThenBy(p => p.Kind).ThenBy(p => p.Target)
|
||||
.Take(w.Data.Balance.Industry.Outlook.PartnersPerGood).ToList();
|
||||
|
||||
private static double Km(Vec2 a, Vec2 b) => Vec2.Distance(a, b) / 1000;
|
||||
|
||||
/// <summary>Stazioni vive (di qualunque compagnia) con l'industria nel bacino e fermata di una linea con treni.</summary>
|
||||
public static List<StationId> ServingStations(World w, Industry ind)
|
||||
{
|
||||
var lineHasTrain = new bool[w.Lines.Count];
|
||||
foreach (var t in w.Trains)
|
||||
{
|
||||
if (!t.Removed && t.Line.IsValid && t.Line.Value < lineHasTrain.Length) lineHasTrain[t.Line.Value] = true;
|
||||
}
|
||||
var served = new bool[w.Network.Stations.Count];
|
||||
foreach (var l in w.Lines)
|
||||
{
|
||||
if (l.Removed || !lineHasTrain[l.Id.Value]) continue;
|
||||
foreach (var stop in l.Stops)
|
||||
{
|
||||
int s = stop.Station.Value;
|
||||
if (s >= 0 && s < served.Length) served[s] = true;
|
||||
}
|
||||
}
|
||||
var result = new List<StationId>();
|
||||
foreach (var s in w.Network.Stations)
|
||||
{
|
||||
if (served[s.Id.Value] && w.Network.IsAlive(s) && s.Industries.Contains(ind.Id)) result.Add(s.Id);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Linee della compagnia con almeno un treno e ciò che raggiungono: industrie, hub e città nel
|
||||
/// bacino delle loro fermate (stazioni vive). Una linea collega due nodi se li raggiunge entrambi.
|
||||
/// </summary>
|
||||
private sealed class LineLinks
|
||||
{
|
||||
private readonly List<(Line Line, HashSet<int> Industries, HashSet<int> Hubs, HashSet<int> Towns)> _lines = [];
|
||||
|
||||
public LineLinks(World w, CompanyId company)
|
||||
{
|
||||
if (!company.IsValid) return;
|
||||
var lineHasTrain = new bool[w.Lines.Count];
|
||||
foreach (var t in w.Trains)
|
||||
{
|
||||
if (t.Owner == company && !t.Removed && t.Line.IsValid && t.Line.Value < lineHasTrain.Length) lineHasTrain[t.Line.Value] = true;
|
||||
}
|
||||
foreach (var l in w.Lines)
|
||||
{
|
||||
if (l.Owner != company || l.Removed || !lineHasTrain[l.Id.Value]) continue;
|
||||
var industries = new HashSet<int>();
|
||||
var hubs = new HashSet<int>();
|
||||
var towns = new HashSet<int>();
|
||||
foreach (var stop in l.Stops)
|
||||
{
|
||||
int s = stop.Station.Value;
|
||||
if (s < 0 || s >= w.Network.Stations.Count) continue;
|
||||
var station = w.Network.Stations[s];
|
||||
if (!w.Network.IsAlive(station)) continue;
|
||||
foreach (var i in station.Industries) industries.Add(i.Value);
|
||||
foreach (var h in station.Hubs) hubs.Add(h.Value);
|
||||
foreach (var t in station.Towns) towns.Add(t.Value);
|
||||
}
|
||||
_lines.Add((l, industries, hubs, towns));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Linee che raggiungono l'industria, per id crescente.</summary>
|
||||
public List<Line> Serving(Industry ind) => _lines.Where(x => x.Industries.Contains(ind.Id.Value)).Select(x => x.Line).ToList();
|
||||
|
||||
/// <summary>Prima linea (id più basso) tra quelle dell'industria che raggiunge anche il nodo indicato.</summary>
|
||||
public LineId Link(List<Line> serving, ChainPartnerKind kind, int target)
|
||||
{
|
||||
foreach (var line in serving)
|
||||
{
|
||||
var entry = _lines.First(x => ReferenceEquals(x.Line, line));
|
||||
var set = kind switch
|
||||
{
|
||||
ChainPartnerKind.Industry => entry.Industries,
|
||||
ChainPartnerKind.Hub => entry.Hubs,
|
||||
_ => entry.Towns,
|
||||
};
|
||||
if (set.Contains(target)) return line.Id;
|
||||
}
|
||||
return LineId.None;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,11 +26,17 @@ public sealed class MoneyLedger(Func<CompanyId, Company> companies, Func<Industr
|
||||
/// <summary>Totale trasferito dall'inizio (statistica).</summary>
|
||||
public long TransfersCount { get; internal set; }
|
||||
|
||||
public void Transfer(Account from, Account to, Money amount, LedgerEntry entry)
|
||||
public void Transfer(Account from, Account to, Money amount, LedgerEntry entry) => Transfer(from, to, amount, entry, entry);
|
||||
|
||||
/// <summary>
|
||||
/// Trasferimento registrato su voci diverse per chi paga e chi incassa (per esempio dividendi pagati
|
||||
/// e dividendi incassati, ADR 0019): la somma dei saldi resta zero.
|
||||
/// </summary>
|
||||
public void Transfer(Account from, Account to, Money amount, LedgerEntry fromEntry, LedgerEntry toEntry)
|
||||
{
|
||||
if (amount.Cents == 0 || from == to) return;
|
||||
Adjust(from, -amount, entry);
|
||||
Adjust(to, amount, entry);
|
||||
Adjust(from, -amount, fromEntry);
|
||||
Adjust(to, amount, toEntry);
|
||||
TransfersCount++;
|
||||
}
|
||||
|
||||
|
||||
@@ -59,14 +59,37 @@ public sealed class Market
|
||||
public static double WorldFactor(MarketBalance m, double volatility, double yearsElapsed, double shock) =>
|
||||
m.World.Amplitude * volatility * DMath.Sin(DMath.TwoPi * yearsElapsed / m.World.PeriodYears) + shock;
|
||||
|
||||
/// <summary>
|
||||
/// Passo giornaliero del prezzo globale (guida 6.3, ADR 0004), senza stato: lo usa MarketSystem e lo
|
||||
/// rifà la spiegazione del prezzo (ADR 0024) con gli stessi ingressi. <paramref name="pg"/> è il prezzo
|
||||
/// di ieri, <paramref name="demand"/> e <paramref name="supply"/> le somme della finestra di 30 giorni,
|
||||
/// <paramref name="windowCount"/> i giorni presenti nella finestra.
|
||||
/// </summary>
|
||||
public static GlobalPriceStep NextPrice(MarketBalance m, double pb, double pg, double demand, double supply, int windowCount,
|
||||
double volatility, double years, double shock)
|
||||
{
|
||||
double pw = pb * Math.Max(m.World.PriceFloor, 1 + WorldFactor(m, volatility, years, shock));
|
||||
double v = Math.Max(m.World.BaselinePerDay * windowCount, m.World.VolumeShare * (demand + supply) / 2);
|
||||
double dTot = demand + v * DMath.Pow(pw / pg, m.World.Elasticity);
|
||||
double sTot = supply + v * DMath.Pow(pg / pw, m.World.Elasticity);
|
||||
double ratio = DMath.Clamp(dTot / Math.Max(1e-9, sTot), m.RatioMin, m.RatioMax);
|
||||
double target = DMath.Clamp(pg * (1 + m.K * (ratio - 1)), m.MinPriceFactor * pb, m.MaxPriceFactor * pb);
|
||||
double next = m.Alpha * target + (1 - m.Alpha) * pg;
|
||||
return new GlobalPriceStep(pg, pb, pw, demand, supply, v, dTot, sTot, ratio, target, next);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Prezzo locale al nodo: Pl = Pg·(1 + λ·(Dl − Sl)/(Dl + Sl + ε)), entro ±maxDeviation.
|
||||
/// </summary>
|
||||
public static double LocalPrice(double globalPrice, double localDemand, double localSupply, LocalPriceBalance p)
|
||||
public static double LocalPrice(double globalPrice, double localDemand, double localSupply, LocalPriceBalance p) =>
|
||||
LocalPriceTerms(globalPrice, localDemand, localSupply, p).Price;
|
||||
|
||||
/// <summary>Prezzo locale con i suoi termini: squilibrio (Dl − Sl)/(Dl + Sl + ε) e fattore limitato.</summary>
|
||||
public static LocalPriceStep LocalPriceTerms(double globalPrice, double localDemand, double localSupply, LocalPriceBalance p)
|
||||
{
|
||||
double imbalance = (localDemand - localSupply) / (localDemand + localSupply + p.Epsilon);
|
||||
double factor = Math.Clamp(1 + p.Lambda * imbalance, 1 - p.MaxDeviation, 1 + p.MaxDeviation);
|
||||
return globalPrice * factor;
|
||||
return new LocalPriceStep(globalPrice, localDemand, localSupply, imbalance, factor, globalPrice * factor);
|
||||
}
|
||||
|
||||
internal void Restore(RollingWindow[] demand, RollingWindow[] supply, RollingWindow[] history)
|
||||
@@ -77,6 +100,23 @@ public sealed class Market
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Termini di un passo del prezzo globale: prezzo di ieri, base, prezzo mondiale Pw = Pb·max(pavimento, 1 + W(t)),
|
||||
/// domanda e offerta della finestra, volume mondiale V, domanda e offerta con il resto del mondo, rapporto
|
||||
/// limitato, prezzo obiettivo Pg′ e prezzo nuovo α·Pg′ + (1 − α)·Pg.
|
||||
/// </summary>
|
||||
public readonly record struct GlobalPriceStep(double Previous, double BasePrice, double WorldPrice, double Demand, double Supply,
|
||||
double WorldVolume, double DemandTotal, double SupplyTotal, double Ratio, double Target, double Price);
|
||||
|
||||
/// <summary>Termini del prezzo locale: Pg, Dl, Sl, squilibrio, fattore limitato e prezzo.</summary>
|
||||
public readonly record struct LocalPriceStep(double GlobalPrice, double LocalDemand, double LocalSupply, double Imbalance, double Factor, double Price);
|
||||
|
||||
/// <summary>
|
||||
/// Termini di una tariffa: fattore del prezzo (merci; 1 per i passeggeri), fattore della distanza km^esponente,
|
||||
/// classe (passeggeri; 1 per le merci), puntualità tf, centesimi non arrotondati e tariffa arrotondata.
|
||||
/// </summary>
|
||||
public readonly record struct TariffTerms(double PriceFactor, double KmFactor, double ClassFactor, double Lateness, double Cents, Money Fare);
|
||||
|
||||
/// <summary>Tariffe del vettore (guida 6.3).</summary>
|
||||
public static class Tariffs
|
||||
{
|
||||
@@ -85,24 +125,36 @@ public static class Tariffs
|
||||
/// tf scende linearmente da 1 a 0,5 quando la consegna supera del 50 % il tempo atteso.
|
||||
/// </summary>
|
||||
public static Money Freight(int units, double km, double globalPrice, double basePrice, double actualDays, double expectedDays,
|
||||
TariffBalance t, double difficultyMultiplier) =>
|
||||
FreightTerms(units, km, globalPrice, basePrice, actualDays, expectedDays, t, difficultyMultiplier).Fare;
|
||||
|
||||
/// <summary>Tariffa merci con i suoi termini (la formula di <see cref="Freight"/>, una sola fonte).</summary>
|
||||
public static TariffTerms FreightTerms(int units, double km, double globalPrice, double basePrice, double actualDays, double expectedDays,
|
||||
TariffBalance t, double difficultyMultiplier)
|
||||
{
|
||||
if (units <= 0 || km <= 0) return Money.Zero;
|
||||
double priceFactor = t.FreightFixedWeight + t.FreightPriceWeight * globalPrice / basePrice;
|
||||
double cents = units * t.FreightBaseRate * priceFactor * DMath.Pow(km, t.FreightKmExponent)
|
||||
* LatenessFactor(actualDays, expectedDays, t) * difficultyMultiplier;
|
||||
return Money.FromCentsRounded(cents);
|
||||
double kmFactor = km > 0 ? DMath.Pow(km, t.FreightKmExponent) : 0;
|
||||
double tf = LatenessFactor(actualDays, expectedDays, t);
|
||||
if (units <= 0 || km <= 0) return new TariffTerms(priceFactor, kmFactor, 1, tf, 0, Money.Zero);
|
||||
double cents = units * t.FreightBaseRate * priceFactor * kmFactor * tf * difficultyMultiplier;
|
||||
return new TariffTerms(priceFactor, kmFactor, 1, tf, cents, Money.FromCentsRounded(cents));
|
||||
}
|
||||
|
||||
/// <summary>Passeggeri: posti × tariffa base × km^0,85 × classe × puntualità × difficoltà.</summary>
|
||||
public static Money Passenger(int pax, double km, PaxClass paxClass, double actualDays, double expectedDays,
|
||||
TariffBalance t, double difficultyMultiplier, double comfort = 1.0) =>
|
||||
PassengerTerms(pax, km, paxClass, actualDays, expectedDays, t, difficultyMultiplier, comfort).Fare;
|
||||
|
||||
/// <summary>Tariffa passeggeri con i suoi termini (la formula di <see cref="Passenger"/>, una sola fonte).</summary>
|
||||
public static TariffTerms PassengerTerms(int pax, double km, PaxClass paxClass, double actualDays, double expectedDays,
|
||||
TariffBalance t, double difficultyMultiplier, double comfort = 1.0)
|
||||
{
|
||||
if (pax <= 0 || km <= 0) return Money.Zero;
|
||||
double cls = t.ClassMultipliers[paxClass == PaxClass.Staff ? "staff" : "worker"];
|
||||
double cents = pax * t.PaxBaseFare * DMath.Pow(km, t.PaxKmExponent) * cls
|
||||
* LatenessFactor(actualDays, expectedDays, t) * difficultyMultiplier * comfort;
|
||||
return Money.FromCentsRounded(cents);
|
||||
double kmFactor = km > 0 ? DMath.Pow(km, t.PaxKmExponent) : 0;
|
||||
double tf = LatenessFactor(actualDays, expectedDays, t);
|
||||
if (pax <= 0 || km <= 0) return new TariffTerms(1, kmFactor, cls, tf, 0, Money.Zero);
|
||||
double cents = pax * t.PaxBaseFare * kmFactor * cls * tf * difficultyMultiplier * comfort;
|
||||
return new TariffTerms(1, kmFactor, cls, tf, cents, Money.FromCentsRounded(cents));
|
||||
}
|
||||
|
||||
/// <summary>Fattore di puntualità: 1 entro la soglia, poi cala fino al minimo.</summary>
|
||||
|
||||
@@ -60,7 +60,7 @@ public sealed class TradingProgress
|
||||
public required bool Unlocked { get; init; }
|
||||
/// <summary>Livello che sblocca il commercio (0 se nessuno).</summary>
|
||||
public required int Level { get; init; }
|
||||
/// <summary>Minimo tra le frazioni dei requisiti numerici (patrimonio, città collegate), in [0, 1].</summary>
|
||||
/// <summary>Avanzamento verso il livello (media delle frazioni dei tre requisiti, ADR 0018), in [0, 1].</summary>
|
||||
public required double Fraction { get; init; }
|
||||
public required Money NetWorth { get; init; }
|
||||
public required Money NetWorthRequired { get; init; }
|
||||
@@ -413,24 +413,22 @@ public static class MarketOutlook
|
||||
Rating = c?.Rating ?? CreditRating.D, RatingRequired = r?.CreditRating ?? CreditRating.D, RatingMet = false,
|
||||
};
|
||||
}
|
||||
var req = target.Requirements;
|
||||
int towns = Tiers.ConnectedTowns(w, c.Id, req.ConnectedTownsOver.Population);
|
||||
double worth = req.NetWorth <= 0 ? 1 : DMath.Clamp((double)c.NetWorth.Cents / req.NetWorth, 0, 1);
|
||||
double townsFraction = req.ConnectedTownsOver.Count <= 0 ? 1 : DMath.Clamp((double)towns / req.ConnectedTownsOver.Count, 0, 1);
|
||||
// stessi requisiti e stesso avanzamento del pannello «La tua scalata» (ADR 0018)
|
||||
var progress = ClimbOutlook.Requirements(w, c, target);
|
||||
bool unlocked = Tiers.Unlocks(w, c).Trading;
|
||||
return new TradingProgress
|
||||
{
|
||||
Unlocked = unlocked,
|
||||
Level = target.Level,
|
||||
Fraction = unlocked ? 1 : Math.Min(worth, townsFraction),
|
||||
NetWorth = c.NetWorth,
|
||||
NetWorthRequired = new Money(req.NetWorth),
|
||||
TownsConnected = towns,
|
||||
TownsRequired = req.ConnectedTownsOver.Count,
|
||||
TownPopulation = req.ConnectedTownsOver.Population,
|
||||
Rating = c.Rating,
|
||||
RatingRequired = req.CreditRating,
|
||||
RatingMet = c.Rating <= req.CreditRating,
|
||||
Fraction = unlocked ? 1 : progress.Progress,
|
||||
NetWorth = progress.NetWorth,
|
||||
NetWorthRequired = progress.NetWorthRequired,
|
||||
TownsConnected = progress.Towns,
|
||||
TownsRequired = progress.TownsRequired,
|
||||
TownPopulation = progress.TownPopulation,
|
||||
Rating = progress.Rating,
|
||||
RatingRequired = progress.RatingRequired,
|
||||
RatingMet = progress.RatingMet,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
namespace RailEnterprise.Core.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// Stato patrimoniale delle compagnie (corpo del salvataggio dalla versione 6, ADR 0018): valore
|
||||
/// contabile degli attivi per voce (<see cref="AssetCategory"/>) e giorno in cui ogni livello è stato
|
||||
/// raggiunto. Entra nell'hash giornaliero con lo stato dinamico. Le versioni precedenti salvano solo
|
||||
/// il totale degli attivi: <see cref="Migrate"/> lo ripartisce senza cambiarlo.
|
||||
/// </summary>
|
||||
public static class BalanceSheetSerializer
|
||||
{
|
||||
public static void Write(World w, SaveWriter s)
|
||||
{
|
||||
s.Write(w.Companies.Count);
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
s.Write(c.BookValues);
|
||||
s.Write(c.TierReachedDay);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Read(World w, SaveReader r)
|
||||
{
|
||||
int n = r.ReadInt32();
|
||||
if (n != w.Companies.Count) throw new InvalidDataException($"Stato patrimoniale di {n} compagnie su {w.Companies.Count}");
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
CopyInto(r.ReadInt64Array(), c.BookValues);
|
||||
CopyInto(r.ReadInt64Array(), c.TierReachedDay);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Migrazione dalle versioni 1–5: il totale salvato (letto nella voce dei binari) si ripartisce in
|
||||
/// proporzione alla scomposizione calcolata al giorno del caricamento, con il resto dell'arrotondamento
|
||||
/// sulla voce più grande; il totale, e quindi il patrimonio netto, non cambia fino al ricalcolo del
|
||||
/// mese. I giorni dei livelli si ricostruiscono dai fatti salienti («diventa «nome»») e, in mancanza,
|
||||
/// dallo storico annuale (giorno della prima fotografia con il livello, tra fondazione e oggi).
|
||||
/// </summary>
|
||||
public static void Migrate(World w)
|
||||
{
|
||||
var live = FinanceSystem.BookValues(w);
|
||||
for (int i = 0; i < w.Companies.Count; i++)
|
||||
{
|
||||
var c = w.Companies[i];
|
||||
long total = c.AssetBookValue.Cents;
|
||||
Array.Clear(c.BookValues);
|
||||
long liveSum = 0;
|
||||
foreach (long v in live[i]) liveSum += v;
|
||||
if (total != 0 && liveSum > 0)
|
||||
{
|
||||
long assigned = 0;
|
||||
int largest = 0;
|
||||
for (int k = 0; k < AssetCategories.Count; k++)
|
||||
{
|
||||
c.BookValues[k] = (long)((Int128)total * live[i][k] / liveSum);
|
||||
assigned += c.BookValues[k];
|
||||
if (live[i][k] > live[i][largest]) largest = k;
|
||||
}
|
||||
c.BookValues[largest] += total - assigned;
|
||||
}
|
||||
else
|
||||
{
|
||||
c.BookValues[(int)AssetCategory.Track] = total;
|
||||
}
|
||||
RebuildTierDays(w, c);
|
||||
}
|
||||
}
|
||||
|
||||
private static void RebuildTierDays(World w, Company c)
|
||||
{
|
||||
Array.Fill(c.TierReachedDay, -1L);
|
||||
var tiers = w.Data.Tiers.Tiers;
|
||||
for (int level = 2; level <= Math.Min(c.Tier, c.TierReachedDay.Length); level++)
|
||||
{
|
||||
string text = $"diventa «{tiers[level - 1].NameIt}»";
|
||||
long day = c.Milestones.FirstOrDefault(m => m.Text == text, new CompanyMilestone(-1, "")).Day;
|
||||
if (day < 0)
|
||||
{
|
||||
// la fotografia dell'anno Y si scatta il primo giorno di Y+1, dopo la chiusura del mese che
|
||||
// può aver promosso la compagnia: il livello è certo solo da quel giorno (come ClimbOutlook.History)
|
||||
int year = c.History.FirstOrDefault(y => y.Tier >= level, new CompanyYear(int.MinValue, 0, 0, 0, 0, 0, 0, 0, 0)).Year;
|
||||
if (year != int.MinValue)
|
||||
day = Math.Clamp((long)(year + 1 - w.Calendar.StartYear) * w.Calendar.DaysPerYear, Math.Max(0, c.FoundedDay), Math.Max(c.FoundedDay, w.Clock.Day));
|
||||
}
|
||||
c.TierReachedDay[level - 1] = day;
|
||||
}
|
||||
}
|
||||
|
||||
private static void CopyInto(long[] source, long[] target) =>
|
||||
Array.Copy(source, target, Math.Min(source.Length, target.Length));
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
|
||||
namespace RailEnterprise.Core.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// Conti delle compagnie (corpo del salvataggio dalla versione 7, ADR 0019): mesi e anni chiusi per voce
|
||||
/// del registro e misure dell'ultimo calcolo del rating. Entra nell'hash giornaliero con lo stato
|
||||
/// dinamico. Le versioni precedenti non hanno i mesi chiusi: <see cref="Migrate"/> parte da zero mesi
|
||||
/// e recupera l'ultimo anno chiuso.
|
||||
/// </summary>
|
||||
public static class FinanceSerializer
|
||||
{
|
||||
public static void Write(World w, SaveWriter s)
|
||||
{
|
||||
s.Write(w.Companies.Count);
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
WriteRecords(c.IncomeMonths, s);
|
||||
WriteRecords(c.IncomeYears, s);
|
||||
s.Write(c.RatingMargin);
|
||||
s.Write(c.RatingLeverage);
|
||||
s.Write(c.RatingScore);
|
||||
s.Write(c.RatingMonths);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Read(World w, SaveReader r)
|
||||
{
|
||||
int n = r.ReadInt32();
|
||||
if (n != w.Companies.Count) throw new InvalidDataException($"Conti di {n} compagnie su {w.Companies.Count}");
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
ReadRecords(c.IncomeMonths, r);
|
||||
ReadRecords(c.IncomeYears, r);
|
||||
c.RatingMargin = r.ReadDouble();
|
||||
c.RatingLeverage = r.ReadDouble();
|
||||
c.RatingScore = r.ReadDouble();
|
||||
c.RatingMonths = r.ReadInt32();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Migrazione dalle versioni 1–6: nessun mese chiuso conservato (il conto economico mensile e la
|
||||
/// finestra del rating si riempiono dal mese dopo il caricamento); l'ultimo anno chiuso, se c'è, entra
|
||||
/// negli anni; il rating resta quello salvato e la sua spiegazione usa le misure del giorno fino al
|
||||
/// primo calcolo mensile (<see cref="Company.RatingMonths"/> = 0).
|
||||
/// </summary>
|
||||
public static void Migrate(World w)
|
||||
{
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
c.IncomeMonths.Clear();
|
||||
c.IncomeYears.Clear();
|
||||
long yearStart = (long)(w.Clock.Year - w.Calendar.StartYear) * w.Calendar.DaysPerYear;
|
||||
bool closedYear = w.Clock.Year > w.Calendar.StartYear && c.FoundedDay < yearStart;
|
||||
if (closedYear && c.LastYearEntries.Any(v => v != 0))
|
||||
c.IncomeYears.Add(new IncomeRecord { Year = w.Clock.Year - 1, Month = 0, Entries = (long[])c.LastYearEntries.Clone() });
|
||||
c.RatingMargin = 0;
|
||||
c.RatingLeverage = 0;
|
||||
c.RatingScore = 0;
|
||||
c.RatingMonths = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static void WriteRecords(List<IncomeRecord> records, SaveWriter s)
|
||||
{
|
||||
s.Write(records.Count);
|
||||
foreach (var m in records)
|
||||
{
|
||||
s.Write(m.Year);
|
||||
s.Write(m.Month);
|
||||
s.Write(m.Entries);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ReadRecords(List<IncomeRecord> into, SaveReader r)
|
||||
{
|
||||
into.Clear();
|
||||
int n = r.ReadInt32();
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
int year = r.ReadInt32();
|
||||
int month = r.ReadInt32();
|
||||
var source = r.ReadInt64Array();
|
||||
// le voci aggiunte dopo il salvataggio partono da zero
|
||||
var entries = new long[Company.EntryCount];
|
||||
Array.Copy(source, entries, Math.Min(source.Length, entries.Length));
|
||||
into.Add(new IncomeRecord { Year = year, Month = month, Entries = entries });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ namespace RailEnterprise.Core.Persistence;
|
||||
public static class WorldSerializer
|
||||
{
|
||||
/// <summary>Versione del corpo del salvataggio (migrazioni in <see cref="Read"/>).</summary>
|
||||
public const int BodyVersion = 5;
|
||||
public const int BodyVersion = 7;
|
||||
|
||||
/// <summary>Scrive l'intero mondo (impostazioni, terreno, stato dinamico, eventi).</summary>
|
||||
public static void Write(World w, SaveWriter s) => Write(w, s, BodyVersion);
|
||||
@@ -247,6 +247,8 @@ public static class WorldSerializer
|
||||
if (version >= 3) CorporateSerializer.Write(w, s);
|
||||
if (version >= 4) TradingSerializer.Write(w, s);
|
||||
if (version >= 5) EventSerializer.Write(w, s);
|
||||
if (version >= 6) BalanceSheetSerializer.Write(w, s);
|
||||
if (version >= 7) FinanceSerializer.Write(w, s);
|
||||
}
|
||||
|
||||
private static void WriteRecipeStock(List<RecipeItemDef> items, int[] stock, SaveWriter s)
|
||||
@@ -641,7 +643,8 @@ public static class WorldSerializer
|
||||
CopyInto(r.ReadInt64Array(), c.MonthEntries);
|
||||
CopyInto(r.ReadInt64Array(), c.YearEntries);
|
||||
CopyInto(r.ReadInt64Array(), c.LastYearEntries);
|
||||
c.AssetBookValue = new Money(r.ReadInt64());
|
||||
// totale degli attivi: dalla versione 6 lo sostituisce la scomposizione per voce (BalanceSheetSerializer)
|
||||
c.BookValues[(int)AssetCategory.Track] = r.ReadInt64();
|
||||
int loans = r.ReadInt32();
|
||||
for (int k = 0; k < loans; k++)
|
||||
{
|
||||
@@ -707,6 +710,12 @@ public static class WorldSerializer
|
||||
else TradingSerializer.Migrate(w);
|
||||
// versione 5 (F6): eventi del mondo in corso; prima nessun evento attivo
|
||||
if (version >= 5) EventSerializer.Read(w, r);
|
||||
// versione 6 (F6): stato patrimoniale per voce e giorni dei livelli raggiunti
|
||||
if (version >= 6) BalanceSheetSerializer.Read(w, r);
|
||||
else BalanceSheetSerializer.Migrate(w);
|
||||
// versione 7 (F6): conto economico per mese e per anno, misure del rating (ADR 0019)
|
||||
if (version >= 7) FinanceSerializer.Read(w, r);
|
||||
else FinanceSerializer.Migrate(w);
|
||||
}
|
||||
|
||||
private static void ReadRecipeStock(List<RecipeItemDef> items, int[] stock, SaveReader r)
|
||||
|
||||
@@ -27,14 +27,17 @@ internal sealed class AiAgent
|
||||
private readonly AiPlanningParams _plan;
|
||||
private readonly AiMarketParams _mk;
|
||||
private readonly GridPath _path;
|
||||
// un deposito in esercizio aspetta la sua linea dei ricambi e la cassa non basta ancora: questo mese
|
||||
// niente reti nuove (nuovi depositi), le linee che usano un deposito esistente restano possibili
|
||||
private bool _partsPending;
|
||||
|
||||
public AiAgent(World w, WorldContext ctx, AiState s, GridPath path)
|
||||
public AiAgent(World w, WorldContext ctx, AiState s, GridPath path, AiPersonalityDef? personality = null)
|
||||
{
|
||||
_w = w;
|
||||
_ctx = ctx;
|
||||
_s = s;
|
||||
_c = w.Company(s.Company);
|
||||
_p = w.Data.Ai.Personalities.FirstOrDefault(p => p.Id == _c.AiPersonality) ?? w.Data.Ai.Personalities[0];
|
||||
_p = personality ?? w.Data.Ai.Personalities.FirstOrDefault(p => p.Id == _c.AiPersonality) ?? w.Data.Ai.Personalities[0];
|
||||
_plan = w.Data.Ai.Planning;
|
||||
_mk = w.Data.Ai.Market;
|
||||
_path = path;
|
||||
@@ -192,10 +195,11 @@ internal sealed class AiAgent
|
||||
/// <summary>Compra locomotiva e carri nel deposito del progetto, compone il treno e lo assegna alla linea.</summary>
|
||||
private bool BuyTrain(AiProject project)
|
||||
{
|
||||
UpdateModels(project);
|
||||
var loco = _w.Data.Vehicle(project.Loco);
|
||||
var car = _w.Data.Vehicle(project.Car);
|
||||
long price = Estimators.TrainPrice(loco, car, project.CarsPerTrain);
|
||||
if (_c.Cash.Cents < price + Reserve() / 2 && !Borrow(price + Reserve() / 2 - _c.Cash.Cents, completing: project.Trains.Count == 0)) return false;
|
||||
if (FreeCash() < price + Reserve() / 2 && !Borrow(price + Reserve() / 2 - FreeCash(), completing: project.Trains.Count == 0)) return false;
|
||||
var ids = new List<VehicleId>();
|
||||
var rl = Do(new BuyVehicleCommand(project.Loco, project.Depot, 1));
|
||||
if (!rl.Ok) return false;
|
||||
@@ -211,6 +215,31 @@ internal sealed class AiAgent
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Modelli superati o fuori produzione (ADR 0020): la linea passa al successore consigliato appena il
|
||||
/// modello è superato, se il successore non ha trazione, potenza o velocità inferiori (comprarlo nuovo
|
||||
/// vorrebbe dire perdere subito valore, pagare di più la manutenzione e rinnovarlo dopo pochi anni)
|
||||
/// o, se è fuori produzione e la catena non offre un tale successore, al modello che l'IA sceglierebbe
|
||||
/// oggi per un progetto nuovo. Così i treni aggiuntivi non nascono superati.
|
||||
/// </summary>
|
||||
private void UpdateModels(AiProject project)
|
||||
{
|
||||
int year = _ctx.Year;
|
||||
var loco = _w.Data.Vehicle(project.Loco);
|
||||
var newLoco = Obsolescence.IsSuperseded(loco, year) && Obsolescence.Recommended(loco, year) is { } rec && Obsolescence.NoWorseThan(rec, loco) ? rec : null;
|
||||
if (newLoco is null && !Obsolescence.InProduction(loco, year)) newLoco = Estimators.BestLocomotive(_w, year);
|
||||
if (newLoco is not null) project.Loco = newLoco.Id;
|
||||
var car = _w.Data.Vehicle(project.Car);
|
||||
var newCar = Obsolescence.IsSuperseded(car, year) && Obsolescence.Recommended(car, year) is { } recCar && Obsolescence.NoWorseThan(recCar, car) ? recCar : null;
|
||||
if (newCar is null && !Obsolescence.InProduction(car, year))
|
||||
{
|
||||
newCar = car.Kind == VehicleKind.Coach
|
||||
? Estimators.CoachFor(_w, car.Class ?? PaxClass.Worker, year)
|
||||
: project.Good >= 0 ? Estimators.WagonFor(_w, project.Good, year) : null;
|
||||
}
|
||||
if (newCar is not null) project.Car = newCar.Id;
|
||||
}
|
||||
|
||||
// ================================================================== mensile
|
||||
|
||||
public void Monthly()
|
||||
@@ -240,9 +269,161 @@ internal sealed class AiAgent
|
||||
}
|
||||
Finance();
|
||||
GrowLines();
|
||||
RenewFleet();
|
||||
StockMarket();
|
||||
BuyIndustries();
|
||||
if (!EnsurePartsSupply()) NewProject();
|
||||
if (!EnsurePartsSupply())
|
||||
{
|
||||
if (_partsPending) _s.PartsBlockedMonths++;
|
||||
NewProject();
|
||||
}
|
||||
Trade();
|
||||
}
|
||||
|
||||
// ================================================================== compravendita in proprio (ADR 0016, 0025)
|
||||
|
||||
/// <summary>Occasione di compravendita: comprare un bene in una stazione e venderlo lì o in un'altra raggiungibile.</summary>
|
||||
private readonly record struct Deal(Station From, Station To, int Good, double BuyPrice, double SellPrice, int Units)
|
||||
{
|
||||
public double Profit => Units * (SellPrice - BuyPrice);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Compravendita in proprio (ADR 0016 §9, ADR 0025), dopo i progetti: le linee hanno la precedenza sulla
|
||||
/// cassa. Prima vende la merce dei propri magazzini a chi paga almeno trading.minSellPriceShare del prezzo
|
||||
/// globale; poi, se il livello lo sblocca, valuta per ogni stazione propria e bene in vendita nel bacino la
|
||||
/// destinazione migliore (la stazione stessa o una raggiungibile sulle proprie linee con i flag delle
|
||||
/// fermate) e, se il margine della prossima unità supera trading.minMargin, compra con un tetto e vende
|
||||
/// subito o spedisce. Regola deterministica: occasioni in ordine di utile atteso, poi stazione, bene e
|
||||
/// destinazione; al più trading.maxTradesPerMonth al mese, una per stazione e bene.
|
||||
/// </summary>
|
||||
private void Trade()
|
||||
{
|
||||
var t = _w.Data.Ai.Trading;
|
||||
if (!t.Enabled) return;
|
||||
var stations = new List<Station>();
|
||||
foreach (var st in _w.Network.Stations)
|
||||
{
|
||||
if (st.Owner == _c.Id && _w.Network.IsAlive(st)) stations.Add(st);
|
||||
}
|
||||
if (stations.Count == 0) return;
|
||||
SellStock(t, stations);
|
||||
if (t.MaxTradesPerMonth <= 0 || !Tiers.Unlocks(_w, _c).Trading) return;
|
||||
double budget = Math.Max(0, FreeCash() - Reserve() * t.CashReserveMultiple) * t.CashShare;
|
||||
if (budget <= 0) return;
|
||||
|
||||
var graph = _w.LineGraphs.For(_w, _c.Id);
|
||||
int[] reserved = TradingMath.ReservedByStation(_w);
|
||||
var deals = new List<Deal>();
|
||||
foreach (var from in stations)
|
||||
{
|
||||
int freeFrom = TradingMath.FreeSpace(_w, from, reserved[from.Id.Value]);
|
||||
if (freeFrom <= 0) continue;
|
||||
for (int g = 0; g < _w.Data.GoodCount; g++)
|
||||
{
|
||||
if (_w.Data.Goods[g].Era > _ctx.Year) continue;
|
||||
var sellers = TradingMath.Sellers(_w, from, g);
|
||||
if (TradingMath.CheapestSeller(_w, sellers, g, out double buy) is null || buy <= 0) continue;
|
||||
int available = 0;
|
||||
foreach (var x in sellers) available += x.Limit;
|
||||
int affordable = (int)Math.Min(int.MaxValue, budget / (buy * (1 + t.PriceSlack)));
|
||||
int cap = Math.Min(Math.Min(t.MaxUnits, available), Math.Min(freeFrom, affordable));
|
||||
if (cap <= 0) continue;
|
||||
Consider(deals, t, from, from, g, buy, cap);
|
||||
var reach = graph.From(from.Id, LineGraph.GoodCargo(g), stopFlags: true);
|
||||
if (reach.Count == 0) continue;
|
||||
var keys = new List<int>(reach.Keys);
|
||||
keys.Sort();
|
||||
foreach (int k in keys)
|
||||
{
|
||||
var to = _w.Network.Stations[k];
|
||||
if (to.Id == from.Id || to.Owner != _c.Id || !_w.Network.IsAlive(to)) continue;
|
||||
int freeTo = TradingMath.FreeSpace(_w, to, reserved[k]);
|
||||
if (freeTo > 0) Consider(deals, t, from, to, g, buy, Math.Min(cap, freeTo));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (deals.Count == 0) return;
|
||||
deals.Sort((a, b) =>
|
||||
a.Profit != b.Profit ? b.Profit.CompareTo(a.Profit)
|
||||
: a.From.Id.Value != b.From.Id.Value ? a.From.Id.Value.CompareTo(b.From.Id.Value)
|
||||
: a.Good != b.Good ? a.Good.CompareTo(b.Good)
|
||||
: a.To.Id.Value.CompareTo(b.To.Id.Value));
|
||||
int done = 0;
|
||||
var used = new List<(int Station, int Good)>();
|
||||
foreach (var d in deals)
|
||||
{
|
||||
if (done >= t.MaxTradesPerMonth) break;
|
||||
if (used.Contains((d.From.Id.Value, d.Good))) continue;
|
||||
used.Add((d.From.Id.Value, d.Good));
|
||||
string good = _w.Data.Goods[d.Good].Id;
|
||||
long maxPrice = (long)Math.Ceiling(d.BuyPrice * (1 + t.PriceSlack));
|
||||
if (FreeCash() < maxPrice) break;
|
||||
// il budget del mese (cashShare della cassa oltre la riserva) vale per tutti gli affari insieme
|
||||
int units = (int)Math.Min(d.Units, budget / maxPrice);
|
||||
if (units <= 0) continue;
|
||||
if (d.To.Id == d.From.Id)
|
||||
{
|
||||
// un affare precedente può aver riempito un compratore comune a due stazioni vicine
|
||||
int room = 0;
|
||||
foreach (var b in TradingMath.Buyers(_w, d.From, d.Good))
|
||||
{
|
||||
if (b.Kind == TradePartyKind.Industry || d.From.Hubs.Count == 0) room += b.Limit;
|
||||
}
|
||||
units = Math.Min(units, room);
|
||||
if (units <= 0) continue;
|
||||
}
|
||||
int before = d.From.StockOf(d.Good);
|
||||
long cashBefore = _c.Cash.Cents;
|
||||
if (!Do(new BuyGoodsCommand(d.From.Id, good, units, new Money(maxPrice))).Ok) continue;
|
||||
budget -= cashBefore - _c.Cash.Cents;
|
||||
int bought = d.From.StockOf(d.Good) - before;
|
||||
if (bought <= 0) continue;
|
||||
done++;
|
||||
_s.Trades++;
|
||||
if (d.To.Id == d.From.Id)
|
||||
Do(new SellGoodsCommand(d.From.Id, good, bought, new Money((long)Math.Floor(d.SellPrice * (1 - t.PriceSlack)))));
|
||||
else
|
||||
Do(new ShipGoodsCommand(d.From.Id, d.To.Id, good, bought));
|
||||
AiSystem.Trace?.Invoke($"{_ctx.Day} {_c.Name}: COMMERCIO {bought} {good} a {d.From.Name} ({d.BuyPrice / 100:0.00}) → {d.To.Name} ({d.SellPrice / 100:0.00})");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Aggiunge l'occasione se i compratori della destinazione pagano la prossima unità con il margine minimo.</summary>
|
||||
private void Consider(List<Deal> deals, AiTradingParams t, Station from, Station to, int good, double buy, int cap)
|
||||
{
|
||||
var buyers = TradingMath.Buyers(_w, to, good);
|
||||
// nello stesso bacino un hub che vende consuma la stessa capacità mensile con cui comprerebbe:
|
||||
// si rivende solo alle industrie
|
||||
if (to.Id == from.Id && from.Hubs.Count > 0) buyers = buyers.Where(b => b.Kind == TradePartyKind.Industry).ToList();
|
||||
if (TradingMath.BestBuyer(_w, buyers, good, out double sell) is null) return;
|
||||
if ((sell - buy) / buy < t.MinMargin) return;
|
||||
int room = 0;
|
||||
foreach (var b in buyers) room += b.Limit;
|
||||
int units = Math.Min(cap, room);
|
||||
if (units > 0) deals.Add(new Deal(from, to, good, buy, sell, units));
|
||||
}
|
||||
|
||||
/// <summary>Vende la merce dei magazzini propri ai compratori del bacino che pagano almeno la quota minima del prezzo globale.</summary>
|
||||
private void SellStock(AiTradingParams t, List<Station> stations)
|
||||
{
|
||||
foreach (var st in stations)
|
||||
{
|
||||
if (st.StockTotal <= 0) continue;
|
||||
for (int g = 0; g < _w.Data.GoodCount; g++)
|
||||
{
|
||||
int stock = st.StockOf(g);
|
||||
if (stock <= 0) continue;
|
||||
double floor = _w.Market.GlobalPrice[g] * t.MinSellPriceShare;
|
||||
var buyers = TradingMath.Buyers(_w, st, g);
|
||||
if (TradingMath.BestBuyer(_w, buyers, g, out double price) is null || price < Math.Ceiling(floor)) continue;
|
||||
// compratori con il magazzino pieno: si riprova il mese dopo invece di farsi rifiutare il comando
|
||||
int room = 0;
|
||||
foreach (var b in buyers) room += b.Limit;
|
||||
if (room <= 0) continue;
|
||||
Do(new SellGoodsCommand(st.Id, _w.Data.Goods[g].Id, Math.Min(stock, room), new Money((long)Math.Ceiling(floor))));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================== ricambi (10.2)
|
||||
@@ -287,7 +468,7 @@ internal sealed class AiAgent
|
||||
sources.Sort((a, b) => a.Km != b.Km ? a.Km.CompareTo(b.Km) : a.Key.CompareTo(b.Key));
|
||||
var loco = Estimators.BestLocomotive(_w, _ctx.Year);
|
||||
if (loco is null) return false;
|
||||
long budget = _c.Cash.Cents - Reserve() / 2 + LoanRoom();
|
||||
long budget = FreeCash() - Reserve() / 2 + LoanRoom();
|
||||
int tried = 0;
|
||||
foreach (var (pos, key, km) in sources)
|
||||
{
|
||||
@@ -307,7 +488,18 @@ internal sealed class AiAgent
|
||||
continue;
|
||||
}
|
||||
AiSystem.Trace?.Invoke($"{_ctx.Day} {_c.Name}: linea dei ricambi per {depot.Name}: {km:0.0} km, capitale {new Money(proposal.Capital)} (budget {new Money(budget)})");
|
||||
if (proposal.Capital > budget) return false;
|
||||
if (proposal.Capital > budget)
|
||||
{
|
||||
// si risparmia per la linea (niente depositi nuovi) solo entro planning.partsDeferYears
|
||||
// dall'apertura della rete; poi l'agente torna a espandersi come prima (ADR 0025)
|
||||
long opened = long.MaxValue;
|
||||
foreach (var p in _s.Projects)
|
||||
{
|
||||
if (p.Depot == depot.Id && p.StartDay < opened) opened = p.StartDay;
|
||||
}
|
||||
if (opened != long.MaxValue && _ctx.Day - opened <= _plan.PartsDeferYears * _w.Calendar.DaysPerYear) _partsPending = true;
|
||||
return false;
|
||||
}
|
||||
Execute(proposal, depot.Id);
|
||||
return true;
|
||||
}
|
||||
@@ -315,6 +507,12 @@ internal sealed class AiAgent
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cassa libera: la cassa meno la spesa impegnata dai rinnovi prenotati e non ancora avviati, che si
|
||||
/// paga giorni dopo a officina avviata (ADR 0020). Gli investimenti guardano questa, non la cassa intera.
|
||||
/// </summary>
|
||||
private long FreeCash() => _c.Cash.Cents - Obsolescence.Committed(_w, _c.Id).Cents;
|
||||
|
||||
/// <summary>Riserva di cassa: mesi di costi d'esercizio stimati dalla flotta e dalla rete.</summary>
|
||||
private long Reserve()
|
||||
{
|
||||
@@ -401,6 +599,48 @@ internal sealed class AiAgent
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================== rinnovo della flotta (ADR 0020)
|
||||
|
||||
/// <summary>
|
||||
/// Manda in officina per il rinnovo (intervento «renew», lo stesso comando ScheduleService del
|
||||
/// giocatore) al più renewal.maxTrainsPerMonth treni in servizio, in ordine di id, che hanno un
|
||||
/// veicolo superato da almeno renewal.minSupersededYears anni o con almeno renewal.minAgeShareOfLife
|
||||
/// della vita utile, se il rinnovo non peggiora le prestazioni del treno
|
||||
/// (<see cref="Obsolescence.KeepsPerformance"/>) e se dopo la spesa (successori − rivendite + lavoro)
|
||||
/// la cassa libera resta sopra renewal.cashReserveMultiple volte la riserva. La spesa resta impegnata
|
||||
/// (<see cref="FreeCash"/>) fino all'avvio dei lavori, così gli investimenti dello stesso mese non la riusano.
|
||||
/// </summary>
|
||||
private void RenewFleet()
|
||||
{
|
||||
var r = _w.Data.Ai.Renewal;
|
||||
if (r.MaxTrainsPerMonth <= 0) return;
|
||||
string renewal = _w.Data.Maintenance.Interventions[Obsolescence.RenewalIntervention(_w.Data)].Id;
|
||||
double daysPerYear = _w.Calendar.DaysPerYear;
|
||||
int scheduled = 0;
|
||||
foreach (var t in _w.Trains)
|
||||
{
|
||||
if (scheduled >= r.MaxTrainsPerMonth) break;
|
||||
if (t.Removed || t.Owner != _c.Id || !t.Line.IsValid || t.Reserve || t.InWorkshop || t.MaintenanceDepot.IsValid
|
||||
|| t.Failure != FailureKind.None || t.State == TrainState.Broken) continue;
|
||||
var plan = Obsolescence.RenewalPlan(_w, t);
|
||||
if (plan.Count == 0) continue;
|
||||
bool due = false;
|
||||
foreach (var item in plan)
|
||||
{
|
||||
double age = (_ctx.Day - item.Old.BoughtDay) / daysPerYear;
|
||||
if (Obsolescence.YearsSuperseded(_w, item.Old) >= r.MinSupersededYears || age >= r.MinAgeShareOfLife * item.Old.Def.LifeYears)
|
||||
{
|
||||
due = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!due || !Obsolescence.KeepsPerformance(_w, t, plan)) continue;
|
||||
long net = Obsolescence.RenewalCost(_w, t, plan).Cents;
|
||||
if (FreeCash() - net < (long)(Reserve() * r.CashReserveMultiple)) continue;
|
||||
if (Do(new ScheduleServiceCommand(t.Id, renewal)).Ok) scheduled++;
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================== borsa (12.2)
|
||||
|
||||
private void StockMarket()
|
||||
@@ -412,13 +652,13 @@ internal sealed class AiAgent
|
||||
if (other.Defunct || other.ControlledBy != _c.Id || other.IsPlayer) continue;
|
||||
if (_ctx.Day - other.ControlSinceDay < sm.MergeAfterDays) continue;
|
||||
double minority = (other.Shares.Outstanding - other.Shares.Of(_c.Id)) * other.SharePrice;
|
||||
if (_c.Cash.Cents > minority + Reserve()) Do(new MergeCompanyCommand(other.Id));
|
||||
if (FreeCash() > minority + Reserve()) Do(new MergeCompanyCommand(other.Id));
|
||||
}
|
||||
if (!_p.BuysShares) return;
|
||||
// la Predatoria accumula quote dei concorrenti quotati (prima il giocatore) e poi lancia l'offerta;
|
||||
// solo con una rete che rende e cassa abbondante, e solo in compagnie in utile
|
||||
if (!_s.Projects.Any(p => p.Stage == AiProjectStage.Running) || _c.AnnualProfit <= 0) return;
|
||||
long budget = (long)(Math.Max(0, _c.Cash.Cents - 3 * Reserve()) * _mk.SharesCashShare);
|
||||
long budget = (long)(Math.Max(0, FreeCash() - 3 * Reserve()) * _mk.SharesCashShare);
|
||||
if (budget <= 0) return;
|
||||
foreach (var target in _w.Companies.OrderByDescending(t => t.IsPlayer).ThenBy(t => t.Id.Value))
|
||||
{
|
||||
@@ -452,7 +692,7 @@ internal sealed class AiAgent
|
||||
long needed = (long)Math.Ceiling(goal * target.Shares.Outstanding) - target.Shares.Of(_c.Id);
|
||||
if (needed <= 0) return false;
|
||||
double cost = (double)needed * price;
|
||||
if (_c.Cash.Cents < cost * _mk.BidCashMultiple + Reserve()) return false;
|
||||
if (FreeCash() < cost * _mk.BidCashMultiple + Reserve()) return false;
|
||||
return Do(new LaunchBidCommand(target.Id, new Money(price), goal)).Ok;
|
||||
}
|
||||
|
||||
@@ -505,7 +745,7 @@ internal sealed class AiAgent
|
||||
private void BuyIndustries()
|
||||
{
|
||||
if (!Tiers.Unlocks(_w, _c).BuyIndustry || _s.LastIndustryYear == _ctx.Year) return;
|
||||
long budget = (long)(Math.Max(0, _c.Cash.Cents - Reserve()) * _mk.IndustryMaxCashShare);
|
||||
long budget = (long)(Math.Max(0, FreeCash() - Reserve()) * _mk.IndustryMaxCashShare);
|
||||
if (budget <= 0) return;
|
||||
var served = Tiers.ServedStations(_w, _c.Id);
|
||||
Industry? best = null;
|
||||
@@ -557,6 +797,8 @@ internal sealed class AiAgent
|
||||
public Vec2? DepotPos { get; init; }
|
||||
public DepotId ExistingDepot { get; init; } = DepotId.None;
|
||||
public required long Capital { get; init; }
|
||||
/// <summary>Parte del capitale spesa dopo, con i ricavi della linea: la linea dei ricambi del deposito (ADR 0025).</summary>
|
||||
public long DeferredCapital { get; init; }
|
||||
public required double Revenue { get; init; }
|
||||
public required double Costs { get; init; }
|
||||
public required int Trains { get; init; }
|
||||
@@ -571,7 +813,7 @@ internal sealed class AiAgent
|
||||
{
|
||||
int open = _s.Projects.Count(p => p.Stage is AiProjectStage.Construction or AiProjectStage.Equip);
|
||||
if (open >= _plan.MaxConcurrentProjects) return;
|
||||
long budget = _c.Cash.Cents - Reserve() + LoanRoom();
|
||||
long budget = FreeCash() - Reserve() + LoanRoom();
|
||||
if (budget <= 0) return;
|
||||
var loco = Estimators.BestLocomotive(_w, _ctx.Year);
|
||||
if (loco is null) return;
|
||||
@@ -596,10 +838,16 @@ internal sealed class AiAgent
|
||||
continue;
|
||||
}
|
||||
AiSystem.Trace?.Invoke($"{_ctx.Day} {_c.Name}: candidato {cand.Kind} bene {cand.Good} {cand.StraightKm:0.0} km: capitale {new Money(proposal.Capital)}, ricavi {Money.FromCentsRounded(proposal.Revenue)}, costi {Money.FromCentsRounded(proposal.Costs)}, ROI {proposal.Roi * 100:0.0} % (soglia {_p.RoiThreshold * 100:0} %, budget {new Money(budget)})");
|
||||
if (proposal.Capital > budget) continue;
|
||||
// la linea dei ricambi entra nel ROI ma si costruisce dopo (EnsurePartsSupply): il deposito parte con la
|
||||
// sua dotazione di ricambi e la linea si paga con i primi ricavi (ADR 0025)
|
||||
if (proposal.Capital - proposal.DeferredCapital > budget) continue;
|
||||
// un deposito aspetta la sua linea dei ricambi: niente reti nuove finché la cassa non basta
|
||||
if (_partsPending && !proposal.ExistingDepot.IsValid) continue;
|
||||
// ROI sul capitale investito, come nella guida (gli interessi sono una scelta di finanziamento)
|
||||
double roi = proposal.Roi;
|
||||
bool townProject = cand.SourceIsTown || cand.DestIsTown;
|
||||
// le linee urbane che servono al livello passano con una soglia ridotta, anche sotto il tasso dei prestiti:
|
||||
// il loro valore è lo sblocco del livello, che il ROI non misura (ADR 0025)
|
||||
double threshold = townProject && NeedTowns() ? _p.RoiThreshold * _plan.TownRoiFactor : _p.RoiThreshold;
|
||||
if (roi < threshold) continue;
|
||||
if (best is null || proposal.Roi > best.Roi) best = proposal;
|
||||
@@ -655,6 +903,8 @@ internal sealed class AiAgent
|
||||
// impianto fermo per un incidente: non si giudica oggi, se ne riparla a evento finito
|
||||
if (capacity <= 0) break;
|
||||
eff = Math.Min(prod.Efficiency / capacity, eff);
|
||||
// senza chi porta gli input l'impianto vive delle scorte iniziali e poi si ferma (ADR 0025)
|
||||
if (!InputsFed(prod, servedBy)) eff = 0;
|
||||
}
|
||||
double supply = (double)prod.Def.Capacity(prod.Level) * outputs[o].PerCycle / outputs[0].PerCycle * months * eff;
|
||||
if (supply <= 0) continue;
|
||||
@@ -857,6 +1107,32 @@ internal sealed class AiAgent
|
||||
+ Estimators.StationCost(_w, _c, _plan.HubPlatforms) + Estimators.DepotCost(_w, _c, "small") + train;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Un'industria di trasformazione ha ogni input alimentato: da una stazione in esercizio che la
|
||||
/// serve o, con il trasporto locale attivo, da un produttore di quel bene entro il suo raggio
|
||||
/// (ADR 0025). Le scorte iniziali e la copertura iniziale piena non bastano a stimarne la resa.
|
||||
/// </summary>
|
||||
private bool InputsFed(Industry ind, CompanyId[] servedBy)
|
||||
{
|
||||
if (servedBy[ind.Id.Value].IsValid) return true;
|
||||
var lt = _w.Data.Balance.LocalTransport;
|
||||
foreach (var input in ind.Def.Recipe.Inputs)
|
||||
{
|
||||
bool fed = false;
|
||||
if (lt.Enabled)
|
||||
{
|
||||
foreach (var other in _w.Industries)
|
||||
{
|
||||
if (other.Closed || other.Level <= 0 || other.Id == ind.Id) continue;
|
||||
if (!other.Def.Recipe.Outputs.Any(o => o.GoodIndex == input.GoodIndex)) continue;
|
||||
if (Vec2.Distance(other.Position, ind.Position) <= lt.RadiusKm * 1000) { fed = true; break; }
|
||||
}
|
||||
}
|
||||
if (!fed) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Compagnia che serve (o sta per servire) ciascuna industria: una sua stazione ha l'industria nel
|
||||
/// bacino, anche se la linea è ancora in costruzione (o None).
|
||||
@@ -909,7 +1185,7 @@ internal sealed class AiAgent
|
||||
Vec2? depotPos = null;
|
||||
var existingDepot = supply is { } supplied ? supplied : existingA.IsValid ? ConnectedDepot(existingA) : DepotId.None;
|
||||
if (!existingDepot.IsValid && existingB.IsValid) existingDepot = ConnectedDepot(existingB);
|
||||
long capital = plan.TotalCost.Cents;
|
||||
long capital = plan.TotalCost.Cents, deferred = 0;
|
||||
bool depotAtB = false;
|
||||
if (!existingDepot.IsValid)
|
||||
{
|
||||
@@ -924,6 +1200,8 @@ internal sealed class AiAgent
|
||||
long partsCost = PartsLineCost(home, sources);
|
||||
if (partsCost < 0) return Reject("nessuna linea di ricambi possibile per il deposito");
|
||||
capital += partsCost;
|
||||
deferred = partsCost;
|
||||
AiSystem.Trace?.Invoke($"{_ctx.Day} {_c.Name}: linea dei ricambi in conto {new Money(partsCost)}");
|
||||
}
|
||||
var next = depotAtB ? (polyline.Count > 1 ? polyline[^2] : posA.Value) : (polyline.Count > 1 ? polyline[1] : posB.Value);
|
||||
depotPos = DepotSite(home, next);
|
||||
@@ -937,6 +1215,7 @@ internal sealed class AiAgent
|
||||
if (!existingB.IsValid) capital += Estimators.StationCost(_w, _c, depotPos is not null && depotAtB ? _plan.HubPlatforms : _plan.Platforms);
|
||||
|
||||
double km = plan.LengthM / 1000;
|
||||
AiSystem.Trace?.Invoke($"{_ctx.Day} {_c.Name}: binari {km:0.0} km: opere {plan.WorksCost}, terreni {plan.LandCost}");
|
||||
VehicleDef? car = cand.Kind == AiProjectKind.Freight ? Estimators.WagonFor(_w, cand.Good, _ctx.Year) : Estimators.CoachFor(_w, cand.Class, _ctx.Year);
|
||||
if (car is null) return null;
|
||||
int cars = supply is not null ? 1 : cand.Kind == AiProjectKind.Freight ? _plan.WagonsPerTrain : Math.Max(1, _plan.WagonsPerTrain / 2);
|
||||
@@ -968,11 +1247,22 @@ internal sealed class AiAgent
|
||||
+ (existingB.IsValid ? 0 : _plan.Platforms * sp.UpkeepPerPlatformPerYear)
|
||||
+ (existingDepot.IsValid ? 0 : sp.DepotUpkeepPerYear["small"])
|
||||
+ km * _plan.TrackUpkeepPerKmPerYear;
|
||||
// la linea dei ricambi si rimanda solo se l'utile della linea la ripaga prima che finisca la dotazione
|
||||
// iniziale del deposito (tagliandi dei treni previsti con la politica della personalità), e comunque
|
||||
// entro planning.partsDeferYears (ADR 0025)
|
||||
if (deferred > 0)
|
||||
{
|
||||
var mt = _w.Data.Maintenance;
|
||||
double servicesPerYear = _w.Calendar.DaysPerYear / (mt.Intervals.ServiceDays * mt.Policy(_p.MaintenancePolicy).IntervalFactor);
|
||||
double partsPerYear = trains * (1 + cars) * servicesPerYear * mt.Intervention("service").SpareParts;
|
||||
double stockYears = partsPerYear <= 0 ? _plan.PartsDeferYears : mt.Depots.InitialSpareParts / partsPerYear;
|
||||
if (deferred > (revenue - costs) * Math.Min(_plan.PartsDeferYears, stockYears)) deferred = 0;
|
||||
}
|
||||
return new Proposal
|
||||
{
|
||||
Candidate = cand, PosA = posA.Value, PosB = posB.Value, ExistingA = existingA, ExistingB = existingB,
|
||||
Polyline = polyline, DepotPos = depotPos, ExistingDepot = existingDepot,
|
||||
Capital = capital, Revenue = revenue, Costs = costs, Trains = trains, Loco = loco, Car = car, Cars = cars,
|
||||
Capital = capital, DeferredCapital = deferred, Revenue = revenue, Costs = costs, Trains = trains, Loco = loco, Car = car, Cars = cars,
|
||||
DepotAtB = depotAtB,
|
||||
};
|
||||
}
|
||||
@@ -1147,7 +1437,7 @@ internal sealed class AiAgent
|
||||
/// <summary>Apre i cantieri del progetto: stazioni, deposito, binario e raccordo del deposito.</summary>
|
||||
private void Execute(Proposal p, DepotId? supply = null)
|
||||
{
|
||||
long need = p.Capital + Reserve() - _c.Cash.Cents;
|
||||
long need = p.Capital - p.DeferredCapital + Reserve() - FreeCash();
|
||||
if (need > 0 && !Borrow(need)) return;
|
||||
var cand = p.Candidate;
|
||||
var stationA = p.ExistingA;
|
||||
|
||||
@@ -30,8 +30,9 @@ public sealed class AiProject
|
||||
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; }
|
||||
/// <summary>Modelli dei treni della linea; se escono di produzione si passa al successore (ADR 0020).</summary>
|
||||
public required string Loco { get; set; }
|
||||
public required string Car { get; set; }
|
||||
public int CarsPerTrain { get; init; }
|
||||
/// <summary>Giorno prima del quale non si aggiungono treni (dopo uno stallo risolto).</summary>
|
||||
public long GrowAfterDay { get; set; }
|
||||
@@ -58,6 +59,14 @@ public sealed class AiState
|
||||
/// <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>
|
||||
/// Diagnostica del banco di bilanciamento (ADR 0025), né salvata né nell'hash: mesi in cui l'agente non
|
||||
/// ha aperto reti nuove perché un deposito aspettava la sua linea dei ricambi, e affari di compravendita
|
||||
/// conclusi (acquisti riusciti).
|
||||
/// </summary>
|
||||
public long PartsBlockedMonths { get; set; }
|
||||
public long Trades { get; set; }
|
||||
|
||||
/// <summary>Quota dei comandi rifiutati sul totale emesso.</summary>
|
||||
public double RejectedShare => Issued == 0 ? 0 : (double)Rejected / Issued;
|
||||
}
|
||||
@@ -20,6 +20,14 @@ public sealed class AiSystem : ISimSystem
|
||||
if (w.AiPaused) return;
|
||||
EnsureStates(w);
|
||||
int dpm = w.Calendar.DaysPerMonth;
|
||||
// il bot del giocatore (ADR 0025) prima delle IA, come un giocatore che costruisce dal primo giorno,
|
||||
// finché la compagnia è in gioco
|
||||
if (w.PlayerBot is { } bot && !w.Player.Defunct && w.GameOver is null)
|
||||
{
|
||||
var agent = new AiAgent(w, ctx, bot.State, _path, bot.Personality);
|
||||
agent.Daily();
|
||||
if (ctx.Day % dpm == bot.State.PlanDay) agent.Monthly();
|
||||
}
|
||||
foreach (var s in w.AiStates)
|
||||
{
|
||||
var c = w.Company(s.Company);
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
using RailEnterprise.Core.Data;
|
||||
|
||||
namespace RailEnterprise.Core.Simulation.Ai;
|
||||
|
||||
/// <summary>
|
||||
/// «Bot giocatore» del banco di bilanciamento (ADR 0025): guida la compagnia del giocatore con lo stesso
|
||||
/// agente delle IA (stessi comandi, stesse validazioni) e una personalità della sezione <c>bots</c> di
|
||||
/// ai.json. Serve solo agli strumenti e ai test: non entra nel salvataggio né nell'hash di stato
|
||||
/// (gli effetti dei suoi comandi sì, come quelli di un giocatore), e un mondo caricato non ha bot.
|
||||
/// </summary>
|
||||
public sealed class PlayerBot
|
||||
{
|
||||
private PlayerBot(AiPersonalityDef personality, AiState state)
|
||||
{
|
||||
Personality = personality;
|
||||
State = state;
|
||||
}
|
||||
|
||||
public AiPersonalityDef Personality { get; }
|
||||
|
||||
/// <summary>Stato dell'agente (progetti, comandi emessi e rifiutati), come per le IA.</summary>
|
||||
public AiState State { get; }
|
||||
|
||||
/// <summary>Bot con la personalità indicata (id di ai.json → bots) per la compagnia del giocatore.</summary>
|
||||
public static PlayerBot Create(World w, string personalityId)
|
||||
{
|
||||
var def = w.Data.Ai.Bots.FirstOrDefault(b => b.Id == personalityId)
|
||||
?? throw new ArgumentException($"Bot sconosciuto: {personalityId} (ai.json → bots: {string.Join(", ", w.Data.Ai.Bots.Select(b => b.Id))})");
|
||||
// pianifica lo stesso giorno della prima IA ma prima di lei (AiSystem): il giocatore sceglie per primo
|
||||
var state = new AiState
|
||||
{
|
||||
Company = w.Player.Id,
|
||||
PlanDay = 1 % w.Calendar.DaysPerMonth,
|
||||
};
|
||||
return new PlayerBot(def, state);
|
||||
}
|
||||
}
|
||||
@@ -62,6 +62,14 @@ public static class CommandProcessor
|
||||
BuyGoodsCommand c => TradingCommandHandlers.Buy(w, company, c, Reply),
|
||||
SellGoodsCommand c => TradingCommandHandlers.Sell(w, company, c, Reply),
|
||||
ShipGoodsCommand c => TradingCommandHandlers.Ship(w, company, c, ctx, Reply),
|
||||
// le concessioni (F7) si rifiutano prima per il livello, poi perché non ancora disponibili; il testo
|
||||
// non promette che il livello basti
|
||||
BuyConcessionCommand when !Tiers.Unlocks(w, company).Concessions =>
|
||||
Result(CommandError.TierLocked, Tiers.ConcessionsAvailable
|
||||
? Tiers.LockedText(w, "Le concessioni", u => u.Concessions, plural: true)
|
||||
: Tiers.ConcessionsUnavailableText(w)),
|
||||
BuyConcessionCommand when !Tiers.ConcessionsAvailable =>
|
||||
Result(CommandError.NotImplemented, "Le concessioni non sono ancora disponibili"),
|
||||
_ => Result(CommandError.NotImplemented, $"Comando {command.Type} non ancora disponibile"),
|
||||
};
|
||||
}
|
||||
@@ -72,7 +80,7 @@ public static class CommandProcessor
|
||||
if (company.Receivership) return result(CommandError.NotAllowed, "In amministrazione controllata non si possono chiedere prestiti");
|
||||
var max = FinanceSystem.MaxLoan(w, company);
|
||||
if (company.Debt + c.Amount > max)
|
||||
return result(CommandError.CreditLimit, $"Fido insufficiente: disponibili {(max - company.Debt).ToString()}");
|
||||
return result(CommandError.CreditLimit, LoanLimitText(w, company, max));
|
||||
var fb = w.Data.Balance.Finance;
|
||||
var loan = new Loan
|
||||
{
|
||||
@@ -85,7 +93,22 @@ public static class CommandProcessor
|
||||
};
|
||||
company.Loans.Add(loan);
|
||||
w.Money.Transfer(Account.External, Account.Of(company.Id), c.Amount, LedgerEntry.LoanTaken);
|
||||
return result(CommandError.None, $"Prestito di {c.Amount} al {loan.AnnualRate * 100:F1}% per {loan.TermMonths / 12} anni");
|
||||
var payment = FinanceSystem.MonthlyPayment(loan.Remaining, loan.AnnualRate, loan.MonthsLeft);
|
||||
return result(CommandError.None,
|
||||
$"Prestito di {c.Amount} al {FinanceOutlook.Percent(loan.AnnualRate)} fisso (base {FinanceOutlook.Percent(w.Difficulty.BaseInterestRate)} + rating {company.Rating}) " +
|
||||
$"per {loan.TermMonths / 12} anni: rata mensile {payment}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rifiuto per fido insufficiente: quanto resta disponibile e, se un livello successivo alza il
|
||||
/// fattore del fido, quale livello serve e a quanto porta il fido (ADR 0018).
|
||||
/// </summary>
|
||||
public static string LoanLimitText(World w, Company company, Money max)
|
||||
{
|
||||
string text = $"Fido insufficiente: disponibili {Money.Max(Money.Zero, max - company.Debt)} su {max}";
|
||||
var current = Tiers.Def(w, company.Tier);
|
||||
var next = w.Data.Tiers.Tiers.FirstOrDefault(t => t.Level > current.Level && t.Unlocks.MaxLoanFactor > current.Unlocks.MaxLoanFactor);
|
||||
return next is null ? text : $"{text}; il livello {next.Level}, «{next.NameIt}», porta il fido a {Tiers.LoanLimit(company, next)}";
|
||||
}
|
||||
|
||||
private static CommandResult RepayLoan(World w, Company company, RepayLoanCommand c, Func<CommandError, string, CommandResult> result)
|
||||
@@ -94,10 +117,17 @@ public static class CommandProcessor
|
||||
if (loan is null) return result(CommandError.NotFound, "Prestito inesistente");
|
||||
if (c.Amount.Cents <= 0) return result(CommandError.InvalidArgument, "Importo non valido");
|
||||
var amount = Money.Min(c.Amount, loan.Remaining);
|
||||
if (company.Cash < amount) return result(CommandError.InsufficientFunds, "Cassa insufficiente");
|
||||
if (company.Cash < amount)
|
||||
return result(CommandError.InsufficientFunds, $"Cassa insufficiente: per rimborsare {amount} ci sono {Money.Max(Money.Zero, company.Cash)} in cassa");
|
||||
w.Money.Transfer(Account.Of(company.Id), Account.External, amount, LedgerEntry.LoanRepaid);
|
||||
loan.Remaining -= amount;
|
||||
if (loan.Remaining.Cents <= 0) company.Loans.Remove(loan);
|
||||
return result(CommandError.None, $"Rimborsati {amount}");
|
||||
if (loan.Remaining.Cents <= 0)
|
||||
{
|
||||
company.Loans.Remove(loan);
|
||||
return result(CommandError.None, $"Rimborsati {amount}: prestito estinto");
|
||||
}
|
||||
// rimborso parziale: stessa durata e stesso tasso, la rata scende con il residuo
|
||||
return result(CommandError.None,
|
||||
$"Rimborsati {amount}: restano {loan.Remaining}, nuova rata mensile {FinanceSystem.MonthlyPayment(loan.Remaining, loan.AnnualRate, loan.MonthsLeft)}");
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ public static class CorporateCommandHandlers
|
||||
{
|
||||
var sm = w.Data.Balance.StockMarket;
|
||||
if (company.IsPlayer && !company.Listed && !Tiers.Unlocks(w, company).Ipo)
|
||||
return reply(CommandError.TierLocked, "La quotazione si sblocca al livello «Grande compagnia»");
|
||||
return reply(CommandError.TierLocked, Tiers.LockedText(w, "La quotazione in borsa", u => u.Ipo));
|
||||
// prima quotazione fino a ipoMaxShare; per chi è già quotato un aumento di capitale fino al flottante massimo
|
||||
double limit = company.Listed ? sm.SecondaryMaxFloat - (double)company.Shares.Public / company.Shares.Total : sm.IpoMaxShare;
|
||||
if (!(c.FloatShare > 0) || c.FloatShare > limit + 1e-9)
|
||||
@@ -137,7 +137,7 @@ public static class CorporateCommandHandlers
|
||||
if (target.Defunct) return reply(CommandError.NotAllowed, $"{target.Name} non è più attiva");
|
||||
|
||||
if (company.IsPlayer && !Tiers.Unlocks(w, company).HostileTakeover)
|
||||
return reply(CommandError.TierLocked, "Le scalate ostili si sbloccano al livello «Impero ferroviario»");
|
||||
return reply(CommandError.TierLocked, Tiers.LockedText(w, "Le scalate ostili", u => u.HostileTakeover, plural: true));
|
||||
if (!target.Listed) return reply(CommandError.NotAllowed, $"{target.Name} non è quotata");
|
||||
if (target.IsPlayer && w.Difficulty.PlayerTakeover == TakeoverRule.Disabled)
|
||||
return reply(CommandError.NotAllowed, "Con questa difficoltà la compagnia del giocatore non è scalabile");
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
namespace RailEnterprise.Core.Simulation;
|
||||
|
||||
@@ -64,26 +65,33 @@ public static class Estimators
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>Carro più economico che trasporta il bene nell'anno.</summary>
|
||||
/// <summary>
|
||||
/// Vero se il modello è superato e il suo successore consigliato si compra e non è peggiore: chi sceglie
|
||||
/// un modello nuovo (IA, stime) lo scarta per non comprare un veicolo che perde subito valore (ADR 0020).
|
||||
/// </summary>
|
||||
private static bool Outdated(VehicleDef v, int year) =>
|
||||
Obsolescence.IsSuperseded(v, year) && Obsolescence.Recommended(v, year) is { } next && Obsolescence.NoWorseThan(next, v);
|
||||
|
||||
/// <summary>Carro più economico che trasporta il bene nell'anno, esclusi i superati con un successore in produzione.</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 (v.Kind != VehicleKind.Wagon || v.EraFrom > year || (v.EraTo is { } to && year > to) || Outdated(v, year)) 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>
|
||||
/// <summary>Carrozza più economica della classe indicata disponibile nell'anno, esclusi i superati con un successore in produzione.</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 (v.Kind != VehicleKind.Coach || v.Class != cls || v.EraFrom > year || (v.EraTo is { } to && year > to) || Outdated(v, year)) continue;
|
||||
if (best is null || v.Price < best.Price) best = v;
|
||||
}
|
||||
return best;
|
||||
|
||||
@@ -20,6 +20,8 @@ public enum EventKind : byte
|
||||
Company = 9,
|
||||
/// <summary>Evento del mondo (events.json, ADR 0017): inizio e fine.</summary>
|
||||
World = 10,
|
||||
/// <summary>Passaggio d'era e novità tecnologiche dell'anno (ADR 0020).</summary>
|
||||
Technology = 11,
|
||||
}
|
||||
|
||||
/// <summary>Riferimento facoltativo all'entità coinvolta.</summary>
|
||||
|
||||
@@ -11,7 +11,7 @@ public static class IndustryCommandHandlers
|
||||
public static CommandResult BuyIndustry(World w, Company company, BuyIndustryCommand c, RailCommandHandlers.Reply reply)
|
||||
{
|
||||
if (!Tiers.Unlocks(w, company).BuyIndustry)
|
||||
return reply(CommandError.TierLocked, "L'acquisto di industrie si sblocca al livello «Compagnia nazionale»");
|
||||
return reply(CommandError.TierLocked, Tiers.LockedText(w, "L'acquisto di industrie", u => u.BuyIndustry));
|
||||
if (!TryIndustry(w, c.Industry, out var ind) || ind.Closed) return reply(CommandError.NotFound, "Industria inesistente");
|
||||
if (ind.Owner == company.Id) return reply(CommandError.NotAllowed, $"{ind.Name} è già della compagnia");
|
||||
if (ind.Owner.IsValid) return reply(CommandError.NotAllowed, $"{ind.Name} appartiene a {w.Company(ind.Owner).Name}");
|
||||
|
||||
@@ -74,13 +74,26 @@ public static class MaintenanceCommandHandlers
|
||||
if (!TryTrain(w, c.Train, company, out var train)) return reply(CommandError.NotFound, "Treno inesistente");
|
||||
var m = w.Data.Maintenance;
|
||||
int idx = m.InterventionIndex(c.Intervention);
|
||||
if (idx < 0 || m.Interventions[idx].Effect is not (InterventionEffect.Inspection or InterventionEffect.Service or InterventionEffect.Overhaul))
|
||||
return reply(CommandError.InvalidArgument, "Intervento: inspection, service o overhaul");
|
||||
if (idx < 0 || m.Interventions[idx].Effect is not (InterventionEffect.Inspection or InterventionEffect.Service or InterventionEffect.Overhaul or InterventionEffect.Renew))
|
||||
return reply(CommandError.InvalidArgument, $"Intervento: inspection, service, overhaul o {m.Interventions.First(i => i.Effect == InterventionEffect.Renew).Id}");
|
||||
if (train.Vehicles.Count == 0) return reply(CommandError.NotAllowed, "Treno senza veicoli");
|
||||
if (train.InWorkshop) return reply(CommandError.NotAllowed, $"{train.Name} è già in officina");
|
||||
if (train.State == TrainState.Broken) return reply(CommandError.NotAllowed, $"{train.Name} attende il soccorso");
|
||||
if (train.Failure != FailureKind.None) return reply(CommandError.NotAllowed, $"{train.Name} ha un guasto: prima la riparazione");
|
||||
var def = m.Interventions[idx];
|
||||
if (def.Effect == InterventionEffect.Renew)
|
||||
{
|
||||
// rinnovo (ADR 0020): serve almeno un veicolo superato con un successore in produzione e la cassa
|
||||
// per la spesa netta, al netto degli altri rinnovi già prenotati; all'avvio dei lavori si ricontrolla
|
||||
var plan = Obsolescence.RenewalPlan(w, train);
|
||||
if (plan.Count == 0) return reply(CommandError.NotAllowed, $"{train.Name}: nessun veicolo superato da rinnovare");
|
||||
var net = Obsolescence.RenewalCost(w, train, plan);
|
||||
var committed = Obsolescence.Committed(w, company.Id, train);
|
||||
if (net.IsPositive && company.Cash - committed < net)
|
||||
return reply(CommandError.InsufficientFunds, committed.IsPositive
|
||||
? $"Il rinnovo di {train.Name} costa {net} al netto delle rivendite: cassa insufficiente (già impegnati {committed} in altri rinnovi)"
|
||||
: $"Il rinnovo di {train.Name} costa {net} al netto delle rivendite: cassa insufficiente");
|
||||
}
|
||||
int parts = Fleet.PartsFor(w, train, def);
|
||||
FleetMaintenanceSystem.CancelBooking(train);
|
||||
if (!FleetMaintenanceSystem.Book(ctx, train, idx, parts, requireParts: true))
|
||||
|
||||
@@ -408,14 +408,11 @@ public static class RailCommandHandlers
|
||||
return reply(CommandError.None, $"Venduto per {value}");
|
||||
}
|
||||
|
||||
/// <summary>Valore di rivendita: prezzo × (1 − età/vita, minimo 10 %) × condizione media.</summary>
|
||||
public static Money ResaleValue(World w, Vehicle v)
|
||||
{
|
||||
double ageYears = (w.Clock.Day - v.BoughtDay) / (double)w.Calendar.DaysPerYear;
|
||||
double residual = Math.Max(w.Data.Balance.Finance.BookValueFloor, 1 - ageYears / v.Def.LifeYears);
|
||||
double condition = v.Components.Length == 0 ? 1 : v.Components.Average() / 100;
|
||||
return new Money(v.Def.Price) * (residual * condition);
|
||||
}
|
||||
/// <summary>
|
||||
/// Valore di rivendita: prezzo × residuo (1 − età/vita, minimo 10 %, più rapido per i modelli
|
||||
/// superati) × condizione media; la curva è in <see cref="Obsolescence"/> (ADR 0020).
|
||||
/// </summary>
|
||||
public static Money ResaleValue(World w, Vehicle v) => Obsolescence.ResaleValue(w, v);
|
||||
|
||||
public static CommandResult ComposeTrain(World w, Company company, ComposeTrainCommand c, Reply reply)
|
||||
{
|
||||
|
||||
@@ -9,7 +9,7 @@ namespace RailEnterprise.Core.Simulation;
|
||||
/// inseriscono nella loro posizione quando vengono implementati:
|
||||
/// Clock → Commands → Construction → Trains → Signals → Stations (+ trasporto locale)
|
||||
/// → Maintenance → Demand → Commuting → Industries → IndustryMaintenance → Towns → Market
|
||||
/// → Finance → StockMarket → AiAgents → Events → Contracts → Hash.
|
||||
/// → Finance → StockMarket → AiAgents → Events → Eras (F6, ADR 0020) → Contracts → Hash.
|
||||
/// </summary>
|
||||
public sealed class SystemPipeline(IReadOnlyList<ISimSystem> systems)
|
||||
{
|
||||
@@ -43,6 +43,7 @@ public sealed class SystemPipeline(IReadOnlyList<ISimSystem> systems)
|
||||
new StockMarketSystem(),
|
||||
new AiSystem(),
|
||||
new EventSystem(),
|
||||
new EraSystem(),
|
||||
new HashSystem(),
|
||||
]);
|
||||
|
||||
|
||||
@@ -23,11 +23,7 @@ public sealed class ConstructionSystem : ISimSystem
|
||||
}
|
||||
|
||||
/// <summary>Squadre disponibili per una compagnia secondo il livello.</summary>
|
||||
public static int Crews(World w, Company c)
|
||||
{
|
||||
var byTier = w.Data.Construction.Crews.CrewsByTier;
|
||||
return byTier[Math.Clamp(c.Tier, 1, byTier.Length) - 1];
|
||||
}
|
||||
public static int Crews(World w, Company c) => Tiers.Crews(w, c.Tier);
|
||||
|
||||
private static void Projects(WorldContext ctx, World w)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
using System.Globalization;
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
|
||||
namespace RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
/// <summary>Tipo di novità tecnologica di un anno (ADR 0020).</summary>
|
||||
public enum TechKind : byte
|
||||
{
|
||||
Traction = 0,
|
||||
Vehicle = 1,
|
||||
BridgeType = 2,
|
||||
TunnelLimit = 3,
|
||||
TrackClass = 4,
|
||||
Signal = 5,
|
||||
Electrification = 6,
|
||||
Good = 7,
|
||||
Industry = 8,
|
||||
}
|
||||
|
||||
/// <summary>Novità che un anno sblocca: tipo, id nei dati (vuoto per gallerie ed elettrificazione) e testo italiano.</summary>
|
||||
public readonly record struct TechUnlock(TechKind Kind, string Id, string TextIt);
|
||||
|
||||
/// <summary>
|
||||
/// Passaggi d'era e novità tecnologiche (F6, ADR 0020). Il 1° gennaio di ogni anno (non il giorno della
|
||||
/// fondazione) annuncia, se ce ne sono, le novità di quell'anno lette dai dati: inizio di un'era
|
||||
/// (eras.json), trazioni, veicoli introdotti, tipi di ponte, limiti delle gallerie, classi di binario,
|
||||
/// segnali, elettrificazione, merci e industrie; poi i modelli che escono di produzione e quelli che
|
||||
/// diventano superati. Nessun elenco è scritto a mano. La notizia (<see cref="EventKind.Technology"/>)
|
||||
/// va a tutte le compagnie e la Cronaca del giocatore la registra come fatto saliente.
|
||||
///
|
||||
/// Il sistema non ha stato: la notizia nasce nel tick del cambio d'anno, che un salvataggio non ripete
|
||||
/// (il mondo si salva tra un tick e l'altro), quindi esce una volta sola anche passando da un
|
||||
/// salvataggio. Le ere continue della F7 aggiungeranno modelli ai dati: questo sistema li annuncerà
|
||||
/// senza cambiare.
|
||||
/// </summary>
|
||||
public sealed class EraSystem : ISimSystem
|
||||
{
|
||||
public string Name => "Eras";
|
||||
|
||||
public void Step(WorldContext ctx)
|
||||
{
|
||||
if (!ctx.IsNewYear || ctx.Day == 0) return;
|
||||
Announce(ctx.World, ctx.Year);
|
||||
}
|
||||
|
||||
/// <summary>Emette la notizia delle novità dell'anno (se ce ne sono) e la annota nella Cronaca del giocatore.</summary>
|
||||
public static GameEvent? Announce(World w, int year)
|
||||
{
|
||||
string? text = NewsText(w.Data, year);
|
||||
if (text is null) return null;
|
||||
var era = EraStarting(w.Data, year);
|
||||
var e = new GameEvent(w.Clock.Day, EventKind.Technology, EventSeverity.Opportunity, text, Company: CompanyId.None);
|
||||
w.Events.Add(e);
|
||||
if (w.Companies.Count > 0)
|
||||
Corporate.Milestone(w, w.Player, era is not null ? $"inizia l'{era.NameIt}" : $"novità del {year}: {string.Join("; ", NewsParts(w.Data, year))}");
|
||||
return e;
|
||||
}
|
||||
|
||||
/// <summary>Era in corso nell'anno: l'ultima iniziata (la prima se l'anno la precede).</summary>
|
||||
public static EraDef CurrentEra(GameData d, int year)
|
||||
{
|
||||
var eras = d.Eras.Eras;
|
||||
var current = eras[0];
|
||||
foreach (var e in eras)
|
||||
{
|
||||
if (e.From <= year) current = e;
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
/// <summary>Prossima era dopo l'anno (null all'ultima).</summary>
|
||||
public static EraDef? NextEra(GameData d, int year) => d.Eras.Eras.FirstOrDefault(e => e.From > year);
|
||||
|
||||
/// <summary>Era che inizia esattamente nell'anno (null se nessuna).</summary>
|
||||
public static EraDef? EraStarting(GameData d, int year) => d.Eras.Eras.FirstOrDefault(e => e.From == year);
|
||||
|
||||
/// <summary>Novità introdotte nell'anno, nell'ordine dei file dati.</summary>
|
||||
public static List<TechUnlock> Unlocks(GameData d, int year)
|
||||
{
|
||||
var list = new List<TechUnlock>();
|
||||
var eras = d.Eras;
|
||||
foreach (var t in eras.Tractions)
|
||||
{
|
||||
if (t.From == year) list.Add(new TechUnlock(TechKind.Traction, t.Id.ToString().ToLowerInvariant(), $"trazione {t.NameIt.ToLowerInvariant()}"));
|
||||
}
|
||||
foreach (var v in d.Vehicles)
|
||||
{
|
||||
if (v.EraFrom == year) list.Add(new TechUnlock(TechKind.Vehicle, v.Id, v.Kind == VehicleKind.Locomotive ? $"locomotiva {v.NameIt}" : v.NameIt.ToLowerInvariant()));
|
||||
}
|
||||
foreach (var b in eras.BridgeTypes)
|
||||
{
|
||||
if (b.From == year) list.Add(new TechUnlock(TechKind.BridgeType, b.Id, $"ponti in {b.NameIt.ToLowerInvariant()} con campate fino a {Number(b.MaxSpanM)} m"));
|
||||
}
|
||||
foreach (var t in eras.TunnelLimits)
|
||||
{
|
||||
if (t.From == year) list.Add(new TechUnlock(TechKind.TunnelLimit, "", $"gallerie fino a {Number(t.MaxLengthM / 1000)} km"));
|
||||
}
|
||||
foreach (var c in eras.TrackClasses)
|
||||
{
|
||||
if (c.From == year) list.Add(new TechUnlock(TechKind.TrackClass, c.Id, $"binario {c.NameIt}"));
|
||||
}
|
||||
foreach (var s in eras.Signals)
|
||||
{
|
||||
if (s.From == year) list.Add(new TechUnlock(TechKind.Signal, s.Id, s.NameIt.ToLowerInvariant()));
|
||||
}
|
||||
if (eras.ElectrificationFrom == year) list.Add(new TechUnlock(TechKind.Electrification, "", "elettrificazione delle linee"));
|
||||
foreach (var g in d.Goods)
|
||||
{
|
||||
if (g.Era == year) list.Add(new TechUnlock(TechKind.Good, g.Id, $"merce {g.NameIt.ToLowerInvariant()}"));
|
||||
}
|
||||
foreach (var i in d.Industries)
|
||||
{
|
||||
if (i.Era == year) list.Add(new TechUnlock(TechKind.Industry, i.Id, $"industria {i.NameIt.ToLowerInvariant()}"));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>Modelli fuori produzione dall'anno (ultimo anno di produzione l'anno prima).</summary>
|
||||
public static List<VehicleDef> Retired(GameData d, int year) => d.Vehicles.Where(v => v.EraTo == year - 1).ToList();
|
||||
|
||||
/// <summary>Modelli che nell'anno diventano superati (il successore è introdotto quell'anno).</summary>
|
||||
public static List<VehicleDef> NewlySuperseded(GameData d, int year) => d.Vehicles.Where(v => v.SuccessorDef?.EraFrom == year).ToList();
|
||||
|
||||
/// <summary>Testo della notizia dell'anno, o null se l'anno non porta nulla di nuovo.</summary>
|
||||
public static string? NewsText(GameData d, int year)
|
||||
{
|
||||
var era = EraStarting(d, year);
|
||||
var parts = NewsParts(d, year);
|
||||
if (era is null && parts.Count == 0) return null;
|
||||
string head = era is not null ? $"Inizia l'{era.NameIt} ({year})" : $"Novità del {year}";
|
||||
return parts.Count == 0 ? head : $"{head}: {string.Join("; ", parts)}";
|
||||
}
|
||||
|
||||
/// <summary>Parti della notizia dell'anno: sblocchi, modelli superati, fuori produzione (vuota se nessuna).</summary>
|
||||
public static List<string> NewsParts(GameData d, int year)
|
||||
{
|
||||
var unlocks = Unlocks(d, year);
|
||||
var retired = Retired(d, year);
|
||||
var superseded = NewlySuperseded(d, year);
|
||||
var parts = new List<string>();
|
||||
if (unlocks.Count > 0) parts.Add($"sblocca {Join(unlocks.Select(u => u.TextIt))}");
|
||||
if (superseded.Count > 0)
|
||||
parts.Add($"{(superseded.Count == 1 ? "modello superato" : "modelli superati")}: {Join(superseded.Select(v => $"{v.NameIt} (successore {v.SuccessorDef!.NameIt})"))}");
|
||||
if (retired.Count > 0) parts.Add($"fuori produzione: {Join(retired.Select(v => v.NameIt))}");
|
||||
return parts;
|
||||
}
|
||||
|
||||
private static string Join(IEnumerable<string> items)
|
||||
{
|
||||
var list = items.ToList();
|
||||
return list.Count <= 1 ? string.Concat(list) : $"{string.Join(", ", list.Take(list.Count - 1))} e {list[^1]}";
|
||||
}
|
||||
|
||||
private static string Number(double value) =>
|
||||
value.ToString("0.#", CultureInfo.InvariantCulture).Replace('.', ',');
|
||||
}
|
||||
@@ -5,62 +5,133 @@ using RailEnterprise.Core.Economy;
|
||||
namespace RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
/// <summary>
|
||||
/// Finanza delle compagnie: giorni di cassa negativa e bancarotta, rate mensili dei prestiti,
|
||||
/// rating di credito, chiusura dei conti mensili e annuali (guida 6.3).
|
||||
/// Finanza delle compagnie (guida 6.3, ADR 0019): costi d'esercizio e salari del personale dei depositi
|
||||
/// ogni giorno, giorni di cassa negativa con avvisi e bancarotta, rate mensili dei prestiti, chiusura dei
|
||||
/// conti mensili e annuali (conto economico per voce), rating di credito dagli ultimi mesi chiusi.
|
||||
/// </summary>
|
||||
public sealed class FinanceSystem : ISimSystem
|
||||
{
|
||||
public string Name => "Finance";
|
||||
|
||||
private double[] _running = [];
|
||||
private double[] _upkeep = [];
|
||||
private double[] _wages = [];
|
||||
|
||||
public void Step(WorldContext ctx)
|
||||
{
|
||||
if (!ctx.IsNewDay) return;
|
||||
var w = ctx.World;
|
||||
PayRunningCosts(w);
|
||||
PayDepotWages(w);
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
if (c.Defunct) continue;
|
||||
c.NegativeCashDays = c.Cash.IsNegative ? c.NegativeCashDays + 1 : 0;
|
||||
if (c.NegativeCashDays >= w.Difficulty.BankruptcyDays)
|
||||
{
|
||||
c.Bankrupt = true;
|
||||
ctx.World.Events.Add(new GameEvent(ctx.Day, EventKind.Finance, EventSeverity.Critical,
|
||||
$"{c.Name}: dichiarata la bancarotta dopo {c.NegativeCashDays} giorni di cassa negativa", EntityKind.Company, c.Id.Value, c.Id));
|
||||
}
|
||||
UpdateNegativeCash(ctx, c);
|
||||
}
|
||||
if (ctx.IsNewMonth && ctx.Day > 0)
|
||||
{
|
||||
UpdateBookValues(w);
|
||||
var closed = w.Calendar.DateOfDay(ctx.Day - 1);
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
if (c.Merged) continue;
|
||||
if (!c.Bankrupt) PayLoans(w, c);
|
||||
c.Rating = ComputeRating(w, c);
|
||||
CloseMonth(w, c, closed.Year, closed.Month);
|
||||
UpdateRating(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);
|
||||
}
|
||||
}
|
||||
if (ctx.IsNewYear && ctx.Day > 0)
|
||||
{
|
||||
int year = w.Calendar.DateOfDay(ctx.Day - 1).Year;
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
Push(c.IncomeYears, new IncomeRecord { Year = year, Month = 0, Entries = (long[])c.YearEntries.Clone() }, w.Data.Balance.Finance.IncomeYears);
|
||||
Array.Copy(c.YearEntries, c.LastYearEntries, c.YearEntries.Length);
|
||||
Array.Clear(c.YearEntries);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Costi d'esercizio giornalieri: veicoli posseduti, binari di stazione, depositi.</summary>
|
||||
/// <summary>
|
||||
/// Chiusura del mese: utile nell'anello dei 12 mesi della borsa (12.2) e movimenti per voce nel conto
|
||||
/// economico mensile (ADR 0019); il nuovo mese parte senza movimenti né dividendi.
|
||||
/// </summary>
|
||||
private static void CloseMonth(World w, Company c, int year, int month)
|
||||
{
|
||||
c.ProfitRing[c.ProfitRingIndex] = Company.OperatingProfit(c.MonthEntries);
|
||||
c.ProfitRingIndex = (c.ProfitRingIndex + 1) % c.ProfitRing.Length;
|
||||
c.DividendRing[c.ProfitRingIndex] = 0;
|
||||
Push(c.IncomeMonths, new IncomeRecord { Year = year, Month = month, Entries = (long[])c.MonthEntries.Clone() }, w.Data.Balance.Finance.IncomeMonths);
|
||||
Array.Clear(c.MonthEntries);
|
||||
}
|
||||
|
||||
private static void Push(List<IncomeRecord> list, IncomeRecord record, int capacity)
|
||||
{
|
||||
list.Add(record);
|
||||
if (list.Count > capacity) list.RemoveRange(0, list.Count - capacity);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Giorni di cassa negativa (guida 6.3): primo avviso dopo finance.negativeCashNoticeDays giorni di
|
||||
/// fila, poi quando mancano i giorni di finance.bankruptcyWarningDaysLeft; bancarotta al limite della
|
||||
/// difficoltà (difficulty.json, bankruptcyDays). Se la cassa torna positiva il conto alla rovescia si
|
||||
/// azzera, con un avviso solo se era durato almeno i giorni del primo avviso: una cassa che oscilla
|
||||
/// intorno a zero non riempie le notizie.
|
||||
/// </summary>
|
||||
private static void UpdateNegativeCash(WorldContext ctx, Company c)
|
||||
{
|
||||
var w = ctx.World;
|
||||
int notice = w.Data.Balance.Finance.NegativeCashNoticeDays;
|
||||
if (!c.Cash.IsNegative)
|
||||
{
|
||||
if (c.NegativeCashDays >= notice)
|
||||
ctx.Emit(new GameEvent(ctx.Day, EventKind.Finance, EventSeverity.Info,
|
||||
$"{c.Name}: la cassa torna positiva dopo {Days(c.NegativeCashDays)} di scoperto, il conto alla rovescia della bancarotta si azzera",
|
||||
EntityKind.Company, c.Id.Value, c.Id));
|
||||
c.NegativeCashDays = 0;
|
||||
return;
|
||||
}
|
||||
c.NegativeCashDays++;
|
||||
int left = w.Difficulty.BankruptcyDays - c.NegativeCashDays;
|
||||
if (left <= 0)
|
||||
{
|
||||
c.Bankrupt = true;
|
||||
ctx.Emit(new GameEvent(ctx.Day, EventKind.Finance, EventSeverity.Critical,
|
||||
$"{c.Name}: dichiarata la bancarotta dopo {Days(c.NegativeCashDays)} di cassa negativa", EntityKind.Company, c.Id.Value, c.Id));
|
||||
return;
|
||||
}
|
||||
var warnings = w.Data.Balance.Finance.BankruptcyWarningDaysLeft;
|
||||
if (c.NegativeCashDays == notice)
|
||||
{
|
||||
ctx.Emit(new GameEvent(ctx.Day, EventKind.Finance, EventSeverity.Warning,
|
||||
$"{c.Name}: cassa negativa da {Days(c.NegativeCashDays)} ({c.Cash}); se non torna sopra zero la bancarotta arriva tra {Days(left)}",
|
||||
EntityKind.Company, c.Id.Value, c.Id));
|
||||
}
|
||||
else if (Array.IndexOf(warnings, left) >= 0)
|
||||
{
|
||||
var severity = left == warnings[^1] ? EventSeverity.Critical : EventSeverity.Warning;
|
||||
ctx.Emit(new GameEvent(ctx.Day, EventKind.Finance, severity,
|
||||
$"{c.Name}: cassa negativa da {Days(c.NegativeCashDays)} ({c.Cash}), bancarotta tra {Days(left)}",
|
||||
EntityKind.Company, c.Id.Value, c.Id));
|
||||
}
|
||||
}
|
||||
|
||||
private static string Days(int n) => n == 1 ? "1 giorno" : $"{n} giorni";
|
||||
|
||||
/// <summary>
|
||||
/// Costi d'esercizio giornalieri: veicoli posseduti (voce «Esercizio dei treni») e binari di stazione
|
||||
/// e depositi (voce «Stazioni e depositi», ADR 0019).
|
||||
/// </summary>
|
||||
private void PayRunningCosts(World w)
|
||||
{
|
||||
if (_running.Length < w.Companies.Count) _running = new double[w.Companies.Count];
|
||||
if (_running.Length < w.Companies.Count)
|
||||
{
|
||||
_running = new double[w.Companies.Count];
|
||||
_upkeep = new double[w.Companies.Count];
|
||||
}
|
||||
Array.Clear(_running);
|
||||
Array.Clear(_upkeep);
|
||||
double days = w.Calendar.DaysPerYear;
|
||||
foreach (var v in w.Vehicles)
|
||||
{
|
||||
@@ -70,61 +141,106 @@ public sealed class FinanceSystem : ISimSystem
|
||||
var sp = w.Data.Construction.Stations;
|
||||
foreach (var s in w.Network.Stations)
|
||||
{
|
||||
if (w.Network.Nodes[s.Node.Value].Station == s.Id) _running[s.Owner.Value] += s.Platforms * sp.UpkeepPerPlatformPerYear / days;
|
||||
if (w.Network.Nodes[s.Node.Value].Station == s.Id) _upkeep[s.Owner.Value] += s.Platforms * sp.UpkeepPerPlatformPerYear / days;
|
||||
}
|
||||
foreach (var d in w.Network.Depots)
|
||||
{
|
||||
if (w.Network.Nodes[d.Node.Value].Depot == d.Id) _running[d.Owner.Value] += sp.DepotUpkeepPerYear[d.Size] / days;
|
||||
if (w.Network.Nodes[d.Node.Value].Depot == d.Id) _upkeep[d.Owner.Value] += sp.DepotUpkeepPerYear[d.Size] / days;
|
||||
}
|
||||
for (int i = 0; i < w.Companies.Count; i++)
|
||||
{
|
||||
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);
|
||||
if (w.Companies[i].Defunct) continue;
|
||||
var account = Account.Of(w.Companies[i].Id);
|
||||
if (_running[i] > 0) w.Money.Transfer(account, Account.External, Money.FromCentsRounded(_running[i]), LedgerEntry.RunningCosts);
|
||||
if (_upkeep[i] > 0) w.Money.Transfer(account, Account.External, Money.FromCentsRounded(_upkeep[i]), LedgerEntry.StationUpkeep);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Salari giornalieri del personale presente nei depositi (operai e tecnici, sezione 9), alle paghe
|
||||
/// delle industrie (balance.json, industry.wagePerWorkerPerMonth e wagePerStaffPerMonth): la voce
|
||||
/// «Stipendi» della guida 6.3 (ADR 0019).
|
||||
/// </summary>
|
||||
private void PayDepotWages(World w)
|
||||
{
|
||||
if (_wages.Length < w.Companies.Count) _wages = new double[w.Companies.Count];
|
||||
Array.Clear(_wages);
|
||||
var ib = w.Data.Balance.Industry;
|
||||
double daysPerMonth = w.Calendar.DaysPerMonth;
|
||||
foreach (var d in w.Network.Depots)
|
||||
{
|
||||
if (!d.Owner.IsValid || d.Owner.Value >= _wages.Length || !w.Network.IsAlive(d)) continue;
|
||||
_wages[d.Owner.Value] += (d.WorkersPresent * ib.WagePerWorkerPerMonth + d.StaffPresent * ib.WagePerStaffPerMonth) / daysPerMonth;
|
||||
}
|
||||
for (int i = 0; i < w.Companies.Count; i++)
|
||||
{
|
||||
if (_wages[i] <= 0 || w.Companies[i].Defunct) continue;
|
||||
w.Money.Transfer(Account.Of(w.Companies[i].Id), Account.External, Money.FromCentsRounded(_wages[i]), LedgerEntry.Wages);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Valore contabile degli attivi: binari e veicoli ammortizzati, stazioni e depositi al costo,
|
||||
/// merce della compagnia (magazzini e spedizioni in viaggio) al prezzo globale (ADR 0016).
|
||||
/// industrie possedute (impianti e cassa dell'impresa, ADR 0018), merce della compagnia
|
||||
/// (magazzini e spedizioni in viaggio) al prezzo globale (ADR 0016). Scrive le voci in
|
||||
/// <see cref="Company.BookValues"/>: il patrimonio netto le somma.
|
||||
/// </summary>
|
||||
public static void UpdateBookValues(World w)
|
||||
{
|
||||
var values = BookValues(w);
|
||||
for (int i = 0; i < w.Companies.Count; i++) Array.Copy(values[i], w.Companies[i].BookValues, AssetCategories.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stato patrimoniale degli attivi non monetari di ogni compagnia, per voce
|
||||
/// (<see cref="AssetCategory"/>), calcolato al giorno corrente. Unica fonte del valore contabile.
|
||||
/// </summary>
|
||||
public static long[][] BookValues(World w)
|
||||
{
|
||||
var fb = w.Data.Balance.Finance;
|
||||
var values = new long[w.Companies.Count];
|
||||
var values = new long[w.Companies.Count][];
|
||||
for (int i = 0; i < values.Length; i++) values[i] = new long[AssetCategories.Count];
|
||||
const int track = (int)AssetCategory.Track, stations = (int)AssetCategory.Stations, vehicles = (int)AssetCategory.Vehicles,
|
||||
industries = (int)AssetCategory.Industries, goods = (int)AssetCategory.Goods;
|
||||
double daysPerYear = w.Calendar.DaysPerYear;
|
||||
long today = w.Clock.Day;
|
||||
foreach (var e in w.Network.Edges)
|
||||
{
|
||||
if (e.State == Rail.EdgeState.Demolished) continue;
|
||||
double age = (today - e.BuiltDay) / daysPerYear;
|
||||
values[e.Owner.Value] += (long)(e.BuildCostCents * Math.Max(fb.BookValueFloor, 1 - age / fb.DepreciationYearsTrack));
|
||||
values[e.Owner.Value][track] += (long)(e.BuildCostCents * Math.Max(fb.BookValueFloor, 1 - age / fb.DepreciationYearsTrack));
|
||||
}
|
||||
foreach (var s in w.Network.Stations)
|
||||
{
|
||||
if (w.Network.Nodes[s.Node.Value].Station == s.Id) values[s.Owner.Value] += s.BuildCostCents;
|
||||
if (w.Network.Nodes[s.Node.Value].Station == s.Id) values[s.Owner.Value][stations] += s.BuildCostCents;
|
||||
}
|
||||
foreach (var d in w.Network.Depots)
|
||||
{
|
||||
if (w.Network.Nodes[d.Node.Value].Depot == d.Id) values[d.Owner.Value] += d.BuildCostCents;
|
||||
if (w.Network.Nodes[d.Node.Value].Depot == d.Id) values[d.Owner.Value][stations] += d.BuildCostCents;
|
||||
}
|
||||
foreach (var v in w.Vehicles)
|
||||
{
|
||||
if (v.Sold) continue;
|
||||
double age = (today - v.BoughtDay) / daysPerYear;
|
||||
values[v.Owner.Value] += (long)(v.Def.Price * Math.Max(fb.BookValueFloor, 1 - age / v.Def.LifeYears));
|
||||
// stessa curva della rivendita, con l'obsolescenza dei modelli superati (ADR 0020)
|
||||
values[v.Owner.Value][vehicles] += Obsolescence.BookValueCents(w, v);
|
||||
}
|
||||
foreach (var ind in w.Industries)
|
||||
{
|
||||
if (ind.Closed || !ind.Owner.IsValid || ind.Owner.Value >= values.Length) continue;
|
||||
values[ind.Owner.Value][industries] += IndustryMath.BookValue(w, ind).Cents;
|
||||
}
|
||||
var prices = w.Market.GlobalPrice;
|
||||
foreach (var s in w.Network.Stations)
|
||||
{
|
||||
if (!s.Owner.IsValid || s.Owner.Value >= values.Length) continue;
|
||||
for (int g = 0; g < s.Stock.Length; g++) values[s.Owner.Value] += (long)(s.Stock[g] * prices[g]);
|
||||
values[s.Owner.Value] += OwnedGoodsValue(s.Waiting, prices);
|
||||
for (int g = 0; g < s.Stock.Length; g++) values[s.Owner.Value][goods] += (long)(s.Stock[g] * prices[g]);
|
||||
values[s.Owner.Value][goods] += OwnedGoodsValue(s.Waiting, prices);
|
||||
}
|
||||
foreach (var t in w.Trains)
|
||||
{
|
||||
if (!t.Removed && t.Owner.IsValid && t.Owner.Value < values.Length) values[t.Owner.Value] += OwnedGoodsValue(t.Cargo, prices);
|
||||
if (!t.Removed && t.Owner.IsValid && t.Owner.Value < values.Length) values[t.Owner.Value][goods] += OwnedGoodsValue(t.Cargo, prices);
|
||||
}
|
||||
for (int i = 0; i < w.Companies.Count; i++) w.Companies[i].AssetBookValue = new Money(values[i]);
|
||||
return values;
|
||||
}
|
||||
|
||||
private static long OwnedGoodsValue(List<Rail.Packet> packets, double[] prices)
|
||||
@@ -170,35 +286,104 @@ public sealed class FinanceSystem : ISimSystem
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rating da margine operativo e leva: punteggio = pesoMargine·clamp(0,5 + margine) +
|
||||
/// pesoLeva·clamp(1 − debito/attivi), confrontato con le soglie di balance.json.
|
||||
/// Misure del rating (ADR 0019): margine = utile operativo / ricavi dei mesi chiusi conservati
|
||||
/// (finance.incomeMonths, 12), leva = debiti (prestiti e scoperto di cassa) / patrimonio netto
|
||||
/// (+∞ con patrimonio non positivo e debiti).
|
||||
/// Il margine è neutro (0) finché la finestra non è piena e ha meno di finance.ratingMinRevenueMonths
|
||||
/// mesi con ricavi: i primi incassi, piccoli rispetto ai costi dei mesi d'avvio, non fanno crollare il
|
||||
/// rating per poi farlo risalire il mese dopo. Con la finestra piena (o con abbastanza mesi di ricavi)
|
||||
/// conta il margine vero; senza ricavi e in perdita è il minimo (−100 %, componente nulla).
|
||||
/// </summary>
|
||||
public static CreditRating ComputeRating(World w, Company c)
|
||||
public static RatingMeasures Measures(World w, Company c)
|
||||
{
|
||||
var fb = w.Data.Balance.Finance;
|
||||
long[] entries = w.Clock.Day % w.Calendar.DaysPerYear < 90 ? c.LastYearEntries : c.YearEntries;
|
||||
long revenue = Company.Revenue(entries);
|
||||
long profit = Company.OperatingProfit(entries);
|
||||
double margin = revenue > 0 ? (double)profit / revenue : 0;
|
||||
double assets = Math.Max(1, c.Cash.Cents + c.AssetBookValue.Cents);
|
||||
double leverage = c.Debt.Cents / assets;
|
||||
double score = fb.ProfitMarginWeight * Math.Clamp(0.5 + margin, 0, 1) + fb.LeverageWeight * Math.Clamp(1 - leverage, 0, 1);
|
||||
if (c.Bankrupt) return CreditRating.D;
|
||||
for (int i = 0; i < fb.RatingByScore.Length; i++)
|
||||
long revenue = 0, profit = 0;
|
||||
int revenueMonths = 0;
|
||||
foreach (var m in c.IncomeMonths)
|
||||
{
|
||||
if (score >= fb.RatingByScore[i]) return (CreditRating)i;
|
||||
long r = Company.Revenue(m.Entries);
|
||||
revenue += r;
|
||||
profit += Company.OperatingProfit(m.Entries);
|
||||
if (r > 0) revenueMonths++;
|
||||
}
|
||||
bool neutral = revenueMonths < fb.RatingMinRevenueMonths && c.IncomeMonths.Count < fb.IncomeMonths;
|
||||
double margin = neutral ? 0 : revenue > 0 ? (double)profit / revenue : profit < 0 ? -1 : 0;
|
||||
long debt = c.Debt.Cents + Math.Max(0, -c.Cash.Cents);
|
||||
long equity = c.NetWorth.Cents;
|
||||
double leverage = debt <= 0 ? 0 : equity <= 0 ? double.PositiveInfinity : (double)debt / equity;
|
||||
return new RatingMeasures(c.IncomeMonths.Count, revenueMonths, neutral, revenue, profit, margin, debt, equity, leverage);
|
||||
}
|
||||
|
||||
/// <summary>Componente del margine nel punteggio: clamp(0,5 + margine, 0, 1).</summary>
|
||||
public static double MarginComponent(double margin) => DMath.Clamp(0.5 + margin, 0, 1);
|
||||
|
||||
/// <summary>
|
||||
/// Componente della leva nel punteggio: 1 / (1 + debiti/patrimonio), cioè patrimonio / (debiti +
|
||||
/// patrimonio): 1 senza debiti, 0 con patrimonio non positivo e debiti.
|
||||
/// </summary>
|
||||
public static double LeverageComponent(double leverage) =>
|
||||
double.IsPositiveInfinity(leverage) ? 0 : DMath.Clamp(1 / (1 + Math.Max(0, leverage)), 0, 1);
|
||||
|
||||
/// <summary>Punteggio del rating (0–1): pesoMargine·componente del margine + pesoLeva·componente della leva.</summary>
|
||||
public static double Score(World w, double margin, double leverage)
|
||||
{
|
||||
var fb = w.Data.Balance.Finance;
|
||||
return fb.ProfitMarginWeight * MarginComponent(margin) + fb.LeverageWeight * LeverageComponent(leverage);
|
||||
}
|
||||
|
||||
/// <summary>Rating di un punteggio con le soglie di balance.json (finance.ratingByScore, da AAA a C; sotto è D).</summary>
|
||||
public static CreditRating RatingOf(World w, double score)
|
||||
{
|
||||
var thresholds = w.Data.Balance.Finance.RatingByScore;
|
||||
for (int i = 0; i < thresholds.Length; i++)
|
||||
{
|
||||
if (score >= thresholds[i]) return (CreditRating)i;
|
||||
}
|
||||
return CreditRating.D;
|
||||
}
|
||||
|
||||
/// <summary>Fido massimo della compagnia secondo il livello raggiunto.</summary>
|
||||
public static Money MaxLoan(World w, Company c)
|
||||
/// <summary>
|
||||
/// Rating di credito (guida 6.3) dalle due misure di <see cref="Measures"/> confrontate con le soglie;
|
||||
/// D per una compagnia in bancarotta. Non scrive nulla.
|
||||
/// </summary>
|
||||
public static CreditRating ComputeRating(World w, Company c)
|
||||
{
|
||||
var tier = w.Data.Tiers.Tiers[Math.Clamp(c.Tier, 1, w.Data.Tiers.Tiers.Count) - 1];
|
||||
return c.BaseCredit * tier.Unlocks.MaxLoanFactor;
|
||||
var m = Measures(w, c);
|
||||
return c.Bankrupt ? CreditRating.D : RatingOf(w, Score(w, m.Margin, m.Leverage));
|
||||
}
|
||||
|
||||
/// <summary>Tasso annuo per un nuovo prestito: base della difficoltà + spread del rating.</summary>
|
||||
public static double LoanRate(World w, Company c) =>
|
||||
w.Difficulty.BaseInterestRate + w.Data.Balance.Finance.RatingSpreads[c.Rating.ToString()];
|
||||
/// <summary>
|
||||
/// Rating mensile, dopo la chiusura del mese: calcola il rating e conserva nella compagnia le misure
|
||||
/// usate (margine, leva, punteggio, mesi della finestra), così il quadro delle finanze lo spiega.
|
||||
/// </summary>
|
||||
public static void UpdateRating(World w, Company c)
|
||||
{
|
||||
var m = Measures(w, c);
|
||||
c.RatingMargin = m.Margin;
|
||||
c.RatingLeverage = m.Leverage;
|
||||
c.RatingScore = Score(w, m.Margin, m.Leverage);
|
||||
c.RatingMonths = m.Months;
|
||||
c.Rating = c.Bankrupt ? CreditRating.D : RatingOf(w, c.RatingScore);
|
||||
}
|
||||
|
||||
/// <summary>Fido massimo della compagnia secondo il livello raggiunto.</summary>
|
||||
public static Money MaxLoan(World w, Company c) => Tiers.LoanLimit(c, Tiers.Def(w, c.Tier));
|
||||
|
||||
/// <summary>
|
||||
/// Tasso annuo per un nuovo prestito: base della difficoltà + spread del rating attuale. Il tasso resta
|
||||
/// fisso per tutta la durata del prestito (ADR 0019).
|
||||
/// </summary>
|
||||
public static double LoanRate(World w, Company c) => LoanRate(w, c.Rating);
|
||||
|
||||
/// <summary>Tasso annuo di un nuovo prestito con il rating indicato.</summary>
|
||||
public static double LoanRate(World w, CreditRating rating) =>
|
||||
w.Difficulty.BaseInterestRate + w.Data.Balance.Finance.RatingSpreads[rating.ToString()];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Misure del rating (ADR 0019): mesi della finestra e quanti con ricavi, margine neutro (avvio), ricavi e
|
||||
/// utile operativo dei mesi, margine, debiti (prestiti e scoperto) e patrimonio netto in centesimi,
|
||||
/// leva = debiti / patrimonio.
|
||||
/// </summary>
|
||||
public readonly record struct RatingMeasures(int Months, int RevenueMonths, bool MarginNeutral, long Revenue, long Profit, double Margin,
|
||||
long Debt, long Equity, double Leverage);
|
||||
@@ -7,6 +7,12 @@ namespace RailEnterprise.Core.Simulation.Systems;
|
||||
/// <summary>Scadenze di un treno in giorni (negative se già scadute).</summary>
|
||||
public readonly record struct FleetDues(double Inspection, double Service, double Overhaul, double Condition, bool ConditionIsBrakes);
|
||||
|
||||
/// <summary>
|
||||
/// Stima del pianificatore sulla condizione (giorni) con il veicolo e il componente che la danno, la loro
|
||||
/// condizione e la loro usura giornaliera (ADR 0024): Days = MaxValue se nessun componente si consuma.
|
||||
/// </summary>
|
||||
public readonly record struct ConditionDueInfo(double Days, Vehicle? Vehicle, int Component, double Condition, double Rate, bool IsBrakes);
|
||||
|
||||
/// <summary>Prossimo intervento di un treno: indice in maintenance.json e giorni alla scadenza.</summary>
|
||||
public readonly record struct NextIntervention(int Intervention, double Days);
|
||||
|
||||
@@ -47,6 +53,33 @@ public static class Fleet
|
||||
public static double Hazard(double condition, FailureParams f) =>
|
||||
condition < f.Pivot ? f.H0 * DMath.Exp(f.Slope * (f.Pivot - condition) / f.Scale) : f.H0 / f.HealthyDivisor;
|
||||
|
||||
/// <summary>
|
||||
/// Rischio giornaliero di guasto del treno nel giorno indicato: il più alto tra i componenti di tutti i
|
||||
/// veicoli (<see cref="Hazard"/>, ridotto dopo un'ispezione), con il veicolo e il componente che lo danno
|
||||
/// (il primo a parità). Lo usa il controllo dei guasti e la spiegazione della condizione (ADR 0024).
|
||||
/// </summary>
|
||||
public static (double Hazard, Vehicle? Vehicle, int Component) DailyHazard(World w, Train t, long day)
|
||||
{
|
||||
var m = w.Data.Maintenance;
|
||||
double best = -1;
|
||||
Vehicle? bv = null;
|
||||
int bc = -1;
|
||||
foreach (var id in t.Vehicles)
|
||||
{
|
||||
var v = w.Vehicles[id.Value];
|
||||
for (int j = 0; j < v.Components.Length; j++)
|
||||
{
|
||||
double h = Hazard(v.Components[j], m.Failure);
|
||||
if (day < v.HazardReducedUntilDay) h *= m.Inspection.HazardFactor;
|
||||
if (h <= best) continue;
|
||||
best = h;
|
||||
bv = v;
|
||||
bc = j;
|
||||
}
|
||||
}
|
||||
return (best, bv, bc);
|
||||
}
|
||||
|
||||
/// <summary>Fattore d'età: 1 fino alla vita utile, poi +0,5 ogni 5 anni, meno le riduzioni delle revisioni (minimo 1).</summary>
|
||||
public static double AgeFactor(World w, Vehicle v) => AgeFactor(w.Data.Maintenance.Wear, v, w.Clock.Day, w.Calendar.DaysPerYear);
|
||||
|
||||
@@ -121,8 +154,7 @@ public static class Fleet
|
||||
double f = policy.IntervalFactor;
|
||||
long today = w.Clock.Day;
|
||||
double kmPerDay = Math.Max(t.ServiceKmPerDay, 1e-6);
|
||||
double ins = double.MaxValue, ser = double.MaxValue, ov = double.MaxValue, cond = double.MaxValue;
|
||||
bool condBrakes = false;
|
||||
double ins = double.MaxValue, ser = double.MaxValue, ov = double.MaxValue;
|
||||
foreach (var id in t.Vehicles)
|
||||
{
|
||||
var v = w.Vehicles[id.Value];
|
||||
@@ -131,6 +163,23 @@ public static class Fleet
|
||||
ser = Math.Min(ser, Math.Min((m.Intervals.ServiceKm * f - (v.OdometerKm - v.LastServiceKm)) / kmPerDay,
|
||||
m.Intervals.ServiceDays * f - (today - v.LastServiceDay)));
|
||||
ov = Math.Min(ov, m.Intervals.OverhaulYears * f * w.Calendar.DaysPerYear - (today - v.LastOverhaulDay));
|
||||
}
|
||||
var cond = ConditionDue(w, t);
|
||||
return new FleetDues(ins, ser, ov, cond.Days, cond.IsBrakes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stima del pianificatore sulla condizione: il minimo su tutti i componenti di (c − obiettivo)/usura − margine
|
||||
/// (−margine se il componente è già all'obiettivo o sotto; esclusi quelli che non si consumano), con il
|
||||
/// componente che la dà (il primo a parità). La usano <see cref="Dues"/> e la spiegazione della condizione.
|
||||
/// </summary>
|
||||
public static ConditionDueInfo ConditionDue(World w, Train t)
|
||||
{
|
||||
var m = w.Data.Maintenance;
|
||||
var best = new ConditionDueInfo(double.MaxValue, null, -1, 100, 0, false);
|
||||
foreach (var id in t.Vehicles)
|
||||
{
|
||||
var v = w.Vehicles[id.Value];
|
||||
var comps = ComponentsOf(w.Data, v.Def);
|
||||
for (int j = 0; j < v.Components.Length && j < comps.Count; j++)
|
||||
{
|
||||
@@ -140,14 +189,10 @@ public static class Fleet
|
||||
if (c <= m.Planner.TargetCondition) days = -m.Planner.MarginDays;
|
||||
else if (rate > 1e-9) days = (c - m.Planner.TargetCondition) / rate - m.Planner.MarginDays;
|
||||
else continue;
|
||||
if (days < cond)
|
||||
{
|
||||
cond = days;
|
||||
condBrakes = comps[j].Id == Brakes;
|
||||
}
|
||||
if (days < best.Days) best = new ConditionDueInfo(days, v, j, c, rate, comps[j].Id == Brakes);
|
||||
}
|
||||
}
|
||||
return new FleetDues(ins, ser, ov, cond, condBrakes);
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -173,27 +218,35 @@ public static class Fleet
|
||||
public static int PartsFor(World w, Train t, InterventionDef def) =>
|
||||
def.Effect == InterventionEffect.Repair ? def.SpareParts : def.SpareParts * t.Vehicles.Count;
|
||||
|
||||
/// <summary>Costo dell'intervento: quota del prezzo dei veicoli interessati × fattore di costo della politica.</summary>
|
||||
/// <summary>
|
||||
/// Costo dell'intervento: quota del prezzo dei veicoli interessati × fattore di costo della politica;
|
||||
/// il prezzo di un modello superato conta maintenanceCostFactor volte (ricambi fuori catalogo, ADR 0020).
|
||||
/// </summary>
|
||||
public static Money CostOf(World w, Train t, InterventionDef def, PolicyDef policy)
|
||||
{
|
||||
long price = 0;
|
||||
double price = 0;
|
||||
int year = w.Clock.Year;
|
||||
if (def.Effect == InterventionEffect.Repair)
|
||||
{
|
||||
if (t.FailedVehicle.IsValid) price = w.Vehicles[t.FailedVehicle.Value].Def.Price;
|
||||
if (t.FailedVehicle.IsValid) price = WeightedPrice(w.Data, w.Vehicles[t.FailedVehicle.Value].Def, year);
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (var id in t.Vehicles) price += w.Vehicles[id.Value].Def.Price;
|
||||
foreach (var id in t.Vehicles) price += WeightedPrice(w.Data, w.Vehicles[id.Value].Def, year);
|
||||
}
|
||||
return Money.FromCentsRounded(price * def.CostShare * policy.CostFactor);
|
||||
}
|
||||
|
||||
private static double WeightedPrice(GameData d, VehicleDef def, int year) => def.Price * Obsolescence.MaintenanceCostFactor(d, def, year);
|
||||
|
||||
/// <summary>Applica gli effetti dell'intervento ai veicoli del treno (10.2), scalati dalla politica.</summary>
|
||||
public static void Apply(World w, Train t, InterventionDef def, PolicyDef policy)
|
||||
{
|
||||
var m = w.Data.Maintenance;
|
||||
long today = w.Clock.Day;
|
||||
double ef = policy.EffectFactor;
|
||||
// rinnovo: i veicoli superati si sono già sostituiti all'avvio dei lavori, quando si è pagato (ADR 0020)
|
||||
if (def.Effect == InterventionEffect.Renew) return;
|
||||
foreach (var id in t.Vehicles)
|
||||
{
|
||||
var v = w.Vehicles[id.Value];
|
||||
@@ -227,11 +280,17 @@ public static class Fleet
|
||||
Raise(v, t.FailedComponent, def.RestoreTo ?? 100, ef);
|
||||
break;
|
||||
case InterventionEffect.Replace:
|
||||
// veicolo sostituito: nuovo di fabbrica
|
||||
// veicolo ricostruito: componenti nuovi di fabbrica. L'età contabile riparte solo se il
|
||||
// modello è ancora in produzione: un modello che non si compra più non torna nuovo nel
|
||||
// patrimonio (ADR 0020), l'usura però riparte da capo
|
||||
for (int j = 0; j < v.Components.Length; j++) v.Components[j] = 100;
|
||||
v.BoughtDay = today;
|
||||
if (Obsolescence.InProduction(v.Def, w.Clock.Year))
|
||||
{
|
||||
v.BoughtDay = today;
|
||||
v.AgeFactorOffset = 0;
|
||||
}
|
||||
else v.AgeFactorOffset = Math.Max(0, RawAgeFactor(m.Wear, v, today, w.Calendar.DaysPerYear) - 1);
|
||||
v.OdometerKm = 0;
|
||||
v.AgeFactorOffset = 0;
|
||||
Array.Clear(v.WearEma);
|
||||
MarkInspection(v, today);
|
||||
MarkService(v, today);
|
||||
|
||||
@@ -120,22 +120,7 @@ public sealed class FleetMaintenanceSystem : ISimSystem
|
||||
{
|
||||
var w = ctx.World;
|
||||
var m = w.Data.Maintenance;
|
||||
double best = -1;
|
||||
Vehicle? bv = null;
|
||||
int bc = -1;
|
||||
foreach (var id in t.Vehicles)
|
||||
{
|
||||
var v = w.Vehicles[id.Value];
|
||||
for (int j = 0; j < v.Components.Length; j++)
|
||||
{
|
||||
double h = Fleet.Hazard(v.Components[j], m.Failure);
|
||||
if (ctx.Day < v.HazardReducedUntilDay) h *= m.Inspection.HazardFactor;
|
||||
if (h <= best) continue;
|
||||
best = h;
|
||||
bv = v;
|
||||
bc = j;
|
||||
}
|
||||
}
|
||||
var (best, bv, bc) = Fleet.DailyHazard(w, t, ctx.Day);
|
||||
if (bv is null) return;
|
||||
var rng = w.Stream("fleet");
|
||||
if (rng.NextDouble() >= best) return;
|
||||
@@ -489,7 +474,13 @@ public sealed class FleetMaintenanceSystem : ISimSystem
|
||||
waitingParts = true;
|
||||
continue;
|
||||
}
|
||||
Start(ctx, d, job, t, rate);
|
||||
if (!Start(ctx, d, job, t, rate))
|
||||
{
|
||||
// rinnovo annullato all'avvio: il treno esce dall'officina senza lavori
|
||||
d.Jobs.RemoveAt(i--);
|
||||
inStall--;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
job.Progress += rate;
|
||||
if (job.Progress + 1e-9 < job.Days) continue;
|
||||
@@ -507,19 +498,50 @@ public sealed class FleetMaintenanceSystem : ISimSystem
|
||||
else if (!waitingParts) d.PartsAlerted = false;
|
||||
}
|
||||
|
||||
private static void Start(WorldContext ctx, Depot d, WorkshopJob job, Train t, double rate)
|
||||
/// <summary>Avvia il lavoro: preleva i ricambi e paga l'intervento. Falso se un rinnovo si annulla.</summary>
|
||||
private static bool Start(WorldContext ctx, Depot d, WorkshopJob job, Train t, double rate)
|
||||
{
|
||||
var w = ctx.World;
|
||||
var m = w.Data.Maintenance;
|
||||
var def = m.Interventions[job.Intervention];
|
||||
var cost = Fleet.CostOf(w, t, def, Fleet.PolicyOf(w, t));
|
||||
List<RenewalItem>? plan = null;
|
||||
if (def.Effect == InterventionEffect.Renew)
|
||||
{
|
||||
// rinnovo (ADR 0020): piano, spesa e cassa si controllano qui, quando si paga, non solo alla
|
||||
// prenotazione: tra le due l'anno può cambiare il piano e la cassa può essersi spesa altrove
|
||||
plan = Obsolescence.RenewalPlan(w, t);
|
||||
var total = Obsolescence.NetCost(plan) + cost;
|
||||
var company = w.Companies[t.Owner.Value];
|
||||
string? why = plan.Count == 0 ? "nessun veicolo superato con un successore in produzione"
|
||||
: total.IsPositive && company.Cash < total ? $"cassa insufficiente per la spesa netta di {total}" : null;
|
||||
if (why is not null)
|
||||
{
|
||||
t.InWorkshop = false;
|
||||
t.MaintenanceDepot = DepotId.None;
|
||||
t.PlannedIntervention = -1;
|
||||
w.Events.Add(new GameEvent(ctx.Day, EventKind.Maintenance, EventSeverity.Warning,
|
||||
$"{t.Name}: rinnovo annullato a {d.Name}, {why}", EntityKind.Train, t.Id.Value, t.Owner));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
d.SpareParts -= job.Parts;
|
||||
w.Goods.Consumed[w.Data.SparePartsGood] += job.Parts;
|
||||
var cost = Fleet.CostOf(w, t, def, Fleet.PolicyOf(w, t));
|
||||
if (cost.IsPositive) w.Money.Transfer(Account.Of(t.Owner), Account.External, cost, LedgerEntry.FleetMaintenance);
|
||||
job.CostCents = cost.Cents;
|
||||
job.Started = true;
|
||||
t.MaintenanceThisYear += cost.Cents;
|
||||
if (plan is not null)
|
||||
{
|
||||
// i veicoli si sostituiscono all'avvio, con il piano appena pagato; i giorni d'officina sono la messa in servizio
|
||||
var net = Obsolescence.NetCost(plan);
|
||||
int renewed = Obsolescence.Renew(w, t, plan);
|
||||
string what = renewed == 1 ? "1 veicolo sostituito" : $"{renewed} veicoli sostituiti";
|
||||
w.Events.Add(new GameEvent(ctx.Day, EventKind.Maintenance, EventSeverity.Info,
|
||||
$"{t.Name}: rinnovo avviato a {d.Name}, {what} (spesa netta {net + cost})", EntityKind.Train, t.Id.Value, t.Owner));
|
||||
}
|
||||
if (job.Days / rate >= m.Planner.ReserveMinDays) Cover(ctx, t, d);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void Complete(WorldContext ctx, Depot d, WorkshopJob job, Train t)
|
||||
@@ -549,6 +571,11 @@ public sealed class FleetMaintenanceSystem : ISimSystem
|
||||
w.Events.Add(new GameEvent(ctx.Day, EventKind.Maintenance, EventSeverity.Info,
|
||||
$"{t.Name}: {def.NameIt.ToLowerInvariant()} completata a {d.Name}", EntityKind.Train, t.Id.Value, t.Owner));
|
||||
}
|
||||
else if (def.Effect == InterventionEffect.Renew)
|
||||
{
|
||||
w.Events.Add(new GameEvent(ctx.Day, EventKind.Maintenance, EventSeverity.Info,
|
||||
$"{t.Name}: rinnovo completato a {d.Name}", EntityKind.Train, t.Id.Value, t.Owner));
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ riserve
|
||||
|
||||
Loaded 100 of 141 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user