Infrastruttura: nome «Rail Enterprise», CI e rilasci su Gitea, documentazione
CI / Build e test (pull_request) Successful in 1m20s
CI / Immagine Docker (pull_request) Successful in 37s

Il progetto adotta il nome «Rail Enterprise» ovunque (codice RailEnterprise.*,
variabili RE_*, intestazioni RESV/RECL, immagine rail-enterprise-server) per
allinearsi al repository Gitea. Aggiunge Gitea Actions sul modello di Chronos:
CI su PR e main, rilascio da tag con gioco Windows (client Godot + server in
server/), server Windows/Linux e immagine Docker nel registro Gitea, nightly.
Aggiunge i riferimenti visivi 06–09, i modelli di PR e issue, l'ADR 0014 e
aggiorna README (comandi locali), STATE e CLAUDE.md. 120 test verdi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-07 11:14:54 +01:00
1 parent f6c2a17b4d
commit c1a0049bcf
300 files changed
+1602 -1045

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -0,0 +1,63 @@
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Rail;
namespace RailEnterprise.Core.Simulation.Ai;
/// <summary>Tipo di progetto di un'IA: merci da un produttore a un consumatore o pendolari da una città.</summary>
public enum AiProjectKind : byte { Freight = 0, Commuter = 1 }
/// <summary>Fase di un progetto: cantieri, acquisto dei treni, esercizio o abbandono.</summary>
public enum AiProjectStage : byte { Construction = 0, Equip = 1, Running = 2, Abandoned = 3 }
/// <summary>Linea costruita (o in costruzione) da un'IA e ciò che serve a seguirla.</summary>
public sealed class AiProject
{
public required int Id { get; init; }
public required AiProjectKind Kind { get; init; }
/// <summary>Bene trasportato (merci) o −1.</summary>
public int Good { get; init; } = -1;
/// <summary>Classe dei pendolari (0 operai, 1 tecnici) per i progetti di pendolarismo.</summary>
public int PaxClass { get; init; }
public required long Key { get; init; }
public StationId StationA { get; set; } = StationId.None;
public StationId StationB { get; set; } = StationId.None;
public DepotId Depot { get; set; } = DepotId.None;
public List<EdgeId> Edges { get; } = [];
public LineId Line { get; set; } = LineId.None;
public List<TrainId> Trains { get; } = [];
public AiProjectStage Stage { get; set; }
public long StartDay { get; init; }
public long CapitalCents { get; init; }
public long RevenuePerYearCents { get; init; }
public int TrainsPlanned { get; set; }
public required string Loco { get; init; }
public required string Car { get; init; }
public int CarsPerTrain { get; init; }
/// <summary>Giorno prima del quale non si aggiungono treni (dopo uno stallo risolto).</summary>
public long GrowAfterDay { get; set; }
/// <summary>Deposito rifornito di ricambi da questa linea (progetti di supporto), o None.</summary>
public DepotId SupplyFor { get; init; } = DepotId.None;
}
/// <summary>Stato persistente dell'agente IA di una compagnia (12.1).</summary>
public sealed class AiState
{
public required CompanyId Company { get; init; }
/// <summary>Giorno del mese (0-based) in cui l'IA pianifica.</summary>
public int PlanDay { get; init; }
public long Issued { get; set; }
public long Rejected { get; set; }
public bool PolicySet { get; set; }
public int NextProjectId { get; set; }
public List<AiProject> Projects { get; } = [];
/// <summary>Chiavi dei candidati scartati (percorso o piano non validi), i più recenti in coda.</summary>
public List<long> Failed { get; } = [];
/// <summary>Offerte pubbliche a cui l'IA ha già risposto come bersaglio.</summary>
public List<int> Responded { get; } = [];
public int LastIndustryYear { get; set; } = int.MinValue;
/// <summary>Ultimo giorno in cui l'IA ha sciolto uno stallo (uno ogni tanto, non a cascata).</summary>
public long LastGridlockDay { get; set; } = -1_000_000;
/// <summary>Quota dei comandi rifiutati sul totale emesso.</summary>
public double RejectedShare => Issued == 0 ? 0 : (double)Rejected / Issued;
}
@@ -0,0 +1,49 @@
namespace RailEnterprise.Core.Simulation.Ai;
/// <summary>
/// Agenti delle compagnie IA (12.1), dopo la borsa: ogni giorno seguono progetti e offerte, una
/// volta al mese (in giorni diversi per ciascuna IA) pianificano. Le IA agiscono solo con i comandi.
/// </summary>
public sealed class AiSystem : ISimSystem
{
public string Name => "AiAgents";
/// <summary>Diagnostica facoltativa (strumenti): non influisce sulla simulazione.</summary>
public static Action<string>? Trace { get; set; }
private readonly GridPath _path = new();
public void Step(WorldContext ctx)
{
if (!ctx.IsNewDay) return;
var w = ctx.World;
if (w.AiPaused) return;
EnsureStates(w);
int dpm = w.Calendar.DaysPerMonth;
foreach (var s in w.AiStates)
{
var c = w.Company(s.Company);
if (c.Defunct) continue;
var agent = new AiAgent(w, ctx, s, _path);
agent.Daily();
if (ctx.Day % dpm == s.PlanDay) agent.Monthly();
}
}
/// <summary>Uno stato per ogni compagnia IA (anche per i nuovi concorrenti), in ordine di id.</summary>
public static void EnsureStates(World w)
{
if (w.AiStates.Count == w.Companies.Count(c => !c.IsPlayer)) return;
int dpm = w.Calendar.DaysPerMonth;
foreach (var c in w.Companies)
{
if (c.IsPlayer || w.AiStates.Any(s => s.Company == c.Id)) continue;
int index = w.AiStates.Count;
w.AiStates.Add(new AiState
{
Company = c.Id,
PlanDay = (1 + index * w.Data.Ai.Planning.PlanningDaySpacing) % dpm,
});
}
}
}
@@ -0,0 +1,381 @@
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Map;
namespace RailEnterprise.Core.Simulation.Ai;
/// <summary>
/// Percorso di un nuovo binario per le IA (12.1): Dijkstra sulla griglia delle celle in un
/// riquadro attorno ai due estremi, con costo = costo di costruzione della cella (modificatori del
/// terreno, acqua da superare con un ponte) + penalità di pendenza; città, industrie e mare non si
/// attraversano. Il percorso si semplifica in una polilinea (Douglas–Peucker).
/// </summary>
public sealed class GridPath
{
private double[] _dist = [];
private int[] _prev = [];
private readonly PriorityQueue<int, double> _queue = new();
// regioni collegabili (componenti connesse delle celle attraversabili) per la campata dell'epoca
private int[] _region = [];
private double _regionSpan = -1;
private int _regionCells = -1;
// celle con binari della compagnia (non si incrociano a raso), ricalcolate quando cambia la rete
private bool[] _ownTrack = [];
private int _ownTrackCompany = -1;
private int _ownTrackEdges = -1;
private long _ownTrackVersion = -1;
private static double MaxSpan(World w)
{
double maxSpan = 0;
foreach (var b in w.Data.Eras.BridgeTypes)
{
if (b.From <= w.Clock.Year) maxSpan = Math.Max(maxSpan, b.MaxSpanM);
}
return maxSpan;
}
private static bool Passable(World w, int x, int y, double maxSpan, double[] riverWidths)
{
var t = w.Terrain;
switch (t.TypeAt(x, y))
{
case CellType.Sea:
case CellType.Town:
case CellType.Industry:
return false;
case CellType.Water:
int cls = t.RiverWidth[y * t.Width + x];
return cls > 0 && riverWidths[Math.Min(cls, riverWidths.Length) - 1] <= maxSpan;
default:
return true;
}
}
/// <summary>
/// Vero se i due punti stanno nella stessa regione collegabile con i ponti dell'epoca
/// (verifica rapida prima della ricerca del percorso).
/// </summary>
public bool SameRegion(World w, Vec2 a, Vec2 b)
{
var t = w.Terrain;
double span = MaxSpan(w);
if (span != _regionSpan || _regionCells != t.Width * t.Height) BuildRegions(w, span);
int ra = RegionNear(w, a), rb = RegionNear(w, b);
return ra >= 0 && ra == rb;
}
private int RegionNear(World w, Vec2 p)
{
var t = w.Terrain;
var (cx, cy) = t.CellAt(p);
for (int r = 0; r <= 2; r++)
{
for (int dy = -r; dy <= r; dy++)
{
for (int dx = -r; dx <= r; dx++)
{
int x = cx + dx, y = cy + dy;
if (!t.InBounds(x, y)) continue;
int label = _region[y * t.Width + x];
if (label >= 0) return label;
}
}
}
return -1;
}
private void BuildRegions(World w, double span)
{
var t = w.Terrain;
var riverWidths = w.Data.Construction.Profile.RiverWidthMByClass;
int n = t.Width * t.Height;
_region = new int[n];
Array.Fill(_region, -1);
var stack = new Stack<int>();
int next = 0;
for (int i = 0; i < n; i++)
{
if (_region[i] >= 0 || !Passable(w, i % t.Width, i / t.Width, span, riverWidths)) continue;
_region[i] = next;
stack.Push(i);
while (stack.Count > 0)
{
int c = stack.Pop();
int cx = c % t.Width, cy = c / t.Width;
for (int k = 0; k < 4; k++)
{
int nx = cx + (k == 0 ? 1 : k == 1 ? -1 : 0), ny = cy + (k == 2 ? 1 : k == 3 ? -1 : 0);
if (!t.InBounds(nx, ny)) continue;
int ni = ny * t.Width + nx;
if (_region[ni] >= 0 || !Passable(w, nx, ny, span, riverWidths)) continue;
_region[ni] = next;
stack.Push(ni);
}
}
next++;
}
_regionSpan = span;
_regionCells = n;
}
private void BuildOwnTrack(World w, CompanyId company)
{
var t = w.Terrain;
int n = t.Width * t.Height;
if (_ownTrack.Length != n) _ownTrack = new bool[n];
else Array.Clear(_ownTrack);
foreach (var e in w.Network.Edges)
{
if (e.Owner != company || e.State == Rail.EdgeState.Demolished) continue;
for (int i = 0; i < e.X.Length; i++)
{
var (cx, cy) = t.CellAt(new Vec2(e.X[i], e.Y[i]));
_ownTrack[cy * t.Width + cx] = true;
}
}
_ownTrackCompany = company.Value;
_ownTrackEdges = w.Network.Edges.Count;
_ownTrackVersion = w.Network.Version;
}
/// <summary>Polilinea in metri da <paramref name="from"/> a <paramref name="to"/>, o null se irraggiungibile.</summary>
public List<Vec2>? Find(World w, CompanyId company, Vec2 from, Vec2 to, double marginKm, double toleranceM, double minRadiusM)
{
var t = w.Terrain;
if (!SameRegion(w, from, to)) return null;
if (_ownTrackCompany != company.Value || _ownTrackEdges != w.Network.Edges.Count || _ownTrackVersion != w.Network.Version)
BuildOwnTrack(w, company);
var plan = w.Data.Ai.Planning;
var costs = w.Data.Construction.Costs;
var (ax, ay) = t.CellAt(from);
var (bx, by) = t.CellAt(to);
int margin = (int)Math.Ceiling(marginKm * 1000 / t.CellSizeM);
int x0 = Math.Max(0, Math.Min(ax, bx) - margin), x1 = Math.Min(t.Width - 1, Math.Max(ax, bx) + margin);
int y0 = Math.Max(0, Math.Min(ay, by) - margin), y1 = Math.Min(t.Height - 1, Math.Max(ay, by) + margin);
int bw = x1 - x0 + 1, bh = y1 - y0 + 1, n = bw * bh;
if (_dist.Length < n)
{
_dist = new double[n];
_prev = new int[n];
}
Array.Fill(_dist, double.PositiveInfinity, 0, n);
Array.Fill(_prev, -1, 0, n);
_queue.Clear();
// fiumi attraversabili con i ponti dell'epoca (larghezza dell'alveo della classe ≤ campata massima)
double maxSpan = 0;
foreach (var b in w.Data.Eras.BridgeTypes)
{
if (b.From <= w.Clock.Year) maxSpan = Math.Max(maxSpan, b.MaxSpanM);
}
var riverWidths = w.Data.Construction.Profile.RiverWidthMByClass;
// pendenza massima della trazione più permissiva disponibile: le celle più ripide costano molto
// (il pianificatore compensa solo piccoli dislivelli con trincee e rilevati)
var g = w.Data.Construction.MaxGradientByTraction;
double gMax = g.Steam;
if (w.Clock.Year >= w.Data.Eras.Eras.First(e => e.Id == "diesel").From) gMax = Math.Max(gMax, g.Diesel);
int start = (ay - y0) * bw + (ax - x0), goal = (by - y0) * bw + (bx - x0);
_dist[start] = 0;
_queue.Enqueue(start, 0);
double cs = t.CellSizeM;
ReadOnlySpan<int> dxs = [1, -1, 0, 0, 1, 1, -1, -1];
ReadOnlySpan<int> dys = [0, 0, 1, -1, 1, -1, 1, -1];
while (_queue.TryDequeue(out int cur, out double d))
{
if (d > _dist[cur]) continue;
if (cur == goal) break;
int cx = cur % bw + x0, cy = cur / bw + y0;
double hc = t.Heights[cy * t.Width + cx] / 10.0;
for (int k = 0; k < 8; k++)
{
int nx = cx + dxs[k], ny = cy + dys[k];
if (nx < x0 || nx > x1 || ny < y0 || ny > y1) continue;
int ni = (ny - y0) * bw + (nx - x0);
bool endpoint = ni == goal;
var type = t.TypeAt(nx, ny);
if (type == CellType.Water)
{
int cls = t.RiverWidth[ny * t.Width + nx];
if (cls <= 0 || riverWidths[Math.Min(cls, riverWidths.Length) - 1] > maxSpan) continue;
}
double cellCost = CellCost(type, costs, plan, endpoint);
if (double.IsPositiveInfinity(cellCost)) continue;
// i propri binari non si incrociano a raso: ci si aggancia solo vicino agli estremi
if (_ownTrack[ny * t.Width + nx] && Vec2.Distance(t.CellCenter(nx, ny), from) > 300 && Vec2.Distance(t.CellCenter(nx, ny), to) > 300) continue;
double step = k < 4 ? 1.0 : 1.41421356237;
double hn = t.Heights[ny * t.Width + nx] / 10.0;
double grade = Math.Abs(hn - hc) / (step * cs);
double steep = grade > gMax * plan.SteepGradeFactor ? plan.SteepPenalty : 0;
double nd = d + step * (cellCost + steep) + plan.PathSlopePenalty * grade * step;
if (nd >= _dist[ni]) continue;
_dist[ni] = nd;
_prev[ni] = cur;
_queue.Enqueue(ni, nd);
}
}
if (double.IsPositiveInfinity(_dist[goal]))
{
int reached = 0;
for (int i = 0; i < n; i++) if (!double.IsPositiveInfinity(_dist[i])) reached++;
AiSystem.Trace?.Invoke($" percorso: obiettivo non raggiunto, celle raggiunte {reached} su {n}, partenza {t.TypeAt(ax, ay)} arrivo {t.TypeAt(bx, by)} binari propri vicino all'arrivo {_ownTrack[by * t.Width + bx]}");
return null;
}
var cells = new List<Vec2>();
for (int c = goal; c >= 0; c = _prev[c]) cells.Add(t.CellCenter(c % bw + x0, c / bw + y0));
cells.Reverse();
cells[0] = from;
cells[^1] = to;
bool Clear(Vec2 a, Vec2 b) => SegmentClear(w, a, b, from, to, maxSpan, riverWidths);
return EnforceRadius(Simplify(cells, toleranceM, Clear), minRadiusM * 1.05, Clear);
}
/// <summary>
/// Il segmento non attraversa città, industrie, mare o fiumi troppo larghi per i ponti dell'epoca
/// (a parte i primi e gli ultimi 200 m, dove stanno le stazioni).
/// </summary>
private static bool SegmentClear(World w, Vec2 a, Vec2 b, Vec2 from, Vec2 to, double maxSpan, double[] riverWidths)
{
var t = w.Terrain;
double len = Vec2.Distance(a, b);
int steps = Math.Max(1, (int)Math.Ceiling(len / 25));
for (int i = 0; i <= steps; i++)
{
var p = Vec2.Lerp(a, b, (double)i / steps);
if (Vec2.Distance(p, from) < 200 || Vec2.Distance(p, to) < 200) continue;
var (cx, cy) = t.CellAt(p);
switch (t.TypeAt(cx, cy))
{
case CellType.Town:
case CellType.Industry:
case CellType.Sea:
return false;
case CellType.Water:
int cls = t.RiverWidth[cy * t.Width + cx];
if (cls <= 0 || riverWidths[Math.Min(cls, riverWidths.Length) - 1] > maxSpan) return false;
break;
}
}
return true;
}
/// <summary>
/// Toglie i vertici i cui raccordi al raggio minimo non entrano nei segmenti adiacenti
/// (tangente R·tan(θ/2) a ciascun estremo), finché la polilinea li ammette tutti.
/// </summary>
public static List<Vec2> EnforceRadius(List<Vec2> points, double radius, Func<Vec2, Vec2, bool>? clear = null)
{
var pts = new List<Vec2>(points);
while (pts.Count > 2)
{
int n = pts.Count;
var tangent = new double[n];
for (int i = 1; i < n - 1; i++)
{
var d1 = (pts[i] - pts[i - 1]).Normalized();
var d2 = (pts[i + 1] - pts[i]).Normalized();
double theta = Math.Abs(DMath.Atan2(Vec2.Cross(d1, d2), Math.Clamp(Vec2.Dot(d1, d2), -1, 1)));
tangent[i] = radius * DMath.Tan(theta / 2);
}
int worst = -1;
double worstExcess = 0;
for (int j = 0; j < n - 1; j++)
{
double excess = tangent[j] + tangent[j + 1] - Vec2.Distance(pts[j], pts[j + 1]);
if (excess <= worstExcess) continue;
// si toglie il vertice con il raccordo più lungo, se il segmento che resta è libero
int first = j == 0 ? 1 : j + 1 == n - 1 ? j : tangent[j] >= tangent[j + 1] ? j : j + 1;
int second = first == j ? j + 1 : j;
foreach (int k in new[] { first, second })
{
if (k <= 0 || k >= n - 1) continue;
if (clear is not null && !clear(pts[k - 1], pts[k + 1])) continue;
worstExcess = excess;
worst = k;
break;
}
}
if (worst < 0) break;
pts.RemoveAt(worst);
}
return pts;
}
/// <summary>Costo relativo di costruzione per cella (∞ = non attraversabile).</summary>
private static double CellCost(CellType type, ConstructionCosts costs, AiPlanningParams plan, bool endpoint)
{
switch (type)
{
case CellType.Sea:
return double.PositiveInfinity;
case CellType.Town:
case CellType.Industry:
return endpoint ? 1.0 : double.PositiveInfinity;
case CellType.Water:
return plan.PathWaterPenalty;
case CellType.Rock:
return costs.TerrainModifiers.GetValueOrDefault("rock", 1.0);
case CellType.Marsh:
return costs.TerrainModifiers.GetValueOrDefault("marsh", 1.0);
case CellType.Mountain:
return costs.TerrainModifiers.GetValueOrDefault("mountain", 1.0);
case CellType.Forest:
return costs.TerrainModifiers.GetValueOrDefault("forest", 1.0);
default:
return 1.0;
}
}
/// <summary>
/// Semplificazione di Douglas–Peucker (estremi conservati): un tratto si divide anche quando il
/// segmento semplificato attraverserebbe un ostacolo.
/// </summary>
public static List<Vec2> Simplify(List<Vec2> points, double tolerance, Func<Vec2, Vec2, bool>? clear = null)
{
if (points.Count <= 2) return [.. points];
var keep = new bool[points.Count];
keep[0] = keep[^1] = true;
var stack = new Stack<(int, int)>();
stack.Push((0, points.Count - 1));
while (stack.Count > 0)
{
var (a, b) = stack.Pop();
double best = -1;
int index = -1;
for (int i = a + 1; i < b; i++)
{
double d = SegmentDistance(points[i], points[a], points[b]);
if (d > best)
{
best = d;
index = i;
}
}
if (index >= 0 && (best > tolerance || (clear is not null && !clear(points[a], points[b]))))
{
keep[index] = true;
stack.Push((a, index));
stack.Push((index, b));
}
}
var result = new List<Vec2>();
for (int i = 0; i < points.Count; i++)
{
if (keep[i]) result.Add(points[i]);
}
return result;
}
private static double SegmentDistance(Vec2 p, Vec2 a, Vec2 b)
{
var ab = b - a;
double len2 = ab.LengthSquared;
if (len2 <= 0) return Vec2.Distance(p, a);
double u = Math.Clamp(Vec2.Dot(p - a, ab) / len2, 0, 1);
return Vec2.Distance(p, a + ab * u);
}
}