Via Ferrea: fondamenta, economia, rete ferroviaria, server e client, manutenzione e pendolarismo (F0–F4) #1

Merged
Alby96 merged 11 commits from claude/funny-pasteur-jvtug9 into main 2026-10-02 09:29:19 +02:00
304 changed files with 34964 additions and 2 deletions

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
# Contesto della build Docker: solo sorgenti e dati del server.
**/bin/
**/obj/
.git/
.godot/
client/
docker/data/
reference/
out/
artifacts/
saves/
*.vfsave
+18
View File
@@ -427,3 +427,21 @@ FodyWeavers.xsd
*.msix
*.msm
*.msp
# --- Via Ferrea ---
# Godot
.godot/
client/ViaFerrea.Client/.godot/
client/ViaFerrea.Client/export/
# Output degli strumenti e dei test
/out/
/artifacts/
*.kpi.csv
# Volume locale del server in Docker
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
+38
View File
@@ -0,0 +1,38 @@
# CLAUDE.md — Via Ferrea
Gestionale ferroviario dall'alto: motore headless in C# (.NET 10), server ASP.NET Core in Docker, client Godot 4 .NET.
La specifica vincolante è `docs/GUIDA.md`; lo stato dei lavori è in `docs/STATE.md`. Leggili entrambi a inizio sessione.
## Comandi
```
scripts/build.sh # check-nuget + build Release della soluzione
scripts/test.sh [filtri] # build + validate-data + tutti i test (--skip-slow, --serial)
dotnet run --project tests/ViaFerrea.Tests -- --list
dotnet run --project src/ViaFerrea.Tools -- <comando> # validate-data, genmap, profile, simulate, bench, replay
```
## Regole non negoziabili
- Zero `PackageReference` in tutta la soluzione (`scripts/check-nuget.sh`). Unica eccezione: l'SDK Godot nel client.
- Identificatori in inglese; commenti, documentazione e testi UI in italiano.
- Nessun numero magico nella simulazione: i parametri stanno in `data/*.json` (con schema in `data/schema/`).
- Simulazione deterministica: solo `Rng` (xoshiro256**) con `Fork`, niente `Random`/`Guid.NewGuid`/`DateTime.Now`/`Environment.TickCount`, niente iterazione di `Dictionary`/`HashSet` per produrre effetti, funzioni trascendenti solo da `DMath`, denaro in `Money` (centesimi).
- Core e Protocol compilano anche per net8.0 (client Godot): niente API successive a .NET 8 lì.
- Il client non contiene logica di gioco; il server è autorevole.
- Ogni decisione non coperta dalla guida → `docs/adr/NNNN-titolo.md`.
## Flusso di lavoro
- Una fase alla volta (sezione 16 della guida). Fine fase: build verde, test verdi, `docs/STATE.md` aggiornato, commit `F<n>: <cosa>`.
- Nuovi test nel harness interno (`[Test]`, `Assert`), un file per area in `tests/ViaFerrea.Tests/<Area>/`.
- I test lunghi si marcano `[Test(Slow = true)]`.
## Mappa del codice
- `src/ViaFerrea.Core` — Common, Time, Data, Map, Economy, Rail, Commands, Simulation, Persistence (vedi `docs/ARCHITECTURE.md`).
- `src/ViaFerrea.Protocol` — frame e messaggi (vedi `docs/PROTOCOL.md`).
- `src/ViaFerrea.Server` — GameLoop, sessioni WebSocket, API HTTP.
- `src/ViaFerrea.Tools` — `viaferrea-tools`.
- `client/ViaFerrea.Client` — progetto Godot.
- `reference/` — immagini di riferimento visivo vincolanti.
+20
View File
@@ -0,0 +1,20 @@
<Project>
<!-- Impostazioni comuni a tutti i progetti .NET di Via Ferrea (il client Godot ha il proprio). -->
<PropertyGroup>
<!-- Unica fonte della versione: letta anche da scripts/publish-image.sh e dal protocollo. -->
<Version>0.1.0</Version>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<InvariantGlobalization>true</InvariantGlobalization>
<Deterministic>true</Deterministic>
<Authors>Via Ferrea</Authors>
<Product>Via Ferrea</Product>
<Copyright>Via Ferrea</Copyright>
<SatelliteResourceLanguages>it;en</SatelliteResourceLanguages>
<GenerateDocumentationFile>false</GenerateDocumentationFile>
<!-- Nessun pacchetto NuGet: niente audit verso feed esterni. -->
<NuGetAudit>false</NuGetAudit>
</PropertyGroup>
</Project>
+69 -2
View File
@@ -1,2 +1,69 @@
# TrainGame
Game train
# Via Ferrea
Gestionale ferroviario visto dall'alto, ambientato dal 1850 in una regione immaginaria: binari con pendenze, trincee, ponti e gallerie; economia con prezzi globali e locali; pendolarismo di lavoratori e personale; manutenzione per componente di treni e industrie; concorrenti IA, borsa e scalate; un mondo che non finisce mai.
Il motore di gioco è headless e deterministico (C# su .NET 10) e gira sia dentro il client desktop (Godot 4 .NET) sia come server Linux in Docker.
## Requisiti
- .NET SDK 10.x (`dotnet --version`)
- Godot 4 .NET, versione stabile più recente, come `godot` nel PATH (solo per il client)
- Docker (solo per l'immagine del server)
## Compilare e provare
```
scripts/build.sh # controllo "zero NuGet" + build Release
scripts/test.sh # validazione dei dati + tutti i test
```
Su Windows: `./scripts/build.ps1 -Test`.
## Struttura
| Cartella | Contenuto |
|---|---|
| `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, smoke, replay |
| `tests/ViaFerrea.Tests` | harness di test interno e scenari |
| `client/ViaFerrea.Client` | client Godot |
| `data/` | parametri di gioco in JSON con schema |
| `docker/` | Dockerfile, compose, template Unraid |
| `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 # 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`).
Il server parla WebSocket in chiaro: per l'uso fuori da una rete privata mettilo dietro un reverse proxy con TLS (per esempio Caddy, Traefik o Nginx Proxy Manager su Unraid) ed esponi solo `wss://`.
## Documentazione
- `docs/GUIDA.md` — specifica operativa vincolante
- `docs/GDD.md` — design del gioco
- `docs/ARCHITECTURE.md` — architettura del codice
- `docs/PROTOCOL.md` — protocollo di rete
- `docs/STATE.md` — stato dei lavori
- `docs/adr/` — decisioni architetturali
+101
View File
@@ -0,0 +1,101 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ViaFerrea.Core", "src\ViaFerrea.Core\ViaFerrea.Core.csproj", "{D50BCC13-4F79-4DB1-BD16-5E7576006DA9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ViaFerrea.Protocol", "src\ViaFerrea.Protocol\ViaFerrea.Protocol.csproj", "{7582B640-61C0-47F8-9A2E-B3607B01FD35}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ViaFerrea.Server", "src\ViaFerrea.Server\ViaFerrea.Server.csproj", "{D9E37057-86E8-4DDE-B3DA-EDC44F4EAE30}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ViaFerrea.Tools", "src\ViaFerrea.Tools\ViaFerrea.Tools.csproj", "{509F4E00-74B7-4FFB-84E0-3CB1F671A70E}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ViaFerrea.Tests", "tests\ViaFerrea.Tests\ViaFerrea.Tests.csproj", "{BE4E0868-2350-4C87-968E-E424D4DEB1C5}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D50BCC13-4F79-4DB1-BD16-5E7576006DA9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D50BCC13-4F79-4DB1-BD16-5E7576006DA9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D50BCC13-4F79-4DB1-BD16-5E7576006DA9}.Debug|x64.ActiveCfg = Debug|Any CPU
{D50BCC13-4F79-4DB1-BD16-5E7576006DA9}.Debug|x64.Build.0 = Debug|Any CPU
{D50BCC13-4F79-4DB1-BD16-5E7576006DA9}.Debug|x86.ActiveCfg = Debug|Any CPU
{D50BCC13-4F79-4DB1-BD16-5E7576006DA9}.Debug|x86.Build.0 = Debug|Any CPU
{D50BCC13-4F79-4DB1-BD16-5E7576006DA9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D50BCC13-4F79-4DB1-BD16-5E7576006DA9}.Release|Any CPU.Build.0 = Release|Any CPU
{D50BCC13-4F79-4DB1-BD16-5E7576006DA9}.Release|x64.ActiveCfg = Release|Any CPU
{D50BCC13-4F79-4DB1-BD16-5E7576006DA9}.Release|x64.Build.0 = Release|Any CPU
{D50BCC13-4F79-4DB1-BD16-5E7576006DA9}.Release|x86.ActiveCfg = Release|Any CPU
{D50BCC13-4F79-4DB1-BD16-5E7576006DA9}.Release|x86.Build.0 = Release|Any CPU
{7582B640-61C0-47F8-9A2E-B3607B01FD35}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7582B640-61C0-47F8-9A2E-B3607B01FD35}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7582B640-61C0-47F8-9A2E-B3607B01FD35}.Debug|x64.ActiveCfg = Debug|Any CPU
{7582B640-61C0-47F8-9A2E-B3607B01FD35}.Debug|x64.Build.0 = Debug|Any CPU
{7582B640-61C0-47F8-9A2E-B3607B01FD35}.Debug|x86.ActiveCfg = Debug|Any CPU
{7582B640-61C0-47F8-9A2E-B3607B01FD35}.Debug|x86.Build.0 = Debug|Any CPU
{7582B640-61C0-47F8-9A2E-B3607B01FD35}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7582B640-61C0-47F8-9A2E-B3607B01FD35}.Release|Any CPU.Build.0 = Release|Any CPU
{7582B640-61C0-47F8-9A2E-B3607B01FD35}.Release|x64.ActiveCfg = Release|Any CPU
{7582B640-61C0-47F8-9A2E-B3607B01FD35}.Release|x64.Build.0 = Release|Any CPU
{7582B640-61C0-47F8-9A2E-B3607B01FD35}.Release|x86.ActiveCfg = Release|Any CPU
{7582B640-61C0-47F8-9A2E-B3607B01FD35}.Release|x86.Build.0 = Release|Any CPU
{D9E37057-86E8-4DDE-B3DA-EDC44F4EAE30}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D9E37057-86E8-4DDE-B3DA-EDC44F4EAE30}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D9E37057-86E8-4DDE-B3DA-EDC44F4EAE30}.Debug|x64.ActiveCfg = Debug|Any CPU
{D9E37057-86E8-4DDE-B3DA-EDC44F4EAE30}.Debug|x64.Build.0 = Debug|Any CPU
{D9E37057-86E8-4DDE-B3DA-EDC44F4EAE30}.Debug|x86.ActiveCfg = Debug|Any CPU
{D9E37057-86E8-4DDE-B3DA-EDC44F4EAE30}.Debug|x86.Build.0 = Debug|Any CPU
{D9E37057-86E8-4DDE-B3DA-EDC44F4EAE30}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D9E37057-86E8-4DDE-B3DA-EDC44F4EAE30}.Release|Any CPU.Build.0 = Release|Any CPU
{D9E37057-86E8-4DDE-B3DA-EDC44F4EAE30}.Release|x64.ActiveCfg = Release|Any CPU
{D9E37057-86E8-4DDE-B3DA-EDC44F4EAE30}.Release|x64.Build.0 = Release|Any CPU
{D9E37057-86E8-4DDE-B3DA-EDC44F4EAE30}.Release|x86.ActiveCfg = Release|Any CPU
{D9E37057-86E8-4DDE-B3DA-EDC44F4EAE30}.Release|x86.Build.0 = Release|Any CPU
{509F4E00-74B7-4FFB-84E0-3CB1F671A70E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{509F4E00-74B7-4FFB-84E0-3CB1F671A70E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{509F4E00-74B7-4FFB-84E0-3CB1F671A70E}.Debug|x64.ActiveCfg = Debug|Any CPU
{509F4E00-74B7-4FFB-84E0-3CB1F671A70E}.Debug|x64.Build.0 = Debug|Any CPU
{509F4E00-74B7-4FFB-84E0-3CB1F671A70E}.Debug|x86.ActiveCfg = Debug|Any CPU
{509F4E00-74B7-4FFB-84E0-3CB1F671A70E}.Debug|x86.Build.0 = Debug|Any CPU
{509F4E00-74B7-4FFB-84E0-3CB1F671A70E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{509F4E00-74B7-4FFB-84E0-3CB1F671A70E}.Release|Any CPU.Build.0 = Release|Any CPU
{509F4E00-74B7-4FFB-84E0-3CB1F671A70E}.Release|x64.ActiveCfg = Release|Any CPU
{509F4E00-74B7-4FFB-84E0-3CB1F671A70E}.Release|x64.Build.0 = Release|Any CPU
{509F4E00-74B7-4FFB-84E0-3CB1F671A70E}.Release|x86.ActiveCfg = Release|Any CPU
{509F4E00-74B7-4FFB-84E0-3CB1F671A70E}.Release|x86.Build.0 = Release|Any CPU
{BE4E0868-2350-4C87-968E-E424D4DEB1C5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BE4E0868-2350-4C87-968E-E424D4DEB1C5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BE4E0868-2350-4C87-968E-E424D4DEB1C5}.Debug|x64.ActiveCfg = Debug|Any CPU
{BE4E0868-2350-4C87-968E-E424D4DEB1C5}.Debug|x64.Build.0 = Debug|Any CPU
{BE4E0868-2350-4C87-968E-E424D4DEB1C5}.Debug|x86.ActiveCfg = Debug|Any CPU
{BE4E0868-2350-4C87-968E-E424D4DEB1C5}.Debug|x86.Build.0 = Debug|Any CPU
{BE4E0868-2350-4C87-968E-E424D4DEB1C5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BE4E0868-2350-4C87-968E-E424D4DEB1C5}.Release|Any CPU.Build.0 = Release|Any CPU
{BE4E0868-2350-4C87-968E-E424D4DEB1C5}.Release|x64.ActiveCfg = Release|Any CPU
{BE4E0868-2350-4C87-968E-E424D4DEB1C5}.Release|x64.Build.0 = Release|Any CPU
{BE4E0868-2350-4C87-968E-E424D4DEB1C5}.Release|x86.ActiveCfg = Release|Any CPU
{BE4E0868-2350-4C87-968E-E424D4DEB1C5}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{D50BCC13-4F79-4DB1-BD16-5E7576006DA9} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{7582B640-61C0-47F8-9A2E-B3607B01FD35} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{D9E37057-86E8-4DDE-B3DA-EDC44F4EAE30} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{509F4E00-74B7-4FFB-84E0-3CB1F671A70E} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{BE4E0868-2350-4C87-968E-E424D4DEB1C5} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
EndGlobalSection
EndGlobal
@@ -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,216 @@
keys,it,en
Abitanti,,Population
Accetta,,Accept
Aggiorna,,Refresh
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)
Attiva,,Active
Avvio del server locale…,,Starting the local server…
Binari,,Track
Binari di stazione,,Platforms
Blu,,Blue
Cantiere,,Construction
Carico,,Load
Cartella di manutenzione,,Maintenance record
Cartella in arrivo dal server…,,Record on its way from the server…
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
Come la linea o la flotta,,Same as line or fleet
Componi,,Compose
Compra veicoli,,Buy vehicles
Condizione,,Condition
Connessione persa,,Connection lost
Consuma,,Consumes
Convenzioni,,Agreements
Coperto dalla riserva,,Covered by reserve
Costi dell'anno,,Costs this year
Costo,,Cost
Costruisci,,Build
Crea linea,,Create line
Dati del gioco non trovati o non validi.,,Game data missing or invalid.
Demolisci,,Demolish
Depositi e officine,,Depots and workshops
Deposito,,Depot
Deragliamento,,Derailment
Disconnesso,,Disconnected
Doppio binario,,Double track
Dove lavorano gli abitanti,,Where residents work
Efficienza,,Efficiency
Elettrificato,,Electrified
Esci,,Quit
Finanze,,Finance
"Flotta, dal treno più usurato",,"Fleet, most worn first"
Galleria,,Tunnel
Gallerie,,Tunnels
Gestionale ferroviario dall'alto,,Top-down railway management
Grano,,Wheat
Guasti nell'anno,,Failures this year
Guasto grave,,Major failure
Guasto lieve,,Minor failure
Il server non risponde più. La partita continua sul server.,,The server is not responding. The game goes on on the server.
Impianti,,Plant
Impieghi,,Jobs
Indica l'indirizzo del server,,Enter the server address
Indietro,,Back
Indirizzo (host:porta),,Address (host:port)
Indirizzo non valido,,Invalid address
Km di servizio al giorno,,Service km per day
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://).
Lavoratori,,Workers
Lavoratori e personale,,Workers and staff
Linea,,Line
Linee,,Lines
Linee della compagnia,,Company lines
Livello,,Level
Locomotiva,,Locomotive
Lunghezza,,Length
Manda al deposito,,Send to depot
Manutenzione,,Maintenance
Mappa di calore della condizione,,Condition heat map
Mercato,,Market
Merci e passeggeri in attesa,,Waiting goods and passengers
Minimappa,,Minimap
Nel bacino,,In the catchment
Nessun posto di lavoro servito dai tuoi treni.,,No workplace served by your trains.
Nessun tracciato,,No route
Nessun treno in officina,,No trains in the workshop
Nessuna convenzione: le industrie la propongono quando i tuoi treni portano almeno 20 pendolari al giorno.,,No agreements: industries offer one when your trains carry at least 20 commuters a day.
Nessuna linea,,No line
Nome automatico,,Automatic name
Nome del treno,,Train name
Nome della linea,,Line name
Notizie,,News
Officine,,Workshops
"Ogni mese le città mandano i loro lavoratori alle industrie e ai depositi raggiungibili con i tuoi treni entro 60 minuti (personale: 90). Qui vedi da dove arrivano, quanti posti restano scoperti e perché.",,"Every month towns send their workers to the industries and depots your trains reach within 60 minutes (staff: 90). Here you see where they come from, how many jobs stay vacant and why."
Ordina,,Order
Partita locale,,Local game
Partita locale non avviata,,Local game not started
Patrimonio netto,,Net worth
Pausa,,Pause
Pendenza massima,,Max gradient
Personale,,Staff
Politica del treno,,Train policy
Politica della flotta,,Fleet policy
Ponte,,Bridge
Ponti,,Bridges
Posti di lavoro,,Workplaces
Prenotato,,Booked
Prestito,,Loan
Prezzi globali di oggi (la borsa arriva in seguito).,,Today's global prices (the stock market comes later).
Produce,,Produces
Prossimo intervento,,Next intervention
Quota rispetto al terreno,,Height above ground
Raggio minimo,,Min radius
Rating,,Rating
Regione di,,Region of
Registro degli impieghi,,Employment register
Registro in arrivo dal server…,,Register on its way from the server…
Registro officina,,Workshop register
Ricambi,,Spare parts
Ricambi esauriti: gli interventi aspettano. Porta i ricambi in treno da una fabbrica di macchinari o da un porto.,,Spare parts exhausted: interventions are waiting. Bring parts by train from a machine factory or a port.
Ricambi già destinati,,Parts already allocated
Rifiuta,,Reject
Rilevato,,Embankment
Ritmo di lavoro (manca personale),,Work rate (staff shortage)
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."
Scorta desiderata,,Target stock
Se la capacità manca per 30 giorni la convenzione salta con una penale.,,If capacity falls short for 30 days the agreement breaks with a penalty.
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
Stalli,,Stalls
Stato,,Status
Stazione,,Station
Storico,,History
Svuota,,Clear
Token,,Token
Token del server,,Server token
Torna al menu,,Back to menu
Treni,,Trains
Treni della compagnia,,Company trains
Treno di riserva in deposito,,Reserve train in depot
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
a piedi,,on foot
abitanti,,inhabitants
al mese,,per month
anni,,years
attende i ricambi,,waiting for parts
attendi il pieno,,wait for full load
capacità delle carrozze insufficiente sulla,,not enough coach capacity on
capacità mancante da,,capacity short for
carica,,load
città senza servizi per il personale,,towns without services for staff
copertura,,coverage
da,,from
fermo in linea,,stranded on the line
fermo in salita,,stalled on grade
g,,d
giorni,,days
giorno,,day
guasto,,broken down
guasto lieve,,minor failure
hub mercato mondiale,,world market hub
in arrivo,,arriving
in attesa,,waiting
in attesa di via libera,,waiting for clearance
in coda,,queued
in deposito,,in depot
in marcia,,running
in officina,,in the workshop
in servizio,,in service
in stazione,,at station
intervento prenotato,,intervention booked
large,Grande,Large
lavoratori,,workers
lavori,,jobs
le città raggiungibili non hanno lavoratori liberi,,reachable towns have no free workers
linea,,line
medium,Medio,Medium
mila km,,thousand km
nessuna città raggiungibile entro,,no town reachable within
nessuna stazione serve il posto di lavoro,,no station serves the workplace
ore,,hours
personale,,staff
posti al giorno garantiti,,guaranteed seats a day
ricambi,,parts
rimorchiato,,towed
riserva,,reserve
scaduta,,overdue
scaduto,,overdue
scarica,,unload
senza linea,,no line
senza percorso,,no route
small,Piccolo,Small
soccorso tra,,rescue in
stallo,,stall
tecnici,,staff
tra,,in
treni,,trains
1 keys it en
2 Abitanti Population
3 Accetta Accept
4 Aggiorna Refresh
5 Ambra Amber
6 Annulla Cancel
7 Anteprima non disponibile: Preview unavailable:
8 Assegna Assign
9 Attendi il pieno alla prima fermata (max 2 giorni) Wait for full load at the first stop (max 2 days)
10 Attiva Active
11 Avvio del server locale… Starting the local server…
12 Binari Track
13 Binari di stazione Platforms
14 Blu Blue
15 Cantiere Construction
16 Carico Load
17 Cartella di manutenzione Maintenance record
18 Cartella in arrivo dal server… Record on its way from the server…
19 Cassa Cash
20 Celeste Light blue
21 Chiedi il prestito Request loan
22 Chiusa Closed
23 Classe Class
24 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.
25 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.
26 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.
27 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.
28 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.
29 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.
30 Collegamento in corso… Connecting…
31 Collegamento non riuscito Connection failed
32 Collegati Connect
33 Collegati a un server Connect to a server
34 Come la linea o la flotta Same as line or fleet
35 Componi Compose
36 Compra veicoli Buy vehicles
37 Condizione Condition
38 Connessione persa Connection lost
39 Consuma Consumes
40 Convenzioni Agreements
41 Coperto dalla riserva Covered by reserve
42 Costi dell'anno Costs this year
43 Costo Cost
44 Costruisci Build
45 Crea linea Create line
46 Dati del gioco non trovati o non validi. Game data missing or invalid.
47 Demolisci Demolish
48 Depositi e officine Depots and workshops
49 Deposito Depot
50 Deragliamento Derailment
51 Disconnesso Disconnected
52 Doppio binario Double track
53 Dove lavorano gli abitanti Where residents work
54 Efficienza Efficiency
55 Elettrificato Electrified
56 Esci Quit
57 Finanze Finance
58 Flotta, dal treno più usurato Fleet, most worn first
59 Galleria Tunnel
60 Gallerie Tunnels
61 Gestionale ferroviario dall'alto Top-down railway management
62 Grano Wheat
63 Guasti nell'anno Failures this year
64 Guasto grave Major failure
65 Guasto lieve Minor failure
66 Il server non risponde più. La partita continua sul server. The server is not responding. The game goes on on the server.
67 Impianti Plant
68 Impieghi Jobs
69 Indica l'indirizzo del server Enter the server address
70 Indietro Back
71 Indirizzo (host:porta) Address (host:port)
72 Indirizzo non valido Invalid address
73 Km di servizio al giorno Service km per day
74 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://).
75 Lavoratori Workers
76 Lavoratori e personale Workers and staff
77 Linea Line
78 Linee Lines
79 Linee della compagnia Company lines
80 Livello Level
81 Locomotiva Locomotive
82 Lunghezza Length
83 Manda al deposito Send to depot
84 Manutenzione Maintenance
85 Mappa di calore della condizione Condition heat map
86 Mercato Market
87 Merci e passeggeri in attesa Waiting goods and passengers
88 Minimappa Minimap
89 Nel bacino In the catchment
90 Nessun posto di lavoro servito dai tuoi treni. No workplace served by your trains.
91 Nessun tracciato No route
92 Nessun treno in officina No trains in the workshop
93 Nessuna convenzione: le industrie la propongono quando i tuoi treni portano almeno 20 pendolari al giorno. No agreements: industries offer one when your trains carry at least 20 commuters a day.
94 Nessuna linea No line
95 Nome automatico Automatic name
96 Nome del treno Train name
97 Nome della linea Line name
98 Notizie News
99 Officine Workshops
100 Ogni mese le città mandano i loro lavoratori alle industrie e ai depositi raggiungibili con i tuoi treni entro 60 minuti (personale: 90). Qui vedi da dove arrivano, quanti posti restano scoperti e perché. Every month towns send their workers to the industries and depots your trains reach within 60 minutes (staff: 90). Here you see where they come from, how many jobs stay vacant and why.
101 Ordina Order
102 Partita locale Local game
103 Partita locale non avviata Local game not started
104 Patrimonio netto Net worth
105 Pausa Pause
106 Pendenza massima Max gradient
107 Personale Staff
108 Politica del treno Train policy
109 Politica della flotta Fleet policy
110 Ponte Bridge
111 Ponti Bridges
112 Posti di lavoro Workplaces
113 Prenotato Booked
114 Prestito Loan
115 Prezzi globali di oggi (la borsa arriva in seguito). Today's global prices (the stock market comes later).
116 Produce Produces
117 Prossimo intervento Next intervention
118 Quota rispetto al terreno Height above ground
119 Raggio minimo Min radius
120 Rating Rating
121 Regione di Region of
122 Registro degli impieghi Employment register
123 Registro in arrivo dal server… Register on its way from the server…
124 Registro officina Workshop register
125 Ricambi Spare parts
126 Ricambi esauriti: gli interventi aspettano. Porta i ricambi in treno da una fabbrica di macchinari o da un porto. Spare parts exhausted: interventions are waiting. Bring parts by train from a machine factory or a port.
127 Ricambi già destinati Parts already allocated
128 Rifiuta Reject
129 Rilevato Embankment
130 Ritmo di lavoro (manca personale) Work rate (staff shortage)
131 Rosso coppo Tile red
132 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.
133 Scorta desiderata Target stock
134 Se la capacità manca per 30 giorni la convenzione salta con una penale. If capacity falls short for 30 days the agreement breaks with a penalty.
135 Segnali Signals
136 Seleziona i veicoli da comporre Select the vehicles to compose
137 Seleziona un treno Select a train
138 Seleziona un treno e un deposito Select a train and a depot
139 Serve un deposito A depot is required
140 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.
141 Servizi Services
142 Servono almeno due fermate At least two stops are needed
143 Soddisfazione Satisfaction
144 Stalli Stalls
145 Stato Status
146 Stazione Station
147 Storico History
148 Svuota Clear
149 Token Token
150 Token del server Server token
151 Torna al menu Back to menu
152 Treni Trains
153 Treni della compagnia Company trains
154 Treno di riserva in deposito Reserve train in depot
155 Trincea Cutting
156 Veicoli Vehicles
157 Veicoli liberi nel deposito (selezione multipla, in ordine) Free vehicles in the depot (multiple selection, in order)
158 Velocità Speed
159 Verde Green
160 Via Ferrea Via Ferrea
161 a piedi on foot
162 abitanti inhabitants
163 al mese per month
164 anni years
165 attende i ricambi waiting for parts
166 attendi il pieno wait for full load
167 capacità delle carrozze insufficiente sulla not enough coach capacity on
168 capacità mancante da capacity short for
169 carica load
170 città senza servizi per il personale towns without services for staff
171 copertura coverage
172 da from
173 fermo in linea stranded on the line
174 fermo in salita stalled on grade
175 g d
176 giorni days
177 giorno day
178 guasto broken down
179 guasto lieve minor failure
180 hub mercato mondiale world market hub
181 in arrivo arriving
182 in attesa waiting
183 in attesa di via libera waiting for clearance
184 in coda queued
185 in deposito in depot
186 in marcia running
187 in officina in the workshop
188 in servizio in service
189 in stazione at station
190 intervento prenotato intervention booked
191 large Grande Large
192 lavoratori workers
193 lavori jobs
194 le città raggiungibili non hanno lavoratori liberi reachable towns have no free workers
195 linea line
196 medium Medio Medium
197 mila km thousand km
198 nessuna città raggiungibile entro no town reachable within
199 nessuna stazione serve il posto di lavoro no station serves the workplace
200 ore hours
201 personale staff
202 posti al giorno garantiti guaranteed seats a day
203 ricambi parts
204 rimorchiato towed
205 riserva reserve
206 scaduta overdue
207 scaduto overdue
208 scarica unload
209 senza linea no line
210 senza percorso no route
211 small Piccolo Small
212 soccorso tra rescue in
213 stallo stall
214 tecnici staff
215 tra in
216 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,188 @@
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);
// manutenzione (F4): un tagliando prenotato, cartella del treno, registro officina, mappa di calore
await Ok(new ScheduleServiceCommand(new TrainId(train2), "service"));
Session.SetSpeed(8);
await Until(() => World.Trains.TryGetValue(train2, out var t2) && t2.Maintenance == TrainMaintenanceStatus.InWorkshop, "treno in officina", 240);
Session.SetSpeed(1);
_game.OpenMaintenance(train);
_game.OpenWorkshop(depot);
await Until(() => World.Cards.ContainsKey(train) && World.Workshops.TryGetValue(depot, out var reg) && reg.Jobs.Count > 0, "cartella e registro", 30);
_game.Map.CenterOn(center);
_game.Map.SetZoom(0.22f);
await Shot("09_officine", 40);
_game.ScrollPanel(1);
await Shot("09b_registro_officina", 20);
_game.ScrollPanel(0);
_game.SetHeatMap(true);
await Shot("10_mappa_di_calore", 20);
// Registro degli impieghi (sezione 9)
_game.UseTool(Tool.Employment);
await Until(() => World.Employment is not null, "registro degli impieghi", 30);
await Shot("11_impieghi", 30);
}
}
@@ -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,152 @@
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, Maintenance, Employment, 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.Maintenance, "Officine"), (Tool.Employment, "Impieghi"),
(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.Maintenance:
// chiave inglese
DrawArc(c + new Vector2(6, -6), 6, MathF.PI * 0.25f, MathF.PI * 1.75f, 16, col, w);
DrawLine(c + new Vector2(2, -2), c + new Vector2(-10, 10), col, w * 1.6f);
break;
case Tool.Employment:
// due persone
DrawCircle(c + new Vector2(-6, -6), 3.5f, col, false, w);
DrawCircle(c + new Vector2(6, -6), 3.5f, col, false, w);
DrawArc(c + new Vector2(-6, 9), 7, MathF.PI, MathF.Tau, 12, col, w);
DrawArc(c + new Vector2(6, 9), 7, MathF.PI, MathF.Tau, 12, 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,222 @@
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>Mappa di calore della condizione (10.3): un alone colorato sotto ogni treno.</summary>
public bool HeatMap { get; set; }
/// <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 (HeatMap)
{
var hp = MapScale.V(headPoint.Value);
var col = Panels.MaintenancePanel.ConditionColor((int)motion.Condition);
DrawCircle(hp, 14 * s, Palette.WithAlpha(col, 0.35f));
DrawArc(hp, 14 * s, 0, MathF.Tau, 32, col, 2 * s);
}
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,156 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
/// <summary>
/// Registro degli impieghi (sezione 9): convenzioni proposte dalle industrie (accetta o rifiuta),
/// posti di lavoro serviti dai treni della compagnia e suoi depositi, con provenienza dei
/// pendolari per città e linea, posti scoperti e motivo.
/// </summary>
public partial class EmploymentPanel : VBoxContainer
{
private readonly GameSession _session;
private readonly VBoxContainer _agreements = PanelKit.Column(8);
private readonly VBoxContainer _rows = PanelKit.Column(10);
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
private int _version = -1;
public EmploymentPanel(GameSession session)
{
_session = session;
AddThemeConstantOverride("separation", 10);
AddChild(UiTheme.TitleLabel(T("Registro degli impieghi"), 30));
var help = UiTheme.Text(T("Ogni mese le città mandano i loro lavoratori alle industrie e ai depositi raggiungibili con i tuoi treni entro 60 minuti (personale: 90). Qui vedi da dove arrivano, quanti posti restano scoperti e perché."), 13, Palette.TextSecondary);
help.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(help);
var refresh = new Button { Text = T("Aggiorna") };
refresh.Pressed += Request;
AddChild(refresh);
AddChild(UiTheme.Text(T("Convenzioni"), 16, bold: true));
AddChild(_agreements);
AddChild(PanelKit.Separator());
AddChild(UiTheme.Text(T("Posti di lavoro"), 16, bold: true));
AddChild(_rows);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(_status);
Request();
}
private void Request() => _session.Send(new RequestDetail { Kind = DetailKind.Employment, Target = 0 });
public override void _Process(double delta)
{
if (_session.World.DetailVersion != _version) Refresh();
}
private void Refresh()
{
var w = _session.World;
_version = w.DetailVersion;
foreach (var c in _agreements.GetChildren()) c.QueueFree();
foreach (var c in _rows.GetChildren()) c.QueueFree();
var report = w.Employment;
if (report is null)
{
_rows.AddChild(UiTheme.Text(T("Registro in arrivo dal server…"), 13, Palette.TextSecondary));
return;
}
var open = report.Agreements.Where(a => a.State <= 1).ToList();
if (open.Count == 0) _agreements.AddChild(Wrapped(T("Nessuna convenzione: le industrie la propongono quando i tuoi treni portano almeno 20 pendolari al giorno."), 13, Palette.TextSecondary));
foreach (var a in open) _agreements.AddChild(AgreementRow(w, a));
foreach (var row in report.Rows.OrderBy(r => r.Kind).ThenBy(r => r.Industry)) _rows.AddChild(WorkplaceRow(w, row));
if (report.Rows.Count == 0) _rows.AddChild(Wrapped(T("Nessun posto di lavoro servito dai tuoi treni."), 13, Palette.TextSecondary));
}
private Control AgreementRow(ClientWorld w, AgreementInfo a)
{
var box = new PanelContainer();
box.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, a.State == 0 ? Palette.Amber : Palette.Border, 8, 10));
var col = PanelKit.Column(6);
box.AddChild(col);
string industry = w.Industries.TryGetValue(a.Industry, out var ind) ? ind.Name : $"#{a.Industry}";
col.AddChild(UiTheme.Text(industry, 15, bold: true));
col.AddChild(Wrapped($"{a.SeatsPerDay} {T("posti al giorno garantiti")} · {a.MonthlyFee} {T("al mese")}", 13, null));
if (a.State == 0)
{
var buttons = PanelKit.Row(6);
var accept = UiTheme.Primary(T("Accetta"));
accept.Pressed += () => _session.Command(new AcceptAgreementCommand(new AgreementId(a.Id)), r => _status.Text = r.Message);
var reject = new Button { Text = T("Rifiuta") };
reject.Pressed += () => _session.Command(new RejectAgreementCommand(new AgreementId(a.Id)), r => _status.Text = r.Message);
buttons.AddChild(accept);
buttons.AddChild(reject);
col.AddChild(buttons);
var risk = UiTheme.Text(T("Se la capacità manca per 30 giorni la convenzione salta con una penale."), 12, Palette.TextSecondary);
risk.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(risk);
}
else
{
col.AddChild(UiTheme.Text($"{T("Attiva")} · {T("copertura")} {a.Coverage * 100:0}%" +
(a.ShortDays > 0 ? $" · {T("capacità mancante da")} {a.ShortDays} {T("giorni")}" : ""), 13, a.ShortDays > 0 ? Palette.Danger : Palette.Ok));
}
return box;
}
private Control WorkplaceRow(ClientWorld w, EmploymentRow row)
{
var col = PanelKit.Column(4);
string name = row.Kind == 1
? (w.Depots.TryGetValue(row.Industry, out var d) ? d.Name : $"#{row.Industry}")
: (w.Industries.TryGetValue(row.Industry, out var ind) ? ind.Name : $"#{row.Industry}");
col.AddChild(UiTheme.Text(name, 15, bold: true));
var stats = PanelKit.Row();
stats.AddChild(PanelKit.Stat(T("Lavoratori"), PanelKit.Value($"{row.WorkersPresent:0} / {row.JobsWorkers}")));
stats.AddChild(PanelKit.Stat(T("Personale"), PanelKit.Value($"{row.StaffPresent:0} / {row.JobsStaff}")));
col.AddChild(stats);
foreach (string reason in new[] { ReasonText(w, row.WorkersReason, row.WorkersReasonLine, staff: false), ReasonText(w, row.StaffReason, row.StaffReasonLine, staff: true) })
{
if (reason.Length == 0) continue;
var l = UiTheme.Text("⚠ " + reason, 13, Palette.Amber);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(l);
}
foreach (var s in row.Sources.OrderByDescending(s => s.Headcount))
{
string town = w.Towns.TryGetValue(s.Town, out var t) ? t.Name : $"#{s.Town}";
string via = s.Line >= 0 && w.Lines.TryGetValue(s.Line, out var line) ? line.Name : T("a piedi");
string who = s.Category == 1 ? T("tecnici") : T("lavoratori");
col.AddChild(Wrapped($"• {s.Headcount} {who} {T("da")} {town} · {via} · {T("copertura")} {s.Coverage * 100:0}%", 13,
s.Category == 1 ? Palette.Staff : Palette.Workers));
}
return col;
}
private static Label Wrapped(string text, int size, Color? color)
{
var l = UiTheme.Text(text, size, color);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
return l;
}
/// <summary>Motivo dei posti scoperti nella lingua dell'interfaccia (codici UncoveredReason).</summary>
public static string ReasonText(ClientWorld w, byte reason, int line, bool staff)
{
string who = staff ? T("Personale") : T("Lavoratori");
string minutes = staff ? $"{w.Data.Balance.Employment.StaffMaxMinutes:0}" : $"{w.Data.Balance.Employment.WorkerMaxMinutes:0}";
return reason switch
{
1 => $"{who}: {T("nessuna stazione serve il posto di lavoro")}",
2 => $"{who}: {T("nessuna città raggiungibile entro")} {minutes} min",
3 => $"{who}: {T("le città raggiungibili non hanno lavoratori liberi")}",
4 => $"{who}: {T("città senza servizi per il personale")}",
5 => $"{who}: {T("capacità delle carrozze insufficiente sulla")} {(w.Lines.TryGetValue(line, out var l) ? l.Name : T("linea"))}",
_ => "",
};
}
}
@@ -0,0 +1 @@
uid://bjfsfdctgdm1q
@@ -0,0 +1,197 @@
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 event Action<int>? MaintenanceRequested;
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("Manutenzione"), PanelKit.Value(MaintenancePanel.StatusName(t.Maintenance) +
(t.Reserve ? " · " + T("riserva") : ""))));
if (t.NextIntervention.Length > 0)
{
string next = w.Data.Maintenance.Interventions.FirstOrDefault(i => i.Id == t.NextIntervention)?.NameIt ?? t.NextIntervention;
AddChild(PanelKit.Pair(T("Prossimo intervento"), PanelKit.Value(t.NextDueDays <= 0 ? $"{next} · {T("scaduto")}" : $"{next} · {T("tra")} {t.NextDueDays} {T("giorni")}")));
}
int trainId = t.Id;
var cardButton = new Button { Text = T("Cartella di manutenzione") };
cardButton.Pressed += () => MaintenanceRequested?.Invoke(trainId);
AddChild(cardButton);
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")));
// dal Registro degli impieghi: presenze, posti scoperti e provenienza dei pendolari
if (w.Employment?.Rows.FirstOrDefault(r => r.Kind == 0 && r.Industry == ind.Id) is { } row)
{
AddChild(UiTheme.Text(T("Lavoratori e personale"), 14, bold: true));
AddChild(PanelKit.Pair(T("Lavoratori"), PanelKit.Value($"{row.WorkersPresent:0} / {row.JobsWorkers}")));
AddChild(PanelKit.Pair(T("Personale"), PanelKit.Value($"{row.StaffPresent:0} / {row.JobsStaff}")));
foreach (string reason in new[] { EmploymentPanel.ReasonText(w, row.WorkersReason, row.WorkersReasonLine, false), EmploymentPanel.ReasonText(w, row.StaffReason, row.StaffReasonLine, true) })
{
if (reason.Length == 0) continue;
var l = UiTheme.Text("⚠ " + reason, 13, Palette.Amber);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(l);
}
foreach (var src in row.Sources.OrderByDescending(x => x.Headcount).Take(6))
{
string town = w.Towns.TryGetValue(src.Town, out var tw) ? tw.Name : "?";
string via = src.Line >= 0 && w.Lines.TryGetValue(src.Line, out var ln) ? ln.Name : T("a piedi");
AddChild(UiTheme.Text($"• {src.Headcount} {T("da")} {town} · {via}", 13, src.Category == 1 ? Palette.Staff : Palette.Workers));
}
}
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}")));
// dove lavorano gli abitanti (posti serviti dai tuoi treni)
if (w.Employment is { } report)
{
var jobs = report.Rows
.Select(r => (Row: r, Count: r.Sources.Where(x => x.Town == town.Id).Sum(x => x.Headcount)))
.Where(x => x.Count > 0).OrderByDescending(x => x.Count).ToList();
if (jobs.Count > 0) AddChild(UiTheme.Text(T("Dove lavorano gli abitanti"), 14, bold: true));
foreach (var (r, count) in jobs.Take(8))
{
string where = r.Kind == 1 ? (w.Depots.TryGetValue(r.Industry, out var d) ? d.Name : "?") : (w.Industries.TryGetValue(r.Industry, out var i2) ? i2.Name : "?");
AddChild(UiTheme.Text($"• {count} · {where}", 13));
}
}
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,352 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Protocol.Messages;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
/// <summary>
/// Officine (sezione 10.3): politica della flotta, avvisi, flotta ordinata per condizione con la
/// mappa di calore, cartella di manutenzione del treno scelto, depositi con il Registro officina e
/// la scorta di ricambi. Le cartelle e i registri arrivano su richiesta dal server.
/// </summary>
public partial class MaintenancePanel : VBoxContainer
{
private static readonly string[] PolicyIds = ["economy", "standard", "thorough"];
private readonly GameSession _session;
private readonly OptionButton _fleetPolicy = new();
private readonly CheckButton _heat = new() { Text = T("Mappa di calore della condizione") };
private readonly VBoxContainer _alerts = PanelKit.Column(4);
private readonly ItemList _trains = new() { CustomMinimumSize = new Vector2(0, 150) };
private readonly VBoxContainer _card = PanelKit.Column(8);
private readonly VBoxContainer _cardControls = PanelKit.Column(8);
private readonly VBoxContainer _cardDetails = PanelKit.Column(6);
private readonly ItemList _depots = new() { CustomMinimumSize = new Vector2(0, 80) };
private readonly VBoxContainer _workshop = PanelKit.Column(8);
private readonly VBoxContainer _workshopDetails = PanelKit.Column(6);
private readonly HBoxContainer _orderRow = PanelKit.Row();
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
private readonly List<int> _trainIds = [];
private readonly List<int> _depotIds = [];
private int _train = -1, _depot = -1;
private int _entityVersion = -1, _detailVersion = -1;
private double _request;
private bool _updating;
public event Action<bool>? HeatMapToggled;
public event Action<int>? TrainSelected;
public MaintenancePanel(GameSession session, bool heatMap)
{
_session = session;
AddThemeConstantOverride("separation", 10);
AddChild(UiTheme.TitleLabel(T("Officine"), 34));
var policyRow = PanelKit.Row();
var caption = UiTheme.Text(T("Politica della flotta"), 14, Palette.TextSecondary);
caption.SizeFlagsHorizontal = SizeFlags.ExpandFill;
policyRow.AddChild(caption);
foreach (var p in session.World.Data.Maintenance.Policies) _fleetPolicy.AddItem(p.NameIt);
policyRow.AddChild(_fleetPolicy);
AddChild(policyRow);
_heat.ButtonPressed = heatMap;
_heat.Toggled += on => HeatMapToggled?.Invoke(on);
AddChild(_heat);
AddChild(_alerts);
AddChild(PanelKit.Separator());
AddChild(UiTheme.Text(T("Flotta, dal treno più usurato"), 14, bold: true));
AddChild(_trains);
AddChild(_card);
AddChild(_cardControls);
AddChild(_cardDetails);
AddChild(PanelKit.Separator());
AddChild(UiTheme.Text(T("Depositi e officine"), 14, bold: true));
AddChild(_depots);
AddChild(_workshop);
AddChild(_workshopDetails);
AddChild(_orderRow);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(_status);
_fleetPolicy.ItemSelected += i =>
{
if (!_updating) _session.Command(new SetMaintenancePolicyCommand(MaintenanceScope.Company, 0, PolicyIds[i]), Result);
};
_trains.ItemSelected += i => SelectTrain(_trainIds[(int)i]);
_depots.ItemSelected += i => SelectDepot(_depotIds[(int)i]);
}
/// <summary>Allinea l'interruttore della mappa di calore senza rilanciare l'evento.</summary>
public void SetHeatMap(bool on) => _heat.SetPressedNoSignal(on);
public void SelectTrain(int id)
{
_train = id;
_detailVersion = -1;
_session.Send(new RequestDetail { Kind = DetailKind.TrainCard, Target = id });
TrainSelected?.Invoke(id);
BuildCardControls();
Refresh();
}
public void SelectDepot(int id)
{
_depot = id;
_detailVersion = -1;
_session.Send(new RequestDetail { Kind = DetailKind.Workshop, Target = id });
BuildOrderRow();
Refresh();
}
public override void _Process(double delta)
{
// cartella e registro aperti si aggiornano una volta al secondo
_request += delta;
if (_request >= 1)
{
_request = 0;
if (_train >= 0) _session.Send(new RequestDetail { Kind = DetailKind.TrainCard, Target = _train });
if (_depot >= 0) _session.Send(new RequestDetail { Kind = DetailKind.Workshop, Target = _depot });
}
var w = _session.World;
if (w.EntityVersion != _entityVersion || w.DetailVersion != _detailVersion) Refresh();
}
private void Result(CommandResultMessage r) => _status.Text = r.Message;
private void Refresh()
{
var w = _session.World;
_entityVersion = w.EntityVersion;
_detailVersion = w.DetailVersion;
int company = w.Summary?.CompanyId ?? 0;
_updating = true;
if (w.Companies.TryGetValue(company, out var me)) _fleetPolicy.Selected = Math.Clamp(me.MaintenancePolicy, 0, PolicyIds.Length - 1);
_updating = false;
foreach (var c in _alerts.GetChildren()) c.QueueFree();
foreach (var a in w.Alerts.Take(4))
{
var l = UiTheme.Text("⚠ " + a.Text, 13, a.Condition < w.Data.Maintenance.Planner.CriticalCondition ? Palette.Danger : Palette.Amber);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
_alerts.AddChild(l);
}
_trainIds.Clear();
_trains.Clear();
foreach (var t in w.Trains.Values.Where(t => t.Owner == company).OrderBy(t => t.Condition).ThenBy(t => t.Id))
{
_trainIds.Add(t.Id);
_trains.AddItem($"{t.Name} · {t.Condition}% · {StatusName(t.Maintenance)}{(t.Reserve ? " · " + T("riserva") : "")}{DueText(t)}");
_trains.SetItemCustomFgColor(_trains.ItemCount - 1, ConditionColor(t.Condition));
}
int ti = _trainIds.IndexOf(_train);
if (ti >= 0) _trains.Select(ti);
_depotIds.Clear();
_depots.Clear();
foreach (var d in w.Depots.Values.Where(d => d.Owner == company).OrderBy(d => d.Id))
{
_depotIds.Add(d.Id);
_depots.AddItem($"{d.Name} · {T("ricambi")} {d.SpareParts}/{d.PartsTarget} · {T("personale")} {d.StaffPercent}% · {d.Jobs} {T("lavori")}");
if (d.WaitingParts) _depots.SetItemCustomFgColor(_depots.ItemCount - 1, Palette.Danger);
}
int di = _depotIds.IndexOf(_depot);
if (di >= 0) _depots.Select(di);
BuildCard();
BuildWorkshop();
}
private string DueText(TrainInfo t)
{
if (t.NextIntervention.Length == 0 || t.Maintenance != TrainMaintenanceStatus.InService) return "";
return t.NextDueDays <= 0
? $" · {InterventionName(t.NextIntervention)} {T("scaduta")}"
: $" · {InterventionName(t.NextIntervention)} {T("tra")} {t.NextDueDays} {T("g")}";
}
// ------------------------------------------------------------------ cartella di manutenzione
private void BuildCard()
{
foreach (var c in _card.GetChildren()) c.QueueFree();
foreach (var c in _cardDetails.GetChildren()) c.QueueFree();
var w = _session.World;
if (_train < 0 || !w.Trains.TryGetValue(_train, out var t)) return;
_card.AddChild(UiTheme.TitleLabel(T("Cartella di manutenzione") + " · " + t.Name, 22));
var card = w.Cards.GetValueOrDefault(_train);
var stats = PanelKit.Row();
stats.AddChild(PanelKit.Stat(T("Condizione"), PanelKit.Value($"{Math.Floor(card?.Condition ?? t.Condition):0}%")));
stats.AddChild(PanelKit.Stat(T("Guasti nell'anno"), PanelKit.Value($"{card?.FailuresThisYear ?? 0}")));
stats.AddChild(PanelKit.Stat(T("Costi dell'anno"), PanelKit.Value((card?.CostThisYear ?? Money.Zero).ToString())));
_card.AddChild(stats);
_card.AddChild(PanelKit.Pair(T("Stato"), PanelKit.Value(StatusName(t.Maintenance))));
if (card is not null)
{
if (card.Failure != 0)
_card.AddChild(UiTheme.Notice($"{FailureName(card.Failure)}: {ComponentName(card.FailedComponent)}" +
(card.RescueHours >= 0 ? $" · {T("soccorso tra")} {card.RescueHours:0.0} {T("ore")}" : "")));
if (card.PlannedIntervention.Length > 0 && card.MaintenanceDepot >= 0 && w.Depots.TryGetValue(card.MaintenanceDepot, out var md))
_card.AddChild(PanelKit.Pair(T("Prenotato"), PanelKit.Value($"{InterventionName(card.PlannedIntervention)} · {md.Name}")));
if (card.NextIntervention.Length > 0)
_card.AddChild(PanelKit.Pair(T("Prossimo intervento"), PanelKit.Value(card.NextDueDays <= 0
? $"{InterventionName(card.NextIntervention)} · {T("scaduto")}"
: $"{InterventionName(card.NextIntervention)} · {T("tra")} {Math.Ceiling(card.NextDueDays):0} {T("giorni")}")));
_card.AddChild(PanelKit.Pair(T("Km di servizio al giorno"), PanelKit.Value($"{card.ServiceKmPerDay:0}")));
if (card.CoveredBy >= 0 && w.Trains.TryGetValue(card.CoveredBy, out var cover))
_card.AddChild(PanelKit.Pair(T("Coperto dalla riserva"), PanelKit.Value(cover.Name)));
}
if (card is null)
{
_cardDetails.AddChild(UiTheme.Text(T("Cartella in arrivo dal server…"), 13, Palette.TextSecondary));
return;
}
foreach (var v in card.Vehicles)
{
var def = w.Data.Vehicles.FirstOrDefault(d => d.Id == v.Type);
_cardDetails.AddChild(UiTheme.Text($"{def?.NameIt ?? v.Type} #{v.Vehicle} · {v.OdometerKm / 1000:0.#} {T("mila km")} · {v.AgeYears:0.#} {T("anni")}", 13, bold: true));
foreach (var c in v.Components)
{
var row = PanelKit.Row(6);
var name = UiTheme.Text(ComponentName(c.Component), 12, Palette.TextSecondary);
name.CustomMinimumSize = new Vector2(150, 0);
row.AddChild(name);
var bar = new ProgressBar { MaxValue = 100, Value = c.Condition, ShowPercentage = false, CustomMinimumSize = new Vector2(0, 10), SizeFlagsHorizontal = SizeFlags.ExpandFill };
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(ConditionColor((int)c.Condition), ConditionColor((int)c.Condition), 3, 0));
row.AddChild(bar);
row.AddChild(UiTheme.Text($"{c.Condition:0}%", 12, bold: true));
_cardDetails.AddChild(row);
}
}
if (card.History.Count > 0)
{
_cardDetails.AddChild(UiTheme.Text(T("Storico"), 14, bold: true));
foreach (var h in Enumerable.Reverse(card.History).Take(6))
{
string depot = w.Depots.TryGetValue(h.Depot, out var dd) ? dd.Name : "";
_cardDetails.AddChild(UiTheme.Text($"{T("giorno")} {h.Day} · {InterventionName(h.Intervention)} · {h.Cost} · {depot}", 12, Palette.TextSecondary));
}
}
}
// controlli della cartella: costruiti alla selezione, non a ogni aggiornamento
private void BuildCardControls()
{
foreach (var c in _cardControls.GetChildren()) c.QueueFree();
var w = _session.World;
if (_train < 0 || !w.Trains.TryGetValue(_train, out var t)) return;
// politica propria del treno e riserva
var policy = new OptionButton();
policy.AddItem(T("Come la linea o la flotta"));
foreach (var p in w.Data.Maintenance.Policies) policy.AddItem(p.NameIt);
policy.Selected = t.Policy == byte.MaxValue ? 0 : t.Policy + 1;
policy.ItemSelected += i => _session.Command(new SetMaintenancePolicyCommand(MaintenanceScope.Train, _train, i == 0 ? "inherit" : PolicyIds[i - 1]), Result);
_cardControls.AddChild(PanelKit.Pair(T("Politica del treno"), new Label()));
_cardControls.AddChild(policy);
var reserve = new CheckBox { Text = T("Treno di riserva in deposito"), ButtonPressed = t.Reserve };
reserve.Toggled += on => _session.Command(new SetReserveCommand(new TrainId(_train), on), Result);
_cardControls.AddChild(reserve);
var actions = PanelKit.Row(6);
foreach (string id in new[] { "inspection", "service", "overhaul" })
{
var b = new Button { Text = InterventionName(id), SizeFlagsHorizontal = SizeFlags.ExpandFill };
b.Pressed += () => _session.Command(new ScheduleServiceCommand(new TrainId(_train), id), Result);
actions.AddChild(b);
}
_cardControls.AddChild(actions);
}
// ------------------------------------------------------------------ registro officina
private void BuildWorkshop()
{
foreach (var c in _workshop.GetChildren()) c.QueueFree();
foreach (var c in _workshopDetails.GetChildren()) c.QueueFree();
var w = _session.World;
if (_depot < 0 || !w.Depots.TryGetValue(_depot, out var d)) return;
_workshop.AddChild(UiTheme.TitleLabel(T("Registro officina") + " · " + d.Name, 22));
var reg = w.Workshops.GetValueOrDefault(_depot);
var stats = PanelKit.Row();
stats.AddChild(PanelKit.Stat(T("Stalli"), PanelKit.Value($"{d.Stalls}")));
stats.AddChild(PanelKit.Stat(T("Personale"), PanelKit.Value($"{d.StaffPercent}%")));
stats.AddChild(PanelKit.Stat(T("Ricambi"), PanelKit.Value($"{d.SpareParts}")));
_workshop.AddChild(stats);
if (d.WaitingParts) _workshop.AddChild(UiTheme.Notice(T("Ricambi esauriti: gli interventi aspettano. Porta i ricambi in treno da una fabbrica di macchinari o da un porto.")));
if (reg is not null)
{
if (reg.WorkRate < 0.999f)
_workshopDetails.AddChild(PanelKit.Pair(T("Ritmo di lavoro (manca personale)"), PanelKit.Value($"{reg.WorkRate * 100:0}%")));
_workshopDetails.AddChild(PanelKit.Pair(T("Ricambi già destinati"), PanelKit.Value($"{reg.PartsReserved}")));
int stall = 0;
foreach (var j in reg.Jobs)
{
string train = w.Trains.TryGetValue(j.Train, out var t) ? t.Name : $"#{j.Train}";
string where = j.InStall ? $"{T("stallo")} {++stall}" : T("in coda");
string what = j.Started ? $"{j.Progress:0.0}/{j.Days:0} {T("giorni")}" : j.InStall ? T("attende i ricambi") : T("in attesa");
var line = UiTheme.Text($"{where} · {train} · {InterventionName(j.Intervention)} · {what}", 13);
line.AutowrapMode = TextServer.AutowrapMode.WordSmart;
_workshopDetails.AddChild(line);
}
foreach (var j in reg.Booked)
{
string train = w.Trains.TryGetValue(j.Train, out var t) ? t.Name : $"#{j.Train}";
_workshopDetails.AddChild(UiTheme.Text($"{T("in arrivo")} · {train} · {InterventionName(j.Intervention)} · {j.Parts} {T("ricambi")}", 13, Palette.TextSecondary));
}
if (reg.Jobs.Count == 0 && reg.Booked.Count == 0) _workshopDetails.AddChild(UiTheme.Text(T("Nessun treno in officina"), 13, Palette.TextSecondary));
}
}
// scorta desiderata: costruita alla selezione del deposito
private void BuildOrderRow()
{
foreach (var c in _orderRow.GetChildren()) c.QueueFree();
var w = _session.World;
if (_depot < 0 || !w.Depots.TryGetValue(_depot, out var d)) return;
var target = new SpinBox { MinValue = 0, MaxValue = w.Data.Maintenance.Depots.MaxSpareParts, Value = d.PartsTarget, SizeFlagsHorizontal = SizeFlags.ExpandFill };
_orderRow.AddChild(UiTheme.Text(T("Scorta desiderata"), 13, Palette.TextSecondary));
_orderRow.AddChild(target);
var button = new Button { Text = T("Ordina") };
button.Pressed += () => _session.Command(new OrderPartsCommand(new DepotId(_depot), (int)target.Value), Result);
_orderRow.AddChild(button);
}
// ------------------------------------------------------------------ testi
public static string StatusName(TrainMaintenanceStatus s) => s switch
{
TrainMaintenanceStatus.Booked => T("intervento prenotato"),
TrainMaintenanceStatus.InWorkshop => T("in officina"),
TrainMaintenanceStatus.MinorFailure => T("guasto lieve"),
TrainMaintenanceStatus.Stranded => T("fermo in linea"),
TrainMaintenanceStatus.Towed => T("rimorchiato"),
_ => T("in servizio"),
};
private static string FailureName(byte f) => f switch
{
1 => T("Guasto lieve"),
2 => T("Guasto grave"),
3 => T("Deragliamento"),
_ => "",
};
public string InterventionName(string id) =>
_session.World.Data.Maintenance.Interventions.FirstOrDefault(i => i.Id == id)?.NameIt ?? id;
private string ComponentName(string id)
{
var m = _session.World.Data.Maintenance.Components;
return m.Locomotive.Concat(m.Car).FirstOrDefault(c => c.Id == id)?.NameIt ?? id;
}
/// <summary>Colore della condizione: verde sopra 70, ambra fino a 40, rosso sotto.</summary>
public static Color ConditionColor(int condition) =>
condition >= 70 ? Palette.Ok : condition >= 40 ? Palette.Amber : Palette.Danger;
}
@@ -0,0 +1 @@
uid://0pftav3413uj
@@ -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,602 @@
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 MaintenancePanel? _maintenance;
private bool _heatMap;
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>
/// <summary>Apre la cartella di manutenzione del treno nel pannello Officine.</summary>
public void OpenMaintenance(int train)
{
_toolbar.Select(Tool.Maintenance);
_maintenance?.SelectTrain(train);
}
/// <summary>Apre il Registro officina del deposito nel pannello Officine.</summary>
public void OpenWorkshop(int depot)
{
if (_tool != Tool.Maintenance) _toolbar.Select(Tool.Maintenance);
_maintenance?.SelectDepot(depot);
}
/// <summary>Mappa di calore della condizione dei treni.</summary>
public void SetHeatMap(bool on)
{
_map.Trains.HeatMap = _heatMap = on;
_maintenance?.SetHeatMap(on);
}
/// <summary>Scorre il pannello laterale (0 = in cima, 1 = in fondo).</summary>
public void ScrollPanel(double fraction)
{
var bar = _scroll.GetVScrollBar();
_scroll.ScrollVertical = (int)Math.Round((bar.MaxValue - bar.Page) * Math.Clamp(fraction, 0, 1));
}
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);
// il Registro degli impieghi alimenta anche le schede di industrie e città
_session.Send(new RequestDetail { Kind = DetailKind.Employment, Target = 0 });
}
public override void _ExitTree() => _session.MessageApplied -= OnMessage;
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;
_maintenance = 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.Maintenance:
_maintenance = new MaintenancePanel(_session, _heatMap);
_maintenance.HeatMapToggled += on => _map.Trains.HeatMap = _heatMap = on;
_maintenance.TrainSelected += id =>
{
_map.Trains.SelectedTrain = id;
if (_map.Trains.Heads.TryGetValue(id, out var p)) _map.CenterOn(p);
};
panel = _maintenance;
break;
case Tool.Employment:
panel = new EmploymentPanel(_session);
break;
case Tool.Market:
panel = new MarketPanel(_session);
break;
case Tool.Finance:
panel = new FinancePanel(_session);
break;
default:
panel = _info = new InfoPanel(_session);
_info.MaintenanceRequested += OpenMaintenance;
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
+28
View File
@@ -0,0 +1,28 @@
{
"$schema": "schema/ai.schema.json",
"version": 1,
"planning": {
"intervalDays": 30,
"maxCandidates": 40,
"maxProjectsPerMonth": 2,
"candidateMaxDistanceKm": 40,
"candidateMinDistanceKm": 4,
"pathSlopePenalty": 40,
"pathWaterPenalty": 8,
"trainsPerLine": 2,
"wagonsPerTrain": 5,
"cashReserveMonths": 3,
"revenueHorizonYears": 10,
"maxRejectedShare": 0.05
},
"personalities": [
{ "id": "expansive", "name_it": "Espansiva", "roiThreshold": 0.08, "loanShareOfCredit": 0.8, "targetsPlayer": false, "buysShares": false, "maintenancePolicy": "standard" },
{ "id": "prudent", "name_it": "Prudente", "roiThreshold": 0.15, "loanShareOfCredit": 0.3, "targetsPlayer": false, "buysShares": false, "maintenancePolicy": "standard" },
{ "id": "predatory", "name_it": "Predatoria", "roiThreshold": 0.10, "loanShareOfCredit": 0.6, "targetsPlayer": true, "buysShares": true, "maintenancePolicy": "standard" }
],
"companyNames": [
"Strade Ferrate del Nord", "Società Ferroviaria Adriatica", "Compagnia delle Valli", "Ferrovie Meridionali",
"Società Anonima delle Strade Ferrate", "Ferrovia Alta Valle", "Compagnia Lombardo-Veneta", "Rete del Litorale"
],
"colors": [ "#3f86d1", "#5fc39b", "#b3573e", "#9cc9f2", "#d9c26a", "#7c8590" ]
}
+186
View File
@@ -0,0 +1,186 @@
{
"$schema": "schema/balance.schema.json",
"version": 1,
"time": {
"tickMs": 50,
"ticksPerDay": 240,
"daysPerMonth": 30,
"monthsPerYear": 12,
"trainClockFactor": 60,
"speeds": [ 0, 1, 2, 4, 8 ],
"defaultStartYear": 1850
},
"map": {
"cellSizeM": 100,
"sizesKm": [ 64, 128, 256 ],
"chunkCells": 64,
"maxElevationM": 2200,
"noise": { "octaves": 5, "baseWavelengthKm": 48, "persistence": 0.5, "lacunarity": 2.0,
"warpStrengthKm": 9, "warpWavelengthKm": 36, "warpOctaves": 2,
"ridgeOctaves": 4, "ridgeWavelengthKm": 28 },
"relief": { "noiseAmplitudeM": 380, "noiseCoastFactor": 0.15, "inlandGradientM": 700, "inlandExponent": 2.0, "seaOffsetM": 25,
"mountainAmplitudeM": 1400, "mountainStart": 0.55, "seaBandFraction": 0.03, "coastNoiseM": 90,
"microReliefM": 6, "microWavelengthKm": 1.2 },
"hydrology": { "riverThresholdKm2": 18, "riverWidthSteps": [ 1, 4, 16, 64 ], "carveDepthM": 4, "valleyRadiusCells": 3, "valleyDepthM": 6,
"lakeMinDepthM": 3, "lakeMinCells": 8, "lakeMaxPercentile": 0.6, "minSourcePercentile": 0.30 },
"cover": { "rockPercentile": 0.70, "rockMinSlope": 0.18, "mountainPercentile": 0.90, "hillMinSlope": 0.07, "hillPercentile": 0.55,
"forestMinSlope": 0.03, "forestMaxSlope": 0.30, "forestNoiseThreshold": 0.52, "forestWavelengthKm": 6,
"marshMaxPercentile": 0.25, "marshRiverDistanceCells": 4, "marshMaxSlope": 0.012, "marshNoiseThreshold": 0.6,
"fieldRadiusCells": 14, "fieldShare": 0.35 },
"deposits": { "perThousandKm2": { "coal": 0.8, "iron": 0.6, "stone": 0.7, "oil": 0.4 },
"radiusCells": [ 3, 7 ], "reserveTonnes": { "coal": [ 250000, 900000 ], "iron": [ 200000, 700000 ], "stone": [ 400000, 1500000 ], "oil": [ 150000, 600000 ] },
"minSpacingKm": 5, "preferredMinPercentile": { "coal": 0.45, "iron": 0.60, "stone": 0.40, "oil": 0.0 },
"preferredMaxPercentile": { "coal": 0.92, "iron": 1.0, "stone": 0.95, "oil": 0.45 } },
"towns": { "countBySize": { "64": 10, "128": 26, "256": 56 }, "minDistanceKm": 6, "maxWaterDistanceKm": 3, "maxSlope": 0.05,
"maxHeightPercentile": 0.65, "largestPopulation": [ 11000, 18000 ], "zipfExponent": 0.85, "minPopulation": 500,
"radiusBaseCells": 2.0, "radiusPerSqrtPop": 0.025, "radiusHysteresisCells": 0.25 },
"industries": { "countBySize": { "64": 32, "128": 110, "256": 400 }, "initialLevels": [ 1, 2 ],
"shares": { "farm": 0.35, "logging": 0.12, "processing": 0.33, "manufacturing": 0.20 }, "placementAttempts": 400,
"maxSlope": 0.15, "spacingCells": 1 },
"hubs": { "ports": 1, "borders": 1, "portMinPopulationNearbyKm": 15 }
},
"market": {
"k": 0.08,
"alpha": 0.15,
"windowDays": 30,
"minPriceFactor": 0.3,
"maxPriceFactor": 3.0,
"ratioMin": 0.2,
"ratioMax": 5.0,
"world": { "amplitude": 0.12, "periodYears": 6, "volumeShare": 0.5, "baselinePerDay": 4.0, "elasticity": 1.0,
"shockChancePerYear": 0.25, "shockMin": 0.08, "shockMax": 0.30, "shockDecayDays": 150, "priceFloor": 0.05 },
"historyDays": 360
},
"localPrice": { "lambda": 0.35, "maxDeviation": 0.40, "epsilon": 1.0 },
"industry": {
"coverageWindowDays": 30,
"profitFactorSlope": 0.5,
"profitFactorMin": 0.6,
"profitFactorMax": 1.2,
"marginWindowDays": 90,
"wagePerWorkerPerMonth": 1800,
"wagePerStaffPerMonth": 5000,
"onSiteWorkerShare": 0.30,
"onSiteStaffShare": 0.30,
"initialStockDays": 10,
"footprintCells": { "small": 2, "medium": 3, "large": 4 },
"depletionStartFraction": 0.20,
"startingCash": 2000000
},
"growth": {
"quarterDays": 90,
"weightShipped": 0.5,
"weightCoverage": 0.3,
"weightProfit": 0.2,
"upgradeThreshold": 0.75,
"upgradeQuarters": 2,
"downgradeThreshold": 0.35,
"closeQuartersAtZero": 4,
"maxLevel": 5,
"spawnUnmetDays": 360,
"spawnUnmetRatio": 1.25,
"spawnMaxPerYear": 2
},
"town": {
"baseGrowth": 0.002,
"satisfactionWeight": 0.004,
"employmentWeight": 0.003,
"employmentPivot": 0.4,
"maxMonthlyGrowth": 0.01,
"satisfactionPivot": 0.5,
"workforceShare": 0.40,
"staffShare": 0.08,
"staffMinPopulation": 5000,
"staffMinServices": 2,
"servicesSatisfactionThreshold": 0.5,
"baseServicesPerPopulation": 6000,
"serviceJobsShare": 0.12,
"satisfactionEmaDays": 30,
"initialSatisfaction": 0.5,
"stockDays": 20,
"workSatisfactionPenalty": 0.05,
"workDissatisfactionDecayDays": 90,
"demandPriceFactorMin": 0.5,
"demandPriceFactorMax": 1.5,
"populationMilestone": 10000,
"maxPopulation": 2000000
},
"migration": { "share": 0.01, "satisfactionThreshold": 0.4, "maxDistanceKm": 60, "emigrationShareWhenNoTarget": 0.5 },
"employment": { "walkRadiusKm": 1.5, "workerMaxMinutes": 60, "staffMaxMinutes": 90, "coverageEmaDays": 30,
"dissolveCoverage": 0.5, "dissolveDays": 90, "walkSpeedKmh": 4.5, "boardDays": 2, "returnBoardDays": 2,
"railStartCoverage": 0.5, "lineCapacityUtilization": 0.85,
"agreements": { "minSeats": 20, "proposalChance": 0.5, "feePerSeatPerMonth": 2500, "proposalDays": 30,
"durationMonths": 24, "cooldownMonths": 6, "minCoverage": 0.9, "breakDays": 30, "penaltyMonths": 3 } },
"localTransport": { "enabled": true, "radiusKm": 3.0, "dailyShare": 0.25, "maxUnitsPerDay": 6 },
"hubs": {
"port": { "name_it": "Porto", "monthlyCapacity": 3000, "duty": 0.08, "footprint": "large" },
"border": { "name_it": "Valico", "monthlyCapacity": 1500, "duty": 0.12, "footprint": "small" }
},
"tariffs": {
"freightBaseRate": 150,
"freightFixedWeight": 0.6,
"freightPriceWeight": 0.4,
"freightKmExponent": 0.9,
"paxBaseFare": 45,
"paxKmExponent": 0.85,
"classMultipliers": { "worker": 1.0, "staff": 3.0 },
"lateThreshold": 1.5,
"lateFactorMin": 0.5,
"lateFactorSpan": 1.0
},
"finance": {
"ratingSpreads": { "AAA": 0.005, "AA": 0.01, "A": 0.015, "BBB": 0.025, "BB": 0.035, "B": 0.05, "CCC": 0.07, "CC": 0.09, "C": 0.12, "D": 0.18 },
"ratingByScore": [ 0.85, 0.75, 0.65, 0.55, 0.45, 0.35, 0.25, 0.15, 0.05 ],
"profitMarginWeight": 0.6,
"leverageWeight": 0.4,
"loanTermMonths": 120,
"loanStep": 5000000,
"startingRating": "BB",
"depreciationYearsTrack": 50,
"bookValueFloor": 0.1
},
"stockMarket": {
"shares": 1000000,
"earningsMultiple": 8,
"sentimentMin": 0.8,
"sentimentMax": 1.3,
"spread": 0.01,
"ipoMaxShare": 0.4,
"controlShare": 0.5,
"mergeAfterDays": 360,
"bidPremiumMin": 0.2,
"bidPremiumMax": 0.5,
"bidDurationDays": 90,
"ransomShare": 0.51,
"receivershipDividend": 0.5
},
"industryMaintenance": {
"wearPerDay": 0.06,
"efficiencyFullAbove": 70,
"efficiencyAt20": 0.5,
"efficiencyBelow20": 0.3,
"breakdownBase": 0.001,
"breakdownPivot": 40,
"breakdownScale": 8,
"breakdownDays": [ 5, 20 ],
"breakdownTownSatisfaction": 0.02,
"accidentBelow": 10,
"accidentDays": 60,
"accidentPopulationLoss": 0.002,
"budgets": {
"none": { "recoveryPerDay": 0.0, "costShareOfRevenue": 0.0, "sparePartsPerLevelPerMonth": 0 },
"base": { "recoveryPerDay": 0.05, "costShareOfRevenue": 0.03, "sparePartsPerLevelPerMonth": 1 },
"high": { "recoveryPerDay": 0.12, "costShareOfRevenue": 0.07, "sparePartsPerLevelPerMonth": 3 }
},
"noPartsRecoveryFactor": 0.5,
"overhaulDays": 30,
"overhaulMachineryPerLevel": 2,
"overhaulMinStaffCoverage": 0.8,
"upgradeMachineryPerLevel": 5,
"upgradeDays": 60,
"npcUpgradeMargin": 0.15,
"npcUpgradeYears": 2,
"npcHighMargin": 0.15,
"npcOverhaulBelow": 35
}
}
+109
View File
@@ -0,0 +1,109 @@
{
"$schema": "schema/construction.schema.json",
"version": 1,
"profile": {
"sampleSpacingM": 25,
"heightOffsetRangeM": 20,
"smoothingWindow": 5,
"naturalToleranceM": 1.5,
"embankmentMaxM": 8,
"cuttingMaxM": 8,
"riverClearanceM": 6,
"navigableClearanceM": 12,
"navigableMinWidthCells": 3,
"riverWidthMByClass": [ 30, 60, 120, 250 ],
"snapAngleDeg": 45
},
"maxGradientByTraction": { "steam": 0.025, "diesel": 0.035, "electric": 0.04, "highspeed": 0.035 },
"speedClasses": [
{ "trackClass": "c60", "minRadiusM": 200, "costMultiplier": 1.0 },
{ "trackClass": "c100", "minRadiusM": 400, "costMultiplier": 1.4 },
{ "trackClass": "c160", "minRadiusM": 900, "costMultiplier": 2.2 },
{ "trackClass": "c250", "minRadiusM": 2500, "costMultiplier": 4.0 }
],
"curveSpeedFactor": 0.65,
"costs": {
"basePerMeter": 1200,
"natural": 1.0,
"embankmentPerM": 0.25,
"cuttingPerM": 0.35,
"bridgeBase": 6.0,
"bridgePerM": 0.5,
"tunnel": 12.0,
"terrainModifiers": { "rock": 1.8, "marsh": 1.6, "mountain": 1.4, "forest": 1.15 },
"land": { "basePerCell": 20000, "nearTownKm": 2.0, "nearTownMultiplier": 3.0, "fieldMultiplier": 2.0 },
"doubleTrackMultiplier": 1.8,
"electrificationExtra": 0.35,
"stationBase": 4000000,
"stationPerPlatform": 1500000,
"depotBySize": { "small": 6000000, "medium": 12000000, "large": 24000000 },
"demolitionRefund": 0.1
},
"crews": {
"metersPerDay": { "natural": 200, "embankment": 60, "cutting": 60, "bridge": 20, "tunnel": 8 },
"crewsByTier": [ 2, 4, 8, 12, 20 ],
"upgradeClosure": true
},
"rules": {
"forbidTownFootprint": true,
"forbidIndustryFootprint": true,
"forbidForeignStations": true,
"foreignCrossingNeedsOverpass": true,
"overpassClearanceM": 7
},
"trackWear": {
"k": 400000,
"gradientWeight": 8,
"speedWeight": 0.4,
"maintenanceDriftPerDay": 0.02,
"maintenanceCostPerKmPerDay": 400,
"limitBelow60": 0.6,
"limitBelow30": 0.3,
"failureChanceBelow30": 0.002,
"renewalCostShare": 0.4,
"renewalDaysPerKm": 3
},
"structures": {
"inspectionCostShare": 0.01,
"inspectionIntervalDays": 360,
"renewalYears": 50,
"missedInspectionWearPerDay": 0.03,
"speedLimitBelow": 50,
"speedLimitFactor": 0.5,
"closeBelow": 15,
"closedSpeedFactor": 0.1,
"agingYearsToZero": 10
},
"stations": {
"catchmentKm": 2.0,
"areaRadiusM": 120,
"maxPlatforms": 8,
"snapM": 60,
"freightUnitsPerMinutePerWagon": 5.0,
"paxPerMinutePerCoach": 30,
"minDwellMinutes": 3,
"upkeepPerPlatformPerYear": 60000,
"depotUpkeepPerYear": { "small": 120000, "medium": 240000, "large": 480000 }
},
"operations": {
"maxVehiclesPerTrain": 24,
"maxTurnDeg": 100,
"lookaheadMarginM": 60,
"waitWarningDays": 20,
"defaultMaxWaitDays": 2,
"lineRunTimeMargin": 1.15,
"defaultLineSpeedKmh": 60
},
"physics": {
"gravity": 9.81,
"adhesion": 1.0,
"adhesionFactor": 0.3,
"rollingResistance": 0.0015,
"aeroCoefficient": 0.6,
"cxByKind": { "locomotive": 6.0, "wagon": 1.5, "coach": 1.8 },
"brakingMs2": 0.5,
"stallSpeedKmh": 1.0,
"stallSeconds": 120,
"passengerMassT": 0.08
}
}
+27
View File
@@ -0,0 +1,27 @@
{
"$schema": "schema/contracts.schema.json",
"version": 1,
"generation": { "perYear": 3, "maxOpen": 6, "expoEveryYears": 12 },
"templates": [
{ "id": "connect_towns", "kind": "connect", "name_it": "Collegamento tra città",
"text_it": "Collega {a} a {b} entro il {deadline} con un tempo di viaggio inferiore a {minutes} minuti",
"durationYears": [ 3, 8 ], "maxMinutes": [ 60, 150 ], "reward": 20000000, "prestige": 10, "penalty": 5000000, "minYear": 1850 },
{ "id": "deliver_goods", "kind": "deliver", "name_it": "Fornitura straordinaria",
"text_it": "Trasporta {qty} {unit} di {good} a {b} prima del {deadline}",
"durationYears": [ 1, 3 ], "quantity": [ 5000, 50000 ], "reward": 15000000, "prestige": 6, "penalty": 3000000, "minYear": 1850 },
{ "id": "great_tunnel", "kind": "greatWork", "name_it": "Traforo",
"text_it": "Traforo di {length} km tra {a} e {b} entro il {deadline}",
"durationYears": [ 6, 10 ], "lengthKm": [ 4, 12 ], "reward": 120000000, "prestige": 50, "penalty": 30000000, "minYear": 1870 },
{ "id": "great_bridge", "kind": "greatWork", "name_it": "Grande ponte",
"text_it": "Ponte di almeno {length} m su {river} entro il {deadline}",
"durationYears": [ 4, 8 ], "lengthKm": [ 0.3, 1.2 ], "reward": 60000000, "prestige": 30, "penalty": 15000000, "minYear": 1870 },
{ "id": "service_obligation", "kind": "service", "name_it": "Servizio pubblico",
"text_it": "Garantisci {qty} posti al giorno tra {a} e {b} per {years} anni",
"durationYears": [ 2, 5 ], "quantity": [ 100, 600 ], "reward": 8000000, "prestige": 5, "penalty": 4000000, "minYear": 1850 }
],
"expositions": [
{ "id": "fastest_line", "name_it": "Linea più veloce", "reward": 30000000, "prestige": 25 },
{ "id": "longest_bridge", "name_it": "Ponte più lungo", "reward": 20000000, "prestige": 20 },
{ "id": "largest_station", "name_it": "Stazione più grande", "reward": 15000000, "prestige": 15 }
]
}
+32
View File
@@ -0,0 +1,32 @@
{
"$schema": "schema/difficulty.schema.json",
"version": 1,
"default": "imprenditore",
"depletionMultipliers": { "slow": 0.5, "normal": 1.0, "fast": 1.6 },
"presets": [
{ "id": "apprendista", "name_it": "Apprendista", "name_en": "Apprentice",
"initialCapital": 50000000, "initialCredit": 50000000, "baseInterestRate": 0.03,
"constructionCostMultiplier": 0.8, "tariffMultiplier": 1.15, "wearMultiplier": 0.7, "marketVolatilityMultiplier": 0.6,
"aiCompetitors": 1, "aiCapitalMultiplier": 0.7, "aiCostDiscount": 0.0,
"playerTakeover": "disabled", "takeoverRansomYears": 0, "bankruptcyDays": 180,
"publicFromStart": false, "playerShareAtStart": 1.0, "ironman": "no", "depletion": "slow" },
{ "id": "imprenditore", "name_it": "Imprenditore", "name_en": "Entrepreneur",
"initialCapital": 25000000, "initialCredit": 30000000, "baseInterestRate": 0.05,
"constructionCostMultiplier": 1.0, "tariffMultiplier": 1.0, "wearMultiplier": 1.0, "marketVolatilityMultiplier": 1.0,
"aiCompetitors": 2, "aiCapitalMultiplier": 1.0, "aiCostDiscount": 0.0,
"playerTakeover": "ransom", "takeoverRansomYears": 3, "bankruptcyDays": 90,
"publicFromStart": false, "playerShareAtStart": 1.0, "ironman": "optional", "depletion": "normal" },
{ "id": "magnate", "name_it": "Magnate", "name_en": "Tycoon",
"initialCapital": 15000000, "initialCredit": 15000000, "baseInterestRate": 0.07,
"constructionCostMultiplier": 1.25, "tariffMultiplier": 0.9, "wearMultiplier": 1.3, "marketVolatilityMultiplier": 1.3,
"aiCompetitors": 3, "aiCapitalMultiplier": 1.5, "aiCostDiscount": 0.10,
"playerTakeover": "ransom", "takeoverRansomYears": 1, "bankruptcyDays": 60,
"publicFromStart": false, "playerShareAtStart": 1.0, "ironman": "optional", "depletion": "fast" },
{ "id": "ferro_e_sangue", "name_it": "Ferro e sangue", "name_en": "Iron and blood",
"initialCapital": 10000000, "initialCredit": 10000000, "baseInterestRate": 0.09,
"constructionCostMultiplier": 1.5, "tariffMultiplier": 0.8, "wearMultiplier": 1.6, "marketVolatilityMultiplier": 1.6,
"aiCompetitors": 5, "aiCapitalMultiplier": 2.0, "aiCostDiscount": 0.20,
"playerTakeover": "immediate", "takeoverRansomYears": 0, "bankruptcyDays": 30,
"publicFromStart": true, "playerShareAtStart": 0.6, "ironman": "yes", "depletion": "fast" }
]
}
+39
View File
@@ -0,0 +1,39 @@
{
"$schema": "schema/eras.schema.json",
"version": 1,
"eras": [
{ "id": "steam", "name_it": "Era del vapore", "name_en": "Steam era", "from": 1850 },
{ "id": "diesel", "name_it": "Era diesel", "name_en": "Diesel era", "from": 1925 },
{ "id": "electric", "name_it": "Era elettrica", "name_en": "Electric era", "from": 1950 },
{ "id": "highspeed", "name_it": "Alta velocità", "name_en": "High speed", "from": 1990 }
],
"tractions": [
{ "id": "steam", "name_it": "Vapore", "from": 1850, "needsElectrification": false },
{ "id": "diesel", "name_it": "Diesel", "from": 1925, "needsElectrification": false },
{ "id": "electric", "name_it": "Elettrica", "from": 1950, "needsElectrification": true },
{ "id": "highspeed", "name_it": "Alta velocità", "from": 1990, "needsElectrification": true }
],
"bridgeTypes": [
{ "id": "wood", "name_it": "Legno", "from": 1850, "maxSpanM": 60, "costMultiplier": 1.0, "lifeYears": 40 },
{ "id": "iron", "name_it": "Ferro", "from": 1870, "maxSpanM": 150, "costMultiplier": 1.25, "lifeYears": 50 },
{ "id": "steel", "name_it": "Acciaio", "from": 1900, "maxSpanM": 400, "costMultiplier": 1.5, "lifeYears": 60 },
{ "id": "concrete", "name_it": "Cemento armato", "from": 1950, "maxSpanM": 800, "costMultiplier": 1.4, "lifeYears": 70 }
],
"tunnelLimits": [
{ "from": 1850, "maxLengthM": 1000 },
{ "from": 1900, "maxLengthM": 5000 },
{ "from": 1950, "maxLengthM": 15000 }
],
"trackClasses": [
{ "id": "c60", "name_it": "Ordinario 60 km/h", "speedKmh": 60, "from": 1850 },
{ "id": "c100", "name_it": "Rinforzato 100 km/h", "speedKmh": 100, "from": 1875 },
{ "id": "c160", "name_it": "Direttissimo 160 km/h", "speedKmh": 160, "from": 1935 },
{ "id": "c250", "name_it": "Alta velocità 250 km/h", "speedKmh": 250, "from": 1990 }
],
"signals": [
{ "id": "semaphore", "name_it": "Semaforo ad ala", "from": 1850, "price": 80000 },
{ "id": "light", "name_it": "Segnale luminoso", "from": 1930, "price": 150000 },
{ "id": "cab", "name_it": "Segnalamento in cabina", "from": 1990, "price": 400000 }
],
"electrificationFrom": 1950
}
+45
View File
@@ -0,0 +1,45 @@
{
"$schema": "schema/goods.schema.json",
"version": 1,
"goods": [
{ "id": "coal", "name_it": "Carbone", "name_en": "Coal", "category": "bulk", "unit": "t", "wagon": "hopper",
"basePrice": 3800, "elasticity": 0.6, "decayDaysAtStation": 60, "era": 1850,
"town": { "category": "fuel", "demandPerThousand": 0.12, "untilYear": 1960 } },
{ "id": "iron_ore", "name_it": "Minerale di ferro", "name_en": "Iron ore", "category": "bulk", "unit": "t", "wagon": "hopper",
"basePrice": 4200, "elasticity": 0.5, "decayDaysAtStation": 90, "era": 1850 },
{ "id": "stone", "name_it": "Pietra", "name_en": "Stone", "category": "bulk", "unit": "t", "wagon": "hopper",
"basePrice": 2500, "elasticity": 0.4, "decayDaysAtStation": 120, "era": 1850 },
{ "id": "crude_oil", "name_it": "Petrolio", "name_en": "Crude oil", "category": "liquid", "unit": "t", "wagon": "tank",
"basePrice": 6500, "elasticity": 0.7, "decayDaysAtStation": 60, "era": 1860 },
{ "id": "logs", "name_it": "Tronchi", "name_en": "Logs", "category": "bulk", "unit": "t", "wagon": "flat",
"basePrice": 3000, "elasticity": 0.5, "decayDaysAtStation": 45, "era": 1850 },
{ "id": "grain", "name_it": "Grano", "name_en": "Grain", "category": "bulk", "unit": "t", "wagon": "hopper",
"basePrice": 5000, "elasticity": 0.6, "decayDaysAtStation": 30, "era": 1850 },
{ "id": "livestock", "name_it": "Bestiame", "name_en": "Livestock", "category": "perishable", "unit": "capi", "wagon": "box",
"basePrice": 9000, "elasticity": 0.7, "decayDaysAtStation": 8, "era": 1850 },
{ "id": "lumber", "name_it": "Legname", "name_en": "Lumber", "category": "general", "unit": "t", "wagon": "flat",
"basePrice": 8000, "elasticity": 0.6, "decayDaysAtStation": 90, "era": 1850,
"town": { "category": "construction", "demandPerThousand": 0.10 } },
{ "id": "steel", "name_it": "Acciaio", "name_en": "Steel", "category": "general", "unit": "t", "wagon": "flat",
"basePrice": 16000, "elasticity": 0.8, "decayDaysAtStation": 120, "era": 1850 },
{ "id": "food", "name_it": "Alimentari", "name_en": "Food", "category": "perishable", "unit": "t", "wagon": "box",
"basePrice": 12000, "elasticity": 0.3, "decayDaysAtStation": 10, "era": 1850,
"town": { "category": "food", "demandPerThousand": 0.45 } },
{ "id": "fuel", "name_it": "Carburante", "name_en": "Fuel", "category": "liquid", "unit": "t", "wagon": "tank",
"basePrice": 16000, "elasticity": 0.5, "decayDaysAtStation": 90, "era": 1870,
"town": { "category": "fuel", "demandPerThousand": 0.12 } },
{ "id": "building_materials", "name_it": "Materiali edili", "name_en": "Building materials", "category": "general", "unit": "t", "wagon": "flat",
"basePrice": 6000, "elasticity": 0.7, "decayDaysAtStation": 120, "era": 1850,
"town": { "category": "construction", "demandPerThousand": 0.18 } },
{ "id": "tools", "name_it": "Attrezzi", "name_en": "Tools", "category": "general", "unit": "casse", "wagon": "box",
"basePrice": 22000, "elasticity": 0.8, "decayDaysAtStation": 120, "era": 1850,
"town": { "category": "goods", "demandPerThousand": 0.06 } },
{ "id": "goods", "name_it": "Merci varie", "name_en": "Goods", "category": "general", "unit": "casse", "wagon": "box",
"basePrice": 20000, "elasticity": 0.9, "decayDaysAtStation": 60, "era": 1850,
"town": { "category": "goods", "demandPerThousand": 0.20 } },
{ "id": "machinery", "name_it": "Macchinari", "name_en": "Machinery", "category": "general", "unit": "pz", "wagon": "flat",
"basePrice": 45000, "elasticity": 0.6, "decayDaysAtStation": 180, "era": 1850, "service": true },
{ "id": "spare_parts", "name_it": "Ricambi", "name_en": "Spare parts", "category": "general", "unit": "casse", "wagon": "box",
"basePrice": 30000, "elasticity": 0.5, "decayDaysAtStation": 180, "era": 1850, "service": true }
]
}
+90
View File
@@ -0,0 +1,90 @@
{
"$schema": "schema/industries.schema.json",
"version": 1,
"industries": [
{ "id": "coal_mine", "name_it": "Miniera di carbone", "name_en": "Coal mine", "kind": "primary",
"recipe": { "inputs": [], "outputs": [ { "good": "coal", "perCycle": 1 } ] },
"cycleDays": 1, "capacityPerLevel": [150, 300, 500, 800, 1200], "workersPerLevel": [30, 60, 120, 200, 300], "staffPerLevel": [1, 3, 6, 10, 16],
"storageDays": 30, "wearIntensity": 1.3, "footprint": "medium",
"placement": { "needs": "deposit", "resource": "coal", "minTownDistanceKm": 2 },
"depletable": true, "era": 1850, "upgradeCost": 1500000, "spawnWeight": 1.0 },
{ "id": "iron_mine", "name_it": "Miniera di ferro", "name_en": "Iron mine", "kind": "primary",
"recipe": { "inputs": [], "outputs": [ { "good": "iron_ore", "perCycle": 1 } ] },
"cycleDays": 1, "capacityPerLevel": [150, 300, 500, 800, 1200], "workersPerLevel": [30, 60, 120, 200, 300], "staffPerLevel": [1, 3, 6, 10, 16],
"storageDays": 30, "wearIntensity": 1.3, "footprint": "medium",
"placement": { "needs": "deposit", "resource": "iron", "minTownDistanceKm": 2 },
"depletable": true, "era": 1850, "upgradeCost": 1500000, "spawnWeight": 1.0 },
{ "id": "quarry", "name_it": "Cava di pietra", "name_en": "Stone quarry", "kind": "primary",
"recipe": { "inputs": [], "outputs": [ { "good": "stone", "perCycle": 1 } ] },
"cycleDays": 1, "capacityPerLevel": [200, 400, 650, 1000, 1500], "workersPerLevel": [20, 40, 80, 130, 200], "staffPerLevel": [1, 2, 4, 7, 10],
"storageDays": 40, "wearIntensity": 1.0, "footprint": "medium",
"placement": { "needs": "deposit", "resource": "stone", "minTownDistanceKm": 1.5 },
"depletable": true, "era": 1850, "upgradeCost": 1000000, "spawnWeight": 0.8 },
{ "id": "oil_well", "name_it": "Pozzo di petrolio", "name_en": "Oil well", "kind": "primary",
"recipe": { "inputs": [], "outputs": [ { "good": "crude_oil", "perCycle": 1 } ] },
"cycleDays": 1, "capacityPerLevel": [120, 240, 400, 650, 1000], "workersPerLevel": [15, 30, 60, 100, 150], "staffPerLevel": [2, 4, 8, 12, 18],
"storageDays": 30, "wearIntensity": 1.1, "footprint": "small",
"placement": { "needs": "deposit", "resource": "oil", "minTownDistanceKm": 2 },
"depletable": true, "era": 1860, "upgradeCost": 2000000, "spawnWeight": 0.6 },
{ "id": "logging_camp", "name_it": "Taglialegna", "name_en": "Logging camp", "kind": "primary",
"recipe": { "inputs": [], "outputs": [ { "good": "logs", "perCycle": 1 } ] },
"cycleDays": 1, "capacityPerLevel": [150, 300, 500, 750, 1100], "workersPerLevel": [20, 40, 80, 120, 180], "staffPerLevel": [0, 1, 2, 4, 6],
"storageDays": 30, "wearIntensity": 0.8, "footprint": "medium",
"placement": { "needs": "forest", "minTownDistanceKm": 2 },
"depletable": false, "era": 1850, "upgradeCost": 800000, "spawnWeight": 1.0 },
{ "id": "farm", "name_it": "Fattoria", "name_en": "Farm", "kind": "primary",
"recipe": { "inputs": [], "outputs": [ { "good": "grain", "perCycle": 2 }, { "good": "livestock", "perCycle": 1 } ] },
"cycleDays": 1, "capacityPerLevel": [160, 320, 520, 800, 1200], "workersPerLevel": [15, 30, 60, 100, 150], "staffPerLevel": [0, 1, 2, 3, 5],
"storageDays": 20, "wearIntensity": 0.6, "footprint": "large",
"placement": { "needs": "plain", "minTownDistanceKm": 2, "maxTownDistanceKm": 10 },
"depletable": false, "era": 1850, "upgradeCost": 600000, "spawnWeight": 1.4 },
{ "id": "sawmill", "name_it": "Segheria", "name_en": "Sawmill", "kind": "processing",
"recipe": { "inputs": [ { "good": "logs", "perCycle": 2 } ], "outputs": [ { "good": "lumber", "perCycle": 1 } ] },
"cycleDays": 1, "capacityPerLevel": [100, 200, 340, 520, 780], "workersPerLevel": [20, 40, 80, 130, 190], "staffPerLevel": [1, 2, 5, 8, 12],
"storageDays": 30, "wearIntensity": 1.0, "footprint": "medium",
"placement": { "needs": "any", "minTownDistanceKm": 2, "maxTownDistanceKm": 12, "maxInputDistanceKm": 12 },
"depletable": false, "era": 1850, "upgradeCost": 1200000, "spawnWeight": 0.9 },
{ "id": "steel_mill", "name_it": "Acciaieria", "name_en": "Steel mill", "kind": "processing",
"recipe": { "inputs": [ { "good": "iron_ore", "perCycle": 2 }, { "good": "coal", "perCycle": 1 } ], "outputs": [ { "good": "steel", "perCycle": 1 } ] },
"cycleDays": 1, "capacityPerLevel": [120, 240, 400, 600, 900], "workersPerLevel": [40, 80, 160, 240, 320], "staffPerLevel": [2, 6, 12, 20, 30],
"storageDays": 30, "wearIntensity": 1.2, "footprint": "large",
"placement": { "needs": "any", "minTownDistanceKm": 2, "maxTownDistanceKm": 12, "maxInputDistanceKm": 12 },
"depletable": false, "era": 1850, "upgradeCost": 3000000, "spawnWeight": 0.7 },
{ "id": "food_plant", "name_it": "Industria alimentare", "name_en": "Food plant", "kind": "processing",
"recipe": { "inputs": [ { "good": "grain", "perCycle": 2 }, { "good": "livestock", "perCycle": 1 } ], "outputs": [ { "good": "food", "perCycle": 2 } ] },
"cycleDays": 1, "capacityPerLevel": [150, 300, 500, 760, 1100], "workersPerLevel": [30, 60, 110, 170, 240], "staffPerLevel": [1, 3, 6, 10, 15],
"storageDays": 15, "wearIntensity": 0.9, "footprint": "medium",
"placement": { "needs": "any", "minTownDistanceKm": 2, "maxTownDistanceKm": 12, "maxInputDistanceKm": 12 },
"depletable": false, "era": 1850, "upgradeCost": 1500000, "spawnWeight": 1.0 },
{ "id": "refinery", "name_it": "Raffineria", "name_en": "Refinery", "kind": "processing",
"recipe": { "inputs": [ { "good": "crude_oil", "perCycle": 2 } ], "outputs": [ { "good": "fuel", "perCycle": 1 } ] },
"cycleDays": 1, "capacityPerLevel": [100, 200, 340, 520, 800], "workersPerLevel": [30, 60, 110, 170, 240], "staffPerLevel": [3, 6, 12, 20, 30],
"storageDays": 30, "wearIntensity": 1.4, "footprint": "large",
"placement": { "needs": "any", "minTownDistanceKm": 3, "maxTownDistanceKm": 12, "maxInputDistanceKm": 12 },
"depletable": false, "era": 1870, "upgradeCost": 3500000, "spawnWeight": 0.5 },
{ "id": "brickworks", "name_it": "Fornace di laterizi", "name_en": "Brickworks", "kind": "processing",
"recipe": { "inputs": [ { "good": "stone", "perCycle": 2 }, { "good": "coal", "perCycle": 1 } ], "outputs": [ { "good": "building_materials", "perCycle": 2 } ] },
"cycleDays": 1, "capacityPerLevel": [140, 280, 460, 700, 1000], "workersPerLevel": [25, 50, 90, 140, 200], "staffPerLevel": [1, 2, 4, 7, 10],
"storageDays": 40, "wearIntensity": 1.1, "footprint": "medium",
"placement": { "needs": "any", "minTownDistanceKm": 2, "maxTownDistanceKm": 12, "maxInputDistanceKm": 12 },
"depletable": false, "era": 1850, "upgradeCost": 1000000, "spawnWeight": 0.8 },
{ "id": "tool_factory", "name_it": "Fabbrica di attrezzi", "name_en": "Tool factory", "kind": "manufacturing",
"recipe": { "inputs": [ { "good": "steel", "perCycle": 2 }, { "good": "coal", "perCycle": 1 } ], "outputs": [ { "good": "tools", "perCycle": 2 } ] },
"cycleDays": 1, "capacityPerLevel": [60, 120, 200, 300, 450], "workersPerLevel": [30, 60, 110, 170, 240], "staffPerLevel": [3, 6, 12, 18, 26],
"storageDays": 30, "wearIntensity": 1.0, "footprint": "medium",
"placement": { "needs": "town", "maxTownDistanceKm": 2.5 },
"depletable": false, "era": 1850, "upgradeCost": 2000000, "spawnWeight": 0.6 },
{ "id": "goods_factory", "name_it": "Manifattura", "name_en": "Goods factory", "kind": "manufacturing",
"recipe": { "inputs": [ { "good": "lumber", "perCycle": 2 }, { "good": "steel", "perCycle": 1 } ], "outputs": [ { "good": "goods", "perCycle": 3 } ] },
"cycleDays": 1, "capacityPerLevel": [120, 240, 400, 600, 900], "workersPerLevel": [40, 80, 150, 230, 320], "staffPerLevel": [3, 6, 12, 18, 26],
"storageDays": 30, "wearIntensity": 0.9, "footprint": "medium",
"placement": { "needs": "town", "maxTownDistanceKm": 2.5 },
"depletable": false, "era": 1850, "upgradeCost": 1800000, "spawnWeight": 0.8 },
{ "id": "machine_factory", "name_it": "Fabbrica di macchinari", "name_en": "Machine factory", "kind": "manufacturing",
"recipe": { "inputs": [ { "good": "steel", "perCycle": 2 }, { "good": "tools", "perCycle": 1 } ], "outputs": [ { "good": "machinery", "perCycle": 1 }, { "good": "spare_parts", "perCycle": 2 } ] },
"cycleDays": 1, "capacityPerLevel": [40, 80, 140, 210, 320], "workersPerLevel": [40, 80, 150, 230, 320], "staffPerLevel": [6, 12, 24, 36, 50],
"storageDays": 60, "wearIntensity": 1.0, "footprint": "large",
"placement": { "needs": "town", "maxTownDistanceKm": 2.5, "minTownPopulation": 4000 },
"depletable": false, "era": 1850, "upgradeCost": 4000000, "spawnWeight": 0.4 }
]
}
+91
View File
@@ -0,0 +1,91 @@
{
"$schema": "schema/maintenance.schema.json",
"version": 1,
"components": {
"locomotive": [
{ "id": "engine", "name_it": "Motore o caldaia", "failureWeight": 0.40, "wearPer100Km": 0.25 },
{ "id": "wheelsets", "name_it": "Rodiggio e assali", "failureWeight": 0.25, "wearPer100Km": 0.20 },
{ "id": "brakes", "name_it": "Freni", "failureWeight": 0.20, "wearPer100Km": 0.35 },
{ "id": "electrics", "name_it": "Impianto elettrico o trasmissione", "failureWeight": 0.15, "wearPer100Km": 0.15 }
],
"car": [
{ "id": "axles", "name_it": "Assali", "failureWeight": 0.5, "wearPer100Km": 0.15 },
{ "id": "brakes", "name_it": "Freni", "failureWeight": 0.3, "wearPer100Km": 0.30 },
{ "id": "body", "name_it": "Cassa", "failureWeight": 0.2, "wearPer100Km": 0.08 }
]
},
"wear": {
"gradientThreshold": 0.015,
"gradientWeight": 2.0,
"highSpeedThreshold": 0.8,
"highSpeedWeight": 0.5,
"loadWeight": 0.3,
"ageStepYears": 5,
"ageStepFactor": 0.5,
"distanceScale": 30
},
"failure": {
"h0": 0.002,
"slope": 0.8,
"pivot": 50,
"scale": 10,
"healthyDivisor": 4,
"minorShare": 0.70,
"majorShare": 0.27,
"catastrophicShare": 0.03,
"catastrophicMaxCondition": 15,
"catastrophicMinSpeedShare": 0.8,
"minorSpeedFactor": 0.5,
"rescueSpeedKmh": 40,
"rescueExtraHours": 2,
"derailmentTrackDays": 3,
"derailmentSatisfaction": 0.05
},
"effects": {
"engineSpeedBelow": 70,
"engineSpeedBase": 0.6,
"engineSpeedSpan": 0.4,
"fuelPenalty": 0.4,
"comfortMin": 0.8,
"comfortMax": 1.05
},
"interventions": [
{ "id": "inspection", "name_it": "Ispezione", "days": 1, "costShare": 0.005, "spareParts": 0, "effect": "inspection" },
{ "id": "service", "name_it": "Tagliando", "days": 3, "costShare": 0.03, "spareParts": 1, "effect": "service" },
{ "id": "overhaul", "name_it": "Revisione generale", "days": 20, "costShare": 0.25, "spareParts": 5, "effect": "overhaul" },
{ "id": "repair_minor", "name_it": "Riparazione dopo guasto lieve", "days": 2, "costShare": 0.05, "spareParts": 1, "effect": "repair", "restoreTo": 80 },
{ "id": "repair_major", "name_it": "Riparazione dopo guasto grave", "days": 7, "costShare": 0.15, "spareParts": 3, "effect": "repair", "restoreTo": 90 },
{ "id": "repair_catastrophic", "name_it": "Ricostruzione dopo deragliamento", "days": 30, "costShare": 0.40, "spareParts": 8, "effect": "replace" }
],
"inspection": { "brakesTo": 100, "othersPlus": 10, "hazardFactor": 0.5, "hazardDays": 30 },
"service": { "plus": 40 },
"overhaul": { "ageFactorReduction": 0.5 },
"depots": {
"stallsBySize": { "small": 2, "medium": 4, "large": 8 },
"staffPerStall": 4,
"slowdownAtHalfStaff": 2.0,
"initialSpareParts": 10,
"jobsWorkersPerStall": 6,
"targetSpareParts": 40,
"maxSpareParts": 400
},
"policies": [
{ "id": "economy", "name_it": "Economica", "intervalFactor": 1.5, "effectFactor": 0.7, "costFactor": 0.6 },
{ "id": "standard", "name_it": "Standard", "intervalFactor": 1.0, "effectFactor": 1.0, "costFactor": 1.0 },
{ "id": "thorough", "name_it": "Accurata", "intervalFactor": 0.7, "effectFactor": 1.2, "costFactor": 1.6 }
],
"intervals": {
"inspectionKm": 3000, "inspectionDays": 45,
"serviceKm": 15000, "serviceDays": 180,
"overhaulYears": 6
},
"planner": {
"targetCondition": 40,
"averageDays": 15,
"marginDays": 5,
"alertCondition": 40,
"criticalCondition": 30,
"reserveMinDays": 5,
"historyLength": 12
}
}
+39
View File
@@ -0,0 +1,39 @@
{
"$schema": "schema/regions.schema.json",
"version": 1,
"concessions": { "unlockTier": 3, "basePrice": 200000000, "priceGrowth": 1.6, "maxRegions": 16 },
"regions": [
{ "id": "valdoria", "name_it": "Regione di Valdoria", "climate": "temperate", "terrainDifficulty": 1.0,
"resources": { "coal": 1.0, "iron": 1.0, "stone": 1.0, "oil": 0.6 }, "hubs": [ "port", "border" ], "namePool": "padana" },
{ "id": "alpi", "name_it": "Alte Valli", "climate": "alpine", "terrainDifficulty": 1.8,
"resources": { "coal": 0.6, "iron": 1.6, "stone": 1.4, "oil": 0.0 }, "hubs": [ "border" ], "namePool": "alpina" },
{ "id": "litorale", "name_it": "Litorale", "climate": "coastal", "terrainDifficulty": 0.7,
"resources": { "coal": 0.3, "iron": 0.4, "stone": 0.8, "oil": 1.4 }, "hubs": [ "port" ], "namePool": "costiera" },
{ "id": "meridione", "name_it": "Terre del Sole", "climate": "dry", "terrainDifficulty": 1.2,
"resources": { "coal": 0.4, "iron": 0.8, "stone": 1.6, "oil": 1.0 }, "hubs": [ "port" ], "namePool": "meridionale" }
],
"namePools": [
{ "id": "padana",
"prefixes": [ "Borgo ", "Villa ", "San ", "Sant'", "Castel ", "Ponte ", "Porto ", "Rocca ", "Corte ", "" ],
"roots": [ "Vald", "Mont", "Cer", "Ros", "Alb", "Fior", "Bel", "Lov", "Cas", "Ser", "Tor", "Pall", "Ard", "Ven", "Mar", "Lun", "Gav", "Brem", "Ost", "Coll" ],
"suffixes": [ "oria", "alto", "esio", "ello", "ano", "enza", "ate", "ona", "ino", "ara", "ago", "edo", "ica", "ia" ],
"saints": [ "Elia", "Ambrogio", "Giorgio", "Martino", "Anna", "Michele", "Ilario", "Agata" ] },
{ "id": "alpina",
"prefixes": [ "Pian ", "Val ", "Passo ", "Malga ", "" ],
"roots": [ "Cort", "Bren", "Auron", "Sest", "Livin", "Chiav", "Bor", "Tirn", "Ponte", "Mezz" ],
"suffixes": [ "ina", "egno", "ago", "olo", "ena", "ola", "io" ],
"saints": [ "Bernardo", "Maurizio", "Vigilio" ] },
{ "id": "costiera",
"prefixes": [ "Marina di ", "Lido ", "Porto ", "Capo ", "" ],
"roots": [ "Sal", "Ancor", "Fan", "Ortom", "Ves", "Rimin", "Senig", "Caor" ],
"suffixes": [ "ona", "ese", "ara", "allia", "ino", "ole" ],
"saints": [ "Nicola", "Benedetto", "Elpidio" ] },
{ "id": "meridionale",
"prefixes": [ "Torre ", "Monte ", "Casal ", "San ", "" ],
"roots": [ "Mel", "Trap", "Agrig", "Lent", "Calt", "Pac", "Nis", "Gel", "Ragus" ],
"suffixes": [ "fi", "ani", "ento", "ini", "anissetta", "ino", "emi", "a" ],
"saints": [ "Vito", "Calogero", "Rosalia" ] }
],
"industryNameTemplates": [ "{type} {town}", "{type} di {town}", "{type} {feature}" ],
"featureNames": [ "Bosco Alto", "Rocca Bruna", "Piana Verde", "Val Fonda", "Colle Rosso", "Prato Lungo", "Sasso Nero", "Fontana Fredda" ]
}
+103
View File
@@ -0,0 +1,103 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Concorrenti IA (ai.json)",
"type": "object",
"properties": {
"$schema": {
"type": "string"
},
"version": {
"type": "integer",
"minimum": 1
},
"planning": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"personalities": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "string",
"pattern": "^[a-z][a-z0-9_]*$"
},
"name_it": {
"type": "string",
"minLength": 1
},
"roiThreshold": {
"type": "number",
"minimum": 0,
"maximum": 1
},
"loanShareOfCredit": {
"type": "number",
"minimum": 0,
"maximum": 1
},
"targetsPlayer": {
"type": "boolean"
},
"buysShares": {
"type": "boolean"
},
"maintenancePolicy": {
"type": "string",
"enum": [
"economy",
"standard",
"thorough"
]
}
},
"required": [
"id",
"name_it",
"roiThreshold",
"loanShareOfCredit",
"targetsPlayer",
"buysShares",
"maintenancePolicy"
],
"additionalProperties": false
},
"minItems": 3
},
"companyNames": {
"type": "array",
"items": {
"type": "string",
"minLength": 1
},
"minItems": 4,
"uniqueItems": true
},
"colors": {
"type": "array",
"items": {
"type": "string",
"pattern": "^#[0-9a-fA-F]{6}$"
},
"minItems": 1
}
},
"required": [
"version",
"planning",
"personalities",
"companyNames",
"colors"
],
"additionalProperties": false
}
+462
View File
@@ -0,0 +1,462 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Bilanciamento (balance.json)",
"type": "object",
"properties": {
"$schema": {
"type": "string"
},
"version": {
"type": "integer",
"minimum": 1
},
"time": {
"type": "object",
"properties": {
"tickMs": {
"type": "integer",
"minimum": 1
},
"ticksPerDay": {
"type": "integer",
"minimum": 1
},
"daysPerMonth": {
"type": "integer",
"minimum": 1
},
"monthsPerYear": {
"type": "integer",
"minimum": 1
},
"trainClockFactor": {
"type": "number",
"minimum": 1
},
"speeds": {
"type": "array",
"items": {
"type": "integer",
"minimum": 0,
"maximum": 64
},
"minItems": 1
},
"defaultStartYear": {
"type": "integer",
"minimum": 1800,
"maximum": 2300
}
},
"required": [
"tickMs",
"ticksPerDay",
"daysPerMonth",
"monthsPerYear",
"trainClockFactor",
"speeds",
"defaultStartYear"
],
"additionalProperties": false
},
"map": {
"type": "object",
"properties": {
"cellSizeM": {
"type": "number",
"minimum": 1
},
"sizesKm": {
"type": "array",
"items": {
"type": "integer",
"minimum": 8,
"maximum": 1024
},
"minItems": 1
},
"chunkCells": {
"type": "integer",
"minimum": 8,
"maximum": 256
},
"maxElevationM": {
"type": "number",
"minimum": 100
},
"noise": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"relief": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"hydrology": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"cover": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"deposits": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"towns": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"industries": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"hubs": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
}
},
"required": [
"cellSizeM",
"sizesKm",
"chunkCells",
"maxElevationM",
"noise",
"relief",
"hydrology",
"cover",
"deposits",
"towns",
"industries",
"hubs"
],
"additionalProperties": false
},
"market": {
"type": "object",
"properties": {
"k": {
"type": "number",
"minimum": 0,
"maximum": 1
},
"alpha": {
"type": "number",
"minimum": 0,
"maximum": 1
},
"windowDays": {
"type": "integer",
"minimum": 1
},
"minPriceFactor": {
"type": "number",
"minimum": 0,
"maximum": 1
},
"maxPriceFactor": {
"type": "number",
"minimum": 1
},
"ratioMin": {
"type": "number",
"minimum": 0,
"maximum": 1
},
"ratioMax": {
"type": "number",
"minimum": 1
},
"world": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"historyDays": {
"type": "integer",
"minimum": 1
}
},
"required": [
"k",
"alpha",
"windowDays",
"minPriceFactor",
"maxPriceFactor",
"ratioMin",
"ratioMax",
"world",
"historyDays"
],
"additionalProperties": false
},
"localPrice": {
"type": "object",
"properties": {
"lambda": {
"type": "number",
"minimum": 0,
"maximum": 1
},
"maxDeviation": {
"type": "number",
"minimum": 0,
"maximum": 1
},
"epsilon": {
"type": "number",
"minimum": 0
}
},
"required": [
"lambda",
"maxDeviation",
"epsilon"
],
"additionalProperties": false
},
"industry": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"growth": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"town": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"migration": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"employment": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"localTransport": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"hubs": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"tariffs": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"finance": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"stockMarket": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"industryMaintenance": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
}
},
"required": [
"version",
"time",
"map",
"market",
"localPrice",
"industry",
"growth",
"town",
"migration",
"employment",
"localTransport",
"hubs",
"tariffs",
"finance",
"stockMarket",
"industryMaintenance"
],
"additionalProperties": false
}
+211
View File
@@ -0,0 +1,211 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Costruzione (construction.json)",
"type": "object",
"properties": {
"$schema": {
"type": "string"
},
"version": {
"type": "integer",
"minimum": 1
},
"profile": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"maxGradientByTraction": {
"type": "object",
"properties": {
"steam": {
"type": "number",
"minimum": 0.001,
"maximum": 0.2
},
"diesel": {
"type": "number",
"minimum": 0.001,
"maximum": 0.2
},
"electric": {
"type": "number",
"minimum": 0.001,
"maximum": 0.2
},
"highspeed": {
"type": "number",
"minimum": 0.001,
"maximum": 0.2
}
},
"required": [
"steam",
"diesel",
"electric",
"highspeed"
],
"additionalProperties": false
},
"speedClasses": {
"type": "array",
"items": {
"type": "object",
"properties": {
"trackClass": {
"type": "string",
"pattern": "^[a-z][a-z0-9_]*$"
},
"minRadiusM": {
"type": "number",
"minimum": 1
},
"costMultiplier": {
"type": "number",
"minimum": 0.1
}
},
"required": [
"trackClass",
"minRadiusM",
"costMultiplier"
],
"additionalProperties": false
},
"minItems": 1
},
"curveSpeedFactor": {
"type": "number",
"minimum": 0,
"maximum": 2
},
"costs": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"crews": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"rules": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"trackWear": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"structures": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"physics": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"stations": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
},
"operations": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean",
"array",
"object",
"string"
]
}
}
},
"required": [
"version",
"profile",
"maxGradientByTraction",
"speedClasses",
"curveSpeedFactor",
"costs",
"crews",
"rules",
"trackWear",
"structures",
"physics",
"stations",
"operations"
],
"additionalProperties": false
}
Loaded 100 of 304 files, more files were not shown because too many files have changed in this diff. Show more