BlueGit

timfa questward

jewelerty, skulls

timfa Tim Falken · pushed by timfa

Authored 2026-08-29 · 2 months ago

Hash
2b6e44d0d293fae144ad37e7f72569f6daa1ca8e
Parent
87524d95
36 files changed +1458 −350
client/assets/blocks/jewelering-station/jewelering-station.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/fx/skull/skull.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/gems/cut.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/gems/rough.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/skills/jewelering.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#5a6a80"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">JW</text></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#5a6a80"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">JW</text></svg>
client/src/editor/tileConfigModal.js +2 −2
@@ -943,7 +943,7 @@ export function initTileConfigModal ({
943 943 field("Level", numberInput("level", config.level ?? 1, 1, 99)),
944 944 field("Bounty", numberInput("bounty", config.bounty ?? 0, 0, 1_000_000)),
945 945 field("Max alive", numberInput("maxAlive", config.maxAlive, 1, 20)),
946 field("Respawn delay (seconds)", numberInput("respawnDelaySeconds", config.respawnDelaySeconds ?? 0, 0, 86_400)),
946 field("Respawn delay (seconds)", numberInput("respawnDelaySeconds", config.respawnDelaySeconds ?? 25, 0, 86_400)),
947 947 field("Spawn range", numberInput("spawnRangeTiles", config.spawnRangeTiles, 1, 32)),
948 948 field("Max wander range", numberInput("maxWanderRangeTiles", config.maxWanderRangeTiles, 1, 64)),
949 949 field("Spawner id", textInput("spawnerId", config.spawnerId, true))
@@ -1110,7 +1110,7 @@ export function initTileConfigModal ({
1110 1110 onSave?.(context, normalizeSpawnerConfig({
1111 1111 mobTypeId: String(data.get("mobTypeId") || "deer"),
1112 1112 maxAlive: Number(data.get("maxAlive") || 3),
1113 respawnDelaySeconds: Number(data.get("respawnDelaySeconds") || 0),
1113 respawnDelaySeconds: Number(data.get("respawnDelaySeconds") ?? 25),
1114 1114 spawnRangeTiles: Number(data.get("spawnRangeTiles") || 4),
1115 1115 maxWanderRangeTiles: Number(data.get("maxWanderRangeTiles") || 4),
1116 1116 level: Number(data.get("level") || 1),
@@ -943,7 +943,7 @@ export function initTileConfigModal ({
943 field("Level", numberInput("level", config.level ?? 1, 1, 99)),
943 field("Level", numberInput("level", config.level ?? 1, 1, 99)),
944 field("Bounty", numberInput("bounty", config.bounty ?? 0, 0, 1_000_000)),
944 field("Bounty", numberInput("bounty", config.bounty ?? 0, 0, 1_000_000)),
945 field("Max alive", numberInput("maxAlive", config.maxAlive, 1, 20)),
945 field("Max alive", numberInput("maxAlive", config.maxAlive, 1, 20)),
946 field("Respawn delay (seconds)", numberInput("respawnDelaySeconds", config.respawnDelaySeconds ?? 0, 0, 86_400)),
946 field("Respawn delay (seconds)", numberInput("respawnDelaySeconds", config.respawnDelaySeconds ?? 25, 0, 86_400)),
947 field("Spawn range", numberInput("spawnRangeTiles", config.spawnRangeTiles, 1, 32)),
947 field("Spawn range", numberInput("spawnRangeTiles", config.spawnRangeTiles, 1, 32)),
948 field("Max wander range", numberInput("maxWanderRangeTiles", config.maxWanderRangeTiles, 1, 64)),
948 field("Max wander range", numberInput("maxWanderRangeTiles", config.maxWanderRangeTiles, 1, 64)),
949 field("Spawner id", textInput("spawnerId", config.spawnerId, true))
949 field("Spawner id", textInput("spawnerId", config.spawnerId, true))
@@ -1110,7 +1110,7 @@ export function initTileConfigModal ({
1110 onSave?.(context, normalizeSpawnerConfig({
1110 onSave?.(context, normalizeSpawnerConfig({
1111 mobTypeId: String(data.get("mobTypeId") || "deer"),
1111 mobTypeId: String(data.get("mobTypeId") || "deer"),
1112 maxAlive: Number(data.get("maxAlive") || 3),
1112 maxAlive: Number(data.get("maxAlive") || 3),
1113 respawnDelaySeconds: Number(data.get("respawnDelaySeconds") || 0),
1113 respawnDelaySeconds: Number(data.get("respawnDelaySeconds") ?? 25),
1114 spawnRangeTiles: Number(data.get("spawnRangeTiles") || 4),
1114 spawnRangeTiles: Number(data.get("spawnRangeTiles") || 4),
1115 maxWanderRangeTiles: Number(data.get("maxWanderRangeTiles") || 4),
1115 maxWanderRangeTiles: Number(data.get("maxWanderRangeTiles") || 4),
1116 level: Number(data.get("level") || 1),
1116 level: Number(data.get("level") || 1),
client/src/play/main.js +37 −3
@@ -827,6 +827,8 @@ function handleLeftClick (mouseX, mouseY)
827 827 { requestFish(tile.tileX, tile.tileY); }
828 828 else if (isAnvilTile(view, tile.tileX, tile.tileY))
829 829 { requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); }
830 else if (isJeweleringStationTile(view, tile.tileX, tile.tileY))
831 { requestOpenCraftStation(CraftingStationId.jeweleringStation, tile.tileX, tile.tileY); }
830 832 else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
831 833 { requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); }
832 834 else if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
@@ -1029,6 +1031,14 @@ function handleRightClick (event, mouseX, mouseY)
1029 1031 });
1030 1032 }
1031 1033
1034 if (isJeweleringStationTile(view, tile.tileX, tile.tileY))
1035 {
1036 items.push({
1037 label: "Jewel",
1038 onSelect: () => requestOpenCraftStation(CraftingStationId.jeweleringStation, tile.tileX, tile.tileY)
1039 });
1040 }
1041
1032 1042 if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
1033 1043 {
1034 1044 items.push({
@@ -1252,8 +1262,13 @@ function startPlay (payload)
1252 1262 payload.characterId,
1253 1263 payload.layers,
1254 1264 payload.health,
1255 payload.maxHealth
1265 payload.maxHealth,
1266 payload.skullValue
1256 1267 );
1268 social?.setLocalIdentity?.({
1269 accountId: payload.accountId,
1270 characterId: payload.characterId
1271 });
1257 1272 graphicsSettingsUi?.apply();
1258 1273 }
1259 1274
@@ -1325,7 +1340,11 @@ async function main ()
1325 1340 });
1326 1341 social = initSocial({
1327 1342 socket: { send (payload) { socket.send(payload); } },
1328 MessageType
1343 MessageType,
1344 resolveSpriteUrl (name)
1345 {
1346 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1347 }
1329 1348 });
1330 1349 contextMenu = initContextMenu({ onSuppressWorldClick: consumeWorldClick });
1331 1350 inventory = initInventory({
@@ -1543,6 +1562,9 @@ async function main ()
1543 1562 case MessageType.entityAppearance:
1544 1563 view?.setAppearance(message);
1545 1564 break;
1565 case MessageType.entitySkull:
1566 view?.updateEntitySkull(message.entityId, message.skullValue);
1567 break;
1546 1568 case MessageType.groundItemAppear:
1547 1569 view?.upsertGroundItem(message);
1548 1570 break;
@@ -2047,6 +2069,11 @@ function isAnvilTile (view, tileX, tileY)
2047 2069 return blockTypeAt(view, tileX, tileY) === BlockType.anvil;
2048 2070 }
2049 2071
2072 function isJeweleringStationTile (view, tileX, tileY)
2073 {
2074 return blockTypeAt(view, tileX, tileY) === BlockType.jeweleringStation;
2075 }
2076
2050 2077 function isGroundWoodLog (ground)
2051 2078 {
2052 2079 const def = itemDefinition(ground?.itemId ?? ground?.stack?.itemId);
@@ -2143,7 +2170,11 @@ function updateSpellTargetHighlight ()
2143 2170 function hideWorldTooltip ()
2144 2171 {
2145 2172 if (worldTooltip)
2146 { worldTooltip.hidden = true; }
2173 {
2174 worldTooltip.hidden = true;
2175 worldTooltip.classList.remove("friend-name");
2176 worldTooltip.style.color = "";
2177 }
2147 2178 }
2148 2179
2149 2180 /** Cursor tip for gatherable resource nodes (ores now; trees / fish / herbs later). */
@@ -2169,6 +2200,9 @@ function updateWorldTooltip ()
2169 2200 const label = entityLabel(entity);
2170 2201 worldTooltip.hidden = false;
2171 2202 worldTooltip.textContent = label;
2203 const friend = entity.characterId && social?.isFriendCharacter?.(entity.characterId, entity.accountId);
2204 worldTooltip.classList.toggle("friend-name", !!friend);
2205 worldTooltip.style.color = friend ? "#e8c84a" : "";
2172 2206 worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
2173 2207 worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
2174 2208 return;
@@ -827,6 +827,8 @@ function handleLeftClick (mouseX, mouseY)
827 { requestFish(tile.tileX, tile.tileY); }
827 { requestFish(tile.tileX, tile.tileY); }
828 else if (isAnvilTile(view, tile.tileX, tile.tileY))
828 else if (isAnvilTile(view, tile.tileX, tile.tileY))
829 { requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); }
829 { requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); }
830 else if (isJeweleringStationTile(view, tile.tileX, tile.tileY))
831 { requestOpenCraftStation(CraftingStationId.jeweleringStation, tile.tileX, tile.tileY); }
830 else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
832 else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
831 { requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); }
833 { requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); }
832 else if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
834 else if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
@@ -1029,6 +1031,14 @@ function handleRightClick (event, mouseX, mouseY)
1029 });
1031 });
1030 }
1032 }
1031
1033
1034 if (isJeweleringStationTile(view, tile.tileX, tile.tileY))
1035 {
1036 items.push({
1037 label: "Jewel",
1038 onSelect: () => requestOpenCraftStation(CraftingStationId.jeweleringStation, tile.tileX, tile.tileY)
1039 });
1040 }
1041
1032 if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
1042 if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
1033 {
1043 {
1034 items.push({
1044 items.push({
@@ -1252,8 +1262,13 @@ function startPlay (payload)
1252 payload.characterId,
1262 payload.characterId,
1253 payload.layers,
1263 payload.layers,
1254 payload.health,
1264 payload.health,
1255 payload.maxHealth
1265 payload.maxHealth,
1266 payload.skullValue
1256 );
1267 );
1268 social?.setLocalIdentity?.({
1269 accountId: payload.accountId,
1270 characterId: payload.characterId
1271 });
1257 graphicsSettingsUi?.apply();
1272 graphicsSettingsUi?.apply();
1258}
1273}
1259
1274
@@ -1325,7 +1340,11 @@ async function main ()
1325 });
1340 });
1326 social = initSocial({
1341 social = initSocial({
1327 socket: { send (payload) { socket.send(payload); } },
1342 socket: { send (payload) { socket.send(payload); } },
1328 MessageType
1343 MessageType,
1344 resolveSpriteUrl (name)
1345 {
1346 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1347 }
1329 });
1348 });
1330 contextMenu = initContextMenu({ onSuppressWorldClick: consumeWorldClick });
1349 contextMenu = initContextMenu({ onSuppressWorldClick: consumeWorldClick });
1331 inventory = initInventory({
1350 inventory = initInventory({
@@ -1543,6 +1562,9 @@ async function main ()
1543 case MessageType.entityAppearance:
1562 case MessageType.entityAppearance:
1544 view?.setAppearance(message);
1563 view?.setAppearance(message);
1545 break;
1564 break;
1565 case MessageType.entitySkull:
1566 view?.updateEntitySkull(message.entityId, message.skullValue);
1567 break;
1546 case MessageType.groundItemAppear:
1568 case MessageType.groundItemAppear:
1547 view?.upsertGroundItem(message);
1569 view?.upsertGroundItem(message);
1548 break;
1570 break;
@@ -2047,6 +2069,11 @@ function isAnvilTile (view, tileX, tileY)
2047 return blockTypeAt(view, tileX, tileY) === BlockType.anvil;
2069 return blockTypeAt(view, tileX, tileY) === BlockType.anvil;
2048}
2070}
2049
2071
2072function isJeweleringStationTile (view, tileX, tileY)
2073{
2074 return blockTypeAt(view, tileX, tileY) === BlockType.jeweleringStation;
2075}
2076
2050function isGroundWoodLog (ground)
2077function isGroundWoodLog (ground)
2051{
2078{
2052 const def = itemDefinition(ground?.itemId ?? ground?.stack?.itemId);
2079 const def = itemDefinition(ground?.itemId ?? ground?.stack?.itemId);
@@ -2143,7 +2170,11 @@ function updateSpellTargetHighlight ()
2143function hideWorldTooltip ()
2170function hideWorldTooltip ()
2144{
2171{
2145 if (worldTooltip)
2172 if (worldTooltip)
2146 { worldTooltip.hidden = true; }
2173 {
2174 worldTooltip.hidden = true;
2175 worldTooltip.classList.remove("friend-name");
2176 worldTooltip.style.color = "";
2177 }
2147}
2178}
2148
2179
2149/** Cursor tip for gatherable resource nodes (ores now; trees / fish / herbs later). */
2180/** Cursor tip for gatherable resource nodes (ores now; trees / fish / herbs later). */
@@ -2169,6 +2200,9 @@ function updateWorldTooltip ()
2169 const label = entityLabel(entity);
2200 const label = entityLabel(entity);
2170 worldTooltip.hidden = false;
2201 worldTooltip.hidden = false;
2171 worldTooltip.textContent = label;
2202 worldTooltip.textContent = label;
2203 const friend = entity.characterId && social?.isFriendCharacter?.(entity.characterId, entity.accountId);
2204 worldTooltip.classList.toggle("friend-name", !!friend);
2205 worldTooltip.style.color = friend ? "#e8c84a" : "";
2172 worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
2206 worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
2173 worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
2207 worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
2174 return;
2208 return;
client/src/play/social.js +185 −48
@@ -1,4 +1,6 @@
1 export function initSocial ({ socket, MessageType })
1 const FRIEND_NAME_COLOR = "#e8c84a";
2
3 export function initSocial ({ socket, MessageType, resolveSpriteUrl = null })
2 4 {
3 5 const nametag = document.getElementById("nametag");
4 6 const inspect = document.getElementById("inspect-modal");
@@ -14,6 +16,10 @@ export function initSocial ({ socket, MessageType })
14 16 let social = { friends: [], incoming: [], outgoing: [] };
15 17 let inspected = null;
16 18 let open = false;
19 /** @type {number|null} expanded friend account in the panel */
20 let expandedAccountId = null;
21 let localAccountId = null;
22 let localCharacterId = null;
17 23
18 24 document.getElementById("inspect-close").addEventListener("click", () => hideInspect());
19 25 inspectBackdrop.addEventListener("click", () => hideInspect());
@@ -36,46 +42,91 @@ export function initSocial ({ socket, MessageType })
36 42 }
37 43 }
38 44
45 function friendAccountOfCharacter (characterId)
46 {
47 const id = characterId | 0;
48 for (const account of social.friends ?? [])
49 {
50 if ((account.characters ?? []).some((entry) => entry.characterId === id))
51 { return account; }
52 }
53 return null;
54 }
55
56 function isFriendCharacter (characterId, accountId = null)
57 {
58 const id = characterId | 0;
59 if (!id)
60 { return false; }
61 if (localAccountId && accountId && (accountId | 0) === (localAccountId | 0) && id !== (localCharacterId | 0))
62 { return true; }
63 return !!friendAccountOfCharacter(id);
64 }
65
39 66 function relation (characterId)
40 67 {
41 if (social.friends.some((entry) => entry.characterId === characterId))
68 if (isFriendCharacter(characterId))
42 69 { return "friends"; }
43 if (social.incoming.some((entry) => entry.characterId === characterId))
70 const account = accountHoldingCharacter(characterId, social.incoming);
71 if (account)
44 72 { return "incoming"; }
45 if (social.outgoing.some((entry) => entry.characterId === characterId))
73 if (accountHoldingCharacter(characterId, social.outgoing))
46 74 { return "outgoing"; }
47 75 return "none";
48 76 }
49 77
78 function accountHoldingCharacter (characterId, accounts)
79 {
80 const id = characterId | 0;
81 return (accounts ?? []).find((account) =>
82 (account.characters ?? []).some((entry) => entry.characterId === id)) ?? null;
83 }
84
50 85 function renderInspect ()
51 86 {
52 87 if (!inspected)
53 88 { return; }
54 89 inspectName.textContent = `${inspected.firstName} ${inspected.lastName}`;
90 inspectName.style.color = isFriendCharacter(inspected.characterId, inspected.accountId) ? FRIEND_NAME_COLOR : "";
55 91 inspectAction.replaceChildren();
56 92 const status = relation(inspected.characterId);
93 const friendAccount = friendAccountOfCharacter(inspected.characterId);
57 94 if (status === "friends")
58 95 {
59 96 inspectAction.append(actionButton("Remove friend", () =>
60 97 {
61 socket.send({ type: MessageType.friendRemove, characterId: inspected.characterId });
98 socket.send({
99 type: MessageType.friendRemove,
100 accountId: friendAccount?.accountId,
101 characterId: inspected.characterId
102 });
62 103 }));
63 104 }
64 105 else if (status === "incoming")
65 106 {
107 const incoming = accountHoldingCharacter(inspected.characterId, social.incoming);
66 108 inspectAction.append(
67 109 actionButton("Accept friend request", () =>
68 110 {
69 socket.send({ type: MessageType.friendAccept, characterId: inspected.characterId });
111 socket.send({
112 type: MessageType.friendAccept,
113 accountId: incoming?.accountId,
114 characterId: inspected.characterId
115 });
70 116 }),
71 117 actionButton("Decline", () =>
72 118 {
73 socket.send({ type: MessageType.friendDecline, characterId: inspected.characterId });
119 socket.send({
120 type: MessageType.friendDecline,
121 accountId: incoming?.accountId,
122 characterId: inspected.characterId
123 });
74 124 })
75 125 );
76 126 }
77 127 else if (status === "outgoing")
78 128 {
129 const outgoing = accountHoldingCharacter(inspected.characterId, social.outgoing);
79 130 const pending = document.createElement("p");
80 131 pending.className = "hint";
81 132 pending.textContent = "Friend request sent.";
@@ -83,7 +134,11 @@ export function initSocial ({ socket, MessageType })
83 134 pending,
84 135 actionButton("Cancel request", () =>
85 136 {
86 socket.send({ type: MessageType.friendDecline, characterId: inspected.characterId });
137 socket.send({
138 type: MessageType.friendDecline,
139 accountId: outgoing?.accountId,
140 characterId: inspected.characterId
141 });
87 142 })
88 143 );
89 144 }
@@ -98,39 +153,109 @@ export function initSocial ({ socket, MessageType })
98 153
99 154 function renderLists ()
100 155 {
101 fillList(friendsList, social.friends, "No friends yet.", (entry) =>
156 fillList(friendsList, social.friends, "No friends yet.", (account) => accountRow(account, {
157 expanded: expandedAccountId === account.accountId,
158 onToggle ()
159 {
160 expandedAccountId = expandedAccountId === account.accountId ? null : account.accountId;
161 renderLists();
162 },
163 onRemove ()
164 {
165 socket.send({ type: MessageType.friendRemove, accountId: account.accountId });
166 }
167 }));
168 fillList(incomingList, social.incoming, "No incoming requests.", (account) => accountRequestRow(account, {
169 onAccept ()
170 {
171 socket.send({ type: MessageType.friendAccept, accountId: account.accountId });
172 },
173 onDecline ()
174 {
175 socket.send({ type: MessageType.friendDecline, accountId: account.accountId });
176 }
177 }));
178 fillList(outgoingList, social.outgoing, "No outgoing requests.", (account) => accountRequestRow(account, {
179 onDecline ()
180 {
181 socket.send({ type: MessageType.friendDecline, accountId: account.accountId });
182 },
183 declineLabel: "Cancel"
184 }));
185 }
186
187 function accountRow (account, { expanded, onToggle, onRemove })
188 {
189 const wrap = document.createElement("div");
190 wrap.className = "friend-account";
191 const header = document.createElement("div");
192 header.className = "social-row friend-account-header";
193 const nameBtn = document.createElement("button");
194 nameBtn.type = "button";
195 nameBtn.className = "friend-account-name";
196 nameBtn.textContent = account.username || `Account ${account.accountId}`;
197 nameBtn.addEventListener("click", onToggle);
198 header.append(nameBtn, actionButton("Remove", onRemove));
199 wrap.append(header);
200 if (expanded)
102 201 {
103 const row = namedRow(entry);
104 row.append(actionButton("Remove", () =>
202 const list = document.createElement("div");
203 list.className = "friend-character-list";
204 for (const character of account.characters ?? [])
205 { list.append(characterPreviewRow(character)); }
206 if (!(account.characters ?? []).length)
105 207 {
106 socket.send({ type: MessageType.friendRemove, characterId: entry.characterId });
107 }));
108 return row;
109 });
110 fillList(incomingList, social.incoming, "No incoming requests.", (entry) =>
208 const empty = document.createElement("p");
209 empty.className = "hint";
210 empty.textContent = "No characters.";
211 list.append(empty);
212 }
213 wrap.append(list);
214 }
215 return wrap;
216 }
217
218 function accountRequestRow (account, { onAccept = null, onDecline, declineLabel = "Decline" })
219 {
220 const row = document.createElement("div");
221 row.className = "social-row";
222 const name = document.createElement("span");
223 name.textContent = account.username || `Account ${account.accountId}`;
224 row.append(name);
225 if (onAccept)
226 { row.append(actionButton("Accept", onAccept)); }
227 row.append(actionButton(declineLabel, onDecline));
228 return row;
229 }
230
231 function characterPreviewRow (entry)
232 {
233 const row = document.createElement("div");
234 row.className = "friend-character-row";
235 row.append(characterPreview(entry.layers), (() =>
111 236 {
112 const row = namedRow(entry);
113 row.append(
114 actionButton("Accept", () =>
115 {
116 socket.send({ type: MessageType.friendAccept, characterId: entry.characterId });
117 }),
118 actionButton("Decline", () =>
119 {
120 socket.send({ type: MessageType.friendDecline, characterId: entry.characterId });
121 })
122 );
123 return row;
124 });
125 fillList(outgoingList, social.outgoing, "No outgoing requests.", (entry) =>
237 const name = document.createElement("span");
238 name.textContent = `${entry.firstName} ${entry.lastName}`.trim();
239 return name;
240 })());
241 return row;
242 }
243
244 function characterPreview (layers)
245 {
246 const wrap = document.createElement("div");
247 wrap.className = "char-preview friend-char-preview";
248 for (const layer of layers ?? [])
126 249 {
127 const row = namedRow(entry);
128 row.append(actionButton("Cancel", () =>
129 {
130 socket.send({ type: MessageType.friendDecline, characterId: entry.characterId });
131 }));
132 return row;
133 });
250 const url = resolveSpriteUrl?.(layer.sprite);
251 if (!url)
252 { continue; }
253 const img = document.createElement("img");
254 img.src = url;
255 img.alt = "";
256 wrap.append(img);
257 }
258 return wrap;
134 259 }
135 260
136 261 return {
@@ -158,13 +283,31 @@ export function initSocial ({ socket, MessageType })
158 283 incoming: message.incoming ?? [],
159 284 outgoing: message.outgoing ?? []
160 285 };
286 if (
287 expandedAccountId != null
288 && !(social.friends ?? []).some((account) => account.accountId === expandedAccountId)
289 )
290 { expandedAccountId = null; }
161 291 renderLists();
162 292 if (open)
163 293 { renderInspect(); }
164 294 },
295 /** Flat character list for pigeon send targets. */
165 296 getFriends ()
166 297 {
167 return social.friends ?? [];
298 const out = [];
299 for (const account of social.friends ?? [])
300 {
301 for (const character of account.characters ?? [])
302 { out.push(character); }
303 }
304 return out;
305 },
306 isFriendCharacter,
307 setLocalIdentity ({ accountId = null, characterId = null } = {})
308 {
309 localAccountId = accountId | 0 || null;
310 localCharacterId = characterId | 0 || null;
168 311 },
169 312 inspect (entity)
170 313 {
@@ -172,6 +315,7 @@ export function initSocial ({ socket, MessageType })
172 315 { return; }
173 316 inspected = {
174 317 characterId: entity.characterId,
318 accountId: entity.accountId ?? null,
175 319 firstName: entity.firstName ?? "",
176 320 lastName: entity.lastName ?? ""
177 321 };
@@ -240,6 +384,9 @@ export function initSocial ({ socket, MessageType })
240 384 }
241 385 nametag.hidden = false;
242 386 nametag.textContent = entity.firstName;
387 const friend = entity.characterId && isFriendCharacter(entity.characterId, entity.accountId);
388 nametag.classList.toggle("friend-name", !!friend);
389 nametag.style.color = friend ? FRIEND_NAME_COLOR : "";
243 390 nametag.style.left = `${rect.left + anchor.x}px`;
244 391 nametag.style.top = `${rect.top + anchor.y - 6}px`;
245 392 canvas.style.cursor = "pointer";
@@ -252,16 +399,6 @@ export function initSocial ({ socket, MessageType })
252 399 };
253 400 }
254 401
255 function namedRow (entry)
256 {
257 const row = document.createElement("div");
258 row.className = "social-row";
259 const name = document.createElement("span");
260 name.textContent = `${entry.firstName} ${entry.lastName}`;
261 row.append(name);
262 return row;
263 }
264
265 402 function fillList (root, entries, emptyText, renderRow)
266 403 {
267 404 root.replaceChildren();
@@ -1,4 +1,6 @@
1export function initSocial ({ socket, MessageType })
1const FRIEND_NAME_COLOR = "#e8c84a";
2
3export function initSocial ({ socket, MessageType, resolveSpriteUrl = null })
2{
4{
3 const nametag = document.getElementById("nametag");
5 const nametag = document.getElementById("nametag");
4 const inspect = document.getElementById("inspect-modal");
6 const inspect = document.getElementById("inspect-modal");
@@ -14,6 +16,10 @@ export function initSocial ({ socket, MessageType })
14 let social = { friends: [], incoming: [], outgoing: [] };
16 let social = { friends: [], incoming: [], outgoing: [] };
15 let inspected = null;
17 let inspected = null;
16 let open = false;
18 let open = false;
19 /** @type {number|null} expanded friend account in the panel */
20 let expandedAccountId = null;
21 let localAccountId = null;
22 let localCharacterId = null;
17
23
18 document.getElementById("inspect-close").addEventListener("click", () => hideInspect());
24 document.getElementById("inspect-close").addEventListener("click", () => hideInspect());
19 inspectBackdrop.addEventListener("click", () => hideInspect());
25 inspectBackdrop.addEventListener("click", () => hideInspect());
@@ -36,46 +42,91 @@ export function initSocial ({ socket, MessageType })
36 }
42 }
37 }
43 }
38
44
45 function friendAccountOfCharacter (characterId)
46 {
47 const id = characterId | 0;
48 for (const account of social.friends ?? [])
49 {
50 if ((account.characters ?? []).some((entry) => entry.characterId === id))
51 { return account; }
52 }
53 return null;
54 }
55
56 function isFriendCharacter (characterId, accountId = null)
57 {
58 const id = characterId | 0;
59 if (!id)
60 { return false; }
61 if (localAccountId && accountId && (accountId | 0) === (localAccountId | 0) && id !== (localCharacterId | 0))
62 { return true; }
63 return !!friendAccountOfCharacter(id);
64 }
65
39 function relation (characterId)
66 function relation (characterId)
40 {
67 {
41 if (social.friends.some((entry) => entry.characterId === characterId))
68 if (isFriendCharacter(characterId))
42 { return "friends"; }
69 { return "friends"; }
43 if (social.incoming.some((entry) => entry.characterId === characterId))
70 const account = accountHoldingCharacter(characterId, social.incoming);
71 if (account)
44 { return "incoming"; }
72 { return "incoming"; }
45 if (social.outgoing.some((entry) => entry.characterId === characterId))
73 if (accountHoldingCharacter(characterId, social.outgoing))
46 { return "outgoing"; }
74 { return "outgoing"; }
47 return "none";
75 return "none";
48 }
76 }
49
77
78 function accountHoldingCharacter (characterId, accounts)
79 {
80 const id = characterId | 0;
81 return (accounts ?? []).find((account) =>
82 (account.characters ?? []).some((entry) => entry.characterId === id)) ?? null;
83 }
84
50 function renderInspect ()
85 function renderInspect ()
51 {
86 {
52 if (!inspected)
87 if (!inspected)
53 { return; }
88 { return; }
54 inspectName.textContent = `${inspected.firstName} ${inspected.lastName}`;
89 inspectName.textContent = `${inspected.firstName} ${inspected.lastName}`;
90 inspectName.style.color = isFriendCharacter(inspected.characterId, inspected.accountId) ? FRIEND_NAME_COLOR : "";
55 inspectAction.replaceChildren();
91 inspectAction.replaceChildren();
56 const status = relation(inspected.characterId);
92 const status = relation(inspected.characterId);
93 const friendAccount = friendAccountOfCharacter(inspected.characterId);
57 if (status === "friends")
94 if (status === "friends")
58 {
95 {
59 inspectAction.append(actionButton("Remove friend", () =>
96 inspectAction.append(actionButton("Remove friend", () =>
60 {
97 {
61 socket.send({ type: MessageType.friendRemove, characterId: inspected.characterId });
98 socket.send({
99 type: MessageType.friendRemove,
100 accountId: friendAccount?.accountId,
101 characterId: inspected.characterId
102 });
62 }));
103 }));
63 }
104 }
64 else if (status === "incoming")
105 else if (status === "incoming")
65 {
106 {
107 const incoming = accountHoldingCharacter(inspected.characterId, social.incoming);
66 inspectAction.append(
108 inspectAction.append(
67 actionButton("Accept friend request", () =>
109 actionButton("Accept friend request", () =>
68 {
110 {
69 socket.send({ type: MessageType.friendAccept, characterId: inspected.characterId });
111 socket.send({
112 type: MessageType.friendAccept,
113 accountId: incoming?.accountId,
114 characterId: inspected.characterId
115 });
70 }),
116 }),
71 actionButton("Decline", () =>
117 actionButton("Decline", () =>
72 {
118 {
73 socket.send({ type: MessageType.friendDecline, characterId: inspected.characterId });
119 socket.send({
120 type: MessageType.friendDecline,
121 accountId: incoming?.accountId,
122 characterId: inspected.characterId
123 });
74 })
124 })
75 );
125 );
76 }
126 }
77 else if (status === "outgoing")
127 else if (status === "outgoing")
78 {
128 {
129 const outgoing = accountHoldingCharacter(inspected.characterId, social.outgoing);
79 const pending = document.createElement("p");
130 const pending = document.createElement("p");
80 pending.className = "hint";
131 pending.className = "hint";
81 pending.textContent = "Friend request sent.";
132 pending.textContent = "Friend request sent.";
@@ -83,7 +134,11 @@ export function initSocial ({ socket, MessageType })
83 pending,
134 pending,
84 actionButton("Cancel request", () =>
135 actionButton("Cancel request", () =>
85 {
136 {
86 socket.send({ type: MessageType.friendDecline, characterId: inspected.characterId });
137 socket.send({
138 type: MessageType.friendDecline,
139 accountId: outgoing?.accountId,
140 characterId: inspected.characterId
141 });
87 })
142 })
88 );
143 );
89 }
144 }
@@ -98,39 +153,109 @@ export function initSocial ({ socket, MessageType })
98
153
99 function renderLists ()
154 function renderLists ()
100 {
155 {
101 fillList(friendsList, social.friends, "No friends yet.", (entry) =>
156 fillList(friendsList, social.friends, "No friends yet.", (account) => accountRow(account, {
157 expanded: expandedAccountId === account.accountId,
158 onToggle ()
159 {
160 expandedAccountId = expandedAccountId === account.accountId ? null : account.accountId;
161 renderLists();
162 },
163 onRemove ()
164 {
165 socket.send({ type: MessageType.friendRemove, accountId: account.accountId });
166 }
167 }));
168 fillList(incomingList, social.incoming, "No incoming requests.", (account) => accountRequestRow(account, {
169 onAccept ()
170 {
171 socket.send({ type: MessageType.friendAccept, accountId: account.accountId });
172 },
173 onDecline ()
174 {
175 socket.send({ type: MessageType.friendDecline, accountId: account.accountId });
176 }
177 }));
178 fillList(outgoingList, social.outgoing, "No outgoing requests.", (account) => accountRequestRow(account, {
179 onDecline ()
180 {
181 socket.send({ type: MessageType.friendDecline, accountId: account.accountId });
182 },
183 declineLabel: "Cancel"
184 }));
185 }
186
187 function accountRow (account, { expanded, onToggle, onRemove })
188 {
189 const wrap = document.createElement("div");
190 wrap.className = "friend-account";
191 const header = document.createElement("div");
192 header.className = "social-row friend-account-header";
193 const nameBtn = document.createElement("button");
194 nameBtn.type = "button";
195 nameBtn.className = "friend-account-name";
196 nameBtn.textContent = account.username || `Account ${account.accountId}`;
197 nameBtn.addEventListener("click", onToggle);
198 header.append(nameBtn, actionButton("Remove", onRemove));
199 wrap.append(header);
200 if (expanded)
102 {
201 {
103 const row = namedRow(entry);
202 const list = document.createElement("div");
104 row.append(actionButton("Remove", () =>
203 list.className = "friend-character-list";
204 for (const character of account.characters ?? [])
205 { list.append(characterPreviewRow(character)); }
206 if (!(account.characters ?? []).length)
105 {
207 {
106 socket.send({ type: MessageType.friendRemove, characterId: entry.characterId });
208 const empty = document.createElement("p");
107 }));
209 empty.className = "hint";
108 return row;
210 empty.textContent = "No characters.";
109 });
211 list.append(empty);
110 fillList(incomingList, social.incoming, "No incoming requests.", (entry) =>
212 }
213 wrap.append(list);
214 }
215 return wrap;
216 }
217
218 function accountRequestRow (account, { onAccept = null, onDecline, declineLabel = "Decline" })
219 {
220 const row = document.createElement("div");
221 row.className = "social-row";
222 const name = document.createElement("span");
223 name.textContent = account.username || `Account ${account.accountId}`;
224 row.append(name);
225 if (onAccept)
226 { row.append(actionButton("Accept", onAccept)); }
227 row.append(actionButton(declineLabel, onDecline));
228 return row;
229 }
230
231 function characterPreviewRow (entry)
232 {
233 const row = document.createElement("div");
234 row.className = "friend-character-row";
235 row.append(characterPreview(entry.layers), (() =>
111 {
236 {
112 const row = namedRow(entry);
237 const name = document.createElement("span");
113 row.append(
238 name.textContent = `${entry.firstName} ${entry.lastName}`.trim();
114 actionButton("Accept", () =>
239 return name;
115 {
240 })());
116 socket.send({ type: MessageType.friendAccept, characterId: entry.characterId });
241 return row;
117 }),
242 }
118 actionButton("Decline", () =>
243
119 {
244 function characterPreview (layers)
120 socket.send({ type: MessageType.friendDecline, characterId: entry.characterId });
245 {
121 })
246 const wrap = document.createElement("div");
122 );
247 wrap.className = "char-preview friend-char-preview";
123 return row;
248 for (const layer of layers ?? [])
124 });
125 fillList(outgoingList, social.outgoing, "No outgoing requests.", (entry) =>
126 {
249 {
127 const row = namedRow(entry);
250 const url = resolveSpriteUrl?.(layer.sprite);
128 row.append(actionButton("Cancel", () =>
251 if (!url)
129 {
252 { continue; }
130 socket.send({ type: MessageType.friendDecline, characterId: entry.characterId });
253 const img = document.createElement("img");
131 }));
254 img.src = url;
132 return row;
255 img.alt = "";
133 });
256 wrap.append(img);
257 }
258 return wrap;
134 }
259 }
135
260
136 return {
261 return {
@@ -158,13 +283,31 @@ export function initSocial ({ socket, MessageType })
158 incoming: message.incoming ?? [],
283 incoming: message.incoming ?? [],
159 outgoing: message.outgoing ?? []
284 outgoing: message.outgoing ?? []
160 };
285 };
286 if (
287 expandedAccountId != null
288 && !(social.friends ?? []).some((account) => account.accountId === expandedAccountId)
289 )
290 { expandedAccountId = null; }
161 renderLists();
291 renderLists();
162 if (open)
292 if (open)
163 { renderInspect(); }
293 { renderInspect(); }
164 },
294 },
295 /** Flat character list for pigeon send targets. */
165 getFriends ()
296 getFriends ()
166 {
297 {
167 return social.friends ?? [];
298 const out = [];
299 for (const account of social.friends ?? [])
300 {
301 for (const character of account.characters ?? [])
302 { out.push(character); }
303 }
304 return out;
305 },
306 isFriendCharacter,
307 setLocalIdentity ({ accountId = null, characterId = null } = {})
308 {
309 localAccountId = accountId | 0 || null;
310 localCharacterId = characterId | 0 || null;
168 },
311 },
169 inspect (entity)
312 inspect (entity)
170 {
313 {
@@ -172,6 +315,7 @@ export function initSocial ({ socket, MessageType })
172 { return; }
315 { return; }
173 inspected = {
316 inspected = {
174 characterId: entity.characterId,
317 characterId: entity.characterId,
318 accountId: entity.accountId ?? null,
175 firstName: entity.firstName ?? "",
319 firstName: entity.firstName ?? "",
176 lastName: entity.lastName ?? ""
320 lastName: entity.lastName ?? ""
177 };
321 };
@@ -240,6 +384,9 @@ export function initSocial ({ socket, MessageType })
240 }
384 }
241 nametag.hidden = false;
385 nametag.hidden = false;
242 nametag.textContent = entity.firstName;
386 nametag.textContent = entity.firstName;
387 const friend = entity.characterId && isFriendCharacter(entity.characterId, entity.accountId);
388 nametag.classList.toggle("friend-name", !!friend);
389 nametag.style.color = friend ? FRIEND_NAME_COLOR : "";
243 nametag.style.left = `${rect.left + anchor.x}px`;
390 nametag.style.left = `${rect.left + anchor.x}px`;
244 nametag.style.top = `${rect.top + anchor.y - 6}px`;
391 nametag.style.top = `${rect.top + anchor.y - 6}px`;
245 canvas.style.cursor = "pointer";
392 canvas.style.cursor = "pointer";
@@ -252,16 +399,6 @@ export function initSocial ({ socket, MessageType })
252 };
399 };
253}
400}
254
401
255function namedRow (entry)
256{
257 const row = document.createElement("div");
258 row.className = "social-row";
259 const name = document.createElement("span");
260 name.textContent = `${entry.firstName} ${entry.lastName}`;
261 row.append(name);
262 return row;
263}
264
265function fillList (root, entries, emptyText, renderRow)
402function fillList (root, entries, emptyText, renderRow)
266{
403{
267 root.replaceChildren();
404 root.replaceChildren();
client/src/render/worldView.js +76 −1
@@ -26,6 +26,7 @@ import
26 26 resolveDimensionSeasonId
27 27 } from "/shared/world/dimensions.js";
28 28 import { SPELL_PROJECTILE_FRAME_MS } from "/shared/spells/constants.js";
29 import { skullTintColor } from "/shared/combat/skull.js";
29 30
30 31 const LAYER_GROUND = 0;
31 32 const LAYER_EDGE = 900000;
@@ -34,6 +35,7 @@ const SORT_ENTITY = 3;
34 35 const SORT_HP_BAR = 4;
35 36 const SORT_FX = 5;
36 37 const RENDER_LAYER_BLOOM = "bloom";
38 const SKULL_SPRITE = "fx:skull:skull";
37 39
38 40 const HP_BAR_W = 14;
39 41 const HP_BAR_H = 4;
@@ -581,7 +583,7 @@ export class WorldView
581 583 this.#scheduleEdgeRebuild();
582 584 }
583 585
584 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null)
586 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null, skullValue = 0)
585 587 {
586 588 this.localEntityId = entityId;
587 589 this.#upsertEntity({
@@ -594,6 +596,7 @@ export class WorldView
594 596 firstName,
595 597 lastName,
596 598 layers: layers ?? undefined,
599 skullValue: skullValue | 0,
597 600 ...(health != null ? { health } : {}),
598 601 ...(maxHealth != null ? { maxHealth } : {})
599 602 });
@@ -717,6 +720,7 @@ export class WorldView
717 720 { return; }
718 721 existing.object?.destroy();
719 722 existing.hpBar?.destroy();
723 existing.skullMarker?.destroy();
720 724 for (const overlay of existing.overlays ?? [])
721 725 { overlay.destroy(); }
722 726 for (const overlay of existing.bloomOverlays ?? [])
@@ -724,6 +728,15 @@ export class WorldView
724 728 this.entities.delete(entityId);
725 729 }
726 730
731 updateEntitySkull (entityId, skullValue)
732 {
733 const entity = this.entities.get(entityId);
734 if (!entity)
735 { return; }
736 entity.skullValue = Math.max(0, skullValue | 0);
737 this.#syncSkullMarker(entity);
738 }
739
727 740 updateEntityHealth (entityId, health, maxHealth)
728 741 {
729 742 const entity = this.entities.get(entityId);
@@ -1946,6 +1959,7 @@ export class WorldView
1946 1959 entity.gait = payload.gait;
1947 1960 entity.sex = payload.sex ?? entity.sex;
1948 1961 entity.characterId = payload.characterId ?? entity.characterId ?? null;
1962 entity.accountId = payload.accountId ?? entity.accountId ?? null;
1949 1963 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
1950 1964 if (payload.level != null)
1951 1965 { entity.level = payload.level | 0; }
@@ -1967,6 +1981,10 @@ export class WorldView
1967 1981 { entity.health = payload.health; }
1968 1982 if (payload.maxHealth != null)
1969 1983 { entity.maxHealth = payload.maxHealth; }
1984 if (payload.skullValue != null)
1985 { entity.skullValue = Math.max(0, payload.skullValue | 0); }
1986 else if (entity.skullValue == null)
1987 { entity.skullValue = 0; }
1970 1988 if (payload.firstName)
1971 1989 { entity.firstName = payload.firstName; }
1972 1990 if (payload.lastName)
@@ -1994,6 +2012,7 @@ export class WorldView
1994 2012 if (payload.layers)
1995 2013 { this.#applyLayers(entity, payload.layers); }
1996 2014 this.#syncHpBar(entity);
2015 this.#syncSkullMarker(entity);
1997 2016 this.#placeEntity(entity, performance.now());
1998 2017 }
1999 2018
@@ -2163,6 +2182,7 @@ export class WorldView
2163 2182 this.#placePivoted(overlay, pivotX, pivotY, pivotY + 0.002, SORT_ENTITY, entity.visualScale ?? 1);
2164 2183 }
2165 2184 this.#placeHpBar(entity, pivotX, pivotY);
2185 this.#placeSkullMarker(entity, pivotX, pivotY, tileShade);
2166 2186 }
2167 2187
2168 2188 #markUnlit (object)
@@ -2517,6 +2537,61 @@ export class WorldView
2517 2537 this.#markSortDirty();
2518 2538 }
2519 2539
2540 #syncSkullMarker (entity)
2541 {
2542 if (!entity?.characterId)
2543 {
2544 entity.skullMarker?.destroy();
2545 entity.skullMarker = null;
2546 return;
2547 }
2548 const tint = skullTintColor(entity.skullValue | 0);
2549 if (!tint)
2550 {
2551 entity.skullMarker?.destroy();
2552 entity.skullMarker = null;
2553 return;
2554 }
2555 const image = this.game.images[SKULL_SPRITE];
2556 if (!image)
2557 { return; }
2558 if (!entity.skullMarker)
2559 {
2560 entity.skullMarker = new GameObject(0, 0, image, SORT_HP_BAR);
2561 this.scene.addObject(entity.skullMarker);
2562 }
2563 entity.skullTint = tint;
2564 entity.skullMarker.renderer.sprite = image;
2565 }
2566
2567 /**
2568 * Bottom edge of the skull sprite sits exactly on the character sprite's top edge.
2569 */
2570 #placeSkullMarker (entity, pivotX, pivotY, darkness)
2571 {
2572 this.#syncSkullMarker(entity);
2573 if (!entity.skullMarker)
2574 { return; }
2575 const body = entity.object?.renderer?.sprite;
2576 const skull = entity.skullMarker.renderer?.sprite;
2577 if (!body || !skull)
2578 { return; }
2579 const zoom = this.zoom;
2580 const scale = entity.visualScale ?? 1;
2581 const bodyH = body.height * zoom * scale;
2582 const skullH = skull.height * zoom;
2583 const skullW = skull.width * zoom;
2584 const bodyCenterY = pivotY - (bodyH / 2 - PIVOT_FROM_BOTTOM_PX * zoom * scale);
2585 const bodyTop = bodyCenterY - bodyH / 2;
2586 // GameObject position is sprite center; bottom of skull at bodyTop ⇒ center at bodyTop - skullH/2
2587 entity.skullMarker.transform.position.x = pivotX;
2588 entity.skullMarker.transform.position.y = bodyTop - skullH / 2;
2589 entity.skullMarker.transform.size = new vector(skullW, skullH);
2590 entity.skullMarker.layer = ySortLayer(pivotY, SORT_HP_BAR);
2591 this.#syncLitSprite(entity.skullMarker, darkness, 0, false, entity.skullTint);
2592 this.#markSortDirty();
2593 }
2594
2520 2595 #rebuildChunk (snapshot, { refreshSoftNeighbors = true } = {})
2521 2596 {
2522 2597 this.#bakeAndPlaceChunk(snapshot);
@@ -26,6 +26,7 @@ import
26 resolveDimensionSeasonId
26 resolveDimensionSeasonId
27} from "/shared/world/dimensions.js";
27} from "/shared/world/dimensions.js";
28import { SPELL_PROJECTILE_FRAME_MS } from "/shared/spells/constants.js";
28import { SPELL_PROJECTILE_FRAME_MS } from "/shared/spells/constants.js";
29import { skullTintColor } from "/shared/combat/skull.js";
29
30
30const LAYER_GROUND = 0;
31const LAYER_GROUND = 0;
31const LAYER_EDGE = 900000;
32const LAYER_EDGE = 900000;
@@ -34,6 +35,7 @@ const SORT_ENTITY = 3;
34const SORT_HP_BAR = 4;
35const SORT_HP_BAR = 4;
35const SORT_FX = 5;
36const SORT_FX = 5;
36const RENDER_LAYER_BLOOM = "bloom";
37const RENDER_LAYER_BLOOM = "bloom";
38const SKULL_SPRITE = "fx:skull:skull";
37
39
38const HP_BAR_W = 14;
40const HP_BAR_W = 14;
39const HP_BAR_H = 4;
41const HP_BAR_H = 4;
@@ -581,7 +583,7 @@ export class WorldView
581 this.#scheduleEdgeRebuild();
583 this.#scheduleEdgeRebuild();
582 }
584 }
583
585
584 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null)
586 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null, skullValue = 0)
585 {
587 {
586 this.localEntityId = entityId;
588 this.localEntityId = entityId;
587 this.#upsertEntity({
589 this.#upsertEntity({
@@ -594,6 +596,7 @@ export class WorldView
594 firstName,
596 firstName,
595 lastName,
597 lastName,
596 layers: layers ?? undefined,
598 layers: layers ?? undefined,
599 skullValue: skullValue | 0,
597 ...(health != null ? { health } : {}),
600 ...(health != null ? { health } : {}),
598 ...(maxHealth != null ? { maxHealth } : {})
601 ...(maxHealth != null ? { maxHealth } : {})
599 });
602 });
@@ -717,6 +720,7 @@ export class WorldView
717 { return; }
720 { return; }
718 existing.object?.destroy();
721 existing.object?.destroy();
719 existing.hpBar?.destroy();
722 existing.hpBar?.destroy();
723 existing.skullMarker?.destroy();
720 for (const overlay of existing.overlays ?? [])
724 for (const overlay of existing.overlays ?? [])
721 { overlay.destroy(); }
725 { overlay.destroy(); }
722 for (const overlay of existing.bloomOverlays ?? [])
726 for (const overlay of existing.bloomOverlays ?? [])
@@ -724,6 +728,15 @@ export class WorldView
724 this.entities.delete(entityId);
728 this.entities.delete(entityId);
725 }
729 }
726
730
731 updateEntitySkull (entityId, skullValue)
732 {
733 const entity = this.entities.get(entityId);
734 if (!entity)
735 { return; }
736 entity.skullValue = Math.max(0, skullValue | 0);
737 this.#syncSkullMarker(entity);
738 }
739
727 updateEntityHealth (entityId, health, maxHealth)
740 updateEntityHealth (entityId, health, maxHealth)
728 {
741 {
729 const entity = this.entities.get(entityId);
742 const entity = this.entities.get(entityId);
@@ -1946,6 +1959,7 @@ export class WorldView
1946 entity.gait = payload.gait;
1959 entity.gait = payload.gait;
1947 entity.sex = payload.sex ?? entity.sex;
1960 entity.sex = payload.sex ?? entity.sex;
1948 entity.characterId = payload.characterId ?? entity.characterId ?? null;
1961 entity.characterId = payload.characterId ?? entity.characterId ?? null;
1962 entity.accountId = payload.accountId ?? entity.accountId ?? null;
1949 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
1963 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
1950 if (payload.level != null)
1964 if (payload.level != null)
1951 { entity.level = payload.level | 0; }
1965 { entity.level = payload.level | 0; }
@@ -1967,6 +1981,10 @@ export class WorldView
1967 { entity.health = payload.health; }
1981 { entity.health = payload.health; }
1968 if (payload.maxHealth != null)
1982 if (payload.maxHealth != null)
1969 { entity.maxHealth = payload.maxHealth; }
1983 { entity.maxHealth = payload.maxHealth; }
1984 if (payload.skullValue != null)
1985 { entity.skullValue = Math.max(0, payload.skullValue | 0); }
1986 else if (entity.skullValue == null)
1987 { entity.skullValue = 0; }
1970 if (payload.firstName)
1988 if (payload.firstName)
1971 { entity.firstName = payload.firstName; }
1989 { entity.firstName = payload.firstName; }
1972 if (payload.lastName)
1990 if (payload.lastName)
@@ -1994,6 +2012,7 @@ export class WorldView
1994 if (payload.layers)
2012 if (payload.layers)
1995 { this.#applyLayers(entity, payload.layers); }
2013 { this.#applyLayers(entity, payload.layers); }
1996 this.#syncHpBar(entity);
2014 this.#syncHpBar(entity);
2015 this.#syncSkullMarker(entity);
1997 this.#placeEntity(entity, performance.now());
2016 this.#placeEntity(entity, performance.now());
1998 }
2017 }
1999
2018
@@ -2163,6 +2182,7 @@ export class WorldView
2163 this.#placePivoted(overlay, pivotX, pivotY, pivotY + 0.002, SORT_ENTITY, entity.visualScale ?? 1);
2182 this.#placePivoted(overlay, pivotX, pivotY, pivotY + 0.002, SORT_ENTITY, entity.visualScale ?? 1);
2164 }
2183 }
2165 this.#placeHpBar(entity, pivotX, pivotY);
2184 this.#placeHpBar(entity, pivotX, pivotY);
2185 this.#placeSkullMarker(entity, pivotX, pivotY, tileShade);
2166 }
2186 }
2167
2187
2168 #markUnlit (object)
2188 #markUnlit (object)
@@ -2517,6 +2537,61 @@ export class WorldView
2517 this.#markSortDirty();
2537 this.#markSortDirty();
2518 }
2538 }
2519
2539
2540 #syncSkullMarker (entity)
2541 {
2542 if (!entity?.characterId)
2543 {
2544 entity.skullMarker?.destroy();
2545 entity.skullMarker = null;
2546 return;
2547 }
2548 const tint = skullTintColor(entity.skullValue | 0);
2549 if (!tint)
2550 {
2551 entity.skullMarker?.destroy();
2552 entity.skullMarker = null;
2553 return;
2554 }
2555 const image = this.game.images[SKULL_SPRITE];
2556 if (!image)
2557 { return; }
2558 if (!entity.skullMarker)
2559 {
2560 entity.skullMarker = new GameObject(0, 0, image, SORT_HP_BAR);
2561 this.scene.addObject(entity.skullMarker);
2562 }
2563 entity.skullTint = tint;
2564 entity.skullMarker.renderer.sprite = image;
2565 }
2566
2567 /**
2568 * Bottom edge of the skull sprite sits exactly on the character sprite's top edge.
2569 */
2570 #placeSkullMarker (entity, pivotX, pivotY, darkness)
2571 {
2572 this.#syncSkullMarker(entity);
2573 if (!entity.skullMarker)
2574 { return; }
2575 const body = entity.object?.renderer?.sprite;
2576 const skull = entity.skullMarker.renderer?.sprite;
2577 if (!body || !skull)
2578 { return; }
2579 const zoom = this.zoom;
2580 const scale = entity.visualScale ?? 1;
2581 const bodyH = body.height * zoom * scale;
2582 const skullH = skull.height * zoom;
2583 const skullW = skull.width * zoom;
2584 const bodyCenterY = pivotY - (bodyH / 2 - PIVOT_FROM_BOTTOM_PX * zoom * scale);
2585 const bodyTop = bodyCenterY - bodyH / 2;
2586 // GameObject position is sprite center; bottom of skull at bodyTop ⇒ center at bodyTop - skullH/2
2587 entity.skullMarker.transform.position.x = pivotX;
2588 entity.skullMarker.transform.position.y = bodyTop - skullH / 2;
2589 entity.skullMarker.transform.size = new vector(skullW, skullH);
2590 entity.skullMarker.layer = ySortLayer(pivotY, SORT_HP_BAR);
2591 this.#syncLitSprite(entity.skullMarker, darkness, 0, false, entity.skullTint);
2592 this.#markSortDirty();
2593 }
2594
2520 #rebuildChunk (snapshot, { refreshSoftNeighbors = true } = {})
2595 #rebuildChunk (snapshot, { refreshSoftNeighbors = true } = {})
2521 {
2596 {
2522 this.#bakeAndPlaceChunk(snapshot);
2597 this.#bakeAndPlaceChunk(snapshot);
client/ui/play.css +51 −0
@@ -456,6 +456,57 @@ a {
456 456 font-size: 0.85rem;
457 457 }
458 458
459 #nametag.friend-name,
460 #world-tooltip.friend-name {
461 color: #e8c84a;
462 }
463
464 .friend-account {
465 display: flex;
466 flex-direction: column;
467 gap: 0.25rem;
468 margin-bottom: 0.35rem;
469 }
470
471 .friend-account-header {
472 align-items: center;
473 }
474
475 button.friend-account-name {
476 flex: 1;
477 text-align: left;
478 background: transparent;
479 border: none;
480 color: inherit;
481 padding: 0.15rem 0;
482 cursor: pointer;
483 font: inherit;
484 }
485
486 button.friend-account-name:hover {
487 color: #e8c84a;
488 }
489
490 .friend-character-list {
491 display: flex;
492 flex-direction: column;
493 gap: 0.25rem;
494 padding-left: 0.35rem;
495 border-left: 2px solid #2c3340;
496 }
497
498 .friend-character-row {
499 display: flex;
500 align-items: center;
501 gap: 0.4rem;
502 }
503
504 .friend-char-preview {
505 width: 28px;
506 height: 28px;
507 flex: 0 0 auto;
508 }
509
459 510 #context-menu {
460 511 position: fixed;
461 512 z-index: 20;
@@ -456,6 +456,57 @@ a {
456 font-size: 0.85rem;
456 font-size: 0.85rem;
457}
457}
458
458
459#nametag.friend-name,
460#world-tooltip.friend-name {
461 color: #e8c84a;
462}
463
464.friend-account {
465 display: flex;
466 flex-direction: column;
467 gap: 0.25rem;
468 margin-bottom: 0.35rem;
469}
470
471.friend-account-header {
472 align-items: center;
473}
474
475button.friend-account-name {
476 flex: 1;
477 text-align: left;
478 background: transparent;
479 border: none;
480 color: inherit;
481 padding: 0.15rem 0;
482 cursor: pointer;
483 font: inherit;
484}
485
486button.friend-account-name:hover {
487 color: #e8c84a;
488}
489
490.friend-character-list {
491 display: flex;
492 flex-direction: column;
493 gap: 0.25rem;
494 padding-left: 0.35rem;
495 border-left: 2px solid #2c3340;
496}
497
498.friend-character-row {
499 display: flex;
500 align-items: center;
501 gap: 0.4rem;
502}
503
504.friend-char-preview {
505 width: 28px;
506 height: 28px;
507 flex: 0 0 auto;
508}
509
459#context-menu {
510#context-menu {
460 position: fixed;
511 position: fixed;
461 z-index: 20;
512 z-index: 20;
server/src/bounty/service.js +8 −1
@@ -142,6 +142,7 @@ export class BountyService
142 142 this.#persistBag(placerCharacterId, bag);
143 143
144 144 const nextAmount = this.stateDb.addCharacterBounty(targetId, copper);
145 this.simulation.refreshCharacterSkull?.(targetId);
145 146 this.simulation.pendingPrivate.push({
146 147 type: "toast",
147 148 characterId: targetId,
@@ -172,7 +173,8 @@ export class BountyService
172 173 }
173 174
174 175 /**
175 * Called when a player dies. PvP killer collects full bounty into vault + office letter.
176 * Called when a player dies. Non-friend PvP killer collects full bounty into vault + office letter.
177 * Friend / same-account / mob kills leave the bounty untouched.
176 178 * @returns {{ paidCopper: number, victimName: string } | null}
177 179 */
178 180 settleKill (victimCharacterId, attackerEntityId, deathTileX, deathTileY)
@@ -185,6 +187,9 @@ export class BountyService
185 187 if (!killerCharacterId || killerCharacterId === (victimCharacterId | 0))
186 188 { return null; }
187 189
190 if (this.stateDb.areFriends(victimCharacterId, killerCharacterId))
191 { return null; }
192
188 193 const paidCopper = this.stateDb.takeCharacterBounty(victimCharacterId);
189 194 if (paidCopper <= 0)
190 195 { return null; }
@@ -224,6 +229,8 @@ export class BountyService
224 229 message: `Bounty collected: ${formatBountyCopper(paidCopper)} for defeating ${victimName} (sent to vault).`
225 230 });
226 231
232 this.simulation.refreshCharacterSkull?.(victimCharacterId);
233
227 234 return { paidCopper, victimName };
228 235 }
229 236
@@ -142,6 +142,7 @@ export class BountyService
142 this.#persistBag(placerCharacterId, bag);
142 this.#persistBag(placerCharacterId, bag);
143
143
144 const nextAmount = this.stateDb.addCharacterBounty(targetId, copper);
144 const nextAmount = this.stateDb.addCharacterBounty(targetId, copper);
145 this.simulation.refreshCharacterSkull?.(targetId);
145 this.simulation.pendingPrivate.push({
146 this.simulation.pendingPrivate.push({
146 type: "toast",
147 type: "toast",
147 characterId: targetId,
148 characterId: targetId,
@@ -172,7 +173,8 @@ export class BountyService
172 }
173 }
173
174
174 /**
175 /**
175 * Called when a player dies. PvP killer collects full bounty into vault + office letter.
176 * Called when a player dies. Non-friend PvP killer collects full bounty into vault + office letter.
177 * Friend / same-account / mob kills leave the bounty untouched.
176 * @returns {{ paidCopper: number, victimName: string } | null}
178 * @returns {{ paidCopper: number, victimName: string } | null}
177 */
179 */
178 settleKill (victimCharacterId, attackerEntityId, deathTileX, deathTileY)
180 settleKill (victimCharacterId, attackerEntityId, deathTileX, deathTileY)
@@ -185,6 +187,9 @@ export class BountyService
185 if (!killerCharacterId || killerCharacterId === (victimCharacterId | 0))
187 if (!killerCharacterId || killerCharacterId === (victimCharacterId | 0))
186 { return null; }
188 { return null; }
187
189
190 if (this.stateDb.areFriends(victimCharacterId, killerCharacterId))
191 { return null; }
192
188 const paidCopper = this.stateDb.takeCharacterBounty(victimCharacterId);
193 const paidCopper = this.stateDb.takeCharacterBounty(victimCharacterId);
189 if (paidCopper <= 0)
194 if (paidCopper <= 0)
190 { return null; }
195 { return null; }
@@ -224,6 +229,8 @@ export class BountyService
224 message: `Bounty collected: ${formatBountyCopper(paidCopper)} for defeating ${victimName} (sent to vault).`
229 message: `Bounty collected: ${formatBountyCopper(paidCopper)} for defeating ${victimName} (sent to vault).`
225 });
230 });
226
231
232 this.simulation.refreshCharacterSkull?.(victimCharacterId);
233
227 return { paidCopper, victimName };
234 return { paidCopper, victimName };
228 }
235 }
229
236
server/src/combat/service.js +27 −23
@@ -2,31 +2,35 @@ import { Component } from "../ecs/components.js";
2 2 import { itemDefinition } from "../../../shared/definitions/items.js";
3 3 import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";
4 4 import { mobDefinition } from "../../../shared/definitions/mobs.js";
5 import {
6 mobCanFightType,
7 mobCanFight,
8 mobMeleeAttackProfile,
9 mobSkillLevels,
10 mobIsAggressive,
11 mobAggroRangeTiles
12 } from "../../../shared/definitions/mobCombat.js";
5 import
6 {
7 mobCanFightType,
8 mobCanFight,
9 mobMeleeAttackProfile,
10 mobSkillLevels,
11 mobIsAggressive,
12 mobAggroRangeTiles
13 } from "../../../shared/definitions/mobCombat.js";
13 14 import { spellDefinition } from "../../../shared/definitions/spells.js";
14 15 import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";
15 import {
16 effectiveHitSkillInDarkness,
17 aggroDistanceMultiplier
18 } from "../../../shared/combat/darkness.js";
19 import {
20 bakedTileLight01,
21 entityLightAtTile,
22 tileCombatLight01,
23 tileIndexLocal
24 } from "../../../shared/lighting/combatLight.js";
16 import
17 {
18 effectiveHitSkillInDarkness,
19 aggroDistanceMultiplier
20 } from "../../../shared/combat/darkness.js";
21 import
22 {
23 bakedTileLight01,
24 entityLightAtTile,
25 tileCombatLight01,
26 tileIndexLocal
27 } from "../../../shared/lighting/combatLight.js";
25 28 import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
26 import {
27 effectiveSkillLevel,
28 equipmentBonusesFromSlots
29 } from "../../../shared/equipment/stats.js";
29 import
30 {
31 effectiveSkillLevel,
32 equipmentBonusesFromSlots
33 } from "../../../shared/equipment/stats.js";
30 34 import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
31 35 import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS, SPELL_COOLDOWN_MS } from "../../../shared/spells/constants.js";
32 36 import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
@@ -1454,7 +1458,7 @@ export function finalizeMobKill (world, attackerId, targetId, targetHandle, tile
1454 1458 scheduleSpawnerRespawn(
1455 1459 world,
1456 1460 origin.spawnerId,
1457 origin.respawnDelaySeconds ?? 0,
1461 origin.respawnDelaySeconds ?? 25,
1458 1462 now
1459 1463 );
1460 1464 }
@@ -2,31 +2,35 @@ import { Component } from "../ecs/components.js";
2import { itemDefinition } from "../../../shared/definitions/items.js";
2import { itemDefinition } from "../../../shared/definitions/items.js";
3import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";
3import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";
4import { mobDefinition } from "../../../shared/definitions/mobs.js";
4import { mobDefinition } from "../../../shared/definitions/mobs.js";
5import {
5import
6 mobCanFightType,
6 {
7 mobCanFight,
7 mobCanFightType,
8 mobMeleeAttackProfile,
8 mobCanFight,
9 mobSkillLevels,
9 mobMeleeAttackProfile,
10 mobIsAggressive,
10 mobSkillLevels,
11 mobAggroRangeTiles
11 mobIsAggressive,
12} from "../../../shared/definitions/mobCombat.js";
12 mobAggroRangeTiles
13 } from "../../../shared/definitions/mobCombat.js";
13import { spellDefinition } from "../../../shared/definitions/spells.js";
14import { spellDefinition } from "../../../shared/definitions/spells.js";
14import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";
15import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";
15import {
16import
16 effectiveHitSkillInDarkness,
17 {
17 aggroDistanceMultiplier
18 effectiveHitSkillInDarkness,
18} from "../../../shared/combat/darkness.js";
19 aggroDistanceMultiplier
19import {
20 } from "../../../shared/combat/darkness.js";
20 bakedTileLight01,
21import
21 entityLightAtTile,
22 {
22 tileCombatLight01,
23 bakedTileLight01,
23 tileIndexLocal
24 entityLightAtTile,
24} from "../../../shared/lighting/combatLight.js";
25 tileCombatLight01,
26 tileIndexLocal
27 } from "../../../shared/lighting/combatLight.js";
25import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
28import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
26import {
29import
27 effectiveSkillLevel,
30 {
28 equipmentBonusesFromSlots
31 effectiveSkillLevel,
29} from "../../../shared/equipment/stats.js";
32 equipmentBonusesFromSlots
33 } from "../../../shared/equipment/stats.js";
30import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
34import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
31import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS, SPELL_COOLDOWN_MS } from "../../../shared/spells/constants.js";
35import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS, SPELL_COOLDOWN_MS } from "../../../shared/spells/constants.js";
32import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
36import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
@@ -1454,7 +1458,7 @@ export function finalizeMobKill (world, attackerId, targetId, targetHandle, tile
1454 scheduleSpawnerRespawn(
1458 scheduleSpawnerRespawn(
1455 world,
1459 world,
1456 origin.spawnerId,
1460 origin.spawnerId,
1457 origin.respawnDelaySeconds ?? 0,
1461 origin.respawnDelaySeconds ?? 25,
1458 now
1462 now
1459 );
1463 );
1460 }
1464 }
server/src/crafting/service.js +15 −11
@@ -4,20 +4,22 @@ import { CraftingStationId, CRAFT_DURATION_MS, COOK_BURN_CHANCE_OVEN, COOK_BURN_
4 4 import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
5 5 import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
6 6 import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
7 import {
8 recipeDefinition,
9 canStartCraft,
10 canCraftFitInventory,
11 hasRecipeInputs
12 } from "../../../shared/crafting/recipes.js";
7 import
8 {
9 recipeDefinition,
10 canStartCraft,
11 canCraftFitInventory,
12 hasRecipeInputs
13 } from "../../../shared/crafting/recipes.js";
13 14 import { resolveTailorCraft } from "../../../shared/crafting/tailor.js";
14 15 import { craftDurationMs, craftXpForConsumedInputs } from "../../../shared/definitions/gathering.js";
15 16 import { takeFromSlot, insertStack, stackQuantity, consumeFillCharge } from "../../../shared/items/inventory.js";
16 import {
17 attachOrigins,
18 craftOrigin,
19 craftOriginVerbForStation
20 } from "../../../shared/items/origin.js";
17 import
18 {
19 attachOrigins,
20 craftOrigin,
21 craftOriginVerbForStation
22 } from "../../../shared/items/origin.js";
21 23 import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
22 24 import { bagView } from "../items/bags.js";
23 25 import { tileToChunk, tileToLocal } from "../world/coordinates.js";
@@ -66,6 +68,8 @@ function stationBlockType (stationId)
66 68 { return BlockType.furnace; }
67 69 if (stationId === CraftingStationId.anvil)
68 70 { return BlockType.anvil; }
71 if (stationId === CraftingStationId.jeweleringStation)
72 { return BlockType.jeweleringStation; }
69 73 if (stationId === CraftingStationId.woodworkingBench)
70 74 { return BlockType.woodworkingBench; }
71 75 if (stationId === CraftingStationId.craftingBench)
@@ -4,20 +4,22 @@ import { CraftingStationId, CRAFT_DURATION_MS, COOK_BURN_CHANCE_OVEN, COOK_BURN_
4import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
4import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
5import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
5import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
6import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
6import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
7import {
7import
8 recipeDefinition,
8 {
9 canStartCraft,
9 recipeDefinition,
10 canCraftFitInventory,
10 canStartCraft,
11 hasRecipeInputs
11 canCraftFitInventory,
12} from "../../../shared/crafting/recipes.js";
12 hasRecipeInputs
13 } from "../../../shared/crafting/recipes.js";
13import { resolveTailorCraft } from "../../../shared/crafting/tailor.js";
14import { resolveTailorCraft } from "../../../shared/crafting/tailor.js";
14import { craftDurationMs, craftXpForConsumedInputs } from "../../../shared/definitions/gathering.js";
15import { craftDurationMs, craftXpForConsumedInputs } from "../../../shared/definitions/gathering.js";
15import { takeFromSlot, insertStack, stackQuantity, consumeFillCharge } from "../../../shared/items/inventory.js";
16import { takeFromSlot, insertStack, stackQuantity, consumeFillCharge } from "../../../shared/items/inventory.js";
16import {
17import
17 attachOrigins,
18 {
18 craftOrigin,
19 attachOrigins,
19 craftOriginVerbForStation
20 craftOrigin,
20} from "../../../shared/items/origin.js";
21 craftOriginVerbForStation
22 } from "../../../shared/items/origin.js";
21import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
23import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
22import { bagView } from "../items/bags.js";
24import { bagView } from "../items/bags.js";
23import { tileToChunk, tileToLocal } from "../world/coordinates.js";
25import { tileToChunk, tileToLocal } from "../world/coordinates.js";
@@ -66,6 +68,8 @@ function stationBlockType (stationId)
66 { return BlockType.furnace; }
68 { return BlockType.furnace; }
67 if (stationId === CraftingStationId.anvil)
69 if (stationId === CraftingStationId.anvil)
68 { return BlockType.anvil; }
70 { return BlockType.anvil; }
71 if (stationId === CraftingStationId.jeweleringStation)
72 { return BlockType.jeweleringStation; }
69 if (stationId === CraftingStationId.woodworkingBench)
73 if (stationId === CraftingStationId.woodworkingBench)
70 { return BlockType.woodworkingBench; }
74 { return BlockType.woodworkingBench; }
71 if (stationId === CraftingStationId.craftingBench)
75 if (stationId === CraftingStationId.craftingBench)
server/src/ecs/serialize.js +4 −1
@@ -93,6 +93,7 @@ export function publicEntityView (ecs, entityId)
93 93 firstName: appearance?.firstName ?? "",
94 94 lastName: appearance?.lastName ?? "",
95 95 characterId: character?.characterId ?? null,
96 accountId: character?.accountId ?? null,
96 97 mobTypeId: creature?.mobTypeId ?? null,
97 98 canFight: mob ? mobCanFight(mob) : !!character,
98 99 hostile: !!mob?.hostile,
@@ -126,6 +127,7 @@ export function replicationSpawn (view)
126 127 type: "entity-spawn",
127 128 entityId: view.entityId,
128 129 characterId: view.characterId,
130 accountId: view.accountId ?? null,
129 131 tileX: view.tileX,
130 132 tileY: view.tileY,
131 133 worldX: view.worldX,
@@ -148,7 +150,8 @@ export function replicationSpawn (view)
148 150 health: view.health,
149 151 maxHealth: view.maxHealth,
150 152 lightRadiusTiles: view.lightRadiusTiles ?? 0,
151 visualScale: view.visualScale ?? 1
153 visualScale: view.visualScale ?? 1,
154 skullValue: view.skullValue | 0
152 155 };
153 156 }
154 157
@@ -93,6 +93,7 @@ export function publicEntityView (ecs, entityId)
93 firstName: appearance?.firstName ?? "",
93 firstName: appearance?.firstName ?? "",
94 lastName: appearance?.lastName ?? "",
94 lastName: appearance?.lastName ?? "",
95 characterId: character?.characterId ?? null,
95 characterId: character?.characterId ?? null,
96 accountId: character?.accountId ?? null,
96 mobTypeId: creature?.mobTypeId ?? null,
97 mobTypeId: creature?.mobTypeId ?? null,
97 canFight: mob ? mobCanFight(mob) : !!character,
98 canFight: mob ? mobCanFight(mob) : !!character,
98 hostile: !!mob?.hostile,
99 hostile: !!mob?.hostile,
@@ -126,6 +127,7 @@ export function replicationSpawn (view)
126 type: "entity-spawn",
127 type: "entity-spawn",
127 entityId: view.entityId,
128 entityId: view.entityId,
128 characterId: view.characterId,
129 characterId: view.characterId,
130 accountId: view.accountId ?? null,
129 tileX: view.tileX,
131 tileX: view.tileX,
130 tileY: view.tileY,
132 tileY: view.tileY,
131 worldX: view.worldX,
133 worldX: view.worldX,
@@ -148,7 +150,8 @@ export function replicationSpawn (view)
148 health: view.health,
150 health: view.health,
149 maxHealth: view.maxHealth,
151 maxHealth: view.maxHealth,
150 lightRadiusTiles: view.lightRadiusTiles ?? 0,
152 lightRadiusTiles: view.lightRadiusTiles ?? 0,
151 visualScale: view.visualScale ?? 1
153 visualScale: view.visualScale ?? 1,
154 skullValue: view.skullValue | 0
152 };
155 };
153}
156}
154
157
server/src/friends/service.js +143 −36
@@ -1,3 +1,9 @@
1 import { layersFromBag } from "../../../shared/appearance/layers.js";
2
3 /**
4 * Account-wide friends: requests and friendships key on account_id.
5 * Same-account characters are always treated as friends.
6 */
1 7 export class FriendService
2 8 {
3 9 constructor (stateDb)
@@ -7,16 +13,46 @@ export class FriendService
7 13
8 14 snapshot (characterId)
9 15 {
16 const accountId = this.#accountId(characterId);
10 17 return {
11 friends: this.listFriends(characterId),
12 incoming: this.#namedRequests(this.stateDb.listIncomingRequests(characterId), "from_character_id"),
13 outgoing: this.#namedRequests(this.stateDb.listOutgoingRequests(characterId), "to_character_id")
18 friends: this.listFriendAccounts(accountId),
19 incoming: this.#namedAccountRequests(
20 this.stateDb.listIncomingAccountRequests(accountId),
21 "from_account_id"
22 ),
23 outgoing: this.#namedAccountRequests(
24 this.stateDb.listOutgoingAccountRequests(accountId),
25 "to_account_id"
26 )
14 27 };
15 28 }
16 29
30 /** Flat character list for pigeon address book (all chars on friend accounts). */
17 31 listFriends (characterId)
18 32 {
19 return this.stateDb.listFriendRecords(characterId).map((row) => this.#publicCharacter(row.character_id)).filter(Boolean);
33 const accounts = this.listFriendAccounts(this.#accountId(characterId));
34 const out = [];
35 for (const account of accounts)
36 {
37 for (const character of account.characters ?? [])
38 { out.push(character); }
39 }
40 return out;
41 }
42
43 listFriendAccounts (accountId)
44 {
45 const id = accountId | 0;
46 if (!id)
47 { return []; }
48 return this.stateDb.listAccountFriendRecords(id)
49 .map((row) => this.#publicAccount(row.account_id))
50 .filter(Boolean);
51 }
52
53 areFriends (characterId, otherCharacterId)
54 {
55 return this.stateDb.areFriends(characterId, otherCharacterId);
20 56 }
21 57
22 58 request (fromCharacterId, toCharacterId)
@@ -25,54 +61,98 @@ export class FriendService
25 61 const toId = Number(toCharacterId);
26 62 if (fromId === toId)
27 63 { throw userError("You cannot friend yourself."); }
28 this.#requireCharacter(fromId);
29 this.#requireCharacter(toId);
30 if (this.stateDb.areFriends(fromId, toId))
64 const from = this.#requireCharacter(fromId);
65 const to = this.#requireCharacter(toId);
66 const fromAccount = from.account_id | 0;
67 const toAccount = to.account_id | 0;
68 if (fromAccount === toAccount)
69 { throw userError("You are already friends with your own characters."); }
70 if (this.stateDb.areAccountFriends(fromAccount, toAccount))
31 71 { throw userError("You are already friends."); }
32 if (this.stateDb.getFriendRequest(fromId, toId))
72 if (this.stateDb.getAccountFriendRequest(fromAccount, toAccount))
33 73 { throw userError("Friend request already sent."); }
34 if (this.stateDb.getFriendRequest(toId, fromId))
74 if (this.stateDb.getAccountFriendRequest(toAccount, fromAccount))
35 75 {
36 this.stateDb.deleteFriendRequest(toId, fromId);
37 this.stateDb.insertFriendship(fromId, toId);
76 this.stateDb.deleteAccountFriendRequest(toAccount, fromAccount);
77 this.stateDb.insertAccountFriendship(fromAccount, toAccount);
38 78 return this.snapshot(fromId);
39 79 }
40 this.stateDb.insertFriendRequest(fromId, toId);
80 this.stateDb.insertAccountFriendRequest(fromAccount, toAccount);
41 81 return this.snapshot(fromId);
42 82 }
43 83
44 84 accept (characterId, fromCharacterId)
45 85 {
46 const toId = Number(characterId);
47 const fromId = Number(fromCharacterId);
48 this.#requireCharacter(toId);
49 this.#requireCharacter(fromId);
50 if (!this.stateDb.getFriendRequest(fromId, toId))
86 const toChar = this.#requireCharacter(characterId);
87 const fromChar = this.#requireCharacter(fromCharacterId);
88 const toAccount = toChar.account_id | 0;
89 const fromAccount = fromChar.account_id | 0;
90 if (!this.stateDb.getAccountFriendRequest(fromAccount, toAccount))
91 { throw userError("There is no friend request to accept."); }
92 this.stateDb.deleteAccountFriendRequest(fromAccount, toAccount);
93 this.stateDb.deleteAccountFriendRequest(toAccount, fromAccount);
94 if (!this.stateDb.areAccountFriends(fromAccount, toAccount))
95 { this.stateDb.insertAccountFriendship(fromAccount, toAccount); }
96 return this.snapshot(toChar.character_id);
97 }
98
99 /** Accept / decline / remove by target account id (friends panel). */
100 acceptAccount (characterId, fromAccountId)
101 {
102 const toChar = this.#requireCharacter(characterId);
103 const toAccount = toChar.account_id | 0;
104 const fromAccount = fromAccountId | 0;
105 if (!this.stateDb.getAccountFriendRequest(fromAccount, toAccount))
51 106 { throw userError("There is no friend request to accept."); }
52 this.stateDb.deleteFriendRequest(fromId, toId);
53 this.stateDb.deleteFriendRequest(toId, fromId);
54 if (!this.stateDb.areFriends(fromId, toId))
55 { this.stateDb.insertFriendship(fromId, toId); }
56 return this.snapshot(toId);
107 this.stateDb.deleteAccountFriendRequest(fromAccount, toAccount);
108 this.stateDb.deleteAccountFriendRequest(toAccount, fromAccount);
109 if (!this.stateDb.areAccountFriends(fromAccount, toAccount))
110 { this.stateDb.insertAccountFriendship(fromAccount, toAccount); }
111 return this.snapshot(toChar.character_id);
57 112 }
58 113
59 114 decline (characterId, otherCharacterId)
60 115 {
61 const actorId = Number(characterId);
62 const otherId = Number(otherCharacterId);
63 this.stateDb.deleteFriendRequest(actorId, otherId);
64 this.stateDb.deleteFriendRequest(otherId, actorId);
65 return this.snapshot(actorId);
116 const actor = this.#requireCharacter(characterId);
117 const other = this.stateDb.getCharacter(otherCharacterId);
118 if (!other)
119 { return this.snapshot(actor.character_id); }
120 this.stateDb.deleteAccountFriendRequest(actor.account_id, other.account_id);
121 this.stateDb.deleteAccountFriendRequest(other.account_id, actor.account_id);
122 return this.snapshot(actor.character_id);
123 }
124
125 declineAccount (characterId, otherAccountId)
126 {
127 const actor = this.#requireCharacter(characterId);
128 const otherAccount = otherAccountId | 0;
129 this.stateDb.deleteAccountFriendRequest(actor.account_id, otherAccount);
130 this.stateDb.deleteAccountFriendRequest(otherAccount, actor.account_id);
131 return this.snapshot(actor.character_id);
66 132 }
67 133
68 134 remove (characterId, otherCharacterId)
69 135 {
70 const actorId = Number(characterId);
71 const otherId = Number(otherCharacterId);
72 if (!this.stateDb.areFriends(actorId, otherId))
136 const actor = this.#requireCharacter(characterId);
137 const other = this.#requireCharacter(otherCharacterId);
138 if (!this.stateDb.areAccountFriends(actor.account_id, other.account_id))
139 { throw userError("You are not friends with that player."); }
140 if ((actor.account_id | 0) === (other.account_id | 0))
141 { throw userError("You cannot unfriend your own characters."); }
142 this.stateDb.deleteAccountFriendship(actor.account_id, other.account_id);
143 return this.snapshot(actor.character_id);
144 }
145
146 removeAccount (characterId, otherAccountId)
147 {
148 const actor = this.#requireCharacter(characterId);
149 const otherAccount = otherAccountId | 0;
150 if ((actor.account_id | 0) === otherAccount)
151 { throw userError("You cannot unfriend your own characters."); }
152 if (!this.stateDb.areAccountFriends(actor.account_id, otherAccount))
73 153 { throw userError("You are not friends with that player."); }
74 this.stateDb.deleteFriendship(actorId, otherId);
75 return this.snapshot(actorId);
154 this.stateDb.deleteAccountFriendship(actor.account_id, otherAccount);
155 return this.snapshot(actor.character_id);
76 156 }
77 157
78 158 findByFullName (firstName, lastName)
@@ -81,9 +161,25 @@ export class FriendService
81 161 return row ? this.#publicCharacter(row.character_id) : null;
82 162 }
83 163
84 #namedRequests (rows, idField)
164 #namedAccountRequests (rows, idField)
165 {
166 return rows.map((row) => this.#publicAccount(row[idField])).filter(Boolean);
167 }
168
169 #publicAccount (accountId)
85 170 {
86 return rows.map((row) => this.#publicCharacter(row[idField])).filter(Boolean);
171 const account = this.stateDb.getAccount(accountId);
172 if (!account)
173 { return null; }
174 const characters = this.stateDb.listCharacters(account.account_id)
175 .filter((row) => !row.deletion_scheduled_at)
176 .map((row) => this.#publicCharacter(row.character_id))
177 .filter(Boolean);
178 return {
179 accountId: account.account_id,
180 username: this.stateDb.accountDisplayName(account.account_id),
181 characters
182 };
87 183 }
88 184
89 185 #publicCharacter (characterId)
@@ -91,17 +187,28 @@ export class FriendService
91 187 const row = this.stateDb.getCharacter(characterId);
92 188 if (!row)
93 189 { return null; }
190 const bag = this.stateDb.getBag(characterId);
94 191 return {
95 192 characterId: row.character_id,
193 accountId: row.account_id,
96 194 firstName: row.first_name,
97 lastName: row.last_name
195 lastName: row.last_name,
196 sex: row.sex,
197 layers: layersFromBag(row.sex, bag)
98 198 };
99 199 }
100 200
201 #accountId (characterId)
202 {
203 return this.#requireCharacter(characterId).account_id | 0;
204 }
205
101 206 #requireCharacter (characterId)
102 207 {
103 if (!this.stateDb.getCharacter(characterId))
208 const row = this.stateDb.getCharacter(characterId);
209 if (!row)
104 210 { throw userError("That player does not exist."); }
211 return row;
105 212 }
106 213 }
107 214
@@ -1,3 +1,9 @@
1import { layersFromBag } from "../../../shared/appearance/layers.js";
2
3/**
4 * Account-wide friends: requests and friendships key on account_id.
5 * Same-account characters are always treated as friends.
6 */
1export class FriendService
7export class FriendService
2{
8{
3 constructor (stateDb)
9 constructor (stateDb)
@@ -7,16 +13,46 @@ export class FriendService
7
13
8 snapshot (characterId)
14 snapshot (characterId)
9 {
15 {
16 const accountId = this.#accountId(characterId);
10 return {
17 return {
11 friends: this.listFriends(characterId),
18 friends: this.listFriendAccounts(accountId),
12 incoming: this.#namedRequests(this.stateDb.listIncomingRequests(characterId), "from_character_id"),
19 incoming: this.#namedAccountRequests(
13 outgoing: this.#namedRequests(this.stateDb.listOutgoingRequests(characterId), "to_character_id")
20 this.stateDb.listIncomingAccountRequests(accountId),
21 "from_account_id"
22 ),
23 outgoing: this.#namedAccountRequests(
24 this.stateDb.listOutgoingAccountRequests(accountId),
25 "to_account_id"
26 )
14 };
27 };
15 }
28 }
16
29
30 /** Flat character list for pigeon address book (all chars on friend accounts). */
17 listFriends (characterId)
31 listFriends (characterId)
18 {
32 {
19 return this.stateDb.listFriendRecords(characterId).map((row) => this.#publicCharacter(row.character_id)).filter(Boolean);
33 const accounts = this.listFriendAccounts(this.#accountId(characterId));
34 const out = [];
35 for (const account of accounts)
36 {
37 for (const character of account.characters ?? [])
38 { out.push(character); }
39 }
40 return out;
41 }
42
43 listFriendAccounts (accountId)
44 {
45 const id = accountId | 0;
46 if (!id)
47 { return []; }
48 return this.stateDb.listAccountFriendRecords(id)
49 .map((row) => this.#publicAccount(row.account_id))
50 .filter(Boolean);
51 }
52
53 areFriends (characterId, otherCharacterId)
54 {
55 return this.stateDb.areFriends(characterId, otherCharacterId);
20 }
56 }
21
57
22 request (fromCharacterId, toCharacterId)
58 request (fromCharacterId, toCharacterId)
@@ -25,54 +61,98 @@ export class FriendService
25 const toId = Number(toCharacterId);
61 const toId = Number(toCharacterId);
26 if (fromId === toId)
62 if (fromId === toId)
27 { throw userError("You cannot friend yourself."); }
63 { throw userError("You cannot friend yourself."); }
28 this.#requireCharacter(fromId);
64 const from = this.#requireCharacter(fromId);
29 this.#requireCharacter(toId);
65 const to = this.#requireCharacter(toId);
30 if (this.stateDb.areFriends(fromId, toId))
66 const fromAccount = from.account_id | 0;
67 const toAccount = to.account_id | 0;
68 if (fromAccount === toAccount)
69 { throw userError("You are already friends with your own characters."); }
70 if (this.stateDb.areAccountFriends(fromAccount, toAccount))
31 { throw userError("You are already friends."); }
71 { throw userError("You are already friends."); }
32 if (this.stateDb.getFriendRequest(fromId, toId))
72 if (this.stateDb.getAccountFriendRequest(fromAccount, toAccount))
33 { throw userError("Friend request already sent."); }
73 { throw userError("Friend request already sent."); }
34 if (this.stateDb.getFriendRequest(toId, fromId))
74 if (this.stateDb.getAccountFriendRequest(toAccount, fromAccount))
35 {
75 {
36 this.stateDb.deleteFriendRequest(toId, fromId);
76 this.stateDb.deleteAccountFriendRequest(toAccount, fromAccount);
37 this.stateDb.insertFriendship(fromId, toId);
77 this.stateDb.insertAccountFriendship(fromAccount, toAccount);
38 return this.snapshot(fromId);
78 return this.snapshot(fromId);
39 }
79 }
40 this.stateDb.insertFriendRequest(fromId, toId);
80 this.stateDb.insertAccountFriendRequest(fromAccount, toAccount);
41 return this.snapshot(fromId);
81 return this.snapshot(fromId);
42 }
82 }
43
83
44 accept (characterId, fromCharacterId)
84 accept (characterId, fromCharacterId)
45 {
85 {
46 const toId = Number(characterId);
86 const toChar = this.#requireCharacter(characterId);
47 const fromId = Number(fromCharacterId);
87 const fromChar = this.#requireCharacter(fromCharacterId);
48 this.#requireCharacter(toId);
88 const toAccount = toChar.account_id | 0;
49 this.#requireCharacter(fromId);
89 const fromAccount = fromChar.account_id | 0;
50 if (!this.stateDb.getFriendRequest(fromId, toId))
90 if (!this.stateDb.getAccountFriendRequest(fromAccount, toAccount))
91 { throw userError("There is no friend request to accept."); }
92 this.stateDb.deleteAccountFriendRequest(fromAccount, toAccount);
93 this.stateDb.deleteAccountFriendRequest(toAccount, fromAccount);
94 if (!this.stateDb.areAccountFriends(fromAccount, toAccount))
95 { this.stateDb.insertAccountFriendship(fromAccount, toAccount); }
96 return this.snapshot(toChar.character_id);
97 }
98
99 /** Accept / decline / remove by target account id (friends panel). */
100 acceptAccount (characterId, fromAccountId)
101 {
102 const toChar = this.#requireCharacter(characterId);
103 const toAccount = toChar.account_id | 0;
104 const fromAccount = fromAccountId | 0;
105 if (!this.stateDb.getAccountFriendRequest(fromAccount, toAccount))
51 { throw userError("There is no friend request to accept."); }
106 { throw userError("There is no friend request to accept."); }
52 this.stateDb.deleteFriendRequest(fromId, toId);
107 this.stateDb.deleteAccountFriendRequest(fromAccount, toAccount);
53 this.stateDb.deleteFriendRequest(toId, fromId);
108 this.stateDb.deleteAccountFriendRequest(toAccount, fromAccount);
54 if (!this.stateDb.areFriends(fromId, toId))
109 if (!this.stateDb.areAccountFriends(fromAccount, toAccount))
55 { this.stateDb.insertFriendship(fromId, toId); }
110 { this.stateDb.insertAccountFriendship(fromAccount, toAccount); }
56 return this.snapshot(toId);
111 return this.snapshot(toChar.character_id);
57 }
112 }
58
113
59 decline (characterId, otherCharacterId)
114 decline (characterId, otherCharacterId)
60 {
115 {
61 const actorId = Number(characterId);
116 const actor = this.#requireCharacter(characterId);
62 const otherId = Number(otherCharacterId);
117 const other = this.stateDb.getCharacter(otherCharacterId);
63 this.stateDb.deleteFriendRequest(actorId, otherId);
118 if (!other)
64 this.stateDb.deleteFriendRequest(otherId, actorId);
119 { return this.snapshot(actor.character_id); }
65 return this.snapshot(actorId);
120 this.stateDb.deleteAccountFriendRequest(actor.account_id, other.account_id);
121 this.stateDb.deleteAccountFriendRequest(other.account_id, actor.account_id);
122 return this.snapshot(actor.character_id);
123 }
124
125 declineAccount (characterId, otherAccountId)
126 {
127 const actor = this.#requireCharacter(characterId);
128 const otherAccount = otherAccountId | 0;
129 this.stateDb.deleteAccountFriendRequest(actor.account_id, otherAccount);
130 this.stateDb.deleteAccountFriendRequest(otherAccount, actor.account_id);
131 return this.snapshot(actor.character_id);
66 }
132 }
67
133
68 remove (characterId, otherCharacterId)
134 remove (characterId, otherCharacterId)
69 {
135 {
70 const actorId = Number(characterId);
136 const actor = this.#requireCharacter(characterId);
71 const otherId = Number(otherCharacterId);
137 const other = this.#requireCharacter(otherCharacterId);
72 if (!this.stateDb.areFriends(actorId, otherId))
138 if (!this.stateDb.areAccountFriends(actor.account_id, other.account_id))
139 { throw userError("You are not friends with that player."); }
140 if ((actor.account_id | 0) === (other.account_id | 0))
141 { throw userError("You cannot unfriend your own characters."); }
142 this.stateDb.deleteAccountFriendship(actor.account_id, other.account_id);
143 return this.snapshot(actor.character_id);
144 }
145
146 removeAccount (characterId, otherAccountId)
147 {
148 const actor = this.#requireCharacter(characterId);
149 const otherAccount = otherAccountId | 0;
150 if ((actor.account_id | 0) === otherAccount)
151 { throw userError("You cannot unfriend your own characters."); }
152 if (!this.stateDb.areAccountFriends(actor.account_id, otherAccount))
73 { throw userError("You are not friends with that player."); }
153 { throw userError("You are not friends with that player."); }
74 this.stateDb.deleteFriendship(actorId, otherId);
154 this.stateDb.deleteAccountFriendship(actor.account_id, otherAccount);
75 return this.snapshot(actorId);
155 return this.snapshot(actor.character_id);
76 }
156 }
77
157
78 findByFullName (firstName, lastName)
158 findByFullName (firstName, lastName)
@@ -81,9 +161,25 @@ export class FriendService
81 return row ? this.#publicCharacter(row.character_id) : null;
161 return row ? this.#publicCharacter(row.character_id) : null;
82 }
162 }
83
163
84 #namedRequests (rows, idField)
164 #namedAccountRequests (rows, idField)
165 {
166 return rows.map((row) => this.#publicAccount(row[idField])).filter(Boolean);
167 }
168
169 #publicAccount (accountId)
85 {
170 {
86 return rows.map((row) => this.#publicCharacter(row[idField])).filter(Boolean);
171 const account = this.stateDb.getAccount(accountId);
172 if (!account)
173 { return null; }
174 const characters = this.stateDb.listCharacters(account.account_id)
175 .filter((row) => !row.deletion_scheduled_at)
176 .map((row) => this.#publicCharacter(row.character_id))
177 .filter(Boolean);
178 return {
179 accountId: account.account_id,
180 username: this.stateDb.accountDisplayName(account.account_id),
181 characters
182 };
87 }
183 }
88
184
89 #publicCharacter (characterId)
185 #publicCharacter (characterId)
@@ -91,17 +187,28 @@ export class FriendService
91 const row = this.stateDb.getCharacter(characterId);
187 const row = this.stateDb.getCharacter(characterId);
92 if (!row)
188 if (!row)
93 { return null; }
189 { return null; }
190 const bag = this.stateDb.getBag(characterId);
94 return {
191 return {
95 characterId: row.character_id,
192 characterId: row.character_id,
193 accountId: row.account_id,
96 firstName: row.first_name,
194 firstName: row.first_name,
97 lastName: row.last_name
195 lastName: row.last_name,
196 sex: row.sex,
197 layers: layersFromBag(row.sex, bag)
98 };
198 };
99 }
199 }
100
200
201 #accountId (characterId)
202 {
203 return this.#requireCharacter(characterId).account_id | 0;
204 }
205
101 #requireCharacter (characterId)
206 #requireCharacter (characterId)
102 {
207 {
103 if (!this.stateDb.getCharacter(characterId))
208 const row = this.stateDb.getCharacter(characterId);
209 if (!row)
104 { throw userError("That player does not exist."); }
210 { throw userError("That player does not exist."); }
211 return row;
105 }
212 }
106}
213}
107
214
server/src/gateway/websocket.js +57 −18
@@ -202,18 +202,27 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
202 202 break;
203 203 case MessageType.friendAccept:
204 204 requirePlaying(session);
205 friends.accept(session.characterId, message.characterId);
206 pushFriends(session.characterId, message.characterId);
205 if (message.accountId)
206 { friends.acceptAccount(session.characterId, message.accountId); }
207 else
208 { friends.accept(session.characterId, message.characterId); }
209 pushFriends(session.characterId, message.characterId, message.accountId);
207 210 break;
208 211 case MessageType.friendDecline:
209 212 requirePlaying(session);
210 friends.decline(session.characterId, message.characterId);
211 pushFriends(session.characterId, message.characterId);
213 if (message.accountId)
214 { friends.declineAccount(session.characterId, message.accountId); }
215 else
216 { friends.decline(session.characterId, message.characterId); }
217 pushFriends(session.characterId, message.characterId, message.accountId);
212 218 break;
213 219 case MessageType.friendRemove:
214 220 requirePlaying(session);
215 friends.remove(session.characterId, message.characterId);
216 pushFriends(session.characterId, message.characterId);
221 if (message.accountId)
222 { friends.removeAccount(session.characterId, message.accountId); }
223 else
224 { friends.remove(session.characterId, message.characterId); }
225 pushFriends(session.characterId, message.characterId, message.accountId);
217 226 break;
218 227 case MessageType.chatSay:
219 228 requirePlaying(session);
@@ -1110,6 +1119,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1110 1119 type: MessageType.enterWorld,
1111 1120 entityId: session.entityId,
1112 1121 characterId: session.characterId,
1122 accountId: session.account?.account_id ?? null,
1113 1123 tileX: spawned.tileX,
1114 1124 tileY: spawned.tileY,
1115 1125 dimensionId: enterDim,
@@ -1122,6 +1132,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1122 1132 layers: spawned.layers ?? [],
1123 1133 health: spawned.health,
1124 1134 maxHealth: spawned.maxHealth,
1135 skullValue: spawned.skullValue | 0,
1125 1136 settings: simulation.settings,
1126 1137 worldTime: simulation.worldTime(),
1127 1138 restartStatus: deploy?.getStatus?.() ?? { scheduled: false }
@@ -1328,21 +1339,36 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1328 1339 }
1329 1340 }
1330 1341
1331 function pushFriends (...characterIds)
1342 function pushFriends (...refs)
1332 1343 {
1333 const seen = new Set();
1334 for (const characterId of characterIds)
1344 const accountIds = new Set();
1345 for (const ref of refs)
1335 1346 {
1336 const id = Number(characterId);
1337 if (!id || seen.has(id))
1347 if (ref == null)
1338 1348 { continue; }
1339 seen.add(id);
1340 const payload = { type: MessageType.friends, ...friends.snapshot(id) };
1341 for (const session of sessions.values())
1349 if (typeof ref === "object" && ref.accountId != null)
1342 1350 {
1343 if (session.characterId === id)
1344 { send(session, payload); }
1351 accountIds.add(ref.accountId | 0);
1352 continue;
1345 1353 }
1354 const asNumber = Number(ref);
1355 if (!asNumber)
1356 { continue; }
1357 // Heuristic: character ids from messages; also accept bare account ids from panel.
1358 const character = stateDb.getCharacter(asNumber);
1359 if (character)
1360 { accountIds.add(character.account_id | 0); }
1361 else if (stateDb.getAccount(asNumber))
1362 { accountIds.add(asNumber); }
1363 }
1364 for (const session of sessions.values())
1365 {
1366 if (!session.characterId)
1367 { continue; }
1368 const accountId = session.account?.account_id | 0;
1369 if (!accountIds.has(accountId))
1370 { continue; }
1371 send(session, { type: MessageType.friends, ...friends.snapshot(session.characterId) });
1346 1372 }
1347 1373 }
1348 1374
@@ -1820,7 +1846,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1820 1846 }
1821 1847 continue;
1822 1848 }
1823 if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block" || event.type === "combat-projectile" || event.type === "spell-projectile" || event.type === "spell-fizzle" || event.type === "spell-cast-flash" || event.type === "spell-light-appear" || event.type === "spell-light-update" || event.type === "spell-light-remove" || event.type === "spell-dark-appear" || event.type === "spell-dark-update" || event.type === "spell-dark-remove" || event.type === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")
1849 if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "entity-skull" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block" || event.type === "combat-projectile" || event.type === "spell-projectile" || event.type === "spell-fizzle" || event.type === "spell-cast-flash" || event.type === "spell-light-appear" || event.type === "spell-light-update" || event.type === "spell-light-remove" || event.type === "spell-dark-appear" || event.type === "spell-dark-update" || event.type === "spell-dark-remove" || event.type === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")
1824 1850 { publishEntity(event); }
1825 1851 }
1826 1852 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
@@ -1881,6 +1907,17 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1881 1907 });
1882 1908 continue;
1883 1909 }
1910 if (event.type === "entity-skull")
1911 {
1912 if (!seesTo && session.entityId !== event.entityId)
1913 { continue; }
1914 send(session, {
1915 type: MessageType.entitySkull,
1916 entityId: event.entityId,
1917 skullValue: event.skullValue | 0
1918 });
1919 continue;
1920 }
1884 1921 if (event.type === "ground-item-appear")
1885 1922 {
1886 1923 if (!seesTo)
@@ -2139,6 +2176,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
2139 2176 type: MessageType.entitySpawn,
2140 2177 entityId: event.entityId,
2141 2178 characterId: record.characterId ?? event.characterId ?? null,
2179 accountId: record.accountId ?? event.accountId ?? null,
2142 2180 tileX: event.tileX ?? record.tileX,
2143 2181 tileY: event.tileY ?? record.tileY,
2144 2182 worldX: event.worldX ?? record.worldX,
@@ -2159,7 +2197,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
2159 2197 freeFlight: !!(record.freeFlight ?? event.freeFlight),
2160 2198 health: record.health ?? event.health,
2161 2199 maxHealth: record.maxHealth ?? event.maxHealth,
2162 lightRadiusTiles: record.lightRadiusTiles ?? event.lightRadiusTiles ?? 0
2200 lightRadiusTiles: record.lightRadiusTiles ?? event.lightRadiusTiles ?? 0,
2201 skullValue: record.skullValue | 0
2163 2202 };
2164 2203 }
2165 2204
@@ -202,18 +202,27 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
202 break;
202 break;
203 case MessageType.friendAccept:
203 case MessageType.friendAccept:
204 requirePlaying(session);
204 requirePlaying(session);
205 friends.accept(session.characterId, message.characterId);
205 if (message.accountId)
206 pushFriends(session.characterId, message.characterId);
206 { friends.acceptAccount(session.characterId, message.accountId); }
207 else
208 { friends.accept(session.characterId, message.characterId); }
209 pushFriends(session.characterId, message.characterId, message.accountId);
207 break;
210 break;
208 case MessageType.friendDecline:
211 case MessageType.friendDecline:
209 requirePlaying(session);
212 requirePlaying(session);
210 friends.decline(session.characterId, message.characterId);
213 if (message.accountId)
211 pushFriends(session.characterId, message.characterId);
214 { friends.declineAccount(session.characterId, message.accountId); }
215 else
216 { friends.decline(session.characterId, message.characterId); }
217 pushFriends(session.characterId, message.characterId, message.accountId);
212 break;
218 break;
213 case MessageType.friendRemove:
219 case MessageType.friendRemove:
214 requirePlaying(session);
220 requirePlaying(session);
215 friends.remove(session.characterId, message.characterId);
221 if (message.accountId)
216 pushFriends(session.characterId, message.characterId);
222 { friends.removeAccount(session.characterId, message.accountId); }
223 else
224 { friends.remove(session.characterId, message.characterId); }
225 pushFriends(session.characterId, message.characterId, message.accountId);
217 break;
226 break;
218 case MessageType.chatSay:
227 case MessageType.chatSay:
219 requirePlaying(session);
228 requirePlaying(session);
@@ -1110,6 +1119,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1110 type: MessageType.enterWorld,
1119 type: MessageType.enterWorld,
1111 entityId: session.entityId,
1120 entityId: session.entityId,
1112 characterId: session.characterId,
1121 characterId: session.characterId,
1122 accountId: session.account?.account_id ?? null,
1113 tileX: spawned.tileX,
1123 tileX: spawned.tileX,
1114 tileY: spawned.tileY,
1124 tileY: spawned.tileY,
1115 dimensionId: enterDim,
1125 dimensionId: enterDim,
@@ -1122,6 +1132,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1122 layers: spawned.layers ?? [],
1132 layers: spawned.layers ?? [],
1123 health: spawned.health,
1133 health: spawned.health,
1124 maxHealth: spawned.maxHealth,
1134 maxHealth: spawned.maxHealth,
1135 skullValue: spawned.skullValue | 0,
1125 settings: simulation.settings,
1136 settings: simulation.settings,
1126 worldTime: simulation.worldTime(),
1137 worldTime: simulation.worldTime(),
1127 restartStatus: deploy?.getStatus?.() ?? { scheduled: false }
1138 restartStatus: deploy?.getStatus?.() ?? { scheduled: false }
@@ -1328,21 +1339,36 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1328 }
1339 }
1329 }
1340 }
1330
1341
1331 function pushFriends (...characterIds)
1342 function pushFriends (...refs)
1332 {
1343 {
1333 const seen = new Set();
1344 const accountIds = new Set();
1334 for (const characterId of characterIds)
1345 for (const ref of refs)
1335 {
1346 {
1336 const id = Number(characterId);
1347 if (ref == null)
1337 if (!id || seen.has(id))
1338 { continue; }
1348 { continue; }
1339 seen.add(id);
1349 if (typeof ref === "object" && ref.accountId != null)
1340 const payload = { type: MessageType.friends, ...friends.snapshot(id) };
1341 for (const session of sessions.values())
1342 {
1350 {
1343 if (session.characterId === id)
1351 accountIds.add(ref.accountId | 0);
1344 { send(session, payload); }
1352 continue;
1345 }
1353 }
1354 const asNumber = Number(ref);
1355 if (!asNumber)
1356 { continue; }
1357 // Heuristic: character ids from messages; also accept bare account ids from panel.
1358 const character = stateDb.getCharacter(asNumber);
1359 if (character)
1360 { accountIds.add(character.account_id | 0); }
1361 else if (stateDb.getAccount(asNumber))
1362 { accountIds.add(asNumber); }
1363 }
1364 for (const session of sessions.values())
1365 {
1366 if (!session.characterId)
1367 { continue; }
1368 const accountId = session.account?.account_id | 0;
1369 if (!accountIds.has(accountId))
1370 { continue; }
1371 send(session, { type: MessageType.friends, ...friends.snapshot(session.characterId) });
1346 }
1372 }
1347 }
1373 }
1348
1374
@@ -1820,7 +1846,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1820 }
1846 }
1821 continue;
1847 continue;
1822 }
1848 }
1823 if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block" || event.type === "combat-projectile" || event.type === "spell-projectile" || event.type === "spell-fizzle" || event.type === "spell-cast-flash" || event.type === "spell-light-appear" || event.type === "spell-light-update" || event.type === "spell-light-remove" || event.type === "spell-dark-appear" || event.type === "spell-dark-update" || event.type === "spell-dark-remove" || event.type === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")
1849 if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "entity-skull" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block" || event.type === "combat-projectile" || event.type === "spell-projectile" || event.type === "spell-fizzle" || event.type === "spell-cast-flash" || event.type === "spell-light-appear" || event.type === "spell-light-update" || event.type === "spell-light-remove" || event.type === "spell-dark-appear" || event.type === "spell-dark-update" || event.type === "spell-dark-remove" || event.type === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")
1824 { publishEntity(event); }
1850 { publishEntity(event); }
1825 }
1851 }
1826 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
1852 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
@@ -1881,6 +1907,17 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1881 });
1907 });
1882 continue;
1908 continue;
1883 }
1909 }
1910 if (event.type === "entity-skull")
1911 {
1912 if (!seesTo && session.entityId !== event.entityId)
1913 { continue; }
1914 send(session, {
1915 type: MessageType.entitySkull,
1916 entityId: event.entityId,
1917 skullValue: event.skullValue | 0
1918 });
1919 continue;
1920 }
1884 if (event.type === "ground-item-appear")
1921 if (event.type === "ground-item-appear")
1885 {
1922 {
1886 if (!seesTo)
1923 if (!seesTo)
@@ -2139,6 +2176,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
2139 type: MessageType.entitySpawn,
2176 type: MessageType.entitySpawn,
2140 entityId: event.entityId,
2177 entityId: event.entityId,
2141 characterId: record.characterId ?? event.characterId ?? null,
2178 characterId: record.characterId ?? event.characterId ?? null,
2179 accountId: record.accountId ?? event.accountId ?? null,
2142 tileX: event.tileX ?? record.tileX,
2180 tileX: event.tileX ?? record.tileX,
2143 tileY: event.tileY ?? record.tileY,
2181 tileY: event.tileY ?? record.tileY,
2144 worldX: event.worldX ?? record.worldX,
2182 worldX: event.worldX ?? record.worldX,
@@ -2159,7 +2197,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
2159 freeFlight: !!(record.freeFlight ?? event.freeFlight),
2197 freeFlight: !!(record.freeFlight ?? event.freeFlight),
2160 health: record.health ?? event.health,
2198 health: record.health ?? event.health,
2161 maxHealth: record.maxHealth ?? event.maxHealth,
2199 maxHealth: record.maxHealth ?? event.maxHealth,
2162 lightRadiusTiles: record.lightRadiusTiles ?? event.lightRadiusTiles ?? 0
2200 lightRadiusTiles: record.lightRadiusTiles ?? event.lightRadiusTiles ?? 0,
2201 skullValue: record.skullValue | 0
2163 };
2202 };
2164 }
2203 }
2165
2204
server/src/persistence/stateDb.js +240 −34
@@ -5,6 +5,7 @@ import { itemDefinition, ItemId } from "../../../shared/definitions/items.js";
5 5 import { buildStarterBagContents } from "../../../shared/items/starterLoadout.js";
6 6 import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";
7 7 import { normalizePlayerSpells, defaultPlayerSpells, storedPlayerSpells } from "../../../shared/spells/state.js";
8 import { decayKillCounter } from "../../../shared/combat/skull.js";
8 9
9 10 const STATE_SCHEMA = `
10 11 CREATE TABLE IF NOT EXISTS accounts (
@@ -208,7 +209,7 @@ CREATE TABLE IF NOT EXISTS character_visited_dimensions (
208 209
209 210 export class StateDatabase
210 211 {
211 constructor (filePath)
212 constructor(filePath)
212 213 {
213 214 this.db = openDatabase(filePath);
214 215 this.db.exec(STATE_SCHEMA);
@@ -254,6 +255,28 @@ export class StateDatabase
254 255 const accountColumns = this.db.prepare("PRAGMA table_info(accounts)").all();
255 256 if (!accountColumns.some((column) => column.name === "username"))
256 257 { this.db.exec("ALTER TABLE accounts ADD COLUMN username TEXT"); }
258 if (!characterColumns.some((column) => column.name === "kill_counter"))
259 { this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter REAL NOT NULL DEFAULT 0"); }
260 if (!characterColumns.some((column) => column.name === "kill_counter_at"))
261 { this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter_at INTEGER"); }
262 this.db.exec(`
263 CREATE TABLE IF NOT EXISTS account_friend_requests (
264 request_id INTEGER PRIMARY KEY AUTOINCREMENT,
265 from_account_id INTEGER NOT NULL,
266 to_account_id INTEGER NOT NULL,
267 created_at INTEGER NOT NULL,
268 UNIQUE (from_account_id, to_account_id)
269 )
270 `);
271 this.db.exec(`
272 CREATE TABLE IF NOT EXISTS account_friendships (
273 account_id_a INTEGER NOT NULL,
274 account_id_b INTEGER NOT NULL,
275 created_at INTEGER NOT NULL,
276 PRIMARY KEY (account_id_a, account_id_b)
277 )
278 `);
279 this.#migrateCharacterFriendsToAccounts();
257 280 this.db.exec(`
258 281 CREATE TABLE IF NOT EXISTS auth_sessions (
259 282 session_id TEXT PRIMARY KEY,
@@ -270,6 +293,45 @@ export class StateDatabase
270 293 this.#grantLanternsToExistingCharacters();
271 294 }
272 295
296 /** One-time: lift legacy character friendships / requests to account scope. */
297 #migrateCharacterFriendsToAccounts ()
298 {
299 const legacyFriends = this.db.prepare("SELECT character_id_a, character_id_b, created_at FROM friendships").all();
300 const insertFriend = this.db.prepare(`
301 INSERT OR IGNORE INTO account_friendships (account_id_a, account_id_b, created_at)
302 VALUES (?, ?, ?)
303 `);
304 for (const row of legacyFriends)
305 {
306 const a = this.getCharacter(row.character_id_a);
307 const b = this.getCharacter(row.character_id_b);
308 if (!a || !b || a.account_id === b.account_id)
309 { continue; }
310 const [idA, idB] = pairIds(a.account_id, b.account_id);
311 insertFriend.run(idA, idB, row.created_at | 0 || Date.now());
312 }
313 const legacyRequests = this.db.prepare(`
314 SELECT from_character_id, to_character_id, created_at FROM friend_requests
315 `).all();
316 const insertReq = this.db.prepare(`
317 INSERT OR IGNORE INTO account_friend_requests (from_account_id, to_account_id, created_at)
318 VALUES (?, ?, ?)
319 `);
320 for (const row of legacyRequests)
321 {
322 const from = this.getCharacter(row.from_character_id);
323 const to = this.getCharacter(row.to_character_id);
324 if (!from || !to || from.account_id === to.account_id)
325 { continue; }
326 insertReq.run(from.account_id, to.account_id, row.created_at | 0 || Date.now());
327 }
328 if (legacyFriends.length || legacyRequests.length)
329 {
330 this.db.exec("DELETE FROM friendships");
331 this.db.exec("DELETE FROM friend_requests");
332 }
333 }
334
273 335 createAuthSession ({ sessionId, authSubject, username = null, email = null, accessToken = null, expiresAtMs })
274 336 {
275 337 this.db.prepare(`
@@ -571,6 +633,8 @@ export class StateDatabase
571 633 this.#moveGoodsToInheritance(character);
572 634 this.db.prepare("DELETE FROM character_bags WHERE character_id = ?").run(characterId);
573 635 this.db.prepare("DELETE FROM characters WHERE character_id = ?").run(characterId);
636 this.db.prepare("DELETE FROM character_bounties WHERE character_id = ?").run(characterId);
637 // Account friendships persist; only clear legacy character rows if any remain.
574 638 this.db.prepare("DELETE FROM friend_requests WHERE from_character_id = ? OR to_character_id = ?").run(
575 639 characterId,
576 640 characterId
@@ -862,84 +926,226 @@ export class StateDatabase
862 926 }
863 927
864 928 listFriendRecords (characterId)
929 {
930 return this.listAccountFriendRecords(this.accountIdOfCharacter(characterId));
931 }
932
933 accountIdOfCharacter (characterId)
934 {
935 const row = this.getCharacter(characterId);
936 return row?.account_id | 0;
937 }
938
939 getAccount (accountId)
865 940 {
941 return this.db.prepare(`
942 SELECT account_id, auth_subject, username, email, is_admin
943 FROM accounts WHERE account_id = ?
944 `).get(accountId | 0) ?? null;
945 }
946
947 accountDisplayName (accountId)
948 {
949 const row = this.getAccount(accountId);
950 if (!row)
951 { return "Unknown"; }
952 const name = String(row.username ?? "").trim();
953 return name || `Account ${row.account_id}`;
954 }
955
956 listAccountFriendRecords (accountId)
957 {
958 const id = accountId | 0;
959 if (!id)
960 { return []; }
866 961 return this.db.prepare(`
867 962 SELECT
868 CASE WHEN character_id_a = ? THEN character_id_b ELSE character_id_a END AS character_id,
963 CASE WHEN account_id_a = ? THEN account_id_b ELSE account_id_a END AS account_id,
869 964 created_at
870 FROM friendships
871 WHERE character_id_a = ? OR character_id_b = ?
965 FROM account_friendships
966 WHERE account_id_a = ? OR account_id_b = ?
872 967 ORDER BY created_at ASC
873 `).all(characterId, characterId, characterId);
968 `).all(id, id, id);
874 969 }
875 970
876 areFriends (characterId, otherId)
971 areAccountFriends (accountId, otherAccountId)
877 972 {
878 const [a, b] = pairIds(characterId, otherId);
973 const aId = accountId | 0;
974 const bId = otherAccountId | 0;
975 if (!aId || !bId)
976 { return false; }
977 if (aId === bId)
978 { return true; }
979 const [a, b] = pairIds(aId, bId);
879 980 return !!this.db.prepare(`
880 SELECT 1 FROM friendships WHERE character_id_a = ? AND character_id_b = ?
981 SELECT 1 FROM account_friendships WHERE account_id_a = ? AND account_id_b = ?
881 982 `).get(a, b);
882 983 }
883 984
884 insertFriendship (characterId, otherId)
985 areFriends (characterId, otherId)
986 {
987 const left = this.getCharacter(characterId);
988 const right = this.getCharacter(otherId);
989 if (!left || !right)
990 { return false; }
991 return this.areAccountFriends(left.account_id, right.account_id);
992 }
993
994 insertAccountFriendship (accountId, otherId)
885 995 {
886 const [a, b] = pairIds(characterId, otherId);
996 const [a, b] = pairIds(accountId, otherId);
887 997 this.db.prepare(`
888 INSERT INTO friendships (character_id_a, character_id_b, created_at)
998 INSERT OR IGNORE INTO account_friendships (account_id_a, account_id_b, created_at)
889 999 VALUES (?, ?, ?)
890 1000 `).run(a, b, Date.now());
891 1001 }
892 1002
893 deleteFriendship (characterId, otherId)
1003 insertFriendship (characterId, otherId)
1004 {
1005 const left = this.getCharacter(characterId);
1006 const right = this.getCharacter(otherId);
1007 if (!left || !right)
1008 { return; }
1009 this.insertAccountFriendship(left.account_id, right.account_id);
1010 }
1011
1012 deleteAccountFriendship (accountId, otherId)
894 1013 {
895 const [a, b] = pairIds(characterId, otherId);
1014 const [a, b] = pairIds(accountId, otherId);
896 1015 this.db.prepare(`
897 DELETE FROM friendships WHERE character_id_a = ? AND character_id_b = ?
1016 DELETE FROM account_friendships WHERE account_id_a = ? AND account_id_b = ?
898 1017 `).run(a, b);
899 1018 }
900 1019
901 listIncomingRequests (characterId)
1020 deleteFriendship (characterId, otherId)
1021 {
1022 const left = this.getCharacter(characterId);
1023 const right = this.getCharacter(otherId);
1024 if (!left || !right)
1025 { return; }
1026 this.deleteAccountFriendship(left.account_id, right.account_id);
1027 }
1028
1029 listIncomingAccountRequests (accountId)
902 1030 {
903 1031 return this.db.prepare(`
904 SELECT request_id, from_character_id, to_character_id, created_at
905 FROM friend_requests
906 WHERE to_character_id = ?
1032 SELECT request_id, from_account_id, to_account_id, created_at
1033 FROM account_friend_requests
1034 WHERE to_account_id = ?
907 1035 ORDER BY created_at ASC
908 `).all(characterId);
1036 `).all(accountId | 0);
909 1037 }
910 1038
911 listOutgoingRequests (characterId)
1039 listOutgoingAccountRequests (accountId)
912 1040 {
913 1041 return this.db.prepare(`
914 SELECT request_id, from_character_id, to_character_id, created_at
915 FROM friend_requests
916 WHERE from_character_id = ?
1042 SELECT request_id, from_account_id, to_account_id, created_at
1043 FROM account_friend_requests
1044 WHERE from_account_id = ?
917 1045 ORDER BY created_at ASC
918 `).all(characterId);
1046 `).all(accountId | 0);
919 1047 }
920 1048
921 getFriendRequest (fromId, toId)
1049 listIncomingRequests (characterId)
1050 {
1051 return this.listIncomingAccountRequests(this.accountIdOfCharacter(characterId));
1052 }
1053
1054 listOutgoingRequests (characterId)
1055 {
1056 return this.listOutgoingAccountRequests(this.accountIdOfCharacter(characterId));
1057 }
1058
1059 getAccountFriendRequest (fromAccountId, toAccountId)
922 1060 {
923 1061 return this.db.prepare(`
924 SELECT * FROM friend_requests
925 WHERE from_character_id = ? AND to_character_id = ?
926 `).get(fromId, toId) ?? null;
1062 SELECT * FROM account_friend_requests
1063 WHERE from_account_id = ? AND to_account_id = ?
1064 `).get(fromAccountId | 0, toAccountId | 0) ?? null;
927 1065 }
928 1066
929 insertFriendRequest (fromId, toId)
1067 getFriendRequest (fromId, toId)
1068 {
1069 const from = this.getCharacter(fromId);
1070 const to = this.getCharacter(toId);
1071 if (!from || !to)
1072 { return null; }
1073 return this.getAccountFriendRequest(from.account_id, to.account_id);
1074 }
1075
1076 insertAccountFriendRequest (fromAccountId, toAccountId)
930 1077 {
931 1078 this.db.prepare(`
932 INSERT INTO friend_requests (from_character_id, to_character_id, created_at)
1079 INSERT INTO account_friend_requests (from_account_id, to_account_id, created_at)
933 1080 VALUES (?, ?, ?)
934 `).run(fromId, toId, Date.now());
1081 `).run(fromAccountId | 0, toAccountId | 0, Date.now());
1082 }
1083
1084 insertFriendRequest (fromId, toId)
1085 {
1086 const from = this.getCharacter(fromId);
1087 const to = this.getCharacter(toId);
1088 if (!from || !to)
1089 { return; }
1090 this.insertAccountFriendRequest(from.account_id, to.account_id);
1091 }
1092
1093 deleteAccountFriendRequest (fromAccountId, toAccountId)
1094 {
1095 this.db.prepare(`
1096 DELETE FROM account_friend_requests
1097 WHERE from_account_id = ? AND to_account_id = ?
1098 `).run(fromAccountId | 0, toAccountId | 0);
935 1099 }
936 1100
937 1101 deleteFriendRequest (fromId, toId)
938 1102 {
1103 const from = this.getCharacter(fromId);
1104 const to = this.getCharacter(toId);
1105 if (!from || !to)
1106 { return; }
1107 this.deleteAccountFriendRequest(from.account_id, to.account_id);
1108 }
1109
1110 /** Decayed kill counter at `now` (does not write). */
1111 peekKillCounter (characterId, now = Date.now())
1112 {
1113 const row = this.getCharacter(characterId);
1114 if (!row)
1115 { return 0; }
1116 const current = Math.max(0, Number(row.kill_counter) || 0);
1117 const at = row.kill_counter_at | 0;
1118 if (!(current > 0) || !at || now <= at)
1119 { return current; }
1120 return decayKillCounter(current, now - at).killCounter;
1121 }
1122
1123 getKillCounterState (characterId)
1124 {
1125 const row = this.getCharacter(characterId);
1126 if (!row)
1127 { return { killCounter: 0, updatedAt: Date.now() }; }
1128 return {
1129 killCounter: Math.max(0, Number(row.kill_counter) || 0),
1130 updatedAt: row.kill_counter_at | 0 || Date.now()
1131 };
1132 }
1133
1134 setKillCounter (characterId, killCounter, updatedAt = Date.now())
1135 {
1136 const value = Math.max(0, Number(killCounter) || 0);
939 1137 this.db.prepare(`
940 DELETE FROM friend_requests
941 WHERE from_character_id = ? AND to_character_id = ?
942 `).run(fromId, toId);
1138 UPDATE characters SET kill_counter = ?, kill_counter_at = ? WHERE character_id = ?
1139 `).run(value, updatedAt | 0, characterId | 0);
1140 return value;
1141 }
1142
1143 addKillCounter (characterId, amount, now = Date.now())
1144 {
1145 const state = this.getKillCounterState(characterId);
1146 const decayed = decayKillCounter(state.killCounter, Math.max(0, now - (state.updatedAt | 0)));
1147 const next = decayed.killCounter + Math.max(0, Number(amount) || 0);
1148 return this.setKillCounter(characterId, next, now);
943 1149 }
944 1150
945 1151 listPersistentInRegion (minX, minY, maxX, maxY)
@@ -5,6 +5,7 @@ import { itemDefinition, ItemId } from "../../../shared/definitions/items.js";
5import { buildStarterBagContents } from "../../../shared/items/starterLoadout.js";
5import { buildStarterBagContents } from "../../../shared/items/starterLoadout.js";
6import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";
6import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";
7import { normalizePlayerSpells, defaultPlayerSpells, storedPlayerSpells } from "../../../shared/spells/state.js";
7import { normalizePlayerSpells, defaultPlayerSpells, storedPlayerSpells } from "../../../shared/spells/state.js";
8import { decayKillCounter } from "../../../shared/combat/skull.js";
8
9
9const STATE_SCHEMA = `
10const STATE_SCHEMA = `
10CREATE TABLE IF NOT EXISTS accounts (
11CREATE TABLE IF NOT EXISTS accounts (
@@ -208,7 +209,7 @@ CREATE TABLE IF NOT EXISTS character_visited_dimensions (
208
209
209export class StateDatabase
210export class StateDatabase
210{
211{
211 constructor (filePath)
212 constructor(filePath)
212 {
213 {
213 this.db = openDatabase(filePath);
214 this.db = openDatabase(filePath);
214 this.db.exec(STATE_SCHEMA);
215 this.db.exec(STATE_SCHEMA);
@@ -254,6 +255,28 @@ export class StateDatabase
254 const accountColumns = this.db.prepare("PRAGMA table_info(accounts)").all();
255 const accountColumns = this.db.prepare("PRAGMA table_info(accounts)").all();
255 if (!accountColumns.some((column) => column.name === "username"))
256 if (!accountColumns.some((column) => column.name === "username"))
256 { this.db.exec("ALTER TABLE accounts ADD COLUMN username TEXT"); }
257 { this.db.exec("ALTER TABLE accounts ADD COLUMN username TEXT"); }
258 if (!characterColumns.some((column) => column.name === "kill_counter"))
259 { this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter REAL NOT NULL DEFAULT 0"); }
260 if (!characterColumns.some((column) => column.name === "kill_counter_at"))
261 { this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter_at INTEGER"); }
262 this.db.exec(`
263 CREATE TABLE IF NOT EXISTS account_friend_requests (
264 request_id INTEGER PRIMARY KEY AUTOINCREMENT,
265 from_account_id INTEGER NOT NULL,
266 to_account_id INTEGER NOT NULL,
267 created_at INTEGER NOT NULL,
268 UNIQUE (from_account_id, to_account_id)
269 )
270 `);
271 this.db.exec(`
272 CREATE TABLE IF NOT EXISTS account_friendships (
273 account_id_a INTEGER NOT NULL,
274 account_id_b INTEGER NOT NULL,
275 created_at INTEGER NOT NULL,
276 PRIMARY KEY (account_id_a, account_id_b)
277 )
278 `);
279 this.#migrateCharacterFriendsToAccounts();
257 this.db.exec(`
280 this.db.exec(`
258 CREATE TABLE IF NOT EXISTS auth_sessions (
281 CREATE TABLE IF NOT EXISTS auth_sessions (
259 session_id TEXT PRIMARY KEY,
282 session_id TEXT PRIMARY KEY,
@@ -270,6 +293,45 @@ export class StateDatabase
270 this.#grantLanternsToExistingCharacters();
293 this.#grantLanternsToExistingCharacters();
271 }
294 }
272
295
296 /** One-time: lift legacy character friendships / requests to account scope. */
297 #migrateCharacterFriendsToAccounts ()
298 {
299 const legacyFriends = this.db.prepare("SELECT character_id_a, character_id_b, created_at FROM friendships").all();
300 const insertFriend = this.db.prepare(`
301 INSERT OR IGNORE INTO account_friendships (account_id_a, account_id_b, created_at)
302 VALUES (?, ?, ?)
303 `);
304 for (const row of legacyFriends)
305 {
306 const a = this.getCharacter(row.character_id_a);
307 const b = this.getCharacter(row.character_id_b);
308 if (!a || !b || a.account_id === b.account_id)
309 { continue; }
310 const [idA, idB] = pairIds(a.account_id, b.account_id);
311 insertFriend.run(idA, idB, row.created_at | 0 || Date.now());
312 }
313 const legacyRequests = this.db.prepare(`
314 SELECT from_character_id, to_character_id, created_at FROM friend_requests
315 `).all();
316 const insertReq = this.db.prepare(`
317 INSERT OR IGNORE INTO account_friend_requests (from_account_id, to_account_id, created_at)
318 VALUES (?, ?, ?)
319 `);
320 for (const row of legacyRequests)
321 {
322 const from = this.getCharacter(row.from_character_id);
323 const to = this.getCharacter(row.to_character_id);
324 if (!from || !to || from.account_id === to.account_id)
325 { continue; }
326 insertReq.run(from.account_id, to.account_id, row.created_at | 0 || Date.now());
327 }
328 if (legacyFriends.length || legacyRequests.length)
329 {
330 this.db.exec("DELETE FROM friendships");
331 this.db.exec("DELETE FROM friend_requests");
332 }
333 }
334
273 createAuthSession ({ sessionId, authSubject, username = null, email = null, accessToken = null, expiresAtMs })
335 createAuthSession ({ sessionId, authSubject, username = null, email = null, accessToken = null, expiresAtMs })
274 {
336 {
275 this.db.prepare(`
337 this.db.prepare(`
@@ -571,6 +633,8 @@ export class StateDatabase
571 this.#moveGoodsToInheritance(character);
633 this.#moveGoodsToInheritance(character);
572 this.db.prepare("DELETE FROM character_bags WHERE character_id = ?").run(characterId);
634 this.db.prepare("DELETE FROM character_bags WHERE character_id = ?").run(characterId);
573 this.db.prepare("DELETE FROM characters WHERE character_id = ?").run(characterId);
635 this.db.prepare("DELETE FROM characters WHERE character_id = ?").run(characterId);
636 this.db.prepare("DELETE FROM character_bounties WHERE character_id = ?").run(characterId);
637 // Account friendships persist; only clear legacy character rows if any remain.
574 this.db.prepare("DELETE FROM friend_requests WHERE from_character_id = ? OR to_character_id = ?").run(
638 this.db.prepare("DELETE FROM friend_requests WHERE from_character_id = ? OR to_character_id = ?").run(
575 characterId,
639 characterId,
576 characterId
640 characterId
@@ -862,84 +926,226 @@ export class StateDatabase
862 }
926 }
863
927
864 listFriendRecords (characterId)
928 listFriendRecords (characterId)
929 {
930 return this.listAccountFriendRecords(this.accountIdOfCharacter(characterId));
931 }
932
933 accountIdOfCharacter (characterId)
934 {
935 const row = this.getCharacter(characterId);
936 return row?.account_id | 0;
937 }
938
939 getAccount (accountId)
865 {
940 {
941 return this.db.prepare(`
942 SELECT account_id, auth_subject, username, email, is_admin
943 FROM accounts WHERE account_id = ?
944 `).get(accountId | 0) ?? null;
945 }
946
947 accountDisplayName (accountId)
948 {
949 const row = this.getAccount(accountId);
950 if (!row)
951 { return "Unknown"; }
952 const name = String(row.username ?? "").trim();
953 return name || `Account ${row.account_id}`;
954 }
955
956 listAccountFriendRecords (accountId)
957 {
958 const id = accountId | 0;
959 if (!id)
960 { return []; }
866 return this.db.prepare(`
961 return this.db.prepare(`
867 SELECT
962 SELECT
868 CASE WHEN character_id_a = ? THEN character_id_b ELSE character_id_a END AS character_id,
963 CASE WHEN account_id_a = ? THEN account_id_b ELSE account_id_a END AS account_id,
869 created_at
964 created_at
870 FROM friendships
965 FROM account_friendships
871 WHERE character_id_a = ? OR character_id_b = ?
966 WHERE account_id_a = ? OR account_id_b = ?
872 ORDER BY created_at ASC
967 ORDER BY created_at ASC
873 `).all(characterId, characterId, characterId);
968 `).all(id, id, id);
874 }
969 }
875
970
876 areFriends (characterId, otherId)
971 areAccountFriends (accountId, otherAccountId)
877 {
972 {
878 const [a, b] = pairIds(characterId, otherId);
973 const aId = accountId | 0;
974 const bId = otherAccountId | 0;
975 if (!aId || !bId)
976 { return false; }
977 if (aId === bId)
978 { return true; }
979 const [a, b] = pairIds(aId, bId);
879 return !!this.db.prepare(`
980 return !!this.db.prepare(`
880 SELECT 1 FROM friendships WHERE character_id_a = ? AND character_id_b = ?
981 SELECT 1 FROM account_friendships WHERE account_id_a = ? AND account_id_b = ?
881 `).get(a, b);
982 `).get(a, b);
882 }
983 }
883
984
884 insertFriendship (characterId, otherId)
985 areFriends (characterId, otherId)
986 {
987 const left = this.getCharacter(characterId);
988 const right = this.getCharacter(otherId);
989 if (!left || !right)
990 { return false; }
991 return this.areAccountFriends(left.account_id, right.account_id);
992 }
993
994 insertAccountFriendship (accountId, otherId)
885 {
995 {
886 const [a, b] = pairIds(characterId, otherId);
996 const [a, b] = pairIds(accountId, otherId);
887 this.db.prepare(`
997 this.db.prepare(`
888 INSERT INTO friendships (character_id_a, character_id_b, created_at)
998 INSERT OR IGNORE INTO account_friendships (account_id_a, account_id_b, created_at)
889 VALUES (?, ?, ?)
999 VALUES (?, ?, ?)
890 `).run(a, b, Date.now());
1000 `).run(a, b, Date.now());
891 }
1001 }
892
1002
893 deleteFriendship (characterId, otherId)
1003 insertFriendship (characterId, otherId)
1004 {
1005 const left = this.getCharacter(characterId);
1006 const right = this.getCharacter(otherId);
1007 if (!left || !right)
1008 { return; }
1009 this.insertAccountFriendship(left.account_id, right.account_id);
1010 }
1011
1012 deleteAccountFriendship (accountId, otherId)
894 {
1013 {
895 const [a, b] = pairIds(characterId, otherId);
1014 const [a, b] = pairIds(accountId, otherId);
896 this.db.prepare(`
1015 this.db.prepare(`
897 DELETE FROM friendships WHERE character_id_a = ? AND character_id_b = ?
1016 DELETE FROM account_friendships WHERE account_id_a = ? AND account_id_b = ?
898 `).run(a, b);
1017 `).run(a, b);
899 }
1018 }
900
1019
901 listIncomingRequests (characterId)
1020 deleteFriendship (characterId, otherId)
1021 {
1022 const left = this.getCharacter(characterId);
1023 const right = this.getCharacter(otherId);
1024 if (!left || !right)
1025 { return; }
1026 this.deleteAccountFriendship(left.account_id, right.account_id);
1027 }
1028
1029 listIncomingAccountRequests (accountId)
902 {
1030 {
903 return this.db.prepare(`
1031 return this.db.prepare(`
904 SELECT request_id, from_character_id, to_character_id, created_at
1032 SELECT request_id, from_account_id, to_account_id, created_at
905 FROM friend_requests
1033 FROM account_friend_requests
906 WHERE to_character_id = ?
1034 WHERE to_account_id = ?
907 ORDER BY created_at ASC
1035 ORDER BY created_at ASC
908 `).all(characterId);
1036 `).all(accountId | 0);
909 }
1037 }
910
1038
911 listOutgoingRequests (characterId)
1039 listOutgoingAccountRequests (accountId)
912 {
1040 {
913 return this.db.prepare(`
1041 return this.db.prepare(`
914 SELECT request_id, from_character_id, to_character_id, created_at
1042 SELECT request_id, from_account_id, to_account_id, created_at
915 FROM friend_requests
1043 FROM account_friend_requests
916 WHERE from_character_id = ?
1044 WHERE from_account_id = ?
917 ORDER BY created_at ASC
1045 ORDER BY created_at ASC
918 `).all(characterId);
1046 `).all(accountId | 0);
919 }
1047 }
920
1048
921 getFriendRequest (fromId, toId)
1049 listIncomingRequests (characterId)
1050 {
1051 return this.listIncomingAccountRequests(this.accountIdOfCharacter(characterId));
1052 }
1053
1054 listOutgoingRequests (characterId)
1055 {
1056 return this.listOutgoingAccountRequests(this.accountIdOfCharacter(characterId));
1057 }
1058
1059 getAccountFriendRequest (fromAccountId, toAccountId)
922 {
1060 {
923 return this.db.prepare(`
1061 return this.db.prepare(`
924 SELECT * FROM friend_requests
1062 SELECT * FROM account_friend_requests
925 WHERE from_character_id = ? AND to_character_id = ?
1063 WHERE from_account_id = ? AND to_account_id = ?
926 `).get(fromId, toId) ?? null;
1064 `).get(fromAccountId | 0, toAccountId | 0) ?? null;
927 }
1065 }
928
1066
929 insertFriendRequest (fromId, toId)
1067 getFriendRequest (fromId, toId)
1068 {
1069 const from = this.getCharacter(fromId);
1070 const to = this.getCharacter(toId);
1071 if (!from || !to)
1072 { return null; }
1073 return this.getAccountFriendRequest(from.account_id, to.account_id);
1074 }
1075
1076 insertAccountFriendRequest (fromAccountId, toAccountId)
930 {
1077 {
931 this.db.prepare(`
1078 this.db.prepare(`
932 INSERT INTO friend_requests (from_character_id, to_character_id, created_at)
1079 INSERT INTO account_friend_requests (from_account_id, to_account_id, created_at)
933 VALUES (?, ?, ?)
1080 VALUES (?, ?, ?)
934 `).run(fromId, toId, Date.now());
1081 `).run(fromAccountId | 0, toAccountId | 0, Date.now());
1082 }
1083
1084 insertFriendRequest (fromId, toId)
1085 {
1086 const from = this.getCharacter(fromId);
1087 const to = this.getCharacter(toId);
1088 if (!from || !to)
1089 { return; }
1090 this.insertAccountFriendRequest(from.account_id, to.account_id);
1091 }
1092
1093 deleteAccountFriendRequest (fromAccountId, toAccountId)
1094 {
1095 this.db.prepare(`
1096 DELETE FROM account_friend_requests
1097 WHERE from_account_id = ? AND to_account_id = ?
1098 `).run(fromAccountId | 0, toAccountId | 0);
935 }
1099 }
936
1100
937 deleteFriendRequest (fromId, toId)
1101 deleteFriendRequest (fromId, toId)
938 {
1102 {
1103 const from = this.getCharacter(fromId);
1104 const to = this.getCharacter(toId);
1105 if (!from || !to)
1106 { return; }
1107 this.deleteAccountFriendRequest(from.account_id, to.account_id);
1108 }
1109
1110 /** Decayed kill counter at `now` (does not write). */
1111 peekKillCounter (characterId, now = Date.now())
1112 {
1113 const row = this.getCharacter(characterId);
1114 if (!row)
1115 { return 0; }
1116 const current = Math.max(0, Number(row.kill_counter) || 0);
1117 const at = row.kill_counter_at | 0;
1118 if (!(current > 0) || !at || now <= at)
1119 { return current; }
1120 return decayKillCounter(current, now - at).killCounter;
1121 }
1122
1123 getKillCounterState (characterId)
1124 {
1125 const row = this.getCharacter(characterId);
1126 if (!row)
1127 { return { killCounter: 0, updatedAt: Date.now() }; }
1128 return {
1129 killCounter: Math.max(0, Number(row.kill_counter) || 0),
1130 updatedAt: row.kill_counter_at | 0 || Date.now()
1131 };
1132 }
1133
1134 setKillCounter (characterId, killCounter, updatedAt = Date.now())
1135 {
1136 const value = Math.max(0, Number(killCounter) || 0);
939 this.db.prepare(`
1137 this.db.prepare(`
940 DELETE FROM friend_requests
1138 UPDATE characters SET kill_counter = ?, kill_counter_at = ? WHERE character_id = ?
941 WHERE from_character_id = ? AND to_character_id = ?
1139 `).run(value, updatedAt | 0, characterId | 0);
942 `).run(fromId, toId);
1140 return value;
1141 }
1142
1143 addKillCounter (characterId, amount, now = Date.now())
1144 {
1145 const state = this.getKillCounterState(characterId);
1146 const decayed = decayKillCounter(state.killCounter, Math.max(0, now - (state.updatedAt | 0)));
1147 const next = decayed.killCounter + Math.max(0, Number(amount) || 0);
1148 return this.setKillCounter(characterId, next, now);
943 }
1149 }
944
1150
945 listPersistentInRegion (minX, minY, maxX, maxY)
1151 listPersistentInRegion (minX, minY, maxX, maxY)
server/src/simulation/simulation.js +68 −2
@@ -33,6 +33,7 @@ import { replicaNeededForOwnedChunks } from "./workerWorld.js";
33 33 import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";
34 34 import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
35 35 import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";
36 import { skullValue, decayKillCounter, SKULL_KILL_BONUS } from "../../../shared/combat/skull.js";
36 37 import { mobComponents } from "./spawners.js";
37 38 import { shadeSummonComponents } from "../spells/summons.js";
38 39 import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";
@@ -344,6 +345,9 @@ export class Simulation
344 345 if (this.tickIndex % Math.max(1, Math.round(simHz * 2)) === 0)
345 346 { events.push(...this.#stepSpawners()); }
346 347
348 if (this.tickIndex % Math.max(1, Math.round(simHz)) === 0)
349 { this.#stepSkullDecay(); }
350
347 351 if (this.courier)
348 352 { events.push(...this.courier.step(now, dt)); }
349 353 if (this.market)
@@ -482,14 +486,68 @@ export class Simulation
482 486 components
483 487 });
484 488 this.#remember(view, workerId);
489 this.#attachSkullToRecord(view.entityId, character.character_id ?? row.character_id);
485 490 this.stateDb.markDimensionVisited(character.character_id, dimensionId);
486 this.#queueReplication(replicationSpawn(view));
491 this.#queueReplication(replicationSpawn(this.directory.get(view.entityId) ?? view));
487 492 this.#recalculateActivation(this.now);
488 493 this.#syncGhosts();
489 494 this.courier?.onCharacterEnteredWorld(character.character_id, tileX, tileY);
490 495 return entityId;
491 496 }
492 497
498 characterSkullValue (characterId, now = this.now)
499 {
500 const bounty = this.stateDb.getCharacterBounty(characterId);
501 const killCounter = this.stateDb.peekKillCounter(characterId, now);
502 return skullValue(bounty, killCounter);
503 }
504
505 refreshCharacterSkull (characterId)
506 {
507 const id = characterId | 0;
508 if (!id)
509 { return; }
510 const state = this.stateDb.getKillCounterState(id);
511 const elapsed = Math.max(0, this.now - (state.updatedAt | 0));
512 const decayed = decayKillCounter(state.killCounter, elapsed);
513 if (decayed.killCounter !== state.killCounter)
514 { this.stateDb.setKillCounter(id, decayed.killCounter, this.now); }
515 const value = this.characterSkullValue(id);
516 const entityId = this.characterEntities.get(id);
517 const record = entityId ? this.directory.get(entityId) : null;
518 if (!record)
519 { return; }
520 if ((record.skullValue | 0) === value)
521 { return; }
522 record.skullValue = value;
523 this.#queueReplication({
524 type: "entity-skull",
525 entityId,
526 skullValue: value,
527 tileX: record.tileX,
528 tileY: record.tileY
529 });
530 }
531
532 #attachSkullToRecord (entityId, characterId)
533 {
534 const record = this.directory.get(entityId);
535 if (!record)
536 { return; }
537 record.skullValue = this.characterSkullValue(characterId);
538 }
539
540 #stepSkullDecay ()
541 {
542 for (const characterId of this.characterEntities.keys())
543 {
544 const state = this.stateDb.getKillCounterState(characterId);
545 if (!(state.killCounter > 0))
546 { continue; }
547 this.refreshCharacterSkull(characterId);
548 }
549 }
550
493 551 isCharacterOnline (characterId)
494 552 {
495 553 return this.characterEntities.has(characterId);
@@ -1584,6 +1642,7 @@ export class Simulation
1584 1642 {
1585 1643 bountyAwarded = event.bounty | 0;
1586 1644 const total = this.stateDb.addCharacterBounty(killerCharacterId, bountyAwarded);
1645 this.refreshCharacterSkull(killerCharacterId);
1587 1646 out.push({
1588 1647 type: "toast",
1589 1648 characterId: killerCharacterId,
@@ -1663,6 +1722,14 @@ export class Simulation
1663 1722 event.tileX,
1664 1723 event.tileY
1665 1724 );
1725 const attackerRecord = event.attackerId != null ? this.directory.get(event.attackerId) : null;
1726 const killerCharacterId = attackerRecord?.characterId | 0;
1727 if (killerCharacterId && killerCharacterId !== (event.characterId | 0))
1728 {
1729 this.stateDb.addKillCounter(killerCharacterId, SKULL_KILL_BONUS, this.now);
1730 this.refreshCharacterSkull(killerCharacterId);
1731 }
1732 this.refreshCharacterSkull(event.characterId);
1666 1733 for (const worker of this.workers)
1667 1734 {
1668 1735 worker.call({
@@ -1673,7 +1740,6 @@ export class Simulation
1673 1740 }
1674 1741 const victimName = `${record.appearance?.firstName ?? "someone"} ${record.appearance?.lastName ?? ""}`.trim()
1675 1742 || "someone";
1676 const attackerRecord = event.attackerId != null ? this.directory.get(event.attackerId) : null;
1677 1743 const killerName = attackerRecord?.appearance
1678 1744 ? (`${attackerRecord.appearance.firstName ?? ""} ${attackerRecord.appearance.lastName ?? ""}`.trim()
1679 1745 || attackerRecord.appearance.displayName
@@ -33,6 +33,7 @@ import { replicaNeededForOwnedChunks } from "./workerWorld.js";
33import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";
33import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";
34import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
34import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
35import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";
35import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";
36import { skullValue, decayKillCounter, SKULL_KILL_BONUS } from "../../../shared/combat/skull.js";
36import { mobComponents } from "./spawners.js";
37import { mobComponents } from "./spawners.js";
37import { shadeSummonComponents } from "../spells/summons.js";
38import { shadeSummonComponents } from "../spells/summons.js";
38import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";
39import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";
@@ -344,6 +345,9 @@ export class Simulation
344 if (this.tickIndex % Math.max(1, Math.round(simHz * 2)) === 0)
345 if (this.tickIndex % Math.max(1, Math.round(simHz * 2)) === 0)
345 { events.push(...this.#stepSpawners()); }
346 { events.push(...this.#stepSpawners()); }
346
347
348 if (this.tickIndex % Math.max(1, Math.round(simHz)) === 0)
349 { this.#stepSkullDecay(); }
350
347 if (this.courier)
351 if (this.courier)
348 { events.push(...this.courier.step(now, dt)); }
352 { events.push(...this.courier.step(now, dt)); }
349 if (this.market)
353 if (this.market)
@@ -482,14 +486,68 @@ export class Simulation
482 components
486 components
483 });
487 });
484 this.#remember(view, workerId);
488 this.#remember(view, workerId);
489 this.#attachSkullToRecord(view.entityId, character.character_id ?? row.character_id);
485 this.stateDb.markDimensionVisited(character.character_id, dimensionId);
490 this.stateDb.markDimensionVisited(character.character_id, dimensionId);
486 this.#queueReplication(replicationSpawn(view));
491 this.#queueReplication(replicationSpawn(this.directory.get(view.entityId) ?? view));
487 this.#recalculateActivation(this.now);
492 this.#recalculateActivation(this.now);
488 this.#syncGhosts();
493 this.#syncGhosts();
489 this.courier?.onCharacterEnteredWorld(character.character_id, tileX, tileY);
494 this.courier?.onCharacterEnteredWorld(character.character_id, tileX, tileY);
490 return entityId;
495 return entityId;
491 }
496 }
492
497
498 characterSkullValue (characterId, now = this.now)
499 {
500 const bounty = this.stateDb.getCharacterBounty(characterId);
501 const killCounter = this.stateDb.peekKillCounter(characterId, now);
502 return skullValue(bounty, killCounter);
503 }
504
505 refreshCharacterSkull (characterId)
506 {
507 const id = characterId | 0;
508 if (!id)
509 { return; }
510 const state = this.stateDb.getKillCounterState(id);
511 const elapsed = Math.max(0, this.now - (state.updatedAt | 0));
512 const decayed = decayKillCounter(state.killCounter, elapsed);
513 if (decayed.killCounter !== state.killCounter)
514 { this.stateDb.setKillCounter(id, decayed.killCounter, this.now); }
515 const value = this.characterSkullValue(id);
516 const entityId = this.characterEntities.get(id);
517 const record = entityId ? this.directory.get(entityId) : null;
518 if (!record)
519 { return; }
520 if ((record.skullValue | 0) === value)
521 { return; }
522 record.skullValue = value;
523 this.#queueReplication({
524 type: "entity-skull",
525 entityId,
526 skullValue: value,
527 tileX: record.tileX,
528 tileY: record.tileY
529 });
530 }
531
532 #attachSkullToRecord (entityId, characterId)
533 {
534 const record = this.directory.get(entityId);
535 if (!record)
536 { return; }
537 record.skullValue = this.characterSkullValue(characterId);
538 }
539
540 #stepSkullDecay ()
541 {
542 for (const characterId of this.characterEntities.keys())
543 {
544 const state = this.stateDb.getKillCounterState(characterId);
545 if (!(state.killCounter > 0))
546 { continue; }
547 this.refreshCharacterSkull(characterId);
548 }
549 }
550
493 isCharacterOnline (characterId)
551 isCharacterOnline (characterId)
494 {
552 {
495 return this.characterEntities.has(characterId);
553 return this.characterEntities.has(characterId);
@@ -1584,6 +1642,7 @@ export class Simulation
1584 {
1642 {
1585 bountyAwarded = event.bounty | 0;
1643 bountyAwarded = event.bounty | 0;
1586 const total = this.stateDb.addCharacterBounty(killerCharacterId, bountyAwarded);
1644 const total = this.stateDb.addCharacterBounty(killerCharacterId, bountyAwarded);
1645 this.refreshCharacterSkull(killerCharacterId);
1587 out.push({
1646 out.push({
1588 type: "toast",
1647 type: "toast",
1589 characterId: killerCharacterId,
1648 characterId: killerCharacterId,
@@ -1663,6 +1722,14 @@ export class Simulation
1663 event.tileX,
1722 event.tileX,
1664 event.tileY
1723 event.tileY
1665 );
1724 );
1725 const attackerRecord = event.attackerId != null ? this.directory.get(event.attackerId) : null;
1726 const killerCharacterId = attackerRecord?.characterId | 0;
1727 if (killerCharacterId && killerCharacterId !== (event.characterId | 0))
1728 {
1729 this.stateDb.addKillCounter(killerCharacterId, SKULL_KILL_BONUS, this.now);
1730 this.refreshCharacterSkull(killerCharacterId);
1731 }
1732 this.refreshCharacterSkull(event.characterId);
1666 for (const worker of this.workers)
1733 for (const worker of this.workers)
1667 {
1734 {
1668 worker.call({
1735 worker.call({
@@ -1673,7 +1740,6 @@ export class Simulation
1673 }
1740 }
1674 const victimName = `${record.appearance?.firstName ?? "someone"} ${record.appearance?.lastName ?? ""}`.trim()
1741 const victimName = `${record.appearance?.firstName ?? "someone"} ${record.appearance?.lastName ?? ""}`.trim()
1675 || "someone";
1742 || "someone";
1676 const attackerRecord = event.attackerId != null ? this.directory.get(event.attackerId) : null;
1677 const killerName = attackerRecord?.appearance
1743 const killerName = attackerRecord?.appearance
1678 ? (`${attackerRecord.appearance.firstName ?? ""} ${attackerRecord.appearance.lastName ?? ""}`.trim()
1744 ? (`${attackerRecord.appearance.firstName ?? ""} ${attackerRecord.appearance.lastName ?? ""}`.trim()
1679 || attackerRecord.appearance.displayName
1745 || attackerRecord.appearance.displayName
server/tests/bounty.test.js +83 −71
@@ -4,7 +4,6 @@ import { BlockType } from "../../shared/definitions/tiles.js";
4 4 import { ItemId } from "../../shared/definitions/items.js";
5 5 import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
6 6 import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
7 import { Component } from "../src/ecs/components.js";
8 7 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
9 8
10 9 function placeBlock (worldDb, tileX, tileY, typeId)
@@ -45,24 +44,6 @@ function giveCoins (harness, entityId, amount)
45 44 );
46 45 }
47 46
48 function componentsOf (simulation, entityId)
49 {
50 const record = simulation.entityRecord(entityId);
51 const worker = simulation.workers[record.workerId];
52 const handle = worker.world.ecs.handleOf(entityId);
53 return worker.world.ecs.componentsOf(handle);
54 }
55
56 function withDeterministicCombat (fn)
57 {
58 const random = Math.random;
59 Math.random = () => 0;
60 try
61 { fn(); }
62 finally
63 { Math.random = random; }
64 }
65
66 47 test("raise bounty spends inventory coins and tracks ledger", () =>
67 48 {
68 49 const harness = makeSimulation({ workerCount: 1 });
@@ -138,57 +119,88 @@ test("open bounty requires standing next to a bounty office", () =>
138 119
139 120 test("PvP kill pays bounty into killer vault and clears ledger", () =>
140 121 {
141 withDeterministicCombat(() =>
122 const harness = makeSimulation({ workerCount: 1 });
123 try
142 124 {
143 const harness = makeSimulation({ workerCount: 1 });
144 try
145 {
146 placeBlock(harness.worldDb, 8, 8, BlockType.bountyOffice);
147 placeBlock(harness.worldDb, 7, 8, BlockType.bank);
148 harness.simulation.reloadWorld();
149
150 const victim = makeCharacter(harness.stateDb, {
151 firstName: "Vic",
152 lastName: "Tim",
153 tileX: 9,
154 tileY: 9
155 });
156 const killer = makeCharacter(harness.stateDb, {
157 firstName: "Kill",
158 lastName: "Er",
159 tileX: 10,
160 tileY: 9
161 });
162 harness.stateDb.addCharacterBounty(victim.character_id, 400);
163
164 const victimId = harness.simulation.spawnCharacter(1, victim);
165 const killerId = harness.simulation.spawnCharacter(2, killer);
166 const victimComps = componentsOf(harness.simulation, victimId);
167 victimComps.health.current = 1;
168 const killerComps = componentsOf(harness.simulation, killerId);
169 killerComps.health.current = 1_000_000;
170 killerComps.health.max = 1_000_000;
171
172 harness.simulation.enqueue(2, {
173 type: "attack",
174 characterId: killer.character_id,
175 targetEntityId: victimId
176 });
177
178 let died = null;
179 for (let i = 0; i < 200; i++)
180 {
181 harness.advance(50);
182 const events = harness.simulation.step().events;
183 died = events.find((event) => event.type === "player-died");
184 if (died)
185 { break; }
186 }
187 assert.ok(died, "victim should die");
188 assert.equal(harness.stateDb.getCharacterBounty(victim.character_id), 0);
189 assert.equal(countCoins(harness.simulation.bagOf(killerId).vault), 400);
190 }
191 finally
192 { harness.close(); }
193 });
125 placeBlock(harness.worldDb, 8, 8, BlockType.bountyOffice);
126 placeBlock(harness.worldDb, 7, 8, BlockType.bank);
127 harness.simulation.reloadWorld();
128
129 const victim = makeCharacter(harness.stateDb, {
130 firstName: "Vic",
131 lastName: "Tim",
132 tileX: 9,
133 tileY: 9
134 });
135 const killer = makeCharacter(harness.stateDb, {
136 firstName: "Kill",
137 lastName: "Er",
138 tileX: 10,
139 tileY: 9
140 });
141 harness.stateDb.addCharacterBounty(victim.character_id, 400);
142
143 const victimId = harness.simulation.spawnCharacter(1, victim);
144 const killerId = harness.simulation.spawnCharacter(2, killer);
145
146 const settled = harness.simulation.bounty.settleKill(
147 victim.character_id,
148 killerId,
149 9,
150 9
151 );
152 assert.equal(settled?.paidCopper, 400);
153 assert.equal(harness.stateDb.getCharacterBounty(victim.character_id), 0);
154 assert.equal(countCoins(harness.simulation.bagOf(killerId).vault), 400);
155
156 harness.stateDb.addKillCounter(killer.character_id, 500, harness.now());
157 harness.simulation.refreshCharacterSkull(killer.character_id);
158 assert.equal(harness.stateDb.peekKillCounter(killer.character_id, harness.now()), 500);
159 assert.equal(harness.simulation.directory.get(killerId).skullValue, 500);
160 assert.equal(harness.simulation.directory.get(victimId).skullValue, 0);
161 }
162 finally
163 { harness.close(); }
164 });
165
166 test("friend PvP kill does not pay or clear bounty", () =>
167 {
168 const harness = makeSimulation({ workerCount: 1 });
169 try
170 {
171 placeBlock(harness.worldDb, 8, 8, BlockType.bountyOffice);
172 placeBlock(harness.worldDb, 7, 8, BlockType.bank);
173 harness.simulation.reloadWorld();
174
175 const victim = makeCharacter(harness.stateDb, {
176 firstName: "Vic",
177 lastName: "Friend",
178 tileX: 9,
179 tileY: 9
180 });
181 const killer = makeCharacter(harness.stateDb, {
182 firstName: "Kill",
183 lastName: "Buddy",
184 tileX: 10,
185 tileY: 9
186 });
187 harness.stateDb.addCharacterBounty(victim.character_id, 400);
188 harness.stateDb.insertAccountFriendship(victim.account_id, killer.account_id);
189
190 const victimId = harness.simulation.spawnCharacter(1, victim);
191 const killerId = harness.simulation.spawnCharacter(2, killer);
192
193 const settled = harness.simulation.bounty.settleKill(
194 victim.character_id,
195 killerId,
196 9,
197 9
198 );
199 assert.equal(settled, null);
200 assert.equal(harness.stateDb.getCharacterBounty(victim.character_id), 400);
201 assert.equal(countCoins(harness.simulation.bagOf(killerId).vault), 0);
202 assert.equal(harness.simulation.directory.get(victimId).skullValue, 400);
203 }
204 finally
205 { harness.close(); }
194 206 });
@@ -4,7 +4,6 @@ import { BlockType } from "../../shared/definitions/tiles.js";
4import { ItemId } from "../../shared/definitions/items.js";
4import { ItemId } from "../../shared/definitions/items.js";
5import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
5import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
6import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
6import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
7import { Component } from "../src/ecs/components.js";
8import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
7import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
9
8
10function placeBlock (worldDb, tileX, tileY, typeId)
9function placeBlock (worldDb, tileX, tileY, typeId)
@@ -45,24 +44,6 @@ function giveCoins (harness, entityId, amount)
45 );
44 );
46}
45}
47
46
48function componentsOf (simulation, entityId)
49{
50 const record = simulation.entityRecord(entityId);
51 const worker = simulation.workers[record.workerId];
52 const handle = worker.world.ecs.handleOf(entityId);
53 return worker.world.ecs.componentsOf(handle);
54}
55
56function withDeterministicCombat (fn)
57{
58 const random = Math.random;
59 Math.random = () => 0;
60 try
61 { fn(); }
62 finally
63 { Math.random = random; }
64}
65
66test("raise bounty spends inventory coins and tracks ledger", () =>
47test("raise bounty spends inventory coins and tracks ledger", () =>
67{
48{
68 const harness = makeSimulation({ workerCount: 1 });
49 const harness = makeSimulation({ workerCount: 1 });
@@ -138,57 +119,88 @@ test("open bounty requires standing next to a bounty office", () =>
138
119
139test("PvP kill pays bounty into killer vault and clears ledger", () =>
120test("PvP kill pays bounty into killer vault and clears ledger", () =>
140{
121{
141 withDeterministicCombat(() =>
122 const harness = makeSimulation({ workerCount: 1 });
123 try
142 {
124 {
143 const harness = makeSimulation({ workerCount: 1 });
125 placeBlock(harness.worldDb, 8, 8, BlockType.bountyOffice);
144 try
126 placeBlock(harness.worldDb, 7, 8, BlockType.bank);
145 {
127 harness.simulation.reloadWorld();
146 placeBlock(harness.worldDb, 8, 8, BlockType.bountyOffice);
128
147 placeBlock(harness.worldDb, 7, 8, BlockType.bank);
129 const victim = makeCharacter(harness.stateDb, {
148 harness.simulation.reloadWorld();
130 firstName: "Vic",
149
131 lastName: "Tim",
150 const victim = makeCharacter(harness.stateDb, {
132 tileX: 9,
151 firstName: "Vic",
133 tileY: 9
152 lastName: "Tim",
134 });
153 tileX: 9,
135 const killer = makeCharacter(harness.stateDb, {
154 tileY: 9
136 firstName: "Kill",
155 });
137 lastName: "Er",
156 const killer = makeCharacter(harness.stateDb, {
138 tileX: 10,
157 firstName: "Kill",
139 tileY: 9
158 lastName: "Er",
140 });
159 tileX: 10,
141 harness.stateDb.addCharacterBounty(victim.character_id, 400);
160 tileY: 9
142
161 });
143 const victimId = harness.simulation.spawnCharacter(1, victim);
162 harness.stateDb.addCharacterBounty(victim.character_id, 400);
144 const killerId = harness.simulation.spawnCharacter(2, killer);
163
145
164 const victimId = harness.simulation.spawnCharacter(1, victim);
146 const settled = harness.simulation.bounty.settleKill(
165 const killerId = harness.simulation.spawnCharacter(2, killer);
147 victim.character_id,
166 const victimComps = componentsOf(harness.simulation, victimId);
148 killerId,
167 victimComps.health.current = 1;
149 9,
168 const killerComps = componentsOf(harness.simulation, killerId);
150 9
169 killerComps.health.current = 1_000_000;
151 );
170 killerComps.health.max = 1_000_000;
152 assert.equal(settled?.paidCopper, 400);
171
153 assert.equal(harness.stateDb.getCharacterBounty(victim.character_id), 0);
172 harness.simulation.enqueue(2, {
154 assert.equal(countCoins(harness.simulation.bagOf(killerId).vault), 400);
173 type: "attack",
155
174 characterId: killer.character_id,
156 harness.stateDb.addKillCounter(killer.character_id, 500, harness.now());
175 targetEntityId: victimId
157 harness.simulation.refreshCharacterSkull(killer.character_id);
176 });
158 assert.equal(harness.stateDb.peekKillCounter(killer.character_id, harness.now()), 500);
177
159 assert.equal(harness.simulation.directory.get(killerId).skullValue, 500);
178 let died = null;
160 assert.equal(harness.simulation.directory.get(victimId).skullValue, 0);
179 for (let i = 0; i < 200; i++)
161 }
180 {
162 finally
181 harness.advance(50);
163 { harness.close(); }
182 const events = harness.simulation.step().events;
164});
183 died = events.find((event) => event.type === "player-died");
165
184 if (died)
166test("friend PvP kill does not pay or clear bounty", () =>
185 { break; }
167{
186 }
168 const harness = makeSimulation({ workerCount: 1 });
187 assert.ok(died, "victim should die");
169 try
188 assert.equal(harness.stateDb.getCharacterBounty(victim.character_id), 0);
170 {
189 assert.equal(countCoins(harness.simulation.bagOf(killerId).vault), 400);
171 placeBlock(harness.worldDb, 8, 8, BlockType.bountyOffice);
190 }
172 placeBlock(harness.worldDb, 7, 8, BlockType.bank);
191 finally
173 harness.simulation.reloadWorld();
192 { harness.close(); }
174
193 });
175 const victim = makeCharacter(harness.stateDb, {
176 firstName: "Vic",
177 lastName: "Friend",
178 tileX: 9,
179 tileY: 9
180 });
181 const killer = makeCharacter(harness.stateDb, {
182 firstName: "Kill",
183 lastName: "Buddy",
184 tileX: 10,
185 tileY: 9
186 });
187 harness.stateDb.addCharacterBounty(victim.character_id, 400);
188 harness.stateDb.insertAccountFriendship(victim.account_id, killer.account_id);
189
190 const victimId = harness.simulation.spawnCharacter(1, victim);
191 const killerId = harness.simulation.spawnCharacter(2, killer);
192
193 const settled = harness.simulation.bounty.settleKill(
194 victim.character_id,
195 killerId,
196 9,
197 9
198 );
199 assert.equal(settled, null);
200 assert.equal(harness.stateDb.getCharacterBounty(victim.character_id), 400);
201 assert.equal(countCoins(harness.simulation.bagOf(killerId).vault), 0);
202 assert.equal(harness.simulation.directory.get(victimId).skullValue, 400);
203 }
204 finally
205 { harness.close(); }
194});
206});
server/tests/crafting.test.js +19 −7
@@ -5,13 +5,14 @@ import { CraftingStationId, CRAFT_DURATION_MS } from "../../shared/definitions/c
5 5 import { ItemId } from "../../shared/definitions/items.js";
6 6 import { ArmourItemId } from "../../shared/definitions/armourItems.js";
7 7 import { SkillId } from "../../shared/definitions/skills.js";
8 import {
9 MaterialTier,
10 GatherMaterialId,
11 tierSmeltSkillLevel,
12 smeltingDurationMs,
13 associatedBarTier
14 } from "../../shared/definitions/materialTiers.js";
8 import
9 {
10 MaterialTier,
11 GatherMaterialId,
12 tierSmeltSkillLevel,
13 smeltingDurationMs,
14 associatedBarTier
15 } from "../../shared/definitions/materialTiers.js";
15 16 import { craftDurationMs } from "../../shared/definitions/gathering.js";
16 17 import { recipesForStation, recipeDefinition } from "../../shared/crafting/stationRecipes.js";
17 18 import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
@@ -107,6 +108,17 @@ test("furnace recipes: bronze is tin+copper; steel is iron+coal; high tiers need
107 108 assert.equal(gold.output.itemId, ItemId.goldBar);
108 109 assert.equal(gold.minSkillLevel, tierSmeltSkillLevel(GatherMaterialId.gold));
109 110
111 const electrum = recipesForStation(CraftingStationId.furnace)
112 .find((recipe) => recipe.recipeId === "smelt-electrum");
113 assert.ok(electrum);
114 assert.deepEqual(electrum.inputs.map((row) => row.itemId).sort(), [
115 ItemId.coal,
116 ItemId.goldOre,
117 ItemId.silverOre
118 ].sort());
119 assert.equal(electrum.output.itemId, ItemId.electrumBar);
120 assert.equal(electrum.minSkillLevel, tierSmeltSkillLevel(GatherMaterialId.electrum));
121
110 122 const adamantium = recipeDefinition("smelt-adamantium");
111 123 assert.deepEqual(adamantium.inputs, [
112 124 { itemId: ItemId.adamantiumOre, quantity: 1 },
@@ -5,13 +5,14 @@ import { CraftingStationId, CRAFT_DURATION_MS } from "../../shared/definitions/c
5import { ItemId } from "../../shared/definitions/items.js";
5import { ItemId } from "../../shared/definitions/items.js";
6import { ArmourItemId } from "../../shared/definitions/armourItems.js";
6import { ArmourItemId } from "../../shared/definitions/armourItems.js";
7import { SkillId } from "../../shared/definitions/skills.js";
7import { SkillId } from "../../shared/definitions/skills.js";
8import {
8import
9 MaterialTier,
9 {
10 GatherMaterialId,
10 MaterialTier,
11 tierSmeltSkillLevel,
11 GatherMaterialId,
12 smeltingDurationMs,
12 tierSmeltSkillLevel,
13 associatedBarTier
13 smeltingDurationMs,
14} from "../../shared/definitions/materialTiers.js";
14 associatedBarTier
15 } from "../../shared/definitions/materialTiers.js";
15import { craftDurationMs } from "../../shared/definitions/gathering.js";
16import { craftDurationMs } from "../../shared/definitions/gathering.js";
16import { recipesForStation, recipeDefinition } from "../../shared/crafting/stationRecipes.js";
17import { recipesForStation, recipeDefinition } from "../../shared/crafting/stationRecipes.js";
17import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
18import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
@@ -107,6 +108,17 @@ test("furnace recipes: bronze is tin+copper; steel is iron+coal; high tiers need
107 assert.equal(gold.output.itemId, ItemId.goldBar);
108 assert.equal(gold.output.itemId, ItemId.goldBar);
108 assert.equal(gold.minSkillLevel, tierSmeltSkillLevel(GatherMaterialId.gold));
109 assert.equal(gold.minSkillLevel, tierSmeltSkillLevel(GatherMaterialId.gold));
109
110
111 const electrum = recipesForStation(CraftingStationId.furnace)
112 .find((recipe) => recipe.recipeId === "smelt-electrum");
113 assert.ok(electrum);
114 assert.deepEqual(electrum.inputs.map((row) => row.itemId).sort(), [
115 ItemId.coal,
116 ItemId.goldOre,
117 ItemId.silverOre
118 ].sort());
119 assert.equal(electrum.output.itemId, ItemId.electrumBar);
120 assert.equal(electrum.minSkillLevel, tierSmeltSkillLevel(GatherMaterialId.electrum));
121
110 const adamantium = recipeDefinition("smelt-adamantium");
122 const adamantium = recipeDefinition("smelt-adamantium");
111 assert.deepEqual(adamantium.inputs, [
123 assert.deepEqual(adamantium.inputs, [
112 { itemId: ItemId.adamantiumOre, quantity: 1 },
124 { itemId: ItemId.adamantiumOre, quantity: 1 },
server/tests/craftingStations.test.js +41 −6
@@ -1,22 +1,27 @@
1 1 import test from "node:test";
2 2 import assert from "node:assert/strict";
3 import {
4 CraftingStationId,
5 FIREPLACE_DURATION_MS,
6 CRAFT_DURATION_MS,
7 craftingStationDefinition
8 } from "../../shared/definitions/craftingStations.js";
3 import
4 {
5 CraftingStationId,
6 FIREPLACE_DURATION_MS,
7 CRAFT_DURATION_MS,
8 craftingStationDefinition
9 } from "../../shared/definitions/craftingStations.js";
9 10 import { SkillId } from "../../shared/definitions/skills.js";
10 11 import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
11 12 import { emptySlots } from "../../shared/items/inventory.js";
12 13 import { canCraftFitInventory, CRAFT_DURATION_MS as RECIPE_CRAFT_MS, canStartCraft } from "../../shared/crafting/recipes.js";
13 14 import { recipesForStation, recipeDefinition } from "../../shared/crafting/stationRecipes.js";
14 15 import { CraftingItemId } from "../../shared/definitions/craftingItems.js";
16 import { GemItemId, JEWELRY_RECIPE_GUIDELINES } from "../../shared/definitions/gemItems.js";
17 import { GatherMaterialId, GemTier, tierSmeltSkillLevel } from "../../shared/definitions/materialTiers.js";
18 import { MetalItemId } from "../../shared/definitions/metalItems.js";
15 19
16 20 test("crafting stations map to the expected skills", () =>
17 21 {
18 22 assert.equal(craftingStationDefinition(CraftingStationId.furnace).skillId, SkillId.smithing);
19 23 assert.equal(craftingStationDefinition(CraftingStationId.anvil).skillId, SkillId.smithing);
24 assert.equal(craftingStationDefinition(CraftingStationId.jeweleringStation).skillId, SkillId.jewelering);
20 25 assert.equal(craftingStationDefinition(CraftingStationId.loom).skillId, SkillId.tailoring);
21 26 assert.equal(craftingStationDefinition(CraftingStationId.craftingBench).skillId, SkillId.crafting);
22 27 assert.equal(craftingStationDefinition(CraftingStationId.oven).skillId, SkillId.cooking);
@@ -124,3 +129,33 @@ test("woodworking, anvil, and crafting bench expose pickaxe and axe chain recipe
124 129 assert.equal(itemDefinition(ItemId.bronzeAxe)?.stub, undefined);
125 130 assert.equal(itemDefinition(ItemId.bronzeAxe)?.equipment?.kind, "axeTool");
126 131 });
132
133 test("jewelering cuts rough gems; staff recipes need cut gems", () =>
134 {
135 const cut = recipeDefinition("cut-tourmaline");
136 assert.ok(cut);
137 assert.equal(cut.stationId, CraftingStationId.jeweleringStation);
138 assert.equal(cut.skillId, SkillId.jewelering);
139 assert.equal(cut.minSkillLevel, tierSmeltSkillLevel(GemTier.tourmaline));
140 assert.deepEqual(cut.inputs, [{ itemId: GemItemId.tourmaline, quantity: 1 }]);
141 assert.equal(cut.output.itemId, GemItemId.tourmalineCut);
142 assert.equal(itemDefinition(GemItemId.tourmaline)?.gemForm, "rough");
143 assert.equal(itemDefinition(GemItemId.tourmalineCut)?.gemForm, "cut");
144 assert.equal(itemDefinition(GemItemId.tourmaline)?.defaultState, "rough");
145 assert.equal(itemDefinition(GemItemId.tourmalineCut)?.defaultState, "cut");
146
147 const staff = recipeDefinition("staff-pine");
148 assert.ok(staff);
149 assert.ok(staff.inputs.some((row) => row.itemId === GemItemId.tourmalineCut));
150 assert.ok(!staff.inputs.some((row) => row.itemId === GemItemId.tourmaline));
151
152 assert.equal(recipesForStation(CraftingStationId.jeweleringStation).length, 7);
153 assert.equal(JEWELRY_RECIPE_GUIDELINES.length, 7);
154 assert.equal(JEWELRY_RECIPE_GUIDELINES[0].metalId, GatherMaterialId.silver);
155 assert.equal(JEWELRY_RECIPE_GUIDELINES[0].metalQuantity, 1);
156 assert.equal(JEWELRY_RECIPE_GUIDELINES[3].metalId, GatherMaterialId.gold);
157 assert.equal(JEWELRY_RECIPE_GUIDELINES[3].metalQuantity, 4);
158 assert.equal(JEWELRY_RECIPE_GUIDELINES[6].metalId, GatherMaterialId.electrum);
159 assert.equal(JEWELRY_RECIPE_GUIDELINES[6].metalBarItemId, MetalItemId.electrumBar);
160 assert.equal(JEWELRY_RECIPE_GUIDELINES[6].metalQuantity, 7);
161 });
@@ -1,22 +1,27 @@
1import test from "node:test";
1import test from "node:test";
2import assert from "node:assert/strict";
2import assert from "node:assert/strict";
3import {
3import
4 CraftingStationId,
4 {
5 FIREPLACE_DURATION_MS,
5 CraftingStationId,
6 CRAFT_DURATION_MS,
6 FIREPLACE_DURATION_MS,
7 craftingStationDefinition
7 CRAFT_DURATION_MS,
8} from "../../shared/definitions/craftingStations.js";
8 craftingStationDefinition
9 } from "../../shared/definitions/craftingStations.js";
9import { SkillId } from "../../shared/definitions/skills.js";
10import { SkillId } from "../../shared/definitions/skills.js";
10import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
11import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
11import { emptySlots } from "../../shared/items/inventory.js";
12import { emptySlots } from "../../shared/items/inventory.js";
12import { canCraftFitInventory, CRAFT_DURATION_MS as RECIPE_CRAFT_MS, canStartCraft } from "../../shared/crafting/recipes.js";
13import { canCraftFitInventory, CRAFT_DURATION_MS as RECIPE_CRAFT_MS, canStartCraft } from "../../shared/crafting/recipes.js";
13import { recipesForStation, recipeDefinition } from "../../shared/crafting/stationRecipes.js";
14import { recipesForStation, recipeDefinition } from "../../shared/crafting/stationRecipes.js";
14import { CraftingItemId } from "../../shared/definitions/craftingItems.js";
15import { CraftingItemId } from "../../shared/definitions/craftingItems.js";
16import { GemItemId, JEWELRY_RECIPE_GUIDELINES } from "../../shared/definitions/gemItems.js";
17import { GatherMaterialId, GemTier, tierSmeltSkillLevel } from "../../shared/definitions/materialTiers.js";
18import { MetalItemId } from "../../shared/definitions/metalItems.js";
15
19
16test("crafting stations map to the expected skills", () =>
20test("crafting stations map to the expected skills", () =>
17{
21{
18 assert.equal(craftingStationDefinition(CraftingStationId.furnace).skillId, SkillId.smithing);
22 assert.equal(craftingStationDefinition(CraftingStationId.furnace).skillId, SkillId.smithing);
19 assert.equal(craftingStationDefinition(CraftingStationId.anvil).skillId, SkillId.smithing);
23 assert.equal(craftingStationDefinition(CraftingStationId.anvil).skillId, SkillId.smithing);
24 assert.equal(craftingStationDefinition(CraftingStationId.jeweleringStation).skillId, SkillId.jewelering);
20 assert.equal(craftingStationDefinition(CraftingStationId.loom).skillId, SkillId.tailoring);
25 assert.equal(craftingStationDefinition(CraftingStationId.loom).skillId, SkillId.tailoring);
21 assert.equal(craftingStationDefinition(CraftingStationId.craftingBench).skillId, SkillId.crafting);
26 assert.equal(craftingStationDefinition(CraftingStationId.craftingBench).skillId, SkillId.crafting);
22 assert.equal(craftingStationDefinition(CraftingStationId.oven).skillId, SkillId.cooking);
27 assert.equal(craftingStationDefinition(CraftingStationId.oven).skillId, SkillId.cooking);
@@ -124,3 +129,33 @@ test("woodworking, anvil, and crafting bench expose pickaxe and axe chain recipe
124 assert.equal(itemDefinition(ItemId.bronzeAxe)?.stub, undefined);
129 assert.equal(itemDefinition(ItemId.bronzeAxe)?.stub, undefined);
125 assert.equal(itemDefinition(ItemId.bronzeAxe)?.equipment?.kind, "axeTool");
130 assert.equal(itemDefinition(ItemId.bronzeAxe)?.equipment?.kind, "axeTool");
126});
131});
132
133test("jewelering cuts rough gems; staff recipes need cut gems", () =>
134{
135 const cut = recipeDefinition("cut-tourmaline");
136 assert.ok(cut);
137 assert.equal(cut.stationId, CraftingStationId.jeweleringStation);
138 assert.equal(cut.skillId, SkillId.jewelering);
139 assert.equal(cut.minSkillLevel, tierSmeltSkillLevel(GemTier.tourmaline));
140 assert.deepEqual(cut.inputs, [{ itemId: GemItemId.tourmaline, quantity: 1 }]);
141 assert.equal(cut.output.itemId, GemItemId.tourmalineCut);
142 assert.equal(itemDefinition(GemItemId.tourmaline)?.gemForm, "rough");
143 assert.equal(itemDefinition(GemItemId.tourmalineCut)?.gemForm, "cut");
144 assert.equal(itemDefinition(GemItemId.tourmaline)?.defaultState, "rough");
145 assert.equal(itemDefinition(GemItemId.tourmalineCut)?.defaultState, "cut");
146
147 const staff = recipeDefinition("staff-pine");
148 assert.ok(staff);
149 assert.ok(staff.inputs.some((row) => row.itemId === GemItemId.tourmalineCut));
150 assert.ok(!staff.inputs.some((row) => row.itemId === GemItemId.tourmaline));
151
152 assert.equal(recipesForStation(CraftingStationId.jeweleringStation).length, 7);
153 assert.equal(JEWELRY_RECIPE_GUIDELINES.length, 7);
154 assert.equal(JEWELRY_RECIPE_GUIDELINES[0].metalId, GatherMaterialId.silver);
155 assert.equal(JEWELRY_RECIPE_GUIDELINES[0].metalQuantity, 1);
156 assert.equal(JEWELRY_RECIPE_GUIDELINES[3].metalId, GatherMaterialId.gold);
157 assert.equal(JEWELRY_RECIPE_GUIDELINES[3].metalQuantity, 4);
158 assert.equal(JEWELRY_RECIPE_GUIDELINES[6].metalId, GatherMaterialId.electrum);
159 assert.equal(JEWELRY_RECIPE_GUIDELINES[6].metalBarItemId, MetalItemId.electrumBar);
160 assert.equal(JEWELRY_RECIPE_GUIDELINES[6].metalQuantity, 7);
161});
server/tests/friends.test.js +31 −7
@@ -10,15 +10,21 @@ function setup ()
10 10 {
11 11 const dir = mkdtempSync(join(tmpdir(), "mmo-friends-"));
12 12 const stateDb = new StateDatabase(join(dir, "state.sqlite"));
13 const accountA = stateDb.createAccount("admin-1", true);
14 const accountB = stateDb.createAccount("admin-2", true);
13 const accountA = stateDb.createAccount("admin-1", true, null, "ada_acc");
14 const accountB = stateDb.createAccount("admin-2", true, null, "ben_acc");
15 15 const left = stateDb.createCharacter(accountA.account_id, "Ada", "West", "female", 8, 8);
16 const leftAlt = stateDb.createCharacter(accountA.account_id, "Ada", "Alt", "female", 8, 8);
16 17 const right = stateDb.createCharacter(accountB.account_id, "Ben", "East", "male", 8, 8);
18 const rightAlt = stateDb.createCharacter(accountB.account_id, "Ben", "Twin", "male", 8, 8);
17 19 return {
18 20 stateDb,
19 21 friends: new FriendService(stateDb),
20 22 leftId: left.character_id,
21 rightId: right.character_id
23 leftAltId: leftAlt.character_id,
24 rightId: right.character_id,
25 rightAltId: rightAlt.character_id,
26 accountA: accountA.account_id,
27 accountB: accountB.account_id
22 28 };
23 29 }
24 30
@@ -30,11 +36,11 @@ test("a friend request must be accepted before both sides are friends", () =>
30 36 const pending = friends.request(leftId, rightId);
31 37 assert.equal(pending.outgoing.length, 1);
32 38 assert.equal(pending.friends.length, 0);
33 assert.equal(friends.snapshot(rightId).incoming[0].firstName, "Ada");
39 assert.equal(friends.snapshot(rightId).incoming[0].username, "ada_acc");
34 40
35 41 friends.accept(rightId, leftId);
36 42 assert.equal(friends.snapshot(leftId).friends.length, 1);
37 assert.equal(friends.snapshot(rightId).friends[0].lastName, "West");
43 assert.equal(friends.snapshot(rightId).friends[0].username, "ada_acc");
38 44 assert.equal(friends.snapshot(leftId).outgoing.length, 0);
39 45 assert.equal(friends.snapshot(rightId).incoming.length, 0);
40 46 }
@@ -42,7 +48,25 @@ test("a friend request must be accepted before both sides are friends", () =>
42 48 { stateDb.close(); }
43 49 });
44 50
45 test("removing a friend removes them for both characters", () =>
51 test("account friendship covers all characters on both accounts", () =>
52 {
53 const { stateDb, friends, leftId, leftAltId, rightId, rightAltId } = setup();
54 try
55 {
56 friends.request(leftId, rightId);
57 friends.accept(rightId, leftId);
58 assert.equal(friends.areFriends(leftId, rightId), true);
59 assert.equal(friends.areFriends(leftAltId, rightAltId), true);
60 assert.equal(friends.areFriends(leftId, leftAltId), true);
61 const flat = friends.listFriends(leftId);
62 assert.ok(flat.some((entry) => entry.characterId === rightId));
63 assert.ok(flat.some((entry) => entry.characterId === rightAltId));
64 }
65 finally
66 { stateDb.close(); }
67 });
68
69 test("removing a friend removes them for both accounts", () =>
46 70 {
47 71 const { stateDb, friends, leftId, rightId } = setup();
48 72 try
@@ -80,7 +104,7 @@ test("friends list is the pigeon address book of first and last names", () =>
80 104 friends.accept(rightId, leftId);
81 105 const found = friends.findByFullName("Ben", "East");
82 106 assert.equal(found.characterId, rightId);
83 assert.deepEqual(friends.listFriends(leftId)[0], found);
107 assert.ok(friends.listFriends(leftId).some((entry) => entry.characterId === found.characterId));
84 108 }
85 109 finally
86 110 { stateDb.close(); }
@@ -10,15 +10,21 @@ function setup ()
10{
10{
11 const dir = mkdtempSync(join(tmpdir(), "mmo-friends-"));
11 const dir = mkdtempSync(join(tmpdir(), "mmo-friends-"));
12 const stateDb = new StateDatabase(join(dir, "state.sqlite"));
12 const stateDb = new StateDatabase(join(dir, "state.sqlite"));
13 const accountA = stateDb.createAccount("admin-1", true);
13 const accountA = stateDb.createAccount("admin-1", true, null, "ada_acc");
14 const accountB = stateDb.createAccount("admin-2", true);
14 const accountB = stateDb.createAccount("admin-2", true, null, "ben_acc");
15 const left = stateDb.createCharacter(accountA.account_id, "Ada", "West", "female", 8, 8);
15 const left = stateDb.createCharacter(accountA.account_id, "Ada", "West", "female", 8, 8);
16 const leftAlt = stateDb.createCharacter(accountA.account_id, "Ada", "Alt", "female", 8, 8);
16 const right = stateDb.createCharacter(accountB.account_id, "Ben", "East", "male", 8, 8);
17 const right = stateDb.createCharacter(accountB.account_id, "Ben", "East", "male", 8, 8);
18 const rightAlt = stateDb.createCharacter(accountB.account_id, "Ben", "Twin", "male", 8, 8);
17 return {
19 return {
18 stateDb,
20 stateDb,
19 friends: new FriendService(stateDb),
21 friends: new FriendService(stateDb),
20 leftId: left.character_id,
22 leftId: left.character_id,
21 rightId: right.character_id
23 leftAltId: leftAlt.character_id,
24 rightId: right.character_id,
25 rightAltId: rightAlt.character_id,
26 accountA: accountA.account_id,
27 accountB: accountB.account_id
22 };
28 };
23}
29}
24
30
@@ -30,11 +36,11 @@ test("a friend request must be accepted before both sides are friends", () =>
30 const pending = friends.request(leftId, rightId);
36 const pending = friends.request(leftId, rightId);
31 assert.equal(pending.outgoing.length, 1);
37 assert.equal(pending.outgoing.length, 1);
32 assert.equal(pending.friends.length, 0);
38 assert.equal(pending.friends.length, 0);
33 assert.equal(friends.snapshot(rightId).incoming[0].firstName, "Ada");
39 assert.equal(friends.snapshot(rightId).incoming[0].username, "ada_acc");
34
40
35 friends.accept(rightId, leftId);
41 friends.accept(rightId, leftId);
36 assert.equal(friends.snapshot(leftId).friends.length, 1);
42 assert.equal(friends.snapshot(leftId).friends.length, 1);
37 assert.equal(friends.snapshot(rightId).friends[0].lastName, "West");
43 assert.equal(friends.snapshot(rightId).friends[0].username, "ada_acc");
38 assert.equal(friends.snapshot(leftId).outgoing.length, 0);
44 assert.equal(friends.snapshot(leftId).outgoing.length, 0);
39 assert.equal(friends.snapshot(rightId).incoming.length, 0);
45 assert.equal(friends.snapshot(rightId).incoming.length, 0);
40 }
46 }
@@ -42,7 +48,25 @@ test("a friend request must be accepted before both sides are friends", () =>
42 { stateDb.close(); }
48 { stateDb.close(); }
43});
49});
44
50
45test("removing a friend removes them for both characters", () =>
51test("account friendship covers all characters on both accounts", () =>
52{
53 const { stateDb, friends, leftId, leftAltId, rightId, rightAltId } = setup();
54 try
55 {
56 friends.request(leftId, rightId);
57 friends.accept(rightId, leftId);
58 assert.equal(friends.areFriends(leftId, rightId), true);
59 assert.equal(friends.areFriends(leftAltId, rightAltId), true);
60 assert.equal(friends.areFriends(leftId, leftAltId), true);
61 const flat = friends.listFriends(leftId);
62 assert.ok(flat.some((entry) => entry.characterId === rightId));
63 assert.ok(flat.some((entry) => entry.characterId === rightAltId));
64 }
65 finally
66 { stateDb.close(); }
67});
68
69test("removing a friend removes them for both accounts", () =>
46{
70{
47 const { stateDb, friends, leftId, rightId } = setup();
71 const { stateDb, friends, leftId, rightId } = setup();
48 try
72 try
@@ -80,7 +104,7 @@ test("friends list is the pigeon address book of first and last names", () =>
80 friends.accept(rightId, leftId);
104 friends.accept(rightId, leftId);
81 const found = friends.findByFullName("Ben", "East");
105 const found = friends.findByFullName("Ben", "East");
82 assert.equal(found.characterId, rightId);
106 assert.equal(found.characterId, rightId);
83 assert.deepEqual(friends.listFriends(leftId)[0], found);
107 assert.ok(friends.listFriends(leftId).some((entry) => entry.characterId === found.characterId));
84 }
108 }
85 finally
109 finally
86 { stateDb.close(); }
110 { stateDb.close(); }
server/tests/origins.test.js +18 −16
@@ -1,21 +1,22 @@
1 1 import test from "node:test";
2 2 import assert from "node:assert/strict";
3 import {
4 ItemOriginKind,
5 GatherOriginVerb,
6 CraftOriginVerb,
7 gatherOrigin,
8 lootOrigin,
9 craftOrigin,
10 craftOriginVerbForStation,
11 royalTreasuryOrigin,
12 ROYAL_TREASURY_ORIGIN_LABEL,
13 originLabel,
14 formatOriginBreakdown,
15 mergeOriginLists,
16 normalizeOrigins,
17 splitOrigins
18 } from "../../shared/items/origin.js";
3 import
4 {
5 ItemOriginKind,
6 GatherOriginVerb,
7 CraftOriginVerb,
8 gatherOrigin,
9 lootOrigin,
10 craftOrigin,
11 craftOriginVerbForStation,
12 royalTreasuryOrigin,
13 ROYAL_TREASURY_ORIGIN_LABEL,
14 originLabel,
15 formatOriginBreakdown,
16 mergeOriginLists,
17 normalizeOrigins,
18 splitOrigins
19 } from "../../shared/items/origin.js";
19 20 import { CraftingStationId } from "../../shared/definitions/craftingStations.js";
20 21 import { emptySlots, insertStack, takeFromSlot, insertStackGrowable, singleItemFromStack } from "../../shared/items/inventory.js";
21 22 import { stackRulesFor } from "../../shared/items/stackRules.js";
@@ -66,6 +67,7 @@ test("craft origins use station verbs", () =>
66 67 {
67 68 assert.equal(craftOriginVerbForStation(CraftingStationId.furnace), CraftOriginVerb.forged);
68 69 assert.equal(craftOriginVerbForStation(CraftingStationId.anvil), CraftOriginVerb.smithed);
70 assert.equal(craftOriginVerbForStation(CraftingStationId.jeweleringStation), CraftOriginVerb.cut);
69 71 assert.equal(craftOriginVerbForStation(CraftingStationId.woodworkingBench), CraftOriginVerb.carved);
70 72 assert.equal(craftOriginVerbForStation(CraftingStationId.craftingBench), CraftOriginVerb.assembled);
71 73 assert.equal(originLabel(craftOrigin(CraftOriginVerb.forged, "Ada")), "Forged by Ada");
@@ -1,21 +1,22 @@
1import test from "node:test";
1import test from "node:test";
2import assert from "node:assert/strict";
2import assert from "node:assert/strict";
3import {
3import
4 ItemOriginKind,
4 {
5 GatherOriginVerb,
5 ItemOriginKind,
6 CraftOriginVerb,
6 GatherOriginVerb,
7 gatherOrigin,
7 CraftOriginVerb,
8 lootOrigin,
8 gatherOrigin,
9 craftOrigin,
9 lootOrigin,
10 craftOriginVerbForStation,
10 craftOrigin,
11 royalTreasuryOrigin,
11 craftOriginVerbForStation,
12 ROYAL_TREASURY_ORIGIN_LABEL,
12 royalTreasuryOrigin,
13 originLabel,
13 ROYAL_TREASURY_ORIGIN_LABEL,
14 formatOriginBreakdown,
14 originLabel,
15 mergeOriginLists,
15 formatOriginBreakdown,
16 normalizeOrigins,
16 mergeOriginLists,
17 splitOrigins
17 normalizeOrigins,
18} from "../../shared/items/origin.js";
18 splitOrigins
19 } from "../../shared/items/origin.js";
19import { CraftingStationId } from "../../shared/definitions/craftingStations.js";
20import { CraftingStationId } from "../../shared/definitions/craftingStations.js";
20import { emptySlots, insertStack, takeFromSlot, insertStackGrowable, singleItemFromStack } from "../../shared/items/inventory.js";
21import { emptySlots, insertStack, takeFromSlot, insertStackGrowable, singleItemFromStack } from "../../shared/items/inventory.js";
21import { stackRulesFor } from "../../shared/items/stackRules.js";
22import { stackRulesFor } from "../../shared/items/stackRules.js";
@@ -66,6 +67,7 @@ test("craft origins use station verbs", () =>
66{
67{
67 assert.equal(craftOriginVerbForStation(CraftingStationId.furnace), CraftOriginVerb.forged);
68 assert.equal(craftOriginVerbForStation(CraftingStationId.furnace), CraftOriginVerb.forged);
68 assert.equal(craftOriginVerbForStation(CraftingStationId.anvil), CraftOriginVerb.smithed);
69 assert.equal(craftOriginVerbForStation(CraftingStationId.anvil), CraftOriginVerb.smithed);
70 assert.equal(craftOriginVerbForStation(CraftingStationId.jeweleringStation), CraftOriginVerb.cut);
69 assert.equal(craftOriginVerbForStation(CraftingStationId.woodworkingBench), CraftOriginVerb.carved);
71 assert.equal(craftOriginVerbForStation(CraftingStationId.woodworkingBench), CraftOriginVerb.carved);
70 assert.equal(craftOriginVerbForStation(CraftingStationId.craftingBench), CraftOriginVerb.assembled);
72 assert.equal(craftOriginVerbForStation(CraftingStationId.craftingBench), CraftOriginVerb.assembled);
71 assert.equal(originLabel(craftOrigin(CraftOriginVerb.forged, "Ada")), "Forged by Ada");
73 assert.equal(originLabel(craftOrigin(CraftOriginVerb.forged, "Ada")), "Forged by Ada");
server/tests/skull.test.js added +35 −0
@@ -0,0 +1,35 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import
4 {
5 skullValue,
6 skullTintColor,
7 decayKillCounter,
8 SKULL_PURE_RED_VALUE,
9 SKULL_DARK_RED_VALUE,
10 SKULL_KILL_BONUS
11 } from "../../shared/combat/skull.js";
12
13 test("skull value is bounty plus kill counter", () =>
14 {
15 assert.equal(skullValue(100, 400), 500);
16 assert.equal(skullValue(0, 0), 0);
17 assert.equal(SKULL_KILL_BONUS, 500);
18 });
19
20 test("kill counter decays one point per second", () =>
21 {
22 assert.deepEqual(decayKillCounter(10, 3500), { killCounter: 7, consumedMs: 3000 });
23 assert.deepEqual(decayKillCounter(2, 10_000), { killCounter: 0, consumedMs: 2000 });
24 });
25
26 test("skull tint: invisible, white, red, dark red", () =>
27 {
28 assert.equal(skullTintColor(0), null);
29 assert.deepEqual(skullTintColor(1), { r: 1, g: 1, b: 1 });
30 assert.deepEqual(skullTintColor(SKULL_PURE_RED_VALUE), { r: 1, g: 0, b: 0 });
31 const dark = skullTintColor(SKULL_DARK_RED_VALUE);
32 assert.ok(Math.abs(dark.r - 128 / 255) < 1e-9);
33 assert.equal(dark.g, 0);
34 assert.equal(dark.b, 0);
35 });
@@ -0,0 +1,35 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import
4 {
5 skullValue,
6 skullTintColor,
7 decayKillCounter,
8 SKULL_PURE_RED_VALUE,
9 SKULL_DARK_RED_VALUE,
10 SKULL_KILL_BONUS
11 } from "../../shared/combat/skull.js";
12
13test("skull value is bounty plus kill counter", () =>
14{
15 assert.equal(skullValue(100, 400), 500);
16 assert.equal(skullValue(0, 0), 0);
17 assert.equal(SKULL_KILL_BONUS, 500);
18});
19
20test("kill counter decays one point per second", () =>
21{
22 assert.deepEqual(decayKillCounter(10, 3500), { killCounter: 7, consumedMs: 3000 });
23 assert.deepEqual(decayKillCounter(2, 10_000), { killCounter: 0, consumedMs: 2000 });
24});
25
26test("skull tint: invisible, white, red, dark red", () =>
27{
28 assert.equal(skullTintColor(0), null);
29 assert.deepEqual(skullTintColor(1), { r: 1, g: 1, b: 1 });
30 assert.deepEqual(skullTintColor(SKULL_PURE_RED_VALUE), { r: 1, g: 0, b: 0 });
31 const dark = skullTintColor(SKULL_DARK_RED_VALUE);
32 assert.ok(Math.abs(dark.r - 128 / 255) < 1e-9);
33 assert.equal(dark.g, 0);
34 assert.equal(dark.b, 0);
35});
shared/combat/skull.js added +71 −0
@@ -0,0 +1,71 @@
1 /** Skull marker: bounty + decaying kill counter. Magenta-tint color curve. */
2
3 export const SKULL_KILL_BONUS = 500;
4 export const SKULL_DECAY_PER_SECOND = 1;
5 /** Skull value at which tint is pure red. */
6 export const SKULL_PURE_RED_VALUE = 500_000;
7 /**
8 * Past pure red, tint reaches dark red (128,0,0) at this value and clamps.
9 * Same span as white→red (500k).
10 */
11 export const SKULL_DARK_RED_VALUE = 1_000_000;
12
13 /**
14 * @param {number} bountyCopper
15 * @param {number} killCounter
16 */
17 export function skullValue (bountyCopper, killCounter)
18 {
19 return Math.max(0, Math.floor(Number(bountyCopper) || 0) + Math.floor(Number(killCounter) || 0));
20 }
21
22 /**
23 * Decay kill counter by elapsed wall time (1 point / second).
24 * @returns {{ killCounter: number, consumedMs: number }}
25 */
26 export function decayKillCounter (killCounter, elapsedMs)
27 {
28 const current = Math.max(0, Number(killCounter) || 0);
29 if (current <= 0 || !(elapsedMs > 0))
30 { return { killCounter: current, consumedMs: 0 }; }
31 const decay = Math.min(current, Math.floor(elapsedMs / 1000) * SKULL_DECAY_PER_SECOND);
32 return {
33 killCounter: current - decay,
34 consumedMs: decay * 1000
35 };
36 }
37
38 function lerp (a, b, t)
39 {
40 return a + (b - a) * t;
41 }
42
43 /**
44 * Magenta-tint target color for a skull value (0 = invisible / unused).
45 * 1 → white; … → pure red at 500_000; then → dark red (128,0,0) by 1_000_000.
46 * @returns {{ r: number, g: number, b: number } | null} 0–1 channels, or null if invisible
47 */
48 export function skullTintColor (value)
49 {
50 const v = Math.max(0, Math.floor(Number(value) || 0));
51 if (v <= 0)
52 { return null; }
53 if (v <= 1)
54 { return Object.freeze({ r: 1, g: 1, b: 1 }); }
55 if (v <= SKULL_PURE_RED_VALUE)
56 {
57 const t = (v - 1) / (SKULL_PURE_RED_VALUE - 1);
58 return Object.freeze({
59 r: 1,
60 g: lerp(1, 0, t),
61 b: lerp(1, 0, t)
62 });
63 }
64 const t = Math.min(1, (v - SKULL_PURE_RED_VALUE) / (SKULL_DARK_RED_VALUE - SKULL_PURE_RED_VALUE));
65 const dark = 128 / 255;
66 return Object.freeze({
67 r: lerp(1, dark, t),
68 g: 0,
69 b: 0
70 });
71 }
@@ -0,0 +1,71 @@
1/** Skull marker: bounty + decaying kill counter. Magenta-tint color curve. */
2
3export const SKULL_KILL_BONUS = 500;
4export const SKULL_DECAY_PER_SECOND = 1;
5/** Skull value at which tint is pure red. */
6export const SKULL_PURE_RED_VALUE = 500_000;
7/**
8 * Past pure red, tint reaches dark red (128,0,0) at this value and clamps.
9 * Same span as white→red (500k).
10 */
11export const SKULL_DARK_RED_VALUE = 1_000_000;
12
13/**
14 * @param {number} bountyCopper
15 * @param {number} killCounter
16 */
17export function skullValue (bountyCopper, killCounter)
18{
19 return Math.max(0, Math.floor(Number(bountyCopper) || 0) + Math.floor(Number(killCounter) || 0));
20}
21
22/**
23 * Decay kill counter by elapsed wall time (1 point / second).
24 * @returns {{ killCounter: number, consumedMs: number }}
25 */
26export function decayKillCounter (killCounter, elapsedMs)
27{
28 const current = Math.max(0, Number(killCounter) || 0);
29 if (current <= 0 || !(elapsedMs > 0))
30 { return { killCounter: current, consumedMs: 0 }; }
31 const decay = Math.min(current, Math.floor(elapsedMs / 1000) * SKULL_DECAY_PER_SECOND);
32 return {
33 killCounter: current - decay,
34 consumedMs: decay * 1000
35 };
36}
37
38function lerp (a, b, t)
39{
40 return a + (b - a) * t;
41}
42
43/**
44 * Magenta-tint target color for a skull value (0 = invisible / unused).
45 * 1 → white; … → pure red at 500_000; then → dark red (128,0,0) by 1_000_000.
46 * @returns {{ r: number, g: number, b: number } | null} 0–1 channels, or null if invisible
47 */
48export function skullTintColor (value)
49{
50 const v = Math.max(0, Math.floor(Number(value) || 0));
51 if (v <= 0)
52 { return null; }
53 if (v <= 1)
54 { return Object.freeze({ r: 1, g: 1, b: 1 }); }
55 if (v <= SKULL_PURE_RED_VALUE)
56 {
57 const t = (v - 1) / (SKULL_PURE_RED_VALUE - 1);
58 return Object.freeze({
59 r: 1,
60 g: lerp(1, 0, t),
61 b: lerp(1, 0, t)
62 });
63 }
64 const t = Math.min(1, (v - SKULL_PURE_RED_VALUE) / (SKULL_DARK_RED_VALUE - SKULL_PURE_RED_VALUE));
65 const dark = 128 / 255;
66 return Object.freeze({
67 r: lerp(1, dark, t),
68 g: 0,
69 b: 0
70 });
71}
shared/crafting/stationRecipes.js +18 −10
@@ -4,18 +4,19 @@ import { CraftingItemId } from "../definitions/craftingItems.js";
4 4 import { MetalItemId } from "../definitions/metalItems.js";
5 5 import { LeatherItemId } from "../definitions/leatherItems.js";
6 6 import { ClothItemId, wovenClothItemId, rawClothItemId, yarnItemId, CLOTHING_TEMPLATES } from "../definitions/clothItems.js";
7 import {
8 MaterialTier,
9 GatherMaterialId,
10 CLOTH_TIER_ORDER,
11 ClothTier,
12 LeatherTier,
13 tierSmeltSkillLevel,
14 tierCraftSkillLevel
15 } from "../definitions/materialTiers.js";
7 import
8 {
9 MaterialTier,
10 GatherMaterialId,
11 CLOTH_TIER_ORDER,
12 ClothTier,
13 LeatherTier,
14 tierSmeltSkillLevel,
15 tierCraftSkillLevel
16 } from "../definitions/materialTiers.js";
16 17 import { TIER_FAMILY_RECIPES } from "./tierRecipes.js";
17 18 import { fishingToolRecipes, fishingCookRecipes } from "../definitions/fishItems.js";
18 import { staffCraftRecipes } from "../definitions/gemItems.js";
19 import { staffCraftRecipes, gemCutRecipes } from "../definitions/gemItems.js";
19 20
20 21 /**
21 22 * Craft recipe schema (shared client + server):
@@ -110,6 +111,12 @@ export const CRAFT_RECIPES = Object.freeze([
110 111 { itemId: MetalItemId.goldOre, quantity: 1 }
111 112 ], MetalItemId.goldBar),
112 113
114 smelt(GatherMaterialId.electrum, "smelt-electrum", [
115 { itemId: MetalItemId.goldOre, quantity: 1 },
116 { itemId: MetalItemId.silverOre, quantity: 1 },
117 { itemId: MetalItemId.coal, quantity: 3 }
118 ], MetalItemId.electrumBar),
119
113 120 smelt(MaterialTier.mithril, "smelt-mithril", [
114 121 { itemId: MetalItemId.mithrilOre, quantity: 1 }
115 122 ], MetalItemId.mithrilBar),
@@ -195,6 +202,7 @@ export const CRAFT_RECIPES = Object.freeze([
195 202
196 203 ...fishingToolRecipes(),
197 204 ...fishingCookRecipes(),
205 ...gemCutRecipes(),
198 206 ...staffCraftRecipes()
199 207 ]);
200 208
@@ -4,18 +4,19 @@ import { CraftingItemId } from "../definitions/craftingItems.js";
4import { MetalItemId } from "../definitions/metalItems.js";
4import { MetalItemId } from "../definitions/metalItems.js";
5import { LeatherItemId } from "../definitions/leatherItems.js";
5import { LeatherItemId } from "../definitions/leatherItems.js";
6import { ClothItemId, wovenClothItemId, rawClothItemId, yarnItemId, CLOTHING_TEMPLATES } from "../definitions/clothItems.js";
6import { ClothItemId, wovenClothItemId, rawClothItemId, yarnItemId, CLOTHING_TEMPLATES } from "../definitions/clothItems.js";
7import {
7import
8 MaterialTier,
8 {
9 GatherMaterialId,
9 MaterialTier,
10 CLOTH_TIER_ORDER,
10 GatherMaterialId,
11 ClothTier,
11 CLOTH_TIER_ORDER,
12 LeatherTier,
12 ClothTier,
13 tierSmeltSkillLevel,
13 LeatherTier,
14 tierCraftSkillLevel
14 tierSmeltSkillLevel,
15} from "../definitions/materialTiers.js";
15 tierCraftSkillLevel
16 } from "../definitions/materialTiers.js";
16import { TIER_FAMILY_RECIPES } from "./tierRecipes.js";
17import { TIER_FAMILY_RECIPES } from "./tierRecipes.js";
17import { fishingToolRecipes, fishingCookRecipes } from "../definitions/fishItems.js";
18import { fishingToolRecipes, fishingCookRecipes } from "../definitions/fishItems.js";
18import { staffCraftRecipes } from "../definitions/gemItems.js";
19import { staffCraftRecipes, gemCutRecipes } from "../definitions/gemItems.js";
19
20
20/**
21/**
21 * Craft recipe schema (shared client + server):
22 * Craft recipe schema (shared client + server):
@@ -110,6 +111,12 @@ export const CRAFT_RECIPES = Object.freeze([
110 { itemId: MetalItemId.goldOre, quantity: 1 }
111 { itemId: MetalItemId.goldOre, quantity: 1 }
111 ], MetalItemId.goldBar),
112 ], MetalItemId.goldBar),
112
113
114 smelt(GatherMaterialId.electrum, "smelt-electrum", [
115 { itemId: MetalItemId.goldOre, quantity: 1 },
116 { itemId: MetalItemId.silverOre, quantity: 1 },
117 { itemId: MetalItemId.coal, quantity: 3 }
118 ], MetalItemId.electrumBar),
119
113 smelt(MaterialTier.mithril, "smelt-mithril", [
120 smelt(MaterialTier.mithril, "smelt-mithril", [
114 { itemId: MetalItemId.mithrilOre, quantity: 1 }
121 { itemId: MetalItemId.mithrilOre, quantity: 1 }
115 ], MetalItemId.mithrilBar),
122 ], MetalItemId.mithrilBar),
@@ -195,6 +202,7 @@ export const CRAFT_RECIPES = Object.freeze([
195
202
196 ...fishingToolRecipes(),
203 ...fishingToolRecipes(),
197 ...fishingCookRecipes(),
204 ...fishingCookRecipes(),
205 ...gemCutRecipes(),
198 ...staffCraftRecipes()
206 ...staffCraftRecipes()
199]);
207]);
200
208
shared/definitions/craftingStations.js +7 −0
@@ -14,6 +14,7 @@ export const CraftingStationId = Object.freeze({
14 14 spinningWheel: "spinning-wheel",
15 15 loom: "loom",
16 16 anvil: "anvil",
17 jeweleringStation: "jewelering-station",
17 18 leatherworkingStation: "leatherworking-station",
18 19 craftingBench: "crafting-bench",
19 20 woodworkingBench: "woodworking-bench",
@@ -89,6 +90,12 @@ export const CRAFTING_STATION_DEFINITIONS = Object.freeze({
89 90 skillId: SkillId.smithing,
90 91 description: "Smith metal items from bars."
91 92 }),
93 [CraftingStationId.jeweleringStation]: Object.freeze({
94 stationId: CraftingStationId.jeweleringStation,
95 displayName: "Jewelering station",
96 skillId: SkillId.jewelering,
97 description: "Cut gemstones and set precious metal jewellery."
98 }),
92 99 [CraftingStationId.leatherworkingStation]: Object.freeze({
93 100 stationId: CraftingStationId.leatherworkingStation,
94 101 displayName: "Leatherworking station",
@@ -14,6 +14,7 @@ export const CraftingStationId = Object.freeze({
14 spinningWheel: "spinning-wheel",
14 spinningWheel: "spinning-wheel",
15 loom: "loom",
15 loom: "loom",
16 anvil: "anvil",
16 anvil: "anvil",
17 jeweleringStation: "jewelering-station",
17 leatherworkingStation: "leatherworking-station",
18 leatherworkingStation: "leatherworking-station",
18 craftingBench: "crafting-bench",
19 craftingBench: "crafting-bench",
19 woodworkingBench: "woodworking-bench",
20 woodworkingBench: "woodworking-bench",
@@ -89,6 +90,12 @@ export const CRAFTING_STATION_DEFINITIONS = Object.freeze({
89 skillId: SkillId.smithing,
90 skillId: SkillId.smithing,
90 description: "Smith metal items from bars."
91 description: "Smith metal items from bars."
91 }),
92 }),
93 [CraftingStationId.jeweleringStation]: Object.freeze({
94 stationId: CraftingStationId.jeweleringStation,
95 displayName: "Jewelering station",
96 skillId: SkillId.jewelering,
97 description: "Cut gemstones and set precious metal jewellery."
98 }),
92 [CraftingStationId.leatherworkingStation]: Object.freeze({
99 [CraftingStationId.leatherworkingStation]: Object.freeze({
93 stationId: CraftingStationId.leatherworkingStation,
100 stationId: CraftingStationId.leatherworkingStation,
94 displayName: "Leatherworking station",
101 displayName: "Leatherworking station",
shared/definitions/gathering.js +23 −20
@@ -5,29 +5,31 @@ import { logItemIdForWood } from "./woodItems.js";
5 5 import { EquipmentKind } from "./equipmentKinds.js";
6 6 import { canEquipItem } from "../equipment/stats.js";
7 7 import { SkillId, skillLevel } from "./skills.js";
8 import {
9 MaterialTier,
10 GatherMaterialId,
11 WoodTier,
12 ORE_BEARING_MATERIALS,
13 associatedBarTier,
14 tierMineSkillLevel,
15 tierSmeltSkillLevel,
16 tierRank,
17 miningDurationMs,
18 oreExhaustDurationMs,
19 smeltingDurationMs,
20 SMELT_DURATION_PER_RANK_MS,
21 EXHAUSTED_ORE_BOULDER_STATE,
22 oreBoulderState,
23 materialFromOreBoulderState,
24 isOreBoulderState,
25 isGemstoneMaterial
26 } from "./materialTiers.js";
8 import
9 {
10 MaterialTier,
11 GatherMaterialId,
12 WoodTier,
13 ORE_BEARING_MATERIALS,
14 associatedBarTier,
15 tierMineSkillLevel,
16 tierSmeltSkillLevel,
17 tierRank,
18 miningDurationMs,
19 oreExhaustDurationMs,
20 smeltingDurationMs,
21 SMELT_DURATION_PER_RANK_MS,
22 EXHAUSTED_ORE_BOULDER_STATE,
23 oreBoulderState,
24 materialFromOreBoulderState,
25 isOreBoulderState,
26 isGemstoneMaterial
27 } from "./materialTiers.js";
27 28 import { gemItemId } from "./gemItems.js";
28 29 import { herbDefinition, herbGatherSkillLevel } from "./herbs.js";
29 30
30 export {
31 export
32 {
31 33 ORE_BEARING_MATERIALS,
32 34 associatedBarTier,
33 35 tierMineSkillLevel,
@@ -78,6 +80,7 @@ export const BAR_ITEM_BY_MATERIAL = Object.freeze({
78 80 [MaterialTier.steel]: MetalItemId.steelBar,
79 81 [GatherMaterialId.silver]: MetalItemId.silverBar,
80 82 [GatherMaterialId.gold]: MetalItemId.goldBar,
83 [GatherMaterialId.electrum]: MetalItemId.electrumBar,
81 84 [MaterialTier.mithril]: MetalItemId.mithrilBar,
82 85 [MaterialTier.adamantium]: MetalItemId.adamantiumBar,
83 86 [MaterialTier.orichalcum]: MetalItemId.orichalcumBar,
@@ -5,29 +5,31 @@ import { logItemIdForWood } from "./woodItems.js";
5import { EquipmentKind } from "./equipmentKinds.js";
5import { EquipmentKind } from "./equipmentKinds.js";
6import { canEquipItem } from "../equipment/stats.js";
6import { canEquipItem } from "../equipment/stats.js";
7import { SkillId, skillLevel } from "./skills.js";
7import { SkillId, skillLevel } from "./skills.js";
8import {
8import
9 MaterialTier,
9 {
10 GatherMaterialId,
10 MaterialTier,
11 WoodTier,
11 GatherMaterialId,
12 ORE_BEARING_MATERIALS,
12 WoodTier,
13 associatedBarTier,
13 ORE_BEARING_MATERIALS,
14 tierMineSkillLevel,
14 associatedBarTier,
15 tierSmeltSkillLevel,
15 tierMineSkillLevel,
16 tierRank,
16 tierSmeltSkillLevel,
17 miningDurationMs,
17 tierRank,
18 oreExhaustDurationMs,
18 miningDurationMs,
19 smeltingDurationMs,
19 oreExhaustDurationMs,
20 SMELT_DURATION_PER_RANK_MS,
20 smeltingDurationMs,
21 EXHAUSTED_ORE_BOULDER_STATE,
21 SMELT_DURATION_PER_RANK_MS,
22 oreBoulderState,
22 EXHAUSTED_ORE_BOULDER_STATE,
23 materialFromOreBoulderState,
23 oreBoulderState,
24 isOreBoulderState,
24 materialFromOreBoulderState,
25 isGemstoneMaterial
25 isOreBoulderState,
26} from "./materialTiers.js";
26 isGemstoneMaterial
27 } from "./materialTiers.js";
27import { gemItemId } from "./gemItems.js";
28import { gemItemId } from "./gemItems.js";
28import { herbDefinition, herbGatherSkillLevel } from "./herbs.js";
29import { herbDefinition, herbGatherSkillLevel } from "./herbs.js";
29
30
30export {
31export
32{
31 ORE_BEARING_MATERIALS,
33 ORE_BEARING_MATERIALS,
32 associatedBarTier,
34 associatedBarTier,
33 tierMineSkillLevel,
35 tierMineSkillLevel,
@@ -78,6 +80,7 @@ export const BAR_ITEM_BY_MATERIAL = Object.freeze({
78 [MaterialTier.steel]: MetalItemId.steelBar,
80 [MaterialTier.steel]: MetalItemId.steelBar,
79 [GatherMaterialId.silver]: MetalItemId.silverBar,
81 [GatherMaterialId.silver]: MetalItemId.silverBar,
80 [GatherMaterialId.gold]: MetalItemId.goldBar,
82 [GatherMaterialId.gold]: MetalItemId.goldBar,
83 [GatherMaterialId.electrum]: MetalItemId.electrumBar,
81 [MaterialTier.mithril]: MetalItemId.mithrilBar,
84 [MaterialTier.mithril]: MetalItemId.mithrilBar,
82 [MaterialTier.adamantium]: MetalItemId.adamantiumBar,
85 [MaterialTier.adamantium]: MetalItemId.adamantiumBar,
83 [MaterialTier.orichalcum]: MetalItemId.orichalcumBar,
86 [MaterialTier.orichalcum]: MetalItemId.orichalcumBar,
shared/definitions/gemItems.js +136 −17
@@ -3,21 +3,25 @@ import
3 3 {
4 4 GemTier,
5 5 GEM_TIER_ORDER,
6 GatherMaterialId,
6 7 MATERIAL_DISPLAY_NAME,
7 8 WOOD_TIER_ORDER,
8 9 gemTierForWood,
9 10 tierMinSkillLevel,
10 tierRank
11 tierRank,
12 tierSmeltSkillLevel
11 13 } from "./materialTiers.js";
12 14 import { EquipmentKind } from "./equipmentKinds.js";
13 15 import { CraftingStationId } from "./craftingStations.js";
16 import { MetalItemId } from "./metalItems.js";
14 17 import { logItemIdForWood, ashItemIdForWood } from "./woodItems.js";
18 import { SkillId } from "./skills.js";
15 19
16 20 const DEFAULT_STACK = 99;
17 21
18 22 /**
19 * Raw gemstones (377–383) and magic staves (384–390).
20 * Staves: red = wood, blue = gem (dual-tint staff sprite).
23 * Rough gemstones (377–383, mined), cut gemstones (402–408), magic staves (384–390).
24 * Staves: red = wood, blue = gem (dual-tint staff sprite); require cut gems.
21 25 */
22 26 export const GemItemId = Object.freeze({
23 27 tourmaline: 377,
@@ -33,10 +37,18 @@ export const GemItemId = Object.freeze({
33 37 ebonyStaff: 387,
34 38 lignumStaff: 388,
35 39 heartwoodStaff: 389,
36 elderStaff: 390
40 elderStaff: 390,
41 tourmalineCut: 402,
42 alexandriteCut: 403,
43 opalCut: 404,
44 diamondCut: 405,
45 emeraldCut: 406,
46 rubyCut: 407,
47 jadeiteCut: 408
37 48 });
38 49
39 export const GEM_ITEM_BY_TIER = Object.freeze({
50 /** Mined / uncut gem item id by tier. */
51 export const ROUGH_GEM_ITEM_BY_TIER = Object.freeze({
40 52 [GemTier.tourmaline]: GemItemId.tourmaline,
41 53 [GemTier.alexandrite]: GemItemId.alexandrite,
42 54 [GemTier.opal]: GemItemId.opal,
@@ -46,6 +58,20 @@ export const GEM_ITEM_BY_TIER = Object.freeze({
46 58 [GemTier.jadeite]: GemItemId.jadeite
47 59 });
48 60
61 /** Cut gem item id by tier (jewelering + staves). */
62 export const CUT_GEM_ITEM_BY_TIER = Object.freeze({
63 [GemTier.tourmaline]: GemItemId.tourmalineCut,
64 [GemTier.alexandrite]: GemItemId.alexandriteCut,
65 [GemTier.opal]: GemItemId.opalCut,
66 [GemTier.diamond]: GemItemId.diamondCut,
67 [GemTier.emerald]: GemItemId.emeraldCut,
68 [GemTier.ruby]: GemItemId.rubyCut,
69 [GemTier.jadeite]: GemItemId.jadeiteCut
70 });
71
72 /** @deprecated Prefer {@link ROUGH_GEM_ITEM_BY_TIER} / {@link roughGemItemId}. */
73 export const GEM_ITEM_BY_TIER = ROUGH_GEM_ITEM_BY_TIER;
74
49 75 export const STAFF_ITEM_BY_WOOD = Object.freeze({
50 76 pine: GemItemId.pineStaff,
51 77 birch: GemItemId.birchStaff,
@@ -56,9 +82,21 @@ export const STAFF_ITEM_BY_WOOD = Object.freeze({
56 82 elder: GemItemId.elderStaff
57 83 });
58 84
85 /** Rough (mined) gem item id. */
86 export function roughGemItemId (gemTier)
87 {
88 return ROUGH_GEM_ITEM_BY_TIER[gemTier] ?? null;
89 }
90
91 /** Alias for mining drops — always the rough stone. */
59 92 export function gemItemId (gemTier)
60 93 {
61 return GEM_ITEM_BY_TIER[gemTier] ?? null;
94 return roughGemItemId(gemTier);
95 }
96
97 export function cutGemItemId (gemTier)
98 {
99 return CUT_GEM_ITEM_BY_TIER[gemTier] ?? null;
62 100 }
63 101
64 102 export function staffItemIdForWood (woodTier)
@@ -66,28 +104,92 @@ export function staffItemIdForWood (woodTier)
66 104 return STAFF_ITEM_BY_WOOD[woodTier] ?? null;
67 105 }
68 106
69 function buildGemDefinitions ()
107 /**
108 * Future jewellery at the jewelering station (not live craft recipes yet).
109 * Metal quantity = gem tier rank; silver (1–3), gold (4–6), electrum (7).
110 */
111 export const JEWELRY_RECIPE_GUIDELINES = Object.freeze(
112 GEM_TIER_ORDER.map((gemTier, index) =>
113 {
114 const tier = index + 1;
115 let metalId;
116 if (tier <= 3)
117 { metalId = GatherMaterialId.silver; }
118 else if (tier <= 6)
119 { metalId = GatherMaterialId.gold; }
120 else
121 { metalId = GatherMaterialId.electrum; }
122 const metalBarItemId = metalId === GatherMaterialId.electrum
123 ? MetalItemId.electrumBar
124 : metalId === GatherMaterialId.gold
125 ? MetalItemId.goldBar
126 : MetalItemId.silverBar;
127 return Object.freeze({
128 tier,
129 gemTier,
130 cutGemItemId: cutGemItemId(gemTier),
131 metalId,
132 metalBarItemId,
133 metalQuantity: tier,
134 stationId: CraftingStationId.jeweleringStation,
135 skillId: SkillId.jewelering,
136 minSkillLevel: tierMinSkillLevel(gemTier)
137 });
138 })
139 );
140
141 function buildRoughGemDefinitions ()
70 142 {
71 143 const out = {};
72 144 for (const gemTier of GEM_TIER_ORDER)
73 145 {
74 const itemId = GEM_ITEM_BY_TIER[gemTier];
146 const itemId = ROUGH_GEM_ITEM_BY_TIER[gemTier];
75 147 const name = MATERIAL_DISPLAY_NAME[gemTier] ?? gemTier;
76 148 out[itemId] = Object.freeze({
77 149 itemId,
78 key: `${gemTier}-gem`,
79 displayName: name,
80 description: `A polished ${name.toLowerCase()}, cool and bright in the hand.`,
150 key: `${gemTier}-rough`,
151 displayName: `Rough ${name.toLowerCase()}`,
152 description: `An uncut ${name.toLowerCase()}, still rough from the rock.`,
153 seedValue: tierRank(gemTier) * 2,
154 stackable: true,
155 maxStackSize: DEFAULT_STACK,
156 uniqueInstance: false,
157 category: ItemCategory.ingredient,
158 iconKey: "gems",
159 defaultState: "rough",
160 tier: gemTier,
161 tintFromTier: true,
162 gemstone: true,
163 gemForm: "rough",
164 npcShopAllowed: true
165 });
166 }
167 return out;
168 }
169
170 function buildCutGemDefinitions ()
171 {
172 const out = {};
173 for (const gemTier of GEM_TIER_ORDER)
174 {
175 const itemId = CUT_GEM_ITEM_BY_TIER[gemTier];
176 const name = MATERIAL_DISPLAY_NAME[gemTier] ?? gemTier;
177 out[itemId] = Object.freeze({
178 itemId,
179 key: `${gemTier}-cut`,
180 displayName: `Cut ${name.toLowerCase()}`,
181 description: `A faceted ${name.toLowerCase()}, cool and bright in the hand.`,
81 182 seedValue: tierRank(gemTier) * 3,
82 183 stackable: true,
83 184 maxStackSize: DEFAULT_STACK,
84 185 uniqueInstance: false,
85 186 category: ItemCategory.ingredient,
86 iconKey: "metal",
87 defaultState: "ore",
187 iconKey: "gems",
188 defaultState: "cut",
88 189 tier: gemTier,
89 190 tintFromTier: true,
90 191 gemstone: true,
192 gemForm: "cut",
91 193 npcShopAllowed: true
92 194 });
93 195 }
@@ -133,11 +235,28 @@ function buildStaffDefinitions ()
133 235 }
134 236
135 237 export const GEM_ITEM_DEFINITIONS = Object.freeze({
136 ...buildGemDefinitions(),
238 ...buildRoughGemDefinitions(),
239 ...buildCutGemDefinitions(),
137 240 ...buildStaffDefinitions()
138 241 });
139 242
140 /** Craft recipes: 1 log + 1 gem + 1 ash → staff (matching wood/gem tier). */
243 /** Jewelering: rough → cut (skill gate matches smithing ore → bar). */
244 export function gemCutRecipes ()
245 {
246 return GEM_TIER_ORDER.map((gemTier) => Object.freeze({
247 recipeId: `cut-${gemTier}`,
248 craftGroup: "cut-gem",
249 craftGroupLabel: "Cut gem",
250 stationId: CraftingStationId.jeweleringStation,
251 output: { itemId: cutGemItemId(gemTier), quantity: 1 },
252 inputs: [{ itemId: roughGemItemId(gemTier), quantity: 1 }],
253 minSkillLevel: tierSmeltSkillLevel(gemTier),
254 skillId: SkillId.jewelering,
255 xpMaterial: gemTier
256 }));
257 }
258
259 /** Craft recipes: 1 log + 1 cut gem + 1 ash → staff (matching wood/gem tier). */
141 260 export function staffCraftRecipes ()
142 261 {
143 262 return WOOD_TIER_ORDER.map((woodTier) =>
@@ -151,11 +270,11 @@ export function staffCraftRecipes ()
151 270 output: { itemId: staffItemIdForWood(woodTier), quantity: 1 },
152 271 inputs: [
153 272 { itemId: logItemIdForWood(woodTier), quantity: 1 },
154 { itemId: gemItemId(gemTier), quantity: 1 },
273 { itemId: cutGemItemId(gemTier), quantity: 1 },
155 274 { itemId: ashItemIdForWood(woodTier), quantity: 1 }
156 275 ],
157 276 minSkillLevel: tierMinSkillLevel(woodTier),
158 skillId: "crafting",
277 skillId: SkillId.crafting,
159 278 xpMaterial: woodTier
160 279 });
161 280 });
@@ -3,21 +3,25 @@ import
3 {
3 {
4 GemTier,
4 GemTier,
5 GEM_TIER_ORDER,
5 GEM_TIER_ORDER,
6 GatherMaterialId,
6 MATERIAL_DISPLAY_NAME,
7 MATERIAL_DISPLAY_NAME,
7 WOOD_TIER_ORDER,
8 WOOD_TIER_ORDER,
8 gemTierForWood,
9 gemTierForWood,
9 tierMinSkillLevel,
10 tierMinSkillLevel,
10 tierRank
11 tierRank,
12 tierSmeltSkillLevel
11 } from "./materialTiers.js";
13 } from "./materialTiers.js";
12import { EquipmentKind } from "./equipmentKinds.js";
14import { EquipmentKind } from "./equipmentKinds.js";
13import { CraftingStationId } from "./craftingStations.js";
15import { CraftingStationId } from "./craftingStations.js";
16import { MetalItemId } from "./metalItems.js";
14import { logItemIdForWood, ashItemIdForWood } from "./woodItems.js";
17import { logItemIdForWood, ashItemIdForWood } from "./woodItems.js";
18import { SkillId } from "./skills.js";
15
19
16const DEFAULT_STACK = 99;
20const DEFAULT_STACK = 99;
17
21
18/**
22/**
19 * Raw gemstones (377–383) and magic staves (384–390).
23 * Rough gemstones (377–383, mined), cut gemstones (402–408), magic staves (384–390).
20 * Staves: red = wood, blue = gem (dual-tint staff sprite).
24 * Staves: red = wood, blue = gem (dual-tint staff sprite); require cut gems.
21 */
25 */
22export const GemItemId = Object.freeze({
26export const GemItemId = Object.freeze({
23 tourmaline: 377,
27 tourmaline: 377,
@@ -33,10 +37,18 @@ export const GemItemId = Object.freeze({
33 ebonyStaff: 387,
37 ebonyStaff: 387,
34 lignumStaff: 388,
38 lignumStaff: 388,
35 heartwoodStaff: 389,
39 heartwoodStaff: 389,
36 elderStaff: 390
40 elderStaff: 390,
41 tourmalineCut: 402,
42 alexandriteCut: 403,
43 opalCut: 404,
44 diamondCut: 405,
45 emeraldCut: 406,
46 rubyCut: 407,
47 jadeiteCut: 408
37});
48});
38
49
39export const GEM_ITEM_BY_TIER = Object.freeze({
50/** Mined / uncut gem item id by tier. */
51export const ROUGH_GEM_ITEM_BY_TIER = Object.freeze({
40 [GemTier.tourmaline]: GemItemId.tourmaline,
52 [GemTier.tourmaline]: GemItemId.tourmaline,
41 [GemTier.alexandrite]: GemItemId.alexandrite,
53 [GemTier.alexandrite]: GemItemId.alexandrite,
42 [GemTier.opal]: GemItemId.opal,
54 [GemTier.opal]: GemItemId.opal,
@@ -46,6 +58,20 @@ export const GEM_ITEM_BY_TIER = Object.freeze({
46 [GemTier.jadeite]: GemItemId.jadeite
58 [GemTier.jadeite]: GemItemId.jadeite
47});
59});
48
60
61/** Cut gem item id by tier (jewelering + staves). */
62export const CUT_GEM_ITEM_BY_TIER = Object.freeze({
63 [GemTier.tourmaline]: GemItemId.tourmalineCut,
64 [GemTier.alexandrite]: GemItemId.alexandriteCut,
65 [GemTier.opal]: GemItemId.opalCut,
66 [GemTier.diamond]: GemItemId.diamondCut,
67 [GemTier.emerald]: GemItemId.emeraldCut,
68 [GemTier.ruby]: GemItemId.rubyCut,
69 [GemTier.jadeite]: GemItemId.jadeiteCut
70});
71
72/** @deprecated Prefer {@link ROUGH_GEM_ITEM_BY_TIER} / {@link roughGemItemId}. */
73export const GEM_ITEM_BY_TIER = ROUGH_GEM_ITEM_BY_TIER;
74
49export const STAFF_ITEM_BY_WOOD = Object.freeze({
75export const STAFF_ITEM_BY_WOOD = Object.freeze({
50 pine: GemItemId.pineStaff,
76 pine: GemItemId.pineStaff,
51 birch: GemItemId.birchStaff,
77 birch: GemItemId.birchStaff,
@@ -56,9 +82,21 @@ export const STAFF_ITEM_BY_WOOD = Object.freeze({
56 elder: GemItemId.elderStaff
82 elder: GemItemId.elderStaff
57});
83});
58
84
85/** Rough (mined) gem item id. */
86export function roughGemItemId (gemTier)
87{
88 return ROUGH_GEM_ITEM_BY_TIER[gemTier] ?? null;
89}
90
91/** Alias for mining drops — always the rough stone. */
59export function gemItemId (gemTier)
92export function gemItemId (gemTier)
60{
93{
61 return GEM_ITEM_BY_TIER[gemTier] ?? null;
94 return roughGemItemId(gemTier);
95}
96
97export function cutGemItemId (gemTier)
98{
99 return CUT_GEM_ITEM_BY_TIER[gemTier] ?? null;
62}
100}
63
101
64export function staffItemIdForWood (woodTier)
102export function staffItemIdForWood (woodTier)
@@ -66,28 +104,92 @@ export function staffItemIdForWood (woodTier)
66 return STAFF_ITEM_BY_WOOD[woodTier] ?? null;
104 return STAFF_ITEM_BY_WOOD[woodTier] ?? null;
67}
105}
68
106
69function buildGemDefinitions ()
107/**
108 * Future jewellery at the jewelering station (not live craft recipes yet).
109 * Metal quantity = gem tier rank; silver (1–3), gold (4–6), electrum (7).
110 */
111export const JEWELRY_RECIPE_GUIDELINES = Object.freeze(
112 GEM_TIER_ORDER.map((gemTier, index) =>
113 {
114 const tier = index + 1;
115 let metalId;
116 if (tier <= 3)
117 { metalId = GatherMaterialId.silver; }
118 else if (tier <= 6)
119 { metalId = GatherMaterialId.gold; }
120 else
121 { metalId = GatherMaterialId.electrum; }
122 const metalBarItemId = metalId === GatherMaterialId.electrum
123 ? MetalItemId.electrumBar
124 : metalId === GatherMaterialId.gold
125 ? MetalItemId.goldBar
126 : MetalItemId.silverBar;
127 return Object.freeze({
128 tier,
129 gemTier,
130 cutGemItemId: cutGemItemId(gemTier),
131 metalId,
132 metalBarItemId,
133 metalQuantity: tier,
134 stationId: CraftingStationId.jeweleringStation,
135 skillId: SkillId.jewelering,
136 minSkillLevel: tierMinSkillLevel(gemTier)
137 });
138 })
139);
140
141function buildRoughGemDefinitions ()
70{
142{
71 const out = {};
143 const out = {};
72 for (const gemTier of GEM_TIER_ORDER)
144 for (const gemTier of GEM_TIER_ORDER)
73 {
145 {
74 const itemId = GEM_ITEM_BY_TIER[gemTier];
146 const itemId = ROUGH_GEM_ITEM_BY_TIER[gemTier];
75 const name = MATERIAL_DISPLAY_NAME[gemTier] ?? gemTier;
147 const name = MATERIAL_DISPLAY_NAME[gemTier] ?? gemTier;
76 out[itemId] = Object.freeze({
148 out[itemId] = Object.freeze({
77 itemId,
149 itemId,
78 key: `${gemTier}-gem`,
150 key: `${gemTier}-rough`,
79 displayName: name,
151 displayName: `Rough ${name.toLowerCase()}`,
80 description: `A polished ${name.toLowerCase()}, cool and bright in the hand.`,
152 description: `An uncut ${name.toLowerCase()}, still rough from the rock.`,
153 seedValue: tierRank(gemTier) * 2,
154 stackable: true,
155 maxStackSize: DEFAULT_STACK,
156 uniqueInstance: false,
157 category: ItemCategory.ingredient,
158 iconKey: "gems",
159 defaultState: "rough",
160 tier: gemTier,
161 tintFromTier: true,
162 gemstone: true,
163 gemForm: "rough",
164 npcShopAllowed: true
165 });
166 }
167 return out;
168}
169
170function buildCutGemDefinitions ()
171{
172 const out = {};
173 for (const gemTier of GEM_TIER_ORDER)
174 {
175 const itemId = CUT_GEM_ITEM_BY_TIER[gemTier];
176 const name = MATERIAL_DISPLAY_NAME[gemTier] ?? gemTier;
177 out[itemId] = Object.freeze({
178 itemId,
179 key: `${gemTier}-cut`,
180 displayName: `Cut ${name.toLowerCase()}`,
181 description: `A faceted ${name.toLowerCase()}, cool and bright in the hand.`,
81 seedValue: tierRank(gemTier) * 3,
182 seedValue: tierRank(gemTier) * 3,
82 stackable: true,
183 stackable: true,
83 maxStackSize: DEFAULT_STACK,
184 maxStackSize: DEFAULT_STACK,
84 uniqueInstance: false,
185 uniqueInstance: false,
85 category: ItemCategory.ingredient,
186 category: ItemCategory.ingredient,
86 iconKey: "metal",
187 iconKey: "gems",
87 defaultState: "ore",
188 defaultState: "cut",
88 tier: gemTier,
189 tier: gemTier,
89 tintFromTier: true,
190 tintFromTier: true,
90 gemstone: true,
191 gemstone: true,
192 gemForm: "cut",
91 npcShopAllowed: true
193 npcShopAllowed: true
92 });
194 });
93 }
195 }
@@ -133,11 +235,28 @@ function buildStaffDefinitions ()
133}
235}
134
236
135export const GEM_ITEM_DEFINITIONS = Object.freeze({
237export const GEM_ITEM_DEFINITIONS = Object.freeze({
136 ...buildGemDefinitions(),
238 ...buildRoughGemDefinitions(),
239 ...buildCutGemDefinitions(),
137 ...buildStaffDefinitions()
240 ...buildStaffDefinitions()
138});
241});
139
242
140/** Craft recipes: 1 log + 1 gem + 1 ash → staff (matching wood/gem tier). */
243/** Jewelering: rough → cut (skill gate matches smithing ore → bar). */
244export function gemCutRecipes ()
245{
246 return GEM_TIER_ORDER.map((gemTier) => Object.freeze({
247 recipeId: `cut-${gemTier}`,
248 craftGroup: "cut-gem",
249 craftGroupLabel: "Cut gem",
250 stationId: CraftingStationId.jeweleringStation,
251 output: { itemId: cutGemItemId(gemTier), quantity: 1 },
252 inputs: [{ itemId: roughGemItemId(gemTier), quantity: 1 }],
253 minSkillLevel: tierSmeltSkillLevel(gemTier),
254 skillId: SkillId.jewelering,
255 xpMaterial: gemTier
256 }));
257}
258
259/** Craft recipes: 1 log + 1 cut gem + 1 ash → staff (matching wood/gem tier). */
141export function staffCraftRecipes ()
260export function staffCraftRecipes ()
142{
261{
143 return WOOD_TIER_ORDER.map((woodTier) =>
262 return WOOD_TIER_ORDER.map((woodTier) =>
@@ -151,11 +270,11 @@ export function staffCraftRecipes ()
151 output: { itemId: staffItemIdForWood(woodTier), quantity: 1 },
270 output: { itemId: staffItemIdForWood(woodTier), quantity: 1 },
152 inputs: [
271 inputs: [
153 { itemId: logItemIdForWood(woodTier), quantity: 1 },
272 { itemId: logItemIdForWood(woodTier), quantity: 1 },
154 { itemId: gemItemId(gemTier), quantity: 1 },
273 { itemId: cutGemItemId(gemTier), quantity: 1 },
155 { itemId: ashItemIdForWood(woodTier), quantity: 1 }
274 { itemId: ashItemIdForWood(woodTier), quantity: 1 }
156 ],
275 ],
157 minSkillLevel: tierMinSkillLevel(woodTier),
276 minSkillLevel: tierMinSkillLevel(woodTier),
158 skillId: "crafting",
277 skillId: SkillId.crafting,
159 xpMaterial: woodTier
278 xpMaterial: woodTier
160 });
279 });
161 });
280 });
shared/definitions/materialTiers.js +10 −3
@@ -135,8 +135,9 @@ export const GEM_TIER_ORDER = Object.freeze([
135 135 /**
136 136 * Gatherable ores / fuels that are not always 1:1 with a gear tier.
137 137 * Tin + copper smelt into bronze; coal fuels steel. Gold and silver have ore +
138 * bars but no tools (jewelry / future recipes). Mine/smelt timing uses
139 * {@link associatedBarTier}. Gemstones map onto the matching metal gate.
138 * bars but no tools (jewelry). Electrum is furnace-only (gold + silver + coal).
139 * Mine/smelt timing uses {@link associatedBarTier}. Gemstones map onto the
140 * matching metal gate.
140 141 */
141 142 export const GatherMaterialId = Object.freeze({
142 143 ...MaterialTier,
@@ -145,7 +146,9 @@ export const GatherMaterialId = Object.freeze({
145 146 copper: "copper",
146 147 coal: "coal",
147 148 silver: "silver",
148 gold: "gold"
149 gold: "gold",
150 /** Smelted only: 1 gold ore + 1 silver ore + 3 coal → electrum bar. */
151 electrum: "electrum"
149 152 });
150 153
151 154 /** Minimum relevant skill level required to equip tools/gear of this tier. */
@@ -159,6 +162,7 @@ export const TIER_MIN_SKILL_LEVEL = Object.freeze({
159 162 [MaterialTier.dragon]: 90,
160 163 [GatherMaterialId.silver]: 10,
161 164 [GatherMaterialId.gold]: 20,
165 [GatherMaterialId.electrum]: 90,
162 166 [GemTier.tourmaline]: 1,
163 167 [GemTier.alexandrite]: 10,
164 168 [GemTier.opal]: 20,
@@ -200,6 +204,7 @@ export const TIER_RANK = Object.freeze({
200 204 [MaterialTier.dragon]: 7,
201 205 [GatherMaterialId.silver]: 2,
202 206 [GatherMaterialId.gold]: 3,
207 [GatherMaterialId.electrum]: 7,
203 208 [GemTier.tourmaline]: 1,
204 209 [GemTier.alexandrite]: 2,
205 210 [GemTier.opal]: 3,
@@ -276,6 +281,7 @@ export const MATERIAL_DISPLAY_NAME = Object.freeze({
276 281 [GatherMaterialId.coal]: "Coal",
277 282 [GatherMaterialId.silver]: "Silver",
278 283 [GatherMaterialId.gold]: "Gold",
284 [GatherMaterialId.electrum]: "Electrum",
279 285 [GemTier.tourmaline]: "Tourmaline",
280 286 [GemTier.alexandrite]: "Alexandrite",
281 287 [GemTier.opal]: "Opal",
@@ -335,6 +341,7 @@ export const MATERIAL_TINT_HEX = Object.freeze({
335 341 [GatherMaterialId.coal]: rgb(45, 45, 48),
336 342 [GatherMaterialId.silver]: rgb(214, 220, 230),
337 343 [GatherMaterialId.gold]: rgb(255, 200, 0),
344 [GatherMaterialId.electrum]: rgb(232, 198, 128),
338 345 [GemTier.tourmaline]: rgb(200, 55, 120),
339 346 [GemTier.alexandrite]: rgb(120, 70, 180),
340 347 [GemTier.opal]: rgb(230, 210, 220),
@@ -135,8 +135,9 @@ export const GEM_TIER_ORDER = Object.freeze([
135/**
135/**
136 * Gatherable ores / fuels that are not always 1:1 with a gear tier.
136 * Gatherable ores / fuels that are not always 1:1 with a gear tier.
137 * Tin + copper smelt into bronze; coal fuels steel. Gold and silver have ore +
137 * Tin + copper smelt into bronze; coal fuels steel. Gold and silver have ore +
138 * bars but no tools (jewelry / future recipes). Mine/smelt timing uses
138 * bars but no tools (jewelry). Electrum is furnace-only (gold + silver + coal).
139 * {@link associatedBarTier}. Gemstones map onto the matching metal gate.
139 * Mine/smelt timing uses {@link associatedBarTier}. Gemstones map onto the
140 * matching metal gate.
140 */
141 */
141export const GatherMaterialId = Object.freeze({
142export const GatherMaterialId = Object.freeze({
142 ...MaterialTier,
143 ...MaterialTier,
@@ -145,7 +146,9 @@ export const GatherMaterialId = Object.freeze({
145 copper: "copper",
146 copper: "copper",
146 coal: "coal",
147 coal: "coal",
147 silver: "silver",
148 silver: "silver",
148 gold: "gold"
149 gold: "gold",
150 /** Smelted only: 1 gold ore + 1 silver ore + 3 coal → electrum bar. */
151 electrum: "electrum"
149});
152});
150
153
151/** Minimum relevant skill level required to equip tools/gear of this tier. */
154/** Minimum relevant skill level required to equip tools/gear of this tier. */
@@ -159,6 +162,7 @@ export const TIER_MIN_SKILL_LEVEL = Object.freeze({
159 [MaterialTier.dragon]: 90,
162 [MaterialTier.dragon]: 90,
160 [GatherMaterialId.silver]: 10,
163 [GatherMaterialId.silver]: 10,
161 [GatherMaterialId.gold]: 20,
164 [GatherMaterialId.gold]: 20,
165 [GatherMaterialId.electrum]: 90,
162 [GemTier.tourmaline]: 1,
166 [GemTier.tourmaline]: 1,
163 [GemTier.alexandrite]: 10,
167 [GemTier.alexandrite]: 10,
164 [GemTier.opal]: 20,
168 [GemTier.opal]: 20,
@@ -200,6 +204,7 @@ export const TIER_RANK = Object.freeze({
200 [MaterialTier.dragon]: 7,
204 [MaterialTier.dragon]: 7,
201 [GatherMaterialId.silver]: 2,
205 [GatherMaterialId.silver]: 2,
202 [GatherMaterialId.gold]: 3,
206 [GatherMaterialId.gold]: 3,
207 [GatherMaterialId.electrum]: 7,
203 [GemTier.tourmaline]: 1,
208 [GemTier.tourmaline]: 1,
204 [GemTier.alexandrite]: 2,
209 [GemTier.alexandrite]: 2,
205 [GemTier.opal]: 3,
210 [GemTier.opal]: 3,
@@ -276,6 +281,7 @@ export const MATERIAL_DISPLAY_NAME = Object.freeze({
276 [GatherMaterialId.coal]: "Coal",
281 [GatherMaterialId.coal]: "Coal",
277 [GatherMaterialId.silver]: "Silver",
282 [GatherMaterialId.silver]: "Silver",
278 [GatherMaterialId.gold]: "Gold",
283 [GatherMaterialId.gold]: "Gold",
284 [GatherMaterialId.electrum]: "Electrum",
279 [GemTier.tourmaline]: "Tourmaline",
285 [GemTier.tourmaline]: "Tourmaline",
280 [GemTier.alexandrite]: "Alexandrite",
286 [GemTier.alexandrite]: "Alexandrite",
281 [GemTier.opal]: "Opal",
287 [GemTier.opal]: "Opal",
@@ -335,6 +341,7 @@ export const MATERIAL_TINT_HEX = Object.freeze({
335 [GatherMaterialId.coal]: rgb(45, 45, 48),
341 [GatherMaterialId.coal]: rgb(45, 45, 48),
336 [GatherMaterialId.silver]: rgb(214, 220, 230),
342 [GatherMaterialId.silver]: rgb(214, 220, 230),
337 [GatherMaterialId.gold]: rgb(255, 200, 0),
343 [GatherMaterialId.gold]: rgb(255, 200, 0),
344 [GatherMaterialId.electrum]: rgb(232, 198, 128),
338 [GemTier.tourmaline]: rgb(200, 55, 120),
345 [GemTier.tourmaline]: rgb(200, 55, 120),
339 [GemTier.alexandrite]: rgb(120, 70, 180),
346 [GemTier.alexandrite]: rgb(120, 70, 180),
340 [GemTier.opal]: rgb(230, 210, 220),
347 [GemTier.opal]: rgb(230, 210, 220),
shared/definitions/metalItems.js +20 −10
@@ -1,13 +1,15 @@
1 1 import { ItemCategory } from "./itemCategories.js";
2 import {
3 MaterialTier,
4 GatherMaterialId
5 } from "./materialTiers.js";
2 import
3 {
4 MaterialTier,
5 GatherMaterialId
6 } from "./materialTiers.js";
6 7 import { CraftingItemId } from "./craftingItems.js";
7 import {
8 ItemFamilyId,
9 buildFamilyDefinitionMap
10 } from "./tierFamilies.js";
8 import
9 {
10 ItemFamilyId,
11 buildFamilyDefinitionMap
12 } from "./tierFamilies.js";
11 13
12 14 /**
13 15 * Metal ores, bars, pickaxes/axes, and coal.
@@ -38,6 +40,7 @@ export const MetalItemId = Object.freeze({
38 40 goldBar: 75,
39 41 silverOre: 76,
40 42 silverBar: 77,
43 electrumBar: 409,
41 44 bronzePickaxeHead: 67,
42 45 ironPickaxeHead: 68,
43 46 steelPickaxeHead: 69,
@@ -92,7 +95,8 @@ export const BAR_ITEM_BY_METAL = Object.freeze({
92 95 const BAR_BY_TIER = Object.freeze({
93 96 ...BAR_ITEM_BY_METAL,
94 97 [GatherMaterialId.gold]: MetalItemId.goldBar,
95 [GatherMaterialId.silver]: MetalItemId.silverBar
98 [GatherMaterialId.silver]: MetalItemId.silverBar,
99 [GatherMaterialId.electrum]: MetalItemId.electrumBar
96 100 });
97 101
98 102 /** Pickaxe head item id by metal tier. */
@@ -149,14 +153,20 @@ export const PLANT_CLIPPERS_ITEM_BY_METAL = Object.freeze({
149 153 });
150 154
151 155 /** Full defs for metal family (merged into ITEM_DEFINITIONS). */
156 const BAR_ITEM_DEFINITIONS = buildFamilyDefinitionMap(ItemFamilyId.bar, BAR_BY_TIER);
157
152 158 export const METAL_ITEM_DEFINITIONS = Object.freeze({
153 159 ...buildFamilyDefinitionMap(ItemFamilyId.ore, ORE_BY_TIER),
154 ...buildFamilyDefinitionMap(ItemFamilyId.bar, BAR_BY_TIER),
160 ...BAR_ITEM_DEFINITIONS,
155 161 ...buildFamilyDefinitionMap(ItemFamilyId.pickaxeHead, PICKAXE_HEAD_ITEM_BY_METAL),
156 162 ...buildFamilyDefinitionMap(ItemFamilyId.axeHead, AXE_HEAD_ITEM_BY_METAL),
157 163 ...buildFamilyDefinitionMap(ItemFamilyId.pickaxe, PICKAXE_ITEM_BY_METAL),
158 164 ...buildFamilyDefinitionMap(ItemFamilyId.axe, AXE_ITEM_BY_METAL),
159 165 ...buildFamilyDefinitionMap(ItemFamilyId.plantClippers, PLANT_CLIPPERS_ITEM_BY_METAL),
166 [MetalItemId.electrumBar]: Object.freeze({
167 ...BAR_ITEM_DEFINITIONS[MetalItemId.electrumBar],
168 description: "A pale gold-silver alloy. Fit for fine jewellery."
169 }),
160 170 [MetalItemId.coal]: Object.freeze({
161 171 itemId: MetalItemId.coal,
162 172 key: "coal",
@@ -1,13 +1,15 @@
1import { ItemCategory } from "./itemCategories.js";
1import { ItemCategory } from "./itemCategories.js";
2import {
2import
3 MaterialTier,
3 {
4 GatherMaterialId
4 MaterialTier,
5} from "./materialTiers.js";
5 GatherMaterialId
6 } from "./materialTiers.js";
6import { CraftingItemId } from "./craftingItems.js";
7import { CraftingItemId } from "./craftingItems.js";
7import {
8import
8 ItemFamilyId,
9 {
9 buildFamilyDefinitionMap
10 ItemFamilyId,
10} from "./tierFamilies.js";
11 buildFamilyDefinitionMap
12 } from "./tierFamilies.js";
11
13
12/**
14/**
13 * Metal ores, bars, pickaxes/axes, and coal.
15 * Metal ores, bars, pickaxes/axes, and coal.
@@ -38,6 +40,7 @@ export const MetalItemId = Object.freeze({
38 goldBar: 75,
40 goldBar: 75,
39 silverOre: 76,
41 silverOre: 76,
40 silverBar: 77,
42 silverBar: 77,
43 electrumBar: 409,
41 bronzePickaxeHead: 67,
44 bronzePickaxeHead: 67,
42 ironPickaxeHead: 68,
45 ironPickaxeHead: 68,
43 steelPickaxeHead: 69,
46 steelPickaxeHead: 69,
@@ -92,7 +95,8 @@ export const BAR_ITEM_BY_METAL = Object.freeze({
92const BAR_BY_TIER = Object.freeze({
95const BAR_BY_TIER = Object.freeze({
93 ...BAR_ITEM_BY_METAL,
96 ...BAR_ITEM_BY_METAL,
94 [GatherMaterialId.gold]: MetalItemId.goldBar,
97 [GatherMaterialId.gold]: MetalItemId.goldBar,
95 [GatherMaterialId.silver]: MetalItemId.silverBar
98 [GatherMaterialId.silver]: MetalItemId.silverBar,
99 [GatherMaterialId.electrum]: MetalItemId.electrumBar
96});
100});
97
101
98/** Pickaxe head item id by metal tier. */
102/** Pickaxe head item id by metal tier. */
@@ -149,14 +153,20 @@ export const PLANT_CLIPPERS_ITEM_BY_METAL = Object.freeze({
149});
153});
150
154
151/** Full defs for metal family (merged into ITEM_DEFINITIONS). */
155/** Full defs for metal family (merged into ITEM_DEFINITIONS). */
156const BAR_ITEM_DEFINITIONS = buildFamilyDefinitionMap(ItemFamilyId.bar, BAR_BY_TIER);
157
152export const METAL_ITEM_DEFINITIONS = Object.freeze({
158export const METAL_ITEM_DEFINITIONS = Object.freeze({
153 ...buildFamilyDefinitionMap(ItemFamilyId.ore, ORE_BY_TIER),
159 ...buildFamilyDefinitionMap(ItemFamilyId.ore, ORE_BY_TIER),
154 ...buildFamilyDefinitionMap(ItemFamilyId.bar, BAR_BY_TIER),
160 ...BAR_ITEM_DEFINITIONS,
155 ...buildFamilyDefinitionMap(ItemFamilyId.pickaxeHead, PICKAXE_HEAD_ITEM_BY_METAL),
161 ...buildFamilyDefinitionMap(ItemFamilyId.pickaxeHead, PICKAXE_HEAD_ITEM_BY_METAL),
156 ...buildFamilyDefinitionMap(ItemFamilyId.axeHead, AXE_HEAD_ITEM_BY_METAL),
162 ...buildFamilyDefinitionMap(ItemFamilyId.axeHead, AXE_HEAD_ITEM_BY_METAL),
157 ...buildFamilyDefinitionMap(ItemFamilyId.pickaxe, PICKAXE_ITEM_BY_METAL),
163 ...buildFamilyDefinitionMap(ItemFamilyId.pickaxe, PICKAXE_ITEM_BY_METAL),
158 ...buildFamilyDefinitionMap(ItemFamilyId.axe, AXE_ITEM_BY_METAL),
164 ...buildFamilyDefinitionMap(ItemFamilyId.axe, AXE_ITEM_BY_METAL),
159 ...buildFamilyDefinitionMap(ItemFamilyId.plantClippers, PLANT_CLIPPERS_ITEM_BY_METAL),
165 ...buildFamilyDefinitionMap(ItemFamilyId.plantClippers, PLANT_CLIPPERS_ITEM_BY_METAL),
166 [MetalItemId.electrumBar]: Object.freeze({
167 ...BAR_ITEM_DEFINITIONS[MetalItemId.electrumBar],
168 description: "A pale gold-silver alloy. Fit for fine jewellery."
169 }),
160 [MetalItemId.coal]: Object.freeze({
170 [MetalItemId.coal]: Object.freeze({
161 itemId: MetalItemId.coal,
171 itemId: MetalItemId.coal,
162 key: "coal",
172 key: "coal",
shared/definitions/mobs.js +11 −2
@@ -287,7 +287,7 @@ export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
287 287 ? centralExchangeStaffCount()
288 288 : (bodyNpc ? 1 : 3),
289 289 /** Seconds after death before this spawner may refill that slot (0 = next spawner tick). */
290 respawnDelaySeconds: 0,
290 respawnDelaySeconds: 25,
291 291 spawnRangeTiles: bodyNpc ? 1 : 4,
292 292 maxWanderRangeTiles: bodyNpc ? 1 : 8,
293 293 level: townGuard ? 30 : 1,
@@ -515,7 +515,16 @@ export function normalizeSpawnerConfig (config, spawnerId = "spawner")
515 515 : Math.max(1, Math.min(20, Number(merged.maxAlive) || base.maxAlive)),
516 516 respawnDelaySeconds: Math.max(
517 517 0,
518 Math.min(86_400, Math.floor(Number(merged.respawnDelaySeconds) || 0))
518 Math.min(
519 86_400,
520 Math.floor(
521 Number(
522 merged.respawnDelaySeconds != null && merged.respawnDelaySeconds !== ""
523 ? merged.respawnDelaySeconds
524 : base.respawnDelaySeconds
525 ) || 0
526 )
527 )
519 528 ),
520 529 spawnRangeTiles,
521 530 maxWanderRangeTiles,
@@ -287,7 +287,7 @@ export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
287 ? centralExchangeStaffCount()
287 ? centralExchangeStaffCount()
288 : (bodyNpc ? 1 : 3),
288 : (bodyNpc ? 1 : 3),
289 /** Seconds after death before this spawner may refill that slot (0 = next spawner tick). */
289 /** Seconds after death before this spawner may refill that slot (0 = next spawner tick). */
290 respawnDelaySeconds: 0,
290 respawnDelaySeconds: 25,
291 spawnRangeTiles: bodyNpc ? 1 : 4,
291 spawnRangeTiles: bodyNpc ? 1 : 4,
292 maxWanderRangeTiles: bodyNpc ? 1 : 8,
292 maxWanderRangeTiles: bodyNpc ? 1 : 8,
293 level: townGuard ? 30 : 1,
293 level: townGuard ? 30 : 1,
@@ -515,7 +515,16 @@ export function normalizeSpawnerConfig (config, spawnerId = "spawner")
515 : Math.max(1, Math.min(20, Number(merged.maxAlive) || base.maxAlive)),
515 : Math.max(1, Math.min(20, Number(merged.maxAlive) || base.maxAlive)),
516 respawnDelaySeconds: Math.max(
516 respawnDelaySeconds: Math.max(
517 0,
517 0,
518 Math.min(86_400, Math.floor(Number(merged.respawnDelaySeconds) || 0))
518 Math.min(
519 86_400,
520 Math.floor(
521 Number(
522 merged.respawnDelaySeconds != null && merged.respawnDelaySeconds !== ""
523 ? merged.respawnDelaySeconds
524 : base.respawnDelaySeconds
525 ) || 0
526 )
527 )
519 ),
528 ),
520 spawnRangeTiles,
529 spawnRangeTiles,
521 maxWanderRangeTiles,
530 maxWanderRangeTiles,
shared/definitions/skills.js +3 −0
@@ -16,6 +16,7 @@ export const SkillId = Object.freeze({
16 16 mining: "mining",
17 17 fishing: "fishing",
18 18 smithing: "smithing",
19 jewelering: "jewelering",
19 20 crafting: "crafting",
20 21 leatherworking: "leatherworking",
21 22 tailoring: "tailoring",
@@ -44,6 +45,7 @@ export const ALL_SKILL_IDS = Object.freeze([
44 45 SkillId.mining,
45 46 SkillId.fishing,
46 47 SkillId.smithing,
48 SkillId.jewelering,
47 49 SkillId.crafting,
48 50 SkillId.leatherworking,
49 51 SkillId.tailoring,
@@ -71,6 +73,7 @@ export const SKILL_DEFINITIONS = Object.freeze({
71 73 [SkillId.mining]: Object.freeze({ skillId: SkillId.mining, displayName: "Mining" }),
72 74 [SkillId.fishing]: Object.freeze({ skillId: SkillId.fishing, displayName: "Fishing" }),
73 75 [SkillId.smithing]: Object.freeze({ skillId: SkillId.smithing, displayName: "Smithing" }),
76 [SkillId.jewelering]: Object.freeze({ skillId: SkillId.jewelering, displayName: "Jewelering" }),
74 77 [SkillId.crafting]: Object.freeze({ skillId: SkillId.crafting, displayName: "Crafting" }),
75 78 [SkillId.leatherworking]: Object.freeze({ skillId: SkillId.leatherworking, displayName: "Leatherworking" }),
76 79 [SkillId.tailoring]: Object.freeze({ skillId: SkillId.tailoring, displayName: "Tailoring" }),
@@ -16,6 +16,7 @@ export const SkillId = Object.freeze({
16 mining: "mining",
16 mining: "mining",
17 fishing: "fishing",
17 fishing: "fishing",
18 smithing: "smithing",
18 smithing: "smithing",
19 jewelering: "jewelering",
19 crafting: "crafting",
20 crafting: "crafting",
20 leatherworking: "leatherworking",
21 leatherworking: "leatherworking",
21 tailoring: "tailoring",
22 tailoring: "tailoring",
@@ -44,6 +45,7 @@ export const ALL_SKILL_IDS = Object.freeze([
44 SkillId.mining,
45 SkillId.mining,
45 SkillId.fishing,
46 SkillId.fishing,
46 SkillId.smithing,
47 SkillId.smithing,
48 SkillId.jewelering,
47 SkillId.crafting,
49 SkillId.crafting,
48 SkillId.leatherworking,
50 SkillId.leatherworking,
49 SkillId.tailoring,
51 SkillId.tailoring,
@@ -71,6 +73,7 @@ export const SKILL_DEFINITIONS = Object.freeze({
71 [SkillId.mining]: Object.freeze({ skillId: SkillId.mining, displayName: "Mining" }),
73 [SkillId.mining]: Object.freeze({ skillId: SkillId.mining, displayName: "Mining" }),
72 [SkillId.fishing]: Object.freeze({ skillId: SkillId.fishing, displayName: "Fishing" }),
74 [SkillId.fishing]: Object.freeze({ skillId: SkillId.fishing, displayName: "Fishing" }),
73 [SkillId.smithing]: Object.freeze({ skillId: SkillId.smithing, displayName: "Smithing" }),
75 [SkillId.smithing]: Object.freeze({ skillId: SkillId.smithing, displayName: "Smithing" }),
76 [SkillId.jewelering]: Object.freeze({ skillId: SkillId.jewelering, displayName: "Jewelering" }),
74 [SkillId.crafting]: Object.freeze({ skillId: SkillId.crafting, displayName: "Crafting" }),
77 [SkillId.crafting]: Object.freeze({ skillId: SkillId.crafting, displayName: "Crafting" }),
75 [SkillId.leatherworking]: Object.freeze({ skillId: SkillId.leatherworking, displayName: "Leatherworking" }),
78 [SkillId.leatherworking]: Object.freeze({ skillId: SkillId.leatherworking, displayName: "Leatherworking" }),
76 [SkillId.tailoring]: Object.freeze({ skillId: SkillId.tailoring, displayName: "Tailoring" }),
79 [SkillId.tailoring]: Object.freeze({ skillId: SkillId.tailoring, displayName: "Tailoring" }),
shared/definitions/tiles.js +15 −1
@@ -71,7 +71,8 @@ export const BlockType = Object.freeze({
71 71 doorway: 30,
72 72 campfire: 31,
73 73 oven: 32,
74 fishingSpot: 33
74 fishingSpot: 33,
75 jeweleringStation: 34
75 76 });
76 77
77 78 export const GROUND_DEFINITIONS = Object.freeze({
@@ -319,6 +320,19 @@ export const BLOCK_DEFINITIONS = Object.freeze({
319 320 craftingStationId: "anvil",
320 321 outdoor: false
321 322 }),
323 [BlockType.jeweleringStation]: Object.freeze({
324 id: BlockType.jeweleringStation,
325 key: "jewelering-station",
326 displayName: "Jewelering station",
327 passable: false,
328 blocksLight: false,
329 lightRangeTiles: 0,
330 frames: 1,
331 framesPerRow: 1,
332 animationSpeed: 0,
333 craftingStationId: "jewelering-station",
334 outdoor: false
335 }),
322 336 [BlockType.woodworkingBench]: Object.freeze({
323 337 id: BlockType.woodworkingBench,
324 338 key: "woodworking-bench",
@@ -71,7 +71,8 @@ export const BlockType = Object.freeze({
71 doorway: 30,
71 doorway: 30,
72 campfire: 31,
72 campfire: 31,
73 oven: 32,
73 oven: 32,
74 fishingSpot: 33
74 fishingSpot: 33,
75 jeweleringStation: 34
75});
76});
76
77
77export const GROUND_DEFINITIONS = Object.freeze({
78export const GROUND_DEFINITIONS = Object.freeze({
@@ -319,6 +320,19 @@ export const BLOCK_DEFINITIONS = Object.freeze({
319 craftingStationId: "anvil",
320 craftingStationId: "anvil",
320 outdoor: false
321 outdoor: false
321 }),
322 }),
323 [BlockType.jeweleringStation]: Object.freeze({
324 id: BlockType.jeweleringStation,
325 key: "jewelering-station",
326 displayName: "Jewelering station",
327 passable: false,
328 blocksLight: false,
329 lightRangeTiles: 0,
330 frames: 1,
331 framesPerRow: 1,
332 animationSpeed: 0,
333 craftingStationId: "jewelering-station",
334 outdoor: false
335 }),
322 [BlockType.woodworkingBench]: Object.freeze({
336 [BlockType.woodworkingBench]: Object.freeze({
323 id: BlockType.woodworkingBench,
337 id: BlockType.woodworkingBench,
324 key: "woodworking-bench",
338 key: "woodworking-bench",
shared/items/origin.js +2 −0
@@ -34,6 +34,7 @@ export const GatherOriginVerb = Object.freeze({
34 34 export const CraftOriginVerb = Object.freeze({
35 35 forged: "Forged",
36 36 smithed: "Smithed",
37 cut: "Cut",
37 38 carved: "Carved",
38 39 assembled: "Assembled",
39 40 made: "Made",
@@ -47,6 +48,7 @@ export const CraftOriginVerb = Object.freeze({
47 48 export const CRAFT_ORIGIN_VERB_BY_STATION = Object.freeze({
48 49 furnace: CraftOriginVerb.forged,
49 50 anvil: CraftOriginVerb.smithed,
51 "jewelering-station": CraftOriginVerb.cut,
50 52 "woodworking-bench": CraftOriginVerb.carved,
51 53 "crafting-bench": CraftOriginVerb.assembled,
52 54 "spinning-wheel": CraftOriginVerb.made,
@@ -34,6 +34,7 @@ export const GatherOriginVerb = Object.freeze({
34export const CraftOriginVerb = Object.freeze({
34export const CraftOriginVerb = Object.freeze({
35 forged: "Forged",
35 forged: "Forged",
36 smithed: "Smithed",
36 smithed: "Smithed",
37 cut: "Cut",
37 carved: "Carved",
38 carved: "Carved",
38 assembled: "Assembled",
39 assembled: "Assembled",
39 made: "Made",
40 made: "Made",
@@ -47,6 +48,7 @@ export const CraftOriginVerb = Object.freeze({
47export const CRAFT_ORIGIN_VERB_BY_STATION = Object.freeze({
48export const CRAFT_ORIGIN_VERB_BY_STATION = Object.freeze({
48 furnace: CraftOriginVerb.forged,
49 furnace: CraftOriginVerb.forged,
49 anvil: CraftOriginVerb.smithed,
50 anvil: CraftOriginVerb.smithed,
51 "jewelering-station": CraftOriginVerb.cut,
50 "woodworking-bench": CraftOriginVerb.carved,
52 "woodworking-bench": CraftOriginVerb.carved,
51 "crafting-bench": CraftOriginVerb.assembled,
53 "crafting-bench": CraftOriginVerb.assembled,
52 "spinning-wheel": CraftOriginVerb.made,
54 "spinning-wheel": CraftOriginVerb.made,
shared/protocol/constants.js +1 −0
@@ -117,6 +117,7 @@ export const MessageType = Object.freeze({
117 117 friendDecline: "FRIEND_DECLINE",
118 118 friendRemove: "FRIEND_REMOVE",
119 119 friends: "FRIENDS",
120 entitySkull: "ENTITY_SKULL",
120 121 chatSay: "CHAT_SAY",
121 122 chatBubble: "CHAT_BUBBLE",
122 123 dropItem: "DROP_ITEM",
@@ -117,6 +117,7 @@ export const MessageType = Object.freeze({
117 friendDecline: "FRIEND_DECLINE",
117 friendDecline: "FRIEND_DECLINE",
118 friendRemove: "FRIEND_REMOVE",
118 friendRemove: "FRIEND_REMOVE",
119 friends: "FRIENDS",
119 friends: "FRIENDS",
120 entitySkull: "ENTITY_SKULL",
120 chatSay: "CHAT_SAY",
121 chatSay: "CHAT_SAY",
121 chatBubble: "CHAT_BUBBLE",
122 chatBubble: "CHAT_BUBBLE",
122 dropItem: "DROP_ITEM",
123 dropItem: "DROP_ITEM",