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

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

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

No files matched your search

@@ -0,0 +1,267 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Core.Map;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
namespace ViaFerrea.Client.Map;
/// <summary>
/// Entità sulla mappa (immagine 04): case con tetti in coppi sulle celle d'abitato, impronte
/// delle industrie per tipo, stazioni con marciapiedi e fabbricato, depositi, porto e valico;
/// alberi delle foreste con MultiMeshInstance2D per chunk.
/// </summary>
public partial class EntityLayer : Node2D
{
private ClientWorld? _world;
private int _drawnEntities = -1;
private int _drawnTerrain = -1;
private int _drawnTrack = -1;
private float _zoom = 1;
private readonly Dictionary<(int, int), MultiMeshInstance2D> _forests = [];
private Texture2D? _treeTexture;
public int SelectedStation { get; set; } = -1;
public void Bind(ClientWorld world)
{
_world = world;
foreach (var f in _forests.Values) f.QueueFree();
_forests.Clear();
_drawnEntities = _drawnTerrain = _drawnTrack = -1;
}
public void SetZoom(float zoom)
{
bool redraw = (zoom >= MapScale.OverviewZoom) != (_zoom >= MapScale.OverviewZoom);
_zoom = zoom;
if (redraw) QueueRedraw();
foreach (var f in _forests.Values) f.Visible = zoom >= 0.02f;
}
public void ForestChunk(int cx, int cy)
{
var w = _world;
if (w?.Terrain is null) return;
_treeTexture ??= TreeTexture();
var t = w.Terrain;
var trees = new List<Transform2D>();
var colors = new List<Color>();
int x0 = cx * t.ChunkCells, y0 = cy * t.ChunkCells;
for (int y = y0; y < Math.Min(t.Height, y0 + t.ChunkCells); y++)
{
for (int x = x0; x < Math.Min(t.Width, x0 + t.ChunkCells); x++)
{
if ((CellType)t.Types[y * t.Width + x] != CellType.Forest) continue;
uint h = (uint)(x * 73856093 ^ y * 19349663);
for (int k = 0; k < 5; k++)
{
h = h * 1664525 + 1013904223;
float jx = (h & 0xFFFF) / 65535f, jy = (h >> 16) / 65535f;
float r = (float)t.CellSizeM * (0.16f + 0.08f * ((h >> 8) & 7) / 7f);
var pos = new Vector2((float)((x + jx) * t.CellSizeM), (float)((y + jy) * t.CellSizeM));
trees.Add(new Transform2D(0, new Vector2(r * 2, r * 2), 0, pos));
colors.Add(Palette.Canopy.Lerp(new Color("7aa65a"), ((h >> 4) & 15) / 15f));
}
}
}
if (_forests.Remove((cx, cy), out var old)) old.QueueFree();
if (trees.Count == 0) return;
var mesh = new MultiMesh
{
TransformFormat = MultiMesh.TransformFormatEnum.Transform2D,
UseColors = true,
Mesh = new QuadMesh { Size = Vector2.One },
InstanceCount = trees.Count,
};
for (int i = 0; i < trees.Count; i++)
{
mesh.SetInstanceTransform2D(i, trees[i]);
mesh.SetInstanceColor(i, colors[i]);
}
var node = new MultiMeshInstance2D { Multimesh = mesh, Texture = _treeTexture, ZIndex = 3 };
AddChild(node);
_forests[(cx, cy)] = node;
}
/// <summary>Chioma d'albero: disco con bordo più scuro (immagine 02).</summary>
private static Texture2D TreeTexture()
{
const int n = 64;
var img = Image.CreateEmpty(n, n, false, Image.Format.Rgba8);
for (int y = 0; y < n; y++)
{
for (int x = 0; x < n; x++)
{
float dx = (x + 0.5f) / n * 2 - 1, dy = (y + 0.5f) / n * 2 - 1;
float d = MathF.Sqrt(dx * dx + dy * dy);
if (d > 1) { img.SetPixel(x, y, new Color(0, 0, 0, 0)); continue; }
float light = 1.05f - 0.25f * Math.Clamp(dx + dy + 0.3f, 0, 1) - (d > 0.82f ? 0.25f : 0);
img.SetPixel(x, y, new Color(light, light, light, 1));
}
}
return ImageTexture.CreateFromImage(img);
}
public override void _Process(double delta)
{
if (_world is null) return;
if (_world.EntityVersion != _drawnEntities || _world.TerrainVersion != _drawnTerrain || _world.TrackVersion != _drawnTrack) QueueRedraw();
}
public override void _Draw()
{
var w = _world;
if (w?.Terrain is null) return;
_drawnEntities = w.EntityVersion;
_drawnTerrain = w.TerrainVersion;
_drawnTrack = w.TrackVersion;
var t = w.Terrain;
float cs = (float)t.CellSizeM;
// case: blocchi per cella d'abitato, disposizione fissa per cella
foreach (var town in w.Towns.Values)
{
int r = (int)Math.Ceiling(town.RadiusCells) + 1;
var (tcx, tcy) = t.CellAt(town.Position);
for (int y = tcy - r; y <= tcy + r; y++)
{
for (int x = tcx - r; x <= tcx + r; x++)
{
if (x < 0 || y < 0 || x >= t.Width || y >= t.Height || (CellType)t.Types[y * t.Width + x] != CellType.Town) continue;
DrawHouses(x, y, cs);
}
}
}
foreach (var ind in w.Industries.Values) DrawIndustry(ind, cs);
foreach (var hub in w.Hubs.Values) DrawHub(hub, cs);
foreach (var d in w.Depots.Values) DrawDepot(w, d);
foreach (var st in w.Stations.Values) DrawStation(w, st);
}
private void DrawHouses(int x, int y, float cs)
{
uint h = (uint)(x * 2654435761u ^ y * 40503u);
int count = 3 + (int)(h % 3);
for (int k = 0; k < count; k++)
{
h = h * 1664525 + 1013904223;
float fx = (h & 1023) / 1023f * 0.62f + 0.06f, fy = ((h >> 10) & 1023) / 1023f * 0.62f + 0.06f;
float wpx = cs * (0.18f + ((h >> 20) & 7) * 0.02f), hpx = cs * (0.13f + ((h >> 23) & 7) * 0.015f);
var rect = new Rect2(x * cs + fx * cs, y * cs + fy * cs, wpx, hpx);
var roof = ((h >> 26) & 3) switch { 0 => Palette.IndustrialRoof.Lightened(0.15f), 1 => new Color("a8836a"), _ => Palette.TileRoof };
DrawRect(new Rect2(rect.Position + new Vector2(cs * 0.02f, cs * 0.02f), rect.Size), new Color(0, 0, 0, 0.18f));
DrawRect(rect, roof);
DrawLine(rect.Position + new Vector2(0, rect.Size.Y / 2), rect.Position + new Vector2(rect.Size.X, rect.Size.Y / 2), roof.Darkened(0.25f), cs * 0.012f);
}
}
private void DrawIndustry(IndustryInfo ind, float cs)
{
float size = Math.Max(1, ind.FootprintCells) * cs;
var c = MapScale.V(ind.Position);
var pad = new Rect2(c - new Vector2(size, size) * 0.45f, new Vector2(size, size) * 0.9f);
var ground = ind.Closed ? new Color("b8b4a6") : new Color("bdb6a2");
DrawRect(pad, ground);
DrawRect(pad, new Color("8f8a7a"), false, cs * 0.03f);
string type = ind.Type;
if (type.Contains("mine") || type.Contains("quarry") || type.Contains("well"))
{
DrawCircle(c, size * 0.28f, new Color("6b5e4f"));
DrawCircle(c, size * 0.18f, new Color("3d3630"));
DrawRect(new Rect2(c + new Vector2(size * 0.12f, -size * 0.38f), new Vector2(size * 0.22f, size * 0.14f)), Palette.IndustrialRoof);
}
else if (type.Contains("farm") || type.Contains("ranch") || type.Contains("logging"))
{
DrawRect(new Rect2(c - new Vector2(size * 0.3f, size * 0.2f), new Vector2(size * 0.32f, size * 0.22f)), Palette.TileRoof);
DrawCircle(c + new Vector2(size * 0.2f, -size * 0.1f), size * 0.08f, new Color("9a9a90"));
}
else
{
// capannoni con lucernari (immagine 04)
int sheds = Math.Max(2, ind.FootprintCells);
float sw = size * 0.8f / sheds;
for (int i = 0; i < sheds; i++)
{
var r = new Rect2(pad.Position + new Vector2(size * 0.05f + i * sw, size * 0.08f), new Vector2(sw * 0.92f, size * 0.55f));
DrawRect(new Rect2(r.Position + new Vector2(cs * 0.04f, cs * 0.04f), r.Size), new Color(0, 0, 0, 0.2f));
DrawRect(r, Palette.IndustrialRoof);
DrawLine(r.Position + new Vector2(r.Size.X / 2, 0), r.Position + new Vector2(r.Size.X / 2, r.Size.Y), Palette.IndustrialRoof.Darkened(0.3f), cs * 0.02f);
}
DrawCircle(pad.Position + new Vector2(size * 0.78f, size * 0.75f), size * 0.07f, new Color("6e7175"));
}
if (ind.Closed) DrawLine(pad.Position, pad.End, Palette.Danger, cs * 0.05f);
}
private void DrawHub(HubInfo hub, float cs)
{
var c = MapScale.V(hub.Position);
if (hub.Kind == "port")
{
DrawRect(new Rect2(c - new Vector2(cs * 0.9f, cs * 0.35f), new Vector2(cs * 1.8f, cs * 0.7f)), new Color("9d968a"));
DrawRect(new Rect2(c + new Vector2(cs * 0.2f, -cs * 0.15f), new Vector2(cs * 1.2f, cs * 0.3f)), new Color("4b5560"));
}
else
{
DrawRect(new Rect2(c - new Vector2(cs * 0.4f, cs * 0.25f), new Vector2(cs * 0.8f, cs * 0.5f)), Palette.IndustrialRoof);
for (int i = 0; i < 6; i++)
DrawLine(c + new Vector2(-cs * 0.6f + i * cs * 0.2f, cs * 0.4f), c + new Vector2(-cs * 0.5f + i * cs * 0.2f, cs * 0.4f), i % 2 == 0 ? Palette.Danger : Colors.White, cs * 0.06f);
}
}
/// <summary>Direzione del binario che entra nel nodo (per orientare marciapiedi e fabbricati).</summary>
private static Vector2 NodeDirection(ClientWorld w, int nodeId)
{
if (nodeId < 0 || nodeId >= w.Network.Nodes.Count) return Vector2.Right;
var node = w.Network.Nodes[nodeId];
foreach (var eid in node.Edges)
{
if (!w.Edges.TryGetValue(eid.Value, out var e) || e.S.Length < 2) continue;
bool atA = e.A == nodeId;
var p0 = atA ? MapScale.V(e.X[0], e.Y[0]) : MapScale.V(e.X[^1], e.Y[^1]);
var p1 = atA ? MapScale.V(e.X[1], e.Y[1]) : MapScale.V(e.X[^2], e.Y[^2]);
var d = p1 - p0;
if (d.LengthSquared() > 0) return atA ? d.Normalized() : -d.Normalized();
}
return Vector2.Right;
}
private void DrawStation(ClientWorld w, StationInfo st)
{
float s = MapScale.Symbol(_zoom);
var c = MapScale.V(st.Position);
var dir = NodeDirection(w, st.Node);
var n = new Vector2(-dir.Y, dir.X);
float len = 60f * Math.Max(1, s * 0.6f);
float pw = 3.5f * s;
// marciapiedi ai lati dei binari (immagine 02) e fabbricato con tetto in coppi
for (int k = 0; k < Math.Min(st.Platforms, 4); k++)
{
float side = (k % 2 == 0 ? 1 : -1) * (7f + 6f * (k / 2)) * s;
DrawLine(c - dir * len / 2 + n * side, c + dir * len / 2 + n * side, new Color("d9d4c6"), pw);
}
var b = c + n * 15f * s;
DrawSetTransform(b, dir.Angle());
DrawRect(new Rect2(new Vector2(-12, -5.5f) * s + new Vector2(1.5f, 1.5f) * s, new Vector2(24, 11) * s), new Color(0, 0, 0, 0.2f));
DrawRect(new Rect2(new Vector2(-12, -5.5f) * s, new Vector2(24, 11) * s), Palette.TileRoof);
DrawLine(new Vector2(-12, 0) * s, new Vector2(12, 0) * s, Palette.TileRoof.Darkened(0.3f), 0.8f * s);
DrawSetTransform(Vector2.Zero, 0);
if (st.Id == SelectedStation)
{
float radius = (float)(w.Data.Construction.Stations.CatchmentKm * 1000);
DrawArc(c, radius, 0, MathF.Tau, 96, Palette.Amber, 2f * s);
}
}
private void DrawDepot(ClientWorld w, DepotInfo d)
{
float s = MapScale.Symbol(_zoom);
var c = MapScale.V(d.Position);
var dir = NodeDirection(w, d.Node);
DrawSetTransform(c, dir.Angle());
DrawRect(new Rect2(new Vector2(-16, -9) * s + new Vector2(2, 2) * s, new Vector2(32, 18) * s), new Color(0, 0, 0, 0.2f));
DrawRect(new Rect2(new Vector2(-16, -9) * s, new Vector2(32, 18) * s), new Color("5a6670"));
for (int i = -1; i <= 1; i++) DrawLine(new Vector2(-14, i * 5) * s, new Vector2(14, i * 5) * s, new Color("8a96a0"), 1f * s);
DrawSetTransform(Vector2.Zero, 0);
}
}
@@ -0,0 +1 @@
uid://b3e42tuyvbw27
@@ -0,0 +1,105 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Core.Common;
using ViaFerrea.Protocol.Client;
namespace ViaFerrea.Client.Map;
/// <summary>
/// Etichette a dimensione costante sullo schermo: città in Big Shoulders Display con gli abitanti,
/// industrie e stazioni in IBM Plex Sans; scala grafica in basso a destra (immagine 01).
/// </summary>
public partial class LabelLayer : Control
{
private ClientWorld? _world;
private Camera2D? _camera;
public void Bind(ClientWorld world, Camera2D camera)
{
_world = world;
_camera = camera;
MouseFilter = MouseFilterEnum.Ignore;
SetAnchorsPreset(LayoutPreset.FullRect);
}
public override void _Process(double delta) => QueueRedraw();
private Vector2 ToScreen(Vector2 world)
{
var vt = GetViewport().GetCanvasTransform();
return vt * world;
}
public override void _Draw()
{
var w = _world;
if (w?.Terrain is null || _camera is null) return;
float zoom = _camera.Zoom.X;
var size = GetViewportRect().Size;
bool InView(Vector2 p) => p.X > -200 && p.Y > -100 && p.X < size.X + 200 && p.Y < size.Y + 100;
foreach (var town in w.Towns.Values)
{
var p = ToScreen(MapScale.V(town.Position));
if (!InView(p)) continue;
int titleSize = town.Population >= 10000 ? 30 : town.Population >= 3000 ? 26 : 22;
Centered(UiTheme.Title, town.Name, p + new Vector2(0, -6), titleSize, new Color("2a2f2c"), outline: true);
Centered(UiTheme.Body, $"{Money.GroupThousands((ulong)town.Population)} {Localization.T("abitanti")}", p + new Vector2(0, 12), 13, new Color("3d4440"), outline: true);
}
if (zoom >= 0.02f)
{
foreach (var ind in w.Industries.Values)
{
var p = ToScreen(MapScale.V(ind.Position) + new Vector2(0, (float)(ind.FootprintCells * w.Terrain.CellSizeM * 0.5)));
if (!InView(p)) continue;
Centered(UiTheme.BodyBold, ind.Name, p + new Vector2(0, 14), 13, new Color("2a2f2c"), outline: true);
}
foreach (var hub in w.Hubs.Values)
{
var p = ToScreen(MapScale.V(hub.Position));
if (!InView(p)) continue;
Centered(UiTheme.BodyBold, hub.Name, p + new Vector2(0, 26), 13, new Color("2a2f2c"), outline: true);
Centered(UiTheme.Body, Localization.T("hub mercato mondiale"), p + new Vector2(0, 42), 12, new Color("3d4440"), outline: true);
}
}
foreach (var st in w.Stations.Values)
{
var p = ToScreen(MapScale.V(st.Position));
if (!InView(p)) continue;
Centered(UiTheme.Body, st.Name, p + new Vector2(0, -18), 12, new Color("2a2f2c"), outline: true);
}
foreach (var d in w.Depots.Values)
{
var p = ToScreen(MapScale.V(d.Position));
if (!InView(p)) continue;
Centered(UiTheme.BodyBold, Localization.T("Deposito"), p + new Vector2(0, 26), 12, new Color("2a2f2c"), outline: true);
}
DrawScaleBar(size, zoom);
}
private void Centered(Font font, string text, Vector2 at, int size, Color color, bool outline)
{
var dims = font.GetStringSize(text, HorizontalAlignment.Left, -1, size);
var pos = at - new Vector2(dims.X / 2, 0);
if (outline) DrawStringOutline(font, pos, text, HorizontalAlignment.Left, -1, size, 4, new Color(0.86f, 0.88f, 0.82f, 0.85f));
DrawString(font, pos, text, HorizontalAlignment.Left, -1, size, color);
}
/// <summary>Scala grafica con una lunghezza «tonda» di circa 100 px.</summary>
private void DrawScaleBar(Vector2 size, float zoom)
{
double meters = 100 / zoom;
double[] nice = [50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000];
double m = nice.FirstOrDefault(v => v >= meters, nice[^1]);
float px = (float)(m * zoom);
var end = new Vector2(size.X - 30, size.Y - 60);
var start = end - new Vector2(px, 0);
var c = new Color("2a2f2c");
DrawLine(start, end, c, 2);
DrawLine(start, start + new Vector2(0, -8), c, 2);
DrawLine(end, end + new Vector2(0, -8), c, 2);
DrawLine((start + end) / 2, (start + end) / 2 + new Vector2(0, -5), c, 2);
string label = m >= 1000 ? $"{m / 1000:0} km" : $"{m:0} m";
Centered(UiTheme.Body, label, (start + end) / 2 + new Vector2(0, 18), 12, c, outline: true);
}
}
@@ -0,0 +1 @@
uid://b843xbckahtip
@@ -0,0 +1,66 @@
using Godot;
using ViaFerrea.Core.Common;
namespace ViaFerrea.Client.Map;
/// <summary>
/// Scala dei simboli: a zoom ravvicinato binari e treni hanno le misure della guida in metri
/// (1 unità = 1 m: rotaie a ±2,4, traversine ogni 5,3, carro 16); allontanandosi i simboli si
/// ingrandiscono per restare leggibili come nell'immagine 01. LOD sotto 0,4 e 0,15.
/// </summary>
public static class MapScale
{
public const float DetailZoom = 0.4f;
public const float OverviewZoom = 0.15f;
public const float ContourMinZoom = 1.0f;
/// <summary>Moltiplicatore dei simboli per lo zoom (pixel per metro).</summary>
/// <remarks>
/// Tarata sui riferimenti: nell'immagine 01 (circa 0,02 px/m) un carro è lungo ~16 px, nella 02
/// (circa 0,6 px/m) ~70 px: pixel per unità = 5,5·zoom^0,44, cioè unità di mondo = 5,5·zoom^−0,56.
/// </remarks>
public static float Symbol(float zoom) => Math.Max(1f, 5.5f * MathF.Pow(Math.Max(zoom, 0.001f), -0.56f));
public static Vector2 V(Vec2 p) => new((float)p.X, (float)p.Y);
public static Vector2 V(double x, double y) => new((float)x, (float)y);
public static Vec2 W(Vector2 p) => new(p.X, p.Y);
/// <summary>Polilinea spostata lateralmente di offset (normale media ai vertici).</summary>
public static Vector2[] Offset(Vector2[] pts, float offset)
{
var result = new Vector2[pts.Length];
for (int i = 0; i < pts.Length; i++)
{
Vector2 dir;
if (i == 0) dir = pts[1] - pts[0];
else if (i == pts.Length - 1) dir = pts[i] - pts[i - 1];
else dir = (pts[i + 1] - pts[i - 1]);
dir = dir.LengthSquared() > 0 ? dir.Normalized() : Vector2.Right;
result[i] = pts[i] + new Vector2(-dir.Y, dir.X) * offset;
}
return result;
}
/// <summary>Punti e direzioni ogni «step» metri lungo una polilinea.</summary>
public static IEnumerable<(Vector2 Point, Vector2 Dir)> Every(Vector2[] pts, float step, float start = 0)
{
float next = start;
float acc = 0;
for (int i = 0; i < pts.Length - 1; i++)
{
var a = pts[i];
var b = pts[i + 1];
float len = a.DistanceTo(b);
if (len <= 0) continue;
var dir = (b - a) / len;
while (next <= acc + len)
{
yield return (a + dir * (next - acc), dir);
next += step;
}
acc += len;
}
}
}
@@ -0,0 +1 @@
uid://cb6evw1enekmi
@@ -0,0 +1,145 @@
using Godot;
using ViaFerrea.Client.Net;
namespace ViaFerrea.Client.Map;
/// <summary>
/// Vista della mappa: Node2D con Camera2D e i livelli (terreno, opere e binari, entità, treni,
/// strumenti). Rotella = zoom attorno al cursore, tasto destro o centrale = spostamento,
/// WASD/frecce = spostamento da tastiera. Coordinate del mondo in metri (1 unità = 1 m).
/// </summary>
public partial class MapView : Node2D
{
public const float MinZoom = 0.008f;
public const float MaxZoom = 6f;
public Camera2D Camera { get; } = new();
public TerrainLayer Terrain { get; } = new() { ZIndex = 0 };
public TrackLayer Track { get; } = new() { ZIndex = 2 };
public EntityLayer Entities { get; } = new() { ZIndex = 1 };
public TrainLayer Trains { get; } = new() { ZIndex = 5 };
public ToolOverlay Tools { get; } = new() { ZIndex = 8 };
/// <summary>Clic sinistro sulla mappa (posizione nel mondo).</summary>
public event Action<Vector2>? Clicked;
/// <summary>Clic destro senza trascinamento (annulla lo strumento).</summary>
public event Action? Cancelled;
/// <summary>Spostamento del mouse sulla mappa (posizione nel mondo).</summary>
public event Action<Vector2>? Hovered;
private bool _dragging;
private Vector2 _dragDistance;
private float _lastZoom = -1;
public override void _Ready()
{
AddChild(Terrain);
AddChild(Entities);
AddChild(Track);
AddChild(Trains);
AddChild(Tools);
AddChild(Camera);
Camera.Enabled = true;
Camera.MakeCurrent();
}
public void Bind(GameSession session)
{
Terrain.Bind(session.World);
Track.Bind(session.World);
Entities.Bind(session.World);
Trains.Bind(session);
Tools.Bind(session.World);
var t = session.World.Summary!;
Camera.Position = new Vector2((float)(t.WidthCells * t.CellSizeM / 2), (float)(t.HeightCells * t.CellSizeM / 2));
float fit = (float)(GetViewportRect().Size.X / (t.WidthCells * t.CellSizeM));
SetZoom(Math.Clamp(fit * 2.5f, MinZoom, MaxZoom));
}
public float Zoom => Camera.Zoom.X;
public void SetZoom(float zoom)
{
zoom = Math.Clamp(zoom, MinZoom, MaxZoom);
Camera.Zoom = new Vector2(zoom, zoom);
}
public void CenterOn(Vector2 world) => Camera.Position = world;
/// <summary>Rettangolo del mondo visibile.</summary>
public Rect2 VisibleRect()
{
var size = GetViewportRect().Size / Zoom;
return new Rect2(Camera.GetScreenCenterPosition() - size / 2, size);
}
public override void _Process(double delta)
{
var move = Vector2.Zero;
if (Input.IsKeyPressed(Key.W) || Input.IsKeyPressed(Key.Up)) move.Y -= 1;
if (Input.IsKeyPressed(Key.S) || Input.IsKeyPressed(Key.Down)) move.Y += 1;
if (Input.IsKeyPressed(Key.A) || Input.IsKeyPressed(Key.Left)) move.X -= 1;
if (Input.IsKeyPressed(Key.D) || Input.IsKeyPressed(Key.Right)) move.X += 1;
if (move != Vector2.Zero && GetViewport().GuiGetFocusOwner() is not LineEdit)
Camera.Position += move.Normalized() * (float)delta * 700f / Zoom;
if (Math.Abs(Zoom - _lastZoom) > 1e-6)
{
_lastZoom = Zoom;
Terrain.SetZoom(Zoom);
Track.SetZoom(Zoom);
Entities.SetZoom(Zoom);
Trains.SetZoom(Zoom);
Tools.SetZoom(Zoom);
}
}
public override void _UnhandledInput(InputEvent e)
{
switch (e)
{
case InputEventMouseButton { ButtonIndex: MouseButton.WheelUp, Pressed: true } wheel:
ZoomAt(wheel.Position, 1.15f);
GetViewport().SetInputAsHandled();
break;
case InputEventMouseButton { ButtonIndex: MouseButton.WheelDown, Pressed: true } wheel:
ZoomAt(wheel.Position, 1 / 1.15f);
GetViewport().SetInputAsHandled();
break;
case InputEventMouseButton { ButtonIndex: MouseButton.Right or MouseButton.Middle } b:
if (b.Pressed)
{
_dragging = true;
_dragDistance = Vector2.Zero;
}
else
{
_dragging = false;
if (b.ButtonIndex == MouseButton.Right && _dragDistance.Length() < 4) Cancelled?.Invoke();
}
GetViewport().SetInputAsHandled();
break;
case InputEventMouseButton { ButtonIndex: MouseButton.Left, Pressed: true }:
Clicked?.Invoke(GetGlobalMousePosition());
GetViewport().SetInputAsHandled();
break;
case InputEventMouseMotion motion:
if (_dragging)
{
Camera.Position -= motion.Relative / Zoom;
_dragDistance += motion.Relative;
}
Hovered?.Invoke(GetGlobalMousePosition());
break;
}
}
private void ZoomAt(Vector2 screen, float factor)
{
var before = GetCanvasTransform().AffineInverse() * screen;
SetZoom(Zoom * factor);
// la camera si sposta perché il punto sotto il cursore resti fermo
var size = GetViewportRect().Size;
var offset = (screen - size / 2) / Zoom;
Camera.Position = before - offset;
}
}
@@ -0,0 +1 @@
uid://3frpv33rahht
@@ -0,0 +1,202 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Core.Map;
using ViaFerrea.Protocol.Client;
namespace ViaFerrea.Client.Map;
/// <summary>
/// Terreno a chunk (immagine 01): colori per tipo di cella e fascia altimetrica, ombreggiatura
/// con luce da nord-ovest (ombre verso sud-est), sponde chiare lungo l'acqua, campi a strisce;
/// curve di livello ogni 20 m su una texture separata visibile oltre lo zoom 1.
/// </summary>
public partial class TerrainLayer : Node2D
{
private const float ContourStepM = 20f;
private readonly Dictionary<(int, int), (Sprite2D Base, Sprite2D Contours)> _sprites = [];
private readonly Queue<(int, int)> _dirty = new();
private readonly HashSet<(int, int)> _queued = [];
private ClientWorld? _world;
public void Bind(ClientWorld world)
{
_world = world;
foreach (var (b, c) in _sprites.Values)
{
b.QueueFree();
c.QueueFree();
}
_sprites.Clear();
_dirty.Clear();
_queued.Clear();
}
/// <summary>Segna un chunk (e i vicini, per la continuità dell'ombreggiatura) da ridisegnare.</summary>
public void MarkDirty(int cx, int cy)
{
for (int dy = -1; dy <= 1; dy++)
{
for (int dx = -1; dx <= 1; dx++)
{
var key = (cx + dx, cy + dy);
if (_world is null || !_world.Chunks.Contains(key) || !_queued.Add(key)) continue;
_dirty.Enqueue(key);
}
}
}
public void SetZoom(float zoom)
{
bool contours = zoom >= MapScale.ContourMinZoom;
foreach (var (_, c) in _sprites.Values) c.Visible = contours;
}
public override void _Process(double delta)
{
// pochi chunk per fotogramma: l'ingresso in partita resta fluido
for (int i = 0; i < 6 && _dirty.Count > 0; i++)
{
var key = _dirty.Dequeue();
_queued.Remove(key);
Build(key.Item1, key.Item2);
}
}
private void Build(int cx, int cy)
{
var w = _world;
if (w?.Terrain is null || w.Sampler is null) return;
var t = w.Terrain;
int ppc = t.Width <= 700 ? 4 : t.Width <= 1300 ? 2 : 1;
int x0 = cx * t.ChunkCells, y0 = cy * t.ChunkCells;
int cellsW = Math.Min(t.ChunkCells, t.Width - x0), cellsH = Math.Min(t.ChunkCells, t.Height - y0);
int pw = cellsW * ppc, ph = cellsH * ppc;
var pixels = new byte[pw * ph * 4];
var contour = new byte[pw * ph * 4];
double cs = t.CellSizeM, px = cs / ppc;
// per cella (con un bordo): ombreggiatura dalle differenze centrali e indicatore d'acqua
int gw = cellsW + 3, gh = cellsH + 3;
var shade = new float[gw * gh];
var water = new float[gw * gh];
for (int gy = 0; gy < gh; gy++)
{
for (int gx = 0; gx < gw; gx++)
{
int x = Math.Clamp(x0 + gx - 1, 0, t.Width - 1), y = Math.Clamp(y0 + gy - 1, 0, t.Height - 1);
double hx = (H(t, x + 1, y) - H(t, x - 1, y)) / (2 * cs);
double hy = (H(t, x, y + 1) - H(t, x, y - 1)) / (2 * cs);
// luce da nord-ovest: i pendii rivolti a sud-est si scuriscono
shade[gy * gw + gx] = (float)Math.Clamp(1.0 - (hx + hy) * 1.8, 0.80, 1.12);
water[gy * gw + gx] = IsWater((CellType)t.Types[y * t.Width + x]) ? 1f : 0f;
}
}
var corner = new Color[4];
for (int y = 0; y < ph; y++)
{
for (int x = 0; x < pw; x++)
{
// posizione in celle rispetto ai centri: interpolazione bilineare tra quattro celle
double fx = (x + 0.5) / ppc - 0.5, fy = (y + 0.5) / ppc - 0.5;
int ix = (int)Math.Floor(fx), iy = (int)Math.Floor(fy);
float tx = (float)(fx - ix), ty = (float)(fy - iy);
int g00 = (iy + 1) * gw + ix + 1;
float wv = Bilinear(water[g00], water[g00 + 1], water[g00 + gw], water[g00 + gw + 1], tx, ty);
float sh = Bilinear(shade[g00], shade[g00 + 1], shade[g00 + gw], shade[g00 + gw + 1], tx, ty);
double h = w.Sampler.HeightAt(x0 * cs + (x + 0.5) * px, y0 * cs + (y + 0.5) * px);
for (int k = 0; k < 4; k++)
{
int cxCell = Math.Clamp(x0 + ix + (k & 1), 0, t.Width - 1), cyCell = Math.Clamp(y0 + iy + (k >> 1), 0, t.Height - 1);
corner[k] = BaseColor((CellType)t.Types[cyCell * t.Width + cxCell], h, cxCell, cyCell, x, y, ppc);
}
var c = corner[0].Lerp(corner[1], tx).Lerp(corner[2].Lerp(corner[3], tx), ty);
if (wv < 0.5f) c = new Color(c.R * sh, c.G * sh, c.B * sh);
SetPixel(pixels, pw, x, y, new Color(c.R, c.G, c.B, wv));
if (wv < 0.5f)
{
double hR = w.Sampler.HeightAt(x0 * cs + (x + 1.5) * px, y0 * cs + (y + 0.5) * px);
double hD = w.Sampler.HeightAt(x0 * cs + (x + 0.5) * px, y0 * cs + (y + 1.5) * px);
int band = (int)Math.Floor(h / ContourStepM);
if (band != (int)Math.Floor(hR / ContourStepM) || band != (int)Math.Floor(hD / ContourStepM))
SetPixel(contour, pw, x, y, new Color(0.25f, 0.27f, 0.22f, (band % 5 == 0) ? 0.45f : 0.22f));
}
}
}
var key = (cx, cy);
if (!_sprites.TryGetValue(key, out var pair))
{
pair = (NewSprite(), NewSprite());
pair.Base.Material = TerrainMaterial();
AddChild(pair.Base);
AddChild(pair.Contours);
pair.Contours.ZIndex = 1;
_sprites[key] = pair;
}
foreach (var (sprite, data) in new[] { (pair.Base, pixels), (pair.Contours, contour) })
{
sprite.Texture = ImageTexture.CreateFromImage(Image.CreateFromData(pw, ph, false, Image.Format.Rgba8, data));
sprite.Position = new Vector2((float)(x0 * cs), (float)(y0 * cs));
sprite.Scale = new Vector2((float)px, (float)px);
}
pair.Contours.Visible = GetViewport().GetCamera2D() is { } cam && cam.Zoom.X >= MapScale.ContourMinZoom;
}
private static ShaderMaterial? _material;
private static ShaderMaterial TerrainMaterial()
{
if (_material is not null) return _material;
var shader = ResourceLoader.Load<Shader>("res://assets/shaders/terrain.gdshader");
_material = new ShaderMaterial { Shader = shader };
_material.SetShaderParameter("bank_color", Palette.Banks);
return _material;
}
private static double H(Terrain t, int x, int y) => t.CellHeightM(Math.Clamp(x, 0, t.Width - 1), Math.Clamp(y, 0, t.Height - 1));
private static float Bilinear(float a, float b, float c, float d, float tx, float ty) => (a + (b - a) * tx) + ((c + (d - c) * tx) - (a + (b - a) * tx)) * ty;
private static Sprite2D NewSprite() => new() { Centered = false, TextureFilter = TextureFilterEnum.Linear };
private static bool IsWater(CellType type) => type is CellType.Water or CellType.Sea;
private static Color BaseColor(CellType type, double h, int cellX, int cellY, int x, int y, int ppc)
{
switch (type)
{
case CellType.Sea: return Palette.Sea;
case CellType.Water: return Palette.Water;
case CellType.Marsh: return (x + y) % 6 < 2 ? Palette.Water.Lerp(Palette.Marsh, 0.6f) : Palette.Marsh;
case CellType.Forest: return Palette.Undergrowth;
case CellType.Field:
{
// campi a strisce, con orientamento e colore per cella
uint hash = (uint)(cellX * 73856093 ^ cellY * 19349663);
bool vertical = (hash & 1) == 0;
int stripe = (vertical ? x : y) * 4 / Math.Max(1, ppc);
var baseColor = ((hash >> 1) % 3) switch { 0 => Palette.Grain, 1 => new Color("a9c46a"), _ => new Color("c8a86a") };
return stripe % 2 == 0 ? baseColor : baseColor.Darkened(0.08f);
}
case CellType.Town: return new Color("d6d2bf");
case CellType.Industry: return new Color("c9c4b2");
case CellType.Rock: return Palette.Rock;
case CellType.Mountain: return Palette.Highland.Darkened(0.05f);
default:
{
// fasce altimetriche: pianura, collina, altura
if (h < 120) return Palette.Plain;
if (h < 320) return Palette.Plain.Lerp(Palette.Hill, (float)((h - 120) / 200));
return Palette.Hill.Lerp(Palette.Highland, (float)Math.Min(1, (h - 320) / 300));
}
}
}
private static void SetPixel(byte[] data, int width, int x, int y, Color c)
{
int i = (y * width + x) * 4;
data[i] = (byte)(Math.Clamp(c.R, 0, 1) * 255);
data[i + 1] = (byte)(Math.Clamp(c.G, 0, 1) * 255);
data[i + 2] = (byte)(Math.Clamp(c.B, 0, 1) * 255);
data[i + 3] = (byte)(Math.Clamp(c.A, 0, 1) * 255);
}
}
@@ -0,0 +1 @@
uid://cjsaug4ypro7
@@ -0,0 +1,122 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol.Client;
namespace ViaFerrea.Client.Map;
/// <summary>Sagome degli strumenti: tracciato in corso con l'anteprima delle opere, stazione o deposito da posare, fermate di una linea.</summary>
public partial class ToolOverlay : Node2D
{
public enum Ghost { None, Station, Depot, Demolish }
private ClientWorld? _world;
private float _zoom = 1;
private List<Vector2> _points = [];
private Vector2? _mouse;
private TrackPlan? _plan;
private Ghost _ghost;
private Vector2? _ghostAt;
private List<Vector2> _stops = [];
public void Bind(ClientWorld world) => _world = world;
public void SetZoom(float zoom)
{
_zoom = zoom;
QueueRedraw();
}
public void SetTrack(List<Vector2> points, Vector2? mouse, TrackPlan? plan)
{
_points = points;
_mouse = mouse;
_plan = plan;
QueueRedraw();
}
public void SetGhost(Ghost ghost, Vector2? at)
{
_ghost = ghost;
_ghostAt = at;
QueueRedraw();
}
public void SetStops(List<Vector2> stops)
{
_stops = stops;
QueueRedraw();
}
public void Clear()
{
_points = [];
_mouse = null;
_plan = null;
_ghost = Ghost.None;
_ghostAt = null;
_stops = [];
QueueRedraw();
}
public static Color WorkColor(WorkKind kind) => kind switch
{
WorkKind.Embankment => new Color("e8e0c2"),
WorkKind.Cutting => new Color("8f8a73"),
WorkKind.Bridge => new Color("5b8fb0"),
WorkKind.Tunnel => new Color("4a4740"),
_ => Palette.Ballast,
};
public override void _Draw()
{
float s = MapScale.Symbol(_zoom);
if (_plan is { Samples.Count: > 1 } plan)
{
var color = plan.Valid ? Palette.Ok : Palette.Danger;
for (int i = 0; i < plan.Samples.Count - 1; i++)
{
var a = MapScale.V(plan.Samples[i].Point);
var b = MapScale.V(plan.Samples[i + 1].Point);
DrawLine(a, b, Palette.WithAlpha(color, 0.45f), 14f * s);
if (plan.Samples[i].Kind == WorkKind.Tunnel) DrawDashedLine(a, b, WorkColor(WorkKind.Tunnel), 5f * s, 6f * s);
else DrawLine(a, b, WorkColor(plan.Samples[i].Kind), 7f * s);
}
}
var pts = new List<Vector2>(_points);
if (_mouse is { } m && pts.Count > 0) pts.Add(m);
for (int i = 0; i < pts.Count - 1; i++) DrawDashedLine(pts[i], pts[i + 1], Palette.Amber, 2f * s, 8f * s);
foreach (var p in _points) DrawCircle(p, 4f * s, Palette.Amber);
if (_ghostAt is { } g && _world is not null)
{
switch (_ghost)
{
case Ghost.Station:
float radius = (float)(_world.Data.Construction.Stations.CatchmentKm * 1000);
for (int k = 0; k < 48; k += 2)
{
float a0 = k * MathF.Tau / 48, a1 = (k + 1) * MathF.Tau / 48;
DrawLine(g + new Vector2(MathF.Cos(a0), MathF.Sin(a0)) * radius, g + new Vector2(MathF.Cos(a1), MathF.Sin(a1)) * radius, Palette.Amber, 2.5f * s);
}
DrawCircle(g, radius, Palette.WithAlpha(Palette.Amber, 0.08f));
DrawRect(new Rect2(g - new Vector2(12, 6) * s, new Vector2(24, 12) * s), Palette.WithAlpha(Palette.TileRoof, 0.8f));
break;
case Ghost.Depot:
DrawRect(new Rect2(g - new Vector2(16, 9) * s, new Vector2(32, 18) * s), Palette.WithAlpha(new Color("5a6670"), 0.8f));
break;
case Ghost.Demolish:
DrawCircle(g, 30f * s, Palette.WithAlpha(Palette.Danger, 0.3f));
DrawLine(g - new Vector2(10, 10) * s, g + new Vector2(10, 10) * s, Palette.Danger, 3f * s);
DrawLine(g + new Vector2(-10, 10) * s, g + new Vector2(10, -10) * s, Palette.Danger, 3f * s);
break;
}
}
for (int i = 0; i < _stops.Count; i++)
{
if (i > 0) DrawDashedLine(_stops[i - 1], _stops[i], Palette.Amber, 3f * s, 10f * s);
DrawCircle(_stops[i], 9f * s, Palette.Amber);
DrawString(UiTheme.BodyBold, _stops[i] + new Vector2(-4, 5) * s, (i + 1).ToString(), HorizontalAlignment.Left, -1, (int)Math.Max(8, 12 * s), Palette.AppBackground);
}
}
}
@@ -0,0 +1 @@
uid://itdwbft1rwnw
@@ -0,0 +1,218 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
namespace ViaFerrea.Client.Map;
/// <summary>
/// Binari e opere (immagini 01 e 02): massicciata #bfb79f, traversine #5b4a39 ogni 5,3 unità,
/// rotaie #3b3f42 a ±2,4; rilevati come banda chiara con ombra, trincee come banda scura, ponti
/// con pile ogni 30 m e spallette, gallerie con portali e binario tratteggiato; cantieri con
/// tratteggio #8a7a52 e barriera ambra. LOD: sotto 0,4 niente traversine fitte, sotto 0,15 solo
/// massicciata e rotaia.
/// </summary>
public partial class TrackLayer : Node2D
{
private ClientWorld? _world;
private int _drawnVersion = -1;
private float _drawnScale = -1;
private float _zoom = 1;
public void Bind(ClientWorld world)
{
_world = world;
_drawnVersion = -1;
QueueRedraw();
}
public void SetZoom(float zoom)
{
_zoom = zoom;
float s = Quantize(MapScale.Symbol(zoom));
if (Math.Abs(s - _drawnScale) > 1e-3) QueueRedraw();
}
private static float Quantize(float s) => s <= 1 ? 1 : MathF.Pow(1.25f, MathF.Round(MathF.Log(s) / MathF.Log(1.25f)));
public override void _Process(double delta)
{
if (_world is not null && _world.TrackVersion != _drawnVersion) QueueRedraw();
}
public override void _Draw()
{
if (_world is null) return;
_drawnVersion = _world.TrackVersion;
float s = Quantize(MapScale.Symbol(_zoom));
_drawnScale = s;
var edges = _world.Edges.Values.OrderBy(e => e.Id).ToList();
// prima le opere sotto il binario, poi i binari, infine i dettagli
foreach (var e in edges) DrawWorks(e, s);
foreach (var e in edges) DrawTrack(e, s);
}
private static Vector2[] Points(EdgeInfo e, int from, int to)
{
var pts = new Vector2[to - from + 1];
for (int i = from; i <= to; i++) pts[i - from] = MapScale.V(e.X[i], e.Y[i]);
return pts;
}
/// <summary>Tratti consecutivi con la stessa opera.</summary>
private static IEnumerable<(WorkKind Kind, int From, int To)> Runs(EdgeInfo e)
{
int start = 0;
for (int i = 1; i <= e.Kinds.Length; i++)
{
if (i < e.Kinds.Length && e.Kinds[i] == e.Kinds[start]) continue;
yield return ((WorkKind)e.Kinds[start], Math.Max(0, start - (start > 0 ? 1 : 0)), Math.Min(e.Kinds.Length - 1, i));
start = i;
}
}
private void DrawWorks(EdgeInfo e, float s)
{
float width = (e.DoubleTrack ? 19f : 9f) * s;
foreach (var (kind, from, to) in Runs(e))
{
if (to <= from) continue;
var pts = Points(e, from, to);
switch (kind)
{
case WorkKind.Embankment:
DrawPolyline(Shift(pts, 2.5f * s), new Color(0.35f, 0.36f, 0.3f, 0.35f), width * 2.2f);
DrawPolyline(pts, new Color("ddd6bf"), width * 2.0f);
break;
case WorkKind.Cutting:
DrawPolyline(pts, new Color("8f8a73"), width * 2.2f);
DrawPolyline(pts, new Color("a8a38a"), width * 1.5f);
break;
case WorkKind.Bridge:
DrawBridge(pts, width, s);
break;
case WorkKind.Tunnel:
DrawPortal(pts[0], pts[1] - pts[0], width, s);
DrawPortal(pts[^1], pts[^2] - pts[^1], width, s);
break;
}
}
}
private void DrawBridge(Vector2[] pts, float width, float s)
{
// pile ogni 30 m, impalcato e spallette alle estremità
foreach (var (p, dir) in MapScale.Every(pts, 30f * Math.Max(1, s * 0.5f), 15f))
{
var n = new Vector2(-dir.Y, dir.X);
DrawLine(p - n * width * 0.85f, p + n * width * 0.85f, new Color("6f6a5e"), 3f * s);
}
DrawPolyline(Shift(pts, 2f * s), new Color(0.2f, 0.25f, 0.28f, 0.35f), width * 1.4f);
DrawPolyline(pts, new Color("b9b3a3"), width * 1.35f);
DrawPolyline(Offset(pts, width * 0.68f), new Color("7a7468"), 1.6f * s);
DrawPolyline(Offset(pts, -width * 0.68f), new Color("7a7468"), 1.6f * s);
foreach (var (end, inner) in new[] { (pts[0], pts[1]), (pts[^1], pts[^2]) })
{
var dir = (inner - end).Normalized();
var n = new Vector2(-dir.Y, dir.X);
DrawLine(end - n * width, end + n * width, new Color("8d877a"), 4f * s);
}
}
private void DrawPortal(Vector2 at, Vector2 inward, float width, float s)
{
if (inward.LengthSquared() <= 0) return;
var dir = inward.Normalized();
var n = new Vector2(-dir.Y, dir.X);
var c = new Color("4a4740");
DrawLine(at - n * width, at + n * width, c, 5f * s);
DrawLine(at - n * width, at - n * width + dir * 8f * s, c, 3f * s);
DrawLine(at + n * width, at + n * width + dir * 8f * s, c, 3f * s);
}
private void DrawTrack(EdgeInfo e, float s)
{
var all = Points(e, 0, e.S.Length - 1);
bool building = e.State == (byte)EdgeState.UnderConstruction;
int built = all.Length - 1;
if (building)
{
// parte costruita in proporzione all'avanzamento, il resto tratteggiato
double target = e.Progress * e.S[^1];
built = 0;
while (built < e.S.Length - 1 && e.S[built + 1] <= target) built++;
}
float[] offsets = e.DoubleTrack ? [-5f * s, 5f * s] : [0f];
foreach (float off in offsets)
{
var line = off == 0 ? all : Offset(all, off);
foreach (var (kind, from, to) in Runs(e))
{
int a = from, b = Math.Min(to, built);
if (b <= a) continue;
var seg = line[a..(b + 1)];
if (kind == WorkKind.Tunnel)
{
for (int i = 0; i < seg.Length - 1; i++) DrawDashedLine(seg[i], seg[i + 1], Palette.Rails, 1.5f * s, 6f * s);
continue;
}
DrawSingleTrack(seg, s, e.State == (byte)EdgeState.Closed);
}
if (building && built < all.Length - 1)
{
var rest = line[built..];
for (int i = 0; i < rest.Length - 1; i++) DrawDashedLine(rest[i], rest[i + 1], Palette.Construction, 2.5f * s, 7f * s);
// barriera ambra al fronte del cantiere
var front = rest[0];
var dir = (rest[Math.Min(1, rest.Length - 1)] - front).Normalized();
var n = new Vector2(-dir.Y, dir.X);
for (int k = -2; k <= 1; k++)
{
var c = k % 2 == 0 ? Palette.Amber : Palette.AppBackground;
DrawLine(front + n * k * 2.5f * s, front + n * (k + 1) * 2.5f * s, c, 2.2f * s);
}
}
}
// segnali: piccoli dischi accanto al binario
foreach (double sig in e.Signals)
{
int i = Array.BinarySearch(e.S, sig);
if (i < 0) i = Math.Max(0, ~i - 1);
i = Math.Min(i, e.S.Length - 2);
var p = all[i];
var dir = (all[i + 1] - p).Normalized();
var n = new Vector2(-dir.Y, dir.X);
DrawCircle(p + n * 7f * s, 1.8f * s, Palette.Rails);
DrawCircle(p + n * 7f * s, 1.1f * s, Palette.Ok);
}
}
private void DrawSingleTrack(Vector2[] pts, float s, bool closed)
{
float zoomDetail = _zoom;
DrawPolyline(pts, closed ? Palette.Ballast.Darkened(0.2f) : Palette.Ballast, 9f * s);
if (zoomDetail >= MapScale.OverviewZoom || s > 1)
{
float spacing = 5.3f * s * (zoomDetail >= MapScale.DetailZoom ? 1 : 1.6f);
var sleepers = new List<Vector2>();
foreach (var (p, dir) in MapScale.Every(pts, spacing, spacing / 2))
{
var n = new Vector2(-dir.Y, dir.X);
sleepers.Add(p - n * 3.6f * s);
sleepers.Add(p + n * 3.6f * s);
}
if (sleepers.Count > 0) DrawMultiline(sleepers.ToArray(), Palette.Sleepers, 1.3f * s);
DrawPolyline(Offset(pts, 2.4f * s), Palette.Rails, 0.9f * s);
DrawPolyline(Offset(pts, -2.4f * s), Palette.Rails, 0.9f * s);
}
else
{
DrawPolyline(pts, Palette.Rails, 1.4f * s);
}
}
private static Vector2[] Offset(Vector2[] pts, float off) => MapScale.Offset(pts, off);
private static Vector2[] Shift(Vector2[] pts, float d) => pts.Select(p => p + new Vector2(d, d)).ToArray();
}
@@ -0,0 +1 @@
uid://ckvbn0wqdgoiy
@@ -0,0 +1,212 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
namespace ViaFerrea.Client.Map;
/// <summary>
/// Treni dall'alto (immagine 03): locomotiva scura con dettagli ambra, carri e carrozze con le
/// proporzioni della guida (larghezza 9, carro 16, carrozza 20, locomotiva 20–26), posizione
/// interpolata avanzando la testa alla velocità ricevuta; fumo per le vaporiere; sfumatura e
/// icona d'avviso sotto condizione 40.
/// </summary>
public partial class TrainLayer : Node2D
{
private GameSession? _session;
private float _zoom = 1;
private readonly List<GpuParticles2D> _smoke = [];
private Dictionary<string, VehicleDef> _defs = [];
public int SelectedTrain { get; set; } = -1;
/// <summary>Teste dei treni disegnate nell'ultimo fotogramma (per la selezione col mouse).</summary>
public Dictionary<int, Vector2> Heads { get; } = [];
public void Bind(GameSession session)
{
_session = session;
_defs = session.World.Data.Vehicles.ToDictionary(v => v.Id);
}
public void SetZoom(float zoom) => _zoom = zoom;
public override void _Process(double delta) => QueueRedraw();
/// <summary>Secondi di orologio dei treni trascorsi dall'arrivo del moto (fattore 60 per la velocità).</summary>
private double Elapsed(int trainId, ClientWorld w)
{
if (_session is null || !_session.MotionReceivedMs.TryGetValue(trainId, out long at)) return 0;
double realSeconds = Math.Max(0, ((long)Time.GetTicksMsec() - at) / 1000.0);
double perTick = w.Calendar?.TrainSecondsPerTick ?? 3;
double ticksPerSecond = 1000.0 / (w.Calendar?.TickMs ?? 50);
// senza interpolare oltre mezzo secondo: il moto successivo arriva ogni 100 ms
return Math.Min(realSeconds, 0.5) * ticksPerSecond * perTick * w.Speed;
}
public override void _Draw()
{
Heads.Clear();
var w = _session?.World;
if (w is null) return;
float s = MapScale.Symbol(_zoom);
var view = VisibleWorldRect().Grow(400 * s);
int smokeUsed = 0;
foreach (var (id, motion) in w.Motions)
{
if (!w.Trains.TryGetValue(id, out var train) || train.State == (byte)TrainState.InDepot) continue;
double total = ClientWorld.TotalLength(motion);
double head = Math.Min(motion.HeadDistance + motion.Speed * Elapsed(id, w), total);
var headPoint = w.PointAlong(motion, head);
if (headPoint is null || !view.HasPoint(MapScale.V(headPoint.Value))) continue;
Heads[id] = MapScale.V(headPoint.Value);
double d = head;
bool first = true;
foreach (int vid in train.Vehicles)
{
if (!w.Vehicles.TryGetValue(vid, out var v) || !_defs.TryGetValue(v.Type, out var def)) continue;
float length = DrawLength(def) * s;
var front = w.PointAlong(motion, Math.Max(0, d));
var back = w.PointAlong(motion, Math.Max(0, d - length));
if (front is null || back is null) break;
var f = MapScale.V(front.Value);
var b = MapScale.V(back.Value);
if (f.DistanceTo(b) < length * 0.9f)
{
// la coda esce dai tratti noti: si prolunga all'indietro lungo la direzione del binario
var ahead = w.PointAlong(motion, Math.Min(total, Math.Max(0, d) + 5));
var dir = ahead is { } ap && MapScale.V(ap).DistanceTo(f) > 0.01f ? (MapScale.V(ap) - f).Normalized()
: (f - b).LengthSquared() > 0.0001f ? (f - b).Normalized() : Vector2.Right;
if (ahead is { } ap2 && MapScale.V(ap2).DistanceTo(f) <= 0.01f && (f - b).LengthSquared() > 0.0001f) dir = (f - b).Normalized();
b = f - dir * length;
}
DrawVehicle(def, v, f, b, s, id == SelectedTrain);
if (first && def.Kind == VehicleKind.Locomotive && def.Traction == Traction.Steam && motion.Speed > 0.5f && smokeUsed < 24)
PlaceSmoke(smokeUsed++, f.Lerp(b, 0.25f), s);
first = false;
d -= length + 1.5f * s;
if (d < 0) break;
}
if (motion.Condition < 40)
{
// icona d'avviso: triangolo ambra sopra la testa
var p = MapScale.V(headPoint.Value) + new Vector2(0, -16 * s);
DrawColoredPolygon([p + new Vector2(0, -6 * s), p + new Vector2(6 * s, 5 * s), p + new Vector2(-6 * s, 5 * s)], Palette.Amber);
DrawLine(p + new Vector2(0, -2.5f * s), p + new Vector2(0, 1.5f * s), Palette.AppBackground, 1.4f * s);
}
}
for (int i = smokeUsed; i < _smoke.Count; i++) _smoke[i].Emitting = false;
}
private static float DrawLength(VehicleDef def) => def.Kind switch
{
VehicleKind.Locomotive => (float)Math.Clamp(def.LengthM * 1.25, 20, 26),
VehicleKind.Coach => 20f,
_ => 16f,
};
private void DrawVehicle(VehicleDef def, VehicleInfo v, Vector2 front, Vector2 back, float s, bool selected)
{
var center = (front + back) / 2;
var dir = front - back;
float length = dir.Length();
DrawSetTransform(center, dir.Angle());
float width = 9f * s;
var rect = new Rect2(-length / 2, -width / 2, length, width);
Color body = def.Kind switch
{
VehicleKind.Locomotive => new Color("1d2226"),
VehicleKind.Coach => def.Class == PaxClass.Staff ? Palette.Staff : Palette.Workers,
_ => def.WagonType switch
{
WagonType.Hopper => new Color("6b4a3a"),
WagonType.Flat => new Color("8a8f94"),
WagonType.Tank => new Color("4b5258"),
_ => new Color("8a5a44"),
},
};
if (v.Condition < 40) body = body.Lerp(Palette.Danger, 0.45f);
DrawRect(new Rect2(rect.Position + new Vector2(1.2f, 1.2f) * s, rect.Size), new Color(0, 0, 0, 0.25f));
DrawRect(rect, body);
DrawRect(rect, selected ? Palette.Amber : body.Darkened(0.35f), false, (selected ? 1.1f : 0.6f) * s);
switch (def.Kind)
{
case VehicleKind.Locomotive:
// cabina ambra verso la coda, caldaia e fanale verso la testa
DrawRect(new Rect2(-length / 2 + 1.5f * s, -width / 2 + 1.2f * s, 4.5f * s, width - 2.4f * s), Palette.Amber);
DrawCircle(new Vector2(length / 2 - 3.5f * s, 0), 1.8f * s, Palette.AmberLight);
DrawLine(new Vector2(-length / 2 + 7 * s, 0), new Vector2(length / 2 - 6 * s, 0), body.Lightened(0.15f), 1f * s);
break;
case VehicleKind.Coach:
for (float x = -length / 2 + 3 * s; x < length / 2 - 2 * s; x += 3.2f * s)
DrawRect(new Rect2(x, -width / 2 + 1.2f * s, 1.8f * s, 1.4f * s), Colors.White.Lerp(body, 0.4f));
break;
default:
if (def.WagonType == WagonType.Hopper)
DrawRect(new Rect2(-length / 2 + 2 * s, -width / 2 + 1.5f * s, length - 4 * s, width - 3 * s), body.Darkened(0.3f));
else if (def.WagonType == WagonType.Tank)
DrawCircle(Vector2.Zero, width * 0.35f, body.Lightened(0.15f));
break;
}
DrawSetTransform(Vector2.Zero, 0);
}
private void PlaceSmoke(int index, Vector2 at, float s)
{
while (_smoke.Count <= index)
{
var gradient = new Gradient();
gradient.SetColor(0, new Color(0.92f, 0.92f, 0.9f, 0.55f));
gradient.SetColor(1, new Color(0.92f, 0.92f, 0.9f, 0f));
var material = new ParticleProcessMaterial
{
Direction = new Vector3(1, -1, 0),
Spread = 25,
InitialVelocityMin = 6,
InitialVelocityMax = 12,
Gravity = new Vector3(4, -2, 0),
ScaleMin = 0.8f,
ScaleMax = 1.6f,
ColorRamp = new GradientTexture1D { Gradient = gradient },
};
var p = new GpuParticles2D { Amount = 16, Lifetime = 1.6, ProcessMaterial = material, Texture = SmokePuff(), ZIndex = 6, LocalCoords = false };
AddChild(p);
_smoke.Add(p);
}
var smoke = _smoke[index];
smoke.Position = at;
smoke.Scale = new Vector2(s, s) * 0.25f;
smoke.Emitting = true;
}
private static Texture2D? _puff;
private static Texture2D SmokePuff()
{
if (_puff is not null) return _puff;
const int n = 32;
var img = Image.CreateEmpty(n, n, false, Image.Format.Rgba8);
for (int y = 0; y < n; y++)
{
for (int x = 0; x < n; x++)
{
float dx = (x + 0.5f) / n * 2 - 1, dy = (y + 0.5f) / n * 2 - 1;
float a = Math.Clamp(1 - MathF.Sqrt(dx * dx + dy * dy), 0, 1);
img.SetPixel(x, y, new Color(1, 1, 1, a * a));
}
}
return _puff = ImageTexture.CreateFromImage(img);
}
private Rect2 VisibleWorldRect()
{
var canvas = GetCanvasTransform().AffineInverse();
var size = GetViewportRect().Size;
var a = canvas * Vector2.Zero;
var b = canvas * size;
return new Rect2(a, b - a).Abs();
}
}
@@ -0,0 +1 @@
uid://dsfaatx2pgfka