@elite-dangerous-almanac/core 0.1.7 → 0.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/PROVENANCE/ships/SOURCES.md +18 -0
- package/dist/chunk-3BM5BHI3.js +1 -0
- package/dist/chunk-3BM5BHI3.js.map +1 -0
- package/dist/{chunk-ZZT2PQZ5.js → chunk-6BO5JJNI.js} +1 -1
- package/dist/{chunk-24INI4U7.js → chunk-CX7B67OI.js} +1 -1
- package/dist/chunk-CX7B67OI.js.map +1 -0
- package/dist/{chunk-UHSNB5SV.js → chunk-EVJ32UF3.js} +1 -1
- package/dist/{chunk-UHSNB5SV.js.map → chunk-EVJ32UF3.js.map} +1 -1
- package/dist/{chunk-UXFMVZAY.js → chunk-OVUHQEH5.js} +1 -1
- package/dist/{chunk-UXFMVZAY.js.map → chunk-OVUHQEH5.js.map} +1 -1
- package/dist/{chunk-LLHGSBPI.js → chunk-PA5EITW5.js} +1 -1
- package/dist/{chunk-LLHGSBPI.js.map → chunk-PA5EITW5.js.map} +1 -1
- package/dist/{chunk-VDVFJXX5.js → chunk-QY3L5BKN.js} +1 -1
- package/dist/ships/index.d.ts +1 -1
- package/dist/ships/index.js +1 -1
- package/dist/ships/mobility.d.ts +12 -0
- package/dist/ships/mobility.js +1 -1
- package/dist/ships/modules-all.js +1 -1
- package/dist/ships/modules-core.js +1 -1
- package/dist/ships/modules.d.ts +27 -1
- package/dist/ships/modules.js +1 -1
- package/dist/ships/pre-engineered-stats.js +1 -1
- package/dist/ships/ship-loadout.d.ts +142 -7
- package/dist/ships/ship-loadout.js +1 -1
- package/dist/ships/slef.d.ts +10 -8
- package/dist/ships/slef.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-24INI4U7.js.map +0 -1
- package/dist/chunk-EXVCRIDP.js +0 -1
- package/dist/chunk-EXVCRIDP.js.map +0 -1
- /package/dist/{chunk-ZZT2PQZ5.js.map → chunk-6BO5JJNI.js.map} +0 -0
- /package/dist/{chunk-VDVFJXX5.js.map → chunk-QY3L5BKN.js.map} +0 -0
|
@@ -397,6 +397,24 @@ FDevIDs, stats from coriolis-data and EDSY, joined on `symbol`.
|
|
|
397
397
|
`passengerCabins` and `vesselHangars`. Guardian and AX weapons retain their distinct
|
|
398
398
|
family where their function differs. A core record's family follows from its `slot`,
|
|
399
399
|
which is on every one of them, so the two never disagree.
|
|
400
|
+
- **`supercruiseOvercharge` — the SCO drive line.** The 36
|
|
401
|
+
`Int_Hyperdrive_Overcharge_*` records carry `true`; the 36 plain drives of the same
|
|
402
|
+
sizes and ratings, and every other record in all four catalogues, omit it.
|
|
403
|
+
- **Source:** FDevIDs `outfitting.csv`, which sells the two drive lines under distinct
|
|
404
|
+
symbol families and names the Overcharge one `Frame Shift Drive (SCO)`. No registry
|
|
405
|
+
publishes a field for the capability: coriolis-data and EDSY both leave it implicit
|
|
406
|
+
in the symbol and the display name.
|
|
407
|
+
- **Derivation:** the symbol family is the classification, exactly as it is for `slot`
|
|
408
|
+
above, and it is applied once here so that consumers read a datum instead of
|
|
409
|
+
matching `Int_Hyperdrive_Overcharge` themselves — which a pre-engineered or fitted
|
|
410
|
+
article's symbol does not always let them do. Stored as a sparse flag rather than a
|
|
411
|
+
`true`/`false` pair on all 72 drives, following `alwaysPowered` and
|
|
412
|
+
`guardianZoneResistance`.
|
|
413
|
+
- **Nothing else is derived from it.** The two lines share every jump constant this
|
|
414
|
+
catalogue carries (`optMass`, `maxFuel`, `fuelMul`, `fuelPower`, and the
|
|
415
|
+
size-determined `fsdHeatRate` above), so no calculation reads the flag; the
|
|
416
|
+
overcharged supercruise behaviour the drives are named for has no published figures
|
|
417
|
+
and none are stored.
|
|
400
418
|
|
|
401
419
|
### `module-families.jsonc` — the family ids and their English names
|
|
402
420
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{weaponsCapacitorMetrics}from"./chunk-FMPRCYKY.js";import{shieldRecovery,cellBankSummary}from"./chunk-VZZUNSDF.js";import{shieldMetrics}from"./chunk-2FHHMYDC.js";import{getShipBySymbol,getShipByName,getShipSlots}from"./chunk-WNGQ3IAM.js";import{parseSlef,toSlef,stringifySlef,getLoadoutModifier}from"./chunk-OVUHQEH5.js";import{sourcePurchaseFromLoadout,getSourceModuleValue}from"./chunk-IYU4WLFM.js";import{powerBudget}from"./chunk-RLUS76LZ.js";import{isNonOutfittingSlot,isBuiltInHullModule,cloneLoadoutModule,identifyPreEngineeredVariant,cloneModuleStats,availableBlueprintsFor,availableExperimentalsFor,ownKeyIn,FITTED_ITEM,blueprintAvailableFor,blueprintRoutesFor,experimentalAvailableFor,primitiveEngineeringInputsFor,missingBaseLabels,journalModifiersFor,getPreEngineeredStats,getPreEngineeredJournalModifiers,getPreEngineeredModifiers,ordinaryEngineeringProof,unresolvedModifiers,orderBySlotLayout,matchingKeyIn,isCargoHatchSlot,isFinalGuardianWeaponEngineering,scaleDamageComponents}from"./chunk-6BO5JJNI.js";import{weaponMetrics,sumWeaponMetrics,combinedRateOfFire}from"./chunk-LJI7VXJD.js";import{builtInModuleBySymbol,getBulkheadsForShip}from"./chunk-PA5EITW5.js";import{getPreEngineeredVariants}from"./chunk-2VPVZELZ.js";import{singleJumpRange,frameShiftDriveMassFactor,fuelPerJump,totalRange}from"./chunk-GQ5GX5TB.js";import{calculateUnladenMass,calculateCargoCapacity,calculateFuelCapacity}from"./chunk-AFVYCQWL.js";import{fixedSlotReason,validateLoadout}from"./chunk-B4ZSTOM4.js";import{mobilityMetrics}from"./chunk-CX7B67OI.js";import{calculateModuleLimits}from"./chunk-KPETDYQX.js";import{ALL_MODULES}from"./chunk-QY3L5BKN.js";import{CORE_MODULES}from"./chunk-EVJ32UF3.js";import{distributorMetrics}from"./chunk-P2QOL63K.js";import{getExperimentalEffectCost}from"./chunk-SNADUQSJ.js";import{getExperimentalEffect}from"./chunk-JPBMRJFC.js";import{heatMetrics}from"./chunk-W6EPHHTS.js";import{ammunitionCapacity}from"./chunk-AA3K5XUE.js";import{armourMetrics}from"./chunk-FGXWVFN6.js";import{getBlueprintCost}from"./chunk-TEOJCBSG.js";import{baseStats,computeModifiers,labelsForDamageType,scaleForLabel,sumMaterials,fieldForLabel,labelsForField,capabilityValueForLabel,damageTypeForLabel}from"./chunk-DYPOL3CI.js";import{resolveBlueprintForModule}from"./chunk-2TW4ZBI3.js";import{getExperimentalsForModule}from"./chunk-QTZPA2FR.js";import{getBlueprintGrade}from"./chunk-Q3QCLNVG.js";import{getDefaultLoadout}from"./chunk-GRIK3EDH.js";import{loadoutSlotName}from"./chunk-KAA4VOOB.js";import{parseSlotName,enumerateSlots,SLOT_RESTRICTION_LABELS}from"./chunk-RAO35XDF.js";import{normalizeKey}from"./chunk-BKWLI44T.js";import{truncate,describeValue,requireString,requireStringIfPresent}from"./chunk-PKWVG2JY.js";import{deepFreeze}from"./chunk-DURKO7JU.js";var NO_ISSUES=Object.freeze([]);function completeResult(value){return Object.freeze({value:value,complete:true,issues:NO_ISSUES})}function incompleteResult(issues){return Object.freeze({value:null,complete:false,issues:Object.freeze(issues.map(issue=>Object.freeze({...issue,...issue.params?{params:Object.freeze({...issue.params})}:{}})))})}var PREFIX={powerPlant:["int_powerplant","int_guardianpowerplant"],thrusters:["int_engine","int_mkiiagileboost_engine"],frameShiftDrive:["int_hyperdrive"],powerDistributor:["int_powerdistributor","int_guardianpowerdistributor"],shieldGenerator:["int_shieldgenerator"],shieldCellBank:["int_shieldcellbank"],shieldBooster:["hpt_shieldbooster"],shieldReinforcement:["int_guardianshieldreinforcement"],hullReinforcement:["int_hullreinforcement","int_guardianhullreinforcement","int_metaalloyhullreinforcement"],moduleReinforcement:["int_modulereinforcement","int_guardianmodulereinforcement"]};var startsWithAny=(symbol,prefixes)=>prefixes.some(prefix=>symbol.toLowerCase().startsWith(prefix));function isPowerDistributor(module,stats){return stats?.slot?stats.slot==="powerDistributor":startsWithAny(module.Item,PREFIX.powerDistributor)}function isPowerPlant(module,stats){const parsed=parseSlotName(module.Slot);if(parsed?.kind==="core"&&parsed.core==="powerPlant")return true;return stats?.slot?stats.slot==="powerPlant":startsWithAny(module.Item,PREFIX.powerPlant)}function isThruster(module,stats){const parsed=parseSlotName(module.Slot);if(parsed?.kind==="core"&&parsed.core==="thrusters")return true;return stats?.slot?stats.slot==="thrusters":startsWithAny(module.Item,PREFIX.thrusters)}function isFrameShiftDrive(module,stats){const parsed=parseSlotName(module.Slot);if(parsed?.kind==="core"&&parsed.core==="frameShiftDrive")return true;return stats?.slot?stats.slot==="frameShiftDrive":startsWithAny(module.Item,PREFIX.frameShiftDrive)}function isEnabled(module){return module.On!==false}function priorityOf(module){return(module.Priority??0)+1}function effectiveStat(module,field,stats){const stated=statedModifier(module,field);if(stated!==void 0)return stated;const base=stats?.[field];return typeof base==="number"?base:void 0}function statedModifier(module,field){for(const label of labelsForField(field)){if(capabilityValueForLabel(label)!==null)continue;const modified=getLoadoutModifier(module,label);if(modified!==null)return modified/scaleForLabel(label)}return void 0}function effectiveCapability(module,field,stats){for(const label of labelsForField(field)){if(capabilityValueForLabel(label)===null)continue;if(module.Engineering?.Modifiers?.some(modifier=>modifier.Label.toLowerCase()===label.toLowerCase())){return true}}const base=stats[field];return typeof base==="boolean"?base:void 0}function effectiveDamageDistribution(module,stats){const fromEffect=module.Engineering?.ExperimentalEffect?getExperimentalEffect(module.Engineering.ExperimentalEffect)?.damageDistribution:void 0;const distribution={...fromEffect??stats.damageDistribution};let resolved=fromEffect!==void 0||stats.damageDistribution!==void 0;const seen=/* @__PURE__ */new Set;for(const modifier of module.Engineering?.Modifiers??[]){const type=damageTypeForLabel(modifier.Label);if(type===null||seen.has(type))continue;seen.add(type);if(modifier.Value===void 0)continue;distribution[type]=modifier.Value/scaleForLabel(modifier.Label);resolved=true}return resolved?distribution:void 0}function convertsDamage(module){if(module.Engineering?.ExperimentalEffect&&getExperimentalEffect(module.Engineering.ExperimentalEffect)?.damageDistribution){return true}return(module.Engineering?.Modifiers??[]).some(modifier=>damageTypeForLabel(modifier.Label)!==null)}function modifierRatio(module,stats,field){const base=stats?.[field];if(typeof base!=="number"||base===0)return 1;const effective=effectiveStat(module,field,stats);return effective===void 0?1:effective/base}function relatedStat(module,stats,field,ratio){const stated=statedModifier(module,field);if(stated!==void 0)return stated;const base=stats?.[field];return typeof base==="number"?base*ratio:void 0}function effectiveModule(module,stats){if(!stats||!module.Engineering)return stats;const merged={...stats};const fields=new Set(Object.keys(stats));for(const modifier of module.Engineering.Modifiers??[]){const field=fieldForLabel(modifier.Label,stats);if(field)fields.add(field)}for(const key of fields){const capability=effectiveCapability(module,key,stats);if(capability!==void 0){merged[key]=capability;continue}const value=effectiveStat(module,key,stats);if(value!==void 0)merged[key]=value}if(stats.engineeringGroup==="thrusters"){const massRatio=modifierRatio(module,stats,"optMass");const minMass=relatedStat(module,stats,"minMass",massRatio);const maxMass=relatedStat(module,stats,"maxMass",massRatio);if(minMass!==void 0)merged.minMass=minMass;if(maxMass!==void 0)merged.maxMass=maxMass}if(stats.engineeringGroup==="thrusters"||stats.engineeringGroup==="shieldGenerators"){const performanceRatio=modifierRatio(module,stats,"optMultiplier");const minMultiplier=relatedStat(module,stats,"minMultiplier",performanceRatio);const maxMultiplier=relatedStat(module,stats,"maxMultiplier",performanceRatio);if(minMultiplier!==void 0)merged.minMultiplier=minMultiplier;if(maxMultiplier!==void 0)merged.maxMultiplier=maxMultiplier;if(stats.engineeringGroup==="thrusters"){for(const field of["minSpeedMultiplier","optSpeedMultiplier","maxSpeedMultiplier","minRotationMultiplier","optRotationMultiplier","maxRotationMultiplier"]){const value=stats[field];if(value!==void 0)merged[field]=value*performanceRatio}}}const damageDistribution=effectiveDamageDistribution(module,stats);if(damageDistribution)merged.damageDistribution=damageDistribution;if(stats.category==="hardpoint")normalizeEffectiveWeapon(module,merged);if(convertsDamage(module)){delete merged.damageComponents}else if(stats.damageComponents){merged.damageComponents=scaleDamageComponents(stats.damageComponents,stats.damage,typeof merged.damage==="number"?merged.damage:void 0)}return merged}function powerConsumerFor(module,stats){const draw=effectiveStat(module,"powerDraw",stats);if(draw===void 0||draw===0)return null;const mounted=stats?.category==="hardpoint"||stats?.category==="utility";return{draw:draw,priority:priorityOf(module),enabled:isEnabled(module),deployedOnly:mounted&&stats?.alwaysPowered!==true,label:module.Slot,symbol:module.Item}}function powerAvailable(modules,statsFor){for(const module of modules){const stats=statsFor(module);if(!isPowerPlant(module,stats))continue;if(!isEnabled(module))return 0;return effectiveStat(module,"powerCapacity",stats)??0}return 0}function metricIssue(field,reason,module){const defaultSlot=field==="powerCapacity"?"PowerPlant":field==="thrusters"?"MainEngines":void 0;const slot=module?.Slot??defaultSlot;const symbol=module?.Item;const params={field:field,reason:reason,...slot===void 0?{}:{slot:slot},...symbol===void 0?{}:{symbol:symbol}};let message;if(reason==="missing"){message=field==="powerCapacity"?"PowerPlant: no power plant is fitted":field==="thrusters"?"MainEngines: no thrusters are fitted":"no shield generator is fitted"}else if(reason==="unresolved"){const unavailable=field==="thrusters"?"thruster stats":field==="shieldGenerator"?"shield-generator stats":field==="powerCapacity"?"power capacity":field;message=`${truncate(slot??field)}: ${unavailable} unavailable for ${truncate(symbol??field)}`}else if(reason==="disabled"){message=`${truncate(slot??field)}: ${truncate(symbol??field)} is switched off`}else if(reason==="invalid"){message=`${truncate(slot??field)}: ${truncate(symbol??field)} has invalid ${field}`}else{message=`${truncate(slot??field)}: ${truncate(symbol??field)} is not powered with hardpoints retracted`}return{field:field,reason:reason,...slot===void 0?{}:{slot:slot},...symbol===void 0?{}:{symbol:symbol},message:message,params:params}}function powerPlantIssueFor(modules,statsFor){for(const module of modules){const stats=statsFor(module);if(!isPowerPlant(module,stats))continue;if(!isEnabled(module))return metricIssue("powerCapacity","disabled",module);const capacity=effectiveStat(module,"powerCapacity",stats);if(capacity===void 0)return metricIssue("powerCapacity","unresolved",module);return!Number.isFinite(capacity)||capacity<=0?metricIssue("powerCapacity","invalid",module):null}return metricIssue("powerCapacity","missing")}function powerDrawIssueFor(modules,statsFor){for(const module of modules){const consumer=powerConsumerFor(module,statsFor(module));if(consumer&&(!Number.isFinite(consumer.draw)||consumer.draw<0)){return metricIssue("powerDraw","invalid",module)}}return null}function poweredMetricBudgetFor(field,module,stats,modules,getBudget,statsFor){if(!isEnabled(module))return incompleteResult([metricIssue(field,"disabled",module)]);const plantIssue=powerPlantIssueFor(modules,statsFor);if(plantIssue)return incompleteResult([plantIssue]);const drawIssue=powerDrawIssueFor(modules,statsFor);if(drawIssue)return incompleteResult([drawIssue]);const budget=getBudget();return budget.available>0&&poweredStates(module,stats,budget).retracted?completeResult(budget):incompleteResult([metricIssue(field,"shed",module)])}function poweredShieldGeneratorResultFor(modules,getBudget,statsFor){for(const module of modules){if(!startsWithAny(module.Item,PREFIX.shieldGenerator))continue;const stats=statsFor(module);const powered=poweredMetricBudgetFor("shieldGenerator",module,stats,modules,getBudget,statsFor);if(!powered.complete)return powered;return stats===null?incompleteResult([metricIssue("shieldGenerator","unresolved",module)]):completeResult({module:module,budget:powered.value})}return incompleteResult([metricIssue("shieldGenerator","missing")])}function mapResistanceFields(read){return{kineticResistance:read("kineticResistance")??0,thermalResistance:read("thermalResistance")??0,explosiveResistance:read("explosiveResistance")??0,causticResistance:read("causticResistance")??0}}function resistancesOf(module,stats){return mapResistanceFields(field=>effectiveStat(module,field,stats))}function shieldInputFor(ship,modules,budget,systemsPips,statsFor){let generator=null;const boosters=[];let reinforcement=0;for(const module of modules){if(!isEnabled(module))continue;const stats=statsFor(module);if(!(budget.available>0&&poweredStates(module,stats,budget).retracted))continue;if(!generator&&startsWithAny(module.Item,PREFIX.shieldGenerator)){const massRatio=modifierRatio(module,stats,"optMass");const strengthRatio=modifierRatio(module,stats,"optMultiplier");const optMass=effectiveStat(module,"optMass",stats);const minMass=relatedStat(module,stats,"minMass",massRatio);const maxMass=relatedStat(module,stats,"maxMass",Math.max(1,massRatio));const optMultiplier=effectiveStat(module,"optMultiplier",stats);const minMultiplier=relatedStat(module,stats,"minMultiplier",strengthRatio);const maxMultiplier=relatedStat(module,stats,"maxMultiplier",strengthRatio);generator={...optMass===void 0?{}:{optMass:optMass},...minMass===void 0?{}:{minMass:minMass},...maxMass===void 0?{}:{maxMass:maxMass},...optMultiplier===void 0?{}:{optMultiplier:optMultiplier},...minMultiplier===void 0?{}:{minMultiplier:minMultiplier},...maxMultiplier===void 0?{}:{maxMultiplier:maxMultiplier},...resistancesOf(module,stats)}}else if(startsWithAny(module.Item,PREFIX.shieldBooster)){boosters.push({shieldBoost:effectiveStat(module,"shieldBoost",stats)??0,...resistancesOf(module,stats)})}else if(startsWithAny(module.Item,PREFIX.shieldReinforcement)){reinforcement+=effectiveStat(module,"shieldAddition",stats)??0}}return{hullMass:ship.hullMass,baseShieldStrength:ship.baseShieldStrength,generator:generator,boosters:boosters,reinforcement:reinforcement,systemsPips:systemsPips}}function shieldInputResultFor(ship,modules,getBudget,systemsPips,statsFor){const fitted=poweredShieldGeneratorResultFor(modules,getBudget,statsFor);if(!fitted.complete)return fitted;const input=shieldInputFor(ship,modules,fitted.value.budget,systemsPips,statsFor);return completeResult(input)}function thrusterCurveFor(module,stats){const effective=effectiveModule(module,stats);const minMass=effective?.minMass;const optMass=effective?.optMass;const maxMass=effective?.maxMass;const minMultiplier=effective?.minMultiplier;const optMultiplier=effective?.optMultiplier;const maxMultiplier=effective?.maxMultiplier;if(minMass===void 0||optMass===void 0||maxMass===void 0||minMultiplier===void 0||optMultiplier===void 0||maxMultiplier===void 0){return null}return{minMass:minMass,optMass:optMass,maxMass:maxMass,minMultiplier:minMultiplier,optMultiplier:optMultiplier,maxMultiplier:maxMultiplier,...effective?.optSpeedMultiplier===void 0?{}:{speedCurve:{minMass:minMass,optMass:optMass,maxMass:maxMass,minMultiplier:effective.minSpeedMultiplier??minMultiplier,optMultiplier:effective.optSpeedMultiplier,maxMultiplier:effective.maxSpeedMultiplier??maxMultiplier}},...effective?.optRotationMultiplier===void 0?{}:{rotationCurve:{minMass:minMass,optMass:optMass,maxMass:maxMass,minMultiplier:effective.minRotationMultiplier??minMultiplier,optMultiplier:effective.optRotationMultiplier,maxMultiplier:effective.maxRotationMultiplier??maxMultiplier}}}}function fittedThrusterParamsFor(modules,statsFor){for(const module of modules){const stats=statsFor(module);if(isThruster(module,stats))return thrusterCurveFor(module,stats)}return null}function mobilityInputResultFor(ship,modules,getBudget,mass,enginesPips,statsFor){let thrusters=null;for(const module of modules){const stats=statsFor(module);if(!isThruster(module,stats))continue;const powered=poweredMetricBudgetFor("thrusters",module,stats,modules,getBudget,statsFor);if(!powered.complete)return powered;thrusters=thrusterCurveFor(module,stats);if(!thrusters)return incompleteResult([metricIssue("thrusters","unresolved",module)]);break}if(!thrusters)return incompleteResult([metricIssue("thrusters","missing")]);return completeResult({minimumSpeed:ship.minimumSpeed,maximumSpeed:ship.maximumSpeed,boost:ship.boost,minPitch:ship.minPitch,pitch:ship.pitch,minRoll:ship.minRoll,roll:ship.roll,minYaw:ship.minYaw,yaw:ship.yaw,mass:typeof mass==="function"?mass():mass,thrusters:thrusters,enginesPips:enginesPips})}function shieldRecoveryInputResultFor(ship,modules,getBudget,systemsPips,statsFor){const generator=poweredShieldGeneratorResultFor(modules,getBudget,statsFor);if(!generator.complete)return generator;const{module:generatorModule,budget:budget}=generator.value;let distributor=null;for(const module of modules){const stats=statsFor(module);if(isPowerDistributor(module,stats)&&isEnabled(module)&&budget.available>0&&poweredStates(module,stats,budget).retracted)distributor=module}const generatorStats=statsFor(generatorModule);const distributorStats=distributor?statsFor(distributor):null;const strength=shieldMetrics(shieldInputFor(ship,modules,budget,0,statsFor)).strength;return completeResult({strength:strength,regenRate:effectiveStat(generatorModule,"shieldRegenRate",generatorStats)??0,brokenRegenRate:effectiveStat(generatorModule,"shieldBrokenRegenRate",generatorStats)??0,distributorDraw:effectiveStat(generatorModule,"distributorDraw",generatorStats)??.6,systemsCapacity:distributor?effectiveStat(distributor,"systemsCapacity",distributorStats)??0:0,systemsRecharge:distributor?effectiveStat(distributor,"systemsRecharge",distributorStats)??0:0,systemsPips:systemsPips})}function weaponsCapacitorInputFor(modules,weaponsPips,budget,statsFor){let weaponsCapacity=0;let weaponsRecharge=0;let sustainedEnergyPerSecond=0;for(const module of modules){if(!isEnabled(module))continue;const stats=statsFor(module);if(!poweredStates(module,stats,budget).deployed)continue;if(isPowerDistributor(module,stats)){weaponsCapacity=effectiveStat(module,"weaponsCapacity",stats)??0;weaponsRecharge=effectiveStat(module,"weaponsRecharge",stats)??0}const weapon=weaponStatsFor(module,stats);if(weapon){sustainedEnergyPerSecond+=weaponMetrics(weapon).sustainedEnergyPerSecond}}return{weaponsCapacity:weaponsCapacity,weaponsRecharge:weaponsRecharge,sustainedEnergyPerSecond:sustainedEnergyPerSecond,weaponsPips:weaponsPips}}function distributorInputFor(modules,pips,budget,statsFor){for(const module of modules){if(!isEnabled(module))continue;const stats=statsFor(module);if(!isPowerDistributor(module,stats))continue;if(!poweredStates(module,stats,budget).retracted)return null;const systemsCapacity=effectiveStat(module,"systemsCapacity",stats);const systemsRecharge=effectiveStat(module,"systemsRecharge",stats);const enginesCapacity=effectiveStat(module,"enginesCapacity",stats);const enginesRecharge=effectiveStat(module,"enginesRecharge",stats);const weaponsCapacity=effectiveStat(module,"weaponsCapacity",stats);const weaponsRecharge=effectiveStat(module,"weaponsRecharge",stats);if(systemsCapacity===void 0||systemsRecharge===void 0||enginesCapacity===void 0||enginesRecharge===void 0||weaponsCapacity===void 0||weaponsRecharge===void 0){return null}return{systemsCapacity:systemsCapacity,systemsRecharge:systemsRecharge,enginesCapacity:enginesCapacity,enginesRecharge:enginesRecharge,weaponsCapacity:weaponsCapacity,weaponsRecharge:weaponsRecharge,...pips}}return null}function heatInputFor(ship,modules,budget,statsFor){let heatEfficiency;let thrusterHeatRate=0;let deployedThrusterHeatRate=0;let fsdHeatRate=0;let weaponsCapacity=0;const weapons=[];for(const module of modules){const stats=statsFor(module);if(isPowerPlant(module,stats)){if(!isEnabled(module))return null;heatEfficiency=effectiveStat(module,"heatEfficiency",stats);continue}if(!isEnabled(module))continue;const running=poweredStates(module,stats,budget);if(isThruster(module,stats)){const heat=effectiveStat(module,"engineHeatRate",stats)??0;if(running.retracted)thrusterHeatRate+=heat;if(running.deployed)deployedThrusterHeatRate+=heat}else if(isFrameShiftDrive(module,stats)){if(running.retracted)fsdHeatRate+=effectiveStat(module,"fsdHeatRate",stats)??0}else if(isPowerDistributor(module,stats)){if(running.deployed){weaponsCapacity=effectiveStat(module,"weaponsCapacity",stats)??0}}const weapon=weaponStatsFor(module,stats);if(!running.deployed)continue;if(!weapon)continue;weapons.push({heatPerSecond:weaponMetrics(weapon).sustainedHeatPerSecond,distributorDraw:weapon.distributorDraw??0})}if(heatEfficiency===void 0)return null;return{heatCapacity:ship.heatCapacity,heatDissipation:ship.heatDissipation,heatEfficiency:heatEfficiency,retractedPowerDraw:poweredDraw(budget,"retracted"),deployedPowerDraw:poweredDraw(budget,"deployed"),thrusterHeatRate:thrusterHeatRate,deployedThrusterHeatRate:deployedThrusterHeatRate,fsdHeatRate:fsdHeatRate,weaponsCapacity:weaponsCapacity,weapons:weapons}}function poweredDraw(budget,state){const powered=state==="retracted"?"poweredRetracted":"poweredDeployed";return budget.bands.reduce((total,band)=>band[powered]?total+band[state]:total,0)}function poweredStates(module,stats,budget){const draw=effectiveStat(module,"powerDraw",stats);if(draw===void 0||draw===0)return{retracted:true,deployed:true};const band=budget.bands[Math.min(budget.bands.length,Math.max(1,priorityOf(module)))-1];if(!band)return{retracted:true,deployed:true};return{retracted:band.poweredRetracted,deployed:band.poweredDeployed}}function cellBankInputsFor(modules,budget,statsFor){const banks=[];for(const module of modules){if(!startsWithAny(module.Item,PREFIX.shieldCellBank))continue;const stats=statsFor(module);const effective=effectiveModule(module,stats);const ammunition=effective?ammunitionCapacity(effective):null;banks.push({slot:module.Slot,symbol:module.Item,reinforcementRate:effective?.shieldBankReinforcement??0,cells:ammunition?.total??0,spinUp:effective?.shieldBankSpinUp??0,duration:effective?.shieldBankDuration??0,heat:effective?.shieldBankHeat??0,powered:budget.available>0&&isEnabled(module)&&poweredStates(module,stats,budget).deployed})}return banks}function stockBulkhead(ship){const variants=getBulkheadsForShip(ship.name,CORE_MODULES);return variants.find(v=>v.symbol.toLowerCase().endsWith("_default"))??variants.find(v=>v.mass===0)??variants[0]??null}function armourInputFor(ship,modules,statsFor){const reinforcements=[];const moduleReinforcements=[];let bulkhead=null;for(const module of modules){if(!isEnabled(module))continue;const stats=statsFor(module);if(module.Slot.toLowerCase()==="armour"){bulkhead={hullBoost:effectiveStat(module,"hullBoost",stats)??0,...resistancesOf(module,stats)}}else if(startsWithAny(module.Item,PREFIX.hullReinforcement)){const boost=getLoadoutModifier(module,"DefenceModifierHealthMultiplier");reinforcements.push({hullReinforcement:effectiveStat(module,"hullReinforcement",stats)??0,hullBoost:boost===null?0:boost/scaleForLabel("DefenceModifierHealthMultiplier"),...resistancesOf(module,stats)})}else if(startsWithAny(module.Item,PREFIX.moduleReinforcement)){moduleReinforcements.push({moduleProtection:effectiveStat(module,"moduleProtection",stats)??0,integrity:effectiveStat(module,"integrity",stats)??0})}}if(!bulkhead){const stock=stockBulkhead(ship);bulkhead=stock?{hullBoost:stock.hullBoost??0,...mapResistanceFields(field=>stock[field])}:null}return{baseArmour:ship.baseArmour,bulkhead:bulkhead,reinforcements:reinforcements,moduleReinforcements:moduleReinforcements}}var WEAPON_FIELDS=["damage","roundsPerShot","rateOfFire","burstInterval","burstRounds","burstRateOfFire","chargeTime","clipSize","ammoMaximum","reloadTime","distributorDraw","thermalLoad","powerDraw","maximumRange","falloffRange","armourPiercing"];function weaponStatsFor(module,stats){if(!stats||stats.category!=="hardpoint")return null;const weapon={};for(const field of WEAPON_FIELDS){const value=effectiveStat(module,field,stats);if(value!==void 0)weapon[field]=value}normalizeEffectiveWeapon(module,weapon);const damageDistribution=effectiveDamageDistribution(module,stats);if(damageDistribution)weapon.damageDistribution=damageDistribution;if(stats.damageComponents&&!convertsDamage(module)){weapon.damageComponents=scaleDamageComponents(stats.damageComponents,stats.damage,typeof weapon.damage==="number"?weapon.damage:void 0)}if(stats.projectileRange)weapon.projectileRange={...stats.projectileRange};return weapon}function burstAdjustedRateOfFire(module,weapon){if(getLoadoutModifier(module,"RateOfFire")!==null)return void 0;const touched=["BurstSize","BurstRateOfFire","BurstInterval"].some(label=>getLoadoutModifier(module,label)!==null);if(!touched)return void 0;return combinedRateOfFire(weapon)}function normalizeEffectiveWeapon(module,weapon){const rate=burstAdjustedRateOfFire(module,weapon);if(rate!==void 0)weapon.rateOfFire=rate;const statedDamagePerSecond=getLoadoutModifier(module,"DamagePerSecond");const firingFactor=Number(weapon.roundsPerShot??1)*Number(weapon.rateOfFire??1);if(statedDamagePerSecond!==null&&firingFactor>0){weapon.damage=statedDamagePerSecond/firingFactor}const{maximumRange:maximumRange,falloffRange:falloffRange}=weapon;if(maximumRange!==void 0&&falloffRange!==void 0&&falloffRange>maximumRange){weapon.falloffRange=maximumRange}}var MILITARY_PREFIXES=["int_hullreinforcement","int_metaalloyhullreinforcement","int_modulereinforcement","int_shieldcellbank","int_guardianhullreinforcement","int_guardianmodulereinforcement","int_guardianshieldreinforcement"];var MINING_PREFIXES=["hpt_mininglaser","hpt_mining_abrblstr","hpt_mining_seismchrgwarhd","hpt_mining_subsurfdispmisle","hpt_human_extraction","hpt_miningtoolv2"];var CARGO_PREFIXES=["int_cargorack","int_largecargorack","int_corrosionproofcargorack","int_fueltank"];var RESTRICTED_SLOT_PREFIXES={mining:MINING_PREFIXES,military:MILITARY_PREFIXES,cargo:CARGO_PREFIXES,limpetController:["int_dronecontrol","int_multidronecontrol"],vesselHangar:["int_fighterbay"],passenger:["int_passengercabin","int_mkii_passengercabin"],planetaryApproachSuite:["int_planetapproachsuite"]};var problem=(constraint,message,params)=>({constraint:constraint,message:message,...params===void 0?{}:{params:params}});function restrictionProblem(slot,symbol){const restriction=slot.restriction;if(!restriction)return null;if(RESTRICTED_SLOT_PREFIXES[restriction].some(prefix=>symbol.startsWith(prefix))){return null}return problem("restrictedMount",`slot only takes ${SLOT_RESTRICTION_LABELS[restriction]}`,{restriction:restriction})}function moduleSlotProblem(slot,module){const required=module.restrictedToSlot;if(!required||slot.restriction===required)return null;return problem("restrictedMount",`module only fits a mount that takes ${SLOT_RESTRICTION_LABELS[required]}`,{restriction:required})}function moduleFitProblem(shipSymbol,slot,module){if(slot.kind==="cargoHatch"){return problem("immutableSlot","the cargoHatch slot cannot be changed")}if(slot.kind==="armour"){const hull=getShipBySymbol(shipSymbol);if(module.slot!=="armour"||module.ship===void 0){return problem("armourRequired","not a ship armour module")}if(!hull||module.ship.toLowerCase()!==hull.name.toLowerCase()){const armourHull=getShipByName(module.ship);return problem("wrongHullArmour",`armour belongs to ${truncate(module.ship)}, not ${truncate(hull?.name??shipSymbol)}`,{armourShipName:module.ship,...armourHull===null?{}:{armourShipSymbol:armourHull.symbol},shipSymbol:shipSymbol,...hull===null?{}:{shipName:hull.name}})}return null}const restricted=module.restrictedToShips;if(restricted&&!restricted.some(symbol2=>symbol2.toLowerCase()===shipSymbol.toLowerCase())){const allowedShipNames=restricted.map(symbol2=>{const hull=getShipBySymbol(symbol2);return hull?.name??symbol2});const labels=restricted.map((symbol2,index)=>{const name=allowedShipNames[index];return name===symbol2?symbol2:`${name} (${symbol2})`});return problem("restrictedHull",`module is restricted to ${truncate(labels.join(", "))}`,{allowedShipNames:allowedShipNames,allowedShipSymbols:[...restricted],shipSymbol:shipSymbol})}const wrongMount=moduleSlotProblem(slot,module);if(wrongMount)return wrongMount;const symbol=module.symbol.toLowerCase();const moduleSlot=module.slot;switch(slot.kind){case"core":if(moduleSlot!==slot.core){return problem("wrongCoreType",`not a ${slot.core} module`,{requiredCore:slot.core,moduleSlot:moduleSlot??"none"})}break;case"hardpoint":{if(module.category!=="hardpoint"){return problem("hardpointRequired","not a hardpoint weapon")}const restricted2=restrictionProblem(slot,symbol);if(restricted2)return restricted2;break}case"utility":if(module.category!=="utility"){return problem("utilityRequired","not a utility module")}return null;case"optional":{const isFuelTank=moduleSlot==="fuelTank";if(module.category!=="internal"&&!isFuelTank){return problem("optionalInternalRequired","not an optional-internal module")}if(moduleSlot&&!isFuelTank){return problem("coreModuleInOptionalSlot","a core module only fits its core slot")}const restricted2=restrictionProblem(slot,symbol);if(restricted2)return restricted2;break}}return module.class>slot.size?problem("oversized",`module size ${truncate(module.class)} exceeds slot size ${slot.size}`,{moduleClass:module.class,slotSize:slot.size}):null}function moduleFitError(shipSymbol,slot,module){return moduleFitProblem(shipSymbol,slot,module)?.message??null}var REBUY_FRACTION=.05;function exportLoadoutEvent(input,options){const fromSource=options.credits==="source";const source=fromSource?input.sourcePurchase:null;const totals=source!==null&&!input.sourceTotalsVoided&&sourceTotalsHold(input.modules,source)?source:null;const hullValue=fromSource?source?.hullValue??null:input.retailHullValue;const modulesValue=fromSource?totals?.modulesValue??null:computedModulesValue(input.modules,input.statsFor);const rebuy=fromSource?totals?.rebuy??null:hullValue===null||modulesValue===null?null:Math.trunc((hullValue+modulesValue)*REBUY_FRACTION);return{Ship:input.shipSymbol.toLowerCase(),...input.shipName===void 0?{}:{ShipName:input.shipName},...input.shipIdent===void 0?{}:{ShipIdent:input.shipIdent},...hullValue===null?{}:{HullValue:hullValue},...modulesValue===null?{}:{ModulesValue:modulesValue},UnladenMass:input.unladenMass,CargoCapacity:input.cargoCapacity,...input.maxJumpRange===null?{}:{MaxJumpRange:input.maxJumpRange},FuelCapacity:{Main:input.fuelCapacity.main,Reserve:input.fuelCapacity.reserve},...rebuy===null?{}:{Rebuy:rebuy},Modules:exportModules(input,options,fromSource)}}function exportModules(input,options,fromSource){const ordered=options.moduleOrder==="slots"?slotOrderedModules(input.modules,input.layout):[...input.modules.values()];return ordered.map(module=>{const on=module.On??(options.explicitPower?true:void 0);const priority=module.Priority??(options.explicitPower?0:void 0);const value=fromSource?sourceModuleValue(module,input.sourcePurchase):moduleValue(module,input.statsFor);return{Slot:module.Slot,Item:module.Item.toLowerCase(),...on===void 0?{}:{On:on},...priority===void 0?{}:{Priority:priority},...module.Health===void 0?{}:{Health:module.Health},...typeof value==="number"?{Value:value}:{},...module.Engineering===void 0?{}:{Engineering:cloneLoadoutModule(module).Engineering}}})}function slotOrderedModules(modules,layout){return orderBySlotLayout([...modules.values()],layout,module=>module.Slot)}function computedModulesValue(modules,statsFor){let sum=0;for(const module of modules.values()){const value=moduleValue(module,statsFor);if(value==="unknown")return null;if(value!=="free")sum+=value}return sum}function moduleValue(module,statsFor){const stats=statsFor(module);if(stats!==null)return stats.cost??"unknown";return isNonOutfittingSlot(module.Slot)||isBuiltInHullModule(module)?"free":"unknown"}var SOURCE_ITEM="ShipLoadout: sourcePurchase moduleValues[].item";function sourceModuleValue(module,source){const entry=source===null?null:getSourceModuleValue(source,module.Slot);if(entry===null)return"unknown";return normalizeKey(entry.item,SOURCE_ITEM)===normalizeKey(module.Item,FITTED_ITEM)?entry.value:"unknown"}function sourceTotalsHold(modules,source){for(const entry of source.moduleValues){const key=matchingKeyIn(modules,entry.slot);const fitted=key===null?void 0:modules.get(key);if(!fitted)return false;if(isCargoHatchSlot(entry.slot)&&entry.value===0)continue;if(normalizeKey(fitted.Item,FITTED_ITEM)!==normalizeKey(entry.item,SOURCE_ITEM)){return false}}return true}function captureLoadoutEvent(event){const modules=event.Modules;const shipName=event.ShipName;const shipIdent=event.ShipIdent;const hullValue=event.HullValue;const modulesValue=event.ModulesValue;const rebuy=event.Rebuy;const unladenMass=event.UnladenMass;const cargoCapacity=event.CargoCapacity;const fuelCapacity=event.FuelCapacity;return{Ship:event.Ship,Modules:Array.isArray(modules)?captureEach(modules,captureModule):modules,...shipName===void 0?{}:{ShipName:shipName},...shipIdent===void 0?{}:{ShipIdent:shipIdent},...hullValue===void 0?{}:{HullValue:hullValue},...modulesValue===void 0?{}:{ModulesValue:modulesValue},...rebuy===void 0?{}:{Rebuy:rebuy},...unladenMass===void 0?{}:{UnladenMass:unladenMass},...cargoCapacity===void 0?{}:{CargoCapacity:cargoCapacity},...fuelCapacity===void 0?{}:{FuelCapacity:{...fuelCapacity}}}}function captureEach(values,capture){const captured=[];const{length:length}=values;for(let index=0;index<length;index++)captured.push(capture(values[index]));return captured}function captureModule(module){if(module===null||typeof module!=="object")return module;const on=module.On;const priority=module.Priority;const health=module.Health;const value=module.Value;const engineering=module.Engineering;return{Slot:module.Slot,Item:module.Item,...on===void 0?{}:{On:on},...priority===void 0?{}:{Priority:priority},...health===void 0?{}:{Health:health},...value===void 0?{}:{Value:value},...engineering===void 0?{}:{Engineering:captureEngineering(engineering)}}}function captureEngineering(engineering){if(engineering===null||typeof engineering!=="object")return engineering;const experimental=engineering.ExperimentalEffect;const experimentalLocalised=engineering.ExperimentalEffect_Localised;const modifiers=engineering.Modifiers;return{BlueprintName:engineering.BlueprintName,Level:engineering.Level,Quality:engineering.Quality,...experimental===void 0?{}:{ExperimentalEffect:experimental},...experimentalLocalised===void 0?{}:{ExperimentalEffect_Localised:experimentalLocalised},...modifiers===void 0?{}:{Modifiers:Array.isArray(modifiers)?captureEach(modifiers,modifier=>modifier!==null&&typeof modifier==="object"?{...modifier}:modifier):modifiers}}}function hullLayout(shipSymbol){const slots=getShipSlots(shipSymbol);return slots?enumerateSlots(slots):[]}function fixedMountRejects(shipSymbol,layout,slot,stats){const mount=layout.find(candidate=>candidate.key.toLowerCase()===slot.toLowerCase());return mount!==void 0&&moduleFitProblem(shipSymbol,mount,stats)!==null}function normalizeLoadoutEvent(rawEvent){const event=captureLoadoutEvent(rawEvent);requireString(event.Ship,"ShipLoadout.fromLoadout: event.Ship");if(!Array.isArray(event.Modules)){throw new TypeError(`ShipLoadout.fromLoadout: event.Modules must be an array, received ${describeValue(event.Modules)}`)}const modules=/* @__PURE__ */new Map;const slots=/* @__PURE__ */new Set;for(const module of event.Modules){if(module===null||typeof module!=="object"){throw new TypeError(`ShipLoadout.fromLoadout: event.Modules[] must hold module objects, received ${describeValue(module)}`)}requireString(module.Slot,"ShipLoadout.fromLoadout: module.Slot");requireString(module.Item,"ShipLoadout.fromLoadout: module.Item");if(module.Engineering!==void 0){if(module.Engineering===null||typeof module.Engineering!=="object"){throw new TypeError(`ShipLoadout.fromLoadout: module.Engineering must be an object, received ${describeValue(module.Engineering)}`)}requireStringIfPresent(module.Engineering.BlueprintName,"ShipLoadout.fromLoadout: module.Engineering.BlueprintName");requireStringIfPresent(module.Engineering.ExperimentalEffect,"ShipLoadout.fromLoadout: module.Engineering.ExperimentalEffect");if(module.Engineering.Modifiers!==void 0&&!Array.isArray(module.Engineering.Modifiers)){throw new TypeError(`ShipLoadout.fromLoadout: module.Engineering.Modifiers must be an array, received ${describeValue(module.Engineering.Modifiers)}`)}for(const[index,modifier]of(module.Engineering.Modifiers??[]).entries()){if(modifier===null||typeof modifier!=="object"){throw new TypeError(`ShipLoadout.fromLoadout: module.Engineering.Modifiers[${index}] must be an object, received ${describeValue(modifier)}`)}requireString(modifier.Label,`ShipLoadout.fromLoadout: module.Engineering.Modifiers[${index}].Label`)}}const normalizedSlot=module.Slot.toLowerCase();if(slots.has(normalizedSlot)){throw new TypeError(`ShipLoadout.fromLoadout: duplicate slot "${truncate(module.Slot)}"`)}slots.add(normalizedSlot);modules.set(module.Slot,cloneLoadoutModule(module))}const top={};if(event.ShipName!==void 0)top.ShipName=event.ShipName;if(event.ShipIdent!==void 0)top.ShipIdent=event.ShipIdent;if(event.HullValue!==void 0)top.HullValue=event.HullValue;if(event.ModulesValue!==void 0)top.ModulesValue=event.ModulesValue;if(event.Rebuy!==void 0)top.Rebuy=event.Rebuy;if(event.UnladenMass!==void 0)top.UnladenMass=event.UnladenMass;if(event.CargoCapacity!==void 0)top.CargoCapacity=event.CargoCapacity;if(event.FuelCapacity!==void 0)top.FuelCapacity={...event.FuelCapacity};let invalidatesAggregates=false;const outcomes=[];const defaults=getDefaultLoadout(event.Ship)?.modules??[];let layout;for(const[slot,module]of modules){if(isNonOutfittingSlot(slot)||isBuiltInHullModule(module))continue;const stats=builtInModuleBySymbol(module.Item,"ShipLoadout.fromLoadout: module.Item");const slotKind=parseSlotName(slot)?.kind;const fallback=slotKind==="core"||slotKind==="armour"||slotKind==="cargoHatch"?defaults.find(candidate=>candidate.slot.toLowerCase()===slot.toLowerCase()):void 0;const rejected=fallback!==void 0&&(stats===null||slotKind==="cargoHatch"||fixedMountRejects(event.Ship,layout??=hullLayout(event.Ship),slot,stats));if(stats!==null&&!rejected)continue;if(fallback){modules.set(slot,{Slot:slot,Item:fallback.symbol,...module.On===void 0?{}:{On:module.On},...module.Priority===void 0?{}:{Priority:module.Priority},...module.Health===void 0?{}:{Health:module.Health}});outcomes.push({action:"defaulted",slot:slot,sourceSymbol:module.Item,replacementSymbol:fallback.symbol})}else{modules.delete(slot);outcomes.push({action:"emptied",slot:slot,sourceSymbol:module.Item})}invalidatesAggregates=true}for(const fallback of defaults){const slotKind=parseSlotName(fallback.slot)?.kind;if(slotKind!=="core"&&slotKind!=="armour"&&slotKind!=="cargoHatch"||matchingKeyIn(modules,fallback.slot)!==null){continue}const slot=ownKeyIn(modules,fallback.slot);modules.set(slot,{Slot:slot,Item:fallback.symbol});outcomes.push({action:"defaulted",slot:slot,sourceSymbol:null,replacementSymbol:fallback.symbol});if(slotKind==="core")invalidatesAggregates=true}if(invalidatesAggregates){delete top.ModulesValue;delete top.Rebuy;delete top.UnladenMass;delete top.CargoCapacity;delete top.FuelCapacity}const moduleStats=/* @__PURE__ */new Map;const primitiveModifiers=/* @__PURE__ */new Map;for(const module of modules.values()){const engineering=module.Engineering;const variant=identifyPreEngineeredVariant(module);const catalogueVariantStats=variant?getPreEngineeredStats(variant):null;let variantStats=catalogueVariantStats;const retainsBakedExperimental=variant?.experimental!==void 0&&typeof engineering?.ExperimentalEffect==="string"&&variant.experimental.trim().toLowerCase()===engineering.ExperimentalEffect.trim().toLowerCase();if(variant&&catalogueVariantStats&&!catalogueVariantStats.engineeringLocked&&!retainsBakedExperimental){const{experimental:originalExperimental,...withoutExperimental}=variant;const currentExperimental=engineering?.ExperimentalEffect;const currentVariant=typeof currentExperimental==="string"?{...withoutExperimental,experimental:currentExperimental}:withoutExperimental;variantStats=getPreEngineeredStats(withoutExperimental);primitiveModifiers.set(module.Slot,[...engineering?.Modifiers??[],...getPreEngineeredModifiers(currentVariant)])}if(variantStats)moduleStats.set(module.Slot,cloneModuleStats(variantStats));const guardianFinal=typeof engineering?.BlueprintName==="string"&&isFinalGuardianWeaponEngineering(module.Item,engineering.BlueprintName);if(variantStats?.engineeringLocked||typeof engineering?.BlueprintName!=="string"||!guardianFinal){continue}const normalizedBlueprint=normalizeKey(engineering.BlueprintName,"ShipLoadout.fromLoadout: module.Engineering.BlueprintName");const normalizedExperimental=normalizeKey(engineering.ExperimentalEffect,"ShipLoadout.fromLoadout: module.Engineering.ExperimentalEffect");const variants=getPreEngineeredVariants(module.Item);const exact=variants.find(candidate=>candidate.engineeringLocked===true&&candidate.blueprint.toLowerCase()===normalizedBlueprint&&candidate.grade===engineering.Level&&candidate.experimental?.toLowerCase()===normalizedExperimental);const guardianBase=variants.find(candidate=>candidate.engineeringLocked===true&&candidate.blueprint.toLowerCase()===normalizedBlueprint&&candidate.grade===engineering.Level&&candidate.experimental===void 0);const stats=exact?getPreEngineeredStats(exact):guardianBase&&engineering.ExperimentalEffect!==void 0?getPreEngineeredStats({...guardianBase,experimental:engineering.ExperimentalEffect}):builtInModuleBySymbol(module.Item,"ShipLoadout.fromLoadout: module.Item");if(stats){moduleStats.set(module.Slot,cloneModuleStats({...stats,engineeringLocked:true}))}}return{shipSymbol:event.Ship,modules:modules,moduleStats:moduleStats,primitiveModifiers:primitiveModifiers,top:top,sourcePurchase:sourcePurchaseFromLoadout(event),outcomes:deepFreeze(outcomes)}}var SLOT_KEY="ShipLoadout: slotKey";var requireLoadOptions=(scope,options)=>{for(const field of["fuel","cargo"]){const value=options[field];if(value!==void 0&&(!Number.isFinite(value)||value<0)){throw new RangeError(`${scope}: ${field} must be a finite non-negative number`)}}};var requireEnginesPips=(scope,enginesPips)=>{if(!Number.isFinite(enginesPips)||enginesPips<0||enginesPips>4){throw new RangeError(`${scope}: enginesPips must be a finite number from 0 to 4`)}return enginesPips};var requireSystemsPips=(scope,systemsPips)=>{if(!Number.isFinite(systemsPips)||systemsPips<0||systemsPips>4){throw new RangeError(`${scope}: systemsPips must be a finite number from 0 to 4`)}return systemsPips};var LoadoutEditError=class extends TypeError{code;constraint;params;constructor(message,code,params,constraint){super(message);this.code=code;this.params=deepFreeze(structuredClone(params));if(constraint!==void 0)this.constraint=constraint}};var experimentalEffectUnsupported=(code,params)=>deepFreeze({kind:"unsupported",code:code,params:params});var engineeringNormalizationUnsupported=(code,params)=>deepFreeze({kind:"unsupported",code:code,params:params});var AGGREGATE_STATS=["mass","cargoCapacity","fuelCapacity"];var ShipLoadout=class _ShipLoadout{#ship;#shipSymbol;#modules;#moduleStats;#primitiveModifiers;#top;#sourcePurchase;#importOutcomes;#slotCache=/* @__PURE__ */new Map;#layoutCache;constructor(ship,shipSymbol,modules,top,sourcePurchase=null,moduleStats=/* @__PURE__ */new Map,primitiveModifiers=/* @__PURE__ */new Map,importOutcomes=deepFreeze([])){this.#ship=ship;this.#shipSymbol=shipSymbol;this.#modules=modules;this.#top=top;this.#sourcePurchase=sourcePurchase;this.#moduleStats=moduleStats;this.#primitiveModifiers=primitiveModifiers;this.#importOutcomes=importOutcomes}static fromSlef(input,index=0){const entries=parseSlef(input);const entry=entries[index];if(!entry){throw new TypeError(`ShipLoadout.fromSlef: no entry at index ${truncate(index)} (have ${entries.length})`)}const imported=normalizeLoadoutEvent(entry.data);const ship=getShipBySymbol(imported.shipSymbol);if(!ship){throw new TypeError(`ShipLoadout.fromSlef: unknown hull "${truncate(imported.shipSymbol)}"`)}return _ShipLoadout.#fromImported(imported,ship)}static fromLoadout(event){if(event===null||typeof event!=="object"){throw new TypeError(`ShipLoadout.fromLoadout: event must be a Loadout event, received ${describeValue(event)}`)}const imported=normalizeLoadoutEvent(event);const ship=getShipBySymbol(imported.shipSymbol);if(!ship){throw new TypeError(`ShipLoadout.fromLoadout: unknown hull "${truncate(imported.shipSymbol)}"`)}return _ShipLoadout.#fromImported(imported,ship)}static#fromImported(imported,ship){return new _ShipLoadout(ship,imported.shipSymbol,imported.modules,imported.top,imported.sourcePurchase,imported.moduleStats,imported.primitiveModifiers,imported.outcomes)}static empty(shipSymbol){const requested=requireString(shipSymbol,"ShipLoadout.empty: shipSymbol");const ship=getShipBySymbol(requested);if(!ship){throw new TypeError(`ShipLoadout.empty: no slot layout for hull "${truncate(shipSymbol)}"`)}const fitted=(getDefaultLoadout(ship.symbol)?.modules??[]).filter(module=>{const parsed=parseSlotName(module.slot);return parsed!==null&&fixedSlotReason(parsed)!==null});return new _ShipLoadout(ship,ship.symbol,new Map(fitted.map(module=>[module.slot,{Slot:module.slot,Item:module.symbol}])),{})}static default(shipSymbol){const requested=requireString(shipSymbol,"ShipLoadout.default: shipSymbol");const ship=getShipBySymbol(requested);if(!ship){throw new TypeError(`ShipLoadout.default: no default loadout for hull "${truncate(shipSymbol)}"`)}const loadout=getDefaultLoadout(ship.symbol);return new _ShipLoadout(ship,loadout.symbol,new Map(loadout.modules.map(module=>[module.slot,{Slot:module.slot,Item:module.symbol}])),{})}get shipSymbol(){return this.#shipSymbol}get shipName(){return this.#top.ShipName??null}get shipIdent(){return this.#top.ShipIdent??null}get unladenMass(){return this.#top.UnladenMass??this.#computedUnladenMass()}#computedUnladenMass(){return calculateUnladenMass(this.#ship.hullMass,this.#calculationModules())}get fuelCapacity(){const cap=this.#top.FuelCapacity;if(cap?.Main!==void 0&&cap.Reserve!==void 0){return Object.freeze({main:cap.Main,reserve:cap.Reserve})}const computed=this.#computedFuelCapacity();return Object.freeze({main:cap?.Main??computed.main,reserve:cap?.Reserve??computed.reserve})}get cargoCapacity(){return this.#top.CargoCapacity??this.#computedCargoCapacity()}#computedCargoCapacity(){return calculateCargoCapacity(this.#calculationModules())}#computedFuelCapacity(){return calculateFuelCapacity(this.#ship.reserveFuelCapacity,this.#calculationModules())}get hullValue(){return this.#top.HullValue??null}get modulesValue(){return this.#top.ModulesValue??null}get rebuy(){return this.#top.Rebuy??null}get sourcePurchase(){return this.#sourcePurchase}get importOutcomes(){return this.#importOutcomes}get validation(){const slots=this.#layout();const byKey=new Map(slots.map(slot=>[slot.key.toLowerCase(),slot]));const modules=[...this.#modules.values()].map(module=>{const stats=this.#statsFor(module);const slot=byKey.get(module.Slot.toLowerCase());const builtIn=stats===null&&isNonOutfittingSlot(module.Slot)||isBuiltInHullModule(module);const fitProblem=stats&&slot&&!builtIn?moduleFitProblem(this.#shipSymbol,slot,stats):null;return{slot:module.Slot,symbol:module.Item,requiresKnownSlot:!builtIn,fitError:fitProblem?.message??null,...fitProblem===null?{}:{fitConstraint:fitProblem.constraint},...fitProblem?.params===void 0?{}:{fitParams:fitProblem.params},...stats?.exclusionGroup===void 0?{}:{exclusionGroup:stats.exclusionGroup},...stats?.limitGroup===void 0?{}:{limitGroup:stats.limitGroup},...stats?.limitIncrease===void 0?{}:{limitIncrease:stats.limitIncrease}}});return validateLoadout({shipSymbol:this.#shipSymbol,slots:slots,modules:modules})}slots(kind){const cached=this.#slotCache.get(kind);if(cached!==void 0)return cached;const slots=kind===void 0?this.#layout():this.#layout().filter(slot=>slot.kind===kind);const currentLimits=this.#moduleLimits();const value=deepFreeze(slots.map(slot=>{const stats=this.#moduleStatsAt(slot.key);const fixedReason=fixedSlotReason(slot);const immovableReason=fixedReason!==null?fixedReason:stats?.limitIncrease!==void 0&&this.#moduleLimitRegression(slot.key,null,currentLimits,stats)!==null?"moduleLimit":null;return{...slot,name:loadoutSlotName(slot),module:this.fittedModuleAt(slot.key),removable:immovableReason===null,...immovableReason===null?{}:{immovableReason:immovableReason}}}));this.#slotCache.set(kind,value);return value}fittedModuleAt(slotKey){const module=this.#fittedModuleFor(slotKey);if(!module)return null;const raw=cloneLoadoutModule(module);const stats=this.#statsFor(module);const effective=effectiveModule(this.#moduleForEffectiveStats(module),stats);return deepFreeze({slot:module.Slot,symbol:raw.Item,on:raw.On,priority:raw.Priority,health:raw.Health,value:raw.Value,engineering:raw.Engineering,raw:raw,stats:stats===null?null:cloneModuleStats(stats),effectiveStats:effective===null?null:cloneModuleStats(effective),ammunition:ammunitionCapacity(effective),preEngineeredVariant:identifyPreEngineeredVariant(raw)})}fittedModules(){return deepFreeze([...this.#modules.keys()].flatMap(key=>{const fitted=this.fittedModuleAt(key);return fitted===null?[]:[fitted]}))}availableBlueprints(slotKey){const module=this.#fittedModuleFor(slotKey);return deepFreeze(module?availableBlueprintsFor(module.Item,this.#statsFor(module)):[])}availableExperimentalEffects(slotKey){const module=this.#fittedModuleFor(slotKey);return deepFreeze(module?availableExperimentalsFor(module.Item,this.#statsFor(module)):[])}modulesForSlot(slotKey){const slot=this.#requireSlot(slotKey);const occupied=new Set([...this.#modules.values()].flatMap(fitted=>{if(fitted.Slot.toLowerCase()===slot.key.toLowerCase())return[];const group=this.#statsFor(fitted)?.exclusionGroup;return group===void 0?[]:[group]}));const currentLimits=this.#moduleLimits();const currentStats=this.#moduleStatsAt(slot.key);return ALL_MODULES.filter(module=>moduleFitError(this.#shipSymbol,slot,module)===null&&(module.exclusionGroup===void 0||!occupied.has(module.exclusionGroup))&&this.#moduleLimitRegression(slot.key,module,currentLimits,currentStats)===null)}repairFixedMount(slotKey){const requested=requireString(slotKey,SLOT_KEY);const wanted=requested.toLowerCase();const slot=this.#requireSlot(requested);const fittedKey=this.#fittedKey(requested);const resultSlot=fittedKey??requested;const canonicalKey=slot.key;if(fixedSlotReason(slot)===null){return deepFreeze({status:"refused",slot:resultSlot,reason:"notFixedMount"})}const current=this.#fittedModuleFor(requested);const currentStats=current?this.#statsFor(current):null;const valid=current!==void 0&¤tStats!==null&&(slot.kind==="cargoHatch"?isBuiltInHullModule(current):moduleFitProblem(this.#shipSymbol,slot,currentStats)===null);if(valid){return deepFreeze({status:"unchanged",slot:current.Slot,symbol:current.Item})}const defaultModule=getDefaultLoadout(this.#shipSymbol)?.modules.find(module=>module.slot.toLowerCase()===wanted);if(!defaultModule){return deepFreeze({status:"defaultUnavailable",slot:resultSlot})}const ownKey=ownKeyIn(this.#modules,canonicalKey);const replacement={Slot:ownKey,Item:defaultModule.symbol,...current?.On===void 0?{}:{On:current.On},...current?.Priority===void 0?{}:{Priority:current.Priority},...current?.Health===void 0?{}:{Health:current.Health}};const replacementStats=builtInModuleBySymbol(defaultModule.symbol,"ShipLoadout.repairFixedMount")??(isBuiltInHullModule(replacement)?builtInModuleBySymbol("ModularCargoBayDoor","ShipLoadout.repairFixedMount"):null);if(!replacementStats){return deepFreeze({status:"defaultUnavailable",slot:resultSlot,symbol:defaultModule.symbol})}this.#replaceModule(ownKey,replacement,replacementStats);return deepFreeze({status:"repaired",slot:ownKey,symbol:defaultModule.symbol})}setModule(slotKey,module){const slot=this.#requireSlot(slotKey);if(module===null||module===void 0){throw new TypeError(`ShipLoadout.setModule: no module supplied for "${truncate(slotKey)}" (did the module lookup return undefined?)`)}if(typeof module.symbol!=="string"){throw new TypeError(`ShipLoadout.setModule: module for "${truncate(slotKey)}" must be an outfitting module, received ${describeValue(module)}`)}module=cloneModuleStats(module);const catalogued=builtInModuleBySymbol(module.symbol,FITTED_ITEM);if(catalogued===null){throw new TypeError(`ShipLoadout.setModule: no module is catalogued as "${truncate(module.symbol)}"`)}for(const field of AGGREGATE_STATS){const stated=module[field];if(stated===void 0){if(catalogued[field]===void 0)continue;throw new TypeError(`ShipLoadout.setModule: the supplied record for "${truncate(module.symbol)}" has no ${field}`)}if(typeof stated!=="number"||!Number.isFinite(stated)){throw new TypeError(`ShipLoadout.setModule: the supplied record for "${truncate(module.symbol)}" states a ${field} of ${describeValue(stated)}`)}}const problem2=moduleFitProblem(this.#shipSymbol,slot,module);if(problem2){if(problem2.constraint==="immutableSlot"){throw new LoadoutEditError(`ShipLoadout.setModule: ${truncate(module.symbol)} → ${truncate(slotKey)}: ${problem2.message}`,"immutableSlot",{slot:slot.key})}throw new LoadoutEditError(`ShipLoadout.setModule: ${truncate(module.symbol)} → ${truncate(slotKey)}: ${problem2.message}`,"incompatibleModule",{...problem2.params,slot:slot.key,symbol:module.symbol,constraint:problem2.constraint},problem2.constraint)}if(module.exclusionGroup!==void 0){const conflict=[...this.#modules.values()].find(fitted=>fitted.Slot.toLowerCase()!==slot.key.toLowerCase()&&this.#statsFor(fitted)?.exclusionGroup===module.exclusionGroup);if(conflict){throw new LoadoutEditError(`ShipLoadout.setModule: ${truncate(module.symbol)} → ${truncate(slotKey)}: ${module.exclusionGroup} is limited to one per ship (already fitted in ${truncate(conflict.Slot)})`,"duplicateExclusiveModule",{exclusionGroup:module.exclusionGroup,slot:slot.key,symbol:module.symbol,previousSlot:conflict.Slot,previousSymbol:conflict.Item})}}const limitProblem=this.#moduleLimitRegression(slot.key,module);if(limitProblem!==null){throw new LoadoutEditError(`ShipLoadout.setModule: ${truncate(module.symbol)} → ${truncate(slotKey)}: ${limitProblem.group} would have ${limitProblem.count} modules but the ship allows ${limitProblem.limit}`,"moduleLimitExceeded",{group:limitProblem.group,count:limitProblem.count,limit:limitProblem.limit,slot:slot.key,symbol:module.symbol})}const key=this.#fittedKey(slotKey)??slot.key;this.#replaceModule(key,{Slot:key,Item:module.symbol},module);return this}removeModule(slotKey){const wanted=requireString(slotKey,SLOT_KEY).toLowerCase();if(wanted==="cargohatch"){throw new LoadoutEditError("ShipLoadout.removeModule: the cargoHatch slot cannot be changed","immutableSlot",{slot:"CargoHatch"})}const parsed=parseSlotName(slotKey);const slot=this.#layout().find(candidate=>candidate.key.toLowerCase()===wanted);if(parsed!==null&&fixedSlotReason(parsed)==="requiredSlot"){const fittedKey=this.#fittedKey(slotKey);const key2=slot?.key??fittedKey??slotKey;throw new LoadoutEditError(`ShipLoadout.removeModule: the ${truncate(key2)} slot is required and cannot be emptied`,"requiredSlot",{slot:key2})}const key=this.#fittedKey(slotKey);if(key!==null){const limitProblem=this.#moduleLimitRegression(key,null);if(limitProblem!==null){const fitted=this.#modules.get(key);throw new LoadoutEditError(`ShipLoadout.removeModule: ${truncate(slotKey)}: ${limitProblem.group} would have ${limitProblem.count} modules but the ship allows ${limitProblem.limit}`,"moduleLimitExceeded",{group:limitProblem.group,count:limitProblem.count,limit:limitProblem.limit,slot:key,...fitted===void 0?{}:{symbol:fitted.Item}})}this.#replaceModule(key,null)}return this}applyBlueprint(slotKey,fdname,options){requireString(fdname,"ShipLoadout.applyBlueprint: fdname");if(options===null||typeof options!=="object"){throw new TypeError(`ShipLoadout.applyBlueprint: options must be an object with a grade, received ${describeValue(options)}`)}const wantedGrade=options.grade;const wantedQuality=options.quality;const wantedExperimental=options.experimental??void 0;requireStringIfPresent(wantedExperimental,"ShipLoadout.applyBlueprint: options.experimental");const module=this.#fittedModuleFor(slotKey);if(!module){throw new RangeError(`ShipLoadout.applyBlueprint: slot "${truncate(slotKey)}" is empty`)}const fittedStats=this.#statsFor(module);if(!fittedStats){throw new TypeError(`ShipLoadout.applyBlueprint: no stats for module "${truncate(module.Item)}"`)}const recipe=resolveBlueprintForModule(module.Item,fdname);const named=recipe===fdname?`"${truncate(fdname)}"`:`"${truncate(fdname)}" (${truncate(recipe)} on this module)`;const written=fdname.trim().toLowerCase();const resolved=recipe.trim().toLowerCase();if(getPreEngineeredVariants(module.Item).some(variant=>variant.acquisition==="eventReward"&&(variant.blueprint.toLowerCase()===written||variant.blueprint.toLowerCase()===resolved))){throw new TypeError(`ShipLoadout.applyBlueprint: ${named} is a fixed pre-engineered identity, not a craftable blueprint; use setPreEngineeredVariant to fit its fixed article`)}if(!Number.isInteger(wantedGrade)||wantedGrade<1||wantedGrade>5){throw new RangeError(`ShipLoadout.applyBlueprint: no blueprint ${named} grade ${truncate(wantedGrade)}`)}const grade=getBlueprintGrade(recipe,wantedGrade);if(!grade){throw new RangeError(`ShipLoadout.applyBlueprint: no blueprint ${named} grade ${truncate(wantedGrade)}`)}let experimental;if(wantedExperimental!==void 0){experimental=getExperimentalEffect(wantedExperimental);if(!experimental){throw new RangeError(`ShipLoadout.applyBlueprint: unknown experimental effect "${truncate(wantedExperimental)}"`)}}const quality=wantedQuality??1;if(!Number.isFinite(quality)||quality<0||quality>1){throw new RangeError(`ShipLoadout.applyBlueprint: quality must be a finite number in [0, 1]`)}if(fittedStats.engineeringLocked){throw new TypeError(`ShipLoadout.applyBlueprint: module "${truncate(module.Item)}" is a final pre-engineered article and accepts no further engineering`)}if(!blueprintAvailableFor(module.Item,fdname)){const offered=[...blueprintRoutesFor(module.Item)].map(([blueprint,route])=>`${blueprint} (${route})`);throw new TypeError(offered.length>0?`ShipLoadout.applyBlueprint: module "${truncate(module.Item)}" is not offered blueprint ${named}; available candidates are ${offered.join(", ")}`:`ShipLoadout.applyBlueprint: no registry lists an engineering menu for module "${truncate(module.Item)}"`)}if(wantedExperimental!==void 0&&!experimentalAvailableFor(module.Item,wantedExperimental)){const offered=getExperimentalsForModule(module.Item);throw new TypeError(`ShipLoadout.applyBlueprint: module "${truncate(module.Item)}" is not offered experimental effect "${truncate(wantedExperimental)}"; it takes ${offered.length>0?offered.join(", "):"no experimental effect"}`)}const stats=this.#engineeringBaseStats(module)??fittedStats;const base=baseStats(stats);const canonical=primitiveEngineeringInputsFor(stats,grade,experimental);const missing=missingBaseLabels(stats,base,canonical.grade.features,canonical.experimental?.modifiers);if(missing.length>0){throw new TypeError(`ShipLoadout.applyBlueprint: cannot compute ${named} for module "${truncate(module.Item)}"; missing base stats for ${missing.join(", ")}`)}const damageDistribution=experimental?.damageDistribution??grade.damageDistribution;const primitiveModifiers=computeModifiers(base,canonical.grade,quality,canonical.experimental);const modifiers=journalModifiersFor(stats,primitiveModifiers);if(damageDistribution){for(const type of["kinetic","thermal","explosive","absolute"]){const value=damageDistribution[type];if(value===void 0)continue;const label=labelsForDamageType(type)[0];if(label===void 0)continue;const damageModifier={Label:label,Value:value*scaleForLabel(label),OriginalValue:(stats.damageDistribution?.[type]??0)*scaleForLabel(label)};modifiers.push(damageModifier);primitiveModifiers.push(damageModifier)}}const engineering={BlueprintName:fdname,Level:wantedGrade,Quality:quality,...wantedExperimental!==void 0?{ExperimentalEffect:wantedExperimental}:{},Modifiers:modifiers};this.#replaceModule(module.Slot,{...module,Engineering:engineering},stats,primitiveModifiers);return this}setExperimentalEffect(slotKey,experimental){if(experimental!==null){requireString(experimental,"ShipLoadout.setExperimentalEffect: experimental")}const wanted=experimental;const module=this.#fittedModuleFor(slotKey);if(!module)return experimentalEffectUnsupported("emptySlot",{slot:slotKey});const stats=this.#statsFor(module);if(!stats){return experimentalEffectUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item})}const engineering=module.Engineering;if(!engineering){return experimentalEffectUnsupported("notEngineered",{slot:module.Slot,symbol:module.Item})}if(stats.engineeringLocked){return experimentalEffectUnsupported("finalArticle",{slot:module.Slot,symbol:module.Item})}const previous=engineering.ExperimentalEffect??null;if(previous===null&&wanted===null||previous!==null&&wanted!==null&&previous.trim().toLowerCase()===wanted.trim().toLowerCase()){return deepFreeze({kind:"unchanged",experimental:previous})}const variant=identifyPreEngineeredVariant(module);let effect;if(wanted!==null){effect=getExperimentalEffect(wanted);if(!effect){return experimentalEffectUnsupported("unknownExperimentalEffect",{slot:module.Slot,symbol:module.Item,experimental:wanted})}const restoresBakedEffect=variant?.experimental!==void 0&&variant.experimental.trim().toLowerCase()===wanted.trim().toLowerCase();if(!experimentalAvailableFor(module.Item,wanted)&&!restoresBakedEffect){return experimentalEffectUnsupported("unsupportedExperimentalEffect",{slot:module.Slot,symbol:module.Item,experimental:wanted})}}if(variant&&variant.acquisition!=="mercenary"){const stock=this.#engineeringBaseStats(module);if(!stock){return experimentalEffectUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item})}const missing=missingBaseLabels(stock,baseStats(stock),[],effect?.modifiers);if(missing.length>0){return experimentalEffectUnsupported("unresolvedModifiers",{slot:module.Slot,symbol:module.Item,labels:missing})}const{experimental:originalEffect,...withoutEffect}=variant;const adjusted=wanted===null?withoutEffect:{...withoutEffect,experimental:wanted};const resolved=getPreEngineeredStats(withoutEffect);if(!resolved){return experimentalEffectUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item})}const replacement={BlueprintName:engineering.BlueprintName,Level:engineering.Level,Quality:engineering.Quality,...wanted===null?{}:{ExperimentalEffect:wanted},Modifiers:getPreEngineeredJournalModifiers(adjusted)};this.#replaceModule(module.Slot,{...module,Engineering:replacement},cloneModuleStats(resolved),getPreEngineeredModifiers(adjusted))}else{const blueprint=engineering.BlueprintName;const grade=engineering.Level;const quality=engineering.Quality;if(typeof blueprint!=="string"||!Number.isInteger(grade)||grade<1||grade>5){return experimentalEffectUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item})}const currentEffect=previous===null?void 0:getExperimentalEffect(previous)??null;if(ordinaryEngineeringProof(module.Item,engineering,currentEffect)==="unproven"){return experimentalEffectUnsupported("unidentifiedPreEngineeredVariant",{slot:module.Slot,symbol:module.Item,blueprint:blueprint})}const recipe=resolveBlueprintForModule(module.Item,blueprint);const blueprintGrade=getBlueprintGrade(recipe,grade);if(!blueprintGrade||!blueprintAvailableFor(module.Item,blueprint)||!Number.isFinite(quality)||quality<0||quality>1){return experimentalEffectUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item,blueprint:blueprint,grade:grade})}const base=this.#engineeringBaseStats(module)??stats;const canonical=primitiveEngineeringInputsFor(base,blueprintGrade,effect);const missing=missingBaseLabels(base,baseStats(base),canonical.grade.features,canonical.experimental?.modifiers);if(missing.length>0){return experimentalEffectUnsupported("unresolvedModifiers",{slot:module.Slot,symbol:module.Item,labels:missing})}this.applyBlueprint(module.Slot,blueprint,{grade:grade,quality:quality,...wanted===null?{}:{experimental:wanted}})}return deepFreeze({kind:"updated",previousExperimental:previous,experimental:wanted})}completeEngineeringGrade(slotKey){const module=this.#fittedModuleFor(slotKey);if(!module)return engineeringNormalizationUnsupported("emptySlot",{slot:slotKey});const stats=this.#statsFor(module);if(!stats){return engineeringNormalizationUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item})}const engineering=module.Engineering;if(!engineering){return engineeringNormalizationUnsupported("notEngineered",{slot:module.Slot,symbol:module.Item})}if(stats.engineeringLocked){return engineeringNormalizationUnsupported("finalArticle",{slot:module.Slot,symbol:module.Item})}if(engineering.Quality===1&&engineering.Modifiers!==void 0){return deepFreeze({kind:"unchanged"})}const previousQuality=engineering.Quality;if(!Number.isFinite(previousQuality)||previousQuality<0||previousQuality>1){return engineeringNormalizationUnsupported("invalidQuality",{slot:module.Slot,symbol:module.Item})}const experimental=engineering.ExperimentalEffect??null;const effect=experimental===null?void 0:getExperimentalEffect(experimental)??void 0;if(experimental!==null&&!effect){return engineeringNormalizationUnsupported("unknownExperimentalEffect",{slot:module.Slot,symbol:module.Item,experimental:experimental})}const blueprint=engineering.BlueprintName;const grade=engineering.Level;if(typeof blueprint!=="string"||!Number.isInteger(grade)||grade<1||grade>5){return engineeringNormalizationUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item})}const variant=identifyPreEngineeredVariant(module);const restoresBakedEffect=variant?.experimental!==void 0&&variant.experimental.trim().toLowerCase()===experimental?.trim().toLowerCase();if(experimental!==null&&!experimentalAvailableFor(module.Item,experimental)&&!restoresBakedEffect){return engineeringNormalizationUnsupported("unsupportedExperimentalEffect",{slot:module.Slot,symbol:module.Item,experimental:experimental})}if(variant&&variant.acquisition!=="mercenary"){const stock=this.#engineeringBaseStats(module);if(!stock){return engineeringNormalizationUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item})}const missing=missingBaseLabels(stock,baseStats(stock),[],effect?.modifiers);if(missing.length>0){return engineeringNormalizationUnsupported("unresolvedModifiers",{slot:module.Slot,symbol:module.Item,labels:missing})}const{experimental:originalEffect,...withoutEffect}=variant;const adjusted=experimental===null?withoutEffect:{...withoutEffect,experimental:experimental};const resolved=getPreEngineeredStats(withoutEffect);if(!resolved){return engineeringNormalizationUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item})}const replacement={BlueprintName:engineering.BlueprintName,Level:engineering.Level,Quality:1,...experimental===null?{}:{ExperimentalEffect:experimental},Modifiers:getPreEngineeredJournalModifiers(adjusted)};this.#replaceModule(module.Slot,{...module,Engineering:replacement},cloneModuleStats(resolved),getPreEngineeredModifiers(adjusted))}else{const proof=ordinaryEngineeringProof(module.Item,engineering,effect);if(proof==="unproven"||proof==="proven"&&!blueprintAvailableFor(module.Item,blueprint)){return engineeringNormalizationUnsupported("unidentifiedPreEngineeredVariant",{slot:module.Slot,symbol:module.Item,blueprint:blueprint})}const recipe=resolveBlueprintForModule(module.Item,blueprint);const blueprintGrade=getBlueprintGrade(recipe,grade);if(!blueprintGrade||!blueprintAvailableFor(module.Item,blueprint)){return engineeringNormalizationUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item,blueprint:blueprint,grade:grade})}const base=this.#engineeringBaseStats(module)??stats;const canonical=primitiveEngineeringInputsFor(base,blueprintGrade,effect);const missing=missingBaseLabels(base,baseStats(base),canonical.grade.features,canonical.experimental?.modifiers);if(missing.length>0){return engineeringNormalizationUnsupported("unresolvedModifiers",{slot:module.Slot,symbol:module.Item,labels:missing})}this.applyBlueprint(module.Slot,blueprint,{grade:grade,quality:1,...experimental===null?{}:{experimental:experimental}})}return deepFreeze({kind:"normalized",previousQuality:previousQuality,quality:1})}setPreEngineeredVariant(slotKey,variant){if(variant===null||typeof variant!=="object"){throw new TypeError(`ShipLoadout.setPreEngineeredVariant: variant must be a pre-engineered variant, received ${describeValue(variant)}`)}requireString(variant.symbol,"ShipLoadout.setPreEngineeredVariant: variant.symbol");requireString(variant.blueprint,"ShipLoadout.setPreEngineeredVariant: variant.blueprint");requireString(variant.acquisition,"ShipLoadout.setPreEngineeredVariant: variant.acquisition");requireStringIfPresent(variant.experimental,"ShipLoadout.setPreEngineeredVariant: variant.experimental");const known=getPreEngineeredVariants(variant.symbol).find(candidate=>candidate.blueprint.toLowerCase()===variant.blueprint.toLowerCase()&&candidate.grade===variant.grade&&(candidate.experimental?.toLowerCase()??"")===(variant.experimental?.toLowerCase()??"")&&candidate.acquisition===variant.acquisition);if(!known){throw new RangeError(`ShipLoadout.setPreEngineeredVariant: no catalogued variant "${truncate(variant.blueprint)}" for module "${truncate(variant.symbol)}"`)}const stats=getPreEngineeredStats(known);const unresolved=unresolvedModifiers(known);if(unresolved.length>0){throw new TypeError(`ShipLoadout.setPreEngineeredVariant: cannot resolve "${truncate(variant.blueprint)}" for module "${truncate(variant.symbol)}"; missing base stats for ${unresolved.join(", ")}`)}this.setModule(slotKey,stats);const module=this.#fittedModuleFor(slotKey);const engineering={BlueprintName:known.blueprint,Level:known.grade,Quality:1,...known.experimental===void 0?{}:{ExperimentalEffect:known.experimental},...known.modifiers?.length?{Modifiers:getPreEngineeredJournalModifiers(known)}:{}};this.#replaceModule(module.Slot,{...module,Engineering:engineering},cloneModuleStats(stats),getPreEngineeredModifiers(known));return this}clearEngineering(slotKey){const module=this.#fittedModuleFor(slotKey);if(module&&this.#statsFor(module)?.engineeringLocked){throw new TypeError(`ShipLoadout.clearEngineering: module "${truncate(module.Item)}" is a final pre-engineered article and its engineering cannot be removed`)}if(module?.Engineering){const baseStats2=this.#engineeringBaseStats(module);const bare={Slot:module.Slot,Item:module.Item};if(module.On!==void 0)bare.On=module.On;if(module.Priority!==void 0){bare.Priority=module.Priority}if(module.Health!==void 0)bare.Health=module.Health;if(module.Value!==void 0)bare.Value=module.Value;this.#replaceModule(module.Slot,bare,baseStats2??void 0)}return this}setModuleEnabled(slotKey,on){this.#patchModule(slotKey,{On:on});return this}setModulePriority(slotKey,priority){if(!Number.isInteger(priority)||priority<0||priority>4){throw new RangeError(`ShipLoadout: power priority must be an integer 0-4, got ${truncate(priority)}`)}this.#patchModule(slotKey,{Priority:priority});return this}#patchModule(slotKey,patch){const module=this.#fittedModuleFor(slotKey);if(!module){throw new RangeError(`ShipLoadout: slot "${truncate(slotKey)}" is empty`)}this.#modules.set(module.Slot,cloneLoadoutModule({...module,...patch}));this.#slotCache.clear()}toLoadoutEvent(options={}){const unladenMass=this.#computedUnladenMass();const cargoCapacity=this.#computedCargoCapacity();const fuel=this.#computedFuelCapacity();const maxJumpRange=this.#exportableJumpRange(unladenMass);return exportLoadoutEvent({shipSymbol:this.#shipSymbol,...this.#top.ShipName===void 0?{}:{shipName:this.#top.ShipName},...this.#top.ShipIdent===void 0?{}:{shipIdent:this.#top.ShipIdent},modules:this.#modules,layout:this.#layout(),sourcePurchase:this.#sourcePurchase,retailHullValue:this.#ship.hullCost,unladenMass:unladenMass,cargoCapacity:cargoCapacity,fuelCapacity:fuel,maxJumpRange:maxJumpRange,sourceTotalsVoided:this.#importOutcomes.some(outcome=>outcome.sourceSymbol===null&&parseSlotName(outcome.slot)?.kind==="core"),statsFor:module=>this.#statsFor(module)},options)}toSlef(options){return toSlef(this.toLoadoutEvent(options),options.header)}toSlefString(options){return stringifySlef(this.toSlef(options),{indent:options.indent??0})}#exportableJumpRange(unladenMass){let drive;try{drive=this.#resolveDrive()}catch{return null}if(drive===null)return null;const tank=this.#computedFuelCapacity();return singleJumpRange(unladenMass,Math.min(tank.main,drive.maxFuel),drive)}get frameShiftDrive(){const drive=this.#resolveDrive();if(drive===null)throw new TypeError("ShipLoadout: build has no frame shift drive");return drive}get thrusters(){return fittedThrusterParamsFor([...this.#modules.values()],module=>this.#statsFor(module))}#maxJumpFuel(fsd){return Math.min(this.fuelCapacity.main,fsd.maxFuel)}frameShiftDriveMassFactor(options={}){requireLoadOptions("ShipLoadout.frameShiftDriveMassFactor",options);const fuel=options.fuel??this.fuelCapacity.main;return frameShiftDriveMassFactor(this.#requireMass(options.cargo??0),fuel,this.frameShiftDrive)}maxJumpRange(){const fsd=this.frameShiftDrive;return singleJumpRange(this.#requireMass(0),this.#maxJumpFuel(fsd),fsd)}jumpRange(options={}){requireLoadOptions("ShipLoadout.jumpRange",options);const fsd=this.frameShiftDrive;const fuel=options.fuel??this.fuelCapacity.main;return singleJumpRange(this.#requireMass(options.cargo??0),fuel,fsd)}ladenJumpRange(){return this.jumpRange({cargo:this.cargoCapacity})}fuelPerJump(distance,options={}){requireLoadOptions("ShipLoadout.fuelPerJump",options);const fsd=this.frameShiftDrive;const fuel=options.fuel??this.fuelCapacity.main;return fuelPerJump(distance,this.#requireMass(options.cargo??0),fuel,fsd)}totalRange(options={}){requireLoadOptions("ShipLoadout.totalRange",options);return totalRange(this.#requireMass(options.cargo??0),options.fuel??this.fuelCapacity.main,this.frameShiftDrive)}standardLoadResult(load){if(load!=="maximum"&&load!=="unladen"&&load!=="laden"){throw new RangeError("ShipLoadout.standardLoadResult: load must be 'maximum', 'unladen', or 'laden'")}const fuel=this.fuelCapacity;const cargo=load==="laden"?this.cargoCapacity:0;const mass=load==="maximum"?this.unladenMass:0;const issues=[];let drive=null;let maximumFuel=null;if(load==="maximum"){const fitted=this.#frameShiftDrive()?.module;let driveError=null;try{drive=this.#resolveDrive();maximumFuel=drive?.maxFuel??null}catch(error){if(!(error instanceof Error))throw error;driveError=error}if(maximumFuel===null){issues.push({field:"frameShiftDrive",reason:fitted?"unresolved":"missing",slot:fitted?.Slot??"FrameShiftDrive",...fitted?{symbol:fitted.Item}:{},message:driveError?.message??"FrameShiftDrive: no frame shift drive is fitted",params:fitted?{field:"frameShiftDrive",reason:"unresolved",slot:fitted.Slot,symbol:fitted.Item}:{field:"frameShiftDrive",reason:"missing",slot:"FrameShiftDrive"}})}}if(issues.length>0){return incompleteResult(issues)}const carriedFuel=load==="maximum"?Math.min(fuel.main,maximumFuel):fuel.main;const value=Object.freeze({fuel:carriedFuel,cargo:cargo,mass:this.unladenMass+carriedFuel+cargo});if(load==="maximum"){try{this.jumpRange(value)}catch(error){if(!(error instanceof RangeError))throw error;const fitted=this.#frameShiftDrive()?.module;const field=drive!==null&&(!Number.isFinite(drive.maxFuel)||drive.maxFuel<0)?"frameShiftDrive":!Number.isFinite(value.fuel)||value.fuel<0?"fuelCapacity":!Number.isFinite(mass)||mass<0?"mass":"frameShiftDrive";const driveParams=field==="frameShiftDrive"&&fitted?{slot:fitted.Slot,symbol:fitted.Item}:{};return incompleteResult([{field:field,reason:"invalid",...driveParams,message:error.message,params:{field:field,reason:"invalid",...driveParams}}])}}return completeResult(value)}jumpRangeSummary(){const maximum=this.#require(this.standardLoadResult("maximum"),"maximum load");const unladen=this.#require(this.standardLoadResult("unladen"),"unladen load");const laden=this.#require(this.standardLoadResult("laden"),"laden load");return{max:this.jumpRange(maximum),unladen:this.jumpRange(unladen),laden:this.jumpRange(laden),totalMax:this.totalRange(maximum),totalUnladen:this.totalRange(unladen),totalLaden:this.totalRange(laden)}}powerBudget(){const modules=[...this.#modules.values()];const consumers=[];for(const module of modules){const consumer=powerConsumerFor(module,this.#statsFor(module));if(consumer)consumers.push(consumer)}return powerBudget(powerAvailable(modules,module=>this.#statsFor(module)),consumers)}heatMetrics(){const input=heatInputFor(this.#ship,this.#modulesForEffectiveStats(),this.powerBudget(),module=>this.#statsFor(module));return input?heatMetrics(input):null}mobilityMetrics(options={}){requireEnginesPips("ShipLoadout.mobilityMetrics",options.enginesPips??4);requireLoadOptions("ShipLoadout.mobilityMetrics",options);return this.mobilityMetricsResult(options).value}mobilityMetricsResult(options={}){const enginesPips=requireEnginesPips("ShipLoadout.mobilityMetricsResult",options.enginesPips??4);requireLoadOptions("ShipLoadout.mobilityMetricsResult",options);const input=mobilityInputResultFor(this.#ship,[...this.#modules.values()],()=>this.powerBudget(),()=>{const main=options.fuel??this.#top.FuelCapacity?.Main??this.fuelCapacity.main;return this.#requireMass(options.cargo??0)+main},enginesPips,module=>this.#statsFor(module));if(!input.complete)return input;return completeResult(mobilityMetrics(input.value))}shieldMetrics(options={}){requireSystemsPips("ShipLoadout.shieldMetrics",options.systemsPips??0);return this.shieldMetricsResult(options).value}shieldMetricsResult(options={}){const systemsPips=requireSystemsPips("ShipLoadout.shieldMetricsResult",options.systemsPips??0);const input=shieldInputResultFor(this.#ship,[...this.#modules.values()],()=>this.powerBudget(),systemsPips,module=>this.#statsFor(module));if(!input.complete)return input;return completeResult(shieldMetrics(input.value))}shieldRecovery(options={}){requireSystemsPips("ShipLoadout.shieldRecovery",options.systemsPips??4);return this.shieldRecoveryResult(options).value}shieldRecoveryResult(options={}){const systemsPips=requireSystemsPips("ShipLoadout.shieldRecoveryResult",options.systemsPips??4);const input=shieldRecoveryInputResultFor(this.#ship,[...this.#modules.values()],()=>this.powerBudget(),systemsPips,module=>this.#statsFor(module));if(!input.complete)return input;return completeResult(shieldRecovery(input.value))}cellBanks(){const modules=[...this.#modules.values()];const banks=orderBySlotLayout(cellBankInputsFor(modules,this.powerBudget(),module=>this.#statsFor(module)),this.#layout(),bank=>bank.slot);return cellBankSummary(banks)}buildCost(){const hull=this.#ship.hullCost;let modules=0;let mercCoins=0;const unpriced=[];const materials=[];for(const module of this.#modules.values()){const stats=this.#statsFor(module);if(stats?.cost!==void 0){modules+=stats.cost}else if(stats!==null||!isNonOutfittingSlot(module.Slot)&&!isBuiltInHullModule(module)){unpriced.push({slot:module.Slot,symbol:module.Item})}const variant=identifyPreEngineeredVariant(module);mercCoins+=variant?.mercCoinCost??0;const engineering=module.Engineering;if(!engineering)continue;const grade=engineering.Level;const bought=variant?.grade??0;if(Number.isInteger(grade)&&grade>bought&&grade<=5){const climb=getBlueprintCost(engineering.BlueprintName,grade,bought);if(climb){materials.push(climb.materials);mercCoins+=climb.mercCoins}}const experimental=engineering.ExperimentalEffect;if(experimental!==void 0&&experimental.toLowerCase()!==variant?.experimental?.toLowerCase()){const cost=getExperimentalEffectCost(experimental);if(cost)materials.push(cost)}}return deepFreeze({credits:{total:hull+modules,hull:hull,modules:modules,rebuy:Math.trunc((hull+modules)*.05),unpriced:unpriced},mercCoins:mercCoins,materials:sumMaterials(...materials)})}buildMass(options={}){requireLoadOptions("ShipLoadout.buildMass",options);const hull=this.#ship.hullMass;const modules=calculateUnladenMass(0,this.#calculationModules());const unladen=this.unladenMass;const fuel=options.fuel??this.fuelCapacity.main;const cargo=options.cargo??0;return Object.freeze({hull:hull,modules:modules,unladen:unladen,fuel:fuel,cargo:cargo,total:unladen+fuel+cargo})}armourMetrics(){return armourMetrics(armourInputFor(this.#ship,[...this.#modules.values()],module=>this.#statsFor(module)))}weaponMetrics(){const weapons=[];for(const module of this.#modules.values()){const record=this.#statsFor(module);const stats=weaponStatsFor(this.#moduleForEffectiveStats(module),record);if(!stats)continue;weapons.push({slot:module.Slot,symbol:module.Item,name:record?.name??module.Item,enabled:module.On!==false,metrics:weaponMetrics(stats),ammunition:ammunitionCapacity(stats),...stats.maximumRange===void 0?{}:{maximumRange:stats.maximumRange},...stats.falloffRange===void 0?{}:{falloffRange:stats.falloffRange},...stats.projectileRange===void 0?{}:{projectileRange:{...stats.projectileRange}},...stats.armourPiercing===void 0?{}:{armourPiercing:stats.armourPiercing}})}const orderedWeapons=orderBySlotLayout(weapons,this.#layout(),weapon=>weapon.slot);return{weapons:orderedWeapons,total:sumWeaponMetrics(orderedWeapons.filter(weapon=>weapon.enabled).map(weapon=>weapon.metrics))}}weaponsCapacitorMetrics(options={}){const weaponsPips=options.weaponsPips??4;if(!Number.isFinite(weaponsPips)||weaponsPips<0||weaponsPips>4){throw new RangeError("ShipLoadout.weaponsCapacitorMetrics: weaponsPips must be a finite number from 0 to 4")}return weaponsCapacitorMetrics(weaponsCapacitorInputFor(this.#modulesForEffectiveStats(),weaponsPips,this.powerBudget(),module=>this.#statsFor(module)))}distributorMetrics(options={}){const pips={systemsPips:options.systemsPips??4,enginesPips:options.enginesPips??4,weaponsPips:options.weaponsPips??4};for(const field of["systemsPips","enginesPips","weaponsPips"]){const value=pips[field];if(!Number.isFinite(value)||value<0||value>4){throw new RangeError(`ShipLoadout.distributorMetrics: ${field} must be a finite number from 0 to 4`)}}const input=distributorInputFor(this.#modulesForEffectiveStats(),pips,this.powerBudget(),module=>this.#statsFor(module));return input?distributorMetrics(input):null}#layout(){if(this.#layoutCache===void 0){this.#layoutCache=Object.freeze(enumerateSlots(this.#ship))}return this.#layoutCache}#requireSlot(slotKey){const wanted=requireString(slotKey,SLOT_KEY).toLowerCase();const slot=this.#layout().find(s=>s.key.toLowerCase()===wanted);if(!slot){throw new RangeError(`ShipLoadout: hull "${truncate(this.#shipSymbol)}" has no slot "${truncate(slotKey)}"`)}return slot}#fittedKey(slotKey){return matchingKeyIn(this.#modules,requireString(slotKey,SLOT_KEY))}#fittedModuleFor(slotKey){const key=this.#fittedKey(slotKey);return key===null?void 0:this.#modules.get(key)}#require(result,what){if(result.value===null){throw new TypeError(`ShipLoadout: cannot determine ${what} (${result.issues.map(i=>i.message).join("; ")})`)}return result.value}#requireMass(cargo){return this.unladenMass+cargo}#calculationModules(){return[...this.#modules.values()].map(module=>({mass:this.#moduleMass(module),cargoCapacity:this.#moduleCapacity(module,"CargoCapacity","cargoCapacity"),fuelCapacity:this.#moduleCapacity(module,"FuelCapacity","fuelCapacity")}))}#moduleLimits(){const entries=[...this.#modules.values()].flatMap(module=>{const stats=this.#statsFor(module);return stats===null?[]:[stats]});return calculateModuleLimits(entries)}#moduleStatsAt(slotKey){const fitted=this.#fittedModuleFor(slotKey);return fitted===void 0?null:this.#statsFor(fitted)}#engineeringBaseStats(module){const fitted=this.#statsFor(module);if(!module.Engineering||identifyPreEngineeredVariant(module)===null)return fitted;const stock=builtInModuleBySymbol(module.Item,FITTED_ITEM);if(!stock)return fitted;return fitted?.engineeringLocked?cloneModuleStats({...stock,engineeringLocked:true}):stock}#moduleForEffectiveStats(module){const modifiers=this.#primitiveModifiers.get(module.Slot);if(modifiers===void 0||module.Engineering===void 0)return module;return{...module,Engineering:{...module.Engineering,Modifiers:modifiers}}}#modulesForEffectiveStats(){return[...this.#modules.values()].map(module=>this.#moduleForEffectiveStats(module))}#moduleLimitRegression(slotKey,replacement,current=this.#moduleLimits(),previous=this.#moduleStatsAt(slotKey)){if(previous?.limitGroup===void 0&&previous?.limitIncrease===void 0&&replacement?.limitGroup===void 0&&replacement?.limitIncrease===void 0){return null}for(const usage of current){const count=usage.count-Number(previous?.limitGroup===usage.group)+Number(replacement?.limitGroup===usage.group);const increase=usage.increase-(previous?.limitIncrease?.group===usage.group?previous.limitIncrease.amount:0)+(replacement?.limitIncrease?.group===usage.group?replacement.limitIncrease.amount:0);const limit=usage.baseLimit+increase;const excess=Math.max(0,count-limit);if(excess>usage.excess){return{...usage,increase:increase,limit:limit,count:count,excess:excess}}}return null}#replaceModule(slotKey,replacement,replacementStats,primitiveModifiers){const previous=this.#modules.get(slotKey)??null;this.#adjustImportedFigures(previous,replacement,replacementStats);if(replacement===null){this.#modules.delete(slotKey);this.#moduleStats.delete(slotKey);this.#primitiveModifiers.delete(slotKey)}else{this.#modules.set(slotKey,cloneLoadoutModule(replacement));if(replacementStats!==void 0)this.#moduleStats.set(slotKey,replacementStats);if(primitiveModifiers===void 0)this.#primitiveModifiers.delete(slotKey);else this.#primitiveModifiers.set(slotKey,primitiveModifiers)}this.#slotCache.clear()}#adjustImportedFigures(previous,next,nextStats){if(this.#top.UnladenMass!==void 0){this.#top.UnladenMass+=this.#moduleMass(next,nextStats)-this.#moduleMass(previous)}if(this.#top.CargoCapacity!==void 0){this.#top.CargoCapacity+=this.#moduleCapacity(next,"CargoCapacity","cargoCapacity",nextStats)-this.#moduleCapacity(previous,"CargoCapacity","cargoCapacity")}if(this.#top.FuelCapacity?.Main!==void 0){const reserve=this.#top.FuelCapacity.Reserve;this.#top.FuelCapacity={Main:this.#top.FuelCapacity.Main+this.#moduleCapacity(next,"FuelCapacity","fuelCapacity",nextStats)-this.#moduleCapacity(previous,"FuelCapacity","fuelCapacity"),...reserve===void 0?{}:{Reserve:reserve}}}if(normalizeKey(previous?.Item,FITTED_ITEM)===normalizeKey(next?.Item,FITTED_ITEM)){return}if(previous!==null&&isCargoHatchSlot(previous.Slot)||next!==null&&isCargoHatchSlot(next.Slot)){return}delete this.#top.ModulesValue;delete this.#top.Rebuy}#moduleMass(module,statsOverride){if(module===null)return 0;if(isCargoHatchSlot(module.Slot))return 0;const modified=getLoadoutModifier(module,"Mass");if(modified!==null)return modified;return(statsOverride??this.#statsFor(module))?.mass??0}#moduleCapacity(module,modifierLabel,field,statsOverride){if(module===null)return 0;if(isCargoHatchSlot(module.Slot))return 0;const modified=getLoadoutModifier(module,modifierLabel);if(modified!==null)return modified;return(statsOverride??this.#statsFor(module))?.[field]??0}#frameShiftDrive(){for(const m of this.#modules.values()){const stats=this.#statsFor(m);if(stats?.slot==="frameShiftDrive")return{module:m,stats:stats}}return void 0}#resolveDrive(){const fsd=this.#frameShiftDrive();if(!fsd)return null;const{module:fsdModule,stats:base}=fsd;if(base.fuelMul===void 0||base.fuelPower===void 0){throw new TypeError(`ShipLoadout: the fitted record for frame shift drive "${truncate(fsdModule.Item)}" has no jump constants`)}const optMass=getLoadoutModifier(fsdModule,"FSDOptimalMass")??base.optMass;const maxFuel=getLoadoutModifier(fsdModule,"MaxFuelPerJump")??base.maxFuel;if(optMass===void 0||maxFuel===void 0){const missing=[...optMass===void 0?["optMass"]:[],...maxFuel===void 0?["maxFuel"]:[]];throw new TypeError(`ShipLoadout: the fitted record for frame shift drive "${truncate(fsdModule.Item)}" has no ${missing.join(" or ")}`)}return{optMass:optMass,maxFuel:maxFuel,fuelMul:base.fuelMul,fuelPower:base.fuelPower,jumpBoost:this.#resolveJumpBoost()}}#resolveJumpBoost(){for(const m of this.#modules.values()){const stats=this.#statsFor(m);if(stats?.engineeringGroup!=="fsdBoosters"&&(stats?.jumpBoost===void 0||stats.jumpBoost===0)){continue}if(m.On===false)continue;if(stats?.jumpBoost===void 0){throw new TypeError(`ShipLoadout: the fitted record for FSD booster "${truncate(m.Item)}" has no jumpBoost`)}return stats.jumpBoost}return 0}#statsFor(module){if(module===null)return null;const stats=this.#moduleStats.get(module.Slot)??builtInModuleBySymbol(module.Item,FITTED_ITEM);if(stats)return stats;return isBuiltInHullModule(module)?builtInModuleBySymbol("ModularCargoBayDoor","ShipLoadout: built-in module"):null}};export{LoadoutEditError,ShipLoadout};//# sourceMappingURL=chunk-3BM5BHI3.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/ships/internal/calculation-result.ts","../src/ships/internal/loadout-metrics.ts","../src/ships/internal/loadout-fitting.ts","../src/ships/internal/loadout-export.ts","../src/ships/internal/loadout-import.ts","../src/ships/ship-loadout.ts"],"names":["weaponsCapacitorMetrics","shieldRecovery","cellBankSummary","shieldMetrics","getShipBySymbol","getShipByName","getShipSlots","parseSlef","toSlef","stringifySlef","getLoadoutModifier","sourcePurchaseFromLoadout","getSourceModuleValue","powerBudget","isNonOutfittingSlot","isBuiltInHullModule","cloneLoadoutModule","identifyPreEngineeredVariant","cloneModuleStats","availableBlueprintsFor","availableExperimentalsFor","ownKeyIn","FITTED_ITEM","blueprintAvailableFor","blueprintRoutesFor","experimentalAvailableFor","primitiveEngineeringInputsFor","missingBaseLabels","journalModifiersFor","getPreEngineeredStats","getPreEngineeredJournalModifiers","getPreEngineeredModifiers","ordinaryEngineeringProof","unresolvedModifiers","orderBySlotLayout","matchingKeyIn","isCargoHatchSlot","isFinalGuardianWeaponEngineering","scaleDamageComponents","weaponMetrics","sumWeaponMetrics","combinedRateOfFire","builtInModuleBySymbol","getBulkheadsForShip","getPreEngineeredVariants","singleJumpRange","frameShiftDriveMassFactor","fuelPerJump","totalRange","calculateUnladenMass","calculateCargoCapacity","calculateFuelCapacity","fixedSlotReason","validateLoadout","mobilityMetrics","calculateModuleLimits","ALL_MODULES","CORE_MODULES","distributorMetrics","getExperimentalEffectCost","getExperimentalEffect","heatMetrics","ammunitionCapacity","armourMetrics","getBlueprintCost","baseStats","computeModifiers","labelsForDamageType","scaleForLabel","sumMaterials","fieldForLabel","labelsForField","capabilityValueForLabel","damageTypeForLabel","resolveBlueprintForModule","getExperimentalsForModule","getBlueprintGrade","getDefaultLoadout","loadoutSlotName","parseSlotName","enumerateSlots","SLOT_RESTRICTION_LABELS","normalizeKey","truncate","describeValue","requireString","requireStringIfPresent","deepFreeze","NO_ISSUES","Object","freeze","completeResult","value","complete","issues","incompleteResult","map","issue","params","PREFIX","powerPlant","thrusters","frameShiftDrive","powerDistributor","shieldGenerator","shieldCellBank","shieldBooster","shieldReinforcement","hullReinforcement","moduleReinforcement","startsWithAny","symbol","prefixes","some","prefix","toLowerCase","startsWith","isPowerDistributor","module","stats","slot","Item","isPowerPlant","parsed","Slot","kind","core","isThruster","isFrameShiftDrive","isEnabled","On","priorityOf","Priority","effectiveStat","field","stated","statedModifier","base","label","modified","effectiveCapability","Engineering","Modifiers","modifier","Label","effectiveDamageDistribution","fromEffect","ExperimentalEffect","damageDistribution","distribution","resolved","seen","Set","type","has","add","Value","convertsDamage","modifierRatio","effective","relatedStat","ratio","effectiveModule","merged","fields","keys","key","capability","engineeringGroup","massRatio","minMass","maxMass","performanceRatio","minMultiplier","maxMultiplier","category","normalizeEffectiveWeapon","damageComponents","damage","powerConsumerFor","draw","mounted","priority","enabled","deployedOnly","alwaysPowered","powerAvailable","modules","statsFor","metricIssue","reason","defaultSlot","message","unavailable","powerPlantIssueFor","capacity","Number","isFinite","powerDrawIssueFor","consumer","poweredMetricBudgetFor","getBudget","plantIssue","drawIssue","budget","available","poweredStates","retracted","poweredShieldGeneratorResultFor","powered","mapResistanceFields","read","kineticResistance","thermalResistance","explosiveResistance","causticResistance","resistancesOf","shieldInputFor","ship","systemsPips","generator","boosters","reinforcement","strengthRatio","optMass","Math","max","optMultiplier","push","shieldBoost","hullMass","baseShieldStrength","shieldInputResultFor","fitted","input","thrusterCurveFor","optSpeedMultiplier","speedCurve","minSpeedMultiplier","maxSpeedMultiplier","optRotationMultiplier","rotationCurve","minRotationMultiplier","maxRotationMultiplier","fittedThrusterParamsFor","mobilityInputResultFor","mass","enginesPips","minimumSpeed","maximumSpeed","boost","minPitch","pitch","minRoll","roll","minYaw","yaw","shieldRecoveryInputResultFor","generatorModule","distributor","generatorStats","distributorStats","strength","regenRate","brokenRegenRate","distributorDraw","systemsCapacity","systemsRecharge","weaponsCapacitorInputFor","weaponsPips","weaponsCapacity","weaponsRecharge","sustainedEnergyPerSecond","deployed","weapon","weaponStatsFor","distributorInputFor","pips","enginesCapacity","enginesRecharge","heatInputFor","heatEfficiency","thrusterHeatRate","deployedThrusterHeatRate","fsdHeatRate","weapons","running","heat","heatPerSecond","sustainedHeatPerSecond","heatCapacity","heatDissipation","retractedPowerDraw","poweredDraw","deployedPowerDraw","state","bands","reduce","total","band","min","length","poweredRetracted","poweredDeployed","cellBankInputsFor","banks","ammunition","reinforcementRate","shieldBankReinforcement","cells","spinUp","shieldBankSpinUp","duration","shieldBankDuration","shieldBankHeat","stockBulkhead","variants","name","find","v","endsWith","armourInputFor","reinforcements","moduleReinforcements","bulkhead","hullBoost","moduleProtection","integrity","stock","baseArmour","WEAPON_FIELDS","projectileRange","burstAdjustedRateOfFire","touched","rate","rateOfFire","statedDamagePerSecond","firingFactor","roundsPerShot","maximumRange","falloffRange","MILITARY_PREFIXES","MINING_PREFIXES","CARGO_PREFIXES","RESTRICTED_SLOT_PREFIXES","mining","military","cargo","limpetController","vesselHangar","passenger","planetaryApproachSuite","problem","constraint","restrictionProblem","restriction","moduleSlotProblem","required","restrictedToSlot","moduleFitProblem","shipSymbol","hull","armourHull","armourShipName","armourShipSymbol","shipName","restricted","restrictedToShips","allowedShipNames","labels","index","join","allowedShipSymbols","wrongMount","moduleSlot","requiredCore","isFuelTank","class","size","moduleClass","slotSize","moduleFitError","REBUY_FRACTION","exportLoadoutEvent","options","fromSource","credits","source","sourcePurchase","totals","sourceTotalsVoided","sourceTotalsHold","hullValue","retailHullValue","modulesValue","computedModulesValue","rebuy","trunc","Ship","ShipName","shipIdent","ShipIdent","HullValue","ModulesValue","UnladenMass","unladenMass","CargoCapacity","cargoCapacity","maxJumpRange","MaxJumpRange","FuelCapacity","Main","fuelCapacity","main","Reserve","reserve","Rebuy","Modules","exportModules","ordered","moduleOrder","slotOrderedModules","layout","values","on","explicitPower","sourceModuleValue","moduleValue","Health","sum","cost","SOURCE_ITEM","entry","item","moduleValues","get","captureLoadoutEvent","event","Array","isArray","captureEach","captureModule","capture","captured","health","engineering","captureEngineering","experimental","experimentalLocalised","ExperimentalEffect_Localised","modifiers","BlueprintName","Level","Quality","hullLayout","slots","fixedMountRejects","mount","candidate","normalizeLoadoutEvent","rawEvent","TypeError","Map","entries","normalizedSlot","set","top","invalidatesAggregates","outcomes","defaults","slotKind","fallback","rejected","action","sourceSymbol","replacementSymbol","delete","moduleStats","primitiveModifiers","variant","catalogueVariantStats","variantStats","retainsBakedExperimental","trim","engineeringLocked","originalExperimental","withoutExperimental","currentExperimental","currentVariant","guardianFinal","normalizedBlueprint","normalizedExperimental","exact","blueprint","grade","guardianBase","SLOT_KEY","requireLoadOptions","scope","RangeError","requireEnginesPips","requireSystemsPips","LoadoutEditError","code","constructor","super","this","structuredClone","experimentalEffectUnsupported","engineeringNormalizationUnsupported","AGGREGATE_STATS","ShipLoadout","_ShipLoadout","importOutcomes","slotCache","layoutCache","fromSlef","imported","data","fromImported","fromLoadout","empty","requested","filter","loadout","computedUnladenMass","calculationModules","cap","computed","computedFuelCapacity","computedCargoCapacity","reserveFuelCapacity","validation","byKey","builtIn","fitProblem","requiresKnownSlot","fitError","fitConstraint","fitParams","exclusionGroup","limitGroup","limitIncrease","cached","currentLimits","moduleLimits","moduleStatsAt","fixedReason","immovableReason","moduleLimitRegression","fittedModuleAt","removable","slotKey","fittedModuleFor","raw","moduleForEffectiveStats","effectiveStats","preEngineeredVariant","fittedModules","flatMap","availableBlueprints","availableExperimentalEffects","modulesForSlot","requireSlot","occupied","group","currentStats","repairFixedMount","wanted","fittedKey","resultSlot","canonicalKey","status","current","valid","defaultModule","ownKey","replacement","replacementStats","replaceModule","setModule","catalogued","conflict","previousSlot","previousSymbol","limitProblem","count","limit","removeModule","applyBlueprint","fdname","wantedGrade","wantedQuality","quality","wantedExperimental","fittedStats","recipe","named","written","acquisition","isInteger","offered","route","engineeringBaseStats","canonical","missing","features","damageModifier","OriginalValue","setExperimentalEffect","previous","effect","restoresBakedEffect","originalEffect","withoutEffect","adjusted","currentEffect","blueprintGrade","previousExperimental","completeEngineeringGrade","previousQuality","proof","setPreEngineeredVariant","known","unresolved","clearEngineering","bare","setModuleEnabled","patchModule","setModulePriority","patch","clear","toLoadoutEvent","fuel","exportableJumpRange","hullCost","outcome","header","toSlefString","indent","drive","resolveDrive","tank","maxFuel","maxJumpFuel","fsd","requireMass","jumpRange","ladenJumpRange","distance","standardLoadResult","load","maximumFuel","driveError","error","Error","carriedFuel","driveParams","jumpRangeSummary","maximum","require","unladen","laden","totalMax","totalUnladen","totalLaden","consumers","modulesForEffectiveStats","mobilityMetricsResult","shieldMetricsResult","shieldRecoveryResult","cellBanks","bank","buildCost","mercCoins","unpriced","materials","mercCoinCost","bought","climb","buildMass","record","metrics","armourPiercing","orderedWeapons","s","result","what","i","moduleMass","moduleCapacity","usage","increase","amount","baseLimit","excess","adjustImportedFigures","next","nextStats","statsOverride","modifierLabel","m","fsdModule","fuelMul","fuelPower","jumpBoost","resolveJumpBoost"],"mappings":"O,+sFAeA,IAAMwF,UAAyBC,OAAOC,OAAO,IAatC,SAASC,eAAkBC,OAC9B,OAAOH,OAAOC,OAAO,CAAEE,YAAOC,SAAU,KAAMC,OAAQN,WAC1D,CAGO,SAASO,iBACZD,QAEA,OAAOL,OAAOC,OAAO,CACjBE,MAAO,KACPC,SAAU,MACVC,OAAQL,OAAOC,OACXI,OAAOE,IAAKC,OACRR,OAAOC,OAAO,IACPO,SACCA,MAAMC,OAAS,CAAEA,OAAQT,OAAOC,OAAO,IAAKO,MAAMC,UAAc,CAAA,OAKxF,CCuBA,IAAMC,OAAS,CACXC,WAAY,CAAC,iBAAkB,0BAC/BC,UAAW,CAAC,aAAc,6BAC1BC,gBAAiB,CAAC,kBAClBC,iBAAkB,CAAC,uBAAwB,gCAC3CC,gBAAiB,CAAC,uBAClBC,eAAgB,CAAC,sBACjBC,cAAe,CAAC,qBAChBC,oBAAqB,CAAC,mCACtBC,kBAAmB,CACf,wBACA,gCACA,kCAEJC,oBAAqB,CAAC,0BAA2B,oCAGrD,IAAMC,cAAgB,CAACC,OAAgBC,WACnCA,SAASC,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,GACI,IAAA,MAAWL,KAAKnM,MAAK/T,QAAS4O,SAAU,CACpC,MAAMhT,MAAQmY,MAAK9T,SAAUigB,GAO7B,GACItkB,OAAOiD,mBAAqB,gBAC3BjD,OAAO0kB,iBAAc,GAAa1kB,MAAM0kB,YAAc,GACzD,CACE,QACJ,CACA,GAAIJ,EAAE3jB,KAAO,MAAO,SACpB,GAAIX,OAAO0kB,iBAAc,EAAW,CAChC,MAAM,IAAIpP,UACN,mDAAmD1X,SAAS0mB,EAAEpkB,0BAEtE,CACA,OAAOF,MAAM0kB,SACjB,CACA,OAAO,CACX,CAGA,SAAArgB,CAAUtE,QACN,GAAIA,SAAW,KAAM,OAAO,KAC5B,MAAMC,MACFmY,MAAK7B,YAAa1C,IAAI7T,OAAOM,OAASlF,sBAAsB4E,OAAOG,KAAMnG,aAC7E,GAAIiG,MAAO,OAAOA,MAIlB,OAAOxG,oBAAoBuG,QACrB5E,sBAAsB,sBAAuB,gCAC7C,IACV,UACJ4c,iBAAAS"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{combinedRateOfFire}from"./chunk-LJI7VXJD.js";import{builtInModuleBySymbol,getModuleBySymbol}from"./chunk-LLHGSBPI.js";import{getPreEngineeredVariants}from"./chunk-2VPVZELZ.js";import{ALL_MODULES}from"./chunk-VDVFJXX5.js";import{EXPERIMENTAL_EFFECTS,getExperimentalEffect}from"./chunk-JPBMRJFC.js";import{fieldForLabel,baseStats,computeModifiers,labelsForDamageType,scaleForLabel,preciseModifierValue,capabilityValueForLabel}from"./chunk-DYPOL3CI.js";import{resolveBlueprintForModule}from"./chunk-2TW4ZBI3.js";import{getBlueprintsForModule,getExperimentalsForModule,getEngineeringGroup}from"./chunk-QTZPA2FR.js";import{getBlueprintGrade,getBlueprint,BLUEPRINTS}from"./chunk-Q3QCLNVG.js";import{normalizeKey}from"./chunk-BKWLI44T.js";import{requireStringIfPresent}from"./chunk-PKWVG2JY.js";import{deepFreeze}from"./chunk-DURKO7JU.js";function scaleDamageComponents(components,baseDamage,effectiveDamage){const scale=baseDamage!==void 0&&baseDamage!==0&&effectiveDamage!==void 0?effectiveDamage/baseDamage:1;return{...components.kinetic===void 0?{}:{kinetic:components.kinetic*scale},...components.thermal===void 0?{}:{thermal:components.thermal*scale},...components.explosive===void 0?{}:{explosive:components.explosive*scale},...components.absolute===void 0?{}:{absolute:components.absolute*scale},...components.antiXeno===void 0?{}:{antiXeno:components.antiXeno*scale},...components.unclassified===void 0?{}:{unclassified:components.unclassified.map(value=>value*scale)}}}function fixedModifierFeatures(modifiers){return modifiers.map(modifier=>({label:modifier.label,method:modifier.method,min:modifier.value,max:modifier.value}))}var FITTED_ITEM="ShipLoadout: fitted module Item";function isNonOutfittingSlot(slotKey){return/^(paintjob|shipname\d+|shipid\d+|bobble\d+|decal\d+|shipkit.+|weaponcolour|enginecolour|vesselvoice|shipcockpit|stringlights)$/i.test(slotKey)}function isCargoHatchSlot(slotKey){return slotKey.toLowerCase()==="cargohatch"}function isBuiltInHullModule(module){return isCargoHatchSlot(module.Slot)&&module.Item.toLowerCase().startsWith("modularcargobaydoor")}function cloneLoadoutModule(module){return{Slot:module.Slot,Item:module.Item,...module.On===void 0?{}:{On:module.On},...module.Priority===void 0?{}:{Priority:module.Priority},...module.Health===void 0?{}:{Health:module.Health},...module.Value===void 0?{}:{Value:module.Value},...module.Engineering===void 0?{}:{Engineering:{BlueprintName:module.Engineering.BlueprintName,Level:module.Engineering.Level,Quality:module.Engineering.Quality,...module.Engineering.ExperimentalEffect===void 0?{}:{ExperimentalEffect:module.Engineering.ExperimentalEffect},...module.Engineering.ExperimentalEffect_Localised===void 0?{}:{ExperimentalEffect_Localised:module.Engineering.ExperimentalEffect_Localised},...module.Engineering.Modifiers===void 0?{}:{Modifiers:module.Engineering.Modifiers.map(modifier=>({...modifier}))}}}}}function matchingKeyIn(keyed,slotKey){if(keyed.has(slotKey))return slotKey;const wanted=slotKey.toLowerCase();for(const key of keyed.keys()){if(key.toLowerCase()===wanted)return key}return null}function ownKeyIn(keyed,canonicalKey){return matchingKeyIn(keyed,canonicalKey)??(keyed.size>0&&[...keyed.keys()].every(key=>key===key.toLowerCase())?canonicalKey.toLowerCase():canonicalKey)}function orderBySlotLayout(values,layout,slotOf){const order=new Map(layout.map((slot,index)=>[slot.key.toLowerCase(),index]));return[...values].sort((left,right)=>(order.get(slotOf(left).toLowerCase())??Number.MAX_SAFE_INTEGER)-(order.get(slotOf(right).toLowerCase())??Number.MAX_SAFE_INTEGER))}function cloneModuleStats(module){try{return deepFreeze(structuredClone(module))}catch(error){if(!(error instanceof Error&&error.name==="DataCloneError"))throw error;return deepFreeze({...module,...module.restrictedToShips===void 0?{}:{restrictedToShips:[...module.restrictedToShips]},...module.limitIncrease===void 0?{}:{limitIncrease:{...module.limitIncrease}},...module.damageDistribution===void 0?{}:{damageDistribution:{...module.damageDistribution}},...module.damageComponents===void 0?{}:{damageComponents:{...module.damageComponents,...module.damageComponents.unclassified===void 0?{}:{unclassified:[...module.damageComponents.unclassified]}}},...module.projectileRange===void 0?{}:{projectileRange:{...module.projectileRange}}})}}var GUARDIAN_WEAPON_GROUPS=/* @__PURE__ */new Set(["guardianGauss","guardianPlasma","guardianShard"]);function missingBaseLabels(stats,base,features,experimental){const contributions=[...features,...experimental??[]];return[...new Set(contributions.map(contribution=>contribution.label).filter(label=>{if(base[label]!==void 0)return false;return fieldForLabel(label,stats)===null}))]}function recipeSignature(fdname){const blueprint=getBlueprint(fdname);if(!blueprint)return null;const grades=Object.entries(blueprint.grades).map(([grade,{features:features}])=>`${grade}:${features.map(feature=>`${feature.label}/${feature.method??""}`).sort().join(",")}`).sort().join(";");return`${blueprint.name.toLowerCase()}|${grades}`}var isGenericSpelling=fdname=>fdname.toLowerCase().startsWith("misc_");function isSoldWithBlueprint(item,wanted){return getPreEngineeredVariants(item).some(variant=>variant.acquisition==="mercenary"&&variant.blueprint.toLowerCase()===wanted)}function blueprintRoutesFor(item){const routes=/* @__PURE__ */new Map;for(const fdname of getBlueprintsForModule(item))routes.set(fdname,"ordinary");for(const variant of getPreEngineeredVariants(item)){if(variant.acquisition==="mercenary"&&!routes.has(variant.blueprint)){routes.set(variant.blueprint,"mercenary")}}return routes}function blueprintAvailableFor(item,fdname){const offered=getBlueprintsForModule(item);const asWritten=normalizeKey(fdname,"ShipLoadout.applyBlueprint: fdname");const resolved=resolveBlueprintForModule(item,fdname).trim();const wanted=resolved.toLowerCase();if(offered.some(id=>id.toLowerCase()===wanted))return true;if(isSoldWithBlueprint(item,wanted)||isSoldWithBlueprint(item,asWritten))return true;if(!isGenericSpelling(wanted))return false;const signature=recipeSignature(resolved);if(signature===null)return false;return offered.some(id=>recipeSignature(id)===signature&&!isGenericSpelling(id))}function experimentalAvailableFor(item,fdname){const wanted=normalizeKey(fdname,"ShipLoadout.applyBlueprint: options.experimental");return getExperimentalsForModule(item).some(id=>id.toLowerCase()===wanted)}function primitiveLabelFor(stats,label){if(label==="MaximumRange"&&stats.maximumRange!==void 0)return"Range";if(label==="DamageFalloffRange"&&stats.falloffRange!==void 0){return"FalloffRange"}if(label==="Range"&&stats.scannerRange!==void 0)return"ScannerRange";if(label==="DSS_PatchRadius")return"ProbeRadius";if(label==="FuelScoopRate")return"RefuelRate";if(label==="EnergyPerRegen"&&stats.shieldRegenRate!==void 0){return"DistributorDraw"}return label}function primitiveEngineeringInputsFor(stats,grade,experimental){const canonicalGrade={...grade,features:grade.features.map(feature=>{const label=primitiveLabelFor(stats,feature.label);return label===feature.label?feature:{...feature,label:label}})};if(!experimental)return{grade:canonicalGrade};return{grade:canonicalGrade,experimental:{...experimental,modifiers:experimental.modifiers.map(modifier=>{const label=primitiveLabelFor(stats,modifier.label);return label===modifier.label?modifier:{...modifier,label:label}})}}}function matchesCalculatedModifiers(captured,calculated){if(!captured||captured.length!==calculated.length)return false;const byLabel=new Map(captured.map(modifier=>[modifier.Label.trim().toLowerCase(),modifier]));if(byLabel.size!==captured.length)return false;return calculated.every(expected=>{const actual=byLabel.get(expected.Label.trim().toLowerCase());if(!actual)return false;if(expected.Value!==void 0){return actual.Value!==void 0&&Math.abs(actual.Value-expected.Value)<=1e-5*Math.max(1,Math.abs(expected.Value))}return actual.ValueStr===expected.ValueStr})}function ordinaryEngineeringProof(item,engineering,experimental){const recipe=resolveBlueprintForModule(item,engineering.BlueprintName);const fixedCandidate=getPreEngineeredVariants(item).some(candidate=>candidate.acquisition!=="mercenary"&&candidate.blueprint.trim().toLowerCase()===recipe.trim().toLowerCase());if(!fixedCandidate)return"notFixedCandidate";const grade=getBlueprintGrade(recipe,engineering.Level);const quality=engineering.Quality;const stock=builtInModuleBySymbol(item,FITTED_ITEM);if(!stock||!grade||experimental===null||!Number.isFinite(quality)||quality<0||quality>1){return"unproven"}const current=primitiveEngineeringInputsFor(stock,grade,experimental);if(missingBaseLabels(stock,baseStats(stock),current.grade.features,current.experimental?.modifiers).length>0){return"unproven"}const calculated=journalModifiersFor(stock,computeModifiers(baseStats(stock),current.grade,quality,current.experimental));const damageDistribution=current.experimental?.damageDistribution??current.grade.damageDistribution;if(damageDistribution){for(const type of["kinetic","thermal","explosive","absolute"]){const value=damageDistribution[type];if(value===void 0)continue;const label=labelsForDamageType(type)[0];if(label===void 0)continue;calculated.push({Label:label,Value:value*scaleForLabel(label),OriginalValue:(stock.damageDistribution?.[type]??0)*scaleForLabel(label)})}}return matchesCalculatedModifiers(engineering.Modifiers,calculated)?"proven":"unproven"}var round6=value=>{const rounded=Math.round(value*1e6)/1e6;return Object.is(rounded,-0)?0:rounded};function float32FiringCycle(interval,burstRounds,burstRateOfFire){if(interval<=0)return void 0;const withinBurst=burstRounds>1?Math.fround(Math.fround(burstRounds-1)/Math.fround(burstRateOfFire)):0;const cycle=Math.fround(withinBurst+Math.fround(interval));return cycle>0?cycle:void 0}function float32RateOfFire(interval,burstRounds,burstRateOfFire){const cycle=float32FiringCycle(interval,burstRounds,burstRateOfFire);return cycle===void 0?void 0:Math.fround(Math.fround(burstRounds)/cycle)}function float32DamagePerSecond(damage,rounds,rate,burstRounds,cycle){if(cycle!==void 0&&(rounds!==1||burstRounds!==1)){const damagePerCycle=Math.fround(Math.fround(Math.fround(damage)*Math.fround(rounds))*Math.fround(burstRounds));return Math.fround(damagePerCycle/cycle)}return Math.fround(Math.fround(Math.fround(damage)*Math.fround(rounds))*Math.fround(rate))}var JOURNAL_MODIFIER_ORDER=["CargoCapacity","GuardianModuleResistance","Mass","Integrity","PowerDraw","BootTime","PowerCapacity","HeatEfficiency","FSDOptimalMass","MaxFuelPerJump","FSDHeatRate","EngineOptimalMass","EngineOptPerformance","EngineHeatRate","ShieldGenOptimalMass","ShieldGenStrength","DamagePerSecond","Damage","DistributorDraw","ThermalLoad","ArmourPenetration","MaximumRange","ShotSpeed","RateOfFire","DamageType","$Kinetic;","$Thermal;","$Explosive;","$Absolute;","AmmoClipSize","AmmoMaximum","ReloadTime","Jitter","DamageFalloffRange","DefenceModifierShieldMultiplier","DefenceModifierHealthMultiplier","DefenceModifierHealthAddition","DefenceModifierShieldAddition","RegenRate","BrokenRegenRate","EnergyPerRegen","KineticResistance","ThermicResistance","ExplosiveResistance","CausticResistance","DamageProtection","ModuleDefenceAbsorption","WeaponsCapacity","WeaponsRecharge","EnginesCapacity","EnginesRecharge","SystemsCapacity","SystemsRecharge","ShieldBankSpinUp","ShieldBankDuration","ShieldBankReinforcement","ShieldBankHeat","FSDInterdictorRange","FSDInterdictorFacingLimit","SensorTargetScanAngle","MaxAngle","ScannerTimeToScan","Range","DSS_PatchRadius","FuelScoopRate","FuelCapacity"];var JOURNAL_MODIFIER_RANK=new Map(JOURNAL_MODIFIER_ORDER.map((label,index)=>[label,index]));function sortJournalModifiers(modifiers){return modifiers.map((modifier,index)=>({modifier:modifier,index:index})).sort((a,b)=>(JOURNAL_MODIFIER_RANK.get(a.modifier.Label)??JOURNAL_MODIFIER_ORDER.length)-(JOURNAL_MODIFIER_RANK.get(b.modifier.Label)??JOURNAL_MODIFIER_ORDER.length)||a.index-b.index).map(({modifier:modifier})=>modifier)}function journalModifiersFor(stats,modifiers){const weapon=stats.damage!==void 0;const valueFor=(label,fallback)=>{const modifier=modifiers.find(candidate=>candidate.Label===label);return(modifier&&preciseModifierValue(modifier))??Math.fround(fallback)};const burstTouched=["BurstInterval","BurstSize","BurstRateOfFire"].some(label=>modifiers.some(modifier=>modifier.Label===label));const damageTouched=modifiers.some(modifier=>modifier.Label==="Damage");const rateTouched=burstTouched||modifiers.some(modifier=>modifier.Label==="RateOfFire");let damagePerSecond;let derivedRate;if(weapon&&(damageTouched||rateTouched)){const continuous=stats.burstInterval===void 0&&stats.rateOfFire===void 0;const baseDamage=Math.fround(stats.damage);const effectiveDamage=valueFor("Damage",stats.damage);if(continuous){damagePerSecond={Label:"DamagePerSecond",Value:round6(effectiveDamage),OriginalValue:round6(baseDamage)}}else{const burstRounds=valueFor("BurstSize",stats.burstRounds??1);const burstRate=valueFor("BurstRateOfFire",stats.burstRateOfFire??1);const baseBurstRounds=Math.fround(stats.burstRounds??1);const baseBurstRate=Math.fround(stats.burstRateOfFire??1);const baseInterval=stats.burstInterval===void 0?void 0:Math.fround(stats.burstInterval);const baseCycle=baseInterval===void 0?void 0:float32FiringCycle(baseInterval,baseBurstRounds,baseBurstRate);const baseRate=baseInterval!==void 0?float32RateOfFire(baseInterval,baseBurstRounds,baseBurstRate):stats.rateOfFire===void 0?void 0:Math.fround(stats.rateOfFire);const rateModifier=modifiers.find(modifier=>modifier.Label==="RateOfFire");const effectiveRate=rateModifier&&preciseModifierValue(rateModifier);const effectiveInterval=valueFor("BurstInterval",stats.burstInterval??0);const effectiveCycle=effectiveRate===void 0?float32FiringCycle(effectiveInterval,burstRounds,burstRate):void 0;const rate=effectiveRate??(effectiveCycle===void 0?void 0:Math.fround(Math.fround(burstRounds)/effectiveCycle));if(baseRate!==void 0&&rate!==void 0){const stockRounds=Math.fround(stats.roundsPerShot??1);const effectiveRounds=Math.fround(modifiers.find(modifier=>modifier.Label==="Rounds"||modifier.Label==="RoundsPerShot")?.Value??stockRounds);damagePerSecond={Label:"DamagePerSecond",Value:round6(float32DamagePerSecond(effectiveDamage,effectiveRounds,rate,burstRounds,effectiveCycle)),OriginalValue:round6(float32DamagePerSecond(baseDamage,stockRounds,baseRate,baseBurstRounds,baseCycle))};if(burstTouched){derivedRate={Label:"RateOfFire",Value:round6(rate),OriginalValue:round6(baseRate)}}}}}const result=[];for(const modifier of modifiers){const label=modifier.Label;if(weapon&&["BurstInterval","BurstSize","BurstRateOfFire"].includes(label))continue;if(weapon&&label==="Damage"&&stats.rateOfFire===void 0)continue;let journalLabel=label;if(label==="Range"&&stats.maximumRange!==void 0)journalLabel="MaximumRange";else if(label==="FalloffRange"&&stats.falloffRange!==void 0){journalLabel="DamageFalloffRange"}else if(label==="ScannerRange"&&stats.scannerRange!==void 0){journalLabel="Range"}else if(label==="ProbeRadius")journalLabel="DSS_PatchRadius";else if(label==="RefuelRate")journalLabel="FuelScoopRate";else if(label==="DistributorDraw"&&stats.shieldRegenRate!==void 0){journalLabel="EnergyPerRegen"}result.push(journalLabel===label?modifier:{...modifier,Label:journalLabel})}if(damagePerSecond)result.push(damagePerSecond);if(derivedRate){const direct=result.findIndex(modifier=>modifier.Label==="RateOfFire");if(direct>=0)result[direct]=derivedRate;else result.push(derivedRate)}return sortJournalModifiers(result)}function isFinalGuardianWeaponEngineering(item,blueprint){const group=getEngineeringGroup(item);if(group===null||!GUARDIAN_WEAPON_GROUPS.has(group))return false;const resolved=resolveBlueprintForModule(item,blueprint);return getBlueprint(resolved)!==null&&!blueprintAvailableFor(item,blueprint)}function engineerableBase(item,statsOverride){const stats=statsOverride??builtInModuleBySymbol(item,FITTED_ITEM);if(!stats||stats.engineeringLocked)return null;return{stats:stats,base:baseStats(stats)}}function availableBlueprintsFor(item,statsOverride){const engineerable=engineerableBase(item,statsOverride);if(!engineerable)return[];const{stats:stats,base:base}=engineerable;const available=[];for(const[fdname,route]of blueprintRoutesFor(item)){const blueprint=BLUEPRINTS[fdname];if(!blueprint)continue;const grades=Object.entries(blueprint.grades).filter(([,grade])=>missingBaseLabels(stats,base,grade.features).length===0).map(([grade])=>Number(grade)).filter(Number.isFinite).sort((a,b)=>a-b);if(grades.length>0)available.push({fdname:fdname,grades:grades,route:route})}return available}function availableExperimentalsFor(item,statsOverride){const engineerable=engineerableBase(item,statsOverride);if(!engineerable)return[];const{stats:stats,base:base}=engineerable;return getExperimentalsForModule(item).filter(fdname=>{const effect=EXPERIMENTAL_EFFECTS[fdname];return effect!==void 0&&missingBaseLabels(stats,base,effect.modifiers).length===0})}var MAX_ENGINEERING_GRADE=5;function modifiersWithExperimental(variant,experimental){const module=getModuleBySymbol(variant.symbol,ALL_MODULES);const effectName=experimental===void 0?variant.experimental:experimental;if(!module||!variant.modifiers?.length&&effectName==null)return null;const effect=effectName==null?void 0:getExperimentalEffect(effectName);if(effectName!==null&&effectName!==void 0&&!effect)return null;return computeModifiers(baseStats(module),fixedModifierFeatures(variant.modifiers??[]),1,effect??void 0)}function getPreEngineeredModifiers(variant){return modifiersWithExperimental(variant)??[]}function journalModifiersWithExperimental(variant,experimental){const module=getModuleBySymbol(variant.symbol,ALL_MODULES);if(!module)return[];const modifiers=journalModifiersFor(module,modifiersWithExperimental(variant,experimental)??[]);const effectName=experimental===void 0?variant.experimental:experimental;const damageDistribution=effectName?getExperimentalEffect(effectName)?.damageDistribution:void 0;if(!damageDistribution)return modifiers;for(const type of["kinetic","thermal","explosive","absolute"]){const value=damageDistribution[type];const label=labelsForDamageType(type)[0];if(value===void 0||label===void 0)continue;modifiers.push({Label:label,Value:value*scaleForLabel(label),OriginalValue:(module.damageDistribution?.[type]??0)*scaleForLabel(label)})}return modifiers}function getPreEngineeredJournalModifiers(variant){return journalModifiersWithExperimental(variant)}function sameJournalNumber(actual,expected){return Math.abs(actual-expected)<=Math.max(1e-5,Math.abs(expected)*1e-6)}function modifierKey(modifier,module){return fieldForLabel(modifier.Label,module)??`label:${normalizeKey(modifier.Label,"identifyPreEngineeredVariant: module.Engineering.Modifiers[].Label")}`}function sameModifier(actual,expected){if(expected.Value!==void 0){return actual.Value!==void 0&&sameJournalNumber(actual.Value,expected.Value)}return expected.ValueStr!==void 0&&actual.ValueStr!==void 0}function matchesModifierSignature(actualByKey,expected,module){let matched=0;for(const predicted of expected){const actual=actualByKey.get(modifierKey(predicted,module));if(!actual)continue;if(!sameModifier(actual,predicted))return false;matched++}return matched>=Math.max(1,expected.length-1)}function identifyPreEngineeredVariant(module){const engineering=module.Engineering;if(!engineering)return null;requireStringIfPresent(module.Item,"identifyPreEngineeredVariant: module.Item");const stock=getModuleBySymbol(module.Item,ALL_MODULES);if(!stock)return null;const capturedBlueprint=normalizeKey(engineering.BlueprintName,"identifyPreEngineeredVariant: module.Engineering.BlueprintName");const variants=getPreEngineeredVariants(module.Item);const blueprintMatches=variants.filter(candidate=>candidate.blueprint.toLowerCase()===capturedBlueprint);const blueprintMatch=blueprintMatches.length===1?blueprintMatches[0]:null;const capturedGrade=engineering.Level;if(blueprintMatch?.acquisition==="mercenary"&&Number.isInteger(capturedGrade)&&capturedGrade>=blueprintMatch.grade&&capturedGrade<=MAX_ENGINEERING_GRADE){return blueprintMatch}if(engineering.Modifiers===void 0){const capturedExperimental=normalizeKey(engineering.ExperimentalEffect,"identifyPreEngineeredVariant: module.Engineering.ExperimentalEffect");const identityMatches=blueprintMatches.filter(candidate=>candidate.engineeringLocked===true&&candidate.grade===capturedGrade&&(candidate.experimental===void 0?capturedExperimental===void 0&&engineering.ExperimentalEffect_Localised===void 0:candidate.experimental.toLowerCase()===capturedExperimental));return identityMatches.length===1?identityMatches[0]:null}if(!engineering.Modifiers?.length)return null;const actualByKey=/* @__PURE__ */new Map;for(const modifier of engineering.Modifiers){actualByKey.set(modifierKey(modifier,stock),modifier)}requireStringIfPresent(engineering.ExperimentalEffect,"identifyPreEngineeredVariant: module.Engineering.ExperimentalEffect");const matches=[];for(const candidate of variants){if(!candidate.modifiers?.length)continue;if(candidate.grade!==engineering.Level)continue;if(candidate.acquisition==="eventReward"&&(engineering.ExperimentalEffect!==void 0||engineering.ExperimentalEffect_Localised!==void 0||capturedBlueprint!==candidate.blueprint.toLowerCase())){continue}const primitive=modifiersWithExperimental(candidate,engineering.ExperimentalEffect??null);if(!primitive?.length)continue;const matched=matchesModifierSignature(actualByKey,primitive,stock)||matchesModifierSignature(actualByKey,journalModifiersWithExperimental(candidate,engineering.ExperimentalEffect??null),stock);if(matched)matches.push(candidate)}return matches.length===1?matches[0]:null}function unresolvedModifiers(variant){const resolved=new Set(getPreEngineeredModifiers(variant).map(modifier=>modifier.Label));return(variant.modifiers??[]).map(modifier=>modifier.label).filter(label=>!resolved.has(label))}function getPreEngineeredStats(variant){const module=getModuleBySymbol(variant.symbol,ALL_MODULES);if(!module)return null;if(!variant.modifiers?.length&&!variant.engineeringLocked&&variant.experimental===void 0)return module;const modifiers=variant.modifiers??[];const resolved={...module,...variant.engineeringLocked?{engineeringLocked:true}:{}};for(const{Label:Label,Value:Value,ValueStr:ValueStr}of getPreEngineeredModifiers(variant)){const field=fieldForLabel(Label,module);if(field&&field!=="damageDistribution"&&Value!==void 0){Object.assign(resolved,{[field]:Value/scaleForLabel(Label)})}else if(field&&ValueStr!==void 0&&capabilityValueForLabel(Label)!==null){Object.assign(resolved,{[field]:true})}}const experimentalDamageDistribution=variant.experimental?getExperimentalEffect(variant.experimental)?.damageDistribution:void 0;if(experimentalDamageDistribution){resolved.damageDistribution={...experimentalDamageDistribution};delete resolved.damageComponents}if(resolved.rateOfFire!==void 0&&!modifiers.some(m=>m.label==="RateOfFire")&&modifiers.some(m=>m.label==="BurstSize"||m.label==="BurstRateOfFire"||m.label==="BurstInterval")){const rate=combinedRateOfFire(resolved);if(rate!==void 0)resolved.rateOfFire=rate}if(module.damageComponents&&!experimentalDamageDistribution){resolved.damageComponents=scaleDamageComponents(module.damageComponents,module.damage,resolved.damage)}return resolved}export{FITTED_ITEM,availableBlueprintsFor,availableExperimentalsFor,blueprintAvailableFor,blueprintRoutesFor,cloneLoadoutModule,cloneModuleStats,experimentalAvailableFor,getPreEngineeredJournalModifiers,getPreEngineeredModifiers,getPreEngineeredStats,identifyPreEngineeredVariant,isBuiltInHullModule,isCargoHatchSlot,isFinalGuardianWeaponEngineering,isNonOutfittingSlot,journalModifiersFor,matchingKeyIn,missingBaseLabels,orderBySlotLayout,ordinaryEngineeringProof,ownKeyIn,primitiveEngineeringInputsFor,scaleDamageComponents,unresolvedModifiers};//# sourceMappingURL=chunk-ZZT2PQZ5.js.map
|
|
1
|
+
import{combinedRateOfFire}from"./chunk-LJI7VXJD.js";import{builtInModuleBySymbol,getModuleBySymbol}from"./chunk-PA5EITW5.js";import{getPreEngineeredVariants}from"./chunk-2VPVZELZ.js";import{ALL_MODULES}from"./chunk-QY3L5BKN.js";import{EXPERIMENTAL_EFFECTS,getExperimentalEffect}from"./chunk-JPBMRJFC.js";import{fieldForLabel,baseStats,computeModifiers,labelsForDamageType,scaleForLabel,preciseModifierValue,capabilityValueForLabel}from"./chunk-DYPOL3CI.js";import{resolveBlueprintForModule}from"./chunk-2TW4ZBI3.js";import{getBlueprintsForModule,getExperimentalsForModule,getEngineeringGroup}from"./chunk-QTZPA2FR.js";import{getBlueprintGrade,getBlueprint,BLUEPRINTS}from"./chunk-Q3QCLNVG.js";import{normalizeKey}from"./chunk-BKWLI44T.js";import{requireStringIfPresent}from"./chunk-PKWVG2JY.js";import{deepFreeze}from"./chunk-DURKO7JU.js";function scaleDamageComponents(components,baseDamage,effectiveDamage){const scale=baseDamage!==void 0&&baseDamage!==0&&effectiveDamage!==void 0?effectiveDamage/baseDamage:1;return{...components.kinetic===void 0?{}:{kinetic:components.kinetic*scale},...components.thermal===void 0?{}:{thermal:components.thermal*scale},...components.explosive===void 0?{}:{explosive:components.explosive*scale},...components.absolute===void 0?{}:{absolute:components.absolute*scale},...components.antiXeno===void 0?{}:{antiXeno:components.antiXeno*scale},...components.unclassified===void 0?{}:{unclassified:components.unclassified.map(value=>value*scale)}}}function fixedModifierFeatures(modifiers){return modifiers.map(modifier=>({label:modifier.label,method:modifier.method,min:modifier.value,max:modifier.value}))}var FITTED_ITEM="ShipLoadout: fitted module Item";function isNonOutfittingSlot(slotKey){return/^(paintjob|shipname\d+|shipid\d+|bobble\d+|decal\d+|shipkit.+|weaponcolour|enginecolour|vesselvoice|shipcockpit|stringlights)$/i.test(slotKey)}function isCargoHatchSlot(slotKey){return slotKey.toLowerCase()==="cargohatch"}function isBuiltInHullModule(module){return isCargoHatchSlot(module.Slot)&&module.Item.toLowerCase().startsWith("modularcargobaydoor")}function cloneLoadoutModule(module){return{Slot:module.Slot,Item:module.Item,...module.On===void 0?{}:{On:module.On},...module.Priority===void 0?{}:{Priority:module.Priority},...module.Health===void 0?{}:{Health:module.Health},...module.Value===void 0?{}:{Value:module.Value},...module.Engineering===void 0?{}:{Engineering:{BlueprintName:module.Engineering.BlueprintName,Level:module.Engineering.Level,Quality:module.Engineering.Quality,...module.Engineering.ExperimentalEffect===void 0?{}:{ExperimentalEffect:module.Engineering.ExperimentalEffect},...module.Engineering.ExperimentalEffect_Localised===void 0?{}:{ExperimentalEffect_Localised:module.Engineering.ExperimentalEffect_Localised},...module.Engineering.Modifiers===void 0?{}:{Modifiers:module.Engineering.Modifiers.map(modifier=>({...modifier}))}}}}}function matchingKeyIn(keyed,slotKey){if(keyed.has(slotKey))return slotKey;const wanted=slotKey.toLowerCase();for(const key of keyed.keys()){if(key.toLowerCase()===wanted)return key}return null}function ownKeyIn(keyed,canonicalKey){return matchingKeyIn(keyed,canonicalKey)??(keyed.size>0&&[...keyed.keys()].every(key=>key===key.toLowerCase())?canonicalKey.toLowerCase():canonicalKey)}function orderBySlotLayout(values,layout,slotOf){const order=new Map(layout.map((slot,index)=>[slot.key.toLowerCase(),index]));return[...values].sort((left,right)=>(order.get(slotOf(left).toLowerCase())??Number.MAX_SAFE_INTEGER)-(order.get(slotOf(right).toLowerCase())??Number.MAX_SAFE_INTEGER))}function cloneModuleStats(module){try{return deepFreeze(structuredClone(module))}catch(error){if(!(error instanceof Error&&error.name==="DataCloneError"))throw error;return deepFreeze({...module,...module.restrictedToShips===void 0?{}:{restrictedToShips:[...module.restrictedToShips]},...module.limitIncrease===void 0?{}:{limitIncrease:{...module.limitIncrease}},...module.damageDistribution===void 0?{}:{damageDistribution:{...module.damageDistribution}},...module.damageComponents===void 0?{}:{damageComponents:{...module.damageComponents,...module.damageComponents.unclassified===void 0?{}:{unclassified:[...module.damageComponents.unclassified]}}},...module.projectileRange===void 0?{}:{projectileRange:{...module.projectileRange}}})}}var GUARDIAN_WEAPON_GROUPS=/* @__PURE__ */new Set(["guardianGauss","guardianPlasma","guardianShard"]);function missingBaseLabels(stats,base,features,experimental){const contributions=[...features,...experimental??[]];return[...new Set(contributions.map(contribution=>contribution.label).filter(label=>{if(base[label]!==void 0)return false;return fieldForLabel(label,stats)===null}))]}function recipeSignature(fdname){const blueprint=getBlueprint(fdname);if(!blueprint)return null;const grades=Object.entries(blueprint.grades).map(([grade,{features:features}])=>`${grade}:${features.map(feature=>`${feature.label}/${feature.method??""}`).sort().join(",")}`).sort().join(";");return`${blueprint.name.toLowerCase()}|${grades}`}var isGenericSpelling=fdname=>fdname.toLowerCase().startsWith("misc_");function isSoldWithBlueprint(item,wanted){return getPreEngineeredVariants(item).some(variant=>variant.acquisition==="mercenary"&&variant.blueprint.toLowerCase()===wanted)}function blueprintRoutesFor(item){const routes=/* @__PURE__ */new Map;for(const fdname of getBlueprintsForModule(item))routes.set(fdname,"ordinary");for(const variant of getPreEngineeredVariants(item)){if(variant.acquisition==="mercenary"&&!routes.has(variant.blueprint)){routes.set(variant.blueprint,"mercenary")}}return routes}function blueprintAvailableFor(item,fdname){const offered=getBlueprintsForModule(item);const asWritten=normalizeKey(fdname,"ShipLoadout.applyBlueprint: fdname");const resolved=resolveBlueprintForModule(item,fdname).trim();const wanted=resolved.toLowerCase();if(offered.some(id=>id.toLowerCase()===wanted))return true;if(isSoldWithBlueprint(item,wanted)||isSoldWithBlueprint(item,asWritten))return true;if(!isGenericSpelling(wanted))return false;const signature=recipeSignature(resolved);if(signature===null)return false;return offered.some(id=>recipeSignature(id)===signature&&!isGenericSpelling(id))}function experimentalAvailableFor(item,fdname){const wanted=normalizeKey(fdname,"ShipLoadout.applyBlueprint: options.experimental");return getExperimentalsForModule(item).some(id=>id.toLowerCase()===wanted)}function primitiveLabelFor(stats,label){if(label==="MaximumRange"&&stats.maximumRange!==void 0)return"Range";if(label==="DamageFalloffRange"&&stats.falloffRange!==void 0){return"FalloffRange"}if(label==="Range"&&stats.scannerRange!==void 0)return"ScannerRange";if(label==="DSS_PatchRadius")return"ProbeRadius";if(label==="FuelScoopRate")return"RefuelRate";if(label==="EnergyPerRegen"&&stats.shieldRegenRate!==void 0){return"DistributorDraw"}return label}function primitiveEngineeringInputsFor(stats,grade,experimental){const canonicalGrade={...grade,features:grade.features.map(feature=>{const label=primitiveLabelFor(stats,feature.label);return label===feature.label?feature:{...feature,label:label}})};if(!experimental)return{grade:canonicalGrade};return{grade:canonicalGrade,experimental:{...experimental,modifiers:experimental.modifiers.map(modifier=>{const label=primitiveLabelFor(stats,modifier.label);return label===modifier.label?modifier:{...modifier,label:label}})}}}function matchesCalculatedModifiers(captured,calculated){if(!captured||captured.length!==calculated.length)return false;const byLabel=new Map(captured.map(modifier=>[modifier.Label.trim().toLowerCase(),modifier]));if(byLabel.size!==captured.length)return false;return calculated.every(expected=>{const actual=byLabel.get(expected.Label.trim().toLowerCase());if(!actual)return false;if(expected.Value!==void 0){return actual.Value!==void 0&&Math.abs(actual.Value-expected.Value)<=1e-5*Math.max(1,Math.abs(expected.Value))}return actual.ValueStr===expected.ValueStr})}function ordinaryEngineeringProof(item,engineering,experimental){const recipe=resolveBlueprintForModule(item,engineering.BlueprintName);const fixedCandidate=getPreEngineeredVariants(item).some(candidate=>candidate.acquisition!=="mercenary"&&candidate.blueprint.trim().toLowerCase()===recipe.trim().toLowerCase());if(!fixedCandidate)return"notFixedCandidate";const grade=getBlueprintGrade(recipe,engineering.Level);const quality=engineering.Quality;const stock=builtInModuleBySymbol(item,FITTED_ITEM);if(!stock||!grade||experimental===null||!Number.isFinite(quality)||quality<0||quality>1){return"unproven"}const current=primitiveEngineeringInputsFor(stock,grade,experimental);if(missingBaseLabels(stock,baseStats(stock),current.grade.features,current.experimental?.modifiers).length>0){return"unproven"}const calculated=journalModifiersFor(stock,computeModifiers(baseStats(stock),current.grade,quality,current.experimental));const damageDistribution=current.experimental?.damageDistribution??current.grade.damageDistribution;if(damageDistribution){for(const type of["kinetic","thermal","explosive","absolute"]){const value=damageDistribution[type];if(value===void 0)continue;const label=labelsForDamageType(type)[0];if(label===void 0)continue;calculated.push({Label:label,Value:value*scaleForLabel(label),OriginalValue:(stock.damageDistribution?.[type]??0)*scaleForLabel(label)})}}return matchesCalculatedModifiers(engineering.Modifiers,calculated)?"proven":"unproven"}var round6=value=>{const rounded=Math.round(value*1e6)/1e6;return Object.is(rounded,-0)?0:rounded};function float32FiringCycle(interval,burstRounds,burstRateOfFire){if(interval<=0)return void 0;const withinBurst=burstRounds>1?Math.fround(Math.fround(burstRounds-1)/Math.fround(burstRateOfFire)):0;const cycle=Math.fround(withinBurst+Math.fround(interval));return cycle>0?cycle:void 0}function float32RateOfFire(interval,burstRounds,burstRateOfFire){const cycle=float32FiringCycle(interval,burstRounds,burstRateOfFire);return cycle===void 0?void 0:Math.fround(Math.fround(burstRounds)/cycle)}function float32DamagePerSecond(damage,rounds,rate,burstRounds,cycle){if(cycle!==void 0&&(rounds!==1||burstRounds!==1)){const damagePerCycle=Math.fround(Math.fround(Math.fround(damage)*Math.fround(rounds))*Math.fround(burstRounds));return Math.fround(damagePerCycle/cycle)}return Math.fround(Math.fround(Math.fround(damage)*Math.fround(rounds))*Math.fround(rate))}var JOURNAL_MODIFIER_ORDER=["CargoCapacity","GuardianModuleResistance","Mass","Integrity","PowerDraw","BootTime","PowerCapacity","HeatEfficiency","FSDOptimalMass","MaxFuelPerJump","FSDHeatRate","EngineOptimalMass","EngineOptPerformance","EngineHeatRate","ShieldGenOptimalMass","ShieldGenStrength","DamagePerSecond","Damage","DistributorDraw","ThermalLoad","ArmourPenetration","MaximumRange","ShotSpeed","RateOfFire","DamageType","$Kinetic;","$Thermal;","$Explosive;","$Absolute;","AmmoClipSize","AmmoMaximum","ReloadTime","Jitter","DamageFalloffRange","DefenceModifierShieldMultiplier","DefenceModifierHealthMultiplier","DefenceModifierHealthAddition","DefenceModifierShieldAddition","RegenRate","BrokenRegenRate","EnergyPerRegen","KineticResistance","ThermicResistance","ExplosiveResistance","CausticResistance","DamageProtection","ModuleDefenceAbsorption","WeaponsCapacity","WeaponsRecharge","EnginesCapacity","EnginesRecharge","SystemsCapacity","SystemsRecharge","ShieldBankSpinUp","ShieldBankDuration","ShieldBankReinforcement","ShieldBankHeat","FSDInterdictorRange","FSDInterdictorFacingLimit","SensorTargetScanAngle","MaxAngle","ScannerTimeToScan","Range","DSS_PatchRadius","FuelScoopRate","FuelCapacity"];var JOURNAL_MODIFIER_RANK=new Map(JOURNAL_MODIFIER_ORDER.map((label,index)=>[label,index]));function sortJournalModifiers(modifiers){return modifiers.map((modifier,index)=>({modifier:modifier,index:index})).sort((a,b)=>(JOURNAL_MODIFIER_RANK.get(a.modifier.Label)??JOURNAL_MODIFIER_ORDER.length)-(JOURNAL_MODIFIER_RANK.get(b.modifier.Label)??JOURNAL_MODIFIER_ORDER.length)||a.index-b.index).map(({modifier:modifier})=>modifier)}function journalModifiersFor(stats,modifiers){const weapon=stats.damage!==void 0;const valueFor=(label,fallback)=>{const modifier=modifiers.find(candidate=>candidate.Label===label);return(modifier&&preciseModifierValue(modifier))??Math.fround(fallback)};const burstTouched=["BurstInterval","BurstSize","BurstRateOfFire"].some(label=>modifiers.some(modifier=>modifier.Label===label));const damageTouched=modifiers.some(modifier=>modifier.Label==="Damage");const rateTouched=burstTouched||modifiers.some(modifier=>modifier.Label==="RateOfFire");let damagePerSecond;let derivedRate;if(weapon&&(damageTouched||rateTouched)){const continuous=stats.burstInterval===void 0&&stats.rateOfFire===void 0;const baseDamage=Math.fround(stats.damage);const effectiveDamage=valueFor("Damage",stats.damage);if(continuous){damagePerSecond={Label:"DamagePerSecond",Value:round6(effectiveDamage),OriginalValue:round6(baseDamage)}}else{const burstRounds=valueFor("BurstSize",stats.burstRounds??1);const burstRate=valueFor("BurstRateOfFire",stats.burstRateOfFire??1);const baseBurstRounds=Math.fround(stats.burstRounds??1);const baseBurstRate=Math.fround(stats.burstRateOfFire??1);const baseInterval=stats.burstInterval===void 0?void 0:Math.fround(stats.burstInterval);const baseCycle=baseInterval===void 0?void 0:float32FiringCycle(baseInterval,baseBurstRounds,baseBurstRate);const baseRate=baseInterval!==void 0?float32RateOfFire(baseInterval,baseBurstRounds,baseBurstRate):stats.rateOfFire===void 0?void 0:Math.fround(stats.rateOfFire);const rateModifier=modifiers.find(modifier=>modifier.Label==="RateOfFire");const effectiveRate=rateModifier&&preciseModifierValue(rateModifier);const effectiveInterval=valueFor("BurstInterval",stats.burstInterval??0);const effectiveCycle=effectiveRate===void 0?float32FiringCycle(effectiveInterval,burstRounds,burstRate):void 0;const rate=effectiveRate??(effectiveCycle===void 0?void 0:Math.fround(Math.fround(burstRounds)/effectiveCycle));if(baseRate!==void 0&&rate!==void 0){const stockRounds=Math.fround(stats.roundsPerShot??1);const effectiveRounds=Math.fround(modifiers.find(modifier=>modifier.Label==="Rounds"||modifier.Label==="RoundsPerShot")?.Value??stockRounds);damagePerSecond={Label:"DamagePerSecond",Value:round6(float32DamagePerSecond(effectiveDamage,effectiveRounds,rate,burstRounds,effectiveCycle)),OriginalValue:round6(float32DamagePerSecond(baseDamage,stockRounds,baseRate,baseBurstRounds,baseCycle))};if(burstTouched){derivedRate={Label:"RateOfFire",Value:round6(rate),OriginalValue:round6(baseRate)}}}}}const result=[];for(const modifier of modifiers){const label=modifier.Label;if(weapon&&["BurstInterval","BurstSize","BurstRateOfFire"].includes(label))continue;if(weapon&&label==="Damage"&&stats.rateOfFire===void 0)continue;let journalLabel=label;if(label==="Range"&&stats.maximumRange!==void 0)journalLabel="MaximumRange";else if(label==="FalloffRange"&&stats.falloffRange!==void 0){journalLabel="DamageFalloffRange"}else if(label==="ScannerRange"&&stats.scannerRange!==void 0){journalLabel="Range"}else if(label==="ProbeRadius")journalLabel="DSS_PatchRadius";else if(label==="RefuelRate")journalLabel="FuelScoopRate";else if(label==="DistributorDraw"&&stats.shieldRegenRate!==void 0){journalLabel="EnergyPerRegen"}result.push(journalLabel===label?modifier:{...modifier,Label:journalLabel})}if(damagePerSecond)result.push(damagePerSecond);if(derivedRate){const direct=result.findIndex(modifier=>modifier.Label==="RateOfFire");if(direct>=0)result[direct]=derivedRate;else result.push(derivedRate)}return sortJournalModifiers(result)}function isFinalGuardianWeaponEngineering(item,blueprint){const group=getEngineeringGroup(item);if(group===null||!GUARDIAN_WEAPON_GROUPS.has(group))return false;const resolved=resolveBlueprintForModule(item,blueprint);return getBlueprint(resolved)!==null&&!blueprintAvailableFor(item,blueprint)}function engineerableBase(item,statsOverride){const stats=statsOverride??builtInModuleBySymbol(item,FITTED_ITEM);if(!stats||stats.engineeringLocked)return null;return{stats:stats,base:baseStats(stats)}}function availableBlueprintsFor(item,statsOverride){const engineerable=engineerableBase(item,statsOverride);if(!engineerable)return[];const{stats:stats,base:base}=engineerable;const available=[];for(const[fdname,route]of blueprintRoutesFor(item)){const blueprint=BLUEPRINTS[fdname];if(!blueprint)continue;const grades=Object.entries(blueprint.grades).filter(([,grade])=>missingBaseLabels(stats,base,grade.features).length===0).map(([grade])=>Number(grade)).filter(Number.isFinite).sort((a,b)=>a-b);if(grades.length>0)available.push({fdname:fdname,grades:grades,route:route})}return available}function availableExperimentalsFor(item,statsOverride){const engineerable=engineerableBase(item,statsOverride);if(!engineerable)return[];const{stats:stats,base:base}=engineerable;return getExperimentalsForModule(item).filter(fdname=>{const effect=EXPERIMENTAL_EFFECTS[fdname];return effect!==void 0&&missingBaseLabels(stats,base,effect.modifiers).length===0})}var MAX_ENGINEERING_GRADE=5;function modifiersWithExperimental(variant,experimental){const module=getModuleBySymbol(variant.symbol,ALL_MODULES);const effectName=experimental===void 0?variant.experimental:experimental;if(!module||!variant.modifiers?.length&&effectName==null)return null;const effect=effectName==null?void 0:getExperimentalEffect(effectName);if(effectName!==null&&effectName!==void 0&&!effect)return null;return computeModifiers(baseStats(module),fixedModifierFeatures(variant.modifiers??[]),1,effect??void 0)}function getPreEngineeredModifiers(variant){return modifiersWithExperimental(variant)??[]}function journalModifiersWithExperimental(variant,experimental){const module=getModuleBySymbol(variant.symbol,ALL_MODULES);if(!module)return[];const modifiers=journalModifiersFor(module,modifiersWithExperimental(variant,experimental)??[]);const effectName=experimental===void 0?variant.experimental:experimental;const damageDistribution=effectName?getExperimentalEffect(effectName)?.damageDistribution:void 0;if(!damageDistribution)return modifiers;for(const type of["kinetic","thermal","explosive","absolute"]){const value=damageDistribution[type];const label=labelsForDamageType(type)[0];if(value===void 0||label===void 0)continue;modifiers.push({Label:label,Value:value*scaleForLabel(label),OriginalValue:(module.damageDistribution?.[type]??0)*scaleForLabel(label)})}return modifiers}function getPreEngineeredJournalModifiers(variant){return journalModifiersWithExperimental(variant)}function sameJournalNumber(actual,expected){return Math.abs(actual-expected)<=Math.max(1e-5,Math.abs(expected)*1e-6)}function modifierKey(modifier,module){return fieldForLabel(modifier.Label,module)??`label:${normalizeKey(modifier.Label,"identifyPreEngineeredVariant: module.Engineering.Modifiers[].Label")}`}function sameModifier(actual,expected){if(expected.Value!==void 0){return actual.Value!==void 0&&sameJournalNumber(actual.Value,expected.Value)}return expected.ValueStr!==void 0&&actual.ValueStr!==void 0}function matchesModifierSignature(actualByKey,expected,module){let matched=0;for(const predicted of expected){const actual=actualByKey.get(modifierKey(predicted,module));if(!actual)continue;if(!sameModifier(actual,predicted))return false;matched++}return matched>=Math.max(1,expected.length-1)}function identifyPreEngineeredVariant(module){const engineering=module.Engineering;if(!engineering)return null;requireStringIfPresent(module.Item,"identifyPreEngineeredVariant: module.Item");const stock=getModuleBySymbol(module.Item,ALL_MODULES);if(!stock)return null;const capturedBlueprint=normalizeKey(engineering.BlueprintName,"identifyPreEngineeredVariant: module.Engineering.BlueprintName");const variants=getPreEngineeredVariants(module.Item);const blueprintMatches=variants.filter(candidate=>candidate.blueprint.toLowerCase()===capturedBlueprint);const blueprintMatch=blueprintMatches.length===1?blueprintMatches[0]:null;const capturedGrade=engineering.Level;if(blueprintMatch?.acquisition==="mercenary"&&Number.isInteger(capturedGrade)&&capturedGrade>=blueprintMatch.grade&&capturedGrade<=MAX_ENGINEERING_GRADE){return blueprintMatch}if(engineering.Modifiers===void 0){const capturedExperimental=normalizeKey(engineering.ExperimentalEffect,"identifyPreEngineeredVariant: module.Engineering.ExperimentalEffect");const identityMatches=blueprintMatches.filter(candidate=>candidate.engineeringLocked===true&&candidate.grade===capturedGrade&&(candidate.experimental===void 0?capturedExperimental===void 0&&engineering.ExperimentalEffect_Localised===void 0:candidate.experimental.toLowerCase()===capturedExperimental));return identityMatches.length===1?identityMatches[0]:null}if(!engineering.Modifiers?.length)return null;const actualByKey=/* @__PURE__ */new Map;for(const modifier of engineering.Modifiers){actualByKey.set(modifierKey(modifier,stock),modifier)}requireStringIfPresent(engineering.ExperimentalEffect,"identifyPreEngineeredVariant: module.Engineering.ExperimentalEffect");const matches=[];for(const candidate of variants){if(!candidate.modifiers?.length)continue;if(candidate.grade!==engineering.Level)continue;if(candidate.acquisition==="eventReward"&&(engineering.ExperimentalEffect!==void 0||engineering.ExperimentalEffect_Localised!==void 0||capturedBlueprint!==candidate.blueprint.toLowerCase())){continue}const primitive=modifiersWithExperimental(candidate,engineering.ExperimentalEffect??null);if(!primitive?.length)continue;const matched=matchesModifierSignature(actualByKey,primitive,stock)||matchesModifierSignature(actualByKey,journalModifiersWithExperimental(candidate,engineering.ExperimentalEffect??null),stock);if(matched)matches.push(candidate)}return matches.length===1?matches[0]:null}function unresolvedModifiers(variant){const resolved=new Set(getPreEngineeredModifiers(variant).map(modifier=>modifier.Label));return(variant.modifiers??[]).map(modifier=>modifier.label).filter(label=>!resolved.has(label))}function getPreEngineeredStats(variant){const module=getModuleBySymbol(variant.symbol,ALL_MODULES);if(!module)return null;if(!variant.modifiers?.length&&!variant.engineeringLocked&&variant.experimental===void 0)return module;const modifiers=variant.modifiers??[];const resolved={...module,...variant.engineeringLocked?{engineeringLocked:true}:{}};for(const{Label:Label,Value:Value,ValueStr:ValueStr}of getPreEngineeredModifiers(variant)){const field=fieldForLabel(Label,module);if(field&&field!=="damageDistribution"&&Value!==void 0){Object.assign(resolved,{[field]:Value/scaleForLabel(Label)})}else if(field&&ValueStr!==void 0&&capabilityValueForLabel(Label)!==null){Object.assign(resolved,{[field]:true})}}const experimentalDamageDistribution=variant.experimental?getExperimentalEffect(variant.experimental)?.damageDistribution:void 0;if(experimentalDamageDistribution){resolved.damageDistribution={...experimentalDamageDistribution};delete resolved.damageComponents}if(resolved.rateOfFire!==void 0&&!modifiers.some(m=>m.label==="RateOfFire")&&modifiers.some(m=>m.label==="BurstSize"||m.label==="BurstRateOfFire"||m.label==="BurstInterval")){const rate=combinedRateOfFire(resolved);if(rate!==void 0)resolved.rateOfFire=rate}if(module.damageComponents&&!experimentalDamageDistribution){resolved.damageComponents=scaleDamageComponents(module.damageComponents,module.damage,resolved.damage)}return resolved}export{FITTED_ITEM,availableBlueprintsFor,availableExperimentalsFor,blueprintAvailableFor,blueprintRoutesFor,cloneLoadoutModule,cloneModuleStats,experimentalAvailableFor,getPreEngineeredJournalModifiers,getPreEngineeredModifiers,getPreEngineeredStats,identifyPreEngineeredVariant,isBuiltInHullModule,isCargoHatchSlot,isFinalGuardianWeaponEngineering,isNonOutfittingSlot,journalModifiersFor,matchingKeyIn,missingBaseLabels,orderBySlotLayout,ordinaryEngineeringProof,ownKeyIn,primitiveEngineeringInputsFor,scaleDamageComponents,unresolvedModifiers};//# sourceMappingURL=chunk-6BO5JJNI.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var requireFiniteNonNegative=(scope,name,value)=>{if(!Number.isFinite(value)||value<0){throw new RangeError(`${scope}: ${name} must be a finite non-negative number`)}};var requireFiniteRange=(scope,name,value,minimum,maximum)=>{if(!Number.isFinite(value)||value<minimum||value>maximum){throw new RangeError(`${scope}: ${name} must be a finite number from ${minimum} to ${maximum}`)}};var validateCurve=(scope,curve)=>{for(const field of["minMass","optMass","maxMass"]){requireFiniteNonNegative(scope,field,curve[field])}const allMassesEqual=curve.minMass===curve.optMass&&curve.optMass===curve.maxMass;if(!allMassesEqual&&!(curve.minMass<curve.optMass&&curve.optMass<curve.maxMass)){throw new RangeError(`${scope}: masses must be strictly ordered minMass < optMass < maxMass, or all equal`)}for(const field of["minMultiplier","optMultiplier","maxMultiplier"]){requireFiniteNonNegative(scope,field,curve[field])}const allMultipliersEqual=curve.minMultiplier===curve.optMultiplier&&curve.optMultiplier===curve.maxMultiplier;const strictlyOrderedMultipliers=curve.minMultiplier<curve.optMultiplier&&curve.optMultiplier<curve.maxMultiplier;if(!allMultipliersEqual&&!strictlyOrderedMultipliers){throw new RangeError(`${scope}: multipliers must be strictly ordered minMultiplier < optMultiplier < maxMultiplier, or all equal`)}if(allMassesEqual&&!allMultipliersEqual){throw new RangeError(`${scope}: an all-equal mass curve must have equal multipliers`)}};var curveMultiplier=(scope,mass,thrusters)=>{requireFiniteNonNegative(scope,"mass",mass);validateCurve(`${scope}: thrusters`,thrusters);if(mass>thrusters.maxMass)return 0;const span=thrusters.maxMass-thrusters.minMass;if(span<=0||thrusters.maxMultiplier===thrusters.minMultiplier){return thrusters.optMultiplier}const normalised=Math.max(0,Math.min(1,(thrusters.maxMass-mass)/span));const optNormalised=Math.min(1,(thrusters.maxMass-thrusters.optMass)/span);const exponent=Math.log((thrusters.optMultiplier-thrusters.minMultiplier)/(thrusters.maxMultiplier-thrusters.minMultiplier))/Math.log(optNormalised);if(!Number.isFinite(exponent)){throw new RangeError(`${scope}: curve values do not produce a finite exponent`)}return thrusters.minMultiplier+Math.pow(normalised,exponent)*(thrusters.maxMultiplier-thrusters.minMultiplier)};function thrusterMassCurveMultiplier(mass,thrusters){return curveMultiplier("thrusterMassCurveMultiplier",mass,thrusters)}function mobilityMetrics(input){const pips=input.enginesPips??4;requireFiniteRange("mobilityMetrics","enginesPips",pips,0,4);for(const field of["minimumSpeed","maximumSpeed","boost","pitch","roll","yaw","mass"]){requireFiniteNonNegative("mobilityMetrics",field,input[field])}if(input.minimumSpeed>input.maximumSpeed){throw new RangeError("mobilityMetrics: minimumSpeed must not exceed maximumSpeed")}for(const[minimum,maximum]of[["minPitch","pitch"],["minRoll","roll"],["minYaw","yaw"]]){requireFiniteRange("mobilityMetrics",minimum,input[minimum],0,input[maximum])}if(!input.thrusters)return null;validateCurve("mobilityMetrics: thrusters",input.thrusters);const massCurveMultiplier=curveMultiplier("mobilityMetrics: speed curve",input.mass,input.thrusters.speedCurve??input.thrusters);const rotationMassCurveMultiplier=curveMultiplier("mobilityMetrics: rotation curve",input.mass,input.thrusters.rotationCurve??input.thrusters);const pipMultiplier=pips/4;const speedAtPips=input.minimumSpeed+(input.maximumSpeed-input.minimumSpeed)*pipMultiplier;const handlingAtPips=(maximum,minimum)=>minimum+(maximum-minimum)*pipMultiplier;return{speed:speedAtPips*massCurveMultiplier,boost:input.boost*massCurveMultiplier,pitch:handlingAtPips(input.pitch,input.minPitch)*rotationMassCurveMultiplier,roll:handlingAtPips(input.roll,input.minRoll)*rotationMassCurveMultiplier,yaw:handlingAtPips(input.yaw,input.minYaw)*rotationMassCurveMultiplier,massCurveMultiplier:massCurveMultiplier,rotationMassCurveMultiplier:rotationMassCurveMultiplier}}export{mobilityMetrics,thrusterMassCurveMultiplier};//# sourceMappingURL=chunk-
|
|
1
|
+
var requireFiniteNonNegative=(scope,name,value)=>{if(!Number.isFinite(value)||value<0){throw new RangeError(`${scope}: ${name} must be a finite non-negative number`)}};var requireFiniteRange=(scope,name,value,minimum,maximum)=>{if(!Number.isFinite(value)||value<minimum||value>maximum){throw new RangeError(`${scope}: ${name} must be a finite number from ${minimum} to ${maximum}`)}};var validateCurve=(scope,curve)=>{for(const field of["minMass","optMass","maxMass"]){requireFiniteNonNegative(scope,field,curve[field])}const allMassesEqual=curve.minMass===curve.optMass&&curve.optMass===curve.maxMass;if(!allMassesEqual&&!(curve.minMass<curve.optMass&&curve.optMass<curve.maxMass)){throw new RangeError(`${scope}: masses must be strictly ordered minMass < optMass < maxMass, or all equal`)}for(const field of["minMultiplier","optMultiplier","maxMultiplier"]){requireFiniteNonNegative(scope,field,curve[field])}const allMultipliersEqual=curve.minMultiplier===curve.optMultiplier&&curve.optMultiplier===curve.maxMultiplier;const strictlyOrderedMultipliers=curve.minMultiplier<curve.optMultiplier&&curve.optMultiplier<curve.maxMultiplier;if(!allMultipliersEqual&&!strictlyOrderedMultipliers){throw new RangeError(`${scope}: multipliers must be strictly ordered minMultiplier < optMultiplier < maxMultiplier, or all equal`)}if(allMassesEqual&&!allMultipliersEqual){throw new RangeError(`${scope}: an all-equal mass curve must have equal multipliers`)}};var curveMultiplier=(scope,mass,thrusters)=>{requireFiniteNonNegative(scope,"mass",mass);validateCurve(`${scope}: thrusters`,thrusters);if(mass>thrusters.maxMass)return 0;const span=thrusters.maxMass-thrusters.minMass;if(span<=0||thrusters.maxMultiplier===thrusters.minMultiplier){return thrusters.optMultiplier}const normalised=Math.max(0,Math.min(1,(thrusters.maxMass-mass)/span));const optNormalised=Math.min(1,(thrusters.maxMass-thrusters.optMass)/span);const exponent=Math.log((thrusters.optMultiplier-thrusters.minMultiplier)/(thrusters.maxMultiplier-thrusters.minMultiplier))/Math.log(optNormalised);if(!Number.isFinite(exponent)){throw new RangeError(`${scope}: curve values do not produce a finite exponent`)}return thrusters.minMultiplier+Math.pow(normalised,exponent)*(thrusters.maxMultiplier-thrusters.minMultiplier)};function thrusterMassCurveMultiplier(mass,thrusters){return curveMultiplier("thrusterMassCurveMultiplier",mass,thrusters)}function mobilityMetrics(input){const pips=input.enginesPips??4;requireFiniteRange("mobilityMetrics","enginesPips",pips,0,4);for(const field of["minimumSpeed","maximumSpeed","boost","pitch","roll","yaw","mass"]){requireFiniteNonNegative("mobilityMetrics",field,input[field])}if(input.minimumSpeed>input.maximumSpeed){throw new RangeError("mobilityMetrics: minimumSpeed must not exceed maximumSpeed")}for(const[minimum,maximum]of[["minPitch","pitch"],["minRoll","roll"],["minYaw","yaw"]]){requireFiniteRange("mobilityMetrics",minimum,input[minimum],0,input[maximum])}if(!input.thrusters)return null;validateCurve("mobilityMetrics: thrusters",input.thrusters);const massCurveMultiplier=curveMultiplier("mobilityMetrics: speed curve",input.mass,input.thrusters.speedCurve??input.thrusters);const rotationMassCurveMultiplier=curveMultiplier("mobilityMetrics: rotation curve",input.mass,input.thrusters.rotationCurve??input.thrusters);const pipMultiplier=pips/4;const speedAtPips=input.minimumSpeed+(input.maximumSpeed-input.minimumSpeed)*pipMultiplier;const handlingAtPips=(maximum,minimum)=>minimum+(maximum-minimum)*pipMultiplier;return{loadedMass:input.mass,speed:speedAtPips*massCurveMultiplier,boost:input.boost*massCurveMultiplier,pitch:handlingAtPips(input.pitch,input.minPitch)*rotationMassCurveMultiplier,roll:handlingAtPips(input.roll,input.minRoll)*rotationMassCurveMultiplier,yaw:handlingAtPips(input.yaw,input.minYaw)*rotationMassCurveMultiplier,massCurveMultiplier:massCurveMultiplier,rotationMassCurveMultiplier:rotationMassCurveMultiplier}}export{mobilityMetrics,thrusterMassCurveMultiplier};//# sourceMappingURL=chunk-CX7B67OI.js.map
|