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