BlueGit

timfa questward

Default lit darkness shader, chunk lightmap atlases, and lantern offhand.

Restore baked chunk rendering with per-chunk lightmaps for tile darkness, make the sprite shader the default for all lit objects, and add an equippable lantern that grants dynamic light to existing and new characters.

timfa Tim Falken · pushed by timfa

Authored 2026-08-24 · 2 months ago

Hash
2920dd06424f238de266eea762f7d5e6395c9ee4
Parent
f5746b29
10 files changed +622 −110
client/assets/fx/melee-swipe/melee-swipe.png Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/lantern/lantern-equip-bloom.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/lantern/lantern-equip.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/lantern/lantern.png added Binary file +0 −0

The contents of this binary file are not shown.

client/scripts/write-placeholder-assets.mjs +3 −0
@@ -45,6 +45,9 @@ solid(join(root, "mobs", "deer", "deer.png"), [120, 78, 42, 255]);
45 45 solid(join(root, "mobs", "rat", "rat.png"), [96, 88, 72, 255], [40, 36, 28, 255]);
46 46 overlay(join(root, "items", "stick", "stick-equip.png"), [150, 98, 46, 230]);
47 47 overlay(join(root, "items", "cloth-shirt", "cloth-shirt-equip.png"), [72, 112, 176, 230]);
48 solid(join(root, "items", "lantern", "lantern.png"), [180, 120, 40, 255]);
49 overlay(join(root, "items", "lantern", "lantern-equip.png"), [200, 130, 48, 230]);
50 torchBloom(join(root, "items", "lantern", "lantern-equip-bloom.png"));
48 51 torchBloom(join(root, "blocks", "torch", "torch-bloom.png"));
49 52
50 53 {
@@ -45,6 +45,9 @@ solid(join(root, "mobs", "deer", "deer.png"), [120, 78, 42, 255]);
45solid(join(root, "mobs", "rat", "rat.png"), [96, 88, 72, 255], [40, 36, 28, 255]);
45solid(join(root, "mobs", "rat", "rat.png"), [96, 88, 72, 255], [40, 36, 28, 255]);
46overlay(join(root, "items", "stick", "stick-equip.png"), [150, 98, 46, 230]);
46overlay(join(root, "items", "stick", "stick-equip.png"), [150, 98, 46, 230]);
47overlay(join(root, "items", "cloth-shirt", "cloth-shirt-equip.png"), [72, 112, 176, 230]);
47overlay(join(root, "items", "cloth-shirt", "cloth-shirt-equip.png"), [72, 112, 176, 230]);
48solid(join(root, "items", "lantern", "lantern.png"), [180, 120, 40, 255]);
49overlay(join(root, "items", "lantern", "lantern-equip.png"), [200, 130, 48, 230]);
50torchBloom(join(root, "items", "lantern", "lantern-equip-bloom.png"));
48torchBloom(join(root, "blocks", "torch", "torch-bloom.png"));
51torchBloom(join(root, "blocks", "torch", "torch-bloom.png"));
49
52
50{
53{
client/src/render/chunkBake.js added +180 −0
@@ -0,0 +1,180 @@
1 import { CHUNK_SIZE, SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2 import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";
3 import { bloomImageName, resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";
4
5 /**
6 * Bake immobile ≤16×16 ground/block/bloom tiles into chunk atlases.
7 * Oversized or animated blocks are returned in `tallBlocks` for individual Y-sorted sprites.
8 */
9 export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })
10 {
11 const width = CHUNK_SIZE * SPRITE_SIZE_PX;
12 const height = CHUNK_SIZE * SPRITE_SIZE_PX;
13 const ground = makeCanvas(width, height);
14 const bloom = makeCanvas(width, height);
15 const blockRows = [];
16 for (let row = 0; row < CHUNK_SIZE; row++)
17 { blockRows.push(makeCanvas(width, SPRITE_SIZE_PX)); }
18
19 const groundCtx = ground.getContext("2d");
20 const bloomCtx = bloom.getContext("2d");
21 const blockCtxs = blockRows.map((canvas) => canvas.getContext("2d"));
22 for (const ctx of [groundCtx, bloomCtx, ...blockCtxs])
23 {
24 ctx.imageSmoothingEnabled = false;
25 ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
26 }
27
28 const tallBlocks = [];
29 const baseTileX = snapshot.chunkX * CHUNK_SIZE;
30 const baseTileY = snapshot.chunkY * CHUNK_SIZE;
31
32 for (let localY = 0; localY < CHUNK_SIZE; localY++)
33 {
34 for (let localX = 0; localX < CHUNK_SIZE; localX++)
35 {
36 const index = localY * CHUNK_SIZE + localX;
37 const tileX = baseTileX + localX;
38 const tileY = baseTileY + localY;
39 let groundEntry = snapshot.grounds[index];
40 let blockEntry = snapshot.blocks[index];
41 if (preview && preview.tileX === tileX && preview.tileY === tileY)
42 {
43 if (preview.ground !== undefined)
44 { groundEntry = preview.ground; }
45 if (preview.block !== undefined)
46 { blockEntry = preview.block; }
47 }
48
49 const dx = localX * SPRITE_SIZE_PX;
50 const dy = localY * SPRITE_SIZE_PX;
51 const groundName = groundSpriteName(catalog, groundEntry);
52 blit(groundCtx, images[groundName], dx, dy);
53
54 const groundBloom = groundBloomName(catalog, groundEntry);
55 if (groundBloom)
56 { blit(bloomCtx, images[groundBloom], dx, dy); }
57
58 const blockName = blockSpriteName(catalog, blockEntry);
59 if (!blockName)
60 { continue; }
61 const blockMeta = blockCatalogMeta(catalog, blockEntry);
62 if (isBakeable(images[blockName], blockMeta))
63 {
64 blit(blockCtxs[localY], images[blockName], dx, 0);
65 const blockBloom = blockBloomName(catalog, blockEntry);
66 if (blockBloom)
67 { blit(bloomCtx, images[blockBloom], dx, dy); }
68 }
69 else
70 {
71 tallBlocks.push({
72 tileX,
73 tileY,
74 sprite: blockName,
75 bloom: blockBloomName(catalog, blockEntry)
76 });
77 }
78 }
79 }
80
81 return { ground, blockRows, bloom, tallBlocks };
82 }
83
84 export function isBakeable (sprite, meta = null)
85 {
86 if (!sprite?.g_image)
87 { return false; }
88 if (sprite.width > SPRITE_SIZE_PX || sprite.height > SPRITE_SIZE_PX)
89 { return false; }
90 if ((meta?.frames ?? 1) > 1)
91 { return false; }
92 if ((meta?.animationSpeed ?? 0) > 0)
93 { return false; }
94 return true;
95 }
96
97 function makeCanvas (width, height)
98 {
99 const canvas = document.createElement("canvas");
100 canvas.width = width;
101 canvas.height = height;
102 return canvas;
103 }
104
105 function blit (ctx, sprite, dx, dy)
106 {
107 if (!sprite?.g_image)
108 { return; }
109 const sub = sprite.getSubImage(0);
110 ctx.drawImage(
111 sprite.g_image,
112 sub.sx,
113 sub.sy,
114 sub.sw,
115 sub.sh,
116 dx,
117 dy,
118 SPRITE_SIZE_PX,
119 SPRITE_SIZE_PX
120 );
121 }
122
123 function groundSpriteName (catalog, ground)
124 {
125 const entry = normalizeGround(ground);
126 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
127 const states = catalog.grounds?.[def.key]?.states ?? [];
128 const state = resolveState(states, entry.state);
129 return spriteImageName("ground", def.key, state);
130 }
131
132 function blockSpriteName (catalog, block)
133 {
134 const entry = normalizeBlock(block);
135 if (!entry)
136 { return null; }
137 const def = BLOCK_DEFINITIONS[entry.typeId];
138 if (!def)
139 { return null; }
140 const states = catalog.blocks?.[def.key]?.states ?? [];
141 const state = resolveState(states, entry.state);
142 return spriteImageName("block", def.key, state);
143 }
144
145 function groundBloomName (catalog, ground)
146 {
147 const entry = normalizeGround(ground);
148 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
149 const type = catalog.grounds?.[def.key];
150 const state = resolveState(type?.states ?? [], entry.state);
151 if (!state || !type?.blooms?.[state])
152 { return null; }
153 return bloomImageName("ground", def.key, state);
154 }
155
156 function blockBloomName (catalog, block)
157 {
158 const entry = normalizeBlock(block);
159 if (!entry)
160 { return null; }
161 const def = BLOCK_DEFINITIONS[entry.typeId];
162 if (!def)
163 { return null; }
164 const type = catalog.blocks?.[def.key];
165 const state = resolveState(type?.states ?? [], entry.state);
166 if (!state || !type?.blooms?.[state])
167 { return null; }
168 return bloomImageName("block", def.key, state);
169 }
170
171 function blockCatalogMeta (catalog, block)
172 {
173 const entry = normalizeBlock(block);
174 if (!entry)
175 { return null; }
176 const def = BLOCK_DEFINITIONS[entry.typeId];
177 if (!def)
178 { return null; }
179 return catalog.blocks?.[def.key] ?? null;
180 }
@@ -0,0 +1,180 @@
1import { CHUNK_SIZE, SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";
3import { bloomImageName, resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";
4
5/**
6 * Bake immobile ≤16×16 ground/block/bloom tiles into chunk atlases.
7 * Oversized or animated blocks are returned in `tallBlocks` for individual Y-sorted sprites.
8 */
9export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })
10{
11 const width = CHUNK_SIZE * SPRITE_SIZE_PX;
12 const height = CHUNK_SIZE * SPRITE_SIZE_PX;
13 const ground = makeCanvas(width, height);
14 const bloom = makeCanvas(width, height);
15 const blockRows = [];
16 for (let row = 0; row < CHUNK_SIZE; row++)
17 { blockRows.push(makeCanvas(width, SPRITE_SIZE_PX)); }
18
19 const groundCtx = ground.getContext("2d");
20 const bloomCtx = bloom.getContext("2d");
21 const blockCtxs = blockRows.map((canvas) => canvas.getContext("2d"));
22 for (const ctx of [groundCtx, bloomCtx, ...blockCtxs])
23 {
24 ctx.imageSmoothingEnabled = false;
25 ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
26 }
27
28 const tallBlocks = [];
29 const baseTileX = snapshot.chunkX * CHUNK_SIZE;
30 const baseTileY = snapshot.chunkY * CHUNK_SIZE;
31
32 for (let localY = 0; localY < CHUNK_SIZE; localY++)
33 {
34 for (let localX = 0; localX < CHUNK_SIZE; localX++)
35 {
36 const index = localY * CHUNK_SIZE + localX;
37 const tileX = baseTileX + localX;
38 const tileY = baseTileY + localY;
39 let groundEntry = snapshot.grounds[index];
40 let blockEntry = snapshot.blocks[index];
41 if (preview && preview.tileX === tileX && preview.tileY === tileY)
42 {
43 if (preview.ground !== undefined)
44 { groundEntry = preview.ground; }
45 if (preview.block !== undefined)
46 { blockEntry = preview.block; }
47 }
48
49 const dx = localX * SPRITE_SIZE_PX;
50 const dy = localY * SPRITE_SIZE_PX;
51 const groundName = groundSpriteName(catalog, groundEntry);
52 blit(groundCtx, images[groundName], dx, dy);
53
54 const groundBloom = groundBloomName(catalog, groundEntry);
55 if (groundBloom)
56 { blit(bloomCtx, images[groundBloom], dx, dy); }
57
58 const blockName = blockSpriteName(catalog, blockEntry);
59 if (!blockName)
60 { continue; }
61 const blockMeta = blockCatalogMeta(catalog, blockEntry);
62 if (isBakeable(images[blockName], blockMeta))
63 {
64 blit(blockCtxs[localY], images[blockName], dx, 0);
65 const blockBloom = blockBloomName(catalog, blockEntry);
66 if (blockBloom)
67 { blit(bloomCtx, images[blockBloom], dx, dy); }
68 }
69 else
70 {
71 tallBlocks.push({
72 tileX,
73 tileY,
74 sprite: blockName,
75 bloom: blockBloomName(catalog, blockEntry)
76 });
77 }
78 }
79 }
80
81 return { ground, blockRows, bloom, tallBlocks };
82}
83
84export function isBakeable (sprite, meta = null)
85{
86 if (!sprite?.g_image)
87 { return false; }
88 if (sprite.width > SPRITE_SIZE_PX || sprite.height > SPRITE_SIZE_PX)
89 { return false; }
90 if ((meta?.frames ?? 1) > 1)
91 { return false; }
92 if ((meta?.animationSpeed ?? 0) > 0)
93 { return false; }
94 return true;
95}
96
97function makeCanvas (width, height)
98{
99 const canvas = document.createElement("canvas");
100 canvas.width = width;
101 canvas.height = height;
102 return canvas;
103}
104
105function blit (ctx, sprite, dx, dy)
106{
107 if (!sprite?.g_image)
108 { return; }
109 const sub = sprite.getSubImage(0);
110 ctx.drawImage(
111 sprite.g_image,
112 sub.sx,
113 sub.sy,
114 sub.sw,
115 sub.sh,
116 dx,
117 dy,
118 SPRITE_SIZE_PX,
119 SPRITE_SIZE_PX
120 );
121}
122
123function groundSpriteName (catalog, ground)
124{
125 const entry = normalizeGround(ground);
126 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
127 const states = catalog.grounds?.[def.key]?.states ?? [];
128 const state = resolveState(states, entry.state);
129 return spriteImageName("ground", def.key, state);
130}
131
132function blockSpriteName (catalog, block)
133{
134 const entry = normalizeBlock(block);
135 if (!entry)
136 { return null; }
137 const def = BLOCK_DEFINITIONS[entry.typeId];
138 if (!def)
139 { return null; }
140 const states = catalog.blocks?.[def.key]?.states ?? [];
141 const state = resolveState(states, entry.state);
142 return spriteImageName("block", def.key, state);
143}
144
145function groundBloomName (catalog, ground)
146{
147 const entry = normalizeGround(ground);
148 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
149 const type = catalog.grounds?.[def.key];
150 const state = resolveState(type?.states ?? [], entry.state);
151 if (!state || !type?.blooms?.[state])
152 { return null; }
153 return bloomImageName("ground", def.key, state);
154}
155
156function blockBloomName (catalog, block)
157{
158 const entry = normalizeBlock(block);
159 if (!entry)
160 { return null; }
161 const def = BLOCK_DEFINITIONS[entry.typeId];
162 if (!def)
163 { return null; }
164 const type = catalog.blocks?.[def.key];
165 const state = resolveState(type?.states ?? [], entry.state);
166 if (!state || !type?.blooms?.[state])
167 { return null; }
168 return bloomImageName("block", def.key, state);
169}
170
171function blockCatalogMeta (catalog, block)
172{
173 const entry = normalizeBlock(block);
174 if (!entry)
175 { return null; }
176 const def = BLOCK_DEFINITIONS[entry.typeId];
177 if (!def)
178 { return null; }
179 return catalog.blocks?.[def.key] ?? null;
180}
client/src/render/worldView.js +348 −104
@@ -2,7 +2,7 @@ import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BO
2 2 import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
3 3 import { itemSpriteName } from "/shared/definitions/items.js";
4 4 import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
5 import { resolveTileSprites } from "./tileRender.js";
5 import { bakeChunkAtlases } from "./chunkBake.js";
6 6 import {
7 7 frameworkImageFromCanvas,
8 8 invalidateCanvasTexture
@@ -40,7 +40,29 @@ const SPRITE_LIGHTING_FRAG = [
40 40 "}"
41 41 ].join("\n");
42 42
43 const ATLAS_LIGHTING_FRAG = [
44 "precision mediump float;",
45 "varying vec2 v_texCoord;",
46 "uniform sampler2D u_texture;",
47 "uniform sampler2D u_secondary;",
48 "uniform float u_ambientDark;",
49 "uniform float u_lightRow;",
50 "void main() {",
51 " vec4 color = texture2D(u_texture, v_texCoord);",
52 " if (color.a <= 0.0) { discard; }",
53 " vec2 lightUV = v_texCoord;",
54 " if (u_lightRow >= 0.0) {",
55 " lightUV.y = (u_lightRow + v_texCoord.y) / 16.0;",
56 " }",
57 " float lit = texture2D(u_secondary, lightUV).r;",
58 " float darkness = u_ambientDark * (1.0 - lit);",
59 " vec3 rgb = mix(color.rgb, vec3(0.0), darkness);",
60 " gl_FragColor = vec4(rgb, color.a);",
61 "}"
62 ].join("\n");
63
43 64 let spriteLightingShader = null;
65 let atlasLightingShader = null;
44 66
45 67 function getSpriteLightingShader ()
46 68 {
@@ -49,6 +71,13 @@ function getSpriteLightingShader ()
49 71 return spriteLightingShader;
50 72 }
51 73
74 function getAtlasLightingShader ()
75 {
76 if (!atlasLightingShader)
77 { atlasLightingShader = Shader.fragment(ATLAS_LIGHTING_FRAG); }
78 return atlasLightingShader;
79 }
80
52 81 export class WorldView
53 82 {
54 83 constructor (game, scene, catalog = { grounds: {}, blocks: {} })
@@ -59,6 +88,7 @@ export class WorldView
59 88 this.preview = null;
60 89 this.zoom = 2;
61 90 this.chunks = new Map();
91 this.bakedChunks = new Map();
62 92 this.tiles = new Map();
63 93 this.entities = new Map();
64 94 this.groundItems = new Map();
@@ -120,6 +150,7 @@ export class WorldView
120 150 {
121 151 const key = `${chunkX},${chunkY}`;
122 152 this.chunks.delete(key);
153 this.#destroyBakedChunk(key);
123 154 this.#destroyEdges(key);
124 155 for (const [tileKey, objects] of [...this.tiles.entries()])
125 156 {
@@ -237,6 +268,7 @@ export class WorldView
237 268 const existing = this.entities.get(payload.entityId);
238 269 if (!existing)
239 270 { return; }
271 existing.lightRadiusTiles = payload.lightRadiusTiles ?? existing.lightRadiusTiles ?? 0;
240 272 this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]);
241 273 this.#placeEntity(existing);
242 274 }
@@ -261,6 +293,7 @@ export class WorldView
261 293 item.displayName = payload.displayName;
262 294 item.sprite = payload.sprite;
263 295 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
296 this.#syncLitSprite(item.object, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);
264 297 }
265 298
266 299 despawnGroundItem (groundItemId)
@@ -307,6 +340,7 @@ export class WorldView
307 340 this.zoom = Math.min(max, Math.max(min, zoom));
308 341 for (const snapshot of this.chunks.values())
309 342 {
343 this.#layoutBakedChunk(snapshot);
310 344 this.#rebuildChunk(snapshot);
311 345 }
312 346 const size = this.tileSize();
@@ -521,13 +555,6 @@ export class WorldView
521 555 });
522 556 }
523 557
524 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY)
525 {
526 const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;
527 const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0;
528 this.#applySpriteLighting(object, (fromAlpha + toAlpha) / 2);
529 }
530
531 558 addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 0.5, durationMs = 250 })
532 559 {
533 560 this.dynamicLights.push({
@@ -629,6 +656,7 @@ export class WorldView
629 656 entity.talkable = !!payload.talkable;
630 657 entity.untargetable = !!payload.untargetable;
631 658 entity.freeFlight = !!payload.freeFlight;
659 entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;
632 660 if (payload.health != null)
633 661 { entity.health = payload.health; }
634 662 if (payload.maxHealth != null)
@@ -692,6 +720,7 @@ export class WorldView
692 720 { continue; }
693 721 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
694 722 bloom.renderer.layer = RENDER_LAYER_BLOOM;
723 this.#markUnlit(bloom);
695 724 this.scene.addObject(bloom);
696 725 entity.bloomOverlays.push(bloom);
697 726 }
@@ -718,14 +747,14 @@ export class WorldView
718 747 const tileShade = this.#entityShadeAlpha(entity, now);
719 748
720 749 entity.object.transform.rotation = walkTilt;
721 this.#applySpriteLighting(entity.object, tileShade, flashStrength);
750 this.#syncLitSprite(entity.object, tileShade, flashStrength);
722 751 this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY);
723 752 for (let index = 0; index < (entity.overlays ?? []).length; index++)
724 753 {
725 754 const overlay = entity.overlays[index];
726 755 const overlaySortY = entity.visualY + 0.5 * (index + 1);
727 756 overlay.transform.rotation = walkTilt;
728 this.#applySpriteLighting(overlay, tileShade, flashStrength);
757 this.#syncLitSprite(overlay, tileShade, flashStrength);
729 758 this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY);
730 759 }
731 760 for (const overlay of entity.bloomOverlays ?? [])
@@ -736,23 +765,33 @@ export class WorldView
736 765 this.#placeHpBar(entity, pivotX, pivotY);
737 766 }
738 767
739 #applySpriteLighting (object, darkness, flashStrength = 0)
768 #markUnlit (object)
740 769 {
741 770 if (!object?.renderer)
742 771 { return; }
772 object._lit = false;
773 object.renderer.shader = null;
774 object.renderer.shaderUniforms = null;
775 object.renderer.secondaryMap = null;
776 }
777
778 #syncLitSprite (object, darkness, flashStrength = 0)
779 {
780 if (!object?.renderer || object._lit === false)
781 { return; }
782 object._lit = true;
743 783 const dark = Math.min(1, Math.max(0, darkness ?? 0));
744 784 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
745 if (dark <= 0 && flash <= 0)
746 {
747 if (object.renderer.shader === getSpriteLightingShader())
748 {
749 object.renderer.shader = null;
750 object.renderer.shaderUniforms = null;
751 }
752 return;
753 }
754 785 object.renderer.shader = getSpriteLightingShader();
755 786 object.renderer.shaderUniforms = { u_darkness: dark, u_strength: flash };
787 object.renderer.secondaryMap = null;
788 }
789
790 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY)
791 {
792 const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;
793 const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0;
794 this.#syncLitSprite(object, (fromAlpha + toAlpha) / 2);
756 795 }
757 796
758 797 #syncHpBar (entity)
@@ -778,6 +817,7 @@ export class WorldView
778 817 entity.hpBarCanvas.height = HP_BAR_H;
779 818 const image = frameworkImageFromCanvas(entity.hpBarCanvas);
780 819 entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR);
820 this.#markUnlit(entity.hpBar);
781 821 this.scene.addObject(entity.hpBar);
782 822 }
783 823 drawHpBar(entity.hpBarCanvas, current, max);
@@ -806,18 +846,152 @@ export class WorldView
806 846
807 847 #rebuildChunk (snapshot)
808 848 {
849 this.#bakeAndPlaceChunk(snapshot);
850 const tall = new Set(
851 (this.bakedChunks.get(`${snapshot.chunkX},${snapshot.chunkY}`)?.tallBlocks ?? [])
852 .map((entry) => `${entry.tileX},${entry.tileY}`)
853 );
809 854 for (let localY = 0; localY < CHUNK_SIZE; localY++)
810 855 {
811 856 for (let localX = 0; localX < CHUNK_SIZE; localX++)
812 857 {
813 this.#drawTile(
814 snapshot.chunkX * CHUNK_SIZE + localX,
815 snapshot.chunkY * CHUNK_SIZE + localY
816 );
858 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
859 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
860 this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`));
817 861 }
818 862 }
819 863 }
820 864
865 #bakeAndPlaceChunk (snapshot)
866 {
867 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
868 const atlases = bakeChunkAtlases({
869 snapshot,
870 catalog: this.catalog,
871 images: this.game.images,
872 preview: this.preview
873 });
874 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
875 let baked = this.bakedChunks.get(key);
876 if (!baked)
877 {
878 const lightmapCanvas = makeLightmapCanvas(atlasPx);
879 baked = {
880 groundCanvas: atlases.ground,
881 blockCanvases: atlases.blockRows,
882 bloomCanvas: atlases.bloom,
883 lightmapCanvas,
884 groundImage: frameworkImageFromCanvas(atlases.ground),
885 blockImages: atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)),
886 bloomImage: frameworkImageFromCanvas(atlases.bloom),
887 lightmapImage: frameworkImageFromCanvas(lightmapCanvas),
888 groundObject: null,
889 blockObjects: [],
890 bloomObject: null,
891 tallBlocks: atlases.tallBlocks,
892 lightmapPixels: null
893 };
894 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
895 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);
896 this.scene.addObject(baked.groundObject);
897 for (let row = 0; row < CHUNK_SIZE; row++)
898 {
899 const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
900 this.#applyAtlasLighting(object, baked.lightmapImage, row);
901 this.scene.addObject(object);
902 baked.blockObjects.push(object);
903 }
904 baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK);
905 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
906 this.#markUnlit(baked.bloomObject);
907 this.scene.addObject(baked.bloomObject);
908 this.bakedChunks.set(key, baked);
909 }
910 else
911 {
912 copyCanvas(atlases.ground, baked.groundCanvas);
913 for (let row = 0; row < CHUNK_SIZE; row++)
914 { copyCanvas(atlases.blockRows[row], baked.blockCanvases[row]); }
915 copyCanvas(atlases.bloom, baked.bloomCanvas);
916 invalidateCanvasTexture(this.scene, baked.groundCanvas);
917 for (const canvas of baked.blockCanvases)
918 { invalidateCanvasTexture(this.scene, canvas); }
919 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
920 baked.tallBlocks = atlases.tallBlocks;
921 }
922 baked.chunkX = snapshot.chunkX;
923 baked.chunkY = snapshot.chunkY;
924 this.#layoutBakedChunk(snapshot);
925 }
926
927 #applyAtlasLighting (object, lightmapImage, lightRow)
928 {
929 if (!object?.renderer)
930 { return; }
931 object._lit = true;
932 object.renderer.shader = getAtlasLightingShader();
933 object.renderer.secondaryMap = lightmapImage;
934 object.renderer.shaderUniforms = {
935 u_ambientDark: 0,
936 u_lightRow: lightRow
937 };
938 }
939
940 #layoutBakedChunk (snapshot)
941 {
942 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
943 const baked = this.bakedChunks.get(key);
944 if (!baked)
945 { return; }
946 const size = this.tileSize();
947 const left = snapshot.chunkX * CHUNK_SIZE * size;
948 const top = snapshot.chunkY * CHUNK_SIZE * size;
949 const chunkPx = CHUNK_SIZE * size;
950 baked.groundObject.transform.position.x = left + chunkPx / 2;
951 baked.groundObject.transform.position.y = top + chunkPx / 2;
952 baked.groundObject.transform.size = new vector(chunkPx, chunkPx);
953 baked.groundObject.layer = LAYER_GROUND;
954
955 for (let row = 0; row < CHUNK_SIZE; row++)
956 {
957 const object = baked.blockObjects[row];
958 const rowY = top + row * size + size / 2;
959 object.transform.position.x = left + chunkPx / 2;
960 object.transform.position.y = rowY;
961 object.transform.size = new vector(chunkPx, size);
962 object.layer = ySortLayer(rowY, SORT_BLOCK);
963 }
964
965 baked.bloomObject.transform.position.x = left + chunkPx / 2;
966 baked.bloomObject.transform.position.y = top + chunkPx / 2;
967 baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
968 baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK);
969 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
970 this.#markSortDirty();
971 setNearestFilter(this.scene, baked.groundCanvas);
972 for (const canvas of baked.blockCanvases)
973 { setNearestFilter(this.scene, canvas); }
974 setNearestFilter(this.scene, baked.bloomCanvas);
975 setNearestFilter(this.scene, baked.lightmapCanvas);
976 }
977
978 #destroyBakedChunk (key)
979 {
980 const baked = this.bakedChunks.get(key);
981 if (!baked)
982 { return; }
983 baked.groundObject?.destroy();
984 for (const object of baked.blockObjects ?? [])
985 { object.destroy(); }
986 baked.bloomObject?.destroy();
987 invalidateCanvasTexture(this.scene, baked.groundCanvas);
988 for (const canvas of baked.blockCanvases ?? [])
989 { invalidateCanvasTexture(this.scene, canvas); }
990 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
991 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
992 this.bakedChunks.delete(key);
993 }
994
821 995 #redrawPreview ()
822 996 {
823 997 if (!this.preview)
@@ -827,7 +1001,7 @@ export class WorldView
827 1001 { this.#rebuildChunk(snapshot); }
828 1002 }
829 1003
830 #drawTile (tileX, tileY)
1004 #drawTile (tileX, tileY, forceTall = null)
831 1005 {
832 1006 const chunkX = Math.floor(tileX / CHUNK_SIZE);
833 1007 const chunkY = Math.floor(tileY / CHUNK_SIZE);
@@ -848,74 +1022,43 @@ export class WorldView
848 1022 objects.tileY = tileY;
849 1023 objects.chunkX = chunkX;
850 1024 objects.chunkY = chunkY;
851
852 let groundEntry = snapshot.grounds[index];
853 let blockEntry = snapshot.blocks[index];
854 if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY)
855 {
856 if (this.preview.ground !== undefined)
857 { groundEntry = this.preview.ground; }
858 if (this.preview.block !== undefined)
859 { blockEntry = this.preview.block; }
860 }
861
862 const size = this.tileSize();
863 const pivot = tilePivot(tileX, tileY, size);
864 1025 objects.light = snapshot.light[index] ?? 0;
865 const sprites = resolveTileSprites({
866 catalog: this.catalog,
867 ground: groundEntry,
868 block: blockEntry
869 });
870 const darkness = objects.shadeAlpha ?? 0;
871 1026
872 if (sprites.ground)
1027 if (objects.ground)
873 1028 {
874 objects.ground = this.#ensureSprite(objects.ground, sprites.ground, LAYER_GROUND);
875 if (objects.ground)
876 {
877 this.#placeTileSprite(objects.ground, pivot, LAYER_GROUND);
878 this.#applySpriteLighting(objects.ground, darkness);
879 }
1029 objects.ground.destroy();
1030 objects.ground = null;
880 1031 }
881 else
1032 if (objects.groundBloom)
882 1033 {
883 objects.ground?.destroy();
884 objects.ground = null;
1034 objects.groundBloom.destroy();
1035 objects.groundBloom = null;
885 1036 }
886 1037
887 objects.groundBloom = this.#placeBloomOverlay(
888 objects.groundBloom,
889 sprites.groundBloom,
890 pivot,
891 SORT_BLOCK,
892 LAYER_GROUND
893 );
894
895 if (sprites.block)
1038 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
1039 const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
1040 const isTall = forceTall === true || !!tallEntry;
1041 if (isTall && tallEntry)
896 1042 {
897 objects.block = this.#ensureSprite(objects.block, sprites.block, SORT_BLOCK);
1043 const pivot = tilePivot(tileX, tileY, this.tileSize());
1044 objects.block = this.#ensureSprite(objects.block, tallEntry.sprite, SORT_ENTITY);
898 1045 if (objects.block)
899 1046 {
900 this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_BLOCK);
901 this.#applySpriteLighting(objects.block, darkness);
1047 this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY);
1048 this.#syncLitSprite(objects.block, objects.shadeAlpha ?? 0);
902 1049 }
1050 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tallEntry.bloom, pivot, SORT_ENTITY);
903 1051 }
904 1052 else
905 1053 {
906 1054 objects.block?.destroy();
907 1055 objects.block = null;
1056 objects.blockBloom?.destroy();
1057 objects.blockBloom = null;
908 1058 }
909
910 objects.blockBloom = this.#placeBloomOverlay(
911 objects.blockBloom,
912 sprites.blockBloom,
913 pivot,
914 SORT_BLOCK
915 );
916 1059 }
917 1060
918 #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK, fixedLayer = null)
1061 #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK)
919 1062 {
920 1063 if (!name)
921 1064 {
@@ -926,23 +1069,11 @@ export class WorldView
926 1069 if (!object)
927 1070 { return null; }
928 1071 object.renderer.layer = RENDER_LAYER_BLOOM;
929 if (fixedLayer != null)
930 { this.#placeTileSprite(object, pivot, fixedLayer); }
931 else
932 { this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder); }
1072 this.#markUnlit(object);
1073 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder);
933 1074 return object;
934 1075 }
935 1076
936 #placeTileSprite (object, pivot, layer)
937 {
938 const size = this.tileSize();
939 object.transform.position.x = pivot.x;
940 object.transform.position.y = pivot.y;
941 object.transform.size = new vector(size, size);
942 object.layer = layer;
943 this.#markSortDirty();
944 }
945
946 1077 #placePivoted (object, pivotX, pivotY, sortY, subOrder)
947 1078 {
948 1079 const sprite = object?.renderer?.sprite;
@@ -970,6 +1101,7 @@ export class WorldView
970 1101 {
971 1102 existing?.destroy();
972 1103 existing = new GameObject(0, 0, sprite, layer);
1104 this.#syncLitSprite(existing, 0);
973 1105 this.scene.addObject(existing);
974 1106 this.#startIdleAnimation(existing);
975 1107 }
@@ -1046,6 +1178,7 @@ export class WorldView
1046 1178 }
1047 1179
1048 1180 existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE);
1181 this.#markUnlit(existing);
1049 1182 existing.renderer.visible = true;
1050 1183 existing.transform.position.x = x;
1051 1184 existing.transform.position.y = y;
@@ -1090,31 +1223,112 @@ export class WorldView
1090 1223 const ambientDark = nightFactor(hour, this.settings.nightDarkness);
1091 1224 const now = performance.now();
1092 1225 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
1226
1227 const activeLights = [...this.dynamicLights];
1228 const tileSize = this.tileSize();
1229 for (const entity of this.entities.values())
1230 {
1231 const radius = entity.lightRadiusTiles ?? 0;
1232 if (radius <= 0)
1233 { continue; }
1234 activeLights.push({
1235 worldX: entity.visualX / tileSize,
1236 worldY: entity.visualY / tileSize,
1237 radiusTiles: radius,
1238 intensity: 0.85
1239 });
1240 }
1241
1093 1242 for (const objects of this.tiles.values())
1094 1243 {
1095 const baked = Math.min(1, Math.max(0, (objects.light ?? 0) / 255));
1096 let dynamic = 0;
1097 for (const light of this.dynamicLights)
1244 const intensity = this.#tileLightIntensity(objects, activeLights);
1245 objects.shadeAlpha = ambientDark * (1 - intensity);
1246 if (objects.block)
1247 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
1248 }
1249
1250 for (const baked of this.bakedChunks.values())
1251 {
1252 this.#writeChunkLightmap(baked, activeLights);
1253 if (baked.groundObject?.renderer?.shaderUniforms)
1254 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
1255 for (const object of baked.blockObjects ?? [])
1098 1256 {
1099 const dx = (objects.tileX + 0.5) - light.worldX;
1100 const dy = (objects.tileY + 0.5) - light.worldY;
1101 const dist = Math.hypot(dx, dy);
1102 if (dist >= light.radiusTiles)
1103 { continue; }
1104 const falloff = 1 - dist / light.radiusTiles;
1105 dynamic = Math.max(dynamic, falloff * light.intensity);
1257 if (object?.renderer?.shaderUniforms)
1258 { object.renderer.shaderUniforms.u_ambientDark = ambientDark; }
1106 1259 }
1107 const intensity = Math.max(baked, dynamic);
1108 const alpha = ambientDark * (1 - intensity);
1109 objects.shadeAlpha = alpha;
1110 this.#applySpriteLighting(objects.ground, alpha);
1111 this.#applySpriteLighting(objects.block, alpha);
1112 1260 }
1261
1113 1262 for (const item of this.groundItems.values())
1114 1263 {
1115 1264 const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
1116 this.#applySpriteLighting(item.object, alpha);
1265 this.#syncLitSprite(item.object, alpha);
1266 }
1267 }
1268
1269 #tileLightIntensity (objects, activeLights)
1270 {
1271 const baked = Math.min(1, Math.max(0, (objects.light ?? 0) / 255));
1272 let dynamic = 0;
1273 for (const light of activeLights)
1274 {
1275 const dx = (objects.tileX + 0.5) - light.worldX;
1276 const dy = (objects.tileY + 0.5) - light.worldY;
1277 const dist = Math.hypot(dx, dy);
1278 if (dist >= light.radiusTiles)
1279 { continue; }
1280 const falloff = 1 - dist / light.radiusTiles;
1281 dynamic = Math.max(dynamic, falloff * light.intensity);
1282 }
1283 return Math.max(baked, dynamic);
1284 }
1285
1286 #writeChunkLightmap (baked, activeLights)
1287 {
1288 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
1289 if (!snapshot)
1290 { return; }
1291 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
1292 const pixelCount = atlasPx * atlasPx * 4;
1293 if (!baked.lightmapPixels || baked.lightmapPixels.length !== pixelCount)
1294 { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); }
1295 const pixels = baked.lightmapPixels;
1296 for (let localY = 0; localY < CHUNK_SIZE; localY++)
1297 {
1298 for (let localX = 0; localX < CHUNK_SIZE; localX++)
1299 {
1300 const tileX = baked.chunkX * CHUNK_SIZE + localX;
1301 const tileY = baked.chunkY * CHUNK_SIZE + localY;
1302 const index = localY * CHUNK_SIZE + localX;
1303 const tileObjects = this.tiles.get(`${tileX},${tileY}`);
1304 let intensity;
1305 if (tileObjects)
1306 {
1307 intensity = this.#tileLightIntensity(tileObjects, activeLights);
1308 }
1309 else
1310 {
1311 intensity = Math.min(1, Math.max(0, (snapshot.light[index] ?? 0) / 255));
1312 }
1313 const value = Math.round(Math.min(1, intensity) * 255);
1314 const baseX = localX * SPRITE_SIZE_PX;
1315 const baseY = localY * SPRITE_SIZE_PX;
1316 for (let py = 0; py < SPRITE_SIZE_PX; py++)
1317 {
1318 for (let px = 0; px < SPRITE_SIZE_PX; px++)
1319 {
1320 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
1321 pixels[offset] = value;
1322 pixels[offset + 1] = value;
1323 pixels[offset + 2] = value;
1324 pixels[offset + 3] = 255;
1325 }
1326 }
1327 }
1117 1328 }
1329 const ctx = baked.lightmapCanvas.getContext("2d");
1330 ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0);
1331 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
1118 1332 }
1119 1333
1120 1334 #updateSwipes (now)
@@ -1224,6 +1438,36 @@ function lerp (a, b, t)
1224 1438 return a + (b - a) * Math.min(1, Math.max(0, t));
1225 1439 }
1226 1440
1441 function makeLightmapCanvas (size)
1442 {
1443 const canvas = document.createElement("canvas");
1444 canvas.width = size;
1445 canvas.height = size;
1446 return canvas;
1447 }
1448
1449 function copyCanvas (source, dest)
1450 {
1451 const ctx = dest.getContext("2d");
1452 ctx.imageSmoothingEnabled = false;
1453 ctx.clearRect(0, 0, dest.width, dest.height);
1454 ctx.drawImage(source, 0, 0);
1455 }
1456
1457 function setNearestFilter (scene, canvas)
1458 {
1459 const glContext = scene?.glContext;
1460 if (!glContext || !canvas)
1461 { return; }
1462 const texture = glContext.getTexture(canvas);
1463 if (!texture)
1464 { return; }
1465 const gl = glContext.gl;
1466 gl.bindTexture(gl.TEXTURE_2D, texture);
1467 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
1468 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
1469 }
1470
1227 1471 function drawHpBar (canvas, current, max)
1228 1472 {
1229 1473 const ctx = canvas.getContext("2d");
@@ -2,7 +2,7 @@ import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BO
2import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
2import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
3import { itemSpriteName } from "/shared/definitions/items.js";
3import { itemSpriteName } from "/shared/definitions/items.js";
4import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
4import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
5import { resolveTileSprites } from "./tileRender.js";
5import { bakeChunkAtlases } from "./chunkBake.js";
6import {
6import {
7 frameworkImageFromCanvas,
7 frameworkImageFromCanvas,
8 invalidateCanvasTexture
8 invalidateCanvasTexture
@@ -40,7 +40,29 @@ const SPRITE_LIGHTING_FRAG = [
40 "}"
40 "}"
41].join("\n");
41].join("\n");
42
42
43const ATLAS_LIGHTING_FRAG = [
44 "precision mediump float;",
45 "varying vec2 v_texCoord;",
46 "uniform sampler2D u_texture;",
47 "uniform sampler2D u_secondary;",
48 "uniform float u_ambientDark;",
49 "uniform float u_lightRow;",
50 "void main() {",
51 " vec4 color = texture2D(u_texture, v_texCoord);",
52 " if (color.a <= 0.0) { discard; }",
53 " vec2 lightUV = v_texCoord;",
54 " if (u_lightRow >= 0.0) {",
55 " lightUV.y = (u_lightRow + v_texCoord.y) / 16.0;",
56 " }",
57 " float lit = texture2D(u_secondary, lightUV).r;",
58 " float darkness = u_ambientDark * (1.0 - lit);",
59 " vec3 rgb = mix(color.rgb, vec3(0.0), darkness);",
60 " gl_FragColor = vec4(rgb, color.a);",
61 "}"
62].join("\n");
63
43let spriteLightingShader = null;
64let spriteLightingShader = null;
65let atlasLightingShader = null;
44
66
45function getSpriteLightingShader ()
67function getSpriteLightingShader ()
46{
68{
@@ -49,6 +71,13 @@ function getSpriteLightingShader ()
49 return spriteLightingShader;
71 return spriteLightingShader;
50}
72}
51
73
74function getAtlasLightingShader ()
75{
76 if (!atlasLightingShader)
77 { atlasLightingShader = Shader.fragment(ATLAS_LIGHTING_FRAG); }
78 return atlasLightingShader;
79}
80
52export class WorldView
81export class WorldView
53{
82{
54 constructor (game, scene, catalog = { grounds: {}, blocks: {} })
83 constructor (game, scene, catalog = { grounds: {}, blocks: {} })
@@ -59,6 +88,7 @@ export class WorldView
59 this.preview = null;
88 this.preview = null;
60 this.zoom = 2;
89 this.zoom = 2;
61 this.chunks = new Map();
90 this.chunks = new Map();
91 this.bakedChunks = new Map();
62 this.tiles = new Map();
92 this.tiles = new Map();
63 this.entities = new Map();
93 this.entities = new Map();
64 this.groundItems = new Map();
94 this.groundItems = new Map();
@@ -120,6 +150,7 @@ export class WorldView
120 {
150 {
121 const key = `${chunkX},${chunkY}`;
151 const key = `${chunkX},${chunkY}`;
122 this.chunks.delete(key);
152 this.chunks.delete(key);
153 this.#destroyBakedChunk(key);
123 this.#destroyEdges(key);
154 this.#destroyEdges(key);
124 for (const [tileKey, objects] of [...this.tiles.entries()])
155 for (const [tileKey, objects] of [...this.tiles.entries()])
125 {
156 {
@@ -237,6 +268,7 @@ export class WorldView
237 const existing = this.entities.get(payload.entityId);
268 const existing = this.entities.get(payload.entityId);
238 if (!existing)
269 if (!existing)
239 { return; }
270 { return; }
271 existing.lightRadiusTiles = payload.lightRadiusTiles ?? existing.lightRadiusTiles ?? 0;
240 this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]);
272 this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]);
241 this.#placeEntity(existing);
273 this.#placeEntity(existing);
242 }
274 }
@@ -261,6 +293,7 @@ export class WorldView
261 item.displayName = payload.displayName;
293 item.displayName = payload.displayName;
262 item.sprite = payload.sprite;
294 item.sprite = payload.sprite;
263 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
295 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
296 this.#syncLitSprite(item.object, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);
264 }
297 }
265
298
266 despawnGroundItem (groundItemId)
299 despawnGroundItem (groundItemId)
@@ -307,6 +340,7 @@ export class WorldView
307 this.zoom = Math.min(max, Math.max(min, zoom));
340 this.zoom = Math.min(max, Math.max(min, zoom));
308 for (const snapshot of this.chunks.values())
341 for (const snapshot of this.chunks.values())
309 {
342 {
343 this.#layoutBakedChunk(snapshot);
310 this.#rebuildChunk(snapshot);
344 this.#rebuildChunk(snapshot);
311 }
345 }
312 const size = this.tileSize();
346 const size = this.tileSize();
@@ -521,13 +555,6 @@ export class WorldView
521 });
555 });
522 }
556 }
523
557
524 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY)
525 {
526 const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;
527 const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0;
528 this.#applySpriteLighting(object, (fromAlpha + toAlpha) / 2);
529 }
530
531 addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 0.5, durationMs = 250 })
558 addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 0.5, durationMs = 250 })
532 {
559 {
533 this.dynamicLights.push({
560 this.dynamicLights.push({
@@ -629,6 +656,7 @@ export class WorldView
629 entity.talkable = !!payload.talkable;
656 entity.talkable = !!payload.talkable;
630 entity.untargetable = !!payload.untargetable;
657 entity.untargetable = !!payload.untargetable;
631 entity.freeFlight = !!payload.freeFlight;
658 entity.freeFlight = !!payload.freeFlight;
659 entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;
632 if (payload.health != null)
660 if (payload.health != null)
633 { entity.health = payload.health; }
661 { entity.health = payload.health; }
634 if (payload.maxHealth != null)
662 if (payload.maxHealth != null)
@@ -692,6 +720,7 @@ export class WorldView
692 { continue; }
720 { continue; }
693 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
721 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
694 bloom.renderer.layer = RENDER_LAYER_BLOOM;
722 bloom.renderer.layer = RENDER_LAYER_BLOOM;
723 this.#markUnlit(bloom);
695 this.scene.addObject(bloom);
724 this.scene.addObject(bloom);
696 entity.bloomOverlays.push(bloom);
725 entity.bloomOverlays.push(bloom);
697 }
726 }
@@ -718,14 +747,14 @@ export class WorldView
718 const tileShade = this.#entityShadeAlpha(entity, now);
747 const tileShade = this.#entityShadeAlpha(entity, now);
719
748
720 entity.object.transform.rotation = walkTilt;
749 entity.object.transform.rotation = walkTilt;
721 this.#applySpriteLighting(entity.object, tileShade, flashStrength);
750 this.#syncLitSprite(entity.object, tileShade, flashStrength);
722 this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY);
751 this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY);
723 for (let index = 0; index < (entity.overlays ?? []).length; index++)
752 for (let index = 0; index < (entity.overlays ?? []).length; index++)
724 {
753 {
725 const overlay = entity.overlays[index];
754 const overlay = entity.overlays[index];
726 const overlaySortY = entity.visualY + 0.5 * (index + 1);
755 const overlaySortY = entity.visualY + 0.5 * (index + 1);
727 overlay.transform.rotation = walkTilt;
756 overlay.transform.rotation = walkTilt;
728 this.#applySpriteLighting(overlay, tileShade, flashStrength);
757 this.#syncLitSprite(overlay, tileShade, flashStrength);
729 this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY);
758 this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY);
730 }
759 }
731 for (const overlay of entity.bloomOverlays ?? [])
760 for (const overlay of entity.bloomOverlays ?? [])
@@ -736,23 +765,33 @@ export class WorldView
736 this.#placeHpBar(entity, pivotX, pivotY);
765 this.#placeHpBar(entity, pivotX, pivotY);
737 }
766 }
738
767
739 #applySpriteLighting (object, darkness, flashStrength = 0)
768 #markUnlit (object)
740 {
769 {
741 if (!object?.renderer)
770 if (!object?.renderer)
742 { return; }
771 { return; }
772 object._lit = false;
773 object.renderer.shader = null;
774 object.renderer.shaderUniforms = null;
775 object.renderer.secondaryMap = null;
776 }
777
778 #syncLitSprite (object, darkness, flashStrength = 0)
779 {
780 if (!object?.renderer || object._lit === false)
781 { return; }
782 object._lit = true;
743 const dark = Math.min(1, Math.max(0, darkness ?? 0));
783 const dark = Math.min(1, Math.max(0, darkness ?? 0));
744 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
784 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
745 if (dark <= 0 && flash <= 0)
746 {
747 if (object.renderer.shader === getSpriteLightingShader())
748 {
749 object.renderer.shader = null;
750 object.renderer.shaderUniforms = null;
751 }
752 return;
753 }
754 object.renderer.shader = getSpriteLightingShader();
785 object.renderer.shader = getSpriteLightingShader();
755 object.renderer.shaderUniforms = { u_darkness: dark, u_strength: flash };
786 object.renderer.shaderUniforms = { u_darkness: dark, u_strength: flash };
787 object.renderer.secondaryMap = null;
788 }
789
790 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY)
791 {
792 const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;
793 const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0;
794 this.#syncLitSprite(object, (fromAlpha + toAlpha) / 2);
756 }
795 }
757
796
758 #syncHpBar (entity)
797 #syncHpBar (entity)
@@ -778,6 +817,7 @@ export class WorldView
778 entity.hpBarCanvas.height = HP_BAR_H;
817 entity.hpBarCanvas.height = HP_BAR_H;
779 const image = frameworkImageFromCanvas(entity.hpBarCanvas);
818 const image = frameworkImageFromCanvas(entity.hpBarCanvas);
780 entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR);
819 entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR);
820 this.#markUnlit(entity.hpBar);
781 this.scene.addObject(entity.hpBar);
821 this.scene.addObject(entity.hpBar);
782 }
822 }
783 drawHpBar(entity.hpBarCanvas, current, max);
823 drawHpBar(entity.hpBarCanvas, current, max);
@@ -806,18 +846,152 @@ export class WorldView
806
846
807 #rebuildChunk (snapshot)
847 #rebuildChunk (snapshot)
808 {
848 {
849 this.#bakeAndPlaceChunk(snapshot);
850 const tall = new Set(
851 (this.bakedChunks.get(`${snapshot.chunkX},${snapshot.chunkY}`)?.tallBlocks ?? [])
852 .map((entry) => `${entry.tileX},${entry.tileY}`)
853 );
809 for (let localY = 0; localY < CHUNK_SIZE; localY++)
854 for (let localY = 0; localY < CHUNK_SIZE; localY++)
810 {
855 {
811 for (let localX = 0; localX < CHUNK_SIZE; localX++)
856 for (let localX = 0; localX < CHUNK_SIZE; localX++)
812 {
857 {
813 this.#drawTile(
858 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
814 snapshot.chunkX * CHUNK_SIZE + localX,
859 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
815 snapshot.chunkY * CHUNK_SIZE + localY
860 this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`));
816 );
817 }
861 }
818 }
862 }
819 }
863 }
820
864
865 #bakeAndPlaceChunk (snapshot)
866 {
867 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
868 const atlases = bakeChunkAtlases({
869 snapshot,
870 catalog: this.catalog,
871 images: this.game.images,
872 preview: this.preview
873 });
874 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
875 let baked = this.bakedChunks.get(key);
876 if (!baked)
877 {
878 const lightmapCanvas = makeLightmapCanvas(atlasPx);
879 baked = {
880 groundCanvas: atlases.ground,
881 blockCanvases: atlases.blockRows,
882 bloomCanvas: atlases.bloom,
883 lightmapCanvas,
884 groundImage: frameworkImageFromCanvas(atlases.ground),
885 blockImages: atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)),
886 bloomImage: frameworkImageFromCanvas(atlases.bloom),
887 lightmapImage: frameworkImageFromCanvas(lightmapCanvas),
888 groundObject: null,
889 blockObjects: [],
890 bloomObject: null,
891 tallBlocks: atlases.tallBlocks,
892 lightmapPixels: null
893 };
894 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
895 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);
896 this.scene.addObject(baked.groundObject);
897 for (let row = 0; row < CHUNK_SIZE; row++)
898 {
899 const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
900 this.#applyAtlasLighting(object, baked.lightmapImage, row);
901 this.scene.addObject(object);
902 baked.blockObjects.push(object);
903 }
904 baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK);
905 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
906 this.#markUnlit(baked.bloomObject);
907 this.scene.addObject(baked.bloomObject);
908 this.bakedChunks.set(key, baked);
909 }
910 else
911 {
912 copyCanvas(atlases.ground, baked.groundCanvas);
913 for (let row = 0; row < CHUNK_SIZE; row++)
914 { copyCanvas(atlases.blockRows[row], baked.blockCanvases[row]); }
915 copyCanvas(atlases.bloom, baked.bloomCanvas);
916 invalidateCanvasTexture(this.scene, baked.groundCanvas);
917 for (const canvas of baked.blockCanvases)
918 { invalidateCanvasTexture(this.scene, canvas); }
919 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
920 baked.tallBlocks = atlases.tallBlocks;
921 }
922 baked.chunkX = snapshot.chunkX;
923 baked.chunkY = snapshot.chunkY;
924 this.#layoutBakedChunk(snapshot);
925 }
926
927 #applyAtlasLighting (object, lightmapImage, lightRow)
928 {
929 if (!object?.renderer)
930 { return; }
931 object._lit = true;
932 object.renderer.shader = getAtlasLightingShader();
933 object.renderer.secondaryMap = lightmapImage;
934 object.renderer.shaderUniforms = {
935 u_ambientDark: 0,
936 u_lightRow: lightRow
937 };
938 }
939
940 #layoutBakedChunk (snapshot)
941 {
942 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
943 const baked = this.bakedChunks.get(key);
944 if (!baked)
945 { return; }
946 const size = this.tileSize();
947 const left = snapshot.chunkX * CHUNK_SIZE * size;
948 const top = snapshot.chunkY * CHUNK_SIZE * size;
949 const chunkPx = CHUNK_SIZE * size;
950 baked.groundObject.transform.position.x = left + chunkPx / 2;
951 baked.groundObject.transform.position.y = top + chunkPx / 2;
952 baked.groundObject.transform.size = new vector(chunkPx, chunkPx);
953 baked.groundObject.layer = LAYER_GROUND;
954
955 for (let row = 0; row < CHUNK_SIZE; row++)
956 {
957 const object = baked.blockObjects[row];
958 const rowY = top + row * size + size / 2;
959 object.transform.position.x = left + chunkPx / 2;
960 object.transform.position.y = rowY;
961 object.transform.size = new vector(chunkPx, size);
962 object.layer = ySortLayer(rowY, SORT_BLOCK);
963 }
964
965 baked.bloomObject.transform.position.x = left + chunkPx / 2;
966 baked.bloomObject.transform.position.y = top + chunkPx / 2;
967 baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
968 baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK);
969 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
970 this.#markSortDirty();
971 setNearestFilter(this.scene, baked.groundCanvas);
972 for (const canvas of baked.blockCanvases)
973 { setNearestFilter(this.scene, canvas); }
974 setNearestFilter(this.scene, baked.bloomCanvas);
975 setNearestFilter(this.scene, baked.lightmapCanvas);
976 }
977
978 #destroyBakedChunk (key)
979 {
980 const baked = this.bakedChunks.get(key);
981 if (!baked)
982 { return; }
983 baked.groundObject?.destroy();
984 for (const object of baked.blockObjects ?? [])
985 { object.destroy(); }
986 baked.bloomObject?.destroy();
987 invalidateCanvasTexture(this.scene, baked.groundCanvas);
988 for (const canvas of baked.blockCanvases ?? [])
989 { invalidateCanvasTexture(this.scene, canvas); }
990 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
991 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
992 this.bakedChunks.delete(key);
993 }
994
821 #redrawPreview ()
995 #redrawPreview ()
822 {
996 {
823 if (!this.preview)
997 if (!this.preview)
@@ -827,7 +1001,7 @@ export class WorldView
827 { this.#rebuildChunk(snapshot); }
1001 { this.#rebuildChunk(snapshot); }
828 }
1002 }
829
1003
830 #drawTile (tileX, tileY)
1004 #drawTile (tileX, tileY, forceTall = null)
831 {
1005 {
832 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1006 const chunkX = Math.floor(tileX / CHUNK_SIZE);
833 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1007 const chunkY = Math.floor(tileY / CHUNK_SIZE);
@@ -848,74 +1022,43 @@ export class WorldView
848 objects.tileY = tileY;
1022 objects.tileY = tileY;
849 objects.chunkX = chunkX;
1023 objects.chunkX = chunkX;
850 objects.chunkY = chunkY;
1024 objects.chunkY = chunkY;
851
852 let groundEntry = snapshot.grounds[index];
853 let blockEntry = snapshot.blocks[index];
854 if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY)
855 {
856 if (this.preview.ground !== undefined)
857 { groundEntry = this.preview.ground; }
858 if (this.preview.block !== undefined)
859 { blockEntry = this.preview.block; }
860 }
861
862 const size = this.tileSize();
863 const pivot = tilePivot(tileX, tileY, size);
864 objects.light = snapshot.light[index] ?? 0;
1025 objects.light = snapshot.light[index] ?? 0;
865 const sprites = resolveTileSprites({
866 catalog: this.catalog,
867 ground: groundEntry,
868 block: blockEntry
869 });
870 const darkness = objects.shadeAlpha ?? 0;
871
1026
872 if (sprites.ground)
1027 if (objects.ground)
873 {
1028 {
874 objects.ground = this.#ensureSprite(objects.ground, sprites.ground, LAYER_GROUND);
1029 objects.ground.destroy();
875 if (objects.ground)
1030 objects.ground = null;
876 {
877 this.#placeTileSprite(objects.ground, pivot, LAYER_GROUND);
878 this.#applySpriteLighting(objects.ground, darkness);
879 }
880 }
1031 }
881 else
1032 if (objects.groundBloom)
882 {
1033 {
883 objects.ground?.destroy();
1034 objects.groundBloom.destroy();
884 objects.ground = null;
1035 objects.groundBloom = null;
885 }
1036 }
886
1037
887 objects.groundBloom = this.#placeBloomOverlay(
1038 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
888 objects.groundBloom,
1039 const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
889 sprites.groundBloom,
1040 const isTall = forceTall === true || !!tallEntry;
890 pivot,
1041 if (isTall && tallEntry)
891 SORT_BLOCK,
892 LAYER_GROUND
893 );
894
895 if (sprites.block)
896 {
1042 {
897 objects.block = this.#ensureSprite(objects.block, sprites.block, SORT_BLOCK);
1043 const pivot = tilePivot(tileX, tileY, this.tileSize());
1044 objects.block = this.#ensureSprite(objects.block, tallEntry.sprite, SORT_ENTITY);
898 if (objects.block)
1045 if (objects.block)
899 {
1046 {
900 this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_BLOCK);
1047 this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY);
901 this.#applySpriteLighting(objects.block, darkness);
1048 this.#syncLitSprite(objects.block, objects.shadeAlpha ?? 0);
902 }
1049 }
1050 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tallEntry.bloom, pivot, SORT_ENTITY);
903 }
1051 }
904 else
1052 else
905 {
1053 {
906 objects.block?.destroy();
1054 objects.block?.destroy();
907 objects.block = null;
1055 objects.block = null;
1056 objects.blockBloom?.destroy();
1057 objects.blockBloom = null;
908 }
1058 }
909
910 objects.blockBloom = this.#placeBloomOverlay(
911 objects.blockBloom,
912 sprites.blockBloom,
913 pivot,
914 SORT_BLOCK
915 );
916 }
1059 }
917
1060
918 #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK, fixedLayer = null)
1061 #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK)
919 {
1062 {
920 if (!name)
1063 if (!name)
921 {
1064 {
@@ -926,23 +1069,11 @@ export class WorldView
926 if (!object)
1069 if (!object)
927 { return null; }
1070 { return null; }
928 object.renderer.layer = RENDER_LAYER_BLOOM;
1071 object.renderer.layer = RENDER_LAYER_BLOOM;
929 if (fixedLayer != null)
1072 this.#markUnlit(object);
930 { this.#placeTileSprite(object, pivot, fixedLayer); }
1073 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder);
931 else
932 { this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder); }
933 return object;
1074 return object;
934 }
1075 }
935
1076
936 #placeTileSprite (object, pivot, layer)
937 {
938 const size = this.tileSize();
939 object.transform.position.x = pivot.x;
940 object.transform.position.y = pivot.y;
941 object.transform.size = new vector(size, size);
942 object.layer = layer;
943 this.#markSortDirty();
944 }
945
946 #placePivoted (object, pivotX, pivotY, sortY, subOrder)
1077 #placePivoted (object, pivotX, pivotY, sortY, subOrder)
947 {
1078 {
948 const sprite = object?.renderer?.sprite;
1079 const sprite = object?.renderer?.sprite;
@@ -970,6 +1101,7 @@ export class WorldView
970 {
1101 {
971 existing?.destroy();
1102 existing?.destroy();
972 existing = new GameObject(0, 0, sprite, layer);
1103 existing = new GameObject(0, 0, sprite, layer);
1104 this.#syncLitSprite(existing, 0);
973 this.scene.addObject(existing);
1105 this.scene.addObject(existing);
974 this.#startIdleAnimation(existing);
1106 this.#startIdleAnimation(existing);
975 }
1107 }
@@ -1046,6 +1178,7 @@ export class WorldView
1046 }
1178 }
1047
1179
1048 existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE);
1180 existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE);
1181 this.#markUnlit(existing);
1049 existing.renderer.visible = true;
1182 existing.renderer.visible = true;
1050 existing.transform.position.x = x;
1183 existing.transform.position.x = x;
1051 existing.transform.position.y = y;
1184 existing.transform.position.y = y;
@@ -1090,31 +1223,112 @@ export class WorldView
1090 const ambientDark = nightFactor(hour, this.settings.nightDarkness);
1223 const ambientDark = nightFactor(hour, this.settings.nightDarkness);
1091 const now = performance.now();
1224 const now = performance.now();
1092 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
1225 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
1226
1227 const activeLights = [...this.dynamicLights];
1228 const tileSize = this.tileSize();
1229 for (const entity of this.entities.values())
1230 {
1231 const radius = entity.lightRadiusTiles ?? 0;
1232 if (radius <= 0)
1233 { continue; }
1234 activeLights.push({
1235 worldX: entity.visualX / tileSize,
1236 worldY: entity.visualY / tileSize,
1237 radiusTiles: radius,
1238 intensity: 0.85
1239 });
1240 }
1241
1093 for (const objects of this.tiles.values())
1242 for (const objects of this.tiles.values())
1094 {
1243 {
1095 const baked = Math.min(1, Math.max(0, (objects.light ?? 0) / 255));
1244 const intensity = this.#tileLightIntensity(objects, activeLights);
1096 let dynamic = 0;
1245 objects.shadeAlpha = ambientDark * (1 - intensity);
1097 for (const light of this.dynamicLights)
1246 if (objects.block)
1247 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
1248 }
1249
1250 for (const baked of this.bakedChunks.values())
1251 {
1252 this.#writeChunkLightmap(baked, activeLights);
1253 if (baked.groundObject?.renderer?.shaderUniforms)
1254 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
1255 for (const object of baked.blockObjects ?? [])
1098 {
1256 {
1099 const dx = (objects.tileX + 0.5) - light.worldX;
1257 if (object?.renderer?.shaderUniforms)
1100 const dy = (objects.tileY + 0.5) - light.worldY;
1258 { object.renderer.shaderUniforms.u_ambientDark = ambientDark; }
1101 const dist = Math.hypot(dx, dy);
1102 if (dist >= light.radiusTiles)
1103 { continue; }
1104 const falloff = 1 - dist / light.radiusTiles;
1105 dynamic = Math.max(dynamic, falloff * light.intensity);
1106 }
1259 }
1107 const intensity = Math.max(baked, dynamic);
1108 const alpha = ambientDark * (1 - intensity);
1109 objects.shadeAlpha = alpha;
1110 this.#applySpriteLighting(objects.ground, alpha);
1111 this.#applySpriteLighting(objects.block, alpha);
1112 }
1260 }
1261
1113 for (const item of this.groundItems.values())
1262 for (const item of this.groundItems.values())
1114 {
1263 {
1115 const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
1264 const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
1116 this.#applySpriteLighting(item.object, alpha);
1265 this.#syncLitSprite(item.object, alpha);
1266 }
1267 }
1268
1269 #tileLightIntensity (objects, activeLights)
1270 {
1271 const baked = Math.min(1, Math.max(0, (objects.light ?? 0) / 255));
1272 let dynamic = 0;
1273 for (const light of activeLights)
1274 {
1275 const dx = (objects.tileX + 0.5) - light.worldX;
1276 const dy = (objects.tileY + 0.5) - light.worldY;
1277 const dist = Math.hypot(dx, dy);
1278 if (dist >= light.radiusTiles)
1279 { continue; }
1280 const falloff = 1 - dist / light.radiusTiles;
1281 dynamic = Math.max(dynamic, falloff * light.intensity);
1282 }
1283 return Math.max(baked, dynamic);
1284 }
1285
1286 #writeChunkLightmap (baked, activeLights)
1287 {
1288 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
1289 if (!snapshot)
1290 { return; }
1291 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
1292 const pixelCount = atlasPx * atlasPx * 4;
1293 if (!baked.lightmapPixels || baked.lightmapPixels.length !== pixelCount)
1294 { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); }
1295 const pixels = baked.lightmapPixels;
1296 for (let localY = 0; localY < CHUNK_SIZE; localY++)
1297 {
1298 for (let localX = 0; localX < CHUNK_SIZE; localX++)
1299 {
1300 const tileX = baked.chunkX * CHUNK_SIZE + localX;
1301 const tileY = baked.chunkY * CHUNK_SIZE + localY;
1302 const index = localY * CHUNK_SIZE + localX;
1303 const tileObjects = this.tiles.get(`${tileX},${tileY}`);
1304 let intensity;
1305 if (tileObjects)
1306 {
1307 intensity = this.#tileLightIntensity(tileObjects, activeLights);
1308 }
1309 else
1310 {
1311 intensity = Math.min(1, Math.max(0, (snapshot.light[index] ?? 0) / 255));
1312 }
1313 const value = Math.round(Math.min(1, intensity) * 255);
1314 const baseX = localX * SPRITE_SIZE_PX;
1315 const baseY = localY * SPRITE_SIZE_PX;
1316 for (let py = 0; py < SPRITE_SIZE_PX; py++)
1317 {
1318 for (let px = 0; px < SPRITE_SIZE_PX; px++)
1319 {
1320 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
1321 pixels[offset] = value;
1322 pixels[offset + 1] = value;
1323 pixels[offset + 2] = value;
1324 pixels[offset + 3] = 255;
1325 }
1326 }
1327 }
1117 }
1328 }
1329 const ctx = baked.lightmapCanvas.getContext("2d");
1330 ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0);
1331 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
1118 }
1332 }
1119
1333
1120 #updateSwipes (now)
1334 #updateSwipes (now)
@@ -1224,6 +1438,36 @@ function lerp (a, b, t)
1224 return a + (b - a) * Math.min(1, Math.max(0, t));
1438 return a + (b - a) * Math.min(1, Math.max(0, t));
1225}
1439}
1226
1440
1441function makeLightmapCanvas (size)
1442{
1443 const canvas = document.createElement("canvas");
1444 canvas.width = size;
1445 canvas.height = size;
1446 return canvas;
1447}
1448
1449function copyCanvas (source, dest)
1450{
1451 const ctx = dest.getContext("2d");
1452 ctx.imageSmoothingEnabled = false;
1453 ctx.clearRect(0, 0, dest.width, dest.height);
1454 ctx.drawImage(source, 0, 0);
1455}
1456
1457function setNearestFilter (scene, canvas)
1458{
1459 const glContext = scene?.glContext;
1460 if (!glContext || !canvas)
1461 { return; }
1462 const texture = glContext.getTexture(canvas);
1463 if (!texture)
1464 { return; }
1465 const gl = glContext.gl;
1466 gl.bindTexture(gl.TEXTURE_2D, texture);
1467 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
1468 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
1469}
1470
1227function drawHpBar (canvas, current, max)
1471function drawHpBar (canvas, current, max)
1228{
1472{
1229 const ctx = canvas.getContext("2d");
1473 const ctx = canvas.getContext("2d");
server/src/ecs/serialize.js +6 −3
@@ -1,5 +1,5 @@
1 1 import { Component } from "./components.js";
2 import { EQUIPMENT_DRAW_ORDER, itemEquipSprite } from "../../../shared/definitions/items.js";
2 import { EQUIPMENT_DRAW_ORDER, equippedLightRadiusTiles, itemEquipSprite } from "../../../shared/definitions/items.js";
3 3 import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
4 4 import { mobDefinition } from "../../../shared/definitions/mobs.js";
5 5 import { mobCanFight } from "../../../shared/definitions/mobCombat.js";
@@ -65,6 +65,7 @@ export function publicEntityView (ecs, entityId)
65 65 const creature = ecs.get(handle, Component.creature);
66 66 const flight = ecs.get(handle, Component.flight);
67 67 const health = ecs.get(handle, Component.health);
68 const equipment = ecs.get(handle, Component.equipment);
68 69 const layers = appearanceLayers(ecs, handle, appearance);
69 70 const mob = creature ? mobDefinition(creature.mobTypeId) : null;
70 71 const isMob = !!creature && !character;
@@ -88,7 +89,8 @@ export function publicEntityView (ecs, entityId)
88 89 health: isMob && health ? health.current : undefined,
89 90 maxHealth: isMob && health ? health.max : undefined,
90 91 sprite: layers[0]?.sprite ?? null,
91 layers
92 layers,
93 lightRadiusTiles: equippedLightRadiusTiles(equipment)
92 94 };
93 95 }
94 96
@@ -166,7 +168,8 @@ export function replicationAppearance (view)
166 168 tileX: view.tileX,
167 169 tileY: view.tileY,
168 170 sprite: view.sprite ?? null,
169 layers: view.layers ?? []
171 layers: view.layers ?? [],
172 lightRadiusTiles: view.lightRadiusTiles ?? 0
170 173 };
171 174 }
172 175
@@ -1,5 +1,5 @@
1import { Component } from "./components.js";
1import { Component } from "./components.js";
2import { EQUIPMENT_DRAW_ORDER, itemEquipSprite } from "../../../shared/definitions/items.js";
2import { EQUIPMENT_DRAW_ORDER, equippedLightRadiusTiles, itemEquipSprite } from "../../../shared/definitions/items.js";
3import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
3import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
4import { mobDefinition } from "../../../shared/definitions/mobs.js";
4import { mobDefinition } from "../../../shared/definitions/mobs.js";
5import { mobCanFight } from "../../../shared/definitions/mobCombat.js";
5import { mobCanFight } from "../../../shared/definitions/mobCombat.js";
@@ -65,6 +65,7 @@ export function publicEntityView (ecs, entityId)
65 const creature = ecs.get(handle, Component.creature);
65 const creature = ecs.get(handle, Component.creature);
66 const flight = ecs.get(handle, Component.flight);
66 const flight = ecs.get(handle, Component.flight);
67 const health = ecs.get(handle, Component.health);
67 const health = ecs.get(handle, Component.health);
68 const equipment = ecs.get(handle, Component.equipment);
68 const layers = appearanceLayers(ecs, handle, appearance);
69 const layers = appearanceLayers(ecs, handle, appearance);
69 const mob = creature ? mobDefinition(creature.mobTypeId) : null;
70 const mob = creature ? mobDefinition(creature.mobTypeId) : null;
70 const isMob = !!creature && !character;
71 const isMob = !!creature && !character;
@@ -88,7 +89,8 @@ export function publicEntityView (ecs, entityId)
88 health: isMob && health ? health.current : undefined,
89 health: isMob && health ? health.current : undefined,
89 maxHealth: isMob && health ? health.max : undefined,
90 maxHealth: isMob && health ? health.max : undefined,
90 sprite: layers[0]?.sprite ?? null,
91 sprite: layers[0]?.sprite ?? null,
91 layers
92 layers,
93 lightRadiusTiles: equippedLightRadiusTiles(equipment)
92 };
94 };
93}
95}
94
96
@@ -166,7 +168,8 @@ export function replicationAppearance (view)
166 tileX: view.tileX,
168 tileX: view.tileX,
167 tileY: view.tileY,
169 tileY: view.tileY,
168 sprite: view.sprite ?? null,
170 sprite: view.sprite ?? null,
169 layers: view.layers ?? []
171 layers: view.layers ?? [],
172 lightRadiusTiles: view.lightRadiusTiles ?? 0
170 };
173 };
171}
174}
172
175
server/src/persistence/stateDb.js +53 −2
@@ -1,6 +1,6 @@
1 1 import { openDatabase } from "./database.js";
2 2 import { emptyEquipment, emptySlots, insertStack, insertStackGrowable, normalizeVault, normalizeInventorySlots, publicSlots, migrateBagCoins, migrateInheritanceCoins } from "../../../shared/items/inventory.js";
3 import { STARTER_ITEMS, itemDefinition } from "../../../shared/definitions/items.js";
3 import { STARTER_ITEMS, ItemId, itemDefinition } from "../../../shared/definitions/items.js";
4 4 import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";
5 5
6 6 const STATE_SCHEMA = `
@@ -112,6 +112,40 @@ export class StateDatabase
112 112 {
113 113 this.db.exec("ALTER TABLE character_bags ADD COLUMN skills_blob TEXT NOT NULL DEFAULT '{}'");
114 114 }
115 this.#grantLanternsToExistingCharacters();
116 }
117
118 #grantLanternsToExistingCharacters ()
119 {
120 const def = itemDefinition(ItemId.lantern);
121 if (!def)
122 { return; }
123 const rows = this.db.prepare("SELECT character_id, inventory_blob, equipment_blob FROM character_bags").all();
124 const update = this.db.prepare(`
125 UPDATE character_bags
126 SET inventory_blob = ?, equipment_blob = ?
127 WHERE character_id = ?
128 `);
129 for (const row of rows)
130 {
131 const inventory = JSON.parse(row.inventory_blob || "[]");
132 const equipment = JSON.parse(row.equipment_blob || "{}");
133 if (bagContainsItem(inventory, equipment, ItemId.lantern))
134 { continue; }
135 if (!equipment.slots?.offhand)
136 {
137 equipment.slots = equipment.slots ?? {};
138 equipment.slots.offhand = { itemId: ItemId.lantern, quantity: 1 };
139 }
140 else
141 {
142 const result = insertStack(inventory, { itemId: ItemId.lantern, quantity: 1 }, def);
143 if (!result.ok)
144 { continue; }
145 inventory.splice(0, inventory.length, ...result.slots);
146 }
147 update.run(JSON.stringify(inventory), JSON.stringify(equipment), row.character_id);
148 }
115 149 }
116 150
117 151 getAccountBySubject (authSubject)
@@ -400,6 +434,8 @@ export class StateDatabase
400 434 if (result.ok)
401 435 { slots.splice(0, slots.length, ...result.slots); }
402 436 }
437 const equipment = emptyEquipment();
438 equipment.slots.offhand = { itemId: ItemId.lantern, quantity: 1 };
403 439 this.db.prepare(`
404 440 INSERT INTO character_bags (
405 441 character_id, inventory_blob, equipment_blob, currency, vault_blob, vault_currency, skills_blob
@@ -407,7 +443,7 @@ export class StateDatabase
407 443 `).run(
408 444 characterId,
409 445 JSON.stringify(slots),
410 JSON.stringify(emptyEquipment()),
446 JSON.stringify(equipment),
411 447 JSON.stringify({ slots: [], reserved: [] }),
412 448 JSON.stringify(storedSkillXp(defaultPlayerSkills()))
413 449 );
@@ -687,6 +723,21 @@ function parseGroundItem (row)
687 723 };
688 724 }
689 725
726 function bagContainsItem (inventory, equipment, itemId)
727 {
728 for (const stack of inventory ?? [])
729 {
730 if (stack?.itemId === itemId)
731 { return true; }
732 }
733 for (const stack of Object.values(equipment?.slots ?? {}))
734 {
735 if (stack?.itemId === itemId)
736 { return true; }
737 }
738 return false;
739 }
740
690 741 function parseBag (row, characterId)
691 742 {
692 743 const vault = normalizeVault(JSON.parse(row.vault_blob));
@@ -1,6 +1,6 @@
1import { openDatabase } from "./database.js";
1import { openDatabase } from "./database.js";
2import { emptyEquipment, emptySlots, insertStack, insertStackGrowable, normalizeVault, normalizeInventorySlots, publicSlots, migrateBagCoins, migrateInheritanceCoins } from "../../../shared/items/inventory.js";
2import { emptyEquipment, emptySlots, insertStack, insertStackGrowable, normalizeVault, normalizeInventorySlots, publicSlots, migrateBagCoins, migrateInheritanceCoins } from "../../../shared/items/inventory.js";
3import { STARTER_ITEMS, itemDefinition } from "../../../shared/definitions/items.js";
3import { STARTER_ITEMS, ItemId, itemDefinition } from "../../../shared/definitions/items.js";
4import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";
4import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";
5
5
6const STATE_SCHEMA = `
6const STATE_SCHEMA = `
@@ -112,6 +112,40 @@ export class StateDatabase
112 {
112 {
113 this.db.exec("ALTER TABLE character_bags ADD COLUMN skills_blob TEXT NOT NULL DEFAULT '{}'");
113 this.db.exec("ALTER TABLE character_bags ADD COLUMN skills_blob TEXT NOT NULL DEFAULT '{}'");
114 }
114 }
115 this.#grantLanternsToExistingCharacters();
116 }
117
118 #grantLanternsToExistingCharacters ()
119 {
120 const def = itemDefinition(ItemId.lantern);
121 if (!def)
122 { return; }
123 const rows = this.db.prepare("SELECT character_id, inventory_blob, equipment_blob FROM character_bags").all();
124 const update = this.db.prepare(`
125 UPDATE character_bags
126 SET inventory_blob = ?, equipment_blob = ?
127 WHERE character_id = ?
128 `);
129 for (const row of rows)
130 {
131 const inventory = JSON.parse(row.inventory_blob || "[]");
132 const equipment = JSON.parse(row.equipment_blob || "{}");
133 if (bagContainsItem(inventory, equipment, ItemId.lantern))
134 { continue; }
135 if (!equipment.slots?.offhand)
136 {
137 equipment.slots = equipment.slots ?? {};
138 equipment.slots.offhand = { itemId: ItemId.lantern, quantity: 1 };
139 }
140 else
141 {
142 const result = insertStack(inventory, { itemId: ItemId.lantern, quantity: 1 }, def);
143 if (!result.ok)
144 { continue; }
145 inventory.splice(0, inventory.length, ...result.slots);
146 }
147 update.run(JSON.stringify(inventory), JSON.stringify(equipment), row.character_id);
148 }
115 }
149 }
116
150
117 getAccountBySubject (authSubject)
151 getAccountBySubject (authSubject)
@@ -400,6 +434,8 @@ export class StateDatabase
400 if (result.ok)
434 if (result.ok)
401 { slots.splice(0, slots.length, ...result.slots); }
435 { slots.splice(0, slots.length, ...result.slots); }
402 }
436 }
437 const equipment = emptyEquipment();
438 equipment.slots.offhand = { itemId: ItemId.lantern, quantity: 1 };
403 this.db.prepare(`
439 this.db.prepare(`
404 INSERT INTO character_bags (
440 INSERT INTO character_bags (
405 character_id, inventory_blob, equipment_blob, currency, vault_blob, vault_currency, skills_blob
441 character_id, inventory_blob, equipment_blob, currency, vault_blob, vault_currency, skills_blob
@@ -407,7 +443,7 @@ export class StateDatabase
407 `).run(
443 `).run(
408 characterId,
444 characterId,
409 JSON.stringify(slots),
445 JSON.stringify(slots),
410 JSON.stringify(emptyEquipment()),
446 JSON.stringify(equipment),
411 JSON.stringify({ slots: [], reserved: [] }),
447 JSON.stringify({ slots: [], reserved: [] }),
412 JSON.stringify(storedSkillXp(defaultPlayerSkills()))
448 JSON.stringify(storedSkillXp(defaultPlayerSkills()))
413 );
449 );
@@ -687,6 +723,21 @@ function parseGroundItem (row)
687 };
723 };
688}
724}
689
725
726function bagContainsItem (inventory, equipment, itemId)
727{
728 for (const stack of inventory ?? [])
729 {
730 if (stack?.itemId === itemId)
731 { return true; }
732 }
733 for (const stack of Object.values(equipment?.slots ?? {}))
734 {
735 if (stack?.itemId === itemId)
736 { return true; }
737 }
738 return false;
739}
740
690function parseBag (row, characterId)
741function parseBag (row, characterId)
691{
742{
692 const vault = normalizeVault(JSON.parse(row.vault_blob));
743 const vault = normalizeVault(JSON.parse(row.vault_blob));
shared/definitions/items.js +32 −1
@@ -16,7 +16,8 @@ export const ItemId = Object.freeze({
16 16 letter: 6,
17 17 filledCheque: 7,
18 18 coins: 8,
19 ...CraftingItemId
19 ...CraftingItemId,
20 lantern: 26
20 21 });
21 22
22 23 export const EQUIPMENT_SLOT = Object.freeze({
@@ -165,6 +166,21 @@ export const ITEM_DEFINITIONS = Object.freeze({
165 166 uniqueInstance: false,
166 167 category: "currency"
167 168 }),
169 [ItemId.lantern]: Object.freeze({
170 itemId: ItemId.lantern,
171 key: "lantern",
172 displayName: "Lantern",
173 description: "A handheld light source. Equip in the offhand to illuminate nearby tiles at night.",
174 seedValue: 12,
175 stackable: false,
176 maxStackSize: 1,
177 uniqueInstance: false,
178 category: "tool",
179 equipment: Object.freeze({
180 slot: EQUIPMENT_SLOT.offhand,
181 lightRadiusTiles: 6
182 })
183 }),
168 184 ...CRAFTING_ITEM_STUBS
169 185 });
170 186
@@ -265,6 +281,21 @@ export function itemEquipSprite (itemId)
265 281 ?? equipImageName("item", def.key, itemDefaultState(def));
266 282 }
267 283
284 /** Largest equipped light radius (e.g. lantern in offhand). */
285 export function equippedLightRadiusTiles (equipment)
286 {
287 let best = 0;
288 for (const stack of Object.values(equipment?.slots ?? {}))
289 {
290 if (!stack)
291 { continue; }
292 const radius = itemDefinition(stack.itemId)?.equipment?.lightRadiusTiles ?? 0;
293 if (radius > best)
294 { best = radius; }
295 }
296 return best;
297 }
298
268 299 export function letterVisualState (instance)
269 300 {
270 301 return instance?.opened === false ? "letter-closed" : "letter-opened";
@@ -16,7 +16,8 @@ export const ItemId = Object.freeze({
16 letter: 6,
16 letter: 6,
17 filledCheque: 7,
17 filledCheque: 7,
18 coins: 8,
18 coins: 8,
19 ...CraftingItemId
19 ...CraftingItemId,
20 lantern: 26
20});
21});
21
22
22export const EQUIPMENT_SLOT = Object.freeze({
23export const EQUIPMENT_SLOT = Object.freeze({
@@ -165,6 +166,21 @@ export const ITEM_DEFINITIONS = Object.freeze({
165 uniqueInstance: false,
166 uniqueInstance: false,
166 category: "currency"
167 category: "currency"
167 }),
168 }),
169 [ItemId.lantern]: Object.freeze({
170 itemId: ItemId.lantern,
171 key: "lantern",
172 displayName: "Lantern",
173 description: "A handheld light source. Equip in the offhand to illuminate nearby tiles at night.",
174 seedValue: 12,
175 stackable: false,
176 maxStackSize: 1,
177 uniqueInstance: false,
178 category: "tool",
179 equipment: Object.freeze({
180 slot: EQUIPMENT_SLOT.offhand,
181 lightRadiusTiles: 6
182 })
183 }),
168 ...CRAFTING_ITEM_STUBS
184 ...CRAFTING_ITEM_STUBS
169});
185});
170
186
@@ -265,6 +281,21 @@ export function itemEquipSprite (itemId)
265 ?? equipImageName("item", def.key, itemDefaultState(def));
281 ?? equipImageName("item", def.key, itemDefaultState(def));
266}
282}
267
283
284/** Largest equipped light radius (e.g. lantern in offhand). */
285export function equippedLightRadiusTiles (equipment)
286{
287 let best = 0;
288 for (const stack of Object.values(equipment?.slots ?? {}))
289 {
290 if (!stack)
291 { continue; }
292 const radius = itemDefinition(stack.itemId)?.equipment?.lightRadiusTiles ?? 0;
293 if (radius > best)
294 { best = radius; }
295 }
296 return best;
297}
298
268export function letterVisualState (instance)
299export function letterVisualState (instance)
269{
300{
270 return instance?.opened === false ? "letter-closed" : "letter-opened";
301 return instance?.opened === false ? "letter-closed" : "letter-opened";