328 lines
13 KiB
C#
328 lines
13 KiB
C#
using SpaceGame.Simulation.Api.Data;
|
|
using SpaceGame.Simulation.Api.Contracts;
|
|
|
|
namespace SpaceGame.Simulation.Api.Simulation;
|
|
|
|
public sealed partial class SimulationEngine
|
|
{
|
|
private void ReviewStationMarketOrders(SimulationWorld world, StationRuntime station)
|
|
{
|
|
if (station.CommanderId is null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var desiredOrders = new List<DesiredMarketOrder>();
|
|
var waterReserve = MathF.Max(30f, station.Population * 3f);
|
|
var refinedReserve = HasStationModules(station, "fabricator-array") ? 140f : 40f;
|
|
var oreReserve = HasRefineryCapability(station) ? 180f : 0f;
|
|
var shipPartsReserve = HasStationModules(station, "fabricator-array")
|
|
&& !HasStationModules(station, "component-factory", "ship-factory")
|
|
&& FactionCommanderHasDirective(world, station.FactionId, "produce-military-ships")
|
|
? 90f
|
|
: 0f;
|
|
|
|
AddDemandOrder(desiredOrders, station, "water", waterReserve, valuationBase: 1.1f);
|
|
AddDemandOrder(desiredOrders, station, "ore", oreReserve, valuationBase: 1.0f);
|
|
AddDemandOrder(desiredOrders, station, "refined-metals", refinedReserve, valuationBase: 1.15f);
|
|
AddDemandOrder(desiredOrders, station, "ship-parts", shipPartsReserve, valuationBase: 1.3f);
|
|
|
|
AddSupplyOrder(desiredOrders, station, "water", waterReserve * 1.5f, reserveFloor: waterReserve, valuationBase: 0.65f);
|
|
AddSupplyOrder(desiredOrders, station, "ore", oreReserve * 1.4f, reserveFloor: oreReserve, valuationBase: 0.7f);
|
|
AddSupplyOrder(desiredOrders, station, "refined-metals", refinedReserve * 1.4f, reserveFloor: refinedReserve, valuationBase: 0.95f);
|
|
|
|
ReconcileStationMarketOrders(world, station, desiredOrders);
|
|
}
|
|
|
|
private void RunStationProduction(SimulationWorld world, StationRuntime station, float deltaSeconds, ICollection<SimulationEventRecord> events)
|
|
{
|
|
var faction = world.Factions.FirstOrDefault(candidate => candidate.Id == station.FactionId);
|
|
foreach (var laneKey in GetStationProductionLanes(world, station))
|
|
{
|
|
var recipe = SelectProductionRecipe(world, station, laneKey);
|
|
if (recipe is null)
|
|
{
|
|
station.ProductionLaneTimers[laneKey] = 0f;
|
|
continue;
|
|
}
|
|
|
|
var throughput = GetStationProductionThroughput(world, station, recipe);
|
|
|
|
var produced = 0f;
|
|
station.ProductionLaneTimers[laneKey] = GetStationProductionTimer(station, laneKey) + (deltaSeconds * station.WorkforceEffectiveRatio * throughput);
|
|
while (station.ProductionLaneTimers[laneKey] >= recipe.Duration && CanRunRecipe(world, station, recipe))
|
|
{
|
|
station.ProductionLaneTimers[laneKey] -= recipe.Duration;
|
|
foreach (var input in recipe.Inputs)
|
|
{
|
|
RemoveInventory(station.Inventory, input.ItemId, input.Amount);
|
|
}
|
|
|
|
if (recipe.ShipOutputId is not null)
|
|
{
|
|
produced += CompleteShipRecipe(world, station, recipe, events);
|
|
continue;
|
|
}
|
|
|
|
foreach (var output in recipe.Outputs)
|
|
{
|
|
produced += TryAddStationInventory(world, station, output.ItemId, output.Amount);
|
|
}
|
|
}
|
|
|
|
if (produced <= 0.01f)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
events.Add(new SimulationEventRecord("station", station.Id, "production-complete", $"{station.Label} completed {recipe.Label}.", DateTimeOffset.UtcNow));
|
|
if (faction is not null)
|
|
{
|
|
faction.GoodsProduced += produced;
|
|
}
|
|
}
|
|
}
|
|
|
|
private static IEnumerable<string> GetStationProductionLanes(SimulationWorld world, StationRuntime station)
|
|
{
|
|
foreach (var moduleId in station.InstalledModules.Distinct(StringComparer.Ordinal))
|
|
{
|
|
if (!world.ModuleDefinitions.TryGetValue(moduleId, out var def) || string.IsNullOrEmpty(def.ProductionMode))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (string.Equals(def.ProductionMode, "commanded", StringComparison.Ordinal) && station.CommanderId is null)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
yield return moduleId;
|
|
}
|
|
}
|
|
|
|
private static float GetStationProductionTimer(StationRuntime station, string laneKey) =>
|
|
station.ProductionLaneTimers.TryGetValue(laneKey, out var timer) ? timer : 0f;
|
|
|
|
private static RecipeDefinition? SelectProductionRecipe(SimulationWorld world, StationRuntime station, string laneKey) =>
|
|
world.Recipes.Values
|
|
.Where(recipe => RecipeAppliesToStation(station, recipe) && string.Equals(GetStationProductionLaneKey(world, recipe), laneKey, StringComparison.Ordinal))
|
|
.OrderByDescending(recipe => GetStationRecipePriority(world, station, recipe))
|
|
.FirstOrDefault(recipe => CanRunRecipe(world, station, recipe));
|
|
|
|
private static string? GetStationProductionLaneKey(SimulationWorld world, RecipeDefinition recipe) =>
|
|
recipe.RequiredModules.FirstOrDefault(moduleId =>
|
|
world.ModuleDefinitions.TryGetValue(moduleId, out var def) && !string.IsNullOrEmpty(def.ProductionMode));
|
|
|
|
private static float GetStationProductionThroughput(SimulationWorld world, StationRuntime station, RecipeDefinition recipe)
|
|
{
|
|
var laneModuleId = GetStationProductionLaneKey(world, recipe);
|
|
if (laneModuleId is null)
|
|
{
|
|
return 1f;
|
|
}
|
|
|
|
return Math.Max(1, CountModules(station.InstalledModules, laneModuleId));
|
|
}
|
|
|
|
private static float GetStationRecipePriority(SimulationWorld world, StationRuntime station, RecipeDefinition recipe)
|
|
{
|
|
var priority = (float)recipe.Priority;
|
|
|
|
var expansionPressure = GetFactionExpansionPressure(world, station.FactionId);
|
|
var fleetPressure = FactionCommanderHasDirective(world, station.FactionId, "produce-military-ships") ? 1f : 0f;
|
|
priority += recipe.Id switch
|
|
{
|
|
"ship-parts-integration" => HasStationModules(station, "component-factory", "ship-factory")
|
|
? -140f * MathF.Max(expansionPressure, fleetPressure)
|
|
: 280f * MathF.Max(expansionPressure, fleetPressure),
|
|
"hull-fabrication" => 180f * expansionPressure,
|
|
"equipment-assembly" => 170f * expansionPressure,
|
|
"gun-assembly" => 160f * expansionPressure,
|
|
"command-bridge-module-assembly" or "reactor-core-module-assembly" or "capacitor-bank-module-assembly" or "ion-drive-module-assembly" or "ftl-core-module-assembly" or "gun-turret-module-assembly"
|
|
=> 220f * MathF.Max(expansionPressure, fleetPressure),
|
|
"frigate-construction" => 320f * MathF.Max(expansionPressure, fleetPressure),
|
|
"destroyer-construction" => 200f * MathF.Max(expansionPressure, fleetPressure),
|
|
"cruiser-construction" => 120f * MathF.Max(expansionPressure, fleetPressure),
|
|
"ammo-fabrication" => -80f * expansionPressure,
|
|
"trade-hub-assembly" or "refinery-assembly" or "farm-ring-assembly" or "manufactory-assembly" or "shipyard-assembly" or "defense-grid-assembly" or "stargate-assembly"
|
|
=> -120f * expansionPressure,
|
|
_ => 0f,
|
|
};
|
|
|
|
return priority;
|
|
}
|
|
|
|
private static bool RecipeAppliesToStation(StationRuntime station, RecipeDefinition recipe)
|
|
{
|
|
var categoryMatch = string.Equals(recipe.FacilityCategory, "station", StringComparison.Ordinal)
|
|
|| string.Equals(recipe.FacilityCategory, "farm", StringComparison.Ordinal)
|
|
|| string.Equals(recipe.FacilityCategory, station.Category, StringComparison.Ordinal);
|
|
return categoryMatch && recipe.RequiredModules.All(moduleId => station.InstalledModules.Contains(moduleId, StringComparer.Ordinal));
|
|
}
|
|
|
|
private static bool CanRunRecipe(SimulationWorld world, StationRuntime station, RecipeDefinition recipe)
|
|
{
|
|
if (recipe.ShipOutputId is not null)
|
|
{
|
|
if (!world.ShipDefinitions.TryGetValue(recipe.ShipOutputId, out var shipDefinition))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
if (!string.Equals(shipDefinition.Kind, "military", StringComparison.Ordinal)
|
|
|| !FactionCommanderHasDirective(world, station.FactionId, "produce-military-ships"))
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
|
|
if (recipe.Inputs.Any(input => GetInventoryAmount(station.Inventory, input.ItemId) + 0.001f < input.Amount))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
return recipe.Outputs.All(output => CanAcceptStationInventory(world, station, output.ItemId, output.Amount));
|
|
}
|
|
|
|
private static bool CanAcceptStationInventory(SimulationWorld world, StationRuntime station, string itemId, float amount)
|
|
{
|
|
if (amount <= 0f || !world.ItemDefinitions.TryGetValue(itemId, out var itemDefinition))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
var requiredModule = GetStorageRequirement(itemDefinition.CargoKind);
|
|
if (requiredModule is not null && !station.InstalledModules.Contains(requiredModule, StringComparer.Ordinal))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
var capacity = GetStationStorageCapacity(station, itemDefinition.CargoKind);
|
|
if (capacity <= 0.01f)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
var used = station.Inventory
|
|
.Where(entry => world.ItemDefinitions.TryGetValue(entry.Key, out var definition) && definition.CargoKind == itemDefinition.CargoKind)
|
|
.Sum(entry => entry.Value);
|
|
return used + amount <= capacity + 0.001f;
|
|
}
|
|
|
|
private static bool HasRefineryCapability(StationRuntime station) =>
|
|
HasStationModules(station, "refinery-stack", "power-core", "bulk-bay");
|
|
|
|
private static void AddDemandOrder(ICollection<DesiredMarketOrder> desiredOrders, StationRuntime station, string itemId, float targetAmount, float valuationBase)
|
|
{
|
|
var current = GetInventoryAmount(station.Inventory, itemId);
|
|
if (current >= targetAmount - 0.01f)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var deficit = targetAmount - current;
|
|
var scarcity = targetAmount <= 0.01f ? 1f : MathF.Min(1f, deficit / targetAmount);
|
|
desiredOrders.Add(new DesiredMarketOrder(MarketOrderKinds.Buy, itemId, deficit, valuationBase + scarcity, null));
|
|
}
|
|
|
|
private static void AddSupplyOrder(ICollection<DesiredMarketOrder> desiredOrders, StationRuntime station, string itemId, float triggerAmount, float reserveFloor, float valuationBase)
|
|
{
|
|
var current = GetInventoryAmount(station.Inventory, itemId);
|
|
if (current <= triggerAmount + 0.01f)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var surplus = current - reserveFloor;
|
|
if (surplus <= 0.01f)
|
|
{
|
|
return;
|
|
}
|
|
|
|
desiredOrders.Add(new DesiredMarketOrder(MarketOrderKinds.Sell, itemId, surplus, valuationBase, reserveFloor));
|
|
}
|
|
|
|
private static void ReconcileStationMarketOrders(SimulationWorld world, StationRuntime station, IReadOnlyCollection<DesiredMarketOrder> desiredOrders)
|
|
{
|
|
var existingOrders = world.MarketOrders
|
|
.Where(order => order.StationId == station.Id && order.ConstructionSiteId is null)
|
|
.ToList();
|
|
|
|
foreach (var desired in desiredOrders)
|
|
{
|
|
var order = existingOrders.FirstOrDefault(candidate =>
|
|
candidate.Kind == desired.Kind &&
|
|
candidate.ItemId == desired.ItemId &&
|
|
candidate.ConstructionSiteId is null);
|
|
|
|
if (order is null)
|
|
{
|
|
order = new MarketOrderRuntime
|
|
{
|
|
Id = $"market-order-{station.Id}-{desired.Kind}-{desired.ItemId}",
|
|
FactionId = station.FactionId,
|
|
StationId = station.Id,
|
|
Kind = desired.Kind,
|
|
ItemId = desired.ItemId,
|
|
Amount = desired.Amount,
|
|
RemainingAmount = desired.Amount,
|
|
Valuation = desired.Valuation,
|
|
ReserveThreshold = desired.ReserveThreshold,
|
|
State = MarketOrderStateKinds.Open,
|
|
};
|
|
world.MarketOrders.Add(order);
|
|
station.MarketOrderIds.Add(order.Id);
|
|
existingOrders.Add(order);
|
|
continue;
|
|
}
|
|
|
|
order.RemainingAmount = desired.Amount;
|
|
order.Valuation = desired.Valuation;
|
|
order.ReserveThreshold = desired.ReserveThreshold;
|
|
order.State = desired.Amount <= 0.01f ? MarketOrderStateKinds.Cancelled : MarketOrderStateKinds.Open;
|
|
}
|
|
|
|
foreach (var order in existingOrders.Where(order => desiredOrders.All(desired => desired.Kind != order.Kind || desired.ItemId != order.ItemId)))
|
|
{
|
|
order.RemainingAmount = 0f;
|
|
order.State = MarketOrderStateKinds.Cancelled;
|
|
}
|
|
}
|
|
|
|
private static float GetFactionExpansionPressure(SimulationWorld world, string factionId)
|
|
{
|
|
var targetSystems = Math.Max(1, Math.Min(StrategicControlTargetSystems, world.Systems.Count));
|
|
var controlledSystems = GetFactionControlledSystemsCount(world, factionId);
|
|
var deficit = Math.Max(0, targetSystems - controlledSystems);
|
|
return Math.Clamp(deficit / (float)targetSystems, 0f, 1f);
|
|
}
|
|
|
|
private static int GetFactionControlledSystemsCount(SimulationWorld world, string factionId)
|
|
{
|
|
return world.Claims
|
|
.Where(claim => claim.State != ClaimStateKinds.Destroyed)
|
|
.Select(claim => claim.SystemId)
|
|
.Distinct(StringComparer.Ordinal)
|
|
.Count(systemId => FactionControlsSystem(world, factionId, systemId));
|
|
}
|
|
|
|
private static bool FactionControlsSystem(SimulationWorld world, string factionId, string systemId)
|
|
{
|
|
var buildableLocations = world.Claims
|
|
.Where(claim =>
|
|
claim.SystemId == systemId &&
|
|
claim.State is ClaimStateKinds.Activating or ClaimStateKinds.Active)
|
|
.ToList();
|
|
if (buildableLocations.Count == 0)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
var ownedLocations = buildableLocations.Count(claim => claim.FactionId == factionId);
|
|
return ownedLocations > (buildableLocations.Count / 2f);
|
|
}
|
|
|
|
private sealed record DesiredMarketOrder(string Kind, string ItemId, float Amount, float Valuation, float? ReserveThreshold);
|
|
}
|