| author | |
| committer | |
| log | 0f4304f00f855af055d98da5759c54607d86d905 |
| tree | 3cefac4b04416cee1c58031b0d9f5972327fa94b |
| parent | b509d0cf05d0ce95484aa119b66a81e1eb8836d1 |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
6 files changed, 2439 insertions(+), 44 deletions(-)
crates/engine/src/custom_shader.rs created+1296| ... | ... | @@ -0,0 +1,1296 @@ |
| 1 | //! General Fusion `CustomTool` (`Custom`) per-pixel math DSL parser, WGSL codegen, | |
| 2 | //! and cached `wgpu::ComputePipeline` compiler/dispatcher. | |
| 3 | ||
| 4 | use bytemuck::{Pod, Zeroable}; | |
| 5 | use std::collections::HashMap; | |
| 6 | use std::collections::hash_map::DefaultHasher; | |
| 7 | use std::hash::{Hash, Hasher}; | |
| 8 | ||
| 9 | /// Uniform payload uploaded per `CustomTool` compute dispatch (4224 bytes, 16-byte aligned). | |
| 10 | #[repr(C)] | |
| 11 | #[derive(Clone, Copy, Pod, Zeroable)] | |
| 12 | pub struct CustomParams { | |
| 13 | /// `n1, n2, n3, n4` (`NumberIn1..4`, default 0.0) | |
| 14 | pub n0: [f32; 4], | |
| 15 | /// `n5, n6, n7, n8` (`NumberIn5..8`, default 0.0) | |
| 16 | pub n1: [f32; 4], | |
| 17 | /// `p1x, p1y, p2x, p2y` (`PointIn1..2`, default 0.5) | |
| 18 | pub p0: [f32; 4], | |
| 19 | /// `p3x, p3y, p4x, p4y` (`PointIn3..4`, default 0.5) | |
| 20 | pub p1: [f32; 4], | |
| 21 | /// `w1, h1, w2, h2` (full-resolution image dimensions in pixels) | |
| 22 | pub img_dims1: [f32; 4], | |
| 23 | /// `w3, h3, time, blend` | |
| 24 | pub img_dims2: [f32; 4], | |
| 25 | /// `has_mask, mask_invert, proc_r, proc_g` | |
| 26 | pub mask_proc: [f32; 4], | |
| 27 | /// `proc_b, proc_a, hdr_float, 0.0` | |
| 28 | pub proc_ba: [f32; 4], | |
| 29 | /// 256-sample baked 1D LUTs for `(LUTIn1, LUTIn2, LUTIn3, LUTIn4)`. | |
| 30 | pub luts: [[f32; 4]; 256], | |
| 31 | } | |
| 32 | ||
| 33 | impl Default for CustomParams { | |
| 34 | fn default() -> Self { | |
| 35 | let mut luts = [[0.0f32; 4]; 256]; | |
| 36 | for (i, slot) in luts.iter_mut().enumerate() { | |
| 37 | let v = i as f32 / 255.0; | |
| 38 | *slot = [v, v, v, v]; | |
| 39 | } | |
| 40 | Self { | |
| 41 | n0: [0.0; 4], | |
| 42 | n1: [0.0; 4], | |
| 43 | p0: [0.5; 4], | |
| 44 | p1: [0.5; 4], | |
| 45 | img_dims1: [1.0, 1.0, 1.0, 1.0], | |
| 46 | img_dims2: [1.0, 1.0, 0.0, 1.0], | |
| 47 | mask_proc: [0.0, 0.0, 1.0, 1.0], | |
| 48 | proc_ba: [1.0, 1.0, 0.0, 0.0], | |
| 49 | luts, | |
| 50 | } | |
| 51 | } | |
| 52 | } | |
| 53 | ||
| 54 | /// Normalized expression bundle for a Fusion `CustomTool` node. | |
| 55 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] | |
| 56 | pub struct CustomProgram { | |
| 57 | pub setups: [String; 4], | |
| 58 | pub intermediates: [String; 8], | |
| 59 | pub red: String, | |
| 60 | pub green: String, | |
| 61 | pub blue: String, | |
| 62 | pub alpha: String, | |
| 63 | } | |
| 64 | ||
| 65 | impl Default for CustomProgram { | |
| 66 | fn default() -> Self { | |
| 67 | Self { | |
| 68 | setups: std::array::from_fn(|_| "0".to_owned()), | |
| 69 | intermediates: std::array::from_fn(|_| "0".to_owned()), | |
| 70 | red: "r1".to_owned(), | |
| 71 | green: "g1".to_owned(), | |
| 72 | blue: "b1".to_owned(), | |
| 73 | alpha: "a1".to_owned(), | |
| 74 | } | |
| 75 | } | |
| 76 | } | |
| 77 | ||
| 78 | impl CustomProgram { | |
| 79 | /// Returns a canonicalized copy with comments stripped, whitespace collapsed, and defaults applied. | |
| 80 | pub fn normalized(&self) -> Self { | |
| 81 | Self { | |
| 82 | setups: std::array::from_fn(|i| normalize_expr(&self.setups[i], "0")), | |
| 83 | intermediates: std::array::from_fn(|i| normalize_expr(&self.intermediates[i], "0")), | |
| 84 | red: normalize_expr(&self.red, "r1"), | |
| 85 | green: normalize_expr(&self.green, "g1"), | |
| 86 | blue: normalize_expr(&self.blue, "b1"), | |
| 87 | alpha: normalize_expr(&self.alpha, "a1"), | |
| 88 | } | |
| 89 | } | |
| 90 | ||
| 91 | pub fn program_hash(&self) -> u64 { | |
| 92 | let mut h = DefaultHasher::new(); | |
| 93 | self.hash(&mut h); | |
| 94 | h.finish() | |
| 95 | } | |
| 96 | } | |
| 97 | ||
| 98 | /// Strips `//` and `/* */` comments, trims, and collapses ASCII whitespace so `"0\n"` == `"0"`. | |
| 99 | pub fn normalize_expr(raw: &str, default: &str) -> String { | |
| 100 | let bytes = raw.as_bytes(); | |
| 101 | let mut cleaned = String::with_capacity(raw.len()); | |
| 102 | let mut i = 0; | |
| 103 | let mut last_ws = true; | |
| 104 | while i < bytes.len() { | |
| 105 | if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'/') { | |
| 106 | i += 2; | |
| 107 | while i < bytes.len() && bytes[i] != b'\n' { | |
| 108 | i += 1; | |
| 109 | } | |
| 110 | continue; | |
| 111 | } | |
| 112 | if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'*') { | |
| 113 | i += 2; | |
| 114 | while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') { | |
| 115 | i += 1; | |
| 116 | } | |
| 117 | i = (i + 2).min(bytes.len()); | |
| 118 | continue; | |
| 119 | } | |
| 120 | let ch = raw[i..].chars().next().unwrap(); | |
| 121 | let len = ch.len_utf8(); | |
| 122 | if ch.is_whitespace() { | |
| 123 | if !last_ws { | |
| 124 | cleaned.push(' '); | |
| 125 | last_ws = true; | |
| 126 | } | |
| 127 | } else { | |
| 128 | cleaned.push(ch); | |
| 129 | last_ws = false; | |
| 130 | } | |
| 131 | i += len; | |
| 132 | } | |
| 133 | let trimmed = cleaned.trim(); | |
| 134 | if trimmed.is_empty() { | |
| 135 | default.to_owned() | |
| 136 | } else { | |
| 137 | trimmed.to_owned() | |
| 138 | } | |
| 139 | } | |
| 140 | ||
| 141 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 142 | enum Channel { | |
| 143 | Red, | |
| 144 | Green, | |
| 145 | Blue, | |
| 146 | Alpha, | |
| 147 | } | |
| 148 | ||
| 149 | impl Channel { | |
| 150 | fn swizzle(self) -> &'static str { | |
| 151 | match self { | |
| 152 | Self::Red => "r", | |
| 153 | Self::Green => "g", | |
| 154 | Self::Blue => "b", | |
| 155 | Self::Alpha => "a", | |
| 156 | } | |
| 157 | } | |
| 158 | } | |
| 159 | ||
| 160 | // ============================================================================ | |
| 161 | // Lexer & Recursive-Descent Parser -> WGSL Expression Compiler | |
| 162 | // ============================================================================ | |
| 163 | ||
| 164 | #[derive(Clone, Debug, PartialEq)] | |
| 165 | enum Token { | |
| 166 | Num(f64), | |
| 167 | Ident(String), | |
| 168 | Plus, | |
| 169 | Minus, | |
| 170 | Star, | |
| 171 | Slash, | |
| 172 | Percent, | |
| 173 | Caret, | |
| 174 | LParen, | |
| 175 | RParen, | |
| 176 | Comma, | |
| 177 | Lt, | |
| 178 | Le, | |
| 179 | Gt, | |
| 180 | Ge, | |
| 181 | Eq, | |
| 182 | Ne, | |
| 183 | And, | |
| 184 | Or, | |
| 185 | Bang, | |
| 186 | } | |
| 187 | ||
| 188 | fn tokenize(src: &str) -> Result<Vec<Token>, String> { | |
| 189 | let b = src.as_bytes(); | |
| 190 | let mut out = Vec::new(); | |
| 191 | let mut i = 0; | |
| 192 | while i < b.len() { | |
| 193 | let c = b[i]; | |
| 194 | if c.is_ascii_whitespace() { | |
| 195 | i += 1; | |
| 196 | continue; | |
| 197 | } | |
| 198 | if c == b'/' && b.get(i + 1) == Some(&b'/') { | |
| 199 | i += 2; | |
| 200 | while i < b.len() && b[i] != b'\n' { | |
| 201 | i += 1; | |
| 202 | } | |
| 203 | continue; | |
| 204 | } | |
| 205 | if c == b'/' && b.get(i + 1) == Some(&b'*') { | |
| 206 | i += 2; | |
| 207 | while i + 1 < b.len() && !(b[i] == b'*' && b[i + 1] == b'/') { | |
| 208 | i += 1; | |
| 209 | } | |
| 210 | i = (i + 2).min(b.len()); | |
| 211 | continue; | |
| 212 | } | |
| 213 | if c.is_ascii_digit() || (c == b'.' && b.get(i + 1).is_some_and(u8::is_ascii_digit)) { | |
| 214 | let start = i; | |
| 215 | while i < b.len() && b[i].is_ascii_digit() { | |
| 216 | i += 1; | |
| 217 | } | |
| 218 | if b.get(i) == Some(&b'.') { | |
| 219 | i += 1; | |
| 220 | while i < b.len() && b[i].is_ascii_digit() { | |
| 221 | i += 1; | |
| 222 | } | |
| 223 | } | |
| 224 | if matches!(b.get(i), Some(b'e' | b'E')) { | |
| 225 | let exp_pos = i; | |
| 226 | i += 1; | |
| 227 | if matches!(b.get(i), Some(b'+' | b'-')) { | |
| 228 | i += 1; | |
| 229 | } | |
| 230 | let dig_start = i; | |
| 231 | while i < b.len() && b[i].is_ascii_digit() { | |
| 232 | i += 1; | |
| 233 | } | |
| 234 | if i == dig_start { | |
| 235 | i = exp_pos; | |
| 236 | } | |
| 237 | } | |
| 238 | let s = &src[start..i]; | |
| 239 | let v: f64 = s.parse().map_err(|_| format!("invalid number literal '{s}'"))?; | |
| 240 | out.push(Token::Num(v)); | |
| 241 | continue; | |
| 242 | } | |
| 243 | if c.is_ascii_alphabetic() || c == b'_' { | |
| 244 | let start = i; | |
| 245 | while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') { | |
| 246 | i += 1; | |
| 247 | } | |
| 248 | out.push(Token::Ident(src[start..i].to_owned())); | |
| 249 | continue; | |
| 250 | } | |
| 251 | let next = b.get(i + 1).copied(); | |
| 252 | match (c, next) { | |
| 253 | (b'<', Some(b'=')) => { out.push(Token::Le); i += 2; } | |
| 254 | (b'>', Some(b'=')) => { out.push(Token::Ge); i += 2; } | |
| 255 | (b'=', Some(b'=')) => { out.push(Token::Eq); i += 2; } | |
| 256 | (b'!', Some(b'=')) | (b'~', Some(b'=')) | (b'<', Some(b'>')) => { out.push(Token::Ne); i += 2; } | |
| 257 | (b'&', Some(b'&')) => { out.push(Token::And); i += 2; } | |
| 258 | (b'|', Some(b'|')) => { out.push(Token::Or); i += 2; } | |
| 259 | (b'+', _) => { out.push(Token::Plus); i += 1; } | |
| 260 | (b'-', _) => { out.push(Token::Minus); i += 1; } | |
| 261 | (b'*', _) => { out.push(Token::Star); i += 1; } | |
| 262 | (b'/', _) => { out.push(Token::Slash); i += 1; } | |
| 263 | (b'%', _) => { out.push(Token::Percent); i += 1; } | |
| 264 | (b'^', _) => { out.push(Token::Caret); i += 1; } | |
| 265 | (b'(', _) => { out.push(Token::LParen); i += 1; } | |
| 266 | (b')', _) => { out.push(Token::RParen); i += 1; } | |
| 267 | (b',', _) => { out.push(Token::Comma); i += 1; } | |
| 268 | (b'<', _) => { out.push(Token::Lt); i += 1; } | |
| 269 | (b'>', _) => { out.push(Token::Gt); i += 1; } | |
| 270 | (b'=', _) => { out.push(Token::Eq); i += 1; } | |
| 271 | (b'&', _) => { out.push(Token::And); i += 1; } | |
| 272 | (b'|', _) => { out.push(Token::Or); i += 1; } | |
| 273 | (b'!', _) => { out.push(Token::Bang); i += 1; } | |
| 274 | _ => return Err(format!("unexpected character '{}'", c as char)), | |
| 275 | } | |
| 276 | } | |
| 277 | Ok(out) | |
| 278 | } | |
| 279 | ||
| 280 | struct ExprCompiler<'a> { | |
| 281 | tokens: &'a [Token], | |
| 282 | pos: usize, | |
| 283 | channel: Channel, | |
| 284 | max_setup: usize, | |
| 285 | max_inter: usize, | |
| 286 | } | |
| 287 | ||
| 288 | impl<'a> ExprCompiler<'a> { | |
| 289 | fn peek(&self) -> Option<&Token> { | |
| 290 | self.tokens.get(self.pos) | |
| 291 | } | |
| 292 | ||
| 293 | fn eat(&mut self, expected: &Token) -> bool { | |
| 294 | if self.peek() == Some(expected) { | |
| 295 | self.pos += 1; | |
| 296 | true | |
| 297 | } else { | |
| 298 | false | |
| 299 | } | |
| 300 | } | |
| 301 | ||
| 302 | fn compile(&mut self) -> Result<String, String> { | |
| 303 | if self.tokens.is_empty() { | |
| 304 | return Ok("0.0".to_owned()); | |
| 305 | } | |
| 306 | let expr = self.parse_or()?; | |
| 307 | if self.pos != self.tokens.len() { | |
| 308 | return Err(format!("unexpected trailing token {:?}", self.tokens[self.pos])); | |
| 309 | } | |
| 310 | Ok(expr) | |
| 311 | } | |
| 312 | ||
| 313 | fn parse_or(&mut self) -> Result<String, String> { | |
| 314 | let mut lhs = self.parse_and()?; | |
| 315 | while self.eat(&Token::Or) { | |
| 316 | let rhs = self.parse_and()?; | |
| 317 | lhs = format!("select(0.0, 1.0, (({lhs}) != 0.0) || (({rhs}) != 0.0))"); | |
| 318 | } | |
| 319 | Ok(lhs) | |
| 320 | } | |
| 321 | ||
| 322 | fn parse_and(&mut self) -> Result<String, String> { | |
| 323 | let mut lhs = self.parse_cmp()?; | |
| 324 | while self.eat(&Token::And) { | |
| 325 | let rhs = self.parse_cmp()?; | |
| 326 | lhs = format!("select(0.0, 1.0, (({lhs}) != 0.0) && (({rhs}) != 0.0))"); | |
| 327 | } | |
| 328 | Ok(lhs) | |
| 329 | } | |
| 330 | ||
| 331 | fn parse_cmp(&mut self) -> Result<String, String> { | |
| 332 | let mut lhs = self.parse_add()?; | |
| 333 | loop { | |
| 334 | let op = match self.peek() { | |
| 335 | Some(Token::Lt) => "<", | |
| 336 | Some(Token::Le) => "<=", | |
| 337 | Some(Token::Gt) => ">", | |
| 338 | Some(Token::Ge) => ">=", | |
| 339 | Some(Token::Eq) => "==", | |
| 340 | Some(Token::Ne) => "!=", | |
| 341 | _ => break, | |
| 342 | }; | |
| 343 | self.pos += 1; | |
| 344 | let rhs = self.parse_add()?; | |
| 345 | lhs = format!("select(0.0, 1.0, ({lhs}) {op} ({rhs}))"); | |
| 346 | } | |
| 347 | Ok(lhs) | |
| 348 | } | |
| 349 | ||
| 350 | fn parse_add(&mut self) -> Result<String, String> { | |
| 351 | let mut lhs = self.parse_mul()?; | |
| 352 | loop { | |
| 353 | if self.eat(&Token::Plus) { | |
| 354 | let rhs = self.parse_mul()?; | |
| 355 | lhs = format!("(({lhs}) + ({rhs}))"); | |
| 356 | } else if self.eat(&Token::Minus) { | |
| 357 | let rhs = self.parse_mul()?; | |
| 358 | lhs = format!("(({lhs}) - ({rhs}))"); | |
| 359 | } else { | |
| 360 | break; | |
| 361 | } | |
| 362 | } | |
| 363 | Ok(lhs) | |
| 364 | } | |
| 365 | ||
| 366 | fn parse_mul(&mut self) -> Result<String, String> { | |
| 367 | let mut lhs = self.parse_pow()?; | |
| 368 | loop { | |
| 369 | if self.eat(&Token::Star) { | |
| 370 | let rhs = self.parse_pow()?; | |
| 371 | lhs = format!("(({lhs}) * ({rhs}))"); | |
| 372 | } else if self.eat(&Token::Slash) { | |
| 373 | let rhs = self.parse_pow()?; | |
| 374 | lhs = format!("safe_div(({lhs}), ({rhs}))"); | |
| 375 | } else if self.eat(&Token::Percent) { | |
| 376 | let rhs = self.parse_pow()?; | |
| 377 | lhs = format!("fu_mod(({lhs}), ({rhs}))"); | |
| 378 | } else { | |
| 379 | break; | |
| 380 | } | |
| 381 | } | |
| 382 | Ok(lhs) | |
| 383 | } | |
| 384 | ||
| 385 | fn parse_pow(&mut self) -> Result<String, String> { | |
| 386 | let base = self.parse_unary()?; | |
| 387 | if self.eat(&Token::Caret) { | |
| 388 | // Right-associative and allows unary rhs (e.g. `e^-x`, `2^-3`) | |
| 389 | let exp = self.parse_pow()?; | |
| 390 | Ok(format!("fu_pow(({base}), ({exp}))")) | |
| 391 | } else { | |
| 392 | Ok(base) | |
| 393 | } | |
| 394 | } | |
| 395 | ||
| 396 | fn parse_unary(&mut self) -> Result<String, String> { | |
| 397 | if self.eat(&Token::Minus) { | |
| 398 | let inner = self.parse_unary()?; | |
| 399 | Ok(format!("(-({inner}))")) | |
| 400 | } else if self.eat(&Token::Plus) { | |
| 401 | self.parse_unary() | |
| 402 | } else if self.eat(&Token::Bang) { | |
| 403 | let inner = self.parse_unary()?; | |
| 404 | Ok(format!("select(0.0, 1.0, ({inner}) == 0.0)")) | |
| 405 | } else { | |
| 406 | self.parse_primary() | |
| 407 | } | |
| 408 | } | |
| 409 | ||
| 410 | fn parse_primary(&mut self) -> Result<String, String> { | |
| 411 | match self.peek().cloned() { | |
| 412 | Some(Token::LParen) => { | |
| 413 | self.pos += 1; | |
| 414 | let inner = self.parse_or()?; | |
| 415 | if !self.eat(&Token::RParen) { | |
| 416 | return Err("expected ')'".to_owned()); | |
| 417 | } | |
| 418 | Ok(format!("({inner})")) | |
| 419 | } | |
| 420 | Some(Token::Num(v)) => { | |
| 421 | self.pos += 1; | |
| 422 | Ok(format_wgsl_f32(v)) | |
| 423 | } | |
| 424 | Some(Token::Ident(name)) => { | |
| 425 | self.pos += 1; | |
| 426 | if self.eat(&Token::LParen) { | |
| 427 | let mut args = Vec::new(); | |
| 428 | if self.peek() != Some(&Token::RParen) { | |
| 429 | loop { | |
| 430 | args.push(self.parse_or()?); | |
| 431 | if !self.eat(&Token::Comma) { | |
| 432 | break; | |
| 433 | } | |
| 434 | } | |
| 435 | } | |
| 436 | if !self.eat(&Token::RParen) { | |
| 437 | return Err(format!("expected ')' after call to '{name}'")); | |
| 438 | } | |
| 439 | self.emit_call(&name, &args) | |
| 440 | } else { | |
| 441 | self.emit_var(&name) | |
| 442 | } | |
| 443 | } | |
| 444 | other => Err(format!("unexpected token {other:?}")), | |
| 445 | } | |
| 446 | } | |
| 447 | ||
| 448 | fn emit_var(&self, name: &str) -> Result<String, String> { | |
| 449 | let ch = self.channel.swizzle(); | |
| 450 | let wgsl = match name { | |
| 451 | "r1" => "p1.r", | |
| 452 | "g1" => "p1.g", | |
| 453 | "b1" => "p1.b", | |
| 454 | "a1" => "p1.a", | |
| 455 | "r2" => "p2.r", | |
| 456 | "g2" => "p2.g", | |
| 457 | "b2" => "p2.b", | |
| 458 | "a2" => "p2.a", | |
| 459 | "r3" => "p3.r", | |
| 460 | "g3" => "p3.g", | |
| 461 | "b3" => "p3.b", | |
| 462 | "a3" => "p3.a", | |
| 463 | "c1" => return Ok(format!("p1.{ch}")), | |
| 464 | "c2" => return Ok(format!("p2.{ch}")), | |
| 465 | "c3" => return Ok(format!("p3.{ch}")), | |
| 466 | "x" => "fu.x", | |
| 467 | "y" => "fu.y", | |
| 468 | "w" | "w1" => "u.img_dims1.x", | |
| 469 | "h" | "h1" => "u.img_dims1.y", | |
| 470 | "w2" => "u.img_dims1.z", | |
| 471 | "h2" => "u.img_dims1.w", | |
| 472 | "w3" => "u.img_dims2.x", | |
| 473 | "h3" => "u.img_dims2.y", | |
| 474 | "time" => "u.img_dims2.z", | |
| 475 | "pi" => "3.14159265", | |
| 476 | "e" => "2.71828183", | |
| 477 | "n1" => "u.n0.x", | |
| 478 | "n2" => "u.n0.y", | |
| 479 | "n3" => "u.n0.z", | |
| 480 | "n4" => "u.n0.w", | |
| 481 | "n5" => "u.n1.x", | |
| 482 | "n6" => "u.n1.y", | |
| 483 | "n7" => "u.n1.z", | |
| 484 | "n8" => "u.n1.w", | |
| 485 | "p1x" => "u.p0.x", | |
| 486 | "p1y" => "u.p0.y", | |
| 487 | "p2x" => "u.p0.z", | |
| 488 | "p2y" => "u.p0.w", | |
| 489 | "p3x" => "u.p1.x", | |
| 490 | "p3y" => "u.p1.y", | |
| 491 | "p4x" => "u.p1.z", | |
| 492 | "p4y" => "u.p1.w", | |
| 493 | "s1" if self.max_setup >= 1 => "s1", | |
| 494 | "s2" if self.max_setup >= 2 => "s2", | |
| 495 | "s3" if self.max_setup >= 3 => "s3", | |
| 496 | "s4" if self.max_setup >= 4 => "s4", | |
| 497 | "s1" | "s2" | "s3" | "s4" => "0.0", | |
| 498 | "i1" if self.max_inter >= 1 => "i1", | |
| 499 | "i2" if self.max_inter >= 2 => "i2", | |
| 500 | "i3" if self.max_inter >= 3 => "i3", | |
| 501 | "i4" if self.max_inter >= 4 => "i4", | |
| 502 | "i5" if self.max_inter >= 5 => "i5", | |
| 503 | "i6" if self.max_inter >= 6 => "i6", | |
| 504 | "i7" if self.max_inter >= 7 => "i7", | |
| 505 | "i8" if self.max_inter >= 8 => "i8", | |
| 506 | "i1" | "i2" | "i3" | "i4" | "i5" | "i6" | "i7" | "i8" => "0.0", | |
| 507 | // Aux channels (Z/Position/Normal/UV/Coverage/Obj/Mat) default cleanly to 0.0 | |
| 508 | "z1" | "z2" | "z3" | |
| 509 | | "cov1" | "cov2" | "cov3" | |
| 510 | | "obj1" | "obj2" | "obj3" | |
| 511 | | "mat1" | "mat2" | "mat3" | |
| 512 | | "px1" | "py1" | "pz1" | |
| 513 | | "px2" | "py2" | "pz2" | |
| 514 | | "px3" | "py3" | "pz3" | |
| 515 | | "nx1" | "ny1" | "nz1" | |
| 516 | | "nx2" | "ny2" | "nz2" | |
| 517 | | "nx3" | "ny3" | "nz3" | |
| 518 | | "u1" | "v1" | "u2" | "v2" | "u3" | "v3" | |
| 519 | | "bg1" | "bga1" | "bg2" | "bga2" | "bg3" | "bga3" => "0.0", | |
| 520 | other => return Err(format!("unknown variable '{other}'")), | |
| 521 | }; | |
| 522 | Ok(wgsl.to_owned()) | |
| 523 | } | |
| 524 | ||
| 525 | fn emit_call(&self, name: &str, args: &[String]) -> Result<String, String> { | |
| 526 | let req = |n: usize| -> Result<(), String> { | |
| 527 | if args.len() != n { | |
| 528 | Err(format!("function '{name}' expects {n} arg(s), got {}", args.len())) | |
| 529 | } else { | |
| 530 | Ok(()) | |
| 531 | } | |
| 532 | }; | |
| 533 | ||
| 534 | // Image samplers: get{r|g|b|a|c}{1|2|3}[b|w|d](sx, sy) | |
| 535 | if let Some(rest) = name.strip_prefix("get") { | |
| 536 | if let Some(code) = self.try_emit_sampler(rest, args)? { | |
| 537 | return Ok(code); | |
| 538 | } | |
| 539 | } | |
| 540 | ||
| 541 | match name { | |
| 542 | // Fusion CustomTool trig operates in DEGREES! | |
| 543 | "sin" => { req(1)?; Ok(format!("sin(({}) * DEG2RAD)", args[0])) } | |
| 544 | "cos" => { req(1)?; Ok(format!("cos(({}) * DEG2RAD)", args[0])) } | |
| 545 | "tan" => { req(1)?; Ok(format!("tan(({}) * DEG2RAD)", args[0])) } | |
| 546 | "asin" => { req(1)?; Ok(format!("(asin(clamp(({}), -1.0, 1.0)) * RAD2DEG)", args[0])) } | |
| 547 | "acos" => { req(1)?; Ok(format!("(acos(clamp(({}), -1.0, 1.0)) * RAD2DEG)", args[0])) } | |
| 548 | "atan" => { req(1)?; Ok(format!("(atan(({})) * RAD2DEG)", args[0])) } | |
| 549 | "atan2" => { req(2)?; Ok(format!("(atan2(({}), ({})) * RAD2DEG)", args[0], args[1])) } | |
| 550 | // Radian trig variants | |
| 551 | "sinr" => { req(1)?; Ok(format!("sin(({}))", args[0])) } | |
| 552 | "cosr" => { req(1)?; Ok(format!("cos(({}))", args[0])) } | |
| 553 | "tanr" => { req(1)?; Ok(format!("tan(({}))", args[0])) } | |
| 554 | "asinr" => { req(1)?; Ok(format!("asin(clamp(({}), -1.0, 1.0))", args[0])) } | |
| 555 | "acosr" => { req(1)?; Ok(format!("acos(clamp(({}), -1.0, 1.0))", args[0])) } | |
| 556 | "atanr" => { req(1)?; Ok(format!("atan(({}))", args[0])) } | |
| 557 | "atan2r" => { req(2)?; Ok(format!("atan2(({}), ({}))", args[0], args[1])) } | |
| 558 | // Hyperbolic | |
| 559 | "sinh" => { req(1)?; Ok(format!("sinh(({}))", args[0])) } | |
| 560 | "cosh" => { req(1)?; Ok(format!("cosh(({}))", args[0])) } | |
| 561 | "tanh" => { req(1)?; Ok(format!("tanh(({}))", args[0])) } | |
| 562 | "deg" => { req(1)?; Ok(format!("(({}) * RAD2DEG)", args[0])) } | |
| 563 | "rad" => { req(1)?; Ok(format!("(({}) * DEG2RAD)", args[0])) } | |
| 564 | // Core math | |
| 565 | "abs" => { req(1)?; Ok(format!("abs(({}))", args[0])) } | |
| 566 | "sqrt" => { req(1)?; Ok(format!("sqrt(max(({}), 0.0))", args[0])) } | |
| 567 | "pow" => { req(2)?; Ok(format!("fu_pow(({}), ({}))", args[0], args[1])) } | |
| 568 | "exp" => { req(1)?; Ok(format!("exp(({}))", args[0])) } | |
| 569 | "log" | "ln" => { req(1)?; Ok(format!("log(max(({}), 1e-12))", args[0])) } | |
| 570 | "log10" => { req(1)?; Ok(format!("(log(max(({}), 1e-12)) * 0.43429448)", args[0])) } | |
| 571 | "log2" => { req(1)?; Ok(format!("log2(max(({}), 1e-12))", args[0])) } | |
| 572 | "floor" | "int" => { req(1)?; Ok(format!("floor(({}))", args[0])) } | |
| 573 | "ceil" => { req(1)?; Ok(format!("ceil(({}))", args[0])) } | |
| 574 | "round" => { req(1)?; Ok(format!("round(({}))", args[0])) } | |
| 575 | "trunc" => { req(1)?; Ok(format!("trunc(({}))", args[0])) } | |
| 576 | "fract" => { req(1)?; Ok(format!("fract(({}))", args[0])) } | |
| 577 | "sign" => { req(1)?; Ok(format!("sign(({}))", args[0])) } | |
| 578 | "min" => { | |
| 579 | if args.len() < 2 { | |
| 580 | return Err("function 'min' expects at least 2 args".to_owned()); | |
| 581 | } | |
| 582 | let mut acc = format!("min(({}), ({}))", args[0], args[1]); | |
| 583 | for arg in &args[2..] { | |
| 584 | acc = format!("min(({acc}), ({arg}))"); | |
| 585 | } | |
| 586 | Ok(acc) | |
| 587 | } | |
| 588 | "max" => { | |
| 589 | if args.len() < 2 { | |
| 590 | return Err("function 'max' expects at least 2 args".to_owned()); | |
| 591 | } | |
| 592 | let mut acc = format!("max(({}), ({}))", args[0], args[1]); | |
| 593 | for arg in &args[2..] { | |
| 594 | acc = format!("max(({acc}), ({arg}))"); | |
| 595 | } | |
| 596 | Ok(acc) | |
| 597 | } | |
| 598 | "clamp" => { req(3)?; Ok(format!("clamp(({}), ({}), ({}))", args[0], args[1], args[2])) } | |
| 599 | "mod" => { req(2)?; Ok(format!("fu_mod(({}), ({}))", args[0], args[1])) } | |
| 600 | "if" | "iif" => { req(3)?; Ok(format!("select(({}), ({}), ({}) != 0.0)", args[2], args[1], args[0])) } | |
| 601 | "dist" => { | |
| 602 | req(4)?; | |
| 603 | Ok(format!("length(vec2<f32>(({}) - ({}), ({}) - ({})))", args[2], args[0], args[3], args[1])) | |
| 604 | } | |
| 605 | "hypot" => { req(2)?; Ok(format!("length(vec2<f32>(({}), ({})))", args[0], args[1])) } | |
| 606 | "mix" | "lerp" => { req(3)?; Ok(format!("mix(({}), ({}), ({}))", args[0], args[1], args[2])) } | |
| 607 | "step" => { req(2)?; Ok(format!("step(({}), ({}))", args[0], args[1])) } | |
| 608 | "smoothstep" => { req(3)?; Ok(format!("smoothstep(({}), ({}), ({}))", args[0], args[1], args[2])) } | |
| 609 | // LUT samplers (Fusion canonical `getlut1..4` + `lut1..4` alias) | |
| 610 | "getlut1" | "lut1" => { req(1)?; Ok(format!("sample_lut(0u, ({}))", args[0])) } | |
| 611 | "getlut2" | "lut2" => { req(1)?; Ok(format!("sample_lut(1u, ({}))", args[0])) } | |
| 612 | "getlut3" | "lut3" => { req(1)?; Ok(format!("sample_lut(2u, ({}))", args[0])) } | |
| 613 | "getlut4" | "lut4" => { req(1)?; Ok(format!("sample_lut(3u, ({}))", args[0])) } | |
| 614 | // Random & procedural noise | |
| 615 | "rand" => { req(2)?; Ok(format!("mix(({}), ({}), fu_hash(vec3<f32>(f32(gid.x), f32(gid.y), u.img_dims2.z)))", args[0], args[1])) } | |
| 616 | "rands" => { req(3)?; Ok(format!("mix(({}), ({}), fu_hash(vec3<f32>(f32(gid.x), f32(gid.y), ({}))))", args[0], args[1], args[2])) } | |
| 617 | "noise" => { req(1)?; Ok(format!("fu_noise1(({}))", args[0])) } | |
| 618 | "noise2" => { req(2)?; Ok(format!("fu_noise2(vec2<f32>(({}), ({})))", args[0], args[1])) } | |
| 619 | "noise3" => { req(3)?; Ok(format!("fu_noise3(vec3<f32>(({}), ({}), ({})))", args[0], args[1], args[2])) } | |
| 620 | other => Err(format!("unknown function '{other}'")), | |
| 621 | } | |
| 622 | } | |
| 623 | ||
| 624 | fn try_emit_sampler(&self, rest: &str, args: &[String]) -> Result<Option<String>, String> { | |
| 625 | let bytes = rest.as_bytes(); | |
| 626 | if bytes.len() < 2 || bytes.len() > 3 { | |
| 627 | return Ok(None); | |
| 628 | } | |
| 629 | let ch = match bytes[0] { | |
| 630 | b'r' => "r", | |
| 631 | b'g' => "g", | |
| 632 | b'b' => "b", | |
| 633 | b'a' => "a", | |
| 634 | b'c' => self.channel.swizzle(), | |
| 635 | _ => return Ok(None), | |
| 636 | }; | |
| 637 | let tex = match bytes[1] { | |
| 638 | b'1' => "src_1", | |
| 639 | b'2' => "src_2", | |
| 640 | b'3' => "src_3", | |
| 641 | _ => return Ok(None), | |
| 642 | }; | |
| 643 | let edge_mode = match bytes.get(2) { | |
| 644 | None | Some(b'b') => 0, // Black / Canvas | |
| 645 | Some(b'w') => 1, // Wrap | |
| 646 | Some(b'd') => 2, // Duplicate / Clamp | |
| 647 | _ => return Ok(None), | |
| 648 | }; | |
| 649 | if args.len() != 2 { | |
| 650 | return Err(format!("sampler 'get{rest}' expects 2 args, got {}", args.len())); | |
| 651 | } | |
| 652 | Ok(Some(format!( | |
| 653 | "sample_img({tex}, ({}), ({}), {edge_mode}).{ch}", | |
| 654 | args[0], args[1] | |
| 655 | ))) | |
| 656 | } | |
| 657 | } | |
| 658 | ||
| 659 | fn format_wgsl_f32(v: f64) -> String { | |
| 660 | let f = v as f32; | |
| 661 | if !f.is_finite() { | |
| 662 | return "0.0".to_owned(); | |
| 663 | } | |
| 664 | let s = format!("{f}"); | |
| 665 | if s.contains('.') || s.contains('e') || s.contains('E') { | |
| 666 | s | |
| 667 | } else { | |
| 668 | format!("{s}.0") | |
| 669 | } | |
| 670 | } | |
| 671 | ||
| 672 | fn compile_single_expr( | |
| 673 | src: &str, | |
| 674 | channel: Channel, | |
| 675 | max_setup: usize, | |
| 676 | max_inter: usize, | |
| 677 | ) -> Result<String, String> { | |
| 678 | let tokens = tokenize(src)?; | |
| 679 | let mut compiler = ExprCompiler { | |
| 680 | tokens: &tokens, | |
| 681 | pos: 0, | |
| 682 | channel, | |
| 683 | max_setup, | |
| 684 | max_inter, | |
| 685 | }; | |
| 686 | compiler.compile() | |
| 687 | } | |
| 688 | ||
| 689 | /// Compiles a normalized `CustomProgram` into a complete WGSL compute shader string | |
| 690 | /// targeting `format` (`Rgba8Unorm`, `Rgba16Float`, or `Rgba32Float`). | |
| 691 | pub fn compile_wgsl(program: &CustomProgram, format: wgpu::TextureFormat) -> Result<String, String> { | |
| 692 | let norm = program.normalized(); | |
| 693 | let storage_fmt = match format { | |
| 694 | wgpu::TextureFormat::Rgba16Float => "rgba16float", | |
| 695 | wgpu::TextureFormat::Rgba32Float => "rgba32float", | |
| 696 | _ => "rgba8unorm", | |
| 697 | }; | |
| 698 | ||
| 699 | let mut setup_decls = String::new(); | |
| 700 | for idx in 0..4 { | |
| 701 | let expr = compile_single_expr(&norm.setups[idx], Channel::Red, idx, 0)?; | |
| 702 | setup_decls.push_str(&format!(" let s{}: f32 = {expr};\n", idx + 1)); | |
| 703 | } | |
| 704 | ||
| 705 | let mut inter_decls = String::new(); | |
| 706 | for idx in 0..8 { | |
| 707 | let expr = compile_single_expr(&norm.intermediates[idx], Channel::Red, 4, idx)?; | |
| 708 | inter_decls.push_str(&format!(" let i{}: f32 = {expr};\n", idx + 1)); | |
| 709 | } | |
| 710 | ||
| 711 | let red_expr = compile_single_expr(&norm.red, Channel::Red, 4, 8)?; | |
| 712 | let green_expr = compile_single_expr(&norm.green, Channel::Green, 4, 8)?; | |
| 713 | let blue_expr = compile_single_expr(&norm.blue, Channel::Blue, 4, 8)?; | |
| 714 | let alpha_expr = compile_single_expr(&norm.alpha, Channel::Alpha, 4, 8)?; | |
| 715 | ||
| 716 | Ok(format!( | |
| 717 | r#"// Auto-generated Fusion CustomTool compute shader | |
| 718 | @group(0) @binding(0) var src_1: texture_2d<f32>; | |
| 719 | @group(0) @binding(1) var src_2: texture_2d<f32>; | |
| 720 | @group(0) @binding(2) var src_3: texture_2d<f32>; | |
| 721 | @group(0) @binding(3) var mask_tex: texture_2d<f32>; | |
| 722 | @group(0) @binding(4) var samp_lin: sampler; | |
| 723 | @group(0) @binding(5) var dst_tex: texture_storage_2d<{storage_fmt}, write>; | |
| 724 | ||
| 725 | struct CustomParams {{ | |
| 726 | n0: vec4<f32>, | |
| 727 | n1: vec4<f32>, | |
| 728 | p0: vec4<f32>, | |
| 729 | p1: vec4<f32>, | |
| 730 | img_dims1: vec4<f32>, | |
| 731 | img_dims2: vec4<f32>, | |
| 732 | mask_proc: vec4<f32>, | |
| 733 | proc_ba: vec4<f32>, | |
| 734 | luts: array<vec4<f32>, 256>, | |
| 735 | }}; | |
| 736 | @group(0) @binding(6) var<uniform> u: CustomParams; | |
| 737 | ||
| 738 | const DEG2RAD: f32 = 0.017453292519943295; | |
| 739 | const RAD2DEG: f32 = 57.29577951308232; | |
| 740 | ||
| 741 | fn safe_div(a: f32, b: f32) -> f32 {{ | |
| 742 | return select(a / b, 0.0, abs(b) < 1e-12); | |
| 743 | }} | |
| 744 | ||
| 745 | fn fu_mod(a: f32, b: f32) -> f32 {{ | |
| 746 | if (abs(b) < 1e-12) {{ return 0.0; }} | |
| 747 | return a - b * floor(a / b); | |
| 748 | }} | |
| 749 | ||
| 750 | fn fu_pow(a: f32, b: f32) -> f32 {{ | |
| 751 | if (a > 0.0) {{ | |
| 752 | return pow(a, b); | |
| 753 | }} | |
| 754 | if (a == 0.0) {{ | |
| 755 | return select(0.0, 1.0, abs(b) < 1e-12); | |
| 756 | }} | |
| 757 | let rb = round(b); | |
| 758 | if (abs(b - rb) < 1e-5) {{ | |
| 759 | let mag = pow(abs(a), rb); | |
| 760 | let odd = (i32(rb) & 1) != 0; | |
| 761 | return select(mag, -mag, odd); | |
| 762 | }} | |
| 763 | return 0.0; | |
| 764 | }} | |
| 765 | ||
| 766 | fn fu_hash(p: vec3<f32>) -> f32 {{ | |
| 767 | var p3 = fract(p * vec3<f32>(0.1031, 0.1030, 0.0973)); | |
| 768 | p3 = p3 + dot(p3, p3.yzx + 33.33); | |
| 769 | return fract((p3.x + p3.y) * p3.z); | |
| 770 | }} | |
| 771 | ||
| 772 | fn fu_noise1(x: f32) -> f32 {{ | |
| 773 | let i = floor(x); | |
| 774 | let f = fract(x); | |
| 775 | let u_f = f * f * (3.0 - 2.0 * f); | |
| 776 | return mix(fu_hash(vec3<f32>(i, 0.0, 0.0)), fu_hash(vec3<f32>(i + 1.0, 0.0, 0.0)), u_f) * 2.0 - 1.0; | |
| 777 | }} | |
| 778 | ||
| 779 | fn fu_noise2(p: vec2<f32>) -> f32 {{ | |
| 780 | let i = floor(p); | |
| 781 | let f = fract(p); | |
| 782 | let u_f = f * f * (3.0 - 2.0 * f); | |
| 783 | let a = fu_hash(vec3<f32>(i, 0.0)); | |
| 784 | let b = fu_hash(vec3<f32>(i + vec2<f32>(1.0, 0.0), 0.0)); | |
| 785 | let c = fu_hash(vec3<f32>(i + vec2<f32>(0.0, 1.0), 0.0)); | |
| 786 | let d = fu_hash(vec3<f32>(i + vec2<f32>(1.0, 1.0), 0.0)); | |
| 787 | return mix(mix(a, b, u_f.x), mix(c, d, u_f.x), u_f.y) * 2.0 - 1.0; | |
| 788 | }} | |
| 789 | ||
| 790 | fn fu_noise3(p: vec3<f32>) -> f32 {{ | |
| 791 | let i = floor(p); | |
| 792 | let f = fract(p); | |
| 793 | let u_f = f * f * (3.0 - 2.0 * f); | |
| 794 | let n000 = fu_hash(i + vec3<f32>(0.0, 0.0, 0.0)); | |
| 795 | let n100 = fu_hash(i + vec3<f32>(1.0, 0.0, 0.0)); | |
| 796 | let n010 = fu_hash(i + vec3<f32>(0.0, 1.0, 0.0)); | |
| 797 | let n110 = fu_hash(i + vec3<f32>(1.0, 1.0, 0.0)); | |
| 798 | let n001 = fu_hash(i + vec3<f32>(0.0, 0.0, 1.0)); | |
| 799 | let n101 = fu_hash(i + vec3<f32>(1.0, 0.0, 1.0)); | |
| 800 | let n011 = fu_hash(i + vec3<f32>(0.0, 1.0, 1.0)); | |
| 801 | let n111 = fu_hash(i + vec3<f32>(1.0, 1.0, 1.0)); | |
| 802 | let nx00 = mix(n000, n100, u_f.x); | |
| 803 | let nx10 = mix(n010, n110, u_f.x); | |
| 804 | let nx01 = mix(n001, n101, u_f.x); | |
| 805 | let nx11 = mix(n011, n111, u_f.x); | |
| 806 | return mix(mix(nx00, nx10, u_f.y), mix(nx01, nx11, u_f.y), u_f.z) * 2.0 - 1.0; | |
| 807 | }} | |
| 808 | ||
| 809 | fn sample_lut(ch: u32, v: f32) -> f32 {{ | |
| 810 | let t = clamp(v, 0.0, 1.0) * 255.0; | |
| 811 | let i0 = u32(floor(t)); | |
| 812 | let i1 = min(i0 + 1u, 255u); | |
| 813 | let frac = t - f32(i0); | |
| 814 | return mix(u.luts[i0][ch], u.luts[i1][ch], frac); | |
| 815 | }} | |
| 816 | ||
| 817 | fn read_img_curr(tex: texture_2d<f32>, gid: vec2<u32>, dims: vec2<u32>) -> vec4<f32> {{ | |
| 818 | let tdims = textureDimensions(tex); | |
| 819 | if (tdims.x == dims.x && tdims.y == dims.y) {{ | |
| 820 | return textureLoad(tex, vec2<i32>(gid), 0); | |
| 821 | }} | |
| 822 | if (tdims.x <= 1u && tdims.y <= 1u) {{ | |
| 823 | return textureLoad(tex, vec2<i32>(0, 0), 0); | |
| 824 | }} | |
| 825 | let uv = (vec2<f32>(gid) + 0.5) / vec2<f32>(dims); | |
| 826 | return textureSampleLevel(tex, samp_lin, uv, 0.0); | |
| 827 | }} | |
| 828 | ||
| 829 | fn sample_img(tex: texture_2d<f32>, fx: f32, fy: f32, mode: i32) -> vec4<f32> {{ | |
| 830 | let uv = vec2<f32>(fx, 1.0 - fy); | |
| 831 | if (mode == 0) {{ | |
| 832 | if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) {{ | |
| 833 | return vec4<f32>(0.0); | |
| 834 | }} | |
| 835 | return textureSampleLevel(tex, samp_lin, uv, 0.0); | |
| 836 | }} else if (mode == 1) {{ | |
| 837 | return textureSampleLevel(tex, samp_lin, fract(uv), 0.0); | |
| 838 | }} else {{ | |
| 839 | return textureSampleLevel(tex, samp_lin, clamp(uv, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0); | |
| 840 | }} | |
| 841 | }} | |
| 842 | ||
| 843 | fn read_custom_mask(gid: vec2<u32>, dims: vec2<u32>, has_mask: f32, invert: f32) -> f32 {{ | |
| 844 | if (has_mask < 0.5) {{ | |
| 845 | return 1.0; | |
| 846 | }} | |
| 847 | let uv = (vec2<f32>(gid) + 0.5) / vec2<f32>(dims); | |
| 848 | let m = textureSampleLevel(mask_tex, samp_lin, uv, 0.0).a; | |
| 849 | return select(m, 1.0 - m, invert > 0.5); | |
| 850 | }} | |
| 851 | ||
| 852 | @compute @workgroup_size(8, 8) | |
| 853 | fn custom_tool_op(@builtin(global_invocation_id) gid: vec3<u32>) {{ | |
| 854 | let dims = textureDimensions(dst_tex); | |
| 855 | if (gid.x >= dims.x || gid.y >= dims.y) {{ return; }} | |
| 856 | ||
| 857 | let fdims = vec2<f32>(dims); | |
| 858 | let fu = vec2<f32>((f32(gid.x) + 0.5) / fdims.x, 1.0 - (f32(gid.y) + 0.5) / fdims.y); | |
| 859 | let p1 = read_img_curr(src_1, gid.xy, dims); | |
| 860 | let p2 = read_img_curr(src_2, gid.xy, dims); | |
| 861 | let p3 = read_img_curr(src_3, gid.xy, dims); | |
| 862 | ||
| 863 | {setup_decls}{inter_decls} let out_r: f32 = select(p1.r, ({red_expr}), u.mask_proc.z > 0.5); | |
| 864 | let out_g: f32 = select(p1.g, ({green_expr}), u.mask_proc.w > 0.5); | |
| 865 | let out_b: f32 = select(p1.b, ({blue_expr}), u.proc_ba.x > 0.5); | |
| 866 | let out_a: f32 = select(p1.a, ({alpha_expr}), u.proc_ba.y > 0.5); | |
| 867 | ||
| 868 | let m = clamp(read_custom_mask(gid.xy, dims, u.mask_proc.x, u.mask_proc.y) * u.img_dims2.w, 0.0, 1.0); | |
| 869 | let final_col = mix(p1, vec4<f32>(out_r, out_g, out_b, out_a), m); | |
| 870 | ||
| 871 | if (u.proc_ba.z > 0.5) {{ | |
| 872 | textureStore(dst_tex, vec2<i32>(gid.xy), final_col); | |
| 873 | }} else {{ | |
| 874 | textureStore(dst_tex, vec2<i32>(gid.xy), clamp(final_col, vec4<f32>(0.0), vec4<f32>(1.0))); | |
| 875 | }} | |
| 876 | }} | |
| 877 | "# | |
| 878 | )) | |
| 879 | } | |
| 880 | ||
| 881 | // ============================================================================ | |
| 882 | // Pipeline Cache & GPU Dispatch | |
| 883 | // ============================================================================ | |
| 884 | ||
| 885 | struct FormatLayouts { | |
| 886 | bgl: wgpu::BindGroupLayout, | |
| 887 | pl: wgpu::PipelineLayout, | |
| 888 | } | |
| 889 | ||
| 890 | /// Caches dynamically compiled `CustomTool` compute pipelines keyed by | |
| 891 | /// `(dst_texture_format, hash_of_normalized_program)`. | |
| 892 | #[derive(Default)] | |
| 893 | pub struct CustomShaderCache { | |
| 894 | layouts: HashMap<wgpu::TextureFormat, FormatLayouts>, | |
| 895 | sampler: Option<wgpu::Sampler>, | |
| 896 | pipelines: HashMap<(wgpu::TextureFormat, u64), Option<wgpu::ComputePipeline>>, | |
| 897 | } | |
| 898 | ||
| 899 | impl CustomShaderCache { | |
| 900 | pub fn new() -> Self { | |
| 901 | Self::default() | |
| 902 | } | |
| 903 | ||
| 904 | pub fn cached_pipeline_count(&self) -> usize { | |
| 905 | self.pipelines.len() | |
| 906 | } | |
| 907 | ||
| 908 | fn ensure_format_layouts(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat) { | |
| 909 | self.layouts.entry(format).or_insert_with(|| { | |
| 910 | let tex_entry = |binding| wgpu::BindGroupLayoutEntry { | |
| 911 | binding, | |
| 912 | visibility: wgpu::ShaderStages::COMPUTE, | |
| 913 | ty: wgpu::BindingType::Texture { | |
| 914 | sample_type: wgpu::TextureSampleType::Float { filterable: true }, | |
| 915 | view_dimension: wgpu::TextureViewDimension::D2, | |
| 916 | multisampled: false, | |
| 917 | }, | |
| 918 | count: None, | |
| 919 | }; | |
| 920 | let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { | |
| 921 | label: Some("custom-tool-bgl"), | |
| 922 | entries: &[ | |
| 923 | tex_entry(0), | |
| 924 | tex_entry(1), | |
| 925 | tex_entry(2), | |
| 926 | tex_entry(3), | |
| 927 | wgpu::BindGroupLayoutEntry { | |
| 928 | binding: 4, | |
| 929 | visibility: wgpu::ShaderStages::COMPUTE, | |
| 930 | ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), | |
| 931 | count: None, | |
| 932 | }, | |
| 933 | wgpu::BindGroupLayoutEntry { | |
| 934 | binding: 5, | |
| 935 | visibility: wgpu::ShaderStages::COMPUTE, | |
| 936 | ty: wgpu::BindingType::StorageTexture { | |
| 937 | access: wgpu::StorageTextureAccess::WriteOnly, | |
| 938 | format, | |
| 939 | view_dimension: wgpu::TextureViewDimension::D2, | |
| 940 | }, | |
| 941 | count: None, | |
| 942 | }, | |
| 943 | wgpu::BindGroupLayoutEntry { | |
| 944 | binding: 6, | |
| 945 | visibility: wgpu::ShaderStages::COMPUTE, | |
| 946 | ty: wgpu::BindingType::Buffer { | |
| 947 | ty: wgpu::BufferBindingType::Uniform, | |
| 948 | has_dynamic_offset: false, | |
| 949 | min_binding_size: None, | |
| 950 | }, | |
| 951 | count: None, | |
| 952 | }, | |
| 953 | ], | |
| 954 | }); | |
| 955 | let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { | |
| 956 | label: Some("custom-tool-pl"), | |
| 957 | bind_group_layouts: &[Some(&bgl)], | |
| 958 | immediate_size: 0, | |
| 959 | }); | |
| 960 | FormatLayouts { bgl, pl } | |
| 961 | }); | |
| 962 | if self.sampler.is_none() { | |
| 963 | self.sampler = Some(device.create_sampler(&wgpu::SamplerDescriptor { | |
| 964 | label: Some("custom-tool-linear"), | |
| 965 | address_mode_u: wgpu::AddressMode::ClampToEdge, | |
| 966 | address_mode_v: wgpu::AddressMode::ClampToEdge, | |
| 967 | mag_filter: wgpu::FilterMode::Linear, | |
| 968 | min_filter: wgpu::FilterMode::Linear, | |
| 969 | mipmap_filter: wgpu::MipmapFilterMode::Nearest, | |
| 970 | ..Default::default() | |
| 971 | })); | |
| 972 | } | |
| 973 | } | |
| 974 | ||
| 975 | /// Compiles and caches the compute pipeline for `program` at `format`, returning `false` | |
| 976 | /// if the program contains unsupported syntax (graceful fallback to passthrough). | |
| 977 | pub fn ensure_compiled( | |
| 978 | &mut self, | |
| 979 | device: &wgpu::Device, | |
| 980 | program: &CustomProgram, | |
| 981 | format: wgpu::TextureFormat, | |
| 982 | ) -> bool { | |
| 983 | let norm = program.normalized(); | |
| 984 | let key = (format, norm.program_hash()); | |
| 985 | if let Some(entry) = self.pipelines.get(&key) { | |
| 986 | return entry.is_some(); | |
| 987 | } | |
| 988 | self.ensure_format_layouts(device, format); | |
| 989 | let pipeline = match compile_wgsl(&norm, format) { | |
| 990 | Ok(wgsl) => { | |
| 991 | let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { | |
| 992 | label: Some("custom-tool-shader"), | |
| 993 | source: wgpu::ShaderSource::Wgsl(wgsl.into()), | |
| 994 | }); | |
| 995 | let pl = &self.layouts[&format].pl; | |
| 996 | Some(device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { | |
| 997 | label: Some("custom_tool_op"), | |
| 998 | layout: Some(pl), | |
| 999 | module: &module, | |
| 1000 | entry_point: Some("custom_tool_op"), | |
| 1001 | compilation_options: Default::default(), | |
| 1002 | cache: None, | |
| 1003 | })) | |
| 1004 | } | |
| 1005 | Err(_) => None, | |
| 1006 | }; | |
| 1007 | let ok = pipeline.is_some(); | |
| 1008 | self.pipelines.insert(key, pipeline); | |
| 1009 | ok | |
| 1010 | } | |
| 1011 | ||
| 1012 | /// Dispatches a compiled `CustomProgram` into `dst_view`. Returns `false` if compilation failed. | |
| 1013 | #[allow(clippy::too_many_arguments)] | |
| 1014 | pub fn dispatch( | |
| 1015 | &mut self, | |
| 1016 | device: &wgpu::Device, | |
| 1017 | queue: &wgpu::Queue, | |
| 1018 | enc: &mut wgpu::CommandEncoder, | |
| 1019 | program: &CustomProgram, | |
| 1020 | format: wgpu::TextureFormat, | |
| 1021 | src_1: &wgpu::TextureView, | |
| 1022 | src_2: &wgpu::TextureView, | |
| 1023 | src_3: &wgpu::TextureView, | |
| 1024 | mask: &wgpu::TextureView, | |
| 1025 | dst_view: &wgpu::TextureView, | |
| 1026 | dst_size: [u32; 2], | |
| 1027 | params: &CustomParams, | |
| 1028 | ) -> bool { | |
| 1029 | let norm = program.normalized(); | |
| 1030 | let key = (format, norm.program_hash()); | |
| 1031 | if !self.ensure_compiled(device, &norm, format) { | |
| 1032 | return false; | |
| 1033 | } | |
| 1034 | let Some(Some(pipeline)) = self.pipelines.get(&key) else { | |
| 1035 | return false; | |
| 1036 | }; | |
| 1037 | let layout = &self.layouts[&format].bgl; | |
| 1038 | let sampler = self.sampler.as_ref().expect("sampler initialized"); | |
| 1039 | ||
| 1040 | let ubuf = device.create_buffer(&wgpu::BufferDescriptor { | |
| 1041 | label: Some("custom-tool-params"), | |
| 1042 | size: std::mem::size_of::<CustomParams>() as u64, | |
| 1043 | usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, | |
| 1044 | mapped_at_creation: false, | |
| 1045 | }); | |
| 1046 | queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(params)); | |
| 1047 | ||
| 1048 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { | |
| 1049 | label: Some("custom-tool-bg"), | |
| 1050 | layout, | |
| 1051 | entries: &[ | |
| 1052 | wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_1) }, | |
| 1053 | wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_2) }, | |
| 1054 | wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(src_3) }, | |
| 1055 | wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(mask) }, | |
| 1056 | wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::Sampler(sampler) }, | |
| 1057 | wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(dst_view) }, | |
| 1058 | wgpu::BindGroupEntry { binding: 6, resource: ubuf.as_entire_binding() }, | |
| 1059 | ], | |
| 1060 | }); | |
| 1061 | ||
| 1062 | let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { | |
| 1063 | label: Some("custom-tool-pass"), | |
| 1064 | timestamp_writes: None, | |
| 1065 | }); | |
| 1066 | pass.set_pipeline(pipeline); | |
| 1067 | pass.set_bind_group(0, &bg, &[]); | |
| 1068 | pass.dispatch_workgroups(dst_size[0].div_ceil(8), dst_size[1].div_ceil(8), 1); | |
| 1069 | true | |
| 1070 | } | |
| 1071 | } | |
| 1072 | ||
| 1073 | #[cfg(test)] | |
| 1074 | mod tests { | |
| 1075 | use super::*; | |
| 1076 | use crate::{Engine, create_texture}; | |
| 1077 | use model::Comp; | |
| 1078 | ||
| 1079 | #[test] | |
| 1080 | fn parses_operator_precedence_and_edge_cases() { | |
| 1081 | let mut p = CustomProgram::default(); | |
| 1082 | p.setups[0] = "1/n1".to_owned(); | |
| 1083 | p.setups[1] = "s1 - n2*s1".to_owned(); | |
| 1084 | p.intermediates[0] = "if(n7=0, (r1/n1), (r1*n1))".to_owned(); | |
| 1085 | p.red = "if(c1>n1, n1+i1*(1-e^-((c1-n1)/i1)), c1)".to_owned(); | |
| 1086 | p.green = "x%s2<n2||y%s2<n2".to_owned(); | |
| 1087 | p.blue = "0\n // trailing comment".to_owned(); | |
| 1088 | p.alpha = "max(r1, g1, b1) * (1 - dist((x-.5)*2, (y-.5)*2, 0, 0))".to_owned(); | |
| 1089 | ||
| 1090 | let wgsl = compile_wgsl(&p, wgpu::TextureFormat::Rgba8Unorm).expect("compile"); | |
| 1091 | assert!(wgsl.contains("safe_div")); | |
| 1092 | assert!(wgsl.contains("fu_pow((2.71828183),")); | |
| 1093 | assert!(wgsl.contains("fu_mod")); | |
| 1094 | assert!(wgsl.contains("select(")); | |
| 1095 | assert!(wgsl.contains("min(") || wgsl.contains("max(")); | |
| 1096 | assert!(wgsl.contains("p1.r")); | |
| 1097 | } | |
| 1098 | ||
| 1099 | #[test] | |
| 1100 | fn compiles_samplers_and_luts() { | |
| 1101 | let mut p = CustomProgram::default(); | |
| 1102 | p.red = "getlut1(getr1b(x + 0.1, y))".to_owned(); | |
| 1103 | p.green = "lut2(getg2w(x, y - 0.25))".to_owned(); | |
| 1104 | p.blue = "getlut3(getb3d(x, y))".to_owned(); | |
| 1105 | p.alpha = "lut4(geta1(x, y))".to_owned(); | |
| 1106 | ||
| 1107 | let wgsl = compile_wgsl(&p, wgpu::TextureFormat::Rgba16Float).expect("compile"); | |
| 1108 | assert!(wgsl.contains("texture_storage_2d<rgba16float, write>")); | |
| 1109 | assert!(wgsl.contains("sample_img(src_1,")); | |
| 1110 | assert!(wgsl.contains("sample_img(src_2,")); | |
| 1111 | assert!(wgsl.contains("sample_img(src_3,")); | |
| 1112 | assert!(wgsl.contains("sample_lut(0u,")); | |
| 1113 | assert!(wgsl.contains("sample_lut(3u,")); | |
| 1114 | } | |
| 1115 | ||
| 1116 | #[test] | |
| 1117 | fn rejects_invalid_syntax_gracefully() { | |
| 1118 | let mut p = CustomProgram::default(); | |
| 1119 | p.red = "unknown_func(r1)".to_owned(); | |
| 1120 | assert!(compile_wgsl(&p, wgpu::TextureFormat::Rgba8Unorm).is_err()); | |
| 1121 | ||
| 1122 | p.red = "r1 + + *".to_owned(); | |
| 1123 | assert!(compile_wgsl(&p, wgpu::TextureFormat::Rgba8Unorm).is_err()); | |
| 1124 | ||
| 1125 | p.red = "totally_unknown_var".to_owned(); | |
| 1126 | assert!(compile_wgsl(&p, wgpu::TextureFormat::Rgba8Unorm).is_err()); | |
| 1127 | } | |
| 1128 | ||
| 1129 | #[test] | |
| 1130 | fn gpu_executes_wave_formula_and_caches_pipeline() { | |
| 1131 | let eng = Engine::new_headless().expect("gpu"); | |
| 1132 | let mut cache = CustomShaderCache::new(); | |
| 1133 | let mut prog = CustomProgram::default(); | |
| 1134 | prog.red = "sin(x*w*n1 + n2*n1*w)*0.5+0.5".to_owned(); | |
| 1135 | prog.green = "sin(y*w*n1 + n2*n1*w)*0.5+0.5".to_owned(); | |
| 1136 | prog.blue = "0\n".to_owned(); | |
| 1137 | prog.alpha = "1".to_owned(); | |
| 1138 | ||
| 1139 | let mut params = CustomParams::default(); | |
| 1140 | params.n0 = [0.7413, 10.655, 0.0, 0.0]; | |
| 1141 | params.img_dims1 = [64.0, 64.0, 64.0, 64.0]; | |
| 1142 | ||
| 1143 | let dummy = create_texture(eng.device(), [1, 1], 0); | |
| 1144 | let dst = create_texture(eng.device(), [64, 64], 1); | |
| 1145 | let mut enc = eng.device().create_command_encoder(&Default::default()); | |
| 1146 | let ok = cache.dispatch( | |
| 1147 | eng.device(), | |
| 1148 | eng.queue(), | |
| 1149 | &mut enc, | |
| 1150 | &prog, | |
| 1151 | wgpu::TextureFormat::Rgba8Unorm, | |
| 1152 | &dummy.view, | |
| 1153 | &dummy.view, | |
| 1154 | &dummy.view, | |
| 1155 | &dummy.view, | |
| 1156 | &dst.view, | |
| 1157 | [64, 64], | |
| 1158 | &params, | |
| 1159 | ); | |
| 1160 | assert!(ok); | |
| 1161 | eng.queue().submit(Some(enc.finish())); | |
| 1162 | assert_eq!(cache.cached_pipeline_count(), 1); | |
| 1163 | ||
| 1164 | // Whitespace-equivalent program hits the exact same cached pipeline! | |
| 1165 | let mut prog2 = prog.clone(); | |
| 1166 | prog2.blue = " 0 ".to_owned(); | |
| 1167 | assert!(cache.ensure_compiled(eng.device(), &prog2, wgpu::TextureFormat::Rgba8Unorm)); | |
| 1168 | assert_eq!(cache.cached_pipeline_count(), 1); | |
| 1169 | ||
| 1170 | let rgba = eng.readback_rgba(&dst).expect("readback"); | |
| 1171 | // Verify pixel (10, 20) against CPU formula | |
| 1172 | let px = 10usize; | |
| 1173 | let py = 20usize; | |
| 1174 | let fu_x = (px as f64 + 0.5) / 64.0; | |
| 1175 | let fu_y = 1.0 - (py as f64 + 0.5) / 64.0; | |
| 1176 | let n1 = 0.7413_f64; | |
| 1177 | let n2 = 10.655_f64; | |
| 1178 | let w = 64.0_f64; | |
| 1179 | let exp_r = ((fu_x * w * n1 + n2 * n1 * w).to_radians().sin() * 0.5 + 0.5) * 255.0; | |
| 1180 | let exp_g = ((fu_y * w * n1 + n2 * n1 * w).to_radians().sin() * 0.5 + 0.5) * 255.0; | |
| 1181 | let idx = (py * 64 + px) * 4; | |
| 1182 | assert!((rgba[idx] as f64 - exp_r).abs() <= 1.5, "r got {} expected {exp_r}", rgba[idx]); | |
| 1183 | assert!((rgba[idx + 1] as f64 - exp_g).abs() <= 1.5, "g got {} expected {exp_g}", rgba[idx + 1]); | |
| 1184 | assert_eq!(rgba[idx + 2], 0); | |
| 1185 | assert_eq!(rgba[idx + 3], 255); | |
| 1186 | } | |
| 1187 | ||
| 1188 | #[test] | |
| 1189 | fn gpu_executes_premul_invert_safe_div_when_alpha_zero() { | |
| 1190 | let eng = Engine::new_headless().expect("gpu"); | |
| 1191 | let mut cache = CustomShaderCache::new(); | |
| 1192 | let mut prog = CustomProgram::default(); | |
| 1193 | prog.intermediates[0] = "a1".to_owned(); | |
| 1194 | prog.red = "(1-r1/a1)*i1".to_owned(); | |
| 1195 | prog.green = "(1-g1/a1)*i1".to_owned(); | |
| 1196 | prog.blue = "(1-b1/a1)*i1".to_owned(); | |
| 1197 | prog.alpha = "i1".to_owned(); | |
| 1198 | ||
| 1199 | // 2x1 input: pixel 0 is transparent black (a1 == 0), pixel 1 is premul (0.2, 0.4, 0.0, 0.5) | |
| 1200 | let src = create_texture(eng.device(), [2, 1], 0); | |
| 1201 | let input_bytes: [u8; 8] = [0, 0, 0, 0, 51, 102, 0, 128]; | |
| 1202 | eng.queue().write_texture( | |
| 1203 | src.texture.as_image_copy(), | |
| 1204 | &input_bytes, | |
| 1205 | wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(8), rows_per_image: Some(1) }, | |
| 1206 | wgpu::Extent3d { width: 2, height: 1, depth_or_array_layers: 1 }, | |
| 1207 | ); | |
| 1208 | let dummy = create_texture(eng.device(), [1, 1], 0); | |
| 1209 | let dst = create_texture(eng.device(), [2, 1], 2); | |
| 1210 | let params = CustomParams { | |
| 1211 | img_dims1: [2.0, 1.0, 1.0, 1.0], | |
| 1212 | ..Default::default() | |
| 1213 | }; | |
| 1214 | ||
| 1215 | let mut enc = eng.device().create_command_encoder(&Default::default()); | |
| 1216 | assert!(cache.dispatch( | |
| 1217 | eng.device(), | |
| 1218 | eng.queue(), | |
| 1219 | &mut enc, | |
| 1220 | &prog, | |
| 1221 | wgpu::TextureFormat::Rgba8Unorm, | |
| 1222 | &src.view, | |
| 1223 | &dummy.view, | |
| 1224 | &dummy.view, | |
| 1225 | &dummy.view, | |
| 1226 | &dst.view, | |
| 1227 | [2, 1], | |
| 1228 | &params, | |
| 1229 | )); | |
| 1230 | eng.queue().submit(Some(enc.finish())); | |
| 1231 | ||
| 1232 | let rgba = eng.readback_rgba(&dst).expect("readback"); | |
| 1233 | // Pixel 0 (a1 == 0): must be clean (0, 0, 0, 0), no NaN! | |
| 1234 | assert_eq!(&rgba[0..4], &[0, 0, 0, 0]); | |
| 1235 | // Pixel 1: straight RGB = (51/128, 102/128, 0) = (0.398, 0.797, 0) | |
| 1236 | // Inverted * a1 = ((1-0.398)*0.502, (1-0.797)*0.502, 1*0.502) * 255 = (77, 26, 128) | |
| 1237 | assert!((rgba[4] as i32 - 77).abs() <= 2, "r={}", rgba[4]); | |
| 1238 | assert!((rgba[5] as i32 - 26).abs() <= 2, "g={}", rgba[5]); | |
| 1239 | assert!((rgba[6] as i32 - 128).abs() <= 2, "b={}", rgba[6]); | |
| 1240 | assert_eq!(rgba[7], 128); | |
| 1241 | } | |
| 1242 | ||
| 1243 | #[test] | |
| 1244 | fn end_to_end_comp_custom_tool_with_lut_and_expression_modifier() { | |
| 1245 | let src = r#"Composition { | |
| 1246 | Prefs = { Comp = { FrameFormat = { Width = 16, Height = 16, Rate = 24 } } }, | |
| 1247 | Tools = ordered() { | |
| 1248 | BG1 = Background { | |
| 1249 | Inputs = { | |
| 1250 | Width = Input { Value = 16, }, | |
| 1251 | Height = Input { Value = 16, }, | |
| 1252 | TopLeftRed = Input { Value = 0.25, }, | |
| 1253 | TopLeftGreen = Input { Value = 0.5, }, | |
| 1254 | TopLeftBlue = Input { Value = 0.75, }, | |
| 1255 | TopLeftAlpha = Input { Value = 1.0, }, | |
| 1256 | }, | |
| 1257 | }, | |
| 1258 | NumExpr = Expression { | |
| 1259 | Inputs = { | |
| 1260 | n1 = Input { Value = 2.0, }, | |
| 1261 | NumberExpression = Input { Value = "n1 * 0.25", }, | |
| 1262 | }, | |
| 1263 | }, | |
| 1264 | CT1LUT1 = LUTBezier { | |
| 1265 | KeyColorSplines = { | |
| 1266 | [0] = { | |
| 1267 | [0] = { 1.0, Flags = { Linear = true } }, | |
| 1268 | [1] = { 0.0, Flags = { Linear = true } }, | |
| 1269 | }, | |
| 1270 | }, | |
| 1271 | }, | |
| 1272 | CT1 = Custom { | |
| 1273 | Inputs = { | |
| 1274 | Image1 = Input { SourceOp = "BG1", Source = "Output", }, | |
| 1275 | NumberIn1 = Input { SourceOp = "NumExpr", Source = "NumberResult", }, | |
| 1276 | LUTIn1 = Input { SourceOp = "CT1LUT1", Source = "Value", }, | |
| 1277 | RedExpression = Input { Value = "lut1(r1)", }, | |
| 1278 | GreenExpression = Input { Value = "g1 * n1", }, | |
| 1279 | BlueExpression = Input { Value = "if(b1 > 0.5, 1, 0)", }, | |
| 1280 | AlphaExpression = Input { Value = "a1", }, | |
| 1281 | }, | |
| 1282 | }, | |
| 1283 | }, | |
| 1284 | }"#; | |
| 1285 | let comp = Comp::from_fusion_str(src).expect("parse"); | |
| 1286 | let mut eng = Engine::new_headless().expect("gpu"); | |
| 1287 | let ct_id = comp.find_node("CT1").unwrap(); | |
| 1288 | let (tex, _) = eng.evaluate(&comp, ct_id, 0.0); | |
| 1289 | let rgba = eng.readback_rgba(&tex).expect("readback"); | |
| 1290 | // r = lut1(0.25) = 0.75 (~191), g = 0.5 * 0.5 = 0.25 (~64), b = 1.0 (255), a = 1.0 (255) | |
| 1291 | assert!((rgba[0] as i32 - 191).abs() <= 2, "r={}", rgba[0]); | |
| 1292 | assert!((rgba[1] as i32 - 64).abs() <= 2, "g={}", rgba[1]); | |
| 1293 | assert_eq!(rgba[2], 255); | |
| 1294 | assert_eq!(rgba[3], 255); | |
| 1295 | } | |
| 1296 | } |
crates/engine/src/eval/color.rs+174-43| ... | ... | @@ -247,54 +247,185 @@ impl Engine { |
| 247 | 247 | visiting: &mut HashSet<(NodeId, i64)>, |
| 248 | 248 | stats: &mut EvalStats, |
| 249 | 249 | ) -> CachedTexture { |
| 250 | let size = if let Some(src_id) = node.connected_node("Image1").and_then(|s| comp.find_node(s)) { | |
| 251 | self.eval_node(comp, src_id, time, enc, visiting, stats).size | |
| 252 | } else { | |
| 253 | comp_dims | |
| 254 | }; | |
| 255 | let n1 = comp.eval_number(node, "NumberIn1", time, 1.0, &self.expr) as f32; | |
| 256 | let n2 = comp.eval_number(node, "NumberIn2", time, 0.0, &self.expr) as f32; | |
| 257 | let red_expr = node.inputs.get("RedExpression").and_then(|b| b.value.as_ref()).and_then(ParamValue::as_str).unwrap_or(""); | |
| 258 | let green_expr = node.inputs.get("GreenExpression").and_then(|b| b.value.as_ref()).and_then(ParamValue::as_str).unwrap_or(""); | |
| 259 | let blue_expr = node.inputs.get("BlueExpression").and_then(|b| b.value.as_ref()).and_then(ParamValue::as_str).unwrap_or(""); | |
| 260 | let wave_mode = |expr: &str| -> f32 { | |
| 261 | if !expr.contains("sin(") { | |
| 262 | 0.0 | |
| 263 | } else if expr.contains("y*w") || expr.contains("y * w") { | |
| 264 | 2.0 | |
| 265 | } else { | |
| 266 | 1.0 | |
| 267 | } | |
| 250 | let img1 = node | |
| 251 | .connected_node("Image1") | |
| 252 | .and_then(|s| comp.find_node(s)) | |
| 253 | .map(|id| { | |
| 254 | let t = self.eval_node(comp, id, time, enc, visiting, stats); | |
| 255 | self.crop_to_canvas(enc, t) | |
| 256 | }); | |
| 257 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; | |
| 258 | if blend <= 1e-6 { | |
| 259 | return img1.unwrap_or_else(|| self.dummy.clone()); | |
| 260 | } | |
| 261 | let img2 = node | |
| 262 | .connected_node("Image2") | |
| 263 | .and_then(|s| comp.find_node(s)) | |
| 264 | .map(|id| { | |
| 265 | let t = self.eval_node(comp, id, time, enc, visiting, stats); | |
| 266 | self.crop_to_canvas(enc, t) | |
| 267 | }); | |
| 268 | let img3 = node | |
| 269 | .connected_node("Image3") | |
| 270 | .and_then(|s| comp.find_node(s)) | |
| 271 | .map(|id| { | |
| 272 | let t = self.eval_node(comp, id, time, enc, visiting, stats); | |
| 273 | self.crop_to_canvas(enc, t) | |
| 274 | }); | |
| 275 | ||
| 276 | let size = img1.as_ref().map_or(comp_dims, |t| t.size); | |
| 277 | let depth = self.node_depth(comp, node, time, img1.as_ref().map(|t| t.depth)); | |
| 278 | let eff_depth = self.effective_depth(depth); | |
| 279 | let (mask, mask_inv) = | |
| 280 | self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats); | |
| 281 | ||
| 282 | let setup_names = ["Setup1", "Setup2", "Setup3", "Setup4"]; | |
| 283 | let inter_names = [ | |
| 284 | ("Intermediate1", "Inter1"), | |
| 285 | ("Intermediate2", "Inter2"), | |
| 286 | ("Intermediate3", "Inter3"), | |
| 287 | ("Intermediate4", "Inter4"), | |
| 288 | ("Intermediate5", "Inter5"), | |
| 289 | ("Intermediate6", "Inter6"), | |
| 290 | ("Intermediate7", "Inter7"), | |
| 291 | ("Intermediate8", "Inter8"), | |
| 292 | ]; | |
| 293 | let program = crate::custom_shader::CustomProgram { | |
| 294 | setups: std::array::from_fn(|i| comp.eval_text(node, setup_names[i], time, "0", &self.expr)), | |
| 295 | intermediates: std::array::from_fn(|i| { | |
| 296 | let (primary, alias) = inter_names[i]; | |
| 297 | if node.inputs.contains_key(primary) { | |
| 298 | comp.eval_text(node, primary, time, "0", &self.expr) | |
| 299 | } else if node.inputs.contains_key(alias) { | |
| 300 | comp.eval_text(node, alias, time, "0", &self.expr) | |
| 301 | } else { | |
| 302 | "0".to_owned() | |
| 303 | } | |
| 304 | }), | |
| 305 | red: comp.eval_text(node, "RedExpression", time, "r1", &self.expr), | |
| 306 | green: comp.eval_text(node, "GreenExpression", time, "g1", &self.expr), | |
| 307 | blue: comp.eval_text(node, "BlueExpression", time, "b1", &self.expr), | |
| 308 | alpha: comp.eval_text(node, "AlphaExpression", time, "a1", &self.expr), | |
| 309 | } | |
| 310 | .normalized(); | |
| 311 | ||
| 312 | let pscale = self.proxy_scale.max(1); | |
| 313 | let w1 = (size[0] * pscale) as f32; | |
| 314 | let h1 = (size[1] * pscale) as f32; | |
| 315 | let (w2, h2) = img2 | |
| 316 | .as_ref() | |
| 317 | .map_or((w1, h1), |t| ((t.size[0] * pscale) as f32, (t.size[1] * pscale) as f32)); | |
| 318 | let (w3, h3) = img3 | |
| 319 | .as_ref() | |
| 320 | .map_or((w1, h1), |t| ((t.size[0] * pscale) as f32, (t.size[1] * pscale) as f32)); | |
| 321 | ||
| 322 | let n = |k: &str| comp.eval_number(node, k, time, 0.0, &self.expr) as f32; | |
| 323 | let pt = |k: &str| { | |
| 324 | let p = comp.eval_point(node, k, time, [0.5, 0.5], &self.expr); | |
| 325 | [p[0] as f32, p[1] as f32] | |
| 268 | 326 | }; |
| 269 | let rm = wave_mode(red_expr); | |
| 270 | let gm = wave_mode(green_expr); | |
| 271 | let bm = wave_mode(blue_expr); | |
| 272 | if rm > 0.5 || gm > 0.5 || bm > 0.5 { | |
| 273 | let mut u = UniformParams::default(); | |
| 274 | // Fusion CustomTool `w` is Image1's full-res pixel width! | |
| 275 | let w_ref = (size[0] * self.proxy_scale.max(1)) as f32; | |
| 276 | u.p[0] = [n1, n2, w_ref, 0.0]; | |
| 277 | u.p[1] = [rm, gm, bm, 1.0]; | |
| 278 | let key = self.make_key(node, "CustomWave", size, &[], bytemuck::cast_slice(&u.p[..2])); | |
| 279 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { | |
| 280 | stats.cache_hits += 1; | |
| 281 | return hit; | |
| 327 | let p1 = pt("PointIn1"); | |
| 328 | let p2 = pt("PointIn2"); | |
| 329 | let p3 = pt("PointIn3"); | |
| 330 | let p4 = pt("PointIn4"); | |
| 331 | ||
| 332 | let lut_names = ["LUTIn1", "LUTIn2", "LUTIn3", "LUTIn4"]; | |
| 333 | let lut_splines: [Option<&model::BezierSpline>; 4] = std::array::from_fn(|idx| { | |
| 334 | node.connected_node(lut_names[idx]) | |
| 335 | .and_then(|s| comp.splines.get(s)) | |
| 336 | .filter(|sp| !sp.keyframes.is_empty()) | |
| 337 | }); | |
| 338 | let mut luts = [[0.0f32; 4]; 256]; | |
| 339 | for (i, slot) in luts.iter_mut().enumerate() { | |
| 340 | let x = i as f64 / 255.0; | |
| 341 | for ch in 0..4 { | |
| 342 | slot[ch] = lut_splines[ch].map_or(x as f32, |sp| sp.eval(x) as f32); | |
| 282 | 343 | } |
| 283 | stats.cache_misses += 1; | |
| 284 | stats.nodes_evaluated += 1; | |
| 285 | let dst = create_texture(&self.device, size, key); | |
| 286 | self.dispatch_op(enc, ShaderOp::CustomWave, &self.dummy.view, &self.dummy.view, &self.dummy.view, &dst, &u); | |
| 287 | self.cache.insert(key, dst.clone(), node.id, frame_i); | |
| 288 | return dst; | |
| 289 | 344 | } |
| 290 | if red_expr.contains("1-r1") || red_expr.contains("1 - r1") { | |
| 291 | return self.eval_invert(comp, node, time, frame_i, enc, visiting, stats); | |
| 345 | let mut lh = DefaultHasher::new(); | |
| 346 | bytemuck::cast_slice::<[f32; 4], u8>(&luts).hash(&mut lh); | |
| 347 | let lut_hash = lh.finish(); | |
| 348 | ||
| 349 | let params = crate::custom_shader::CustomParams { | |
| 350 | n0: [n("NumberIn1"), n("NumberIn2"), n("NumberIn3"), n("NumberIn4")], | |
| 351 | n1: [n("NumberIn5"), n("NumberIn6"), n("NumberIn7"), n("NumberIn8")], | |
| 352 | p0: [p1[0], p1[1], p2[0], p2[1]], | |
| 353 | p1: [p3[0], p3[1], p4[0], p4[1]], | |
| 354 | img_dims1: [w1, h1, w2, h2], | |
| 355 | img_dims2: [w3, h3, time as f32, blend], | |
| 356 | mask_proc: [ | |
| 357 | if mask.is_some() { 1.0 } else { 0.0 }, | |
| 358 | if mask_inv { 1.0 } else { 0.0 }, | |
| 359 | comp.eval_number(node, "ProcessRed", time, 1.0, &self.expr) as f32, | |
| 360 | comp.eval_number(node, "ProcessGreen", time, 1.0, &self.expr) as f32, | |
| 361 | ], | |
| 362 | proc_ba: [ | |
| 363 | comp.eval_number(node, "ProcessBlue", time, 1.0, &self.expr) as f32, | |
| 364 | comp.eval_number(node, "ProcessAlpha", time, 1.0, &self.expr) as f32, | |
| 365 | if eff_depth.is_float() { 1.0 } else { 0.0 }, | |
| 366 | 0.0, | |
| 367 | ], | |
| 368 | luts, | |
| 369 | }; | |
| 370 | ||
| 371 | let prog_hash = program.program_hash(); | |
| 372 | let scalar_slice: [[f32; 4]; 8] = [ | |
| 373 | params.n0, | |
| 374 | params.n1, | |
| 375 | params.p0, | |
| 376 | params.p1, | |
| 377 | params.img_dims1, | |
| 378 | params.img_dims2, | |
| 379 | params.mask_proc, | |
| 380 | params.proc_ba, | |
| 381 | ]; | |
| 382 | let key = self.make_key( | |
| 383 | node, | |
| 384 | "CustomTool", | |
| 385 | size, | |
| 386 | &[ | |
| 387 | img1.as_ref().map_or(0, |t| t.content_hash), | |
| 388 | img2.as_ref().map_or(0, |t| t.content_hash), | |
| 389 | img3.as_ref().map_or(0, |t| t.content_hash), | |
| 390 | mask.as_ref().map_or(0, |m| m.content_hash), | |
| 391 | prog_hash, | |
| 392 | lut_hash, | |
| 393 | eff_depth as u64, | |
| 394 | ], | |
| 395 | bytemuck::cast_slice(&scalar_slice), | |
| 396 | ); | |
| 397 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { | |
| 398 | stats.cache_hits += 1; | |
| 399 | return hit; | |
| 292 | 400 | } |
| 293 | // Fallback: passthrough Image1 | |
| 294 | if let Some(src_id) = node.connected_node("Image1").and_then(|s| comp.find_node(s)) { | |
| 295 | self.eval_node(comp, src_id, time, enc, visiting, stats) | |
| 401 | stats.cache_misses += 1; | |
| 402 | stats.nodes_evaluated += 1; | |
| 403 | ||
| 404 | let dst = self.alloc_tex(size, eff_depth, key); | |
| 405 | let v1 = img1.as_ref().map_or(&self.dummy.view, |t| &t.view); | |
| 406 | let v2 = img2.as_ref().map_or(&self.dummy.view, |t| &t.view); | |
| 407 | let v3 = img3.as_ref().map_or(&self.dummy.view, |t| &t.view); | |
| 408 | let vm = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); | |
| 409 | ||
| 410 | let ok = self.custom_shaders.dispatch( | |
| 411 | &self.device, | |
| 412 | &self.queue, | |
| 413 | enc, | |
| 414 | &program, | |
| 415 | dst.format, | |
| 416 | v1, | |
| 417 | v2, | |
| 418 | v3, | |
| 419 | vm, | |
| 420 | &dst.view, | |
| 421 | dst.size, | |
| 422 | &params, | |
| 423 | ); | |
| 424 | if ok { | |
| 425 | self.cache.insert(key, dst.clone(), node.id, frame_i); | |
| 426 | dst | |
| 296 | 427 | } else { |
| 297 | self.dummy.clone() | |
| 428 | img1.unwrap_or_else(|| self.dummy.clone()) | |
| 298 | 429 | } |
| 299 | 430 | } |
| 300 | 431 |
crates/engine/src/eval/mod.rs+4-1| ... | ... | @@ -4,7 +4,7 @@ |
| 4 | 4 | use crate::cache::{CacheMode, CachedTexture, EvalStats, NodeCache}; |
| 5 | 5 | use crate::media::{MediaCache, TextPlusParams, rasterize_polyline_mask, rasterize_text_plus}; |
| 6 | 6 | use bytemuck::{Pod, Zeroable}; |
| 7 | use model::{BitDepth, Comp, ExprEngine, Node, NodeId, ParamValue, default_main_input_port}; | |
| 7 | use model::{BitDepth, Comp, ExprEngine, Node, NodeId, default_main_input_port}; | |
| 8 | 8 | use std::cell::{OnceCell, RefCell}; |
| 9 | 9 | use std::collections::{HashMap, HashSet}; |
| 10 | 10 | use std::collections::hash_map::DefaultHasher; |
| ... | ... | @@ -118,6 +118,7 @@ enum ShaderOp { |
| 118 | 118 | OutlineTint, |
| 119 | 119 | OutlineComposite, |
| 120 | 120 | TextOutline, |
| 121 | #[allow(dead_code)] | |
| 121 | 122 | CustomWave, |
| 122 | 123 | Crop, |
| 123 | 124 | GlowAdd, |
| ... | ... | @@ -386,6 +387,7 @@ pub struct Engine { |
| 386 | 387 | scene3d: crate::scene3d::Scene3DRenderer, |
| 387 | 388 | optflow: std::sync::OnceLock<crate::optflow::OpticalFlowPipelines>, |
| 388 | 389 | particles: crate::particles::ParticleCache, |
| 390 | custom_shaders: crate::custom_shader::CustomShaderCache, | |
| 389 | 391 | sprite_cache: HashMap<(NodeId, u64, i64), crate::particles::SpriteImage>, |
| 390 | 392 | dummy: CachedTexture, |
| 391 | 393 | pub cache: NodeCache, |
| ... | ... | @@ -435,6 +437,7 @@ impl Engine { |
| 435 | 437 | scene3d, |
| 436 | 438 | optflow: std::sync::OnceLock::new(), |
| 437 | 439 | particles: crate::particles::ParticleCache::default(), |
| 440 | custom_shaders: crate::custom_shader::CustomShaderCache::new(), | |
| 438 | 441 | sprite_cache: HashMap::new(), |
| 439 | 442 | dummy, |
| 440 | 443 | cache: NodeCache::new(crate::cache::DEFAULT_VRAM_BUDGET_MB), |
crates/engine/src/lib.rs+1| ... | ... | @@ -1,6 +1,7 @@ |
| 1 | 1 | pub mod audio; |
| 2 | 2 | pub mod cache; |
| 3 | 3 | pub mod cryptomatte; |
| 4 | pub mod custom_shader; | |
| 4 | 5 | pub mod eval; |
| 5 | 6 | pub mod export; |
| 6 | 7 | pub mod media; |
crates/model/src/comp.rs+799| ... | ... | @@ -351,6 +351,13 @@ pub struct ShakeModifier { |
| 351 | 351 | pub inputs: HashMap<String, InputBinding>, |
| 352 | 352 | } |
| 353 | 353 | |
| 354 | /// Fusion standalone `Expression` modifier (`NumberExpression`, `PointExpressionX`, | |
| 355 | /// `PointExpressionY`, `PointExpression`, `n1..n9` / `NumberIn1..9`, `p1..p9` / `PointIn1..9`). | |
| 356 | #[derive(Clone, Debug, PartialEq)] | |
| 357 | pub struct ExpressionModifier { | |
| 358 | pub inputs: HashMap<String, InputBinding>, | |
| 359 | } | |
| 360 | ||
| 354 | 361 | #[derive(Clone, Debug)] |
| 355 | 362 | pub struct Comp { |
| 356 | 363 | pub path: Option<PathBuf>, |
| ... | ... | @@ -384,6 +391,8 @@ pub struct Comp { |
| 384 | 391 | pub text_cls: HashMap<String, Vec<ClsEntry>>, |
| 385 | 392 | /// Procedural `Shake` modifiers keyed by modifier name (e.g. `"Shake1"`). |
| 386 | 393 | pub shakes: HashMap<String, ShakeModifier>, |
| 394 | /// Standalone `Expression` modifiers keyed by modifier name (e.g. `"Expression1"`). | |
| 395 | pub expression_modifiers: HashMap<String, ExpressionModifier>, | |
| 387 | 396 | /// Preserved raw root `Composition { ... }` Lua AST for lossless `.comp` roundtrip. |
| 388 | 397 | pub raw_root: Option<LuaTable>, |
| 389 | 398 | /// Generation counter incremented whenever any node, wire, or spline mutates. |
| ... | ... | @@ -487,6 +496,7 @@ impl Comp { |
| 487 | 496 | let mut polyline_splines = HashMap::new(); |
| 488 | 497 | let mut text_cls = HashMap::new(); |
| 489 | 498 | let mut shakes = HashMap::new(); |
| 499 | let mut expression_modifiers = HashMap::new(); | |
| 490 | 500 | let mut tracker_aliases: Vec<(String, String)> = Vec::new(); |
| 491 | 501 | let mut macro_defaults: Vec<(String, String, ParamValue)> = Vec::new(); |
| 492 | 502 | let mut instanced_from: Vec<(NodeId, String)> = Vec::new(); |
| ... | ... | @@ -505,6 +515,7 @@ impl Comp { |
| 505 | 515 | &mut polyline_splines, |
| 506 | 516 | &mut text_cls, |
| 507 | 517 | &mut shakes, |
| 518 | &mut expression_modifiers, | |
| 508 | 519 | &mut tracker_aliases, |
| 509 | 520 | &mut macro_defaults, |
| 510 | 521 | &mut instanced_from, |
| ... | ... | @@ -629,6 +640,7 @@ impl Comp { |
| 629 | 640 | polyline_splines, |
| 630 | 641 | text_cls, |
| 631 | 642 | shakes, |
| 643 | expression_modifiers, | |
| 632 | 644 | raw_root: Some(root.clone()), |
| 633 | 645 | revision: 1, |
| 634 | 646 | }) |
| ... | ... | @@ -773,6 +785,19 @@ impl Comp { |
| 773 | 785 | }; |
| 774 | 786 | return self.eval_shake_axis(sh, axis, time, expr_engine); |
| 775 | 787 | } |
| 788 | if let Some(em) = self.expression_modifiers.get(src) { | |
| 789 | if let Some(v) = self.eval_expr_mod_number( | |
| 790 | em, | |
| 791 | binding.source_output.as_deref(), | |
| 792 | time, | |
| 793 | expr_engine, | |
| 794 | 0, | |
| 795 | ) { | |
| 796 | if v.is_finite() { | |
| 797 | return v; | |
| 798 | } | |
| 799 | } | |
| 800 | } | |
| 776 | 801 | } |
| 777 | 802 | binding |
| 778 | 803 | .value |
| ... | ... | @@ -813,6 +838,13 @@ impl Comp { |
| 813 | 838 | let y = self.eval_shake_axis(sh, 1, time, expr_engine); |
| 814 | 839 | return [x, y]; |
| 815 | 840 | } |
| 841 | if let Some(em) = self.expression_modifiers.get(src) { | |
| 842 | if let Some(pt) = self.eval_expr_mod_point(em, time, expr_engine, 0) { | |
| 843 | if pt[0].is_finite() && pt[1].is_finite() { | |
| 844 | return pt; | |
| 845 | } | |
| 846 | } | |
| 847 | } | |
| 816 | 848 | } |
| 817 | 849 | binding |
| 818 | 850 | .value |
| ... | ... | @@ -897,6 +929,299 @@ impl Comp { |
| 897 | 929 | min_v + (max_v - min_v) * t01 |
| 898 | 930 | } |
| 899 | 931 | |
| 932 | fn eval_expr_mod_input_number( | |
| 933 | &self, | |
| 934 | em: &ExpressionModifier, | |
| 935 | keys: &[&str], | |
| 936 | time: f64, | |
| 937 | default: f64, | |
| 938 | expr_engine: &ExprEngine, | |
| 939 | depth: u8, | |
| 940 | ) -> f64 { | |
| 941 | let Some(b) = keys.iter().find_map(|k| em.inputs.get(*k)) else { | |
| 942 | return default; | |
| 943 | }; | |
| 944 | if let Some(expr) = &b.expression { | |
| 945 | if let Some(v) = self.eval_modifier_inline_number(expr, time, expr_engine) { | |
| 946 | if v.is_finite() { | |
| 947 | return v; | |
| 948 | } | |
| 949 | } | |
| 950 | } | |
| 951 | if let Some(src) = &b.source_op { | |
| 952 | if let Some(spl) = self.splines.get(src) { | |
| 953 | return spl.eval(time); | |
| 954 | } | |
| 955 | if let Some(sh) = self.shakes.get(src) { | |
| 956 | let axis = match b.source_output.as_deref() { | |
| 957 | Some("Y") => 1, | |
| 958 | _ => 0, | |
| 959 | }; | |
| 960 | return self.eval_shake_axis(sh, axis, time, expr_engine); | |
| 961 | } | |
| 962 | if depth < 8 { | |
| 963 | if let Some(sub) = self.expression_modifiers.get(src) { | |
| 964 | if let Some(v) = self.eval_expr_mod_number( | |
| 965 | sub, | |
| 966 | b.source_output.as_deref(), | |
| 967 | time, | |
| 968 | expr_engine, | |
| 969 | depth + 1, | |
| 970 | ) { | |
| 971 | if v.is_finite() { | |
| 972 | return v; | |
| 973 | } | |
| 974 | } | |
| 975 | } | |
| 976 | } | |
| 977 | } | |
| 978 | b.value.as_ref().and_then(ParamValue::as_f64).unwrap_or(default) | |
| 979 | } | |
| 980 | ||
| 981 | fn eval_expr_mod_input_point( | |
| 982 | &self, | |
| 983 | em: &ExpressionModifier, | |
| 984 | keys: &[&str], | |
| 985 | time: f64, | |
| 986 | default: [f64; 2], | |
| 987 | expr_engine: &ExprEngine, | |
| 988 | depth: u8, | |
| 989 | ) -> [f64; 2] { | |
| 990 | let Some(b) = keys.iter().find_map(|k| em.inputs.get(*k)) else { | |
| 991 | return default; | |
| 992 | }; | |
| 993 | if let Some(expr) = &b.expression { | |
| 994 | let trimmed = expr.trim(); | |
| 995 | // Direct `NodeName.ParamName` reference to a Point input on another flow node. | |
| 996 | if let Some((node_name, param_name)) = trimmed.split_once('.') { | |
| 997 | if !param_name.contains('.') && !param_name.contains(' ') { | |
| 998 | if let Some(nid) = self.find_node(node_name.trim()) { | |
| 999 | return self.eval_point(self.node(nid), param_name.trim(), time, default, expr_engine); | |
| 1000 | } | |
| 1001 | } | |
| 1002 | } | |
| 1003 | let (sp, spts, en) = self.collect_global_expr_env(time); | |
| 1004 | if let Some(pt) = expr_engine.eval_point(trimmed, time, &sp, &spts, &en) { | |
| 1005 | if pt[0].is_finite() && pt[1].is_finite() { | |
| 1006 | return pt; | |
| 1007 | } | |
| 1008 | } | |
| 1009 | } | |
| 1010 | if let Some(src) = &b.source_op { | |
| 1011 | if let Some(pp) = self.poly_paths.get(src) { | |
| 1012 | let disp = pp | |
| 1013 | .displacement_op | |
| 1014 | .as_deref() | |
| 1015 | .and_then(|d| self.splines.get(d)) | |
| 1016 | .map(|sp| sp.eval(time)) | |
| 1017 | .unwrap_or(pp.displacement_value); | |
| 1018 | return pp.eval_center(disp); | |
| 1019 | } | |
| 1020 | if let Some(sh) = self.shakes.get(src) { | |
| 1021 | let x = self.eval_shake_axis(sh, 0, time, expr_engine); | |
| 1022 | let y = self.eval_shake_axis(sh, 1, time, expr_engine); | |
| 1023 | return [x, y]; | |
| 1024 | } | |
| 1025 | if depth < 8 { | |
| 1026 | if let Some(sub) = self.expression_modifiers.get(src) { | |
| 1027 | if let Some(pt) = self.eval_expr_mod_point(sub, time, expr_engine, depth + 1) { | |
| 1028 | if pt[0].is_finite() && pt[1].is_finite() { | |
| 1029 | return pt; | |
| 1030 | } | |
| 1031 | } | |
| 1032 | } | |
| 1033 | } | |
| 1034 | } | |
| 1035 | b.value.as_ref().and_then(ParamValue::as_point).unwrap_or(default) | |
| 1036 | } | |
| 1037 | ||
| 1038 | fn eval_modifier_inline_number( | |
| 1039 | &self, | |
| 1040 | expr: &str, | |
| 1041 | time: f64, | |
| 1042 | expr_engine: &ExprEngine, | |
| 1043 | ) -> Option<f64> { | |
| 1044 | let trimmed = expr.trim(); | |
| 1045 | if let Some((node_name, param_name)) = trimmed.split_once('.') { | |
| 1046 | if !param_name.contains('.') && !param_name.contains(' ') && !param_name.contains('(') { | |
| 1047 | if let Some(nid) = self.find_node(node_name.trim()) { | |
| 1048 | return Some(self.eval_number(self.node(nid), param_name.trim(), time, 0.0, expr_engine)); | |
| 1049 | } | |
| 1050 | } | |
| 1051 | } | |
| 1052 | let (sp, spts, en) = self.collect_global_expr_env(time); | |
| 1053 | expr_engine.eval_number(trimmed, time, &sp, &spts, &en) | |
| 1054 | } | |
| 1055 | ||
| 1056 | fn collect_global_expr_env( | |
| 1057 | &self, | |
| 1058 | time: f64, | |
| 1059 | ) -> ( | |
| 1060 | HashMap<String, f64>, | |
| 1061 | HashMap<String, [f64; 2]>, | |
| 1062 | HashMap<String, HashMap<String, f64>>, | |
| 1063 | ) { | |
| 1064 | let mut env_nodes = HashMap::new(); | |
| 1065 | for n in &self.nodes { | |
| 1066 | let mut m = HashMap::new(); | |
| 1067 | for (k, b) in &n.inputs { | |
| 1068 | if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) { | |
| 1069 | m.insert(k.clone(), v); | |
| 1070 | } else if let Some(src) = &b.source_op { | |
| 1071 | if let Some(sp) = self.splines.get(src) { | |
| 1072 | m.insert(k.clone(), sp.eval(time)); | |
| 1073 | } | |
| 1074 | } | |
| 1075 | } | |
| 1076 | if !m.is_empty() { | |
| 1077 | env_nodes.insert(n.name.clone(), m); | |
| 1078 | } | |
| 1079 | } | |
| 1080 | (HashMap::new(), HashMap::new(), env_nodes) | |
| 1081 | } | |
| 1082 | ||
| 1083 | fn build_expr_mod_vars( | |
| 1084 | &self, | |
| 1085 | em: &ExpressionModifier, | |
| 1086 | time: f64, | |
| 1087 | expr_engine: &ExprEngine, | |
| 1088 | depth: u8, | |
| 1089 | ) -> (HashMap<String, f64>, HashMap<String, [f64; 2]>) { | |
| 1090 | let mut vars = HashMap::with_capacity(32); | |
| 1091 | let mut pts = HashMap::with_capacity(18); | |
| 1092 | vars.insert("time".to_owned(), time); | |
| 1093 | vars.insert("pi".to_owned(), std::f64::consts::PI); | |
| 1094 | vars.insert("e".to_owned(), std::f64::consts::E); | |
| 1095 | ||
| 1096 | for i in 1..=9 { | |
| 1097 | let short = format!("n{i}"); | |
| 1098 | let long = format!("NumberIn{i}"); | |
| 1099 | let v = self.eval_expr_mod_input_number( | |
| 1100 | em, | |
| 1101 | &[short.as_str(), long.as_str()], | |
| 1102 | time, | |
| 1103 | 0.0, | |
| 1104 | expr_engine, | |
| 1105 | depth, | |
| 1106 | ); | |
| 1107 | vars.insert(short, v); | |
| 1108 | vars.insert(long, v); | |
| 1109 | } | |
| 1110 | for i in 1..=9 { | |
| 1111 | let short = format!("p{i}"); | |
| 1112 | let long = format!("PointIn{i}"); | |
| 1113 | let pt = self.eval_expr_mod_input_point( | |
| 1114 | em, | |
| 1115 | &[short.as_str(), long.as_str()], | |
| 1116 | time, | |
| 1117 | [0.5, 0.5], | |
| 1118 | expr_engine, | |
| 1119 | depth, | |
| 1120 | ); | |
| 1121 | vars.insert(format!("p{i}x"), pt[0]); | |
| 1122 | vars.insert(format!("p{i}y"), pt[1]); | |
| 1123 | pts.insert(short, pt); | |
| 1124 | pts.insert(long, pt); | |
| 1125 | } | |
| 1126 | for (k, b) in &em.inputs { | |
| 1127 | if !vars.contains_key(k) { | |
| 1128 | if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) { | |
| 1129 | vars.insert(k.clone(), v); | |
| 1130 | } | |
| 1131 | } | |
| 1132 | } | |
| 1133 | (vars, pts) | |
| 1134 | } | |
| 1135 | ||
| 1136 | fn eval_expr_mod_formula( | |
| 1137 | &self, | |
| 1138 | formula: &str, | |
| 1139 | time: f64, | |
| 1140 | vars: &HashMap<String, f64>, | |
| 1141 | pts: &HashMap<String, [f64; 2]>, | |
| 1142 | expr_engine: &ExprEngine, | |
| 1143 | ) -> Option<f64> { | |
| 1144 | let trimmed = formula.trim(); | |
| 1145 | if trimmed.is_empty() { | |
| 1146 | return None; | |
| 1147 | } | |
| 1148 | if let Some(v) = eval_fusion_math_expr(trimmed, vars) { | |
| 1149 | return Some(v); | |
| 1150 | } | |
| 1151 | // Fallback to Lua SimpleExpression engine for Lua-specific formulas | |
| 1152 | let (_, _, en) = self.collect_global_expr_env(time); | |
| 1153 | expr_engine.eval_number(trimmed, time, vars, pts, &en) | |
| 1154 | } | |
| 1155 | ||
| 1156 | fn eval_expr_mod_number( | |
| 1157 | &self, | |
| 1158 | em: &ExpressionModifier, | |
| 1159 | source_output: Option<&str>, | |
| 1160 | time: f64, | |
| 1161 | expr_engine: &ExprEngine, | |
| 1162 | depth: u8, | |
| 1163 | ) -> Option<f64> { | |
| 1164 | if depth >= 8 { | |
| 1165 | return None; | |
| 1166 | } | |
| 1167 | let (vars, pts) = self.build_expr_mod_vars(em, time, expr_engine, depth); | |
| 1168 | let key = match source_output { | |
| 1169 | Some("X") => "PointExpressionX", | |
| 1170 | Some("Y") => "PointExpressionY", | |
| 1171 | _ => "NumberExpression", | |
| 1172 | }; | |
| 1173 | let formula = em | |
| 1174 | .inputs | |
| 1175 | .get(key) | |
| 1176 | .and_then(|b| b.value.as_ref()) | |
| 1177 | .and_then(ParamValue::as_str)?; | |
| 1178 | self.eval_expr_mod_formula(formula, time, &vars, &pts, expr_engine) | |
| 1179 | } | |
| 1180 | ||
| 1181 | fn eval_expr_mod_point( | |
| 1182 | &self, | |
| 1183 | em: &ExpressionModifier, | |
| 1184 | time: f64, | |
| 1185 | expr_engine: &ExprEngine, | |
| 1186 | depth: u8, | |
| 1187 | ) -> Option<[f64; 2]> { | |
| 1188 | if depth >= 8 { | |
| 1189 | return None; | |
| 1190 | } | |
| 1191 | let (vars, pts) = self.build_expr_mod_vars(em, time, expr_engine, depth); | |
| 1192 | let fx = em | |
| 1193 | .inputs | |
| 1194 | .get("PointExpressionX") | |
| 1195 | .and_then(|b| b.value.as_ref()) | |
| 1196 | .and_then(ParamValue::as_str); | |
| 1197 | let fy = em | |
| 1198 | .inputs | |
| 1199 | .get("PointExpressionY") | |
| 1200 | .and_then(|b| b.value.as_ref()) | |
| 1201 | .and_then(ParamValue::as_str); | |
| 1202 | if fx.is_some() || fy.is_some() { | |
| 1203 | let x = fx | |
| 1204 | .and_then(|s| self.eval_expr_mod_formula(s, time, &vars, &pts, expr_engine)) | |
| 1205 | .unwrap_or(0.5); | |
| 1206 | let y = fy | |
| 1207 | .and_then(|s| self.eval_expr_mod_formula(s, time, &vars, &pts, expr_engine)) | |
| 1208 | .unwrap_or(0.5); | |
| 1209 | return Some([x, y]); | |
| 1210 | } | |
| 1211 | if let Some(fp) = em | |
| 1212 | .inputs | |
| 1213 | .get("PointExpression") | |
| 1214 | .and_then(|b| b.value.as_ref()) | |
| 1215 | .and_then(ParamValue::as_str) | |
| 1216 | { | |
| 1217 | let (_, _, en) = self.collect_global_expr_env(time); | |
| 1218 | if let Some(pt) = expr_engine.eval_point(fp, time, &vars, &pts, &en) { | |
| 1219 | return Some(pt); | |
| 1220 | } | |
| 1221 | } | |
| 1222 | None | |
| 1223 | } | |
| 1224 | ||
| 900 | 1225 | pub fn eval_text( |
| 901 | 1226 | &self, |
| 902 | 1227 | node: &Node, |
| ... | ... | @@ -1782,6 +2107,7 @@ fn parse_tools_table( |
| 1782 | 2107 | polyline_splines: &mut HashMap<String, (BezierSpline, Vec<(f64, Vec<crate::spline::PolyPoint>)>)>, |
| 1783 | 2108 | text_cls: &mut HashMap<String, Vec<ClsEntry>>, |
| 1784 | 2109 | shakes: &mut HashMap<String, ShakeModifier>, |
| 2110 | expression_modifiers: &mut HashMap<String, ExpressionModifier>, | |
| 1785 | 2111 | tracker_aliases: &mut Vec<(String, String)>, |
| 1786 | 2112 | macro_defaults: &mut Vec<(String, String, ParamValue)>, |
| 1787 | 2113 | instanced_from: &mut Vec<(NodeId, String)>, |
| ... | ... | @@ -1888,6 +2214,40 @@ fn parse_tools_table( |
| 1888 | 2214 | shakes.insert(name.clone(), ShakeModifier { inputs }); |
| 1889 | 2215 | continue; |
| 1890 | 2216 | } |
| 2217 | if kind == "Expression" { | |
| 2218 | let mut inputs = HashMap::new(); | |
| 2219 | if let Some(in_tbl) = tbl.get_table("Inputs") { | |
| 2220 | for (ik, iv) in &in_tbl.entries { | |
| 2221 | let LuaKey::Str(in_name) = ik else { continue }; | |
| 2222 | let Some(it) = iv.as_table() else { continue }; | |
| 2223 | inputs.insert(in_name.clone(), parse_input_binding(it)); | |
| 2224 | } | |
| 2225 | } | |
| 2226 | if let Some(uc) = tbl.get_table("UserControls") { | |
| 2227 | for (uk, uv) in &uc.entries { | |
| 2228 | let LuaKey::Str(uname) = uk else { continue }; | |
| 2229 | let Some(ut) = uv.as_table() else { continue }; | |
| 2230 | let missing = inputs.get(uname).is_none_or(|b| { | |
| 2231 | b.value.is_none() && b.source_op.is_none() && b.expression.is_none() | |
| 2232 | }); | |
| 2233 | if missing { | |
| 2234 | if let Some(val) = ut.get("INP_Default").map(parse_param_value) { | |
| 2235 | inputs.insert( | |
| 2236 | uname.clone(), | |
| 2237 | InputBinding { | |
| 2238 | value: Some(val), | |
| 2239 | source_op: None, | |
| 2240 | source_output: None, | |
| 2241 | expression: None, | |
| 2242 | }, | |
| 2243 | ); | |
| 2244 | } | |
| 2245 | } | |
| 2246 | } | |
| 2247 | } | |
| 2248 | expression_modifiers.insert(name.clone(), ExpressionModifier { inputs }); | |
| 2249 | continue; | |
| 2250 | } | |
| 1891 | 2251 | if is_modifier_type(&kind) { |
| 1892 | 2252 | if tbl.get_table("KeyFrames").is_some() { |
| 1893 | 2253 | splines.insert(name.clone(), BezierSpline::from_lua(name.clone(), tbl)); |
| ... | ... | @@ -2018,6 +2378,7 @@ fn parse_tools_table( |
| 2018 | 2378 | polyline_splines, |
| 2019 | 2379 | text_cls, |
| 2020 | 2380 | shakes, |
| 2381 | expression_modifiers, | |
| 2021 | 2382 | tracker_aliases, |
| 2022 | 2383 | macro_defaults, |
| 2023 | 2384 | instanced_from, |
| ... | ... | @@ -2053,6 +2414,7 @@ fn parse_tools_table( |
| 2053 | 2414 | polyline_splines, |
| 2054 | 2415 | text_cls, |
| 2055 | 2416 | shakes, |
| 2417 | expression_modifiers, | |
| 2056 | 2418 | tracker_aliases, |
| 2057 | 2419 | macro_defaults, |
| 2058 | 2420 | instanced_from, |
| ... | ... | @@ -2089,3 +2451,440 @@ fn parse_tools_table( |
| 2089 | 2451 | }); |
| 2090 | 2452 | } |
| 2091 | 2453 | } |
| 2454 | ||
| 2455 | /// Evaluates a Fusion `Expression` modifier math formula (C-like Fusion math DSL) to an `f64`. | |
| 2456 | /// Returns `None` if syntax is not recognized so callers can fall back to Lua `ExprEngine`. | |
| 2457 | fn eval_fusion_math_expr(src: &str, vars: &HashMap<String, f64>) -> Option<f64> { | |
| 2458 | struct Parser<'a> { | |
| 2459 | bytes: &'a [u8], | |
| 2460 | pos: usize, | |
| 2461 | vars: &'a HashMap<String, f64>, | |
| 2462 | } | |
| 2463 | ||
| 2464 | impl<'a> Parser<'a> { | |
| 2465 | fn skip_ws(&mut self) { | |
| 2466 | while self.pos < self.bytes.len() { | |
| 2467 | let b = self.bytes[self.pos]; | |
| 2468 | if b.is_ascii_whitespace() { | |
| 2469 | self.pos += 1; | |
| 2470 | } else if b == b'/' && self.bytes.get(self.pos + 1) == Some(&b'/') { | |
| 2471 | while self.pos < self.bytes.len() && self.bytes[self.pos] != b'\n' { | |
| 2472 | self.pos += 1; | |
| 2473 | } | |
| 2474 | } else { | |
| 2475 | break; | |
| 2476 | } | |
| 2477 | } | |
| 2478 | } | |
| 2479 | ||
| 2480 | fn peek(&mut self) -> Option<u8> { | |
| 2481 | self.skip_ws(); | |
| 2482 | self.bytes.get(self.pos).copied() | |
| 2483 | } | |
| 2484 | ||
| 2485 | fn eat_str(&mut self, s: &str) -> bool { | |
| 2486 | self.skip_ws(); | |
| 2487 | if self.bytes[self.pos..].starts_with(s.as_bytes()) { | |
| 2488 | self.pos += s.len(); | |
| 2489 | true | |
| 2490 | } else { | |
| 2491 | false | |
| 2492 | } | |
| 2493 | } | |
| 2494 | ||
| 2495 | fn parse_or(&mut self) -> Option<f64> { | |
| 2496 | let mut v = self.parse_and()?; | |
| 2497 | loop { | |
| 2498 | self.skip_ws(); | |
| 2499 | if self.eat_str("||") || self.eat_str("|") { | |
| 2500 | let r = self.parse_and()?; | |
| 2501 | v = if v != 0.0 || r != 0.0 { 1.0 } else { 0.0 }; | |
| 2502 | } else { | |
| 2503 | break; | |
| 2504 | } | |
| 2505 | } | |
| 2506 | Some(v) | |
| 2507 | } | |
| 2508 | ||
| 2509 | fn parse_and(&mut self) -> Option<f64> { | |
| 2510 | let mut v = self.parse_cmp()?; | |
| 2511 | loop { | |
| 2512 | self.skip_ws(); | |
| 2513 | if self.eat_str("&&") || self.eat_str("&") { | |
| 2514 | let r = self.parse_cmp()?; | |
| 2515 | v = if v != 0.0 && r != 0.0 { 1.0 } else { 0.0 }; | |
| 2516 | } else { | |
| 2517 | break; | |
| 2518 | } | |
| 2519 | } | |
| 2520 | Some(v) | |
| 2521 | } | |
| 2522 | ||
| 2523 | fn parse_cmp(&mut self) -> Option<f64> { | |
| 2524 | let mut v = self.parse_add()?; | |
| 2525 | loop { | |
| 2526 | self.skip_ws(); | |
| 2527 | if self.eat_str("<=") { | |
| 2528 | let r = self.parse_add()?; | |
| 2529 | v = if v <= r { 1.0 } else { 0.0 }; | |
| 2530 | } else if self.eat_str(">=") { | |
| 2531 | let r = self.parse_add()?; | |
| 2532 | v = if v >= r { 1.0 } else { 0.0 }; | |
| 2533 | } else if self.eat_str("==") || self.eat_str("=") { | |
| 2534 | let r = self.parse_add()?; | |
| 2535 | v = if (v - r).abs() <= 1e-12 { 1.0 } else { 0.0 }; | |
| 2536 | } else if self.eat_str("!=") || self.eat_str("~=") || self.eat_str("<>") { | |
| 2537 | let r = self.parse_add()?; | |
| 2538 | v = if (v - r).abs() > 1e-12 { 1.0 } else { 0.0 }; | |
| 2539 | } else if self.eat_str("<") { | |
| 2540 | let r = self.parse_add()?; | |
| 2541 | v = if v < r { 1.0 } else { 0.0 }; | |
| 2542 | } else if self.eat_str(">") { | |
| 2543 | let r = self.parse_add()?; | |
| 2544 | v = if v > r { 1.0 } else { 0.0 }; | |
| 2545 | } else { | |
| 2546 | break; | |
| 2547 | } | |
| 2548 | } | |
| 2549 | Some(v) | |
| 2550 | } | |
| 2551 | ||
| 2552 | fn parse_add(&mut self) -> Option<f64> { | |
| 2553 | let mut v = self.parse_mul()?; | |
| 2554 | loop { | |
| 2555 | match self.peek() { | |
| 2556 | Some(b'+') => { | |
| 2557 | self.pos += 1; | |
| 2558 | v += self.parse_mul()?; | |
| 2559 | } | |
| 2560 | Some(b'-') => { | |
| 2561 | self.pos += 1; | |
| 2562 | v -= self.parse_mul()?; | |
| 2563 | } | |
| 2564 | _ => break, | |
| 2565 | } | |
| 2566 | } | |
| 2567 | Some(v) | |
| 2568 | } | |
| 2569 | ||
| 2570 | fn parse_mul(&mut self) -> Option<f64> { | |
| 2571 | let mut v = self.parse_pow()?; | |
| 2572 | loop { | |
| 2573 | match self.peek() { | |
| 2574 | Some(b'*') => { | |
| 2575 | self.pos += 1; | |
| 2576 | v *= self.parse_pow()?; | |
| 2577 | } | |
| 2578 | Some(b'/') => { | |
| 2579 | self.pos += 1; | |
| 2580 | let r = self.parse_pow()?; | |
| 2581 | v = if r.abs() < 1e-12 { 0.0 } else { v / r }; | |
| 2582 | } | |
| 2583 | Some(b'%') => { | |
| 2584 | self.pos += 1; | |
| 2585 | let r = self.parse_pow()?; | |
| 2586 | v = if r.abs() < 1e-12 { 0.0 } else { v - r * (v / r).floor() }; | |
| 2587 | } | |
| 2588 | _ => break, | |
| 2589 | } | |
| 2590 | } | |
| 2591 | Some(v) | |
| 2592 | } | |
| 2593 | ||
| 2594 | fn parse_pow(&mut self) -> Option<f64> { | |
| 2595 | let base = self.parse_unary()?; | |
| 2596 | if self.peek() == Some(b'^') { | |
| 2597 | self.pos += 1; | |
| 2598 | let exp = self.parse_pow()?; | |
| 2599 | Some(if base > 0.0 { | |
| 2600 | base.powf(exp) | |
| 2601 | } else if base == 0.0 { | |
| 2602 | if exp == 0.0 { 1.0 } else { 0.0 } | |
| 2603 | } else if (exp - exp.round()).abs() < 1e-6 { | |
| 2604 | let p = base.abs().powf(exp); | |
| 2605 | if (exp.round() as i64) & 1 != 0 { -p } else { p } | |
| 2606 | } else { | |
| 2607 | 0.0 | |
| 2608 | }) | |
| 2609 | } else { | |
| 2610 | Some(base) | |
| 2611 | } | |
| 2612 | } | |
| 2613 | ||
| 2614 | fn parse_unary(&mut self) -> Option<f64> { | |
| 2615 | match self.peek() { | |
| 2616 | Some(b'-') => { | |
| 2617 | self.pos += 1; | |
| 2618 | Some(-self.parse_unary()?) | |
| 2619 | } | |
| 2620 | Some(b'+') => { | |
| 2621 | self.pos += 1; | |
| 2622 | self.parse_unary() | |
| 2623 | } | |
| 2624 | Some(b'!') => { | |
| 2625 | self.pos += 1; | |
| 2626 | let v = self.parse_unary()?; | |
| 2627 | Some(if v == 0.0 { 1.0 } else { 0.0 }) | |
| 2628 | } | |
| 2629 | _ => self.parse_primary(), | |
| 2630 | } | |
| 2631 | } | |
| 2632 | ||
| 2633 | fn parse_primary(&mut self) -> Option<f64> { | |
| 2634 | let b = self.peek()?; | |
| 2635 | if b == b'(' { | |
| 2636 | self.pos += 1; | |
| 2637 | let v = self.parse_or()?; | |
| 2638 | if self.peek() != Some(b')') { | |
| 2639 | return None; | |
| 2640 | } | |
| 2641 | self.pos += 1; | |
| 2642 | return Some(v); | |
| 2643 | } | |
| 2644 | if b.is_ascii_digit() || b == b'.' { | |
| 2645 | let start = self.pos; | |
| 2646 | while self.pos < self.bytes.len() && self.bytes[self.pos].is_ascii_digit() { | |
| 2647 | self.pos += 1; | |
| 2648 | } | |
| 2649 | if self.bytes.get(self.pos) == Some(&b'.') { | |
| 2650 | self.pos += 1; | |
| 2651 | while self.pos < self.bytes.len() && self.bytes[self.pos].is_ascii_digit() { | |
| 2652 | self.pos += 1; | |
| 2653 | } | |
| 2654 | } | |
| 2655 | if matches!(self.bytes.get(self.pos), Some(b'e' | b'E')) { | |
| 2656 | let exp_pos = self.pos; | |
| 2657 | self.pos += 1; | |
| 2658 | if matches!(self.bytes.get(self.pos), Some(b'+' | b'-')) { | |
| 2659 | self.pos += 1; | |
| 2660 | } | |
| 2661 | let dig_start = self.pos; | |
| 2662 | while self.pos < self.bytes.len() && self.bytes[self.pos].is_ascii_digit() { | |
| 2663 | self.pos += 1; | |
| 2664 | } | |
| 2665 | if self.pos == dig_start { | |
| 2666 | self.pos = exp_pos; | |
| 2667 | } | |
| 2668 | } | |
| 2669 | let s = std::str::from_utf8(&self.bytes[start..self.pos]).ok()?; | |
| 2670 | return s.parse::<f64>().ok(); | |
| 2671 | } | |
| 2672 | if b.is_ascii_alphabetic() || b == b'_' { | |
| 2673 | let start = self.pos; | |
| 2674 | while self.pos < self.bytes.len() | |
| 2675 | && (self.bytes[self.pos].is_ascii_alphanumeric() || self.bytes[self.pos] == b'_') | |
| 2676 | { | |
| 2677 | self.pos += 1; | |
| 2678 | } | |
| 2679 | let ident = std::str::from_utf8(&self.bytes[start..self.pos]).ok()?; | |
| 2680 | if self.peek() == Some(b'(') { | |
| 2681 | self.pos += 1; | |
| 2682 | let mut args = Vec::new(); | |
| 2683 | if self.peek() != Some(b')') { | |
| 2684 | loop { | |
| 2685 | args.push(self.parse_or()?); | |
| 2686 | if self.peek() == Some(b',') { | |
| 2687 | self.pos += 1; | |
| 2688 | } else { | |
| 2689 | break; | |
| 2690 | } | |
| 2691 | } | |
| 2692 | } | |
| 2693 | if self.peek() != Some(b')') { | |
| 2694 | return None; | |
| 2695 | } | |
| 2696 | self.pos += 1; | |
| 2697 | return Self::eval_fn(ident, &args); | |
| 2698 | } | |
| 2699 | return self.vars.get(ident).copied(); | |
| 2700 | } | |
| 2701 | None | |
| 2702 | } | |
| 2703 | ||
| 2704 | fn eval_fn(name: &str, args: &[f64]) -> Option<f64> { | |
| 2705 | const DEG2RAD: f64 = std::f64::consts::PI / 180.0; | |
| 2706 | const RAD2DEG: f64 = 180.0 / std::f64::consts::PI; | |
| 2707 | let a = |i: usize| args.get(i).copied(); | |
| 2708 | Some(match name { | |
| 2709 | "sin" => (a(0)? * DEG2RAD).sin(), | |
| 2710 | "cos" => (a(0)? * DEG2RAD).cos(), | |
| 2711 | "tan" => (a(0)? * DEG2RAD).tan(), | |
| 2712 | "asin" => a(0)?.clamp(-1.0, 1.0).asin() * RAD2DEG, | |
| 2713 | "acos" => a(0)?.clamp(-1.0, 1.0).acos() * RAD2DEG, | |
| 2714 | "atan" => a(0)?.atan() * RAD2DEG, | |
| 2715 | "atan2" => a(0)?.atan2(a(1)?) * RAD2DEG, | |
| 2716 | "sinr" => a(0)?.sin(), | |
| 2717 | "cosr" => a(0)?.cos(), | |
| 2718 | "tanr" => a(0)?.tan(), | |
| 2719 | "asinr" => a(0)?.clamp(-1.0, 1.0).asin(), | |
| 2720 | "acosr" => a(0)?.clamp(-1.0, 1.0).acos(), | |
| 2721 | "atanr" => a(0)?.atan(), | |
| 2722 | "atan2r" => a(0)?.atan2(a(1)?), | |
| 2723 | "sinh" => a(0)?.sinh(), | |
| 2724 | "cosh" => a(0)?.cosh(), | |
| 2725 | "tanh" => a(0)?.tanh(), | |
| 2726 | "deg" => a(0)? * RAD2DEG, | |
| 2727 | "rad" => a(0)? * DEG2RAD, | |
| 2728 | "abs" => a(0)?.abs(), | |
| 2729 | "sqrt" => a(0)?.max(0.0).sqrt(), | |
| 2730 | "pow" => a(0)?.powf(a(1)?), | |
| 2731 | "exp" => a(0)?.exp(), | |
| 2732 | "log" | "ln" => a(0)?.max(1e-12).ln(), | |
| 2733 | "log10" => a(0)?.max(1e-12).log10(), | |
| 2734 | "log2" => a(0)?.max(1e-12).log2(), | |
| 2735 | "floor" | "int" => a(0)?.floor(), | |
| 2736 | "ceil" => a(0)?.ceil(), | |
| 2737 | "round" => a(0)?.round(), | |
| 2738 | "trunc" => a(0)?.trunc(), | |
| 2739 | "fract" => a(0)? - a(0)?.floor(), | |
| 2740 | "sign" => { | |
| 2741 | let v = a(0)?; | |
| 2742 | if v > 0.0 { 1.0 } else if v < 0.0 { -1.0 } else { 0.0 } | |
| 2743 | } | |
| 2744 | "min" => { | |
| 2745 | if args.is_empty() { return None; } | |
| 2746 | args.iter().copied().fold(f64::INFINITY, f64::min) | |
| 2747 | } | |
| 2748 | "max" => { | |
| 2749 | if args.is_empty() { return None; } | |
| 2750 | args.iter().copied().fold(f64::NEG_INFINITY, f64::max) | |
| 2751 | } | |
| 2752 | "clamp" => a(0)?.clamp(a(1)?, a(2)?), | |
| 2753 | "mod" => { | |
| 2754 | let (x, y) = (a(0)?, a(1)?); | |
| 2755 | if y.abs() < 1e-12 { 0.0 } else { x - y * (x / y).floor() } | |
| 2756 | } | |
| 2757 | "if" | "iif" => { | |
| 2758 | if a(0)? != 0.0 { a(1)? } else { a(2)? } | |
| 2759 | } | |
| 2760 | "dist" => { | |
| 2761 | let (x1, y1, x2, y2) = (a(0)?, a(1)?, a(2)?, a(3)?); | |
| 2762 | ((x2 - x1).powi(2) + (y2 - y1).powi(2)).sqrt() | |
| 2763 | } | |
| 2764 | "hypot" => a(0)?.hypot(a(1)?), | |
| 2765 | "mix" | "lerp" => { | |
| 2766 | let (x, y, t) = (a(0)?, a(1)?, a(2)?); | |
| 2767 | x + (y - x) * t | |
| 2768 | } | |
| 2769 | "step" => if a(1)? < a(0)? { 0.0 } else { 1.0 }, | |
| 2770 | "smoothstep" => { | |
| 2771 | let (e0, e1, x) = (a(0)?, a(1)?, a(2)?); | |
| 2772 | let denom = e1 - e0; | |
| 2773 | let t = if denom.abs() < 1e-12 { 0.0 } else { ((x - e0) / denom).clamp(0.0, 1.0) }; | |
| 2774 | t * t * (3.0 - 2.0 * t) | |
| 2775 | } | |
| 2776 | _ => return None, | |
| 2777 | }) | |
| 2778 | } | |
| 2779 | } | |
| 2780 | ||
| 2781 | let mut p = Parser { | |
| 2782 | bytes: src.as_bytes(), | |
| 2783 | pos: 0, | |
| 2784 | vars, | |
| 2785 | }; | |
| 2786 | let val = p.parse_or()?; | |
| 2787 | p.skip_ws(); | |
| 2788 | if p.pos != p.bytes.len() || !val.is_finite() { | |
| 2789 | return None; | |
| 2790 | } | |
| 2791 | Some(val) | |
| 2792 | } | |
| 2793 | ||
| 2794 | #[cfg(test)] | |
| 2795 | mod expression_modifier_tests { | |
| 2796 | use super::*; | |
| 2797 | ||
| 2798 | #[test] | |
| 2799 | fn evaluates_standalone_expression_modifier_number_and_chained() { | |
| 2800 | let src = r#"Composition { | |
| 2801 | Tools = ordered() { | |
| 2802 | XF1 = Transform { | |
| 2803 | Inputs = { | |
| 2804 | Angle = Input { SourceOp = "Clock_MinHandExpr", Source = "NumberResult", }, | |
| 2805 | Size = Input { SourceOp = "HourHandExpr", Source = "NumberResult", }, | |
| 2806 | }, | |
| 2807 | }, | |
| 2808 | Clock_MinHandExpr = Expression { | |
| 2809 | Inputs = { | |
| 2810 | n1 = Input { Value = 1, }, | |
| 2811 | n2 = Input { SourceOp = "TimeSpline", Source = "Value", }, | |
| 2812 | NumberExpression = Input { Value = "if(n1>0.5,floor(-n2)*30,-n2*30)", }, | |
| 2813 | }, | |
| 2814 | }, | |
| 2815 | HourHandExpr = Expression { | |
| 2816 | Inputs = { | |
| 2817 | n1 = Input { SourceOp = "Clock_MinHandExpr", Source = "NumberResult", }, | |
| 2818 | NumberExpression = Input { Value = "n1/12", }, | |
| 2819 | }, | |
| 2820 | }, | |
| 2821 | TimeSpline = BezierSpline { | |
| 2822 | KeyFrames = { | |
| 2823 | [0] = { 0.0, Flags = { Linear = true } }, | |
| 2824 | [10] = { 2.5, Flags = { Linear = true } }, | |
| 2825 | }, | |
| 2826 | }, | |
| 2827 | }, | |
| 2828 | }"#; | |
| 2829 | ||
| 2830 | let comp = Comp::from_fusion_str(src).expect("parse comp"); | |
| 2831 | assert!(comp.expression_modifiers.contains_key("Clock_MinHandExpr")); | |
| 2832 | assert!(comp.expression_modifiers.contains_key("HourHandExpr")); | |
| 2833 | // Expression modifiers are modifiers, not flow nodes | |
| 2834 | assert!(comp.find_node("Clock_MinHandExpr").is_none()); | |
| 2835 | ||
| 2836 | let expr = ExprEngine::new(); | |
| 2837 | let xf = comp.node(comp.find_node("XF1").unwrap()); | |
| 2838 | // At t=10: n2 = 2.5, floor(-2.5) = -3.0, -3.0 * 30 = -90.0 | |
| 2839 | let angle = comp.eval_number(xf, "Angle", 10.0, 0.0, &expr); | |
| 2840 | assert!((angle - (-90.0)).abs() < 1e-6, "got {angle}"); | |
| 2841 | // Chained HourHandExpr: n1 / 12 = -90 / 12 = -7.5 | |
| 2842 | let size = comp.eval_number(xf, "Size", 10.0, 1.0, &expr); | |
| 2843 | assert!((size - (-7.5)).abs() < 1e-6, "got {size}"); | |
| 2844 | ||
| 2845 | // Lossless roundtrip preserves Expression modifiers | |
| 2846 | let saved = comp.to_fusion_string(); | |
| 2847 | let reloaded = Comp::from_fusion_str(&saved).expect("reload"); | |
| 2848 | let r_xf = reloaded.node(reloaded.find_node("XF1").unwrap()); | |
| 2849 | assert!((reloaded.eval_number(r_xf, "Angle", 10.0, 0.0, &expr) - (-90.0)).abs() < 1e-6); | |
| 2850 | } | |
| 2851 | ||
| 2852 | #[test] | |
| 2853 | fn evaluates_standalone_expression_modifier_point_and_dist_trig() { | |
| 2854 | let src = r#"Composition { | |
| 2855 | Tools = ordered() { | |
| 2856 | XF1 = Transform { | |
| 2857 | Inputs = { | |
| 2858 | Center = Input { SourceOp = "PtExpr", Source = "PointResult", }, | |
| 2859 | Angle = Input { SourceOp = "TrigExpr", Source = "NumberResult", }, | |
| 2860 | }, | |
| 2861 | }, | |
| 2862 | PtExpr = Expression { | |
| 2863 | Inputs = { | |
| 2864 | p1 = Input { Value = { 0.8, 0.2 }, }, | |
| 2865 | n1 = Input { Value = 10, }, | |
| 2866 | PointExpressionX = Input { Value = "if(p1x>0.5, 0.5 + time*dist(p1x,p1y,0.5,p1y)/n1, 0.5)", }, | |
| 2867 | PointExpressionY = Input { Value = "-p1y + p1y*0.5 + 0.5", }, | |
| 2868 | }, | |
| 2869 | }, | |
| 2870 | TrigExpr = Expression { | |
| 2871 | Inputs = { | |
| 2872 | NumberIn1 = Input { Value = 90, }, | |
| 2873 | NumberExpression = Input { Value = "sin(n1) + cos(0) + (1/0)", }, | |
| 2874 | }, | |
| 2875 | }, | |
| 2876 | }, | |
| 2877 | }"#; | |
| 2878 | ||
| 2879 | let comp = Comp::from_fusion_str(src).expect("parse comp"); | |
| 2880 | let expr = ExprEngine::new(); | |
| 2881 | let xf = comp.node(comp.find_node("XF1").unwrap()); | |
| 2882 | // At t=5: dist(0.8,0.2,0.5,0.2) = 0.3, x = 0.5 + 5*0.3/10 = 0.65, y = -0.2 + 0.1 + 0.5 = 0.4 | |
| 2883 | let pt = comp.eval_point(xf, "Center", 5.0, [0.5, 0.5], &expr); | |
| 2884 | assert!((pt[0] - 0.65).abs() < 1e-6, "got x={}", pt[0]); | |
| 2885 | assert!((pt[1] - 0.40).abs() < 1e-6, "got y={}", pt[1]); | |
| 2886 | // sin(90 deg) + cos(0 deg) + safe_div(1,0) = 1 + 1 + 0 = 2.0 | |
| 2887 | let ang = comp.eval_number(xf, "Angle", 0.0, 0.0, &expr); | |
| 2888 | assert!((ang - 2.0).abs() < 1e-6, "got {ang}"); | |
| 2889 | } | |
| 2890 | } |
scripts/fusion_probes.py+165| ... | ... | @@ -2000,6 +2000,170 @@ def build_probe_archive_3d(): |
| 2000 | 2000 | return comp_path, "archive_3d", cases |
| 2001 | 2001 | |
| 2002 | 2002 | |
| 2003 | def build_probe_custom_tool(): | |
| 2004 | """Shale #18 probe: CustomTool per-pixel DSL (waves, premul invert, samplers, if, LUTIn1, Setup/Inter, mask/blend) + Expression modifier.""" | |
| 2005 | chart = generate_color_chart() | |
| 2006 | grid = generate_grid_chart() | |
| 2007 | cases = [ | |
| 2008 | (0, "custom_wave_sin_deg"), | |
| 2009 | (1, "custom_premul_invert_i1"), | |
| 2010 | (2, "custom_samplers_b_w_d"), | |
| 2011 | (3, "custom_if_img2_pt_num"), | |
| 2012 | (4, "custom_lut1_curve"), | |
| 2013 | (5, "custom_setup_c1_mod_dist"), | |
| 2014 | (6, "custom_mask_blend_procb0"), | |
| 2015 | (7, "expression_modifier_num_pt"), | |
| 2016 | ] | |
| 2017 | nodes = [ | |
| 2018 | make_loader("ChartLoader", chart, post_mult=1), | |
| 2019 | make_loader("GridLoader", grid, post_mult=1), | |
| 2020 | """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, TopLeftAlpha = Input { Value = 1, }, }, }, | |
| 2021 | \t\t-- f00: sin/cos wave generator matching 20_falling CustomTool1 | |
| 2022 | \t\tOp_0 = Custom { | |
| 2023 | \t\t\tInputs = { | |
| 2024 | \t\t\t\tImage1 = Input { SourceOp = "ChartLoader", Source = "Output", }, | |
| 2025 | \t\t\t\tNumberIn1 = Input { Value = 0.7413, }, | |
| 2026 | \t\t\t\tNumberIn2 = Input { Value = 10.655, }, | |
| 2027 | \t\t\t\tRedExpression = Input { Value = "sin(x*w*n1 + n2*n1*w)*0.5+0.5", }, | |
| 2028 | \t\t\t\tGreenExpression = Input { Value = "sin(y*w*n1 + n2*n1*w)*0.5+0.5", }, | |
| 2029 | \t\t\t\tBlueExpression = Input { Value = "0\\n", }, | |
| 2030 | \t\t\t\tAlphaExpression = Input { Value = "1", }, | |
| 2031 | \t\t\t}, | |
| 2032 | \t\t}, | |
| 2033 | \t\t-- f01: Premul/unpremul invert via Intermediate1 matching CustomTool2 | |
| 2034 | \t\tOp_1 = Custom { | |
| 2035 | \t\t\tInputs = { | |
| 2036 | \t\t\t\tImage1 = Input { SourceOp = "ChartLoader", Source = "Output", }, | |
| 2037 | \t\t\t\tIntermediate1 = Input { Value = "a1", }, | |
| 2038 | \t\t\t\tRedExpression = Input { Value = "(1-r1/a1)*i1", }, | |
| 2039 | \t\t\t\tGreenExpression = Input { Value = "(1-g1/a1)*i1", }, | |
| 2040 | \t\t\t\tBlueExpression = Input { Value = "(1-b1/a1)*i1", }, | |
| 2041 | \t\t\t\tAlphaExpression = Input { Value = "i1", }, | |
| 2042 | \t\t\t}, | |
| 2043 | \t\t}, | |
| 2044 | \t\t-- f02: Offset image samplers (b=black, w=wrap, d=duplicate) | |
| 2045 | \t\tOp_2 = Custom { | |
| 2046 | \t\t\tInputs = { | |
| 2047 | \t\t\t\tImage1 = Input { SourceOp = "GridLoader", Source = "Output", }, | |
| 2048 | \t\t\t\tRedExpression = Input { Value = "getr1b(x + 0.15, y - 0.1)", }, | |
| 2049 | \t\t\t\tGreenExpression = Input { Value = "getg1w(x + 0.25, y + 0.25)", }, | |
| 2050 | \t\t\t\tBlueExpression = Input { Value = "getb1d(x - 0.2, y + 0.2)", }, | |
| 2051 | \t\t\t\tAlphaExpression = Input { Value = "1", }, | |
| 2052 | \t\t\t}, | |
| 2053 | \t\t}, | |
| 2054 | \t\t-- f03: if(...), Image2, PointIn1, NumberIn1 | |
| 2055 | \t\tOp_3 = Custom { | |
| 2056 | \t\t\tInputs = { | |
| 2057 | \t\t\t\tImage1 = Input { SourceOp = "ChartLoader", Source = "Output", }, | |
| 2058 | \t\t\t\tImage2 = Input { SourceOp = "GridLoader", Source = "Output", }, | |
| 2059 | \t\t\t\tNumberIn1 = Input { Value = 0.6, }, | |
| 2060 | \t\t\t\tPointIn1 = Input { Value = { 0.4, 0.6 }, }, | |
| 2061 | \t\t\t\tRedExpression = Input { Value = "if(x > p1x, r1 * n1, r2)", }, | |
| 2062 | \t\t\t\tGreenExpression = Input { Value = "if(y > p1y, g1, g2 * n1)", }, | |
| 2063 | \t\t\t\tBlueExpression = Input { Value = "if(x > p1x && y > p1y, b2, b1)", }, | |
| 2064 | \t\t\t\tAlphaExpression = Input { Value = "1", }, | |
| 2065 | \t\t\t}, | |
| 2066 | \t\t}, | |
| 2067 | \t\t-- f04: LUTIn1 curved spline | |
| 2068 | \t\tOp_4LUTIn1 = LUTBezier { | |
| 2069 | \t\t\tKeyColorSplines = { | |
| 2070 | \t\t\t\t[0] = { | |
| 2071 | \t\t\t\t\t[0] = { 0.0, RH = { 0.15, 0.6 }, }, | |
| 2072 | \t\t\t\t\t[0.5] = { 0.85, LH = { 0.35, 0.85 }, RH = { 0.65, 0.85 }, }, | |
| 2073 | \t\t\t\t\t[1] = { 0.2, LH = { 0.85, 0.4 }, }, | |
| 2074 | \t\t\t\t}, | |
| 2075 | \t\t\t}, | |
| 2076 | \t\t}, | |
| 2077 | \t\tOp_4 = Custom { | |
| 2078 | \t\t\tInputs = { | |
| 2079 | \t\t\t\tImage1 = Input { SourceOp = "ChartLoader", Source = "Output", }, | |
| 2080 | \t\t\t\tLUTIn1 = Input { SourceOp = "Op_4LUTIn1", Source = "Value", }, | |
| 2081 | \t\t\t\tRedExpression = Input { Value = "getlut1(r1)", }, | |
| 2082 | \t\t\t\tGreenExpression = Input { Value = "getlut1(g1)", }, | |
| 2083 | \t\t\t\tBlueExpression = Input { Value = "getlut1(b1)", }, | |
| 2084 | \t\t\t\tAlphaExpression = Input { Value = "a1", }, | |
| 2085 | \t\t\t}, | |
| 2086 | \t\t}, | |
| 2087 | \t\t-- f05: Setup1/2, Intermediate1, c1, e^-(), %, dist, max(3) | |
| 2088 | \t\tOp_5 = Custom { | |
| 2089 | \t\t\tInputs = { | |
| 2090 | \t\t\t\tImage1 = Input { SourceOp = "ChartLoader", Source = "Output", }, | |
| 2091 | \t\t\t\tNumberIn1 = Input { Value = 0.4, }, | |
| 2092 | \t\t\t\tNumberIn2 = Input { Value = 0.2, }, | |
| 2093 | \t\t\t\tSetup1 = Input { Value = "1 - n1", }, | |
| 2094 | \t\t\t\tIntermediate1 = Input { Value = "max(0, 1 - dist(x, y, 0.5, 0.5) * 2)", }, | |
| 2095 | \t\t\t\tRedExpression = Input { Value = "if(c1>n1, n1+s1*(1-e^-((c1-n1)/s1)), c1) * i1", }, | |
| 2096 | \t\t\t\tGreenExpression = Input { Value = "((x * 4) % 1) * i1", }, | |
| 2097 | \t\t\t\tBlueExpression = Input { Value = "max(r1, g1, b1) * i1", }, | |
| 2098 | \t\t\t\tAlphaExpression = Input { Value = "1", }, | |
| 2099 | \t\t\t}, | |
| 2100 | \t\t}, | |
| 2101 | \t\t-- f06: EffectMask + Blend=0.75 + ProcessBlue=0 | |
| 2102 | \t\tMask6 = EllipseMask { Inputs = { MaskWidth = Input { Value = 512, }, MaskHeight = Input { Value = 512, }, Width = Input { Value = 0.65, }, Height = Input { Value = 0.65, }, }, }, | |
| 2103 | \t\tOp_6 = Custom { | |
| 2104 | \t\t\tInputs = { | |
| 2105 | \t\t\t\tEffectMask = Input { SourceOp = "Mask6", Source = "Mask", }, | |
| 2106 | \t\t\t\tBlend = Input { Value = 0.75, }, | |
| 2107 | \t\t\t\tProcessBlue = Input { Value = 0, }, | |
| 2108 | \t\t\t\tImage1 = Input { SourceOp = "GridLoader", Source = "Output", }, | |
| 2109 | \t\t\t\tRedExpression = Input { Value = "1 - r1", }, | |
| 2110 | \t\t\t\tGreenExpression = Input { Value = "1 - g1", }, | |
| 2111 | \t\t\t\tBlueExpression = Input { Value = "0", }, | |
| 2112 | \t\t\t\tAlphaExpression = Input { Value = "a1", }, | |
| 2113 | \t\t\t}, | |
| 2114 | \t\t}, | |
| 2115 | \t\t-- f07: Standalone Expression modifier driving CustomTool NumberIn1 & Transform Center | |
| 2116 | \t\tExprNum7 = Expression { | |
| 2117 | \t\t\tInputs = { | |
| 2118 | \t\t\t\tn1 = Input { Value = 1.0, }, | |
| 2119 | \t\t\t\tNumberExpression = Input { Value = "if(n1>0.5, sin(90)*0.5 + 0.25, 0.1)", }, | |
| 2120 | \t\t\t}, | |
| 2121 | \t\t}, | |
| 2122 | \t\tExprPt7 = Expression { | |
| 2123 | \t\t\tInputs = { | |
| 2124 | \t\t\t\tp1 = Input { Value = { 0.8, 0.2 }, }, | |
| 2125 | \t\t\t\tPointExpressionX = Input { Value = "0.5 + (p1x - 0.5) * 0.5", }, | |
| 2126 | \t\t\t\tPointExpressionY = Input { Value = "0.6", }, | |
| 2127 | \t\t\t}, | |
| 2128 | \t\t}, | |
| 2129 | \t\tXf7 = Transform { | |
| 2130 | \t\t\tInputs = { | |
| 2131 | \t\t\t\tInput = Input { SourceOp = "GridLoader", Source = "Output", }, | |
| 2132 | \t\t\t\tCenter = Input { SourceOp = "ExprPt7", Source = "PointResult", }, | |
| 2133 | \t\t\t\tSize = Input { Value = 0.7, }, | |
| 2134 | \t\t\t}, | |
| 2135 | \t\t}, | |
| 2136 | \t\tOp_7 = Custom { | |
| 2137 | \t\t\tInputs = { | |
| 2138 | \t\t\t\tImage1 = Input { SourceOp = "Xf7", Source = "Output", }, | |
| 2139 | \t\t\t\tNumberIn1 = Input { SourceOp = "ExprNum7", Source = "NumberResult", }, | |
| 2140 | \t\t\t\tRedExpression = Input { Value = "r1 * n1", }, | |
| 2141 | \t\t\t\tGreenExpression = Input { Value = "g1 * n1", }, | |
| 2142 | \t\t\t\tBlueExpression = Input { Value = "b1", }, | |
| 2143 | \t\t\t\tAlphaExpression = Input { Value = "a1", }, | |
| 2144 | \t\t\t}, | |
| 2145 | \t\t},""", | |
| 2146 | ] | |
| 2147 | splines = [] | |
| 2148 | prev = "BlackBG" | |
| 2149 | for f, _label in cases: | |
| 2150 | bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases} | |
| 2151 | sname = f"CT_{f}_Blend" | |
| 2152 | splines.append(step_spline(sname, bl)) | |
| 2153 | nodes.append(f"""\t\tSw_{f} = Merge {{ | |
| 2154 | \t\t\tInputs = {{ | |
| 2155 | \t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }}, | |
| 2156 | \t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }}, | |
| 2157 | \t\t\t\tForeground = Input {{ SourceOp = "Op_{f}", Source = "Output", }}, | |
| 2158 | \t\t\t}}, | |
| 2159 | \t\t}},""") | |
| 2160 | prev = f"Sw_{f}" | |
| 2161 | nodes.append(make_saver(prev, "custom_tool")) | |
| 2162 | comp_path = local_root() / "comps" / "probe_custom_tool.comp" | |
| 2163 | comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1)) | |
| 2164 | return comp_path, "custom_tool", cases | |
| 2165 | ||
| 2166 | ||
| 2003 | 2167 | def main(): |
| 2004 | 2168 | ensure_dirs() |
| 2005 | 2169 | which = [a for a in sys.argv[1:] if not a.startswith("--")] or ["merge"] |
| ... | ... | @@ -2019,6 +2183,7 @@ def main(): |
| 2019 | 2183 | "moon_3d": build_probe_moon_3d, |
| 2020 | 2184 | "ultrakey": build_probe_ultrakey, |
| 2021 | 2185 | "archive_3d": build_probe_archive_3d, |
| 2186 | "custom_tool": build_probe_custom_tool, | |
| 2022 | 2187 | "glow": build_probe_glow, |
| 2023 | 2188 | "text": build_probe_text, |
| 2024 | 2189 | "noise_text": build_probe_noise_text, |