gizmo_scripting/
api_audio.rs1use crate::commands::{CommandQueue, ScriptCommand};
4use gizmo_math::Vec3;
5use mlua::prelude::*;
6use std::sync::Arc;
7
8pub fn register_audio_api(lua: &Lua, command_queue: Arc<CommandQueue>) -> Result<(), LuaError> {
10 crate::api_table::register_protected(lua, "audio", |audio_table| {
11
12 {
14 let cq = command_queue.clone();
15 audio_table.set(
16 "play",
17 lua.create_function(move |_, sound_name: String| {
18 cq.push(ScriptCommand::PlaySound(sound_name));
19 Ok(())
20 })?,
21 )?;
22 }
23
24 {
26 let cq = command_queue.clone();
27 audio_table.set(
28 "play_3d",
29 lua.create_function(move |_, (sound_name, x, y, z): (String, f32, f32, f32)| {
30 cq.push(ScriptCommand::PlaySound3D(sound_name, Vec3::new(x, y, z)));
31 Ok(())
32 })?,
33 )?;
34 }
35
36 {
38 let cq = command_queue.clone();
39 audio_table.set(
40 "stop",
41 lua.create_function(move |_, sound_name: String| {
42 cq.push(ScriptCommand::StopSound(sound_name));
43 Ok(())
44 })?,
45 )?;
46 }
47
48 Ok(())
49 })
50}
51
52#[cfg(test)]
53mod tests {
54 use super::*;
55 use mlua::Lua;
56
57 #[test]
60 fn audio_calls_push_expected_commands() {
61 let lua = Lua::new();
62 let cq = Arc::new(CommandQueue::new());
63 register_audio_api(&lua, cq.clone()).unwrap();
64
65 lua.load(
66 r#"
67 audio.play("jump")
68 audio.play_3d("explosion", 1.0, 2.0, 3.0)
69 audio.stop("music")
70 "#,
71 )
72 .exec()
73 .unwrap();
74
75 let cmds = cq.drain();
76 assert_eq!(cmds.len(), 3);
77 match &cmds[0] {
78 ScriptCommand::PlaySound(name) => assert_eq!(name, "jump"),
79 other => panic!("beklenen PlaySound, gelen {other:?}"),
80 }
81 match &cmds[1] {
82 ScriptCommand::PlaySound3D(name, pos) => {
83 assert_eq!(name, "explosion");
84 assert_eq!(*pos, Vec3::new(1.0, 2.0, 3.0));
85 }
86 other => panic!("beklenen PlaySound3D, gelen {other:?}"),
87 }
88 match &cmds[2] {
89 ScriptCommand::StopSound(name) => assert_eq!(name, "music"),
90 other => panic!("beklenen StopSound, gelen {other:?}"),
91 }
92 }
93}