using ViaFerrea.Core.Common;
using ViaFerrea.Core.Economy;
namespace ViaFerrea.Core.Simulation.Systems;
///
/// Domanda giornaliera: consumo desiderato delle città (con elasticità al prezzo), input
/// richiesti dalle industrie al loro potenziale di lavoro e ricambi per gli impianti.
/// Alimenta D del mercato.
///
public sealed class DemandSystem : ISimSystem
{
public string Name => "Demand";
public void Step(WorldContext ctx)
{
if (!ctx.IsNewDay) return;
var w = ctx.World;
var data = w.Data;
var market = w.Market;
int year = ctx.Year;
foreach (var town in w.Towns)
{
for (int g = 0; g < data.GoodCount; g++)
{
double d = TownDemand(w, town, g, year);
town.DemandToday[g] = d;
market.DemandToday[g] += d;
}
}
int dpm = w.Calendar.DaysPerMonth;
var im = data.Balance.IndustryMaintenance;
foreach (var ind in w.Industries)
{
if (ind.Closed || ind.Level <= 0)
{
Array.Clear(ind.InputDemandToday);
continue;
}
// ricambi per la manutenzione degli impianti (sezione 11)
market.DemandToday[data.SparePartsGood] += (double)IndustryMath.MonthlyPartsUse(ind, im) / dpm;
double eLabor = Math.Min(ind.CovWorkers, ind.CovStaff) * IndustryMath.ProfitFactor(ind, data.Balance.Industry)
* IndustryMath.ConditionMultiplier(ind.Condition, data.Balance.IndustryMaintenance);
double cycles = ind.CyclesPerDayAtFullCapacity(dpm) * eLabor;
var inputs = ind.Def.Recipe.Inputs;
for (int i = 0; i < inputs.Count; i++)
{
double need = cycles * inputs[i].PerCycle;
ind.InputDemandToday[i] = need;
market.DemandToday[inputs[i].GoodIndex] += need;
}
}
}
/// Domanda giornaliera di una città per un bene, in unità.
public static double TownDemand(World w, Town town, int good, int year)
{
var def = w.Data.Goods[good];
if (def.Town is not { } td || def.Era > year || (td.UntilYear is { } until && year >= until)) return 0;
double ratio = w.Market.GlobalPrice[good] / def.BasePrice;
var tb = w.Data.Balance.Town;
double priceFactor = DMath.Clamp(DMath.Pow(ratio, -def.Elasticity), tb.DemandPriceFactorMin, tb.DemandPriceFactorMax);
return town.Population / 1000.0 * td.DemandPerThousand * priceFactor;
}
}