@yaks/stage 0.0.0-stage → 0.2.36

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 (79) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +73 -2
  3. package/_dist/aim.d.ts +14 -0
  4. package/_dist/aim.d.ts.map +1 -0
  5. package/_dist/air.d.ts +23 -0
  6. package/_dist/air.d.ts.map +1 -0
  7. package/_dist/bus.d.ts +8 -0
  8. package/_dist/bus.d.ts.map +1 -0
  9. package/_dist/cam.d.ts +75 -0
  10. package/_dist/cam.d.ts.map +1 -0
  11. package/_dist/ears.d.ts +71 -0
  12. package/_dist/ears.d.ts.map +1 -0
  13. package/_dist/flames.d.ts +10 -0
  14. package/_dist/flames.d.ts.map +1 -0
  15. package/_dist/fx.d.ts +27 -0
  16. package/_dist/fx.d.ts.map +1 -0
  17. package/_dist/halo.d.ts +4 -0
  18. package/_dist/halo.d.ts.map +1 -0
  19. package/_dist/instances.d.ts +24 -0
  20. package/_dist/instances.d.ts.map +1 -0
  21. package/_dist/mod.d.ts +7 -0
  22. package/_dist/mod.d.ts.map +1 -0
  23. package/_dist/pace.d.ts +19 -0
  24. package/_dist/pace.d.ts.map +1 -0
  25. package/_dist/render.d.ts +7 -0
  26. package/_dist/render.d.ts.map +1 -0
  27. package/_dist/samples.d.ts +27 -0
  28. package/_dist/samples.d.ts.map +1 -0
  29. package/_dist/scene.d.ts +28 -0
  30. package/_dist/scene.d.ts.map +1 -0
  31. package/_dist/sound.d.ts +13 -0
  32. package/_dist/sound.d.ts.map +1 -0
  33. package/aim.js +63 -0
  34. package/aim.js.map +1 -0
  35. package/aim.ts +71 -0
  36. package/air.js +40 -0
  37. package/air.js.map +1 -0
  38. package/air.ts +66 -0
  39. package/bus.js +36 -0
  40. package/bus.js.map +1 -0
  41. package/bus.ts +51 -0
  42. package/cam.js +110 -0
  43. package/cam.js.map +1 -0
  44. package/cam.ts +181 -0
  45. package/deno.json +1 -0
  46. package/ears.js +123 -0
  47. package/ears.js.map +1 -0
  48. package/ears.ts +131 -0
  49. package/flames.js +61 -0
  50. package/flames.js.map +1 -0
  51. package/flames.ts +69 -0
  52. package/fx.js +235 -0
  53. package/fx.js.map +1 -0
  54. package/fx.ts +330 -0
  55. package/halo.js +22 -0
  56. package/halo.js.map +1 -0
  57. package/halo.ts +23 -0
  58. package/instances.js +131 -0
  59. package/instances.js.map +1 -0
  60. package/instances.ts +166 -0
  61. package/mod.js +5 -0
  62. package/mod.js.map +1 -0
  63. package/mod.ts +7 -0
  64. package/pace.js +63 -0
  65. package/pace.js.map +1 -0
  66. package/pace.ts +86 -0
  67. package/package.json +73 -4
  68. package/render.js +50 -0
  69. package/render.js.map +1 -0
  70. package/render.ts +68 -0
  71. package/samples.js +162 -0
  72. package/samples.js.map +1 -0
  73. package/samples.ts +204 -0
  74. package/scene.js +80 -0
  75. package/scene.js.map +1 -0
  76. package/scene.ts +112 -0
  77. package/sound.js +117 -0
  78. package/sound.js.map +1 -0
  79. package/sound.ts +175 -0
package/cam.ts ADDED
@@ -0,0 +1,181 @@
1
+ // The camera: behind and above the hero, turned by dragging and pulled in or
2
+ // out by the wheel. It keeps the chosen orbit until asked to swing behind the
3
+ // hero (`snap`). It keeps its distance unless a hill or a house is in the way,
4
+ // when it comes in at once, and it eases back
5
+ // out after. While the hero is in a building it rises to look down into it
6
+ // over the walls, the roof and the floors over them faded (solid.ts
7
+ // `cutaway`), and that building's walls never pull it in. It sees from a
8
+ // little way before it out to where the fog hides everything, and no further
9
+ // (`depth`).
10
+ // @ts-types="npm:@types/three@^0.186.0"
11
+ import * as THREE from 'three'
12
+ export type CameraIntent = {
13
+ orbit: [number, number]
14
+ turn: number
15
+ zoom: number
16
+ look: boolean
17
+ snap: boolean
18
+ faceMove: boolean
19
+ }
20
+ let clamp = (n: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, n))
21
+
22
+ export type Cam = {
23
+ /** which way it looks from, round the hero: 0 looks from +z */
24
+ yaw: number
25
+ pitch: number
26
+ /** how far back it stands, and how far it can stand this frame */
27
+ dist: number
28
+ reach: number
29
+ /** the point it follows, eased after the hero */
30
+ x: number
31
+ y: number
32
+ z: number
33
+ shake: number
34
+ /** it is swinging round behind the hero */
35
+ snap: boolean
36
+ /** a free look keeps movement relative to the hero until steering or snap */
37
+ orbiting: boolean
38
+ /** the least it looks down, raised while the hero is in a building */
39
+ lift: number
40
+ }
41
+
42
+ /** How near the camera comes to the hero, in metres, when the level is in
43
+ * the way. */
44
+ export let CLOSEST = 1.2
45
+
46
+ /** How near the camera sees, in metres: as far out as the hero's nearest side
47
+ * ever comes, at its closest, so the depth buffer is as fine as it can be
48
+ * Nearer surfaces are clipped by the camera. */
49
+ export let NEAR = 0.5
50
+
51
+ /** Fit `camera`'s depth to what it can see: from NEAR out to the far edge of
52
+ * the level's fog, past which nothing shows. */
53
+ export let depth = (camera: THREE.PerspectiveCamera, fog: THREE.Fog): void => {
54
+ if (camera.near == NEAR && camera.far == fog.far) return
55
+ camera.near = NEAR
56
+ camera.far = fog.far
57
+ camera.updateProjectionMatrix()
58
+ }
59
+
60
+ // How fast it swings behind the hero when asked.
61
+ let SNAP = 12
62
+
63
+ /** Turn the camera for a frame: as the hands turned and pulled it, or round
64
+ * behind a hero facing `yaw` when asked. Holding the stick sideways cannot
65
+ * make the view spin.
66
+ *
67
+ * ```ts
68
+ * import { assertAlmostEquals, assertEquals } from '@std/assert'
69
+ * let hands = (move: [number, number], more = {}) => ({
70
+ * move, turn: 0, faceMove: false, jump: false, strike: false, ability: 0,
71
+ * dodge: false, talk: false, gather: false, drink: false, snap: false,
72
+ * mic: false,
73
+ * orbit: [0, 0] as [number, number], look: false, zoom: 0, ...more,
74
+ * })
75
+ * let cam = () => ({
76
+ * yaw: 0, pitch: 0.4, dist: 9, reach: 9, x: 0, y: 0, z: 0, shake: 0,
77
+ * snap: false, orbiting: false, lift: 0,
78
+ * })
79
+ * // A hero facing +x has the camera behind them at -x, which is yaw -π/2.
80
+ * let run = (c: ReturnType<typeof cam>, i: ReturnType<typeof hands>) => {
81
+ * for (let f = 0; f < 60; f++) steer(c, f ? { ...i, snap: false } : i, Math.PI / 2, 1 / 60)
82
+ * return c.yaw
83
+ * }
84
+ * assertAlmostEquals(run(cam(), hands([0, 0], { snap: true })), -Math.PI / 2, 1e-9)
85
+ * assertEquals(run(cam(), hands([1, 0])), 0)
86
+ * assertEquals(run(cam(), hands([1, 0], { faceMove: true })), 0)
87
+ * assertEquals(run(cam(), hands([0, 1], { look: true })), 0)
88
+ * let turned = cam()
89
+ * steer(turned, hands([0, 0], { turn: -6 }), Math.PI, 0.1)
90
+ * assertAlmostEquals(turned.yaw, 0.6)
91
+ * ```
92
+ */
93
+ export let steer = (
94
+ cam: Cam,
95
+ i: CameraIntent,
96
+ yaw: number,
97
+ dt: number,
98
+ ): void => {
99
+ let [dx, dy] = i.orbit
100
+ cam.yaw += dx - i.turn * dt
101
+ cam.pitch = clamp(cam.pitch + dy, 0.1, 1.3)
102
+ cam.dist = clamp(cam.dist * (1 + i.zoom * 0.12), 4, 22)
103
+ if (i.look && (dx || dy)) cam.orbiting = true
104
+ else if (dx || dy) cam.orbiting = false
105
+ if (i.snap) cam.snap = true
106
+ else if (dx || dy || i.turn || i.faceMove || i.look) cam.snap = false
107
+ let off = Math.atan2(
108
+ Math.sin(yaw + Math.PI - cam.yaw),
109
+ Math.cos(yaw + Math.PI - cam.yaw),
110
+ )
111
+ // A snap ends where it meant to: right behind the hero.
112
+ if (cam.snap && Math.abs(off) < 0.02) {
113
+ cam.yaw += off
114
+ cam.snap = false
115
+ cam.orbiting = false
116
+ return
117
+ }
118
+ if (cam.snap) cam.yaw += off * (1 - Math.exp(-dt * SNAP))
119
+ }
120
+
121
+ /** Free orbit changes the view, not where the keys say forward is. A turning
122
+ * key changes both the camera and the hero's heading this frame. The stick
123
+ * keeps moving in screen space so its direction remains direct on touch. */
124
+ export let moveLook = <I extends CameraIntent>(
125
+ cam: Cam,
126
+ i: I,
127
+ yaw: number,
128
+ dt: number,
129
+ ) => cam.orbiting && !i.faceMove ? yaw - Math.PI - i.turn * dt : cam.yaw
130
+
131
+ /** Which way the camera looks, in whole degrees clockwise from north (-z).
132
+ *
133
+ * ```ts
134
+ * import { assertEquals } from '@std/assert'
135
+ * assertEquals(bearing(0), 0) // from the south, looking north
136
+ * assertEquals(bearing(-Math.PI / 2), 90) // from the west, looking east
137
+ * assertEquals(bearing(Math.PI / 2 + 4 * Math.PI), 270)
138
+ * ```
139
+ */
140
+ export let bearing = (yaw: number): number =>
141
+ (Math.round(-yaw * 180 / Math.PI) % 360 + 360) % 360
142
+
143
+ /** Orbit around target, shortening the arm immediately when blocked and
144
+ * easing it back out. The caller supplies collision and the minimum pitch. */
145
+ export let aim = (
146
+ cam: Cam,
147
+ camera: THREE.Camera,
148
+ target: THREE.Vector3,
149
+ blocked: (point: THREE.Vector3) => boolean,
150
+ dt: number,
151
+ lift = 0,
152
+ ): void => {
153
+ cam.lift += (lift - cam.lift) * (1 - Math.exp(-dt * 3))
154
+ let pitch = Math.max(cam.pitch, cam.lift)
155
+ let cp = Math.cos(pitch)
156
+ let dir = new THREE.Vector3(
157
+ Math.sin(cam.yaw) * cp,
158
+ Math.sin(pitch),
159
+ Math.cos(cam.yaw) * cp,
160
+ )
161
+ let clear = cam.dist
162
+ for (let d = CLOSEST; d <= cam.dist; d += 0.4) {
163
+ let p = target.clone().addScaledVector(dir, d)
164
+ if (
165
+ blocked(p)
166
+ ) {
167
+ clear = Math.max(CLOSEST, d - 0.6)
168
+ break
169
+ }
170
+ }
171
+ cam.reach = clear < cam.reach
172
+ ? clear
173
+ : cam.reach + (clear - cam.reach) * (1 - Math.exp(-dt * 2.5))
174
+ camera.position.copy(target).addScaledVector(dir, cam.reach)
175
+ if (cam.shake > 0.002) {
176
+ camera.position.x += (Math.random() - 0.5) * cam.shake
177
+ camera.position.y += (Math.random() - 0.5) * cam.shake
178
+ cam.shake *= Math.exp(-dt * 12)
179
+ }
180
+ camera.lookAt(target)
181
+ }
package/deno.json ADDED
@@ -0,0 +1 @@
1
+ {"publish":{"exclude":["**/*_test.ts"]},"name":"@yaks/stage","version":"0.2.36","license":"Apache-2.0","description":"Three.js scenes, effects, instancing, orbit cameras, picking and positional sound over caller-supplied values.","exports":{".":"./mod.ts","./pace":"./pace.ts","./aim":"./aim.ts","./cam":"./cam.ts","./render":"./render.ts","./halo":"./halo.ts","./flames":"./flames.ts","./instances":"./instances.ts","./ears":"./ears.ts","./bus":"./bus.ts","./sound":"./sound.ts","./samples":"./samples.ts","./fx":"./fx.ts","./air":"./air.ts","./scene":"./scene.ts"},"imports":{"@yaks/stage":"./mod.ts","@yaks/stage/pace":"./pace.ts","@yaks/stage/aim":"./aim.ts","@yaks/stage/cam":"./cam.ts","@yaks/stage/render":"./render.ts","@yaks/stage/halo":"./halo.ts","@yaks/stage/flames":"./flames.ts","@yaks/stage/instances":"./instances.ts","@yaks/stage/ears":"./ears.ts","@yaks/stage/bus":"./bus.ts","@yaks/stage/sound":"./sound.ts","@yaks/stage/samples":"./samples.ts","@yaks/stage/fx":"./fx.ts","@yaks/stage/air":"./air.ts","@yaks/stage/scene":"./scene.ts"}}
package/ears.js ADDED
@@ -0,0 +1,123 @@
1
+ // The ears: one pair, standing at the listener and turned the way the camera
2
+ // looks, so the screen's right is theirs and a sound is as near as it is to
3
+ // the listener. With no target, they stand where the camera is. Web
4
+ // Audio pans and fades every sound in the scene by itself (sound.ts gives each
5
+ // source a PannerNode as its `Falloff` says, `FALLOFF` for most); `hear` is
6
+ // the same sum done by hand, so the page knows a sound too far off to hear
7
+ // before it makes one, and a test can say where a sound is heard.
8
+ // @ts-types="npm:@types/three@^0.186.0"
9
+ /** How positional sounds are heard. Inside 5 m they peak at 0.6;
10
+ * beyond 5 m this is the old 3 m inverse curve (3 / distance). */ export let FALLOFF = {
11
+ pan: {
12
+ panningModel: 'HRTF',
13
+ distanceModel: 'inverse',
14
+ refDistance: 5,
15
+ rolloffFactor: 1
16
+ },
17
+ near: 0.6
18
+ };
19
+ /** How water is heard: at its own loudness out to `refDistance`, but beyond
20
+ * that falling away with the square of the distance, so a lake is heard at
21
+ * its edge and gone some twenty metres off. */ export let NEAR = {
22
+ pan: {
23
+ ...FALLOFF.pan,
24
+ distanceModel: 'exponential',
25
+ refDistance: 3,
26
+ rolloffFactor: 2
27
+ },
28
+ near: 1
29
+ };
30
+ /** Below this loudness at the ears a sound is not made at all: a sound
31
+ * dies away within some 25 m, a louder sound carries further. */ export let QUIET = 0.004;
32
+ let sub = (a, b)=>[
33
+ a[0] - b[0],
34
+ a[1] - b[1],
35
+ a[2] - b[2]
36
+ ];
37
+ let dot = (a, b)=>a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
38
+ let cross = (a, b)=>[
39
+ a[1] * b[2] - a[2] * b[1],
40
+ a[2] * b[0] - a[0] * b[2],
41
+ a[0] * b[1] - a[1] * b[0]
42
+ ];
43
+ let norm = (a)=>{
44
+ let l = Math.hypot(...a) || 1;
45
+ return [
46
+ a[0] / l,
47
+ a[1] / l,
48
+ a[2] / l
49
+ ];
50
+ };
51
+ /** The ears for a camera: at `at`, the listener, or where the camera stands when
52
+ * there is no target; turned the way the camera looks down its own -z, held
53
+ * level, so the ground about the listener is at the height of the ears. */ export let ear = (eye, at)=>{
54
+ eye.updateMatrixWorld();
55
+ let m = eye.matrixWorld.elements;
56
+ return {
57
+ at: at ?? [
58
+ m[12],
59
+ m[13],
60
+ m[14]
61
+ ],
62
+ forward: norm([
63
+ -m[8],
64
+ 0,
65
+ -m[10]
66
+ ]),
67
+ up: [
68
+ 0,
69
+ 1,
70
+ 0
71
+ ]
72
+ };
73
+ };
74
+ /** What the ears make of a sound at `at`: how far to their right it is, from
75
+ * -1 hard left to 1 hard right; how far ahead, from -1 behind to 1 before
76
+ * them; and how loud, as `FALLOFF` hears it: `near` at `refDistance` or
77
+ * nearer. Right is forward × up, as Web Audio has it.
78
+ *
79
+ * ```ts
80
+ * import { assert, assertAlmostEquals, assertEquals } from '@std/assert'
81
+ * import * as THREE from 'three'
82
+ * // The camera behind and above a listener at (20, 6, 20), looking down at them,
83
+ * // and the ears at the listener.
84
+ * let eye = new THREE.PerspectiveCamera()
85
+ * eye.position.set(26, 10, 28)
86
+ * eye.lookAt(20, 6, 20)
87
+ * let target = new THREE.Vector3(20, 6, 20)
88
+ * let e = ear(eye, [20, 6, 20])
89
+ * // The camera's right as it draws it, and the way it looks, level.
90
+ * let right = new THREE.Vector3(1, 0, 0).applyQuaternion(eye.quaternion)
91
+ * let ahead = new THREE.Vector3(-6, 0, -8).normalize()
92
+ * let from = (dir: THREE.Vector3, d: number) => {
93
+ * let p = target.clone().addScaledVector(dir, d)
94
+ * return hear(e, [p.x, p.y, p.z])
95
+ * }
96
+ * // A sound to the listener's right on the screen is heard on the right, and to
97
+ * // their left on the left, whichever way the camera is turned.
98
+ * assertAlmostEquals(from(right, 5).side, 1, 1e-9)
99
+ * assertAlmostEquals(from(right, -5).side, -1, 1e-9)
100
+ * // On along the camera's view is ahead of the listener; the camera is behind.
101
+ * assertAlmostEquals(from(ahead, 5).ahead, 1, 1e-9)
102
+ * assert(hear(e, [26, 10, 28]).ahead < -0.8)
103
+ * // Beside the listener a sound is as loud as it is up close; further off it
104
+ * // fades.
105
+ * assertEquals(from(right, 2).gain, FALLOFF.near)
106
+ * assert(from(right, 12).gain < from(right, 8).gain)
107
+ * assertAlmostEquals(from(right, 5).gain, 3 / 5, 1e-9)
108
+ * assertAlmostEquals(from(right, 8).gain, 3 / 8, 1e-9)
109
+ * assertAlmostEquals(from(ahead, 40).gain, 3 / 40, 1e-9)
110
+ * // With no target, the ears are where the camera is.
111
+ * assertEquals(ear(eye).at, [26, 10, 28])
112
+ * ```
113
+ */ export let hear = (e, at)=>{
114
+ let to = sub(at, e.at);
115
+ let d = Math.hypot(...to);
116
+ let { pan: { refDistance: r = 1, rolloffFactor: k = 1 }, near } = FALLOFF;
117
+ return {
118
+ side: d ? dot(to, norm(cross(e.forward, e.up))) / d : 0,
119
+ ahead: d ? dot(to, e.forward) / d : 0,
120
+ gain: near * r / (r + k * (Math.max(d, r) - r))
121
+ };
122
+ };
123
+ //# sourceMappingURL=ears.js.map
package/ears.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ears.js","sources":["./ears.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,4EAA4E;AAC5E,oEAAoE;AACpE,+EAA+E;AAC/E,4EAA4E;AAC5E,2EAA2E;AAC3E,kEAAkE;AAClE,wCAAwC;AAaxC;gEACgE,GAChE,OAAO,IAAI,UAAmB;EAC5B,KAAK;IACH,cAAc;IACd,eAAe;IACf,aAAa;IACb,eAAe;EACjB;EACA,MAAM;AACR,EAAC;AAED;;6CAE6C,GAC7C,OAAO,IAAI,OAAgB;EACzB,KAAK;IACH,GAAG,QAAQ,GAAG;IACd,eAAe;IACf,aAAa;IACb,eAAe;EACjB;EACA,MAAM;AACR,EAAC;AAED;+DAC+D,GAC/D,OAAO,IAAI,QAAQ,MAAK;AAExB,IAAI,MAAM,CAAC,GAAS,IAAkB;IAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,EAAE;IAAE,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,EAAE;IAAE,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,EAAE;GAAC;AAC7E,IAAI,MAAM,CAAC,GAAS,IAAY,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,EAAE;AACvE,IAAI,QAAQ,CAAC,GAAS,IAAkB;IACtC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,EAAE;IACzB,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,EAAE;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standing at the listener and turned the way the camera
2
+ // looks, so the screen's right is theirs and a sound is as near as it is to
3
+ // the listener. With no target, they stand where the camera is. Web
4
+ // Audio pans and fades every sound in the scene by itself (sound.ts gives each
5
+ // source a PannerNode as its `Falloff` says, `FALLOFF` for most); `hear` is
6
+ // the same sum done by hand, so the page knows a sound too far off to hear
7
+ // before it makes one, and a test can say where a sound is heard.
8
+ // @ts-types="npm:@types/three@^0.186.0"
9
+ import type * as THREE from 'npm:three@^0.186.1'
10
+ export type Vec3 = [number, number, number]
11
+
12
+ /** Where the ears are, which way they face, and which way is up for them:
13
+ * what Web Audio's `AudioListener` is told each frame. */
14
+ export type Ear = { at: Vec3; forward: Vec3; up: Vec3 }
15
+
16
+ /** How a source is heard: `pan` places it round the head and fades it with
17
+ * distance (Web Audio's PannerNode), and out to the panner's `refDistance` it
18
+ * is at `near` of its own loudness. */
19
+ export type Falloff = { pan: PannerOptions; near: number }
20
+
21
+ /** How positional sounds are heard. Inside 5 m they peak at 0.6;
22
+ * beyond 5 m this is the old 3 m inverse curve (3 / distance). */
23
+ export let FALLOFF: Falloff = {
24
+ pan: {
25
+ panningModel: 'HRTF',
26
+ distanceModel: 'inverse',
27
+ refDistance: 5,
28
+ rolloffFactor: 1,
29
+ },
30
+ near: 0.6,
31
+ }
32
+
33
+ /** How water is heard: at its own loudness out to `refDistance`, but beyond
34
+ * that falling away with the square of the distance, so a lake is heard at
35
+ * its edge and gone some twenty metres off. */
36
+ export let NEAR: Falloff = {
37
+ pan: {
38
+ ...FALLOFF.pan,
39
+ distanceModel: 'exponential',
40
+ refDistance: 3,
41
+ rolloffFactor: 2,
42
+ },
43
+ near: 1,
44
+ }
45
+
46
+ /** Below this loudness at the ears a sound is not made at all: a sound
47
+ * dies away within some 25 m, a louder sound carries further. */
48
+ export let QUIET = 0.004
49
+
50
+ let sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
51
+ let dot = (a: Vec3, b: Vec3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
52
+ let cross = (a: Vec3, b: Vec3): Vec3 => [
53
+ a[1] * b[2] - a[2] * b[1],
54
+ a[2] * b[0] - a[0] * b[2],
55
+ a[0] * b[1] - a[1] * b[0],
56
+ ]
57
+ let norm = (a: Vec3): Vec3 => {
58
+ let l = Math.hypot(...a) || 1
59
+ return [a[0] / l, a[1] / l, a[2] / l]
60
+ }
61
+
62
+ /** The ears for a camera: at `at`, the listener, or where the camera stands when
63
+ * there is no target; turned the way the camera looks down its own -z, held
64
+ * level, so the ground about the listener is at the height of the ears. */
65
+ export let ear = (eye: THREE.Object3D, at?: Vec3): Ear => {
66
+ eye.updateMatrixWorld()
67
+ let m = eye.matrixWorld.elements
68
+ return {
69
+ at: at ?? [m[12], m[13], m[14]],
70
+ forward: norm([-m[8], 0, -m[10]]),
71
+ up: [0, 1, 0],
72
+ }
73
+ }
74
+
75
+ /** The source's normalized direction and distance-attenuated gain. */
76
+ export interface Hearing {
77
+ side: number
78
+ ahead: number
79
+ gain: number
80
+ }
81
+
82
+ /** What the ears make of a sound at `at`: how far to their right it is, from
83
+ * -1 hard left to 1 hard right; how far ahead, from -1 behind to 1 before
84
+ * them; and how loud, as `FALLOFF` hears it: `near` at `refDistance` or
85
+ * nearer. Right is forward × up, as Web Audio has it.
86
+ *
87
+ * ```ts
88
+ * import { assert, assertAlmostEquals, assertEquals } from '@std/assert'
89
+ * import * as THREE from 'three'
90
+ * // The camera behind and above a listener at (20, 6, 20), looking down at them,
91
+ * // and the ears at the listener.
92
+ * let eye = new THREE.PerspectiveCamera()
93
+ * eye.position.set(26, 10, 28)
94
+ * eye.lookAt(20, 6, 20)
95
+ * let target = new THREE.Vector3(20, 6, 20)
96
+ * let e = ear(eye, [20, 6, 20])
97
+ * // The camera's right as it draws it, and the way it looks, level.
98
+ * let right = new THREE.Vector3(1, 0, 0).applyQuaternion(eye.quaternion)
99
+ * let ahead = new THREE.Vector3(-6, 0, -8).normalize()
100
+ * let from = (dir: THREE.Vector3, d: number) => {
101
+ * let p = target.clone().addScaledVector(dir, d)
102
+ * return hear(e, [p.x, p.y, p.z])
103
+ * }
104
+ * // A sound to the listener's right on the screen is heard on the right, and to
105
+ * // their left on the left, whichever way the camera is turned.
106
+ * assertAlmostEquals(from(right, 5).side, 1, 1e-9)
107
+ * assertAlmostEquals(from(right, -5).side, -1, 1e-9)
108
+ * // On along the camera's view is ahead of the listener; the camera is behind.
109
+ * assertAlmostEquals(from(ahead, 5).ahead, 1, 1e-9)
110
+ * assert(hear(e, [26, 10, 28]).ahead < -0.8)
111
+ * // Beside the listener a sound is as loud as it is up close; further off it
112
+ * // fades.
113
+ * assertEquals(from(right, 2).gain, FALLOFF.near)
114
+ * assert(from(right, 12).gain < from(right, 8).gain)
115
+ * assertAlmostEquals(from(right, 5).gain, 3 / 5, 1e-9)
116
+ * assertAlmostEquals(from(right, 8).gain, 3 / 8, 1e-9)
117
+ * assertAlmostEquals(from(ahead, 40).gain, 3 / 40, 1e-9)
118
+ * // With no target, the ears are where the camera is.
119
+ * assertEquals(ear(eye).at, [26, 10, 28])
120
+ * ```
121
+ */
122
+ export let hear = (e: Ear, at: Vec3): Hearing => {
123
+ let to = sub(at, e.at)
124
+ let d = Math.hypot(...to)
125
+ let { pan: { refDistance: r = 1, rolloffFactor: k = 1 }, near } = FALLOFF
126
+ return {
127
+ side: d ? dot(to, norm(cross(e.forward, e.up))) / d : 0,
128
+ ahead: d ? dot(to, e.forward) / d : 0,
129
+ gain: near * r / (r + k * (Math.max(d, r) - r)),
130
+ }
131
+ }
package/flames.js ADDED
@@ -0,0 +1,61 @@
1
+ // The live flame over a hearth or forge. Every fire in sight shares one
2
+ // instanced mesh, whether its building has just streamed in or out.
3
+ // @ts-types="npm:@types/three@^0.186.0"
4
+ import * as THREE from "three";
5
+ export let flames = (scene)=>{
6
+ let shape = new THREE.BoxGeometry(1, 1, 1);
7
+ let material = new THREE.MeshBasicMaterial({
8
+ color: 0xffffff,
9
+ transparent: true,
10
+ opacity: 0.85,
11
+ blending: THREE.AdditiveBlending,
12
+ depthWrite: false
13
+ });
14
+ let mesh = null, capacity = 0;
15
+ let fit = (n)=>{
16
+ if (n <= capacity) return;
17
+ capacity = Math.max(n, capacity * 2, 6);
18
+ if (mesh) scene.remove(mesh);
19
+ mesh = new THREE.InstancedMesh(shape, material, capacity);
20
+ mesh.frustumCulled = false;
21
+ mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
22
+ for(let i = 0; i < capacity; i++){
23
+ let color = [
24
+ 0xff6124,
25
+ 0xffa02e,
26
+ 0xffd15a
27
+ ][i % 3];
28
+ mesh.setColorAt(i, new THREE.Color(color));
29
+ }
30
+ if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
31
+ scene.add(mesh);
32
+ };
33
+ // Prepare the instanced-color shader at the gate, before any fire is near.
34
+ fit(1);
35
+ mesh.visible = false;
36
+ mesh.count = 0;
37
+ let matrix = new THREE.Matrix4(), at = new THREE.Vector3();
38
+ let turn = new THREE.Quaternion(), size = new THREE.Vector3();
39
+ return (t, focus, fires)=>{
40
+ let near = fires.filter((f)=>Math.hypot(f.at[0] - focus.x, f.at[2] - focus.z) < 110);
41
+ if (!near.length) {
42
+ if (mesh) mesh.visible = false;
43
+ return;
44
+ }
45
+ fit(near.length * 3);
46
+ mesh.visible = true;
47
+ mesh.count = near.length * 3;
48
+ near.forEach((f, i)=>{
49
+ for(let j = 0; j < 3; j++){
50
+ let lick = 1 + Math.sin(t * (8 + j * 3) + i * 7 + j) * 0.23;
51
+ let width = f.size * (1 - j * 0.22) * (2 - lick);
52
+ at.set(f.at[0] + Math.sin(t * 3 + j * 2 + i) * f.size * 0.25, f.at[1] + j * f.size * 0.3 + lick * f.size * 0.35, f.at[2] + Math.cos(t * 2 + j * 3 + i) * f.size * 0.18);
53
+ turn.setFromAxisAngle(THREE.Object3D.DEFAULT_UP, t * (j + 1));
54
+ size.set(width, f.size * (1 - j * 0.18) * lick * 1.3, width);
55
+ mesh.setMatrixAt(i * 3 + j, matrix.compose(at, turn, size));
56
+ }
57
+ });
58
+ mesh.instanceMatrix.needsUpdate = true;
59
+ };
60
+ };
61
+ //# sourceMappingURL=flames.js.map
package/flames.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"flames.js","sources":["./flames.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,oEAAoE;AACpE,wCAAwC;AACxC,YAAY,mBAA+B;AAQ3C,OAAO,IAAI,SAAS,CAAC;EACnB,IAAI,QAAQ,IAAI,MAAM,WAAW,CAAC,GAAG,GAAG;EACxC,IAAI,WAAW,IAAI,MAAM,iBAAiB,CAAC;IACzC,OAAO;IACP,aAAa;IACb,SAAS;IACT,UAAU,MAAM,gBAAgB;IAChC,YAAY;EACd;EACA,IAAI,OAAmC,MAAM,WAAW;EACxD,IAAI,MAAM,CAAC;IACT,IAAI,KAAK,UAAU;IACnB,WAAW,KAAK,GAAG,CAAC,GAAG,WAAW,GAAG;IACrC,IAAI,MAAM,MAAM,MAAM,CAAC;IACvB,OAAO,IAAI,MAAM,aAAa,CAAC,OAAO,UAAU;IAChD,KAAK,aAAa,GAAG;IACrB,KAAK,cAAc,CAAC,QAAQ,CAAC,MAAM,gBAAgB;IACnD,IAAK,IAAI,IAAI,GAAG,IAAI,UAAU,IAAK;MACjC,IAAI,QAAQ;QAAC;QAAU;QAAU;OAAS,CAAC,IAAI,EAAE;MACjD,KAAK,UAAU,CAAC,GAAG,IAAI,MAAM,KAAK,CAAC;IACrC;IACA,IAAI,KAAK,aAAa,EAAE,KAAK,aAAa,CAAC,WAAW,GAAG;IACzD,MAAM,GAAG,CAAC;EACZ;EACA,2EAA2E;EAC3E,IAAI;EACJ,KAAM,OAAO,GAAG;EAChB,KAAM,KAAK,GAAG;EACd,IAAI,SAAS,IAAI,MAAM,OAAO,IAAI,KAAK,IAAI,MAAM,OAAO;EACxD,IAAI,OAAO,IAAI,MAAM,UAAU,IAAI,OAAO,IAAI,MAAM,OAAO;E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C,WAAW,GAAG;EACrC;AACF,EAAC"}
package/flames.ts ADDED
@@ -0,0 +1,69 @@
1
+ // The live flame over a hearth or forge. Every fire in sight shares one
2
+ // instanced mesh, whether its building has just streamed in or out.
3
+ // @ts-types="npm:@types/three@^0.186.0"
4
+ import * as THREE from 'three'
5
+
6
+ export type Fire = { at: [number, number, number]; size: number }
7
+
8
+ /** Hang a flame mesh in `scene`, sized as fires come into sight, and return
9
+ * its motion for each frame. */
10
+ export type Flames = (t: number, focus: THREE.Vector3, fires: Fire[]) => void
11
+
12
+ export let flames = (scene: THREE.Scene): Flames => {
13
+ let shape = new THREE.BoxGeometry(1, 1, 1)
14
+ let material = new THREE.MeshBasicMaterial({
15
+ color: 0xffffff,
16
+ transparent: true,
17
+ opacity: 0.85,
18
+ blending: THREE.AdditiveBlending,
19
+ depthWrite: false,
20
+ })
21
+ let mesh: THREE.InstancedMesh | null = null, capacity = 0
22
+ let fit = (n: number) => {
23
+ if (n <= capacity) return
24
+ capacity = Math.max(n, capacity * 2, 6)
25
+ if (mesh) scene.remove(mesh)
26
+ mesh = new THREE.InstancedMesh(shape, material, capacity)
27
+ mesh.frustumCulled = false
28
+ mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage)
29
+ for (let i = 0; i < capacity; i++) {
30
+ let color = [0xff6124, 0xffa02e, 0xffd15a][i % 3]
31
+ mesh.setColorAt(i, new THREE.Color(color))
32
+ }
33
+ if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true
34
+ scene.add(mesh)
35
+ }
36
+ // Prepare the instanced-color shader at the gate, before any fire is near.
37
+ fit(1)
38
+ mesh!.visible = false
39
+ mesh!.count = 0
40
+ let matrix = new THREE.Matrix4(), at = new THREE.Vector3()
41
+ let turn = new THREE.Quaternion(), size = new THREE.Vector3()
42
+ return (t: number, focus: THREE.Vector3, fires: Fire[]) => {
43
+ let near = fires.filter((f) =>
44
+ Math.hypot(f.at[0] - focus.x, f.at[2] - focus.z) < 110
45
+ )
46
+ if (!near.length) {
47
+ if (mesh) mesh.visible = false
48
+ return
49
+ }
50
+ fit(near.length * 3)
51
+ mesh!.visible = true
52
+ mesh!.count = near.length * 3
53
+ near.forEach((f, i) => {
54
+ for (let j = 0; j < 3; j++) {
55
+ let lick = 1 + Math.sin(t * (8 + j * 3) + i * 7 + j) * 0.23
56
+ let width = f.size * (1 - j * 0.22) * (2 - lick)
57
+ at.set(
58
+ f.at[0] + Math.sin(t * 3 + j * 2 + i) * f.size * 0.25,
59
+ f.at[1] + j * f.size * 0.3 + lick * f.size * 0.35,
60
+ f.at[2] + Math.cos(t * 2 + j * 3 + i) * f.size * 0.18,
61
+ )
62
+ turn.setFromAxisAngle(THREE.Object3D.DEFAULT_UP, t * (j + 1))
63
+ size.set(width, f.size * (1 - j * 0.18) * lick * 1.3, width)
64
+ mesh!.setMatrixAt(i * 3 + j, matrix.compose(at, turn, size))
65
+ }
66
+ })
67
+ mesh!.instanceMatrix.needsUpdate = true
68
+ }
69
+ }