arcane-core 0.26.1

Core library for Arcane - agent-native 2D game engine (TypeScript runtime, renderer, platform layer)
Documentation
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
use std::collections::HashMap;
use std::io::Cursor;
use std::sync::{mpsc, Arc};

use rodio::Source;

/// Audio bus for grouping sounds. Each bus has independent volume control.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AudioBus {
    Sfx = 0,
    Music = 1,
    Ambient = 2,
    Voice = 3,
}

impl AudioBus {
    pub fn from_u32(value: u32) -> Option<Self> {
        match value {
            0 => Some(Self::Sfx),
            1 => Some(Self::Music),
            2 => Some(Self::Ambient),
            3 => Some(Self::Voice),
            _ => None,
        }
    }
}

/// Commands sent from the main thread to the audio thread.
pub enum AudioCommand {
    LoadSound { id: u32, data: Vec<u8> },
    StopAll,
    SetMasterVolume { volume: f32 },

    // Phase 20: New instance-based commands
    PlaySoundEx {
        sound_id: u32,
        instance_id: u64,
        volume: f32,
        looping: bool,
        bus: AudioBus,
        pan: f32,
        pitch: f32,
        low_pass_freq: u32,
        reverb_mix: f32,
        reverb_delay_ms: u32,
    },
    PlaySoundSpatial {
        sound_id: u32,
        instance_id: u64,
        volume: f32,
        looping: bool,
        bus: AudioBus,
        pitch: f32,
        source_x: f32,
        source_y: f32,
        listener_x: f32,
        listener_y: f32,
    },
    StopInstance { instance_id: u64 },
    SetInstanceVolume { instance_id: u64, volume: f32 },
    SetInstancePitch { instance_id: u64, pitch: f32 },
    UpdateSpatialPositions {
        updates: Vec<(u64, f32, f32)>, // (instance_id, source_x, source_y)
        listener_x: f32,
        listener_y: f32,
    },
    SetBusVolume { bus: AudioBus, volume: f32 },

    Shutdown,
}

pub type AudioSender = mpsc::Sender<AudioCommand>;
pub type AudioReceiver = mpsc::Receiver<AudioCommand>;

/// Create a channel for sending audio commands to the audio thread.
pub fn audio_channel() -> (AudioSender, AudioReceiver) {
    mpsc::channel()
}

/// Instance metadata for tracking per-instance state.
struct InstanceMetadata {
    bus: AudioBus,
    base_volume: f32,
    is_spatial: bool,
}

/// Scale factor to convert game pixel coordinates to audio-space coordinates.
/// rodio's SpatialSink uses inverse-distance attenuation, so game distances
/// of 100s of pixels would produce near-zero volume without scaling.
/// With SPATIAL_SCALE = 0.01, 100 game pixels = 1.0 audio unit.
const SPATIAL_SCALE: f32 = 0.01;

/// Spawn the audio thread. It owns the rodio OutputStream and processes commands.
pub fn start_audio_thread(rx: AudioReceiver) -> std::thread::JoinHandle<()> {
    std::thread::spawn(move || {
        // Initialize rodio output stream
        let stream_handle = match rodio::OutputStream::try_default() {
            Ok((stream, handle)) => {
                // Leak the stream so it lives as long as the thread
                std::mem::forget(stream);
                handle
            }
            Err(e) => {
                eprintln!("[audio] Failed to initialize audio output: {e}");
                // Drain commands without playing
                while let Ok(cmd) = rx.recv() {
                    if matches!(cmd, AudioCommand::Shutdown) {
                        break;
                    }
                }
                return;
            }
        };

        // Sound data storage (Arc for sharing across concurrent plays)
        let mut sounds: HashMap<u32, Arc<Vec<u8>>> = HashMap::new();

        // Instance-based sinks (Phase 20+ architecture)
        let mut sinks: HashMap<u64, rodio::Sink> = HashMap::new();
        let mut spatial_sinks: HashMap<u64, rodio::SpatialSink> = HashMap::new();
        let mut instance_metadata: HashMap<u64, InstanceMetadata> = HashMap::new();

        // Volume state
        let mut master_volume: f32 = 1.0;
        let mut bus_volumes: [f32; 4] = [1.0, 1.0, 1.0, 1.0]; // Sfx, Music, Ambient, Voice

        // Cleanup counter for periodic sink cleanup
        let mut cleanup_counter = 0;

        loop {
            let cmd = match rx.recv() {
                Ok(cmd) => cmd,
                Err(_) => break, // Channel closed
            };

            match cmd {
                AudioCommand::LoadSound { id, data } => {
                    sounds.insert(id, Arc::new(data));
                }

                AudioCommand::StopAll => {
                    for (_, sink) in sinks.drain() {
                        sink.stop();
                    }
                    for (_, sink) in spatial_sinks.drain() {
                        sink.stop();
                    }
                    instance_metadata.clear();
                }

                AudioCommand::SetMasterVolume { volume } => {
                    master_volume = volume;
                    update_all_volumes(&sinks, &spatial_sinks, &instance_metadata, &bus_volumes, master_volume);
                }

                // Phase 20: New instance-based commands
                AudioCommand::PlaySoundEx {
                    sound_id,
                    instance_id,
                    volume,
                    looping,
                    bus,
                    pan,
                    pitch,
                    low_pass_freq,
                    reverb_mix: _,
                    reverb_delay_ms: _,
                } => {
                    if let Some(data) = sounds.get(&sound_id) {
                        match rodio::Sink::try_new(&stream_handle) {
                            Ok(sink) => {
                                let cursor = Cursor::new((**data).clone());
                                match rodio::Decoder::new(cursor) {
                                    Ok(source) => {
                                        // Convert to f32 samples for effects
                                        let source = source.convert_samples::<f32>();

                                        // Apply low-pass filter if requested
                                        let source = if low_pass_freq > 0 {
                                            rodio::source::Source::low_pass(source, low_pass_freq)
                                        } else {
                                            rodio::source::Source::low_pass(source, 20000) // No filtering
                                        };

                                        // Note: rodio's reverb requires Clone, which BltFilter doesn't implement.
                                        // For simplicity, skip reverb implementation for now (or use buffered source).
                                        // In production, we'd buffer the source first.

                                        // Apply looping
                                        if looping {
                                            sink.append(rodio::source::Source::repeat_infinite(source));
                                        } else {
                                            sink.append(source);
                                        }

                                        // Apply pan by adjusting left/right channel volumes
                                        // Pan range: -1.0 (left) to +1.0 (right)
                                        // Note: rodio doesn't expose direct channel volume control,
                                        // so pan is computed but not applied. Store for future reference.
                                        let (_left, _right) = pan_to_volumes(pan);

                                        sink.set_volume(volume * bus_volumes[bus as usize] * master_volume);

                                        // Apply pitch
                                        sink.set_speed(pitch);

                                        sink.play();

                                        // Store metadata
                                        instance_metadata.insert(instance_id, InstanceMetadata {
                                            bus,
                                            base_volume: volume,
                                            is_spatial: false,
                                        });

                                        sinks.insert(instance_id, sink);
                                    }
                                    Err(e) => {
                                        eprintln!("[audio] Failed to decode sound {sound_id} for instance {instance_id}: {e}");
                                    }
                                }
                            }
                            Err(e) => {
                                eprintln!("[audio] Failed to create sink for sound {sound_id}: {e}");
                            }
                        }
                    }
                }

                AudioCommand::PlaySoundSpatial {
                    sound_id,
                    instance_id,
                    volume,
                    looping,
                    bus,
                    pitch,
                    source_x,
                    source_y,
                    listener_x,
                    listener_y,
                } => {
                    if let Some(data) = sounds.get(&sound_id) {
                        // Scale game pixel coords to audio-space coords
                        let sx = source_x * SPATIAL_SCALE;
                        let sy = source_y * SPATIAL_SCALE;
                        let lx = listener_x * SPATIAL_SCALE;
                        let ly = listener_y * SPATIAL_SCALE;

                        // SpatialSink constructor: try_new(handle, emitter_pos, left_ear, right_ear)
                        match rodio::SpatialSink::try_new(
                            &stream_handle,
                            [sx, sy, 0.0],
                            [lx - 0.1, ly, 0.0], // Left ear
                            [lx + 0.1, ly, 0.0], // Right ear
                        ) {
                            Ok(sink) => {
                                let cursor = Cursor::new((**data).clone());
                                match rodio::Decoder::new(cursor) {
                                    Ok(source) => {
                                        if looping {
                                            sink.append(rodio::source::Source::repeat_infinite(source));
                                        } else {
                                            sink.append(source);
                                        }

                                        sink.set_volume(volume * bus_volumes[bus as usize] * master_volume);
                                        sink.set_speed(pitch);
                                        sink.play();

                                        instance_metadata.insert(instance_id, InstanceMetadata {
                                            bus,
                                            base_volume: volume,
                                            is_spatial: true,
                                        });

                                        spatial_sinks.insert(instance_id, sink);
                                    }
                                    Err(e) => {
                                        eprintln!("[audio] Failed to decode sound {sound_id} for spatial instance {instance_id}: {e}");
                                    }
                                }
                            }
                            Err(e) => {
                                eprintln!("[audio] Failed to create spatial sink for sound {sound_id}: {e}");
                            }
                        }
                    }
                }

                AudioCommand::StopInstance { instance_id } => {
                    if let Some(sink) = sinks.remove(&instance_id) {
                        sink.stop();
                        instance_metadata.remove(&instance_id);
                    } else if let Some(sink) = spatial_sinks.remove(&instance_id) {
                        sink.stop();
                        instance_metadata.remove(&instance_id);
                    }
                }

                AudioCommand::SetInstanceVolume { instance_id, volume } => {
                    if let Some(metadata) = instance_metadata.get_mut(&instance_id) {
                        metadata.base_volume = volume;
                        let final_volume = volume * bus_volumes[metadata.bus as usize] * master_volume;

                        if metadata.is_spatial {
                            if let Some(sink) = spatial_sinks.get(&instance_id) {
                                sink.set_volume(final_volume);
                            }
                        } else {
                            if let Some(sink) = sinks.get(&instance_id) {
                                sink.set_volume(final_volume);
                            }
                        }
                    }
                }

                AudioCommand::SetInstancePitch { instance_id, pitch } => {
                    if let Some(metadata) = instance_metadata.get(&instance_id) {
                        if metadata.is_spatial {
                            if let Some(sink) = spatial_sinks.get(&instance_id) {
                                sink.set_speed(pitch);
                            }
                        } else {
                            if let Some(sink) = sinks.get(&instance_id) {
                                sink.set_speed(pitch);
                            }
                        }
                    }
                }

                AudioCommand::UpdateSpatialPositions { updates, listener_x, listener_y } => {
                    let lx = listener_x * SPATIAL_SCALE;
                    let ly = listener_y * SPATIAL_SCALE;
                    for (instance_id, source_x, source_y) in updates {
                        if let Some(sink) = spatial_sinks.get(&instance_id) {
                            sink.set_emitter_position([source_x * SPATIAL_SCALE, source_y * SPATIAL_SCALE, 0.0]);
                            sink.set_left_ear_position([lx - 0.1, ly, 0.0]);
                            sink.set_right_ear_position([lx + 0.1, ly, 0.0]);
                        }
                    }
                }

                AudioCommand::SetBusVolume { bus, volume } => {
                    bus_volumes[bus as usize] = volume;
                    update_all_volumes(&sinks, &spatial_sinks, &instance_metadata, &bus_volumes, master_volume);
                }

                AudioCommand::Shutdown => break,
            }

            // Periodic cleanup of finished sinks (every 100 commands)
            cleanup_counter += 1;
            if cleanup_counter >= 100 {
                cleanup_counter = 0;
                sinks.retain(|id, sink| {
                    let keep = !sink.empty();
                    if !keep {
                        instance_metadata.remove(id);
                    }
                    keep
                });
                spatial_sinks.retain(|id, sink| {
                    let keep = !sink.empty();
                    if !keep {
                        instance_metadata.remove(id);
                    }
                    keep
                });
            }
        }
    })
}

/// Convert pan value (-1.0 to +1.0) to left/right channel volumes.
/// Pan -1.0 = full left (1.0, 0.0), 0.0 = center (0.707, 0.707), +1.0 = full right (0.0, 1.0)
fn pan_to_volumes(pan: f32) -> (f32, f32) {
    let pan_clamped = pan.clamp(-1.0, 1.0);
    // Equal power panning: use sqrt for smooth volume curve
    let left = ((1.0 - pan_clamped) / 2.0).sqrt();
    let right = ((1.0 + pan_clamped) / 2.0).sqrt();
    (left, right)
}

/// Update volumes for all active instances based on bus volumes and master volume.
fn update_all_volumes(
    sinks: &HashMap<u64, rodio::Sink>,
    spatial_sinks: &HashMap<u64, rodio::SpatialSink>,
    metadata: &HashMap<u64, InstanceMetadata>,
    bus_volumes: &[f32; 4],
    master_volume: f32,
) {
    for (id, sink) in sinks {
        if let Some(meta) = metadata.get(id) {
            let final_volume = meta.base_volume * bus_volumes[meta.bus as usize] * master_volume;
            sink.set_volume(final_volume);
        }
    }

    for (id, sink) in spatial_sinks {
        if let Some(meta) = metadata.get(id) {
            let final_volume = meta.base_volume * bus_volumes[meta.bus as usize] * master_volume;
            sink.set_volume(final_volume);
        }
    }
}