| 1 | //! Pure-Rust DCTL (DaVinci Color Transform Language / Fusion GPU Fuse) to WGSL |
| 2 | //! compute shader transpiler and std430 parameter block layout parser. |
| 3 | //! |
| 4 | //! Compiles on all targets including `wasm32-unknown-unknown`. |
| 5 | |
| 6 | use std::collections::HashMap; |
| 7 | |
| 8 | /// Scalar / vector field type supported inside a DCTL parameter block. |
| 9 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
| 10 | pub enum ParamType { |
| 11 | F32, |
| 12 | I32, |
| 13 | U32, |
| 14 | Vec2F, |
| 15 | Vec3F, |
| 16 | Vec4F, |
| 17 | Vec2I, |
| 18 | Vec3I, |
| 19 | Vec4I, |
| 20 | } |
| 21 | |
| 22 | impl ParamType { |
| 23 | pub fn from_c_type(s: &str) -> Option<Self> { |
| 24 | match s.trim() { |
| 25 | "float" | "double" | "half" => Some(Self::F32), |
| 26 | "int" | "bool" | "short" | "char" => Some(Self::I32), |
| 27 | "uint" | "unsigned int" | "unsigned" => Some(Self::U32), |
| 28 | "float2" => Some(Self::Vec2F), |
| 29 | "float3" => Some(Self::Vec3F), |
| 30 | "float4" => Some(Self::Vec4F), |
| 31 | "int2" => Some(Self::Vec2I), |
| 32 | "int3" => Some(Self::Vec3I), |
| 33 | "int4" => Some(Self::Vec4I), |
| 34 | _ => None, |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | pub fn wgsl_name(self) -> &'static str { |
| 39 | match self { |
| 40 | Self::F32 => "f32", |
| 41 | Self::I32 => "i32", |
| 42 | Self::U32 => "u32", |
| 43 | Self::Vec2F => "vec2<f32>", |
| 44 | Self::Vec3F => "vec3<f32>", |
| 45 | Self::Vec4F => "vec4<f32>", |
| 46 | Self::Vec2I => "vec2<i32>", |
| 47 | Self::Vec3I => "vec3<i32>", |
| 48 | Self::Vec4I => "vec4<i32>", |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | pub fn align(self) -> usize { |
| 53 | match self { |
| 54 | Self::F32 | Self::I32 | Self::U32 => 4, |
| 55 | Self::Vec2F | Self::Vec2I => 8, |
| 56 | Self::Vec3F | Self::Vec3I | Self::Vec4F | Self::Vec4I => 16, |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | pub fn size(self) -> usize { |
| 61 | match self { |
| 62 | Self::F32 | Self::I32 | Self::U32 => 4, |
| 63 | Self::Vec2F | Self::Vec2I => 8, |
| 64 | Self::Vec3F | Self::Vec3I => 12, |
| 65 | Self::Vec4F | Self::Vec4I => 16, |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | pub fn elem_stride(self) -> usize { |
| 70 | round_up(self.size(), self.align()) |
| 71 | } |
| 72 | |
| 73 | pub fn components(self) -> usize { |
| 74 | match self { |
| 75 | Self::F32 | Self::I32 | Self::U32 => 1, |
| 76 | Self::Vec2F | Self::Vec2I => 2, |
| 77 | Self::Vec3F | Self::Vec3I => 3, |
| 78 | Self::Vec4F | Self::Vec4I => 4, |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | pub fn is_int(self) -> bool { |
| 83 | matches!(self, Self::I32 | Self::U32 | Self::Vec2I | Self::Vec3I | Self::Vec4I) |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | /// One field in a std430-laid-out DCTL parameter struct. |
| 88 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 89 | pub struct ParamField { |
| 90 | pub name: String, |
| 91 | pub ty: ParamType, |
| 92 | /// `None` for scalar/vector fields, `Some(n)` for fixed C arrays (`float color[3]`). |
| 93 | pub array_len: Option<usize>, |
| 94 | pub offset: usize, |
| 95 | pub size: usize, |
| 96 | pub align: usize, |
| 97 | } |
| 98 | |
| 99 | /// Full std430 layout of a DCTL parameter block. |
| 100 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 101 | pub struct ParamLayout { |
| 102 | pub fields: Vec<ParamField>, |
| 103 | pub total_size: usize, |
| 104 | } |
| 105 | |
| 106 | impl ParamLayout { |
| 107 | pub fn field(&self, name: &str) -> Option<&ParamField> { |
| 108 | self.fields.iter().find(|f| f.name == name) |
| 109 | } |
| 110 | |
| 111 | pub fn buffer_size(&self) -> usize { |
| 112 | self.total_size.max(16) |
| 113 | } |
| 114 | |
| 115 | /// Emits a WGSL `struct` definition matching this std430 storage layout. |
| 116 | pub fn to_wgsl_struct(&self, struct_name: &str) -> String { |
| 117 | let mut out = format!("struct {struct_name} {{\n"); |
| 118 | if self.fields.is_empty() { |
| 119 | out.push_str(" _dctl_pad0: u32,\n _dctl_pad1: u32,\n _dctl_pad2: u32,\n _dctl_pad3: u32,\n"); |
| 120 | } else { |
| 121 | for f in &self.fields { |
| 122 | if let Some(n) = f.array_len { |
| 123 | out.push_str(&format!(" {}: array<{}, {n}>,\n", f.name, f.ty.wgsl_name())); |
| 124 | } else { |
| 125 | out.push_str(&format!(" {}: {},\n", f.name, f.ty.wgsl_name())); |
| 126 | } |
| 127 | } |
| 128 | } |
| 129 | out.push_str("}\n"); |
| 130 | out |
| 131 | } |
| 132 | |
| 133 | /// Writes a single scalar/vector element at `field_name` (and optional `index`) into `buf`. |
| 134 | pub fn write_scalar(&self, buf: &mut [u8], field_name: &str, index: Option<usize>, value: f64) { |
| 135 | let Some(f) = self.field(field_name) else { |
| 136 | return; |
| 137 | }; |
| 138 | let off = match (f.array_len, index) { |
| 139 | (Some(len), Some(idx)) if idx < len => f.offset + idx * f.ty.elem_stride(), |
| 140 | (None, None) => f.offset, |
| 141 | (None, Some(idx)) if idx < f.ty.components() => f.offset + idx * 4, |
| 142 | _ => return, |
| 143 | }; |
| 144 | if off + 4 > buf.len() { |
| 145 | return; |
| 146 | } |
| 147 | let bytes = match f.ty { |
| 148 | ParamType::I32 | ParamType::Vec2I | ParamType::Vec3I | ParamType::Vec4I => { |
| 149 | (value.round() as i32).to_le_bytes() |
| 150 | } |
| 151 | ParamType::U32 => (value.round().max(0.0) as u32).to_le_bytes(), |
| 152 | _ => (value as f32).to_le_bytes(), |
| 153 | }; |
| 154 | buf[off..off + 4].copy_from_slice(&bytes); |
| 155 | } |
| 156 | |
| 157 | /// Reads a single scalar/vector element from `buf`. |
| 158 | pub fn read_scalar(&self, buf: &[u8], field_name: &str, index: Option<usize>) -> Option<f64> { |
| 159 | let f = self.field(field_name)?; |
| 160 | let off = match (f.array_len, index) { |
| 161 | (Some(len), Some(idx)) if idx < len => f.offset + idx * f.ty.elem_stride(), |
| 162 | (None, None) => f.offset, |
| 163 | (None, Some(idx)) if idx < f.ty.components() => f.offset + idx * 4, |
| 164 | _ => return None, |
| 165 | }; |
| 166 | let bytes: [u8; 4] = buf.get(off..off + 4)?.try_into().ok()?; |
| 167 | let val = match f.ty { |
| 168 | ParamType::I32 | ParamType::Vec2I | ParamType::Vec3I | ParamType::Vec4I => { |
| 169 | i32::from_le_bytes(bytes) as f64 |
| 170 | } |
| 171 | ParamType::U32 => u32::from_le_bytes(bytes) as f64, |
| 172 | _ => f32::from_le_bytes(bytes) as f64, |
| 173 | }; |
| 174 | Some(val) |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | /// Output of `transpile_dctl_to_wgsl`. |
| 179 | #[derive(Clone, Debug)] |
| 180 | pub struct TranspiledKernel { |
| 181 | pub wgsl: String, |
| 182 | pub entry_point: String, |
| 183 | pub params_struct_name: String, |
| 184 | pub param_layout: ParamLayout, |
| 185 | pub input_textures: Vec<String>, |
| 186 | pub output_textures: Vec<String>, |
| 187 | } |
| 188 | |
| 189 | fn round_up(val: usize, align: usize) -> usize { |
| 190 | if align <= 1 { |
| 191 | val |
| 192 | } else { |
| 193 | (val + align - 1) & !(align - 1) |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | pub fn wgsl_storage_format(format: wgpu::TextureFormat) -> &'static str { |
| 198 | match format { |
| 199 | wgpu::TextureFormat::Rgba16Float => "rgba16float", |
| 200 | wgpu::TextureFormat::Rgba32Float => "rgba32float", |
| 201 | _ => "rgba8unorm", |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | /// Parses a DCTL parameter block definition (either bare C fields or `typedef struct { ... } Name;`) |
| 206 | /// into a std430 `ParamLayout`. |
| 207 | pub fn parse_param_block(def: &str) -> Result<ParamLayout, String> { |
| 208 | let cleaned = strip_comments(def); |
| 209 | let body = extract_struct_body(&cleaned); |
| 210 | let mut layout = ParamLayout::default(); |
| 211 | let mut offset = 0usize; |
| 212 | let mut max_align = 4usize; |
| 213 | |
| 214 | for raw_stmt in body.split(';') { |
| 215 | let stmt = raw_stmt.trim(); |
| 216 | if stmt.is_empty() || stmt.starts_with('#') { |
| 217 | continue; |
| 218 | } |
| 219 | let tokens: Vec<&str> = stmt.split_whitespace().collect(); |
| 220 | if tokens.len() < 2 { |
| 221 | continue; |
| 222 | } |
| 223 | let (ty_str, rest_start) = if tokens[0] == "unsigned" && tokens.len() >= 3 && tokens[1] == "int" { |
| 224 | ("unsigned int", 2) |
| 225 | } else if matches!(tokens[0], "const" | "volatile") && tokens.len() >= 3 { |
| 226 | (tokens[1], 2) |
| 227 | } else { |
| 228 | (tokens[0], 1) |
| 229 | }; |
| 230 | let Some(ty) = ParamType::from_c_type(ty_str) else { |
| 231 | return Err(format!("unsupported DCTL param field type `{ty_str}` in `{stmt}`")); |
| 232 | }; |
| 233 | let rest = tokens[rest_start..].join(" "); |
| 234 | for decl in rest.split(',') { |
| 235 | let decl = decl.trim(); |
| 236 | if decl.is_empty() { |
| 237 | continue; |
| 238 | } |
| 239 | let (name, array_len) = if let Some(b) = decl.find('[') { |
| 240 | let end = decl.find(']').ok_or_else(|| format!("unclosed `[` in `{decl}`"))?; |
| 241 | let len_str = decl[b + 1..end].trim(); |
| 242 | let len: usize = len_str |
| 243 | .parse() |
| 244 | .map_err(|_| format!("invalid array size `{len_str}` in `{decl}`"))?; |
| 245 | (decl[..b].trim(), Some(len.max(1))) |
| 246 | } else { |
| 247 | (decl, None) |
| 248 | }; |
| 249 | let align = ty.align(); |
| 250 | max_align = max_align.max(align); |
| 251 | offset = round_up(offset, align); |
| 252 | let size = match array_len { |
| 253 | Some(n) => ty.elem_stride() * n, |
| 254 | None => ty.size(), |
| 255 | }; |
| 256 | layout.fields.push(ParamField { |
| 257 | name: name.to_owned(), |
| 258 | ty, |
| 259 | array_len, |
| 260 | offset, |
| 261 | size, |
| 262 | align, |
| 263 | }); |
| 264 | offset += size; |
| 265 | } |
| 266 | } |
| 267 | layout.total_size = round_up(offset, max_align).max(16); |
| 268 | Ok(layout) |
| 269 | } |
| 270 | |
| 271 | fn extract_struct_body(src: &str) -> &str { |
| 272 | if let (Some(open), Some(close)) = (src.find('{'), src.rfind('}')) |
| 273 | && open < close |
| 274 | { |
| 275 | &src[open + 1..close] |
| 276 | } else { |
| 277 | src |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | fn strip_comments(src: &str) -> String { |
| 282 | let bytes = src.as_bytes(); |
| 283 | let mut out = String::with_capacity(src.len()); |
| 284 | let mut i = 0; |
| 285 | while i < bytes.len() { |
| 286 | if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'/') { |
| 287 | i += 2; |
| 288 | while i < bytes.len() && bytes[i] != b'\n' { |
| 289 | i += 1; |
| 290 | } |
| 291 | } else if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'*') { |
| 292 | i += 2; |
| 293 | while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') { |
| 294 | i += 1; |
| 295 | } |
| 296 | i = (i + 2).min(bytes.len()); |
| 297 | out.push(' '); |
| 298 | } else { |
| 299 | let ch = src[i..].chars().next().unwrap(); |
| 300 | out.push(ch); |
| 301 | i += ch.len_utf8(); |
| 302 | } |
| 303 | } |
| 304 | out |
| 305 | } |
| 306 | |
| 307 | // --------------------------------------------------------------------------- |
| 308 | // Lexer |
| 309 | // --------------------------------------------------------------------------- |
| 310 | |
| 311 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 312 | pub(super) enum Tok { |
| 313 | Ident(String), |
| 314 | Float(String), |
| 315 | Int(String), |
| 316 | Punct(String), |
| 317 | } |
| 318 | |
| 319 | pub(super) fn lex_dctl(src: &str) -> Vec<Tok> { |
| 320 | let stripped = strip_comments(src); |
| 321 | let mut defines: HashMap<String, Vec<Tok>> = HashMap::new(); |
| 322 | let mut body = String::with_capacity(stripped.len()); |
| 323 | |
| 324 | for line in stripped.lines() { |
| 325 | let trimmed = line.trim_start(); |
| 326 | if let Some(rest) = trimmed.strip_prefix("#define") |
| 327 | && rest.starts_with(char::is_whitespace) |
| 328 | { |
| 329 | let rest = rest.trim_start(); |
| 330 | let mut parts = rest.splitn(2, char::is_whitespace); |
| 331 | if let (Some(name), Some(val)) = (parts.next(), parts.next()) |
| 332 | && !name.contains('(') |
| 333 | && !val.trim().is_empty() |
| 334 | { |
| 335 | defines.insert(name.to_owned(), lex_raw(val)); |
| 336 | } |
| 337 | } else if trimmed.starts_with('#') { |
| 338 | // Skip #include, #ifdef, #endif, #pragma, etc. |
| 339 | } else { |
| 340 | body.push_str(line); |
| 341 | body.push('\n'); |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | let raw = lex_raw(&body); |
| 346 | if defines.is_empty() { |
| 347 | return raw; |
| 348 | } |
| 349 | let mut expanded = Vec::with_capacity(raw.len()); |
| 350 | for tok in raw { |
| 351 | if let Tok::Ident(ref name) = tok |
| 352 | && let Some(rep) = defines.get(name) |
| 353 | { |
| 354 | expanded.extend(rep.iter().cloned()); |
| 355 | continue; |
| 356 | } |
| 357 | expanded.push(tok); |
| 358 | } |
| 359 | expanded |
| 360 | } |
| 361 | |
| 362 | fn lex_raw(src: &str) -> Vec<Tok> { |
| 363 | let b = src.as_bytes(); |
| 364 | let mut toks = Vec::new(); |
| 365 | let mut i = 0; |
| 366 | while i < b.len() { |
| 367 | let c = b[i]; |
| 368 | if c.is_ascii_whitespace() { |
| 369 | i += 1; |
| 370 | continue; |
| 371 | } |
| 372 | if c.is_ascii_alphabetic() || c == b'_' { |
| 373 | let start = i; |
| 374 | i += 1; |
| 375 | while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') { |
| 376 | i += 1; |
| 377 | } |
| 378 | toks.push(Tok::Ident(src[start..i].to_owned())); |
| 379 | continue; |
| 380 | } |
| 381 | if c.is_ascii_digit() || (c == b'.' && b.get(i + 1).is_some_and(u8::is_ascii_digit)) { |
| 382 | let start = i; |
| 383 | let mut is_float = c == b'.'; |
| 384 | if c == b'0' && matches!(b.get(i + 1), Some(b'x' | b'X')) { |
| 385 | i += 2; |
| 386 | while i < b.len() && b[i].is_ascii_hexdigit() { |
| 387 | i += 1; |
| 388 | } |
| 389 | while i < b.len() && matches!(b[i], b'u' | b'U' | b'l' | b'L') { |
| 390 | i += 1; |
| 391 | } |
| 392 | let s = src[start..i].trim_end_matches(['u', 'U', 'l', 'L']); |
| 393 | toks.push(Tok::Int(s.to_owned())); |
| 394 | continue; |
| 395 | } |
| 396 | while i < b.len() && b[i].is_ascii_digit() { |
| 397 | i += 1; |
| 398 | } |
| 399 | if i < b.len() && b[i] == b'.' { |
| 400 | is_float = true; |
| 401 | i += 1; |
| 402 | while i < b.len() && b[i].is_ascii_digit() { |
| 403 | i += 1; |
| 404 | } |
| 405 | } |
| 406 | if i < b.len() && matches!(b[i], b'e' | b'E') { |
| 407 | is_float = true; |
| 408 | i += 1; |
| 409 | if i < b.len() && matches!(b[i], b'+' | b'-') { |
| 410 | i += 1; |
| 411 | } |
| 412 | while i < b.len() && b[i].is_ascii_digit() { |
| 413 | i += 1; |
| 414 | } |
| 415 | } |
| 416 | let num_end = i; |
| 417 | let mut has_f = false; |
| 418 | while i < b.len() && matches!(b[i], b'f' | b'F' | b'h' | b'H' | b'u' | b'U' | b'l' | b'L') { |
| 419 | if matches!(b[i], b'f' | b'F' | b'h' | b'H') { |
| 420 | has_f = true; |
| 421 | } |
| 422 | i += 1; |
| 423 | } |
| 424 | let raw = &src[start..num_end]; |
| 425 | if is_float || has_f { |
| 426 | let mut norm = raw.to_owned(); |
| 427 | if norm.starts_with('.') { |
| 428 | norm.insert(0, '0'); |
| 429 | } |
| 430 | if norm.ends_with('.') { |
| 431 | norm.push('0'); |
| 432 | } |
| 433 | if !norm.contains('.') && !norm.contains('e') && !norm.contains('E') { |
| 434 | norm.push_str(".0"); |
| 435 | } |
| 436 | norm.push('f'); |
| 437 | toks.push(Tok::Float(norm)); |
| 438 | } else { |
| 439 | toks.push(Tok::Int(raw.to_owned())); |
| 440 | } |
| 441 | continue; |
| 442 | } |
| 443 | // Two-character operators |
| 444 | if i + 1 < b.len() { |
| 445 | let two = &src[i..i + 2]; |
| 446 | if matches!( |
| 447 | two, |
| 448 | "->" | "==" |
| 449 | | "!=" |
| 450 | | "<=" |
| 451 | | ">=" |
| 452 | | "&&" |
| 453 | | "||" |
| 454 | | "++" |
| 455 | | "--" |
| 456 | | "+=" |
| 457 | | "-=" |
| 458 | | "*=" |
| 459 | | "/=" |
| 460 | | "%=" |
| 461 | | "<<" |
| 462 | | ">>" |
| 463 | | "&=" |
| 464 | | "|=" |
| 465 | | "^=" |
| 466 | ) { |
| 467 | toks.push(Tok::Punct(two.to_owned())); |
| 468 | i += 2; |
| 469 | continue; |
| 470 | } |
| 471 | } |
| 472 | toks.push(Tok::Punct((c as char).to_string())); |
| 473 | i += 1; |
| 474 | } |
| 475 | toks |
| 476 | } |
| 477 | |
| 478 | // --------------------------------------------------------------------------- |
| 479 | // Type Mapping |
| 480 | // --------------------------------------------------------------------------- |
| 481 | |
| 482 | pub(super) fn c_type_to_wgsl(name: &str) -> Option<&'static str> { |
| 483 | match name { |
| 484 | "float" | "double" | "half" => Some("f32"), |
| 485 | "int" | "short" | "char" => Some("i32"), |
| 486 | "uint" | "unsigned" => Some("u32"), |
| 487 | "bool" => Some("bool"), |
| 488 | "void" => Some("void"), |
| 489 | "float2" => Some("vec2<f32>"), |
| 490 | "float3" => Some("vec3<f32>"), |
| 491 | "float4" => Some("vec4<f32>"), |
| 492 | "int2" => Some("vec2<i32>"), |
| 493 | "int3" => Some("vec3<i32>"), |
| 494 | "int4" => Some("vec4<i32>"), |
| 495 | "uint2" => Some("vec2<u32>"), |
| 496 | "uint3" => Some("vec3<u32>"), |
| 497 | "uint4" => Some("vec4<u32>"), |
| 498 | "float2x2" => Some("mat2x2<f32>"), |
| 499 | "float3x3" => Some("mat3x3<f32>"), |
| 500 | "float4x4" => Some("mat4x4<f32>"), |
| 501 | _ => None, |
| 502 | } |
| 503 | } |
| 504 | |
| 505 | pub(super) fn is_c_qualifier(s: &str) -> bool { |
| 506 | matches!( |
| 507 | s, |
| 508 | "const" |
| 509 | | "volatile" |
| 510 | | "inline" |
| 511 | | "static" |
| 512 | | "__CONSTANT__" |
| 513 | | "__CONSTANTREF__" |
| 514 | | "__GLOBAL__" |
| 515 | | "__LOCAL__" |
| 516 | | "__PRIVATE__" |
| 517 | ) |
| 518 | } |
| 519 | |
| 520 | |
| 521 | use super::dctl_parse::Transpiler; |
| 522 | |
| 523 | /// Transpiles a DCTL source string into a complete WebGPU-safe WGSL compute shader |
| 524 | /// (`@compute @workgroup_size(8, 8)`). |
| 525 | pub fn transpile_dctl_to_wgsl( |
| 526 | source: &str, |
| 527 | kernel_name: &str, |
| 528 | params_name: Option<&str>, |
| 529 | params_def: Option<&str>, |
| 530 | storage_format: wgpu::TextureFormat, |
| 531 | ) -> Result<TranspiledKernel, String> { |
| 532 | let toks = lex_dctl(source); |
| 533 | let mut tr = Transpiler::new(toks); |
| 534 | if let Some(pname) = params_name |
| 535 | && !pname.is_empty() |
| 536 | { |
| 537 | tr.known_structs.insert(pname.to_owned()); |
| 538 | } |
| 539 | tr.parse_program()?; |
| 540 | |
| 541 | let kernel = tr |
| 542 | .kernels |
| 543 | .iter() |
| 544 | .find(|k| k.name == kernel_name) |
| 545 | .or_else(|| tr.kernels.first()) |
| 546 | .ok_or_else(|| format!("no `__KERNEL__` function `{kernel_name}` found in DCTL source"))?; |
| 547 | |
| 548 | let resolved_params_name = params_name |
| 549 | .filter(|s| !s.is_empty()) |
| 550 | .map(str::to_owned) |
| 551 | .or_else(|| kernel.params_type.clone()) |
| 552 | .unwrap_or_else(|| "DctlParams".to_owned()); |
| 553 | |
| 554 | let param_layout = if let Some(def) = params_def.filter(|s| !s.trim().is_empty()) { |
| 555 | parse_param_block(def)? |
| 556 | } else if let Some(inline) = tr.inline_param_structs.get(&resolved_params_name) { |
| 557 | inline.clone() |
| 558 | } else { |
| 559 | ParamLayout { |
| 560 | fields: Vec::new(), |
| 561 | total_size: 16, |
| 562 | } |
| 563 | }; |
| 564 | |
| 565 | let fmt = wgsl_storage_format(storage_format); |
| 566 | let mut wgsl = String::with_capacity(source.len() * 2 + 1024); |
| 567 | |
| 568 | // 1. Meta uniform struct & parameter struct(s) |
| 569 | wgsl.push_str( |
| 570 | "struct _DctlMeta {\n\ |
| 571 | \x20 width: u32,\n\ |
| 572 | \x20 height: u32,\n\ |
| 573 | \x20 normalized: u32,\n\ |
| 574 | \x20 linear_filter: u32,\n\ |
| 575 | }\n\n", |
| 576 | ); |
| 577 | |
| 578 | let mut emitted_params_struct = false; |
| 579 | for (sname, sdef) in &tr.struct_defs { |
| 580 | if *sname == resolved_params_name { |
| 581 | wgsl.push_str(&param_layout.to_wgsl_struct(&resolved_params_name)); |
| 582 | wgsl.push('\n'); |
| 583 | emitted_params_struct = true; |
| 584 | } else { |
| 585 | wgsl.push_str(sdef); |
| 586 | wgsl.push('\n'); |
| 587 | } |
| 588 | } |
| 589 | if !emitted_params_struct { |
| 590 | wgsl.push_str(&param_layout.to_wgsl_struct(&resolved_params_name)); |
| 591 | wgsl.push('\n'); |
| 592 | } |
| 593 | |
| 594 | // 2. Bindings: 0 = params storage, 1 = sampler, 2 = meta uniform, 3.. = inputs, 3+N.. = outputs |
| 595 | wgsl.push_str(&format!( |
| 596 | "@group(0) @binding(0) var<storage, read> {}: {};\n", |
| 597 | kernel.params_var, resolved_params_name |
| 598 | )); |
| 599 | wgsl.push_str("@group(0) @binding(1) var _dctl_sampler: sampler;\n"); |
| 600 | wgsl.push_str("@group(0) @binding(2) var<uniform> _dctl_meta: _DctlMeta;\n"); |
| 601 | |
| 602 | let mut binding = 3u32; |
| 603 | for tex in &kernel.input_textures { |
| 604 | wgsl.push_str(&format!("@group(0) @binding({binding}) var {tex}: texture_2d<f32>;\n")); |
| 605 | binding += 1; |
| 606 | } |
| 607 | for dst in &kernel.output_textures { |
| 608 | wgsl.push_str(&format!( |
| 609 | "@group(0) @binding({binding}) var {dst}: texture_storage_2d<{fmt}, write>;\n" |
| 610 | )); |
| 611 | binding += 1; |
| 612 | } |
| 613 | wgsl.push('\n'); |
| 614 | |
| 615 | // 3. Built-in DCTL helper functions |
| 616 | wgsl.push_str( |
| 617 | "fn _dctl_pow(base: f32, exp_v: f32) -> f32 {\n\ |
| 618 | \x20 if (base <= 0.0) { return select(0.0, 1.0, exp_v == 0.0); }\n\ |
| 619 | \x20 return pow(base, exp_v);\n\ |
| 620 | }\n\ |
| 621 | fn _dctl_fmod(x: f32, y: f32) -> f32 {\n\ |
| 622 | \x20 if (y == 0.0) { return 0.0; }\n\ |
| 623 | \x20 return x - y * trunc(x / y);\n\ |
| 624 | }\n\ |
| 625 | fn _dctl_copysign(x: f32, y: f32) -> f32 {\n\ |
| 626 | \x20 return select(-abs(x), abs(x), y >= 0.0);\n\ |
| 627 | }\n\ |
| 628 | fn _dctl_tex2d(t: texture_2d<f32>, fx: f32, fy: f32) -> vec4<f32> {\n\ |
| 629 | \x20 let dims = textureDimensions(t);\n\ |
| 630 | \x20 if (_dctl_meta.normalized != 0u) {\n\ |
| 631 | \x20 return textureSampleLevel(t, _dctl_sampler, vec2<f32>(fx, 1.0 - fy), 0.0);\n\ |
| 632 | \x20 }\n\ |
| 633 | \x20 if (_dctl_meta.linear_filter != 0u) {\n\ |
| 634 | \x20 let uv = vec2<f32>((fx + 0.5) / f32(dims.x), 1.0 - (fy + 0.5) / f32(dims.y));\n\ |
| 635 | \x20 return textureSampleLevel(t, _dctl_sampler, uv, 0.0);\n\ |
| 636 | \x20 }\n\ |
| 637 | \x20 let ix = clamp(i32(round(fx)), 0, i32(dims.x) - 1);\n\ |
| 638 | \x20 let iy = clamp(i32(dims.y) - 1 - i32(round(fy)), 0, i32(dims.y) - 1);\n\ |
| 639 | \x20 return textureLoad(t, vec2<i32>(ix, iy), 0);\n\ |
| 640 | }\n\ |
| 641 | fn _dctl_tex2d_n(t: texture_2d<f32>, fx: f32, fy: f32, comp_order: i32) -> vec4<f32> {\n\ |
| 642 | \x20 let c = _dctl_tex2d(t, fx, fy);\n\ |
| 643 | \x20 if (comp_order == 1) { return vec4<f32>(c.w, c.w, c.w, c.w); }\n\ |
| 644 | \x20 return c;\n\ |
| 645 | }\n\n", |
| 646 | ); |
| 647 | |
| 648 | // 4. Global constants and `__DEVICE__` helper functions |
| 649 | for g in &tr.globals_wgsl { |
| 650 | wgsl.push_str(g); |
| 651 | } |
| 652 | for h in &tr.helpers_wgsl { |
| 653 | wgsl.push_str(h); |
| 654 | wgsl.push('\n'); |
| 655 | } |
| 656 | |
| 657 | // 5. Compute entry point |
| 658 | let entry_point = "dctl_main".to_owned(); |
| 659 | let dims_expr = if let Some(dst0) = kernel.output_textures.first() { |
| 660 | format!("textureDimensions({dst0})") |
| 661 | } else { |
| 662 | "vec2<u32>(_dctl_meta.width, _dctl_meta.height)".to_owned() |
| 663 | }; |
| 664 | wgsl.push_str(&format!( |
| 665 | "@compute @workgroup_size(8, 8)\n\ |
| 666 | fn {entry_point}(@builtin(global_invocation_id) _dctl_gid: vec3<u32>) {{\n\ |
| 667 | \x20 let _dctl_dims = {dims_expr};\n\ |
| 668 | \x20 if (_dctl_gid.x >= _dctl_dims.x || _dctl_gid.y >= _dctl_dims.y) {{ return; }}\n" |
| 669 | )); |
| 670 | wgsl.push_str(&kernel.body_wgsl); |
| 671 | wgsl.push_str("}\n"); |
| 672 | |
| 673 | Ok(TranspiledKernel { |
| 674 | wgsl, |
| 675 | entry_point, |
| 676 | params_struct_name: resolved_params_name, |
| 677 | param_layout, |
| 678 | input_textures: kernel.input_textures.clone(), |
| 679 | output_textures: kernel.output_textures.clone(), |
| 680 | }) |
| 681 | } |