1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
//! Shortcuts on [`Context`] for the things almost every game does.
use glam::Vec3;
use crate::audio::Sound;
use crate::engine::Context;
use crate::input::Key;
use crate::physics::{BodyId, PhysicsEvent};
/// Storage key under which [`Context::set_language`] remembers the player's language.
pub(crate) const LANGUAGE_KEY: &str = "language";
/// A sound that follows a physics body.
#[derive(Debug)]
pub(crate) struct Attached {
body: BodyId,
sound: Sound,
last: Vec3,
}
impl Context {
/// Speaks text, interrupting current speech. Same as `ctx.speech.speak(text)`.
pub fn speak(&mut self, text: impl AsRef<str>) {
self.speech.speak(text);
}
/// The text for `key` in the current language. Same as `ctx.lang.get(key)`.
///
/// ```no_run
/// # use audio_code::prelude::*;
/// # fn f(ctx: &mut Context) {
/// ctx.speak(ctx.tr("intro"));
/// # }
/// ```
pub fn tr(&self, key: &str) -> String {
self.lang.get(key)
}
/// The text for `key` with `{name}` placeholders filled in. Same as
/// `ctx.lang.format(key, args)`.
///
/// ```no_run
/// # use audio_code::prelude::*;
/// # fn f(ctx: &mut Context, score: u32) {
/// // In lang/en.txt: score = You have {points} points.
/// ctx.speak(ctx.tr_with("score", &[("points", &score)]));
/// # }
/// ```
pub fn tr_with(&self, key: &str, args: &[(&str, &dyn std::fmt::Display)]) -> String {
self.lang.format(key, args)
}
/// Switches the language and remembers it in [`Context::storage`], so the game starts in
/// it next time. Returns `false` if there are no texts for it.
///
/// ```no_run
/// # use audio_code::prelude::*;
/// # fn f(ctx: &mut Context) {
/// let mut menu = Menu::new("language", "Language");
/// for code in ctx.lang.languages() {
/// menu = menu.button(code.clone(), ctx.lang.name(&code));
/// }
/// ctx.ui.open(menu);
/// // ...later, in update():
/// if let Some(code) = ctx.ui.activated("language").map(String::from) {
/// ctx.set_language(&code);
/// ctx.ui.close();
/// }
/// # }
/// ```
pub fn set_language(&mut self, code: &str) -> bool {
if !self.lang.set(code) {
return false;
}
let current = self.lang.current().to_string();
self.storage.set(LANGUAGE_KEY, current);
true
}
/// Where `target` is as seen from `from`, in the current language, e.g.
/// `"3 o'clock, 12 meters"` or `"3 Uhr, 12 Meter"`. Like
/// [`World::describe`](crate::physics::World::describe), which is always English.
pub fn describe(&self, from: BodyId, target: BodyId) -> String {
let world = &self.physics;
self.lang.describe_position(world.position(from), world.facing(from), world.position(target))
}
/// Plays a sound once. Same as `ctx.audio.play(name)`.
pub fn play(&mut self, name: &str) -> Sound {
self.audio.play(name)
}
/// Plays a sound once at a position. Same as `ctx.audio.play_at(name, position)`.
pub fn play_at(&mut self, name: &str, position: Vec3) -> Sound {
self.audio.play_at(name, position)
}
/// Whether a key went down this frame. Same as `ctx.input.pressed(key)`.
pub fn pressed(&self, key: Key) -> bool {
self.input.pressed(key)
}
/// Whether a key is held. Same as `ctx.input.held(key)`.
pub fn held(&self, key: Key) -> bool {
self.input.held(key)
}
/// Returns `true` the first time it is called with `name`, and `false` afterwards.
/// Handy for one-time setup in closure games and for "say this only once" hints.
///
/// ```no_run
/// # use audio_code::prelude::*;
/// # fn f(ctx: &mut Context) {
/// if ctx.once("intro") {
/// ctx.speak("Welcome! Press F1 for help.");
/// }
/// # }
/// ```
pub fn once(&mut self, name: &str) -> bool {
self.once.insert(name.to_string())
}
/// Makes the listener (the player's ears) follow a body every frame: its position, its
/// [`facing`](crate::physics::Body::facing) and its [`pitch`](crate::physics::Body::pitch). After this you never call
/// `ctx.audio.set_listener` yourself.
pub fn follow(&mut self, body: BodyId) {
self.follow = Some(body);
self.sync_world();
}
/// Stops following a body with the listener.
pub fn unfollow(&mut self) {
self.follow = None;
}
/// The body the listener follows, if any.
pub fn followed(&self) -> Option<BodyId> {
self.follow
}
/// Plays a sound once at a body; the sound moves with the body.
pub fn play_on(&mut self, body: BodyId, name: &str) -> Sound {
let sound = self.audio.play_at(name, self.physics.position(body));
self.attach(body, sound.clone());
sound
}
/// Plays a looping sound at a body. It moves with the body and stops automatically when
/// the body is removed. Perfect for enemies, engines, coins and beacons:
///
/// ```no_run
/// # use audio_code::prelude::*;
/// # fn f(ctx: &mut Context) {
/// let enemy = ctx.physics.add(Body::kinematic(vec3(5.0, 5.0, 0.0)).with_tag("enemy"));
/// ctx.loop_on(enemy, "growl");
/// # }
/// ```
pub fn loop_on(&mut self, body: BodyId, name: &str) -> Sound {
let sound = self.audio.play_looped_at(name, self.physics.position(body));
self.attach(body, sound.clone());
sound
}
/// Makes any positioned sound follow a body, e.g. one made with the sound builder:
/// `let s = ctx.audio.sound("hum").volume(0.3).looped().at(pos).play(); ctx.attach(body, s);`
pub fn attach(&mut self, body: BodyId, sound: Sound) {
let position = self.physics.position(body);
sound.set_position(position);
self.attached.push(Attached { body, sound, last: position });
}
/// Stops every sound attached to a body.
pub fn stop_sounds_on(&mut self, body: BodyId) {
self.attached.retain(|a| {
if a.body == body {
a.sound.stop();
false
} else {
true
}
});
}
/// Drives a vehicle with the keyboard: Up or W is the gas pedal, Down or S brakes and,
/// once the vehicle stands still, reverses, Left / Right or A / D steer, Space is the
/// handbrake. Call it every frame. Does nothing for bodies without a vehicle. While a
/// menu is open all pedals are released.
///
/// ```no_run
/// # use audio_code::prelude::*;
/// # fn f(ctx: &mut Context) {
/// let car = ctx.physics.add(Body::car(Vec3::ZERO));
/// ctx.follow(car);
/// // in update():
/// ctx.drive(car);
/// # }
/// ```
pub fn drive(&mut self, vehicle: BodyId) {
let input = &self.input;
let throttle = (input.held(Key::Up) || input.held(Key::W)) as u8 as f32;
let brake = (input.held(Key::Down) || input.held(Key::S)) as u8 as f32;
let right = (input.held(Key::Right) || input.held(Key::D)) as i32;
let left = (input.held(Key::Left) || input.held(Key::A)) as i32;
let handbrake = input.held(Key::Space);
if let Some(v) = self.physics.vehicle_mut(vehicle) {
v.throttle = throttle;
v.brake = brake;
v.steer = (right - left) as f32;
v.handbrake = handbrake;
}
}
/// Honks: plays the vehicle's horn sound at the vehicle. Returns a silent handle if it
/// has none.
pub fn horn(&mut self, vehicle: BodyId) -> Sound {
match self.physics.vehicle(vehicle).and_then(|v| v.horn_sound.clone()) {
Some(name) => self.play_on(vehicle, &name),
None => Sound::none(),
}
}
/// Starts the engine of a vehicle and plays its start sound. Returns `false` if the
/// body is no vehicle, the engine already runs or the tank is empty.
pub fn start_engine(&mut self, vehicle: BodyId) -> bool {
let Some(v) = self.physics.vehicle_mut(vehicle) else {
return false;
};
if v.is_engine_on() || !v.start_engine() {
return false;
}
if let Some(name) = v.start_sound.clone() {
self.play_on(vehicle, &name);
}
true
}
/// Stops the engine of a vehicle. Its engine sound fades out and it rolls out.
pub fn stop_engine(&mut self, vehicle: BodyId) {
if let Some(v) = self.physics.vehicle_mut(vehicle) {
v.stop_engine();
}
}
/// Keeps the engine loops of vehicles playing, and plays shift and crash sounds.
/// Called by the engine once per frame.
pub(crate) fn sync_vehicles(&mut self) {
let (physics, audio) = (&self.physics, &mut self.audio);
// Engine loops: start while the engine runs, follow rpm and throttle, stop otherwise.
self.engine_sounds.retain(|(id, sound)| {
let running = physics.vehicle(*id).is_some_and(|v| v.is_engine_on() && v.engine_sound.is_some());
if !running || !sound.is_playing() {
sound.fade_out(0.3);
}
running && sound.is_playing()
});
for (id, body) in physics.bodies() {
let Some(v) = &body.vehicle else {
continue;
};
let Some(name) = &v.engine_sound else {
continue;
};
if !v.is_engine_on() {
continue;
}
let (pitch, volume) = (v.engine_pitch(), 0.6 + 0.4 * v.throttle.clamp(0.0, 1.0));
match self.engine_sounds.iter().find(|(e, _)| *e == id) {
Some((_, sound)) => {
sound.set_position(body.position);
sound.set_pitch(pitch);
sound.set_volume(volume);
}
None => {
let sound = audio.sound(name).looped().at(body.position).pitch(pitch).volume(volume).play();
self.engine_sounds.push((id, sound));
}
}
}
for event in physics.events() {
let (vehicle, name, volume) = match *event {
PhysicsEvent::Crashed { vehicle, speed, .. } => {
(vehicle, physics.vehicle(vehicle).and_then(|v| v.crash_sound.as_deref()), (speed / 15.0).min(1.0))
}
PhysicsEvent::GearChanged { vehicle, gear } if gear != 0 => {
(vehicle, physics.vehicle(vehicle).and_then(|v| v.shift_sound.as_deref()), 1.0)
}
_ => continue,
};
if let Some(name) = name {
audio.sound(name).at(physics.position(vehicle)).volume(volume).play();
}
}
}
/// Moves the listener and attached sounds to their bodies. Called by the engine every frame.
pub(crate) fn sync_world(&mut self) {
if let Some(id) = self.follow {
match self.physics.get(id) {
Some(body) => {
let (position, facing, pitch) = (body.position, body.facing, body.pitch);
if position != self.audio.listener_position()
|| facing != self.audio.listener_yaw()
|| pitch != self.audio.listener_pitch()
{
self.audio.set_listener_3d(position, facing, pitch);
}
}
None => self.follow = None,
}
}
let physics = &self.physics;
self.attached.retain_mut(|a| {
if !a.sound.is_playing() {
return false;
}
match physics.get(a.body) {
Some(body) => {
if body.position != a.last {
a.sound.set_position(body.position);
a.last = body.position;
}
true
}
None => {
a.sound.stop();
false
}
}
});
}
}
#[cfg(test)]
mod tests {
use crate::prelude::*;
#[test]
fn follow_and_attach() {
let mut runner = Engine::new("t").headless().build_fn(|_| {});
let ctx = &mut runner.ctx;
let player = ctx.physics.add(Body::kinematic(vec3(1.0, 2.0, 0.0)).with_facing(90.0));
ctx.follow(player);
assert_eq!(ctx.audio.listener_position(), vec3(1.0, 2.0, 0.0));
assert_eq!(ctx.audio.listener_yaw(), 90.0);
ctx.physics.move_forward(player, 3.0);
ctx.sync_world();
assert!((ctx.audio.listener_position().x - 4.0).abs() < 1e-4);
assert!(ctx.once("a"));
assert!(!ctx.once("a"));
}
}