diff --git a/.gitignore b/.gitignore index 80380a7..6b4f75a 100644 --- a/.gitignore +++ b/.gitignore @@ -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 diff --git a/README.md b/README.md index e3032c7..0284725 100644 --- a/README.md +++ b/README.md @@ -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 +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`). diff --git a/client/ViaFerrea.Client/ViaFerrea.Client.csproj b/client/ViaFerrea.Client/ViaFerrea.Client.csproj new file mode 100644 index 0000000..fd5c0b0 --- /dev/null +++ b/client/ViaFerrea.Client/ViaFerrea.Client.csproj @@ -0,0 +1,33 @@ + + + + + net8.0 + true + ViaFerrea.Client + enable + enable + latest + true + true + + + + + + + + + + + + + + + + + + diff --git a/client/ViaFerrea.Client/assets/fonts/BigShouldersDisplay-ExtraBold.ttf b/client/ViaFerrea.Client/assets/fonts/BigShouldersDisplay-ExtraBold.ttf new file mode 100644 index 0000000..7613d3f Binary files /dev/null and b/client/ViaFerrea.Client/assets/fonts/BigShouldersDisplay-ExtraBold.ttf differ diff --git a/client/ViaFerrea.Client/assets/fonts/BigShouldersDisplay-ExtraBold.ttf.import b/client/ViaFerrea.Client/assets/fonts/BigShouldersDisplay-ExtraBold.ttf.import new file mode 100644 index 0000000..79c581e --- /dev/null +++ b/client/ViaFerrea.Client/assets/fonts/BigShouldersDisplay-ExtraBold.ttf.import @@ -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={} diff --git a/client/ViaFerrea.Client/assets/fonts/IBMPlexSans-Regular.ttf b/client/ViaFerrea.Client/assets/fonts/IBMPlexSans-Regular.ttf new file mode 100644 index 0000000..af2edfe Binary files /dev/null and b/client/ViaFerrea.Client/assets/fonts/IBMPlexSans-Regular.ttf differ diff --git a/client/ViaFerrea.Client/assets/fonts/IBMPlexSans-Regular.ttf.import b/client/ViaFerrea.Client/assets/fonts/IBMPlexSans-Regular.ttf.import new file mode 100644 index 0000000..fdc62d8 --- /dev/null +++ b/client/ViaFerrea.Client/assets/fonts/IBMPlexSans-Regular.ttf.import @@ -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={} diff --git a/client/ViaFerrea.Client/assets/fonts/IBMPlexSans-SemiBold.ttf b/client/ViaFerrea.Client/assets/fonts/IBMPlexSans-SemiBold.ttf new file mode 100644 index 0000000..bd1c0c4 Binary files /dev/null and b/client/ViaFerrea.Client/assets/fonts/IBMPlexSans-SemiBold.ttf differ diff --git a/client/ViaFerrea.Client/assets/fonts/IBMPlexSans-SemiBold.ttf.import b/client/ViaFerrea.Client/assets/fonts/IBMPlexSans-SemiBold.ttf.import new file mode 100644 index 0000000..8de09b7 --- /dev/null +++ b/client/ViaFerrea.Client/assets/fonts/IBMPlexSans-SemiBold.ttf.import @@ -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={} diff --git a/client/ViaFerrea.Client/assets/fonts/OFL.txt b/client/ViaFerrea.Client/assets/fonts/OFL.txt new file mode 100644 index 0000000..1d3b800 --- /dev/null +++ b/client/ViaFerrea.Client/assets/fonts/OFL.txt @@ -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. diff --git a/client/ViaFerrea.Client/assets/i18n/strings.csv b/client/ViaFerrea.Client/assets/i18n/strings.csv new file mode 100644 index 0000000..1932192 --- /dev/null +++ b/client/ViaFerrea.Client/assets/i18n/strings.csv @@ -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 diff --git a/client/ViaFerrea.Client/assets/i18n/strings.csv.import b/client/ViaFerrea.Client/assets/i18n/strings.csv.import new file mode 100644 index 0000000..97a71b6 --- /dev/null +++ b/client/ViaFerrea.Client/assets/i18n/strings.csv.import @@ -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 diff --git a/client/ViaFerrea.Client/assets/shaders/terrain.gdshader b/client/ViaFerrea.Client/assets/shaders/terrain.gdshader new file mode 100644 index 0000000..00786a6 --- /dev/null +++ b/client/ViaFerrea.Client/assets/shaders/terrain.gdshader @@ -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); +} diff --git a/client/ViaFerrea.Client/assets/shaders/terrain.gdshader.uid b/client/ViaFerrea.Client/assets/shaders/terrain.gdshader.uid new file mode 100644 index 0000000..c3d5d6a --- /dev/null +++ b/client/ViaFerrea.Client/assets/shaders/terrain.gdshader.uid @@ -0,0 +1 @@ +uid://d18pluemvpfne diff --git a/client/ViaFerrea.Client/assets/theme/icon.svg b/client/ViaFerrea.Client/assets/theme/icon.svg new file mode 100644 index 0000000..3a3c59a --- /dev/null +++ b/client/ViaFerrea.Client/assets/theme/icon.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/client/ViaFerrea.Client/assets/theme/icon.svg.import b/client/ViaFerrea.Client/assets/theme/icon.svg.import new file mode 100644 index 0000000..0c2c828 --- /dev/null +++ b/client/ViaFerrea.Client/assets/theme/icon.svg.import @@ -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 diff --git a/client/ViaFerrea.Client/export_presets.cfg b/client/ViaFerrea.Client/export_presets.cfg new file mode 100644 index 0000000..77b67ee --- /dev/null +++ b/client/ViaFerrea.Client/export_presets.cfg @@ -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 diff --git a/client/ViaFerrea.Client/project.godot b/client/ViaFerrea.Client/project.godot new file mode 100644 index 0000000..b349c49 --- /dev/null +++ b/client/ViaFerrea.Client/project.godot @@ -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 diff --git a/client/ViaFerrea.Client/scenes/Main.tscn b/client/ViaFerrea.Client/scenes/Main.tscn new file mode 100644 index 0000000..6ec40f9 --- /dev/null +++ b/client/ViaFerrea.Client/scenes/Main.tscn @@ -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") diff --git a/client/ViaFerrea.Client/scripts/App/AutoPilot.cs b/client/ViaFerrea.Client/scripts/App/AutoPilot.cs new file mode 100644 index 0000000..254b131 --- /dev/null +++ b/client/ViaFerrea.Client/scripts/App/AutoPilot.cs @@ -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; + +/// +/// Pilota automatico per il collaudo del client (-- --autopilot cartella): 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. +/// +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 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 Do(GameCommand command) + { + var tcs = new TaskCompletionSource(); + Session.Command(command, r => tcs.TrySetResult(r)); + return tcs.Task; + } + + private async Task 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); + } +} diff --git a/client/ViaFerrea.Client/scripts/App/AutoPilot.cs.uid b/client/ViaFerrea.Client/scripts/App/AutoPilot.cs.uid new file mode 100644 index 0000000..de43d2b --- /dev/null +++ b/client/ViaFerrea.Client/scripts/App/AutoPilot.cs.uid @@ -0,0 +1 @@ +uid://bdw1fy2qphri5 diff --git a/client/ViaFerrea.Client/scripts/App/GodotDataSource.cs b/client/ViaFerrea.Client/scripts/App/GodotDataSource.cs new file mode 100644 index 0000000..6e27de0 --- /dev/null +++ b/client/ViaFerrea.Client/scripts/App/GodotDataSource.cs @@ -0,0 +1,26 @@ +using Godot; +using ViaFerrea.Core.Data; + +namespace ViaFerrea.Client.App; + +/// File dati del gioco dentro il progetto Godot (res://data, copiati dalla build del client). +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(); + } + + /// Dati del gioco: res://data se presenti, altrimenti la cartella data del repository. + public static GameData LoadGameData() + { + var source = new GodotDataSource(); + return source.Exists("goods.json") ? GameData.Load(source) : GameData.LoadDefault(); + } +} diff --git a/client/ViaFerrea.Client/scripts/App/GodotDataSource.cs.uid b/client/ViaFerrea.Client/scripts/App/GodotDataSource.cs.uid new file mode 100644 index 0000000..06f2613 --- /dev/null +++ b/client/ViaFerrea.Client/scripts/App/GodotDataSource.cs.uid @@ -0,0 +1 @@ +uid://bn1h4nbl2f1rc diff --git a/client/ViaFerrea.Client/scripts/App/Localization.cs b/client/ViaFerrea.Client/scripts/App/Localization.cs new file mode 100644 index 0000000..5908b47 --- /dev/null +++ b/client/ViaFerrea.Client/scripts/App/Localization.cs @@ -0,0 +1,43 @@ +using Godot; + +namespace ViaFerrea.Client.App; + +/// +/// Testi dell'interfaccia: la lingua sorgente è l'italiano (le chiavi sono i testi italiani), +/// le traduzioni stanno in assets/i18n/strings.csv (colonne keys, it, en) e si caricano +/// all'avvio senza passare dall'importazione dell'editor. +/// +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(); + 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); + } + + /// Traduce un testo dell'interfaccia (chiave = testo italiano). + public static string T(string italian) => TranslationServer.Translate(italian); +} diff --git a/client/ViaFerrea.Client/scripts/App/Localization.cs.uid b/client/ViaFerrea.Client/scripts/App/Localization.cs.uid new file mode 100644 index 0000000..c63bb93 --- /dev/null +++ b/client/ViaFerrea.Client/scripts/App/Localization.cs.uid @@ -0,0 +1 @@ +uid://bxob5yr4t8lu8 diff --git a/client/ViaFerrea.Client/scripts/App/Palette.cs b/client/ViaFerrea.Client/scripts/App/Palette.cs new file mode 100644 index 0000000..08aa03a --- /dev/null +++ b/client/ViaFerrea.Client/scripts/App/Palette.cs @@ -0,0 +1,43 @@ +using Godot; + +namespace ViaFerrea.Client.App; + +/// Palette dell'immagine di riferimento 05: interfaccia blu-ardesia con accento ambra, mappa cartografica chiara. +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); +} diff --git a/client/ViaFerrea.Client/scripts/App/Palette.cs.uid b/client/ViaFerrea.Client/scripts/App/Palette.cs.uid new file mode 100644 index 0000000..371f544 --- /dev/null +++ b/client/ViaFerrea.Client/scripts/App/Palette.cs.uid @@ -0,0 +1 @@ +uid://blsg133y5mi21 diff --git a/client/ViaFerrea.Client/scripts/App/UiTheme.cs b/client/ViaFerrea.Client/scripts/App/UiTheme.cs new file mode 100644 index 0000000..bb6a520 --- /dev/null +++ b/client/ViaFerrea.Client/scripts/App/UiTheme.cs @@ -0,0 +1,144 @@ +using Godot; + +namespace ViaFerrea.Client.App; + +/// +/// 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. +/// +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; + } + + /// Riquadro piatto con bordo di 1 px. + 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; + } + + /// Carica un font importato dall'editor oppure, in mancanza, direttamente dal file. + private static Font LoadFont(string path) + { + if (ResourceLoader.Exists(path)) + { + var imported = ResourceLoader.Load(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; + } + + /// Etichetta con il font dei titoli. + 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; + } + + /// Pulsante d'azione primaria (ambra). + 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; + } + + /// Distintivo ambra (livello della compagnia, linea). + 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; + } + + /// Etichetta di linea: ambra su fondo ambra scuro, su una riga (immagine 01). + 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; + } + + /// Riquadro d'avviso ambra scuro (colli di bottiglia e opportunità). + 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; + } +} diff --git a/client/ViaFerrea.Client/scripts/App/UiTheme.cs.uid b/client/ViaFerrea.Client/scripts/App/UiTheme.cs.uid new file mode 100644 index 0000000..92f17a8 --- /dev/null +++ b/client/ViaFerrea.Client/scripts/App/UiTheme.cs.uid @@ -0,0 +1 @@ +uid://fvsnf1rxxhbh diff --git a/client/ViaFerrea.Client/scripts/Hud/Minimap.cs b/client/ViaFerrea.Client/scripts/Hud/Minimap.cs new file mode 100644 index 0000000..7498b55 --- /dev/null +++ b/client/ViaFerrea.Client/scripts/Hud/Minimap.cs @@ -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; + +/// Minimappa: terreno ridotto, linee, città e rettangolo della vista; un clic centra la mappa. +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(); + } + } +} diff --git a/client/ViaFerrea.Client/scripts/Hud/Minimap.cs.uid b/client/ViaFerrea.Client/scripts/Hud/Minimap.cs.uid new file mode 100644 index 0000000..1d6cf70 --- /dev/null +++ b/client/ViaFerrea.Client/scripts/Hud/Minimap.cs.uid @@ -0,0 +1 @@ +uid://ci04fqk4we7bk diff --git a/client/ViaFerrea.Client/scripts/Hud/Ticker.cs b/client/ViaFerrea.Client/scripts/Hud/Ticker.cs new file mode 100644 index 0000000..4fb6eb6 --- /dev/null +++ b/client/ViaFerrea.Client/scripts/Hud/Ticker.cs @@ -0,0 +1,42 @@ +using Godot; +using ViaFerrea.Client.App; +using ViaFerrea.Protocol.Messages; +using static ViaFerrea.Client.App.Localization; + +namespace ViaFerrea.Client.Hud; + +/// Notiziario in basso (immagine 01): «Notizie» e gli ultimi eventi che scorrono. +public partial class Ticker : PanelContainer +{ + private readonly List _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); + } +} diff --git a/client/ViaFerrea.Client/scripts/Hud/Ticker.cs.uid b/client/ViaFerrea.Client/scripts/Hud/Ticker.cs.uid new file mode 100644 index 0000000..a5682f2 --- /dev/null +++ b/client/ViaFerrea.Client/scripts/Hud/Ticker.cs.uid @@ -0,0 +1 @@ +uid://c57cbfp1dm0qo diff --git a/client/ViaFerrea.Client/scripts/Hud/Toolbar.cs b/client/ViaFerrea.Client/scripts/Hud/Toolbar.cs new file mode 100644 index 0000000..44b0889 --- /dev/null +++ b/client/ViaFerrea.Client/scripts/Hud/Toolbar.cs @@ -0,0 +1,139 @@ +using Godot; +using ViaFerrea.Client.App; +using static ViaFerrea.Client.App.Localization; + +namespace ViaFerrea.Client.Hud; + +/// Strumenti e pannelli della barra sinistra (immagine 01). +public enum Tool { None, Track, Station, Signal, Depot, Trains, Lines, Market, Finance, Demolish } + +/// Barra degli strumenti a sinistra: icone disegnate in codice con l'etichetta sotto. +public partial class Toolbar : PanelContainer +{ + private readonly Dictionary _buttons = []; + + public event Action? 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); + } + + /// Pulsante con icona vettoriale. + 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; + } + } + } +} diff --git a/client/ViaFerrea.Client/scripts/Hud/Toolbar.cs.uid b/client/ViaFerrea.Client/scripts/Hud/Toolbar.cs.uid new file mode 100644 index 0000000..c89b276 --- /dev/null +++ b/client/ViaFerrea.Client/scripts/Hud/Toolbar.cs.uid @@ -0,0 +1 @@ +uid://bngg3p5mnbnru diff --git a/client/ViaFerrea.Client/scripts/Hud/TopBar.cs b/client/ViaFerrea.Client/scripts/Hud/TopBar.cs new file mode 100644 index 0000000..a40a1d6 --- /dev/null +++ b/client/ViaFerrea.Client/scripts/Hud/TopBar.cs @@ -0,0 +1,111 @@ +using Godot; +using ViaFerrea.Client.App; +using ViaFerrea.Client.Net; +using static ViaFerrea.Client.App.Localization; + +namespace ViaFerrea.Client.Hud; + +/// Barra superiore (immagine 01): compagnia e livello, data, velocità, cassa, patrimonio, rating, stato del server. +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