| 1 | //! GPU + Comp host bridge shared with the sandboxed Fusion Lua runtime. |
| 2 | |
| 3 | use std::cell::RefCell; |
| 4 | use std::collections::HashMap; |
| 5 | use std::rc::Rc; |
| 6 | use std::sync::{Arc, Mutex}; |
| 7 | |
| 8 | use model::{BitDepth, Gradient}; |
| 9 | |
| 10 | use crate::cache::CachedTexture; |
| 11 | use crate::eval::create_texture_dod_fmt; |
| 12 | |
| 13 | use super::lua_types::ImageInner; |
| 14 | use super::{DctlPipelineCache, FuseMeta}; |
| 15 | |
| 16 | /// Pre-evaluated Fusion parameter value passed from `Comp` / `Node` into the Lua host. |
| 17 | #[derive(Clone, Debug)] |
| 18 | pub enum EvalParam { |
| 19 | Number(f64), |
| 20 | Point([f64; 2]), |
| 21 | Text(String), |
| 22 | Gradient(Gradient), |
| 23 | } |
| 24 | |
| 25 | /// GPU + Comp bridge stored in `Lua` app data during a single Fuse execution. |
| 26 | pub struct HostBridge { |
| 27 | pub device: wgpu::Device, |
| 28 | pub queue: wgpu::Queue, |
| 29 | pub encoder: Option<wgpu::CommandEncoder>, |
| 30 | pub dummy_tex: CachedTexture, |
| 31 | pub pipeline_cache: Arc<Mutex<DctlPipelineCache>>, |
| 32 | pub supports_f32_filter: bool, |
| 33 | pub hiq: bool, |
| 34 | pub default_depth: BitDepth, |
| 35 | pub comp_dims: [u32; 2], |
| 36 | pub time: f64, |
| 37 | pub global_range: [i64; 2], |
| 38 | pub render_range: [i64; 2], |
| 39 | pub upstream_images: HashMap<String, CachedTexture>, |
| 40 | pub main_input: Option<CachedTexture>, |
| 41 | pub params: HashMap<String, EvalParam>, |
| 42 | pub fuse_meta: FuseMeta, |
| 43 | pub output_image: Option<Rc<RefCell<ImageInner>>>, |
| 44 | pub tool_data: HashMap<String, String>, |
| 45 | pub content_hash_seed: u64, |
| 46 | } |
| 47 | |
| 48 | impl HostBridge { |
| 49 | pub(super) fn format_for_depth(&self, depth: BitDepth) -> wgpu::TextureFormat { |
| 50 | let eff = if self.hiq { depth } else { BitDepth::Int8 }; |
| 51 | match eff { |
| 52 | BitDepth::Int8 => wgpu::TextureFormat::Rgba8Unorm, |
| 53 | BitDepth::Int16 | BitDepth::Float16 => wgpu::TextureFormat::Rgba16Float, |
| 54 | BitDepth::Float32 => { |
| 55 | if self.supports_f32_filter { |
| 56 | wgpu::TextureFormat::Rgba32Float |
| 57 | } else { |
| 58 | wgpu::TextureFormat::Rgba16Float |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | pub(super) fn alloc_gpu_tex(&self, size: [u32; 2], depth: BitDepth, hash: u64) -> CachedTexture { |
| 65 | let eff = if self.hiq { depth } else { BitDepth::Int8 }; |
| 66 | let fmt = self.format_for_depth(eff); |
| 67 | create_texture_dod_fmt(&self.device, size, [0, 0], size, eff, fmt, hash) |
| 68 | } |
| 69 | |
| 70 | /// Flushes any pending GPU commands so subsequent CPU readbacks observe upstream writes. |
| 71 | fn flush_encoder(&mut self) { |
| 72 | if let Some(enc) = self.encoder.take() { |
| 73 | let sub = self.queue.submit(Some(enc.finish())); |
| 74 | let _ = self.device.poll(wgpu::PollType::Wait { |
| 75 | submission_index: Some(sub), |
| 76 | timeout: Some(std::time::Duration::from_secs(10)), |
| 77 | }); |
| 78 | self.encoder = Some(self.device.create_command_encoder( |
| 79 | &wgpu::CommandEncoderDescriptor { |
| 80 | label: Some("fuse-runtime-post-flush"), |
| 81 | }, |
| 82 | )); |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | /// Reads back a `CachedTexture` (Fission Y-down) into Fusion Y-up linear `Vec<[f32; 4]>`. |
| 87 | pub(super) fn readback_gpu_to_fusion_y_up(&mut self, tex: &CachedTexture) -> Result<Vec<[f32; 4]>, String> { |
| 88 | self.flush_encoder(); |
| 89 | let [w, h] = tex.size; |
| 90 | let bpp: u32 = match tex.format { |
| 91 | wgpu::TextureFormat::Rgba32Float => 16, |
| 92 | wgpu::TextureFormat::Rgba16Float => 8, |
| 93 | wgpu::TextureFormat::Rgba8Unorm => 4, |
| 94 | other => return Err(format!("unsupported format for Fuse CPU readback: {other:?}")), |
| 95 | }; |
| 96 | let unpadded_bpr = w * bpp; |
| 97 | let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; |
| 98 | let padded_bpr = unpadded_bpr.div_ceil(align) * align; |
| 99 | let buf_size = u64::from(padded_bpr) * u64::from(h); |
| 100 | let staging = self.device.create_buffer(&wgpu::BufferDescriptor { |
| 101 | label: Some("fuse-cpu-readback"), |
| 102 | size: buf_size.max(4), |
| 103 | usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, |
| 104 | mapped_at_creation: false, |
| 105 | }); |
| 106 | let mut enc = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { |
| 107 | label: Some("fuse-readback-copy"), |
| 108 | }); |
| 109 | enc.copy_texture_to_buffer( |
| 110 | tex.texture.as_image_copy(), |
| 111 | wgpu::TexelCopyBufferInfo { |
| 112 | buffer: &staging, |
| 113 | layout: wgpu::TexelCopyBufferLayout { |
| 114 | offset: 0, |
| 115 | bytes_per_row: Some(padded_bpr), |
| 116 | rows_per_image: Some(h), |
| 117 | }, |
| 118 | }, |
| 119 | wgpu::Extent3d { |
| 120 | width: w, |
| 121 | height: h, |
| 122 | depth_or_array_layers: 1, |
| 123 | }, |
| 124 | ); |
| 125 | let sub = self.queue.submit(Some(enc.finish())); |
| 126 | let slice = staging.slice(..); |
| 127 | let (tx, rx) = std::sync::mpsc::channel(); |
| 128 | slice.map_async(wgpu::MapMode::Read, move |res| { |
| 129 | let _ = tx.send(res); |
| 130 | }); |
| 131 | let _ = self.device.poll(wgpu::PollType::Wait { |
| 132 | submission_index: Some(sub), |
| 133 | timeout: Some(std::time::Duration::from_secs(10)), |
| 134 | }); |
| 135 | rx.recv() |
| 136 | .map_err(|e| e.to_string())? |
| 137 | .map_err(|e| format!("{e:?}"))?; |
| 138 | |
| 139 | let mapped = slice.get_mapped_range().map_err(|e| format!("{e:?}"))?; |
| 140 | let mut pixels = vec![[0.0f32; 4]; (w as usize) * (h as usize)]; |
| 141 | for ty in 0..h as usize { |
| 142 | let fy = (h as usize) - 1 - ty; // flip Y-down -> Fusion Y-up |
| 143 | let row = &mapped[ty * padded_bpr as usize..ty * padded_bpr as usize + unpadded_bpr as usize]; |
| 144 | let dst_row = &mut pixels[fy * w as usize..(fy + 1) * w as usize]; |
| 145 | match tex.format { |
| 146 | wgpu::TextureFormat::Rgba8Unorm => { |
| 147 | for (x, c) in row.chunks_exact(4).enumerate() { |
| 148 | dst_row[x] = [ |
| 149 | f32::from(c[0]) / 255.0, |
| 150 | f32::from(c[1]) / 255.0, |
| 151 | f32::from(c[2]) / 255.0, |
| 152 | f32::from(c[3]) / 255.0, |
| 153 | ]; |
| 154 | } |
| 155 | } |
| 156 | wgpu::TextureFormat::Rgba16Float => { |
| 157 | for (x, c) in row.chunks_exact(8).enumerate() { |
| 158 | dst_row[x] = [ |
| 159 | ::exr::prelude::f16::from_bits(u16::from_le_bytes([c[0], c[1]])).to_f32(), |
| 160 | ::exr::prelude::f16::from_bits(u16::from_le_bytes([c[2], c[3]])).to_f32(), |
| 161 | ::exr::prelude::f16::from_bits(u16::from_le_bytes([c[4], c[5]])).to_f32(), |
| 162 | ::exr::prelude::f16::from_bits(u16::from_le_bytes([c[6], c[7]])).to_f32(), |
| 163 | ]; |
| 164 | } |
| 165 | } |
| 166 | wgpu::TextureFormat::Rgba32Float => { |
| 167 | for (x, c) in row.chunks_exact(16).enumerate() { |
| 168 | dst_row[x] = [ |
| 169 | f32::from_le_bytes([c[0], c[1], c[2], c[3]]), |
| 170 | f32::from_le_bytes([c[4], c[5], c[6], c[7]]), |
| 171 | f32::from_le_bytes([c[8], c[9], c[10], c[11]]), |
| 172 | f32::from_le_bytes([c[12], c[13], c[14], c[15]]), |
| 173 | ]; |
| 174 | } |
| 175 | } |
| 176 | _ => {} |
| 177 | } |
| 178 | } |
| 179 | drop(mapped); |
| 180 | staging.unmap(); |
| 181 | Ok(pixels) |
| 182 | } |
| 183 | |
| 184 | /// Uploads a Fusion Y-up `Vec<[f32; 4]>` buffer into a Fission Y-down GPU `CachedTexture`. |
| 185 | pub(super) fn upload_fusion_y_up_to_gpu( |
| 186 | &self, |
| 187 | width: u32, |
| 188 | height: u32, |
| 189 | depth: BitDepth, |
| 190 | pixels: &[[f32; 4]], |
| 191 | hash: u64, |
| 192 | ) -> CachedTexture { |
| 193 | let tex = self.alloc_gpu_tex([width, height], depth, hash); |
| 194 | let w = width as usize; |
| 195 | let h = height as usize; |
| 196 | match tex.format { |
| 197 | wgpu::TextureFormat::Rgba8Unorm => { |
| 198 | let mut raw = vec![0u8; w * h * 4]; |
| 199 | for ty in 0..h { |
| 200 | let fy = h - 1 - ty; |
| 201 | for x in 0..w { |
| 202 | let p = pixels[fy * w + x]; |
| 203 | let o = (ty * w + x) * 4; |
| 204 | raw[o] = (p[0].clamp(0.0, 1.0) * 255.0).round() as u8; |
| 205 | raw[o + 1] = (p[1].clamp(0.0, 1.0) * 255.0).round() as u8; |
| 206 | raw[o + 2] = (p[2].clamp(0.0, 1.0) * 255.0).round() as u8; |
| 207 | raw[o + 3] = (p[3].clamp(0.0, 1.0) * 255.0).round() as u8; |
| 208 | } |
| 209 | } |
| 210 | self.queue.write_texture( |
| 211 | tex.texture.as_image_copy(), |
| 212 | &raw, |
| 213 | wgpu::TexelCopyBufferLayout { |
| 214 | offset: 0, |
| 215 | bytes_per_row: Some(width * 4), |
| 216 | rows_per_image: Some(height), |
| 217 | }, |
| 218 | wgpu::Extent3d { |
| 219 | width, |
| 220 | height, |
| 221 | depth_or_array_layers: 1, |
| 222 | }, |
| 223 | ); |
| 224 | } |
| 225 | wgpu::TextureFormat::Rgba16Float => { |
| 226 | let mut raw = vec![0u8; w * h * 8]; |
| 227 | for ty in 0..h { |
| 228 | let fy = h - 1 - ty; |
| 229 | for x in 0..w { |
| 230 | let p = pixels[fy * w + x]; |
| 231 | let o = (ty * w + x) * 8; |
| 232 | for (c, &val) in p.iter().enumerate() { |
| 233 | let bits = ::exr::prelude::f16::from_f32(val).to_bits().to_le_bytes(); |
| 234 | raw[o + c * 2] = bits[0]; |
| 235 | raw[o + c * 2 + 1] = bits[1]; |
| 236 | } |
| 237 | } |
| 238 | } |
| 239 | self.queue.write_texture( |
| 240 | tex.texture.as_image_copy(), |
| 241 | &raw, |
| 242 | wgpu::TexelCopyBufferLayout { |
| 243 | offset: 0, |
| 244 | bytes_per_row: Some(width * 8), |
| 245 | rows_per_image: Some(height), |
| 246 | }, |
| 247 | wgpu::Extent3d { |
| 248 | width, |
| 249 | height, |
| 250 | depth_or_array_layers: 1, |
| 251 | }, |
| 252 | ); |
| 253 | } |
| 254 | wgpu::TextureFormat::Rgba32Float => { |
| 255 | let mut raw = vec![0u8; w * h * 16]; |
| 256 | for ty in 0..h { |
| 257 | let fy = h - 1 - ty; |
| 258 | for x in 0..w { |
| 259 | let p = pixels[fy * w + x]; |
| 260 | let o = (ty * w + x) * 16; |
| 261 | for (c, &val) in p.iter().enumerate() { |
| 262 | raw[o + c * 4..o + c * 4 + 4].copy_from_slice(&val.to_le_bytes()); |
| 263 | } |
| 264 | } |
| 265 | } |
| 266 | self.queue.write_texture( |
| 267 | tex.texture.as_image_copy(), |
| 268 | &raw, |
| 269 | wgpu::TexelCopyBufferLayout { |
| 270 | offset: 0, |
| 271 | bytes_per_row: Some(width * 16), |
| 272 | rows_per_image: Some(height), |
| 273 | }, |
| 274 | wgpu::Extent3d { |
| 275 | width, |
| 276 | height, |
| 277 | depth_or_array_layers: 1, |
| 278 | }, |
| 279 | ); |
| 280 | } |
| 281 | _ => {} |
| 282 | } |
| 283 | tex |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | |