diff --git a/api/src/lib/ancientRunicLeatherStirrupLeathersBench.ts b/api/src/lib/ancientRunicLeatherStirrupLeathersBench.ts new file mode 100644 index 00000000..3813639b --- /dev/null +++ b/api/src/lib/ancientRunicLeatherStirrupLeathersBench.ts @@ -0,0 +1,261 @@ +import crypto from "node:crypto"; + +/** + * Ancient Runic Leather Stirrup Leathers Bench, Mithril Tread Iron & Valkyrie Aerial Rig Engine for OpenAO MMORPG. + * Simulates stirrup strap stitching benches and tread iron shaping rigs (Ash Stirrup Leather Bench, Runic Ironwood Knight Rig, Celestial Void Valkyrie Aerial Sanctum), + * raw tanned heavy buffalo stirrup straps and tempered mithril tread iron sets (Tanned Heavy Buffalo Stirrup Strap, Tempered Mithril Tread Iron Set, Celestial Void Starlight Valkyrie Leather), + * novice mounted stirrup leathers and celestial sovereign aerial stirrup recipes (Novice Mounted Stirrup Leather, Warmaster Mithril Tread Stirrup, Celestial Void Valkyrie Aerial Stirrup), + * independent rider balance & posture stability ratings (scaled across catalog baselines ~14% to 100%), calibrated clamped rider weight distribution bonus and clamped lance shock absorption mitigation scaling, + * upfront leather material deduction on all craft attempts, consistent remainingProvidedLeathers return shapes across all paths, immutable bench cloning for safe rollbacks on both craft and maintain operations, cached static catalog maxima, crypto-secure default gameplay rolls strictly in [0, 1), authoritative catalog power ratio without dead instance fields, and stirrup leathers bench maintenance. + */ + +export type StirrupLeathersBenchType = "ASH_STIRRUP_LEATHER_BENCH" | "RUNIC_IRONWOOD_KNIGHT_RIG" | "CELESTIAL_VOID_VALKYRIE_AERIAL_SANCTUM"; +export type RawLeatherStirrupLeathersType = "TANNED_HEAVY_BUFFALO_STIRRUP_STRAP" | "TEMPERED_MITHRIL_TREAD_IRON_SET" | "CELESTIAL_VOID_STARLIGHT_VALKYRIE_LEATHER"; +export type StirrupLeathersRecipeType = "NOVICE_MOUNTED_STIRRUP_LEATHER" | "WARMASTER_MITHRIL_TREAD_STIRRUP" | "CELESTIAL_VOID_VALKYRIE_AERIAL_STIRRUP"; + +export interface StirrupLeathersBenchData { + benchType: StirrupLeathersBenchType; + maxDurability: number; + leathercraftPower: number; + baseSuccessRatePercent: number; // 0 to 100 + balanceBonusPercent: number; +} + +export interface StirrupLeathersRecipeData { + recipeType: StirrupLeathersRecipeType; + requiredLeatherType: RawLeatherStirrupLeathersType; + requiredLeatherCount: number; + baseRiderWeightDistributionBonusPercent: number; + baseLanceShockAbsorptionMitigationPercent: number; +} + +export interface ActiveStirrupLeathersBench { + benchId: string; + leatherworkerPlayerId: string; + benchType: StirrupLeathersBenchType; + currentDurability: number; + maxDurability: number; + isFunctional: boolean; +} + +export interface CraftedStirrupLeathers { + stirrupId: string; + recipeType: StirrupLeathersRecipeType; + finalRiderWeightDistributionBonusPercent: number; + finalLanceShockAbsorptionMitigationPercent: number; + riderBalancePercent: number; // Scaled rating (clamped 0 to 100%, with catalog bench baselines ~14% to 100%) + consumedLeatherCount: number; + consumedLeatherType: RawLeatherStirrupLeathersType; + remainingProvidedLeathers: RawLeatherStirrupLeathersType[]; + craftedEpochMs: number; +} + +export const STIRRUP_LEATHERS_BENCH_CATALOG: Record = { + ASH_STIRRUP_LEATHER_BENCH: { benchType: "ASH_STIRRUP_LEATHER_BENCH", maxDurability: 85, leathercraftPower: 25, baseSuccessRatePercent: 85, balanceBonusPercent: 10 }, + RUNIC_IRONWOOD_KNIGHT_RIG: { benchType: "RUNIC_IRONWOOD_KNIGHT_RIG", maxDurability: 190, leathercraftPower: 65, baseSuccessRatePercent: 92, balanceBonusPercent: 20 }, + CELESTIAL_VOID_VALKYRIE_AERIAL_SANCTUM: { benchType: "CELESTIAL_VOID_VALKYRIE_AERIAL_SANCTUM", maxDurability: 330, leathercraftPower: 120, baseSuccessRatePercent: 99, balanceBonusPercent: 35 }, +}; + +export const STIRRUP_LEATHERS_RECIPE_CATALOG: Record = { + NOVICE_MOUNTED_STIRRUP_LEATHER: { recipeType: "NOVICE_MOUNTED_STIRRUP_LEATHER", requiredLeatherType: "TANNED_HEAVY_BUFFALO_STIRRUP_STRAP", requiredLeatherCount: 2, baseRiderWeightDistributionBonusPercent: 20, baseLanceShockAbsorptionMitigationPercent: 10 }, + WARMASTER_MITHRIL_TREAD_STIRRUP: { recipeType: "WARMASTER_MITHRIL_TREAD_STIRRUP", requiredLeatherType: "TEMPERED_MITHRIL_TREAD_IRON_SET", requiredLeatherCount: 2, baseRiderWeightDistributionBonusPercent: 45, baseLanceShockAbsorptionMitigationPercent: 25 }, + CELESTIAL_VOID_VALKYRIE_AERIAL_STIRRUP: { recipeType: "CELESTIAL_VOID_VALKYRIE_AERIAL_STIRRUP", requiredLeatherType: "CELESTIAL_VOID_STARLIGHT_VALKYRIE_LEATHER", requiredLeatherCount: 2, baseRiderWeightDistributionBonusPercent: 80, baseLanceShockAbsorptionMitigationPercent: 60 }, +}; + +export class AncientRunicLeatherStirrupLeathersBenchEngine { + public static readonly DURABILITY_COST_PER_CRAFT = 10; + + /** + * Cached static catalog maxima to prevent runtime array reallocation. + */ + public static readonly CATALOG_MAXIMA = { + maxPower: Math.max(...Object.values(STIRRUP_LEATHERS_BENCH_CATALOG).map(b => b.leathercraftPower), 1), + maxBonus: Math.max(...Object.values(STIRRUP_LEATHERS_BENCH_CATALOG).map(b => b.balanceBonusPercent), 1), + }; + + /** + * Generates a crypto-secure UUID or 128-bit hex string using node:crypto. + */ + private static generateSecureId(): string { + if (typeof crypto.randomUUID === "function") { + return crypto.randomUUID(); + } + return crypto.randomBytes(16).toString("hex"); + } + + /** + * Generates a cryptographically secure random float strictly in [0, 1). + */ + public static generateSecureRoll(): number { + if (typeof crypto.randomInt === "function") { + return crypto.randomInt(0, 1000000) / 1000000; + } + return crypto.randomBytes(4).readUInt32LE(0) / 0x100000000; + } + + /** + * Constructs and initializes a stirrup leathers stitching bench or knight rig. + */ + public static constructBench( + leatherworkerPlayerId: string, + benchType: StirrupLeathersBenchType + ): ActiveStirrupLeathersBench { + const data = STIRRUP_LEATHERS_BENCH_CATALOG[benchType]; + if (!data) { + throw new Error(`Unsupported stirrup leathers bench type: ${String(benchType)}`); + } + + const uuid = this.generateSecureId(); + + return { + benchId: `bench_${benchType.toLowerCase()}_${uuid}`, + leatherworkerPlayerId, + benchType, + currentDurability: data.maxDurability, + maxDurability: data.maxDurability, + isFunctional: true, + }; + } + + /** + * Stitches and rivets buffalo stirrup straps and tempered mithril tread irons into stirrup leathers. + * Returns an updated clone of `bench` leaving the input instance immutable. + */ + public static craftStirrups( + bench: ActiveStirrupLeathersBench, + recipeType: StirrupLeathersRecipeType, + providedLeathers: RawLeatherStirrupLeathersType[], + craftRoll?: number, + balanceRoll?: number, + currentEpochMs = Date.now() + ): { success: boolean; stirrup?: CraftedStirrupLeathers; updatedBench?: ActiveStirrupLeathersBench; remainingDurability: number; remainingProvidedLeathers: RawLeatherStirrupLeathersType[]; reason?: string } { + const fallbackLeathers = Array.isArray(providedLeathers) ? [...providedLeathers] : []; + + if (!bench || !bench.isFunctional || bench.currentDurability < this.DURABILITY_COST_PER_CRAFT) { + return { + success: false, + updatedBench: bench ? { ...bench } : undefined, + remainingDurability: bench?.currentDurability ?? 0, + remainingProvidedLeathers: fallbackLeathers, + reason: `Stirrup leathers bench is warped or lacks durability (requires ${this.DURABILITY_COST_PER_CRAFT}).`, + }; + } + + const benchData = STIRRUP_LEATHERS_BENCH_CATALOG[bench.benchType]; + if (!benchData) { + return { success: false, updatedBench: { ...bench }, remainingDurability: bench.currentDurability, remainingProvidedLeathers: fallbackLeathers, reason: `Unknown bench model: ${String(bench.benchType)}` }; + } + + const recipe = STIRRUP_LEATHERS_RECIPE_CATALOG[recipeType]; + if (!recipe) { + return { success: false, updatedBench: { ...bench }, remainingDurability: bench.currentDurability, remainingProvidedLeathers: fallbackLeathers, reason: `Unknown stirrup leathers recipe: ${String(recipeType)}` }; + } + + if (!Array.isArray(providedLeathers)) { + return { success: false, updatedBench: { ...bench }, remainingDurability: bench.currentDurability, remainingProvidedLeathers: [], reason: "Invalid leathers array." }; + } + + // Count matching leather materials + const matchingCount = providedLeathers.filter(l => l === recipe.requiredLeatherType).length; + if (matchingCount < recipe.requiredLeatherCount) { + return { + success: false, + updatedBench: { ...bench }, + remainingDurability: bench.currentDurability, + remainingProvidedLeathers: fallbackLeathers, + reason: `Insufficient stirrup leather/tread sets: requires ${recipe.requiredLeatherCount}x ${recipe.requiredLeatherType}, provided ${matchingCount}.`, + }; + } + + // Create updated bench clone + const updatedBench = { ...bench }; + + // Deduct durability on clone + updatedBench.currentDurability -= this.DURABILITY_COST_PER_CRAFT; + if (updatedBench.currentDurability < this.DURABILITY_COST_PER_CRAFT) { + updatedBench.currentDurability = Math.max(0, updatedBench.currentDurability); + updatedBench.isFunctional = false; + } + + // Deduct materials upfront on all craft attempts + const remaining = [...providedLeathers]; + let removed = 0; + for (let i = remaining.length - 1; i >= 0 && removed < recipe.requiredLeatherCount; i--) { + if (remaining[i] === recipe.requiredLeatherType) { + remaining.splice(i, 1); + removed++; + } + } + + const safeRoll = typeof craftRoll === "number" && Number.isFinite(craftRoll) ? Math.max(0, Math.min(1, craftRoll)) : this.generateSecureRoll(); + const rollPercent = safeRoll * 100; + + if (rollPercent > benchData.baseSuccessRatePercent) { + return { + success: false, + updatedBench, + remainingDurability: updatedBench.currentDurability, + remainingProvidedLeathers: remaining, + reason: `Tread iron misaligned: mithril footbed rivet tore heavy buffalo stirrup strap, rolled ${rollPercent.toFixed(1)}, needed <= ${benchData.baseSuccessRatePercent}.`, + }; + } + + // Calculate independent rider balance score dynamically using cached catalog maxima & authoritative catalog values (clamped 0% to 100%, scaling across catalog baselines) + const { maxPower, maxBonus } = this.CATALOG_MAXIMA; + const safeBalanceRoll = typeof balanceRoll === "number" && Number.isFinite(balanceRoll) ? Math.max(0, Math.min(1, balanceRoll)) : this.generateSecureRoll(); + const powerRatio = Math.min(1.0, benchData.leathercraftPower / maxPower); + const bonusPoints = (benchData.balanceBonusPercent / maxBonus) * 20; + const balanceScore = Math.max(0, Math.min(100, Math.round( + (safeBalanceRoll * 40) + (powerRatio * 40) + bonusPoints + ))); + const qualityMultiplier = 0.8 + ((balanceScore / 100) * 0.4); // 0.8 to 1.2x + + const finalWeightBonus = Math.max(0, Math.min(100, Math.round(recipe.baseRiderWeightDistributionBonusPercent * qualityMultiplier))); + const finalShockMitigate = Math.max(0, Math.min(100, Math.round(recipe.baseLanceShockAbsorptionMitigationPercent * qualityMultiplier))); + + const uuid = this.generateSecureId(); + + const stirrup: CraftedStirrupLeathers = { + stirrupId: `stirrup_${recipeType.toLowerCase()}_${uuid}`, + recipeType, + finalRiderWeightDistributionBonusPercent: finalWeightBonus, + finalLanceShockAbsorptionMitigationPercent: finalShockMitigate, + riderBalancePercent: balanceScore, + consumedLeatherCount: recipe.requiredLeatherCount, + consumedLeatherType: recipe.requiredLeatherType, + remainingProvidedLeathers: remaining, + craftedEpochMs: currentEpochMs, + }; + + return { + success: true, + stirrup, + updatedBench, + remainingDurability: updatedBench.currentDurability, + remainingProvidedLeathers: remaining, + }; + } + + /** + * Cleans equestrian grit and maintains stirrup leathers bench. + * Returns an updated clone of `bench` leaving the input instance immutable. + */ + public static maintainBench( + bench: ActiveStirrupLeathersBench, + repairAmount = 50 + ): { success: boolean; updatedBench?: ActiveStirrupLeathersBench; newDurability: number; isFunctional: boolean } { + if (!bench) return { success: false, newDurability: 0, isFunctional: false }; + + const updatedBench = { ...bench }; + const amt = Number.isFinite(repairAmount) ? Math.max(0, repairAmount) : 50; + updatedBench.currentDurability = Math.min(updatedBench.maxDurability, updatedBench.currentDurability + amt); + updatedBench.isFunctional = updatedBench.currentDurability >= this.DURABILITY_COST_PER_CRAFT; + + return { + success: true, + updatedBench, + newDurability: updatedBench.currentDurability, + isFunctional: updatedBench.isFunctional, + }; + } +} \ No newline at end of file diff --git a/api/src/tests/ancientRunicLeatherStirrupLeathersBench.test.ts b/api/src/tests/ancientRunicLeatherStirrupLeathersBench.test.ts new file mode 100644 index 00000000..2b29aab1 --- /dev/null +++ b/api/src/tests/ancientRunicLeatherStirrupLeathersBench.test.ts @@ -0,0 +1,154 @@ +import { describe, it, expect } from "vitest"; +import { AncientRunicLeatherStirrupLeathersBenchEngine } from "../lib/ancientRunicLeatherStirrupLeathersBench"; +import type { ActiveStirrupLeathersBench } from "../lib/ancientRunicLeatherStirrupLeathersBench"; + +describe("AncientRunicLeatherStirrupLeathersBenchEngine Stirrup Benches & Rigs", () => { + it("crafts Celestial Void Valkyrie Aerial Stirrup in Aerial Sanctum achieving 100% balance and returns spliced leathers", () => { + const bench = AncientRunicLeatherStirrupLeathersBenchEngine.constructBench("leather_01", "CELESTIAL_VOID_VALKYRIE_AERIAL_SANCTUM"); + expect(bench.benchType).toBe("CELESTIAL_VOID_VALKYRIE_AERIAL_SANCTUM"); + expect(bench.currentDurability).toBe(330); + + const initialLeathers = [ + "CELESTIAL_VOID_STARLIGHT_VALKYRIE_LEATHER", + "CELESTIAL_VOID_STARLIGHT_VALKYRIE_LEATHER", + "CELESTIAL_VOID_STARLIGHT_VALKYRIE_LEATHER" + ] as any[]; + + const craftRes = AncientRunicLeatherStirrupLeathersBenchEngine.craftStirrups( + bench, + "CELESTIAL_VOID_VALKYRIE_AERIAL_STIRRUP", + initialLeathers, + 0.1, // Success roll + 1.0, // Balance roll 1.0 -> 40 + 40 + 20 = 100% + 100000 + ); + + expect(craftRes.success).toBe(true); + expect(craftRes.stirrup?.recipeType).toBe("CELESTIAL_VOID_VALKYRIE_AERIAL_STIRRUP"); + expect(craftRes.stirrup?.riderBalancePercent).toBe(100); + expect(craftRes.stirrup?.finalRiderWeightDistributionBonusPercent).toBe(96); // 80 * 1.20 = 96% + expect(craftRes.stirrup?.finalLanceShockAbsorptionMitigationPercent).toBe(72); // 60 * 1.20 = 72% + expect(craftRes.stirrup?.consumedLeatherCount).toBe(2); + expect(craftRes.stirrup?.consumedLeatherType).toBe("CELESTIAL_VOID_STARLIGHT_VALKYRIE_LEATHER"); + expect(craftRes.stirrup?.remainingProvidedLeathers.length).toBe(1); + expect(craftRes.remainingDurability).toBe(320); // 330 - 10 + }); + + it("verifies mid-range balance roll and sub-100% quality scaling on Ash stirrup bench", () => { + const bench = AncientRunicLeatherStirrupLeathersBenchEngine.constructBench("leather_mid", "ASH_STIRRUP_LEATHER_BENCH"); + // powerRatio = 25/120 = 0.20833, bonusPoints = (10/35)*20 = 5.714 + // safeBalanceRoll = 0.5 -> 0.5 * 40 = 20 + // balanceScore = Math.round(20 + 8.333 + 5.714) = 34 + // qualityMultiplier = 0.8 + (34/100)*0.4 = 0.8 + 0.136 = 0.936 + // finalWeightBonus = Math.round(20 * 0.936) = 19 + // finalShockMitigate = Math.round(10 * 0.936) = 9 + const craftRes = AncientRunicLeatherStirrupLeathersBenchEngine.craftStirrups( + bench, + "NOVICE_MOUNTED_STIRRUP_LEATHER", + ["TANNED_HEAVY_BUFFALO_STIRRUP_STRAP", "TANNED_HEAVY_BUFFALO_STIRRUP_STRAP"], + 0.1, + 0.5 + ); + + expect(craftRes.success).toBe(true); + expect(craftRes.stirrup?.riderBalancePercent).toBe(34); + expect(craftRes.stirrup?.finalRiderWeightDistributionBonusPercent).toBe(19); + expect(craftRes.stirrup?.finalLanceShockAbsorptionMitigationPercent).toBe(9); + }); + + it("handles bench becoming non-functional after successful craft when durability falls below threshold", () => { + const bench = AncientRunicLeatherStirrupLeathersBenchEngine.constructBench("leather_wear", "ASH_STIRRUP_LEATHER_BENCH"); + bench.currentDurability = 15; + expect(bench.isFunctional).toBe(true); + + // First craft succeeds: 15 - 10 = 5 (< 10), so isFunctional flips to false in updatedBench + const res1 = AncientRunicLeatherStirrupLeathersBenchEngine.craftStirrups( + bench, + "NOVICE_MOUNTED_STIRRUP_LEATHER", + ["TANNED_HEAVY_BUFFALO_STIRRUP_STRAP", "TANNED_HEAVY_BUFFALO_STIRRUP_STRAP"], + 0.1 + ); + expect(res1.success).toBe(true); + expect(res1.remainingDurability).toBe(5); + expect(res1.updatedBench?.isFunctional).toBe(false); + + // Subsequent craft on updated bench is rejected and returns fallback array + const res2 = AncientRunicLeatherStirrupLeathersBenchEngine.craftStirrups( + res1.updatedBench!, + "NOVICE_MOUNTED_STIRRUP_LEATHER", + ["TANNED_HEAVY_BUFFALO_STIRRUP_STRAP", "TANNED_HEAVY_BUFFALO_STIRRUP_STRAP"] + ); + expect(res2.success).toBe(false); + expect(res2.reason).toContain("warped or lacks durability"); + expect(res2.remainingProvidedLeathers.length).toBe(2); + }); + + it("rejects crafting when insufficient leather is provided and returns provided leathers", () => { + const bench = AncientRunicLeatherStirrupLeathersBenchEngine.constructBench("leather_02", "ASH_STIRRUP_LEATHER_BENCH"); + + const failRes = AncientRunicLeatherStirrupLeathersBenchEngine.craftStirrups( + bench, + "WARMASTER_MITHRIL_TREAD_STIRRUP", + ["TEMPERED_MITHRIL_TREAD_IRON_SET"] + ); + + expect(failRes.success).toBe(false); + expect(failRes.reason).toContain("Insufficient stirrup leather/tread sets"); + expect(failRes.remainingProvidedLeathers.length).toBe(1); + expect(bench.currentDurability).toBe(85); + }); + + it("handles tread iron misaligned failure roll consuming durability and leathers", () => { + const bench = AncientRunicLeatherStirrupLeathersBenchEngine.constructBench("leather_03", "ASH_STIRRUP_LEATHER_BENCH"); // 85% success + + const fail = AncientRunicLeatherStirrupLeathersBenchEngine.craftStirrups( + bench, + "NOVICE_MOUNTED_STIRRUP_LEATHER", + ["TANNED_HEAVY_BUFFALO_STIRRUP_STRAP", "TANNED_HEAVY_BUFFALO_STIRRUP_STRAP", "TANNED_HEAVY_BUFFALO_STIRRUP_STRAP"], + 0.95 + ); + + expect(fail.success).toBe(false); + expect(fail.reason).toContain("misaligned"); + expect(fail.remainingProvidedLeathers?.length).toBe(1); // 3 - 2 = 1 remaining + expect(fail.remainingDurability).toBe(75); // 85 - 10 + }); + + it("gates isFunctional in maintainBench based on DURABILITY_COST_PER_CRAFT threshold and returns clone", () => { + const bench = AncientRunicLeatherStirrupLeathersBenchEngine.constructBench("leather_04", "ASH_STIRRUP_LEATHER_BENCH"); + bench.currentDurability = 0; + bench.isFunctional = false; + + // Maintain 5 (below 10 required) -> isFunctional remains false + const repLow = AncientRunicLeatherStirrupLeathersBenchEngine.maintainBench(bench, 5); + expect(repLow.success).toBe(true); + expect(repLow.newDurability).toBe(5); + expect(repLow.isFunctional).toBe(false); + expect(bench.currentDurability).toBe(0); // input unchanged + + // Maintain 10 more on clone -> 15 (>= 10) -> isFunctional becomes true + const repHigh = AncientRunicLeatherStirrupLeathersBenchEngine.maintainBench(repLow.updatedBench!, 10); + expect(repHigh.success).toBe(true); + expect(repHigh.newDurability).toBe(15); + expect(repHigh.isFunctional).toBe(true); + }); + + it("guards against null inputs and unsupported bench models", () => { + expect(() => AncientRunicLeatherStirrupLeathersBenchEngine.constructBench("l", "PLASTIC_BENCH" as any)).toThrow( + "Unsupported stirrup leathers bench type" + ); + + const invalidBench: ActiveStirrupLeathersBench = { + benchId: "bad", + leatherworkerPlayerId: "p", + benchType: "BENCH" as any, + currentDurability: 50, + maxDurability: 50, + isFunctional: true, + }; + + expect(AncientRunicLeatherStirrupLeathersBenchEngine.craftStirrups(invalidBench, "NOVICE_MOUNTED_STIRRUP_LEATHER", ["TANNED_HEAVY_BUFFALO_STIRRUP_STRAP", "TANNED_HEAVY_BUFFALO_STIRRUP_STRAP"]).success).toBe(false); + expect(AncientRunicLeatherStirrupLeathersBenchEngine.craftStirrups(null as any, "NOVICE_MOUNTED_STIRRUP_LEATHER", []).success).toBe(false); + expect(AncientRunicLeatherStirrupLeathersBenchEngine.maintainBench(null as any).success).toBe(false); + }); +}); \ No newline at end of file