| 1 | //! Fusion `DVIPComputeNode` and `ParamBlock` GPU DCTL compilation and dispatch. |
| 2 | |
| 3 | use std::cell::RefCell; |
| 4 | use std::collections::hash_map::DefaultHasher; |
| 5 | use std::hash::{Hash, Hasher}; |
| 6 | use std::rc::Rc; |
| 7 | use std::sync::Arc; |
| 8 | |
| 9 | use mlua::{MetaMethod, Result as LuaResult, UserData, UserDataMethods, Value}; |
| 10 | |
| 11 | use crate::cache::CachedTexture; |
| 12 | |
| 13 | use super::CompiledDctlPipeline; |
| 14 | use super::dctl::{ParamLayout, parse_param_block, transpile_dctl_to_wgsl}; |
| 15 | use super::lua_host::{HostBridge, val_to_f64}; |
| 16 | use super::lua_types::{ImageBacking, ImageInner, LuaImage}; |
| 17 | |
| 18 | // --------------------------------------------------------------------------- |
| 19 | // DVIPComputeNode + ParamBlock (GPU DCTL execution) |
| 20 | // --------------------------------------------------------------------------- |
| 21 | |
| 22 | struct ParamBlockInner { |
| 23 | layout: ParamLayout, |
| 24 | bytes: Vec<u8>, |
| 25 | } |
| 26 | |
| 27 | #[derive(Clone)] |
| 28 | struct LuaParamBlock(Rc<RefCell<ParamBlockInner>>); |
| 29 | |
| 30 | #[derive(Clone)] |
| 31 | struct LuaParamArrayView { |
| 32 | inner: Rc<RefCell<ParamBlockInner>>, |
| 33 | field_name: String, |
| 34 | } |
| 35 | |
| 36 | impl UserData for LuaParamArrayView { |
| 37 | fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { |
| 38 | methods.add_meta_method(MetaMethod::Index, |_, this, key: Value| { |
| 39 | let idx = key_to_elem_index(&key)?; |
| 40 | let inner = this.inner.borrow(); |
| 41 | Ok(inner.layout.read_scalar(&inner.bytes, &this.field_name, Some(idx)).unwrap_or(0.0)) |
| 42 | }); |
| 43 | methods.add_meta_method(MetaMethod::NewIndex, |_, this, (key, val): (Value, Value)| { |
| 44 | let idx = key_to_elem_index(&key)?; |
| 45 | let num = val_to_f64(&val); |
| 46 | let mut inner = this.inner.borrow_mut(); |
| 47 | let layout = inner.layout.clone(); |
| 48 | layout.write_scalar(&mut inner.bytes, &this.field_name, Some(idx), num); |
| 49 | Ok(()) |
| 50 | }); |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | impl UserData for LuaParamBlock { |
| 55 | fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { |
| 56 | methods.add_meta_method(MetaMethod::Index, |lua, this, key: String| { |
| 57 | let inner = this.0.borrow(); |
| 58 | if let Some(f) = inner.layout.field(&key) { |
| 59 | if f.array_len.is_some() || f.ty.components() > 1 { |
| 60 | let view = LuaParamArrayView { |
| 61 | inner: this.0.clone(), |
| 62 | field_name: key, |
| 63 | }; |
| 64 | return Ok(Value::UserData(lua.create_userdata(view)?)); |
| 65 | } |
| 66 | let v = inner.layout.read_scalar(&inner.bytes, &key, None).unwrap_or(0.0); |
| 67 | return Ok(Value::Number(v)); |
| 68 | } |
| 69 | Ok(Value::Nil) |
| 70 | }); |
| 71 | methods.add_meta_method(MetaMethod::NewIndex, |_, this, (key, val): (String, Value)| { |
| 72 | let mut inner = this.0.borrow_mut(); |
| 73 | let layout = inner.layout.clone(); |
| 74 | if let Some(f) = layout.field(&key) { |
| 75 | match val { |
| 76 | Value::Table(tbl) => { |
| 77 | let count = f.array_len.unwrap_or_else(|| f.ty.components()); |
| 78 | let zero_based = tbl.get::<Value>(0).ok().is_some_and(|v| !matches!(v, Value::Nil)); |
| 79 | for i in 0..count { |
| 80 | let k = if zero_based { i as i64 } else { (i + 1) as i64 }; |
| 81 | if let Ok(v) = tbl.get::<f64>(k) { |
| 82 | layout.write_scalar(&mut inner.bytes, &key, Some(i), v); |
| 83 | } |
| 84 | } |
| 85 | } |
| 86 | other => { |
| 87 | layout.write_scalar(&mut inner.bytes, &key, None, val_to_f64(&other)); |
| 88 | } |
| 89 | } |
| 90 | } |
| 91 | Ok(()) |
| 92 | }); |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | fn key_to_elem_index(key: &Value) -> LuaResult<usize> { |
| 97 | match key { |
| 98 | Value::Integer(i) if *i >= 0 => Ok(*i as usize), |
| 99 | Value::Number(n) if *n >= 0.0 => Ok(*n as usize), |
| 100 | Value::String(s) => match s.to_str()?.as_ref() { |
| 101 | "x" | "X" | "r" | "R" => Ok(0), |
| 102 | "y" | "Y" | "g" | "G" => Ok(1), |
| 103 | "z" | "Z" | "b" | "B" => Ok(2), |
| 104 | "w" | "W" | "a" | "A" => Ok(3), |
| 105 | other => Err(mlua::Error::RuntimeError(format!("unknown vector component `{other}`"))), |
| 106 | }, |
| 107 | _ => Err(mlua::Error::RuntimeError("invalid param array index".into())), |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | pub(super) struct DvipNodeInner { |
| 112 | pub(super) kernel_name: String, |
| 113 | pub(super) source: String, |
| 114 | pub(super) params_name: String, |
| 115 | pub(super) params_def: String, |
| 116 | pub(super) param_bytes: Vec<u8>, |
| 117 | pub(super) inputs: Vec<(String, Rc<RefCell<ImageInner>>)>, |
| 118 | pub(super) outputs: Vec<(String, Rc<RefCell<ImageInner>>)>, |
| 119 | pub(super) normalized_coords: bool, |
| 120 | pub(super) linear_filter: bool, |
| 121 | pub(super) address_mode: u32, |
| 122 | pub(super) error_log: String, |
| 123 | } |
| 124 | |
| 125 | #[derive(Clone)] |
| 126 | pub(super) struct LuaDvipNode(pub(super) Rc<RefCell<DvipNodeInner>>); |
| 127 | |
| 128 | impl UserData for LuaDvipNode { |
| 129 | fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { |
| 130 | methods.add_method("GetParamBlock", |_, this, def_override: Option<String>| { |
| 131 | let def = def_override.unwrap_or_else(|| this.0.borrow().params_def.clone()); |
| 132 | let layout = parse_param_block(&def).map_err(mlua::Error::RuntimeError)?; |
| 133 | let bytes = vec![0u8; layout.buffer_size()]; |
| 134 | Ok(LuaParamBlock(Rc::new(RefCell::new(ParamBlockInner { layout, bytes })))) |
| 135 | }); |
| 136 | methods.add_method("SetParamBlock", |_, this, params: mlua::UserDataRef<LuaParamBlock>| { |
| 137 | let bytes = params.0.borrow().bytes.clone(); |
| 138 | this.0.borrow_mut().param_bytes = bytes; |
| 139 | Ok(()) |
| 140 | }); |
| 141 | methods.add_method( |
| 142 | "AddSampler", |
| 143 | |_, this, (_name, filter, addr, norm): (String, Option<i32>, Option<i32>, Option<i32>)| { |
| 144 | let mut n = this.0.borrow_mut(); |
| 145 | if let Some(f) = filter { |
| 146 | n.linear_filter = f != 0; |
| 147 | } |
| 148 | if let Some(a) = addr { |
| 149 | n.address_mode = a.max(0) as u32; |
| 150 | } |
| 151 | if let Some(nc) = norm { |
| 152 | n.normalized_coords = nc != 0; |
| 153 | } |
| 154 | Ok(()) |
| 155 | }, |
| 156 | ); |
| 157 | methods.add_method("AddInput", |_, this, (name, img): (String, mlua::UserDataRef<LuaImage>)| { |
| 158 | let mut n = this.0.borrow_mut(); |
| 159 | if let Some(slot) = n.inputs.iter_mut().find(|(k, _)| k == &name) { |
| 160 | slot.1 = img.0.clone(); |
| 161 | } else { |
| 162 | n.inputs.push((name, img.0.clone())); |
| 163 | } |
| 164 | Ok(()) |
| 165 | }); |
| 166 | methods.add_method("AddOutput", |_, this, (name, img): (String, mlua::UserDataRef<LuaImage>)| { |
| 167 | let mut n = this.0.borrow_mut(); |
| 168 | if let Some(slot) = n.outputs.iter_mut().find(|(k, _)| k == &name) { |
| 169 | slot.1 = img.0.clone(); |
| 170 | } else { |
| 171 | n.outputs.push((name, img.0.clone())); |
| 172 | } |
| 173 | Ok(()) |
| 174 | }); |
| 175 | methods.add_method("GetErrorLog", |_, this, ()| Ok(this.0.borrow().error_log.clone())); |
| 176 | methods.add_method("RunSession", |lua, this, _req: Value| { |
| 177 | let mut bridge = lua |
| 178 | .app_data_mut::<HostBridge>() |
| 179 | .ok_or_else(|| mlua::Error::RuntimeError("missing HostBridge".into()))?; |
| 180 | let res = run_dvip_session(&mut this.0.borrow_mut(), &mut bridge); |
| 181 | match res { |
| 182 | Ok(()) => Ok(true), |
| 183 | Err(msg) => { |
| 184 | this.0.borrow_mut().error_log = msg; |
| 185 | Ok(false) |
| 186 | } |
| 187 | } |
| 188 | }); |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | fn run_dvip_session(node: &mut DvipNodeInner, bridge: &mut HostBridge) -> Result<(), String> { |
| 193 | if node.outputs.is_empty() { |
| 194 | return Err("DVIPComputeNode has no registered outputs".to_owned()); |
| 195 | } |
| 196 | let (dst_size, dst_depth) = { |
| 197 | let out0 = node.outputs[0].1.borrow(); |
| 198 | ([out0.width.max(1), out0.height.max(1)], out0.depth) |
| 199 | }; |
| 200 | let dst_format = bridge.format_for_depth(dst_depth); |
| 201 | |
| 202 | // 1. Lookup or compile cached WGSL compute pipeline |
| 203 | let mut hasher = DefaultHasher::new(); |
| 204 | node.source.hash(&mut hasher); |
| 205 | node.kernel_name.hash(&mut hasher); |
| 206 | node.params_name.hash(&mut hasher); |
| 207 | node.params_def.hash(&mut hasher); |
| 208 | let cache_key = (hasher.finish(), dst_format); |
| 209 | |
| 210 | let compiled: Arc<CompiledDctlPipeline> = { |
| 211 | let mut cache = bridge |
| 212 | .pipeline_cache |
| 213 | .lock() |
| 214 | .map_err(|_| "DCTL pipeline cache poisoned".to_owned())?; |
| 215 | if let Some(hit) = cache.get(&cache_key) { |
| 216 | hit |
| 217 | } else { |
| 218 | let transpiled = transpile_dctl_to_wgsl( |
| 219 | &node.source, |
| 220 | &node.kernel_name, |
| 221 | Some(&node.params_name), |
| 222 | Some(&node.params_def), |
| 223 | dst_format, |
| 224 | )?; |
| 225 | let compiled = compile_dctl_pipeline(&bridge.device, &transpiled, dst_format)?; |
| 226 | let arc = Arc::new(compiled); |
| 227 | cache.insert(cache_key, arc.clone()); |
| 228 | arc |
| 229 | } |
| 230 | }; |
| 231 | |
| 232 | // 2. Ensure GPU textures for all kernel inputs (zero CPU roundtrip!) |
| 233 | let mut input_texs: Vec<CachedTexture> = Vec::with_capacity(compiled.input_textures.len()); |
| 234 | for (idx, tex_name) in compiled.input_textures.iter().enumerate() { |
| 235 | let found = node |
| 236 | .inputs |
| 237 | .iter() |
| 238 | .find(|(k, _)| k == tex_name) |
| 239 | .or_else(|| node.inputs.get(idx)); |
| 240 | if let Some((_, img_rc)) = found { |
| 241 | let tex = img_rc.borrow_mut().ensure_gpu(bridge, bridge.content_hash_seed ^ (idx as u64 + 1)); |
| 242 | input_texs.push(tex); |
| 243 | } else { |
| 244 | input_texs.push(bridge.dummy_tex.clone()); |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | // 3. Allocate GPU output textures and attach them back onto the Lua output Image handles |
| 249 | let mut output_texs: Vec<CachedTexture> = Vec::with_capacity(compiled.output_textures.len()); |
| 250 | for (idx, dst_name) in compiled.output_textures.iter().enumerate() { |
| 251 | let found = node |
| 252 | .outputs |
| 253 | .iter() |
| 254 | .find(|(k, _)| k == dst_name) |
| 255 | .or_else(|| node.outputs.get(idx)); |
| 256 | let out_tex = if let Some((_, img_rc)) = found { |
| 257 | let mut inner = img_rc.borrow_mut(); |
| 258 | let sz = [inner.width.max(1), inner.height.max(1)]; |
| 259 | let tex = bridge.alloc_gpu_tex(sz, inner.depth, bridge.content_hash_seed ^ (0xF000 + idx as u64)); |
| 260 | inner.backing = ImageBacking::Gpu(tex.clone()); |
| 261 | tex |
| 262 | } else { |
| 263 | bridge.alloc_gpu_tex(dst_size, dst_depth, bridge.content_hash_seed ^ (0xF000 + idx as u64)) |
| 264 | }; |
| 265 | output_texs.push(out_tex); |
| 266 | } |
| 267 | |
| 268 | // 4. Upload params storage buffer & meta uniform buffer |
| 269 | let required_param_bytes = compiled.param_layout.buffer_size(); |
| 270 | let mut param_data = node.param_bytes.clone(); |
| 271 | param_data.resize(required_param_bytes, 0); |
| 272 | let param_buf = bridge.device.create_buffer(&wgpu::BufferDescriptor { |
| 273 | label: Some("dctl-params-buf"), |
| 274 | size: required_param_bytes as u64, |
| 275 | usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, |
| 276 | mapped_at_creation: false, |
| 277 | }); |
| 278 | bridge.queue.write_buffer(&param_buf, 0, &param_data); |
| 279 | |
| 280 | let meta: [u32; 4] = [ |
| 281 | dst_size[0], |
| 282 | dst_size[1], |
| 283 | u32::from(node.normalized_coords), |
| 284 | u32::from(node.linear_filter), |
| 285 | ]; |
| 286 | let meta_buf = bridge.device.create_buffer(&wgpu::BufferDescriptor { |
| 287 | label: Some("dctl-meta-buf"), |
| 288 | size: 16, |
| 289 | usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, |
| 290 | mapped_at_creation: false, |
| 291 | }); |
| 292 | bridge.queue.write_buffer(&meta_buf, 0, bytemuck::cast_slice(&meta)); |
| 293 | |
| 294 | let addr_mode = match node.address_mode { |
| 295 | 2 => wgpu::AddressMode::Repeat, |
| 296 | 3 => wgpu::AddressMode::MirrorRepeat, |
| 297 | _ => wgpu::AddressMode::ClampToEdge, |
| 298 | }; |
| 299 | let filter = if node.linear_filter { |
| 300 | wgpu::FilterMode::Linear |
| 301 | } else { |
| 302 | wgpu::FilterMode::Nearest |
| 303 | }; |
| 304 | let sampler = bridge.device.create_sampler(&wgpu::SamplerDescriptor { |
| 305 | label: Some("dctl-sampler"), |
| 306 | address_mode_u: addr_mode, |
| 307 | address_mode_v: addr_mode, |
| 308 | mag_filter: filter, |
| 309 | min_filter: filter, |
| 310 | ..Default::default() |
| 311 | }); |
| 312 | |
| 313 | // 5. Build bind group & dispatch compute pass onto the shared CommandEncoder! |
| 314 | let mut entries: Vec<wgpu::BindGroupEntry<'_>> = Vec::with_capacity(3 + input_texs.len() + output_texs.len()); |
| 315 | entries.push(wgpu::BindGroupEntry { |
| 316 | binding: 0, |
| 317 | resource: param_buf.as_entire_binding(), |
| 318 | }); |
| 319 | entries.push(wgpu::BindGroupEntry { |
| 320 | binding: 1, |
| 321 | resource: wgpu::BindingResource::Sampler(&sampler), |
| 322 | }); |
| 323 | entries.push(wgpu::BindGroupEntry { |
| 324 | binding: 2, |
| 325 | resource: meta_buf.as_entire_binding(), |
| 326 | }); |
| 327 | let mut binding = 3u32; |
| 328 | for t in &input_texs { |
| 329 | entries.push(wgpu::BindGroupEntry { |
| 330 | binding, |
| 331 | resource: wgpu::BindingResource::TextureView(&t.view), |
| 332 | }); |
| 333 | binding += 1; |
| 334 | } |
| 335 | for t in &output_texs { |
| 336 | entries.push(wgpu::BindGroupEntry { |
| 337 | binding, |
| 338 | resource: wgpu::BindingResource::TextureView(&t.view), |
| 339 | }); |
| 340 | binding += 1; |
| 341 | } |
| 342 | let bg = bridge.device.create_bind_group(&wgpu::BindGroupDescriptor { |
| 343 | label: Some("dctl-bg"), |
| 344 | layout: &compiled.bgl, |
| 345 | entries: &entries, |
| 346 | }); |
| 347 | |
| 348 | let enc = bridge |
| 349 | .encoder |
| 350 | .as_mut() |
| 351 | .ok_or_else(|| "missing active CommandEncoder".to_owned())?; |
| 352 | let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { |
| 353 | label: Some("dctl-compute-pass"), |
| 354 | timestamp_writes: None, |
| 355 | }); |
| 356 | pass.set_pipeline(&compiled.pipeline); |
| 357 | pass.set_bind_group(0, &bg, &[]); |
| 358 | pass.dispatch_workgroups(dst_size[0].div_ceil(8), dst_size[1].div_ceil(8), 1); |
| 359 | Ok(()) |
| 360 | } |
| 361 | |
| 362 | /// Compiles a transpiled DCTL WGSL shader into a validated `wgpu::ComputePipeline` inside |
| 363 | /// `push_error_scope` so malformed Fuses never panic. |
| 364 | pub fn compile_dctl_pipeline( |
| 365 | device: &wgpu::Device, |
| 366 | transpiled: &super::dctl::TranspiledKernel, |
| 367 | dst_format: wgpu::TextureFormat, |
| 368 | ) -> Result<CompiledDctlPipeline, String> { |
| 369 | let mut layout_entries = vec![ |
| 370 | wgpu::BindGroupLayoutEntry { |
| 371 | binding: 0, |
| 372 | visibility: wgpu::ShaderStages::COMPUTE, |
| 373 | ty: wgpu::BindingType::Buffer { |
| 374 | ty: wgpu::BufferBindingType::Storage { read_only: true }, |
| 375 | has_dynamic_offset: false, |
| 376 | min_binding_size: None, |
| 377 | }, |
| 378 | count: None, |
| 379 | }, |
| 380 | wgpu::BindGroupLayoutEntry { |
| 381 | binding: 1, |
| 382 | visibility: wgpu::ShaderStages::COMPUTE, |
| 383 | ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), |
| 384 | count: None, |
| 385 | }, |
| 386 | wgpu::BindGroupLayoutEntry { |
| 387 | binding: 2, |
| 388 | visibility: wgpu::ShaderStages::COMPUTE, |
| 389 | ty: wgpu::BindingType::Buffer { |
| 390 | ty: wgpu::BufferBindingType::Uniform, |
| 391 | has_dynamic_offset: false, |
| 392 | min_binding_size: None, |
| 393 | }, |
| 394 | count: None, |
| 395 | }, |
| 396 | ]; |
| 397 | let mut binding = 3u32; |
| 398 | for _ in &transpiled.input_textures { |
| 399 | layout_entries.push(wgpu::BindGroupLayoutEntry { |
| 400 | binding, |
| 401 | visibility: wgpu::ShaderStages::COMPUTE, |
| 402 | ty: wgpu::BindingType::Texture { |
| 403 | sample_type: wgpu::TextureSampleType::Float { filterable: true }, |
| 404 | view_dimension: wgpu::TextureViewDimension::D2, |
| 405 | multisampled: false, |
| 406 | }, |
| 407 | count: None, |
| 408 | }); |
| 409 | binding += 1; |
| 410 | } |
| 411 | for _ in &transpiled.output_textures { |
| 412 | layout_entries.push(wgpu::BindGroupLayoutEntry { |
| 413 | binding, |
| 414 | visibility: wgpu::ShaderStages::COMPUTE, |
| 415 | ty: wgpu::BindingType::StorageTexture { |
| 416 | access: wgpu::StorageTextureAccess::WriteOnly, |
| 417 | format: dst_format, |
| 418 | view_dimension: wgpu::TextureViewDimension::D2, |
| 419 | }, |
| 420 | count: None, |
| 421 | }); |
| 422 | binding += 1; |
| 423 | } |
| 424 | |
| 425 | let scope = device.push_error_scope(wgpu::ErrorFilter::Validation); |
| 426 | let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { |
| 427 | label: Some("dctl-bgl"), |
| 428 | entries: &layout_entries, |
| 429 | }); |
| 430 | let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { |
| 431 | label: Some("dctl-pl"), |
| 432 | bind_group_layouts: &[Some(&bgl)], |
| 433 | immediate_size: 0, |
| 434 | }); |
| 435 | let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { |
| 436 | label: Some("dctl-shader"), |
| 437 | source: wgpu::ShaderSource::Wgsl(transpiled.wgsl.as_str().into()), |
| 438 | }); |
| 439 | let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { |
| 440 | label: Some("dctl-compute-pipeline"), |
| 441 | layout: Some(&pl), |
| 442 | module: &module, |
| 443 | entry_point: Some(&transpiled.entry_point), |
| 444 | compilation_options: Default::default(), |
| 445 | cache: None, |
| 446 | }); |
| 447 | if let Some(err) = pollster::block_on(scope.pop()) { |
| 448 | return Err(format!("WGSL validation failed: {err}")); |
| 449 | } |
| 450 | |
| 451 | Ok(CompiledDctlPipeline { |
| 452 | pipeline, |
| 453 | bgl, |
| 454 | param_layout: transpiled.param_layout.clone(), |
| 455 | input_textures: transpiled.input_textures.clone(), |
| 456 | output_textures: transpiled.output_textures.clone(), |
| 457 | }) |
| 458 | } |
| 459 | |