using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Rail;
using ViaFerrea.Core.Simulation.Systems;
namespace ViaFerrea.Core.Simulation.Ai;
///
/// Agente di una compagnia IA (12.1). Legge solo informazioni pubbliche del mondo e agisce
/// esclusivamente con i comandi del protocollo, eseguiti dallo stesso CommandProcessor dei
/// giocatori (stesse validazioni, stessi costi). Ogni giorno segue i progetti in corso e le
/// offerte pubbliche; una volta al mese pianifica: finanza, treni aggiuntivi, borsa, industrie e
/// al più un nuovo progetto con il ROI migliore sopra la soglia della personalità (ADR 0013).
///
internal sealed class AiAgent
{
/// Numeri di sequenza dei comandi delle IA (non vanno ai client).
public const uint SeqBase = 0x8000_0000;
private readonly World _w;
private readonly WorldContext _ctx;
private readonly AiState _s;
private readonly Company _c;
private readonly AiPersonalityDef _p;
private readonly AiPlanningParams _plan;
private readonly AiMarketParams _mk;
private readonly GridPath _path;
public AiAgent(World w, WorldContext ctx, AiState s, GridPath path)
{
_w = w;
_ctx = ctx;
_s = s;
_c = w.Company(s.Company);
_p = w.Data.Ai.Personalities.FirstOrDefault(p => p.Id == _c.AiPersonality) ?? w.Data.Ai.Personalities[0];
_plan = w.Data.Ai.Planning;
_mk = w.Data.Ai.Market;
_path = path;
}
private CommandResult Do(GameCommand command)
{
var cmd = command with { Issuer = _c.Id, Seq = SeqBase };
var result = CommandProcessor.Execute(_w, cmd, _ctx);
_s.Issued++;
if (!result.Ok)
{
_s.Rejected++;
AiSystem.Trace?.Invoke($"{_ctx.Day} {_c.Name}: RIFIUTATO {cmd.Type}: {result.Error} {result.Message}");
}
return result;
}
// ================================================================== giornaliero
public void Daily()
{
if (!_s.PolicySet)
{
Do(new SetMaintenancePolicyCommand(MaintenanceScope.Company, 0, PolicyId(_p.MaintenancePolicy)));
_s.PolicySet = true;
}
foreach (var project in _s.Projects)
{
switch (project.Stage)
{
case AiProjectStage.Construction:
AdvanceConstruction(project);
break;
case AiProjectStage.Equip:
Equip(project);
break;
}
}
BreakGridlock();
RespondToBids();
Liquidity();
}
///
/// Cassa negativa: prima della bancarotta l'IA usa tutto il fido e, se quotata, colloca altro capitale.
///
private void Liquidity()
{
if (!_c.Cash.IsNegative) return;
long need = -_c.Cash.Cents + Reserve() / 2;
if (Borrow(need, completing: true)) return;
if (_c.Listed && !_c.ControlledBy.IsValid)
{
double float_ = (double)_c.Shares.Public / _c.Shares.Total;
double share = Math.Min(_mk.IssueShare, _w.Data.Balance.StockMarket.SecondaryMaxFloat - float_);
if (share > 0.001 && _c.Shares.Founder > _c.Shares.Total * share) Do(new IpoCommand(share));
}
}
///
/// Stallo di capacità (8.4): se almeno due treni della compagnia aspettano via libera da più dei
/// giorni d'avviso, quello fermo da più tempo diventa riserva e rientra al deposito (libera binari
/// e marciapiedi, e coprirà le linee durante gli interventi lunghi).
///
private void BreakGridlock()
{
int waitDays = _w.Data.Construction.Operations.WaitWarningDays;
if (_ctx.Day - _s.LastGridlockDay < waitDays * 3) return;
long limit = (long)waitDays * _w.Calendar.TicksPerDay;
Train? oldest = null;
int stuck = 0;
foreach (var t in _w.Trains)
{
if (t.Owner != _c.Id || t.Removed) continue;
// un treno guasto in linea blocca chi lo segue finché arriva il soccorso: non è uno stallo
if (t.State == TrainState.Broken) return;
if (!t.Line.IsValid || t.State != TrainState.Waiting) continue;
if (_ctx.Tick - t.WaitingSinceTick < limit) continue;
stuck++;
if (oldest is null || t.WaitingSinceTick < oldest.WaitingSinceTick) oldest = t;
}
if (stuck < 2 || oldest is null) return;
if (!Do(new SetReserveCommand(oldest.Id, true)).Ok) return;
_s.LastGridlockDay = _ctx.Day;
foreach (var p in _s.Projects)
{
if (!p.Trains.Remove(oldest.Id)) continue;
p.TrainsPlanned = Math.Max(1, p.Trains.Count);
p.GrowAfterDay = _ctx.Day + _w.Calendar.DaysPerYear;
}
AiSystem.Trace?.Invoke($"{_ctx.Day} {_c.Name}: stallo con {stuck} treni fermi, {oldest.Name} diventa riserva");
if (AiSystem.Trace is { } tr)
{
foreach (var t in _w.Trains)
{
if (t.Owner != _c.Id || t.Removed) continue;
var step = t.RouteIndex < t.Route.Count ? t.Route[t.RouteIndex] : default;
string edge = "";
if (t.Route.Count > 0 && t.RouteIndex < t.Route.Count)
{
var e = _w.Network.Edges[step.Edge.Value];
edge = $"arco {e.Id.Value} {e.State} cond {e.Condition:0} strutt {e.StructureCondition:0} verso {e.LockDir}x{e.LockCount} blocchi [{string.Join(",", e.BlocksForward)}|{string.Join(",", e.BlocksBackward)}]";
}
tr($" {t.Name} {t.State} nodo {t.AtNode.Value} linea {t.Line.Value} fermata {t.StopIndex} percorso {t.RouteIndex}/{t.Route.Count} {edge} tiene {t.Held.Count} attesa {(_ctx.Tick - t.WaitingSinceTick) / _w.Calendar.TicksPerDay} g, deposito {t.GoingToDepot.Value}");
}
}
}
private static string PolicyId(MaintenancePolicy policy) => policy switch
{
MaintenancePolicy.Economy => "economy",
MaintenancePolicy.Thorough => "thorough",
_ => "standard",
};
private void AdvanceConstruction(AiProject project)
{
bool done = true;
foreach (var id in project.Edges)
{
var e = _w.Network.Edges[id.Value];
if (e.State == EdgeState.Demolished)
{
project.Stage = AiProjectStage.Abandoned;
return;
}
if (e.State != EdgeState.Active) done = false;
}
if (done) project.Stage = AiProjectStage.Equip;
}
private void Equip(AiProject project)
{
if (!project.Line.IsValid)
{
var a = _w.Network.Stations[project.StationA.Value];
var b = _w.Network.Stations[project.StationB.Value];
var r = Do(new CreateLineCommand($"{a.Name} – {b.Name}", _c.Color,
[new LineStop(project.StationA), new LineStop(project.StationB)]));
if (!r.Ok)
{
project.Stage = AiProjectStage.Abandoned;
return;
}
project.Line = new LineId(r.Created[0]);
}
while (project.Trains.Count < project.TrainsPlanned)
{
if (!BuyTrain(project)) return;
}
project.Stage = AiProjectStage.Running;
}
/// Compra locomotiva e carri nel deposito del progetto, compone il treno e lo assegna alla linea.
private bool BuyTrain(AiProject project)
{
var loco = _w.Data.Vehicle(project.Loco);
var car = _w.Data.Vehicle(project.Car);
long price = Estimators.TrainPrice(loco, car, project.CarsPerTrain);
if (_c.Cash.Cents < price + Reserve() / 2 && !Borrow(price + Reserve() / 2 - _c.Cash.Cents, completing: project.Trains.Count == 0)) return false;
var ids = new List();
var rl = Do(new BuyVehicleCommand(project.Loco, project.Depot, 1));
if (!rl.Ok) return false;
ids.AddRange(rl.Created.Select(i => new VehicleId(i)));
var rc = Do(new BuyVehicleCommand(project.Car, project.Depot, project.CarsPerTrain));
if (!rc.Ok) return false;
ids.AddRange(rc.Created.Select(i => new VehicleId(i)));
var rt = Do(new ComposeTrainCommand(project.Depot, ids));
if (!rt.Ok) return false;
var train = new TrainId(rt.Created[0]);
if (!Do(new AssignTrainCommand(train, project.Line)).Ok) return false;
project.Trains.Add(train);
return true;
}
// ================================================================== mensile
public void Monthly()
{
if (AiSystem.Trace is { } trace)
{
int last = (_c.ProfitRingIndex + 11) % 12;
trace($"{_ctx.Day} {_c.Name}: cassa {_c.Cash}, debito {_c.Debt}, utile del mese {new Money(_c.ProfitRing[last])}, " +
$"ricavi anno {new Money(Company.Revenue(_c.YearEntries))}, costi esercizio anno {new Money(_c.YearEntries[(int)LedgerEntry.RunningCosts])}, " +
$"manutenzione {new Money(_c.YearEntries[(int)LedgerEntry.FleetMaintenance])}, binari {new Money(_c.YearEntries[(int)LedgerEntry.TrackMaintenance])}, interessi {new Money(_c.YearEntries[(int)LedgerEntry.Interest])}, " +
$"progetti {string.Join(",", _s.Projects.Select(p => $"{p.Stage}:{p.Trains.Count}"))}");
int pax = 0, contracts = 0;
foreach (var cc in _w.Commutes)
{
if (cc.Carrier != _c.Id) continue;
contracts++;
pax += cc.Headcount;
}
var states = string.Join(",", _w.Trains.Where(t => t.Owner == _c.Id && !t.Removed).Select(t => $"{t.State}/{Fleet.TrainCondition(_w, t):0}"));
var depots = string.Join(",", _w.Network.Depots.Where(d => d.Owner == _c.Id).Select(d => $"{d.SpareParts}/{d.PartsTarget} lavori {d.Jobs.Count}"));
trace($"{_ctx.Day} {_c.Name}: pendolari {pax} in {contracts} contratti, treni {states}, depositi {depots}");
foreach (var cc in _w.Commutes)
{
if (cc.Carrier == _c.Id)
trace($"{_ctx.Day} {_c.Name}: contratto {cc.Id.Value} {cc.Category} {cc.Headcount} pers., copertura {cc.Coverage:0.00}, giorni bassi {cc.LowCoverageDays}, {cc.ExpectedMinutes:0} min, arrivati oggi {cc.ArrivedToday}");
}
}
Finance();
GrowLines();
StockMarket();
BuyIndustries();
if (!EnsurePartsSupply()) NewProject();
}
// ================================================================== ricambi (10.2)
///
/// Ogni deposito con treni in servizio deve ricevere ricambi via treno: se non c'è ancora una
/// linea che li porta, l'IA ne costruisce una da un hub o da una fabbrica di macchinari alla
/// stazione del deposito, anche sotto la soglia di ROI (è un costo di esercizio). Restituisce
/// true se ha aperto un cantiere (niente altri progetti questo mese).
///
private bool EnsurePartsSupply()
{
int good = _w.Data.SparePartsGood;
if (_s.Projects.Any(p => p.SupplyFor.IsValid && p.Stage is AiProjectStage.Construction or AiProjectStage.Equip)) return false;
foreach (var depot in _w.Network.Depots)
{
if (depot.Owner != _c.Id || !_w.Network.IsAlive(depot)) continue;
if (_s.Projects.Any(p => p.SupplyFor == depot.Id && p.Stage != AiProjectStage.Abandoned)) continue;
if (!_s.Projects.Any(p => p.Depot == depot.Id && p.Stage == AiProjectStage.Running)) continue;
// stazione della compagnia che ha il deposito nel bacino
Station? home = null;
foreach (var st in _w.Network.Stations)
{
if (st.Owner == _c.Id && _w.Network.IsAlive(st) && st.Depots.Contains(depot.Id))
{
home = st;
break;
}
}
if (home is null) continue;
// una fonte nel bacino della stazione del deposito basta (trasbordo nel bacino)
if (home.Hubs.Count > 0 || home.Industries.Any(i => !_w.Industries[i.Value].Closed && _w.Industries[i.Value].OutputIndexOf(good) >= 0)) continue;
// fonti: hub (importano ricambi) e industrie che li producono, la più vicina prima
var sources = new List<(Vec2 Pos, long Key, double Km)>();
foreach (var hub in _w.Hubs)
sources.Add((hub.Position, KeyOf(AiProjectKind.Freight, good, (2 << 22) | hub.Id.Value, depot.Id.Value), Vec2.Distance(hub.Position, home.Position) / 1000));
foreach (var ind in _w.Industries)
{
if (ind.Closed || ind.Level <= 0 || ind.OutputIndexOf(good) < 0) continue;
sources.Add((ind.Position, KeyOf(AiProjectKind.Freight, good, ind.Id.Value, depot.Id.Value), Vec2.Distance(ind.Position, home.Position) / 1000));
}
sources.Sort((a, b) => a.Km != b.Km ? a.Km.CompareTo(b.Km) : a.Key.CompareTo(b.Key));
var loco = Estimators.BestLocomotive(_w, _ctx.Year);
if (loco is null) return false;
long budget = _c.Cash.Cents - Reserve() / 2 + LoanRoom();
int tried = 0;
foreach (var (pos, key, km) in sources)
{
if (tried >= 3 || km > _plan.CandidateMaxDistanceKm * 1.5) break;
if (Known(key)) continue;
tried++;
var cand = new Candidate
{
Kind = AiProjectKind.Freight, Key = key, Good = good,
SourcePos = pos, DestPos = home.Position, SourceIsTown = false, DestIsTown = false,
StraightKm = km, UnitsPerYear = _w.Data.Maintenance.Depots.TargetSpareParts * 2, RoughScore = 0,
};
var proposal = Evaluate(cand, loco, supply: depot.Id);
if (proposal is null)
{
Remember(key);
continue;
}
AiSystem.Trace?.Invoke($"{_ctx.Day} {_c.Name}: linea dei ricambi per {depot.Name}: {km:0.0} km, capitale {new Money(proposal.Capital)} (budget {new Money(budget)})");
if (proposal.Capital > budget) return false;
Execute(proposal, depot.Id);
return true;
}
}
return false;
}
/// Riserva di cassa: mesi di costi d'esercizio stimati dalla flotta e dalla rete.
private long Reserve()
{
double yearly = 0;
foreach (var v in _w.Vehicles)
{
if (v.Owner == _c.Id && !v.Sold) yearly += v.Def.RunningCostPerYear * (1 + _plan.MaintenanceCostShare);
}
var sp = _w.Data.Construction.Stations;
foreach (var s in _w.Network.Stations)
{
if (s.Owner == _c.Id && _w.Network.IsAlive(s)) yearly += s.Platforms * sp.UpkeepPerPlatformPerYear;
}
foreach (var l in _c.Loans) yearly += FinanceSystem.MonthlyPayment(l.Remaining, l.AnnualRate, l.MonthsLeft).Cents * 12.0;
return (long)(yearly / 12 * _plan.CashReserveMonths);
}
/// Prestito disponibile entro la quota del fido della personalità.
private long LoanRoom()
{
if (_c.Receivership) return 0;
long max = (long)(FinanceSystem.MaxLoan(_w, _c).Cents * _p.LoanShareOfCredit);
return Math.Max(0, max - _c.Debt.Cents);
}
/// Chiede un prestito (a gradini) per almeno l'importo indicato, se la personalità lo consente.
private bool Borrow(long amount, bool completing = false)
{
if (amount <= 0) return true;
long step = Math.Max(1, _w.Data.Balance.Finance.LoanStep);
long request = (amount + step - 1) / step * step;
// per completare una linea già costruita (il primo treno) si usa tutto il fido disponibile
long room = completing && !_c.Receivership ? Math.Max(0, FinanceSystem.MaxLoan(_w, _c).Cents - _c.Debt.Cents) : LoanRoom();
if (room < amount) return false;
request = Math.Min(request, room);
return Do(new TakeLoanCommand(new Money(request))).Ok;
}
private void Finance()
{
// cassa abbondante: rimborsa i prestiti più cari
long reserve = Reserve();
long surplus = _c.Cash.Cents - (long)(reserve * _plan.RepayCashMonths / Math.Max(1, _plan.CashReserveMonths));
foreach (var loan in _c.Loans.OrderByDescending(l => l.AnnualRate).ThenBy(l => l.Id.Value).ToList())
{
if (surplus <= 0) break;
long pay = Math.Min(surplus, loan.Remaining.Cents);
if (pay <= 0) continue;
if (Do(new RepayLoanCommand(loan.Id, new Money(pay))).Ok) surplus -= pay;
}
// cassa scarsa: aumento di capitale in borsa (fino al flottante massimo)
if (_c.Listed && _c.Cash.Cents < reserve && !_c.ControlledBy.IsValid)
{
double float_ = (double)_c.Shares.Public / _c.Shares.Total;
double share = Math.Min(_mk.IssueShare, _mk.IssueFloatMax - float_);
if (share > 0.001 && _c.Shares.Founder > _c.Shares.Total * share) Do(new IpoCommand(share));
}
}
/// Aggiunge un treno alle linee dove la merce in attesa supera più carichi pieni.
private void GrowLines()
{
foreach (var project in _s.Projects)
{
if (project.Stage != AiProjectStage.Running || project.SupplyFor.IsValid || project.Trains.Count >= _plan.MaxTrainsPerLine
|| _ctx.Day < project.GrowAfterDay) continue;
if (!project.StationA.IsValid) continue;
var a = _w.Network.Stations[project.StationA.Value];
if (!_w.Network.IsAlive(a)) continue;
var car = _w.Data.Vehicle(project.Car);
int perTrip = (car.Capacity ?? car.PaxCapacity ?? 0) * project.CarsPerTrain;
long waiting = 0;
foreach (var pk in a.Waiting)
{
if (pk.HopLine == project.Line) waiting += pk.Units;
}
if (perTrip <= 0 || waiting < perTrip * _plan.AddTrainWaitingTrips) continue;
var b = _w.Network.Stations[project.StationB.Value];
if (StationLoad(a.Id) + 1 > a.Platforms - 1 || StationLoad(b.Id) + 1 > b.Platforms - 1) continue;
project.TrainsPlanned = project.Trains.Count + 1;
BuyTrain(project);
project.TrainsPlanned = project.Trains.Count;
return; // un treno al mese
}
}
// ================================================================== borsa (12.2)
private void StockMarket()
{
// fusione delle controllate dopo il periodo minimo
var sm = _w.Data.Balance.StockMarket;
foreach (var other in _w.Companies)
{
if (other.Defunct || other.ControlledBy != _c.Id || other.IsPlayer) continue;
if (_ctx.Day - other.ControlSinceDay < sm.MergeAfterDays) continue;
double minority = (other.Shares.Outstanding - other.Shares.Of(_c.Id)) * other.SharePrice;
if (_c.Cash.Cents > minority + Reserve()) Do(new MergeCompanyCommand(other.Id));
}
if (!_p.BuysShares) return;
// la Predatoria accumula quote dei concorrenti quotati (prima il giocatore) e poi lancia l'offerta;
// solo con una rete che rende e cassa abbondante, e solo in compagnie in utile
if (!_s.Projects.Any(p => p.Stage == AiProjectStage.Running) || _c.AnnualProfit <= 0) return;
long budget = (long)(Math.Max(0, _c.Cash.Cents - 3 * Reserve()) * _mk.SharesCashShare);
if (budget <= 0) return;
foreach (var target in _w.Companies.OrderByDescending(t => t.IsPlayer).ThenBy(t => t.Id.Value))
{
if (target.Id == _c.Id || target.Defunct || !target.Listed || target.ControlledBy == _c.Id) continue;
if (target.AnnualProfit <= 0 || target.Rating > CreditRating.BBB) continue;
if (target.IsPlayer && _w.Difficulty.PlayerTakeover == TakeoverRule.Disabled && target.Shares.FractionOf(_c.Id) >= sm.ControlShare - _mk.IssueShare) continue;
double stake = target.Shares.FractionOf(_c.Id);
if (stake >= _mk.BidMinStake && TryLaunchBid(target)) return;
if (stake >= _mk.PredatoryStakeTarget) continue;
double ask = Corporate.Ask(_w, target);
long free = Corporate.FreeFloat(_w, target);
long maxDaily = (long)(target.Shares.Total * sm.MaxDailyTradeShare);
long shares = Math.Min(Math.Min(free, maxDaily), (long)(budget / Math.Max(Corporate.MinPrice, ask)));
if (target.IsPlayer && _w.Difficulty.PlayerTakeover == TakeoverRule.Disabled)
shares = Math.Min(shares, (long)(target.Shares.Outstanding * (sm.ControlShare - _mk.IssueShare)) - target.Shares.Of(_c.Id));
if (shares <= 0) continue;
Do(new BuySharesCommand(target.Id, shares, Money.Zero));
return;
}
}
private bool TryLaunchBid(Company target)
{
var sm = _w.Data.Balance.StockMarket;
if (target.IsPlayer && _w.Difficulty.PlayerTakeover == TakeoverRule.Disabled) return false;
if (_w.Bids.Any(b => b.State == BidState.Open && b.Target == target.Id)) return false;
long price = (long)Math.Ceiling(target.SharePrice * (1 + _mk.BidPremium));
double premium = price / Math.Max(Corporate.MinPrice, target.SharePrice) - 1;
if (price <= 0 || premium < sm.BidPremiumMin || premium > sm.BidPremiumMax) return false;
double goal = Math.Min(1.0, sm.ControlShare + 0.01);
long needed = (long)Math.Ceiling(goal * target.Shares.Outstanding) - target.Shares.Of(_c.Id);
if (needed <= 0) return false;
double cost = (double)needed * price;
if (_c.Cash.Cents < cost * _mk.BidCashMultiple + Reserve()) return false;
return Do(new LaunchBidCommand(target.Id, new Money(price), goal)).Ok;
}
/// Adesioni alle offerte sulle azioni possedute e difese quando l'IA è il bersaglio.
private void RespondToBids()
{
foreach (var bid in _w.Bids)
{
if (bid.State != BidState.Open || bid.Bidder == _c.Id) continue;
var target = _w.Company(bid.Target);
if (bid.Target == _c.Id)
{
Defend(bid);
continue;
}
if (target.Shares.Of(_c.Id) <= 0 || bid.Accepted.Contains(_c.Id)) continue;
double premium = bid.PricePerShare / Math.Max(Corporate.MinPrice, target.SharePrice) - 1;
if (premium >= _mk.HolderAcceptPremium) Do(new RespondBidCommand(bid.Id, true));
}
}
private void Defend(TakeoverBid bid)
{
if (bid.Defenses != 0 || _s.Responded.Contains(bid.Id.Value)) return; // una difesa per offerta
_s.Responded.Add(bid.Id.Value);
while (_s.Responded.Count > 16) _s.Responded.RemoveAt(0);
var sm = _w.Data.Balance.StockMarket;
long free = Corporate.FreeFloat(_w, _c);
double cost = free * Corporate.Ask(_w, _c);
if (cost > 0 && _c.Cash.Cents * _mk.BuybackCashShare >= cost)
{
Do(new RespondBidCommand(bid.Id, false) { Defense = BidDefense.Buyback });
return;
}
// cavaliere bianco: un'altra IA non predatoria con cassa abbondante
double knightCost = free * bid.PricePerShare * (1 + sm.WhiteKnightPremium);
foreach (var k in free <= 0 ? [] : _w.Companies)
{
if (k.Id == _c.Id || k.Id == bid.Bidder || k.Defunct || k.IsPlayer) continue;
var kp = _w.Data.Ai.Personalities.FirstOrDefault(p => p.Id == k.AiPersonality);
if (kp is null || kp.TargetsPlayer) continue;
if (k.Cash.Cents < knightCost * _mk.KnightCashMultiple) continue;
Do(new RespondBidCommand(bid.Id, false) { Defense = BidDefense.WhiteKnight, Knight = k.Id });
return;
}
Do(new RespondBidCommand(bid.Id, false) { Defense = _c.Cash.Cents > 0 ? BidDefense.ExtraDividend : BidDefense.None });
}
/// Al livello che lo sblocca, compra un'industria redditizia servita dalle proprie linee (una l'anno).
private void BuyIndustries()
{
if (!Tiers.Unlocks(_w, _c).BuyIndustry || _s.LastIndustryYear == _ctx.Year) return;
long budget = (long)(Math.Max(0, _c.Cash.Cents - Reserve()) * _mk.IndustryMaxCashShare);
if (budget <= 0) return;
var served = Tiers.ServedStations(_w, _c.Id);
Industry? best = null;
double bestMargin = _mk.IndustryMinMargin;
foreach (var s in _w.Network.Stations)
{
if (s.Owner != _c.Id || !served[s.Id.Value]) continue;
foreach (var id in s.Industries)
{
var ind = _w.Industries[id.Value];
if (ind.Closed || ind.Owner.IsValid || ind.Level <= 0 || ind.Margin <= bestMargin) continue;
if (IndustryMath.Valuation(_w, ind).Cents > budget) continue;
best = ind;
bestMargin = ind.Margin;
}
}
if (best is null) return;
if (Do(new BuyIndustryCommand(best.Id, IndustryMath.Valuation(_w, best))).Ok) _s.LastIndustryYear = _ctx.Year;
}
// ================================================================== nuovi progetti
private sealed class Candidate
{
public required AiProjectKind Kind { get; init; }
public required long Key { get; init; }
public int Good { get; init; } = -1;
public PaxClass Class { get; init; }
public required Vec2 SourcePos { get; init; }
public required Vec2 DestPos { get; init; }
/// Raggio entro cui deve stare la stazione (bacino) e se il riferimento è una città.
public required bool SourceIsTown { get; init; }
public required bool DestIsTown { get; init; }
public TownId SourceTown { get; init; } = TownId.None;
public TownId DestTown { get; init; } = TownId.None;
public required double StraightKm { get; init; }
public required double UnitsPerYear { get; init; }
public required double RoughScore { get; init; }
}
private sealed class Proposal
{
public required Candidate Candidate { get; init; }
public required Vec2 PosA { get; init; }
public required Vec2 PosB { get; init; }
public required StationId ExistingA { get; init; }
public required StationId ExistingB { get; init; }
public required List Polyline { get; init; }
public Vec2? DepotPos { get; init; }
public DepotId ExistingDepot { get; init; } = DepotId.None;
public required long Capital { get; init; }
public required double Revenue { get; init; }
public required double Costs { get; init; }
public required int Trains { get; init; }
public required VehicleDef Loco { get; init; }
public required VehicleDef Car { get; init; }
public required int Cars { get; init; }
public bool DepotAtB { get; init; }
public double Roi => Capital <= 0 ? 0 : (Revenue - Costs) / Capital;
}
private void NewProject()
{
int open = _s.Projects.Count(p => p.Stage is AiProjectStage.Construction or AiProjectStage.Equip);
if (open >= _plan.MaxConcurrentProjects) return;
long budget = _c.Cash.Cents - Reserve() + LoanRoom();
if (budget <= 0) return;
var loco = Estimators.BestLocomotive(_w, _ctx.Year);
if (loco is null) return;
var candidates = Candidates(loco, budget);
candidates.Sort((a, b) => b.RoughScore != a.RoughScore ? b.RoughScore.CompareTo(a.RoughScore) : a.Key.CompareTo(b.Key));
if (AiSystem.Trace is { } tr)
tr($"{_ctx.Day} {_c.Name}: {candidates.Count} candidati; migliori: " + string.Join(" | ", candidates.Take(8).Select(x => $"{x.Kind} g{x.Good} {x.StraightKm:0.0}km u{x.UnitsPerYear:0} s{x.RoughScore:0.000}")));
Proposal? best = null;
int evaluated = 0;
foreach (var cand in candidates)
{
if (evaluated >= _plan.EvaluateTop) break;
// i progetti fuori portata non si valutano nemmeno (si guarda oltre, ai più piccoli)
if (RoughCapital(cand.StraightKm) > budget) continue;
evaluated++;
var proposal = Evaluate(cand, loco);
if (proposal is null)
{
AiSystem.Trace?.Invoke($"{_ctx.Day} {_c.Name}: candidato {cand.Kind} {cand.Key:x} ({cand.StraightKm:0.0} km) non realizzabile");
Remember(cand.Key);
continue;
}
AiSystem.Trace?.Invoke($"{_ctx.Day} {_c.Name}: candidato {cand.Kind} bene {cand.Good} {cand.StraightKm:0.0} km: capitale {new Money(proposal.Capital)}, ricavi {Money.FromCentsRounded(proposal.Revenue)}, costi {Money.FromCentsRounded(proposal.Costs)}, ROI {proposal.Roi * 100:0.0} % (soglia {_p.RoiThreshold * 100:0} %, budget {new Money(budget)})");
if (proposal.Capital > budget) continue;
// ROI sul capitale investito, come nella guida (gli interessi sono una scelta di finanziamento)
double roi = proposal.Roi;
bool townProject = cand.SourceIsTown || cand.DestIsTown;
double threshold = townProject && NeedTowns() ? _p.RoiThreshold * _plan.TownRoiFactor : _p.RoiThreshold;
if (roi < threshold) continue;
if (best is null || proposal.Roi > best.Roi) best = proposal;
}
if (best is not null) Execute(best);
}
private void Remember(long key)
{
_s.Failed.Add(key);
while (_s.Failed.Count > _plan.FailedMemory) _s.Failed.RemoveAt(0);
}
private bool Known(long key)
{
foreach (var p in _s.Projects)
{
if (p.Key == key) return true;
}
return _s.Failed.Contains(key);
}
private static long KeyOf(AiProjectKind kind, int good, int source, int dest) =>
((long)kind << 60) | ((long)(good + 1) << 48) | ((long)source << 24) | (uint)dest;
/// Candidati: coppie produttore–consumatore non servite e città con lavoratori liberi verso posti scoperti.
private List Candidates(VehicleDef loco, long budget)
{
var list = new List();
double minKm = _plan.CandidateMinDistanceKm, maxKm = _plan.CandidateMaxDistanceKm;
int dpm = _w.Calendar.DaysPerMonth;
int months = _w.Calendar.MonthsPerYear;
var servedBy = ServedIndustries();
// merci
foreach (var prod in _w.Industries)
{
if (prod.Closed || prod.Level <= 0 || prod.IsStopped(_ctx.Day)) continue;
var outputs = prod.Def.Recipe.Outputs;
for (int o = 0; o < outputs.Count; o++)
{
int good = outputs[o].GoodIndex;
if (Estimators.WagonFor(_w, good, _ctx.Year) is null) continue;
var who = servedBy[prod.Id.Value];
if (who == _c.Id) continue;
if (who.IsValid && !(_p.TargetsPlayer && who == _w.Player.Id)) continue;
// produzione attesa: le primarie lavorano un po' meglio quando sono servite; le industrie di
// trasformazione producono solo quanto i loro input consentono (efficienza attuale)
double eff = prod.Def.Kind == IndustryKind.Primary ? _plan.AssumedEfficiency : Math.Min(prod.Efficiency, _plan.AssumedEfficiency);
double supply = (double)prod.Def.Capacity(prod.Level) * outputs[o].PerCycle / outputs[0].PerCycle * months * eff;
if (supply <= 0) continue;
foreach (var cons in _w.Industries)
{
if (cons.Closed || cons.Level <= 0 || cons.Id == prod.Id) continue;
int i = cons.InputIndexOf(good);
if (i < 0) continue;
double km = Vec2.Distance(prod.Position, cons.Position) / 1000;
if (km < minKm || km > maxKm) continue;
long key = KeyOf(AiProjectKind.Freight, good, prod.Id.Value, cons.Id.Value);
if (Known(key)) continue;
double demand = cons.CyclesPerDayAtFullCapacity(dpm) * dpm * months * cons.Def.Recipe.Inputs[i].PerCycle * _plan.AssumedEfficiency;
double units = Math.Min(supply, demand);
list.Add(new Candidate
{
Kind = AiProjectKind.Freight, Key = key, Good = good,
SourcePos = prod.Position, DestPos = cons.Position, SourceIsTown = false, DestIsTown = false,
StraightKm = km, UnitsPerYear = units,
RoughScore = RoughScore(units * Estimators.FreightPerUnit(_w, good, km * 1.2), km),
});
}
// esportazione: un hub compra tutto entro la sua capacità mensile (ed è una fonte di ricambi)
foreach (var hub in _w.Hubs)
{
double km = Vec2.Distance(prod.Position, hub.Position) / 1000;
if (km < minKm || km > maxKm) continue;
long key = KeyOf(AiProjectKind.Freight, good, prod.Id.Value, (2 << 22) | hub.Id.Value);
if (Known(key)) continue;
double units = Math.Min(supply, hub.MonthlyCapacity * months * _plan.HubShare);
double perUnit = Estimators.FreightPerUnit(_w, good, km * 1.2);
list.Add(new Candidate
{
Kind = AiProjectKind.Freight, Key = key, Good = good,
SourcePos = prod.Position, DestPos = hub.Position, SourceIsTown = false, DestIsTown = false,
StraightKm = km, UnitsPerYear = units,
RoughScore = RoughScore(units * perUnit, km),
});
}
foreach (var town in _w.Towns)
{
double perDay = DemandSystem.TownDemand(_w, town, good, _ctx.Year);
if (perDay <= 0) continue;
double km = _w.TownEdgeDistanceKm(town, prod.Position);
if (km < minKm || km > maxKm) continue;
long key = KeyOf(AiProjectKind.Freight, good, prod.Id.Value, (1 << 22) | town.Id.Value);
if (Known(key)) continue;
double units = Math.Min(supply, perDay * _w.Calendar.DaysPerYear);
list.Add(new Candidate
{
Kind = AiProjectKind.Freight, Key = key, Good = good,
SourcePos = prod.Position, DestPos = town.Position, SourceIsTown = false, DestIsTown = true, DestTown = town.Id,
StraightKm = km, UnitsPerYear = units,
RoughScore = RoughScore(units * Estimators.FreightPerUnit(_w, good, km * 1.2), km),
});
}
}
}
// pendolari: città con lavoratori liberi verso posti scoperti
var tb = _w.Data.Balance.Town;
var eb = _w.Data.Balance.Employment;
foreach (var ind in _w.Industries)
{
// pendolari solo verso industrie che la compagnia serve già con le merci: un'industria
// senza vettore perde livelli e posti, e i contratti di pendolarismo si sciolgono
if (ind.Closed || ind.Level <= 0 || servedBy[ind.Id.Value] != _c.Id) continue;
for (int cls = 0; cls < 2; cls++)
{
double uncovered = cls == 0 ? ind.JobsWorkers - ind.WorkersPresent : ind.JobsStaff - ind.StaffPresent;
if (uncovered < _plan.MinCommuters) continue;
var paxClass = cls == 0 ? PaxClass.Worker : PaxClass.Staff;
foreach (var town in _w.Towns)
{
int free = cls == 0 ? town.FreeWorkers(tb) : town.FreeStaff(tb);
if (free < _plan.MinCommuters) continue;
double km = _w.TownEdgeDistanceKm(town, ind.Position);
if (km < Math.Max(minKm, eb.WalkRadiusKm) || km > maxKm) continue;
// il viaggio (con un tracciato del 25 % più lungo della linea d'aria) deve stare nel tempo massimo
double minutes = km * 1.25 / Math.Max(1, loco.MaxSpeedKmh * _plan.SpeedFactor) * 60 + _plan.DwellMinutes;
if (minutes > (cls == 0 ? eb.WorkerMaxMinutes : eb.StaffMaxMinutes)) continue;
long key = KeyOf(AiProjectKind.Commuter, cls, (1 << 22) | town.Id.Value, ind.Id.Value);
if (Known(key)) continue;
// posti al giorno di due treni con le carrozze previste: i giri lunghi servono pochi pendolari
var coach = Estimators.CoachFor(_w, paxClass, _ctx.Year);
if (coach is null) continue;
double tripDays = Estimators.RoundTripDays(_w, km * 1.25, Math.Min(loco.MaxSpeedKmh, coach.MaxSpeedKmh));
double seats = (coach.PaxCapacity ?? 0) * Math.Max(1, _plan.WagonsPerTrain / 2) / Math.Max(0.05, tripDays)
* eb.LineCapacityUtilization * _plan.TrainsPerLine;
double pax = Math.Min(Math.Min(uncovered, free), seats) * _plan.CommuterCoverage;
double perYear = pax * 2 * _w.Calendar.DaysPerYear;
list.Add(new Candidate
{
Kind = AiProjectKind.Commuter, Key = key, Class = paxClass,
SourcePos = town.Position, DestPos = ind.Position, SourceIsTown = true, DestIsTown = false, SourceTown = town.Id,
StraightKm = km, UnitsPerYear = perYear,
RoughScore = RoughScore(perYear * Estimators.PassengerPerTrip(_w, paxClass, km * 1.2), km),
});
}
}
}
// fuori portata: inutile tenerli tra i migliori (si guarda ai progetti che la cassa consente)
list.RemoveAll(c => RoughCapital(c.StraightKm) > budget);
AdjustForNetwork(list);
if (list.Count > _plan.MaxCandidates)
{
list.Sort((a, b) => b.RoughScore != a.RoughScore ? b.RoughScore.CompareTo(a.RoughScore) : a.Key.CompareTo(b.Key));
list.RemoveRange(_plan.MaxCandidates, list.Count - _plan.MaxCandidates);
}
return list;
}
/// Hub e industrie che producono ricambi: le fonti per le officine (10.2).
private List PartsSources()
{
int good = _w.Data.SparePartsGood;
var list = new List();
foreach (var hub in _w.Hubs) list.Add(hub.Position);
foreach (var ind in _w.Industries)
{
if (!ind.Closed && ind.Level > 0 && ind.OutputIndexOf(good) >= 0) list.Add(ind.Position);
}
return list;
}
/// Una fonte di ricambi cadrebbe nel bacino di una stazione in questo punto.
private bool NearParts(Vec2 p, List sources, double slackM)
{
double r = _w.Data.Construction.Stations.CatchmentKm * 1000 + slackM;
foreach (var src in sources)
{
if (Vec2.Distance(src, p) <= r) return true;
}
return false;
}
/// Stazione della compagnia che serve già l'industria o la città indicata.
private bool HasOwnStationNear(Vec2 anchor, bool town, TownId townId)
{
double catchM = _w.Data.Construction.Stations.CatchmentKm * 1000;
foreach (var s in _w.Network.Stations)
{
if (s.Owner != _c.Id || !_w.Network.IsAlive(s)) continue;
if (town ? s.Towns.Contains(townId) : Vec2.Distance(s.Position, anchor) <= catchM) return true;
}
return false;
}
///
/// Ritocca il punteggio: una linea che parte da una stazione già della compagnia è più economica
/// e usa il deposito esistente; una rete nuova deve avere una fonte di ricambi a un capo.
///
/// Il livello successivo chiede più città collegate di quelle che la compagnia ha.
private bool NeedTowns()
{
var tiers = _w.Data.Tiers.Tiers;
return _c.Tier < tiers.Count
&& Tiers.ConnectedTowns(_w, _c.Id, tiers[_c.Tier].Requirements.ConnectedTownsOver.Population) < tiers[_c.Tier].Requirements.ConnectedTownsOver.Count;
}
private void AdjustForNetwork(List list)
{
var sources = PartsSources();
// se il prossimo livello chiede più città collegate, le linee che toccano una città valgono di più
bool needTowns = NeedTowns();
for (int i = list.Count - 1; i >= 0; i--)
{
var c = list[i];
bool existing = HasOwnStationNear(c.SourcePos, c.SourceIsTown, c.SourceTown) || HasOwnStationNear(c.DestPos, c.DestIsTown, c.DestTown);
double factor = existing ? 1.3
: NearParts(c.SourcePos, sources, 1000) || NearParts(c.DestPos, sources, 1000) ? 1.0 : _plan.NoPartsFactor;
if (needTowns && (c.SourceIsTown || c.DestIsTown)) factor *= _plan.TownBonus;
if (factor <= 0)
{
list.RemoveAt(i);
continue;
}
list[i] = new Candidate
{
Kind = c.Kind, Key = c.Key, Good = c.Good, Class = c.Class, SourcePos = c.SourcePos, DestPos = c.DestPos,
SourceIsTown = c.SourceIsTown, DestIsTown = c.DestIsTown, SourceTown = c.SourceTown, DestTown = c.DestTown,
StraightKm = c.StraightKm, UnitsPerYear = c.UnitsPerYear, RoughScore = c.RoughScore * factor,
};
}
}
/// Ricavo annuo stimato diviso il costo di massima (binario in linea d'aria + stazioni + deposito).
private double RoughScore(double revenue, double km) => revenue / Math.Max(1, RoughCapital(km));
/// Costo di massima di un progetto: binario (+20 % di percorso, +30 % di opere), stazioni, deposito, un treno.
private long RoughCapital(double km)
{
var loco = Estimators.BestLocomotive(_w, _ctx.Year);
long train = loco is null ? 0 : loco.Price + 5 * 150_000;
return (long)(Estimators.RoughTrackCost(_w, _c, km * 1.2) * 1.3) + Estimators.StationCost(_w, _c, _plan.Platforms)
+ Estimators.StationCost(_w, _c, _plan.HubPlatforms) + Estimators.DepotCost(_w, _c, "small") + train;
}
///
/// Compagnia che serve (o sta per servire) ciascuna industria: una sua stazione ha l'industria nel
/// bacino, anche se la linea è ancora in costruzione (o None).
///
private CompanyId[] ServedIndustries()
{
var result = new CompanyId[_w.Industries.Count];
Array.Fill(result, CompanyId.None);
foreach (var company in _w.Companies)
{
if (company.Defunct) continue;
foreach (var s in _w.Network.Stations)
{
if (s.Owner != company.Id || !_w.Network.IsAlive(s)) continue;
foreach (var id in s.Industries)
{
if (!result[id.Value].IsValid || company.Id == _c.Id) result[id.Value] = company.Id;
}
}
}
return result;
}
/// Valuta un candidato: stazioni, percorso, piano dei binari, treni, costi e ricavi.
private Proposal? Evaluate(Candidate cand, VehicleDef loco, DepotId? supply = null)
{
var (posA, existingA) = StationSite(cand.SourcePos, cand.DestPos, cand.SourceIsTown, cand.SourceTown, default);
if (posA is null) return Reject("nessun sito per la prima stazione");
var (posB, existingB) = StationSite(cand.DestPos, cand.SourcePos, cand.DestIsTown, cand.DestTown, posA.Value);
if (posB is null) return Reject("nessun sito per la seconda stazione");
if (existingA.IsValid && existingA == existingB) return Reject("stessa stazione");
if (Vec2.Distance(posA.Value, posB.Value) < _plan.CandidateMinDistanceKm * 1000) return Reject("stazioni troppo vicine");
double minRadius = _w.Data.Construction.SpeedClasses.First(x => x.TrackClass == "c60").MinRadiusM;
if (!_path.SameRegion(_w, posA.Value, posB.Value)) return Reject("regioni separate da fiumi troppo larghi o dal mare");
var polyline = _path.Find(_w, _c.Id, posA.Value, posB.Value, _plan.PathMarginKm, _plan.SimplifyToleranceM, minRadius)
?? _path.Find(_w, _c.Id, posA.Value, posB.Value, _plan.PathMarginRetryKm, _plan.SimplifyToleranceM, minRadius);
if (polyline is null) return Reject("nessun percorso");
var (plan, _, _) = RailCommandHandlers.PreparePlan(_w, _c, new BuildTrackCommand(polyline));
if (!plan.Valid)
{
string first = plan.Errors[0].Message;
polyline = _path.Find(_w, _c.Id, posA.Value, posB.Value, _plan.PathMarginKm, _plan.SimplifyToleranceM / 2, minRadius);
if (polyline is null) return Reject("nessun percorso");
(plan, _, _) = RailCommandHandlers.PreparePlan(_w, _c, new BuildTrackCommand(polyline));
if (!plan.Valid) return Reject($"piano non valido: {first} / {plan.Errors[0].Message}");
}
// deposito: quello della rete già collegata alla stazione esistente, altrimenti uno nuovo accanto ad A
Vec2? depotPos = null;
var existingDepot = supply is { } supplied ? supplied : existingA.IsValid ? ConnectedDepot(existingA) : DepotId.None;
if (!existingDepot.IsValid && existingB.IsValid) existingDepot = ConnectedDepot(existingB);
long capital = plan.TotalCost.Cents;
bool depotAtB = false;
if (!existingDepot.IsValid)
{
// il deposito va dalla parte della fonte di ricambi, che finisce nel bacino della sua stazione
var sources = PartsSources();
bool nearA = NearParts(posA.Value, sources, -200), nearB = NearParts(posB.Value, sources, -200);
depotAtB = !nearA && nearB;
var home = depotAtB ? posB.Value : posA.Value;
if (!nearA && !nearB && supply is null)
{
// rete nuova lontana dai ricambi: serve una linea apposta, che deve esistere e si mette in conto
long partsCost = PartsLineCost(home, sources);
if (partsCost < 0) return Reject("nessuna linea di ricambi possibile per il deposito");
capital += partsCost;
}
var next = depotAtB ? (polyline.Count > 1 ? polyline[^2] : posA.Value) : (polyline.Count > 1 ? polyline[1] : posB.Value);
depotPos = DepotSite(home, next);
if (depotPos is null) return Reject("nessun sito per il deposito");
var (stub, _, _) = RailCommandHandlers.PreparePlan(_w, _c, new BuildTrackCommand([depotPos.Value, home]));
if (!stub.Valid) return Reject($"raccordo del deposito non valido: {stub.Errors[0].Message}");
capital += stub.TotalCost.Cents + Estimators.DepotCost(_w, _c, "small");
}
// la stazione del deposito diventa il nodo della rete: più binari per le linee future
if (!existingA.IsValid) capital += Estimators.StationCost(_w, _c, depotPos is not null && !depotAtB ? _plan.HubPlatforms : _plan.Platforms);
if (!existingB.IsValid) capital += Estimators.StationCost(_w, _c, depotPos is not null && depotAtB ? _plan.HubPlatforms : _plan.Platforms);
double km = plan.LengthM / 1000;
VehicleDef? car = cand.Kind == AiProjectKind.Freight ? Estimators.WagonFor(_w, cand.Good, _ctx.Year) : Estimators.CoachFor(_w, cand.Class, _ctx.Year);
if (car is null) return null;
int cars = supply is not null ? 1 : cand.Kind == AiProjectKind.Freight ? _plan.WagonsPerTrain : Math.Max(1, _plan.WagonsPerTrain / 2);
double speed = Math.Min(loco.MaxSpeedKmh, Math.Min(car.MaxSpeedKmh, plan.ClassSpeedKmh > 0 ? plan.ClassSpeedKmh : loco.MaxSpeedKmh));
double tripDays = Estimators.RoundTripDays(_w, km, speed);
double tripsPerYear = _w.Calendar.DaysPerYear / Math.Max(0.05, tripDays);
double revenue, units;
int trains;
if (cand.Kind == AiProjectKind.Freight)
{
double perTrain = (car.Capacity ?? 0) * cars * tripsPerYear;
trains = Math.Clamp((int)Math.Ceiling(cand.UnitsPerYear / Math.Max(1, perTrain)), 1, _plan.TrainsPerLine);
units = Math.Min(cand.UnitsPerYear, perTrain * trains);
revenue = units * Estimators.FreightPerUnit(_w, cand.Good, km);
}
else
{
// posti al giorno per verso: carrozze × posti × giri al giorno × utilizzo
double seatsPerDay = (car.PaxCapacity ?? 0) * cars / Math.Max(0.05, tripDays) * _w.Data.Balance.Employment.LineCapacityUtilization;
double paxPerDay = cand.UnitsPerYear / (2 * _w.Calendar.DaysPerYear);
trains = Math.Clamp((int)Math.Ceiling(paxPerDay / Math.Max(1, seatsPerDay * _plan.CommuterCoverage)), 1, _plan.TrainsPerLine);
units = Math.Min(paxPerDay, seatsPerDay * trains * _plan.CommuterCoverage) * 2 * _w.Calendar.DaysPerYear;
revenue = units * Estimators.PassengerPerTrip(_w, cand.Class, km);
}
capital += Estimators.TrainPrice(loco, car, cars) * trains;
var sp = _w.Data.Construction.Stations;
double costs = Estimators.TrainCostPerYear(_w, loco, car, cars) * trains
+ (existingA.IsValid ? 0 : _plan.Platforms * sp.UpkeepPerPlatformPerYear)
+ (existingB.IsValid ? 0 : _plan.Platforms * sp.UpkeepPerPlatformPerYear)
+ (existingDepot.IsValid ? 0 : sp.DepotUpkeepPerYear["small"])
+ km * _plan.TrackUpkeepPerKmPerYear;
return new Proposal
{
Candidate = cand, PosA = posA.Value, PosB = posB.Value, ExistingA = existingA, ExistingB = existingB,
Polyline = polyline, DepotPos = depotPos, ExistingDepot = existingDepot,
Capital = capital, Revenue = revenue, Costs = costs, Trains = trains, Loco = loco, Car = car, Cars = cars,
DepotAtB = depotAtB,
};
}
private Proposal? Reject(string reason)
{
AiSystem.Trace?.Invoke($"{_ctx.Day} {_c.Name}: scartato: {reason}");
return null;
}
///
/// Sito della stazione vicino a un'industria o a una città: una stazione della compagnia già nel
/// bacino, oppure un punto libero alle distanze provate, verso l'altro estremo.
///
private (Vec2? Pos, StationId Existing) StationSite(Vec2 anchor, Vec2 toward, bool town, TownId townId, Vec2 avoid)
{
var sp = _w.Data.Construction.Stations;
double catchM = sp.CatchmentKm * 1000;
foreach (var s in _w.Network.Stations)
{
if (s.Owner != _c.Id || !_w.Network.IsAlive(s)) continue;
bool covers = town ? s.Towns.Contains(townId) : Vec2.Distance(s.Position, anchor) <= catchM;
// una stazione condivisa regge al massimo binari − 1 treni (altrimenti stallo di capacità)
if (covers && Vec2.Distance(s.Position, avoid) > catchM && StationLoad(s.Id) + _plan.TrainsPerLine <= s.Platforms - 1)
return (s.Position, s.Id);
}
var dir = (toward - anchor).Normalized();
double baseAngle = DMath.Atan2(dir.Y, dir.X);
double townRadius = 0;
if (town) townRadius = _w.Towns[townId.Value].RadiusCells * _w.Terrain.CellSizeM;
ReadOnlySpan turns = [0, 0.5, -0.5, 1.0, -1.0, 1.6, -1.6];
foreach (double offset in _plan.StationOffsetsM)
{
foreach (double turn in turns)
{
double a = baseAngle + turn;
var p = anchor + new Vec2(DMath.Cos(a), DMath.Sin(a)) * (offset + townRadius);
if (!SiteFree(p)) continue;
double reach = town ? _w.TownEdgeDistanceKm(_w.Towns[townId.Value], p) * 1000 : Vec2.Distance(p, anchor);
if (reach > catchM - 100) continue;
if (avoid != default && Vec2.Distance(p, avoid) < sp.AreaRadiusM * 4) continue;
return (p, StationId.None);
}
}
return (null, StationId.None);
}
///
/// Costo stimato della linea di ricambi dalla fonte più vicina raggiungibile verso
/// (binario, stazione, un treno), o −1 se nessuna fonte è collegabile.
///
private long PartsLineCost(Vec2 home, List sources)
{
var order = sources.Select(p => (Pos: p, Km: Vec2.Distance(p, home) / 1000)).Where(x => x.Km <= _plan.CandidateMaxDistanceKm * 1.5)
.OrderBy(x => x.Km).ThenBy(x => x.Pos.X).ThenBy(x => x.Pos.Y).Take(2);
double minRadius = _w.Data.Construction.SpeedClasses.First(x => x.TrackClass == "c60").MinRadiusM;
foreach (var (pos, _) in order)
{
var (site, existing) = StationSite(pos, home, false, TownId.None, home);
if (site is null) continue;
var line = _path.Find(_w, _c.Id, site.Value, home, _plan.PathMarginKm, _plan.SimplifyToleranceM, minRadius);
if (line is null) continue;
var (plan, _, _) = RailCommandHandlers.PreparePlan(_w, _c, new BuildTrackCommand(line));
if (!plan.Valid) continue;
var loco = Estimators.BestLocomotive(_w, _ctx.Year);
var box = Estimators.WagonFor(_w, _w.Data.SparePartsGood, _ctx.Year);
if (loco is null || box is null) return -1;
return plan.TotalCost.Cents + (existing.IsValid ? 0 : Estimators.StationCost(_w, _c, _plan.Platforms)) + Estimators.TrainPrice(loco, box, 1);
}
return -1;
}
/// Treni (in linea o diretti a una linea) che fermano nella stazione.
private int StationLoad(StationId station)
{
int load = 0;
foreach (var t in _w.Trains)
{
if (t.Owner != _c.Id || t.Removed || !t.Line.IsValid) continue;
var line = _w.Lines[t.Line.Value];
foreach (var stop in line.Stops)
{
if (stop.Station != station) continue;
load++;
break;
}
}
return load;
}
/// Punto adatto a una stazione o a un deposito (stesse regole del comando).
private bool SiteFree(Vec2 p)
{
var sp = _w.Data.Construction.Stations;
if (p.X < 200 || p.Y < 200 || p.X > _w.Terrain.WidthM - 200 || p.Y > _w.Terrain.HeightM - 200) return false;
var (cx, cy) = _w.Terrain.CellAt(p);
for (int dy = -1; dy <= 1; dy++)
{
for (int dx = -1; dx <= 1; dx++)
{
int x = Math.Clamp(cx + dx, 0, _w.Terrain.Width - 1), y = Math.Clamp(cy + dy, 0, _w.Terrain.Height - 1);
if (_w.Terrain.TypeAt(x, y) is Map.CellType.Water or Map.CellType.Sea or Map.CellType.Town or Map.CellType.Industry) return false;
}
}
foreach (var s in _w.Network.Stations)
{
if (_w.Network.IsAlive(s) && Vec2.Distance(s.Position, p) < sp.AreaRadiusM * 2 + 50) return false;
}
foreach (var d in _w.Network.Depots)
{
if (_w.Network.IsAlive(d) && Vec2.Distance(d.Position, p) < sp.AreaRadiusM * 2 + 50) return false;
}
foreach (var e in _w.Network.Edges)
{
if (e.State == EdgeState.Demolished || e.Owner == _c.Id) continue;
// lontano dai binari altrui: la stazione non deve agganciarsi alla rete di un'altra compagnia
var na = _w.Network.Nodes[e.A.Value].Position;
var nb = _w.Network.Nodes[e.B.Value].Position;
if (DistanceToSegment(p, na, nb) < sp.SnapM * 3) return false;
}
return true;
}
private static double DistanceToSegment(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);
}
/// Deposito accanto alla stazione, di lato rispetto al binario.
private Vec2? DepotSite(Vec2 station, Vec2 next)
{
var dir = (next - station).Normalized();
var normal = new Vec2(-dir.Y, dir.X);
foreach (var v in new[] { normal, -normal, -dir, (normal - dir).Normalized(), (-normal - dir).Normalized() })
{
var p = station + v * _plan.DepotOffsetM;
if (SiteFree(p)) return p;
}
return null;
}
/// Deposito della compagnia raggiungibile dalla stazione sulla rete (BFS sui nodi), o None.
private DepotId ConnectedDepot(StationId station)
{
var net = _w.Network;
var start = net.Stations[station.Value].Node;
var seen = new bool[net.Nodes.Count];
var queue = new Queue();
queue.Enqueue(start);
seen[start.Value] = true;
while (queue.Count > 0)
{
var n = net.Nodes[queue.Dequeue().Value];
if (n.Depot.IsValid && net.Depots[n.Depot.Value].Owner == _c.Id) return n.Depot;
foreach (var eid in n.Edges)
{
var e = net.Edges[eid.Value];
if (e.State == EdgeState.Demolished || e.Owner != _c.Id) continue;
var other = e.A == n.Id ? e.B : e.A;
if (seen[other.Value]) continue;
seen[other.Value] = true;
queue.Enqueue(other);
}
}
return DepotId.None;
}
/// Apre i cantieri del progetto: stazioni, deposito, binario e raccordo del deposito.
private void Execute(Proposal p, DepotId? supply = null)
{
long need = p.Capital + Reserve() - _c.Cash.Cents;
if (need > 0 && !Borrow(need)) return;
var cand = p.Candidate;
var stationA = p.ExistingA;
var stationB = p.ExistingB;
if (!stationA.IsValid)
{
var r = Do(new BuildStationCommand(p.PosA, p.DepotPos is not null && !p.DepotAtB ? _plan.HubPlatforms : _plan.Platforms));
if (!r.Ok)
{
Remember(cand.Key);
return;
}
stationA = new StationId(r.Created[0]);
}
if (!stationB.IsValid)
{
var r = Do(new BuildStationCommand(p.PosB, p.DepotPos is not null && p.DepotAtB ? _plan.HubPlatforms : _plan.Platforms));
if (!r.Ok)
{
Remember(cand.Key);
return;
}
stationB = new StationId(r.Created[0]);
}
var project = new AiProject
{
Id = _s.NextProjectId++,
Kind = cand.Kind,
Good = cand.Good,
PaxClass = (int)cand.Class,
Key = cand.Key,
StationA = stationA,
StationB = stationB,
StartDay = _ctx.Day,
CapitalCents = p.Capital,
RevenuePerYearCents = (long)p.Revenue,
TrainsPlanned = p.Trains,
Loco = p.Loco.Id,
Car = p.Car.Id,
CarsPerTrain = p.Cars,
SupplyFor = supply ?? DepotId.None,
};
_s.Projects.Add(project);
var track = Do(new BuildTrackCommand(p.Polyline));
if (!track.Ok)
{
project.Stage = AiProjectStage.Abandoned;
Remember(cand.Key);
return;
}
project.Edges.Add(new EdgeId(track.Created[0]));
if (p.ExistingDepot.IsValid)
{
project.Depot = p.ExistingDepot;
return;
}
var depot = Do(new BuildDepotCommand(p.DepotPos!.Value, "small"));
if (!depot.Ok)
{
project.Stage = AiProjectStage.Abandoned;
return;
}
project.Depot = new DepotId(depot.Created[0]);
var stub = Do(new BuildTrackCommand([p.DepotPos.Value, _w.Network.Stations[(p.DepotAtB ? stationB : stationA).Value].Position]));
if (!stub.Ok)
{
project.Stage = AiProjectStage.Abandoned;
return;
}
project.Edges.Add(new EdgeId(stub.Created[0]));
var sa = _w.Network.Stations[stationA.Value];
var sb = _w.Network.Stations[stationB.Value];
string what = cand.Kind == AiProjectKind.Freight ? _w.Data.Goods[cand.Good].NameIt.ToLowerInvariant() : "pendolari";
AiSystem.Trace?.Invoke($"{_ctx.Day} {_c.Name}: PROGETTO {project.Id} {what} {sa.Name} → {sb.Name}, {p.Polyline.Count} vertici, capitale {new Money(p.Capital)}, ricavi stimati {Money.FromCentsRounded(p.Revenue)}, treni {p.Trains}, chiave {cand.Key:x}");
_ctx.Emit(new GameEvent(_ctx.Day, EventKind.Company, EventSeverity.Info,
$"{_c.Name} apre i cantieri della linea {sa.Name} – {sb.Name} ({what})", EntityKind.Company, _c.Id.Value, _c.Id));
}
}