Correzioni dalla revisione della scheda industria e della schermata di
connessione.
- Dati di altre compagnie: la forza lavoro della scheda mostra solo i
contratti a piedi, quelli della compagnia della sessione e, se
l'industria è sua, quelli di tutti i vettori, come il Registro degli
impieghi. Lo stesso filtro vale per provenienze, conteggio e viaggio
medio.
- Prezzo: «prezzo medio realizzato» mescolava una media mobile dei
ricavi con i totali del trimestre in corso. Al suo posto c'è il prezzo
di vendita, cioè il prezzo globale del giorno (SalePrice).
- Avvisi del server: hanno il giorno −1, così il rifiuto di Load o
NewGame non si confonde più con gli eventi del mondo che arrivano
mentre si aspetta il Welcome.
- Schermata di connessione:
- all'apertura avvia la strada scelta l'ultima volta;
- cambiando strada chiude la sessione dell'altra;
- senza sessione «Connetti e riprendi» la apre;
- il cambio di lingua passa la sessione alla schermata nuova;
- la scelta del salvataggio si tiene per id;
- Load e nuova partita chiedono conferma;
- stato del server su 3×2 con la versione del protocollo, salvataggi
su tre colonne, «Attivo da» che avanza.
- Scheda dell'industria:
- collegamenti e nodi non collegati sono leggibili;
- testo per l'industria inattiva;
- revisione e ammodernamento disabilitati, con il motivo, quando il
server li rifiuterebbe;
- l'esito dell'acquisto compare accanto al pulsante;
- le righe lunghe vanno a capo;
- «in sede» al posto di «al lavoro ora».
- Gli avvisi dei comandi compaiono anche sulle schermate a tutto
schermo.
- Pilota automatico:
- la schermata 20 sta su un suo CanvasLayer sopra l'interfaccia;
- 12 e 12b sono ora la scheda a tutto schermo.
- Test: pendolari di altri vettori nascosti, Load rifiutato via
WebSocket, Welcome senza ServerInfo. 202 test, 183 senza i lenti.
Refs #42.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
528 lines
27 KiB
C#
528 lines
27 KiB
C#
using RailEnterprise.Core.Common;
|
||
using RailEnterprise.Core.Data;
|
||
using RailEnterprise.Core.Rail;
|
||
using RailEnterprise.Core.Simulation;
|
||
using RailEnterprise.Core.Simulation.Systems;
|
||
|
||
namespace RailEnterprise.Core.Economy;
|
||
|
||
/// <summary>
|
||
/// Fattore che limita l'efficienza dell'industria (e = min(copertura input, lavoratori, personale) ×
|
||
/// pf × mc × giacimento × eventi, guida 6.3): il più basso sotto 1, nell'ordine dell'enum a parità.
|
||
/// </summary>
|
||
public enum IndustryLimit : byte
|
||
{
|
||
/// <summary>Nessun fattore sotto 1: l'industria lavora a piena capacità.</summary>
|
||
None = 0,
|
||
Inputs = 1,
|
||
Workers = 2,
|
||
Staff = 3,
|
||
/// <summary>Fattore di profitto (margine negativo).</summary>
|
||
Profit = 4,
|
||
/// <summary>Condizione degli impianti sotto la soglia del rendimento pieno.</summary>
|
||
Condition = 5,
|
||
/// <summary>Giacimento sotto la soglia di esaurimento.</summary>
|
||
Depletion = 6,
|
||
/// <summary>Evento del mondo sulla capacità (incidente).</summary>
|
||
Event = 7,
|
||
/// <summary>Fermo in corso (guasto, incidente, revisione, ammodernamento).</summary>
|
||
Stopped = 8,
|
||
/// <summary>Livello 0 (dormiente) o industria chiusa.</summary>
|
||
Dormant = 9,
|
||
}
|
||
|
||
/// <summary>Tipo di nodo della catena produttiva.</summary>
|
||
public enum ChainPartnerKind : byte { Industry = 0, Hub = 1, Town = 2 }
|
||
|
||
/// <summary>
|
||
/// Fornitore o cliente di un bene nella catena produttiva: unità al mese (produzione attuale del
|
||
/// fornitore, fabbisogno a piena capacità del cliente, capacità mensile dell'hub, domanda della
|
||
/// città), prezzo (centesimi per unità: prezzo globale per chi vende al mercato, prezzo locale
|
||
/// dell'ADR 0004 per l'industria che compra, prezzo dell'hub con il dazio), linea della compagnia che
|
||
/// collega i due (None se nessuna) e distanza in linea d'aria.
|
||
/// </summary>
|
||
public readonly record struct ChainPartner(ChainPartnerKind Kind, int Target, double MonthlyUnits, double Price, LineId Line, double DistanceKm);
|
||
|
||
/// <summary>
|
||
/// Un input o un output dell'industria al livello attuale: quantità al mese a piena efficienza e al
|
||
/// ritmo attuale, scorta e capienza del magazzino, giorni di scorta (input, al ritmo dei presenti) o
|
||
/// giorni prima che il magazzino si riempia (output, al ritmo attuale; oltre si perde la merce);
|
||
/// −1 se il ritmo è nullo. Partner: fornitori (input) o clienti (output).
|
||
/// </summary>
|
||
public sealed class IndustryFlow
|
||
{
|
||
public required int Good { get; init; }
|
||
public required double FullMonth { get; init; }
|
||
public required double CurrentMonth { get; init; }
|
||
public required int Stock { get; init; }
|
||
public required int Storage { get; init; }
|
||
public required double Days { get; init; }
|
||
/// <summary>Input che limita l'efficienza (quello con meno giorni di scorta quando il limite sono gli input).</summary>
|
||
public required bool Limiting { get; init; }
|
||
public required List<ChainPartner> Partners { get; init; }
|
||
}
|
||
|
||
/// <summary>Provenienza dei lavoratori (o del personale): città, linea del primo tratto, vettore, minuti di viaggio.</summary>
|
||
public readonly record struct WorkforceSource(TownId Town, int Headcount, double Coverage, LineId Line, CompanyId Carrier, double Minutes, bool Walking);
|
||
|
||
/// <summary>Lavoratori o personale qualificato dell'industria.</summary>
|
||
public sealed class WorkforceOutlook
|
||
{
|
||
public required int Jobs { get; init; }
|
||
public required double Present { get; init; }
|
||
/// <summary>Persone in sede: posti coperti da chi vive negli alloggi dell'industria (posti × quota in sede).</summary>
|
||
public required double OnSite { get; init; }
|
||
/// <summary>Copertura media su coverageWindowDays (entra nell'efficienza).</summary>
|
||
public required double Coverage { get; init; }
|
||
/// <summary>Posti scoperti oggi (posti − presenti, arrotondato).</summary>
|
||
public required int Missing { get; init; }
|
||
public required UncoveredReason Reason { get; init; }
|
||
public required LineId ReasonLine { get; init; }
|
||
/// <summary>Viaggio medio in treno (minuti, pesato sulle persone) dei contratti visibili; −1 se nessuno.</summary>
|
||
public required double AverageMinutes { get; init; }
|
||
/// <summary>Provenienze più numerose (al massimo industry.outlook.workforceSources).</summary>
|
||
public required List<WorkforceSource> Sources { get; init; }
|
||
/// <summary>Provenienze visibili in tutto (anche quelle non elencate).</summary>
|
||
public required int SourceCount { get; init; }
|
||
}
|
||
|
||
/// <summary>Crescita trimestrale (guida 6.3): punteggio del trimestre in corso, soglie e trimestri.</summary>
|
||
public sealed class GrowthOutlook
|
||
{
|
||
public required double LastScore { get; init; }
|
||
public required GrowthScoreParts Current { get; init; }
|
||
public required double UpgradeThreshold { get; init; }
|
||
public required double DowngradeThreshold { get; init; }
|
||
public required int UpgradeQuarters { get; init; }
|
||
public required int QuartersAbove { get; init; }
|
||
/// <summary>Giorni del trimestre già contati e lunghezza del trimestre.</summary>
|
||
public required int QuarterDay { get; init; }
|
||
public required int QuarterDays { get; init; }
|
||
/// <summary>Servita da un vettore nel trimestre: solo allora il livello cambia (ADR 0004).</summary>
|
||
public required bool Served { get; init; }
|
||
public required int MaxLevel { get; init; }
|
||
}
|
||
|
||
/// <summary>Scheda dell'industria per la compagnia della sessione (immagine di riferimento 07, ADR 0021).</summary>
|
||
public sealed class IndustryOutlookReport
|
||
{
|
||
public required IndustryId Industry { get; init; }
|
||
public required int Level { get; init; }
|
||
public required int MaxLevel { get; init; }
|
||
public required double Efficiency { get; init; }
|
||
public required IndustryLimit Limit { get; init; }
|
||
public required double CovInput { get; init; }
|
||
public required double CovWorkers { get; init; }
|
||
public required double CovStaff { get; init; }
|
||
public required int CoverageWindowDays { get; init; }
|
||
public required double ProfitFactor { get; init; }
|
||
public required double ConditionMultiplier { get; init; }
|
||
public required double Depletion { get; init; }
|
||
public required double EventCapacity { get; init; }
|
||
/// <summary>Riserva residua del giacimento (0–1); −1 se l'industria non è esauribile.</summary>
|
||
public required double ReserveFraction { get; init; }
|
||
public required int StorageDays { get; init; }
|
||
public required List<IndustryFlow> Inputs { get; init; }
|
||
public required List<IndustryFlow> Outputs { get; init; }
|
||
public required WorkforceOutlook Workers { get; init; }
|
||
public required WorkforceOutlook Staff { get; init; }
|
||
/// <summary>
|
||
/// Prezzo di vendita del prodotto (centesimi): il prezzo globale del giorno, quello a cui le
|
||
/// industrie vendono al mercato (ADR 0004); −1 senza prodotti o con più prodotti.
|
||
/// </summary>
|
||
public required double SalePrice { get; init; }
|
||
public required Money AnnualProfit { get; init; }
|
||
public required GrowthOutlook Growth { get; init; }
|
||
/// <summary>Stazioni (di qualunque compagnia) che servono l'industria con una linea con treni.</summary>
|
||
public required List<StationId> ServingStations { get; init; }
|
||
/// <summary>Linea della compagnia della sessione che serve l'industria (id più basso), None se nessuna.</summary>
|
||
public required LineId ServingLine { get; init; }
|
||
/// <summary>Dei privati e attiva: si può comprare (dal livello che sblocca l'acquisto).</summary>
|
||
public required bool ForSale { get; init; }
|
||
public required bool BuyUnlocked { get; init; }
|
||
public required int BuyTier { get; init; }
|
||
/// <summary>Avanzamento verso il livello che sblocca l'acquisto (ADR 0018); 1 se sbloccato.</summary>
|
||
public required double BuyProgress { get; init; }
|
||
}
|
||
|
||
/// <summary>
|
||
/// Scheda dell'industria (ADR 0021): legge il mondo e non scrive nulla, come MarketOutlook e
|
||
/// ClimbOutlook. Catena produttiva con fornitori e clienti per bene, coperture, forza lavoro con le
|
||
/// provenienze, produzione e magazzino, fattore limitante, crescita trimestrale e acquisto.
|
||
/// </summary>
|
||
public static class IndustryOutlook
|
||
{
|
||
public static IndustryOutlookReport Build(World w, Industry ind, CompanyId company)
|
||
{
|
||
var data = w.Data;
|
||
var ib = data.Balance.Industry;
|
||
var g = data.Balance.Growth;
|
||
int dpm = w.Calendar.DaysPerMonth;
|
||
long today = w.Clock.Day;
|
||
var recipe = ind.Def.Recipe;
|
||
var factors = Factors(w, ind);
|
||
var links = new LineLinks(w, company);
|
||
var mine = links.Serving(ind);
|
||
|
||
// ritmo dei presenti senza la copertura degli input (giorni di scorta) e ritmo effettivo
|
||
double cyclesFull = ind.Closed ? 0 : ind.CyclesPerDayAtFullCapacity(dpm);
|
||
double labour = factors.Stopped || ind.Closed
|
||
? 0
|
||
: Math.Min(ind.CovWorkers, ind.CovStaff) * factors.ProfitFactor * factors.ConditionMultiplier * factors.Depletion * factors.EventCapacity;
|
||
double efficiency = ind.Closed ? 0 : ind.Efficiency;
|
||
|
||
int limiting = -1;
|
||
if (factors.Limit == IndustryLimit.Inputs)
|
||
{
|
||
double least = double.MaxValue;
|
||
for (int i = 0; i < recipe.Inputs.Count; i++)
|
||
{
|
||
double perDay = cyclesFull * recipe.Inputs[i].PerCycle * labour;
|
||
double days = perDay > 0 ? ind.InputStock[i] / perDay : double.MaxValue;
|
||
if (limiting < 0 || days < least)
|
||
{
|
||
least = days;
|
||
limiting = i;
|
||
}
|
||
}
|
||
}
|
||
var inputs = new List<IndustryFlow>(recipe.Inputs.Count);
|
||
for (int i = 0; i < recipe.Inputs.Count; i++)
|
||
{
|
||
int good = recipe.Inputs[i].GoodIndex;
|
||
double full = cyclesFull * recipe.Inputs[i].PerCycle * dpm;
|
||
double perDay = cyclesFull * recipe.Inputs[i].PerCycle * labour;
|
||
inputs.Add(new IndustryFlow
|
||
{
|
||
Good = good, FullMonth = full, CurrentMonth = full * efficiency, Stock = ind.InputStock[i],
|
||
Storage = IndustryMath.InputCapacity(ind, i, dpm), Days = perDay > 0 ? ind.InputStock[i] / perDay : -1,
|
||
Limiting = i == limiting, Partners = Suppliers(w, ind, good, links, mine),
|
||
});
|
||
}
|
||
var outputs = new List<IndustryFlow>(recipe.Outputs.Count);
|
||
for (int o = 0; o < recipe.Outputs.Count; o++)
|
||
{
|
||
int good = recipe.Outputs[o].GoodIndex;
|
||
double full = cyclesFull * recipe.Outputs[o].PerCycle * dpm;
|
||
double perDay = full * efficiency / dpm;
|
||
int storage = IndustryMath.OutputCapacity(ind, o, dpm);
|
||
outputs.Add(new IndustryFlow
|
||
{
|
||
Good = good, FullMonth = full, CurrentMonth = full * efficiency, Stock = ind.OutputStock[o], Storage = storage,
|
||
Days = perDay > 0 ? Math.Max(0, storage - ind.OutputStock[o]) / perDay : -1,
|
||
Limiting = false, Partners = Customers(w, ind, good, links, mine),
|
||
});
|
||
}
|
||
|
||
// prezzo di vendita: le industrie vendono al prezzo globale del giorno (ADR 0004). Una media dei
|
||
// ricavi mescolerebbe la media mobile dei ricavi con i totali del trimestre in corso
|
||
double salePrice = recipe.Outputs.Count == 1 ? w.Market.GlobalPrice[recipe.Outputs[0].GoodIndex] : -1;
|
||
|
||
var buyTier = data.Tiers.Tiers.FirstOrDefault(t => t.Unlocks.BuyIndustry);
|
||
var owner = company.IsValid && company.Value < w.Companies.Count ? w.Companies[company.Value] : null;
|
||
bool buyUnlocked = owner is not null && Tiers.Unlocks(w, owner).BuyIndustry;
|
||
double buyProgress = buyUnlocked ? 1 : owner is not null && buyTier is not null ? ClimbOutlook.Requirements(w, owner, buyTier).Progress : 0;
|
||
|
||
return new IndustryOutlookReport
|
||
{
|
||
Industry = ind.Id,
|
||
Level = ind.Level,
|
||
MaxLevel = g.MaxLevel,
|
||
Efficiency = efficiency,
|
||
Limit = factors.Limit,
|
||
CovInput = ind.CovInput,
|
||
CovWorkers = ind.CovWorkers,
|
||
CovStaff = ind.CovStaff,
|
||
CoverageWindowDays = ib.CoverageWindowDays,
|
||
ProfitFactor = factors.ProfitFactor,
|
||
ConditionMultiplier = factors.ConditionMultiplier,
|
||
Depletion = factors.Depletion,
|
||
EventCapacity = factors.EventCapacity,
|
||
ReserveFraction = factors.ReserveFraction,
|
||
StorageDays = ind.Def.StorageDays,
|
||
Inputs = inputs,
|
||
Outputs = outputs,
|
||
Workers = Workforce(w, ind, PaxClass.Worker, company),
|
||
Staff = Workforce(w, ind, PaxClass.Staff, company),
|
||
SalePrice = salePrice,
|
||
AnnualProfit = Money.FromCentsRounded(IndustryMath.AnnualProfit(w, ind)),
|
||
Growth = new GrowthOutlook
|
||
{
|
||
LastScore = ind.LastScore,
|
||
Current = IndustryMath.GrowthScore(ind, g),
|
||
UpgradeThreshold = g.UpgradeThreshold,
|
||
DowngradeThreshold = g.DowngradeThreshold,
|
||
UpgradeQuarters = g.UpgradeQuarters,
|
||
QuartersAbove = ind.QuartersAboveUpgrade,
|
||
QuarterDay = ind.QuarterDays,
|
||
QuarterDays = g.QuarterDays,
|
||
Served = ind.ServedWithin(today, g.QuarterDays),
|
||
MaxLevel = g.MaxLevel,
|
||
},
|
||
ServingStations = ServingStations(w, ind),
|
||
ServingLine = mine.Count > 0 ? mine[0].Id : LineId.None,
|
||
ForSale = !ind.Owner.IsValid && !ind.Closed && ind.Level > 0,
|
||
BuyUnlocked = buyUnlocked,
|
||
BuyTier = buyTier?.Level ?? 0,
|
||
BuyProgress = buyProgress,
|
||
};
|
||
}
|
||
|
||
/// <summary>Fattori dell'efficienza dell'industria e quello che la limita.</summary>
|
||
public readonly record struct EfficiencyFactors(
|
||
double ProfitFactor, double ConditionMultiplier, double Depletion, double EventCapacity, double ReserveFraction, bool Stopped, IndustryLimit Limit);
|
||
|
||
/// <summary>
|
||
/// Fattori dell'efficienza come li usa la produzione (IndustrySystem): coperture medie, fattore di
|
||
/// profitto, condizione degli impianti, giacimento, eventi; il limite è il fattore più basso sotto 1
|
||
/// (a parità nell'ordine di <see cref="IndustryLimit"/>), Fermo se l'industria è ferma, Dormiente al
|
||
/// livello 0 o chiusa.
|
||
/// </summary>
|
||
public static EfficiencyFactors Factors(World w, Industry ind)
|
||
{
|
||
var data = w.Data;
|
||
double pf = IndustryMath.ProfitFactor(ind, data.Balance.Industry);
|
||
double mc = IndustryMath.ConditionMultiplier(ind.Condition, data.Balance.IndustryMaintenance);
|
||
double depletion = 1;
|
||
double reserve = -1;
|
||
if (ind.Def.Depletable && ind.Site.IsValid)
|
||
{
|
||
reserve = w.Sites[ind.Site.Value].ReserveFraction;
|
||
double start = data.Balance.Industry.DepletionStartFraction;
|
||
if (reserve < start) depletion = Math.Max(0, reserve) / start;
|
||
}
|
||
double capacity = w.WorldEvents.IndustryCapacity(ind.Id);
|
||
bool stopped = ind.IsStopped(w.Clock.Day);
|
||
IndustryLimit limit;
|
||
if (ind.Closed || ind.Level <= 0) limit = IndustryLimit.Dormant;
|
||
else if (stopped) limit = IndustryLimit.Stopped;
|
||
else
|
||
{
|
||
limit = IndustryLimit.None;
|
||
double least = 1;
|
||
void Consider(IndustryLimit kind, double value)
|
||
{
|
||
if (value < least)
|
||
{
|
||
least = value;
|
||
limit = kind;
|
||
}
|
||
}
|
||
if (ind.Def.Recipe.Inputs.Count > 0) Consider(IndustryLimit.Inputs, ind.CovInput);
|
||
if (ind.JobsWorkers > 0) Consider(IndustryLimit.Workers, ind.CovWorkers);
|
||
if (ind.JobsStaff > 0) Consider(IndustryLimit.Staff, ind.CovStaff);
|
||
Consider(IndustryLimit.Profit, pf);
|
||
Consider(IndustryLimit.Condition, mc);
|
||
Consider(IndustryLimit.Depletion, depletion);
|
||
Consider(IndustryLimit.Event, capacity);
|
||
}
|
||
return new EfficiencyFactors(pf, mc, depletion, capacity, reserve, stopped, limit);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Lavoratori o personale: presenti, persone in sede, posti scoperti con il motivo e provenienze per
|
||
/// città e linea. Come il Registro degli impieghi (Projection.Employment), la compagnia vede i
|
||
/// contratti a piedi e quelli che trasporta lei; quelli degli altri vettori solo se l'industria è
|
||
/// sua. Presenti e copertura restano quelli dell'industria.
|
||
/// </summary>
|
||
public static WorkforceOutlook Workforce(World w, Industry ind, PaxClass cls, CompanyId company)
|
||
{
|
||
var ib = w.Data.Balance.Industry;
|
||
bool staff = cls == PaxClass.Staff;
|
||
int jobs = staff ? ind.JobsStaff : ind.JobsWorkers;
|
||
double present = staff ? ind.StaffPresent : ind.WorkersPresent;
|
||
var me = WorkplaceRef.Of(ind.Id);
|
||
// contratti raggruppati per città, primo tratto, vettore e modo (a piedi o in treno), nell'ordine dei contratti
|
||
var groups = new List<(TownId Town, LineId Line, CompanyId Carrier, bool Walking, int Headcount, double CoverageSum, double MinutesSum)>();
|
||
double railPeople = 0, railMinutes = 0;
|
||
foreach (var c in w.Commutes)
|
||
{
|
||
if (c.Workplace != me || c.Category != cls || c.Headcount <= 0) continue;
|
||
if (!Visible(c, ind, company)) continue;
|
||
var line = c.Route.Count > 0 ? c.Route[0] : LineId.None;
|
||
int at = groups.FindIndex(x => x.Town == c.Town && x.Line == line && x.Carrier == c.Carrier && x.Walking == c.Walking);
|
||
if (at < 0)
|
||
{
|
||
groups.Add((c.Town, line, c.Carrier, c.Walking, 0, 0, 0));
|
||
at = groups.Count - 1;
|
||
}
|
||
var gr = groups[at];
|
||
groups[at] = gr with
|
||
{
|
||
Headcount = gr.Headcount + c.Headcount,
|
||
CoverageSum = gr.CoverageSum + c.Coverage * c.Headcount,
|
||
MinutesSum = gr.MinutesSum + c.ExpectedMinutes * c.Headcount,
|
||
};
|
||
if (!c.Walking)
|
||
{
|
||
railPeople += c.Headcount;
|
||
railMinutes += c.ExpectedMinutes * c.Headcount;
|
||
}
|
||
}
|
||
var sources = groups
|
||
.Select(x => new WorkforceSource(x.Town, x.Headcount, x.CoverageSum / x.Headcount, x.Line, x.Carrier, x.MinutesSum / x.Headcount, x.Walking))
|
||
.OrderByDescending(s => s.Headcount).ThenBy(s => s.Town.Value).ThenBy(s => s.Line.Value).ThenBy(s => s.Carrier.Value).ThenBy(s => s.Walking)
|
||
.Take(ib.Outlook.WorkforceSources).ToList();
|
||
return new WorkforceOutlook
|
||
{
|
||
Jobs = jobs,
|
||
Present = present,
|
||
OnSite = EmploymentSystem.OnSite(jobs, staff ? ib.OnSiteStaffShare : ib.OnSiteWorkerShare),
|
||
Coverage = staff ? ind.CovStaff : ind.CovWorkers,
|
||
Missing = (int)Math.Max(0, Math.Round(jobs - present, MidpointRounding.AwayFromZero)),
|
||
Reason = staff ? ind.StaffReason : ind.WorkersReason,
|
||
ReasonLine = staff ? ind.StaffReasonLine : ind.WorkersReasonLine,
|
||
AverageMinutes = railPeople > 0 ? railMinutes / railPeople : -1,
|
||
Sources = sources,
|
||
SourceCount = groups.Count,
|
||
};
|
||
}
|
||
|
||
/// <summary>Contratto che la compagnia può vedere: a piedi, trasportato da lei, o verso una sua industria.</summary>
|
||
public static bool Visible(CommuteContract c, Industry ind, CompanyId company) =>
|
||
c.Walking || (company.IsValid && (c.Carrier == company || ind.Owner == company));
|
||
|
||
/// <summary>
|
||
/// Fornitori di un input: industrie attive che producono il bene (unità al mese al ritmo attuale,
|
||
/// prezzo globale: le industrie vendono al mercato, ADR 0004) e hub (capacità mensile, prezzo
|
||
/// d'importazione). Prima i collegati da una linea della compagnia, poi i più vicini.
|
||
/// </summary>
|
||
private static List<ChainPartner> Suppliers(World w, Industry ind, int good, LineLinks links, List<Line> mine)
|
||
{
|
||
int dpm = w.Calendar.DaysPerMonth;
|
||
double pg = w.Market.GlobalPrice[good];
|
||
var all = new List<ChainPartner>();
|
||
foreach (var other in w.Industries)
|
||
{
|
||
if (other.Id == ind.Id || other.Closed || other.Level <= 0) continue;
|
||
int o = other.OutputIndexOf(good);
|
||
if (o < 0) continue;
|
||
double month = other.CyclesPerDayAtFullCapacity(dpm) * other.Def.Recipe.Outputs[o].PerCycle * dpm * other.Efficiency;
|
||
all.Add(new ChainPartner(ChainPartnerKind.Industry, other.Id.Value, month, pg, links.Link(mine, ChainPartnerKind.Industry, other.Id.Value), Km(ind.Position, other.Position)));
|
||
}
|
||
foreach (var h in w.Hubs)
|
||
all.Add(new ChainPartner(ChainPartnerKind.Hub, h.Id.Value, h.MonthlyCapacity, h.SellPrice(pg), links.Link(mine, ChainPartnerKind.Hub, h.Id.Value), Km(ind.Position, h.Position)));
|
||
return Pick(w, all);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Clienti di un output: industrie attive che lo consumano (fabbisogno al mese a piena capacità,
|
||
/// prezzo locale dell'ADR 0004 come «Dove conviene vendere»), hub (prezzo d'esportazione) e città con
|
||
/// domanda del bene (domanda al mese, prezzo globale). Prima i collegati, poi i più vicini.
|
||
/// </summary>
|
||
private static List<ChainPartner> Customers(World w, Industry ind, int good, LineLinks links, List<Line> mine)
|
||
{
|
||
int dpm = w.Calendar.DaysPerMonth;
|
||
double pg = w.Market.GlobalPrice[good];
|
||
var lp = w.Data.Balance.LocalPrice;
|
||
var all = new List<ChainPartner>();
|
||
foreach (var other in w.Industries)
|
||
{
|
||
if (other.Id == ind.Id || other.Closed || other.Level <= 0) continue;
|
||
int i = other.InputIndexOf(good);
|
||
if (i < 0) continue;
|
||
double month = other.CyclesPerDayAtFullCapacity(dpm) * other.Def.Recipe.Inputs[i].PerCycle * dpm;
|
||
double price = Market.LocalPrice(pg, IndustryMath.InputCapacity(other, i, dpm), other.InputStock[i], lp);
|
||
all.Add(new ChainPartner(ChainPartnerKind.Industry, other.Id.Value, month, price, links.Link(mine, ChainPartnerKind.Industry, other.Id.Value), Km(ind.Position, other.Position)));
|
||
}
|
||
foreach (var h in w.Hubs)
|
||
all.Add(new ChainPartner(ChainPartnerKind.Hub, h.Id.Value, h.MonthlyCapacity, h.BuyPrice(pg), links.Link(mine, ChainPartnerKind.Hub, h.Id.Value), Km(ind.Position, h.Position)));
|
||
foreach (var t in w.Towns)
|
||
{
|
||
if (t.DemandToday.Length <= good || t.DemandToday[good] <= 0) continue;
|
||
all.Add(new ChainPartner(ChainPartnerKind.Town, t.Id.Value, t.DemandToday[good] * dpm, pg, links.Link(mine, ChainPartnerKind.Town, t.Id.Value), Km(ind.Position, t.Position)));
|
||
}
|
||
return Pick(w, all);
|
||
}
|
||
|
||
/// <summary>Prima i collegati (per linea), poi i più vicini; a parità tipo e id; al massimo partnersPerGood.</summary>
|
||
private static List<ChainPartner> Pick(World w, List<ChainPartner> all) =>
|
||
all.OrderBy(p => p.Line.IsValid ? 0 : 1).ThenBy(p => p.DistanceKm).ThenBy(p => p.Kind).ThenBy(p => p.Target)
|
||
.Take(w.Data.Balance.Industry.Outlook.PartnersPerGood).ToList();
|
||
|
||
private static double Km(Vec2 a, Vec2 b) => Vec2.Distance(a, b) / 1000;
|
||
|
||
/// <summary>Stazioni vive (di qualunque compagnia) con l'industria nel bacino e fermata di una linea con treni.</summary>
|
||
public static List<StationId> ServingStations(World w, Industry ind)
|
||
{
|
||
var lineHasTrain = new bool[w.Lines.Count];
|
||
foreach (var t in w.Trains)
|
||
{
|
||
if (!t.Removed && t.Line.IsValid && t.Line.Value < lineHasTrain.Length) lineHasTrain[t.Line.Value] = true;
|
||
}
|
||
var served = new bool[w.Network.Stations.Count];
|
||
foreach (var l in w.Lines)
|
||
{
|
||
if (l.Removed || !lineHasTrain[l.Id.Value]) continue;
|
||
foreach (var stop in l.Stops)
|
||
{
|
||
int s = stop.Station.Value;
|
||
if (s >= 0 && s < served.Length) served[s] = true;
|
||
}
|
||
}
|
||
var result = new List<StationId>();
|
||
foreach (var s in w.Network.Stations)
|
||
{
|
||
if (served[s.Id.Value] && w.Network.IsAlive(s) && s.Industries.Contains(ind.Id)) result.Add(s.Id);
|
||
}
|
||
return result;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Linee della compagnia con almeno un treno e ciò che raggiungono: industrie, hub e città nel
|
||
/// bacino delle loro fermate (stazioni vive). Una linea collega due nodi se li raggiunge entrambi.
|
||
/// </summary>
|
||
private sealed class LineLinks
|
||
{
|
||
private readonly List<(Line Line, HashSet<int> Industries, HashSet<int> Hubs, HashSet<int> Towns)> _lines = [];
|
||
|
||
public LineLinks(World w, CompanyId company)
|
||
{
|
||
if (!company.IsValid) return;
|
||
var lineHasTrain = new bool[w.Lines.Count];
|
||
foreach (var t in w.Trains)
|
||
{
|
||
if (t.Owner == company && !t.Removed && t.Line.IsValid && t.Line.Value < lineHasTrain.Length) lineHasTrain[t.Line.Value] = true;
|
||
}
|
||
foreach (var l in w.Lines)
|
||
{
|
||
if (l.Owner != company || l.Removed || !lineHasTrain[l.Id.Value]) continue;
|
||
var industries = new HashSet<int>();
|
||
var hubs = new HashSet<int>();
|
||
var towns = new HashSet<int>();
|
||
foreach (var stop in l.Stops)
|
||
{
|
||
int s = stop.Station.Value;
|
||
if (s < 0 || s >= w.Network.Stations.Count) continue;
|
||
var station = w.Network.Stations[s];
|
||
if (!w.Network.IsAlive(station)) continue;
|
||
foreach (var i in station.Industries) industries.Add(i.Value);
|
||
foreach (var h in station.Hubs) hubs.Add(h.Value);
|
||
foreach (var t in station.Towns) towns.Add(t.Value);
|
||
}
|
||
_lines.Add((l, industries, hubs, towns));
|
||
}
|
||
}
|
||
|
||
/// <summary>Linee che raggiungono l'industria, per id crescente.</summary>
|
||
public List<Line> Serving(Industry ind) => _lines.Where(x => x.Industries.Contains(ind.Id.Value)).Select(x => x.Line).ToList();
|
||
|
||
/// <summary>Prima linea (id più basso) tra quelle dell'industria che raggiunge anche il nodo indicato.</summary>
|
||
public LineId Link(List<Line> serving, ChainPartnerKind kind, int target)
|
||
{
|
||
foreach (var line in serving)
|
||
{
|
||
var entry = _lines.First(x => ReferenceEquals(x.Line, line));
|
||
var set = kind switch
|
||
{
|
||
ChainPartnerKind.Industry => entry.Industries,
|
||
ChainPartnerKind.Hub => entry.Hubs,
|
||
_ => entry.Towns,
|
||
};
|
||
if (set.Contains(target)) return line.Id;
|
||
}
|
||
return LineId.None;
|
||
}
|
||
}
|
||
}
|