BlueGit

timfa questward

Add per-door passage requirements with blocked toast.

Right-click wooden doors in the editor to set ConditionSet gates and a deny message; players who fail stay blocked even when another player holds the door open.

timfa Tim Falken · pushed by timfa

Authored 2026-09-06 · 2 months ago

Hash
a16e7bd7f9afc0fa96951569551daa4a84acf3b1
Parent
71fb4b54
15 files changed +667 −22
client/src/editor/main.js +66 −0
@@ -47,6 +47,7 @@ import
47 47 normalizeDimensionId,
48 48 isOverworld
49 49 } from "/shared/world/dimensions.js";
50 import { normalizeDoorConfig } from "/shared/world/doorRequirements.js";
50 51
51 52 const game = new Game();
52 53 let socket;
@@ -1197,6 +1198,9 @@ async function main ()
1197 1198 },
1198 1199 MessageType,
1199 1200 getDialogues: () => dialoguesModal?.getDialogues?.() ?? [],
1201 getQuests: () => questsModal?.getQuests?.() ?? [],
1202 describeWorldTile,
1203 centerEditorOnTile,
1200 1204 getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
1201 1205 id: dim.dimensionId,
1202 1206 label: dim.displayName || dim.dimensionId,
@@ -1227,6 +1231,31 @@ async function main ()
1227 1231 afterDraftMutation();
1228 1232 return;
1229 1233 }
1234 if (ctx.kind === "door")
1235 {
1236 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1237 const existing = draft.blocks[index];
1238 if (!existing || existing.typeId !== BlockType.door)
1239 { return; }
1240 const prev = existing.config && typeof existing.config === "object" ? { ...existing.config } : {};
1241 const nextConfig = normalizeDoorConfig({
1242 ...prev,
1243 when: config.when,
1244 blockedMessage: config.blockedMessage
1245 });
1246 draft.blocks[index] = {
1247 typeId: BlockType.door,
1248 state: existing.state,
1249 config: nextConfig
1250 };
1251 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1252 ground: draft.grounds[index],
1253 block: draft.blocks[index],
1254 light: draft.light[index]
1255 });
1256 afterDraftMutation();
1257 return;
1258 }
1230 1259 if (ctx.kind === "fishing-spot")
1231 1260 {
1232 1261 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
@@ -1253,6 +1282,30 @@ async function main ()
1253 1282 {
1254 1283 if (!draft)
1255 1284 { return; }
1285 if (ctx.kind === "door")
1286 {
1287 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1288 const existing = draft.blocks[index];
1289 if (!existing || existing.typeId !== BlockType.door)
1290 { return; }
1291 const prev = existing.config && typeof existing.config === "object" ? { ...existing.config } : {};
1292 delete prev.when;
1293 delete prev.requirements;
1294 delete prev.blockedMessage;
1295 delete prev.denyMessage;
1296 draft.blocks[index] = {
1297 typeId: BlockType.door,
1298 state: existing.state,
1299 config: normalizeDoorConfig(prev)
1300 };
1301 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1302 ground: draft.grounds[index],
1303 block: draft.blocks[index],
1304 light: draft.light[index]
1305 });
1306 afterDraftMutation();
1307 return;
1308 }
1256 1309 if (ctx.kind === "doorway")
1257 1310 {
1258 1311 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
@@ -1376,6 +1429,7 @@ async function main ()
1376 1429 questsModal?.handleMessage(message);
1377 1430 settingsModal?.handleMessage(message);
1378 1431 dialoguesModal?.handleMessage(message);
1432 tileConfigModal?.handleMessage(message);
1379 1433 }
1380 1434 else if (message.type === MessageType.editorDialogues)
1381 1435 {
@@ -1768,6 +1822,18 @@ document.addEventListener("contextmenu", (event) =>
1768 1822 });
1769 1823 return;
1770 1824 }
1825 if (block?.typeId === BlockType.door)
1826 {
1827 tileConfigModal.openDoor({
1828 localX,
1829 localY,
1830 tileX: tile.tileX,
1831 tileY: tile.tileY,
1832 state: block.state,
1833 config: block.config ? { ...block.config } : {}
1834 });
1835 return;
1836 }
1771 1837 if (block?.typeId === BlockType.fishingSpot)
1772 1838 {
1773 1839 tileConfigModal.openFishingSpot({
@@ -47,6 +47,7 @@ import
47 normalizeDimensionId,
47 normalizeDimensionId,
48 isOverworld
48 isOverworld
49} from "/shared/world/dimensions.js";
49} from "/shared/world/dimensions.js";
50import { normalizeDoorConfig } from "/shared/world/doorRequirements.js";
50
51
51const game = new Game();
52const game = new Game();
52let socket;
53let socket;
@@ -1197,6 +1198,9 @@ async function main ()
1197 },
1198 },
1198 MessageType,
1199 MessageType,
1199 getDialogues: () => dialoguesModal?.getDialogues?.() ?? [],
1200 getDialogues: () => dialoguesModal?.getDialogues?.() ?? [],
1201 getQuests: () => questsModal?.getQuests?.() ?? [],
1202 describeWorldTile,
1203 centerEditorOnTile,
1200 getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
1204 getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
1201 id: dim.dimensionId,
1205 id: dim.dimensionId,
1202 label: dim.displayName || dim.dimensionId,
1206 label: dim.displayName || dim.dimensionId,
@@ -1227,6 +1231,31 @@ async function main ()
1227 afterDraftMutation();
1231 afterDraftMutation();
1228 return;
1232 return;
1229 }
1233 }
1234 if (ctx.kind === "door")
1235 {
1236 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1237 const existing = draft.blocks[index];
1238 if (!existing || existing.typeId !== BlockType.door)
1239 { return; }
1240 const prev = existing.config && typeof existing.config === "object" ? { ...existing.config } : {};
1241 const nextConfig = normalizeDoorConfig({
1242 ...prev,
1243 when: config.when,
1244 blockedMessage: config.blockedMessage
1245 });
1246 draft.blocks[index] = {
1247 typeId: BlockType.door,
1248 state: existing.state,
1249 config: nextConfig
1250 };
1251 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1252 ground: draft.grounds[index],
1253 block: draft.blocks[index],
1254 light: draft.light[index]
1255 });
1256 afterDraftMutation();
1257 return;
1258 }
1230 if (ctx.kind === "fishing-spot")
1259 if (ctx.kind === "fishing-spot")
1231 {
1260 {
1232 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1261 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
@@ -1253,6 +1282,30 @@ async function main ()
1253 {
1282 {
1254 if (!draft)
1283 if (!draft)
1255 { return; }
1284 { return; }
1285 if (ctx.kind === "door")
1286 {
1287 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1288 const existing = draft.blocks[index];
1289 if (!existing || existing.typeId !== BlockType.door)
1290 { return; }
1291 const prev = existing.config && typeof existing.config === "object" ? { ...existing.config } : {};
1292 delete prev.when;
1293 delete prev.requirements;
1294 delete prev.blockedMessage;
1295 delete prev.denyMessage;
1296 draft.blocks[index] = {
1297 typeId: BlockType.door,
1298 state: existing.state,
1299 config: normalizeDoorConfig(prev)
1300 };
1301 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1302 ground: draft.grounds[index],
1303 block: draft.blocks[index],
1304 light: draft.light[index]
1305 });
1306 afterDraftMutation();
1307 return;
1308 }
1256 if (ctx.kind === "doorway")
1309 if (ctx.kind === "doorway")
1257 {
1310 {
1258 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1311 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
@@ -1376,6 +1429,7 @@ async function main ()
1376 questsModal?.handleMessage(message);
1429 questsModal?.handleMessage(message);
1377 settingsModal?.handleMessage(message);
1430 settingsModal?.handleMessage(message);
1378 dialoguesModal?.handleMessage(message);
1431 dialoguesModal?.handleMessage(message);
1432 tileConfigModal?.handleMessage(message);
1379 }
1433 }
1380 else if (message.type === MessageType.editorDialogues)
1434 else if (message.type === MessageType.editorDialogues)
1381 {
1435 {
@@ -1768,6 +1822,18 @@ document.addEventListener("contextmenu", (event) =>
1768 });
1822 });
1769 return;
1823 return;
1770 }
1824 }
1825 if (block?.typeId === BlockType.door)
1826 {
1827 tileConfigModal.openDoor({
1828 localX,
1829 localY,
1830 tileX: tile.tileX,
1831 tileY: tile.tileY,
1832 state: block.state,
1833 config: block.config ? { ...block.config } : {}
1834 });
1835 return;
1836 }
1771 if (block?.typeId === BlockType.fishingSpot)
1837 if (block?.typeId === BlockType.fishingSpot)
1772 {
1838 {
1773 tileConfigModal.openFishingSpot({
1839 tileConfigModal.openFishingSpot({
client/src/editor/questsModal.js +1 −0
@@ -216,6 +216,7 @@ export function initQuestsModal ({
216 216
217 217 return {
218 218 isOpen: () => open,
219 getQuests: () => quests,
219 220 handleMessage (message)
220 221 {
221 222 if (message.type === MessageType.editorDialogues)
@@ -216,6 +216,7 @@ export function initQuestsModal ({
216
216
217 return {
217 return {
218 isOpen: () => open,
218 isOpen: () => open,
219 getQuests: () => quests,
219 handleMessage (message)
220 handleMessage (message)
220 {
221 {
221 if (message.type === MessageType.editorDialogues)
222 if (message.type === MessageType.editorDialogues)
client/src/editor/tileConfigModal.js +98 −11
@@ -20,6 +20,8 @@ import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
20 20 import { normalizeRgb } from "/shared/render/tint.js";
21 21 import { createDimensionCombobox } from "./dimensionCombobox.js";
22 22 import { OVERWORLD_ID, normalizeDimensionId } from "/shared/world/dimensions.js";
23 import { renderConditionSet, emptyConditionSet, normalizeConditionSet } from "./conditionSetEditor.js";
24 import { DEFAULT_DOOR_BLOCKED_MESSAGE } from "/shared/world/doorRequirements.js";
23 25
24 26 const DOORWAY_STATES = Object.freeze(["door", "ladder", "hole", "cave"]);
25 27 const ITEM_SEARCH_PAGE_SIZE = 40;
@@ -90,7 +92,10 @@ export function initTileConfigModal ({
90 92 socket,
91 93 MessageType,
92 94 getDialogues,
93 getDimensionOptions
95 getQuests,
96 getDimensionOptions,
97 describeWorldTile = null,
98 centerEditorOnTile = null
94 99 })
95 100 {
96 101 const backdrop = document.getElementById("tile-config-backdrop");
@@ -140,6 +145,10 @@ export function initTileConfigModal ({
140 145 let itemSearchMatches = null;
141 146 /** @type {ReturnType<typeof createDimensionCombobox>|null} */
142 147 let doorwayDimCombo = null;
148 /** @type {{ all: object[] }} */
149 let doorWhenDraft = emptyConditionSet();
150 /** @type {string} */
151 let doorBlockedMessageDraft = "";
143 152
144 153 function show (visible)
145 154 {
@@ -150,6 +159,8 @@ export function initTileConfigModal ({
150 159 {
151 160 context = null;
152 161 doorwayDimCombo = null;
162 doorWhenDraft = emptyConditionSet();
163 doorBlockedMessageDraft = "";
153 164 closeItemSearch();
154 165 closeDyePicker();
155 166 }
@@ -1050,6 +1061,64 @@ export function initTileConfigModal ({
1050 1061 show(true);
1051 1062 }
1052 1063
1064 function renderDoorRequirementsForm ()
1065 {
1066 form.innerHTML = "";
1067 const hint = document.createElement("p");
1068 hint.className = "tile-config-hint";
1069 hint.textContent = "Players who fail these requirements cannot pass this door — even when it is held open.";
1070 form.append(hint);
1071 const whenHost = document.createElement("div");
1072 whenHost.className = "door-requirements-when";
1073 form.append(whenHost);
1074 const remountWhen = () =>
1075 {
1076 whenHost.replaceChildren(renderConditionSet(doorWhenDraft, (next, { remount = true } = {}) =>
1077 {
1078 doorWhenDraft = normalizeConditionSet(next);
1079 if (remount)
1080 { remountWhen(); }
1081 }, {
1082 quests: typeof getQuests === "function" ? (getQuests() ?? []) : [],
1083 dialogues: typeof getDialogues === "function" ? (getDialogues() ?? []) : [],
1084 describeWorldTile,
1085 centerEditorOnTile,
1086 getDimensionOptions
1087 }));
1088 };
1089 remountWhen();
1090 const msgLabel = document.createElement("label");
1091 msgLabel.append(document.createTextNode("Blocked toast"));
1092 const msg = document.createElement("input");
1093 msg.type = "text";
1094 msg.name = "blockedMessage";
1095 msg.maxLength = 200;
1096 msg.placeholder = DEFAULT_DOOR_BLOCKED_MESSAGE;
1097 msg.value = doorBlockedMessageDraft;
1098 msg.addEventListener("input", () =>
1099 {
1100 doorBlockedMessageDraft = msg.value;
1101 });
1102 msgLabel.append(msg);
1103 form.append(msgLabel);
1104 }
1105
1106 function openDoor (ctx)
1107 {
1108 context = { kind: "door", ...ctx };
1109 const config = ctx.config && typeof ctx.config === "object" ? ctx.config : {};
1110 doorWhenDraft = normalizeConditionSet(config.when ?? config.requirements ?? emptyConditionSet());
1111 doorBlockedMessageDraft = String(config.blockedMessage ?? config.denyMessage ?? "").trim();
1112 title.textContent = `Door · ${ctx.tileX}, ${ctx.tileY}`;
1113 if (socket && MessageType)
1114 {
1115 socket.send({ type: MessageType.editorLoadQuests });
1116 socket.send({ type: MessageType.editorLoadDialogues });
1117 }
1118 renderDoorRequirementsForm();
1119 show(true);
1120 }
1121
1053 1122 document.getElementById("tile-config-close").addEventListener("click", () => show(false));
1054 1123 document.getElementById("tile-config-cancel").addEventListener("click", () => show(false));
1055 1124 backdrop.addEventListener("click", () => show(false));
@@ -1111,6 +1180,15 @@ export function initTileConfigModal ({
1111 1180 show(false);
1112 1181 return;
1113 1182 }
1183 if (context.kind === "door")
1184 {
1185 onSave?.(context, {
1186 when: normalizeConditionSet(doorWhenDraft),
1187 blockedMessage: String(doorBlockedMessageDraft ?? "").trim()
1188 });
1189 show(false);
1190 return;
1191 }
1114 1192 if (context.kind === "fishing-spot")
1115 1193 {
1116 1194 onSave?.(context, normalizeFishingSpotConfig({ fishes: fishesDraft }));
@@ -1169,23 +1247,32 @@ export function initTileConfigModal ({
1169 1247 isOpen: () => open,
1170 1248 openSpawner,
1171 1249 openDoorway,
1250 openDoor,
1172 1251 openFishingSpot,
1173 1252 close: () => show(false),
1174 1253 handleMessage (message)
1175 1254 {
1176 if (!MessageType || message.type !== MessageType.editorDialogues)
1255 if (!MessageType)
1177 1256 { return; }
1178 dialogueOptions = (message.dialogues ?? []).map((d) => ({
1179 dialogueId: String(d.dialogueId ?? ""),
1180 label: String(d.label ?? d.dialogueId ?? ""),
1181 unique: !!d.unique
1182 })).filter((d) => d.dialogueId);
1183 const select = form.querySelector('[name="dialogueId"]');
1184 if (select && open)
1257 if (message.type === MessageType.editorDialogues)
1185 1258 {
1186 const current = select.value || pendingDialogueId || "";
1187 select.replaceWith(dialogueSelect("dialogueId", current, dialogueOptions));
1259 dialogueOptions = (message.dialogues ?? []).map((d) => ({
1260 dialogueId: String(d.dialogueId ?? ""),
1261 label: String(d.label ?? d.dialogueId ?? ""),
1262 unique: !!d.unique
1263 })).filter((d) => d.dialogueId);
1264 const select = form.querySelector('[name="dialogueId"]');
1265 if (select && open)
1266 {
1267 const current = select.value || pendingDialogueId || "";
1268 select.replaceWith(dialogueSelect("dialogueId", current, dialogueOptions));
1269 }
1270 if (open && context?.kind === "door")
1271 { renderDoorRequirementsForm(); }
1272 return;
1188 1273 }
1274 if (message.type === MessageType.editorQuests && open && context?.kind === "door")
1275 { renderDoorRequirementsForm(); }
1189 1276 }
1190 1277 };
1191 1278 }
@@ -20,6 +20,8 @@ import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
20import { normalizeRgb } from "/shared/render/tint.js";
20import { normalizeRgb } from "/shared/render/tint.js";
21import { createDimensionCombobox } from "./dimensionCombobox.js";
21import { createDimensionCombobox } from "./dimensionCombobox.js";
22import { OVERWORLD_ID, normalizeDimensionId } from "/shared/world/dimensions.js";
22import { OVERWORLD_ID, normalizeDimensionId } from "/shared/world/dimensions.js";
23import { renderConditionSet, emptyConditionSet, normalizeConditionSet } from "./conditionSetEditor.js";
24import { DEFAULT_DOOR_BLOCKED_MESSAGE } from "/shared/world/doorRequirements.js";
23
25
24const DOORWAY_STATES = Object.freeze(["door", "ladder", "hole", "cave"]);
26const DOORWAY_STATES = Object.freeze(["door", "ladder", "hole", "cave"]);
25const ITEM_SEARCH_PAGE_SIZE = 40;
27const ITEM_SEARCH_PAGE_SIZE = 40;
@@ -90,7 +92,10 @@ export function initTileConfigModal ({
90 socket,
92 socket,
91 MessageType,
93 MessageType,
92 getDialogues,
94 getDialogues,
93 getDimensionOptions
95 getQuests,
96 getDimensionOptions,
97 describeWorldTile = null,
98 centerEditorOnTile = null
94})
99})
95{
100{
96 const backdrop = document.getElementById("tile-config-backdrop");
101 const backdrop = document.getElementById("tile-config-backdrop");
@@ -140,6 +145,10 @@ export function initTileConfigModal ({
140 let itemSearchMatches = null;
145 let itemSearchMatches = null;
141 /** @type {ReturnType<typeof createDimensionCombobox>|null} */
146 /** @type {ReturnType<typeof createDimensionCombobox>|null} */
142 let doorwayDimCombo = null;
147 let doorwayDimCombo = null;
148 /** @type {{ all: object[] }} */
149 let doorWhenDraft = emptyConditionSet();
150 /** @type {string} */
151 let doorBlockedMessageDraft = "";
143
152
144 function show (visible)
153 function show (visible)
145 {
154 {
@@ -150,6 +159,8 @@ export function initTileConfigModal ({
150 {
159 {
151 context = null;
160 context = null;
152 doorwayDimCombo = null;
161 doorwayDimCombo = null;
162 doorWhenDraft = emptyConditionSet();
163 doorBlockedMessageDraft = "";
153 closeItemSearch();
164 closeItemSearch();
154 closeDyePicker();
165 closeDyePicker();
155 }
166 }
@@ -1050,6 +1061,64 @@ export function initTileConfigModal ({
1050 show(true);
1061 show(true);
1051 }
1062 }
1052
1063
1064 function renderDoorRequirementsForm ()
1065 {
1066 form.innerHTML = "";
1067 const hint = document.createElement("p");
1068 hint.className = "tile-config-hint";
1069 hint.textContent = "Players who fail these requirements cannot pass this door — even when it is held open.";
1070 form.append(hint);
1071 const whenHost = document.createElement("div");
1072 whenHost.className = "door-requirements-when";
1073 form.append(whenHost);
1074 const remountWhen = () =>
1075 {
1076 whenHost.replaceChildren(renderConditionSet(doorWhenDraft, (next, { remount = true } = {}) =>
1077 {
1078 doorWhenDraft = normalizeConditionSet(next);
1079 if (remount)
1080 { remountWhen(); }
1081 }, {
1082 quests: typeof getQuests === "function" ? (getQuests() ?? []) : [],
1083 dialogues: typeof getDialogues === "function" ? (getDialogues() ?? []) : [],
1084 describeWorldTile,
1085 centerEditorOnTile,
1086 getDimensionOptions
1087 }));
1088 };
1089 remountWhen();
1090 const msgLabel = document.createElement("label");
1091 msgLabel.append(document.createTextNode("Blocked toast"));
1092 const msg = document.createElement("input");
1093 msg.type = "text";
1094 msg.name = "blockedMessage";
1095 msg.maxLength = 200;
1096 msg.placeholder = DEFAULT_DOOR_BLOCKED_MESSAGE;
1097 msg.value = doorBlockedMessageDraft;
1098 msg.addEventListener("input", () =>
1099 {
1100 doorBlockedMessageDraft = msg.value;
1101 });
1102 msgLabel.append(msg);
1103 form.append(msgLabel);
1104 }
1105
1106 function openDoor (ctx)
1107 {
1108 context = { kind: "door", ...ctx };
1109 const config = ctx.config && typeof ctx.config === "object" ? ctx.config : {};
1110 doorWhenDraft = normalizeConditionSet(config.when ?? config.requirements ?? emptyConditionSet());
1111 doorBlockedMessageDraft = String(config.blockedMessage ?? config.denyMessage ?? "").trim();
1112 title.textContent = `Door · ${ctx.tileX}, ${ctx.tileY}`;
1113 if (socket && MessageType)
1114 {
1115 socket.send({ type: MessageType.editorLoadQuests });
1116 socket.send({ type: MessageType.editorLoadDialogues });
1117 }
1118 renderDoorRequirementsForm();
1119 show(true);
1120 }
1121
1053 document.getElementById("tile-config-close").addEventListener("click", () => show(false));
1122 document.getElementById("tile-config-close").addEventListener("click", () => show(false));
1054 document.getElementById("tile-config-cancel").addEventListener("click", () => show(false));
1123 document.getElementById("tile-config-cancel").addEventListener("click", () => show(false));
1055 backdrop.addEventListener("click", () => show(false));
1124 backdrop.addEventListener("click", () => show(false));
@@ -1111,6 +1180,15 @@ export function initTileConfigModal ({
1111 show(false);
1180 show(false);
1112 return;
1181 return;
1113 }
1182 }
1183 if (context.kind === "door")
1184 {
1185 onSave?.(context, {
1186 when: normalizeConditionSet(doorWhenDraft),
1187 blockedMessage: String(doorBlockedMessageDraft ?? "").trim()
1188 });
1189 show(false);
1190 return;
1191 }
1114 if (context.kind === "fishing-spot")
1192 if (context.kind === "fishing-spot")
1115 {
1193 {
1116 onSave?.(context, normalizeFishingSpotConfig({ fishes: fishesDraft }));
1194 onSave?.(context, normalizeFishingSpotConfig({ fishes: fishesDraft }));
@@ -1169,23 +1247,32 @@ export function initTileConfigModal ({
1169 isOpen: () => open,
1247 isOpen: () => open,
1170 openSpawner,
1248 openSpawner,
1171 openDoorway,
1249 openDoorway,
1250 openDoor,
1172 openFishingSpot,
1251 openFishingSpot,
1173 close: () => show(false),
1252 close: () => show(false),
1174 handleMessage (message)
1253 handleMessage (message)
1175 {
1254 {
1176 if (!MessageType || message.type !== MessageType.editorDialogues)
1255 if (!MessageType)
1177 { return; }
1256 { return; }
1178 dialogueOptions = (message.dialogues ?? []).map((d) => ({
1257 if (message.type === MessageType.editorDialogues)
1179 dialogueId: String(d.dialogueId ?? ""),
1180 label: String(d.label ?? d.dialogueId ?? ""),
1181 unique: !!d.unique
1182 })).filter((d) => d.dialogueId);
1183 const select = form.querySelector('[name="dialogueId"]');
1184 if (select && open)
1185 {
1258 {
1186 const current = select.value || pendingDialogueId || "";
1259 dialogueOptions = (message.dialogues ?? []).map((d) => ({
1187 select.replaceWith(dialogueSelect("dialogueId", current, dialogueOptions));
1260 dialogueId: String(d.dialogueId ?? ""),
1261 label: String(d.label ?? d.dialogueId ?? ""),
1262 unique: !!d.unique
1263 })).filter((d) => d.dialogueId);
1264 const select = form.querySelector('[name="dialogueId"]');
1265 if (select && open)
1266 {
1267 const current = select.value || pendingDialogueId || "";
1268 select.replaceWith(dialogueSelect("dialogueId", current, dialogueOptions));
1269 }
1270 if (open && context?.kind === "door")
1271 { renderDoorRequirementsForm(); }
1272 return;
1188 }
1273 }
1274 if (message.type === MessageType.editorQuests && open && context?.kind === "door")
1275 { renderDoorRequirementsForm(); }
1189 }
1276 }
1190 };
1277 };
1191}
1278}
client/ui/editor.css +13 −0
@@ -992,6 +992,19 @@ label {
992 992 flex: 1;
993 993 min-height: 0;
994 994 overflow: auto;
995 max-height: min(70vh, 640px);
996 }
997
998 #tile-config-form .tile-config-hint {
999 margin: 0;
1000 opacity: 0.85;
1001 font-size: 0.9rem;
1002 }
1003
1004 #tile-config-form .door-requirements-when {
1005 display: flex;
1006 flex-direction: column;
1007 gap: 0.5rem;
995 1008 }
996 1009
997 1010 .spawner-sells-header {
@@ -992,6 +992,19 @@ label {
992 flex: 1;
992 flex: 1;
993 min-height: 0;
993 min-height: 0;
994 overflow: auto;
994 overflow: auto;
995 max-height: min(70vh, 640px);
996}
997
998#tile-config-form .tile-config-hint {
999 margin: 0;
1000 opacity: 0.85;
1001 font-size: 0.9rem;
1002}
1003
1004#tile-config-form .door-requirements-when {
1005 display: flex;
1006 flex-direction: column;
1007 gap: 0.5rem;
995}
1008}
996
1009
997.spawner-sells-header {
1010.spawner-sells-header {
server/src/doors/conditionContext.js added +162 −0
@@ -0,0 +1,162 @@
1 /**
2 * Build evaluateConditionSet context from ECS entity + conditionAccess snapshot.
3 * Used on simulation workers (no stateDb).
4 */
5 import { Component } from "../ecs/components.js";
6 import { countItemInSlots } from "../../../shared/items/inventory.js";
7 import { skillLevel } from "../../../shared/definitions/skills.js";
8 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
9 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
10 import { doorHasRequirements, doorRequirementsMet } from "../../../shared/world/doorRequirements.js";
11 import { BlockType } from "../../../shared/definitions/tiles.js";
12 import { tileToChunk, tileToLocal, tileKey } from "../world/coordinates.js";
13
14 function killProgressKey (condition)
15 {
16 if (condition?.spawnerId)
17 { return `spawner:${condition.spawnerId}`; }
18 return `mob:${condition.mobTypeId}`;
19 }
20
21 function interactProgressKey (condition)
22 {
23 if (condition?.tileX != null)
24 { return `tile:${condition.tileX},${condition.tileY}`; }
25 return `block:${condition.blockTypeId}`;
26 }
27
28 function floorDiv (value, size)
29 {
30 return Math.floor(value / size);
31 }
32
33 /**
34 * Serializable snapshot stored on Component.conditionAccess.
35 * @param {import("../persistence/stateDb.js").StateDb} stateDb
36 * @param {number} characterId
37 */
38 export function buildConditionAccessSnapshot (stateDb, characterId)
39 {
40 const questStates = Object.create(null);
41 const questProgress = Object.create(null);
42 for (const row of stateDb.listQuestStates(characterId))
43 {
44 questStates[row.questId] = row.state;
45 questProgress[row.questId] = row.progress ?? {};
46 }
47 const dialogueHeard = (stateDb.listDialogueHeard(characterId) ?? []).map(
48 (row) => `${row.dialogue_id}\0${row.step_id}`
49 );
50 const dialogueTriggers = (stateDb.listDialogueTriggers?.(characterId) ?? []).map(
51 (row) => `${row.dialogue_id}\0${row.trigger_id}`
52 );
53 const visitedDimensions = (stateDb.listVisitedDimensions(characterId) ?? []).map(
54 (row) => normalizeDimensionId(row.dimensionId)
55 );
56 return {
57 questStates,
58 questProgress,
59 dialogueHeard,
60 dialogueTriggers,
61 visitedDimensions
62 };
63 }
64
65 /**
66 * @param {object} world — WorkerWorld-like (ecs + chunkData)
67 * @param {number} entityId
68 */
69 export function buildEntityConditionContext (world, entityId)
70 {
71 const handle = world.ecs.handleOf(entityId);
72 if (handle == null)
73 { return null; }
74 const position = world.ecs.get(handle, Component.position);
75 if (!position)
76 { return null; }
77 const tileX = position.tileX | 0;
78 const tileY = position.tileY | 0;
79 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
80 const inventory = world.ecs.get(handle, Component.inventory)?.slots ?? [];
81 const health = world.ecs.get(handle, Component.health);
82 const stamina = world.ecs.get(handle, Component.stamina);
83 const skills = world.ecs.get(handle, Component.skills);
84 const access = world.ecs.get(handle, Component.conditionAccess) ?? {
85 questStates: {},
86 questProgress: {},
87 dialogueHeard: [],
88 dialogueTriggers: [],
89 visitedDimensions: []
90 };
91 const heard = new Set(access.dialogueHeard ?? []);
92 const triggers = new Set(access.dialogueTriggers ?? []);
93 const visited = new Set(access.visitedDimensions ?? []);
94 const questStates = access.questStates ?? {};
95 const questProgress = access.questProgress ?? {};
96 return {
97 tileX,
98 tileY,
99 chunkX: floorDiv(tileX, CHUNK_SIZE),
100 chunkY: floorDiv(tileY, CHUNK_SIZE),
101 dimensionId,
102 hp: health?.current ?? 0,
103 maxHp: health?.max ?? 1,
104 stamina: stamina?.current ?? 0,
105 maxStamina: stamina?.max ?? 1,
106 countItem: (itemId) => countItemInSlots(inventory, itemId | 0),
107 questState: (questId) => questStates[String(questId)] ?? "not-started",
108 dialogueHeard: (dialogueId, stepId) => heard.has(`${dialogueId}\0${stepId}`),
109 dialogueTriggerLatched: (dialogueId, trigger) => triggers.has(`${dialogueId}\0${trigger}`),
110 skillLevel: (skillId) => skillLevel(skills ?? {}, skillId),
111 hasVisitedDimension: (dimId) => visited.has(normalizeDimensionId(dimId)),
112 killCount: (condition) =>
113 {
114 const key = killProgressKey(condition);
115 let total = 0;
116 for (const progress of Object.values(questProgress))
117 { total += progress?.counters?.[key] | 0; }
118 return total;
119 },
120 interactBlockDone: (condition) =>
121 {
122 const key = interactProgressKey(condition);
123 for (const progress of Object.values(questProgress))
124 {
125 if (progress?.interacts?.[key])
126 { return true; }
127 }
128 return false;
129 }
130 };
131 }
132
133 function readDoorBlock (world, tileX, tileY, dimensionId)
134 {
135 const data = world.chunkData?.(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
136 if (!data)
137 { return null; }
138 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
139 return data.blocks?.[index] ?? null;
140 }
141
142 /**
143 * Players must meet door requirements; mobs ignore gates.
144 * Empty requirements always allow.
145 */
146 export function entityDoorRequirementsAllow (world, entityId, tileX, tileY)
147 {
148 const handle = world.ecs.handleOf(entityId);
149 if (handle == null)
150 { return true; }
151 const position = world.ecs.get(handle, Component.position);
152 const dimensionId = normalizeDimensionId(position?.dimensionId ?? OVERWORLD_ID);
153 const block = readDoorBlock(world, tileX, tileY, dimensionId);
154 if (!block || (block.typeId | 0) !== BlockType.door || !doorHasRequirements(block))
155 { return true; }
156 if (!world.ecs.get(handle, Component.character))
157 { return true; }
158 const ctx = buildEntityConditionContext(world, entityId);
159 return doorRequirementsMet(block, ctx);
160 }
161
162 export { tileKey };
@@ -0,0 +1,162 @@
1/**
2 * Build evaluateConditionSet context from ECS entity + conditionAccess snapshot.
3 * Used on simulation workers (no stateDb).
4 */
5import { Component } from "../ecs/components.js";
6import { countItemInSlots } from "../../../shared/items/inventory.js";
7import { skillLevel } from "../../../shared/definitions/skills.js";
8import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
9import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
10import { doorHasRequirements, doorRequirementsMet } from "../../../shared/world/doorRequirements.js";
11import { BlockType } from "../../../shared/definitions/tiles.js";
12import { tileToChunk, tileToLocal, tileKey } from "../world/coordinates.js";
13
14function killProgressKey (condition)
15{
16 if (condition?.spawnerId)
17 { return `spawner:${condition.spawnerId}`; }
18 return `mob:${condition.mobTypeId}`;
19}
20
21function interactProgressKey (condition)
22{
23 if (condition?.tileX != null)
24 { return `tile:${condition.tileX},${condition.tileY}`; }
25 return `block:${condition.blockTypeId}`;
26}
27
28function floorDiv (value, size)
29{
30 return Math.floor(value / size);
31}
32
33/**
34 * Serializable snapshot stored on Component.conditionAccess.
35 * @param {import("../persistence/stateDb.js").StateDb} stateDb
36 * @param {number} characterId
37 */
38export function buildConditionAccessSnapshot (stateDb, characterId)
39{
40 const questStates = Object.create(null);
41 const questProgress = Object.create(null);
42 for (const row of stateDb.listQuestStates(characterId))
43 {
44 questStates[row.questId] = row.state;
45 questProgress[row.questId] = row.progress ?? {};
46 }
47 const dialogueHeard = (stateDb.listDialogueHeard(characterId) ?? []).map(
48 (row) => `${row.dialogue_id}\0${row.step_id}`
49 );
50 const dialogueTriggers = (stateDb.listDialogueTriggers?.(characterId) ?? []).map(
51 (row) => `${row.dialogue_id}\0${row.trigger_id}`
52 );
53 const visitedDimensions = (stateDb.listVisitedDimensions(characterId) ?? []).map(
54 (row) => normalizeDimensionId(row.dimensionId)
55 );
56 return {
57 questStates,
58 questProgress,
59 dialogueHeard,
60 dialogueTriggers,
61 visitedDimensions
62 };
63}
64
65/**
66 * @param {object} world — WorkerWorld-like (ecs + chunkData)
67 * @param {number} entityId
68 */
69export function buildEntityConditionContext (world, entityId)
70{
71 const handle = world.ecs.handleOf(entityId);
72 if (handle == null)
73 { return null; }
74 const position = world.ecs.get(handle, Component.position);
75 if (!position)
76 { return null; }
77 const tileX = position.tileX | 0;
78 const tileY = position.tileY | 0;
79 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
80 const inventory = world.ecs.get(handle, Component.inventory)?.slots ?? [];
81 const health = world.ecs.get(handle, Component.health);
82 const stamina = world.ecs.get(handle, Component.stamina);
83 const skills = world.ecs.get(handle, Component.skills);
84 const access = world.ecs.get(handle, Component.conditionAccess) ?? {
85 questStates: {},
86 questProgress: {},
87 dialogueHeard: [],
88 dialogueTriggers: [],
89 visitedDimensions: []
90 };
91 const heard = new Set(access.dialogueHeard ?? []);
92 const triggers = new Set(access.dialogueTriggers ?? []);
93 const visited = new Set(access.visitedDimensions ?? []);
94 const questStates = access.questStates ?? {};
95 const questProgress = access.questProgress ?? {};
96 return {
97 tileX,
98 tileY,
99 chunkX: floorDiv(tileX, CHUNK_SIZE),
100 chunkY: floorDiv(tileY, CHUNK_SIZE),
101 dimensionId,
102 hp: health?.current ?? 0,
103 maxHp: health?.max ?? 1,
104 stamina: stamina?.current ?? 0,
105 maxStamina: stamina?.max ?? 1,
106 countItem: (itemId) => countItemInSlots(inventory, itemId | 0),
107 questState: (questId) => questStates[String(questId)] ?? "not-started",
108 dialogueHeard: (dialogueId, stepId) => heard.has(`${dialogueId}\0${stepId}`),
109 dialogueTriggerLatched: (dialogueId, trigger) => triggers.has(`${dialogueId}\0${trigger}`),
110 skillLevel: (skillId) => skillLevel(skills ?? {}, skillId),
111 hasVisitedDimension: (dimId) => visited.has(normalizeDimensionId(dimId)),
112 killCount: (condition) =>
113 {
114 const key = killProgressKey(condition);
115 let total = 0;
116 for (const progress of Object.values(questProgress))
117 { total += progress?.counters?.[key] | 0; }
118 return total;
119 },
120 interactBlockDone: (condition) =>
121 {
122 const key = interactProgressKey(condition);
123 for (const progress of Object.values(questProgress))
124 {
125 if (progress?.interacts?.[key])
126 { return true; }
127 }
128 return false;
129 }
130 };
131}
132
133function readDoorBlock (world, tileX, tileY, dimensionId)
134{
135 const data = world.chunkData?.(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
136 if (!data)
137 { return null; }
138 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
139 return data.blocks?.[index] ?? null;
140}
141
142/**
143 * Players must meet door requirements; mobs ignore gates.
144 * Empty requirements always allow.
145 */
146export function entityDoorRequirementsAllow (world, entityId, tileX, tileY)
147{
148 const handle = world.ecs.handleOf(entityId);
149 if (handle == null)
150 { return true; }
151 const position = world.ecs.get(handle, Component.position);
152 const dimensionId = normalizeDimensionId(position?.dimensionId ?? OVERWORLD_ID);
153 const block = readDoorBlock(world, tileX, tileY, dimensionId);
154 if (!block || (block.typeId | 0) !== BlockType.door || !doorHasRequirements(block))
155 { return true; }
156 if (!world.ecs.get(handle, Component.character))
157 { return true; }
158 const ctx = buildEntityConditionContext(world, entityId);
159 return doorRequirementsMet(block, ctx);
160}
161
162export { tileKey };
server/src/doors/service.js +3 −0
@@ -11,6 +11,7 @@ import { tileToChunk, tileToLocal, tileKey, parseTileKey } from "../world/coordi
11 11 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
12 12 import { OVERWORLD_ID } from "../../../shared/world/dimensions.js";
13 13 import { tileLightOcclusionAt } from "../../../shared/lighting/chunkOcclusion.js";
14 import { entityDoorRequirementsAllow } from "./conditionContext.js";
14 15
15 16 export function isDoorTypeId (typeId)
16 17 {
@@ -199,6 +200,8 @@ export function maybeOpenDoorOnApproach (world, entityId, nextTileX, nextTileY)
199 200 {
200 201 if (!entityCanOpenDoors(world.ecs, entityId))
201 202 { return null; }
203 if (!entityDoorRequirementsAllow(world, entityId, nextTileX, nextTileY))
204 { return null; }
202 205 const handle = world.ecs.handleOf(entityId);
203 206 const position = handle != null ? world.ecs.get(handle, Component.position) : null;
204 207 const dimensionId = position?.dimensionId ?? OVERWORLD_ID;
@@ -11,6 +11,7 @@ import { tileToChunk, tileToLocal, tileKey, parseTileKey } from "../world/coordi
11import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
11import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
12import { OVERWORLD_ID } from "../../../shared/world/dimensions.js";
12import { OVERWORLD_ID } from "../../../shared/world/dimensions.js";
13import { tileLightOcclusionAt } from "../../../shared/lighting/chunkOcclusion.js";
13import { tileLightOcclusionAt } from "../../../shared/lighting/chunkOcclusion.js";
14import { entityDoorRequirementsAllow } from "./conditionContext.js";
14
15
15export function isDoorTypeId (typeId)
16export function isDoorTypeId (typeId)
16{
17{
@@ -199,6 +200,8 @@ export function maybeOpenDoorOnApproach (world, entityId, nextTileX, nextTileY)
199{
200{
200 if (!entityCanOpenDoors(world.ecs, entityId))
201 if (!entityCanOpenDoors(world.ecs, entityId))
201 { return null; }
202 { return null; }
203 if (!entityDoorRequirementsAllow(world, entityId, nextTileX, nextTileY))
204 { return null; }
202 const handle = world.ecs.handleOf(entityId);
205 const handle = world.ecs.handleOf(entityId);
203 const position = handle != null ? world.ecs.get(handle, Component.position) : null;
206 const position = handle != null ? world.ecs.get(handle, Component.position) : null;
204 const dimensionId = position?.dimensionId ?? OVERWORLD_ID;
207 const dimensionId = position?.dimensionId ?? OVERWORLD_ID;
server/src/ecs/components.js +6 −1
@@ -29,7 +29,12 @@ export const Component = Object.freeze({
29 29 /** Temporary summoned companion (Shade, jadeite fairy). */
30 30 summon: "summon",
31 31 /** Player chunk residency for aggro peace (sinceMs when current chunk was entered). */
32 chunkPresence: "chunkPresence"
32 chunkPresence: "chunkPresence",
33 /**
34 * Snapshot for ConditionSet evaluation on workers (quests / dialogue / visited dims).
35 * Inventory, skills, HP come from live ECS components.
36 */
37 conditionAccess: "conditionAccess"
33 38 });
34 39
35 40 /** Default position component fields (tile coords + dimension). */
@@ -29,7 +29,12 @@ export const Component = Object.freeze({
29 /** Temporary summoned companion (Shade, jadeite fairy). */
29 /** Temporary summoned companion (Shade, jadeite fairy). */
30 summon: "summon",
30 summon: "summon",
31 /** Player chunk residency for aggro peace (sinceMs when current chunk was entered). */
31 /** Player chunk residency for aggro peace (sinceMs when current chunk was entered). */
32 chunkPresence: "chunkPresence"
32 chunkPresence: "chunkPresence",
33 /**
34 * Snapshot for ConditionSet evaluation on workers (quests / dialogue / visited dims).
35 * Inventory, skills, HP come from live ECS components.
36 */
37 conditionAccess: "conditionAccess"
33});
38});
34
39
35/** Default position component fields (tile coords + dimension). */
40/** Default position component fields (tile coords + dimension). */
server/src/persistence/stateDb.js +9 −0
@@ -1018,6 +1018,15 @@ export class StateDatabase
1018 1018 `).run(characterId | 0, String(dialogueId), String(triggerId), Date.now());
1019 1019 }
1020 1020
1021 listDialogueTriggers (characterId)
1022 {
1023 return this.db.prepare(`
1024 SELECT dialogue_id, trigger_id, latched_at
1025 FROM character_dialogue_triggers
1026 WHERE character_id = ?
1027 `).all(characterId | 0);
1028 }
1029
1021 1030 appendQuestJournal (characterId, questId, stepId, text)
1022 1031 {
1023 1032 const trimmed = String(text ?? "").trim();
@@ -1018,6 +1018,15 @@ export class StateDatabase
1018 `).run(characterId | 0, String(dialogueId), String(triggerId), Date.now());
1018 `).run(characterId | 0, String(dialogueId), String(triggerId), Date.now());
1019 }
1019 }
1020
1020
1021 listDialogueTriggers (characterId)
1022 {
1023 return this.db.prepare(`
1024 SELECT dialogue_id, trigger_id, latched_at
1025 FROM character_dialogue_triggers
1026 WHERE character_id = ?
1027 `).all(characterId | 0);
1028 }
1029
1021 appendQuestJournal (characterId, questId, stepId, text)
1030 appendQuestJournal (characterId, questId, stepId, text)
1022 {
1031 {
1023 const trimmed = String(text ?? "").trim();
1032 const trimmed = String(text ?? "").trim();
server/src/simulation/protocol.js +1 −0
@@ -43,6 +43,7 @@ export const WorkerMessage = Object.freeze({
43 43 releaseExchangeClerk: "releaseExchangeClerk",
44 44 applyAppearance: "applyAppearance",
45 45 applySkullValue: "applySkullValue",
46 applyConditionAccess: "applyConditionAccess",
46 47 engageTarget: "engageTarget",
47 48 listTownGuardsNear: "listTownGuardsNear",
48 49 pinDialogue: "pinDialogue",
@@ -43,6 +43,7 @@ export const WorkerMessage = Object.freeze({
43 releaseExchangeClerk: "releaseExchangeClerk",
43 releaseExchangeClerk: "releaseExchangeClerk",
44 applyAppearance: "applyAppearance",
44 applyAppearance: "applyAppearance",
45 applySkullValue: "applySkullValue",
45 applySkullValue: "applySkullValue",
46 applyConditionAccess: "applyConditionAccess",
46 engageTarget: "engageTarget",
47 engageTarget: "engageTarget",
47 listTownGuardsNear: "listTownGuardsNear",
48 listTownGuardsNear: "listTownGuardsNear",
48 pinDialogue: "pinDialogue",
49 pinDialogue: "pinDialogue",
server/src/simulation/simulation.js +30 −0
@@ -61,6 +61,7 @@ import { hairFromCharacterRow, appearanceHairFields } from "../../../shared/appe
61 61 import { QuestContentCache } from "../quests/contentCache.js";
62 62 import { QuestRuntime } from "../quests/runtime.js";
63 63 import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
64 import { buildConditionAccessSnapshot } from "../doors/conditionContext.js";
64 65
65 66 export class Simulation
66 67 {
@@ -524,6 +525,7 @@ export class Simulation
524 525 dimensionId,
525 526 sinceMs: this.now
526 527 },
528 conditionAccess: buildConditionAccessSnapshot(this.stateDb, character.character_id ?? row.character_id)
527 529 };
528 530 if (isDead)
529 531 { components.dead = {}; }
@@ -537,11 +539,13 @@ export class Simulation
537 539 this.#remember(view, workerId);
538 540 this.#attachSkullToRecord(view.entityId, character.character_id ?? row.character_id);
539 541 this.stateDb.markDimensionVisited(character.character_id, dimensionId);
542 this.syncCharacterConditionAccess(character.character_id ?? row.character_id);
540 543 this.#queueReplication(replicationSpawn(this.directory.get(view.entityId) ?? view));
541 544 this.#recalculateActivation(this.now);
542 545 this.#syncGhosts();
543 546 this.courier?.onCharacterEnteredWorld(character.character_id, tileX, tileY);
544 547 this.quests?.ensureInitialQuests?.(character.character_id ?? row.character_id);
548 this.syncCharacterConditionAccess(character.character_id ?? row.character_id);
545 549 return entityId;
546 550 }
547 551
@@ -587,6 +591,23 @@ export class Simulation
587 591 return event;
588 592 }
589 593
594 /** Push quest / dialogue / visited-dim snapshot onto the character's worker ECS. */
595 syncCharacterConditionAccess (characterId)
596 {
597 const id = characterId | 0;
598 if (!id)
599 { return; }
600 const entityId = this.characterEntities.get(id);
601 const record = entityId ? this.directory.get(entityId) : null;
602 if (!record)
603 { return; }
604 this.workers[record.workerId]?.call({
605 type: WorkerMessage.applyConditionAccess,
606 entityId,
607 conditionAccess: buildConditionAccessSnapshot(this.stateDb, id)
608 });
609 }
610
590 611 #attachSkullToRecord (entityId, characterId)
591 612 {
592 613 const record = this.directory.get(entityId);
@@ -1900,12 +1921,15 @@ export class Simulation
1900 1921 {
1901 1922 const out = [];
1902 1923 let needSnapshot = false;
1924 const syncAccessIds = new Set();
1903 1925 for (const event of events ?? [])
1904 1926 {
1905 1927 const cid = event.characterId ?? characterId;
1906 1928 const sid = sessionId ?? this.#sessionIdForCharacter(cid);
1907 1929 if (event.type === "dialogueStep")
1908 1930 {
1931 if (cid != null)
1932 { syncAccessIds.add(cid | 0); }
1909 1933 out.push({
1910 1934 type: "dialogue-step",
1911 1935 sessionId: sid,
@@ -1919,6 +1943,8 @@ export class Simulation
1919 1943 }
1920 1944 else if (event.type === "dialogueChoices")
1921 1945 {
1946 if (cid != null)
1947 { syncAccessIds.add(cid | 0); }
1922 1948 out.push({
1923 1949 type: "dialogue-choices",
1924 1950 sessionId: sid,
@@ -1985,7 +2011,10 @@ export class Simulation
1985 2011 characterId,
1986 2012 ...snap
1987 2013 });
2014 syncAccessIds.add(characterId | 0);
1988 2015 }
2016 for (const id of syncAccessIds)
2017 { this.syncCharacterConditionAccess(id); }
1989 2018 return out;
1990 2019 }
1991 2020
@@ -2351,6 +2380,7 @@ export class Simulation
2351 2380 targetDimensionId
2352 2381 );
2353 2382 this.stateDb.markDimensionVisited(characterId, targetDimensionId);
2383 this.syncCharacterConditionAccess(characterId);
2354 2384 this.#recalculateActivation(this.now);
2355 2385 this.#syncGhosts();
2356 2386 const dimRecord = this.getDimensionRecord(targetDimensionId);
@@ -61,6 +61,7 @@ import { hairFromCharacterRow, appearanceHairFields } from "../../../shared/appe
61import { QuestContentCache } from "../quests/contentCache.js";
61import { QuestContentCache } from "../quests/contentCache.js";
62import { QuestRuntime } from "../quests/runtime.js";
62import { QuestRuntime } from "../quests/runtime.js";
63import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
63import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
64import { buildConditionAccessSnapshot } from "../doors/conditionContext.js";
64
65
65export class Simulation
66export class Simulation
66{
67{
@@ -524,6 +525,7 @@ export class Simulation
524 dimensionId,
525 dimensionId,
525 sinceMs: this.now
526 sinceMs: this.now
526 },
527 },
528 conditionAccess: buildConditionAccessSnapshot(this.stateDb, character.character_id ?? row.character_id)
527 };
529 };
528 if (isDead)
530 if (isDead)
529 { components.dead = {}; }
531 { components.dead = {}; }
@@ -537,11 +539,13 @@ export class Simulation
537 this.#remember(view, workerId);
539 this.#remember(view, workerId);
538 this.#attachSkullToRecord(view.entityId, character.character_id ?? row.character_id);
540 this.#attachSkullToRecord(view.entityId, character.character_id ?? row.character_id);
539 this.stateDb.markDimensionVisited(character.character_id, dimensionId);
541 this.stateDb.markDimensionVisited(character.character_id, dimensionId);
542 this.syncCharacterConditionAccess(character.character_id ?? row.character_id);
540 this.#queueReplication(replicationSpawn(this.directory.get(view.entityId) ?? view));
543 this.#queueReplication(replicationSpawn(this.directory.get(view.entityId) ?? view));
541 this.#recalculateActivation(this.now);
544 this.#recalculateActivation(this.now);
542 this.#syncGhosts();
545 this.#syncGhosts();
543 this.courier?.onCharacterEnteredWorld(character.character_id, tileX, tileY);
546 this.courier?.onCharacterEnteredWorld(character.character_id, tileX, tileY);
544 this.quests?.ensureInitialQuests?.(character.character_id ?? row.character_id);
547 this.quests?.ensureInitialQuests?.(character.character_id ?? row.character_id);
548 this.syncCharacterConditionAccess(character.character_id ?? row.character_id);
545 return entityId;
549 return entityId;
546 }
550 }
547
551
@@ -587,6 +591,23 @@ export class Simulation
587 return event;
591 return event;
588 }
592 }
589
593
594 /** Push quest / dialogue / visited-dim snapshot onto the character's worker ECS. */
595 syncCharacterConditionAccess (characterId)
596 {
597 const id = characterId | 0;
598 if (!id)
599 { return; }
600 const entityId = this.characterEntities.get(id);
601 const record = entityId ? this.directory.get(entityId) : null;
602 if (!record)
603 { return; }
604 this.workers[record.workerId]?.call({
605 type: WorkerMessage.applyConditionAccess,
606 entityId,
607 conditionAccess: buildConditionAccessSnapshot(this.stateDb, id)
608 });
609 }
610
590 #attachSkullToRecord (entityId, characterId)
611 #attachSkullToRecord (entityId, characterId)
591 {
612 {
592 const record = this.directory.get(entityId);
613 const record = this.directory.get(entityId);
@@ -1900,12 +1921,15 @@ export class Simulation
1900 {
1921 {
1901 const out = [];
1922 const out = [];
1902 let needSnapshot = false;
1923 let needSnapshot = false;
1924 const syncAccessIds = new Set();
1903 for (const event of events ?? [])
1925 for (const event of events ?? [])
1904 {
1926 {
1905 const cid = event.characterId ?? characterId;
1927 const cid = event.characterId ?? characterId;
1906 const sid = sessionId ?? this.#sessionIdForCharacter(cid);
1928 const sid = sessionId ?? this.#sessionIdForCharacter(cid);
1907 if (event.type === "dialogueStep")
1929 if (event.type === "dialogueStep")
1908 {
1930 {
1931 if (cid != null)
1932 { syncAccessIds.add(cid | 0); }
1909 out.push({
1933 out.push({
1910 type: "dialogue-step",
1934 type: "dialogue-step",
1911 sessionId: sid,
1935 sessionId: sid,
@@ -1919,6 +1943,8 @@ export class Simulation
1919 }
1943 }
1920 else if (event.type === "dialogueChoices")
1944 else if (event.type === "dialogueChoices")
1921 {
1945 {
1946 if (cid != null)
1947 { syncAccessIds.add(cid | 0); }
1922 out.push({
1948 out.push({
1923 type: "dialogue-choices",
1949 type: "dialogue-choices",
1924 sessionId: sid,
1950 sessionId: sid,
@@ -1985,7 +2011,10 @@ export class Simulation
1985 characterId,
2011 characterId,
1986 ...snap
2012 ...snap
1987 });
2013 });
2014 syncAccessIds.add(characterId | 0);
1988 }
2015 }
2016 for (const id of syncAccessIds)
2017 { this.syncCharacterConditionAccess(id); }
1989 return out;
2018 return out;
1990 }
2019 }
1991
2020
@@ -2351,6 +2380,7 @@ export class Simulation
2351 targetDimensionId
2380 targetDimensionId
2352 );
2381 );
2353 this.stateDb.markDimensionVisited(characterId, targetDimensionId);
2382 this.stateDb.markDimensionVisited(characterId, targetDimensionId);
2383 this.syncCharacterConditionAccess(characterId);
2354 this.#recalculateActivation(this.now);
2384 this.#recalculateActivation(this.now);
2355 this.#syncGhosts();
2385 this.#syncGhosts();
2356 const dimRecord = this.getDimensionRecord(targetDimensionId);
2386 const dimRecord = this.getDimensionRecord(targetDimensionId);
server/src/simulation/workerWorld.js +82 −5
@@ -43,7 +43,14 @@ import {
43 43 cancelJewelryTeleport
44 44 } from "../equipment/jewelryTeleport.js";
45 45 import { publicSpellsView } from "../../../shared/spells/state.js";
46 import { maybeOpenDoorOnApproach, stepDoors, entityCanOpenDoors } from "../doors/service.js";
46 import { maybeOpenDoorOnApproach, stepDoors, entityCanOpenDoors, isDoorBlock } from "../doors/service.js";
47 import {
48 entityDoorRequirementsAllow
49 } from "../doors/conditionContext.js";
50 import {
51 doorBlockedMessage,
52 doorHasRequirements
53 } from "../../../shared/world/doorRequirements.js";
47 54 import {
48 55 handleGatherCommand,
49 56 stepGather,
@@ -181,6 +188,8 @@ export class WorkerWorld
181 188 return this.#applyAppearance(message.entityId, message.appearance);
182 189 case WorkerMessage.applySkullValue:
183 190 return this.#applySkullValue(message.entityId, message.skullValue);
191 case WorkerMessage.applyConditionAccess:
192 return this.#applyConditionAccess(message.entityId, message.conditionAccess);
184 193 case WorkerMessage.engageTarget:
185 194 return this.#engageTargetMessage(message);
186 195 case WorkerMessage.setSpellAutoCast:
@@ -894,6 +903,62 @@ export class WorkerWorld
894 903 return { ok: true, skullValue: character.skullValue };
895 904 }
896 905
906 #applyConditionAccess (entityId, conditionAccess)
907 {
908 const handle = this.ecs.handleOf(entityId);
909 if (handle == null)
910 { return null; }
911 if (!this.ecs.get(handle, Component.character))
912 { return null; }
913 const next = conditionAccess && typeof conditionAccess === "object"
914 ? structuredClone(conditionAccess)
915 : {
916 questStates: {},
917 questProgress: {},
918 dialogueHeard: [],
919 dialogueTriggers: [],
920 visitedDimensions: []
921 };
922 if (this.ecs.has(handle, Component.conditionAccess))
923 { Object.assign(this.ecs.get(handle, Component.conditionAccess), next); }
924 else
925 { this.ecs.add(handle, Component.conditionAccess, next); }
926 return { ok: true };
927 }
928
929 /**
930 * Toast when a player walks into a door they fail requirements for.
931 * Debounced per door tile so movement ticks do not spam.
932 */
933 #doorRequirementBlockedToast (entityId, tileX, tileY, now = Date.now())
934 {
935 const handle = this.ecs.handleOf(entityId);
936 if (handle == null)
937 { return null; }
938 const character = this.ecs.get(handle, Component.character);
939 if (!character?.characterId)
940 { return null; }
941 const dimensionId = this.#entityDimensionId(entityId);
942 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
943 const block = data?.blocks?.[tileIndex(tileToLocal(tileX), tileToLocal(tileY))];
944 if (!isDoorBlock(block) || !doorHasRequirements(block))
945 { return null; }
946 if (entityDoorRequirementsAllow(this, entityId, tileX, tileY))
947 { return null; }
948 if (!this.doorBlockToastAt)
949 { this.doorBlockToastAt = new Map(); }
950 const key = `${character.characterId}|${tileKey(tileX, tileY, dimensionId)}`;
951 const last = this.doorBlockToastAt.get(key);
952 if (last != null && now - last < 2500)
953 { return null; }
954 this.doorBlockToastAt.set(key, now);
955 return {
956 type: "toast",
957 characterId: character.characterId,
958 message: doorBlockedMessage(block)
959 };
960 }
961
897 962 #updateFlight (entityId, flightPatch, now = Date.now())
898 963 {
899 964 const handle = this.ecs.handleOf(entityId);
@@ -1572,6 +1637,13 @@ export class WorkerWorld
1572 1637
1573 1638 if (!this.walkableFor(entityId, next.x, next.y))
1574 1639 {
1640 const blockedToast = this.#doorRequirementBlockedToast(entityId, next.x, next.y, now);
1641 if (blockedToast)
1642 {
1643 events.push(blockedToast);
1644 path.tiles = [];
1645 continue;
1646 }
1575 1647 const combat = this.ecs.get(handle, Component.combat);
1576 1648 if (combat?.targetEntityId != null)
1577 1649 {
@@ -2250,7 +2322,8 @@ export class WorkerWorld
2250 2322 }
2251 2323 // Entities pass through each other; only terrain / closed chunks block movement.
2252 2324 return this.isEnterable(tileX, tileY, dim, {
2253 canOpenDoors: entityCanOpenDoors(this.ecs, entityId)
2325 canOpenDoors: entityCanOpenDoors(this.ecs, entityId),
2326 requirementsAllow: entityDoorRequirementsAllow(this, entityId, tileX, tileY)
2254 2327 });
2255 2328 }
2256 2329
@@ -2333,7 +2406,8 @@ export class WorkerWorld
2333 2406 {
2334 2407 const dim = this.#entityDimensionId(entityId);
2335 2408 if (!this.isEnterable(tileX, tileY, dim, {
2336 canOpenDoors: entityCanOpenDoors(this.ecs, entityId)
2409 canOpenDoors: entityCanOpenDoors(this.ecs, entityId),
2410 requirementsAllow: entityDoorRequirementsAllow(this, entityId, tileX, tileY)
2337 2411 }))
2338 2412 { return false; }
2339 2413 return !this.#hasOtherOccupant(entityId, tileX, tileY, dim);
@@ -2362,12 +2436,15 @@ export class WorkerWorld
2362 2436 return createEmptyChunkData(this.settings.defaultGroundTypeId);
2363 2437 }
2364 2438
2365 isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID, { canOpenDoors = false } = {})
2439 isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID, { canOpenDoors = false, requirementsAllow = true } = {})
2366 2440 {
2367 2441 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
2368 2442 if (!data.open)
2369 2443 { return false; }
2370 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY), { canOpenDoors });
2444 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY), {
2445 canOpenDoors,
2446 requirementsAllow
2447 });
2371 2448 }
2372 2449
2373 2450 isClearForRangedAttack (tileX, tileY, dimensionId = OVERWORLD_ID)
@@ -43,7 +43,14 @@ import {
43 cancelJewelryTeleport
43 cancelJewelryTeleport
44} from "../equipment/jewelryTeleport.js";
44} from "../equipment/jewelryTeleport.js";
45import { publicSpellsView } from "../../../shared/spells/state.js";
45import { publicSpellsView } from "../../../shared/spells/state.js";
46import { maybeOpenDoorOnApproach, stepDoors, entityCanOpenDoors } from "../doors/service.js";
46import { maybeOpenDoorOnApproach, stepDoors, entityCanOpenDoors, isDoorBlock } from "../doors/service.js";
47import {
48 entityDoorRequirementsAllow
49} from "../doors/conditionContext.js";
50import {
51 doorBlockedMessage,
52 doorHasRequirements
53} from "../../../shared/world/doorRequirements.js";
47import {
54import {
48 handleGatherCommand,
55 handleGatherCommand,
49 stepGather,
56 stepGather,
@@ -181,6 +188,8 @@ export class WorkerWorld
181 return this.#applyAppearance(message.entityId, message.appearance);
188 return this.#applyAppearance(message.entityId, message.appearance);
182 case WorkerMessage.applySkullValue:
189 case WorkerMessage.applySkullValue:
183 return this.#applySkullValue(message.entityId, message.skullValue);
190 return this.#applySkullValue(message.entityId, message.skullValue);
191 case WorkerMessage.applyConditionAccess:
192 return this.#applyConditionAccess(message.entityId, message.conditionAccess);
184 case WorkerMessage.engageTarget:
193 case WorkerMessage.engageTarget:
185 return this.#engageTargetMessage(message);
194 return this.#engageTargetMessage(message);
186 case WorkerMessage.setSpellAutoCast:
195 case WorkerMessage.setSpellAutoCast:
@@ -894,6 +903,62 @@ export class WorkerWorld
894 return { ok: true, skullValue: character.skullValue };
903 return { ok: true, skullValue: character.skullValue };
895 }
904 }
896
905
906 #applyConditionAccess (entityId, conditionAccess)
907 {
908 const handle = this.ecs.handleOf(entityId);
909 if (handle == null)
910 { return null; }
911 if (!this.ecs.get(handle, Component.character))
912 { return null; }
913 const next = conditionAccess && typeof conditionAccess === "object"
914 ? structuredClone(conditionAccess)
915 : {
916 questStates: {},
917 questProgress: {},
918 dialogueHeard: [],
919 dialogueTriggers: [],
920 visitedDimensions: []
921 };
922 if (this.ecs.has(handle, Component.conditionAccess))
923 { Object.assign(this.ecs.get(handle, Component.conditionAccess), next); }
924 else
925 { this.ecs.add(handle, Component.conditionAccess, next); }
926 return { ok: true };
927 }
928
929 /**
930 * Toast when a player walks into a door they fail requirements for.
931 * Debounced per door tile so movement ticks do not spam.
932 */
933 #doorRequirementBlockedToast (entityId, tileX, tileY, now = Date.now())
934 {
935 const handle = this.ecs.handleOf(entityId);
936 if (handle == null)
937 { return null; }
938 const character = this.ecs.get(handle, Component.character);
939 if (!character?.characterId)
940 { return null; }
941 const dimensionId = this.#entityDimensionId(entityId);
942 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
943 const block = data?.blocks?.[tileIndex(tileToLocal(tileX), tileToLocal(tileY))];
944 if (!isDoorBlock(block) || !doorHasRequirements(block))
945 { return null; }
946 if (entityDoorRequirementsAllow(this, entityId, tileX, tileY))
947 { return null; }
948 if (!this.doorBlockToastAt)
949 { this.doorBlockToastAt = new Map(); }
950 const key = `${character.characterId}|${tileKey(tileX, tileY, dimensionId)}`;
951 const last = this.doorBlockToastAt.get(key);
952 if (last != null && now - last < 2500)
953 { return null; }
954 this.doorBlockToastAt.set(key, now);
955 return {
956 type: "toast",
957 characterId: character.characterId,
958 message: doorBlockedMessage(block)
959 };
960 }
961
897 #updateFlight (entityId, flightPatch, now = Date.now())
962 #updateFlight (entityId, flightPatch, now = Date.now())
898 {
963 {
899 const handle = this.ecs.handleOf(entityId);
964 const handle = this.ecs.handleOf(entityId);
@@ -1572,6 +1637,13 @@ export class WorkerWorld
1572
1637
1573 if (!this.walkableFor(entityId, next.x, next.y))
1638 if (!this.walkableFor(entityId, next.x, next.y))
1574 {
1639 {
1640 const blockedToast = this.#doorRequirementBlockedToast(entityId, next.x, next.y, now);
1641 if (blockedToast)
1642 {
1643 events.push(blockedToast);
1644 path.tiles = [];
1645 continue;
1646 }
1575 const combat = this.ecs.get(handle, Component.combat);
1647 const combat = this.ecs.get(handle, Component.combat);
1576 if (combat?.targetEntityId != null)
1648 if (combat?.targetEntityId != null)
1577 {
1649 {
@@ -2250,7 +2322,8 @@ export class WorkerWorld
2250 }
2322 }
2251 // Entities pass through each other; only terrain / closed chunks block movement.
2323 // Entities pass through each other; only terrain / closed chunks block movement.
2252 return this.isEnterable(tileX, tileY, dim, {
2324 return this.isEnterable(tileX, tileY, dim, {
2253 canOpenDoors: entityCanOpenDoors(this.ecs, entityId)
2325 canOpenDoors: entityCanOpenDoors(this.ecs, entityId),
2326 requirementsAllow: entityDoorRequirementsAllow(this, entityId, tileX, tileY)
2254 });
2327 });
2255 }
2328 }
2256
2329
@@ -2333,7 +2406,8 @@ export class WorkerWorld
2333 {
2406 {
2334 const dim = this.#entityDimensionId(entityId);
2407 const dim = this.#entityDimensionId(entityId);
2335 if (!this.isEnterable(tileX, tileY, dim, {
2408 if (!this.isEnterable(tileX, tileY, dim, {
2336 canOpenDoors: entityCanOpenDoors(this.ecs, entityId)
2409 canOpenDoors: entityCanOpenDoors(this.ecs, entityId),
2410 requirementsAllow: entityDoorRequirementsAllow(this, entityId, tileX, tileY)
2337 }))
2411 }))
2338 { return false; }
2412 { return false; }
2339 return !this.#hasOtherOccupant(entityId, tileX, tileY, dim);
2413 return !this.#hasOtherOccupant(entityId, tileX, tileY, dim);
@@ -2362,12 +2436,15 @@ export class WorkerWorld
2362 return createEmptyChunkData(this.settings.defaultGroundTypeId);
2436 return createEmptyChunkData(this.settings.defaultGroundTypeId);
2363 }
2437 }
2364
2438
2365 isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID, { canOpenDoors = false } = {})
2439 isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID, { canOpenDoors = false, requirementsAllow = true } = {})
2366 {
2440 {
2367 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
2441 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
2368 if (!data.open)
2442 if (!data.open)
2369 { return false; }
2443 { return false; }
2370 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY), { canOpenDoors });
2444 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY), {
2445 canOpenDoors,
2446 requirementsAllow
2447 });
2371 }
2448 }
2372
2449
2373 isClearForRangedAttack (tileX, tileY, dimensionId = OVERWORLD_ID)
2450 isClearForRangedAttack (tileX, tileY, dimensionId = OVERWORLD_ID)
server/src/world/chunkData.js +2 −2
@@ -172,7 +172,7 @@ export function setBlock (data, localX, localY, block)
172 172 data.blocks[tileIndex(localX, localY)] = normalizeBlock(block);
173 173 }
174 174
175 export function isChunkTilePassable (data, localX, localY, { canOpenDoors = false } = {})
175 export function isChunkTilePassable (data, localX, localY, { canOpenDoors = false, requirementsAllow = true } = {})
176 176 {
177 177 const index = tileIndex(localX, localY);
178 178 const ground = normalizeGround(data.grounds[index]);
@@ -182,7 +182,7 @@ export function isChunkTilePassable (data, localX, localY, { canOpenDoors = fals
182 182 if (!block)
183 183 { return true; }
184 184 if ((block.typeId | 0) === BlockType.door)
185 { return isDoorTraversable(block, { canOpenDoors }); }
185 { return isDoorTraversable(block, { canOpenDoors, requirementsAllow }); }
186 186 return isBlockPassable(block.typeId, block.state);
187 187 }
188 188
@@ -172,7 +172,7 @@ export function setBlock (data, localX, localY, block)
172 data.blocks[tileIndex(localX, localY)] = normalizeBlock(block);
172 data.blocks[tileIndex(localX, localY)] = normalizeBlock(block);
173}
173}
174
174
175export function isChunkTilePassable (data, localX, localY, { canOpenDoors = false } = {})
175export function isChunkTilePassable (data, localX, localY, { canOpenDoors = false, requirementsAllow = true } = {})
176{
176{
177 const index = tileIndex(localX, localY);
177 const index = tileIndex(localX, localY);
178 const ground = normalizeGround(data.grounds[index]);
178 const ground = normalizeGround(data.grounds[index]);
@@ -182,7 +182,7 @@ export function isChunkTilePassable (data, localX, localY, { canOpenDoors = fals
182 if (!block)
182 if (!block)
183 { return true; }
183 { return true; }
184 if ((block.typeId | 0) === BlockType.door)
184 if ((block.typeId | 0) === BlockType.door)
185 { return isDoorTraversable(block, { canOpenDoors }); }
185 { return isDoorTraversable(block, { canOpenDoors, requirementsAllow }); }
186 return isBlockPassable(block.typeId, block.state);
186 return isBlockPassable(block.typeId, block.state);
187}
187}
188
188
server/tests/doors.test.js +124 −2
@@ -5,6 +5,8 @@ import { join } from "node:path";
5 5 import { BlockType, isBlockPassable, isChunkAtlasBakedBlock, blockLightOcclusionForBlock, blockBlocksRangedAttacks, LightOcclusion } from "../../shared/definitions/tiles.js";
6 6 import { WOOD_TIER_ORDER } from "../../shared/definitions/materialTiers.js";
7 7 import { MobId } from "../../shared/definitions/mobs.js";
8 import { ItemId } from "../../shared/definitions/items.js";
9 import { ConditionKind } from "../../shared/quests/conditions.js";
8 10 import {
9 11 composeDoorState,
10 12 doorSortSubOrder,
@@ -13,6 +15,11 @@ import {
13 15 listAllDoorStates,
14 16 parseDoorState
15 17 } from "../../shared/world/doors.js";
18 import {
19 doorHasRequirements,
20 doorRequirementsMet,
21 normalizeDoorConfig
22 } from "../../shared/world/doorRequirements.js";
16 23 import { buildSpriteCatalog } from "../src/assets/spriteCatalog.js";
17 24 import { Component } from "../src/ecs/components.js";
18 25 import { mobComponents } from "../src/simulation/spawners.js";
@@ -32,7 +39,7 @@ function workerOf (simulation, entityId)
32 39 return simulation.workers[record.workerId];
33 40 }
34 41
35 function placeDoor (worker, tileX, tileY, state)
42 function placeDoor (worker, tileX, tileY, state, config = null)
36 43 {
37 44 const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
38 45 const localX = ((tileX % 16) + 16) % 16;
@@ -40,7 +47,7 @@ function placeDoor (worker, tileX, tileY, state)
40 47 data.blocks[localY * 16 + localX] = {
41 48 typeId: BlockType.door,
42 49 state,
43 config: null
50 config
44 51 };
45 52 }
46 53
@@ -249,3 +256,118 @@ test("resting open (≈ W-closed) flips to closed for passage, then restores", (
249 256 finally
250 257 { harness.close(); }
251 258 });
259
260 test("door requirements normalize and fail closed without context", () =>
261 {
262 assert.equal(doorHasRequirements({ config: null }), false);
263 const gated = {
264 config: normalizeDoorConfig({
265 when: { all: [{ condition: { kind: ConditionKind.hasItem, itemId: ItemId.apple, quantity: 1 } }] },
266 blockedMessage: "Need an apple."
267 })
268 };
269 assert.equal(doorHasRequirements(gated), true);
270 assert.equal(doorRequirementsMet(gated, null), false);
271 assert.equal(isDoorTraversable(gated, { canOpenDoors: true, requirementsAllow: false }), false);
272 assert.equal(isDoorTraversable({
273 state: "pine-s-closed",
274 config: { restingState: "pine-s-open", when: gated.config.when }
275 }, { canOpenDoors: false, requirementsAllow: false }), false);
276 });
277
278 test("gated doors stay impassable for players who fail requirements even when held open", () =>
279 {
280 const harness = makeSimulation({ workerCount: 1 });
281 try
282 {
283 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
284 const entityId = harness.simulation.spawnCharacter(1, character);
285 harness.simulation.step();
286 const worker = workerOf(harness.simulation, entityId);
287 const gate = normalizeDoorConfig({
288 when: { all: [{ condition: { kind: ConditionKind.hasItem, itemId: ItemId.bones, quantity: 1 } }] },
289 blockedMessage: "The door ignores you."
290 });
291 placeDoor(worker, 9, 8, "pine-s-closed", gate);
292
293 assert.equal(worker.world.walkableFor(entityId, 9, 8), false);
294 assert.equal(maybeOpenDoorOnApproach(worker.world, entityId, 9, 8), null);
295
296 /** Another player holds the door open — still blocked for the gated character. */
297 placeDoor(worker, 9, 8, "pine-s-open", {
298 ...gate,
299 restingState: "pine-s-closed"
300 });
301 assert.equal(worker.world.walkableFor(entityId, 9, 8), false);
302
303 const bag = harness.simulation.bagOf(entityId);
304 bag.inventory[0] = { itemId: ItemId.bones, quantity: 1 };
305 harness.simulation.applyBag(entityId, bag);
306 assert.equal(worker.world.walkableFor(entityId, 9, 8), true);
307 }
308 finally
309 { harness.close(); }
310 });
311
312 test("walking into a gated door emits a blocked toast", () =>
313 {
314 const harness = makeSimulation({ workerCount: 1 });
315 try
316 {
317 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
318 const entityId = harness.simulation.spawnCharacter(1, character);
319 harness.simulation.step();
320 const worker = workerOf(harness.simulation, entityId);
321 const gate = normalizeDoorConfig({
322 when: { all: [{ condition: { kind: ConditionKind.hasItem, itemId: ItemId.bones, quantity: 1 } }] },
323 blockedMessage: "Members only."
324 });
325 placeDoor(worker, 9, 8, "pine-s-closed", gate);
326
327 const handle = worker.world.ecs.handleOf(entityId);
328 const path = worker.world.ecs.get(handle, Component.path);
329 path.tiles = [{ x: 9, y: 8 }, { x: 10, y: 8 }];
330
331 let toast = null;
332 for (let i = 0; i < walkTicks(2); i++)
333 {
334 harness.advance(50);
335 const result = harness.simulation.step();
336 toast ??= (result.events ?? []).find((e) => e.type === "toast" && e.message === "Members only.");
337 }
338 assert.ok(toast);
339 assert.equal(toast.characterId, character.character_id);
340 const position = worker.world.ecs.get(handle, Component.position);
341 assert.equal(position.tileX, 8);
342 assert.equal(position.tileY, 8);
343 }
344 finally
345 { harness.close(); }
346 });
347
348 test("quest-gated doors unlock after conditionAccess sync", () =>
349 {
350 const harness = makeSimulation({ workerCount: 1 });
351 try
352 {
353 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
354 const entityId = harness.simulation.spawnCharacter(1, character);
355 harness.simulation.step();
356 const worker = workerOf(harness.simulation, entityId);
357 placeDoor(worker, 9, 8, "oak-n-closed", normalizeDoorConfig({
358 when: {
359 all: [{
360 condition: { kind: ConditionKind.questState, questId: "door-key-quest", state: "completed" }
361 }]
362 },
363 blockedMessage: "Finish the quest first."
364 }));
365 assert.equal(worker.world.walkableFor(entityId, 9, 8), false);
366
367 harness.stateDb.saveQuestState(character.character_id, "door-key-quest", "completed", {}, Date.now(), Date.now());
368 harness.simulation.syncCharacterConditionAccess(character.character_id);
369 assert.equal(worker.world.walkableFor(entityId, 9, 8), true);
370 }
371 finally
372 { harness.close(); }
373 });
@@ -5,6 +5,8 @@ import { join } from "node:path";
5import { BlockType, isBlockPassable, isChunkAtlasBakedBlock, blockLightOcclusionForBlock, blockBlocksRangedAttacks, LightOcclusion } from "../../shared/definitions/tiles.js";
5import { BlockType, isBlockPassable, isChunkAtlasBakedBlock, blockLightOcclusionForBlock, blockBlocksRangedAttacks, LightOcclusion } from "../../shared/definitions/tiles.js";
6import { WOOD_TIER_ORDER } from "../../shared/definitions/materialTiers.js";
6import { WOOD_TIER_ORDER } from "../../shared/definitions/materialTiers.js";
7import { MobId } from "../../shared/definitions/mobs.js";
7import { MobId } from "../../shared/definitions/mobs.js";
8import { ItemId } from "../../shared/definitions/items.js";
9import { ConditionKind } from "../../shared/quests/conditions.js";
8import {
10import {
9 composeDoorState,
11 composeDoorState,
10 doorSortSubOrder,
12 doorSortSubOrder,
@@ -13,6 +15,11 @@ import {
13 listAllDoorStates,
15 listAllDoorStates,
14 parseDoorState
16 parseDoorState
15} from "../../shared/world/doors.js";
17} from "../../shared/world/doors.js";
18import {
19 doorHasRequirements,
20 doorRequirementsMet,
21 normalizeDoorConfig
22} from "../../shared/world/doorRequirements.js";
16import { buildSpriteCatalog } from "../src/assets/spriteCatalog.js";
23import { buildSpriteCatalog } from "../src/assets/spriteCatalog.js";
17import { Component } from "../src/ecs/components.js";
24import { Component } from "../src/ecs/components.js";
18import { mobComponents } from "../src/simulation/spawners.js";
25import { mobComponents } from "../src/simulation/spawners.js";
@@ -32,7 +39,7 @@ function workerOf (simulation, entityId)
32 return simulation.workers[record.workerId];
39 return simulation.workers[record.workerId];
33}
40}
34
41
35function placeDoor (worker, tileX, tileY, state)
42function placeDoor (worker, tileX, tileY, state, config = null)
36{
43{
37 const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
44 const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
38 const localX = ((tileX % 16) + 16) % 16;
45 const localX = ((tileX % 16) + 16) % 16;
@@ -40,7 +47,7 @@ function placeDoor (worker, tileX, tileY, state)
40 data.blocks[localY * 16 + localX] = {
47 data.blocks[localY * 16 + localX] = {
41 typeId: BlockType.door,
48 typeId: BlockType.door,
42 state,
49 state,
43 config: null
50 config
44 };
51 };
45}
52}
46
53
@@ -249,3 +256,118 @@ test("resting open (≈ W-closed) flips to closed for passage, then restores", (
249 finally
256 finally
250 { harness.close(); }
257 { harness.close(); }
251});
258});
259
260test("door requirements normalize and fail closed without context", () =>
261{
262 assert.equal(doorHasRequirements({ config: null }), false);
263 const gated = {
264 config: normalizeDoorConfig({
265 when: { all: [{ condition: { kind: ConditionKind.hasItem, itemId: ItemId.apple, quantity: 1 } }] },
266 blockedMessage: "Need an apple."
267 })
268 };
269 assert.equal(doorHasRequirements(gated), true);
270 assert.equal(doorRequirementsMet(gated, null), false);
271 assert.equal(isDoorTraversable(gated, { canOpenDoors: true, requirementsAllow: false }), false);
272 assert.equal(isDoorTraversable({
273 state: "pine-s-closed",
274 config: { restingState: "pine-s-open", when: gated.config.when }
275 }, { canOpenDoors: false, requirementsAllow: false }), false);
276});
277
278test("gated doors stay impassable for players who fail requirements even when held open", () =>
279{
280 const harness = makeSimulation({ workerCount: 1 });
281 try
282 {
283 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
284 const entityId = harness.simulation.spawnCharacter(1, character);
285 harness.simulation.step();
286 const worker = workerOf(harness.simulation, entityId);
287 const gate = normalizeDoorConfig({
288 when: { all: [{ condition: { kind: ConditionKind.hasItem, itemId: ItemId.bones, quantity: 1 } }] },
289 blockedMessage: "The door ignores you."
290 });
291 placeDoor(worker, 9, 8, "pine-s-closed", gate);
292
293 assert.equal(worker.world.walkableFor(entityId, 9, 8), false);
294 assert.equal(maybeOpenDoorOnApproach(worker.world, entityId, 9, 8), null);
295
296 /** Another player holds the door open — still blocked for the gated character. */
297 placeDoor(worker, 9, 8, "pine-s-open", {
298 ...gate,
299 restingState: "pine-s-closed"
300 });
301 assert.equal(worker.world.walkableFor(entityId, 9, 8), false);
302
303 const bag = harness.simulation.bagOf(entityId);
304 bag.inventory[0] = { itemId: ItemId.bones, quantity: 1 };
305 harness.simulation.applyBag(entityId, bag);
306 assert.equal(worker.world.walkableFor(entityId, 9, 8), true);
307 }
308 finally
309 { harness.close(); }
310});
311
312test("walking into a gated door emits a blocked toast", () =>
313{
314 const harness = makeSimulation({ workerCount: 1 });
315 try
316 {
317 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
318 const entityId = harness.simulation.spawnCharacter(1, character);
319 harness.simulation.step();
320 const worker = workerOf(harness.simulation, entityId);
321 const gate = normalizeDoorConfig({
322 when: { all: [{ condition: { kind: ConditionKind.hasItem, itemId: ItemId.bones, quantity: 1 } }] },
323 blockedMessage: "Members only."
324 });
325 placeDoor(worker, 9, 8, "pine-s-closed", gate);
326
327 const handle = worker.world.ecs.handleOf(entityId);
328 const path = worker.world.ecs.get(handle, Component.path);
329 path.tiles = [{ x: 9, y: 8 }, { x: 10, y: 8 }];
330
331 let toast = null;
332 for (let i = 0; i < walkTicks(2); i++)
333 {
334 harness.advance(50);
335 const result = harness.simulation.step();
336 toast ??= (result.events ?? []).find((e) => e.type === "toast" && e.message === "Members only.");
337 }
338 assert.ok(toast);
339 assert.equal(toast.characterId, character.character_id);
340 const position = worker.world.ecs.get(handle, Component.position);
341 assert.equal(position.tileX, 8);
342 assert.equal(position.tileY, 8);
343 }
344 finally
345 { harness.close(); }
346});
347
348test("quest-gated doors unlock after conditionAccess sync", () =>
349{
350 const harness = makeSimulation({ workerCount: 1 });
351 try
352 {
353 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
354 const entityId = harness.simulation.spawnCharacter(1, character);
355 harness.simulation.step();
356 const worker = workerOf(harness.simulation, entityId);
357 placeDoor(worker, 9, 8, "oak-n-closed", normalizeDoorConfig({
358 when: {
359 all: [{
360 condition: { kind: ConditionKind.questState, questId: "door-key-quest", state: "completed" }
361 }]
362 },
363 blockedMessage: "Finish the quest first."
364 }));
365 assert.equal(worker.world.walkableFor(entityId, 9, 8), false);
366
367 harness.stateDb.saveQuestState(character.character_id, "door-key-quest", "completed", {}, Date.now(), Date.now());
368 harness.simulation.syncCharacterConditionAccess(character.character_id);
369 assert.equal(worker.world.walkableFor(entityId, 9, 8), true);
370 }
371 finally
372 { harness.close(); }
373});
shared/world/doorRequirements.js added +66 −0
@@ -0,0 +1,66 @@
1 /**
2 * Authored wooden-door passage gates (ConditionSet + toast).
3 * Empty requirements = unrestricted. Players who fail may not pass even if the door is held open.
4 */
5 import { normalizeConditionSet, emptyConditionSet, evaluateConditionSet } from "../quests/conditions.js";
6
7 export const DEFAULT_DOOR_BLOCKED_MESSAGE = "You cannot go through here.";
8
9 /**
10 * Preserve runtime restingState while normalizing authored gate fields.
11 * @param {object | null | undefined} raw
12 */
13 export function normalizeDoorConfig (raw)
14 {
15 if (!raw || typeof raw !== "object")
16 { return null; }
17 const when = normalizeConditionSet(raw.when ?? raw.requirements);
18 const blockedMessage = String(raw.blockedMessage ?? raw.denyMessage ?? "")
19 .trim()
20 .slice(0, 200);
21 const restingState = typeof raw.restingState === "string" && raw.restingState
22 ? raw.restingState
23 : undefined;
24 const hasWhen = (when.all?.length ?? 0) > 0;
25 const hasMessage = blockedMessage.length > 0;
26 if (!hasWhen && !hasMessage && restingState == null)
27 { return null; }
28 const out = {};
29 if (restingState != null)
30 { out.restingState = restingState; }
31 if (hasWhen)
32 { out.when = when; }
33 if (hasMessage)
34 { out.blockedMessage = blockedMessage; }
35 return Object.keys(out).length ? out : null;
36 }
37
38 export function doorRequirementSet (block)
39 {
40 const when = block?.config?.when ?? block?.config?.requirements;
41 return normalizeConditionSet(when ?? emptyConditionSet());
42 }
43
44 export function doorHasRequirements (block)
45 {
46 return (doorRequirementSet(block).all?.length ?? 0) > 0;
47 }
48
49 export function doorBlockedMessage (block)
50 {
51 const text = String(block?.config?.blockedMessage ?? block?.config?.denyMessage ?? "").trim();
52 return text || DEFAULT_DOOR_BLOCKED_MESSAGE;
53 }
54
55 /**
56 * @param {object} block
57 * @param {object | null} ctx — evaluateConditionSet snapshot; null/undefined fails closed when gated
58 */
59 export function doorRequirementsMet (block, ctx)
60 {
61 if (!doorHasRequirements(block))
62 { return true; }
63 if (!ctx)
64 { return false; }
65 return evaluateConditionSet(doorRequirementSet(block), ctx);
66 }
@@ -0,0 +1,66 @@
1/**
2 * Authored wooden-door passage gates (ConditionSet + toast).
3 * Empty requirements = unrestricted. Players who fail may not pass even if the door is held open.
4 */
5import { normalizeConditionSet, emptyConditionSet, evaluateConditionSet } from "../quests/conditions.js";
6
7export const DEFAULT_DOOR_BLOCKED_MESSAGE = "You cannot go through here.";
8
9/**
10 * Preserve runtime restingState while normalizing authored gate fields.
11 * @param {object | null | undefined} raw
12 */
13export function normalizeDoorConfig (raw)
14{
15 if (!raw || typeof raw !== "object")
16 { return null; }
17 const when = normalizeConditionSet(raw.when ?? raw.requirements);
18 const blockedMessage = String(raw.blockedMessage ?? raw.denyMessage ?? "")
19 .trim()
20 .slice(0, 200);
21 const restingState = typeof raw.restingState === "string" && raw.restingState
22 ? raw.restingState
23 : undefined;
24 const hasWhen = (when.all?.length ?? 0) > 0;
25 const hasMessage = blockedMessage.length > 0;
26 if (!hasWhen && !hasMessage && restingState == null)
27 { return null; }
28 const out = {};
29 if (restingState != null)
30 { out.restingState = restingState; }
31 if (hasWhen)
32 { out.when = when; }
33 if (hasMessage)
34 { out.blockedMessage = blockedMessage; }
35 return Object.keys(out).length ? out : null;
36}
37
38export function doorRequirementSet (block)
39{
40 const when = block?.config?.when ?? block?.config?.requirements;
41 return normalizeConditionSet(when ?? emptyConditionSet());
42}
43
44export function doorHasRequirements (block)
45{
46 return (doorRequirementSet(block).all?.length ?? 0) > 0;
47}
48
49export function doorBlockedMessage (block)
50{
51 const text = String(block?.config?.blockedMessage ?? block?.config?.denyMessage ?? "").trim();
52 return text || DEFAULT_DOOR_BLOCKED_MESSAGE;
53}
54
55/**
56 * @param {object} block
57 * @param {object | null} ctx — evaluateConditionSet snapshot; null/undefined fails closed when gated
58 */
59export function doorRequirementsMet (block, ctx)
60{
61 if (!doorHasRequirements(block))
62 { return true; }
63 if (!ctx)
64 { return false; }
65 return evaluateConditionSet(doorRequirementSet(block), ctx);
66}
shared/world/doors.js +4 −1
@@ -119,9 +119,12 @@ export function doorSortSubOrder (state, defaultSubOrder = 3)
119 119 /**
120 120 * Passability: traversable when held open for passage (flipped from resting),
121 121 * or when the mover can open doors (they flip on approach).
122 * Optional `requirementsAllow: false` blocks everyone (including held-open passage).
122 123 */
123 export function isDoorTraversable (block, { canOpenDoors = false } = {})
124 export function isDoorTraversable (block, { canOpenDoors = false, requirementsAllow = true } = {})
124 125 {
126 if (!requirementsAllow)
127 { return false; }
125 128 if (isDoorPassageOpen(block))
126 129 { return true; }
127 130 return !!canOpenDoors;
@@ -119,9 +119,12 @@ export function doorSortSubOrder (state, defaultSubOrder = 3)
119/**
119/**
120 * Passability: traversable when held open for passage (flipped from resting),
120 * Passability: traversable when held open for passage (flipped from resting),
121 * or when the mover can open doors (they flip on approach).
121 * or when the mover can open doors (they flip on approach).
122 * Optional `requirementsAllow: false` blocks everyone (including held-open passage).
122 */
123 */
123export function isDoorTraversable (block, { canOpenDoors = false } = {})
124export function isDoorTraversable (block, { canOpenDoors = false, requirementsAllow = true } = {})
124{
125{
126 if (!requirementsAllow)
127 { return false; }
125 if (isDoorPassageOpen(block))
128 if (isDoorPassageOpen(block))
126 { return true; }
129 { return true; }
127 return !!canOpenDoors;
130 return !!canOpenDoors;