BlueGit

timfa questward

Files

questward / server / src / editor / service.js

service.js

service.js 9.4 KiB Download Raw
1import { groundDefinition, blockDefinition, normalizeGround, normalizeBlock } 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 { BLOCK_DEFINITIONS } from "../../../shared/definitions/tiles.js";
6import { bakeLightMaps, maxDefinitionLightRange } from "../lighting/baker.js";
7import { closedNeighborEdges } from "../world/chunkFlags.js";
8import { coerceSettingValue, diffSettings, diffItemSeedValues, allSettingFields, itemSeedMapsEqual } from "../../../shared/definitions/worldSettings.js";
9import { normalizeItemSeedValues } from "../../../shared/shop/pricing.js";
10import { itemDefinition } from "../../../shared/definitions/items.js";
11import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
12
13export class EditorService
14{
15 constructor (worldDb)
16 {
17 this.worldDb = worldDb;
18 }
19
20 loadChunk (chunkX, chunkY)
21 {
22 const revisionId = this.worldDb.getEditorRevisionId();
23 const settings = this.worldDb.getLiveSettings();
24 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId);
25 const data = row
26 ? decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId)
27 : createEmptyChunkData(settings.defaultGroundTypeId);
28 const isOpen = (x, y) =>
29 {
30 const neighbor = this.worldDb.getChunkVersion(x, y, revisionId);
31 if (!neighbor)
32 { return false; }
33 return !!decodeChunkBlob(neighbor.data_blob, settings.defaultGroundTypeId).open;
34 };
35 return {
36 chunkX,
37 chunkY,
38 revisionId,
39 pendingRevisionId: this.worldDb.getPendingRevisionId(),
40 activeRevisionId: this.worldDb.getActiveRevisionId(),
41 authored: !!row,
42 settings,
43 data,
44 closedEdges: closedNeighborEdges(chunkX, chunkY, isOpen),
45 changelog: this.worldDb.listChangelog(chunkX, chunkY)
46 };
47 }
48
49 saveChunk (chunkX, chunkY, draft, editorAdminId)
50 {
51 const previous = this.loadChunk(chunkX, chunkY);
52 const next = cloneChunkData(previous.data);
53 const settings = previous.settings ?? this.worldDb.getLiveSettings();
54 next.open = !!draft.open;
55 if (Array.isArray(draft.grounds))
56 { next.grounds = draft.grounds.map((ground) => normalizeGround(ground, settings.defaultGroundTypeId)); }
57 if (Array.isArray(draft.blocks))
58 { next.blocks = draft.blocks.map((block) => normalizeBlock(block)); }
59 if (Array.isArray(draft.spawners))
60 { next.spawners = draft.spawners.map((entry) => normalizeSpawner(entry)).filter(Boolean); }
61
62 const diffEntries = diffChunks(chunkX, chunkY, previous.data, next, previous.authored);
63 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
64 const baked = bakeLightMaps(
65 chunkX,
66 chunkY,
67 (x, y) => this.#loadForBake(x, y, revisionId, settings.defaultGroundTypeId, chunkX, chunkY, next),
68 maxDefinitionLightRange(BLOCK_DEFINITIONS)
69 );
70
71 for (const result of baked)
72 {
73 const shouldStore = result.chunkX === chunkX && result.chunkY === chunkY
74 || this.worldDb.getChunkVersion(result.chunkX, result.chunkY, revisionId)
75 || result.data.light.some((value) => value > 0);
76
77 if (!shouldStore)
78 { continue; }
79
80 this.worldDb.saveChunkVersion(
81 result.chunkX,
82 result.chunkY,
83 revisionId,
84 result.data.open ? 1 : 0,
85 encodeChunkBlob(result.data)
86 );
87 }
88
89 if (diffEntries.length > 0)
90 { this.worldDb.appendChangelog(chunkX, chunkY, revisionId, editorAdminId, diffEntries); }
91
92 return this.loadChunk(chunkX, chunkY);
93 }
94
95 loadSettings ()
96 {
97 return {
98 settings: this.worldDb.getLiveSettings(),
99 changelog: this.worldDb.listSettingsChangelog()
100 };
101 }
102
103 saveSettings (partial, editorAdminId)
104 {
105 const current = this.worldDb.getLiveSettings();
106 const next = {
107 ...current,
108 itemSeedValues: {
109 ...(current.itemSeedValues && typeof current.itemSeedValues === "object"
110 ? current.itemSeedValues
111 : {})
112 }
113 };
114 for (const field of allSettingFields())
115 {
116 if (!Object.prototype.hasOwnProperty.call(partial, field.key))
117 { continue; }
118 const value = coerceSettingValue(field, partial[field.key]);
119 if (value == null)
120 { continue; }
121 next[field.key] = value;
122 }
123 if (Object.prototype.hasOwnProperty.call(partial, "itemSeedValues"))
124 {
125 next.itemSeedValues = normalizeItemSeedValues(partial.itemSeedValues);
126 }
127 const { bullets: scalarBullets, changed } = diffSettings(current, next);
128 const seedBullets = Object.prototype.hasOwnProperty.call(partial, "itemSeedValues")
129 ? diffItemSeedValues(
130 normalizeItemSeedValues(current.itemSeedValues),
131 next.itemSeedValues,
132 (itemId) => itemDefinition(itemId)?.displayName ?? null
133 )
134 : [];
135 if (!itemSeedMapsEqual(current.itemSeedValues, next.itemSeedValues)
136 && Object.prototype.hasOwnProperty.call(partial, "itemSeedValues"))
137 {
138 changed.itemSeedValues = next.itemSeedValues;
139 }
140 const bullets = [...scalarBullets, ...seedBullets];
141 if (Object.keys(changed).length === 0)
142 {
143 return {
144 settings: current,
145 changelog: this.worldDb.listSettingsChangelog(),
146 changed: {}
147 };
148 }
149 const settings = {
150 ...current,
151 ...changed,
152 itemSeedValues: changed.itemSeedValues
153 ?? normalizeItemSeedValues(current.itemSeedValues)
154 ?? { ...(DEFAULT_WORLD_SETTINGS.itemSeedValues ?? {}) }
155 };
156 this.worldDb.saveLiveSettings(settings, editorAdminId);
157 this.worldDb.appendSettingsChangelog(editorAdminId, bullets);
158 return {
159 settings,
160 changelog: this.worldDb.listSettingsChangelog(),
161 changed,
162 diffEntries: bullets
163 };
164 }
165
166 applyPendingRevision ()
167 {
168 return this.worldDb.promotePendingRevision();
169 }
170
171 revisionStatus ()
172 {
173 return {
174 activeRevisionId: this.worldDb.getActiveRevisionId(),
175 pendingRevisionId: this.worldDb.getPendingRevisionId()
176 };
177 }
178
179 #loadForBake (chunkX, chunkY, revisionId, defaultGroundTypeId, savedX, savedY, savedData)
180 {
181 if (chunkX === savedX && chunkY === savedY)
182 { return savedData; }
183
184 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId);
185 return row
186 ? decodeChunkBlob(row.data_blob, defaultGroundTypeId)
187 : createEmptyChunkData(defaultGroundTypeId);
188 }
189}
190
191export function diffChunks (chunkX, chunkY, previous, next, previousAuthored)
192{
193 const bullets = [];
194 const prevOpen = previousAuthored ? !!previous.open : false;
195 if (prevOpen !== !!next.open)
196 { bullets.push(next.open ? "Chunk opened." : "Chunk closed."); }
197
198 for (let localY = 0; localY < CHUNK_SIZE; localY++)
199 {
200 for (let localX = 0; localX < CHUNK_SIZE; localX++)
201 {
202 const index = localY * CHUNK_SIZE + localX;
203 const tileX = localToTile(chunkX, localX);
204 const tileY = localToTile(chunkY, localY);
205 const prevGround = normalizeGround(previous.grounds[index]);
206 const nextGround = normalizeGround(next.grounds[index]);
207 if (prevGround.typeId !== nextGround.typeId)
208 {
209 bullets.push(
210 `Ground at ${tileX}, ${tileY} changed from ${nameGround(prevGround.typeId)} to ${nameGround(nextGround.typeId)}.`
211 );
212 }
213 else if ((prevGround.state ?? "") !== (nextGround.state ?? ""))
214 {
215 bullets.push(
216 `Ground ${nameGround(nextGround.typeId)} at ${tileX}, ${tileY} state changed from ${stateLabel(prevGround.state)} to ${stateLabel(nextGround.state)}.`
217 );
218 }
219
220 const prevBlock = normalizeBlock(previous.blocks[index]);
221 const nextBlock = normalizeBlock(next.blocks[index]);
222 const prevId = prevBlock?.typeId ?? null;
223 const nextId = nextBlock?.typeId ?? null;
224 const prevConfig = JSON.stringify(prevBlock?.config ?? null);
225 const nextConfig = JSON.stringify(nextBlock?.config ?? null);
226 if (prevId !== nextId || prevConfig !== nextConfig)
227 {
228 if (prevId == null && nextId != null)
229 { bullets.push(`Block ${nameBlock(nextId)} placed at ${tileX}, ${tileY}.`); }
230 else if (prevId != null && nextId == null)
231 { bullets.push(`Block ${nameBlock(prevId)} removed at ${tileX}, ${tileY}.`); }
232 else
233 { bullets.push(`Block at ${tileX}, ${tileY} changed from ${nameBlock(prevId)} to ${nameBlock(nextId)}.`); }
234 }
235 else if (prevBlock && nextBlock && (prevBlock.state ?? "") !== (nextBlock.state ?? ""))
236 {
237 bullets.push(
238 `Block ${nameBlock(nextId)} at ${tileX}, ${tileY} state changed from ${stateLabel(prevBlock.state)} to ${stateLabel(nextBlock.state)}.`
239 );
240 }
241 }
242 }
243
244 const prevSpawners = indexSpawners(previous.spawners);
245 const nextSpawners = indexSpawners(next.spawners);
246 for (const key of new Set([...prevSpawners.keys(), ...nextSpawners.keys()]))
247 {
248 const prev = prevSpawners.get(key);
249 const cur = nextSpawners.get(key);
250 const [localX, localY] = key.split(",").map(Number);
251 const tileX = localToTile(chunkX, localX);
252 const tileY = localToTile(chunkY, localY);
253 const prevConfig = JSON.stringify(prev?.config ?? null);
254 const nextConfig = JSON.stringify(cur?.config ?? null);
255 if (!prev && cur)
256 { bullets.push(`Spawner (${cur.config.mobTypeId}) placed at ${tileX}, ${tileY}.`); }
257 else if (prev && !cur)
258 { bullets.push(`Spawner removed at ${tileX}, ${tileY}.`); }
259 else if (prevConfig !== nextConfig)
260 { bullets.push(`Spawner at ${tileX}, ${tileY} config changed.`); }
261 }
262 return bullets;
263}
264
265function indexSpawners (spawners)
266{
267 const map = new Map();
268 for (const entry of spawners ?? [])
269 { map.set(`${entry.localX},${entry.localY}`, entry); }
270 return map;
271}
272
273function nameGround (typeId)
274{
275 return groundDefinition(typeId)?.displayName ?? `ground ${typeId}`;
276}
277
278function nameBlock (typeId)
279{
280 return blockDefinition(typeId)?.displayName ?? `block ${typeId}`;
281}
282
283function stateLabel (state)
284{
285 return state || "default";
286}