BlueGit

timfa questward

Files

questward / client / src / render / chunkBake.js

chunkBake.js

chunkBake.js 15.6 KiB Download Raw
1import { CHUNK_SIZE, SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock, isChunkAtlasBakedBlock } from "/shared/definitions/tiles.js";
3import { bloomImageName, spriteImageName } from "/shared/definitions/tileSprites.js";
4import { resolveSeasonalVisualState, SeasonId } from "/shared/world/season.js";
5import {
6 SOFT_TERRAIN_NEIGHBOR_DIRS,
7 softTerrainBlendWeight,
8 softTerrainNeighborSample,
9 mixSoftTerrainPixel
10} from "/shared/render/softTerrain.js";
11import { computeChunkAtlasKeys } from "/shared/render/chunkAtlasKeys.js";
12
13/**
14 * Bake immobile ≤16×16 ground/block/bloom tiles into chunk atlases.
15 * Oversized or animated blocks/grounds are returned for individual sprites.
16 * When `cache` is set, identical ground/row/bloom layouts reuse canvases already in GPU memory.
17 * @param {{
18 * snapshot: object,
19 * catalog: object,
20 * images: object,
21 * preview?: object | null,
22 * season?: string,
23 * softTerrain?: boolean,
24 * resolveGround?: (tileX: number, tileY: number) => object | number | null,
25 * cache?: ReturnType<typeof import("./chunkAtlasCache.js").createChunkAtlasCache>
26 * }} options
27 */
28export function bakeChunkAtlases ({
29 snapshot,
30 catalog,
31 images,
32 preview = null,
33 season = SeasonId.summer,
34 softTerrain = false,
35 resolveGround = null,
36 cache = null
37})
38{
39 const extras = collectChunkSpriteExtras({
40 snapshot,
41 catalog,
42 images,
43 preview,
44 season
45 });
46 const keys = computeChunkAtlasKeys({
47 snapshot,
48 catalog,
49 preview,
50 season,
51 softTerrain,
52 resolveGround
53 });
54 const bakeCtx = {
55 snapshot,
56 catalog,
57 images,
58 preview,
59 season,
60 softTerrain,
61 resolveGround
62 };
63
64 let groundEntry;
65 let blockRowEntries;
66 let bloomEntry;
67
68 if (cache)
69 {
70 groundEntry = cache.acquireGround(keys.groundKey, () => bakeGroundCanvas(bakeCtx));
71 blockRowEntries = keys.blockRowKeys.map((key, row) =>
72 cache.acquireBlockRow(key, () => bakeBlockRowCanvas(bakeCtx, row)));
73 bloomEntry = cache.acquireBloom(keys.bloomKey, () => bakeBloomCanvas(bakeCtx));
74 }
75 else
76 {
77 groundEntry = { canvas: bakeGroundCanvas(bakeCtx) };
78 blockRowEntries = keys.blockRowKeys.map((_key, row) => ({
79 canvas: bakeBlockRowCanvas(bakeCtx, row)
80 }));
81 bloomEntry = { canvas: bakeBloomCanvas(bakeCtx) };
82 }
83
84 return {
85 ground: groundEntry.canvas,
86 blockRows: blockRowEntries.map((entry) => entry.canvas),
87 bloom: bloomEntry.canvas,
88 tallBlocks: extras.tallBlocks,
89 animatedGrounds: extras.animatedGrounds,
90 cacheRefs: cache
91 ? {
92 ground: groundEntry,
93 blockRows: blockRowEntries,
94 bloom: bloomEntry
95 }
96 : null
97 };
98}
99
100export { computeChunkAtlasKeys } from "/shared/render/chunkAtlasKeys.js";
101
102export function collectChunkSpriteExtras ({
103 snapshot,
104 catalog,
105 images,
106 preview = null,
107 season = SeasonId.summer
108})
109{
110 const tallBlocks = [];
111 const animatedGrounds = [];
112 const baseTileX = snapshot.chunkX * CHUNK_SIZE;
113 const baseTileY = snapshot.chunkY * CHUNK_SIZE;
114
115 for (let localY = 0; localY < CHUNK_SIZE; localY++)
116 {
117 for (let localX = 0; localX < CHUNK_SIZE; localX++)
118 {
119 const index = localY * CHUNK_SIZE + localX;
120 const tileX = baseTileX + localX;
121 const tileY = baseTileY + localY;
122 const groundEntry = tileGroundEntry(snapshot, preview, localX, localY);
123 const blockEntry = tileBlockEntry(snapshot, preview, tileX, tileY, index);
124
125 const groundName = groundSpriteName(catalog, groundEntry, season);
126 const groundMeta = groundCatalogMeta(catalog, groundEntry);
127 if (groundName && !isBakeable(images[groundName], groundMeta))
128 {
129 animatedGrounds.push({
130 tileX,
131 tileY,
132 sprite: groundName,
133 typeId: normalizeGround(groundEntry).typeId,
134 bloom: groundBloomName(catalog, groundEntry, season)
135 });
136 }
137
138 const blockName = blockSpriteName(catalog, blockEntry, season);
139 if (!blockName)
140 { continue; }
141 const blockMeta = blockCatalogMeta(catalog, blockEntry);
142 if (!isBakeable(images[blockName], blockMeta) || !isChunkAtlasBakedBlock(blockEntry))
143 {
144 tallBlocks.push({
145 tileX,
146 tileY,
147 sprite: blockName,
148 bloom: blockBloomName(catalog, blockEntry, season)
149 });
150 }
151 }
152 }
153
154 return { tallBlocks, animatedGrounds };
155}
156
157/**
158 * Per-tile block sprite when the block is not represented in the chunk atlas row.
159 * @returns {{ sprite: string, bloom: string | null } | null}
160 */
161export function tileBlockSpriteEntry (catalog, images, blockEntry, season = SeasonId.summer)
162{
163 if (!blockEntry)
164 { return null; }
165 const blockName = blockSpriteName(catalog, blockEntry, season);
166 if (!blockName)
167 { return null; }
168 const blockMeta = blockCatalogMeta(catalog, blockEntry);
169 const bakeable = isBakeable(images[blockName], blockMeta);
170 if (bakeable && isChunkAtlasBakedBlock(blockEntry))
171 { return null; }
172 return {
173 sprite: blockName,
174 bloom: blockBloomName(catalog, blockEntry, season)
175 };
176}
177
178function bakeGroundCanvas ({
179 snapshot,
180 catalog,
181 images,
182 preview,
183 season,
184 softTerrain,
185 resolveGround
186})
187{
188 const width = CHUNK_SIZE * SPRITE_SIZE_PX;
189 const height = CHUNK_SIZE * SPRITE_SIZE_PX;
190 const ground = makeCanvas(width, height);
191 const groundCtx = ground.getContext("2d", { willReadFrequently: softTerrain });
192 groundCtx.imageSmoothingEnabled = false;
193 groundCtx.clearRect(0, 0, width, height);
194 const pixelCache = softTerrain ? new Map() : null;
195 const baseTileX = snapshot.chunkX * CHUNK_SIZE;
196 const baseTileY = snapshot.chunkY * CHUNK_SIZE;
197
198 for (let localY = 0; localY < CHUNK_SIZE; localY++)
199 {
200 for (let localX = 0; localX < CHUNK_SIZE; localX++)
201 {
202 const tileX = baseTileX + localX;
203 const tileY = baseTileY + localY;
204 const groundEntry = tileGroundEntry(snapshot, preview, localX, localY);
205 const dx = localX * SPRITE_SIZE_PX;
206 const dy = localY * SPRITE_SIZE_PX;
207 const groundName = groundSpriteName(catalog, groundEntry, season);
208 const groundMeta = groundCatalogMeta(catalog, groundEntry);
209 if (!isBakeable(images[groundName], groundMeta))
210 { continue; }
211 const blendable = softTerrain && isGroundBlendable(groundEntry);
212 if (blendable)
213 {
214 blitSoftGround(
215 groundCtx,
216 images,
217 catalog,
218 groundEntry,
219 groundName,
220 dx,
221 dy,
222 tileX,
223 tileY,
224 season,
225 resolveGround,
226 pixelCache
227 );
228 }
229 else
230 { blit(groundCtx, images[groundName], dx, dy); }
231 }
232 }
233 return ground;
234}
235
236function bakeBlockRowCanvas ({
237 snapshot,
238 catalog,
239 images,
240 preview,
241 season
242}, row)
243{
244 const width = CHUNK_SIZE * SPRITE_SIZE_PX;
245 const canvas = makeCanvas(width, SPRITE_SIZE_PX);
246 const ctx = canvas.getContext("2d");
247 ctx.imageSmoothingEnabled = false;
248 ctx.clearRect(0, 0, width, SPRITE_SIZE_PX);
249 const baseTileX = snapshot.chunkX * CHUNK_SIZE;
250 const baseTileY = snapshot.chunkY * CHUNK_SIZE;
251
252 for (let localX = 0; localX < CHUNK_SIZE; localX++)
253 {
254 const index = row * CHUNK_SIZE + localX;
255 const tileX = baseTileX + localX;
256 const tileY = baseTileY + row;
257 const blockEntry = tileBlockEntry(snapshot, preview, tileX, tileY, index);
258 const blockName = blockSpriteName(catalog, blockEntry, season);
259 if (!blockName)
260 { continue; }
261 const blockMeta = blockCatalogMeta(catalog, blockEntry);
262 if (!isBakeable(images[blockName], blockMeta) || !isChunkAtlasBakedBlock(blockEntry))
263 { continue; }
264 blit(ctx, images[blockName], localX * SPRITE_SIZE_PX, 0);
265 }
266 return canvas;
267}
268
269function bakeBloomCanvas ({
270 snapshot,
271 catalog,
272 images,
273 preview,
274 season
275})
276{
277 const width = CHUNK_SIZE * SPRITE_SIZE_PX;
278 const bloom = makeCanvas(width, width);
279 const bloomCtx = bloom.getContext("2d");
280 bloomCtx.imageSmoothingEnabled = false;
281 bloomCtx.clearRect(0, 0, width, width);
282 const baseTileX = snapshot.chunkX * CHUNK_SIZE;
283 const baseTileY = snapshot.chunkY * CHUNK_SIZE;
284
285 for (let localY = 0; localY < CHUNK_SIZE; localY++)
286 {
287 for (let localX = 0; localX < CHUNK_SIZE; localX++)
288 {
289 const index = localY * CHUNK_SIZE + localX;
290 const tileX = baseTileX + localX;
291 const tileY = baseTileY + localY;
292 const dx = localX * SPRITE_SIZE_PX;
293 const dy = localY * SPRITE_SIZE_PX;
294 const groundEntry = tileGroundEntry(snapshot, preview, localX, localY);
295 const blockEntry = tileBlockEntry(snapshot, preview, tileX, tileY, index);
296
297 const groundBloom = groundBloomName(catalog, groundEntry, season);
298 if (groundBloom)
299 { blit(bloomCtx, images[groundBloom], dx, dy); }
300
301 const blockName = blockSpriteName(catalog, blockEntry, season);
302 if (!blockName)
303 { continue; }
304 const blockMeta = blockCatalogMeta(catalog, blockEntry);
305 if (!isBakeable(images[blockName], blockMeta) || !isChunkAtlasBakedBlock(blockEntry))
306 { continue; }
307 const blockBloom = blockBloomName(catalog, blockEntry, season);
308 if (blockBloom)
309 { blit(bloomCtx, images[blockBloom], dx, dy); }
310 }
311 }
312 return bloom;
313}
314
315export function isBakeable (sprite, meta = null)
316{
317 if (!sprite?.g_image)
318 { return false; }
319 if (sprite.width > SPRITE_SIZE_PX || sprite.height > SPRITE_SIZE_PX)
320 { return false; }
321 const frames = Number(sprite.subImages) || Number(sprite.subImgTotal) || (meta?.frames ?? 1);
322 const speed = sprite._animationSpeed ?? meta?.animationSpeed ?? 0;
323 if (frames > 1)
324 { return false; }
325 if (speed > 0)
326 { return false; }
327 return true;
328}
329
330function tileGroundEntry (snapshot, preview, localX, localY)
331{
332 const index = localY * CHUNK_SIZE + localX;
333 const baseTileX = snapshot.chunkX * CHUNK_SIZE;
334 const baseTileY = snapshot.chunkY * CHUNK_SIZE;
335 const tileX = baseTileX + localX;
336 const tileY = baseTileY + localY;
337 let groundEntry = snapshot.grounds[index];
338 if (preview && preview.tileX === tileX && preview.tileY === tileY && preview.ground !== undefined)
339 { groundEntry = preview.ground; }
340 return groundEntry;
341}
342
343function tileBlockEntry (snapshot, preview, tileX, tileY, index)
344{
345 let blockEntry = snapshot.blocks[index];
346 if (preview && preview.tileX === tileX && preview.tileY === tileY && preview.block !== undefined)
347 { blockEntry = preview.block; }
348 return blockEntry;
349}
350
351function makeCanvas (width, height)
352{
353 const canvas = document.createElement("canvas");
354 canvas.width = width;
355 canvas.height = height;
356 return canvas;
357}
358
359function blit (ctx, sprite, dx, dy)
360{
361 if (!sprite?.g_image)
362 { return; }
363 const sub = sprite.getSubImage(0);
364 ctx.drawImage(
365 sprite.g_image,
366 sub.sx,
367 sub.sy,
368 sub.sw,
369 sub.sh,
370 dx,
371 dy,
372 SPRITE_SIZE_PX,
373 SPRITE_SIZE_PX
374 );
375}
376
377function isGroundBlendable (ground)
378{
379 const entry = normalizeGround(ground);
380 return !!GROUND_DEFINITIONS[entry.typeId]?.blendable;
381}
382
383function groundVisualKey (catalog, ground, season)
384{
385 const entry = normalizeGround(ground);
386 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
387 const states = catalog.grounds?.[def.key]?.states ?? [];
388 const state = resolveSeasonalVisualState(states, entry.state, season);
389 return `${entry.typeId}:${state ?? ""}`;
390}
391
392function blitSoftGround (
393 ctx,
394 images,
395 catalog,
396 groundEntry,
397 groundName,
398 dx,
399 dy,
400 tileX,
401 tileY,
402 season,
403 resolveGround,
404 pixelCache
405)
406{
407 const selfPixels = spritePixels(images[groundName], pixelCache);
408 if (!selfPixels)
409 {
410 blit(ctx, images[groundName], dx, dy);
411 return;
412 }
413
414 const selfKey = groundVisualKey(catalog, groundEntry, season);
415 const neighborSprites = [];
416 for (const { ndx, ndy } of SOFT_TERRAIN_NEIGHBOR_DIRS)
417 {
418 const neighborGround = resolveNeighborGround(
419 tileX + ndx,
420 tileY + ndy,
421 resolveGround
422 );
423 if (neighborGround == null)
424 { continue; }
425 if (groundVisualKey(catalog, neighborGround, season) === selfKey)
426 { continue; }
427 const neighborName = groundSpriteName(catalog, neighborGround, season);
428 const pixels = spritePixels(images[neighborName], pixelCache);
429 if (!pixels)
430 { continue; }
431 neighborSprites.push({
432 ndx,
433 ndy,
434 pixels,
435 neighborBlendable: isGroundBlendable(neighborGround)
436 });
437 }
438
439 if (!neighborSprites.length)
440 {
441 blit(ctx, images[groundName], dx, dy);
442 return;
443 }
444
445 const out = ctx.createImageData(SPRITE_SIZE_PX, SPRITE_SIZE_PX);
446 const dst = out.data;
447 for (let py = 0; py < SPRITE_SIZE_PX; py++)
448 {
449 for (let px = 0; px < SPRITE_SIZE_PX; px++)
450 {
451 const self = readPixel(selfPixels, px, py);
452 const contribs = [];
453 for (const neighbor of neighborSprites)
454 {
455 const weight = softTerrainBlendWeight(px, py, neighbor.ndx, neighbor.ndy, SPRITE_SIZE_PX, {
456 neighborBlendable: neighbor.neighborBlendable
457 });
458 if (weight <= 0)
459 { continue; }
460 const sample = softTerrainNeighborSample(px, py, neighbor.ndx, neighbor.ndy, SPRITE_SIZE_PX);
461 contribs.push({
462 weight,
463 color: readPixel(neighbor.pixels, sample.sx, sample.sy)
464 });
465 }
466 const mixed = mixSoftTerrainPixel(self, contribs);
467 const i = (py * SPRITE_SIZE_PX + px) * 4;
468 dst[i] = mixed.r;
469 dst[i + 1] = mixed.g;
470 dst[i + 2] = mixed.b;
471 dst[i + 3] = mixed.a;
472 }
473 }
474 ctx.putImageData(out, dx, dy);
475}
476
477function resolveNeighborGround (tileX, tileY, resolveGround)
478{
479 if (typeof resolveGround === "function")
480 { return resolveGround(tileX, tileY); }
481 return null;
482}
483
484function spritePixels (sprite, cache)
485{
486 if (!sprite?.g_image)
487 { return null; }
488 const key = sprite.g_image?.src ?? sprite;
489 if (cache?.has(key))
490 { return cache.get(key); }
491 const sub = sprite.getSubImage(0);
492 const canvas = makeCanvas(SPRITE_SIZE_PX, SPRITE_SIZE_PX);
493 const ctx = canvas.getContext("2d", { willReadFrequently: true });
494 ctx.imageSmoothingEnabled = false;
495 ctx.drawImage(
496 sprite.g_image,
497 sub.sx,
498 sub.sy,
499 sub.sw,
500 sub.sh,
501 0,
502 0,
503 SPRITE_SIZE_PX,
504 SPRITE_SIZE_PX
505 );
506 const data = ctx.getImageData(0, 0, SPRITE_SIZE_PX, SPRITE_SIZE_PX);
507 cache?.set(key, data);
508 return data;
509}
510
511function readPixel (imageData, x, y)
512{
513 const i = (y * imageData.width + x) * 4;
514 const d = imageData.data;
515 return { r: d[i], g: d[i + 1], b: d[i + 2], a: d[i + 3] };
516}
517
518function groundSpriteName (catalog, ground, season = SeasonId.summer)
519{
520 const entry = normalizeGround(ground);
521 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
522 const states = catalog.grounds?.[def.key]?.states ?? [];
523 const state = resolveSeasonalVisualState(states, entry.state, season);
524 return spriteImageName("ground", def.key, state);
525}
526
527function blockSpriteName (catalog, block, season = SeasonId.summer)
528{
529 const entry = normalizeBlock(block);
530 if (!entry)
531 { return null; }
532 const def = BLOCK_DEFINITIONS[entry.typeId];
533 if (!def || def.editorHidden)
534 { return null; }
535 const states = catalog.blocks?.[def.key]?.states ?? [];
536 const state = resolveSeasonalVisualState(states, entry.state, season);
537 return spriteImageName("block", def.key, state);
538}
539
540function groundBloomName (catalog, ground, season = SeasonId.summer)
541{
542 const entry = normalizeGround(ground);
543 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
544 const type = catalog.grounds?.[def.key];
545 const state = resolveSeasonalVisualState(type?.states ?? [], entry.state, season);
546 if (!state || !type?.blooms?.[state])
547 { return null; }
548 return bloomImageName("ground", def.key, state);
549}
550
551function blockBloomName (catalog, block, season = SeasonId.summer)
552{
553 const entry = normalizeBlock(block);
554 if (!entry)
555 { return null; }
556 const def = BLOCK_DEFINITIONS[entry.typeId];
557 if (!def)
558 { return null; }
559 const type = catalog.blocks?.[def.key];
560 const state = resolveSeasonalVisualState(type?.states ?? [], entry.state, season);
561 if (!state || !type?.blooms?.[state])
562 { return null; }
563 return bloomImageName("block", def.key, state);
564}
565
566function blockCatalogMeta (catalog, block)
567{
568 const entry = normalizeBlock(block);
569 if (!entry)
570 { return null; }
571 const def = BLOCK_DEFINITIONS[entry.typeId];
572 if (!def)
573 { return null; }
574 return catalog.blocks?.[def.key] ?? null;
575}
576
577function groundCatalogMeta (catalog, ground)
578{
579 const entry = normalizeGround(ground);
580 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
581 return catalog.grounds?.[def.key] ?? {
582 frames: def.frames,
583 animationSpeed: def.animationSpeed
584 };
585}