devalang_wasm/engine/special_vars/
mod.rs1use crate::language::syntax::ast::Value;
4use std::collections::HashMap;
5
6pub const SPECIAL_VAR_PREFIX: char = '$';
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum SpecialVarCategory {
12 Time, Random, Music, Position, Midi, System, }
19
20#[derive(Debug, Clone)]
22pub struct SpecialVarContext {
23 pub current_time: f32, pub current_beat: f32, pub current_bar: f32, pub bpm: f32, pub duration: f32, pub sample_rate: u32, pub channels: usize, pub position: f32, pub total_duration: f32, }
33
34impl Default for SpecialVarContext {
35 fn default() -> Self {
36 Self {
37 current_time: 0.0,
38 current_beat: 0.0,
39 current_bar: 0.0,
40 bpm: 120.0,
41 duration: 0.5,
42 sample_rate: 44100,
43 channels: 2,
44 position: 0.0,
45 total_duration: 0.0,
46 }
47 }
48}
49
50impl SpecialVarContext {
51 pub fn new(bpm: f32, sample_rate: u32) -> Self {
52 Self {
53 bpm,
54 duration: 60.0 / bpm,
55 sample_rate,
56 ..Default::default()
57 }
58 }
59
60 pub fn update_time(&mut self, time: f32) {
62 self.current_time = time;
63 self.current_beat = time / self.duration;
64 self.current_bar = self.current_beat / 4.0;
65
66 if self.total_duration > 0.0 {
67 self.position = (time / self.total_duration).clamp(0.0, 1.0);
68 }
69 }
70
71 pub fn update_bpm(&mut self, bpm: f32) {
73 self.bpm = bpm;
74 self.duration = 60.0 / bpm;
75 }
76}
77
78pub fn is_special_var(name: &str) -> bool {
80 name.starts_with(SPECIAL_VAR_PREFIX)
81}
82
83pub fn resolve_special_var(name: &str, context: &SpecialVarContext) -> Option<Value> {
85 if !is_special_var(name) {
86 return None;
87 }
88
89 let eps = 1e-6_f32;
93
94 match name {
95 "$time" => Some(Value::Number(context.current_time)),
97 "$beat" => Some(Value::Number(context.current_beat)),
98 "$bar" => Some(Value::Number((context.current_bar + eps).floor() + 1.0)),
101 "$currentTime" => Some(Value::Number(context.current_time)),
102 "$currentBeat" => Some(Value::Number(context.current_beat)),
103 "$currentBar" => Some(Value::Number((context.current_bar + eps).floor() + 1.0)),
104
105 "$bpm" => Some(Value::Number(context.bpm)),
107 "$tempo" => Some(Value::Number(context.bpm)),
108 "$duration" => Some(Value::Number(context.duration)),
109
110 "$position" => Some(Value::Number(context.position)),
112 "$progress" => Some(Value::Number(context.position)),
113
114 "$sampleRate" => Some(Value::Number(context.sample_rate as f32)),
116 "$channels" => Some(Value::Number(context.channels as f32)),
117
118 #[cfg(any(feature = "cli", feature = "wasm"))]
120 "$random" | "$random.float" => Some(Value::Number(rand::random::<f32>())),
121 #[cfg(any(feature = "cli", feature = "wasm"))]
122 "$random.noise" => Some(Value::Number(rand::random::<f32>() * 2.0 - 1.0)), #[cfg(any(feature = "cli", feature = "wasm"))]
124 "$random.int" => Some(Value::Number((rand::random::<u32>() % 100) as f32)),
125 #[cfg(any(feature = "cli", feature = "wasm"))]
126 "$random.bool" => Some(Value::Boolean(rand::random::<bool>())),
127
128 #[cfg(any(feature = "cli", feature = "wasm"))]
130 _ if name.starts_with("$random.range(") => {
131 parse_random_range(name)
133 }
134
135 _ => None,
136 }
137}
138
139#[cfg(any(feature = "cli", feature = "wasm"))]
141fn parse_random_range(name: &str) -> Option<Value> {
142 let start = name.find('(')?;
144 let end = name.rfind(')')?;
145 let content = &name[start + 1..end];
146
147 let parts: Vec<&str> = content.split(',').map(|s| s.trim()).collect();
149 if parts.len() != 2 {
150 return None;
151 }
152
153 let min: f32 = parts[0].parse().ok()?;
155 let max: f32 = parts[1].parse().ok()?;
156
157 let value = min + rand::random::<f32>() * (max - min);
159 Some(Value::Number(value))
160}
161
162pub fn get_all_special_vars(context: &SpecialVarContext) -> HashMap<String, Value> {
164 let mut vars = HashMap::new();
165
166 let eps = 1e-6_f32;
168
169 vars.insert("$time".to_string(), Value::Number(context.current_time));
171 vars.insert("$beat".to_string(), Value::Number(context.current_beat));
172 vars.insert(
174 "$bar".to_string(),
175 Value::Number((context.current_bar + eps).floor() + 1.0),
176 );
177 vars.insert(
178 "$currentTime".to_string(),
179 Value::Number(context.current_time),
180 );
181 vars.insert(
182 "$currentBeat".to_string(),
183 Value::Number(context.current_beat),
184 );
185 vars.insert(
186 "$currentBar".to_string(),
187 Value::Number((context.current_bar + eps).floor() + 1.0),
188 );
189
190 vars.insert("$bpm".to_string(), Value::Number(context.bpm));
192 vars.insert("$tempo".to_string(), Value::Number(context.bpm));
193 vars.insert("$duration".to_string(), Value::Number(context.duration));
194
195 vars.insert("$position".to_string(), Value::Number(context.position));
197 vars.insert("$progress".to_string(), Value::Number(context.position));
198
199 vars.insert(
201 "$sampleRate".to_string(),
202 Value::Number(context.sample_rate as f32),
203 );
204 vars.insert(
205 "$channels".to_string(),
206 Value::Number(context.channels as f32),
207 );
208
209 vars
210}
211
212pub fn list_special_vars() -> HashMap<&'static str, Vec<(&'static str, &'static str)>> {
214 let mut categories = HashMap::new();
215
216 categories.insert(
217 "Time",
218 vec![
219 ("$time", "Current time in seconds"),
220 ("$beat", "Current beat position"),
221 ("$bar", "Current bar position"),
222 ("$currentTime", "Alias for $time"),
223 ("$currentBeat", "Alias for $beat"),
224 ("$currentBar", "Alias for $bar"),
225 ],
226 );
227
228 categories.insert(
229 "Music",
230 vec![
231 ("$bpm", "Current BPM"),
232 ("$tempo", "Alias for $bpm"),
233 ("$duration", "Beat duration in seconds"),
234 ],
235 );
236
237 categories.insert(
238 "Position",
239 vec![
240 ("$position", "Normalized position (0.0-1.0)"),
241 ("$progress", "Alias for $position"),
242 ],
243 );
244
245 categories.insert(
246 "Random",
247 vec![
248 ("$random", "Random float 0.0-1.0"),
249 ("$random.float", "Random float 0.0-1.0"),
250 ("$random.noise", "Random float -1.0 to 1.0"),
251 ("$random.int", "Random integer 0-99"),
252 ("$random.bool", "Random boolean"),
253 ("$random.range(min, max)", "Random float in range"),
254 ],
255 );
256
257 categories.insert(
258 "System",
259 vec![
260 ("$sampleRate", "Sample rate in Hz"),
261 ("$channels", "Number of audio channels"),
262 ],
263 );
264
265 categories
266}
267
268#[cfg(test)]
269#[path = "test_special_vars.rs"]
270mod tests;