@inglorious/engine 23.0.7 → 24.1.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.
Files changed (38) hide show
  1. package/README.md +7 -4
  2. package/package.json +3 -3
  3. package/src/ai/movement/dynamic/arrive.js +2 -1
  4. package/src/ai/movement/dynamic/evade.js +2 -1
  5. package/src/ai/movement/dynamic/face.js +2 -1
  6. package/src/ai/movement/dynamic/look-where-youre-going.js +2 -1
  7. package/src/ai/movement/dynamic/pursue.js +2 -1
  8. package/src/ai/movement/dynamic/wander.js +2 -1
  9. package/src/ai/movement/kinematic/face.js +2 -1
  10. package/src/ai/movement/kinematic/wander-as-seek.js +2 -1
  11. package/src/animation/sprite.js +2 -1
  12. package/src/behaviors/at-fps.js +1 -1
  13. package/src/behaviors/audio.js +24 -24
  14. package/src/behaviors/camera.js +2 -1
  15. package/src/behaviors/controls/dynamic/modern.js +1 -1
  16. package/src/behaviors/controls/dynamic/shooter.js +2 -2
  17. package/src/behaviors/controls/dynamic/tank.js +1 -1
  18. package/src/behaviors/controls/kinematic/modern.js +1 -1
  19. package/src/behaviors/controls/kinematic/shooter.js +2 -2
  20. package/src/behaviors/controls/kinematic/tank.js +1 -1
  21. package/src/behaviors/fps.js +2 -1
  22. package/src/behaviors/input/hover.js +1 -1
  23. package/src/behaviors/input/mouse.js +3 -2
  24. package/src/behaviors/input/touch.js +3 -2
  25. package/src/behaviors/physics/clamped.js +2 -1
  26. package/src/behaviors/physics/jumpable.js +2 -1
  27. package/src/behaviors/ui/button.js +1 -1
  28. package/src/collision/detection.js +23 -22
  29. package/src/core/engine.js +3 -3
  30. package/src/core/middlewares/entity-pool/entity-pool-middleware.js +1 -1
  31. package/src/main.js +2 -1
  32. package/src/physics/bounds.js +2 -5
  33. package/src/storage.js +4 -4
  34. package/src/systems/sprite-animation.js +1 -1
  35. package/src/systems/ticks.js +61 -0
  36. package/src/behaviors/state-machine/fsm.js +0 -55
  37. package/src/behaviors/state-machine/scenes.js +0 -89
  38. /package/src/behaviors/{state-machine → input}/mappings.js +0 -0
package/README.md CHANGED
@@ -29,17 +29,18 @@ This will set up a complete project with a development server ready to go.
29
29
  - **Pausing without permission checks**: `notify("pause")` halts the world, so nothing that moves has to ask whether it is allowed to.
30
30
  - **A way out that works anywhere**: `notify("quit")` ends the game, from any state, without a handler of its own.
31
31
  - **Sprites in one call**: `crop()` points an entity at a frame of a sheet without you having to remember which half of the crop lives where. See [renderer-2d](https://github.com/iceonfire/inglorious-forge/tree/main/packages/renderer-2d).
32
- - **Screens that share a world**: `scenes()` puts a state's entities up and takes the last state's down, leaving whatever the two have in common standing.
32
+ - **Screens that share a world**: `scenes()` puts a state's entities up and takes the last state's down, leaving whatever the two have in common standing. It and `fsm()` are general-purpose behaviors, so they live in [Inglorious Store](https://github.com/IngloriousCoderz/inglorious-forge/tree/main/packages/store).
33
33
  - **A mistyped type is an error**: the engine refuses a configuration whose entity names a type nothing declared, and says which type was nearly meant.
34
34
 
35
35
  ### Scenes
36
36
 
37
37
  A state machine says when it moves; `scenes()` says what each state is made of. Pair them
38
- and each screen is a description of what should be standing there:
38
+ and each screen is a description of what should be standing there. Neither knows anything
39
+ about games, so both come from `@inglorious/store`:
39
40
 
40
41
  ```javascript
41
- import { fsm } from "@inglorious/engine/behaviors/fsm.js"
42
- import { scenes } from "@inglorious/engine/behaviors/scenes.js"
42
+ import { fsm } from "@inglorious/store/fsm"
43
+ import { scenes } from "@inglorious/store/scenes"
43
44
 
44
45
  const SCENES = {
45
46
  title: () => [createTitleEntity(), createMenuEntity()],
@@ -409,6 +410,8 @@ The core engine relies on a few key, lightweight packages:
409
410
 
410
411
  If you prefer to avoid a build step, you can run the engine directly in the browser. The example below demonstrates how to set up a minimal game using ES modules, an `importmap`, and the 2D canvas renderer.
411
412
 
413
+ An import map knows nothing of a package's `exports`, so without a bundler import files by their real path: `@inglorious/store/behaviors/state-machine/fsm.js` rather than `@inglorious/store/fsm`.
414
+
412
415
  ```html
413
416
  <!DOCTYPE html>
414
417
  <html lang="en">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inglorious/engine",
3
- "version": "23.0.7",
3
+ "version": "24.1.0",
4
4
  "description": "A JavaScript game engine written with global state, immutability, and pure functions in mind. Have fun(ctional programming) with it!",
5
5
  "author": "Matteo Antony Mistretta <antony.mistretta@gmail.com> (https://ingloriouscoderz.it)",
6
6
  "license": "MIT",
@@ -33,8 +33,8 @@
33
33
  },
34
34
  "sideEffects": false,
35
35
  "dependencies": {
36
- "@inglorious/store": "11.2.0",
37
- "@inglorious/utils": "5.0.0"
36
+ "@inglorious/store": "12.0.0",
37
+ "@inglorious/utils": "5.1.0"
38
38
  },
39
39
  "peerDependencies": {
40
40
  "vitest": "^5.0.0"
@@ -1,6 +1,7 @@
1
- import { matchVelocity } from "@inglorious/engine/ai/movement/dynamic/match-velocity.js"
2
1
  import { magnitude, setMagnitude, subtract } from "@inglorious/utils/vector.js"
3
2
 
3
+ import { matchVelocity } from "./match-velocity.js"
4
+
4
5
  export const DEFAULT_TARGET_RADIUS = 1
5
6
  export const DEFAULT_SLOW_RADIUS = 100
6
7
  export const DEFAULT_TIME_TO_TARGET = 0.1
@@ -1,4 +1,3 @@
1
- import { flee } from "@inglorious/engine/ai/movement/dynamic/flee.js"
2
1
  import {
3
2
  magnitude,
4
3
  multiply,
@@ -7,6 +6,8 @@ import {
7
6
  zero,
8
7
  } from "@inglorious/utils/vector.js"
9
8
 
9
+ import { flee } from "./flee.js"
10
+
10
11
  export const DEFAULT_MAX_PREDICTION = 10
11
12
 
12
13
  export function evade(
@@ -1,6 +1,7 @@
1
- import { align } from "@inglorious/engine/ai/movement/dynamic/align.js"
2
1
  import { angle, magnitude, subtract } from "@inglorious/utils/vector.js"
3
2
 
3
+ import { align } from "./align.js"
4
+
4
5
  export function face(entity, target, dt, options) {
5
6
  const direction = subtract(target.position, entity.position)
6
7
  const distance = magnitude(direction)
@@ -1,6 +1,7 @@
1
- import { align } from "@inglorious/engine/ai/movement/dynamic/align.js"
2
1
  import { angle, magnitude, zero } from "@inglorious/utils/vector.js"
3
2
 
3
+ import { align } from "./align.js"
4
+
4
5
  export function lookWhereYoureGoing(entity, dt, options) {
5
6
  const velocity = entity.velocity ?? zero()
6
7
 
@@ -1,4 +1,3 @@
1
- import { seek } from "@inglorious/engine/ai/movement/dynamic/seek.js"
2
1
  import {
3
2
  magnitude,
4
3
  multiply,
@@ -7,6 +6,8 @@ import {
7
6
  zero,
8
7
  } from "@inglorious/utils/vector.js"
9
8
 
9
+ import { seek } from "./seek.js"
10
+
10
11
  export const DEFAULT_MAX_PREDICTION = 10
11
12
 
12
13
  export function pursue(
@@ -1,7 +1,8 @@
1
- import { seek } from "@inglorious/engine/ai/movement/dynamic/seek.js"
2
1
  import { randomBinomial } from "@inglorious/utils/math/rng.js"
3
2
  import { createVector, sum } from "@inglorious/utils/vector.js"
4
3
 
4
+ import { seek } from "./seek.js"
5
+
5
6
  export const DEFAULT_WANDER_OFFSET = 100
6
7
  export const DEFAULT_WANDER_RADIUS = 100
7
8
 
@@ -1,6 +1,7 @@
1
- import { align } from "@inglorious/engine/ai/movement/kinematic/align.js"
2
1
  import { angle, magnitude, subtract } from "@inglorious/utils/vector.js"
3
2
 
3
+ import { align } from "./align.js"
4
+
4
5
  export function face(entity, target, dt, options) {
5
6
  const direction = subtract(target.position, entity.position)
6
7
  const distance = magnitude(direction)
@@ -1,7 +1,8 @@
1
- import { seek } from "@inglorious/engine/ai/movement/kinematic/seek.js"
2
1
  import { randomBinomial } from "@inglorious/utils/math/rng.js"
3
2
  import { fromAngle, multiply, sum } from "@inglorious/utils/vector.js"
4
3
 
4
+ import { seek } from "./seek.js"
5
+
5
6
  export const DEFAULT_WANDER_RADIUS = 10
6
7
 
7
8
  const DEFAULT_MAX_ANGULAR_SPEED = 0
@@ -1,8 +1,9 @@
1
1
  /* eslint-disable no-magic-numbers */
2
- import { Ticker } from "@inglorious/engine/animation/ticker.js"
3
2
  import { mod } from "@inglorious/utils/math/number.js"
4
3
  import { pi, toRange } from "@inglorious/utils/math/trigonometry.js"
5
4
 
5
+ import { Ticker } from "./ticker.js"
6
+
6
7
  export const Sprite = {
7
8
  fromAngle,
8
9
  move2,
@@ -1,4 +1,4 @@
1
- import { dueAt } from "@inglorious/engine/animation/due.js"
1
+ import { dueAt } from "../animation/due.js"
2
2
 
3
3
  const ONE_SECOND = 1
4
4
 
@@ -1,29 +1,5 @@
1
1
  const DEFAULT_VOLUME = 1
2
2
 
3
- /**
4
- * Fetches and decodes one sound. A sound that is missing, or that the browser
5
- * cannot decode, is reported and skipped: losing one effect is not worth refusing
6
- * to start.
7
- */
8
- async function load(context, cache, name, url) {
9
- try {
10
- const response = await fetch(url)
11
-
12
- if (!response.ok) {
13
- console.warn(`Sound '${name}' could not be fetched from ${url}`)
14
- return
15
- }
16
-
17
- const audioBuffer = await context.decodeAudioData(
18
- await response.arrayBuffer(),
19
- )
20
-
21
- cache.set(name, audioBuffer)
22
- } catch (error) {
23
- console.warn(`Sound '${name}' could not be loaded from ${url}`, error)
24
- }
25
- }
26
-
27
3
  export function audio() {
28
4
  const audioBufferCache = new Map()
29
5
  const activeSources = new Map()
@@ -117,3 +93,27 @@ export function audio() {
117
93
  destroy: release,
118
94
  }
119
95
  }
96
+
97
+ /**
98
+ * Fetches and decodes one sound. A sound that is missing, or that the browser
99
+ * cannot decode, is reported and skipped: losing one effect is not worth refusing
100
+ * to start.
101
+ */
102
+ async function load(context, cache, name, url) {
103
+ try {
104
+ const response = await fetch(url)
105
+
106
+ if (!response.ok) {
107
+ console.warn(`Sound '${name}' could not be fetched from ${url}`)
108
+ return
109
+ }
110
+
111
+ const audioBuffer = await context.decodeAudioData(
112
+ await response.arrayBuffer(),
113
+ )
114
+
115
+ cache.set(name, audioBuffer)
116
+ } catch (error) {
117
+ console.warn(`Sound '${name}' could not be loaded from ${url}`, error)
118
+ }
119
+ }
@@ -1,7 +1,8 @@
1
- import { arrive } from "@inglorious/engine/ai/movement/dynamic/arrive.js"
2
1
  import { lerp } from "@inglorious/utils/math/linear-interpolation.js"
3
2
  import { defaults, extend, merge } from "@inglorious/utils/object.js"
4
3
 
4
+ import { arrive } from "../ai/movement/dynamic/arrive.js"
5
+
5
6
  const DEFAULT_PARAMS = {
6
7
  zoom: 1,
7
8
  zoomSpeed: 0.1,
@@ -1,7 +1,7 @@
1
- import { modernMove } from "@inglorious/engine/movement/dynamic/modern.js"
2
1
  import { extend, merge } from "@inglorious/utils/object.js"
3
2
  import { zero } from "@inglorious/utils/vector.js"
4
3
 
4
+ import { modernMove } from "../../../movement/dynamic/modern.js"
5
5
  import { createMovementEventHandlers } from "../event-handlers.js"
6
6
 
7
7
  const DEFAULT_PARAMS = {
@@ -1,9 +1,9 @@
1
- import { face } from "@inglorious/engine/ai/movement/dynamic/face.js"
2
- import { tankMove } from "@inglorious/engine/movement/dynamic/tank.js"
3
1
  import { pi } from "@inglorious/utils/math/trigonometry.js"
4
2
  import { extend, merge } from "@inglorious/utils/object.js"
5
3
  import { zero } from "@inglorious/utils/vector.js"
6
4
 
5
+ import { face } from "../../../ai/movement/dynamic/face.js"
6
+ import { tankMove } from "../../../movement/dynamic/tank.js"
7
7
  import { createMovementEventHandlers } from "../event-handlers.js"
8
8
 
9
9
  const FULL_CIRCLE = 2
@@ -1,7 +1,7 @@
1
- import { tankMove } from "@inglorious/engine/movement/dynamic/tank.js"
2
1
  import { extend, merge } from "@inglorious/utils/object.js"
3
2
  import { zero } from "@inglorious/utils/vector.js"
4
3
 
4
+ import { tankMove } from "../../../movement/dynamic/tank.js"
5
5
  import { createMovementEventHandlers } from "../event-handlers.js"
6
6
 
7
7
  const DEFAULT_PARAMS = {
@@ -1,7 +1,7 @@
1
- import { modernMove } from "@inglorious/engine/movement/kinematic/modern.js"
2
1
  import { extend, merge } from "@inglorious/utils/object.js"
3
2
  import { zero } from "@inglorious/utils/vector.js"
4
3
 
4
+ import { modernMove } from "../../../movement/kinematic/modern.js"
5
5
  import { createMovementEventHandlers } from "../event-handlers.js"
6
6
 
7
7
  const DEFAULT_PARAMS = {
@@ -1,9 +1,9 @@
1
- import { face } from "@inglorious/engine/ai/movement/kinematic/face.js"
2
- import { tankMove } from "@inglorious/engine/movement/kinematic/tank.js"
3
1
  import { pi } from "@inglorious/utils/math/trigonometry.js"
4
2
  import { extend, merge } from "@inglorious/utils/object.js"
5
3
  import { zero } from "@inglorious/utils/vector.js"
6
4
 
5
+ import { face } from "../../../ai/movement/kinematic/face.js"
6
+ import { tankMove } from "../../../movement/kinematic/tank.js"
7
7
  import { createMovementEventHandlers } from "../event-handlers.js"
8
8
 
9
9
  const FULL_CIRCLE = 2
@@ -1,7 +1,7 @@
1
- import { tankMove } from "@inglorious/engine/movement/kinematic/tank.js"
2
1
  import { extend, merge } from "@inglorious/utils/object.js"
3
2
  import { zero } from "@inglorious/utils/vector.js"
4
3
 
4
+ import { tankMove } from "../../../movement/kinematic/tank.js"
5
5
  import { createMovementEventHandlers } from "../event-handlers.js"
6
6
 
7
7
  const DEFAULT_PARAMS = {
@@ -1,6 +1,7 @@
1
- import { Ticker } from "@inglorious/engine/animation/ticker.js"
2
1
  import { extend } from "@inglorious/utils/object.js"
3
2
 
3
+ import { Ticker } from "../animation/ticker.js"
4
+
4
5
  const DEFAULT_PARAMS = {
5
6
  accuracy: 1,
6
7
  size: 16,
@@ -1,4 +1,4 @@
1
- import { findCollision } from "@inglorious/engine/collision/detection.js"
1
+ import { findCollision } from "../../collision/detection.js"
2
2
 
3
3
  const HAND = "hand"
4
4
  const DEFAULT_CURSOR = "arrow"
@@ -1,7 +1,8 @@
1
- import { findCollision } from "@inglorious/engine/collision/detection.js"
2
- import { clampToBounds } from "@inglorious/engine/physics/bounds.js"
3
1
  import { zero } from "@inglorious/utils/vector.js"
4
2
 
3
+ import { findCollision } from "../../collision/detection.js"
4
+ import { clampToBounds } from "../../physics/bounds.js"
5
+
5
6
  export function mouse() {
6
7
  return {
7
8
  create(entity) {
@@ -1,8 +1,9 @@
1
- import { findCollision } from "@inglorious/engine/collision/detection.js"
2
- import { clampToBounds } from "@inglorious/engine/physics/bounds.js"
3
1
  import { v } from "@inglorious/utils/v.js"
4
2
  import { magnitude, subtract } from "@inglorious/utils/vector.js"
5
3
 
4
+ import { findCollision } from "../../collision/detection.js"
5
+ import { clampToBounds } from "../../physics/bounds.js"
6
+
6
7
  const MOVEMENT_THRESHOLD = 5
7
8
 
8
9
  export function touch() {
@@ -1,6 +1,7 @@
1
- import { clampToBounds } from "@inglorious/engine/physics/bounds.js"
2
1
  import { extend, merge } from "@inglorious/utils/object.js"
3
2
 
3
+ import { clampToBounds } from "../../physics/bounds.js"
4
+
4
5
  const DEFAULT_PARAMS = {
5
6
  collisionGroup: "bounds",
6
7
  depthAxis: "y",
@@ -1,9 +1,10 @@
1
- import { findCollision } from "@inglorious/engine/collision/detection.js"
2
1
  import { defaults, extend } from "@inglorious/utils/object.js"
3
2
  import { applyGravity } from "@inglorious/utils/physics/gravity.js"
4
3
  import { jump } from "@inglorious/utils/physics/jump.js"
5
4
  import { angle, magnitude, zero } from "@inglorious/utils/vector.js"
6
5
 
6
+ import { findCollision } from "../../collision/detection.js"
7
+
7
8
  const DEFAULT_PARAMS = {
8
9
  maxSpeed: 250,
9
10
  maxJump: 100,
@@ -1,4 +1,4 @@
1
- import { fsm } from "@inglorious/engine/behaviors/state-machine/fsm.js"
1
+ import { fsm } from "@inglorious/store/behaviors/state-machine/fsm.js"
2
2
 
3
3
  /**
4
4
  * A button that looks pressed while it is being pressed.
@@ -1,4 +1,3 @@
1
- import { anchorOffset, shapeAnchor } from "@inglorious/engine/physics/anchor.js"
2
1
  import * as circle from "@inglorious/utils/math/circle.js"
3
2
  import * as hitmask from "@inglorious/utils/math/hitmask.js"
4
3
  import * as line from "@inglorious/utils/math/line.js"
@@ -8,6 +7,8 @@ import * as segment from "@inglorious/utils/math/segment.js"
8
7
  import { filter } from "@inglorious/utils/object.js"
9
8
  import { add, zero } from "@inglorious/utils/vector.js"
10
9
 
10
+ import { anchorOffset, shapeAnchor } from "../physics/anchor.js"
11
+
11
12
  const Z = 2 // Z-axis index.
12
13
  const RECTANGLE = "rectangle"
13
14
 
@@ -49,27 +50,6 @@ export function collidesWith(entity, target, collisionGroup = "hitbox") {
49
50
  return shapeCollidesWith(entityShape, targetShape)
50
51
  }
51
52
 
52
- function shapeCollidesWith(entity, target) {
53
- const shapeFns = Shape[entity.shape]
54
-
55
- switch (target.shape) {
56
- case "circle":
57
- return shapeFns.intersectsCircle(entity, target)
58
-
59
- case "line":
60
- return shapeFns.intersectsLine(entity, target)
61
-
62
- case "point":
63
- return shapeFns.intersectsPoint(entity, target)
64
-
65
- case "rectangle":
66
- return shapeFns.intersectsRectangle(entity, target)
67
-
68
- case "segment":
69
- return shapeFns.intersectsSegment(entity, target)
70
- }
71
- }
72
-
73
53
  export function findCollisions(entity, target, collisionGroup = "hitbox") {
74
54
  const entityShape = getCollisionShape(entity, collisionGroup)
75
55
  const targetShape = getCollisionShape(target, collisionGroup)
@@ -138,3 +118,24 @@ function getCollisionShape(entity, collisionGroup = "hitbox") {
138
118
  radius: collision.radius ?? entity.radius,
139
119
  }
140
120
  }
121
+
122
+ function shapeCollidesWith(entity, target) {
123
+ const shapeFns = Shape[entity.shape]
124
+
125
+ switch (target.shape) {
126
+ case "circle":
127
+ return shapeFns.intersectsCircle(entity, target)
128
+
129
+ case "line":
130
+ return shapeFns.intersectsLine(entity, target)
131
+
132
+ case "point":
133
+ return shapeFns.intersectsPoint(entity, target)
134
+
135
+ case "rectangle":
136
+ return shapeFns.intersectsRectangle(entity, target)
137
+
138
+ case "segment":
139
+ return shapeFns.intersectsSegment(entity, target)
140
+ }
141
+ }
@@ -1,6 +1,3 @@
1
- import { audio } from "@inglorious/engine/behaviors/audio.js"
2
- import { game } from "@inglorious/engine/behaviors/game.js"
3
- import { images } from "@inglorious/engine/behaviors/images.js"
4
1
  import { createApi } from "@inglorious/store/api.js"
5
2
  import { createDevtools } from "@inglorious/store/client/devtools.js"
6
3
  import { multiplayerMiddleware } from "@inglorious/store/client/multiplayer-middleware.js"
@@ -15,6 +12,9 @@ import { extendWith, isObject } from "@inglorious/utils/object.js"
15
12
  import { v } from "@inglorious/utils/v.js"
16
13
  import { isVector } from "@inglorious/utils/vector.js"
17
14
 
15
+ import { audio } from "../behaviors/audio.js"
16
+ import { game } from "../behaviors/game.js"
17
+ import { images } from "../behaviors/images.js"
18
18
  import { coreEvents } from "./core-events.js"
19
19
  import { Loop } from "./loops/index.js"
20
20
  import { entityPoolMiddleware } from "./middlewares/entity-pool/entity-pool-middleware.js"
@@ -1,7 +1,7 @@
1
- import { findCollision } from "@inglorious/engine/collision/detection.js"
2
1
  import { createApi } from "@inglorious/store/api.js"
3
2
  import { EventMap } from "@inglorious/store/event-map.js"
4
3
 
4
+ import { findCollision } from "../../../collision/detection.js"
5
5
  import { EntityPools } from "./entity-pools"
6
6
 
7
7
  export function entityPoolMiddleware() {
package/src/main.js CHANGED
@@ -1,7 +1,8 @@
1
- import { Engine } from "@inglorious/engine/core/engine.js"
2
1
  import { createRenderer } from "@inglorious/renderer-2d/index.js"
3
2
  import game from "game"
4
3
 
4
+ import { Engine } from "./core/engine.js"
5
+
5
6
  window.addEventListener("load", async () => {
6
7
  const canvas = document.getElementById("canvas")
7
8
  const renderer = createRenderer(canvas)
@@ -1,8 +1,3 @@
1
- import {
2
- anchorMargins,
3
- entityAnchor,
4
- shapeAnchor,
5
- } from "@inglorious/engine/physics/anchor.js"
6
1
  import { abs } from "@inglorious/utils/math/number.js"
7
2
  import { v } from "@inglorious/utils/v.js"
8
3
  import {
@@ -15,6 +10,8 @@ import {
15
10
  zero,
16
11
  } from "@inglorious/utils/vector.js"
17
12
 
13
+ import { anchorMargins, entityAnchor, shapeAnchor } from "./anchor.js"
14
+
18
15
  const ORIGIN = 0
19
16
  const DOUBLE = 2
20
17
  const X = 0
package/src/storage.js CHANGED
@@ -1,9 +1,5 @@
1
1
  const DEFAULT_STORAGE = () => globalThis.localStorage
2
2
 
3
- function store(storage) {
4
- return storage ?? DEFAULT_STORAGE()
5
- }
6
-
7
3
  /**
8
4
  * Reads a value back as JSON.
9
5
  *
@@ -51,3 +47,7 @@ export function writeJSON(key, value, storage) {
51
47
  return false
52
48
  }
53
49
  }
50
+
51
+ function store(storage) {
52
+ return storage ?? DEFAULT_STORAGE()
53
+ }
@@ -1,4 +1,4 @@
1
- import { Sprite } from "@inglorious/engine/animation/sprite.js"
1
+ import { Sprite } from "../animation/sprite.js"
2
2
 
3
3
  /**
4
4
  * Advances sprite animations for entities that have a sprite component
@@ -0,0 +1,61 @@
1
+ import { dueAt } from "../animation/due.js"
2
+
3
+ const ONE_SECOND = 1
4
+
5
+ /**
6
+ * A clock for a whole world that turns at a rate of its own.
7
+ *
8
+ * This is `atFps` for a world rather than for an entity. A board where everything moves
9
+ * together -- a generation of Life, a day for foxes and rabbits -- has one clock, kept
10
+ * here, and notifies `tick` whenever a turn is due. Whatever turns with the world handles
11
+ * `tick` instead of `update`, and the loop stays as fast as the screen takes it, so the
12
+ * pointer and the controls never wait on the world.
13
+ *
14
+ * It is also what lets a large world be cheap between turns. An entity with `atFps` is
15
+ * still handed every `update` to keep its own time, so every one of them is written to on
16
+ * every frame; an entity that only handles `tick` is left alone until the world turns.
17
+ *
18
+ * The event carries the time the turn covers, as `atFps` does: six frames of a sixtieth
19
+ * of a second are a tenth of a second, and a world moving by velocity times dt has to
20
+ * move by all of it.
21
+ *
22
+ * Halting the store stops the entities updating, but systems are still asked, so the
23
+ * clock hears the pause for itself. Without that the world would carry on turning
24
+ * underneath a pause that everything else is honouring.
25
+ *
26
+ * @param {Object} [options] - How the world turns.
27
+ * @param {number} [options.fps=Infinity] - Turns a second. `Infinity` for one a frame.
28
+ * @param {string} [options.event="tick"] - What a turn is called.
29
+ * @returns {Object} The system.
30
+ */
31
+ export function ticks({ fps = Infinity, event = "tick" } = {}) {
32
+ const isDue = dueAt(ONE_SECOND / fps)
33
+
34
+ let halted = false
35
+ let clock = 0
36
+
37
+ return {
38
+ pause() {
39
+ halted = true
40
+ },
41
+
42
+ resume() {
43
+ halted = false
44
+ },
45
+
46
+ update(entities, dt, api) {
47
+ if (halted) return
48
+
49
+ const { since, elapsed } = isDue(clock, dt)
50
+
51
+ clock = since
52
+
53
+ if (elapsed === undefined) return
54
+
55
+ // Notified rather than called, so that the turn reaches entities and systems alike,
56
+ // in the same pass: the store drains the queue before it publishes, and anything
57
+ // the turn notifies in its own right follows it in.
58
+ api.notify(event, elapsed)
59
+ },
60
+ }
61
+ }
@@ -1,55 +0,0 @@
1
- const DEFAULT_STATE = "default"
2
-
3
- export function fsm(states) {
4
- const uniqueEventNames = [
5
- ...new Set(Object.values(states).flatMap(Object.keys)),
6
- ]
7
-
8
- return (type) => {
9
- return {
10
- create(entity, payload, api) {
11
- type.create?.(entity, payload, api)
12
-
13
- entity.state ??= DEFAULT_STATE
14
- },
15
-
16
- ...uniqueEventNames.reduce(
17
- (acc, eventName) => ({
18
- ...acc,
19
-
20
- [eventName](entity, event, api) {
21
- const from = entity.state
22
-
23
- // A state answers for itself, and what it has to say replaces what the type
24
- // would have said. The type-stage handler is the default -- the thing every
25
- // state would otherwise do -- and a state takes it over by naming the same
26
- // event, which is how a state can take the way out for itself rather than
27
- // being quit by, without whatever answers by default having to know that
28
- // state exists.
29
- const handler = states[entity.state]?.[eventName] ?? type[eventName]
30
-
31
- handler?.(entity, event, api)
32
-
33
- announce(entity, from, api)
34
- },
35
- }),
36
- {},
37
- ),
38
- }
39
- }
40
- }
41
-
42
- /**
43
- * A machine announces where it has landed, but only when it has actually moved: a
44
- * handler that reads the state without changing it should not wake anything up.
45
- *
46
- * The announcement is broadcast and carries the id, rather than being addressed to
47
- * this entity, because what wants to hear it is usually something else.
48
- */
49
- function announce(entity, from, api) {
50
- const to = entity.state
51
-
52
- if (to === from) return
53
-
54
- api.notify("stateChange", { entityId: entity.id, from, to })
55
- }
@@ -1,89 +0,0 @@
1
- import { isDeepEqual } from "@inglorious/utils/object.js"
2
-
3
- /**
4
- * Puts an entity up, and takes down whatever the state before it had up.
5
- *
6
- * A state machine says when it moves; this says what each state is made of, and is
7
- * usually the pair to `fsm`. Together they cover the ordinary case of a game that is a
8
- * few screens and a world that survives the move between them -- a menu has nothing on it
9
- * that the play has, and two states of the same play have all of it in common.
10
- *
11
- * Only the difference between two states is touched. Anything they have in common is
12
- * left standing as it is, which is what carries whatever the two share from one into the
13
- * next without rebuilding it, and so without losing whatever the world has already done
14
- * to it.
15
- *
16
- * A thing that stands on both sides but is not configured the same way is patched rather
17
- * than rebuilt, so one state may take over part of it -- a keyboard whose keys mean
18
- * something else there -- without the rest of it being torn up to make room.
19
- *
20
- * @example
21
- * ```js
22
- * import { scenes } from "@inglorious/engine/behaviors/state-machine/scenes.js"
23
- * import { fsm } from "@inglorious/engine/behaviors/state-machine/fsm.js"
24
- *
25
- * const SCENES = {
26
- * title: () => [createTitleEntity(), createMenuEntity()],
27
- * play: () => [createPaddleEntity(), createBallEntity()],
28
- * }
29
- *
30
- * const types = {
31
- * Game: [scenes(SCENES), fsm({ title: { start(e) { e.state = "play" } } })],
32
- * }
33
- *
34
- * const entities = { game: { type: "Game", state: "title" } }
35
- * ```
36
- *
37
- * @param {object} scenesByState - What stands in each state, given the state and the
38
- * entity asking. Returns the entity configurations to have standing.
39
- * @returns {object} The behaviour.
40
- */
41
- export function scenes(scenesByState) {
42
- function build(entity, state, api) {
43
- const leaving = entity.scene ?? []
44
- const arriving = scenesByState[state]?.(entity) ?? []
45
-
46
- const leavingIds = leaving.map(({ id }) => id)
47
- const arrivingIds = arriving.map(({ id }) => id)
48
-
49
- for (const { id } of leaving) {
50
- if (arrivingIds.includes(id)) continue
51
-
52
- api.notify("remove", id)
53
- }
54
-
55
- for (const added of arriving) {
56
- if (!leavingIds.includes(added.id)) {
57
- api.notify("add", added)
58
-
59
- continue
60
- }
61
-
62
- // The same thing stands on both sides of the move, so it is neither added nor
63
- // removed -- but it may be wanted to be a different thing now, and then only what
64
- // has actually changed is merged over it. That is what leaves a shared thing where
65
- // the world had put it when the next state says nothing different about it.
66
- const previous = leaving.find(({ id }) => id === added.id)
67
-
68
- if (!isDeepEqual(previous, added)) {
69
- api.notify("patch", added)
70
- }
71
- }
72
-
73
- entity.scene = arriving
74
- }
75
-
76
- return {
77
- create(entity, payload, api) {
78
- build(entity, entity.state, api)
79
- },
80
-
81
- // The announcement is broadcast and carries the id, so that anything else listening
82
- // for it can tell which machine moved. This one is only interested in its own.
83
- stateChange(entity, { entityId, to }, api) {
84
- if (entityId !== entity.id) return
85
-
86
- build(entity, to, api)
87
- },
88
- }
89
- }