Add spellcasting, leather crafting, and combat approach polish.
Spells with favourites bar, tile/entity targeting, Light and Spark, server-authoritative casts with auto-walk into range, and crafting stations/tables that no longer block ranged or magic line of sight. Skill XP growth uses 10% per level instead of doubling; leather legwear, NPC auto-equip, and assorted test fixes included.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
@@ -0,0 +1,4 @@
1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
2
<rect width="32" height="32" rx="6" fill="#c8a840"/>
3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">LT</text>
4
</svg>
@@ -0,0 +1,4 @@1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">2
<rect width="32" height="32" rx="6" fill="#c8a840"/>3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">LT</text>4
</svg>@@ -0,0 +1,4 @@
1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
2
<rect width="32" height="32" rx="6" fill="#e06030"/>
3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">SP</text>
4
</svg>
@@ -0,0 +1,4 @@1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">2
<rect width="32" height="32" rx="6" fill="#e06030"/>3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">SP</text>4
</svg>@@ -12,6 +12,7 @@
12
12
<span>Zoom: <strong id="zoom">2.00×</strong> (scroll)</span>
13
13
<button id="friends-toggle" type="button">Friends</button>
14
14
<button id="skills-toggle" type="button">Skills</button>
15
<button id="spells-toggle" type="button">Spells</button>
15
16
<button id="bag-toggle" type="button">Bag</button>
16
17
<button id="leave" type="button">Leave world</button>
17
18
</div>
@@ -50,11 +51,7 @@
50
51
<p id="bag-coins" hidden>0 coins</p>
51
52
<div id="equip-grid" class="item-grid equip"></div>
52
53
<div id="bag-grid" class="item-grid"></div>
53
<p id="bag-hint" class="hint">Left-click to select. Right-click an item for Send, Equip, Drop, or Write letter.</p>
54
<div class="bag-actions">
55
<button id="bag-drop" type="button">Drop</button>
56
<button id="bag-equip" type="button">Equip</button>
57
</div>
54
<p id="bag-hint" class="hint">Left-click to select. Right-click for other options.</p>
58
55
</aside>
59
56
<aside id="bank-panel" hidden>
60
57
<header>
@@ -94,6 +91,15 @@
94
91
<h2>Skills</h2>
95
92
<div id="skills-list" class="skills-grid"></div>
96
93
</aside>
94
<aside id="spells-panel" hidden>
95
<h2>Spells</h2>
96
<label class="spell-autocast-row">
97
<input id="spell-autocast-toggle" type="checkbox">
98
Auto-cast (repeat on target)
99
</label>
100
<div id="spells-list" class="spells-grid"></div>
101
</aside>
102
<div id="spell-favorites-bar" hidden></div>
97
103
98
104
<div id="send-backdrop" class="modal-backdrop" hidden></div>
99
105
<aside id="send-panel" hidden>
@@ -12,6 +12,7 @@12
<span>Zoom: <strong id="zoom">2.00×</strong> (scroll)</span>12
<span>Zoom: <strong id="zoom">2.00×</strong> (scroll)</span>13
<button id="friends-toggle" type="button">Friends</button>13
<button id="friends-toggle" type="button">Friends</button>14
<button id="skills-toggle" type="button">Skills</button>14
<button id="skills-toggle" type="button">Skills</button>15
<button id="spells-toggle" type="button">Spells</button>15
<button id="bag-toggle" type="button">Bag</button>16
<button id="bag-toggle" type="button">Bag</button>16
<button id="leave" type="button">Leave world</button>17
<button id="leave" type="button">Leave world</button>17
</div>18
</div>@@ -50,11 +51,7 @@50
<p id="bag-coins" hidden>0 coins</p>51
<p id="bag-coins" hidden>0 coins</p>51
<div id="equip-grid" class="item-grid equip"></div>52
<div id="equip-grid" class="item-grid equip"></div>52
<div id="bag-grid" class="item-grid"></div>53
<div id="bag-grid" class="item-grid"></div>53
<p id="bag-hint" class="hint">Left-click to select. Right-click an item for Send, Equip, Drop, or Write letter.</p>54
<p id="bag-hint" class="hint">Left-click to select. Right-click for other options.</p>54
<div class="bag-actions">55
<button id="bag-drop" type="button">Drop</button>56
<button id="bag-equip" type="button">Equip</button>57
</div>58
</aside>55
</aside>59
<aside id="bank-panel" hidden>56
<aside id="bank-panel" hidden>60
<header>57
<header>@@ -94,6 +91,15 @@94
<h2>Skills</h2>91
<h2>Skills</h2>95
<div id="skills-list" class="skills-grid"></div>92
<div id="skills-list" class="skills-grid"></div>96
</aside>93
</aside>94
<aside id="spells-panel" hidden>95
<h2>Spells</h2>96
<label class="spell-autocast-row">97
<input id="spell-autocast-toggle" type="checkbox">98
Auto-cast (repeat on target)99
</label>100
<div id="spells-list" class="spells-grid"></div>101
</aside>102
<div id="spell-favorites-bar" hidden></div>97
103
98
<div id="send-backdrop" class="modal-backdrop" hidden></div>104
<div id="send-backdrop" class="modal-backdrop" hidden></div>99
<aside id="send-panel" hidden>105
<aside id="send-panel" hidden>@@ -0,0 +1,153 @@
1
/**
2
* Derive cloth shorts/trousers and leather-shoe sprites from greaves/boots overlays.
3
* Shorts: greaves with the bottom few rows cleared.
4
*/
5
import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
import { deflateSync, inflateSync } from "node:zlib";
7
import { dirname, join } from "node:path";
8
import { fileURLToPath } from "node:url";
9
10
const SIZE = 16;
11
const SHORTS_TRIM_ROWS = 4;
12
const root = join(dirname(fileURLToPath(import.meta.url)), "../assets/items");
13
const armour = join(root, "armour");
14
const clothing = join(root, "clothing");
15
16
function crcTable ()
17
{
18
const table = new Uint32Array(256);
19
for (let n = 0; n < 256; n++)
20
{
21
let c = n;
22
for (let k = 0; k < 8; k++)
23
{ c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }
24
table[n] = c >>> 0;
25
}
26
return table;
27
}
28
29
const CRC_TABLE = crcTable();
30
31
function crc32 (buf)
32
{
33
let c = 0xffffffff;
34
for (let i = 0; i < buf.length; i++)
35
{ c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }
36
return (c ^ 0xffffffff) >>> 0;
37
}
38
39
function chunk (type, data)
40
{
41
const len = Buffer.alloc(4);
42
len.writeUInt32BE(data.length);
43
const typeBuf = Buffer.from(type, "ascii");
44
const crcBuf = Buffer.alloc(4);
45
crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));
46
return Buffer.concat([len, typeBuf, data, crcBuf]);
47
}
48
49
function encodePng (rgba, width = SIZE, height = SIZE)
50
{
51
const raw = Buffer.alloc((width * 4 + 1) * height);
52
for (let y = 0; y < height; y++)
53
{
54
const row = y * (width * 4 + 1);
55
raw[row] = 0;
56
for (let x = 0; x < width; x++)
57
{
58
const i = (y * width + x) * 4;
59
const o = row + 1 + x * 4;
60
raw[o] = rgba[i];
61
raw[o + 1] = rgba[i + 1];
62
raw[o + 2] = rgba[i + 2];
63
raw[o + 3] = rgba[i + 3];
64
}
65
}
66
const ihdr = Buffer.alloc(13);
67
ihdr.writeUInt32BE(width, 0);
68
ihdr.writeUInt32BE(height, 4);
69
ihdr[8] = 8;
70
ihdr[9] = 6;
71
return Buffer.concat([
72
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
73
chunk("IHDR", ihdr),
74
chunk("IDAT", deflateSync(raw, { level: 9 })),
75
chunk("IEND", Buffer.alloc(0))
76
]);
77
}
78
79
function decodePngRgba (buf)
80
{
81
let off = 8;
82
let w = 0;
83
let h = 0;
84
const idat = [];
85
while (off < buf.length)
86
{
87
const len = buf.readUInt32BE(off);
88
const type = buf.slice(off + 4, off + 8).toString("ascii");
89
const data = buf.slice(off + 8, off + 8 + len);
90
if (type === "IHDR")
91
{
92
w = data.readUInt32BE(0);
93
h = data.readUInt32BE(4);
94
}
95
else if (type === "IDAT")
96
{ idat.push(data); }
97
else if (type === "IEND")
98
{ break; }
99
off += 12 + len;
100
}
101
const raw = inflateSync(Buffer.concat(idat));
102
const stride = 1 + w * 4;
103
const rgba = new Uint8Array(w * h * 4);
104
for (let y = 0; y < h; y++)
105
{
106
for (let x = 0; x < w; x++)
107
{
108
const i = y * stride + 1 + x * 4;
109
const o = (y * w + x) * 4;
110
rgba[o] = raw[i];
111
rgba[o + 1] = raw[i + 1];
112
rgba[o + 2] = raw[i + 2];
113
rgba[o + 3] = raw[i + 3];
114
}
115
}
116
return { width: w, height: h, rgba };
117
}
118
119
function writePair (name, rgba)
120
{
121
mkdirSync(clothing, { recursive: true });
122
writeFileSync(join(clothing, `${name}.png`), encodePng(rgba));
123
writeFileSync(join(clothing, `${name}-equip.png`), encodePng(rgba));
124
}
125
126
function trimBottomRows (rgba, width, height, rows)
127
{
128
const next = new Uint8Array(rgba);
129
for (let y = height - rows; y < height; y++)
130
{
131
for (let x = 0; x < width; x++)
132
{
133
const o = (y * width + x) * 4;
134
next[o] = 0;
135
next[o + 1] = 0;
136
next[o + 2] = 0;
137
next[o + 3] = 0;
138
}
139
}
140
return next;
141
}
142
143
const greaves = decodePngRgba(readFileSync(join(armour, "greaves.png")));
144
const boots = decodePngRgba(readFileSync(join(armour, "boots.png")));
145
146
writePair("trousers", greaves.rgba);
147
writePair("shorts", trimBottomRows(greaves.rgba, greaves.width, greaves.height, SHORTS_TRIM_ROWS));
148
writePair("leather-shoes", boots.rgba);
149
150
mkdirSync(join(root, "leather"), { recursive: true });
151
writeFileSync(join(root, "leather", "leather.png"), encodePng(greaves.rgba));
152
153
console.log("Wrote shorts, trousers, leather-shoes, and leather icon sprites");
@@ -0,0 +1,153 @@1
/**2
* Derive cloth shorts/trousers and leather-shoe sprites from greaves/boots overlays.3
* Shorts: greaves with the bottom few rows cleared.4
*/5
import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";6
import { deflateSync, inflateSync } from "node:zlib";7
import { dirname, join } from "node:path";8
import { fileURLToPath } from "node:url";9
10
const SIZE = 16;11
const SHORTS_TRIM_ROWS = 4;12
const root = join(dirname(fileURLToPath(import.meta.url)), "../assets/items");13
const armour = join(root, "armour");14
const clothing = join(root, "clothing");15
16
function crcTable ()17
{18
const table = new Uint32Array(256);19
for (let n = 0; n < 256; n++)20
{21
let c = n;22
for (let k = 0; k < 8; k++)23
{ c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }24
table[n] = c >>> 0;25
}26
return table;27
}28
29
const CRC_TABLE = crcTable();30
31
function crc32 (buf)32
{33
let c = 0xffffffff;34
for (let i = 0; i < buf.length; i++)35
{ c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }36
return (c ^ 0xffffffff) >>> 0;37
}38
39
function chunk (type, data)40
{41
const len = Buffer.alloc(4);42
len.writeUInt32BE(data.length);43
const typeBuf = Buffer.from(type, "ascii");44
const crcBuf = Buffer.alloc(4);45
crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));46
return Buffer.concat([len, typeBuf, data, crcBuf]);47
}48
49
function encodePng (rgba, width = SIZE, height = SIZE)50
{51
const raw = Buffer.alloc((width * 4 + 1) * height);52
for (let y = 0; y < height; y++)53
{54
const row = y * (width * 4 + 1);55
raw[row] = 0;56
for (let x = 0; x < width; x++)57
{58
const i = (y * width + x) * 4;59
const o = row + 1 + x * 4;60
raw[o] = rgba[i];61
raw[o + 1] = rgba[i + 1];62
raw[o + 2] = rgba[i + 2];63
raw[o + 3] = rgba[i + 3];64
}65
}66
const ihdr = Buffer.alloc(13);67
ihdr.writeUInt32BE(width, 0);68
ihdr.writeUInt32BE(height, 4);69
ihdr[8] = 8;70
ihdr[9] = 6;71
return Buffer.concat([72
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),73
chunk("IHDR", ihdr),74
chunk("IDAT", deflateSync(raw, { level: 9 })),75
chunk("IEND", Buffer.alloc(0))76
]);77
}78
79
function decodePngRgba (buf)80
{81
let off = 8;82
let w = 0;83
let h = 0;84
const idat = [];85
while (off < buf.length)86
{87
const len = buf.readUInt32BE(off);88
const type = buf.slice(off + 4, off + 8).toString("ascii");89
const data = buf.slice(off + 8, off + 8 + len);90
if (type === "IHDR")91
{92
w = data.readUInt32BE(0);93
h = data.readUInt32BE(4);94
}95
else if (type === "IDAT")96
{ idat.push(data); }97
else if (type === "IEND")98
{ break; }99
off += 12 + len;100
}101
const raw = inflateSync(Buffer.concat(idat));102
const stride = 1 + w * 4;103
const rgba = new Uint8Array(w * h * 4);104
for (let y = 0; y < h; y++)105
{106
for (let x = 0; x < w; x++)107
{108
const i = y * stride + 1 + x * 4;109
const o = (y * w + x) * 4;110
rgba[o] = raw[i];111
rgba[o + 1] = raw[i + 1];112
rgba[o + 2] = raw[i + 2];113
rgba[o + 3] = raw[i + 3];114
}115
}116
return { width: w, height: h, rgba };117
}118
119
function writePair (name, rgba)120
{121
mkdirSync(clothing, { recursive: true });122
writeFileSync(join(clothing, `${name}.png`), encodePng(rgba));123
writeFileSync(join(clothing, `${name}-equip.png`), encodePng(rgba));124
}125
126
function trimBottomRows (rgba, width, height, rows)127
{128
const next = new Uint8Array(rgba);129
for (let y = height - rows; y < height; y++)130
{131
for (let x = 0; x < width; x++)132
{133
const o = (y * width + x) * 4;134
next[o] = 0;135
next[o + 1] = 0;136
next[o + 2] = 0;137
next[o + 3] = 0;138
}139
}140
return next;141
}142
143
const greaves = decodePngRgba(readFileSync(join(armour, "greaves.png")));144
const boots = decodePngRgba(readFileSync(join(armour, "boots.png")));145
146
writePair("trousers", greaves.rgba);147
writePair("shorts", trimBottomRows(greaves.rgba, greaves.width, greaves.height, SHORTS_TRIM_ROWS));148
writePair("leather-shoes", boots.rgba);149
150
mkdirSync(join(root, "leather"), { recursive: true });151
writeFileSync(join(root, "leather", "leather.png"), encodePng(greaves.rgba));152
153
console.log("Wrote shorts, trousers, leather-shoes, and leather icon sprites");@@ -0,0 +1,74 @@
1
import { mkdirSync, writeFileSync } from "node:fs";
2
import { deflateSync } from "node:zlib";
3
4
const spells = [
5
{ id: "spell-light", rgb: [255, 248, 192] },
6
{ id: "spell-spark", rgb: [255, 144, 64] }
7
];
8
9
mkdirSync(new URL("../assets/fx/projectile/", import.meta.url), { recursive: true });
10
11
for (const spell of spells)
12
{
13
for (let frame = 0; frame < 3; frame++)
14
{
15
const png = buildPng5(spell.rgb);
16
writeFileSync(
17
new URL(`../assets/fx/projectile/${spell.id}-${frame}.png`, import.meta.url),
18
png
19
);
20
}
21
}
22
23
function buildPng5 ([r, g, b])
24
{
25
const row = Buffer.alloc(1 + 5 * 4);
26
row[0] = 0;
27
for (let x = 0; x < 5; x++)
28
{
29
const i = 1 + x * 4;
30
row[i] = r;
31
row[i + 1] = g;
32
row[i + 2] = b;
33
row[i + 3] = x === 0 || x === 4 ? 0 : 255;
34
}
35
const raw = Buffer.concat(Array.from({ length: 5 }, () => row));
36
return encodePng(5, 5, deflateSync(raw));
37
}
38
39
function encodePng (w, h, idat)
40
{
41
const signature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
42
const ihdr = chunk("IHDR", (() =>
43
{
44
const buf = Buffer.alloc(13);
45
buf.writeUInt32BE(w, 0);
46
buf.writeUInt32BE(h, 4);
47
buf[8] = 8; buf[9] = 6;
48
return buf;
49
})());
50
return Buffer.concat([signature, ihdr, chunk("IDAT", idat), chunk("IEND", Buffer.alloc(0))]);
51
}
52
53
function chunk (type, data)
54
{
55
const len = Buffer.alloc(4);
56
len.writeUInt32BE(data.length, 0);
57
const t = Buffer.from(type);
58
const crc = crc32(Buffer.concat([t, data]));
59
const c = Buffer.alloc(4);
60
c.writeUInt32BE(crc >>> 0, 0);
61
return Buffer.concat([len, t, data, c]);
62
}
63
64
function crc32 (buf)
65
{
66
let c = ~0;
67
for (let i = 0; i < buf.length; i++)
68
{
69
c ^= buf[i];
70
for (let k = 0; k < 8; k++)
71
{ c = (c >>> 1) ^ (c & 1 ? 0xedb88320 : 0); }
72
}
73
return ~c;
74
}
@@ -0,0 +1,74 @@1
import { mkdirSync, writeFileSync } from "node:fs";2
import { deflateSync } from "node:zlib";3
4
const spells = [5
{ id: "spell-light", rgb: [255, 248, 192] },6
{ id: "spell-spark", rgb: [255, 144, 64] }7
];8
9
mkdirSync(new URL("../assets/fx/projectile/", import.meta.url), { recursive: true });10
11
for (const spell of spells)12
{13
for (let frame = 0; frame < 3; frame++)14
{15
const png = buildPng5(spell.rgb);16
writeFileSync(17
new URL(`../assets/fx/projectile/${spell.id}-${frame}.png`, import.meta.url),18
png19
);20
}21
}22
23
function buildPng5 ([r, g, b])24
{25
const row = Buffer.alloc(1 + 5 * 4);26
row[0] = 0;27
for (let x = 0; x < 5; x++)28
{29
const i = 1 + x * 4;30
row[i] = r;31
row[i + 1] = g;32
row[i + 2] = b;33
row[i + 3] = x === 0 || x === 4 ? 0 : 255;34
}35
const raw = Buffer.concat(Array.from({ length: 5 }, () => row));36
return encodePng(5, 5, deflateSync(raw));37
}38
39
function encodePng (w, h, idat)40
{41
const signature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);42
const ihdr = chunk("IHDR", (() =>43
{44
const buf = Buffer.alloc(13);45
buf.writeUInt32BE(w, 0);46
buf.writeUInt32BE(h, 4);47
buf[8] = 8; buf[9] = 6;48
return buf;49
})());50
return Buffer.concat([signature, ihdr, chunk("IDAT", idat), chunk("IEND", Buffer.alloc(0))]);51
}52
53
function chunk (type, data)54
{55
const len = Buffer.alloc(4);56
len.writeUInt32BE(data.length, 0);57
const t = Buffer.from(type);58
const crc = crc32(Buffer.concat([t, data]));59
const c = Buffer.alloc(4);60
c.writeUInt32BE(crc >>> 0, 0);61
return Buffer.concat([len, t, data, c]);62
}63
64
function crc32 (buf)65
{66
let c = ~0;67
for (let i = 0; i < buf.length; i++)68
{69
c ^= buf[i];70
for (let k = 0; k < 8; k++)71
{ c = (c >>> 1) ^ (c & 1 ? 0xedb88320 : 0); }72
}73
return ~c;74
}@@ -74,18 +74,6 @@ export function initInventory ({
74
74
{
75
75
bagPanel.hidden = !bagPanel.hidden;
76
76
});
77
document.getElementById("bag-drop").addEventListener("click", () =>
78
{
79
if (selected == null)
80
{ return; }
81
socket.send({ type: MessageType.dropItem, slotIndex: selected });
82
});
83
document.getElementById("bag-equip").addEventListener("click", () =>
84
{
85
if (selected == null)
86
{ return; }
87
socket.send({ type: MessageType.equipItem, slotIndex: selected });
88
});
89
77
document.getElementById("bank-close").addEventListener("click", () => closeBank());
90
78
document.getElementById("bank-claim").addEventListener("click", () =>
91
79
{
@@ -265,6 +253,13 @@ export function initInventory ({
265
253
});
266
254
}
267
255
}
256
if (slot.instance?.kind === "spellbook")
257
{
258
items.push({
259
label: "Study",
260
onSelect: () => socket.send({ type: MessageType.readSpellbook, slotIndex })
261
});
262
}
268
263
if (slot.itemId === ItemId.recipePaper && slot.instance?.kind === "recipe-paper")
269
264
{
270
265
items.push({
@@ -74,18 +74,6 @@ export function initInventory ({74
{74
{75
bagPanel.hidden = !bagPanel.hidden;75
bagPanel.hidden = !bagPanel.hidden;76
});76
});77
document.getElementById("bag-drop").addEventListener("click", () =>78
{79
if (selected == null)80
{ return; }81
socket.send({ type: MessageType.dropItem, slotIndex: selected });82
});83
document.getElementById("bag-equip").addEventListener("click", () =>84
{85
if (selected == null)86
{ return; }87
socket.send({ type: MessageType.equipItem, slotIndex: selected });88
});89
document.getElementById("bank-close").addEventListener("click", () => closeBank());77
document.getElementById("bank-close").addEventListener("click", () => closeBank());90
document.getElementById("bank-claim").addEventListener("click", () =>78
document.getElementById("bank-claim").addEventListener("click", () =>91
{79
{@@ -265,6 +253,13 @@ export function initInventory ({265
});253
});266
}254
}267
}255
}256
if (slot.instance?.kind === "spellbook")257
{258
items.push({259
label: "Study",260
onSelect: () => socket.send({ type: MessageType.readSpellbook, slotIndex })261
});262
}268
if (slot.itemId === ItemId.recipePaper && slot.instance?.kind === "recipe-paper")263
if (slot.itemId === ItemId.recipePaper && slot.instance?.kind === "recipe-paper")269
{264
{270
items.push({265
items.push({@@ -1,4 +1,5 @@
1
1
import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";
2
import { COMBAT_RANGE_TILES } from "/shared/spells/constants.js";
2
3
import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock } from "/shared/definitions/tiles.js";
3
4
import { GameSocket, defaultSocketUrl } from "../net/socket.js";
4
5
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
@@ -7,6 +8,7 @@ import { initSocial } from "./social.js";
7
8
import { initChat } from "./chat.js";
8
9
import { initInventory } from "./inventory.js";
9
10
import { initSkills } from "./skills.js";
11
import { initSpells } from "./spells.js";
10
12
import { initCrafting } from "./crafting.js";
11
13
import { initAlchemy } from "./alchemy.js";
12
14
import { initStamina } from "./stamina.js";
@@ -47,6 +49,7 @@ let social;
47
49
let chat;
48
50
let inventory;
49
51
let skills;
52
let spells;
50
53
let crafting;
51
54
let alchemy;
52
55
let staminaUi;
@@ -112,7 +115,16 @@ function uiBlocked ()
112
115
return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
113
116
|| crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking()
114
117
|| market?.isBlocking() || bounty?.isBlocking() || barber?.isBlocking()
115
|| contextMenu?.isOpen() || death?.isBlocking());
118
|| contextMenu?.isOpen() || death?.isBlocking() || spells?.isBlocking()
119
|| pointerOverSpellUi());
120
}
121
122
function pointerOverSpellUi ()
123
{
124
const el = document.elementFromPoint(GameInput.mousePosition.x, GameInput.mousePosition.y);
125
if (!el)
126
{ return false; }
127
return !!el.closest("#spells-panel, #spell-favorites-bar, #spells-toggle");
116
128
}
117
129
118
130
function applyGraphicsSettings (settings)
@@ -500,6 +512,11 @@ function isAttackableEntity (entity)
500
512
501
513
function handleLeftClick (mouseX, mouseY)
502
514
{
515
const tile = view.screenToTile(mouseX, mouseY);
516
const armed = spells?.getArmedSpell?.();
517
if (armed?.target === "tile" && armed.canCast && spells.tryCastAtTile(tile.tileX, tile.tileY))
518
{ return; }
519
503
520
const entity = view.entityAtScreen(mouseX, mouseY);
504
521
if (entity && entity.entityId !== view.localEntityId && !entity.untargetable)
505
522
{
@@ -517,6 +534,8 @@ function handleLeftClick (mouseX, mouseY)
517
534
}
518
535
if (isAttackableEntity(entity))
519
536
{
537
if (spells?.tryCastAtEntity?.(entity.entityId))
538
{ return; }
520
539
requestAttack(entity.entityId);
521
540
return;
522
541
}
@@ -524,7 +543,6 @@ function handleLeftClick (mouseX, mouseY)
524
543
return;
525
544
}
526
545
527
const tile = view.screenToTile(mouseX, mouseY);
528
546
const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
529
547
if (ground)
530
548
{ requestPickup(ground); }
@@ -568,6 +586,12 @@ function handleLeftClick (mouseX, mouseY)
568
586
function handleRightClick (event, mouseX, mouseY)
569
587
{
570
588
event.preventDefault();
589
if (spells?.isTargeting?.())
590
{
591
spells.cancelTargeting();
592
view?.clearSpellTargetHighlight();
593
return;
594
}
571
595
const tile = view.screenToTile(mouseX, mouseY);
572
596
const items = [];
573
597
const walkTileX = tile.tileX;
@@ -847,10 +871,14 @@ function startPlay (payload)
847
871
flushPendingInteract();
848
872
social?.updateNametag(view, scene, view.localEntityId);
849
873
chat?.update(view, scene);
874
updateSpellTargetHighlight();
850
875
updateWorldTooltip();
851
876
}
852
877
else
853
{ hideWorldTooltip(); }
878
{
879
hideWorldTooltip();
880
view?.clearSpellTargetHighlight();
881
}
854
882
view.update(dt);
855
883
};
856
884
scene.addObject(ticker);
@@ -943,6 +971,10 @@ async function main ()
943
971
}
944
972
});
945
973
skills = initSkills();
974
spells = initSpells({
975
socket: { send (payload) { socket.send(payload); } },
976
MessageType
977
});
946
978
crafting = initCrafting({
947
979
socket: { send (payload) { socket.send(payload); } },
948
980
MessageType,
@@ -1100,6 +1132,34 @@ async function main ()
1100
1132
skills?.render(message.skills);
1101
1133
crafting?.refresh();
1102
1134
break;
1135
case MessageType.spells:
1136
case MessageType.spellsUpdated:
1137
spells?.render(message);
1138
break;
1139
case MessageType.spellArmed:
1140
spells?.handleSpellArmed(message);
1141
break;
1142
case MessageType.spellDisarmed:
1143
spells?.handleSpellDisarmed();
1144
break;
1145
case MessageType.spellProjectile:
1146
view?.spawnSpellProjectileFx(message);
1147
break;
1148
case MessageType.spellFizzle:
1149
view?.spawnSpellFizzleFx(message);
1150
if (message.casterId === view?.localEntityId)
1151
{ toasts?.show("Failed to cast spell"); }
1152
break;
1153
case MessageType.spellCastFlash:
1154
view?.spawnSpellCastFlash(message);
1155
break;
1156
case MessageType.spellLightAppear:
1157
case MessageType.spellLightUpdate:
1158
view?.setSpellLight(message);
1159
break;
1160
case MessageType.spellLightRemove:
1161
view?.removeSpellLight(message);
1162
break;
1103
1163
case MessageType.stamina:
1104
1164
staminaUi?.apply(message);
1105
1165
if (message.gait)
@@ -1313,6 +1373,7 @@ function returnToMenu (reason = "")
1313
1373
healthUi?.hide();
1314
1374
statusEffectsUi?.hide();
1315
1375
skills?.hide();
1376
spells?.hide();
1316
1377
contextMenu?.hide();
1317
1378
death?.reset();
1318
1379
shop?.close({ notifyServer: false });
@@ -1461,6 +1522,31 @@ function isPickablePlantTile (view, tileX, tileY)
1461
1522
return isPickablePlantBlock(blockAt(view, tileX, tileY));
1462
1523
}
1463
1524
1525
function updateSpellTargetHighlight ()
1526
{
1527
if (!view || !playing || uiBlocked() || !spells?.isTargeting?.())
1528
{
1529
view?.clearSpellTargetHighlight();
1530
return;
1531
}
1532
const canvas = scene?.canvas;
1533
if (!canvas)
1534
{ return; }
1535
const rect = canvas.getBoundingClientRect();
1536
const mouseX = GameInput.mousePosition.x - rect.left;
1537
const mouseY = GameInput.mousePosition.y - rect.top;
1538
if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
1539
{
1540
view.clearSpellTargetHighlight();
1541
return;
1542
}
1543
const tile = view.screenToTile(mouseX, mouseY);
1544
const local = view.entities.get(view.localEntityId);
1545
const inRange = !local
1546
|| chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= COMBAT_RANGE_TILES;
1547
view.setSpellTargetHighlight(tile.tileX, tile.tileY, inRange);
1548
}
1549
1464
1550
function hideWorldTooltip ()
1465
1551
{
1466
1552
if (worldTooltip)
@@ -1,4 +1,5 @@1
import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";1
import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";2
import { COMBAT_RANGE_TILES } from "/shared/spells/constants.js";2
import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock } from "/shared/definitions/tiles.js";3
import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock } from "/shared/definitions/tiles.js";3
import { GameSocket, defaultSocketUrl } from "../net/socket.js";4
import { GameSocket, defaultSocketUrl } from "../net/socket.js";4
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";5
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";@@ -7,6 +8,7 @@ import { initSocial } from "./social.js";7
import { initChat } from "./chat.js";8
import { initChat } from "./chat.js";8
import { initInventory } from "./inventory.js";9
import { initInventory } from "./inventory.js";9
import { initSkills } from "./skills.js";10
import { initSkills } from "./skills.js";11
import { initSpells } from "./spells.js";10
import { initCrafting } from "./crafting.js";12
import { initCrafting } from "./crafting.js";11
import { initAlchemy } from "./alchemy.js";13
import { initAlchemy } from "./alchemy.js";12
import { initStamina } from "./stamina.js";14
import { initStamina } from "./stamina.js";@@ -47,6 +49,7 @@ let social;47
let chat;49
let chat;48
let inventory;50
let inventory;49
let skills;51
let skills;52
let spells;50
let crafting;53
let crafting;51
let alchemy;54
let alchemy;52
let staminaUi;55
let staminaUi;@@ -112,7 +115,16 @@ function uiBlocked ()112
return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()115
return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()113
|| crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking()116
|| crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking()114
|| market?.isBlocking() || bounty?.isBlocking() || barber?.isBlocking()117
|| market?.isBlocking() || bounty?.isBlocking() || barber?.isBlocking()115
|| contextMenu?.isOpen() || death?.isBlocking());118
|| contextMenu?.isOpen() || death?.isBlocking() || spells?.isBlocking()119
|| pointerOverSpellUi());120
}121
122
function pointerOverSpellUi ()123
{124
const el = document.elementFromPoint(GameInput.mousePosition.x, GameInput.mousePosition.y);125
if (!el)126
{ return false; }127
return !!el.closest("#spells-panel, #spell-favorites-bar, #spells-toggle");116
}128
}117
129
118
function applyGraphicsSettings (settings)130
function applyGraphicsSettings (settings)@@ -500,6 +512,11 @@ function isAttackableEntity (entity)500
512
501
function handleLeftClick (mouseX, mouseY)513
function handleLeftClick (mouseX, mouseY)502
{514
{515
const tile = view.screenToTile(mouseX, mouseY);516
const armed = spells?.getArmedSpell?.();517
if (armed?.target === "tile" && armed.canCast && spells.tryCastAtTile(tile.tileX, tile.tileY))518
{ return; }519
503
const entity = view.entityAtScreen(mouseX, mouseY);520
const entity = view.entityAtScreen(mouseX, mouseY);504
if (entity && entity.entityId !== view.localEntityId && !entity.untargetable)521
if (entity && entity.entityId !== view.localEntityId && !entity.untargetable)505
{522
{@@ -517,6 +534,8 @@ function handleLeftClick (mouseX, mouseY)517
}534
}518
if (isAttackableEntity(entity))535
if (isAttackableEntity(entity))519
{536
{537
if (spells?.tryCastAtEntity?.(entity.entityId))538
{ return; }520
requestAttack(entity.entityId);539
requestAttack(entity.entityId);521
return;540
return;522
}541
}@@ -524,7 +543,6 @@ function handleLeftClick (mouseX, mouseY)524
return;543
return;525
}544
}526
545
527
const tile = view.screenToTile(mouseX, mouseY);528
const ground = view.groundItemAtTile(tile.tileX, tile.tileY);546
const ground = view.groundItemAtTile(tile.tileX, tile.tileY);529
if (ground)547
if (ground)530
{ requestPickup(ground); }548
{ requestPickup(ground); }@@ -568,6 +586,12 @@ function handleLeftClick (mouseX, mouseY)568
function handleRightClick (event, mouseX, mouseY)586
function handleRightClick (event, mouseX, mouseY)569
{587
{570
event.preventDefault();588
event.preventDefault();589
if (spells?.isTargeting?.())590
{591
spells.cancelTargeting();592
view?.clearSpellTargetHighlight();593
return;594
}571
const tile = view.screenToTile(mouseX, mouseY);595
const tile = view.screenToTile(mouseX, mouseY);572
const items = [];596
const items = [];573
const walkTileX = tile.tileX;597
const walkTileX = tile.tileX;@@ -847,10 +871,14 @@ function startPlay (payload)847
flushPendingInteract();871
flushPendingInteract();848
social?.updateNametag(view, scene, view.localEntityId);872
social?.updateNametag(view, scene, view.localEntityId);849
chat?.update(view, scene);873
chat?.update(view, scene);874
updateSpellTargetHighlight();850
updateWorldTooltip();875
updateWorldTooltip();851
}876
}852
else877
else853
{ hideWorldTooltip(); }878
{879
hideWorldTooltip();880
view?.clearSpellTargetHighlight();881
}854
view.update(dt);882
view.update(dt);855
};883
};856
scene.addObject(ticker);884
scene.addObject(ticker);@@ -943,6 +971,10 @@ async function main ()943
}971
}944
});972
});945
skills = initSkills();973
skills = initSkills();974
spells = initSpells({975
socket: { send (payload) { socket.send(payload); } },976
MessageType977
});946
crafting = initCrafting({978
crafting = initCrafting({947
socket: { send (payload) { socket.send(payload); } },979
socket: { send (payload) { socket.send(payload); } },948
MessageType,980
MessageType,@@ -1100,6 +1132,34 @@ async function main ()1100
skills?.render(message.skills);1132
skills?.render(message.skills);1101
crafting?.refresh();1133
crafting?.refresh();1102
break;1134
break;1135
case MessageType.spells:1136
case MessageType.spellsUpdated:1137
spells?.render(message);1138
break;1139
case MessageType.spellArmed:1140
spells?.handleSpellArmed(message);1141
break;1142
case MessageType.spellDisarmed:1143
spells?.handleSpellDisarmed();1144
break;1145
case MessageType.spellProjectile:1146
view?.spawnSpellProjectileFx(message);1147
break;1148
case MessageType.spellFizzle:1149
view?.spawnSpellFizzleFx(message);1150
if (message.casterId === view?.localEntityId)1151
{ toasts?.show("Failed to cast spell"); }1152
break;1153
case MessageType.spellCastFlash:1154
view?.spawnSpellCastFlash(message);1155
break;1156
case MessageType.spellLightAppear:1157
case MessageType.spellLightUpdate:1158
view?.setSpellLight(message);1159
break;1160
case MessageType.spellLightRemove:1161
view?.removeSpellLight(message);1162
break;1103
case MessageType.stamina:1163
case MessageType.stamina:1104
staminaUi?.apply(message);1164
staminaUi?.apply(message);1105
if (message.gait)1165
if (message.gait)@@ -1313,6 +1373,7 @@ function returnToMenu (reason = "")1313
healthUi?.hide();1373
healthUi?.hide();1314
statusEffectsUi?.hide();1374
statusEffectsUi?.hide();1315
skills?.hide();1375
skills?.hide();1376
spells?.hide();1316
contextMenu?.hide();1377
contextMenu?.hide();1317
death?.reset();1378
death?.reset();1318
shop?.close({ notifyServer: false });1379
shop?.close({ notifyServer: false });@@ -1461,6 +1522,31 @@ function isPickablePlantTile (view, tileX, tileY)1461
return isPickablePlantBlock(blockAt(view, tileX, tileY));1522
return isPickablePlantBlock(blockAt(view, tileX, tileY));1462
}1523
}1463
1524
1525
function updateSpellTargetHighlight ()1526
{1527
if (!view || !playing || uiBlocked() || !spells?.isTargeting?.())1528
{1529
view?.clearSpellTargetHighlight();1530
return;1531
}1532
const canvas = scene?.canvas;1533
if (!canvas)1534
{ return; }1535
const rect = canvas.getBoundingClientRect();1536
const mouseX = GameInput.mousePosition.x - rect.left;1537
const mouseY = GameInput.mousePosition.y - rect.top;1538
if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)1539
{1540
view.clearSpellTargetHighlight();1541
return;1542
}1543
const tile = view.screenToTile(mouseX, mouseY);1544
const local = view.entities.get(view.localEntityId);1545
const inRange = !local1546
|| chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= COMBAT_RANGE_TILES;1547
view.setSpellTargetHighlight(tile.tileX, tile.tileY, inRange);1548
}1549
1464
function hideWorldTooltip ()1550
function hideWorldTooltip ()1465
{1551
{1466
if (worldTooltip)1552
if (worldTooltip)@@ -0,0 +1,227 @@
1
export function initSpells ({ socket, MessageType })
2
{
3
const panel = document.getElementById("spells-panel");
4
const list = document.getElementById("spells-list");
5
const bar = document.getElementById("spell-favorites-bar");
6
const autoCastToggle = document.getElementById("spell-autocast-toggle");
7
let spells = [];
8
let autoCast = false;
9
let armedSpellId = null;
10
11
document.getElementById("spells-toggle")?.addEventListener("click", () =>
12
{
13
panel.hidden = !panel.hidden;
14
});
15
16
autoCastToggle?.addEventListener("change", () =>
17
{
18
socket.send({
19
type: MessageType.setSpellAutoCast,
20
enabled: autoCastToggle.checked
21
});
22
});
23
24
function disarmLocal ()
25
{
26
if (!armedSpellId)
27
{ return; }
28
armedSpellId = null;
29
renderList();
30
renderBar();
31
}
32
33
function render (payload)
34
{
35
spells = payload?.spells ?? [];
36
autoCast = !!payload?.autoCast;
37
if (payload?.armedSpellId !== undefined)
38
{ armedSpellId = payload.armedSpellId; }
39
if (autoCastToggle)
40
{ autoCastToggle.checked = autoCast; }
41
renderList();
42
renderBar();
43
}
44
45
function renderList ()
46
{
47
list.replaceChildren();
48
for (const spell of spells)
49
{
50
list.append(renderSpellRow(spell));
51
}
52
}
53
54
function renderSpellRow (spell)
55
{
56
const row = document.createElement("div");
57
row.className = "spell-row";
58
if (spell.spellId === armedSpellId)
59
{ row.classList.add("armed"); }
60
61
const icon = document.createElement("img");
62
icon.className = "spell-icon";
63
icon.src = spell.icon;
64
icon.alt = "";
65
icon.loading = "lazy";
66
67
const body = document.createElement("div");
68
body.className = "spell-body";
69
70
const title = document.createElement("div");
71
title.className = "spell-title";
72
title.textContent = spell.displayName;
73
74
const desc = document.createElement("div");
75
desc.className = "spell-desc hint";
76
desc.textContent = spell.description ?? "";
77
78
const actions = document.createElement("div");
79
actions.className = "spell-actions";
80
81
const favorite = document.createElement("button");
82
favorite.type = "button";
83
favorite.className = "spell-favorite-btn";
84
favorite.textContent = spell.favorite ? "★" : "☆";
85
favorite.title = spell.canFavorite
86
? (spell.favorite ? "Remove from favourites" : "Add to favourites")
87
: "Magic level too low to favourite";
88
favorite.disabled = !spell.canFavorite;
89
favorite.addEventListener("click", () =>
90
{
91
socket.send({ type: MessageType.setSpellFavorite, spellId: spell.spellId });
92
});
93
94
const arm = document.createElement("button");
95
arm.type = "button";
96
arm.className = "spell-arm-btn";
97
arm.textContent = spell.spellId === armedSpellId ? "Armed" : "Arm";
98
arm.disabled = !spell.canCast;
99
arm.addEventListener("click", () =>
100
{
101
if (spell.spellId === armedSpellId)
102
{ cancelTargeting(); }
103
else
104
{ socket.send({ type: MessageType.armSpell, spellId: spell.spellId }); }
105
});
106
107
actions.append(favorite, arm);
108
body.append(title, desc, actions);
109
row.append(icon, body);
110
return row;
111
}
112
113
function renderBar ()
114
{
115
const favorites = spells.filter((entry) => entry.favorite);
116
bar.replaceChildren();
117
bar.hidden = favorites.length === 0;
118
for (const spell of favorites)
119
{
120
const btn = document.createElement("button");
121
btn.type = "button";
122
btn.className = "spell-favorite-slot";
123
if (spell.spellId === armedSpellId)
124
{ btn.classList.add("armed"); }
125
btn.title = spell.displayName;
126
btn.disabled = !spell.canCast;
127
128
const icon = document.createElement("img");
129
icon.src = spell.icon;
130
icon.alt = "";
131
btn.append(icon);
132
133
btn.addEventListener("click", () =>
134
{
135
if (spell.spellId === armedSpellId)
136
{ return; }
137
socket.send({ type: MessageType.armSpell, spellId: spell.spellId });
138
});
139
btn.addEventListener("contextmenu", (event) =>
140
{
141
event.preventDefault();
142
socket.send({ type: MessageType.setSpellFavorite, spellId: spell.spellId });
143
});
144
bar.append(btn);
145
}
146
}
147
148
function getArmedSpell ()
149
{
150
if (!armedSpellId)
151
{ return null; }
152
return spells.find((entry) => entry.spellId === armedSpellId) ?? null;
153
}
154
155
function tryCastAtTile (tileX, tileY)
156
{
157
const armed = getArmedSpell();
158
if (!armed || armed.target !== "tile" || !armed.canCast)
159
{ return false; }
160
socket.send({
161
type: MessageType.castSpellTile,
162
spellId: armed.spellId,
163
tileX,
164
tileY
165
});
166
return true;
167
}
168
169
function tryCastAtEntity (targetEntityId)
170
{
171
const armed = getArmedSpell();
172
if (!armed || armed.target !== "entity" || !armed.canCast)
173
{ return false; }
174
socket.send({
175
type: MessageType.castSpellEntity,
176
spellId: armed.spellId,
177
targetEntityId
178
});
179
return true;
180
}
181
182
function cancelTargeting ()
183
{
184
if (!armedSpellId)
185
{ return; }
186
socket.send({ type: MessageType.cancelArmSpell });
187
disarmLocal();
188
}
189
190
return {
191
render,
192
getArmedSpell,
193
tryCastAtTile,
194
tryCastAtEntity,
195
cancelTargeting,
196
isBlocking ()
197
{
198
return panel != null && !panel.hidden;
199
},
200
isTargeting ()
201
{
202
return armedSpellId != null;
203
},
204
handleSpellArmed (message)
205
{
206
armedSpellId = message.spellId ?? null;
207
renderList();
208
renderBar();
209
},
210
handleSpellDisarmed ()
211
{
212
disarmLocal();
213
},
214
hide ()
215
{
216
panel.hidden = true;
217
spells = [];
218
autoCast = false;
219
armedSpellId = null;
220
if (autoCastToggle)
221
{ autoCastToggle.checked = false; }
222
list.replaceChildren();
223
bar.replaceChildren();
224
bar.hidden = true;
225
}
226
};
227
}
@@ -0,0 +1,227 @@1
export function initSpells ({ socket, MessageType })2
{3
const panel = document.getElementById("spells-panel");4
const list = document.getElementById("spells-list");5
const bar = document.getElementById("spell-favorites-bar");6
const autoCastToggle = document.getElementById("spell-autocast-toggle");7
let spells = [];8
let autoCast = false;9
let armedSpellId = null;10
11
document.getElementById("spells-toggle")?.addEventListener("click", () =>12
{13
panel.hidden = !panel.hidden;14
});15
16
autoCastToggle?.addEventListener("change", () =>17
{18
socket.send({19
type: MessageType.setSpellAutoCast,20
enabled: autoCastToggle.checked21
});22
});23
24
function disarmLocal ()25
{26
if (!armedSpellId)27
{ return; }28
armedSpellId = null;29
renderList();30
renderBar();31
}32
33
function render (payload)34
{35
spells = payload?.spells ?? [];36
autoCast = !!payload?.autoCast;37
if (payload?.armedSpellId !== undefined)38
{ armedSpellId = payload.armedSpellId; }39
if (autoCastToggle)40
{ autoCastToggle.checked = autoCast; }41
renderList();42
renderBar();43
}44
45
function renderList ()46
{47
list.replaceChildren();48
for (const spell of spells)49
{50
list.append(renderSpellRow(spell));51
}52
}53
54
function renderSpellRow (spell)55
{56
const row = document.createElement("div");57
row.className = "spell-row";58
if (spell.spellId === armedSpellId)59
{ row.classList.add("armed"); }60
61
const icon = document.createElement("img");62
icon.className = "spell-icon";63
icon.src = spell.icon;64
icon.alt = "";65
icon.loading = "lazy";66
67
const body = document.createElement("div");68
body.className = "spell-body";69
70
const title = document.createElement("div");71
title.className = "spell-title";72
title.textContent = spell.displayName;73
74
const desc = document.createElement("div");75
desc.className = "spell-desc hint";76
desc.textContent = spell.description ?? "";77
78
const actions = document.createElement("div");79
actions.className = "spell-actions";80
81
const favorite = document.createElement("button");82
favorite.type = "button";83
favorite.className = "spell-favorite-btn";84
favorite.textContent = spell.favorite ? "★" : "☆";85
favorite.title = spell.canFavorite86
? (spell.favorite ? "Remove from favourites" : "Add to favourites")87
: "Magic level too low to favourite";88
favorite.disabled = !spell.canFavorite;89
favorite.addEventListener("click", () =>90
{91
socket.send({ type: MessageType.setSpellFavorite, spellId: spell.spellId });92
});93
94
const arm = document.createElement("button");95
arm.type = "button";96
arm.className = "spell-arm-btn";97
arm.textContent = spell.spellId === armedSpellId ? "Armed" : "Arm";98
arm.disabled = !spell.canCast;99
arm.addEventListener("click", () =>100
{101
if (spell.spellId === armedSpellId)102
{ cancelTargeting(); }103
else104
{ socket.send({ type: MessageType.armSpell, spellId: spell.spellId }); }105
});106
107
actions.append(favorite, arm);108
body.append(title, desc, actions);109
row.append(icon, body);110
return row;111
}112
113
function renderBar ()114
{115
const favorites = spells.filter((entry) => entry.favorite);116
bar.replaceChildren();117
bar.hidden = favorites.length === 0;118
for (const spell of favorites)119
{120
const btn = document.createElement("button");121
btn.type = "button";122
btn.className = "spell-favorite-slot";123
if (spell.spellId === armedSpellId)124
{ btn.classList.add("armed"); }125
btn.title = spell.displayName;126
btn.disabled = !spell.canCast;127
128
const icon = document.createElement("img");129
icon.src = spell.icon;130
icon.alt = "";131
btn.append(icon);132
133
btn.addEventListener("click", () =>134
{135
if (spell.spellId === armedSpellId)136
{ return; }137
socket.send({ type: MessageType.armSpell, spellId: spell.spellId });138
});139
btn.addEventListener("contextmenu", (event) =>140
{141
event.preventDefault();142
socket.send({ type: MessageType.setSpellFavorite, spellId: spell.spellId });143
});144
bar.append(btn);145
}146
}147
148
function getArmedSpell ()149
{150
if (!armedSpellId)151
{ return null; }152
return spells.find((entry) => entry.spellId === armedSpellId) ?? null;153
}154
155
function tryCastAtTile (tileX, tileY)156
{157
const armed = getArmedSpell();158
if (!armed || armed.target !== "tile" || !armed.canCast)159
{ return false; }160
socket.send({161
type: MessageType.castSpellTile,162
spellId: armed.spellId,163
tileX,164
tileY165
});166
return true;167
}168
169
function tryCastAtEntity (targetEntityId)170
{171
const armed = getArmedSpell();172
if (!armed || armed.target !== "entity" || !armed.canCast)173
{ return false; }174
socket.send({175
type: MessageType.castSpellEntity,176
spellId: armed.spellId,177
targetEntityId178
});179
return true;180
}181
182
function cancelTargeting ()183
{184
if (!armedSpellId)185
{ return; }186
socket.send({ type: MessageType.cancelArmSpell });187
disarmLocal();188
}189
190
return {191
render,192
getArmedSpell,193
tryCastAtTile,194
tryCastAtEntity,195
cancelTargeting,196
isBlocking ()197
{198
return panel != null && !panel.hidden;199
},200
isTargeting ()201
{202
return armedSpellId != null;203
},204
handleSpellArmed (message)205
{206
armedSpellId = message.spellId ?? null;207
renderList();208
renderBar();209
},210
handleSpellDisarmed ()211
{212
disarmLocal();213
},214
hide ()215
{216
panel.hidden = true;217
spells = [];218
autoCast = false;219
armedSpellId = null;220
if (autoCastToggle)221
{ autoCastToggle.checked = false; }222
list.replaceChildren();223
bar.replaceChildren();224
bar.hidden = true;225
}226
};227
}@@ -42,7 +42,7 @@ export function initStatusEffects ()
42
42
43
43
function remainingMs (entry, now = Date.now())
44
44
{
45
return Math.max(0, (entry.expiresAt | 0) - now);
45
return Math.max(0, Number(entry.expiresAt) - now);
46
46
}
47
47
48
48
function prune (now = Date.now())
@@ -173,10 +173,10 @@ export function initStatusEffects ()
173
173
{
174
174
const list = Array.isArray(message?.effects) ? message.effects : [];
175
175
effects = list
176
.filter((entry) => entry?.type && (entry.expiresAt | 0) > Date.now())
176
.filter((entry) => entry?.type && Number(entry.expiresAt) > Date.now())
177
177
.map((entry) => ({
178
178
type: entry.type,
179
expiresAt: entry.expiresAt | 0,
179
expiresAt: Number(entry.expiresAt) || 0,
180
180
amount: entry.amount | 0,
181
181
amountPerSecond: Number(entry.amountPerSecond) || 0,
182
182
scale: entry.scale ?? null,
@@ -42,7 +42,7 @@ export function initStatusEffects ()42
42
43
function remainingMs (entry, now = Date.now())43
function remainingMs (entry, now = Date.now())44
{44
{45
return Math.max(0, (entry.expiresAt | 0) - now);45
return Math.max(0, Number(entry.expiresAt) - now);46
}46
}47
47
48
function prune (now = Date.now())48
function prune (now = Date.now())@@ -173,10 +173,10 @@ export function initStatusEffects ()173
{173
{174
const list = Array.isArray(message?.effects) ? message.effects : [];174
const list = Array.isArray(message?.effects) ? message.effects : [];175
effects = list175
effects = list176
.filter((entry) => entry?.type && (entry.expiresAt | 0) > Date.now())176
.filter((entry) => entry?.type && Number(entry.expiresAt) > Date.now())177
.map((entry) => ({177
.map((entry) => ({178
type: entry.type,178
type: entry.type,179
expiresAt: entry.expiresAt | 0,179
expiresAt: Number(entry.expiresAt) || 0,180
amount: entry.amount | 0,180
amount: entry.amount | 0,181
amountPerSecond: Number(entry.amountPerSecond) || 0,181
amountPerSecond: Number(entry.amountPerSecond) || 0,182
scale: entry.scale ?? null,182
scale: entry.scale ?? null,@@ -5,7 +5,9 @@ export const UTILITY_IMAGES = [
5
5
{ name: "night-shade", url: shadeDataUrl("#000000") },
6
6
{ name: "chunk-edge", url: shadeDataUrl("#e23d3d") },
7
7
{ name: "spawn-range", url: shadeDataUrl("rgba(72, 180, 210, 0.32)") },
8
{ name: "wander-range", url: shadeDataUrl("rgba(210, 170, 72, 0.22)") }
8
{ name: "wander-range", url: shadeDataUrl("rgba(210, 170, 72, 0.22)") },
9
{ name: "spell-target-tile", url: shadeDataUrl("rgba(110, 220, 255, 0.62)") },
10
{ name: "spell-target-invalid", url: shadeDataUrl("rgba(255, 72, 72, 0.48)") }
9
11
];
10
12
11
13
export function playImagesFromCatalog (catalog)
@@ -5,7 +5,9 @@ export const UTILITY_IMAGES = [5
{ name: "night-shade", url: shadeDataUrl("#000000") },5
{ name: "night-shade", url: shadeDataUrl("#000000") },6
{ name: "chunk-edge", url: shadeDataUrl("#e23d3d") },6
{ name: "chunk-edge", url: shadeDataUrl("#e23d3d") },7
{ name: "spawn-range", url: shadeDataUrl("rgba(72, 180, 210, 0.32)") },7
{ name: "spawn-range", url: shadeDataUrl("rgba(72, 180, 210, 0.32)") },8
{ name: "wander-range", url: shadeDataUrl("rgba(210, 170, 72, 0.22)") }8
{ name: "wander-range", url: shadeDataUrl("rgba(210, 170, 72, 0.22)") },9
{ name: "spell-target-tile", url: shadeDataUrl("rgba(110, 220, 255, 0.62)") },10
{ name: "spell-target-invalid", url: shadeDataUrl("rgba(255, 72, 72, 0.48)") }9
];11
];10
12
11
export function playImagesFromCatalog (catalog)13
export function playImagesFromCatalog (catalog)@@ -360,6 +360,7 @@ export class WorldView
360
360
this.editorSpawners = new Map();
361
361
this.spawnRangeHighlight = null;
362
362
this.wanderRangeHighlight = null;
363
this.spellTargetHighlight = null;
363
364
this.#syncBloomLayer();
364
365
}
365
366
@@ -725,6 +726,7 @@ export class WorldView
725
726
this.#redrawPreview();
726
727
this.#relayoutEditorSpawners();
727
728
this.#relayoutSpawnRangeHighlight();
729
this.#relayoutSpellTargetHighlight();
728
730
applyNearestToAllTextures(this.scene, this.game.images);
729
731
}
730
732
@@ -1246,6 +1248,50 @@ export class WorldView
1246
1248
this.wanderRangeHighlight = null;
1247
1249
}
1248
1250
1251
setSpellTargetHighlight (tileX, tileY, inRange = true)
1252
{
1253
if (
1254
this.spellTargetHighlight
1255
&& this.spellTargetHighlight.tileX === tileX
1256
&& this.spellTargetHighlight.tileY === tileY
1257
&& this.spellTargetHighlight.inRange === inRange
1258
)
1259
{
1260
this.#relayoutSpellTargetHighlight();
1261
return;
1262
}
1263
this.clearSpellTargetHighlight();
1264
const spriteName = inRange ? "spell-target-tile" : "spell-target-invalid";
1265
const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1);
1266
if (!object)
1267
{ return; }
1268
this.#markUnlit(object);
1269
object.renderer.alpha = 1;
1270
this.spellTargetHighlight = { object, tileX, tileY, inRange, spriteName };
1271
this.#relayoutSpellTargetHighlight();
1272
}
1273
1274
clearSpellTargetHighlight ()
1275
{
1276
this.spellTargetHighlight?.object?.destroy();
1277
this.spellTargetHighlight = null;
1278
}
1279
1280
#relayoutSpellTargetHighlight ()
1281
{
1282
const highlight = this.spellTargetHighlight;
1283
if (!highlight?.object)
1284
{ return; }
1285
const size = this.tileSize();
1286
const left = highlight.tileX * size;
1287
const top = highlight.tileY * size;
1288
highlight.object.transform.position.x = left + size / 2;
1289
highlight.object.transform.position.y = top + size / 2;
1290
highlight.object.transform.size = new vector(size, size);
1291
highlight.object.layer = LAYER_EDGE - 1;
1292
this.#markSortDirty();
1293
}
1294
1249
1295
#relayoutSpawnRangeHighlight ()
1250
1296
{
1251
1297
this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2);
@@ -360,6 +360,7 @@ export class WorldView360
this.editorSpawners = new Map();360
this.editorSpawners = new Map();361
this.spawnRangeHighlight = null;361
this.spawnRangeHighlight = null;362
this.wanderRangeHighlight = null;362
this.wanderRangeHighlight = null;363
this.spellTargetHighlight = null;363
this.#syncBloomLayer();364
this.#syncBloomLayer();364
}365
}365
366
@@ -725,6 +726,7 @@ export class WorldView725
this.#redrawPreview();726
this.#redrawPreview();726
this.#relayoutEditorSpawners();727
this.#relayoutEditorSpawners();727
this.#relayoutSpawnRangeHighlight();728
this.#relayoutSpawnRangeHighlight();729
this.#relayoutSpellTargetHighlight();728
applyNearestToAllTextures(this.scene, this.game.images);730
applyNearestToAllTextures(this.scene, this.game.images);729
}731
}730
732
@@ -1246,6 +1248,50 @@ export class WorldView1246
this.wanderRangeHighlight = null;1248
this.wanderRangeHighlight = null;1247
}1249
}1248
1250
1251
setSpellTargetHighlight (tileX, tileY, inRange = true)1252
{1253
if (1254
this.spellTargetHighlight1255
&& this.spellTargetHighlight.tileX === tileX1256
&& this.spellTargetHighlight.tileY === tileY1257
&& this.spellTargetHighlight.inRange === inRange1258
)1259
{1260
this.#relayoutSpellTargetHighlight();1261
return;1262
}1263
this.clearSpellTargetHighlight();1264
const spriteName = inRange ? "spell-target-tile" : "spell-target-invalid";1265
const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1);1266
if (!object)1267
{ return; }1268
this.#markUnlit(object);1269
object.renderer.alpha = 1;1270
this.spellTargetHighlight = { object, tileX, tileY, inRange, spriteName };1271
this.#relayoutSpellTargetHighlight();1272
}1273
1274
clearSpellTargetHighlight ()1275
{1276
this.spellTargetHighlight?.object?.destroy();1277
this.spellTargetHighlight = null;1278
}1279
1280
#relayoutSpellTargetHighlight ()1281
{1282
const highlight = this.spellTargetHighlight;1283
if (!highlight?.object)1284
{ return; }1285
const size = this.tileSize();1286
const left = highlight.tileX * size;1287
const top = highlight.tileY * size;1288
highlight.object.transform.position.x = left + size / 2;1289
highlight.object.transform.position.y = top + size / 2;1290
highlight.object.transform.size = new vector(size, size);1291
highlight.object.layer = LAYER_EDGE - 1;1292
this.#markSortDirty();1293
}1294
1249
#relayoutSpawnRangeHighlight ()1295
#relayoutSpawnRangeHighlight ()1250
{1296
{1251
this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2);1297
this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2);@@ -509,6 +509,151 @@ a { color: #d4c48a; }
509
509
transition: width 0.25s ease-out;
510
510
}
511
511
512
#spells-panel {
513
position: fixed;
514
z-index: 5;
515
top: 50%;
516
left: 50%;
517
transform: translate(-50%, -50%);
518
width: min(520px, 94vw);
519
max-height: calc(100vh - 80px);
520
overflow: auto;
521
background: #1a1e26;
522
border: 1px solid #2c3340;
523
padding: 0.75rem;
524
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
525
}
526
527
.spell-autocast-row {
528
display: flex;
529
align-items: center;
530
gap: 0.5rem;
531
margin: 0.35rem 0 0.75rem;
532
font-size: 0.92rem;
533
color: #c8d0dc;
534
}
535
536
.spells-grid {
537
display: grid;
538
grid-template-columns: 1fr;
539
gap: 0.55rem;
540
margin: 0.5rem 0;
541
}
542
543
.spell-row {
544
display: flex;
545
gap: 0.55rem;
546
align-items: stretch;
547
min-width: 0;
548
padding: 0.45rem;
549
border: 1px solid #2c3340;
550
border-radius: 8px;
551
background: #12151b;
552
}
553
554
.spell-row.armed {
555
border-color: #6eb5ff;
556
box-shadow: 0 0 0 1px rgba(110, 181, 255, 0.35);
557
}
558
559
.spell-icon {
560
flex: 0 0 36px;
561
width: 36px;
562
height: 36px;
563
border-radius: 6px;
564
background: #101216;
565
border: 1px solid #3a4250;
566
}
567
568
.spell-body {
569
flex: 1;
570
display: flex;
571
flex-direction: column;
572
gap: 0.25rem;
573
min-width: 0;
574
}
575
576
.spell-title {
577
font-weight: 600;
578
color: #eef2f8;
579
}
580
581
.spell-desc {
582
margin: 0;
583
font-size: 0.86rem;
584
line-height: 1.35;
585
}
586
587
.spell-actions {
588
display: flex;
589
gap: 0.4rem;
590
margin-top: 0.15rem;
591
}
592
593
.spell-favorite-btn,
594
.spell-arm-btn {
595
font: inherit;
596
font-size: 0.85rem;
597
padding: 0.2rem 0.55rem;
598
border-radius: 6px;
599
border: 1px solid #3a4250;
600
background: #1f2430;
601
color: #eef2f8;
602
cursor: pointer;
603
}
604
605
.spell-favorite-btn:disabled,
606
.spell-arm-btn:disabled {
607
opacity: 0.45;
608
cursor: not-allowed;
609
}
610
611
#spell-favorites-bar {
612
position: fixed;
613
z-index: 5;
614
left: 0.75rem;
615
bottom: 0.65rem;
616
display: flex;
617
gap: 0.35rem;
618
padding: 0.35rem;
619
border-radius: 10px;
620
background: rgba(18, 21, 27, 0.94);
621
border: 1px solid #2c3340;
622
box-shadow: 0 4px 18px rgba(0, 0, 0, 0.35);
623
}
624
625
.spell-favorite-slot {
626
width: 44px;
627
height: 44px;
628
padding: 0;
629
border-radius: 8px;
630
border: 2px solid #3a4250;
631
background: #1a1e26;
632
cursor: pointer;
633
transition: border-color 0.12s ease, box-shadow 0.12s ease, transform 0.12s ease;
634
}
635
636
.spell-favorite-slot.armed {
637
border-color: #8fd0ff;
638
background: #1e2a38;
639
box-shadow:
640
0 0 0 2px rgba(143, 208, 255, 0.45),
641
0 0 14px rgba(110, 181, 255, 0.55);
642
transform: translateY(-2px);
643
}
644
645
.spell-favorite-slot img {
646
width: 100%;
647
height: 100%;
648
object-fit: contain;
649
border-radius: 6px;
650
}
651
652
.spell-favorite-slot:disabled {
653
opacity: 0.45;
654
cursor: not-allowed;
655
}
656
512
657
#bag-panel, #bank-panel {
513
658
position: fixed;
514
659
z-index: 5;
@@ -1137,6 +1282,8 @@ a { color: #d4c48a; }
1137
1282
#death-backdrop[hidden],
1138
1283
#friends-panel[hidden],
1139
1284
#skills-panel[hidden],
1285
#spells-panel[hidden],
1286
#spell-favorites-bar[hidden],
1140
1287
#bag-panel[hidden],
1141
1288
#bank-panel[hidden],
1142
1289
#craft-panel[hidden],
@@ -509,6 +509,151 @@ a { color: #d4c48a; }509
transition: width 0.25s ease-out;509
transition: width 0.25s ease-out;510
}510
}511
511
512
#spells-panel {513
position: fixed;514
z-index: 5;515
top: 50%;516
left: 50%;517
transform: translate(-50%, -50%);518
width: min(520px, 94vw);519
max-height: calc(100vh - 80px);520
overflow: auto;521
background: #1a1e26;522
border: 1px solid #2c3340;523
padding: 0.75rem;524
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);525
}526
527
.spell-autocast-row {528
display: flex;529
align-items: center;530
gap: 0.5rem;531
margin: 0.35rem 0 0.75rem;532
font-size: 0.92rem;533
color: #c8d0dc;534
}535
536
.spells-grid {537
display: grid;538
grid-template-columns: 1fr;539
gap: 0.55rem;540
margin: 0.5rem 0;541
}542
543
.spell-row {544
display: flex;545
gap: 0.55rem;546
align-items: stretch;547
min-width: 0;548
padding: 0.45rem;549
border: 1px solid #2c3340;550
border-radius: 8px;551
background: #12151b;552
}553
554
.spell-row.armed {555
border-color: #6eb5ff;556
box-shadow: 0 0 0 1px rgba(110, 181, 255, 0.35);557
}558
559
.spell-icon {560
flex: 0 0 36px;561
width: 36px;562
height: 36px;563
border-radius: 6px;564
background: #101216;565
border: 1px solid #3a4250;566
}567
568
.spell-body {569
flex: 1;570
display: flex;571
flex-direction: column;572
gap: 0.25rem;573
min-width: 0;574
}575
576
.spell-title {577
font-weight: 600;578
color: #eef2f8;579
}580
581
.spell-desc {582
margin: 0;583
font-size: 0.86rem;584
line-height: 1.35;585
}586
587
.spell-actions {588
display: flex;589
gap: 0.4rem;590
margin-top: 0.15rem;591
}592
593
.spell-favorite-btn,594
.spell-arm-btn {595
font: inherit;596
font-size: 0.85rem;597
padding: 0.2rem 0.55rem;598
border-radius: 6px;599
border: 1px solid #3a4250;600
background: #1f2430;601
color: #eef2f8;602
cursor: pointer;603
}604
605
.spell-favorite-btn:disabled,606
.spell-arm-btn:disabled {607
opacity: 0.45;608
cursor: not-allowed;609
}610
611
#spell-favorites-bar {612
position: fixed;613
z-index: 5;614
left: 0.75rem;615
bottom: 0.65rem;616
display: flex;617
gap: 0.35rem;618
padding: 0.35rem;619
border-radius: 10px;620
background: rgba(18, 21, 27, 0.94);621
border: 1px solid #2c3340;622
box-shadow: 0 4px 18px rgba(0, 0, 0, 0.35);623
}624
625
.spell-favorite-slot {626
width: 44px;627
height: 44px;628
padding: 0;629
border-radius: 8px;630
border: 2px solid #3a4250;631
background: #1a1e26;632
cursor: pointer;633
transition: border-color 0.12s ease, box-shadow 0.12s ease, transform 0.12s ease;634
}635
636
.spell-favorite-slot.armed {637
border-color: #8fd0ff;638
background: #1e2a38;639
box-shadow:640
0 0 0 2px rgba(143, 208, 255, 0.45),641
0 0 14px rgba(110, 181, 255, 0.55);642
transform: translateY(-2px);643
}644
645
.spell-favorite-slot img {646
width: 100%;647
height: 100%;648
object-fit: contain;649
border-radius: 6px;650
}651
652
.spell-favorite-slot:disabled {653
opacity: 0.45;654
cursor: not-allowed;655
}656
512
#bag-panel, #bank-panel {657
#bag-panel, #bank-panel {513
position: fixed;658
position: fixed;514
z-index: 5;659
z-index: 5;@@ -1137,6 +1282,8 @@ a { color: #d4c48a; }1137
#death-backdrop[hidden],1282
#death-backdrop[hidden],1138
#friends-panel[hidden],1283
#friends-panel[hidden],1139
#skills-panel[hidden],1284
#skills-panel[hidden],1285
#spells-panel[hidden],1286
#spell-favorites-bar[hidden],1140
#bag-panel[hidden],1287
#bag-panel[hidden],1141
#bank-panel[hidden],1288
#bank-panel[hidden],1142
#craft-panel[hidden],1289
#craft-panel[hidden],@@ -25,6 +25,7 @@ import {
25
25
equipmentBonusesFromSlots
26
26
} from "../../../shared/equipment/stats.js";
27
27
import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
28
import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS } from "../../../shared/spells/constants.js";
28
29
import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
29
30
import { chunkBoundsAround, findPath } from "../navigation/astar.js";
30
31
import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
@@ -144,7 +145,10 @@ export function clearEngage (ecs, entityId)
144
145
145
146
export function hasCombatLineOfSight (world, fromX, fromY, toX, toY)
146
147
{
147
return rayReaches(fromX, fromY, toX, toY, (x, y) => world.isEnterable(x, y));
148
const isClear = world.isClearForRangedAttack
149
? (x, y) => world.isClearForRangedAttack(x, y)
150
: (x, y) => world.isEnterable(x, y);
151
return rayReaches(fromX, fromY, toX, toY, isClear);
148
152
}
149
153
150
154
/** Target-tile lighting 0–1 (baked + entity lights + time of day). */
@@ -395,7 +399,7 @@ export function stepCombat (world, now = Date.now())
395
399
if (profile.mode === "ranged")
396
400
{
397
401
const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
398
const maxRange = profile.rangeTiles | 0 || 8;
402
const maxRange = profile.rangeTiles | 0 || COMBAT_RANGE_TILES;
399
403
const equipment = world.ecs.get(entity.handle, Component.equipment);
400
404
const hasArrows = arrowStackInOffhand(equipment) && stackQuantity(arrowStackInOffhand(equipment).quantity) > 0;
401
405
const inRange = dist >= 1 && dist <= maxRange
@@ -460,7 +464,7 @@ function clearCombatApproachPath (ecs, handle)
460
464
{ path.tiles = []; }
461
465
}
462
466
463
function queueMeleeApproach (world, entityId, handle, position, targetPos)
467
export function queueMeleeApproach (world, entityId, handle, position, targetPos)
464
468
{
465
469
if (world.frozen?.has?.(entityId))
466
470
{ return; }
@@ -525,7 +529,36 @@ function queueMeleeApproach (world, entityId, handle, position, targetPos)
525
529
{ movement.walkCarry = 0; }
526
530
}
527
531
528
function queueRangedApproach (world, entityId, handle, position, targetPos, maxRange)
532
function standInRangePathStale (world, entityId, path, goal, targetTileX, targetTileY, maxRange, minStandDist)
533
{
534
const dest = path.tiles[path.tiles.length - 1];
535
if (dest.x !== goal.x || dest.y !== goal.y)
536
{ return true; }
537
const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY);
538
if (standOff < minStandDist || standOff > maxRange)
539
{ return true; }
540
if (!hasCombatLineOfSight(world, dest.x, dest.y, targetTileX, targetTileY))
541
{ return true; }
542
const next = path.tiles[0];
543
if (!next)
544
{ return true; }
545
return !world.walkableFor(entityId, next.x, next.y);
546
}
547
548
/**
549
* Path toward the nearest tile from which `targetTile` is in Chebyshev range with LOS.
550
* @param {number} minStandDist Minimum stand-off from target (0 = may stand on target tile).
551
*/
552
export function queueStandInRangeApproach (
553
world,
554
entityId,
555
handle,
556
position,
557
targetTileX,
558
targetTileY,
559
maxRange,
560
minStandDist = 1
561
)
529
562
{
530
563
if (world.frozen?.has?.(entityId))
531
564
{ return; }
@@ -533,10 +566,12 @@ function queueRangedApproach (world, entityId, handle, position, targetPos, maxR
533
566
if (!path)
534
567
{ path = world.ecs.add(handle, Component.path, { tiles: [] }); }
535
568
536
const dist = chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY);
537
if (dist >= 1 && dist <= maxRange && hasCombatLineOfSight(
538
world, position.tileX, position.tileY, targetPos.tileX, targetPos.tileY
539
))
569
const distToTarget = chebyshev(position.tileX, position.tileY, targetTileX, targetTileY);
570
if (
571
distToTarget <= maxRange
572
&& distToTarget >= minStandDist
573
&& hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY)
574
)
540
575
{
541
576
path.tiles = [];
542
577
return;
@@ -548,14 +583,14 @@ function queueRangedApproach (world, entityId, handle, position, targetPos, maxR
548
583
{
549
584
for (let dx = -maxRange; dx <= maxRange; dx++)
550
585
{
551
const x = targetPos.tileX + dx;
552
const y = targetPos.tileY + dy;
553
const toTarget = chebyshev(x, y, targetPos.tileX, targetPos.tileY);
554
if (toTarget < 1 || toTarget > maxRange)
586
const x = targetTileX + dx;
587
const y = targetTileY + dy;
588
const standOff = chebyshev(x, y, targetTileX, targetTileY);
589
if (standOff < minStandDist || standOff > maxRange)
555
590
{ continue; }
556
591
if (!world.walkableFor(entityId, x, y))
557
592
{ continue; }
558
if (!hasCombatLineOfSight(world, x, y, targetPos.tileX, targetPos.tileY))
593
if (!hasCombatLineOfSight(world, x, y, targetTileX, targetTileY))
559
594
{ continue; }
560
595
const d = chebyshev(position.tileX, position.tileY, x, y);
561
596
if (d < bestDist)
@@ -575,6 +610,17 @@ function queueRangedApproach (world, entityId, handle, position, targetPos, maxR
575
610
path.tiles = [];
576
611
return;
577
612
}
613
if (path.tiles?.length && !standInRangePathStale(
614
world,
615
entityId,
616
path,
617
bestGoal,
618
targetTileX,
619
targetTileY,
620
maxRange,
621
minStandDist
622
))
623
{ return; }
578
624
const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
579
625
const preferVertical = !!world.ecs.get(handle, Component.character);
580
626
const tiles = findPath(
@@ -595,6 +641,20 @@ function queueRangedApproach (world, entityId, handle, position, targetPos, maxR
595
641
{ movement.walkCarry = 0; }
596
642
}
597
643
644
function queueRangedApproach (world, entityId, handle, position, targetPos, maxRange)
645
{
646
queueStandInRangeApproach(
647
world,
648
entityId,
649
handle,
650
position,
651
targetPos.tileX,
652
targetPos.tileY,
653
maxRange,
654
1
655
);
656
}
657
598
658
export function resolveRangedShot (world, attackerId, targetId, profile, now = Date.now(), targetPos)
599
659
{
600
660
const events = [];
@@ -668,7 +728,7 @@ export function resolveRangedShot (world, attackerId, targetId, profile, now = D
668
728
fromTileY: from.tileY,
669
729
tileX: endX,
670
730
tileY: endY,
671
durationMs: 400,
731
durationMs: RANGED_PROJECTILE_MS,
672
732
...publicDualTint(projectileDualTintFromAttacker(world.ecs, attackerHandle)) ?? {}
673
733
});
674
734
return events.concat(hitEvents);
@@ -827,7 +887,7 @@ export function applyRemoteRangedShot (world, payload)
827
887
fromTileY: payload.fromTileY,
828
888
tileX: endX,
829
889
tileY: endY,
830
durationMs: 400,
890
durationMs: RANGED_PROJECTILE_MS,
831
891
shaftTint: payload.shaftTint ?? null,
832
892
tipTint: payload.tipTint ?? null
833
893
}, ...hitEvents];
@@ -25,6 +25,7 @@ import {25
equipmentBonusesFromSlots25
equipmentBonusesFromSlots26
} from "../../../shared/equipment/stats.js";26
} from "../../../shared/equipment/stats.js";27
import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";27
import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";28
import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS } from "../../../shared/spells/constants.js";28
import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";29
import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";29
import { chunkBoundsAround, findPath } from "../navigation/astar.js";30
import { chunkBoundsAround, findPath } from "../navigation/astar.js";30
import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";31
import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";@@ -144,7 +145,10 @@ export function clearEngage (ecs, entityId)144
145
145
export function hasCombatLineOfSight (world, fromX, fromY, toX, toY)146
export function hasCombatLineOfSight (world, fromX, fromY, toX, toY)146
{147
{147
return rayReaches(fromX, fromY, toX, toY, (x, y) => world.isEnterable(x, y));148
const isClear = world.isClearForRangedAttack149
? (x, y) => world.isClearForRangedAttack(x, y)150
: (x, y) => world.isEnterable(x, y);151
return rayReaches(fromX, fromY, toX, toY, isClear);148
}152
}149
153
150
/** Target-tile lighting 0–1 (baked + entity lights + time of day). */154
/** Target-tile lighting 0–1 (baked + entity lights + time of day). */@@ -395,7 +399,7 @@ export function stepCombat (world, now = Date.now())395
if (profile.mode === "ranged")399
if (profile.mode === "ranged")396
{400
{397
const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);401
const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);398
const maxRange = profile.rangeTiles | 0 || 8;402
const maxRange = profile.rangeTiles | 0 || COMBAT_RANGE_TILES;399
const equipment = world.ecs.get(entity.handle, Component.equipment);403
const equipment = world.ecs.get(entity.handle, Component.equipment);400
const hasArrows = arrowStackInOffhand(equipment) && stackQuantity(arrowStackInOffhand(equipment).quantity) > 0;404
const hasArrows = arrowStackInOffhand(equipment) && stackQuantity(arrowStackInOffhand(equipment).quantity) > 0;401
const inRange = dist >= 1 && dist <= maxRange405
const inRange = dist >= 1 && dist <= maxRange@@ -460,7 +464,7 @@ function clearCombatApproachPath (ecs, handle)460
{ path.tiles = []; }464
{ path.tiles = []; }461
}465
}462
466
463
function queueMeleeApproach (world, entityId, handle, position, targetPos)467
export function queueMeleeApproach (world, entityId, handle, position, targetPos)464
{468
{465
if (world.frozen?.has?.(entityId))469
if (world.frozen?.has?.(entityId))466
{ return; }470
{ return; }@@ -525,7 +529,36 @@ function queueMeleeApproach (world, entityId, handle, position, targetPos)525
{ movement.walkCarry = 0; }529
{ movement.walkCarry = 0; }526
}530
}527
531
528
function queueRangedApproach (world, entityId, handle, position, targetPos, maxRange)532
function standInRangePathStale (world, entityId, path, goal, targetTileX, targetTileY, maxRange, minStandDist)533
{534
const dest = path.tiles[path.tiles.length - 1];535
if (dest.x !== goal.x || dest.y !== goal.y)536
{ return true; }537
const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY);538
if (standOff < minStandDist || standOff > maxRange)539
{ return true; }540
if (!hasCombatLineOfSight(world, dest.x, dest.y, targetTileX, targetTileY))541
{ return true; }542
const next = path.tiles[0];543
if (!next)544
{ return true; }545
return !world.walkableFor(entityId, next.x, next.y);546
}547
548
/**549
* Path toward the nearest tile from which `targetTile` is in Chebyshev range with LOS.550
* @param {number} minStandDist Minimum stand-off from target (0 = may stand on target tile).551
*/552
export function queueStandInRangeApproach (553
world,554
entityId,555
handle,556
position,557
targetTileX,558
targetTileY,559
maxRange,560
minStandDist = 1561
)529
{562
{530
if (world.frozen?.has?.(entityId))563
if (world.frozen?.has?.(entityId))531
{ return; }564
{ return; }@@ -533,10 +566,12 @@ function queueRangedApproach (world, entityId, handle, position, targetPos, maxR533
if (!path)566
if (!path)534
{ path = world.ecs.add(handle, Component.path, { tiles: [] }); }567
{ path = world.ecs.add(handle, Component.path, { tiles: [] }); }535
568
536
const dist = chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY);569
const distToTarget = chebyshev(position.tileX, position.tileY, targetTileX, targetTileY);537
if (dist >= 1 && dist <= maxRange && hasCombatLineOfSight(570
if (538
world, position.tileX, position.tileY, targetPos.tileX, targetPos.tileY571
distToTarget <= maxRange539
))572
&& distToTarget >= minStandDist573
&& hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY)574
)540
{575
{541
path.tiles = [];576
path.tiles = [];542
return;577
return;@@ -548,14 +583,14 @@ function queueRangedApproach (world, entityId, handle, position, targetPos, maxR548
{583
{549
for (let dx = -maxRange; dx <= maxRange; dx++)584
for (let dx = -maxRange; dx <= maxRange; dx++)550
{585
{551
const x = targetPos.tileX + dx;586
const x = targetTileX + dx;552
const y = targetPos.tileY + dy;587
const y = targetTileY + dy;553
const toTarget = chebyshev(x, y, targetPos.tileX, targetPos.tileY);588
const standOff = chebyshev(x, y, targetTileX, targetTileY);554
if (toTarget < 1 || toTarget > maxRange)589
if (standOff < minStandDist || standOff > maxRange)555
{ continue; }590
{ continue; }556
if (!world.walkableFor(entityId, x, y))591
if (!world.walkableFor(entityId, x, y))557
{ continue; }592
{ continue; }558
if (!hasCombatLineOfSight(world, x, y, targetPos.tileX, targetPos.tileY))593
if (!hasCombatLineOfSight(world, x, y, targetTileX, targetTileY))559
{ continue; }594
{ continue; }560
const d = chebyshev(position.tileX, position.tileY, x, y);595
const d = chebyshev(position.tileX, position.tileY, x, y);561
if (d < bestDist)596
if (d < bestDist)@@ -575,6 +610,17 @@ function queueRangedApproach (world, entityId, handle, position, targetPos, maxR575
path.tiles = [];610
path.tiles = [];576
return;611
return;577
}612
}613
if (path.tiles?.length && !standInRangePathStale(614
world,615
entityId,616
path,617
bestGoal,618
targetTileX,619
targetTileY,620
maxRange,621
minStandDist622
))623
{ return; }578
const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);624
const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);579
const preferVertical = !!world.ecs.get(handle, Component.character);625
const preferVertical = !!world.ecs.get(handle, Component.character);580
const tiles = findPath(626
const tiles = findPath(@@ -595,6 +641,20 @@ function queueRangedApproach (world, entityId, handle, position, targetPos, maxR595
{ movement.walkCarry = 0; }641
{ movement.walkCarry = 0; }596
}642
}597
643
644
function queueRangedApproach (world, entityId, handle, position, targetPos, maxRange)645
{646
queueStandInRangeApproach(647
world,648
entityId,649
handle,650
position,651
targetPos.tileX,652
targetPos.tileY,653
maxRange,654
1655
);656
}657
598
export function resolveRangedShot (world, attackerId, targetId, profile, now = Date.now(), targetPos)658
export function resolveRangedShot (world, attackerId, targetId, profile, now = Date.now(), targetPos)599
{659
{600
const events = [];660
const events = [];@@ -668,7 +728,7 @@ export function resolveRangedShot (world, attackerId, targetId, profile, now = D668
fromTileY: from.tileY,728
fromTileY: from.tileY,669
tileX: endX,729
tileX: endX,670
tileY: endY,730
tileY: endY,671
durationMs: 400,731
durationMs: RANGED_PROJECTILE_MS,672
...publicDualTint(projectileDualTintFromAttacker(world.ecs, attackerHandle)) ?? {}732
...publicDualTint(projectileDualTintFromAttacker(world.ecs, attackerHandle)) ?? {}673
});733
});674
return events.concat(hitEvents);734
return events.concat(hitEvents);@@ -827,7 +887,7 @@ export function applyRemoteRangedShot (world, payload)827
fromTileY: payload.fromTileY,887
fromTileY: payload.fromTileY,828
tileX: endX,888
tileX: endX,829
tileY: endY,889
tileY: endY,830
durationMs: 400,890
durationMs: RANGED_PROJECTILE_MS,831
shaftTint: payload.shaftTint ?? null,891
shaftTint: payload.shaftTint ?? null,832
tipTint: payload.tipTint ?? null892
tipTint: payload.tipTint ?? null833
}, ...hitEvents];893
}, ...hitEvents];@@ -21,5 +21,7 @@ export const Component = Object.freeze({
21
21
stamina: "stamina",
22
22
gather: "gather",
23
23
shop: "shop",
24
statusEffects: "statusEffects"
24
statusEffects: "statusEffects",
25
spells: "spells",
26
spellcasting: "spellcasting"
25
27
});
@@ -21,5 +21,7 @@ export const Component = Object.freeze({21
stamina: "stamina",21
stamina: "stamina",22
gather: "gather",22
gather: "gather",23
shop: "shop",23
shop: "shop",24
statusEffects: "statusEffects"24
statusEffects: "statusEffects",25
spells: "spells",26
spellcasting: "spellcasting"25
});27
});@@ -515,6 +515,64 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
515
515
characterId: session.characterId
516
516
});
517
517
break;
518
case MessageType.setSpellFavorite:
519
requirePlaying(session);
520
simulation.enqueue(session.id, {
521
type: "set-spell-favorite",
522
characterId: session.characterId,
523
spellId: message.spellId
524
});
525
break;
526
case MessageType.setSpellAutoCast:
527
requirePlaying(session);
528
simulation.enqueue(session.id, {
529
type: "set-spell-autocast",
530
characterId: session.characterId,
531
enabled: !!message.enabled
532
});
533
break;
534
case MessageType.armSpell:
535
requirePlaying(session);
536
simulation.enqueue(session.id, {
537
type: "arm-spell",
538
characterId: session.characterId,
539
spellId: message.spellId
540
});
541
break;
542
case MessageType.cancelArmSpell:
543
requirePlaying(session);
544
simulation.enqueue(session.id, {
545
type: "cancel-arm-spell",
546
characterId: session.characterId
547
});
548
break;
549
case MessageType.castSpellTile:
550
requirePlaying(session);
551
simulation.enqueue(session.id, {
552
type: "cast-spell-tile",
553
characterId: session.characterId,
554
spellId: message.spellId,
555
tileX: message.tileX | 0,
556
tileY: message.tileY | 0
557
});
558
break;
559
case MessageType.castSpellEntity:
560
requirePlaying(session);
561
simulation.enqueue(session.id, {
562
type: "cast-spell-entity",
563
characterId: session.characterId,
564
spellId: message.spellId,
565
targetEntityId: message.targetEntityId | 0
566
});
567
break;
568
case MessageType.readSpellbook:
569
requirePlaying(session);
570
simulation.enqueue(session.id, {
571
type: "read-spellbook",
572
characterId: session.characterId,
573
slotIndex: message.slotIndex | 0
574
});
575
break;
518
576
case MessageType.interact:
519
577
requirePlaying(session);
520
578
simulation.enqueue(session.id, {
@@ -776,6 +834,16 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
776
834
const skills = simulation.skillsOf(session.entityId);
777
835
if (skills)
778
836
{ send(session, { type: MessageType.skills, skills: publicSkillsView(skills) }); }
837
const spellView = simulation.spellsOf(session.entityId);
838
if (spellView)
839
{
840
send(session, {
841
type: MessageType.spells,
842
spells: spellView.spells,
843
autoCast: spellView.autoCast,
844
armedSpellId: spellView.armedSpellId ?? null
845
});
846
}
779
847
const stamina = simulation.staminaOf(session.entityId);
780
848
if (stamina)
781
849
{
@@ -970,6 +1038,38 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
970
1038
send(session, { type: MessageType.skills, skills: event.skills ?? [] });
971
1039
continue;
972
1040
}
1041
if (event.type === "spells")
1042
{
1043
const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1044
if (!session)
1045
{ continue; }
1046
send(session, {
1047
type: MessageType.spellsUpdated,
1048
spells: event.spells ?? [],
1049
autoCast: !!event.autoCast,
1050
armedSpellId: event.armedSpellId ?? null
1051
});
1052
continue;
1053
}
1054
if (event.type === "spell-armed")
1055
{
1056
const session = [...sessions.values()].find((entry) => entry.entityId === event.entityId);
1057
if (!session)
1058
{ continue; }
1059
send(session, {
1060
type: MessageType.spellArmed,
1061
spellId: event.spellId
1062
});
1063
continue;
1064
}
1065
if (event.type === "spell-disarmed")
1066
{
1067
const session = [...sessions.values()].find((entry) => entry.entityId === event.entityId);
1068
if (!session)
1069
{ continue; }
1070
send(session, { type: MessageType.spellDisarmed });
1071
continue;
1072
}
973
1073
if (event.type === "stamina")
974
1074
{
975
1075
const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
@@ -1251,7 +1351,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1251
1351
}
1252
1352
continue;
1253
1353
}
1254
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 === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")
1354
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 === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")
1255
1355
{ publishEntity(event); }
1256
1356
}
1257
1357
if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
@@ -1361,6 +1461,82 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1361
1461
});
1362
1462
continue;
1363
1463
}
1464
if (event.type === "spell-projectile")
1465
{
1466
if (!seesTo && !seesFrom)
1467
{ continue; }
1468
send(session, {
1469
type: MessageType.spellProjectile,
1470
casterId: event.casterId,
1471
spellId: event.spellId,
1472
fromTileX: event.fromTileX,
1473
fromTileY: event.fromTileY,
1474
tileX: event.tileX,
1475
tileY: event.tileY,
1476
durationMs: event.durationMs ?? 2000,
1477
sprite: event.sprite ?? null
1478
});
1479
continue;
1480
}
1481
if (event.type === "spell-fizzle")
1482
{
1483
if (!seesTo && !seesFrom)
1484
{ continue; }
1485
send(session, {
1486
type: MessageType.spellFizzle,
1487
casterId: event.casterId,
1488
spellId: event.spellId,
1489
fromTileX: event.fromTileX,
1490
fromTileY: event.fromTileY,
1491
tileX: event.tileX,
1492
tileY: event.tileY
1493
});
1494
continue;
1495
}
1496
if (event.type === "spell-cast-flash")
1497
{
1498
if (!seesTo)
1499
{ continue; }
1500
send(session, {
1501
type: MessageType.spellCastFlash,
1502
casterId: event.casterId,
1503
tileX: event.tileX,
1504
tileY: event.tileY,
1505
radiusTiles: event.radiusTiles ?? 1,
1506
durationMs: event.durationMs ?? 500,
1507
tier: event.tier ?? 1
1508
});
1509
continue;
1510
}
1511
if (event.type === "spell-light-appear" || event.type === "spell-light-update")
1512
{
1513
if (!seesTo)
1514
{ continue; }
1515
send(session, {
1516
type: event.type === "spell-light-appear"
1517
? MessageType.spellLightAppear
1518
: MessageType.spellLightUpdate,
1519
tileX: event.tileX,
1520
tileY: event.tileY,
1521
ownerEntityId: event.ownerEntityId,
1522
remainingMs: event.remainingMs ?? 0,
1523
rangeTiles: event.rangeTiles ?? 0,
1524
intensity: event.intensity ?? 0,
1525
expiresAt: event.expiresAt ?? 0
1526
});
1527
continue;
1528
}
1529
if (event.type === "spell-light-remove")
1530
{
1531
if (!seesTo)
1532
{ continue; }
1533
send(session, {
1534
type: MessageType.spellLightRemove,
1535
tileX: event.tileX,
1536
tileY: event.tileY
1537
});
1538
continue;
1539
}
1364
1540
if (event.type === "entity-health")
1365
1541
{
1366
1542
if (!seesTo && !seesFrom)
@@ -515,6 +515,64 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,515
characterId: session.characterId515
characterId: session.characterId516
});516
});517
break;517
break;518
case MessageType.setSpellFavorite:519
requirePlaying(session);520
simulation.enqueue(session.id, {521
type: "set-spell-favorite",522
characterId: session.characterId,523
spellId: message.spellId524
});525
break;526
case MessageType.setSpellAutoCast:527
requirePlaying(session);528
simulation.enqueue(session.id, {529
type: "set-spell-autocast",530
characterId: session.characterId,531
enabled: !!message.enabled532
});533
break;534
case MessageType.armSpell:535
requirePlaying(session);536
simulation.enqueue(session.id, {537
type: "arm-spell",538
characterId: session.characterId,539
spellId: message.spellId540
});541
break;542
case MessageType.cancelArmSpell:543
requirePlaying(session);544
simulation.enqueue(session.id, {545
type: "cancel-arm-spell",546
characterId: session.characterId547
});548
break;549
case MessageType.castSpellTile:550
requirePlaying(session);551
simulation.enqueue(session.id, {552
type: "cast-spell-tile",553
characterId: session.characterId,554
spellId: message.spellId,555
tileX: message.tileX | 0,556
tileY: message.tileY | 0557
});558
break;559
case MessageType.castSpellEntity:560
requirePlaying(session);561
simulation.enqueue(session.id, {562
type: "cast-spell-entity",563
characterId: session.characterId,564
spellId: message.spellId,565
targetEntityId: message.targetEntityId | 0566
});567
break;568
case MessageType.readSpellbook:569
requirePlaying(session);570
simulation.enqueue(session.id, {571
type: "read-spellbook",572
characterId: session.characterId,573
slotIndex: message.slotIndex | 0574
});575
break;518
case MessageType.interact:576
case MessageType.interact:519
requirePlaying(session);577
requirePlaying(session);520
simulation.enqueue(session.id, {578
simulation.enqueue(session.id, {@@ -776,6 +834,16 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,776
const skills = simulation.skillsOf(session.entityId);834
const skills = simulation.skillsOf(session.entityId);777
if (skills)835
if (skills)778
{ send(session, { type: MessageType.skills, skills: publicSkillsView(skills) }); }836
{ send(session, { type: MessageType.skills, skills: publicSkillsView(skills) }); }837
const spellView = simulation.spellsOf(session.entityId);838
if (spellView)839
{840
send(session, {841
type: MessageType.spells,842
spells: spellView.spells,843
autoCast: spellView.autoCast,844
armedSpellId: spellView.armedSpellId ?? null845
});846
}779
const stamina = simulation.staminaOf(session.entityId);847
const stamina = simulation.staminaOf(session.entityId);780
if (stamina)848
if (stamina)781
{849
{@@ -970,6 +1038,38 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,970
send(session, { type: MessageType.skills, skills: event.skills ?? [] });1038
send(session, { type: MessageType.skills, skills: event.skills ?? [] });971
continue;1039
continue;972
}1040
}1041
if (event.type === "spells")1042
{1043
const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);1044
if (!session)1045
{ continue; }1046
send(session, {1047
type: MessageType.spellsUpdated,1048
spells: event.spells ?? [],1049
autoCast: !!event.autoCast,1050
armedSpellId: event.armedSpellId ?? null1051
});1052
continue;1053
}1054
if (event.type === "spell-armed")1055
{1056
const session = [...sessions.values()].find((entry) => entry.entityId === event.entityId);1057
if (!session)1058
{ continue; }1059
send(session, {1060
type: MessageType.spellArmed,1061
spellId: event.spellId1062
});1063
continue;1064
}1065
if (event.type === "spell-disarmed")1066
{1067
const session = [...sessions.values()].find((entry) => entry.entityId === event.entityId);1068
if (!session)1069
{ continue; }1070
send(session, { type: MessageType.spellDisarmed });1071
continue;1072
}973
if (event.type === "stamina")1073
if (event.type === "stamina")974
{1074
{975
const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);1075
const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);@@ -1251,7 +1351,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,1251
}1351
}1252
continue;1352
continue;1253
}1353
}1254
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 === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")1354
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 === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")1255
{ publishEntity(event); }1355
{ publishEntity(event); }1256
}1356
}1257
if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)1357
if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)@@ -1361,6 +1461,82 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,1361
});1461
});1362
continue;1462
continue;1363
}1463
}1464
if (event.type === "spell-projectile")1465
{1466
if (!seesTo && !seesFrom)1467
{ continue; }1468
send(session, {1469
type: MessageType.spellProjectile,1470
casterId: event.casterId,1471
spellId: event.spellId,1472
fromTileX: event.fromTileX,1473
fromTileY: event.fromTileY,1474
tileX: event.tileX,1475
tileY: event.tileY,1476
durationMs: event.durationMs ?? 2000,1477
sprite: event.sprite ?? null1478
});1479
continue;1480
}1481
if (event.type === "spell-fizzle")1482
{1483
if (!seesTo && !seesFrom)1484
{ continue; }1485
send(session, {1486
type: MessageType.spellFizzle,1487
casterId: event.casterId,1488
spellId: event.spellId,1489
fromTileX: event.fromTileX,1490
fromTileY: event.fromTileY,1491
tileX: event.tileX,1492
tileY: event.tileY1493
});1494
continue;1495
}1496
if (event.type === "spell-cast-flash")1497
{1498
if (!seesTo)1499
{ continue; }1500
send(session, {1501
type: MessageType.spellCastFlash,1502
casterId: event.casterId,1503
tileX: event.tileX,1504
tileY: event.tileY,1505
radiusTiles: event.radiusTiles ?? 1,1506
durationMs: event.durationMs ?? 500,1507
tier: event.tier ?? 11508
});1509
continue;1510
}1511
if (event.type === "spell-light-appear" || event.type === "spell-light-update")1512
{1513
if (!seesTo)1514
{ continue; }1515
send(session, {1516
type: event.type === "spell-light-appear"1517
? MessageType.spellLightAppear1518
: MessageType.spellLightUpdate,1519
tileX: event.tileX,1520
tileY: event.tileY,1521
ownerEntityId: event.ownerEntityId,1522
remainingMs: event.remainingMs ?? 0,1523
rangeTiles: event.rangeTiles ?? 0,1524
intensity: event.intensity ?? 0,1525
expiresAt: event.expiresAt ?? 01526
});1527
continue;1528
}1529
if (event.type === "spell-light-remove")1530
{1531
if (!seesTo)1532
{ continue; }1533
send(session, {1534
type: MessageType.spellLightRemove,1535
tileX: event.tileX,1536
tileY: event.tileY1537
});1538
continue;1539
}1364
if (event.type === "entity-health")1540
if (event.type === "entity-health")1365
{1541
{1366
if (!seesTo && !seesFrom)1542
if (!seesTo && !seesFrom)@@ -26,6 +26,7 @@ import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
26
26
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
27
27
import { randomUUID } from "node:crypto";
28
28
import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
29
import { resolvePotionEffect } from "../../../shared/alchemy/recipes.js";
29
30
import {
30
31
applyStatusEffect,
31
32
emptyStatusEffects,
@@ -435,7 +436,7 @@ function drinkItem (world, sessionId, command)
435
436
throw userError("That inventory slot is empty.");
436
437
}
437
438
inventory.slots = consumed.slots;
438
const effectResult = applyPotionEffect(world.ecs, handle, consumed.instance?.effect);
439
const effectResult = applyPotionEffect(world.ecs, handle, resolvePotionEffect(consumed.instance));
439
440
return {
440
441
events: effectResult.events ?? [],
441
442
private: bagView(world.ecs, handle),
@@ -26,6 +26,7 @@ import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";26
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";26
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";27
import { randomUUID } from "node:crypto";27
import { randomUUID } from "node:crypto";28
import { tileShoveTowardBlock } from "../simulation/tileInteract.js";28
import { tileShoveTowardBlock } from "../simulation/tileInteract.js";29
import { resolvePotionEffect } from "../../../shared/alchemy/recipes.js";29
import {30
import {30
applyStatusEffect,31
applyStatusEffect,31
emptyStatusEffects,32
emptyStatusEffects,@@ -435,7 +436,7 @@ function drinkItem (world, sessionId, command)435
throw userError("That inventory slot is empty.");436
throw userError("That inventory slot is empty.");436
}437
}437
inventory.slots = consumed.slots;438
inventory.slots = consumed.slots;438
const effectResult = applyPotionEffect(world.ecs, handle, consumed.instance?.effect);439
const effectResult = applyPotionEffect(world.ecs, handle, resolvePotionEffect(consumed.instance));439
return {440
return {440
events: effectResult.events ?? [],441
events: effectResult.events ?? [],441
private: bagView(world.ecs, handle),442
private: bagView(world.ecs, handle),@@ -3,6 +3,7 @@ import { emptyEquipment, emptySlots, insertStack, insertStackGrowable, normalize
3
3
import { itemDefinition, ItemId } from "../../../shared/definitions/items.js";
4
4
import { buildStarterBagContents } from "../../../shared/items/starterLoadout.js";
5
5
import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";
6
import { normalizePlayerSpells, defaultPlayerSpells, storedPlayerSpells } from "../../../shared/spells/state.js";
6
7
7
8
const STATE_SCHEMA = `
8
9
CREATE TABLE IF NOT EXISTS accounts (
@@ -191,6 +192,12 @@ export class StateDatabase
191
192
const courierColumns = this.db.prepare("PRAGMA table_info(courier_transits)").all();
192
193
if (!courierColumns.some((column) => column.name === "vault_character_id"))
193
194
{ this.db.exec("ALTER TABLE courier_transits ADD COLUMN vault_character_id INTEGER"); }
195
if (!bagColumns.some((column) => column.name === "spells_blob"))
196
{
197
this.db.exec("ALTER TABLE character_bags ADD COLUMN spells_blob TEXT NOT NULL DEFAULT '{}'");
198
}
199
if (!characterColumns.some((column) => column.name === "health_current"))
200
{ this.db.exec("ALTER TABLE characters ADD COLUMN health_current INTEGER"); }
194
201
this.#grantLanternsToExistingCharacters();
195
202
}
196
203
@@ -398,6 +405,14 @@ export class StateDatabase
398
405
);
399
406
}
400
407
408
saveCharacterHealth (characterId, current)
409
{
410
this.db.prepare("UPDATE characters SET health_current = ? WHERE character_id = ?").run(
411
Math.max(0, current | 0),
412
characterId
413
);
414
}
415
401
416
setCharacterDead (characterId, isDead)
402
417
{
403
418
this.db.prepare("UPDATE characters SET is_dead = ? WHERE character_id = ?").run(
@@ -675,6 +690,29 @@ export class StateDatabase
675
690
);
676
691
}
677
692
693
getSpells (characterId)
694
{
695
const row = this.db.prepare("SELECT spells_blob FROM character_bags WHERE character_id = ?").get(characterId);
696
if (row)
697
{
698
return normalizePlayerSpells(JSON.parse(row.spells_blob || "{}"));
699
}
700
if (this.getCharacter(characterId))
701
{
702
this.#ensureBag(characterId);
703
return this.getSpells(characterId);
704
}
705
return null;
706
}
707
708
saveSpells (characterId, spells)
709
{
710
this.#ensureBag(characterId);
711
this.db.prepare("UPDATE character_bags SET spells_blob = ? WHERE character_id = ?").run(
712
JSON.stringify(storedPlayerSpells(spells)),
713
characterId
714
);
715
}
678
716
getInheritance (accountId)
679
717
{
680
718
const row = this.db.prepare("SELECT * FROM account_inheritance WHERE account_id = ?").get(accountId);
@@ -3,6 +3,7 @@ import { emptyEquipment, emptySlots, insertStack, insertStackGrowable, normalize3
import { itemDefinition, ItemId } from "../../../shared/definitions/items.js";3
import { itemDefinition, ItemId } from "../../../shared/definitions/items.js";4
import { buildStarterBagContents } from "../../../shared/items/starterLoadout.js";4
import { buildStarterBagContents } from "../../../shared/items/starterLoadout.js";5
import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";5
import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";6
import { normalizePlayerSpells, defaultPlayerSpells, storedPlayerSpells } from "../../../shared/spells/state.js";6
7
7
const STATE_SCHEMA = `8
const STATE_SCHEMA = `8
CREATE TABLE IF NOT EXISTS accounts (9
CREATE TABLE IF NOT EXISTS accounts (@@ -191,6 +192,12 @@ export class StateDatabase191
const courierColumns = this.db.prepare("PRAGMA table_info(courier_transits)").all();192
const courierColumns = this.db.prepare("PRAGMA table_info(courier_transits)").all();192
if (!courierColumns.some((column) => column.name === "vault_character_id"))193
if (!courierColumns.some((column) => column.name === "vault_character_id"))193
{ this.db.exec("ALTER TABLE courier_transits ADD COLUMN vault_character_id INTEGER"); }194
{ this.db.exec("ALTER TABLE courier_transits ADD COLUMN vault_character_id INTEGER"); }195
if (!bagColumns.some((column) => column.name === "spells_blob"))196
{197
this.db.exec("ALTER TABLE character_bags ADD COLUMN spells_blob TEXT NOT NULL DEFAULT '{}'");198
}199
if (!characterColumns.some((column) => column.name === "health_current"))200
{ this.db.exec("ALTER TABLE characters ADD COLUMN health_current INTEGER"); }194
this.#grantLanternsToExistingCharacters();201
this.#grantLanternsToExistingCharacters();195
}202
}196
203
@@ -398,6 +405,14 @@ export class StateDatabase398
);405
);399
}406
}400
407
408
saveCharacterHealth (characterId, current)409
{410
this.db.prepare("UPDATE characters SET health_current = ? WHERE character_id = ?").run(411
Math.max(0, current | 0),412
characterId413
);414
}415
401
setCharacterDead (characterId, isDead)416
setCharacterDead (characterId, isDead)402
{417
{403
this.db.prepare("UPDATE characters SET is_dead = ? WHERE character_id = ?").run(418
this.db.prepare("UPDATE characters SET is_dead = ? WHERE character_id = ?").run(@@ -675,6 +690,29 @@ export class StateDatabase675
);690
);676
}691
}677
692
693
getSpells (characterId)694
{695
const row = this.db.prepare("SELECT spells_blob FROM character_bags WHERE character_id = ?").get(characterId);696
if (row)697
{698
return normalizePlayerSpells(JSON.parse(row.spells_blob || "{}"));699
}700
if (this.getCharacter(characterId))701
{702
this.#ensureBag(characterId);703
return this.getSpells(characterId);704
}705
return null;706
}707
708
saveSpells (characterId, spells)709
{710
this.#ensureBag(characterId);711
this.db.prepare("UPDATE character_bags SET spells_blob = ? WHERE character_id = ?").run(712
JSON.stringify(storedPlayerSpells(spells)),713
characterId714
);715
}678
getInheritance (accountId)716
getInheritance (accountId)679
{717
{680
const row = this.db.prepare("SELECT * FROM account_inheritance WHERE account_id = ?").get(accountId);718
const row = this.db.prepare("SELECT * FROM account_inheritance WHERE account_id = ?").get(accountId);@@ -21,6 +21,7 @@ export const WorkerMessage = Object.freeze({
21
21
inspect: "inspect",
22
22
inspectBag: "inspectBag",
23
23
inspectSkills: "inspectSkills",
24
inspectSpells: "inspectSpells",
24
25
applyBag: "applyBag",
25
26
updateFlight: "updateFlight",
26
27
chunkIsSimulating: "chunkIsSimulating",
@@ -21,6 +21,7 @@ export const WorkerMessage = Object.freeze({21
inspect: "inspect",21
inspect: "inspect",22
inspectBag: "inspectBag",22
inspectBag: "inspectBag",23
inspectSkills: "inspectSkills",23
inspectSkills: "inspectSkills",24
inspectSpells: "inspectSpells",24
applyBag: "applyBag",25
applyBag: "applyBag",25
updateFlight: "updateFlight",26
updateFlight: "updateFlight",26
chunkIsSimulating: "chunkIsSimulating",27
chunkIsSimulating: "chunkIsSimulating",@@ -31,6 +31,7 @@ import { replicationAppearance, replicationDespawn, replicationSpawn } from "../
31
31
import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
32
32
import { mobComponents } from "./spawners.js";
33
33
import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";
34
import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/state.js";
34
35
import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
35
36
import { BlockType } from "../../../shared/definitions/tiles.js";
36
37
import { ItemId } from "../../../shared/definitions/items.js";
@@ -224,6 +225,11 @@ export class Simulation
224
225
events.push(...this.#skillLevelUpEvents(event));
225
226
continue;
226
227
}
228
if (event.type === "spells-updated")
229
{
230
this.#applySpellsUpdated(event);
231
continue;
232
}
227
233
if (event.type === "inventory" && event.characterId)
228
234
{
229
235
this.#saveBagFromView(event.characterId, {
@@ -276,6 +282,11 @@ export class Simulation
276
282
events.push(...this.#skillLevelUpEvents(event));
277
283
continue;
278
284
}
285
if (event.type === "spells-updated")
286
{
287
this.#applySpellsUpdated(event);
288
continue;
289
}
279
290
this.#persistGroundEvent(event);
280
291
if (event.type !== "skills-updated")
281
292
{ events.push(event); }
@@ -347,12 +358,19 @@ export class Simulation
347
358
vaultReserved: []
348
359
};
349
360
const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills();
361
const spells = this.stateDb.getSpells(character.character_id) ?? defaultPlayerSpells();
350
362
// Login floor: Health ≥ 10, every other skill ≥ 1 (persist if raised).
351
363
if (enforceMinimumSkillLevels(skills))
352
364
{ this.stateDb.saveSkills(character.character_id, skills); }
353
365
const maxHealth = playerMaxHealth(skills);
354
366
const maxStamina = playerMaxStamina(skills);
355
367
const isDead = !!row.is_dead;
368
const savedHealth = row.health_current;
369
const currentHealth = isDead
370
? 0
371
: savedHealth != null
372
? Math.max(0, Math.min(maxHealth, savedHealth | 0))
373
: maxHealth;
356
374
const entityId = this.nextEntityId++;
357
375
const components = {
358
376
position: { tileX, tileY },
@@ -376,10 +394,17 @@ export class Simulation
376
394
slots: bag.vault ?? [],
377
395
reserved: bag.vaultReserved ?? []
378
396
},
379
health: { current: isDead ? 0 : maxHealth, max: maxHealth },
397
health: { current: currentHealth, max: maxHealth },
380
398
stamina: { current: maxStamina, max: maxStamina, xpDebt: 0 },
381
399
combat: { targetEntityId: null, nextSwingAt: 0 },
382
400
skills,
401
spells,
402
spellcasting: {
403
armedSpellId: null,
404
repeatSpellId: null,
405
repeatTargetEntityId: null,
406
nextCastAt: 0
407
},
383
408
};
384
409
if (isDead)
385
410
{ components.dead = {}; }
@@ -564,6 +589,15 @@ export class Simulation
564
589
});
565
590
}
566
591
592
pushSpells (characterId, payload)
593
{
594
this.pendingPrivate.push({
595
type: "spells",
596
characterId,
597
...payload
598
});
599
}
600
567
601
skillsOf (entityId)
568
602
{
569
603
const record = this.directory.get(entityId);
@@ -575,6 +609,17 @@ export class Simulation
575
609
});
576
610
}
577
611
612
spellsOf (entityId)
613
{
614
const record = this.directory.get(entityId);
615
if (!record)
616
{ return null; }
617
return this.workers[record.workerId].call({
618
type: WorkerMessage.inspectSpells,
619
entityId
620
});
621
}
622
578
623
staminaOf (entityId)
579
624
{
580
625
const record = this.directory.get(entityId);
@@ -692,6 +737,8 @@ export class Simulation
692
737
dropped.tileY,
693
738
dropped.gait ?? GAIT.walk
694
739
);
740
if (dropped.health != null)
741
{ this.stateDb.saveCharacterHealth(characterId, dropped.health); }
695
742
this.#queueReplication(replicationDespawn(dropped));
696
743
}
697
744
this.#forget(entityId);
@@ -982,7 +1029,16 @@ export class Simulation
982
1029
}
983
1030
for (const event of result?.events ?? [])
984
1031
{ this.#persistGroundEvent(event); }
985
const events = [...(result?.events ?? [])];
1032
const events = [];
1033
for (const event of result?.events ?? [])
1034
{
1035
if (event.type === "spells-updated")
1036
{
1037
this.#applySpellsUpdated(event);
1038
continue;
1039
}
1040
events.push(event);
1041
}
986
1042
if (result?.private)
987
1043
{
988
1044
events.push({
@@ -1040,6 +1096,11 @@ export class Simulation
1040
1096
events.push(...this.#skillLevelUpEvents(event));
1041
1097
continue;
1042
1098
}
1099
if (event.type === "spells-updated")
1100
{
1101
this.#applySpellsUpdated(event);
1102
continue;
1103
}
1043
1104
if (event.type === "player-died")
1044
1105
{
1045
1106
events.push(...this.#applyPlayerDeath(event));
@@ -1096,6 +1157,11 @@ export class Simulation
1096
1157
events.push(...this.#skillLevelUpEvents(event));
1097
1158
continue;
1098
1159
}
1160
if (event.type === "spells-updated")
1161
{
1162
this.#applySpellsUpdated(event);
1163
continue;
1164
}
1099
1165
if (event.type === "player-died")
1100
1166
{
1101
1167
events.push(...this.#applyPlayerDeath(event));
@@ -1241,6 +1307,8 @@ export class Simulation
1241
1307
throw error;
1242
1308
}
1243
1309
this.stateDb.setCharacterDead(characterId, false);
1310
const respawnHealth = playerMaxHealth(skills);
1311
this.stateDb.saveCharacterHealth(characterId, respawnHealth);
1244
1312
this.stateDb.saveCharacterPosition(
1245
1313
characterId,
1246
1314
destination.tileX,
@@ -1827,6 +1895,17 @@ export class Simulation
1827
1895
this.pushSkills(event.characterId, event.skills ?? []);
1828
1896
}
1829
1897
1898
#applySpellsUpdated (event)
1899
{
1900
if (!event?.characterId || !event.stored)
1901
{ return; }
1902
this.stateDb.saveSpells(event.characterId, event.stored);
1903
this.pushSpells(event.characterId, {
1904
spells: event.spells ?? [],
1905
autoCast: !!event.autoCast
1906
});
1907
}
1908
1830
1909
#skillLevelUpEvents (event)
1831
1910
{
1832
1911
const levelUps = event?.levelUps ?? [];
@@ -31,6 +31,7 @@ import { replicationAppearance, replicationDespawn, replicationSpawn } from "../31
import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";31
import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";32
import { mobComponents } from "./spawners.js";32
import { mobComponents } from "./spawners.js";33
import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";33
import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";34
import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/state.js";34
import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";35
import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";35
import { BlockType } from "../../../shared/definitions/tiles.js";36
import { BlockType } from "../../../shared/definitions/tiles.js";36
import { ItemId } from "../../../shared/definitions/items.js";37
import { ItemId } from "../../../shared/definitions/items.js";@@ -224,6 +225,11 @@ export class Simulation224
events.push(...this.#skillLevelUpEvents(event));225
events.push(...this.#skillLevelUpEvents(event));225
continue;226
continue;226
}227
}228
if (event.type === "spells-updated")229
{230
this.#applySpellsUpdated(event);231
continue;232
}227
if (event.type === "inventory" && event.characterId)233
if (event.type === "inventory" && event.characterId)228
{234
{229
this.#saveBagFromView(event.characterId, {235
this.#saveBagFromView(event.characterId, {@@ -276,6 +282,11 @@ export class Simulation276
events.push(...this.#skillLevelUpEvents(event));282
events.push(...this.#skillLevelUpEvents(event));277
continue;283
continue;278
}284
}285
if (event.type === "spells-updated")286
{287
this.#applySpellsUpdated(event);288
continue;289
}279
this.#persistGroundEvent(event);290
this.#persistGroundEvent(event);280
if (event.type !== "skills-updated")291
if (event.type !== "skills-updated")281
{ events.push(event); }292
{ events.push(event); }@@ -347,12 +358,19 @@ export class Simulation347
vaultReserved: []358
vaultReserved: []348
};359
};349
const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills();360
const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills();361
const spells = this.stateDb.getSpells(character.character_id) ?? defaultPlayerSpells();350
// Login floor: Health ≥ 10, every other skill ≥ 1 (persist if raised).362
// Login floor: Health ≥ 10, every other skill ≥ 1 (persist if raised).351
if (enforceMinimumSkillLevels(skills))363
if (enforceMinimumSkillLevels(skills))352
{ this.stateDb.saveSkills(character.character_id, skills); }364
{ this.stateDb.saveSkills(character.character_id, skills); }353
const maxHealth = playerMaxHealth(skills);365
const maxHealth = playerMaxHealth(skills);354
const maxStamina = playerMaxStamina(skills);366
const maxStamina = playerMaxStamina(skills);355
const isDead = !!row.is_dead;367
const isDead = !!row.is_dead;368
const savedHealth = row.health_current;369
const currentHealth = isDead370
? 0371
: savedHealth != null372
? Math.max(0, Math.min(maxHealth, savedHealth | 0))373
: maxHealth;356
const entityId = this.nextEntityId++;374
const entityId = this.nextEntityId++;357
const components = {375
const components = {358
position: { tileX, tileY },376
position: { tileX, tileY },@@ -376,10 +394,17 @@ export class Simulation376
slots: bag.vault ?? [],394
slots: bag.vault ?? [],377
reserved: bag.vaultReserved ?? []395
reserved: bag.vaultReserved ?? []378
},396
},379
health: { current: isDead ? 0 : maxHealth, max: maxHealth },397
health: { current: currentHealth, max: maxHealth },380
stamina: { current: maxStamina, max: maxStamina, xpDebt: 0 },398
stamina: { current: maxStamina, max: maxStamina, xpDebt: 0 },381
combat: { targetEntityId: null, nextSwingAt: 0 },399
combat: { targetEntityId: null, nextSwingAt: 0 },382
skills,400
skills,401
spells,402
spellcasting: {403
armedSpellId: null,404
repeatSpellId: null,405
repeatTargetEntityId: null,406
nextCastAt: 0407
},383
};408
};384
if (isDead)409
if (isDead)385
{ components.dead = {}; }410
{ components.dead = {}; }@@ -564,6 +589,15 @@ export class Simulation564
});589
});565
}590
}566
591
592
pushSpells (characterId, payload)593
{594
this.pendingPrivate.push({595
type: "spells",596
characterId,597
...payload598
});599
}600
567
skillsOf (entityId)601
skillsOf (entityId)568
{602
{569
const record = this.directory.get(entityId);603
const record = this.directory.get(entityId);@@ -575,6 +609,17 @@ export class Simulation575
});609
});576
}610
}577
611
612
spellsOf (entityId)613
{614
const record = this.directory.get(entityId);615
if (!record)616
{ return null; }617
return this.workers[record.workerId].call({618
type: WorkerMessage.inspectSpells,619
entityId620
});621
}622
578
staminaOf (entityId)623
staminaOf (entityId)579
{624
{580
const record = this.directory.get(entityId);625
const record = this.directory.get(entityId);@@ -692,6 +737,8 @@ export class Simulation692
dropped.tileY,737
dropped.tileY,693
dropped.gait ?? GAIT.walk738
dropped.gait ?? GAIT.walk694
);739
);740
if (dropped.health != null)741
{ this.stateDb.saveCharacterHealth(characterId, dropped.health); }695
this.#queueReplication(replicationDespawn(dropped));742
this.#queueReplication(replicationDespawn(dropped));696
}743
}697
this.#forget(entityId);744
this.#forget(entityId);@@ -982,7 +1029,16 @@ export class Simulation982
}1029
}983
for (const event of result?.events ?? [])1030
for (const event of result?.events ?? [])984
{ this.#persistGroundEvent(event); }1031
{ this.#persistGroundEvent(event); }985
const events = [...(result?.events ?? [])];1032
const events = [];1033
for (const event of result?.events ?? [])1034
{1035
if (event.type === "spells-updated")1036
{1037
this.#applySpellsUpdated(event);1038
continue;1039
}1040
events.push(event);1041
}986
if (result?.private)1042
if (result?.private)987
{1043
{988
events.push({1044
events.push({@@ -1040,6 +1096,11 @@ export class Simulation1040
events.push(...this.#skillLevelUpEvents(event));1096
events.push(...this.#skillLevelUpEvents(event));1041
continue;1097
continue;1042
}1098
}1099
if (event.type === "spells-updated")1100
{1101
this.#applySpellsUpdated(event);1102
continue;1103
}1043
if (event.type === "player-died")1104
if (event.type === "player-died")1044
{1105
{1045
events.push(...this.#applyPlayerDeath(event));1106
events.push(...this.#applyPlayerDeath(event));@@ -1096,6 +1157,11 @@ export class Simulation1096
events.push(...this.#skillLevelUpEvents(event));1157
events.push(...this.#skillLevelUpEvents(event));1097
continue;1158
continue;1098
}1159
}1160
if (event.type === "spells-updated")1161
{1162
this.#applySpellsUpdated(event);1163
continue;1164
}1099
if (event.type === "player-died")1165
if (event.type === "player-died")1100
{1166
{1101
events.push(...this.#applyPlayerDeath(event));1167
events.push(...this.#applyPlayerDeath(event));@@ -1241,6 +1307,8 @@ export class Simulation1241
throw error;1307
throw error;1242
}1308
}1243
this.stateDb.setCharacterDead(characterId, false);1309
this.stateDb.setCharacterDead(characterId, false);1310
const respawnHealth = playerMaxHealth(skills);1311
this.stateDb.saveCharacterHealth(characterId, respawnHealth);1244
this.stateDb.saveCharacterPosition(1312
this.stateDb.saveCharacterPosition(1245
characterId,1313
characterId,1246
destination.tileX,1314
destination.tileX,@@ -1827,6 +1895,17 @@ export class Simulation1827
this.pushSkills(event.characterId, event.skills ?? []);1895
this.pushSkills(event.characterId, event.skills ?? []);1828
}1896
}1829
1897
1898
#applySpellsUpdated (event)1899
{1900
if (!event?.characterId || !event.stored)1901
{ return; }1902
this.stateDb.saveSpells(event.characterId, event.stored);1903
this.pushSpells(event.characterId, {1904
spells: event.spells ?? [],1905
autoCast: !!event.autoCast1906
});1907
}1908
1830
#skillLevelUpEvents (event)1909
#skillLevelUpEvents (event)1831
{1910
{1832
const levelUps = event?.levelUps ?? [];1911
const levelUps = event?.levelUps ?? [];@@ -8,10 +8,12 @@ import {
8
8
MobId,
9
9
spawnerEquipmentSlot
10
10
} from "../../../shared/definitions/mobs.js";
11
import { LeatherItemId } from "../../../shared/definitions/leatherItems.js";
11
12
import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";
12
13
import { emptyEquipment } from "../../../shared/items/inventory.js";
13
14
import { itemDefinition } from "../../../shared/definitions/items.js";
14
15
import { appearanceHairFields, hairFromNameSeed } from "../../../shared/appearance/hair.js";
16
import { npcDefaultEquipment } from "../../../shared/appearance/npcEquipment.js";
15
17
import { Component } from "../ecs/components.js";
16
18
import { tileToChunk, tileToRegion } from "../world/coordinates.js";
17
19
@@ -171,9 +173,16 @@ export function mobComponents (request)
171
173
172
174
const equipmentSlots = emptyEquipment().slots;
173
175
const authored = request.equipment ?? {};
176
const defaults = def.usePlayerBody ? npcDefaultEquipment(displayName, sex) : null;
174
177
for (const slot of Object.keys(equipmentSlots))
175
178
{
176
const { itemId, dyeColor } = spawnerEquipmentSlot(authored[slot]);
179
const authoredEntry = authored[slot];
180
let { itemId, dyeColor } = spawnerEquipmentSlot(authoredEntry);
181
if (!itemId && defaults?.[slot])
182
{
183
itemId = defaults[slot].itemId;
184
dyeColor = defaults[slot].dyeColor ?? null;
185
}
177
186
if (!itemId)
178
187
{ continue; }
179
188
const itemDef = itemDefinition(itemId);
@@ -8,10 +8,12 @@ import {8
MobId,8
MobId,9
spawnerEquipmentSlot9
spawnerEquipmentSlot10
} from "../../../shared/definitions/mobs.js";10
} from "../../../shared/definitions/mobs.js";11
import { LeatherItemId } from "../../../shared/definitions/leatherItems.js";11
import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";12
import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";12
import { emptyEquipment } from "../../../shared/items/inventory.js";13
import { emptyEquipment } from "../../../shared/items/inventory.js";13
import { itemDefinition } from "../../../shared/definitions/items.js";14
import { itemDefinition } from "../../../shared/definitions/items.js";14
import { appearanceHairFields, hairFromNameSeed } from "../../../shared/appearance/hair.js";15
import { appearanceHairFields, hairFromNameSeed } from "../../../shared/appearance/hair.js";16
import { npcDefaultEquipment } from "../../../shared/appearance/npcEquipment.js";15
import { Component } from "../ecs/components.js";17
import { Component } from "../ecs/components.js";16
import { tileToChunk, tileToRegion } from "../world/coordinates.js";18
import { tileToChunk, tileToRegion } from "../world/coordinates.js";17
19
@@ -171,9 +173,16 @@ export function mobComponents (request)171
173
172
const equipmentSlots = emptyEquipment().slots;174
const equipmentSlots = emptyEquipment().slots;173
const authored = request.equipment ?? {};175
const authored = request.equipment ?? {};176
const defaults = def.usePlayerBody ? npcDefaultEquipment(displayName, sex) : null;174
for (const slot of Object.keys(equipmentSlots))177
for (const slot of Object.keys(equipmentSlots))175
{178
{176
const { itemId, dyeColor } = spawnerEquipmentSlot(authored[slot]);179
const authoredEntry = authored[slot];180
let { itemId, dyeColor } = spawnerEquipmentSlot(authoredEntry);181
if (!itemId && defaults?.[slot])182
{183
itemId = defaults[slot].itemId;184
dyeColor = defaults[slot].dyeColor ?? null;185
}177
if (!itemId)186
if (!itemId)178
{ continue; }187
{ continue; }179
const itemDef = itemDefinition(itemId);188
const itemDef = itemDefinition(itemId);@@ -9,7 +9,7 @@ import {
9
9
tileToLocal,
10
10
tileToRegion
11
11
} from "../world/coordinates.js";
12
import { cloneChunkData, createEmptyChunkData, isChunkTilePassable } from "../world/chunkData.js";
12
import { cloneChunkData, createEmptyChunkData, isChunkTilePassable, isChunkTileClearForRangedAttacks } from "../world/chunkData.js";
13
13
import { closedNeighborEdges } from "../world/chunkFlags.js";
14
14
import { EcsWorld } from "../ecs/world.js";
15
15
import { Component } from "../ecs/components.js";
@@ -30,7 +30,8 @@ import {
30
30
publicGroundItem,
31
31
setGroundItemsForRegion
32
32
} from "../items/bags.js";
33
import { handleAlchemyCommand } from "../alchemy/service.js";
33
import { handleSpellCommand, processSpellImpacts, stepPendingSpellCast, stepSpellAutoCast, tickSpellLights } from "../spells/service.js";
34
import { publicSpellsView } from "../../../shared/spells/state.js";
34
35
import {
35
36
handleGatherCommand,
36
37
stepGather,
@@ -40,14 +41,18 @@ import {
40
41
clearPlantRespawnsForChunk
41
42
} from "../gathering/service.js";
42
43
import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
44
import { handleAlchemyCommand } from "../alchemy/service.js";
43
45
import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
44
46
import {
45
47
applyRemoteMeleeSwing,
46
48
applyRemoteRangedShot,
49
attackProfileOf,
47
50
clearEngage,
48
51
engageTarget,
49
52
ensureMobCombat,
50
53
isUntargetable,
54
queueMeleeApproach,
55
queueStandInRangeApproach,
51
56
resolveCombatTarget,
52
57
stepAggression,
53
58
stepCombat
@@ -82,6 +87,7 @@ export class WorkerWorld
82
87
this.groundByTile = new Map();
83
88
this.oreRespawns = new Map();
84
89
this.treeRespawns = new Map();
90
this.pendingSpellImpacts = [];
85
91
this.settings = { ...DEFAULT_WORLD_SETTINGS };
86
92
this.activeRevisionId = 1;
87
93
}
@@ -125,6 +131,8 @@ export class WorkerWorld
125
131
return this.#inspectBag(message.entityId);
126
132
case WorkerMessage.inspectSkills:
127
133
return this.#inspectSkills(message.entityId);
134
case WorkerMessage.inspectSpells:
135
return this.#inspectSpells(message.entityId);
128
136
case WorkerMessage.inspectStamina:
129
137
return this.#inspectStamina(message.entityId);
130
138
case WorkerMessage.applyBag:
@@ -418,6 +426,14 @@ export class WorkerWorld
418
426
return this.#follow(sessionId, command.characterId, command.targetEntityId);
419
427
case "cancel-follow":
420
428
return this.#cancelFollow(sessionId, command.characterId);
429
case "set-spell-favorite":
430
case "set-spell-autocast":
431
case "arm-spell":
432
case "cancel-arm-spell":
433
case "cast-spell-tile":
434
case "cast-spell-entity":
435
case "read-spellbook":
436
return handleSpellCommand(this, sessionId, command, message.now ?? Date.now()) ?? { events: [] };
421
437
default:
422
438
{
423
439
const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now());
@@ -554,6 +570,23 @@ export class WorkerWorld
554
570
return skills;
555
571
}
556
572
573
#inspectSpells (entityId)
574
{
575
const handle = this.ecs.handleOf(entityId);
576
if (handle == null)
577
{ return null; }
578
const spells = this.ecs.get(handle, Component.spells);
579
const skills = this.ecs.get(handle, Component.skills);
580
const casting = this.ecs.get(handle, Component.spellcasting);
581
if (!spells)
582
{ return null; }
583
return {
584
spells: publicSpellsView(spells, skills),
585
autoCast: !!spells.autoCast,
586
armedSpellId: casting?.armedSpellId ?? null
587
};
588
}
589
557
590
#inspectStamina (entityId)
558
591
{
559
592
const handle = this.ecs.handleOf(entityId);
@@ -653,6 +686,9 @@ export class WorkerWorld
653
686
clearEngage(this.ecs, entityId);
654
687
clearFollow(this.ecs, entityId);
655
688
cancelGather(this.ecs, handle);
689
const casting = this.ecs.get(handle, Component.spellcasting);
690
if (casting)
691
{ casting.pendingCast = null; }
656
692
const position = this.ecs.get(handle, Component.position);
657
693
const movement = this.ecs.get(handle, Component.movement);
658
694
let path = this.ecs.get(handle, Component.path);
@@ -700,11 +736,29 @@ export class WorkerWorld
700
736
{ this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
701
737
clearFollow(this.ecs, entityId);
702
738
cancelGather(this.ecs, handle);
703
// Engage only the attacker. Targets retaliate on the first resolved swing.
704
739
engageTarget(this.ecs, entityId, targetEntityId, now);
705
const path = this.ecs.get(handle, Component.path);
706
if (path)
707
{ path.tiles = []; }
740
const position = this.ecs.get(handle, Component.position);
741
const profile = attackProfileOf(this.ecs, handle);
742
if (position && target.pos)
743
{
744
if (profile.mode === "ranged")
745
{
746
queueStandInRangeApproach(
747
this,
748
entityId,
749
handle,
750
position,
751
target.pos.tileX,
752
target.pos.tileY,
753
profile.rangeTiles | 0 || COMBAT_RANGE_TILES,
754
1
755
);
756
}
757
else if (profile.mode === "melee")
758
{
759
queueMeleeApproach(this, entityId, handle, position, target.pos);
760
}
761
}
708
762
return { events: [] };
709
763
}
710
764
@@ -991,6 +1045,10 @@ export class WorkerWorld
991
1045
}
992
1046
stepAggression(this, now);
993
1047
events.push(...stepCombat(this, now));
1048
events.push(...stepPendingSpellCast(this, now));
1049
events.push(...processSpellImpacts(this, now));
1050
events.push(...stepSpellAutoCast(this, now));
1051
events.push(...tickSpellLights(this, now));
994
1052
stepFollow(this);
995
1053
const gather = stepGather(this, now);
996
1054
events.push(...gather.events);
@@ -1154,7 +1212,7 @@ export class WorkerWorld
1154
1212
position.tileY,
1155
1213
goal.x,
1156
1214
goal.y,
1157
(x, y) => this.walkableFor(entityId, x, y),
1215
(x, y) => this.isClearStanding(entityId, x, y),
1158
1216
bounds.minX,
1159
1217
bounds.minY,
1160
1218
bounds.maxX,
@@ -1585,6 +1643,14 @@ export class WorkerWorld
1585
1643
return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
1586
1644
}
1587
1645
1646
isClearForRangedAttack (tileX, tileY)
1647
{
1648
const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
1649
if (!data.open)
1650
{ return false; }
1651
return isChunkTileClearForRangedAttacks(data, tileToLocal(tileX), tileToLocal(tileY));
1652
}
1653
1588
1654
#walkableFor (entityId, tileX, tileY)
1589
1655
{
1590
1656
return this.walkableFor(entityId, tileX, tileY);
@@ -9,7 +9,7 @@ import {9
tileToLocal,9
tileToLocal,10
tileToRegion10
tileToRegion11
} from "../world/coordinates.js";11
} from "../world/coordinates.js";12
import { cloneChunkData, createEmptyChunkData, isChunkTilePassable } from "../world/chunkData.js";12
import { cloneChunkData, createEmptyChunkData, isChunkTilePassable, isChunkTileClearForRangedAttacks } from "../world/chunkData.js";13
import { closedNeighborEdges } from "../world/chunkFlags.js";13
import { closedNeighborEdges } from "../world/chunkFlags.js";14
import { EcsWorld } from "../ecs/world.js";14
import { EcsWorld } from "../ecs/world.js";15
import { Component } from "../ecs/components.js";15
import { Component } from "../ecs/components.js";@@ -30,7 +30,8 @@ import {30
publicGroundItem,30
publicGroundItem,31
setGroundItemsForRegion31
setGroundItemsForRegion32
} from "../items/bags.js";32
} from "../items/bags.js";33
import { handleAlchemyCommand } from "../alchemy/service.js";33
import { handleSpellCommand, processSpellImpacts, stepPendingSpellCast, stepSpellAutoCast, tickSpellLights } from "../spells/service.js";34
import { publicSpellsView } from "../../../shared/spells/state.js";34
import {35
import {35
handleGatherCommand,36
handleGatherCommand,36
stepGather,37
stepGather,@@ -40,14 +41,18 @@ import {40
clearPlantRespawnsForChunk41
clearPlantRespawnsForChunk41
} from "../gathering/service.js";42
} from "../gathering/service.js";42
import { handleCraftCommand, stepCrafting } from "../crafting/service.js";43
import { handleCraftCommand, stepCrafting } from "../crafting/service.js";44
import { handleAlchemyCommand } from "../alchemy/service.js";43
import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";45
import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";44
import {46
import {45
applyRemoteMeleeSwing,47
applyRemoteMeleeSwing,46
applyRemoteRangedShot,48
applyRemoteRangedShot,49
attackProfileOf,47
clearEngage,50
clearEngage,48
engageTarget,51
engageTarget,49
ensureMobCombat,52
ensureMobCombat,50
isUntargetable,53
isUntargetable,54
queueMeleeApproach,55
queueStandInRangeApproach,51
resolveCombatTarget,56
resolveCombatTarget,52
stepAggression,57
stepAggression,53
stepCombat58
stepCombat@@ -82,6 +87,7 @@ export class WorkerWorld82
this.groundByTile = new Map();87
this.groundByTile = new Map();83
this.oreRespawns = new Map();88
this.oreRespawns = new Map();84
this.treeRespawns = new Map();89
this.treeRespawns = new Map();90
this.pendingSpellImpacts = [];85
this.settings = { ...DEFAULT_WORLD_SETTINGS };91
this.settings = { ...DEFAULT_WORLD_SETTINGS };86
this.activeRevisionId = 1;92
this.activeRevisionId = 1;87
}93
}@@ -125,6 +131,8 @@ export class WorkerWorld125
return this.#inspectBag(message.entityId);131
return this.#inspectBag(message.entityId);126
case WorkerMessage.inspectSkills:132
case WorkerMessage.inspectSkills:127
return this.#inspectSkills(message.entityId);133
return this.#inspectSkills(message.entityId);134
case WorkerMessage.inspectSpells:135
return this.#inspectSpells(message.entityId);128
case WorkerMessage.inspectStamina:136
case WorkerMessage.inspectStamina:129
return this.#inspectStamina(message.entityId);137
return this.#inspectStamina(message.entityId);130
case WorkerMessage.applyBag:138
case WorkerMessage.applyBag:@@ -418,6 +426,14 @@ export class WorkerWorld418
return this.#follow(sessionId, command.characterId, command.targetEntityId);426
return this.#follow(sessionId, command.characterId, command.targetEntityId);419
case "cancel-follow":427
case "cancel-follow":420
return this.#cancelFollow(sessionId, command.characterId);428
return this.#cancelFollow(sessionId, command.characterId);429
case "set-spell-favorite":430
case "set-spell-autocast":431
case "arm-spell":432
case "cancel-arm-spell":433
case "cast-spell-tile":434
case "cast-spell-entity":435
case "read-spellbook":436
return handleSpellCommand(this, sessionId, command, message.now ?? Date.now()) ?? { events: [] };421
default:437
default:422
{438
{423
const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now());439
const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now());@@ -554,6 +570,23 @@ export class WorkerWorld554
return skills;570
return skills;555
}571
}556
572
573
#inspectSpells (entityId)574
{575
const handle = this.ecs.handleOf(entityId);576
if (handle == null)577
{ return null; }578
const spells = this.ecs.get(handle, Component.spells);579
const skills = this.ecs.get(handle, Component.skills);580
const casting = this.ecs.get(handle, Component.spellcasting);581
if (!spells)582
{ return null; }583
return {584
spells: publicSpellsView(spells, skills),585
autoCast: !!spells.autoCast,586
armedSpellId: casting?.armedSpellId ?? null587
};588
}589
557
#inspectStamina (entityId)590
#inspectStamina (entityId)558
{591
{559
const handle = this.ecs.handleOf(entityId);592
const handle = this.ecs.handleOf(entityId);@@ -653,6 +686,9 @@ export class WorkerWorld653
clearEngage(this.ecs, entityId);686
clearEngage(this.ecs, entityId);654
clearFollow(this.ecs, entityId);687
clearFollow(this.ecs, entityId);655
cancelGather(this.ecs, handle);688
cancelGather(this.ecs, handle);689
const casting = this.ecs.get(handle, Component.spellcasting);690
if (casting)691
{ casting.pendingCast = null; }656
const position = this.ecs.get(handle, Component.position);692
const position = this.ecs.get(handle, Component.position);657
const movement = this.ecs.get(handle, Component.movement);693
const movement = this.ecs.get(handle, Component.movement);658
let path = this.ecs.get(handle, Component.path);694
let path = this.ecs.get(handle, Component.path);@@ -700,11 +736,29 @@ export class WorkerWorld700
{ this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }736
{ this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }701
clearFollow(this.ecs, entityId);737
clearFollow(this.ecs, entityId);702
cancelGather(this.ecs, handle);738
cancelGather(this.ecs, handle);703
// Engage only the attacker. Targets retaliate on the first resolved swing.704
engageTarget(this.ecs, entityId, targetEntityId, now);739
engageTarget(this.ecs, entityId, targetEntityId, now);705
const path = this.ecs.get(handle, Component.path);740
const position = this.ecs.get(handle, Component.position);706
if (path)741
const profile = attackProfileOf(this.ecs, handle);707
{ path.tiles = []; }742
if (position && target.pos)743
{744
if (profile.mode === "ranged")745
{746
queueStandInRangeApproach(747
this,748
entityId,749
handle,750
position,751
target.pos.tileX,752
target.pos.tileY,753
profile.rangeTiles | 0 || COMBAT_RANGE_TILES,754
1755
);756
}757
else if (profile.mode === "melee")758
{759
queueMeleeApproach(this, entityId, handle, position, target.pos);760
}761
}708
return { events: [] };762
return { events: [] };709
}763
}710
764
@@ -991,6 +1045,10 @@ export class WorkerWorld991
}1045
}992
stepAggression(this, now);1046
stepAggression(this, now);993
events.push(...stepCombat(this, now));1047
events.push(...stepCombat(this, now));1048
events.push(...stepPendingSpellCast(this, now));1049
events.push(...processSpellImpacts(this, now));1050
events.push(...stepSpellAutoCast(this, now));1051
events.push(...tickSpellLights(this, now));994
stepFollow(this);1052
stepFollow(this);995
const gather = stepGather(this, now);1053
const gather = stepGather(this, now);996
events.push(...gather.events);1054
events.push(...gather.events);@@ -1154,7 +1212,7 @@ export class WorkerWorld1154
position.tileY,1212
position.tileY,1155
goal.x,1213
goal.x,1156
goal.y,1214
goal.y,1157
(x, y) => this.walkableFor(entityId, x, y),1215
(x, y) => this.isClearStanding(entityId, x, y),1158
bounds.minX,1216
bounds.minX,1159
bounds.minY,1217
bounds.minY,1160
bounds.maxX,1218
bounds.maxX,@@ -1585,6 +1643,14 @@ export class WorkerWorld1585
return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));1643
return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));1586
}1644
}1587
1645
1646
isClearForRangedAttack (tileX, tileY)1647
{1648
const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));1649
if (!data.open)1650
{ return false; }1651
return isChunkTileClearForRangedAttacks(data, tileToLocal(tileX), tileToLocal(tileY));1652
}1653
1588
#walkableFor (entityId, tileX, tileY)1654
#walkableFor (entityId, tileX, tileY)1589
{1655
{1590
return this.walkableFor(entityId, tileX, tileY);1656
return this.walkableFor(entityId, tileX, tileY);@@ -0,0 +1,168 @@
1
import { Component } from "../ecs/components.js";
2
import { tileKey } from "../world/coordinates.js";
3
import {
4
LIGHT_FADE_MS,
5
LIGHT_MAX_DURATION_MS,
6
LIGHT_OWNER_DISTANCE_CAP_MS,
7
SPELL_LIGHT_INTENSITY,
8
SPELL_LIGHT_RANGE_TILES,
9
COMBAT_RANGE_TILES
10
} from "../../../shared/spells/constants.js";
11
12
/**
13
* Authoritative temporary spell lights keyed by tile.
14
* @typedef {object} SpellLight
15
* @property {number} tileX
16
* @property {number} tileY
17
* @property {number} ownerEntityId
18
* @property {number} expiresAt
19
* @property {number} maxDurationMs
20
* @property {number} baseRange
21
* @property {number} baseIntensity
22
*/
23
24
export class SpellLightRegistry
25
{
26
constructor ()
27
{
28
/** @type {Map<string, SpellLight>} */
29
this.byTile = new Map();
30
this.nextLightId = 1;
31
}
32
33
getAt (tileX, tileY)
34
{
35
return this.byTile.get(tileKey(tileX, tileY)) ?? null;
36
}
37
38
/** @returns {{ light: SpellLight, extended: boolean }} */
39
placeOrExtend ({
40
tileX,
41
tileY,
42
ownerEntityId,
43
durationMs,
44
now = Date.now()
45
})
46
{
47
const key = tileKey(tileX, tileY);
48
const addMs = Math.max(0, Math.min(LIGHT_MAX_DURATION_MS, durationMs | 0));
49
const existing = this.byTile.get(key);
50
if (existing)
51
{
52
const remaining = Math.max(0, existing.expiresAt - now);
53
const next = Math.min(LIGHT_MAX_DURATION_MS, remaining + addMs);
54
existing.expiresAt = now + next;
55
existing.maxDurationMs = Math.max(existing.maxDurationMs, next);
56
existing.ownerEntityId = ownerEntityId;
57
return { light: existing, extended: true };
58
}
59
const light = {
60
lightId: this.nextLightId++,
61
tileX,
62
tileY,
63
ownerEntityId,
64
expiresAt: now + addMs,
65
maxDurationMs: addMs,
66
baseRange: SPELL_LIGHT_RANGE_TILES,
67
baseIntensity: SPELL_LIGHT_INTENSITY
68
};
69
this.byTile.set(key, light);
70
return { light, extended: false };
71
}
72
73
removeAt (tileX, tileY)
74
{
75
const key = tileKey(tileX, tileY);
76
const existing = this.byTile.get(key);
77
if (!existing)
78
{ return null; }
79
this.byTile.delete(key);
80
return existing;
81
}
82
83
/** Tick ownership distance penalty and expiry. Returns replication events. */
84
tick (world, now = Date.now())
85
{
86
const events = [];
87
for (const [, light] of [...this.byTile.entries()])
88
{
89
if (now >= light.expiresAt)
90
{
91
this.byTile.delete(tileKey(light.tileX, light.tileY));
92
events.push({ type: "spell-light-remove", tileX: light.tileX, tileY: light.tileY });
93
continue;
94
}
95
const ownerHandle = world.ecs.handleOf(light.ownerEntityId);
96
const ownerPos = ownerHandle != null ? world.ecs.get(ownerHandle, Component.position) : null;
97
if (ownerPos)
98
{
99
const dist = Math.max(
100
Math.abs(ownerPos.tileX - light.tileX),
101
Math.abs(ownerPos.tileY - light.tileY)
102
);
103
if (dist > COMBAT_RANGE_TILES)
104
{
105
const remaining = light.expiresAt - now;
106
const capped = Math.min( remaining, LIGHT_OWNER_DISTANCE_CAP_MS);
107
if (capped !== remaining)
108
{
109
light.expiresAt = now + capped;
110
events.push({ type: "spell-light-update", ...publicSpellLight(light, now) });
111
}
112
}
113
}
114
}
115
return events;
116
}
117
118
listInBounds (minX, minY, maxX, maxY, now = Date.now())
119
{
120
const out = [];
121
for (const light of this.byTile.values())
122
{
123
if (light.tileX < minX || light.tileX > maxX || light.tileY < minY || light.tileY > maxY)
124
{ continue; }
125
if (now >= light.expiresAt)
126
{ continue; }
127
out.push(publicSpellLight(light, now));
128
}
129
return out;
130
}
131
}
132
133
export function publicSpellLight (light, now = Date.now())
134
{
135
const remainingMs = Math.max(0, light.expiresAt - now);
136
const fadeT = remainingMs <= LIGHT_FADE_MS ? remainingMs / LIGHT_FADE_MS : 1;
137
const range = light.baseRange * fadeT;
138
const intensity = light.baseIntensity * fadeT;
139
return {
140
tileX: light.tileX,
141
tileY: light.tileY,
142
ownerEntityId: light.ownerEntityId,
143
remainingMs,
144
rangeTiles: range,
145
intensity,
146
expiresAt: light.expiresAt
147
};
148
}
149
150
export function spellLightsForDynamicLighting (registry, now = Date.now())
151
{
152
const out = [];
153
for (const light of registry.byTile.values())
154
{
155
if (now >= light.expiresAt)
156
{ continue; }
157
const pub = publicSpellLight(light, now);
158
if (pub.intensity <= 0 || pub.rangeTiles <= 0)
159
{ continue; }
160
out.push({
161
tileX: light.tileX,
162
tileY: light.tileY,
163
range: pub.rangeTiles,
164
intensity: pub.intensity
165
});
166
}
167
return out;
168
}
@@ -0,0 +1,168 @@1
import { Component } from "../ecs/components.js";2
import { tileKey } from "../world/coordinates.js";3
import {4
LIGHT_FADE_MS,5
LIGHT_MAX_DURATION_MS,6
LIGHT_OWNER_DISTANCE_CAP_MS,7
SPELL_LIGHT_INTENSITY,8
SPELL_LIGHT_RANGE_TILES,9
COMBAT_RANGE_TILES10
} from "../../../shared/spells/constants.js";11
12
/**13
* Authoritative temporary spell lights keyed by tile.14
* @typedef {object} SpellLight15
* @property {number} tileX16
* @property {number} tileY17
* @property {number} ownerEntityId18
* @property {number} expiresAt19
* @property {number} maxDurationMs20
* @property {number} baseRange21
* @property {number} baseIntensity22
*/23
24
export class SpellLightRegistry25
{26
constructor ()27
{28
/** @type {Map<string, SpellLight>} */29
this.byTile = new Map();30
this.nextLightId = 1;31
}32
33
getAt (tileX, tileY)34
{35
return this.byTile.get(tileKey(tileX, tileY)) ?? null;36
}37
38
/** @returns {{ light: SpellLight, extended: boolean }} */39
placeOrExtend ({40
tileX,41
tileY,42
ownerEntityId,43
durationMs,44
now = Date.now()45
})46
{47
const key = tileKey(tileX, tileY);48
const addMs = Math.max(0, Math.min(LIGHT_MAX_DURATION_MS, durationMs | 0));49
const existing = this.byTile.get(key);50
if (existing)51
{52
const remaining = Math.max(0, existing.expiresAt - now);53
const next = Math.min(LIGHT_MAX_DURATION_MS, remaining + addMs);54
existing.expiresAt = now + next;55
existing.maxDurationMs = Math.max(existing.maxDurationMs, next);56
existing.ownerEntityId = ownerEntityId;57
return { light: existing, extended: true };58
}59
const light = {60
lightId: this.nextLightId++,61
tileX,62
tileY,63
ownerEntityId,64
expiresAt: now + addMs,65
maxDurationMs: addMs,66
baseRange: SPELL_LIGHT_RANGE_TILES,67
baseIntensity: SPELL_LIGHT_INTENSITY68
};69
this.byTile.set(key, light);70
return { light, extended: false };71
}72
73
removeAt (tileX, tileY)74
{75
const key = tileKey(tileX, tileY);76
const existing = this.byTile.get(key);77
if (!existing)78
{ return null; }79
this.byTile.delete(key);80
return existing;81
}82
83
/** Tick ownership distance penalty and expiry. Returns replication events. */84
tick (world, now = Date.now())85
{86
const events = [];87
for (const [, light] of [...this.byTile.entries()])88
{89
if (now >= light.expiresAt)90
{91
this.byTile.delete(tileKey(light.tileX, light.tileY));92
events.push({ type: "spell-light-remove", tileX: light.tileX, tileY: light.tileY });93
continue;94
}95
const ownerHandle = world.ecs.handleOf(light.ownerEntityId);96
const ownerPos = ownerHandle != null ? world.ecs.get(ownerHandle, Component.position) : null;97
if (ownerPos)98
{99
const dist = Math.max(100
Math.abs(ownerPos.tileX - light.tileX),101
Math.abs(ownerPos.tileY - light.tileY)102
);103
if (dist > COMBAT_RANGE_TILES)104
{105
const remaining = light.expiresAt - now;106
const capped = Math.min( remaining, LIGHT_OWNER_DISTANCE_CAP_MS);107
if (capped !== remaining)108
{109
light.expiresAt = now + capped;110
events.push({ type: "spell-light-update", ...publicSpellLight(light, now) });111
}112
}113
}114
}115
return events;116
}117
118
listInBounds (minX, minY, maxX, maxY, now = Date.now())119
{120
const out = [];121
for (const light of this.byTile.values())122
{123
if (light.tileX < minX || light.tileX > maxX || light.tileY < minY || light.tileY > maxY)124
{ continue; }125
if (now >= light.expiresAt)126
{ continue; }127
out.push(publicSpellLight(light, now));128
}129
return out;130
}131
}132
133
export function publicSpellLight (light, now = Date.now())134
{135
const remainingMs = Math.max(0, light.expiresAt - now);136
const fadeT = remainingMs <= LIGHT_FADE_MS ? remainingMs / LIGHT_FADE_MS : 1;137
const range = light.baseRange * fadeT;138
const intensity = light.baseIntensity * fadeT;139
return {140
tileX: light.tileX,141
tileY: light.tileY,142
ownerEntityId: light.ownerEntityId,143
remainingMs,144
rangeTiles: range,145
intensity,146
expiresAt: light.expiresAt147
};148
}149
150
export function spellLightsForDynamicLighting (registry, now = Date.now())151
{152
const out = [];153
for (const light of registry.byTile.values())154
{155
if (now >= light.expiresAt)156
{ continue; }157
const pub = publicSpellLight(light, now);158
if (pub.intensity <= 0 || pub.rangeTiles <= 0)159
{ continue; }160
out.push({161
tileX: light.tileX,162
tileY: light.tileY,163
range: pub.rangeTiles,164
intensity: pub.intensity165
});166
}167
return out;168
}@@ -0,0 +1,707 @@
1
import { Component } from "../ecs/components.js";
2
import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
3
import { SpellId, spellDefinition, spellDifficulty } from "../../../shared/definitions/spells.js";
4
import {
5
canCastSpell,
6
defaultPlayerSpells,
7
normalizePlayerSpells,
8
publicSpellsView,
9
storedPlayerSpells,
10
toggleFavorite,
11
learnSpell
12
} from "../../../shared/spells/state.js";
13
import {
14
CAST_FLASH_MS,
15
COMBAT_RANGE_TILES,
16
LIGHT_DURATION_MS_PER_MIND,
17
SPELL_COOLDOWN_MS,
18
SPELL_PROJECTILE_MS,
19
castFlashRadiusTiles
20
} from "../../../shared/spells/constants.js";
21
import {
22
mobElementAffinities,
23
ElementMultiplier,
24
resolveMagicAttack,
25
resolveSpellCast,
26
resolveSpellPotency
27
} from "../../../shared/combat/magic.js";
28
import { mobDefinition } from "../../../shared/definitions/mobs.js";
29
import { awardCombatHitXp, awardDamageHealthXp, awardSpellCastXp, syncPlayerHealth } from "../skills/service.js";
30
import {
31
chebyshev,
32
hasCombatLineOfSight,
33
queueStandInRangeApproach,
34
resolveCombatTarget
35
} from "../combat/service.js";
36
import { publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
37
import { spellCastXpFromDifficulty } from "../../../shared/skills/progression.js";
38
import { publicSpellLight, SpellLightRegistry } from "./lights.js";
39
import { SpellbookItemId, spellbookInstance } from "../../../shared/definitions/spellItems.js";
40
import { bagView } from "../items/bags.js";
41
42
const MAGIC_ATTACK_PROFILE = Object.freeze({
43
hitSkillId: SkillId.magic,
44
damageSkillId: SkillId.mind
45
});
46
47
export function ensureSpellComponents (ecs, handle, storedSpells = null)
48
{
49
if (!ecs.get(handle, Component.spells))
50
{
51
ecs.add(handle, Component.spells, normalizePlayerSpells(storedSpells ?? defaultPlayerSpells()));
52
}
53
if (!ecs.get(handle, Component.spellcasting))
54
{
55
ecs.add(handle, Component.spellcasting, {
56
armedSpellId: null,
57
repeatSpellId: null,
58
repeatTargetEntityId: null,
59
nextCastAt: 0
60
});
61
}
62
}
63
64
export function handleSpellCommand (world, sessionId, command, now = Date.now())
65
{
66
switch (command.type)
67
{
68
case "set-spell-favorite":
69
return setSpellFavorite(world, sessionId, command, now);
70
case "set-spell-autocast":
71
return setSpellAutoCast(world, sessionId, command, now);
72
case "arm-spell":
73
return armSpell(world, sessionId, command, now);
74
case "cancel-arm-spell":
75
return cancelArmSpell(world, sessionId, command, now);
76
case "cast-spell-tile":
77
return castSpellAtTile(world, sessionId, command, now);
78
case "cast-spell-entity":
79
return castSpellAtEntity(world, sessionId, command, now);
80
case "read-spellbook":
81
return readSpellbook(world, sessionId, command, now);
82
default:
83
return null;
84
}
85
}
86
87
function requirePlayer (world, sessionId, characterId)
88
{
89
for (const entity of world.ecs.query(Component.networkIdentity, Component.character))
90
{
91
if (entity.networkIdentity.sessionId !== sessionId)
92
{ continue; }
93
if (entity.character.characterId !== characterId)
94
{ continue; }
95
return { handle: entity.handle, entityId: entity.entityId, character: entity.character };
96
}
97
const error = new Error("Character not found.");
98
error.userFacing = true;
99
throw error;
100
}
101
102
function spellsUpdatedEvent (entityId, characterId, spells, skills, levelUps = [])
103
{
104
return {
105
type: "spells-updated",
106
entityId,
107
characterId,
108
spells: publicSpellsView(spells, skills),
109
stored: storedPlayerSpells(spells),
110
autoCast: !!spells.autoCast,
111
levelUps
112
};
113
}
114
115
function setSpellFavorite (world, sessionId, command, now)
116
{
117
const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
118
ensureSpellComponents(world.ecs, handle);
119
const skills = world.ecs.get(handle, Component.skills);
120
const spells = world.ecs.get(handle, Component.spells);
121
const result = toggleFavorite(spells, command.spellId, skills);
122
if (result.error)
123
{
124
const error = new Error(result.error);
125
error.userFacing = true;
126
throw error;
127
}
128
Object.assign(spells, result.spells);
129
const events = [];
130
if (result.changed)
131
{
132
events.push(spellsUpdatedEvent(entityId, character.characterId, spells, skills));
133
}
134
return { events };
135
}
136
137
function setSpellAutoCast (world, sessionId, command, now)
138
{
139
const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
140
ensureSpellComponents(world.ecs, handle);
141
const skills = world.ecs.get(handle, Component.skills);
142
const spells = world.ecs.get(handle, Component.spells);
143
spells.autoCast = !!command.enabled;
144
const casting = world.ecs.get(handle, Component.spellcasting);
145
if (!spells.autoCast)
146
{
147
casting.repeatSpellId = null;
148
casting.repeatTargetEntityId = null;
149
}
150
return {
151
events: [spellsUpdatedEvent(entityId, character.characterId, spells, skills)]
152
};
153
}
154
155
function armSpell (world, sessionId, command, now)
156
{
157
const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
158
ensureSpellComponents(world.ecs, handle);
159
const skills = world.ecs.get(handle, Component.skills);
160
const spells = world.ecs.get(handle, Component.spells);
161
const check = canCastSpell(skills, spells, command.spellId);
162
if (!check.ok)
163
{
164
const error = new Error(check.reason);
165
error.userFacing = true;
166
throw error;
167
}
168
const casting = world.ecs.get(handle, Component.spellcasting);
169
casting.armedSpellId = command.spellId;
170
casting.repeatSpellId = null;
171
casting.repeatTargetEntityId = null;
172
casting.pendingCast = null;
173
return {
174
events: [{
175
type: "spell-armed",
176
entityId,
177
characterId: character.characterId,
178
spellId: command.spellId
179
}]
180
};
181
}
182
183
function cancelArmSpell (world, sessionId, command)
184
{
185
const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
186
const casting = world.ecs.get(handle, Component.spellcasting);
187
if (!casting)
188
{ return { events: [] }; }
189
casting.armedSpellId = null;
190
casting.repeatSpellId = null;
191
casting.repeatTargetEntityId = null;
192
casting.pendingCast = null;
193
return {
194
events: [{
195
type: "spell-disarmed",
196
entityId,
197
characterId: character.characterId
198
}]
199
};
200
}
201
202
function casterMagicLevels (ecs, handle)
203
{
204
const skills = ecs.get(handle, Component.skills);
205
return {
206
magic: skillLevel(skills, SkillId.magic),
207
mind: skillLevel(skills, SkillId.mind)
208
};
209
}
210
211
function validateCastRange (world, handle, tileX, tileY, now)
212
{
213
const pos = world.ecs.get(handle, Component.position);
214
if (!pos)
215
{ return { ok: false, reason: "You are not in the world." }; }
216
const dist = chebyshev(pos.tileX, pos.tileY, tileX, tileY);
217
if (dist > COMBAT_RANGE_TILES)
218
{ return { ok: false, reason: "That is out of range." }; }
219
if (!hasCombatLineOfSight(world, pos.tileX, pos.tileY, tileX, tileY))
220
{ return { ok: false, reason: "You cannot see that spot." }; }
221
return { ok: true };
222
}
223
224
function resolvePendingCastTarget (world, pending)
225
{
226
if (pending.targetEntityId == null)
227
{
228
return {
229
tileX: pending.tileX | 0,
230
tileY: pending.tileY | 0,
231
targetEntityId: null
232
};
233
}
234
const target = resolveCombatTarget(world, pending.targetEntityId);
235
if (!target)
236
{ return null; }
237
return {
238
tileX: target.pos.tileX,
239
tileY: target.pos.tileY,
240
targetEntityId: pending.targetEntityId
241
};
242
}
243
244
function queueSpellApproach (world, handle, entityId, target, minStandDist)
245
{
246
const position = world.ecs.get(handle, Component.position);
247
if (!position)
248
{ return; }
249
queueStandInRangeApproach(
250
world,
251
entityId,
252
handle,
253
position,
254
target.tileX,
255
target.tileY,
256
COMBAT_RANGE_TILES,
257
minStandDist
258
);
259
}
260
261
function beginCastOrApproach (world, sessionId, characterId, spellId, target, now, minStandDist = 0)
262
{
263
const { handle, entityId } = requirePlayer(world, sessionId, characterId);
264
ensureSpellComponents(world.ecs, handle);
265
const casting = world.ecs.get(handle, Component.spellcasting);
266
const rangeCheck = validateCastRange(world, handle, target.tileX, target.tileY, now);
267
if (!rangeCheck.ok)
268
{
269
casting.pendingCast = {
270
spellId,
271
tileX: target.tileX,
272
tileY: target.tileY,
273
targetEntityId: target.targetEntityId ?? null
274
};
275
queueSpellApproach(world, handle, entityId, target, minStandDist);
276
return { events: [] };
277
}
278
casting.pendingCast = null;
279
return executeCast(world, sessionId, characterId, spellId, target, now);
280
}
281
282
function castSpellAtTile (world, sessionId, command, now)
283
{
284
const spellId = command.spellId;
285
const def = spellDefinition(spellId);
286
if (!def || def.target !== "tile")
287
{
288
const error = new Error("That spell needs a different target.");
289
error.userFacing = true;
290
throw error;
291
}
292
return beginCastOrApproach(world, sessionId, command.characterId, spellId, {
293
tileX: command.tileX | 0,
294
tileY: command.tileY | 0,
295
targetEntityId: null
296
}, now, 0);
297
}
298
299
function castSpellAtEntity (world, sessionId, command, now)
300
{
301
const spellId = command.spellId;
302
const def = spellDefinition(spellId);
303
if (!def || def.target !== "entity")
304
{
305
const error = new Error("That spell needs a tile target.");
306
error.userFacing = true;
307
throw error;
308
}
309
const target = resolveCombatTarget(world, command.targetEntityId);
310
if (!target)
311
{
312
const error = new Error("Target is not here.");
313
error.userFacing = true;
314
throw error;
315
}
316
return beginCastOrApproach(world, sessionId, command.characterId, spellId, {
317
tileX: target.pos.tileX,
318
tileY: target.pos.tileY,
319
targetEntityId: command.targetEntityId
320
}, now, 1);
321
}
322
323
function executeCast (world, sessionId, characterId, spellId, target, now)
324
{
325
const { handle, entityId, character } = requirePlayer(world, sessionId, characterId);
326
ensureSpellComponents(world.ecs, handle);
327
const skills = world.ecs.get(handle, Component.skills);
328
const spells = world.ecs.get(handle, Component.spells);
329
const casting = world.ecs.get(handle, Component.spellcasting);
330
const def = spellDefinition(spellId);
331
const check = canCastSpell(skills, spells, spellId);
332
if (!check.ok)
333
{
334
const error = new Error(check.reason);
335
error.userFacing = true;
336
throw error;
337
}
338
if (now < (casting.nextCastAt || 0))
339
{
340
const error = new Error("You are not ready to cast yet.");
341
error.userFacing = true;
342
throw error;
343
}
344
const rangeCheck = validateCastRange(world, handle, target.tileX, target.tileY, now);
345
if (!rangeCheck.ok)
346
{
347
const error = new Error(rangeCheck.reason);
348
error.userFacing = true;
349
throw error;
350
}
351
352
const levels = casterMagicLevels(world.ecs, handle);
353
const difficulty = spellDifficulty(def);
354
const cast = resolveSpellCast({
355
magicSkillLevel: levels.magic,
356
spellDifficulty: difficulty
357
});
358
359
const events = [];
360
const from = world.ecs.get(handle, Component.position);
361
casting.armedSpellId = null;
362
casting.repeatSpellId = null;
363
casting.repeatTargetEntityId = null;
364
casting.nextCastAt = now + SPELL_COOLDOWN_MS;
365
events.push({
366
type: "spell-disarmed",
367
entityId,
368
characterId: character.characterId
369
});
370
371
if (!cast.success)
372
{
373
events.push({
374
type: "spell-fizzle",
375
casterId: entityId,
376
spellId,
377
fromTileX: from.tileX,
378
fromTileY: from.tileY,
379
tileX: target.tileX,
380
tileY: target.tileY
381
});
382
return { events };
383
}
384
385
const xpAward = awardSpellCastXp(world.ecs, handle, difficulty);
386
if (xpAward)
387
{
388
events.push({
389
type: "skills-updated",
390
entityId,
391
characterId: character.characterId,
392
skills: xpAward.view,
393
stored: xpAward.stored,
394
levelUps: xpAward.levelUps ?? []
395
});
396
}
397
398
const flashRadius = castFlashRadiusTiles(def.tier);
399
events.push({
400
type: "spell-cast-flash",
401
casterId: entityId,
402
tileX: from.tileX,
403
tileY: from.tileY,
404
radiusTiles: flashRadius,
405
durationMs: CAST_FLASH_MS,
406
tier: def.tier
407
});
408
409
world.pendingSpellImpacts.push({
410
executeAt: now + SPELL_PROJECTILE_MS,
411
casterEntityId: entityId,
412
casterCharacterId: character.characterId,
413
spellId,
414
targetTileX: target.tileX,
415
targetTileY: target.tileY,
416
targetEntityId: target.targetEntityId,
417
levels
418
});
419
420
events.push({
421
type: "spell-projectile",
422
casterId: entityId,
423
spellId,
424
fromTileX: from.tileX,
425
fromTileY: from.tileY,
426
tileX: target.tileX,
427
tileY: target.tileY,
428
durationMs: SPELL_PROJECTILE_MS,
429
sprite: def.projectileSprite
430
});
431
432
if (def.autoRepeat && spells.autoCast && target.targetEntityId != null)
433
{
434
casting.repeatSpellId = spellId;
435
casting.repeatTargetEntityId = target.targetEntityId;
436
}
437
else
438
{
439
casting.repeatSpellId = null;
440
casting.repeatTargetEntityId = null;
441
}
442
443
return { events };
444
}
445
446
function targetAffinitiesForEntity (world, entityId)
447
{
448
if (entityId == null)
449
{ return {}; }
450
const handle = world.ecs.handleOf(entityId);
451
if (handle == null)
452
{ return {}; }
453
const creature = world.ecs.get(handle, Component.creature);
454
if (!creature)
455
{ return {}; }
456
return mobElementAffinities(mobDefinition(creature.mobTypeId));
457
}
458
459
export function processSpellImpacts (world, now = Date.now())
460
{
461
const queue = world.pendingSpellImpacts ?? [];
462
if (!queue.length)
463
{ return []; }
464
const events = [];
465
const keep = [];
466
for (const impact of queue)
467
{
468
if (impact.executeAt > now)
469
{
470
keep.push(impact);
471
continue;
472
}
473
events.push(...applySpellImpact(world, impact, now));
474
}
475
world.pendingSpellImpacts = keep;
476
return events;
477
}
478
479
function applySpellImpact (world, impact, now)
480
{
481
const def = spellDefinition(impact.spellId);
482
if (!def)
483
{ return []; }
484
const events = [];
485
events.push({
486
type: "spell-cast-flash",
487
casterId: impact.casterEntityId,
488
tileX: impact.targetTileX,
489
tileY: impact.targetTileY,
490
radiusTiles: castFlashRadiusTiles(def.tier),
491
durationMs: CAST_FLASH_MS,
492
tier: def.tier
493
});
494
495
if (impact.spellId === SpellId.light)
496
{
497
world.spellLights = world.spellLights ?? new SpellLightRegistry();
498
const mindRoll = resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll;
499
const durationMs = mindRoll * LIGHT_DURATION_MS_PER_MIND;
500
const { light, extended } = world.spellLights.placeOrExtend({
501
tileX: impact.targetTileX,
502
tileY: impact.targetTileY,
503
ownerEntityId: impact.casterEntityId,
504
durationMs,
505
now
506
});
507
events.push({
508
type: extended ? "spell-light-update" : "spell-light-appear",
509
...publicSpellLight(light, now)
510
});
511
return events;
512
}
513
514
if (impact.spellId === SpellId.spark && impact.targetEntityId != null)
515
{
516
const targetHandle = world.ecs.handleOf(impact.targetEntityId);
517
if (targetHandle == null)
518
{ return events; }
519
const affinities = targetAffinitiesForEntity(world, impact.targetEntityId);
520
const mindRoll = resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll;
521
let multiplier = ElementMultiplier.neutral;
522
const affinity = affinities[def.element ?? "fire"];
523
if (affinity === "weak")
524
{ multiplier = ElementMultiplier.weak; }
525
else if (affinity === "resistant")
526
{ multiplier = ElementMultiplier.resistant; }
527
const damage = Math.max(1, Math.floor(mindRoll * multiplier));
528
const health = world.ecs.get(targetHandle, Component.health);
529
if (health)
530
{
531
health.current = Math.max(0, (health.current | 0) - damage);
532
}
533
events.push({
534
type: "combat-hit",
535
attackerId: impact.casterEntityId,
536
targetId: impact.targetEntityId,
537
damage,
538
tileX: impact.targetTileX,
539
tileY: impact.targetTileY,
540
health: health?.current ?? 0,
541
maxHealth: health?.max ?? 0
542
});
543
const casterHandle = world.ecs.handleOf(impact.casterEntityId);
544
if (casterHandle != null)
545
{
546
const xp = awardCombatHitXp(world.ecs, casterHandle, MAGIC_ATTACK_PROFILE, damage);
547
if (xp)
548
{
549
events.push({
550
type: "skills-updated",
551
entityId: impact.casterEntityId,
552
characterId: impact.casterCharacterId,
553
skills: xp.view,
554
stored: xp.stored,
555
levelUps: xp.levelUps ?? []
556
});
557
}
558
}
559
const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
560
if (healthXp)
561
{
562
events.push({
563
type: "skills-updated",
564
entityId: impact.targetEntityId,
565
characterId: healthXp.characterId,
566
skills: healthXp.view,
567
stored: healthXp.stored,
568
levelUps: healthXp.levelUps ?? []
569
});
570
}
571
}
572
return events;
573
}
574
575
export function stepPendingSpellCast (world, now = Date.now())
576
{
577
const events = [];
578
for (const entity of world.ecs.query(Component.spellcasting, Component.character, Component.networkIdentity))
579
{
580
const casting = entity.spellcasting;
581
if (!casting?.pendingCast)
582
{ continue; }
583
const pending = casting.pendingCast;
584
const target = resolvePendingCastTarget(world, pending);
585
if (!target)
586
{
587
casting.pendingCast = null;
588
continue;
589
}
590
const rangeCheck = validateCastRange(world, entity.handle, target.tileX, target.tileY, now);
591
if (!rangeCheck.ok)
592
{
593
const minStandDist = target.targetEntityId != null ? 1 : 0;
594
queueSpellApproach(world, entity.handle, entity.entityId, target, minStandDist);
595
continue;
596
}
597
casting.pendingCast = null;
598
const result = executeCast(
599
world,
600
entity.networkIdentity.sessionId,
601
entity.character.characterId,
602
pending.spellId,
603
target,
604
now
605
);
606
events.push(...(result.events ?? []));
607
}
608
return events;
609
}
610
611
export function stepSpellAutoCast (world, now = Date.now())
612
{
613
const events = [];
614
for (const entity of world.ecs.query(Component.spellcasting, Component.spells, Component.character))
615
{
616
const casting = entity.spellcasting;
617
const spells = entity.spells;
618
if (!spells.autoCast || !casting.repeatSpellId || casting.repeatTargetEntityId == null)
619
{ continue; }
620
if (now < (casting.nextCastAt || 0))
621
{ continue; }
622
const def = spellDefinition(casting.repeatSpellId);
623
if (!def?.autoRepeat)
624
{ continue; }
625
const target = resolveCombatTarget(world, casting.repeatTargetEntityId);
626
if (!target || (target.health && target.health.current <= 0))
627
{
628
casting.repeatSpellId = null;
629
casting.repeatTargetEntityId = null;
630
continue;
631
}
632
const range = validateCastRange(world, entity.handle, target.pos.tileX, target.pos.tileY, now);
633
if (!range.ok)
634
{ continue; }
635
const sessionId = entity.networkIdentity?.sessionId;
636
if (!sessionId)
637
{ continue; }
638
const result = executeCast(
639
world,
640
sessionId,
641
entity.character.characterId,
642
casting.repeatSpellId,
643
{
644
tileX: target.pos.tileX,
645
tileY: target.pos.tileY,
646
targetEntityId: casting.repeatTargetEntityId
647
},
648
now
649
);
650
events.push(...(result.events ?? []));
651
}
652
return events;
653
}
654
655
export function tickSpellLights (world, now = Date.now())
656
{
657
if (!world.spellLights)
658
{ return []; }
659
return world.spellLights.tick(world, now);
660
}
661
662
function readSpellbook (world, sessionId, command, now)
663
{
664
const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
665
ensureSpellComponents(world.ecs, handle);
666
const inventory = world.ecs.get(handle, Component.inventory);
667
const slotIndex = command.slotIndex | 0;
668
const slot = inventory?.slots?.[slotIndex];
669
if (!slot?.instance || slot.instance.kind !== "spellbook")
670
{
671
const error = new Error("That is not a spellbook.");
672
error.userFacing = true;
673
throw error;
674
}
675
const spellId = slot.instance.spellId;
676
const spells = world.ecs.get(handle, Component.spells);
677
const skills = world.ecs.get(handle, Component.skills);
678
const learned = learnSpell(spells, spellId);
679
if (!learned.changed)
680
{
681
const error = new Error("You already know that spell.");
682
error.userFacing = true;
683
throw error;
684
}
685
Object.assign(spells, learned.spells);
686
inventory.slots[slotIndex] = null;
687
const events = [
688
spellsUpdatedEvent(entityId, character.characterId, spells, skills)
689
];
690
return {
691
events,
692
private: bagView(world.ecs, handle)
693
};
694
}
695
696
export function createSpellbookStack (spellId)
697
{
698
const instance = spellbookInstance(spellId);
699
if (!instance)
700
{ return null; }
701
const itemId = spellId === SpellId.spark
702
? SpellbookItemId.sparkSpellbook
703
: null;
704
if (itemId == null)
705
{ return null; }
706
return { itemId, quantity: 1, instance };
707
}
@@ -0,0 +1,707 @@1
import { Component } from "../ecs/components.js";2
import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";3
import { SpellId, spellDefinition, spellDifficulty } from "../../../shared/definitions/spells.js";4
import {5
canCastSpell,6
defaultPlayerSpells,7
normalizePlayerSpells,8
publicSpellsView,9
storedPlayerSpells,10
toggleFavorite,11
learnSpell12
} from "../../../shared/spells/state.js";13
import {14
CAST_FLASH_MS,15
COMBAT_RANGE_TILES,16
LIGHT_DURATION_MS_PER_MIND,17
SPELL_COOLDOWN_MS,18
SPELL_PROJECTILE_MS,19
castFlashRadiusTiles20
} from "../../../shared/spells/constants.js";21
import {22
mobElementAffinities,23
ElementMultiplier,24
resolveMagicAttack,25
resolveSpellCast,26
resolveSpellPotency27
} from "../../../shared/combat/magic.js";28
import { mobDefinition } from "../../../shared/definitions/mobs.js";29
import { awardCombatHitXp, awardDamageHealthXp, awardSpellCastXp, syncPlayerHealth } from "../skills/service.js";30
import {31
chebyshev,32
hasCombatLineOfSight,33
queueStandInRangeApproach,34
resolveCombatTarget35
} from "../combat/service.js";36
import { publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";37
import { spellCastXpFromDifficulty } from "../../../shared/skills/progression.js";38
import { publicSpellLight, SpellLightRegistry } from "./lights.js";39
import { SpellbookItemId, spellbookInstance } from "../../../shared/definitions/spellItems.js";40
import { bagView } from "../items/bags.js";41
42
const MAGIC_ATTACK_PROFILE = Object.freeze({43
hitSkillId: SkillId.magic,44
damageSkillId: SkillId.mind45
});46
47
export function ensureSpellComponents (ecs, handle, storedSpells = null)48
{49
if (!ecs.get(handle, Component.spells))50
{51
ecs.add(handle, Component.spells, normalizePlayerSpells(storedSpells ?? defaultPlayerSpells()));52
}53
if (!ecs.get(handle, Component.spellcasting))54
{55
ecs.add(handle, Component.spellcasting, {56
armedSpellId: null,57
repeatSpellId: null,58
repeatTargetEntityId: null,59
nextCastAt: 060
});61
}62
}63
64
export function handleSpellCommand (world, sessionId, command, now = Date.now())65
{66
switch (command.type)67
{68
case "set-spell-favorite":69
return setSpellFavorite(world, sessionId, command, now);70
case "set-spell-autocast":71
return setSpellAutoCast(world, sessionId, command, now);72
case "arm-spell":73
return armSpell(world, sessionId, command, now);74
case "cancel-arm-spell":75
return cancelArmSpell(world, sessionId, command, now);76
case "cast-spell-tile":77
return castSpellAtTile(world, sessionId, command, now);78
case "cast-spell-entity":79
return castSpellAtEntity(world, sessionId, command, now);80
case "read-spellbook":81
return readSpellbook(world, sessionId, command, now);82
default:83
return null;84
}85
}86
87
function requirePlayer (world, sessionId, characterId)88
{89
for (const entity of world.ecs.query(Component.networkIdentity, Component.character))90
{91
if (entity.networkIdentity.sessionId !== sessionId)92
{ continue; }93
if (entity.character.characterId !== characterId)94
{ continue; }95
return { handle: entity.handle, entityId: entity.entityId, character: entity.character };96
}97
const error = new Error("Character not found.");98
error.userFacing = true;99
throw error;100
}101
102
function spellsUpdatedEvent (entityId, characterId, spells, skills, levelUps = [])103
{104
return {105
type: "spells-updated",106
entityId,107
characterId,108
spells: publicSpellsView(spells, skills),109
stored: storedPlayerSpells(spells),110
autoCast: !!spells.autoCast,111
levelUps112
};113
}114
115
function setSpellFavorite (world, sessionId, command, now)116
{117
const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);118
ensureSpellComponents(world.ecs, handle);119
const skills = world.ecs.get(handle, Component.skills);120
const spells = world.ecs.get(handle, Component.spells);121
const result = toggleFavorite(spells, command.spellId, skills);122
if (result.error)123
{124
const error = new Error(result.error);125
error.userFacing = true;126
throw error;127
}128
Object.assign(spells, result.spells);129
const events = [];130
if (result.changed)131
{132
events.push(spellsUpdatedEvent(entityId, character.characterId, spells, skills));133
}134
return { events };135
}136
137
function setSpellAutoCast (world, sessionId, command, now)138
{139
const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);140
ensureSpellComponents(world.ecs, handle);141
const skills = world.ecs.get(handle, Component.skills);142
const spells = world.ecs.get(handle, Component.spells);143
spells.autoCast = !!command.enabled;144
const casting = world.ecs.get(handle, Component.spellcasting);145
if (!spells.autoCast)146
{147
casting.repeatSpellId = null;148
casting.repeatTargetEntityId = null;149
}150
return {151
events: [spellsUpdatedEvent(entityId, character.characterId, spells, skills)]152
};153
}154
155
function armSpell (world, sessionId, command, now)156
{157
const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);158
ensureSpellComponents(world.ecs, handle);159
const skills = world.ecs.get(handle, Component.skills);160
const spells = world.ecs.get(handle, Component.spells);161
const check = canCastSpell(skills, spells, command.spellId);162
if (!check.ok)163
{164
const error = new Error(check.reason);165
error.userFacing = true;166
throw error;167
}168
const casting = world.ecs.get(handle, Component.spellcasting);169
casting.armedSpellId = command.spellId;170
casting.repeatSpellId = null;171
casting.repeatTargetEntityId = null;172
casting.pendingCast = null;173
return {174
events: [{175
type: "spell-armed",176
entityId,177
characterId: character.characterId,178
spellId: command.spellId179
}]180
};181
}182
183
function cancelArmSpell (world, sessionId, command)184
{185
const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);186
const casting = world.ecs.get(handle, Component.spellcasting);187
if (!casting)188
{ return { events: [] }; }189
casting.armedSpellId = null;190
casting.repeatSpellId = null;191
casting.repeatTargetEntityId = null;192
casting.pendingCast = null;193
return {194
events: [{195
type: "spell-disarmed",196
entityId,197
characterId: character.characterId198
}]199
};200
}201
202
function casterMagicLevels (ecs, handle)203
{204
const skills = ecs.get(handle, Component.skills);205
return {206
magic: skillLevel(skills, SkillId.magic),207
mind: skillLevel(skills, SkillId.mind)208
};209
}210
211
function validateCastRange (world, handle, tileX, tileY, now)212
{213
const pos = world.ecs.get(handle, Component.position);214
if (!pos)215
{ return { ok: false, reason: "You are not in the world." }; }216
const dist = chebyshev(pos.tileX, pos.tileY, tileX, tileY);217
if (dist > COMBAT_RANGE_TILES)218
{ return { ok: false, reason: "That is out of range." }; }219
if (!hasCombatLineOfSight(world, pos.tileX, pos.tileY, tileX, tileY))220
{ return { ok: false, reason: "You cannot see that spot." }; }221
return { ok: true };222
}223
224
function resolvePendingCastTarget (world, pending)225
{226
if (pending.targetEntityId == null)227
{228
return {229
tileX: pending.tileX | 0,230
tileY: pending.tileY | 0,231
targetEntityId: null232
};233
}234
const target = resolveCombatTarget(world, pending.targetEntityId);235
if (!target)236
{ return null; }237
return {238
tileX: target.pos.tileX,239
tileY: target.pos.tileY,240
targetEntityId: pending.targetEntityId241
};242
}243
244
function queueSpellApproach (world, handle, entityId, target, minStandDist)245
{246
const position = world.ecs.get(handle, Component.position);247
if (!position)248
{ return; }249
queueStandInRangeApproach(250
world,251
entityId,252
handle,253
position,254
target.tileX,255
target.tileY,256
COMBAT_RANGE_TILES,257
minStandDist258
);259
}260
261
function beginCastOrApproach (world, sessionId, characterId, spellId, target, now, minStandDist = 0)262
{263
const { handle, entityId } = requirePlayer(world, sessionId, characterId);264
ensureSpellComponents(world.ecs, handle);265
const casting = world.ecs.get(handle, Component.spellcasting);266
const rangeCheck = validateCastRange(world, handle, target.tileX, target.tileY, now);267
if (!rangeCheck.ok)268
{269
casting.pendingCast = {270
spellId,271
tileX: target.tileX,272
tileY: target.tileY,273
targetEntityId: target.targetEntityId ?? null274
};275
queueSpellApproach(world, handle, entityId, target, minStandDist);276
return { events: [] };277
}278
casting.pendingCast = null;279
return executeCast(world, sessionId, characterId, spellId, target, now);280
}281
282
function castSpellAtTile (world, sessionId, command, now)283
{284
const spellId = command.spellId;285
const def = spellDefinition(spellId);286
if (!def || def.target !== "tile")287
{288
const error = new Error("That spell needs a different target.");289
error.userFacing = true;290
throw error;291
}292
return beginCastOrApproach(world, sessionId, command.characterId, spellId, {293
tileX: command.tileX | 0,294
tileY: command.tileY | 0,295
targetEntityId: null296
}, now, 0);297
}298
299
function castSpellAtEntity (world, sessionId, command, now)300
{301
const spellId = command.spellId;302
const def = spellDefinition(spellId);303
if (!def || def.target !== "entity")304
{305
const error = new Error("That spell needs a tile target.");306
error.userFacing = true;307
throw error;308
}309
const target = resolveCombatTarget(world, command.targetEntityId);310
if (!target)311
{312
const error = new Error("Target is not here.");313
error.userFacing = true;314
throw error;315
}316
return beginCastOrApproach(world, sessionId, command.characterId, spellId, {317
tileX: target.pos.tileX,318
tileY: target.pos.tileY,319
targetEntityId: command.targetEntityId320
}, now, 1);321
}322
323
function executeCast (world, sessionId, characterId, spellId, target, now)324
{325
const { handle, entityId, character } = requirePlayer(world, sessionId, characterId);326
ensureSpellComponents(world.ecs, handle);327
const skills = world.ecs.get(handle, Component.skills);328
const spells = world.ecs.get(handle, Component.spells);329
const casting = world.ecs.get(handle, Component.spellcasting);330
const def = spellDefinition(spellId);331
const check = canCastSpell(skills, spells, spellId);332
if (!check.ok)333
{334
const error = new Error(check.reason);335
error.userFacing = true;336
throw error;337
}338
if (now < (casting.nextCastAt || 0))339
{340
const error = new Error("You are not ready to cast yet.");341
error.userFacing = true;342
throw error;343
}344
const rangeCheck = validateCastRange(world, handle, target.tileX, target.tileY, now);345
if (!rangeCheck.ok)346
{347
const error = new Error(rangeCheck.reason);348
error.userFacing = true;349
throw error;350
}351
352
const levels = casterMagicLevels(world.ecs, handle);353
const difficulty = spellDifficulty(def);354
const cast = resolveSpellCast({355
magicSkillLevel: levels.magic,356
spellDifficulty: difficulty357
});358
359
const events = [];360
const from = world.ecs.get(handle, Component.position);361
casting.armedSpellId = null;362
casting.repeatSpellId = null;363
casting.repeatTargetEntityId = null;364
casting.nextCastAt = now + SPELL_COOLDOWN_MS;365
events.push({366
type: "spell-disarmed",367
entityId,368
characterId: character.characterId369
});370
371
if (!cast.success)372
{373
events.push({374
type: "spell-fizzle",375
casterId: entityId,376
spellId,377
fromTileX: from.tileX,378
fromTileY: from.tileY,379
tileX: target.tileX,380
tileY: target.tileY381
});382
return { events };383
}384
385
const xpAward = awardSpellCastXp(world.ecs, handle, difficulty);386
if (xpAward)387
{388
events.push({389
type: "skills-updated",390
entityId,391
characterId: character.characterId,392
skills: xpAward.view,393
stored: xpAward.stored,394
levelUps: xpAward.levelUps ?? []395
});396
}397
398
const flashRadius = castFlashRadiusTiles(def.tier);399
events.push({400
type: "spell-cast-flash",401
casterId: entityId,402
tileX: from.tileX,403
tileY: from.tileY,404
radiusTiles: flashRadius,405
durationMs: CAST_FLASH_MS,406
tier: def.tier407
});408
409
world.pendingSpellImpacts.push({410
executeAt: now + SPELL_PROJECTILE_MS,411
casterEntityId: entityId,412
casterCharacterId: character.characterId,413
spellId,414
targetTileX: target.tileX,415
targetTileY: target.tileY,416
targetEntityId: target.targetEntityId,417
levels418
});419
420
events.push({421
type: "spell-projectile",422
casterId: entityId,423
spellId,424
fromTileX: from.tileX,425
fromTileY: from.tileY,426
tileX: target.tileX,427
tileY: target.tileY,428
durationMs: SPELL_PROJECTILE_MS,429
sprite: def.projectileSprite430
});431
432
if (def.autoRepeat && spells.autoCast && target.targetEntityId != null)433
{434
casting.repeatSpellId = spellId;435
casting.repeatTargetEntityId = target.targetEntityId;436
}437
else438
{439
casting.repeatSpellId = null;440
casting.repeatTargetEntityId = null;441
}442
443
return { events };444
}445
446
function targetAffinitiesForEntity (world, entityId)447
{448
if (entityId == null)449
{ return {}; }450
const handle = world.ecs.handleOf(entityId);451
if (handle == null)452
{ return {}; }453
const creature = world.ecs.get(handle, Component.creature);454
if (!creature)455
{ return {}; }456
return mobElementAffinities(mobDefinition(creature.mobTypeId));457
}458
459
export function processSpellImpacts (world, now = Date.now())460
{461
const queue = world.pendingSpellImpacts ?? [];462
if (!queue.length)463
{ return []; }464
const events = [];465
const keep = [];466
for (const impact of queue)467
{468
if (impact.executeAt > now)469
{470
keep.push(impact);471
continue;472
}473
events.push(...applySpellImpact(world, impact, now));474
}475
world.pendingSpellImpacts = keep;476
return events;477
}478
479
function applySpellImpact (world, impact, now)480
{481
const def = spellDefinition(impact.spellId);482
if (!def)483
{ return []; }484
const events = [];485
events.push({486
type: "spell-cast-flash",487
casterId: impact.casterEntityId,488
tileX: impact.targetTileX,489
tileY: impact.targetTileY,490
radiusTiles: castFlashRadiusTiles(def.tier),491
durationMs: CAST_FLASH_MS,492
tier: def.tier493
});494
495
if (impact.spellId === SpellId.light)496
{497
world.spellLights = world.spellLights ?? new SpellLightRegistry();498
const mindRoll = resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll;499
const durationMs = mindRoll * LIGHT_DURATION_MS_PER_MIND;500
const { light, extended } = world.spellLights.placeOrExtend({501
tileX: impact.targetTileX,502
tileY: impact.targetTileY,503
ownerEntityId: impact.casterEntityId,504
durationMs,505
now506
});507
events.push({508
type: extended ? "spell-light-update" : "spell-light-appear",509
...publicSpellLight(light, now)510
});511
return events;512
}513
514
if (impact.spellId === SpellId.spark && impact.targetEntityId != null)515
{516
const targetHandle = world.ecs.handleOf(impact.targetEntityId);517
if (targetHandle == null)518
{ return events; }519
const affinities = targetAffinitiesForEntity(world, impact.targetEntityId);520
const mindRoll = resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll;521
let multiplier = ElementMultiplier.neutral;522
const affinity = affinities[def.element ?? "fire"];523
if (affinity === "weak")524
{ multiplier = ElementMultiplier.weak; }525
else if (affinity === "resistant")526
{ multiplier = ElementMultiplier.resistant; }527
const damage = Math.max(1, Math.floor(mindRoll * multiplier));528
const health = world.ecs.get(targetHandle, Component.health);529
if (health)530
{531
health.current = Math.max(0, (health.current | 0) - damage);532
}533
events.push({534
type: "combat-hit",535
attackerId: impact.casterEntityId,536
targetId: impact.targetEntityId,537
damage,538
tileX: impact.targetTileX,539
tileY: impact.targetTileY,540
health: health?.current ?? 0,541
maxHealth: health?.max ?? 0542
});543
const casterHandle = world.ecs.handleOf(impact.casterEntityId);544
if (casterHandle != null)545
{546
const xp = awardCombatHitXp(world.ecs, casterHandle, MAGIC_ATTACK_PROFILE, damage);547
if (xp)548
{549
events.push({550
type: "skills-updated",551
entityId: impact.casterEntityId,552
characterId: impact.casterCharacterId,553
skills: xp.view,554
stored: xp.stored,555
levelUps: xp.levelUps ?? []556
});557
}558
}559
const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);560
if (healthXp)561
{562
events.push({563
type: "skills-updated",564
entityId: impact.targetEntityId,565
characterId: healthXp.characterId,566
skills: healthXp.view,567
stored: healthXp.stored,568
levelUps: healthXp.levelUps ?? []569
});570
}571
}572
return events;573
}574
575
export function stepPendingSpellCast (world, now = Date.now())576
{577
const events = [];578
for (const entity of world.ecs.query(Component.spellcasting, Component.character, Component.networkIdentity))579
{580
const casting = entity.spellcasting;581
if (!casting?.pendingCast)582
{ continue; }583
const pending = casting.pendingCast;584
const target = resolvePendingCastTarget(world, pending);585
if (!target)586
{587
casting.pendingCast = null;588
continue;589
}590
const rangeCheck = validateCastRange(world, entity.handle, target.tileX, target.tileY, now);591
if (!rangeCheck.ok)592
{593
const minStandDist = target.targetEntityId != null ? 1 : 0;594
queueSpellApproach(world, entity.handle, entity.entityId, target, minStandDist);595
continue;596
}597
casting.pendingCast = null;598
const result = executeCast(599
world,600
entity.networkIdentity.sessionId,601
entity.character.characterId,602
pending.spellId,603
target,604
now605
);606
events.push(...(result.events ?? []));607
}608
return events;609
}610
611
export function stepSpellAutoCast (world, now = Date.now())612
{613
const events = [];614
for (const entity of world.ecs.query(Component.spellcasting, Component.spells, Component.character))615
{616
const casting = entity.spellcasting;617
const spells = entity.spells;618
if (!spells.autoCast || !casting.repeatSpellId || casting.repeatTargetEntityId == null)619
{ continue; }620
if (now < (casting.nextCastAt || 0))621
{ continue; }622
const def = spellDefinition(casting.repeatSpellId);623
if (!def?.autoRepeat)624
{ continue; }625
const target = resolveCombatTarget(world, casting.repeatTargetEntityId);626
if (!target || (target.health && target.health.current <= 0))627
{628
casting.repeatSpellId = null;629
casting.repeatTargetEntityId = null;630
continue;631
}632
const range = validateCastRange(world, entity.handle, target.pos.tileX, target.pos.tileY, now);633
if (!range.ok)634
{ continue; }635
const sessionId = entity.networkIdentity?.sessionId;636
if (!sessionId)637
{ continue; }638
const result = executeCast(639
world,640
sessionId,641
entity.character.characterId,642
casting.repeatSpellId,643
{644
tileX: target.pos.tileX,645
tileY: target.pos.tileY,646
targetEntityId: casting.repeatTargetEntityId647
},648
now649
);650
events.push(...(result.events ?? []));651
}652
return events;653
}654
655
export function tickSpellLights (world, now = Date.now())656
{657
if (!world.spellLights)658
{ return []; }659
return world.spellLights.tick(world, now);660
}661
662
function readSpellbook (world, sessionId, command, now)663
{664
const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);665
ensureSpellComponents(world.ecs, handle);666
const inventory = world.ecs.get(handle, Component.inventory);667
const slotIndex = command.slotIndex | 0;668
const slot = inventory?.slots?.[slotIndex];669
if (!slot?.instance || slot.instance.kind !== "spellbook")670
{671
const error = new Error("That is not a spellbook.");672
error.userFacing = true;673
throw error;674
}675
const spellId = slot.instance.spellId;676
const spells = world.ecs.get(handle, Component.spells);677
const skills = world.ecs.get(handle, Component.skills);678
const learned = learnSpell(spells, spellId);679
if (!learned.changed)680
{681
const error = new Error("You already know that spell.");682
error.userFacing = true;683
throw error;684
}685
Object.assign(spells, learned.spells);686
inventory.slots[slotIndex] = null;687
const events = [688
spellsUpdatedEvent(entityId, character.characterId, spells, skills)689
];690
return {691
events,692
private: bagView(world.ecs, handle)693
};694
}695
696
export function createSpellbookStack (spellId)697
{698
const instance = spellbookInstance(spellId);699
if (!instance)700
{ return null; }701
const itemId = spellId === SpellId.spark702
? SpellbookItemId.sparkSpellbook703
: null;704
if (itemId == null)705
{ return null; }706
return { itemId, quantity: 1, instance };707
}@@ -3,6 +3,7 @@ import {
3
3
GroundType,
4
4
BlockType,
5
5
isBlockPassable,
6
blockBlocksRangedAttacks,
6
7
blockLightOcclusionForBlock,
7
8
LightOcclusion,
8
9
isGroundPassable,
@@ -191,6 +192,17 @@ export function isChunkTileClearForLight (data, localX, localY)
191
192
return chunkTileLightOcclusion(data, localX, localY) !== LightOcclusion.solid;
192
193
}
193
194
195
/** True when ranged attacks and spell casts may trace a ray through this tile. */
196
export function isChunkTileClearForRangedAttacks (data, localX, localY)
197
{
198
const index = tileIndex(localX, localY);
199
const ground = normalizeGround(data.grounds[index]);
200
if (!isGroundPassable(ground.typeId))
201
{ return false; }
202
const block = data.blocks[index];
203
return !blockBlocksRangedAttacks(block?.typeId ?? null);
204
}
205
194
206
export function collectLightSources (chunkX, chunkY, data)
195
207
{
196
208
const sources = [];
@@ -3,6 +3,7 @@ import {3
GroundType,3
GroundType,4
BlockType,4
BlockType,5
isBlockPassable,5
isBlockPassable,6
blockBlocksRangedAttacks,6
blockLightOcclusionForBlock,7
blockLightOcclusionForBlock,7
LightOcclusion,8
LightOcclusion,8
isGroundPassable,9
isGroundPassable,@@ -191,6 +192,17 @@ export function isChunkTileClearForLight (data, localX, localY)191
return chunkTileLightOcclusion(data, localX, localY) !== LightOcclusion.solid;192
return chunkTileLightOcclusion(data, localX, localY) !== LightOcclusion.solid;192
}193
}193
194
195
/** True when ranged attacks and spell casts may trace a ray through this tile. */196
export function isChunkTileClearForRangedAttacks (data, localX, localY)197
{198
const index = tileIndex(localX, localY);199
const ground = normalizeGround(data.grounds[index]);200
if (!isGroundPassable(ground.typeId))201
{ return false; }202
const block = data.blocks[index];203
return !blockBlocksRangedAttacks(block?.typeId ?? null);204
}205
194
export function collectLightSources (chunkX, chunkY, data)206
export function collectLightSources (chunkX, chunkY, data)195
{207
{196
const sources = [];208
const sources = [];@@ -7,13 +7,17 @@ import {
7
7
evaluateAlchemyBottle,
8
8
hashAlchemySteps,
9
9
resolvedAlchemyPotions,
10
unstablePotionFromSteps
10
unstablePotionFromSteps,
11
potionItemInstance
11
12
} from "../../shared/alchemy/recipes.js";
12
import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
13
import { emptyEquipment, emptySlots, insertStack } from "../../shared/items/inventory.js";
14
import { itemDefinition } from "../../shared/definitions/items.js";
13
15
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
16
import { Component } from "../src/ecs/components.js";
14
17
import {
15
18
makeCharacter,
16
makeSimulation
19
makeSimulation,
20
stepTimes
17
21
} from "./helpers/simulationHarness.js";
18
22
19
23
function placeCauldron (worldDb, tileX, tileY)
@@ -156,3 +160,52 @@ test("cauldron bottles lesser health tonic when steps and ratios match", () =>
156
160
finally
157
161
{ harness.close(); }
158
162
});
163
164
test("drinking a lesser health tonic applies health regen", () =>
165
{
166
const harness = makeSimulation({ workerCount: 1 });
167
try
168
{
169
const character = makeCharacter(harness.stateDb);
170
const inventory = emptySlots();
171
const instance = potionItemInstance({
172
potionKey: "lesserHealthTonic",
173
displayName: "Lesser health tonic",
174
unstable: false,
175
color: { r: 0.35, g: 0.78, b: 0.42 },
176
fillLevel: 4,
177
effect: { type: "health-regen", amountPerSecond: 1, durationMs: 10_000 },
178
effectKey: "health-regen"
179
});
180
const inserted = insertStack(
181
inventory,
182
{ itemId: ItemId.potion, quantity: 1, instance },
183
itemDefinition(ItemId.potion)
184
);
185
harness.stateDb.saveBag(character.character_id, {
186
inventory: inserted.slots,
187
equipment: emptyEquipment(),
188
vault: [],
189
vaultReserved: []
190
});
191
const entityId = harness.simulation.spawnCharacter(1, character);
192
const record = harness.simulation.directory.get(entityId);
193
const worker = harness.simulation.workers[record.workerId];
194
const handle = worker.world.ecs.handleOf(entityId);
195
const health = worker.world.ecs.get(handle, Component.health);
196
health.current = 5;
197
198
const slotIndex = inserted.slots.findIndex((slot) => slot?.itemId === ItemId.potion);
199
harness.simulation.enqueue(1, { type: "drink-item", characterId: character.character_id, slotIndex });
200
const drink = harness.simulation.step();
201
assert.equal(drink.events.some((event) => event.type === "command-error"), false, JSON.stringify(drink.events));
202
assert.ok(drink.events.some((event) => event.type === "status-effects"));
203
const status = worker.world.ecs.get(handle, Component.statusEffects);
204
assert.ok(status?.effects?.some((entry) => entry.type === "health-regen"));
205
206
stepTimes(harness.simulation, 25);
207
assert.ok(Number(worker.world.ecs.get(handle, Component.health)?.current) > 5);
208
}
209
finally
210
{ harness.close(); }
211
});
@@ -7,13 +7,17 @@ import {7
evaluateAlchemyBottle,7
evaluateAlchemyBottle,8
hashAlchemySteps,8
hashAlchemySteps,9
resolvedAlchemyPotions,9
resolvedAlchemyPotions,10
unstablePotionFromSteps10
unstablePotionFromSteps,11
potionItemInstance11
} from "../../shared/alchemy/recipes.js";12
} from "../../shared/alchemy/recipes.js";12
import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";13
import { emptyEquipment, emptySlots, insertStack } from "../../shared/items/inventory.js";14
import { itemDefinition } from "../../shared/definitions/items.js";13
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";15
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";16
import { Component } from "../src/ecs/components.js";14
import {17
import {15
makeCharacter,18
makeCharacter,16
makeSimulation19
makeSimulation,20
stepTimes17
} from "./helpers/simulationHarness.js";21
} from "./helpers/simulationHarness.js";18
22
19
function placeCauldron (worldDb, tileX, tileY)23
function placeCauldron (worldDb, tileX, tileY)@@ -156,3 +160,52 @@ test("cauldron bottles lesser health tonic when steps and ratios match", () =>156
finally160
finally157
{ harness.close(); }161
{ harness.close(); }158
});162
});163
164
test("drinking a lesser health tonic applies health regen", () =>165
{166
const harness = makeSimulation({ workerCount: 1 });167
try168
{169
const character = makeCharacter(harness.stateDb);170
const inventory = emptySlots();171
const instance = potionItemInstance({172
potionKey: "lesserHealthTonic",173
displayName: "Lesser health tonic",174
unstable: false,175
color: { r: 0.35, g: 0.78, b: 0.42 },176
fillLevel: 4,177
effect: { type: "health-regen", amountPerSecond: 1, durationMs: 10_000 },178
effectKey: "health-regen"179
});180
const inserted = insertStack(181
inventory,182
{ itemId: ItemId.potion, quantity: 1, instance },183
itemDefinition(ItemId.potion)184
);185
harness.stateDb.saveBag(character.character_id, {186
inventory: inserted.slots,187
equipment: emptyEquipment(),188
vault: [],189
vaultReserved: []190
});191
const entityId = harness.simulation.spawnCharacter(1, character);192
const record = harness.simulation.directory.get(entityId);193
const worker = harness.simulation.workers[record.workerId];194
const handle = worker.world.ecs.handleOf(entityId);195
const health = worker.world.ecs.get(handle, Component.health);196
health.current = 5;197
198
const slotIndex = inserted.slots.findIndex((slot) => slot?.itemId === ItemId.potion);199
harness.simulation.enqueue(1, { type: "drink-item", characterId: character.character_id, slotIndex });200
const drink = harness.simulation.step();201
assert.equal(drink.events.some((event) => event.type === "command-error"), false, JSON.stringify(drink.events));202
assert.ok(drink.events.some((event) => event.type === "status-effects"));203
const status = worker.world.ecs.get(handle, Component.statusEffects);204
assert.ok(status?.effects?.some((entry) => entry.type === "health-regen"));205
206
stepTimes(harness.simulation, 25);207
assert.ok(Number(worker.world.ecs.get(handle, Component.health)?.current) > 5);208
}209
finally210
{ harness.close(); }211
});@@ -1,5 +1,6 @@
1
1
import test from "node:test";
2
2
import assert from "node:assert/strict";
3
import { Component } from "../src/ecs/components.js";
3
4
import { makeCharacter, makeSimulation, stepTimes, walkTicks } from "./helpers/simulationHarness.js";
4
5
5
6
test("logout saves tile and login resumes nearby that tile", () =>
@@ -47,3 +48,29 @@ test("login prefers a nearby free tile over a distant world spawn when blocked",
47
48
finally
48
49
{ harness.close(); }
49
50
});
51
52
test("logout saves current health and login restores it", () =>
53
{
54
const harness = makeSimulation({ workerCount: 1 });
55
try
56
{
57
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
58
const entityId = harness.simulation.spawnCharacter(1, character);
59
const record = harness.simulation.directory.get(entityId);
60
const worker = harness.simulation.workers[record.workerId];
61
const handle = worker.world.ecs.handleOf(entityId);
62
const health = worker.world.ecs.get(handle, Component.health);
63
health.current = 4;
64
65
harness.simulation.despawnCharacter(character.character_id);
66
const saved = harness.stateDb.getCharacter(character.character_id);
67
assert.equal(saved.health_current, 4);
68
69
const again = harness.simulation.spawnCharacter(2, saved);
70
const resumed = harness.simulation.entityRecord(again);
71
assert.equal(resumed.health, 4);
72
assert.equal(resumed.maxHealth, 10);
73
}
74
finally
75
{ harness.close(); }
76
});
@@ -1,5 +1,6 @@1
import test from "node:test";1
import test from "node:test";2
import assert from "node:assert/strict";2
import assert from "node:assert/strict";3
import { Component } from "../src/ecs/components.js";3
import { makeCharacter, makeSimulation, stepTimes, walkTicks } from "./helpers/simulationHarness.js";4
import { makeCharacter, makeSimulation, stepTimes, walkTicks } from "./helpers/simulationHarness.js";4
5
5
test("logout saves tile and login resumes nearby that tile", () =>6
test("logout saves tile and login resumes nearby that tile", () =>@@ -47,3 +48,29 @@ test("login prefers a nearby free tile over a distant world spawn when blocked",47
finally48
finally48
{ harness.close(); }49
{ harness.close(); }49
});50
});51
52
test("logout saves current health and login restores it", () =>53
{54
const harness = makeSimulation({ workerCount: 1 });55
try56
{57
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });58
const entityId = harness.simulation.spawnCharacter(1, character);59
const record = harness.simulation.directory.get(entityId);60
const worker = harness.simulation.workers[record.workerId];61
const handle = worker.world.ecs.handleOf(entityId);62
const health = worker.world.ecs.get(handle, Component.health);63
health.current = 4;64
65
harness.simulation.despawnCharacter(character.character_id);66
const saved = harness.stateDb.getCharacter(character.character_id);67
assert.equal(saved.health_current, 4);68
69
const again = harness.simulation.spawnCharacter(2, saved);70
const resumed = harness.simulation.entityRecord(again);71
assert.equal(resumed.health, 4);72
assert.equal(resumed.maxHealth, 10);73
}74
finally75
{ harness.close(); }76
});@@ -3,14 +3,14 @@ import assert from "node:assert/strict";
3
3
import { mobComponents } from "../src/simulation/spawners.js";
4
4
import { MobId } from "../../shared/definitions/mobs.js";
5
5
import { ItemId, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";
6
import { BlockType } from "../../shared/definitions/tiles.js";
6
import { BlockType, blockBlocksRangedAttacks } from "../../shared/definitions/tiles.js";
7
7
import { Component } from "../src/ecs/components.js";
8
8
import { tileKey } from "../src/world/coordinates.js";
9
9
import { WorkerMessage } from "../src/simulation/protocol.js";
10
10
import { tileToRegion } from "../src/world/coordinates.js";
11
11
import { SkillId } from "../../shared/definitions/skills.js";
12
12
import { totalXpForLevel } from "../../shared/skills/progression.js";
13
import { resolveMeleeSwing, attackProfileOf } from "../src/combat/service.js";
13
import { resolveMeleeSwing, attackProfileOf, hasCombatLineOfSight } from "../src/combat/service.js";
14
14
import { makeCharacter, makeSimulation, pinEastSplit, stepTimes } from "./helpers/simulationHarness.js";
15
15
16
16
function workerOf (simulation, entityId)
@@ -622,6 +622,47 @@ test("aggressive rats do not aggro through walls or beyond range", () =>
622
622
{ harness.close(); }
623
623
});
624
624
625
test("crafting stations and tables do not block ranged or spell line of sight", () =>
626
{
627
assert.equal(blockBlocksRangedAttacks(BlockType.stoneWall), true);
628
assert.equal(blockBlocksRangedAttacks(BlockType.furnace), false);
629
assert.equal(blockBlocksRangedAttacks(BlockType.table), false);
630
assert.equal(blockBlocksRangedAttacks(null), false);
631
632
const harness = makeSimulation({ workerCount: 1 });
633
try
634
{
635
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
636
const playerId = harness.simulation.spawnCharacter(1, character);
637
const worker = workerOf(harness.simulation, playerId);
638
const data = worker.world.chunkData(0, 0);
639
const blockIndex = (localY, localX) => localY * 16 + localX;
640
641
data.blocks[blockIndex(8, 10)] = { typeId: BlockType.furnace, state: null, config: null };
642
assert.equal(
643
hasCombatLineOfSight(worker.world, 8, 8, 12, 8),
644
true,
645
"furnace between caster and target should not block"
646
);
647
648
data.blocks[blockIndex(8, 10)] = { typeId: BlockType.table, state: null, config: null };
649
assert.equal(
650
hasCombatLineOfSight(worker.world, 8, 8, 12, 8),
651
true,
652
"table between caster and target should not block"
653
);
654
655
data.blocks[blockIndex(8, 10)] = { typeId: BlockType.stoneWall, state: null, config: null };
656
assert.equal(
657
hasCombatLineOfSight(worker.world, 8, 8, 12, 8),
658
false,
659
"stone wall should still block"
660
);
661
}
662
finally
663
{ harness.close(); }
664
});
665
625
666
test("attacker keeps pursuing and can swing after the target moves", () =>
626
667
{
627
668
const harness = makeSimulation({ workerCount: 1 });
@@ -3,14 +3,14 @@ import assert from "node:assert/strict";3
import { mobComponents } from "../src/simulation/spawners.js";3
import { mobComponents } from "../src/simulation/spawners.js";4
import { MobId } from "../../shared/definitions/mobs.js";4
import { MobId } from "../../shared/definitions/mobs.js";5
import { ItemId, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";5
import { ItemId, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";6
import { BlockType } from "../../shared/definitions/tiles.js";6
import { BlockType, blockBlocksRangedAttacks } from "../../shared/definitions/tiles.js";7
import { Component } from "../src/ecs/components.js";7
import { Component } from "../src/ecs/components.js";8
import { tileKey } from "../src/world/coordinates.js";8
import { tileKey } from "../src/world/coordinates.js";9
import { WorkerMessage } from "../src/simulation/protocol.js";9
import { WorkerMessage } from "../src/simulation/protocol.js";10
import { tileToRegion } from "../src/world/coordinates.js";10
import { tileToRegion } from "../src/world/coordinates.js";11
import { SkillId } from "../../shared/definitions/skills.js";11
import { SkillId } from "../../shared/definitions/skills.js";12
import { totalXpForLevel } from "../../shared/skills/progression.js";12
import { totalXpForLevel } from "../../shared/skills/progression.js";13
import { resolveMeleeSwing, attackProfileOf } from "../src/combat/service.js";13
import { resolveMeleeSwing, attackProfileOf, hasCombatLineOfSight } from "../src/combat/service.js";14
import { makeCharacter, makeSimulation, pinEastSplit, stepTimes } from "./helpers/simulationHarness.js";14
import { makeCharacter, makeSimulation, pinEastSplit, stepTimes } from "./helpers/simulationHarness.js";15
15
16
function workerOf (simulation, entityId)16
function workerOf (simulation, entityId)@@ -622,6 +622,47 @@ test("aggressive rats do not aggro through walls or beyond range", () =>622
{ harness.close(); }622
{ harness.close(); }623
});623
});624
624
625
test("crafting stations and tables do not block ranged or spell line of sight", () =>626
{627
assert.equal(blockBlocksRangedAttacks(BlockType.stoneWall), true);628
assert.equal(blockBlocksRangedAttacks(BlockType.furnace), false);629
assert.equal(blockBlocksRangedAttacks(BlockType.table), false);630
assert.equal(blockBlocksRangedAttacks(null), false);631
632
const harness = makeSimulation({ workerCount: 1 });633
try634
{635
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });636
const playerId = harness.simulation.spawnCharacter(1, character);637
const worker = workerOf(harness.simulation, playerId);638
const data = worker.world.chunkData(0, 0);639
const blockIndex = (localY, localX) => localY * 16 + localX;640
641
data.blocks[blockIndex(8, 10)] = { typeId: BlockType.furnace, state: null, config: null };642
assert.equal(643
hasCombatLineOfSight(worker.world, 8, 8, 12, 8),644
true,645
"furnace between caster and target should not block"646
);647
648
data.blocks[blockIndex(8, 10)] = { typeId: BlockType.table, state: null, config: null };649
assert.equal(650
hasCombatLineOfSight(worker.world, 8, 8, 12, 8),651
true,652
"table between caster and target should not block"653
);654
655
data.blocks[blockIndex(8, 10)] = { typeId: BlockType.stoneWall, state: null, config: null };656
assert.equal(657
hasCombatLineOfSight(worker.world, 8, 8, 12, 8),658
false,659
"stone wall should still block"660
);661
}662
finally663
{ harness.close(); }664
});665
625
test("attacker keeps pursuing and can swing after the target moves", () =>666
test("attacker keeps pursuing and can swing after the target moves", () =>626
{667
{627
const harness = makeSimulation({ workerCount: 1 });668
const harness = makeSimulation({ workerCount: 1 });@@ -1,7 +1,7 @@
1
1
import test from "node:test";
2
2
import assert from "node:assert/strict";
3
3
import { resolveMagicAttack, resolveMagicEffect, resolveSpellCast } from "../../shared/combat/magic.js";
4
import { spellDefinition, SpellId } from "../../shared/definitions/spells.js";
4
import { spellDefinition, spellDifficulty, SpellId } from "../../shared/definitions/spells.js";
5
5
6
6
test("spell cast fails when difficulty roll beats magic roll", () =>
7
7
{
@@ -30,7 +30,6 @@ test("fizzled magic attack deals no damage", () =>
30
30
magicSkillLevel: 3,
31
31
spellDifficulty: 10,
32
32
mindSkillLevel: 10,
33
mindBonus: 5,
34
33
element: "fire",
35
34
rng
36
35
});
@@ -41,26 +40,25 @@ test("fizzled magic attack deals no damage", () =>
41
40
test("successful magic attack rolls mind damage and elemental multiplier", () =>
42
41
{
43
42
let i = 0;
44
const rng = () => [0.9, 0, 0, 0][i++];
43
const rng = () => [0.9, 0, 0][i++];
45
44
const neutral = resolveMagicAttack({
46
45
magicSkillLevel: 10,
47
46
spellDifficulty: 1,
48
47
mindSkillLevel: 5,
49
mindBonus: 2,
50
48
element: "fire",
51
49
targetAffinities: {},
52
50
rng
53
51
});
54
52
assert.equal(neutral.outcome, "hit");
55
53
assert.equal(neutral.multiplier, 1);
54
assert.equal(neutral.damage, 1);
56
55
57
56
let j = 0;
58
const rngWeak = () => [0.9, 0, 0, 0][j++];
57
const rngWeak = () => [0.9, 0, 0][j++];
59
58
const weak = resolveMagicAttack({
60
59
magicSkillLevel: 10,
61
60
spellDifficulty: 1,
62
61
mindSkillLevel: 5,
63
mindBonus: 2,
64
62
element: "fire",
65
63
targetAffinities: { fire: "weak" },
66
64
rng: rngWeak
@@ -83,9 +81,10 @@ test("non-damage spell applies effect only after a successful cast roll", () =>
83
81
assert.equal(result.effectId, "slow");
84
82
});
85
83
86
test("spell definitions expose per-spell difficulty", () =>
84
test("spell definitions expose tier-based difficulty", () =>
87
85
{
88
86
const spark = spellDefinition(SpellId.spark);
89
assert.equal(spark.difficulty, 4);
87
assert.equal(spellDifficulty(spark), 4);
90
88
assert.equal(spark.element, "fire");
89
assert.ok(spellDefinition(SpellId.light));
91
90
});
@@ -1,7 +1,7 @@1
import test from "node:test";1
import test from "node:test";2
import assert from "node:assert/strict";2
import assert from "node:assert/strict";3
import { resolveMagicAttack, resolveMagicEffect, resolveSpellCast } from "../../shared/combat/magic.js";3
import { resolveMagicAttack, resolveMagicEffect, resolveSpellCast } from "../../shared/combat/magic.js";4
import { spellDefinition, SpellId } from "../../shared/definitions/spells.js";4
import { spellDefinition, spellDifficulty, SpellId } from "../../shared/definitions/spells.js";5
5
6
test("spell cast fails when difficulty roll beats magic roll", () =>6
test("spell cast fails when difficulty roll beats magic roll", () =>7
{7
{@@ -30,7 +30,6 @@ test("fizzled magic attack deals no damage", () =>30
magicSkillLevel: 3,30
magicSkillLevel: 3,31
spellDifficulty: 10,31
spellDifficulty: 10,32
mindSkillLevel: 10,32
mindSkillLevel: 10,33
mindBonus: 5,34
element: "fire",33
element: "fire",35
rng34
rng36
});35
});@@ -41,26 +40,25 @@ test("fizzled magic attack deals no damage", () =>41
test("successful magic attack rolls mind damage and elemental multiplier", () =>40
test("successful magic attack rolls mind damage and elemental multiplier", () =>42
{41
{43
let i = 0;42
let i = 0;44
const rng = () => [0.9, 0, 0, 0][i++];43
const rng = () => [0.9, 0, 0][i++];45
const neutral = resolveMagicAttack({44
const neutral = resolveMagicAttack({46
magicSkillLevel: 10,45
magicSkillLevel: 10,47
spellDifficulty: 1,46
spellDifficulty: 1,48
mindSkillLevel: 5,47
mindSkillLevel: 5,49
mindBonus: 2,50
element: "fire",48
element: "fire",51
targetAffinities: {},49
targetAffinities: {},52
rng50
rng53
});51
});54
assert.equal(neutral.outcome, "hit");52
assert.equal(neutral.outcome, "hit");55
assert.equal(neutral.multiplier, 1);53
assert.equal(neutral.multiplier, 1);54
assert.equal(neutral.damage, 1);56
55
57
let j = 0;56
let j = 0;58
const rngWeak = () => [0.9, 0, 0, 0][j++];57
const rngWeak = () => [0.9, 0, 0][j++];59
const weak = resolveMagicAttack({58
const weak = resolveMagicAttack({60
magicSkillLevel: 10,59
magicSkillLevel: 10,61
spellDifficulty: 1,60
spellDifficulty: 1,62
mindSkillLevel: 5,61
mindSkillLevel: 5,63
mindBonus: 2,64
element: "fire",62
element: "fire",65
targetAffinities: { fire: "weak" },63
targetAffinities: { fire: "weak" },66
rng: rngWeak64
rng: rngWeak@@ -83,9 +81,10 @@ test("non-damage spell applies effect only after a successful cast roll", () =>83
assert.equal(result.effectId, "slow");81
assert.equal(result.effectId, "slow");84
});82
});85
83
86
test("spell definitions expose per-spell difficulty", () =>84
test("spell definitions expose tier-based difficulty", () =>87
{85
{88
const spark = spellDefinition(SpellId.spark);86
const spark = spellDefinition(SpellId.spark);89
assert.equal(spark.difficulty, 4);87
assert.equal(spellDifficulty(spark), 4);90
assert.equal(spark.element, "fire");88
assert.equal(spark.element, "fire");89
assert.ok(spellDefinition(SpellId.light));91
});90
});@@ -0,0 +1,62 @@
1
import test from "node:test";
2
import assert from "node:assert/strict";
3
import { npcDefaultEquipment, npcClothDyeFromSeed, NPC_CLOTH_DYE_BYTE_MIN } from "../../shared/appearance/npcEquipment.js";
4
import { ItemId } from "../../shared/definitions/items.js";
5
import { LeatherItemId } from "../../shared/definitions/leatherItems.js";
6
import { mobComponents } from "../src/simulation/spawners.js";
7
import { MobId } from "../../shared/definitions/mobs.js";
8
9
test("npcDefaultEquipment picks deterministic garments from display name", () =>
10
{
11
const a = npcDefaultEquipment("Ada Lovelace", "female");
12
const b = npcDefaultEquipment("Ada Lovelace", "female");
13
assert.deepEqual(a, b);
14
assert.ok(a.chest?.itemId);
15
assert.ok([LeatherItemId.clothShorts, LeatherItemId.clothTrousers].includes(a.legs?.itemId));
16
assert.equal(a.boots?.itemId, LeatherItemId.leatherShoes);
17
assert.ok(a.chest.dyeColor);
18
assert.ok(a.legs.dyeColor);
19
});
20
21
test("npc cloth dyes stay above minimum channel", () =>
22
{
23
const dye = npcClothDyeFromSeed("Test NPC", 3);
24
const min = NPC_CLOTH_DYE_BYTE_MIN / 255;
25
assert.ok(dye.r >= min);
26
assert.ok(dye.g >= min);
27
assert.ok(dye.b >= min);
28
});
29
30
test("humanoid spawner without equipment gets default clothing", () =>
31
{
32
const components = mobComponents({
33
mobTypeId: MobId.humanoid,
34
tileX: 8,
35
tileY: 8,
36
displayName: "Village Guard",
37
sex: "male",
38
equipment: {},
39
spawnerId: "test"
40
});
41
const slots = components.equipment?.slots ?? {};
42
assert.ok(slots.chest?.itemId);
43
assert.ok(slots.legs?.itemId);
44
assert.equal(slots.boots?.itemId, LeatherItemId.leatherShoes);
45
assert.equal(slots.chest?.instance?.kind, "clothing");
46
assert.equal(slots.legs?.instance?.kind, "clothing");
47
});
48
49
test("authored spawner chest overrides default clothing", () =>
50
{
51
const components = mobComponents({
52
mobTypeId: MobId.humanoid,
53
tileX: 8,
54
tileY: 8,
55
displayName: "Tailor",
56
sex: "female",
57
equipment: { chest: ItemId.clothShirt },
58
spawnerId: "test"
59
});
60
assert.equal(components.equipment.slots.chest.itemId, ItemId.clothShirt);
61
assert.equal(components.equipment.slots.chest.instance, undefined);
62
});
@@ -0,0 +1,62 @@1
import test from "node:test";2
import assert from "node:assert/strict";3
import { npcDefaultEquipment, npcClothDyeFromSeed, NPC_CLOTH_DYE_BYTE_MIN } from "../../shared/appearance/npcEquipment.js";4
import { ItemId } from "../../shared/definitions/items.js";5
import { LeatherItemId } from "../../shared/definitions/leatherItems.js";6
import { mobComponents } from "../src/simulation/spawners.js";7
import { MobId } from "../../shared/definitions/mobs.js";8
9
test("npcDefaultEquipment picks deterministic garments from display name", () =>10
{11
const a = npcDefaultEquipment("Ada Lovelace", "female");12
const b = npcDefaultEquipment("Ada Lovelace", "female");13
assert.deepEqual(a, b);14
assert.ok(a.chest?.itemId);15
assert.ok([LeatherItemId.clothShorts, LeatherItemId.clothTrousers].includes(a.legs?.itemId));16
assert.equal(a.boots?.itemId, LeatherItemId.leatherShoes);17
assert.ok(a.chest.dyeColor);18
assert.ok(a.legs.dyeColor);19
});20
21
test("npc cloth dyes stay above minimum channel", () =>22
{23
const dye = npcClothDyeFromSeed("Test NPC", 3);24
const min = NPC_CLOTH_DYE_BYTE_MIN / 255;25
assert.ok(dye.r >= min);26
assert.ok(dye.g >= min);27
assert.ok(dye.b >= min);28
});29
30
test("humanoid spawner without equipment gets default clothing", () =>31
{32
const components = mobComponents({33
mobTypeId: MobId.humanoid,34
tileX: 8,35
tileY: 8,36
displayName: "Village Guard",37
sex: "male",38
equipment: {},39
spawnerId: "test"40
});41
const slots = components.equipment?.slots ?? {};42
assert.ok(slots.chest?.itemId);43
assert.ok(slots.legs?.itemId);44
assert.equal(slots.boots?.itemId, LeatherItemId.leatherShoes);45
assert.equal(slots.chest?.instance?.kind, "clothing");46
assert.equal(slots.legs?.instance?.kind, "clothing");47
});48
49
test("authored spawner chest overrides default clothing", () =>50
{51
const components = mobComponents({52
mobTypeId: MobId.humanoid,53
tileX: 8,54
tileY: 8,55
displayName: "Tailor",56
sex: "female",57
equipment: { chest: ItemId.clothShirt },58
spawnerId: "test"59
});60
assert.equal(components.equipment.slots.chest.itemId, ItemId.clothShirt);61
assert.equal(components.equipment.slots.chest.instance, undefined);62
});@@ -4,6 +4,7 @@ import {
4
4
SKILL_XP_BASE,
5
5
xpToAdvanceFromLevel,
6
6
totalXpForLevel,
7
maxTotalSkillXp,
7
8
xpProgress,
8
9
levelFromTotalXp,
9
10
combatDamageXp,
@@ -86,11 +87,11 @@ test("legacy empty skills_blob loads as Health level 10 max HP", () =>
86
87
{ harness.close(); }
87
88
});
88
89
89
test("xp to advance doubles each level starting at 50", () =>
90
test("xp to advance grows 10% per level starting at 50", () =>
90
91
{
91
92
assert.equal(xpToAdvanceFromLevel(1), 50);
92
assert.equal(xpToAdvanceFromLevel(2), 100);
93
assert.equal(xpToAdvanceFromLevel(3), 200);
93
assert.equal(xpToAdvanceFromLevel(2), 55);
94
assert.equal(xpToAdvanceFromLevel(3), 60);
94
95
assert.equal(xpToAdvanceFromLevel(99), 0);
95
96
});
96
97
@@ -105,7 +106,7 @@ test("level is derived from total xp", () =>
105
106
106
107
test("skills cap at level 99", () =>
107
108
{
108
const capped = totalXpForLevel(100) - 1;
109
const capped = maxTotalSkillXp();
109
110
assert.equal(levelFromTotalXp(capped), 99);
110
111
const progress = xpProgress(capped);
111
112
assert.equal(progress.level, 99);
@@ -4,6 +4,7 @@ import {4
SKILL_XP_BASE,4
SKILL_XP_BASE,5
xpToAdvanceFromLevel,5
xpToAdvanceFromLevel,6
totalXpForLevel,6
totalXpForLevel,7
maxTotalSkillXp,7
xpProgress,8
xpProgress,8
levelFromTotalXp,9
levelFromTotalXp,9
combatDamageXp,10
combatDamageXp,@@ -86,11 +87,11 @@ test("legacy empty skills_blob loads as Health level 10 max HP", () =>86
{ harness.close(); }87
{ harness.close(); }87
});88
});88
89
89
test("xp to advance doubles each level starting at 50", () =>90
test("xp to advance grows 10% per level starting at 50", () =>90
{91
{91
assert.equal(xpToAdvanceFromLevel(1), 50);92
assert.equal(xpToAdvanceFromLevel(1), 50);92
assert.equal(xpToAdvanceFromLevel(2), 100);93
assert.equal(xpToAdvanceFromLevel(2), 55);93
assert.equal(xpToAdvanceFromLevel(3), 200);94
assert.equal(xpToAdvanceFromLevel(3), 60);94
assert.equal(xpToAdvanceFromLevel(99), 0);95
assert.equal(xpToAdvanceFromLevel(99), 0);95
});96
});96
97
@@ -105,7 +106,7 @@ test("level is derived from total xp", () =>105
106
106
test("skills cap at level 99", () =>107
test("skills cap at level 99", () =>107
{108
{108
const capped = totalXpForLevel(100) - 1;109
const capped = maxTotalSkillXp();109
assert.equal(levelFromTotalXp(capped), 99);110
assert.equal(levelFromTotalXp(capped), 99);110
const progress = xpProgress(capped);111
const progress = xpProgress(capped);111
assert.equal(progress.level, 99);112
assert.equal(progress.level, 99);@@ -0,0 +1,104 @@
1
import test from "node:test";
2
import assert from "node:assert/strict";
3
import { SpellId } from "../../shared/definitions/spells.js";
4
import { SPELL_PROJECTILE_MS } from "../../shared/spells/constants.js";
5
import { mobComponents } from "../src/simulation/spawners.js";
6
import { MobId } from "../../shared/definitions/mobs.js";
7
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
8
9
test("cast light resolves without command error and can place a spell light", () =>
10
{
11
const harness = makeSimulation({ workerCount: 1 });
12
try
13
{
14
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
15
harness.simulation.spawnCharacter(1, character);
16
17
harness.simulation.enqueue(1, {
18
type: "cast-spell-tile",
19
characterId: character.character_id,
20
spellId: SpellId.light,
21
tileX: 10,
22
tileY: 8
23
});
24
const cast = harness.simulation.step();
25
assert.equal(
26
cast.events.some((event) => event.type === "command-error"),
27
false,
28
JSON.stringify(cast.events)
29
);
30
assert.ok(
31
cast.events.some((event) => event.type === "spell-fizzle" || event.type === "spell-projectile"),
32
"expected fizzle or projectile"
33
);
34
35
if (!cast.events.some((event) => event.type === "spell-projectile"))
36
{ return; }
37
38
harness.advance(SPELL_PROJECTILE_MS + 50);
39
const impact = harness.simulation.step();
40
assert.ok(
41
impact.events.some((event) => event.type === "spell-light-appear"),
42
JSON.stringify(impact.events.map((event) => event.type))
43
);
44
}
45
finally
46
{ harness.close(); }
47
});
48
49
test("out-of-range spell cast paths toward the nearest in-range tile", () =>
50
{
51
const harness = makeSimulation({ workerCount: 1 });
52
try
53
{
54
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
55
const playerId = harness.simulation.spawnCharacter(1, character);
56
harness.simulation.enqueue(1, {
57
type: "cast-spell-tile",
58
characterId: character.character_id,
59
spellId: SpellId.light,
60
tileX: 30,
61
tileY: 8
62
});
63
const cast = harness.simulation.step();
64
assert.equal(cast.events.some((event) => event.type === "command-error"), false);
65
const start = harness.simulation.entityRecord(playerId);
66
for (let i = 0; i < 80; i++)
67
{ harness.simulation.step(); }
68
const moved = harness.simulation.entityRecord(playerId);
69
assert.ok(
70
moved.tileX !== start.tileX || moved.tileY !== start.tileY,
71
`expected movement from (${start.tileX},${start.tileY}), got (${moved.tileX},${moved.tileY})`
72
);
73
}
74
finally
75
{ harness.close(); }
76
});
77
78
test("attack from out of range paths toward the target", () =>
79
{
80
const harness = makeSimulation({ workerCount: 1 });
81
try
82
{
83
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
84
const playerId = harness.simulation.spawnCharacter(1, character);
85
const deerId = harness.simulation.spawnEntity(mobComponents({
86
tileX: 24,
87
tileY: 8,
88
mobTypeId: MobId.deer
89
}));
90
harness.simulation.enqueue(1, {
91
type: "attack",
92
characterId: character.character_id,
93
targetEntityId: deerId
94
});
95
harness.simulation.step();
96
const record = harness.simulation.entityRecord(playerId);
97
assert.ok(record.tileX < 24);
98
for (let i = 0; i < 80 && record.tileX < 20; i++)
99
{ harness.simulation.step(); }
100
assert.ok(harness.simulation.entityRecord(playerId).tileX > 8);
101
}
102
finally
103
{ harness.close(); }
104
});
@@ -0,0 +1,104 @@1
import test from "node:test";2
import assert from "node:assert/strict";3
import { SpellId } from "../../shared/definitions/spells.js";4
import { SPELL_PROJECTILE_MS } from "../../shared/spells/constants.js";5
import { mobComponents } from "../src/simulation/spawners.js";6
import { MobId } from "../../shared/definitions/mobs.js";7
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";8
9
test("cast light resolves without command error and can place a spell light", () =>10
{11
const harness = makeSimulation({ workerCount: 1 });12
try13
{14
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });15
harness.simulation.spawnCharacter(1, character);16
17
harness.simulation.enqueue(1, {18
type: "cast-spell-tile",19
characterId: character.character_id,20
spellId: SpellId.light,21
tileX: 10,22
tileY: 823
});24
const cast = harness.simulation.step();25
assert.equal(26
cast.events.some((event) => event.type === "command-error"),27
false,28
JSON.stringify(cast.events)29
);30
assert.ok(31
cast.events.some((event) => event.type === "spell-fizzle" || event.type === "spell-projectile"),32
"expected fizzle or projectile"33
);34
35
if (!cast.events.some((event) => event.type === "spell-projectile"))36
{ return; }37
38
harness.advance(SPELL_PROJECTILE_MS + 50);39
const impact = harness.simulation.step();40
assert.ok(41
impact.events.some((event) => event.type === "spell-light-appear"),42
JSON.stringify(impact.events.map((event) => event.type))43
);44
}45
finally46
{ harness.close(); }47
});48
49
test("out-of-range spell cast paths toward the nearest in-range tile", () =>50
{51
const harness = makeSimulation({ workerCount: 1 });52
try53
{54
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });55
const playerId = harness.simulation.spawnCharacter(1, character);56
harness.simulation.enqueue(1, {57
type: "cast-spell-tile",58
characterId: character.character_id,59
spellId: SpellId.light,60
tileX: 30,61
tileY: 862
});63
const cast = harness.simulation.step();64
assert.equal(cast.events.some((event) => event.type === "command-error"), false);65
const start = harness.simulation.entityRecord(playerId);66
for (let i = 0; i < 80; i++)67
{ harness.simulation.step(); }68
const moved = harness.simulation.entityRecord(playerId);69
assert.ok(70
moved.tileX !== start.tileX || moved.tileY !== start.tileY,71
`expected movement from (${start.tileX},${start.tileY}), got (${moved.tileX},${moved.tileY})`72
);73
}74
finally75
{ harness.close(); }76
});77
78
test("attack from out of range paths toward the target", () =>79
{80
const harness = makeSimulation({ workerCount: 1 });81
try82
{83
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });84
const playerId = harness.simulation.spawnCharacter(1, character);85
const deerId = harness.simulation.spawnEntity(mobComponents({86
tileX: 24,87
tileY: 8,88
mobTypeId: MobId.deer89
}));90
harness.simulation.enqueue(1, {91
type: "attack",92
characterId: character.character_id,93
targetEntityId: deerId94
});95
harness.simulation.step();96
const record = harness.simulation.entityRecord(playerId);97
assert.ok(record.tileX < 24);98
for (let i = 0; i < 80 && record.tileX < 20; i++)99
{ harness.simulation.step(); }100
assert.ok(harness.simulation.entityRecord(playerId).tileX > 8);101
}102
finally103
{ harness.close(); }104
});@@ -1,5 +1,6 @@
1
1
import test from "node:test";
2
2
import assert from "node:assert/strict";
3
import { BlockType } from "../../shared/definitions/tiles.js";
3
4
import {
4
5
makeCharacter,
5
6
makeSimulation,
@@ -65,18 +66,20 @@ test("a blocked destination rejects the transfer and leaves one copy on the sour
65
66
try
66
67
{
67
68
const walker = makeCharacter(harness.stateDb, { tileX: 62, tileY: 8 });
68
const blocker = makeCharacter(harness.stateDb, { tileX: 64, tileY: 8, firstName: "Bob" });
69
const anchor = makeCharacter(harness.stateDb, { tileX: 70, tileY: 8, firstName: "Bob" });
69
70
const walkerId = harness.simulation.spawnCharacter(1, walker);
70
const blockerId = harness.simulation.spawnCharacter(2, blocker);
71
harness.simulation.spawnCharacter(2, anchor);
71
72
assert.equal(harness.simulation.entityRecord(walkerId).workerId, 0);
72
assert.equal(harness.simulation.entityRecord(blockerId).workerId, 1);
73
74
const eastWorker = harness.simulation.workers[1];
75
const data = eastWorker.world.chunkData(4, 0);
76
data.blocks[8 * 16 + 0] = { typeId: BlockType.stoneWall, state: null, config: null };
73
77
74
78
harness.simulation.enqueue(1, { type: "move-to", characterId: walker.character_id, tileX: 64, tileY: 8 });
75
79
stepTimes(harness.simulation, walkTicks(3));
76
80
const walking = harness.simulation.entityRecord(walkerId);
77
81
assert.ok(walking.tileX < 64);
78
82
assert.equal(walking.workerId, 0);
79
assert.equal(harness.simulation.entityRecord(blockerId).tileX, 64);
80
83
assert.equal(harness.simulation.debugWorld().entities.filter((entity) => entity.entityId === walkerId).length, 1);
81
84
}
82
85
finally
@@ -1,5 +1,6 @@1
import test from "node:test";1
import test from "node:test";2
import assert from "node:assert/strict";2
import assert from "node:assert/strict";3
import { BlockType } from "../../shared/definitions/tiles.js";3
import {4
import {4
makeCharacter,5
makeCharacter,5
makeSimulation,6
makeSimulation,@@ -65,18 +66,20 @@ test("a blocked destination rejects the transfer and leaves one copy on the sour65
try66
try66
{67
{67
const walker = makeCharacter(harness.stateDb, { tileX: 62, tileY: 8 });68
const walker = makeCharacter(harness.stateDb, { tileX: 62, tileY: 8 });68
const blocker = makeCharacter(harness.stateDb, { tileX: 64, tileY: 8, firstName: "Bob" });69
const anchor = makeCharacter(harness.stateDb, { tileX: 70, tileY: 8, firstName: "Bob" });69
const walkerId = harness.simulation.spawnCharacter(1, walker);70
const walkerId = harness.simulation.spawnCharacter(1, walker);70
const blockerId = harness.simulation.spawnCharacter(2, blocker);71
harness.simulation.spawnCharacter(2, anchor);71
assert.equal(harness.simulation.entityRecord(walkerId).workerId, 0);72
assert.equal(harness.simulation.entityRecord(walkerId).workerId, 0);72
assert.equal(harness.simulation.entityRecord(blockerId).workerId, 1);73
74
const eastWorker = harness.simulation.workers[1];75
const data = eastWorker.world.chunkData(4, 0);76
data.blocks[8 * 16 + 0] = { typeId: BlockType.stoneWall, state: null, config: null };73
77
74
harness.simulation.enqueue(1, { type: "move-to", characterId: walker.character_id, tileX: 64, tileY: 8 });78
harness.simulation.enqueue(1, { type: "move-to", characterId: walker.character_id, tileX: 64, tileY: 8 });75
stepTimes(harness.simulation, walkTicks(3));79
stepTimes(harness.simulation, walkTicks(3));76
const walking = harness.simulation.entityRecord(walkerId);80
const walking = harness.simulation.entityRecord(walkerId);77
assert.ok(walking.tileX < 64);81
assert.ok(walking.tileX < 64);78
assert.equal(walking.workerId, 0);82
assert.equal(walking.workerId, 0);79
assert.equal(harness.simulation.entityRecord(blockerId).tileX, 64);80
assert.equal(harness.simulation.debugWorld().entities.filter((entity) => entity.entityId === walkerId).length, 1);83
assert.equal(harness.simulation.debugWorld().entities.filter((entity) => entity.entityId === walkerId).length, 1);81
}84
}82
finally85
finally