BlueGit

timfa questward

Files

questward / server / src / editor / service.js

service.js

service.js 22.0 KiB Download Raw
1import { groundDefinition, blockDefinition, normalizeGround, normalizeBlock, BLOCK_DEFINITIONS, GROUND_DEFINITIONS } from "../../../shared/definitions/tiles.js";
2import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
3import { localToTile } from "../world/coordinates.js";
4import { cloneChunkData, createEmptyChunkData, decodeChunkBlob, encodeChunkBlob, normalizeSpawner } from "../world/chunkData.js";
5import { bakeLightMaps, maxDefinitionLightRange } from "../lighting/baker.js";
6import { closedNeighborEdges } from "../world/chunkFlags.js";
7import { coerceSettingValue, diffSettings, diffItemSeedValues, allSettingFields, itemSeedMapsEqual } from "../../../shared/definitions/worldSettings.js";
8import { normalizeItemSeedValues } from "../../../shared/shop/pricing.js";
9import { itemDefinition } from "../../../shared/definitions/items.js";
10import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
11import {
12 normalizeStarterLoadout,
13 starterLoadoutsEqual,
14 diffStarterLoadout
15} from "../../../shared/items/starterLoadout.js";
16import {
17 normalizeEquipmentStatBonuses,
18 diffEquipmentStatBonuses,
19 equipmentStatBonusMapsEqual
20} from "../../../shared/definitions/equipmentStatCategories.js";
21import { normalizeQuestDef, normalizeDialogueTree } from "../../../shared/quests/normalize.js";
22import {
23 OVERWORLD_ID,
24 normalizeDimensionId,
25 normalizeDimensionRecord,
26 defaultDimensionRecord,
27 isOverworld,
28 normalizeLightingMode,
29 normalizeSeasonMode
30} from "../../../shared/world/dimensions.js";
31
32export class EditorService
33{
34 constructor (worldDb)
35 {
36 this.worldDb = worldDb;
37 }
38
39 #defaultGroundForDimension (dimensionId, revisionId = null)
40 {
41 const rev = revisionId ?? this.worldDb.getEditorRevisionId();
42 const dimId = normalizeDimensionId(dimensionId);
43 const settings = this.worldDb.getLiveSettings();
44 const record = this.worldDb.getDimension(rev, dimId)
45 ?? defaultDimensionRecord(dimId, { defaultGroundTypeId: settings.defaultGroundTypeId });
46 return record.defaultGroundTypeId;
47 }
48
49 loadChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID)
50 {
51 const dimId = normalizeDimensionId(dimensionId);
52 const revisionId = this.worldDb.getEditorRevisionId();
53 const settings = this.worldDb.getLiveSettings();
54 const defaultGroundTypeId = this.#defaultGroundForDimension(dimId, revisionId);
55 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId, dimId);
56 const data = row
57 ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY)
58 : createEmptyChunkData(defaultGroundTypeId);
59 const isOpen = (x, y) =>
60 {
61 const neighbor = this.worldDb.getChunkVersion(x, y, revisionId, dimId);
62 if (!neighbor)
63 { return false; }
64 return !!decodeChunkBlob(neighbor.data_blob, defaultGroundTypeId, x, y).open;
65 };
66 return {
67 chunkX,
68 chunkY,
69 dimensionId: dimId,
70 revisionId,
71 pendingRevisionId: this.worldDb.getPendingRevisionId(),
72 activeRevisionId: this.worldDb.getActiveRevisionId(),
73 authored: !!row,
74 settings,
75 data,
76 closedEdges: closedNeighborEdges(chunkX, chunkY, isOpen),
77 changelog: this.worldDb.listChangelog(chunkX, chunkY, dimId)
78 };
79 }
80
81 saveChunk (chunkX, chunkY, draft, editorAdminId, dimensionId = OVERWORLD_ID)
82 {
83 const dimId = normalizeDimensionId(dimensionId);
84 const previous = this.loadChunk(chunkX, chunkY, dimId);
85 const next = cloneChunkData(previous.data);
86 const defaultGroundTypeId = this.#defaultGroundForDimension(dimId);
87 next.open = !!draft.open;
88 if (Array.isArray(draft.grounds))
89 { next.grounds = draft.grounds.map((ground) => normalizeGround(ground, defaultGroundTypeId)); }
90 if (Array.isArray(draft.blocks))
91 { next.blocks = draft.blocks.map((block) => normalizeBlock(block)); }
92 if (Array.isArray(draft.spawners))
93 { next.spawners = draft.spawners.map((entry) => normalizeSpawner(entry)).filter(Boolean); }
94
95 this.validateSpawnerDialogues(chunkX, chunkY, next.spawners);
96
97 const diffEntries = diffChunks(chunkX, chunkY, previous.data, next, previous.authored);
98 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
99 const baked = bakeLightMaps(
100 chunkX,
101 chunkY,
102 (x, y) => this.#loadForBake(x, y, revisionId, defaultGroundTypeId, chunkX, chunkY, next, dimId),
103 maxDefinitionLightRange(BLOCK_DEFINITIONS, GROUND_DEFINITIONS)
104 );
105
106 for (const result of baked)
107 {
108 const shouldStore = result.chunkX === chunkX && result.chunkY === chunkY
109 || this.worldDb.getChunkVersion(result.chunkX, result.chunkY, revisionId, dimId)
110 || result.data.light.some((value) => value > 0);
111
112 if (!shouldStore)
113 { continue; }
114
115 this.worldDb.saveChunkVersion(
116 result.chunkX,
117 result.chunkY,
118 revisionId,
119 result.data.open ? 1 : 0,
120 encodeChunkBlob(result.data),
121 dimId
122 );
123 }
124
125 if (diffEntries.length > 0)
126 { this.worldDb.appendChangelog(chunkX, chunkY, revisionId, editorAdminId, diffEntries, dimId); }
127
128 return this.loadChunk(chunkX, chunkY, dimId);
129 }
130
131 listDimensions ()
132 {
133 const revisionId = this.worldDb.getEditorRevisionId();
134 return {
135 revisionId,
136 pendingRevisionId: this.worldDb.getPendingRevisionId(),
137 activeRevisionId: this.worldDb.getActiveRevisionId(),
138 dimensions: this.worldDb.listDimensions(revisionId)
139 };
140 }
141
142 createDimension (rawId, displayName, editorAdminId)
143 {
144 const trimmed = String(rawId ?? "").trim();
145 if (!trimmed)
146 {
147 const err = new Error("Dimension id is required.");
148 err.userFacing = true;
149 throw err;
150 }
151 const dimensionId = normalizeDimensionId(trimmed);
152 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
153 if (this.worldDb.getDimension(revisionId, dimensionId))
154 {
155 const err = new Error(`Dimension "${dimensionId}" already exists.`);
156 err.userFacing = true;
157 throw err;
158 }
159 const settings = this.worldDb.getLiveSettings();
160 const record = defaultDimensionRecord(dimensionId, {
161 displayName: displayName != null && String(displayName).trim()
162 ? String(displayName).trim()
163 : dimensionId,
164 defaultGroundTypeId: settings.defaultGroundTypeId
165 });
166 this.worldDb.saveDimension(revisionId, record);
167 return this.listDimensions();
168 }
169
170 saveDimension (raw, editorAdminId)
171 {
172 if (!raw || typeof raw !== "object")
173 {
174 const err = new Error("Dimension payload required.");
175 err.userFacing = true;
176 throw err;
177 }
178 const dimensionId = normalizeDimensionId(raw.dimensionId);
179 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
180 const settings = this.worldDb.getLiveSettings();
181 const existing = this.worldDb.getDimension(revisionId, dimensionId)
182 ?? defaultDimensionRecord(dimensionId, { defaultGroundTypeId: settings.defaultGroundTypeId });
183 const next = normalizeDimensionRecord({
184 ...existing,
185 displayName: Object.prototype.hasOwnProperty.call(raw, "displayName")
186 ? raw.displayName
187 : existing.displayName,
188 lightingMode: Object.prototype.hasOwnProperty.call(raw, "lightingMode")
189 ? normalizeLightingMode(raw.lightingMode)
190 : existing.lightingMode,
191 seasonMode: Object.prototype.hasOwnProperty.call(raw, "seasonMode")
192 ? normalizeSeasonMode(raw.seasonMode)
193 : existing.seasonMode,
194 defaultGroundTypeId: Object.prototype.hasOwnProperty.call(raw, "defaultGroundTypeId")
195 ? raw.defaultGroundTypeId
196 : existing.defaultGroundTypeId,
197 deletedAt: existing.deletedAt,
198 purgeAfter: existing.purgeAfter
199 });
200 this.worldDb.saveDimension(revisionId, next);
201 return this.listDimensions();
202 }
203
204 softDeleteDimension (dimensionId, editorAdminId)
205 {
206 const id = normalizeDimensionId(dimensionId);
207 if (isOverworld(id))
208 {
209 const err = new Error("Cannot delete overworld.");
210 err.userFacing = true;
211 throw err;
212 }
213 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
214 const result = this.worldDb.softDeleteDimension(revisionId, id);
215 if (!result.ok)
216 {
217 const err = new Error(result.error ?? "Delete failed.");
218 err.userFacing = true;
219 throw err;
220 }
221 return this.listDimensions();
222 }
223
224 cancelDimensionDeletion (dimensionId, editorAdminId)
225 {
226 const id = normalizeDimensionId(dimensionId);
227 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
228 const result = this.worldDb.cancelDimensionDeletion(revisionId, id);
229 if (!result.ok)
230 {
231 const err = new Error(result.error ?? "Cancel failed.");
232 err.userFacing = true;
233 throw err;
234 }
235 return this.listDimensions();
236 }
237
238 loadSettings ()
239 {
240 return {
241 settings: this.worldDb.getLiveSettings(),
242 changelog: this.worldDb.listSettingsChangelog()
243 };
244 }
245
246 saveSettings (partial, editorAdminId)
247 {
248 const current = this.worldDb.getLiveSettings();
249 const next = {
250 ...current,
251 itemSeedValues: {
252 ...(current.itemSeedValues && typeof current.itemSeedValues === "object"
253 ? current.itemSeedValues
254 : {})
255 }
256 };
257 for (const field of allSettingFields())
258 {
259 if (!Object.prototype.hasOwnProperty.call(partial, field.key))
260 { continue; }
261 const value = coerceSettingValue(field, partial[field.key]);
262 if (value == null)
263 { continue; }
264 next[field.key] = value;
265 }
266 if (Object.prototype.hasOwnProperty.call(partial, "itemSeedValues"))
267 {
268 next.itemSeedValues = normalizeItemSeedValues(partial.itemSeedValues);
269 }
270 if (Object.prototype.hasOwnProperty.call(partial, "starterEquipment")
271 || Object.prototype.hasOwnProperty.call(partial, "starterInventory"))
272 {
273 const loadout = normalizeStarterLoadout({
274 starterEquipment: Object.prototype.hasOwnProperty.call(partial, "starterEquipment")
275 ? partial.starterEquipment
276 : current.starterEquipment,
277 starterInventory: Object.prototype.hasOwnProperty.call(partial, "starterInventory")
278 ? partial.starterInventory
279 : current.starterInventory
280 });
281 next.starterEquipment = loadout.equipment;
282 next.starterInventory = loadout.inventory;
283 }
284 if (Object.prototype.hasOwnProperty.call(partial, "equipmentStatBonuses"))
285 {
286 next.equipmentStatBonuses = normalizeEquipmentStatBonuses(partial.equipmentStatBonuses);
287 }
288 else
289 {
290 next.equipmentStatBonuses = normalizeEquipmentStatBonuses(current.equipmentStatBonuses);
291 }
292 const { bullets: scalarBullets, changed } = diffSettings(current, next);
293 const seedBullets = Object.prototype.hasOwnProperty.call(partial, "itemSeedValues")
294 ? diffItemSeedValues(
295 normalizeItemSeedValues(current.itemSeedValues),
296 next.itemSeedValues,
297 (itemId) => itemDefinition(itemId)?.displayName ?? null
298 )
299 : [];
300 if (!itemSeedMapsEqual(current.itemSeedValues, next.itemSeedValues)
301 && Object.prototype.hasOwnProperty.call(partial, "itemSeedValues"))
302 {
303 changed.itemSeedValues = next.itemSeedValues;
304 }
305 const starterChanged = !starterLoadoutsEqual(current, next)
306 && (Object.prototype.hasOwnProperty.call(partial, "starterEquipment")
307 || Object.prototype.hasOwnProperty.call(partial, "starterInventory"));
308 if (starterChanged)
309 {
310 changed.starterEquipment = next.starterEquipment;
311 changed.starterInventory = next.starterInventory;
312 }
313 const starterBullets = starterChanged
314 ? diffStarterLoadout(current, next)
315 : [];
316 const equipmentStatsChanged = Object.prototype.hasOwnProperty.call(partial, "equipmentStatBonuses")
317 && !equipmentStatBonusMapsEqual(current.equipmentStatBonuses, next.equipmentStatBonuses);
318 if (equipmentStatsChanged)
319 { changed.equipmentStatBonuses = next.equipmentStatBonuses; }
320 const equipmentStatBullets = equipmentStatsChanged
321 ? diffEquipmentStatBonuses(
322 current.equipmentStatBonuses,
323 next.equipmentStatBonuses,
324 (itemId) => itemDefinition(itemId)?.displayName ?? null
325 )
326 : [];
327 const bullets = [...scalarBullets, ...seedBullets, ...starterBullets, ...equipmentStatBullets];
328 if (Object.keys(changed).length === 0)
329 {
330 return {
331 settings: current,
332 changelog: this.worldDb.listSettingsChangelog(),
333 changed: {}
334 };
335 }
336 const settings = {
337 ...current,
338 ...changed,
339 itemSeedValues: changed.itemSeedValues
340 ?? normalizeItemSeedValues(current.itemSeedValues)
341 ?? { ...(DEFAULT_WORLD_SETTINGS.itemSeedValues ?? {}) },
342 starterEquipment: changed.starterEquipment ?? current.starterEquipment
343 ?? DEFAULT_WORLD_SETTINGS.starterEquipment,
344 starterInventory: changed.starterInventory ?? current.starterInventory
345 ?? DEFAULT_WORLD_SETTINGS.starterInventory,
346 equipmentStatBonuses: changed.equipmentStatBonuses
347 ?? normalizeEquipmentStatBonuses(current.equipmentStatBonuses)
348 };
349 const normalized = normalizeStarterLoadout(settings);
350 settings.starterEquipment = normalized.equipment;
351 settings.starterInventory = normalized.inventory;
352 this.worldDb.saveLiveSettings(settings, editorAdminId);
353 this.worldDb.appendSettingsChangelog(editorAdminId, bullets);
354 return {
355 settings,
356 changelog: this.worldDb.listSettingsChangelog(),
357 changed,
358 diffEntries: bullets
359 };
360 }
361
362 applyPendingRevision ()
363 {
364 return this.worldDb.promotePendingRevision();
365 }
366
367 revisionStatus ()
368 {
369 return {
370 activeRevisionId: this.worldDb.getActiveRevisionId(),
371 pendingRevisionId: this.worldDb.getPendingRevisionId()
372 };
373 }
374
375 loadQuests ()
376 {
377 const revisionId = this.worldDb.getEditorRevisionId();
378 const quests = this.worldDb.listQuestDefs(revisionId).map((raw) => normalizeQuestDef(raw));
379 return {
380 revisionId,
381 pendingRevisionId: this.worldDb.getPendingRevisionId(),
382 activeRevisionId: this.worldDb.getActiveRevisionId(),
383 quests
384 };
385 }
386
387 saveQuest (raw, editorAdminId)
388 {
389 const def = normalizeQuestDef(raw);
390 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
391 this.worldDb.saveQuestDef(revisionId, def);
392 return this.loadQuests();
393 }
394
395 deleteQuest (questId, editorAdminId)
396 {
397 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
398 this.worldDb.deleteQuestDef(revisionId, String(questId));
399 return this.loadQuests();
400 }
401
402 loadDialogues ()
403 {
404 const revisionId = this.worldDb.getEditorRevisionId();
405 const trees = this.worldDb.listDialogueTrees(revisionId).map((raw) => normalizeDialogueTree(raw));
406 const assignmentCounts = this.#countDialogueAssignments(revisionId);
407 return {
408 revisionId,
409 pendingRevisionId: this.worldDb.getPendingRevisionId(),
410 activeRevisionId: this.worldDb.getActiveRevisionId(),
411 dialogues: trees.map((tree) => ({
412 ...tree,
413 assignedSpawnerCount: assignmentCounts.get(tree.dialogueId) ?? 0
414 }))
415 };
416 }
417
418 saveDialogue (raw, editorAdminId)
419 {
420 const tree = normalizeDialogueTree(raw);
421 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
422 const assignmentCounts = this.#countDialogueAssignments(revisionId);
423 const assigned = assignmentCounts.get(tree.dialogueId) ?? 0;
424 if (tree.unique && assigned > 1)
425 {
426 const err = new Error("Unique dialogue can be assigned to at most one spawner.");
427 err.userFacing = true;
428 throw err;
429 }
430 if (tree.unique && assigned === 1)
431 {
432 const violation = this.#uniqueDialogueMaxAliveViolation(revisionId, tree.dialogueId);
433 if (violation)
434 {
435 const err = new Error(violation);
436 err.userFacing = true;
437 throw err;
438 }
439 }
440 this.worldDb.saveDialogueTree(revisionId, tree);
441 return this.loadDialogues();
442 }
443
444 deleteDialogue (dialogueId, editorAdminId)
445 {
446 const id = String(dialogueId);
447 const revisionId = this.worldDb.getEditorRevisionId();
448 const assigned = this.#countDialogueAssignments(revisionId).get(id) ?? 0;
449 if (assigned > 0)
450 {
451 const err = new Error(`Dialogue is still assigned to ${assigned} spawner(s). Unassign first.`);
452 err.userFacing = true;
453 throw err;
454 }
455 const pendingId = this.worldDb.ensurePendingRevision(editorAdminId);
456 this.worldDb.deleteDialogueTree(pendingId, id);
457 return this.loadDialogues();
458 }
459
460 /** Validate dialogueId / unique / maxAlive when saving a chunk's spawners. */
461 validateSpawnerDialogues (chunkX, chunkY, spawners)
462 {
463 const revisionId = this.worldDb.getEditorRevisionId();
464 const trees = new Map(
465 this.worldDb.listDialogueTrees(revisionId).map((raw) =>
466 {
467 const tree = normalizeDialogueTree(raw);
468 return [tree.dialogueId, tree];
469 })
470 );
471 for (const entry of spawners ?? [])
472 {
473 const dialogueId = entry?.config?.dialogueId;
474 if (!dialogueId)
475 { continue; }
476 const tree = trees.get(dialogueId);
477 if (!tree)
478 {
479 const err = new Error(`Unknown dialogue "${dialogueId}" on a spawner.`);
480 err.userFacing = true;
481 throw err;
482 }
483 if (tree.unique && (Math.max(1, Number(entry.config.maxAlive) || 1) !== 1))
484 {
485 const err = new Error(`Unique dialogue "${dialogueId}" requires spawner maxAlive = 1.`);
486 err.userFacing = true;
487 throw err;
488 }
489 }
490 const counts = this.#countDialogueAssignments(revisionId, { chunkX, chunkY, spawners });
491 for (const [dialogueId, tree] of trees)
492 {
493 const n = counts.get(dialogueId) ?? 0;
494 if (tree.unique && n > 1)
495 {
496 const err = new Error(`Unique dialogue "${dialogueId}" would be on ${n} spawners.`);
497 err.userFacing = true;
498 throw err;
499 }
500 }
501 }
502
503 #countDialogueAssignments (revisionId, replaceChunk = null)
504 {
505 const settings = this.worldDb.getLiveSettings();
506 const counts = new Map();
507 const coords = this.worldDb.listChunkCoords(revisionId);
508 for (const { chunk_x: cx, chunk_y: cy } of coords)
509 {
510 if (replaceChunk && cx === replaceChunk.chunkX && cy === replaceChunk.chunkY)
511 { continue; }
512 const row = this.worldDb.getChunkVersion(cx, cy, revisionId);
513 if (!row)
514 { continue; }
515 const data = decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId, cx, cy);
516 for (const entry of data.spawners ?? [])
517 {
518 const id = entry?.config?.dialogueId;
519 if (!id)
520 { continue; }
521 counts.set(id, (counts.get(id) ?? 0) + 1);
522 }
523 }
524 if (replaceChunk?.spawners)
525 {
526 for (const entry of replaceChunk.spawners)
527 {
528 const id = entry?.config?.dialogueId;
529 if (!id)
530 { continue; }
531 counts.set(id, (counts.get(id) ?? 0) + 1);
532 }
533 }
534 return counts;
535 }
536
537 #uniqueDialogueMaxAliveViolation (revisionId, dialogueId)
538 {
539 const settings = this.worldDb.getLiveSettings();
540 const coords = this.worldDb.listChunkCoords(revisionId);
541 for (const { chunk_x: chunkX, chunk_y: chunkY } of coords)
542 {
543 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId);
544 if (!row)
545 { continue; }
546 const data = decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId, chunkX, chunkY);
547 for (const entry of data.spawners ?? [])
548 {
549 if (entry?.config?.dialogueId !== dialogueId)
550 { continue; }
551 const maxAlive = Math.max(1, Number(entry.config.maxAlive) || 1);
552 if (maxAlive !== 1)
553 { return `Unique dialogue "${dialogueId}" requires spawner maxAlive = 1.`; }
554 }
555 }
556 return null;
557 }
558
559 #loadForBake (chunkX, chunkY, revisionId, defaultGroundTypeId, savedX, savedY, savedData, dimensionId = OVERWORLD_ID)
560 {
561 if (chunkX === savedX && chunkY === savedY)
562 { return savedData; }
563
564 const dimId = normalizeDimensionId(dimensionId);
565 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId, dimId);
566 return row
567 ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY)
568 : createEmptyChunkData(defaultGroundTypeId);
569 }
570}
571
572export function diffChunks (chunkX, chunkY, previous, next, previousAuthored)
573{
574 const bullets = [];
575 const prevOpen = previousAuthored ? !!previous.open : false;
576 if (prevOpen !== !!next.open)
577 { bullets.push(next.open ? "Chunk opened." : "Chunk closed."); }
578
579 for (let localY = 0; localY < CHUNK_SIZE; localY++)
580 {
581 for (let localX = 0; localX < CHUNK_SIZE; localX++)
582 {
583 const index = localY * CHUNK_SIZE + localX;
584 const tileX = localToTile(chunkX, localX);
585 const tileY = localToTile(chunkY, localY);
586 const prevGround = normalizeGround(previous.grounds[index]);
587 const nextGround = normalizeGround(next.grounds[index]);
588 if (prevGround.typeId !== nextGround.typeId)
589 {
590 bullets.push(
591 `Ground at ${tileX}, ${tileY} changed from ${nameGround(prevGround.typeId)} to ${nameGround(nextGround.typeId)}.`
592 );
593 }
594 else if ((prevGround.state ?? "") !== (nextGround.state ?? ""))
595 {
596 bullets.push(
597 `Ground ${nameGround(nextGround.typeId)} at ${tileX}, ${tileY} state changed from ${stateLabel(prevGround.state)} to ${stateLabel(nextGround.state)}.`
598 );
599 }
600
601 const prevBlock = normalizeBlock(previous.blocks[index]);
602 const nextBlock = normalizeBlock(next.blocks[index]);
603 const prevId = prevBlock?.typeId ?? null;
604 const nextId = nextBlock?.typeId ?? null;
605 const prevConfig = JSON.stringify(prevBlock?.config ?? null);
606 const nextConfig = JSON.stringify(nextBlock?.config ?? null);
607 if (prevId !== nextId || prevConfig !== nextConfig)
608 {
609 if (prevId == null && nextId != null)
610 { bullets.push(`Block ${nameBlock(nextId)} placed at ${tileX}, ${tileY}.`); }
611 else if (prevId != null && nextId == null)
612 { bullets.push(`Block ${nameBlock(prevId)} removed at ${tileX}, ${tileY}.`); }
613 else
614 { bullets.push(`Block at ${tileX}, ${tileY} changed from ${nameBlock(prevId)} to ${nameBlock(nextId)}.`); }
615 }
616 else if (prevBlock && nextBlock && (prevBlock.state ?? "") !== (nextBlock.state ?? ""))
617 {
618 bullets.push(
619 `Block ${nameBlock(nextId)} at ${tileX}, ${tileY} state changed from ${stateLabel(prevBlock.state)} to ${stateLabel(nextBlock.state)}.`
620 );
621 }
622 }
623 }
624
625 const prevSpawners = indexSpawners(previous.spawners);
626 const nextSpawners = indexSpawners(next.spawners);
627 for (const key of new Set([...prevSpawners.keys(), ...nextSpawners.keys()]))
628 {
629 const prev = prevSpawners.get(key);
630 const cur = nextSpawners.get(key);
631 const [localX, localY] = key.split(",").map(Number);
632 const tileX = localToTile(chunkX, localX);
633 const tileY = localToTile(chunkY, localY);
634 const prevConfig = JSON.stringify(prev?.config ?? null);
635 const nextConfig = JSON.stringify(cur?.config ?? null);
636 if (!prev && cur)
637 { bullets.push(`Spawner (${cur.config.mobTypeId}) placed at ${tileX}, ${tileY}.`); }
638 else if (prev && !cur)
639 { bullets.push(`Spawner removed at ${tileX}, ${tileY}.`); }
640 else if (prevConfig !== nextConfig)
641 { bullets.push(`Spawner at ${tileX}, ${tileY} config changed.`); }
642 }
643 return bullets;
644}
645
646function indexSpawners (spawners)
647{
648 const map = new Map();
649 for (const entry of spawners ?? [])
650 { map.set(`${entry.localX},${entry.localY}`, entry); }
651 return map;
652}
653
654function nameGround (typeId)
655{
656 return groundDefinition(typeId)?.displayName ?? `ground ${typeId}`;
657}
658
659function nameBlock (typeId)
660{
661 return blockDefinition(typeId)?.displayName ?? `block ${typeId}`;
662}
663
664function stateLabel (state)
665{
666 return state || "default";
667}