F3: client Godot minimo, replay dei comandi e collaudi automatici

- Client Godot 4.7 .NET (Godot.NET.Sdk 4.7.2): menu, collegamento, partita
  locale con server figlio; mappa con terreno (fasce, ombreggiatura, rive
  curve con shader, curve di livello), opere, entità, alberi, treni
  interpolati con fumo; strumenti binari con profilo, stazione, deposito,
  segnali, demolizione; pannelli treni, linee, mercato, finanze, schede;
  barra superiore, minimappa, notiziario; italiano e inglese.
- Pilota automatico del client e scripts/client-autopilot.sh: partita locale,
  linea con ponte, treni in moto e schermate (docs/screenshots).
- Registro dei comandi del server (--record) e viaferrea-tools replay.
- PROTOCOL.md normativo, ADR 0009, ARCHITECTURE, STATE e README aggiornati.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0191R7vXgtbAvSV4V8tj8uzL
This commit is contained in:
Claude committed 2026-10-02 00:47:42 +00:00
1 parent 5a318e6528
commit 9a4ada6d9d
97 files changed
+5151 -96

No files matched your search

+4
View File
@@ -441,3 +441,7 @@ client/ViaFerrea.Client/export/
docker/data/
# Salvataggi locali di sviluppo
/saves/
# Dati copiati nel progetto Godot dalla build del client
client/ViaFerrea.Client/data/
# Traduzioni generate da Godot importando strings.csv
client/ViaFerrea.Client/assets/i18n/*.translation
+16 -2
View File
@@ -26,7 +26,7 @@ Su Windows: `./scripts/build.ps1 -Test`.
| `src/ViaFerrea.Core` | simulazione, dati, mappa, economia, rete ferroviaria, salvataggi |
| `src/ViaFerrea.Protocol` | protocollo binario su WebSocket |
| `src/ViaFerrea.Server` | server autorevole (Kestrel) |
| `src/ViaFerrea.Tools` | `viaferrea-tools`: validate-data, genmap, profile, simulate, bench, replay |
| `src/ViaFerrea.Tools` | `viaferrea-tools`: validate-data, genmap, profile, simulate, bench, smoke, replay |
| `tests/ViaFerrea.Tests` | harness di test interno e scenari |
| `client/ViaFerrea.Client` | client Godot |
| `data/` | parametri di gioco in JSON con schema |
@@ -34,11 +34,25 @@ Su Windows: `./scripts/build.ps1 -Test`.
| `docs/` | guida, GDD, architettura, protocollo, stato, ADR |
| `reference/` | immagini di riferimento visivo |
## Server e client in locale
```
dotnet run --project src/ViaFerrea.Server -- --local --token prova # stampa LISTENING <porta>
dotnet build client/ViaFerrea.Client/ViaFerrea.Client.csproj # poi apri client/ViaFerrea.Client con Godot 4.7 .NET
```
Dal menu del client, «Partita locale» avvia da solo il server compilato (`src/ViaFerrea.Server/bin/...` oppure `VF_SERVER_PATH`).
Collaudi senza mani: `dotnet run --project src/ViaFerrea.Tools -- smoke --url ws://127.0.0.1:7400/ws --token prova`
contro un server in esecuzione; `GODOT=/percorso/godot scripts/client-autopilot.sh` per il client con schermate.
![Linea con ponte nel client](docs/screenshots/f3-linea-con-ponte.jpg)
## Server in Docker
```
docker compose -f docker/docker-compose.yml up -d
docker compose -f docker/docker-compose.yml up -d # oppure scripts/publish-image.sh per il registry Gitea
curl http://localhost:7400/health
curl http://localhost:7400/metrics
```
Variabili principali: `VF_TOKEN` (obbligatoria in rete), `VF_DIFFICULTY`, `VF_SEED`, `VF_MAP_SIZE`, `VF_DATA_DIR` (default `/data`).
@@ -0,0 +1,33 @@
<Project Sdk="Godot.NET.Sdk/4.7.2">
<!--
Client Godot di Via Ferrea: fuori dalla soluzione principale. Usa Core e Protocol (net8.0)
per le anteprime e per la copia locale del mondo; nessuna logica di gioco.
-->
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<EnableDynamicLoading>true</EnableDynamicLoading>
<RootNamespace>ViaFerrea.Client</RootNamespace>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\ViaFerrea.Core\ViaFerrea.Core.csproj" />
<ProjectReference Include="..\..\src\ViaFerrea.Protocol\ViaFerrea.Protocol.csproj" />
</ItemGroup>
<!-- I file dati del gioco entrano nel progetto Godot (res://data) prima di ogni build. -->
<Target Name="CopyGameData" BeforeTargets="BeforeBuild">
<ItemGroup>
<GameDataFile Include="..\..\data\*.json" />
<GameSchemaFile Include="..\..\data\schema\*.json" />
</ItemGroup>
<Copy SourceFiles="@(GameDataFile)" DestinationFolder="$(MSBuildProjectDirectory)\data" SkipUnchangedFiles="true" />
<Copy SourceFiles="@(GameSchemaFile)" DestinationFolder="$(MSBuildProjectDirectory)\data\schema" SkipUnchangedFiles="true" />
</Target>
</Project>
@@ -0,0 +1,36 @@
[remap]
importer="font_data_dynamic"
type="FontFile"
uid="uid://ctn3r3irayxtn"
path="res://.godot/imported/BigShouldersDisplay-ExtraBold.ttf-06ad0a7babb718d5a091c8ed4e7073f9.fontdata"
[deps]
source_file="res://assets/fonts/BigShouldersDisplay-ExtraBold.ttf"
dest_files=["res://.godot/imported/BigShouldersDisplay-ExtraBold.ttf-06ad0a7babb718d5a091c8ed4e7073f9.fontdata"]
[params]
Rendering=null
antialiasing=1
generate_mipmaps=false
disable_embedded_bitmaps=true
multichannel_signed_distance_field=false
msdf_pixel_range=8
msdf_size=48
allow_system_fallback=true
force_autohinter=false
modulate_color_glyphs=false
hinting=3
subpixel_positioning=4
keep_rounding_remainders=true
oversampling=0.0
Fallbacks=null
fallbacks=[]
Compress=null
compress=true
preload=[]
language_support={}
script_support={}
opentype_features={}
@@ -0,0 +1,36 @@
[remap]
importer="font_data_dynamic"
type="FontFile"
uid="uid://dmgv5ntajuive"
path="res://.godot/imported/IBMPlexSans-Regular.ttf-196fcb82807990841fe9b17f1801fc73.fontdata"
[deps]
source_file="res://assets/fonts/IBMPlexSans-Regular.ttf"
dest_files=["res://.godot/imported/IBMPlexSans-Regular.ttf-196fcb82807990841fe9b17f1801fc73.fontdata"]
[params]
Rendering=null
antialiasing=1
generate_mipmaps=false
disable_embedded_bitmaps=true
multichannel_signed_distance_field=false
msdf_pixel_range=8
msdf_size=48
allow_system_fallback=true
force_autohinter=false
modulate_color_glyphs=false
hinting=3
subpixel_positioning=4
keep_rounding_remainders=true
oversampling=0.0
Fallbacks=null
fallbacks=[]
Compress=null
compress=true
preload=[]
language_support={}
script_support={}
opentype_features={}
@@ -0,0 +1,36 @@
[remap]
importer="font_data_dynamic"
type="FontFile"
uid="uid://div2g0y3mai1g"
path="res://.godot/imported/IBMPlexSans-SemiBold.ttf-f99727d7fe8b757844d4be5f9599636c.fontdata"
[deps]
source_file="res://assets/fonts/IBMPlexSans-SemiBold.ttf"
dest_files=["res://.godot/imported/IBMPlexSans-SemiBold.ttf-f99727d7fe8b757844d4be5f9599636c.fontdata"]
[params]
Rendering=null
antialiasing=1
generate_mipmaps=false
disable_embedded_bitmaps=true
multichannel_signed_distance_field=false
msdf_pixel_range=8
msdf_size=48
allow_system_fallback=true
force_autohinter=false
modulate_color_glyphs=false
hinting=3
subpixel_positioning=4
keep_rounding_remainders=true
oversampling=0.0
Fallbacks=null
fallbacks=[]
Compress=null
compress=true
preload=[]
language_support={}
script_support={}
opentype_features={}
@@ -0,0 +1,94 @@
Big Shoulders Display: Copyright 2019 The Big Shoulders Project Authors (https://github.com/xotypeco/big_shoulders)
IBM Plex Sans: Copyright 2019 IBM Corp. All rights reserved. (Reserved Font Name "Plex")
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://openfontlicense.org
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) and the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,130 @@
keys,it,en
Abitanti,,Population
Ambra,,Amber
Annulla,,Cancel
Anteprima non disponibile: ,,Preview unavailable:
Assegna,,Assign
Attendi il pieno alla prima fermata (max 2 giorni),,Wait for full load at the first stop (max 2 days)
Avvio del server locale…,,Starting the local server…
Binari,,Track
Binari di stazione,,Platforms
Blu,,Blue
Cantiere,,Construction
Carico,,Load
Cassa,,Cash
Celeste,,Light blue
Chiedi il prestito,,Request loan
Chiusa,,Closed
Classe,,Class
Clic su un binario per posare un segnale di blocco: divide l'arco in sezioni e aumenta la capacità della linea.,,Click a track to place a block signal: it splits the edge into sections and raises line capacity.
"Clic su una stazione, un deposito o un binario libero per demolirlo; si recupera una parte del costo.",,"Click a station, depot or free track to demolish it; part of the cost is refunded."
"Clic sulla mappa per i punti del tracciato (Maiusc: senza scatto a 45°), Invio per costruire, tasto destro per annullare.",,"Click the map to place route points (Shift: no 45° snap), Enter to build, right click to cancel."
"Clic sulla mappa vicino a un binario, poi raccordalo con lo strumento Binari. Nel deposito si comprano i veicoli e si compongono i treni.",,"Click the map near a track, then connect it with the Track tool. Vehicles are bought and trains composed in the depot."
Clic sulla mappa: la stazione si aggancia al binario vicino o nasce come capolinea. Il cerchio è il bacino di utenza.,,Click the map: the station attaches to the nearby track or becomes a terminus. The circle is the catchment area.
Clic sulle stazioni della mappa per aggiungere le fermate in ordine; la linea torna alla prima.,,Click stations on the map to add stops in order; the line returns to the first.
Collegamento in corso…,,Connecting…
Collegamento non riuscito,,Connection failed
Collegati,,Connect
Collegati a un server,,Connect to a server
Componi,,Compose
Compra veicoli,,Buy vehicles
Condizione,,Condition
Connessione persa,,Connection lost
Consuma,,Consumes
Costo,,Cost
Costruisci,,Build
Crea linea,,Create line
Dati del gioco non trovati o non validi.,,Game data missing or invalid.
Demolisci,,Demolish
Deposito,,Depot
Disconnesso,,Disconnected
Doppio binario,,Double track
Efficienza,,Efficiency
Elettrificato,,Electrified
Esci,,Quit
Finanze,,Finance
Galleria,,Tunnel
Gallerie,,Tunnels
Gestionale ferroviario dall'alto,,Top-down railway management
Grano,,Wheat
Il server non risponde più. La partita continua sul server.,,The server is not responding. The game goes on on the server.
Impianti,,Plant
Indica l'indirizzo del server,,Enter the server address
Indietro,,Back
Indirizzo (host:porta),,Address (host:port)
Indirizzo non valido,,Invalid address
La connessione non è cifrata: per Internet usa un reverse proxy con TLS (wss://).,,The connection is not encrypted: over the Internet use a TLS reverse proxy (wss://).
Linea,,Line
Linee,,Lines
Linee della compagnia,,Company lines
Livello,,Level
Locomotiva,,Locomotive
Lunghezza,,Length
Manda al deposito,,Send to depot
Mercato,,Market
Merci e passeggeri in attesa,,Waiting goods and passengers
Minimappa,,Minimap
Nel bacino,,In the catchment
Nessun tracciato,,No route
Nessuna linea,,No line
Nome automatico,,Automatic name
Nome del treno,,Train name
Nome della linea,,Line name
Notizie,,News
Partita locale,,Local game
Partita locale non avviata,,Local game not started
Patrimonio netto,,Net worth
Pausa,,Pause
Pendenza massima,,Max gradient
Ponte,,Bridge
Ponti,,Bridges
Prestito,,Loan
Prezzi globali di oggi (la borsa arriva in seguito).,,Today's global prices (the stock market comes later).
Produce,,Produces
Quota rispetto al terreno,,Height above ground
Raggio minimo,,Min radius
Rating,,Rating
Regione di,,Region of
Rilevato,,Embankment
Rosso coppo,,Tile red
"Scegli uno strumento a sinistra oppure fai clic su un treno, una stazione, un'industria o una città per vederne la scheda.",,"Pick a tool on the left or click a train, station, industry or town to see its card."
Segnali,,Signals
Seleziona i veicoli da comporre,,Select the vehicles to compose
Seleziona un treno,,Select a train
Seleziona un treno e un deposito,,Select a train and a depot
Serve un deposito,,A depot is required
Server locale non trovato: compila src/ViaFerrea.Server o imposta VF_SERVER_PATH.,,Local server not found: build src/ViaFerrea.Server or set VF_SERVER_PATH.
Servizi,,Services
Servono almeno due fermate,,At least two stops are needed
Soddisfazione,,Satisfaction
Stazione,,Station
Svuota,,Clear
Token,,Token
Token del server,,Server token
Torna al menu,,Back to menu
Treni,,Trains
Treni della compagnia,,Company trains
Trincea,,Cutting
Veicoli,,Vehicles
"Veicoli liberi nel deposito (selezione multipla, in ordine)",,"Free vehicles in the depot (multiple selection, in order)"
Velocità,,Speed
Verde,,Green
Via Ferrea,,Via Ferrea
abitanti,,inhabitants
attendi il pieno,,wait for full load
carica,,load
fermo in salita,,stalled on grade
giorni,,days
guasto,,broken down
hub mercato mondiale,,world market hub
in attesa di via libera,,waiting for clearance
in deposito,,in depot
in marcia,,running
in stazione,,at station
large,Grande,Large
medium,Medio,Medium
scarica,,unload
senza linea,,no line
senza percorso,,no route
small,Piccolo,Small
treni,,trains
1 keys it en
2 Abitanti Population
3 Ambra Amber
4 Annulla Cancel
5 Anteprima non disponibile: Preview unavailable:
6 Assegna Assign
7 Attendi il pieno alla prima fermata (max 2 giorni) Wait for full load at the first stop (max 2 days)
8 Avvio del server locale… Starting the local server…
9 Binari Track
10 Binari di stazione Platforms
11 Blu Blue
12 Cantiere Construction
13 Carico Load
14 Cassa Cash
15 Celeste Light blue
16 Chiedi il prestito Request loan
17 Chiusa Closed
18 Classe Class
19 Clic su un binario per posare un segnale di blocco: divide l'arco in sezioni e aumenta la capacità della linea. Click a track to place a block signal: it splits the edge into sections and raises line capacity.
20 Clic su una stazione, un deposito o un binario libero per demolirlo; si recupera una parte del costo. Click a station, depot or free track to demolish it; part of the cost is refunded.
21 Clic sulla mappa per i punti del tracciato (Maiusc: senza scatto a 45°), Invio per costruire, tasto destro per annullare. Click the map to place route points (Shift: no 45° snap), Enter to build, right click to cancel.
22 Clic sulla mappa vicino a un binario, poi raccordalo con lo strumento Binari. Nel deposito si comprano i veicoli e si compongono i treni. Click the map near a track, then connect it with the Track tool. Vehicles are bought and trains composed in the depot.
23 Clic sulla mappa: la stazione si aggancia al binario vicino o nasce come capolinea. Il cerchio è il bacino di utenza. Click the map: the station attaches to the nearby track or becomes a terminus. The circle is the catchment area.
24 Clic sulle stazioni della mappa per aggiungere le fermate in ordine; la linea torna alla prima. Click stations on the map to add stops in order; the line returns to the first.
25 Collegamento in corso… Connecting…
26 Collegamento non riuscito Connection failed
27 Collegati Connect
28 Collegati a un server Connect to a server
29 Componi Compose
30 Compra veicoli Buy vehicles
31 Condizione Condition
32 Connessione persa Connection lost
33 Consuma Consumes
34 Costo Cost
35 Costruisci Build
36 Crea linea Create line
37 Dati del gioco non trovati o non validi. Game data missing or invalid.
38 Demolisci Demolish
39 Deposito Depot
40 Disconnesso Disconnected
41 Doppio binario Double track
42 Efficienza Efficiency
43 Elettrificato Electrified
44 Esci Quit
45 Finanze Finance
46 Galleria Tunnel
47 Gallerie Tunnels
48 Gestionale ferroviario dall'alto Top-down railway management
49 Grano Wheat
50 Il server non risponde più. La partita continua sul server. The server is not responding. The game goes on on the server.
51 Impianti Plant
52 Indica l'indirizzo del server Enter the server address
53 Indietro Back
54 Indirizzo (host:porta) Address (host:port)
55 Indirizzo non valido Invalid address
56 La connessione non è cifrata: per Internet usa un reverse proxy con TLS (wss://). The connection is not encrypted: over the Internet use a TLS reverse proxy (wss://).
57 Linea Line
58 Linee Lines
59 Linee della compagnia Company lines
60 Livello Level
61 Locomotiva Locomotive
62 Lunghezza Length
63 Manda al deposito Send to depot
64 Mercato Market
65 Merci e passeggeri in attesa Waiting goods and passengers
66 Minimappa Minimap
67 Nel bacino In the catchment
68 Nessun tracciato No route
69 Nessuna linea No line
70 Nome automatico Automatic name
71 Nome del treno Train name
72 Nome della linea Line name
73 Notizie News
74 Partita locale Local game
75 Partita locale non avviata Local game not started
76 Patrimonio netto Net worth
77 Pausa Pause
78 Pendenza massima Max gradient
79 Ponte Bridge
80 Ponti Bridges
81 Prestito Loan
82 Prezzi globali di oggi (la borsa arriva in seguito). Today's global prices (the stock market comes later).
83 Produce Produces
84 Quota rispetto al terreno Height above ground
85 Raggio minimo Min radius
86 Rating Rating
87 Regione di Region of
88 Rilevato Embankment
89 Rosso coppo Tile red
90 Scegli uno strumento a sinistra oppure fai clic su un treno, una stazione, un'industria o una città per vederne la scheda. Pick a tool on the left or click a train, station, industry or town to see its card.
91 Segnali Signals
92 Seleziona i veicoli da comporre Select the vehicles to compose
93 Seleziona un treno Select a train
94 Seleziona un treno e un deposito Select a train and a depot
95 Serve un deposito A depot is required
96 Server locale non trovato: compila src/ViaFerrea.Server o imposta VF_SERVER_PATH. Local server not found: build src/ViaFerrea.Server or set VF_SERVER_PATH.
97 Servizi Services
98 Servono almeno due fermate At least two stops are needed
99 Soddisfazione Satisfaction
100 Stazione Station
101 Svuota Clear
102 Token Token
103 Token del server Server token
104 Torna al menu Back to menu
105 Treni Trains
106 Treni della compagnia Company trains
107 Trincea Cutting
108 Veicoli Vehicles
109 Veicoli liberi nel deposito (selezione multipla, in ordine) Free vehicles in the depot (multiple selection, in order)
110 Velocità Speed
111 Verde Green
112 Via Ferrea Via Ferrea
113 abitanti inhabitants
114 attendi il pieno wait for full load
115 carica load
116 fermo in salita stalled on grade
117 giorni days
118 guasto broken down
119 hub mercato mondiale world market hub
120 in attesa di via libera waiting for clearance
121 in deposito in depot
122 in marcia running
123 in stazione at station
124 large Grande Large
125 medium Medio Medium
126 scarica unload
127 senza linea no line
128 senza percorso no route
129 small Piccolo Small
130 treni trains
@@ -0,0 +1,19 @@
[remap]
importer="csv_translation"
type="Translation"
uid="uid://b3f81cstnijyn"
[deps]
files=["res://assets/i18n/strings.it.translation", "res://assets/i18n/strings.en.translation"]
source_file="res://assets/i18n/strings.csv"
dest_files=["res://assets/i18n/strings.it.translation", "res://assets/i18n/strings.en.translation"]
[params]
compress=1
delimiter=0
unescape_keys=false
unescape_translations=true
@@ -0,0 +1,15 @@
// Terreno: l'alfa della texture è il campo dell'acqua interpolato tra i centri delle celle.
// La soglia a 0,5 dà rive curve e nette a ogni zoom; tra 0,3 e 0,5 la fascia chiara delle sponde.
shader_type canvas_item;
uniform vec4 bank_color : source_color = vec4(0.725, 0.749, 0.612, 1.0);
void fragment() {
vec4 t = texture(TEXTURE, UV);
float w = t.a;
float aa = fwidth(w) * 0.8 + 0.002;
float water = smoothstep(0.5 - aa, 0.5 + aa, w);
float bank = smoothstep(0.28 - aa, 0.28 + aa, w) * (1.0 - water);
vec3 land = mix(t.rgb, bank_color.rgb, bank);
COLOR = vec4(mix(land, t.rgb, water), 1.0);
}
@@ -0,0 +1 @@
uid://d18pluemvpfne
@@ -0,0 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128">
<rect width="128" height="128" rx="20" fill="#11181c"/>
<circle cx="64" cy="64" r="38" fill="none" stroke="#e0a526" stroke-width="8"/>
<path d="M26 64h76M64 26v76" stroke="#e0a526" stroke-width="8"/>
<circle cx="64" cy="64" r="10" fill="#e0a526"/>
</svg>

After

Width:  |  Height:  |  Size: 351 B

@@ -0,0 +1,43 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://c4uc2gnb3ehdx"
path="res://.godot/imported/icon.svg-a9d7d51f2e724465af4bd29137d7fb03.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://assets/theme/icon.svg"
dest_files=["res://.godot/imported/icon.svg-a9d7d51f2e724465af4bd29137d7fb03.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1
svg/scale=1.0
editor/scale_with_editor_scale=false
editor/convert_colors_with_editor_theme=false
@@ -0,0 +1,51 @@
[preset.0]
name="Windows Desktop"
platform="Windows Desktop"
runnable=true
dedicated_server=false
custom_features=""
export_filter="all_resources"
include_filter="data/*.json, data/schema/*.json, assets/i18n/*.csv, assets/fonts/*.ttf, assets/fonts/OFL.txt"
exclude_filter=""
export_path="export/windows/ViaFerrea.exe"
encryption_include_filters=""
encryption_exclude_filters=""
encrypt_pck=false
encrypt_directory=false
[preset.0.options]
custom_template/debug=""
custom_template/release=""
debug/export_console_wrapper=1
binary_format/embed_pck=false
binary_format/architecture="x86_64"
application/product_name="Via Ferrea"
application/company_name="Via Ferrea"
application/file_description="Gestionale ferroviario dall'alto"
dotnet/include_scripts_content=false
dotnet/include_debug_symbols=false
dotnet/embed_build_outputs=false
[preset.1]
name="Linux"
platform="Linux"
runnable=true
dedicated_server=false
custom_features=""
export_filter="all_resources"
include_filter="data/*.json, data/schema/*.json, assets/i18n/*.csv, assets/fonts/*.ttf, assets/fonts/OFL.txt"
exclude_filter=""
export_path="export/linux/ViaFerrea.x86_64"
encrypt_pck=false
encrypt_directory=false
[preset.1.options]
binary_format/embed_pck=false
binary_format/architecture="x86_64"
dotnet/include_scripts_content=false
dotnet/include_debug_symbols=false
dotnet/embed_build_outputs=false
+36
View File
@@ -0,0 +1,36 @@
; File di progetto di Godot 4: client di Via Ferrea (rendering, input, interfaccia).
; Nessuna logica di gioco: il server è autorevole (docs/GUIDA.md, sezione 14.3).
config_version=5
[application]
config/name="Via Ferrea"
config/description="Gestionale ferroviario dall'alto"
run/main_scene="res://scenes/Main.tscn"
config/features=PackedStringArray("4.7", "C#", "GL Compatibility")
boot_splash/bg_color=Color(0.0667, 0.0941, 0.1098, 1)
config/icon="res://assets/theme/icon.svg"
[display]
window/size/viewport_width=1600
window/size/viewport_height=900
window/size/mode=2
window/stretch/aspect="expand"
[dotnet]
project/assembly_name="ViaFerrea.Client"
[internationalization]
locale/fallback="it"
[rendering]
renderer/rendering_method="gl_compatibility"
renderer/rendering_method.mobile="gl_compatibility"
environment/defaults/default_clear_color=Color(0.0667, 0.0941, 0.1098, 1)
textures/canvas_textures/default_texture_filter=1
anti_aliasing/quality/msaa_2d=2
+6
View File
@@ -0,0 +1,6 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://scripts/Main.cs" id="1_main"]
[node name="Main" type="Node"]
script = ExtResource("1_main")
@@ -0,0 +1,166 @@
using Godot;
using ViaFerrea.Client.Hud;
using ViaFerrea.Client.Map;
using ViaFerrea.Client.Net;
using ViaFerrea.Client.Screens;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
namespace ViaFerrea.Client.App;
/// <summary>
/// Pilota automatico per il collaudo del client (<c>-- --autopilot cartella</c>): nella partita
/// locale costruisce stazioni, deposito e una linea con ponte usando l'anteprima, compra un treno,
/// lo mette in linea e salva schermate della mappa, del ponte, del treno e del profilo.
/// </summary>
public partial class AutoPilot : Node
{
private readonly GameScreen _game;
private readonly string _out;
public AutoPilot(GameScreen game, string outDir)
{
_game = game;
_out = outDir;
}
private GameSession Session => _game.Session;
private ClientWorld World => _game.Session.World;
public override async void _Ready()
{
int code = 0;
try
{
await Run();
GD.Print("autopilot: ok");
}
catch (Exception e)
{
GD.PrintErr($"autopilot: FALLITO {e.Message}\n{e.StackTrace}");
code = 1;
}
GetTree().Quit(code);
}
private async Task Frame() => await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
private async Task Until(Func<bool> condition, string what, double timeoutS = 120)
{
ulong start = Time.GetTicksMsec();
while (!condition())
{
if (Time.GetTicksMsec() - start > timeoutS * 1000) throw new TimeoutException(what);
await Frame();
}
}
private Task<CommandResultMessage> Do(GameCommand command)
{
var tcs = new TaskCompletionSource<CommandResultMessage>();
Session.Command(command, r => tcs.TrySetResult(r));
return tcs.Task;
}
private async Task<int> Ok(GameCommand command)
{
var r = await Do(command);
if (!r.Ok) throw new InvalidOperationException($"{command.Type}: {r.Message}");
GD.Print($"autopilot: {r.Message}");
return r.Created.Length > 0 ? r.Created[0] : -1;
}
private async Task Shot(string name, int settleFrames = 30)
{
for (int i = 0; i < settleFrames; i++) await Frame();
await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
var image = GetViewport().GetTexture().GetImage();
string path = Path.Combine(_out, name + ".jpg");
image.SaveJpg(path, 0.88f);
GD.Print($"autopilot: schermata {path}");
}
private async Task Run()
{
Directory.CreateDirectory(_out);
var summary = World.Summary!;
Session.Send(new Subscribe { X0 = 0, Y0 = 0, X1 = summary.WidthCells - 1, Y1 = summary.HeightCells - 1 });
int chunks = ((summary.WidthCells + summary.ChunkCells - 1) / summary.ChunkCells) * ((summary.HeightCells + summary.ChunkCells - 1) / summary.ChunkCells);
await Until(() => World.Chunks.Count == chunks && World.Towns.Count > 0, "terreno");
await Shot("01_avvio", 90);
await Ok(new TakeLoanCommand(Money.FromLire(200_000)));
var site = BridgeSiteFinder.Find(World) ?? throw new InvalidOperationException("nessun sito con ponte");
int a = await Ok(new BuildStationCommand(site.A, 2));
int b = await Ok(new BuildStationCommand(site.B, 2));
int depot = await Ok(new BuildDepotCommand(site.Depot, "small"));
await Until(() => World.Stations.ContainsKey(b) && World.Depots.ContainsKey(depot), "stazioni");
var main = new BuildTrackCommand([site.A, site.B]);
var plan = World.PreviewTrack(main);
await Ok(main with { ExpectedCostCents = plan.TotalCost.Cents });
await Until(() => World.Edges.Count > 0, "binario");
var spur = new BuildTrackCommand([site.Depot, site.A]);
await Ok(spur with { ExpectedCostCents = World.PreviewTrack(spur).TotalCost.Cents });
// vista d'insieme del cantiere
var center = MapScale.V((site.A + site.B) / 2);
_game.Map.CenterOn(center);
_game.Map.SetZoom(0.22f);
await Shot("02_cantiere");
Session.SetSpeed(8);
await Until(() => World.Edges.Count >= 2 && World.Edges.Values.All(e => e.State == (byte)EdgeState.Active), "cantieri", 240);
var loco = await Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1));
var wagons = await Do(new BuyVehicleCommand("wagon_hopper", new DepotId(depot), 3));
int train = await Ok(new ComposeTrainCommand(new DepotId(depot), loco.Created.Concat(wagons.Created).Select(i => new VehicleId(i)).ToList(), "Treno 1"));
var loco2 = await Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1));
var coaches = await Do(new BuyVehicleCommand("coach_worker", new DepotId(depot), 2));
int train2 = await Ok(new ComposeTrainCommand(new DepotId(depot), loco2.Created.Concat(coaches.Created).Select(i => new VehicleId(i)).ToList(), "Treno 2"));
int line = await Ok(new CreateLineCommand("Linea 1, collaudo", "#e0a526", [new LineStop(new StationId(a)), new LineStop(new StationId(b))]));
await Ok(new AssignTrainCommand(new TrainId(train), new LineId(line)));
Session.SetSpeed(1);
await Until(() => World.Motions.TryGetValue(train, out var m) && m.Speed > 3, "treno in moto", 120);
await Ok(new AssignTrainCommand(new TrainId(train2), new LineId(line)));
_game.Map.CenterOn(center);
_game.Map.SetZoom(0.22f);
await Shot("03_linea");
// ponte da vicino (immagine 02)
_game.Map.CenterOn(MapScale.V(site.River));
_game.Map.SetZoom(0.9f);
await Shot("04_ponte");
// treno da vicino (immagine 03): la camera lo segue per qualche fotogramma
for (int i = 0; i < 40; i++)
{
if (World.TrainHead(train) is { } head) _game.Map.CenterOn(MapScale.V(head));
_game.Map.SetZoom(1.4f);
await Frame();
}
_game.SelectTrain(train);
await Shot("05_treno", 5);
// scheda del treno con la mappa d'insieme
_game.Map.SetZoom(0.3f);
await Shot("06_scheda_treno", 20);
// strumento binari con il profilo di un tracciato in collina
_game.UseTool(Tool.Track);
var dir = (site.B - site.A).Normalized();
var normal = new Vec2(-dir.Y, dir.X);
var p0 = MapScale.V(site.B);
var p1 = MapScale.V(site.B + normal * 2500);
var p2 = MapScale.V(site.B + normal * 4000 + dir * 1500);
_game.SetTrackPoints([p0, p1], p2);
_game.Map.CenterOn(MapScale.V(site.B + normal * 2000 + dir * 500));
_game.Map.SetZoom(0.2f);
await Shot("07_profilo", 40);
_game.UseTool(Tool.None);
_game.Map.SetZoom(0.06f);
await Shot("08_panoramica", 60);
}
}
@@ -0,0 +1 @@
uid://bdw1fy2qphri5
@@ -0,0 +1,26 @@
using Godot;
using ViaFerrea.Core.Data;
namespace ViaFerrea.Client.App;
/// <summary>File dati del gioco dentro il progetto Godot (res://data, copiati dalla build del client).</summary>
public sealed class GodotDataSource(string root = "res://data") : IDataSource
{
public string Description => root;
public bool Exists(string relativePath) => Godot.FileAccess.FileExists($"{root}/{relativePath}");
public string ReadText(string relativePath)
{
using var f = Godot.FileAccess.Open($"{root}/{relativePath}", Godot.FileAccess.ModeFlags.Read)
?? throw new FileNotFoundException(relativePath);
return f.GetAsText();
}
/// <summary>Dati del gioco: res://data se presenti, altrimenti la cartella data del repository.</summary>
public static GameData LoadGameData()
{
var source = new GodotDataSource();
return source.Exists("goods.json") ? GameData.Load(source) : GameData.LoadDefault();
}
}
@@ -0,0 +1 @@
uid://bn1h4nbl2f1rc
@@ -0,0 +1,43 @@
using Godot;
namespace ViaFerrea.Client.App;
/// <summary>
/// Testi dell'interfaccia: la lingua sorgente è l'italiano (le chiavi sono i testi italiani),
/// le traduzioni stanno in <c>assets/i18n/strings.csv</c> (colonne keys, it, en) e si caricano
/// all'avvio senza passare dall'importazione dell'editor.
/// </summary>
public static class Localization
{
public static void Load(string locale)
{
const string path = "res://assets/i18n/strings.csv";
using var file = Godot.FileAccess.Open(path, Godot.FileAccess.ModeFlags.Read);
if (file is null)
{
GD.PushWarning("Traduzioni non trovate");
return;
}
string[] header = file.GetCsvLine();
var translations = new List<Translation>();
for (int c = 1; c < header.Length; c++)
{
var t = new Translation { Locale = header[c] };
translations.Add(t);
}
while (!file.EofReached())
{
string[] row = file.GetCsvLine();
if (row.Length < 2 || row[0].Length == 0) continue;
for (int c = 1; c < row.Length && c - 1 < translations.Count; c++)
{
if (row[c].Length > 0) translations[c - 1].AddMessage(row[0], row[c]);
}
}
foreach (var t in translations) TranslationServer.AddTranslation(t);
TranslationServer.SetLocale(locale);
}
/// <summary>Traduce un testo dell'interfaccia (chiave = testo italiano).</summary>
public static string T(string italian) => TranslationServer.Translate(italian);
}
@@ -0,0 +1 @@
uid://bxob5yr4t8lu8
@@ -0,0 +1,43 @@
using Godot;
namespace ViaFerrea.Client.App;
/// <summary>Palette dell'immagine di riferimento 05: interfaccia blu-ardesia con accento ambra, mappa cartografica chiara.</summary>
public static class Palette
{
// interfaccia
public static readonly Color AppBackground = new("11181c");
public static readonly Color Panel = new("172127");
public static readonly Color Inner = new("1f2a30");
public static readonly Color Border = new("2c3a42");
public static readonly Color Text = new("dde3e6");
public static readonly Color TextSecondary = new("9fb0b8");
public static readonly Color Amber = new("e0a526");
public static readonly Color AmberLight = new("f0bd52");
public static readonly Color AmberDark = new("3a2c12");
public static readonly Color Workers = new("3f86d1");
public static readonly Color Staff = new("9cc9f2");
public static readonly Color Ok = new("5fc39b");
public static readonly Color Danger = new("b3573e");
// mappa
public static readonly Color Plain = new("cfd7bd");
public static readonly Color Hill = new("c0c8a6");
public static readonly Color Highland = new("aeb690");
public static readonly Color Undergrowth = new("9db38a");
public static readonly Color Canopy = new("5f8f4a");
public static readonly Color Water = new("8fb4c6");
public static readonly Color Banks = new("b9bf9c");
public static readonly Color Grain = new("d9c26a");
public static readonly Color TileRoof = new("b3573e");
public static readonly Color IndustrialRoof = new("7c8590");
public static readonly Color Ballast = new("bfb79f");
public static readonly Color Sleepers = new("5b4a39");
public static readonly Color Rails = new("3b3f42");
public static readonly Color Construction = new("8a7a52");
public static readonly Color Rock = new("9a9a8c");
public static readonly Color Marsh = new("a9bba0");
public static readonly Color Sea = new("86adc0");
public static Color WithAlpha(Color c, float a) => new(c.R, c.G, c.B, a);
}
@@ -0,0 +1 @@
uid://blsg133y5mi21
@@ -0,0 +1,144 @@
using Godot;
namespace ViaFerrea.Client.App;
/// <summary>
/// Tema dell'interfaccia costruito in codice dalla palette (immagine 05): titoli in Big Shoulders
/// Display 800, testo e numeri in IBM Plex Sans; raggio 8–12 px, bordi 1 px #2c3a42, nessuna ombra.
/// </summary>
public static class UiTheme
{
public static Font Body { get; private set; } = ThemeDB.FallbackFont;
public static Font BodyBold { get; private set; } = ThemeDB.FallbackFont;
public static Font Title { get; private set; } = ThemeDB.FallbackFont;
public static Theme Build()
{
Body = LoadFont("res://assets/fonts/IBMPlexSans-Regular.ttf");
BodyBold = LoadFont("res://assets/fonts/IBMPlexSans-SemiBold.ttf");
Title = LoadFont("res://assets/fonts/BigShouldersDisplay-ExtraBold.ttf");
var t = new Theme { DefaultFont = Body, DefaultFontSize = 14 };
foreach (string type in new[] { "Label", "Button", "LineEdit", "CheckBox", "OptionButton", "SpinBox", "ItemList", "PopupMenu", "TooltipLabel" })
{
t.SetColor("font_color", type, Palette.Text);
}
t.SetColor("font_color", "TooltipLabel", Palette.Text);
t.SetStylebox("panel", "TooltipPanel", Box(Palette.Inner, Palette.Border, 8, 8));
t.SetStylebox("panel", "PanelContainer", Box(Palette.Panel, Palette.Border, 10, 12));
t.SetStylebox("panel", "Panel", Box(Palette.Panel, Palette.Border, 0, 0));
var normal = Box(Palette.Panel, Palette.Border, 8, 10);
t.SetStylebox("normal", "Button", normal);
t.SetStylebox("hover", "Button", Box(Palette.Inner, Palette.TextSecondary, 8, 10));
t.SetStylebox("pressed", "Button", Box(Palette.Amber, Palette.Amber, 8, 10));
t.SetStylebox("disabled", "Button", Box(Palette.AppBackground, Palette.Border, 8, 10));
t.SetStylebox("focus", "Button", Box(new Color(0, 0, 0, 0), Palette.AmberLight, 8, 10));
t.SetColor("font_pressed_color", "Button", Palette.AppBackground);
t.SetColor("font_hover_color", "Button", Palette.Text);
t.SetColor("font_disabled_color", "Button", Palette.TextSecondary);
t.SetColor("font_hover_pressed_color", "Button", Palette.AppBackground);
t.SetStylebox("normal", "LineEdit", Box(Palette.Inner, Palette.Border, 8, 8));
t.SetStylebox("focus", "LineEdit", Box(Palette.Inner, Palette.Amber, 8, 8));
t.SetColor("caret_color", "LineEdit", Palette.Amber);
t.SetStylebox("panel", "ItemList", Box(Palette.Inner, Palette.Border, 8, 6));
t.SetColor("font_selected_color", "ItemList", Palette.AppBackground);
t.SetStylebox("selected", "ItemList", Box(Palette.Amber, Palette.Amber, 4, 4));
t.SetStylebox("selected_focus", "ItemList", Box(Palette.Amber, Palette.Amber, 4, 4));
t.SetStylebox("background", "ProgressBar", Box(Palette.Border, Palette.Border, 4, 0));
t.SetStylebox("fill", "ProgressBar", Box(Palette.Workers, Palette.Workers, 4, 0));
t.SetColor("font_color", "ProgressBar", Palette.Text);
return t;
}
/// <summary>Riquadro piatto con bordo di 1 px.</summary>
public static StyleBoxFlat Box(Color bg, Color border, int radius, int margin)
{
var s = new StyleBoxFlat { BgColor = bg, BorderColor = border };
s.SetBorderWidthAll(1);
s.SetCornerRadiusAll(radius);
s.ContentMarginLeft = margin;
s.ContentMarginRight = margin;
s.ContentMarginTop = margin * 0.6f;
s.ContentMarginBottom = margin * 0.6f;
return s;
}
/// <summary>Carica un font importato dall'editor oppure, in mancanza, direttamente dal file.</summary>
private static Font LoadFont(string path)
{
if (ResourceLoader.Exists(path))
{
var imported = ResourceLoader.Load<FontFile>(path);
if (imported is not null) return imported;
}
var font = new FontFile();
if (font.LoadDynamicFont(path) == Error.Ok) return font;
GD.PushWarning($"Font non trovato: {path}");
return ThemeDB.FallbackFont;
}
/// <summary>Etichetta con il font dei titoli.</summary>
public static Label TitleLabel(string text, int size, Color? color = null)
{
var l = new Label { Text = text };
l.AddThemeFontOverride("font", Title);
l.AddThemeFontSizeOverride("font_size", size);
l.AddThemeColorOverride("font_color", color ?? Palette.Text);
return l;
}
public static Label Text(string text, int size = 14, Color? color = null, bool bold = false)
{
var l = new Label { Text = text };
l.AddThemeFontOverride("font", bold ? BodyBold : Body);
l.AddThemeFontSizeOverride("font_size", size);
l.AddThemeColorOverride("font_color", color ?? Palette.Text);
return l;
}
/// <summary>Pulsante d'azione primaria (ambra).</summary>
public static Button Primary(string text)
{
var b = new Button { Text = text };
b.AddThemeStyleboxOverride("normal", Box(Palette.Amber, Palette.Amber, 8, 12));
b.AddThemeStyleboxOverride("hover", Box(Palette.AmberLight, Palette.AmberLight, 8, 12));
b.AddThemeColorOverride("font_color", Palette.AppBackground);
b.AddThemeColorOverride("font_hover_color", Palette.AppBackground);
b.AddThemeFontOverride("font", BodyBold);
return b;
}
/// <summary>Distintivo ambra (livello della compagnia, linea).</summary>
public static PanelContainer Badge(string text)
{
var p = new PanelContainer();
p.AddThemeStyleboxOverride("panel", Box(Palette.Amber, Palette.Amber, 4, 6));
var l = Text(text, 12, Palette.AppBackground, bold: true);
p.AddChild(l);
return p;
}
/// <summary>Etichetta di linea: ambra su fondo ambra scuro, su una riga (immagine 01).</summary>
public static PanelContainer LineBadge(string text)
{
var p = new PanelContainer();
p.AddThemeStyleboxOverride("panel", Box(Palette.AmberDark, Palette.AmberDark, 6, 10));
p.AddChild(Text(text, 13, Palette.AmberLight, bold: true));
return p;
}
/// <summary>Riquadro d'avviso ambra scuro (colli di bottiglia e opportunità).</summary>
public static PanelContainer Notice(string text)
{
var p = new PanelContainer();
p.AddThemeStyleboxOverride("panel", Box(Palette.AmberDark, Palette.AmberDark, 8, 12));
var l = Text(text, 13, Palette.AmberLight);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
p.AddChild(l);
return p;
}
}
@@ -0,0 +1 @@
uid://fvsnf1rxxhbh
@@ -0,0 +1,104 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Map;
using ViaFerrea.Core.Map;
using ViaFerrea.Protocol.Client;
namespace ViaFerrea.Client.Hud;
/// <summary>Minimappa: terreno ridotto, linee, città e rettangolo della vista; un clic centra la mappa.</summary>
public partial class Minimap : Control
{
private ClientWorld? _world;
private MapView? _map;
private ImageTexture? _texture;
private int _terrainVersion = -1;
public void Bind(ClientWorld world, MapView map)
{
_world = world;
_map = map;
_terrainVersion = -1;
CustomMinimumSize = new Vector2(0, 220);
MouseFilter = MouseFilterEnum.Stop;
}
public override void _Process(double delta)
{
if (_world?.Terrain is { } t && _world.TerrainVersion != _terrainVersion && Engine.GetProcessFrames() % 30 == 0)
{
_terrainVersion = _world.TerrainVersion;
int step = Math.Max(1, t.Width / 256);
int w = t.Width / step, h = t.Height / step;
var data = new byte[w * h * 4];
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
var type = (CellType)t.Types[y * step * t.Width + x * step];
var c = type switch
{
CellType.Sea => Palette.Sea,
CellType.Water => Palette.Water,
CellType.Forest => Palette.Undergrowth,
CellType.Town => Palette.TileRoof.Lightened(0.3f),
CellType.Mountain or CellType.Rock => Palette.Highland,
CellType.Hill => Palette.Hill,
_ => Palette.Plain,
};
int i = (y * w + x) * 4;
data[i] = (byte)(c.R * 255);
data[i + 1] = (byte)(c.G * 255);
data[i + 2] = (byte)(c.B * 255);
data[i + 3] = 255;
}
}
_texture = ImageTexture.CreateFromImage(Image.CreateFromData(w, h, false, Image.Format.Rgba8, data));
}
QueueRedraw();
}
private Rect2 MapRect()
{
var t = _world!.Terrain!;
float aspect = (float)t.Width / t.Height;
float w = Size.X, h = Size.X / aspect;
if (h > Size.Y)
{
h = Size.Y;
w = h * aspect;
}
return new Rect2((Size.X - w) / 2, (Size.Y - h) / 2, w, h);
}
public override void _Draw()
{
DrawStyleBox(UiTheme.Box(Palette.Inner, Palette.Border, 8, 0), new Rect2(Vector2.Zero, Size));
if (_world?.Terrain is not { } t || _texture is null || _map is null) return;
var r = MapRect();
DrawTextureRect(_texture, r, false);
float k = r.Size.X / (float)(t.Width * t.CellSizeM);
Vector2 P(Vector2 world) => r.Position + world * k;
foreach (var e in _world.Edges.Values)
{
if (e.S.Length < 2) continue;
DrawLine(P(MapScale.V(e.X[0], e.Y[0])), P(MapScale.V(e.X[^1], e.Y[^1])), new Color("2a2f2c"), 2);
}
foreach (var town in _world.Towns.Values) DrawCircle(P(MapScale.V(town.Position)), 3.5f, new Color("8a6a55"));
var view = _map.VisibleRect();
DrawRect(new Rect2(P(view.Position), view.Size * k), Palette.Amber, false, 2);
}
public override void _GuiInput(InputEvent e)
{
if (_world?.Terrain is not { } t || _map is null) return;
if (e is InputEventMouseButton { ButtonIndex: MouseButton.Left, Pressed: true } b || e is InputEventMouseMotion { ButtonMask: MouseButtonMask.Left })
{
var pos = e is InputEventMouse m ? m.Position : Vector2.Zero;
var r = MapRect();
float k = r.Size.X / (float)(t.Width * t.CellSizeM);
_map.CenterOn((pos - r.Position) / k);
AcceptEvent();
}
}
}
@@ -0,0 +1 @@
uid://ci04fqk4we7bk
@@ -0,0 +1,42 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Protocol.Messages;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Hud;
/// <summary>Notiziario in basso (immagine 01): «Notizie» e gli ultimi eventi che scorrono.</summary>
public partial class Ticker : PanelContainer
{
private readonly List<string> _items = [];
private readonly Label _text = UiTheme.Text("", 14);
private readonly Control _clip = new() { ClipContents = true, SizeFlagsHorizontal = SizeFlags.ExpandFill, CustomMinimumSize = new Vector2(0, 22) };
private float _offset;
public override void _Ready()
{
AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 0, 14));
var row = new HBoxContainer();
row.AddThemeConstantOverride("separation", 18);
AddChild(row);
row.AddChild(UiTheme.Text(T("Notizie"), 14, Palette.Amber, bold: true));
row.AddChild(_clip);
_clip.AddChild(_text);
}
public void Add(EventInfo e)
{
_items.Insert(0, e.Text);
if (_items.Count > 8) _items.RemoveAt(_items.Count - 1);
_text.Text = string.Join(" | ", _items);
}
public override void _Process(double delta)
{
if (_items.Count == 0) return;
_offset += (float)delta * 40f;
float width = _text.GetMinimumSize().X;
if (_offset > width) _offset = -_clip.Size.X;
_text.Position = new Vector2(-_offset, 0);
}
}
@@ -0,0 +1 @@
uid://c57cbfp1dm0qo
@@ -0,0 +1,139 @@
using Godot;
using ViaFerrea.Client.App;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Hud;
/// <summary>Strumenti e pannelli della barra sinistra (immagine 01).</summary>
public enum Tool { None, Track, Station, Signal, Depot, Trains, Lines, Market, Finance, Demolish }
/// <summary>Barra degli strumenti a sinistra: icone disegnate in codice con l'etichetta sotto.</summary>
public partial class Toolbar : PanelContainer
{
private readonly Dictionary<Tool, ToolButton> _buttons = [];
public event Action<Tool>? Selected;
public Tool Current { get; private set; }
public override void _Ready()
{
AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 0, 6));
CustomMinimumSize = new Vector2(88, 0);
var col = new VBoxContainer();
col.AddThemeConstantOverride("separation", 6);
AddChild(col);
foreach (var (tool, label) in new[]
{
(Tool.Track, "Binari"), (Tool.Station, "Stazione"), (Tool.Signal, "Segnali"), (Tool.Depot, "Deposito"),
(Tool.Trains, "Treni"), (Tool.Lines, "Linee"), (Tool.Market, "Mercato"), (Tool.Finance, "Finanze"), (Tool.Demolish, "Demolisci"),
})
{
var b = new ToolButton(tool, T(label));
b.Pressed += () => Select(Current == tool ? Tool.None : tool);
_buttons[tool] = b;
col.AddChild(b);
}
}
public void Select(Tool tool)
{
Current = tool;
foreach (var (t, b) in _buttons) b.Active = t == tool;
Selected?.Invoke(tool);
}
/// <summary>Pulsante con icona vettoriale.</summary>
private sealed partial class ToolButton : Button
{
private readonly Tool _tool;
private readonly string _label;
private bool _active;
public ToolButton(Tool tool, string label)
{
_tool = tool;
_label = label;
CustomMinimumSize = new Vector2(76, 72);
Flat = true;
TooltipText = label;
MouseEntered += QueueRedraw;
MouseExited += QueueRedraw;
}
public bool Active
{
get => _active;
set
{
_active = value;
QueueRedraw();
}
}
public override void _Draw()
{
if (_active) DrawStyleBox(UiTheme.Box(Palette.Inner, Palette.Inner, 8, 0), new Rect2(Vector2.Zero, Size));
else if (IsHovered()) DrawStyleBox(UiTheme.Box(Palette.Inner, Palette.Border, 8, 0), new Rect2(Vector2.Zero, Size));
var color = _active ? Palette.Amber : Palette.Text;
var c = new Vector2(Size.X / 2, 26);
DrawGlyph(c, color);
var font = _active ? UiTheme.BodyBold : UiTheme.Body;
var dims = font.GetStringSize(_label, HorizontalAlignment.Left, -1, 13);
DrawString(font, new Vector2((Size.X - dims.X) / 2, 60), _label, HorizontalAlignment.Left, -1, 13, color);
}
private void DrawGlyph(Vector2 c, Color col)
{
const float w = 2.2f;
switch (_tool)
{
case Tool.Track:
DrawLine(c + new Vector2(-5, -11), c + new Vector2(-5, 11), col, w);
DrawLine(c + new Vector2(5, -11), c + new Vector2(5, 11), col, w);
for (int i = -1; i <= 1; i++) DrawLine(c + new Vector2(-10, i * 7), c + new Vector2(10, i * 7), col, w);
break;
case Tool.Station:
DrawPolyline([c + new Vector2(-11, -1), c + new Vector2(0, -11), c + new Vector2(11, -1)], col, w);
DrawRect(new Rect2(c + new Vector2(-8, -1), new Vector2(16, 12)), col, false, w);
DrawRect(new Rect2(c + new Vector2(-2, 4), new Vector2(4, 7)), col, false, w);
break;
case Tool.Signal:
DrawCircle(c + new Vector2(0, -6), 5, col, false, w);
DrawLine(c + new Vector2(0, -1), c + new Vector2(0, 11), col, w);
DrawLine(c + new Vector2(-5, 11), c + new Vector2(5, 11), col, w);
break;
case Tool.Depot:
DrawPolyline([c + new Vector2(-11, 11), c + new Vector2(-11, -3), c + new Vector2(0, -11), c + new Vector2(11, -3), c + new Vector2(11, 11)], col, w);
DrawRect(new Rect2(c + new Vector2(-6, 1), new Vector2(12, 10)), col, false, w);
break;
case Tool.Trains:
DrawRect(new Rect2(c + new Vector2(-8, -11), new Vector2(16, 17)), col, false, w);
DrawLine(c + new Vector2(-8, -2), c + new Vector2(8, -2), col, w);
DrawLine(c + new Vector2(-5, 6), c + new Vector2(-8, 12), col, w);
DrawLine(c + new Vector2(5, 6), c + new Vector2(8, 12), col, w);
break;
case Tool.Lines:
DrawCircle(c + new Vector2(-8, -8), 3.5f, col, false, w);
DrawCircle(c + new Vector2(8, 8), 3.5f, col, false, w);
DrawPolyline([c + new Vector2(-4, -8), c + new Vector2(8, -8), c + new Vector2(8, -2), c + new Vector2(-8, 2), c + new Vector2(-8, 8), c + new Vector2(4, 8)], col, w);
break;
case Tool.Market:
DrawPolyline([c + new Vector2(-11, 8), c + new Vector2(-4, 0), c + new Vector2(2, 5), c + new Vector2(11, -7)], col, w);
DrawLine(c + new Vector2(-11, 11), c + new Vector2(11, 11), col, w);
break;
case Tool.Finance:
DrawArc(c + new Vector2(0, -7), 9, 0, MathF.Tau, 24, col, w);
DrawLine(c + new Vector2(-9, -7), c + new Vector2(-9, 7), col, w);
DrawLine(c + new Vector2(9, -7), c + new Vector2(9, 7), col, w);
DrawArc(c + new Vector2(0, 7), 9, 0, MathF.PI, 16, col, w);
break;
case Tool.Demolish:
DrawLine(c + new Vector2(-10, -8), c + new Vector2(10, -8), col, w);
DrawLine(c + new Vector2(-4, -11), c + new Vector2(4, -11), col, w);
DrawPolyline([c + new Vector2(-7, -8), c + new Vector2(-5, 11), c + new Vector2(5, 11), c + new Vector2(7, -8)], col, w);
break;
}
}
}
}
@@ -0,0 +1 @@
uid://bngg3p5mnbnru
@@ -0,0 +1,111 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Hud;
/// <summary>Barra superiore (immagine 01): compagnia e livello, data, velocità, cassa, patrimonio, rating, stato del server.</summary>
public partial class TopBar : PanelContainer
{
private GameSession? _session;
private readonly Label _company = UiTheme.TitleLabel("", 30);
private readonly PanelContainer _tier = UiTheme.Badge("");
private readonly Label _date = UiTheme.Text("", 17, bold: true);
private readonly Label _cash = UiTheme.Text("", 20, Palette.AmberLight, bold: true);
private readonly Label _worth = UiTheme.Text("", 20, bold: true);
private readonly Label _rating = UiTheme.Text("", 20, bold: true);
private readonly Label _server = UiTheme.Text("", 14);
private readonly ColorRect _serverDot = new() { CustomMinimumSize = new Vector2(10, 10) };
private readonly List<Button> _speeds = [];
public override void _Ready()
{
AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 0, 14));
CustomMinimumSize = new Vector2(0, 68);
var row = new HBoxContainer();
row.AddThemeConstantOverride("separation", 18);
AddChild(row);
row.AddChild(new Logo { CustomMinimumSize = new Vector2(40, 40) });
row.AddChild(_company);
var tierBox = new CenterContainer();
tierBox.AddChild(_tier);
row.AddChild(tierBox);
row.AddChild(new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill });
row.AddChild(_date);
var speeds = new HBoxContainer();
speeds.AddThemeConstantOverride("separation", 4);
foreach (byte speed in new byte[] { 0, 1, 2, 4, 8 })
{
var b = new Button { Text = speed == 0 ? "II" : $"{speed}×", ToggleMode = true, CustomMinimumSize = new Vector2(46, 40) };
b.Pressed += () => _session?.SetSpeed(speed);
b.TooltipText = speed == 0 ? T("Pausa") : T("Velocità");
_speeds.Add(b);
speeds.AddChild(b);
}
row.AddChild(speeds);
row.AddChild(new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill });
row.AddChild(Stat(T("Cassa"), _cash));
row.AddChild(Stat(T("Patrimonio netto"), _worth));
row.AddChild(Stat(T("Rating"), _rating));
var chip = new PanelContainer();
chip.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, Palette.Border, 16, 12));
var chipRow = new HBoxContainer();
chipRow.AddThemeConstantOverride("separation", 8);
var dotBox = new CenterContainer();
dotBox.AddChild(_serverDot);
chipRow.AddChild(dotBox);
chipRow.AddChild(_server);
chip.AddChild(chipRow);
var chipCenter = new CenterContainer();
chipCenter.AddChild(chip);
row.AddChild(chipCenter);
}
private static VBoxContainer Stat(string caption, Label value)
{
var box = new VBoxContainer();
box.AddThemeConstantOverride("separation", -2);
var c = UiTheme.Text(caption, 12, Palette.TextSecondary);
c.HorizontalAlignment = HorizontalAlignment.Right;
value.HorizontalAlignment = HorizontalAlignment.Right;
box.AddChild(c);
box.AddChild(value);
return box;
}
public void Bind(GameSession session) => _session = session;
public override void _Process(double delta)
{
var w = _session?.World;
if (w?.Summary is null) return;
var me = w.Companies.GetValueOrDefault(w.Summary.CompanyId);
_company.Text = me?.Name ?? w.Summary.CompanyName;
int tier = Math.Clamp(me?.Tier ?? 1, 1, w.Data.Tiers.Tiers.Count);
((Label)_tier.GetChild(0)).Text = TranslationServer.GetLocale().StartsWith("en") ? w.Data.Tiers.Tiers[tier - 1].NameEn : w.Data.Tiers.Tiers[tier - 1].NameIt;
_date.Text = w.LastDigest?.Date ?? w.Summary.Date;
_cash.Text = (w.LastDigest?.Cash ?? me?.Cash ?? default).ToString();
_worth.Text = (w.LastDigest?.NetWorth ?? me?.NetWorth ?? default).ToString("short");
_rating.Text = w.LastDigest?.Rating ?? me?.Rating ?? "—";
byte speed = _session!.RequestedSpeed ?? w.LastDigest?.Speed ?? w.Speed;
for (int i = 0; i < _speeds.Count; i++) _speeds[i].SetPressedNoSignal(new byte[] { 0, 1, 2, 4, 8 }[i] == speed);
bool open = _session!.IsOpen;
_serverDot.Color = !open ? Palette.Danger : w.LastDigest?.Slow == true ? Palette.Amber : Palette.Ok;
_server.Text = open ? $"{_session.ServerLabel} {_session.LatencyMs:0} ms" : T("Disconnesso");
}
/// <summary>Marchio: ruota stilizzata ambra (immagine 01).</summary>
private sealed partial class Logo : Control
{
public override void _Draw()
{
var c = Size / 2;
float r = Math.Min(Size.X, Size.Y) / 2 - 3;
DrawArc(c, r, 0, MathF.Tau, 48, Palette.Amber, 3, true);
DrawLine(c - new Vector2(r, 0), c + new Vector2(r, 0), Palette.Amber, 3);
DrawLine(c - new Vector2(0, r), c + new Vector2(0, r), Palette.Amber, 3);
DrawCircle(c, r * 0.28f, Palette.Amber);
}
}
}
@@ -0,0 +1 @@
uid://dgi7tae6dnp32
+150
View File
@@ -0,0 +1,150 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Client.Screens;
using ViaFerrea.Core.Data;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client;
/// <summary>
/// Nodo radice: tema e traduzioni, dati del gioco, passaggio tra menu, collegamento e partita;
/// alla chiusura termina la sessione e l'eventuale server locale.
/// </summary>
public partial class Main : Node
{
private const string SettingsPath = "user://settings.cfg";
private GameData? _data;
private Node? _screen;
private GameSession? _session;
private string? _autopilot;
public override void _Ready()
{
var cfg = new ConfigFile();
cfg.Load(SettingsPath);
string locale = (string)cfg.GetValue("ui", "locale", "it");
Localization.Load(locale);
GetWindow().Theme = UiTheme.Build();
GetWindow().Title = "Via Ferrea";
try
{
_data = GodotDataSource.LoadGameData();
}
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)
{
// 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("VF_MAP_SIZE", "64");
System.Environment.SetEnvironmentVariable("VF_SEED", "3");
System.Environment.SetEnvironmentVariable("VF_AUTOSAVE_MIN", "0");
StartLocal();
}
}
private void Swap(Node screen)
{
_screen?.QueueFree();
_screen = screen;
AddChild(screen);
}
private void ShowMenu(string status = "")
{
var menu = new MenuScreen();
menu.LocalGame += StartLocal;
menu.ConnectToServer += ShowConnect;
menu.LanguageChanged += code =>
{
var cfg = new ConfigFile();
cfg.Load(SettingsPath);
cfg.SetValue("ui", "locale", code);
cfg.Save(SettingsPath);
TranslationServer.SetLocale(code);
ShowMenu();
};
Swap(menu);
if (status.Length > 0) menu.SetStatus(status);
}
private void ShowConnect()
{
var screen = new ConnectScreen();
screen.Back += () => ShowMenu();
screen.ConnectRequested += async (uri, token, label) =>
{
if (_data is null) return;
screen.SetStatus(T("Collegamento in corso…"), busy: true);
try
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
var session = await GameSession.ConnectAsync(_data, uri, token, label, cts.Token);
ShowGame(session);
}
catch (Exception e)
{
screen.SetStatus($"{T("Collegamento non riuscito")}: {e.Message}", busy: false);
}
};
Swap(screen);
}
private async void StartLocal()
{
if (_data is null) return;
string? server = LocalServerLauncher.FindServer();
if (server is null)
{
ShowMenu(T("Server locale non trovato: compila src/ViaFerrea.Server o imposta VF_SERVER_PATH."));
return;
}
if (_screen is MenuScreen menu) menu.SetStatus(T("Avvio del server locale…"));
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);
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);
}
catch (Exception e)
{
launcher.Dispose();
ShowMenu($"{T("Partita locale non avviata")}: {e.Message}");
}
}
private void ShowGame(GameSession session)
{
_session = session;
var game = new GameScreen(session);
game.Exit += async () =>
{
var s = _session;
_session = null;
ShowMenu();
if (s is not null) await s.DisposeAsync();
};
Swap(game);
if (_autopilot is not null) game.AddChild(new AutoPilot(game, _autopilot));
}
public override void _Notification(int what)
{
if (what == NotificationWMCloseRequest && _session is not null)
{
_session.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(3));
_session = null;
}
}
}
@@ -0,0 +1 @@
uid://dva7myhv6o38v
@@ -0,0 +1,267 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Core.Map;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
namespace ViaFerrea.Client.Map;
/// <summary>
/// Entità sulla mappa (immagine 04): case con tetti in coppi sulle celle d'abitato, impronte
/// delle industrie per tipo, stazioni con marciapiedi e fabbricato, depositi, porto e valico;
/// alberi delle foreste con MultiMeshInstance2D per chunk.
/// </summary>
public partial class EntityLayer : Node2D
{
private ClientWorld? _world;
private int _drawnEntities = -1;
private int _drawnTerrain = -1;
private int _drawnTrack = -1;
private float _zoom = 1;
private readonly Dictionary<(int, int), MultiMeshInstance2D> _forests = [];
private Texture2D? _treeTexture;
public int SelectedStation { get; set; } = -1;
public void Bind(ClientWorld world)
{
_world = world;
foreach (var f in _forests.Values) f.QueueFree();
_forests.Clear();
_drawnEntities = _drawnTerrain = _drawnTrack = -1;
}
public void SetZoom(float zoom)
{
bool redraw = (zoom >= MapScale.OverviewZoom) != (_zoom >= MapScale.OverviewZoom);
_zoom = zoom;
if (redraw) QueueRedraw();
foreach (var f in _forests.Values) f.Visible = zoom >= 0.02f;
}
public void ForestChunk(int cx, int cy)
{
var w = _world;
if (w?.Terrain is null) return;
_treeTexture ??= TreeTexture();
var t = w.Terrain;
var trees = new List<Transform2D>();
var colors = new List<Color>();
int x0 = cx * t.ChunkCells, y0 = cy * t.ChunkCells;
for (int y = y0; y < Math.Min(t.Height, y0 + t.ChunkCells); y++)
{
for (int x = x0; x < Math.Min(t.Width, x0 + t.ChunkCells); x++)
{
if ((CellType)t.Types[y * t.Width + x] != CellType.Forest) continue;
uint h = (uint)(x * 73856093 ^ y * 19349663);
for (int k = 0; k < 5; k++)
{
h = h * 1664525 + 1013904223;
float jx = (h & 0xFFFF) / 65535f, jy = (h >> 16) / 65535f;
float r = (float)t.CellSizeM * (0.16f + 0.08f * ((h >> 8) & 7) / 7f);
var pos = new Vector2((float)((x + jx) * t.CellSizeM), (float)((y + jy) * t.CellSizeM));
trees.Add(new Transform2D(0, new Vector2(r * 2, r * 2), 0, pos));
colors.Add(Palette.Canopy.Lerp(new Color("7aa65a"), ((h >> 4) & 15) / 15f));
}
}
}
if (_forests.Remove((cx, cy), out var old)) old.QueueFree();
if (trees.Count == 0) return;
var mesh = new MultiMesh
{
TransformFormat = MultiMesh.TransformFormatEnum.Transform2D,
UseColors = true,
Mesh = new QuadMesh { Size = Vector2.One },
InstanceCount = trees.Count,
};
for (int i = 0; i < trees.Count; i++)
{
mesh.SetInstanceTransform2D(i, trees[i]);
mesh.SetInstanceColor(i, colors[i]);
}
var node = new MultiMeshInstance2D { Multimesh = mesh, Texture = _treeTexture, ZIndex = 3 };
AddChild(node);
_forests[(cx, cy)] = node;
}
/// <summary>Chioma d'albero: disco con bordo più scuro (immagine 02).</summary>
private static Texture2D TreeTexture()
{
const int n = 64;
var img = Image.CreateEmpty(n, n, false, Image.Format.Rgba8);
for (int y = 0; y < n; y++)
{
for (int x = 0; x < n; x++)
{
float dx = (x + 0.5f) / n * 2 - 1, dy = (y + 0.5f) / n * 2 - 1;
float d = MathF.Sqrt(dx * dx + dy * dy);
if (d > 1) { img.SetPixel(x, y, new Color(0, 0, 0, 0)); continue; }
float light = 1.05f - 0.25f * Math.Clamp(dx + dy + 0.3f, 0, 1) - (d > 0.82f ? 0.25f : 0);
img.SetPixel(x, y, new Color(light, light, light, 1));
}
}
return ImageTexture.CreateFromImage(img);
}
public override void _Process(double delta)
{
if (_world is null) return;
if (_world.EntityVersion != _drawnEntities || _world.TerrainVersion != _drawnTerrain || _world.TrackVersion != _drawnTrack) QueueRedraw();
}
public override void _Draw()
{
var w = _world;
if (w?.Terrain is null) return;
_drawnEntities = w.EntityVersion;
_drawnTerrain = w.TerrainVersion;
_drawnTrack = w.TrackVersion;
var t = w.Terrain;
float cs = (float)t.CellSizeM;
// case: blocchi per cella d'abitato, disposizione fissa per cella
foreach (var town in w.Towns.Values)
{
int r = (int)Math.Ceiling(town.RadiusCells) + 1;
var (tcx, tcy) = t.CellAt(town.Position);
for (int y = tcy - r; y <= tcy + r; y++)
{
for (int x = tcx - r; x <= tcx + r; x++)
{
if (x < 0 || y < 0 || x >= t.Width || y >= t.Height || (CellType)t.Types[y * t.Width + x] != CellType.Town) continue;
DrawHouses(x, y, cs);
}
}
}
foreach (var ind in w.Industries.Values) DrawIndustry(ind, cs);
foreach (var hub in w.Hubs.Values) DrawHub(hub, cs);
foreach (var d in w.Depots.Values) DrawDepot(w, d);
foreach (var st in w.Stations.Values) DrawStation(w, st);
}
private void DrawHouses(int x, int y, float cs)
{
uint h = (uint)(x * 2654435761u ^ y * 40503u);
int count = 3 + (int)(h % 3);
for (int k = 0; k < count; k++)
{
h = h * 1664525 + 1013904223;
float fx = (h & 1023) / 1023f * 0.62f + 0.06f, fy = ((h >> 10) & 1023) / 1023f * 0.62f + 0.06f;
float wpx = cs * (0.18f + ((h >> 20) & 7) * 0.02f), hpx = cs * (0.13f + ((h >> 23) & 7) * 0.015f);
var rect = new Rect2(x * cs + fx * cs, y * cs + fy * cs, wpx, hpx);
var roof = ((h >> 26) & 3) switch { 0 => Palette.IndustrialRoof.Lightened(0.15f), 1 => new Color("a8836a"), _ => Palette.TileRoof };
DrawRect(new Rect2(rect.Position + new Vector2(cs * 0.02f, cs * 0.02f), rect.Size), new Color(0, 0, 0, 0.18f));
DrawRect(rect, roof);
DrawLine(rect.Position + new Vector2(0, rect.Size.Y / 2), rect.Position + new Vector2(rect.Size.X, rect.Size.Y / 2), roof.Darkened(0.25f), cs * 0.012f);
}
}
private void DrawIndustry(IndustryInfo ind, float cs)
{
float size = Math.Max(1, ind.FootprintCells) * cs;
var c = MapScale.V(ind.Position);
var pad = new Rect2(c - new Vector2(size, size) * 0.45f, new Vector2(size, size) * 0.9f);
var ground = ind.Closed ? new Color("b8b4a6") : new Color("bdb6a2");
DrawRect(pad, ground);
DrawRect(pad, new Color("8f8a7a"), false, cs * 0.03f);
string type = ind.Type;
if (type.Contains("mine") || type.Contains("quarry") || type.Contains("well"))
{
DrawCircle(c, size * 0.28f, new Color("6b5e4f"));
DrawCircle(c, size * 0.18f, new Color("3d3630"));
DrawRect(new Rect2(c + new Vector2(size * 0.12f, -size * 0.38f), new Vector2(size * 0.22f, size * 0.14f)), Palette.IndustrialRoof);
}
else if (type.Contains("farm") || type.Contains("ranch") || type.Contains("logging"))
{
DrawRect(new Rect2(c - new Vector2(size * 0.3f, size * 0.2f), new Vector2(size * 0.32f, size * 0.22f)), Palette.TileRoof);
DrawCircle(c + new Vector2(size * 0.2f, -size * 0.1f), size * 0.08f, new Color("9a9a90"));
}
else
{
// capannoni con lucernari (immagine 04)
int sheds = Math.Max(2, ind.FootprintCells);
float sw = size * 0.8f / sheds;
for (int i = 0; i < sheds; i++)
{
var r = new Rect2(pad.Position + new Vector2(size * 0.05f + i * sw, size * 0.08f), new Vector2(sw * 0.92f, size * 0.55f));
DrawRect(new Rect2(r.Position + new Vector2(cs * 0.04f, cs * 0.04f), r.Size), new Color(0, 0, 0, 0.2f));
DrawRect(r, Palette.IndustrialRoof);
DrawLine(r.Position + new Vector2(r.Size.X / 2, 0), r.Position + new Vector2(r.Size.X / 2, r.Size.Y), Palette.IndustrialRoof.Darkened(0.3f), cs * 0.02f);
}
DrawCircle(pad.Position + new Vector2(size * 0.78f, size * 0.75f), size * 0.07f, new Color("6e7175"));
}
if (ind.Closed) DrawLine(pad.Position, pad.End, Palette.Danger, cs * 0.05f);
}
private void DrawHub(HubInfo hub, float cs)
{
var c = MapScale.V(hub.Position);
if (hub.Kind == "port")
{
DrawRect(new Rect2(c - new Vector2(cs * 0.9f, cs * 0.35f), new Vector2(cs * 1.8f, cs * 0.7f)), new Color("9d968a"));
DrawRect(new Rect2(c + new Vector2(cs * 0.2f, -cs * 0.15f), new Vector2(cs * 1.2f, cs * 0.3f)), new Color("4b5560"));
}
else
{
DrawRect(new Rect2(c - new Vector2(cs * 0.4f, cs * 0.25f), new Vector2(cs * 0.8f, cs * 0.5f)), Palette.IndustrialRoof);
for (int i = 0; i < 6; i++)
DrawLine(c + new Vector2(-cs * 0.6f + i * cs * 0.2f, cs * 0.4f), c + new Vector2(-cs * 0.5f + i * cs * 0.2f, cs * 0.4f), i % 2 == 0 ? Palette.Danger : Colors.White, cs * 0.06f);
}
}
/// <summary>Direzione del binario che entra nel nodo (per orientare marciapiedi e fabbricati).</summary>
private static Vector2 NodeDirection(ClientWorld w, int nodeId)
{
if (nodeId < 0 || nodeId >= w.Network.Nodes.Count) return Vector2.Right;
var node = w.Network.Nodes[nodeId];
foreach (var eid in node.Edges)
{
if (!w.Edges.TryGetValue(eid.Value, out var e) || e.S.Length < 2) continue;
bool atA = e.A == nodeId;
var p0 = atA ? MapScale.V(e.X[0], e.Y[0]) : MapScale.V(e.X[^1], e.Y[^1]);
var p1 = atA ? MapScale.V(e.X[1], e.Y[1]) : MapScale.V(e.X[^2], e.Y[^2]);
var d = p1 - p0;
if (d.LengthSquared() > 0) return atA ? d.Normalized() : -d.Normalized();
}
return Vector2.Right;
}
private void DrawStation(ClientWorld w, StationInfo st)
{
float s = MapScale.Symbol(_zoom);
var c = MapScale.V(st.Position);
var dir = NodeDirection(w, st.Node);
var n = new Vector2(-dir.Y, dir.X);
float len = 60f * Math.Max(1, s * 0.6f);
float pw = 3.5f * s;
// marciapiedi ai lati dei binari (immagine 02) e fabbricato con tetto in coppi
for (int k = 0; k < Math.Min(st.Platforms, 4); k++)
{
float side = (k % 2 == 0 ? 1 : -1) * (7f + 6f * (k / 2)) * s;
DrawLine(c - dir * len / 2 + n * side, c + dir * len / 2 + n * side, new Color("d9d4c6"), pw);
}
var b = c + n * 15f * s;
DrawSetTransform(b, dir.Angle());
DrawRect(new Rect2(new Vector2(-12, -5.5f) * s + new Vector2(1.5f, 1.5f) * s, new Vector2(24, 11) * s), new Color(0, 0, 0, 0.2f));
DrawRect(new Rect2(new Vector2(-12, -5.5f) * s, new Vector2(24, 11) * s), Palette.TileRoof);
DrawLine(new Vector2(-12, 0) * s, new Vector2(12, 0) * s, Palette.TileRoof.Darkened(0.3f), 0.8f * s);
DrawSetTransform(Vector2.Zero, 0);
if (st.Id == SelectedStation)
{
float radius = (float)(w.Data.Construction.Stations.CatchmentKm * 1000);
DrawArc(c, radius, 0, MathF.Tau, 96, Palette.Amber, 2f * s);
}
}
private void DrawDepot(ClientWorld w, DepotInfo d)
{
float s = MapScale.Symbol(_zoom);
var c = MapScale.V(d.Position);
var dir = NodeDirection(w, d.Node);
DrawSetTransform(c, dir.Angle());
DrawRect(new Rect2(new Vector2(-16, -9) * s + new Vector2(2, 2) * s, new Vector2(32, 18) * s), new Color(0, 0, 0, 0.2f));
DrawRect(new Rect2(new Vector2(-16, -9) * s, new Vector2(32, 18) * s), new Color("5a6670"));
for (int i = -1; i <= 1; i++) DrawLine(new Vector2(-14, i * 5) * s, new Vector2(14, i * 5) * s, new Color("8a96a0"), 1f * s);
DrawSetTransform(Vector2.Zero, 0);
}
}
@@ -0,0 +1 @@
uid://b3e42tuyvbw27
@@ -0,0 +1,105 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Core.Common;
using ViaFerrea.Protocol.Client;
namespace ViaFerrea.Client.Map;
/// <summary>
/// Etichette a dimensione costante sullo schermo: città in Big Shoulders Display con gli abitanti,
/// industrie e stazioni in IBM Plex Sans; scala grafica in basso a destra (immagine 01).
/// </summary>
public partial class LabelLayer : Control
{
private ClientWorld? _world;
private Camera2D? _camera;
public void Bind(ClientWorld world, Camera2D camera)
{
_world = world;
_camera = camera;
MouseFilter = MouseFilterEnum.Ignore;
SetAnchorsPreset(LayoutPreset.FullRect);
}
public override void _Process(double delta) => QueueRedraw();
private Vector2 ToScreen(Vector2 world)
{
var vt = GetViewport().GetCanvasTransform();
return vt * world;
}
public override void _Draw()
{
var w = _world;
if (w?.Terrain is null || _camera is null) return;
float zoom = _camera.Zoom.X;
var size = GetViewportRect().Size;
bool InView(Vector2 p) => p.X > -200 && p.Y > -100 && p.X < size.X + 200 && p.Y < size.Y + 100;
foreach (var town in w.Towns.Values)
{
var p = ToScreen(MapScale.V(town.Position));
if (!InView(p)) continue;
int titleSize = town.Population >= 10000 ? 30 : town.Population >= 3000 ? 26 : 22;
Centered(UiTheme.Title, town.Name, p + new Vector2(0, -6), titleSize, new Color("2a2f2c"), outline: true);
Centered(UiTheme.Body, $"{Money.GroupThousands((ulong)town.Population)} {Localization.T("abitanti")}", p + new Vector2(0, 12), 13, new Color("3d4440"), outline: true);
}
if (zoom >= 0.02f)
{
foreach (var ind in w.Industries.Values)
{
var p = ToScreen(MapScale.V(ind.Position) + new Vector2(0, (float)(ind.FootprintCells * w.Terrain.CellSizeM * 0.5)));
if (!InView(p)) continue;
Centered(UiTheme.BodyBold, ind.Name, p + new Vector2(0, 14), 13, new Color("2a2f2c"), outline: true);
}
foreach (var hub in w.Hubs.Values)
{
var p = ToScreen(MapScale.V(hub.Position));
if (!InView(p)) continue;
Centered(UiTheme.BodyBold, hub.Name, p + new Vector2(0, 26), 13, new Color("2a2f2c"), outline: true);
Centered(UiTheme.Body, Localization.T("hub mercato mondiale"), p + new Vector2(0, 42), 12, new Color("3d4440"), outline: true);
}
}
foreach (var st in w.Stations.Values)
{
var p = ToScreen(MapScale.V(st.Position));
if (!InView(p)) continue;
Centered(UiTheme.Body, st.Name, p + new Vector2(0, -18), 12, new Color("2a2f2c"), outline: true);
}
foreach (var d in w.Depots.Values)
{
var p = ToScreen(MapScale.V(d.Position));
if (!InView(p)) continue;
Centered(UiTheme.BodyBold, Localization.T("Deposito"), p + new Vector2(0, 26), 12, new Color("2a2f2c"), outline: true);
}
DrawScaleBar(size, zoom);
}
private void Centered(Font font, string text, Vector2 at, int size, Color color, bool outline)
{
var dims = font.GetStringSize(text, HorizontalAlignment.Left, -1, size);
var pos = at - new Vector2(dims.X / 2, 0);
if (outline) DrawStringOutline(font, pos, text, HorizontalAlignment.Left, -1, size, 4, new Color(0.86f, 0.88f, 0.82f, 0.85f));
DrawString(font, pos, text, HorizontalAlignment.Left, -1, size, color);
}
/// <summary>Scala grafica con una lunghezza «tonda» di circa 100 px.</summary>
private void DrawScaleBar(Vector2 size, float zoom)
{
double meters = 100 / zoom;
double[] nice = [50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000];
double m = nice.FirstOrDefault(v => v >= meters, nice[^1]);
float px = (float)(m * zoom);
var end = new Vector2(size.X - 30, size.Y - 60);
var start = end - new Vector2(px, 0);
var c = new Color("2a2f2c");
DrawLine(start, end, c, 2);
DrawLine(start, start + new Vector2(0, -8), c, 2);
DrawLine(end, end + new Vector2(0, -8), c, 2);
DrawLine((start + end) / 2, (start + end) / 2 + new Vector2(0, -5), c, 2);
string label = m >= 1000 ? $"{m / 1000:0} km" : $"{m:0} m";
Centered(UiTheme.Body, label, (start + end) / 2 + new Vector2(0, 18), 12, c, outline: true);
}
}
@@ -0,0 +1 @@
uid://b843xbckahtip
@@ -0,0 +1,66 @@
using Godot;
using ViaFerrea.Core.Common;
namespace ViaFerrea.Client.Map;
/// <summary>
/// Scala dei simboli: a zoom ravvicinato binari e treni hanno le misure della guida in metri
/// (1 unità = 1 m: rotaie a ±2,4, traversine ogni 5,3, carro 16); allontanandosi i simboli si
/// ingrandiscono per restare leggibili come nell'immagine 01. LOD sotto 0,4 e 0,15.
/// </summary>
public static class MapScale
{
public const float DetailZoom = 0.4f;
public const float OverviewZoom = 0.15f;
public const float ContourMinZoom = 1.0f;
/// <summary>Moltiplicatore dei simboli per lo zoom (pixel per metro).</summary>
/// <remarks>
/// Tarata sui riferimenti: nell'immagine 01 (circa 0,02 px/m) un carro è lungo ~16 px, nella 02
/// (circa 0,6 px/m) ~70 px: pixel per unità = 5,5·zoom^0,44, cioè unità di mondo = 5,5·zoom^−0,56.
/// </remarks>
public static float Symbol(float zoom) => Math.Max(1f, 5.5f * MathF.Pow(Math.Max(zoom, 0.001f), -0.56f));
public static Vector2 V(Vec2 p) => new((float)p.X, (float)p.Y);
public static Vector2 V(double x, double y) => new((float)x, (float)y);
public static Vec2 W(Vector2 p) => new(p.X, p.Y);
/// <summary>Polilinea spostata lateralmente di offset (normale media ai vertici).</summary>
public static Vector2[] Offset(Vector2[] pts, float offset)
{
var result = new Vector2[pts.Length];
for (int i = 0; i < pts.Length; i++)
{
Vector2 dir;
if (i == 0) dir = pts[1] - pts[0];
else if (i == pts.Length - 1) dir = pts[i] - pts[i - 1];
else dir = (pts[i + 1] - pts[i - 1]);
dir = dir.LengthSquared() > 0 ? dir.Normalized() : Vector2.Right;
result[i] = pts[i] + new Vector2(-dir.Y, dir.X) * offset;
}
return result;
}
/// <summary>Punti e direzioni ogni «step» metri lungo una polilinea.</summary>
public static IEnumerable<(Vector2 Point, Vector2 Dir)> Every(Vector2[] pts, float step, float start = 0)
{
float next = start;
float acc = 0;
for (int i = 0; i < pts.Length - 1; i++)
{
var a = pts[i];
var b = pts[i + 1];
float len = a.DistanceTo(b);
if (len <= 0) continue;
var dir = (b - a) / len;
while (next <= acc + len)
{
yield return (a + dir * (next - acc), dir);
next += step;
}
acc += len;
}
}
}
@@ -0,0 +1 @@
uid://cb6evw1enekmi
@@ -0,0 +1,145 @@
using Godot;
using ViaFerrea.Client.Net;
namespace ViaFerrea.Client.Map;
/// <summary>
/// Vista della mappa: Node2D con Camera2D e i livelli (terreno, opere e binari, entità, treni,
/// strumenti). Rotella = zoom attorno al cursore, tasto destro o centrale = spostamento,
/// WASD/frecce = spostamento da tastiera. Coordinate del mondo in metri (1 unità = 1 m).
/// </summary>
public partial class MapView : Node2D
{
public const float MinZoom = 0.008f;
public const float MaxZoom = 6f;
public Camera2D Camera { get; } = new();
public TerrainLayer Terrain { get; } = new() { ZIndex = 0 };
public TrackLayer Track { get; } = new() { ZIndex = 2 };
public EntityLayer Entities { get; } = new() { ZIndex = 1 };
public TrainLayer Trains { get; } = new() { ZIndex = 5 };
public ToolOverlay Tools { get; } = new() { ZIndex = 8 };
/// <summary>Clic sinistro sulla mappa (posizione nel mondo).</summary>
public event Action<Vector2>? Clicked;
/// <summary>Clic destro senza trascinamento (annulla lo strumento).</summary>
public event Action? Cancelled;
/// <summary>Spostamento del mouse sulla mappa (posizione nel mondo).</summary>
public event Action<Vector2>? Hovered;
private bool _dragging;
private Vector2 _dragDistance;
private float _lastZoom = -1;
public override void _Ready()
{
AddChild(Terrain);
AddChild(Entities);
AddChild(Track);
AddChild(Trains);
AddChild(Tools);
AddChild(Camera);
Camera.Enabled = true;
Camera.MakeCurrent();
}
public void Bind(GameSession session)
{
Terrain.Bind(session.World);
Track.Bind(session.World);
Entities.Bind(session.World);
Trains.Bind(session);
Tools.Bind(session.World);
var t = session.World.Summary!;
Camera.Position = new Vector2((float)(t.WidthCells * t.CellSizeM / 2), (float)(t.HeightCells * t.CellSizeM / 2));
float fit = (float)(GetViewportRect().Size.X / (t.WidthCells * t.CellSizeM));
SetZoom(Math.Clamp(fit * 2.5f, MinZoom, MaxZoom));
}
public float Zoom => Camera.Zoom.X;
public void SetZoom(float zoom)
{
zoom = Math.Clamp(zoom, MinZoom, MaxZoom);
Camera.Zoom = new Vector2(zoom, zoom);
}
public void CenterOn(Vector2 world) => Camera.Position = world;
/// <summary>Rettangolo del mondo visibile.</summary>
public Rect2 VisibleRect()
{
var size = GetViewportRect().Size / Zoom;
return new Rect2(Camera.GetScreenCenterPosition() - size / 2, size);
}
public override void _Process(double delta)
{
var move = Vector2.Zero;
if (Input.IsKeyPressed(Key.W) || Input.IsKeyPressed(Key.Up)) move.Y -= 1;
if (Input.IsKeyPressed(Key.S) || Input.IsKeyPressed(Key.Down)) move.Y += 1;
if (Input.IsKeyPressed(Key.A) || Input.IsKeyPressed(Key.Left)) move.X -= 1;
if (Input.IsKeyPressed(Key.D) || Input.IsKeyPressed(Key.Right)) move.X += 1;
if (move != Vector2.Zero && GetViewport().GuiGetFocusOwner() is not LineEdit)
Camera.Position += move.Normalized() * (float)delta * 700f / Zoom;
if (Math.Abs(Zoom - _lastZoom) > 1e-6)
{
_lastZoom = Zoom;
Terrain.SetZoom(Zoom);
Track.SetZoom(Zoom);
Entities.SetZoom(Zoom);
Trains.SetZoom(Zoom);
Tools.SetZoom(Zoom);
}
}
public override void _UnhandledInput(InputEvent e)
{
switch (e)
{
case InputEventMouseButton { ButtonIndex: MouseButton.WheelUp, Pressed: true } wheel:
ZoomAt(wheel.Position, 1.15f);
GetViewport().SetInputAsHandled();
break;
case InputEventMouseButton { ButtonIndex: MouseButton.WheelDown, Pressed: true } wheel:
ZoomAt(wheel.Position, 1 / 1.15f);
GetViewport().SetInputAsHandled();
break;
case InputEventMouseButton { ButtonIndex: MouseButton.Right or MouseButton.Middle } b:
if (b.Pressed)
{
_dragging = true;
_dragDistance = Vector2.Zero;
}
else
{
_dragging = false;
if (b.ButtonIndex == MouseButton.Right && _dragDistance.Length() < 4) Cancelled?.Invoke();
}
GetViewport().SetInputAsHandled();
break;
case InputEventMouseButton { ButtonIndex: MouseButton.Left, Pressed: true }:
Clicked?.Invoke(GetGlobalMousePosition());
GetViewport().SetInputAsHandled();
break;
case InputEventMouseMotion motion:
if (_dragging)
{
Camera.Position -= motion.Relative / Zoom;
_dragDistance += motion.Relative;
}
Hovered?.Invoke(GetGlobalMousePosition());
break;
}
}
private void ZoomAt(Vector2 screen, float factor)
{
var before = GetCanvasTransform().AffineInverse() * screen;
SetZoom(Zoom * factor);
// la camera si sposta perché il punto sotto il cursore resti fermo
var size = GetViewportRect().Size;
var offset = (screen - size / 2) / Zoom;
Camera.Position = before - offset;
}
}
@@ -0,0 +1 @@
uid://3frpv33rahht
@@ -0,0 +1,202 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Core.Map;
using ViaFerrea.Protocol.Client;
namespace ViaFerrea.Client.Map;
/// <summary>
/// Terreno a chunk (immagine 01): colori per tipo di cella e fascia altimetrica, ombreggiatura
/// con luce da nord-ovest (ombre verso sud-est), sponde chiare lungo l'acqua, campi a strisce;
/// curve di livello ogni 20 m su una texture separata visibile oltre lo zoom 1.
/// </summary>
public partial class TerrainLayer : Node2D
{
private const float ContourStepM = 20f;
private readonly Dictionary<(int, int), (Sprite2D Base, Sprite2D Contours)> _sprites = [];
private readonly Queue<(int, int)> _dirty = new();
private readonly HashSet<(int, int)> _queued = [];
private ClientWorld? _world;
public void Bind(ClientWorld world)
{
_world = world;
foreach (var (b, c) in _sprites.Values)
{
b.QueueFree();
c.QueueFree();
}
_sprites.Clear();
_dirty.Clear();
_queued.Clear();
}
/// <summary>Segna un chunk (e i vicini, per la continuità dell'ombreggiatura) da ridisegnare.</summary>
public void MarkDirty(int cx, int cy)
{
for (int dy = -1; dy <= 1; dy++)
{
for (int dx = -1; dx <= 1; dx++)
{
var key = (cx + dx, cy + dy);
if (_world is null || !_world.Chunks.Contains(key) || !_queued.Add(key)) continue;
_dirty.Enqueue(key);
}
}
}
public void SetZoom(float zoom)
{
bool contours = zoom >= MapScale.ContourMinZoom;
foreach (var (_, c) in _sprites.Values) c.Visible = contours;
}
public override void _Process(double delta)
{
// pochi chunk per fotogramma: l'ingresso in partita resta fluido
for (int i = 0; i < 6 && _dirty.Count > 0; i++)
{
var key = _dirty.Dequeue();
_queued.Remove(key);
Build(key.Item1, key.Item2);
}
}
private void Build(int cx, int cy)
{
var w = _world;
if (w?.Terrain is null || w.Sampler is null) return;
var t = w.Terrain;
int ppc = t.Width <= 700 ? 4 : t.Width <= 1300 ? 2 : 1;
int x0 = cx * t.ChunkCells, y0 = cy * t.ChunkCells;
int cellsW = Math.Min(t.ChunkCells, t.Width - x0), cellsH = Math.Min(t.ChunkCells, t.Height - y0);
int pw = cellsW * ppc, ph = cellsH * ppc;
var pixels = new byte[pw * ph * 4];
var contour = new byte[pw * ph * 4];
double cs = t.CellSizeM, px = cs / ppc;
// per cella (con un bordo): ombreggiatura dalle differenze centrali e indicatore d'acqua
int gw = cellsW + 3, gh = cellsH + 3;
var shade = new float[gw * gh];
var water = new float[gw * gh];
for (int gy = 0; gy < gh; gy++)
{
for (int gx = 0; gx < gw; gx++)
{
int x = Math.Clamp(x0 + gx - 1, 0, t.Width - 1), y = Math.Clamp(y0 + gy - 1, 0, t.Height - 1);
double hx = (H(t, x + 1, y) - H(t, x - 1, y)) / (2 * cs);
double hy = (H(t, x, y + 1) - H(t, x, y - 1)) / (2 * cs);
// luce da nord-ovest: i pendii rivolti a sud-est si scuriscono
shade[gy * gw + gx] = (float)Math.Clamp(1.0 - (hx + hy) * 1.8, 0.80, 1.12);
water[gy * gw + gx] = IsWater((CellType)t.Types[y * t.Width + x]) ? 1f : 0f;
}
}
var corner = new Color[4];
for (int y = 0; y < ph; y++)
{
for (int x = 0; x < pw; x++)
{
// posizione in celle rispetto ai centri: interpolazione bilineare tra quattro celle
double fx = (x + 0.5) / ppc - 0.5, fy = (y + 0.5) / ppc - 0.5;
int ix = (int)Math.Floor(fx), iy = (int)Math.Floor(fy);
float tx = (float)(fx - ix), ty = (float)(fy - iy);
int g00 = (iy + 1) * gw + ix + 1;
float wv = Bilinear(water[g00], water[g00 + 1], water[g00 + gw], water[g00 + gw + 1], tx, ty);
float sh = Bilinear(shade[g00], shade[g00 + 1], shade[g00 + gw], shade[g00 + gw + 1], tx, ty);
double h = w.Sampler.HeightAt(x0 * cs + (x + 0.5) * px, y0 * cs + (y + 0.5) * px);
for (int k = 0; k < 4; k++)
{
int cxCell = Math.Clamp(x0 + ix + (k & 1), 0, t.Width - 1), cyCell = Math.Clamp(y0 + iy + (k >> 1), 0, t.Height - 1);
corner[k] = BaseColor((CellType)t.Types[cyCell * t.Width + cxCell], h, cxCell, cyCell, x, y, ppc);
}
var c = corner[0].Lerp(corner[1], tx).Lerp(corner[2].Lerp(corner[3], tx), ty);
if (wv < 0.5f) c = new Color(c.R * sh, c.G * sh, c.B * sh);
SetPixel(pixels, pw, x, y, new Color(c.R, c.G, c.B, wv));
if (wv < 0.5f)
{
double hR = w.Sampler.HeightAt(x0 * cs + (x + 1.5) * px, y0 * cs + (y + 0.5) * px);
double hD = w.Sampler.HeightAt(x0 * cs + (x + 0.5) * px, y0 * cs + (y + 1.5) * px);
int band = (int)Math.Floor(h / ContourStepM);
if (band != (int)Math.Floor(hR / ContourStepM) || band != (int)Math.Floor(hD / ContourStepM))
SetPixel(contour, pw, x, y, new Color(0.25f, 0.27f, 0.22f, (band % 5 == 0) ? 0.45f : 0.22f));
}
}
}
var key = (cx, cy);
if (!_sprites.TryGetValue(key, out var pair))
{
pair = (NewSprite(), NewSprite());
pair.Base.Material = TerrainMaterial();
AddChild(pair.Base);
AddChild(pair.Contours);
pair.Contours.ZIndex = 1;
_sprites[key] = pair;
}
foreach (var (sprite, data) in new[] { (pair.Base, pixels), (pair.Contours, contour) })
{
sprite.Texture = ImageTexture.CreateFromImage(Image.CreateFromData(pw, ph, false, Image.Format.Rgba8, data));
sprite.Position = new Vector2((float)(x0 * cs), (float)(y0 * cs));
sprite.Scale = new Vector2((float)px, (float)px);
}
pair.Contours.Visible = GetViewport().GetCamera2D() is { } cam && cam.Zoom.X >= MapScale.ContourMinZoom;
}
private static ShaderMaterial? _material;
private static ShaderMaterial TerrainMaterial()
{
if (_material is not null) return _material;
var shader = ResourceLoader.Load<Shader>("res://assets/shaders/terrain.gdshader");
_material = new ShaderMaterial { Shader = shader };
_material.SetShaderParameter("bank_color", Palette.Banks);
return _material;
}
private static double H(Terrain t, int x, int y) => t.CellHeightM(Math.Clamp(x, 0, t.Width - 1), Math.Clamp(y, 0, t.Height - 1));
private static float Bilinear(float a, float b, float c, float d, float tx, float ty) => (a + (b - a) * tx) + ((c + (d - c) * tx) - (a + (b - a) * tx)) * ty;
private static Sprite2D NewSprite() => new() { Centered = false, TextureFilter = TextureFilterEnum.Linear };
private static bool IsWater(CellType type) => type is CellType.Water or CellType.Sea;
private static Color BaseColor(CellType type, double h, int cellX, int cellY, int x, int y, int ppc)
{
switch (type)
{
case CellType.Sea: return Palette.Sea;
case CellType.Water: return Palette.Water;
case CellType.Marsh: return (x + y) % 6 < 2 ? Palette.Water.Lerp(Palette.Marsh, 0.6f) : Palette.Marsh;
case CellType.Forest: return Palette.Undergrowth;
case CellType.Field:
{
// campi a strisce, con orientamento e colore per cella
uint hash = (uint)(cellX * 73856093 ^ cellY * 19349663);
bool vertical = (hash & 1) == 0;
int stripe = (vertical ? x : y) * 4 / Math.Max(1, ppc);
var baseColor = ((hash >> 1) % 3) switch { 0 => Palette.Grain, 1 => new Color("a9c46a"), _ => new Color("c8a86a") };
return stripe % 2 == 0 ? baseColor : baseColor.Darkened(0.08f);
}
case CellType.Town: return new Color("d6d2bf");
case CellType.Industry: return new Color("c9c4b2");
case CellType.Rock: return Palette.Rock;
case CellType.Mountain: return Palette.Highland.Darkened(0.05f);
default:
{
// fasce altimetriche: pianura, collina, altura
if (h < 120) return Palette.Plain;
if (h < 320) return Palette.Plain.Lerp(Palette.Hill, (float)((h - 120) / 200));
return Palette.Hill.Lerp(Palette.Highland, (float)Math.Min(1, (h - 320) / 300));
}
}
}
private static void SetPixel(byte[] data, int width, int x, int y, Color c)
{
int i = (y * width + x) * 4;
data[i] = (byte)(Math.Clamp(c.R, 0, 1) * 255);
data[i + 1] = (byte)(Math.Clamp(c.G, 0, 1) * 255);
data[i + 2] = (byte)(Math.Clamp(c.B, 0, 1) * 255);
data[i + 3] = (byte)(Math.Clamp(c.A, 0, 1) * 255);
}
}
@@ -0,0 +1 @@
uid://cjsaug4ypro7
@@ -0,0 +1,122 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol.Client;
namespace ViaFerrea.Client.Map;
/// <summary>Sagome degli strumenti: tracciato in corso con l'anteprima delle opere, stazione o deposito da posare, fermate di una linea.</summary>
public partial class ToolOverlay : Node2D
{
public enum Ghost { None, Station, Depot, Demolish }
private ClientWorld? _world;
private float _zoom = 1;
private List<Vector2> _points = [];
private Vector2? _mouse;
private TrackPlan? _plan;
private Ghost _ghost;
private Vector2? _ghostAt;
private List<Vector2> _stops = [];
public void Bind(ClientWorld world) => _world = world;
public void SetZoom(float zoom)
{
_zoom = zoom;
QueueRedraw();
}
public void SetTrack(List<Vector2> points, Vector2? mouse, TrackPlan? plan)
{
_points = points;
_mouse = mouse;
_plan = plan;
QueueRedraw();
}
public void SetGhost(Ghost ghost, Vector2? at)
{
_ghost = ghost;
_ghostAt = at;
QueueRedraw();
}
public void SetStops(List<Vector2> stops)
{
_stops = stops;
QueueRedraw();
}
public void Clear()
{
_points = [];
_mouse = null;
_plan = null;
_ghost = Ghost.None;
_ghostAt = null;
_stops = [];
QueueRedraw();
}
public static Color WorkColor(WorkKind kind) => kind switch
{
WorkKind.Embankment => new Color("e8e0c2"),
WorkKind.Cutting => new Color("8f8a73"),
WorkKind.Bridge => new Color("5b8fb0"),
WorkKind.Tunnel => new Color("4a4740"),
_ => Palette.Ballast,
};
public override void _Draw()
{
float s = MapScale.Symbol(_zoom);
if (_plan is { Samples.Count: > 1 } plan)
{
var color = plan.Valid ? Palette.Ok : Palette.Danger;
for (int i = 0; i < plan.Samples.Count - 1; i++)
{
var a = MapScale.V(plan.Samples[i].Point);
var b = MapScale.V(plan.Samples[i + 1].Point);
DrawLine(a, b, Palette.WithAlpha(color, 0.45f), 14f * s);
if (plan.Samples[i].Kind == WorkKind.Tunnel) DrawDashedLine(a, b, WorkColor(WorkKind.Tunnel), 5f * s, 6f * s);
else DrawLine(a, b, WorkColor(plan.Samples[i].Kind), 7f * s);
}
}
var pts = new List<Vector2>(_points);
if (_mouse is { } m && pts.Count > 0) pts.Add(m);
for (int i = 0; i < pts.Count - 1; i++) DrawDashedLine(pts[i], pts[i + 1], Palette.Amber, 2f * s, 8f * s);
foreach (var p in _points) DrawCircle(p, 4f * s, Palette.Amber);
if (_ghostAt is { } g && _world is not null)
{
switch (_ghost)
{
case Ghost.Station:
float radius = (float)(_world.Data.Construction.Stations.CatchmentKm * 1000);
for (int k = 0; k < 48; k += 2)
{
float a0 = k * MathF.Tau / 48, a1 = (k + 1) * MathF.Tau / 48;
DrawLine(g + new Vector2(MathF.Cos(a0), MathF.Sin(a0)) * radius, g + new Vector2(MathF.Cos(a1), MathF.Sin(a1)) * radius, Palette.Amber, 2.5f * s);
}
DrawCircle(g, radius, Palette.WithAlpha(Palette.Amber, 0.08f));
DrawRect(new Rect2(g - new Vector2(12, 6) * s, new Vector2(24, 12) * s), Palette.WithAlpha(Palette.TileRoof, 0.8f));
break;
case Ghost.Depot:
DrawRect(new Rect2(g - new Vector2(16, 9) * s, new Vector2(32, 18) * s), Palette.WithAlpha(new Color("5a6670"), 0.8f));
break;
case Ghost.Demolish:
DrawCircle(g, 30f * s, Palette.WithAlpha(Palette.Danger, 0.3f));
DrawLine(g - new Vector2(10, 10) * s, g + new Vector2(10, 10) * s, Palette.Danger, 3f * s);
DrawLine(g + new Vector2(-10, 10) * s, g + new Vector2(10, -10) * s, Palette.Danger, 3f * s);
break;
}
}
for (int i = 0; i < _stops.Count; i++)
{
if (i > 0) DrawDashedLine(_stops[i - 1], _stops[i], Palette.Amber, 3f * s, 10f * s);
DrawCircle(_stops[i], 9f * s, Palette.Amber);
DrawString(UiTheme.BodyBold, _stops[i] + new Vector2(-4, 5) * s, (i + 1).ToString(), HorizontalAlignment.Left, -1, (int)Math.Max(8, 12 * s), Palette.AppBackground);
}
}
}
@@ -0,0 +1 @@
uid://itdwbft1rwnw
@@ -0,0 +1,218 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
namespace ViaFerrea.Client.Map;
/// <summary>
/// Binari e opere (immagini 01 e 02): massicciata #bfb79f, traversine #5b4a39 ogni 5,3 unità,
/// rotaie #3b3f42 a ±2,4; rilevati come banda chiara con ombra, trincee come banda scura, ponti
/// con pile ogni 30 m e spallette, gallerie con portali e binario tratteggiato; cantieri con
/// tratteggio #8a7a52 e barriera ambra. LOD: sotto 0,4 niente traversine fitte, sotto 0,15 solo
/// massicciata e rotaia.
/// </summary>
public partial class TrackLayer : Node2D
{
private ClientWorld? _world;
private int _drawnVersion = -1;
private float _drawnScale = -1;
private float _zoom = 1;
public void Bind(ClientWorld world)
{
_world = world;
_drawnVersion = -1;
QueueRedraw();
}
public void SetZoom(float zoom)
{
_zoom = zoom;
float s = Quantize(MapScale.Symbol(zoom));
if (Math.Abs(s - _drawnScale) > 1e-3) QueueRedraw();
}
private static float Quantize(float s) => s <= 1 ? 1 : MathF.Pow(1.25f, MathF.Round(MathF.Log(s) / MathF.Log(1.25f)));
public override void _Process(double delta)
{
if (_world is not null && _world.TrackVersion != _drawnVersion) QueueRedraw();
}
public override void _Draw()
{
if (_world is null) return;
_drawnVersion = _world.TrackVersion;
float s = Quantize(MapScale.Symbol(_zoom));
_drawnScale = s;
var edges = _world.Edges.Values.OrderBy(e => e.Id).ToList();
// prima le opere sotto il binario, poi i binari, infine i dettagli
foreach (var e in edges) DrawWorks(e, s);
foreach (var e in edges) DrawTrack(e, s);
}
private static Vector2[] Points(EdgeInfo e, int from, int to)
{
var pts = new Vector2[to - from + 1];
for (int i = from; i <= to; i++) pts[i - from] = MapScale.V(e.X[i], e.Y[i]);
return pts;
}
/// <summary>Tratti consecutivi con la stessa opera.</summary>
private static IEnumerable<(WorkKind Kind, int From, int To)> Runs(EdgeInfo e)
{
int start = 0;
for (int i = 1; i <= e.Kinds.Length; i++)
{
if (i < e.Kinds.Length && e.Kinds[i] == e.Kinds[start]) continue;
yield return ((WorkKind)e.Kinds[start], Math.Max(0, start - (start > 0 ? 1 : 0)), Math.Min(e.Kinds.Length - 1, i));
start = i;
}
}
private void DrawWorks(EdgeInfo e, float s)
{
float width = (e.DoubleTrack ? 19f : 9f) * s;
foreach (var (kind, from, to) in Runs(e))
{
if (to <= from) continue;
var pts = Points(e, from, to);
switch (kind)
{
case WorkKind.Embankment:
DrawPolyline(Shift(pts, 2.5f * s), new Color(0.35f, 0.36f, 0.3f, 0.35f), width * 2.2f);
DrawPolyline(pts, new Color("ddd6bf"), width * 2.0f);
break;
case WorkKind.Cutting:
DrawPolyline(pts, new Color("8f8a73"), width * 2.2f);
DrawPolyline(pts, new Color("a8a38a"), width * 1.5f);
break;
case WorkKind.Bridge:
DrawBridge(pts, width, s);
break;
case WorkKind.Tunnel:
DrawPortal(pts[0], pts[1] - pts[0], width, s);
DrawPortal(pts[^1], pts[^2] - pts[^1], width, s);
break;
}
}
}
private void DrawBridge(Vector2[] pts, float width, float s)
{
// pile ogni 30 m, impalcato e spallette alle estremità
foreach (var (p, dir) in MapScale.Every(pts, 30f * Math.Max(1, s * 0.5f), 15f))
{
var n = new Vector2(-dir.Y, dir.X);
DrawLine(p - n * width * 0.85f, p + n * width * 0.85f, new Color("6f6a5e"), 3f * s);
}
DrawPolyline(Shift(pts, 2f * s), new Color(0.2f, 0.25f, 0.28f, 0.35f), width * 1.4f);
DrawPolyline(pts, new Color("b9b3a3"), width * 1.35f);
DrawPolyline(Offset(pts, width * 0.68f), new Color("7a7468"), 1.6f * s);
DrawPolyline(Offset(pts, -width * 0.68f), new Color("7a7468"), 1.6f * s);
foreach (var (end, inner) in new[] { (pts[0], pts[1]), (pts[^1], pts[^2]) })
{
var dir = (inner - end).Normalized();
var n = new Vector2(-dir.Y, dir.X);
DrawLine(end - n * width, end + n * width, new Color("8d877a"), 4f * s);
}
}
private void DrawPortal(Vector2 at, Vector2 inward, float width, float s)
{
if (inward.LengthSquared() <= 0) return;
var dir = inward.Normalized();
var n = new Vector2(-dir.Y, dir.X);
var c = new Color("4a4740");
DrawLine(at - n * width, at + n * width, c, 5f * s);
DrawLine(at - n * width, at - n * width + dir * 8f * s, c, 3f * s);
DrawLine(at + n * width, at + n * width + dir * 8f * s, c, 3f * s);
}
private void DrawTrack(EdgeInfo e, float s)
{
var all = Points(e, 0, e.S.Length - 1);
bool building = e.State == (byte)EdgeState.UnderConstruction;
int built = all.Length - 1;
if (building)
{
// parte costruita in proporzione all'avanzamento, il resto tratteggiato
double target = e.Progress * e.S[^1];
built = 0;
while (built < e.S.Length - 1 && e.S[built + 1] <= target) built++;
}
float[] offsets = e.DoubleTrack ? [-5f * s, 5f * s] : [0f];
foreach (float off in offsets)
{
var line = off == 0 ? all : Offset(all, off);
foreach (var (kind, from, to) in Runs(e))
{
int a = from, b = Math.Min(to, built);
if (b <= a) continue;
var seg = line[a..(b + 1)];
if (kind == WorkKind.Tunnel)
{
for (int i = 0; i < seg.Length - 1; i++) DrawDashedLine(seg[i], seg[i + 1], Palette.Rails, 1.5f * s, 6f * s);
continue;
}
DrawSingleTrack(seg, s, e.State == (byte)EdgeState.Closed);
}
if (building && built < all.Length - 1)
{
var rest = line[built..];
for (int i = 0; i < rest.Length - 1; i++) DrawDashedLine(rest[i], rest[i + 1], Palette.Construction, 2.5f * s, 7f * s);
// barriera ambra al fronte del cantiere
var front = rest[0];
var dir = (rest[Math.Min(1, rest.Length - 1)] - front).Normalized();
var n = new Vector2(-dir.Y, dir.X);
for (int k = -2; k <= 1; k++)
{
var c = k % 2 == 0 ? Palette.Amber : Palette.AppBackground;
DrawLine(front + n * k * 2.5f * s, front + n * (k + 1) * 2.5f * s, c, 2.2f * s);
}
}
}
// segnali: piccoli dischi accanto al binario
foreach (double sig in e.Signals)
{
int i = Array.BinarySearch(e.S, sig);
if (i < 0) i = Math.Max(0, ~i - 1);
i = Math.Min(i, e.S.Length - 2);
var p = all[i];
var dir = (all[i + 1] - p).Normalized();
var n = new Vector2(-dir.Y, dir.X);
DrawCircle(p + n * 7f * s, 1.8f * s, Palette.Rails);
DrawCircle(p + n * 7f * s, 1.1f * s, Palette.Ok);
}
}
private void DrawSingleTrack(Vector2[] pts, float s, bool closed)
{
float zoomDetail = _zoom;
DrawPolyline(pts, closed ? Palette.Ballast.Darkened(0.2f) : Palette.Ballast, 9f * s);
if (zoomDetail >= MapScale.OverviewZoom || s > 1)
{
float spacing = 5.3f * s * (zoomDetail >= MapScale.DetailZoom ? 1 : 1.6f);
var sleepers = new List<Vector2>();
foreach (var (p, dir) in MapScale.Every(pts, spacing, spacing / 2))
{
var n = new Vector2(-dir.Y, dir.X);
sleepers.Add(p - n * 3.6f * s);
sleepers.Add(p + n * 3.6f * s);
}
if (sleepers.Count > 0) DrawMultiline(sleepers.ToArray(), Palette.Sleepers, 1.3f * s);
DrawPolyline(Offset(pts, 2.4f * s), Palette.Rails, 0.9f * s);
DrawPolyline(Offset(pts, -2.4f * s), Palette.Rails, 0.9f * s);
}
else
{
DrawPolyline(pts, Palette.Rails, 1.4f * s);
}
}
private static Vector2[] Offset(Vector2[] pts, float off) => MapScale.Offset(pts, off);
private static Vector2[] Shift(Vector2[] pts, float d) => pts.Select(p => p + new Vector2(d, d)).ToArray();
}
@@ -0,0 +1 @@
uid://ckvbn0wqdgoiy
@@ -0,0 +1,212 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
namespace ViaFerrea.Client.Map;
/// <summary>
/// Treni dall'alto (immagine 03): locomotiva scura con dettagli ambra, carri e carrozze con le
/// proporzioni della guida (larghezza 9, carro 16, carrozza 20, locomotiva 20–26), posizione
/// interpolata avanzando la testa alla velocità ricevuta; fumo per le vaporiere; sfumatura e
/// icona d'avviso sotto condizione 40.
/// </summary>
public partial class TrainLayer : Node2D
{
private GameSession? _session;
private float _zoom = 1;
private readonly List<GpuParticles2D> _smoke = [];
private Dictionary<string, VehicleDef> _defs = [];
public int SelectedTrain { get; set; } = -1;
/// <summary>Teste dei treni disegnate nell'ultimo fotogramma (per la selezione col mouse).</summary>
public Dictionary<int, Vector2> Heads { get; } = [];
public void Bind(GameSession session)
{
_session = session;
_defs = session.World.Data.Vehicles.ToDictionary(v => v.Id);
}
public void SetZoom(float zoom) => _zoom = zoom;
public override void _Process(double delta) => QueueRedraw();
/// <summary>Secondi di orologio dei treni trascorsi dall'arrivo del moto (fattore 60 per la velocità).</summary>
private double Elapsed(int trainId, ClientWorld w)
{
if (_session is null || !_session.MotionReceivedMs.TryGetValue(trainId, out long at)) return 0;
double realSeconds = Math.Max(0, ((long)Time.GetTicksMsec() - at) / 1000.0);
double perTick = w.Calendar?.TrainSecondsPerTick ?? 3;
double ticksPerSecond = 1000.0 / (w.Calendar?.TickMs ?? 50);
// senza interpolare oltre mezzo secondo: il moto successivo arriva ogni 100 ms
return Math.Min(realSeconds, 0.5) * ticksPerSecond * perTick * w.Speed;
}
public override void _Draw()
{
Heads.Clear();
var w = _session?.World;
if (w is null) return;
float s = MapScale.Symbol(_zoom);
var view = VisibleWorldRect().Grow(400 * s);
int smokeUsed = 0;
foreach (var (id, motion) in w.Motions)
{
if (!w.Trains.TryGetValue(id, out var train) || train.State == (byte)TrainState.InDepot) continue;
double total = ClientWorld.TotalLength(motion);
double head = Math.Min(motion.HeadDistance + motion.Speed * Elapsed(id, w), total);
var headPoint = w.PointAlong(motion, head);
if (headPoint is null || !view.HasPoint(MapScale.V(headPoint.Value))) continue;
Heads[id] = MapScale.V(headPoint.Value);
double d = head;
bool first = true;
foreach (int vid in train.Vehicles)
{
if (!w.Vehicles.TryGetValue(vid, out var v) || !_defs.TryGetValue(v.Type, out var def)) continue;
float length = DrawLength(def) * s;
var front = w.PointAlong(motion, Math.Max(0, d));
var back = w.PointAlong(motion, Math.Max(0, d - length));
if (front is null || back is null) break;
var f = MapScale.V(front.Value);
var b = MapScale.V(back.Value);
if (f.DistanceTo(b) < length * 0.9f)
{
// la coda esce dai tratti noti: si prolunga all'indietro lungo la direzione del binario
var ahead = w.PointAlong(motion, Math.Min(total, Math.Max(0, d) + 5));
var dir = ahead is { } ap && MapScale.V(ap).DistanceTo(f) > 0.01f ? (MapScale.V(ap) - f).Normalized()
: (f - b).LengthSquared() > 0.0001f ? (f - b).Normalized() : Vector2.Right;
if (ahead is { } ap2 && MapScale.V(ap2).DistanceTo(f) <= 0.01f && (f - b).LengthSquared() > 0.0001f) dir = (f - b).Normalized();
b = f - dir * length;
}
DrawVehicle(def, v, f, b, s, id == SelectedTrain);
if (first && def.Kind == VehicleKind.Locomotive && def.Traction == Traction.Steam && motion.Speed > 0.5f && smokeUsed < 24)
PlaceSmoke(smokeUsed++, f.Lerp(b, 0.25f), s);
first = false;
d -= length + 1.5f * s;
if (d < 0) break;
}
if (motion.Condition < 40)
{
// icona d'avviso: triangolo ambra sopra la testa
var p = MapScale.V(headPoint.Value) + new Vector2(0, -16 * s);
DrawColoredPolygon([p + new Vector2(0, -6 * s), p + new Vector2(6 * s, 5 * s), p + new Vector2(-6 * s, 5 * s)], Palette.Amber);
DrawLine(p + new Vector2(0, -2.5f * s), p + new Vector2(0, 1.5f * s), Palette.AppBackground, 1.4f * s);
}
}
for (int i = smokeUsed; i < _smoke.Count; i++) _smoke[i].Emitting = false;
}
private static float DrawLength(VehicleDef def) => def.Kind switch
{
VehicleKind.Locomotive => (float)Math.Clamp(def.LengthM * 1.25, 20, 26),
VehicleKind.Coach => 20f,
_ => 16f,
};
private void DrawVehicle(VehicleDef def, VehicleInfo v, Vector2 front, Vector2 back, float s, bool selected)
{
var center = (front + back) / 2;
var dir = front - back;
float length = dir.Length();
DrawSetTransform(center, dir.Angle());
float width = 9f * s;
var rect = new Rect2(-length / 2, -width / 2, length, width);
Color body = def.Kind switch
{
VehicleKind.Locomotive => new Color("1d2226"),
VehicleKind.Coach => def.Class == PaxClass.Staff ? Palette.Staff : Palette.Workers,
_ => def.WagonType switch
{
WagonType.Hopper => new Color("6b4a3a"),
WagonType.Flat => new Color("8a8f94"),
WagonType.Tank => new Color("4b5258"),
_ => new Color("8a5a44"),
},
};
if (v.Condition < 40) body = body.Lerp(Palette.Danger, 0.45f);
DrawRect(new Rect2(rect.Position + new Vector2(1.2f, 1.2f) * s, rect.Size), new Color(0, 0, 0, 0.25f));
DrawRect(rect, body);
DrawRect(rect, selected ? Palette.Amber : body.Darkened(0.35f), false, (selected ? 1.1f : 0.6f) * s);
switch (def.Kind)
{
case VehicleKind.Locomotive:
// cabina ambra verso la coda, caldaia e fanale verso la testa
DrawRect(new Rect2(-length / 2 + 1.5f * s, -width / 2 + 1.2f * s, 4.5f * s, width - 2.4f * s), Palette.Amber);
DrawCircle(new Vector2(length / 2 - 3.5f * s, 0), 1.8f * s, Palette.AmberLight);
DrawLine(new Vector2(-length / 2 + 7 * s, 0), new Vector2(length / 2 - 6 * s, 0), body.Lightened(0.15f), 1f * s);
break;
case VehicleKind.Coach:
for (float x = -length / 2 + 3 * s; x < length / 2 - 2 * s; x += 3.2f * s)
DrawRect(new Rect2(x, -width / 2 + 1.2f * s, 1.8f * s, 1.4f * s), Colors.White.Lerp(body, 0.4f));
break;
default:
if (def.WagonType == WagonType.Hopper)
DrawRect(new Rect2(-length / 2 + 2 * s, -width / 2 + 1.5f * s, length - 4 * s, width - 3 * s), body.Darkened(0.3f));
else if (def.WagonType == WagonType.Tank)
DrawCircle(Vector2.Zero, width * 0.35f, body.Lightened(0.15f));
break;
}
DrawSetTransform(Vector2.Zero, 0);
}
private void PlaceSmoke(int index, Vector2 at, float s)
{
while (_smoke.Count <= index)
{
var gradient = new Gradient();
gradient.SetColor(0, new Color(0.92f, 0.92f, 0.9f, 0.55f));
gradient.SetColor(1, new Color(0.92f, 0.92f, 0.9f, 0f));
var material = new ParticleProcessMaterial
{
Direction = new Vector3(1, -1, 0),
Spread = 25,
InitialVelocityMin = 6,
InitialVelocityMax = 12,
Gravity = new Vector3(4, -2, 0),
ScaleMin = 0.8f,
ScaleMax = 1.6f,
ColorRamp = new GradientTexture1D { Gradient = gradient },
};
var p = new GpuParticles2D { Amount = 16, Lifetime = 1.6, ProcessMaterial = material, Texture = SmokePuff(), ZIndex = 6, LocalCoords = false };
AddChild(p);
_smoke.Add(p);
}
var smoke = _smoke[index];
smoke.Position = at;
smoke.Scale = new Vector2(s, s) * 0.25f;
smoke.Emitting = true;
}
private static Texture2D? _puff;
private static Texture2D SmokePuff()
{
if (_puff is not null) return _puff;
const int n = 32;
var img = Image.CreateEmpty(n, n, false, Image.Format.Rgba8);
for (int y = 0; y < n; y++)
{
for (int x = 0; x < n; x++)
{
float dx = (x + 0.5f) / n * 2 - 1, dy = (y + 0.5f) / n * 2 - 1;
float a = Math.Clamp(1 - MathF.Sqrt(dx * dx + dy * dy), 0, 1);
img.SetPixel(x, y, new Color(1, 1, 1, a * a));
}
}
return _puff = ImageTexture.CreateFromImage(img);
}
private Rect2 VisibleWorldRect()
{
var canvas = GetCanvasTransform().AffineInverse();
var size = GetViewportRect().Size;
var a = canvas * Vector2.Zero;
var b = canvas * size;
return new Rect2(a, b - a).Abs();
}
}
@@ -0,0 +1 @@
uid://dsfaatx2pgfka
@@ -0,0 +1,142 @@
using Godot;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Data;
using ViaFerrea.Protocol;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
namespace ViaFerrea.Client.Net;
/// <summary>
/// Sessione di gioco del client: connessione, copia locale del mondo, esiti dei comandi e
/// notifiche. I messaggi si applicano sul thread principale in <see cref="Poll"/>.
/// </summary>
public sealed class GameSession : IAsyncDisposable
{
private readonly Dictionary<uint, Action<CommandResultMessage>> _callbacks = [];
private long _pingSentMs;
private ulong _pingNonce;
public ProtocolClient Connection { get; }
public ClientWorld World { get; }
public string ServerLabel { get; }
public LocalServerLauncher? LocalServer { get; set; }
/// <summary>Istante di arrivo (ms) dell'ultimo moto di ogni treno, per l'interpolazione.</summary>
public Dictionary<int, long> MotionReceivedMs { get; } = [];
/// <summary>Ritardo di andata e ritorno dell'ultimo ping (ms).</summary>
public double LatencyMs { get; private set; }
public event Action<IMessage>? MessageApplied;
public event Action<EventInfo>? Notified;
public event Action<CommandResultMessage>? CommandFailed;
private GameSession(ProtocolClient connection, ClientWorld world, string label)
{
Connection = connection;
World = world;
ServerLabel = label;
}
public static async Task<GameSession> ConnectAsync(GameData data, Uri uri, string token, string label, CancellationToken ct = default)
{
var connection = await ProtocolClient.ConnectAsync(uri, ct);
try
{
var welcome = await connection.HandshakeAsync(new Hello
{
ClientVersion = typeof(GameSession).Assembly.GetName().Version?.ToString() ?? "0",
Token = token,
DataHash = data.Hash,
}, ct);
var world = new ClientWorld(data);
world.Apply(welcome);
return new GameSession(connection, world, label);
}
catch
{
await connection.DisposeAsync();
throw;
}
}
public bool IsOpen => Connection.IsOpen;
/// <summary>Applica i messaggi arrivati (al massimo maxMessages per fotogramma).</summary>
public int Poll(int maxMessages = 2000)
{
int n = 0;
while (n < maxMessages && Connection.TryReceive(out var message))
{
n++;
World.Apply(message);
switch (message)
{
case CommandResultMessage r:
if (_callbacks.Remove(r.Seq, out var callback)) callback(r);
if (!r.Ok) CommandFailed?.Invoke(r);
break;
case TrainMotion motion:
MotionReceivedMs[motion.TrainId] = (long)Time.GetTicksMsec();
break;
case Notification note:
Notified?.Invoke(note.Event);
break;
case DailyDigest digest when RequestedSpeed == digest.Speed:
RequestedSpeed = null;
break;
case Pong pong when pong.Nonce == _pingNonce:
LatencyMs = (long)Time.GetTicksMsec() - _pingSentMs;
break;
}
MessageApplied?.Invoke(message);
}
if ((long)Time.GetTicksMsec() - _pingSentMs > 2000) Ping();
return n;
}
private void Ping()
{
_pingSentMs = (long)Time.GetTicksMsec();
_pingNonce++;
Send(new Ping { Nonce = _pingNonce });
}
public void Send(IMessage message) => _ = SendSafe(message);
private async Task SendSafe(IMessage message)
{
try
{
await Connection.SendAsync(message);
}
catch (Exception e)
{
GD.PrintErr($"Invio non riuscito: {e.Message}");
}
}
/// <summary>Invia un comando; la callback riceve l'esito sul thread principale.</summary>
public void Command(GameCommand command, Action<CommandResultMessage>? onResult = null)
{
uint seq = Connection.ReserveSeq();
if (onResult is not null) _callbacks[seq] = onResult;
Send(new CommandMessage { Seq = seq, Command = command });
}
/// <summary>Ultima velocità chiesta da questo client (mostrata finché il resoconto non la conferma).</summary>
public byte? RequestedSpeed { get; private set; }
public void SetSpeed(byte speed)
{
RequestedSpeed = speed;
Send(new SetSpeed { Speed = speed });
}
public async ValueTask DisposeAsync()
{
await Connection.DisposeAsync();
LocalServer?.Dispose();
}
}
@@ -0,0 +1 @@
uid://b8etsc0caa35g
@@ -0,0 +1,94 @@
using System.Diagnostics;
using Godot;
namespace ViaFerrea.Client.Net;
/// <summary>
/// Partita locale: avvia il server come processo figlio con <c>--local --token</c>, legge
/// «LISTENING porta» dallo standard output e lo termina alla chiusura del client.
/// </summary>
public sealed class LocalServerLauncher : IDisposable
{
private Process? _process;
public int Port { get; private set; }
public string Token { get; } = Guid.NewGuid().ToString("N");
/// <summary>Percorso del server: variabile VF_SERVER_PATH, cartella «server» accanto al gioco, build del repository.</summary>
public static string? FindServer()
{
string? env = System.Environment.GetEnvironmentVariable("VF_SERVER_PATH");
if (!string.IsNullOrWhiteSpace(env) && File.Exists(env)) return env;
string exeDir = Path.GetDirectoryName(OS.GetExecutablePath()) ?? ".";
foreach (string name in new[] { "ViaFerrea.Server.exe", "ViaFerrea.Server", "ViaFerrea.Server.dll" })
{
string candidate = Path.Combine(exeDir, "server", name);
if (File.Exists(candidate)) return candidate;
}
// sviluppo: il progetto Godot sta in client/ViaFerrea.Client, il server in src/
string project = ProjectSettings.GlobalizePath("res://");
foreach (string config in new[] { "Release", "Debug" })
{
string candidate = Path.GetFullPath(Path.Combine(project, "..", "..", "src", "ViaFerrea.Server", "bin", config, "net10.0", "ViaFerrea.Server.dll"));
if (File.Exists(candidate)) return candidate;
}
return null;
}
/// <summary>Avvia il server e attende la porta (al massimo timeout).</summary>
public async Task<int> StartAsync(string serverPath, string dataDir, TimeSpan timeout)
{
bool dll = serverPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase);
var info = new ProcessStartInfo
{
FileName = dll ? "dotnet" : serverPath,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
WorkingDirectory = Path.GetDirectoryName(serverPath) ?? ".",
};
if (dll) info.ArgumentList.Add(serverPath);
info.ArgumentList.Add("--local");
info.ArgumentList.Add("--token");
info.ArgumentList.Add(Token);
info.ArgumentList.Add("--data");
info.ArgumentList.Add(dataDir);
_process = Process.Start(info) ?? throw new InvalidOperationException("Server non avviato");
_process.ErrorDataReceived += (_, e) => { if (e.Data is not null) GD.PrintErr("[server] " + e.Data); };
_process.BeginErrorReadLine();
using var cts = new CancellationTokenSource(timeout);
while (!cts.IsCancellationRequested)
{
string? line = await _process.StandardOutput.ReadLineAsync(cts.Token);
if (line is null) break;
if (line.StartsWith("LISTENING ", StringComparison.Ordinal) && int.TryParse(line.AsSpan(10), out int port))
{
Port = port;
// il resto dell'output (log JSON) si scarta per non riempire il buffer
_ = Task.Run(async () =>
{
while (await _process.StandardOutput.ReadLineAsync() is not null)
{
}
});
return port;
}
}
throw new TimeoutException("Il server locale non ha risposto");
}
public void Dispose()
{
try
{
if (_process is { HasExited: false }) _process.Kill(entireProcessTree: true);
}
catch (InvalidOperationException)
{
}
_process?.Dispose();
_process = null;
}
}
@@ -0,0 +1 @@
uid://cr4o72tey2gop
@@ -0,0 +1,151 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Rail;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
/// <summary>Scheda dell'entità selezionata (treno, stazione, industria, città) come nel pannello destro dell'immagine 01.</summary>
public partial class InfoPanel : VBoxContainer
{
public enum Kind { None, Train, Station, Industry, Town }
private readonly GameSession _session;
private Kind _kind;
private int _id = -1;
private double _refresh;
public InfoPanel(GameSession session)
{
_session = session;
AddThemeConstantOverride("separation", 10);
Select(Kind.None, -1);
}
public void Select(Kind kind, int id)
{
_kind = kind;
_id = id;
Rebuild();
}
public override void _Process(double delta)
{
_refresh += delta;
if (_refresh < 0.5) return;
_refresh = 0;
Rebuild();
}
private void Rebuild()
{
foreach (var c in GetChildren()) c.QueueFree();
var w = _session.World;
switch (_kind)
{
case Kind.Train when w.Trains.TryGetValue(_id, out var t):
{
var head = PanelKit.Row();
var title = UiTheme.TitleLabel(t.Name, 38);
title.SizeFlagsHorizontal = SizeFlags.ExpandFill;
head.AddChild(title);
if (t.Line >= 0 && w.Lines.TryGetValue(t.Line, out var line))
{
var badge = new CenterContainer();
var b = UiTheme.LineBadge(line.Name);
badge.AddChild(b);
head.AddChild(badge);
AddChild(head);
string route = string.Join(" → ", line.Stops.Select(s => w.Stations.TryGetValue(s.Station.Value, out var st) ? st.Name : "?"));
AddChild(UiTheme.Text(route, 17, bold: true));
}
else
{
AddChild(head);
}
var loco = t.Vehicles.Select(v => w.Vehicles.GetValueOrDefault(v)).FirstOrDefault(v => v is not null && w.Data.Vehicles.Any(d => d.Id == v.Type && d.Kind == Core.Data.VehicleKind.Locomotive));
var locoDef = loco is null ? null : w.Data.Vehicles.First(d => d.Id == loco.Type);
AddChild(UiTheme.Text($"{T("Locomotiva")} {locoDef?.NameIt ?? "—"} · {TrainsPanel.StateName((TrainState)t.State)}", 14, Palette.TextSecondary));
var stats = PanelKit.Row();
double speed = w.Motions.TryGetValue(t.Id, out var m) ? m.Speed * 3.6 : 0;
double condition = w.Motions.TryGetValue(t.Id, out var m2) ? m2.Condition : t.Vehicles.Select(v => w.Vehicles.GetValueOrDefault(v)?.Condition ?? 100).DefaultIfEmpty(100).Min();
stats.AddChild(PanelKit.Stat(T("Velocità"), PanelKit.Value($"{speed:0} km/h")));
stats.AddChild(PanelKit.Stat(T("Condizione"), PanelKit.Value($"{condition:0}%")));
stats.AddChild(PanelKit.Stat(T("Veicoli"), PanelKit.Value($"{t.Vehicles.Length}")));
AddChild(stats);
AddChild(PanelKit.Pair(T("Carico"), PanelKit.Value($"{t.Load} / {t.Capacity}")));
var bar = new ProgressBar { MaxValue = Math.Max(1, t.Capacity), Value = t.Load, ShowPercentage = false, CustomMinimumSize = new Vector2(0, 10) };
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(Palette.Amber, Palette.Amber, 4, 0));
AddChild(bar);
if (t.Line >= 0 && w.Lines.TryGetValue(t.Line, out var l2))
{
for (int i = 0; i < l2.Stops.Length; i++)
{
var s = l2.Stops[i];
string name = w.Stations.TryGetValue(s.Station.Value, out var st) ? st.Name : "?";
string orders = (s.Load ? T("carica") : "") + (s.Unload ? (s.Load ? ", " : "") + T("scarica") : "")
+ (s.WaitFull ? $", {T("attendi il pieno")} (max {s.MaxWaitDays} {T("giorni")})" : "");
var row = PanelKit.Row();
row.AddChild(UiTheme.Text($"{i + 1}", 14, Palette.TextSecondary, bold: true));
var col = PanelKit.Column(0);
col.AddChild(UiTheme.Text(name, 15, bold: true));
col.AddChild(UiTheme.Text(orders, 13, Palette.TextSecondary));
row.AddChild(col);
AddChild(row);
}
}
break;
}
case Kind.Station when w.Stations.TryGetValue(_id, out var s):
{
AddChild(UiTheme.TitleLabel(s.Name, 38));
AddChild(PanelKit.Pair(T("Binari di stazione"), PanelKit.Value($"{s.Platforms}")));
AddChild(PanelKit.Pair(T("Merci e passeggeri in attesa"), PanelKit.Value($"{s.WaitingUnits}")));
AddChild(UiTheme.Text(T("Nel bacino"), 14, bold: true));
foreach (int i in s.Industries)
if (w.Industries.TryGetValue(i, out var ind)) AddChild(UiTheme.Text($"• {ind.Name}", 13));
foreach (int i in s.Towns)
if (w.Towns.TryGetValue(i, out var town)) AddChild(UiTheme.Text($"• {town.Name}", 13));
break;
}
case Kind.Industry when w.Industries.TryGetValue(_id, out var ind):
{
AddChild(UiTheme.TitleLabel(ind.Name, 38));
var def = w.Data.Industries.FirstOrDefault(d => d.Id == ind.Type);
AddChild(UiTheme.Text(def?.NameIt ?? ind.Type, 14, Palette.TextSecondary));
var stats = PanelKit.Row();
stats.AddChild(PanelKit.Stat(T("Livello"), PanelKit.Value($"{ind.Level}")));
stats.AddChild(PanelKit.Stat(T("Efficienza"), PanelKit.Value($"{ind.Efficiency * 100:0}%")));
stats.AddChild(PanelKit.Stat(T("Impianti"), PanelKit.Value($"{ind.Condition:0}%")));
AddChild(stats);
if (def is not null)
{
string inputs = string.Join(", ", def.Recipe.Inputs.Select(i => w.Data.Goods.First(g => g.Id == i.Good).NameIt));
string outputs = string.Join(", ", def.Recipe.Outputs.Select(o => w.Data.Goods.First(g => g.Id == o.Good).NameIt));
if (inputs.Length > 0) AddChild(PanelKit.Pair(T("Consuma"), PanelKit.Value(inputs)));
AddChild(PanelKit.Pair(T("Produce"), PanelKit.Value(outputs)));
}
if (ind.Closed) AddChild(UiTheme.Notice(T("Chiusa")));
break;
}
case Kind.Town when w.Towns.TryGetValue(_id, out var town):
{
AddChild(UiTheme.TitleLabel(town.Name, 38));
AddChild(PanelKit.Pair(T("Abitanti"), PanelKit.Value(Money.GroupThousands((ulong)town.Population))));
AddChild(PanelKit.Pair(T("Soddisfazione"), PanelKit.Value($"{town.Satisfaction * 100:0}%")));
AddChild(PanelKit.Pair(T("Servizi"), PanelKit.Value($"{town.Services}")));
break;
}
default:
{
AddChild(UiTheme.TitleLabel(T("Via Ferrea"), 38));
var help = UiTheme.Text(T("Scegli uno strumento a sinistra oppure fai clic su un treno, una stazione, un'industria o una città per vederne la scheda."), 14, Palette.TextSecondary);
help.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(help);
break;
}
}
}
}
@@ -0,0 +1 @@
uid://b48ikeoeho1rb
@@ -0,0 +1,117 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Rail;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
/// <summary>Linee: fermate scelte con un clic sulle stazioni, nome e colore, attesa del pieno alla prima fermata.</summary>
public partial class LinesPanel : VBoxContainer
{
private static readonly (string Name, string Hex)[] Colors =
[
("Ambra", "#e0a526"), ("Blu", "#3f86d1"), ("Rosso coppo", "#b3573e"), ("Verde", "#5fc39b"), ("Celeste", "#9cc9f2"), ("Grano", "#d9c26a"),
];
private readonly GameSession _session;
private readonly ItemList _stopsList = new() { CustomMinimumSize = new Vector2(0, 110) };
private readonly LineEdit _name = new() { PlaceholderText = T("Nome della linea") };
private readonly OptionButton _color = new();
private readonly CheckBox _waitFull = new() { Text = T("Attendi il pieno alla prima fermata (max 2 giorni)") };
private readonly ItemList _lines = new() { CustomMinimumSize = new Vector2(0, 120) };
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
private int _version = -1;
public List<int> Stops { get; } = [];
public event Action? StopsChanged;
public LinesPanel(GameSession session)
{
_session = session;
AddThemeConstantOverride("separation", 8);
AddChild(UiTheme.TitleLabel(T("Linee"), 34));
var help = UiTheme.Text(T("Clic sulle stazioni della mappa per aggiungere le fermate in ordine; la linea torna alla prima."), 13, Palette.TextSecondary);
help.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(help);
AddChild(_stopsList);
foreach (var (name, _) in Colors) _color.AddItem(T(name));
_color.Selected = 0;
AddChild(_name);
AddChild(_color);
AddChild(_waitFull);
var row = PanelKit.Row();
var create = UiTheme.Primary(T("Crea linea"));
create.SizeFlagsHorizontal = SizeFlags.ExpandFill;
create.Pressed += Create;
var clear = new Button { Text = T("Svuota") };
clear.Pressed += () =>
{
Stops.Clear();
RefreshStops();
};
row.AddChild(create);
row.AddChild(clear);
AddChild(row);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(_status);
AddChild(PanelKit.Separator());
AddChild(UiTheme.Text(T("Linee della compagnia"), 14, bold: true));
AddChild(_lines);
}
public void AddStop(int station)
{
if (Stops.Count > 0 && Stops[^1] == station) return;
Stops.Add(station);
RefreshStops();
}
private void RefreshStops()
{
_stopsList.Clear();
for (int i = 0; i < Stops.Count; i++)
{
string name = _session.World.Stations.TryGetValue(Stops[i], out var s) ? s.Name : $"#{Stops[i]}";
_stopsList.AddItem($"{i + 1}. {name}");
}
StopsChanged?.Invoke();
}
public override void _Process(double delta)
{
var w = _session.World;
if (w.EntityVersion == _version) return;
_version = w.EntityVersion;
_lines.Clear();
int company = w.Summary?.CompanyId ?? 0;
foreach (var l in w.Lines.Values.Where(l => l.Owner == company).OrderBy(l => l.Id))
{
int trains = w.Trains.Values.Count(t => t.Line == l.Id);
string stops = string.Join(" → ", l.Stops.Select(s => w.Stations.TryGetValue(s.Station.Value, out var st) ? st.Name : "?"));
_lines.AddItem($"{l.Name} ({trains} {T("treni")}): {stops}");
}
}
private void Create()
{
if (Stops.Count < 2)
{
_status.Text = T("Servono almeno due fermate");
return;
}
var stops = Stops.Select((s, i) => new LineStop(new StationId(s), WaitFull: i == 0 && _waitFull.ButtonPressed, MaxWaitDays: i == 0 && _waitFull.ButtonPressed ? 2 : 0)).ToList();
string name = string.IsNullOrWhiteSpace(_name.Text) ? $"{T("Linea")} {_session.World.Lines.Count + 1}" : _name.Text.Trim();
_session.Command(new CreateLineCommand(name, Colors[Math.Max(0, _color.Selected)].Hex, stops), r =>
{
_status.Text = r.Message;
if (!r.Ok) return;
Stops.Clear();
_name.Text = "";
RefreshStops();
});
}
}
@@ -0,0 +1 @@
uid://c5bnynb60j4xs
@@ -0,0 +1,56 @@
using Godot;
using ViaFerrea.Client.App;
namespace ViaFerrea.Client.Panels;
/// <summary>Mattoni comuni dei pannelli laterali.</summary>
public static class PanelKit
{
public static VBoxContainer Column(int separation = 10)
{
var v = new VBoxContainer { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill };
v.AddThemeConstantOverride("separation", separation);
return v;
}
public static HBoxContainer Row(int separation = 10)
{
var h = new HBoxContainer { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill };
h.AddThemeConstantOverride("separation", separation);
return h;
}
/// <summary>Riga etichetta : valore.</summary>
public static HBoxContainer Pair(string caption, Label value)
{
var row = Row();
var c = UiTheme.Text(caption, 14, Palette.TextSecondary);
c.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
value.HorizontalAlignment = HorizontalAlignment.Right;
row.AddChild(c);
row.AddChild(value);
return row;
}
/// <summary>Riquadro statistico (velocità, affidabilità, età…) come nell'immagine 01.</summary>
public static PanelContainer Stat(string caption, Label value)
{
var p = new PanelContainer { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill };
p.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, Palette.Inner, 8, 12));
var v = Column(2);
v.AddChild(UiTheme.Text(caption, 12, Palette.TextSecondary));
value.AddThemeFontSizeOverride("font_size", 20);
v.AddChild(value);
p.AddChild(v);
return p;
}
public static Label Value(string text = "") => UiTheme.Text(text, 14, bold: true);
public static HSeparator Separator()
{
var s = new HSeparator();
s.AddThemeStyleboxOverride("separator", UiTheme.Box(Palette.Border, Palette.Border, 0, 0));
return s;
}
}
@@ -0,0 +1 @@
uid://lo82o2847rj3
@@ -0,0 +1,53 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Map;
using ViaFerrea.Core.Rail;
namespace ViaFerrea.Client.Panels;
/// <summary>Grafico altimetrico del tracciato: terreno, quota del binario e opere colorate (pannello TrackProfile).</summary>
public partial class ProfileChart : Control
{
private TrackPlan? _plan;
public ProfileChart() => CustomMinimumSize = new Vector2(0, 140);
public void Show(TrackPlan? plan)
{
_plan = plan;
QueueRedraw();
}
public override void _Draw()
{
DrawStyleBox(UiTheme.Box(Palette.Inner, Palette.Border, 8, 0), new Rect2(Vector2.Zero, Size));
if (_plan is not { Samples.Count: > 1 } plan) return;
var samples = plan.Samples;
double minH = samples.Min(s => Math.Min(s.TerrainM, s.TrackM)), maxH = samples.Max(s => Math.Max(s.TerrainM, s.TrackM));
if (maxH - minH < 10) maxH = minH + 10;
double length = Math.Max(1, samples[^1].S);
var area = new Rect2(10, 10, Size.X - 20, Size.Y - 40);
Vector2 P(double s, double h) => new(area.Position.X + (float)(s / length) * area.Size.X, area.End.Y - (float)((h - minH) / (maxH - minH)) * area.Size.Y);
// terreno pieno
var ground = new List<Vector2> { new(area.Position.X, area.End.Y) };
foreach (var s in samples) ground.Add(P(s.S, s.TerrainM));
ground.Add(new Vector2(area.End.X, area.End.Y));
DrawColoredPolygon(ground.ToArray(), Palette.WithAlpha(Palette.Hill, 0.55f));
// opere sotto la linea del binario
for (int i = 0; i < samples.Count - 1; i++)
{
var a = samples[i];
var b = samples[i + 1];
var color = ToolOverlay.WorkColor(a.Kind);
if (a.Kind == WorkKind.Natural) continue;
DrawRect(new Rect2(P(a.S, minH).X, area.End.Y + 6, Math.Max(1, P(b.S, minH).X - P(a.S, minH).X), 8), color);
if (a.Kind == WorkKind.Bridge) DrawLine(P(a.S, a.TrackM), P(a.S, a.TerrainM), Palette.WithAlpha(color, 0.6f), 1.5f);
}
var track = samples.Select(s => P(s.S, s.TrackM)).ToArray();
DrawPolyline(track, plan.Valid ? Palette.Amber : Palette.Danger, 2.5f, true);
DrawString(UiTheme.Body, new Vector2(area.Position.X + 4, area.Position.Y + 12), $"{maxH:0} m", HorizontalAlignment.Left, -1, 11, Palette.TextSecondary);
DrawString(UiTheme.Body, new Vector2(area.Position.X + 4, area.End.Y - 4), $"{minH:0} m", HorizontalAlignment.Left, -1, 11, Palette.TextSecondary);
DrawString(UiTheme.Body, new Vector2(area.End.X - 60, Size.Y - 6), $"{length / 1000:0.0} km", HorizontalAlignment.Left, -1, 11, Palette.TextSecondary);
}
}
@@ -0,0 +1 @@
uid://d1kct34qv0wvl
@@ -0,0 +1,150 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
/// <summary>Strumento stazione: numero di binari, nome facoltativo, costo stimato; clic sulla mappa per posarla.</summary>
public partial class StationPanel : VBoxContainer
{
public SpinBox Platforms { get; } = new() { MinValue = 1, Value = 2, SizeFlagsHorizontal = SizeFlags.ExpandFill };
public LineEdit StationName { get; } = new() { PlaceholderText = T("Nome automatico") };
private readonly Label _cost = PanelKit.Value();
private readonly GameSession _session;
public StationPanel(GameSession session)
{
_session = session;
var data = session.World.Data;
Platforms.MaxValue = data.Construction.Stations.MaxPlatforms;
AddThemeConstantOverride("separation", 10);
AddChild(UiTheme.TitleLabel(T("Stazione"), 34));
AddChild(UiTheme.Text(T("Clic sulla mappa: la stazione si aggancia al binario vicino o nasce come capolinea. Il cerchio è il bacino di utenza."), 13, Palette.TextSecondary));
AddChild(PanelKit.Pair(T("Binari di stazione"), new Label()));
AddChild(Platforms);
AddChild(StationName);
AddChild(PanelKit.Pair(T("Costo"), _cost));
Platforms.ValueChanged += _ => UpdateCost();
UpdateCost();
foreach (var l in GetChildren().OfType<Label>()) l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
}
private void UpdateCost()
{
var c = _session.World.Data.Construction.Costs;
double mult = _session.World.Summary?.CostMultiplier ?? 1;
_cost.Text = (new Money(c.StationBase + c.StationPerPlatform * (long)Platforms.Value) * mult).ToString();
}
}
/// <summary>Strumento deposito: dimensione e costo; clic sulla mappa per posarlo.</summary>
public partial class DepotPanel : VBoxContainer
{
public OptionButton SizeChoice { get; } = new();
private readonly List<string> _sizes;
public DepotPanel(GameSession session)
{
var data = session.World.Data;
_sizes = data.Construction.Costs.DepotBySize.Keys.OrderBy(k => data.Construction.Costs.DepotBySize[k]).ToList();
double mult = session.World.Summary?.CostMultiplier ?? 1;
foreach (string s in _sizes)
SizeChoice.AddItem($"{T(s)} — {new Money(data.Construction.Costs.DepotBySize[s]) * mult}");
SizeChoice.Selected = 0;
AddThemeConstantOverride("separation", 10);
AddChild(UiTheme.TitleLabel(T("Deposito"), 34));
var help = UiTheme.Text(T("Clic sulla mappa vicino a un binario, poi raccordalo con lo strumento Binari. Nel deposito si comprano i veicoli e si compongono i treni."), 13, Palette.TextSecondary);
help.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(help);
AddChild(SizeChoice);
}
public string SelectedSize => _sizes[Math.Max(0, SizeChoice.Selected)];
}
/// <summary>Testo d'aiuto per gli strumenti senza opzioni (segnali, demolizione).</summary>
public partial class HelpPanel : VBoxContainer
{
public HelpPanel(string title, string help)
{
AddThemeConstantOverride("separation", 10);
AddChild(UiTheme.TitleLabel(title, 34));
var l = UiTheme.Text(help, 13, Palette.TextSecondary);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(l);
}
}
/// <summary>Prezzi globali del giorno (resoconto giornaliero).</summary>
public partial class MarketPanel : VBoxContainer
{
private readonly GameSession _session;
private readonly VBoxContainer _rows = PanelKit.Column(4);
private long _day = -1;
public MarketPanel(GameSession session)
{
_session = session;
AddThemeConstantOverride("separation", 10);
AddChild(UiTheme.TitleLabel(T("Mercato"), 34));
AddChild(UiTheme.Text(T("Prezzi globali di oggi (la borsa arriva in seguito)."), 13, Palette.TextSecondary));
AddChild(_rows);
}
public override void _Process(double delta)
{
var digest = _session.World.LastDigest;
if (digest is null || digest.Day == _day) return;
_day = digest.Day;
foreach (var c in _rows.GetChildren()) c.QueueFree();
var goods = _session.World.Data.Goods;
for (int g = 0; g < Math.Min(goods.Count, digest.Prices.Count); g++)
{
var ratio = digest.Prices[g].Cents / (double)Math.Max(1, goods[g].BasePrice);
var value = PanelKit.Value($"{digest.Prices[g]} / {goods[g].Unit}");
value.AddThemeColorOverride("font_color", ratio > 1.15 ? Palette.AmberLight : ratio < 0.85 ? Palette.Staff : Palette.Text);
_rows.AddChild(PanelKit.Pair(goods[g].NameIt, value));
}
}
}
/// <summary>Conti della compagnia e prestiti.</summary>
public partial class FinancePanel : VBoxContainer
{
private readonly GameSession _session;
private readonly Label _cash = PanelKit.Value();
private readonly Label _worth = PanelKit.Value();
private readonly Label _rating = PanelKit.Value();
private readonly SpinBox _loan = new() { MinValue = 10_000, MaxValue = 10_000_000, Step = 10_000, Value = 100_000, Prefix = "₤", SizeFlagsHorizontal = SizeFlags.ExpandFill };
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
public FinancePanel(GameSession session)
{
_session = session;
AddThemeConstantOverride("separation", 10);
AddChild(UiTheme.TitleLabel(T("Finanze"), 34));
AddChild(PanelKit.Pair(T("Cassa"), _cash));
AddChild(PanelKit.Pair(T("Patrimonio netto"), _worth));
AddChild(PanelKit.Pair(T("Rating"), _rating));
AddChild(PanelKit.Separator());
AddChild(UiTheme.Text(T("Prestito"), 14, bold: true));
AddChild(_loan);
var take = UiTheme.Primary(T("Chiedi il prestito"));
take.Pressed += () => _session.Command(new TakeLoanCommand(Money.FromLire((long)_loan.Value)), r => _status.Text = r.Message);
AddChild(take);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(_status);
}
public override void _Process(double delta)
{
var w = _session.World;
var me = w.Summary is null ? null : w.Companies.GetValueOrDefault(w.Summary.CompanyId);
_cash.Text = (w.LastDigest?.Cash ?? me?.Cash ?? default).ToString();
_worth.Text = (w.LastDigest?.NetWorth ?? me?.NetWorth ?? default).ToString();
_rating.Text = w.LastDigest?.Rating ?? me?.Rating ?? "—";
}
}
@@ -0,0 +1 @@
uid://bnvriayoaoihl
@@ -0,0 +1,124 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol.Client;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
/// <summary>
/// Strumento binari: classe, ponti, gallerie, doppio binario, elettrificazione e quota; anteprima
/// del profilo con opere, costo e giorni (calcolata con Core come farà il server).
/// </summary>
public partial class TrackPanel : VBoxContainer
{
private readonly ClientWorld _world;
private readonly OptionButton _class = new();
private readonly CheckBox _bridges = new() { Text = T("Ponti"), ButtonPressed = true };
private readonly CheckBox _tunnels = new() { Text = T("Gallerie"), ButtonPressed = true };
private readonly CheckBox _double = new() { Text = T("Doppio binario") };
private readonly CheckBox _electric = new() { Text = T("Elettrificato") };
private readonly HSlider _height = new() { SizeFlagsHorizontal = SizeFlags.ExpandFill, Step = 0.5 };
private readonly Label _heightValue = PanelKit.Value("0 m");
private readonly ProfileChart _chart = new();
private readonly VBoxContainer _summary = PanelKit.Column(4);
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
public Button Build { get; } = UiTheme.Primary(T("Costruisci"));
public Button Cancel { get; } = new() { Text = T("Annulla") };
public event Action? OptionsChanged;
public TrackPanel(ClientWorld world)
{
_world = world;
AddThemeConstantOverride("separation", 10);
AddChild(UiTheme.TitleLabel(T("Binari"), 34));
AddChild(UiTheme.Text(T("Clic sulla mappa per i punti del tracciato (Maiusc: senza scatto a 45°), Invio per costruire, tasto destro per annullare."), 13, Palette.TextSecondary));
foreach (var cls in world.Data.Eras.TrackClasses)
{
_class.AddItem($"{cls.NameIt}", cls.Index);
_class.SetItemDisabled(_class.ItemCount - 1, cls.From > world.Year);
}
_class.Selected = 0;
AddChild(PanelKit.Pair(T("Classe"), new Label()));
AddChild(_class);
var flags = new GridContainer { Columns = 2 };
flags.AddChild(_bridges);
flags.AddChild(_tunnels);
flags.AddChild(_double);
flags.AddChild(_electric);
AddChild(flags);
double range = world.Data.Construction.Profile.HeightOffsetRangeM;
_height.MinValue = -range;
_height.MaxValue = range;
AddChild(PanelKit.Pair(T("Quota rispetto al terreno"), _heightValue));
AddChild(_height);
var buttons = PanelKit.Row();
Build.SizeFlagsHorizontal = SizeFlags.ExpandFill;
Cancel.SizeFlagsHorizontal = SizeFlags.ExpandFill;
buttons.AddChild(Build);
buttons.AddChild(Cancel);
AddChild(buttons);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(_status);
AddChild(_chart);
AddChild(_summary);
_class.ItemSelected += _ => OptionsChanged?.Invoke();
foreach (var c in new[] { _bridges, _tunnels, _double, _electric }) c.Toggled += _ => OptionsChanged?.Invoke();
_height.ValueChanged += v =>
{
_heightValue.Text = $"{v:+0.0;-0.0;0} m";
OptionsChanged?.Invoke();
};
Show(null);
}
public string TrackClass => _world.Data.Eras.TrackClasses[Math.Max(0, _class.Selected)].Id;
public bool AllowBridges => _bridges.ButtonPressed;
public bool AllowTunnels => _tunnels.ButtonPressed;
public bool DoubleTrack => _double.ButtonPressed;
public bool Electrified => _electric.ButtonPressed;
public double HeightOffset => _height.Value;
public void SetStatus(string text, bool error = false)
{
_status.Text = text;
_status.AddThemeColorOverride("font_color", error ? Palette.Danger : Palette.TextSecondary);
}
public void Show(TrackPlan? plan)
{
_chart.Show(plan);
foreach (var child in _summary.GetChildren()) child.QueueFree();
Build.Disabled = plan is not { Valid: true };
if (plan is null)
{
_summary.AddChild(UiTheme.Text(T("Nessun tracciato"), 13, Palette.TextSecondary));
return;
}
_summary.AddChild(PanelKit.Pair(T("Lunghezza"), PanelKit.Value($"{plan.LengthM / 1000:0.00} km")));
_summary.AddChild(PanelKit.Pair(T("Pendenza massima"), PanelKit.Value($"{plan.MaxGradient * 100:0.0} % / {plan.GradientLimit * 100:0.0} %")));
_summary.AddChild(PanelKit.Pair(T("Raggio minimo"), PanelKit.Value(double.IsInfinity(plan.MinRadiusM) ? "—" : $"{plan.MinRadiusM:0} m")));
foreach (var kind in new[] { WorkKind.Embankment, WorkKind.Cutting, WorkKind.Bridge, WorkKind.Tunnel })
{
double len = plan.LengthOf(kind);
if (len <= 0) continue;
string name = kind switch
{
WorkKind.Embankment => T("Rilevato"),
WorkKind.Cutting => T("Trincea"),
WorkKind.Bridge => T("Ponte") + (plan.BridgeType is { } b ? $" ({b})" : ""),
_ => T("Galleria"),
};
_summary.AddChild(PanelKit.Pair(name, PanelKit.Value($"{len:0} m")));
}
var cost = PanelKit.Value(plan.TotalCost.ToString());
cost.AddThemeColorOverride("font_color", Palette.AmberLight);
_summary.AddChild(PanelKit.Pair(T("Costo"), cost));
_summary.AddChild(PanelKit.Pair(T("Cantiere"), PanelKit.Value($"{plan.Days} {T("giorni")}")));
foreach (var e in plan.Errors.Take(3)) _summary.AddChild(UiTheme.Notice(e.Message));
foreach (var e in plan.Warnings.Take(2)) _summary.AddChild(UiTheme.Text(e.Message, 12, Palette.AmberLight));
}
}
@@ -0,0 +1 @@
uid://x2netu5v1ewj
@@ -0,0 +1,195 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol.Messages;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
/// <summary>
/// Treni: acquisto dei veicoli in un deposito, composizione, assegnazione alle linee, rientro.
/// Ogni azione è un comando; la lista si aggiorna con i delta del server.
/// </summary>
public partial class TrainsPanel : VBoxContainer
{
private readonly GameSession _session;
private readonly OptionButton _depot = new();
private readonly OptionButton _vehicle = new();
private readonly SpinBox _count = new() { MinValue = 1, MaxValue = 12, Value = 1 };
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 _status = UiTheme.Text("", 13, Palette.TextSecondary);
private readonly List<int> _depotIds = [];
private readonly List<VehicleDef> _catalog = [];
private readonly List<int> _vehicleIds = [];
private readonly List<int> _trainIds = [];
private readonly List<int> _lineIds = [];
private int _version = -1;
public event Action<int>? TrainSelected;
public TrainsPanel(GameSession session)
{
_session = session;
AddThemeConstantOverride("separation", 8);
AddChild(UiTheme.TitleLabel(T("Treni"), 34));
AddChild(PanelKit.Pair(T("Deposito"), new Label()));
AddChild(_depot);
var buy = PanelKit.Row();
_vehicle.SizeFlagsHorizontal = SizeFlags.ExpandFill;
buy.AddChild(_vehicle);
buy.AddChild(_count);
AddChild(buy);
var buyButton = UiTheme.Primary(T("Compra veicoli"));
buyButton.Pressed += Buy;
AddChild(buyButton);
AddChild(UiTheme.Text(T("Veicoli liberi nel deposito (selezione multipla, in ordine)"), 13, Palette.TextSecondary));
AddChild(_inDepot);
var compose = PanelKit.Row();
_name.SizeFlagsHorizontal = SizeFlags.ExpandFill;
compose.AddChild(_name);
var composeButton = new Button { Text = T("Componi") };
composeButton.Pressed += Compose;
compose.AddChild(composeButton);
AddChild(compose);
AddChild(PanelKit.Separator());
AddChild(UiTheme.Text(T("Treni della compagnia"), 14, bold: true));
AddChild(_trains);
var assign = PanelKit.Row();
_line.SizeFlagsHorizontal = SizeFlags.ExpandFill;
assign.AddChild(_line);
var assignButton = new Button { Text = T("Assegna") };
assignButton.Pressed += Assign;
assign.AddChild(assignButton);
AddChild(assign);
var home = new Button { Text = T("Manda al deposito") };
home.Pressed += SendHome;
AddChild(home);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(_status);
_depot.ItemSelected += _ => Refresh(force: true);
_trains.ItemSelected += i => TrainSelected?.Invoke(_trainIds[(int)i]);
}
public override void _Process(double delta)
{
if (_session.World.EntityVersion != _version) Refresh(force: false);
}
private int Company => _session.World.Summary?.CompanyId ?? 0;
private void Refresh(bool force)
{
var w = _session.World;
_version = w.EntityVersion;
int selectedDepot = _depot.Selected >= 0 && _depot.Selected < _depotIds.Count ? _depotIds[_depot.Selected] : -1;
_depotIds.Clear();
_depot.Clear();
foreach (var d in w.Depots.Values.Where(d => d.Owner == Company).OrderBy(d => d.Id))
{
_depotIds.Add(d.Id);
_depot.AddItem(d.Name);
}
int di = _depotIds.IndexOf(selectedDepot);
_depot.Selected = di >= 0 ? di : _depotIds.Count > 0 ? 0 : -1;
if (_catalog.Count == 0 || force)
{
int keep = _vehicle.Selected;
_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)))
{
_catalog.Add(def);
_vehicle.AddItem($"{def.NameIt} — {new Money(def.Price)}");
}
_vehicle.Selected = keep >= 0 && keep < _catalog.Count ? keep : 0;
}
int depot = _depot.Selected >= 0 ? _depotIds[_depot.Selected] : -1;
_vehicleIds.Clear();
_inDepot.Clear();
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 selectedTrain = _trains.GetSelectedItems() is { Length: > 0 } sel ? _trainIds[sel[0]] : -1;
_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}");
}
int ti = _trainIds.IndexOf(selectedTrain);
if (ti >= 0) _trains.Select(ti);
int selectedLine = _line.Selected >= 0 && _line.Selected < _lineIds.Count ? _lineIds[_line.Selected] : -1;
_lineIds.Clear();
_line.Clear();
_lineIds.Add(-1);
_line.AddItem(T("Nessuna linea"));
foreach (var l in w.Lines.Values.Where(l => l.Owner == Company).OrderBy(l => l.Id))
{
_lineIds.Add(l.Id);
_line.AddItem(l.Name);
}
int li = _lineIds.IndexOf(selectedLine);
_line.Selected = li >= 0 ? li : Math.Min(1, _lineIds.Count - 1);
}
public static string StateName(TrainState s) => s switch
{
TrainState.InDepot => T("in deposito"),
TrainState.Moving => T("in marcia"),
TrainState.Waiting => T("in attesa di via libera"),
TrainState.Loading => T("in stazione"),
TrainState.Stalled => T("fermo in salita"),
TrainState.Broken => T("guasto"),
TrainState.NoRoute => T("senza percorso"),
_ => s.ToString(),
};
private void Result(CommandResultMessage r) => _status.Text = r.Message;
private void Buy()
{
if (_depot.Selected < 0 || _vehicle.Selected < 0) { _status.Text = T("Serve un deposito"); return; }
_session.Command(new BuyVehicleCommand(_catalog[_vehicle.Selected].Id, new DepotId(_depotIds[_depot.Selected]), (int)_count.Value), Result);
}
private void Compose()
{
if (_depot.Selected < 0) return;
var selected = _inDepot.GetSelectedItems().OrderBy(i => i).Select(i => new VehicleId(_vehicleIds[i])).ToList();
if (selected.Count == 0) { _status.Text = T("Seleziona i veicoli da comporre"); return; }
string? name = string.IsNullOrWhiteSpace(_name.Text) ? null : _name.Text.Trim();
_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 Assign()
{
int train = SelectedTrain;
if (train < 0 || _line.Selected < 0) { _status.Text = T("Seleziona un treno"); return; }
_session.Command(new AssignTrainCommand(new TrainId(train), new LineId(_lineIds[_line.Selected])), Result);
}
private void SendHome()
{
int train = SelectedTrain;
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);
}
}
@@ -0,0 +1 @@
uid://s6uq2ln014q2
@@ -0,0 +1,91 @@
using Godot;
using ViaFerrea.Client.App;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Screens;
/// <summary>
/// Collegamento a un server (immagine 09 non fornita: palette e componenti dell'immagine 05).
/// Ricorda indirizzo e token in user://settings.cfg.
/// </summary>
public partial class ConnectScreen : Control
{
private const string SettingsPath = "user://settings.cfg";
private readonly LineEdit _address = new() { PlaceholderText = "unraid.lan:7400" };
private readonly LineEdit _token = new() { Secret = true, PlaceholderText = T("Token del server") };
private readonly Label _status = UiTheme.Text("", 14, Palette.TextSecondary);
private readonly Button _connect = UiTheme.Primary(T("Collegati"));
public event Action<Uri, string, string>? ConnectRequested;
public event Action? Back;
public override void _Ready()
{
SetAnchorsPreset(LayoutPreset.FullRect);
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);
_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)
{
_address.Text = (string)cfg.GetValue("server", "address", "");
_token.Text = (string)cfg.GetValue("server", "token", "");
}
_token.TextSubmitted += _ => Submit();
}
public void SetStatus(string text, bool busy)
{
_status.Text = text;
_connect.Disabled = busy;
}
private void Submit()
{
string address = _address.Text.Trim();
if (address.Length == 0)
{
SetStatus(T("Indica l'indirizzo del server"), false);
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);
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);
}
}
@@ -0,0 +1 @@
uid://3yfity6oaer
@@ -0,0 +1,555 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Hud;
using ViaFerrea.Client.Map;
using ViaFerrea.Client.Net;
using ViaFerrea.Client.Panels;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol;
using ViaFerrea.Protocol.Messages;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Screens;
/// <summary>
/// Partita: mappa con i livelli, HUD (barra superiore, strumenti, pannello destro con minimappa,
/// notiziario) e logica degli strumenti. Ogni modifica è un comando al server; il client calcola
/// solo l'anteprima del tracciato con le classi di Core.
/// </summary>
public partial class GameScreen : Node
{
private readonly GameSession _session;
private readonly MapView _map = new();
private readonly LabelLayer _labels = new();
private readonly TopBar _top = new();
private readonly Toolbar _toolbar = new();
private readonly Ticker _ticker = new();
private readonly Minimap _minimap = new();
private readonly ScrollContainer _scroll = new() { SizeFlagsVertical = Control.SizeFlags.ExpandFill, HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled };
private readonly VBoxContainer _content = new() { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill };
private readonly VBoxContainer _toasts = new();
private readonly Control _disconnected = new();
private Tool _tool = Tool.None;
private TrackPanel? _trackPanel;
private StationPanel? _stationPanel;
private DepotPanel? _depotPanel;
private LinesPanel? _linesPanel;
private InfoPanel? _info;
private readonly List<Vector2> _trackPoints = [];
private Vector2? _mouse;
private bool _previewDirty;
private double _sincePreview;
private TrackPlan? _plan;
private Vector2 _lastViewportCenter;
private float _lastViewportZoom;
public event Action? Exit;
public GameScreen(GameSession session) => _session = session;
public GameSession Session => _session;
public MapView Map => _map;
/// <summary>Seleziona uno strumento come dalla barra (anche per il pilota automatico).</summary>
public void UseTool(Tool tool) => _toolbar.Select(tool);
/// <summary>Imposta i punti del tracciato in corso e aggiorna l'anteprima.</summary>
public void SetTrackPoints(IEnumerable<Vector2> points, Vector2? mouse)
{
_trackPoints.Clear();
_trackPoints.AddRange(points);
_mouse = mouse;
_previewDirty = true;
}
/// <summary>Mostra la scheda di un treno e lo evidenzia.</summary>
public void SelectTrain(int id)
{
_map.Trains.SelectedTrain = id;
_info?.Select(InfoPanel.Kind.Train, id);
}
public override void _Ready()
{
AddChild(_map);
var labelLayer = new CanvasLayer { Layer = 1 };
AddChild(labelLayer);
labelLayer.AddChild(_labels);
_labels.Bind(_session.World, _map.Camera);
var hud = new CanvasLayer { Layer = 2 };
AddChild(hud);
var root = new VBoxContainer { MouseFilter = Control.MouseFilterEnum.Ignore };
root.SetAnchorsPreset(Control.LayoutPreset.FullRect);
root.AddThemeConstantOverride("separation", 0);
hud.AddChild(root);
root.AddChild(_top);
var middle = new HBoxContainer { SizeFlagsVertical = Control.SizeFlags.ExpandFill, MouseFilter = Control.MouseFilterEnum.Ignore };
middle.AddThemeConstantOverride("separation", 0);
root.AddChild(middle);
middle.AddChild(_toolbar);
var mapArea = new Control { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, MouseFilter = Control.MouseFilterEnum.Ignore };
middle.AddChild(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);
var sideCol = new VBoxContainer();
sideCol.AddThemeConstantOverride("separation", 12);
side.AddChild(sideCol);
sideCol.AddChild(_scroll);
_scroll.AddChild(_content);
var miniHeader = new HBoxContainer();
var miniTitle = UiTheme.Text(T("Minimappa"), 13, Palette.TextSecondary);
miniTitle.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
miniHeader.AddChild(miniTitle);
miniHeader.AddChild(UiTheme.Text(_session.World.Summary?.RegionId is { Length: > 0 } r ? $"{T("Regione di")} {char.ToUpperInvariant(r[0])}{r[1..]}" : "", 13, Palette.TextSecondary));
sideCol.AddChild(miniHeader);
sideCol.AddChild(_minimap);
root.AddChild(_ticker);
BuildDisconnectedOverlay(hud);
_map.Bind(_session);
_minimap.Bind(_session.World, _map);
_top.Bind(_session);
_toolbar.Selected += SelectTool;
_map.Clicked += OnMapClicked;
_map.Hovered += OnMapHovered;
_map.Cancelled += () => _toolbar.Select(Tool.None);
_session.MessageApplied += OnMessage;
_session.Notified += e => _ticker.Add(e);
_session.CommandFailed += r => Toast(r.Message, error: true);
SelectTool(Tool.None);
SendViewport(force: true);
}
public override void _ExitTree() => _session.MessageApplied -= OnMessage;
private void BuildDisconnectedOverlay(CanvasLayer hud)
{
_disconnected.SetAnchorsPreset(Control.LayoutPreset.FullRect);
_disconnected.Visible = false;
var shade = new ColorRect { Color = new Color(0, 0, 0, 0.55f) };
shade.SetAnchorsPreset(Control.LayoutPreset.FullRect);
_disconnected.AddChild(shade);
var center = new CenterContainer();
center.SetAnchorsPreset(Control.LayoutPreset.FullRect);
_disconnected.AddChild(center);
var panel = new PanelContainer();
var col = new VBoxContainer();
col.AddThemeConstantOverride("separation", 12);
col.AddChild(UiTheme.TitleLabel(T("Connessione persa"), 36));
col.AddChild(UiTheme.Text(T("Il server non risponde più. La partita continua sul server."), 14, Palette.TextSecondary));
var back = UiTheme.Primary(T("Torna al menu"));
back.Pressed += () => Exit?.Invoke();
col.AddChild(back);
panel.AddChild(col);
center.AddChild(panel);
hud.AddChild(_disconnected);
}
// ------------------------------------------------------------------ messaggi e ciclo
private void OnMessage(IMessage m)
{
switch (m)
{
case MapChunk c:
_map.Terrain.MarkDirty(c.Cx, c.Cy);
_map.Entities.ForestChunk(c.Cx, c.Cy);
break;
case Welcome:
// nuova partita o caricamento: si ricomincia dalla copia locale vuota
_map.Bind(_session);
_minimap.Bind(_session.World, _map);
SendViewport(force: true);
break;
case DailyDigest d:
foreach (var e in d.Events.Where(e => e.Severity >= 2)) _ticker.Add(e);
break;
}
}
public override void _Process(double delta)
{
_session.Poll();
_disconnected.Visible = !_session.IsOpen;
SendViewport(force: false);
_sincePreview += delta;
if (_previewDirty && _sincePreview > 0.12)
{
_previewDirty = false;
_sincePreview = 0;
UpdateTrackPreview();
}
}
/// <summary>Sottoscrive l'area visibile quando la camera si sposta di almeno un quarto di schermo.</summary>
private void SendViewport(bool force)
{
var w = _session.World;
if (w.Summary is null) return;
var view = _map.VisibleRect();
var center = view.GetCenter();
if (!force && center.DistanceTo(_lastViewportCenter) < view.Size.X / 4 && Math.Abs(_map.Zoom - _lastViewportZoom) < _lastViewportZoom * 0.3f) return;
_lastViewportCenter = center;
_lastViewportZoom = _map.Zoom;
double cs = w.Summary.CellSizeM;
_session.Send(new Subscribe
{
X0 = Math.Max(0, (int)(view.Position.X / cs)),
Y0 = Math.Max(0, (int)(view.Position.Y / cs)),
X1 = Math.Min(w.Summary.WidthCells - 1, (int)(view.End.X / cs)),
Y1 = Math.Min(w.Summary.HeightCells - 1, (int)(view.End.Y / cs)),
Lod = (byte)(_map.Zoom >= MapScale.DetailZoom ? 0 : _map.Zoom >= MapScale.OverviewZoom ? 1 : 2),
});
}
public override void _UnhandledKeyInput(InputEvent e)
{
if (e is not InputEventKey { Pressed: true } key) return;
switch (key.Keycode)
{
case Key.Escape:
_toolbar.Select(Tool.None);
break;
case Key.Enter or Key.KpEnter when _tool == Tool.Track:
BuildTrack();
break;
case Key.Backspace when _tool == Tool.Track && _trackPoints.Count > 0:
_trackPoints.RemoveAt(_trackPoints.Count - 1);
_previewDirty = true;
break;
case Key.Space:
_session.SetSpeed(_session.World.Speed == 0 ? (byte)1 : (byte)0);
break;
}
}
// ------------------------------------------------------------------ strumenti
private void SelectTool(Tool tool)
{
_tool = tool;
_trackPoints.Clear();
_plan = null;
_map.Tools.Clear();
_map.Entities.SelectedStation = -1;
foreach (var c in _content.GetChildren()) c.QueueFree();
_trackPanel = null;
_stationPanel = null;
_depotPanel = null;
_linesPanel = null;
_info = null;
Control panel;
switch (tool)
{
case Tool.Track:
_trackPanel = new TrackPanel(_session.World);
_trackPanel.OptionsChanged += () => _previewDirty = true;
_trackPanel.Build.Pressed += BuildTrack;
_trackPanel.Cancel.Pressed += () => _toolbar.Select(Tool.None);
panel = _trackPanel;
break;
case Tool.Station:
panel = _stationPanel = new StationPanel(_session);
break;
case Tool.Depot:
panel = _depotPanel = new DepotPanel(_session);
break;
case Tool.Signal:
panel = new HelpPanel(T("Segnali"), T("Clic su un binario per posare un segnale di blocco: divide l'arco in sezioni e aumenta la capacità della linea."));
break;
case Tool.Demolish:
panel = new HelpPanel(T("Demolisci"), T("Clic su una stazione, un deposito o un binario libero per demolirlo; si recupera una parte del costo."));
break;
case Tool.Trains:
var trains = new TrainsPanel(_session);
trains.TrainSelected += id =>
{
_map.Trains.SelectedTrain = id;
if (_map.Trains.Heads.TryGetValue(id, out var p)) _map.CenterOn(p);
};
panel = trains;
break;
case Tool.Lines:
_linesPanel = new LinesPanel(_session);
_linesPanel.StopsChanged += UpdateStopsOverlay;
panel = _linesPanel;
break;
case Tool.Market:
panel = new MarketPanel(_session);
break;
case Tool.Finance:
panel = new FinancePanel(_session);
break;
default:
panel = _info = new InfoPanel(_session);
break;
}
panel.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
_content.AddChild(panel);
}
private void OnMapHovered(Vector2 world)
{
_mouse = world;
switch (_tool)
{
case Tool.Track:
if (_trackPoints.Count > 0) _previewDirty = true;
_map.Tools.SetTrack(_trackPoints, Snap(world), _plan);
break;
case Tool.Station:
_map.Tools.SetGhost(ToolOverlay.Ghost.Station, world);
break;
case Tool.Depot:
_map.Tools.SetGhost(ToolOverlay.Ghost.Depot, world);
break;
case Tool.Demolish:
_map.Tools.SetGhost(ToolOverlay.Ghost.Demolish, world);
break;
}
}
private void OnMapClicked(Vector2 world)
{
var w = _session.World;
var p = MapScale.W(world);
switch (_tool)
{
case Tool.Track:
_trackPoints.Add(Snap(world));
_previewDirty = true;
break;
case Tool.Station when _stationPanel is not null:
string? name = string.IsNullOrWhiteSpace(_stationPanel.StationName.Text) ? null : _stationPanel.StationName.Text.Trim();
_session.Command(new BuildStationCommand(p, (int)_stationPanel.Platforms.Value, name), r => { if (r.Ok) Toast(r.Message); });
break;
case Tool.Depot when _depotPanel is not null:
_session.Command(new BuildDepotCommand(p, _depotPanel.SelectedSize), r => { if (r.Ok) Toast(r.Message); });
break;
case Tool.Signal:
if (NearestEdge(world) is { } hit)
_session.Command(new PlaceSignalCommand(new EdgeId(hit.Edge), hit.S), r => { if (r.Ok) Toast(r.Message); });
break;
case Tool.Demolish:
Demolish(world);
break;
case Tool.Lines when _linesPanel is not null:
if (NearestStation(world) is { } station) _linesPanel.AddStop(station);
break;
default:
SelectAt(world);
break;
}
}
/// <summary>Scatto a 45° rispetto al punto precedente (Maiusc per disattivarlo).</summary>
private Vector2 Snap(Vector2 world)
{
if (_trackPoints.Count == 0 || Input.IsKeyPressed(Key.Shift)) return world;
var prev = _trackPoints[^1];
var d = world - prev;
if (d.LengthSquared() < 1) return world;
float step = MathF.PI / 4;
float angle = MathF.Round(d.Angle() / step) * step;
return prev + Vector2.FromAngle(angle) * d.Length();
}
private void UpdateTrackPreview()
{
if (_tool != Tool.Track || _trackPanel is null) return;
var pts = new List<Vector2>(_trackPoints);
if (_mouse is { } m && pts.Count >= 1) pts.Add(Snap(m));
if (pts.Count < 2)
{
_plan = null;
_trackPanel.Show(null);
_map.Tools.SetTrack(_trackPoints, _mouse, null);
return;
}
try
{
_plan = _session.World.PreviewTrack(TrackCommand(pts, 0));
_trackPanel.Show(_plan);
_trackPanel.SetStatus("");
}
catch (Exception e)
{
_plan = null;
_trackPanel.Show(null);
_trackPanel.SetStatus(T("Anteprima non disponibile: ") + e.Message, error: true);
}
_map.Tools.SetTrack(_trackPoints, _mouse is { } mm ? Snap(mm) : null, _plan);
}
private BuildTrackCommand TrackCommand(List<Vector2> pts, long expectedCost)
{
var p = _trackPanel!;
return new BuildTrackCommand(pts.Select(MapScale.W).ToList(), p.HeightOffset, p.AllowBridges, p.AllowTunnels, p.TrackClass, p.DoubleTrack, p.Electrified, expectedCost);
}
private void BuildTrack()
{
if (_trackPanel is null || _trackPoints.Count < 2) return;
// si costruisce il tracciato dei punti fissati (senza il punto sotto il mouse)
var plan = _session.World.PreviewTrack(TrackCommand(_trackPoints, 0));
if (!plan.Valid)
{
_trackPanel.SetStatus(plan.Errors[0].Message, error: true);
return;
}
_session.Command(TrackCommand(_trackPoints, plan.TotalCost.Cents), r =>
{
if (!r.Ok)
{
_trackPanel?.SetStatus(r.Message, error: true);
return;
}
Toast(r.Message);
// il prossimo tratto parte dall'ultimo punto
var last = _trackPoints[^1];
_trackPoints.Clear();
_trackPoints.Add(last);
_plan = null;
_trackPanel?.Show(null);
_map.Tools.SetTrack(_trackPoints, _mouse, null);
});
}
private void UpdateStopsOverlay()
{
if (_linesPanel is null) return;
var pts = _linesPanel.Stops.Where(_session.World.Stations.ContainsKey).Select(s => MapScale.V(_session.World.Stations[s].Position)).ToList();
_map.Tools.SetStops(pts);
}
private float PickRadius => 24f / _map.Zoom;
private int? NearestStation(Vector2 world)
{
int? best = null;
float bestD = Math.Max(PickRadius, 150);
foreach (var s in _session.World.Stations.Values)
{
float d = MapScale.V(s.Position).DistanceTo(world);
if (d < bestD)
{
bestD = d;
best = s.Id;
}
}
return best;
}
private int? NearestDepot(Vector2 world)
{
int? best = null;
float bestD = Math.Max(PickRadius, 120);
foreach (var d in _session.World.Depots.Values)
{
float dist = MapScale.V(d.Position).DistanceTo(world);
if (dist < bestD)
{
bestD = dist;
best = d.Id;
}
}
return best;
}
private (int Edge, double S)? NearestEdge(Vector2 world)
{
(int, double)? best = null;
double bestD = Math.Max(PickRadius, 25);
var p = MapScale.W(world);
foreach (var e in _session.World.Edges.Values)
{
for (int i = 0; i < e.S.Length - 1; i++)
{
var a = new Vec2(e.X[i], e.Y[i]);
var b = new Vec2(e.X[i + 1], e.Y[i + 1]);
double d = RailNetwork.DistanceToSegment(p, a, b, out double t);
if (d >= bestD) continue;
bestD = d;
best = (e.Id, e.S[i] + (e.S[i + 1] - e.S[i]) * t);
}
}
return best;
}
private void Demolish(Vector2 world)
{
if (NearestStation(world) is { } st)
_session.Command(new DemolishCommand(DemolishTarget.Station, st), r => { if (r.Ok) Toast(r.Message); });
else if (NearestDepot(world) is { } dp)
_session.Command(new DemolishCommand(DemolishTarget.Depot, dp), r => { if (r.Ok) Toast(r.Message); });
else if (NearestEdge(world) is { } hit)
_session.Command(new DemolishCommand(DemolishTarget.Edge, hit.Edge), r => { if (r.Ok) Toast(r.Message); });
}
private void SelectAt(Vector2 world)
{
if (_info is null) return;
var w = _session.World;
foreach (var (id, head) in _map.Trains.Heads)
{
if (head.DistanceTo(world) < PickRadius * 1.5f)
{
_map.Trains.SelectedTrain = id;
_info.Select(InfoPanel.Kind.Train, id);
return;
}
}
_map.Trains.SelectedTrain = -1;
if (NearestStation(world) is { } st)
{
_map.Entities.SelectedStation = st;
_map.Entities.QueueRedraw();
_info.Select(InfoPanel.Kind.Station, st);
return;
}
_map.Entities.SelectedStation = -1;
_map.Entities.QueueRedraw();
double cs = w.Summary?.CellSizeM ?? 100;
foreach (var ind in w.Industries.Values)
{
if (MapScale.V(ind.Position).DistanceTo(world) < Math.Max(PickRadius, ind.FootprintCells * cs * 0.6))
{
_info.Select(InfoPanel.Kind.Industry, ind.Id);
return;
}
}
foreach (var town in w.Towns.Values)
{
if (MapScale.V(town.Position).DistanceTo(world) < Math.Max(PickRadius, (town.RadiusCells + 0.5) * cs))
{
_info.Select(InfoPanel.Kind.Town, town.Id);
return;
}
}
_info.Select(InfoPanel.Kind.None, -1);
}
/// <summary>Messaggio temporaneo in alto sulla mappa.</summary>
private 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));
_toasts.AddChild(notice);
GetTree().CreateTimer(4.5).Timeout += () =>
{
if (IsInstanceValid(notice)) notice.QueueFree();
};
while (_toasts.GetChildCount() > 4) _toasts.GetChild(0).QueueFree();
}
}
@@ -0,0 +1 @@
uid://ddktpojqhxvg6
@@ -0,0 +1,54 @@
using Godot;
using ViaFerrea.Client.App;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Screens;
/// <summary>Menu iniziale: partita locale (server figlio), collegamento a un server, lingua, uscita.</summary>
public partial class MenuScreen : Control
{
public event Action? LocalGame;
public event Action? ConnectToServer;
public event Action<string>? LanguageChanged;
private readonly Label _status = UiTheme.Text("", 14, Palette.TextSecondary);
public override void _Ready()
{
SetAnchorsPreset(LayoutPreset.FullRect);
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("Via Ferrea", 96));
col.AddChild(UiTheme.Text(T("Gestionale ferroviario dall'alto"), 18, Palette.TextSecondary));
col.AddChild(new Control { CustomMinimumSize = new Vector2(0, 20) });
var local = UiTheme.Primary(T("Partita locale"));
local.CustomMinimumSize = new Vector2(0, 48);
local.Pressed += () => LocalGame?.Invoke();
col.AddChild(local);
var remote = new Button { Text = T("Collegati a un server"), CustomMinimumSize = new Vector2(0, 48) };
remote.Pressed += () => ConnectToServer?.Invoke();
col.AddChild(remote);
var lang = new HBoxContainer();
lang.AddThemeConstantOverride("separation", 8);
foreach (var (code, label) in new[] { ("it", "Italiano"), ("en", "English") })
{
var b = new Button { Text = label, ToggleMode = true, ButtonPressed = TranslationServer.GetLocale().StartsWith(code) };
b.Pressed += () => LanguageChanged?.Invoke(code);
lang.AddChild(b);
}
col.AddChild(lang);
var quit = new Button { Text = T("Esci"), CustomMinimumSize = new Vector2(0, 40) };
quit.Pressed += () => GetTree().Quit();
col.AddChild(quit);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(_status);
}
public void SetStatus(string text) => _status.Text = text;
}
@@ -0,0 +1 @@
uid://b5eyw35w2vo7l
+16 -15
View File
@@ -8,7 +8,7 @@ Questo documento descrive come è fatto il codice. Va aggiornato a ogni fase: le
ViaFerrea.Core (net10.0; net8.0) simulazione deterministica, dati, mappa, economia, rete, salvataggi
ViaFerrea.Protocol (net10.0; net8.0) frame binari, messaggi, SpanWriter/SpanReader → Core
ViaFerrea.Server (net10.0, Web SDK) Kestrel, WebSocket, GameLoop, API HTTP, autosave → Core, Protocol
ViaFerrea.Tools (net10.0) viaferrea-tools: validate-data, genmap, profile, simulate, bench, replay → Core, Protocol
ViaFerrea.Tools (net10.0) viaferrea-tools: validate-data, genmap, profile, simulate, bench, smoke, replay → Core, Protocol
ViaFerrea.Tests (net10.0) harness interno, test di unità, scenari → Core, Protocol, Server
client/ViaFerrea.Client (Godot .NET) rendering, input, UI; anteprime con Core → Core, Protocol
```
@@ -97,23 +97,24 @@ Requisito: stesso seme + stessi comandi agli stessi tick ⇒ stesso hash di stat
- Definizioni salvate per id testuale e rimappate al caricamento; terreno salvato per intero.
- `StateHasher` = XxHash64 di `WorldSerializer.WriteDynamic` (stato senza terreno, impostazioni ed eventi; il terreno entra con il suo hash). Dettagli: ADR 0006.
## 8. Server *(pianificato, F3)*
## 8. Server
- `GameLoop` su thread dedicato con accumulatore: a velocità v esegue v tick ogni 50 ms reali; se un tick supera il budget riduce la velocità effettiva e segnala `slow` nel resoconto giornaliero.
- `SessionManager`: WebSocket su `/ws`, autenticazione con token nell'`Hello`, coda di invio per sessione con backpressure, riconnessione con `sessionId`, interesse per viewport.
- API HTTP: `/health`, `/metrics` (Prometheus), `/api/saves`.
- `ServerProgram`: Kestrel minimale, log JSON su stdout, configurazione da ambiente (`ServerConfig`: `VF_PORT`, `VF_TOKEN`, `VF_DATA_DIR`, `VF_TICK_MS`, `VF_AUTOSAVE_MIN`, `VF_SEED`, `VF_MAP_SIZE`, `VF_DIFFICULTY`, `VF_LOG_LEVEL`) e argomenti `--local` (127.0.0.1 su porta casuale, stampa `LISTENING porta`), `--healthcheck`, `--token`, `--port`, `--data`.
- `GameHost`: possiede il mondo su un thread dedicato. Ogni giro drena la coda delle azioni (messaggi delle sessioni, richieste HTTP), esegue i tick dovuti con un accumulatore (velocità 0/1/2/4/8, budget `VF_TICK_MS`), adegua la velocità effettiva se i tick costano troppo (`slow`), pubblica e fa l'autosave a rotazione.
- `Session` / `SessionEndpoint`: WebSocket su `/ws`, primo frame `Hello`, coda d'invio a due classi (affidabili e moti scartabili), ripresa con `sessionId` entro 120 s.
- `Projection`: mondo → record del protocollo (entità, archi, chunk, moto dei treni, resoconti); i delta per sessione si calcolano con gli hash dei record.
- `SaveStore`: salvataggi `.vfsave` in `$VF_DATA_DIR/saves`, ultimi cinque automatici; all'avvio si riprende il più recente.
- HTTP: `/health`, `/metrics` (Prometheus), `GET/POST /api/saves`, `GET /api/saves/{id}`.
- Docker: `docker/Dockerfile` (build in due stadi, utente non root, healthcheck), `docker-compose.yml`, `unraid-template.xml`; `scripts/publish-image.sh` per il registry Gitea.
## 9. Client *(pianificato, F3)*
## 9. Client
- Scene Godot: `Main` → `Menu`, `Connect`, `Game` (`MapView` + `Hud` + `Panels/`).
- Livelli di rendering: terreno per chunk (texture con fasce altimetriche, hillshade, curve di livello), binari e opere, entità, treni interpolati; LOD a zoom ridotto.
- `LocalServerLauncher` avvia il server come processo figlio per la partita in locale.
## 6 bis. Rete e circolazione
- Il binario è un grafo di nodi (estremità, scambi, stazioni, depositi) e archi campionati ogni 25 m con quota, opera e velocità ammessa. Gli archi si percorrono nei due versi; il doppio binario ha un binario per verso.
- I treni seguono un percorso A* fino alla prossima fermata e avanzano prenotando sezioni di blocco; sul binario semplice prenotano il verso fino al primo punto sicuro (ADR 0007).
- Le merci viaggiano in pacchetti (struct) con tratto corrente (linea, stazione di discesa); i pendolari sono pacchetti dei contratti. Il `LineGraph` per compagnia si ricostruisce quando cambia la versione di rete o linee (ADR 0008).
- Progetto Godot 4.7 .NET in `client/ViaFerrea.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.
- `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, mercato, finanze, scheda dell'entità.
- Collaudo: pilota automatico (`-- --autopilot cartella`, `scripts/client-autopilot.sh`) con schermate.
## 10. Prestazioni
+118 -36
View File
@@ -1,12 +1,13 @@
# Via Ferrea — Protocollo di rete (bozza)
# Via Ferrea — Protocollo di rete
Stato: **bozza F0**. Diventa normativo in F3, quando ogni messaggio avrà il test di round-trip.
Stato: **normativo da F3**. Ogni messaggio e ogni comando ha un test di round-trip
(`tests/ViaFerrea.Tests/Protocol/ProtocolTests.cs`); decisioni in ADR 0009.
## 1. Trasporto
- WebSocket su `ws://<host>:<porta>/ws` (TLS a carico del reverse proxy: `wss://`).
- Solo messaggi binari. Un messaggio WebSocket contiene esattamente un frame.
- Porta predefinita 7400 (`VF_PORT`).
- Porta predefinita 7400 (`VF_PORT`). Il primo messaggio del client dev'essere `Hello` entro 10 s.
## 2. Frame
@@ -17,37 +18,48 @@ offset tipo campo
6 ... payload corpo serializzato a mano
```
- Little endian. Dimensione massima 4 MB (`length ≤ 4 194 298`): frame più grandi chiudono la connessione con codice 1009.
- Serializzazione con `SpanWriter`/`SpanReader` (`Write(ref SpanWriter)` / `Read(ref SpanReader)` per ogni messaggio). Nessuna reflection, nessun JSON.
- Little endian. Dimensione massima 4 MB: frame più grandi chiudono la connessione (1009).
- `SpanWriter`/`SpanReader` con `Write(ref SpanWriter)` / `Read(ref SpanReader)` per ogni messaggio.
### Tipi elementari
| Tipo | Codifica |
|---|---|
| `bool` | 1 byte, 0 o 1 |
| `u8/u16/u32/u64`, `i8…i64` | little endian a larghezza fissa |
| `bool` | 1 byte, 0 o 1 (altri valori: errore) |
| `u8/u16/u32/u64`, `i16/i32/i64` | little endian a larghezza fissa |
| `varuint` | LEB128 (lunghezze e conteggi) |
| `f32/f64` | IEEE 754 little endian |
| `string` | `varuint` lunghezza in byte + UTF-8 |
| `bytes` | `varuint` lunghezza + byte |
| `Money` | `i64` centesimi |
| identità (`StationId`…) | `i32` |
| `Vec2` | due `f64` (metri) |
| identità | `i32` (−1 = nessuna) |
| liste | `varuint` conteggio + elementi |
| `flags` | `u8` di estensione in coda a ogni messaggio e record (0 oggi) |
### Evoluzione
- Gli id dei messaggi e l'ordine dei campi non cambiano mai.
- I campi nuovi si aggiungono in coda, dopo un `u8 flags` che dice quali blocchi opzionali seguono. Un lettore vecchio ignora i byte residui del payload.
- `protocolVersion` cresce solo per modifiche incompatibili.
- Gli id dei messaggi, dei comandi e l'ordine dei campi non cambiano mai.
- I campi nuovi si aggiungono in coda, dopo il byte `flags`, che dice quali blocchi seguono. Un
lettore vecchio ignora i byte residui; un messaggio vecchio senza `flags` vale 0.
- `protocolVersion` (oggi 1) cresce solo per modifiche incompatibili.
## 3. Handshake
```
Client → Hello { protocolVersion: u16, clientVersion: string, token: string, resumeSessionId: u64 (0 = nuova) }
Server → Welcome { sessionId: u64, worldSummary, dataHash: u64, difficulty: string }
Client → Hello { protocolVersion: u16, clientVersion: string, token: string, resumeSessionId: u64, dataHash: u64 }
Server → Welcome { sessionId: u64, summary: WorldSummary, dataHash: u64, difficulty: string }
| Reject { code: u16, reason: string }
```
Codici di `Reject`: 1 versione del protocollo, 2 token errato, 3 dati diversi, 4 server pieno, 5 partita non caricata.
- `resumeSessionId` ≠ 0 riprende una sessione disconnessa da meno di 120 s (stato rimandato per intero).
- `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.
`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,
costMultiplier: f64 }`
## 4. Messaggi Client → Server
@@ -55,19 +67,60 @@ Codici di `Reject`: 1 versione del protocollo, 2 token errato, 3 dati diversi, 4
|---|---|---|
| 1 | Hello | vedi handshake |
| 2 | Ping | `nonce: u64` |
| 3 | Subscribe | `viewport` (rettangolo in celle), livello di dettaglio |
| 4 | Command | `seq: u32`, `type: u16`, `payload` del comando |
| 3 | Subscribe | `x0, y0, x1, y1: i32` (celle, estremi inclusi), `lod: u8` |
| 4 | Command | `seq: u32`, `type: u16`, `payload: bytes` (vedi sotto) |
| 5 | SetSpeed | `speed: u8` (0, 1, 2, 4, 8) |
| 6 | ListSaves | — |
| 7 | Save | `name: string` |
| 8 | Load | `id: string` |
| 9 | NewGame | `seed`, `size`, `startYear`, `difficultyPreset`, `overrides`, `endlessFlags` |
| 8 | Load | `saveId: string` |
| 9 | NewGame | `seed: u64`, `sizeKm: i32`, `startYear: i32` (0 = predefinito), `difficultyPreset: string`, `overrides: [(key: string, value: f64)]`, `endlessFlags: u32` |
### Comandi (`Command.type`)
### Comandi (`Command.type`, payload in ordine)
BuildTrack, RenewTrack, UpgradeTrack, Demolish, BuildStation, BuildDepot, PlaceSignal, BuyVehicle, SellVehicle, ComposeTrain, CreateLine, EditLine, AssignTrain, SendToDepot, SetReserve, SetMaintenancePolicy, ScheduleService, OrderParts, TakeLoan, RepayLoan, AcceptAgreement, RejectAgreement, BuyGoods, SellGoods, BuyIndustry, SetIndustryPolicy, OverhaulIndustry, UpgradeIndustry, Ipo, BuyShares, SellShares, PayDividend, LaunchBid, RespondBid, BuyConcession, AcceptContract, FundResearch, DelegateRegion.
| type | Comando | Payload |
|---|---|---|
| 1 | BuildTrack | `polyline: [Vec2]`, `heightOffsetM: f64`, `allowBridges: bool`, `allowTunnels: bool`, `trackClass: string`, `doubleTrack: bool`, `electrified: bool`, `expectedCostCents: i64` (0 = non verificare) |
| 2 | RenewTrack | `edge: i32` |
| 3 | UpgradeTrack | `edge: i32`, `trackClass: string`, `doubleTrack: bool`, `electrified: bool` |
| 4 | Demolish | `target: u8` (0 arco, 1 stazione, 2 deposito, 3 segnali), `id: i32` |
| 5 | BuildStation | `position: Vec2`, `platforms: i32`, `name: bool + string` |
| 6 | BuildDepot | `position: Vec2`, `size: string`, `name: bool + string` |
| 7 | PlaceSignal | `edge: i32`, `positionM: f64` |
| 8 | BuyVehicle | `vehicleType: string`, `depot: i32`, `count: i32` |
| 9 | SellVehicle | `vehicle: i32` |
| 10 | ComposeTrain | `depot: i32`, `vehicles: [i32]`, `name: bool + string` |
| 11 | CreateLine | `name: string`, `color: string`, `stops: [LineStop]` |
| 12 | EditLine | `line: i32`, `stops: [LineStop]`, `name: bool + string` |
| 13 | AssignTrain | `train: i32`, `line: i32` (−1 = togli dal servizio) |
| 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` |
| 18 | OrderParts | `depot: i32`, `quantity: i32` |
| 19 | TakeLoan | `amount: Money` |
| 20 | RepayLoan | `loan: i32`, `amount: Money` |
| 21 | AcceptAgreement | `agreement: i32` |
| 22 | RejectAgreement | `agreement: i32` |
| 23 | BuyGoods | `station: i32`, `good: string`, `units: i32`, `maxUnitPrice: Money` |
| 24 | SellGoods | `station: i32`, `good: string`, `units: i32`, `minUnitPrice: Money` |
| 25 | BuyIndustry | `industry: i32`, `offer: Money` |
| 26 | SetIndustryPolicy | `industry: i32`, `budget: u8` (0 nessuno, 1 base, 2 alto) |
| 27 | OverhaulIndustry | `industry: i32` |
| 28 | UpgradeIndustry | `industry: i32` |
| 29 | Ipo | `floatShare: f64` |
| 30 | BuyShares | `company: i32`, `shares: i64`, `maxPrice: Money` |
| 31 | SellShares | `company: i32`, `shares: i64`, `minPrice: Money` |
| 32 | PayDividend | `perShare: Money` |
| 33 | LaunchBid | `target: i32`, `pricePerShare: Money`, `targetShare: f64` |
| 34 | RespondBid | `bid: i32`, `accept: bool` |
| 35 | BuyConcession | `region: i32` |
| 36 | AcceptContract | `contract: i32` |
| 37 | FundResearch | `project: string`, `amount: Money` |
| 38 | DelegateRegion | `region: i32`, `objective: string`, `budget: Money` |
I codici numerici dei comandi coincidono con l'enum `CommandType` di Core e non cambiano mai.
`LineStop { station: i32, load: bool, unload: bool, waitFull: bool, maxWaitDays: i32 }`. Ogni payload termina con `flags`.
I codici coincidono con l'enum `CommandType` di Core. Fino alla loro fase i comandi 15–18 e 21–38
(tranne 26) rispondono `NotImplemented`. Il server imposta l'emittente in base alla sessione.
## 5. Messaggi Server → Client
@@ -76,21 +129,50 @@ I codici numerici dei comandi coincidono con l'enum `CommandType` di Core e non
| 101 | Welcome | vedi handshake |
| 102 | Reject | vedi handshake |
| 103 | Pong | `nonce: u64`, `serverTick: u64` |
| 110 | MapChunk | coordinate del chunk 64×64, altezze, tipi cella |
| 111 | EntitySnapshot | stato completo delle entità visibili |
| 112 | EntityDelta | variazioni dall'ultimo snapshot |
| 113 | TrackWorks | opere per arco: tipo, altezze, stato del cantiere |
| 114 | TrainMotion | `trainId`, segmenti di moto, stato, condizione |
| 120 | DailyDigest | data, cassa, patrimonio, rating, prezzi, eventi, `stateHash`, `slow` |
| 121 | MaintenanceAlert | treno o deposito, componente, scadenza |
| 122 | EmploymentReport | mensile |
| 123 | MarketTape | giornaliero: prezzi delle azioni, offerte in corso |
| 130 | CommandResult | `seq`, esito, codice di errore, messaggio |
| 131 | Notification | livello, testo, riferimento all'entità |
| 132 | Newspaper | mensile: la «Cronaca» |
| 110 | MapChunk | `cx, cy, width, height: i32`, `compression: u8` (1 = Brotli), `data: bytes` = altezze `u16` (dm) + tipi `u8` + larghezza fiumi `u8` |
| 111 | EntitySnapshot | `tick: i64`, `EntityLists` |
| 112 | EntityDelta | `tick: i64`, `EntityLists` (nuovi o cambiati), `removed: [(type: u8, id: i32)]` |
| 113 | TrackWorks | `edges: [EdgeInfo]`, `removed: [i32]` (lotti sotto 1 MB) |
| 114 | TrainMotion | `trainId: i32`, `tick: i64`, `state: u8`, `condition: f32`, `speed: f32` (m/s), `lengthM: f32`, `headDistance: f64`, `segments: [(edge: i32, forward: bool, fromS: f64, toS: f64)]` |
| 120 | DailyDigest | `day: i64`, `tick: i64`, `date: string`, `cash: Money`, `netWorth: Money`, `rating: string`, `prices: [Money]`, `events: [EventInfo]`, `stateHash: u64`, `slow: bool`, `speed: u8`, `tickMs: f32` |
| 121 | MaintenanceAlert | `train: i32`, `depot: i32`, `component: string`, `condition: f32`, `dueDays: i32`, `text: string` |
| 122 | EmploymentReport | `day: i64`, `rows: [EmploymentRow]` (mensile) |
| 123 | MarketTape | `day: i64`, `shares: [SharePrice]`, `bids: [BidInfo]` |
| 130 | CommandResult | `seq: u32`, `type: u16`, `error: u16`, `message: string`, `created: [i32]`, `tick: i64` |
| 131 | Notification | `EventInfo` |
| 132 | Newspaper | `day: i64`, `title: string`, `articles: [(headline: string, body: string)]` |
| 133 | SaveList | `saves: [SaveInfo]` |
## 6. Interest management
Record (ognuno chiude con `flags`):
- `TrainMotion` solo per i treni nel viewport sottoscritto più un chunk di margine, al massimo 10 aggiornamenti al secondo per treno.
- I chunk della mappa si inviano su richiesta implicita (viewport) e una sola volta per sessione, salvo modifiche.
- `EntityLists`: liste in quest'ordine di `CompanyInfo`, `TownInfo`, `IndustryInfo`, `HubInfo`, `NodeInfo`, `StationInfo`, `DepotInfo`, `LineInfo`, `VehicleInfo`, `TrainInfo`.
- `CompanyInfo { id, name, color, isPlayer, cash: Money, netWorth: Money, rating, tier: u8, bankrupt }`
- `TownInfo { id, name, position: Vec2, population: i32, radiusCells: f64, satisfaction: f32, services: i32 }`
- `IndustryInfo { id, type: string, name, position, footprintCells: i32, level: i32, closed, efficiency: f32, condition: f32, owner: i32 }`
- `HubInfo { id, kind: string, name, position }`
- `NodeInfo { id, position, heightM: f64, owner, station, depot, edges: [i32] }`
- `StationInfo { id, owner, name, node, position, platforms: i32, waitingUnits: i32, industries: [i32], towns: [i32] }`
- `DepotInfo { id, owner, name, node, position, size: string }`
- `LineInfo { id, owner, name, color, stops: [LineStop] }`
- `VehicleInfo { id, owner, type: string, depot, train, condition: f32 }`
- `TrainInfo { id, owner, name, line, state: u8, vehicles: [i32], maxSpeedKmh: f32, lengthM: f32, load: i32, capacity: i32, depot: 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 }`
- `EmploymentRow { industry, jobsWorkers, jobsStaff, workersPresent: f32, staffPresent: f32, reason, sources: [EmploymentSource { town, homeStation, line, category: u8, headcount, coverage: f32 }] }`
- `SharePrice { company, price: Money, change: f32, listed }`, `BidInfo { bid, bidder, target, pricePerShare: Money, targetShare: f64, expiresDay: i64 }`
- `SaveInfo { saveId, name, gameDate, sizeBytes: i64, savedUnixMs: i64, autosave }`
## 6. Flusso e interest management
- Dopo il `Welcome` il server manda `EntitySnapshot` e tutti i `TrackWorks`; i chunk arrivano dopo
il primo `Subscribe` (viewport con un chunk di margine), una volta per sessione, e si rimandano se
cambiano.
- `EntityDelta` e `TrackWorks` incrementali dopo ogni comando riuscito e a ogni cambio di giorno.
- `TrainMotion` ogni 100 ms per i treni in moto con la testa nel viewport (più un chunk), una volta
per quelli fermi: al massimo 10 aggiornamenti al secondo per treno. Il client avanza la testa a
velocità costante tra un moto e l'altro (fattore 60: un tick = 3 s di orologio dei treni).
- `DailyDigest` a ogni giorno; `EmploymentReport` a ogni mese; `Notification` per gli eventi non
informativi della compagnia della sessione.
- 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.
+23 -4
View File
@@ -9,8 +9,9 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
| .NET SDK | 10.0.112 | da apt (Ubuntu 24.04, `dotnet-sdk-10.0`) |
| Runtime .NET / ASP.NET Core | 10.0.12 | |
| Targeting pack net8.0 | 8.0.31 | `dotnet-targeting-pack-8.0`, per Core e Protocol |
| Godot .NET | non installato | github.com non raggiungibile dall'ambiente cloud; `Godot.NET.Sdk` 4.7.2 è su NuGet |
| Docker CLI | 29.6.2 | demone non attivo nell'ambiente cloud |
| Godot .NET | 4.7.2.stable.mono | scaricato dal mirror SourceForge (github.com non raggiungibile); client compilato con `Godot.NET.Sdk` 4.7.2 da NuGet |
| Docker | 29.6.2 (CLI e demone) | demone avviato a mano nell'ambiente cloud; immagini di base da mcr.microsoft.com |
| Xvfb + Mesa (llvmpipe) | 21.1.12 / 25.2.8 | rendering software per il collaudo grafico del client |
| Sistema | Ubuntu 24.04.4 LTS x86_64, 4 core, 15 GB | |
## Fatto
@@ -43,19 +44,32 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
- `viaferrea-tools bench --trains 2000`: rete di 300 linee a doppio binario costruita con i comandi.
- 75 test (dati, mappa, economia, persistenza, pianificatore, rete, treni, incroci senza stallo, `Stalled`, salvataggio con treni in moto, pendolarismo, scenario Valdoria).
### F3 — Server e client minimo
- Protocollo (`ViaFerrea.Protocol`, normativo in `docs/PROTOCOL.md`): `SpanWriter`/`SpanReader`, frame, tutti i messaggi dei due versi e i 38 comandi (record definitivi in Core anche per le fasi future), byte di estensione, test di round-trip, troncamento e corruzione (ADR 0009).
- `ClientWorld` e `ProtocolClient` condivisi da client, test e strumenti; `TrackPreview` in Core: anteprima del client e piano del server con lo stesso codice (`PreviewMismatch` se differiscono).
- Server: `GameHost` con ciclo su thread dedicato, velocità e `slow`, sessioni WebSocket con backpressure e ripresa, snapshot e delta per hash, `TrackWorks` a lotti, chunk del viewport, moto dei treni, resoconti giornalieri e mensili, `/health`, `/metrics`, `/api/saves`, autosave a rotazione, log JSON, `--local`, `--healthcheck`.
- Docker: `docker/Dockerfile`, `docker-compose.yml`, `unraid-template.xml`; immagine costruita e provata (health, metriche, healthcheck interno, utente non root).
- Registro dei comandi (`--record` / `VF_RECORD`, con salvataggio di partenza) e `viaferrea-tools replay` con confronto dell'hash; `viaferrea-tools smoke` per collaudare un server in esecuzione.
- Client Godot 4.7 .NET: menu, collegamento, partita locale con server figlio, mappa con terreno (fasce, ombreggiatura, sponde, curve di livello), opere, entità, alberi, treni interpolati con fumo; strumenti binari (scatto a 45°, quota, ponti e gallerie, classe, profilo con opere, costo e giorni), stazione, deposito, segnali, demolizione; pannelli treni, linee, mercato, finanze, schede; barra superiore con velocità, minimappa, notiziario; italiano e inglese.
- Accettazione F3 verificata senza intervento umano: test in processo (linea con ponte via WebSocket, anteprima identica al server, scarto client/server sotto 1 cm), `viaferrea-tools smoke` contro il container Docker (ponte di 275 m, scarto 0,00 m) e pilota automatico del client Godot con schermate (`docs/screenshots/`).
- 85 test.
## In corso
- Nessun lavoro a metà: F2 chiusa.
- Nessun lavoro a metà: F3 chiusa.
## Prossimo passo
- F3: protocollo completo con test di round-trip di ogni messaggio, server (GameLoop, sessioni WebSocket, API HTTP, autosave, `/metrics`), file Docker, client Godot minimo (connessione, mappa con terreno e opere, strumento binari con profilo, stazioni, depositi, treni, linee, HUD, velocità).
- F4: pendolarismo completo (Registro degli impieghi, convenzioni `CommuteAgreement`, posti di personale nei depositi) e manutenzione dei treni della sezione 10 (componenti, guasti, soccorso, interventi, ricambi via treno, politiche, pianificatore predittivo, riserve); accettazione nello scenario con e senza linea dei ricambi.
## Limiti noti
- Le immagini di riferimento 06–09 (pannelli a tutto schermo e schermata di connessione) non sono state fornite: i pannelli seguiranno palette e componenti dell'immagine 05 finché non arrivano.
- 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 `VF_SERVER_PATH`.
- Nella vista d'insieme i fiumi larghi una cella mostrano ancora gradini; i pannelli 06–08 e la schermata di connessione 09 seguono la palette dell'immagine 05 finché non arrivano i riferimenti.
- In F3 tutte le sessioni guidano la compagnia del giocatore (ADR 0009).
- Il bilanciamento economico è provvisorio (F6): nello scenario l'acciaieria cresce di livello ogni due trimestri finché la linea operai non satura; il prezzo del minerale sale oltre 1,5 volte il base e il margine dei trasformatori diventa negativo quando la domanda supera l'offerta delle miniere.
- La lunghezza dei marciapiedi non è modellata; i segnali sono solo a blocco fisso (niente segnali di percorso).
- I depositi non hanno ancora posti per personale né officine (F4); le convenzioni (`CommuteAgreement`) e il Registro degli impieghi arrivano in F4.
@@ -74,3 +88,8 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
| Scenario Valdoria, 24 mesi con tre linee | 2,3 s | F2 |
| `bench --trains 2000` (256 km, 600 stazioni, 300 linee, 2.280 km di binario, 2.089 segnali) | tick medio 0,84 ms, p95 0,92, p99 1,21, massimo 10,5 (cambio di giorno); `TrainSystem` 0,79 ms | F2 |
| Allocazioni nel tick ordinario con 2.000 treni | < 1 KB (crescita delle liste), nessuna raccolta gen0 in 1.200 tick | F2 |
| Suite di test (85, parallela su 4 core) | ~14 s (il test di accettazione via WebSocket ~8 s) | F3 |
| Immagine Docker del server | 344 MB, build ~15 s con le immagini di base in cache | F3 |
| `smoke` contro il container (64 km, tick 50 ms) | 48 s: 28 giorni di cantiere a 8×, treno in moto, scarto 0,00 m | F3 |
| Build del client Godot (Debug) | ~13 s | F3 |
| Pilota automatico del client sotto Xvfb | ~60 s, 8 schermate | F3 |
+73
View File
@@ -0,0 +1,73 @@
# ADR 0009 — Protocollo, server, client e collaudi (F3)
Stato: accettato (F3).
## Contesto
La guida (sezione 14) fissa frame, elenco dei messaggi, configurazione del server, Docker e
struttura del client, ma lascia aperti il contenuto dei messaggi di stato, il calcolo dei delta,
la rappresentazione del moto dei treni, come il client calcola le anteprime con le stesse classi
del server e come collaudare client e immagine in un ambiente senza grafica.
## Decisione
1. **Evoluzione dei messaggi.** Ogni messaggio e ogni record termina con un byte di estensione
(0 oggi); i lettori ignorano i byte residui. I comandi viaggiano con il payload preceduto dalla
lunghezza, così un lettore vecchio può saltarli. Tutti i 38 comandi hanno già un record in Core
con il formato definitivo; quelli delle fasi future rispondono `NotImplemented`.
2. **Messaggio in più.** `SaveList` (133) risponde a `ListSaves` e `Save`: la guida elenca le
richieste ma non la risposta.
3. **Stato delle entità.** `EntitySnapshot` alla connessione e dopo un caricamento; `EntityDelta`
con i record il cui hash (XxHash64 del record serializzato) è cambiato rispetto all'ultimo
invio a quella sessione, più le rimozioni. Si calcola dopo i comandi riusciti e ogni giorno.
`TrackWorks` porta gli archi con i campioni a precisione piena (servono alle anteprime) in lotti
sotto 1 MB, perché il frame massimo è 4 MB.
4. **Terreno.** `MapChunk` 64×64 celle con altezze, tipi e larghezza dei fiumi compressi con
Brotli; si inviano i chunk del viewport (con un chunk di margine) una sola volta per sessione e
si rimandano quando cambia il loro hash (abitati che crescono, industrie che nascono o chiudono).
5. **Moto dei treni.** `TrainMotion` porta i passi del percorso dalla coda al tratto prenotato,
la distanza della testa lungo quei passi e la velocità; il client avanza la testa a velocità
costante (al massimo mezzo secondo di estrapolazione). Si invia ogni 100 ms per i treni in moto
nel viewport e una volta per quelli fermi; i moti si scartano per primi se la coda d'invio supera
256 KB (backpressure), mentre i messaggi affidabili chiudono la sessione oltre 64 MB.
6. **Una compagnia per tutte le sessioni.** In F3 ogni sessione guida la compagnia del giocatore:
più client sono più finestre sulla stessa partita. Le compagnie per giocatore arrivano con le IA.
7. **Copia del mondo nel client.** `ClientWorld` e `ProtocolClient` stanno in `ViaFerrea.Protocol`
(namespace `Client`): li usano il client Godot, i test di integrazione e `viaferrea-tools smoke`.
`ClientWorld` ricostruisce un `RailNetwork` con gli stessi id del server; `TrackPreview` (Core)
è lo stesso codice del comando `BuildTrack`, quindi l'anteprima coincide: il client manda il
costo atteso e il server rifiuta con `PreviewMismatch` se differisce.
8. **Server.** Il ciclo di gioco ha un thread suo; i messaggi delle sessioni entrano da una coda
concorrente drenata a inizio giro. Se il tick medio moltiplicato per la velocità supera il 90 %
del budget la velocità effettiva si dimezza e il resoconto segnala `slow`. All'avvio si riprende
l'ultimo salvataggio automatico, se c'è. Le metriche Prometheus hanno i nomi della guida
(`tick_ms`, `trains`, `packets`, `contracts`, `sessions`).
9. **Docker.** L'immagine .NET 10 è Ubuntu 24.04: l'utente si crea con `useradd` invece di
`adduser` (assente). Core e Protocol si compilano solo per net10.0 nell'immagine
(`-p:VfServerOnly=true`): la build non scarica il targeting pack net8.0 e non ha bisogno di rete
oltre alle immagini di base. `IsTrimmable` è stato tolto per lo stesso motivo (pacchetto ILLink).
10. **Client.** Scena principale minima e nodi costruiti in codice (niente editor nel flusso di
lavoro); tema dalla palette dell'immagine 05 con i font OFL in `assets/fonts/`; testi con
l'italiano come lingua sorgente e traduzioni in `assets/i18n/strings.csv` caricate all'avvio;
italiano predefinito. Scala dei simboli tarata sulle immagini 01 e 02: unità di mondo =
5,5·zoom^−0,56 (1 unità = 1 m da vicino). Rive curve: l'alfa della texture del terreno è il
campo dell'acqua interpolato tra i centri delle celle e uno shader lo taglia a 0,5. Fumo con
`GpuParticles2D`, alberi con `MultiMeshInstance2D`.
11. **Collaudi senza grafica.** `viaferrea-tools smoke` gioca contro un server vero (locale o in
Docker): trova un fiume, costruisce con l'anteprima, compra un treno e confronta la posizione
estrapolata con quella del moto successivo. Il client ha un pilota automatico
(`-- --autopilot cartella`, `scripts/client-autopilot.sh`) che fa lo stesso con la grafica vera
(Godot sotto Xvfb con Mesa) e salva schermate.
12. **Replay.** Con `--record` (o `VF_RECORD`) il server salva lo stato di partenza accanto al
registro e vi accoda ogni comando eseguito con tick, emittente e payload del protocollo;
`viaferrea-tools replay` li riapplica ai loro tick e confronta l'hash di stato.
## Conseguenze
- L'accettazione F3 è verificata in tre modi: test in processo (scarto tra client e server sotto
1 cm), `smoke` contro il container Docker e pilota automatico del client con schermate.
- I fiumi larghi una cella mostrano ancora gradini nella vista d'insieme: servirà un disegno
vettoriale dei corsi d'acqua.
- I nodi Godot creati in codice hanno costruttori con parametri: vanno bene in gioco, ma l'editor
non può ricrearli in caso di ricarica a caldo degli assembly.
Binary file not shown.

After

Width:  |  Height:  |  Size: 150 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 129 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 157 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 152 KiB

+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
# Collaudo grafico del client Godot: compila server e client, importa il progetto, avvia una
# partita locale con il pilota automatico (stazioni, ponte, treni) e salva le schermate.
# Senza display usa xvfb-run (rendering software Mesa).
# Uso: GODOT=/percorso/Godot_v4.7.2-stable_mono_linux.x86_64 scripts/client-autopilot.sh [cartella]
set -euo pipefail
cd "$(dirname "$0")/.."
godot="${GODOT:-godot}"
out="$(realpath -m "${1:-out/autopilot}")"
mkdir -p "$out"
dotnet build src/ViaFerrea.Server -c Release -v quiet -nologo
dotnet build client/ViaFerrea.Client/ViaFerrea.Client.csproj -c Debug -v quiet -nologo
"$godot" --headless --path client/ViaFerrea.Client --import >/dev/null 2>&1 || true
run=("$godot" --path client/ViaFerrea.Client --rendering-driver opengl3 --resolution 1600x900 --windowed -- --autopilot "$out")
if [ -z "${DISPLAY:-}" ] && command -v xvfb-run >/dev/null 2>&1; then
xvfb-run -a -s "-screen 0 1600x900x24" "${run[@]}" 2>&1 | grep -E "autopilot|ERROR" || true
else
"${run[@]}" 2>&1 | grep -E "autopilot|ERROR" || true
fi
ls "$out"/*.jpg >/dev/null 2>&1 && grep -q . <(ls "$out") && echo "client-autopilot: schermate in $out"
@@ -0,0 +1,49 @@
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Map;
using ViaFerrea.Core.Rail;
namespace ViaFerrea.Protocol.Client;
/// <summary>
/// Collaudi (viaferrea-tools smoke, pilota automatico del client): cerca sulla copia locale del
/// terreno un attraversamento di fiume rettilineo di 1,5–2,5 km con estremità e deposito su
/// terreno libero e un'anteprima valida con ponte.
/// </summary>
public static class BridgeSiteFinder
{
public readonly record struct Site(Vec2 A, Vec2 B, Vec2 Depot, Vec2 River);
public static Site? Find(ClientWorld w, ulong seed = 7, int attempts = 400, int maxDays = 120)
{
var t = w.Terrain ?? throw new InvalidOperationException("Terreno non ricevuto");
var rng = new Rng(seed);
bool Free(Vec2 p)
{
if (p.X < 2000 || p.Y < 2000 || p.X > t.WidthM - 2000 || p.Y > t.HeightM - 2000) return false;
var (x, y) = t.CellAt(p);
return (CellType)t.Types[y * t.Width + x] is CellType.Plain or CellType.Field or CellType.Forest or CellType.Hill;
}
var rivers = new List<int>();
for (int i = 0; i < t.RiverWidth.Length; i++)
{
if (t.RiverWidth[i] > 0) rivers.Add(i);
}
if (rivers.Count == 0) return null;
for (int attempt = 0; attempt < attempts; attempt++)
{
int cell = rivers[rng.NextInt(rivers.Count)];
var center = t.CellCenter(cell % t.Width, cell / t.Width);
double angle = rng.NextDouble(0, Math.PI);
var dir = new Vec2(Math.Cos(angle), Math.Sin(angle));
double half = rng.NextDouble(750, 1250);
var a = center - dir * half;
var b = center + dir * half;
var depot = a - dir * 600;
if (!Free(a) || !Free(b) || !Free(depot)) continue;
var plan = w.PreviewTrack(new BuildTrackCommand([a, b]));
if (plan.Valid && plan.LengthOf(WorkKind.Bridge) > 0 && plan.Days <= maxDays) return new Site(a, b, depot, center);
}
return null;
}
}
@@ -66,6 +66,9 @@ public sealed class ProtocolClient : IAsyncDisposable
}
}
/// <summary>Riserva un numero di sequenza (per registrare l'attesa dell'esito prima dell'invio).</summary>
public uint ReserveSeq() => Interlocked.Increment(ref _seq);
/// <summary>Invia un comando con un nuovo numero di sequenza e lo restituisce.</summary>
public async Task<uint> SendCommandAsync(GameCommand command, CancellationToken ct = default)
{
+60
View File
@@ -0,0 +1,60 @@
using System.Buffers.Binary;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
namespace ViaFerrea.Protocol;
/// <summary>
/// Registro dei comandi per il replay: intestazione «VFCL» + versione, poi record
/// <c>[u32 lunghezza][i64 tick][i32 emittente][u32 seq][u16 tipo][payload]</c> con il payload
/// del protocollo. Il server lo scrive con <c>--record</c>, <c>viaferrea-tools replay</c> lo rilegge.
/// </summary>
public static class CommandLogFile
{
private static ReadOnlySpan<byte> Magic => "VFCL"u8;
public const ushort Version = 1;
public static void WriteHeader(Stream s)
{
s.Write(Magic);
Span<byte> v = stackalloc byte[2];
BinaryPrimitives.WriteUInt16LittleEndian(v, Version);
s.Write(v);
}
public static void Append(Stream s, long tick, GameCommand command)
{
var w = new SpanWriter(128);
w.U32(0);
w.I64(tick);
w.I32(command.Issuer.Value);
w.U32(command.Seq);
w.U16((ushort)command.Type);
CommandCodec.Write(ref w, command);
w.PatchU32(0, (uint)(w.Length - 4));
s.Write(w.Written);
}
public static List<(long Tick, GameCommand Command)> ReadAll(byte[] file)
{
if (file.Length < 6 || !file.AsSpan(0, 4).SequenceEqual(Magic)) throw new ProtocolException("non è un registro di comandi di Via Ferrea");
ushort version = BinaryPrimitives.ReadUInt16LittleEndian(file.AsSpan(4));
if (version > Version) throw new ProtocolException($"registro di versione più recente ({version})");
var list = new List<(long, GameCommand)>();
int pos = 6;
while (pos + 4 <= file.Length)
{
int length = (int)BinaryPrimitives.ReadUInt32LittleEndian(file.AsSpan(pos));
if (length < 18 || pos + 4 + length > file.Length) throw new ProtocolException("registro troncato");
var r = new SpanReader(file.AsSpan(pos + 4, length));
long tick = r.I64();
var issuer = new CompanyId(r.I32());
uint seq = r.U32();
var type = (CommandType)r.U16();
var command = CommandCodec.Read(type, ref r) with { Issuer = issuer, Seq = seq };
list.Add((tick, command));
pos += 4 + length;
}
return list;
}
}
+17
View File
@@ -48,6 +48,7 @@ public sealed class GameHost : IDisposable
private bool _dailyDue;
private bool _monthlyDue;
private ulong _lastTerrainHash;
private FileStream? _record;
// istantanee per /metrics (lette da altri thread)
private volatile int _sessionCount;
@@ -67,6 +68,15 @@ public sealed class GameHost : IDisposable
_saves = new SaveStore(config.SavesDir, GameVersion);
_world = world ?? InitialWorld();
_lastTerrainHash = _world.Terrain.ComputeHash();
if (config.RecordPath is { Length: > 0 } path)
{
// registro dei comandi: si apre con un salvataggio di partenza accanto
_record = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read);
Protocol.CommandLogFile.WriteHeader(_record);
Core.Persistence.SaveFile.SaveToFile(_world, path + ".start.vfsave", GameVersion);
_world.CommandLog = [];
_log.LogInformation("Registro dei comandi in {Path}", path);
}
}
public SaveStore Saves => _saves;
@@ -109,6 +119,7 @@ public sealed class GameHost : IDisposable
{
_stop = true;
_thread?.Join(5000);
_record?.Dispose();
}
/// <summary>Esegue un'azione sul thread del ciclo di gioco.</summary>
@@ -337,6 +348,12 @@ public sealed class GameHost : IDisposable
Interlocked.Exchange(ref _tickMsBits, BitConverter.DoubleToInt64Bits(_tickMsEma));
Interlocked.Increment(ref _ticks);
if (_record is not null && w.CommandLog is { Count: > 0 } log)
{
foreach (var (tick, command) in log) Protocol.CommandLogFile.Append(_record, tick, command);
log.Clear();
_record.Flush();
}
foreach (var r in w.DrainResults())
{
if (r.Ok) _publishDirty = true;
+3
View File
@@ -20,6 +20,8 @@ public sealed class ServerConfig
/// <summary>Processo locale figlio del client: porta casuale su 127.0.0.1, stampa «LISTENING porta».</summary>
public bool Local { get; init; }
public bool HealthCheck { get; init; }
/// <summary>File in cui registrare i comandi eseguiti (per <c>viaferrea-tools replay</c>).</summary>
public string? RecordPath { get; init; }
/// <summary>Numero massimo di sessioni contemporanee.</summary>
public int MaxSessions { get; init; } = 16;
@@ -43,6 +45,7 @@ public sealed class ServerConfig
{
Local = local,
HealthCheck = args.Contains("--healthcheck"),
RecordPath = Arg("--record") ?? Env("VF_RECORD"),
Port = int.TryParse(Arg("--port") ?? Env("VF_PORT"), out int port) ? port : 7400,
Token = Arg("--token") ?? Env("VF_TOKEN") ?? "",
DataDir = dataDir,
@@ -0,0 +1,51 @@
using System.Diagnostics;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Persistence;
using ViaFerrea.Protocol;
namespace ViaFerrea.Tools.Commands;
/// <summary>
/// replay: carica un salvataggio, riapplica i comandi registrati dal server (<c>--record</c>) ai
/// loro tick e stampa l'hash di stato finale; con <c>--expect</c> lo confronta (determinismo).
/// </summary>
public sealed class ReplayCommand : IToolCommand
{
public string Name => "replay";
public string Usage => "replay --save <file.vfsave> --commands <file.vfcmd> [--until <tick>] [--expect <hash esadecimale>]";
public int Run(CommandLine args)
{
string savePath = args.Required("save");
string commandsPath = args.Required("commands");
long until = args.Int("until", -1);
string? expect = args.String("expect");
args.EnsureAllUsed();
var data = GameData.LoadDefault();
var world = SaveFile.LoadFromFile(data, savePath);
var commands = CommandLogFile.ReadAll(File.ReadAllBytes(commandsPath));
long start = world.Clock.Tick;
long last = commands.Count > 0 ? commands[^1].Tick : start;
long end = until >= 0 ? until : last + 1;
var clock = Stopwatch.StartNew();
int next = 0;
while (next < commands.Count && commands[next].Tick < start) next++;
int skipped = next;
while (world.Clock.Tick < end)
{
while (next < commands.Count && commands[next].Tick == world.Clock.Tick) world.Enqueue(commands[next++].Command);
world.Tick();
world.DrainResults();
world.Events.Drain();
}
ulong hash = StateHasher.Compute(world);
Console.WriteLine($"replay: {next - skipped} comandi su {commands.Count} (saltati {skipped} precedenti al salvataggio), tick {start} → {world.Clock.Tick} in {clock.ElapsedMilliseconds} ms");
Console.WriteLine($" data {world.Clock.Date}, hash di stato {hash:x16}");
if (expect is null) return 0;
bool ok = string.Equals(expect.Trim(), hash.ToString("x16"), StringComparison.OrdinalIgnoreCase);
Console.WriteLine(ok ? " hash atteso: coincide" : $" hash atteso {expect}: DIVERSO");
return ok ? 0 : 1;
}
}
+2 -39
View File
@@ -93,9 +93,9 @@ public sealed class SmokeCommand : IToolCommand
break;
}
await s.Until(() => w.Companies.TryGetValue(summary.CompanyId, out var c) && c.Cash.Cents > 0, ct);
var site = FindBridgeSite(w);
var site = BridgeSiteFinder.Find(w);
if (site is null) return Fail("nessun attraversamento di fiume adatto trovato");
var (a, b, depotAt) = site.Value;
var (a, b, depotAt, _) = site.Value;
Console.WriteLine($" sito: da ({a.X / 1000:F2}, {a.Y / 1000:F2}) a ({b.X / 1000:F2}, {b.Y / 1000:F2}) km");
var sa = await s.Do(new BuildStationCommand(a, 2, "Smoke Ovest"), ct);
@@ -173,41 +173,4 @@ public sealed class SmokeCommand : IToolCommand
Console.Error.WriteLine($"smoke: FALLITO — {why}");
return 1;
}
/// <summary>
/// Cerca un attraversamento di fiume rettilineo di 1,5–2,5 km con estremità e deposito su
/// terreno libero e un'anteprima valida con ponte.
/// </summary>
private static (Vec2 A, Vec2 B, Vec2 Depot)? FindBridgeSite(ClientWorld w)
{
var t = w.Terrain!;
var rng = new Rng(7);
bool Free(Vec2 p)
{
if (p.X < 2000 || p.Y < 2000 || p.X > t.WidthM - 2000 || p.Y > t.HeightM - 2000) return false;
var (x, y) = t.CellAt(p);
return (CellType)t.Types[y * t.Width + x] is CellType.Plain or CellType.Field or CellType.Forest or CellType.Hill;
}
var rivers = new List<int>();
for (int i = 0; i < t.RiverWidth.Length; i++)
{
if (t.RiverWidth[i] > 0) rivers.Add(i);
}
if (rivers.Count == 0) return null;
for (int attempt = 0; attempt < 400; attempt++)
{
int cell = rivers[rng.NextInt(rivers.Count)];
var center = t.CellCenter(cell % t.Width, cell / t.Width);
double angle = rng.NextDouble(0, Math.PI);
var dir = new Vec2(Math.Cos(angle), Math.Sin(angle));
double half = rng.NextDouble(750, 1250);
var a = center - dir * half;
var b = center + dir * half;
var depot = a - dir * 600;
if (!Free(a) || !Free(b) || !Free(depot)) continue;
var plan = w.PreviewTrack(new BuildTrackCommand([a, b]));
if (plan.Valid && plan.LengthOf(WorkKind.Bridge) > 0 && plan.Days <= 120) return (a, b, depot);
}
return null;
}
}
+1
View File
@@ -13,6 +13,7 @@ public static class ToolsProgram
new ProfileCommand(),
new BenchCommand(),
new SmokeCommand(),
new ReplayCommand(),
];
public static int Main(string[] args)
@@ -281,3 +281,36 @@ public static class ProtocolTests
Assert.Equal(1 + 1 + 2 + 10 + 1 + 6, w.Length);
}
}
public static class CommandLogTests
{
[Test(Description = "Registro dei comandi: salvataggio di partenza + comandi riapplicati ai loro tick = stesso hash")]
public static void RecordedCommandsReplayToTheSameState()
{
var f = ViaFerrea.Tests.Rail.RailFixture.Valdoria();
var w = f.W;
byte[] start = ViaFerrea.Core.Persistence.SaveFile.Save(w, "test");
w.CommandLog = [];
var (mine, mill, depot) = f.BuildFreightNetwork(waitForConstruction: false);
f.Ok(new TakeLoanCommand(Money.FromLire(10_000)));
w.RunDays(3);
var file = new MemoryStream();
CommandLogFile.WriteHeader(file);
foreach (var (tick, command) in w.CommandLog) CommandLogFile.Append(file, tick, command);
long endTick = w.Clock.Tick;
ulong expected = ViaFerrea.Core.Persistence.StateHasher.Compute(w);
var commands = CommandLogFile.ReadAll(file.ToArray());
Assert.Equal(w.CommandLog.Count, commands.Count);
var replay = ViaFerrea.Core.Persistence.SaveFile.Load(TestData.Data, start);
int next = 0;
while (replay.Clock.Tick < endTick)
{
while (next < commands.Count && commands[next].Tick == replay.Clock.Tick) replay.Enqueue(commands[next++].Command);
replay.Tick();
}
Assert.Equal(commands.Count, next);
Assert.Equal(expected, ViaFerrea.Core.Persistence.StateHasher.Compute(replay));
Assert.True(mine >= 0 && mill >= 0 && depot >= 0);
}
}