BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

worldView.js 15.2 KiB Download Raw
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS } from "/shared/protocol/constants.js";
2import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";
3import { resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";
4import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
5
6const LAYER_GROUND = 0;
7const LAYER_SHADE = 500000;
8const LAYER_EDGE = 900000;
9const SORT_BLOCK = 1;
10const SORT_ENTITY = 2;
11
12export class WorldView
13{
14 constructor (game, scene, catalog = { grounds: {}, blocks: {} })
15 {
16 this.game = game;
17 this.scene = scene;
18 this.catalog = catalog;
19 this.preview = null;
20 this.zoom = 2;
21 this.chunks = new Map();
22 this.tiles = new Map();
23 this.entities = new Map();
24 this.edges = new Map();
25 this.localEntityId = null;
26 this.settings = { ...DEFAULT_WORLD_SETTINGS };
27 this.worldHour = 12;
28 this.nightPreview = null;
29 this.followPlayer = true;
30 }
31
32 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null)
33 {
34 this.localEntityId = entityId;
35 this.#upsertEntity({
36 entityId,
37 characterId,
38 tileX,
39 tileY,
40 gait,
41 sex,
42 firstName,
43 lastName
44 });
45 }
46
47 applySnapshot (snapshot)
48 {
49 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
50 this.chunks.set(key, snapshot);
51 this.#rebuildChunk(snapshot);
52 this.#redrawPreview();
53 for (const entity of snapshot.entities ?? [])
54 { this.#upsertEntity(entity); }
55 this.#rebuildAllEdges();
56 }
57
58 removeChunk (chunkX, chunkY)
59 {
60 const key = `${chunkX},${chunkY}`;
61 this.chunks.delete(key);
62 this.#destroyEdges(key);
63 for (const [tileKey, objects] of [...this.tiles.entries()])
64 {
65 if (objects.chunkX === chunkX && objects.chunkY === chunkY)
66 {
67 objects.ground?.destroy();
68 objects.block?.destroy();
69 objects.shade?.destroy();
70 this.tiles.delete(tileKey);
71 }
72 }
73 this.#rebuildAllEdges();
74 }
75
76 setChunkOpen (chunkX, chunkY, open)
77 {
78 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
79 if (!snapshot)
80 { return; }
81 snapshot.open = !!open;
82 this.#rebuildAllEdges();
83 }
84
85 moveEntity (payload)
86 {
87 const existing = this.entities.get(payload.entityId);
88 if (!existing)
89 {
90 this.#upsertEntity(payload);
91 return;
92 }
93 existing.fromX = existing.visualX;
94 existing.fromY = existing.visualY;
95 existing.tileX = payload.tileX;
96 existing.tileY = payload.tileY;
97 existing.gait = payload.gait;
98 existing.lerpStarted = performance.now();
99 existing.lerpMs = this.#lerpMs(payload.gait);
100 }
101
102 despawnEntity (entityId)
103 {
104 const existing = this.entities.get(entityId);
105 if (!existing)
106 { return; }
107 existing.object?.destroy();
108 this.entities.delete(entityId);
109 }
110
111 setZoom (zoom, limits = { min: 1, max: 4 })
112 {
113 const min = limits.min ?? 1;
114 const max = limits.max ?? 4;
115 this.zoom = Math.min(max, Math.max(min, zoom));
116 for (const snapshot of this.chunks.values())
117 { this.#rebuildChunk(snapshot); }
118 const size = this.tileSize();
119 for (const entity of this.entities.values())
120 {
121 entity.visualX = tilePivot(entity.tileX, entity.tileY, size).x;
122 entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y;
123 entity.fromX = entity.visualX;
124 entity.fromY = entity.visualY;
125 entity.lerpStarted = null;
126 this.#placeEntity(entity);
127 }
128 this.#rebuildAllEdges();
129 this.#redrawPreview();
130 }
131
132 tileSize ()
133 {
134 return SPRITE_SIZE_PX * this.zoom;
135 }
136
137 screenToTile (mouseX, mouseY)
138 {
139 const size = this.tileSize();
140 const worldX = mouseX - this.scene.cameraPosition.x;
141 const worldY = mouseY - this.scene.cameraPosition.y;
142 return {
143 tileX: Math.floor(worldX / size),
144 tileY: Math.floor(worldY / size)
145 };
146 }
147
148 entityAtScreen (mouseX, mouseY)
149 {
150 let best = null;
151 let bestLayer = -Infinity;
152 for (const entity of this.entities.values())
153 {
154 const box = this.#entityScreenBox(entity);
155 if (!box)
156 { continue; }
157 if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom)
158 {
159 const layer = entity.object?.layer ?? 0;
160 if (layer >= bestLayer)
161 {
162 best = entity;
163 bestLayer = layer;
164 }
165 }
166 }
167 return best;
168 }
169
170 nametagAnchor (entity)
171 {
172 const box = this.#entityScreenBox(entity);
173 if (!box)
174 { return null; }
175 return { x: (box.left + box.right) / 2, y: box.top };
176 }
177
178 #entityScreenBox (entity)
179 {
180 const object = entity?.object;
181 if (!object)
182 { return null; }
183 const size = object.transform.size;
184 const x = object.transform.position.x + this.scene.cameraPosition.x;
185 const y = object.transform.position.y + this.scene.cameraPosition.y;
186 return {
187 left: x - size.x / 2,
188 right: x + size.x / 2,
189 top: y - size.y / 2,
190 bottom: y + size.y / 2
191 };
192 }
193
194 update (deltaTime)
195 {
196 const now = performance.now();
197 const size = this.tileSize();
198 for (const entity of this.entities.values())
199 {
200 const target = tilePivot(entity.tileX, entity.tileY, size);
201 if (entity.lerpStarted != null)
202 {
203 const t = Math.min(1, (now - entity.lerpStarted) / entity.lerpMs);
204 entity.visualX = entity.fromX + (target.x - entity.fromX) * t;
205 entity.visualY = entity.fromY + (target.y - entity.fromY) * t;
206 if (t >= 1)
207 { entity.lerpStarted = null; }
208 }
209 else
210 {
211 entity.visualX = target.x;
212 entity.visualY = target.y;
213 }
214 this.#placeEntity(entity);
215 }
216
217 this.#centerCamera();
218 this.#updateShade(deltaTime);
219 }
220
221 updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {})
222 {
223 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
224 if (!snapshot)
225 { return; }
226 const index = localY * CHUNK_SIZE + localX;
227 if (ground !== undefined)
228 { snapshot.grounds[index] = ground; }
229 if (block !== undefined)
230 { snapshot.blocks[index] = block; }
231 if (light !== undefined)
232 { snapshot.light[index] = light; }
233 this.#drawTile(chunkX * CHUNK_SIZE + localX, chunkY * CHUNK_SIZE + localY);
234 }
235
236 setTilePreview (tileX, tileY, override)
237 {
238 const previous = this.preview;
239 this.preview = { tileX, tileY, ...override };
240 if (previous && (previous.tileX !== tileX || previous.tileY !== tileY))
241 { this.#drawTile(previous.tileX, previous.tileY); }
242 this.#drawTile(tileX, tileY);
243 }
244
245 clearTilePreview ()
246 {
247 const previous = this.preview;
248 this.preview = null;
249 if (previous)
250 { this.#drawTile(previous.tileX, previous.tileY); }
251 }
252
253 #lerpMs (gait)
254 {
255 const walk = this.settings.walkTilesPerSecond || 2;
256 const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk;
257 return seconds * 1000;
258 }
259
260 #centerCamera ()
261 {
262 if (!this.followPlayer)
263 { return; }
264 const local = this.entities.get(this.localEntityId);
265 if (!local)
266 { return; }
267 this.scene.cameraPosition.x = this.scene.real_size.x / 2 - local.visualX;
268 this.scene.cameraPosition.y = this.scene.real_size.y / 2 - local.visualY;
269 }
270
271 #upsertEntity (payload)
272 {
273 const size = this.tileSize();
274 const pivot = tilePivot(payload.tileX, payload.tileY, size);
275 let entity = this.entities.get(payload.entityId);
276 if (!entity)
277 {
278 const spriteName = payload.sex === "female" ? "player-body-female" : "player-body-male";
279 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY);
280 this.scene.addObject(object);
281 entity = { object, visualX: pivot.x, visualY: pivot.y };
282 this.entities.set(payload.entityId, entity);
283 }
284 entity.entityId = payload.entityId;
285 entity.tileX = payload.tileX;
286 entity.tileY = payload.tileY;
287 entity.gait = payload.gait;
288 entity.sex = payload.sex ?? entity.sex;
289 entity.characterId = payload.characterId ?? entity.characterId ?? null;
290 if (payload.firstName)
291 { entity.firstName = payload.firstName; }
292 if (payload.lastName)
293 { entity.lastName = payload.lastName; }
294 entity.firstName = entity.firstName ?? "";
295 entity.lastName = entity.lastName ?? "";
296 entity.visualX = pivot.x;
297 entity.visualY = pivot.y;
298 entity.fromX = pivot.x;
299 entity.fromY = pivot.y;
300 this.#placeEntity(entity);
301 }
302
303 #placeEntity (entity)
304 {
305 this.#placePivoted(entity.object, entity.visualX, entity.visualY, entity.visualY, SORT_ENTITY);
306 }
307
308 #rebuildChunk (snapshot)
309 {
310 for (let localY = 0; localY < CHUNK_SIZE; localY++)
311 {
312 for (let localX = 0; localX < CHUNK_SIZE; localX++)
313 { this.#drawTile(snapshot.chunkX * CHUNK_SIZE + localX, snapshot.chunkY * CHUNK_SIZE + localY); }
314 }
315 }
316
317 #redrawPreview ()
318 {
319 if (this.preview)
320 { this.#drawTile(this.preview.tileX, this.preview.tileY); }
321 }
322
323 #drawTile (tileX, tileY)
324 {
325 const chunkX = Math.floor(tileX / CHUNK_SIZE);
326 const chunkY = Math.floor(tileY / CHUNK_SIZE);
327 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
328 if (!snapshot)
329 { return; }
330 const localX = tileX - chunkX * CHUNK_SIZE;
331 const localY = tileY - chunkY * CHUNK_SIZE;
332 const index = localY * CHUNK_SIZE + localX;
333 const key = `${tileX},${tileY}`;
334 let objects = this.tiles.get(key);
335 if (!objects)
336 {
337 objects = { chunkX, chunkY };
338 this.tiles.set(key, objects);
339 }
340
341 let ground = snapshot.grounds[index];
342 let block = snapshot.blocks[index];
343 const preview = this.preview;
344 if (preview && preview.tileX === tileX && preview.tileY === tileY)
345 {
346 if (preview.ground !== undefined)
347 { ground = preview.ground; }
348 if (preview.block !== undefined)
349 { block = preview.block; }
350 }
351
352 const size = this.tileSize();
353 const pivot = tilePivot(tileX, tileY, size);
354 const groundName = this.#groundSpriteName(ground);
355 objects.ground = this.#ensureSprite(objects.ground, groundName, LAYER_GROUND);
356 if (objects.ground)
357 {
358 this.#placePivoted(objects.ground, pivot.x, pivot.y, pivot.y, 0);
359 objects.ground.layer = LAYER_GROUND;
360 }
361
362 const blockName = this.#blockSpriteName(block);
363 if (blockName)
364 {
365 objects.block = this.#ensureSprite(objects.block, blockName, SORT_BLOCK);
366 if (objects.block)
367 { this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_BLOCK); }
368 }
369 else if (objects.block)
370 {
371 objects.block.destroy();
372 objects.block = null;
373 }
374
375 objects.light = snapshot.light[index] ?? 0;
376 const previousShade = objects.shade;
377 objects.shade = this.#tileFill(objects.shade, "night-shade", pivot.x, pivot.y, LAYER_SHADE + tileY);
378 if (objects.shade && objects.shade !== previousShade)
379 { objects.shade.renderer.alpha = 0; }
380 }
381
382 #groundSpriteName (ground)
383 {
384 const entry = normalizeGround(ground);
385 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
386 const states = this.catalog.grounds?.[def.key]?.states ?? [];
387 const state = resolveState(states, entry.state);
388 return spriteImageName("ground", def.key, state);
389 }
390
391 #blockSpriteName (block)
392 {
393 const entry = normalizeBlock(block);
394 if (!entry)
395 { return null; }
396 const def = BLOCK_DEFINITIONS[entry.typeId];
397 if (!def)
398 { return null; }
399 const states = this.catalog.blocks?.[def.key]?.states ?? [];
400 const state = resolveState(states, entry.state);
401 return spriteImageName("block", def.key, state);
402 }
403
404 #tileFill (existing, name, x, y, layer)
405 {
406 existing = this.#ensureSprite(existing, name, layer);
407 if (!existing)
408 { return null; }
409 const size = this.tileSize();
410 existing.transform.position.x = x;
411 existing.transform.position.y = y;
412 existing.transform.size = new vector(size, size);
413 existing.layer = layer;
414 this.#markSortDirty();
415 return existing;
416 }
417
418 #placePivoted (object, pivotX, pivotY, sortY, subOrder)
419 {
420 const sprite = object?.renderer?.sprite;
421 if (!sprite)
422 { return; }
423 const zoom = this.zoom;
424 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
425 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom);
426 object.transform.position.x = center.x;
427 object.transform.position.y = center.y;
428 object.transform.size = new vector(draw.w, draw.h);
429 object.layer = ySortLayer(sortY, subOrder);
430 this.#markSortDirty();
431 }
432
433 #ensureSprite (existing, name, layer)
434 {
435 const sprite = this.game.images[name];
436 if (!sprite)
437 {
438 existing?.destroy();
439 return null;
440 }
441 if (!existing || existing.renderer.sprite !== sprite)
442 {
443 existing?.destroy();
444 existing = new GameObject(0, 0, sprite, layer);
445 this.scene.addObject(existing);
446 if (sprite.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0)
447 { existing.renderer.setAnimation("idle", 0, sprite._animationSpeed); }
448 }
449 return existing;
450 }
451
452 #neighborClosed (snapshot, dir, dx, dy)
453 {
454 const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
455 if (other)
456 { return !other.open; }
457 return !!snapshot.closedEdges?.[dir];
458 }
459
460 #rebuildAllEdges ()
461 {
462 const seen = new Set();
463 for (const snapshot of this.chunks.values())
464 {
465 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
466 seen.add(key);
467 this.#rebuildChunkEdges(snapshot);
468 }
469 for (const key of [...this.edges.keys()])
470 {
471 if (!seen.has(key))
472 { this.#destroyEdges(key); }
473 }
474 }
475
476 #rebuildChunkEdges (snapshot)
477 {
478 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
479 let bars = this.edges.get(key);
480 if (!bars)
481 {
482 bars = {};
483 this.edges.set(key, bars);
484 }
485
486 const size = this.tileSize();
487 const chunkPx = CHUNK_SIZE * size;
488 const left = snapshot.chunkX * CHUNK_SIZE * size;
489 const top = snapshot.chunkY * CHUNK_SIZE * size;
490 const centerX = left + chunkPx / 2;
491 const centerY = top + chunkPx / 2;
492 const thickness = Math.max(2, Math.round(2 * this.zoom));
493 const draw = snapshot.open === true;
494
495 bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1),
496 centerX, top, chunkPx, thickness, true);
497 bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1),
498 centerX, top + chunkPx, chunkPx, thickness, true);
499 bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0),
500 left, centerY, chunkPx, thickness, false);
501 bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0),
502 left + chunkPx, centerY, chunkPx, thickness, false);
503 }
504
505 #edgeBar (existing, visible, x, y, length, thickness, horizontal)
506 {
507 if (!visible)
508 {
509 if (existing)
510 { existing.renderer.visible = false; }
511 return existing;
512 }
513
514 existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE);
515 existing.renderer.visible = true;
516 existing.transform.position.x = x;
517 existing.transform.position.y = y;
518 existing.transform.size = horizontal
519 ? new vector(length, thickness)
520 : new vector(thickness, length);
521 existing.layer = LAYER_EDGE;
522 this.#markSortDirty();
523 return existing;
524 }
525
526 #destroyEdges (key)
527 {
528 const bars = this.edges.get(key);
529 if (!bars)
530 { return; }
531 bars.north?.destroy();
532 bars.east?.destroy();
533 bars.south?.destroy();
534 bars.west?.destroy();
535 this.edges.delete(key);
536 }
537
538 #markSortDirty ()
539 {
540 this.scene._sortDirty = true;
541 }
542
543 #updateShade ()
544 {
545 const hour = this.nightPreview ?? this.worldHour;
546 const ambientDark = nightFactor(hour, this.settings.nightDarkness);
547 for (const objects of this.tiles.values())
548 {
549 if (!objects.shade)
550 { continue; }
551 const intensity = Math.min(1, Math.max(0, (objects.light ?? 0) / 255));
552 objects.shade.renderer.alpha = ambientDark * (1 - intensity);
553 }
554 }
555}
556
557export function nightFactor (hour, nightDarkness = 0.72)
558{
559 const peak = Math.min(1, Math.max(0, nightDarkness));
560 if (hour >= 8 && hour <= 16)
561 { return 0; }
562 if (hour >= 22 || hour <= 5)
563 { return peak; }
564 if (hour < 8)
565 { return lerp(peak, 0, (hour - 5) / 3); }
566 return lerp(0, peak, (hour - 16) / 6);
567}
568
569function lerp (a, b, t)
570{
571 return a + (b - a) * Math.min(1, Math.max(0, t));
572}