import { groundDefinition, blockDefinition, normalizeGround, normalizeBlock, BLOCK_DEFINITIONS, GROUND_DEFINITIONS } from "../../../shared/definitions/tiles.js"; import { CHUNK_SIZE } from "../../../shared/protocol/constants.js"; import { localToTile } from "../world/coordinates.js"; import { cloneChunkData, createEmptyChunkData, decodeChunkBlob, encodeChunkBlob, normalizeSpawner } from "../world/chunkData.js"; import { bakeLightMaps, maxDefinitionLightRange } from "../lighting/baker.js"; import { closedNeighborEdges } from "../world/chunkFlags.js"; import { coerceSettingValue, diffSettings, diffItemSeedValues, allSettingFields, itemSeedMapsEqual } from "../../../shared/definitions/worldSettings.js"; import { normalizeItemSeedValues } from "../../../shared/shop/pricing.js"; import { itemDefinition } from "../../../shared/definitions/items.js"; import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js"; import { normalizeStarterLoadout, starterLoadoutsEqual, diffStarterLoadout } from "../../../shared/items/starterLoadout.js"; import { normalizeInitialQuests, initialQuestsEqual, diffInitialQuests } from "../../../shared/quests/initialQuests.js"; import { normalizeEquipmentStatBonuses, diffEquipmentStatBonuses, equipmentStatBonusMapsEqual } from "../../../shared/definitions/equipmentStatCategories.js"; import { normalizeQuestDef, normalizeDialogueTree } from "../../../shared/quests/normalize.js"; import { OVERWORLD_ID, normalizeDimensionId, normalizeDimensionRecord, defaultDimensionRecord, isOverworld, normalizeLightingMode, normalizeSeasonMode } from "../../../shared/world/dimensions.js"; export class EditorService { constructor (worldDb) { this.worldDb = worldDb; } #defaultGroundForDimension (dimensionId, revisionId = null) { const rev = revisionId ?? this.worldDb.getEditorRevisionId(); const dimId = normalizeDimensionId(dimensionId); const settings = this.worldDb.getLiveSettings(); const record = this.worldDb.getDimension(rev, dimId) ?? defaultDimensionRecord(dimId, { defaultGroundTypeId: settings.defaultGroundTypeId }); return record.defaultGroundTypeId; } loadChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID) { const dimId = normalizeDimensionId(dimensionId); const revisionId = this.worldDb.getEditorRevisionId(); const settings = this.worldDb.getLiveSettings(); const defaultGroundTypeId = this.#defaultGroundForDimension(dimId, revisionId); const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId, dimId); const data = row ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY) : createEmptyChunkData(defaultGroundTypeId); const isOpen = (x, y) => { const neighbor = this.worldDb.getChunkVersion(x, y, revisionId, dimId); if (!neighbor) { return false; } return !!decodeChunkBlob(neighbor.data_blob, defaultGroundTypeId, x, y).open; }; return { chunkX, chunkY, dimensionId: dimId, revisionId, pendingRevisionId: this.worldDb.getPendingRevisionId(), activeRevisionId: this.worldDb.getActiveRevisionId(), authored: !!row, settings, data, closedEdges: closedNeighborEdges(chunkX, chunkY, isOpen), changelog: this.worldDb.listChangelog(chunkX, chunkY, dimId) }; } saveChunk (chunkX, chunkY, draft, editorAdminId, dimensionId = OVERWORLD_ID) { const dimId = normalizeDimensionId(dimensionId); const previous = this.loadChunk(chunkX, chunkY, dimId); const next = cloneChunkData(previous.data); const defaultGroundTypeId = this.#defaultGroundForDimension(dimId); next.open = !!draft.open; if (Array.isArray(draft.grounds)) { next.grounds = draft.grounds.map((ground) => normalizeGround(ground, defaultGroundTypeId)); } if (Array.isArray(draft.blocks)) { next.blocks = draft.blocks.map((block) => normalizeBlock(block)); } if (Array.isArray(draft.spawners)) { next.spawners = draft.spawners.map((entry) => normalizeSpawner(entry)).filter(Boolean); } this.validateSpawnerDialogues(chunkX, chunkY, next.spawners); const diffEntries = diffChunks(chunkX, chunkY, previous.data, next, previous.authored); const revisionId = this.worldDb.ensurePendingRevision(editorAdminId); const baked = bakeLightMaps( chunkX, chunkY, (x, y) => this.#loadForBake(x, y, revisionId, defaultGroundTypeId, chunkX, chunkY, next, dimId), maxDefinitionLightRange(BLOCK_DEFINITIONS, GROUND_DEFINITIONS) ); for (const result of baked) { const shouldStore = result.chunkX === chunkX && result.chunkY === chunkY || this.worldDb.getChunkVersion(result.chunkX, result.chunkY, revisionId, dimId) || result.data.light.some((value) => value > 0); if (!shouldStore) { continue; } this.worldDb.saveChunkVersion( result.chunkX, result.chunkY, revisionId, result.data.open ? 1 : 0, encodeChunkBlob(result.data), dimId ); } if (diffEntries.length > 0) { this.worldDb.appendChangelog(chunkX, chunkY, revisionId, editorAdminId, diffEntries, dimId); } return this.loadChunk(chunkX, chunkY, dimId); } listDimensions () { const revisionId = this.worldDb.getEditorRevisionId(); return { revisionId, pendingRevisionId: this.worldDb.getPendingRevisionId(), activeRevisionId: this.worldDb.getActiveRevisionId(), dimensions: this.worldDb.listDimensions(revisionId) }; } createDimension (rawId, displayName, editorAdminId) { const trimmed = String(rawId ?? "").trim(); if (!trimmed) { const err = new Error("Dimension id is required."); err.userFacing = true; throw err; } const dimensionId = normalizeDimensionId(trimmed); const revisionId = this.worldDb.ensurePendingRevision(editorAdminId); if (this.worldDb.getDimension(revisionId, dimensionId)) { const err = new Error(`Dimension "${dimensionId}" already exists.`); err.userFacing = true; throw err; } const settings = this.worldDb.getLiveSettings(); const record = defaultDimensionRecord(dimensionId, { displayName: displayName != null && String(displayName).trim() ? String(displayName).trim() : dimensionId, defaultGroundTypeId: settings.defaultGroundTypeId }); this.worldDb.saveDimension(revisionId, record); return this.listDimensions(); } saveDimension (raw, editorAdminId) { if (!raw || typeof raw !== "object") { const err = new Error("Dimension payload required."); err.userFacing = true; throw err; } const dimensionId = normalizeDimensionId(raw.dimensionId); const revisionId = this.worldDb.ensurePendingRevision(editorAdminId); const settings = this.worldDb.getLiveSettings(); const existing = this.worldDb.getDimension(revisionId, dimensionId) ?? defaultDimensionRecord(dimensionId, { defaultGroundTypeId: settings.defaultGroundTypeId }); const next = normalizeDimensionRecord({ ...existing, displayName: Object.prototype.hasOwnProperty.call(raw, "displayName") ? raw.displayName : existing.displayName, lightingMode: Object.prototype.hasOwnProperty.call(raw, "lightingMode") ? normalizeLightingMode(raw.lightingMode) : existing.lightingMode, seasonMode: Object.prototype.hasOwnProperty.call(raw, "seasonMode") ? normalizeSeasonMode(raw.seasonMode) : existing.seasonMode, defaultGroundTypeId: Object.prototype.hasOwnProperty.call(raw, "defaultGroundTypeId") ? raw.defaultGroundTypeId : existing.defaultGroundTypeId, deletedAt: existing.deletedAt, purgeAfter: existing.purgeAfter }); this.worldDb.saveDimension(revisionId, next); return this.listDimensions(); } softDeleteDimension (dimensionId, editorAdminId) { const id = normalizeDimensionId(dimensionId); if (isOverworld(id)) { const err = new Error("Cannot delete overworld."); err.userFacing = true; throw err; } const revisionId = this.worldDb.ensurePendingRevision(editorAdminId); const result = this.worldDb.softDeleteDimension(revisionId, id); if (!result.ok) { const err = new Error(result.error ?? "Delete failed."); err.userFacing = true; throw err; } return this.listDimensions(); } cancelDimensionDeletion (dimensionId, editorAdminId) { const id = normalizeDimensionId(dimensionId); const revisionId = this.worldDb.ensurePendingRevision(editorAdminId); const result = this.worldDb.cancelDimensionDeletion(revisionId, id); if (!result.ok) { const err = new Error(result.error ?? "Cancel failed."); err.userFacing = true; throw err; } return this.listDimensions(); } loadSettings () { return { settings: this.worldDb.getLiveSettings(), changelog: this.worldDb.listSettingsChangelog() }; } saveSettings (partial, editorAdminId) { const current = this.worldDb.getLiveSettings(); const next = { ...current, itemSeedValues: { ...(current.itemSeedValues && typeof current.itemSeedValues === "object" ? current.itemSeedValues : {}) } }; for (const field of allSettingFields()) { if (!Object.prototype.hasOwnProperty.call(partial, field.key)) { continue; } const value = coerceSettingValue(field, partial[field.key]); if (value == null) { continue; } next[field.key] = value; } if (Object.prototype.hasOwnProperty.call(partial, "itemSeedValues")) { next.itemSeedValues = normalizeItemSeedValues(partial.itemSeedValues); } if (Object.prototype.hasOwnProperty.call(partial, "starterEquipment") || Object.prototype.hasOwnProperty.call(partial, "starterInventory")) { const loadout = normalizeStarterLoadout({ starterEquipment: Object.prototype.hasOwnProperty.call(partial, "starterEquipment") ? partial.starterEquipment : current.starterEquipment, starterInventory: Object.prototype.hasOwnProperty.call(partial, "starterInventory") ? partial.starterInventory : current.starterInventory }); next.starterEquipment = loadout.equipment; next.starterInventory = loadout.inventory; } if (Object.prototype.hasOwnProperty.call(partial, "equipmentStatBonuses")) { next.equipmentStatBonuses = normalizeEquipmentStatBonuses(partial.equipmentStatBonuses); } else { next.equipmentStatBonuses = normalizeEquipmentStatBonuses(current.equipmentStatBonuses); } if (Object.prototype.hasOwnProperty.call(partial, "initialQuests")) { next.initialQuests = normalizeInitialQuests(partial.initialQuests); } else { next.initialQuests = normalizeInitialQuests(current.initialQuests); } const { bullets: scalarBullets, changed } = diffSettings(current, next); const seedBullets = Object.prototype.hasOwnProperty.call(partial, "itemSeedValues") ? diffItemSeedValues( normalizeItemSeedValues(current.itemSeedValues), next.itemSeedValues, (itemId) => itemDefinition(itemId)?.displayName ?? null ) : []; if (!itemSeedMapsEqual(current.itemSeedValues, next.itemSeedValues) && Object.prototype.hasOwnProperty.call(partial, "itemSeedValues")) { changed.itemSeedValues = next.itemSeedValues; } const starterChanged = !starterLoadoutsEqual(current, next) && (Object.prototype.hasOwnProperty.call(partial, "starterEquipment") || Object.prototype.hasOwnProperty.call(partial, "starterInventory")); if (starterChanged) { changed.starterEquipment = next.starterEquipment; changed.starterInventory = next.starterInventory; } const starterBullets = starterChanged ? diffStarterLoadout(current, next) : []; const equipmentStatsChanged = Object.prototype.hasOwnProperty.call(partial, "equipmentStatBonuses") && !equipmentStatBonusMapsEqual(current.equipmentStatBonuses, next.equipmentStatBonuses); if (equipmentStatsChanged) { changed.equipmentStatBonuses = next.equipmentStatBonuses; } const equipmentStatBullets = equipmentStatsChanged ? diffEquipmentStatBonuses( current.equipmentStatBonuses, next.equipmentStatBonuses, (itemId) => itemDefinition(itemId)?.displayName ?? null ) : []; const initialQuestsChanged = Object.prototype.hasOwnProperty.call(partial, "initialQuests") && !initialQuestsEqual(current.initialQuests, next.initialQuests); if (initialQuestsChanged) { changed.initialQuests = next.initialQuests; } const initialQuestBullets = initialQuestsChanged ? diffInitialQuests(current.initialQuests, next.initialQuests) : []; const bullets = [ ...scalarBullets, ...seedBullets, ...starterBullets, ...equipmentStatBullets, ...initialQuestBullets ]; if (Object.keys(changed).length === 0) { return { settings: current, changelog: this.worldDb.listSettingsChangelog(), changed: {} }; } const settings = { ...current, ...changed, itemSeedValues: changed.itemSeedValues ?? normalizeItemSeedValues(current.itemSeedValues) ?? { ...(DEFAULT_WORLD_SETTINGS.itemSeedValues ?? {}) }, starterEquipment: changed.starterEquipment ?? current.starterEquipment ?? DEFAULT_WORLD_SETTINGS.starterEquipment, starterInventory: changed.starterInventory ?? current.starterInventory ?? DEFAULT_WORLD_SETTINGS.starterInventory, equipmentStatBonuses: changed.equipmentStatBonuses ?? normalizeEquipmentStatBonuses(current.equipmentStatBonuses), initialQuests: changed.initialQuests ?? normalizeInitialQuests(current.initialQuests) }; const normalized = normalizeStarterLoadout(settings); settings.starterEquipment = normalized.equipment; settings.starterInventory = normalized.inventory; this.worldDb.saveLiveSettings(settings, editorAdminId); this.worldDb.appendSettingsChangelog(editorAdminId, bullets); return { settings, changelog: this.worldDb.listSettingsChangelog(), changed, diffEntries: bullets }; } applyPendingRevision () { return this.worldDb.promotePendingRevision(); } revisionStatus () { return { activeRevisionId: this.worldDb.getActiveRevisionId(), pendingRevisionId: this.worldDb.getPendingRevisionId() }; } loadQuests () { const revisionId = this.worldDb.getEditorRevisionId(); const quests = this.worldDb.listQuestDefs(revisionId).map((raw) => normalizeQuestDef(raw)); return { revisionId, pendingRevisionId: this.worldDb.getPendingRevisionId(), activeRevisionId: this.worldDb.getActiveRevisionId(), quests }; } saveQuest (raw, editorAdminId) { const def = normalizeQuestDef(raw); const revisionId = this.worldDb.ensurePendingRevision(editorAdminId); this.worldDb.saveQuestDef(revisionId, def); return this.loadQuests(); } deleteQuest (questId, editorAdminId) { const revisionId = this.worldDb.ensurePendingRevision(editorAdminId); this.worldDb.deleteQuestDef(revisionId, String(questId)); return this.loadQuests(); } loadDialogues () { const revisionId = this.worldDb.getEditorRevisionId(); const trees = this.worldDb.listDialogueTrees(revisionId).map((raw) => normalizeDialogueTree(raw)); const assignmentCounts = this.#countDialogueAssignments(revisionId); return { revisionId, pendingRevisionId: this.worldDb.getPendingRevisionId(), activeRevisionId: this.worldDb.getActiveRevisionId(), dialogues: trees.map((tree) => ({ ...tree, assignedSpawnerCount: assignmentCounts.get(tree.dialogueId) ?? 0 })) }; } saveDialogue (raw, editorAdminId) { const tree = normalizeDialogueTree(raw); const revisionId = this.worldDb.ensurePendingRevision(editorAdminId); const assignmentCounts = this.#countDialogueAssignments(revisionId); const assigned = assignmentCounts.get(tree.dialogueId) ?? 0; if (tree.unique && assigned > 1) { const err = new Error("Unique dialogue can be assigned to at most one spawner."); err.userFacing = true; throw err; } if (tree.unique && assigned === 1) { const violation = this.#uniqueDialogueMaxAliveViolation(revisionId, tree.dialogueId); if (violation) { const err = new Error(violation); err.userFacing = true; throw err; } } this.worldDb.saveDialogueTree(revisionId, tree); return this.loadDialogues(); } deleteDialogue (dialogueId, editorAdminId) { const id = String(dialogueId); const revisionId = this.worldDb.getEditorRevisionId(); const assigned = this.#countDialogueAssignments(revisionId).get(id) ?? 0; if (assigned > 0) { const err = new Error(`Dialogue is still assigned to ${assigned} spawner(s). Unassign first.`); err.userFacing = true; throw err; } const pendingId = this.worldDb.ensurePendingRevision(editorAdminId); this.worldDb.deleteDialogueTree(pendingId, id); return this.loadDialogues(); } /** Validate dialogueId / unique / maxAlive when saving a chunk's spawners. */ validateSpawnerDialogues (chunkX, chunkY, spawners) { const revisionId = this.worldDb.getEditorRevisionId(); const trees = new Map( this.worldDb.listDialogueTrees(revisionId).map((raw) => { const tree = normalizeDialogueTree(raw); return [tree.dialogueId, tree]; }) ); for (const entry of spawners ?? []) { const dialogueId = entry?.config?.dialogueId; if (!dialogueId) { continue; } const tree = trees.get(dialogueId); if (!tree) { const err = new Error(`Unknown dialogue "${dialogueId}" on a spawner.`); err.userFacing = true; throw err; } if (tree.unique && (Math.max(1, Number(entry.config.maxAlive) || 1) !== 1)) { const err = new Error(`Unique dialogue "${dialogueId}" requires spawner maxAlive = 1.`); err.userFacing = true; throw err; } } const counts = this.#countDialogueAssignments(revisionId, { chunkX, chunkY, spawners }); for (const [dialogueId, tree] of trees) { const n = counts.get(dialogueId) ?? 0; if (tree.unique && n > 1) { const err = new Error(`Unique dialogue "${dialogueId}" would be on ${n} spawners.`); err.userFacing = true; throw err; } } } #countDialogueAssignments (revisionId, replaceChunk = null) { const settings = this.worldDb.getLiveSettings(); const counts = new Map(); const coords = this.worldDb.listChunkCoords(revisionId); for (const { chunk_x: cx, chunk_y: cy } of coords) { if (replaceChunk && cx === replaceChunk.chunkX && cy === replaceChunk.chunkY) { continue; } const row = this.worldDb.getChunkVersion(cx, cy, revisionId); if (!row) { continue; } const data = decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId, cx, cy); for (const entry of data.spawners ?? []) { const id = entry?.config?.dialogueId; if (!id) { continue; } counts.set(id, (counts.get(id) ?? 0) + 1); } } if (replaceChunk?.spawners) { for (const entry of replaceChunk.spawners) { const id = entry?.config?.dialogueId; if (!id) { continue; } counts.set(id, (counts.get(id) ?? 0) + 1); } } return counts; } #uniqueDialogueMaxAliveViolation (revisionId, dialogueId) { const settings = this.worldDb.getLiveSettings(); const coords = this.worldDb.listChunkCoords(revisionId); for (const { chunk_x: chunkX, chunk_y: chunkY } of coords) { const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId); if (!row) { continue; } const data = decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId, chunkX, chunkY); for (const entry of data.spawners ?? []) { if (entry?.config?.dialogueId !== dialogueId) { continue; } const maxAlive = Math.max(1, Number(entry.config.maxAlive) || 1); if (maxAlive !== 1) { return `Unique dialogue "${dialogueId}" requires spawner maxAlive = 1.`; } } } return null; } #loadForBake (chunkX, chunkY, revisionId, defaultGroundTypeId, savedX, savedY, savedData, dimensionId = OVERWORLD_ID) { if (chunkX === savedX && chunkY === savedY) { return savedData; } const dimId = normalizeDimensionId(dimensionId); const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId, dimId); return row ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY) : createEmptyChunkData(defaultGroundTypeId); } } export function diffChunks (chunkX, chunkY, previous, next, previousAuthored) { const bullets = []; const prevOpen = previousAuthored ? !!previous.open : false; if (prevOpen !== !!next.open) { bullets.push(next.open ? "Chunk opened." : "Chunk closed."); } for (let localY = 0; localY < CHUNK_SIZE; localY++) { for (let localX = 0; localX < CHUNK_SIZE; localX++) { const index = localY * CHUNK_SIZE + localX; const tileX = localToTile(chunkX, localX); const tileY = localToTile(chunkY, localY); const prevGround = normalizeGround(previous.grounds[index]); const nextGround = normalizeGround(next.grounds[index]); if (prevGround.typeId !== nextGround.typeId) { bullets.push( `Ground at ${tileX}, ${tileY} changed from ${nameGround(prevGround.typeId)} to ${nameGround(nextGround.typeId)}.` ); } else if ((prevGround.state ?? "") !== (nextGround.state ?? "")) { bullets.push( `Ground ${nameGround(nextGround.typeId)} at ${tileX}, ${tileY} state changed from ${stateLabel(prevGround.state)} to ${stateLabel(nextGround.state)}.` ); } const prevBlock = normalizeBlock(previous.blocks[index]); const nextBlock = normalizeBlock(next.blocks[index]); const prevId = prevBlock?.typeId ?? null; const nextId = nextBlock?.typeId ?? null; const prevConfig = JSON.stringify(prevBlock?.config ?? null); const nextConfig = JSON.stringify(nextBlock?.config ?? null); if (prevId !== nextId || prevConfig !== nextConfig) { if (prevId == null && nextId != null) { bullets.push(`Block ${nameBlock(nextId)} placed at ${tileX}, ${tileY}.`); } else if (prevId != null && nextId == null) { bullets.push(`Block ${nameBlock(prevId)} removed at ${tileX}, ${tileY}.`); } else { bullets.push(`Block at ${tileX}, ${tileY} changed from ${nameBlock(prevId)} to ${nameBlock(nextId)}.`); } } else if (prevBlock && nextBlock && (prevBlock.state ?? "") !== (nextBlock.state ?? "")) { bullets.push( `Block ${nameBlock(nextId)} at ${tileX}, ${tileY} state changed from ${stateLabel(prevBlock.state)} to ${stateLabel(nextBlock.state)}.` ); } } } const prevSpawners = indexSpawners(previous.spawners); const nextSpawners = indexSpawners(next.spawners); for (const key of new Set([...prevSpawners.keys(), ...nextSpawners.keys()])) { const prev = prevSpawners.get(key); const cur = nextSpawners.get(key); const [localX, localY] = key.split(",").map(Number); const tileX = localToTile(chunkX, localX); const tileY = localToTile(chunkY, localY); const prevConfig = JSON.stringify(prev?.config ?? null); const nextConfig = JSON.stringify(cur?.config ?? null); if (!prev && cur) { bullets.push(`Spawner (${cur.config.mobTypeId}) placed at ${tileX}, ${tileY}.`); } else if (prev && !cur) { bullets.push(`Spawner removed at ${tileX}, ${tileY}.`); } else if (prevConfig !== nextConfig) { bullets.push(`Spawner at ${tileX}, ${tileY} config changed.`); } } return bullets; } function indexSpawners (spawners) { const map = new Map(); for (const entry of spawners ?? []) { map.set(`${entry.localX},${entry.localY}`, entry); } return map; } function nameGround (typeId) { return groundDefinition(typeId)?.displayName ?? `ground ${typeId}`; } function nameBlock (typeId) { return blockDefinition(typeId)?.displayName ?? `block ${typeId}`; } function stateLabel (state) { return state || "default"; }