BlueGit

timfa questward

Files

questward / server / src / editor / service.js

service.js

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