diff --git a/client/RailEnterprise.Client/assets/i18n/strings.csv b/client/RailEnterprise.Client/assets/i18n/strings.csv
index 99eff90..a689ca5 100644
--- a/client/RailEnterprise.Client/assets/i18n/strings.csv
+++ b/client/RailEnterprise.Client/assets/i18n/strings.csv
@@ -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
@@ -561,6 +641,8 @@ 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
@@ -576,14 +658,19 @@ 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
@@ -611,6 +698,9 @@ 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
@@ -633,6 +723,8 @@ 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
@@ -660,6 +752,8 @@ 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
@@ -670,6 +764,8 @@ Cassa negativa da {0}: bancarotta tra {1},,Cash negative for {0}: bankruptcy in
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})
@@ -677,52 +773,106 @@ una leva non oltre {0} (rimborsando {1}),,leverage no higher than {0} (by repayi
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 dal menu,,Reopen the tutorial with F1 or from the menu
-Mostra il tutorial,,Show the tutorial
-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
-Partita locale con il tutorial dal primo passo,,Local game with the tutorial from the first step
-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.
+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)
diff --git a/client/RailEnterprise.Client/scripts/App/AutoPilot.cs b/client/RailEnterprise.Client/scripts/App/AutoPilot.cs
index 7394a92..3b4f3a2 100644
--- a/client/RailEnterprise.Client/scripts/App/AutoPilot.cs
+++ b/client/RailEnterprise.Client/scripts/App/AutoPilot.cs
@@ -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);
@@ -254,5 +255,33 @@ public partial class AutoPilot : Node
_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();
}
}
diff --git a/client/RailEnterprise.Client/scripts/Audio/AudioManager.cs b/client/RailEnterprise.Client/scripts/Audio/AudioManager.cs
new file mode 100644
index 0000000..29814ba
--- /dev/null
+++ b/client/RailEnterprise.Client/scripts/Audio/AudioManager.cs
@@ -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;
+
+///
+/// Regia dell'audio, figlia di Main 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, DailyDigest , moti dei treni) e alla vista.
+/// I suoni si sintetizzano all'avvio su un altro thread ( , );
+/// nel ciclo per fotogramma non si alloca (elenchi preparati, nessuna LINQ).
+///
+public partial class AudioManager : Node
+{
+ /// Unica istanza (nulla prima dell'avvio del client).
+ public static AudioManager? Instance { get; private set; }
+
+ /// Volumi e muto attuali (anche con l'audio disattivato, per il pannello).
+ public AudioSettings Settings { get; private set; } = new();
+
+ /// Cambio di volumi o muto (per aggiornare il pannello e l'icona della barra).
+ public event Action? SettingsChanged;
+
+ private readonly bool _enabled;
+ private Task? _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];
+
+ ///
+ /// 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.
+ ///
+ 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 _themes = [];
+ private readonly HashSet _failedThemes = [];
+ private Task? _composing;
+ private int _composingEra;
+ private string[] _eraIds = ["steam"];
+ private int[] _eraFroms = [0];
+
+ // partita in corso
+ private GameSession? _session;
+ private MapView? _map;
+ private Dictionary _vehicles = [];
+ private SynthRng _rng = new(0xA0D10);
+ private ulong _lastUiMs, _lastNotifyMs;
+ private bool _settingsDirty;
+
+ // pannello delle impostazioni
+ private CanvasLayer? _overlay;
+ private AudioSettingsPanel? _panel;
+
+ /// Falso nel pilota automatico e senza schermo: niente sintesi né riproduzione, Master muto.
+ 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();
+ }
+
+ /// Ere di eras.json (id e anno d'inizio, crescenti): scelgono il tema musicale.
+ public void SetEras(IReadOnlyList 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);
+ }
+
+ /// Cambia il volume di un bus (indice in ) e lo applica subito.
+ 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();
+ }
+
+ /// Scrive volumi e muto in user://settings.cfg se sono cambiati dall'ultimo salvataggio.
+ public void SaveSettings()
+ {
+ if (!_settingsDirty) return;
+ _settingsDirty = false;
+ Settings.Save();
+ }
+
+ /// Apre il pannello «Audio» sopra a tutto (menu o partita).
+ 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
+
+ /// Collega la partita: messaggi della sessione e vista della mappa.
+ 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;
+ }
+
+ ///
+ /// 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).
+ ///
+ 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;
+ }
+ }
+
+ /// Codice di EventKind.Construction nel protocollo (cantiere completato, sempre informativo).
+ 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
+
+ /// Campioni di tutti gli effetti e degli anelli, sintetizzati fuori dal thread principale.
+ 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);
+ }
+ }
+ }
+
+ /// Frazioni del terreno su una griglia 8×8 della vista (allargata di un quarto per sentire l'acqua vicina).
+ 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);
+ }
+ }
+
+ /// Trazione della prima locomotiva del treno (vapore se non si sa).
+ 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;
+ }
+}
diff --git a/client/RailEnterprise.Client/scripts/Audio/AudioMix.cs b/client/RailEnterprise.Client/scripts/Audio/AudioMix.cs
new file mode 100644
index 0000000..6273967
--- /dev/null
+++ b/client/RailEnterprise.Client/scripts/Audio/AudioMix.cs
@@ -0,0 +1,150 @@
+namespace RailEnterprise.Client.Audio;
+
+/// Frazioni del terreno sotto la telecamera (somma 1 sui campioni letti).
+public struct TerrainMix
+{
+ public float River;
+ public float Lake;
+ public float Sea;
+ public float Town;
+ public float Forest;
+ public float Open;
+}
+
+/// Guadagni lineari (0–1) dei quattro anelli d'ambiente e probabilità relativa degli uccelli.
+public readonly record struct AmbienceGains(float Wind, float Water, float Sea, float City, float Birds);
+
+///
+/// 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.
+///
+public static class AudioMix
+{
+ /// Zoom (pixel per metro) sotto il quale si sente quasi solo il vento della vista d'insieme.
+ public const float FarZoom = 0.02f;
+ /// Zoom da cui ambiente e treni sono al massimo.
+ public const float NearZoom = 0.5f;
+ /// Canali dei treni: al più tanti treni suonano insieme.
+ public const int TrainChannels = 3;
+ /// Velocità (m/s) a cui il rotolamento è al massimo.
+ public const float FullSpeedMs = 25f;
+ /// Sbuffi al secondo da fermo (al passo) e alla velocità .
+ public const float ChuffMinRate = 1.2f, ChuffMaxRate = 10f;
+ /// Velocità (m/s, circa 110 km/h) a cui gli sbuffi sono più fitti.
+ 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);
+ }
+
+ /// Vicinanza della telecamera (0 = vista d'insieme, 1 = da vicino) su scala logaritmica dello zoom.
+ 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)));
+ }
+
+ ///
+ /// 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.
+ ///
+ 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);
+ }
+
+ /// Volume di un treno: vicinanza al centro dello schermo, velocità e zoom.
+ /// Distanza in pixel dal centro dello schermo.
+ /// Raggio oltre il quale non si sente (di solito metà della diagonale).
+ 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));
+ }
+
+ /// Intonazione del rotolamento: più rapido e acuto con la velocità.
+ public static float RumblePitch(float speedMs) => 0.55f + 1.0f * Clamp01(speedMs / FullSpeedMs);
+
+ /// Intonazione del motore (diesel o elettrico) con la velocità.
+ public static float EnginePitch(float speedMs) => 0.8f + 0.5f * Clamp01(speedMs / FullSpeedMs);
+
+ ///
+ /// Secondi tra due sbuffi della vaporiera alla velocità data: la frequenza cresce in modo lineare
+ /// da a fino a ,
+ /// 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.
+ ///
+ public static float ChuffInterval(float speedMs) => 1f / (ChuffMinRate + (ChuffMaxRate - ChuffMinRate) * Clamp01(speedMs / ChuffFullSpeedMs));
+
+ ///
+ /// 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.
+ ///
+ 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);
+ }
+
+ /// Era dell'anno: l'ultima il cui inizio («from» di eras.json, crescente) non è dopo l'anno.
+ public static int EraIndex(int year, IReadOnlyList froms)
+ {
+ int index = 0;
+ for (int i = 0; i < froms.Count; i++)
+ {
+ if (froms[i] <= year) index = i;
+ }
+ return index;
+ }
+
+ /// Avvicina un valore al bersaglio con velocità costante (unità al secondo).
+ 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);
+ }
+
+ /// Lineare → decibel, con −80 dB come silenzio.
+ public static float LinearToDb(float linear) => linear <= 0.0001f ? -80f : 20f * MathF.Log10(linear);
+
+ /// Campioni in [−1, 1] → PCM a 16 bit little-endian (formato di AudioStreamWAV).
+ 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;
+ }
+}
diff --git a/client/RailEnterprise.Client/scripts/Audio/AudioSettings.cs b/client/RailEnterprise.Client/scripts/Audio/AudioSettings.cs
new file mode 100644
index 0000000..3fadbc5
--- /dev/null
+++ b/client/RailEnterprise.Client/scripts/Audio/AudioSettings.cs
@@ -0,0 +1,91 @@
+using Godot;
+
+namespace RailEnterprise.Client.Audio;
+
+/// Bus audio del client: Master e quattro bus che vi confluiscono.
+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";
+
+ /// Nell'ordine dei cursori delle impostazioni.
+ public static readonly string[] All = [Master, Music, Ambience, Sfx, Ui];
+
+ ///
+ /// 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.
+ ///
+ 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 });
+ }
+}
+
+///
+/// Volumi per bus (0–1) e muto generale, salvati nella sezione «audio» di
+/// user://settings.cfg (lo stesso file della lingua e del server).
+///
+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];
+
+ /// Volumi nell'ordine di .
+ 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();
+
+ /// Applica volumi e muto ai bus (il cursore segue il volume percepito: guadagno = valore²).
+ 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);
+ }
+}
diff --git a/client/RailEnterprise.Client/scripts/Audio/AudioSettingsPanel.cs b/client/RailEnterprise.Client/scripts/Audio/AudioSettingsPanel.cs
new file mode 100644
index 0000000..4e9abe3
--- /dev/null
+++ b/client/RailEnterprise.Client/scripts/Audio/AudioSettingsPanel.cs
@@ -0,0 +1,110 @@
+using Godot;
+using RailEnterprise.Client.App;
+using static RailEnterprise.Client.App.Localization;
+
+namespace RailEnterprise.Client.Audio;
+
+///
+/// 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 user://settings.cfg . Esc o un clic
+/// sinistro fuori chiudono.
+///
+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();
+ }
+}
diff --git a/client/RailEnterprise.Client/scripts/Audio/MusicComposer.cs b/client/RailEnterprise.Client/scripts/Audio/MusicComposer.cs
new file mode 100644
index 0000000..985a4c7
--- /dev/null
+++ b/client/RailEnterprise.Client/scripts/Audio/MusicComposer.cs
@@ -0,0 +1,327 @@
+namespace RailEnterprise.Client.Audio;
+
+///
+/// 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 Hz.
+///
+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 }
+
+ /// Stile di un'era.
+ 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];
+
+ /// Progressioni per grado della scala (0 = primo grado), una battuta per accordo.
+ 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],
+ ];
+
+ /// Stile dell'era per posizione nell'elenco di eras.json (le ere oltre la quarta riprendono il ciclo).
+ 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),
+ };
+
+ /// Seme fisso del tema: hash dell'id dell'era e della sua posizione.
+ public static ulong Seed(int eraIndex, string eraId) => SynthRng.Hash(eraId) ^ ((ulong)(eraIndex + 1) * 0x9E3779B97F4A7C15UL);
+
+ /// Durata dell'anello in secondi.
+ public static float LengthSeconds(Style style) => Bars * style.BeatsPerBar * 60f / style.Bpm;
+
+ // ------------------------------------------------------------------ timbri
+
+ private sealed class Voice
+ {
+ /// Ampiezza della n-esima armonica in Harmonics[n−1].
+ public required float[] Harmonics { get; init; }
+ public float Attack { get; init; } = 0.005f;
+ /// Decadimento verso il sostegno (s).
+ public float Decay { get; init; } = 0.3f;
+ public float Sustain { get; init; }
+ public float Release { get; init; } = 0.1f;
+ /// Copie leggermente scordate (coro).
+ 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 _tables = [];
+
+ ///
+ /// Forma d'onda per una nota alla frequenza data, con le sole armoniche sotto
+ /// della frequenza di campionamento: quelle oltre Nyquist
+ /// tornerebbero indietro come toni stonati.
+ ///
+ 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;
+ }
+ }
+
+ /// Frazione della frequenza di campionamento sotto cui stanno le armoniche (margine per vibrato e coro).
+ private const float MaxHarmonicShare = 0.45f;
+
+ private const int TableSize = 2048;
+
+ /// Forma d'onda di un periodo dalla somma delle prime «count» armoniche (ampiezza della n-esima in harmonics[n−1]).
+ 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);
+
+ /// Suona una nota nell'anello (con la coda che rientra dall'inizio).
+ 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;
+ }
+ }
+ }
+
+ /// Altezza MIDI del grado della scala (i gradi oltre la scala salgono d'ottava).
+ 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;
+ }
+
+ /// Compone e sintetizza il tema dell'era: campioni mono in [−1, 1].
+ 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;
+ }
+
+ /// Eco con retroazione su un anello (due giri per la continuità all'inizio).
+ 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];
+ }
+}
diff --git a/client/RailEnterprise.Client/scripts/Audio/SpeakerButton.cs b/client/RailEnterprise.Client/scripts/Audio/SpeakerButton.cs
new file mode 100644
index 0000000..bd4422d
--- /dev/null
+++ b/client/RailEnterprise.Client/scripts/Audio/SpeakerButton.cs
@@ -0,0 +1,49 @@
+using Godot;
+using RailEnterprise.Client.App;
+using static RailEnterprise.Client.App.Localization;
+
+namespace RailEnterprise.Client.Audio;
+
+/// Altoparlante nella barra superiore: apre il pannello «Audio»; barrato quando il muto è attivo.
+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);
+ }
+ }
+}
diff --git a/client/RailEnterprise.Client/scripts/Audio/Synth.cs b/client/RailEnterprise.Client/scripts/Audio/Synth.cs
new file mode 100644
index 0000000..4133028
--- /dev/null
+++ b/client/RailEnterprise.Client/scripts/Audio/Synth.cs
@@ -0,0 +1,554 @@
+namespace RailEnterprise.Client.Audio;
+
+///
+/// Generatore pseudo-casuale xorshift64* per la sintesi dei suoni. Non è il Rng della
+/// simulazione: serve solo a rendere ripetibili rumori, variazioni e temi musicali del client.
+///
+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;
+ }
+
+ /// Numero in [0, 1).
+ public float Next01() => (NextU64() >> 40) * (1f / (1 << 24));
+
+ /// Numero in [−1, 1).
+ public float NextSigned() => Next01() * 2f - 1f;
+
+ /// Intero in [0, n).
+ public int Next(int n) => (int)((NextU64() >> 33) % (ulong)n);
+
+ /// Numero in [a, b).
+ public float Range(float a, float b) => a + (b - a) * Next01();
+
+ /// FNV-1a a 64 bit di una stringa: semi fissi derivati da un identificatore (per esempio l'id dell'era).
+ public static ulong Hash(string text)
+ {
+ ulong h = 14695981039346656037UL;
+ foreach (char c in text)
+ {
+ h ^= c;
+ h *= 1099511628211UL;
+ }
+ return h;
+ }
+}
+
+/// Filtro biquadratico (formule RBJ): passa-basso, passa-alto, passa-banda a guadagno di picco unitario.
+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);
+ }
+
+ /// Cambia i coefficienti mantenendo lo stato (filtri a frequenza variabile).
+ 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;
+ }
+}
+
+///
+/// Sintesi procedurale di tutti gli effetti del gioco, senza dipendenze da Godot: ogni funzione
+/// restituisce campioni mono in virgola mobile a Hz, da convertire in PCM a
+/// 16 bit con . 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.
+///
+public static class Synth
+{
+ /// Frequenza di campionamento di tutti i suoni (Hz).
+ 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))];
+
+ /// Inviluppo attacco lineare e decadimento esponenziale.
+ public static float Env(float t, float attack, float decay) =>
+ t < 0 ? 0 : t < attack ? t / attack : MathF.Exp(-(t - attack) / decay);
+
+ /// Porta il picco al valore indicato.
+ 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;
+ }
+
+ /// Sfuma gli ultimi millisecondi di un suono singolo (niente scatto alla fine).
+ 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;
+ }
+
+ /// Rumore bianco ripetibile.
+ 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;
+ }
+
+ /// Filtra un anello due volte: la seconda passata riparte dallo stato della fine della prima.
+ 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;
+ }
+
+ /// Rumore marrone in anello: integrazione con perdita del rumore bianco, due passate.
+ 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;
+ }
+
+ /// Somma un suono breve nell'anello a partire da «at» campioni, con la coda che rientra dall'inizio.
+ 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
+
+ /// Clic dell'interfaccia: un colpetto secco e brillante.
+ 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;
+ }
+
+ /// Nota con armoniche (ampiezze in «harmonics», la prima è la fondamentale) e decadimento esponenziale.
+ 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;
+ }
+ }
+
+ /// Esito positivo di un comando: due note ascendenti (la, mi).
+ 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;
+ }
+
+ /// Comando rifiutato: due note scure discendenti.
+ 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;
+ }
+
+ /// Campana in modulazione di frequenza (portante f, modulante 1,4·f, indice che decade).
+ 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;
+ }
+ }
+
+ /// Notifica: 0 = informazione o opportunità, 1 = avviso, 2 = critica.
+ 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;
+ }
+
+ /// Cantiere completato: due colpi metallici e un arpeggio maggiore.
+ 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
+
+ /// Fischio a vapore all'arrivo: accordo 4:5:6 con salita d'intonazione, vibrato e soffio.
+ 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;
+ }
+
+ /// Tromba bitonale delle locomotive diesel ed elettriche.
+ 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;
+ }
+
+ /// Sbuffo del vapore: rumore filtrato a banda con un tonfo grave.
+ 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;
+ }
+
+ /// Rotolamento in anello (1,6 s a intonazione 1): rumore grave e il «tu-tum» dei carrelli sui giunti.
+ 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;
+ }
+
+ /// Motore diesel in anello (1 s): 48 Hz con armoniche e scoppi a 8 Hz.
+ 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;
+ }
+
+ /// Ronzio elettrico in anello (1 s): 100, 200 e 300 Hz e un fischio dei motori.
+ 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
+
+ /// Vento e campagna in anello (8 s): rumore con passa-basso mobile e raffiche.
+ 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;
+ }
+
+ /// Acqua di fiume in anello (6 s): rumore a banda con un gorgoglio lento e bolle.
+ 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;
+ }
+
+ /// Mare in anello (10 s): due onde con risacca e schiuma.
+ 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;
+ }
+
+ /// Città in anello (8 s): brusio grave, voci lontane e qualche colpo di carri e porte.
+ 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;
+ }
+
+ /// Cinguettio (varianti per numero): due–quattro brevi glissati acuti.
+ 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;
+ }
+}
diff --git a/client/RailEnterprise.Client/scripts/Hud/TopBar.cs b/client/RailEnterprise.Client/scripts/Hud/TopBar.cs
index 3ebf49e..d27c444 100644
--- a/client/RailEnterprise.Client/scripts/Hud/TopBar.cs
+++ b/client/RailEnterprise.Client/scripts/Hud/TopBar.cs
@@ -7,7 +7,7 @@ using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Hud;
-/// Barra superiore (immagine 01): compagnia e livello, data, velocità, cassa, patrimonio, rating, stato del server.
+/// Barra superiore (immagine 01): compagnia e livello, data, velocità, cassa, patrimonio, rating, stato del server, audio.
public partial class TopBar : PanelContainer
{
private GameSession? _session;
@@ -90,6 +90,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)
diff --git a/client/RailEnterprise.Client/scripts/Main.cs b/client/RailEnterprise.Client/scripts/Main.cs
index 1528914..d4f2a4d 100644
--- a/client/RailEnterprise.Client/scripts/Main.cs
+++ b/client/RailEnterprise.Client/scripts/Main.cs
@@ -1,5 +1,6 @@
using Godot;
using RailEnterprise.Client.App;
+using RailEnterprise.Client.Audio;
using RailEnterprise.Client.Net;
using RailEnterprise.Client.Screens;
using RailEnterprise.Client.Tutorial;
@@ -9,17 +10,22 @@ using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client;
///
-/// 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.
///
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 del menu e opzione «Tutorial» (dal primo passo)
+ // tutorial della partita che si apre: casella «Mostra il tutorial» e pulsante «Tutorial» (dal primo passo)
private bool _tutorialRequested, _tutorialRestart;
public override void _Ready()
@@ -30,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");
@@ -59,35 +71,48 @@ public partial class Main : Node
AddChild(screen);
}
- private void ShowMenu(string status = "")
+ /// Schermata iniziale e di connessione (immagine 09): server locale o in rete, stato, salvataggi.
+ /// Avvia subito la strada scelta l'ultima volta (server locale o in rete).
+ /// Sessione di prova della schermata precedente, ripresa così com'è (cambio di lingua).
+ private void ShowMenu(string status = "", bool autoStart = true, GameSession? handover = null)
{
- var menu = new MenuScreen();
- menu.LocalGame += () =>
+ if (_data is null)
{
- SetTutorial(menu.ShowTutorial, restart: false);
- StartLocal();
+ // 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);
};
- menu.ConnectToServer += () =>
- {
- SetTutorial(menu.ShowTutorial, restart: false);
- ShowConnect();
- };
- menu.TutorialRequested += () =>
+ 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();
+ StartLocal(tutorial: true);
};
- menu.LanguageChanged += code =>
+ 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();
+ // la schermata si ricrea con i testi nuovi: la sessione di prova (e il server locale) passa a lei
+ ShowMenu(handover: screen.TakeSession());
};
- Swap(menu);
- if (status.Length > 0) menu.SetStatus(status);
+ Swap(screen);
+ if (status.Length > 0) screen.SetStatus(status, error: true);
}
private void SetTutorial(bool requested, bool restart)
@@ -96,73 +121,72 @@ public partial class Main : Node
_tutorialRestart = restart;
}
- private void ShowConnect()
+ /// Vero se la partita locale del giocatore ha già dei salvataggi (file .vfsave del server).
+ private static bool HasLocalSaves()
{
- var screen = new ConnectScreen();
- screen.Back += () => ShowMenu();
- screen.ConnectRequested += async (uri, token, label) =>
+ try
{
- 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);
- }
- };
- Swap(screen);
+ string saves = System.IO.Path.Combine(ProjectSettings.GlobalizePath(LocalDataDir), "saves");
+ return Directory.Exists(saves) && Directory.EnumerateFiles(saves, "*.vfsave").Any();
+ }
+ catch (IOException)
+ {
+ return false;
+ }
}
- private async void StartLocal()
+ ///
+ /// 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.
+ ///
+ /// pulsante «Tutorial»: partita di prova nuova, con il tutorial dal primo passo
+ 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)
+ /// origine della partita (locale, tutorial, server in rete) per la voce del tutorial
+ 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 restano quelle di sempre
+ // 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, _tutorialRequested, _tutorialRestart));
+ game.AddChild(new TutorialController(game, scope, _tutorialRequested, _tutorialRestart));
TutorialSettings.Played = true;
_tutorialRestart = false;
}
@@ -170,10 +194,10 @@ public partial class Main : Node
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));
}
}
diff --git a/client/RailEnterprise.Client/scripts/Net/GameSession.cs b/client/RailEnterprise.Client/scripts/Net/GameSession.cs
index f1c01be..ac928d9 100644
--- a/client/RailEnterprise.Client/scripts/Net/GameSession.cs
+++ b/client/RailEnterprise.Client/scripts/Net/GameSession.cs
@@ -134,9 +134,13 @@ public sealed class GameSession : IAsyncDisposable
/// Ultima velocità chiesta da questo client (mostrata finché il resoconto non la conferma).
public byte? RequestedSpeed { get; private set; }
+ /// Velocità chieste finora da questo client (il tutorial non conta i cambi fatti da altri giocatori).
+ public int SpeedRequests { get; private set; }
+
public void SetSpeed(byte speed)
{
RequestedSpeed = speed;
+ SpeedRequests++;
Send(new SetSpeed { Speed = speed });
}
diff --git a/client/RailEnterprise.Client/scripts/Panels/IndustryPanel.cs b/client/RailEnterprise.Client/scripts/Panels/IndustryPanel.cs
index e0b4914..fdbf420 100644
--- a/client/RailEnterprise.Client/scripts/Panels/IndustryPanel.cs
+++ b/client/RailEnterprise.Client/scripts/Panels/IndustryPanel.cs
@@ -11,21 +11,39 @@ using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Panels;
///
-/// 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'è.
///
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 _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);
+ /// Esito dell'offerta di acquisto, accanto al pulsante (la scheda è a tutto schermo e la mappa è nascosta).
+ private readonly Label _buyStatus = UiTheme.Text("", 13, Palette.TextSecondary);
+ private Button? _overhaul, _upgrade;
private readonly List _budgetButtons = [];
private SpinBox? _partsOrder;
private int _industry = -1;
@@ -33,25 +51,108 @@ public partial class IndustryPanel : VBoxContainer
private int _entityVersion = -1, _detailVersion = -1;
private double _request, _sinceRefresh;
+ /// «Torna alla mappa».
+ public event Action? CloseRequested;
+
+ /// «Crea una linea verso questa industria»: strumento binari centrato sull'industria.
+ public event Action? 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);
+ _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();
}
+ /// Scheda con titolo e contenuto, larga in proporzione al rapporto dato.
+ 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;
+ }
+
/// Industria mostrata (−1 se nessuna).
public int Industry => _industry;
@@ -60,11 +161,20 @@ public partial class IndustryPanel : VBoxContainer
if (id == _industry) return;
_industry = id;
_status.Text = "";
+ _buyStatus.Text = "";
+ _scroll.ScrollVertical = 0;
SyncSelection();
Request();
Refresh();
}
+ /// Scorre il corpo della scheda (0 in cima, 1 in fondo).
+ 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 +194,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 +210,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 +228,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
- /// Elenco: si ricostruisce solo se cambiano le industrie o il loro ordine, altrimenti si aggiornano i testi.
+ /// Selettore: si ricostruisce solo se cambiano le industrie o il loro ordine, altrimenti si aggiornano i testi.
private void RefreshList()
{
var w = _session.World;
@@ -126,7 +257,7 @@ public partial class IndustryPanel : VBoxContainer
if (!same)
{
_ids.Clear();
- _list.Clear();
+ _chooser.Clear();
}
for (int n = 0; n < ordered.Count; n++)
{
@@ -137,13 +268,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 +281,374 @@ 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));
}
- /// Comandi del proprietario o dell'acquirente: si ricostruiscono solo se cambia l'industria o il proprietario.
+ // ------------------------------------------------------------------ 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, 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, 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")}")));
+ _production.AddChild(PanelKit.Pair(T("Prezzo di vendita"), PanelKit.Value(s.SalePrice < 0 ? "—" : Fmt.PricePrecise(s.SalePrice))));
+ _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();
+ 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();
+ 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());
+ _plants.AddChild(FlowHeader(T("Punteggio di crescita"), $"{Fmt.Number(s.Score, 2)} · {T("giorno")} {s.QuarterDay} {T("di")} {s.QuarterDays}"));
+ var bar = new ScoreBar();
+ bar.Set(s.Score, s.LastScore, s.DowngradeThreshold, s.UpgradeThreshold);
+ _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));
+ }
+
+ /// Comandi del proprietario: si ricostruiscono solo se cambia l'industria o il proprietario.
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";
+
+ /// Abilita il pulsante, o lo disabilita con il motivo in testa al suggerimento.
+ 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, 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}";
+ return Wrapped(text, 12, p.Line >= 0 ? Palette.AmberLight : Palette.TextSecondary);
+ }
+
+ 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 +664,21 @@ public partial class IndustryPanel : VBoxContainer
// ------------------------------------------------------------------ testi
+ /// Fattore che limita l'efficienza (IndustryLimit) nella lingua dell'interfaccia.
+ 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"),
diff --git a/client/RailEnterprise.Client/scripts/Panels/IndustryWidgets.cs b/client/RailEnterprise.Client/scripts/Panels/IndustryWidgets.cs
new file mode 100644
index 0000000..4646952
--- /dev/null
+++ b/client/RailEnterprise.Client/scripts/Panels/IndustryWidgets.cs
@@ -0,0 +1,198 @@
+using Godot;
+using RailEnterprise.Client.App;
+
+namespace RailEnterprise.Client.Panels;
+
+/// Anello dell'efficienza (immagine 07, in alto a destra): arco ambra sulla percentuale.
+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);
+ }
+}
+
+///
+/// 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.
+///
+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);
+ }
+}
+
+/// Come si disegna un collegamento della catena produttiva (legenda dell'immagine 07).
+public enum ChainEdge
+{
+ /// Merci su una linea della compagnia: linea piena ambra.
+ Goods,
+ /// Lavoratori pendolari: tratteggio blu.
+ Workers,
+ /// Personale qualificato: puntinato azzurro.
+ Staff,
+ /// Partner possibile ma non collegato: tratteggio grigio.
+ Unlinked,
+}
+
+/// Nodo del grafo: titolo, riga secondaria, stile del collegamento, industria da aprire (−1 se nessuna).
+public sealed record ChainNode(string Title, string Subtitle, ChainEdge Edge, int Industry = -1);
+
+///
+/// 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.
+///
+public partial class ChainGraph : Control
+{
+ private const float NodeW = 210, NodeH = 50, Gap = 10;
+ private readonly List<(Rect2 Rect, ChainNode Node)> _hits = [];
+ private List _left = [], _right = [];
+ private ChainNode? _center;
+
+ public event Action? IndustryClicked;
+
+ public ChainGraph()
+ {
+ CustomMinimumSize = new Vector2(0, 260);
+ MouseFilter = MouseFilterEnum.Stop;
+ }
+
+ public void Set(List left, ChainNode center, List 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 Column(List 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(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;
+ }
+ }
+}
diff --git a/client/RailEnterprise.Client/scripts/Panels/MaintenancePanel.cs b/client/RailEnterprise.Client/scripts/Panels/MaintenancePanel.cs
index 6447a6b..acd2985 100644
--- a/client/RailEnterprise.Client/scripts/Panels/MaintenancePanel.cs
+++ b/client/RailEnterprise.Client/scripts/Panels/MaintenancePanel.cs
@@ -3,6 +3,7 @@ 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;
@@ -11,7 +12,8 @@ namespace RailEnterprise.Client.Panels;
///
/// 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.
///
public partial class MaintenancePanel : VBoxContainer
{
@@ -29,12 +31,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 _trainIds = [];
private readonly List _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? HeatMapToggled;
@@ -69,6 +78,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 +125,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 +188,7 @@ public partial class MaintenancePanel : VBoxContainer
BuildCard();
BuildWorkshop();
+ if (!_fleetBuilt || !ReferenceEquals(w.Fleet, _fleetShown)) BuildFleet();
}
private string DueText(TrainInfo t)
@@ -212,6 +241,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 +296,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
+
+ /// Riga di obsolescenza di un veicolo: superato, successore con prestazioni e prezzo, valori, costo di manutenzione.
+ private string VehicleOutlook(FleetVehicleInfo v)
+ {
+ var parts = new List();
+ 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);
+ }
+ }
+
+ /// Nome italiano dell'era dal suo id in eras.json (il quadro della flotta manda l'id).
+ private string EraName(string id) => _session.World.Data.Eras.Eras.FirstOrDefault(e => e.Id == id)?.NameIt ?? id;
+
// ------------------------------------------------------------------ registro officina
private void BuildWorkshop()
diff --git a/client/RailEnterprise.Client/scripts/Panels/TrainsPanel.cs b/client/RailEnterprise.Client/scripts/Panels/TrainsPanel.cs
index 9bb501f..562f8cf 100644
--- a/client/RailEnterprise.Client/scripts/Panels/TrainsPanel.cs
+++ b/client/RailEnterprise.Client/scripts/Panels/TrainsPanel.cs
@@ -11,8 +11,11 @@ using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Panels;
///
-/// 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.
///
public partial class TrainsPanel : VBoxContainer
{
@@ -20,10 +23,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 _depotIds = [];
private readonly List _catalog = [];
@@ -31,6 +36,9 @@ public partial class TrainsPanel : VBoxContainer
private readonly List _trainIds = [];
private readonly List _lineIds = [];
private int _version = -1;
+ private FleetReport? _fleetShown;
+ private long _requestedDay = long.MinValue;
+ private double _sinceRequest = double.MaxValue;
public event Action? TrainSelected;
@@ -51,6 +59,8 @@ 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);
@@ -64,6 +74,9 @@ public partial class TrainsPanel : VBoxContainer
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));
@@ -79,15 +92,38 @@ public partial class TrainsPanel : VBoxContainer
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;
@@ -95,7 +131,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();
@@ -109,16 +147,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();
@@ -126,18 +181,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);
@@ -154,6 +216,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);
+
+ /// Modello scelto nel catalogo: superato o no, successore con prestazioni e prezzo, ultimo anno di produzione.
+ 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();
+ 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);
+ }
+
+ /// Rinnovo del treno scelto: veicoli superati e spesa netta calcolati dal server.
+ 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
@@ -168,7 +264,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()
{
@@ -185,7 +286,14 @@ 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);
+ }
+
+ private int SelectedTrain => _trains.GetSelectedItems() is { Length: > 0 } sel && sel[0] < _trainIds.Count ? _trainIds[sel[0]] : -1;
private void Assign()
{
@@ -200,4 +308,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);
+ }
}
diff --git a/client/RailEnterprise.Client/scripts/Screens/ConnectScreen.cs b/client/RailEnterprise.Client/scripts/Screens/ConnectScreen.cs
index 167682f..e7e2712 100644
--- a/client/RailEnterprise.Client/scripts/Screens/ConnectScreen.cs
+++ b/client/RailEnterprise.Client/scripts/Screens/ConnectScreen.cs
@@ -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;
///
-/// 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).
///
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;
+ /// Metadato della riga «Partita in corso» nell'elenco dei salvataggi.
+ 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);
+ /// Stato del server in tre colonne per due righe, didascalia sopra il valore (immagine 09).
+ private readonly GridContainer _stateGrid = new() { Columns = 3 };
+ private readonly List<(Label Caption, Label Value)> _stateCells = [];
+ /// Partite salvate in tre colonne: nome, data di gioco, quanto tempo fa.
+ 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;
+ /// Riga scelta nell'elenco, per id del salvataggio (CurrentGame per la partita in corso): l'elenco si riordina a ogni aggiornamento.
+ private string _selectedSave = CurrentGame;
+ private Action? _awaitingWelcome;
+ private double _waiting;
+ /// Stato del server mostrato e istante in cui è arrivato: il tempo di attività avanza da lì.
+ private ServerInfo? _infoSeen;
+ private double _infoAt;
- public event Action? ConnectRequested;
- public event Action? Back;
+ /// La sessione di prova diventa la partita: la schermata non la chiude più.
+ public event Action? PlayRequested;
+ public event Action? LanguageChanged;
+ /// Apre il pannello delle impostazioni audio.
+ public event Action? AudioRequested;
+ /// Pulsante «Tutorial»: Main apre la partita di prova del tutorial.
+ public event Action? TutorialRequested;
+
+ /// Casella «Mostra il tutorial» per la partita che si apre.
+ public bool ShowTutorial => _showTutorial.ButtonPressed;
+
+ /// Origine della partita per la voce del tutorial: il server locale o l'indirizzo del server in rete.
+ public string GameScope => _local ? "local" : "remote_" + _address.Text.Trim();
+
+ /// Falso per l'anteprima del collaudo: non legge né scrive le impostazioni.
+ /// Avvia subito il server locale o verifica il server ricordato (falso nel collaudo).
+ /// Sessione di prova di una schermata precedente (cambio di lingua): la si riprende così com'è.
+ public ConnectScreen(GameData data, bool remember = true, bool autoStart = true, GameSession? handover = null)
+ {
+ _data = data;
+ _remember = remember;
+ _autoStart = autoStart;
+ _handover = handover;
+ }
+
+ /// Stato e salvataggi sono arrivati dal server (serve al collaudo).
+ 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
+
+ /// La sessione di prova è della strada scelta: server locale figlio del gioco o server in rete.
+ private bool SessionMatchesMode => _session is not null && (_session.LocalServer is not null) == _local;
+
+ ///
+ /// 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.
+ ///
+ 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();
+ }
+
+ /// Avvia il server locale figlio del gioco e apre la sessione di prova.
+ 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);
+ }
+
+ /// Collega la sessione di prova a un server in rete (dal pulsante o dal collaudo).
+ 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();
+ }
+
+ ///
+ /// 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.
+ ///
+ 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;
+ }
+
+ /// Chiude la sessione di prova (e il server locale, se è suo).
+ private async Task Release()
+ {
+ var s = _session;
+ _session = null;
+ _shownSaves = null;
+ _awaitingWelcome = null;
+ if (s is null) return;
+ s.MessageApplied -= OnMessage;
+ await s.DisposeAsync();
+ }
+
+ /// Consegna la sessione di prova a chi la chiede (Main: partita, cambio di lingua, chiusura del gioco).
+ 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();
+ }
+
+ /// Dopo Load o NewGame il server rimanda il Welcome a tutti: allora si entra in partita.
+ 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;
+ }
+
+ /// Elenco ricostruito a ogni aggiornamento: la riga scelta si ritrova per id, non per posizione.
+ 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")}";
+ }
+}
+
+///
+/// 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.
+///
+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();
}
}
diff --git a/client/RailEnterprise.Client/scripts/Screens/GameScreen.cs b/client/RailEnterprise.Client/scripts/Screens/GameScreen.cs
index bebf4d6..662d65d 100644
--- a/client/RailEnterprise.Client/scripts/Screens/GameScreen.cs
+++ b/client/RailEnterprise.Client/scripts/Screens/GameScreen.cs
@@ -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;
@@ -105,7 +106,7 @@ public partial class GameScreen : Node
_maintenance?.SelectDepot(depot);
}
- /// Apre il pannello Industrie sull'industria indicata (scheda del proprietario).
+ /// Apre la scheda dell'industria a tutto schermo (immagine 07) sull'industria indicata.
public void OpenIndustry(int industry)
{
if (_tool != Tool.Industries) _toolbar.Select(Tool.Industries);
@@ -132,6 +133,9 @@ public partial class GameScreen : Node
if (_tool != Tool.Climb) _toolbar.Select(Tool.Climb);
}
+ /// Chiude lo strumento o la schermata a tutto schermo aperta e torna alla mappa.
+ public void CloseTools() => _toolbar.Select(Tool.None);
+
/// Apre le «Finanze» a tutto schermo: conto economico, rating e prestiti.
public void OpenFinance()
{
@@ -149,6 +153,17 @@ public partial class GameScreen : Node
}
}
+ /// Dalla scheda dell'industria: strumento binari con la mappa centrata sull'industria da collegare.
+ 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);
+ }
+ }
+
/// Chiede al server la Cronaca (provvisoria a partita in corso) e la mostra all'arrivo.
public void OpenChronicle()
{
@@ -168,6 +183,11 @@ public partial class GameScreen : Node
/// Scorre il pannello laterale (0 = in cima, 1 = in fondo).
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));
}
@@ -201,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);
@@ -232,6 +247,9 @@ 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);
@@ -247,13 +265,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);
+ }
/// Codice di EventKind.World nel protocollo (notizie degli eventi del mondo, ADR 0017).
private const byte WorldEventKind = 10;
@@ -341,6 +364,7 @@ public partial class GameScreen : Node
public override void _Process(double delta)
{
+ PlaceToasts();
_session.Poll();
_disconnected.Visible = !_session.IsOpen;
UpdateChronicle();
@@ -419,7 +443,7 @@ public partial class GameScreen : Node
_finance = null;
_trainsPanel = null;
foreach (var c in _full.GetChildren()) c.QueueFree();
- bool full = tool is Tool.Companies or Tool.Market or Tool.Climb or Tool.Finance;
+ 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;
@@ -473,7 +497,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);
@@ -831,7 +859,8 @@ public partial class GameScreen : Node
_chronicleScreen = screen;
}
- private void CloseChronicle()
+ /// Chiude la Cronaca se è aperta.
+ public void CloseChronicle()
{
_chronicleScreen?.QueueFree();
_chronicleScreen = null;
@@ -856,8 +885,19 @@ public partial class GameScreen : Node
Toast($"{T("Nuova partita+ in preparazione")}: {(TranslationServer.GetLocale().StartsWith("en") ? next.NameEn : next.NameIt)}");
}
- /// Messaggio temporaneo in alto sulla mappa.
- private void Toast(string text, bool error = false)
+ /// Allinea gli avvisi in cima all'area visibile: la mappa o la schermata a tutto schermo.
+ 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);
+ }
+
+ /// Messaggio temporaneo in alto sull'area visibile (mappa o schermata a tutto schermo); lo usa anche il tutorial.
+ 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));
@@ -867,5 +907,6 @@ public partial class GameScreen : Node
if (IsInstanceValid(notice)) notice.QueueFree();
};
while (_toasts.GetChildCount() > 4) _toasts.GetChild(0).QueueFree();
+ PlaceToasts();
}
}
diff --git a/client/RailEnterprise.Client/scripts/Screens/MenuScreen.cs b/client/RailEnterprise.Client/scripts/Screens/MenuScreen.cs
deleted file mode 100644
index 18cbbf1..0000000
--- a/client/RailEnterprise.Client/scripts/Screens/MenuScreen.cs
+++ /dev/null
@@ -1,73 +0,0 @@
-using Godot;
-using RailEnterprise.Client.App;
-using RailEnterprise.Client.Tutorial;
-using static RailEnterprise.Client.App.Localization;
-
-namespace RailEnterprise.Client.Screens;
-
-///
-/// Menu iniziale: partita locale (server figlio), collegamento a un server, tutorial, lingua, uscita. La
-/// casella «Mostra il tutorial» è attiva alla prima partita; «Tutorial» apre la partita locale con il
-/// tutorial dal primo passo.
-///
-public partial class MenuScreen : Control
-{
- public event Action? LocalGame;
- public event Action? ConnectToServer;
- public event Action? LanguageChanged;
- public event Action? TutorialRequested;
- private readonly CheckBox _showTutorial = new() { Text = T("Mostra il tutorial") };
-
- /// Casella «Mostra il tutorial» per la partita che si apre.
- public bool ShowTutorial => _showTutorial.ButtonPressed;
- 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);
- _showTutorial.ButtonPressed = !TutorialSettings.Played;
- _showTutorial.TooltipText = T("Guida passo per passo alla prima linea: si chiude quando vuoi e si riapre con F1");
- col.AddChild(_showTutorial);
- var remote = new Button { Text = T("Collegati a un server"), CustomMinimumSize = new Vector2(0, 48) };
- remote.Pressed += () => ConnectToServer?.Invoke();
- col.AddChild(remote);
- var tutorial = new Button { Text = T("Tutorial"), CustomMinimumSize = new Vector2(0, 40) };
- tutorial.TooltipText = T("Partita locale con il tutorial dal primo passo");
- tutorial.Pressed += () => TutorialRequested?.Invoke();
- col.AddChild(tutorial);
- 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;
-}
diff --git a/client/RailEnterprise.Client/scripts/Screens/MenuScreen.cs.uid b/client/RailEnterprise.Client/scripts/Screens/MenuScreen.cs.uid
deleted file mode 100644
index b2971a2..0000000
--- a/client/RailEnterprise.Client/scripts/Screens/MenuScreen.cs.uid
+++ /dev/null
@@ -1 +0,0 @@
-uid://b5eyw35w2vo7l
diff --git a/client/RailEnterprise.Client/scripts/Tutorial/Logic/TutorialMachine.cs b/client/RailEnterprise.Client/scripts/Tutorial/Logic/TutorialMachine.cs
index 810c6d9..aed1539 100644
--- a/client/RailEnterprise.Client/scripts/Tutorial/Logic/TutorialMachine.cs
+++ b/client/RailEnterprise.Client/scripts/Tutorial/Logic/TutorialMachine.cs
@@ -1,3 +1,5 @@
+using RailEnterprise.Protocol.Messages;
+
namespace RailEnterprise.Client.Tutorial;
/// Stato del tutorial di una partita.
@@ -36,10 +38,23 @@ public readonly record struct TutorialProgress(string? StepId, TutorialStatus St
};
///
- /// Chiave della partita nelle impostazioni: seme, impronta del terreno e compagnia del giocatore, che il
- /// client riceve nel Welcome. Resta la stessa dopo un salvataggio e un caricamento della stessa partita.
+ /// Chiave della partita nelle impostazioni: origine ( : 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.
///
- public static string GameKey(ulong seed, ulong terrainHash, int companyId) => $"g_{seed:x16}_{terrainHash:x16}_{companyId}";
+ 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}");
+
+ /// Chiave della partita dal riepilogo del Welcome (vedi l'altra forma).
+ 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]) : '_';
+ });
/// Legge una voce salvata; null se vuota o non riconosciuta.
public static TutorialProgress? Decode(string? text)
@@ -60,8 +75,10 @@ public readonly record struct TutorialProgress(string? StepId, TutorialStatus St
///
/// Macchina a stati dei passi: un passo alla volta, completato quando la sua condizione è vera sui fatti
/// osservati ( ), oppure con Avanti (passi informativi), Salta passo o Chiudi. I contatori
-/// con increase si confrontano con i fatti al primo aggiornamento del passo. Non decide regole di
-/// gioco: guarda soltanto ciò che il client ha già ricevuto.
+/// con increase 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.
///
public sealed class TutorialMachine
{
@@ -88,15 +105,17 @@ public sealed class TutorialMachine
public TutorialProgress Progress => new(Current?.Id, Status);
///
- /// Decide se mostrare il tutorial all'apertura di una partita. (opzione «Tutorial»
- /// del menu) riparte sempre dal primo passo; un tutorial in corso in quella partita si riprende; uno
- /// completato o chiuso resta nascosto; senza voce salvata si mostra solo se il giocatore l'ha chiesto
- /// (casella «Mostra il tutorial», attiva alla prima partita).
+ /// Decide se mostrare il tutorial all'apertura di una partita. (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.
///
public static TutorialLaunch Plan(bool requested, bool restart, TutorialProgress? saved)
{
if (restart) return TutorialLaunch.StartFresh;
- if (saved is { } s) return s.Status == TutorialStatus.Active ? TutorialLaunch.Resume : TutorialLaunch.Hidden;
+ if (saved is { Status: TutorialStatus.Active }) return TutorialLaunch.Resume;
return requested ? TutorialLaunch.StartFresh : TutorialLaunch.Hidden;
}
@@ -128,6 +147,9 @@ public sealed class TutorialMachine
_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;
}
@@ -137,7 +159,7 @@ public sealed class TutorialMachine
/// Salta il passo corrente.
public void Skip() => Advance();
- /// Chiude il tutorial; si potrà riaprire dal menu.
+ /// Chiude il tutorial; si potrà riaprire con F1 o dalla schermata iniziale.
public void Close()
{
if (Status == TutorialStatus.Active) Status = TutorialStatus.Closed;
diff --git a/client/RailEnterprise.Client/scripts/Tutorial/Logic/TutorialScript.cs b/client/RailEnterprise.Client/scripts/Tutorial/Logic/TutorialScript.cs
index b493485..74dcf6d 100644
--- a/client/RailEnterprise.Client/scripts/Tutorial/Logic/TutorialScript.cs
+++ b/client/RailEnterprise.Client/scripts/Tutorial/Logic/TutorialScript.cs
@@ -17,7 +17,7 @@ public sealed class TutorialScript
public List Steps { get; init; } = [];
/// Indice del passo con l'id indicato, -1 se non c'è.
- public int IndexOf(string? id) => id is null ? -1 : Steps.FindIndex(s => s.Id == id);
+ public int IndexOf(string? id) => id is null ? -1 : Steps.FindIndex(s => s?.Id == id);
/// Legge il copione dal testo JSON (commenti e virgole finali ammessi, campi sconosciuti rifiutati).
public static TutorialScript Parse(string json) =>
@@ -41,15 +41,29 @@ public sealed class TutorialScript
return list;
}
- /// Controlla il copione: id unici, testi presenti, elementi, contatori e pannelli noti. Restituisce gli errori in italiano.
+ ///
+ /// Controlla il copione: elenco e passi presenti (il JSON ammette null ), id unici, testi presenti,
+ /// elementi, contatori e pannelli noti. Restituisce gli errori in italiano.
+ ///
public List Validate()
{
var errors = new List();
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(StringComparer.Ordinal);
- foreach (var step in Steps)
+ 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");
@@ -140,7 +154,11 @@ public sealed class TutorialCondition
{
if (list is null) continue;
if (list.Count == 0) errors.Add($"{where}: elenco di condizioni vuoto");
- foreach (var c in list) c.Validate(where, errors);
+ foreach (var c in list)
+ {
+ if (c is null) errors.Add($"{where}: condizione nulla");
+ else c.Validate(where, errors);
+ }
}
}
}
diff --git a/client/RailEnterprise.Client/scripts/Tutorial/TutorialController.cs b/client/RailEnterprise.Client/scripts/Tutorial/TutorialController.cs
index 6892863..7cc748e 100644
--- a/client/RailEnterprise.Client/scripts/Tutorial/TutorialController.cs
+++ b/client/RailEnterprise.Client/scripts/Tutorial/TutorialController.cs
@@ -11,9 +11,9 @@ namespace RailEnterprise.Client.Tutorial;
///
/// 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à, anteprime del tracciato), fa avanzare
-/// , aggiorna e salva l'avanzamento per partita.
-/// Non invia comandi e non decide regole. F1 riapre o nasconde il tutorial.
+/// copia locale, esiti dei comandi, pannello aperto, camera, velocità chiesta da questo client, anteprime del
+/// tracciato), fa avanzare , aggiorna e salva
+/// l'avanzamento per partita. Non invia comandi e non decide regole. F1 riapre o nasconde il tutorial.
///
public partial class TutorialController : Node
{
@@ -21,6 +21,7 @@ public partial class TutorialController : Node
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 };
@@ -28,19 +29,24 @@ public partial class TutorialController : Node
private readonly TutorialFacts _facts = new();
private readonly Dictionary _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 byte? _lastSpeed;
+ private int _lastSpeedRequests;
- /// casella «Mostra il tutorial» del menu
- /// opzione «Tutorial» del menu: dal primo passo anche se già fatto
- public TutorialController(GameScreen game, bool requested, bool restart)
+ /// origine della partita (locale, tutorial, server remoto) per la chiave dell'avanzamento
+ /// casella «Mostra il tutorial» della schermata di connessione
+ /// pulsante «Tutorial» della schermata di connessione: dal primo passo anche se già fatto
+ public TutorialController(GameScreen game, string scope, bool requested, bool restart)
{
_game = game;
+ _scope = scope;
_requested = requested;
_restart = restart;
}
@@ -58,7 +64,10 @@ public partial class TutorialController : Node
}
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;
@@ -68,16 +77,19 @@ public partial class TutorialController : Node
_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);
+
/// All'avvio e a ogni Welcome (nuova partita, caricamento): chiave della partita e piano di apertura.
private void OpenForGame()
{
if (_machine is null || _game.Session.World.Summary is not { } s) return;
- _gameKey = TutorialProgress.GameKey(s.Seed, s.TerrainHash, s.CompanyId);
+ _gameKey = TutorialProgress.GameKey(_scope, s);
var saved = TutorialSettings.Read(_gameKey);
switch (TutorialMachine.Plan(_requested, _restart, saved))
{
@@ -96,10 +108,9 @@ public partial class TutorialController : Node
_visible = false;
break;
}
- // casella e opzione del menu valgono per la partita aperta, non per le successive (Nuova partita+)
+ // casella e pulsante della schermata di connessione valgono per la partita aperta, non per le successive (Nuova partita+)
_requested = _restart = false;
_lastCamera = null;
- _lastSpeed = null;
_shownIndex = -1;
Refresh();
}
@@ -113,6 +124,8 @@ public partial class TutorialController : Node
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;
}
}
@@ -133,7 +146,12 @@ public partial class TutorialController : Node
public override void _UnhandledKeyInput(InputEvent e)
{
- if (_machine is null || e is not InputEventKey { Pressed: true, Echo: false, Keycode: Key.F1 }) return;
+ 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
@@ -160,22 +178,24 @@ public partial class TutorialController : Node
{
_sinceFacts = 0;
CollectWorldFacts();
- if (_visible)
- {
- string? title = _machine.Current is { } step ? T(step.Title) : null;
- if (_machine.Update(_facts))
- {
- Save();
- if (title is not null) _overlay.Flash(title);
- // completato l'ultimo passo il riquadro si chiude
- if (_machine.Status != TutorialStatus.Active) _visible = false;
- }
- }
+ Evaluate();
}
Refresh();
}
- /// Spostamento della camera (in schermate), zoom (in logaritmi) e cambi di velocità, sommati.
+ /// Valuta il passo corrente sui fatti raccolti; se si completa salva e mostra «Fatto».
+ 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;
+ }
+
+ /// Spostamento della camera (in schermate), zoom (in logaritmi) e velocità chieste da questo client, sommati.
private void TrackCameraAndSpeed()
{
var map = _game.Map;
@@ -197,10 +217,10 @@ public partial class TutorialController : Node
_lastCamera = camera;
_lastZoom = zoom;
- var w = _game.Session.World;
- byte speed = _game.Session.RequestedSpeed ?? w.LastDigest?.Speed ?? w.Speed;
- if (_lastSpeed is { } s && s != speed) _facts.Add("speedChanges", 1);
- _lastSpeed = speed;
+ // 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;
}
/// Entità della compagnia nella copia locale, pannello aperto, anteprime del tracciato.
@@ -253,14 +273,40 @@ public partial class TutorialController : Node
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();
- Control? target = null;
- if (step.Highlight is { } h) target = Shown(_game.TutorialTarget(h));
- if (target is null && step.Fallback is { } f) target = Shown(_game.TutorialTarget(f));
- _overlay.Target = target?.GetGlobalRect();
+ 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;
}
- private static Control? Shown(Control? c) => c is not null && IsInstanceValid(c) && c.IsVisibleInTree() && c.Size.X > 0 ? c : null;
+ ///
+ /// 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.
+ ///
+ 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;
+ }
}
diff --git a/client/RailEnterprise.Client/scripts/Tutorial/TutorialOverlay.cs b/client/RailEnterprise.Client/scripts/Tutorial/TutorialOverlay.cs
index f5e7ee1..cd2afaa 100644
--- a/client/RailEnterprise.Client/scripts/Tutorial/TutorialOverlay.cs
+++ b/client/RailEnterprise.Client/scripts/Tutorial/TutorialOverlay.cs
@@ -39,6 +39,9 @@ public partial class TutorialOverlay : Control
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);
@@ -81,7 +84,7 @@ public partial class TutorialOverlay : Control
_next.Pressed += () => NextPressed?.Invoke();
_skip.Pressed += () => SkipPressed?.Invoke();
_close.Pressed += () => ClosePressed?.Invoke();
- _close.TooltipText = T("Il tutorial si riapre con F1 o dal menu");
+ _close.TooltipText = T("Il tutorial si riapre con F1 o dalla schermata iniziale");
}
/// Mostra un passo: numero, titolo e testo già tradotti; Avanti solo per i passi informativi.
diff --git a/data/ai.json b/data/ai.json
index d34d431..3cb9d40 100644
--- a/data/ai.json
+++ b/data/ai.json
@@ -57,6 +57,12 @@
"industryMaxCashShare": 0.25,
"industryMinMargin": 0.1
},
+ "renewal": {
+ "minSupersededYears": 3,
+ "minAgeShareOfLife": 0.5,
+ "cashReserveMultiple": 2.0,
+ "maxTrainsPerMonth": 1
+ },
"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" },
diff --git a/data/balance.json b/data/balance.json
index 1c813d6..31cdfea 100644
--- a/data/balance.json
+++ b/data/balance.json
@@ -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,
diff --git a/data/maintenance.json b/data/maintenance.json
index 32a3238..2c75e95 100644
--- a/data/maintenance.json
+++ b/data/maintenance.json
@@ -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 },
diff --git a/data/schema/ai.schema.json b/data/schema/ai.schema.json
index 9456435..9888e27 100644
--- a/data/schema/ai.schema.json
+++ b/data/schema/ai.schema.json
@@ -91,6 +91,34 @@
},
"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
+ },
"market": {
"type": "object",
"additionalProperties": {
@@ -108,7 +136,8 @@
"personalities",
"companyNames",
"colors",
- "market"
+ "market",
+ "renewal"
],
"additionalProperties": false
}
diff --git a/data/schema/maintenance.schema.json b/data/schema/maintenance.schema.json
index ce88a48..882fffb 100644
--- a/data/schema/maintenance.schema.json
+++ b/data/schema/maintenance.schema.json
@@ -160,7 +160,8 @@
"service",
"overhaul",
"repair",
- "replace"
+ "replace",
+ "renew"
]
},
"restoreTo": {
diff --git a/data/schema/vehicles.schema.json b/data/schema/vehicles.schema.json
index dc02d15..d700c2b 100644
--- a/data/schema/vehicles.schema.json
+++ b/data/schema/vehicles.schema.json
@@ -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
diff --git a/data/vehicles.json b/data/vehicles.json
index 5d2cdca..8a53f80 100644
--- a/data/vehicles.json
+++ b/data/vehicles.json
@@ -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",
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index ee3ce5f..8c91c50 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -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:
@@ -64,6 +64,7 @@ Sistemi implementati (F1–F5), nella loro posizione:
| `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`.
@@ -92,7 +93,7 @@ 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. `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à.
+- 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. 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.
@@ -124,11 +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; 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`; 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.
-- 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à, anteprime del tracciato) e salva l'avanzamento per partita in `user://settings.cfg`; `TutorialOverlay` disegna il riquadro non modale e il contorno sull'elemento che `GameScreen.TutorialTarget` risolve. Si avvia dal menu («Mostra il tutorial», «Tutorial»), F1 lo nasconde o lo riapre; non c'è nel pilota automatico.
+- 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.
+- 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
diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md
index c067a32..2aa6b17 100644
--- a/docs/PROTOCOL.md
+++ b/docs/PROTOCOL.md
@@ -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, 8 quadro della scalata, 9 quadro delle finanze), `target: i32` (id del treno, del deposito, della compagnia o dell'industria; ignorato per 3, 6, 7, 8 e 9). 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), `target: i32` (id del treno, del deposito, della compagnia o dell'industria; ignorato per 3, 6, 7, 8, 9 e 10). 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,7 +160,7 @@ 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` |
@@ -162,6 +169,7 @@ loro fase i comandi 35–38 rispondono `NotImplemented`. Il server imposta l'emi
| 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) |
Record (ognuno chiude con `flags`):
@@ -182,7 +190,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`
@@ -203,7 +211,13 @@ Record (ognuno chiude con `flags`):
- `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 }`
- `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
@@ -225,7 +239,7 @@ 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. 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.
+ 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.
- 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.
diff --git a/docs/STATE.md b/docs/STATE.md
index a2ed144..ca88566 100644
--- a/docs/STATE.md
+++ b/docs/STATE.md
@@ -141,26 +141,80 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
- 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).
- **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:`), pannello aperto, camera, velocità, 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`);
- - interfaccia: riquadro non modale in basso a sinistra della mappa (riducibile, non copre barra degli strumenti né pannello destro), contorno ambra animato sull'elemento, Avanti per i passi informativi, Salta passo, Chiudi tutorial, «Fatto: …» al completamento; F1 nasconde o riapre; menu con la casella «Mostra il tutorial» (attiva alla prima partita) e l'opzione «Tutorial» (partita locale dal primo passo);
- - avanzamento per partita in `user://settings.cfg` (sezione `tutorial`, chiave da seme, impronta del terreno e compagnia del Welcome): si riprende dopo il caricamento, chiuso o completato resta nascosto; 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`, 8, 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, validazione dei copioni sbagliati, prima partita simulata che percorre tutto il copione. 202 test (183 senza i lenti); interfaccia non provata in Godot (qui manca l'editor).
-- Restano della F6: ere e obsolescenza, pannello 07, tooltip «perché», audio, bilanciamento con i bot.
+ - condizioni solo su ciò che il client riceve o fa: entità della compagnia in `ClientWorld`, esiti riusciti dei comandi (`cmd:`), 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).
+- Restano della F6: tooltip «perché», bilanciamento con i bot.
## Prossimo passo
-- F6: ere e obsolescenza, pannello 07, tooltip «perché», audio, bilanciamento con i bot su `simulate`.
+- F6: tooltip «perché», bilanciamento con i bot su `simulate`.
## 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 e «La tua scalata» alla 08 (F6, non ancora provati in Godot: qui manca l'editor); Industria 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).
diff --git a/docs/adr/0020-ere-e-obsolescenza.md b/docs/adr/0020-ere-e-obsolescenza.md
new file mode 100644
index 0000000..2e2120b
--- /dev/null
+++ b/docs/adr/0020-ere-e-obsolescenza.md
@@ -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).
diff --git a/docs/adr/0021-scheda-industria-e-connessione.md b/docs/adr/0021-scheda-industria-e-connessione.md
new file mode 100644
index 0000000..7e8f4c2
--- /dev/null
+++ b/docs/adr/0021-scheda-industria-e-connessione.md
@@ -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.
diff --git a/docs/adr/0022-audio.md b/docs/adr/0022-audio.md
new file mode 100644
index 0000000..de0aaa7
--- /dev/null
+++ b/docs/adr/0022-audio.md
@@ -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.
diff --git a/docs/adr/0023-tutorial.md b/docs/adr/0023-tutorial.md
index e68680f..778981c 100644
--- a/docs/adr/0023-tutorial.md
+++ b/docs/adr/0023-tutorial.md
@@ -21,17 +21,22 @@ produrre le stesse schermate.
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 il valore al primo aggiornamento del passo. I contatori vengono solo da ciò che
+ `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, cambi di velocità, anteprime del tracciato
+ 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, fa avanzare la macchina, salva) e `TutorialOverlay`.
+ `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
@@ -42,16 +47,30 @@ produrre le stesse schermate.
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). Colori e caratteri da `Palette`/`UiTheme` (immagine 05). Il riquadro si nasconde
+ 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.** Nel menu la casella «Mostra il tutorial» è attiva finché non si è aperta una
- partita (impostazione `tutorial/played`); «Tutorial» apre la partita locale con il tutorial dal primo
- passo. L'avanzamento sta in `user://settings.cfg`, sezione `tutorial`, una voce per partita con chiave
- `g___` (dati del Welcome) e valore `active:`, `completed`
- o `closed`. Aprendo una partita: un tutorial in corso si riprende dal passo salvato (anche dopo un
- caricamento), uno chiuso o completato resta nascosto, senza voce si mostra solo se richiesto; la
- richiesta del menu vale per la partita aperta, non per una Nuova partita+.
-7. **Pilota automatico.** Con `--autopilot` il tutorial non si crea: le schermate del collaudo non cambiano.
+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 `local`, `tutorial` o
+ `remote__`; il resto dal Welcome) e valore `active:`, `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
@@ -61,6 +80,9 @@ produrre le stesse schermate.
- 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 lo stesso seme, la stessa mappa e la stessa compagnia condividono la voce; i
+ è 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).
diff --git a/src/RailEnterprise.Core/Data/AiDefs.cs b/src/RailEnterprise.Core/Data/AiDefs.cs
index 0e7764b..8ca6959 100644
--- a/src/RailEnterprise.Core/Data/AiDefs.cs
+++ b/src/RailEnterprise.Core/Data/AiDefs.cs
@@ -10,6 +10,8 @@ public sealed class AiFile
public required int Version { get; init; }
public required AiPlanningParams Planning { get; init; }
public required AiMarketParams Market { get; init; }
+ /// Rinnovo dei treni con veicoli superati (F6, ADR 0020).
+ public required AiRenewalParams Renewal { get; init; }
public required List Personalities { get; init; }
public required List CompanyNames { get; init; }
public required List Colors { get; init; }
@@ -77,6 +79,21 @@ public sealed class AiPlanningParams
public required int FailedMemory { get; init; }
}
+///
+/// Rinnovo della flotta delle IA (ADR 0020): ogni mese al più treni in
+/// servizio con un veicolo superato vanno in officina per il rinnovo, se il veicolo è superato da almeno
+/// anni o ha già consumato della vita
+/// utile, e se dopo la spesa netta (successori − rivendite) la cassa resta sopra
+/// volte la riserva dell'IA.
+///
+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; }
+}
+
/// Comportamento in borsa delle IA (12.1–12.2).
public sealed class AiMarketParams
{
diff --git a/src/RailEnterprise.Core/Data/BalanceDefs.cs b/src/RailEnterprise.Core/Data/BalanceDefs.cs
index ce335a1..bab3c41 100644
--- a/src/RailEnterprise.Core/Data/BalanceDefs.cs
+++ b/src/RailEnterprise.Core/Data/BalanceDefs.cs
@@ -243,6 +243,17 @@ public sealed class IndustryBalance
public required Dictionary FootprintCells { get; init; }
public required double DepletionStartFraction { get; init; }
public required long StartingCash { get; init; }
+ /// Scheda dell'industria (IndustryOutlook, ADR 0021).
+ public required IndustryOutlookBalance Outlook { get; init; }
+}
+
+/// Parametri della scheda dell'industria (IndustryOutlook, ADR 0021).
+public sealed class IndustryOutlookBalance
+{
+ /// Fornitori o clienti elencati per ogni bene della catena produttiva (prima i collegati, poi i più vicini).
+ public required int PartnersPerGood { get; init; }
+ /// Provenienze dei lavoratori (e del personale) elencate nella scheda, dalle più numerose.
+ public required int WorkforceSources { get; init; }
}
public sealed class GrowthBalance
diff --git a/src/RailEnterprise.Core/Data/DataValidator.cs b/src/RailEnterprise.Core/Data/DataValidator.cs
index 7ad1af0..9533004 100644
--- a/src/RailEnterprise.Core/Data/DataValidator.cs
+++ b/src/RailEnterprise.Core/Data/DataValidator.cs
@@ -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(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));
@@ -186,6 +203,8 @@ 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(), errors);
if (b.Finance.RatingByScore.Length != 9) Err("balance.json", "finance.ratingByScore deve avere 9 soglie (AAA … C)");
@@ -249,6 +268,8 @@ 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
diff --git a/src/RailEnterprise.Core/Data/Enums.cs b/src/RailEnterprise.Core/Data/Enums.cs
index 4612e11..44a1fcc 100644
--- a/src/RailEnterprise.Core/Data/Enums.cs
+++ b/src/RailEnterprise.Core/Data/Enums.cs
@@ -28,7 +28,8 @@ public enum IronmanRule { No, Optional, Yes }
public enum DepletionRate { Slow, Normal, Fast }
-public enum InterventionEffect { Inspection, Service, Overhaul, Repair, Replace }
+/// Effetto di un intervento; Renew sostituisce i veicoli superati con il successore consigliato (ADR 0020).
+public enum InterventionEffect { Inspection, Service, Overhaul, Repair, Replace, Renew }
public enum MaintenancePolicy { Economy, Standard, Thorough }
diff --git a/src/RailEnterprise.Core/Data/GameData.cs b/src/RailEnterprise.Core/Data/GameData.cs
index 4b5b96a..d16f60b 100644
--- a/src/RailEnterprise.Core/Data/GameData.cs
+++ b/src/RailEnterprise.Core/Data/GameData.cs
@@ -23,6 +23,8 @@ public sealed class GameData
public required IReadOnlyList Goods { get; init; }
public required IReadOnlyList Industries { get; init; }
public required IReadOnlyList Vehicles { get; init; }
+ /// Obsolescenza dei modelli superati (vehicles.json, ADR 0020).
+ 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++)
{
diff --git a/src/RailEnterprise.Core/Data/VehicleDefs.cs b/src/RailEnterprise.Core/Data/VehicleDefs.cs
index 40422d1..aaca6ca 100644
--- a/src/RailEnterprise.Core/Data/VehicleDefs.cs
+++ b/src/RailEnterprise.Core/Data/VehicleDefs.cs
@@ -7,9 +7,24 @@ public sealed class VehiclesFile
{
[JsonPropertyName("$schema")] public string? Schema { get; init; }
public required int Version { get; init; }
+ /// Parametri dell'obsolescenza dei modelli superati (F6, ADR 0020).
+ public required ObsolescenceParams Obsolescence { get; init; }
public required List Vehicles { get; init; }
}
+///
+/// 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 e poi si
+/// ammortizza volte più in fretta; gli interventi di manutenzione
+/// costano volte tanto.
+///
+public sealed class ObsolescenceParams
+{
+ public required double ImmediateValueLoss { get; init; }
+ public required double DepreciationSpeed { get; init; }
+ public required double MaintenanceCostFactor { get; init; }
+}
+
/// Modello di veicolo: locomotiva, carro merci o carrozza.
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; }
+ /// Anno di introduzione: da quest'anno il modello si può comprare.
public required int EraFrom { get; init; }
+ /// Ultimo anno di produzione (assente: sempre in produzione); dall'anno dopo non si compra più.
public int? EraTo { get; init; }
+ ///
+ /// Modello che lo sostituisce (stessa categoria, introdotto dopo): dall'anno di introduzione del
+ /// successore questo modello è «superato» (ADR 0020).
+ ///
+ 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; }
+ /// Successore risolto (null se il modello non ne ha).
+ [JsonIgnore] public VehicleDef? SuccessorDef { get; internal set; }
/// Indici dei beni trasportabili (carri).
[JsonIgnore] public int[] GoodIndices { get; internal set; } = [];
}
diff --git a/src/RailEnterprise.Core/Economy/FleetOutlook.cs b/src/RailEnterprise.Core/Economy/FleetOutlook.cs
new file mode 100644
index 0000000..d9b15f1
--- /dev/null
+++ b/src/RailEnterprise.Core/Economy/FleetOutlook.cs
@@ -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;
+
+///
+/// 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.
+///
+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);
+
+/// Modello in produzione nell'anno, come lo mostra il catalogo d'acquisto: superato o no e successore consigliato.
+public sealed record VehicleModelLine(VehicleDef Def, bool Superseded, int? SupersededYear, VehicleDef? Successor, int? LastYear);
+
+///
+/// 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).
+///
+public sealed record RenewalTrainLine(TrainId Train, int Vehicles, Money NetCost, bool Affordable, bool Booked);
+
+///
+/// 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 : lo stesso valore del patrimonio e
+/// della rivendita. Il client lo mostra com'è.
+///
+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; }
+ /// Veicoli non venduti della compagnia, in ordine di id.
+ public required List Vehicles { get; init; }
+ /// Modelli in produzione nell'anno, nell'ordine di vehicles.json (i fuori produzione non ci sono).
+ public required List Models { get; init; }
+ /// Treni della compagnia con almeno un veicolo da rinnovare, in ordine di id.
+ public required List Trains { get; init; }
+ /// Somma dei valori di libro: coincide con la voce «veicoli» dello stato patrimoniale calcolata oggi.
+ 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();
+ 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();
+ 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();
+ 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,
+ };
+ }
+}
diff --git a/src/RailEnterprise.Core/Economy/IndustryOutlook.cs b/src/RailEnterprise.Core/Economy/IndustryOutlook.cs
new file mode 100644
index 0000000..5008435
--- /dev/null
+++ b/src/RailEnterprise.Core/Economy/IndustryOutlook.cs
@@ -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;
+
+///
+/// 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à.
+///
+public enum IndustryLimit : byte
+{
+ /// Nessun fattore sotto 1: l'industria lavora a piena capacità.
+ None = 0,
+ Inputs = 1,
+ Workers = 2,
+ Staff = 3,
+ /// Fattore di profitto (margine negativo).
+ Profit = 4,
+ /// Condizione degli impianti sotto la soglia del rendimento pieno.
+ Condition = 5,
+ /// Giacimento sotto la soglia di esaurimento.
+ Depletion = 6,
+ /// Evento del mondo sulla capacità (incidente).
+ Event = 7,
+ /// Fermo in corso (guasto, incidente, revisione, ammodernamento).
+ Stopped = 8,
+ /// Livello 0 (dormiente) o industria chiusa.
+ Dormant = 9,
+}
+
+/// Tipo di nodo della catena produttiva.
+public enum ChainPartnerKind : byte { Industry = 0, Hub = 1, Town = 2 }
+
+///
+/// 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.
+///
+public readonly record struct ChainPartner(ChainPartnerKind Kind, int Target, double MonthlyUnits, double Price, LineId Line, double DistanceKm);
+
+///
+/// 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).
+///
+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; }
+ /// Input che limita l'efficienza (quello con meno giorni di scorta quando il limite sono gli input).
+ public required bool Limiting { get; init; }
+ public required List Partners { get; init; }
+}
+
+/// Provenienza dei lavoratori (o del personale): città, linea del primo tratto, vettore, minuti di viaggio.
+public readonly record struct WorkforceSource(TownId Town, int Headcount, double Coverage, LineId Line, CompanyId Carrier, double Minutes, bool Walking);
+
+/// Lavoratori o personale qualificato dell'industria.
+public sealed class WorkforceOutlook
+{
+ public required int Jobs { get; init; }
+ public required double Present { get; init; }
+ /// Persone in sede: posti coperti da chi vive negli alloggi dell'industria (posti × quota in sede).
+ public required double OnSite { get; init; }
+ /// Copertura media su coverageWindowDays (entra nell'efficienza).
+ public required double Coverage { get; init; }
+ /// Posti scoperti oggi (posti − presenti, arrotondato).
+ public required int Missing { get; init; }
+ public required UncoveredReason Reason { get; init; }
+ public required LineId ReasonLine { get; init; }
+ /// Viaggio medio in treno (minuti, pesato sulle persone) dei contratti visibili; −1 se nessuno.
+ public required double AverageMinutes { get; init; }
+ /// Provenienze più numerose (al massimo industry.outlook.workforceSources).
+ public required List Sources { get; init; }
+ /// Provenienze visibili in tutto (anche quelle non elencate).
+ public required int SourceCount { get; init; }
+}
+
+/// Crescita trimestrale (guida 6.3): punteggio del trimestre in corso, soglie e trimestri.
+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; }
+ /// Giorni del trimestre già contati e lunghezza del trimestre.
+ public required int QuarterDay { get; init; }
+ public required int QuarterDays { get; init; }
+ /// Servita da un vettore nel trimestre: solo allora il livello cambia (ADR 0004).
+ public required bool Served { get; init; }
+ public required int MaxLevel { get; init; }
+}
+
+/// Scheda dell'industria per la compagnia della sessione (immagine di riferimento 07, ADR 0021).
+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; }
+ /// Riserva residua del giacimento (0–1); −1 se l'industria non è esauribile.
+ public required double ReserveFraction { get; init; }
+ public required int StorageDays { get; init; }
+ public required List Inputs { get; init; }
+ public required List Outputs { get; init; }
+ public required WorkforceOutlook Workers { get; init; }
+ public required WorkforceOutlook Staff { get; init; }
+ ///
+ /// 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.
+ ///
+ public required double SalePrice { get; init; }
+ public required Money AnnualProfit { get; init; }
+ public required GrowthOutlook Growth { get; init; }
+ /// Stazioni (di qualunque compagnia) che servono l'industria con una linea con treni.
+ public required List ServingStations { get; init; }
+ /// Linea della compagnia della sessione che serve l'industria (id più basso), None se nessuna.
+ public required LineId ServingLine { get; init; }
+ /// Dei privati e attiva: si può comprare (dal livello che sblocca l'acquisto).
+ public required bool ForSale { get; init; }
+ public required bool BuyUnlocked { get; init; }
+ public required int BuyTier { get; init; }
+ /// Avanzamento verso il livello che sblocca l'acquisto (ADR 0018); 1 se sbloccato.
+ public required double BuyProgress { get; init; }
+}
+
+///
+/// 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.
+///
+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(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(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,
+ };
+ }
+
+ /// Fattori dell'efficienza dell'industria e quello che la limita.
+ public readonly record struct EfficiencyFactors(
+ double ProfitFactor, double ConditionMultiplier, double Depletion, double EventCapacity, double ReserveFraction, bool Stopped, IndustryLimit Limit);
+
+ ///
+ /// 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 ), Fermo se l'industria è ferma, Dormiente al
+ /// livello 0 o chiusa.
+ ///
+ 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);
+ }
+
+ ///
+ /// 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.
+ ///
+ 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,
+ };
+ }
+
+ /// Contratto che la compagnia può vedere: a piedi, trasportato da lei, o verso una sua industria.
+ public static bool Visible(CommuteContract c, Industry ind, CompanyId company) =>
+ c.Walking || (company.IsValid && (c.Carrier == company || ind.Owner == company));
+
+ ///
+ /// 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.
+ ///
+ private static List Suppliers(World w, Industry ind, int good, LineLinks links, List mine)
+ {
+ int dpm = w.Calendar.DaysPerMonth;
+ double pg = w.Market.GlobalPrice[good];
+ var all = new List();
+ 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);
+ }
+
+ ///
+ /// 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.
+ ///
+ private static List Customers(World w, Industry ind, int good, LineLinks links, List mine)
+ {
+ int dpm = w.Calendar.DaysPerMonth;
+ double pg = w.Market.GlobalPrice[good];
+ var lp = w.Data.Balance.LocalPrice;
+ var all = new List();
+ 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);
+ }
+
+ /// Prima i collegati (per linea), poi i più vicini; a parità tipo e id; al massimo partnersPerGood.
+ private static List Pick(World w, List 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;
+
+ /// Stazioni vive (di qualunque compagnia) con l'industria nel bacino e fermata di una linea con treni.
+ public static List 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();
+ 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;
+ }
+
+ ///
+ /// 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.
+ ///
+ private sealed class LineLinks
+ {
+ private readonly List<(Line Line, HashSet Industries, HashSet Hubs, HashSet 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();
+ var hubs = new HashSet();
+ var towns = new HashSet();
+ 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));
+ }
+ }
+
+ /// Linee che raggiungono l'industria, per id crescente.
+ public List Serving(Industry ind) => _lines.Where(x => x.Industries.Contains(ind.Id.Value)).Select(x => x.Line).ToList();
+
+ /// Prima linea (id più basso) tra quelle dell'industria che raggiunge anche il nodo indicato.
+ public LineId Link(List 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;
+ }
+ }
+}
diff --git a/src/RailEnterprise.Core/Simulation/Ai/AiAgent.cs b/src/RailEnterprise.Core/Simulation/Ai/AiAgent.cs
index d5e53d7..0b74169 100644
--- a/src/RailEnterprise.Core/Simulation/Ai/AiAgent.cs
+++ b/src/RailEnterprise.Core/Simulation/Ai/AiAgent.cs
@@ -192,10 +192,11 @@ internal sealed class AiAgent
/// Compra locomotiva e carri nel deposito del progetto, compone il treno e lo assegna alla linea.
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();
var rl = Do(new BuyVehicleCommand(project.Loco, project.Depot, 1));
if (!rl.Ok) return false;
@@ -211,6 +212,31 @@ internal sealed class AiAgent
return true;
}
+ ///
+ /// 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.
+ ///
+ 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,6 +266,7 @@ internal sealed class AiAgent
}
Finance();
GrowLines();
+ RenewFleet();
StockMarket();
BuyIndustries();
if (!EnsurePartsSupply()) NewProject();
@@ -287,7 +314,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)
{
@@ -315,6 +342,12 @@ internal sealed class AiAgent
return false;
}
+ ///
+ /// 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.
+ ///
+ private long FreeCash() => _c.Cash.Cents - Obsolescence.Committed(_w, _c.Id).Cents;
+
/// Riserva di cassa: mesi di costi d'esercizio stimati dalla flotta e dalla rete.
private long Reserve()
{
@@ -401,6 +434,48 @@ internal sealed class AiAgent
}
}
+ // ================================================================== rinnovo della flotta (ADR 0020)
+
+ ///
+ /// 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
+ /// ( ) e se dopo la spesa (successori − rivendite + lavoro)
+ /// la cassa libera resta sopra renewal.cashReserveMultiple volte la riserva. La spesa resta impegnata
+ /// ( ) fino all'avvio dei lavori, così gli investimenti dello stesso mese non la riusano.
+ ///
+ 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 +487,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 +527,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 +580,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;
@@ -571,7 +646,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;
@@ -1147,7 +1222,7 @@ internal sealed class AiAgent
/// Apre i cantieri del progetto: stazioni, deposito, binario e raccordo del deposito.
private void Execute(Proposal p, DepotId? supply = null)
{
- long need = p.Capital + Reserve() - _c.Cash.Cents;
+ long need = p.Capital + Reserve() - FreeCash();
if (need > 0 && !Borrow(need)) return;
var cand = p.Candidate;
var stationA = p.ExistingA;
diff --git a/src/RailEnterprise.Core/Simulation/Ai/AiState.cs b/src/RailEnterprise.Core/Simulation/Ai/AiState.cs
index a09a03e..a38dd9e 100644
--- a/src/RailEnterprise.Core/Simulation/Ai/AiState.cs
+++ b/src/RailEnterprise.Core/Simulation/Ai/AiState.cs
@@ -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; }
+ /// Modelli dei treni della linea; se escono di produzione si passa al successore (ADR 0020).
+ public required string Loco { get; set; }
+ public required string Car { get; set; }
public int CarsPerTrain { get; init; }
/// Giorno prima del quale non si aggiungono treni (dopo uno stallo risolto).
public long GrowAfterDay { get; set; }
diff --git a/src/RailEnterprise.Core/Simulation/Estimators.cs b/src/RailEnterprise.Core/Simulation/Estimators.cs
index 762773c..cbbc22d 100644
--- a/src/RailEnterprise.Core/Simulation/Estimators.cs
+++ b/src/RailEnterprise.Core/Simulation/Estimators.cs
@@ -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;
}
- /// Carro più economico che trasporta il bene nell'anno.
+ ///
+ /// 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).
+ ///
+ private static bool Outdated(VehicleDef v, int year) =>
+ Obsolescence.IsSuperseded(v, year) && Obsolescence.Recommended(v, year) is { } next && Obsolescence.NoWorseThan(next, v);
+
+ /// Carro più economico che trasporta il bene nell'anno, esclusi i superati con un successore in produzione.
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;
}
- /// Carrozza della classe indicata disponibile nell'anno.
+ /// Carrozza più economica della classe indicata disponibile nell'anno, esclusi i superati con un successore in produzione.
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;
diff --git a/src/RailEnterprise.Core/Simulation/GameEvents.cs b/src/RailEnterprise.Core/Simulation/GameEvents.cs
index c1863f2..ef2a9da 100644
--- a/src/RailEnterprise.Core/Simulation/GameEvents.cs
+++ b/src/RailEnterprise.Core/Simulation/GameEvents.cs
@@ -20,6 +20,8 @@ public enum EventKind : byte
Company = 9,
/// Evento del mondo (events.json, ADR 0017): inizio e fine.
World = 10,
+ /// Passaggio d'era e novità tecnologiche dell'anno (ADR 0020).
+ Technology = 11,
}
/// Riferimento facoltativo all'entità coinvolta.
diff --git a/src/RailEnterprise.Core/Simulation/MaintenanceCommandHandlers.cs b/src/RailEnterprise.Core/Simulation/MaintenanceCommandHandlers.cs
index 15262ff..23757d9 100644
--- a/src/RailEnterprise.Core/Simulation/MaintenanceCommandHandlers.cs
+++ b/src/RailEnterprise.Core/Simulation/MaintenanceCommandHandlers.cs
@@ -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))
diff --git a/src/RailEnterprise.Core/Simulation/RailCommandHandlers.cs b/src/RailEnterprise.Core/Simulation/RailCommandHandlers.cs
index d5c0606..20b5ab8 100644
--- a/src/RailEnterprise.Core/Simulation/RailCommandHandlers.cs
+++ b/src/RailEnterprise.Core/Simulation/RailCommandHandlers.cs
@@ -408,14 +408,11 @@ public static class RailCommandHandlers
return reply(CommandError.None, $"Venduto per {value}");
}
- /// Valore di rivendita: prezzo × (1 − età/vita, minimo 10 %) × condizione media.
- 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);
- }
+ ///
+ /// Valore di rivendita: prezzo × residuo (1 − età/vita, minimo 10 %, più rapido per i modelli
+ /// superati) × condizione media; la curva è in (ADR 0020).
+ ///
+ public static Money ResaleValue(World w, Vehicle v) => Obsolescence.ResaleValue(w, v);
public static CommandResult ComposeTrain(World w, Company company, ComposeTrainCommand c, Reply reply)
{
diff --git a/src/RailEnterprise.Core/Simulation/SystemPipeline.cs b/src/RailEnterprise.Core/Simulation/SystemPipeline.cs
index 89be274..ab2a752 100644
--- a/src/RailEnterprise.Core/Simulation/SystemPipeline.cs
+++ b/src/RailEnterprise.Core/Simulation/SystemPipeline.cs
@@ -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.
///
public sealed class SystemPipeline(IReadOnlyList systems)
{
@@ -43,6 +43,7 @@ public sealed class SystemPipeline(IReadOnlyList systems)
new StockMarketSystem(),
new AiSystem(),
new EventSystem(),
+ new EraSystem(),
new HashSystem(),
]);
diff --git a/src/RailEnterprise.Core/Simulation/Systems/EraSystem.cs b/src/RailEnterprise.Core/Simulation/Systems/EraSystem.cs
new file mode 100644
index 0000000..7be6e49
--- /dev/null
+++ b/src/RailEnterprise.Core/Simulation/Systems/EraSystem.cs
@@ -0,0 +1,157 @@
+using System.Globalization;
+using RailEnterprise.Core.Common;
+using RailEnterprise.Core.Data;
+
+namespace RailEnterprise.Core.Simulation.Systems;
+
+/// Tipo di novità tecnologica di un anno (ADR 0020).
+public enum TechKind : byte
+{
+ Traction = 0,
+ Vehicle = 1,
+ BridgeType = 2,
+ TunnelLimit = 3,
+ TrackClass = 4,
+ Signal = 5,
+ Electrification = 6,
+ Good = 7,
+ Industry = 8,
+}
+
+/// Novità che un anno sblocca: tipo, id nei dati (vuoto per gallerie ed elettrificazione) e testo italiano.
+public readonly record struct TechUnlock(TechKind Kind, string Id, string TextIt);
+
+///
+/// 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 ( )
+/// 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.
+///
+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);
+ }
+
+ /// Emette la notizia delle novità dell'anno (se ce ne sono) e la annota nella Cronaca del giocatore.
+ 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;
+ }
+
+ /// Era in corso nell'anno: l'ultima iniziata (la prima se l'anno la precede).
+ 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;
+ }
+
+ /// Prossima era dopo l'anno (null all'ultima).
+ public static EraDef? NextEra(GameData d, int year) => d.Eras.Eras.FirstOrDefault(e => e.From > year);
+
+ /// Era che inizia esattamente nell'anno (null se nessuna).
+ public static EraDef? EraStarting(GameData d, int year) => d.Eras.Eras.FirstOrDefault(e => e.From == year);
+
+ /// Novità introdotte nell'anno, nell'ordine dei file dati.
+ public static List Unlocks(GameData d, int year)
+ {
+ var list = new List();
+ 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;
+ }
+
+ /// Modelli fuori produzione dall'anno (ultimo anno di produzione l'anno prima).
+ public static List Retired(GameData d, int year) => d.Vehicles.Where(v => v.EraTo == year - 1).ToList();
+
+ /// Modelli che nell'anno diventano superati (il successore è introdotto quell'anno).
+ public static List NewlySuperseded(GameData d, int year) => d.Vehicles.Where(v => v.SuccessorDef?.EraFrom == year).ToList();
+
+ /// Testo della notizia dell'anno, o null se l'anno non porta nulla di nuovo.
+ 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)}";
+ }
+
+ /// Parti della notizia dell'anno: sblocchi, modelli superati, fuori produzione (vuota se nessuna).
+ public static List NewsParts(GameData d, int year)
+ {
+ var unlocks = Unlocks(d, year);
+ var retired = Retired(d, year);
+ var superseded = NewlySuperseded(d, year);
+ var parts = new List();
+ 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 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('.', ',');
+}
diff --git a/src/RailEnterprise.Core/Simulation/Systems/FinanceSystem.cs b/src/RailEnterprise.Core/Simulation/Systems/FinanceSystem.cs
index dfc7ef0..02c06e7 100644
--- a/src/RailEnterprise.Core/Simulation/Systems/FinanceSystem.cs
+++ b/src/RailEnterprise.Core/Simulation/Systems/FinanceSystem.cs
@@ -221,8 +221,8 @@ public sealed class FinanceSystem : ISimSystem
foreach (var v in w.Vehicles)
{
if (v.Sold) continue;
- double age = (today - v.BoughtDay) / daysPerYear;
- values[v.Owner.Value][vehicles] += (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)
{
diff --git a/src/RailEnterprise.Core/Simulation/Systems/Fleet.cs b/src/RailEnterprise.Core/Simulation/Systems/Fleet.cs
index dbb58ac..45b5166 100644
--- a/src/RailEnterprise.Core/Simulation/Systems/Fleet.cs
+++ b/src/RailEnterprise.Core/Simulation/Systems/Fleet.cs
@@ -173,27 +173,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;
- /// Costo dell'intervento: quota del prezzo dei veicoli interessati × fattore di costo della politica.
+ ///
+ /// 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).
+ ///
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);
+
/// Applica gli effetti dell'intervento ai veicoli del treno (10.2), scalati dalla politica.
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 +235,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);
diff --git a/src/RailEnterprise.Core/Simulation/Systems/FleetMaintenanceSystem.cs b/src/RailEnterprise.Core/Simulation/Systems/FleetMaintenanceSystem.cs
index bd8458e..262619e 100644
--- a/src/RailEnterprise.Core/Simulation/Systems/FleetMaintenanceSystem.cs
+++ b/src/RailEnterprise.Core/Simulation/Systems/FleetMaintenanceSystem.cs
@@ -489,7 +489,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 +513,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)
+ /// Avvia il lavoro: preleva i ricambi e paga l'intervento. Falso se un rinnovo si annulla.
+ 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? 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 +586,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
diff --git a/src/RailEnterprise.Core/Simulation/Systems/IndustryMath.cs b/src/RailEnterprise.Core/Simulation/Systems/IndustryMath.cs
index 8859d23..8566256 100644
--- a/src/RailEnterprise.Core/Simulation/Systems/IndustryMath.cs
+++ b/src/RailEnterprise.Core/Simulation/Systems/IndustryMath.cs
@@ -4,6 +4,9 @@ using RailEnterprise.Core.Economy;
namespace RailEnterprise.Core.Simulation.Systems;
+/// Componenti del punteggio di crescita trimestrale (quota trasportata, copertura, redditività) e punteggio.
+public readonly record struct GrowthScoreParts(double Shipped, double Coverage, double Profit, double Score);
+
/// Formule dell'industria condivise da più sistemi (guida 6.3 e 11).
public static class IndustryMath
{
@@ -20,6 +23,20 @@ public static class IndustryMath
return m.EfficiencyAt20 + (1.0 - m.EfficiencyAt20) * t;
}
+ ///
+ /// Punteggio di crescita del trimestre (guida 6.3) dalle statistiche accumulate finora:
+ /// 0,5·quota trasportata + 0,3·copertura media + 0,2·redditività, con i pesi di balance.json.
+ /// Lo usa la crescita trimestrale e, a trimestre in corso, la scheda dell'industria.
+ ///
+ public static GrowthScoreParts GrowthScore(Industry ind, GrowthBalance g)
+ {
+ double shipped = ind.QuarterProduced > 0 ? Math.Min(1.0, (double)ind.QuarterShipped / ind.QuarterProduced) : 0;
+ double coverage = ind.QuarterDays > 0 ? ind.QuarterCoverageSum / ind.QuarterDays : 0;
+ double profit = Math.Clamp((ind.Margin + 1) / 2, 0, 1);
+ double score = g.WeightShipped * shipped + g.WeightCoverage * coverage + g.WeightProfit * profit;
+ return new GrowthScoreParts(shipped, coverage, profit, score);
+ }
+
/// Capienza del magazzino di un output (unità) al livello corrente.
public static int OutputCapacity(Industry ind, int outputIndex, int daysPerMonth)
{
diff --git a/src/RailEnterprise.Core/Simulation/Systems/IndustrySystem.cs b/src/RailEnterprise.Core/Simulation/Systems/IndustrySystem.cs
index 7d54a8e..e8b90d3 100644
--- a/src/RailEnterprise.Core/Simulation/Systems/IndustrySystem.cs
+++ b/src/RailEnterprise.Core/Simulation/Systems/IndustrySystem.cs
@@ -138,10 +138,7 @@ public sealed class IndustrySystem : ISimSystem
foreach (var ind in w.Industries)
{
if (ind.Closed) continue;
- double shipped = ind.QuarterProduced > 0 ? Math.Min(1.0, (double)ind.QuarterShipped / ind.QuarterProduced) : 0;
- double coverage = ind.QuarterDays > 0 ? ind.QuarterCoverageSum / ind.QuarterDays : 0;
- double profit = Math.Clamp((ind.Margin + 1) / 2, 0, 1);
- double score = g.WeightShipped * shipped + g.WeightCoverage * coverage + g.WeightProfit * profit;
+ double score = IndustryMath.GrowthScore(ind, g).Score;
ind.LastScore = score;
ind.QuarterProduced = 0;
ind.QuarterShipped = 0;
diff --git a/src/RailEnterprise.Core/Simulation/Systems/Obsolescence.cs b/src/RailEnterprise.Core/Simulation/Systems/Obsolescence.cs
new file mode 100644
index 0000000..30371d6
--- /dev/null
+++ b/src/RailEnterprise.Core/Simulation/Systems/Obsolescence.cs
@@ -0,0 +1,226 @@
+using RailEnterprise.Core.Common;
+using RailEnterprise.Core.Data;
+using RailEnterprise.Core.Economy;
+using RailEnterprise.Core.Rail;
+using RailEnterprise.Core.Time;
+
+namespace RailEnterprise.Core.Simulation.Systems;
+
+/// Veicolo superato da rinnovare: il successore consigliato, il suo prezzo e la rivendita del vecchio.
+public readonly record struct RenewalItem(Vehicle Old, VehicleDef Successor, Money Price, Money Resale);
+
+///
+/// Produzione, obsolescenza e valore dei veicoli (F6, ADR 0020), senza stato: tutto discende dai dati
+/// (anno di introduzione, ultimo anno di produzione, successore di vehicles.json), dal calendario e dal
+/// giorno d'acquisto del veicolo. È l'unica fonte del valore di un veicolo: il valore di libro del
+/// patrimonio ( ), la rivendita di SellVehicle , il rinnovo e
+/// i quadri del client leggono le stesse funzioni.
+///
+/// Curva del valore (residuo r, frazione del prezzo, con il minimo finance.bookValueFloor ):
+/// - modello non superato: r = 1 − età / vita;
+/// - superato (dal 1° gennaio dell'anno d'introduzione del successore, o dall'acquisto se è successivo):
+/// r = (1 − perdita) × (1 − (età + (velocità − 1) × anni da superato) / vita), cioè un gradino di
+/// immediateValueLoss e poi un ammortamento depreciationSpeed volte più rapido.
+/// Valore di libro = prezzo × r; rivendita = prezzo × r × condizione media dei componenti.
+///
+public static class Obsolescence
+{
+ /// Vero se il modello si può comprare nell'anno: introdotto e non ancora fuori produzione.
+ public static bool InProduction(VehicleDef def, int year) => def.EraFrom <= year && (def.EraTo is not { } to || year <= to);
+
+ /// Vero se il successore del modello è già stato introdotto nell'anno.
+ public static bool IsSuperseded(VehicleDef def, int year) => def.SuccessorDef is { } s && s.EraFrom <= year;
+
+ /// Anno da cui il modello è superato (null se non ha successore).
+ public static int? SupersededYear(VehicleDef def) => def.SuccessorDef?.EraFrom;
+
+ ///
+ /// Successore consigliato nell'anno: il più recente della catena dei successori già introdotto e
+ /// ancora in produzione (null se il modello non è superato o nessun successore si può comprare).
+ ///
+ public static VehicleDef? Recommended(VehicleDef def, int year)
+ {
+ VehicleDef? best = null;
+ for (var s = def.SuccessorDef; s is not null && s.EraFrom <= year; s = s.SuccessorDef)
+ {
+ if (InProduction(s, year)) best = s;
+ }
+ return best;
+ }
+
+ /// Primo giorno in cui il modello è superato (long.MaxValue se non ha successore).
+ public static long SupersededDay(Calendar calendar, VehicleDef def) =>
+ def.SuccessorDef is { } s ? (long)(s.EraFrom - calendar.StartYear) * calendar.DaysPerYear : long.MaxValue;
+
+ /// Anni da quando il veicolo è superato (dal giorno d'acquisto se è successivo); 0 se non lo è.
+ public static double YearsSuperseded(World w, Vehicle v)
+ {
+ long since = SupersededDay(w.Calendar, v.Def);
+ long today = w.Clock.Day;
+ if (today < since) return 0;
+ return (today - Math.Max(v.BoughtDay, since)) / (double)w.Calendar.DaysPerYear;
+ }
+
+ /// Residuo del valore del veicolo oggi (frazione del prezzo di listino).
+ public static double Residual(World w, Vehicle v) => Residual(w.Data, w.Calendar, v.Def, v.BoughtDay, w.Clock.Day);
+
+ /// Residuo del valore di un veicolo del modello comprato in , al giorno .
+ public static double Residual(GameData d, Calendar calendar, VehicleDef def, long boughtDay, long today)
+ {
+ double daysPerYear = calendar.DaysPerYear;
+ double floor = d.Balance.Finance.BookValueFloor;
+ double age = (today - boughtDay) / daysPerYear;
+ long since = SupersededDay(calendar, def);
+ if (today < since) return Math.Max(floor, 1 - age / def.LifeYears);
+ var o = d.Obsolescence;
+ double years = (today - Math.Max(boughtDay, since)) / daysPerYear;
+ double effectiveAge = age + (o.DepreciationSpeed - 1) * years;
+ return Math.Max(floor, (1 - o.ImmediateValueLoss) * (1 - effectiveAge / def.LifeYears));
+ }
+
+ /// Valore di libro del veicolo in centesimi: prezzo × residuo (voce «veicoli» del patrimonio).
+ public static long BookValueCents(World w, Vehicle v) => (long)(v.Def.Price * Residual(w, v));
+
+ /// Condizione media dei componenti come frazione (1 se il veicolo non ne ha).
+ public static double AverageCondition(Vehicle v) => v.Components.Length == 0 ? 1 : v.Components.Average() / 100;
+
+ /// Valore di rivendita (mercato dell'usato): prezzo × residuo × condizione media.
+ public static Money ResaleValue(World w, Vehicle v) => new Money(v.Def.Price) * (Residual(w, v) * AverageCondition(v));
+
+ /// Moltiplicatore dei costi di manutenzione del modello nell'anno: maintenanceCostFactor se superato, altrimenti 1.
+ public static double MaintenanceCostFactor(GameData d, VehicleDef def, int year) =>
+ IsSuperseded(def, year) ? d.Obsolescence.MaintenanceCostFactor : 1;
+
+ ///
+ /// Veicoli del treno da rinnovare oggi, in ordine di composizione: quelli superati con un successore
+ /// consigliato in produzione, con il prezzo del successore e la rivendita del vecchio.
+ ///
+ public static List RenewalPlan(World w, Train t)
+ {
+ var list = new List();
+ int year = w.Clock.Year;
+ foreach (var id in t.Vehicles)
+ {
+ var v = w.Vehicles[id.Value];
+ if (!IsSuperseded(v.Def, year) || Recommended(v.Def, year) is not { } next) continue;
+ list.Add(new RenewalItem(v, next, new Money(next.Price), ResaleValue(w, v)));
+ }
+ return list;
+ }
+
+ /// Spesa netta di un rinnovo: prezzi dei successori meno le rivendite (può essere negativa).
+ public static Money NetCost(List plan)
+ {
+ long cents = 0;
+ foreach (var item in plan) cents += item.Price.Cents - item.Resale.Cents;
+ return new Money(cents);
+ }
+
+ /// Indice in maintenance.json dell'intervento con effetto «renew» (il validatore ne garantisce uno).
+ public static int RenewalIntervention(GameData d) => d.Maintenance.Interventions.FindIndex(i => i.Effect == InterventionEffect.Renew);
+
+ /// Spesa complessiva del rinnovo del treno oggi: successori − rivendite + lavoro dell'officina.
+ public static Money RenewalCost(World w, Train t, List plan) =>
+ NetCost(plan) + Fleet.CostOf(w, t, w.Data.Maintenance.Interventions[RenewalIntervention(w.Data)], Fleet.PolicyOf(w, t));
+
+ /// Vero se il treno ha un rinnovo prenotato o in officina.
+ public static bool RenewalBooked(World w, Train t) => t.PlannedIntervention >= 0 && t.PlannedIntervention == RenewalIntervention(w.Data);
+
+ ///
+ /// Spesa impegnata dal rinnovo prenotato del treno e non ancora pagata: la spesa di oggi (se positiva)
+ /// finché i lavori non partono. All'avvio i veicoli si sostituiscono e il piano si svuota, quindi un
+ /// rinnovo già pagato non impegna più nulla.
+ ///
+ public static Money Commitment(World w, Train t)
+ {
+ if (t.Removed || !RenewalBooked(w, t)) return Money.Zero;
+ var plan = RenewalPlan(w, t);
+ if (plan.Count == 0) return Money.Zero;
+ var cost = RenewalCost(w, t, plan);
+ return cost.IsPositive ? cost : Money.Zero;
+ }
+
+ ///
+ /// Spesa impegnata dai rinnovi prenotati della compagnia e non ancora avviati, escluso eventualmente
+ /// un treno: va tolta dalla cassa prima di prenotarne un altro o di investire (ADR 0020).
+ ///
+ public static Money Committed(World w, CompanyId company, Train? except = null)
+ {
+ long cents = 0;
+ foreach (var t in w.Trains)
+ {
+ if (t != except && t.Owner == company) cents += Commitment(w, t).Cents;
+ }
+ return new Money(cents);
+ }
+
+ /// Vero se il modello non ha sforzo di trazione, potenza o velocità massima inferiori a .
+ public static bool NoWorseThan(VehicleDef next, VehicleDef old) =>
+ next.TractiveEffortKn >= old.TractiveEffortKn && next.PowerKw >= old.PowerKw && next.MaxSpeedKmh >= old.MaxSpeedKmh;
+
+ ///
+ /// Vero se il rinnovo non peggiora le prestazioni del treno: sforzo di trazione, potenza, velocità
+ /// massima e rapporto potenza/massa restano almeno quelli di oggi. Le IA rinnovano solo così; il
+ /// giocatore vede il successore con le sue prestazioni e decide da sé.
+ ///
+ public static bool KeepsPerformance(World w, Train t, List plan)
+ {
+ double te = 0, power = 0, mass = 0, vmax = double.MaxValue;
+ double te2 = 0, power2 = 0, mass2 = 0, vmax2 = double.MaxValue;
+ foreach (var id in t.Vehicles)
+ {
+ var def = w.Vehicles[id.Value].Def;
+ var next = def;
+ foreach (var item in plan)
+ {
+ if (item.Old.Id == id) next = item.Successor;
+ }
+ te += def.TractiveEffortKn; power += def.PowerKw; mass += def.MassT; vmax = Math.Min(vmax, def.MaxSpeedKmh);
+ te2 += next.TractiveEffortKn; power2 += next.PowerKw; mass2 += next.MassT; vmax2 = Math.Min(vmax2, next.MaxSpeedKmh);
+ }
+ if (mass <= 0 || mass2 <= 0) return true;
+ const double eps = 1e-9;
+ return te2 + eps >= te && power2 + eps >= power && vmax2 + eps >= vmax && power2 / mass2 + eps >= power / mass;
+ }
+
+ ///
+ /// Rinnovo in officina (intervento con effetto «renew»), all'avvio dei lavori: ogni veicolo del piano
+ /// si vende al valore di rivendita (voce «vendita di treni») e al suo posto, nella stessa posizione
+ /// della composizione, entra un veicolo nuovo del successore consigliato (voce «acquisto di treni»).
+ /// I veicoli venduti restano nell'elenco con Sold , come quelli di SellVehicle .
+ /// Il controllo della cassa spetta a chi chiama. Restituisce quanti veicoli sono stati sostituiti.
+ ///
+ public static int Renew(World w, Train t) => Renew(w, t, RenewalPlan(w, t));
+
+ /// Rinnovo con un piano già calcolato oggi (vedi ).
+ public static int Renew(World w, Train t, List plan)
+ {
+ if (plan.Count == 0) return 0;
+ var owner = Account.Of(t.Owner);
+ foreach (var item in plan)
+ {
+ var old = item.Old;
+ int index = t.Vehicles.IndexOf(old.Id);
+ var fresh = new Vehicle
+ {
+ Id = new VehicleId(w.Vehicles.Count),
+ Def = item.Successor,
+ Owner = old.Owner,
+ BoughtDay = w.Clock.Day,
+ Train = t.Id,
+ };
+ Fleet.InitVehicle(w.Data, fresh, w.Clock.Day);
+ w.Vehicles.Add(fresh);
+ old.Sold = true;
+ old.Train = TrainId.None;
+ old.Depot = DepotId.None;
+ t.Vehicles[index] = fresh.Id;
+ if (item.Resale.IsPositive) w.Money.Transfer(Account.External, owner, item.Resale, LedgerEntry.VehicleSale);
+ w.Money.Transfer(owner, Account.External, item.Price, LedgerEntry.VehiclePurchase);
+ }
+ w.NextIds.Vehicle = w.Vehicles.Count;
+ RailCommandHandlers.RecomputeTrain(w, t);
+ w.LineGraphs.Touch();
+ return plan.Count;
+ }
+}
diff --git a/src/RailEnterprise.Protocol/Client/ClientWorld.cs b/src/RailEnterprise.Protocol/Client/ClientWorld.cs
index 2ffa47f..706ebe4 100644
--- a/src/RailEnterprise.Protocol/Client/ClientWorld.cs
+++ b/src/RailEnterprise.Protocol/Client/ClientWorld.cs
@@ -56,6 +56,15 @@ public sealed class ClientWorld(GameData data)
/// Quadro delle finanze (F6), su richiesta: lo usa il pannello «Finanze».
public FinanceReport? Finance { get; private set; }
+ /// Quadro del rinnovo della flotta (F6, ADR 0020), su richiesta: lo usano i pannelli Treni e Officine.
+ public FleetReport? Fleet { get; private set; }
+
+ /// Stato del server dall'ultimo Welcome (F6, ADR 0021): versione, sistema, attività, tick, sessioni.
+ public ServerInfo? Server { get; private set; }
+
+ /// Ultimo elenco dei salvataggi del server (risposta a ListSaves e a Save); resta valido anche dopo un nuovo Welcome.
+ public SaveList? Saves { get; private set; }
+
/// Contatore dei listini ricevuti (per aggiornare il pannello della borsa).
public int TapeVersion { get; private set; }
@@ -148,6 +157,14 @@ public sealed class ClientWorld(GameData data)
Finance = m;
DetailVersion++;
return true;
+ case FleetReport m:
+ Fleet = m;
+ DetailVersion++;
+ return true;
+ case SaveList m:
+ Saves = m;
+ DetailVersion++;
+ return true;
case MaintenanceAlert m:
Alerts.Insert(0, m);
if (Alerts.Count > AlertCapacity) Alerts.RemoveAt(Alerts.Count - 1);
@@ -170,8 +187,10 @@ public sealed class ClientWorld(GameData data)
Market = null;
Climb = null;
Finance = null;
+ Fleet = null;
Alerts.Clear();
Summary = m.Summary;
+ Server = m.Server;
SessionId = m.SessionId;
Tick = m.Summary.Tick;
Speed = m.Summary.Speed;
diff --git a/src/RailEnterprise.Protocol/Message.cs b/src/RailEnterprise.Protocol/Message.cs
index 49ca71d..c961a59 100644
--- a/src/RailEnterprise.Protocol/Message.cs
+++ b/src/RailEnterprise.Protocol/Message.cs
@@ -47,6 +47,8 @@ public enum MessageId : ushort
ClimbReport = 134,
/// Quadro delle finanze: conto economico per voce, rating spiegato, prestiti, bancarotta (F6).
FinanceReport = 135,
+ /// Quadro del rinnovo della flotta: ere, veicoli superati, successori, valori (F6).
+ FleetReport = 136,
}
/// Messaggio del protocollo: si serializza a mano, campo per campo.
diff --git a/src/RailEnterprise.Protocol/Messages/ClientMessages.cs b/src/RailEnterprise.Protocol/Messages/ClientMessages.cs
index f030345..c013070 100644
--- a/src/RailEnterprise.Protocol/Messages/ClientMessages.cs
+++ b/src/RailEnterprise.Protocol/Messages/ClientMessages.cs
@@ -243,6 +243,8 @@ public enum DetailKind : byte
Climb = 8,
/// Quadro delle finanze (risposta FinanceReport, F6; Id ignorato).
Finance = 9,
+ /// Quadro del rinnovo della flotta (risposta FleetReport, F6, ADR 0020; Id ignorato).
+ Fleet = 10,
}
/// Chiede al server un dettaglio che non viaggia con le entità (aggiunto in F4).
diff --git a/src/RailEnterprise.Protocol/Messages/CorporateMessages.cs b/src/RailEnterprise.Protocol/Messages/CorporateMessages.cs
index 597b51b..d404799 100644
--- a/src/RailEnterprise.Protocol/Messages/CorporateMessages.cs
+++ b/src/RailEnterprise.Protocol/Messages/CorporateMessages.cs
@@ -161,6 +161,8 @@ public sealed class IndustryCard : IMessage
public Money Cash { get; init; }
public float BreakdownChancePerYear { get; init; }
public List Stops { get; init; } = [];
+ /// Blocco 1 (F6, ADR 0021): scheda dell'immagine 07 per la compagnia della sessione; null se assente.
+ public IndustrySheetInfo? Sheet { get; init; }
public void Write(ref SpanWriter w)
{
@@ -169,7 +171,8 @@ public sealed class IndustryCard : IMessage
w.I32(MachineryRequired); w.Money(UpgradeCost); w.Money(Valuation); w.Money(Cash); w.F32(BreakdownChancePerYear);
w.Count(Stops.Count);
foreach (var s in Stops) s.Write(ref w);
- w.Flags(0);
+ w.Flags((byte)(Sheet is not null ? 1 : 0));
+ Sheet?.Write(ref w);
}
public static IndustryCard Read(ref SpanReader r)
@@ -181,9 +184,18 @@ public sealed class IndustryCard : IMessage
MachineryRequired = r.I32(), UpgradeCost = r.Money(), Valuation = r.Money(), Cash = r.Money(), BreakdownChancePerYear = r.F32(),
};
for (int n = r.Count(), i = 0; i < n; i++) m.Stops.Add(IndustryStopInfo.Read(ref r));
- r.Flags();
+ byte flags = r.Flags();
+ if ((flags & 1) != 0) m = m.With(IndustrySheetInfo.Read(ref r));
return m;
}
+
+ private IndustryCard With(IndustrySheetInfo sheet) => new()
+ {
+ Industry = Industry, Margin = Margin, ConditionMultiplier = ConditionMultiplier, WearPerDay = WearPerDay, RecoveryPerDay = RecoveryPerDay,
+ MaintenanceCostPerDay = MaintenanceCostPerDay, MaintenanceSpentYear = MaintenanceSpentYear, PartsTarget = PartsTarget, PartsPerMonth = PartsPerMonth,
+ PartsOrdered = PartsOrdered, MachineryRequired = MachineryRequired, UpgradeCost = UpgradeCost, Valuation = Valuation, Cash = Cash,
+ BreakdownChancePerYear = BreakdownChancePerYear, Stops = Stops, Sheet = sheet,
+ };
}
/// Primato della Cronaca finale (descrizione e valore già formattati in italiano).
diff --git a/src/RailEnterprise.Protocol/Messages/FleetMessages.cs b/src/RailEnterprise.Protocol/Messages/FleetMessages.cs
new file mode 100644
index 0000000..7a9044d
--- /dev/null
+++ b/src/RailEnterprise.Protocol/Messages/FleetMessages.cs
@@ -0,0 +1,161 @@
+using RailEnterprise.Core.Common;
+
+namespace RailEnterprise.Protocol.Messages;
+
+// Messaggi della fase F6: ere e obsolescenza dei veicoli (ADR 0020). Il quadro del rinnovo della flotta
+// arriva su richiesta (RequestDetail con DetailKind.Fleet) ed è calcolato dal server con FleetOutlook: il
+// client lo mostra com'è, senza calcolare età, valori, successori o modelli in produzione.
+
+///
+/// Veicolo della compagnia per il rinnovo: modello, treno o deposito, età e vita utile, condizione media
+/// (0–1), produzione, obsolescenza (anno da cui è superato, 0 se non ha successore), successore consigliato
+/// ("" se non superato o senza successore in produzione), valore di libro e di rivendita, moltiplicatore dei
+/// costi di manutenzione.
+///
+public sealed class FleetVehicleInfo
+{
+ public int Vehicle { get; init; }
+ public string Type { get; init; } = "";
+ public int Train { get; init; } = -1;
+ public int Depot { get; init; } = -1;
+ public float AgeYears { get; init; }
+ public int LifeYears { get; init; }
+ public float Condition { get; init; }
+ public bool InProduction { get; init; }
+ public bool Superseded { get; init; }
+ public int SupersededYear { get; init; }
+ public string Successor { get; init; } = "";
+ public Money BookValue { get; init; }
+ public Money Resale { get; init; }
+ public float MaintenanceFactor { get; init; }
+
+ public void Write(ref SpanWriter w)
+ {
+ w.I32(Vehicle); w.String(Type); w.I32(Train); w.I32(Depot); w.F32(AgeYears); w.I32(LifeYears); w.F32(Condition);
+ w.Bool(InProduction); w.Bool(Superseded); w.I32(SupersededYear); w.String(Successor);
+ w.Money(BookValue); w.Money(Resale); w.F32(MaintenanceFactor);
+ w.Flags(0);
+ }
+
+ public static FleetVehicleInfo Read(ref SpanReader r)
+ {
+ var m = new FleetVehicleInfo
+ {
+ Vehicle = r.I32(), Type = r.String(), Train = r.I32(), Depot = r.I32(), AgeYears = r.F32(), LifeYears = r.I32(), Condition = r.F32(),
+ InProduction = r.Bool(), Superseded = r.Bool(), SupersededYear = r.I32(), Successor = r.String(),
+ BookValue = r.Money(), Resale = r.Money(), MaintenanceFactor = r.F32(),
+ };
+ r.Flags();
+ return m;
+ }
+}
+
+///
+/// Modello in produzione per il catalogo d'acquisto: superato o no, anno da cui lo è (0 se non ha
+/// successore), successore consigliato, ultimo anno di produzione (0 se non previsto).
+///
+public sealed class VehicleModelInfo
+{
+ public string Type { get; init; } = "";
+ public bool Superseded { get; init; }
+ public int SupersededYear { get; init; }
+ public string Successor { get; init; } = "";
+ public int LastYear { get; init; }
+
+ public void Write(ref SpanWriter w)
+ {
+ w.String(Type); w.Bool(Superseded); w.I32(SupersededYear); w.String(Successor); w.I32(LastYear);
+ w.Flags(0);
+ }
+
+ public static VehicleModelInfo Read(ref SpanReader r)
+ {
+ var m = new VehicleModelInfo { Type = r.String(), Superseded = r.Bool(), SupersededYear = r.I32(), Successor = r.String(), LastYear = r.I32() };
+ r.Flags();
+ return m;
+ }
+}
+
+///
+/// Treno con veicoli superati da rinnovare: quanti, spesa netta (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).
+///
+public sealed class RenewalTrainInfo
+{
+ public int Train { get; init; }
+ public int Vehicles { get; init; }
+ public Money NetCost { get; init; }
+ public bool Affordable { get; init; }
+ public bool Booked { get; init; }
+
+ public void Write(ref SpanWriter w)
+ {
+ w.I32(Train); w.I32(Vehicles); w.Money(NetCost); w.Bool(Affordable); w.Bool(Booked);
+ w.Flags(0);
+ }
+
+ public static RenewalTrainInfo Read(ref SpanReader r)
+ {
+ var m = new RenewalTrainInfo { Train = r.I32(), Vehicles = r.I32(), NetCost = r.Money(), Affordable = r.Bool(), Booked = r.Bool() };
+ r.Flags();
+ return m;
+ }
+}
+
+///
+/// Quadro del rinnovo della flotta della compagnia della sessione (F6, ADR 0020): era in corso e prossima
+/// (con l'anno; "" e 0 all'ultima), veicoli con età, obsolescenza, successore e valori, catalogo dei
+/// modelli in produzione, treni da rinnovare con l'intervento «renewal».
+///
+public sealed class FleetReport : IMessage
+{
+ public MessageId Id => MessageId.FleetReport;
+ public long Day { get; init; }
+ public int Company { get; init; }
+ public int Year { get; init; }
+ public string Era { get; init; } = "";
+ public string NextEra { get; init; } = "";
+ public int NextEraYear { get; init; }
+ /// Id dell'intervento di rinnovo in maintenance.json (per ScheduleService).
+ public string RenewalIntervention { get; init; } = "";
+ public Money BookValueTotal { get; init; }
+ public List Vehicles { get; init; } = [];
+ public List Models { get; init; } = [];
+ public List Trains { get; init; } = [];
+
+ public void Write(ref SpanWriter w)
+ {
+ w.I64(Day); w.I32(Company); w.I32(Year); w.String(Era); w.String(NextEra); w.I32(NextEraYear); w.String(RenewalIntervention);
+ w.Money(BookValueTotal);
+ w.Count(Vehicles.Count);
+ foreach (var v in Vehicles) v.Write(ref w);
+ w.Count(Models.Count);
+ foreach (var m in Models) m.Write(ref w);
+ w.Count(Trains.Count);
+ foreach (var t in Trains) t.Write(ref w);
+ w.Flags(0);
+ }
+
+ public static FleetReport Read(ref SpanReader r)
+ {
+ long day = r.I64();
+ int company = r.I32(), year = r.I32();
+ string era = r.String(), next = r.String();
+ int nextYear = r.I32();
+ string renewal = r.String();
+ var book = r.Money();
+ var vehicles = new List();
+ for (int n = r.Count(), i = 0; i < n; i++) vehicles.Add(FleetVehicleInfo.Read(ref r));
+ var models = new List();
+ for (int n = r.Count(), i = 0; i < n; i++) models.Add(VehicleModelInfo.Read(ref r));
+ var trains = new List();
+ for (int n = r.Count(), i = 0; i < n; i++) trains.Add(RenewalTrainInfo.Read(ref r));
+ var m = new FleetReport
+ {
+ Day = day, Company = company, Year = year, Era = era, NextEra = next, NextEraYear = nextYear, RenewalIntervention = renewal,
+ BookValueTotal = book, Vehicles = vehicles, Models = models, Trains = trains,
+ };
+ r.Flags();
+ return m;
+ }
+}
diff --git a/src/RailEnterprise.Protocol/Messages/IndustryMessages.cs b/src/RailEnterprise.Protocol/Messages/IndustryMessages.cs
new file mode 100644
index 0000000..92f8d95
--- /dev/null
+++ b/src/RailEnterprise.Protocol/Messages/IndustryMessages.cs
@@ -0,0 +1,269 @@
+using RailEnterprise.Core.Common;
+
+namespace RailEnterprise.Protocol.Messages;
+
+// Blocchi della fase F6 (ADR 0021): scheda dell'industria dell'immagine di riferimento 07 (blocco 1 di
+// IndustryCard, calcolato dal server con IndustryOutlook) e stato del server per la schermata di
+// connessione dell'immagine 09 (blocco 1 di Welcome). Il client li mostra come arrivano.
+
+///
+/// Fornitore o cliente nella catena produttiva. Kind: 0 industria, 1 hub, 2 città (ChainPartnerKind);
+/// unità al mese, prezzo in centesimi per unità, linea della compagnia che collega (−1 nessuna), km in linea d'aria.
+///
+public sealed class ChainPartnerInfo
+{
+ public byte Kind { get; init; }
+ public int Target { get; init; }
+ public float MonthlyUnits { get; init; }
+ public double Price { get; init; }
+ public int Line { get; init; } = -1;
+ public float DistanceKm { get; init; }
+
+ public void Write(ref SpanWriter w)
+ {
+ w.U8(Kind); w.I32(Target); w.F32(MonthlyUnits); w.F64(Price); w.I32(Line); w.F32(DistanceKm);
+ w.Flags(0);
+ }
+
+ public static ChainPartnerInfo Read(ref SpanReader r)
+ {
+ var m = new ChainPartnerInfo { Kind = r.U8(), Target = r.I32(), MonthlyUnits = r.F32(), Price = r.F64(), Line = r.I32(), DistanceKm = r.F32() };
+ r.Flags();
+ return m;
+ }
+}
+
+///
+/// Input o output dell'industria: al mese a piena efficienza (fabbisogno o capacità) e al ritmo attuale,
+/// scorta, capienza, giorni (di scorta per un input, prima del magazzino pieno per un output; −1 senza
+/// ritmo), input limitante, fornitori o clienti.
+///
+public sealed class IndustryFlowInfo
+{
+ public int Good { get; init; }
+ public float FullMonth { get; init; }
+ public float CurrentMonth { get; init; }
+ public int Stock { get; init; }
+ public int Storage { get; init; }
+ public float Days { get; init; } = -1;
+ public bool Limiting { get; init; }
+ public List Partners { get; init; } = [];
+
+ public void Write(ref SpanWriter w)
+ {
+ w.I32(Good); w.F32(FullMonth); w.F32(CurrentMonth); w.I32(Stock); w.I32(Storage); w.F32(Days); w.Bool(Limiting);
+ w.Count(Partners.Count);
+ foreach (var p in Partners) p.Write(ref w);
+ w.Flags(0);
+ }
+
+ public static IndustryFlowInfo Read(ref SpanReader r)
+ {
+ var m = new IndustryFlowInfo { Good = r.I32(), FullMonth = r.F32(), CurrentMonth = r.F32(), Stock = r.I32(), Storage = r.I32(), Days = r.F32(), Limiting = r.Bool() };
+ for (int n = r.Count(), i = 0; i < n; i++) m.Partners.Add(ChainPartnerInfo.Read(ref r));
+ r.Flags();
+ return m;
+ }
+}
+
+/// Provenienza dei lavoratori o del personale: città, persone, copertura, linea del primo tratto (−1 a piedi), vettore, minuti.
+public sealed class WorkforceSourceInfo
+{
+ public int Town { get; init; }
+ public int Headcount { get; init; }
+ public float Coverage { get; init; }
+ public int Line { get; init; } = -1;
+ public int Carrier { get; init; } = -1;
+ public float Minutes { get; init; }
+ public bool Walking { get; init; }
+
+ public void Write(ref SpanWriter w)
+ {
+ w.I32(Town); w.I32(Headcount); w.F32(Coverage); w.I32(Line); w.I32(Carrier); w.F32(Minutes); w.Bool(Walking);
+ w.Flags(0);
+ }
+
+ public static WorkforceSourceInfo Read(ref SpanReader r)
+ {
+ var m = new WorkforceSourceInfo { Town = r.I32(), Headcount = r.I32(), Coverage = r.F32(), Line = r.I32(), Carrier = r.I32(), Minutes = r.F32(), Walking = r.Bool() };
+ r.Flags();
+ return m;
+ }
+}
+
+///
+/// Lavoratori o personale: posti, presenti, persone in sede (posti coperti da chi vive negli alloggi), copertura media, posti scoperti, motivo
+/// (UncoveredReason) e linea del motivo, viaggio medio in treno (−1 senza), provenienze elencate e in tutto.
+///
+public sealed class WorkforceInfo
+{
+ public int Jobs { get; init; }
+ public float Present { get; init; }
+ public float OnSite { get; init; }
+ public float Coverage { get; init; }
+ public int Missing { get; init; }
+ public byte Reason { get; init; }
+ public int ReasonLine { get; init; } = -1;
+ public float AverageMinutes { get; init; } = -1;
+ public int SourceCount { get; init; }
+ public List Sources { get; init; } = [];
+
+ public void Write(ref SpanWriter w)
+ {
+ w.I32(Jobs); w.F32(Present); w.F32(OnSite); w.F32(Coverage); w.I32(Missing); w.U8(Reason); w.I32(ReasonLine); w.F32(AverageMinutes); w.I32(SourceCount);
+ w.Count(Sources.Count);
+ foreach (var s in Sources) s.Write(ref w);
+ w.Flags(0);
+ }
+
+ public static WorkforceInfo Read(ref SpanReader r)
+ {
+ var m = new WorkforceInfo
+ {
+ Jobs = r.I32(), Present = r.F32(), OnSite = r.F32(), Coverage = r.F32(), Missing = r.I32(), Reason = r.U8(), ReasonLine = r.I32(),
+ AverageMinutes = r.F32(), SourceCount = r.I32(),
+ };
+ for (int n = r.Count(), i = 0; i < n; i++) m.Sources.Add(WorkforceSourceInfo.Read(ref r));
+ r.Flags();
+ return m;
+ }
+}
+
+///
+/// Blocco 1 di IndustryCard (F6, ADR 0021): scheda dell'immagine 07 calcolata da IndustryOutlook per la
+/// compagnia della sessione. Limit come IndustryLimit del Core (0 nessuno, 1 input, 2 lavoratori,
+/// 3 personale, 4 profitto, 5 impianti, 6 giacimento, 7 evento, 8 fermo, 9 dormiente).
+///
+public sealed class IndustrySheetInfo
+{
+ public byte Level { get; init; }
+ public byte MaxLevel { get; init; }
+ public float Efficiency { get; init; }
+ public byte Limit { get; init; }
+ public float CovInput { get; init; }
+ public float CovWorkers { get; init; }
+ public float CovStaff { get; init; }
+ public int CoverageWindowDays { get; init; }
+ public float ProfitFactor { get; init; }
+ public float Depletion { get; init; }
+ public float EventCapacity { get; init; }
+ /// Riserva residua del giacimento (0–1), −1 se non esauribile.
+ public float ReserveFraction { get; init; } = -1;
+ public int StorageDays { get; init; }
+ public List Inputs { get; init; } = [];
+ public List Outputs { get; init; } = [];
+ public WorkforceInfo Workers { get; init; } = new();
+ public WorkforceInfo Staff { get; init; } = new();
+ /// Prezzo di vendita del prodotto (centesimi): prezzo globale del giorno; −1 senza prodotti o con più prodotti.
+ public double SalePrice { get; init; } = -1;
+ public Money AnnualProfit { get; init; }
+ /// Crescita trimestrale: ultimo punteggio, componenti e punteggio del trimestre in corso, soglie, trimestri.
+ public float LastScore { get; init; }
+ public float Shipped { get; init; }
+ public float Coverage { get; init; }
+ public float Profit { get; init; }
+ public float Score { get; init; }
+ public float UpgradeThreshold { get; init; }
+ public float DowngradeThreshold { get; init; }
+ public byte UpgradeQuarters { get; init; }
+ public byte QuartersAbove { get; init; }
+ public int QuarterDay { get; init; }
+ public int QuarterDays { get; init; }
+ public bool Served { get; init; }
+ /// Stazioni (di qualunque compagnia) che servono l'industria; linea della compagnia della sessione (−1 nessuna).
+ public List ServingStations { get; init; } = [];
+ public int ServingLine { get; init; } = -1;
+ /// Acquisto: dei privati e attiva, sbloccato dal livello, livello che lo sblocca e avanzamento verso di esso.
+ public bool ForSale { get; init; }
+ public bool BuyUnlocked { get; init; }
+ public byte BuyTier { get; init; }
+ public float BuyProgress { get; init; }
+
+ public void Write(ref SpanWriter w)
+ {
+ w.U8(Level); w.U8(MaxLevel); w.F32(Efficiency); w.U8(Limit); w.F32(CovInput); w.F32(CovWorkers); w.F32(CovStaff); w.I32(CoverageWindowDays);
+ w.F32(ProfitFactor); w.F32(Depletion); w.F32(EventCapacity); w.F32(ReserveFraction); w.I32(StorageDays);
+ w.Count(Inputs.Count);
+ foreach (var f in Inputs) f.Write(ref w);
+ w.Count(Outputs.Count);
+ foreach (var f in Outputs) f.Write(ref w);
+ Workers.Write(ref w);
+ Staff.Write(ref w);
+ w.F64(SalePrice); w.Money(AnnualProfit);
+ w.F32(LastScore); w.F32(Shipped); w.F32(Coverage); w.F32(Profit); w.F32(Score); w.F32(UpgradeThreshold); w.F32(DowngradeThreshold);
+ w.U8(UpgradeQuarters); w.U8(QuartersAbove); w.I32(QuarterDay); w.I32(QuarterDays); w.Bool(Served);
+ w.Count(ServingStations.Count);
+ foreach (int s in ServingStations) w.I32(s);
+ w.I32(ServingLine); w.Bool(ForSale); w.Bool(BuyUnlocked); w.U8(BuyTier); w.F32(BuyProgress);
+ w.Flags(0);
+ }
+
+ public static IndustrySheetInfo Read(ref SpanReader r)
+ {
+ byte level = r.U8(), maxLevel = r.U8();
+ float efficiency = r.F32();
+ byte limit = r.U8();
+ float covInput = r.F32(), covWorkers = r.F32(), covStaff = r.F32();
+ int window = r.I32();
+ float pf = r.F32(), depletion = r.F32(), eventCapacity = r.F32(), reserve = r.F32();
+ int storageDays = r.I32();
+ var inputs = new List();
+ for (int n = r.Count(), i = 0; i < n; i++) inputs.Add(IndustryFlowInfo.Read(ref r));
+ var outputs = new List();
+ for (int n = r.Count(), i = 0; i < n; i++) outputs.Add(IndustryFlowInfo.Read(ref r));
+ var workers = WorkforceInfo.Read(ref r);
+ var staff = WorkforceInfo.Read(ref r);
+ double salePrice = r.F64();
+ var profit = r.Money();
+ float last = r.F32(), shipped = r.F32(), coverage = r.F32(), profitShare = r.F32(), score = r.F32(), up = r.F32(), down = r.F32();
+ byte upQuarters = r.U8(), above = r.U8();
+ int quarterDay = r.I32(), quarterDays = r.I32();
+ bool served = r.Bool();
+ var stations = new List();
+ for (int n = r.Count(), i = 0; i < n; i++) stations.Add(r.I32());
+ var m = new IndustrySheetInfo
+ {
+ Level = level, MaxLevel = maxLevel, Efficiency = efficiency, Limit = limit, CovInput = covInput, CovWorkers = covWorkers, CovStaff = covStaff,
+ CoverageWindowDays = window, ProfitFactor = pf, Depletion = depletion, EventCapacity = eventCapacity, ReserveFraction = reserve, StorageDays = storageDays,
+ Inputs = inputs, Outputs = outputs, Workers = workers, Staff = staff, SalePrice = salePrice, AnnualProfit = profit,
+ LastScore = last, Shipped = shipped, Coverage = coverage, Profit = profitShare, Score = score, UpgradeThreshold = up, DowngradeThreshold = down,
+ UpgradeQuarters = upQuarters, QuartersAbove = above, QuarterDay = quarterDay, QuarterDays = quarterDays, Served = served, ServingStations = stations,
+ ServingLine = r.I32(), ForSale = r.Bool(), BuyUnlocked = r.Bool(), BuyTier = r.U8(), BuyProgress = r.F32(),
+ };
+ r.Flags();
+ return m;
+ }
+}
+
+///
+/// Blocco 1 di Welcome (F6, ADR 0021): stato del server per la schermata di connessione (immagine 09):
+/// versione del gioco, sistema operativo, container, secondi di attività, durata del tick (ms), sessioni
+/// collegate e massime, server locale (figlio del client).
+///
+public sealed class ServerInfo
+{
+ public string Version { get; init; } = "";
+ public string Os { get; init; } = "";
+ public bool Container { get; init; }
+ public long UptimeSeconds { get; init; }
+ public float TickMs { get; init; }
+ public int Sessions { get; init; }
+ public int MaxSessions { get; init; }
+ public bool Local { get; init; }
+
+ public void Write(ref SpanWriter w)
+ {
+ w.String(Version); w.String(Os); w.Bool(Container); w.I64(UptimeSeconds); w.F32(TickMs); w.I32(Sessions); w.I32(MaxSessions); w.Bool(Local);
+ w.Flags(0);
+ }
+
+ public static ServerInfo Read(ref SpanReader r)
+ {
+ var m = new ServerInfo
+ {
+ Version = r.String(), Os = r.String(), Container = r.Bool(), UptimeSeconds = r.I64(), TickMs = r.F32(), Sessions = r.I32(), MaxSessions = r.I32(), Local = r.Bool(),
+ };
+ r.Flags();
+ return m;
+ }
+}
diff --git a/src/RailEnterprise.Protocol/Messages/MessageCodec.cs b/src/RailEnterprise.Protocol/Messages/MessageCodec.cs
index 72ddbea..f1b805c 100644
--- a/src/RailEnterprise.Protocol/Messages/MessageCodec.cs
+++ b/src/RailEnterprise.Protocol/Messages/MessageCodec.cs
@@ -34,6 +34,7 @@ public static class MessageCodec
MessageId.MarketReport => MarketReport.Read(ref r),
MessageId.ClimbReport => ClimbReport.Read(ref r),
MessageId.FinanceReport => FinanceReport.Read(ref r),
+ MessageId.FleetReport => FleetReport.Read(ref r),
MessageId.MarketTape => MarketTape.Read(ref r),
MessageId.CommandResult => CommandResultMessage.Read(ref r),
MessageId.Notification => Notification.Read(ref r),
diff --git a/src/RailEnterprise.Protocol/Messages/ServerMessages.cs b/src/RailEnterprise.Protocol/Messages/ServerMessages.cs
index b525302..f974522 100644
--- a/src/RailEnterprise.Protocol/Messages/ServerMessages.cs
+++ b/src/RailEnterprise.Protocol/Messages/ServerMessages.cs
@@ -13,6 +13,8 @@ public sealed class Welcome : IMessage
public required WorldSummary Summary { get; init; }
public ulong DataHash { get; init; }
public string Difficulty { get; init; } = "";
+ /// Blocco 1 (F6, ADR 0021): stato del server per la schermata di connessione; null se assente.
+ public ServerInfo? Server { get; init; }
public void Write(ref SpanWriter w)
{
@@ -20,14 +22,19 @@ public sealed class Welcome : IMessage
Summary.Write(ref w);
w.U64(DataHash);
w.String(Difficulty);
- w.Flags(0);
+ w.Flags((byte)(Server is not null ? 1 : 0));
+ Server?.Write(ref w);
}
public static Welcome Read(ref SpanReader r)
{
- var m = new Welcome { SessionId = r.U64(), Summary = WorldSummary.Read(ref r), DataHash = r.U64(), Difficulty = r.String() };
- r.Flags();
- return m;
+ ulong session = r.U64();
+ var summary = WorldSummary.Read(ref r);
+ ulong hash = r.U64();
+ string difficulty = r.String();
+ byte flags = r.Flags();
+ var server = (flags & 1) != 0 ? ServerInfo.Read(ref r) : null;
+ return new Welcome { SessionId = session, Summary = summary, DataHash = hash, Difficulty = difficulty, Server = server };
}
}
diff --git a/src/RailEnterprise.Server/GameHost.cs b/src/RailEnterprise.Server/GameHost.cs
index db976a1..7512770 100644
--- a/src/RailEnterprise.Server/GameHost.cs
+++ b/src/RailEnterprise.Server/GameHost.cs
@@ -198,6 +198,21 @@ public sealed class GameHost : IDisposable
Summary = Projection.Summary(_world, _world.Companies[s.Company.Value], _speed),
DataHash = _data.Hash,
Difficulty = _world.Difficulty.Id,
+ Server = ServerStatus(),
+ };
+
+ /// Stato del server per la schermata di connessione (blocco 1 del Welcome, ADR 0021).
+ private ServerInfo ServerStatus() => new()
+ {
+ Version = GameVersion,
+ Os = System.Runtime.InteropServices.RuntimeInformation.OSDescription,
+ // le immagini .NET ufficiali impostano DOTNET_RUNNING_IN_CONTAINER
+ Container = string.Equals(Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER"), "true", StringComparison.OrdinalIgnoreCase),
+ UptimeSeconds = NowMs / 1000,
+ TickMs = _config.TickMs,
+ Sessions = _sessions.Values.Count(x => x.Connected),
+ MaxSessions = _config.MaxSessions,
+ Local = _config.Local,
};
private void Handle(Session s, IMessage message)
@@ -269,11 +284,18 @@ public sealed class GameHost : IDisposable
}
}
- private static Notification Notice(string text) => new()
+ ///
+ /// Avviso del server a una sola sessione (Load o NewGame rifiutati): giorno −1, così il client lo
+ /// distingue dagli eventi del mondo, che hanno sempre il giorno della partita.
+ ///
+ public static Notification Notice(string text) => new()
{
- Event = new EventInfo { Severity = (byte)EventSeverity.Warning, Text = text },
+ Event = new EventInfo { Day = ServerNoticeDay, Severity = (byte)EventSeverity.Warning, Text = text },
};
+ /// Giorno degli avvisi del server (vedi ).
+ public const long ServerNoticeDay = -1;
+
public Protocol.Messages.SaveInfo SaveNow(string name)
{
var info = _saves.Save(_world, name);
@@ -653,7 +675,7 @@ public sealed class GameHost : IDisposable
break;
case DetailKind.Industry:
if (m.Target >= 0 && m.Target < w.Industries.Count && !w.Industries[m.Target].Closed)
- s.Send(Projection.IndustryCard(w, w.Industries[m.Target]));
+ s.Send(Projection.IndustryCard(w, w.Industries[m.Target], s.Company));
break;
case DetailKind.Chronicle:
s.Send(Projection.Chronicle(w));
@@ -667,6 +689,9 @@ public sealed class GameHost : IDisposable
case DetailKind.Finance:
if (s.Company.IsValid && s.Company.Value < w.Companies.Count) s.Send(Projection.Finance(w, s.Company));
break;
+ case DetailKind.Fleet:
+ if (s.Company.IsValid && s.Company.Value < w.Companies.Count) s.Send(Projection.FleetRenewal(w, s.Company));
+ break;
}
}
diff --git a/src/RailEnterprise.Server/Projection.cs b/src/RailEnterprise.Server/Projection.cs
index ecf8a20..bf9a6a3 100644
--- a/src/RailEnterprise.Server/Projection.cs
+++ b/src/RailEnterprise.Server/Projection.cs
@@ -485,8 +485,8 @@ public static class Projection
};
}
- /// Scheda del proprietario di un'industria (sezione 11).
- public static IndustryCard IndustryCard(World w, Industry ind)
+ /// Scheda del proprietario di un'industria (sezione 11) con la scheda dell'immagine 07 per la compagnia (blocco 1, ADR 0021).
+ public static IndustryCard IndustryCard(World w, Industry ind, CompanyId company)
{
var m = w.Data.Balance.IndustryMaintenance;
var budget = m.For(ind.Budget);
@@ -502,6 +502,45 @@ public static class Projection
PartsOrdered = ind.PartsOrdered, MachineryRequired = IndustryMath.MachineryRequired(ind, m), UpgradeCost = IndustryMaintenanceSystem.UpgradeCost(ind),
Valuation = IndustryMath.Valuation(w, ind), Cash = ind.Cash, BreakdownChancePerYear = (float)perYear,
Stops = ind.StopHistory.Select(h => new IndustryStopInfo { Day = h.Day, Days = h.Days, Kind = (byte)h.Kind }).ToList(),
+ Sheet = IndustrySheet(IndustryOutlook.Build(w, ind, company)),
+ };
+ }
+
+ /// Scheda dell'industria dell'immagine 07 (IndustryOutlook, ADR 0021).
+ public static IndustrySheetInfo IndustrySheet(IndustryOutlookReport r)
+ {
+ static IndustryFlowInfo Flow(IndustryFlow f) => new()
+ {
+ Good = f.Good, FullMonth = (float)f.FullMonth, CurrentMonth = (float)f.CurrentMonth, Stock = f.Stock, Storage = f.Storage, Days = (float)f.Days,
+ Limiting = f.Limiting,
+ Partners = f.Partners.Select(p => new ChainPartnerInfo
+ {
+ Kind = (byte)p.Kind, Target = p.Target, MonthlyUnits = (float)p.MonthlyUnits, Price = p.Price, Line = p.Line.Value, DistanceKm = (float)p.DistanceKm,
+ }).ToList(),
+ };
+ static WorkforceInfo Work(WorkforceOutlook o) => new()
+ {
+ Jobs = o.Jobs, Present = (float)o.Present, OnSite = (float)o.OnSite, Coverage = (float)o.Coverage, Missing = o.Missing, Reason = (byte)o.Reason,
+ ReasonLine = o.ReasonLine.Value, AverageMinutes = (float)o.AverageMinutes, SourceCount = o.SourceCount,
+ Sources = o.Sources.Select(x => new WorkforceSourceInfo
+ {
+ Town = x.Town.Value, Headcount = x.Headcount, Coverage = (float)x.Coverage, Line = x.Line.Value, Carrier = x.Carrier.Value, Minutes = (float)x.Minutes, Walking = x.Walking,
+ }).ToList(),
+ };
+ var g = r.Growth;
+ return new IndustrySheetInfo
+ {
+ Level = (byte)Math.Clamp(r.Level, 0, 255), MaxLevel = (byte)Math.Clamp(r.MaxLevel, 0, 255), Efficiency = (float)r.Efficiency, Limit = (byte)r.Limit,
+ CovInput = (float)r.CovInput, CovWorkers = (float)r.CovWorkers, CovStaff = (float)r.CovStaff, CoverageWindowDays = r.CoverageWindowDays,
+ ProfitFactor = (float)r.ProfitFactor, Depletion = (float)r.Depletion, EventCapacity = (float)r.EventCapacity, ReserveFraction = (float)r.ReserveFraction,
+ StorageDays = r.StorageDays, Inputs = r.Inputs.Select(Flow).ToList(), Outputs = r.Outputs.Select(Flow).ToList(),
+ Workers = Work(r.Workers), Staff = Work(r.Staff), SalePrice = r.SalePrice, AnnualProfit = r.AnnualProfit,
+ LastScore = (float)g.LastScore, Shipped = (float)g.Current.Shipped, Coverage = (float)g.Current.Coverage, Profit = (float)g.Current.Profit,
+ Score = (float)g.Current.Score, UpgradeThreshold = (float)g.UpgradeThreshold, DowngradeThreshold = (float)g.DowngradeThreshold,
+ UpgradeQuarters = (byte)Math.Clamp(g.UpgradeQuarters, 0, 255), QuartersAbove = (byte)Math.Clamp(g.QuartersAbove, 0, 255),
+ QuarterDay = g.QuarterDay, QuarterDays = g.QuarterDays, Served = g.Served,
+ ServingStations = r.ServingStations.Select(s => s.Value).ToList(), ServingLine = r.ServingLine.Value,
+ ForSale = r.ForSale, BuyUnlocked = r.BuyUnlocked, BuyTier = (byte)Math.Clamp(r.BuyTier, 0, 255), BuyProgress = (float)r.BuyProgress,
};
}
@@ -625,6 +664,32 @@ public static class Projection
};
}
+ /// Quadro del rinnovo della flotta per la compagnia della sessione (FleetOutlook, ADR 0020).
+ public static FleetReport FleetRenewal(World w, CompanyId company)
+ {
+ var report = FleetOutlook.Build(w, company);
+ var interventions = w.Data.Maintenance.Interventions;
+ return new FleetReport
+ {
+ Day = report.Day, Company = report.Company.Value, Year = report.Year, Era = report.Era.Id,
+ NextEra = report.NextEra?.Id ?? "", NextEraYear = report.NextEra?.From ?? 0,
+ RenewalIntervention = interventions.First(i => i.Effect == InterventionEffect.Renew).Id,
+ BookValueTotal = report.BookValueTotal,
+ Vehicles = report.Vehicles.Select(v => new FleetVehicleInfo
+ {
+ Vehicle = v.Id.Value, Type = v.Def.Id, Train = v.Train.Value, Depot = v.Depot.Value, AgeYears = (float)v.AgeYears,
+ LifeYears = v.Def.LifeYears, Condition = (float)v.Condition, InProduction = v.InProduction, Superseded = v.Superseded,
+ SupersededYear = v.SupersededYear ?? 0, Successor = v.Successor?.Id ?? "", BookValue = v.BookValue, Resale = v.ResaleValue,
+ MaintenanceFactor = (float)v.MaintenanceFactor,
+ }).ToList(),
+ Models = report.Models.Select(m => new VehicleModelInfo
+ {
+ Type = m.Def.Id, Superseded = m.Superseded, SupersededYear = m.SupersededYear ?? 0, Successor = m.Successor?.Id ?? "", LastYear = m.LastYear ?? 0,
+ }).ToList(),
+ Trains = report.Trains.Select(t => new RenewalTrainInfo { Train = t.Train.Value, Vehicles = t.Vehicles, NetCost = t.NetCost, Affordable = t.Affordable, Booked = t.Booked }).ToList(),
+ };
+ }
+
/// Evento del mondo in corso → record del protocollo (ADR 0017).
public static WorldEventInfo WorldEvent(ActiveWorldEvent e) => new()
{
diff --git a/tests/RailEnterprise.Tests/Client/TutorialTests.cs b/tests/RailEnterprise.Tests/Client/TutorialTests.cs
index dd4bfd2..2ea316b 100644
--- a/tests/RailEnterprise.Tests/Client/TutorialTests.cs
+++ b/tests/RailEnterprise.Tests/Client/TutorialTests.cs
@@ -2,6 +2,7 @@ using System.Text;
using System.Text.RegularExpressions;
using RailEnterprise.Client.Tutorial;
using RailEnterprise.Core.Commands;
+using RailEnterprise.Protocol.Messages;
using RailEnterprise.Tests.Harness;
namespace RailEnterprise.Tests.Client;
@@ -66,7 +67,8 @@ public static class TutorialTests
var rows = ReadCsv(Path.Combine(ClientDir(), "assets", "i18n", "strings.csv"));
var keys = new List();
foreach (var s in RealScript().Steps) keys.AddRange([s.Title, s.Text]);
- keys.AddRange(["Avanti", "Salta passo", "Chiudi tutorial", "Tutorial", "Passo {0} di {1}", "Fine", "Fatto", "Mostra il tutorial"]);
+ keys.AddRange(["Avanti", "Salta passo", "Chiudi tutorial", "Tutorial", "Passo {0} di {1}", "Fine", "Fatto", "Mostra il tutorial",
+ "Tutorial non disponibile: {0}", "Nuova partita locale di prova con il tutorial dal primo passo: la tua partita locale resta com'è"]);
foreach (string key in keys)
{
Assert.True(rows.TryGetValue(key, out var row), $"manca in strings.csv: «{key}»");
@@ -181,12 +183,67 @@ public static class TutorialTests
Assert.Equal(TutorialLaunch.StartFresh, TutorialMachine.Plan(requested: true, restart: false, saved: null));
Assert.Equal(TutorialLaunch.Hidden, TutorialMachine.Plan(requested: false, restart: false, saved: null));
Assert.Equal(TutorialLaunch.Resume, TutorialMachine.Plan(requested: false, restart: false, saved: active));
- Assert.Equal(TutorialLaunch.Hidden, TutorialMachine.Plan(requested: true, restart: false, saved: closed));
+ var completed = new TutorialProgress(null, TutorialStatus.Completed);
+ Assert.Equal(TutorialLaunch.Hidden, TutorialMachine.Plan(requested: false, restart: false, saved: closed), "chiuso e non richiesto: nascosto");
+ Assert.Equal(TutorialLaunch.Hidden, TutorialMachine.Plan(requested: false, restart: false, saved: completed));
+ // la casella spuntata è una richiesta esplicita: vale anche su una voce chiusa (partita nuova con lo stesso seme)
+ Assert.Equal(TutorialLaunch.StartFresh, TutorialMachine.Plan(requested: true, restart: false, saved: closed));
+ Assert.Equal(TutorialLaunch.StartFresh, TutorialMachine.Plan(requested: true, restart: false, saved: completed));
+ Assert.Equal(TutorialLaunch.Resume, TutorialMachine.Plan(requested: true, restart: false, saved: active), "in corso: si riprende");
Assert.Equal(TutorialLaunch.StartFresh, TutorialMachine.Plan(requested: false, restart: true, saved: closed));
+ Assert.Equal(TutorialLaunch.StartFresh, TutorialMachine.Plan(requested: false, restart: true, saved: active));
+ }
- string key = TutorialProgress.GameKey(3, 0xABCDEFUL, 1);
- Assert.Equal("g_0000000000000003_0000000000abcdef_1", key);
- Assert.True(key.All(c => char.IsAsciiLetterOrDigit(c) || c == '_'), "chiave adatta a ConfigFile");
+ [Test(Description = "La chiave della partita non cambia giocando (impronta del terreno, data) e separa le origini")]
+ public static void GameKeyIsStableDuringTheGame()
+ {
+ var start = new WorldSummary { Seed = 1, SizeKm = 128, StartYear = 1850, RegionId = "pianura-padana", CompanyId = 0, TerrainHash = 0x1111, Tick = 0, Date = "1850-01-01" };
+ // un anno dopo: le città si sono allargate (impronta del terreno nuova) e la data è avanzata
+ var later = new WorldSummary { Seed = 1, SizeKm = 128, StartYear = 1850, RegionId = "pianura-padana", CompanyId = 0, TerrainHash = 0x2222, Tick = 2_000_000, Date = "1851-03-01" };
+ string key = TutorialProgress.GameKey("local", start);
+ Assert.Equal(key, TutorialProgress.GameKey("local", later), "stessa partita dopo un anno di gioco: stessa voce");
+ Assert.True(key.All(c => char.IsAsciiLetterOrDigit(c) || c == '_'), $"chiave adatta a ConfigFile: {key}");
+ Assert.Equal(key, key.ToLowerInvariant());
+
+ Assert.NotEqual(key, TutorialProgress.GameKey("tutorial", start), "la partita di prova del tutorial ha la sua voce");
+ Assert.NotEqual(key, TutorialProgress.GameKey("remote_192.168.1.5_7400", start), "un server remoto ha la sua voce");
+ Assert.NotEqual(key, TutorialProgress.GameKey("local", new WorldSummary { Seed = 2, SizeKm = 128, StartYear = 1850, RegionId = "pianura-padana" }));
+ Assert.NotEqual(key, TutorialProgress.GameKey("local", new WorldSummary { Seed = 1, SizeKm = 128, StartYear = 1850, RegionId = "pianura-padana", CompanyId = 2 }));
+ string remote = TutorialProgress.GameKey("remote_192.168.1.5_7400", start);
+ Assert.True(remote.All(c => char.IsAsciiLetterOrDigit(c) || c == '_'), $"chiave adatta a ConfigFile: {remote}");
+ }
+
+ [Test(Description = "Un comando riuscito subito dopo il completamento di un passo conta per il passo nuovo")]
+ public static void BaselineIsTakenWhenThePreviousStepCompletes()
+ {
+ var build = new TutorialCondition { Counter = "cmd:BuildTrack", Increase = 1 };
+ var script = new TutorialScript
+ {
+ Steps =
+ [
+ Step("profile", new TutorialCondition { Counter = "trackPreviews", Increase = 1 }),
+ Step("build", build),
+ Step("link", build),
+ Step("end"),
+ ],
+ };
+ var m = new TutorialMachine(script);
+ Assert.False(m.Update(Facts(counters: ("trackPreviews", 0))));
+ Assert.True(m.Update(Facts(counters: ("trackPreviews", 1))));
+ Assert.Equal("build", m.Current!.Id);
+ // il binario costruito arriva prima del prossimo aggiornamento: conta per «build»
+ Assert.True(m.Update(Facts(counters: [("trackPreviews", 1), ("cmd:BuildTrack", 1)])), "il primo binario completa «build»");
+ Assert.Equal("link", m.Current!.Id);
+ // gli stessi fatti non completano anche «link»
+ Assert.False(m.Update(Facts(counters: [("trackPreviews", 1), ("cmd:BuildTrack", 1)])));
+ Assert.True(m.Update(Facts(counters: [("trackPreviews", 1), ("cmd:BuildTrack", 2)])), "il secondo binario completa «link»");
+ Assert.Equal("end", m.Current!.Id);
+
+ // dopo Salta passo la base resta il primo aggiornamento del passo
+ m.Restart();
+ m.Skip();
+ Assert.False(m.Update(Facts(counters: ("cmd:BuildTrack", 5))));
+ Assert.True(m.Update(Facts(counters: ("cmd:BuildTrack", 6))));
}
[Test(Description = "La validazione rifiuta copioni sbagliati e il parser i campi sconosciuti")]
@@ -204,6 +261,11 @@ public static class TutorialTests
Assert.True(Errors(Step("a", new TutorialCondition { All = [] })).Exists(e => e.Contains("vuoto")));
Assert.True(Errors(Step("a", highlight: "toolbar:cucina")).Exists(e => e.Contains("evidenziare sconosciuto")));
Assert.True(Errors().Exists(e => e.Contains("nessun passo")));
+ // valori null ammessi dal JSON: errori chiari, nessuna eccezione
+ Assert.True(TutorialScript.Parse("""{ "steps": null }""").Validate().Exists(e => e.Contains("elenco dei passi mancante")));
+ Assert.True(TutorialScript.Parse("""{ "steps": [ null ] }""").Validate().Exists(e => e.Contains("passo n. 1 nullo")));
+ Assert.True(TutorialScript.Parse("""{ "steps": [ { "id": "a", "title": "t", "text": "x", "done": { "all": [ null ] } } ] }""").Validate().Exists(e => e.Contains("condizione nulla")));
+ Assert.True(TutorialScript.Parse("""{ "steps": [ { "id": "a", "title": "t", "text": "x", "done": { "any": [ null ] } } ] }""").Validate().Exists(e => e.Contains("condizione nulla")));
Assert.Equal(0, Errors(Step("a", new TutorialCondition { Counter = TutorialFacts.CommandCounter(CommandType.BuildStation), Increase = 1 }, "toolbar:station")).Count);
Assert.Throws(() => TutorialScript.Parse("""{ "steps": [ { "id": "a", "title": "t", "text": "x", "colore": "rosso" } ] }"""));
diff --git a/tests/RailEnterprise.Tests/Economy/ErasTests.cs b/tests/RailEnterprise.Tests/Economy/ErasTests.cs
new file mode 100644
index 0000000..6d82996
--- /dev/null
+++ b/tests/RailEnterprise.Tests/Economy/ErasTests.cs
@@ -0,0 +1,511 @@
+using System.Text.Json.Nodes;
+using RailEnterprise.Core.Commands;
+using RailEnterprise.Core.Common;
+using RailEnterprise.Core.Data;
+using RailEnterprise.Core.Economy;
+using RailEnterprise.Core.Persistence;
+using RailEnterprise.Core.Rail;
+using RailEnterprise.Core.Simulation;
+using RailEnterprise.Core.Simulation.Ai;
+using RailEnterprise.Core.Simulation.Scenarios;
+using RailEnterprise.Core.Simulation.Systems;
+using RailEnterprise.Protocol;
+using RailEnterprise.Protocol.Messages;
+using RailEnterprise.Server;
+using RailEnterprise.Tests.Harness;
+using RailEnterprise.Tests.Rail;
+using RailEnterprise.Tests.Scenarios;
+
+namespace RailEnterprise.Tests.Economy;
+
+/// Ere, novità tecnologiche, obsolescenza e rinnovo della flotta (F6, ADR 0020).
+public static class ErasTests
+{
+ private static readonly Vec2 DepotPos = RailFixture.K(2.6, 4.4);
+
+ /// Valdoria che comincia nell'anno indicato, con un deposito e l'id del deposito.
+ private static (RailFixture F, int Depot) ValdoriaIn(int year, GameData? data = null)
+ {
+ var json = JsonNode.Parse(File.ReadAllText(ScenarioHelper.PathOf("valdoria")))!;
+ json["startYear"] = year;
+ var s = ScenarioLoader.Load(data ?? TestData.Data, json.ToJsonString());
+ var f = new RailFixture(s.World, s);
+ int depot = f.Ok(new BuildDepotCommand(DepotPos, "small", "Deposito di prova"));
+ return (f, depot);
+ }
+
+ private static int CountTechnology(IEnumerable events) => events.Count(e => e.Kind == EventKind.Technology);
+
+ private static void AssertInvariants(World w, string when)
+ {
+ Assert.Equal(0L, w.MoneyBalanceSum(), $"denaro {when}");
+ for (int g = 0; g < w.Data.GoodCount; g++)
+ Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"merce {w.Data.Goods[g].Id} {when}");
+ }
+
+ [Test(Description = "Sblocchi per anno letti dai dati: era in corso, novità, fuori produzione, superati e testo della notizia")]
+ public static void UnlocksFollowTheYear()
+ {
+ var d = TestData.Data;
+ Assert.Equal("steam", EraSystem.CurrentEra(d, 1924).Id);
+ Assert.Equal("diesel", EraSystem.CurrentEra(d, 1925).Id);
+ Assert.Equal("electric", EraSystem.NextEra(d, 1925)!.Id);
+ Assert.True(EraSystem.NextEra(d, 1990) is null, "dopo l'ultima era non ce n'è un'altra");
+
+ var u1878 = EraSystem.Unlocks(d, 1878);
+ Assert.True(u1878.Any(u => u.Kind == TechKind.Vehicle && u.Id == "loco_steam_1878"), "1878: Vittoria 2-8-0");
+ Assert.Equal("loco_steam_1850", EraSystem.NewlySuperseded(d, 1878).Single().Id);
+ var u1925 = EraSystem.Unlocks(d, 1925);
+ Assert.True(u1925.Any(u => u.Kind == TechKind.Traction && u.Id == "diesel"), "1925: trazione diesel");
+ Assert.True(u1925.Any(u => u.Kind == TechKind.Vehicle && u.Id == "loco_diesel_1925"), "1925: Aquila D1");
+ var u1950 = EraSystem.Unlocks(d, 1950);
+ Assert.True(u1950.Any(u => u.Kind == TechKind.Electrification), "1950: elettrificazione");
+ Assert.True(u1950.Any(u => u.Kind == TechKind.BridgeType && u.Id == "concrete"), "1950: ponti in cemento armato");
+ Assert.True(u1950.Any(u => u.Kind == TechKind.TunnelLimit), "1950: gallerie più lunghe");
+ Assert.Equal("loco_steam_1850", EraSystem.Retired(d, 1906).Single().Id);
+
+ string text = EraSystem.NewsText(d, 1925)!;
+ Assert.True(text.StartsWith("Inizia l'Era diesel (1925)", StringComparison.Ordinal), text);
+ Assert.True(text.Contains("Aquila D1", StringComparison.Ordinal) && text.Contains("Freccia 4-6-2 (successore Aquila D1)", StringComparison.Ordinal), text);
+ Assert.True(EraSystem.NewsText(d, 1878)!.StartsWith("Novità del 1878", StringComparison.Ordinal));
+ Assert.True(EraSystem.NewsText(d, 1906)!.Contains("fuori produzione: Ardita 2-6-0", StringComparison.Ordinal));
+ Assert.True(EraSystem.NewsText(d, 1851) is null, "un anno senza novità non dà notizie");
+
+ // nessun elenco scritto a mano: un modello aggiunto ai dati entra nella notizia del suo anno
+ var files = MemoryDataSource.Snapshot(TestData.Source);
+ var vehicles = JsonNode.Parse(files["vehicles.json"])!;
+ var copy = JsonNode.Parse(vehicles["vehicles"]![0]!.ToJsonString())!;
+ copy["id"] = "loco_steam_1851";
+ copy["name_it"] = "Prova 1851";
+ copy["eraFrom"] = 1851;
+ copy.AsObject().Remove("successor");
+ vehicles["vehicles"]!.AsArray().Add(copy);
+ files["vehicles.json"] = vehicles.ToJsonString();
+ var altered = GameData.Load(new MemoryDataSource(files));
+ Assert.True(EraSystem.NewsText(altered, 1851)!.Contains("locomotiva Prova 1851", StringComparison.Ordinal));
+ }
+
+ [Test(Description = "Il validatore rifiuta successori sconosciuti, di un'altra categoria o introdotti prima")]
+ public static void SuccessorValidation()
+ {
+ static string? Error(Action change)
+ {
+ var files = MemoryDataSource.Snapshot(TestData.Source);
+ var vehicles = JsonNode.Parse(files["vehicles.json"])!;
+ change(vehicles["vehicles"]!);
+ files["vehicles.json"] = vehicles.ToJsonString();
+ try
+ {
+ GameData.Load(new MemoryDataSource(files));
+ return null;
+ }
+ catch (DataValidationException ex)
+ {
+ return ex.Message;
+ }
+ }
+ JsonNode Find(JsonNode list, string id) => list.AsArray().First(v => (string)v!["id"]! == id)!;
+ Assert.True(Error(l => Find(l, "loco_steam_1850")["successor"] = "loco_inesistente") is { } e1 && e1.Contains("sconosciuto", StringComparison.Ordinal));
+ Assert.True(Error(l => Find(l, "loco_steam_1850")["successor"] = "wagon_hopper") is { } e2 && e2.Contains("categoria", StringComparison.Ordinal));
+ Assert.True(Error(l => Find(l, "loco_steam_1878")["successor"] = "loco_steam_1850") is { } e3 && e3.Contains("dopo", StringComparison.Ordinal));
+ Assert.True(Error(l => Find(l, "loco_diesel_1925")["successor"] = "loco_electric_1950") is { } e4 && e4.Contains("elettrificata", StringComparison.Ordinal));
+ }
+
+ [Test(Description = "La notizia del passaggio d'anno esce una volta sola, anche salvando prima o dopo, e la Cronaca la registra")]
+ public static void EraNewsOnceAcrossSaves()
+ {
+ var (f, _) = ValdoriaIn(1877);
+ var w = f.W;
+ int dpy = w.Calendar.DaysPerYear;
+ w.RunTicks((long)dpy * w.Calendar.TicksPerDay - 1 - w.Clock.Tick);
+ Assert.Equal(1877, w.Clock.Year);
+ Assert.Equal(0, CountTechnology(w.Events.Drain()), "nessuna notizia nel 1877");
+ var before = SaveFile.Load(TestData.Data, SaveFile.Save(w, "test"));
+ w.RunDays(2);
+ before.RunDays(2);
+ var news = w.Events.Drain().Where(e => e.Kind == EventKind.Technology).ToList();
+ Assert.Equal(1, news.Count, "una notizia nel tick del 1° gennaio");
+ Assert.Equal(1, CountTechnology(before.Events.Drain()), "anche dal salvataggio fatto il 31 dicembre");
+ Assert.True(news[0].Text.Contains("Vittoria 2-8-0", StringComparison.Ordinal), news[0].Text);
+ Assert.False(news[0].Company.IsValid, "la notizia è per tutte le compagnie");
+ Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(before), "stesso stato passando dal salvataggio");
+
+ var after = SaveFile.Load(TestData.Data, SaveFile.Save(w, "test"));
+ after.RunDays(60);
+ Assert.Equal(0, CountTechnology(after.Events.Drain()), "dopo il caricamento la notizia non si ripete");
+ Assert.Equal(1, after.Player.Milestones.Count(m => m.Text.StartsWith("novità del 1878", StringComparison.Ordinal)), "fatto saliente nella Cronaca");
+ Assert.True(ChronicleReport.Build(after).Highlights.Any(h => h.Contains("Vittoria 2-8-0", StringComparison.Ordinal)), "nella Cronaca");
+ }
+
+ [Test(Description = "Un modello fuori produzione non si compra né compare nel catalogo; i superati sono segnati con il successore")]
+ public static void OutOfProductionIsNotBuyable()
+ {
+ var (f, depot) = ValdoriaIn(1906);
+ var r = f.Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1));
+ Assert.Equal(CommandError.EraLocked, r.Error, r.Message);
+ Assert.True(f.Do(new BuyVehicleCommand("loco_steam_1878", new DepotId(depot), 1)).Ok, "il modello del 1878 è ancora in produzione");
+ var report = FleetOutlook.Build(f.W, f.Me);
+ Assert.False(report.Models.Any(m => m.Def.Id == "loco_steam_1850"), "il catalogo nasconde i fuori produzione");
+ var m1878 = report.Models.Single(m => m.Def.Id == "loco_steam_1878");
+ Assert.True(m1878.Superseded, "superato dalla Freccia del 1902");
+ Assert.Equal("loco_steam_1902", m1878.Successor!.Id);
+ Assert.False(report.Models.Single(m => m.Def.Id == "wagon_hopper").Superseded, "un carro senza successore non è superato");
+ Assert.Equal("loco_steam_1902", Obsolescence.Recommended(f.W.Data.Vehicle("loco_steam_1850"), 1906)!.Id,
+ "il successore consigliato salta i modelli fuori produzione della catena");
+ }
+
+ [Test(Description = "Curva del valore: gradino all'arrivo del successore, poi ammortamento più rapido; rivendita = libro × condizione")]
+ public static void ValueCurveOfSupersededModels()
+ {
+ var d = TestData.Data;
+ var (f, depot) = ValdoriaIn(1876);
+ var w = f.W;
+ var cal = w.Calendar;
+ var o = d.Obsolescence;
+ double floor = d.Balance.Finance.BookValueFloor;
+ var loco = d.Vehicle("loco_steam_1850");
+ var wagon = d.Vehicle("wagon_hopper");
+ long obsolete = Obsolescence.SupersededDay(cal, loco);
+ Assert.Equal((long)(1878 - 1876) * cal.DaysPerYear, obsolete);
+
+ double before = Obsolescence.Residual(d, cal, loco, 0, obsolete - 1);
+ double at = Obsolescence.Residual(d, cal, loco, 0, obsolete);
+ Assert.Approx(1 - (obsolete - 1) / (double)cal.DaysPerYear / loco.LifeYears, before, 1e-12, "prima: lineare sulla vita");
+ Assert.Approx((1 - o.ImmediateValueLoss) * (1 - 2.0 / loco.LifeYears), at, 1e-12, "gradino di immediateValueLoss");
+ double oneYear = Obsolescence.Residual(d, cal, loco, 0, obsolete + cal.DaysPerYear);
+ Assert.Approx((1 - o.ImmediateValueLoss) * (1 - (3 + (o.DepreciationSpeed - 1)) / loco.LifeYears), oneYear, 1e-12, "ammortamento più rapido");
+ // pendenza da superato = depreciationSpeed volte quella normale (scalata dal gradino)
+ double normalSlope = 1.0 / loco.LifeYears;
+ Assert.Approx((1 - o.ImmediateValueLoss) * o.DepreciationSpeed * normalSlope, at - oneYear, 1e-12);
+ // un carro senza successore segue la curva di sempre
+ Assert.Approx(1 - 3.0 / wagon.LifeYears, Obsolescence.Residual(d, cal, wagon, 0, obsolete + cal.DaysPerYear), 1e-12);
+ // monotona e mai sotto il minimo, anche per un veicolo comprato dopo l'arrivo del successore
+ foreach (long bought in new[] { 0L, obsolete + 100 })
+ {
+ double last = double.MaxValue;
+ for (long day = bought; day < bought + 40L * cal.DaysPerYear; day += 7)
+ {
+ double r = Obsolescence.Residual(d, cal, loco, bought, day);
+ Assert.True(r <= last + 1e-12 && r >= floor - 1e-12, $"residuo {r} al giorno {day}");
+ last = r;
+ }
+ }
+ Assert.Approx(1 - o.ImmediateValueLoss, Obsolescence.Residual(d, cal, loco, obsolete + 100, obsolete + 100), 1e-12, "nuovo ma già superato");
+
+ // valore di libro, rivendita e SellVehicle sullo stesso residuo
+ int id = f.Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1)).Created[0];
+ w.RunDays((int)(obsolete - w.Clock.Day) + 30);
+ var v = w.Vehicles[id];
+ v.Components[0] = 50;
+ double residual = Obsolescence.Residual(w, v);
+ Assert.Equal((long)(loco.Price * residual), Obsolescence.BookValueCents(w, v));
+ var resale = Obsolescence.ResaleValue(w, v);
+ Assert.Equal(new Money(loco.Price) * (residual * Obsolescence.AverageCondition(v)), resale);
+ var cash = w.Player.Cash;
+ Assert.True(f.Do(new SellVehicleCommand(new VehicleId(id))).Ok);
+ Assert.Equal(cash + resale, w.Player.Cash, "SellVehicle incassa la rivendita");
+ AssertInvariants(w, "dopo la vendita");
+ }
+
+ [Test(Description = "La manutenzione di un modello superato costa maintenanceCostFactor volte; gli altri veicoli non cambiano")]
+ public static void SupersededMaintenanceCostsMore()
+ {
+ Money ServiceCost(int year)
+ {
+ var (f, depot) = ValdoriaIn(year);
+ int train = f.Train(depot, "Prova", ("loco_steam_1850", 1), ("wagon_hopper", 3));
+ var w = f.W;
+ var t = w.Trains[train];
+ var def = w.Data.Maintenance.Interventions[w.Data.Maintenance.InterventionIndex("service")];
+ return Fleet.CostOf(w, t, def, Fleet.PolicyOf(w, t));
+ }
+ var d = TestData.Data;
+ var service = d.Maintenance.Interventions[d.Maintenance.InterventionIndex("service")];
+ long loco = d.Vehicle("loco_steam_1850").Price, wagon = d.Vehicle("wagon_hopper").Price;
+ Assert.Equal(Money.FromCentsRounded((loco + 3.0 * wagon) * service.CostShare), ServiceCost(1877), "prima del successore");
+ Assert.Equal(Money.FromCentsRounded((loco * d.Obsolescence.MaintenanceCostFactor + 3.0 * wagon) * service.CostShare), ServiceCost(1878),
+ "superato: solo la locomotiva costa di più");
+ }
+
+ [Test(Description = "Valore di libro dei veicoli: una sola fonte per patrimonio, quadro della flotta e stato patrimoniale")]
+ public static void BookValueMatchesNetWorth()
+ {
+ var (f, depot) = ValdoriaIn(1877);
+ var w = f.W;
+ f.Train(depot, "Prova", ("loco_steam_1850", 2), ("coach_worker", 2));
+ w.RunDays(w.Calendar.DaysPerYear + w.Calendar.DaysPerMonth - (int)(w.Clock.Day % w.Calendar.DaysPerMonth));
+ Assert.Equal(1878, w.Clock.Year);
+ Assert.Equal(0L, w.Clock.Day % w.Calendar.DaysPerMonth, "inizio del mese: valori appena aggiornati");
+ long expected = w.Vehicles.Where(v => !v.Sold && v.Owner == f.Me).Sum(v => Obsolescence.BookValueCents(w, v));
+ Assert.Equal(expected, FinanceSystem.BookValues(w)[f.Me.Value][(int)AssetCategory.Vehicles], "FinanceSystem.BookValues");
+ Assert.Equal(expected, w.Player.BookValues[(int)AssetCategory.Vehicles], "voce salvata dal mese");
+ Assert.Equal(new Money(expected), FleetOutlook.Build(w, f.Me).BookValueTotal, "quadro della flotta");
+ var balance = ClimbOutlook.Balance(w.Player);
+ Assert.Equal(new Money(expected), balance.Assets.Single(a => a.Category == AssetCategory.Vehicles).Value, "stato patrimoniale");
+ Assert.Equal(w.Player.NetWorth, w.Player.Cash + w.Player.AssetBookValue + w.Player.PortfolioValue - w.Player.Debt);
+ }
+
+ [Test(Description = "Rinnovo in officina: i veicoli superati si vendono e i successori prendono il loro posto, con denaro e merci in equilibrio")]
+ public static void RenewalReplacesSupersededVehicles()
+ {
+ var (f, depot) = ValdoriaIn(1878);
+ var w = f.W;
+ int fresh = f.Train(depot, "Nuovo", ("loco_steam_1878", 1), ("wagon_hopper", 2));
+ var refused = f.Do(new ScheduleServiceCommand(new TrainId(fresh), "renewal"));
+ Assert.Equal(CommandError.NotAllowed, refused.Error, "niente da rinnovare");
+
+ int train = f.Train(depot, "Vecchio", ("loco_steam_1850", 1), ("wagon_hopper", 2));
+ var t = w.Trains[train];
+ var oldLoco = t.Vehicles[0];
+ var wagons = t.Vehicles.Skip(1).ToList();
+ var plan = Obsolescence.RenewalPlan(w, t);
+ Assert.Equal(1, plan.Count, "solo la locomotiva è superata");
+ Assert.Equal("loco_steam_1878", plan[0].Successor.Id);
+ var renewal = w.Data.Maintenance.Interventions[w.Data.Maintenance.InterventionIndex("renewal")];
+ var outlook = FleetOutlook.Build(w, f.Me).Trains.Single(x => x.Train.Value == train);
+ Assert.Equal(Obsolescence.NetCost(plan) + Fleet.CostOf(w, t, renewal, Fleet.PolicyOf(w, t)), outlook.NetCost);
+
+ var cash = w.Player.Cash;
+ Assert.True(f.Do(new ScheduleServiceCommand(new TrainId(train), "renewal")).Ok);
+ Assert.True(t.InWorkshop, "il treno è già nel deposito: entra subito in officina");
+ Assert.True(f.RunUntil(() => !t.InWorkshop, 30), "rinnovo completato");
+ Assert.True(w.Vehicles[oldLoco.Value].Sold, "la vecchia locomotiva è venduta");
+ var loco = w.Vehicles[t.Vehicles[0].Value];
+ Assert.Equal("loco_steam_1878", loco.Def.Id);
+ Assert.Equal(t.Id, loco.Train);
+ Assert.SequenceEqual(wagons, t.Vehicles.Skip(1), "i carri restano al loro posto");
+ Assert.Approx(loco.Def.PowerKw, t.PowerKw, 1e-9, "caratteristiche del treno ricalcolate");
+ Assert.True(w.Player.Cash < cash, "il rinnovo costa");
+ Assert.Equal(0, Obsolescence.RenewalPlan(w, t).Count, "niente più da rinnovare");
+ Assert.True(t.History.Any(h => h.Intervention == w.Data.Maintenance.InterventionIndex("renewal")), "nello storico della manutenzione");
+ AssertInvariants(w, "dopo il rinnovo");
+ }
+
+ [Test(Description = "Rinnovo deterministico e salvataggio a metà officina: stesso hash e stesso esito, senza nuovo stato (corpo versione 7)")]
+ public static void RenewalIsDeterministicAcrossSaves()
+ {
+ Assert.Equal(7, WorldSerializer.BodyVersion, "ere e obsolescenza non aggiungono stato al salvataggio");
+ (World W, int Train) Start()
+ {
+ var (f, depot) = ValdoriaIn(1878);
+ int train = f.Train(depot, "Vecchio", ("loco_steam_1850", 1), ("coach_worker", 2));
+ Assert.True(f.Do(new ScheduleServiceCommand(new TrainId(train), "renewal")).Ok);
+ f.W.RunDays(1);
+ return (f.W, train);
+ }
+ var (a, train) = Start();
+ var (b, _) = Start();
+ var loaded = SaveFile.Load(TestData.Data, SaveFile.Save(b, "test"));
+ Assert.True(loaded.Trains[train].InWorkshop, "salvato a metà officina");
+ a.RunDays(40);
+ loaded.RunDays(40);
+ Assert.Equal(StateHasher.Compute(a), StateHasher.Compute(loaded));
+ Assert.Equal("loco_steam_1878", loaded.Vehicles[loaded.Trains[train].Vehicles[0].Value].Def.Id);
+ Assert.Equal(0L, loaded.MoneyBalanceSum());
+ }
+
+ [Test(Description = "Il quadro della flotta si proietta nel protocollo e sopravvive al round-trip")]
+ public static void FleetReportRoundTrip()
+ {
+ var (f, depot) = ValdoriaIn(1878);
+ var w = f.W;
+ int train = f.Train(depot, "Vecchio", ("loco_steam_1850", 1), ("wagon_hopper", 1));
+ ulong hash = StateHasher.Compute(w);
+ var report = Projection.FleetRenewal(w, f.Me);
+ Assert.Equal(hash, StateHasher.Compute(w), "il quadro non cambia il mondo");
+ var decoded = (FleetReport)Frame.Decode(Frame.Encode(report));
+ Assert.Equal("steam", decoded.Era);
+ Assert.Equal("diesel", decoded.NextEra);
+ Assert.Equal(1925, decoded.NextEraYear);
+ Assert.Equal("renewal", decoded.RenewalIntervention);
+ Assert.Equal(2, decoded.Vehicles.Count);
+ var loco = decoded.Vehicles.Single(v => v.Type == "loco_steam_1850");
+ Assert.True(loco.Superseded && loco.InProduction);
+ Assert.Equal(1878, loco.SupersededYear);
+ Assert.Equal("loco_steam_1878", loco.Successor);
+ Assert.Equal(train, loco.Train);
+ Assert.Approx(w.Data.Obsolescence.MaintenanceCostFactor, loco.MaintenanceFactor, 1e-6);
+ var v = w.Vehicles[loco.Vehicle];
+ Assert.Equal(Obsolescence.ResaleValue(w, v), loco.Resale);
+ Assert.Equal(new Money(Obsolescence.BookValueCents(w, v)), loco.BookValue);
+ Assert.Equal(decoded.Vehicles.Sum(x => x.BookValue.Cents), decoded.BookValueTotal.Cents);
+ Assert.Equal(train, decoded.Trains.Single().Train);
+ Assert.True(decoded.Models.Single(m => m.Type == "loco_steam_1850").Superseded);
+ Assert.False(decoded.Models.Any(m => m.Type == "loco_diesel_1925"), "non ancora introdotto");
+ }
+
+ private static void SetCash(World w, Company c, Money target)
+ {
+ var delta = target - c.Cash;
+ if (delta.IsPositive) w.Money.Transfer(Account.External, Account.Of(c.Id), delta, LedgerEntry.Other);
+ else if (delta.IsNegative) w.Money.Transfer(Account.Of(c.Id), Account.External, -delta, LedgerEntry.Other);
+ }
+
+ [Test(Description = "Rinnovo: la cassa spesa tra prenotazione e avvio annulla il lavoro senza scoperto; due prenotazioni non impegnano la stessa cassa")]
+ public static void RenewalCashIsCheckedAtStartAndCommitted()
+ {
+ var (f, depot) = ValdoriaIn(1878);
+ var w = f.W;
+ int a = f.Train(depot, "Primo", ("loco_steam_1850", 1), ("wagon_hopper", 1));
+ int b = f.Train(depot, "Secondo", ("loco_steam_1850", 1), ("wagon_hopper", 1));
+ var ta = w.Trains[a];
+ var tb = w.Trains[b];
+ // all'inizio di un giorno: l'officina avvia i lavori solo al giorno dopo
+ w.RunTicks(w.Calendar.TicksPerDay - w.Clock.Tick % w.Calendar.TicksPerDay + 1);
+ var cost = Obsolescence.RenewalCost(w, ta, Obsolescence.RenewalPlan(w, ta));
+ Assert.True(cost.IsPositive, "il rinnovo costa");
+ // cassa per un rinnovo solo: il secondo trova la cassa già impegnata dal primo
+ SetCash(w, w.Player, cost + cost * 0.5);
+ Assert.True(f.Do(new ScheduleServiceCommand(new TrainId(a), "renewal")).Ok);
+ Assert.Equal(cost, Obsolescence.Committed(w, f.Me), "spesa impegnata dal rinnovo prenotato");
+ var outlook = FleetOutlook.Build(w, f.Me);
+ Assert.True(outlook.Trains.Single(x => x.Train.Value == a).Booked, "il primo è prenotato");
+ var second = outlook.Trains.Single(x => x.Train.Value == b);
+ Assert.False(second.Booked, "il secondo no");
+ Assert.False(second.Affordable, "il secondo non è pagabile con la cassa già impegnata");
+ var refused = f.Do(new ScheduleServiceCommand(new TrainId(b), "renewal"));
+ Assert.Equal(CommandError.InsufficientFunds, refused.Error, refused.Message);
+ Assert.True(refused.Message.Contains("impegnati", StringComparison.Ordinal), refused.Message);
+
+ // la cassa si spende altrove prima dell'avvio: il rinnovo si annulla, niente scoperto
+ SetCash(w, w.Player, cost - new Money(1));
+ var oldLoco = ta.Vehicles[0];
+ w.Events.Drain();
+ w.RunDays(2);
+ Assert.False(ta.InWorkshop, "il treno esce dall'officina");
+ Assert.Equal(-1, ta.PlannedIntervention);
+ Assert.Equal(oldLoco, ta.Vehicles[0], "nessun veicolo sostituito");
+ Assert.False(w.Vehicles[oldLoco.Value].Sold);
+ Assert.False(w.Player.Cash.IsNegative, "la cassa non va in scoperto");
+ Assert.Equal(0L, ta.MaintenanceThisYear, "nemmeno il lavoro è pagato");
+ Assert.True(w.Events.Drain().Any(e => e.Severity == EventSeverity.Warning && e.Text.Contains("rinnovo annullato", StringComparison.Ordinal)),
+ "notizia di avviso");
+ Assert.Equal(Money.Zero, Obsolescence.Committed(w, f.Me), "niente più impegnato");
+
+ // con la cassa, il rinnovo si paga all'avvio e poi non impegna più nulla
+ SetCash(w, w.Player, cost * 3);
+ Assert.True(f.Do(new ScheduleServiceCommand(new TrainId(a), "renewal")).Ok);
+ w.RunDays(2);
+ Assert.True(ta.InWorkshop, "lavori in corso");
+ Assert.Equal("loco_steam_1878", w.Vehicles[ta.Vehicles[0].Value].Def.Id, "veicoli sostituiti all'avvio");
+ Assert.Equal(Money.Zero, Obsolescence.Committed(w, f.Me), "spesa già pagata");
+ Assert.True(f.RunUntil(() => !ta.InWorkshop, 30), "rinnovo completato");
+ Assert.True(tb.Vehicles.All(id => !w.Vehicles[id.Value].Sold));
+ AssertInvariants(w, "dopo i rinnovi");
+ }
+
+ [Test(Description = "Un rinnovo che all'avvio non ha più nulla da sostituire si annulla senza far pagare il lavoro")]
+ public static void RenewalWithEmptyPlanAtStartIsCancelled()
+ {
+ // la Vittoria 2-8-0 si produce solo nel 1878: dal 1879 l'Ardita è superata ma senza successore in produzione
+ var files = MemoryDataSource.Snapshot(TestData.Source);
+ var vehicles = JsonNode.Parse(files["vehicles.json"])!;
+ vehicles["vehicles"]!.AsArray().First(v => (string)v!["id"]! == "loco_steam_1878")!["eraTo"] = 1878;
+ files["vehicles.json"] = vehicles.ToJsonString();
+ var data = GameData.Load(new MemoryDataSource(files));
+ var (f, depot) = ValdoriaIn(1878, data);
+ var w = f.W;
+ w.RunDays(w.Calendar.DaysPerYear - 3 - (int)w.Clock.Day);
+ Assert.Equal(1878, w.Clock.Year);
+ // due revisioni generali occupano gli stalli del deposito piccolo oltre la fine dell'anno
+ for (int i = 0; i < w.Network.Depots[depot].Stalls; i++)
+ {
+ int busy = f.Train(depot, $"Occupato {i}", ("loco_steam_1878", 1));
+ Assert.True(f.Do(new ScheduleServiceCommand(new TrainId(busy), "overhaul")).Ok);
+ }
+ int train = f.Train(depot, "Vecchio", ("loco_steam_1850", 1), ("wagon_hopper", 1));
+ var t = w.Trains[train];
+ Assert.Equal(1, Obsolescence.RenewalPlan(w, t).Count, "nel 1878 la Vittoria si compra");
+ Assert.True(f.Do(new ScheduleServiceCommand(new TrainId(train), "renewal")).Ok);
+ var oldLoco = t.Vehicles[0];
+ w.Events.Drain();
+ Assert.True(f.RunUntil(() => !t.InWorkshop, 120), "il rinnovo esce dalla coda");
+ Assert.Equal(1879, w.Clock.Year);
+ Assert.Equal(oldLoco, t.Vehicles[0], "nessun veicolo sostituito");
+ Assert.Equal(0L, t.MaintenanceThisYear, "il lavoro non si paga");
+ Assert.False(t.History.Any(h => h.Intervention == w.Data.Maintenance.InterventionIndex("renewal")), "nessun rinnovo nello storico");
+ Assert.True(w.Events.Drain().Any(e => e.Severity == EventSeverity.Warning && e.Text.Contains("rinnovo annullato", StringComparison.Ordinal)),
+ "notizia di avviso");
+ Assert.Equal(0L, w.MoneyBalanceSum());
+ }
+
+ [Test(Description = "La ricostruzione di un modello fuori produzione non lo rende nuovo nel patrimonio")]
+ public static void RebuildKeepsBookAgeOfRetiredModels()
+ {
+ var (f, depot) = ValdoriaIn(1905);
+ var w = f.W;
+ int train = f.Train(depot, "Vecchio", ("loco_steam_1850", 1), ("wagon_hopper", 1));
+ var t = w.Trains[train];
+ w.RunDays(w.Calendar.DaysPerYear + 10);
+ Assert.Equal(1906, w.Clock.Year);
+ var loco = w.Vehicles[t.Vehicles[0].Value];
+ var wagon = w.Vehicles[t.Vehicles[1].Value];
+ long locoBought = loco.BoughtDay;
+ long locoBook = Obsolescence.BookValueCents(w, loco);
+ loco.Components[0] = 10;
+ var replace = w.Data.Maintenance.Interventions[w.Data.Maintenance.InterventionIndex("repair_catastrophic")];
+ Fleet.Apply(w, t, replace, Fleet.PolicyOf(w, t));
+ Assert.Equal(locoBought, loco.BoughtDay, "l'Ardita non si produce più: età contabile invariata");
+ Assert.Equal(locoBook, Obsolescence.BookValueCents(w, loco), "valore di libro invariato");
+ Assert.True(loco.Components.All(c => c == 100), "componenti ricostruiti");
+ Assert.Approx(1, Fleet.AgeFactor(w, loco), 1e-12, "l'usura riparte da capo");
+ Assert.Equal(w.Clock.Day, wagon.BoughtDay, "il carro, ancora in produzione, torna nuovo");
+ }
+
+ [Test(Description = "La Cronaca registra il contenuto di un anno con soli modelli fuori produzione")]
+ public static void MilestoneOfRetirementOnlyYear()
+ {
+ var d = TestData.Data;
+ Assert.Equal(0, EraSystem.Unlocks(d, 1906).Count, "nel 1906 nessuno sblocco");
+ var (f, _) = ValdoriaIn(1878);
+ EraSystem.Announce(f.W, 1906);
+ string text = f.W.Player.Milestones[^1].Text;
+ Assert.True(text.StartsWith("novità del 1906: ", StringComparison.Ordinal) && text.Contains("fuori produzione: Ardita 2-6-0", StringComparison.Ordinal), text);
+ }
+
+ [Test(Description = "Scelte delle IA: carrozze non superate, rinnovi che non peggiorano trazione, potenza, velocità e potenza/massa")]
+ public static void AiChoicesAvoidSupersededAndWeakerModels()
+ {
+ var (f1949, _) = ValdoriaIn(1878);
+ Assert.Equal("coach_worker", Estimators.CoachFor(f1949.W, PaxClass.Worker, 1949)!.Id);
+ Assert.Equal("coach_modern", Estimators.CoachFor(f1949.W, PaxClass.Worker, 1950)!.Id, "dal 1950 la carrozza operai è superata");
+ Assert.Equal("coach_staff", Estimators.CoachFor(f1949.W, PaxClass.Staff, 1950)!.Id, "senza successore resta quella");
+
+ bool Keeps(int year, params (string Type, int Count)[] vehicles)
+ {
+ var (f, depot) = ValdoriaIn(year);
+ var t = f.W.Trains[f.Train(depot, "Prova", vehicles)];
+ var plan = Obsolescence.RenewalPlan(f.W, t);
+ Assert.True(plan.Count > 0, $"{year}: qualcosa da rinnovare");
+ return Obsolescence.KeepsPerformance(f.W, t, plan);
+ }
+ Assert.True(Keeps(1878, ("loco_steam_1850", 1), ("wagon_hopper", 3)), "Ardita → Vittoria migliora tutto");
+ Assert.False(Keeps(1902, ("loco_steam_1878", 1), ("wagon_hopper", 3)), "Vittoria → Freccia perde sforzo di trazione");
+ Assert.True(Keeps(1925, ("loco_steam_1878", 1), ("wagon_hopper", 3)), "dal 1925 la Vittoria passa all'Aquila D1");
+ Assert.False(Keeps(1950, ("loco_diesel_1925", 1), ("coach_worker", 8)), "carrozze più pesanti con la stessa potenza");
+ }
+
+ [Test(Slow = true, Description = "Le IA rinnovano i treni con locomotive superate, senza comandi rifiutati oltre il 5 %")]
+ public static void AiRenewsSupersededTrains()
+ {
+ var files = MemoryDataSource.Snapshot(TestData.Source);
+ var ai = JsonNode.Parse(files["ai.json"])!;
+ ai["renewal"]!["minSupersededYears"] = 0;
+ files["ai.json"] = ai.ToJsonString();
+ var data = GameData.Load(new MemoryDataSource(files));
+ var w = WorldFactory.Create(data, new NewGameSettings { Seed = 42, SizeKm = 64, StartYear = 1875 });
+ // fino al 1878: le IA costruiscono le prime linee con l'Ardita del 1850
+ w.RunTicks((long)3 * w.Calendar.DaysPerYear * w.Calendar.TicksPerDay - w.Clock.Tick);
+ Assert.Equal(1878, w.Clock.Year);
+ var oldTrains = w.Trains
+ .Where(t => !t.Removed && !w.Company(t.Owner).IsPlayer && t.Vehicles.Any(id => w.Vehicles[id.Value].Def.Id == "loco_steam_1850"))
+ .Select(t => t.Id).ToList();
+ Assert.True(oldTrains.Count > 0, "le IA hanno treni con l'Ardita");
+ w.RunYears(2);
+ int renewed = oldTrains.Count(id => w.Trains[id.Value].Vehicles.Any(v => w.Vehicles[v.Value].Def.Id == "loco_steam_1878"));
+ Assert.True(renewed > 0, $"almeno un treno rinnovato su {oldTrains.Count}");
+ foreach (var s in w.AiStates)
+ Assert.True(s.RejectedShare <= w.Data.Ai.Planning.MaxRejectedShare, $"{w.Company(s.Company).Name}: {s.Rejected} rifiutati su {s.Issued}");
+ Assert.Equal(0L, w.MoneyBalanceSum());
+ }
+}
diff --git a/tests/RailEnterprise.Tests/Economy/IndustryOutlookTests.cs b/tests/RailEnterprise.Tests/Economy/IndustryOutlookTests.cs
new file mode 100644
index 0000000..0ef6809
--- /dev/null
+++ b/tests/RailEnterprise.Tests/Economy/IndustryOutlookTests.cs
@@ -0,0 +1,319 @@
+using RailEnterprise.Core.Commands;
+using RailEnterprise.Core.Common;
+using RailEnterprise.Core.Data;
+using RailEnterprise.Core.Economy;
+using RailEnterprise.Core.Persistence;
+using RailEnterprise.Core.Rail;
+using RailEnterprise.Core.Simulation;
+using RailEnterprise.Core.Simulation.Systems;
+using RailEnterprise.Protocol;
+using RailEnterprise.Protocol.Messages;
+using RailEnterprise.Server;
+using RailEnterprise.Tests.Harness;
+using RailEnterprise.Tests.Rail;
+
+namespace RailEnterprise.Tests.Economy;
+
+/// Scheda dell'industria dell'immagine 07 (F6, ADR 0021): catena produttiva, coperture, limite, crescita.
+public static class IndustryOutlookTests
+{
+ private static int GoodIndex(World w, string id) => w.Data.Goods.First(g => g.Id == id).Index;
+
+ /// Valdoria con la rete merci miniere → acciaieria, un treno sulla linea e 40 giorni di servizio.
+ private static (RailFixture F, int Line, int MillStation) ServedValdoria()
+ {
+ var f = RailFixture.Valdoria();
+ var (mine, mill, depot) = f.BuildFreightNetwork();
+ int train = f.Train(depot, "Merci 1", ("loco_steam_1850", 1), ("wagon_hopper", 4));
+ int line = f.Ok(new CreateLineCommand("Linea 1", "#e0a526", new[] { new LineStop(new StationId(mine)), new LineStop(new StationId(mill)) }));
+ f.Ok(new AssignTrainCommand(new TrainId(train), new LineId(line)));
+ f.W.RunDays(40);
+ return (f, line, mill);
+ }
+
+ [Test(Description = "Scheda dell'acciaieria di Valdoria: input, output, fornitore collegato dalla linea, clienti, stazione che serve; nessun effetto sul mondo")]
+ public static void SheetOfTheSteelMill()
+ {
+ var (f, line, millStation) = ServedValdoria();
+ var w = f.W;
+ var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
+ ulong hash = StateHasher.Compute(w);
+ var r = IndustryOutlook.Build(w, steel, f.Me);
+ Assert.Equal(hash, StateHasher.Compute(w), "la scheda non cambia il mondo");
+
+ int dpm = w.Calendar.DaysPerMonth;
+ Assert.Equal(steel.Level, r.Level);
+ Assert.Equal(w.Data.Balance.Growth.MaxLevel, r.MaxLevel);
+ Assert.Equal(steel.Efficiency, r.Efficiency);
+ Assert.Equal(steel.Def.StorageDays, r.StorageDays);
+ Assert.Equal(w.Data.Balance.Industry.CoverageWindowDays, r.CoverageWindowDays);
+
+ // input nell'ordine della ricetta: fabbisogno a piena capacità e consumo al ritmo attuale
+ Assert.Equal(2, r.Inputs.Count);
+ int ore = GoodIndex(w, "iron_ore");
+ Assert.Equal(ore, r.Inputs[0].Good);
+ Assert.Equal(GoodIndex(w, "coal"), r.Inputs[1].Good);
+ double cyclesMonth = (double)steel.Def.Capacity(steel.Level) / steel.Def.Recipe.Outputs[0].PerCycle;
+ Assert.Approx(cyclesMonth * 2, r.Inputs[0].FullMonth, 1e-9);
+ Assert.Approx(cyclesMonth * 1, r.Inputs[1].FullMonth, 1e-9);
+ Assert.Approx(r.Inputs[0].FullMonth * steel.Efficiency, r.Inputs[0].CurrentMonth, 1e-9);
+ Assert.Equal(steel.InputStock[0], r.Inputs[0].Stock);
+ Assert.Equal(IndustryMath.InputCapacity(steel, 0, dpm), r.Inputs[0].Storage);
+
+ // output: capacità del livello, produzione al ritmo attuale, magazzino
+ Assert.Equal(1, r.Outputs.Count);
+ Assert.Approx(steel.Def.Capacity(steel.Level), r.Outputs[0].FullMonth, 1e-9);
+ Assert.Approx(r.Outputs[0].FullMonth * steel.Efficiency, r.Outputs[0].CurrentMonth, 1e-9);
+ Assert.Equal(IndustryMath.OutputCapacity(steel, 0, dpm), r.Outputs[0].Storage);
+ if (r.Outputs[0].CurrentMonth > 0)
+ {
+ double perDay = r.Outputs[0].CurrentMonth / dpm;
+ Assert.Approx(Math.Max(0, r.Outputs[0].Storage - r.Outputs[0].Stock) / perDay, r.Outputs[0].Days, 1e-9);
+ }
+
+ // il primo fornitore di minerale è la miniera di Rocca Bruna, collegata dalla linea
+ int perGood = w.Data.Balance.Industry.Outlook.PartnersPerGood;
+ var suppliers = r.Inputs[0].Partners;
+ Assert.True(suppliers.Count is > 0 && suppliers.Count <= perGood, $"fornitori {suppliers.Count}");
+ var mine = w.Industries.First(i => i.Def.Id == "iron_mine");
+ Assert.Equal(ChainPartnerKind.Industry, suppliers[0].Kind);
+ Assert.Equal(mine.Id.Value, suppliers[0].Target);
+ Assert.Equal(line, suppliers[0].Line.Value);
+ Assert.Equal(w.Market.GlobalPrice[ore], suppliers[0].Price);
+ double mineMonth = mine.CyclesPerDayAtFullCapacity(dpm) * dpm * mine.Efficiency;
+ Assert.Approx(mineMonth, suppliers[0].MonthlyUnits, 1e-9);
+ // dopo i collegati, i più vicini
+ for (int i = 1; i < suppliers.Count; i++)
+ {
+ if (suppliers[i - 1].Line.IsValid == suppliers[i].Line.IsValid)
+ Assert.True(suppliers[i - 1].DistanceKm <= suppliers[i].DistanceKm, "ordinati per distanza");
+ else Assert.True(suppliers[i - 1].Line.IsValid, "prima i collegati");
+ }
+
+ // clienti dell'acciaio: la fabbrica di attrezzi al prezzo locale dell'ADR 0004 e il porto, non collegati
+ var customers = r.Outputs[0].Partners;
+ Assert.True(customers.Count is > 0 && customers.Count <= perGood, $"clienti {customers.Count}");
+ Assert.True(customers.All(c => !c.Line.IsValid), "nessun cliente collegato");
+ var tools = w.Industries.First(i => i.Def.Id == "tool_factory");
+ var toolsEntry = customers.FirstOrDefault(c => c.Kind == ChainPartnerKind.Industry && c.Target == tools.Id.Value);
+ Assert.True(toolsEntry.Kind == ChainPartnerKind.Industry && toolsEntry.Target == tools.Id.Value, "la fabbrica di attrezzi compra acciaio");
+ int steelGood = GoodIndex(w, "steel");
+ int slot = tools.InputIndexOf(steelGood);
+ double local = Market.LocalPrice(w.Market.GlobalPrice[steelGood], IndustryMath.InputCapacity(tools, slot, dpm), tools.InputStock[slot], w.Data.Balance.LocalPrice);
+ Assert.Equal(local, toolsEntry.Price);
+ if (customers.FirstOrDefault(c => c.Kind == ChainPartnerKind.Hub) is { Kind: ChainPartnerKind.Hub } port)
+ Assert.Equal(w.Hubs[port.Target].BuyPrice(w.Market.GlobalPrice[steelGood]), port.Price);
+
+ // servita dalla stazione dell'acciaieria con la linea della compagnia
+ Assert.True(r.ServingStations.Contains(new StationId(millStation)), "stazione dell'acciaieria");
+ Assert.Equal(line, r.ServingLine.Value);
+ // per un'altra compagnia nessuna linea collega
+ var other = IndustryOutlook.Build(w, steel, CompanyId.None);
+ Assert.False(other.ServingLine.IsValid);
+ Assert.True(other.Inputs[0].Partners.All(p => !p.Line.IsValid), "senza compagnia nessun collegamento");
+
+ // crescita: punteggio del trimestre dalla stessa funzione della crescita trimestrale
+ var g = w.Data.Balance.Growth;
+ Assert.Equal(IndustryMath.GrowthScore(steel, g), r.Growth.Current);
+ Assert.Equal(g.UpgradeThreshold, r.Growth.UpgradeThreshold);
+ Assert.Equal(g.DowngradeThreshold, r.Growth.DowngradeThreshold);
+ Assert.Equal(steel.QuarterDays, r.Growth.QuarterDay);
+ Assert.Equal(g.QuarterDays, r.Growth.QuarterDays);
+ Assert.True(r.Growth.Served, "servita da un vettore");
+
+ // acquisto: dei privati, livello e avanzamento dai dati (ADR 0018)
+ var tier = w.Data.Tiers.Tiers.First(t => t.Unlocks.BuyIndustry);
+ Assert.True(r.ForSale);
+ Assert.False(r.BuyUnlocked);
+ Assert.Equal(tier.Level, r.BuyTier);
+ Assert.Approx(ClimbOutlook.Requirements(w, w.Player, tier).Progress, r.BuyProgress, 1e-12);
+ Assert.Approx(IndustryMath.AnnualProfit(w, steel), r.AnnualProfit.Cents, 1);
+
+ // prezzo di vendita: il prezzo globale del giorno del prodotto (ADR 0004)
+ Assert.Equal(w.Market.GlobalPrice[steelGood], r.SalePrice);
+ }
+
+ [Test(Description = "La scheda non mostra i pendolari portati da altri vettori, come il Registro degli impieghi; li mostra solo se l'industria è della compagnia")]
+ public static void WorkforceHidesOtherCarriers()
+ {
+ var (f, line, _) = ServedValdoria();
+ var w = f.W;
+ var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
+ var rival = new CompanyId(f.Me.Value + 1);
+ var before = IndustryOutlook.Workforce(w, steel, PaxClass.Worker, f.Me);
+ var town = w.Towns.First();
+ var contract = new CommuteContract
+ {
+ Id = new ContractId(w.NextIds.Contract++), Town = town.Id, Workplace = WorkplaceRef.Of(steel.Id), Category = PaxClass.Worker,
+ Headcount = 120, Carrier = rival, ExpectedMinutes = 400, Coverage = 0.9,
+ };
+ contract.Route.Add(new LineId(line));
+ w.Commutes.Add(contract);
+
+ // per la compagnia del giocatore il contratto del rivale non c'è: né provenienza né viaggio medio
+ var mine = IndustryOutlook.Workforce(w, steel, PaxClass.Worker, f.Me);
+ Assert.False(mine.Sources.Any(x => x.Carrier == rival), "nessuna provenienza del rivale");
+ Assert.Equal(before.SourceCount, mine.SourceCount);
+ Assert.Equal(before.AverageMinutes, mine.AverageMinutes);
+ var sheet = Projection.IndustryCard(w, steel, f.Me).Sheet!;
+ Assert.False(sheet.Workers.Sources.Any(x => x.Carrier == rival.Value), "nemmeno nel messaggio");
+
+ // il rivale vede il suo contratto
+ var theirs = IndustryOutlook.Workforce(w, steel, PaxClass.Worker, rival);
+ Assert.True(theirs.Sources.Any(x => x.Carrier == rival && x.Headcount == 120 && x.Town == town.Id), "il vettore vede i suoi pendolari");
+ Assert.True(theirs.AverageMinutes > 0, "viaggio medio dai suoi contratti");
+
+ // l'industria della compagnia mostra i pendolari di tutti i vettori
+ steel.Owner = f.Me;
+ var owned = IndustryOutlook.Workforce(w, steel, PaxClass.Worker, f.Me);
+ Assert.True(owned.Sources.Any(x => x.Carrier == rival), "il proprietario vede tutti i vettori");
+ Assert.Equal(before.SourceCount + 1, owned.SourceCount);
+ }
+
+ [Test(Description = "Forza lavoro della scheda: presenti, quota in sede, posti scoperti e provenienze dai contratti di pendolarismo")]
+ public static void WorkforceComesFromTheCommuteContracts()
+ {
+ var (f, _, _) = ServedValdoria();
+ var w = f.W;
+ var ib = w.Data.Balance.Industry;
+ foreach (var ind in w.Industries.Where(i => !i.Closed))
+ {
+ foreach (var cls in new[] { PaxClass.Worker, PaxClass.Staff })
+ {
+ var o = IndustryOutlook.Workforce(w, ind, cls, f.Me);
+ bool staff = cls == PaxClass.Staff;
+ int jobs = staff ? ind.JobsStaff : ind.JobsWorkers;
+ double present = staff ? ind.StaffPresent : ind.WorkersPresent;
+ Assert.Equal(jobs, o.Jobs);
+ Assert.Equal(present, o.Present);
+ Assert.Approx(jobs * (staff ? ib.OnSiteStaffShare : ib.OnSiteWorkerShare), o.OnSite, 1e-9);
+ Assert.Equal((int)Math.Max(0, Math.Round(jobs - present, MidpointRounding.AwayFromZero)), o.Missing);
+ var contracts = w.Commutes.Where(c => c.Workplace == WorkplaceRef.Of(ind.Id) && c.Category == cls && c.Headcount > 0 && IndustryOutlook.Visible(c, ind, f.Me)).ToList();
+ Assert.True(o.Sources.Count <= ib.Outlook.WorkforceSources && o.Sources.Count <= o.SourceCount, "provenienze entro il limite");
+ if (o.SourceCount <= ib.Outlook.WorkforceSources)
+ Assert.Equal(contracts.Sum(c => c.Headcount), o.Sources.Sum(s => s.Headcount));
+ for (int i = 1; i < o.Sources.Count; i++) Assert.True(o.Sources[i - 1].Headcount >= o.Sources[i].Headcount, "dalle più numerose");
+ var rail = contracts.Where(c => !c.Walking).ToList();
+ if (rail.Count == 0) Assert.Equal(-1.0, o.AverageMinutes);
+ else Assert.Approx(rail.Sum(c => c.ExpectedMinutes * c.Headcount) / rail.Sum(c => c.Headcount), o.AverageMinutes, 1e-9);
+ }
+ }
+ }
+
+ [Test(Description = "Il limite dell'efficienza è il fattore più basso sotto 1; fermo e livello 0 hanno la precedenza")]
+ public static void LimitIsTheLowestFactor()
+ {
+ var f = RailFixture.Valdoria();
+ var w = f.W;
+ w.RunDays(2);
+ var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
+ var m = w.Data.Balance.IndustryMaintenance;
+
+ steel.CovInput = 1;
+ steel.CovWorkers = 1;
+ steel.CovStaff = 1;
+ steel.RevenueEma = 100;
+ steel.CostEma = 100;
+ steel.Condition = 100;
+ Assert.Equal(IndustryLimit.None, IndustryOutlook.Factors(w, steel).Limit);
+
+ steel.CovStaff = 0.4;
+ steel.CovWorkers = 0.6;
+ Assert.Equal(IndustryLimit.Staff, IndustryOutlook.Factors(w, steel).Limit);
+ steel.CovInput = 0.3;
+ Assert.Equal(IndustryLimit.Inputs, IndustryOutlook.Factors(w, steel).Limit);
+
+ // impianti sotto il 20 %: mc al minimo, sotto le coperture
+ steel.CovInput = 0.9;
+ steel.Condition = 10;
+ var factors = IndustryOutlook.Factors(w, steel);
+ Assert.Equal(m.EfficiencyBelow20, factors.ConditionMultiplier);
+ Assert.Equal(m.EfficiencyBelow20 < 0.4 ? IndustryLimit.Condition : IndustryLimit.Staff, factors.Limit);
+
+ // margine negativo: fattore di profitto sotto 1
+ steel.Condition = 100;
+ steel.CovStaff = 1;
+ steel.CovWorkers = 1;
+ steel.CovInput = 1;
+ steel.RevenueEma = 0;
+ steel.CostEma = 100;
+ Assert.Equal(IndustryLimit.Profit, IndustryOutlook.Factors(w, steel).Limit);
+ Assert.Equal(IndustryMath.ProfitFactor(steel, w.Data.Balance.Industry), IndustryOutlook.Factors(w, steel).ProfitFactor);
+
+ // fermo e livello 0
+ steel.StoppedUntilDay = w.Clock.Day + 5;
+ Assert.Equal(IndustryLimit.Stopped, IndustryOutlook.Factors(w, steel).Limit);
+ steel.StoppedUntilDay = -1;
+ steel.Level = 0;
+ Assert.Equal(IndustryLimit.Dormant, IndustryOutlook.Factors(w, steel).Limit);
+
+ // senza input (miniera) l'input non è mai il limite; giacimento sotto la soglia
+ var mine = w.Industries.First(i => i.Def.Id == "iron_mine");
+ mine.CovInput = 0;
+ mine.CovWorkers = 1;
+ mine.CovStaff = 1;
+ mine.RevenueEma = 100;
+ mine.CostEma = 100;
+ mine.Condition = 100;
+ Assert.Equal(IndustryLimit.None, IndustryOutlook.Factors(w, mine).Limit);
+ var site = w.Sites[mine.Site.Value];
+ site.ReserveTonnes = site.InitialReserveTonnes * w.Data.Balance.Industry.DepletionStartFraction / 2;
+ var depleted = IndustryOutlook.Factors(w, mine);
+ Assert.Equal(IndustryLimit.Depletion, depleted.Limit);
+ Assert.Approx(0.5, depleted.Depletion, 1e-9);
+ Assert.Approx(site.ReserveFraction, depleted.ReserveFraction, 1e-12);
+ }
+
+ [Test(Description = "Il punteggio di crescita trimestrale pesa quota trasportata, copertura e redditività come in balance.json")]
+ public static void GrowthScoreUsesTheWeights()
+ {
+ var f = RailFixture.Valdoria();
+ var w = f.W;
+ var g = w.Data.Balance.Growth;
+ var ind = w.Industries.First(i => i.Def.Id == "steel_mill");
+ ind.QuarterProduced = 200;
+ ind.QuarterShipped = 150;
+ ind.QuarterCoverageSum = 30;
+ ind.QuarterDays = 60;
+ ind.RevenueEma = 300;
+ ind.CostEma = 100;
+ var s = IndustryMath.GrowthScore(ind, g);
+ Assert.Approx(0.75, s.Shipped, 1e-12);
+ Assert.Approx(0.5, s.Coverage, 1e-12);
+ Assert.Approx((ind.Margin + 1) / 2, s.Profit, 1e-12);
+ Assert.Approx(g.WeightShipped * 0.75 + g.WeightCoverage * 0.5 + g.WeightProfit * s.Profit, s.Score, 1e-12);
+ // spedito oltre il prodotto (scorte vecchie): la quota resta 1
+ ind.QuarterShipped = 500;
+ Assert.Equal(1.0, IndustryMath.GrowthScore(ind, g).Shipped);
+ ind.QuarterProduced = 0;
+ ind.QuarterDays = 0;
+ Assert.Equal(0.0, IndustryMath.GrowthScore(ind, g).Shipped);
+ Assert.Equal(0.0, IndustryMath.GrowthScore(ind, g).Coverage);
+ }
+
+ [Test(Description = "La scheda viaggia nel blocco 1 di IndustryCard e torna identica; senza blocco il lettore la lascia vuota")]
+ public static void SheetRoundTripsInTheIndustryCard()
+ {
+ var (f, line, _) = ServedValdoria();
+ var w = f.W;
+ var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
+ var card = Projection.IndustryCard(w, steel, f.Me);
+ Assert.True(card.Sheet is not null, "scheda nel blocco 1");
+ var decoded = (IndustryCard)Frame.Decode(Frame.Encode(card));
+ var sheet = decoded.Sheet!;
+ Assert.True(Frame.Encode(card).AsSpan().SequenceEqual(Frame.Encode(decoded)), "stessi byte");
+ Assert.Equal((byte)steel.Level, sheet.Level);
+ Assert.Equal(2, sheet.Inputs.Count);
+ Assert.Equal(line, sheet.ServingLine);
+ Assert.Equal(line, sheet.Inputs[0].Partners[0].Line);
+ Assert.Equal((float)steel.Efficiency, sheet.Efficiency);
+ Assert.Equal(card.Valuation, decoded.Valuation);
+ Assert.Equal(steel.JobsWorkers, sheet.Workers.Jobs);
+
+ // un messaggio senza blocco (server F5) si legge con la scheda assente
+ var old = new IndustryCard { Industry = 3, Valuation = new Money(100) };
+ var back = (IndustryCard)Frame.Decode(Frame.Encode(old));
+ Assert.True(back.Sheet is null, "nessuna scheda");
+ Assert.Equal(new Money(100), back.Valuation);
+ }
+}
diff --git a/tests/RailEnterprise.Tests/Protocol/ProtocolTests.cs b/tests/RailEnterprise.Tests/Protocol/ProtocolTests.cs
index 5b89bc1..3d1fcbb 100644
--- a/tests/RailEnterprise.Tests/Protocol/ProtocolTests.cs
+++ b/tests/RailEnterprise.Tests/Protocol/ProtocolTests.cs
@@ -35,6 +35,7 @@ public static class ProtocolTests
},
DataHash = 12345,
Difficulty = "imprenditore",
+ Server = new ServerInfo { Version = "0.6.1", Os = "Linux 6.8", Container = true, UptimeSeconds = 518_400, TickMs = 50, Sessions = 1, MaxSessions = 16, Local = false },
};
yield return new Reject { Code = RejectCode.BadToken, Reason = "Token errato" };
yield return new Pong { Nonce = 7, ServerTick = 123456 };
@@ -117,6 +118,36 @@ public static class ProtocolTests
MaintenanceSpentYear = new Money(9999), PartsTarget = 9, PartsPerMonth = 3, PartsOrdered = 20, MachineryRequired = 6, UpgradeCost = new Money(3_000_000),
Valuation = new Money(4_500_000), Cash = new Money(2_000_000), BreakdownChancePerYear = 0.3f,
Stops = [new IndustryStopInfo { Day = 300, Days = 12, Kind = 1 }, new IndustryStopInfo { Day = 500, Days = 30, Kind = 3 }],
+ Sheet = new IndustrySheetInfo
+ {
+ Level = 3, MaxLevel = 5, Efficiency = 0.6f, Limit = 3, CovInput = 0.73f, CovWorkers = 0.8f, CovStaff = 0.6f, CoverageWindowDays = 30,
+ ProfitFactor = 1.05f, Depletion = 1, EventCapacity = 1, ReserveFraction = -1, StorageDays = 30,
+ Inputs =
+ [
+ new IndustryFlowInfo
+ {
+ Good = 2, FullMonth = 480, CurrentMonth = 350, Stock = 105, Storage = 480, Days = 9, Limiting = true,
+ Partners = [new ChainPartnerInfo { Kind = 0, Target = 1, MonthlyUnits = 500, Price = 4_200, Line = 5, DistanceKm = 9.4f }],
+ },
+ ],
+ Outputs =
+ [
+ new IndustryFlowInfo
+ {
+ Good = 4, FullMonth = 500, CurrentMonth = 300, Stock = 40, Storage = 500, Days = 46, Limiting = false,
+ Partners = [new ChainPartnerInfo { Kind = 1, Target = 0, MonthlyUnits = 4000, Price = 15_600, Line = -1, DistanceKm = 4.2f }],
+ },
+ ],
+ Workers = new WorkforceInfo
+ {
+ Jobs = 200, Present = 160, OnSite = 60, Coverage = 0.8f, Missing = 40, Reason = 5, ReasonLine = 1, AverageMinutes = 38, SourceCount = 2,
+ Sources = [new WorkforceSourceInfo { Town = 0, Headcount = 120, Coverage = 0.95f, Line = 1, Carrier = 0, Minutes = 35, Walking = false }],
+ },
+ Staff = new WorkforceInfo { Jobs = 20, Present = 12, Missing = 8, Reason = 4, ReasonLine = -1, AverageMinutes = -1 },
+ SalePrice = 15_600, AnnualProfit = new Money(41_000_000), LastScore = 0.62f, Shipped = 0.8f, Coverage = 0.6f, Profit = 0.55f, Score = 0.69f,
+ UpgradeThreshold = 0.75f, DowngradeThreshold = 0.35f, UpgradeQuarters = 2, QuartersAbove = 1, QuarterDay = 45, QuarterDays = 90, Served = true,
+ ServingStations = [2, 7], ServingLine = 1, ForSale = true, BuyUnlocked = false, BuyTier = 3, BuyProgress = 0.58f,
+ },
};
yield return new Chronicle
{
@@ -188,6 +219,22 @@ public static class ProtocolTests
MaxLoan = new Money(100_000_000), LoanAvailable = new Money(88_000_000), NewLoanRate = 0.061f, LoansAllowed = false,
History = [new NetWorthPointInfo { Day = 0, Value = new Money(25_000_000) }, new NetWorthPointInfo { Day = 2600, Value = new Money(39_144_993) }],
};
+ yield return new FleetReport
+ {
+ Day = 10_100, Company = 0, Year = 1878, Era = "steam", NextEra = "diesel", NextEraYear = 1925, RenewalIntervention = "renewal",
+ BookValueTotal = new Money(1_234_567),
+ Vehicles =
+ [
+ new FleetVehicleInfo { Vehicle = 3, Type = "loco_steam_1850", Train = 1, Depot = -1, AgeYears = 26.5f, LifeYears = 25, Condition = 0.8f,
+ InProduction = true, Superseded = true, SupersededYear = 1878, Successor = "loco_steam_1878", BookValue = new Money(180_000),
+ Resale = new Money(144_000), MaintenanceFactor = 1.5f },
+ new FleetVehicleInfo { Vehicle = 4, Type = "wagon_hopper", Train = -1, Depot = 2, AgeYears = 1f, LifeYears = 40, Condition = 1f,
+ InProduction = true, BookValue = new Money(117_000), Resale = new Money(117_000), MaintenanceFactor = 1f },
+ ],
+ Models = [new VehicleModelInfo { Type = "loco_steam_1850", Superseded = true, SupersededYear = 1878, Successor = "loco_steam_1878", LastYear = 1905 },
+ new VehicleModelInfo { Type = "wagon_hopper" }],
+ Trains = [new RenewalTrainInfo { Train = 1, Vehicles = 1, NetCost = new Money(3_056_000), Affordable = true, Booked = true }],
+ };
yield return new FinanceReport
{
Day = 2610, Company = 0, Cash = new Money(-120_000), NetWorth = new Money(39_000_000), Loans = new Money(12_000_000), Overdraft = new Money(120_000),
@@ -338,6 +385,31 @@ public static class ProtocolTests
foreach (var id in Enum.GetValues()) Assert.True(seen.Contains(id), $"manca l'esemplare di {id}");
}
+ [Test(Description = "Un Welcome senza blocco 1 (server F5) si legge con lo stato del server assente, stessi byte, e la copia locale lo lascia null")]
+ public static void WelcomeWithoutServerInfoRoundTrips()
+ {
+ var old = new Welcome
+ {
+ SessionId = 9,
+ Summary = new WorldSummary { Seed = 1, SizeKm = 64, StartYear = 1850, Date = "1 gennaio 1850", CompanyName = "Società", WidthCells = 64, HeightCells = 64, CellSizeM = 100, ChunkCells = 64 },
+ DataHash = 7,
+ };
+ byte[] frame = Frame.Encode(old);
+ var back = (Welcome)Frame.Decode(frame);
+ Assert.True(back.Server is null, "nessuno stato del server");
+ Assert.True(frame.AsSpan().SequenceEqual(Frame.Encode(back)), "stessi byte");
+ Assert.Equal(old.SessionId, back.SessionId);
+ Assert.Equal("Società", back.Summary.CompanyName);
+
+ // la copia locale del client resta senza stato del server, anche dopo un Welcome che lo aveva
+ var world = new RailEnterprise.Protocol.Client.ClientWorld(TestData.Data);
+ var withInfo = (Welcome)Frame.Decode(Frame.Encode(new Welcome { Summary = old.Summary, Server = new ServerInfo { Version = "0.6.1" } }));
+ world.Apply(withInfo);
+ Assert.True(world.Server is not null, "stato del server dal Welcome F6");
+ world.Apply(back);
+ Assert.True(world.Server is null, "un Welcome F5 azzera lo stato del server");
+ }
+
[Test(Description = "Ogni tipo di comando sopravvive al round-trip dentro un messaggio Command")]
public static void EveryCommandRoundTrips()
{
diff --git a/tests/RailEnterprise.Tests/Server/ServerTests.cs b/tests/RailEnterprise.Tests/Server/ServerTests.cs
index b3b9a0f..e493153 100644
--- a/tests/RailEnterprise.Tests/Server/ServerTests.cs
+++ b/tests/RailEnterprise.Tests/Server/ServerTests.cs
@@ -404,6 +404,55 @@ public static class ServerTests
Assert.Equal(Money.FromLire(5_000), after.Loans);
}
+ [Test(Description = "F6 in rete: la scheda dell'industria arriva su richiesta con la catena produttiva; il Welcome porta lo stato del server e ListSaves l'elenco (ADR 0021)")]
+ public static void IndustrySheetAndServerStatusOnRequest() => RunIndustrySheet().GetAwaiter().GetResult();
+
+ private static async Task RunIndustrySheet()
+ {
+ var scenario = ScenarioHelper.Load("valdoria");
+ var steel = scenario.World.Industries.First(i => i.Def.Id == "steel_mill");
+ await using var server = ServerFixture.Start(scenario.World);
+ await using var client = await TestClient.ConnectAsync(server);
+ var w = client.World;
+ var data = TestData.Data;
+
+ // stato del server nel blocco 1 del Welcome
+ var info = client.Welcome.Server;
+ Assert.True(info is not null, "stato del server nel Welcome");
+ Assert.Equal(server.Host.GameVersion, info!.Version);
+ Assert.Equal(1f, info.TickMs);
+ Assert.True(info.Sessions >= 1 && info.Sessions <= info.MaxSessions, $"sessioni {info.Sessions} su {info.MaxSessions}");
+ Assert.True(info.Local, "server in processo avviato come locale");
+ Assert.True(info.Os.Length > 0 && info.UptimeSeconds >= 0, "sistema e tempo di attività");
+ Assert.True(w.Server is not null && w.Server.Version == info.Version, "la copia locale tiene lo stato del server");
+
+ // elenco dei salvataggi: risposta a ListSaves, poi a Save con il salvataggio nuovo
+ await client.Connection.SendAsync(new ListSaves());
+ var empty = await client.WaitFor(() => w.Saves, "elenco dei salvataggi");
+ var stale = w.Saves;
+ await client.Connection.SendAsync(new Save { Name = "Valdoria" });
+ var saves = await client.WaitFor(() => ReferenceEquals(w.Saves, stale) ? null : w.Saves, "elenco dopo il salvataggio");
+ Assert.Equal(empty.Saves.Count + 1, saves.Saves.Count);
+ Assert.True(saves.Saves.Any(x => !x.Autosave && (x.Name.Contains("Valdoria", StringComparison.Ordinal) || x.SaveId.Contains("Valdoria", StringComparison.OrdinalIgnoreCase))), "il salvataggio nuovo è nell'elenco");
+
+ // scheda dell'industria: si aspetta la risposta alla richiesta, non una scheda vecchia
+ await client.WaitUntil(() => w.LastDigest is { Day: >= 2 }, "due giorni di partita");
+ var old = w.IndustryCards.GetValueOrDefault(steel.Id.Value);
+ await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Industry, Target = steel.Id.Value });
+ var card = await client.WaitFor(() => w.IndustryCards.TryGetValue(steel.Id.Value, out var c) && !ReferenceEquals(c, old) ? c : null, "scheda dell'industria");
+ var sheet = card.Sheet;
+ Assert.True(sheet is not null, "scheda nel blocco 1");
+ Assert.Equal(steel.Def.Recipe.Inputs.Count, sheet!.Inputs.Count);
+ Assert.Equal(steel.Def.Recipe.Outputs.Count, sheet.Outputs.Count);
+ Assert.Equal(data.Goods.First(g => g.Id == "iron_ore").Index, sheet.Inputs[0].Good);
+ Assert.True(sheet.Inputs[0].Partners.Count > 0 && sheet.Inputs[0].Partners.All(p => p.Line == -1), "fornitori, nessuno collegato");
+ Assert.Equal(data.Balance.Growth.MaxLevel, (int)sheet.MaxLevel);
+ Assert.Equal(-1, sheet.ServingLine);
+ Assert.True(sheet.ForSale && !sheet.BuyUnlocked, "in vendita, acquisto non ancora sbloccato");
+ Assert.Equal(data.Tiers.Tiers.First(t => t.Unlocks.BuyIndustry).Level, (int)sheet.BuyTier);
+ Assert.Equal(steel.JobsWorkers, sheet.Workers.Jobs);
+ }
+
[Test(Description = "Hello con token errato, dati diversi o protocollo vecchio riceve Reject")]
public static void HandshakeRejections() => RunRejections().GetAwaiter().GetResult();
@@ -447,6 +496,12 @@ public static class ServerTests
Assert.Equal(1, list.Saves.Count);
Assert.True(list.Saves[0].SaveId.StartsWith("prova_rete-", StringComparison.Ordinal), list.Saves[0].SaveId);
await client.WaitFor(() => client.Received.OfType().FirstOrDefault(), "snapshot");
+ // un Load rifiutato risponde con un avviso del server: giorno −1, distinto dagli eventi del mondo
+ await client.Connection.SendAsync(new Load { SaveId = "non-esiste" });
+ var refused = await client.WaitFor(() => client.Received.OfType().FirstOrDefault(n => n.Event.Day < 0), "avviso del Load rifiutato");
+ Assert.Equal(GameHost.ServerNoticeDay, refused.Event.Day);
+ Assert.True(refused.Event.Text.StartsWith("Caricamento non riuscito", StringComparison.Ordinal), refused.Event.Text);
+ Assert.False(client.Received.OfType().Any(n => n.Event.Day >= 0 && n.Event.Text.StartsWith("Caricamento", StringComparison.Ordinal)), "nessun evento del mondo scambiato per l'avviso");
}
// ripresa con lo stesso id: stessa sessione, stato rimandato per intero
await using (var again = await TestClient.ConnectAsync(server, resume: sessionId))