BlueGit

timfa questward

Files

questward / client / src / render / chunkBake.js

chunkBake.js

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