diff --git a/data/ai.json b/data/ai.json new file mode 100644 index 0000000..c5cf0aa --- /dev/null +++ b/data/ai.json @@ -0,0 +1,28 @@ +{ + "$schema": "schema/ai.schema.json", + "version": 1, + "planning": { + "intervalDays": 30, + "maxCandidates": 40, + "maxProjectsPerMonth": 2, + "candidateMaxDistanceKm": 40, + "candidateMinDistanceKm": 4, + "pathSlopePenalty": 40, + "pathWaterPenalty": 8, + "trainsPerLine": 2, + "wagonsPerTrain": 5, + "cashReserveMonths": 3, + "revenueHorizonYears": 10, + "maxRejectedShare": 0.05 + }, + "personalities": [ + { "id": "expansive", "name_it": "Espansiva", "roiThreshold": 0.08, "loanShareOfCredit": 0.8, "targetsPlayer": false, "buysShares": false, "maintenancePolicy": "standard" }, + { "id": "prudent", "name_it": "Prudente", "roiThreshold": 0.15, "loanShareOfCredit": 0.3, "targetsPlayer": false, "buysShares": false, "maintenancePolicy": "standard" }, + { "id": "predatory", "name_it": "Predatoria", "roiThreshold": 0.10, "loanShareOfCredit": 0.6, "targetsPlayer": true, "buysShares": true, "maintenancePolicy": "standard" } + ], + "companyNames": [ + "Strade Ferrate del Nord", "Società Ferroviaria Adriatica", "Compagnia delle Valli", "Ferrovie Meridionali", + "Società Anonima delle Strade Ferrate", "Ferrovia Alta Valle", "Compagnia Lombardo-Veneta", "Rete del Litorale" + ], + "colors": [ "#3f86d1", "#5fc39b", "#b3573e", "#9cc9f2", "#d9c26a", "#7c8590" ] +} diff --git a/data/balance.json b/data/balance.json new file mode 100644 index 0000000..725bd95 --- /dev/null +++ b/data/balance.json @@ -0,0 +1,178 @@ +{ + "$schema": "schema/balance.schema.json", + "version": 1, + "time": { + "tickMs": 50, + "ticksPerDay": 240, + "daysPerMonth": 30, + "monthsPerYear": 12, + "trainClockFactor": 60, + "speeds": [ 0, 1, 2, 4, 8 ], + "defaultStartYear": 1850 + }, + "map": { + "cellSizeM": 100, + "sizesKm": [ 64, 128, 256 ], + "chunkCells": 64, + "maxElevationM": 2200, + "noise": { "octaves": 5, "baseWavelengthKm": 48, "persistence": 0.5, "lacunarity": 2.0, + "warpStrengthKm": 9, "warpWavelengthKm": 36, "warpOctaves": 2, + "ridgeOctaves": 4, "ridgeWavelengthKm": 28 }, + "relief": { "noiseAmplitudeM": 380, "noiseCoastFactor": 0.15, "inlandGradientM": 700, "inlandExponent": 2.0, "seaOffsetM": 25, + "mountainAmplitudeM": 1400, "mountainStart": 0.55, "seaBandFraction": 0.03, "coastNoiseM": 90, + "microReliefM": 6, "microWavelengthKm": 1.2 }, + "hydrology": { "riverThresholdKm2": 18, "riverWidthSteps": [ 1, 4, 16, 64 ], "carveDepthM": 4, "valleyRadiusCells": 3, "valleyDepthM": 6, + "lakeMinDepthM": 3, "lakeMinCells": 8, "lakeMaxPercentile": 0.6, "minSourcePercentile": 0.30 }, + "cover": { "rockPercentile": 0.70, "rockMinSlope": 0.18, "mountainPercentile": 0.90, "hillMinSlope": 0.07, "hillPercentile": 0.55, + "forestMinSlope": 0.03, "forestMaxSlope": 0.30, "forestNoiseThreshold": 0.52, "forestWavelengthKm": 6, + "marshMaxPercentile": 0.25, "marshRiverDistanceCells": 4, "marshMaxSlope": 0.012, "marshNoiseThreshold": 0.6, + "fieldRadiusCells": 14, "fieldShare": 0.35 }, + "deposits": { "perThousandKm2": { "coal": 0.8, "iron": 0.6, "stone": 0.7, "oil": 0.4 }, + "radiusCells": [ 3, 7 ], "reserveTonnes": { "coal": [ 250000, 900000 ], "iron": [ 200000, 700000 ], "stone": [ 400000, 1500000 ], "oil": [ 150000, 600000 ] }, + "minSpacingKm": 5, "preferredMinPercentile": { "coal": 0.45, "iron": 0.60, "stone": 0.40, "oil": 0.0 }, + "preferredMaxPercentile": { "coal": 0.92, "iron": 1.0, "stone": 0.95, "oil": 0.45 } }, + "towns": { "countBySize": { "64": 10, "128": 26, "256": 56 }, "minDistanceKm": 6, "maxWaterDistanceKm": 3, "maxSlope": 0.05, + "maxHeightPercentile": 0.65, "largestPopulation": [ 11000, 18000 ], "zipfExponent": 0.85, "minPopulation": 500, + "radiusBaseCells": 2.0, "radiusPerSqrtPop": 0.025 }, + "industries": { "countBySize": { "64": 32, "128": 110, "256": 400 }, "initialLevels": [ 1, 2 ], + "shares": { "farm": 0.35, "logging": 0.12, "processing": 0.33, "manufacturing": 0.20 }, "placementAttempts": 400, + "maxSlope": 0.15, "spacingCells": 1 }, + "hubs": { "ports": 1, "borders": 1, "portMinPopulationNearbyKm": 15 } + }, + "market": { + "k": 0.08, + "alpha": 0.15, + "windowDays": 30, + "minPriceFactor": 0.3, + "maxPriceFactor": 3.0, + "ratioMin": 0.2, + "ratioMax": 5.0, + "world": { "amplitude": 0.12, "periodYears": 6, "volumeShare": 0.5, "baselinePerDay": 4.0, "elasticity": 1.0, + "shockChancePerYear": 0.25, "shockMin": 0.08, "shockMax": 0.30, "shockDecayDays": 150 }, + "historyDays": 360 + }, + "localPrice": { "lambda": 0.35, "maxDeviation": 0.40, "epsilon": 1.0 }, + "industry": { + "coverageWindowDays": 30, + "profitFactorSlope": 0.5, + "profitFactorMin": 0.6, + "profitFactorMax": 1.2, + "marginWindowDays": 90, + "wagePerWorkerPerMonth": 1800, + "wagePerStaffPerMonth": 5000, + "onSiteWorkerShare": 0.30, + "onSiteStaffShare": 0.30, + "initialStockDays": 10, + "footprintCells": { "small": 2, "medium": 3, "large": 4 }, + "depletionStartFraction": 0.20, + "startingCash": 2000000 + }, + "growth": { + "quarterDays": 90, + "weightShipped": 0.5, + "weightCoverage": 0.3, + "weightProfit": 0.2, + "upgradeThreshold": 0.75, + "upgradeQuarters": 2, + "downgradeThreshold": 0.35, + "closeQuartersAtZero": 4, + "maxLevel": 5, + "spawnUnmetDays": 360, + "spawnUnmetRatio": 1.25, + "spawnMaxPerYear": 2 + }, + "town": { + "baseGrowth": 0.002, + "satisfactionWeight": 0.004, + "employmentWeight": 0.003, + "employmentPivot": 0.4, + "maxMonthlyGrowth": 0.01, + "satisfactionPivot": 0.5, + "workforceShare": 0.40, + "staffShare": 0.08, + "staffMinPopulation": 5000, + "staffMinServices": 2, + "servicesSatisfactionThreshold": 0.5, + "serviceJobsShare": 0.12, + "satisfactionEmaDays": 30, + "initialSatisfaction": 0.5, + "stockDays": 20, + "workSatisfactionPenalty": 0.05, + "maxPopulation": 2000000 + }, + "migration": { "share": 0.01, "satisfactionThreshold": 0.4, "maxDistanceKm": 60, "emigrationShareWhenNoTarget": 0.5 }, + "employment": { "walkRadiusKm": 1.5, "workerMaxMinutes": 60, "staffMaxMinutes": 90, "coverageEmaDays": 30, + "dissolveCoverage": 0.5, "dissolveDays": 90, "walkSpeedKmh": 4.5 }, + "localTransport": { "enabled": true, "radiusKm": 3.0, "dailyShare": 0.25, "maxUnitsPerDay": 6 }, + "hubs": { + "port": { "name_it": "Porto", "monthlyCapacity": 3000, "duty": 0.08, "footprint": "large" }, + "border": { "name_it": "Valico", "monthlyCapacity": 1500, "duty": 0.12, "footprint": "small" } + }, + "tariffs": { + "freightBaseRate": 150, + "freightFixedWeight": 0.6, + "freightPriceWeight": 0.4, + "freightKmExponent": 0.9, + "paxBaseFare": 45, + "paxKmExponent": 0.85, + "classMultipliers": { "worker": 1.0, "staff": 3.0 }, + "lateThreshold": 1.5, + "lateFactorMin": 0.5, + "lateFactorSpan": 1.0 + }, + "finance": { + "ratingSpreads": { "AAA": 0.005, "AA": 0.01, "A": 0.015, "BBB": 0.025, "BB": 0.035, "B": 0.05, "CCC": 0.07, "CC": 0.09, "C": 0.12, "D": 0.18 }, + "ratingByScore": [ 0.85, 0.75, 0.65, 0.55, 0.45, 0.35, 0.25, 0.15, 0.05 ], + "profitMarginWeight": 0.6, + "leverageWeight": 0.4, + "loanTermMonths": 120, + "loanStep": 5000000, + "startingRating": "BB", + "depreciationYearsTrack": 50, + "bookValueFloor": 0.1 + }, + "stockMarket": { + "shares": 1000000, + "earningsMultiple": 8, + "sentimentMin": 0.8, + "sentimentMax": 1.3, + "spread": 0.01, + "ipoMaxShare": 0.4, + "controlShare": 0.5, + "mergeAfterDays": 360, + "bidPremiumMin": 0.2, + "bidPremiumMax": 0.5, + "bidDurationDays": 90, + "ransomShare": 0.51, + "receivershipDividend": 0.5 + }, + "industryMaintenance": { + "wearPerDay": 0.06, + "efficiencyFullAbove": 70, + "efficiencyAt20": 0.5, + "efficiencyBelow20": 0.3, + "breakdownBase": 0.001, + "breakdownPivot": 40, + "breakdownScale": 8, + "breakdownDays": [ 5, 20 ], + "breakdownTownSatisfaction": 0.02, + "accidentBelow": 10, + "accidentDays": 60, + "accidentPopulationLoss": 0.002, + "budgets": { + "none": { "recoveryPerDay": 0.0, "costShareOfRevenue": 0.0, "sparePartsPerLevelPerMonth": 0 }, + "base": { "recoveryPerDay": 0.05, "costShareOfRevenue": 0.03, "sparePartsPerLevelPerMonth": 1 }, + "high": { "recoveryPerDay": 0.12, "costShareOfRevenue": 0.07, "sparePartsPerLevelPerMonth": 3 } + }, + "noPartsRecoveryFactor": 0.5, + "overhaulDays": 30, + "overhaulMachineryPerLevel": 2, + "overhaulMinStaffCoverage": 0.8, + "upgradeMachineryPerLevel": 5, + "upgradeDays": 60, + "npcUpgradeMargin": 0.15, + "npcUpgradeYears": 2, + "npcHighMargin": 0.15, + "npcOverhaulBelow": 35 + } +} diff --git a/data/construction.json b/data/construction.json new file mode 100644 index 0000000..5e96db9 --- /dev/null +++ b/data/construction.json @@ -0,0 +1,85 @@ +{ + "$schema": "schema/construction.schema.json", + "version": 1, + "profile": { + "sampleSpacingM": 25, + "heightOffsetRangeM": 20, + "smoothingWindow": 5, + "naturalToleranceM": 1.5, + "embankmentMaxM": 8, + "cuttingMaxM": 8, + "riverClearanceM": 6, + "navigableClearanceM": 12, + "navigableMinWidthCells": 3, + "snapAngleDeg": 45 + }, + "maxGradientByTraction": { "steam": 0.025, "diesel": 0.035, "electric": 0.04, "highspeed": 0.035 }, + "speedClasses": [ + { "trackClass": "c60", "minRadiusM": 200, "costMultiplier": 1.0 }, + { "trackClass": "c100", "minRadiusM": 400, "costMultiplier": 1.4 }, + { "trackClass": "c160", "minRadiusM": 900, "costMultiplier": 2.2 }, + { "trackClass": "c250", "minRadiusM": 2500, "costMultiplier": 4.0 } + ], + "curveSpeedFactor": 0.65, + "costs": { + "basePerMeter": 1200, + "natural": 1.0, + "embankmentPerM": 0.25, + "cuttingPerM": 0.35, + "bridgeBase": 6.0, + "bridgePerM": 0.5, + "tunnel": 12.0, + "terrainModifiers": { "rock": 1.8, "marsh": 1.6, "mountain": 1.4, "forest": 1.15 }, + "land": { "basePerCell": 20000, "nearTownKm": 2.0, "nearTownMultiplier": 3.0, "fieldMultiplier": 2.0 }, + "doubleTrackMultiplier": 1.8, + "electrificationExtra": 0.35, + "stationBase": 4000000, + "stationPerPlatform": 1500000, + "depotBySize": { "small": 6000000, "medium": 12000000, "large": 24000000 }, + "demolitionRefund": 0.1 + }, + "crews": { + "metersPerDay": { "natural": 200, "embankment": 60, "cutting": 60, "bridge": 20, "tunnel": 8 }, + "crewsByTier": [ 2, 4, 8, 12, 20 ], + "upgradeClosure": true + }, + "rules": { + "forbidTownFootprint": true, + "forbidIndustryFootprint": true, + "forbidForeignStations": true, + "foreignCrossingNeedsOverpass": true, + "overpassClearanceM": 7 + }, + "trackWear": { + "k": 400000, + "gradientWeight": 8, + "speedWeight": 0.4, + "maintenanceDriftPerDay": 0.02, + "maintenanceCostPerKmPerDay": 400, + "limitBelow60": 0.6, + "limitBelow30": 0.3, + "failureChanceBelow30": 0.002, + "renewalCostShare": 0.4, + "renewalDaysPerKm": 3 + }, + "structures": { + "inspectionCostShare": 0.01, + "inspectionIntervalDays": 360, + "renewalYears": 50, + "missedInspectionWearPerDay": 0.03, + "speedLimitBelow": 50, + "speedLimitFactor": 0.5, + "closeBelow": 15 + }, + "physics": { + "gravity": 9.81, + "adhesion": 0.3, + "adhesionFactor": 0.3, + "rollingResistance": 0.0015, + "aeroCoefficient": 0.6, + "cxByKind": { "locomotive": 0.0025, "wagon": 0.0012, "coach": 0.0015 }, + "brakingMs2": 0.5, + "stallSpeedKmh": 1.0, + "stallSeconds": 120 + } +} diff --git a/data/contracts.json b/data/contracts.json new file mode 100644 index 0000000..00346fc --- /dev/null +++ b/data/contracts.json @@ -0,0 +1,27 @@ +{ + "$schema": "schema/contracts.schema.json", + "version": 1, + "generation": { "perYear": 3, "maxOpen": 6, "expoEveryYears": 12 }, + "templates": [ + { "id": "connect_towns", "kind": "connect", "name_it": "Collegamento tra città", + "text_it": "Collega {a} a {b} entro il {deadline} con un tempo di viaggio inferiore a {minutes} minuti", + "durationYears": [ 3, 8 ], "maxMinutes": [ 60, 150 ], "reward": 20000000, "prestige": 10, "penalty": 5000000, "minYear": 1850 }, + { "id": "deliver_goods", "kind": "deliver", "name_it": "Fornitura straordinaria", + "text_it": "Trasporta {qty} {unit} di {good} a {b} prima del {deadline}", + "durationYears": [ 1, 3 ], "quantity": [ 5000, 50000 ], "reward": 15000000, "prestige": 6, "penalty": 3000000, "minYear": 1850 }, + { "id": "great_tunnel", "kind": "greatWork", "name_it": "Traforo", + "text_it": "Traforo di {length} km tra {a} e {b} entro il {deadline}", + "durationYears": [ 6, 10 ], "lengthKm": [ 4, 12 ], "reward": 120000000, "prestige": 50, "penalty": 30000000, "minYear": 1870 }, + { "id": "great_bridge", "kind": "greatWork", "name_it": "Grande ponte", + "text_it": "Ponte di almeno {length} m su {river} entro il {deadline}", + "durationYears": [ 4, 8 ], "lengthKm": [ 0.3, 1.2 ], "reward": 60000000, "prestige": 30, "penalty": 15000000, "minYear": 1870 }, + { "id": "service_obligation", "kind": "service", "name_it": "Servizio pubblico", + "text_it": "Garantisci {qty} posti al giorno tra {a} e {b} per {years} anni", + "durationYears": [ 2, 5 ], "quantity": [ 100, 600 ], "reward": 8000000, "prestige": 5, "penalty": 4000000, "minYear": 1850 } + ], + "expositions": [ + { "id": "fastest_line", "name_it": "Linea più veloce", "reward": 30000000, "prestige": 25 }, + { "id": "longest_bridge", "name_it": "Ponte più lungo", "reward": 20000000, "prestige": 20 }, + { "id": "largest_station", "name_it": "Stazione più grande", "reward": 15000000, "prestige": 15 } + ] +} diff --git a/data/difficulty.json b/data/difficulty.json new file mode 100644 index 0000000..f05f2c3 --- /dev/null +++ b/data/difficulty.json @@ -0,0 +1,32 @@ +{ + "$schema": "schema/difficulty.schema.json", + "version": 1, + "default": "imprenditore", + "depletionMultipliers": { "slow": 0.5, "normal": 1.0, "fast": 1.6 }, + "presets": [ + { "id": "apprendista", "name_it": "Apprendista", "name_en": "Apprentice", + "initialCapital": 50000000, "initialCredit": 50000000, "baseInterestRate": 0.03, + "constructionCostMultiplier": 0.8, "tariffMultiplier": 1.15, "wearMultiplier": 0.7, "marketVolatilityMultiplier": 0.6, + "aiCompetitors": 1, "aiCapitalMultiplier": 0.7, "aiCostDiscount": 0.0, + "playerTakeover": "disabled", "takeoverRansomYears": 0, "bankruptcyDays": 180, + "publicFromStart": false, "playerShareAtStart": 1.0, "ironman": "no", "depletion": "slow" }, + { "id": "imprenditore", "name_it": "Imprenditore", "name_en": "Entrepreneur", + "initialCapital": 25000000, "initialCredit": 30000000, "baseInterestRate": 0.05, + "constructionCostMultiplier": 1.0, "tariffMultiplier": 1.0, "wearMultiplier": 1.0, "marketVolatilityMultiplier": 1.0, + "aiCompetitors": 2, "aiCapitalMultiplier": 1.0, "aiCostDiscount": 0.0, + "playerTakeover": "ransom", "takeoverRansomYears": 3, "bankruptcyDays": 90, + "publicFromStart": false, "playerShareAtStart": 1.0, "ironman": "optional", "depletion": "normal" }, + { "id": "magnate", "name_it": "Magnate", "name_en": "Tycoon", + "initialCapital": 15000000, "initialCredit": 15000000, "baseInterestRate": 0.07, + "constructionCostMultiplier": 1.25, "tariffMultiplier": 0.9, "wearMultiplier": 1.3, "marketVolatilityMultiplier": 1.3, + "aiCompetitors": 3, "aiCapitalMultiplier": 1.5, "aiCostDiscount": 0.10, + "playerTakeover": "ransom", "takeoverRansomYears": 1, "bankruptcyDays": 60, + "publicFromStart": false, "playerShareAtStart": 1.0, "ironman": "optional", "depletion": "fast" }, + { "id": "ferro_e_sangue", "name_it": "Ferro e sangue", "name_en": "Iron and blood", + "initialCapital": 10000000, "initialCredit": 10000000, "baseInterestRate": 0.09, + "constructionCostMultiplier": 1.5, "tariffMultiplier": 0.8, "wearMultiplier": 1.6, "marketVolatilityMultiplier": 1.6, + "aiCompetitors": 5, "aiCapitalMultiplier": 2.0, "aiCostDiscount": 0.20, + "playerTakeover": "immediate", "takeoverRansomYears": 0, "bankruptcyDays": 30, + "publicFromStart": true, "playerShareAtStart": 0.6, "ironman": "yes", "depletion": "fast" } + ] +} diff --git a/data/eras.json b/data/eras.json new file mode 100644 index 0000000..5d377a5 --- /dev/null +++ b/data/eras.json @@ -0,0 +1,39 @@ +{ + "$schema": "schema/eras.schema.json", + "version": 1, + "eras": [ + { "id": "steam", "name_it": "Era del vapore", "name_en": "Steam era", "from": 1850 }, + { "id": "diesel", "name_it": "Era diesel", "name_en": "Diesel era", "from": 1925 }, + { "id": "electric", "name_it": "Era elettrica", "name_en": "Electric era", "from": 1950 }, + { "id": "highspeed", "name_it": "Alta velocità", "name_en": "High speed", "from": 1990 } + ], + "tractions": [ + { "id": "steam", "name_it": "Vapore", "from": 1850, "needsElectrification": false }, + { "id": "diesel", "name_it": "Diesel", "from": 1925, "needsElectrification": false }, + { "id": "electric", "name_it": "Elettrica", "from": 1950, "needsElectrification": true }, + { "id": "highspeed", "name_it": "Alta velocità", "from": 1990, "needsElectrification": true } + ], + "bridgeTypes": [ + { "id": "wood", "name_it": "Legno", "from": 1850, "maxSpanM": 60, "costMultiplier": 1.0, "lifeYears": 40 }, + { "id": "iron", "name_it": "Ferro", "from": 1870, "maxSpanM": 150, "costMultiplier": 1.25, "lifeYears": 50 }, + { "id": "steel", "name_it": "Acciaio", "from": 1900, "maxSpanM": 400, "costMultiplier": 1.5, "lifeYears": 60 }, + { "id": "concrete", "name_it": "Cemento armato", "from": 1950, "maxSpanM": 800, "costMultiplier": 1.4, "lifeYears": 70 } + ], + "tunnelLimits": [ + { "from": 1850, "maxLengthM": 1000 }, + { "from": 1900, "maxLengthM": 5000 }, + { "from": 1950, "maxLengthM": 15000 } + ], + "trackClasses": [ + { "id": "c60", "name_it": "Ordinario 60 km/h", "speedKmh": 60, "from": 1850 }, + { "id": "c100", "name_it": "Rinforzato 100 km/h", "speedKmh": 100, "from": 1875 }, + { "id": "c160", "name_it": "Direttissimo 160 km/h", "speedKmh": 160, "from": 1935 }, + { "id": "c250", "name_it": "Alta velocità 250 km/h", "speedKmh": 250, "from": 1990 } + ], + "signals": [ + { "id": "semaphore", "name_it": "Semaforo ad ala", "from": 1850, "price": 80000 }, + { "id": "light", "name_it": "Segnale luminoso", "from": 1930, "price": 150000 }, + { "id": "cab", "name_it": "Segnalamento in cabina", "from": 1990, "price": 400000 } + ], + "electrificationFrom": 1950 +} diff --git a/data/goods.json b/data/goods.json new file mode 100644 index 0000000..13d266a --- /dev/null +++ b/data/goods.json @@ -0,0 +1,45 @@ +{ + "$schema": "schema/goods.schema.json", + "version": 1, + "goods": [ + { "id": "coal", "name_it": "Carbone", "name_en": "Coal", "category": "bulk", "unit": "t", "wagon": "hopper", + "basePrice": 3800, "elasticity": 0.6, "decayDaysAtStation": 60, "era": 1850, + "town": { "category": "fuel", "demandPerThousand": 0.12, "untilYear": 1960 } }, + { "id": "iron_ore", "name_it": "Minerale di ferro", "name_en": "Iron ore", "category": "bulk", "unit": "t", "wagon": "hopper", + "basePrice": 4200, "elasticity": 0.5, "decayDaysAtStation": 90, "era": 1850 }, + { "id": "stone", "name_it": "Pietra", "name_en": "Stone", "category": "bulk", "unit": "t", "wagon": "hopper", + "basePrice": 2500, "elasticity": 0.4, "decayDaysAtStation": 120, "era": 1850 }, + { "id": "crude_oil", "name_it": "Petrolio", "name_en": "Crude oil", "category": "liquid", "unit": "t", "wagon": "tank", + "basePrice": 6500, "elasticity": 0.7, "decayDaysAtStation": 60, "era": 1860 }, + { "id": "logs", "name_it": "Tronchi", "name_en": "Logs", "category": "bulk", "unit": "t", "wagon": "flat", + "basePrice": 3000, "elasticity": 0.5, "decayDaysAtStation": 45, "era": 1850 }, + { "id": "grain", "name_it": "Grano", "name_en": "Grain", "category": "bulk", "unit": "t", "wagon": "hopper", + "basePrice": 5000, "elasticity": 0.6, "decayDaysAtStation": 30, "era": 1850 }, + { "id": "livestock", "name_it": "Bestiame", "name_en": "Livestock", "category": "perishable", "unit": "capi", "wagon": "box", + "basePrice": 9000, "elasticity": 0.7, "decayDaysAtStation": 8, "era": 1850 }, + { "id": "lumber", "name_it": "Legname", "name_en": "Lumber", "category": "general", "unit": "t", "wagon": "flat", + "basePrice": 8000, "elasticity": 0.6, "decayDaysAtStation": 90, "era": 1850, + "town": { "category": "construction", "demandPerThousand": 0.10 } }, + { "id": "steel", "name_it": "Acciaio", "name_en": "Steel", "category": "general", "unit": "t", "wagon": "flat", + "basePrice": 16000, "elasticity": 0.8, "decayDaysAtStation": 120, "era": 1850 }, + { "id": "food", "name_it": "Alimentari", "name_en": "Food", "category": "perishable", "unit": "t", "wagon": "box", + "basePrice": 12000, "elasticity": 0.3, "decayDaysAtStation": 10, "era": 1850, + "town": { "category": "food", "demandPerThousand": 0.45 } }, + { "id": "fuel", "name_it": "Carburante", "name_en": "Fuel", "category": "liquid", "unit": "t", "wagon": "tank", + "basePrice": 16000, "elasticity": 0.5, "decayDaysAtStation": 90, "era": 1870, + "town": { "category": "fuel", "demandPerThousand": 0.12 } }, + { "id": "building_materials", "name_it": "Materiali edili", "name_en": "Building materials", "category": "general", "unit": "t", "wagon": "flat", + "basePrice": 6000, "elasticity": 0.7, "decayDaysAtStation": 120, "era": 1850, + "town": { "category": "construction", "demandPerThousand": 0.18 } }, + { "id": "tools", "name_it": "Attrezzi", "name_en": "Tools", "category": "general", "unit": "casse", "wagon": "box", + "basePrice": 22000, "elasticity": 0.8, "decayDaysAtStation": 120, "era": 1850, + "town": { "category": "goods", "demandPerThousand": 0.06 } }, + { "id": "goods", "name_it": "Merci varie", "name_en": "Goods", "category": "general", "unit": "casse", "wagon": "box", + "basePrice": 20000, "elasticity": 0.9, "decayDaysAtStation": 60, "era": 1850, + "town": { "category": "goods", "demandPerThousand": 0.20 } }, + { "id": "machinery", "name_it": "Macchinari", "name_en": "Machinery", "category": "general", "unit": "pz", "wagon": "flat", + "basePrice": 45000, "elasticity": 0.6, "decayDaysAtStation": 180, "era": 1850, "service": true }, + { "id": "spare_parts", "name_it": "Ricambi", "name_en": "Spare parts", "category": "general", "unit": "casse", "wagon": "box", + "basePrice": 30000, "elasticity": 0.5, "decayDaysAtStation": 180, "era": 1850, "service": true } + ] +} diff --git a/data/industries.json b/data/industries.json new file mode 100644 index 0000000..4c400e2 --- /dev/null +++ b/data/industries.json @@ -0,0 +1,90 @@ +{ + "$schema": "schema/industries.schema.json", + "version": 1, + "industries": [ + { "id": "coal_mine", "name_it": "Miniera di carbone", "name_en": "Coal mine", "kind": "primary", + "recipe": { "inputs": [], "outputs": [ { "good": "coal", "perCycle": 1 } ] }, + "cycleDays": 1, "capacityPerLevel": [150, 300, 500, 800, 1200], "workersPerLevel": [30, 60, 120, 200, 300], "staffPerLevel": [1, 3, 6, 10, 16], + "storageDays": 30, "wearIntensity": 1.3, "footprint": "medium", + "placement": { "needs": "deposit", "resource": "coal", "minTownDistanceKm": 2 }, + "depletable": true, "era": 1850, "upgradeCost": 1500000, "spawnWeight": 1.0 }, + { "id": "iron_mine", "name_it": "Miniera di ferro", "name_en": "Iron mine", "kind": "primary", + "recipe": { "inputs": [], "outputs": [ { "good": "iron_ore", "perCycle": 1 } ] }, + "cycleDays": 1, "capacityPerLevel": [150, 300, 500, 800, 1200], "workersPerLevel": [30, 60, 120, 200, 300], "staffPerLevel": [1, 3, 6, 10, 16], + "storageDays": 30, "wearIntensity": 1.3, "footprint": "medium", + "placement": { "needs": "deposit", "resource": "iron", "minTownDistanceKm": 2 }, + "depletable": true, "era": 1850, "upgradeCost": 1500000, "spawnWeight": 1.0 }, + { "id": "quarry", "name_it": "Cava di pietra", "name_en": "Stone quarry", "kind": "primary", + "recipe": { "inputs": [], "outputs": [ { "good": "stone", "perCycle": 1 } ] }, + "cycleDays": 1, "capacityPerLevel": [200, 400, 650, 1000, 1500], "workersPerLevel": [20, 40, 80, 130, 200], "staffPerLevel": [1, 2, 4, 7, 10], + "storageDays": 40, "wearIntensity": 1.0, "footprint": "medium", + "placement": { "needs": "deposit", "resource": "stone", "minTownDistanceKm": 1.5 }, + "depletable": true, "era": 1850, "upgradeCost": 1000000, "spawnWeight": 0.8 }, + { "id": "oil_well", "name_it": "Pozzo di petrolio", "name_en": "Oil well", "kind": "primary", + "recipe": { "inputs": [], "outputs": [ { "good": "crude_oil", "perCycle": 1 } ] }, + "cycleDays": 1, "capacityPerLevel": [120, 240, 400, 650, 1000], "workersPerLevel": [15, 30, 60, 100, 150], "staffPerLevel": [2, 4, 8, 12, 18], + "storageDays": 30, "wearIntensity": 1.1, "footprint": "small", + "placement": { "needs": "deposit", "resource": "oil", "minTownDistanceKm": 2 }, + "depletable": true, "era": 1860, "upgradeCost": 2000000, "spawnWeight": 0.6 }, + { "id": "logging_camp", "name_it": "Taglialegna", "name_en": "Logging camp", "kind": "primary", + "recipe": { "inputs": [], "outputs": [ { "good": "logs", "perCycle": 1 } ] }, + "cycleDays": 1, "capacityPerLevel": [150, 300, 500, 750, 1100], "workersPerLevel": [20, 40, 80, 120, 180], "staffPerLevel": [0, 1, 2, 4, 6], + "storageDays": 30, "wearIntensity": 0.8, "footprint": "medium", + "placement": { "needs": "forest", "minTownDistanceKm": 2 }, + "depletable": false, "era": 1850, "upgradeCost": 800000, "spawnWeight": 1.0 }, + { "id": "farm", "name_it": "Fattoria", "name_en": "Farm", "kind": "primary", + "recipe": { "inputs": [], "outputs": [ { "good": "grain", "perCycle": 2 }, { "good": "livestock", "perCycle": 1 } ] }, + "cycleDays": 1, "capacityPerLevel": [160, 320, 520, 800, 1200], "workersPerLevel": [15, 30, 60, 100, 150], "staffPerLevel": [0, 1, 2, 3, 5], + "storageDays": 20, "wearIntensity": 0.6, "footprint": "large", + "placement": { "needs": "plain", "minTownDistanceKm": 2, "maxTownDistanceKm": 10 }, + "depletable": false, "era": 1850, "upgradeCost": 600000, "spawnWeight": 1.4 }, + { "id": "sawmill", "name_it": "Segheria", "name_en": "Sawmill", "kind": "processing", + "recipe": { "inputs": [ { "good": "logs", "perCycle": 2 } ], "outputs": [ { "good": "lumber", "perCycle": 1 } ] }, + "cycleDays": 1, "capacityPerLevel": [100, 200, 340, 520, 780], "workersPerLevel": [20, 40, 80, 130, 190], "staffPerLevel": [1, 2, 5, 8, 12], + "storageDays": 30, "wearIntensity": 1.0, "footprint": "medium", + "placement": { "needs": "any", "minTownDistanceKm": 2, "maxTownDistanceKm": 12, "maxInputDistanceKm": 12 }, + "depletable": false, "era": 1850, "upgradeCost": 1200000, "spawnWeight": 0.9 }, + { "id": "steel_mill", "name_it": "Acciaieria", "name_en": "Steel mill", "kind": "processing", + "recipe": { "inputs": [ { "good": "iron_ore", "perCycle": 2 }, { "good": "coal", "perCycle": 1 } ], "outputs": [ { "good": "steel", "perCycle": 1 } ] }, + "cycleDays": 1, "capacityPerLevel": [120, 240, 400, 600, 900], "workersPerLevel": [40, 80, 160, 240, 320], "staffPerLevel": [2, 6, 12, 20, 30], + "storageDays": 30, "wearIntensity": 1.2, "footprint": "large", + "placement": { "needs": "any", "minTownDistanceKm": 2, "maxTownDistanceKm": 12, "maxInputDistanceKm": 12 }, + "depletable": false, "era": 1850, "upgradeCost": 3000000, "spawnWeight": 0.7 }, + { "id": "food_plant", "name_it": "Industria alimentare", "name_en": "Food plant", "kind": "processing", + "recipe": { "inputs": [ { "good": "grain", "perCycle": 2 }, { "good": "livestock", "perCycle": 1 } ], "outputs": [ { "good": "food", "perCycle": 2 } ] }, + "cycleDays": 1, "capacityPerLevel": [150, 300, 500, 760, 1100], "workersPerLevel": [30, 60, 110, 170, 240], "staffPerLevel": [1, 3, 6, 10, 15], + "storageDays": 15, "wearIntensity": 0.9, "footprint": "medium", + "placement": { "needs": "any", "minTownDistanceKm": 2, "maxTownDistanceKm": 12, "maxInputDistanceKm": 12 }, + "depletable": false, "era": 1850, "upgradeCost": 1500000, "spawnWeight": 1.0 }, + { "id": "refinery", "name_it": "Raffineria", "name_en": "Refinery", "kind": "processing", + "recipe": { "inputs": [ { "good": "crude_oil", "perCycle": 2 } ], "outputs": [ { "good": "fuel", "perCycle": 1 } ] }, + "cycleDays": 1, "capacityPerLevel": [100, 200, 340, 520, 800], "workersPerLevel": [30, 60, 110, 170, 240], "staffPerLevel": [3, 6, 12, 20, 30], + "storageDays": 30, "wearIntensity": 1.4, "footprint": "large", + "placement": { "needs": "any", "minTownDistanceKm": 3, "maxTownDistanceKm": 12, "maxInputDistanceKm": 12 }, + "depletable": false, "era": 1870, "upgradeCost": 3500000, "spawnWeight": 0.5 }, + { "id": "brickworks", "name_it": "Fornace di laterizi", "name_en": "Brickworks", "kind": "processing", + "recipe": { "inputs": [ { "good": "stone", "perCycle": 2 }, { "good": "coal", "perCycle": 1 } ], "outputs": [ { "good": "building_materials", "perCycle": 2 } ] }, + "cycleDays": 1, "capacityPerLevel": [140, 280, 460, 700, 1000], "workersPerLevel": [25, 50, 90, 140, 200], "staffPerLevel": [1, 2, 4, 7, 10], + "storageDays": 40, "wearIntensity": 1.1, "footprint": "medium", + "placement": { "needs": "any", "minTownDistanceKm": 2, "maxTownDistanceKm": 12, "maxInputDistanceKm": 12 }, + "depletable": false, "era": 1850, "upgradeCost": 1000000, "spawnWeight": 0.8 }, + { "id": "tool_factory", "name_it": "Fabbrica di attrezzi", "name_en": "Tool factory", "kind": "manufacturing", + "recipe": { "inputs": [ { "good": "steel", "perCycle": 2 }, { "good": "coal", "perCycle": 1 } ], "outputs": [ { "good": "tools", "perCycle": 2 } ] }, + "cycleDays": 1, "capacityPerLevel": [60, 120, 200, 300, 450], "workersPerLevel": [30, 60, 110, 170, 240], "staffPerLevel": [3, 6, 12, 18, 26], + "storageDays": 30, "wearIntensity": 1.0, "footprint": "medium", + "placement": { "needs": "town", "maxTownDistanceKm": 2.5 }, + "depletable": false, "era": 1850, "upgradeCost": 2000000, "spawnWeight": 0.6 }, + { "id": "goods_factory", "name_it": "Manifattura", "name_en": "Goods factory", "kind": "manufacturing", + "recipe": { "inputs": [ { "good": "lumber", "perCycle": 2 }, { "good": "steel", "perCycle": 1 } ], "outputs": [ { "good": "goods", "perCycle": 3 } ] }, + "cycleDays": 1, "capacityPerLevel": [120, 240, 400, 600, 900], "workersPerLevel": [40, 80, 150, 230, 320], "staffPerLevel": [3, 6, 12, 18, 26], + "storageDays": 30, "wearIntensity": 0.9, "footprint": "medium", + "placement": { "needs": "town", "maxTownDistanceKm": 2.5 }, + "depletable": false, "era": 1850, "upgradeCost": 1800000, "spawnWeight": 0.8 }, + { "id": "machine_factory", "name_it": "Fabbrica di macchinari", "name_en": "Machine factory", "kind": "manufacturing", + "recipe": { "inputs": [ { "good": "steel", "perCycle": 2 }, { "good": "tools", "perCycle": 1 } ], "outputs": [ { "good": "machinery", "perCycle": 1 }, { "good": "spare_parts", "perCycle": 2 } ] }, + "cycleDays": 1, "capacityPerLevel": [40, 80, 140, 210, 320], "workersPerLevel": [40, 80, 150, 230, 320], "staffPerLevel": [6, 12, 24, 36, 50], + "storageDays": 60, "wearIntensity": 1.0, "footprint": "large", + "placement": { "needs": "town", "maxTownDistanceKm": 2.5, "minTownPopulation": 4000 }, + "depletable": false, "era": 1850, "upgradeCost": 4000000, "spawnWeight": 0.4 } + ] +} diff --git a/data/maintenance.json b/data/maintenance.json new file mode 100644 index 0000000..ab0c5ce --- /dev/null +++ b/data/maintenance.json @@ -0,0 +1,86 @@ +{ + "$schema": "schema/maintenance.schema.json", + "version": 1, + "components": { + "locomotive": [ + { "id": "engine", "name_it": "Motore o caldaia", "failureWeight": 0.40, "wearPer100Km": 0.25 }, + { "id": "wheelsets", "name_it": "Rodiggio e assali", "failureWeight": 0.25, "wearPer100Km": 0.20 }, + { "id": "brakes", "name_it": "Freni", "failureWeight": 0.20, "wearPer100Km": 0.35 }, + { "id": "electrics", "name_it": "Impianto elettrico o trasmissione", "failureWeight": 0.15, "wearPer100Km": 0.15 } + ], + "car": [ + { "id": "axles", "name_it": "Assali", "failureWeight": 0.5, "wearPer100Km": 0.15 }, + { "id": "brakes", "name_it": "Freni", "failureWeight": 0.3, "wearPer100Km": 0.30 }, + { "id": "body", "name_it": "Cassa", "failureWeight": 0.2, "wearPer100Km": 0.08 } + ] + }, + "wear": { + "gradientThreshold": 0.015, + "gradientWeight": 2.0, + "highSpeedThreshold": 0.8, + "highSpeedWeight": 0.5, + "loadWeight": 0.3, + "ageStepYears": 5, + "ageStepFactor": 0.5 + }, + "failure": { + "h0": 0.002, + "slope": 0.8, + "pivot": 50, + "scale": 10, + "healthyDivisor": 4, + "minorShare": 0.70, + "majorShare": 0.27, + "catastrophicShare": 0.03, + "catastrophicMaxCondition": 15, + "catastrophicMinSpeedShare": 0.8, + "minorSpeedFactor": 0.5, + "rescueSpeedKmh": 40, + "rescueExtraHours": 2, + "derailmentTrackDays": 3, + "derailmentSatisfaction": 0.05 + }, + "effects": { + "engineSpeedBelow": 70, + "engineSpeedBase": 0.6, + "engineSpeedSpan": 0.4, + "fuelPenalty": 0.4, + "comfortMin": 0.8, + "comfortMax": 1.05 + }, + "interventions": [ + { "id": "inspection", "name_it": "Ispezione", "days": 1, "costShare": 0.005, "spareParts": 0, "effect": "inspection" }, + { "id": "service", "name_it": "Tagliando", "days": 3, "costShare": 0.03, "spareParts": 1, "effect": "service" }, + { "id": "overhaul", "name_it": "Revisione generale", "days": 20, "costShare": 0.25, "spareParts": 5, "effect": "overhaul" }, + { "id": "repair_minor", "name_it": "Riparazione dopo guasto lieve", "days": 2, "costShare": 0.05, "spareParts": 1, "effect": "repair", "restoreTo": 80 }, + { "id": "repair_major", "name_it": "Riparazione dopo guasto grave", "days": 7, "costShare": 0.15, "spareParts": 3, "effect": "repair", "restoreTo": 90 }, + { "id": "repair_catastrophic", "name_it": "Ricostruzione dopo deragliamento", "days": 30, "costShare": 0.40, "spareParts": 8, "effect": "replace" } + ], + "inspection": { "brakesTo": 100, "othersPlus": 10, "hazardFactor": 0.5, "hazardDays": 30 }, + "service": { "plus": 40 }, + "overhaul": { "ageFactorReduction": 0.5 }, + "depots": { + "stallsBySize": { "small": 2, "medium": 4, "large": 8 }, + "staffPerStall": 4, + "slowdownAtHalfStaff": 2.0, + "initialSpareParts": 10, + "jobsWorkersPerStall": 6 + }, + "policies": [ + { "id": "economy", "name_it": "Economica", "intervalFactor": 1.5, "effectFactor": 0.7, "costFactor": 0.6 }, + { "id": "standard", "name_it": "Standard", "intervalFactor": 1.0, "effectFactor": 1.0, "costFactor": 1.0 }, + { "id": "thorough", "name_it": "Accurata", "intervalFactor": 0.7, "effectFactor": 1.2, "costFactor": 1.6 } + ], + "intervals": { + "inspectionKm": 3000, "inspectionDays": 45, + "serviceKm": 15000, "serviceDays": 180, + "overhaulYears": 6 + }, + "planner": { + "targetCondition": 40, + "averageDays": 15, + "marginDays": 5, + "alertCondition": 40, + "criticalCondition": 30 + } +} diff --git a/data/regions.json b/data/regions.json new file mode 100644 index 0000000..02ffd24 --- /dev/null +++ b/data/regions.json @@ -0,0 +1,39 @@ +{ + "$schema": "schema/regions.schema.json", + "version": 1, + "concessions": { "unlockTier": 3, "basePrice": 200000000, "priceGrowth": 1.6, "maxRegions": 16 }, + "regions": [ + { "id": "valdoria", "name_it": "Regione di Valdoria", "climate": "temperate", "terrainDifficulty": 1.0, + "resources": { "coal": 1.0, "iron": 1.0, "stone": 1.0, "oil": 0.6 }, "hubs": [ "port", "border" ], "namePool": "padana" }, + { "id": "alpi", "name_it": "Alte Valli", "climate": "alpine", "terrainDifficulty": 1.8, + "resources": { "coal": 0.6, "iron": 1.6, "stone": 1.4, "oil": 0.0 }, "hubs": [ "border" ], "namePool": "alpina" }, + { "id": "litorale", "name_it": "Litorale", "climate": "coastal", "terrainDifficulty": 0.7, + "resources": { "coal": 0.3, "iron": 0.4, "stone": 0.8, "oil": 1.4 }, "hubs": [ "port" ], "namePool": "costiera" }, + { "id": "meridione", "name_it": "Terre del Sole", "climate": "dry", "terrainDifficulty": 1.2, + "resources": { "coal": 0.4, "iron": 0.8, "stone": 1.6, "oil": 1.0 }, "hubs": [ "port" ], "namePool": "meridionale" } + ], + "namePools": [ + { "id": "padana", + "prefixes": [ "Borgo ", "Villa ", "San ", "Sant'", "Castel ", "Ponte ", "Porto ", "Rocca ", "Corte ", "" ], + "roots": [ "Vald", "Mont", "Cer", "Ros", "Alb", "Fior", "Bel", "Lov", "Cas", "Ser", "Tor", "Pall", "Ard", "Ven", "Mar", "Lun", "Gav", "Brem", "Ost", "Coll" ], + "suffixes": [ "oria", "alto", "esio", "ello", "ano", "enza", "ate", "ona", "ino", "ara", "ago", "edo", "ica", "ia" ], + "saints": [ "Elia", "Ambrogio", "Giorgio", "Martino", "Anna", "Michele", "Ilario", "Agata" ] }, + { "id": "alpina", + "prefixes": [ "Pian ", "Val ", "Passo ", "Malga ", "" ], + "roots": [ "Cort", "Bren", "Auron", "Sest", "Livin", "Chiav", "Bor", "Tirn", "Ponte", "Mezz" ], + "suffixes": [ "ina", "egno", "ago", "olo", "ena", "ola", "io" ], + "saints": [ "Bernardo", "Maurizio", "Vigilio" ] }, + { "id": "costiera", + "prefixes": [ "Marina di ", "Lido ", "Porto ", "Capo ", "" ], + "roots": [ "Sal", "Ancor", "Fan", "Ortom", "Ves", "Rimin", "Senig", "Caor" ], + "suffixes": [ "ona", "ese", "ara", "allia", "ino", "ole" ], + "saints": [ "Nicola", "Benedetto", "Elpidio" ] }, + { "id": "meridionale", + "prefixes": [ "Torre ", "Monte ", "Casal ", "San ", "" ], + "roots": [ "Mel", "Trap", "Agrig", "Lent", "Calt", "Pac", "Nis", "Gel", "Ragus" ], + "suffixes": [ "fi", "ani", "ento", "ini", "anissetta", "ino", "emi", "a" ], + "saints": [ "Vito", "Calogero", "Rosalia" ] } + ], + "industryNameTemplates": [ "{type} {town}", "{type} di {town}", "{type} {feature}" ], + "featureNames": [ "Bosco Alto", "Rocca Bruna", "Piana Verde", "Val Fonda", "Colle Rosso", "Prato Lungo", "Sasso Nero", "Fontana Fredda" ] +} diff --git a/data/schema/ai.schema.json b/data/schema/ai.schema.json new file mode 100644 index 0000000..ef9d804 --- /dev/null +++ b/data/schema/ai.schema.json @@ -0,0 +1,103 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Concorrenti IA (ai.json)", + "type": "object", + "properties": { + "$schema": { + "type": "string" + }, + "version": { + "type": "integer", + "minimum": 1 + }, + "planning": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "personalities": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$" + }, + "name_it": { + "type": "string", + "minLength": 1 + }, + "roiThreshold": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "loanShareOfCredit": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "targetsPlayer": { + "type": "boolean" + }, + "buysShares": { + "type": "boolean" + }, + "maintenancePolicy": { + "type": "string", + "enum": [ + "economy", + "standard", + "thorough" + ] + } + }, + "required": [ + "id", + "name_it", + "roiThreshold", + "loanShareOfCredit", + "targetsPlayer", + "buysShares", + "maintenancePolicy" + ], + "additionalProperties": false + }, + "minItems": 3 + }, + "companyNames": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "minItems": 4, + "uniqueItems": true + }, + "colors": { + "type": "array", + "items": { + "type": "string", + "pattern": "^#[0-9a-fA-F]{6}$" + }, + "minItems": 1 + } + }, + "required": [ + "version", + "planning", + "personalities", + "companyNames", + "colors" + ], + "additionalProperties": false +} diff --git a/data/schema/balance.schema.json b/data/schema/balance.schema.json new file mode 100644 index 0000000..5af6531 --- /dev/null +++ b/data/schema/balance.schema.json @@ -0,0 +1,462 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Bilanciamento (balance.json)", + "type": "object", + "properties": { + "$schema": { + "type": "string" + }, + "version": { + "type": "integer", + "minimum": 1 + }, + "time": { + "type": "object", + "properties": { + "tickMs": { + "type": "integer", + "minimum": 1 + }, + "ticksPerDay": { + "type": "integer", + "minimum": 1 + }, + "daysPerMonth": { + "type": "integer", + "minimum": 1 + }, + "monthsPerYear": { + "type": "integer", + "minimum": 1 + }, + "trainClockFactor": { + "type": "number", + "minimum": 1 + }, + "speeds": { + "type": "array", + "items": { + "type": "integer", + "minimum": 0, + "maximum": 64 + }, + "minItems": 1 + }, + "defaultStartYear": { + "type": "integer", + "minimum": 1800, + "maximum": 2300 + } + }, + "required": [ + "tickMs", + "ticksPerDay", + "daysPerMonth", + "monthsPerYear", + "trainClockFactor", + "speeds", + "defaultStartYear" + ], + "additionalProperties": false + }, + "map": { + "type": "object", + "properties": { + "cellSizeM": { + "type": "number", + "minimum": 1 + }, + "sizesKm": { + "type": "array", + "items": { + "type": "integer", + "minimum": 8, + "maximum": 1024 + }, + "minItems": 1 + }, + "chunkCells": { + "type": "integer", + "minimum": 8, + "maximum": 256 + }, + "maxElevationM": { + "type": "number", + "minimum": 100 + }, + "noise": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "relief": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "hydrology": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "cover": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "deposits": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "towns": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "industries": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "hubs": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + } + }, + "required": [ + "cellSizeM", + "sizesKm", + "chunkCells", + "maxElevationM", + "noise", + "relief", + "hydrology", + "cover", + "deposits", + "towns", + "industries", + "hubs" + ], + "additionalProperties": false + }, + "market": { + "type": "object", + "properties": { + "k": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "alpha": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "windowDays": { + "type": "integer", + "minimum": 1 + }, + "minPriceFactor": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "maxPriceFactor": { + "type": "number", + "minimum": 1 + }, + "ratioMin": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "ratioMax": { + "type": "number", + "minimum": 1 + }, + "world": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "historyDays": { + "type": "integer", + "minimum": 1 + } + }, + "required": [ + "k", + "alpha", + "windowDays", + "minPriceFactor", + "maxPriceFactor", + "ratioMin", + "ratioMax", + "world", + "historyDays" + ], + "additionalProperties": false + }, + "localPrice": { + "type": "object", + "properties": { + "lambda": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "maxDeviation": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "epsilon": { + "type": "number", + "minimum": 0 + } + }, + "required": [ + "lambda", + "maxDeviation", + "epsilon" + ], + "additionalProperties": false + }, + "industry": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "growth": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "town": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "migration": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "employment": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "localTransport": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "hubs": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "tariffs": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "finance": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "stockMarket": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "industryMaintenance": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + } + }, + "required": [ + "version", + "time", + "map", + "market", + "localPrice", + "industry", + "growth", + "town", + "migration", + "employment", + "localTransport", + "hubs", + "tariffs", + "finance", + "stockMarket", + "industryMaintenance" + ], + "additionalProperties": false +} diff --git a/data/schema/construction.schema.json b/data/schema/construction.schema.json new file mode 100644 index 0000000..18636ac --- /dev/null +++ b/data/schema/construction.schema.json @@ -0,0 +1,183 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Costruzione (construction.json)", + "type": "object", + "properties": { + "$schema": { + "type": "string" + }, + "version": { + "type": "integer", + "minimum": 1 + }, + "profile": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "maxGradientByTraction": { + "type": "object", + "properties": { + "steam": { + "type": "number", + "minimum": 0.001, + "maximum": 0.2 + }, + "diesel": { + "type": "number", + "minimum": 0.001, + "maximum": 0.2 + }, + "electric": { + "type": "number", + "minimum": 0.001, + "maximum": 0.2 + }, + "highspeed": { + "type": "number", + "minimum": 0.001, + "maximum": 0.2 + } + }, + "required": [ + "steam", + "diesel", + "electric", + "highspeed" + ], + "additionalProperties": false + }, + "speedClasses": { + "type": "array", + "items": { + "type": "object", + "properties": { + "trackClass": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$" + }, + "minRadiusM": { + "type": "number", + "minimum": 1 + }, + "costMultiplier": { + "type": "number", + "minimum": 0.1 + } + }, + "required": [ + "trackClass", + "minRadiusM", + "costMultiplier" + ], + "additionalProperties": false + }, + "minItems": 1 + }, + "curveSpeedFactor": { + "type": "number", + "minimum": 0, + "maximum": 2 + }, + "costs": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "crews": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "rules": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "trackWear": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "structures": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "physics": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + } + }, + "required": [ + "version", + "profile", + "maxGradientByTraction", + "speedClasses", + "curveSpeedFactor", + "costs", + "crews", + "rules", + "trackWear", + "structures", + "physics" + ], + "additionalProperties": false +} diff --git a/data/schema/contracts.schema.json b/data/schema/contracts.schema.json new file mode 100644 index 0000000..94b6cd1 --- /dev/null +++ b/data/schema/contracts.schema.json @@ -0,0 +1,161 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Contratti e grandi opere (contracts.json)", + "type": "object", + "properties": { + "$schema": { + "type": "string" + }, + "version": { + "type": "integer", + "minimum": 1 + }, + "generation": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "templates": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$" + }, + "kind": { + "type": "string", + "enum": [ + "connect", + "deliver", + "greatWork", + "service" + ] + }, + "name_it": { + "type": "string", + "minLength": 1 + }, + "text_it": { + "type": "string", + "minLength": 1 + }, + "durationYears": { + "type": "array", + "items": { + "type": "integer", + "minimum": 1 + }, + "minItems": 2, + "maxItems": 2 + }, + "maxMinutes": { + "type": "array", + "items": { + "type": "integer", + "minimum": 1 + }, + "minItems": 2, + "maxItems": 2 + }, + "quantity": { + "type": "array", + "items": { + "type": "integer", + "minimum": 1 + }, + "minItems": 2, + "maxItems": 2 + }, + "lengthKm": { + "type": "array", + "items": { + "type": "number", + "minimum": 0 + }, + "minItems": 2, + "maxItems": 2 + }, + "reward": { + "type": "integer", + "minimum": 0 + }, + "prestige": { + "type": "integer", + "minimum": 0 + }, + "penalty": { + "type": "integer", + "minimum": 0 + }, + "minYear": { + "type": "integer", + "minimum": 1800, + "maximum": 2300 + } + }, + "required": [ + "id", + "kind", + "name_it", + "text_it", + "durationYears", + "reward", + "prestige", + "penalty", + "minYear" + ], + "additionalProperties": false + }, + "minItems": 1 + }, + "expositions": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$" + }, + "name_it": { + "type": "string", + "minLength": 1 + }, + "reward": { + "type": "integer", + "minimum": 0 + }, + "prestige": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "id", + "name_it", + "reward", + "prestige" + ], + "additionalProperties": false + }, + "minItems": 1 + } + }, + "required": [ + "version", + "generation", + "templates", + "expositions" + ], + "additionalProperties": false +} diff --git a/data/schema/difficulty.schema.json b/data/schema/difficulty.schema.json new file mode 100644 index 0000000..45fec9c --- /dev/null +++ b/data/schema/difficulty.schema.json @@ -0,0 +1,182 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Difficoltà (difficulty.json)", + "type": "object", + "properties": { + "$schema": { + "type": "string" + }, + "version": { + "type": "integer", + "minimum": 1 + }, + "default": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$" + }, + "depletionMultipliers": { + "type": "object", + "properties": { + "slow": { + "type": "number", + "minimum": 0 + }, + "normal": { + "type": "number", + "minimum": 0 + }, + "fast": { + "type": "number", + "minimum": 0 + } + }, + "required": [ + "slow", + "normal", + "fast" + ], + "additionalProperties": false + }, + "presets": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$" + }, + "name_it": { + "type": "string", + "minLength": 1 + }, + "name_en": { + "type": "string", + "minLength": 1 + }, + "initialCapital": { + "type": "integer", + "minimum": 0 + }, + "initialCredit": { + "type": "integer", + "minimum": 0 + }, + "baseInterestRate": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "constructionCostMultiplier": { + "type": "number", + "minimum": 0.1, + "maximum": 10 + }, + "tariffMultiplier": { + "type": "number", + "minimum": 0.1, + "maximum": 10 + }, + "wearMultiplier": { + "type": "number", + "minimum": 0, + "maximum": 10 + }, + "marketVolatilityMultiplier": { + "type": "number", + "minimum": 0, + "maximum": 10 + }, + "aiCompetitors": { + "type": "integer", + "minimum": 0, + "maximum": 16 + }, + "aiCapitalMultiplier": { + "type": "number", + "minimum": 0, + "maximum": 10 + }, + "aiCostDiscount": { + "type": "number", + "minimum": 0, + "maximum": 0.9 + }, + "playerTakeover": { + "type": "string", + "enum": [ + "disabled", + "ransom", + "immediate" + ] + }, + "takeoverRansomYears": { + "type": "integer", + "minimum": 0, + "maximum": 50 + }, + "bankruptcyDays": { + "type": "integer", + "minimum": 1, + "maximum": 3650 + }, + "publicFromStart": { + "type": "boolean" + }, + "playerShareAtStart": { + "type": "number", + "minimum": 0.5, + "maximum": 1 + }, + "ironman": { + "type": "string", + "enum": [ + "no", + "optional", + "yes" + ] + }, + "depletion": { + "type": "string", + "enum": [ + "slow", + "normal", + "fast" + ] + } + }, + "required": [ + "id", + "name_it", + "name_en", + "initialCapital", + "initialCredit", + "baseInterestRate", + "constructionCostMultiplier", + "tariffMultiplier", + "wearMultiplier", + "marketVolatilityMultiplier", + "aiCompetitors", + "aiCapitalMultiplier", + "aiCostDiscount", + "playerTakeover", + "takeoverRansomYears", + "bankruptcyDays", + "publicFromStart", + "playerShareAtStart", + "ironman", + "depletion" + ], + "additionalProperties": false + }, + "minItems": 4 + } + }, + "required": [ + "version", + "default", + "depletionMultipliers", + "presets" + ], + "additionalProperties": false +} diff --git a/data/schema/eras.schema.json b/data/schema/eras.schema.json new file mode 100644 index 0000000..6777d81 --- /dev/null +++ b/data/schema/eras.schema.json @@ -0,0 +1,233 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Ere (eras.json)", + "type": "object", + "properties": { + "$schema": { + "type": "string" + }, + "version": { + "type": "integer", + "minimum": 1 + }, + "eras": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$" + }, + "name_it": { + "type": "string", + "minLength": 1 + }, + "name_en": { + "type": "string", + "minLength": 1 + }, + "from": { + "type": "integer", + "minimum": 1800, + "maximum": 2300 + } + }, + "required": [ + "id", + "name_it", + "name_en", + "from" + ], + "additionalProperties": false + }, + "minItems": 4 + }, + "tractions": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "enum": [ + "steam", + "diesel", + "electric", + "highspeed" + ] + }, + "name_it": { + "type": "string", + "minLength": 1 + }, + "from": { + "type": "integer", + "minimum": 1800, + "maximum": 2300 + }, + "needsElectrification": { + "type": "boolean" + } + }, + "required": [ + "id", + "name_it", + "from", + "needsElectrification" + ], + "additionalProperties": false + }, + "minItems": 1 + }, + "bridgeTypes": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$" + }, + "name_it": { + "type": "string", + "minLength": 1 + }, + "from": { + "type": "integer", + "minimum": 1800, + "maximum": 2300 + }, + "maxSpanM": { + "type": "number", + "minimum": 1 + }, + "costMultiplier": { + "type": "number", + "minimum": 0.1 + }, + "lifeYears": { + "type": "integer", + "minimum": 1 + } + }, + "required": [ + "id", + "name_it", + "from", + "maxSpanM", + "costMultiplier", + "lifeYears" + ], + "additionalProperties": false + }, + "minItems": 1 + }, + "tunnelLimits": { + "type": "array", + "items": { + "type": "object", + "properties": { + "from": { + "type": "integer", + "minimum": 1800, + "maximum": 2300 + }, + "maxLengthM": { + "type": "number", + "minimum": 0 + } + }, + "required": [ + "from", + "maxLengthM" + ], + "additionalProperties": false + }, + "minItems": 1 + }, + "trackClasses": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$" + }, + "name_it": { + "type": "string", + "minLength": 1 + }, + "speedKmh": { + "type": "number", + "minimum": 10, + "maximum": 600 + }, + "from": { + "type": "integer", + "minimum": 1800, + "maximum": 2300 + } + }, + "required": [ + "id", + "name_it", + "speedKmh", + "from" + ], + "additionalProperties": false + }, + "minItems": 1 + }, + "signals": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$" + }, + "name_it": { + "type": "string", + "minLength": 1 + }, + "from": { + "type": "integer", + "minimum": 1800, + "maximum": 2300 + }, + "price": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "id", + "name_it", + "from", + "price" + ], + "additionalProperties": false + }, + "minItems": 1 + }, + "electrificationFrom": { + "type": "integer", + "minimum": 1800, + "maximum": 2300 + } + }, + "required": [ + "version", + "eras", + "tractions", + "bridgeTypes", + "tunnelLimits", + "trackClasses", + "signals", + "electrificationFrom" + ], + "additionalProperties": false +} diff --git a/data/schema/goods.schema.json b/data/schema/goods.schema.json new file mode 100644 index 0000000..87906ed --- /dev/null +++ b/data/schema/goods.schema.json @@ -0,0 +1,125 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Beni (goods.json)", + "type": "object", + "properties": { + "$schema": { + "type": "string" + }, + "version": { + "type": "integer", + "minimum": 1 + }, + "goods": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$" + }, + "name_it": { + "type": "string", + "minLength": 1 + }, + "name_en": { + "type": "string", + "minLength": 1 + }, + "category": { + "type": "string", + "enum": [ + "bulk", + "general", + "liquid", + "perishable" + ] + }, + "unit": { + "type": "string", + "minLength": 1 + }, + "wagon": { + "type": "string", + "enum": [ + "hopper", + "flat", + "tank", + "box" + ] + }, + "basePrice": { + "type": "integer", + "minimum": 1 + }, + "elasticity": { + "type": "number", + "minimum": 0, + "maximum": 3 + }, + "decayDaysAtStation": { + "type": "integer", + "minimum": 1 + }, + "era": { + "type": "integer", + "minimum": 1800, + "maximum": 2300 + }, + "town": { + "type": "object", + "properties": { + "category": { + "type": "string", + "enum": [ + "food", + "goods", + "fuel", + "construction" + ] + }, + "demandPerThousand": { + "type": "number", + "minimum": 0, + "maximum": 10 + }, + "untilYear": { + "type": "integer", + "minimum": 1800, + "maximum": 2300 + } + }, + "required": [ + "category", + "demandPerThousand" + ], + "additionalProperties": false + }, + "service": { + "type": "boolean" + } + }, + "required": [ + "id", + "name_it", + "name_en", + "category", + "unit", + "wagon", + "basePrice", + "elasticity", + "decayDaysAtStation", + "era" + ], + "additionalProperties": false + }, + "minItems": 12 + } + }, + "required": [ + "version", + "goods" + ], + "additionalProperties": false +} diff --git a/data/schema/industries.schema.json b/data/schema/industries.schema.json new file mode 100644 index 0000000..1a8329d --- /dev/null +++ b/data/schema/industries.schema.json @@ -0,0 +1,241 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Industrie (industries.json)", + "type": "object", + "properties": { + "$schema": { + "type": "string" + }, + "version": { + "type": "integer", + "minimum": 1 + }, + "industries": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$" + }, + "name_it": { + "type": "string", + "minLength": 1 + }, + "name_en": { + "type": "string", + "minLength": 1 + }, + "kind": { + "type": "string", + "enum": [ + "primary", + "processing", + "manufacturing" + ] + }, + "recipe": { + "type": "object", + "properties": { + "inputs": { + "type": "array", + "items": { + "type": "object", + "properties": { + "good": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$" + }, + "perCycle": { + "type": "integer", + "minimum": 1, + "maximum": 100 + } + }, + "required": [ + "good", + "perCycle" + ], + "additionalProperties": false + }, + "minItems": 0, + "maxItems": 4 + }, + "outputs": { + "type": "array", + "items": { + "type": "object", + "properties": { + "good": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$" + }, + "perCycle": { + "type": "integer", + "minimum": 1, + "maximum": 100 + } + }, + "required": [ + "good", + "perCycle" + ], + "additionalProperties": false + }, + "minItems": 1, + "maxItems": 3 + } + }, + "required": [ + "inputs", + "outputs" + ], + "additionalProperties": false + }, + "cycleDays": { + "type": "integer", + "minimum": 1, + "maximum": 30 + }, + "capacityPerLevel": { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + }, + "minItems": 5, + "maxItems": 5 + }, + "workersPerLevel": { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + }, + "minItems": 5, + "maxItems": 5 + }, + "staffPerLevel": { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + }, + "minItems": 5, + "maxItems": 5 + }, + "storageDays": { + "type": "integer", + "minimum": 1, + "maximum": 365 + }, + "wearIntensity": { + "type": "number", + "minimum": 0, + "maximum": 5 + }, + "footprint": { + "type": "string", + "enum": [ + "small", + "medium", + "large" + ] + }, + "placement": { + "type": "object", + "properties": { + "needs": { + "type": "string", + "enum": [ + "deposit", + "forest", + "plain", + "coast", + "town", + "any" + ] + }, + "resource": { + "type": "string", + "enum": [ + "coal", + "iron", + "stone", + "oil" + ] + }, + "minTownDistanceKm": { + "type": "number", + "minimum": 0, + "maximum": 50 + }, + "maxTownDistanceKm": { + "type": "number", + "minimum": 0, + "maximum": 100 + }, + "maxInputDistanceKm": { + "type": "number", + "minimum": 0, + "maximum": 100 + }, + "minTownPopulation": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "needs" + ], + "additionalProperties": false + }, + "depletable": { + "type": "boolean" + }, + "era": { + "type": "integer", + "minimum": 1800, + "maximum": 2300 + }, + "upgradeCost": { + "type": "integer", + "minimum": 0 + }, + "spawnWeight": { + "type": "number", + "minimum": 0, + "maximum": 10 + } + }, + "required": [ + "id", + "name_it", + "name_en", + "kind", + "recipe", + "cycleDays", + "capacityPerLevel", + "workersPerLevel", + "staffPerLevel", + "storageDays", + "wearIntensity", + "footprint", + "placement", + "depletable", + "era", + "upgradeCost", + "spawnWeight" + ], + "additionalProperties": false + }, + "minItems": 14 + } + }, + "required": [ + "version", + "industries" + ], + "additionalProperties": false +} diff --git a/data/schema/maintenance.schema.json b/data/schema/maintenance.schema.json new file mode 100644 index 0000000..ce88a48 --- /dev/null +++ b/data/schema/maintenance.schema.json @@ -0,0 +1,321 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Manutenzione dei treni (maintenance.json)", + "type": "object", + "properties": { + "$schema": { + "type": "string" + }, + "version": { + "type": "integer", + "minimum": 1 + }, + "components": { + "type": "object", + "properties": { + "locomotive": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$" + }, + "name_it": { + "type": "string", + "minLength": 1 + }, + "failureWeight": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "wearPer100Km": { + "type": "number", + "minimum": 0, + "maximum": 10 + } + }, + "required": [ + "id", + "name_it", + "failureWeight", + "wearPer100Km" + ], + "additionalProperties": false + }, + "minItems": 1 + }, + "car": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$" + }, + "name_it": { + "type": "string", + "minLength": 1 + }, + "failureWeight": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "wearPer100Km": { + "type": "number", + "minimum": 0, + "maximum": 10 + } + }, + "required": [ + "id", + "name_it", + "failureWeight", + "wearPer100Km" + ], + "additionalProperties": false + }, + "minItems": 1 + } + }, + "required": [ + "locomotive", + "car" + ], + "additionalProperties": false + }, + "wear": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "failure": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "effects": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "interventions": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$" + }, + "name_it": { + "type": "string", + "minLength": 1 + }, + "days": { + "type": "integer", + "minimum": 1 + }, + "costShare": { + "type": "number", + "minimum": 0, + "maximum": 2 + }, + "spareParts": { + "type": "integer", + "minimum": 0 + }, + "effect": { + "type": "string", + "enum": [ + "inspection", + "service", + "overhaul", + "repair", + "replace" + ] + }, + "restoreTo": { + "type": "number", + "minimum": 0, + "maximum": 100 + } + }, + "required": [ + "id", + "name_it", + "days", + "costShare", + "spareParts", + "effect" + ], + "additionalProperties": false + }, + "minItems": 6 + }, + "inspection": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "service": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "overhaul": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "depots": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "policies": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "enum": [ + "economy", + "standard", + "thorough" + ] + }, + "name_it": { + "type": "string", + "minLength": 1 + }, + "intervalFactor": { + "type": "number", + "minimum": 0.1 + }, + "effectFactor": { + "type": "number", + "minimum": 0.1 + }, + "costFactor": { + "type": "number", + "minimum": 0.1 + } + }, + "required": [ + "id", + "name_it", + "intervalFactor", + "effectFactor", + "costFactor" + ], + "additionalProperties": false + }, + "minItems": 3, + "maxItems": 3 + }, + "intervals": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "planner": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + } + }, + "required": [ + "version", + "components", + "wear", + "failure", + "effects", + "interventions", + "inspection", + "service", + "overhaul", + "depots", + "policies", + "intervals", + "planner" + ], + "additionalProperties": false +} diff --git a/data/schema/regions.schema.json b/data/schema/regions.schema.json new file mode 100644 index 0000000..cb43873 --- /dev/null +++ b/data/schema/regions.schema.json @@ -0,0 +1,205 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Regioni e nomi (regions.json)", + "type": "object", + "properties": { + "$schema": { + "type": "string" + }, + "version": { + "type": "integer", + "minimum": 1 + }, + "concessions": { + "type": "object", + "properties": { + "unlockTier": { + "type": "integer", + "minimum": 1, + "maximum": 5 + }, + "basePrice": { + "type": "integer", + "minimum": 0 + }, + "priceGrowth": { + "type": "number", + "minimum": 1 + }, + "maxRegions": { + "type": "integer", + "minimum": 1, + "maximum": 64 + } + }, + "required": [ + "unlockTier", + "basePrice", + "priceGrowth", + "maxRegions" + ], + "additionalProperties": false + }, + "regions": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$" + }, + "name_it": { + "type": "string", + "minLength": 1 + }, + "climate": { + "type": "string", + "enum": [ + "temperate", + "alpine", + "coastal", + "dry" + ] + }, + "terrainDifficulty": { + "type": "number", + "minimum": 0.1, + "maximum": 5 + }, + "resources": { + "type": "object", + "properties": { + "coal": { + "type": "number", + "minimum": 0 + }, + "iron": { + "type": "number", + "minimum": 0 + }, + "stone": { + "type": "number", + "minimum": 0 + }, + "oil": { + "type": "number", + "minimum": 0 + } + }, + "required": [ + "coal", + "iron", + "stone", + "oil" + ], + "additionalProperties": false + }, + "hubs": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "port", + "border" + ] + }, + "minItems": 0 + }, + "namePool": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$" + } + }, + "required": [ + "id", + "name_it", + "climate", + "terrainDifficulty", + "resources", + "hubs", + "namePool" + ], + "additionalProperties": false + }, + "minItems": 1 + }, + "namePools": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$" + }, + "prefixes": { + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1 + }, + "roots": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "minItems": 4 + }, + "suffixes": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "minItems": 2 + }, + "saints": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "minItems": 1 + } + }, + "required": [ + "id", + "prefixes", + "roots", + "suffixes", + "saints" + ], + "additionalProperties": false + }, + "minItems": 1 + }, + "industryNameTemplates": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "minItems": 1 + }, + "featureNames": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "minItems": 1 + } + }, + "required": [ + "version", + "concessions", + "regions", + "namePools", + "industryNameTemplates", + "featureNames" + ], + "additionalProperties": false +} diff --git a/data/schema/tiers.schema.json b/data/schema/tiers.schema.json new file mode 100644 index 0000000..717abad --- /dev/null +++ b/data/schema/tiers.schema.json @@ -0,0 +1,158 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Livelli della compagnia (tiers.json)", + "type": "object", + "properties": { + "$schema": { + "type": "string" + }, + "version": { + "type": "integer", + "minimum": 1 + }, + "ratingScale": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "AAA", + "AA", + "A", + "BBB", + "BB", + "B", + "CCC", + "CC", + "C", + "D" + ] + }, + "minItems": 10, + "maxItems": 10, + "uniqueItems": true + }, + "tiers": { + "type": "array", + "items": { + "type": "object", + "properties": { + "level": { + "type": "integer", + "minimum": 1, + "maximum": 5 + }, + "name_it": { + "type": "string", + "minLength": 1 + }, + "name_en": { + "type": "string", + "minLength": 1 + }, + "requirements": { + "type": "object", + "properties": { + "netWorth": { + "type": "integer", + "minimum": 0 + }, + "connectedTownsOver": { + "type": "object", + "properties": { + "count": { + "type": "integer", + "minimum": 0 + }, + "population": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "count", + "population" + ], + "additionalProperties": false + }, + "creditRating": { + "type": "string", + "enum": [ + "AAA", + "AA", + "A", + "BBB", + "BB", + "B", + "CCC", + "CC", + "C", + "D" + ] + } + }, + "required": [ + "netWorth", + "connectedTownsOver", + "creditRating" + ], + "additionalProperties": false + }, + "unlocks": { + "type": "object", + "properties": { + "maxLoanFactor": { + "type": "number", + "minimum": 0 + }, + "crews": { + "type": "integer", + "minimum": 1 + }, + "trading": { + "type": "boolean" + }, + "buyIndustry": { + "type": "boolean" + }, + "ipo": { + "type": "boolean" + }, + "hostileTakeover": { + "type": "boolean" + }, + "concessions": { + "type": "boolean" + } + }, + "required": [ + "maxLoanFactor", + "crews", + "trading", + "buyIndustry", + "ipo", + "hostileTakeover", + "concessions" + ], + "additionalProperties": false + } + }, + "required": [ + "level", + "name_it", + "name_en", + "requirements", + "unlocks" + ], + "additionalProperties": false + }, + "minItems": 5, + "maxItems": 5 + } + }, + "required": [ + "version", + "ratingScale", + "tiers" + ], + "additionalProperties": false +} diff --git a/data/schema/vehicles.schema.json b/data/schema/vehicles.schema.json new file mode 100644 index 0000000..dc02d15 --- /dev/null +++ b/data/schema/vehicles.schema.json @@ -0,0 +1,158 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Veicoli (vehicles.json)", + "type": "object", + "properties": { + "$schema": { + "type": "string" + }, + "version": { + "type": "integer", + "minimum": 1 + }, + "vehicles": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$" + }, + "kind": { + "type": "string", + "enum": [ + "locomotive", + "wagon", + "coach" + ] + }, + "name_it": { + "type": "string", + "minLength": 1 + }, + "name_en": { + "type": "string", + "minLength": 1 + }, + "eraFrom": { + "type": "integer", + "minimum": 1800, + "maximum": 2300 + }, + "eraTo": { + "type": "integer", + "minimum": 1800, + "maximum": 2300 + }, + "powerKw": { + "type": "number", + "minimum": 0 + }, + "tractiveEffortKn": { + "type": "number", + "minimum": 0 + }, + "maxSpeedKmh": { + "type": "number", + "minimum": 1, + "maximum": 600 + }, + "massT": { + "type": "number", + "minimum": 0.1 + }, + "lengthM": { + "type": "number", + "minimum": 1, + "maximum": 60 + }, + "price": { + "type": "integer", + "minimum": 0 + }, + "runningCostPerYear": { + "type": "integer", + "minimum": 0 + }, + "lifeYears": { + "type": "integer", + "minimum": 1, + "maximum": 200 + }, + "traction": { + "type": "string", + "enum": [ + "steam", + "diesel", + "electric", + "highspeed" + ] + }, + "components": { + "type": "object", + "additionalProperties": { + "type": "number", + "minimum": 0, + "maximum": 5 + } + }, + "capacity": { + "type": "integer", + "minimum": 1 + }, + "wagonType": { + "type": "string", + "enum": [ + "hopper", + "flat", + "tank", + "box" + ] + }, + "goods": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$" + }, + "minItems": 1, + "uniqueItems": true + }, + "paxCapacity": { + "type": "integer", + "minimum": 1 + }, + "class": { + "type": "string", + "enum": [ + "worker", + "staff" + ] + } + }, + "required": [ + "id", + "kind", + "name_it", + "name_en", + "eraFrom", + "maxSpeedKmh", + "massT", + "lengthM", + "price", + "runningCostPerYear", + "lifeYears", + "components" + ], + "additionalProperties": false + }, + "minItems": 8 + } + }, + "required": [ + "version", + "vehicles" + ], + "additionalProperties": false +} diff --git a/data/tiers.json b/data/tiers.json new file mode 100644 index 0000000..1eb5ccb --- /dev/null +++ b/data/tiers.json @@ -0,0 +1,22 @@ +{ + "$schema": "schema/tiers.schema.json", + "version": 1, + "ratingScale": [ "AAA", "AA", "A", "BBB", "BB", "B", "CCC", "CC", "C", "D" ], + "tiers": [ + { "level": 1, "name_it": "Compagnia locale", "name_en": "Local company", + "requirements": { "netWorth": 0, "connectedTownsOver": { "count": 0, "population": 0 }, "creditRating": "D" }, + "unlocks": { "maxLoanFactor": 1.0, "crews": 2, "trading": false, "buyIndustry": false, "ipo": false, "hostileTakeover": false, "concessions": false } }, + { "level": 2, "name_it": "Compagnia regionale", "name_en": "Regional company", + "requirements": { "netWorth": 100000000, "connectedTownsOver": { "count": 3, "population": 1000 }, "creditRating": "BB" }, + "unlocks": { "maxLoanFactor": 2.0, "crews": 4, "trading": true, "buyIndustry": false, "ipo": false, "hostileTakeover": false, "concessions": false } }, + { "level": 3, "name_it": "Compagnia nazionale", "name_en": "National company", + "requirements": { "netWorth": 500000000, "connectedTownsOver": { "count": 8, "population": 2000 }, "creditRating": "BBB" }, + "unlocks": { "maxLoanFactor": 4.0, "crews": 8, "trading": true, "buyIndustry": true, "ipo": false, "hostileTakeover": false, "concessions": true } }, + { "level": 4, "name_it": "Grande compagnia", "name_en": "Major company", + "requirements": { "netWorth": 2000000000, "connectedTownsOver": { "count": 15, "population": 3000 }, "creditRating": "A" }, + "unlocks": { "maxLoanFactor": 8.0, "crews": 12, "trading": true, "buyIndustry": true, "ipo": true, "hostileTakeover": false, "concessions": true } }, + { "level": 5, "name_it": "Impero ferroviario", "name_en": "Railway empire", + "requirements": { "netWorth": 8000000000, "connectedTownsOver": { "count": 25, "population": 5000 }, "creditRating": "AA" }, + "unlocks": { "maxLoanFactor": 16.0, "crews": 20, "trading": true, "buyIndustry": true, "ipo": true, "hostileTakeover": true, "concessions": true } } + ] +} diff --git a/data/vehicles.json b/data/vehicles.json new file mode 100644 index 0000000..ea461f5 --- /dev/null +++ b/data/vehicles.json @@ -0,0 +1,58 @@ +{ + "$schema": "schema/vehicles.schema.json", + "version": 1, + "vehicles": [ + { "id": "loco_steam_1850", "kind": "locomotive", "name_it": "Ardita 2-6-0", "name_en": "Ardita 2-6-0", + "eraFrom": 1850, "eraTo": 1905, "powerKw": 300, "tractiveEffortKn": 45, "maxSpeedKmh": 60, "massT": 38, "lengthM": 16, + "price": 1800000, "runningCostPerYear": 240000, "lifeYears": 25, "traction": "steam", + "components": { "engine": 1.0, "wheelsets": 0.8, "brakes": 1.0, "electrics": 0.6 } }, + { "id": "loco_steam_1878", "kind": "locomotive", "name_it": "Vittoria 2-8-0", "name_en": "Vittoria 2-8-0", + "eraFrom": 1878, "eraTo": 1935, "powerKw": 650, "tractiveEffortKn": 110, "maxSpeedKmh": 70, "massT": 62, "lengthM": 18, + "price": 3200000, "runningCostPerYear": 380000, "lifeYears": 30, "traction": "steam", + "components": { "engine": 1.0, "wheelsets": 0.9, "brakes": 1.0, "electrics": 0.6 } }, + { "id": "loco_steam_1902", "kind": "locomotive", "name_it": "Freccia 4-6-2", "name_en": "Freccia 4-6-2", + "eraFrom": 1902, "eraTo": 1945, "powerKw": 1150, "tractiveEffortKn": 95, "maxSpeedKmh": 110, "massT": 88, "lengthM": 21, + "price": 5600000, "runningCostPerYear": 560000, "lifeYears": 30, "traction": "steam", + "components": { "engine": 1.1, "wheelsets": 1.0, "brakes": 1.0, "electrics": 0.6 } }, + { "id": "loco_diesel_1925", "kind": "locomotive", "name_it": "Aquila D1", "name_en": "Aquila D1", + "eraFrom": 1925, "eraTo": 1975, "powerKw": 950, "tractiveEffortKn": 180, "maxSpeedKmh": 100, "massT": 72, "lengthM": 17, + "price": 7500000, "runningCostPerYear": 420000, "lifeYears": 30, "traction": "diesel", + "components": { "engine": 0.9, "wheelsets": 0.8, "brakes": 0.9, "electrics": 0.9 } }, + { "id": "loco_electric_1950", "kind": "locomotive", "name_it": "Saetta E50", "name_en": "Saetta E50", + "eraFrom": 1950, "eraTo": 2010, "powerKw": 3200, "tractiveEffortKn": 260, "maxSpeedKmh": 160, "massT": 84, "lengthM": 18, + "price": 14000000, "runningCostPerYear": 520000, "lifeYears": 35, "traction": "electric", + "components": { "engine": 0.7, "wheelsets": 0.9, "brakes": 0.9, "electrics": 1.2 } }, + { "id": "loco_highspeed_1990", "kind": "locomotive", "name_it": "Lampo AV", "name_en": "Lampo HS", + "eraFrom": 1990, "eraTo": 2045, "powerKw": 8800, "tractiveEffortKn": 300, "maxSpeedKmh": 250, "massT": 68, "lengthM": 22, + "price": 42000000, "runningCostPerYear": 1400000, "lifeYears": 30, "traction": "highspeed", + "components": { "engine": 0.8, "wheelsets": 1.2, "brakes": 1.1, "electrics": 1.3 } }, + { "id": "wagon_hopper", "kind": "wagon", "name_it": "Carro tramoggia", "name_en": "Hopper wagon", + "eraFrom": 1850, "maxSpeedKmh": 90, "massT": 9, "lengthM": 11, "price": 120000, "runningCostPerYear": 12000, "lifeYears": 40, + "capacity": 20, "wagonType": "hopper", "goods": [ "coal", "iron_ore", "stone", "grain" ], + "components": { "axles": 1.0, "brakes": 1.0, "body": 0.8 } }, + { "id": "wagon_flat", "kind": "wagon", "name_it": "Carro pianale", "name_en": "Flat wagon", + "eraFrom": 1850, "maxSpeedKmh": 90, "massT": 8, "lengthM": 11, "price": 100000, "runningCostPerYear": 10000, "lifeYears": 40, + "capacity": 20, "wagonType": "flat", "goods": [ "logs", "lumber", "steel", "building_materials", "machinery" ], + "components": { "axles": 1.0, "brakes": 1.0, "body": 0.6 } }, + { "id": "wagon_tank", "kind": "wagon", "name_it": "Carro cisterna", "name_en": "Tank wagon", + "eraFrom": 1860, "maxSpeedKmh": 90, "massT": 10, "lengthM": 11, "price": 160000, "runningCostPerYear": 14000, "lifeYears": 40, + "capacity": 18, "wagonType": "tank", "goods": [ "crude_oil", "fuel" ], + "components": { "axles": 1.0, "brakes": 1.0, "body": 1.0 } }, + { "id": "wagon_box", "kind": "wagon", "name_it": "Carro coperto", "name_en": "Box wagon", + "eraFrom": 1850, "maxSpeedKmh": 90, "massT": 9, "lengthM": 11, "price": 130000, "runningCostPerYear": 12000, "lifeYears": 40, + "capacity": 16, "wagonType": "box", "goods": [ "food", "goods", "tools", "spare_parts", "livestock", "grain" ], + "components": { "axles": 1.0, "brakes": 1.0, "body": 1.0 } }, + { "id": "coach_worker", "kind": "coach", "name_it": "Carrozza operai", "name_en": "Workers' coach", + "eraFrom": 1850, "maxSpeedKmh": 100, "massT": 18, "lengthM": 14, "price": 220000, "runningCostPerYear": 20000, "lifeYears": 40, + "paxCapacity": 60, "class": "worker", + "components": { "axles": 1.0, "brakes": 1.0, "body": 1.0 } }, + { "id": "coach_staff", "kind": "coach", "name_it": "Carrozza tecnici", "name_en": "Staff coach", + "eraFrom": 1850, "maxSpeedKmh": 110, "massT": 20, "lengthM": 14, "price": 320000, "runningCostPerYear": 26000, "lifeYears": 40, + "paxCapacity": 32, "class": "staff", + "components": { "axles": 1.0, "brakes": 1.0, "body": 1.2 } }, + { "id": "coach_modern", "kind": "coach", "name_it": "Carrozza moderna", "name_en": "Modern coach", + "eraFrom": 1950, "maxSpeedKmh": 250, "massT": 40, "lengthM": 26, "price": 1600000, "runningCostPerYear": 60000, "lifeYears": 35, + "paxCapacity": 80, "class": "worker", + "components": { "axles": 1.0, "brakes": 1.0, "body": 1.0 } } + ] +} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 95283fe..c516ce3 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -26,16 +26,16 @@ Regole: | `ViaFerrea.Core.Common` | `Rng` (xoshiro256**), `StableHash`, `XxHash64`, `DMath` (funzioni trascendenti deterministiche), `Money`, identità tipizzate, `Vec2`. | | `ViaFerrea.Core.Time` | `GameClock`, `GameDate`, costanti di calendario. | | `ViaFerrea.Core.Data` | Definizioni immutabili caricate da `data/*.json` (`GameData`), contesto JSON con source generator, validatore di schema e validatore semantico. | -| `ViaFerrea.Core.Map` | `Terrain` (altezze `ushort` in decimetri, tipi cella `byte`), `MapGenerator`, rumore di valore, giacimenti, `TerrainSampler`, chunk 64×64. | +| `ViaFerrea.Core.Map` | `Terrain` (altezze `ushort` in decimetri, tipi cella `byte`, larghezza dei fiumi), `MapGenerator` (ADR 0005), `ValueNoise`, `TerrainSampler`, `NameGenerator`, chunk 64×64. | | `ViaFerrea.Core.Economy` | Città, industrie, hub, mercato, compagnie, registro contabile a partita doppia, finanza. | | `ViaFerrea.Core.Rail` *(F2)* | `TrackPlanner`, opere e cantieri, `TrackGraph`, stazioni, depositi, segnali, treni, linee, `LineGraph`, pacchetti, tariffe. | | `ViaFerrea.Core.Commands` | Comandi di gioco (record immutabili) ed esiti. Sono l'unico modo di cambiare il mondo dall'esterno, anche per le IA. | -| `ViaFerrea.Core.Simulation` | `World`, `WorldContext`, i sistemi e il loro ordine, eventi in uscita. | +| `ViaFerrea.Core.Simulation` | `World`, `WorldContext`, `SystemPipeline` e `Systems/`, `WorldFactory`, `IndustryPlacer`, `CommandProcessor`, eventi in uscita. | | `ViaFerrea.Core.Persistence` | `SaveWriter`/`SaveReader`, `SaveFile` (Brotli), `StateHasher`. | ## 3. Il tick -`World.Tick()` avanza di un tick (50 ms di gioco, 1/240 di giorno) e chiama i sistemi in ordine fisso: +`World.Tick()` esegue i sistemi in ordine fisso (`SystemPipeline.CreateDefault`) e poi avanza l'orologio. L'ordine della guida è: ``` Clock → Commands → Construction → Trains → Signals → Stations → Maintenance (treni) @@ -43,9 +43,25 @@ Clock → Commands → Construction → Trains → Signals → Stations → Main → Finance → StockMarket → AiAgents (mensile) → Events → Contracts → Hash (giornaliero) ``` -- Ogni sistema implementa `ISimSystem.Step(WorldContext ctx)`; i sistemi giornalieri o mensili controllano `ctx.IsNewDay` / `ctx.IsNewMonth` e ritornano subito negli altri tick, così il costo di un tick «vuoto» è di poche decine di nanosecondi. -- `WorldContext` espone il mondo, i dati, il calendario, i flussi `Rng` del sistema e la coda degli eventi in uscita (notifiche, avvisi, notizie) che il server traduce in messaggi. -- I comandi arrivano in una coda; il server la riempie dai socket, le IA la riempiono dal proprio sistema; il sistema `Commands` la drena a inizio tick. Per il replay si registrano `(tick, comando)`. +Sistemi implementati (F1), nella loro posizione: + +| Sistema | Frequenza | Cosa fa | +|---|---|---| +| `ClockSystem` | tick | calcola una volta gli indicatori di giorno, mese, trimestre, anno | +| `CommandSystem` | tick | drena la coda dei comandi (`CommandProcessor`), registra esiti ed eventualmente il log per il replay | +| `LocalTransportSystem` | giorno | trasporto locale su strada tra produttori, consumatori e hub entro 3 km (posto di «Stations», ADR 0004) | +| `DemandSystem` | giorno | domanda delle città (con elasticità) e input richiesti dalle industrie | +| `EmploymentSystem` | giorno/mese | servizi cittadini, lavoratori in sede, contratti a piedi; presenze e coperture (posto di «Commuting») | +| `IndustrySystem` | giorno/trimestre/anno | produzione, esaurimento giacimenti, salari, crescita delle industrie servite, chiusure, nascite | +| `TownSystem` | giorno/mese/anno | consumo e soddisfazione, crescita, migrazione, espansione dell'abitato | +| `MarketSystem` | giorno | prezzi globali con componente mondiale e shock, domanda insoddisfatta | +| `FinanceSystem` | giorno/mese/anno | cassa negativa e bancarotta, rate dei prestiti, rating, chiusura dei conti | +| `HashSystem` | giorno | hash dello stato dinamico | + +- Ogni sistema implementa `ISimSystem.Step(WorldContext ctx)`; i sistemi giornalieri o mensili controllano `ctx.IsNewDay` / `ctx.IsNewMonth` e ritornano subito negli altri tick: 239 tick su 240 costano pochi nanosecondi finché non arrivano i treni. +- `WorldContext` espone il mondo, i dati e il calendario; gli eventi in uscita (notifiche, notizie) vanno in `World.Events`, che il server svuota. +- I comandi arrivano in una coda; il server la riempie dai socket, le IA dal proprio sistema; il sistema `Commands` la drena a inizio tick. Per il replay si registrano `(tick, comando)` in `World.CommandLog`. +- I flussi pseudo-casuali dei sottosistemi si ottengono con `World.Stream(nome)` (derivati dalla radice con `Rng.Fork`, salvati per nome). ## 4. Determinismo @@ -60,20 +76,22 @@ Requisito: stesso seme + stessi comandi agli stessi tick ⇒ stesso hash di stat ## 5. Dati -- File in `data/*.json`, schema in `data/schema/*.schema.json` (sottoinsieme di JSON Schema validato da Core senza librerie esterne), validazione semantica (id univoci, riferimenti risolti, limiti) in `DataValidator`. +- File in `data/*.json`, schema in `data/schema/*.schema.json` (sottoinsieme di JSON Schema validato da Core senza librerie esterne), deserializzazione rigorosa (proprietà sconosciute vietate, proprietà `required`), validazione semantica (id univoci, riferimenti risolti, limiti) in `DataValidator` (ADR 0002). - Caricamento con `System.Text.Json` e source generator (`DataJsonContext`), nessuna reflection. - `GameData.Hash` (XxHash64 dei file normalizzati) viaggia nel `Welcome`: client e server devono avere gli stessi dati. ## 6. Economia e contabilità -- Ogni movimento di denaro passa dal registro (`Ledger`) come trasferimento tra conti: compagnie, industrie, città (servizi), e il conto `Esterno` che rappresenta il resto del mondo (salari, clienti delle tariffe, mercato mondiale degli hub). La somma di tutti i saldi è sempre zero: è l'invariante «denaro» dei test. -- Ogni unità di merce sta in un deposito tracciato (magazzini delle industrie, delle stazioni, dei depositi, carichi dei treni, pacchetti) e i contatori per bene registrano prodotto, consumato, deperito, importato, esportato: totale in giacenza = prodotto + importato − consumato − deperito − esportato. È l'invariante «merci». +- Entità in `ViaFerrea.Core.Economy`: `Town`, `Industry`, `Hub`, `ResourceSite`, `Company` (con `Loan`), `CommuteContract`, `Market`, `Tariffs`. +- Ogni movimento di denaro passa dal registro (`MoneyLedger.Transfer`) tra conti: compagnie, industrie e il conto `Esterno` (famiglie, clienti delle tariffe, mercato mondiale). La somma di tutti i saldi è sempre zero: è l'invariante «denaro» dei test. Le voci del conto economico delle compagnie (`LedgerEntry`) si accumulano per mese e per anno. +- Ogni unità di merce sta in un magazzino tracciato (industrie, città; da F2 stazioni, depositi, treni, pacchetti) e `GoodsCounters` registra prodotto, consumato, deperito, importato, esportato: giacenza = prodotto + importato − consumato − deperito − esportato. È l'invariante «merci». +- Interpretazioni delle formule della guida: ADR 0004. ## 7. Salvataggi -- Formato: intestazione `VFSV`, versione del formato, versione del gioco, hash dei dati, poi il corpo compresso con Brotli. -- Il corpo è scritto con `SaveWriter` (little endian, lunghezze esplicite, nessuna reflection) componente per componente; ogni componente ha la propria versione per le migrazioni. -- Il terreno è salvato per intero (comprimibile), non rigenerato dal seme: le versioni future del generatore non devono rompere i salvataggi. +- `SaveFile`: intestazione `VFSV` leggibile senza decomprimere, corpo Brotli scritto da `WorldSerializer` con `SaveWriter` (little endian, nessuna reflection). +- Definizioni salvate per id testuale e rimappate al caricamento; terreno salvato per intero. +- `StateHasher` = XxHash64 di `WorldSerializer.WriteDynamic` (stato senza terreno, impostazioni ed eventi; il terreno entra con il suo hash). Dettagli: ADR 0006. ## 8. Server *(pianificato, F3)* diff --git a/docs/STATE.md b/docs/STATE.md index 4407d45..674e81b 100644 --- a/docs/STATE.md +++ b/docs/STATE.md @@ -19,26 +19,39 @@ Aggiornato alla fine di ogni fase (guida, sezione 18). - Soluzione `ViaFerrea.sln` con Core, Protocol (net10.0 + net8.0), Server (Web SDK), Tools (`viaferrea-tools`), Tests. - `Directory.Build.props` con Nullable, ImplicitUsings, LangVersion latest, warning come errori, globalizzazione invariante, build deterministica, versione unica (0.1.0). - Script: `build.sh`, `build.ps1`, `test.sh`, `check-nuget.sh`, `publish-image.sh`. -- Documenti: GUIDA (copia della specifica v2), GDD, ARCHITECTURE, PROTOCOL (bozza), STATE, ADR 0001 (stack). -- Harness di test interno (`[Test]`, `Assert`, esecuzione parallela, filtri, `--skip-slow`) con i primi test reali su `Rng` (vettore di riferimento di xoshiro256**). -- Immagini di riferimento 01–05 in `reference/`. +- Documenti: GUIDA, GDD, ARCHITECTURE, PROTOCOL (bozza), STATE, ADR 0001. +- Harness di test interno (`[Test]`, `Assert`, esecuzione parallela, filtri, `--skip-slow`). + +### F1 — Economia headless +- Base: `Rng` (xoshiro256** con `Fork`), `Money` (centesimi, formati italiani), 20 identità tipizzate, `DMath` deterministica (ADR 0003), `XxHash64`, `Vec2`, `Calendar`/`GameClock`/`GameDate`. +- Dati: 12 file `data/*.json` (16 beni con ricambi e macchinari, 14 industrie, 13 veicoli, 4 ere, 5 livelli, 4 difficoltà; costruzione, manutenzione, IA, contratti, regioni) con 12 schemi in `data/schema/`; caricamento con source generator, validatore di schema interno, deserializzazione rigorosa, validazione semantica, hash dei dati (ADR 0002). `viaferrea-tools validate-data`. +- Mappa: generatore deterministico (rilievo con domain warping, mare, priority-flood, fiumi larghi 1–4 celle, laghi, copertura, giacimenti con riserva, città, porto e valico, 14 tipi di industria) e `viaferrea-tools genmap` con BMP di controllo (ADR 0005). +- Economia: città (domanda con elasticità, soddisfazione per categoria, servizi, crescita, migrazione, espansione), industrie (efficienza dalle coperture, fattore di profitto, condizione, esaurimento giacimenti, salari, crescita trimestrale delle industrie servite, chiusure, nascita per capacità mancante), hub, mercato con componente mondiale e shock, prezzi locali, tariffe, lavoratori in sede e a piedi, trasporto locale su strada, registro a partita doppia, prestiti e rating, difficoltà applicata (ADR 0004). +- Comandi: `TakeLoan`, `RepayLoan`, `SetIndustryPolicy`; gli altri tipi esistono e rispondono `NotImplemented`. +- Persistenza: `SaveFile` (intestazione + Brotli), `WorldSerializer` con rimappatura per id, `StateHasher` giornaliero (ADR 0006). +- `viaferrea-tools simulate` con KPI annuali in CSV (separatore `;`). +- 45 test: dati, determinismo, round-trip dei salvataggi, invarianti di merci e denaro, limiti dei prezzi, crescita e chiusura delle industrie, città, prestiti, collocazione e distanze della mappa, tempi di generazione. ## In corso -- F1 — Economia headless. +- F2 — Rete ferroviaria realistica headless. ## Prossimo passo -- F1.2: Clock, Money, identità tipizzate, DataLoader con source generator, validatore di schema e semantico, file `data/*.json` completi. +- F2.5: `TrackPlanner` (profilo a 25 m, due passate di pendenza, smussatura, classificazione delle opere, costi e tempi, vincoli per era), cantieri con squadre, classi di binario, usura del binario, ponti e gallerie con condizione; `viaferrea-tools profile`. ## Limiti noti - Le immagini di riferimento 06–09 (pannelli a tutto schermo e schermata di connessione) non sono state fornite: i pannelli seguiranno palette e componenti dell'immagine 05 finché non arrivano. - Godot non è eseguibile nell'ambiente cloud: il client potrà essere compilato con `Godot.NET.Sdk` ma non avviato né esportato qui. +- Senza vettori (F2) il mondo è in lento declino: le città perdono circa l'1 % di abitanti l'anno e le industrie lavorano a circa il 15–30 % (voluto, ADR 0004). +- La manutenzione degli impianti (sezione 11) arriva in F5: fino ad allora la condizione delle industrie resta 100. ## Misure di prestazione | Misura | Valore | Fase | |---|---|---| | Build Release da pulito | ~15 s | F0 | -| Test (5) | < 0,1 s | F0 | +| Generazione mappa 64 / 128 / 256 km | 0,8 / 1,4 / 5,6 s | F1 | +| `simulate --years 20` su 128 km (110 industrie, 26 città) | 1,7 s (+1,4 s di creazione) | F1 | +| Suite di test (45, parallela su 4 core) | ~10 s | F1 | diff --git a/docs/adr/0002-dati-e-validazione.md b/docs/adr/0002-dati-e-validazione.md new file mode 100644 index 0000000..b48017c --- /dev/null +++ b/docs/adr/0002-dati-e-validazione.md @@ -0,0 +1,24 @@ +# ADR 0002 — File dati, schemi e validazione + +Stato: accettato (F1). + +## Contesto + +La guida chiede che ogni parametro stia in `data/*.json`, con uno schema in `data/schema/`, validato all'avvio del server e da `viaferrea-tools validate-data`. Non si possono usare librerie NuGet (niente validatori JSON Schema esterni) e il caricamento deve usare System.Text.Json con source generator. + +## Decisione + +1. **Tre livelli di controllo**, tutti eseguiti da `GameData.Load`: + - *schema*: un validatore interno (`JsonSchemaValidator`) di un sottoinsieme di JSON Schema 2020-12 (type, properties, required, additionalProperties, items, min/maxItems, uniqueItems, enum, const, minimum/maximum, min/maxLength, pattern, `$ref` locali, anyOf/oneOf/allOf). Le parole chiave non supportate sono errori: uno schema non può sembrare più severo di quanto sia; + - *deserializzazione rigorosa*: `DataJsonContext` con `UnmappedMemberHandling.Disallow` e proprietà C# `required`. Le sezioni di `balance.json` hanno uno schema aperto (dizionari numerici), ma un refuso o un valore mancante bloccano comunque il caricamento; + - *semantica* (`DataValidator`): id univoci, riferimenti risolti (beni nelle ricette e nei carri, classi di binario tra `eras.json` e `construction.json`, componenti tra veicoli e `maintenance.json`, serbatoi di nomi), somme che devono valere 1, sequenze crescenti per ere e livelli, chiavi obbligatorie dei dizionari. +2. **Tutti gli errori insieme**: `DataValidationException` raccoglie l'elenco completo, così una correzione non ne nasconde un'altra. +3. **Hash dei dati**: XxHash64 del JSON minificato dei dodici file in ordine canonico, preceduti dal nome del file. Indipendente da spazi e a capo; viaggia nel `Welcome` del protocollo. +4. **Unità**: tutti gli importi nei dati sono in centesimi di lira; le capacità delle industrie sono unità del primo output al mese a efficienza 1. +5. **Gli schemi sono generati una volta** da uno script e poi mantenuti a mano come file JSON nel repository (sono documentazione e contratto per chi modifica i dati). +6. **`balance.json` cresce con le fasi**: le sezioni per sistemi futuri (borsa, manutenzione delle industrie) sono già presenti per non cambiare il formato a ogni fase. + +## Conseguenze + +- Aggiungere un parametro richiede di toccare tre posti (JSON, classe C#, eventuale regola semantica): è voluto, perché un parametro dimenticato non passa mai in silenzio. +- I test alterano i dati in memoria (`MemoryDataSource`) per verificare che ogni livello di controllo rifiuti gli errori tipici. diff --git a/docs/adr/0003-matematica-deterministica.md b/docs/adr/0003-matematica-deterministica.md new file mode 100644 index 0000000..9a3dcf3 --- /dev/null +++ b/docs/adr/0003-matematica-deterministica.md @@ -0,0 +1,20 @@ +# ADR 0003 — Matematica deterministica + +Stato: accettato (F1). + +## Contesto + +Il server è autorevole, ma il client calcola anteprime con le stesse classi di Core (profilo dei binari, stime) e il server le confronta («rifiuta se il risultato differisce»). I test di determinismo confrontano hash di stato tra esecuzioni; i salvataggi devono restare coerenti tra Windows (client con server locale) e Linux (Docker). In .NET le operazioni elementari IEEE 754 (+ − × ÷ e la radice quadrata) sono identiche su x64 e ARM64, ma `Math.Exp`, `Math.Log`, `Math.Pow`, `Math.Sin`, `Math.Cos`, `Math.Atan2` delegano alla libreria C della piattaforma, che può differire nell'ultimo bit. + +## Decisione + +1. Core implementa `DMath` con sole operazioni elementari: `Exp` (riduzione di Cody-Waite e serie di Taylor), `Log` (scomposizione in mantissa ed esponente e serie di atanh), `Pow` (potenze intere esatte per quadrature, altrimenti exp·log), `Sin`/`Cos` (riduzione con π/2 in tre parti e serie), `Atan` (due dimezzamenti dell'angolo e serie), `Atan2`, `Tanh`. +2. Nella simulazione sono vietate le funzioni trascendenti di `System.Math`; restano ammesse le funzioni esatte (`Sqrt`, `Floor`, `Round`, `Abs`, `Min`, `Max`, `Clamp`). +3. Precisione verificata dai test contro `System.Math`: errore relativo ≤ 2·10⁻¹⁴ su 20.000 argomenti casuali per funzione. +4. I campi di lavoro del generatore possono usare `float`: la conversione da `double` è deterministica. +5. Il parallelismo è ammesso solo per calcoli indipendenti per cella (rumore del rilievo, copertura del suolo, pendenze), il cui risultato non dipende dall'ordine. + +## Conseguenze + +- Costo trascurabile (le funzioni girano una volta al giorno per bene o per entità, mai nei cicli interni del tick). +- Il contratto vale anche per il client: le anteprime del profilo coincidono bit per bit con il server. diff --git a/docs/adr/0004-modello-economico.md b/docs/adr/0004-modello-economico.md new file mode 100644 index 0000000..beb33f3 --- /dev/null +++ b/docs/adr/0004-modello-economico.md @@ -0,0 +1,25 @@ +# ADR 0004 — Interpretazione del modello economico (F1) + +Stato: accettato (F1). + +## Contesto + +La guida (6.3) fissa le formule ma lascia aperti alcuni punti: come si somma la componente mondiale W(t) a domanda e offerta, cosa sono domanda e offerta locali di un nodo, chi paga cosa, come vive il territorio prima che arrivino i treni, quando un'industria «resta insoddisfatta». + +## Decisione + +1. **Componente mondiale.** Il resto del mondo scambia ogni giorno con la regione un volume V = max(baseline·giorni, quota·(D + S)/2) al prezzo mondiale Pw = Pb·(1 + A·sin(2πt/T) + shock). Entra nel rapporto come domanda V·(Pw/Pg)^ε e offerta V·(Pg/Pw)^ε: a Pg = Pw è neutra, sopra Pw spinge il prezzo giù e viceversa. Così la formula della guida `Pg' = clamp(Pg·(1 + k·(D/S − 1)))` resta intatta e il prezzo torna verso il ciclo mondiale invece di divergere. Il rapporto D/S è limitato a [0,2; 5]. Gli shock sono per bene, decadono esponenzialmente e la volatilità della difficoltà moltiplica ampiezza e shock. +2. **Domanda e offerta.** D = consumo desiderato dalle città (con elasticità al prezzo, limitata a ×0,5…×1,5) + input che le industrie userebbero al loro potenziale di lavoro; S = produzione effettiva. Il trasporto quindi conta: senza consegne gli output dei trasformatori scarseggiano e i loro prezzi salgono. +3. **Prezzo locale.** Per un nodo: Dl = domanda giornaliera × giorni di scorta desiderati, Sl = giacenza. Un produttore con magazzino pieno vende a ~0,65·Pg, un consumatore a secco paga ~1,35·Pg (entro ±40 %). +4. **Contabilità a partita doppia.** Ogni movimento è un trasferimento tra conti (compagnie, industrie, conto Esterno). Il ritiro di merce paga il produttore al prezzo locale d'origine; la consegna a un'industria la addebita al prezzo locale di destinazione; le famiglie e il mercato mondiale sono il conto Esterno. La somma dei saldi è sempre zero. Le scorte iniziali e quelle create dai test sono contabilizzate come prodotte. +5. **Lavoro in sede.** Il 30 % dei posti di ogni industria è coperto da chi vive in sede (villaggio operaio): l'efficienza di un'industria isolata parte da circa 0,3 e cresce solo con i pendolari. È il punto di partenza dell'accettazione F2 («dall'acciaieria sotto il 40 %…»). +6. **Trasporto locale su strada.** Produttori, consumatori e hub entro 3 km si scambiano piccole quantità (25 % della giacenza, al massimo 6 unità al giorno per bene), senza vettore. I lavoratori vanno a piedi entro 1,5 km dal bordo della città. Tiene vivo il territorio senza rendere superflua la ferrovia; si spegne da `balance.json`. +7. **Crescita solo per le industrie servite.** Il punteggio trimestrale si calcola sempre, ma livello, regressione e chiusura si applicano solo alle industrie `Served` (con una stazione di un vettore nel bacino, da F2). Senza questa regola, all'inizio della partita quasi tutte le industrie chiuderebbero entro due anni perché nessuno le serve ancora. +8. **Domanda insoddisfatta = capacità mancante.** Un bene è «insoddisfatto» quando la domanda media supera di 1,25 volte la capacità installata (non la produzione effettiva): nascono nuove industrie dove manca capacità, non dove manca il trasporto. Al massimo due nascite all'anno. +9. **Servizi cittadini.** I «servizi» di una città sono le categorie di consumo (alimentari, merci, combustibili, edilizia) con soddisfazione ≥ 0,5: il personale qualificato esiste solo nelle città grandi e ben rifornite. +10. **Distanze dalle città** si misurano dal bordo dell'abitato (distanza dal centro meno il raggio), sia nella generazione sia nel gioco. + +## Conseguenze + +- Un mondo senza vettori è stabile ma in lento declino (circa −1 % di popolazione all'anno): è lo spazio di crescita per giocatore e IA. +- Le regole 5–8 sono parametri in `balance.json` e si possono ribilanciare con `simulate` senza toccare il codice. diff --git a/docs/adr/0005-generazione-mappa.md b/docs/adr/0005-generazione-mappa.md new file mode 100644 index 0000000..362c99b --- /dev/null +++ b/docs/adr/0005-generazione-mappa.md @@ -0,0 +1,23 @@ +# ADR 0005 — Generazione della mappa + +Stato: accettato (F1). + +## Contesto + +La guida (6.2) descrive gli ingredienti (rumore di valore a 5 ottave, domain warping, mare collegato al bordo, fiumi con larghezza crescente, laghi, foreste, roccia, paludi, giacimenti, città, industrie, porto e valico) ma non la forma del rilievo né l'algoritmo idrologico. + +## Decisione + +1. **Profilo costa-entroterra.** Un lato della mappa (scelto dal seme) è il mare. La quota cresce con la distanza normalizzata g dal mare come `gradiente·g²` (pianura costiera ampia, salita interna), più rumore di base con ampiezza crescente verso l'interno, più creste (rumore a creste, attivo solo oltre `mountainStart` con raccordo smoothstep), più rumore costiero e microrilievo. Una fascia del 3 % lungo il bordo è spinta sotto zero per garantire il mare. +2. **Idrologia con priority-flood** (Barnes et al.) con incremento epsilon a partire da mare e bordi: ogni cella ha un percorso di drenaggio. L'accumulo di flusso in ordine inverso di estrazione dà i fiumi (soglia in km² di bacino), la larghezza 1–4 celle per soglie ×1, ×4, ×16, ×64; la superficie dei fiumi scende sempre verso valle; le valli si abbassano entro qualche cella. Le conche profonde diventano laghi solo sotto il 60° percentile di quota (in montagna si colmano: niente laghi sulle creste). +3. **Il «30° percentile» della guida** è la quota minima a monte di una sorgente: un fiume nasce solo se il suo bacino raggiunge quella quota. +4. **Copertura** per cella da percentile di quota (istogramma esatto in decimetri) e pendenza: roccia sopra il 70° percentile e ripida, montagna sopra il 90°, bosco su pendii medi (e chiazze in pianura) secondo un rumore dedicato, palude in pianura bassa vicino ai fiumi, collina per pendenza o quota, campi attorno a città e fattorie. +5. **Città** su pianura entro 3 km dall'acqua, scelte per punteggio (vicinanza all'acqua, pianezza, caso) con distanza minima di 6 km e lontane dai giacimenti; popolazione di Zipf (la più grande 11.000–18.000). Nomi dal serbatoio della regione. +6. **Industrie**: una per giacimento (se l'era lo consente), poi le altre ripartite tra fattorie, taglialegna, trasformazione e manifattura secondo `map.industries.shares`; ogni collocazione rispetta impronta, pendenza, distanze dalle città e, per la trasformazione, la presenza di produttori di ogni input entro 12 km. +7. **Hub**: il porto nel punto costiero con più abitanti vicini, il valico nel punto più basso dei bordi di terra. Nomi dal lato della mappa (Porto di Levante, Valico del Nord). +8. Il terreno generato si salva per intero: le versioni future del generatore non cambiano le partite esistenti. + +## Conseguenze + +- 128 km in circa 1,4 s su 4 core (accettazione: < 3 s); 256 km in circa 6 s, dominati dal priority-flood. +- L'aspetto si regola dai parametri di `balance.json` (`map.*`); `genmap` produce un BMP di controllo. diff --git a/docs/adr/0006-salvataggi.md b/docs/adr/0006-salvataggi.md new file mode 100644 index 0000000..6dddcdd --- /dev/null +++ b/docs/adr/0006-salvataggi.md @@ -0,0 +1,20 @@ +# ADR 0006 — Formato dei salvataggi e hash di stato + +Stato: accettato (F1). + +## Contesto + +La guida chiede snapshot binari compressi con Brotli, portabili tra Windows e Linux, un hash di stato giornaliero e la compatibilità dei salvataggi tra versioni (migrazioni, F7). + +## Decisione + +1. **File**: `VFSV`, versione del formato (u16), intestazione leggibile senza decomprimere (versione del gioco, hash dei dati, hash di stato, tick, data, nome della compagnia, seme, dimensione, difficoltà, lunghezza del corpo), poi il corpo compresso con Brotli. Scrittura atomica (file temporaneo e rinomina). +2. **Corpo** scritto a mano con `SaveWriter` (little endian, lunghezze esplicite): versione del corpo, dizionario dei beni, impostazioni (difficoltà effettiva completa), terreno intero, stato dinamico, ultimo hash, eventi recenti. +3. **Riferimenti per id**: tipi di industria e beni sono salvati per id testuale e rimappati al caricamento; giacenze per ricetta come coppie (bene, quantità). Aggiungere o riordinare definizioni non rompe i salvataggi; rimuovere un tipo di industria usato sì (errore esplicito). +4. **Hash di stato** = XxHash64 dello stato dinamico (tutto tranne terreno, impostazioni ed eventi; il terreno entra con il proprio hash, ricalcolato solo quando cambia un'impronta). Calcolato dal sistema Hash nel primo tick di ogni giorno. +5. I dati derivati e le cache dei sistemi (vicini del trasporto locale, buffer di lavoro) non si salvano: si ricostruiscono identici. + +## Conseguenze + +- Caricare e riprendere dà lo stesso hash e lo stesso futuro (test `SaveLoadRoundTripPreservesFuture`), e due salvataggi dello stesso stato sono identici byte per byte. +- Ogni nuovo campo di stato va aggiunto in scrittura, lettura e nel test di round-trip: il test fallisce subito se uno dei tre manca. diff --git a/src/ViaFerrea.Core/Commands/GameCommand.cs b/src/ViaFerrea.Core/Commands/GameCommand.cs new file mode 100644 index 0000000..9f35777 --- /dev/null +++ b/src/ViaFerrea.Core/Commands/GameCommand.cs @@ -0,0 +1,113 @@ +using ViaFerrea.Core.Common; + +namespace ViaFerrea.Core.Commands; + +/// +/// Tipi di comando con codici stabili: coincidono con Command.type del protocollo e non +/// cambiano mai (PROTOCOL.md). +/// +public enum CommandType : ushort +{ + BuildTrack = 1, + RenewTrack = 2, + UpgradeTrack = 3, + Demolish = 4, + BuildStation = 5, + BuildDepot = 6, + PlaceSignal = 7, + BuyVehicle = 8, + SellVehicle = 9, + ComposeTrain = 10, + CreateLine = 11, + EditLine = 12, + AssignTrain = 13, + SendToDepot = 14, + SetReserve = 15, + SetMaintenancePolicy = 16, + ScheduleService = 17, + OrderParts = 18, + TakeLoan = 19, + RepayLoan = 20, + AcceptAgreement = 21, + RejectAgreement = 22, + BuyGoods = 23, + SellGoods = 24, + BuyIndustry = 25, + SetIndustryPolicy = 26, + OverhaulIndustry = 27, + UpgradeIndustry = 28, + Ipo = 29, + BuyShares = 30, + SellShares = 31, + PayDividend = 32, + LaunchBid = 33, + RespondBid = 34, + BuyConcession = 35, + AcceptContract = 36, + FundResearch = 37, + DelegateRegion = 38, +} + +/// Codici di errore stabili degli esiti dei comandi. +public enum CommandError : ushort +{ + None = 0, + NotImplemented = 1, + UnknownCompany = 2, + InvalidArgument = 3, + InsufficientFunds = 4, + CreditLimit = 5, + NotFound = 6, + NotAllowed = 7, + TierLocked = 8, + Bankrupt = 9, + InvalidTrack = 10, + Blocked = 11, + PreviewMismatch = 12, + EraLocked = 13, +} + +/// Comando di gioco: unico modo di cambiare il mondo dall'esterno, per giocatori e IA. +public abstract record GameCommand +{ + /// Compagnia che emette il comando (impostata dal server in base alla sessione). + public CompanyId Issuer { get; init; } + + /// Numero di sequenza del client, rimandato nell'esito. + public uint Seq { get; init; } + + public abstract CommandType Type { get; } +} + +/// Esito di un comando. +public sealed record CommandResult(CompanyId Issuer, uint Seq, CommandType Type, CommandError Error, string Message, long Tick) +{ + public bool Ok => Error == CommandError.None; +} + +/// Richiede un prestito entro il fido disponibile. +public sealed record TakeLoanCommand(Money Amount) : GameCommand +{ + public override CommandType Type => CommandType.TakeLoan; +} + +/// Rimborsa (in tutto o in parte) un prestito. +public sealed record RepayLoanCommand(LoanId Loan, Money Amount) : GameCommand +{ + public override CommandType Type => CommandType.RepayLoan; +} + +/// Imposta il budget di manutenzione di un'industria posseduta. +public sealed record SetIndustryPolicyCommand(IndustryId Industry, Economy.IndustryBudget Budget) : GameCommand +{ + public override CommandType Type => CommandType.SetIndustryPolicy; +} + +/// +/// Comando non ancora implementato nella fase corrente: viaggia nel protocollo e riceve +/// l'esito NotImplemented. Permette al protocollo di essere completo fin da subito. +/// +public sealed record PendingCommand(CommandType Kind, byte[] Payload) : GameCommand +{ + public override CommandType Type => Kind; +} diff --git a/src/ViaFerrea.Core/Common/DMath.cs b/src/ViaFerrea.Core/Common/DMath.cs new file mode 100644 index 0000000..91df8d5 --- /dev/null +++ b/src/ViaFerrea.Core/Common/DMath.cs @@ -0,0 +1,274 @@ +namespace ViaFerrea.Core.Common; + +/// +/// Funzioni matematiche deterministiche per la simulazione (ADR 0003). +/// Usano solo operazioni IEEE 754 elementari (+ − × ÷ e radice quadrata, che lo standard +/// impone correttamente arrotondate), quindi danno lo stesso risultato bit per bit su ogni +/// piattaforma, a differenza di Math.Exp/Log/Pow/Sin che delegano alla libreria C. +/// Precisione: errore relativo dell'ordine di 1e-15, più che sufficiente per il gioco. +/// +public static class DMath +{ + public const double Pi = 3.14159265358979323846; + public const double TwoPi = 6.28318530717958647692; + public const double HalfPi = 1.57079632679489661923; + public const double E = 2.71828182845904523536; + + private const double Ln2Hi = 6.93147180369123816490e-01; // ln2 con gli ultimi bit a zero + private const double Ln2Lo = 1.90821492927058770002e-10; + private const double InvLn2 = 1.44269504088896338700e+00; + private const double Sqrt2 = 1.41421356237309504880; + + // π/2 diviso in tre parti (fdlibm) per la riduzione dell'argomento di sin e cos. + private const double Pio2_1 = 1.57079632673412561417e+00; + private const double Pio2_2 = 6.07710050630396597660e-11; + private const double Pio2_3 = 2.02226624871116645580e-21; + private const double InvPio2 = 6.36619772367581382433e-01; + + /// Radice quadrata (IEEE la garantisce correttamente arrotondata: già deterministica). + public static double Sqrt(double x) => Math.Sqrt(x); + + /// e^x. + public static double Exp(double x) + { + if (double.IsNaN(x)) return x; + if (x > 709.782712893383973096) return double.PositiveInfinity; + if (x < -745.133219101941108420) return 0.0; + if (x == 0) return 1.0; + + // x = k·ln2 + r, |r| ≤ ln2/2 + double kd = Math.Round(x * InvLn2, MidpointRounding.ToEven); + int k = (int)kd; + double r = (x - kd * Ln2Hi) - kd * Ln2Lo; + + // Serie di Taylor fino a r^14/14! (|r| ≤ 0,347: resto < 1e-18), forma di Horner. + double p = 1.0 + r * (1.0 + r * (1.0 / 2 + r * (1.0 / 6 + r * (1.0 / 24 + r * (1.0 / 120 + + r * (1.0 / 720 + r * (1.0 / 5040 + r * (1.0 / 40320 + r * (1.0 / 362880 + + r * (1.0 / 3628800 + r * (1.0 / 39916800 + r * (1.0 / 479001600 + + r * (1.0 / 6227020800 + r * (1.0 / 87178291200)))))))))))))); + return ScaleB(p, k); + } + + /// Logaritmo naturale. + public static double Log(double x) + { + if (double.IsNaN(x) || x < 0) return double.NaN; + if (x == 0) return double.NegativeInfinity; + if (double.IsPositiveInfinity(x)) return x; + if (x == 1) return 0.0; + + int e = 0; + long bits = BitConverter.DoubleToInt64Bits(x); + int exp = (int)((bits >> 52) & 0x7FF); + if (exp == 0) + { + // subnormale: porta nel campo normale + x *= 18014398509481984.0; // 2^54 + e = -54; + bits = BitConverter.DoubleToInt64Bits(x); + exp = (int)((bits >> 52) & 0x7FF); + } + e += exp - 1023; + double m = BitConverter.Int64BitsToDouble((bits & 0x000FFFFFFFFFFFFFL) | 0x3FF0000000000000L); // [1, 2) + if (m > Sqrt2) + { + m *= 0.5; + e++; + } + + // log(m) = 2·atanh(f) con f = (m−1)/(m+1), |f| ≤ 0,1716 + double f = (m - 1.0) / (m + 1.0); + double s = f * f; + double series = 1.0 + s * (1.0 / 3 + s * (1.0 / 5 + s * (1.0 / 7 + s * (1.0 / 9 + s * (1.0 / 11 + + s * (1.0 / 13 + s * (1.0 / 15 + s * (1.0 / 17 + s * (1.0 / 19 + s * (1.0 / 21)))))))))); + double logM = 2.0 * f * series; + return e * Ln2Hi + (e * Ln2Lo + logM); + } + + /// Logaritmo in base 10. + public static double Log10(double x) => Log(x) * 0.43429448190325182765; + + /// Logaritmo in base 2. + public static double Log2(double x) => Log(x) * InvLn2; + + /// x^y. + public static double Pow(double x, double y) + { + if (y == 0) return 1.0; + if (double.IsNaN(x) || double.IsNaN(y)) return double.NaN; + if (x == 1) return 1.0; + if (y == 1) return x; + if (y == 2) return x * x; + if (y == 0.5 && x >= 0) return Math.Sqrt(x); + if (y == -1) return 1.0 / x; + + bool yIsInteger = Math.Floor(y) == y && Math.Abs(y) < 9.007199254740992e15; + if (x == 0) + { + if (y > 0) return 0.0; + return double.PositiveInfinity; + } + if (x < 0) + { + if (!yIsInteger) return double.NaN; + double r = Exp(y * Log(-x)); + bool odd = Math.Abs(y % 2.0) == 1.0; + return odd ? -r : r; + } + if (yIsInteger && Math.Abs(y) <= 64) + { + // potenza intera esatta per quadrature successive + long n = (long)Math.Abs(y); + double result = 1.0, b = x; + while (n > 0) + { + if ((n & 1) != 0) result *= b; + b *= b; + n >>= 1; + } + return y < 0 ? 1.0 / result : result; + } + return Exp(y * Log(x)); + } + + /// Seno. + public static double Sin(double x) + { + if (double.IsNaN(x) || double.IsInfinity(x)) return double.NaN; + double r = Reduce(x, out int q); + return (q & 3) switch + { + 0 => KernelSin(r), + 1 => KernelCos(r), + 2 => -KernelSin(r), + _ => -KernelCos(r), + }; + } + + /// Coseno. + public static double Cos(double x) + { + if (double.IsNaN(x) || double.IsInfinity(x)) return double.NaN; + double r = Reduce(x, out int q); + return (q & 3) switch + { + 0 => KernelCos(r), + 1 => -KernelSin(r), + 2 => -KernelCos(r), + _ => KernelSin(r), + }; + } + + /// Tangente. + public static double Tan(double x) => Sin(x) / Cos(x); + + /// Arcotangente in (−π/2, π/2). + public static double Atan(double x) + { + if (double.IsNaN(x)) return x; + if (double.IsPositiveInfinity(x)) return HalfPi; + if (double.IsNegativeInfinity(x)) return -HalfPi; + bool negative = x < 0; + double a = negative ? -x : x; + bool inverted = a > 1.0; + if (inverted) a = 1.0 / a; + // due dimezzamenti dell'angolo: atan(a) = 2·atan(a / (1 + √(1 + a²))) → |a| ≤ tan(π/16) + a = a / (1.0 + Math.Sqrt(1.0 + a * a)); + a = a / (1.0 + Math.Sqrt(1.0 + a * a)); + double s = a * a; + double series = 1.0 - s * (1.0 / 3 - s * (1.0 / 5 - s * (1.0 / 7 - s * (1.0 / 9 - s * (1.0 / 11 + - s * (1.0 / 13 - s * (1.0 / 15 - s * (1.0 / 17 - s * (1.0 / 19 - s * (1.0 / 21 + - s * (1.0 / 23 - s * (1.0 / 25)))))))))))); + double result = 4.0 * a * series; + if (inverted) result = HalfPi - result; + return negative ? -result : result; + } + + /// Arcotangente di y/x nel quadrante corretto, in (−π, π]. + public static double Atan2(double y, double x) + { + if (double.IsNaN(x) || double.IsNaN(y)) return double.NaN; + if (x == 0) + { + if (y > 0) return HalfPi; + if (y < 0) return -HalfPi; + return 0.0; + } + double a = Atan(y / x); + if (x > 0) return a; + return y >= 0 ? a + Pi : a - Pi; + } + + /// Tangente iperbolica. + public static double Tanh(double x) + { + if (x > 20) return 1.0; + if (x < -20) return -1.0; + double e2 = Exp(2 * x); + return (e2 - 1) / (e2 + 1); + } + + /// Limita v all'intervallo [min, max]. + public static double Clamp(double v, double min, double max) => v < min ? min : v > max ? max : v; + + /// Interpolazione lineare. + public static double Lerp(double a, double b, double t) => a + (b - a) * t; + + /// Interpolazione con curva smoothstep (3t² − 2t³). + public static double SmoothStep(double t) => t * t * (3 - 2 * t); + + // x · 2^k gestendo anche risultati subnormali. + private static double ScaleB(double x, int k) + { + if (k > 1023) + { + x *= BitConverter.Int64BitsToDouble(0x7FE0000000000000L); // 2^1023 + k -= 1023; + if (k > 1023) return double.PositiveInfinity; + } + else if (k < -1022) + { + x *= BitConverter.Int64BitsToDouble(0x0010000000000000L) * 9007199254740992.0; // 2^-1022 · 2^53 + k += 1022 - 53; + if (k < -1022) + { + x *= BitConverter.Int64BitsToDouble(0x0010000000000000L) * 9007199254740992.0; + k += 1022 - 53; + if (k < -1022) return 0.0; + } + } + return x * BitConverter.Int64BitsToDouble((long)(k + 1023) << 52); + } + + // Riduce x in [−π/4, π/4] restituendo il quadrante. Esatto per |x| < 2^19·π/2 circa; + // oltre perde precisione ma resta deterministico. + private static double Reduce(double x, out int quadrant) + { + if (Math.Abs(x) <= 0.785398163397448279) + { + quadrant = 0; + return x; + } + double n = Math.Round(x * InvPio2, MidpointRounding.ToEven); + quadrant = (int)(long)n; + return ((x - n * Pio2_1) - n * Pio2_2) - n * Pio2_3; + } + + // Seno su [−π/4, π/4]: Taylor fino a x^19. + private static double KernelSin(double x) + { + double s = x * x; + return x * (1.0 - s * (1.0 / 6 - s * (1.0 / 120 - s * (1.0 / 5040 - s * (1.0 / 362880 + - s * (1.0 / 39916800 - s * (1.0 / 6227020800 - s * (1.0 / 1307674368000 + - s * (1.0 / 355687428096000 - s * (1.0 / 121645100408832000)))))))))); + } + + // Coseno su [−π/4, π/4]: Taylor fino a x^20. + private static double KernelCos(double x) + { + double s = x * x; + return 1.0 - s * (1.0 / 2 - s * (1.0 / 24 - s * (1.0 / 720 - s * (1.0 / 40320 - s * (1.0 / 3628800 + - s * (1.0 / 479001600 - s * (1.0 / 87178291200 - s * (1.0 / 20922789888000 + - s * (1.0 / 6402373705728000 - s * (1.0 / 2432902008176640000)))))))))); + } +} diff --git a/src/ViaFerrea.Core/Common/Ids.cs b/src/ViaFerrea.Core/Common/Ids.cs new file mode 100644 index 0000000..f69d834 --- /dev/null +++ b/src/ViaFerrea.Core/Common/Ids.cs @@ -0,0 +1,184 @@ +namespace ViaFerrea.Core.Common; + +// Identità tipizzate: impediscono di confondere gli id di entità diverse. +// Il valore −1 (None) indica l'assenza di riferimento. Generato da uno script: tutte le identità hanno la stessa forma. + +/// Identità tipizzata: stazione. +public readonly record struct StationId(int Value) : IComparable +{ + public static readonly StationId None = new(-1); + public bool IsValid => Value >= 0; + public int CompareTo(StationId other) => Value.CompareTo(other.Value); + public override string ToString() => IsValid ? $"Station#{Value}" : "Station#none"; +} + +/// Identità tipizzata: città. +public readonly record struct TownId(int Value) : IComparable +{ + public static readonly TownId None = new(-1); + public bool IsValid => Value >= 0; + public int CompareTo(TownId other) => Value.CompareTo(other.Value); + public override string ToString() => IsValid ? $"Town#{Value}" : "Town#none"; +} + +/// Identità tipizzata: industria. +public readonly record struct IndustryId(int Value) : IComparable +{ + public static readonly IndustryId None = new(-1); + public bool IsValid => Value >= 0; + public int CompareTo(IndustryId other) => Value.CompareTo(other.Value); + public override string ToString() => IsValid ? $"Industry#{Value}" : "Industry#none"; +} + +/// Identità tipizzata: hub (porto o valico). +public readonly record struct HubId(int Value) : IComparable +{ + public static readonly HubId None = new(-1); + public bool IsValid => Value >= 0; + public int CompareTo(HubId other) => Value.CompareTo(other.Value); + public override string ToString() => IsValid ? $"Hub#{Value}" : "Hub#none"; +} + +/// Identità tipizzata: nodo del grafo dei binari. +public readonly record struct NodeId(int Value) : IComparable +{ + public static readonly NodeId None = new(-1); + public bool IsValid => Value >= 0; + public int CompareTo(NodeId other) => Value.CompareTo(other.Value); + public override string ToString() => IsValid ? $"Node#{Value}" : "Node#none"; +} + +/// Identità tipizzata: arco del grafo dei binari. +public readonly record struct EdgeId(int Value) : IComparable +{ + public static readonly EdgeId None = new(-1); + public bool IsValid => Value >= 0; + public int CompareTo(EdgeId other) => Value.CompareTo(other.Value); + public override string ToString() => IsValid ? $"Edge#{Value}" : "Edge#none"; +} + +/// Identità tipizzata: segnale. +public readonly record struct SignalId(int Value) : IComparable +{ + public static readonly SignalId None = new(-1); + public bool IsValid => Value >= 0; + public int CompareTo(SignalId other) => Value.CompareTo(other.Value); + public override string ToString() => IsValid ? $"Signal#{Value}" : "Signal#none"; +} + +/// Identità tipizzata: treno. +public readonly record struct TrainId(int Value) : IComparable +{ + public static readonly TrainId None = new(-1); + public bool IsValid => Value >= 0; + public int CompareTo(TrainId other) => Value.CompareTo(other.Value); + public override string ToString() => IsValid ? $"Train#{Value}" : "Train#none"; +} + +/// Identità tipizzata: veicolo (locomotiva, carro o carrozza). +public readonly record struct VehicleId(int Value) : IComparable +{ + public static readonly VehicleId None = new(-1); + public bool IsValid => Value >= 0; + public int CompareTo(VehicleId other) => Value.CompareTo(other.Value); + public override string ToString() => IsValid ? $"Vehicle#{Value}" : "Vehicle#none"; +} + +/// Identità tipizzata: linea. +public readonly record struct LineId(int Value) : IComparable +{ + public static readonly LineId None = new(-1); + public bool IsValid => Value >= 0; + public int CompareTo(LineId other) => Value.CompareTo(other.Value); + public override string ToString() => IsValid ? $"Line#{Value}" : "Line#none"; +} + +/// Identità tipizzata: compagnia. +public readonly record struct CompanyId(int Value) : IComparable +{ + public static readonly CompanyId None = new(-1); + public bool IsValid => Value >= 0; + public int CompareTo(CompanyId other) => Value.CompareTo(other.Value); + public override string ToString() => IsValid ? $"Company#{Value}" : "Company#none"; +} + +/// Identità tipizzata: pacchetto di merci o passeggeri. +public readonly record struct PacketId(int Value) : IComparable +{ + public static readonly PacketId None = new(-1); + public bool IsValid => Value >= 0; + public int CompareTo(PacketId other) => Value.CompareTo(other.Value); + public override string ToString() => IsValid ? $"Packet#{Value}" : "Packet#none"; +} + +/// Identità tipizzata: contratto di pendolarismo o bando. +public readonly record struct ContractId(int Value) : IComparable +{ + public static readonly ContractId None = new(-1); + public bool IsValid => Value >= 0; + public int CompareTo(ContractId other) => Value.CompareTo(other.Value); + public override string ToString() => IsValid ? $"Contract#{Value}" : "Contract#none"; +} + +/// Identità tipizzata: deposito e officina della compagnia. +public readonly record struct DepotId(int Value) : IComparable +{ + public static readonly DepotId None = new(-1); + public bool IsValid => Value >= 0; + public int CompareTo(DepotId other) => Value.CompareTo(other.Value); + public override string ToString() => IsValid ? $"Depot#{Value}" : "Depot#none"; +} + +/// Identità tipizzata: regione. +public readonly record struct RegionId(int Value) : IComparable +{ + public static readonly RegionId None = new(-1); + public bool IsValid => Value >= 0; + public int CompareTo(RegionId other) => Value.CompareTo(other.Value); + public override string ToString() => IsValid ? $"Region#{Value}" : "Region#none"; +} + +/// Identità tipizzata: giacimento (carbone, ferro, pietra, petrolio). +public readonly record struct ResourceSiteId(int Value) : IComparable +{ + public static readonly ResourceSiteId None = new(-1); + public bool IsValid => Value >= 0; + public int CompareTo(ResourceSiteId other) => Value.CompareTo(other.Value); + public override string ToString() => IsValid ? $"ResourceSite#{Value}" : "ResourceSite#none"; +} + +/// Identità tipizzata: prestito. +public readonly record struct LoanId(int Value) : IComparable +{ + public static readonly LoanId None = new(-1); + public bool IsValid => Value >= 0; + public int CompareTo(LoanId other) => Value.CompareTo(other.Value); + public override string ToString() => IsValid ? $"Loan#{Value}" : "Loan#none"; +} + +/// Identità tipizzata: convenzione di pendolarismo. +public readonly record struct AgreementId(int Value) : IComparable +{ + public static readonly AgreementId None = new(-1); + public bool IsValid => Value >= 0; + public int CompareTo(AgreementId other) => Value.CompareTo(other.Value); + public override string ToString() => IsValid ? $"Agreement#{Value}" : "Agreement#none"; +} + +/// Identità tipizzata: opera di costruzione (rilevato, trincea, ponte, galleria). +public readonly record struct WorkId(int Value) : IComparable +{ + public static readonly WorkId None = new(-1); + public bool IsValid => Value >= 0; + public int CompareTo(WorkId other) => Value.CompareTo(other.Value); + public override string ToString() => IsValid ? $"Work#{Value}" : "Work#none"; +} + +/// Identità tipizzata: offerta pubblica di acquisto. +public readonly record struct BidId(int Value) : IComparable +{ + public static readonly BidId None = new(-1); + public bool IsValid => Value >= 0; + public int CompareTo(BidId other) => Value.CompareTo(other.Value); + public override string ToString() => IsValid ? $"Bid#{Value}" : "Bid#none"; +} diff --git a/src/ViaFerrea.Core/Common/Money.cs b/src/ViaFerrea.Core/Common/Money.cs new file mode 100644 index 0000000..6d902cb --- /dev/null +++ b/src/ViaFerrea.Core/Common/Money.cs @@ -0,0 +1,119 @@ +using System.Globalization; +using System.Text; + +namespace ViaFerrea.Core.Common; + +/// +/// Importo in centesimi di lira (₤). Tutta la contabilità della simulazione usa interi per +/// essere esatta e deterministica; i reali compaiono solo nei calcoli intermedi e si +/// arrotondano con . +/// +public readonly record struct Money(long Cents) : IComparable +{ + public static readonly Money Zero = new(0); + + /// Importo da lire con decimali (arrotondamento al centesimo, metà lontano da zero). + public static Money FromLire(decimal lire) => new((long)decimal.Round(lire * 100m, MidpointRounding.AwayFromZero)); + + /// Importo da lire intere. + public static Money FromLire(long lire) => new(checked(lire * 100)); + + /// Arrotonda un importo reale in centesimi (metà al pari, come IEEE). + public static Money FromCentsRounded(double cents) + { + if (double.IsNaN(cents)) throw new ArgumentException("Importo NaN", nameof(cents)); + return new((long)Math.Round(cents, MidpointRounding.ToEven)); + } + + /// Valore in lire come reale (solo per visualizzazione e stime). + public double Lire => Cents / 100.0; + + public bool IsNegative => Cents < 0; + public bool IsPositive => Cents > 0; + + public static Money operator +(Money a, Money b) => new(checked(a.Cents + b.Cents)); + public static Money operator -(Money a, Money b) => new(checked(a.Cents - b.Cents)); + public static Money operator -(Money a) => new(checked(-a.Cents)); + public static Money operator *(Money a, long k) => new(checked(a.Cents * k)); + public static Money operator *(long k, Money a) => new(checked(a.Cents * k)); + /// Moltiplica per un fattore reale arrotondando al centesimo. + public static Money operator *(Money a, double k) => FromCentsRounded(a.Cents * k); + public static Money operator *(double k, Money a) => FromCentsRounded(a.Cents * k); + public static bool operator <(Money a, Money b) => a.Cents < b.Cents; + public static bool operator >(Money a, Money b) => a.Cents > b.Cents; + public static bool operator <=(Money a, Money b) => a.Cents <= b.Cents; + public static bool operator >=(Money a, Money b) => a.Cents >= b.Cents; + + public static Money Min(Money a, Money b) => a.Cents <= b.Cents ? a : b; + public static Money Max(Money a, Money b) => a.Cents >= b.Cents ? a : b; + + public int CompareTo(Money other) => Cents.CompareTo(other.Cents); + + /// Formato predefinito: lire intere all'italiana, per esempio «₤ 1.284.500». + public override string ToString() => ToString("it"); + + /// + /// Formati: «it» lire intere («₤ 1.284.500»), «it2» con centesimi («₤ 1.284.500,25»), + /// «short» compatto («₤ 3,91 mln», «₤ 48.200»), «cents» numero grezzo. + /// La formattazione è fatta a mano per non dipendere dalla globalizzazione. + /// + public string ToString(string format) => format switch + { + "it" => FormatLire(Cents, decimals: false), + "it2" => FormatLire(Cents, decimals: true), + "short" => FormatShort(Cents), + "cents" => Cents.ToString(CultureInfo.InvariantCulture), + _ => throw new FormatException($"Formato Money sconosciuto: {format}"), + }; + + private static string FormatLire(long cents, bool decimals) + { + bool negative = cents < 0; + ulong abs = negative ? (ulong)(-(cents + 1)) + 1UL : (ulong)cents; + ulong lire = abs / 100; + ulong rest = abs % 100; + if (!decimals && rest >= 50) lire++; + var sb = new StringBuilder(); + if (negative && (lire > 0 || (decimals && rest > 0))) sb.Append('−'); + sb.Append("₤ "); + sb.Append(GroupThousands(lire)); + if (decimals) + { + sb.Append(','); + sb.Append(rest.ToString("00", CultureInfo.InvariantCulture)); + } + return sb.ToString(); + } + + private static string FormatShort(long cents) + { + double lire = cents / 100.0; + double abs = Math.Abs(lire); + string sign = lire < 0 ? "−" : ""; + if (abs >= 1_000_000_000) return $"{sign}₤ {Decimal2(abs / 1_000_000_000)} mld"; + if (abs >= 1_000_000) return $"{sign}₤ {Decimal2(abs / 1_000_000)} mln"; + return FormatLire(cents, decimals: false); + } + + private static string Decimal2(double v) + { + long hundredths = (long)Math.Round(v * 100, MidpointRounding.AwayFromZero); + return $"{GroupThousands((ulong)(hundredths / 100))},{(hundredths % 100).ToString("00", CultureInfo.InvariantCulture)}"; + } + + /// Raggruppa le migliaia con il punto. + public static string GroupThousands(ulong value) + { + string digits = value.ToString(CultureInfo.InvariantCulture); + if (digits.Length <= 3) return digits; + var sb = new StringBuilder(digits.Length + digits.Length / 3); + int first = digits.Length % 3; + if (first > 0) sb.Append(digits, 0, first); + for (int i = first; i < digits.Length; i += 3) + { + if (sb.Length > 0) sb.Append('.'); + sb.Append(digits, i, 3); + } + return sb.ToString(); + } +} diff --git a/src/ViaFerrea.Core/Common/Vec2.cs b/src/ViaFerrea.Core/Common/Vec2.cs new file mode 100644 index 0000000..14075d4 --- /dev/null +++ b/src/ViaFerrea.Core/Common/Vec2.cs @@ -0,0 +1,34 @@ +namespace ViaFerrea.Core.Common; + +/// Vettore 2D in metri (x verso est, y verso sud, come le righe della mappa). +public readonly record struct Vec2(double X, double Y) +{ + public static readonly Vec2 Zero = new(0, 0); + + public static Vec2 operator +(Vec2 a, Vec2 b) => new(a.X + b.X, a.Y + b.Y); + public static Vec2 operator -(Vec2 a, Vec2 b) => new(a.X - b.X, a.Y - b.Y); + public static Vec2 operator -(Vec2 a) => new(-a.X, -a.Y); + public static Vec2 operator *(Vec2 a, double k) => new(a.X * k, a.Y * k); + public static Vec2 operator *(double k, Vec2 a) => new(a.X * k, a.Y * k); + public static Vec2 operator /(Vec2 a, double k) => new(a.X / k, a.Y / k); + + public double Length => Math.Sqrt(X * X + Y * Y); + public double LengthSquared => X * X + Y * Y; + + public static double Dot(Vec2 a, Vec2 b) => a.X * b.X + a.Y * b.Y; + public static double Cross(Vec2 a, Vec2 b) => a.X * b.Y - a.Y * b.X; + public static double Distance(Vec2 a, Vec2 b) => (a - b).Length; + public static Vec2 Lerp(Vec2 a, Vec2 b, double t) => new(a.X + (b.X - a.X) * t, a.Y + (b.Y - a.Y) * t); + + /// Versore; il vettore nullo resta nullo. + public Vec2 Normalized() + { + double len = Length; + return len > 0 ? new Vec2(X / len, Y / len) : Zero; + } + + /// Perpendicolare (rotazione di 90° in senso antiorario nel piano x-est, y-sud). + public Vec2 Perpendicular => new(-Y, X); + + public override string ToString() => FormattableString.Invariant($"({X:F1}, {Y:F1})"); +} diff --git a/src/ViaFerrea.Core/Common/XxHash64.cs b/src/ViaFerrea.Core/Common/XxHash64.cs new file mode 100644 index 0000000..70ed616 --- /dev/null +++ b/src/ViaFerrea.Core/Common/XxHash64.cs @@ -0,0 +1,97 @@ +using System.Buffers.Binary; + +namespace ViaFerrea.Core.Common; + +/// +/// XXH64 (Yann Collet), implementato in Core perché System.IO.Hashing è un pacchetto NuGet. +/// Usato per l'hash di stato giornaliero e per l'hash dei dati di gioco. +/// +public static class XxHash64 +{ + private const ulong P1 = 0x9E3779B185EBCA87UL; + private const ulong P2 = 0xC2B2AE3D27D4EB4FUL; + private const ulong P3 = 0x165667B19E3779F9UL; + private const ulong P4 = 0x85EBCA77C2B2AE63UL; + private const ulong P5 = 0x27D4EB2F165667C5UL; + + /// Hash di un intervallo di byte. + public static ulong Hash(ReadOnlySpan data, ulong seed = 0) + { + int length = data.Length; + int offset = 0; + ulong h; + + if (length >= 32) + { + ulong v1 = seed + P1 + P2; + ulong v2 = seed + P2; + ulong v3 = seed; + ulong v4 = seed - P1; + int limit = length - 32; + while (offset <= limit) + { + v1 = Round(v1, BinaryPrimitives.ReadUInt64LittleEndian(data.Slice(offset))); + v2 = Round(v2, BinaryPrimitives.ReadUInt64LittleEndian(data.Slice(offset + 8))); + v3 = Round(v3, BinaryPrimitives.ReadUInt64LittleEndian(data.Slice(offset + 16))); + v4 = Round(v4, BinaryPrimitives.ReadUInt64LittleEndian(data.Slice(offset + 24))); + offset += 32; + } + h = Rotl(v1, 1) + Rotl(v2, 7) + Rotl(v3, 12) + Rotl(v4, 18); + h = MergeRound(h, v1); + h = MergeRound(h, v2); + h = MergeRound(h, v3); + h = MergeRound(h, v4); + } + else + { + h = seed + P5; + } + + h += (ulong)length; + + while (offset + 8 <= length) + { + ulong k1 = Round(0, BinaryPrimitives.ReadUInt64LittleEndian(data.Slice(offset))); + h ^= k1; + h = Rotl(h, 27) * P1 + P4; + offset += 8; + } + if (offset + 4 <= length) + { + h ^= BinaryPrimitives.ReadUInt32LittleEndian(data.Slice(offset)) * P1; + h = Rotl(h, 23) * P2 + P3; + offset += 4; + } + while (offset < length) + { + h ^= data[offset] * P5; + h = Rotl(h, 11) * P1; + offset++; + } + + h ^= h >> 33; + h *= P2; + h ^= h >> 29; + h *= P3; + h ^= h >> 32; + return h; + } + + private static ulong Round(ulong acc, ulong input) + { + acc += input * P2; + acc = Rotl(acc, 31); + acc *= P1; + return acc; + } + + private static ulong MergeRound(ulong acc, ulong val) + { + val = Round(0, val); + acc ^= val; + acc = acc * P1 + P4; + return acc; + } + + private static ulong Rotl(ulong x, int r) => (x << r) | (x >> (64 - r)); +} diff --git a/src/ViaFerrea.Core/Data/AiDefs.cs b/src/ViaFerrea.Core/Data/AiDefs.cs new file mode 100644 index 0000000..644836a --- /dev/null +++ b/src/ViaFerrea.Core/Data/AiDefs.cs @@ -0,0 +1,42 @@ +using System.Text.Json.Serialization; + +namespace ViaFerrea.Core.Data; + +// Contenuto di ai.json (guida, sezione 12.1). + +public sealed class AiFile +{ + [JsonPropertyName("$schema")] public string? Schema { get; init; } + public required int Version { get; init; } + public required AiPlanningParams Planning { get; init; } + public required List Personalities { get; init; } + public required List CompanyNames { get; init; } + public required List Colors { get; init; } +} + +public sealed class AiPlanningParams +{ + public required int IntervalDays { get; init; } + public required int MaxCandidates { get; init; } + public required int MaxProjectsPerMonth { get; init; } + public required double CandidateMaxDistanceKm { get; init; } + public required double CandidateMinDistanceKm { get; init; } + public required double PathSlopePenalty { get; init; } + public required double PathWaterPenalty { get; init; } + public required int TrainsPerLine { get; init; } + public required int WagonsPerTrain { get; init; } + public required double CashReserveMonths { get; init; } + public required double RevenueHorizonYears { get; init; } + public required double MaxRejectedShare { get; init; } +} + +public sealed class AiPersonalityDef +{ + public required string Id { get; init; } + [JsonPropertyName("name_it")] public required string NameIt { get; init; } + public required double RoiThreshold { get; init; } + public required double LoanShareOfCredit { get; init; } + public required bool TargetsPlayer { get; init; } + public required bool BuysShares { get; init; } + public required MaintenancePolicy MaintenancePolicy { get; init; } +} diff --git a/src/ViaFerrea.Core/Data/BalanceDefs.cs b/src/ViaFerrea.Core/Data/BalanceDefs.cs new file mode 100644 index 0000000..b28fe7e --- /dev/null +++ b/src/ViaFerrea.Core/Data/BalanceDefs.cs @@ -0,0 +1,371 @@ +using System.Text.Json.Serialization; + +namespace ViaFerrea.Core.Data; + +// Contenuto di balance.json: costanti delle formule (guida, sezioni 6–11). +// Ogni proprietà è obbligatoria: un valore mancante o un nome sbagliato blocca il caricamento. + +public sealed class BalanceFile +{ + [JsonPropertyName("$schema")] public string? Schema { get; init; } + public required int Version { get; init; } + public required TimeBalance Time { get; init; } + public required MapBalance Map { get; init; } + public required MarketBalance Market { get; init; } + public required LocalPriceBalance LocalPrice { get; init; } + public required IndustryBalance Industry { get; init; } + public required GrowthBalance Growth { get; init; } + public required TownBalance Town { get; init; } + public required MigrationBalance Migration { get; init; } + public required EmploymentBalance Employment { get; init; } + public required LocalTransportBalance LocalTransport { get; init; } + public required HubsBalance Hubs { get; init; } + public required TariffBalance Tariffs { get; init; } + public required FinanceBalance Finance { get; init; } + public required StockMarketBalance StockMarket { get; init; } + public required IndustryMaintenanceBalance IndustryMaintenance { get; init; } +} + +public sealed class TimeBalance +{ + public required int TickMs { get; init; } + public required int TicksPerDay { get; init; } + public required int DaysPerMonth { get; init; } + public required int MonthsPerYear { get; init; } + /// Secondi di orologio dei treni per secondo reale a 1×. + public required double TrainClockFactor { get; init; } + public required int[] Speeds { get; init; } + public required int DefaultStartYear { get; init; } +} + +public sealed class MapBalance +{ + public required double CellSizeM { get; init; } + public required int[] SizesKm { get; init; } + public required int ChunkCells { get; init; } + public required double MaxElevationM { get; init; } + public required NoiseParams Noise { get; init; } + public required ReliefParams Relief { get; init; } + public required HydrologyParams Hydrology { get; init; } + public required CoverParams Cover { get; init; } + public required DepositGenParams Deposits { get; init; } + public required TownGenParams Towns { get; init; } + public required IndustryGenParams Industries { get; init; } + public required HubGenParams Hubs { get; init; } +} + +public sealed class NoiseParams +{ + public required int Octaves { get; init; } + public required double BaseWavelengthKm { get; init; } + public required double Persistence { get; init; } + public required double Lacunarity { get; init; } + public required double WarpStrengthKm { get; init; } + public required double WarpWavelengthKm { get; init; } + public required int WarpOctaves { get; init; } + public required int RidgeOctaves { get; init; } + public required double RidgeWavelengthKm { get; init; } +} + +public sealed class ReliefParams +{ + /// Ampiezza del rumore di base nell'entroterra. + public required double NoiseAmplitudeM { get; init; } + /// Frazione dell'ampiezza del rumore sulla costa (cresce linearmente verso l'interno). + public required double NoiseCoastFactor { get; init; } + public required double InlandGradientM { get; init; } + /// Esponente del profilo costa-entroterra (2 = pianura costiera ampia, salita interna). + public required double InlandExponent { get; init; } + public required double SeaOffsetM { get; init; } + public required double MountainAmplitudeM { get; init; } + public required double MountainStart { get; init; } + public required double SeaBandFraction { get; init; } + public required double CoastNoiseM { get; init; } + /// Microrilievo che fa serpeggiare i fiumi nelle pianure. + public required double MicroReliefM { get; init; } + public required double MicroWavelengthKm { get; init; } +} + +public sealed class HydrologyParams +{ + public required double RiverThresholdKm2 { get; init; } + public required int[] RiverWidthSteps { get; init; } + public required double CarveDepthM { get; init; } + public required int ValleyRadiusCells { get; init; } + public required double ValleyDepthM { get; init; } + public required double LakeMinDepthM { get; init; } + public required int LakeMinCells { get; init; } + /// Le conche sopra questo percentile di quota si colmano invece di diventare laghi. + public required double LakeMaxPercentile { get; init; } + public required double MinSourcePercentile { get; init; } +} + +public sealed class CoverParams +{ + public required double RockPercentile { get; init; } + public required double RockMinSlope { get; init; } + public required double MountainPercentile { get; init; } + public required double HillMinSlope { get; init; } + public required double HillPercentile { get; init; } + public required double ForestMinSlope { get; init; } + public required double ForestMaxSlope { get; init; } + public required double ForestNoiseThreshold { get; init; } + public required double ForestWavelengthKm { get; init; } + public required double MarshMaxPercentile { get; init; } + public required int MarshRiverDistanceCells { get; init; } + public required double MarshMaxSlope { get; init; } + public required double MarshNoiseThreshold { get; init; } + public required int FieldRadiusCells { get; init; } + public required double FieldShare { get; init; } +} + +public sealed class DepositGenParams +{ + public required Dictionary PerThousandKm2 { get; init; } + public required int[] RadiusCells { get; init; } + public required Dictionary ReserveTonnes { get; init; } + public required double MinSpacingKm { get; init; } + public required Dictionary PreferredMinPercentile { get; init; } + public required Dictionary PreferredMaxPercentile { get; init; } +} + +public sealed class TownGenParams +{ + public required Dictionary CountBySize { get; init; } + public required double MinDistanceKm { get; init; } + public required double MaxWaterDistanceKm { get; init; } + public required double MaxSlope { get; init; } + public required double MaxHeightPercentile { get; init; } + public required int[] LargestPopulation { get; init; } + public required double ZipfExponent { get; init; } + public required int MinPopulation { get; init; } + public required double RadiusBaseCells { get; init; } + public required double RadiusPerSqrtPop { get; init; } +} + +public sealed class IndustryGenParams +{ + public required Dictionary CountBySize { get; init; } + public required int[] InitialLevels { get; init; } + /// Ripartizione delle industrie non legate a giacimenti: farm, logging, processing, manufacturing. + public required Dictionary Shares { get; init; } + public required int PlacementAttempts { get; init; } + public required double MaxSlope { get; init; } + public required int SpacingCells { get; init; } +} + +public sealed class HubGenParams +{ + public required int Ports { get; init; } + public required int Borders { get; init; } + public required double PortMinPopulationNearbyKm { get; init; } +} + +public sealed class MarketBalance +{ + public required double K { get; init; } + public required double Alpha { get; init; } + public required int WindowDays { get; init; } + public required double MinPriceFactor { get; init; } + public required double MaxPriceFactor { get; init; } + public required double RatioMin { get; init; } + public required double RatioMax { get; init; } + public required WorldMarketParams World { get; init; } + public required int HistoryDays { get; init; } +} + +public sealed class WorldMarketParams +{ + public required double Amplitude { get; init; } + public required double PeriodYears { get; init; } + public required double VolumeShare { get; init; } + public required double BaselinePerDay { get; init; } + public required double Elasticity { get; init; } + public required double ShockChancePerYear { get; init; } + public required double ShockMin { get; init; } + public required double ShockMax { get; init; } + public required double ShockDecayDays { get; init; } +} + +public sealed class LocalPriceBalance +{ + public required double Lambda { get; init; } + public required double MaxDeviation { get; init; } + public required double Epsilon { get; init; } +} + +public sealed class IndustryBalance +{ + public required int CoverageWindowDays { get; init; } + public required double ProfitFactorSlope { get; init; } + public required double ProfitFactorMin { get; init; } + public required double ProfitFactorMax { get; init; } + public required int MarginWindowDays { get; init; } + public required long WagePerWorkerPerMonth { get; init; } + public required long WagePerStaffPerMonth { get; init; } + public required double OnSiteWorkerShare { get; init; } + public required double OnSiteStaffShare { get; init; } + public required int InitialStockDays { get; init; } + public required Dictionary FootprintCells { get; init; } + public required double DepletionStartFraction { get; init; } + public required long StartingCash { get; init; } +} + +public sealed class GrowthBalance +{ + public required int QuarterDays { get; init; } + public required double WeightShipped { get; init; } + public required double WeightCoverage { get; init; } + public required double WeightProfit { get; init; } + public required double UpgradeThreshold { get; init; } + public required int UpgradeQuarters { get; init; } + public required double DowngradeThreshold { get; init; } + public required int CloseQuartersAtZero { get; init; } + public required int MaxLevel { get; init; } + public required int SpawnUnmetDays { get; init; } + public required double SpawnUnmetRatio { get; init; } + public required int SpawnMaxPerYear { get; init; } +} + +public sealed class TownBalance +{ + public required double BaseGrowth { get; init; } + public required double SatisfactionWeight { get; init; } + public required double EmploymentWeight { get; init; } + public required double EmploymentPivot { get; init; } + public required double MaxMonthlyGrowth { get; init; } + public required double SatisfactionPivot { get; init; } + public required double WorkforceShare { get; init; } + public required double StaffShare { get; init; } + public required int StaffMinPopulation { get; init; } + public required int StaffMinServices { get; init; } + public required double ServicesSatisfactionThreshold { get; init; } + public required double ServiceJobsShare { get; init; } + public required int SatisfactionEmaDays { get; init; } + public required double InitialSatisfaction { get; init; } + public required int StockDays { get; init; } + public required double WorkSatisfactionPenalty { get; init; } + public required int MaxPopulation { get; init; } +} + +public sealed class MigrationBalance +{ + public required double Share { get; init; } + public required double SatisfactionThreshold { get; init; } + public required double MaxDistanceKm { get; init; } + public required double EmigrationShareWhenNoTarget { get; init; } +} + +public sealed class EmploymentBalance +{ + public required double WalkRadiusKm { get; init; } + public required double WorkerMaxMinutes { get; init; } + public required double StaffMaxMinutes { get; init; } + public required int CoverageEmaDays { get; init; } + public required double DissolveCoverage { get; init; } + public required int DissolveDays { get; init; } + public required double WalkSpeedKmh { get; init; } +} + +public sealed class LocalTransportBalance +{ + public required bool Enabled { get; init; } + public required double RadiusKm { get; init; } + public required double DailyShare { get; init; } + public required int MaxUnitsPerDay { get; init; } +} + +public sealed class HubsBalance +{ + public required HubParams Port { get; init; } + public required HubParams Border { get; init; } + + public HubParams For(HubKind kind) => kind == HubKind.Port ? Port : Border; +} + +public sealed class HubParams +{ + [JsonPropertyName("name_it")] public required string NameIt { get; init; } + public required int MonthlyCapacity { get; init; } + public required double Duty { get; init; } + public required Footprint Footprint { get; init; } +} + +public sealed class TariffBalance +{ + public required double FreightBaseRate { get; init; } + public required double FreightFixedWeight { get; init; } + public required double FreightPriceWeight { get; init; } + public required double FreightKmExponent { get; init; } + public required double PaxBaseFare { get; init; } + public required double PaxKmExponent { get; init; } + public required Dictionary ClassMultipliers { get; init; } + public required double LateThreshold { get; init; } + public required double LateFactorMin { get; init; } + public required double LateFactorSpan { get; init; } +} + +public sealed class FinanceBalance +{ + public required Dictionary RatingSpreads { get; init; } + /// Soglie del punteggio (0–1) da AAA a C; sotto l'ultima soglia il rating è D. + public required double[] RatingByScore { get; init; } + public required double ProfitMarginWeight { get; init; } + public required double LeverageWeight { get; init; } + public required int LoanTermMonths { get; init; } + public required long LoanStep { get; init; } + public required CreditRating StartingRating { get; init; } + public required int DepreciationYearsTrack { get; init; } + public required double BookValueFloor { get; init; } +} + +public sealed class StockMarketBalance +{ + public required int Shares { get; init; } + public required double EarningsMultiple { get; init; } + public required double SentimentMin { get; init; } + public required double SentimentMax { get; init; } + public required double Spread { get; init; } + public required double IpoMaxShare { get; init; } + public required double ControlShare { get; init; } + public required int MergeAfterDays { get; init; } + public required double BidPremiumMin { get; init; } + public required double BidPremiumMax { get; init; } + public required int BidDurationDays { get; init; } + public required double RansomShare { get; init; } + public required double ReceivershipDividend { get; init; } +} + +public sealed class IndustryMaintenanceBalance +{ + public required double WearPerDay { get; init; } + public required double EfficiencyFullAbove { get; init; } + public required double EfficiencyAt20 { get; init; } + public required double EfficiencyBelow20 { get; init; } + public required double BreakdownBase { get; init; } + public required double BreakdownPivot { get; init; } + public required double BreakdownScale { get; init; } + public required int[] BreakdownDays { get; init; } + public required double BreakdownTownSatisfaction { get; init; } + public required double AccidentBelow { get; init; } + public required int AccidentDays { get; init; } + public required double AccidentPopulationLoss { get; init; } + public required Dictionary Budgets { get; init; } + public required double NoPartsRecoveryFactor { get; init; } + public required int OverhaulDays { get; init; } + public required int OverhaulMachineryPerLevel { get; init; } + public required double OverhaulMinStaffCoverage { get; init; } + public required int UpgradeMachineryPerLevel { get; init; } + public required int UpgradeDays { get; init; } + public required double NpcUpgradeMargin { get; init; } + public required int NpcUpgradeYears { get; init; } + public required double NpcHighMargin { get; init; } + public required double NpcOverhaulBelow { get; init; } +} + +public sealed class IndustryBudgetParams +{ + public required double RecoveryPerDay { get; init; } + public required double CostShareOfRevenue { get; init; } + public required int SparePartsPerLevelPerMonth { get; init; } +} diff --git a/src/ViaFerrea.Core/Data/ConstructionDefs.cs b/src/ViaFerrea.Core/Data/ConstructionDefs.cs new file mode 100644 index 0000000..458123b --- /dev/null +++ b/src/ViaFerrea.Core/Data/ConstructionDefs.cs @@ -0,0 +1,140 @@ +using System.Text.Json.Serialization; + +namespace ViaFerrea.Core.Data; + +// Contenuto di construction.json (guida, sezione 8). + +public sealed class ConstructionFile +{ + [JsonPropertyName("$schema")] public string? Schema { get; init; } + public required int Version { get; init; } + public required ProfileParams Profile { get; init; } + public required GradientLimits MaxGradientByTraction { get; init; } + public required List SpeedClasses { get; init; } + public required double CurveSpeedFactor { get; init; } + public required ConstructionCosts Costs { get; init; } + public required CrewParams Crews { get; init; } + public required ConstructionRules Rules { get; init; } + public required TrackWearParams TrackWear { get; init; } + public required StructureParams Structures { get; init; } + public required PhysicsParams Physics { get; init; } +} + +public sealed class ProfileParams +{ + public required double SampleSpacingM { get; init; } + public required double HeightOffsetRangeM { get; init; } + public required int SmoothingWindow { get; init; } + public required double NaturalToleranceM { get; init; } + public required double EmbankmentMaxM { get; init; } + public required double CuttingMaxM { get; init; } + public required double RiverClearanceM { get; init; } + public required double NavigableClearanceM { get; init; } + public required int NavigableMinWidthCells { get; init; } + public required double SnapAngleDeg { get; init; } +} + +public sealed class GradientLimits +{ + public required double Steam { get; init; } + public required double Diesel { get; init; } + public required double Electric { get; init; } + public required double HighSpeed { get; init; } + + public double For(Traction traction) => traction switch + { + Traction.Steam => Steam, + Traction.Diesel => Diesel, + Traction.Electric => Electric, + _ => HighSpeed, + }; +} + +public sealed class SpeedClassDef +{ + public required string TrackClass { get; init; } + public required double MinRadiusM { get; init; } + public required double CostMultiplier { get; init; } +} + +public sealed class ConstructionCosts +{ + /// Costo base per metro di sede naturale, in centesimi. + public required double BasePerMeter { get; init; } + public required double Natural { get; init; } + public required double EmbankmentPerM { get; init; } + public required double CuttingPerM { get; init; } + public required double BridgeBase { get; init; } + public required double BridgePerM { get; init; } + public required double Tunnel { get; init; } + public required Dictionary TerrainModifiers { get; init; } + public required LandCostParams Land { get; init; } + public required double DoubleTrackMultiplier { get; init; } + public required double ElectrificationExtra { get; init; } + public required long StationBase { get; init; } + public required long StationPerPlatform { get; init; } + public required Dictionary DepotBySize { get; init; } + public required double DemolitionRefund { get; init; } +} + +public sealed class LandCostParams +{ + public required long BasePerCell { get; init; } + public required double NearTownKm { get; init; } + public required double NearTownMultiplier { get; init; } + public required double FieldMultiplier { get; init; } +} + +public sealed class CrewParams +{ + public required Dictionary MetersPerDay { get; init; } + public required int[] CrewsByTier { get; init; } + public required bool UpgradeClosure { get; init; } +} + +public sealed class ConstructionRules +{ + public required bool ForbidTownFootprint { get; init; } + public required bool ForbidIndustryFootprint { get; init; } + public required bool ForbidForeignStations { get; init; } + public required bool ForeignCrossingNeedsOverpass { get; init; } + public required double OverpassClearanceM { get; init; } +} + +public sealed class TrackWearParams +{ + public required double K { get; init; } + public required double GradientWeight { get; init; } + public required double SpeedWeight { get; init; } + public required double MaintenanceDriftPerDay { get; init; } + public required long MaintenanceCostPerKmPerDay { get; init; } + public required double LimitBelow60 { get; init; } + public required double LimitBelow30 { get; init; } + public required double FailureChanceBelow30 { get; init; } + public required double RenewalCostShare { get; init; } + public required double RenewalDaysPerKm { get; init; } +} + +public sealed class StructureParams +{ + public required double InspectionCostShare { get; init; } + public required int InspectionIntervalDays { get; init; } + public required int RenewalYears { get; init; } + public required double MissedInspectionWearPerDay { get; init; } + public required double SpeedLimitBelow { get; init; } + public required double SpeedLimitFactor { get; init; } + public required double CloseBelow { get; init; } +} + +public sealed class PhysicsParams +{ + public required double Gravity { get; init; } + public required double Adhesion { get; init; } + public required double AdhesionFactor { get; init; } + public required double RollingResistance { get; init; } + public required double AeroCoefficient { get; init; } + public required Dictionary CxByKind { get; init; } + public required double BrakingMs2 { get; init; } + public required double StallSpeedKmh { get; init; } + public required double StallSeconds { get; init; } +} diff --git a/src/ViaFerrea.Core/Data/ContractsDefs.cs b/src/ViaFerrea.Core/Data/ContractsDefs.cs new file mode 100644 index 0000000..07d5b49 --- /dev/null +++ b/src/ViaFerrea.Core/Data/ContractsDefs.cs @@ -0,0 +1,45 @@ +using System.Text.Json.Serialization; + +namespace ViaFerrea.Core.Data; + +// Contenuto di contracts.json (guida, sezione 13.5). + +public sealed class ContractsFile +{ + [JsonPropertyName("$schema")] public string? Schema { get; init; } + public required int Version { get; init; } + public required ContractGenerationParams Generation { get; init; } + public required List Templates { get; init; } + public required List Expositions { get; init; } +} + +public sealed class ContractGenerationParams +{ + public required double PerYear { get; init; } + public required int MaxOpen { get; init; } + public required int ExpoEveryYears { get; init; } +} + +public sealed class ContractTemplateDef +{ + public required string Id { get; init; } + public required ContractKind Kind { get; init; } + [JsonPropertyName("name_it")] public required string NameIt { get; init; } + [JsonPropertyName("text_it")] public required string TextIt { get; init; } + public required int[] DurationYears { get; init; } + public int[]? MaxMinutes { get; init; } + public int[]? Quantity { get; init; } + public double[]? LengthKm { get; init; } + public required long Reward { get; init; } + public required int Prestige { get; init; } + public required long Penalty { get; init; } + public required int MinYear { get; init; } +} + +public sealed class ExpositionDef +{ + public required string Id { get; init; } + [JsonPropertyName("name_it")] public required string NameIt { get; init; } + public required long Reward { get; init; } + public required int Prestige { get; init; } +} diff --git a/src/ViaFerrea.Core/Data/DataJsonContext.cs b/src/ViaFerrea.Core/Data/DataJsonContext.cs new file mode 100644 index 0000000..0b49325 --- /dev/null +++ b/src/ViaFerrea.Core/Data/DataJsonContext.cs @@ -0,0 +1,33 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace ViaFerrea.Core.Data; + +/// +/// Contesto System.Text.Json generato a compile time per i file dati: niente reflection, +/// proprietà sconosciute vietate (un refuso nel JSON è un errore, non un valore ignorato), +/// enumerazioni come stringhe. +/// +[JsonSourceGenerationOptions( + PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, + PropertyNameCaseInsensitive = true, + UseStringEnumConverter = true, + ReadCommentHandling = JsonCommentHandling.Disallow, + AllowTrailingCommas = false, + UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow, + NumberHandling = JsonNumberHandling.Strict, + WriteIndented = true)] +[JsonSerializable(typeof(GoodsFile))] +[JsonSerializable(typeof(IndustriesFile))] +[JsonSerializable(typeof(VehiclesFile))] +[JsonSerializable(typeof(ErasFile))] +[JsonSerializable(typeof(TiersFile))] +[JsonSerializable(typeof(BalanceFile))] +[JsonSerializable(typeof(DifficultyFile))] +[JsonSerializable(typeof(ConstructionFile))] +[JsonSerializable(typeof(MaintenanceFile))] +[JsonSerializable(typeof(AiFile))] +[JsonSerializable(typeof(ContractsFile))] +[JsonSerializable(typeof(RegionsFile))] +[JsonSerializable(typeof(DifficultyDef))] +public sealed partial class DataJsonContext : JsonSerializerContext; diff --git a/src/ViaFerrea.Core/Data/DataSource.cs b/src/ViaFerrea.Core/Data/DataSource.cs new file mode 100644 index 0000000..aa56337 --- /dev/null +++ b/src/ViaFerrea.Core/Data/DataSource.cs @@ -0,0 +1,79 @@ +namespace ViaFerrea.Core.Data; + +/// Sorgente dei file dati: cartella su disco, risorse del client Godot, memoria nei test. +public interface IDataSource +{ + /// Descrizione per i messaggi d'errore. + string Description { get; } + + bool Exists(string relativePath); + + string ReadText(string relativePath); +} + +/// File dati in una cartella del file system. +public sealed class DirectoryDataSource(string root) : IDataSource +{ + public string Root { get; } = Path.GetFullPath(root); + + public string Description => Root; + + public bool Exists(string relativePath) => File.Exists(Path.Combine(Root, relativePath)); + + public string ReadText(string relativePath) => File.ReadAllText(Path.Combine(Root, relativePath)); + + /// + /// Trova la cartella dati: variabile VF_GAME_DATA, poi «data» accanto all'eseguibile, + /// poi risalendo dalla cartella corrente (utile in sviluppo). + /// + public static DirectoryDataSource FindDefault() + { + string? env = Environment.GetEnvironmentVariable("VF_GAME_DATA"); + if (!string.IsNullOrWhiteSpace(env) && File.Exists(Path.Combine(env, "goods.json"))) + return new DirectoryDataSource(env); + + string beside = Path.Combine(AppContext.BaseDirectory, "data"); + if (File.Exists(Path.Combine(beside, "goods.json"))) return new DirectoryDataSource(beside); + + var dir = new DirectoryInfo(Directory.GetCurrentDirectory()); + while (dir is not null) + { + string candidate = Path.Combine(dir.FullName, "data"); + if (File.Exists(Path.Combine(candidate, "goods.json"))) return new DirectoryDataSource(candidate); + dir = dir.Parent; + } + throw new DirectoryNotFoundException("Cartella dei dati di gioco non trovata (imposta VF_GAME_DATA)"); + } +} + +/// File dati in memoria, per i test (per esempio dati volutamente sbagliati). +public sealed class MemoryDataSource(IReadOnlyDictionary files, string description = "memoria") : IDataSource +{ + public string Description => description; + + public bool Exists(string relativePath) => files.ContainsKey(Normalize(relativePath)); + + public string ReadText(string relativePath) => + files.TryGetValue(Normalize(relativePath), out var text) ? text : throw new FileNotFoundException(relativePath); + + private static string Normalize(string path) => path.Replace('\\', '/'); + + /// Copia tutti i file .json di una sorgente su disco, per poterne alterare alcuni. + public static Dictionary Snapshot(DirectoryDataSource source) + { + var result = new Dictionary(StringComparer.Ordinal); + foreach (string file in Directory.EnumerateFiles(source.Root, "*.json", SearchOption.AllDirectories)) + { + string rel = Path.GetRelativePath(source.Root, file).Replace('\\', '/'); + result[rel] = File.ReadAllText(file); + } + return result; + } +} + +/// Errori di validazione dei dati, tutti insieme. +public sealed class DataValidationException(IReadOnlyList errors) + : Exception($"Dati di gioco non validi ({errors.Count} errori):\n " + string.Join("\n ", errors)) +{ + public IReadOnlyList Errors { get; } = errors; +} diff --git a/src/ViaFerrea.Core/Data/DataValidator.cs b/src/ViaFerrea.Core/Data/DataValidator.cs new file mode 100644 index 0000000..da513be --- /dev/null +++ b/src/ViaFerrea.Core/Data/DataValidator.cs @@ -0,0 +1,290 @@ +namespace ViaFerrea.Core.Data; + +/// +/// Validazione semantica dei dati, dopo lo schema: id univoci, riferimenti risolti, +/// coerenza tra file e limiti che lo schema non può esprimere. +/// +public static class DataValidator +{ + private static readonly string[] SizeKeys = ["small", "medium", "large"]; + private static readonly string[] ResourceKeys = ["coal", "iron", "stone", "oil"]; + private static readonly string[] WorkKeys = ["natural", "embankment", "cutting", "bridge", "tunnel"]; + private static readonly string[] CellTypeKeys = ["plain", "hill", "mountain", "forest", "field", "water", "sea", "town", "industry", "rock", "marsh"]; + + public static void Validate(GameData d, List errors) + { + void Err(string file, string message) => errors.Add($"{file}: {message}"); + + // --- beni + Unique("goods.json", d.Goods.Select(g => g.Id), errors); + var goodIds = d.Goods.Select(g => g.Id).ToHashSet(StringComparer.Ordinal); + foreach (string required in new[] { "spare_parts", "machinery" }) + { + if (!goodIds.Contains(required)) Err("goods.json", $"manca il bene di servizio obbligatorio «{required}»"); + } + foreach (var g in d.Goods) + { + if (g.Town is { UntilYear: { } until } && until <= g.Era) Err("goods.json", $"{g.Id}: town.untilYear precedente all'era del bene"); + } + + // --- industrie + Unique("industries.json", d.Industries.Select(i => i.Id), errors); + foreach (var ind in d.Industries) + { + string p = $"{ind.Id}:"; + foreach (var item in ind.Recipe.Inputs.Concat(ind.Recipe.Outputs)) + { + if (!goodIds.Contains(item.Good)) Err("industries.json", $"{p} bene sconosciuto «{item.Good}»"); + } + Unique("industries.json", ind.Recipe.Inputs.Select(x => x.Good), errors, $"{p} input"); + Unique("industries.json", ind.Recipe.Outputs.Select(x => x.Good), errors, $"{p} output"); + if (ind.Kind == IndustryKind.Primary && ind.Recipe.Inputs.Count > 0) Err("industries.json", $"{p} un'industria primaria non ha input"); + if (ind.Kind != IndustryKind.Primary && ind.Recipe.Inputs.Count == 0) Err("industries.json", $"{p} un'industria di trasformazione richiede input"); + NonDecreasing("industries.json", $"{p} capacityPerLevel", ind.CapacityPerLevel, errors); + NonDecreasing("industries.json", $"{p} workersPerLevel", ind.WorkersPerLevel, errors); + NonDecreasing("industries.json", $"{p} staffPerLevel", ind.StaffPerLevel, errors); + if (ind.CapacityPerLevel[0] <= 0) Err("industries.json", $"{p} capacità di livello 1 nulla"); + if (ind.Placement.Needs == PlacementNeed.Deposit && ind.Placement.Resource is null) + Err("industries.json", $"{p} needs=deposit richiede «resource»"); + if (ind.Depletable && ind.Placement.Needs != PlacementNeed.Deposit) + Err("industries.json", $"{p} solo le industrie su giacimento possono esaurirsi"); + if (ind.Placement is { MinTownDistanceKm: { } mn, MaxTownDistanceKm: { } mx } && mx < mn) + Err("industries.json", $"{p} maxTownDistanceKm < minTownDistanceKm"); + if (d.Balance.Industry.FootprintCells is { } fc && !fc.ContainsKey(ind.Footprint.ToString().ToLowerInvariant())) + Err("balance.json", $"industry.footprintCells non definisce «{ind.Footprint}»"); + } + foreach (var g in d.Goods) + { + bool produced = d.Industries.Any(i => i.Recipe.Outputs.Any(o => o.Good == g.Id)); + if (!produced) Err("industries.json", $"nessuna industria produce «{g.Id}»"); + } + + // --- veicoli + Unique("vehicles.json", d.Vehicles.Select(v => v.Id), errors); + var locoComponents = d.Maintenance.Components.Locomotive.Select(c => c.Id).ToHashSet(StringComparer.Ordinal); + var carComponents = d.Maintenance.Components.Car.Select(c => c.Id).ToHashSet(StringComparer.Ordinal); + foreach (var v in d.Vehicles) + { + string p = $"{v.Id}:"; + if (v.EraTo is { } to && to < v.EraFrom) Err("vehicles.json", $"{p} eraTo precedente a eraFrom"); + switch (v.Kind) + { + case VehicleKind.Locomotive: + if (v.Traction is null) Err("vehicles.json", $"{p} una locomotiva richiede «traction»"); + if (v.PowerKw <= 0 || v.TractiveEffortKn <= 0) Err("vehicles.json", $"{p} potenza e sforzo di trazione devono essere positivi"); + foreach (string comp in v.Components.Keys) + { + if (!locoComponents.Contains(comp)) Err("vehicles.json", $"{p} componente sconosciuto «{comp}»"); + } + foreach (string comp in locoComponents) + { + if (!v.Components.ContainsKey(comp)) Err("vehicles.json", $"{p} manca il componente «{comp}»"); + } + break; + case VehicleKind.Wagon: + if (v.Capacity is null || v.WagonType is null || v.Goods is null) + Err("vehicles.json", $"{p} un carro richiede capacity, wagonType e goods"); + foreach (string g in v.Goods ?? []) + { + if (!goodIds.Contains(g)) Err("vehicles.json", $"{p} bene sconosciuto «{g}»"); + } + CheckCarComponents(v, carComponents, errors); + break; + case VehicleKind.Coach: + if (v.PaxCapacity is null || v.Class is null) Err("vehicles.json", $"{p} una carrozza richiede paxCapacity e class"); + CheckCarComponents(v, carComponents, errors); + break; + } + } + foreach (var g in d.Goods) + { + bool carried = d.Vehicles.Any(v => v.Kind == VehicleKind.Wagon && v.WagonType == g.Wagon && (v.Goods?.Contains(g.Id) ?? false)); + if (!carried) Err("vehicles.json", $"nessun carro di tipo «{g.Wagon}» trasporta «{g.Id}»"); + } + foreach (PaxClass cls in Enum.GetValues()) + { + if (!d.Vehicles.Any(v => v.Kind == VehicleKind.Coach && v.Class == cls)) + Err("vehicles.json", $"nessuna carrozza per la classe «{cls}»"); + } + if (!d.Vehicles.Any(v => v.Kind == VehicleKind.Locomotive && v.EraFrom <= d.Balance.Time.DefaultStartYear)) + Err("vehicles.json", "nessuna locomotiva disponibile all'anno di inizio predefinito"); + + // --- ere + Unique("eras.json", d.Eras.Eras.Select(e => e.Id), errors); + Unique("eras.json", d.Eras.TrackClasses.Select(e => e.Id), errors); + Unique("eras.json", d.Eras.BridgeTypes.Select(e => e.Id), errors); + Unique("eras.json", d.Eras.Signals.Select(e => e.Id), errors); + Unique("eras.json", d.Eras.Tractions.Select(e => e.Id.ToString()), errors); + foreach (Traction t in Enum.GetValues()) + { + if (!d.Eras.Tractions.Any(x => x.Id == t)) Err("eras.json", $"manca la trazione «{t}»"); + } + Increasing("eras.json", "eras.from", d.Eras.Eras.Select(e => (double)e.From), errors); + Increasing("eras.json", "bridgeTypes.from", d.Eras.BridgeTypes.Select(e => (double)e.From), errors); + Increasing("eras.json", "bridgeTypes.maxSpanM", d.Eras.BridgeTypes.Select(e => e.MaxSpanM), errors); + Increasing("eras.json", "tunnelLimits.from", d.Eras.TunnelLimits.Select(e => (double)e.From), errors); + Increasing("eras.json", "tunnelLimits.maxLengthM", d.Eras.TunnelLimits.Select(e => e.MaxLengthM), errors); + Increasing("eras.json", "trackClasses.speedKmh", d.Eras.TrackClasses.Select(e => e.SpeedKmh), errors); + int start = d.Balance.Time.DefaultStartYear; + if (d.Eras.BridgeTypes[0].From > start) Err("eras.json", "nessun tipo di ponte all'anno di inizio"); + if (d.Eras.TunnelLimits[0].From > start) Err("eras.json", "nessun limite di galleria all'anno di inizio"); + if (d.Eras.TrackClasses[0].From > start) Err("eras.json", "nessuna classe di binario all'anno di inizio"); + + // --- livelli + var levels = d.Tiers.Tiers.Select(t => t.Level).ToList(); + if (!levels.SequenceEqual(Enumerable.Range(1, levels.Count))) Err("tiers.json", "i livelli devono essere 1, 2, 3, 4, 5 in ordine"); + Increasing("tiers.json", "requirements.netWorth", d.Tiers.Tiers.Select(t => (double)t.Requirements.NetWorth), errors, strictFromSecond: true); + if (!d.Tiers.RatingScale.SequenceEqual(Enum.GetValues())) Err("tiers.json", "ratingScale deve elencare i rating da AAA a D"); + + // --- difficoltà + Unique("difficulty.json", d.Difficulty.Presets.Select(p => p.Id), errors); + if (!d.Difficulty.Presets.Any(p => p.Id == d.Difficulty.Default)) Err("difficulty.json", $"preset predefinito «{d.Difficulty.Default}» inesistente"); + + // --- bilanciamento + var b = d.Balance; + if (!b.Time.Speeds.Contains(0) || !b.Time.Speeds.Contains(1)) Err("balance.json", "time.speeds deve contenere 0 e 1"); + if (b.Market.MinPriceFactor >= 1 || b.Market.MaxPriceFactor <= 1) Err("balance.json", "market: i fattori di prezzo devono racchiudere 1"); + foreach (int size in b.Map.SizesKm) + { + string key = size.ToString(System.Globalization.CultureInfo.InvariantCulture); + if (!b.Map.Towns.CountBySize.ContainsKey(key)) Err("balance.json", $"map.towns.countBySize non definisce {key}"); + if (!b.Map.Industries.CountBySize.ContainsKey(key)) Err("balance.json", $"map.industries.countBySize non definisce {key}"); + } + RequireKeys("balance.json", "map.deposits.perThousandKm2", b.Map.Deposits.PerThousandKm2.Keys, ResourceKeys, errors); + RequireKeys("balance.json", "map.deposits.reserveTonnes", b.Map.Deposits.ReserveTonnes.Keys, ResourceKeys, errors); + RequireKeys("balance.json", "map.deposits.preferredMinPercentile", b.Map.Deposits.PreferredMinPercentile.Keys, ResourceKeys, errors); + RequireKeys("balance.json", "map.deposits.preferredMaxPercentile", b.Map.Deposits.PreferredMaxPercentile.Keys, ResourceKeys, errors); + foreach (var (k, range) in b.Map.Deposits.ReserveTonnes) + { + if (range.Length != 2 || range[0] > range[1] || range[0] <= 0) Err("balance.json", $"map.deposits.reserveTonnes.{k} deve essere [min, max] positivo"); + } + if (b.Map.Deposits.RadiusCells.Length != 2) Err("balance.json", "map.deposits.radiusCells deve essere [min, max]"); + if (b.Map.Towns.LargestPopulation.Length != 2) Err("balance.json", "map.towns.largestPopulation deve essere [min, max]"); + if (b.Map.Hydrology.RiverWidthSteps.Length != 4) Err("balance.json", "map.hydrology.riverWidthSteps deve avere 4 soglie (larghezze 1–4)"); + RequireKeys("balance.json", "map.industries.shares", b.Map.Industries.Shares.Keys, ["farm", "logging", "processing", "manufacturing"], errors); + if (Math.Abs(b.Map.Industries.Shares.Values.Sum() - 1.0) > 1e-6) Err("balance.json", "map.industries.shares deve sommare a 1"); + if (b.Map.Industries.InitialLevels.Length != 2 || b.Map.Industries.InitialLevels[0] > b.Map.Industries.InitialLevels[1]) + Err("balance.json", "map.industries.initialLevels deve essere [min, max]"); + RequireKeys("balance.json", "industry.footprintCells", b.Industry.FootprintCells.Keys, SizeKeys, errors); + RequireKeys("balance.json", "tariffs.classMultipliers", b.Tariffs.ClassMultipliers.Keys, ["worker", "staff"], errors); + RequireKeys("balance.json", "finance.ratingSpreads", b.Finance.RatingSpreads.Keys, Enum.GetNames(), errors); + if (b.Finance.RatingByScore.Length != 9) Err("balance.json", "finance.ratingByScore deve avere 9 soglie (AAA … C)"); + Increasing("balance.json", "finance.ratingByScore (decrescente)", Enumerable.Reverse(b.Finance.RatingByScore), errors); + RequireKeys("balance.json", "industryMaintenance.budgets", b.IndustryMaintenance.Budgets.Keys, ["none", "base", "high"], errors); + if (b.IndustryMaintenance.BreakdownDays.Length != 2) Err("balance.json", "industryMaintenance.breakdownDays deve essere [min, max]"); + if (b.Growth.MaxLevel > 5 || b.Growth.MaxLevel < 1) Err("balance.json", "growth.maxLevel deve stare tra 1 e 5"); + + // --- costruzione + var c = d.Construction; + var classIds = d.Eras.TrackClasses.Select(t => t.Id).ToHashSet(StringComparer.Ordinal); + foreach (var sc in c.SpeedClasses) + { + if (!classIds.Contains(sc.TrackClass)) Err("construction.json", $"speedClasses: classe «{sc.TrackClass}» inesistente in eras.json"); + } + foreach (string id in classIds) + { + if (!c.SpeedClasses.Any(s => s.TrackClass == id)) Err("construction.json", $"speedClasses non definisce la classe «{id}»"); + } + RequireKeys("construction.json", "crews.metersPerDay", c.Crews.MetersPerDay.Keys, WorkKeys, errors); + if (c.Crews.CrewsByTier.Length != 5) Err("construction.json", "crews.crewsByTier deve avere 5 valori"); + RequireKeys("construction.json", "costs.depotBySize", c.Costs.DepotBySize.Keys, SizeKeys, errors); + foreach (string k in c.Costs.TerrainModifiers.Keys) + { + if (!CellTypeKeys.Contains(k)) Err("construction.json", $"costs.terrainModifiers: tipo di cella sconosciuto «{k}»"); + } + RequireKeys("construction.json", "physics.cxByKind", c.Physics.CxByKind.Keys, ["locomotive", "wagon", "coach"], errors); + if (c.Profile.SmoothingWindow % 2 == 0) Err("construction.json", "profile.smoothingWindow deve essere dispari"); + + // --- manutenzione + var m = d.Maintenance; + Unique("maintenance.json", m.Interventions.Select(i => i.Id), errors); + Unique("maintenance.json", m.Components.Locomotive.Select(i => i.Id), errors); + Unique("maintenance.json", m.Components.Car.Select(i => i.Id), errors); + Near1("maintenance.json", "components.locomotive.failureWeight", m.Components.Locomotive.Sum(x => x.FailureWeight), errors); + Near1("maintenance.json", "components.car.failureWeight", m.Components.Car.Sum(x => x.FailureWeight), errors); + Near1("maintenance.json", "failure.*Share", m.Failure.MinorShare + m.Failure.MajorShare + m.Failure.CatastrophicShare, errors); + foreach (string id in new[] { "inspection", "service", "overhaul", "repair_minor", "repair_major", "repair_catastrophic" }) + { + if (!m.Interventions.Any(i => i.Id == id)) Err("maintenance.json", $"manca l'intervento «{id}»"); + } + foreach (var i in m.Interventions) + { + if (i.Effect == InterventionEffect.Repair && i.RestoreTo is null) Err("maintenance.json", $"{i.Id}: una riparazione richiede restoreTo"); + } + RequireKeys("maintenance.json", "depots.stallsBySize", m.Depots.StallsBySize.Keys, SizeKeys, errors); + + // --- IA, contratti, regioni + Unique("ai.json", d.Ai.Personalities.Select(p => p.Id), errors); + Unique("contracts.json", d.Contracts.Templates.Select(t => t.Id), errors); + foreach (var t in d.Contracts.Templates) + { + if (t.DurationYears[0] > t.DurationYears[1]) Err("contracts.json", $"{t.Id}: durationYears [min, max] invertito"); + if (t.Kind == ContractKind.Connect && t.MaxMinutes is null) Err("contracts.json", $"{t.Id}: un collegamento richiede maxMinutes"); + if (t.Kind is ContractKind.Deliver or ContractKind.Service && t.Quantity is null) Err("contracts.json", $"{t.Id}: richiede quantity"); + if (t.Kind == ContractKind.GreatWork && t.LengthKm is null) Err("contracts.json", $"{t.Id}: una grande opera richiede lengthKm"); + } + Unique("regions.json", d.Regions.Regions.Select(r => r.Id), errors); + Unique("regions.json", d.Regions.NamePools.Select(r => r.Id), errors); + var pools = d.Regions.NamePools.Select(p => p.Id).ToHashSet(StringComparer.Ordinal); + foreach (var r in d.Regions.Regions) + { + if (!pools.Contains(r.NamePool)) Err("regions.json", $"{r.Id}: serbatoio di nomi «{r.NamePool}» inesistente"); + } + } + + private static void CheckCarComponents(VehicleDef v, HashSet carComponents, List errors) + { + foreach (string c in v.Components.Keys) + { + if (!carComponents.Contains(c)) errors.Add($"vehicles.json: {v.Id}: componente sconosciuto «{c}»"); + } + foreach (string c in carComponents) + { + if (!v.Components.ContainsKey(c)) errors.Add($"vehicles.json: {v.Id}: manca il componente «{c}»"); + } + } + + private static void Unique(string file, IEnumerable ids, List errors, string context = "id") + { + var seen = new HashSet(StringComparer.Ordinal); + foreach (string id in ids) + { + if (!seen.Add(id)) errors.Add($"{file}: {context} duplicato «{id}»"); + } + } + + private static void RequireKeys(string file, string what, IEnumerable keys, IEnumerable required, List errors) + { + var set = keys.ToHashSet(StringComparer.Ordinal); + foreach (string k in required) + { + if (!set.Contains(k)) errors.Add($"{file}: {what} non definisce «{k}»"); + } + } + + private static void NonDecreasing(string file, string what, IReadOnlyList values, List errors) + { + for (int i = 1; i < values.Count; i++) + { + if (values[i] < values[i - 1]) errors.Add($"{file}: {what} non deve decrescere"); + } + } + + private static void Increasing(string file, string what, IEnumerable values, List errors, bool strictFromSecond = false) + { + double? prev = null; + int i = 0; + foreach (double v in values) + { + if (prev is { } p && (strictFromSecond && i == 1 ? v < p : v <= p)) + errors.Add($"{file}: {what} deve essere crescente"); + prev = v; + i++; + } + } + + private static void Near1(string file, string what, double sum, List errors) + { + if (Math.Abs(sum - 1.0) > 1e-6) errors.Add($"{file}: la somma di {what} deve essere 1 (è {sum})"); + } +} diff --git a/src/ViaFerrea.Core/Data/DifficultyDefs.cs b/src/ViaFerrea.Core/Data/DifficultyDefs.cs new file mode 100644 index 0000000..6207a53 --- /dev/null +++ b/src/ViaFerrea.Core/Data/DifficultyDefs.cs @@ -0,0 +1,55 @@ +using System.Text.Json.Serialization; + +namespace ViaFerrea.Core.Data; + +/// Contenuto di difficulty.json. +public sealed class DifficultyFile +{ + [JsonPropertyName("$schema")] public string? Schema { get; init; } + public required int Version { get; init; } + public required string Default { get; init; } + public required DepletionMultipliers DepletionMultipliers { get; init; } + public required List Presets { get; init; } +} + +public sealed class DepletionMultipliers +{ + public required double Slow { get; init; } + public required double Normal { get; init; } + public required double Fast { get; init; } + + public double For(DepletionRate rate) => rate switch + { + DepletionRate.Slow => Slow, + DepletionRate.Fast => Fast, + _ => Normal, + }; +} + +/// +/// Preset di difficoltà. È anche il formato della difficoltà «Personalizzata»: la partita +/// conserva una copia completa dei valori effettivi. +/// +public sealed record DifficultyDef +{ + public required string Id { get; init; } + [JsonPropertyName("name_it")] public required string NameIt { get; init; } + [JsonPropertyName("name_en")] public required string NameEn { get; init; } + public required long InitialCapital { get; init; } + public required long InitialCredit { get; init; } + public required double BaseInterestRate { get; init; } + public required double ConstructionCostMultiplier { get; init; } + public required double TariffMultiplier { get; init; } + public required double WearMultiplier { get; init; } + public required double MarketVolatilityMultiplier { get; init; } + public required int AiCompetitors { get; init; } + public required double AiCapitalMultiplier { get; init; } + public required double AiCostDiscount { get; init; } + public required TakeoverRule PlayerTakeover { get; init; } + public required int TakeoverRansomYears { get; init; } + public required int BankruptcyDays { get; init; } + public required bool PublicFromStart { get; init; } + public required double PlayerShareAtStart { get; init; } + public required IronmanRule Ironman { get; init; } + public required DepletionRate Depletion { get; init; } +} diff --git a/src/ViaFerrea.Core/Data/Enums.cs b/src/ViaFerrea.Core/Data/Enums.cs new file mode 100644 index 0000000..4e24a3e --- /dev/null +++ b/src/ViaFerrea.Core/Data/Enums.cs @@ -0,0 +1,42 @@ +namespace ViaFerrea.Core.Data; + +// Enumerazioni dei file dati. Nel JSON compaiono in minuscolo; la lettura è insensibile alle maiuscole. + +public enum GoodCategory { Bulk, General, Liquid, Perishable } + +public enum WagonType { Hopper, Flat, Tank, Box } + +public enum TownCategory { Food, Goods, Fuel, Construction } + +public enum IndustryKind { Primary, Processing, Manufacturing } + +public enum Footprint { Small, Medium, Large } + +public enum PlacementNeed { Deposit, Forest, Plain, Coast, Town, Any } + +public enum ResourceKind { Coal, Iron, Stone, Oil } + +public enum VehicleKind { Locomotive, Wagon, Coach } + +public enum Traction { Steam, Diesel, Electric, HighSpeed } + +public enum PaxClass { Worker, Staff } + +public enum TakeoverRule { Disabled, Ransom, Immediate } + +public enum IronmanRule { No, Optional, Yes } + +public enum DepletionRate { Slow, Normal, Fast } + +public enum InterventionEffect { Inspection, Service, Overhaul, Repair, Replace } + +public enum MaintenancePolicy { Economy, Standard, Thorough } + +public enum ContractKind { Connect, Deliver, GreatWork, Service } + +public enum Climate { Temperate, Alpine, Coastal, Dry } + +public enum HubKind { Port, Border } + +/// Rating di credito, dal migliore (AAA) al peggiore (D). +public enum CreditRating { AAA, AA, A, BBB, BB, B, CCC, CC, C, D } diff --git a/src/ViaFerrea.Core/Data/ErasDefs.cs b/src/ViaFerrea.Core/Data/ErasDefs.cs new file mode 100644 index 0000000..51b9141 --- /dev/null +++ b/src/ViaFerrea.Core/Data/ErasDefs.cs @@ -0,0 +1,67 @@ +using System.Text.Json.Serialization; + +namespace ViaFerrea.Core.Data; + +/// Contenuto di eras.json: introduzione di trazioni, ponti, gallerie, binari e segnali. +public sealed class ErasFile +{ + [JsonPropertyName("$schema")] public string? Schema { get; init; } + public required int Version { get; init; } + public required List Eras { get; init; } + public required List Tractions { get; init; } + public required List BridgeTypes { get; init; } + public required List TunnelLimits { get; init; } + public required List TrackClasses { get; init; } + public required List Signals { get; init; } + public required int ElectrificationFrom { get; init; } +} + +public sealed class EraDef +{ + public required string Id { get; init; } + [JsonPropertyName("name_it")] public required string NameIt { get; init; } + [JsonPropertyName("name_en")] public required string NameEn { get; init; } + public required int From { get; init; } +} + +public sealed class TractionDef +{ + public required Traction Id { get; init; } + [JsonPropertyName("name_it")] public required string NameIt { get; init; } + public required int From { get; init; } + public required bool NeedsElectrification { get; init; } +} + +public sealed class BridgeTypeDef +{ + public required string Id { get; init; } + [JsonPropertyName("name_it")] public required string NameIt { get; init; } + public required int From { get; init; } + public required double MaxSpanM { get; init; } + public required double CostMultiplier { get; init; } + public required int LifeYears { get; init; } +} + +public sealed class TunnelLimitDef +{ + public required int From { get; init; } + public required double MaxLengthM { get; init; } +} + +public sealed class TrackClassDef +{ + public required string Id { get; init; } + [JsonPropertyName("name_it")] public required string NameIt { get; init; } + public required double SpeedKmh { get; init; } + public required int From { get; init; } + + [JsonIgnore] public int Index { get; internal set; } +} + +public sealed class SignalTypeDef +{ + public required string Id { get; init; } + [JsonPropertyName("name_it")] public required string NameIt { get; init; } + public required int From { get; init; } + public required long Price { get; init; } +} diff --git a/src/ViaFerrea.Core/Data/GameData.cs b/src/ViaFerrea.Core/Data/GameData.cs new file mode 100644 index 0000000..33658b0 --- /dev/null +++ b/src/ViaFerrea.Core/Data/GameData.cs @@ -0,0 +1,197 @@ +using System.Buffers; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization.Metadata; +using ViaFerrea.Core.Common; + +namespace ViaFerrea.Core.Data; + +/// +/// Tutte le definizioni immutabili del gioco, caricate e validate da data/*.json. +/// Un'istanza è condivisa in sola lettura da mondo, server, strumenti e client. +/// +public sealed class GameData +{ + /// File dati nell'ordine canonico usato anche per l'hash. + public static readonly string[] FileNames = + [ + "goods.json", "industries.json", "vehicles.json", "eras.json", "tiers.json", "balance.json", + "difficulty.json", "construction.json", "maintenance.json", "ai.json", "contracts.json", "regions.json", + ]; + + public required IReadOnlyList Goods { get; init; } + public required IReadOnlyList Industries { get; init; } + public required IReadOnlyList Vehicles { get; init; } + public required ErasFile Eras { get; init; } + public required TiersFile Tiers { get; init; } + public required BalanceFile Balance { get; init; } + public required DifficultyFile Difficulty { get; init; } + public required ConstructionFile Construction { get; init; } + public required MaintenanceFile Maintenance { get; init; } + public required AiFile Ai { get; init; } + public required ContractsFile Contracts { get; init; } + public required RegionsFile Regions { get; init; } + + /// XxHash64 del contenuto canonico (minificato) di tutti i file: client e server devono coincidere. + public ulong Hash { get; private init; } + + /// Indice del bene «ricambi». + public int SparePartsGood { get; private set; } + + /// Indice del bene «macchinari». + public int MachineryGood { get; private set; } + + private Dictionary _goodIndex = new(StringComparer.Ordinal); + private Dictionary _industryIndex = new(StringComparer.Ordinal); + private Dictionary _vehicleIndex = new(StringComparer.Ordinal); + + public int GoodCount => Goods.Count; + + public GoodDef Good(string id) => Goods[GoodIndex(id)]; + + public int GoodIndex(string id) => + _goodIndex.TryGetValue(id, out int i) ? i : throw new KeyNotFoundException($"Bene sconosciuto: {id}"); + + public bool TryGoodIndex(string id, out int index) => _goodIndex.TryGetValue(id, out index); + + public IndustryDef Industry(string id) => + _industryIndex.TryGetValue(id, out int i) ? Industries[i] : throw new KeyNotFoundException($"Industria sconosciuta: {id}"); + + public bool TryIndustry(string id, out IndustryDef? def) + { + def = _industryIndex.TryGetValue(id, out int i) ? Industries[i] : null; + return def is not null; + } + + public VehicleDef Vehicle(string id) => + _vehicleIndex.TryGetValue(id, out int i) ? Vehicles[i] : throw new KeyNotFoundException($"Veicolo sconosciuto: {id}"); + + public bool TryVehicle(string id, out VehicleDef? def) + { + def = _vehicleIndex.TryGetValue(id, out int i) ? Vehicles[i] : null; + return def is not null; + } + + /// Preset di difficoltà per id. + public DifficultyDef DifficultyPreset(string id) => + Difficulty.Presets.FirstOrDefault(p => p.Id == id) ?? throw new KeyNotFoundException($"Difficoltà sconosciuta: {id}"); + + /// Carica i dati dalla cartella predefinita. + public static GameData LoadDefault() => Load(DirectoryDataSource.FindDefault()); + + /// + /// Carica, valida (schema e semantica) e indicizza tutti i file dati. In caso di errori + /// lancia con l'elenco completo. + /// + public static GameData Load(IDataSource source) + { + var errors = new List(); + var canonical = new ArrayBufferWriter(); + + GoodsFile? goods = Read(source, "goods.json", DataJsonContext.Default.GoodsFile, errors, canonical); + IndustriesFile? industries = Read(source, "industries.json", DataJsonContext.Default.IndustriesFile, errors, canonical); + VehiclesFile? vehicles = Read(source, "vehicles.json", DataJsonContext.Default.VehiclesFile, errors, canonical); + ErasFile? eras = Read(source, "eras.json", DataJsonContext.Default.ErasFile, errors, canonical); + TiersFile? tiers = Read(source, "tiers.json", DataJsonContext.Default.TiersFile, errors, canonical); + BalanceFile? balance = Read(source, "balance.json", DataJsonContext.Default.BalanceFile, errors, canonical); + DifficultyFile? difficulty = Read(source, "difficulty.json", DataJsonContext.Default.DifficultyFile, errors, canonical); + ConstructionFile? construction = Read(source, "construction.json", DataJsonContext.Default.ConstructionFile, errors, canonical); + MaintenanceFile? maintenance = Read(source, "maintenance.json", DataJsonContext.Default.MaintenanceFile, errors, canonical); + AiFile? ai = Read(source, "ai.json", DataJsonContext.Default.AiFile, errors, canonical); + ContractsFile? contracts = Read(source, "contracts.json", DataJsonContext.Default.ContractsFile, errors, canonical); + RegionsFile? regions = Read(source, "regions.json", DataJsonContext.Default.RegionsFile, errors, canonical); + + if (errors.Count > 0) throw new DataValidationException(errors); + + var data = new GameData + { + Goods = goods!.Goods, + Industries = industries!.Industries, + Vehicles = vehicles!.Vehicles, + Eras = eras!, + Tiers = tiers!, + Balance = balance!, + Difficulty = difficulty!, + Construction = construction!, + Maintenance = maintenance!, + Ai = ai!, + Contracts = contracts!, + Regions = regions!, + Hash = XxHash64.Hash(canonical.WrittenSpan), + }; + + DataValidator.Validate(data, errors); + if (errors.Count > 0) throw new DataValidationException(errors); + data.Index(); + return data; + } + + private static T? Read(IDataSource source, string file, JsonTypeInfo typeInfo, List errors, ArrayBufferWriter canonical) + where T : class + { + if (!source.Exists(file)) + { + errors.Add($"{file}: file mancante in {source.Description}"); + return null; + } + string schemaFile = "schema/" + file.Replace(".json", ".schema.json", StringComparison.Ordinal); + if (!source.Exists(schemaFile)) + { + errors.Add($"{file}: schema mancante ({schemaFile})"); + return null; + } + try + { + using var doc = JsonDocument.Parse(source.ReadText(file)); + using var schemaDoc = JsonDocument.Parse(source.ReadText(schemaFile)); + var schemaErrors = JsonSchemaValidator.Validate(doc.RootElement, schemaDoc.RootElement); + foreach (string e in schemaErrors) errors.Add($"{file}: {e}"); + if (schemaErrors.Count > 0) return null; + + // forma canonica per l'hash: nome del file + JSON minificato + canonical.Write(Encoding.UTF8.GetBytes(file)); + canonical.Write("\n"u8); + using (var writer = new Utf8JsonWriter(canonical, new JsonWriterOptions { Indented = false })) + doc.RootElement.WriteTo(writer); + canonical.Write("\n"u8); + + return doc.RootElement.Deserialize(typeInfo); + } + catch (JsonException ex) + { + errors.Add($"{file}: {ex.Message}"); + return null; + } + } + + // Assegna indici e risolve i riferimenti per id dopo la validazione. + private void Index() + { + _goodIndex = new Dictionary(StringComparer.Ordinal); + for (int i = 0; i < Goods.Count; i++) + { + Goods[i].Index = i; + _goodIndex[Goods[i].Id] = i; + } + _industryIndex = new Dictionary(StringComparer.Ordinal); + for (int i = 0; i < Industries.Count; i++) + { + var def = Industries[i]; + def.Index = i; + _industryIndex[def.Id] = i; + foreach (var item in def.Recipe.Inputs) item.GoodIndex = _goodIndex[item.Good]; + foreach (var item in def.Recipe.Outputs) item.GoodIndex = _goodIndex[item.Good]; + } + _vehicleIndex = new Dictionary(StringComparer.Ordinal); + for (int i = 0; i < Vehicles.Count; i++) + { + var def = Vehicles[i]; + def.Index = i; + _vehicleIndex[def.Id] = i; + def.GoodIndices = def.Goods?.Select(g => _goodIndex[g]).ToArray() ?? []; + } + for (int i = 0; i < Eras.TrackClasses.Count; i++) Eras.TrackClasses[i].Index = i; + SparePartsGood = _goodIndex["spare_parts"]; + MachineryGood = _goodIndex["machinery"]; + } +} diff --git a/src/ViaFerrea.Core/Data/GoodsDefs.cs b/src/ViaFerrea.Core/Data/GoodsDefs.cs new file mode 100644 index 0000000..358f34c --- /dev/null +++ b/src/ViaFerrea.Core/Data/GoodsDefs.cs @@ -0,0 +1,45 @@ +using System.Text.Json.Serialization; + +namespace ViaFerrea.Core.Data; + +/// Contenuto di goods.json. +public sealed class GoodsFile +{ + [JsonPropertyName("$schema")] public string? Schema { get; init; } + public required int Version { get; init; } + public required List Goods { get; init; } +} + +/// Definizione di un bene trasportabile. +public sealed class GoodDef +{ + public required string Id { get; init; } + [JsonPropertyName("name_it")] public required string NameIt { get; init; } + [JsonPropertyName("name_en")] public required string NameEn { get; init; } + public required GoodCategory Category { get; init; } + public required string Unit { get; init; } + public required WagonType Wagon { get; init; } + /// Prezzo base Pb in centesimi per unità. + public required long BasePrice { get; init; } + /// Elasticità della domanda al prezzo. + public required double Elasticity { get; init; } + public required int DecayDaysAtStation { get; init; } + public required int Era { get; init; } + /// Consumo da parte delle città, se il bene è richiesto dalla popolazione. + public TownDemandDef? Town { get; init; } + /// Bene di servizio (ricambi, macchinari) consumato dalla manutenzione. + public bool Service { get; init; } + + /// Indice nell'elenco dei beni (assegnato al caricamento). + [JsonIgnore] public int Index { get; internal set; } +} + +/// Domanda cittadina di un bene. +public sealed class TownDemandDef +{ + public required TownCategory Category { get; init; } + /// Unità al giorno ogni 1.000 abitanti al prezzo base. + public required double DemandPerThousand { get; init; } + /// Anno dopo il quale le città smettono di richiederlo (facoltativo). + public int? UntilYear { get; init; } +} diff --git a/src/ViaFerrea.Core/Data/IndustryDefs.cs b/src/ViaFerrea.Core/Data/IndustryDefs.cs new file mode 100644 index 0000000..0b778ed --- /dev/null +++ b/src/ViaFerrea.Core/Data/IndustryDefs.cs @@ -0,0 +1,70 @@ +using System.Text.Json.Serialization; + +namespace ViaFerrea.Core.Data; + +/// Contenuto di industries.json. +public sealed class IndustriesFile +{ + [JsonPropertyName("$schema")] public string? Schema { get; init; } + public required int Version { get; init; } + public required List Industries { get; init; } +} + +/// Tipo di industria. +public sealed class IndustryDef +{ + public required string Id { get; init; } + [JsonPropertyName("name_it")] public required string NameIt { get; init; } + [JsonPropertyName("name_en")] public required string NameEn { get; init; } + public required IndustryKind Kind { get; init; } + public required RecipeDef Recipe { get; init; } + public required int CycleDays { get; init; } + /// Unità del primo output al mese a efficienza 1, per livello (1–5). + public required int[] CapacityPerLevel { get; init; } + public required int[] WorkersPerLevel { get; init; } + public required int[] StaffPerLevel { get; init; } + public required int StorageDays { get; init; } + public required double WearIntensity { get; init; } + public required Footprint Footprint { get; init; } + public required PlacementDef Placement { get; init; } + public required bool Depletable { get; init; } + public required int Era { get; init; } + /// Costo di ammodernamento per livello, in centesimi. + public required long UpgradeCost { get; init; } + /// Peso relativo nella generazione della mappa. + public required double SpawnWeight { get; init; } + + [JsonIgnore] public int Index { get; internal set; } + + /// Capacità mensile al livello dato (1–5). + public int Capacity(int level) => CapacityPerLevel[Math.Clamp(level, 1, CapacityPerLevel.Length) - 1]; + public int Workers(int level) => WorkersPerLevel[Math.Clamp(level, 1, WorkersPerLevel.Length) - 1]; + public int Staff(int level) => StaffPerLevel[Math.Clamp(level, 1, StaffPerLevel.Length) - 1]; +} + +/// Ricetta: input e output per ciclo produttivo. +public sealed class RecipeDef +{ + public required List Inputs { get; init; } + public required List Outputs { get; init; } +} + +public sealed class RecipeItemDef +{ + public required string Good { get; init; } + public required int PerCycle { get; init; } + + /// Indice del bene risolto al caricamento. + [JsonIgnore] public int GoodIndex { get; internal set; } +} + +/// Regole di collocazione nella generazione e nella nascita di nuove industrie. +public sealed class PlacementDef +{ + public required PlacementNeed Needs { get; init; } + public ResourceKind? Resource { get; init; } + public double? MinTownDistanceKm { get; init; } + public double? MaxTownDistanceKm { get; init; } + public double? MaxInputDistanceKm { get; init; } + public int? MinTownPopulation { get; init; } +} diff --git a/src/ViaFerrea.Core/Data/JsonSchemaValidator.cs b/src/ViaFerrea.Core/Data/JsonSchemaValidator.cs new file mode 100644 index 0000000..5e87481 --- /dev/null +++ b/src/ViaFerrea.Core/Data/JsonSchemaValidator.cs @@ -0,0 +1,286 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace ViaFerrea.Core.Data; + +/// +/// Validatore di un sottoinsieme di JSON Schema (draft 2020-12), sufficiente per gli schemi +/// di data/schema: type, properties, required, additionalProperties, items, minItems, +/// maxItems, uniqueItems, enum, const, minimum, maximum, exclusiveMinimum, exclusiveMaximum, +/// minLength, maxLength, pattern, $ref locali (#/$defs/… e #/definitions/…), anyOf, oneOf, allOf. +/// Le parole chiave non supportate vengono segnalate come errore, così uno schema non può +/// sembrare più severo di quanto sia. +/// +public static class JsonSchemaValidator +{ + private static readonly HashSet Annotations = + ["$schema", "$id", "title", "description", "$comment", "default", "examples", "$defs", "definitions"]; + + private static readonly HashSet Supported = + [ + "type", "properties", "required", "additionalProperties", "items", "minItems", "maxItems", "uniqueItems", + "enum", "const", "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "minLength", "maxLength", + "pattern", "$ref", "anyOf", "oneOf", "allOf", + ]; + + /// Valida l'istanza contro lo schema; restituisce gli errori con il percorso JSON. + public static List Validate(JsonElement instance, JsonElement schema) + { + var errors = new List(); + ValidateNode(instance, schema, schema, "$", errors); + return errors; + } + + private static void ValidateNode(JsonElement value, JsonElement schema, JsonElement root, string path, List errors) + { + if (schema.ValueKind == JsonValueKind.True) return; + if (schema.ValueKind == JsonValueKind.False) + { + errors.Add($"{path}: valore non ammesso"); + return; + } + if (schema.ValueKind != JsonValueKind.Object) + { + errors.Add($"{path}: schema non valido"); + return; + } + + foreach (var kw in schema.EnumerateObject()) + { + if (!Supported.Contains(kw.Name) && !Annotations.Contains(kw.Name)) + errors.Add($"{path}: parola chiave di schema non supportata «{kw.Name}»"); + } + + if (schema.TryGetProperty("$ref", out var refEl)) + { + var target = Resolve(root, refEl.GetString() ?? ""); + if (target is null) errors.Add($"{path}: riferimento non risolto {refEl.GetString()}"); + else ValidateNode(value, target.Value, root, path, errors); + } + + if (schema.TryGetProperty("type", out var typeEl) && !MatchesType(value, typeEl)) + { + errors.Add($"{path}: tipo atteso {TypeText(typeEl)}, trovato {KindText(value)}"); + return; + } + + if (schema.TryGetProperty("enum", out var enumEl)) + { + bool found = false; + foreach (var option in enumEl.EnumerateArray()) + { + if (JsonEquals(option, value)) { found = true; break; } + } + if (!found) errors.Add($"{path}: valore {Short(value)} non tra quelli ammessi"); + } + if (schema.TryGetProperty("const", out var constEl) && !JsonEquals(constEl, value)) + errors.Add($"{path}: valore atteso {Short(constEl)}"); + + switch (value.ValueKind) + { + case JsonValueKind.Object: + ValidateObject(value, schema, root, path, errors); + break; + case JsonValueKind.Array: + ValidateArray(value, schema, root, path, errors); + break; + case JsonValueKind.String: + ValidateString(value, schema, path, errors); + break; + case JsonValueKind.Number: + ValidateNumber(value, schema, path, errors); + break; + } + + if (schema.TryGetProperty("allOf", out var allOf)) + { + foreach (var sub in allOf.EnumerateArray()) ValidateNode(value, sub, root, path, errors); + } + if (schema.TryGetProperty("anyOf", out var anyOf)) + { + bool ok = anyOf.EnumerateArray().Any(sub => IsValid(value, sub, root, path)); + if (!ok) errors.Add($"{path}: nessuna alternativa di anyOf è soddisfatta"); + } + if (schema.TryGetProperty("oneOf", out var oneOf)) + { + int count = oneOf.EnumerateArray().Count(sub => IsValid(value, sub, root, path)); + if (count != 1) errors.Add($"{path}: soddisfatte {count} alternative di oneOf invece di una"); + } + } + + private static bool IsValid(JsonElement value, JsonElement schema, JsonElement root, string path) + { + var sub = new List(); + ValidateNode(value, schema, root, path, sub); + return sub.Count == 0; + } + + private static void ValidateObject(JsonElement value, JsonElement schema, JsonElement root, string path, List errors) + { + schema.TryGetProperty("properties", out var props); + if (schema.TryGetProperty("required", out var required)) + { + foreach (var name in required.EnumerateArray()) + { + string n = name.GetString() ?? ""; + if (!value.TryGetProperty(n, out _)) errors.Add($"{path}: manca la proprietà obbligatoria «{n}»"); + } + } + bool hasAdditional = schema.TryGetProperty("additionalProperties", out var additional); + foreach (var p in value.EnumerateObject()) + { + string childPath = $"{path}.{p.Name}"; + if (props.ValueKind == JsonValueKind.Object && props.TryGetProperty(p.Name, out var propSchema)) + { + ValidateNode(p.Value, propSchema, root, childPath, errors); + } + else if (hasAdditional) + { + if (additional.ValueKind == JsonValueKind.False) + errors.Add($"{path}: proprietà non ammessa «{p.Name}»"); + else + ValidateNode(p.Value, additional, root, childPath, errors); + } + } + } + + private static void ValidateArray(JsonElement value, JsonElement schema, JsonElement root, string path, List errors) + { + int length = value.GetArrayLength(); + if (schema.TryGetProperty("minItems", out var minItems) && length < minItems.GetInt32()) + errors.Add($"{path}: almeno {minItems.GetInt32()} elementi richiesti, trovati {length}"); + if (schema.TryGetProperty("maxItems", out var maxItems) && length > maxItems.GetInt32()) + errors.Add($"{path}: al massimo {maxItems.GetInt32()} elementi ammessi, trovati {length}"); + if (schema.TryGetProperty("items", out var items)) + { + int i = 0; + foreach (var element in value.EnumerateArray()) + ValidateNode(element, items, root, $"{path}[{i++}]", errors); + } + if (schema.TryGetProperty("uniqueItems", out var unique) && unique.ValueKind == JsonValueKind.True) + { + var seen = new List(); + foreach (var element in value.EnumerateArray()) + { + if (seen.Any(s => JsonEquals(s, element))) errors.Add($"{path}: elemento duplicato {Short(element)}"); + else seen.Add(element); + } + } + } + + private static void ValidateString(JsonElement value, JsonElement schema, string path, List errors) + { + string s = value.GetString() ?? ""; + int length = new StringInfo(s).LengthInTextElements; + if (schema.TryGetProperty("minLength", out var minLength) && length < minLength.GetInt32()) + errors.Add($"{path}: stringa troppo corta"); + if (schema.TryGetProperty("maxLength", out var maxLength) && length > maxLength.GetInt32()) + errors.Add($"{path}: stringa troppo lunga"); + if (schema.TryGetProperty("pattern", out var pattern) && + !Regex.IsMatch(s, pattern.GetString() ?? "", RegexOptions.CultureInvariant, TimeSpan.FromSeconds(1))) + errors.Add($"{path}: «{s}» non rispetta il formato {pattern.GetString()}"); + } + + private static void ValidateNumber(JsonElement value, JsonElement schema, string path, List errors) + { + double d = value.GetDouble(); + if (schema.TryGetProperty("minimum", out var min) && d < min.GetDouble()) + errors.Add($"{path}: {Short(value)} minore del minimo {Short(min)}"); + if (schema.TryGetProperty("maximum", out var max) && d > max.GetDouble()) + errors.Add($"{path}: {Short(value)} maggiore del massimo {Short(max)}"); + if (schema.TryGetProperty("exclusiveMinimum", out var emin) && d <= emin.GetDouble()) + errors.Add($"{path}: {Short(value)} deve essere maggiore di {Short(emin)}"); + if (schema.TryGetProperty("exclusiveMaximum", out var emax) && d >= emax.GetDouble()) + errors.Add($"{path}: {Short(value)} deve essere minore di {Short(emax)}"); + } + + private static JsonElement? Resolve(JsonElement root, string reference) + { + if (!reference.StartsWith("#/", StringComparison.Ordinal)) return null; + var current = root; + foreach (var part in reference[2..].Split('/')) + { + string key = part.Replace("~1", "/").Replace("~0", "~"); + if (current.ValueKind != JsonValueKind.Object || !current.TryGetProperty(key, out current)) return null; + } + return current; + } + + private static bool MatchesType(JsonElement value, JsonElement typeEl) + { + if (typeEl.ValueKind == JsonValueKind.Array) + return typeEl.EnumerateArray().Any(t => MatchesSingle(value, t.GetString() ?? "")); + return MatchesSingle(value, typeEl.GetString() ?? ""); + } + + private static bool MatchesSingle(JsonElement value, string type) => type switch + { + "object" => value.ValueKind == JsonValueKind.Object, + "array" => value.ValueKind == JsonValueKind.Array, + "string" => value.ValueKind == JsonValueKind.String, + "boolean" => value.ValueKind is JsonValueKind.True or JsonValueKind.False, + "null" => value.ValueKind == JsonValueKind.Null, + "number" => value.ValueKind == JsonValueKind.Number, + "integer" => value.ValueKind == JsonValueKind.Number && IsInteger(value), + _ => false, + }; + + private static bool IsInteger(JsonElement value) + { + if (value.TryGetInt64(out _)) return true; + double d = value.GetDouble(); + return Math.Floor(d) == d && !double.IsInfinity(d); + } + + private static bool JsonEquals(JsonElement a, JsonElement b) + { + if (a.ValueKind == JsonValueKind.Number && b.ValueKind == JsonValueKind.Number) + return a.GetDouble() == b.GetDouble(); + if (a.ValueKind != b.ValueKind) return false; + switch (a.ValueKind) + { + case JsonValueKind.String: + return a.GetString() == b.GetString(); + case JsonValueKind.True: + case JsonValueKind.False: + case JsonValueKind.Null: + return true; + case JsonValueKind.Array: + if (a.GetArrayLength() != b.GetArrayLength()) return false; + return a.EnumerateArray().Zip(b.EnumerateArray()).All(p => JsonEquals(p.First, p.Second)); + case JsonValueKind.Object: + var pa = a.EnumerateObject().OrderBy(p => p.Name, StringComparer.Ordinal).ToList(); + var pb = b.EnumerateObject().OrderBy(p => p.Name, StringComparer.Ordinal).ToList(); + if (pa.Count != pb.Count) return false; + for (int i = 0; i < pa.Count; i++) + { + if (pa[i].Name != pb[i].Name || !JsonEquals(pa[i].Value, pb[i].Value)) return false; + } + return true; + default: + return false; + } + } + + private static string TypeText(JsonElement typeEl) => typeEl.ValueKind == JsonValueKind.Array + ? string.Join("|", typeEl.EnumerateArray().Select(t => t.GetString())) + : typeEl.GetString() ?? "?"; + + private static string KindText(JsonElement value) => value.ValueKind switch + { + JsonValueKind.Object => "object", + JsonValueKind.Array => "array", + JsonValueKind.String => "string", + JsonValueKind.Number => IsInteger(value) ? "integer" : "number", + JsonValueKind.True or JsonValueKind.False => "boolean", + JsonValueKind.Null => "null", + _ => "undefined", + }; + + private static string Short(JsonElement value) + { + string raw = value.GetRawText(); + return raw.Length > 40 ? raw[..37] + "..." : raw; + } +} diff --git a/src/ViaFerrea.Core/Data/MaintenanceDefs.cs b/src/ViaFerrea.Core/Data/MaintenanceDefs.cs new file mode 100644 index 0000000..3b44f3b --- /dev/null +++ b/src/ViaFerrea.Core/Data/MaintenanceDefs.cs @@ -0,0 +1,142 @@ +using System.Text.Json.Serialization; + +namespace ViaFerrea.Core.Data; + +// Contenuto di maintenance.json (guida, sezione 10). + +public sealed class MaintenanceFile +{ + [JsonPropertyName("$schema")] public string? Schema { get; init; } + public required int Version { get; init; } + public required ComponentSets Components { get; init; } + public required WearParams Wear { get; init; } + public required FailureParams Failure { get; init; } + public required ConditionEffects Effects { get; init; } + public required List Interventions { get; init; } + public required InspectionParams Inspection { get; init; } + public required ServiceParams Service { get; init; } + public required OverhaulParams Overhaul { get; init; } + public required DepotParams Depots { get; init; } + public required List Policies { get; init; } + public required ServiceIntervals Intervals { get; init; } + public required PlannerParams Planner { get; init; } +} + +public sealed class ComponentSets +{ + public required List Locomotive { get; init; } + public required List Car { get; init; } +} + +public sealed class ComponentDef +{ + public required string Id { get; init; } + [JsonPropertyName("name_it")] public required string NameIt { get; init; } + public required double FailureWeight { get; init; } + public required double WearPer100Km { get; init; } +} + +public sealed class WearParams +{ + public required double GradientThreshold { get; init; } + public required double GradientWeight { get; init; } + public required double HighSpeedThreshold { get; init; } + public required double HighSpeedWeight { get; init; } + public required double LoadWeight { get; init; } + public required int AgeStepYears { get; init; } + public required double AgeStepFactor { get; init; } +} + +public sealed class FailureParams +{ + public required double H0 { get; init; } + public required double Slope { get; init; } + public required double Pivot { get; init; } + public required double Scale { get; init; } + public required double HealthyDivisor { get; init; } + public required double MinorShare { get; init; } + public required double MajorShare { get; init; } + public required double CatastrophicShare { get; init; } + public required double CatastrophicMaxCondition { get; init; } + public required double CatastrophicMinSpeedShare { get; init; } + public required double MinorSpeedFactor { get; init; } + public required double RescueSpeedKmh { get; init; } + public required double RescueExtraHours { get; init; } + public required int DerailmentTrackDays { get; init; } + public required double DerailmentSatisfaction { get; init; } +} + +public sealed class ConditionEffects +{ + public required double EngineSpeedBelow { get; init; } + public required double EngineSpeedBase { get; init; } + public required double EngineSpeedSpan { get; init; } + public required double FuelPenalty { get; init; } + public required double ComfortMin { get; init; } + public required double ComfortMax { get; init; } +} + +public sealed class InterventionDef +{ + public required string Id { get; init; } + [JsonPropertyName("name_it")] public required string NameIt { get; init; } + public required int Days { get; init; } + public required double CostShare { get; init; } + public required int SpareParts { get; init; } + public required InterventionEffect Effect { get; init; } + public double? RestoreTo { get; init; } +} + +public sealed class InspectionParams +{ + public required double BrakesTo { get; init; } + public required double OthersPlus { get; init; } + public required double HazardFactor { get; init; } + public required int HazardDays { get; init; } +} + +public sealed class ServiceParams +{ + public required double Plus { get; init; } +} + +public sealed class OverhaulParams +{ + public required double AgeFactorReduction { get; init; } +} + +public sealed class DepotParams +{ + public required Dictionary StallsBySize { get; init; } + public required int StaffPerStall { get; init; } + public required double SlowdownAtHalfStaff { get; init; } + public required int InitialSpareParts { get; init; } + public required int JobsWorkersPerStall { get; init; } +} + +public sealed class PolicyDef +{ + public required MaintenancePolicy Id { get; init; } + [JsonPropertyName("name_it")] public required string NameIt { get; init; } + public required double IntervalFactor { get; init; } + public required double EffectFactor { get; init; } + public required double CostFactor { get; init; } +} + +public sealed class ServiceIntervals +{ + public required double InspectionKm { get; init; } + public required int InspectionDays { get; init; } + public required double ServiceKm { get; init; } + public required int ServiceDays { get; init; } + public required int OverhaulYears { get; init; } +} + +public sealed class PlannerParams +{ + public required double TargetCondition { get; init; } + public required int AverageDays { get; init; } + public required int MarginDays { get; init; } + public required double AlertCondition { get; init; } + public required double CriticalCondition { get; init; } +} diff --git a/src/ViaFerrea.Core/Data/RegionsDefs.cs b/src/ViaFerrea.Core/Data/RegionsDefs.cs new file mode 100644 index 0000000..d72ee1a --- /dev/null +++ b/src/ViaFerrea.Core/Data/RegionsDefs.cs @@ -0,0 +1,60 @@ +using System.Text.Json.Serialization; + +namespace ViaFerrea.Core.Data; + +// Contenuto di regions.json (guida, sezione 13.1) e serbatoi di nomi. + +public sealed class RegionsFile +{ + [JsonPropertyName("$schema")] public string? Schema { get; init; } + public required int Version { get; init; } + public required ConcessionParams Concessions { get; init; } + public required List Regions { get; init; } + public required List NamePools { get; init; } + public required List IndustryNameTemplates { get; init; } + public required List FeatureNames { get; init; } +} + +public sealed class ConcessionParams +{ + public required int UnlockTier { get; init; } + public required long BasePrice { get; init; } + public required double PriceGrowth { get; init; } + public required int MaxRegions { get; init; } +} + +public sealed class RegionDef +{ + public required string Id { get; init; } + [JsonPropertyName("name_it")] public required string NameIt { get; init; } + public required Climate Climate { get; init; } + public required double TerrainDifficulty { get; init; } + public required ResourceAbundance Resources { get; init; } + public required List Hubs { get; init; } + public required string NamePool { get; init; } +} + +public sealed class ResourceAbundance +{ + public required double Coal { get; init; } + public required double Iron { get; init; } + public required double Stone { get; init; } + public required double Oil { get; init; } + + public double For(ResourceKind kind) => kind switch + { + ResourceKind.Coal => Coal, + ResourceKind.Iron => Iron, + ResourceKind.Stone => Stone, + _ => Oil, + }; +} + +public sealed class NamePoolDef +{ + public required string Id { get; init; } + public required List Prefixes { get; init; } + public required List Roots { get; init; } + public required List Suffixes { get; init; } + public required List Saints { get; init; } +} diff --git a/src/ViaFerrea.Core/Data/TiersDefs.cs b/src/ViaFerrea.Core/Data/TiersDefs.cs new file mode 100644 index 0000000..1dccc2d --- /dev/null +++ b/src/ViaFerrea.Core/Data/TiersDefs.cs @@ -0,0 +1,48 @@ +using System.Text.Json.Serialization; + +namespace ViaFerrea.Core.Data; + +/// Contenuto di tiers.json: livelli della compagnia e sblocchi. +public sealed class TiersFile +{ + [JsonPropertyName("$schema")] public string? Schema { get; init; } + public required int Version { get; init; } + public required List RatingScale { get; init; } + public required List Tiers { get; init; } +} + +public sealed class TierDef +{ + public required int Level { get; init; } + [JsonPropertyName("name_it")] public required string NameIt { get; init; } + [JsonPropertyName("name_en")] public required string NameEn { get; init; } + public required TierRequirements Requirements { get; init; } + public required TierUnlocks Unlocks { get; init; } +} + +public sealed class TierRequirements +{ + /// Patrimonio netto minimo in centesimi. + public required long NetWorth { get; init; } + public required ConnectedTownsRequirement ConnectedTownsOver { get; init; } + /// Rating minimo (uguale o migliore). + public required CreditRating CreditRating { get; init; } +} + +public sealed class ConnectedTownsRequirement +{ + public required int Count { get; init; } + public required int Population { get; init; } +} + +public sealed class TierUnlocks +{ + /// Fido massimo come multiplo del fido iniziale della difficoltà. + public required double MaxLoanFactor { get; init; } + public required int Crews { get; init; } + public required bool Trading { get; init; } + public required bool BuyIndustry { get; init; } + public required bool Ipo { get; init; } + public required bool HostileTakeover { get; init; } + public required bool Concessions { get; init; } +} diff --git a/src/ViaFerrea.Core/Data/VehicleDefs.cs b/src/ViaFerrea.Core/Data/VehicleDefs.cs new file mode 100644 index 0000000..2d633de --- /dev/null +++ b/src/ViaFerrea.Core/Data/VehicleDefs.cs @@ -0,0 +1,44 @@ +using System.Text.Json.Serialization; + +namespace ViaFerrea.Core.Data; + +/// Contenuto di vehicles.json. +public sealed class VehiclesFile +{ + [JsonPropertyName("$schema")] public string? Schema { get; init; } + public required int Version { get; init; } + public required List Vehicles { get; init; } +} + +/// Modello di veicolo: locomotiva, carro merci o carrozza. +public sealed class VehicleDef +{ + public required string Id { get; init; } + public required VehicleKind Kind { get; init; } + [JsonPropertyName("name_it")] public required string NameIt { get; init; } + [JsonPropertyName("name_en")] public required string NameEn { get; init; } + public required int EraFrom { get; init; } + public int? EraTo { get; init; } + public double PowerKw { get; init; } + public double TractiveEffortKn { get; init; } + public required double MaxSpeedKmh { get; init; } + public required double MassT { get; init; } + public required double LengthM { get; init; } + public required long Price { get; init; } + public required long RunningCostPerYear { get; init; } + public required int LifeYears { get; init; } + public Traction? Traction { get; init; } + /// Moltiplicatori di usura per componente. + public required Dictionary Components { get; init; } + /// Carri: capacità in unità. + public int? Capacity { get; init; } + public WagonType? WagonType { get; init; } + public List? Goods { get; init; } + /// Carrozze: posti. + public int? PaxCapacity { get; init; } + public PaxClass? Class { get; init; } + + [JsonIgnore] public int Index { get; internal set; } + /// Indici dei beni trasportabili (carri). + [JsonIgnore] public int[] GoodIndices { get; internal set; } = []; +} diff --git a/src/ViaFerrea.Core/Economy/Company.cs b/src/ViaFerrea.Core/Economy/Company.cs new file mode 100644 index 0000000..f822c59 --- /dev/null +++ b/src/ViaFerrea.Core/Economy/Company.cs @@ -0,0 +1,103 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Data; + +namespace ViaFerrea.Core.Economy; + +/// Voci del conto economico di una compagnia. +public enum LedgerEntry : byte +{ + FreightRevenue = 0, + PassengerRevenue = 1, + Construction = 2, + VehiclePurchase = 3, + VehicleSale = 4, + RunningCosts = 5, + TrackMaintenance = 6, + FleetMaintenance = 7, + Wages = 8, + Interest = 9, + LoanTaken = 10, + LoanRepaid = 11, + Trading = 12, + IndustryPurchase = 13, + Dividends = 14, + Shares = 15, + Contracts = 16, + Penalties = 17, + Other = 18, +} + +/// Prestito con rata costante (ammortamento alla francese). +public sealed class Loan +{ + public required LoanId Id { get; init; } + public required Money Principal { get; init; } + public required double AnnualRate { get; init; } + public required int TermMonths { get; init; } + public Money Remaining { get; set; } + public int MonthsLeft { get; set; } +} + +/// Compagnia ferroviaria (giocatore o IA). +public sealed class Company +{ + public const int EntryCount = 19; + + public required CompanyId Id { get; init; } + public required string Name { get; set; } + public required bool IsPlayer { get; init; } + public string? AiPersonality { get; init; } + public required string Color { get; init; } + + public Money Cash { get; set; } + public List Loans { get; } = []; + + /// Fido iniziale della difficoltà (base del fido massimo per livello). + public Money BaseCredit { get; set; } + + public CreditRating Rating { get; set; } = CreditRating.BB; + public int Tier { get; set; } = 1; + public int NegativeCashDays { get; set; } + public bool Bankrupt { get; set; } + public long FoundedDay { get; init; } + + /// Movimenti del mese corrente per voce (centesimi, segno del flusso di cassa). + public long[] MonthEntries { get; } = new long[EntryCount]; + + /// Movimenti dell'anno corrente per voce. + public long[] YearEntries { get; } = new long[EntryCount]; + + /// Movimenti dell'anno precedente per voce (per rating e borsa). + public long[] LastYearEntries { get; } = new long[EntryCount]; + + /// Valore contabile degli attivi non monetari (binari, stazioni, veicoli), aggiornato mensilmente. + public Money AssetBookValue { get; set; } + + public Money Debt + { + get + { + long sum = 0; + foreach (var l in Loans) sum += l.Remaining.Cents; + return new Money(sum); + } + } + + /// Patrimonio netto = cassa + attivi a valore di libro − debiti. + public Money NetWorth => Cash + AssetBookValue - Debt; + + /// Utile operativo dell'anno indicato (ricavi meno costi d'esercizio, esclusi prestiti e investimenti). + public static long OperatingProfit(long[] entries) + { + long revenue = entries[(int)LedgerEntry.FreightRevenue] + entries[(int)LedgerEntry.PassengerRevenue] + + entries[(int)LedgerEntry.Trading] + entries[(int)LedgerEntry.Contracts]; + long costs = entries[(int)LedgerEntry.RunningCosts] + entries[(int)LedgerEntry.TrackMaintenance] + + entries[(int)LedgerEntry.FleetMaintenance] + entries[(int)LedgerEntry.Wages] + + entries[(int)LedgerEntry.Interest] + entries[(int)LedgerEntry.Penalties]; + return revenue + costs; // i costi sono già negativi + } + + public static long Revenue(long[] entries) => + entries[(int)LedgerEntry.FreightRevenue] + entries[(int)LedgerEntry.PassengerRevenue] + + Math.Max(0, entries[(int)LedgerEntry.Trading]) + Math.Max(0, entries[(int)LedgerEntry.Contracts]); +} diff --git a/src/ViaFerrea.Core/Economy/Employment.cs b/src/ViaFerrea.Core/Economy/Employment.cs new file mode 100644 index 0000000..ede7522 --- /dev/null +++ b/src/ViaFerrea.Core/Economy/Employment.cs @@ -0,0 +1,49 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Data; + +namespace ViaFerrea.Core.Economy; + +/// Tipo di posto di lavoro. +public enum WorkplaceKind : byte { Industry = 0, Depot = 1 } + +/// Riferimento a un posto di lavoro (industria o deposito della compagnia). +public readonly record struct WorkplaceRef(WorkplaceKind Kind, int Index) +{ + public static WorkplaceRef Of(IndustryId id) => new(WorkplaceKind.Industry, id.Value); + public static WorkplaceRef Of(DepotId id) => new(WorkplaceKind.Depot, id.Value); +} + +/// +/// Contratto casa-lavoro (guida, sezione 9): un gruppo di residenti di una città lavora in un +/// posto preciso e lo raggiunge a piedi (Carrier = None) o con le linee di un vettore. +/// +public sealed class CommuteContract +{ + public required ContractId Id { get; init; } + public required TownId Town { get; init; } + public required WorkplaceRef Workplace { get; init; } + public required PaxClass Category { get; init; } + public required int Headcount { get; set; } + + /// Vettore: None per chi va a piedi. + public CompanyId Carrier { get; set; } = CompanyId.None; + public StationId HomeStation { get; set; } = StationId.None; + public StationId WorkStation { get; set; } = StationId.None; + + /// Linee e cambi del percorso (vuoto a piedi). + public List Route { get; } = []; + + /// Durata attesa in minuti di orologio dei treni. + public double ExpectedMinutes { get; set; } + + /// Copertura (EMA su 30 giorni di arrivati/Headcount). + public double Coverage { get; set; } = 1; + + /// Giorni consecutivi con copertura sotto la soglia di scioglimento. + public int LowCoverageDays { get; set; } + + /// Arrivati oggi (pendolari consegnati dal vettore o a piedi). + public int ArrivedToday { get; set; } + + public bool Walking => !Carrier.IsValid; +} diff --git a/src/ViaFerrea.Core/Economy/Hub.cs b/src/ViaFerrea.Core/Economy/Hub.cs new file mode 100644 index 0000000..423ffe8 --- /dev/null +++ b/src/ViaFerrea.Core/Economy/Hub.cs @@ -0,0 +1,35 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Data; + +namespace ViaFerrea.Core.Economy; + +/// +/// Hub verso il mercato mondiale (porto o valico): importa ed esporta qualsiasi bene al prezzo +/// globale con un dazio, entro una capacità mensile complessiva. +/// +public sealed class Hub +{ + public required HubId Id { get; init; } + public required HubKind Kind { get; init; } + public required string Name { get; init; } + public required int CellX { get; init; } + public required int CellY { get; init; } + public required int FootprintCells { get; init; } + public required Vec2 Position { get; init; } + public required int MonthlyCapacity { get; set; } + public required double Duty { get; set; } + + /// Unità movimentate nel mese corrente (import + export). + public int UsedThisMonth { get; set; } + + public int[] ImportedThisMonth { get; init; } = []; + public int[] ExportedThisMonth { get; init; } = []; + + public int RemainingCapacity => Math.Max(0, MonthlyCapacity - UsedThisMonth); + + /// Prezzo a cui l'hub vende (importazione). + public double SellPrice(double globalPrice) => globalPrice * (1 + Duty); + + /// Prezzo a cui l'hub compra (esportazione). + public double BuyPrice(double globalPrice) => globalPrice * (1 - Duty); +} diff --git a/src/ViaFerrea.Core/Economy/Industry.cs b/src/ViaFerrea.Core/Economy/Industry.cs new file mode 100644 index 0000000..52fc5a1 --- /dev/null +++ b/src/ViaFerrea.Core/Economy/Industry.cs @@ -0,0 +1,139 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Data; + +namespace ViaFerrea.Core.Economy; + +/// Budget di manutenzione degli impianti scelto dal proprietario (guida, sezione 11). +public enum IndustryBudget : byte { None = 0, Base = 1, High = 2 } + +/// +/// Industria: produce secondo la ricetta del suo tipo, con efficienza +/// e = min(copertura input, lavoratori, personale) × fattore di profitto × condizione impianti. +/// +public sealed class Industry +{ + public required IndustryId Id { get; init; } + public required IndustryDef Def { get; init; } + public required string Name { get; set; } + public required int CellX { get; init; } + public required int CellY { get; init; } + public required int FootprintCells { get; init; } + public required Vec2 Position { get; init; } + + /// Livello 0–5; il livello 0 è dormiente (nessuna produzione) e porta alla chiusura. + public int Level { get; set; } + + public bool Closed { get; set; } + + /// Giacimento sfruttato (industrie esauribili). + public ResourceSiteId Site { get; init; } = ResourceSiteId.None; + + /// Proprietario: None per le industrie dei privati (NPC). + public CompanyId Owner { get; set; } = CompanyId.None; + + /// Cassa dell'impresa (conto del registro). + public Money Cash { get; set; } + + /// Condizione degli impianti 0–100 (sezione 11). + public double Condition { get; set; } = 100; + + public IndustryBudget Budget { get; set; } = IndustryBudget.Base; + + /// Scorte degli input, allineate a Def.Recipe.Inputs. + public int[] InputStock { get; init; } = []; + + /// Scorte degli output, allineate a Def.Recipe.Outputs. + public int[] OutputStock { get; init; } = []; + + /// Cicli produttivi frazionari non ancora eseguiti. + public double CycleAccumulator { get; set; } + + /// Coperture medie (EMA su 30 giorni) di input, lavoratori e personale. + public double CovInput { get; set; } = 1; + public double CovWorkers { get; set; } + public double CovStaff { get; set; } + + /// Efficienza dell'ultimo giorno. + public double Efficiency { get; set; } + + /// Lavoratori e personale presenti oggi (quota in sede + pendolari arrivati), frazionari. + public double WorkersPresent { get; set; } + public double StaffPresent { get; set; } + + /// Lavoratori e personale con contratto di pendolarismo (esclusi quelli in sede). + public int ContractedWorkers { get; set; } + public int ContractedStaff { get; set; } + + /// Ricavi e costi medi giornalieri (EMA su 90 giorni) per il margine. + public double RevenueEma { get; set; } + public double CostEma { get; set; } + + /// Statistiche del trimestre corrente. + public long QuarterProduced { get; set; } + public long QuarterShipped { get; set; } + public double QuarterCoverageSum { get; set; } + public int QuarterDays { get; set; } + + public int QuartersAboveUpgrade { get; set; } + public int QuartersAtZero { get; set; } + public double LastScore { get; set; } + + /// Servita da un vettore (stazione con bacino che la include): solo allora cresce o regredisce (ADR 0004). + public bool Served { get; set; } + + /// Vendite e acquisti del giorno corrente (centesimi), per il margine. + public double SalesToday { get; set; } + public double PurchasesToday { get; set; } + + /// Unità del primo output spedite oggi (ritirate da vettori o trasporto locale). + public int ShippedToday { get; set; } + + /// Produzione dell'ultimo giorno per output. + public int[] ProducedToday { get; init; } = []; + + /// Domanda di input dell'ultimo giorno (unità) per input. + public double[] InputDemandToday { get; init; } = []; + + /// Margine = (ricavi − costi) / max(ricavi, costi) in [−1, 1]. + public double Margin + { + get + { + double denom = Math.Max(Math.Max(RevenueEma, CostEma), 1.0); + return Math.Clamp((RevenueEma - CostEma) / denom, -1, 1); + } + } + + /// Cicli al giorno a efficienza 1 per il livello corrente. + public double CyclesPerDayAtFullCapacity(int daysPerMonth) + { + if (Level <= 0) return 0; + int perCycle = Def.Recipe.Outputs[0].PerCycle; + return (double)Def.Capacity(Level) / perCycle / daysPerMonth; + } + + public int JobsWorkers => Level <= 0 ? 0 : Def.Workers(Level); + public int JobsStaff => Level <= 0 ? 0 : Def.Staff(Level); + + /// Indice dell'input che usa il bene dato, o −1. + public int InputIndexOf(int good) + { + var inputs = Def.Recipe.Inputs; + for (int i = 0; i < inputs.Count; i++) + { + if (inputs[i].GoodIndex == good) return i; + } + return -1; + } + + /// Indice dell'output che produce il bene dato, o −1. + public int OutputIndexOf(int good) + { + var outputs = Def.Recipe.Outputs; + for (int i = 0; i < outputs.Count; i++) + { + if (outputs[i].GoodIndex == good) return i; + } + return -1; + } +} diff --git a/src/ViaFerrea.Core/Economy/Ledger.cs b/src/ViaFerrea.Core/Economy/Ledger.cs new file mode 100644 index 0000000..b7f9e51 --- /dev/null +++ b/src/ViaFerrea.Core/Economy/Ledger.cs @@ -0,0 +1,71 @@ +using ViaFerrea.Core.Common; + +namespace ViaFerrea.Core.Economy; + +/// Titolare di un conto nel registro a partita doppia. +public enum AccountKind : byte { External = 0, Company = 1, Industry = 2 } + +/// Conto: il resto del mondo, una compagnia o un'industria. +public readonly record struct Account(AccountKind Kind, int Index) +{ + public static readonly Account External = new(AccountKind.External, 0); + public static Account Of(CompanyId id) => new(AccountKind.Company, id.Value); + public static Account Of(IndustryId id) => new(AccountKind.Industry, id.Value); +} + +/// +/// Registro a partita doppia: ogni movimento è un trasferimento tra due conti, quindi la +/// somma di tutti i saldi (compagnie, industrie e conto Esterno) resta sempre zero. +/// Il conto Esterno rappresenta salari pagati alle famiglie, clienti delle tariffe e mercato mondiale. +/// +public sealed class MoneyLedger(Func companies, Func industries) +{ + /// Saldo del conto Esterno. + public Money External { get; set; } + + /// Totale trasferito dall'inizio (statistica). + public long TransfersCount { get; internal set; } + + public void Transfer(Account from, Account to, Money amount, LedgerEntry entry) + { + if (amount.Cents == 0 || from == to) return; + Adjust(from, -amount, entry); + Adjust(to, amount, entry); + TransfersCount++; + } + + private void Adjust(Account account, Money delta, LedgerEntry entry) + { + switch (account.Kind) + { + case AccountKind.External: + External += delta; + break; + case AccountKind.Company: + var c = companies(new CompanyId(account.Index)); + c.Cash += delta; + c.MonthEntries[(int)entry] += delta.Cents; + c.YearEntries[(int)entry] += delta.Cents; + break; + case AccountKind.Industry: + var i = industries(new IndustryId(account.Index)); + i.Cash += delta; + break; + } + } +} + +/// +/// Contatori dei flussi di merci per bene: la giacenza totale nel mondo deve valere +/// prodotto + importato − consumato − deperito − esportato (invariante «nessun bene dal nulla»). +/// +public sealed class GoodsCounters(int goodCount) +{ + public long[] Produced { get; } = new long[goodCount]; + public long[] Consumed { get; } = new long[goodCount]; + public long[] Decayed { get; } = new long[goodCount]; + public long[] Imported { get; } = new long[goodCount]; + public long[] Exported { get; } = new long[goodCount]; + + public long ExpectedStock(int good) => Produced[good] + Imported[good] - Consumed[good] - Decayed[good] - Exported[good]; +} diff --git a/src/ViaFerrea.Core/Economy/Market.cs b/src/ViaFerrea.Core/Economy/Market.cs new file mode 100644 index 0000000..8fd5280 --- /dev/null +++ b/src/ViaFerrea.Core/Economy/Market.cs @@ -0,0 +1,115 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Data; + +namespace ViaFerrea.Core.Economy; + +/// +/// Mercato dei beni: prezzo globale per bene aggiornato ogni giorno dal rapporto tra domanda e +/// offerta della regione negli ultimi 30 giorni più la componente mondiale (ADR 0004). +/// +public sealed class Market +{ + public Market(GameData data) + { + int n = data.GoodCount; + int window = data.Balance.Market.WindowDays; + int history = data.Balance.Market.HistoryDays; + GlobalPrice = new double[n]; + Shock = new double[n]; + DemandToday = new double[n]; + SupplyToday = new double[n]; + CapacityToday = new double[n]; + UnmetDays = new int[n]; + Demand = new RollingWindow[n]; + Supply = new RollingWindow[n]; + PriceHistory = new RollingWindow[n]; + for (int g = 0; g < n; g++) + { + GlobalPrice[g] = data.Goods[g].BasePrice; + Demand[g] = new RollingWindow(window); + Supply[g] = new RollingWindow(window); + PriceHistory[g] = new RollingWindow(history); + } + } + + /// Prezzo globale Pg in centesimi per unità. + public double[] GlobalPrice { get; } + + /// Shock mondiale corrente per bene (frazione del prezzo base), decade nel tempo. + public double[] Shock { get; } + + /// Domanda e offerta accumulate nel giorno corrente dai sistemi. + public double[] DemandToday { get; } + public double[] SupplyToday { get; } + + /// Capacità produttiva installata del giorno (unità/giorno a efficienza 1) per bene. + public double[] CapacityToday { get; } + + /// Domanda e offerta degli ultimi giorni (finestra mobile). + public RollingWindow[] Demand { get; private set; } + public RollingWindow[] Supply { get; private set; } + + /// Storico dei prezzi globali (un anno). + public RollingWindow[] PriceHistory { get; private set; } + + /// Giorni consecutivi con domanda insoddisfatta, per bene (nascita di nuove industrie). + public int[] UnmetDays { get; } + + /// Componente mondiale relativa: A·sin(2πt/T) + shock. + public static double WorldFactor(MarketBalance m, double volatility, double yearsElapsed, double shock) => + m.World.Amplitude * volatility * DMath.Sin(DMath.TwoPi * yearsElapsed / m.World.PeriodYears) + shock; + + /// + /// Prezzo locale al nodo: Pl = Pg·(1 + λ·(Dl − Sl)/(Dl + Sl + ε)), entro ±maxDeviation. + /// + public static double LocalPrice(double globalPrice, double localDemand, double localSupply, LocalPriceBalance p) + { + double imbalance = (localDemand - localSupply) / (localDemand + localSupply + p.Epsilon); + double factor = Math.Clamp(1 + p.Lambda * imbalance, 1 - p.MaxDeviation, 1 + p.MaxDeviation); + return globalPrice * factor; + } + + internal void Restore(RollingWindow[] demand, RollingWindow[] supply, RollingWindow[] history) + { + Demand = demand; + Supply = supply; + PriceHistory = history; + } +} + +/// Tariffe del vettore (guida 6.3). +public static class Tariffs +{ + /// + /// Merci: unità × tariffa base × (0,6 + 0,4·Pg/Pb) × km^0,9 × tf × moltiplicatore della difficoltà. + /// tf scende linearmente da 1 a 0,5 quando la consegna supera del 50 % il tempo atteso. + /// + public static Money Freight(int units, double km, double globalPrice, double basePrice, double actualDays, double expectedDays, + TariffBalance t, double difficultyMultiplier) + { + if (units <= 0 || km <= 0) return Money.Zero; + double priceFactor = t.FreightFixedWeight + t.FreightPriceWeight * globalPrice / basePrice; + double cents = units * t.FreightBaseRate * priceFactor * DMath.Pow(km, t.FreightKmExponent) + * LatenessFactor(actualDays, expectedDays, t) * difficultyMultiplier; + return Money.FromCentsRounded(cents); + } + + /// Passeggeri: posti × tariffa base × km^0,85 × classe × puntualità × difficoltà. + public static Money Passenger(int pax, double km, PaxClass paxClass, double actualDays, double expectedDays, + TariffBalance t, double difficultyMultiplier, double comfort = 1.0) + { + if (pax <= 0 || km <= 0) return Money.Zero; + double cls = t.ClassMultipliers[paxClass == PaxClass.Staff ? "staff" : "worker"]; + double cents = pax * t.PaxBaseFare * DMath.Pow(km, t.PaxKmExponent) * cls + * LatenessFactor(actualDays, expectedDays, t) * difficultyMultiplier * comfort; + return Money.FromCentsRounded(cents); + } + + /// Fattore di puntualità: 1 entro la soglia, poi cala fino al minimo. + public static double LatenessFactor(double actualDays, double expectedDays, TariffBalance t) + { + if (expectedDays <= 0 || actualDays <= expectedDays * t.LateThreshold) return 1.0; + double over = actualDays / expectedDays - t.LateThreshold; + return Math.Max(t.LateFactorMin, 1.0 - (1.0 - t.LateFactorMin) * over / t.LateFactorSpan); + } +} diff --git a/src/ViaFerrea.Core/Economy/ResourceSite.cs b/src/ViaFerrea.Core/Economy/ResourceSite.cs new file mode 100644 index 0000000..973f238 --- /dev/null +++ b/src/ViaFerrea.Core/Economy/ResourceSite.cs @@ -0,0 +1,23 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Data; + +namespace ViaFerrea.Core.Economy; + +/// Giacimento con riserva finita (carbone, ferro, pietra, petrolio). +public sealed class ResourceSite +{ + public required ResourceSiteId Id { get; init; } + public required ResourceKind Kind { get; init; } + public required int CellX { get; init; } + public required int CellY { get; init; } + public required int RadiusCells { get; init; } + public required long InitialReserveTonnes { get; init; } + + /// Riserva residua in tonnellate (frazionaria: l'estrazione segue la produzione). + public double ReserveTonnes { get; set; } + + /// Scoperto (i giacimenti nascosti si trovano con la prospezione, F7). + public bool Discovered { get; set; } = true; + + public double ReserveFraction => InitialReserveTonnes <= 0 ? 0 : ReserveTonnes / InitialReserveTonnes; +} diff --git a/src/ViaFerrea.Core/Economy/RollingWindow.cs b/src/ViaFerrea.Core/Economy/RollingWindow.cs new file mode 100644 index 0000000..c5eb009 --- /dev/null +++ b/src/ViaFerrea.Core/Economy/RollingWindow.cs @@ -0,0 +1,78 @@ +namespace ViaFerrea.Core.Economy; + +/// +/// Somma mobile su una finestra fissa di N campioni giornalieri (per esempio domanda e offerta +/// degli ultimi 30 giorni). La somma è ricalcolata dal buffer a ogni giro completo per non +/// accumulare errori di arrotondamento. +/// +public sealed class RollingWindow +{ + private readonly double[] _values; + private int _next; + private int _count; + private double _sum; + + public RollingWindow(int length) + { + if (length <= 0) throw new ArgumentOutOfRangeException(nameof(length)); + _values = new double[length]; + } + + public int Length => _values.Length; + public int Count => _count; + public double Sum => _sum; + public double Average => _count == 0 ? 0 : _sum / _count; + + public void Add(double value) + { + _sum -= _values[_next]; + _values[_next] = value; + _sum += value; + _next++; + if (_next == _values.Length) + { + _next = 0; + double s = 0; + foreach (double v in _values) s += v; + _sum = s; + } + if (_count < _values.Length) _count++; + } + + /// Valore aggiunto k giorni fa (0 = l'ultimo). + public double Ago(int k) + { + if (k < 0 || k >= _count) return 0; + int i = (_next - 1 - k) % _values.Length; + if (i < 0) i += _values.Length; + return _values[i]; + } + + internal void Save(Persistence.SaveWriter w) + { + w.Write(_values.Length); + foreach (double v in _values) w.Write(v); + w.Write(_next); + w.Write(_count); + w.Write(_sum); + } + + internal static RollingWindow Load(Persistence.SaveReader r) + { + int length = r.ReadInt32(); + var window = new RollingWindow(length); + for (int i = 0; i < length; i++) window._values[i] = r.ReadDouble(); + window._next = r.ReadInt32(); + window._count = r.ReadInt32(); + window._sum = r.ReadDouble(); + return window; + } +} + +/// Media mobile esponenziale con costante pari a una finestra di N giorni (α = 2/(N+1)). +public static class Ema +{ + public static double Alpha(int windowDays) => 2.0 / (windowDays + 1); + + public static double Step(double current, double sample, int windowDays) => current + Alpha(windowDays) * (sample - current); +} diff --git a/src/ViaFerrea.Core/Economy/Town.cs b/src/ViaFerrea.Core/Economy/Town.cs new file mode 100644 index 0000000..4d55799 --- /dev/null +++ b/src/ViaFerrea.Core/Economy/Town.cs @@ -0,0 +1,78 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Data; + +namespace ViaFerrea.Core.Economy; + +/// Città: popolazione, domanda di beni, soddisfazione per categoria e forza lavoro. +public sealed class Town +{ + public const int CategoryCount = 4; // Food, Goods, Fuel, Construction + + public required TownId Id { get; init; } + public required string Name { get; init; } + public required int CellX { get; init; } + public required int CellY { get; init; } + public required Vec2 Position { get; init; } + public double RadiusCells { get; set; } + public int Population { get; set; } + + /// Scorte di beni consegnati in attesa di consumo, per bene. + public int[] Stock { get; init; } = []; + + /// Domanda del giorno corrente per bene (unità), calcolata dal sistema Demand. + public double[] DemandToday { get; init; } = []; + + /// Accumulatore frazionario della domanda per bene (si consumano unità intere). + public double[] DemandAccumulator { get; init; } = []; + + /// Soddisfazione per categoria (EMA di consegnato/domanda), indicizzata da . + public double[] Satisfaction { get; init; } = new double[CategoryCount]; + + /// Categorie con domanda nel periodo corrente. + public bool[] CategoryActive { get; init; } = new bool[CategoryCount]; + + /// Insoddisfazione per il lavoro perso (contratti sciolti), 0–1, decresce col tempo. + public double WorkDissatisfaction { get; set; } + + /// Lavoratori e personale impiegati (in industrie, depositi e servizi cittadini). + public int EmployedWorkers { get; set; } + public int EmployedStaff { get; set; } + + /// Posti nei servizi cittadini occupati dai residenti. + public int ServiceJobs { get; set; } + + /// Numero di categorie di servizi soddisfatte (servono al personale qualificato). + public int Services { get; set; } + + /// Crescita dell'ultimo mese (frazione). + public double LastGrowth { get; set; } + + /// Soddisfazione media sulle categorie attive. + public double OverallSatisfaction + { + get + { + double sum = 0; + int n = 0; + for (int c = 0; c < CategoryCount; c++) + { + if (!CategoryActive[c]) continue; + sum += Satisfaction[c]; + n++; + } + double s = n == 0 ? 0.5 : sum / n; + return Math.Max(0, s - WorkDissatisfaction); + } + } + + /// Forza lavoro (lavoratori) secondo la quota della popolazione. + public int Workforce(TownBalance b) => (int)(Population * b.WorkforceShare); + + /// Personale qualificato: solo nelle città grandi e con servizi sufficienti. + public int StaffPool(TownBalance b) => + Population >= b.StaffMinPopulation && Services >= b.StaffMinServices ? (int)(Population * b.StaffShare) : 0; + + public int FreeWorkers(TownBalance b) => Math.Max(0, Workforce(b) - EmployedWorkers); + + public int FreeStaff(TownBalance b) => Math.Max(0, StaffPool(b) - EmployedStaff); +} diff --git a/src/ViaFerrea.Core/Map/GeneratedMap.cs b/src/ViaFerrea.Core/Map/GeneratedMap.cs new file mode 100644 index 0000000..029ee30 --- /dev/null +++ b/src/ViaFerrea.Core/Map/GeneratedMap.cs @@ -0,0 +1,39 @@ +using ViaFerrea.Core.Data; + +namespace ViaFerrea.Core.Map; + +/// Parametri di generazione di una mappa. +public sealed record MapSpec(ulong Seed, int SizeKm, int StartYear, string RegionId = "valdoria"); + +/// Lato della mappa affacciato sul mare. +public enum MapSide : byte { North = 0, East = 1, South = 2, West = 3 } + +/// Giacimento generato. +public sealed record ResourceSiteSeed(ResourceKind Kind, int CellX, int CellY, int RadiusCells, long ReserveTonnes); + +/// Città generata. +public sealed record TownSeed(string Name, int CellX, int CellY, int Population, double RadiusCells); + +/// Industria generata. (CellX, CellY) è la cella centrale dell'impronta quadrata. +public sealed record IndustrySeed(int TypeIndex, string Name, int CellX, int CellY, int Level, int SiteIndex, int FootprintCells); + +/// Hub generato (porto o valico). +public sealed record HubSeed(HubKind Kind, string Name, int CellX, int CellY, int FootprintCells); + +/// Risultato del generatore: terreno ed entità iniziali, da cui si costruisce il mondo. +public sealed class GeneratedMap +{ + public required MapSpec Spec { get; init; } + public required Terrain Terrain { get; init; } + public required MapSide SeaSide { get; init; } + public required List Sites { get; init; } + public required List Towns { get; init; } + public required List Industries { get; init; } + public required List Hubs { get; init; } + + /// Tempi delle fasi di generazione (ms), per i rapporti di prestazione. + public Dictionary PhaseMillis { get; } = new(StringComparer.Ordinal); + + /// Quadrato dell'impronta di un'industria o di un hub: celle da (x0, y0) a (x0 + n − 1, y0 + n − 1). + public static (int X0, int Y0) FootprintOrigin(int cx, int cy, int size) => (cx - (size - 1) / 2, cy - (size - 1) / 2); +} diff --git a/src/ViaFerrea.Core/Map/MapGenerator.Placement.cs b/src/ViaFerrea.Core/Map/MapGenerator.Placement.cs new file mode 100644 index 0000000..c48a02a --- /dev/null +++ b/src/ViaFerrea.Core/Map/MapGenerator.Placement.cs @@ -0,0 +1,558 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Data; + +namespace ViaFerrea.Core.Map; + +// Copertura del suolo e collocazione di giacimenti, città, hub e industrie. +public sealed partial class MapGenerator +{ + // ------------------------------------------------------------------ copertura + + private void Cover() + { + var c = _p.Cover; + var rng = _root.Fork("map.cover"); + var forest = new ValueNoise(rng.NextU64()); + var marsh = new ValueNoise(rng.NextU64()); + double forestWl = KmToCells(c.ForestWavelengthKm); + ushort rockH = Percentile(c.RockPercentile); + ushort mountainH = Percentile(c.MountainPercentile); + ushort hillH = Percentile(c.HillPercentile); + ushort marshH = Percentile(c.MarshMaxPercentile); + var types = _t.Types; + var heights = _t.Heights; + + Parallel.For(0, _h, y => + { + for (int x = 0; x < _w; x++) + { + int i = y * _w + x; + if (types[i] is (byte)CellType.Sea or (byte)CellType.Water) continue; + ushort hgt = heights[i]; + double slope = _slope[i]; + double fn = forest.Fbm(x, y, 3, forestWl, 0.5, 2.0); + CellType t; + if (hgt >= rockH && slope >= c.RockMinSlope) t = CellType.Rock; + else if (hgt >= mountainH) t = CellType.Mountain; + else if (slope >= c.ForestMinSlope && slope <= c.ForestMaxSlope && fn > c.ForestNoiseThreshold) t = CellType.Forest; + else if (slope < c.ForestMaxSlope && fn > c.ForestNoiseThreshold + 0.12) t = CellType.Forest; + else if (hgt <= marshH && slope <= c.MarshMaxSlope && _riverDist[i] <= c.MarshRiverDistanceCells + && marsh.Fbm(x, y, 2, forestWl * 0.5, 0.5, 2.0) > c.MarshNoiseThreshold) t = CellType.Marsh; + else if (slope >= c.HillMinSlope || hgt >= hillH) t = CellType.Hill; + else t = CellType.Plain; + types[i] = (byte)t; + } + }); + } + + // ------------------------------------------------------------------ giacimenti + + private double AreaKm2 => _w * _cs / 1000.0 * (_h * _cs / 1000.0); + + private void PlaceDeposits() + { + var d = _p.Deposits; + double spacing = KmToCells(d.MinSpacingKm); + foreach (ResourceKind kind in Enum.GetValues()) + { + string key = kind.ToString().ToLowerInvariant(); + var rng = _root.Fork("map.deposits." + key); + int count = (int)Math.Round(d.PerThousandKm2[key] * _region.Resources.For(kind) * AreaKm2 / 1000.0); + double minPct = d.PreferredMinPercentile[key], maxPct = d.PreferredMaxPercentile[key]; + long[] reserve = d.ReserveTonnes[key]; + int placed = 0; + for (int attempt = 0; attempt < count * 300 && placed < count; attempt++) + { + int x = rng.NextInt(_w), y = rng.NextInt(_h); + if (!IsLand(x, y) || IsNearBorder(x, y, 8)) continue; + double pct = PercentileOf(_t.Heights[Idx(x, y)]); + if (pct < minPct || pct > maxPct) continue; + bool tooClose = _sites.Any(s => Dist2(s.CellX, s.CellY, x, y) < spacing * spacing); + if (tooClose) continue; + int radius = rng.NextInt(d.RadiusCells[0], d.RadiusCells[1] + 1); + long tonnes = (long)Math.Round(rng.NextDouble(reserve[0], reserve[1]) / 1000.0) * 1000; + _sites.Add(new ResourceSiteSeed(kind, x, y, radius, tonnes)); + placed++; + } + } + } + + // ------------------------------------------------------------------ città + + private void PlaceTowns() + { + var tp = _p.Towns; + var rng = _root.Fork("map.towns"); + int count = tp.CountBySize[_spec.SizeKm.ToString(System.Globalization.CultureInfo.InvariantCulture)]; + int maxWater = (int)Math.Ceiling(KmToCells(tp.MaxWaterDistanceKm)); + var waterDist = DistanceField(i => _t.Types[i] is (byte)CellType.Water or (byte)CellType.Sea, maxWater); + ushort maxH = Percentile(tp.MaxHeightPercentile); + int stride = Math.Max(1, _w / 400); + int margin = (int)Math.Ceiling(KmToCells(1.5)); + + var candidates = new List<(double Score, int X, int Y)>(); + for (int y = margin; y < _h - margin; y += stride) + { + for (int x = margin; x < _w - margin; x += stride) + { + int i = Idx(x, y); + byte t = _t.Types[i]; + if (t is not ((byte)CellType.Plain or (byte)CellType.Forest or (byte)CellType.Hill)) continue; + if (_slope[i] > tp.MaxSlope || _t.Heights[i] > maxH || waterDist[i] > maxWater) continue; + double score = (1.0 - (double)waterDist[i] / (maxWater + 1)) + 0.5 * (1.0 - _slope[i] / tp.MaxSlope) + 0.6 * rng.NextDouble(); + candidates.Add((score, x, y)); + } + } + candidates.Sort((a, b) => a.Score != b.Score ? b.Score.CompareTo(a.Score) : (a.Y * _w + a.X).CompareTo(b.Y * _w + b.X)); + + double minDist = KmToCells(tp.MinDistanceKm); + var picked = new List<(int X, int Y)>(); + foreach (var cand in candidates) + { + if (picked.Count >= count) break; + if (picked.Any(p => Dist2(p.X, p.Y, cand.X, cand.Y) < minDist * minDist)) continue; + if (_sites.Any(s => Dist2(s.CellX, s.CellY, cand.X, cand.Y) < (s.RadiusCells + 6) * (s.RadiusCells + 6))) continue; + picked.Add((cand.X, cand.Y)); + } + + double largest = rng.NextDouble(tp.LargestPopulation[0], tp.LargestPopulation[1]); + for (int r = 0; r < picked.Count; r++) + { + int pop = Math.Max(tp.MinPopulation, (int)Math.Round(largest / DMath.Pow(r + 1, tp.ZipfExponent) / 10.0) * 10); + double radius = tp.RadiusBaseCells + tp.RadiusPerSqrtPop * Math.Sqrt(pop); + var (x, y) = picked[r]; + _towns.Add(new TownSeed(_names.Next(), x, y, pop, radius)); + MarkDisc(x, y, radius, CellType.Town); + } + } + + private void MarkDisc(int cx, int cy, double radius, CellType type) + { + int r = (int)Math.Ceiling(radius); + for (int y = cy - r; y <= cy + r; y++) + { + for (int x = cx - r; x <= cx + r; x++) + { + if (!_t.InBounds(x, y) || Dist2(x, y, cx, cy) > radius * radius) continue; + if (_t.IsWater(x, y)) continue; + _t.SetType(x, y, type); + } + } + } + + // ------------------------------------------------------------------ hub + + private void PlaceHubs() + { + var rng = _root.Fork("map.hubs"); + var hp = _data.Balance.Hubs; + int footprintPort = FootprintCells(hp.Port.Footprint); + int footprintBorder = FootprintCells(hp.Border.Footprint); + + for (int k = 0; k < _p.Hubs.Ports; k++) + { + double nearby = KmToCells(_p.Hubs.PortMinPopulationNearbyKm); + (double Score, int X, int Y) best = (double.MinValue, -1, -1); + for (int y = 2; y < _h - 2; y++) + { + for (int x = 2; x < _w - 2; x++) + { + if (!IsLand(x, y) || !NearSea(x, y, 2)) continue; + if (!FootprintFree(x, y, footprintPort, allowTownMargin: true, maxSlope: 0.12)) continue; + double score = 0; + foreach (var t in _towns) + { + double d = Math.Sqrt(Dist2(t.CellX, t.CellY, x, y)); + if (d < nearby) score += t.Population / (1.0 + d / 10.0); + } + score += rng.NextDouble() * 10; + if (_hubs.Any(h => Dist2(h.CellX, h.CellY, x, y) < 100 * 100)) continue; + if (score > best.Score) best = (score, x, y); + } + } + if (best.X < 0) continue; + string name = "Porto di " + SideName(_seaSide, port: true); + _hubs.Add(new HubSeed(HubKind.Port, name, best.X, best.Y, footprintPort)); + MarkFootprint(best.X, best.Y, footprintPort, CellType.Industry); + } + + for (int k = 0; k < _p.Hubs.Borders; k++) + { + (double Score, int X, int Y, MapSide Side) best = (double.MinValue, -1, -1, MapSide.North); + int inset = footprintBorder; + foreach (MapSide side in Enum.GetValues()) + { + if (side == _seaSide) continue; + for (int s = inset; s < (side is MapSide.North or MapSide.South ? _w : _h) - inset; s += 2) + { + var (x, y) = side switch + { + MapSide.North => (s, inset), + MapSide.South => (s, _h - 1 - inset), + MapSide.East => (_w - 1 - inset, s), + _ => (inset, s), + }; + if (!IsLand(x, y) || !FootprintFree(x, y, footprintBorder, allowTownMargin: false, maxSlope: 0.2)) continue; + if (_hubs.Any(h => Dist2(h.CellX, h.CellY, x, y) < 100 * 100)) continue; + double pct = PercentileOf(_t.Heights[Idx(x, y)]); + double score = -pct + rng.NextDouble() * 0.3; + if (score > best.Score) best = (score, x, y, side); + } + } + if (best.X < 0) continue; + string name = "Valico " + SideName(best.Side, port: false); + _hubs.Add(new HubSeed(HubKind.Border, name, best.X, best.Y, footprintBorder)); + MarkFootprint(best.X, best.Y, footprintBorder, CellType.Industry); + } + } + + private static string SideName(MapSide side, bool port) => (side, port) switch + { + (MapSide.East, true) => "Levante", + (MapSide.West, true) => "Ponente", + (MapSide.North, true) => "Tramontana", + (MapSide.South, true) => "Mezzogiorno", + (MapSide.North, false) => "del Nord", + (MapSide.South, false) => "del Sud", + (MapSide.East, false) => "d'Oriente", + _ => "d'Occidente", + }; + + // ------------------------------------------------------------------ industrie + + private void PlaceIndustries() + { + var ip = _p.Industries; + var rng = _root.Fork("map.industries"); + int target = ip.CountBySize[_spec.SizeKm.ToString(System.Globalization.CultureInfo.InvariantCulture)]; + var available = _data.Industries.Where(d => d.Era <= _spec.StartYear).ToList(); + + // 1. miniere, cave e pozzi sui giacimenti + for (int s = 0; s < _sites.Count; s++) + { + var site = _sites[s]; + var type = available.FirstOrDefault(d => d.Placement.Needs == PlacementNeed.Deposit && d.Placement.Resource == site.Kind); + if (type is null) continue; + int size = FootprintCells(type.Footprint); + if (FindNear(site.CellX, site.CellY, site.RadiusCells + 2, size, type, out int fx, out int fy)) + AddIndustry(type, fx, fy, size, s, rng); + } + + int remaining = Math.Max(0, target - _industries.Count); + int farms = (int)Math.Round(remaining * ip.Shares.GetValueOrDefault("farm")); + int logging = (int)Math.Round(remaining * ip.Shares.GetValueOrDefault("logging")); + int processing = (int)Math.Round(remaining * ip.Shares.GetValueOrDefault("processing")); + int manufacturing = Math.Max(0, remaining - farms - logging - processing); + + // 2. fattorie attorno alle città + foreach (var type in available.Where(d => d.Placement.Needs == PlacementNeed.Plain)) + { + int n = (int)Math.Round(farms * type.SpawnWeight / Math.Max(1e-9, available.Where(d => d.Placement.Needs == PlacementNeed.Plain).Sum(d => d.SpawnWeight))); + for (int k = 0; k < n; k++) PlaceAroundTown(type, rng, requirePlain: true); + } + + // 3. taglialegna nei boschi + var loggingTypes = available.Where(d => d.Placement.Needs == PlacementNeed.Forest).ToList(); + if (loggingTypes.Count > 0) + { + var forestCells = new List(); + for (int i = 0; i < _t.Types.Length; i += 13) + { + if (_t.Types[i] == (byte)CellType.Forest) forestCells.Add(i); + } + for (int k = 0; k < logging && forestCells.Count > 0; k++) + { + var type = WeightedPick(loggingTypes, rng); + int size = FootprintCells(type.Footprint); + for (int attempt = 0; attempt < ip.PlacementAttempts; attempt++) + { + int i = forestCells[rng.NextInt(forestCells.Count)]; + int x = i % _w, y = i / _w; + if (ValidSite(x, y, size, type)) { AddIndustry(type, x, y, size, -1, rng); break; } + } + } + } + + // 4. manifatture accanto alle città + var manufacturingTypes = available.Where(d => d.Placement.Needs == PlacementNeed.Town).ToList(); + for (int k = 0; k < manufacturing && manufacturingTypes.Count > 0; k++) + { + var type = k < manufacturingTypes.Count ? manufacturingTypes[k] : WeightedPick(manufacturingTypes, rng); + PlaceAroundTown(type, rng, requirePlain: false); + } + + // 5. trasformazione tra materie prime e città + var processingTypes = available.Where(d => d.Kind == IndustryKind.Processing && d.Placement.Needs == PlacementNeed.Any).ToList(); + for (int k = 0; k < processing && processingTypes.Count > 0; k++) + { + var type = k < processingTypes.Count ? processingTypes[k] : WeightedPick(processingTypes, rng); + PlaceProcessing(type, rng); + } + } + + private void PlaceAroundTown(IndustryDef type, Rng rng, bool requirePlain) + { + var pl = type.Placement; + var eligible = _towns.Where(t => t.Population >= (pl.MinTownPopulation ?? 0)).ToList(); + if (eligible.Count == 0) return; + int size = FootprintCells(type.Footprint); + double minKm = pl.MinTownDistanceKm ?? 0, maxKm = pl.MaxTownDistanceKm ?? 3; + for (int attempt = 0; attempt < _p.Industries.PlacementAttempts; attempt++) + { + var town = eligible[rng.NextInt(eligible.Count)]; + double angle = rng.NextDouble() * DMath.TwoPi; + double dist = town.RadiusCells + size * 0.75 + KmToCells(rng.NextDouble(minKm, maxKm)); + int x = (int)Math.Round(town.CellX + DMath.Cos(angle) * dist); + int y = (int)Math.Round(town.CellY + DMath.Sin(angle) * dist); + if (!_t.InBounds(x, y)) continue; + if (requirePlain && _t.TypeAt(x, y) is not (CellType.Plain or CellType.Field)) continue; + if (ValidSite(x, y, size, type)) { AddIndustry(type, x, y, size, -1, rng); return; } + } + } + + private void PlaceProcessing(IndustryDef type, Rng rng) + { + var pl = type.Placement; + double inputRange = KmToCells(pl.MaxInputDistanceKm ?? 12); + // produttori già collocati per ogni input + var producers = type.Recipe.Inputs + .Select(input => _industries.Where(ind => _data.Industries[ind.TypeIndex].Recipe.Outputs.Any(o => o.Good == input.Good)).ToList()) + .ToList(); + if (producers.Any(p => p.Count == 0)) return; + int size = FootprintCells(type.Footprint); + for (int attempt = 0; attempt < _p.Industries.PlacementAttempts; attempt++) + { + var anchorList = producers[rng.NextInt(producers.Count)]; + var anchor = anchorList[rng.NextInt(anchorList.Count)]; + double angle = rng.NextDouble() * DMath.TwoPi; + double dist = rng.NextDouble() * inputRange; + int x = (int)Math.Round(anchor.CellX + DMath.Cos(angle) * dist); + int y = (int)Math.Round(anchor.CellY + DMath.Sin(angle) * dist); + if (!_t.InBounds(x, y)) continue; + bool allInputs = producers.All(list => list.Any(p => Dist2(p.CellX, p.CellY, x, y) <= inputRange * inputRange)); + if (!allInputs) continue; + if (ValidSite(x, y, size, type)) { AddIndustry(type, x, y, size, -1, rng); return; } + } + } + + private bool FindNear(int cx, int cy, int radius, int size, IndustryDef type, out int fx, out int fy) + { + // ricerca a spirale: prima le celle più vicine al centro del giacimento + for (int r = 0; r <= radius; r++) + { + for (int dy = -r; dy <= r; dy++) + { + for (int dx = -r; dx <= r; dx++) + { + if (Math.Max(Math.Abs(dx), Math.Abs(dy)) != r) continue; + int x = cx + dx, y = cy + dy; + if (ValidSite(x, y, size, type)) + { + fx = x; + fy = y; + return true; + } + } + } + } + fx = fy = -1; + return false; + } + + /// Verifica impronta, pendenza, distanze dalle città e distanza dalle altre industrie. + private bool ValidSite(int x, int y, int size, IndustryDef type) + { + var pl = type.Placement; + bool nextToTown = pl.Needs == PlacementNeed.Town; + if (!FootprintFree(x, y, size, allowTownMargin: nextToTown, maxSlope: _p.Industries.MaxSlope)) return false; + var center = _t.CellCenter(x, y); + double nearestEdgeKm = double.MaxValue; + foreach (var t in _towns) nearestEdgeKm = Math.Min(nearestEdgeKm, TownEdgeDistanceKm(t, center)); + if (pl.MinTownDistanceKm is { } mn && nearestEdgeKm < mn) return false; + if (pl.MaxTownDistanceKm is { } mx && nearestEdgeKm > mx) return false; + if (nextToTown && pl.MinTownPopulation is { } minPop) + { + var nearest = _towns.MinBy(t => TownEdgeDistanceKm(t, center)); + if (nearest is null || nearest.Population < minPop) return false; + } + return true; + } + + /// Distanza in km tra un punto e il bordo di una città (centro meno raggio, mai negativa). + public static double TownEdgeDistanceKm(TownSeed town, Vec2 point, double cellSizeM) + { + var c = new Vec2((town.CellX + 0.5) * cellSizeM, (town.CellY + 0.5) * cellSizeM); + return Math.Max(0, (Vec2.Distance(c, point) - town.RadiusCells * cellSizeM) / 1000.0); + } + + private double TownEdgeDistanceKm(TownSeed town, Vec2 point) => TownEdgeDistanceKm(town, point, _cs); + + private bool FootprintFree(int cx, int cy, int size, bool allowTownMargin, double maxSlope) + { + var (x0, y0) = GeneratedMap.FootprintOrigin(cx, cy, size); + int spacing = _p.Industries.SpacingCells; + for (int y = y0 - spacing; y < y0 + size + spacing; y++) + { + for (int x = x0 - spacing; x < x0 + size + spacing; x++) + { + if (!_t.InBounds(x, y)) return false; + bool inside = x >= x0 && x < x0 + size && y >= y0 && y < y0 + size; + var t = _t.TypeAt(x, y); + if (inside) + { + if (t is CellType.Water or CellType.Sea or CellType.Town or CellType.Industry) return false; + if (_slope[Idx(x, y)] > maxSlope) return false; + } + else + { + if (t == CellType.Industry) return false; + if (t == CellType.Town && !allowTownMargin) return false; + } + } + } + return true; + } + + private void MarkFootprint(int cx, int cy, int size, CellType type) + { + var (x0, y0) = GeneratedMap.FootprintOrigin(cx, cy, size); + for (int y = y0; y < y0 + size; y++) + { + for (int x = x0; x < x0 + size; x++) + { + if (_t.InBounds(x, y)) _t.SetType(x, y, type); + } + } + } + + private void AddIndustry(IndustryDef type, int x, int y, int size, int siteIndex, Rng rng) + { + var levels = _p.Industries.InitialLevels; + int level = rng.NextInt(levels[0], levels[^1] + 1); + string name = IndustryName(type, x, y, rng); + _industries.Add(new IndustrySeed(type.Index, name, x, y, level, siteIndex, size)); + MarkFootprint(x, y, size, CellType.Industry); + } + + private string IndustryName(IndustryDef type, int x, int y, Rng rng) + { + var templates = _data.Regions.IndustryNameTemplates; + var center = _t.CellCenter(x, y); + string town = _towns.Count > 0 ? _towns.MinBy(t => TownEdgeDistanceKm(t, center))!.Name : ""; + for (int attempt = 0; attempt < 6; attempt++) + { + string template = templates[rng.NextInt(templates.Count)]; + if (type.Placement.Needs == PlacementNeed.Town && template.Contains("{feature}", StringComparison.Ordinal)) continue; + string feature = _data.Regions.FeatureNames[rng.NextInt(_data.Regions.FeatureNames.Count)]; + string name = template.Replace("{type}", type.NameIt, StringComparison.Ordinal) + .Replace("{town}", town, StringComparison.Ordinal) + .Replace("{feature}", feature, StringComparison.Ordinal); + if (!_industries.Any(i => i.Name == name)) return name; + } + return $"{type.NameIt} {town} {_industries.Count + 1}"; + } + + private static IndustryDef WeightedPick(List types, Rng rng) + { + double total = types.Sum(t => t.SpawnWeight); + double r = rng.NextDouble() * total; + foreach (var t in types) + { + r -= t.SpawnWeight; + if (r < 0) return t; + } + return types[^1]; + } + + private int FootprintCells(Footprint footprint) => + _data.Balance.Industry.FootprintCells[footprint.ToString().ToLowerInvariant()]; + + // ------------------------------------------------------------------ campi + + private void Fields() + { + var c = _p.Cover; + var noise = new ValueNoise(_root.Fork("map.fields").NextU64()); + double wl = KmToCells(0.8); + double threshold = 1.0 - c.FieldShare; + void Around(int cx, int cy, double radius, double bonus) + { + int r = (int)Math.Ceiling(radius); + for (int y = cy - r; y <= cy + r; y++) + { + for (int x = cx - r; x <= cx + r; x++) + { + if (!_t.InBounds(x, y) || _t.TypeAt(x, y) != CellType.Plain) continue; + double d = Math.Sqrt(Dist2(x, y, cx, cy)); + if (d > radius) continue; + double v = noise.Fbm(x, y, 2, wl, 0.5, 2.0) + bonus * (1.0 - d / radius); + if (v > threshold) _t.SetType(x, y, CellType.Field); + } + } + } + foreach (var t in _towns) Around(t.CellX, t.CellY, t.RadiusCells + c.FieldRadiusCells, 0.1); + foreach (var ind in _industries) + { + if (_data.Industries[ind.TypeIndex].Placement.Needs == PlacementNeed.Plain) + Around(ind.CellX, ind.CellY, c.FieldRadiusCells * 0.6, 0.35); + } + } + + // ------------------------------------------------------------------ utilità + + private bool IsLand(int x, int y) => _t.InBounds(x, y) && !_t.IsWater(x, y); + + private bool IsNearBorder(int x, int y, int margin) => x < margin || y < margin || x >= _w - margin || y >= _h - margin; + + private bool NearSea(int x, int y, int r) + { + for (int dy = -r; dy <= r; dy++) + { + for (int dx = -r; dx <= r; dx++) + { + int nx = x + dx, ny = y + dy; + if (_t.InBounds(nx, ny) && _t.TypeAt(nx, ny) == CellType.Sea) return true; + } + } + return false; + } + + private static double Dist2(int x1, int y1, int x2, int y2) + { + double dx = x1 - x2, dy = y1 - y2; + return dx * dx + dy * dy; + } + + /// Distanza a 8 vicini (in celle) dalle celle sorgente, fino a maxDist; oltre vale int.MaxValue. + private int[] DistanceField(Func isSource, int maxDist) + { + var dist = new int[_w * _h]; + Array.Fill(dist, int.MaxValue); + var queue = new Queue(); + for (int i = 0; i < dist.Length; i++) + { + if (isSource(i)) + { + dist[i] = 0; + queue.Enqueue(i); + } + } + while (queue.Count > 0) + { + int c = queue.Dequeue(); + int d = dist[c]; + if (d >= maxDist) continue; + int cx = c % _w, cy = c / _w; + for (int k = 0; k < 8; k++) + { + int nx = cx + Dx8[k], ny = cy + Dy8[k]; + if ((uint)nx >= (uint)_w || (uint)ny >= (uint)_h) continue; + int ni = Idx(nx, ny); + if (dist[ni] <= d + 1) continue; + dist[ni] = d + 1; + queue.Enqueue(ni); + } + } + return dist; + } +} diff --git a/src/ViaFerrea.Core/Map/MapGenerator.cs b/src/ViaFerrea.Core/Map/MapGenerator.cs new file mode 100644 index 0000000..263ed30 --- /dev/null +++ b/src/ViaFerrea.Core/Map/MapGenerator.cs @@ -0,0 +1,512 @@ +using System.Diagnostics; +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Data; + +namespace ViaFerrea.Core.Map; + +/// +/// Generatore procedurale della regione (guida 6.2). Tutto dipende solo dal seme e dai dati: +/// rilievo con rumore di valore a ottave e dominio deformato, mare collegato a un bordo, +/// idrologia con priority-flood (laghi nelle conche, fiumi per accumulo di flusso con +/// scavo e larghezza crescente), copertura del suolo, giacimenti, città, hub e industrie. +/// I calcoli per cella indipendenti girano in parallelo: il risultato non dipende dall'ordine. +/// +public sealed partial class MapGenerator +{ + private readonly GameData _data; + private readonly MapBalance _p; + private readonly MapSpec _spec; + private readonly RegionDef _region; + private readonly Rng _root; + private readonly int _w, _h; + private readonly double _cs; + private readonly Terrain _t; + + // campi di lavoro (metri) + private float[] _elev = []; + private bool[] _sea = []; + private float[] _slope = []; + private int[] _riverDist = []; + private MapSide _seaSide; + + private readonly List _sites = []; + private readonly List _towns = []; + private readonly List _industries = []; + private readonly List _hubs = []; + private readonly Dictionary _phases = new(StringComparer.Ordinal); + + private ushort[] _heightHistogramSorted = []; + private int _landCount; + private NameGenerator _names = null!; + + private MapGenerator(GameData data, MapSpec spec) + { + _data = data; + _p = data.Balance.Map; + _spec = spec; + _region = data.Regions.Regions.FirstOrDefault(r => r.Id == spec.RegionId) + ?? throw new ArgumentException($"Regione sconosciuta: {spec.RegionId}"); + if (!_p.SizesKm.Contains(spec.SizeKm)) + throw new ArgumentException($"Dimensione della mappa non ammessa: {spec.SizeKm} km (ammesse: {string.Join(", ", _p.SizesKm)})"); + _root = new Rng(spec.Seed); + _cs = _p.CellSizeM; + _w = _h = (int)Math.Round(spec.SizeKm * 1000.0 / _cs); + _t = new Terrain(_w, _h, _cs, _p.ChunkCells); + } + + /// Genera la mappa completa. + public static GeneratedMap Generate(GameData data, MapSpec spec) => new MapGenerator(data, spec).Run(); + + private GeneratedMap Run() + { + Phase("rilievo", BuildRelief); + Phase("mare", MarkSea); + Phase("idrologia", Hydrology); + Phase("altezze", WriteHeights); + Phase("copertura", Cover); + var pool = _data.Regions.NamePools.First(n => n.Id == _region.NamePool); + _names = new NameGenerator(pool, _root.Fork("map.names")); + Phase("giacimenti", PlaceDeposits); + Phase("città", PlaceTowns); + Phase("hub", PlaceHubs); + Phase("industrie", PlaceIndustries); + Phase("campi", Fields); + + var map = new GeneratedMap + { + Spec = _spec, + Terrain = _t, + SeaSide = _seaSide, + Sites = _sites, + Towns = _towns, + Industries = _industries, + Hubs = _hubs, + }; + foreach (var (k, v) in _phases) map.PhaseMillis[k] = v; + return map; + } + + private void Phase(string name, Action action) + { + var sw = Stopwatch.StartNew(); + action(); + _phases[name] = sw.ElapsedMilliseconds; + } + + private double KmToCells(double km) => km * 1000.0 / _cs; + + private int Idx(int x, int y) => y * _w + x; + + // ------------------------------------------------------------------ rilievo + + private void BuildRelief() + { + var rng = _root.Fork("map.relief"); + _seaSide = (MapSide)rng.NextInt(4); + var baseNoise = new ValueNoise(rng.NextU64()); + var warpX = new ValueNoise(rng.NextU64()); + var warpY = new ValueNoise(rng.NextU64()); + var ridgeNoise = new ValueNoise(rng.NextU64()); + var coastNoise = new ValueNoise(rng.NextU64()); + var microNoise = new ValueNoise(rng.NextU64()); + + var n = _p.Noise; + var r = _p.Relief; + double baseWl = KmToCells(n.BaseWavelengthKm); + double warpWl = KmToCells(n.WarpWavelengthKm); + double warpStrength = KmToCells(n.WarpStrengthKm); + double ridgeWl = KmToCells(n.RidgeWavelengthKm); + double coastWl = baseWl * 0.35; + double microWl = KmToCells(r.MicroWavelengthKm); + double maxElev = _p.MaxElevationM; + _elev = new float[_w * _h]; + + Parallel.For(0, _h, y => + { + for (int x = 0; x < _w; x++) + { + double g = InlandFraction(x, y); + double wx = x + (warpX.Fbm(x, y, n.WarpOctaves, warpWl, 0.5, 2.0) - 0.5) * 2.0 * warpStrength; + double wy = y + (warpY.Fbm(x, y, n.WarpOctaves, warpWl, 0.5, 2.0) - 0.5) * 2.0 * warpStrength; + double b = baseNoise.Fbm(wx, wy, n.Octaves, baseWl, n.Persistence, n.Lacunarity); + double mask = DMath.SmoothStep(DMath.Clamp((g - r.MountainStart) / (1.0 - r.MountainStart), 0, 1)); + double ridge = mask > 0 ? ridgeNoise.Ridged(wx, wy, n.RidgeOctaves, ridgeWl, n.Persistence, n.Lacunarity) : 0; + double coast = (coastNoise.Fbm(x, y, 3, coastWl, 0.5, 2.0) - 0.5) * 2.0 * r.CoastNoiseM; + double micro = (microNoise.Fbm(x, y, 2, microWl, 0.5, 2.0) - 0.5) * 2.0 * r.MicroReliefM; + double noiseAmp = r.NoiseAmplitudeM * (r.NoiseCoastFactor + (1.0 - r.NoiseCoastFactor) * g); + double profile = r.InlandGradientM * DMath.Pow(g, r.InlandExponent); + double h = profile + b * noiseAmp + ridge * mask * r.MountainAmplitudeM - r.SeaOffsetM + coast + micro; + if (g < r.SeaBandFraction) + h -= (1.0 - g / r.SeaBandFraction) * (r.SeaOffsetM + r.CoastNoiseM + noiseAmp); + if (h > maxElev) h = maxElev; + _elev[y * _w + x] = (float)h; + } + }); + } + + /// Distanza normalizzata dal bordo del mare: 0 sul bordo marino, 1 sul bordo opposto. + private double InlandFraction(int x, int y) => _seaSide switch + { + MapSide.North => (double)y / (_h - 1), + MapSide.East => (double)(_w - 1 - x) / (_w - 1), + MapSide.South => (double)(_h - 1 - y) / (_h - 1), + _ => (double)x / (_w - 1), + }; + + // ------------------------------------------------------------------ mare + + private void MarkSea() + { + // il mare è l'insieme delle celle sotto quota 0 collegate a un bordo + _sea = new bool[_w * _h]; + var queue = new Queue(); + void Seed(int x, int y) + { + int i = Idx(x, y); + if (_elev[i] < 0 && !_sea[i]) + { + _sea[i] = true; + queue.Enqueue(i); + } + } + for (int x = 0; x < _w; x++) + { + Seed(x, 0); + Seed(x, _h - 1); + } + for (int y = 0; y < _h; y++) + { + Seed(0, y); + Seed(_w - 1, y); + } + while (queue.Count > 0) + { + int i = queue.Dequeue(); + int x = i % _w, y = i / _w; + if (x > 0) Seed(x - 1, y); + if (x < _w - 1) Seed(x + 1, y); + if (y > 0) Seed(x, y - 1); + if (y < _h - 1) Seed(x, y + 1); + } + // le conche sotto zero non collegate al mare diventano terreno basso (poi laghi o colmate) + for (int i = 0; i < _elev.Length; i++) + { + if (_sea[i]) _elev[i] = 0; + else if (_elev[i] < 0.5f) _elev[i] = 0.5f; + } + } + + // ------------------------------------------------------------------ idrologia + + private static readonly int[] Dx8 = [1, -1, 0, 0, 1, 1, -1, -1]; + private static readonly int[] Dy8 = [0, 0, 1, -1, 1, -1, 1, -1]; + + private void Hydrology() + { + int n = _w * _h; + var filled = new float[n]; + var parent = new int[n]; + var visited = new bool[n]; + var order = new int[n]; + int orderCount = 0; + const float eps = 0.001f; + + // priority-flood (Barnes et al. 2014) con incremento epsilon: ogni cella di terra riceve + // un percorso di drenaggio verso il mare o verso un bordo della mappa. + var pq = new PriorityQueue(Math.Max(16, n / 16)); + for (int y = 0; y < _h; y++) + { + for (int x = 0; x < _w; x++) + { + int i = Idx(x, y); + parent[i] = -1; + bool border = x == 0 || y == 0 || x == _w - 1 || y == _h - 1; + if (_sea[i]) + { + if (HasLandNeighbor(x, y)) + { + visited[i] = true; + filled[i] = 0; + pq.Enqueue(i, (0f, i)); + } + else + { + visited[i] = true; + } + } + else if (border) + { + visited[i] = true; + filled[i] = _elev[i]; + pq.Enqueue(i, (_elev[i], i)); + } + } + } + while (pq.TryDequeue(out int c, out _)) + { + if (!_sea[c]) order[orderCount++] = c; + int cx = c % _w, cy = c / _w; + for (int k = 0; k < 8; k++) + { + int nx = cx + Dx8[k], ny = cy + Dy8[k]; + if ((uint)nx >= (uint)_w || (uint)ny >= (uint)_h) continue; + int ni = Idx(nx, ny); + if (visited[ni]) continue; + visited[ni] = true; + parent[ni] = c; + float f = Math.Max(_elev[ni], filled[c] + eps); + filled[ni] = f; + pq.Enqueue(ni, (f, ni)); + } + } + + // accumulo di flusso in ordine inverso di estrazione (da monte a valle) + var acc = new int[n]; + for (int k = 0; k < orderCount; k++) acc[order[k]] = 1; + for (int k = orderCount - 1; k >= 0; k--) + { + int c = order[k]; + int p = parent[c]; + if (p >= 0 && !_sea[p]) acc[p] += acc[c]; + } + + // laghi: conche profonde e abbastanza estese; le altre si colmano + var hy = _p.Hydrology; + float lakeMaxSurface = LandPercentileFloat(hy.LakeMaxPercentile); + var lake = new bool[n]; + var seen = new bool[n]; + var component = new List(); + var stack = new Stack(); + for (int i = 0; i < n; i++) + { + if (seen[i] || _sea[i] || filled[i] - _elev[i] <= hy.LakeMinDepthM) continue; + component.Clear(); + stack.Push(i); + seen[i] = true; + while (stack.Count > 0) + { + int c = stack.Pop(); + component.Add(c); + int cx = c % _w, cy = c / _w; + for (int k = 0; k < 4; k++) + { + int nx = cx + Dx8[k], ny = cy + Dy8[k]; + if ((uint)nx >= (uint)_w || (uint)ny >= (uint)_h) continue; + int ni = Idx(nx, ny); + if (seen[ni] || _sea[ni] || filled[ni] - _elev[ni] <= hy.LakeMinDepthM) continue; + seen[ni] = true; + stack.Push(ni); + } + } + float surface = float.MaxValue; + foreach (int c in component) surface = Math.Min(surface, filled[c]); + if (component.Count >= hy.LakeMinCells && surface <= lakeMaxSurface) + { + foreach (int c in component) + { + lake[c] = true; + _elev[c] = surface; + } + } + } + for (int i = 0; i < n; i++) + { + if (!_sea[i] && !lake[i] && filled[i] > _elev[i]) _elev[i] = filled[i]; + } + + // sorgenti solo sopra il percentile minimo: quota massima a monte di ogni cella + float sourceMin = LandPercentileFloat(hy.MinSourcePercentile); + var maxUp = new float[n]; + for (int k = 0; k < orderCount; k++) maxUp[order[k]] = _elev[order[k]]; + for (int k = orderCount - 1; k >= 0; k--) + { + int c = order[k]; + int p = parent[c]; + if (p >= 0 && !_sea[p] && maxUp[c] > maxUp[p]) maxUp[p] = maxUp[c]; + } + + // fiumi: accumulo oltre soglia, superficie discendente verso valle, larghezza 1–4 celle + double thresholdCells = hy.RiverThresholdKm2 * 1e6 / (_cs * _cs); + var surfaceArr = new float[n]; + var river = new byte[n]; + for (int k = 0; k < orderCount; k++) + { + int c = order[k]; + if (lake[c] || acc[c] < thresholdCells || maxUp[c] < sourceMin) continue; + int w = 1; + for (int s = 1; s < hy.RiverWidthSteps.Length; s++) + { + if (acc[c] >= thresholdCells * hy.RiverWidthSteps[s]) w = s + 1; + } + float surface = (float)(_elev[c] - hy.CarveDepthM * w); + int p = parent[c]; + float downstream = p < 0 || _sea[p] ? 0.2f : river[p] > 0 ? surfaceArr[p] : lake[p] ? _elev[p] : _elev[p]; + if (surface < downstream) surface = downstream; + if (surface < 0.2f) surface = 0.2f; + surfaceArr[c] = surface; + river[c] = (byte)w; + } + + // allargamento dei fiumi e scrittura delle celle d'acqua + var riverWidth = _t.RiverWidth; + var types = _t.Types; + for (int i = 0; i < n; i++) + { + if (_sea[i]) types[i] = (byte)CellType.Sea; + else if (lake[i]) types[i] = (byte)CellType.Water; + } + for (int c = 0; c < n; c++) + { + int w = river[c]; + if (w == 0) continue; + int cx = c % _w, cy = c / _w; + int off = (w - 1) / 2; + for (int dy = 0; dy < w; dy++) + { + for (int dx = 0; dx < w; dx++) + { + int x = cx + dx - off, y = cy + dy - off; + if ((uint)x >= (uint)_w || (uint)y >= (uint)_h) continue; + int i = Idx(x, y); + if (_sea[i] || lake[i]) continue; + types[i] = (byte)CellType.Water; + if (riverWidth[i] < w) riverWidth[i] = (byte)w; + float s = surfaceArr[c]; + if (_elev[i] > s) _elev[i] = s; + } + } + } + for (int i = 0; i < n; i++) + { + if (river[i] > 0) _elev[i] = surfaceArr[i]; + } + + // valli: abbassa i dintorni dei fiumi senza scendere sotto le sponde + int radius = hy.ValleyRadiusCells; + _riverDist = new int[n]; + Array.Fill(_riverDist, int.MaxValue); + var srcHeight = new float[n]; + var bfs = new Queue(); + for (int i = 0; i < n; i++) + { + if (riverWidth[i] > 0) + { + _riverDist[i] = 0; + srcHeight[i] = _elev[i]; + bfs.Enqueue(i); + } + } + int maxDist = Math.Max(radius, _p.Cover.MarshRiverDistanceCells); + while (bfs.Count > 0) + { + int c = bfs.Dequeue(); + int d = _riverDist[c]; + if (d >= maxDist) continue; + int cx = c % _w, cy = c / _w; + for (int k = 0; k < 8; k++) + { + int nx = cx + Dx8[k], ny = cy + Dy8[k]; + if ((uint)nx >= (uint)_w || (uint)ny >= (uint)_h) continue; + int ni = Idx(nx, ny); + if (_riverDist[ni] <= d + 1) continue; + _riverDist[ni] = d + 1; + srcHeight[ni] = srcHeight[c]; + bfs.Enqueue(ni); + } + } + for (int i = 0; i < n; i++) + { + int d = _riverDist[i]; + if (d == 0 || d > radius || _sea[i] || types[i] == (byte)CellType.Water) continue; + double bank = srcHeight[i] + 0.5 + d * 0.8; + double lowered = _elev[i] - hy.ValleyDepthM * (1.0 - (double)d / (radius + 1)); + double target = Math.Max(bank, lowered); + if (target < _elev[i]) _elev[i] = (float)target; + } + } + + private bool HasLandNeighbor(int x, int y) + { + for (int k = 0; k < 8; k++) + { + int nx = x + Dx8[k], ny = y + Dy8[k]; + if ((uint)nx >= (uint)_w || (uint)ny >= (uint)_h) continue; + if (!_sea[Idx(nx, ny)]) return true; + } + return false; + } + + // percentile delle quote di terra calcolato sui float di lavoro (prima della quantizzazione) + private float LandPercentileFloat(double q) + { + var land = new List(_elev.Length); + for (int i = 0; i < _elev.Length; i += 7) + { + if (!_sea[i]) land.Add(_elev[i]); + } + if (land.Count == 0) return 0; + land.Sort(); + return land[Math.Clamp((int)(q * (land.Count - 1)), 0, land.Count - 1)]; + } + + // ------------------------------------------------------------------ altezze definitive + + private void WriteHeights() + { + var heights = _t.Heights; + Parallel.For(0, _h, y => + { + for (int x = 0; x < _w; x++) + { + int i = y * _w + x; + heights[i] = _sea[i] ? (ushort)0 : Terrain.ToDecimeters(Math.Max(0.5, _elev[i])); + } + }); + + // istogramma delle quote di terra (decimetri): percentili esatti e veloci + var histogram = new int[ushort.MaxValue + 1]; + _landCount = 0; + for (int i = 0; i < heights.Length; i++) + { + if (_t.Types[i] is (byte)CellType.Sea or (byte)CellType.Water) continue; + histogram[heights[i]]++; + _landCount++; + } + _heightHistogramSorted = new ushort[101]; + long cumulative = 0; + int next = 0; + for (int h = 0; h < histogram.Length && next <= 100; h++) + { + cumulative += histogram[h]; + while (next <= 100 && cumulative >= (long)Math.Ceiling(_landCount * next / 100.0) && cumulative > 0) + { + _heightHistogramSorted[next] = (ushort)h; + next++; + } + } + for (; next <= 100; next++) _heightHistogramSorted[next] = ushort.MaxValue; + + _slope = new float[_w * _h]; + var sampler = new TerrainSampler(_t); + Parallel.For(0, _h, y => + { + for (int x = 0; x < _w; x++) _slope[y * _w + x] = (float)sampler.CellSlope(x, y); + }); + } + + /// Quota (decimetri) al percentile q ∈ [0, 1] delle celle di terra. + private ushort Percentile(double q) => _heightHistogramSorted[Math.Clamp((int)Math.Round(q * 100), 0, 100)]; + + /// Percentile (0–1) della quota di una cella di terra. + private double PercentileOf(ushort heightDm) + { + int lo = 0, hi = 100; + while (lo < hi) + { + int mid = (lo + hi + 1) / 2; + if (_heightHistogramSorted[mid] <= heightDm) lo = mid; + else hi = mid - 1; + } + return lo / 100.0; + } +} diff --git a/src/ViaFerrea.Core/Map/NameGenerator.cs b/src/ViaFerrea.Core/Map/NameGenerator.cs new file mode 100644 index 0000000..2e3e519 --- /dev/null +++ b/src/ViaFerrea.Core/Map/NameGenerator.cs @@ -0,0 +1,55 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Data; + +namespace ViaFerrea.Core.Map; + +/// Nomi di città all'italiana composti da prefissi, radici e suffissi del serbatoio della regione. +public sealed class NameGenerator(NamePoolDef pool, Rng rng) +{ + private readonly HashSet _used = new(StringComparer.Ordinal); + + /// Un nome nuovo, mai restituito prima da questo generatore. + public string Next() + { + for (int attempt = 0; attempt < 200; attempt++) + { + string name = Compose(); + if (_used.Add(name)) return name; + } + // serbatoio esaurito: numerazione romana sul nome base + string baseName = Compose(); + for (int n = 2; ; n++) + { + string name = $"{baseName} {Roman(n)}"; + if (_used.Add(name)) return name; + } + } + + /// Riserva un nome già usato altrove (per esempio da un salvataggio). + public void Reserve(string name) => _used.Add(name); + + private string Compose() + { + if (rng.Chance(0.18)) + { + string saint = pool.Saints[rng.NextInt(pool.Saints.Count)]; + return IsVowel(saint[0]) ? $"Sant'{saint}" : $"San {saint}"; + } + string prefix = pool.Prefixes[rng.NextInt(pool.Prefixes.Count)]; + if (prefix is "San " or "Sant'") prefix = ""; + string root = pool.Roots[rng.NextInt(pool.Roots.Count)]; + string suffix = pool.Suffixes[rng.NextInt(pool.Suffixes.Count)]; + // evita doppie vocali brutte all'incontro tra radice e suffisso + if (IsVowel(root[^1]) && IsVowel(suffix[0])) root = root[..^1]; + string core = root + suffix; + return prefix + char.ToUpperInvariant(core[0]) + core[1..]; + } + + private static bool IsVowel(char c) => "AEIOUaeiouàèéìòù".Contains(c, StringComparison.Ordinal); + + private static string Roman(int n) => n switch + { + 2 => "II", 3 => "III", 4 => "IV", 5 => "V", 6 => "VI", 7 => "VII", 8 => "VIII", 9 => "IX", 10 => "X", + _ => n.ToString(System.Globalization.CultureInfo.InvariantCulture), + }; +} diff --git a/src/ViaFerrea.Core/Map/Terrain.cs b/src/ViaFerrea.Core/Map/Terrain.cs new file mode 100644 index 0000000..6aaf828 --- /dev/null +++ b/src/ViaFerrea.Core/Map/Terrain.cs @@ -0,0 +1,88 @@ +using ViaFerrea.Core.Common; + +namespace ViaFerrea.Core.Map; + +/// Tipo di cella (un byte nella mappa). +public enum CellType : byte +{ + Plain = 0, + Hill = 1, + Mountain = 2, + Forest = 3, + Field = 4, + Water = 5, + Sea = 6, + Town = 7, + Industry = 8, + Rock = 9, + Marsh = 10, +} + +/// +/// Griglia del terreno: altezze in decimetri (ushort, 0–6553,5 m), tipo di cella e larghezza +/// dei fiumi. La cella (x, y) ha il centro in ((x + 0,5)·cella, (y + 0,5)·cella) metri; +/// x cresce verso est, y verso sud. +/// +public sealed class Terrain +{ + public int Width { get; } + public int Height { get; } + public double CellSizeM { get; } + public int ChunkCells { get; } + + /// Altezze in decimetri. + public ushort[] Heights { get; } + + /// Tipi di cella (). + public byte[] Types { get; } + + /// Larghezza del fiume in celle (1–4) sulle celle d'acqua fluviali; 0 altrove (laghi compresi). + public byte[] RiverWidth { get; } + + public Terrain(int width, int height, double cellSizeM, int chunkCells) + { + Width = width; + Height = height; + CellSizeM = cellSizeM; + ChunkCells = chunkCells; + Heights = new ushort[width * height]; + Types = new byte[width * height]; + RiverWidth = new byte[width * height]; + } + + public double WidthM => Width * CellSizeM; + public double HeightM => Height * CellSizeM; + public int ChunksX => (Width + ChunkCells - 1) / ChunkCells; + public int ChunksY => (Height + ChunkCells - 1) / ChunkCells; + + public int Index(int x, int y) => y * Width + x; + + public bool InBounds(int x, int y) => (uint)x < (uint)Width && (uint)y < (uint)Height; + + /// Altezza della cella in metri. + public double CellHeightM(int x, int y) => Heights[Index(x, y)] / 10.0; + + public CellType TypeAt(int x, int y) => (CellType)Types[Index(x, y)]; + + public void SetType(int x, int y, CellType type) => Types[Index(x, y)] = (byte)type; + + /// Converte metri in quota memorizzabile (decimetri, saturata). + public static ushort ToDecimeters(double meters) => (ushort)Math.Clamp(Math.Round(meters * 10.0), 0, ushort.MaxValue); + + public bool IsWater(int x, int y) => TypeAt(x, y) is CellType.Water or CellType.Sea; + + /// Cella che contiene il punto (in metri), saturata ai bordi. + public (int X, int Y) CellAt(Vec2 p) => + (Math.Clamp((int)Math.Floor(p.X / CellSizeM), 0, Width - 1), Math.Clamp((int)Math.Floor(p.Y / CellSizeM), 0, Height - 1)); + + /// Centro della cella in metri. + public Vec2 CellCenter(int x, int y) => new((x + 0.5) * CellSizeM, (y + 0.5) * CellSizeM); + + /// Hash del terreno (altezze, tipi, fiumi). + public ulong ComputeHash() + { + ulong h1 = XxHash64.Hash(System.Runtime.InteropServices.MemoryMarshal.AsBytes(Heights.AsSpan())); + ulong h2 = XxHash64.Hash(Types, h1); + return XxHash64.Hash(RiverWidth, h2); + } +} diff --git a/src/ViaFerrea.Core/Map/TerrainSampler.cs b/src/ViaFerrea.Core/Map/TerrainSampler.cs new file mode 100644 index 0000000..88c4e14 --- /dev/null +++ b/src/ViaFerrea.Core/Map/TerrainSampler.cs @@ -0,0 +1,70 @@ +using ViaFerrea.Core.Common; + +namespace ViaFerrea.Core.Map; + +/// +/// Campionamento continuo del terreno: altezza bilineare in un punto qualsiasi (metri), +/// pendenza e esposizione per l'ombreggiatura e per il tracciamento dei binari. +/// +public sealed class TerrainSampler(Terrain terrain) +{ + public Terrain Terrain { get; } = terrain; + + /// Altezza in metri nel punto (x, y) in metri, interpolando tra i centri delle celle. + public double HeightAt(double x, double y) + { + double cs = Terrain.CellSizeM; + double gx = x / cs - 0.5, gy = y / cs - 0.5; + double fx = Math.Floor(gx), fy = Math.Floor(gy); + int x0 = (int)fx, y0 = (int)fy; + double tx = gx - fx, ty = gy - fy; + double h00 = H(x0, y0), h10 = H(x0 + 1, y0), h01 = H(x0, y0 + 1), h11 = H(x0 + 1, y0 + 1); + double a = h00 + (h10 - h00) * tx; + double b = h01 + (h11 - h01) * tx; + return a + (b - a) * ty; + } + + public double HeightAt(Vec2 p) => HeightAt(p.X, p.Y); + + /// Gradiente (dh/dx, dh/dy) adimensionale nel punto. + public Vec2 Gradient(double x, double y) + { + double d = Terrain.CellSizeM * 0.5; + double dx = (HeightAt(x + d, y) - HeightAt(x - d, y)) / (2 * d); + double dy = (HeightAt(x, y + d) - HeightAt(x, y - d)) / (2 * d); + return new Vec2(dx, dy); + } + + /// Pendenza (tangente dell'inclinazione) nel punto. + public double Slope(double x, double y) => Gradient(x, y).Length; + + /// Esposizione: direzione di massima discesa in radianti (0 = est, π/2 = sud). + public double Aspect(double x, double y) + { + var g = Gradient(x, y); + return DMath.Atan2(-g.Y, -g.X); + } + + /// Pendenza di una cella (differenze centrali tra celle vicine). + public double CellSlope(int x, int y) + { + double cs = Terrain.CellSizeM; + double dx = (H(x + 1, y) - H(x - 1, y)) / (2 * cs); + double dy = (H(x, y + 1) - H(x, y - 1)) / (2 * cs); + return Math.Sqrt(dx * dx + dy * dy); + } + + /// Tipo della cella che contiene il punto. + public CellType TypeAt(Vec2 p) + { + var (cx, cy) = Terrain.CellAt(p); + return Terrain.TypeAt(cx, cy); + } + + private double H(int x, int y) + { + x = Math.Clamp(x, 0, Terrain.Width - 1); + y = Math.Clamp(y, 0, Terrain.Height - 1); + return Terrain.Heights[y * Terrain.Width + x] / 10.0; + } +} diff --git a/src/ViaFerrea.Core/Map/ValueNoise.cs b/src/ViaFerrea.Core/Map/ValueNoise.cs new file mode 100644 index 0000000..8769014 --- /dev/null +++ b/src/ViaFerrea.Core/Map/ValueNoise.cs @@ -0,0 +1,72 @@ +namespace ViaFerrea.Core.Map; + +/// +/// Rumore di valore 2D deterministico: valori pseudo-casuali sui nodi di un reticolo intero, +/// interpolati con la curva quintica. Somme a ottave (fBm) e variante a creste. +/// Solo operazioni elementari: risultati identici su ogni piattaforma. +/// +public readonly struct ValueNoise(ulong seed) +{ + private readonly ulong _seed = seed; + + /// Valore del reticolo nel nodo (ix, iy), in [0, 1). + private double Lattice(long ix, long iy, int octave) + { + ulong h = _seed ^ ((ulong)ix * 0x9E3779B97F4A7C15UL) ^ ((ulong)iy * 0xC2B2AE3D27D4EB4FUL) ^ ((ulong)octave * 0x165667B19E3779F9UL); + h ^= h >> 30; + h *= 0xBF58476D1CE4E5B9UL; + h ^= h >> 27; + h *= 0x94D049BB133111EBUL; + h ^= h >> 31; + return (h >> 11) * (1.0 / (1UL << 53)); + } + + private static double Fade(double t) => t * t * t * (t * (t * 6 - 15) + 10); + + /// Rumore di una singola ottava in [0, 1) alla posizione (x, y) in unità di reticolo. + public double Sample(double x, double y, int octave = 0) + { + double fx = Math.Floor(x), fy = Math.Floor(y); + long ix = (long)fx, iy = (long)fy; + double tx = Fade(x - fx), ty = Fade(y - fy); + double v00 = Lattice(ix, iy, octave), v10 = Lattice(ix + 1, iy, octave); + double v01 = Lattice(ix, iy + 1, octave), v11 = Lattice(ix + 1, iy + 1, octave); + double a = v00 + (v10 - v00) * tx; + double b = v01 + (v11 - v01) * tx; + return a + (b - a) * ty; + } + + /// + /// Somma frattale (fBm) normalizzata in [0, 1]. wavelength è la lunghezza d'onda della + /// prima ottava nelle stesse unità di x e y. + /// + public double Fbm(double x, double y, int octaves, double wavelength, double persistence, double lacunarity) + { + double sum = 0, norm = 0, amp = 1, freq = 1.0 / wavelength; + for (int o = 0; o < octaves; o++) + { + sum += Sample(x * freq, y * freq, o) * amp; + norm += amp; + amp *= persistence; + freq *= lacunarity; + } + return sum / norm; + } + + /// Rumore a creste in [0, 1]: valori alti lungo linee sottili, per le catene montuose. + public double Ridged(double x, double y, int octaves, double wavelength, double persistence, double lacunarity) + { + double sum = 0, norm = 0, amp = 1, freq = 1.0 / wavelength; + for (int o = 0; o < octaves; o++) + { + double n = Sample(x * freq, y * freq, o + 17); + double r = 1.0 - Math.Abs(2.0 * n - 1.0); + r *= r; + sum += r * amp; + norm += amp; + amp *= persistence; + freq *= lacunarity; + } + return sum / norm; + } +} diff --git a/src/ViaFerrea.Core/Persistence/SaveFile.cs b/src/ViaFerrea.Core/Persistence/SaveFile.cs new file mode 100644 index 0000000..9d4e083 --- /dev/null +++ b/src/ViaFerrea.Core/Persistence/SaveFile.cs @@ -0,0 +1,120 @@ +using System.IO.Compression; +using System.Text; +using ViaFerrea.Core.Data; +using ViaFerrea.Core.Simulation; + +namespace ViaFerrea.Core.Persistence; + +/// Informazioni leggibili dall'intestazione senza decomprimere il salvataggio. +public sealed record SaveInfo(int FormatVersion, string GameVersion, ulong DataHash, ulong StateHash, long Tick, + string Date, string CompanyName, ulong Seed, int SizeKm, string Difficulty); + +/// +/// File di salvataggio: intestazione «VFSV» in chiaro + corpo binario compresso con Brotli. +/// Portabile tra Windows e Linux (little endian esplicito, nessuna dipendenza dalla piattaforma). +/// +public static class SaveFile +{ + private static readonly byte[] Magic = "VFSV"u8.ToArray(); + public const ushort FormatVersion = 1; + + /// Serializza e comprime il mondo. + public static byte[] Save(World w, string gameVersion, CompressionLevel level = CompressionLevel.Optimal) + { + var body = new SaveWriter(1 << 20); + WorldSerializer.Write(w, body); + + using var output = new MemoryStream(); + output.Write(Magic); + var header = new SaveWriter(512); + header.Write(FormatVersion); + header.Write(gameVersion); + header.Write(w.Data.Hash); + header.Write(w.LastStateHash); + header.Write(w.Clock.Tick); + header.Write(w.Clock.Date.ToString()); + header.Write(w.Companies.FirstOrDefault(c => c.IsPlayer)?.Name ?? ""); + header.Write(w.Settings.Seed); + header.Write(w.Settings.SizeKm); + header.Write(w.Settings.Difficulty.Id); + header.Write(body.Length); + output.Write(header.WrittenSpan); + using (var brotli = new BrotliStream(output, level, leaveOpen: true)) + brotli.Write(body.WrittenSpan); + return output.ToArray(); + } + + /// Legge solo l'intestazione. + public static SaveInfo ReadInfo(byte[] file) => ReadHeader(file, out _, out _); + + /// Decomprime e ricostruisce il mondo. + public static World Load(GameData data, byte[] file) + { + ReadHeader(file, out int bodyOffset, out int bodyLength); + var body = new byte[bodyLength]; + using (var input = new MemoryStream(file, bodyOffset, file.Length - bodyOffset)) + using (var brotli = new BrotliStream(input, CompressionMode.Decompress)) + { + int read = 0; + while (read < bodyLength) + { + int n = brotli.Read(body, read, bodyLength - read); + if (n == 0) throw new InvalidDataException("Corpo del salvataggio troncato"); + read += n; + } + } + return WorldSerializer.Read(data, new SaveReader(body)); + } + + public static void SaveToFile(World w, string path, string gameVersion, CompressionLevel level = CompressionLevel.Optimal) + { + string tmp = path + ".tmp"; + File.WriteAllBytes(tmp, Save(w, gameVersion, level)); + File.Move(tmp, path, overwrite: true); + } + + public static World LoadFromFile(GameData data, string path) => Load(data, File.ReadAllBytes(path)); + + private static SaveInfo ReadHeader(byte[] file, out int bodyOffset, out int bodyLength) + { + if (file.Length < 8 || !file.AsSpan(0, 4).SequenceEqual(Magic)) + throw new InvalidDataException("Non è un salvataggio di Via Ferrea"); + var r = new SaveReader(file, 4); + ushort version = r.ReadUInt16(); + if (version > FormatVersion) throw new InvalidDataException($"Formato di salvataggio più recente del gioco ({version})"); + var info = new SaveInfo(version, r.ReadRequiredString(), r.ReadUInt64(), r.ReadUInt64(), r.ReadInt64(), + r.ReadRequiredString(), r.ReadRequiredString(), r.ReadUInt64(), r.ReadInt32(), r.ReadRequiredString()); + bodyLength = r.ReadInt32(); + bodyOffset = HeaderLength(file); + return info; + } + + // ripercorre l'intestazione per trovarne la fine + private static int HeaderLength(byte[] file) + { + int pos = 4 + 2; + pos = SkipString(file, pos); + pos += 8 + 8 + 8; + pos = SkipString(file, pos); + pos = SkipString(file, pos); + pos += 8 + 4; + pos = SkipString(file, pos); + pos += 4; + return pos; + } + + private static int SkipString(byte[] file, int pos) + { + int len = BitConverter.ToInt32(file, pos); + return pos + 4 + Math.Max(0, len); + } + + /// Nome di file sicuro da un nome libero. + public static string SafeFileName(string name) + { + var sb = new StringBuilder(); + foreach (char ch in name) + sb.Append(char.IsLetterOrDigit(ch) || ch is '-' or '_' ? ch : '_'); + return sb.Length == 0 ? "salvataggio" : sb.ToString(); + } +} diff --git a/src/ViaFerrea.Core/Persistence/SaveWriter.cs b/src/ViaFerrea.Core/Persistence/SaveWriter.cs new file mode 100644 index 0000000..56e90a0 --- /dev/null +++ b/src/ViaFerrea.Core/Persistence/SaveWriter.cs @@ -0,0 +1,180 @@ +using System.Buffers.Binary; +using System.Text; + +namespace ViaFerrea.Core.Persistence; + +/// +/// Scrittore binario little endian su buffer crescente e riutilizzabile (nessuna reflection). +/// Usato per i salvataggi e, con lo stesso formato, per l'hash di stato giornaliero. +/// +public sealed class SaveWriter +{ + private byte[] _buffer; + private int _position; + + public SaveWriter(int initialCapacity = 64 * 1024) => _buffer = new byte[initialCapacity]; + + public int Length => _position; + + public ReadOnlySpan WrittenSpan => _buffer.AsSpan(0, _position); + + public byte[] ToArray() => _buffer.AsSpan(0, _position).ToArray(); + + public void Reset() => _position = 0; + + private Span Take(int count) + { + if (_position + count > _buffer.Length) + { + int size = Math.Max(_buffer.Length * 2, _position + count); + Array.Resize(ref _buffer, size); + } + var span = _buffer.AsSpan(_position, count); + _position += count; + return span; + } + + public void Write(byte v) => Take(1)[0] = v; + public void Write(bool v) => Take(1)[0] = v ? (byte)1 : (byte)0; + public void Write(short v) => BinaryPrimitives.WriteInt16LittleEndian(Take(2), v); + public void Write(ushort v) => BinaryPrimitives.WriteUInt16LittleEndian(Take(2), v); + public void Write(int v) => BinaryPrimitives.WriteInt32LittleEndian(Take(4), v); + public void Write(uint v) => BinaryPrimitives.WriteUInt32LittleEndian(Take(4), v); + public void Write(long v) => BinaryPrimitives.WriteInt64LittleEndian(Take(8), v); + public void Write(ulong v) => BinaryPrimitives.WriteUInt64LittleEndian(Take(8), v); + public void Write(double v) => BinaryPrimitives.WriteInt64LittleEndian(Take(8), BitConverter.DoubleToInt64Bits(v)); + public void Write(float v) => BinaryPrimitives.WriteInt32LittleEndian(Take(4), BitConverter.SingleToInt32Bits(v)); + + public void Write(string? v) + { + if (v is null) + { + Write(-1); + return; + } + int count = Encoding.UTF8.GetByteCount(v); + Write(count); + Encoding.UTF8.GetBytes(v, Take(count)); + } + + public void WriteBytes(ReadOnlySpan bytes) + { + Write(bytes.Length); + bytes.CopyTo(Take(bytes.Length)); + } + + public void Write(ReadOnlySpan values) + { + Write(values.Length); + foreach (int v in values) Write(v); + } + + public void Write(ReadOnlySpan values) + { + Write(values.Length); + foreach (long v in values) Write(v); + } + + public void Write(ReadOnlySpan values) + { + Write(values.Length); + foreach (double v in values) Write(v); + } + + public void Write(ReadOnlySpan values) + { + Write(values.Length); + foreach (bool v in values) Write(v); + } + + public void Write(ReadOnlySpan values) + { + Write(values.Length); + var dst = Take(values.Length * 2); + for (int i = 0; i < values.Length; i++) BinaryPrimitives.WriteUInt16LittleEndian(dst.Slice(i * 2), values[i]); + } +} + +/// Lettore corrispondente a ; lancia InvalidDataException su dati troncati. +public sealed class SaveReader(byte[] buffer, int offset = 0, int? length = null) +{ + private readonly int _end = offset + (length ?? buffer.Length - offset); + private int _position = offset; + + public bool AtEnd => _position >= _end; + + private ReadOnlySpan Take(int count) + { + if (count < 0 || _position + count > _end) throw new InvalidDataException("Salvataggio troncato o corrotto"); + var span = buffer.AsSpan(_position, count); + _position += count; + return span; + } + + public byte ReadByte() => Take(1)[0]; + public bool ReadBool() => Take(1)[0] != 0; + public short ReadInt16() => BinaryPrimitives.ReadInt16LittleEndian(Take(2)); + public ushort ReadUInt16() => BinaryPrimitives.ReadUInt16LittleEndian(Take(2)); + public int ReadInt32() => BinaryPrimitives.ReadInt32LittleEndian(Take(4)); + public uint ReadUInt32() => BinaryPrimitives.ReadUInt32LittleEndian(Take(4)); + public long ReadInt64() => BinaryPrimitives.ReadInt64LittleEndian(Take(8)); + public ulong ReadUInt64() => BinaryPrimitives.ReadUInt64LittleEndian(Take(8)); + public double ReadDouble() => BitConverter.Int64BitsToDouble(BinaryPrimitives.ReadInt64LittleEndian(Take(8))); + public float ReadSingle() => BitConverter.Int32BitsToSingle(BinaryPrimitives.ReadInt32LittleEndian(Take(4))); + + public string? ReadString() + { + int count = ReadInt32(); + if (count < 0) return null; + return Encoding.UTF8.GetString(Take(count)); + } + + public string ReadRequiredString() => ReadString() ?? throw new InvalidDataException("Stringa mancante nel salvataggio"); + + public byte[] ReadBytes() => Take(ReadInt32()).ToArray(); + + public int[] ReadInt32Array() + { + var a = new int[ReadCount(4)]; + for (int i = 0; i < a.Length; i++) a[i] = ReadInt32(); + return a; + } + + public long[] ReadInt64Array() + { + var a = new long[ReadCount(8)]; + for (int i = 0; i < a.Length; i++) a[i] = ReadInt64(); + return a; + } + + public double[] ReadDoubleArray() + { + var a = new double[ReadCount(8)]; + for (int i = 0; i < a.Length; i++) a[i] = ReadDouble(); + return a; + } + + public bool[] ReadBoolArray() + { + var a = new bool[ReadCount(1)]; + for (int i = 0; i < a.Length; i++) a[i] = ReadBool(); + return a; + } + + public ushort[] ReadUInt16Array() + { + int n = ReadCount(2); + var src = Take(n * 2); + var a = new ushort[n]; + for (int i = 0; i < n; i++) a[i] = BinaryPrimitives.ReadUInt16LittleEndian(src.Slice(i * 2)); + return a; + } + + /// Legge un conteggio e controlla che i dati necessari ci siano davvero. + public int ReadCount(int bytesPerItem) + { + int n = ReadInt32(); + if (n < 0 || (long)n * bytesPerItem > _end - _position) throw new InvalidDataException("Conteggio non valido nel salvataggio"); + return n; + } +} diff --git a/src/ViaFerrea.Core/Persistence/StateHasher.cs b/src/ViaFerrea.Core/Persistence/StateHasher.cs new file mode 100644 index 0000000..c781278 --- /dev/null +++ b/src/ViaFerrea.Core/Persistence/StateHasher.cs @@ -0,0 +1,21 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Simulation; + +namespace ViaFerrea.Core.Persistence; + +/// +/// Hash dello stato dinamico: XxHash64 della serializzazione di . +/// Stesso seme e stessi comandi agli stessi tick devono dare lo stesso hash su ogni piattaforma. +/// +public static class StateHasher +{ + [ThreadStatic] private static SaveWriter? _writer; + + public static ulong Compute(World w) + { + var writer = _writer ??= new SaveWriter(1 << 20); + writer.Reset(); + WorldSerializer.WriteDynamic(w, writer); + return XxHash64.Hash(writer.WrittenSpan); + } +} diff --git a/src/ViaFerrea.Core/Persistence/WorldSerializer.cs b/src/ViaFerrea.Core/Persistence/WorldSerializer.cs new file mode 100644 index 0000000..76a29e3 --- /dev/null +++ b/src/ViaFerrea.Core/Persistence/WorldSerializer.cs @@ -0,0 +1,705 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Data; +using ViaFerrea.Core.Economy; +using ViaFerrea.Core.Map; +using ViaFerrea.Core.Simulation; + +namespace ViaFerrea.Core.Persistence; + +/// +/// Serializzazione completa del mondo. I riferimenti alle definizioni sono salvati per id +/// (stringhe) e rimappati al caricamento: aggiungere o riordinare beni, industrie o veicoli nei +/// dati non rompe i salvataggi esistenti. Lo stesso formato dello stato dinamico alimenta l'hash. +/// +public static class WorldSerializer +{ + /// Versione del corpo del salvataggio (migrazioni in ). + public const int BodyVersion = 1; + + /// Scrive l'intero mondo (impostazioni, terreno, stato dinamico, eventi). + public static void Write(World w, SaveWriter s) + { + s.Write(BodyVersion); + WriteDictionary(w.Data, s); + WriteSettings(w.Settings, s); + WriteTerrain(w.Terrain, w.SeaSide, s); + WriteDynamic(w, s); + s.Write(w.LastStateHash); + s.Write(w.LastHashDay); + WriteEvents(w.Events, s); + } + + /// + /// Stato dinamico (tutto tranne terreno, impostazioni ed eventi): è ciò che entra nell'hash + /// giornaliero. Il terreno vi entra attraverso il suo hash. + /// + public static void WriteDynamic(World w, SaveWriter s) + { + if (w.TerrainHash == 0) w.TerrainHash = w.Terrain.ComputeHash(); + s.Write(w.TerrainHash); + s.Write(w.Clock.Tick); + + var streams = w.Streams.ToList(); + s.Write(streams.Count); + foreach (var (name, rng) in streams) + { + s.Write(name); + var (a, b, c, d) = rng.State; + s.Write(a); + s.Write(b); + s.Write(c); + s.Write(d); + } + + var ids = w.NextIds; + s.Write(ids.Contract); s.Write(ids.Loan); s.Write(ids.Industry); s.Write(ids.Station); s.Write(ids.Node); + s.Write(ids.Edge); s.Write(ids.Signal); s.Write(ids.Train); s.Write(ids.Vehicle); s.Write(ids.Line); + s.Write(ids.Packet); s.Write(ids.Depot); s.Write(ids.Work); s.Write(ids.Bid); s.Write(ids.Agreement); + s.Write(w.SpawnedThisYear); + + s.Write(w.Sites.Count); + foreach (var site in w.Sites) + { + s.Write(site.Id.Value); + s.Write((byte)site.Kind); + s.Write(site.CellX); + s.Write(site.CellY); + s.Write(site.RadiusCells); + s.Write(site.InitialReserveTonnes); + s.Write(site.ReserveTonnes); + s.Write(site.Discovered); + } + + s.Write(w.Towns.Count); + foreach (var t in w.Towns) + { + s.Write(t.Id.Value); + s.Write(t.Name); + s.Write(t.CellX); + s.Write(t.CellY); + s.Write(t.Position.X); + s.Write(t.Position.Y); + s.Write(t.RadiusCells); + s.Write(t.Population); + s.Write(t.Stock); + s.Write(t.DemandToday); + s.Write(t.DemandAccumulator); + s.Write(t.Satisfaction); + s.Write(t.CategoryActive); + s.Write(t.WorkDissatisfaction); + s.Write(t.EmployedWorkers); + s.Write(t.EmployedStaff); + s.Write(t.ServiceJobs); + s.Write(t.Services); + s.Write(t.LastGrowth); + } + + s.Write(w.Hubs.Count); + foreach (var h in w.Hubs) + { + s.Write(h.Id.Value); + s.Write((byte)h.Kind); + s.Write(h.Name); + s.Write(h.CellX); + s.Write(h.CellY); + s.Write(h.FootprintCells); + s.Write(h.Position.X); + s.Write(h.Position.Y); + s.Write(h.MonthlyCapacity); + s.Write(h.Duty); + s.Write(h.UsedThisMonth); + s.Write(h.ImportedThisMonth); + s.Write(h.ExportedThisMonth); + } + + s.Write(w.Industries.Count); + foreach (var i in w.Industries) + { + s.Write(i.Id.Value); + s.Write(i.Def.Id); + s.Write(i.Name); + s.Write(i.CellX); + s.Write(i.CellY); + s.Write(i.FootprintCells); + s.Write(i.Position.X); + s.Write(i.Position.Y); + s.Write(i.Level); + s.Write(i.Closed); + s.Write(i.Site.Value); + s.Write(i.Owner.Value); + s.Write(i.Cash.Cents); + s.Write(i.Condition); + s.Write((byte)i.Budget); + WriteRecipeStock(i.Def.Recipe.Inputs, i.InputStock, s); + WriteRecipeStock(i.Def.Recipe.Outputs, i.OutputStock, s); + s.Write(i.CycleAccumulator); + s.Write(i.CovInput); + s.Write(i.CovWorkers); + s.Write(i.CovStaff); + s.Write(i.Efficiency); + s.Write(i.WorkersPresent); + s.Write(i.StaffPresent); + s.Write(i.ContractedWorkers); + s.Write(i.ContractedStaff); + s.Write(i.RevenueEma); + s.Write(i.CostEma); + s.Write(i.QuarterProduced); + s.Write(i.QuarterShipped); + s.Write(i.QuarterCoverageSum); + s.Write(i.QuarterDays); + s.Write(i.QuartersAboveUpgrade); + s.Write(i.QuartersAtZero); + s.Write(i.LastScore); + s.Write(i.Served); + s.Write(i.SalesToday); + s.Write(i.PurchasesToday); + s.Write(i.ShippedToday); + s.Write(i.ProducedToday); + s.Write(i.InputDemandToday); + } + + var m = w.Market; + s.Write(w.Data.GoodCount); + for (int g = 0; g < w.Data.GoodCount; g++) + { + s.Write(m.GlobalPrice[g]); + s.Write(m.Shock[g]); + s.Write(m.DemandToday[g]); + s.Write(m.SupplyToday[g]); + s.Write(m.CapacityToday[g]); + s.Write(m.UnmetDays[g]); + m.Demand[g].Save(s); + m.Supply[g].Save(s); + m.PriceHistory[g].Save(s); + } + + s.Write(w.Companies.Count); + foreach (var c in w.Companies) + { + s.Write(c.Id.Value); + s.Write(c.Name); + s.Write(c.IsPlayer); + s.Write(c.AiPersonality); + s.Write(c.Color); + s.Write(c.Cash.Cents); + s.Write(c.BaseCredit.Cents); + s.Write((byte)c.Rating); + s.Write(c.Tier); + s.Write(c.NegativeCashDays); + s.Write(c.Bankrupt); + s.Write(c.FoundedDay); + s.Write(c.MonthEntries); + s.Write(c.YearEntries); + s.Write(c.LastYearEntries); + s.Write(c.AssetBookValue.Cents); + s.Write(c.Loans.Count); + foreach (var l in c.Loans) + { + s.Write(l.Id.Value); + s.Write(l.Principal.Cents); + s.Write(l.AnnualRate); + s.Write(l.TermMonths); + s.Write(l.Remaining.Cents); + s.Write(l.MonthsLeft); + } + } + + s.Write(w.Money.External.Cents); + s.Write(w.Money.TransfersCount); + var goods = w.Goods; + s.Write(goods.Produced); + s.Write(goods.Consumed); + s.Write(goods.Decayed); + s.Write(goods.Imported); + s.Write(goods.Exported); + + s.Write(w.Commutes.Count); + foreach (var c in w.Commutes) + { + s.Write(c.Id.Value); + s.Write(c.Town.Value); + s.Write((byte)c.Workplace.Kind); + s.Write(c.Workplace.Index); + s.Write((byte)c.Category); + s.Write(c.Headcount); + s.Write(c.Carrier.Value); + s.Write(c.HomeStation.Value); + s.Write(c.WorkStation.Value); + s.Write(c.Route.Count); + foreach (var line in c.Route) s.Write(line.Value); + s.Write(c.ExpectedMinutes); + s.Write(c.Coverage); + s.Write(c.LowCoverageDays); + s.Write(c.ArrivedToday); + } + } + + private static void WriteRecipeStock(List items, int[] stock, SaveWriter s) + { + s.Write(items.Count); + for (int k = 0; k < items.Count; k++) + { + s.Write(items[k].Good); + s.Write(stock[k]); + } + } + + private static void WriteDictionary(GameData data, SaveWriter s) + { + s.Write(data.Hash); + s.Write(data.GoodCount); + foreach (var g in data.Goods) s.Write(g.Id); + } + + private static void WriteSettings(WorldSettings st, SaveWriter s) + { + s.Write(st.Seed); + s.Write(st.SizeKm); + s.Write(st.StartYear); + s.Write(st.RegionId); + s.Write((ushort)st.Endless); + var d = st.Difficulty; + s.Write(d.Id); + s.Write(d.NameIt); + s.Write(d.NameEn); + s.Write(d.InitialCapital); + s.Write(d.InitialCredit); + s.Write(d.BaseInterestRate); + s.Write(d.ConstructionCostMultiplier); + s.Write(d.TariffMultiplier); + s.Write(d.WearMultiplier); + s.Write(d.MarketVolatilityMultiplier); + s.Write(d.AiCompetitors); + s.Write(d.AiCapitalMultiplier); + s.Write(d.AiCostDiscount); + s.Write((byte)d.PlayerTakeover); + s.Write(d.TakeoverRansomYears); + s.Write(d.BankruptcyDays); + s.Write(d.PublicFromStart); + s.Write(d.PlayerShareAtStart); + s.Write((byte)d.Ironman); + s.Write((byte)d.Depletion); + } + + private static void WriteTerrain(Terrain t, MapSide seaSide, SaveWriter s) + { + s.Write(t.Width); + s.Write(t.Height); + s.Write(t.CellSizeM); + s.Write(t.ChunkCells); + s.Write((byte)seaSide); + s.Write(t.Heights); + s.WriteBytes(t.Types); + s.WriteBytes(t.RiverWidth); + } + + private static void WriteEvents(EventLog events, SaveWriter s) + { + s.Write(events.Total); + s.Write(events.Recent.Count); + foreach (var e in events.Recent) + { + s.Write(e.Day); + s.Write((byte)e.Kind); + s.Write((byte)e.Severity); + s.Write(e.Text); + s.Write((byte)e.Entity); + s.Write(e.EntityIndex); + s.Write(e.Company.Value); + } + } + + // ------------------------------------------------------------------ lettura + + /// Ricostruisce un mondo da un corpo di salvataggio decompresso. + public static World Read(GameData data, SaveReader r) + { + int version = r.ReadInt32(); + if (version < 1 || version > BodyVersion) throw new InvalidDataException($"Versione del salvataggio non supportata: {version}"); + + r.ReadUInt64(); // hash dei dati al momento del salvataggio (informativo) + int savedGoods = r.ReadInt32(); + var goodMap = new int[savedGoods]; + for (int g = 0; g < savedGoods; g++) + { + string id = r.ReadRequiredString(); + goodMap[g] = data.TryGoodIndex(id, out int idx) ? idx : -1; + } + + var settings = ReadSettings(r); + var (terrain, seaSide) = ReadTerrain(r); + var w = new World(data, settings, terrain, seaSide); + ReadDynamic(w, r, goodMap); + w.LastStateHash = r.ReadUInt64(); + w.LastHashDay = r.ReadInt64(); + ReadEvents(w.Events, r); + return w; + } + + private static WorldSettings ReadSettings(SaveReader r) + { + ulong seed = r.ReadUInt64(); + int size = r.ReadInt32(); + int startYear = r.ReadInt32(); + string region = r.ReadRequiredString(); + var endless = (EndlessFlags)r.ReadUInt16(); + var d = new DifficultyDef + { + Id = r.ReadRequiredString(), + NameIt = r.ReadRequiredString(), + NameEn = r.ReadRequiredString(), + InitialCapital = r.ReadInt64(), + InitialCredit = r.ReadInt64(), + BaseInterestRate = r.ReadDouble(), + ConstructionCostMultiplier = r.ReadDouble(), + TariffMultiplier = r.ReadDouble(), + WearMultiplier = r.ReadDouble(), + MarketVolatilityMultiplier = r.ReadDouble(), + AiCompetitors = r.ReadInt32(), + AiCapitalMultiplier = r.ReadDouble(), + AiCostDiscount = r.ReadDouble(), + PlayerTakeover = (TakeoverRule)r.ReadByte(), + TakeoverRansomYears = r.ReadInt32(), + BankruptcyDays = r.ReadInt32(), + PublicFromStart = r.ReadBool(), + PlayerShareAtStart = r.ReadDouble(), + Ironman = (IronmanRule)r.ReadByte(), + Depletion = (DepletionRate)r.ReadByte(), + }; + return new WorldSettings { Seed = seed, SizeKm = size, StartYear = startYear, RegionId = region, Endless = endless, Difficulty = d }; + } + + private static (Terrain, MapSide) ReadTerrain(SaveReader r) + { + int width = r.ReadInt32(); + int height = r.ReadInt32(); + double cell = r.ReadDouble(); + int chunk = r.ReadInt32(); + var side = (MapSide)r.ReadByte(); + var t = new Terrain(width, height, cell, chunk); + var heights = r.ReadUInt16Array(); + var types = r.ReadBytes(); + var river = r.ReadBytes(); + if (heights.Length != t.Heights.Length || types.Length != t.Types.Length || river.Length != t.RiverWidth.Length) + throw new InvalidDataException("Dimensioni del terreno incoerenti nel salvataggio"); + heights.CopyTo(t.Heights, 0); + types.CopyTo(t.Types, 0); + river.CopyTo(t.RiverWidth, 0); + return (t, side); + } + + private static void ReadDynamic(World w, SaveReader r, int[] goodMap) + { + var data = w.Data; + int goods = data.GoodCount; + w.TerrainHash = r.ReadUInt64(); + w.Clock.Restore(r.ReadInt64()); + + int streams = r.ReadInt32(); + for (int i = 0; i < streams; i++) + { + string name = r.ReadRequiredString(); + w.RestoreStream(name, Rng.FromState(r.ReadUInt64(), r.ReadUInt64(), r.ReadUInt64(), r.ReadUInt64())); + } + + var ids = w.NextIds; + ids.Contract = r.ReadInt32(); ids.Loan = r.ReadInt32(); ids.Industry = r.ReadInt32(); ids.Station = r.ReadInt32(); ids.Node = r.ReadInt32(); + ids.Edge = r.ReadInt32(); ids.Signal = r.ReadInt32(); ids.Train = r.ReadInt32(); ids.Vehicle = r.ReadInt32(); ids.Line = r.ReadInt32(); + ids.Packet = r.ReadInt32(); ids.Depot = r.ReadInt32(); ids.Work = r.ReadInt32(); ids.Bid = r.ReadInt32(); ids.Agreement = r.ReadInt32(); + w.SpawnedThisYear = r.ReadInt32(); + + int sites = r.ReadInt32(); + for (int i = 0; i < sites; i++) + { + var site = new ResourceSite + { + Id = new ResourceSiteId(r.ReadInt32()), + Kind = (ResourceKind)r.ReadByte(), + CellX = r.ReadInt32(), + CellY = r.ReadInt32(), + RadiusCells = r.ReadInt32(), + InitialReserveTonnes = r.ReadInt64(), + }; + site.ReserveTonnes = r.ReadDouble(); + site.Discovered = r.ReadBool(); + w.Sites.Add(site); + } + + int towns = r.ReadInt32(); + for (int i = 0; i < towns; i++) + { + var id = new TownId(r.ReadInt32()); + string name = r.ReadRequiredString(); + int cx = r.ReadInt32(), cy = r.ReadInt32(); + var pos = new Vec2(r.ReadDouble(), r.ReadDouble()); + var t = new Town + { + Id = id, + Name = name, + CellX = cx, + CellY = cy, + Position = pos, + Stock = new int[goods], + DemandToday = new double[goods], + DemandAccumulator = new double[goods], + }; + t.RadiusCells = r.ReadDouble(); + t.Population = r.ReadInt32(); + RemapInto(r.ReadInt32Array(), goodMap, t.Stock); + RemapInto(r.ReadDoubleArray(), goodMap, t.DemandToday); + RemapInto(r.ReadDoubleArray(), goodMap, t.DemandAccumulator); + CopyInto(r.ReadDoubleArray(), t.Satisfaction); + CopyInto(r.ReadBoolArray(), t.CategoryActive); + t.WorkDissatisfaction = r.ReadDouble(); + t.EmployedWorkers = r.ReadInt32(); + t.EmployedStaff = r.ReadInt32(); + t.ServiceJobs = r.ReadInt32(); + t.Services = r.ReadInt32(); + t.LastGrowth = r.ReadDouble(); + w.Towns.Add(t); + } + + int hubs = r.ReadInt32(); + for (int i = 0; i < hubs; i++) + { + var id = new HubId(r.ReadInt32()); + var kind = (HubKind)r.ReadByte(); + string name = r.ReadRequiredString(); + int cx = r.ReadInt32(), cy = r.ReadInt32(), fp = r.ReadInt32(); + var pos = new Vec2(r.ReadDouble(), r.ReadDouble()); + var h = new Hub + { + Id = id, + Kind = kind, + Name = name, + CellX = cx, + CellY = cy, + FootprintCells = fp, + Position = pos, + MonthlyCapacity = r.ReadInt32(), + Duty = r.ReadDouble(), + ImportedThisMonth = new int[goods], + ExportedThisMonth = new int[goods], + }; + h.UsedThisMonth = r.ReadInt32(); + RemapInto(r.ReadInt32Array(), goodMap, h.ImportedThisMonth); + RemapInto(r.ReadInt32Array(), goodMap, h.ExportedThisMonth); + w.Hubs.Add(h); + } + + int industries = r.ReadInt32(); + for (int i = 0; i < industries; i++) + { + var id = new IndustryId(r.ReadInt32()); + string typeId = r.ReadRequiredString(); + if (!data.TryIndustry(typeId, out var def) || def is null) + throw new InvalidDataException($"Tipo di industria «{typeId}» assente dai dati correnti"); + string name = r.ReadRequiredString(); + int cx = r.ReadInt32(), cy = r.ReadInt32(), fp = r.ReadInt32(); + var pos = new Vec2(r.ReadDouble(), r.ReadDouble()); + var ind = new Industry + { + Id = id, + Def = def, + Name = name, + CellX = cx, + CellY = cy, + FootprintCells = fp, + Position = pos, + InputStock = new int[def.Recipe.Inputs.Count], + OutputStock = new int[def.Recipe.Outputs.Count], + ProducedToday = new int[def.Recipe.Outputs.Count], + InputDemandToday = new double[def.Recipe.Inputs.Count], + Level = r.ReadInt32(), + Closed = r.ReadBool(), + Site = new ResourceSiteId(r.ReadInt32()), + }; + ind.Owner = new CompanyId(r.ReadInt32()); + ind.Cash = new Money(r.ReadInt64()); + ind.Condition = r.ReadDouble(); + ind.Budget = (IndustryBudget)r.ReadByte(); + ReadRecipeStock(def.Recipe.Inputs, ind.InputStock, r); + ReadRecipeStock(def.Recipe.Outputs, ind.OutputStock, r); + ind.CycleAccumulator = r.ReadDouble(); + ind.CovInput = r.ReadDouble(); + ind.CovWorkers = r.ReadDouble(); + ind.CovStaff = r.ReadDouble(); + ind.Efficiency = r.ReadDouble(); + ind.WorkersPresent = r.ReadDouble(); + ind.StaffPresent = r.ReadDouble(); + ind.ContractedWorkers = r.ReadInt32(); + ind.ContractedStaff = r.ReadInt32(); + ind.RevenueEma = r.ReadDouble(); + ind.CostEma = r.ReadDouble(); + ind.QuarterProduced = r.ReadInt64(); + ind.QuarterShipped = r.ReadInt64(); + ind.QuarterCoverageSum = r.ReadDouble(); + ind.QuarterDays = r.ReadInt32(); + ind.QuartersAboveUpgrade = r.ReadInt32(); + ind.QuartersAtZero = r.ReadInt32(); + ind.LastScore = r.ReadDouble(); + ind.Served = r.ReadBool(); + ind.SalesToday = r.ReadDouble(); + ind.PurchasesToday = r.ReadDouble(); + ind.ShippedToday = r.ReadInt32(); + CopyInto(r.ReadInt32Array(), ind.ProducedToday); + CopyInto(r.ReadDoubleArray(), ind.InputDemandToday); + w.Industries.Add(ind); + } + + var m = w.Market; + int savedGoods = r.ReadInt32(); + var demand = new RollingWindow[goods]; + var supply = new RollingWindow[goods]; + var history = new RollingWindow[goods]; + for (int g = 0; g < goods; g++) + { + demand[g] = m.Demand[g]; + supply[g] = m.Supply[g]; + history[g] = m.PriceHistory[g]; + } + for (int sg = 0; sg < savedGoods; sg++) + { + int g = sg < goodMap.Length ? goodMap[sg] : -1; + double price = r.ReadDouble(), shock = r.ReadDouble(), dt = r.ReadDouble(), st = r.ReadDouble(), ct = r.ReadDouble(); + int unmet = r.ReadInt32(); + var dw = RollingWindow.Load(r); + var sw = RollingWindow.Load(r); + var hw = RollingWindow.Load(r); + if (g < 0) continue; + m.GlobalPrice[g] = price; + m.Shock[g] = shock; + m.DemandToday[g] = dt; + m.SupplyToday[g] = st; + m.CapacityToday[g] = ct; + m.UnmetDays[g] = unmet; + demand[g] = dw; + supply[g] = sw; + history[g] = hw; + } + m.Restore(demand, supply, history); + + int companies = r.ReadInt32(); + for (int i = 0; i < companies; i++) + { + var cid = new CompanyId(r.ReadInt32()); + string cname = r.ReadRequiredString(); + bool isPlayer = r.ReadBool(); + string? personality = r.ReadString(); + string color = r.ReadRequiredString(); + var cash = new Money(r.ReadInt64()); + var baseCredit = new Money(r.ReadInt64()); + var rating = (CreditRating)r.ReadByte(); + int tier = r.ReadInt32(); + int negDays = r.ReadInt32(); + bool bankrupt = r.ReadBool(); + long founded = r.ReadInt64(); + var c = new Company + { + Id = cid, + Name = cname, + IsPlayer = isPlayer, + AiPersonality = personality, + Color = color, + FoundedDay = founded, + Cash = cash, + BaseCredit = baseCredit, + Rating = rating, + Tier = tier, + NegativeCashDays = negDays, + Bankrupt = bankrupt, + }; + CopyInto(r.ReadInt64Array(), c.MonthEntries); + CopyInto(r.ReadInt64Array(), c.YearEntries); + CopyInto(r.ReadInt64Array(), c.LastYearEntries); + c.AssetBookValue = new Money(r.ReadInt64()); + int loans = r.ReadInt32(); + for (int k = 0; k < loans; k++) + { + var loan = new Loan + { + Id = new LoanId(r.ReadInt32()), + Principal = new Money(r.ReadInt64()), + AnnualRate = r.ReadDouble(), + TermMonths = r.ReadInt32(), + }; + loan.Remaining = new Money(r.ReadInt64()); + loan.MonthsLeft = r.ReadInt32(); + c.Loans.Add(loan); + } + w.Companies.Add(c); + } + + w.Money.External = new Money(r.ReadInt64()); + w.Money.TransfersCount = r.ReadInt64(); + RemapInto(r.ReadInt64Array(), goodMap, w.Goods.Produced); + RemapInto(r.ReadInt64Array(), goodMap, w.Goods.Consumed); + RemapInto(r.ReadInt64Array(), goodMap, w.Goods.Decayed); + RemapInto(r.ReadInt64Array(), goodMap, w.Goods.Imported); + RemapInto(r.ReadInt64Array(), goodMap, w.Goods.Exported); + + int commutes = r.ReadInt32(); + for (int i = 0; i < commutes; i++) + { + var id = new ContractId(r.ReadInt32()); + var town = new TownId(r.ReadInt32()); + var wk = (WorkplaceKind)r.ReadByte(); + int widx = r.ReadInt32(); + var cat = (PaxClass)r.ReadByte(); + var c = new CommuteContract + { + Id = id, + Town = town, + Workplace = new WorkplaceRef(wk, widx), + Category = cat, + Headcount = r.ReadInt32(), + }; + c.Carrier = new CompanyId(r.ReadInt32()); + c.HomeStation = new StationId(r.ReadInt32()); + c.WorkStation = new StationId(r.ReadInt32()); + int route = r.ReadInt32(); + for (int k = 0; k < route; k++) c.Route.Add(new LineId(r.ReadInt32())); + c.ExpectedMinutes = r.ReadDouble(); + c.Coverage = r.ReadDouble(); + c.LowCoverageDays = r.ReadInt32(); + c.ArrivedToday = r.ReadInt32(); + w.Commutes.Add(c); + } + } + + private static void ReadRecipeStock(List items, int[] stock, SaveReader r) + { + int n = r.ReadInt32(); + for (int k = 0; k < n; k++) + { + string good = r.ReadRequiredString(); + int qty = r.ReadInt32(); + int idx = items.FindIndex(it => it.Good == good); + if (idx >= 0) stock[idx] = qty; + } + } + + private static void ReadEvents(EventLog events, SaveReader r) + { + long total = r.ReadInt64(); + int n = r.ReadInt32(); + var list = new List(n); + for (int i = 0; i < n; i++) + { + list.Add(new GameEvent(r.ReadInt64(), (EventKind)r.ReadByte(), (EventSeverity)r.ReadByte(), r.ReadRequiredString(), + (EntityKind)r.ReadByte(), r.ReadInt32(), new CompanyId(r.ReadInt32()))); + } + events.Restore(list, total); + } + + private static void RemapInto(T[] saved, int[] goodMap, T[] target) + { + for (int sg = 0; sg < saved.Length && sg < goodMap.Length; sg++) + { + int g = goodMap[sg]; + if (g >= 0) target[g] = saved[sg]; + } + } + + private static void CopyInto(T[] source, T[] target) => Array.Copy(source, target, Math.Min(source.Length, target.Length)); +} diff --git a/src/ViaFerrea.Core/Simulation/CommandProcessor.cs b/src/ViaFerrea.Core/Simulation/CommandProcessor.cs new file mode 100644 index 0000000..67f451e --- /dev/null +++ b/src/ViaFerrea.Core/Simulation/CommandProcessor.cs @@ -0,0 +1,72 @@ +using ViaFerrea.Core.Commands; +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Economy; +using ViaFerrea.Core.Simulation.Systems; + +namespace ViaFerrea.Core.Simulation; + +/// Esecuzione dei comandi di gioco con validazione completa: un comando non valido non cambia nulla. +public static class CommandProcessor +{ + public static CommandResult Execute(World w, GameCommand command, WorldContext ctx) + { + CommandResult Result(CommandError error, string message) => new(command.Issuer, command.Seq, command.Type, error, message, ctx.Tick); + + if (!command.Issuer.IsValid || command.Issuer.Value >= w.Companies.Count) + return Result(CommandError.UnknownCompany, "Compagnia sconosciuta"); + var company = w.Companies[command.Issuer.Value]; + if (company.Bankrupt) + return Result(CommandError.Bankrupt, "La compagnia è in bancarotta"); + + return command switch + { + TakeLoanCommand c => TakeLoan(w, company, c, Result), + RepayLoanCommand c => RepayLoan(w, company, c, Result), + SetIndustryPolicyCommand c => SetIndustryPolicy(w, company, c, Result), + _ => Result(CommandError.NotImplemented, $"Comando {command.Type} non ancora disponibile"), + }; + } + + private static CommandResult TakeLoan(World w, Company company, TakeLoanCommand c, Func result) + { + if (c.Amount.Cents <= 0) return result(CommandError.InvalidArgument, "Importo non valido"); + var max = FinanceSystem.MaxLoan(w, company); + if (company.Debt + c.Amount > max) + return result(CommandError.CreditLimit, $"Fido insufficiente: disponibili {(max - company.Debt).ToString()}"); + var fb = w.Data.Balance.Finance; + var loan = new Loan + { + Id = new LoanId(w.NextIds.Loan++), + Principal = c.Amount, + AnnualRate = FinanceSystem.LoanRate(w, company), + TermMonths = fb.LoanTermMonths, + Remaining = c.Amount, + MonthsLeft = fb.LoanTermMonths, + }; + company.Loans.Add(loan); + w.Money.Transfer(Account.External, Account.Of(company.Id), c.Amount, LedgerEntry.LoanTaken); + return result(CommandError.None, $"Prestito di {c.Amount} al {loan.AnnualRate * 100:F1}% per {loan.TermMonths / 12} anni"); + } + + private static CommandResult RepayLoan(World w, Company company, RepayLoanCommand c, Func result) + { + var loan = company.Loans.FirstOrDefault(l => l.Id == c.Loan); + if (loan is null) return result(CommandError.NotFound, "Prestito inesistente"); + if (c.Amount.Cents <= 0) return result(CommandError.InvalidArgument, "Importo non valido"); + var amount = Money.Min(c.Amount, loan.Remaining); + if (company.Cash < amount) return result(CommandError.InsufficientFunds, "Cassa insufficiente"); + w.Money.Transfer(Account.Of(company.Id), Account.External, amount, LedgerEntry.LoanRepaid); + loan.Remaining -= amount; + if (loan.Remaining.Cents <= 0) company.Loans.Remove(loan); + return result(CommandError.None, $"Rimborsati {amount}"); + } + + private static CommandResult SetIndustryPolicy(World w, Company company, SetIndustryPolicyCommand c, Func result) + { + if (!c.Industry.IsValid || c.Industry.Value >= w.Industries.Count) return result(CommandError.NotFound, "Industria inesistente"); + var ind = w.Industries[c.Industry.Value]; + if (ind.Owner != company.Id) return result(CommandError.NotAllowed, "L'industria non appartiene alla compagnia"); + ind.Budget = c.Budget; + return result(CommandError.None, $"Budget di manutenzione di {ind.Name}: {c.Budget}"); + } +} diff --git a/src/ViaFerrea.Core/Simulation/GameEvents.cs b/src/ViaFerrea.Core/Simulation/GameEvents.cs new file mode 100644 index 0000000..9cbb9a3 --- /dev/null +++ b/src/ViaFerrea.Core/Simulation/GameEvents.cs @@ -0,0 +1,66 @@ +using ViaFerrea.Core.Common; + +namespace ViaFerrea.Core.Simulation; + +/// Gravità di un evento mostrato al giocatore. +public enum EventSeverity : byte { Info = 0, Opportunity = 1, Warning = 2, Critical = 3 } + +/// Categoria di un evento (per filtri, notizie e statistiche). +public enum EventKind : byte +{ + General = 0, + Market = 1, + Industry = 2, + Town = 3, + Finance = 4, + Construction = 5, + Train = 6, + Maintenance = 7, + Employment = 8, + Company = 9, +} + +/// Riferimento facoltativo all'entità coinvolta. +public enum EntityKind : byte { None = 0, Town = 1, Industry = 2, Hub = 3, Company = 4, Station = 5, Train = 6, Depot = 7, Line = 8 } + +/// Evento della simulazione destinato a notifiche, ticker e Cronaca. +public sealed record GameEvent(long Day, EventKind Kind, EventSeverity Severity, string Text, + EntityKind Entity = EntityKind.None, int EntityIndex = -1, CompanyId Company = default); + +/// Coda degli eventi in uscita: il server la svuota a ogni tick, i test la ispezionano. +public sealed class EventLog +{ + private readonly List _pending = []; + private readonly List _recent = []; + private const int RecentCapacity = 500; + + public IReadOnlyList Pending => _pending; + + /// Ultimi eventi (per la Cronaca e i nuovi client). + public IReadOnlyList Recent => _recent; + + public long Total { get; private set; } + + public void Add(GameEvent e) + { + _pending.Add(e); + _recent.Add(e); + if (_recent.Count > RecentCapacity) _recent.RemoveAt(0); + Total++; + } + + /// Restituisce e azzera gli eventi in attesa. + public List Drain() + { + var list = new List(_pending); + _pending.Clear(); + return list; + } + + internal void Restore(IEnumerable recent, long total) + { + _recent.Clear(); + _recent.AddRange(recent); + Total = total; + } +} diff --git a/src/ViaFerrea.Core/Simulation/ISimSystem.cs b/src/ViaFerrea.Core/Simulation/ISimSystem.cs new file mode 100644 index 0000000..ab9f823 --- /dev/null +++ b/src/ViaFerrea.Core/Simulation/ISimSystem.cs @@ -0,0 +1,33 @@ +namespace ViaFerrea.Core.Simulation; + +/// Un sistema della simulazione: chiamato una volta per tick in ordine fisso. +public interface ISimSystem +{ + /// Nome per profilazione e diagnostica. + string Name { get; } + + void Step(WorldContext ctx); +} + +/// +/// Contesto del tick: riferimenti al mondo e indicatori di calendario calcolati una volta dal +/// sistema Clock. Riutilizzato a ogni tick: nessuna allocazione. +/// +public sealed class WorldContext(World world) +{ + public World World { get; } = world; + public Data.GameData Data => World.Data; + + public long Tick { get; internal set; } + public long Day { get; internal set; } + public int Year { get; internal set; } + public bool IsNewDay { get; internal set; } + public bool IsNewMonth { get; internal set; } + public bool IsNewQuarter { get; internal set; } + public bool IsNewYear { get; internal set; } + + public void Emit(GameEvent e) => World.Events.Add(e); + + public void Emit(EventKind kind, EventSeverity severity, string text, EntityKind entity = EntityKind.None, int index = -1) => + World.Events.Add(new GameEvent(Day, kind, severity, text, entity, index)); +} diff --git a/src/ViaFerrea.Core/Simulation/IndustryPlacer.cs b/src/ViaFerrea.Core/Simulation/IndustryPlacer.cs new file mode 100644 index 0000000..543dca6 --- /dev/null +++ b/src/ViaFerrea.Core/Simulation/IndustryPlacer.cs @@ -0,0 +1,212 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Data; +using ViaFerrea.Core.Economy; +using ViaFerrea.Core.Map; + +namespace ViaFerrea.Core.Simulation; + +/// Creazione e collocazione delle industrie durante la partita (nascita per domanda insoddisfatta). +public static class IndustryPlacer +{ + /// Crea l'oggetto industria con scorte iniziali e cassa di avvio (dal conto Esterno). + public static Industry Create(World w, IndustryDef def, string name, int cellX, int cellY, int footprint, int level, ResourceSiteId site) + { + var ib = w.Data.Balance.Industry; + var ind = new Industry + { + Id = new IndustryId(w.Industries.Count), + Def = def, + Name = name, + CellX = cellX, + CellY = cellY, + FootprintCells = footprint, + Position = w.Terrain.CellCenter(cellX, cellY), + Level = level, + Site = site, + InputStock = new int[def.Recipe.Inputs.Count], + OutputStock = new int[def.Recipe.Outputs.Count], + ProducedToday = new int[def.Recipe.Outputs.Count], + InputDemandToday = new double[def.Recipe.Inputs.Count], + CovWorkers = ib.OnSiteWorkerShare, + CovStaff = def.StaffPerLevel[0] == 0 ? 1.0 : ib.OnSiteStaffShare, + }; + w.Industries.Add(ind); + w.NextIds.Industry = w.Industries.Count; + + int dpm = w.Calendar.DaysPerMonth; + double cycles = ind.CyclesPerDayAtFullCapacity(dpm) * ib.InitialStockDays; + for (int i = 0; i < def.Recipe.Inputs.Count; i++) + { + int units = (int)Math.Round(cycles * def.Recipe.Inputs[i].PerCycle); + ind.InputStock[i] = units; + w.Goods.Produced[def.Recipe.Inputs[i].GoodIndex] += units; + } + for (int o = 0; o < def.Recipe.Outputs.Count; o++) + { + int units = (int)Math.Round(cycles * def.Recipe.Outputs[o].PerCycle); + ind.OutputStock[o] = units; + w.Goods.Produced[def.Recipe.Outputs[o].GoodIndex] += units; + } + w.Money.Transfer(Account.External, Account.Of(ind.Id), new Money(ib.StartingCash), LedgerEntry.Other); + MarkFootprint(w, cellX, cellY, footprint, CellType.Industry); + return ind; + } + + /// Prova a far nascere un produttore del bene; restituisce null se nessun sito è adatto. + public static Industry? TrySpawnProducer(World w, int good, int year) + { + var rng = w.Stream("industries.spawn"); + var candidates = w.Data.Industries + .Where(d => d.Era <= year && d.Recipe.Outputs.Any(o => o.GoodIndex == good)) + .Where(d => d.Recipe.Inputs.All(input => w.Industries.Any(i => !i.Closed && i.OutputIndexOf(input.GoodIndex) >= 0))) + .ToList(); + while (candidates.Count > 0) + { + double total = candidates.Sum(c => c.SpawnWeight); + double r = rng.NextDouble() * total; + int pick = candidates.Count - 1; + for (int i = 0; i < candidates.Count; i++) + { + r -= candidates[i].SpawnWeight; + if (r < 0) { pick = i; break; } + } + var def = candidates[pick]; + candidates.RemoveAt(pick); + if (TryFindSite(w, def, rng, out int x, out int y, out var site)) + { + int footprint = FootprintCells(w, def.Footprint); + string townName = w.Towns.Count > 0 ? w.Towns.MinBy(t => w.TownEdgeDistanceKm(t, w.Terrain.CellCenter(x, y)))!.Name : ""; + string name = $"{def.NameIt} di {townName}"; + var features = w.Data.Regions.FeatureNames; + for (int k = 0; k < features.Count && w.Industries.Any(i => i.Name == name); k++) + name = $"{def.NameIt} {features[(k + rng.NextInt(features.Count)) % features.Count]}"; + if (w.Industries.Any(i => i.Name == name)) name = $"{def.NameIt} di {townName} ({w.Industries.Count + 1})"; + return Create(w, def, name, x, y, footprint, 1, site); + } + } + return null; + } + + private static bool TryFindSite(World w, IndustryDef def, Rng rng, out int x, out int y, out ResourceSiteId site) + { + var pl = def.Placement; + var mapGen = w.Data.Balance.Map.Industries; + int footprint = FootprintCells(w, def.Footprint); + double cs = w.Terrain.CellSizeM; + site = ResourceSiteId.None; + x = y = -1; + for (int attempt = 0; attempt < mapGen.PlacementAttempts; attempt++) + { + int cx, cy; + switch (pl.Needs) + { + case PlacementNeed.Deposit: + { + var free = w.Sites.Where(s => s.Kind == pl.Resource && s.Discovered && s.ReserveTonnes > 0 + && !w.Industries.Any(i => !i.Closed && i.Site == s.Id)).ToList(); + if (free.Count == 0) return false; + var s = free[rng.NextInt(free.Count)]; + cx = s.CellX + rng.NextInt(-s.RadiusCells, s.RadiusCells + 1); + cy = s.CellY + rng.NextInt(-s.RadiusCells, s.RadiusCells + 1); + if (Valid(w, def, cx, cy, footprint)) { x = cx; y = cy; site = s.Id; return true; } + continue; + } + case PlacementNeed.Plain: + case PlacementNeed.Town: + { + var towns = w.Towns.Where(t => t.Population >= (pl.MinTownPopulation ?? 0)).ToList(); + if (towns.Count == 0) return false; + var t = towns[rng.NextInt(towns.Count)]; + double angle = rng.NextDouble() * DMath.TwoPi; + double dist = t.RadiusCells + footprint * 0.75 + rng.NextDouble(pl.MinTownDistanceKm ?? 0, pl.MaxTownDistanceKm ?? 3) * 1000 / cs; + cx = (int)Math.Round(t.CellX + DMath.Cos(angle) * dist); + cy = (int)Math.Round(t.CellY + DMath.Sin(angle) * dist); + break; + } + case PlacementNeed.Forest: + cx = rng.NextInt(w.Terrain.Width); + cy = rng.NextInt(w.Terrain.Height); + if (w.Terrain.TypeAt(cx, cy) != CellType.Forest) continue; + break; + default: + { + var producers = w.Industries.Where(i => !i.Closed && def.Recipe.Inputs.Any(inp => i.OutputIndexOf(inp.GoodIndex) >= 0)).ToList(); + if (producers.Count == 0) return false; + var anchor = producers[rng.NextInt(producers.Count)]; + double angle = rng.NextDouble() * DMath.TwoPi; + double dist = rng.NextDouble() * (pl.MaxInputDistanceKm ?? 12) * 1000 / cs; + cx = (int)Math.Round(anchor.CellX + DMath.Cos(angle) * dist); + cy = (int)Math.Round(anchor.CellY + DMath.Sin(angle) * dist); + break; + } + } + if (Valid(w, def, cx, cy, footprint)) + { + x = cx; + y = cy; + return true; + } + } + return false; + } + + private static bool Valid(World w, IndustryDef def, int cx, int cy, int footprint) + { + var t = w.Terrain; + var mapGen = w.Data.Balance.Map.Industries; + var (x0, y0) = GeneratedMap.FootprintOrigin(cx, cy, footprint); + int spacing = mapGen.SpacingCells; + bool nextToTown = def.Placement.Needs == PlacementNeed.Town; + for (int y = y0 - spacing; y < y0 + footprint + spacing; y++) + { + for (int x = x0 - spacing; x < x0 + footprint + spacing; x++) + { + if (!t.InBounds(x, y)) return false; + var type = t.TypeAt(x, y); + bool inside = x >= x0 && x < x0 + footprint && y >= y0 && y < y0 + footprint; + if (inside) + { + if (type is CellType.Water or CellType.Sea or CellType.Town or CellType.Industry) return false; + if (w.Sampler.CellSlope(x, y) > mapGen.MaxSlope) return false; + } + else if (type == CellType.Industry || (type == CellType.Town && !nextToTown)) + { + return false; + } + } + } + var p = t.CellCenter(cx, cy); + double nearest = w.Towns.Count == 0 ? double.MaxValue : w.Towns.Min(town => w.TownEdgeDistanceKm(town, p)); + var pl = def.Placement; + if (pl.MinTownDistanceKm is { } mn && nearest < mn) return false; + if (pl.MaxTownDistanceKm is { } mx && nearest > mx) return false; + if (pl.MaxInputDistanceKm is { } maxIn) + { + foreach (var input in def.Recipe.Inputs) + { + bool near = w.Industries.Any(i => !i.Closed && i.OutputIndexOf(input.GoodIndex) >= 0 + && Vec2.Distance(i.Position, p) <= maxIn * 1000); + if (!near) return false; + } + } + return true; + } + + public static int FootprintCells(World w, Footprint footprint) => + w.Data.Balance.Industry.FootprintCells[footprint.ToString().ToLowerInvariant()]; + + public static void ClearFootprint(World w, Industry ind) => MarkFootprint(w, ind.CellX, ind.CellY, ind.FootprintCells, CellType.Plain); + + private static void MarkFootprint(World w, int cx, int cy, int size, CellType type) + { + var (x0, y0) = GeneratedMap.FootprintOrigin(cx, cy, size); + for (int y = y0; y < y0 + size; y++) + { + for (int x = x0; x < x0 + size; x++) + { + if (w.Terrain.InBounds(x, y)) w.Terrain.SetType(x, y, type); + } + } + w.TerrainHash = 0; // ricalcolato al prossimo hash di stato + } +} diff --git a/src/ViaFerrea.Core/Simulation/SystemPipeline.cs b/src/ViaFerrea.Core/Simulation/SystemPipeline.cs new file mode 100644 index 0000000..94952fc --- /dev/null +++ b/src/ViaFerrea.Core/Simulation/SystemPipeline.cs @@ -0,0 +1,53 @@ +using System.Diagnostics; +using ViaFerrea.Core.Simulation.Systems; + +namespace ViaFerrea.Core.Simulation; + +/// +/// Sistemi nell'ordine fisso della guida (sezione 4). I sistemi delle fasi successive si +/// inseriscono nella loro posizione quando vengono implementati: +/// Clock → Commands → Construction → Trains → Signals → Stations (+ trasporto locale) +/// → Maintenance → Demand → Commuting → Industries → IndustryMaintenance → Towns → Market +/// → Finance → StockMarket → AiAgents → Events → Contracts → Hash. +/// +public sealed class SystemPipeline(IReadOnlyList systems) +{ + public IReadOnlyList Systems { get; } = systems; + + /// Se attivo, misura il tempo di ogni sistema (diagnostica e bench). + public bool Profile { get; set; } + + /// Tick totali (Stopwatch) spesi per sistema quando Profile è attivo. + public long[] ElapsedTicks { get; } = new long[systems.Count]; + + public static SystemPipeline CreateDefault() => new( + [ + new ClockSystem(), + new CommandSystem(), + new LocalTransportSystem(), + new DemandSystem(), + new EmploymentSystem(), + new IndustrySystem(), + new TownSystem(), + new MarketSystem(), + new FinanceSystem(), + new HashSystem(), + ]); + + public void Run(WorldContext ctx) + { + if (!Profile) + { + for (int i = 0; i < Systems.Count; i++) Systems[i].Step(ctx); + return; + } + for (int i = 0; i < Systems.Count; i++) + { + long start = Stopwatch.GetTimestamp(); + Systems[i].Step(ctx); + ElapsedTicks[i] += Stopwatch.GetTimestamp() - start; + } + } + + public T Get() where T : ISimSystem => Systems.OfType().First(); +} diff --git a/src/ViaFerrea.Core/Simulation/Systems/ClockSystem.cs b/src/ViaFerrea.Core/Simulation/Systems/ClockSystem.cs new file mode 100644 index 0000000..4294636 --- /dev/null +++ b/src/ViaFerrea.Core/Simulation/Systems/ClockSystem.cs @@ -0,0 +1,19 @@ +namespace ViaFerrea.Core.Simulation.Systems; + +/// Primo sistema del tick: calcola una volta gli indicatori di calendario. +public sealed class ClockSystem : ISimSystem +{ + public string Name => "Clock"; + + public void Step(WorldContext ctx) + { + var clock = ctx.World.Clock; + ctx.Tick = clock.Tick; + ctx.Day = clock.Day; + ctx.Year = clock.Year; + ctx.IsNewDay = clock.IsNewDay; + ctx.IsNewMonth = clock.IsNewMonth; + ctx.IsNewQuarter = clock.IsNewQuarter; + ctx.IsNewYear = clock.IsNewYear; + } +} diff --git a/src/ViaFerrea.Core/Simulation/Systems/CommandSystem.cs b/src/ViaFerrea.Core/Simulation/Systems/CommandSystem.cs new file mode 100644 index 0000000..a7be557 --- /dev/null +++ b/src/ViaFerrea.Core/Simulation/Systems/CommandSystem.cs @@ -0,0 +1,20 @@ +using ViaFerrea.Core.Commands; + +namespace ViaFerrea.Core.Simulation.Systems; + +/// Drena la coda dei comandi a inizio tick e ne registra gli esiti. +public sealed class CommandSystem : ISimSystem +{ + public string Name => "Commands"; + + public void Step(WorldContext ctx) + { + var world = ctx.World; + while (world.TryDequeueCommand(out var command)) + { + world.CommandLog?.Add((ctx.Tick, command)); + var result = CommandProcessor.Execute(world, command, ctx); + world.AddResult(result); + } + } +} diff --git a/src/ViaFerrea.Core/Simulation/Systems/DemandSystem.cs b/src/ViaFerrea.Core/Simulation/Systems/DemandSystem.cs new file mode 100644 index 0000000..d1882b3 --- /dev/null +++ b/src/ViaFerrea.Core/Simulation/Systems/DemandSystem.cs @@ -0,0 +1,62 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Economy; + +namespace ViaFerrea.Core.Simulation.Systems; + +/// +/// Domanda giornaliera: consumo desiderato delle città (con elasticità al prezzo) e input +/// richiesti dalle industrie al loro potenziale di lavoro. 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; + foreach (var ind in w.Industries) + { + if (ind.Closed || ind.Level <= 0) + { + Array.Clear(ind.InputDemandToday); + continue; + } + 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; + double priceFactor = DMath.Clamp(DMath.Pow(ratio, -def.Elasticity), 0.5, 1.5); + return town.Population / 1000.0 * td.DemandPerThousand * priceFactor; + } +} diff --git a/src/ViaFerrea.Core/Simulation/Systems/EmploymentSystem.cs b/src/ViaFerrea.Core/Simulation/Systems/EmploymentSystem.cs new file mode 100644 index 0000000..90f2a68 --- /dev/null +++ b/src/ViaFerrea.Core/Simulation/Systems/EmploymentSystem.cs @@ -0,0 +1,151 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Data; +using ViaFerrea.Core.Economy; + +namespace ViaFerrea.Core.Simulation.Systems; + +/// +/// Pendolarismo (guida, sezione 9). In F1 gestisce i servizi cittadini, i lavoratori in sede e i +/// contratti a piedi verso posti di lavoro entro il raggio pedonale; i contratti su rotaia +/// arrivano in F4 con il LineGraph. Ogni mese ricostruisce i contratti a piedi; ogni giorno +/// aggiorna presenze e coperture. +/// +public sealed class EmploymentSystem : ISimSystem +{ + public string Name => "Commuting"; + + public void Step(WorldContext ctx) + { + if (!ctx.IsNewDay) return; + if (ctx.IsNewMonth) Rematch(ctx); + UpdatePresence(ctx); + } + + /// Ricostruisce servizi cittadini e contratti a piedi. + public static void Rematch(WorldContext ctx) + { + var w = ctx.World; + var tb = w.Data.Balance.Town; + var ib = w.Data.Balance.Industry; + var eb = w.Data.Balance.Employment; + + w.Commutes.RemoveAll(c => c.Walking); + + foreach (var town in w.Towns) + { + int workforce = town.Workforce(tb); + town.ServiceJobs = Math.Min(workforce, (int)(town.Population * tb.ServiceJobsShare)); + town.EmployedWorkers = town.ServiceJobs; + town.EmployedStaff = 0; + } + // i contratti su rotaia (F4) restano validi e occupano forza lavoro + foreach (var c in w.Commutes) + { + var town = w.Towns[c.Town.Value]; + if (c.Category == PaxClass.Staff) town.EmployedStaff += c.Headcount; + else town.EmployedWorkers += c.Headcount; + } + + foreach (var ind in w.Industries) + { + ind.ContractedWorkers = 0; + ind.ContractedStaff = 0; + } + foreach (var c in w.Commutes) + { + if (c.Workplace.Kind != WorkplaceKind.Industry) continue; + var ind = w.Industries[c.Workplace.Index]; + if (c.Category == PaxClass.Staff) ind.ContractedStaff += c.Headcount; + else ind.ContractedWorkers += c.Headcount; + } + + var nearby = new List<(double Km, Town Town)>(); + foreach (var ind in w.Industries) + { + if (ind.Closed || ind.Level <= 0) continue; + nearby.Clear(); + foreach (var town in w.Towns) + { + double km = w.TownEdgeDistanceKm(town, ind.Position); + if (km <= eb.WalkRadiusKm) nearby.Add((km, town)); + } + if (nearby.Count == 0) continue; + nearby.Sort((a, b) => a.Km != b.Km ? a.Km.CompareTo(b.Km) : a.Town.Id.Value.CompareTo(b.Town.Id.Value)); + + int openWorkers = ind.JobsWorkers - (int)Math.Ceiling(OnSite(ind.JobsWorkers, ib.OnSiteWorkerShare)) - ind.ContractedWorkers; + int openStaff = ind.JobsStaff - (int)Math.Ceiling(OnSite(ind.JobsStaff, ib.OnSiteStaffShare)) - ind.ContractedStaff; + foreach (var (km, town) in nearby) + { + if (openWorkers > 0) + { + int take = Math.Min(openWorkers, town.FreeWorkers(tb)); + if (take > 0) + { + AddWalking(w, town, ind, PaxClass.Worker, take, km, eb); + town.EmployedWorkers += take; + ind.ContractedWorkers += take; + openWorkers -= take; + } + } + if (openStaff > 0) + { + int take = Math.Min(openStaff, town.FreeStaff(tb)); + if (take > 0) + { + AddWalking(w, town, ind, PaxClass.Staff, take, km, eb); + town.EmployedStaff += take; + ind.ContractedStaff += take; + openStaff -= take; + } + } + } + } + } + + private static void AddWalking(World w, Town town, Industry ind, PaxClass category, int headcount, double km, EmploymentBalance eb) + { + w.Commutes.Add(new CommuteContract + { + Id = new ContractId(w.NextIds.Contract++), + Town = town.Id, + Workplace = WorkplaceRef.Of(ind.Id), + Category = category, + Headcount = headcount, + ExpectedMinutes = km / eb.WalkSpeedKmh * 60.0, + }); + } + + /// Posti coperti da chi vive in sede (quota fissa dei posti, frazionaria). + public static double OnSite(int jobs, double share) => jobs * share; + + private static void UpdatePresence(WorldContext ctx) + { + var w = ctx.World; + var ib = w.Data.Balance.Industry; + var eb = w.Data.Balance.Employment; + foreach (var ind in w.Industries) + { + ind.WorkersPresent = OnSite(ind.JobsWorkers, ib.OnSiteWorkerShare); + ind.StaffPresent = OnSite(ind.JobsStaff, ib.OnSiteStaffShare); + } + foreach (var c in w.Commutes) + { + // a piedi si arriva sempre; su rotaia contano i passeggeri consegnati (F4) + if (c.Walking) c.ArrivedToday = c.Headcount; + double ratio = c.Headcount > 0 ? Math.Min(1.0, (double)c.ArrivedToday / c.Headcount) : 0; + c.Coverage = Ema.Step(c.Coverage, ratio, eb.CoverageEmaDays); + if (c.Workplace.Kind == WorkplaceKind.Industry) + { + var ind = w.Industries[c.Workplace.Index]; + if (c.Category == PaxClass.Staff) ind.StaffPresent += c.ArrivedToday; + else ind.WorkersPresent += c.ArrivedToday; + } + if (!c.Walking) c.ArrivedToday = 0; + } + foreach (var ind in w.Industries) + { + ind.WorkersPresent = Math.Min(ind.WorkersPresent, ind.JobsWorkers); + ind.StaffPresent = Math.Min(ind.StaffPresent, ind.JobsStaff); + } + } +} diff --git a/src/ViaFerrea.Core/Simulation/Systems/FinanceSystem.cs b/src/ViaFerrea.Core/Simulation/Systems/FinanceSystem.cs new file mode 100644 index 0000000..dba0f16 --- /dev/null +++ b/src/ViaFerrea.Core/Simulation/Systems/FinanceSystem.cs @@ -0,0 +1,113 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Data; +using ViaFerrea.Core.Economy; + +namespace ViaFerrea.Core.Simulation.Systems; + +/// +/// Finanza delle compagnie: giorni di cassa negativa e bancarotta, rate mensili dei prestiti, +/// rating di credito, chiusura dei conti mensili e annuali (guida 6.3). +/// +public sealed class FinanceSystem : ISimSystem +{ + public string Name => "Finance"; + + public void Step(WorldContext ctx) + { + if (!ctx.IsNewDay) return; + var w = ctx.World; + foreach (var c in w.Companies) + { + if (c.Bankrupt) continue; + c.NegativeCashDays = c.Cash.IsNegative ? c.NegativeCashDays + 1 : 0; + if (c.NegativeCashDays >= w.Difficulty.BankruptcyDays) + { + c.Bankrupt = true; + ctx.World.Events.Add(new GameEvent(ctx.Day, EventKind.Finance, EventSeverity.Critical, + $"{c.Name}: dichiarata la bancarotta dopo {c.NegativeCashDays} giorni di cassa negativa", EntityKind.Company, c.Id.Value, c.Id)); + } + } + if (ctx.IsNewMonth && ctx.Day > 0) + { + foreach (var c in w.Companies) + { + if (!c.Bankrupt) PayLoans(w, c); + c.Rating = ComputeRating(w, c); + Array.Clear(c.MonthEntries); + } + } + if (ctx.IsNewYear && ctx.Day > 0) + { + foreach (var c in w.Companies) + { + Array.Copy(c.YearEntries, c.LastYearEntries, c.YearEntries.Length); + Array.Clear(c.YearEntries); + } + } + } + + /// Rata mensile costante (alla francese) per il residuo e i mesi restanti. + public static Money MonthlyPayment(Money remaining, double annualRate, int monthsLeft) + { + if (monthsLeft <= 0) return remaining; + double r = annualRate / 12; + if (r <= 0) return Money.FromCentsRounded((double)remaining.Cents / monthsLeft); + double factor = r / (1 - DMath.Pow(1 + r, -monthsLeft)); + return Money.FromCentsRounded(remaining.Cents * factor); + } + + private static void PayLoans(World w, Company c) + { + for (int i = c.Loans.Count - 1; i >= 0; i--) + { + var loan = c.Loans[i]; + var interest = Money.FromCentsRounded(loan.Remaining.Cents * loan.AnnualRate / 12); + var payment = MonthlyPayment(loan.Remaining, loan.AnnualRate, loan.MonthsLeft); + var principal = Money.Min(loan.Remaining, payment - interest); + if (principal.IsNegative) principal = Money.Zero; + w.Money.Transfer(Account.Of(c.Id), Account.External, interest, LedgerEntry.Interest); + w.Money.Transfer(Account.Of(c.Id), Account.External, principal, LedgerEntry.LoanRepaid); + loan.Remaining -= principal; + loan.MonthsLeft--; + if (loan.Remaining.Cents <= 0 || loan.MonthsLeft <= 0) + { + if (loan.Remaining.IsPositive) + w.Money.Transfer(Account.Of(c.Id), Account.External, loan.Remaining, LedgerEntry.LoanRepaid); + c.Loans.RemoveAt(i); + } + } + } + + /// + /// Rating da margine operativo e leva: punteggio = pesoMargine·clamp(0,5 + margine) + + /// pesoLeva·clamp(1 − debito/attivi), confrontato con le soglie di balance.json. + /// + public static CreditRating ComputeRating(World w, Company c) + { + var fb = w.Data.Balance.Finance; + long[] entries = w.Clock.Day % w.Calendar.DaysPerYear < 90 ? c.LastYearEntries : c.YearEntries; + long revenue = Company.Revenue(entries); + long profit = Company.OperatingProfit(entries); + double margin = revenue > 0 ? (double)profit / revenue : 0; + double assets = Math.Max(1, c.Cash.Cents + c.AssetBookValue.Cents); + double leverage = c.Debt.Cents / assets; + double score = fb.ProfitMarginWeight * Math.Clamp(0.5 + margin, 0, 1) + fb.LeverageWeight * Math.Clamp(1 - leverage, 0, 1); + if (c.Bankrupt) return CreditRating.D; + for (int i = 0; i < fb.RatingByScore.Length; i++) + { + if (score >= fb.RatingByScore[i]) return (CreditRating)i; + } + return CreditRating.D; + } + + /// Fido massimo della compagnia secondo il livello raggiunto. + public static Money MaxLoan(World w, Company c) + { + var tier = w.Data.Tiers.Tiers[Math.Clamp(c.Tier, 1, w.Data.Tiers.Tiers.Count) - 1]; + return c.BaseCredit * tier.Unlocks.MaxLoanFactor; + } + + /// Tasso annuo per un nuovo prestito: base della difficoltà + spread del rating. + public static double LoanRate(World w, Company c) => + w.Difficulty.BaseInterestRate + w.Data.Balance.Finance.RatingSpreads[c.Rating.ToString()]; +} diff --git a/src/ViaFerrea.Core/Simulation/Systems/HashSystem.cs b/src/ViaFerrea.Core/Simulation/Systems/HashSystem.cs new file mode 100644 index 0000000..878d4c2 --- /dev/null +++ b/src/ViaFerrea.Core/Simulation/Systems/HashSystem.cs @@ -0,0 +1,17 @@ +using ViaFerrea.Core.Persistence; + +namespace ViaFerrea.Core.Simulation.Systems; + +/// Ultimo sistema: una volta al giorno calcola l'hash dello stato (resoconto giornaliero e test di determinismo). +public sealed class HashSystem : ISimSystem +{ + public string Name => "Hash"; + + public void Step(WorldContext ctx) + { + if (!ctx.IsNewDay) return; + var w = ctx.World; + w.LastStateHash = StateHasher.Compute(w); + w.LastHashDay = ctx.Day; + } +} diff --git a/src/ViaFerrea.Core/Simulation/Systems/IndustryMath.cs b/src/ViaFerrea.Core/Simulation/Systems/IndustryMath.cs new file mode 100644 index 0000000..52fa034 --- /dev/null +++ b/src/ViaFerrea.Core/Simulation/Systems/IndustryMath.cs @@ -0,0 +1,39 @@ +using ViaFerrea.Core.Data; +using ViaFerrea.Core.Economy; + +namespace ViaFerrea.Core.Simulation.Systems; + +/// Formule dell'industria condivise da più sistemi (guida 6.3 e 11). +public static class IndustryMath +{ + /// pf = clamp(1 + 0,5·margine, 0,6, 1,2). + public static double ProfitFactor(Industry ind, IndustryBalance b) => + Math.Clamp(1 + b.ProfitFactorSlope * ind.Margin, b.ProfitFactorMin, b.ProfitFactorMax); + + /// mc: 1 sopra 70, lineare fino a 0,5 a 20, 0,3 sotto 20. + public static double ConditionMultiplier(double condition, IndustryMaintenanceBalance m) + { + if (condition >= m.EfficiencyFullAbove) return 1.0; + if (condition < 20) return m.EfficiencyBelow20; + double t = (condition - 20) / (m.EfficiencyFullAbove - 20); + return m.EfficiencyAt20 + (1.0 - m.EfficiencyAt20) * t; + } + + /// Capienza del magazzino di un output (unità) al livello corrente. + public static int OutputCapacity(Industry ind, int outputIndex, int daysPerMonth) + { + if (ind.Level <= 0) return 0; + var outputs = ind.Def.Recipe.Outputs; + double perDay = ind.CyclesPerDayAtFullCapacity(daysPerMonth) * outputs[outputIndex].PerCycle; + return (int)Math.Ceiling(perDay * ind.Def.StorageDays); + } + + /// Capienza del magazzino di un input (unità) al livello corrente. + public static int InputCapacity(Industry ind, int inputIndex, int daysPerMonth) + { + if (ind.Level <= 0 || ind.Closed) return 0; + var inputs = ind.Def.Recipe.Inputs; + double perDay = ind.CyclesPerDayAtFullCapacity(daysPerMonth) * inputs[inputIndex].PerCycle; + return (int)Math.Ceiling(perDay * ind.Def.StorageDays); + } +} diff --git a/src/ViaFerrea.Core/Simulation/Systems/IndustrySystem.cs b/src/ViaFerrea.Core/Simulation/Systems/IndustrySystem.cs new file mode 100644 index 0000000..d065264 --- /dev/null +++ b/src/ViaFerrea.Core/Simulation/Systems/IndustrySystem.cs @@ -0,0 +1,225 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Data; +using ViaFerrea.Core.Economy; + +namespace ViaFerrea.Core.Simulation.Systems; + +/// +/// Produzione giornaliera delle industrie (guida 6.3), esaurimento dei giacimenti, salari, +/// crescita trimestrale delle industrie servite, chiusure e nascita di nuove industrie. +/// +public sealed class IndustrySystem : ISimSystem +{ + public string Name => "Industries"; + + public void Step(WorldContext ctx) + { + if (!ctx.IsNewDay) return; + var w = ctx.World; + foreach (var ind in w.Industries) + { + if (!ind.Closed) Produce(ctx, ind); + } + if (ctx.IsNewQuarter && ctx.Day > 0) Quarter(ctx); + if (ctx.IsNewYear) w.SpawnedThisYear = 0; + SpawnForUnmetDemand(ctx); + } + + private static void Produce(WorldContext ctx, Industry ind) + { + var w = ctx.World; + var data = w.Data; + var ib = data.Balance.Industry; + int dpm = w.Calendar.DaysPerMonth; + var recipe = ind.Def.Recipe; + + // coperture di lavoratori e personale (EMA su 30 giorni) + double covW = ind.JobsWorkers > 0 ? ind.WorkersPresent / ind.JobsWorkers : 1.0; + double covS = ind.JobsStaff > 0 ? ind.StaffPresent / ind.JobsStaff : 1.0; + ind.CovWorkers = Ema.Step(ind.CovWorkers, covW, ib.CoverageWindowDays); + ind.CovStaff = Ema.Step(ind.CovStaff, covS, ib.CoverageWindowDays); + + double pf = IndustryMath.ProfitFactor(ind, ib); + double mc = IndustryMath.ConditionMultiplier(ind.Condition, data.Balance.IndustryMaintenance); + double eLabor = Math.Min(ind.CovWorkers, ind.CovStaff) * pf * mc; + + // giacimento: sotto la soglia la capacità cala linearmente, a zero l'industria chiude + double depletion = 1.0; + ResourceSite? site = ind.Site.IsValid ? w.Sites[ind.Site.Value] : null; + if (ind.Def.Depletable && site is not null) + { + double frac = site.ReserveFraction; + if (frac <= 0) + { + Close(ctx, ind, $"{ind.Name}: giacimento esaurito, l'attività chiude"); + return; + } + if (frac < ib.DepletionStartFraction) depletion = frac / ib.DepletionStartFraction; + } + + double cycles = ind.CyclesPerDayAtFullCapacity(dpm) * eLabor * depletion; + for (int o = 0; o < recipe.Outputs.Count; o++) + w.Market.CapacityToday[recipe.Outputs[o].GoodIndex] += ind.CyclesPerDayAtFullCapacity(dpm) * depletion * recipe.Outputs[o].PerCycle; + + // copertura degli input di oggi: limita la produzione alle scorte disponibili + double covInToday = 1.0; + for (int i = 0; i < recipe.Inputs.Count; i++) + { + double need = cycles * recipe.Inputs[i].PerCycle; + if (need > 0) covInToday = Math.Min(covInToday, ind.InputStock[i] / need); + } + covInToday = Math.Min(1.0, covInToday); + ind.CovInput = Ema.Step(ind.CovInput, recipe.Inputs.Count == 0 ? 1.0 : covInToday, ib.CoverageWindowDays); + + double total = cycles * covInToday + ind.CycleAccumulator; + long whole = (long)Math.Floor(total); + for (int i = 0; i < recipe.Inputs.Count; i++) + whole = Math.Min(whole, ind.InputStock[i] / recipe.Inputs[i].PerCycle); + ind.CycleAccumulator = Math.Clamp(total - whole, 0, 1); + + for (int i = 0; i < recipe.Inputs.Count; i++) + { + int used = (int)(whole * recipe.Inputs[i].PerCycle); + ind.InputStock[i] -= used; + w.Goods.Consumed[recipe.Inputs[i].GoodIndex] += used; + } + for (int o = 0; o < recipe.Outputs.Count; o++) + { + int good = recipe.Outputs[o].GoodIndex; + int made = (int)(whole * recipe.Outputs[o].PerCycle); + ind.ProducedToday[o] = made; + ind.OutputStock[o] += made; + w.Goods.Produced[good] += made; + w.Market.SupplyToday[good] += made; + + // oltre la capienza del magazzino (storageDays) la merce si perde + int cap = IndustryMath.OutputCapacity(ind, o, dpm); + if (ind.OutputStock[o] > cap) + { + int lost = ind.OutputStock[o] - cap; + ind.OutputStock[o] = cap; + w.Goods.Decayed[good] += lost; + } + } + if (site is not null && ind.Def.Depletable) + { + double extracted = whole * recipe.Outputs[0].PerCycle * data.Difficulty.DepletionMultipliers.For(w.Difficulty.Depletion); + site.ReserveTonnes = Math.Max(0, site.ReserveTonnes - extracted); + } + ind.Efficiency = eLabor * covInToday * depletion; + + // salari giornalieri ai presenti + double wages = (ind.WorkersPresent * ib.WagePerWorkerPerMonth + ind.StaffPresent * ib.WagePerStaffPerMonth) / dpm; + var wageMoney = Money.FromCentsRounded(wages); + w.Money.Transfer(Account.Of(ind.Id), Account.External, wageMoney, LedgerEntry.Wages); + + ind.RevenueEma = Ema.Step(ind.RevenueEma, ind.SalesToday, ib.MarginWindowDays); + ind.CostEma = Ema.Step(ind.CostEma, wageMoney.Cents + ind.PurchasesToday, ib.MarginWindowDays); + ind.SalesToday = 0; + ind.PurchasesToday = 0; + + // statistiche del trimestre + ind.QuarterProduced += whole * recipe.Outputs[0].PerCycle; + ind.QuarterShipped += ind.ShippedToday; + ind.ShippedToday = 0; + ind.QuarterCoverageSum += Math.Min(ind.CovInput, Math.Min(ind.CovWorkers, ind.CovStaff)); + ind.QuarterDays++; + } + + private static void Quarter(WorldContext ctx) + { + var w = ctx.World; + var g = w.Data.Balance.Growth; + foreach (var ind in w.Industries) + { + if (ind.Closed) continue; + double shipped = ind.QuarterProduced > 0 ? Math.Min(1.0, (double)ind.QuarterShipped / ind.QuarterProduced) : 0; + double coverage = ind.QuarterDays > 0 ? ind.QuarterCoverageSum / ind.QuarterDays : 0; + double profit = Math.Clamp((ind.Margin + 1) / 2, 0, 1); + double score = g.WeightShipped * shipped + g.WeightCoverage * coverage + g.WeightProfit * profit; + ind.LastScore = score; + ind.QuarterProduced = 0; + ind.QuarterShipped = 0; + ind.QuarterCoverageSum = 0; + ind.QuarterDays = 0; + + // solo le industrie servite da un vettore crescono o regrediscono (ADR 0004) + if (!ind.Served) continue; + + if (ind.Level == 0) + { + ind.QuartersAtZero++; + if (ind.QuartersAtZero >= g.CloseQuartersAtZero) + { + Close(ctx, ind, $"{ind.Name} chiude dopo un anno di inattività"); + continue; + } + } + else + { + ind.QuartersAtZero = 0; + } + + if (score > g.UpgradeThreshold) + { + ind.QuartersAboveUpgrade++; + if (ind.QuartersAboveUpgrade >= g.UpgradeQuarters && ind.Level < g.MaxLevel) + { + ind.Level++; + ind.QuartersAboveUpgrade = 0; + ctx.Emit(EventKind.Industry, EventSeverity.Opportunity, $"{ind.Name} si espande al livello {ind.Level}", EntityKind.Industry, ind.Id.Value); + } + } + else + { + ind.QuartersAboveUpgrade = 0; + if (score < g.DowngradeThreshold && ind.Level > 0) + { + ind.Level--; + ctx.Emit(EventKind.Industry, EventSeverity.Warning, $"{ind.Name} riduce l'attività (livello {ind.Level})", EntityKind.Industry, ind.Id.Value); + } + } + } + } + + /// Chiude un'industria: le scorte si perdono, l'impronta torna libera. + public static void Close(WorldContext ctx, Industry ind, string reason) + { + var w = ctx.World; + ind.Closed = true; + ind.Level = 0; + var recipe = ind.Def.Recipe; + for (int i = 0; i < recipe.Inputs.Count; i++) + { + w.Goods.Decayed[recipe.Inputs[i].GoodIndex] += ind.InputStock[i]; + ind.InputStock[i] = 0; + } + for (int o = 0; o < recipe.Outputs.Count; o++) + { + w.Goods.Decayed[recipe.Outputs[o].GoodIndex] += ind.OutputStock[o]; + ind.OutputStock[o] = 0; + } + IndustryPlacer.ClearFootprint(w, ind); + w.Commutes.RemoveAll(c => c.Workplace.Kind == WorkplaceKind.Industry && c.Workplace.Index == ind.Id.Value); + ctx.Emit(EventKind.Industry, EventSeverity.Warning, reason, EntityKind.Industry, ind.Id.Value); + } + + private static void SpawnForUnmetDemand(WorldContext ctx) + { + var w = ctx.World; + var g = w.Data.Balance.Growth; + if (w.SpawnedThisYear >= g.SpawnMaxPerYear) return; + for (int good = 0; good < w.Data.GoodCount; good++) + { + if (w.Market.UnmetDays[good] < g.SpawnUnmetDays) continue; + w.Market.UnmetDays[good] = 0; + var ind = IndustryPlacer.TrySpawnProducer(w, good, ctx.Year); + if (ind is null) continue; + w.SpawnedThisYear++; + ctx.Emit(EventKind.Industry, EventSeverity.Opportunity, + $"Apre {ind.Name}: la domanda di {w.Data.Goods[good].NameIt.ToLowerInvariant()} è rimasta insoddisfatta per un anno", + EntityKind.Industry, ind.Id.Value); + if (w.SpawnedThisYear >= g.SpawnMaxPerYear) return; + } + } +} diff --git a/src/ViaFerrea.Core/Simulation/Systems/LocalTransportSystem.cs b/src/ViaFerrea.Core/Simulation/Systems/LocalTransportSystem.cs new file mode 100644 index 0000000..7ae4a76 --- /dev/null +++ b/src/ViaFerrea.Core/Simulation/Systems/LocalTransportSystem.cs @@ -0,0 +1,180 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Data; +using ViaFerrea.Core.Economy; + +namespace ViaFerrea.Core.Simulation.Systems; + +/// +/// Trasporto locale su strada (carrettieri, ADR 0004): piccole quantità tra produttori, consumatori +/// e hub vicinissimi, senza vettore. Tiene vivo il territorio senza rendere superflua la ferrovia. +/// Vendite e acquisti avvengono ai prezzi locali; le merci passano solo da un magazzino all'altro. +/// +public sealed class LocalTransportSystem : ISimSystem +{ + public string Name => "LocalTransport"; + + private int _cacheIndustries = -1; + private int _cacheTowns = -1; + private List<(int Industry, double Km)>[] _nearIndustries = []; + private List<(int Town, double Km)>[] _nearTowns = []; + private List<(int Hub, double Km)>[] _nearHubs = []; + + public void Step(WorldContext ctx) + { + if (!ctx.IsNewDay) return; + var w = ctx.World; + var lt = w.Data.Balance.LocalTransport; + if (!lt.Enabled) return; + RebuildCache(w, lt); + if (ctx.IsNewMonth) + { + foreach (var hub in w.Hubs) + { + hub.UsedThisMonth = 0; + Array.Clear(hub.ImportedThisMonth); + Array.Clear(hub.ExportedThisMonth); + } + } + + var lp = w.Data.Balance.LocalPrice; + int dpm = w.Calendar.DaysPerMonth; + foreach (var producer in w.Industries) + { + if (producer.Closed) continue; + var outputs = producer.Def.Recipe.Outputs; + for (int o = 0; o < outputs.Count; o++) + { + int good = outputs[o].GoodIndex; + int available = Math.Min(lt.MaxUnitsPerDay, (int)Math.Ceiling(producer.OutputStock[o] * lt.DailyShare)); + if (available <= 0) continue; + double sellPrice = Market.LocalPrice(w.Market.GlobalPrice[good], 0, producer.OutputStock[o], lp); + + foreach (var (ci, _) in _nearIndustries[producer.Id.Value]) + { + if (available <= 0) break; + var consumer = w.Industries[ci]; + int i = consumer.InputIndexOf(good); + if (i < 0 || consumer.Closed) continue; + int free = IndustryMath.InputCapacity(consumer, i, dpm) - consumer.InputStock[i]; + int units = Math.Min(available, free); + if (units <= 0) continue; + double buyPrice = Market.LocalPrice(w.Market.GlobalPrice[good], consumer.InputDemandToday[i] * consumer.Def.StorageDays, consumer.InputStock[i], lp); + producer.OutputStock[o] -= units; + consumer.InputStock[i] += units; + available -= units; + Sell(w, producer, o, units, sellPrice); + Buy(w, consumer, units, buyPrice); + } + foreach (var (ti, _) in _nearTowns[producer.Id.Value]) + { + if (available <= 0) break; + var town = w.Towns[ti]; + double demand = town.DemandToday[good]; + if (demand <= 0) continue; + int free = (int)Math.Ceiling(demand * w.Data.Balance.Town.StockDays) - town.Stock[good]; + int units = Math.Min(available, free); + if (units <= 0) continue; + producer.OutputStock[o] -= units; + town.Stock[good] += units; + available -= units; + Sell(w, producer, o, units, sellPrice); + } + foreach (var (hi, _) in _nearHubs[producer.Id.Value]) + { + if (available <= 0) break; + var hub = w.Hubs[hi]; + int units = Math.Min(available, hub.RemainingCapacity); + if (units <= 0) continue; + producer.OutputStock[o] -= units; + hub.UsedThisMonth += units; + hub.ExportedThisMonth[good] += units; + w.Goods.Exported[good] += units; + available -= units; + Sell(w, producer, o, units, hub.BuyPrice(w.Market.GlobalPrice[good])); + } + } + } + + // importazioni dagli hub verso i consumatori vicini + foreach (var hub in w.Hubs) + { + foreach (var consumer in w.Industries) + { + if (consumer.Closed || hub.RemainingCapacity <= 0) continue; + if (Vec2.Distance(hub.Position, consumer.Position) > lt.RadiusKm * 1000) continue; + var inputs = consumer.Def.Recipe.Inputs; + for (int i = 0; i < inputs.Count; i++) + { + int good = inputs[i].GoodIndex; + int free = IndustryMath.InputCapacity(consumer, i, dpm) - consumer.InputStock[i]; + int units = Math.Min(Math.Min(lt.MaxUnitsPerDay, free), hub.RemainingCapacity); + if (units <= 0) continue; + consumer.InputStock[i] += units; + hub.UsedThisMonth += units; + hub.ImportedThisMonth[good] += units; + w.Goods.Imported[good] += units; + Buy(w, consumer, units, hub.SellPrice(w.Market.GlobalPrice[good])); + } + } + } + } + + private static void Sell(World w, Industry producer, int outputIndex, int units, double unitPrice) + { + var amount = Money.FromCentsRounded(units * unitPrice); + w.Money.Transfer(Account.External, Account.Of(producer.Id), amount, LedgerEntry.Other); + producer.SalesToday += amount.Cents; + if (outputIndex == 0) producer.ShippedToday += units; + } + + private static void Buy(World w, Industry consumer, int units, double unitPrice) + { + var amount = Money.FromCentsRounded(units * unitPrice); + w.Money.Transfer(Account.Of(consumer.Id), Account.External, amount, LedgerEntry.Other); + consumer.PurchasesToday += amount.Cents; + } + + // vicini entro il raggio, ordinati per distanza e id; ricalcolati quando cambiano le entità + private void RebuildCache(World w, LocalTransportBalance lt) + { + if (_cacheIndustries == w.Industries.Count && _cacheTowns == w.Towns.Count) return; + _cacheIndustries = w.Industries.Count; + _cacheTowns = w.Towns.Count; + int n = w.Industries.Count; + _nearIndustries = new List<(int, double)>[n]; + _nearTowns = new List<(int, double)>[n]; + _nearHubs = new List<(int, double)>[n]; + double radiusM = lt.RadiusKm * 1000; + for (int p = 0; p < n; p++) + { + var producer = w.Industries[p]; + var li = new List<(int, double)>(); + for (int c = 0; c < n; c++) + { + if (c == p) continue; + double d = Vec2.Distance(producer.Position, w.Industries[c].Position); + if (d <= radiusM) li.Add((c, d / 1000)); + } + li.Sort((a, b) => a.Item2 != b.Item2 ? a.Item2.CompareTo(b.Item2) : a.Item1.CompareTo(b.Item1)); + _nearIndustries[p] = li; + + var lt2 = new List<(int, double)>(); + foreach (var town in w.Towns) + { + double km = w.TownEdgeDistanceKm(town, producer.Position); + if (km <= lt.RadiusKm) lt2.Add((town.Id.Value, km)); + } + lt2.Sort((a, b) => a.Item2 != b.Item2 ? a.Item2.CompareTo(b.Item2) : a.Item1.CompareTo(b.Item1)); + _nearTowns[p] = lt2; + + var lh = new List<(int, double)>(); + foreach (var hub in w.Hubs) + { + double d = Vec2.Distance(producer.Position, hub.Position); + if (d <= radiusM) lh.Add((hub.Id.Value, d / 1000)); + } + lh.Sort((a, b) => a.Item2 != b.Item2 ? a.Item2.CompareTo(b.Item2) : a.Item1.CompareTo(b.Item1)); + _nearHubs[p] = lh; + } + } +} diff --git a/src/ViaFerrea.Core/Simulation/Systems/MarketSystem.cs b/src/ViaFerrea.Core/Simulation/Systems/MarketSystem.cs new file mode 100644 index 0000000..e9aef3b --- /dev/null +++ b/src/ViaFerrea.Core/Simulation/Systems/MarketSystem.cs @@ -0,0 +1,78 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Economy; + +namespace ViaFerrea.Core.Simulation.Systems; + +/// +/// Prezzi globali giornalieri (guida 6.3, ADR 0004): +/// Pg' = clamp(Pg·(1 + k·(D/S − 1)), 0,3·Pb, 3·Pb), Pg ← α·Pg' + (1 − α)·Pg, +/// dove D e S sono domanda e offerta degli ultimi 30 giorni più la componente mondiale: +/// un volume V scambiato con il resto del mondo al prezzo mondiale Pw = Pb·(1 + W(t)). +/// +public sealed class MarketSystem : ISimSystem +{ + public string Name => "Market"; + + public void Step(WorldContext ctx) + { + if (!ctx.IsNewDay) return; + var w = ctx.World; + var data = w.Data; + var m = data.Balance.Market; + var market = w.Market; + var rng = w.Stream("market"); + double volatility = w.Difficulty.MarketVolatilityMultiplier; + double years = w.Clock.YearsElapsed; + double decay = DMath.Exp(-1.0 / m.World.ShockDecayDays); + double shockChance = m.World.ShockChancePerYear / w.Calendar.DaysPerYear; + var growth = data.Balance.Growth; + + for (int g = 0; g < data.GoodCount; g++) + { + var def = data.Goods[g]; + market.Demand[g].Add(market.DemandToday[g]); + market.Supply[g].Add(market.SupplyToday[g]); + market.DemandToday[g] = 0; + market.SupplyToday[g] = 0; + + // shock mondiali per bene + market.Shock[g] *= decay; + if (rng.Chance(shockChance)) + { + double magnitude = rng.NextDouble(m.World.ShockMin, m.World.ShockMax) * volatility; + double sign = rng.Chance(0.5) ? 1 : -1; + market.Shock[g] += sign * magnitude; + int pct = (int)Math.Round(magnitude * 100); + ctx.Emit(EventKind.Market, sign > 0 ? EventSeverity.Opportunity : EventSeverity.Warning, + $"{def.NameIt}: prezzo mondiale {(sign > 0 ? "in rialzo" : "in calo")} del {pct}%"); + } + + double pb = def.BasePrice; + double pg = market.GlobalPrice[g]; + if (def.Era > ctx.Year) + { + market.PriceHistory[g].Add(pg); + market.CapacityToday[g] = 0; + continue; + } + double pw = pb * Math.Max(0.05, 1 + Market.WorldFactor(m, volatility, years, market.Shock[g])); + double d = market.Demand[g].Sum; + double s = market.Supply[g].Sum; + double v = Math.Max(m.World.BaselinePerDay * market.Demand[g].Count, m.World.VolumeShare * (d + s) / 2); + double dTot = d + v * DMath.Pow(pw / pg, m.World.Elasticity); + double sTot = s + v * DMath.Pow(pg / pw, m.World.Elasticity); + double ratio = DMath.Clamp(dTot / Math.Max(1e-9, sTot), m.RatioMin, m.RatioMax); + double target = DMath.Clamp(pg * (1 + m.K * (ratio - 1)), m.MinPriceFactor * pb, m.MaxPriceFactor * pb); + pg = m.Alpha * target + (1 - m.Alpha) * pg; + market.GlobalPrice[g] = pg; + market.PriceHistory[g].Add(pg); + + // domanda insoddisfatta per mancanza di capacità installata (non di trasporto): + // è il segnale per la nascita di nuove industrie + double avgDemand = market.Demand[g].Average; + if (avgDemand > growth.SpawnUnmetRatio * market.CapacityToday[g] + m.World.BaselinePerDay) market.UnmetDays[g]++; + else market.UnmetDays[g] = 0; + market.CapacityToday[g] = 0; + } + } +} diff --git a/src/ViaFerrea.Core/Simulation/Systems/TownSystem.cs b/src/ViaFerrea.Core/Simulation/Systems/TownSystem.cs new file mode 100644 index 0000000..f4f6ca7 --- /dev/null +++ b/src/ViaFerrea.Core/Simulation/Systems/TownSystem.cs @@ -0,0 +1,157 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Data; +using ViaFerrea.Core.Economy; +using ViaFerrea.Core.Map; + +namespace ViaFerrea.Core.Simulation.Systems; + +/// +/// Città: consumo giornaliero e soddisfazione per categoria, crescita mensile, espansione +/// dell'abitato e migrazione annuale verso le città meglio servite (guida 6.3). +/// +public sealed class TownSystem : ISimSystem +{ + public string Name => "Towns"; + + private readonly double[] _catDemand = new double[Town.CategoryCount]; + private readonly double[] _catConsumed = new double[Town.CategoryCount]; + + public void Step(WorldContext ctx) + { + if (!ctx.IsNewDay) return; + var w = ctx.World; + foreach (var town in w.Towns) Consume(w, town); + if (ctx.IsNewMonth && ctx.Day > 0) + { + foreach (var town in w.Towns) Grow(ctx, town); + } + if (ctx.IsNewYear && ctx.Day > 0) + { + Migrate(ctx); + foreach (var town in w.Towns) ExpandFootprint(w, town); + } + } + + private void Consume(World w, Town town) + { + var data = w.Data; + var tb = data.Balance.Town; + Array.Clear(_catDemand); + Array.Clear(_catConsumed); + for (int g = 0; g < data.GoodCount; g++) + { + double demand = town.DemandToday[g]; + if (demand <= 0) + { + town.DemandAccumulator[g] = 0; + continue; + } + int cat = (int)data.Goods[g].Town!.Category; + town.DemandAccumulator[g] += demand; + int want = (int)Math.Floor(town.DemandAccumulator[g]); + int used = Math.Min(want, town.Stock[g]); + town.Stock[g] -= used; + w.Goods.Consumed[g] += used; + town.DemandAccumulator[g] -= want; // la domanda non servita non si accumula + _catDemand[cat] += demand; + _catConsumed[cat] += used; + } + for (int c = 0; c < Town.CategoryCount; c++) + { + town.CategoryActive[c] = _catDemand[c] > 0; + if (_catDemand[c] <= 0) continue; + double ratio = Math.Min(1.0, _catConsumed[c] / _catDemand[c]); + town.Satisfaction[c] = Ema.Step(town.Satisfaction[c], ratio, tb.SatisfactionEmaDays); + } + town.WorkDissatisfaction *= 1.0 - 1.0 / 90.0; + } + + private static void Grow(WorldContext ctx, Town town) + { + var tb = ctx.Data.Balance.Town; + int services = 0; + for (int c = 0; c < Town.CategoryCount; c++) + { + if (town.CategoryActive[c] && town.Satisfaction[c] >= tb.ServicesSatisfactionThreshold) services++; + } + town.Services = services; + double sat = town.OverallSatisfaction; + double employment = town.Population > 0 ? (double)(town.EmployedWorkers + town.EmployedStaff) / town.Population : 0; + double g = tb.BaseGrowth + tb.SatisfactionWeight * (sat - tb.SatisfactionPivot) + tb.EmploymentWeight * (employment - tb.EmploymentPivot); + g = Math.Clamp(g, -tb.MaxMonthlyGrowth, tb.MaxMonthlyGrowth); + town.LastGrowth = g; + int before = town.Population; + town.Population = Math.Clamp((int)Math.Round(town.Population * (1 + g)), 0, tb.MaxPopulation); + if (before < 10_000 && town.Population >= 10_000) + ctx.Emit(EventKind.Town, EventSeverity.Info, $"{town.Name} supera i 10.000 abitanti", EntityKind.Town, town.Id.Value); + } + + private static void Migrate(WorldContext ctx) + { + var w = ctx.World; + var mb = w.Data.Balance.Migration; + var leaving = new List<(Town Town, int People)>(); + foreach (var town in w.Towns) + { + if (town.OverallSatisfaction >= mb.SatisfactionThreshold) continue; + int people = (int)(town.Population * mb.Share); + if (people > 0) leaving.Add((town, people)); + } + foreach (var (from, people) in leaving) + { + var targets = w.Towns + .Where(t => t != from && t.OverallSatisfaction > from.OverallSatisfaction + && Vec2.Distance(t.Position, from.Position) <= mb.MaxDistanceKm * 1000) + .ToList(); + from.Population -= people; + if (targets.Count == 0) + { + // nessuna destinazione migliore: una parte emigra fuori regione, il resto resta + int emigrants = (int)(people * mb.EmigrationShareWhenNoTarget); + from.Population += people - emigrants; + if (emigrants >= 100) + ctx.Emit(EventKind.Town, EventSeverity.Warning, $"{emigrants} abitanti di {from.Name} emigrano fuori regione", EntityKind.Town, from.Id.Value); + continue; + } + double totalWeight = targets.Sum(t => t.OverallSatisfaction * t.Population); + int moved = 0; + for (int i = 0; i < targets.Count; i++) + { + int share = i == targets.Count - 1 + ? people - moved + : (int)Math.Floor(people * targets[i].OverallSatisfaction * targets[i].Population / Math.Max(1e-9, totalWeight)); + targets[i].Population += share; + moved += share; + } + if (people >= 100) + ctx.Emit(EventKind.Town, EventSeverity.Warning, $"{people} abitanti lasciano {from.Name} per città meglio servite", EntityKind.Town, from.Id.Value); + } + } + + /// L'abitato si allarga con la popolazione sulle celle libere vicine. + private static void ExpandFootprint(World w, Town town) + { + var tp = w.Data.Balance.Map.Towns; + double radius = tp.RadiusBaseCells + tp.RadiusPerSqrtPop * Math.Sqrt(town.Population); + if (radius <= town.RadiusCells + 0.25) return; + town.RadiusCells = radius; + int r = (int)Math.Ceiling(radius); + bool changed = false; + for (int y = town.CellY - r; y <= town.CellY + r; y++) + { + for (int x = town.CellX - r; x <= town.CellX + r; x++) + { + if (!w.Terrain.InBounds(x, y)) continue; + double dx = x - town.CellX, dy = y - town.CellY; + if (dx * dx + dy * dy > radius * radius) continue; + var type = w.Terrain.TypeAt(x, y); + if (type is CellType.Plain or CellType.Field or CellType.Forest or CellType.Hill) + { + w.Terrain.SetType(x, y, CellType.Town); + changed = true; + } + } + } + if (changed) w.TerrainHash = 0; + } +} diff --git a/src/ViaFerrea.Core/Simulation/World.cs b/src/ViaFerrea.Core/Simulation/World.cs new file mode 100644 index 0000000..c547f81 --- /dev/null +++ b/src/ViaFerrea.Core/Simulation/World.cs @@ -0,0 +1,183 @@ +using ViaFerrea.Core.Commands; +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Data; +using ViaFerrea.Core.Economy; +using ViaFerrea.Core.Map; +using ViaFerrea.Core.Time; + +namespace ViaFerrea.Core.Simulation; + +/// +/// Il mondo di gioco: tutto lo stato della simulazione e il ciclo dei sistemi. +/// Single-thread: chi lo usa da più thread (il server) deve serializzare gli accessi. +/// +public sealed class World +{ + private readonly Dictionary _streams = new(StringComparer.Ordinal); + private readonly Queue _commands = new(); + private readonly List _results = []; + + public World(GameData data, WorldSettings settings, Terrain terrain, MapSide seaSide) + { + Data = data; + Settings = settings; + Calendar = new Calendar(data.Balance.Time, settings.StartYear); + Clock = new GameClock(Calendar); + Rng = new Rng(settings.Seed); + Terrain = terrain; + Sampler = new TerrainSampler(terrain); + SeaSide = seaSide; + Market = new Market(data); + Goods = new GoodsCounters(data.GoodCount); + Money = new MoneyLedger(id => Companies[id.Value], id => Industries[id.Value]); + Context = new WorldContext(this); + Pipeline = SystemPipeline.CreateDefault(); + TerrainHash = terrain.ComputeHash(); + } + + public GameData Data { get; } + public WorldSettings Settings { get; } + public DifficultyDef Difficulty => Settings.Difficulty; + public Calendar Calendar { get; } + public GameClock Clock { get; } + + /// Generatore radice: non estrae mai, serve solo a derivare i flussi dei sottosistemi. + public Rng Rng { get; } + + public Terrain Terrain { get; } + public TerrainSampler Sampler { get; } + public MapSide SeaSide { get; } + public ulong TerrainHash { get; internal set; } + + public List Sites { get; } = []; + public List Towns { get; } = []; + public List Industries { get; } = []; + public List Hubs { get; } = []; + public List Companies { get; } = []; + public List Commutes { get; } = []; + + public Market Market { get; } + public MoneyLedger Money { get; } + public GoodsCounters Goods { get; } + public EventLog Events { get; } = new(); + + public WorldContext Context { get; } + public SystemPipeline Pipeline { get; } + + /// Contatori per l'assegnazione di nuovi id (mai riutilizzati). + public IdCounters NextIds { get; } = new(); + + /// Hash di stato dell'ultimo giorno calcolato dal sistema Hash. + public ulong LastStateHash { get; internal set; } + public long LastHashDay { get; internal set; } = -1; + + /// Nuove industrie nate nell'anno corrente (limite annuo). + public int SpawnedThisYear { get; internal set; } + + /// Registro dei comandi applicati (tick, comando), se attivo: serve al replay. + public List<(long Tick, GameCommand Command)>? CommandLog { get; set; } + + public Company Player => Companies.First(c => c.IsPlayer); + + /// Flusso pseudo-casuale nominato di un sottosistema (derivato dalla radice, persistito nei salvataggi). + public Rng Stream(string name) + { + if (!_streams.TryGetValue(name, out var rng)) + { + rng = Rng.Fork(name); + _streams[name] = rng; + } + return rng; + } + + /// Flussi creati finora, in ordine di nome (per salvataggio e hash). + public IEnumerable> Streams => _streams.OrderBy(kv => kv.Key, StringComparer.Ordinal); + + internal void RestoreStream(string name, Rng rng) => _streams[name] = rng; + + /// Accoda un comando: verrà eseguito dal sistema Commands del prossimo tick. + public void Enqueue(GameCommand command) => _commands.Enqueue(command); + + internal bool TryDequeueCommand(out GameCommand command) => _commands.TryDequeue(out command!); + + internal void AddResult(CommandResult result) => _results.Add(result); + + /// Restituisce e azzera gli esiti dei comandi eseguiti. + public List DrainResults() + { + var list = new List(_results); + _results.Clear(); + return list; + } + + /// Esegue un tick: tutti i sistemi in ordine, poi avanza l'orologio. + public void Tick() + { + Pipeline.Run(Context); + Clock.Advance(); + } + + /// Esegue n tick. + public void RunTicks(long n) + { + for (long i = 0; i < n; i++) Tick(); + } + + /// Esegue un numero intero di giorni di calendario. + public void RunDays(int days) => RunTicks((long)days * Calendar.TicksPerDay); + + /// Esegue un numero intero di anni di calendario. + public void RunYears(int years) => RunDays(years * Calendar.DaysPerYear); + + public Town Town(TownId id) => Towns[id.Value]; + public Industry Industry(IndustryId id) => Industries[id.Value]; + public Company Company(CompanyId id) => Companies[id.Value]; + + /// Distanza in km tra un punto e il bordo della città. + public double TownEdgeDistanceKm(Town town, Vec2 p) => + Math.Max(0, (Vec2.Distance(town.Position, p) - town.RadiusCells * Terrain.CellSizeM) / 1000.0); + + /// Giacenza totale di un bene in tutti i depositi tracciati (invariante delle merci). + public long TotalStock(int good) + { + long sum = 0; + foreach (var t in Towns) sum += t.Stock[good]; + foreach (var ind in Industries) + { + int i = ind.InputIndexOf(good); + if (i >= 0) sum += ind.InputStock[i]; + int o = ind.OutputIndexOf(good); + if (o >= 0) sum += ind.OutputStock[o]; + } + return sum; + } + + /// Somma di tutti i saldi (deve essere zero: invariante del denaro). + public long MoneyBalanceSum() + { + long sum = Money.External.Cents; + foreach (var c in Companies) sum += c.Cash.Cents; + foreach (var i in Industries) sum += i.Cash.Cents; + return sum; + } +} + +/// Prossimi id liberi per tipo di entità. +public sealed class IdCounters +{ + public int Contract { get; set; } + public int Loan { get; set; } + public int Industry { get; set; } + public int Station { get; set; } + public int Node { get; set; } + public int Edge { get; set; } + public int Signal { get; set; } + public int Train { get; set; } + public int Vehicle { get; set; } + public int Line { get; set; } + public int Packet { get; set; } + public int Depot { get; set; } + public int Work { get; set; } + public int Bid { get; set; } + public int Agreement { get; set; } +} diff --git a/src/ViaFerrea.Core/Simulation/WorldFactory.cs b/src/ViaFerrea.Core/Simulation/WorldFactory.cs new file mode 100644 index 0000000..a226c0f --- /dev/null +++ b/src/ViaFerrea.Core/Simulation/WorldFactory.cs @@ -0,0 +1,140 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Data; +using ViaFerrea.Core.Economy; +using ViaFerrea.Core.Map; + +namespace ViaFerrea.Core.Simulation; + +/// Creazione di una partita nuova: mappa, entità iniziali, compagnie e contabilità di apertura. +public static class WorldFactory +{ + /// Genera la mappa e costruisce il mondo. + public static World Create(GameData data, NewGameSettings settings) + { + int startYear = settings.StartYear ?? data.Balance.Time.DefaultStartYear; + var map = MapGenerator.Generate(data, new MapSpec(settings.Seed, settings.SizeKm, startYear, settings.RegionId)); + return FromMap(data, map, settings); + } + + /// Costruisce il mondo da una mappa già generata (o da uno scenario costruito a mano). + public static World FromMap(GameData data, GeneratedMap map, NewGameSettings settings) + { + var difficulty = settings.DifficultyOverride ?? data.DifficultyPreset(settings.DifficultyId); + var worldSettings = new WorldSettings + { + Seed = settings.Seed, + SizeKm = map.Spec.SizeKm, + StartYear = map.Spec.StartYear, + RegionId = map.Spec.RegionId, + Difficulty = difficulty, + Endless = settings.Endless, + }; + var w = new World(data, worldSettings, map.Terrain, map.SeaSide); + int goods = data.GoodCount; + + for (int i = 0; i < map.Sites.Count; i++) + { + var s = map.Sites[i]; + w.Sites.Add(new ResourceSite + { + Id = new ResourceSiteId(i), + Kind = s.Kind, + CellX = s.CellX, + CellY = s.CellY, + RadiusCells = s.RadiusCells, + InitialReserveTonnes = s.ReserveTonnes, + ReserveTonnes = s.ReserveTonnes, + }); + } + + var tb = data.Balance.Town; + for (int i = 0; i < map.Towns.Count; i++) + { + var s = map.Towns[i]; + var town = new Town + { + Id = new TownId(i), + Name = s.Name, + CellX = s.CellX, + CellY = s.CellY, + Position = map.Terrain.CellCenter(s.CellX, s.CellY), + RadiusCells = s.RadiusCells, + Population = s.Population, + Stock = new int[goods], + DemandToday = new double[goods], + DemandAccumulator = new double[goods], + }; + for (int c = 0; c < Town.CategoryCount; c++) town.Satisfaction[c] = tb.InitialSatisfaction; + w.Towns.Add(town); + } + + for (int i = 0; i < map.Hubs.Count; i++) + { + var s = map.Hubs[i]; + var hp = data.Balance.Hubs.For(s.Kind); + w.Hubs.Add(new Hub + { + Id = new HubId(i), + Kind = s.Kind, + Name = s.Name, + CellX = s.CellX, + CellY = s.CellY, + FootprintCells = s.FootprintCells, + Position = map.Terrain.CellCenter(s.CellX, s.CellY), + MonthlyCapacity = hp.MonthlyCapacity, + Duty = hp.Duty, + ImportedThisMonth = new int[goods], + ExportedThisMonth = new int[goods], + }); + } + + foreach (var s in map.Industries) + { + var def = data.Industries[s.TypeIndex]; + IndustryPlacer.Create(w, def, s.Name, s.CellX, s.CellY, s.FootprintCells, s.Level, + s.SiteIndex >= 0 ? new ResourceSiteId(s.SiteIndex) : ResourceSiteId.None); + } + + CreateCompanies(w, settings); + w.TerrainHash = w.Terrain.ComputeHash(); + return w; + } + + private static void CreateCompanies(World w, NewGameSettings settings) + { + var data = w.Data; + var d = w.Difficulty; + var rng = w.Stream("companies"); + var player = new Company + { + Id = new CompanyId(0), + Name = settings.PlayerCompanyName, + IsPlayer = true, + Color = "#e0a526", + BaseCredit = new Money(d.InitialCredit), + Rating = data.Balance.Finance.StartingRating, + }; + w.Companies.Add(player); + w.Money.Transfer(Account.External, Account.Of(player.Id), new Money(d.InitialCapital), LedgerEntry.Other); + + var names = data.Ai.CompanyNames.ToList(); + for (int i = 0; i < d.AiCompetitors; i++) + { + string name = names.Count > 0 ? names[rng.NextInt(names.Count)] : $"Compagnia {i + 1}"; + names.Remove(name); + var personality = data.Ai.Personalities[rng.NextInt(data.Ai.Personalities.Count)]; + var ai = new Company + { + Id = new CompanyId(w.Companies.Count), + Name = name, + IsPlayer = false, + AiPersonality = personality.Id, + Color = data.Ai.Colors[i % data.Ai.Colors.Count], + BaseCredit = new Money(d.InitialCredit) * d.AiCapitalMultiplier, + Rating = data.Balance.Finance.StartingRating, + }; + w.Companies.Add(ai); + w.Money.Transfer(Account.External, Account.Of(ai.Id), new Money(d.InitialCapital) * d.AiCapitalMultiplier, LedgerEntry.Other); + } + } +} diff --git a/src/ViaFerrea.Core/Simulation/WorldSettings.cs b/src/ViaFerrea.Core/Simulation/WorldSettings.cs new file mode 100644 index 0000000..3663708 --- /dev/null +++ b/src/ViaFerrea.Core/Simulation/WorldSettings.cs @@ -0,0 +1,46 @@ +using ViaFerrea.Core.Data; + +namespace ViaFerrea.Core.Simulation; + +/// Sistemi del gioco infinito attivabili alla creazione della partita (guida, sezione 13). +[Flags] +public enum EndlessFlags : ushort +{ + None = 0, + Regions = 1 << 0, + Eras = 1 << 1, + Decay = 1 << 2, + Antitrust = 1 << 3, + Contracts = 1 << 4, + Dynasty = 1 << 5, + Holding = 1 << 6, + NewGamePlus = 1 << 7, + + /// Predefinito: tutti tranne la dinastia. + Default = Regions | Eras | Decay | Antitrust | Contracts | Holding | NewGamePlus, +} + +/// Richiesta di nuova partita (comando NewGame del protocollo). +public sealed record NewGameSettings +{ + public ulong Seed { get; init; } = 1; + public int SizeKm { get; init; } = 128; + public int? StartYear { get; init; } + public string DifficultyId { get; init; } = "imprenditore"; + /// Difficoltà «Personalizzata»: sostituisce il preset se presente. + public DifficultyDef? DifficultyOverride { get; init; } + public EndlessFlags Endless { get; init; } = EndlessFlags.Default; + public string RegionId { get; init; } = "valdoria"; + public string PlayerCompanyName { get; init; } = "Società Ferroviaria Valdoria"; +} + +/// Impostazioni effettive di una partita, salvate con il mondo. +public sealed class WorldSettings +{ + public required ulong Seed { get; init; } + public required int SizeKm { get; init; } + public required int StartYear { get; init; } + public required string RegionId { get; init; } + public required DifficultyDef Difficulty { get; init; } + public required EndlessFlags Endless { get; init; } +} diff --git a/src/ViaFerrea.Core/Time/Calendar.cs b/src/ViaFerrea.Core/Time/Calendar.cs new file mode 100644 index 0000000..f511dc1 --- /dev/null +++ b/src/ViaFerrea.Core/Time/Calendar.cs @@ -0,0 +1,63 @@ +using ViaFerrea.Core.Data; + +namespace ViaFerrea.Core.Time; + +/// +/// Costanti del calendario lette da balance.json (time): tick per giorno, giorni per mese, +/// mesi per anno e fattore dell'orologio dei treni. +/// +public sealed class Calendar +{ + public int TickMs { get; } + public int TicksPerDay { get; } + public int DaysPerMonth { get; } + public int MonthsPerYear { get; } + public int DaysPerYear { get; } + public int StartYear { get; } + + /// Secondi di orologio dei treni che passano in un tick. + public double TrainSecondsPerTick { get; } + + /// Minuti di orologio dei treni in un giorno di calendario. + public double TrainMinutesPerDay => TrainSecondsPerTick * TicksPerDay / 60.0; + + public Calendar(TimeBalance time, int startYear) + { + TickMs = time.TickMs; + TicksPerDay = time.TicksPerDay; + DaysPerMonth = time.DaysPerMonth; + MonthsPerYear = time.MonthsPerYear; + DaysPerYear = time.DaysPerMonth * time.MonthsPerYear; + StartYear = startYear; + TrainSecondsPerTick = time.TickMs / 1000.0 * time.TrainClockFactor; + } + + /// Data di calendario corrispondente a un indice di giorno dall'inizio della partita. + public GameDate DateOfDay(long dayIndex) + { + long year = dayIndex / DaysPerYear; + int dayOfYear = (int)(dayIndex % DaysPerYear); + return new GameDate(StartYear + (int)year, dayOfYear / DaysPerMonth + 1, dayOfYear % DaysPerMonth + 1); + } + + /// Indice di giorno di una data (inverso di ). + public long DayOf(GameDate date) => + (long)(date.Year - StartYear) * DaysPerYear + (date.Month - 1) * DaysPerMonth + (date.Day - 1); + + /// Converte minuti di orologio dei treni in giorni di calendario. + public double TrainMinutesToDays(double minutes) => minutes / TrainMinutesPerDay; +} + +/// Data di calendario di gioco (mesi da 30 giorni). +public readonly record struct GameDate(int Year, int Month, int Day) : IComparable +{ + private static readonly string[] MonthsIt = + ["gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"]; + + public int CompareTo(GameDate other) => + Year != other.Year ? Year.CompareTo(other.Year) : Month != other.Month ? Month.CompareTo(other.Month) : Day.CompareTo(other.Day); + + /// Formato italiano, per esempio «14 marzo 1872». + public override string ToString() => + $"{Day} {(Month >= 1 && Month <= MonthsIt.Length ? MonthsIt[Month - 1] : Month.ToString(System.Globalization.CultureInfo.InvariantCulture))} {Year}"; +} diff --git a/src/ViaFerrea.Core/Time/GameClock.cs b/src/ViaFerrea.Core/Time/GameClock.cs new file mode 100644 index 0000000..3eea42b --- /dev/null +++ b/src/ViaFerrea.Core/Time/GameClock.cs @@ -0,0 +1,37 @@ +namespace ViaFerrea.Core.Time; + +/// +/// Orologio della simulazione: conta i tick e segnala i cambi di giorno, mese, trimestre e anno. +/// Il tick 0 è la mezzanotte del primo giorno; i flag «nuovo giorno» valgono nel primo tick del giorno. +/// +public sealed class GameClock(Calendar calendar) +{ + public Calendar Calendar { get; } = calendar; + + /// Tick eseguiti dall'inizio della partita. + public long Tick { get; private set; } + + /// Giorni interi trascorsi (indice del giorno corrente). + public long Day => Tick / Calendar.TicksPerDay; + + /// Tick all'interno del giorno corrente. + public int TickOfDay => (int)(Tick % Calendar.TicksPerDay); + + public bool IsNewDay => TickOfDay == 0; + public bool IsNewMonth => IsNewDay && Day % Calendar.DaysPerMonth == 0; + public bool IsNewQuarter => IsNewDay && Day % (Calendar.DaysPerMonth * 3) == 0; + public bool IsNewYear => IsNewDay && Day % Calendar.DaysPerYear == 0; + + public GameDate Date => Calendar.DateOfDay(Day); + + public int Year => Calendar.StartYear + (int)(Day / Calendar.DaysPerYear); + + /// Anni (frazionari) trascorsi dall'inizio: usato dal ciclo economico mondiale. + public double YearsElapsed => (double)Tick / ((long)Calendar.TicksPerDay * Calendar.DaysPerYear); + + /// Avanza di un tick. + public void Advance() => Tick++; + + /// Ripristina da salvataggio. + public void Restore(long tick) => Tick = tick; +} diff --git a/src/ViaFerrea.Tools/BmpWriter.cs b/src/ViaFerrea.Tools/BmpWriter.cs new file mode 100644 index 0000000..f68a6f4 --- /dev/null +++ b/src/ViaFerrea.Tools/BmpWriter.cs @@ -0,0 +1,42 @@ +namespace ViaFerrea.Tools; + +/// Scrittura di bitmap BMP a 24 bit senza dipendenze. +public static class BmpWriter +{ + /// Scrive un'immagine RGB (pixel riga per riga dall'alto, 3 byte per pixel). + public static void Write(string path, int width, int height, byte[] rgb) + { + int rowSize = (width * 3 + 3) & ~3; + int imageSize = rowSize * height; + using var fs = File.Create(path); + using var w = new BinaryWriter(fs); + w.Write((byte)'B'); + w.Write((byte)'M'); + w.Write(54 + imageSize); + w.Write(0); + w.Write(54); + w.Write(40); + w.Write(width); + w.Write(height); + w.Write((short)1); + w.Write((short)24); + w.Write(0); + w.Write(imageSize); + w.Write(2835); + w.Write(2835); + w.Write(0); + w.Write(0); + var row = new byte[rowSize]; + for (int y = height - 1; y >= 0; y--) + { + for (int x = 0; x < width; x++) + { + int s = (y * width + x) * 3; + row[x * 3] = rgb[s + 2]; + row[x * 3 + 1] = rgb[s + 1]; + row[x * 3 + 2] = rgb[s]; + } + w.Write(row); + } + } +} diff --git a/src/ViaFerrea.Tools/CommandLine.cs b/src/ViaFerrea.Tools/CommandLine.cs new file mode 100644 index 0000000..691a312 --- /dev/null +++ b/src/ViaFerrea.Tools/CommandLine.cs @@ -0,0 +1,82 @@ +using System.Globalization; + +namespace ViaFerrea.Tools; + +/// Analisi minima degli argomenti: «--chiave valore» e opzioni booleane «--flag». +public sealed class CommandLine +{ + private readonly Dictionary _options = new(StringComparer.Ordinal); + private readonly HashSet _used = new(StringComparer.Ordinal); + + public CommandLine(IReadOnlyList args) + { + for (int i = 0; i < args.Count; i++) + { + string a = args[i]; + if (!a.StartsWith("--", StringComparison.Ordinal)) + throw new ArgumentException($"Argomento inatteso: {a}"); + string key = a[2..]; + string? value = null; + int eq = key.IndexOf('='); + if (eq >= 0) + { + value = key[(eq + 1)..]; + key = key[..eq]; + } + else if (i + 1 < args.Count && !args[i + 1].StartsWith("--", StringComparison.Ordinal)) + { + value = args[++i]; + } + _options[key] = value; + } + } + + public bool Flag(string name) + { + _used.Add(name); + return _options.ContainsKey(name); + } + + public string? String(string name) + { + _used.Add(name); + return _options.TryGetValue(name, out var v) ? v : null; + } + + public string String(string name, string fallback) => String(name) ?? fallback; + + public string Required(string name) => String(name) ?? throw new ArgumentException($"Opzione obbligatoria mancante: --{name}"); + + public int Int(string name, int fallback) + { + string? v = String(name); + return v is null ? fallback : int.Parse(v, NumberStyles.Integer, CultureInfo.InvariantCulture); + } + + public ulong ULong(string name, ulong fallback) + { + string? v = String(name); + return v is null ? fallback : ulong.Parse(v, NumberStyles.Integer, CultureInfo.InvariantCulture); + } + + public double Double(string name, double fallback) + { + string? v = String(name); + return v is null ? fallback : double.Parse(v, NumberStyles.Float, CultureInfo.InvariantCulture); + } + + /// Segnala le opzioni passate ma mai lette (probabili refusi). + public void EnsureAllUsed() + { + var unknown = _options.Keys.Where(k => !_used.Contains(k)).ToList(); + if (unknown.Count > 0) throw new ArgumentException($"Opzioni sconosciute: {string.Join(", ", unknown.Select(u => "--" + u))}"); + } +} + +/// Un comando di viaferrea-tools. +public interface IToolCommand +{ + string Name { get; } + string Usage { get; } + int Run(CommandLine args); +} diff --git a/src/ViaFerrea.Tools/Commands/GenMapCommand.cs b/src/ViaFerrea.Tools/Commands/GenMapCommand.cs new file mode 100644 index 0000000..55afe55 --- /dev/null +++ b/src/ViaFerrea.Tools/Commands/GenMapCommand.cs @@ -0,0 +1,44 @@ +using System.Diagnostics; +using ViaFerrea.Core.Data; +using ViaFerrea.Core.Map; + +namespace ViaFerrea.Tools.Commands; + +/// genmap --seed --size --out mappa.bmp: genera una mappa e ne scrive un'immagine di controllo. +public sealed class GenMapCommand : IToolCommand +{ + public string Name => "genmap"; + + public string Usage => "genmap --seed --size <64|128|256> --out [--scale ] [--year ] [--region ]"; + + public int Run(CommandLine args) + { + ulong seed = args.ULong("seed", 1); + int size = args.Int("size", 128); + string output = args.String("out", "mappa.bmp"); + int scale = args.Int("scale", 1); + var data = GameData.LoadDefault(); + int year = args.Int("year", data.Balance.Time.DefaultStartYear); + string region = args.String("region", "valdoria"); + args.EnsureAllUsed(); + + var sw = Stopwatch.StartNew(); + var map = MapGenerator.Generate(data, new MapSpec(seed, size, year, region)); + long genMs = sw.ElapsedMilliseconds; + + var rgb = MapRenderer.Render(map, Math.Max(1, scale), out int w, out int h); + BmpWriter.Write(output, w, h, rgb); + + var t = map.Terrain; + var counts = new int[11]; + foreach (byte b in t.Types) counts[b]++; + Console.WriteLine($"genmap: seme {seed}, {size} km ({t.Width}×{t.Height} celle), mare a {map.SeaSide}, generata in {genMs} ms"); + Console.WriteLine($" fasi: {string.Join(", ", map.PhaseMillis.Select(kv => $"{kv.Key} {kv.Value} ms"))}"); + Console.WriteLine($" città {map.Towns.Count}, industrie {map.Industries.Count}, giacimenti {map.Sites.Count}, hub {map.Hubs.Count}"); + Console.WriteLine(" celle: " + string.Join(", ", Enum.GetValues().Select(c => $"{c} {100.0 * counts[(int)c] / t.Types.Length:F1}%"))); + foreach (var town in map.Towns.Take(8)) Console.WriteLine($" città {town.Name}: {town.Population} abitanti"); + Console.WriteLine($" hash del terreno {t.ComputeHash():x16}"); + Console.WriteLine($" immagine {output} ({w}×{h})"); + return 0; + } +} diff --git a/src/ViaFerrea.Tools/Commands/SimulateCommand.cs b/src/ViaFerrea.Tools/Commands/SimulateCommand.cs new file mode 100644 index 0000000..037141e --- /dev/null +++ b/src/ViaFerrea.Tools/Commands/SimulateCommand.cs @@ -0,0 +1,100 @@ +using System.Diagnostics; +using System.Globalization; +using System.Text; +using ViaFerrea.Core.Data; +using ViaFerrea.Core.Economy; +using ViaFerrea.Core.Persistence; +using ViaFerrea.Core.Simulation; + +namespace ViaFerrea.Tools.Commands; + +/// +/// simulate: fa girare il mondo per N anni senza client e scrive i KPI annuali in CSV +/// (separatore «;», decimali con la virgola) con le colonne della guida (14.5). +/// +public sealed class SimulateCommand : IToolCommand +{ + public string Name => "simulate"; + + public string Usage => "simulate --seed --years [--size 128] [--difficulty imprenditore] [--scenario ] [--out kpi.csv] [--save ]"; + + private static readonly CultureInfo It = CultureInfo.InvariantCulture; + + public int Run(CommandLine args) + { + ulong seed = args.ULong("seed", 1); + int years = args.Int("years", 20); + int size = args.Int("size", 128); + string difficulty = args.String("difficulty", "imprenditore"); + string? scenario = args.String("scenario"); + string output = args.String("out", "kpi.csv"); + string? savePath = args.String("save"); + args.EnsureAllUsed(); + + var data = GameData.LoadDefault(); + var total = Stopwatch.StartNew(); + World world; + if (scenario is not null) + world = Scenarios.ScenarioLoader.Load(data, scenario).World; + else + world = WorldFactory.Create(data, new NewGameSettings { Seed = seed, SizeKm = size, DifficultyId = difficulty }); + long createMs = total.ElapsedMilliseconds; + + var csv = new StringBuilder(); + csv.AppendLine("anno;compagnia;bene;prezzo medio;produzione;consumo;popolazione;efficienza media;condizione media flotta;condizione media impianti;cassa;patrimonio;quota di mercato;nota"); + var lastProduced = (long[])world.Goods.Produced.Clone(); + var lastConsumed = (long[])world.Goods.Consumed.Clone(); + + var sim = Stopwatch.StartNew(); + for (int y = 0; y < years; y++) + { + int year = world.Clock.Year; + world.RunYears(1); + WriteYear(world, year, csv, lastProduced, lastConsumed); + Array.Copy(world.Goods.Produced, lastProduced, lastProduced.Length); + Array.Copy(world.Goods.Consumed, lastConsumed, lastConsumed.Length); + world.Events.Drain(); + } + long simMs = sim.ElapsedMilliseconds; + + File.WriteAllText(output, csv.ToString(), new UTF8Encoding(encoderShouldEmitUTF8Identifier: true)); + if (savePath is not null) SaveFile.SaveToFile(world, savePath, typeof(SimulateCommand).Assembly.GetName().Version?.ToString() ?? "?"); + + Console.WriteLine($"simulate: {years} anni su {world.Settings.SizeKm} km in {simMs / 1000.0:F1} s (creazione {createMs} ms)"); + Console.WriteLine($" data finale {world.Clock.Date}, hash {world.LastStateHash:x16}"); + Console.WriteLine($" popolazione {Core.Common.Money.GroupThousands((ulong)world.Towns.Sum(t => (long)t.Population))}, industrie aperte {world.Industries.Count(i => !i.Closed)} su {world.Industries.Count}"); + Console.WriteLine($" invarianti: denaro {(world.MoneyBalanceSum() == 0 ? "ok" : "ROTTO")}, merci {(Enumerable.Range(0, data.GoodCount).All(g => world.TotalStock(g) == world.Goods.ExpectedStock(g)) ? "ok" : "ROTTO")}"); + Console.WriteLine($" KPI in {output}"); + return 0; + } + + private static void WriteYear(World w, int year, StringBuilder csv, long[] lastProduced, long[] lastConsumed) + { + var data = w.Data; + long population = w.Towns.Sum(t => (long)t.Population); + var open = w.Industries.Where(i => !i.Closed).ToList(); + double efficiency = open.Count == 0 ? 0 : open.Average(i => i.Efficiency); + double plant = open.Count == 0 ? 0 : open.Average(i => i.Condition); + for (int g = 0; g < data.GoodCount; g++) + { + var def = data.Goods[g]; + double price = w.Market.PriceHistory[g].Average / 100.0; + long produced = w.Goods.Produced[g] - lastProduced[g]; + long consumed = w.Goods.Consumed[g] - lastConsumed[g]; + string note = def.Era > year ? "non ancora disponibile" : ""; + csv.AppendLine(string.Join(';', year.ToString(It), "", def.Id, Dec(price), produced.ToString(It), consumed.ToString(It), + population.ToString(It), Dec(efficiency), "", Dec(plant), "", "", "", note)); + } + long totalCarrier = w.Companies.Sum(c => Company.Revenue(c.LastYearEntries)); + foreach (var c in w.Companies) + { + long revenue = Company.Revenue(c.LastYearEntries); + double share = totalCarrier > 0 ? (double)revenue / totalCarrier : 0; + string note = $"{(c.IsPlayer ? "giocatore" : c.AiPersonality)}, rating {c.Rating}, livello {c.Tier}{(c.Bankrupt ? ", bancarotta" : "")}"; + csv.AppendLine(string.Join(';', year.ToString(It), c.Name, "", "", "", "", population.ToString(It), "", "", "", + Dec(c.Cash.Lire), Dec(c.NetWorth.Lire), Dec(share), note)); + } + } + + private static string Dec(double v) => v.ToString("0.###", It).Replace('.', ','); +} diff --git a/src/ViaFerrea.Tools/Commands/ValidateDataCommand.cs b/src/ViaFerrea.Tools/Commands/ValidateDataCommand.cs new file mode 100644 index 0000000..92dbf99 --- /dev/null +++ b/src/ViaFerrea.Tools/Commands/ValidateDataCommand.cs @@ -0,0 +1,32 @@ +using ViaFerrea.Core.Data; + +namespace ViaFerrea.Tools.Commands; + +/// validate-data [--data cartella]: valida schema e semantica di tutti i file dati. +public sealed class ValidateDataCommand : IToolCommand +{ + public string Name => "validate-data"; + + public string Usage => "validate-data [--data ] valida data/*.json con schema e regole semantiche"; + + public int Run(CommandLine args) + { + string? dir = args.String("data"); + args.EnsureAllUsed(); + var source = dir is null ? DirectoryDataSource.FindDefault() : new DirectoryDataSource(dir); + try + { + var data = GameData.Load(source); + Console.WriteLine($"validate-data: ok ({source.Description})"); + Console.WriteLine($" beni {data.Goods.Count}, industrie {data.Industries.Count}, veicoli {data.Vehicles.Count}, " + + $"ere {data.Eras.Eras.Count}, livelli {data.Tiers.Tiers.Count}, difficoltà {data.Difficulty.Presets.Count}"); + Console.WriteLine($" hash dei dati {data.Hash:x16}"); + return 0; + } + catch (DataValidationException ex) + { + Console.Error.WriteLine(ex.Message); + return 1; + } + } +} diff --git a/src/ViaFerrea.Tools/MapRenderer.cs b/src/ViaFerrea.Tools/MapRenderer.cs new file mode 100644 index 0000000..a968a44 --- /dev/null +++ b/src/ViaFerrea.Tools/MapRenderer.cs @@ -0,0 +1,72 @@ +using ViaFerrea.Core.Map; + +namespace ViaFerrea.Tools; + +/// +/// Rendering di controllo della mappa con la palette dell'immagine di riferimento 05: +/// colore per tipo di cella, fasce altimetriche, ombreggiatura da nord-ovest, città e industrie. +/// +public static class MapRenderer +{ + private static (byte R, byte G, byte B) Hex(int rgb) => ((byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb); + + private static readonly (byte R, byte G, byte B) Plain = Hex(0xcfd7bd); + private static readonly (byte R, byte G, byte B) Hill = Hex(0xc0c8a6); + private static readonly (byte R, byte G, byte B) Mountain = Hex(0xaeb690); + private static readonly (byte R, byte G, byte B) Forest = Hex(0x5f8f4a); + private static readonly (byte R, byte G, byte B) Field = Hex(0xd9c26a); + private static readonly (byte R, byte G, byte B) Water = Hex(0x8fb4c6); + private static readonly (byte R, byte G, byte B) Sea = Hex(0x8fb4c6); + private static readonly (byte R, byte G, byte B) Town = Hex(0xb3573e); + private static readonly (byte R, byte G, byte B) Industry = Hex(0x7c8590); + private static readonly (byte R, byte G, byte B) Rock = Hex(0x9a9a8a); + private static readonly (byte R, byte G, byte B) Marsh = Hex(0x9db38a); + + public static byte[] Render(GeneratedMap map, int scale, out int width, out int height) + { + var t = map.Terrain; + width = t.Width / scale; + height = t.Height / scale; + var rgb = new byte[width * height * 3]; + var sampler = new TerrainSampler(t); + for (int py = 0; py < height; py++) + { + for (int px = 0; px < width; px++) + { + int x = px * scale + scale / 2, y = py * scale + scale / 2; + var type = t.TypeAt(x, y); + var c = type switch + { + CellType.Plain => Plain, + CellType.Hill => Hill, + CellType.Mountain => Mountain, + CellType.Forest => Forest, + CellType.Field => Field, + CellType.Water => Water, + CellType.Sea => Sea, + CellType.Town => Town, + CellType.Industry => Industry, + CellType.Rock => Rock, + _ => Marsh, + }; + double shade = 1.0; + if (type is not (CellType.Sea or CellType.Water)) + { + // ombreggiatura: luce da nord-ovest, ombre verso sud-est + var g = sampler.Gradient((x + 0.5) * t.CellSizeM, (y + 0.5) * t.CellSizeM); + double light = (-g.X * -0.7071 + -g.Y * -0.7071) * 6.0; + shade = Math.Clamp(1.0 + light, 0.6, 1.25); + // fasce altimetriche leggere + double h = t.CellHeightM(x, y); + shade *= 1.0 - Math.Min(0.18, h / 2200.0 * 0.18); + if (Math.Abs(h % 100) < 4 && h > 50) shade *= 0.93; + } + int o = (py * width + px) * 3; + rgb[o] = (byte)Math.Clamp(c.R * shade, 0, 255); + rgb[o + 1] = (byte)Math.Clamp(c.G * shade, 0, 255); + rgb[o + 2] = (byte)Math.Clamp(c.B * shade, 0, 255); + } + } + return rgb; + } +} diff --git a/src/ViaFerrea.Tools/Program.cs b/src/ViaFerrea.Tools/Program.cs index 9363298..f589f49 100644 --- a/src/ViaFerrea.Tools/Program.cs +++ b/src/ViaFerrea.Tools/Program.cs @@ -1,8 +1,17 @@ +using ViaFerrea.Tools.Commands; + namespace ViaFerrea.Tools; /// Strumenti da riga di comando di Via Ferrea. public static class ToolsProgram { + private static readonly IToolCommand[] Commands = + [ + new ValidateDataCommand(), + new GenMapCommand(), + new SimulateCommand(), + ]; + public static int Main(string[] args) { if (args.Length == 0 || args[0] is "-h" or "--help" or "help") @@ -10,14 +19,28 @@ public static class ToolsProgram PrintHelp(); return args.Length == 0 ? 1 : 0; } - Console.Error.WriteLine($"Comando sconosciuto: {args[0]}"); - PrintHelp(); - return 1; + var command = Commands.FirstOrDefault(c => c.Name == args[0]); + if (command is null) + { + Console.Error.WriteLine($"Comando sconosciuto: {args[0]}"); + PrintHelp(); + return 1; + } + try + { + return command.Run(new CommandLine(args[1..])); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine($"{command.Name}: {ex.Message}"); + Console.Error.WriteLine($"uso: viaferrea-tools {command.Usage}"); + return 2; + } } private static void PrintHelp() { Console.WriteLine("viaferrea-tools [opzioni]"); - Console.WriteLine(" (i comandi arrivano dalla Fase 1)"); + foreach (var c in Commands) Console.WriteLine($" {c.Usage}"); } } diff --git a/src/ViaFerrea.Tools/Scenarios/ScenarioLoader.cs b/src/ViaFerrea.Tools/Scenarios/ScenarioLoader.cs new file mode 100644 index 0000000..0f229af --- /dev/null +++ b/src/ViaFerrea.Tools/Scenarios/ScenarioLoader.cs @@ -0,0 +1,13 @@ +using ViaFerrea.Core.Data; +using ViaFerrea.Core.Simulation; + +namespace ViaFerrea.Tools.Scenarios; + +/// Caricamento degli scenari di prova (tests/scenarios/*.json): arriva con la Fase 2. +public static class ScenarioLoader +{ + public sealed record LoadedScenario(World World); + + public static LoadedScenario Load(GameData data, string path) => + throw new ArgumentException($"Gli scenari ({path}) sono supportati dalla Fase 2"); +} diff --git a/tests/ViaFerrea.Tests/Core/CommonTests.cs b/tests/ViaFerrea.Tests/Core/CommonTests.cs new file mode 100644 index 0000000..4a99cf4 --- /dev/null +++ b/tests/ViaFerrea.Tests/Core/CommonTests.cs @@ -0,0 +1,98 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Tests.Harness; + +namespace ViaFerrea.Tests.Basics; + +public static class CommonTests +{ + [Test] + public static void MoneyFormatsItalian() + { + Assert.Equal("₤ 1.284.500", Money.FromLire(1_284_500).ToString()); + Assert.Equal("₤ 1.284.500,25", Money.FromLire(1_284_500.25m).ToString("it2")); + Assert.Equal("₤ 3,91 mln", Money.FromLire(3_910_000).ToString("short")); + Assert.Equal("₤ 48.200", Money.FromLire(48_200).ToString("short")); + Assert.Equal("−₤ 19.700", Money.FromLire(-19_700).ToString()); + Assert.Equal("₤ 0", Money.Zero.ToString()); + Assert.Equal("₤ 999", Money.FromLire(999).ToString()); + } + + [Test] + public static void MoneyArithmeticIsExact() + { + var a = Money.FromLire(10.10m); + var b = Money.FromLire(0.20m); + Assert.Equal(1030L, (a + b).Cents); + Assert.Equal(990L, (a - b).Cents); + Assert.Equal(3030L, (a * 3).Cents); + Assert.Equal(1515L, (a * 1.5).Cents); + Assert.True(a > b); + Assert.Throws(() => _ = new Money(long.MaxValue) + new Money(1)); + } + + [Test] + public static void XxHash64MatchesReferenceVectors() + { + Assert.Equal(0xef46db3751d8e999UL, XxHash64.Hash([])); + Assert.Equal(0xd24ec4f1a98c6e5bUL, XxHash64.Hash("a"u8)); + Assert.Equal(0x44bc2cf5ad770999UL, XxHash64.Hash("abc"u8)); + Assert.Equal(0x7e13e2793f7d6198UL, XxHash64.Hash("Via Ferrea"u8)); + Assert.Equal(0x95584af7701f808dUL, XxHash64.Hash([], 12345)); + var hundred = new byte[100]; + for (int i = 0; i < hundred.Length; i++) hundred[i] = (byte)i; + Assert.Equal(0x6ac1e58032166597UL, XxHash64.Hash(hundred)); + Assert.Equal(0x28ba1ae2de4de27UL, XxHash64.Hash(hundred, 12345)); + } + + [Test(Description = "DMath coincide con Math entro 1e-14 relativi su argomenti casuali")] + public static void DMathMatchesMathClosely() + { + var rng = new Rng(2024); + for (int i = 0; i < 20_000; i++) + { + double x = rng.NextDouble(-50, 50); + Check(Math.Exp(x), DMath.Exp(x), "exp", x); + double p = rng.NextDouble(1e-6, 1e6); + Check(Math.Log(p), DMath.Log(p), "log", p); + double a = rng.NextDouble(-1000, 1000); + CheckAbs(Math.Sin(a), DMath.Sin(a), "sin", a); + CheckAbs(Math.Cos(a), DMath.Cos(a), "cos", a); + double t = rng.NextDouble(-100, 100); + Check(Math.Atan(t), DMath.Atan(t), "atan", t); + double y = rng.NextDouble(-5, 5), xx = rng.NextDouble(-5, 5); + CheckAbs(Math.Atan2(y, xx), DMath.Atan2(y, xx), "atan2", y); + double b = rng.NextDouble(0.01, 300), e = rng.NextDouble(-3, 3); + Check(Math.Pow(b, e), DMath.Pow(b, e), "pow", b); + } + Assert.Equal(1.0, DMath.Exp(0)); + Assert.Equal(0.0, DMath.Log(1)); + Assert.Equal(8.0, DMath.Pow(2, 3)); + Assert.Equal(0.125, DMath.Pow(2, -3)); + Assert.True(double.IsNaN(DMath.Log(-1))); + Assert.Equal(double.PositiveInfinity, DMath.Exp(1000)); + Assert.Equal(0.0, DMath.Exp(-1000)); + Assert.Approx(Math.Exp(-740), DMath.Exp(-740), 1e-320); + Assert.Approx(Math.Log(5e-310), DMath.Log(5e-310), 1e-12); + } + + private static void Check(double expected, double actual, string fn, double arg) + { + double tol = Math.Max(1e-300, Math.Abs(expected) * 2e-14); + Assert.Approx(expected, actual, tol, $"{fn}({arg:R})"); + } + + private static void CheckAbs(double expected, double actual, string fn, double arg) + { + Assert.Approx(expected, actual, 1e-13, $"{fn}({arg:R})"); + } + + [Test] + public static void TypedIdsAreDistinctAndOrdered() + { + var a = new StationId(3); + var b = new StationId(5); + Assert.True(a.CompareTo(b) < 0); + Assert.False(StationId.None.IsValid); + Assert.Equal("Station#3", a.ToString()); + } +} diff --git a/tests/ViaFerrea.Tests/Core/RngTests.cs b/tests/ViaFerrea.Tests/Core/RngTests.cs index 39eb0d7..2bc1bd5 100644 --- a/tests/ViaFerrea.Tests/Core/RngTests.cs +++ b/tests/ViaFerrea.Tests/Core/RngTests.cs @@ -1,7 +1,7 @@ using ViaFerrea.Core.Common; using ViaFerrea.Tests.Harness; -namespace ViaFerrea.Tests.Core; +namespace ViaFerrea.Tests.Basics; public static class RngTests { diff --git a/tests/ViaFerrea.Tests/Core/TimeTests.cs b/tests/ViaFerrea.Tests/Core/TimeTests.cs new file mode 100644 index 0000000..e73b84b --- /dev/null +++ b/tests/ViaFerrea.Tests/Core/TimeTests.cs @@ -0,0 +1,46 @@ +using ViaFerrea.Core.Time; +using ViaFerrea.Tests.Harness; + +namespace ViaFerrea.Tests.Basics; + +public static class TimeTests +{ + private static Calendar Cal() => new(TestData.Data.Balance.Time, 1850); + + [Test] + public static void CalendarConstantsMatchGuide() + { + var c = Cal(); + Assert.Equal(240, c.TicksPerDay); + Assert.Equal(360, c.DaysPerYear); + Assert.Approx(3.0, c.TrainSecondsPerTick, 1e-12, "un tick = 3 s di orologio dei treni"); + Assert.Approx(2.5, c.TrainMinutesToDays(30), 1e-12, "30 minuti di orologio = 2,5 giorni"); + } + + [Test] + public static void DatesRoundTripAndFormatInItalian() + { + var c = Cal(); + var d = c.DateOfDay(22 * 360 + 2 * 30 + 13); + Assert.Equal(new GameDate(1872, 3, 14), d); + Assert.Equal("14 marzo 1872", d.ToString()); + Assert.Equal(22L * 360 + 2 * 30 + 13, c.DayOf(d)); + } + + [Test] + public static void ClockFlagsFireAtBoundaries() + { + var clock = new GameClock(Cal()); + Assert.True(clock.IsNewDay && clock.IsNewMonth && clock.IsNewYear); + clock.Advance(); + Assert.False(clock.IsNewDay); + clock.Restore(240L * 30); + Assert.True(clock.IsNewMonth); + Assert.False(clock.IsNewQuarter); + clock.Restore(240L * 90); + Assert.True(clock.IsNewQuarter); + clock.Restore(240L * 360); + Assert.True(clock.IsNewYear); + Assert.Equal(1851, clock.Year); + } +} diff --git a/tests/ViaFerrea.Tests/Data/DataTests.cs b/tests/ViaFerrea.Tests/Data/DataTests.cs new file mode 100644 index 0000000..20c6ae4 --- /dev/null +++ b/tests/ViaFerrea.Tests/Data/DataTests.cs @@ -0,0 +1,148 @@ +using System.Text.Json.Nodes; +using ViaFerrea.Core.Data; +using ViaFerrea.Tests.Harness; + +namespace ViaFerrea.Tests.Data; + +public static class DataTests +{ + [Test(Description = "I file dati reali superano schema e validazione semantica, con le quantità minime richieste")] + public static void RealDataLoadsWithMinimumCounts() + { + var d = TestData.Data; + Assert.True(d.Goods.Count >= 12, "almeno 12 beni"); + Assert.True(d.Industries.Count >= 14, "almeno 14 industrie"); + Assert.True(d.Vehicles.Count >= 8, "almeno 8 veicoli"); + Assert.True(d.Eras.Eras.Count >= 4, "almeno 4 ere"); + Assert.Equal(5, d.Tiers.Tiers.Count); + Assert.True(d.Difficulty.Presets.Count >= 4, "almeno 4 difficoltà"); + Assert.Equal("spare_parts", d.Goods[d.SparePartsGood].Id); + Assert.Equal("machinery", d.Goods[d.MachineryGood].Id); + Assert.NotEqual(0UL, d.Hash); + } + + [Test] + public static void ReferencesAreResolvedToIndices() + { + var d = TestData.Data; + var steel = d.Industry("steel_mill"); + Assert.Equal(d.GoodIndex("iron_ore"), steel.Recipe.Inputs[0].GoodIndex); + Assert.Equal(d.GoodIndex("steel"), steel.Recipe.Outputs[0].GoodIndex); + Assert.Equal(Traction.Steam, d.Vehicle("loco_steam_1850").Traction); + Assert.True(d.Vehicle("wagon_hopper").GoodIndices.Contains(d.GoodIndex("coal"))); + Assert.Equal(120, steel.Capacity(1)); + Assert.Equal(900, steel.Capacity(5)); + } + + [Test] + public static void DifficultyPresetsMatchGuideTable() + { + var d = TestData.Data; + var a = d.DifficultyPreset("apprendista"); + var f = d.DifficultyPreset("ferro_e_sangue"); + Assert.Equal(50_000_000L, a.InitialCapital); + Assert.Equal(180, a.BankruptcyDays); + Assert.Equal(TakeoverRule.Disabled, a.PlayerTakeover); + Assert.Equal(5, f.AiCompetitors); + Assert.True(f.PublicFromStart); + Assert.Approx(0.6, f.PlayerShareAtStart, 1e-12); + Assert.Equal(IronmanRule.Yes, f.Ironman); + } + + [Test] + public static void HashIgnoresFormatting() + { + var files = MemoryDataSource.Snapshot(TestData.Source); + var node = JsonNode.Parse(files["goods.json"])!; + files["goods.json"] = node.ToJsonString(new System.Text.Json.JsonSerializerOptions { WriteIndented = false }); + var reformatted = GameData.Load(new MemoryDataSource(files)); + Assert.Equal(TestData.Data.Hash, reformatted.Hash); + } + + [Test] + public static void HashChangesWithContent() + { + var files = MemoryDataSource.Snapshot(TestData.Source); + files["goods.json"] = files["goods.json"].Replace("\"basePrice\": 3800", "\"basePrice\": 3900", StringComparison.Ordinal); + Assert.NotEqual(TestData.Data.Hash, GameData.Load(new MemoryDataSource(files)).Hash); + } + + [Test] + public static void SchemaRejectsUnknownAndMissingProperties() + { + var errors = LoadErrors(files => + { + var root = JsonNode.Parse(files["goods.json"])!; + root["goods"]![0]!["colour"] = "black"; + root["goods"]![1]!.AsObject().Remove("basePrice"); + files["goods.json"] = root.ToJsonString(); + }); + Assert.True(errors.Any(e => e.Contains("colour", StringComparison.Ordinal)), "proprietà sconosciuta segnalata"); + Assert.True(errors.Any(e => e.Contains("basePrice", StringComparison.Ordinal)), "proprietà mancante segnalata"); + } + + [Test] + public static void SchemaRejectsOutOfRangeAndBadEnum() + { + var errors = LoadErrors(files => + { + var root = JsonNode.Parse(files["industries.json"])!; + root["industries"]![0]!["kind"] = "magical"; + root["industries"]![0]!["capacityPerLevel"] = new JsonArray(1, 2, 3); + files["industries.json"] = root.ToJsonString(); + }); + Assert.True(errors.Any(e => e.Contains("non tra quelli ammessi", StringComparison.Ordinal))); + Assert.True(errors.Any(e => e.Contains("almeno 5 elementi", StringComparison.Ordinal))); + } + + [Test] + public static void SemanticRejectsUnknownReferenceAndDuplicates() + { + var errors = LoadErrors(files => + { + var root = JsonNode.Parse(files["industries.json"])!; + root["industries"]![7]!["recipe"]!["inputs"]![0]!["good"] = "unobtanium"; + root["industries"]![1]!["id"] = "coal_mine"; + files["industries.json"] = root.ToJsonString(); + }); + Assert.True(errors.Any(e => e.Contains("unobtanium", StringComparison.Ordinal))); + Assert.True(errors.Any(e => e.Contains("duplicato «coal_mine»", StringComparison.Ordinal))); + } + + [Test(Description = "Un refuso in balance.json (sezione con schema aperto) è comunque bloccato dal deserializzatore")] + public static void TypoInBalanceIsRejected() + { + var errors = LoadErrors(files => + { + files["balance.json"] = files["balance.json"].Replace("\"wagePerWorkerPerMonth\"", "\"wagePerWorkerPerMoth\"", StringComparison.Ordinal); + }); + Assert.True(errors.Count > 0); + Assert.True(errors.Any(e => e.Contains("balance.json", StringComparison.Ordinal))); + } + + [Test] + public static void SemanticRejectsBrokenFailureShares() + { + var errors = LoadErrors(files => + { + files["maintenance.json"] = files["maintenance.json"].Replace("\"minorShare\": 0.70", "\"minorShare\": 0.60", StringComparison.Ordinal); + }); + Assert.True(errors.Any(e => e.Contains("failure.*Share", StringComparison.Ordinal))); + } + + private static IReadOnlyList LoadErrors(Action> mutate) + { + var files = MemoryDataSource.Snapshot(TestData.Source); + mutate(files); + try + { + GameData.Load(new MemoryDataSource(files)); + } + catch (DataValidationException ex) + { + return ex.Errors; + } + Assert.Fail("i dati alterati dovevano essere rifiutati"); + return []; + } +} diff --git a/tests/ViaFerrea.Tests/Economy/EconomyTests.cs b/tests/ViaFerrea.Tests/Economy/EconomyTests.cs new file mode 100644 index 0000000..98015f9 --- /dev/null +++ b/tests/ViaFerrea.Tests/Economy/EconomyTests.cs @@ -0,0 +1,215 @@ +using ViaFerrea.Core.Commands; +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Data; +using ViaFerrea.Core.Economy; +using ViaFerrea.Core.Simulation; +using ViaFerrea.Core.Simulation.Systems; +using ViaFerrea.Tests.Harness; + +namespace ViaFerrea.Tests.Economy; + +public static class EconomyTests +{ + [Test(Description = "Invarianti: la somma di tutti i saldi resta zero, nessun bene nasce dal nulla")] + public static void MoneyAndGoodsInvariantsHold() + { + var w = TestWorlds.Small(101); + for (int month = 0; month < 18; month++) + { + w.RunDays(30); + Assert.Equal(0L, w.MoneyBalanceSum(), $"denaro al mese {month}"); + for (int g = 0; g < w.Data.GoodCount; g++) + Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"merce {w.Data.Goods[g].Id} al mese {month}"); + } + Assert.True(w.Goods.Produced.Sum() > 0, "qualcosa è stato prodotto"); + } + + [Test(Description = "I prezzi globali restano sempre entro 0,3·Pb e 3·Pb")] + public static void PricesStayWithinLimits() + { + var w = TestWorlds.Small(102, "ferro_e_sangue"); + var m = w.Data.Balance.Market; + for (int day = 0; day < 3 * 360; day++) + { + w.RunDays(1); + for (int g = 0; g < w.Data.GoodCount; g++) + { + double pb = w.Data.Goods[g].BasePrice; + Assert.InRange(w.Market.GlobalPrice[g], m.MinPriceFactor * pb - 1e-6, m.MaxPriceFactor * pb + 1e-6); + } + } + } + + [Test] + public static void PriceRisesWhenDemandExceedsSupply() + { + var w = TestWorlds.Small(103); + int food = w.Data.GoodIndex("food"); + double before = w.Market.GlobalPrice[food]; + // nessuna produzione di alimentari raggiunge il mercato: la domanda cittadina spinge il prezzo + w.RunDays(120); + Assert.True(w.Market.GlobalPrice[food] > before * 1.5, $"prezzo alimentari {before} → {w.Market.GlobalPrice[food]}"); + } + + [Test] + public static void LocalPriceFollowsImbalanceWithinBounds() + { + var lp = TestData.Data.Balance.LocalPrice; + Assert.Approx(100.0, Market.LocalPrice(100, 10, 10, lp), 1e-9); + Assert.True(Market.LocalPrice(100, 50, 0, lp) > 130); + Assert.True(Market.LocalPrice(100, 0, 50, lp) < 70); + Assert.InRange(Market.LocalPrice(100, 1e9, 0, lp), 60, 140); + Assert.InRange(Market.LocalPrice(100, 0, 1e9, lp), 60, 140); + } + + [Test] + public static void FreightAndPassengerTariffsFollowFormulas() + { + var t = TestData.Data.Balance.Tariffs; + // a prezzo base: 40 t × 150 × 1 × 20^0,9 centesimi + var freight = Tariffs.Freight(40, 20, 3800, 3800, 1, 1, t, 1.0); + Assert.Equal(Money.FromCentsRounded(40 * 150 * DMath.Pow(20, 0.9)), freight); + // consegna con il doppio del tempo atteso: oltre la soglia del 50 % la tariffa cala + var late = Tariffs.Freight(40, 20, 3800, 3800, 2, 1, t, 1.0); + Assert.True(late < freight && late.Cents >= freight.Cents / 2); + var staff = Tariffs.Passenger(10, 15, PaxClass.Staff, 1, 1, t, 1.0); + var worker = Tariffs.Passenger(10, 15, PaxClass.Worker, 1, 1, t, 1.0); + Assert.Approx(3.0, (double)staff.Cents / worker.Cents, 0.01, "classe personale ×3"); + } + + [Test(Description = "Solo le industrie servite crescono; con punteggio alto salgono di livello dopo due trimestri")] + public static void ServedIndustryWithGoodScoreUpgrades() + { + var w = TestWorlds.Small(104); + var mine = w.Industries.First(i => i.Def.Kind == IndustryKind.Primary && i.Level == 1 && !i.Closed); + var other = w.Industries.First(i => i != mine && i.Def.Kind == IndustryKind.Primary && !i.Closed); + int otherLevel = other.Level; + mine.Served = true; + for (int q = 0; q < 2; q++) + { + for (int d = 0; d < 90; d++) + { + // tutta la produzione viene spedita e i posti sono coperti + mine.WorkersPresent = mine.JobsWorkers; + mine.StaffPresent = mine.JobsStaff; + mine.CovWorkers = 1; + mine.CovStaff = 1; + mine.RevenueEma = 1_000_000; + mine.CostEma = 100_000; + mine.QuarterShipped = mine.QuarterProduced; + w.RunDays(1); + } + } + w.RunDays(1); // il secondo trimestre si chiude nel primo tick del giorno 180 + Assert.Equal(2, mine.Level, "livello dopo due trimestri ottimi"); + Assert.Equal(otherLevel, other.Level, "un'industria non servita non cambia livello"); + } + + [Test(Description = "Un'industria servita ma abbandonata scende fino a 0 e chiude dopo quattro trimestri a zero")] + public static void NeglectedServedIndustryDeclinesAndCloses() + { + var w = TestWorlds.Small(105); + var ind = w.Industries.First(i => i.Def.Kind == IndustryKind.Processing && !i.Closed); + ind.Served = true; + int startLevel = ind.Level; + w.RunDays(90 * (startLevel + 5) + 1); + Assert.True(ind.Closed, $"chiusa (livello iniziale {startLevel}, ultimo punteggio {ind.LastScore:F2})"); + Assert.True(w.Events.Recent.Any(e => e.Text.Contains(ind.Name, StringComparison.Ordinal) && e.Text.Contains("chiude", StringComparison.Ordinal))); + } + + [Test] + public static void TownsGrowWithSatisfactionAndShrinkWithout() + { + var w = TestWorlds.Small(106); + var served = w.Towns[0]; + var neglected = w.Towns[1]; + int s0 = served.Population, n0 = neglected.Population; + for (int d = 0; d < 360; d++) + { + for (int g = 0; g < w.Data.GoodCount; g++) + { + int need = (int)Math.Ceiling(served.DemandToday[g]) + 1; + if (served.DemandToday[g] > 0 && served.Stock[g] < need) + { + int add = need - served.Stock[g]; + served.Stock[g] += add; + w.Goods.Produced[g] += add; // consegna simulata, contabilizzata + } + } + w.RunDays(1); + } + Assert.True(served.OverallSatisfaction > 0.9, $"soddisfazione {served.OverallSatisfaction:F2}"); + Assert.True(served.Population > s0, $"la città servita cresce: {s0} → {served.Population}"); + Assert.True(neglected.Population < n0, $"la città trascurata cala: {n0} → {neglected.Population}"); + Assert.True(served.Services >= 2); + } + + [Test] + public static void LoansRespectCreditAndAccrueInterest() + { + var w = TestWorlds.Small(107); + var player = w.Player; + var credit = FinanceSystem.MaxLoan(w, player); + Assert.Equal(new Money(w.Difficulty.InitialCredit), credit); + var cash0 = player.Cash; + + w.Enqueue(new TakeLoanCommand(credit + Money.FromLire(1)) { Issuer = player.Id, Seq = 1 }); + w.Enqueue(new TakeLoanCommand(Money.FromLire(100_000)) { Issuer = player.Id, Seq = 2 }); + w.RunTicks(1); + var results = w.DrainResults(); + Assert.Equal(CommandError.CreditLimit, results[0].Error); + Assert.True(results[1].Ok, results[1].Message); + Assert.Equal(cash0 + Money.FromLire(100_000), player.Cash); + Assert.Equal(Money.FromLire(100_000), player.Debt); + + w.RunDays(31); + Assert.True(player.Debt < Money.FromLire(100_000), "la rata riduce il debito"); + Assert.True(player.YearEntries[(int)LedgerEntry.Interest] < 0, "interessi pagati"); + Assert.Equal(0L, w.MoneyBalanceSum()); + + var loanId = player.Loans[0].Id; + w.Enqueue(new RepayLoanCommand(loanId, player.Debt) { Issuer = player.Id, Seq = 3 }); + w.RunTicks(1); + Assert.True(w.DrainResults()[0].Ok); + Assert.Equal(Money.Zero, player.Debt); + } + + [Test] + public static void UnimplementedCommandsAreRejectedWithoutSideEffects() + { + var w = TestWorlds.Small(108); + ulong before = ViaFerrea.Core.Persistence.StateHasher.Compute(w); + w.Enqueue(new PendingCommand(CommandType.BuildTrack, []) { Issuer = w.Player.Id, Seq = 9 }); + w.Enqueue(new TakeLoanCommand(Money.FromLire(1)) { Issuer = new CompanyId(99), Seq = 10 }); + w.Pipeline.Get().Step(w.Context); + var results = w.DrainResults(); + Assert.Equal(CommandError.NotImplemented, results[0].Error); + Assert.Equal(CommandError.UnknownCompany, results[1].Error); + Assert.Equal(before, ViaFerrea.Core.Persistence.StateHasher.Compute(w)); + } + + [Test] + public static void WalkingWorkersStaffIndustriesNextToTowns() + { + var w = TestWorlds.Small(109); + w.RunDays(40); + var manufacturing = w.Industries.Where(i => i.Def.Kind == IndustryKind.Manufacturing && !i.Closed).ToList(); + Assert.True(manufacturing.Count > 0); + Assert.True(manufacturing.Any(i => i.CovWorkers > 0.9), "almeno una manifattura con lavoratori a piedi dalla città vicina"); + Assert.True(w.Commutes.All(c => c.Walking)); + foreach (var town in w.Towns) + Assert.True(town.EmployedWorkers <= town.Workforce(w.Data.Balance.Town), $"{town.Name}: occupati oltre la forza lavoro"); + } + + [Test] + public static void DifficultyChangesStartingConditions() + { + var easy = TestWorlds.Small(110, "apprendista"); + var hard = TestWorlds.Small(110, "ferro_e_sangue"); + Assert.Equal(Money.FromLire(500_000), easy.Player.Cash); + Assert.Equal(Money.FromLire(100_000), hard.Player.Cash); + Assert.Equal(1 + 1, easy.Companies.Count); + Assert.Equal(1 + 5, hard.Companies.Count); + Assert.Equal(easy.Terrain.ComputeHash(), hard.Terrain.ComputeHash(), "la difficoltà non cambia la mappa"); + } +} diff --git a/tests/ViaFerrea.Tests/Map/MapTests.cs b/tests/ViaFerrea.Tests/Map/MapTests.cs new file mode 100644 index 0000000..a18ca57 --- /dev/null +++ b/tests/ViaFerrea.Tests/Map/MapTests.cs @@ -0,0 +1,126 @@ +using System.Diagnostics; +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Data; +using ViaFerrea.Core.Map; +using ViaFerrea.Tests.Harness; + +namespace ViaFerrea.Tests.Map; + +public static class MapTests +{ + [Test(Description = "Accettazione F1: mappa da 128 km generata in meno di 3 s", Slow = true, Isolated = true)] + public static void Map128GeneratesUnderThreeSeconds() + { + TestWorlds.Map(1, 64); // riscaldamento JIT + var sw = Stopwatch.StartNew(); + var map = TestWorlds.Map(3, 128); + sw.Stop(); + Assert.Equal(1280, map.Terrain.Width); + Assert.True(sw.ElapsedMilliseconds < 3000, $"generazione in {sw.ElapsedMilliseconds} ms"); + } + + [Test] + public static void SameSeedSameMapDifferentSeedDifferentMap() + { + var a = TestWorlds.Map(5, 64); + var b = TestWorlds.Map(5, 64); + var c = TestWorlds.Map(6, 64); + Assert.Equal(a.Terrain.ComputeHash(), b.Terrain.ComputeHash()); + Assert.SequenceEqual(a.Towns.Select(t => t.Name), b.Towns.Select(t => t.Name)); + Assert.NotEqual(a.Terrain.ComputeHash(), c.Terrain.ComputeHash()); + } + + [Test(Description = "Distanze della guida: città ≥ 6 km, industrie entro i vincoli di collocazione")] + public static void PlacementDistancesAreRespected() + { + var data = TestData.Data; + foreach (ulong seed in new ulong[] { 11, 12 }) + { + var map = TestWorlds.Map(seed, 128); + double cs = map.Terrain.CellSizeM; + int expectedTowns = data.Balance.Map.Towns.CountBySize["128"]; + Assert.True(map.Towns.Count >= expectedTowns * 0.8, $"città {map.Towns.Count} su {expectedTowns}"); + for (int i = 0; i < map.Towns.Count; i++) + { + for (int j = i + 1; j < map.Towns.Count; j++) + { + var a = map.Towns[i]; + var b = map.Towns[j]; + double km = Math.Sqrt(Sq(a.CellX - b.CellX) + Sq(a.CellY - b.CellY)) * cs / 1000; + Assert.True(km >= data.Balance.Map.Towns.MinDistanceKm - 1e-9, $"{a.Name}–{b.Name}: {km:F2} km"); + } + } + foreach (var ind in map.Industries) + { + var def = data.Industries[ind.TypeIndex]; + var p = map.Terrain.CellCenter(ind.CellX, ind.CellY); + double nearest = map.Towns.Min(t => MapGenerator.TownEdgeDistanceKm(t, p, cs)); + if (def.Placement.MinTownDistanceKm is { } mn) Assert.True(nearest >= mn, $"{ind.Name}: {nearest:F2} km < {mn}"); + if (def.Placement.MaxTownDistanceKm is { } mx) Assert.True(nearest <= mx, $"{ind.Name}: {nearest:F2} km > {mx}"); + if (def.Placement.MaxInputDistanceKm is { } maxIn) + { + foreach (var input in def.Recipe.Inputs) + { + bool near = map.Industries.Any(o => data.Industries[o.TypeIndex].Recipe.Outputs.Any(x => x.Good == input.Good) + && Math.Sqrt(Sq(o.CellX - ind.CellX) + Sq(o.CellY - ind.CellY)) * cs / 1000 <= maxIn + 1e-9); + Assert.True(near, $"{ind.Name}: nessun produttore di {input.Good} entro {maxIn} km"); + } + } + if (def.Placement.Needs == PlacementNeed.Deposit) + { + Assert.True(ind.SiteIndex >= 0, $"{ind.Name} senza giacimento"); + Assert.Equal(def.Placement.Resource, map.Sites[ind.SiteIndex].Kind); + } + var (x0, y0) = GeneratedMap.FootprintOrigin(ind.CellX, ind.CellY, ind.FootprintCells); + for (int y = y0; y < y0 + ind.FootprintCells; y++) + for (int x = x0; x < x0 + ind.FootprintCells; x++) + Assert.Equal(CellType.Industry, map.Terrain.TypeAt(x, y)); + } + Assert.True(map.Hubs.Any(h => h.Kind == HubKind.Port), "almeno un porto"); + Assert.True(map.Hubs.Any(h => h.Kind == HubKind.Border), "almeno un valico"); + } + } + + private static double Sq(double v) => v * v; + + [Test] + public static void TerrainHasSeaRiversAndCover() + { + var map = TestWorlds.Map(21, 64); + var t = map.Terrain; + var counts = new int[11]; + foreach (byte b in t.Types) counts[b]++; + Assert.True(counts[(int)CellType.Sea] > 0, "mare presente"); + Assert.True(counts[(int)CellType.Water] > 0, "fiumi o laghi presenti"); + Assert.True(counts[(int)CellType.Forest] > 0, "boschi presenti"); + Assert.True(counts[(int)CellType.Plain] > t.Types.Length / 10, "pianure abbondanti"); + // il mare tocca il lato scelto ed è a quota zero + bool seaOnEdge = false; + for (int i = 0; i < t.Width; i++) + { + seaOnEdge |= t.TypeAt(i, 0) == CellType.Sea || t.TypeAt(i, t.Height - 1) == CellType.Sea + || t.TypeAt(0, i) == CellType.Sea || t.TypeAt(t.Width - 1, i) == CellType.Sea; + } + Assert.True(seaOnEdge); + for (int i = 0; i < t.Types.Length; i++) + { + if (t.Types[i] == (byte)CellType.Sea) Assert.Equal((ushort)0, t.Heights[i]); + } + Assert.True(t.RiverWidth.Any(w => w >= 2), "almeno un fiume largo più di una cella"); + } + + [Test] + public static void SamplerInterpolatesBetweenCellCenters() + { + var t = new Terrain(4, 4, 100, 64); + for (int y = 0; y < 4; y++) + for (int x = 0; x < 4; x++) + t.Heights[t.Index(x, y)] = Terrain.ToDecimeters(x * 10); // pendenza costante del 10 % + var s = new TerrainSampler(t); + Assert.Approx(0.0, s.HeightAt(50, 150), 1e-9); + Assert.Approx(5.0, s.HeightAt(100, 150), 1e-9); + Assert.Approx(15.0, s.HeightAt(200, 250), 1e-9); + Assert.Approx(0.1, s.Slope(150, 150), 1e-9); + Assert.Approx(DMath.Pi, Math.Abs(s.Aspect(150, 150)), 1e-9, "discesa verso ovest"); + } +} diff --git a/tests/ViaFerrea.Tests/Persistence/PersistenceTests.cs b/tests/ViaFerrea.Tests/Persistence/PersistenceTests.cs new file mode 100644 index 0000000..8d92f5f --- /dev/null +++ b/tests/ViaFerrea.Tests/Persistence/PersistenceTests.cs @@ -0,0 +1,104 @@ +using ViaFerrea.Core.Commands; +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Persistence; +using ViaFerrea.Core.Simulation; +using ViaFerrea.Tests.Harness; + +namespace ViaFerrea.Tests.Persistence; + +public static class PersistenceTests +{ + [Test(Description = "Determinismo: stesso seme e stessi comandi agli stessi tick → stesso hash")] + public static void SameSeedAndCommandsGiveSameHash() + { + ulong Run() + { + var w = TestWorlds.Small(200); + w.RunDays(45); + w.Enqueue(new TakeLoanCommand(Money.FromLire(50_000)) { Issuer = w.Player.Id, Seq = 1 }); + w.RunDays(400); + return w.LastStateHash; + } + ulong a = Run(); + ulong b = Run(); + Assert.Equal(a, b); + var other = TestWorlds.Small(201); + other.RunDays(445); + Assert.NotEqual(a, other.LastStateHash); + } + + [Test(Description = "Salvataggio e caricamento: stesso hash subito e dopo altri 200 giorni")] + public static void SaveLoadRoundTripPreservesFuture() + { + var a = TestWorlds.Small(202); + a.Enqueue(new TakeLoanCommand(Money.FromLire(80_000)) { Issuer = a.Player.Id }); + a.RunDays(100); + byte[] file = SaveFile.Save(a, "test"); + var b = SaveFile.Load(TestData.Data, file); + + Assert.Equal(StateHasher.Compute(a), StateHasher.Compute(b)); + Assert.Equal(a.LastStateHash, b.LastStateHash); + Assert.Equal(a.Clock.Tick, b.Clock.Tick); + Assert.Equal(a.Events.Total, b.Events.Total); + + a.RunDays(200); + b.RunDays(200); + Assert.Equal(a.LastStateHash, b.LastStateHash); + Assert.Equal(0L, b.MoneyBalanceSum()); + + // un secondo giro di salvataggio produce un file identico + Assert.SequenceEqual(SaveFile.Save(a, "test"), SaveFile.Save(b, "test")); + } + + [Test] + public static void SaveHeaderIsReadableWithoutDecompressing() + { + var w = TestWorlds.Small(203); + w.RunDays(10); + var info = SaveFile.ReadInfo(SaveFile.Save(w, "0.1.0")); + Assert.Equal("0.1.0", info.GameVersion); + Assert.Equal(w.Clock.Tick, info.Tick); + Assert.Equal(w.Settings.Seed, info.Seed); + Assert.Equal(w.Player.Name, info.CompanyName); + Assert.Equal(w.Data.Hash, info.DataHash); + } + + [Test] + public static void CorruptSavesAreRejected() + { + var w = TestWorlds.Small(204); + byte[] file = SaveFile.Save(w, "test"); + Assert.Throws(() => SaveFile.Load(TestData.Data, "XXXX"u8.ToArray())); + var truncated = file.AsSpan(0, file.Length / 2).ToArray(); + Assert.Throws(() => SaveFile.Load(TestData.Data, truncated)); + } + + [Test] + public static void SaveWriterReaderRoundTripPrimitives() + { + var wtr = new SaveWriter(4); + wtr.Write((byte)7); + wtr.Write(true); + wtr.Write(-12345); + wtr.Write(long.MinValue); + wtr.Write(ulong.MaxValue); + wtr.Write(Math.PI); + wtr.Write("Città d'acqua €"); + wtr.Write((string?)null); + wtr.Write(new[] { 1, 2, 3 }.AsSpan()); + wtr.Write(new ushort[] { 0, 65535 }.AsSpan()); + var r = new SaveReader(wtr.ToArray()); + Assert.Equal((byte)7, r.ReadByte()); + Assert.True(r.ReadBool()); + Assert.Equal(-12345, r.ReadInt32()); + Assert.Equal(long.MinValue, r.ReadInt64()); + Assert.Equal(ulong.MaxValue, r.ReadUInt64()); + Assert.Equal(Math.PI, r.ReadDouble()); + Assert.Equal("Città d'acqua €", r.ReadString()); + Assert.Equal(null, r.ReadString()); + Assert.SequenceEqual(new[] { 1, 2, 3 }, r.ReadInt32Array()); + Assert.SequenceEqual(new ushort[] { 0, 65535 }, r.ReadUInt16Array()); + Assert.True(r.AtEnd); + Assert.Throws(() => r.ReadInt32()); + } +} diff --git a/tests/ViaFerrea.Tests/TestData.cs b/tests/ViaFerrea.Tests/TestData.cs new file mode 100644 index 0000000..7c33203 --- /dev/null +++ b/tests/ViaFerrea.Tests/TestData.cs @@ -0,0 +1,13 @@ +using ViaFerrea.Core.Data; + +namespace ViaFerrea.Tests; + +/// Dati di gioco caricati una volta sola e condivisi dai test (sono immutabili). +public static class TestData +{ + private static readonly Lazy Shared = new(() => GameData.Load(Source), LazyThreadSafetyMode.ExecutionAndPublication); + + public static DirectoryDataSource Source => DirectoryDataSource.FindDefault(); + + public static GameData Data => Shared.Value; +} diff --git a/tests/ViaFerrea.Tests/TestWorlds.cs b/tests/ViaFerrea.Tests/TestWorlds.cs new file mode 100644 index 0000000..02b8386 --- /dev/null +++ b/tests/ViaFerrea.Tests/TestWorlds.cs @@ -0,0 +1,14 @@ +using ViaFerrea.Core.Map; +using ViaFerrea.Core.Simulation; + +namespace ViaFerrea.Tests; + +/// Mondi di prova generati dal seme (64 km: veloci da creare). +public static class TestWorlds +{ + public static World Small(ulong seed = 42, string difficulty = "imprenditore") => + WorldFactory.Create(TestData.Data, new NewGameSettings { Seed = seed, SizeKm = 64, DifficultyId = difficulty }); + + public static GeneratedMap Map(ulong seed, int sizeKm) => + MapGenerator.Generate(TestData.Data, new MapSpec(seed, sizeKm, TestData.Data.Balance.Time.DefaultStartYear)); +}