BlueGit

timfa questward

Add jadeite fairy companion and emerald/ruby jewelry teleports.

Fairies spawn while the amulet is worn, assist in the owner's fights, leash/teleport to the player, and respawn on a 60s timer that survives unequip. Emerald bracelets and ruby rings channel a 3s teleport to the nearest church or bank.

timfa Tim Falken · pushed by timfa

Authored 2026-09-02 · 2 months ago

Hash
719e6d4ad8500e0113ae8bf708668ee2837b89a7
Parent
b4308d34
13 files changed +1258 −30
client/src/play/main.js +42 −3
@@ -24,7 +24,8 @@ import { initContextMenu } from "./contextMenu.js";
24 24 import { initDeath } from "./death.js";
25 25 import { initToasts } from "./toasts.js";
26 26 import { skillLevelUpToastText, skillUnlockMessages } from "/shared/skills/levelUpUnlocks.js";
27 import { mobDefinition, mobLevelDisplayName } from "/shared/definitions/mobs.js";
27 import { mobDefinition, mobLevelDisplayName, MobId } from "/shared/definitions/mobs.js";
28 import { canTeleportToBank, canTeleportToChurch } from "/shared/equipment/jewelryEffects.js";
28 29 import { initQuests } from "./quests.js";
29 30 import { initDialogue } from "./dialogue.js";
30 31 import { initShop } from "./shop.js";
@@ -1154,7 +1155,38 @@ function handleRightClick (event, mouseX, mouseY)
1154 1155 for (const entity of view.entitiesAtTile(tile.tileX, tile.tileY, { includePrevious: true }))
1155 1156 {
1156 1157 if (entity.entityId === view.localEntityId)
1157 { continue; }
1158 {
1159 const equipment = { slots: inventory?.getEquipment?.() ?? {} };
1160 if (canTeleportToChurch(equipment))
1161 {
1162 items.push({
1163 label: "Teleport to Church",
1164 onSelect: () =>
1165 {
1166 clearAllPendingActions();
1167 socket.send({
1168 type: MessageType.jewelryTeleport,
1169 destination: "church"
1170 });
1171 }
1172 });
1173 }
1174 if (canTeleportToBank(equipment))
1175 {
1176 items.push({
1177 label: "Teleport to bank",
1178 onSelect: () =>
1179 {
1180 clearAllPendingActions();
1181 socket.send({
1182 type: MessageType.jewelryTeleport,
1183 destination: "bank"
1184 });
1185 }
1186 });
1187 }
1188 continue;
1189 }
1158 1190 const targetName = entityLabel(entity);
1159 1191 items.push({
1160 1192 label: `Follow ${targetName}`,
@@ -1402,9 +1434,12 @@ function entityLabel (entity)
1402 1434 const def = mobDefinition(entity.mobTypeId);
1403 1435 const first = (entity?.firstName ?? "").trim();
1404 1436 const last = (entity?.lastName ?? "").trim();
1437 // Fairies keep type name in tooltips ("Lv.n Fairy") even when firstName is "Ada's Fairy".
1405 1438 const name = first && last
1406 1439 ? `${first} ${last}`
1407 : (first || def?.displayName || "Creature");
1440 : (entity.mobTypeId === MobId.fairy
1441 ? (def?.displayName || "Fairy")
1442 : (first || def?.displayName || "Creature"));
1408 1443 const level = entity?.level ?? def?.attackSkill ?? 1;
1409 1444 return mobLevelDisplayName(level, name);
1410 1445 }
@@ -1732,6 +1767,10 @@ async function main ()
1732 1767 {
1733 1768 return inventory?.getInventorySlots?.() ?? [];
1734 1769 },
1770 getEquipment ()
1771 {
1772 return inventory?.getEquipment?.() ?? {};
1773 },
1735 1774 getSkillLevel (skillId)
1736 1775 {
1737 1776 return skills?.skillLevel?.(skillId) ?? 1;
@@ -24,7 +24,8 @@ import { initContextMenu } from "./contextMenu.js";
24import { initDeath } from "./death.js";
24import { initDeath } from "./death.js";
25import { initToasts } from "./toasts.js";
25import { initToasts } from "./toasts.js";
26import { skillLevelUpToastText, skillUnlockMessages } from "/shared/skills/levelUpUnlocks.js";
26import { skillLevelUpToastText, skillUnlockMessages } from "/shared/skills/levelUpUnlocks.js";
27import { mobDefinition, mobLevelDisplayName } from "/shared/definitions/mobs.js";
27import { mobDefinition, mobLevelDisplayName, MobId } from "/shared/definitions/mobs.js";
28import { canTeleportToBank, canTeleportToChurch } from "/shared/equipment/jewelryEffects.js";
28import { initQuests } from "./quests.js";
29import { initQuests } from "./quests.js";
29import { initDialogue } from "./dialogue.js";
30import { initDialogue } from "./dialogue.js";
30import { initShop } from "./shop.js";
31import { initShop } from "./shop.js";
@@ -1154,7 +1155,38 @@ function handleRightClick (event, mouseX, mouseY)
1154 for (const entity of view.entitiesAtTile(tile.tileX, tile.tileY, { includePrevious: true }))
1155 for (const entity of view.entitiesAtTile(tile.tileX, tile.tileY, { includePrevious: true }))
1155 {
1156 {
1156 if (entity.entityId === view.localEntityId)
1157 if (entity.entityId === view.localEntityId)
1157 { continue; }
1158 {
1159 const equipment = { slots: inventory?.getEquipment?.() ?? {} };
1160 if (canTeleportToChurch(equipment))
1161 {
1162 items.push({
1163 label: "Teleport to Church",
1164 onSelect: () =>
1165 {
1166 clearAllPendingActions();
1167 socket.send({
1168 type: MessageType.jewelryTeleport,
1169 destination: "church"
1170 });
1171 }
1172 });
1173 }
1174 if (canTeleportToBank(equipment))
1175 {
1176 items.push({
1177 label: "Teleport to bank",
1178 onSelect: () =>
1179 {
1180 clearAllPendingActions();
1181 socket.send({
1182 type: MessageType.jewelryTeleport,
1183 destination: "bank"
1184 });
1185 }
1186 });
1187 }
1188 continue;
1189 }
1158 const targetName = entityLabel(entity);
1190 const targetName = entityLabel(entity);
1159 items.push({
1191 items.push({
1160 label: `Follow ${targetName}`,
1192 label: `Follow ${targetName}`,
@@ -1402,9 +1434,12 @@ function entityLabel (entity)
1402 const def = mobDefinition(entity.mobTypeId);
1434 const def = mobDefinition(entity.mobTypeId);
1403 const first = (entity?.firstName ?? "").trim();
1435 const first = (entity?.firstName ?? "").trim();
1404 const last = (entity?.lastName ?? "").trim();
1436 const last = (entity?.lastName ?? "").trim();
1437 // Fairies keep type name in tooltips ("Lv.n Fairy") even when firstName is "Ada's Fairy".
1405 const name = first && last
1438 const name = first && last
1406 ? `${first} ${last}`
1439 ? `${first} ${last}`
1407 : (first || def?.displayName || "Creature");
1440 : (entity.mobTypeId === MobId.fairy
1441 ? (def?.displayName || "Fairy")
1442 : (first || def?.displayName || "Creature"));
1408 const level = entity?.level ?? def?.attackSkill ?? 1;
1443 const level = entity?.level ?? def?.attackSkill ?? 1;
1409 return mobLevelDisplayName(level, name);
1444 return mobLevelDisplayName(level, name);
1410 }
1445 }
@@ -1732,6 +1767,10 @@ async function main ()
1732 {
1767 {
1733 return inventory?.getInventorySlots?.() ?? [];
1768 return inventory?.getInventorySlots?.() ?? [];
1734 },
1769 },
1770 getEquipment ()
1771 {
1772 return inventory?.getEquipment?.() ?? {};
1773 },
1735 getSkillLevel (skillId)
1774 getSkillLevel (skillId)
1736 {
1775 {
1737 return skills?.skillLevel?.(skillId) ?? 1;
1776 return skills?.skillLevel?.(skillId) ?? 1;
server/src/combat/service.js +104 −8
@@ -65,13 +65,26 @@ import { chunkBoundsAround, findPath } from "../navigation/astar.js";
65 65 import { tileToChunk } from "../world/coordinates.js";
66 66 import { findPathToNearestGoal } from "../../../shared/navigation/bfs.js";
67 67 import { CHUNK_SIZE, VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
68 import { stackQuantity } from "../../../shared/items/inventory.js";
69 import { addGroundItem, publicGroundItem } from "../items/bags.js";
68 import { stackQuantity, insertStack } from "../../../shared/items/inventory.js";
69 import { addGroundItem, publicGroundItem, bagView } from "../items/bags.js";
70 70 import { resolveItemDualTint } from "../../../shared/render/tint.js";
71 71 import { essenceItemIdForElement } from "../../../shared/definitions/essenceItems.js";
72 72 import { castMobAttackSpell } from "../spells/mobCast.js";
73 73 import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";
74 74 import { scheduleSpawnerRespawn } from "../simulation/spawners.js";
75 import
76 {
77 passiveHpRegenMultiplier,
78 attackerToHitRng,
79 enemyToHitRngAgainst,
80 hitSkillBonus,
81 jewelryDamageAffinities,
82 mergeAffinities,
83 damageReflectFraction,
84 autoLootOnKill,
85 ignoresNonBossAggro,
86 JADEITE_FAIRY_RESPAWN_MS
87 } from "../../../shared/equipment/jewelryEffects.js";
75 88
76 89 export function chebyshev (ax, ay, bx, by)
77 90 {
@@ -167,7 +180,8 @@ function playerCombatLevels (ecs, handle, profile, settings = null)
167 180 bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0);
168 181
169 182 return {
170 hitLevel: effectiveSkillLevel(skills, profile.hitSkillId ?? SkillId.unarmed, bonuses),
183 hitLevel: effectiveSkillLevel(skills, profile.hitSkillId ?? SkillId.unarmed, bonuses)
184 + hitSkillBonus(equipment),
171 185 damageLevel: effectiveSkillLevel(skills, profile.damageSkillId ?? SkillId.strength, bonuses),
172 186 agilityLevel: effectiveSkillLevel(skills, SkillId.agility, bonuses),
173 187 defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses)
@@ -332,6 +346,9 @@ export function markFleeOnHit (world, targetId, attackerId)
332 346 const creature = ecs.get(targetHandle, Component.creature);
333 347 if (!creature || ecs.get(targetHandle, Component.character))
334 348 { return; }
349 // Companion summons (jadeite fairy, shade) stay in the fight.
350 if (ecs.get(targetHandle, Component.summon))
351 { return; }
335 352 const fleeDist = mobDefinition(creature.mobTypeId)?.fleeOnHitTiles | 0;
336 353 if (fleeDist <= 0)
337 354 { return; }
@@ -526,12 +543,14 @@ function spawnMobDrops (world, targetHandle, tileX, tileY, now, attackerId = nul
526 543 const quantity = rollDropQuantity(drop);
527 544 if (quantity <= 0)
528 545 { continue; }
529 const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1);
530 546 const stack = attachOrigins({
531 547 itemId: drop.itemId,
532 548 quantity,
533 549 origins: [{ origin, quantity }]
534 550 });
551 if (tryAutoLootToKiller(world, attackerId, stack, events))
552 { continue; }
553 const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1);
535 554 const item = {
536 555 groundItemId,
537 556 tileX,
@@ -554,6 +573,33 @@ function spawnMobDrops (world, targetHandle, tileX, tileY, now, attackerId = nul
554 573 return events;
555 574 }
556 575
576 function tryAutoLootToKiller (world, attackerId, stack, events)
577 {
578 if (attackerId == null)
579 { return false; }
580 const attackerHandle = world.ecs.handleOf(attackerId);
581 if (attackerHandle == null)
582 { return false; }
583 const equipment = world.ecs.get(attackerHandle, Component.equipment);
584 if (!autoLootOnKill(equipment))
585 { return false; }
586 const inventory = world.ecs.get(attackerHandle, Component.inventory);
587 const character = world.ecs.get(attackerHandle, Component.character);
588 const def = itemDefinition(stack.itemId);
589 if (!inventory || !character || !def)
590 { return false; }
591 const inserted = insertStack(inventory.slots, stack, def);
592 if (!inserted.ok || (inserted.remainder | 0) > 0)
593 { return false; }
594 inventory.slots = inserted.slots;
595 events.push({
596 type: "inventory",
597 characterId: character.characterId,
598 ...bagView(world.ecs, attackerHandle)
599 });
600 return true;
601 }
602
557 603 function entityCombatDisplayName (ecs, handle)
558 604 {
559 605 const appearance = ecs.get(handle, Component.appearance);
@@ -711,6 +757,9 @@ function playerIgnoresAggressiveMob (world, mobEntity, playerHandle, now)
711 757 const def = mobDefinition(mobEntity.creature.mobTypeId);
712 758 if (mobIsBoss(def))
713 759 { return false; }
760 const playerEquipment = world.ecs.get(playerHandle, Component.equipment);
761 if (ignoresNonBossAggro(playerEquipment))
762 { return true; }
714 763 const skills = world.ecs.get(playerHandle, Component.skills);
715 764 if (!skills)
716 765 { return false; }
@@ -861,9 +910,11 @@ export function stepPassiveHealthRegen (world, now = Date.now(), dt = 1 / 20)
861 910 if (now - lastDamageAt < PASSIVE_HP_REGEN_DELAY_MS)
862 911 { continue; }
863 912 const beforeInt = health.current | 0;
913 const equipment = world.ecs.get(handle, Component.equipment);
914 const regenMult = passiveHpRegenMultiplier(equipment);
864 915 health.current = Math.min(
865 916 health.max | 0,
866 (Number(health.current) || 0) + PASSIVE_HP_REGEN_PER_SECOND * dt
917 (Number(health.current) || 0) + PASSIVE_HP_REGEN_PER_SECOND * regenMult * dt
867 918 );
868 919 if ((health.current | 0) === beforeInt)
869 920 { continue; }
@@ -1951,9 +2002,16 @@ function applyLocalMeleeHit (
1951 2002
1952 2003 const attackType = resolveAttackDamageType(world.ecs, attackerHandle, profile);
1953 2004 const targetCreature = world.ecs.get(targetHandle, Component.creature);
1954 const targetAffinities = targetCreature
2005 const mobAffinities = targetCreature
1955 2006 ? mobDamageAffinities(mobDefinition(targetCreature.mobTypeId))
1956 2007 : {};
2008 const targetAffinities = mergeAffinities(mobAffinities, jewelryDamageAffinities(defenderEquipment));
2009 const attackerEquipment = attackerHandle != null
2010 ? world.ecs.get(attackerHandle, Component.equipment)
2011 : null;
2012 let hitRng = Math.random;
2013 hitRng = attackerToHitRng(attackerEquipment, hitRng);
2014 hitRng = enemyToHitRngAgainst(defenderEquipment, hitRng);
1957 2015 const resolved = resolvePhysicalAttack({
1958 2016 hitSkillLevel: effectiveHitSkillInDarkness(
1959 2017 attackerLevels.hitLevel,
@@ -1963,7 +2021,8 @@ function applyLocalMeleeHit (
1963 2021 damageSkillLevel: attackerLevels.damageLevel,
1964 2022 defenceSkillLevel: defenceLevel,
1965 2023 attackType,
1966 targetAffinities
2024 targetAffinities,
2025 rng: hitRng
1967 2026 });
1968 2027
1969 2028 if (resolved.outcome === "miss")
@@ -2070,6 +2129,8 @@ function applyLocalMeleeHit (
2070 2129 }
2071 2130 }
2072 2131
2132 events.push(...maybeReflectDamage(world, attackerId, targetId, targetHandle, damage, now));
2133
2073 2134 if (attackerHandle != null)
2074 2135 { markFleeOnHit(world, targetId, attackerId); }
2075 2136
@@ -2151,6 +2212,24 @@ export function finalizeMobKill (world, attackerId, targetId, targetHandle, tile
2151 2212 const creature = world.ecs.get(handle, Component.creature);
2152 2213 const origin = world.ecs.get(handle, Component.spawnOrigin);
2153 2214 const appearance = world.ecs.get(handle, Component.appearance);
2215 const summon = world.ecs.get(handle, Component.summon);
2216 if (summon?.kind === "jadeite-fairy")
2217 {
2218 const respawnAt = now + JADEITE_FAIRY_RESPAWN_MS;
2219 const characterId = summon.ownerCharacterId | 0;
2220 if (!world.jadeiteFairyTimers)
2221 { world.jadeiteFairyTimers = new Map(); }
2222 if (characterId)
2223 { world.jadeiteFairyTimers.set(characterId, respawnAt); }
2224 const ownerHandle = summon.ownerEntityId != null
2225 ? world.ecs.handleOf(summon.ownerEntityId)
2226 : null;
2227 const character = ownerHandle != null
2228 ? world.ecs.get(ownerHandle, Component.character)
2229 : null;
2230 if (character)
2231 { character.jadeiteFairyRespawnAt = respawnAt; }
2232 }
2154 2233 events.push(...spawnMobDrops(world, handle, tileX, tileY, now, attackerId));
2155 2234 events.push({
2156 2235 type: "mob-killed",
@@ -2191,7 +2270,7 @@ export function finalizeMobKill (world, attackerId, targetId, targetHandle, tile
2191 2270 }
2192 2271
2193 2272 /** Apply HP loss and shared death/loot side-effects (used by spell impacts). */
2194 export function applyDamageAndKill (world, attackerId, targetId, damage, now = Date.now())
2273 export function applyDamageAndKill (world, attackerId, targetId, damage, now = Date.now(), options = {})
2195 2274 {
2196 2275 const events = [];
2197 2276 const targetHandle = world.ecs.handleOf(targetId);
@@ -2250,6 +2329,8 @@ export function applyDamageAndKill (world, attackerId, targetId, damage, now = D
2250 2329 });
2251 2330 }
2252 2331
2332 events.push(...maybeReflectDamage(world, attackerId, targetId, targetHandle, damage, now, options));
2333
2253 2334 if (health && health.current <= 0)
2254 2335 {
2255 2336 clearEngage(world.ecs, attackerId);
@@ -2286,3 +2367,18 @@ export function applyDamageAndKill (world, attackerId, targetId, damage, now = D
2286 2367 }
2287 2368 return events;
2288 2369 }
2370
2371 function maybeReflectDamage (world, attackerId, targetId, targetHandle, damage, now, options = {})
2372 {
2373 if (options.noReflect || !(damage > 0) || attackerId == null || attackerId === targetId)
2374 { return []; }
2375 const equipment = world.ecs.get(targetHandle, Component.equipment);
2376 const fraction = damageReflectFraction(equipment);
2377 if (!(fraction > 0))
2378 { return []; }
2379 const attackerHandle = world.ecs.handleOf(attackerId);
2380 if (attackerHandle == null)
2381 { return []; }
2382 const reflectDamage = Math.max(1, Math.floor(damage * fraction));
2383 return applyDamageAndKill(world, targetId, attackerId, reflectDamage, now, { noReflect: true });
2384 }
@@ -65,13 +65,26 @@ import { chunkBoundsAround, findPath } from "../navigation/astar.js";
65import { tileToChunk } from "../world/coordinates.js";
65import { tileToChunk } from "../world/coordinates.js";
66import { findPathToNearestGoal } from "../../../shared/navigation/bfs.js";
66import { findPathToNearestGoal } from "../../../shared/navigation/bfs.js";
67import { CHUNK_SIZE, VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
67import { CHUNK_SIZE, VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
68import { stackQuantity } from "../../../shared/items/inventory.js";
68import { stackQuantity, insertStack } from "../../../shared/items/inventory.js";
69import { addGroundItem, publicGroundItem } from "../items/bags.js";
69import { addGroundItem, publicGroundItem, bagView } from "../items/bags.js";
70import { resolveItemDualTint } from "../../../shared/render/tint.js";
70import { resolveItemDualTint } from "../../../shared/render/tint.js";
71import { essenceItemIdForElement } from "../../../shared/definitions/essenceItems.js";
71import { essenceItemIdForElement } from "../../../shared/definitions/essenceItems.js";
72import { castMobAttackSpell } from "../spells/mobCast.js";
72import { castMobAttackSpell } from "../spells/mobCast.js";
73import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";
73import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";
74import { scheduleSpawnerRespawn } from "../simulation/spawners.js";
74import { scheduleSpawnerRespawn } from "../simulation/spawners.js";
75import
76{
77 passiveHpRegenMultiplier,
78 attackerToHitRng,
79 enemyToHitRngAgainst,
80 hitSkillBonus,
81 jewelryDamageAffinities,
82 mergeAffinities,
83 damageReflectFraction,
84 autoLootOnKill,
85 ignoresNonBossAggro,
86 JADEITE_FAIRY_RESPAWN_MS
87} from "../../../shared/equipment/jewelryEffects.js";
75
88
76export function chebyshev (ax, ay, bx, by)
89export function chebyshev (ax, ay, bx, by)
77{
90{
@@ -167,7 +180,8 @@ function playerCombatLevels (ecs, handle, profile, settings = null)
167 bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0);
180 bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0);
168
181
169 return {
182 return {
170 hitLevel: effectiveSkillLevel(skills, profile.hitSkillId ?? SkillId.unarmed, bonuses),
183 hitLevel: effectiveSkillLevel(skills, profile.hitSkillId ?? SkillId.unarmed, bonuses)
184 + hitSkillBonus(equipment),
171 damageLevel: effectiveSkillLevel(skills, profile.damageSkillId ?? SkillId.strength, bonuses),
185 damageLevel: effectiveSkillLevel(skills, profile.damageSkillId ?? SkillId.strength, bonuses),
172 agilityLevel: effectiveSkillLevel(skills, SkillId.agility, bonuses),
186 agilityLevel: effectiveSkillLevel(skills, SkillId.agility, bonuses),
173 defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses)
187 defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses)
@@ -332,6 +346,9 @@ export function markFleeOnHit (world, targetId, attackerId)
332 const creature = ecs.get(targetHandle, Component.creature);
346 const creature = ecs.get(targetHandle, Component.creature);
333 if (!creature || ecs.get(targetHandle, Component.character))
347 if (!creature || ecs.get(targetHandle, Component.character))
334 { return; }
348 { return; }
349 // Companion summons (jadeite fairy, shade) stay in the fight.
350 if (ecs.get(targetHandle, Component.summon))
351 { return; }
335 const fleeDist = mobDefinition(creature.mobTypeId)?.fleeOnHitTiles | 0;
352 const fleeDist = mobDefinition(creature.mobTypeId)?.fleeOnHitTiles | 0;
336 if (fleeDist <= 0)
353 if (fleeDist <= 0)
337 { return; }
354 { return; }
@@ -526,12 +543,14 @@ function spawnMobDrops (world, targetHandle, tileX, tileY, now, attackerId = nul
526 const quantity = rollDropQuantity(drop);
543 const quantity = rollDropQuantity(drop);
527 if (quantity <= 0)
544 if (quantity <= 0)
528 { continue; }
545 { continue; }
529 const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1);
530 const stack = attachOrigins({
546 const stack = attachOrigins({
531 itemId: drop.itemId,
547 itemId: drop.itemId,
532 quantity,
548 quantity,
533 origins: [{ origin, quantity }]
549 origins: [{ origin, quantity }]
534 });
550 });
551 if (tryAutoLootToKiller(world, attackerId, stack, events))
552 { continue; }
553 const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1);
535 const item = {
554 const item = {
536 groundItemId,
555 groundItemId,
537 tileX,
556 tileX,
@@ -554,6 +573,33 @@ function spawnMobDrops (world, targetHandle, tileX, tileY, now, attackerId = nul
554 return events;
573 return events;
555}
574}
556
575
576function tryAutoLootToKiller (world, attackerId, stack, events)
577{
578 if (attackerId == null)
579 { return false; }
580 const attackerHandle = world.ecs.handleOf(attackerId);
581 if (attackerHandle == null)
582 { return false; }
583 const equipment = world.ecs.get(attackerHandle, Component.equipment);
584 if (!autoLootOnKill(equipment))
585 { return false; }
586 const inventory = world.ecs.get(attackerHandle, Component.inventory);
587 const character = world.ecs.get(attackerHandle, Component.character);
588 const def = itemDefinition(stack.itemId);
589 if (!inventory || !character || !def)
590 { return false; }
591 const inserted = insertStack(inventory.slots, stack, def);
592 if (!inserted.ok || (inserted.remainder | 0) > 0)
593 { return false; }
594 inventory.slots = inserted.slots;
595 events.push({
596 type: "inventory",
597 characterId: character.characterId,
598 ...bagView(world.ecs, attackerHandle)
599 });
600 return true;
601}
602
557function entityCombatDisplayName (ecs, handle)
603function entityCombatDisplayName (ecs, handle)
558{
604{
559 const appearance = ecs.get(handle, Component.appearance);
605 const appearance = ecs.get(handle, Component.appearance);
@@ -711,6 +757,9 @@ function playerIgnoresAggressiveMob (world, mobEntity, playerHandle, now)
711 const def = mobDefinition(mobEntity.creature.mobTypeId);
757 const def = mobDefinition(mobEntity.creature.mobTypeId);
712 if (mobIsBoss(def))
758 if (mobIsBoss(def))
713 { return false; }
759 { return false; }
760 const playerEquipment = world.ecs.get(playerHandle, Component.equipment);
761 if (ignoresNonBossAggro(playerEquipment))
762 { return true; }
714 const skills = world.ecs.get(playerHandle, Component.skills);
763 const skills = world.ecs.get(playerHandle, Component.skills);
715 if (!skills)
764 if (!skills)
716 { return false; }
765 { return false; }
@@ -861,9 +910,11 @@ export function stepPassiveHealthRegen (world, now = Date.now(), dt = 1 / 20)
861 if (now - lastDamageAt < PASSIVE_HP_REGEN_DELAY_MS)
910 if (now - lastDamageAt < PASSIVE_HP_REGEN_DELAY_MS)
862 { continue; }
911 { continue; }
863 const beforeInt = health.current | 0;
912 const beforeInt = health.current | 0;
913 const equipment = world.ecs.get(handle, Component.equipment);
914 const regenMult = passiveHpRegenMultiplier(equipment);
864 health.current = Math.min(
915 health.current = Math.min(
865 health.max | 0,
916 health.max | 0,
866 (Number(health.current) || 0) + PASSIVE_HP_REGEN_PER_SECOND * dt
917 (Number(health.current) || 0) + PASSIVE_HP_REGEN_PER_SECOND * regenMult * dt
867 );
918 );
868 if ((health.current | 0) === beforeInt)
919 if ((health.current | 0) === beforeInt)
869 { continue; }
920 { continue; }
@@ -1951,9 +2002,16 @@ function applyLocalMeleeHit (
1951
2002
1952 const attackType = resolveAttackDamageType(world.ecs, attackerHandle, profile);
2003 const attackType = resolveAttackDamageType(world.ecs, attackerHandle, profile);
1953 const targetCreature = world.ecs.get(targetHandle, Component.creature);
2004 const targetCreature = world.ecs.get(targetHandle, Component.creature);
1954 const targetAffinities = targetCreature
2005 const mobAffinities = targetCreature
1955 ? mobDamageAffinities(mobDefinition(targetCreature.mobTypeId))
2006 ? mobDamageAffinities(mobDefinition(targetCreature.mobTypeId))
1956 : {};
2007 : {};
2008 const targetAffinities = mergeAffinities(mobAffinities, jewelryDamageAffinities(defenderEquipment));
2009 const attackerEquipment = attackerHandle != null
2010 ? world.ecs.get(attackerHandle, Component.equipment)
2011 : null;
2012 let hitRng = Math.random;
2013 hitRng = attackerToHitRng(attackerEquipment, hitRng);
2014 hitRng = enemyToHitRngAgainst(defenderEquipment, hitRng);
1957 const resolved = resolvePhysicalAttack({
2015 const resolved = resolvePhysicalAttack({
1958 hitSkillLevel: effectiveHitSkillInDarkness(
2016 hitSkillLevel: effectiveHitSkillInDarkness(
1959 attackerLevels.hitLevel,
2017 attackerLevels.hitLevel,
@@ -1963,7 +2021,8 @@ function applyLocalMeleeHit (
1963 damageSkillLevel: attackerLevels.damageLevel,
2021 damageSkillLevel: attackerLevels.damageLevel,
1964 defenceSkillLevel: defenceLevel,
2022 defenceSkillLevel: defenceLevel,
1965 attackType,
2023 attackType,
1966 targetAffinities
2024 targetAffinities,
2025 rng: hitRng
1967 });
2026 });
1968
2027
1969 if (resolved.outcome === "miss")
2028 if (resolved.outcome === "miss")
@@ -2070,6 +2129,8 @@ function applyLocalMeleeHit (
2070 }
2129 }
2071 }
2130 }
2072
2131
2132 events.push(...maybeReflectDamage(world, attackerId, targetId, targetHandle, damage, now));
2133
2073 if (attackerHandle != null)
2134 if (attackerHandle != null)
2074 { markFleeOnHit(world, targetId, attackerId); }
2135 { markFleeOnHit(world, targetId, attackerId); }
2075
2136
@@ -2151,6 +2212,24 @@ export function finalizeMobKill (world, attackerId, targetId, targetHandle, tile
2151 const creature = world.ecs.get(handle, Component.creature);
2212 const creature = world.ecs.get(handle, Component.creature);
2152 const origin = world.ecs.get(handle, Component.spawnOrigin);
2213 const origin = world.ecs.get(handle, Component.spawnOrigin);
2153 const appearance = world.ecs.get(handle, Component.appearance);
2214 const appearance = world.ecs.get(handle, Component.appearance);
2215 const summon = world.ecs.get(handle, Component.summon);
2216 if (summon?.kind === "jadeite-fairy")
2217 {
2218 const respawnAt = now + JADEITE_FAIRY_RESPAWN_MS;
2219 const characterId = summon.ownerCharacterId | 0;
2220 if (!world.jadeiteFairyTimers)
2221 { world.jadeiteFairyTimers = new Map(); }
2222 if (characterId)
2223 { world.jadeiteFairyTimers.set(characterId, respawnAt); }
2224 const ownerHandle = summon.ownerEntityId != null
2225 ? world.ecs.handleOf(summon.ownerEntityId)
2226 : null;
2227 const character = ownerHandle != null
2228 ? world.ecs.get(ownerHandle, Component.character)
2229 : null;
2230 if (character)
2231 { character.jadeiteFairyRespawnAt = respawnAt; }
2232 }
2154 events.push(...spawnMobDrops(world, handle, tileX, tileY, now, attackerId));
2233 events.push(...spawnMobDrops(world, handle, tileX, tileY, now, attackerId));
2155 events.push({
2234 events.push({
2156 type: "mob-killed",
2235 type: "mob-killed",
@@ -2191,7 +2270,7 @@ export function finalizeMobKill (world, attackerId, targetId, targetHandle, tile
2191}
2270}
2192
2271
2193/** Apply HP loss and shared death/loot side-effects (used by spell impacts). */
2272/** Apply HP loss and shared death/loot side-effects (used by spell impacts). */
2194export function applyDamageAndKill (world, attackerId, targetId, damage, now = Date.now())
2273export function applyDamageAndKill (world, attackerId, targetId, damage, now = Date.now(), options = {})
2195{
2274{
2196 const events = [];
2275 const events = [];
2197 const targetHandle = world.ecs.handleOf(targetId);
2276 const targetHandle = world.ecs.handleOf(targetId);
@@ -2250,6 +2329,8 @@ export function applyDamageAndKill (world, attackerId, targetId, damage, now = D
2250 });
2329 });
2251 }
2330 }
2252
2331
2332 events.push(...maybeReflectDamage(world, attackerId, targetId, targetHandle, damage, now, options));
2333
2253 if (health && health.current <= 0)
2334 if (health && health.current <= 0)
2254 {
2335 {
2255 clearEngage(world.ecs, attackerId);
2336 clearEngage(world.ecs, attackerId);
@@ -2286,3 +2367,18 @@ export function applyDamageAndKill (world, attackerId, targetId, damage, now = D
2286 }
2367 }
2287 return events;
2368 return events;
2288}
2369}
2370
2371function maybeReflectDamage (world, attackerId, targetId, targetHandle, damage, now, options = {})
2372{
2373 if (options.noReflect || !(damage > 0) || attackerId == null || attackerId === targetId)
2374 { return []; }
2375 const equipment = world.ecs.get(targetHandle, Component.equipment);
2376 const fraction = damageReflectFraction(equipment);
2377 if (!(fraction > 0))
2378 { return []; }
2379 const attackerHandle = world.ecs.handleOf(attackerId);
2380 if (attackerHandle == null)
2381 { return []; }
2382 const reflectDamage = Math.max(1, Math.floor(damage * fraction));
2383 return applyDamageAndKill(world, targetId, attackerId, reflectDamage, now, { noReflect: true });
2384}
server/src/ecs/components.js +1 −1
@@ -26,7 +26,7 @@ export const Component = Object.freeze({
26 26 statusEffects: "statusEffects",
27 27 spells: "spells",
28 28 spellcasting: "spellcasting",
29 /** Temporary summoned companion (Shade). */
29 /** Temporary summoned companion (Shade, jadeite fairy). */
30 30 summon: "summon",
31 31 /** Player chunk residency for aggro peace (sinceMs when current chunk was entered). */
32 32 chunkPresence: "chunkPresence"
@@ -26,7 +26,7 @@ export const Component = Object.freeze({
26 statusEffects: "statusEffects",
26 statusEffects: "statusEffects",
27 spells: "spells",
27 spells: "spells",
28 spellcasting: "spellcasting",
28 spellcasting: "spellcasting",
29 /** Temporary summoned companion (Shade). */
29 /** Temporary summoned companion (Shade, jadeite fairy). */
30 summon: "summon",
30 summon: "summon",
31 /** Player chunk residency for aggro peace (sinceMs when current chunk was entered). */
31 /** Player chunk residency for aggro peace (sinceMs when current chunk was entered). */
32 chunkPresence: "chunkPresence"
32 chunkPresence: "chunkPresence"
server/src/equipment/jewelryTeleport.js added +146 −0
@@ -0,0 +1,146 @@
1 import { Component } from "../ecs/components.js";
2 import
3 {
4 JEWELRY_TELEPORT_MS,
5 canTeleportToBank,
6 canTeleportToChurch
7 } from "../../../shared/equipment/jewelryEffects.js";
8
9 export const JewelryTeleportDestination = Object.freeze({
10 church: "church",
11 bank: "bank"
12 });
13
14 function ensureSessions (world)
15 {
16 if (!world.jewelryTeleportSessions)
17 { world.jewelryTeleportSessions = new Map(); }
18 return world.jewelryTeleportSessions;
19 }
20
21 export function cancelJewelryTeleport (world, characterId)
22 {
23 ensureSessions(world).delete(characterId | 0);
24 }
25
26 function userError (message)
27 {
28 const error = new Error(message);
29 error.userFacing = true;
30 return error;
31 }
32
33 /**
34 * Begin a 3s jewelry teleport channel. Interrupted by move or damage.
35 */
36 export function startJewelryTeleport (world, sessionId, characterId, destination, now = Date.now())
37 {
38 const dest = String(destination || "");
39 if (dest !== JewelryTeleportDestination.church && dest !== JewelryTeleportDestination.bank)
40 { throw userError("Unknown teleport destination."); }
41
42 const entityId = world.characterEntities.get(characterId);
43 if (entityId == null)
44 { throw userError("Character is not in the world."); }
45 const handle = world.ecs.handleOf(entityId);
46 const identity = world.ecs.get(handle, Component.networkIdentity);
47 if (!identity || identity.sessionId !== sessionId)
48 { throw userError("Character is not in the world."); }
49 if (world.ecs.has(handle, Component.dead))
50 { throw userError("You are dead."); }
51
52 const equipment = world.ecs.get(handle, Component.equipment);
53 if (dest === JewelryTeleportDestination.church && !canTeleportToChurch(equipment))
54 { throw userError("You need an emerald bracelet to teleport to a church."); }
55 if (dest === JewelryTeleportDestination.bank && !canTeleportToBank(equipment))
56 { throw userError("You need a ruby ring to teleport to a bank."); }
57
58 const path = world.ecs.get(handle, Component.path);
59 if (path)
60 { path.tiles = []; }
61
62 ensureSessions(world).set(characterId | 0, {
63 sessionId,
64 entityId,
65 destination: dest,
66 startedAt: now,
67 finishesAt: now + JEWELRY_TELEPORT_MS
68 });
69 return { events: [] };
70 }
71
72 export function handleJewelryTeleportCommand (world, sessionId, command, now = Date.now())
73 {
74 if (command.type !== "jewelry-teleport")
75 { return null; }
76 return startJewelryTeleport(
77 world,
78 sessionId,
79 command.characterId,
80 command.destination,
81 now
82 );
83 }
84
85 /**
86 * Advance jewelry teleport channels. Emits finish events for the simulation to relocate.
87 * @returns {{ events: object[] }}
88 */
89 export function stepJewelryTeleports (world, now = Date.now())
90 {
91 const sessions = ensureSessions(world);
92 const events = [];
93 for (const [characterId, session] of [...sessions.entries()])
94 {
95 const entityId = world.characterEntities.get(characterId) ?? session.entityId;
96 const handle = entityId != null ? world.ecs.handleOf(entityId) : null;
97 if (handle == null || world.ecs.has(handle, Component.dead))
98 {
99 sessions.delete(characterId);
100 continue;
101 }
102
103 const path = world.ecs.get(handle, Component.path);
104 if (path?.tiles?.length)
105 {
106 sessions.delete(characterId);
107 continue;
108 }
109
110 const health = world.ecs.get(handle, Component.health);
111 if (health?.lastDamageAt != null && health.lastDamageAt >= session.startedAt)
112 {
113 sessions.delete(characterId);
114 continue;
115 }
116
117 const equipment = world.ecs.get(handle, Component.equipment);
118 if (session.destination === JewelryTeleportDestination.church && !canTeleportToChurch(equipment))
119 {
120 sessions.delete(characterId);
121 continue;
122 }
123 if (session.destination === JewelryTeleportDestination.bank && !canTeleportToBank(equipment))
124 {
125 sessions.delete(characterId);
126 continue;
127 }
128
129 if (now < session.finishesAt)
130 { continue; }
131
132 sessions.delete(characterId);
133 const position = world.ecs.get(handle, Component.position);
134 events.push({
135 type: "jewelry-teleport-finish",
136 sessionId: session.sessionId,
137 characterId,
138 entityId,
139 destination: session.destination,
140 fromTileX: position?.tileX ?? 0,
141 fromTileY: position?.tileY ?? 0,
142 dimensionId: position?.dimensionId
143 });
144 }
145 return { events };
146 }
@@ -0,0 +1,146 @@
1import { Component } from "../ecs/components.js";
2import
3 {
4 JEWELRY_TELEPORT_MS,
5 canTeleportToBank,
6 canTeleportToChurch
7 } from "../../../shared/equipment/jewelryEffects.js";
8
9export const JewelryTeleportDestination = Object.freeze({
10 church: "church",
11 bank: "bank"
12});
13
14function ensureSessions (world)
15{
16 if (!world.jewelryTeleportSessions)
17 { world.jewelryTeleportSessions = new Map(); }
18 return world.jewelryTeleportSessions;
19}
20
21export function cancelJewelryTeleport (world, characterId)
22{
23 ensureSessions(world).delete(characterId | 0);
24}
25
26function userError (message)
27{
28 const error = new Error(message);
29 error.userFacing = true;
30 return error;
31}
32
33/**
34 * Begin a 3s jewelry teleport channel. Interrupted by move or damage.
35 */
36export function startJewelryTeleport (world, sessionId, characterId, destination, now = Date.now())
37{
38 const dest = String(destination || "");
39 if (dest !== JewelryTeleportDestination.church && dest !== JewelryTeleportDestination.bank)
40 { throw userError("Unknown teleport destination."); }
41
42 const entityId = world.characterEntities.get(characterId);
43 if (entityId == null)
44 { throw userError("Character is not in the world."); }
45 const handle = world.ecs.handleOf(entityId);
46 const identity = world.ecs.get(handle, Component.networkIdentity);
47 if (!identity || identity.sessionId !== sessionId)
48 { throw userError("Character is not in the world."); }
49 if (world.ecs.has(handle, Component.dead))
50 { throw userError("You are dead."); }
51
52 const equipment = world.ecs.get(handle, Component.equipment);
53 if (dest === JewelryTeleportDestination.church && !canTeleportToChurch(equipment))
54 { throw userError("You need an emerald bracelet to teleport to a church."); }
55 if (dest === JewelryTeleportDestination.bank && !canTeleportToBank(equipment))
56 { throw userError("You need a ruby ring to teleport to a bank."); }
57
58 const path = world.ecs.get(handle, Component.path);
59 if (path)
60 { path.tiles = []; }
61
62 ensureSessions(world).set(characterId | 0, {
63 sessionId,
64 entityId,
65 destination: dest,
66 startedAt: now,
67 finishesAt: now + JEWELRY_TELEPORT_MS
68 });
69 return { events: [] };
70}
71
72export function handleJewelryTeleportCommand (world, sessionId, command, now = Date.now())
73{
74 if (command.type !== "jewelry-teleport")
75 { return null; }
76 return startJewelryTeleport(
77 world,
78 sessionId,
79 command.characterId,
80 command.destination,
81 now
82 );
83}
84
85/**
86 * Advance jewelry teleport channels. Emits finish events for the simulation to relocate.
87 * @returns {{ events: object[] }}
88 */
89export function stepJewelryTeleports (world, now = Date.now())
90{
91 const sessions = ensureSessions(world);
92 const events = [];
93 for (const [characterId, session] of [...sessions.entries()])
94 {
95 const entityId = world.characterEntities.get(characterId) ?? session.entityId;
96 const handle = entityId != null ? world.ecs.handleOf(entityId) : null;
97 if (handle == null || world.ecs.has(handle, Component.dead))
98 {
99 sessions.delete(characterId);
100 continue;
101 }
102
103 const path = world.ecs.get(handle, Component.path);
104 if (path?.tiles?.length)
105 {
106 sessions.delete(characterId);
107 continue;
108 }
109
110 const health = world.ecs.get(handle, Component.health);
111 if (health?.lastDamageAt != null && health.lastDamageAt >= session.startedAt)
112 {
113 sessions.delete(characterId);
114 continue;
115 }
116
117 const equipment = world.ecs.get(handle, Component.equipment);
118 if (session.destination === JewelryTeleportDestination.church && !canTeleportToChurch(equipment))
119 {
120 sessions.delete(characterId);
121 continue;
122 }
123 if (session.destination === JewelryTeleportDestination.bank && !canTeleportToBank(equipment))
124 {
125 sessions.delete(characterId);
126 continue;
127 }
128
129 if (now < session.finishesAt)
130 { continue; }
131
132 sessions.delete(characterId);
133 const position = world.ecs.get(handle, Component.position);
134 events.push({
135 type: "jewelry-teleport-finish",
136 sessionId: session.sessionId,
137 characterId,
138 entityId,
139 destination: session.destination,
140 fromTileX: position?.tileX ?? 0,
141 fromTileY: position?.tileY ?? 0,
142 dimensionId: position?.dimensionId
143 });
144 }
145 return { events };
146}
server/src/gateway/websocket.js +8 −0
@@ -795,6 +795,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
795 795 characterId: session.characterId
796 796 });
797 797 break;
798 case MessageType.jewelryTeleport:
799 requirePlaying(session);
800 simulation.enqueue(session.id, {
801 type: "jewelry-teleport",
802 characterId: session.characterId,
803 destination: message.destination === "bank" ? "bank" : "church"
804 });
805 break;
798 806 case MessageType.sendPigeon:
799 807 requirePlaying(session);
800 808 {
@@ -795,6 +795,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
795 characterId: session.characterId
795 characterId: session.characterId
796 });
796 });
797 break;
797 break;
798 case MessageType.jewelryTeleport:
799 requirePlaying(session);
800 simulation.enqueue(session.id, {
801 type: "jewelry-teleport",
802 characterId: session.characterId,
803 destination: message.destination === "bank" ? "bank" : "church"
804 });
805 break;
798 case MessageType.sendPigeon:
806 case MessageType.sendPigeon:
799 requirePlaying(session);
807 requirePlaying(session);
800 {
808 {
server/src/simulation/simulation.js +123 −8
@@ -36,6 +36,8 @@ import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";
36 36 import { skullValue, decayKillCounter, SKULL_KILL_BONUS } from "../../../shared/combat/skull.js";
37 37 import { mobComponents } from "./spawners.js";
38 38 import { shadeSummonComponents } from "../spells/summons.js";
39 import { jadeiteFairyComponents } from "../spells/jadeiteFairy.js";
40 import { MobId } from "../../../shared/definitions/mobs.js";
39 41 import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";
40 42 import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/state.js";
41 43 import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
@@ -244,6 +246,11 @@ export class Simulation
244 246 events.push(...this.#applySummonEntity(event));
245 247 continue;
246 248 }
249 if (event.type === "jewelry-teleport-finish")
250 {
251 events.push(...this.#applyJewelryTeleport(event));
252 continue;
253 }
247 254 if (event.type === "entity-move")
248 255 { this.#applyMoveToDirectory(event); }
249 256 if (event.type === "entity-despawn")
@@ -2710,14 +2717,25 @@ export class Simulation
2710 2717
2711 2718 #applySummonEntity (event)
2712 2719 {
2713 const components = shadeSummonComponents({
2714 tileX: event.tileX | 0,
2715 tileY: event.tileY | 0,
2716 level: event.level | 0 || 1,
2717 ownerEntityId: event.ownerEntityId,
2718 expiresAt: event.expiresAt,
2719 dimensionId: event.dimensionId
2720 });
2720 const isFairy = event.mobTypeId === MobId.fairy || event.mobTypeId === "fairy";
2721 const components = isFairy
2722 ? jadeiteFairyComponents({
2723 tileX: event.tileX | 0,
2724 tileY: event.tileY | 0,
2725 level: event.level | 0 || 1,
2726 ownerEntityId: event.ownerEntityId,
2727 ownerCharacterId: event.ownerCharacterId ?? null,
2728 ownerName: event.ownerName,
2729 dimensionId: event.dimensionId
2730 })
2731 : shadeSummonComponents({
2732 tileX: event.tileX | 0,
2733 tileY: event.tileY | 0,
2734 level: event.level | 0 || 1,
2735 ownerEntityId: event.ownerEntityId,
2736 expiresAt: event.expiresAt,
2737 dimensionId: event.dimensionId
2738 });
2721 2739 try
2722 2740 {
2723 2741 const entityId = this.spawnEntity(components, { requireResident: true });
@@ -2731,6 +2749,103 @@ export class Simulation
2731 2749 }
2732 2750 }
2733 2751
2752 #applyJewelryTeleport (event)
2753 {
2754 const entityId = event.entityId ?? this.characterEntities.get(event.characterId);
2755 const record = entityId ? this.directory.get(entityId) : null;
2756 if (!record)
2757 { return []; }
2758 const destination = this.#findJewelryTeleportDestination(
2759 event.fromTileX | 0,
2760 event.fromTileY | 0,
2761 entityId,
2762 event.destination
2763 );
2764 if (!destination)
2765 {
2766 return [{
2767 type: "command-error",
2768 sessionId: event.sessionId,
2769 message: event.destination === "bank"
2770 ? "No bank is available."
2771 : "No church altar is available."
2772 }];
2773 }
2774 const loader = { ...DEFAULT_CHUNK_LOADER };
2775 this.#ensureCoverage(
2776 destination.tileX,
2777 destination.tileY,
2778 loader,
2779 destination.dimensionId ?? OVERWORLD_ID
2780 );
2781 const result = this.workers[record.workerId].call({
2782 type: WorkerMessage.relocateEntity,
2783 entityId,
2784 tileX: destination.tileX,
2785 tileY: destination.tileY,
2786 dimensionId: destination.dimensionId ?? OVERWORLD_ID
2787 });
2788 if (!result?.accepted)
2789 {
2790 return [{
2791 type: "command-error",
2792 sessionId: event.sessionId,
2793 message: "The destination is no longer available."
2794 }];
2795 }
2796 const events = [];
2797 if (result.transferRequest)
2798 { events.push(...this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }])); }
2799 else if (result.event)
2800 {
2801 this.#applyMoveToDirectory(result.event);
2802 events.push(result.event);
2803 const view = this.workers[record.workerId].call({
2804 type: WorkerMessage.inspect,
2805 entityId
2806 });
2807 if (view)
2808 { this.#remember(view, record.workerId); }
2809 }
2810 return events;
2811 }
2812
2813 #findJewelryTeleportDestination (originX, originY, entityId, destination)
2814 {
2815 if (destination === "church")
2816 { return this.#findRespawnDestination(originX, originY, entityId); }
2817 if (destination !== "bank")
2818 { return null; }
2819 const record = this.directory.get(entityId);
2820 const dimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID);
2821 const bank = this.courier?.nearestBank(originX, originY);
2822 if (!bank)
2823 { return null; }
2824 const adjacent = [];
2825 for (let dy = -1; dy <= 1; dy++)
2826 {
2827 for (let dx = -1; dx <= 1; dx++)
2828 {
2829 if (dx === 0 && dy === 0)
2830 { continue; }
2831 adjacent.push({
2832 tileX: bank.tileX + dx,
2833 tileY: bank.tileY + dy,
2834 dimensionId
2835 });
2836 }
2837 }
2838 adjacent.sort((left, right) =>
2839 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
2840 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
2841 );
2842 const tile = adjacent.find((entry) =>
2843 this.isEnterable(entry.tileX, entry.tileY, dimensionId)
2844 && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId, dimensionId)
2845 );
2846 return tile ?? null;
2847 }
2848
2734 2849 #skillLevelUpEvents (event)
2735 2850 {
2736 2851 const levelUps = event?.levelUps ?? [];
@@ -36,6 +36,8 @@ import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";
36import { skullValue, decayKillCounter, SKULL_KILL_BONUS } from "../../../shared/combat/skull.js";
36import { skullValue, decayKillCounter, SKULL_KILL_BONUS } from "../../../shared/combat/skull.js";
37import { mobComponents } from "./spawners.js";
37import { mobComponents } from "./spawners.js";
38import { shadeSummonComponents } from "../spells/summons.js";
38import { shadeSummonComponents } from "../spells/summons.js";
39import { jadeiteFairyComponents } from "../spells/jadeiteFairy.js";
40import { MobId } from "../../../shared/definitions/mobs.js";
39import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";
41import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";
40import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/state.js";
42import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/state.js";
41import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
43import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
@@ -244,6 +246,11 @@ export class Simulation
244 events.push(...this.#applySummonEntity(event));
246 events.push(...this.#applySummonEntity(event));
245 continue;
247 continue;
246 }
248 }
249 if (event.type === "jewelry-teleport-finish")
250 {
251 events.push(...this.#applyJewelryTeleport(event));
252 continue;
253 }
247 if (event.type === "entity-move")
254 if (event.type === "entity-move")
248 { this.#applyMoveToDirectory(event); }
255 { this.#applyMoveToDirectory(event); }
249 if (event.type === "entity-despawn")
256 if (event.type === "entity-despawn")
@@ -2710,14 +2717,25 @@ export class Simulation
2710
2717
2711 #applySummonEntity (event)
2718 #applySummonEntity (event)
2712 {
2719 {
2713 const components = shadeSummonComponents({
2720 const isFairy = event.mobTypeId === MobId.fairy || event.mobTypeId === "fairy";
2714 tileX: event.tileX | 0,
2721 const components = isFairy
2715 tileY: event.tileY | 0,
2722 ? jadeiteFairyComponents({
2716 level: event.level | 0 || 1,
2723 tileX: event.tileX | 0,
2717 ownerEntityId: event.ownerEntityId,
2724 tileY: event.tileY | 0,
2718 expiresAt: event.expiresAt,
2725 level: event.level | 0 || 1,
2719 dimensionId: event.dimensionId
2726 ownerEntityId: event.ownerEntityId,
2720 });
2727 ownerCharacterId: event.ownerCharacterId ?? null,
2728 ownerName: event.ownerName,
2729 dimensionId: event.dimensionId
2730 })
2731 : shadeSummonComponents({
2732 tileX: event.tileX | 0,
2733 tileY: event.tileY | 0,
2734 level: event.level | 0 || 1,
2735 ownerEntityId: event.ownerEntityId,
2736 expiresAt: event.expiresAt,
2737 dimensionId: event.dimensionId
2738 });
2721 try
2739 try
2722 {
2740 {
2723 const entityId = this.spawnEntity(components, { requireResident: true });
2741 const entityId = this.spawnEntity(components, { requireResident: true });
@@ -2731,6 +2749,103 @@ export class Simulation
2731 }
2749 }
2732 }
2750 }
2733
2751
2752 #applyJewelryTeleport (event)
2753 {
2754 const entityId = event.entityId ?? this.characterEntities.get(event.characterId);
2755 const record = entityId ? this.directory.get(entityId) : null;
2756 if (!record)
2757 { return []; }
2758 const destination = this.#findJewelryTeleportDestination(
2759 event.fromTileX | 0,
2760 event.fromTileY | 0,
2761 entityId,
2762 event.destination
2763 );
2764 if (!destination)
2765 {
2766 return [{
2767 type: "command-error",
2768 sessionId: event.sessionId,
2769 message: event.destination === "bank"
2770 ? "No bank is available."
2771 : "No church altar is available."
2772 }];
2773 }
2774 const loader = { ...DEFAULT_CHUNK_LOADER };
2775 this.#ensureCoverage(
2776 destination.tileX,
2777 destination.tileY,
2778 loader,
2779 destination.dimensionId ?? OVERWORLD_ID
2780 );
2781 const result = this.workers[record.workerId].call({
2782 type: WorkerMessage.relocateEntity,
2783 entityId,
2784 tileX: destination.tileX,
2785 tileY: destination.tileY,
2786 dimensionId: destination.dimensionId ?? OVERWORLD_ID
2787 });
2788 if (!result?.accepted)
2789 {
2790 return [{
2791 type: "command-error",
2792 sessionId: event.sessionId,
2793 message: "The destination is no longer available."
2794 }];
2795 }
2796 const events = [];
2797 if (result.transferRequest)
2798 { events.push(...this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }])); }
2799 else if (result.event)
2800 {
2801 this.#applyMoveToDirectory(result.event);
2802 events.push(result.event);
2803 const view = this.workers[record.workerId].call({
2804 type: WorkerMessage.inspect,
2805 entityId
2806 });
2807 if (view)
2808 { this.#remember(view, record.workerId); }
2809 }
2810 return events;
2811 }
2812
2813 #findJewelryTeleportDestination (originX, originY, entityId, destination)
2814 {
2815 if (destination === "church")
2816 { return this.#findRespawnDestination(originX, originY, entityId); }
2817 if (destination !== "bank")
2818 { return null; }
2819 const record = this.directory.get(entityId);
2820 const dimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID);
2821 const bank = this.courier?.nearestBank(originX, originY);
2822 if (!bank)
2823 { return null; }
2824 const adjacent = [];
2825 for (let dy = -1; dy <= 1; dy++)
2826 {
2827 for (let dx = -1; dx <= 1; dx++)
2828 {
2829 if (dx === 0 && dy === 0)
2830 { continue; }
2831 adjacent.push({
2832 tileX: bank.tileX + dx,
2833 tileY: bank.tileY + dy,
2834 dimensionId
2835 });
2836 }
2837 }
2838 adjacent.sort((left, right) =>
2839 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
2840 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
2841 );
2842 const tile = adjacent.find((entry) =>
2843 this.isEnterable(entry.tileX, entry.tileY, dimensionId)
2844 && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId, dimensionId)
2845 );
2846 return tile ?? null;
2847 }
2848
2734 #skillLevelUpEvents (event)
2849 #skillLevelUpEvents (event)
2735 {
2850 {
2736 const levelUps = event?.levelUps ?? [];
2851 const levelUps = event?.levelUps ?? [];
server/src/simulation/workerWorld.js +69 −8
@@ -35,6 +35,12 @@ import {
35 35 } from "../items/bags.js";
36 36 import { handleSpellCommand, processSpellImpacts, stepPendingSpellCast, stepSpellAutoCast, tickSpellLights, clearSpellAutoRepeat } from "../spells/service.js";
37 37 import { stepSummons } from "../spells/summons.js";
38 import { stepJadeiteFairies } from "../spells/jadeiteFairy.js";
39 import {
40 handleJewelryTeleportCommand,
41 stepJewelryTeleports,
42 cancelJewelryTeleport
43 } from "../equipment/jewelryTeleport.js";
38 44 import { publicSpellsView } from "../../../shared/spells/state.js";
39 45 import { maybeOpenDoorOnApproach, stepDoors, entityCanOpenDoors } from "../doors/service.js";
40 46 import {
@@ -71,6 +77,9 @@ import {
71 77 import { awardCombatHitXp, syncPlayerStamina } from "../skills/service.js";
72 78 import { SkillId } from "../../../shared/definitions/skills.js";
73 79 import { applySkillXp, publicSkillsPayload, storedSkillXp } from "../../../shared/skills/state.js";
80 import { passiveStaminaRegenMultiplier, dropAmuletInsteadOfCoins } from "../../../shared/equipment/jewelryEffects.js";
81 import { JewelryItemId } from "../../../shared/definitions/jewelryItems.js";
82 import { EQUIPMENT_SLOT } from "../../../shared/definitions/items.js";
74 83 import { syncCharacterChunkPresence } from "../navigation/chunkPresence.js";
75 84 import {
76 85 STAMINA_REGEN_PER_SECOND,
@@ -111,6 +120,8 @@ export class WorkerWorld
111 120 this.fishingSpotRespawns = new Map();
112 121 this.fishSessions = new Map();
113 122 this.pendingSpellImpacts = [];
123 this.jadeiteFairyTimers = new Map();
124 this.jewelryTeleportSessions = new Map();
114 125 this.settings = { ...DEFAULT_WORLD_SETTINGS };
115 126 this.activeRevisionId = 1;
116 127 }
@@ -496,6 +507,13 @@ export class WorkerWorld
496 507 return this.#follow(sessionId, command.characterId, command.targetEntityId);
497 508 case "cancel-follow":
498 509 return this.#cancelFollow(sessionId, command.characterId);
510 case "jewelry-teleport":
511 {
512 const jewelry = handleJewelryTeleportCommand(this, sessionId, command, message.now ?? Date.now());
513 if (jewelry)
514 { return jewelry; }
515 return { events: [] };
516 }
499 517 case "set-spell-favorite":
500 518 case "set-spell-autocast":
501 519 case "arm-spell":
@@ -540,14 +558,42 @@ export class WorkerWorld
540 558 let privateBag = null;
541 559 if (message.dropCarriedCoins)
542 560 {
543 const stripped = stripCarriedCoinsForDeath(this, message.characterId);
544 privateBag = stripped.private;
545 if (stripped.stack && message.coinGroundItemId != null)
561 const entityId = this.characterEntities.get(message.characterId);
562 const handle = entityId != null ? this.ecs.handleOf(entityId) : null;
563 const equipment = handle != null ? this.ecs.get(handle, Component.equipment) : null;
564 if (dropAmuletInsteadOfCoins(equipment))
546 565 {
547 drops.push({
548 groundItemId: message.coinGroundItemId,
549 stack: stripped.stack
550 });
566 const amulet = equipment?.slots?.[EQUIPMENT_SLOT.amulet]
567 ?? equipment?.slots?.amulet
568 ?? null;
569 if (amulet && (amulet.itemId | 0) === JewelryItemId.rubyAmulet)
570 {
571 equipment.slots[EQUIPMENT_SLOT.amulet] = null;
572 if (message.coinGroundItemId != null)
573 {
574 drops.push({
575 groundItemId: message.coinGroundItemId,
576 stack: {
577 itemId: JewelryItemId.rubyAmulet,
578 quantity: 1,
579 origins: amulet.origins ?? []
580 }
581 });
582 }
583 privateBag = bagView(this.ecs, handle);
584 }
585 }
586 else
587 {
588 const stripped = stripCarriedCoinsForDeath(this, message.characterId);
589 privateBag = stripped.private;
590 if (stripped.stack && message.coinGroundItemId != null)
591 {
592 drops.push({
593 groundItemId: message.coinGroundItemId,
594 stack: stripped.stack
595 });
596 }
551 597 }
552 598 }
553 599 for (const drop of drops)
@@ -863,6 +909,7 @@ export class WorkerWorld
863 909 clearEngage(this.ecs, entityId);
864 910 clearFollow(this.ecs, entityId);
865 911 cancelGather(this.ecs, handle);
912 cancelJewelryTeleport(this, characterId);
866 913 clearSpellAutoRepeat(this.ecs.get(handle, Component.spellcasting));
867 914 const position = this.ecs.get(handle, Component.position);
868 915 const movement = this.ecs.get(handle, Component.movement);
@@ -1259,7 +1306,12 @@ export class WorkerWorld
1259 1306 const before = Number(stamina.current) || 0;
1260 1307 if (before >= stamina.max)
1261 1308 { continue; }
1262 stamina.current = Math.min(stamina.max, before + dt * STAMINA_REGEN_PER_SECOND);
1309 stamina.current = Math.min(
1310 stamina.max,
1311 before + dt * STAMINA_REGEN_PER_SECOND * passiveStaminaRegenMultiplier(
1312 this.ecs.get(handle, Component.equipment)
1313 )
1314 );
1263 1315 const after = Number(stamina.current) || 0;
1264 1316 // Sync on display-bucket changes (ceil) or when the bar fills — avoid per-tick spam.
1265 1317 if (Math.ceil(before) !== Math.ceil(after) || (after >= stamina.max && before < stamina.max))
@@ -1335,6 +1387,15 @@ export class WorkerWorld
1335 1387 if (dropped)
1336 1388 { events.push({ type: "entity-despawn", entityId }); }
1337 1389 }
1390 const fairies = stepJadeiteFairies(this, now);
1391 events.push(...(fairies.events ?? []));
1392 for (const entityId of fairies.despawnIds ?? [])
1393 {
1394 const dropped = this.#destroyEntity(entityId);
1395 if (dropped)
1396 { events.push({ type: "entity-despawn", entityId }); }
1397 }
1398 events.push(...stepJewelryTeleports(this, now).events);
1338 1399 stepFollow(this);
1339 1400 const gather = stepGather(this, now);
1340 1401 events.push(...gather.events);
@@ -35,6 +35,12 @@ import {
35} from "../items/bags.js";
35} from "../items/bags.js";
36import { handleSpellCommand, processSpellImpacts, stepPendingSpellCast, stepSpellAutoCast, tickSpellLights, clearSpellAutoRepeat } from "../spells/service.js";
36import { handleSpellCommand, processSpellImpacts, stepPendingSpellCast, stepSpellAutoCast, tickSpellLights, clearSpellAutoRepeat } from "../spells/service.js";
37import { stepSummons } from "../spells/summons.js";
37import { stepSummons } from "../spells/summons.js";
38import { stepJadeiteFairies } from "../spells/jadeiteFairy.js";
39import {
40 handleJewelryTeleportCommand,
41 stepJewelryTeleports,
42 cancelJewelryTeleport
43} from "../equipment/jewelryTeleport.js";
38import { publicSpellsView } from "../../../shared/spells/state.js";
44import { publicSpellsView } from "../../../shared/spells/state.js";
39import { maybeOpenDoorOnApproach, stepDoors, entityCanOpenDoors } from "../doors/service.js";
45import { maybeOpenDoorOnApproach, stepDoors, entityCanOpenDoors } from "../doors/service.js";
40import {
46import {
@@ -71,6 +77,9 @@ import {
71import { awardCombatHitXp, syncPlayerStamina } from "../skills/service.js";
77import { awardCombatHitXp, syncPlayerStamina } from "../skills/service.js";
72import { SkillId } from "../../../shared/definitions/skills.js";
78import { SkillId } from "../../../shared/definitions/skills.js";
73import { applySkillXp, publicSkillsPayload, storedSkillXp } from "../../../shared/skills/state.js";
79import { applySkillXp, publicSkillsPayload, storedSkillXp } from "../../../shared/skills/state.js";
80import { passiveStaminaRegenMultiplier, dropAmuletInsteadOfCoins } from "../../../shared/equipment/jewelryEffects.js";
81import { JewelryItemId } from "../../../shared/definitions/jewelryItems.js";
82import { EQUIPMENT_SLOT } from "../../../shared/definitions/items.js";
74import { syncCharacterChunkPresence } from "../navigation/chunkPresence.js";
83import { syncCharacterChunkPresence } from "../navigation/chunkPresence.js";
75import {
84import {
76 STAMINA_REGEN_PER_SECOND,
85 STAMINA_REGEN_PER_SECOND,
@@ -111,6 +120,8 @@ export class WorkerWorld
111 this.fishingSpotRespawns = new Map();
120 this.fishingSpotRespawns = new Map();
112 this.fishSessions = new Map();
121 this.fishSessions = new Map();
113 this.pendingSpellImpacts = [];
122 this.pendingSpellImpacts = [];
123 this.jadeiteFairyTimers = new Map();
124 this.jewelryTeleportSessions = new Map();
114 this.settings = { ...DEFAULT_WORLD_SETTINGS };
125 this.settings = { ...DEFAULT_WORLD_SETTINGS };
115 this.activeRevisionId = 1;
126 this.activeRevisionId = 1;
116 }
127 }
@@ -496,6 +507,13 @@ export class WorkerWorld
496 return this.#follow(sessionId, command.characterId, command.targetEntityId);
507 return this.#follow(sessionId, command.characterId, command.targetEntityId);
497 case "cancel-follow":
508 case "cancel-follow":
498 return this.#cancelFollow(sessionId, command.characterId);
509 return this.#cancelFollow(sessionId, command.characterId);
510 case "jewelry-teleport":
511 {
512 const jewelry = handleJewelryTeleportCommand(this, sessionId, command, message.now ?? Date.now());
513 if (jewelry)
514 { return jewelry; }
515 return { events: [] };
516 }
499 case "set-spell-favorite":
517 case "set-spell-favorite":
500 case "set-spell-autocast":
518 case "set-spell-autocast":
501 case "arm-spell":
519 case "arm-spell":
@@ -540,14 +558,42 @@ export class WorkerWorld
540 let privateBag = null;
558 let privateBag = null;
541 if (message.dropCarriedCoins)
559 if (message.dropCarriedCoins)
542 {
560 {
543 const stripped = stripCarriedCoinsForDeath(this, message.characterId);
561 const entityId = this.characterEntities.get(message.characterId);
544 privateBag = stripped.private;
562 const handle = entityId != null ? this.ecs.handleOf(entityId) : null;
545 if (stripped.stack && message.coinGroundItemId != null)
563 const equipment = handle != null ? this.ecs.get(handle, Component.equipment) : null;
564 if (dropAmuletInsteadOfCoins(equipment))
546 {
565 {
547 drops.push({
566 const amulet = equipment?.slots?.[EQUIPMENT_SLOT.amulet]
548 groundItemId: message.coinGroundItemId,
567 ?? equipment?.slots?.amulet
549 stack: stripped.stack
568 ?? null;
550 });
569 if (amulet && (amulet.itemId | 0) === JewelryItemId.rubyAmulet)
570 {
571 equipment.slots[EQUIPMENT_SLOT.amulet] = null;
572 if (message.coinGroundItemId != null)
573 {
574 drops.push({
575 groundItemId: message.coinGroundItemId,
576 stack: {
577 itemId: JewelryItemId.rubyAmulet,
578 quantity: 1,
579 origins: amulet.origins ?? []
580 }
581 });
582 }
583 privateBag = bagView(this.ecs, handle);
584 }
585 }
586 else
587 {
588 const stripped = stripCarriedCoinsForDeath(this, message.characterId);
589 privateBag = stripped.private;
590 if (stripped.stack && message.coinGroundItemId != null)
591 {
592 drops.push({
593 groundItemId: message.coinGroundItemId,
594 stack: stripped.stack
595 });
596 }
551 }
597 }
552 }
598 }
553 for (const drop of drops)
599 for (const drop of drops)
@@ -863,6 +909,7 @@ export class WorkerWorld
863 clearEngage(this.ecs, entityId);
909 clearEngage(this.ecs, entityId);
864 clearFollow(this.ecs, entityId);
910 clearFollow(this.ecs, entityId);
865 cancelGather(this.ecs, handle);
911 cancelGather(this.ecs, handle);
912 cancelJewelryTeleport(this, characterId);
866 clearSpellAutoRepeat(this.ecs.get(handle, Component.spellcasting));
913 clearSpellAutoRepeat(this.ecs.get(handle, Component.spellcasting));
867 const position = this.ecs.get(handle, Component.position);
914 const position = this.ecs.get(handle, Component.position);
868 const movement = this.ecs.get(handle, Component.movement);
915 const movement = this.ecs.get(handle, Component.movement);
@@ -1259,7 +1306,12 @@ export class WorkerWorld
1259 const before = Number(stamina.current) || 0;
1306 const before = Number(stamina.current) || 0;
1260 if (before >= stamina.max)
1307 if (before >= stamina.max)
1261 { continue; }
1308 { continue; }
1262 stamina.current = Math.min(stamina.max, before + dt * STAMINA_REGEN_PER_SECOND);
1309 stamina.current = Math.min(
1310 stamina.max,
1311 before + dt * STAMINA_REGEN_PER_SECOND * passiveStaminaRegenMultiplier(
1312 this.ecs.get(handle, Component.equipment)
1313 )
1314 );
1263 const after = Number(stamina.current) || 0;
1315 const after = Number(stamina.current) || 0;
1264 // Sync on display-bucket changes (ceil) or when the bar fills — avoid per-tick spam.
1316 // Sync on display-bucket changes (ceil) or when the bar fills — avoid per-tick spam.
1265 if (Math.ceil(before) !== Math.ceil(after) || (after >= stamina.max && before < stamina.max))
1317 if (Math.ceil(before) !== Math.ceil(after) || (after >= stamina.max && before < stamina.max))
@@ -1335,6 +1387,15 @@ export class WorkerWorld
1335 if (dropped)
1387 if (dropped)
1336 { events.push({ type: "entity-despawn", entityId }); }
1388 { events.push({ type: "entity-despawn", entityId }); }
1337 }
1389 }
1390 const fairies = stepJadeiteFairies(this, now);
1391 events.push(...(fairies.events ?? []));
1392 for (const entityId of fairies.despawnIds ?? [])
1393 {
1394 const dropped = this.#destroyEntity(entityId);
1395 if (dropped)
1396 { events.push({ type: "entity-despawn", entityId }); }
1397 }
1398 events.push(...stepJewelryTeleports(this, now).events);
1338 stepFollow(this);
1399 stepFollow(this);
1339 const gather = stepGather(this, now);
1400 const gather = stepGather(this, now);
1340 events.push(...gather.events);
1401 events.push(...gather.events);
server/src/spells/jadeiteFairy.js added +333 −0
@@ -0,0 +1,333 @@
1 import { Component } from "../ecs/components.js";
2 import { MobId } from "../../../shared/definitions/mobs.js";
3 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
4 import
5 {
6 JADEITE_FAIRY_LEASH_TILES,
7 JADEITE_FAIRY_LEVEL_FRACTION,
8 JADEITE_FAIRY_RESPAWN_MS,
9 summonsJadeiteFairy
10 } from "../../../shared/equipment/jewelryEffects.js";
11 import { combatLevelFromSkills } from "../../../shared/combat/combatLevel.js";
12 import
13 {
14 chebyshev,
15 engageTarget,
16 ensureMobCombat,
17 hasCombatLineOfSight
18 } from "../combat/service.js";
19 import { mobComponents } from "../simulation/spawners.js";
20 import { clearFollow, setFollow } from "../simulation/follow.js";
21
22 export const JADEITE_FAIRY_KIND = "jadeite-fairy";
23
24 function ensureFairyTimers (world)
25 {
26 if (!world.jadeiteFairyTimers)
27 { world.jadeiteFairyTimers = new Map(); }
28 return world.jadeiteFairyTimers;
29 }
30
31 /** Persist respawn-at on the character so unequip/re-equip does not clear it. */
32 export function noteJadeiteFairyDeath (world, summon, now = Date.now())
33 {
34 const respawnAt = now + JADEITE_FAIRY_RESPAWN_MS;
35 const characterId = summon?.ownerCharacterId | 0;
36 if (characterId)
37 { ensureFairyTimers(world).set(characterId, respawnAt); }
38 const ownerId = summon?.ownerEntityId;
39 if (ownerId == null)
40 { return; }
41 const ownerHandle = world.ecs.handleOf(ownerId);
42 if (ownerHandle == null)
43 { return; }
44 const character = world.ecs.get(ownerHandle, Component.character);
45 if (character)
46 { character.jadeiteFairyRespawnAt = respawnAt; }
47 }
48
49 export function jadeiteFairyRespawnAt (world, characterId, characterComponent)
50 {
51 const fromCharacter = Number(characterComponent?.jadeiteFairyRespawnAt || 0);
52 const fromWorld = Number(ensureFairyTimers(world).get(characterId) || 0);
53 return Math.max(fromCharacter, fromWorld);
54 }
55
56 export function clearJadeiteFairyRespawnIfReady (world, characterId, characterComponent, now)
57 {
58 const until = jadeiteFairyRespawnAt(world, characterId, characterComponent);
59 if (until > 0 && now >= until)
60 {
61 if (characterComponent)
62 { characterComponent.jadeiteFairyRespawnAt = null; }
63 ensureFairyTimers(world).delete(characterId);
64 return true;
65 }
66 return until <= 0;
67 }
68
69 function ownerDisplayName (world, ownerHandle)
70 {
71 const appearance = world.ecs.get(ownerHandle, Component.appearance);
72 const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
73 return name || "Adventurer";
74 }
75
76 function fairyLevelForOwner (skills)
77 {
78 const combatLevel = combatLevelFromSkills(skills);
79 return Math.max(1, Math.floor(combatLevel * JADEITE_FAIRY_LEVEL_FRACTION));
80 }
81
82 /** Build ECS components for a jadeite-amulet fairy companion. */
83 export function jadeiteFairyComponents ({
84 tileX,
85 tileY,
86 level,
87 ownerEntityId,
88 ownerCharacterId,
89 ownerName,
90 dimensionId
91 })
92 {
93 const label = `${String(ownerName || "Adventurer").trim() || "Adventurer"}'s Fairy`;
94 const components = mobComponents({
95 mobTypeId: MobId.fairy,
96 tileX,
97 tileY,
98 level,
99 dimensionId,
100 displayName: label,
101 aggressive: false
102 });
103 components.summon = {
104 kind: JADEITE_FAIRY_KIND,
105 ownerEntityId,
106 ownerCharacterId: ownerCharacterId ?? null
107 };
108 return components;
109 }
110
111 export function isJadeiteFairySummon (summon)
112 {
113 return summon?.kind === JADEITE_FAIRY_KIND;
114 }
115
116 function resolveFairyTarget (world, targetId, ownerEntityId, fairyId)
117 {
118 if (targetId == null || targetId === ownerEntityId || targetId === fairyId)
119 { return false; }
120 const handle = world.ecs.handleOf(targetId);
121 if (handle == null)
122 { return false; }
123 if (world.ecs.has(handle, Component.dead))
124 { return false; }
125 const health = world.ecs.get(handle, Component.health);
126 if (health && health.current <= 0)
127 { return false; }
128 return true;
129 }
130
131 /** Owner's target, or anything currently targeting the owner. */
132 function pickFairyTarget (world, fairyId, fairyPos, ownerEntityId)
133 {
134 const ownerHandle = world.ecs.handleOf(ownerEntityId);
135 if (ownerHandle == null || world.ecs.has(ownerHandle, Component.dead))
136 { return null; }
137
138 const ownerCombat = world.ecs.get(ownerHandle, Component.combat);
139 if (ownerCombat?.targetEntityId != null
140 && resolveFairyTarget(world, ownerCombat.targetEntityId, ownerEntityId, fairyId))
141 { return ownerCombat.targetEntityId; }
142
143 for (const entity of world.ecs.query(Component.combat, Component.creature, Component.position))
144 {
145 if (entity.entityId === fairyId || entity.entityId === ownerEntityId)
146 { continue; }
147 if (entity.combat.targetEntityId !== ownerEntityId)
148 { continue; }
149 if (world.ecs.has(entity.handle, Component.dead))
150 { continue; }
151 const dist = chebyshev(
152 fairyPos.tileX,
153 fairyPos.tileY,
154 entity.position.tileX,
155 entity.position.tileY
156 );
157 if (dist < 1)
158 { continue; }
159 if (!hasCombatLineOfSight(
160 world,
161 fairyPos.tileX,
162 fairyPos.tileY,
163 entity.position.tileX,
164 entity.position.tileY
165 ))
166 { continue; }
167 return entity.entityId;
168 }
169 return null;
170 }
171
172 function findLivingFairyForOwner (world, ownerEntityId)
173 {
174 for (const entity of world.ecs.query(Component.summon, Component.creature, Component.position))
175 {
176 if (!isJadeiteFairySummon(entity.summon))
177 { continue; }
178 if (entity.summon.ownerEntityId !== ownerEntityId)
179 { continue; }
180 if (world.ecs.has(entity.handle, Component.dead))
181 { continue; }
182 const health = world.ecs.get(entity.handle, Component.health);
183 if (health && health.current <= 0)
184 { continue; }
185 return entity;
186 }
187 return null;
188 }
189
190 function teleportFairyToOwner (world, fairy, ownerPos, now)
191 {
192 const fromTileX = fairy.position.tileX;
193 const fromTileY = fairy.position.tileY;
194 fairy.position.tileX = ownerPos.tileX;
195 fairy.position.tileY = ownerPos.tileY;
196 fairy.position.dimensionId = ownerPos.dimensionId ?? fairy.position.dimensionId;
197 const path = world.ecs.get(fairy.handle, Component.path);
198 if (path)
199 { path.tiles = []; }
200 return {
201 type: "entity-move",
202 entityId: fairy.entityId,
203 fromTileX,
204 fromTileY,
205 tileX: fairy.position.tileX,
206 tileY: fairy.position.tileY,
207 dimensionId: fairy.position.dimensionId,
208 gait: world.ecs.get(fairy.handle, Component.movement)?.gait ?? "walk",
209 lerpMs: 50
210 };
211 }
212
213 /**
214 * Maintain jadeite-amulet fairy companions: spawn / despawn / leash / combat assist.
215 * @returns {{ events: object[], despawnIds: number[] }}
216 */
217 export function stepJadeiteFairies (world, now = Date.now())
218 {
219 const events = [];
220 const despawnIds = [];
221 const ownersWithFairy = new Set();
222
223 for (const entity of world.ecs.query(Component.summon, Component.creature, Component.position))
224 {
225 if (!isJadeiteFairySummon(entity.summon))
226 { continue; }
227 const ownerEntityId = entity.summon.ownerEntityId;
228 const ownerHandle = ownerEntityId != null ? world.ecs.handleOf(ownerEntityId) : null;
229 const ownerDead = ownerHandle == null || world.ecs.has(ownerHandle, Component.dead);
230 const equipment = ownerHandle != null ? world.ecs.get(ownerHandle, Component.equipment) : null;
231 const wearing = !ownerDead && summonsJadeiteFairy(equipment);
232
233 if (!wearing)
234 {
235 despawnIds.push(entity.entityId);
236 continue;
237 }
238
239 ownersWithFairy.add(ownerEntityId);
240 const characterId = entity.summon.ownerCharacterId | 0;
241 if (characterId && world.pendingJadeiteFairySpawns)
242 { world.pendingJadeiteFairySpawns.delete(characterId); }
243 const ownerPos = world.ecs.get(ownerHandle, Component.position);
244 if (!ownerPos)
245 { continue; }
246
247 const dist = chebyshev(
248 entity.position.tileX,
249 entity.position.tileY,
250 ownerPos.tileX,
251 ownerPos.tileY
252 );
253 if (dist > CHUNK_SIZE)
254 {
255 events.push(teleportFairyToOwner(world, entity, ownerPos, now));
256 }
257 else if (dist > JADEITE_FAIRY_LEASH_TILES)
258 {
259 setFollow(world.ecs, entity.entityId, ownerEntityId);
260 }
261
262 if (world.ecs.has(entity.handle, Component.dead))
263 { continue; }
264
265 const combat = world.ecs.get(entity.handle, Component.combat);
266 if (combat?.targetEntityId != null)
267 {
268 const stillValid = resolveFairyTarget(
269 world,
270 combat.targetEntityId,
271 ownerEntityId,
272 entity.entityId
273 );
274 if (stillValid)
275 {
276 clearFollow(world.ecs, entity.entityId);
277 continue;
278 }
279 combat.targetEntityId = null;
280 }
281
282 const targetId = pickFairyTarget(world, entity.entityId, entity.position, ownerEntityId);
283 if (targetId != null)
284 {
285 clearFollow(world.ecs, entity.entityId);
286 if (ensureMobCombat(world.ecs, entity.entityId))
287 { engageTarget(world.ecs, entity.entityId, targetId, now); }
288 continue;
289 }
290
291 setFollow(world.ecs, entity.entityId, ownerEntityId);
292 }
293
294 for (const entity of world.ecs.query(Component.character, Component.equipment, Component.position, Component.skills))
295 {
296 if (world.ecs.has(entity.handle, Component.dead))
297 { continue; }
298 if (!summonsJadeiteFairy(entity.equipment))
299 { continue; }
300 if (ownersWithFairy.has(entity.entityId))
301 { continue; }
302 if (findLivingFairyForOwner(world, entity.entityId))
303 { continue; }
304
305 const characterId = entity.character.characterId | 0;
306 if (!clearJadeiteFairyRespawnIfReady(world, characterId, entity.character, now))
307 {
308 if (jadeiteFairyRespawnAt(world, characterId, entity.character) > now)
309 { continue; }
310 }
311
312 if (!world.pendingJadeiteFairySpawns)
313 { world.pendingJadeiteFairySpawns = new Map(); }
314 const pendingAt = world.pendingJadeiteFairySpawns.get(characterId);
315 if (pendingAt != null && now - pendingAt < 2000)
316 { continue; }
317 world.pendingJadeiteFairySpawns.set(characterId, now);
318
319 events.push({
320 type: "summon-entity",
321 ownerEntityId: entity.entityId,
322 ownerCharacterId: characterId || null,
323 ownerName: ownerDisplayName(world, entity.handle),
324 tileX: entity.position.tileX | 0,
325 tileY: entity.position.tileY | 0,
326 dimensionId: entity.position.dimensionId,
327 level: fairyLevelForOwner(entity.skills),
328 mobTypeId: MobId.fairy
329 });
330 }
331
332 return { events, despawnIds };
333 }
@@ -0,0 +1,333 @@
1import { Component } from "../ecs/components.js";
2import { MobId } from "../../../shared/definitions/mobs.js";
3import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
4import
5 {
6 JADEITE_FAIRY_LEASH_TILES,
7 JADEITE_FAIRY_LEVEL_FRACTION,
8 JADEITE_FAIRY_RESPAWN_MS,
9 summonsJadeiteFairy
10 } from "../../../shared/equipment/jewelryEffects.js";
11import { combatLevelFromSkills } from "../../../shared/combat/combatLevel.js";
12import
13 {
14 chebyshev,
15 engageTarget,
16 ensureMobCombat,
17 hasCombatLineOfSight
18 } from "../combat/service.js";
19import { mobComponents } from "../simulation/spawners.js";
20import { clearFollow, setFollow } from "../simulation/follow.js";
21
22export const JADEITE_FAIRY_KIND = "jadeite-fairy";
23
24function ensureFairyTimers (world)
25{
26 if (!world.jadeiteFairyTimers)
27 { world.jadeiteFairyTimers = new Map(); }
28 return world.jadeiteFairyTimers;
29}
30
31/** Persist respawn-at on the character so unequip/re-equip does not clear it. */
32export function noteJadeiteFairyDeath (world, summon, now = Date.now())
33{
34 const respawnAt = now + JADEITE_FAIRY_RESPAWN_MS;
35 const characterId = summon?.ownerCharacterId | 0;
36 if (characterId)
37 { ensureFairyTimers(world).set(characterId, respawnAt); }
38 const ownerId = summon?.ownerEntityId;
39 if (ownerId == null)
40 { return; }
41 const ownerHandle = world.ecs.handleOf(ownerId);
42 if (ownerHandle == null)
43 { return; }
44 const character = world.ecs.get(ownerHandle, Component.character);
45 if (character)
46 { character.jadeiteFairyRespawnAt = respawnAt; }
47}
48
49export function jadeiteFairyRespawnAt (world, characterId, characterComponent)
50{
51 const fromCharacter = Number(characterComponent?.jadeiteFairyRespawnAt || 0);
52 const fromWorld = Number(ensureFairyTimers(world).get(characterId) || 0);
53 return Math.max(fromCharacter, fromWorld);
54}
55
56export function clearJadeiteFairyRespawnIfReady (world, characterId, characterComponent, now)
57{
58 const until = jadeiteFairyRespawnAt(world, characterId, characterComponent);
59 if (until > 0 && now >= until)
60 {
61 if (characterComponent)
62 { characterComponent.jadeiteFairyRespawnAt = null; }
63 ensureFairyTimers(world).delete(characterId);
64 return true;
65 }
66 return until <= 0;
67}
68
69function ownerDisplayName (world, ownerHandle)
70{
71 const appearance = world.ecs.get(ownerHandle, Component.appearance);
72 const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
73 return name || "Adventurer";
74}
75
76function fairyLevelForOwner (skills)
77{
78 const combatLevel = combatLevelFromSkills(skills);
79 return Math.max(1, Math.floor(combatLevel * JADEITE_FAIRY_LEVEL_FRACTION));
80}
81
82/** Build ECS components for a jadeite-amulet fairy companion. */
83export function jadeiteFairyComponents ({
84 tileX,
85 tileY,
86 level,
87 ownerEntityId,
88 ownerCharacterId,
89 ownerName,
90 dimensionId
91})
92{
93 const label = `${String(ownerName || "Adventurer").trim() || "Adventurer"}'s Fairy`;
94 const components = mobComponents({
95 mobTypeId: MobId.fairy,
96 tileX,
97 tileY,
98 level,
99 dimensionId,
100 displayName: label,
101 aggressive: false
102 });
103 components.summon = {
104 kind: JADEITE_FAIRY_KIND,
105 ownerEntityId,
106 ownerCharacterId: ownerCharacterId ?? null
107 };
108 return components;
109}
110
111export function isJadeiteFairySummon (summon)
112{
113 return summon?.kind === JADEITE_FAIRY_KIND;
114}
115
116function resolveFairyTarget (world, targetId, ownerEntityId, fairyId)
117{
118 if (targetId == null || targetId === ownerEntityId || targetId === fairyId)
119 { return false; }
120 const handle = world.ecs.handleOf(targetId);
121 if (handle == null)
122 { return false; }
123 if (world.ecs.has(handle, Component.dead))
124 { return false; }
125 const health = world.ecs.get(handle, Component.health);
126 if (health && health.current <= 0)
127 { return false; }
128 return true;
129}
130
131/** Owner's target, or anything currently targeting the owner. */
132function pickFairyTarget (world, fairyId, fairyPos, ownerEntityId)
133{
134 const ownerHandle = world.ecs.handleOf(ownerEntityId);
135 if (ownerHandle == null || world.ecs.has(ownerHandle, Component.dead))
136 { return null; }
137
138 const ownerCombat = world.ecs.get(ownerHandle, Component.combat);
139 if (ownerCombat?.targetEntityId != null
140 && resolveFairyTarget(world, ownerCombat.targetEntityId, ownerEntityId, fairyId))
141 { return ownerCombat.targetEntityId; }
142
143 for (const entity of world.ecs.query(Component.combat, Component.creature, Component.position))
144 {
145 if (entity.entityId === fairyId || entity.entityId === ownerEntityId)
146 { continue; }
147 if (entity.combat.targetEntityId !== ownerEntityId)
148 { continue; }
149 if (world.ecs.has(entity.handle, Component.dead))
150 { continue; }
151 const dist = chebyshev(
152 fairyPos.tileX,
153 fairyPos.tileY,
154 entity.position.tileX,
155 entity.position.tileY
156 );
157 if (dist < 1)
158 { continue; }
159 if (!hasCombatLineOfSight(
160 world,
161 fairyPos.tileX,
162 fairyPos.tileY,
163 entity.position.tileX,
164 entity.position.tileY
165 ))
166 { continue; }
167 return entity.entityId;
168 }
169 return null;
170}
171
172function findLivingFairyForOwner (world, ownerEntityId)
173{
174 for (const entity of world.ecs.query(Component.summon, Component.creature, Component.position))
175 {
176 if (!isJadeiteFairySummon(entity.summon))
177 { continue; }
178 if (entity.summon.ownerEntityId !== ownerEntityId)
179 { continue; }
180 if (world.ecs.has(entity.handle, Component.dead))
181 { continue; }
182 const health = world.ecs.get(entity.handle, Component.health);
183 if (health && health.current <= 0)
184 { continue; }
185 return entity;
186 }
187 return null;
188}
189
190function teleportFairyToOwner (world, fairy, ownerPos, now)
191{
192 const fromTileX = fairy.position.tileX;
193 const fromTileY = fairy.position.tileY;
194 fairy.position.tileX = ownerPos.tileX;
195 fairy.position.tileY = ownerPos.tileY;
196 fairy.position.dimensionId = ownerPos.dimensionId ?? fairy.position.dimensionId;
197 const path = world.ecs.get(fairy.handle, Component.path);
198 if (path)
199 { path.tiles = []; }
200 return {
201 type: "entity-move",
202 entityId: fairy.entityId,
203 fromTileX,
204 fromTileY,
205 tileX: fairy.position.tileX,
206 tileY: fairy.position.tileY,
207 dimensionId: fairy.position.dimensionId,
208 gait: world.ecs.get(fairy.handle, Component.movement)?.gait ?? "walk",
209 lerpMs: 50
210 };
211}
212
213/**
214 * Maintain jadeite-amulet fairy companions: spawn / despawn / leash / combat assist.
215 * @returns {{ events: object[], despawnIds: number[] }}
216 */
217export function stepJadeiteFairies (world, now = Date.now())
218{
219 const events = [];
220 const despawnIds = [];
221 const ownersWithFairy = new Set();
222
223 for (const entity of world.ecs.query(Component.summon, Component.creature, Component.position))
224 {
225 if (!isJadeiteFairySummon(entity.summon))
226 { continue; }
227 const ownerEntityId = entity.summon.ownerEntityId;
228 const ownerHandle = ownerEntityId != null ? world.ecs.handleOf(ownerEntityId) : null;
229 const ownerDead = ownerHandle == null || world.ecs.has(ownerHandle, Component.dead);
230 const equipment = ownerHandle != null ? world.ecs.get(ownerHandle, Component.equipment) : null;
231 const wearing = !ownerDead && summonsJadeiteFairy(equipment);
232
233 if (!wearing)
234 {
235 despawnIds.push(entity.entityId);
236 continue;
237 }
238
239 ownersWithFairy.add(ownerEntityId);
240 const characterId = entity.summon.ownerCharacterId | 0;
241 if (characterId && world.pendingJadeiteFairySpawns)
242 { world.pendingJadeiteFairySpawns.delete(characterId); }
243 const ownerPos = world.ecs.get(ownerHandle, Component.position);
244 if (!ownerPos)
245 { continue; }
246
247 const dist = chebyshev(
248 entity.position.tileX,
249 entity.position.tileY,
250 ownerPos.tileX,
251 ownerPos.tileY
252 );
253 if (dist > CHUNK_SIZE)
254 {
255 events.push(teleportFairyToOwner(world, entity, ownerPos, now));
256 }
257 else if (dist > JADEITE_FAIRY_LEASH_TILES)
258 {
259 setFollow(world.ecs, entity.entityId, ownerEntityId);
260 }
261
262 if (world.ecs.has(entity.handle, Component.dead))
263 { continue; }
264
265 const combat = world.ecs.get(entity.handle, Component.combat);
266 if (combat?.targetEntityId != null)
267 {
268 const stillValid = resolveFairyTarget(
269 world,
270 combat.targetEntityId,
271 ownerEntityId,
272 entity.entityId
273 );
274 if (stillValid)
275 {
276 clearFollow(world.ecs, entity.entityId);
277 continue;
278 }
279 combat.targetEntityId = null;
280 }
281
282 const targetId = pickFairyTarget(world, entity.entityId, entity.position, ownerEntityId);
283 if (targetId != null)
284 {
285 clearFollow(world.ecs, entity.entityId);
286 if (ensureMobCombat(world.ecs, entity.entityId))
287 { engageTarget(world.ecs, entity.entityId, targetId, now); }
288 continue;
289 }
290
291 setFollow(world.ecs, entity.entityId, ownerEntityId);
292 }
293
294 for (const entity of world.ecs.query(Component.character, Component.equipment, Component.position, Component.skills))
295 {
296 if (world.ecs.has(entity.handle, Component.dead))
297 { continue; }
298 if (!summonsJadeiteFairy(entity.equipment))
299 { continue; }
300 if (ownersWithFairy.has(entity.entityId))
301 { continue; }
302 if (findLivingFairyForOwner(world, entity.entityId))
303 { continue; }
304
305 const characterId = entity.character.characterId | 0;
306 if (!clearJadeiteFairyRespawnIfReady(world, characterId, entity.character, now))
307 {
308 if (jadeiteFairyRespawnAt(world, characterId, entity.character) > now)
309 { continue; }
310 }
311
312 if (!world.pendingJadeiteFairySpawns)
313 { world.pendingJadeiteFairySpawns = new Map(); }
314 const pendingAt = world.pendingJadeiteFairySpawns.get(characterId);
315 if (pendingAt != null && now - pendingAt < 2000)
316 { continue; }
317 world.pendingJadeiteFairySpawns.set(characterId, now);
318
319 events.push({
320 type: "summon-entity",
321 ownerEntityId: entity.entityId,
322 ownerCharacterId: characterId || null,
323 ownerName: ownerDisplayName(world, entity.handle),
324 tileX: entity.position.tileX | 0,
325 tileY: entity.position.tileY | 0,
326 dimensionId: entity.position.dimensionId,
327 level: fairyLevelForOwner(entity.skills),
328 mobTypeId: MobId.fairy
329 });
330 }
331
332 return { events, despawnIds };
333}
server/src/spells/summons.js +6 −1
@@ -14,6 +14,7 @@ const SHADE_AGGRO_RANGE = 12;
14 14
15 15 /**
16 16 * Expire summons and pick combat targets for Shade companions.
17 * Jadeite fairies are handled by {@link stepJadeiteFairies}.
17 18 * @returns {{ events: object[], despawnIds: number[] }}
18 19 */
19 20 export function stepSummons (world, now = Date.now())
@@ -23,7 +24,11 @@ export function stepSummons (world, now = Date.now())
23 24 for (const entity of world.ecs.query(Component.summon, Component.creature, Component.position))
24 25 {
25 26 const { handle, entityId, summon, position } = entity;
26 if (now >= Number(summon.expiresAt || 0))
27 if (summon?.kind === "jadeite-fairy")
28 { continue; }
29 if (summon.expiresAt == null)
30 { continue; }
31 if (now >= Number(summon.expiresAt))
27 32 {
28 33 despawnIds.push(entityId);
29 34 continue;
@@ -14,6 +14,7 @@ const SHADE_AGGRO_RANGE = 12;
14
14
15/**
15/**
16 * Expire summons and pick combat targets for Shade companions.
16 * Expire summons and pick combat targets for Shade companions.
17 * Jadeite fairies are handled by {@link stepJadeiteFairies}.
17 * @returns {{ events: object[], despawnIds: number[] }}
18 * @returns {{ events: object[], despawnIds: number[] }}
18 */
19 */
19export function stepSummons (world, now = Date.now())
20export function stepSummons (world, now = Date.now())
@@ -23,7 +24,11 @@ export function stepSummons (world, now = Date.now())
23 for (const entity of world.ecs.query(Component.summon, Component.creature, Component.position))
24 for (const entity of world.ecs.query(Component.summon, Component.creature, Component.position))
24 {
25 {
25 const { handle, entityId, summon, position } = entity;
26 const { handle, entityId, summon, position } = entity;
26 if (now >= Number(summon.expiresAt || 0))
27 if (summon?.kind === "jadeite-fairy")
28 { continue; }
29 if (summon.expiresAt == null)
30 { continue; }
31 if (now >= Number(summon.expiresAt))
27 {
32 {
28 despawnIds.push(entityId);
33 despawnIds.push(entityId);
29 continue;
34 continue;
server/tests/jadeite-fairy-jewelry-teleport.test.js added +162 −0
@@ -0,0 +1,162 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { JewelryItemId } from "../../shared/definitions/jewelryItems.js";
4 import { MobId, mobLevelDisplayName } from "../../shared/definitions/mobs.js";
5 import { EQUIPMENT_SLOT } from "../../shared/definitions/items.js";
6 import { JADEITE_FAIRY_RESPAWN_MS, JEWELRY_TELEPORT_MS } from "../../shared/equipment/jewelryEffects.js";
7 import { Component } from "../src/ecs/components.js";
8 import { applyDamageAndKill } from "../src/combat/service.js";
9 import
10 {
11 jadeiteFairyComponents,
12 stepJadeiteFairies,
13 jadeiteFairyRespawnAt
14 } from "../src/spells/jadeiteFairy.js";
15 import
16 {
17 startJewelryTeleport,
18 stepJewelryTeleports,
19 JewelryTeleportDestination
20 } from "../src/equipment/jewelryTeleport.js";
21 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
22
23 function workerOf (simulation, entityId)
24 {
25 const record = simulation.entityRecord(entityId);
26 assert.ok(record, "entity must be remembered");
27 return simulation.workers[record.workerId];
28 }
29
30 function equipJewelry (world, entityId, slot, itemId)
31 {
32 const handle = world.ecs.handleOf(entityId);
33 const equipment = world.ecs.get(handle, Component.equipment);
34 equipment.slots[slot] = itemId == null ? null : { itemId, quantity: 1 };
35 }
36
37 test("jadeite fairy spawn uses owner name and level fraction", () =>
38 {
39 const components = jadeiteFairyComponents({
40 tileX: 8,
41 tileY: 8,
42 level: 12,
43 ownerEntityId: 1,
44 ownerCharacterId: 9,
45 ownerName: "Ada Worker"
46 });
47 assert.equal(components.creature.mobTypeId, MobId.fairy);
48 assert.equal(components.appearance.firstName, "Ada Worker's Fairy");
49 assert.equal(components.summon.kind, "jadeite-fairy");
50 assert.equal(components.spawnOrigin, undefined);
51 assert.equal(mobLevelDisplayName(12, "Fairy"), "Lv.12 Fairy");
52 });
53
54 test("jadeite fairy respawn timer survives unequip and despawn", () =>
55 {
56 const harness = makeSimulation({ workerCount: 1 });
57 try
58 {
59 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ada" });
60 const playerId = harness.simulation.spawnCharacter(1, character);
61 const worker = workerOf(harness.simulation, playerId);
62 const world = worker.world;
63 equipJewelry(world, playerId, EQUIPMENT_SLOT.amulet, JewelryItemId.jadeiteAmulet);
64
65 const t0 = harness.now();
66 let result = stepJadeiteFairies(world, t0);
67 assert.ok(result.events.some((event) => event.type === "summon-entity" && event.mobTypeId === MobId.fairy));
68
69 const fairyId = harness.simulation.spawnEntity(jadeiteFairyComponents({
70 tileX: 9,
71 tileY: 8,
72 level: 2,
73 ownerEntityId: playerId,
74 ownerCharacterId: character.character_id,
75 ownerName: "Ada"
76 }));
77 const fairyHandle = world.ecs.handleOf(fairyId);
78 const hp = world.ecs.get(fairyHandle, Component.health)?.max ?? 10;
79 applyDamageAndKill(world, playerId, fairyId, hp, t0);
80
81 const characterComp = world.ecs.get(world.ecs.handleOf(playerId), Component.character);
82 const until = jadeiteFairyRespawnAt(world, character.character_id, characterComp);
83 assert.ok(until >= t0 + JADEITE_FAIRY_RESPAWN_MS);
84
85 // Unequip / re-equip must not clear the timer.
86 equipJewelry(world, playerId, EQUIPMENT_SLOT.amulet, null);
87 result = stepJadeiteFairies(world, t0 + 1000);
88 assert.equal(result.events.some((event) => event.type === "summon-entity"), false);
89 assert.equal(
90 jadeiteFairyRespawnAt(world, character.character_id, characterComp),
91 until
92 );
93
94 equipJewelry(world, playerId, EQUIPMENT_SLOT.amulet, JewelryItemId.jadeiteAmulet);
95 result = stepJadeiteFairies(world, t0 + 1000);
96 assert.equal(result.events.some((event) => event.type === "summon-entity"), false);
97
98 result = stepJadeiteFairies(world, until);
99 assert.ok(result.events.some((event) => event.type === "summon-entity"));
100 }
101 finally
102 { harness.close(); }
103 });
104
105 test("jewelry teleport requires emerald bracelet or ruby ring", () =>
106 {
107 const harness = makeSimulation({ workerCount: 1 });
108 try
109 {
110 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
111 const playerId = harness.simulation.spawnCharacter(1, character);
112 const worker = workerOf(harness.simulation, playerId);
113 const world = worker.world;
114 const sessionId = 1;
115 const now = harness.now();
116
117 assert.throws(
118 () => startJewelryTeleport(world, sessionId, character.character_id, "church", now),
119 /emerald bracelet/i
120 );
121 assert.throws(
122 () => startJewelryTeleport(world, sessionId, character.character_id, "bank", now),
123 /ruby ring/i
124 );
125
126 equipJewelry(world, playerId, EQUIPMENT_SLOT.bracelet, JewelryItemId.emeraldBracelet);
127 startJewelryTeleport(
128 world,
129 sessionId,
130 character.character_id,
131 JewelryTeleportDestination.church,
132 now
133 );
134 assert.equal(stepJewelryTeleports(world, now + JEWELRY_TELEPORT_MS - 1).events.length, 0);
135 const finished = stepJewelryTeleports(world, now + JEWELRY_TELEPORT_MS);
136 assert.equal(finished.events.length, 1);
137 assert.equal(finished.events[0].type, "jewelry-teleport-finish");
138 assert.equal(finished.events[0].destination, "church");
139 }
140 finally
141 { harness.close(); }
142 });
143
144 test("jewelry teleport channel cancels on move", () =>
145 {
146 const harness = makeSimulation({ workerCount: 1 });
147 try
148 {
149 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
150 const playerId = harness.simulation.spawnCharacter(1, character);
151 const worker = workerOf(harness.simulation, playerId);
152 const world = worker.world;
153 equipJewelry(world, playerId, EQUIPMENT_SLOT.ring, JewelryItemId.rubyRing);
154 const now = harness.now();
155 startJewelryTeleport(world, 1, character.character_id, "bank", now);
156 const path = world.ecs.get(world.ecs.handleOf(playerId), Component.path);
157 path.tiles = [{ x: 9, y: 8 }];
158 assert.equal(stepJewelryTeleports(world, now + JEWELRY_TELEPORT_MS).events.length, 0);
159 }
160 finally
161 { harness.close(); }
162 });
@@ -0,0 +1,162 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { JewelryItemId } from "../../shared/definitions/jewelryItems.js";
4import { MobId, mobLevelDisplayName } from "../../shared/definitions/mobs.js";
5import { EQUIPMENT_SLOT } from "../../shared/definitions/items.js";
6import { JADEITE_FAIRY_RESPAWN_MS, JEWELRY_TELEPORT_MS } from "../../shared/equipment/jewelryEffects.js";
7import { Component } from "../src/ecs/components.js";
8import { applyDamageAndKill } from "../src/combat/service.js";
9import
10 {
11 jadeiteFairyComponents,
12 stepJadeiteFairies,
13 jadeiteFairyRespawnAt
14 } from "../src/spells/jadeiteFairy.js";
15import
16 {
17 startJewelryTeleport,
18 stepJewelryTeleports,
19 JewelryTeleportDestination
20 } from "../src/equipment/jewelryTeleport.js";
21import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
22
23function workerOf (simulation, entityId)
24{
25 const record = simulation.entityRecord(entityId);
26 assert.ok(record, "entity must be remembered");
27 return simulation.workers[record.workerId];
28}
29
30function equipJewelry (world, entityId, slot, itemId)
31{
32 const handle = world.ecs.handleOf(entityId);
33 const equipment = world.ecs.get(handle, Component.equipment);
34 equipment.slots[slot] = itemId == null ? null : { itemId, quantity: 1 };
35}
36
37test("jadeite fairy spawn uses owner name and level fraction", () =>
38{
39 const components = jadeiteFairyComponents({
40 tileX: 8,
41 tileY: 8,
42 level: 12,
43 ownerEntityId: 1,
44 ownerCharacterId: 9,
45 ownerName: "Ada Worker"
46 });
47 assert.equal(components.creature.mobTypeId, MobId.fairy);
48 assert.equal(components.appearance.firstName, "Ada Worker's Fairy");
49 assert.equal(components.summon.kind, "jadeite-fairy");
50 assert.equal(components.spawnOrigin, undefined);
51 assert.equal(mobLevelDisplayName(12, "Fairy"), "Lv.12 Fairy");
52});
53
54test("jadeite fairy respawn timer survives unequip and despawn", () =>
55{
56 const harness = makeSimulation({ workerCount: 1 });
57 try
58 {
59 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ada" });
60 const playerId = harness.simulation.spawnCharacter(1, character);
61 const worker = workerOf(harness.simulation, playerId);
62 const world = worker.world;
63 equipJewelry(world, playerId, EQUIPMENT_SLOT.amulet, JewelryItemId.jadeiteAmulet);
64
65 const t0 = harness.now();
66 let result = stepJadeiteFairies(world, t0);
67 assert.ok(result.events.some((event) => event.type === "summon-entity" && event.mobTypeId === MobId.fairy));
68
69 const fairyId = harness.simulation.spawnEntity(jadeiteFairyComponents({
70 tileX: 9,
71 tileY: 8,
72 level: 2,
73 ownerEntityId: playerId,
74 ownerCharacterId: character.character_id,
75 ownerName: "Ada"
76 }));
77 const fairyHandle = world.ecs.handleOf(fairyId);
78 const hp = world.ecs.get(fairyHandle, Component.health)?.max ?? 10;
79 applyDamageAndKill(world, playerId, fairyId, hp, t0);
80
81 const characterComp = world.ecs.get(world.ecs.handleOf(playerId), Component.character);
82 const until = jadeiteFairyRespawnAt(world, character.character_id, characterComp);
83 assert.ok(until >= t0 + JADEITE_FAIRY_RESPAWN_MS);
84
85 // Unequip / re-equip must not clear the timer.
86 equipJewelry(world, playerId, EQUIPMENT_SLOT.amulet, null);
87 result = stepJadeiteFairies(world, t0 + 1000);
88 assert.equal(result.events.some((event) => event.type === "summon-entity"), false);
89 assert.equal(
90 jadeiteFairyRespawnAt(world, character.character_id, characterComp),
91 until
92 );
93
94 equipJewelry(world, playerId, EQUIPMENT_SLOT.amulet, JewelryItemId.jadeiteAmulet);
95 result = stepJadeiteFairies(world, t0 + 1000);
96 assert.equal(result.events.some((event) => event.type === "summon-entity"), false);
97
98 result = stepJadeiteFairies(world, until);
99 assert.ok(result.events.some((event) => event.type === "summon-entity"));
100 }
101 finally
102 { harness.close(); }
103});
104
105test("jewelry teleport requires emerald bracelet or ruby ring", () =>
106{
107 const harness = makeSimulation({ workerCount: 1 });
108 try
109 {
110 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
111 const playerId = harness.simulation.spawnCharacter(1, character);
112 const worker = workerOf(harness.simulation, playerId);
113 const world = worker.world;
114 const sessionId = 1;
115 const now = harness.now();
116
117 assert.throws(
118 () => startJewelryTeleport(world, sessionId, character.character_id, "church", now),
119 /emerald bracelet/i
120 );
121 assert.throws(
122 () => startJewelryTeleport(world, sessionId, character.character_id, "bank", now),
123 /ruby ring/i
124 );
125
126 equipJewelry(world, playerId, EQUIPMENT_SLOT.bracelet, JewelryItemId.emeraldBracelet);
127 startJewelryTeleport(
128 world,
129 sessionId,
130 character.character_id,
131 JewelryTeleportDestination.church,
132 now
133 );
134 assert.equal(stepJewelryTeleports(world, now + JEWELRY_TELEPORT_MS - 1).events.length, 0);
135 const finished = stepJewelryTeleports(world, now + JEWELRY_TELEPORT_MS);
136 assert.equal(finished.events.length, 1);
137 assert.equal(finished.events[0].type, "jewelry-teleport-finish");
138 assert.equal(finished.events[0].destination, "church");
139 }
140 finally
141 { harness.close(); }
142});
143
144test("jewelry teleport channel cancels on move", () =>
145{
146 const harness = makeSimulation({ workerCount: 1 });
147 try
148 {
149 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
150 const playerId = harness.simulation.spawnCharacter(1, character);
151 const worker = workerOf(harness.simulation, playerId);
152 const world = worker.world;
153 equipJewelry(world, playerId, EQUIPMENT_SLOT.ring, JewelryItemId.rubyRing);
154 const now = harness.now();
155 startJewelryTeleport(world, 1, character.character_id, "bank", now);
156 const path = world.ecs.get(world.ecs.handleOf(playerId), Component.path);
157 path.tiles = [{ x: 9, y: 8 }];
158 assert.equal(stepJewelryTeleports(world, now + JEWELRY_TELEPORT_MS).events.length, 0);
159 }
160 finally
161 { harness.close(); }
162});
server/tests/jewelry.test.js +33 −0
@@ -9,6 +9,14 @@ import { GatherMaterialId, GemTier } from "../../shared/definitions/materialTier
9 9 import { resolveItemDualTint } from "../../shared/render/tint.js";
10 10 import { EQUIPMENT_SLOTS, emptyEquipment } from "../../shared/items/inventory.js";
11 11 import { recipeDefinition } from "../../shared/crafting/recipes.js";
12 import
13 {
14 JADEITE_FAIRY_RESPAWN_MS,
15 JEWELRY_TELEPORT_MS,
16 canTeleportToBank,
17 canTeleportToChurch,
18 summonsJadeiteFairy
19 } from "../../shared/equipment/jewelryEffects.js";
12 20
13 21 test("equipment slots include ring bracelet amulet", () =>
14 22 {
@@ -62,3 +70,28 @@ test("jewellery dual tint maps metal gem and yarn channels", () =>
62 70 assert.equal(itemDefinition(JewelryItemId.diamondBracelet)?.equipment?.slot, EQUIPMENT_SLOT.bracelet);
63 71 assert.equal(ItemId.diamondRing, JewelryItemId.diamondRing);
64 72 });
73
74 test("jadeite fairy and jewelry teleport helpers gate on worn pieces", () =>
75 {
76 assert.equal(JADEITE_FAIRY_RESPAWN_MS, 60_000);
77 assert.equal(JEWELRY_TELEPORT_MS, 3000);
78 const empty = emptyEquipment();
79 assert.equal(summonsJadeiteFairy(empty), false);
80 assert.equal(canTeleportToChurch(empty), false);
81 assert.equal(canTeleportToBank(empty), false);
82
83 const withFairy = emptyEquipment();
84 withFairy.slots.amulet = { itemId: JewelryItemId.jadeiteAmulet, quantity: 1 };
85 assert.equal(summonsJadeiteFairy(withFairy), true);
86 assert.equal(canTeleportToChurch(withFairy), false);
87
88 const withChurch = emptyEquipment();
89 withChurch.slots.bracelet = { itemId: JewelryItemId.emeraldBracelet, quantity: 1 };
90 assert.equal(canTeleportToChurch(withChurch), true);
91 assert.equal(canTeleportToBank(withChurch), false);
92
93 const withBank = emptyEquipment();
94 withBank.slots.ring = { itemId: JewelryItemId.rubyRing, quantity: 1 };
95 assert.equal(canTeleportToBank(withBank), true);
96 assert.equal(canTeleportToChurch(withBank), false);
97 });
@@ -9,6 +9,14 @@ import { GatherMaterialId, GemTier } from "../../shared/definitions/materialTier
9import { resolveItemDualTint } from "../../shared/render/tint.js";
9import { resolveItemDualTint } from "../../shared/render/tint.js";
10import { EQUIPMENT_SLOTS, emptyEquipment } from "../../shared/items/inventory.js";
10import { EQUIPMENT_SLOTS, emptyEquipment } from "../../shared/items/inventory.js";
11import { recipeDefinition } from "../../shared/crafting/recipes.js";
11import { recipeDefinition } from "../../shared/crafting/recipes.js";
12import
13 {
14 JADEITE_FAIRY_RESPAWN_MS,
15 JEWELRY_TELEPORT_MS,
16 canTeleportToBank,
17 canTeleportToChurch,
18 summonsJadeiteFairy
19 } from "../../shared/equipment/jewelryEffects.js";
12
20
13test("equipment slots include ring bracelet amulet", () =>
21test("equipment slots include ring bracelet amulet", () =>
14{
22{
@@ -62,3 +70,28 @@ test("jewellery dual tint maps metal gem and yarn channels", () =>
62 assert.equal(itemDefinition(JewelryItemId.diamondBracelet)?.equipment?.slot, EQUIPMENT_SLOT.bracelet);
70 assert.equal(itemDefinition(JewelryItemId.diamondBracelet)?.equipment?.slot, EQUIPMENT_SLOT.bracelet);
63 assert.equal(ItemId.diamondRing, JewelryItemId.diamondRing);
71 assert.equal(ItemId.diamondRing, JewelryItemId.diamondRing);
64});
72});
73
74test("jadeite fairy and jewelry teleport helpers gate on worn pieces", () =>
75{
76 assert.equal(JADEITE_FAIRY_RESPAWN_MS, 60_000);
77 assert.equal(JEWELRY_TELEPORT_MS, 3000);
78 const empty = emptyEquipment();
79 assert.equal(summonsJadeiteFairy(empty), false);
80 assert.equal(canTeleportToChurch(empty), false);
81 assert.equal(canTeleportToBank(empty), false);
82
83 const withFairy = emptyEquipment();
84 withFairy.slots.amulet = { itemId: JewelryItemId.jadeiteAmulet, quantity: 1 };
85 assert.equal(summonsJadeiteFairy(withFairy), true);
86 assert.equal(canTeleportToChurch(withFairy), false);
87
88 const withChurch = emptyEquipment();
89 withChurch.slots.bracelet = { itemId: JewelryItemId.emeraldBracelet, quantity: 1 };
90 assert.equal(canTeleportToChurch(withChurch), true);
91 assert.equal(canTeleportToBank(withChurch), false);
92
93 const withBank = emptyEquipment();
94 withBank.slots.ring = { itemId: JewelryItemId.rubyRing, quantity: 1 };
95 assert.equal(canTeleportToBank(withBank), true);
96 assert.equal(canTeleportToChurch(withBank), false);
97});
shared/equipment/jewelryEffects.js added +229 −0
@@ -0,0 +1,229 @@
1 import { JewelryItemId } from "../definitions/jewelryItems.js";
2 import { EQUIPMENT_SLOT, itemDefinition } from "../definitions/items.js";
3 import { AttackType, MAGIC_ELEMENT_ORDER } from "../definitions/attackTypes.js";
4 import { ALL_SKILL_IDS, skillLevel } from "../definitions/skills.js";
5 import { tierMinSkillLevel } from "../definitions/materialTiers.js";
6 import { EquipmentKind } from "../definitions/equipmentKinds.js";
7
8 /** Torch block range; opal bracelet uses the same radius at half intensity. */
9 export const OPAL_NIGHT_VISION_RANGE_TILES = 8;
10 export const OPAL_NIGHT_VISION_INTENSITY = 0.5;
11
12 export const JEWELRY_TELEPORT_MS = 3000;
13 export const JADEITE_FAIRY_RESPAWN_MS = 60_000;
14 export const JADEITE_FAIRY_LEASH_TILES = 8;
15 export const JADEITE_FAIRY_LEVEL_FRACTION = 0.6;
16
17 function slotItemId (equipment, slot)
18 {
19 return equipment?.slots?.[slot]?.itemId ?? null;
20 }
21
22 export function wornJewelryIds (equipment)
23 {
24 return {
25 ring: slotItemId(equipment, EQUIPMENT_SLOT.ring),
26 bracelet: slotItemId(equipment, EQUIPMENT_SLOT.bracelet),
27 amulet: slotItemId(equipment, EQUIPMENT_SLOT.amulet)
28 };
29 }
30
31 export function isWearingJewelry (equipment, itemId)
32 {
33 const worn = wornJewelryIds(equipment);
34 return worn.ring === itemId || worn.bracelet === itemId || worn.amulet === itemId;
35 }
36
37 /** Combat level required to wear a jewellery piece (same tier curve as Magic gates). */
38 export function jewelryMinCombatLevel (itemDef)
39 {
40 const equipment = itemDef?.equipment;
41 if (!equipment || equipment.kind !== EquipmentKind.jewelry)
42 { return null; }
43 return equipment.minCombatLevel ?? tierMinSkillLevel(equipment.tier);
44 }
45
46 export function passiveHpRegenMultiplier (equipment)
47 {
48 return isWearingJewelry(equipment, JewelryItemId.tourmalineRing) ? 2 : 1;
49 }
50
51 export function passiveStaminaRegenMultiplier (equipment)
52 {
53 return isWearingJewelry(equipment, JewelryItemId.tourmalineBracelet) ? 2 : 1;
54 }
55
56 /** Double XP only for the wearer's current lowest skill. */
57 export function skillXpMultiplier (equipment, skills, skillId)
58 {
59 if (!isWearingJewelry(equipment, JewelryItemId.tourmalineAmulet))
60 { return 1; }
61 let lowest = Infinity;
62 let lowestIds = [];
63 for (const id of ALL_SKILL_IDS)
64 {
65 const level = skillLevel(skills, id);
66 if (level < lowest)
67 {
68 lowest = level;
69 lowestIds = [id];
70 }
71 else if (level === lowest)
72 { lowestIds.push(id); }
73 }
74 return lowestIds.includes(skillId) ? 2 : 1;
75 }
76
77 export function craftDurationMultiplier (equipment)
78 {
79 return isWearingJewelry(equipment, JewelryItemId.alexandriteBracelet) ? 0.5 : 1;
80 }
81
82 export function gatherDurationMultiplier (equipment)
83 {
84 return isWearingJewelry(equipment, JewelryItemId.alexandriteAmulet) ? 0.5 : 1;
85 }
86
87 export function harvestYieldMultiplier (equipment)
88 {
89 return isWearingJewelry(equipment, JewelryItemId.jadeiteRing) ? 2 : 1;
90 }
91
92 export function maxHealthMultiplier (equipment)
93 {
94 return isWearingJewelry(equipment, JewelryItemId.rubyBracelet) ? 1.1 : 1;
95 }
96
97 export function hitSkillBonus (equipment)
98 {
99 return isWearingJewelry(equipment, JewelryItemId.emeraldAmulet) ? 1 : 0;
100 }
101
102 export function damageReflectFraction (equipment)
103 {
104 return isWearingJewelry(equipment, JewelryItemId.opalAmulet) ? 0.1 : 0;
105 }
106
107 export function autoLootOnKill (equipment)
108 {
109 return isWearingJewelry(equipment, JewelryItemId.diamondAmulet);
110 }
111
112 export function dropAmuletInsteadOfCoins (equipment)
113 {
114 return isWearingJewelry(equipment, JewelryItemId.rubyAmulet);
115 }
116
117 export function ignoresNonBossAggro (equipment)
118 {
119 return isWearingJewelry(equipment, JewelryItemId.jadeiteBracelet);
120 }
121
122 export function summonsJadeiteFairy (equipment)
123 {
124 return isWearingJewelry(equipment, JewelryItemId.jadeiteAmulet);
125 }
126
127 export function canTeleportToChurch (equipment)
128 {
129 return isWearingJewelry(equipment, JewelryItemId.emeraldBracelet);
130 }
131
132 export function canTeleportToBank (equipment)
133 {
134 return isWearingJewelry(equipment, JewelryItemId.rubyRing);
135 }
136
137 /**
138 * Lucky attacker rolls (diamond bracelet): bias toward high outcomes.
139 * Unlucky defender-facing rolls (emerald ring): bias enemy to-hit toward low.
140 */
141 export function attackerToHitRng (equipment, rng = Math.random)
142 {
143 if (!isWearingJewelry(equipment, JewelryItemId.diamondBracelet))
144 { return rng; }
145 return () => 1 - Math.pow(1 - rng(), 2);
146 }
147
148 export function attackerSpellCastRng (equipment, rng = Math.random)
149 {
150 return attackerToHitRng(equipment, rng);
151 }
152
153 export function enemyToHitRngAgainst (defenderEquipment, rng = Math.random)
154 {
155 if (!isWearingJewelry(defenderEquipment, JewelryItemId.emeraldRing))
156 { return rng; }
157 return () => Math.pow(rng(), 1.75);
158 }
159
160 /** Affinity map merged onto the wearer's defence (resistant = half damage). */
161 export function jewelryDamageAffinities (equipment)
162 {
163 const affinities = {};
164 if (isWearingJewelry(equipment, JewelryItemId.alexandriteRing))
165 {
166 for (const element of MAGIC_ELEMENT_ORDER)
167 { affinities[element] = "resistant"; }
168 }
169 if (isWearingJewelry(equipment, JewelryItemId.opalRing))
170 { affinities[AttackType.piercing] = "resistant"; }
171 if (isWearingJewelry(equipment, JewelryItemId.diamondRing))
172 {
173 affinities[AttackType.blunt] = "resistant";
174 affinities[AttackType.slashing] = "resistant";
175 affinities[AttackType.crushing] = "resistant";
176 affinities[AttackType.chopping] = "resistant";
177 }
178 return affinities;
179 }
180
181 export function mergeAffinities (...maps)
182 {
183 const out = {};
184 for (const map of maps)
185 {
186 if (!map)
187 { continue; }
188 for (const [key, value] of Object.entries(map))
189 {
190 if (value === "weak" || (value === "resistant" && out[key] !== "weak"))
191 { out[key] = value; }
192 else if (!out[key])
193 { out[key] = value; }
194 }
195 }
196 return out;
197 }
198
199 export function nightVisionLight (equipment)
200 {
201 if (!isWearingJewelry(equipment, JewelryItemId.opalBracelet))
202 { return null; }
203 return {
204 lightRadiusTiles: OPAL_NIGHT_VISION_RANGE_TILES,
205 lightIntensity: OPAL_NIGHT_VISION_INTENSITY
206 };
207 }
208
209 export function jewelryEffectsFromEquipment (equipment)
210 {
211 return {
212 passiveHpRegenMult: passiveHpRegenMultiplier(equipment),
213 passiveStaminaRegenMult: passiveStaminaRegenMultiplier(equipment),
214 craftDurationMult: craftDurationMultiplier(equipment),
215 gatherDurationMult: gatherDurationMultiplier(equipment),
216 harvestYieldMult: harvestYieldMultiplier(equipment),
217 maxHealthMult: maxHealthMultiplier(equipment),
218 hitBonus: hitSkillBonus(equipment),
219 reflectFraction: damageReflectFraction(equipment),
220 autoLoot: autoLootOnKill(equipment),
221 keepCoinsDropAmulet: dropAmuletInsteadOfCoins(equipment),
222 ignoreNonBossAggro: ignoresNonBossAggro(equipment),
223 jadeiteFairy: summonsJadeiteFairy(equipment),
224 teleportChurch: canTeleportToChurch(equipment),
225 teleportBank: canTeleportToBank(equipment),
226 affinities: jewelryDamageAffinities(equipment),
227 nightVision: nightVisionLight(equipment)
228 };
229 }
@@ -0,0 +1,229 @@
1import { JewelryItemId } from "../definitions/jewelryItems.js";
2import { EQUIPMENT_SLOT, itemDefinition } from "../definitions/items.js";
3import { AttackType, MAGIC_ELEMENT_ORDER } from "../definitions/attackTypes.js";
4import { ALL_SKILL_IDS, skillLevel } from "../definitions/skills.js";
5import { tierMinSkillLevel } from "../definitions/materialTiers.js";
6import { EquipmentKind } from "../definitions/equipmentKinds.js";
7
8/** Torch block range; opal bracelet uses the same radius at half intensity. */
9export const OPAL_NIGHT_VISION_RANGE_TILES = 8;
10export const OPAL_NIGHT_VISION_INTENSITY = 0.5;
11
12export const JEWELRY_TELEPORT_MS = 3000;
13export const JADEITE_FAIRY_RESPAWN_MS = 60_000;
14export const JADEITE_FAIRY_LEASH_TILES = 8;
15export const JADEITE_FAIRY_LEVEL_FRACTION = 0.6;
16
17function slotItemId (equipment, slot)
18{
19 return equipment?.slots?.[slot]?.itemId ?? null;
20}
21
22export function wornJewelryIds (equipment)
23{
24 return {
25 ring: slotItemId(equipment, EQUIPMENT_SLOT.ring),
26 bracelet: slotItemId(equipment, EQUIPMENT_SLOT.bracelet),
27 amulet: slotItemId(equipment, EQUIPMENT_SLOT.amulet)
28 };
29}
30
31export function isWearingJewelry (equipment, itemId)
32{
33 const worn = wornJewelryIds(equipment);
34 return worn.ring === itemId || worn.bracelet === itemId || worn.amulet === itemId;
35}
36
37/** Combat level required to wear a jewellery piece (same tier curve as Magic gates). */
38export function jewelryMinCombatLevel (itemDef)
39{
40 const equipment = itemDef?.equipment;
41 if (!equipment || equipment.kind !== EquipmentKind.jewelry)
42 { return null; }
43 return equipment.minCombatLevel ?? tierMinSkillLevel(equipment.tier);
44}
45
46export function passiveHpRegenMultiplier (equipment)
47{
48 return isWearingJewelry(equipment, JewelryItemId.tourmalineRing) ? 2 : 1;
49}
50
51export function passiveStaminaRegenMultiplier (equipment)
52{
53 return isWearingJewelry(equipment, JewelryItemId.tourmalineBracelet) ? 2 : 1;
54}
55
56/** Double XP only for the wearer's current lowest skill. */
57export function skillXpMultiplier (equipment, skills, skillId)
58{
59 if (!isWearingJewelry(equipment, JewelryItemId.tourmalineAmulet))
60 { return 1; }
61 let lowest = Infinity;
62 let lowestIds = [];
63 for (const id of ALL_SKILL_IDS)
64 {
65 const level = skillLevel(skills, id);
66 if (level < lowest)
67 {
68 lowest = level;
69 lowestIds = [id];
70 }
71 else if (level === lowest)
72 { lowestIds.push(id); }
73 }
74 return lowestIds.includes(skillId) ? 2 : 1;
75}
76
77export function craftDurationMultiplier (equipment)
78{
79 return isWearingJewelry(equipment, JewelryItemId.alexandriteBracelet) ? 0.5 : 1;
80}
81
82export function gatherDurationMultiplier (equipment)
83{
84 return isWearingJewelry(equipment, JewelryItemId.alexandriteAmulet) ? 0.5 : 1;
85}
86
87export function harvestYieldMultiplier (equipment)
88{
89 return isWearingJewelry(equipment, JewelryItemId.jadeiteRing) ? 2 : 1;
90}
91
92export function maxHealthMultiplier (equipment)
93{
94 return isWearingJewelry(equipment, JewelryItemId.rubyBracelet) ? 1.1 : 1;
95}
96
97export function hitSkillBonus (equipment)
98{
99 return isWearingJewelry(equipment, JewelryItemId.emeraldAmulet) ? 1 : 0;
100}
101
102export function damageReflectFraction (equipment)
103{
104 return isWearingJewelry(equipment, JewelryItemId.opalAmulet) ? 0.1 : 0;
105}
106
107export function autoLootOnKill (equipment)
108{
109 return isWearingJewelry(equipment, JewelryItemId.diamondAmulet);
110}
111
112export function dropAmuletInsteadOfCoins (equipment)
113{
114 return isWearingJewelry(equipment, JewelryItemId.rubyAmulet);
115}
116
117export function ignoresNonBossAggro (equipment)
118{
119 return isWearingJewelry(equipment, JewelryItemId.jadeiteBracelet);
120}
121
122export function summonsJadeiteFairy (equipment)
123{
124 return isWearingJewelry(equipment, JewelryItemId.jadeiteAmulet);
125}
126
127export function canTeleportToChurch (equipment)
128{
129 return isWearingJewelry(equipment, JewelryItemId.emeraldBracelet);
130}
131
132export function canTeleportToBank (equipment)
133{
134 return isWearingJewelry(equipment, JewelryItemId.rubyRing);
135}
136
137/**
138 * Lucky attacker rolls (diamond bracelet): bias toward high outcomes.
139 * Unlucky defender-facing rolls (emerald ring): bias enemy to-hit toward low.
140 */
141export function attackerToHitRng (equipment, rng = Math.random)
142{
143 if (!isWearingJewelry(equipment, JewelryItemId.diamondBracelet))
144 { return rng; }
145 return () => 1 - Math.pow(1 - rng(), 2);
146}
147
148export function attackerSpellCastRng (equipment, rng = Math.random)
149{
150 return attackerToHitRng(equipment, rng);
151}
152
153export function enemyToHitRngAgainst (defenderEquipment, rng = Math.random)
154{
155 if (!isWearingJewelry(defenderEquipment, JewelryItemId.emeraldRing))
156 { return rng; }
157 return () => Math.pow(rng(), 1.75);
158}
159
160/** Affinity map merged onto the wearer's defence (resistant = half damage). */
161export function jewelryDamageAffinities (equipment)
162{
163 const affinities = {};
164 if (isWearingJewelry(equipment, JewelryItemId.alexandriteRing))
165 {
166 for (const element of MAGIC_ELEMENT_ORDER)
167 { affinities[element] = "resistant"; }
168 }
169 if (isWearingJewelry(equipment, JewelryItemId.opalRing))
170 { affinities[AttackType.piercing] = "resistant"; }
171 if (isWearingJewelry(equipment, JewelryItemId.diamondRing))
172 {
173 affinities[AttackType.blunt] = "resistant";
174 affinities[AttackType.slashing] = "resistant";
175 affinities[AttackType.crushing] = "resistant";
176 affinities[AttackType.chopping] = "resistant";
177 }
178 return affinities;
179}
180
181export function mergeAffinities (...maps)
182{
183 const out = {};
184 for (const map of maps)
185 {
186 if (!map)
187 { continue; }
188 for (const [key, value] of Object.entries(map))
189 {
190 if (value === "weak" || (value === "resistant" && out[key] !== "weak"))
191 { out[key] = value; }
192 else if (!out[key])
193 { out[key] = value; }
194 }
195 }
196 return out;
197}
198
199export function nightVisionLight (equipment)
200{
201 if (!isWearingJewelry(equipment, JewelryItemId.opalBracelet))
202 { return null; }
203 return {
204 lightRadiusTiles: OPAL_NIGHT_VISION_RANGE_TILES,
205 lightIntensity: OPAL_NIGHT_VISION_INTENSITY
206 };
207}
208
209export function jewelryEffectsFromEquipment (equipment)
210{
211 return {
212 passiveHpRegenMult: passiveHpRegenMultiplier(equipment),
213 passiveStaminaRegenMult: passiveStaminaRegenMultiplier(equipment),
214 craftDurationMult: craftDurationMultiplier(equipment),
215 gatherDurationMult: gatherDurationMultiplier(equipment),
216 harvestYieldMult: harvestYieldMultiplier(equipment),
217 maxHealthMult: maxHealthMultiplier(equipment),
218 hitBonus: hitSkillBonus(equipment),
219 reflectFraction: damageReflectFraction(equipment),
220 autoLoot: autoLootOnKill(equipment),
221 keepCoinsDropAmulet: dropAmuletInsteadOfCoins(equipment),
222 ignoreNonBossAggro: ignoresNonBossAggro(equipment),
223 jadeiteFairy: summonsJadeiteFairy(equipment),
224 teleportChurch: canTeleportToChurch(equipment),
225 teleportBank: canTeleportToBank(equipment),
226 affinities: jewelryDamageAffinities(equipment),
227 nightVision: nightVisionLight(equipment)
228 };
229}
shared/protocol/constants.js +2 −1
@@ -280,6 +280,7 @@ export const MessageType = Object.freeze({
280 280 dialogueItemRewards: "DIALOGUE_ITEM_REWARDS",
281 281 requestQuests: "REQUEST_QUESTS",
282 282 questsSnapshot: "QUESTS_SNAPSHOT",
283 questStepComplete: "QUEST_STEP_COMPLETE"
283 questStepComplete: "QUEST_STEP_COMPLETE",
284 jewelryTeleport: "JEWELRY_TELEPORT"
284 285 });
285 286
@@ -280,6 +280,7 @@ export const MessageType = Object.freeze({
280 dialogueItemRewards: "DIALOGUE_ITEM_REWARDS",
280 dialogueItemRewards: "DIALOGUE_ITEM_REWARDS",
281 requestQuests: "REQUEST_QUESTS",
281 requestQuests: "REQUEST_QUESTS",
282 questsSnapshot: "QUESTS_SNAPSHOT",
282 questsSnapshot: "QUESTS_SNAPSHOT",
283 questStepComplete: "QUEST_STEP_COMPLETE"
283 questStepComplete: "QUEST_STEP_COMPLETE",
284 jewelryTeleport: "JEWELRY_TELEPORT"
284});
285});
285
286