Files
Rail_Enterprise/src/RailEnterprise.Server/Projection.cs
T
Alby96andClaude Opus 5.5 2992e7cc36 F6: mercato globale, storico prezzi a 24 mesi e previsione
Prima parte della F6: il pannello «Mercato globale» dell'immagine di
riferimento 06, con i dati calcolati dal server.

- Lo storico dei prezzi globali passa da 360 a 720 giorni. I salvataggi
  con lo storico di un anno si migrano al caricamento allungando la
  finestra (RollingWindow.Extended), senza cambiare formato.
- MarketOutlook (Core) è un'analisi in sola lettura del mondo: storico
  mensile, variazione a 30 giorni, offerta e domanda con la quota
  mondiale, scorte in mesi, indice materie prime, previsione a 4 mesi
  dalla componente mondiale con banda, destinazioni di vendita ordinate
  per prezzo con la linea che le collega, hub, evento in corso e
  avanzamento verso la compravendita in proprio. Parametri nuovi in
  balance.json (market.outlook); interpretazioni nell'ADR 0015.
- Protocollo: DetailKind.Market (7) e MarketReport (129); il server
  risponde su richiesta, il client lo mostra in un pannello a tutto
  schermo e il pilota automatico ne fa la schermata 16_mercato.
- Test: finestra allungata e migrazione, storico mensile, previsione
  deterministica ed entro i limiti, evento, analisi su Valdoria,
  round-trip del messaggio e quadro via WebSocket.

La simulazione non cambia: l'analisi non scrive nel mondo e
l'accettazione F4 dà gli stessi numeri di prima.

Closes #29.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 14:25:38 +01:00

553 lines
29 KiB
C#

using RailEnterprise.Core.Common;
using RailEnterprise.Core.Economy;
using RailEnterprise.Core.Rail;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Core.Simulation.Systems;
using RailEnterprise.Protocol;
using RailEnterprise.Protocol.Messages;
namespace RailEnterprise.Server;
/// <summary>
/// Proiezione del mondo autorevole nei record del protocollo. Gira sul thread del ciclo di gioco:
/// legge il mondo, non lo modifica.
/// </summary>
public static class Projection
{
public static WorldSummary Summary(World w, Company company, byte speed) => new()
{
Seed = w.Settings.Seed,
SizeKm = w.Settings.SizeKm,
StartYear = w.Settings.StartYear,
Tick = w.Clock.Tick,
Date = w.Clock.Date.ToString(),
CompanyId = company.Id.Value,
CompanyName = company.Name,
RegionId = w.Settings.RegionId,
WidthCells = w.Terrain.Width,
HeightCells = w.Terrain.Height,
CellSizeM = w.Terrain.CellSizeM,
ChunkCells = w.Terrain.ChunkCells,
Speed = speed,
TerrainHash = w.Terrain.ComputeHash(),
CostMultiplier = RailCommandHandlers.CostMultiplier(w, company),
};
public static MapChunk Chunk(World w, int cx, int cy)
{
var t = w.Terrain;
int x0 = cx * t.ChunkCells, y0 = cy * t.ChunkCells;
int width = Math.Min(t.ChunkCells, t.Width - x0), height = Math.Min(t.ChunkCells, t.Height - y0);
var heights = new ushort[width * height];
var types = new byte[width * height];
var river = new byte[width * height];
for (int y = 0; y < height; y++)
{
int src = (y0 + y) * t.Width + x0;
t.Heights.AsSpan(src, width).CopyTo(heights.AsSpan(y * width));
t.Types.AsSpan(src, width).CopyTo(types.AsSpan(y * width));
t.RiverWidth.AsSpan(src, width).CopyTo(river.AsSpan(y * width));
}
return new MapChunk { Cx = cx, Cy = cy, Width = width, Height = height, Heights = heights, Types = types, RiverWidth = river };
}
/// <summary>Hash del contenuto di un chunk (per rimandarlo quando l'abitato o un'industria cambia il terreno).</summary>
public static ulong ChunkHash(World w, int cx, int cy)
{
var t = w.Terrain;
int x0 = cx * t.ChunkCells, y0 = cy * t.ChunkCells;
int width = Math.Min(t.ChunkCells, t.Width - x0), height = Math.Min(t.ChunkCells, t.Height - y0);
ulong h = 0;
for (int y = 0; y < height; y++)
{
int src = (y0 + y) * t.Width + x0;
h = XxHash64.Hash(t.Types.AsSpan(src, width), h);
h = XxHash64.Hash(System.Runtime.InteropServices.MemoryMarshal.AsBytes(t.Heights.AsSpan(src, width)), h);
}
return h;
}
/// <summary>Tutte le entità visibili a una compagnia (in F3: tutte).</summary>
public static EntityLists Entities(World w)
{
var net = w.Network;
var e = new EntityLists();
foreach (var c in w.Companies)
{
e.Companies.Add(new CompanyInfo
{
Id = c.Id.Value, Name = c.Name, Color = c.Color, IsPlayer = c.IsPlayer, Cash = c.Cash, NetWorth = c.NetWorth,
Rating = c.Rating.ToString(), Tier = (byte)c.Tier, Bankrupt = c.Bankrupt, MaintenancePolicy = (byte)c.MaintenancePolicy,
Personality = c.AiPersonality ?? "", Listed = c.Listed, SharePriceCents = Math.Round(c.SharePrice, 2), Sentiment = (float)c.Sentiment,
FounderShare = (float)c.Shares.FounderFraction, ControlledBy = c.ControlledBy.Value, Merged = c.Merged,
Receivership = c.Receivership, ReceivershipUntilDay = c.ReceivershipUntilDay, AnnualProfit = new Money(c.AnnualProfit),
});
}
foreach (var t in w.Towns)
{
e.Towns.Add(new TownInfo
{
Id = t.Id.Value, Name = t.Name, Position = t.Position, Population = t.Population, RadiusCells = t.RadiusCells,
Satisfaction = (float)t.OverallSatisfaction, Services = t.Services,
});
}
foreach (var i in w.Industries)
{
e.Industries.Add(new IndustryInfo
{
Id = i.Id.Value, Type = i.Def.Id, Name = i.Name, Position = i.Position, FootprintCells = i.FootprintCells, Level = i.Level,
Closed = i.Closed, Efficiency = (float)i.Efficiency, Condition = (float)Math.Round(i.Condition, 1), Owner = i.Owner.IsValid ? i.Owner.Value : -1,
Budget = (byte)i.Budget, SpareParts = i.SpareParts, Machinery = i.Machinery, StoppedUntilDay = i.StoppedUntilDay,
StopKind = (byte)i.StopKind, PendingWork = (byte)i.PendingWork, PartsShort = i.PartsShort,
});
}
foreach (var h in w.Hubs)
e.Hubs.Add(new HubInfo { Id = h.Id.Value, Kind = h.Kind.ToString().ToLowerInvariant(), Name = h.Name, Position = h.Position });
foreach (var n in net.Nodes)
{
if (n.Removed) continue;
e.Nodes.Add(new NodeInfo
{
Id = n.Id.Value, Position = n.Position, HeightM = n.HeightM, Owner = n.Owner.Value, Station = n.Station.Value, Depot = n.Depot.Value,
Edges = n.Edges.Select(x => x.Value).ToArray(),
});
}
foreach (var s in net.Stations)
{
if (!net.IsAlive(s)) continue;
int waiting = 0;
foreach (var p in s.Waiting) waiting += p.Units;
e.Stations.Add(new StationInfo
{
Id = s.Id.Value, Owner = s.Owner.Value, Name = s.Name, Node = s.Node.Value, Position = s.Position, Platforms = s.Platforms,
WaitingUnits = waiting, Industries = s.Industries.Select(x => x.Value).ToArray(), Towns = s.Towns.Select(x => x.Value).ToArray(),
});
}
foreach (var d in net.Depots)
{
if (!net.IsAlive(d)) continue;
bool waiting = false;
foreach (var j in d.Jobs) waiting |= j.InStall && !j.Started && d.SpareParts < j.Parts;
e.Depots.Add(new DepotInfo
{
Id = d.Id.Value, Owner = d.Owner.Value, Name = d.Name, Node = d.Node.Value, Position = d.Position, Size = d.Size,
Stalls = d.Stalls, JobsStaff = d.JobsStaff, StaffPercent = (byte)Math.Round(d.StaffRatio * 100), SpareParts = d.SpareParts,
PartsTarget = d.PartsTarget, Jobs = d.Jobs.Count, WaitingParts = waiting,
});
}
foreach (var l in w.Lines)
{
if (l.Removed) continue;
e.Lines.Add(new LineInfo
{
Id = l.Id.Value, Owner = l.Owner.Value, Name = l.Name, Color = l.Color, Stops = l.Stops.ToArray(),
Policy = l.Policy is { } p ? (byte)p : byte.MaxValue,
});
}
foreach (var v in w.Vehicles)
{
if (v.Sold) continue;
// condizione arrotondata all'unità: il record cambia (e viaggia nei delta) solo quando serve
double cond = Math.Floor(v.Components.Length == 0 ? 100 : v.Components.Min());
e.Vehicles.Add(new VehicleInfo { Id = v.Id.Value, Owner = v.Owner.Value, Type = v.Def.Id, Depot = v.Depot.Value, Train = v.Train.Value, Condition = (float)cond });
}
foreach (var t in w.Trains)
{
if (t.Removed) continue;
int load = 0, capacity = 0;
foreach (var vid in t.Vehicles)
{
var v = w.Vehicles[vid.Value];
load += v.Load + v.Pax;
capacity += (v.Def.Capacity ?? 0) + (v.Def.PaxCapacity ?? 0);
}
var atDepot = t.AtNode.IsValid ? net.Nodes[t.AtNode.Value].Depot : DepotId.None;
var next = t.Vehicles.Count > 0 ? Fleet.Next(w, t) : new NextIntervention(-1, 0);
e.Trains.Add(new TrainInfo
{
Id = t.Id.Value, Owner = t.Owner.Value, Name = t.Name, Line = t.Line.Value, State = (byte)t.State,
Vehicles = t.Vehicles.Select(x => x.Value).ToArray(), MaxSpeedKmh = (float)t.MaxSpeedKmh, LengthM = (float)t.LengthM,
Load = load, Capacity = capacity, Depot = atDepot.Value,
Condition = (byte)Math.Clamp(Math.Floor(Fleet.TrainCondition(w, t)), 0, 100), Maintenance = MaintenanceStatus(t),
Reserve = t.Reserve, Policy = t.Policy is { } p ? (byte)p : byte.MaxValue,
NextIntervention = next.Intervention >= 0 ? w.Data.Maintenance.Interventions[next.Intervention].Id : "",
NextDueDays = (int)Math.Clamp(Math.Floor(next.Days), -9999, 9999), MaintenanceDepot = t.MaintenanceDepot.Value,
});
}
return e;
}
public static TrainMaintenanceStatus MaintenanceStatus(Train t)
{
if (t.State == TrainState.Broken) return TrainMaintenanceStatus.Stranded;
if (t.Towed) return TrainMaintenanceStatus.Towed;
if (t.InWorkshop) return TrainMaintenanceStatus.InWorkshop;
if (t.Failure == FailureKind.Minor) return TrainMaintenanceStatus.MinorFailure;
return t.MaintenanceDepot.IsValid ? TrainMaintenanceStatus.Booked : TrainMaintenanceStatus.InService;
}
/// <summary>Cartella di manutenzione di un treno (10.3).</summary>
public static MaintenanceCard Card(World w, Train t)
{
var m = w.Data.Maintenance;
var next = t.Vehicles.Count > 0 ? Fleet.Next(w, t) : new NextIntervention(-1, 0);
var card = new MaintenanceCard
{
Train = t.Id.Value, Day = w.Clock.Day, Condition = (float)Fleet.TrainCondition(w, t), Status = MaintenanceStatus(t),
Policy = (byte)Fleet.PolicyOf(w, t).Id, PolicyOverride = t.Policy is { } p ? (byte)p : byte.MaxValue, Reserve = t.Reserve,
Failure = (byte)t.Failure, FailedVehicle = t.FailedVehicle.Value,
FailedComponent = t.FailedVehicle.IsValid && t.FailedComponent >= 0
? Fleet.ComponentsOf(w.Data, w.Vehicles[t.FailedVehicle.Value].Def)[t.FailedComponent].Id : "",
RescueHours = t.RescueTick >= 0 ? (float)((t.RescueTick - w.Clock.Tick) * w.Calendar.TrainSecondsPerTick / 3600) : -1,
NextIntervention = next.Intervention >= 0 ? m.Interventions[next.Intervention].Id : "", NextDueDays = (float)next.Days,
PlannedIntervention = t.PlannedIntervention >= 0 ? m.Interventions[t.PlannedIntervention].Id : "",
MaintenanceDepot = t.MaintenanceDepot.Value, ServiceKmPerDay = (float)t.ServiceKmPerDay,
CostThisYear = new Money(t.MaintenanceThisYear), CostLastYear = new Money(t.MaintenanceLastYear),
FailuresThisYear = t.FailuresThisYear, FailuresTotal = t.FailuresTotal, CoveredBy = t.CoveredBy.Value, Covering = t.Covering.Value,
};
foreach (var id in t.Vehicles)
{
var v = w.Vehicles[id.Value];
var comps = Fleet.ComponentsOf(w.Data, v.Def);
var vc = new VehicleCard
{
Vehicle = v.Id.Value, Type = v.Def.Id, OdometerKm = (float)v.OdometerKm,
AgeYears = (float)((w.Clock.Day - v.BoughtDay) / (double)w.Calendar.DaysPerYear), AgeFactor = (float)Fleet.AgeFactor(w, v),
};
for (int j = 0; j < v.Components.Length && j < comps.Count; j++)
vc.Components.Add(new ComponentCard { Component = comps[j].Id, Condition = (float)v.Components[j], WearPerDay = j < v.WearEma.Length ? (float)v.WearEma[j] : 0 });
card.Vehicles.Add(vc);
}
foreach (var h in t.History)
{
card.History.Add(new MaintenanceRecordInfo
{
Day = h.Day, Intervention = m.Interventions[h.Intervention].Id, Cost = new Money(h.CostCents), Depot = h.Depot.Value, Parts = h.Parts,
});
}
return card;
}
/// <summary>Registro officina di un deposito (10.3).</summary>
public static WorkshopRegister Workshop(World w, Depot d)
{
var m = w.Data.Maintenance;
var backlog = new double[w.Network.Depots.Count];
var reserved = new int[w.Network.Depots.Count];
FleetMaintenanceSystem.DepotLoads(w, null, backlog, reserved);
var reg = new WorkshopRegister
{
Depot = d.Id.Value, Day = w.Clock.Day, Stalls = d.Stalls, JobsStaff = d.JobsStaff, StaffPresent = (float)d.StaffPresent,
WorkRate = (float)FleetMaintenanceSystem.WorkRate(w, d), SpareParts = d.SpareParts, PartsTarget = d.PartsTarget,
PartsReserved = reserved[d.Id.Value],
};
foreach (var j in d.Jobs)
{
reg.Jobs.Add(new WorkshopJobInfo
{
Train = j.Train.Value, Intervention = m.Interventions[j.Intervention].Id, InStall = j.InStall, Started = j.Started,
Progress = (float)j.Progress, Days = (float)j.Days, Parts = j.Parts, QueuedDay = j.QueuedDay,
});
}
foreach (var t in w.Trains)
{
if (t.Removed || t.InWorkshop || t.MaintenanceDepot != d.Id || t.PlannedIntervention < 0) continue;
var def = m.Interventions[t.PlannedIntervention];
reg.Booked.Add(new WorkshopJobInfo { Train = t.Id.Value, Intervention = def.Id, Days = def.Days, Parts = Fleet.PartsFor(w, t, def), QueuedDay = -1 });
}
return reg;
}
/// <summary>Testo italiano del motivo dei posti scoperti (per i lettori senza il blocco F4).</summary>
public static string ReasonText(World w, UncoveredReason reason, LineId line, PaxClass cls) => reason switch
{
UncoveredReason.NoStation => "nessuna stazione serve il posto di lavoro",
UncoveredReason.NoTownInReach => $"nessuna città raggiungibile entro {(cls == PaxClass.Staff ? w.Data.Balance.Employment.StaffMaxMinutes : w.Data.Balance.Employment.WorkerMaxMinutes):F0} min",
UncoveredReason.NoFreeWorkers => "le città raggiungibili non hanno lavoratori liberi",
UncoveredReason.NoStaffServices => "città senza servizi per il personale",
UncoveredReason.LineCapacity => $"capacità delle carrozze insufficiente sulla {(line.IsValid && line.Value < w.Lines.Count ? w.Lines[line.Value].Name : "linea")}",
_ => "",
};
/// <summary>
/// Registro degli impieghi della compagnia: industrie servite dai suoi treni e suoi depositi, con
/// provenienze, posti scoperti e motivi, più le convenzioni proposte o attive.
/// </summary>
public static EmploymentReport Employment(World w, CompanyId company)
{
var report = new EmploymentReport { Day = w.Clock.Day };
var places = new List<IWorkplace>();
EmploymentSystem.Workplaces(w, places);
foreach (var p in places)
{
bool mine = p is Depot depot && depot.Owner == company;
var sources = new List<EmploymentSource>();
foreach (var c in w.Commutes)
{
if (c.Workplace != p.Ref || (!mine && c.Carrier != company)) continue;
sources.Add(new EmploymentSource
{
Town = c.Town.Value, HomeStation = c.HomeStation.Value, Line = c.Route.Count > 0 ? c.Route[0].Value : -1,
Category = (byte)c.Category, Headcount = c.Headcount, Coverage = (float)c.Coverage,
});
}
bool served = w.Network.Stations.Any(s => s.Owner == company && w.Network.IsAlive(s) && p is Industry ind && s.Industries.Contains(ind.Id));
if (!mine && sources.Count == 0 && !served) continue;
string reason = string.Join("; ", new[]
{
ReasonText(w, p.WorkersReason, p.WorkersReasonLine, PaxClass.Worker),
ReasonText(w, p.StaffReason, p.StaffReasonLine, PaxClass.Staff),
}.Where(x => x.Length > 0));
report.Rows.Add(new EmploymentRow
{
Industry = p.Ref.Index, JobsWorkers = p.JobsWorkers, JobsStaff = p.JobsStaff,
WorkersPresent = (float)p.WorkersPresent, StaffPresent = (float)p.StaffPresent, Reason = reason, Sources = sources,
Kind = (byte)p.Ref.Kind, WorkersReason = (byte)p.WorkersReason, StaffReason = (byte)p.StaffReason,
WorkersReasonLine = p.WorkersReasonLine.Value, StaffReasonLine = p.StaffReasonLine.Value,
});
}
foreach (var a in w.Agreements)
{
if (a.Carrier != company) continue;
report.Agreements.Add(new AgreementInfo
{
Id = a.Id.Value, Industry = a.Industry.Value, Carrier = a.Carrier.Value, SeatsPerDay = a.SeatsPerDay, MonthlyFee = a.MonthlyFee,
State = (byte)a.State, ProposedDay = a.ProposedDay, StartDay = a.StartDay, EndDay = a.EndDay, Coverage = (float)a.Coverage,
ShortDays = a.ShortDays,
});
}
return report;
}
public static EdgeInfo Edge(World w, TrackEdge e)
{
float progress = 1;
if (e.Project >= 0 && e.Project < w.Network.Projects.Count)
{
var p = w.Network.Projects[e.Project];
if (!p.Done) progress = (float)Math.Clamp(p.ProgressDays / Math.Max(1, p.TotalDays), 0, 1);
}
return new EdgeInfo
{
Id = e.Id.Value, Owner = e.Owner.Value, A = e.A.Value, B = e.B.Value, TrackClass = (byte)e.TrackClass, DoubleTrack = e.DoubleTrack,
Electrified = e.Electrified, State = (byte)e.State, Condition = (float)e.Condition, StructureCondition = (float)e.StructureCondition,
Progress = progress, S = e.S, X = e.X, Y = e.Y, H = e.H, Ground = e.Ground, Kinds = e.Kinds.Select(k => (byte)k).ToArray(),
SpeedLimitKmh = e.SpeedLimitKmh, Signals = e.Signals.ToArray(),
};
}
/// <summary>
/// Moto di un treno: i passi del percorso dalla coda (testa meno lunghezza) fino al tratto
/// prenotato, con la distanza della testa misurata dal primo passo incluso.
/// </summary>
public static TrainMotion? Motion(World w, Train t)
{
if (t.Removed || t.Route.Count == 0 || t.State == TrainState.InDepot) return null;
var net = w.Network;
int index = Math.Clamp(t.RouteIndex, 0, t.Route.Count - 1);
double headInStep = Math.Min(t.StepPos, net.Edges[t.Route[index].Edge.Value].Length);
// risale fino al passo che contiene la coda
int first = index;
double behind = t.LengthM - headInStep;
while (behind > 0 && first > 0)
{
first--;
behind -= net.Edges[t.Route[first].Edge.Value].Length;
}
int last = Math.Clamp(Math.Max(index, t.ReservedStep), index, t.Route.Count - 1);
var segments = new List<MotionSegment>(last - first + 1);
double head = 0;
for (int i = first; i <= last; i++)
{
var step = t.Route[i];
double len = net.Edges[step.Edge.Value].Length;
segments.Add(step.Forward ? new MotionSegment(step.Edge.Value, true, 0, len) : new MotionSegment(step.Edge.Value, false, len, 0));
if (i < index) head += len;
}
head += headInStep;
double cond = 100;
foreach (var vid in t.Vehicles)
{
var v = w.Vehicles[vid.Value];
foreach (double c in v.Components) cond = Math.Min(cond, c);
}
return new TrainMotion
{
TrainId = t.Id.Value, Tick = w.Clock.Tick, State = (byte)t.State, Condition = (float)cond, Speed = (float)t.Speed,
LengthM = (float)t.LengthM, HeadDistance = head, Segments = segments,
};
}
/// <summary>Punto della testa del treno sul server (riferimento dei test di coerenza).</summary>
public static Vec2? HeadPoint(World w, Train t)
{
if (t.Route.Count == 0) return t.AtNode.IsValid ? w.Network.Nodes[t.AtNode.Value].Position : null;
int index = Math.Clamp(t.RouteIndex, 0, t.Route.Count - 1);
var step = t.Route[index];
var edge = w.Network.Edges[step.Edge.Value];
double s = Math.Min(t.StepPos, edge.Length);
return edge.PointAt(step.Forward ? s : edge.Length - s);
}
public static EventInfo Event(GameEvent e) => new()
{
Day = e.Day, Kind = (byte)e.Kind, Severity = (byte)e.Severity, Text = e.Text, Entity = (byte)e.Entity, EntityIndex = e.EntityIndex,
Company = e.Company.IsValid ? e.Company.Value : -1,
};
public static DailyDigest Digest(World w, Company company, List<EventInfo> events, bool slow, byte speed, float tickMs) => new()
{
Day = w.Clock.Day,
Tick = w.Clock.Tick,
Date = w.Clock.Date.ToString(),
Cash = company.Cash,
NetWorth = company.NetWorth,
Rating = company.Rating.ToString(),
Prices = w.Market.GlobalPrice.Select(p => Money.FromCentsRounded(p)).ToList(),
Events = events,
StateHash = w.LastStateHash,
Slow = slow,
Speed = speed,
TickMs = tickMs,
};
/// <summary>Hash di un record serializzato (per i delta per sessione).</summary>
public static ulong Hash(IWritable record)
{
var w = new SpanWriter(128);
record.Write(ref w);
return XxHash64.Hash(w.Written);
}
// ------------------------------------------------------------------ F5: borsa, industrie, Cronaca
/// <summary>Listino del giorno: prezzi delle compagnie attive e offerte pubbliche in corso.</summary>
public static MarketTape Tape(World w, CompanyId viewer)
{
var tape = new MarketTape { Day = w.Clock.Day };
foreach (var c in w.Companies)
{
if (c.Defunct) continue;
double last = c.PriceHistory.Count > 0 ? c.PriceHistory[^1] : c.SharePrice;
tape.Shares.Add(new SharePrice
{
Company = c.Id.Value, Price = Money.FromCentsRounded(c.SharePrice), Change = last > 0 ? (float)(c.SharePrice / last - 1) : 0,
Listed = c.Listed, PriceCents = Math.Round(c.SharePrice, 4), Outstanding = c.Shares.Outstanding, FreeFloat = Corporate.FreeFloat(w, c),
FounderShare = (float)c.Shares.FounderFraction, ControlledBy = c.ControlledBy.Value,
});
}
foreach (var b in w.Bids)
{
if (b.State != BidState.Open) continue;
var target = w.Company(b.Target);
tape.Bids.Add(new BidInfo
{
Bid = b.Id.Value, Bidder = b.Bidder.Value, Target = b.Target.Value, PricePerShare = new Money(b.PricePerShare), TargetShare = b.TargetShare,
ExpiresDay = b.EndDay, State = (byte)b.State,
CommittedShare = target.Shares.Outstanding > 0 ? (double)StockMarketSystem.Committed(w, b) / target.Shares.Outstanding : 0,
Defenses = b.Defenses, Knight = b.Knight.Value, Accepted = b.Accepted.Contains(viewer),
});
}
return tape;
}
private static CompanyYearInfo YearInfo(CompanyYear y) => new()
{
Year = y.Year, NetWorth = new Money(y.NetWorthCents), Cash = new Money(y.CashCents), Revenue = new Money(y.RevenueCents),
Profit = new Money(y.ProfitCents), Tier = (byte)y.Tier, Trains = y.Trains, TrackKm = (float)y.TrackKm, SharePrice = new Money(y.SharePriceCents),
};
/// <summary>Scheda di una compagnia: libro dei soci, prezzi mensili, storico annuale, asta.</summary>
public static CompanyCard CompanyCard(World w, Company c)
{
var holdings = new List<HoldingInfo>
{
new() { Holder = HoldingInfo.Founder, Shares = c.Shares.Founder },
new() { Holder = HoldingInfo.Market, Shares = c.Shares.Public },
};
for (int i = 0; i < c.Shares.ByCompany.Length; i++)
{
if (c.Shares.ByCompany[i] > 0) holdings.Add(new HoldingInfo { Holder = i, Shares = c.Shares.ByCompany[i] });
}
long dividends = 0;
foreach (long d in c.DividendRing) dividends += d;
var auction = w.Auctions.FirstOrDefault(a => a.Seller == c.Id && !a.Closed);
return new CompanyCard
{
Company = c.Id.Value, TotalShares = c.Shares.Total, Treasury = c.Shares.Treasury, Holdings = holdings,
PriceHistory = [.. c.PriceHistory], History = c.History.Select(YearInfo).ToList(),
AnnualProfit = new Money(c.AnnualProfit), DividendsYear = new Money(dividends), Debt = c.Debt, MarketCap = Money.FromCentsRounded(c.MarketCap),
ControlDays = c.ControlledBy.IsValid ? w.Clock.Day - c.ControlSinceDay : -1,
AuctionMin = new Money(auction?.MinPriceCents ?? 0), AuctionBest = new Money(auction?.BestPriceCents ?? 0),
AuctionBestBidder = auction?.BestBidder.Value ?? -1, AuctionEndDay = auction?.EndDay ?? -1,
};
}
/// <summary>Scheda del proprietario di un'industria (sezione 11).</summary>
public static IndustryCard IndustryCard(World w, Industry ind)
{
var m = w.Data.Balance.IndustryMaintenance;
var budget = m.For(ind.Budget);
double wear = m.WearPerDay * Math.Max(0, ind.Efficiency) * ind.Def.WearIntensity * w.Difficulty.WearMultiplier;
double recovery = budget.RecoveryPerDay * (ind.PartsShort ? m.NoPartsRecoveryFactor : 1);
double hazard = ind.Condition >= m.BreakdownPivot ? 0 : m.BreakdownBase * DMath.Exp((m.BreakdownPivot - ind.Condition) / m.BreakdownScale);
double perYear = 1 - DMath.Pow(1 - Math.Min(1, hazard), w.Calendar.DaysPerYear);
return new IndustryCard
{
Industry = ind.Id.Value, Margin = (float)ind.Margin, ConditionMultiplier = (float)IndustryMath.ConditionMultiplier(ind.Condition, m),
WearPerDay = (float)wear, RecoveryPerDay = (float)recovery, MaintenanceCostPerDay = Money.FromCentsRounded(ind.RevenueEma * budget.CostShareOfRevenue),
MaintenanceSpentYear = new Money(ind.MaintenanceSpentYear), PartsTarget = IndustryMath.PartsTarget(ind, m), PartsPerMonth = IndustryMath.MonthlyPartsUse(ind, m),
PartsOrdered = ind.PartsOrdered, MachineryRequired = IndustryMath.MachineryRequired(ind, m), UpgradeCost = IndustryMaintenanceSystem.UpgradeCost(ind),
Valuation = IndustryMath.Valuation(w, ind), Cash = ind.Cash, BreakdownChancePerYear = (float)perYear,
Stops = ind.StopHistory.Select(h => new IndustryStopInfo { Day = h.Day, Days = h.Days, Kind = (byte)h.Kind }).ToList(),
};
}
/// <summary>Cronaca finale (o provvisoria, se la partita è in corso) della compagnia del giocatore.</summary>
public static Chronicle Chronicle(World w)
{
var report = ChronicleReport.Build(w);
return new Chronicle
{
GameOver = w.GameOver is not null, Reason = (byte)(w.GameOver?.Reason ?? GameOverReason.None), Text = w.GameOver?.Text ?? "",
Winner = w.GameOver?.Winner.Value ?? -1, Day = w.GameOver?.Day ?? w.Clock.Day, Company = w.Player.Name,
FoundedYear = w.Calendar.StartYear, Prestige = report.Prestige,
History = report.History.Select(YearInfo).ToList(),
Records = report.Records.Select(r => new RecordInfo { Title = r.Title, Value = r.Value, Year = r.Year }).ToList(),
Highlights = report.Highlights,
};
}
/// <summary>Quadro del mercato globale per la compagnia della sessione (MarketOutlook, ADR 0015).</summary>
public static MarketReport Market(World w, CompanyId company)
{
var report = MarketOutlook.Build(w, company);
var trading = report.Trading;
return new MarketReport
{
Day = report.Day,
Index = (float)report.Index,
IndexChange = (float)report.IndexChange,
Goods = report.Goods.Select(g => new GoodMarketInfo
{
Good = g.Good, Available = g.Available, Price = g.Price, Change = (float)g.Change,
SupplyMonth = g.SupplyMonth, DemandMonth = g.DemandMonth, WorldSupplyMonth = g.WorldSupplyMonth, WorldDemandMonth = g.WorldDemandMonth,
StockUnits = g.StockUnits, StockMonths = (float)g.StockMonths,
History = g.History.Select(p => new PricePointInfo { Day = p.Day, Price = p.Price }).ToList(),
Forecast = g.Forecast.Select(f => new ForecastInfo { Months = (byte)f.Months, Price = f.Price, Low = f.Low, High = f.High }).ToList(),
SellPlaces = g.SellPlaces.Select(p => new SellPlaceInfo { Kind = (byte)p.Kind, Target = p.Target, Price = p.Price, Line = p.Line.Value }).ToList(),
}).ToList(),
Hubs = report.Hubs.Select(h => new HubMarketInfo
{
Hub = h.Hub.Value, Kind = (byte)h.Kind, MonthlyCapacity = h.MonthlyCapacity, Duty = (float)h.Duty, UsedThisMonth = h.UsedThisMonth, Line = h.Line.Value,
}).ToList(),
EventGood = report.Event.Good, EventShock = (float)report.Event.Shock, EventMonths = (float)report.Event.Months,
TradingUnlocked = trading.Unlocked, TradingTier = (byte)trading.Level, TradingProgress = (float)trading.Fraction,
NetWorth = trading.NetWorth, NetWorthRequired = trading.NetWorthRequired, TownsConnected = trading.TownsConnected,
TownsRequired = trading.TownsRequired, TownPopulation = trading.TownPopulation, Rating = trading.Rating.ToString(),
RatingRequired = trading.RatingRequired.ToString(), RatingMet = trading.RatingMet,
};
}
}