1//! Pure-Rust per-particle expression parser & evaluator for `pCustom` and `pCustomForce`.
2//!
3//! Supports Fusion particle expressions (`px/py/pz`, `vx/vy/vz`, `rx/ry/rz`, `sx/sy/sz`,
4//! `r/g/b/a`, `size`, `age`, `lifespan`/`life`, `id`, `mass`, `user`, `time`, `n1..n8`,
5//! `p1x/p1y/p1z..p4x/p4y/p4z`, `s1..s4`, `i1..i8`, `getr1/g1/b1/a1`, degree trig + radian
6//! `sinr/cosr/...`, `abs/sqrt/pow/exp/log/floor/ceil/round/clamp/min/max/if/iif/mix/step/smoothstep/rand/rands/noise`).
7
8
9#[derive(Clone, Debug, PartialEq)]
10enum Tok {
11 Num(f64),
12 Ident(String),
13 Plus,
14 Minus,
15 Star,
16 Slash,
17 Percent,
18 Caret,
19 LParen,
20 RParen,
21 Comma,
22 Lt,
23 Le,
24 Gt,
25 Ge,
26 Eq,
27 Ne,
28 And,
29 Or,
30 Bang,
31}
32
33fn tokenize(src: &str) -> Result<Vec<Tok>, ()> {
34 let b = src.as_bytes();
35 let mut out = Vec::new();
36 let mut i = 0;
37 while i < b.len() {
38 let c = b[i];
39 if c.is_ascii_whitespace() {
40 i += 1;
41 continue;
42 }
43 if c == b'/' && b.get(i + 1) == Some(&b'/') {
44 i += 2;
45 while i < b.len() && b[i] != b'\n' {
46 i += 1;
47 }
48 continue;
49 }
50 if c == b'/' && b.get(i + 1) == Some(&b'*') {
51 i += 2;
52 while i + 1 < b.len() && !(b[i] == b'*' && b[i + 1] == b'/') {
53 i += 1;
54 }
55 i = (i + 2).min(b.len());
56 continue;
57 }
58 if c.is_ascii_digit() || (c == b'.' && b.get(i + 1).is_some_and(u8::is_ascii_digit)) {
59 let start = i;
60 while i < b.len() && b[i].is_ascii_digit() {
61 i += 1;
62 }
63 if b.get(i) == Some(&b'.') {
64 i += 1;
65 while i < b.len() && b[i].is_ascii_digit() {
66 i += 1;
67 }
68 }
69 if matches!(b.get(i), Some(b'e' | b'E')) {
70 let exp_pos = i;
71 i += 1;
72 if matches!(b.get(i), Some(b'+' | b'-')) {
73 i += 1;
74 }
75 let dig_start = i;
76 while i < b.len() && b[i].is_ascii_digit() {
77 i += 1;
78 }
79 if i == dig_start {
80 i = exp_pos;
81 }
82 }
83 let v: f64 = src[start..i].parse().map_err(|_| ())?;
84 out.push(Tok::Num(v));
85 continue;
86 }
87 if c.is_ascii_alphabetic() || c == b'_' {
88 let start = i;
89 while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') {
90 i += 1;
91 }
92 out.push(Tok::Ident(src[start..i].to_owned()));
93 continue;
94 }
95 let next = b.get(i + 1).copied();
96 match (c, next) {
97 (b'<', Some(b'=')) => { out.push(Tok::Le); i += 2; }
98 (b'>', Some(b'=')) => { out.push(Tok::Ge); i += 2; }
99 (b'=', Some(b'=')) => { out.push(Tok::Eq); i += 2; }
100 (b'!', Some(b'=')) | (b'~', Some(b'=')) | (b'<', Some(b'>')) => { out.push(Tok::Ne); i += 2; }
101 (b'&', Some(b'&')) => { out.push(Tok::And); i += 2; }
102 (b'|', Some(b'|')) => { out.push(Tok::Or); i += 2; }
103 (b'+', _) => { out.push(Tok::Plus); i += 1; }
104 (b'-', _) => { out.push(Tok::Minus); i += 1; }
105 (b'*', _) => { out.push(Tok::Star); i += 1; }
106 (b'/', _) => { out.push(Tok::Slash); i += 1; }
107 (b'%', _) => { out.push(Tok::Percent); i += 1; }
108 (b'^', _) => { out.push(Tok::Caret); i += 1; }
109 (b'(', _) => { out.push(Tok::LParen); i += 1; }
110 (b')', _) => { out.push(Tok::RParen); i += 1; }
111 (b',', _) => { out.push(Tok::Comma); i += 1; }
112 (b'<', _) => { out.push(Tok::Lt); i += 1; }
113 (b'>', _) => { out.push(Tok::Gt); i += 1; }
114 (b'=', _) => { out.push(Tok::Eq); i += 1; }
115 (b'&', _) => { out.push(Tok::And); i += 1; }
116 (b'|', _) => { out.push(Tok::Or); i += 1; }
117 (b'!', _) => { out.push(Tok::Bang); i += 1; }
118 _ => return Err(()),
119 }
120 }
121 Ok(out)
122}
123
124#[derive(Clone, Copy, Debug)]
125pub(super) enum Var {
126 Px, Py, Pz,
127 Vx, Vy, Vz,
128 Rx, Ry, Rz,
129 Sx, Sy, Sz,
130 R, G, B, A,
131 Size, Age, Lifespan, Id, Mass, User, Time, Pi, E,
132 Num(u8),
133 Pt(u8, u8),
134 Setup(u8),
135 Inter(u8),
136}
137
138#[derive(Clone, Copy, Debug)]
139pub(super) enum BinOp {
140 Add, Sub, Mul, Div, Mod, Pow,
141 Lt, Le, Gt, Ge, Eq, Ne,
142 And, Or,
143}
144
145#[derive(Clone, Copy, Debug)]
146pub(super) enum Func {
147 Sin, Cos, Tan, Asin, Acos, Atan, Atan2,
148 Sinr, Cosr, Tanr, Asinr, Acosr, Atanr, Atan2r,
149 Sinh, Cosh, Tanh, Deg, Rad,
150 Abs, Sqrt, Pow, Exp, Log, Log10, Log2,
151 Floor, Ceil, Round, Trunc, Fract, Sign,
152 Min, Max, Clamp, Mod, If, Dist, Hypot, Mix, Step, Smoothstep,
153 Rand, Rands, Noise1, Noise2, Noise3,
154 SampleImg(u8, u8), // (channel 0..4, edge_mode 0..2)
155}
156
157#[derive(Clone, Debug)]
158pub(super) enum Ast {
159 Const(f64),
160 Var(Var),
161 Neg(Box<Ast>),
162 Not(Box<Ast>),
163 Bin(BinOp, Box<Ast>, Box<Ast>),
164 Call(Func, Vec<Ast>),
165}
166
167struct Parser<'a> {
168 toks: &'a [Tok],
169 pos: usize,
170 depth: usize,
171}
172
173impl<'a> Parser<'a> {
174 fn peek(&self) -> Option<&Tok> {
175 self.toks.get(self.pos)
176 }
177
178 fn eat(&mut self, t: &Tok) -> bool {
179 if self.peek() == Some(t) {
180 self.pos += 1;
181 true
182 } else {
183 false
184 }
185 }
186
187 fn parse(&mut self) -> Result<Ast, ()> {
188 if self.toks.is_empty() {
189 return Ok(Ast::Const(0.0));
190 }
191 let e = self.parse_or()?;
192 if self.pos != self.toks.len() {
193 return Err(());
194 }
195 Ok(e)
196 }
197
198 fn with_depth(&mut self, f: impl FnOnce(&mut Self) -> Result<Ast, ()>) -> Result<Ast, ()> {
199 if self.depth >= 64 {
200 return Err(());
201 }
202 self.depth += 1;
203 let r = f(self);
204 self.depth -= 1;
205 r
206 }
207
208 fn parse_or(&mut self) -> Result<Ast, ()> {
209 let mut lhs = self.parse_and()?;
210 while self.eat(&Tok::Or) {
211 let rhs = self.parse_and()?;
212 lhs = Ast::Bin(BinOp::Or, Box::new(lhs), Box::new(rhs));
213 }
214 Ok(lhs)
215 }
216
217 fn parse_and(&mut self) -> Result<Ast, ()> {
218 let mut lhs = self.parse_cmp()?;
219 while self.eat(&Tok::And) {
220 let rhs = self.parse_cmp()?;
221 lhs = Ast::Bin(BinOp::And, Box::new(lhs), Box::new(rhs));
222 }
223 Ok(lhs)
224 }
225
226 fn parse_cmp(&mut self) -> Result<Ast, ()> {
227 let mut lhs = self.parse_add()?;
228 loop {
229 let op = match self.peek() {
230 Some(Tok::Lt) => BinOp::Lt,
231 Some(Tok::Le) => BinOp::Le,
232 Some(Tok::Gt) => BinOp::Gt,
233 Some(Tok::Ge) => BinOp::Ge,
234 Some(Tok::Eq) => BinOp::Eq,
235 Some(Tok::Ne) => BinOp::Ne,
236 _ => break,
237 };
238 self.pos += 1;
239 let rhs = self.parse_add()?;
240 lhs = Ast::Bin(op, Box::new(lhs), Box::new(rhs));
241 }
242 Ok(lhs)
243 }
244
245 fn parse_add(&mut self) -> Result<Ast, ()> {
246 let mut lhs = self.parse_mul()?;
247 loop {
248 if self.eat(&Tok::Plus) {
249 let rhs = self.parse_mul()?;
250 lhs = Ast::Bin(BinOp::Add, Box::new(lhs), Box::new(rhs));
251 } else if self.eat(&Tok::Minus) {
252 let rhs = self.parse_mul()?;
253 lhs = Ast::Bin(BinOp::Sub, Box::new(lhs), Box::new(rhs));
254 } else {
255 break;
256 }
257 }
258 Ok(lhs)
259 }
260
261 fn parse_mul(&mut self) -> Result<Ast, ()> {
262 let mut lhs = self.parse_pow()?;
263 loop {
264 if self.eat(&Tok::Star) {
265 let rhs = self.parse_pow()?;
266 lhs = Ast::Bin(BinOp::Mul, Box::new(lhs), Box::new(rhs));
267 } else if self.eat(&Tok::Slash) {
268 let rhs = self.parse_pow()?;
269 lhs = Ast::Bin(BinOp::Div, Box::new(lhs), Box::new(rhs));
270 } else if self.eat(&Tok::Percent) {
271 let rhs = self.parse_pow()?;
272 lhs = Ast::Bin(BinOp::Mod, Box::new(lhs), Box::new(rhs));
273 } else {
274 break;
275 }
276 }
277 Ok(lhs)
278 }
279
280 fn parse_pow(&mut self) -> Result<Ast, ()> {
281 let base = self.parse_unary()?;
282 if self.eat(&Tok::Caret) {
283 let exp = self.with_depth(Self::parse_pow)?;
284 Ok(Ast::Bin(BinOp::Pow, Box::new(base), Box::new(exp)))
285 } else {
286 Ok(base)
287 }
288 }
289
290 fn parse_unary(&mut self) -> Result<Ast, ()> {
291 if self.eat(&Tok::Minus) {
292 let inner = self.with_depth(Self::parse_unary)?;
293 Ok(Ast::Neg(Box::new(inner)))
294 } else if self.eat(&Tok::Plus) {
295 self.with_depth(Self::parse_unary)
296 } else if self.eat(&Tok::Bang) {
297 let inner = self.with_depth(Self::parse_unary)?;
298 Ok(Ast::Not(Box::new(inner)))
299 } else {
300 self.parse_primary()
301 }
302 }
303
304 fn parse_primary(&mut self) -> Result<Ast, ()> {
305 match self.peek().cloned() {
306 Some(Tok::LParen) => {
307 self.pos += 1;
308 let inner = self.with_depth(Self::parse_or)?;
309 if !self.eat(&Tok::RParen) {
310 return Err(());
311 }
312 Ok(inner)
313 }
314 Some(Tok::Num(v)) => {
315 self.pos += 1;
316 Ok(Ast::Const(v))
317 }
318 Some(Tok::Ident(name)) => {
319 self.pos += 1;
320 if self.eat(&Tok::LParen) {
321 let mut args = Vec::new();
322 if self.peek() != Some(&Tok::RParen) {
323 loop {
324 args.push(self.with_depth(Self::parse_or)?);
325 if !self.eat(&Tok::Comma) {
326 break;
327 }
328 }
329 }
330 if !self.eat(&Tok::RParen) {
331 return Err(());
332 }
333 Ok(Ast::Call(resolve_func(&name, args.len())?, args))
334 } else {
335 Ok(Ast::Var(resolve_var(&name)?))
336 }
337 }
338 _ => Err(()),
339 }
340 }
341}
342
343fn resolve_var(name: &str) -> Result<Var, ()> {
344 match name {
345 "px" => Ok(Var::Px),
346 "py" => Ok(Var::Py),
347 "pz" => Ok(Var::Pz),
348 "vx" => Ok(Var::Vx),
349 "vy" => Ok(Var::Vy),
350 "vz" => Ok(Var::Vz),
351 "rx" => Ok(Var::Rx),
352 "ry" => Ok(Var::Ry),
353 "rz" => Ok(Var::Rz),
354 "sx" => Ok(Var::Sx),
355 "sy" => Ok(Var::Sy),
356 "sz" => Ok(Var::Sz),
357 "r" => Ok(Var::R),
358 "g" => Ok(Var::G),
359 "b" => Ok(Var::B),
360 "a" => Ok(Var::A),
361 "size" => Ok(Var::Size),
362 "age" => Ok(Var::Age),
363 "lifespan" | "life" => Ok(Var::Lifespan),
364 "id" => Ok(Var::Id),
365 "mass" => Ok(Var::Mass),
366 "user" => Ok(Var::User),
367 "time" => Ok(Var::Time),
368 "pi" => Ok(Var::Pi),
369 "e" => Ok(Var::E),
370 "n1" => Ok(Var::Num(0)),
371 "n2" => Ok(Var::Num(1)),
372 "n3" => Ok(Var::Num(2)),
373 "n4" => Ok(Var::Num(3)),
374 "n5" => Ok(Var::Num(4)),
375 "n6" => Ok(Var::Num(5)),
376 "n7" => Ok(Var::Num(6)),
377 "n8" => Ok(Var::Num(7)),
378 "p1x" => Ok(Var::Pt(0, 0)),
379 "p1y" => Ok(Var::Pt(0, 1)),
380 "p1z" => Ok(Var::Pt(0, 2)),
381 "p2x" => Ok(Var::Pt(1, 0)),
382 "p2y" => Ok(Var::Pt(1, 1)),
383 "p2z" => Ok(Var::Pt(1, 2)),
384 "p3x" => Ok(Var::Pt(2, 0)),
385 "p3y" => Ok(Var::Pt(2, 1)),
386 "p3z" => Ok(Var::Pt(2, 2)),
387 "p4x" => Ok(Var::Pt(3, 0)),
388 "p4y" => Ok(Var::Pt(3, 1)),
389 "p4z" => Ok(Var::Pt(3, 2)),
390 "s1" => Ok(Var::Setup(0)),
391 "s2" => Ok(Var::Setup(1)),
392 "s3" => Ok(Var::Setup(2)),
393 "s4" => Ok(Var::Setup(3)),
394 "i1" => Ok(Var::Inter(0)),
395 "i2" => Ok(Var::Inter(1)),
396 "i3" => Ok(Var::Inter(2)),
397 "i4" => Ok(Var::Inter(3)),
398 "i5" => Ok(Var::Inter(4)),
399 "i6" => Ok(Var::Inter(5)),
400 "i7" => Ok(Var::Inter(6)),
401 "i8" => Ok(Var::Inter(7)),
402 _ => Err(()),
403 }
404}
405
406fn resolve_func(name: &str, argc: usize) -> Result<Func, ()> {
407 if let Some(rest) = name.strip_prefix("get") {
408 let bytes = rest.as_bytes();
409 if (2..=3).contains(&bytes.len()) && argc == 2 {
410 let ch = match bytes[0] {
411 b'r' => Some(0),
412 b'g' => Some(1),
413 b'b' => Some(2),
414 b'a' => Some(3),
415 b'c' => Some(4),
416 _ => None,
417 };
418 let edge = match bytes.get(2) {
419 None | Some(b'b') => Some(0),
420 Some(b'w') => Some(1),
421 Some(b'd') => Some(2),
422 _ => None,
423 };
424 if let (Some(ch), Some(edge)) = (ch, edge) {
425 if bytes[1] == b'1' || bytes[1] == b'2' {
426 return Ok(Func::SampleImg(ch, edge));
427 }
428 }
429 }
430 }
431 let f = match (name, argc) {
432 ("sin", 1) => Func::Sin,
433 ("cos", 1) => Func::Cos,
434 ("tan", 1) => Func::Tan,
435 ("asin", 1) => Func::Asin,
436 ("acos", 1) => Func::Acos,
437 ("atan", 1) => Func::Atan,
438 ("atan2", 2) => Func::Atan2,
439 ("sinr", 1) => Func::Sinr,
440 ("cosr", 1) => Func::Cosr,
441 ("tanr", 1) => Func::Tanr,
442 ("asinr", 1) => Func::Asinr,
443 ("acosr", 1) => Func::Acosr,
444 ("atanr", 1) => Func::Atanr,
445 ("atan2r", 2) => Func::Atan2r,
446 ("sinh", 1) => Func::Sinh,
447 ("cosh", 1) => Func::Cosh,
448 ("tanh", 1) => Func::Tanh,
449 ("deg", 1) => Func::Deg,
450 ("rad", 1) => Func::Rad,
451 ("abs", 1) => Func::Abs,
452 ("sqrt", 1) => Func::Sqrt,
453 ("pow", 2) => Func::Pow,
454 ("exp", 1) => Func::Exp,
455 ("log" | "ln", 1) => Func::Log,
456 ("log10", 1) => Func::Log10,
457 ("log2", 1) => Func::Log2,
458 ("floor" | "int", 1) => Func::Floor,
459 ("ceil", 1) => Func::Ceil,
460 ("round", 1) => Func::Round,
461 ("trunc", 1) => Func::Trunc,
462 ("fract", 1) => Func::Fract,
463 ("sign", 1) => Func::Sign,
464 ("min", n) if n >= 2 => Func::Min,
465 ("max", n) if n >= 2 => Func::Max,
466 ("clamp", 3) => Func::Clamp,
467 ("mod", 2) => Func::Mod,
468 ("if" | "iif", 3) => Func::If,
469 ("dist", 4) => Func::Dist,
470 ("hypot", 2) => Func::Hypot,
471 ("mix" | "lerp", 3) => Func::Mix,
472 ("step", 2) => Func::Step,
473 ("smoothstep", 3) => Func::Smoothstep,
474 ("rand", 2) => Func::Rand,
475 ("rands", 3) => Func::Rands,
476 ("noise", 1) => Func::Noise1,
477 ("noise2", 2) => Func::Noise2,
478 ("noise3", 3) => Func::Noise3,
479 _ => return Err(()),
480 };
481 Ok(f)
482}
483
484pub(super) fn compile_expr(src: &str) -> Option<Ast> {
485 let trimmed = src.trim();
486 if trimmed.is_empty() {
487 return None;
488 }
489 let toks = tokenize(trimmed).ok()?;
490 let mut p = Parser { toks: &toks, pos: 0, depth: 0 };
491 p.parse().ok()
492}
493
494pub(super) use super::custom_eval::{apply_custom, apply_custom_force};