yuuna-engine 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.cjs CHANGED
@@ -107,6 +107,19 @@ const keyboardKeys = [
107
107
 
108
108
  let resetCanvas = null;
109
109
  let latestRunId = 0;
110
+ // Shared between drawing TEXT renderables and hit-testing them for
111
+ // clicks/hovers, so the clickable area always matches what's on screen.
112
+ const DEFAULT_TEXT_FONT_SIZE = 30;
113
+ const textFont = (fontSize) => `${fontSize}px Arial`;
114
+ // Renderables with the same layer keep render()'s order — Array#sort is
115
+ // stable — so `layer` only needs to move something relative to the rest,
116
+ // not say anything about where exactly it lands among equal layers.
117
+ const sortByLayer = (renderables) => [...renderables].sort((a, b) => (a.layer ?? 0) - (b.layer ?? 0));
118
+ // A LINE has no `position`, just two endpoints — `from` anchors its scale
119
+ // the same way `position` anchors every other renderable's.
120
+ const anchorOf = (renderable) => renderable.type === "LINE" ? renderable.from : renderable.position;
121
+ // No RunEngineProps.camera set is the same as one that doesn't pan or zoom.
122
+ const DEFAULT_CAMERA = { x: 0, y: 0, zoom: 1 };
110
123
  const runEngine = async (props) => {
111
124
  const runId = ++latestRunId;
112
125
  resetCanvas?.();
@@ -146,9 +159,51 @@ const runEngine = async (props) => {
146
159
  height: value.size.height / value.slices.vertical,
147
160
  },
148
161
  slices: value.slices,
162
+ animations: value.animations ?? {},
149
163
  });
150
164
  };
151
165
  }));
166
+ const loadAudio = (src) => new Promise((resolve) => {
167
+ const audio = new Audio(src);
168
+ audio.oncanplaythrough = function () {
169
+ resolve(audio);
170
+ };
171
+ });
172
+ const sounds = props.sounds ?? {};
173
+ const audioById = await iterateRecordAsync(sounds, ({ value }) => loadAudio(value.src));
174
+ // Cloning the loaded element per play (instead of reusing it directly)
175
+ // lets the same sound overlap itself — e.g. rapid clicks each get their
176
+ // own playback instead of restarting/cutting off the previous one.
177
+ const playSound = (id) => {
178
+ const audio = audioById[id];
179
+ if (audio === undefined) {
180
+ return;
181
+ }
182
+ const instance = audio.cloneNode();
183
+ instance.play();
184
+ };
185
+ const music = props.music ?? {};
186
+ const musicById = await iterateRecordAsync(music, ({ value }) => loadAudio(value.src));
187
+ // Unlike sounds, music reuses the same element instead of cloning it —
188
+ // there's only ever one track playing, and reusing it is what lets
189
+ // pauseMusic()/playMusic() resume from where playback left off instead
190
+ // of starting over.
191
+ let currentMusic = null;
192
+ const playMusic = (id) => {
193
+ const audio = musicById[id];
194
+ if (audio === undefined) {
195
+ return;
196
+ }
197
+ if (currentMusic !== null && currentMusic !== audio) {
198
+ currentMusic.pause();
199
+ }
200
+ audio.loop = true;
201
+ audio.play();
202
+ currentMusic = audio;
203
+ };
204
+ const pauseMusic = () => {
205
+ currentMusic?.pause();
206
+ };
152
207
  // A newer runEngine() call started while this one was still loading
153
208
  // resources (e.g. a spritesheet) — abandon this run instead of setting
154
209
  // up a second, orphaned render loop alongside the newer one.
@@ -156,18 +211,185 @@ const runEngine = async (props) => {
156
211
  return;
157
212
  }
158
213
  context.imageSmoothingEnabled = false;
159
- function getFocusedElement(position, r) {
160
- const isNonInteractable = r.type === "TEXT" ||
161
- r.type === "LINE" ||
214
+ // An offscreen 1x1 canvas used only to resolve a CSS color string (a
215
+ // name, hex, rgb(), hsl(), ...) into concrete RGBA bytes: paint it that
216
+ // color and read the pixel back. Lets modulateColor() below multiply
217
+ // any two colors together without hand-rolling a CSS color parser.
218
+ const colorSwatchContext = window.document.createElement("canvas").getContext("2d");
219
+ // Color strings are almost always the same literal reused every frame,
220
+ // and getImageData is one of the slower canvas operations — cached so a
221
+ // given color only actually gets resolved once.
222
+ const resolvedColorByString = {};
223
+ const resolveColor = (color) => {
224
+ const cached = resolvedColorByString[color];
225
+ if (cached !== undefined) {
226
+ return cached;
227
+ }
228
+ if (colorSwatchContext === null) {
229
+ return [255, 255, 255, 255];
230
+ }
231
+ colorSwatchContext.clearRect(0, 0, 1, 1);
232
+ colorSwatchContext.fillStyle = color;
233
+ colorSwatchContext.fillRect(0, 0, 1, 1);
234
+ const [r, g, b, a] = colorSwatchContext.getImageData(0, 0, 1, 1).data;
235
+ const resolved = [r, g, b, a];
236
+ resolvedColorByString[color] = resolved;
237
+ return resolved;
238
+ };
239
+ // Multiplies two colors channel-by-channel, the same way Godot's
240
+ // `modulate` works — e.g. modulating "white" by "#808080" halves
241
+ // brightness, by "#ff0000" keeps only the red channel.
242
+ const modulateColor = (color, modulate) => {
243
+ const [r1, g1, b1, a1] = resolveColor(color);
244
+ const [r2, g2, b2, a2] = resolveColor(modulate);
245
+ const mixChannel = (c1, c2) => (c1 * c2) / 255;
246
+ return `rgba(${mixChannel(r1, r2)}, ${mixChannel(g1, g2)}, ${mixChannel(b1, b2)}, ${mixChannel(a1, a2) / 255})`;
247
+ };
248
+ // Combines a parent's already-composed modulate with a child's own —
249
+ // undefined means "no tint from this side", so it just passes the
250
+ // other one through instead of multiplying against an implicit white.
251
+ const composeModulate = (parent, own) => {
252
+ if (parent === undefined)
253
+ return own;
254
+ if (own === undefined)
255
+ return parent;
256
+ return modulateColor(parent, own);
257
+ };
258
+ const IDENTITY_TRANSFORM = {
259
+ anchor: { x: 0, y: 0 },
260
+ scale: { x: 1, y: 1 },
261
+ modulate: undefined,
262
+ layer: 0,
263
+ };
264
+ // A child's own position is authored relative to its parent, in the
265
+ // parent's local (unscaled) units — the same way Godot composes
266
+ // Node2D transforms — so it needs both the parent's scale and its
267
+ // accumulated offset applied to land in absolute canvas coordinates.
268
+ const transformPoint = (parent, localPoint) => ({
269
+ x: parent.anchor.x + localPoint.x * parent.scale.x,
270
+ y: parent.anchor.y + localPoint.y * parent.scale.y,
271
+ });
272
+ // Each id's accumulated playback time for its current animation, plus
273
+ // when that was last updated — keyed by id, since an ANIMATED_SPRITE
274
+ // has no state of its own (render() returns brand-new objects every
275
+ // frame). elapsedMs only advances while not paused (see
276
+ // resolveAnimatedSprite), so pausing genuinely stops the clock rather
277
+ // than just freezing which frame gets drawn — unpausing resumes from
278
+ // the same frame instead of skipping ahead by however long it was
279
+ // paused. Accumulating incrementally like this (instead of computing
280
+ // elapsed from an absolute start time every call) is also what makes
281
+ // pausing possible at all, and as a side effect means a `timeScale`
282
+ // that changes over an animation's lifetime scales each tick as it
283
+ // happens rather than retroactively rescaling the whole duration so
284
+ // far. Pruned each renderState() call (see seenAnimationIds there) to
285
+ // only ids actually present that frame, so a game that spawns entities
286
+ // with ever-incrementing ids doesn't leak one entry per entity ever
287
+ // spawned.
288
+ const animationStateById = new Map();
289
+ const seenAnimationIds = new Set();
290
+ // Resolves an ANIMATED_SPRITE down to a plain SPRITE with `frame`
291
+ // computed from how long its current animation has been playing —
292
+ // everything past this point (flattenRenderable's position/scale/
293
+ // modulate/layer composition, hit-testing, drawing) treats the result
294
+ // exactly like any other SPRITE, with no idea ANIMATED_SPRITE exists.
295
+ const resolveAnimatedSprite = (renderable) => {
296
+ seenAnimationIds.add(renderable.id);
297
+ const resource = resourceById[renderable.resourceId];
298
+ const animation = resource.animations[renderable.animation];
299
+ const timeScale = renderable.timeScale ?? 1;
300
+ const paused = renderable.paused ?? false;
301
+ const now = Date.now();
302
+ const tracked = animationStateById.get(renderable.id);
303
+ // A new id, or the same id switching to a different animation, both
304
+ // start that animation over from frame 0 rather than picking up
305
+ // wherever the previous timer happened to be.
306
+ const previous = tracked !== undefined && tracked.animation === renderable.animation
307
+ ? tracked
308
+ : { animation: renderable.animation, elapsedMs: 0, lastUpdateTime: now };
309
+ const elapsedMs = paused
310
+ ? previous.elapsedMs
311
+ : previous.elapsedMs + Math.max(0, now - previous.lastUpdateTime) * timeScale;
312
+ // lastUpdateTime always moves forward, paused or not — otherwise the
313
+ // first tick after unpausing would see a gap stretching back to
314
+ // whenever it was paused, and (dis)count that whole gap as elapsed
315
+ // playback time in one jump.
316
+ animationStateById.set(renderable.id, { animation: renderable.animation, elapsedMs, lastUpdateTime: now });
317
+ const frameCursor = Math.floor(elapsedMs / animation.frameDuration);
318
+ const frameIndex = animation.loop
319
+ ? frameCursor % animation.frames.length
320
+ : Math.min(frameCursor, animation.frames.length - 1);
321
+ return { ...renderable, type: "SPRITE", frame: animation.frames[frameIndex] };
322
+ };
323
+ // Turns a render() tree into the flat list the rest of the engine
324
+ // already knows how to sort/draw/hit-test — each renderable's own
325
+ // position/from/to/scale/modulate/layer replaced by the *effective*
326
+ // (absolute, fully composed with its ancestors') values, and its
327
+ // children peeled off into their own entries in the returned list
328
+ // instead of staying nested. Nothing past this point needs to know
329
+ // parent/child relationships existed at all.
330
+ const flattenRenderable = (renderable, parent) => {
331
+ const resolved = renderable.type === "ANIMATED_SPRITE" ? resolveAnimatedSprite(renderable) : renderable;
332
+ const localScale = resolved.scale ?? { x: 1, y: 1 };
333
+ const scale = { x: parent.scale.x * localScale.x, y: parent.scale.y * localScale.y };
334
+ const modulate = composeModulate(parent.modulate, resolved.modulate);
335
+ const layer = parent.layer + (resolved.layer ?? 0);
336
+ const effective = resolved.type === "LINE"
337
+ ? {
338
+ ...resolved,
339
+ from: transformPoint(parent, resolved.from),
340
+ to: transformPoint(parent, resolved.to),
341
+ scale,
342
+ modulate,
343
+ layer,
344
+ children: undefined,
345
+ }
346
+ : {
347
+ ...resolved,
348
+ position: transformPoint(parent, resolved.position),
349
+ scale,
350
+ modulate,
351
+ layer,
352
+ children: undefined,
353
+ };
354
+ const childTransform = { anchor: anchorOf(effective), scale, modulate, layer };
355
+ const children = (resolved.children ?? []).flatMap((child) => flattenRenderable(child, childTransform));
356
+ return [effective, ...children];
357
+ };
358
+ // parent defaults to the identity transform (used for screen-space
359
+ // renderables, and by everything before the camera existed) — callers
360
+ // that need a different root, like renderState's camera below, pass
361
+ // their own.
362
+ const flattenRenderables = (renderables, parent = IDENTITY_TRANSFORM) => renderables.flatMap((renderable) => flattenRenderable(renderable, parent));
363
+ const getFocusedElement = (position, r) => {
364
+ const isNonInteractable = r.type === "LINE" ||
365
+ r.type === "GROUP" ||
366
+ // Unreachable — flattenRenderable always resolves ANIMATED_SPRITE
367
+ // to a plain SPRITE before hit-testing ever sees one. Listed here
368
+ // (rather than left for exhaust() to catch) so getFocusedElement
369
+ // itself type-checks as exhaustive.
370
+ r.type === "ANIMATED_SPRITE" ||
162
371
  ((r.isHoverable === undefined || !r.isHoverable) &&
163
372
  (r.isClickable === undefined || !r.isClickable));
164
373
  if (isNonInteractable) {
165
374
  return false;
166
375
  }
376
+ // Scale is applied around the renderable's anchor as a draw-time canvas
377
+ // transform (see applyScale below) rather than by inflating its
378
+ // size — so hit-testing does the inverse instead: bring the mouse
379
+ // position into the renderable's own unscaled coordinate space, then
380
+ // run the exact same math below as if scale were untouched. For
381
+ // CIRCLE this also happens to be the standard "is this point inside
382
+ // this ellipse" test, for free, once it's drawing as one.
383
+ const { x: scaleX, y: scaleY } = r.scale ?? { x: 1, y: 1 };
384
+ const anchor = anchorOf(r);
385
+ const localPosition = {
386
+ x: anchor.x + (position.x - anchor.x) / scaleX,
387
+ y: anchor.y + (position.y - anchor.y) / scaleY,
388
+ };
167
389
  if (r.type === "CIRCLE") {
168
390
  const delta = {
169
- x: Math.abs(position.x - r.position.x),
170
- y: Math.abs(position.y - r.position.y),
391
+ x: Math.abs(localPosition.x - r.position.x),
392
+ y: Math.abs(localPosition.y - r.position.y),
171
393
  };
172
394
  const distance = Math.sqrt(delta.x * delta.x + delta.y * delta.y);
173
395
  const isHovered = distance < r.radius;
@@ -179,26 +401,86 @@ const runEngine = async (props) => {
179
401
  x: r.position.x + r.size.width,
180
402
  y: r.position.y + r.size.height,
181
403
  };
182
- const isInsideX = position.x > topLeft.x && position.x < bottomRight.x;
183
- const isInsideY = position.y > topLeft.y && position.y < bottomRight.y;
404
+ const isInsideX = localPosition.x > topLeft.x && localPosition.x < bottomRight.x;
405
+ const isInsideY = localPosition.y > topLeft.y && localPosition.y < bottomRight.y;
184
406
  const isHovered = isInsideX && isInsideY;
185
407
  return isHovered;
186
408
  }
187
409
  if (r.type === "SPRITE") {
188
410
  const topLeft = { x: r.position.x, y: r.position.y };
189
411
  const resource = resourceById[r.resourceId];
190
- const { scale = 1 } = r;
191
412
  const bottomRight = {
192
- x: r.position.x + resource.size.width * scale,
193
- y: r.position.y + resource.size.height * scale,
413
+ x: r.position.x + resource.size.width,
414
+ y: r.position.y + resource.size.height,
194
415
  };
195
- const isInsideX = position.x > topLeft.x && position.x < bottomRight.x;
196
- const isInsideY = position.y > topLeft.y && position.y < bottomRight.y;
416
+ const isInsideX = localPosition.x > topLeft.x && localPosition.x < bottomRight.x;
417
+ const isInsideY = localPosition.y > topLeft.y && localPosition.y < bottomRight.y;
197
418
  const isHovered = isInsideX && isInsideY;
198
419
  return isHovered;
199
420
  }
421
+ if (r.type === "TEXT") {
422
+ // Text has no explicit size, so its clickable area is derived from
423
+ // measuring it the same way it's drawn (see the TEXT branch in the
424
+ // render loop below) — anchored the same way its `align` positions
425
+ // it relative to `position`.
426
+ const fontSize = r.fontSize ?? DEFAULT_TEXT_FONT_SIZE;
427
+ context.font = textFont(fontSize);
428
+ const width = context.measureText(r.text).width;
429
+ const height = fontSize;
430
+ const alignX = r.align?.x ?? "left";
431
+ const left = alignX === "center" ? r.position.x - width / 2 : alignX === "right" ? r.position.x - width : r.position.x;
432
+ const alignY = r.align?.y ?? "top";
433
+ const top = alignY === "middle" ? r.position.y - height / 2 : alignY === "bottom" ? r.position.y - height : r.position.y;
434
+ const isInsideX = localPosition.x > left && localPosition.x < left + width;
435
+ const isInsideY = localPosition.y > top && localPosition.y < top + height;
436
+ return isInsideX && isInsideY;
437
+ }
200
438
  exhaust(r);
201
- }
439
+ };
440
+ // The camera is just another ancestor transform, exactly like a
441
+ // renderable's own parent — { x, y } is the world position mapped to
442
+ // canvas (0, 0), so it's the anchor transformPoint already expects:
443
+ // screen = (world - camera.position) * zoom.
444
+ const cameraTransformOf = (camera) => ({
445
+ anchor: { x: -camera.x * camera.zoom, y: -camera.y * camera.zoom },
446
+ scale: { x: camera.zoom, y: camera.zoom },
447
+ modulate: undefined,
448
+ layer: 0,
449
+ });
450
+ // The inverse of cameraTransformOf, for turning a raw canvas position
451
+ // (mouse) into a world position (worldMouse) — see ClickEvent etc.
452
+ const toWorldPosition = (position, camera) => ({
453
+ x: camera.x + position.x / camera.zoom,
454
+ y: camera.y + position.y / camera.zoom,
455
+ });
456
+ // Every call site needs renderables flattened and in draw order — the
457
+ // mousemove/click handlers below to find whichever's topmost under the
458
+ // mouse, the draw loop to actually draw them that way — so both are
459
+ // applied once here instead of separately wherever props.render() gets
460
+ // called. Screen-space renderables skip the camera entirely (flattened
461
+ // from the identity transform, same as before there was a camera);
462
+ // everything else is flattened as if the camera were its shared parent.
463
+ const renderState = (state) => {
464
+ const result = props.render(state);
465
+ const camera = props.camera?.(state) ?? DEFAULT_CAMERA;
466
+ const cameraTransform = cameraTransformOf(camera);
467
+ const worldRenderables = result.renderables.filter((r) => !r.screenSpace);
468
+ const screenRenderables = result.renderables.filter((r) => r.screenSpace);
469
+ seenAnimationIds.clear();
470
+ const renderables = sortByLayer([
471
+ ...flattenRenderables(worldRenderables, cameraTransform),
472
+ ...flattenRenderables(screenRenderables),
473
+ ]);
474
+ // Anything not seen this pass is no longer being rendered (e.g. the
475
+ // entity it belonged to died) — drop its tracked start time instead
476
+ // of keeping it forever.
477
+ for (const id of animationStateById.keys()) {
478
+ if (!seenAnimationIds.has(id)) {
479
+ animationStateById.delete(id);
480
+ }
481
+ }
482
+ return { cursor: result.cursor, renderables, camera };
483
+ };
202
484
  // ev.offsetX/offsetY are in CSS-rendered pixels, which differ from the
203
485
  // canvas's drawing-buffer resolution whenever it's displayed at a
204
486
  // different size (e.g. scaled down to fit its container). Renderable
@@ -221,10 +503,10 @@ const runEngine = async (props) => {
221
503
  const mouse = getCanvasPosition(ev);
222
504
  if (hoveredId === null)
223
505
  return;
224
- const { renderables } = props.render(state);
506
+ const { renderables, camera } = renderState(state);
225
507
  const hovered = renderables.find((e) => e.id === hoveredId);
226
508
  if (hovered !== undefined && hovered.isClickable) {
227
- events.push({ tag: "CLICK", id: hovered.id, mouse });
509
+ events.push({ tag: "CLICK", id: hovered.id, mouse, worldMouse: toWorldPosition(mouse, camera) });
228
510
  }
229
511
  });
230
512
  const initialState = {
@@ -255,17 +537,18 @@ const runEngine = async (props) => {
255
537
  });
256
538
  canvas.addEventListener("mousemove", (ev) => {
257
539
  const mouse = getCanvasPosition(ev);
258
- const { renderables } = props.render(state);
540
+ const { renderables, camera } = renderState(state);
541
+ const worldMouse = toWorldPosition(mouse, camera);
259
542
  const hovered = [...renderables]
260
543
  .reverse()
261
544
  .find((r) => getFocusedElement(mouse, r));
262
545
  if (hovered !== undefined && hovered.isHoverable) {
263
- events.push({ tag: "HOVER_IN", id: hovered.id, mouse });
546
+ events.push({ tag: "HOVER_IN", id: hovered.id, mouse, worldMouse });
264
547
  }
265
548
  if (hoveredId !== null) {
266
549
  const lastHovered = renderables.find((r) => r.id === hoveredId);
267
550
  if (lastHovered !== undefined && lastHovered.id !== hovered?.id) {
268
- events.push({ tag: "HOVER_OUT", id: lastHovered.id, mouse });
551
+ events.push({ tag: "HOVER_OUT", id: lastHovered.id, mouse, worldMouse });
269
552
  }
270
553
  }
271
554
  hoveredId = hovered === undefined ? null : hovered.id ?? null;
@@ -275,13 +558,62 @@ const runEngine = async (props) => {
275
558
  if (hoveredId === null) {
276
559
  return;
277
560
  }
278
- const { renderables } = props.render(state);
561
+ const { renderables, camera } = renderState(state);
279
562
  const hovered = renderables.find((r) => r.id === hoveredId);
280
563
  if (hovered !== undefined && hovered.trackMouseMovement) {
281
- events.push({ tag: "MOUSE_MOVE", mouse, id: hovered.id });
564
+ events.push({ tag: "MOUSE_MOVE", mouse, worldMouse: toWorldPosition(mouse, camera), id: hovered.id });
282
565
  }
283
566
  });
284
567
  context.imageSmoothingEnabled = false;
568
+ // Scale is a canvas transform around the renderable's anchor, applied
569
+ // before its type-specific drawing runs below — everything drawn under
570
+ // it (fills, strokes, images, even font size) comes out scaled without
571
+ // each renderable type needing its own size math, and a CIRCLE drawn
572
+ // under a non-uniform scale comes out an ellipse for free.
573
+ const applyScale = (renderable) => {
574
+ const { x: scaleX, y: scaleY } = renderable.scale ?? { x: 1, y: 1 };
575
+ if (scaleX === 1 && scaleY === 1) {
576
+ return;
577
+ }
578
+ const anchor = anchorOf(renderable);
579
+ context.translate(anchor.x, anchor.y);
580
+ context.scale(scaleX, scaleY);
581
+ context.translate(-anchor.x, -anchor.y);
582
+ };
583
+ // Reused across every tinted SPRITE draw this run, instead of allocating
584
+ // a fresh offscreen canvas per sprite per frame — see tintedSpriteFrame.
585
+ const tintBuffer = window.document.createElement("canvas");
586
+ const tintBufferContext = tintBuffer.getContext("2d");
587
+ // Renders one frame of a spritesheet, tinted by `modulate`, onto the
588
+ // shared offscreen buffer and returns it ready to draw — multiply-
589
+ // blending a filled rectangle over the frame would also color its
590
+ // fully-transparent pixels, so this clips that back down to the
591
+ // frame's own shape afterward with `destination-in`.
592
+ //
593
+ // This has to happen on an *isolated* buffer rather than directly on
594
+ // the main canvas: destination-in isn't scoped to this draw call's own
595
+ // area, it's a whole-buffer operation that erases anything the new
596
+ // draw doesn't cover. Doing it on the main canvas would erase whatever
597
+ // was already drawn underneath the sprite's transparent pixels (e.g.
598
+ // terrain showing through the gaps in a character) instead of leaving
599
+ // it alone. The buffer starts out empty, so there's nothing under it
600
+ // to lose — only the finished, correctly-masked result ever reaches
601
+ // the main canvas, via a normal (source-over) drawImage.
602
+ const tintedSpriteFrame = (image, source, modulate) => {
603
+ if (tintBufferContext === null) {
604
+ return image;
605
+ }
606
+ tintBuffer.width = source.width;
607
+ tintBuffer.height = source.height;
608
+ tintBufferContext.drawImage(image, source.x, source.y, source.width, source.height, 0, 0, source.width, source.height);
609
+ tintBufferContext.globalCompositeOperation = "multiply";
610
+ tintBufferContext.fillStyle = modulate;
611
+ tintBufferContext.fillRect(0, 0, source.width, source.height);
612
+ tintBufferContext.globalCompositeOperation = "destination-in";
613
+ tintBufferContext.drawImage(image, source.x, source.y, source.width, source.height, 0, 0, source.width, source.height);
614
+ tintBufferContext.globalCompositeOperation = "source-over";
615
+ return tintBuffer;
616
+ };
285
617
  const intervalId = setInterval(() => {
286
618
  const now = Date.now();
287
619
  const delta = now - lastFrame;
@@ -296,7 +628,7 @@ const runEngine = async (props) => {
296
628
  };
297
629
  });
298
630
  for (const nextState of nextStateFns) {
299
- const result = nextState({ state, event, keyboard });
631
+ const result = nextState({ state, event, keyboard, playSound, playMusic, pauseMusic });
300
632
  // STOP stops the rest of the list from running for this event,
301
633
  // instead of every later mechanic needing to repeat the same
302
634
  // guard. undefined just means this mechanic made no change, so
@@ -311,63 +643,102 @@ const runEngine = async (props) => {
311
643
  }
312
644
  events.splice(0, events.length);
313
645
  context.clearRect(0, 0, canvas.width, canvas.height);
314
- const { cursor, renderables } = props.render(state);
646
+ const { cursor, renderables } = renderState(state);
315
647
  canvas.style.cursor = cursor ?? "default";
316
648
  for (const renderable of renderables) {
649
+ context.save();
650
+ applyScale(renderable);
317
651
  if (renderable.type === "RECTANGLE") {
318
- context.fillStyle = renderable.color;
652
+ context.fillStyle =
653
+ renderable.modulate === undefined ? renderable.color : modulateColor(renderable.color, renderable.modulate);
319
654
  context.fillRect(renderable.position.x, renderable.position.y, renderable.size.width, renderable.size.height);
655
+ context.restore();
320
656
  continue;
321
657
  }
322
658
  if (renderable.type === "CIRCLE") {
323
- context.fillStyle = renderable.color;
659
+ context.fillStyle =
660
+ renderable.modulate === undefined ? renderable.color : modulateColor(renderable.color, renderable.modulate);
324
661
  context.beginPath();
325
662
  context.arc(renderable.position.x, renderable.position.y, renderable.radius, 0, 2 * Math.PI);
326
663
  context.fill();
664
+ context.restore();
327
665
  continue;
328
666
  }
329
667
  if (renderable.type === "TEXT") {
330
- const { color, position: { x, y }, text, align, } = renderable;
331
- context.fillStyle = color;
332
- context.font = "30px Arial";
668
+ const { color, position: { x, y }, text, align, fontSize, modulate, } = renderable;
669
+ context.fillStyle = modulate === undefined ? color : modulateColor(color, modulate);
670
+ context.font = textFont(fontSize ?? DEFAULT_TEXT_FONT_SIZE);
333
671
  context.textAlign = align?.x ?? "left";
334
672
  context.textBaseline = align?.y ?? "top";
335
673
  context.fillText(text, x, y);
674
+ context.restore();
336
675
  continue;
337
676
  }
338
677
  if (renderable.type === "SPRITE") {
339
- const { scale = 1, opacity = 1, flipX = false } = renderable;
678
+ const { opacity = 1, flipX = false, modulate } = renderable;
340
679
  const resource = resourceById[renderable.resourceId];
341
680
  const frame = {
342
681
  x: renderable.frame % resource.slices.horizontal,
343
682
  y: Math.floor(renderable.frame / resource.slices.horizontal) %
344
683
  resource.slices.vertical,
345
684
  };
346
- const destWidth = resource.size.width * scale;
347
- const destHeight = resource.size.height * scale;
685
+ const source = {
686
+ x: frame.x * resource.size.width,
687
+ y: frame.y * resource.size.height,
688
+ width: resource.size.width,
689
+ height: resource.size.height,
690
+ };
691
+ const destWidth = resource.size.width;
692
+ const destHeight = resource.size.height;
693
+ // Tinting swaps in an already-tinted offscreen copy of this frame
694
+ // as the image to draw — everything past this point (flipX,
695
+ // positioning) treats it exactly like the untinted spritesheet,
696
+ // just drawn starting at (0, 0) instead of cropped from a sheet.
697
+ const image = modulate === undefined ? resource.image : tintedSpriteFrame(resource.image, source, modulate);
698
+ const imageSource = modulate === undefined ? source : { x: 0, y: 0, width: source.width, height: source.height };
348
699
  context.globalAlpha = opacity;
700
+ const drawSprite = (destX, destY) => {
701
+ context.drawImage(image, imageSource.x, imageSource.y, imageSource.width, imageSource.height, destX, destY, destWidth, destHeight);
702
+ };
349
703
  if (flipX) {
350
704
  context.save();
351
705
  context.translate(renderable.position.x + destWidth, renderable.position.y);
352
706
  context.scale(-1, 1);
353
- context.drawImage(resource.image, frame.x * resource.size.width, frame.y * resource.size.height, resource.size.width, resource.size.height, 0, 0, destWidth, destHeight);
707
+ drawSprite(0, 0);
354
708
  context.restore();
355
709
  }
356
710
  else {
357
- context.drawImage(resource.image, frame.x * resource.size.width, frame.y * resource.size.height, resource.size.width, resource.size.height, renderable.position.x, renderable.position.y, destWidth, destHeight);
711
+ drawSprite(renderable.position.x, renderable.position.y);
358
712
  }
359
713
  context.globalAlpha = 1;
714
+ context.restore();
360
715
  continue;
361
716
  }
362
717
  if (renderable.type === "LINE") {
363
- context.strokeStyle = renderable.color;
718
+ context.strokeStyle =
719
+ renderable.modulate === undefined ? renderable.color : modulateColor(renderable.color, renderable.modulate);
364
720
  context.lineWidth = renderable.width ?? 2;
365
721
  context.beginPath();
366
722
  context.moveTo(renderable.from.x, renderable.from.y);
367
723
  context.lineTo(renderable.to.x, renderable.to.y);
368
724
  context.stroke();
725
+ context.restore();
369
726
  continue;
370
727
  }
728
+ if (renderable.type === "GROUP") {
729
+ // Draws nothing itself — it only exists to give its children
730
+ // (already peeled off into their own entries by flattenRenderables)
731
+ // something to be positioned/scaled/tinted relative to.
732
+ context.restore();
733
+ continue;
734
+ }
735
+ if (renderable.type === "ANIMATED_SPRITE") {
736
+ // Unreachable — flattenRenderable always resolves ANIMATED_SPRITE
737
+ // to a plain SPRITE before it gets here. A real error (not a
738
+ // silent skip) if it's somehow still one, since that would mean
739
+ // an actual engine bug rather than anything a game author did.
740
+ throw new Error("ANIMATED_SPRITE reached the draw loop unresolved — this is an engine bug");
741
+ }
371
742
  exhaust(renderable);
372
743
  }
373
744
  lastFrame = now;
package/lib/index.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}