Keep combat-logged-out characters fighting, with PvP cowardice mail.
Disconnect during or shortly after combat leaves the entity in the world with forced auto-cast until five quiet minutes pass; offline death forces a church resurrection letter, and PvP logout cowardice adds skull points plus a Questward warning (one free pass per clock hour). Co-authored-by: Cursor <cursoragent@cursor.com>
@@ -0,0 +1,150 @@
1
import { randomUUID } from "node:crypto";
2
import { ItemId, LETTER_MAX_BODY_CHARS } from "../../../shared/definitions/items.js";
3
import { attachOrigins, writtenOrigin } from "../../../shared/items/origin.js";
4
import { combatLevelFromSkills } from "../../../shared/combat/combatLevel.js";
5
import
6
{
7
combatLogoutCoinThreshold,
8
cowardiceHourKey
9
} from "../../../shared/combat/combatLogout.js";
10
import
11
{
12
CHURCH_LETTER_AUTHOR,
13
QUESTWARD_GIFT_AUTHOR,
14
QUESTWARD_GIFT_ORG,
15
formatChurchOfflineResurrectionBody,
16
formatCombatLogoutCowardiceBody
17
} from "../../../shared/courier/systemLetters.js";
18
import { defaultPlayerSkills } from "../../../shared/skills/state.js";
19
20
/**
21
* Apply PvP combat-logout cowardice (skull + bank letter), honouring the
22
* once-per-hour forgiveness. Returns whether a penalty was applied.
23
*/
24
export function applyCombatLogoutCowardice (simulation, characterId, {
25
coinsDropped = null,
26
now = Date.now()
27
} = {})
28
{
29
const id = characterId | 0;
30
const skills = simulation.stateDb.getSkills(id) ?? defaultPlayerSkills();
31
const threshold = combatLogoutCoinThreshold(combatLevelFromSkills(skills));
32
let amount;
33
if (coinsDropped == null)
34
{ amount = threshold; }
35
else if ((coinsDropped | 0) > threshold)
36
{ return { applied: false, forgiven: false, amount: 0, threshold }; }
37
else
38
{ amount = Math.max(0, threshold - (coinsDropped | 0)); }
39
40
if (amount <= 0)
41
{ return { applied: false, forgiven: false, amount: 0, threshold }; }
42
43
const hour = cowardiceHourKey(now);
44
const forgivenHour = simulation.stateDb.getCowardiceForgivenHour(id);
45
if (forgivenHour !== hour)
46
{
47
simulation.stateDb.setCowardiceForgivenHour(id, hour);
48
return { applied: false, forgiven: true, amount, threshold };
49
}
50
51
simulation.stateDb.addKillCounter(id, amount, now);
52
simulation.refreshCharacterSkull?.(id, { force: true });
53
dispatchCombatLogoutBankLetter(simulation, id);
54
return { applied: true, forgiven: false, amount, threshold };
55
}
56
57
export function dispatchCombatLogoutBankLetter (simulation, characterId)
58
{
59
const row = simulation.stateDb.getCharacter(characterId);
60
if (!row || !simulation.courier)
61
{ return; }
62
const body = formatCombatLogoutCowardiceBody().slice(0, LETTER_MAX_BODY_CHARS);
63
const stack = attachOrigins({
64
itemId: ItemId.letter,
65
quantity: 1,
66
origins: [{ origin: writtenOrigin(QUESTWARD_GIFT_AUTHOR), quantity: 1 }],
67
instance: {
68
kind: "letter",
69
letterId: randomUUID(),
70
authorCharacterId: 0,
71
authorDisplayName: QUESTWARD_GIFT_AUTHOR,
72
authorOrganization: QUESTWARD_GIFT_ORG,
73
body,
74
opened: false,
75
writtenAt: Date.now()
76
}
77
});
78
const originTileX = row.tile_x | 0;
79
const originTileY = row.tile_y | 0;
80
const bank = simulation.courier.nearestBank?.(originTileX, originTileY);
81
simulation.courier.dispatchSystemLetter({
82
characterId,
83
originTileX: bank?.tileX ?? originTileX,
84
originTileY: bank?.tileY ?? originTileY,
85
stack
86
});
87
}
88
89
export function dispatchChurchOfflineResurrectionLetter (simulation, characterId, tileX, tileY)
90
{
91
if (!simulation.courier)
92
{ return; }
93
const body = formatChurchOfflineResurrectionBody().slice(0, LETTER_MAX_BODY_CHARS);
94
const stack = attachOrigins({
95
itemId: ItemId.letter,
96
quantity: 1,
97
origins: [{ origin: writtenOrigin(CHURCH_LETTER_AUTHOR), quantity: 1 }],
98
instance: {
99
kind: "letter",
100
letterId: randomUUID(),
101
authorCharacterId: 0,
102
authorDisplayName: CHURCH_LETTER_AUTHOR,
103
authorOrganization: null,
104
body,
105
opened: false,
106
writtenAt: Date.now()
107
}
108
});
109
const altar = nearestAltarTile(simulation, tileX, tileY);
110
simulation.courier.dispatchSystemLetter({
111
characterId,
112
originTileX: altar?.tileX ?? (tileX | 0),
113
originTileY: altar?.tileY ?? (tileY | 0),
114
stack
115
});
116
}
117
118
function nearestAltarTile (simulation, tileX, tileY)
119
{
120
const altars = simulation.altarTiles ?? [];
121
if (!altars.length)
122
{ return null; }
123
let best = null;
124
let bestDist = Infinity;
125
for (const altar of altars)
126
{
127
const dist = Math.hypot((altar.tileX | 0) - (tileX | 0), (altar.tileY | 0) - (tileY | 0));
128
if (dist < bestDist)
129
{
130
best = altar;
131
bestDist = dist;
132
}
133
}
134
return best;
135
}
136
137
export function coinsDroppedFromDeathEvents (events)
138
{
139
let total = 0;
140
for (const event of events ?? [])
141
{
142
if (event.type !== "ground-item-appear")
143
{ continue; }
144
const itemId = event.stack?.itemId ?? event.itemId;
145
if ((itemId | 0) !== ItemId.coins)
146
{ continue; }
147
total += Math.max(0, event.stack?.quantity | 0);
148
}
149
return total;
150
}
@@ -0,0 +1,150 @@1
import { randomUUID } from "node:crypto";2
import { ItemId, LETTER_MAX_BODY_CHARS } from "../../../shared/definitions/items.js";3
import { attachOrigins, writtenOrigin } from "../../../shared/items/origin.js";4
import { combatLevelFromSkills } from "../../../shared/combat/combatLevel.js";5
import6
{7
combatLogoutCoinThreshold,8
cowardiceHourKey9
} from "../../../shared/combat/combatLogout.js";10
import11
{12
CHURCH_LETTER_AUTHOR,13
QUESTWARD_GIFT_AUTHOR,14
QUESTWARD_GIFT_ORG,15
formatChurchOfflineResurrectionBody,16
formatCombatLogoutCowardiceBody17
} from "../../../shared/courier/systemLetters.js";18
import { defaultPlayerSkills } from "../../../shared/skills/state.js";19
20
/**21
* Apply PvP combat-logout cowardice (skull + bank letter), honouring the22
* once-per-hour forgiveness. Returns whether a penalty was applied.23
*/24
export function applyCombatLogoutCowardice (simulation, characterId, {25
coinsDropped = null,26
now = Date.now()27
} = {})28
{29
const id = characterId | 0;30
const skills = simulation.stateDb.getSkills(id) ?? defaultPlayerSkills();31
const threshold = combatLogoutCoinThreshold(combatLevelFromSkills(skills));32
let amount;33
if (coinsDropped == null)34
{ amount = threshold; }35
else if ((coinsDropped | 0) > threshold)36
{ return { applied: false, forgiven: false, amount: 0, threshold }; }37
else38
{ amount = Math.max(0, threshold - (coinsDropped | 0)); }39
40
if (amount <= 0)41
{ return { applied: false, forgiven: false, amount: 0, threshold }; }42
43
const hour = cowardiceHourKey(now);44
const forgivenHour = simulation.stateDb.getCowardiceForgivenHour(id);45
if (forgivenHour !== hour)46
{47
simulation.stateDb.setCowardiceForgivenHour(id, hour);48
return { applied: false, forgiven: true, amount, threshold };49
}50
51
simulation.stateDb.addKillCounter(id, amount, now);52
simulation.refreshCharacterSkull?.(id, { force: true });53
dispatchCombatLogoutBankLetter(simulation, id);54
return { applied: true, forgiven: false, amount, threshold };55
}56
57
export function dispatchCombatLogoutBankLetter (simulation, characterId)58
{59
const row = simulation.stateDb.getCharacter(characterId);60
if (!row || !simulation.courier)61
{ return; }62
const body = formatCombatLogoutCowardiceBody().slice(0, LETTER_MAX_BODY_CHARS);63
const stack = attachOrigins({64
itemId: ItemId.letter,65
quantity: 1,66
origins: [{ origin: writtenOrigin(QUESTWARD_GIFT_AUTHOR), quantity: 1 }],67
instance: {68
kind: "letter",69
letterId: randomUUID(),70
authorCharacterId: 0,71
authorDisplayName: QUESTWARD_GIFT_AUTHOR,72
authorOrganization: QUESTWARD_GIFT_ORG,73
body,74
opened: false,75
writtenAt: Date.now()76
}77
});78
const originTileX = row.tile_x | 0;79
const originTileY = row.tile_y | 0;80
const bank = simulation.courier.nearestBank?.(originTileX, originTileY);81
simulation.courier.dispatchSystemLetter({82
characterId,83
originTileX: bank?.tileX ?? originTileX,84
originTileY: bank?.tileY ?? originTileY,85
stack86
});87
}88
89
export function dispatchChurchOfflineResurrectionLetter (simulation, characterId, tileX, tileY)90
{91
if (!simulation.courier)92
{ return; }93
const body = formatChurchOfflineResurrectionBody().slice(0, LETTER_MAX_BODY_CHARS);94
const stack = attachOrigins({95
itemId: ItemId.letter,96
quantity: 1,97
origins: [{ origin: writtenOrigin(CHURCH_LETTER_AUTHOR), quantity: 1 }],98
instance: {99
kind: "letter",100
letterId: randomUUID(),101
authorCharacterId: 0,102
authorDisplayName: CHURCH_LETTER_AUTHOR,103
authorOrganization: null,104
body,105
opened: false,106
writtenAt: Date.now()107
}108
});109
const altar = nearestAltarTile(simulation, tileX, tileY);110
simulation.courier.dispatchSystemLetter({111
characterId,112
originTileX: altar?.tileX ?? (tileX | 0),113
originTileY: altar?.tileY ?? (tileY | 0),114
stack115
});116
}117
118
function nearestAltarTile (simulation, tileX, tileY)119
{120
const altars = simulation.altarTiles ?? [];121
if (!altars.length)122
{ return null; }123
let best = null;124
let bestDist = Infinity;125
for (const altar of altars)126
{127
const dist = Math.hypot((altar.tileX | 0) - (tileX | 0), (altar.tileY | 0) - (tileY | 0));128
if (dist < bestDist)129
{130
best = altar;131
bestDist = dist;132
}133
}134
return best;135
}136
137
export function coinsDroppedFromDeathEvents (events)138
{139
let total = 0;140
for (const event of events ?? [])141
{142
if (event.type !== "ground-item-appear")143
{ continue; }144
const itemId = event.stack?.itemId ?? event.itemId;145
if ((itemId | 0) !== ItemId.coins)146
{ continue; }147
total += Math.max(0, event.stack?.quantity | 0);148
}149
return total;150
}@@ -1139,7 +1139,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1139
1139
if (other === session || other.account.account_id !== session.account.account_id || !other.characterId)
1140
1140
{ continue; }
1141
1141
const sameCharacter = other.characterId === targetCharacterId;
1142
if (sameCharacter && simulation.isCharacterOnline(targetCharacterId))
1142
if (sameCharacter && simulation.isCharacterInWorld(targetCharacterId))
1143
1143
{ handoffEntityId = simulation.entityForCharacter(targetCharacterId); }
1144
1144
disconnectPlayingSession(other, {
1145
1145
despawn: !sameCharacter,
@@ -1149,6 +1149,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1149
1149
});
1150
1150
}
1151
1151
session.characterId = targetCharacterId;
1152
if (handoffEntityId == null && simulation.isCharacterInWorld(targetCharacterId))
1153
{ handoffEntityId = simulation.entityForCharacter(targetCharacterId); }
1152
1154
if (handoffEntityId != null)
1153
1155
{
1154
1156
const entityId = simulation.reattachCharacterSession(targetCharacterId, session.id);
@@ -1244,7 +1246,9 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1244
1246
session.staticSubscribed.clear();
1245
1247
if (despawn && characterId)
1246
1248
{
1247
simulation.despawnCharacter(characterId);
1249
const stayed = simulation.beginCombatLogout(characterId);
1250
if (!stayed)
1251
{ simulation.despawnCharacter(characterId); }
1248
1252
publishReplication(simulation.drainReplication());
1249
1253
}
1250
1254
session.suppressLeaveWorldOnClose = true;
@@ -1258,7 +1262,11 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1258
1262
{
1259
1263
const accountId = session.account?.account_id | 0;
1260
1264
if (session.characterId)
1261
{ simulation.despawnCharacter(session.characterId); }
1265
{
1266
const stayed = simulation.beginCombatLogout(session.characterId);
1267
if (!stayed)
1268
{ simulation.despawnCharacter(session.characterId); }
1269
}
1262
1270
publishReplication(simulation.drainReplication());
1263
1271
session.characterId = null;
1264
1272
session.entityId = null;
@@ -1139,7 +1139,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,1139
if (other === session || other.account.account_id !== session.account.account_id || !other.characterId)1139
if (other === session || other.account.account_id !== session.account.account_id || !other.characterId)1140
{ continue; }1140
{ continue; }1141
const sameCharacter = other.characterId === targetCharacterId;1141
const sameCharacter = other.characterId === targetCharacterId;1142
if (sameCharacter && simulation.isCharacterOnline(targetCharacterId))1142
if (sameCharacter && simulation.isCharacterInWorld(targetCharacterId))1143
{ handoffEntityId = simulation.entityForCharacter(targetCharacterId); }1143
{ handoffEntityId = simulation.entityForCharacter(targetCharacterId); }1144
disconnectPlayingSession(other, {1144
disconnectPlayingSession(other, {1145
despawn: !sameCharacter,1145
despawn: !sameCharacter,@@ -1149,6 +1149,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,1149
});1149
});1150
}1150
}1151
session.characterId = targetCharacterId;1151
session.characterId = targetCharacterId;1152
if (handoffEntityId == null && simulation.isCharacterInWorld(targetCharacterId))1153
{ handoffEntityId = simulation.entityForCharacter(targetCharacterId); }1152
if (handoffEntityId != null)1154
if (handoffEntityId != null)1153
{1155
{1154
const entityId = simulation.reattachCharacterSession(targetCharacterId, session.id);1156
const entityId = simulation.reattachCharacterSession(targetCharacterId, session.id);@@ -1244,7 +1246,9 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,1244
session.staticSubscribed.clear();1246
session.staticSubscribed.clear();1245
if (despawn && characterId)1247
if (despawn && characterId)1246
{1248
{1247
simulation.despawnCharacter(characterId);1249
const stayed = simulation.beginCombatLogout(characterId);1250
if (!stayed)1251
{ simulation.despawnCharacter(characterId); }1248
publishReplication(simulation.drainReplication());1252
publishReplication(simulation.drainReplication());1249
}1253
}1250
session.suppressLeaveWorldOnClose = true;1254
session.suppressLeaveWorldOnClose = true;@@ -1258,7 +1262,11 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,1258
{1262
{1259
const accountId = session.account?.account_id | 0;1263
const accountId = session.account?.account_id | 0;1260
if (session.characterId)1264
if (session.characterId)1261
{ simulation.despawnCharacter(session.characterId); }1265
{1266
const stayed = simulation.beginCombatLogout(session.characterId);1267
if (!stayed)1268
{ simulation.despawnCharacter(session.characterId); }1269
}1262
publishReplication(simulation.drainReplication());1270
publishReplication(simulation.drainReplication());1263
session.characterId = null;1271
session.characterId = null;1264
session.entityId = null;1272
session.entityId = null;@@ -260,6 +260,8 @@ export class StateDatabase
260
260
{ this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter REAL NOT NULL DEFAULT 0"); }
261
261
if (!characterColumns.some((column) => column.name === "kill_counter_at"))
262
262
{ this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter_at INTEGER"); }
263
if (!characterColumns.some((column) => column.name === "cowardice_forgiven_hour"))
264
{ this.db.exec("ALTER TABLE characters ADD COLUMN cowardice_forgiven_hour INTEGER"); }
263
265
const marketColumns = this.db.prepare("PRAGMA table_info(market_orders)").all();
264
266
if (!marketColumns.some((column) => column.name === "listing_key"))
265
267
{ this.db.exec("ALTER TABLE market_orders ADD COLUMN listing_key TEXT"); }
@@ -1207,6 +1209,21 @@ export class StateDatabase
1207
1209
return this.setKillCounter(characterId, next, now);
1208
1210
}
1209
1211
1212
getCowardiceForgivenHour (characterId)
1213
{
1214
const row = this.getCharacter(characterId);
1215
if (!row || row.cowardice_forgiven_hour == null)
1216
{ return null; }
1217
return row.cowardice_forgiven_hour | 0;
1218
}
1219
1220
setCowardiceForgivenHour (characterId, hourKey)
1221
{
1222
this.db.prepare(`
1223
UPDATE characters SET cowardice_forgiven_hour = ? WHERE character_id = ?
1224
`).run(hourKey | 0, characterId | 0);
1225
}
1226
1210
1227
listPersistentInRegion (minX, minY, maxX, maxY)
1211
1228
{
1212
1229
return this.db.prepare(`
@@ -260,6 +260,8 @@ export class StateDatabase260
{ this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter REAL NOT NULL DEFAULT 0"); }260
{ this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter REAL NOT NULL DEFAULT 0"); }261
if (!characterColumns.some((column) => column.name === "kill_counter_at"))261
if (!characterColumns.some((column) => column.name === "kill_counter_at"))262
{ this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter_at INTEGER"); }262
{ this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter_at INTEGER"); }263
if (!characterColumns.some((column) => column.name === "cowardice_forgiven_hour"))264
{ this.db.exec("ALTER TABLE characters ADD COLUMN cowardice_forgiven_hour INTEGER"); }263
const marketColumns = this.db.prepare("PRAGMA table_info(market_orders)").all();265
const marketColumns = this.db.prepare("PRAGMA table_info(market_orders)").all();264
if (!marketColumns.some((column) => column.name === "listing_key"))266
if (!marketColumns.some((column) => column.name === "listing_key"))265
{ this.db.exec("ALTER TABLE market_orders ADD COLUMN listing_key TEXT"); }267
{ this.db.exec("ALTER TABLE market_orders ADD COLUMN listing_key TEXT"); }@@ -1207,6 +1209,21 @@ export class StateDatabase1207
return this.setKillCounter(characterId, next, now);1209
return this.setKillCounter(characterId, next, now);1208
}1210
}1209
1211
1212
getCowardiceForgivenHour (characterId)1213
{1214
const row = this.getCharacter(characterId);1215
if (!row || row.cowardice_forgiven_hour == null)1216
{ return null; }1217
return row.cowardice_forgiven_hour | 0;1218
}1219
1220
setCowardiceForgivenHour (characterId, hourKey)1221
{1222
this.db.prepare(`1223
UPDATE characters SET cowardice_forgiven_hour = ? WHERE character_id = ?1224
`).run(hourKey | 0, characterId | 0);1225
}1226
1210
listPersistentInRegion (minX, minY, maxX, maxY)1227
listPersistentInRegion (minX, minY, maxX, maxY)1211
{1228
{1212
return this.db.prepare(`1229
return this.db.prepare(`@@ -46,5 +46,7 @@ export const WorkerMessage = Object.freeze({
46
46
engageTarget: "engageTarget",
47
47
listTownGuardsNear: "listTownGuardsNear",
48
48
pinDialogue: "pinDialogue",
49
unpinDialogue: "unpinDialogue"
49
unpinDialogue: "unpinDialogue",
50
setSpellAutoCast: "setSpellAutoCast",
51
inspectCombatState: "inspectCombatState"
50
52
});
@@ -46,5 +46,7 @@ export const WorkerMessage = Object.freeze({46
engageTarget: "engageTarget",46
engageTarget: "engageTarget",47
listTownGuardsNear: "listTownGuardsNear",47
listTownGuardsNear: "listTownGuardsNear",48
pinDialogue: "pinDialogue",48
pinDialogue: "pinDialogue",49
unpinDialogue: "unpinDialogue"49
unpinDialogue: "unpinDialogue",50
setSpellAutoCast: "setSpellAutoCast",51
inspectCombatState: "inspectCombatState"50
});52
});@@ -34,6 +34,13 @@ import { replicationAppearance, replicationDespawn, replicationSpawn } from "../
34
34
import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
35
35
import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";
36
36
import { skullValue, decayKillCounter, SKULL_KILL_BONUS } from "../../../shared/combat/skull.js";
37
import { COMBAT_LOGOUT_MS } from "../../../shared/combat/combatLogout.js";
38
import
39
{
40
applyCombatLogoutCowardice,
41
coinsDroppedFromDeathEvents,
42
dispatchChurchOfflineResurrectionLetter
43
} from "../combat/combatLogout.js";
37
44
import { mobComponents } from "./spawners.js";
38
45
import { shadeSummonComponents } from "../spells/summons.js";
39
46
import { jadeiteFairyComponents } from "../spells/jadeiteFairy.js";
@@ -69,6 +76,10 @@ export class Simulation
69
76
this.regionGraceUntil = new Map();
70
77
this.directory = new Map();
71
78
this.characterEntities = new Map();
79
/** @type {Map<number, { lastCombatEndedAt: number|null, lastOutboundAttackAt: number|null, lastCombatActivityAt: number|null, pvpInvolved: boolean, wasInCombat: boolean }>} */
80
this.combatTracking = new Map();
81
/** @type {Map<number, { savedAutoCast: boolean, pendingCowardice: boolean, startedAt: number }>} */
82
this.combatLogouts = new Map();
72
83
this.commandQueue = [];
73
84
this.replication = [];
74
85
this.pendingPrivate = [];
@@ -280,6 +291,13 @@ export class Simulation
280
291
events.push(...this.#applyPlayerDeath(event));
281
292
continue;
282
293
}
294
if (
295
event.type === "combat-hit"
296
|| event.type === "combat-miss"
297
|| event.type === "combat-block"
298
|| event.type === "combat-swing"
299
)
300
{ this.#noteCombatEvent(event); }
283
301
if (event.type === "mob-killed")
284
302
{
285
303
events.push(...this.#applyMobKilled(event));
@@ -353,7 +371,10 @@ export class Simulation
353
371
{ events.push(...this.#stepSpawners()); }
354
372
355
373
if (this.tickIndex % Math.max(1, Math.round(simHz)) === 0)
356
{ this.#stepSkullDecay(); }
374
{
375
this.#stepSkullDecay();
376
events.push(...this.#stepCombatLogout());
377
}
357
378
358
379
if (this.courier)
359
380
{ events.push(...this.courier.step(now, dt)); }
@@ -581,7 +602,70 @@ export class Simulation
581
602
582
603
isCharacterOnline (characterId)
583
604
{
584
return this.characterEntities.has(characterId);
605
const id = characterId | 0;
606
return this.characterEntities.has(id) && !this.combatLogouts.has(id);
607
}
608
609
/** True while the entity exists, including combat-logout ghosts without a session. */
610
isCharacterInWorld (characterId)
611
{
612
return this.characterEntities.has(characterId | 0);
613
}
614
615
isCombatLogout (characterId)
616
{
617
return this.combatLogouts.has(characterId | 0);
618
}
619
620
/** Apply a worker `player-died` event (also used by combat-logout tests). */
621
applyPlayerDiedEvent (event)
622
{
623
return this.#applyPlayerDeath(event);
624
}
625
626
/**
627
* Keep the character fighting after the controlling session leaves.
628
* @returns {boolean} true when the character stayed in the world
629
*/
630
beginCombatLogout (characterId)
631
{
632
const id = characterId | 0;
633
if (!this.characterEntities.has(id))
634
{ return false; }
635
if (this.combatLogouts.has(id))
636
{ return true; }
637
const row = this.stateDb.getCharacter(id);
638
if (row?.is_dead)
639
{ return false; }
640
if (!this.#shouldStayOnLeave(id))
641
{ return false; }
642
this.market?.leaveExchangeStations?.(id);
643
const track = this.#ensureCombatTrack(id);
644
const spells = this.#setCharacterAutoCast(id, true);
645
this.combatLogouts.set(id, {
646
savedAutoCast: spells?.previousAutoCast ?? false,
647
pendingCowardice: !!track.pvpInvolved,
648
startedAt: this.now
649
});
650
return true;
651
}
652
653
/**
654
* Player reclaimed the character. Restore prefs and apply pending PvP cowardice.
655
*/
656
endCombatLogout (characterId, { applyCowardice = true } = {})
657
{
658
const id = characterId | 0;
659
const logout = this.combatLogouts.get(id);
660
if (!logout)
661
{ return { ended: false }; }
662
let cowardice = null;
663
// Apply while still marked combat-logout so system letters stay held offline.
664
if (applyCowardice && logout.pendingCowardice)
665
{ cowardice = applyCombatLogoutCowardice(this, id, { now: this.now }); }
666
this.#restoreCombatLogoutAutoCast(id, logout);
667
this.combatLogouts.delete(id);
668
return { ended: true, cowardice };
585
669
}
586
670
587
671
reattachCharacterSession (characterId, sessionId)
@@ -600,9 +684,220 @@ export class Simulation
600
684
if (!result?.ok)
601
685
{ return null; }
602
686
this.market?.reattachSession?.(characterId, sessionId);
687
if (this.combatLogouts.has(characterId | 0))
688
{ this.endCombatLogout(characterId, { applyCowardice: true }); }
603
689
return entityId;
604
690
}
605
691
692
#ensureCombatTrack (characterId)
693
{
694
const id = characterId | 0;
695
let track = this.combatTracking.get(id);
696
if (!track)
697
{
698
track = {
699
lastCombatEndedAt: null,
700
lastOutboundAttackAt: null,
701
lastCombatActivityAt: null,
702
pvpInvolved: false,
703
wasInCombat: false
704
};
705
this.combatTracking.set(id, track);
706
}
707
return track;
708
}
709
710
#notePlayerAttack (characterId, targetEntityId)
711
{
712
const id = characterId | 0;
713
if (!id)
714
{ return; }
715
const track = this.#ensureCombatTrack(id);
716
const now = this.now;
717
track.lastOutboundAttackAt = now;
718
track.lastCombatActivityAt = now;
719
track.wasInCombat = true;
720
const targetRecord = this.directory.get(targetEntityId);
721
if (targetRecord?.characterId)
722
{
723
track.pvpInvolved = true;
724
const logout = this.combatLogouts.get(id);
725
if (logout)
726
{ logout.pendingCowardice = true; }
727
const other = this.#ensureCombatTrack(targetRecord.characterId);
728
other.pvpInvolved = true;
729
other.lastCombatActivityAt = now;
730
other.wasInCombat = true;
731
const otherLogout = this.combatLogouts.get(targetRecord.characterId | 0);
732
if (otherLogout)
733
{ otherLogout.pendingCowardice = true; }
734
}
735
}
736
737
#noteCombatEvent (event)
738
{
739
const attackerId = event.attackerId;
740
const targetId = event.targetId;
741
const attackerRecord = attackerId != null ? this.directory.get(attackerId) : null;
742
const targetRecord = targetId != null ? this.directory.get(targetId) : null;
743
const pvp = !!(attackerRecord?.characterId && targetRecord?.characterId);
744
const now = this.now;
745
if (attackerRecord?.characterId)
746
{
747
const track = this.#ensureCombatTrack(attackerRecord.characterId);
748
track.lastOutboundAttackAt = now;
749
track.lastCombatActivityAt = now;
750
track.wasInCombat = true;
751
if (pvp)
752
{
753
track.pvpInvolved = true;
754
const logout = this.combatLogouts.get(attackerRecord.characterId | 0);
755
if (logout)
756
{ logout.pendingCowardice = true; }
757
}
758
}
759
if (targetRecord?.characterId && event.type !== "combat-swing")
760
{
761
const track = this.#ensureCombatTrack(targetRecord.characterId);
762
track.lastCombatActivityAt = now;
763
track.wasInCombat = true;
764
if (pvp)
765
{
766
track.pvpInvolved = true;
767
const logout = this.combatLogouts.get(targetRecord.characterId | 0);
768
if (logout)
769
{ logout.pendingCowardice = true; }
770
}
771
}
772
}
773
774
#characterInCombat (entityId)
775
{
776
const record = this.directory.get(entityId);
777
if (!record)
778
{ return false; }
779
const state = this.workers[record.workerId].call({
780
type: WorkerMessage.inspectCombatState,
781
entityId
782
});
783
return !!state?.inCombat;
784
}
785
786
#shouldStayOnLeave (characterId)
787
{
788
const id = characterId | 0;
789
const entityId = this.characterEntities.get(id);
790
if (!entityId)
791
{ return false; }
792
const inCombat = this.#characterInCombat(entityId);
793
if (inCombat)
794
{ return true; }
795
const track = this.combatTracking.get(id);
796
if (!track)
797
{ return false; }
798
const now = this.now;
799
const endedRecently = track.lastCombatEndedAt != null
800
&& (now - track.lastCombatEndedAt) <= COMBAT_LOGOUT_MS;
801
const attackedRecently = track.lastOutboundAttackAt != null
802
&& (now - track.lastOutboundAttackAt) <= COMBAT_LOGOUT_MS;
803
return endedRecently && attackedRecently;
804
}
805
806
#setCharacterAutoCast (characterId, autoCast)
807
{
808
const entityId = this.characterEntities.get(characterId | 0);
809
const record = entityId ? this.directory.get(entityId) : null;
810
if (!record)
811
{ return null; }
812
return this.workers[record.workerId].call({
813
type: WorkerMessage.setSpellAutoCast,
814
entityId,
815
autoCast: !!autoCast
816
});
817
}
818
819
#restoreCombatLogoutAutoCast (characterId, logout)
820
{
821
if (!logout)
822
{ return; }
823
this.#setCharacterAutoCast(characterId, !!logout.savedAutoCast);
824
const stored = this.stateDb.getSpells(characterId);
825
if (stored)
826
{
827
this.stateDb.saveSpells(characterId, {
828
...stored,
829
autoCast: !!logout.savedAutoCast
830
});
831
}
832
}
833
834
#stepCombatLogout ()
835
{
836
const events = [];
837
const now = this.now;
838
for (const [characterId, entityId] of this.characterEntities)
839
{
840
const inCombat = this.#characterInCombat(entityId);
841
const track = this.#ensureCombatTrack(characterId);
842
if (track.wasInCombat && !inCombat)
843
{ track.lastCombatEndedAt = now; }
844
track.wasInCombat = inCombat;
845
}
846
for (const [characterId, logout] of [...this.combatLogouts.entries()])
847
{
848
const track = this.combatTracking.get(characterId);
849
const lastActivity = track?.lastCombatActivityAt ?? logout.startedAt;
850
if ((now - lastActivity) < COMBAT_LOGOUT_MS)
851
{ continue; }
852
if (logout.pendingCowardice)
853
{ applyCombatLogoutCowardice(this, characterId, { now }); }
854
this.#restoreCombatLogoutAutoCast(characterId, logout);
855
this.combatLogouts.delete(characterId);
856
this.despawnCharacter(characterId);
857
}
858
return events;
859
}
860
861
despawnCharacter (characterId)
862
{
863
this.market?.leaveExchangeStations?.(characterId);
864
const entityId = this.characterEntities.get(characterId);
865
if (!entityId)
866
{
867
this.combatLogouts.delete(characterId | 0);
868
return;
869
}
870
const record = this.directory.get(entityId);
871
if (!record)
872
{
873
this.characterEntities.delete(characterId);
874
this.combatLogouts.delete(characterId | 0);
875
return;
876
}
877
this.#saveBag(entityId, record.workerId);
878
const dropped = this.workers[record.workerId].call({
879
type: WorkerMessage.despawnCharacter,
880
characterId
881
});
882
if (dropped)
883
{
884
this.stateDb.saveCharacterPosition(
885
characterId,
886
dropped.tileX,
887
dropped.tileY,
888
dropped.gait ?? GAIT.walk,
889
dropped.dimensionId ?? OVERWORLD_ID
890
);
891
if (dropped.health != null)
892
{ this.stateDb.saveCharacterHealth(characterId, dropped.health); }
893
this.#queueReplication(replicationDespawn(dropped));
894
}
895
this.#forget(entityId);
896
this.combatLogouts.delete(characterId | 0);
897
this.#recalculateActivation(this.now);
898
this.#syncGhosts();
899
}
900
606
901
spawnEntity (components, options = {})
607
902
{
608
903
const entityId = options.entityId ?? this.nextEntityId++;
@@ -892,41 +1187,6 @@ export class Simulation
892
1187
});
893
1188
}
894
1189
895
despawnCharacter (characterId)
896
{
897
this.market?.leaveExchangeStations?.(characterId);
898
const entityId = this.characterEntities.get(characterId);
899
if (!entityId)
900
{ return; }
901
const record = this.directory.get(entityId);
902
if (!record)
903
{
904
this.characterEntities.delete(characterId);
905
return;
906
}
907
this.#saveBag(entityId, record.workerId);
908
const dropped = this.workers[record.workerId].call({
909
type: WorkerMessage.despawnCharacter,
910
characterId
911
});
912
if (dropped)
913
{
914
this.stateDb.saveCharacterPosition(
915
characterId,
916
dropped.tileX,
917
dropped.tileY,
918
dropped.gait ?? GAIT.walk,
919
dropped.dimensionId ?? OVERWORLD_ID
920
);
921
if (dropped.health != null)
922
{ this.stateDb.saveCharacterHealth(characterId, dropped.health); }
923
this.#queueReplication(replicationDespawn(dropped));
924
}
925
this.#forget(entityId);
926
this.#recalculateActivation(this.now);
927
this.#syncGhosts();
928
}
929
930
1190
entityForCharacter (characterId)
931
1191
{
932
1192
return this.characterEntities.get(characterId) ?? null;
@@ -1317,14 +1577,32 @@ export class Simulation
1317
1577
events.push(...this.#handleOpenDialogue(event));
1318
1578
continue;
1319
1579
}
1580
if (
1581
event.type === "combat-hit"
1582
|| event.type === "combat-miss"
1583
|| event.type === "combat-block"
1584
|| event.type === "combat-swing"
1585
)
1586
{ this.#noteCombatEvent(event); }
1587
if (event.type === "player-died")
1588
{
1589
events.push(...this.#applyPlayerDeath(event));
1590
continue;
1591
}
1320
1592
events.push(event);
1321
1593
}
1322
1594
if (item.command.type === "attack" && item.command.targetEntityId != null)
1323
1595
{
1596
this.#notePlayerAttack(item.command.characterId, item.command.targetEntityId);
1324
1597
events.push(...this.#mapQuestPrivateEvents(
1325
1598
this.quests?.interruptDialogueForEntity(item.command.targetEntityId) ?? []
1326
1599
));
1327
1600
}
1601
if (
1602
(item.command.type === "cast-spell-entity")
1603
&& item.command.targetEntityId != null
1604
)
1605
{ this.#notePlayerAttack(item.command.characterId, item.command.targetEntityId); }
1328
1606
if (result?.private)
1329
1607
{
1330
1608
events.push({
@@ -1393,6 +1671,13 @@ export class Simulation
1393
1671
events.push(...this.#applyPlayerDeath(event));
1394
1672
continue;
1395
1673
}
1674
if (
1675
event.type === "combat-hit"
1676
|| event.type === "combat-miss"
1677
|| event.type === "combat-block"
1678
|| event.type === "combat-swing"
1679
)
1680
{ this.#noteCombatEvent(event); }
1396
1681
if (event.type === "mob-killed")
1397
1682
{
1398
1683
events.push(...this.#applyMobKilled(event));
@@ -1459,6 +1744,13 @@ export class Simulation
1459
1744
events.push(...this.#applyPlayerDeath(event));
1460
1745
continue;
1461
1746
}
1747
if (
1748
event.type === "combat-hit"
1749
|| event.type === "combat-miss"
1750
|| event.type === "combat-block"
1751
|| event.type === "combat-swing"
1752
)
1753
{ this.#noteCombatEvent(event); }
1462
1754
if (event.type === "mob-killed")
1463
1755
{
1464
1756
events.push(...this.#applyMobKilled(event));
@@ -1884,6 +2176,40 @@ export class Simulation
1884
2176
});
1885
2177
}
1886
2178
}
2179
const coinsDropped = coinsDroppedFromDeathEvents(events);
2180
if (this.combatLogouts.has(event.characterId | 0))
2181
{ events.push(...this.#finishCombatLogoutDeath(event, coinsDropped)); }
2182
return events;
2183
}
2184
2185
#finishCombatLogoutDeath (event, coinsDropped)
2186
{
2187
const characterId = event.characterId | 0;
2188
const logout = this.combatLogouts.get(characterId);
2189
const events = [];
2190
if (logout?.pendingCowardice)
2191
{
2192
applyCombatLogoutCowardice(this, characterId, {
2193
coinsDropped,
2194
now: this.now
2195
});
2196
}
2197
dispatchChurchOfflineResurrectionLetter(
2198
this,
2199
characterId,
2200
event.tileX | 0,
2201
event.tileY | 0
2202
);
2203
try
2204
{ events.push(...this.#respawnCharacter(event.sessionId ?? null, characterId)); }
2205
catch
2206
{
2207
// Respawn can fail without an altar tile; still despawn the corpse session.
2208
}
2209
this.#restoreCombatLogoutAutoCast(characterId, logout);
2210
this.combatLogouts.delete(characterId);
2211
this.combatTracking.delete(characterId);
2212
this.despawnCharacter(characterId);
1887
2213
return events;
1888
2214
}
1889
2215
@@ -34,6 +34,13 @@ import { replicationAppearance, replicationDespawn, replicationSpawn } from "../34
import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";34
import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";35
import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";35
import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";36
import { skullValue, decayKillCounter, SKULL_KILL_BONUS } from "../../../shared/combat/skull.js";36
import { skullValue, decayKillCounter, SKULL_KILL_BONUS } from "../../../shared/combat/skull.js";37
import { COMBAT_LOGOUT_MS } from "../../../shared/combat/combatLogout.js";38
import39
{40
applyCombatLogoutCowardice,41
coinsDroppedFromDeathEvents,42
dispatchChurchOfflineResurrectionLetter43
} from "../combat/combatLogout.js";37
import { mobComponents } from "./spawners.js";44
import { mobComponents } from "./spawners.js";38
import { shadeSummonComponents } from "../spells/summons.js";45
import { shadeSummonComponents } from "../spells/summons.js";39
import { jadeiteFairyComponents } from "../spells/jadeiteFairy.js";46
import { jadeiteFairyComponents } from "../spells/jadeiteFairy.js";@@ -69,6 +76,10 @@ export class Simulation69
this.regionGraceUntil = new Map();76
this.regionGraceUntil = new Map();70
this.directory = new Map();77
this.directory = new Map();71
this.characterEntities = new Map();78
this.characterEntities = new Map();79
/** @type {Map<number, { lastCombatEndedAt: number|null, lastOutboundAttackAt: number|null, lastCombatActivityAt: number|null, pvpInvolved: boolean, wasInCombat: boolean }>} */80
this.combatTracking = new Map();81
/** @type {Map<number, { savedAutoCast: boolean, pendingCowardice: boolean, startedAt: number }>} */82
this.combatLogouts = new Map();72
this.commandQueue = [];83
this.commandQueue = [];73
this.replication = [];84
this.replication = [];74
this.pendingPrivate = [];85
this.pendingPrivate = [];@@ -280,6 +291,13 @@ export class Simulation280
events.push(...this.#applyPlayerDeath(event));291
events.push(...this.#applyPlayerDeath(event));281
continue;292
continue;282
}293
}294
if (295
event.type === "combat-hit"296
|| event.type === "combat-miss"297
|| event.type === "combat-block"298
|| event.type === "combat-swing"299
)300
{ this.#noteCombatEvent(event); }283
if (event.type === "mob-killed")301
if (event.type === "mob-killed")284
{302
{285
events.push(...this.#applyMobKilled(event));303
events.push(...this.#applyMobKilled(event));@@ -353,7 +371,10 @@ export class Simulation353
{ events.push(...this.#stepSpawners()); }371
{ events.push(...this.#stepSpawners()); }354
372
355
if (this.tickIndex % Math.max(1, Math.round(simHz)) === 0)373
if (this.tickIndex % Math.max(1, Math.round(simHz)) === 0)356
{ this.#stepSkullDecay(); }374
{375
this.#stepSkullDecay();376
events.push(...this.#stepCombatLogout());377
}357
378
358
if (this.courier)379
if (this.courier)359
{ events.push(...this.courier.step(now, dt)); }380
{ events.push(...this.courier.step(now, dt)); }@@ -581,7 +602,70 @@ export class Simulation581
602
582
isCharacterOnline (characterId)603
isCharacterOnline (characterId)583
{604
{584
return this.characterEntities.has(characterId);605
const id = characterId | 0;606
return this.characterEntities.has(id) && !this.combatLogouts.has(id);607
}608
609
/** True while the entity exists, including combat-logout ghosts without a session. */610
isCharacterInWorld (characterId)611
{612
return this.characterEntities.has(characterId | 0);613
}614
615
isCombatLogout (characterId)616
{617
return this.combatLogouts.has(characterId | 0);618
}619
620
/** Apply a worker `player-died` event (also used by combat-logout tests). */621
applyPlayerDiedEvent (event)622
{623
return this.#applyPlayerDeath(event);624
}625
626
/**627
* Keep the character fighting after the controlling session leaves.628
* @returns {boolean} true when the character stayed in the world629
*/630
beginCombatLogout (characterId)631
{632
const id = characterId | 0;633
if (!this.characterEntities.has(id))634
{ return false; }635
if (this.combatLogouts.has(id))636
{ return true; }637
const row = this.stateDb.getCharacter(id);638
if (row?.is_dead)639
{ return false; }640
if (!this.#shouldStayOnLeave(id))641
{ return false; }642
this.market?.leaveExchangeStations?.(id);643
const track = this.#ensureCombatTrack(id);644
const spells = this.#setCharacterAutoCast(id, true);645
this.combatLogouts.set(id, {646
savedAutoCast: spells?.previousAutoCast ?? false,647
pendingCowardice: !!track.pvpInvolved,648
startedAt: this.now649
});650
return true;651
}652
653
/**654
* Player reclaimed the character. Restore prefs and apply pending PvP cowardice.655
*/656
endCombatLogout (characterId, { applyCowardice = true } = {})657
{658
const id = characterId | 0;659
const logout = this.combatLogouts.get(id);660
if (!logout)661
{ return { ended: false }; }662
let cowardice = null;663
// Apply while still marked combat-logout so system letters stay held offline.664
if (applyCowardice && logout.pendingCowardice)665
{ cowardice = applyCombatLogoutCowardice(this, id, { now: this.now }); }666
this.#restoreCombatLogoutAutoCast(id, logout);667
this.combatLogouts.delete(id);668
return { ended: true, cowardice };585
}669
}586
670
587
reattachCharacterSession (characterId, sessionId)671
reattachCharacterSession (characterId, sessionId)@@ -600,9 +684,220 @@ export class Simulation600
if (!result?.ok)684
if (!result?.ok)601
{ return null; }685
{ return null; }602
this.market?.reattachSession?.(characterId, sessionId);686
this.market?.reattachSession?.(characterId, sessionId);687
if (this.combatLogouts.has(characterId | 0))688
{ this.endCombatLogout(characterId, { applyCowardice: true }); }603
return entityId;689
return entityId;604
}690
}605
691
692
#ensureCombatTrack (characterId)693
{694
const id = characterId | 0;695
let track = this.combatTracking.get(id);696
if (!track)697
{698
track = {699
lastCombatEndedAt: null,700
lastOutboundAttackAt: null,701
lastCombatActivityAt: null,702
pvpInvolved: false,703
wasInCombat: false704
};705
this.combatTracking.set(id, track);706
}707
return track;708
}709
710
#notePlayerAttack (characterId, targetEntityId)711
{712
const id = characterId | 0;713
if (!id)714
{ return; }715
const track = this.#ensureCombatTrack(id);716
const now = this.now;717
track.lastOutboundAttackAt = now;718
track.lastCombatActivityAt = now;719
track.wasInCombat = true;720
const targetRecord = this.directory.get(targetEntityId);721
if (targetRecord?.characterId)722
{723
track.pvpInvolved = true;724
const logout = this.combatLogouts.get(id);725
if (logout)726
{ logout.pendingCowardice = true; }727
const other = this.#ensureCombatTrack(targetRecord.characterId);728
other.pvpInvolved = true;729
other.lastCombatActivityAt = now;730
other.wasInCombat = true;731
const otherLogout = this.combatLogouts.get(targetRecord.characterId | 0);732
if (otherLogout)733
{ otherLogout.pendingCowardice = true; }734
}735
}736
737
#noteCombatEvent (event)738
{739
const attackerId = event.attackerId;740
const targetId = event.targetId;741
const attackerRecord = attackerId != null ? this.directory.get(attackerId) : null;742
const targetRecord = targetId != null ? this.directory.get(targetId) : null;743
const pvp = !!(attackerRecord?.characterId && targetRecord?.characterId);744
const now = this.now;745
if (attackerRecord?.characterId)746
{747
const track = this.#ensureCombatTrack(attackerRecord.characterId);748
track.lastOutboundAttackAt = now;749
track.lastCombatActivityAt = now;750
track.wasInCombat = true;751
if (pvp)752
{753
track.pvpInvolved = true;754
const logout = this.combatLogouts.get(attackerRecord.characterId | 0);755
if (logout)756
{ logout.pendingCowardice = true; }757
}758
}759
if (targetRecord?.characterId && event.type !== "combat-swing")760
{761
const track = this.#ensureCombatTrack(targetRecord.characterId);762
track.lastCombatActivityAt = now;763
track.wasInCombat = true;764
if (pvp)765
{766
track.pvpInvolved = true;767
const logout = this.combatLogouts.get(targetRecord.characterId | 0);768
if (logout)769
{ logout.pendingCowardice = true; }770
}771
}772
}773
774
#characterInCombat (entityId)775
{776
const record = this.directory.get(entityId);777
if (!record)778
{ return false; }779
const state = this.workers[record.workerId].call({780
type: WorkerMessage.inspectCombatState,781
entityId782
});783
return !!state?.inCombat;784
}785
786
#shouldStayOnLeave (characterId)787
{788
const id = characterId | 0;789
const entityId = this.characterEntities.get(id);790
if (!entityId)791
{ return false; }792
const inCombat = this.#characterInCombat(entityId);793
if (inCombat)794
{ return true; }795
const track = this.combatTracking.get(id);796
if (!track)797
{ return false; }798
const now = this.now;799
const endedRecently = track.lastCombatEndedAt != null800
&& (now - track.lastCombatEndedAt) <= COMBAT_LOGOUT_MS;801
const attackedRecently = track.lastOutboundAttackAt != null802
&& (now - track.lastOutboundAttackAt) <= COMBAT_LOGOUT_MS;803
return endedRecently && attackedRecently;804
}805
806
#setCharacterAutoCast (characterId, autoCast)807
{808
const entityId = this.characterEntities.get(characterId | 0);809
const record = entityId ? this.directory.get(entityId) : null;810
if (!record)811
{ return null; }812
return this.workers[record.workerId].call({813
type: WorkerMessage.setSpellAutoCast,814
entityId,815
autoCast: !!autoCast816
});817
}818
819
#restoreCombatLogoutAutoCast (characterId, logout)820
{821
if (!logout)822
{ return; }823
this.#setCharacterAutoCast(characterId, !!logout.savedAutoCast);824
const stored = this.stateDb.getSpells(characterId);825
if (stored)826
{827
this.stateDb.saveSpells(characterId, {828
...stored,829
autoCast: !!logout.savedAutoCast830
});831
}832
}833
834
#stepCombatLogout ()835
{836
const events = [];837
const now = this.now;838
for (const [characterId, entityId] of this.characterEntities)839
{840
const inCombat = this.#characterInCombat(entityId);841
const track = this.#ensureCombatTrack(characterId);842
if (track.wasInCombat && !inCombat)843
{ track.lastCombatEndedAt = now; }844
track.wasInCombat = inCombat;845
}846
for (const [characterId, logout] of [...this.combatLogouts.entries()])847
{848
const track = this.combatTracking.get(characterId);849
const lastActivity = track?.lastCombatActivityAt ?? logout.startedAt;850
if ((now - lastActivity) < COMBAT_LOGOUT_MS)851
{ continue; }852
if (logout.pendingCowardice)853
{ applyCombatLogoutCowardice(this, characterId, { now }); }854
this.#restoreCombatLogoutAutoCast(characterId, logout);855
this.combatLogouts.delete(characterId);856
this.despawnCharacter(characterId);857
}858
return events;859
}860
861
despawnCharacter (characterId)862
{863
this.market?.leaveExchangeStations?.(characterId);864
const entityId = this.characterEntities.get(characterId);865
if (!entityId)866
{867
this.combatLogouts.delete(characterId | 0);868
return;869
}870
const record = this.directory.get(entityId);871
if (!record)872
{873
this.characterEntities.delete(characterId);874
this.combatLogouts.delete(characterId | 0);875
return;876
}877
this.#saveBag(entityId, record.workerId);878
const dropped = this.workers[record.workerId].call({879
type: WorkerMessage.despawnCharacter,880
characterId881
});882
if (dropped)883
{884
this.stateDb.saveCharacterPosition(885
characterId,886
dropped.tileX,887
dropped.tileY,888
dropped.gait ?? GAIT.walk,889
dropped.dimensionId ?? OVERWORLD_ID890
);891
if (dropped.health != null)892
{ this.stateDb.saveCharacterHealth(characterId, dropped.health); }893
this.#queueReplication(replicationDespawn(dropped));894
}895
this.#forget(entityId);896
this.combatLogouts.delete(characterId | 0);897
this.#recalculateActivation(this.now);898
this.#syncGhosts();899
}900
606
spawnEntity (components, options = {})901
spawnEntity (components, options = {})607
{902
{608
const entityId = options.entityId ?? this.nextEntityId++;903
const entityId = options.entityId ?? this.nextEntityId++;@@ -892,41 +1187,6 @@ export class Simulation892
});1187
});893
}1188
}894
1189
895
despawnCharacter (characterId)896
{897
this.market?.leaveExchangeStations?.(characterId);898
const entityId = this.characterEntities.get(characterId);899
if (!entityId)900
{ return; }901
const record = this.directory.get(entityId);902
if (!record)903
{904
this.characterEntities.delete(characterId);905
return;906
}907
this.#saveBag(entityId, record.workerId);908
const dropped = this.workers[record.workerId].call({909
type: WorkerMessage.despawnCharacter,910
characterId911
});912
if (dropped)913
{914
this.stateDb.saveCharacterPosition(915
characterId,916
dropped.tileX,917
dropped.tileY,918
dropped.gait ?? GAIT.walk,919
dropped.dimensionId ?? OVERWORLD_ID920
);921
if (dropped.health != null)922
{ this.stateDb.saveCharacterHealth(characterId, dropped.health); }923
this.#queueReplication(replicationDespawn(dropped));924
}925
this.#forget(entityId);926
this.#recalculateActivation(this.now);927
this.#syncGhosts();928
}929
930
entityForCharacter (characterId)1190
entityForCharacter (characterId)931
{1191
{932
return this.characterEntities.get(characterId) ?? null;1192
return this.characterEntities.get(characterId) ?? null;@@ -1317,14 +1577,32 @@ export class Simulation1317
events.push(...this.#handleOpenDialogue(event));1577
events.push(...this.#handleOpenDialogue(event));1318
continue;1578
continue;1319
}1579
}1580
if (1581
event.type === "combat-hit"1582
|| event.type === "combat-miss"1583
|| event.type === "combat-block"1584
|| event.type === "combat-swing"1585
)1586
{ this.#noteCombatEvent(event); }1587
if (event.type === "player-died")1588
{1589
events.push(...this.#applyPlayerDeath(event));1590
continue;1591
}1320
events.push(event);1592
events.push(event);1321
}1593
}1322
if (item.command.type === "attack" && item.command.targetEntityId != null)1594
if (item.command.type === "attack" && item.command.targetEntityId != null)1323
{1595
{1596
this.#notePlayerAttack(item.command.characterId, item.command.targetEntityId);1324
events.push(...this.#mapQuestPrivateEvents(1597
events.push(...this.#mapQuestPrivateEvents(1325
this.quests?.interruptDialogueForEntity(item.command.targetEntityId) ?? []1598
this.quests?.interruptDialogueForEntity(item.command.targetEntityId) ?? []1326
));1599
));1327
}1600
}1601
if (1602
(item.command.type === "cast-spell-entity")1603
&& item.command.targetEntityId != null1604
)1605
{ this.#notePlayerAttack(item.command.characterId, item.command.targetEntityId); }1328
if (result?.private)1606
if (result?.private)1329
{1607
{1330
events.push({1608
events.push({@@ -1393,6 +1671,13 @@ export class Simulation1393
events.push(...this.#applyPlayerDeath(event));1671
events.push(...this.#applyPlayerDeath(event));1394
continue;1672
continue;1395
}1673
}1674
if (1675
event.type === "combat-hit"1676
|| event.type === "combat-miss"1677
|| event.type === "combat-block"1678
|| event.type === "combat-swing"1679
)1680
{ this.#noteCombatEvent(event); }1396
if (event.type === "mob-killed")1681
if (event.type === "mob-killed")1397
{1682
{1398
events.push(...this.#applyMobKilled(event));1683
events.push(...this.#applyMobKilled(event));@@ -1459,6 +1744,13 @@ export class Simulation1459
events.push(...this.#applyPlayerDeath(event));1744
events.push(...this.#applyPlayerDeath(event));1460
continue;1745
continue;1461
}1746
}1747
if (1748
event.type === "combat-hit"1749
|| event.type === "combat-miss"1750
|| event.type === "combat-block"1751
|| event.type === "combat-swing"1752
)1753
{ this.#noteCombatEvent(event); }1462
if (event.type === "mob-killed")1754
if (event.type === "mob-killed")1463
{1755
{1464
events.push(...this.#applyMobKilled(event));1756
events.push(...this.#applyMobKilled(event));@@ -1884,6 +2176,40 @@ export class Simulation1884
});2176
});1885
}2177
}1886
}2178
}2179
const coinsDropped = coinsDroppedFromDeathEvents(events);2180
if (this.combatLogouts.has(event.characterId | 0))2181
{ events.push(...this.#finishCombatLogoutDeath(event, coinsDropped)); }2182
return events;2183
}2184
2185
#finishCombatLogoutDeath (event, coinsDropped)2186
{2187
const characterId = event.characterId | 0;2188
const logout = this.combatLogouts.get(characterId);2189
const events = [];2190
if (logout?.pendingCowardice)2191
{2192
applyCombatLogoutCowardice(this, characterId, {2193
coinsDropped,2194
now: this.now2195
});2196
}2197
dispatchChurchOfflineResurrectionLetter(2198
this,2199
characterId,2200
event.tileX | 0,2201
event.tileY | 02202
);2203
try2204
{ events.push(...this.#respawnCharacter(event.sessionId ?? null, characterId)); }2205
catch2206
{2207
// Respawn can fail without an altar tile; still despawn the corpse session.2208
}2209
this.#restoreCombatLogoutAutoCast(characterId, logout);2210
this.combatLogouts.delete(characterId);2211
this.combatTracking.delete(characterId);2212
this.despawnCharacter(characterId);1887
return events;2213
return events;1888
}2214
}1889
2215
@@ -180,6 +180,10 @@ export class WorkerWorld
180
180
return this.#applySkullValue(message.entityId, message.skullValue);
181
181
case WorkerMessage.engageTarget:
182
182
return this.#engageTargetMessage(message);
183
case WorkerMessage.setSpellAutoCast:
184
return this.#setSpellAutoCast(message);
185
case WorkerMessage.inspectCombatState:
186
return this.#inspectCombatState(message.entityId);
183
187
case WorkerMessage.listTownGuardsNear:
184
188
return this.#listTownGuardsNear(message);
185
189
case WorkerMessage.updateFlight:
@@ -812,6 +816,48 @@ export class WorkerWorld
812
816
};
813
817
}
814
818
819
#setSpellAutoCast (message)
820
{
821
const entityId = message.entityId != null
822
? message.entityId
823
: this.characterEntities.get(message.characterId | 0);
824
const handle = entityId != null ? this.ecs.handleOf(entityId) : null;
825
if (handle == null)
826
{ return { ok: false }; }
827
const spells = this.ecs.get(handle, Component.spells);
828
if (!spells)
829
{ return { ok: false }; }
830
const previous = !!spells.autoCast;
831
spells.autoCast = !!message.autoCast;
832
return { ok: true, previousAutoCast: previous, autoCast: !!spells.autoCast };
833
}
834
835
#inspectCombatState (entityId)
836
{
837
const handle = this.ecs.handleOf(entityId);
838
if (handle == null)
839
{ return null; }
840
const combat = this.ecs.get(handle, Component.combat);
841
const casting = this.ecs.get(handle, Component.spellcasting);
842
const character = this.ecs.get(handle, Component.character);
843
const dead = this.ecs.has(handle, Component.dead);
844
const targetId = combat?.targetEntityId ?? null;
845
const repeatTargetId = casting?.repeatTargetEntityId ?? null;
846
const pendingTargetId = casting?.pendingCast?.targetEntityId ?? null;
847
const inCombat = !dead && !!(targetId != null
848
|| repeatTargetId != null
849
|| (casting?.pendingCast && (pendingTargetId != null
850
|| casting.pendingCast.tileX != null)));
851
return {
852
characterId: character?.characterId ?? null,
853
inCombat,
854
dead,
855
targetEntityId: targetId,
856
repeatTargetEntityId: repeatTargetId,
857
pendingTargetEntityId: pendingTargetId
858
};
859
}
860
815
861
#inspectStamina (entityId)
816
862
{
817
863
const handle = this.ecs.handleOf(entityId);
@@ -180,6 +180,10 @@ export class WorkerWorld180
return this.#applySkullValue(message.entityId, message.skullValue);180
return this.#applySkullValue(message.entityId, message.skullValue);181
case WorkerMessage.engageTarget:181
case WorkerMessage.engageTarget:182
return this.#engageTargetMessage(message);182
return this.#engageTargetMessage(message);183
case WorkerMessage.setSpellAutoCast:184
return this.#setSpellAutoCast(message);185
case WorkerMessage.inspectCombatState:186
return this.#inspectCombatState(message.entityId);183
case WorkerMessage.listTownGuardsNear:187
case WorkerMessage.listTownGuardsNear:184
return this.#listTownGuardsNear(message);188
return this.#listTownGuardsNear(message);185
case WorkerMessage.updateFlight:189
case WorkerMessage.updateFlight:@@ -812,6 +816,48 @@ export class WorkerWorld812
};816
};813
}817
}814
818
819
#setSpellAutoCast (message)820
{821
const entityId = message.entityId != null822
? message.entityId823
: this.characterEntities.get(message.characterId | 0);824
const handle = entityId != null ? this.ecs.handleOf(entityId) : null;825
if (handle == null)826
{ return { ok: false }; }827
const spells = this.ecs.get(handle, Component.spells);828
if (!spells)829
{ return { ok: false }; }830
const previous = !!spells.autoCast;831
spells.autoCast = !!message.autoCast;832
return { ok: true, previousAutoCast: previous, autoCast: !!spells.autoCast };833
}834
835
#inspectCombatState (entityId)836
{837
const handle = this.ecs.handleOf(entityId);838
if (handle == null)839
{ return null; }840
const combat = this.ecs.get(handle, Component.combat);841
const casting = this.ecs.get(handle, Component.spellcasting);842
const character = this.ecs.get(handle, Component.character);843
const dead = this.ecs.has(handle, Component.dead);844
const targetId = combat?.targetEntityId ?? null;845
const repeatTargetId = casting?.repeatTargetEntityId ?? null;846
const pendingTargetId = casting?.pendingCast?.targetEntityId ?? null;847
const inCombat = !dead && !!(targetId != null848
|| repeatTargetId != null849
|| (casting?.pendingCast && (pendingTargetId != null850
|| casting.pendingCast.tileX != null)));851
return {852
characterId: character?.characterId ?? null,853
inCombat,854
dead,855
targetEntityId: targetId,856
repeatTargetEntityId: repeatTargetId,857
pendingTargetEntityId: pendingTargetId858
};859
}860
815
#inspectStamina (entityId)861
#inspectStamina (entityId)816
{862
{817
const handle = this.ecs.handleOf(entityId);863
const handle = this.ecs.handleOf(entityId);@@ -0,0 +1,361 @@
1
import test from "node:test";
2
import assert from "node:assert/strict";
3
import { BlockType } from "../../shared/definitions/tiles.js";
4
import { ItemId } from "../../shared/definitions/items.js";
5
import { Component } from "../src/ecs/components.js";
6
import { MobId } from "../../shared/definitions/mobs.js";
7
import { mobComponents } from "../src/simulation/spawners.js";
8
import { createEmptyChunkData, encodeChunkBlob, decodeChunkBlob } from "../src/world/chunkData.js";
9
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
10
import { emptyEquipment, emptySlots, addCoinsToSlots } from "../../shared/items/inventory.js";
11
import { COMBAT_LOGOUT_MS, combatLogoutCoinThreshold, cowardiceHourKey } from "../../shared/combat/combatLogout.js";
12
import { combatLevelFromSkills } from "../../shared/combat/combatLevel.js";
13
import { defaultPlayerSkills } from "../../shared/skills/state.js";
14
import
15
{
16
CHURCH_LETTER_AUTHOR,
17
QUESTWARD_GIFT_AUTHOR,
18
QUESTWARD_GIFT_ORG,
19
formatCombatLogoutCowardiceBody,
20
formatChurchOfflineResurrectionBody
21
} from "../../shared/courier/systemLetters.js";
22
import { applyDamageAndKill } from "../src/combat/service.js";
23
import { WorkerMessage } from "../src/simulation/protocol.js";
24
25
function componentsOf (simulation, entityId)
26
{
27
const record = simulation.entityRecord(entityId);
28
const worker = simulation.workers[record.workerId];
29
const handle = worker.world.ecs.handleOf(entityId);
30
return worker.world.ecs.componentsOf(handle);
31
}
32
33
function placeBlock (worldDb, tileX, tileY, typeId)
34
{
35
const chunkX = Math.floor(tileX / 16);
36
const chunkY = Math.floor(tileY / 16);
37
const revisionId = worldDb.getActiveRevisionId();
38
const row = worldDb.getChunkVersion(chunkX, chunkY, revisionId);
39
const data = row
40
? decodeChunkBlob(row.data_blob, undefined, chunkX, chunkY)
41
: createEmptyChunkData();
42
data.open = true;
43
const localX = tileX - chunkX * 16;
44
const localY = tileY - chunkY * 16;
45
data.blocks[localY * 16 + localX] = { typeId, state: 0 };
46
worldDb.saveChunkVersion(chunkX, chunkY, revisionId, true, encodeChunkBlob(data));
47
}
48
49
function heldLetters (stateDb, characterId)
50
{
51
return stateDb.listHeldCourierDeliveries(characterId)
52
.map((hold) => hold.cargo?.stack)
53
.filter((stack) => stack?.itemId === ItemId.letter);
54
}
55
56
function engageAndLogout (harness, character, playerId, targetEntityId)
57
{
58
harness.simulation.enqueue(1, {
59
type: "attack",
60
characterId: character.character_id,
61
targetEntityId
62
});
63
harness.simulation.step();
64
assert.equal(harness.simulation.beginCombatLogout(character.character_id), true);
65
assert.equal(harness.simulation.isCombatLogout(character.character_id), true);
66
return playerId;
67
}
68
69
function clearCombatAndExpireQuiet (harness, characterId, entityId)
70
{
71
const record = harness.simulation.entityRecord(entityId);
72
if (record)
73
{
74
harness.simulation.workers[record.workerId].call({
75
type: WorkerMessage.clearCombat,
76
entityId,
77
targetEntityId: entityId
78
});
79
}
80
const track = harness.simulation.combatTracking.get(characterId);
81
if (track)
82
{
83
track.lastCombatActivityAt = harness.now() - COMBAT_LOGOUT_MS - 1;
84
track.wasInCombat = false;
85
}
86
const logout = harness.simulation.combatLogouts.get(characterId);
87
if (logout)
88
{ logout.startedAt = harness.now() - COMBAT_LOGOUT_MS - 1; }
89
for (let i = 0; i < 60; i++)
90
{ harness.simulation.step(); }
91
}
92
93
test("combat logout keeps the character until quiet timeout", () =>
94
{
95
const harness = makeSimulation({ workerCount: 1 });
96
try
97
{
98
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
99
const playerId = harness.simulation.spawnCharacter(1, character);
100
const deerId = harness.simulation.spawnEntity(mobComponents({
101
tileX: 9,
102
tileY: 8,
103
mobTypeId: MobId.deer,
104
spawnerId: null
105
}));
106
engageAndLogout(harness, character, playerId, deerId);
107
108
const worker = harness.simulation.workers[0];
109
const spells = worker.world.ecs.get(worker.world.ecs.handleOf(playerId), Component.spells);
110
assert.equal(spells.autoCast, true);
111
assert.ok(harness.simulation.isCharacterInWorld(character.character_id));
112
assert.equal(harness.simulation.isCharacterOnline(character.character_id), false);
113
114
clearCombatAndExpireQuiet(harness, character.character_id, playerId);
115
assert.equal(harness.simulation.isCharacterInWorld(character.character_id), false);
116
assert.equal(harness.simulation.isCombatLogout(character.character_id), false);
117
}
118
finally
119
{ harness.close(); }
120
});
121
122
test("combat activity resets the combat-logout quiet timer", () =>
123
{
124
const harness = makeSimulation({ workerCount: 1 });
125
try
126
{
127
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
128
const playerId = harness.simulation.spawnCharacter(1, character);
129
const deerId = harness.simulation.spawnEntity(mobComponents({
130
tileX: 9,
131
tileY: 8,
132
mobTypeId: MobId.deer,
133
spawnerId: null
134
}));
135
engageAndLogout(harness, character, playerId, deerId);
136
137
harness.advance(COMBAT_LOGOUT_MS - 5_000);
138
for (let i = 0; i < 3; i++)
139
{ harness.simulation.step(); }
140
assert.equal(harness.simulation.isCharacterInWorld(character.character_id), true);
141
142
const track = harness.simulation.combatTracking.get(character.character_id);
143
track.lastCombatActivityAt = harness.now();
144
const logout = harness.simulation.combatLogouts.get(character.character_id);
145
logout.startedAt = harness.now();
146
147
harness.advance(COMBAT_LOGOUT_MS - 10_000);
148
for (let i = 0; i < 3; i++)
149
{ harness.simulation.step(); }
150
assert.equal(harness.simulation.isCharacterInWorld(character.character_id), true);
151
152
clearCombatAndExpireQuiet(harness, character.character_id, playerId);
153
assert.equal(harness.simulation.isCharacterInWorld(character.character_id), false);
154
}
155
finally
156
{ harness.close(); }
157
});
158
159
test("offline combat-logout death resurrects at altar with church letter", () =>
160
{
161
const harness = makeSimulation({ workerCount: 1 });
162
try
163
{
164
placeBlock(harness.worldDb, 20, 8, BlockType.churchAltar);
165
placeBlock(harness.worldDb, 7, 8, BlockType.bank);
166
harness.simulation.reloadWorld();
167
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
168
const playerId = harness.simulation.spawnCharacter(1, character);
169
const deerId = harness.simulation.spawnEntity(mobComponents({
170
tileX: 9,
171
tileY: 8,
172
mobTypeId: MobId.deer,
173
spawnerId: null
174
}));
175
engageAndLogout(harness, character, playerId, deerId);
176
177
const worker = harness.simulation.workers[0];
178
componentsOf(harness.simulation, playerId).health.current = 1;
179
const events = applyDamageAndKill(worker.world, deerId, playerId, 999, harness.now());
180
const died = events.find((event) => event.type === "player-died");
181
assert.ok(died);
182
harness.simulation.applyPlayerDiedEvent(died);
183
184
assert.equal(harness.stateDb.getCharacter(character.character_id).is_dead, 0);
185
assert.equal(harness.simulation.isCharacterInWorld(character.character_id), false);
186
const letters = heldLetters(harness.stateDb, character.character_id);
187
assert.ok(letters.some((stack) =>
188
stack.instance?.authorDisplayName === CHURCH_LETTER_AUTHOR
189
&& stack.instance?.body === formatChurchOfflineResurrectionBody()
190
));
191
const row = harness.stateDb.getCharacter(character.character_id);
192
assert.equal(
193
Math.max(Math.abs(row.tile_x - 20), Math.abs(row.tile_y - 8)),
194
1
195
);
196
}
197
finally
198
{ harness.close(); }
199
});
200
201
test("PvP combat-logout quiet end applies skull after hourly forgiveness", () =>
202
{
203
const harness = makeSimulation({ workerCount: 1 });
204
try
205
{
206
placeBlock(harness.worldDb, 7, 8, BlockType.bank);
207
harness.simulation.reloadWorld();
208
const victim = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Vic" });
209
const attacker = makeCharacter(harness.stateDb, { tileX: 9, tileY: 8, firstName: "Atk" });
210
const victimId = harness.simulation.spawnCharacter(1, victim);
211
const attackerId = harness.simulation.spawnCharacter(2, attacker);
212
engageAndLogout(harness, victim, victimId, attackerId);
213
assert.equal(
214
harness.simulation.combatLogouts.get(victim.character_id).pendingCowardice,
215
true
216
);
217
218
const skills = harness.stateDb.getSkills(victim.character_id) ?? defaultPlayerSkills();
219
const threshold = combatLogoutCoinThreshold(combatLevelFromSkills(skills));
220
const hour = cowardiceHourKey(harness.now());
221
222
clearCombatAndExpireQuiet(harness, victim.character_id, victimId);
223
assert.equal(harness.simulation.isCharacterInWorld(victim.character_id), false);
224
assert.equal(harness.stateDb.getCowardiceForgivenHour(victim.character_id), hour);
225
assert.equal(harness.stateDb.getKillCounterState(victim.character_id).killCounter, 0);
226
assert.equal(heldLetters(harness.stateDb, victim.character_id).length, 0);
227
228
const victimRow = harness.stateDb.getCharacter(victim.character_id);
229
const victimId2 = harness.simulation.spawnCharacter(1, victimRow);
230
const standIn = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8, firstName: "Stand" });
231
const standId = harness.simulation.spawnCharacter(3, standIn);
232
engageAndLogout(harness, victim, victimId2, standId);
233
clearCombatAndExpireQuiet(harness, victim.character_id, victimId2);
234
235
assert.equal(
236
harness.stateDb.getKillCounterState(victim.character_id).killCounter,
237
threshold
238
);
239
const letters = heldLetters(harness.stateDb, victim.character_id);
240
assert.ok(letters.some((stack) =>
241
stack.instance?.authorDisplayName === QUESTWARD_GIFT_AUTHOR
242
&& stack.instance?.authorOrganization === QUESTWARD_GIFT_ORG
243
&& stack.instance?.body === formatCombatLogoutCowardiceBody()
244
));
245
void attackerId;
246
}
247
finally
248
{ harness.close(); }
249
});
250
251
test("reattach after PvP combat-logout applies cowardice and restores autoCast", () =>
252
{
253
const harness = makeSimulation({ workerCount: 1 });
254
try
255
{
256
placeBlock(harness.worldDb, 7, 8, BlockType.bank);
257
harness.simulation.reloadWorld();
258
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
259
const playerId = harness.simulation.spawnCharacter(1, character);
260
const other = makeCharacter(harness.stateDb, { tileX: 9, tileY: 8, firstName: "Other" });
261
const otherId = harness.simulation.spawnCharacter(2, other);
262
263
const worker = harness.simulation.workers[0];
264
const spells = worker.world.ecs.get(worker.world.ecs.handleOf(playerId), Component.spells);
265
spells.autoCast = false;
266
harness.stateDb.saveSpells(character.character_id, {
267
known: spells.known ?? [],
268
favorites: spells.favorites ?? [],
269
autoCast: false,
270
castChances: spells.castChances ?? {}
271
});
272
273
engageAndLogout(harness, character, playerId, otherId);
274
assert.equal(spells.autoCast, true);
275
harness.stateDb.setCowardiceForgivenHour(character.character_id, cowardiceHourKey(harness.now()));
276
277
const reattached = harness.simulation.reattachCharacterSession(character.character_id, 99);
278
assert.equal(reattached, playerId);
279
assert.equal(harness.simulation.isCombatLogout(character.character_id), false);
280
assert.equal(spells.autoCast, false);
281
282
const skills = harness.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills();
283
const threshold = combatLogoutCoinThreshold(combatLevelFromSkills(skills));
284
assert.equal(
285
harness.stateDb.getKillCounterState(character.character_id).killCounter,
286
threshold
287
);
288
assert.ok(heldLetters(harness.stateDb, character.character_id).some((stack) =>
289
stack.instance?.authorDisplayName === QUESTWARD_GIFT_AUTHOR
290
));
291
}
292
finally
293
{ harness.close(); }
294
});
295
296
test("offline PvP death with enough coins skips cowardice skull", () =>
297
{
298
const harness = makeSimulation({ workerCount: 1 });
299
try
300
{
301
placeBlock(harness.worldDb, 20, 8, BlockType.churchAltar);
302
placeBlock(harness.worldDb, 7, 8, BlockType.bank);
303
harness.simulation.reloadWorld();
304
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
305
const skills = harness.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills();
306
const threshold = combatLogoutCoinThreshold(combatLevelFromSkills(skills));
307
const funded = addCoinsToSlots(emptySlots(), threshold + 10);
308
assert.equal(funded.ok, true);
309
harness.stateDb.saveBag(character.character_id, {
310
inventory: funded.slots,
311
equipment: emptyEquipment(),
312
vault: [],
313
vaultReserved: []
314
});
315
const playerId = harness.simulation.spawnCharacter(1, character);
316
const other = makeCharacter(harness.stateDb, { tileX: 9, tileY: 8, firstName: "Foe" });
317
const otherId = harness.simulation.spawnCharacter(2, other);
318
engageAndLogout(harness, character, playerId, otherId);
319
harness.stateDb.setCowardiceForgivenHour(character.character_id, cowardiceHourKey(harness.now()));
320
321
const worker = harness.simulation.workers[0];
322
componentsOf(harness.simulation, playerId).health.current = 1;
323
const events = applyDamageAndKill(worker.world, otherId, playerId, 999, harness.now());
324
const died = events.find((event) => event.type === "player-died");
325
harness.simulation.applyPlayerDiedEvent(died);
326
327
assert.equal(harness.stateDb.getKillCounterState(character.character_id).killCounter, 0);
328
assert.ok(heldLetters(harness.stateDb, character.character_id).some((stack) =>
329
stack.instance?.authorDisplayName === CHURCH_LETTER_AUTHOR
330
));
331
assert.equal(
332
heldLetters(harness.stateDb, character.character_id).some((stack) =>
333
stack.instance?.authorDisplayName === QUESTWARD_GIFT_AUTHOR
334
),
335
false
336
);
337
}
338
finally
339
{ harness.close(); }
340
});
341
342
test("leave without recent combat despawns immediately", () =>
343
{
344
const harness = makeSimulation({ workerCount: 1 });
345
try
346
{
347
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
348
harness.simulation.spawnCharacter(1, character);
349
assert.equal(harness.simulation.beginCombatLogout(character.character_id), false);
350
harness.simulation.despawnCharacter(character.character_id);
351
assert.equal(harness.simulation.isCharacterOnline(character.character_id), false);
352
}
353
finally
354
{ harness.close(); }
355
});
356
357
test("combat logout letter copy is fixed", () =>
358
{
359
assert.match(formatChurchOfflineResurrectionBody(), /priesthood found your lifeless body/);
360
assert.match(formatCombatLogoutCowardiceBody(), /cowardice in honourable combat/);
361
});
@@ -0,0 +1,361 @@1
import test from "node:test";2
import assert from "node:assert/strict";3
import { BlockType } from "../../shared/definitions/tiles.js";4
import { ItemId } from "../../shared/definitions/items.js";5
import { Component } from "../src/ecs/components.js";6
import { MobId } from "../../shared/definitions/mobs.js";7
import { mobComponents } from "../src/simulation/spawners.js";8
import { createEmptyChunkData, encodeChunkBlob, decodeChunkBlob } from "../src/world/chunkData.js";9
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";10
import { emptyEquipment, emptySlots, addCoinsToSlots } from "../../shared/items/inventory.js";11
import { COMBAT_LOGOUT_MS, combatLogoutCoinThreshold, cowardiceHourKey } from "../../shared/combat/combatLogout.js";12
import { combatLevelFromSkills } from "../../shared/combat/combatLevel.js";13
import { defaultPlayerSkills } from "../../shared/skills/state.js";14
import15
{16
CHURCH_LETTER_AUTHOR,17
QUESTWARD_GIFT_AUTHOR,18
QUESTWARD_GIFT_ORG,19
formatCombatLogoutCowardiceBody,20
formatChurchOfflineResurrectionBody21
} from "../../shared/courier/systemLetters.js";22
import { applyDamageAndKill } from "../src/combat/service.js";23
import { WorkerMessage } from "../src/simulation/protocol.js";24
25
function componentsOf (simulation, entityId)26
{27
const record = simulation.entityRecord(entityId);28
const worker = simulation.workers[record.workerId];29
const handle = worker.world.ecs.handleOf(entityId);30
return worker.world.ecs.componentsOf(handle);31
}32
33
function placeBlock (worldDb, tileX, tileY, typeId)34
{35
const chunkX = Math.floor(tileX / 16);36
const chunkY = Math.floor(tileY / 16);37
const revisionId = worldDb.getActiveRevisionId();38
const row = worldDb.getChunkVersion(chunkX, chunkY, revisionId);39
const data = row40
? decodeChunkBlob(row.data_blob, undefined, chunkX, chunkY)41
: createEmptyChunkData();42
data.open = true;43
const localX = tileX - chunkX * 16;44
const localY = tileY - chunkY * 16;45
data.blocks[localY * 16 + localX] = { typeId, state: 0 };46
worldDb.saveChunkVersion(chunkX, chunkY, revisionId, true, encodeChunkBlob(data));47
}48
49
function heldLetters (stateDb, characterId)50
{51
return stateDb.listHeldCourierDeliveries(characterId)52
.map((hold) => hold.cargo?.stack)53
.filter((stack) => stack?.itemId === ItemId.letter);54
}55
56
function engageAndLogout (harness, character, playerId, targetEntityId)57
{58
harness.simulation.enqueue(1, {59
type: "attack",60
characterId: character.character_id,61
targetEntityId62
});63
harness.simulation.step();64
assert.equal(harness.simulation.beginCombatLogout(character.character_id), true);65
assert.equal(harness.simulation.isCombatLogout(character.character_id), true);66
return playerId;67
}68
69
function clearCombatAndExpireQuiet (harness, characterId, entityId)70
{71
const record = harness.simulation.entityRecord(entityId);72
if (record)73
{74
harness.simulation.workers[record.workerId].call({75
type: WorkerMessage.clearCombat,76
entityId,77
targetEntityId: entityId78
});79
}80
const track = harness.simulation.combatTracking.get(characterId);81
if (track)82
{83
track.lastCombatActivityAt = harness.now() - COMBAT_LOGOUT_MS - 1;84
track.wasInCombat = false;85
}86
const logout = harness.simulation.combatLogouts.get(characterId);87
if (logout)88
{ logout.startedAt = harness.now() - COMBAT_LOGOUT_MS - 1; }89
for (let i = 0; i < 60; i++)90
{ harness.simulation.step(); }91
}92
93
test("combat logout keeps the character until quiet timeout", () =>94
{95
const harness = makeSimulation({ workerCount: 1 });96
try97
{98
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });99
const playerId = harness.simulation.spawnCharacter(1, character);100
const deerId = harness.simulation.spawnEntity(mobComponents({101
tileX: 9,102
tileY: 8,103
mobTypeId: MobId.deer,104
spawnerId: null105
}));106
engageAndLogout(harness, character, playerId, deerId);107
108
const worker = harness.simulation.workers[0];109
const spells = worker.world.ecs.get(worker.world.ecs.handleOf(playerId), Component.spells);110
assert.equal(spells.autoCast, true);111
assert.ok(harness.simulation.isCharacterInWorld(character.character_id));112
assert.equal(harness.simulation.isCharacterOnline(character.character_id), false);113
114
clearCombatAndExpireQuiet(harness, character.character_id, playerId);115
assert.equal(harness.simulation.isCharacterInWorld(character.character_id), false);116
assert.equal(harness.simulation.isCombatLogout(character.character_id), false);117
}118
finally119
{ harness.close(); }120
});121
122
test("combat activity resets the combat-logout quiet timer", () =>123
{124
const harness = makeSimulation({ workerCount: 1 });125
try126
{127
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });128
const playerId = harness.simulation.spawnCharacter(1, character);129
const deerId = harness.simulation.spawnEntity(mobComponents({130
tileX: 9,131
tileY: 8,132
mobTypeId: MobId.deer,133
spawnerId: null134
}));135
engageAndLogout(harness, character, playerId, deerId);136
137
harness.advance(COMBAT_LOGOUT_MS - 5_000);138
for (let i = 0; i < 3; i++)139
{ harness.simulation.step(); }140
assert.equal(harness.simulation.isCharacterInWorld(character.character_id), true);141
142
const track = harness.simulation.combatTracking.get(character.character_id);143
track.lastCombatActivityAt = harness.now();144
const logout = harness.simulation.combatLogouts.get(character.character_id);145
logout.startedAt = harness.now();146
147
harness.advance(COMBAT_LOGOUT_MS - 10_000);148
for (let i = 0; i < 3; i++)149
{ harness.simulation.step(); }150
assert.equal(harness.simulation.isCharacterInWorld(character.character_id), true);151
152
clearCombatAndExpireQuiet(harness, character.character_id, playerId);153
assert.equal(harness.simulation.isCharacterInWorld(character.character_id), false);154
}155
finally156
{ harness.close(); }157
});158
159
test("offline combat-logout death resurrects at altar with church letter", () =>160
{161
const harness = makeSimulation({ workerCount: 1 });162
try163
{164
placeBlock(harness.worldDb, 20, 8, BlockType.churchAltar);165
placeBlock(harness.worldDb, 7, 8, BlockType.bank);166
harness.simulation.reloadWorld();167
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });168
const playerId = harness.simulation.spawnCharacter(1, character);169
const deerId = harness.simulation.spawnEntity(mobComponents({170
tileX: 9,171
tileY: 8,172
mobTypeId: MobId.deer,173
spawnerId: null174
}));175
engageAndLogout(harness, character, playerId, deerId);176
177
const worker = harness.simulation.workers[0];178
componentsOf(harness.simulation, playerId).health.current = 1;179
const events = applyDamageAndKill(worker.world, deerId, playerId, 999, harness.now());180
const died = events.find((event) => event.type === "player-died");181
assert.ok(died);182
harness.simulation.applyPlayerDiedEvent(died);183
184
assert.equal(harness.stateDb.getCharacter(character.character_id).is_dead, 0);185
assert.equal(harness.simulation.isCharacterInWorld(character.character_id), false);186
const letters = heldLetters(harness.stateDb, character.character_id);187
assert.ok(letters.some((stack) =>188
stack.instance?.authorDisplayName === CHURCH_LETTER_AUTHOR189
&& stack.instance?.body === formatChurchOfflineResurrectionBody()190
));191
const row = harness.stateDb.getCharacter(character.character_id);192
assert.equal(193
Math.max(Math.abs(row.tile_x - 20), Math.abs(row.tile_y - 8)),194
1195
);196
}197
finally198
{ harness.close(); }199
});200
201
test("PvP combat-logout quiet end applies skull after hourly forgiveness", () =>202
{203
const harness = makeSimulation({ workerCount: 1 });204
try205
{206
placeBlock(harness.worldDb, 7, 8, BlockType.bank);207
harness.simulation.reloadWorld();208
const victim = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Vic" });209
const attacker = makeCharacter(harness.stateDb, { tileX: 9, tileY: 8, firstName: "Atk" });210
const victimId = harness.simulation.spawnCharacter(1, victim);211
const attackerId = harness.simulation.spawnCharacter(2, attacker);212
engageAndLogout(harness, victim, victimId, attackerId);213
assert.equal(214
harness.simulation.combatLogouts.get(victim.character_id).pendingCowardice,215
true216
);217
218
const skills = harness.stateDb.getSkills(victim.character_id) ?? defaultPlayerSkills();219
const threshold = combatLogoutCoinThreshold(combatLevelFromSkills(skills));220
const hour = cowardiceHourKey(harness.now());221
222
clearCombatAndExpireQuiet(harness, victim.character_id, victimId);223
assert.equal(harness.simulation.isCharacterInWorld(victim.character_id), false);224
assert.equal(harness.stateDb.getCowardiceForgivenHour(victim.character_id), hour);225
assert.equal(harness.stateDb.getKillCounterState(victim.character_id).killCounter, 0);226
assert.equal(heldLetters(harness.stateDb, victim.character_id).length, 0);227
228
const victimRow = harness.stateDb.getCharacter(victim.character_id);229
const victimId2 = harness.simulation.spawnCharacter(1, victimRow);230
const standIn = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8, firstName: "Stand" });231
const standId = harness.simulation.spawnCharacter(3, standIn);232
engageAndLogout(harness, victim, victimId2, standId);233
clearCombatAndExpireQuiet(harness, victim.character_id, victimId2);234
235
assert.equal(236
harness.stateDb.getKillCounterState(victim.character_id).killCounter,237
threshold238
);239
const letters = heldLetters(harness.stateDb, victim.character_id);240
assert.ok(letters.some((stack) =>241
stack.instance?.authorDisplayName === QUESTWARD_GIFT_AUTHOR242
&& stack.instance?.authorOrganization === QUESTWARD_GIFT_ORG243
&& stack.instance?.body === formatCombatLogoutCowardiceBody()244
));245
void attackerId;246
}247
finally248
{ harness.close(); }249
});250
251
test("reattach after PvP combat-logout applies cowardice and restores autoCast", () =>252
{253
const harness = makeSimulation({ workerCount: 1 });254
try255
{256
placeBlock(harness.worldDb, 7, 8, BlockType.bank);257
harness.simulation.reloadWorld();258
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });259
const playerId = harness.simulation.spawnCharacter(1, character);260
const other = makeCharacter(harness.stateDb, { tileX: 9, tileY: 8, firstName: "Other" });261
const otherId = harness.simulation.spawnCharacter(2, other);262
263
const worker = harness.simulation.workers[0];264
const spells = worker.world.ecs.get(worker.world.ecs.handleOf(playerId), Component.spells);265
spells.autoCast = false;266
harness.stateDb.saveSpells(character.character_id, {267
known: spells.known ?? [],268
favorites: spells.favorites ?? [],269
autoCast: false,270
castChances: spells.castChances ?? {}271
});272
273
engageAndLogout(harness, character, playerId, otherId);274
assert.equal(spells.autoCast, true);275
harness.stateDb.setCowardiceForgivenHour(character.character_id, cowardiceHourKey(harness.now()));276
277
const reattached = harness.simulation.reattachCharacterSession(character.character_id, 99);278
assert.equal(reattached, playerId);279
assert.equal(harness.simulation.isCombatLogout(character.character_id), false);280
assert.equal(spells.autoCast, false);281
282
const skills = harness.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills();283
const threshold = combatLogoutCoinThreshold(combatLevelFromSkills(skills));284
assert.equal(285
harness.stateDb.getKillCounterState(character.character_id).killCounter,286
threshold287
);288
assert.ok(heldLetters(harness.stateDb, character.character_id).some((stack) =>289
stack.instance?.authorDisplayName === QUESTWARD_GIFT_AUTHOR290
));291
}292
finally293
{ harness.close(); }294
});295
296
test("offline PvP death with enough coins skips cowardice skull", () =>297
{298
const harness = makeSimulation({ workerCount: 1 });299
try300
{301
placeBlock(harness.worldDb, 20, 8, BlockType.churchAltar);302
placeBlock(harness.worldDb, 7, 8, BlockType.bank);303
harness.simulation.reloadWorld();304
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });305
const skills = harness.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills();306
const threshold = combatLogoutCoinThreshold(combatLevelFromSkills(skills));307
const funded = addCoinsToSlots(emptySlots(), threshold + 10);308
assert.equal(funded.ok, true);309
harness.stateDb.saveBag(character.character_id, {310
inventory: funded.slots,311
equipment: emptyEquipment(),312
vault: [],313
vaultReserved: []314
});315
const playerId = harness.simulation.spawnCharacter(1, character);316
const other = makeCharacter(harness.stateDb, { tileX: 9, tileY: 8, firstName: "Foe" });317
const otherId = harness.simulation.spawnCharacter(2, other);318
engageAndLogout(harness, character, playerId, otherId);319
harness.stateDb.setCowardiceForgivenHour(character.character_id, cowardiceHourKey(harness.now()));320
321
const worker = harness.simulation.workers[0];322
componentsOf(harness.simulation, playerId).health.current = 1;323
const events = applyDamageAndKill(worker.world, otherId, playerId, 999, harness.now());324
const died = events.find((event) => event.type === "player-died");325
harness.simulation.applyPlayerDiedEvent(died);326
327
assert.equal(harness.stateDb.getKillCounterState(character.character_id).killCounter, 0);328
assert.ok(heldLetters(harness.stateDb, character.character_id).some((stack) =>329
stack.instance?.authorDisplayName === CHURCH_LETTER_AUTHOR330
));331
assert.equal(332
heldLetters(harness.stateDb, character.character_id).some((stack) =>333
stack.instance?.authorDisplayName === QUESTWARD_GIFT_AUTHOR334
),335
false336
);337
}338
finally339
{ harness.close(); }340
});341
342
test("leave without recent combat despawns immediately", () =>343
{344
const harness = makeSimulation({ workerCount: 1 });345
try346
{347
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });348
harness.simulation.spawnCharacter(1, character);349
assert.equal(harness.simulation.beginCombatLogout(character.character_id), false);350
harness.simulation.despawnCharacter(character.character_id);351
assert.equal(harness.simulation.isCharacterOnline(character.character_id), false);352
}353
finally354
{ harness.close(); }355
});356
357
test("combat logout letter copy is fixed", () =>358
{359
assert.match(formatChurchOfflineResurrectionBody(), /priesthood found your lifeless body/);360
assert.match(formatCombatLogoutCowardiceBody(), /cowardice in honourable combat/);361
});