| author | |
| committer | |
| log | 8ca9c80ab9057ebd8247c88cca56f8cbb43baccf |
| tree | 5fa158a94fea143440a47f038ff958d865fc7e55 |
| parent | f09f4d4d1335865b7fda16b04dc7cafcff542f8f |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
6 files changed, 2448 insertions(+), 0 deletions(-)
crates/engine/src/eval/color_science.rs created+594| ... | @@ -0,0 +1,594 @@ | ||
| 1 | //! Wave 36 — Color Science, `MatteControl` & `MultiMerge` GPU pipelines and evaluators: | ||
| 2 | //! - `AcesTransform` (ACES 1.3 IDT/ODT: AP0, AP1/ACEScg, ACEScct, ACEScc, Linear sRGB, sRGB, Rec.709) | ||
| 3 | //! - `ColorSpace` (RGB <-> BW, YUV, YIQ, CMY, HLS/HSL, HSV, XYZ, CIE-LAB, YCbCr) | ||
| 4 | //! - `ColorMatrix` (5x4 RGBA color matrix + offset) | ||
| 5 | //! - `WhiteBalance` (Kelvin temperature, tint, sampled white-point neutralization) | ||
| 6 | //! - `MatteControl` (matte combine, contract/expand, blur, threshold, gamma, invert, garbage/solid, spill suppress, post-multiply) | ||
| 7 | //! - `MultiMerge` & `Fuse.MultiMerge` (N-layer transform + blend composite reusing `ShaderOp::Merge`) | ||
| 8 | //! | ||
| 9 | //! WebGPU safety: all texture inputs use `TextureSampleType::Float { filterable: false }` | ||
| 10 | //! (sampled via `textureLoad` / manual bilinear), outputs are `WriteOnly` storage textures, | ||
| 11 | //! and uniform slots grow in 512-slot chunks reset via `Engine::reset_uniform_cursors()`. | ||
| 12 | |||
| 13 | mod matte_merge; | ||
| 14 | mod params; | ||
| 15 | #[cfg(test)] | ||
| 16 | mod tests; | ||
| 17 | |||
| 18 | use super::*; | ||
| 19 | use params::*; | ||
| 20 | use std::num::NonZeroU64; | ||
| 21 | |||
| 22 | const COLOR_SCIENCE_WGSL: &str = include_str!("../shaders/color_science.wgsl"); | ||
| 23 | const CS_UNIFORM_SLOTS_PER_CHUNK: u32 = 512; | ||
| 24 | |||
| 25 | #[derive(Clone, Copy)] | ||
| 26 | pub(self) enum ColorScienceOp { | ||
| 27 | AcesTransform, | ||
| 28 | ColorSpace, | ||
| 29 | ColorMatrix, | ||
| 30 | WhiteBalance, | ||
| 31 | MatteCombine, | ||
| 32 | MatteFinish, | ||
| 33 | BlendMask, | ||
| 34 | } | ||
| 35 | |||
| 36 | struct ColorScienceFormatPipelines { | ||
| 37 | bgl: wgpu::BindGroupLayout, | ||
| 38 | aces_transform: wgpu::ComputePipeline, | ||
| 39 | color_space: wgpu::ComputePipeline, | ||
| 40 | color_matrix: wgpu::ComputePipeline, | ||
| 41 | white_balance: wgpu::ComputePipeline, | ||
| 42 | matte_combine: wgpu::ComputePipeline, | ||
| 43 | matte_finish: wgpu::ComputePipeline, | ||
| 44 | blend_mask: wgpu::ComputePipeline, | ||
| 45 | } | ||
| 46 | |||
| 47 | impl ColorScienceFormatPipelines { | ||
| 48 | fn pipeline(&self, op: ColorScienceOp) -> &wgpu::ComputePipeline { | ||
| 49 | match op { | ||
| 50 | ColorScienceOp::AcesTransform => &self.aces_transform, | ||
| 51 | ColorScienceOp::ColorSpace => &self.color_space, | ||
| 52 | ColorScienceOp::ColorMatrix => &self.color_matrix, | ||
| 53 | ColorScienceOp::WhiteBalance => &self.white_balance, | ||
| 54 | ColorScienceOp::MatteCombine => &self.matte_combine, | ||
| 55 | ColorScienceOp::MatteFinish => &self.matte_finish, | ||
| 56 | ColorScienceOp::BlendMask => &self.blend_mask, | ||
| 57 | } | ||
| 58 | } | ||
| 59 | } | ||
| 60 | |||
| 61 | pub(super) struct ColorSciencePipelines { | ||
| 62 | uniform_stride: u32, | ||
| 63 | uniform_chunks: Vec<wgpu::Buffer>, | ||
| 64 | uniform_cursor: u32, | ||
| 65 | formats: HashMap<(wgpu::TextureFormat, bool), ColorScienceFormatPipelines>, | ||
| 66 | } | ||
| 67 | |||
| 68 | fn build_cs_wgsl(format: wgpu::TextureFormat, hdr_float: bool) -> String { | ||
| 69 | let mut src = COLOR_SCIENCE_WGSL.to_owned(); | ||
| 70 | let storage_fmt = match format { | ||
| 71 | wgpu::TextureFormat::Rgba16Float => "rgba16float", | ||
| 72 | wgpu::TextureFormat::Rgba32Float => "rgba32float", | ||
| 73 | _ => "rgba8unorm", | ||
| 74 | }; | ||
| 75 | if storage_fmt != "rgba8unorm" { | ||
| 76 | src = src.replace( | ||
| 77 | "texture_storage_2d<rgba8unorm, write>", | ||
| 78 | &format!("texture_storage_2d<{storage_fmt}, write>"), | ||
| 79 | ); | ||
| 80 | } | ||
| 81 | if hdr_float { | ||
| 82 | src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;"); | ||
| 83 | } | ||
| 84 | src | ||
| 85 | } | ||
| 86 | |||
| 87 | fn unfilterable_tex_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { | ||
| 88 | wgpu::BindGroupLayoutEntry { | ||
| 89 | binding, | ||
| 90 | visibility: wgpu::ShaderStages::COMPUTE, | ||
| 91 | ty: wgpu::BindingType::Texture { | ||
| 92 | sample_type: wgpu::TextureSampleType::Float { filterable: false }, | ||
| 93 | view_dimension: wgpu::TextureViewDimension::D2, | ||
| 94 | multisampled: false, | ||
| 95 | }, | ||
| 96 | count: None, | ||
| 97 | } | ||
| 98 | } | ||
| 99 | |||
| 100 | impl ColorSciencePipelines { | ||
| 101 | pub(super) fn new(device: &wgpu::Device) -> Self { | ||
| 102 | let uniform_size = std::mem::size_of::<UniformParams>() as u32; | ||
| 103 | let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1); | ||
| 104 | let uniform_stride = uniform_size.div_ceil(min_align) * min_align; | ||
| 105 | Self { | ||
| 106 | uniform_stride, | ||
| 107 | uniform_chunks: Vec::new(), | ||
| 108 | uniform_cursor: 0, | ||
| 109 | formats: HashMap::new(), | ||
| 110 | } | ||
| 111 | } | ||
| 112 | |||
| 113 | pub(super) fn reset_uniform_cursor(&mut self) { | ||
| 114 | self.uniform_cursor = 0; | ||
| 115 | } | ||
| 116 | |||
| 117 | pub(super) fn trim_uniform_chunks(&mut self, max_chunks: usize) { | ||
| 118 | self.uniform_cursor = 0; | ||
| 119 | if self.uniform_chunks.len() > max_chunks { | ||
| 120 | self.uniform_chunks.truncate(max_chunks); | ||
| 121 | } | ||
| 122 | } | ||
| 123 | |||
| 124 | fn alloc_uniform_slot( | ||
| 125 | &mut self, | ||
| 126 | device: &wgpu::Device, | ||
| 127 | queue: &wgpu::Queue, | ||
| 128 | params: &UniformParams, | ||
| 129 | ) -> (usize, u32) { | ||
| 130 | let slot_global = self.uniform_cursor; | ||
| 131 | let chunk_idx = (slot_global / CS_UNIFORM_SLOTS_PER_CHUNK) as usize; | ||
| 132 | let slot_in_chunk = slot_global % CS_UNIFORM_SLOTS_PER_CHUNK; | ||
| 133 | while chunk_idx >= self.uniform_chunks.len() { | ||
| 134 | let size = u64::from(CS_UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride); | ||
| 135 | let buf = device.create_buffer(&wgpu::BufferDescriptor { | ||
| 136 | label: Some("color-science-params-ring"), | ||
| 137 | size, | ||
| 138 | usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, | ||
| 139 | mapped_at_creation: false, | ||
| 140 | }); | ||
| 141 | self.uniform_chunks.push(buf); | ||
| 142 | } | ||
| 143 | let offset = slot_in_chunk * self.uniform_stride; | ||
| 144 | queue.write_buffer( | ||
| 145 | &self.uniform_chunks[chunk_idx], | ||
| 146 | u64::from(offset), | ||
| 147 | bytemuck::bytes_of(params), | ||
| 148 | ); | ||
| 149 | self.uniform_cursor = slot_global + 1; | ||
| 150 | (chunk_idx, offset) | ||
| 151 | } | ||
| 152 | |||
| 153 | fn ensure_format(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) { | ||
| 154 | if self.formats.contains_key(&(format, hdr_float)) { | ||
| 155 | return; | ||
| 156 | } | ||
| 157 | let u_size = std::mem::size_of::<UniformParams>() as u64; | ||
| 158 | let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { | ||
| 159 | label: Some("color-science-bgl"), | ||
| 160 | entries: &[ | ||
| 161 | unfilterable_tex_entry(0), | ||
| 162 | unfilterable_tex_entry(1), | ||
| 163 | unfilterable_tex_entry(2), | ||
| 164 | unfilterable_tex_entry(3), | ||
| 165 | wgpu::BindGroupLayoutEntry { | ||
| 166 | binding: 4, | ||
| 167 | visibility: wgpu::ShaderStages::COMPUTE, | ||
| 168 | ty: wgpu::BindingType::StorageTexture { | ||
| 169 | access: wgpu::StorageTextureAccess::WriteOnly, | ||
| 170 | format, | ||
| 171 | view_dimension: wgpu::TextureViewDimension::D2, | ||
| 172 | }, | ||
| 173 | count: None, | ||
| 174 | }, | ||
| 175 | wgpu::BindGroupLayoutEntry { | ||
| 176 | binding: 5, | ||
| 177 | visibility: wgpu::ShaderStages::COMPUTE, | ||
| 178 | ty: wgpu::BindingType::Buffer { | ||
| 179 | ty: wgpu::BufferBindingType::Uniform, | ||
| 180 | has_dynamic_offset: true, | ||
| 181 | min_binding_size: NonZeroU64::new(u_size), | ||
| 182 | }, | ||
| 183 | count: None, | ||
| 184 | }, | ||
| 185 | ], | ||
| 186 | }); | ||
| 187 | let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { | ||
| 188 | label: Some("color-science-pl"), | ||
| 189 | bind_group_layouts: &[Some(&bgl)], | ||
| 190 | immediate_size: 0, | ||
| 191 | }); | ||
| 192 | let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { | ||
| 193 | label: Some("color-science-wgsl"), | ||
| 194 | source: wgpu::ShaderSource::Wgsl(build_cs_wgsl(format, hdr_float).into()), | ||
| 195 | }); | ||
| 196 | let mk = |entry: &str| { | ||
| 197 | device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { | ||
| 198 | label: Some(entry), | ||
| 199 | layout: Some(&pl), | ||
| 200 | module: &module, | ||
| 201 | entry_point: Some(entry), | ||
| 202 | compilation_options: Default::default(), | ||
| 203 | cache: None, | ||
| 204 | }) | ||
| 205 | }; | ||
| 206 | self.formats.insert( | ||
| 207 | (format, hdr_float), | ||
| 208 | ColorScienceFormatPipelines { | ||
| 209 | bgl, | ||
| 210 | aces_transform: mk("aces_transform_op"), | ||
| 211 | color_space: mk("color_space_op"), | ||
| 212 | color_matrix: mk("color_matrix_op"), | ||
| 213 | white_balance: mk("white_balance_op"), | ||
| 214 | matte_combine: mk("matte_combine_op"), | ||
| 215 | matte_finish: mk("matte_finish_op"), | ||
| 216 | blend_mask: mk("blend_mask_op"), | ||
| 217 | }, | ||
| 218 | ); | ||
| 219 | } | ||
| 220 | |||
| 221 | #[allow(clippy::too_many_arguments)] | ||
| 222 | fn dispatch( | ||
| 223 | &mut self, | ||
| 224 | device: &wgpu::Device, | ||
| 225 | queue: &wgpu::Queue, | ||
| 226 | enc: &mut wgpu::CommandEncoder, | ||
| 227 | op: ColorScienceOp, | ||
| 228 | views: [&wgpu::TextureView; 4], | ||
| 229 | dst: &CachedTexture, | ||
| 230 | params: &UniformParams, | ||
| 231 | ) { | ||
| 232 | let hdr_float = dst.depth.is_float(); | ||
| 233 | self.ensure_format(device, dst.format, hdr_float); | ||
| 234 | let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params); | ||
| 235 | let entry = &self.formats[&(dst.format, hdr_float)]; | ||
| 236 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { | ||
| 237 | label: Some("color-science-bg"), | ||
| 238 | layout: &entry.bgl, | ||
| 239 | entries: &[ | ||
| 240 | wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(views[0]) }, | ||
| 241 | wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(views[1]) }, | ||
| 242 | wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(views[2]) }, | ||
| 243 | wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(views[3]) }, | ||
| 244 | wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(&dst.view) }, | ||
| 245 | wgpu::BindGroupEntry { | ||
| 246 | binding: 5, | ||
| 247 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { | ||
| 248 | buffer: &self.uniform_chunks[chunk_idx], | ||
| 249 | offset: 0, | ||
| 250 | size: NonZeroU64::new(std::mem::size_of::<UniformParams>() as u64), | ||
| 251 | }), | ||
| 252 | }, | ||
| 253 | ], | ||
| 254 | }); | ||
| 255 | let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { | ||
| 256 | label: Some("color-science-pass"), | ||
| 257 | timestamp_writes: None, | ||
| 258 | }); | ||
| 259 | pass.set_pipeline(entry.pipeline(op)); | ||
| 260 | pass.set_bind_group(0, &bg, &[offset]); | ||
| 261 | pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1); | ||
| 262 | } | ||
| 263 | } | ||
| 264 | |||
| 265 | impl Engine { | ||
| 266 | pub(super) fn color_science_pipelines(&self) -> &RefCell<ColorSciencePipelines> { | ||
| 267 | self.color_science_pipelines | ||
| 268 | .get_or_init(|| RefCell::new(ColorSciencePipelines::new(&self.device))) | ||
| 269 | } | ||
| 270 | |||
| 271 | #[allow(clippy::too_many_arguments)] | ||
| 272 | pub(self) fn dispatch_cs( | ||
| 273 | &self, | ||
| 274 | enc: &mut wgpu::CommandEncoder, | ||
| 275 | op: ColorScienceOp, | ||
| 276 | views: [&wgpu::TextureView; 4], | ||
| 277 | dst: &CachedTexture, | ||
| 278 | params: &UniformParams, | ||
| 279 | ) { | ||
| 280 | self.color_science_pipelines() | ||
| 281 | .borrow_mut() | ||
| 282 | .dispatch(&self.device, &self.queue, enc, op, views, dst, params); | ||
| 283 | } | ||
| 284 | |||
| 285 | /// 1. `AcesTransform` — ACES 1.3 IDT/ODT color transform with Bradford D60<->D65, | ||
| 286 | /// Reference Gamut Compression, and RRT+ODT display tone mapping. | ||
| 287 | #[allow(clippy::too_many_arguments)] | ||
| 288 | pub(super) fn eval_aces_transform( | ||
| 289 | &mut self, | ||
| 290 | comp: &Comp, | ||
| 291 | node: &Node, | ||
| 292 | time: f64, | ||
| 293 | frame_i: i64, | ||
| 294 | enc: &mut wgpu::CommandEncoder, | ||
| 295 | visiting: &mut HashSet<(NodeId, i64)>, | ||
| 296 | stats: &mut EvalStats, | ||
| 297 | ) -> CachedTexture { | ||
| 298 | let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { | ||
| 299 | return self.dummy.clone(); | ||
| 300 | }; | ||
| 301 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); | ||
| 302 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; | ||
| 303 | let mbm = self.multiplies_by_mask(comp, node, time); | ||
| 304 | let has_mask = Self::resolve_effect_mask_id(comp, node).is_some(); | ||
| 305 | if blend <= 1e-6 && !(mbm && has_mask) { | ||
| 306 | return src; | ||
| 307 | } | ||
| 308 | let in_space = parse_aces_space(comp, node, "InputTransform", time, &self.expr); | ||
| 309 | let out_space = parse_aces_space(comp, node, "OutputTransform", time, &self.expr); | ||
| 310 | let use_rgc = comp.eval_number(node, "ReferenceGamutCompress", time, 0.0, &self.expr) > 0.5; | ||
| 311 | let luminance = comp.eval_number(node, "Luminance", time, 100.0, &self.expr).clamp(10.0, 10000.0) as f32; | ||
| 312 | |||
| 313 | if in_space == AcesSpace::None && out_space == AcesSpace::None && !use_rgc && !(mbm && has_mask) { | ||
| 314 | return src; | ||
| 315 | } | ||
| 316 | |||
| 317 | let eff_in = if in_space == AcesSpace::None { AcesSpace::Aces2065_1 } else { in_space }; | ||
| 318 | let eff_out = if out_space == AcesSpace::None { AcesSpace::Aces2065_1 } else { out_space }; | ||
| 319 | let use_rrt = matches!(out_space, AcesSpace::Srgb | AcesSpace::Rec709); | ||
| 320 | |||
| 321 | let (m1, m2) = if use_rgc || use_rrt { | ||
| 322 | ( | ||
| 323 | rgb_to_rgb_bradford(eff_in.primaries(), AP1_P), | ||
| 324 | rgb_to_rgb_bradford(AP1_P, eff_out.primaries()), | ||
| 325 | ) | ||
| 326 | } else { | ||
| 327 | ( | ||
| 328 | rgb_to_rgb_bradford(eff_in.primaries(), eff_out.primaries()), | ||
| 329 | [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], | ||
| 330 | ) | ||
| 331 | }; | ||
| 332 | |||
| 333 | let src = if has_mask { self.crop_to_canvas(enc, src) } else { src }; | ||
| 334 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); | ||
| 335 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); | ||
| 336 | let skip = self.process_skip(comp, node, time); | ||
| 337 | |||
| 338 | let mut u = UniformParams::default(); | ||
| 339 | u.p[0] = [ | ||
| 340 | eff_in.transfer_id(), | ||
| 341 | eff_out.transfer_id(), | ||
| 342 | if use_rgc { 1.0 } else { 0.0 }, | ||
| 343 | if use_rrt { 1.0 } else { 0.0 }, | ||
| 344 | ]; | ||
| 345 | u.p[1] = [100.0 / luminance, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }]; | ||
| 346 | u.p[2] = [if mbm { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0]; | ||
| 347 | u.p[3] = skip; | ||
| 348 | u.p[4] = [m1[0][0], m1[0][1], m1[0][2], 0.0]; | ||
| 349 | u.p[5] = [m1[1][0], m1[1][1], m1[1][2], 0.0]; | ||
| 350 | u.p[6] = [m1[2][0], m1[2][1], m1[2][2], 0.0]; | ||
| 351 | u.p[7] = [m2[0][0], m2[0][1], m2[0][2], 0.0]; | ||
| 352 | u.p[8] = [m2[1][0], m2[1][1], m2[1][2], 0.0]; | ||
| 353 | u.p[9] = [m2[2][0], m2[2][1], m2[2][2], 0.0]; | ||
| 354 | |||
| 355 | let key = self.make_key(node, "AcesTransform", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..10])); | ||
| 356 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { | ||
| 357 | stats.cache_hits += 1; | ||
| 358 | return hit; | ||
| 359 | } | ||
| 360 | stats.cache_misses += 1; | ||
| 361 | stats.nodes_evaluated += 1; | ||
| 362 | |||
| 363 | let mut dst = self.alloc_tex_like(&src, src.depth, key); | ||
| 364 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); | ||
| 365 | self.dispatch_cs(enc, ColorScienceOp::AcesTransform, [&src.view, &self.dummy.view, &self.dummy.view, mv], &dst, &u); | ||
| 366 | if src.aux.is_some() { | ||
| 367 | dst.set_aux(src.aux.clone()); | ||
| 368 | } | ||
| 369 | self.cache.insert(key, dst.clone(), node.id, frame_i); | ||
| 370 | dst | ||
| 371 | } | ||
| 372 | |||
| 373 | /// 2. `ColorSpace` — RGB <-> BW / YUV / YIQ / CMY / HLS / HSV / XYZ / CIE-LAB / YCbCr. | ||
| 374 | #[allow(clippy::too_many_arguments)] | ||
| 375 | pub(super) fn eval_color_space( | ||
| 376 | &mut self, | ||
| 377 | comp: &Comp, | ||
| 378 | node: &Node, | ||
| 379 | time: f64, | ||
| 380 | frame_i: i64, | ||
| 381 | enc: &mut wgpu::CommandEncoder, | ||
| 382 | visiting: &mut HashSet<(NodeId, i64)>, | ||
| 383 | stats: &mut EvalStats, | ||
| 384 | ) -> CachedTexture { | ||
| 385 | let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { | ||
| 386 | return self.dummy.clone(); | ||
| 387 | }; | ||
| 388 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); | ||
| 389 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; | ||
| 390 | let mbm = self.multiplies_by_mask(comp, node, time); | ||
| 391 | let has_mask = Self::resolve_effect_mask_id(comp, node).is_some(); | ||
| 392 | let conv_dir = parse_color_space_dir(comp, node, time, &self.expr); | ||
| 393 | let color_type = parse_color_type(comp, node, time, &self.expr); | ||
| 394 | let dst_depth = self.node_depth(comp, node, time, Some(src.depth)); | ||
| 395 | |||
| 396 | if (blend <= 1e-6 || conv_dir == 0) && dst_depth == src.depth && !(mbm && has_mask) { | ||
| 397 | return src; | ||
| 398 | } | ||
| 399 | |||
| 400 | let src = if has_mask { self.crop_to_canvas(enc, src) } else { src }; | ||
| 401 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); | ||
| 402 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); | ||
| 403 | let skip = self.process_skip(comp, node, time); | ||
| 404 | |||
| 405 | let mut u = UniformParams::default(); | ||
| 406 | u.p[0] = [conv_dir as f32, color_type as f32, blend, if mask.is_some() { 1.0 } else { 0.0 }]; | ||
| 407 | u.p[1] = [if mask_inv { 1.0 } else { 0.0 }, if mbm { 1.0 } else { 0.0 }, dst_depth as u32 as f32, 0.0]; | ||
| 408 | u.p[2] = skip; | ||
| 409 | |||
| 410 | let key = self.make_key(node, "ColorSpace", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..3])); | ||
| 411 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { | ||
| 412 | stats.cache_hits += 1; | ||
| 413 | return hit; | ||
| 414 | } | ||
| 415 | stats.cache_misses += 1; | ||
| 416 | stats.nodes_evaluated += 1; | ||
| 417 | |||
| 418 | let mut dst = self.alloc_tex_like(&src, dst_depth, key); | ||
| 419 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); | ||
| 420 | self.dispatch_cs(enc, ColorScienceOp::ColorSpace, [&src.view, &self.dummy.view, &self.dummy.view, mv], &dst, &u); | ||
| 421 | if src.aux.is_some() { | ||
| 422 | dst.set_aux(src.aux.clone()); | ||
| 423 | } | ||
| 424 | self.cache.insert(key, dst.clone(), node.id, frame_i); | ||
| 425 | dst | ||
| 426 | } | ||
| 427 | |||
| 428 | /// 3. `ColorMatrix` — 5x4 RGBA color matrix + offset. | ||
| 429 | #[allow(clippy::too_many_arguments)] | ||
| 430 | pub(super) fn eval_color_matrix( | ||
| 431 | &mut self, | ||
| 432 | comp: &Comp, | ||
| 433 | node: &Node, | ||
| 434 | time: f64, | ||
| 435 | frame_i: i64, | ||
| 436 | enc: &mut wgpu::CommandEncoder, | ||
| 437 | visiting: &mut HashSet<(NodeId, i64)>, | ||
| 438 | stats: &mut EvalStats, | ||
| 439 | ) -> CachedTexture { | ||
| 440 | let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { | ||
| 441 | return self.dummy.clone(); | ||
| 442 | }; | ||
| 443 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); | ||
| 444 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; | ||
| 445 | let mbm = self.multiplies_by_mask(comp, node, time); | ||
| 446 | let has_mask = Self::resolve_effect_mask_id(comp, node).is_some(); | ||
| 447 | if blend <= 1e-6 && !(mbm && has_mask) { | ||
| 448 | return src; | ||
| 449 | } | ||
| 450 | |||
| 451 | let (mat, off) = read_color_matrix(comp, node, time, &self.expr); | ||
| 452 | let prediv = comp.eval_number(node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32; | ||
| 453 | let clip_b = comp.eval_number(node, "ClipBlack", time, 0.0, &self.expr) as f32; | ||
| 454 | let clip_w = comp.eval_number(node, "ClipWhite", time, 0.0, &self.expr) as f32; | ||
| 455 | |||
| 456 | let src = if has_mask { self.crop_to_canvas(enc, src) } else { src }; | ||
| 457 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); | ||
| 458 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); | ||
| 459 | let skip = self.process_skip(comp, node, time); | ||
| 460 | |||
| 461 | let mut u = UniformParams::default(); | ||
| 462 | u.p[0] = mat[0]; | ||
| 463 | u.p[1] = mat[1]; | ||
| 464 | u.p[2] = mat[2]; | ||
| 465 | u.p[3] = mat[3]; | ||
| 466 | u.p[4] = off; | ||
| 467 | u.p[5] = [prediv, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }]; | ||
| 468 | u.p[6] = [if mbm { 1.0 } else { 0.0 }, clip_b, clip_w, 0.0]; | ||
| 469 | u.p[7] = skip; | ||
| 470 | |||
| 471 | let key = self.make_key(node, "ColorMatrix", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..8])); | ||
| 472 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { | ||
| 473 | stats.cache_hits += 1; | ||
| 474 | return hit; | ||
| 475 | } | ||
| 476 | stats.cache_misses += 1; | ||
| 477 | stats.nodes_evaluated += 1; | ||
| 478 | |||
| 479 | let mut dst = self.alloc_tex_like(&src, src.depth, key); | ||
| 480 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); | ||
| 481 | self.dispatch_cs(enc, ColorScienceOp::ColorMatrix, [&src.view, &self.dummy.view, &self.dummy.view, mv], &dst, &u); | ||
| 482 | if src.aux.is_some() { | ||
| 483 | dst.set_aux(src.aux.clone()); | ||
| 484 | } | ||
| 485 | self.cache.insert(key, dst.clone(), node.id, frame_i); | ||
| 486 | dst | ||
| 487 | } | ||
| 488 | |||
| 489 | /// 4. `WhiteBalance` — Kelvin / relative temperature, tint, and sampled white-point gains. | ||
| 490 | #[allow(clippy::too_many_arguments)] | ||
| 491 | pub(super) fn eval_white_balance( | ||
| 492 | &mut self, | ||
| 493 | comp: &Comp, | ||
| 494 | node: &Node, | ||
| 495 | time: f64, | ||
| 496 | frame_i: i64, | ||
| 497 | enc: &mut wgpu::CommandEncoder, | ||
| 498 | visiting: &mut HashSet<(NodeId, i64)>, | ||
| 499 | stats: &mut EvalStats, | ||
| 500 | ) -> CachedTexture { | ||
| 501 | let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { | ||
| 502 | return self.dummy.clone(); | ||
| 503 | }; | ||
| 504 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); | ||
| 505 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; | ||
| 506 | let mbm = self.multiplies_by_mask(comp, node, time); | ||
| 507 | let has_mask = Self::resolve_effect_mask_id(comp, node).is_some(); | ||
| 508 | if blend <= 1e-6 && !(mbm && has_mask) { | ||
| 509 | return src; | ||
| 510 | } | ||
| 511 | |||
| 512 | let temp_raw = if node.inputs.contains_key("Temperature") { | ||
| 513 | comp.eval_number(node, "Temperature", time, 0.0, &self.expr) | ||
| 514 | } else { | ||
| 515 | comp.eval_number(node, "ColorTemperature", time, 0.0, &self.expr) | ||
| 516 | }; | ||
| 517 | let kelvin = if temp_raw > 100.0 { | ||
| 518 | temp_raw.clamp(1667.0, 25000.0) | ||
| 519 | } else { | ||
| 520 | 6500.0 * 2.0_f64.powf(temp_raw.clamp(-2.5, 2.5)) | ||
| 521 | }; | ||
| 522 | let w_ref = kelvin_to_srgb_white(6500.0); | ||
| 523 | let w_cur = kelvin_to_srgb_white(kelvin); | ||
| 524 | let tint = comp.eval_number(node, "Tint", time, 0.0, &self.expr).clamp(-2.0, 2.0); | ||
| 525 | let tint_g = 2.0_f64.powf(-tint * 0.5); | ||
| 526 | |||
| 527 | let mut gain = [w_ref[0] / w_cur[0], (w_ref[1] / w_cur[1]) * tint_g, w_ref[2] / w_cur[2]]; | ||
| 528 | let read_opt = |keys: &[&str], def: f64| -> f64 { | ||
| 529 | for &k in keys { | ||
| 530 | if node.inputs.contains_key(k) { | ||
| 531 | return comp.eval_number(node, k, time, def, &self.expr); | ||
| 532 | } | ||
| 533 | } | ||
| 534 | def | ||
| 535 | }; | ||
| 536 | let lock_ref = comp.eval_number(node, "LockReference", time, 1.0, &self.expr) > 0.5; | ||
| 537 | let rr = read_opt(&["ReferenceRed", "RefRed", "BalanceRed"], 1.0).max(1e-4); | ||
| 538 | let rg = read_opt(&["ReferenceGreen", "RefGreen", "BalanceGreen"], 1.0).max(1e-4); | ||
| 539 | let rb = read_opt(&["ReferenceBlue", "RefBlue", "BalanceBlue"], 1.0).max(1e-4); | ||
| 540 | |||
| 541 | const LUMA: [f64; 3] = [0.2126, 0.7152, 0.0722]; | ||
| 542 | let ref_luma = rr * LUMA[0] + rg * LUMA[1] + rb * LUMA[2]; | ||
| 543 | if lock_ref { | ||
| 544 | gain[0] *= ref_luma / rr; | ||
| 545 | gain[1] *= ref_luma / rg; | ||
| 546 | gain[2] *= ref_luma / rb; | ||
| 547 | } else { | ||
| 548 | let tr = read_opt(&["TargetRed", "WhiteRed"], 1.0).max(1e-4); | ||
| 549 | let tg = read_opt(&["TargetGreen", "WhiteGreen"], 1.0).max(1e-4); | ||
| 550 | let tb = read_opt(&["TargetBlue", "WhiteBlue"], 1.0).max(1e-4); | ||
| 551 | gain[0] *= tr / rr; | ||
| 552 | gain[1] *= tg / rg; | ||
| 553 | gain[2] *= tb / rb; | ||
| 554 | } | ||
| 555 | let g_luma = (gain[0] * LUMA[0] + gain[1] * LUMA[1] + gain[2] * LUMA[2]).max(1e-5); | ||
| 556 | let gain_f32 = [(gain[0] / g_luma) as f32, (gain[1] / g_luma) as f32, (gain[2] / g_luma) as f32]; | ||
| 557 | |||
| 558 | let gamut_str = node.static_str("Gamut").or_else(|| node.static_str("ColorSpace")).unwrap_or(""); | ||
| 559 | let gamma_mode = match gamut_str.to_ascii_lowercase().replace(['.', ' ', '_'], "").as_str() { | ||
| 560 | "srgb" => 1.0_f32, | ||
| 561 | "rec709" => 2.0_f32, | ||
| 562 | _ => 0.0_f32, | ||
| 563 | }; | ||
| 564 | let prediv = comp.eval_number(node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32; | ||
| 565 | |||
| 566 | let src = if has_mask { self.crop_to_canvas(enc, src) } else { src }; | ||
| 567 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); | ||
| 568 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); | ||
| 569 | let skip = self.process_skip(comp, node, time); | ||
| 570 | |||
| 571 | let mut u = UniformParams::default(); | ||
| 572 | u.p[0] = [gain_f32[0], gain_f32[1], gain_f32[2], gamma_mode]; | ||
| 573 | u.p[1] = [prediv, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }]; | ||
| 574 | u.p[2] = [if mbm { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0]; | ||
| 575 | u.p[3] = skip; | ||
| 576 | |||
| 577 | let key = self.make_key(node, "WhiteBalance", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..4])); | ||
| 578 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { | ||
| 579 | stats.cache_hits += 1; | ||
| 580 | return hit; | ||
| 581 | } | ||
| 582 | stats.cache_misses += 1; | ||
| 583 | stats.nodes_evaluated += 1; | ||
| 584 | |||
| 585 | let mut dst = self.alloc_tex_like(&src, src.depth, key); | ||
| 586 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); | ||
| 587 | self.dispatch_cs(enc, ColorScienceOp::WhiteBalance, [&src.view, &self.dummy.view, &self.dummy.view, mv], &dst, &u); | ||
| 588 | if src.aux.is_some() { | ||
| 589 | dst.set_aux(src.aux.clone()); | ||
| 590 | } | ||
| 591 | self.cache.insert(key, dst.clone(), node.id, frame_i); | ||
| 592 | dst | ||
| 593 | } | ||
| 594 | } | ||
crates/engine/src/eval/color_science/matte_merge.rs created+336| ... | @@ -0,0 +1,336 @@ | ||
| 1 | //! `MatteControl` and `MultiMerge` / `Fuse.MultiMerge` GPU evaluators. | ||
| 2 | |||
| 3 | use super::params::*; | ||
| 4 | use super::ColorScienceOp; | ||
| 5 | use crate::eval::*; | ||
| 6 | |||
| 7 | impl Engine { | ||
| 8 | /// 5. `MatteControl` — matte combine, contract/expand, blur, threshold, gamma, invert, | ||
| 9 | /// garbage/solid mattes, spill suppression, and post-multiply. | ||
| 10 | #[allow(clippy::too_many_arguments)] | ||
| 11 | pub(in crate::eval) fn eval_matte_control( | ||
| 12 | &mut self, | ||
| 13 | comp: &Comp, | ||
| 14 | node: &Node, | ||
| 15 | time: f64, | ||
| 16 | frame_i: i64, | ||
| 17 | enc: &mut wgpu::CommandEncoder, | ||
| 18 | visiting: &mut HashSet<(NodeId, i64)>, | ||
| 19 | stats: &mut EvalStats, | ||
| 20 | ) -> CachedTexture { | ||
| 21 | let Some(bg_id) = node | ||
| 22 | .connected_node("Background") | ||
| 23 | .or_else(|| node.connected_node("Input")) | ||
| 24 | .and_then(|s| comp.find_node(s)) | ||
| 25 | else { | ||
| 26 | return self.dummy.clone(); | ||
| 27 | }; | ||
| 28 | let bg = self.eval_node(comp, bg_id, time, enc, visiting, stats); | ||
| 29 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr).clamp(0.0, 1.0) as f32; | ||
| 30 | let mbm = self.multiplies_by_mask(comp, node, time); | ||
| 31 | let has_mask = Self::resolve_effect_mask_id(comp, node).is_some(); | ||
| 32 | if blend <= 1e-6 && !(mbm && has_mask) { | ||
| 33 | return bg; | ||
| 34 | } | ||
| 35 | let bg = self.crop_to_canvas(enc, bg); | ||
| 36 | |||
| 37 | let fg = node | ||
| 38 | .connected_node("Foreground") | ||
| 39 | .and_then(|s| comp.find_node(s)) | ||
| 40 | .map(|fid| self.eval_node(comp, fid, time, enc, visiting, stats)) | ||
| 41 | .map(|t| self.crop_to_canvas(enc, t)); | ||
| 42 | |||
| 43 | let prev_sz = self.mask_target_size; | ||
| 44 | self.mask_target_size = Some(bg.size); | ||
| 45 | let garbage = node | ||
| 46 | .connected_node("Garbage.Matte") | ||
| 47 | .or_else(|| node.connected_node("GarbageMatte")) | ||
| 48 | .and_then(|s| comp.find_node(s)) | ||
| 49 | .map(|gid| self.eval_node(comp, gid, time, enc, visiting, stats)) | ||
| 50 | .map(|m| self.crop_to_canvas(enc, m)); | ||
| 51 | let solid = node | ||
| 52 | .connected_node("Solid.Matte") | ||
| 53 | .or_else(|| node.connected_node("SolidMatte")) | ||
| 54 | .and_then(|s| comp.find_node(s)) | ||
| 55 | .map(|sid| self.eval_node(comp, sid, time, enc, visiting, stats)) | ||
| 56 | .map(|m| self.crop_to_canvas(enc, m)); | ||
| 57 | self.mask_target_size = prev_sz; | ||
| 58 | |||
| 59 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(bg.size), enc, visiting, stats); | ||
| 60 | |||
| 61 | let matte_combine = parse_matte_combine(comp, node, time, &self.expr); | ||
| 62 | let combine_op = parse_combine_op(comp, node, time, &self.expr); | ||
| 63 | let inv_fg = if comp.eval_number(node, "InvertCombineMatte", time, 0.0, &self.expr) > 0.5 | ||
| 64 | || comp.eval_number(node, "InvertForeground", time, 0.0, &self.expr) > 0.5 | ||
| 65 | { | ||
| 66 | 1.0_f32 | ||
| 67 | } else { | ||
| 68 | 0.0_f32 | ||
| 69 | }; | ||
| 70 | let contract_expand = if node.inputs.contains_key("MatteContractExpand") { | ||
| 71 | comp.eval_number(node, "MatteContractExpand", time, 0.0, &self.expr) | ||
| 72 | } else { | ||
| 73 | comp.eval_number(node, "ContractExpand", time, 0.0, &self.expr) | ||
| 74 | } as f32; | ||
| 75 | let matte_blur = comp.eval_number(node, "MatteBlur", time, 0.0, &self.expr).max(0.0) as f32; | ||
| 76 | let thresh_lo = if node.inputs.contains_key("MatteThresholdLow") { | ||
| 77 | comp.eval_number(node, "MatteThresholdLow", time, 0.0, &self.expr) | ||
| 78 | } else { | ||
| 79 | comp.eval_number(node, "LowThreshold", time, 0.0, &self.expr) | ||
| 80 | } as f32; | ||
| 81 | let thresh_hi = if node.inputs.contains_key("MatteThresholdHigh") { | ||
| 82 | comp.eval_number(node, "MatteThresholdHigh", time, 1.0, &self.expr) | ||
| 83 | } else { | ||
| 84 | comp.eval_number(node, "HighThreshold", time, 1.0, &self.expr) | ||
| 85 | } as f32; | ||
| 86 | let matte_gamma = comp.eval_number(node, "MatteGamma", time, 1.0, &self.expr).max(1e-4) as f32; | ||
| 87 | let invert_matte = if comp.eval_number(node, "InvertMatte", time, 0.0, &self.expr) > 0.5 { 1.0 } else { 0.0 }; | ||
| 88 | let garbage_inv = if comp.eval_number(node, "Garbage.MaskInverted", time, 0.0, &self.expr) > 0.5 { 1.0 } else { 0.0 }; | ||
| 89 | let solid_inv = if comp.eval_number(node, "Solid.MaskInverted", time, 0.0, &self.expr) > 0.5 { 1.0 } else { 0.0 }; | ||
| 90 | let post_mult = if comp.eval_number(node, "PostMultiplyImage", time, 0.0, &self.expr) > 0.5 { 1.0 } else { 0.0 }; | ||
| 91 | let spill_sup = comp.eval_number(node, "SpillSuppression", time, 0.0, &self.expr).clamp(0.0, 1.0) as f32; | ||
| 92 | let spill_col = match node.static_str("SpillColor") { | ||
| 93 | Some(s) if s.eq_ignore_ascii_case("blue") => 1.0, | ||
| 94 | Some(s) if s.eq_ignore_ascii_case("red") => 2.0, | ||
| 95 | Some(_) => 0.0, | ||
| 96 | None => comp.eval_number(node, "SpillColor", time, 0.0, &self.expr).round().clamp(0.0, 2.0) as f32, | ||
| 97 | }; | ||
| 98 | let skip = self.process_skip(comp, node, time); | ||
| 99 | |||
| 100 | let key_floats: [f32; 20] = [ | ||
| 101 | matte_combine as f32, combine_op as f32, inv_fg, contract_expand, | ||
| 102 | matte_blur, thresh_lo, thresh_hi, matte_gamma, | ||
| 103 | invert_matte, garbage_inv, solid_inv, post_mult, | ||
| 104 | spill_sup, spill_col, blend, if mask_inv { 1.0 } else { 0.0 }, | ||
| 105 | skip[0], skip[1], skip[2], skip[3], | ||
| 106 | ]; | ||
| 107 | let hashes = [ | ||
| 108 | bg.content_hash, | ||
| 109 | fg.as_ref().map_or(0, |t| t.content_hash), | ||
| 110 | garbage.as_ref().map_or(0, |t| t.content_hash), | ||
| 111 | solid.as_ref().map_or(0, |t| t.content_hash), | ||
| 112 | mask.as_ref().map_or(0, |t| t.content_hash), | ||
| 113 | if mbm { 1 } else { 0 }, | ||
| 114 | ]; | ||
| 115 | let key = self.make_key(node, "MatteControl", bg.size, &hashes, bytemuck::cast_slice(&key_floats)); | ||
| 116 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { | ||
| 117 | stats.cache_hits += 1; | ||
| 118 | return hit; | ||
| 119 | } | ||
| 120 | stats.cache_misses += 1; | ||
| 121 | stats.nodes_evaluated += 1; | ||
| 122 | |||
| 123 | let mut matte = self.alloc_tex(bg.size, bg.depth, 0); | ||
| 124 | let mut u0 = UniformParams::default(); | ||
| 125 | u0.p[0] = [0.0, matte_combine as f32, combine_op as f32, if fg.is_some() { 1.0 } else { 0.0 }]; | ||
| 126 | u0.p[1] = [inv_fg, 0.0, 0.0, 0.0]; | ||
| 127 | let fg_view = fg.as_ref().map_or(&self.dummy.view, |t| &t.view); | ||
| 128 | self.dispatch_cs(enc, ColorScienceOp::MatteCombine, [&bg.view, fg_view, &self.dummy.view, &self.dummy.view], &matte, &u0); | ||
| 129 | |||
| 130 | if contract_expand.abs() > 1e-6 { | ||
| 131 | matte = self.morpho_tex(enc, &matte, contract_expand * bg.size[0] as f32); | ||
| 132 | } | ||
| 133 | if matte_blur > 1e-4 { | ||
| 134 | matte = self.blur_separable(enc, &matte, matte_blur, matte_blur, 0.0, 1.0); | ||
| 135 | } | ||
| 136 | |||
| 137 | let refined = self.alloc_tex(bg.size, bg.depth, 0); | ||
| 138 | let mut u1 = UniformParams::default(); | ||
| 139 | u1.p[0] = [1.0, thresh_lo, thresh_hi, matte_gamma]; | ||
| 140 | u1.p[1] = [invert_matte, if garbage.is_some() { 1.0 } else { 0.0 }, garbage_inv, if solid.is_some() { 1.0 } else { 0.0 }]; | ||
| 141 | u1.p[2] = [solid_inv, 0.0, 0.0, 0.0]; | ||
| 142 | let gv = garbage.as_ref().map_or(&self.dummy.view, |m| &m.view); | ||
| 143 | let sv = solid.as_ref().map_or(&self.dummy.view, |m| &m.view); | ||
| 144 | self.dispatch_cs(enc, ColorScienceOp::MatteCombine, [&matte.view, &self.dummy.view, gv, sv], &refined, &u1); | ||
| 145 | |||
| 146 | let mut dst = self.alloc_tex_like(&bg, bg.depth, key); | ||
| 147 | let mut u2 = UniformParams::default(); | ||
| 148 | u2.p[0] = [spill_sup, spill_col, post_mult, blend]; | ||
| 149 | u2.p[1] = [if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, if mbm { 1.0 } else { 0.0 }, 0.0]; | ||
| 150 | u2.p[2] = skip; | ||
| 151 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); | ||
| 152 | self.dispatch_cs(enc, ColorScienceOp::MatteFinish, [&bg.view, &refined.view, &self.dummy.view, mv], &dst, &u2); | ||
| 153 | if bg.aux.is_some() { | ||
| 154 | dst.set_aux(bg.aux.clone()); | ||
| 155 | } | ||
| 156 | self.cache.insert(key, dst.clone(), node.id, frame_i); | ||
| 157 | dst | ||
| 158 | } | ||
| 159 | |||
| 160 | /// 6. `MultiMerge` & `Fuse.MultiMerge` — N-layer merge reusing `ShaderOp::Merge`. | ||
| 161 | #[allow(clippy::too_many_arguments)] | ||
| 162 | pub(in crate::eval) fn eval_multi_merge( | ||
| 163 | &mut self, | ||
| 164 | comp: &Comp, | ||
| 165 | node: &Node, | ||
| 166 | time: f64, | ||
| 167 | frame_i: i64, | ||
| 168 | enc: &mut wgpu::CommandEncoder, | ||
| 169 | visiting: &mut HashSet<(NodeId, i64)>, | ||
| 170 | stats: &mut EvalStats, | ||
| 171 | ) -> CachedTexture { | ||
| 172 | let Some(bg_id) = node | ||
| 173 | .connected_node("Background") | ||
| 174 | .or_else(|| node.connected_node("Input")) | ||
| 175 | .and_then(|s| comp.find_node(s)) | ||
| 176 | else { | ||
| 177 | return self.dummy.clone(); | ||
| 178 | }; | ||
| 179 | let bg = self.eval_node(comp, bg_id, time, enc, visiting, stats); | ||
| 180 | let global_blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr).clamp(0.0, 1.0) as f32; | ||
| 181 | let global_mbm = self.multiplies_by_mask(comp, node, time); | ||
| 182 | let has_global_mask = Self::resolve_effect_mask_id(comp, node).is_some(); | ||
| 183 | if global_blend <= 1e-6 && !(global_mbm && has_global_mask) { | ||
| 184 | stats.pruned_branches += 1; | ||
| 185 | return bg; | ||
| 186 | } | ||
| 187 | |||
| 188 | let layers = discover_multimerge_layers(node); | ||
| 189 | let mut acc = bg.clone(); | ||
| 190 | |||
| 191 | for idx in layers { | ||
| 192 | let pfx = format!("Layer{idx}"); | ||
| 193 | let enabled = { | ||
| 194 | let k1 = format!("LayerEnabled{idx}"); | ||
| 195 | let k2 = format!("{pfx}.Enabled"); | ||
| 196 | let k3 = format!("{pfx}.LayerEnabled"); | ||
| 197 | if node.inputs.contains_key(&k1) { | ||
| 198 | comp.eval_number(node, &k1, time, 1.0, &self.expr) > 0.5 | ||
| 199 | } else if node.inputs.contains_key(&k2) { | ||
| 200 | comp.eval_number(node, &k2, time, 1.0, &self.expr) > 0.5 | ||
| 201 | } else if node.inputs.contains_key(&k3) { | ||
| 202 | comp.eval_number(node, &k3, time, 1.0, &self.expr) > 0.5 | ||
| 203 | } else { | ||
| 204 | true | ||
| 205 | } | ||
| 206 | }; | ||
| 207 | if !enabled { | ||
| 208 | continue; | ||
| 209 | } | ||
| 210 | |||
| 211 | let fg_id = node | ||
| 212 | .connected_node(&format!("{pfx}.Foreground")) | ||
| 213 | .or_else(|| node.connected_node(&pfx)) | ||
| 214 | .or_else(|| node.connected_node(&format!("Foreground{idx}"))) | ||
| 215 | .and_then(|s| comp.find_node(s)); | ||
| 216 | let Some(fid) = fg_id else { | ||
| 217 | continue; | ||
| 218 | }; | ||
| 219 | |||
| 220 | let l_blend = eval_layer_num(comp, node, idx, "Blend", 1.0, time, &self.expr).clamp(0.0, 1.0); | ||
| 221 | let l_mbm = eval_layer_num(comp, node, idx, "MultiplyByMask", 0.0, time, &self.expr) > 0.5; | ||
| 222 | let l_mask_id = node | ||
| 223 | .connected_node(&format!("{pfx}.EffectMask")) | ||
| 224 | .or_else(|| node.connected_node(&format!("{pfx}.Mask"))) | ||
| 225 | .or_else(|| node.connected_node(&format!("EffectMask{idx}"))) | ||
| 226 | .and_then(|s| comp.find_node(s)); | ||
| 227 | if l_blend <= 1e-6 && !(l_mbm && l_mask_id.is_some()) { | ||
| 228 | stats.pruned_branches += 1; | ||
| 229 | continue; | ||
| 230 | } | ||
| 231 | |||
| 232 | let fg = self.eval_node(comp, fid, time, enc, visiting, stats); | ||
| 233 | let l_mask = l_mask_id.map(|mid| { | ||
| 234 | let prev = self.mask_target_size; | ||
| 235 | self.mask_target_size = Some(acc.canvas_size); | ||
| 236 | let m = self.eval_node(comp, mid, time, enc, visiting, stats); | ||
| 237 | self.mask_target_size = prev; | ||
| 238 | m | ||
| 239 | }); | ||
| 240 | let l_mask_inv = eval_layer_num(comp, node, idx, "ApplyMaskInverted", 0.0, time, &self.expr) > 0.5; | ||
| 241 | let l_mask_hash = l_mask.as_ref().map_or(0, |m| m.content_hash); | ||
| 242 | |||
| 243 | let center = { | ||
| 244 | let k1 = format!("{pfx}.Center"); | ||
| 245 | let k2 = format!("Center{idx}"); | ||
| 246 | if node.inputs.contains_key(&k1) { | ||
| 247 | comp.eval_point(node, &k1, time, [0.5, 0.5], &self.expr) | ||
| 248 | } else if node.inputs.contains_key(&k2) { | ||
| 249 | comp.eval_point(node, &k2, time, [0.5, 0.5], &self.expr) | ||
| 250 | } else { | ||
| 251 | [0.5, 0.5] | ||
| 252 | } | ||
| 253 | }; | ||
| 254 | let size_s = eval_layer_num(comp, node, idx, "Size", 1.0, time, &self.expr); | ||
| 255 | let angle_deg = eval_layer_num(comp, node, idx, "Angle", 0.0, time, &self.expr); | ||
| 256 | let gain = eval_layer_num(comp, node, idx, "Gain", 1.0, time, &self.expr).clamp(0.0, 1.0); | ||
| 257 | let burn_in = eval_layer_num(comp, node, idx, "BurnIn", 0.0, time, &self.expr); | ||
| 258 | let sub_add = eval_layer_num(comp, node, idx, "SubtractiveAdditive", 1.0, time, &self.expr); | ||
| 259 | let edges = eval_layer_num(comp, node, idx, "Edges", 0.0, time, &self.expr); | ||
| 260 | let flip_h = eval_layer_num(comp, node, idx, "FlipHoriz", 0.0, time, &self.expr); | ||
| 261 | let flip_v = eval_layer_num(comp, node, idx, "FlipVert", 0.0, time, &self.expr); | ||
| 262 | let nearest = if eval_layer_num(comp, node, idx, "FilterMethod", 2.0, time, &self.expr) < 0.5 { 1.0 } else { 0.0 }; | ||
| 263 | let mode_id = layer_str(node, idx, "ApplyMode") | ||
| 264 | .map(parse_apply_mode_str) | ||
| 265 | .unwrap_or_else(|| eval_layer_num(comp, node, idx, "ApplyMode", 0.0, time, &self.expr).round().clamp(0.0, 24.0)); | ||
| 266 | let op_id = layer_str(node, idx, "Operator") | ||
| 267 | .map(parse_operator_str) | ||
| 268 | .unwrap_or_else(|| eval_layer_num(comp, node, idx, "Operator", 0.0, time, &self.expr).round().clamp(0.0, 5.0)); | ||
| 269 | |||
| 270 | let eff_size = size_s * (acc.tex_scale / fg.tex_scale.max(1e-4)); | ||
| 271 | let mut u = UniformParams::default(); | ||
| 272 | u.p[0] = [center[0] as f32, center[1] as f32, eff_size, angle_deg.to_radians()]; | ||
| 273 | u.p[1] = [l_blend, gain, mode_id, edges]; | ||
| 274 | u.p[2] = [flip_h, flip_v, nearest, op_id]; | ||
| 275 | u.p[3] = [ | ||
| 276 | if l_mask.is_some() { 1.0 } else { 0.0 }, | ||
| 277 | if l_mask_inv { 1.0 } else { 0.0 }, | ||
| 278 | fg.canvas_size[0] as f32, | ||
| 279 | fg.canvas_size[1] as f32, | ||
| 280 | ]; | ||
| 281 | if fg.has_dod() { | ||
| 282 | u.p[4] = [fg.origin[0] as f32, fg.origin[1] as f32, fg.canvas_size[0] as f32, fg.canvas_size[1] as f32]; | ||
| 283 | } | ||
| 284 | if acc.has_dod() { | ||
| 285 | u.p[5] = [acc.origin[0] as f32, acc.origin[1] as f32, acc.canvas_size[0] as f32, acc.canvas_size[1] as f32]; | ||
| 286 | } | ||
| 287 | u.p[6] = [burn_in, sub_add, 0.0, 0.0]; | ||
| 288 | u.p[7] = [if l_mbm { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0]; | ||
| 289 | |||
| 290 | let layer_tag = format!("MultiMergeL{idx}"); | ||
| 291 | let key = self.make_key(node, &layer_tag, acc.size, &[acc.content_hash, fg.content_hash, l_mask_hash], bytemuck::cast_slice(&u.p[..8])); | ||
| 292 | acc = if let Some(hit) = self.cache.get(key, node.id, frame_i) { | ||
| 293 | stats.cache_hits += 1; | ||
| 294 | hit | ||
| 295 | } else { | ||
| 296 | stats.cache_misses += 1; | ||
| 297 | stats.nodes_evaluated += 1; | ||
| 298 | let mut dst = self.alloc_tex_dod(acc.size, acc.origin, acc.canvas_size, acc.depth.max(fg.depth), key); | ||
| 299 | dst.tex_scale = acc.tex_scale; | ||
| 300 | let mv = l_mask.as_ref().map_or(&self.dummy.view, |m| &m.view); | ||
| 301 | self.dispatch_op(enc, ShaderOp::Merge, &acc.view, &fg.view, mv, &dst, &u); | ||
| 302 | self.cache.insert(key, dst.clone(), node.id, frame_i); | ||
| 303 | dst | ||
| 304 | }; | ||
| 305 | } | ||
| 306 | |||
| 307 | if global_blend < 1.0 - 1e-6 || has_global_mask { | ||
| 308 | let bg_c = self.crop_to_canvas(enc, bg.clone()); | ||
| 309 | let acc_c = self.crop_to_canvas(enc, acc); | ||
| 310 | let (g_mask, g_mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(bg_c.size), enc, visiting, stats); | ||
| 311 | let g_mask_hash = g_mask.as_ref().map_or(0, |m| m.content_hash); | ||
| 312 | let skip = self.process_skip(comp, node, time); | ||
| 313 | let mut u = UniformParams::default(); | ||
| 314 | u.p[0] = [global_blend, if g_mask.is_some() { 1.0 } else { 0.0 }, if g_mask_inv { 1.0 } else { 0.0 }, if global_mbm { 1.0 } else { 0.0 }]; | ||
| 315 | u.p[1] = skip; | ||
| 316 | let key = self.make_key(node, "MultiMergeBlend", acc_c.size, &[bg_c.content_hash, acc_c.content_hash, g_mask_hash], bytemuck::cast_slice(&u.p[..2])); | ||
| 317 | acc = if let Some(hit) = self.cache.get(key, node.id, frame_i) { | ||
| 318 | stats.cache_hits += 1; | ||
| 319 | hit | ||
| 320 | } else { | ||
| 321 | stats.cache_misses += 1; | ||
| 322 | stats.nodes_evaluated += 1; | ||
| 323 | let dst = self.alloc_tex_like(&acc_c, acc_c.depth, key); | ||
| 324 | let mv = g_mask.as_ref().map_or(&self.dummy.view, |m| &m.view); | ||
| 325 | self.dispatch_cs(enc, ColorScienceOp::BlendMask, [&bg_c.view, &acc_c.view, &self.dummy.view, mv], &dst, &u); | ||
| 326 | self.cache.insert(key, dst.clone(), node.id, frame_i); | ||
| 327 | dst | ||
| 328 | }; | ||
| 329 | } | ||
| 330 | |||
| 331 | if bg.aux.is_some() && acc.size == bg.size && acc.origin == bg.origin && acc.aux.is_none() { | ||
| 332 | acc.set_aux(bg.aux.clone()); | ||
| 333 | } | ||
| 334 | acc | ||
| 335 | } | ||
| 336 | } | ||
crates/engine/src/eval/color_science/params.rs created+454| ... | @@ -0,0 +1,454 @@ | ||
| 1 | //! Colorimetry math (ACES 1.3 Bradford matrices, Planckian locus) and parameter parsers | ||
| 2 | //! for Wave 36 color science, `MatteControl`, and `MultiMerge` evaluators. | ||
| 3 | |||
| 4 | use model::{Comp, ExprEngine, LuaKey, LuaValue, Node, ParamValue}; | ||
| 5 | |||
| 6 | pub(super) const D60: [f64; 2] = [0.32168, 0.33767]; | ||
| 7 | pub(super) const D65: [f64; 2] = [0.3127, 0.3290]; | ||
| 8 | pub(super) const AP0_P: [[f64; 2]; 4] = [[0.7347, 0.2653], [0.0, 1.0], [0.0001, -0.0770], D60]; | ||
| 9 | pub(super) const AP1_P: [[f64; 2]; 4] = [[0.713, 0.293], [0.165, 0.830], [0.128, 0.044], D60]; | ||
| 10 | pub(super) const SRGB_P: [[f64; 2]; 4] = [[0.64, 0.33], [0.30, 0.60], [0.15, 0.06], D65]; | ||
| 11 | |||
| 12 | const BRADFORD: [[f64; 3]; 3] = [ | ||
| 13 | [0.8951, 0.2664, -0.1614], | ||
| 14 | [-0.7502, 1.7135, 0.0367], | ||
| 15 | [0.0389, -0.0685, 1.0296], | ||
| 16 | ]; | ||
| 17 | |||
| 18 | fn mat3_inv(m: [[f64; 3]; 3]) -> [[f64; 3]; 3] { | ||
| 19 | let [a, b, c] = m[0]; | ||
| 20 | let [d, e, f] = m[1]; | ||
| 21 | let [g, h, i] = m[2]; | ||
| 22 | let det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g); | ||
| 23 | let inv = if det.abs() > 1e-12 { 1.0 / det } else { 0.0 }; | ||
| 24 | [ | ||
| 25 | [(e * i - f * h) * inv, (c * h - b * i) * inv, (b * f - c * e) * inv], | ||
| 26 | [(f * g - d * i) * inv, (a * i - c * g) * inv, (c * d - a * f) * inv], | ||
| 27 | [(d * h - e * g) * inv, (b * g - a * h) * inv, (a * e - b * d) * inv], | ||
| 28 | ] | ||
| 29 | } | ||
| 30 | |||
| 31 | fn mat3_mul(a: [[f64; 3]; 3], b: [[f64; 3]; 3]) -> [[f64; 3]; 3] { | ||
| 32 | std::array::from_fn(|r| std::array::from_fn(|c| (0..3).map(|k| a[r][k] * b[k][c]).sum())) | ||
| 33 | } | ||
| 34 | |||
| 35 | fn mat3_vec(m: [[f64; 3]; 3], v: [f64; 3]) -> [f64; 3] { | ||
| 36 | std::array::from_fn(|r| (0..3).map(|c| m[r][c] * v[c]).sum()) | ||
| 37 | } | ||
| 38 | |||
| 39 | fn xy_to_xyz(xy: [f64; 2]) -> [f64; 3] { | ||
| 40 | let y = xy[1].max(1e-6); | ||
| 41 | [xy[0] / y, 1.0, (1.0 - xy[0] - xy[1]) / y] | ||
| 42 | } | ||
| 43 | |||
| 44 | fn primaries_to_xyz(p: [[f64; 2]; 4]) -> [[f64; 3]; 3] { | ||
| 45 | let [xr, xg, xb, xw] = [xy_to_xyz(p[0]), xy_to_xyz(p[1]), xy_to_xyz(p[2]), xy_to_xyz(p[3])]; | ||
| 46 | let base = [[xr[0], xg[0], xb[0]], [xr[1], xg[1], xb[1]], [xr[2], xg[2], xb[2]]]; | ||
| 47 | let s = mat3_vec(mat3_inv(base), xw); | ||
| 48 | std::array::from_fn(|r| std::array::from_fn(|c| base[r][c] * s[c])) | ||
| 49 | } | ||
| 50 | |||
| 51 | pub(super) fn rgb_to_rgb_bradford(src: [[f64; 2]; 4], dst: [[f64; 2]; 4]) -> [[f32; 3]; 3] { | ||
| 52 | if src == dst { | ||
| 53 | return [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]; | ||
| 54 | } | ||
| 55 | let m_src = primaries_to_xyz(src); | ||
| 56 | let m_dst_inv = mat3_inv(primaries_to_xyz(dst)); | ||
| 57 | let m = if (src[3][0] - dst[3][0]).abs() > 1e-6 || (src[3][1] - dst[3][1]).abs() > 1e-6 { | ||
| 58 | let cs = mat3_vec(BRADFORD, xy_to_xyz(src[3])); | ||
| 59 | let cd = mat3_vec(BRADFORD, xy_to_xyz(dst[3])); | ||
| 60 | let diag = [ | ||
| 61 | [cd[0] / cs[0].max(1e-6), 0.0, 0.0], | ||
| 62 | [0.0, cd[1] / cs[1].max(1e-6), 0.0], | ||
| 63 | [0.0, 0.0, cd[2] / cs[2].max(1e-6)], | ||
| 64 | ]; | ||
| 65 | let adapt = mat3_mul(mat3_inv(BRADFORD), mat3_mul(diag, BRADFORD)); | ||
| 66 | mat3_mul(m_dst_inv, mat3_mul(adapt, m_src)) | ||
| 67 | } else { | ||
| 68 | mat3_mul(m_dst_inv, m_src) | ||
| 69 | }; | ||
| 70 | std::array::from_fn(|r| std::array::from_fn(|c| m[r][c] as f32)) | ||
| 71 | } | ||
| 72 | |||
| 73 | #[derive(Clone, Copy, PartialEq, Eq)] | ||
| 74 | pub(super) enum AcesSpace { | ||
| 75 | None, | ||
| 76 | Aces2065_1, | ||
| 77 | AcesCg, | ||
| 78 | AcesCct, | ||
| 79 | AcesCc, | ||
| 80 | LinearSrgb, | ||
| 81 | Srgb, | ||
| 82 | Rec709, | ||
| 83 | } | ||
| 84 | |||
| 85 | impl AcesSpace { | ||
| 86 | pub(super) fn primaries(self) -> [[f64; 2]; 4] { | ||
| 87 | match self { | ||
| 88 | Self::None | Self::Aces2065_1 => AP0_P, | ||
| 89 | Self::AcesCg | Self::AcesCct | Self::AcesCc => AP1_P, | ||
| 90 | Self::LinearSrgb | Self::Srgb | Self::Rec709 => SRGB_P, | ||
| 91 | } | ||
| 92 | } | ||
| 93 | |||
| 94 | pub(super) fn transfer_id(self) -> f32 { | ||
| 95 | match self { | ||
| 96 | Self::AcesCct => 1.0, | ||
| 97 | Self::AcesCc => 2.0, | ||
| 98 | Self::Srgb => 3.0, | ||
| 99 | Self::Rec709 => 4.0, | ||
| 100 | _ => 0.0, | ||
| 101 | } | ||
| 102 | } | ||
| 103 | } | ||
| 104 | |||
| 105 | pub(super) fn parse_aces_space( | ||
| 106 | comp: &Comp, | ||
| 107 | node: &Node, | ||
| 108 | param: &str, | ||
| 109 | time: f64, | ||
| 110 | expr: &ExprEngine, | ||
| 111 | ) -> AcesSpace { | ||
| 112 | if let Some(raw) = node.static_str(param) { | ||
| 113 | let s: String = raw | ||
| 114 | .to_ascii_lowercase() | ||
| 115 | .chars() | ||
| 116 | .filter(|c| c.is_ascii_alphanumeric()) | ||
| 117 | .collect(); | ||
| 118 | let s = s.strip_prefix("idt").or_else(|| s.strip_prefix("odt")).unwrap_or(&s); | ||
| 119 | if s.is_empty() | ||
| 120 | || s.contains("notransform") | ||
| 121 | || s.contains("noinput") | ||
| 122 | || s.contains("nooutput") | ||
| 123 | || s == "none" | ||
| 124 | || s == "nochange" | ||
| 125 | { | ||
| 126 | return AcesSpace::None; | ||
| 127 | } | ||
| 128 | if s.contains("acescct") { | ||
| 129 | return AcesSpace::AcesCct; | ||
| 130 | } | ||
| 131 | if s.contains("acescc") { | ||
| 132 | return AcesSpace::AcesCc; | ||
| 133 | } | ||
| 134 | if s.contains("acescg") || s == "ap1" { | ||
| 135 | return AcesSpace::AcesCg; | ||
| 136 | } | ||
| 137 | if s.contains("aces2065") || s == "aces" || s == "ap0" { | ||
| 138 | return AcesSpace::Aces2065_1; | ||
| 139 | } | ||
| 140 | if s.contains("linear") && (s.contains("srgb") || s.contains("709")) { | ||
| 141 | return AcesSpace::LinearSrgb; | ||
| 142 | } | ||
| 143 | if s.contains("srgb") { | ||
| 144 | return AcesSpace::Srgb; | ||
| 145 | } | ||
| 146 | if s.contains("709") { | ||
| 147 | return AcesSpace::Rec709; | ||
| 148 | } | ||
| 149 | return AcesSpace::None; | ||
| 150 | } | ||
| 151 | match comp.eval_number(node, param, time, 0.0, expr).round() as i32 { | ||
| 152 | 1 => AcesSpace::Aces2065_1, | ||
| 153 | 2 => AcesSpace::AcesCg, | ||
| 154 | 3 => AcesSpace::AcesCct, | ||
| 155 | 4 => AcesSpace::AcesCc, | ||
| 156 | 5 => AcesSpace::LinearSrgb, | ||
| 157 | 6 => AcesSpace::Srgb, | ||
| 158 | 7 => AcesSpace::Rec709, | ||
| 159 | _ => AcesSpace::None, | ||
| 160 | } | ||
| 161 | } | ||
| 162 | |||
| 163 | /// Kang et al. (2002) Planckian locus chromaticity `xy(T)` for `1667K..25000K`. | ||
| 164 | fn kelvin_to_xy(t_in: f64) -> [f64; 2] { | ||
| 165 | let t = t_in.clamp(1667.0, 25000.0); | ||
| 166 | let x = if t <= 4000.0 { | ||
| 167 | -0.2661239e9 / (t * t * t) - 0.2343589e6 / (t * t) + 0.8776956e3 / t + 0.179910 | ||
| 168 | } else { | ||
| 169 | -3.0258469e9 / (t * t * t) + 2.1070379e6 / (t * t) + 0.2226347e3 / t + 0.240390 | ||
| 170 | }; | ||
| 171 | let y = if t <= 2222.0 { | ||
| 172 | -1.1063814 * x * x * x - 1.34811020 * x * x + 2.18555832 * x - 0.20219683 | ||
| 173 | } else if t <= 4000.0 { | ||
| 174 | -0.9549476 * x * x * x - 1.37418593 * x * x + 2.09137015 * x - 0.16748867 | ||
| 175 | } else { | ||
| 176 | 3.0817580 * x * x * x - 5.87338670 * x * x + 3.75112997 * x - 0.37001483 | ||
| 177 | }; | ||
| 178 | [x, y] | ||
| 179 | } | ||
| 180 | |||
| 181 | pub(super) fn kelvin_to_srgb_white(t: f64) -> [f64; 3] { | ||
| 182 | let xyz = xy_to_xyz(kelvin_to_xy(t)); | ||
| 183 | let m_inv = mat3_inv(primaries_to_xyz(SRGB_P)); | ||
| 184 | let rgb = mat3_vec(m_inv, xyz); | ||
| 185 | [rgb[0].max(1e-4), rgb[1].max(1e-4), rgb[2].max(1e-4)] | ||
| 186 | } | ||
| 187 | |||
| 188 | pub(super) fn parse_color_type(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> i32 { | ||
| 189 | if let Some(s) = node.static_str("ColorType") { | ||
| 190 | return match s.to_ascii_lowercase().replace(['-', '_', ' '], "").as_str() { | ||
| 191 | "bw" | "grayscale" | "greyscale" => 0, | ||
| 192 | "yuv" => 1, | ||
| 193 | "yiq" => 2, | ||
| 194 | "cmy" => 3, | ||
| 195 | "hls" | "hsl" => 4, | ||
| 196 | "hsv" => 5, | ||
| 197 | "xyz" | "ciexyz" => 6, | ||
| 198 | "lab" | "cielab" => 7, | ||
| 199 | "ycbcr" => 8, | ||
| 200 | _ => 0, | ||
| 201 | }; | ||
| 202 | } | ||
| 203 | comp.eval_number(node, "ColorType", time, 0.0, expr).round().clamp(0.0, 8.0) as i32 | ||
| 204 | } | ||
| 205 | |||
| 206 | pub(super) fn parse_color_space_dir(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> i32 { | ||
| 207 | if let Some(s) = node.static_str("ColorSpaceConversion") { | ||
| 208 | return match s.to_ascii_lowercase().replace(['_', ' '], "").as_str() { | ||
| 209 | "tocolor" | "to" => 1, | ||
| 210 | "fromcolor" | "from" => 2, | ||
| 211 | _ => 0, | ||
| 212 | }; | ||
| 213 | } | ||
| 214 | comp.eval_number(node, "ColorSpaceConversion", time, 0.0, expr).round().clamp(0.0, 2.0) as i32 | ||
| 215 | } | ||
| 216 | |||
| 217 | pub(super) fn parse_matte_combine(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> i32 { | ||
| 218 | if let Some(s) = node.static_str("MatteCombine") { | ||
| 219 | return match s.to_ascii_lowercase().replace(['_', ' '], "").as_str() { | ||
| 220 | "none" => 0, | ||
| 221 | "combinealpha" | "alpha" => 1, | ||
| 222 | "combineluminance" | "luminance" | "luma" => 2, | ||
| 223 | "combinered" | "red" => 3, | ||
| 224 | "combinegreen" | "green" => 4, | ||
| 225 | "combineblue" | "blue" => 5, | ||
| 226 | _ => 0, | ||
| 227 | }; | ||
| 228 | } | ||
| 229 | comp.eval_number(node, "MatteCombine", time, 0.0, expr).round().clamp(0.0, 5.0) as i32 | ||
| 230 | } | ||
| 231 | |||
| 232 | pub(super) fn parse_combine_op(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> i32 { | ||
| 233 | if let Some(s) = node.static_str("CombineOp") { | ||
| 234 | return match s.to_ascii_lowercase().replace(['_', ' '], "").as_str() { | ||
| 235 | "copy" => 0, | ||
| 236 | "add" => 1, | ||
| 237 | "subtract" | "sub" => 2, | ||
| 238 | "and" | "min" | "minimum" => 3, | ||
| 239 | "or" | "max" | "maximum" => 4, | ||
| 240 | "xor" => 5, | ||
| 241 | "multiply" | "mul" => 6, | ||
| 242 | _ => 0, | ||
| 243 | }; | ||
| 244 | } | ||
| 245 | comp.eval_number(node, "CombineOp", time, 0.0, expr).round().clamp(0.0, 6.0) as i32 | ||
| 246 | } | ||
| 247 | |||
| 248 | pub(super) fn parse_apply_mode_str(s: &str) -> f32 { | ||
| 249 | match s { | ||
| 250 | "Screen" => 1.0, | ||
| 251 | "Multiply" => 2.0, | ||
| 252 | "Darken" => 3.0, | ||
| 253 | "Lighten" => 4.0, | ||
| 254 | "Difference" => 5.0, | ||
| 255 | "Exclusion" => 6.0, | ||
| 256 | "Overlay" => 7.0, | ||
| 257 | "Hard Light" | "HardLight" => 8.0, | ||
| 258 | "Soft Light" | "SoftLight" => 9.0, | ||
| 259 | "LinearLight" | "Linear Light" => 10.0, | ||
| 260 | "Color Dodge" | "ColorDodge" => 11.0, | ||
| 261 | "LinearDodge" | "Linear Dodge" | "Add" => 12.0, | ||
| 262 | "VividLight" | "Vivid Light" => 13.0, | ||
| 263 | "Hypotenuse" => 14.0, | ||
| 264 | "DarkerColor" | "Darker Color" => 15.0, | ||
| 265 | "LighterColor" | "Lighter Color" => 16.0, | ||
| 266 | "PinLight" | "Pin Light" => 17.0, | ||
| 267 | "Color Burn" | "ColorBurn" => 18.0, | ||
| 268 | "LinearBurn" | "Linear Burn" => 19.0, | ||
| 269 | "Geometric" => 20.0, | ||
| 270 | "Hue" => 21.0, | ||
| 271 | "Saturation" => 22.0, | ||
| 272 | "Color" => 23.0, | ||
| 273 | "Luminosity" => 24.0, | ||
| 274 | _ => 0.0, | ||
| 275 | } | ||
| 276 | } | ||
| 277 | |||
| 278 | pub(super) fn parse_operator_str(s: &str) -> f32 { | ||
| 279 | match s { | ||
| 280 | "Under" => 1.0, | ||
| 281 | "In" => 2.0, | ||
| 282 | "Held Out" | "HeldOut" => 3.0, | ||
| 283 | "Atop" => 4.0, | ||
| 284 | "XOr" | "Xor" => 5.0, | ||
| 285 | _ => 0.0, | ||
| 286 | } | ||
| 287 | } | ||
| 288 | |||
| 289 | pub(super) fn read_color_matrix( | ||
| 290 | comp: &Comp, | ||
| 291 | node: &Node, | ||
| 292 | time: f64, | ||
| 293 | expr: &ExprEngine, | ||
| 294 | ) -> ([[f32; 4]; 4], [f32; 4]) { | ||
| 295 | let mut m = [ | ||
| 296 | [1.0_f32, 0.0, 0.0, 0.0], | ||
| 297 | [0.0, 1.0, 0.0, 0.0], | ||
| 298 | [0.0, 0.0, 1.0, 0.0], | ||
| 299 | [0.0, 0.0, 0.0, 1.0], | ||
| 300 | ]; | ||
| 301 | let mut off = [0.0_f32; 4]; | ||
| 302 | |||
| 303 | if let Some(ParamValue::Raw(LuaValue::Table(tbl))) = | ||
| 304 | node.inputs.get("Matrix").and_then(|b| b.value.as_ref()) | ||
| 305 | { | ||
| 306 | for (ri, rname) in ["R", "G", "B", "A"].iter().enumerate() { | ||
| 307 | if let Some(rt) = tbl.get_table(rname) { | ||
| 308 | for ci in 0..4 { | ||
| 309 | if let Some(v) = rt.get_index((ci + 1) as i64).and_then(LuaValue::as_f64) { | ||
| 310 | m[ri][ci] = v as f32; | ||
| 311 | } | ||
| 312 | } | ||
| 313 | if let Some(v) = rt.get_index(5).and_then(LuaValue::as_f64) { | ||
| 314 | off[ri] = v as f32; | ||
| 315 | } | ||
| 316 | } | ||
| 317 | } | ||
| 318 | let flat: Vec<f64> = (1..=20) | ||
| 319 | .filter_map(|i| tbl.get_index(i).and_then(LuaValue::as_f64)) | ||
| 320 | .collect(); | ||
| 321 | if flat.len() == 20 { | ||
| 322 | for r in 0..4 { | ||
| 323 | for c in 0..4 { | ||
| 324 | m[r][c] = flat[r * 5 + c] as f32; | ||
| 325 | } | ||
| 326 | off[r] = flat[r * 5 + 4] as f32; | ||
| 327 | } | ||
| 328 | } else if flat.len() == 16 { | ||
| 329 | for r in 0..4 { | ||
| 330 | for c in 0..4 { | ||
| 331 | m[r][c] = flat[r * 4 + c] as f32; | ||
| 332 | } | ||
| 333 | } | ||
| 334 | } | ||
| 335 | } | ||
| 336 | |||
| 337 | let ch = ['R', 'G', 'B', 'A']; | ||
| 338 | for r in 0..4 { | ||
| 339 | for c in 0..4 { | ||
| 340 | let k_rr = format!("{}_{}", ch[r], ch[c]); | ||
| 341 | let k_mat = format!("Matrix.{}_{}", ch[r], ch[c]); | ||
| 342 | let k_mn = format!("M{}{}", r + 1, c + 1); | ||
| 343 | for key in [&k_mat, &k_rr, &k_mn] { | ||
| 344 | if node.inputs.contains_key(key.as_str()) { | ||
| 345 | m[r][c] = comp.eval_number(node, key, time, m[r][c] as f64, expr) as f32; | ||
| 346 | break; | ||
| 347 | } | ||
| 348 | } | ||
| 349 | } | ||
| 350 | let k_off_num = format!("Offset{}", r + 1); | ||
| 351 | let k_off_ch = format!("Offset{}", ch[r]); | ||
| 352 | let k_ro = format!("{}_O", ch[r]); | ||
| 353 | let k_mro = format!("Matrix.{}_O", ch[r]); | ||
| 354 | let k_m5 = format!("M{}5", r + 1); | ||
| 355 | for key in [&k_mro, &k_ro, &k_off_num, &k_off_ch, &k_m5] { | ||
| 356 | if node.inputs.contains_key(key.as_str()) { | ||
| 357 | off[r] = comp.eval_number(node, key, time, off[r] as f64, expr) as f32; | ||
| 358 | break; | ||
| 359 | } | ||
| 360 | } | ||
| 361 | } | ||
| 362 | (m, off) | ||
| 363 | } | ||
| 364 | |||
| 365 | pub(super) fn eval_layer_num( | ||
| 366 | comp: &Comp, | ||
| 367 | node: &Node, | ||
| 368 | idx: usize, | ||
| 369 | param: &str, | ||
| 370 | def: f64, | ||
| 371 | time: f64, | ||
| 372 | expr: &ExprEngine, | ||
| 373 | ) -> f32 { | ||
| 374 | let k1 = format!("Layer{idx}.{param}"); | ||
| 375 | let k2 = format!("{param}{idx}"); | ||
| 376 | if node.inputs.contains_key(&k1) { | ||
| 377 | comp.eval_number(node, &k1, time, def, expr) as f32 | ||
| 378 | } else if node.inputs.contains_key(&k2) { | ||
| 379 | comp.eval_number(node, &k2, time, def, expr) as f32 | ||
| 380 | } else { | ||
| 381 | def as f32 | ||
| 382 | } | ||
| 383 | } | ||
| 384 | |||
| 385 | pub(super) fn layer_str<'a>(node: &'a Node, idx: usize, param: &str) -> Option<&'a str> { | ||
| 386 | node.static_str(&format!("Layer{idx}.{param}")) | ||
| 387 | .or_else(|| node.static_str(&format!("{param}{idx}"))) | ||
| 388 | } | ||
| 389 | |||
| 390 | pub(super) fn discover_multimerge_layers(node: &Node) -> Vec<usize> { | ||
| 391 | let mut found = Vec::new(); | ||
| 392 | for key in node.inputs.keys() { | ||
| 393 | let idx = if let Some(rest) = key.strip_prefix("Layer") { | ||
| 394 | rest.strip_suffix(".Foreground") | ||
| 395 | .unwrap_or(rest) | ||
| 396 | .parse::<usize>() | ||
| 397 | .ok() | ||
| 398 | } else if let Some(rest) = key.strip_prefix("Foreground") { | ||
| 399 | rest.parse::<usize>().ok().filter(|&n| n >= 1) | ||
| 400 | } else { | ||
| 401 | None | ||
| 402 | }; | ||
| 403 | if let Some(n) = idx { | ||
| 404 | if n >= 1 && !found.contains(&n) { | ||
| 405 | found.push(n); | ||
| 406 | } | ||
| 407 | } | ||
| 408 | } | ||
| 409 | found.sort_unstable(); | ||
| 410 | |||
| 411 | if let Some(val) = node.inputs.get("LayerOrder").and_then(|b| b.value.as_ref()) { | ||
| 412 | let mut raw_order: Vec<usize> = Vec::new(); | ||
| 413 | match val { | ||
| 414 | ParamValue::Point([a, b]) => { | ||
| 415 | raw_order.push(a.round() as usize); | ||
| 416 | raw_order.push(b.round() as usize); | ||
| 417 | } | ||
| 418 | ParamValue::Raw(LuaValue::Table(tbl)) => { | ||
| 419 | let mut pairs: Vec<(i64, usize)> = tbl | ||
| 420 | .entries | ||
| 421 | .iter() | ||
| 422 | .filter_map(|(k, v)| { | ||
| 423 | let ord = match k { | ||
| 424 | LuaKey::Index(i) => *i, | ||
| 425 | LuaKey::Number(f) => *f as i64, | ||
| 426 | _ => return None, | ||
| 427 | }; | ||
| 428 | let layer_idx = v.as_f64()?.round() as usize; | ||
| 429 | Some((ord, layer_idx)) | ||
| 430 | }) | ||
| 431 | .collect(); | ||
| 432 | pairs.sort_by_key(|(ord, _)| *ord); | ||
| 433 | raw_order.extend(pairs.into_iter().map(|(_, idx)| idx)); | ||
| 434 | } | ||
| 435 | _ => {} | ||
| 436 | } | ||
| 437 | if !raw_order.is_empty() { | ||
| 438 | let mut ordered = Vec::with_capacity(found.len()); | ||
| 439 | for idx in raw_order { | ||
| 440 | if found.contains(&idx) && !ordered.contains(&idx) { | ||
| 441 | ordered.push(idx); | ||
| 442 | } | ||
| 443 | } | ||
| 444 | for idx in found { | ||
| 445 | if !ordered.contains(&idx) { | ||
| 446 | ordered.push(idx); | ||
| 447 | } | ||
| 448 | } | ||
| 449 | return ordered; | ||
| 450 | } | ||
| 451 | } | ||
| 452 | |||
| 453 | found | ||
| 454 | } | ||
crates/engine/src/eval/color_science/tests.rs created+329| ... | @@ -0,0 +1,329 @@ | ||
| 1 | use super::*; | ||
| 2 | |||
| 3 | fn eval_px(eng: &mut Engine, comp: &Comp, name: &str) -> (CachedTexture, Vec<u8>) { | ||
| 4 | let id = comp.find_node(name).unwrap_or_else(|| panic!("missing node {name}")); | ||
| 5 | let (tex, _) = eng.evaluate(comp, id, 0.0); | ||
| 6 | let rgba = eng.readback_rgba(&tex).expect("readback_rgba"); | ||
| 7 | (tex, rgba) | ||
| 8 | } | ||
| 9 | |||
| 10 | fn eval_f32(eng: &mut Engine, comp: &Comp, name: &str) -> (CachedTexture, Vec<f32>) { | ||
| 11 | let id = comp.find_node(name).unwrap_or_else(|| panic!("missing node {name}")); | ||
| 12 | let (tex, _) = eng.evaluate(comp, id, 0.0); | ||
| 13 | let rgba = eng.readback_rgba_f32(&tex).expect("readback_rgba_f32"); | ||
| 14 | (tex, rgba) | ||
| 15 | } | ||
| 16 | |||
| 17 | fn px_at(rgba: &[u8], w: u32, x: u32, y: u32) -> [u8; 4] { | ||
| 18 | let i = ((y * w + x) * 4) as usize; | ||
| 19 | [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] | ||
| 20 | } | ||
| 21 | |||
| 22 | #[test] | ||
| 23 | fn aces_transform_scene_roundtrips_rgc_and_display_odt() { | ||
| 24 | let src = r#"Composition { | ||
| 25 | Prefs = { Comp = { FrameFormat = { Width = 32, Height = 32, DepthFull = 3, }, }, }, | ||
| 26 | Tools = ordered() { | ||
| 27 | Col = Background { Inputs = { Width = Input { Value = 32, }, Height = 32, Depth = Input { Value = 3, }, | ||
| 28 | TopLeftRed = Input { Value = 0.65, }, TopLeftGreen = Input { Value = 0.25, }, TopLeftBlue = Input { Value = 0.12, }, TopLeftAlpha = Input { Value = 0.9, }, }, }, | ||
| 29 | Grey = Background { Inputs = { Width = Input { Value = 32, }, Height = 32, Depth = Input { Value = 3, }, | ||
| 30 | TopLeftRed = Input { Value = 0.18, }, TopLeftGreen = Input { Value = 0.18, }, TopLeftBlue = Input { Value = 0.18, }, }, }, | ||
| 31 | Bright = Background { Inputs = { Width = Input { Value = 32, }, Height = 32, Depth = Input { Value = 3, }, | ||
| 32 | TopLeftRed = Input { Value = 1.0, }, TopLeftGreen = Input { Value = 1.0, }, TopLeftBlue = Input { Value = 1.0, }, }, }, | ||
| 33 | Hdr = BrightnessContrast { Inputs = { Input = Input { SourceOp = "Bright", Source = "Output", }, Gain = Input { Value = 10.0, }, }, }, | ||
| 34 | ToCg = AcesTransform { Inputs = { Input = Input { SourceOp = "Col", Source = "Output", }, | ||
| 35 | InputTransform = Input { Value = FuID { "IDT_LINEAR_SRGB" }, }, OutputTransform = Input { Value = FuID { "ODT_ACESCG" }, }, }, }, | ||
| 36 | BackLin = AcesTransform { Inputs = { Input = Input { SourceOp = "ToCg", Source = "Output", }, | ||
| 37 | InputTransform = Input { Value = FuID { "IDT_ACESCG" }, }, OutputTransform = Input { Value = FuID { "ODT_LINEAR_SRGB" }, }, }, }, | ||
| 38 | ToCct = AcesTransform { Inputs = { Input = Input { SourceOp = "ToCg", Source = "Output", }, | ||
| 39 | InputTransform = Input { Value = FuID { "ACEScg" }, }, OutputTransform = Input { Value = FuID { "ACEScct" }, }, }, }, | ||
| 40 | BackFromCct = AcesTransform { Inputs = { Input = Input { SourceOp = "ToCct", Source = "Output", }, | ||
| 41 | InputTransform = Input { Value = FuID { "ACEScct" }, }, OutputTransform = Input { Value = FuID { "ACEScg" }, }, }, }, | ||
| 42 | ToCc = AcesTransform { Inputs = { Input = Input { SourceOp = "ToCg", Source = "Output", }, | ||
| 43 | InputTransform = Input { Value = FuID { "ACEScg" }, }, OutputTransform = Input { Value = FuID { "ACEScc" }, }, }, }, | ||
| 44 | BackFromCc = AcesTransform { Inputs = { Input = Input { SourceOp = "ToCc", Source = "Output", }, | ||
| 45 | InputTransform = Input { Value = FuID { "ACEScc" }, }, OutputTransform = Input { Value = FuID { "ACEScg" }, }, }, }, | ||
| 46 | ToAp0 = AcesTransform { Inputs = { Input = Input { SourceOp = "ToCg", Source = "Output", }, | ||
| 47 | InputTransform = Input { Value = FuID { "ACEScg" }, }, OutputTransform = Input { Value = FuID { "ACES2065-1" }, }, }, }, | ||
| 48 | BackFromAp0 = AcesTransform { Inputs = { Input = Input { SourceOp = "ToAp0", Source = "Output", }, | ||
| 49 | InputTransform = Input { Value = FuID { "ACES2065-1" }, }, OutputTransform = Input { Value = FuID { "ACEScg" }, }, }, }, | ||
| 50 | GreySrgb = AcesTransform { Inputs = { Input = Input { SourceOp = "Grey", Source = "Output", }, | ||
| 51 | InputTransform = Input { Value = FuID { "ACEScg" }, }, OutputTransform = Input { Value = FuID { "sRGB" }, }, }, }, | ||
| 52 | HdrRec709 = AcesTransform { Inputs = { Input = Input { SourceOp = "Hdr", Source = "Output", }, | ||
| 53 | InputTransform = Input { Value = FuID { "ACEScg" }, }, OutputTransform = Input { Value = FuID { "Rec.709" }, }, | ||
| 54 | ReferenceGamutCompress = Input { Value = 1, }, }, }, | ||
| 55 | WithAux = Dimension.CopyAux { Inputs = { Input = Input { SourceOp = "Col", Source = "Output", }, | ||
| 56 | Mode = Input { Value = 1, }, AuxChannel = Input { Value = FuID { "Z" }, }, }, }, | ||
| 57 | AcesAux = AcesTransform { Inputs = { Input = Input { SourceOp = "WithAux", Source = "Output", }, | ||
| 58 | InputTransform = Input { Value = FuID { "Linear sRGB" }, }, OutputTransform = Input { Value = FuID { "ACEScg" }, }, }, }, | ||
| 59 | } }"#; | ||
| 60 | let comp = Comp::from_fusion_str(src).expect("parse ACES comp"); | ||
| 61 | let Ok(mut eng) = Engine::new_headless() else { return }; | ||
| 62 | |||
| 63 | let (_, orig) = eval_f32(&mut eng, &comp, "Col"); | ||
| 64 | let (_, cg) = eval_f32(&mut eng, &comp, "ToCg"); | ||
| 65 | let (_, back) = eval_f32(&mut eng, &comp, "BackLin"); | ||
| 66 | assert!((orig[0] - cg[0]).abs() > 0.02, "Linear sRGB -> ACEScg must shift primaries"); | ||
| 67 | for c in 0..4 { | ||
| 68 | assert!((back[c] - orig[c]).abs() < 0.005, "LinSRGB<->ACEScg roundtrip ch {c}: {} vs {}", back[c], orig[c]); | ||
| 69 | } | ||
| 70 | |||
| 71 | let (_, back_cct) = eval_f32(&mut eng, &comp, "BackFromCct"); | ||
| 72 | let (_, back_cc) = eval_f32(&mut eng, &comp, "BackFromCc"); | ||
| 73 | let (_, back_ap0) = eval_f32(&mut eng, &comp, "BackFromAp0"); | ||
| 74 | for c in 0..3 { | ||
| 75 | assert!((back_cct[c] - cg[c]).abs() < 0.005, "ACEScg<->ACEScct roundtrip ch {c}"); | ||
| 76 | assert!((back_cc[c] - cg[c]).abs() < 0.005, "ACEScg<->ACEScc roundtrip ch {c}"); | ||
| 77 | assert!((back_ap0[c] - cg[c]).abs() < 0.005, "ACEScg<->AP0 roundtrip ch {c}"); | ||
| 78 | } | ||
| 79 | |||
| 80 | let (_, gs) = eval_f32(&mut eng, &comp, "GreySrgb"); | ||
| 81 | assert!((gs[0] - gs[1]).abs() < 0.01 && (gs[1] - gs[2]).abs() < 0.01, "D60->D65 grey stays neutral: {:?}", &gs[..3]); | ||
| 82 | assert!(gs[0] > 0.30 && gs[0] < 0.45, "18% grey ACES ODT sRGB midtone: {}", gs[0]); | ||
| 83 | |||
| 84 | let (_, hr) = eval_f32(&mut eng, &comp, "HdrRec709"); | ||
| 85 | assert!(hr[0] > 0.85 && hr[0] <= 1.0, "10.0 HDR white rolls off cleanly in Rec.709 ODT: {}", hr[0]); | ||
| 86 | |||
| 87 | let (aux_tex, _) = eng.evaluate(&comp, comp.find_node("AcesAux").unwrap(), 0.0); | ||
| 88 | assert!(aux_tex.aux.as_ref().is_some_and(|a| a.z.is_some()), "AcesTransform preserves upstream aux"); | ||
| 89 | } | ||
| 90 | |||
| 91 | #[test] | ||
| 92 | fn color_space_roundtrips_and_bw_depth() { | ||
| 93 | let src = r#"Composition { | ||
| 94 | Tools = ordered() { | ||
| 95 | Col = Background { Inputs = { Width = Input { Value = 16, }, Height = Input { Value = 16, }, Depth = Input { Value = 3, }, | ||
| 96 | TopLeftRed = Input { Value = 0.72, }, TopLeftGreen = Input { Value = 0.38, }, TopLeftBlue = Input { Value = 0.20, }, TopLeftAlpha = Input { Value = 0.85, }, }, }, | ||
| 97 | ToHls = ColorSpace { Inputs = { Input = Input { SourceOp = "Col", Source = "Output", }, ColorSpaceConversion = Input { Value = 1, }, ColorType = Input { Value = FuID { "HLS" }, }, }, }, | ||
| 98 | FromHls = ColorSpace { Inputs = { Input = Input { SourceOp = "ToHls", Source = "Output", }, ColorSpaceConversion = Input { Value = 2, }, ColorType = Input { Value = FuID { "HSL" }, }, }, }, | ||
| 99 | ToHsv = ColorSpace { Inputs = { Input = Input { SourceOp = "Col", Source = "Output", }, ColorSpaceConversion = Input { Value = 1, }, ColorType = Input { Value = FuID { "HSV" }, }, }, }, | ||
| 100 | FromHsv = ColorSpace { Inputs = { Input = Input { SourceOp = "ToHsv", Source = "Output", }, ColorSpaceConversion = Input { Value = 2, }, ColorType = Input { Value = FuID { "HSV" }, }, }, }, | ||
| 101 | ToYuv = ColorSpace { Inputs = { Input = Input { SourceOp = "Col", Source = "Output", }, ColorSpaceConversion = Input { Value = 1, }, ColorType = Input { Value = FuID { "YUV" }, }, }, }, | ||
| 102 | FromYuv = ColorSpace { Inputs = { Input = Input { SourceOp = "ToYuv", Source = "Output", }, ColorSpaceConversion = Input { Value = 2, }, ColorType = Input { Value = FuID { "YUV" }, }, }, }, | ||
| 103 | ToYcbcr = ColorSpace { Inputs = { Input = Input { SourceOp = "Col", Source = "Output", }, ColorSpaceConversion = Input { Value = 1, }, ColorType = Input { Value = FuID { "YCbCr" }, }, }, }, | ||
| 104 | FromYcbcr = ColorSpace { Inputs = { Input = Input { SourceOp = "ToYcbcr", Source = "Output", }, ColorSpaceConversion = Input { Value = 2, }, ColorType = Input { Value = FuID { "YCbCr" }, }, }, }, | ||
| 105 | ToLab = ColorSpace { Inputs = { Input = Input { SourceOp = "Col", Source = "Output", }, ColorSpaceConversion = Input { Value = 1, }, ColorType = Input { Value = FuID { "LAB" }, }, }, }, | ||
| 106 | FromLab = ColorSpace { Inputs = { Input = Input { SourceOp = "ToLab", Source = "Output", }, ColorSpaceConversion = Input { Value = 2, }, ColorType = Input { Value = FuID { "LAB" }, }, }, }, | ||
| 107 | ToXyz = ColorSpace { Inputs = { Input = Input { SourceOp = "Col", Source = "Output", }, ColorSpaceConversion = Input { Value = 1, }, ColorType = Input { Value = FuID { "XYZ" }, }, }, }, | ||
| 108 | FromXyz = ColorSpace { Inputs = { Input = Input { SourceOp = "ToXyz", Source = "Output", }, ColorSpaceConversion = Input { Value = 2, }, ColorType = Input { Value = FuID { "XYZ" }, }, }, }, | ||
| 109 | ToYiq = ColorSpace { Inputs = { Input = Input { SourceOp = "Col", Source = "Output", }, ColorSpaceConversion = Input { Value = 1, }, ColorType = Input { Value = FuID { "YIQ" }, }, }, }, | ||
| 110 | FromYiq = ColorSpace { Inputs = { Input = Input { SourceOp = "ToYiq", Source = "Output", }, ColorSpaceConversion = Input { Value = 2, }, ColorType = Input { Value = FuID { "YIQ" }, }, }, }, | ||
| 111 | ToCmy = ColorSpace { Inputs = { Input = Input { SourceOp = "Col", Source = "Output", }, ColorSpaceConversion = Input { Value = 1, }, ColorType = Input { Value = FuID { "CMY" }, }, }, }, | ||
| 112 | FromCmy = ColorSpace { Inputs = { Input = Input { SourceOp = "ToCmy", Source = "Output", }, ColorSpaceConversion = Input { Value = 2, }, ColorType = Input { Value = FuID { "CMY" }, }, }, }, | ||
| 113 | ToBw = ColorSpace { Inputs = { Input = Input { SourceOp = "Col", Source = "Output", }, ColorSpaceConversion = Input { Value = 1, }, ColorType = Input { Value = FuID { "BW" }, }, Depth = Input { Value = 1, }, }, }, | ||
| 114 | WithAux = Dimension.CopyAux { Inputs = { Input = Input { SourceOp = "Col", Source = "Output", }, Mode = Input { Value = 1, }, AuxChannel = Input { Value = FuID { "Z" }, }, }, }, | ||
| 115 | CsAux = ColorSpace { Inputs = { Input = Input { SourceOp = "WithAux", Source = "Output", }, ColorSpaceConversion = Input { Value = 1, }, ColorType = Input { Value = FuID { "CMY" }, }, }, }, | ||
| 116 | } }"#; | ||
| 117 | let comp = Comp::from_fusion_str(src).expect("parse ColorSpace comp"); | ||
| 118 | let Ok(mut eng) = Engine::new_headless() else { return }; | ||
| 119 | |||
| 120 | let (_, orig) = eval_f32(&mut eng, &comp, "Col"); | ||
| 121 | for name in ["FromHls", "FromHsv", "FromYuv", "FromYcbcr", "FromLab", "FromXyz", "FromYiq", "FromCmy"] { | ||
| 122 | let (_, rt) = eval_f32(&mut eng, &comp, name); | ||
| 123 | for c in 0..4 { | ||
| 124 | assert!((rt[c] - orig[c]).abs() < 0.01, "{name} roundtrip ch {c}: {} vs {}", rt[c], orig[c]); | ||
| 125 | } | ||
| 126 | } | ||
| 127 | let (bw_tex, bw) = eval_px(&mut eng, &comp, "ToBw"); | ||
| 128 | assert_eq!(bw_tex.depth, BitDepth::Int8); | ||
| 129 | let expected_luma = (0.299 * 0.72 + 0.587 * 0.38 + 0.114 * 0.20) * 255.0; | ||
| 130 | assert_eq!(bw[0], bw[1]); | ||
| 131 | assert_eq!(bw[1], bw[2]); | ||
| 132 | assert!((bw[0] as f32 - expected_luma).abs() <= 2.0, "BW luma={:?}", &bw[..4]); | ||
| 133 | let (aux_tex, _) = eng.evaluate(&comp, comp.find_node("CsAux").unwrap(), 0.0); | ||
| 134 | assert!(aux_tex.aux.as_ref().is_some_and(|a| a.z.is_some()), "ColorSpace preserves upstream aux"); | ||
| 135 | } | ||
| 136 | |||
| 137 | #[test] | ||
| 138 | fn color_matrix_5x4_channel_swap_offset_and_table() { | ||
| 139 | let src = r#"Composition { Tools = ordered() { | ||
| 140 | Col = Background { Inputs = { Width = Input { Value = 16, }, Height = Input { Value = 16, }, | ||
| 141 | TopLeftRed = Input { Value = 0.2, }, TopLeftGreen = Input { Value = 0.6, }, TopLeftBlue = Input { Value = 0.4, }, TopLeftAlpha = Input { Value = 0.5, }, }, }, | ||
| 142 | CM = ColorMatrix { Inputs = { Input = Input { SourceOp = "Col", Source = "Output", }, | ||
| 143 | M11 = Input { Value = 0.0, }, M12 = Input { Value = 1.0, }, Offset1 = Input { Value = 0.1, }, | ||
| 144 | M21 = Input { Value = 1.0, }, M22 = Input { Value = 0.0, }, | ||
| 145 | M33 = Input { Value = 0.5, }, Offset3 = Input { Value = 0.25, }, | ||
| 146 | M44 = Input { Value = 1.0, }, Offset4 = Input { Value = 0.5, }, }, }, | ||
| 147 | CMTable = ColorMatrix { Inputs = { Input = Input { SourceOp = "Col", Source = "Output", }, | ||
| 148 | Matrix = Input { Value = ColorMatrixFull { | ||
| 149 | R = { 0.0, 0.0, 1.0, 0.0, 0.0 }, | ||
| 150 | G = { 1.0, 0.0, 0.0, 0.0, 0.0 }, | ||
| 151 | B = { 0.0, 1.0, 0.0, 0.0, 0.0 }, | ||
| 152 | A = { 0.0, 0.0, 0.0, 1.0, 0.0 }, | ||
| 153 | }, }, }, }, | ||
| 154 | } }"#; | ||
| 155 | let comp = Comp::from_fusion_str(src).expect("parse ColorMatrix comp"); | ||
| 156 | let Ok(mut eng) = Engine::new_headless() else { return }; | ||
| 157 | |||
| 158 | let (_, cm) = eval_px(&mut eng, &comp, "CM"); | ||
| 159 | // R = 0.6 + 0.1 = 0.7 (179), G = 0.2 (51), B = 0.4*0.5 + 0.25 = 0.45 (115), A = 1.0 (255) | ||
| 160 | assert!((cm[0] as i32 - 179).abs() <= 2 && (cm[1] as i32 - 51).abs() <= 2 && (cm[2] as i32 - 115).abs() <= 2 && cm[3] >= 253, "CM={:?}", &cm[..4]); | ||
| 161 | |||
| 162 | let (_, cmt) = eval_px(&mut eng, &comp, "CMTable"); | ||
| 163 | // R = old B (102), G = old R (51), B = old G (153) | ||
| 164 | assert!((cmt[0] as i32 - 102).abs() <= 2 && (cmt[1] as i32 - 51).abs() <= 2 && (cmt[2] as i32 - 153).abs() <= 2, "CMTable={:?}", &cmt[..4]); | ||
| 165 | } | ||
| 166 | |||
| 167 | #[test] | ||
| 168 | fn white_balance_temperature_tint_and_reference_neutralization() { | ||
| 169 | let src = r#"Composition { Tools = ordered() { | ||
| 170 | Grey = Background { Inputs = { Width = Input { Value = 16, }, Height = Input { Value = 16, }, | ||
| 171 | TopLeftRed = Input { Value = 0.5, }, TopLeftGreen = Input { Value = 0.5, }, TopLeftBlue = Input { Value = 0.5, }, }, }, | ||
| 172 | Cast = Background { Inputs = { Width = Input { Value = 16, }, Height = Input { Value = 16, }, | ||
| 173 | TopLeftRed = Input { Value = 0.8, }, TopLeftGreen = Input { Value = 0.6, }, TopLeftBlue = Input { Value = 0.4, }, }, }, | ||
| 174 | Neutral = WhiteBalance { Inputs = { Input = Input { SourceOp = "Grey", Source = "Output", }, Temperature = Input { Value = 6500.0, }, Tint = Input { Value = 0.0, }, }, }, | ||
| 175 | Warm = WhiteBalance { Inputs = { Input = Input { SourceOp = "Grey", Source = "Output", }, Temperature = Input { Value = 9500.0, }, }, }, | ||
| 176 | Cool = WhiteBalance { Inputs = { Input = Input { SourceOp = "Grey", Source = "Output", }, Temperature = Input { Value = 3500.0, }, }, }, | ||
| 177 | Magenta = WhiteBalance { Inputs = { Input = Input { SourceOp = "Grey", Source = "Output", }, Tint = Input { Value = 0.8, }, }, }, | ||
| 178 | Neutralize = WhiteBalance { Inputs = { Input = Input { SourceOp = "Cast", Source = "Output", }, | ||
| 179 | ReferenceRed = Input { Value = 0.8, }, ReferenceGreen = Input { Value = 0.6, }, ReferenceBlue = Input { Value = 0.4, }, }, }, | ||
| 180 | } }"#; | ||
| 181 | let comp = Comp::from_fusion_str(src).expect("parse WhiteBalance comp"); | ||
| 182 | let Ok(mut eng) = Engine::new_headless() else { return }; | ||
| 183 | |||
| 184 | let (_, neu) = eval_px(&mut eng, &comp, "Neutral"); | ||
| 185 | assert!((neu[0] as i32 - 128).abs() <= 2 && neu[0] == neu[1] && neu[1] == neu[2], "Neutral={:?}", &neu[..4]); | ||
| 186 | |||
| 187 | let (_, warm) = eval_px(&mut eng, &comp, "Warm"); | ||
| 188 | assert!(warm[0] > warm[2] + 10, "Warm boosts R over B: {:?}", &warm[..3]); | ||
| 189 | |||
| 190 | let (_, cool) = eval_px(&mut eng, &comp, "Cool"); | ||
| 191 | assert!(cool[2] > cool[0] + 15, "Cool boosts B over R: {:?}", &cool[..3]); | ||
| 192 | |||
| 193 | let (_, mag) = eval_px(&mut eng, &comp, "Magenta"); | ||
| 194 | assert!(mag[0] > mag[1] + 10 && mag[2] > mag[1] + 10, "Positive tint reduces G vs R/B: {:?}", &mag[..3]); | ||
| 195 | |||
| 196 | let (_, fix) = eval_px(&mut eng, &comp, "Neutralize"); | ||
| 197 | assert!((fix[0] as i32 - fix[1] as i32).abs() <= 2 && (fix[1] as i32 - fix[2] as i32).abs() <= 2, "Sampled cast neutralized to grey: {:?}", &fix[..3]); | ||
| 198 | } | ||
| 199 | |||
| 200 | #[test] | ||
| 201 | fn matte_control_combine_erode_blur_garbage_solid_spill_and_postmult() { | ||
| 202 | let src = r#"Composition { Tools = ordered() { | ||
| 203 | Bg = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, | ||
| 204 | TopLeftRed = Input { Value = 0.4, }, TopLeftGreen = Input { Value = 0.9, }, TopLeftBlue = Input { Value = 0.2, }, TopLeftAlpha = Input { Value = 1.0, }, }, }, | ||
| 205 | FgMask = RectangleMask { Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, | ||
| 206 | Center = Input { Value = { 0.5, 0.5 }, }, Width = Input { Value = 0.5, }, Height = Input { Value = 0.5, }, }, }, | ||
| 207 | Fg = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, | ||
| 208 | TopLeftRed = Input { Value = 1.0, }, TopLeftGreen = Input { Value = 1.0, }, TopLeftBlue = Input { Value = 1.0, }, | ||
| 209 | EffectMask = Input { SourceOp = "FgMask", Source = "Mask", }, }, }, | ||
| 210 | Garb = RectangleMask { Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, | ||
| 211 | Center = Input { Value = { 0.5, 0.5 }, }, Width = Input { Value = 0.15, }, Height = Input { Value = 0.15, }, }, }, | ||
| 212 | Solid = RectangleMask { Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, | ||
| 213 | Center = Input { Value = { 0.1, 0.5 }, }, Width = Input { Value = 0.12, }, Height = Input { Value = 0.2, }, }, }, | ||
| 214 | MC = MatteControl { Inputs = { | ||
| 215 | Background = Input { SourceOp = "Bg", Source = "Output", }, | ||
| 216 | Foreground = Input { SourceOp = "Fg", Source = "Output", }, | ||
| 217 | ["Garbage.Matte"] = Input { SourceOp = "Garb", Source = "Mask", }, | ||
| 218 | ["Solid.Matte"] = Input { SourceOp = "Solid", Source = "Mask", }, | ||
| 219 | MatteCombine = Input { Value = 1, }, | ||
| 220 | CombineOp = Input { Value = 0, }, | ||
| 221 | MatteContractExpand = Input { Value = 0.0, }, | ||
| 222 | MatteBlur = Input { Value = 0.0, }, | ||
| 223 | SpillSuppression = Input { Value = 1.0, }, | ||
| 224 | PostMultiplyImage = Input { Value = 1, }, | ||
| 225 | }, }, | ||
| 226 | MCBlurInv = MatteControl { Inputs = { | ||
| 227 | Background = Input { SourceOp = "Bg", Source = "Output", }, | ||
| 228 | Foreground = Input { SourceOp = "Fg", Source = "Output", }, | ||
| 229 | MatteCombine = Input { Value = 2, }, | ||
| 230 | CombineOp = Input { Value = 0, }, | ||
| 231 | MatteBlur = Input { Value = 3.0, }, | ||
| 232 | InvertMatte = Input { Value = 1, }, | ||
| 233 | PostMultiplyImage = Input { Value = 0, }, | ||
| 234 | }, }, | ||
| 235 | MCDilate = MatteControl { Inputs = { | ||
| 236 | Background = Input { SourceOp = "Bg", Source = "Output", }, | ||
| 237 | Foreground = Input { SourceOp = "Fg", Source = "Output", }, | ||
| 238 | MatteCombine = Input { Value = 1, }, | ||
| 239 | CombineOp = Input { Value = FuID { "And" }, }, | ||
| 240 | MatteContractExpand = Input { Value = 0.08, }, | ||
| 241 | }, }, | ||
| 242 | MCContract = MatteControl { Inputs = { | ||
| 243 | Background = Input { SourceOp = "Bg", Source = "Output", }, | ||
| 244 | Foreground = Input { SourceOp = "Fg", Source = "Output", }, | ||
| 245 | MatteCombine = Input { Value = 1, }, | ||
| 246 | CombineOp = Input { Value = FuID { "Min" }, }, | ||
| 247 | MatteContractExpand = Input { Value = -0.08, }, | ||
| 248 | }, }, | ||
| 249 | } }"#; | ||
| 250 | let comp = Comp::from_fusion_str(src).expect("parse MatteControl comp"); | ||
| 251 | let Ok(mut eng) = Engine::new_headless() else { return }; | ||
| 252 | |||
| 253 | let (_, mc) = eval_px(&mut eng, &comp, "MC"); | ||
| 254 | assert_eq!(px_at(&mc, 64, 58, 32), [0, 0, 0, 0]); | ||
| 255 | let kept = px_at(&mc, 64, 22, 32); | ||
| 256 | assert_eq!(kept[3], 255); | ||
| 257 | assert!((kept[1] as i32 - 77).abs() <= 3, "Green spill suppressed: {kept:?}"); | ||
| 258 | assert_eq!(px_at(&mc, 64, 32, 32)[3], 0); | ||
| 259 | assert_eq!(px_at(&mc, 64, 6, 32)[3], 255); | ||
| 260 | |||
| 261 | let (_, mbi) = eval_px(&mut eng, &comp, "MCBlurInv"); | ||
| 262 | assert_eq!(px_at(&mbi, 64, 58, 32)[3], 255, "Inverted matte is opaque outside"); | ||
| 263 | assert_eq!(px_at(&mbi, 64, 32, 32)[3], 0, "Inverted matte is transparent inside"); | ||
| 264 | let edge = px_at(&mbi, 64, 16, 32)[3]; | ||
| 265 | assert!(edge > 10 && edge < 245, "MatteBlur softens edge alpha: {edge}"); | ||
| 266 | |||
| 267 | let (_, dil) = eval_px(&mut eng, &comp, "MCDilate"); | ||
| 268 | let (_, con) = eval_px(&mut eng, &comp, "MCContract"); | ||
| 269 | let dil_opaque = dil.chunks_exact(4).filter(|p| p[3] > 200).count(); | ||
| 270 | let con_opaque = con.chunks_exact(4).filter(|p| p[3] > 200).count(); | ||
| 271 | assert!(dil_opaque > con_opaque + 400, "MatteContractExpand dilate ({dil_opaque}) > contract ({con_opaque})"); | ||
| 272 | } | ||
| 273 | |||
| 274 | #[test] | ||
| 275 | fn multi_merge_layers_enable_order_masks_and_fuse_alias() { | ||
| 276 | let src = r#"Composition { Tools = ordered() { | ||
| 277 | Bg = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, | ||
| 278 | TopLeftRed = Input { Value = 0.0, }, TopLeftGreen = Input { Value = 0.0, }, TopLeftBlue = Input { Value = 0.0, }, }, }, | ||
| 279 | L1 = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, | ||
| 280 | TopLeftRed = Input { Value = 1.0, }, TopLeftGreen = Input { Value = 0.0, }, TopLeftBlue = Input { Value = 0.0, }, }, }, | ||
| 281 | L2 = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, | ||
| 282 | TopLeftRed = Input { Value = 0.0, }, TopLeftGreen = Input { Value = 1.0, }, TopLeftBlue = Input { Value = 0.0, }, }, }, | ||
| 283 | L3 = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, | ||
| 284 | TopLeftRed = Input { Value = 0.0, }, TopLeftGreen = Input { Value = 0.0, }, TopLeftBlue = Input { Value = 1.0, }, }, }, | ||
| 285 | RightM = RectangleMask { Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, | ||
| 286 | Center = Input { Value = { 0.75, 0.5 }, }, Width = Input { Value = 0.5, }, Height = Input { Value = 1.0, }, }, }, | ||
| 287 | MM = MultiMerge { Inputs = { | ||
| 288 | Background = Input { SourceOp = "Bg", Source = "Output", }, | ||
| 289 | ["Layer1.Foreground"] = Input { SourceOp = "L1", Source = "Output", }, | ||
| 290 | ["Layer2.Foreground"] = Input { SourceOp = "L2", Source = "Output", }, | ||
| 291 | LayerEnabled2 = Input { Value = 0, }, | ||
| 292 | ["Layer3.Foreground"] = Input { SourceOp = "L3", Source = "Output", }, | ||
| 293 | ["Layer3.EffectMask"] = Input { SourceOp = "RightM", Source = "Mask", }, | ||
| 294 | ["Layer3.Blend"] = Input { Value = 0.5, }, | ||
| 295 | }, }, | ||
| 296 | FuseMM = Fuse.MultiMerge { Inputs = { | ||
| 297 | Background = Input { SourceOp = "Bg", Source = "Output", }, | ||
| 298 | Layer1 = Input { SourceOp = "L1", Source = "Output", }, | ||
| 299 | Layer2 = Input { SourceOp = "L2", Source = "Output", }, | ||
| 300 | ApplyMode2 = Input { Value = FuID { "Screen" }, }, | ||
| 301 | Blend = Input { Value = 0.5, }, | ||
| 302 | }, }, | ||
| 303 | MMOrder = MultiMerge { Inputs = { | ||
| 304 | Background = Input { SourceOp = "Bg", Source = "Output", }, | ||
| 305 | ["Layer1.Foreground"] = Input { SourceOp = "L1", Source = "Output", }, | ||
| 306 | ["Layer2.Foreground"] = Input { SourceOp = "L2", Source = "Output", }, | ||
| 307 | ["Layer1.Size"] = Input { Value = 0.5, }, | ||
| 308 | ["Layer1.Center"] = Input { Value = { 0.5, 0.5 }, }, | ||
| 309 | LayerOrder = Input { Value = { 2, 1 }, }, | ||
| 310 | }, }, | ||
| 311 | } }"#; | ||
| 312 | let comp = Comp::from_fusion_str(src).expect("parse MultiMerge comp"); | ||
| 313 | let Ok(mut eng) = Engine::new_headless() else { return }; | ||
| 314 | |||
| 315 | let (_, mm) = eval_px(&mut eng, &comp, "MM"); | ||
| 316 | let left = px_at(&mm, 64, 10, 32); | ||
| 317 | assert_eq!(left, [255, 0, 0, 255], "Left half gets L1 red only: {left:?}"); | ||
| 318 | let right = px_at(&mm, 64, 52, 32); | ||
| 319 | assert!((right[0] as i32 - 128).abs() <= 2 && right[1] == 0 && (right[2] as i32 - 128).abs() <= 2, "Right half blends L3 over L1: {right:?}"); | ||
| 320 | |||
| 321 | let (_, fmm) = eval_px(&mut eng, &comp, "FuseMM"); | ||
| 322 | let px = px_at(&fmm, 64, 32, 32); | ||
| 323 | assert!((px[0] as i32 - 128).abs() <= 2 && (px[1] as i32 - 128).abs() <= 2 && px[2] == 0, "Fuse.MultiMerge screen+global blend: {px:?}"); | ||
| 324 | |||
| 325 | let (_, mmo) = eval_px(&mut eng, &comp, "MMOrder"); | ||
| 326 | // LayerOrder={2,1} draws L2 green first (full frame), then L1 red (Size=0.5 centered) on top! | ||
| 327 | assert_eq!(px_at(&mmo, 64, 4, 32), [0, 255, 0, 255], "Outer pixel shows L2 green"); | ||
| 328 | assert_eq!(px_at(&mmo, 64, 32, 32), [255, 0, 0, 255], "Center pixel shows L1 red on top"); | ||
| 329 | } | ||
crates/engine/src/eval/mod.rs+15| ... | @@ -16,6 +16,7 @@ use web_time::Instant; | ... | @@ -16,6 +16,7 @@ use web_time::Instant; |
| 16 | mod io; | 16 | mod io; |
| 17 | mod alpha_keyers; | 17 | mod alpha_keyers; |
| 18 | mod aux_ops; | 18 | mod aux_ops; |
| 19 | mod color_science; | ||
| 19 | mod depth_optical; | 20 | mod depth_optical; |
| 20 | mod composite; | 21 | mod composite; |
| 21 | mod transform; | 22 | mod transform; |
| ... | @@ -74,6 +75,7 @@ pub struct Engine { | ... | @@ -74,6 +75,7 @@ pub struct Engine { |
| 74 | pipelines_f32: OnceCell<RefCell<ShaderRegistry>>, | 75 | pipelines_f32: OnceCell<RefCell<ShaderRegistry>>, |
| 75 | aux_pipelines: OnceCell<RefCell<aux_ops::AuxPipelines>>, | 76 | aux_pipelines: OnceCell<RefCell<aux_ops::AuxPipelines>>, |
| 76 | alpha_keyer_pipelines: OnceCell<RefCell<alpha_keyers::AlphaKeyerPipelines>>, | 77 | alpha_keyer_pipelines: OnceCell<RefCell<alpha_keyers::AlphaKeyerPipelines>>, |
| 78 | color_science_pipelines: OnceCell<RefCell<color_science::ColorSciencePipelines>>, | ||
| 77 | depth_optical_pipelines: OnceCell<RefCell<depth_optical::DepthOpticalPipelines>>, | 79 | depth_optical_pipelines: OnceCell<RefCell<depth_optical::DepthOpticalPipelines>>, |
| 78 | warps_masks_pipelines: OnceCell<RefCell<warps_masks::WarpsMasksPipelines>>, | 80 | warps_masks_pipelines: OnceCell<RefCell<warps_masks::WarpsMasksPipelines>>, |
| 79 | motion_blur: crate::motion_blur::MotionBlurPipelines, | 81 | motion_blur: crate::motion_blur::MotionBlurPipelines, |
| ... | @@ -181,6 +183,7 @@ impl Engine { | ... | @@ -181,6 +183,7 @@ impl Engine { |
| 181 | pipelines_f32: OnceCell::new(), | 183 | pipelines_f32: OnceCell::new(), |
| 182 | aux_pipelines: OnceCell::new(), | 184 | aux_pipelines: OnceCell::new(), |
| 183 | alpha_keyer_pipelines: OnceCell::new(), | 185 | alpha_keyer_pipelines: OnceCell::new(), |
| 186 | color_science_pipelines: OnceCell::new(), | ||
| 184 | depth_optical_pipelines: OnceCell::new(), | 187 | depth_optical_pipelines: OnceCell::new(), |
| 185 | warps_masks_pipelines: OnceCell::new(), | 188 | warps_masks_pipelines: OnceCell::new(), |
| 186 | motion_blur: crate::motion_blur::MotionBlurPipelines::default(), | 189 | motion_blur: crate::motion_blur::MotionBlurPipelines::default(), |
| ... | @@ -327,6 +330,9 @@ impl Engine { | ... | @@ -327,6 +330,9 @@ impl Engine { |
| 327 | if let Some(ak) = self.alpha_keyer_pipelines.get() { | 330 | if let Some(ak) = self.alpha_keyer_pipelines.get() { |
| 328 | ak.borrow_mut().reset_uniform_cursor(); | 331 | ak.borrow_mut().reset_uniform_cursor(); |
| 329 | } | 332 | } |
| 333 | if let Some(cs) = self.color_science_pipelines.get() { | ||
| 334 | cs.borrow_mut().reset_uniform_cursor(); | ||
| 335 | } | ||
| 330 | if let Some(dp) = self.depth_optical_pipelines.get() { | 336 | if let Some(dp) = self.depth_optical_pipelines.get() { |
| 331 | dp.borrow_mut().reset_uniform_cursor(); | 337 | dp.borrow_mut().reset_uniform_cursor(); |
| 332 | } | 338 | } |
| ... | @@ -347,6 +353,9 @@ impl Engine { | ... | @@ -347,6 +353,9 @@ impl Engine { |
| 347 | if let Some(ak) = self.alpha_keyer_pipelines.get() { | 353 | if let Some(ak) = self.alpha_keyer_pipelines.get() { |
| 348 | ak.borrow_mut().trim_uniform_chunks(2); | 354 | ak.borrow_mut().trim_uniform_chunks(2); |
| 349 | } | 355 | } |
| 356 | if let Some(cs) = self.color_science_pipelines.get() { | ||
| 357 | cs.borrow_mut().trim_uniform_chunks(2); | ||
| 358 | } | ||
| 350 | if let Some(dp) = self.depth_optical_pipelines.get() { | 359 | if let Some(dp) = self.depth_optical_pipelines.get() { |
| 351 | dp.borrow_mut().trim_uniform_chunks(2); | 360 | dp.borrow_mut().trim_uniform_chunks(2); |
| 352 | } | 361 | } |
| ... | @@ -818,6 +827,7 @@ impl Engine { | ... | @@ -818,6 +827,7 @@ impl Engine { |
| 818 | "Loader" => self.eval_loader(comp, node, time, frame_i, enc, visiting, stats), | 827 | "Loader" => self.eval_loader(comp, node, time, frame_i, enc, visiting, stats), |
| 819 | "Background" => self.eval_background(comp, node, time, frame_i, comp_dims, enc, visiting, stats), | 828 | "Background" => self.eval_background(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 820 | "Merge" => self.eval_merge(comp, node, time, frame_i, enc, visiting, stats), | 829 | "Merge" => self.eval_merge(comp, node, time, frame_i, enc, visiting, stats), |
| 830 | "MultiMerge" | "Fuse.MultiMerge" => self.eval_multi_merge(comp, node, time, frame_i, enc, visiting, stats), | ||
| 821 | "Dissolve" => self.eval_dissolve(comp, node, time, frame_i, enc, visiting, stats), | 831 | "Dissolve" => self.eval_dissolve(comp, node, time, frame_i, enc, visiting, stats), |
| 822 | "Transform" => self.eval_transform(comp, node, time, frame_i, enc, visiting, stats), | 832 | "Transform" => self.eval_transform(comp, node, time, frame_i, enc, visiting, stats), |
| 823 | "CameraShake" => self.eval_camera_shake(comp, node, time, frame_i, enc, visiting, stats), | 833 | "CameraShake" => self.eval_camera_shake(comp, node, time, frame_i, enc, visiting, stats), |
| ... | @@ -852,6 +862,11 @@ impl Engine { | ... | @@ -852,6 +862,11 @@ impl Engine { |
| 852 | "ColorCurves" => self.eval_color_curves(comp, node, time, frame_i, enc, visiting, stats), | 862 | "ColorCurves" => self.eval_color_curves(comp, node, time, frame_i, enc, visiting, stats), |
| 853 | "HueCurves" => self.eval_hue_curves(comp, node, time, frame_i, enc, visiting, stats), | 863 | "HueCurves" => self.eval_hue_curves(comp, node, time, frame_i, enc, visiting, stats), |
| 854 | "GamutConvert" => self.eval_gamut_convert(comp, node, time, frame_i, enc, visiting, stats), | 864 | "GamutConvert" => self.eval_gamut_convert(comp, node, time, frame_i, enc, visiting, stats), |
| 865 | "AcesTransform" => self.eval_aces_transform(comp, node, time, frame_i, enc, visiting, stats), | ||
| 866 | "ColorSpace" => self.eval_color_space(comp, node, time, frame_i, enc, visiting, stats), | ||
| 867 | "ColorMatrix" => self.eval_color_matrix(comp, node, time, frame_i, enc, visiting, stats), | ||
| 868 | "WhiteBalance" => self.eval_white_balance(comp, node, time, frame_i, enc, visiting, stats), | ||
| 869 | "MatteControl" => self.eval_matte_control(comp, node, time, frame_i, enc, visiting, stats), | ||
| 855 | "InvertColor" => self.eval_invert(comp, node, time, frame_i, enc, visiting, stats), | 870 | "InvertColor" => self.eval_invert(comp, node, time, frame_i, enc, visiting, stats), |
| 856 | "AlphaMultiply" => self.eval_alpha_multiply(comp, node, time, frame_i, enc, visiting, stats), | 871 | "AlphaMultiply" => self.eval_alpha_multiply(comp, node, time, frame_i, enc, visiting, stats), |
| 857 | "AlphaDivide" => self.eval_alpha_divide(comp, node, time, frame_i, enc, visiting, stats), | 872 | "AlphaDivide" => self.eval_alpha_divide(comp, node, time, frame_i, enc, visiting, stats), |
crates/engine/src/shaders/color_science.wgsl created+720| ... | @@ -0,0 +1,720 @@ | ||
| 1 | // Wave 36 — Color Science, MatteControl & MultiMerge compute shaders (100% WebGPU-safe). | ||
| 2 | // | ||
| 3 | // All input textures are bound as unfilterable `texture_2d<f32>` and read via `textureLoad` | ||
| 4 | // (with manual bilinear interpolation where needed), so every pass works uniformly on | ||
| 5 | // `Rgba8Unorm`, `Rgba16Float`, and `Rgba32Float` on native and `wasm32` without requiring | ||
| 6 | // `FLOAT32_FILTERABLE` or `read_write` storage textures. | ||
| 7 | |||
| 8 | @group(0) @binding(0) var tex_a: texture_2d<f32>; | ||
| 9 | @group(0) @binding(1) var tex_b: texture_2d<f32>; | ||
| 10 | @group(0) @binding(2) var tex_c: texture_2d<f32>; | ||
| 11 | @group(0) @binding(3) var mask_tex: texture_2d<f32>; | ||
| 12 | @group(0) @binding(4) var dst_tex: texture_storage_2d<rgba8unorm, write>; | ||
| 13 | |||
| 14 | struct Params { | ||
| 15 | p: array<vec4<f32>, 16>, | ||
| 16 | }; | ||
| 17 | @group(0) @binding(5) var<uniform> u: Params; | ||
| 18 | |||
| 19 | const HDR_FLOAT: bool = false; | ||
| 20 | |||
| 21 | fn store_dst(p: vec2<i32>, col: vec4<f32>) { | ||
| 22 | if (HDR_FLOAT) { | ||
| 23 | textureStore(dst_tex, p, col); | ||
| 24 | } else { | ||
| 25 | textureStore(dst_tex, p, clamp(col, vec4<f32>(0.0), vec4<f32>(1.0))); | ||
| 26 | } | ||
| 27 | } | ||
| 28 | |||
| 29 | fn load_clamped(tex: texture_2d<f32>, p: vec2<i32>) -> vec4<f32> { | ||
| 30 | let d = vec2<i32>(textureDimensions(tex)); | ||
| 31 | let c = clamp(p, vec2<i32>(0), max(d - vec2<i32>(1), vec2<i32>(0))); | ||
| 32 | return textureLoad(tex, c, 0); | ||
| 33 | } | ||
| 34 | |||
| 35 | fn sample_bilinear(tex: texture_2d<f32>, uv: vec2<f32>) -> vec4<f32> { | ||
| 36 | let dims = vec2<f32>(textureDimensions(tex)); | ||
| 37 | let pos = uv * dims - vec2<f32>(0.5); | ||
| 38 | let p0 = vec2<i32>(floor(pos)); | ||
| 39 | let f = pos - vec2<f32>(p0); | ||
| 40 | let c00 = load_clamped(tex, p0); | ||
| 41 | let c10 = load_clamped(tex, p0 + vec2<i32>(1, 0)); | ||
| 42 | let c01 = load_clamped(tex, p0 + vec2<i32>(0, 1)); | ||
| 43 | let c11 = load_clamped(tex, p0 + vec2<i32>(1, 1)); | ||
| 44 | return mix(mix(c00, c10, f.x), mix(c01, c11, f.x), f.y); | ||
| 45 | } | ||
| 46 | |||
| 47 | fn read_mask(gid: vec2<u32>, dims: vec2<u32>, has_mask: f32, inv: f32) -> f32 { | ||
| 48 | if (has_mask < 0.5) { | ||
| 49 | return 1.0; | ||
| 50 | } | ||
| 51 | let uv = (vec2<f32>(gid) + vec2<f32>(0.5)) / vec2<f32>(dims); | ||
| 52 | let m = sample_bilinear(mask_tex, uv).a; | ||
| 53 | return select(m, 1.0 - m, inv > 0.5); | ||
| 54 | } | ||
| 55 | |||
| 56 | fn apply_mask_blend( | ||
| 57 | src: vec4<f32>, | ||
| 58 | res: vec4<f32>, | ||
| 59 | gid: vec2<u32>, | ||
| 60 | dims: vec2<u32>, | ||
| 61 | blend: f32, | ||
| 62 | has_mask: f32, | ||
| 63 | mask_inv: f32, | ||
| 64 | mbm: f32, | ||
| 65 | skip: vec4<f32>, | ||
| 66 | ) -> vec4<f32> { | ||
| 67 | let raw_mask = read_mask(gid, dims, has_mask, mask_inv); | ||
| 68 | let m = clamp(raw_mask * blend, 0.0, 1.0); | ||
| 69 | let use_mbm = has_mask > 0.5 && mbm > 0.5; | ||
| 70 | var out_col = select(mix(src, res, m), res * m, use_mbm); | ||
| 71 | let unproc = select(src, vec4<f32>(0.0), use_mbm); | ||
| 72 | out_col = select(out_col, unproc, skip > vec4<f32>(0.5)); | ||
| 73 | return out_col; | ||
| 74 | } | ||
| 75 | |||
| 76 | fn mul_mat3_rows(r0: vec3<f32>, r1: vec3<f32>, r2: vec3<f32>, v: vec3<f32>) -> vec3<f32> { | ||
| 77 | return vec3<f32>(dot(r0, v), dot(r1, v), dot(r2, v)); | ||
| 78 | } | ||
| 79 | |||
| 80 | // ============================================================================ | ||
| 81 | // Transfer functions (exact algebraic inverses for ACES 1.3 / sRGB / Rec.709) | ||
| 82 | // ============================================================================ | ||
| 83 | fn srgb_to_linear_ch(c: f32) -> f32 { | ||
| 84 | let s = select(1.0, -1.0, c < 0.0); | ||
| 85 | let a = abs(c); | ||
| 86 | let lin = select(pow((a + 0.055) / 1.055, 2.4), a / 12.92, a <= 0.04045); | ||
| 87 | return s * lin; | ||
| 88 | } | ||
| 89 | |||
| 90 | fn linear_to_srgb_ch(c: f32) -> f32 { | ||
| 91 | let s = select(1.0, -1.0, c < 0.0); | ||
| 92 | let a = abs(c); | ||
| 93 | let enc = select(1.055 * pow(a, 1.0 / 2.4) - 0.055, a * 12.92, a <= 0.0031308); | ||
| 94 | return s * enc; | ||
| 95 | } | ||
| 96 | |||
| 97 | fn rec709_to_linear_ch(c: f32) -> f32 { | ||
| 98 | let s = select(1.0, -1.0, c < 0.0); | ||
| 99 | let a = abs(c); | ||
| 100 | let lin = select(pow((a + 0.099) / 1.099, 1.0 / 0.45), a / 4.5, a < 0.081); | ||
| 101 | return s * lin; | ||
| 102 | } | ||
| 103 | |||
| 104 | fn linear_to_rec709_ch(c: f32) -> f32 { | ||
| 105 | let s = select(1.0, -1.0, c < 0.0); | ||
| 106 | let a = abs(c); | ||
| 107 | let enc = select(1.099 * pow(a, 0.45) - 0.099, a * 4.5, a < 0.018); | ||
| 108 | return s * enc; | ||
| 109 | } | ||
| 110 | |||
| 111 | // Academy S-2016-001 ACEScct exact transfer | ||
| 112 | const ACESCCT_X_BRK: f32 = 0.0078125; | ||
| 113 | const ACESCCT_Y_BRK: f32 = 0.155251141552511; | ||
| 114 | const ACESCCT_A: f32 = 10.5402377416545; | ||
| 115 | const ACESCCT_B: f32 = 0.0729055341958355; | ||
| 116 | |||
| 117 | fn acescct_to_linear_ch(y: f32) -> f32 { | ||
| 118 | if (y <= ACESCCT_Y_BRK) { | ||
| 119 | return (y - ACESCCT_B) / ACESCCT_A; | ||
| 120 | } | ||
| 121 | let y_max = (log2(65504.0) + 9.72) / 17.52; | ||
| 122 | if (y < y_max) { | ||
| 123 | return exp2(y * 17.52 - 9.72); | ||
| 124 | } | ||
| 125 | return 65504.0; | ||
| 126 | } | ||
| 127 | |||
| 128 | fn linear_to_acescct_ch(x: f32) -> f32 { | ||
| 129 | if (x <= ACESCCT_X_BRK) { | ||
| 130 | return ACESCCT_A * x + ACESCCT_B; | ||
| 131 | } | ||
| 132 | return (log2(x) + 9.72) / 17.52; | ||
| 133 | } | ||
| 134 | |||
| 135 | // Academy S-2014-003 ACEScc exact transfer | ||
| 136 | fn acescc_to_linear_ch(y: f32) -> f32 { | ||
| 137 | let y_lo = (9.72 - 15.0) / 17.52; | ||
| 138 | if (y < y_lo) { | ||
| 139 | return (exp2(y * 17.52 - 9.72) - exp2(-16.0)) * 2.0; | ||
| 140 | } | ||
| 141 | let y_max = (log2(65504.0) + 9.72) / 17.52; | ||
| 142 | if (y < y_max) { | ||
| 143 | return exp2(y * 17.52 - 9.72); | ||
| 144 | } | ||
| 145 | return 65504.0; | ||
| 146 | } | ||
| 147 | |||
| 148 | fn linear_to_acescc_ch(x: f32) -> f32 { | ||
| 149 | if (x <= 0.0) { | ||
| 150 | return (-16.0 + 9.72) / 17.52; | ||
| 151 | } | ||
| 152 | if (x < exp2(-15.0)) { | ||
| 153 | return (log2(exp2(-16.0) + x * 0.5) + 9.72) / 17.52; | ||
| 154 | } | ||
| 155 | return (log2(x) + 9.72) / 17.52; | ||
| 156 | } | ||
| 157 | |||
| 158 | fn decode_transfer(rgb: vec3<f32>, xfer: i32) -> vec3<f32> { | ||
| 159 | switch xfer { | ||
| 160 | case 1: { return vec3<f32>(acescct_to_linear_ch(rgb.r), acescct_to_linear_ch(rgb.g), acescct_to_linear_ch(rgb.b)); } | ||
| 161 | case 2: { return vec3<f32>(acescc_to_linear_ch(rgb.r), acescc_to_linear_ch(rgb.g), acescc_to_linear_ch(rgb.b)); } | ||
| 162 | case 3: { return vec3<f32>(srgb_to_linear_ch(rgb.r), srgb_to_linear_ch(rgb.g), srgb_to_linear_ch(rgb.b)); } | ||
| 163 | case 4: { return vec3<f32>(rec709_to_linear_ch(rgb.r), rec709_to_linear_ch(rgb.g), rec709_to_linear_ch(rgb.b)); } | ||
| 164 | default: { return rgb; } | ||
| 165 | } | ||
| 166 | } | ||
| 167 | |||
| 168 | fn encode_transfer(rgb: vec3<f32>, xfer: i32) -> vec3<f32> { | ||
| 169 | switch xfer { | ||
| 170 | case 1: { return vec3<f32>(linear_to_acescct_ch(rgb.r), linear_to_acescct_ch(rgb.g), linear_to_acescct_ch(rgb.b)); } | ||
| 171 | case 2: { return vec3<f32>(linear_to_acescc_ch(rgb.r), linear_to_acescc_ch(rgb.g), linear_to_acescc_ch(rgb.b)); } | ||
| 172 | case 3: { return vec3<f32>(linear_to_srgb_ch(rgb.r), linear_to_srgb_ch(rgb.g), linear_to_srgb_ch(rgb.b)); } | ||
| 173 | case 4: { return vec3<f32>(linear_to_rec709_ch(rgb.r), linear_to_rec709_ch(rgb.g), linear_to_rec709_ch(rgb.b)); } | ||
| 174 | default: { return rgb; } | ||
| 175 | } | ||
| 176 | } | ||
| 177 | |||
| 178 | // Academy S-2021-001 ACES 1.3 Reference Gamut Compression (in AP1 linear space) | ||
| 179 | fn rgc_compress_ch(dist: f32, lim: f32, thr: f32, pwr: f32) -> f32 { | ||
| 180 | if (dist <= thr) { | ||
| 181 | return dist; | ||
| 182 | } | ||
| 183 | let s = (lim - thr) / pow(pow((1.0 - thr) / (lim - thr), -pwr) - 1.0, 1.0 / pwr); | ||
| 184 | let nd = (dist - thr) / s; | ||
| 185 | return thr + s * nd / pow(1.0 + pow(nd, pwr), 1.0 / pwr); | ||
| 186 | } | ||
| 187 | |||
| 188 | fn aces_reference_gamut_compress(ap1: vec3<f32>) -> vec3<f32> { | ||
| 189 | let ach = max(ap1.r, max(ap1.g, ap1.b)); | ||
| 190 | if (ach <= 1e-6) { | ||
| 191 | return ap1; | ||
| 192 | } | ||
| 193 | let inv_ach = 1.0 / abs(ach); | ||
| 194 | let d = (vec3<f32>(ach) - ap1) * inv_ach; | ||
| 195 | let dc = vec3<f32>( | ||
| 196 | rgc_compress_ch(d.r, 1.147, 0.815, 1.2), | ||
| 197 | rgc_compress_ch(d.g, 1.264, 0.803, 1.2), | ||
| 198 | rgc_compress_ch(d.b, 1.312, 0.880, 1.2), | ||
| 199 | ); | ||
| 200 | return vec3<f32>(ach) - dc * abs(ach); | ||
| 201 | } | ||
| 202 | |||
| 203 | // ACES 1.3 RRT + ODT fit in AP1 space (with RRT_SAT=0.96, ODT_SAT=0.93) | ||
| 204 | fn aces_rrt_odt_ap1(ap1_in: vec3<f32>, lum_scale: f32) -> vec3<f32> { | ||
| 205 | let ap1_w = vec3<f32>(0.2722287168, 0.6740817658, 0.0536895174); | ||
| 206 | let v_scaled = max(ap1_in * lum_scale, vec3<f32>(0.0)); | ||
| 207 | let luma0 = dot(v_scaled, ap1_w); | ||
| 208 | let v = mix(vec3<f32>(luma0), v_scaled, 0.96); | ||
| 209 | let a = v * (v + 0.0245786) - 0.000090537; | ||
| 210 | let b = v * (0.983729 * v + 0.4329510) + 0.238081; | ||
| 211 | let t = max(a / b, vec3<f32>(0.0)); | ||
| 212 | let luma1 = dot(t, ap1_w); | ||
| 213 | return mix(vec3<f32>(luma1), t, 0.93); | ||
| 214 | } | ||
| 215 | |||
| 216 | // ============================================================================ | ||
| 217 | // 1. AcesTransform | ||
| 218 | // p[0] = (in_xfer, out_xfer, use_rgc, use_rrt_odt) | ||
| 219 | // p[1] = (lum_scale, blend, has_mask, mask_inv) | ||
| 220 | // p[2] = (mbm, 0, 0, 0) | ||
| 221 | // p[3] = (skip_r, skip_g, skip_b, skip_a) | ||
| 222 | // p[4..6] = M1 rows (in_linear -> AP1 if rgc/rrt, else direct in_linear -> out_linear) | ||
| 223 | // p[7..9] = M2 rows (AP1 -> out_linear when rgc/rrt active) | ||
| 224 | // ============================================================================ | ||
| 225 | @compute @workgroup_size(8, 8) | ||
| 226 | fn aces_transform_op(@builtin(global_invocation_id) gid: vec3<u32>) { | ||
| 227 | let dims = textureDimensions(dst_tex); | ||
| 228 | if (gid.x >= dims.x || gid.y >= dims.y) { return; } | ||
| 229 | let p = vec2<i32>(gid.xy); | ||
| 230 | let src = textureLoad(tex_a, p, 0); | ||
| 231 | |||
| 232 | let in_xfer = i32(round(u.p[0].x)); | ||
| 233 | let out_xfer = i32(round(u.p[0].y)); | ||
| 234 | let use_rgc = u.p[0].z > 0.5; | ||
| 235 | let use_rrt = u.p[0].w > 0.5; | ||
| 236 | let lum_scale = u.p[1].x; | ||
| 237 | |||
| 238 | var rgb = decode_transfer(src.rgb, in_xfer); | ||
| 239 | rgb = mul_mat3_rows(u.p[4].xyz, u.p[5].xyz, u.p[6].xyz, rgb); | ||
| 240 | |||
| 241 | if (use_rgc || use_rrt) { | ||
| 242 | if (use_rgc) { | ||
| 243 | rgb = aces_reference_gamut_compress(rgb); | ||
| 244 | } | ||
| 245 | if (use_rrt) { | ||
| 246 | rgb = aces_rrt_odt_ap1(rgb, lum_scale); | ||
| 247 | } | ||
| 248 | rgb = mul_mat3_rows(u.p[7].xyz, u.p[8].xyz, u.p[9].xyz, rgb); | ||
| 249 | if (use_rrt) { | ||
| 250 | rgb = clamp(rgb, vec3<f32>(0.0), vec3<f32>(1.0)); | ||
| 251 | } | ||
| 252 | } | ||
| 253 | |||
| 254 | rgb = encode_transfer(rgb, out_xfer); | ||
| 255 | let res = vec4<f32>(rgb, src.a); | ||
| 256 | let out_col = apply_mask_blend( | ||
| 257 | src, res, gid.xy, dims, u.p[1].y, u.p[1].z, u.p[1].w, u.p[2].x, u.p[3], | ||
| 258 | ); | ||
| 259 | store_dst(p, out_col); | ||
| 260 | } | ||
| 261 | |||
| 262 | // ============================================================================ | ||
| 263 | // 2. ColorSpace (RGB <-> BW / YUV / YIQ / CMY / HLS / HSV / XYZ / LAB / YCbCr) | ||
| 264 | // p[0] = (conv_dir: 0=none 1=to_color 2=from_color, color_type: 0..8, blend, has_mask) | ||
| 265 | // p[1] = (mask_inv, mbm, 0, 0) | ||
| 266 | // p[2] = (skip_r, skip_g, skip_b, skip_a) | ||
| 267 | // ============================================================================ | ||
| 268 | fn cs_rgb_to_hls(c: vec3<f32>) -> vec3<f32> { | ||
| 269 | let mx = max(c.r, max(c.g, c.b)); | ||
| 270 | let mn = min(c.r, min(c.g, c.b)); | ||
| 271 | let l = 0.5 * (mx + mn); | ||
| 272 | let d = mx - mn; | ||
| 273 | if (d <= 1e-6) { | ||
| 274 | return vec3<f32>(0.0, l, 0.0); | ||
| 275 | } | ||
| 276 | let denom = 1.0 - abs(2.0 * l - 1.0); | ||
| 277 | let s = select(0.0, d / denom, denom > 1e-6); | ||
| 278 | var h: f32; | ||
| 279 | if (mx == c.r) { | ||
| 280 | h = (c.g - c.b) / d + select(0.0, 6.0, c.g < c.b); | ||
| 281 | } else if (mx == c.g) { | ||
| 282 | h = (c.b - c.r) / d + 2.0; | ||
| 283 | } else { | ||
| 284 | h = (c.r - c.g) / d + 4.0; | ||
| 285 | } | ||
| 286 | return vec3<f32>(fract(h / 6.0), l, s); | ||
| 287 | } | ||
| 288 | |||
| 289 | fn cs_hue_to_rgb(p: f32, q: f32, t_in: f32) -> f32 { | ||
| 290 | let t = fract(t_in); | ||
| 291 | if (t < 1.0 / 6.0) { return p + (q - p) * 6.0 * t; } | ||
| 292 | if (t < 0.5) { return q; } | ||
| 293 | if (t < 2.0 / 3.0) { return p + (q - p) * (2.0 / 3.0 - t) * 6.0; } | ||
| 294 | return p; | ||
| 295 | } | ||
| 296 | |||
| 297 | fn cs_hls_to_rgb(hls: vec3<f32>) -> vec3<f32> { | ||
| 298 | let h = hls.x; | ||
| 299 | let l = hls.y; | ||
| 300 | let s = hls.z; | ||
| 301 | if (s <= 1e-6) { | ||
| 302 | return vec3<f32>(l); | ||
| 303 | } | ||
| 304 | let q = select(l + s - l * s, l * (1.0 + s), l < 0.5); | ||
| 305 | let p = 2.0 * l - q; | ||
| 306 | return vec3<f32>( | ||
| 307 | cs_hue_to_rgb(p, q, h + 1.0 / 3.0), | ||
| 308 | cs_hue_to_rgb(p, q, h), | ||
| 309 | cs_hue_to_rgb(p, q, h - 1.0 / 3.0), | ||
| 310 | ); | ||
| 311 | } | ||
| 312 | |||
| 313 | fn cs_rgb_to_hsv(c: vec3<f32>) -> vec3<f32> { | ||
| 314 | let mx = max(c.r, max(c.g, c.b)); | ||
| 315 | let mn = min(c.r, min(c.g, c.b)); | ||
| 316 | let d = mx - mn; | ||
| 317 | let s = select(0.0, d / mx, mx > 1e-6); | ||
| 318 | if (d <= 1e-6) { | ||
| 319 | return vec3<f32>(0.0, s, mx); | ||
| 320 | } | ||
| 321 | var h: f32; | ||
| 322 | if (mx == c.r) { | ||
| 323 | h = (c.g - c.b) / d + select(0.0, 6.0, c.g < c.b); | ||
| 324 | } else if (mx == c.g) { | ||
| 325 | h = (c.b - c.r) / d + 2.0; | ||
| 326 | } else { | ||
| 327 | h = (c.r - c.g) / d + 4.0; | ||
| 328 | } | ||
| 329 | return vec3<f32>(fract(h / 6.0), s, mx); | ||
| 330 | } | ||
| 331 | |||
| 332 | fn cs_hsv_to_rgb(hsv: vec3<f32>) -> vec3<f32> { | ||
| 333 | let h = fract(hsv.x) * 6.0; | ||
| 334 | let s = hsv.y; | ||
| 335 | let v = hsv.z; | ||
| 336 | let c = v * s; | ||
| 337 | let x = c * (1.0 - abs(h - 2.0 * floor(h * 0.5) - 1.0)); | ||
| 338 | let m = v - c; | ||
| 339 | var rgb: vec3<f32>; | ||
| 340 | if (h < 1.0) { rgb = vec3<f32>(c, x, 0.0); } | ||
| 341 | else if (h < 2.0) { rgb = vec3<f32>(x, c, 0.0); } | ||
| 342 | else if (h < 3.0) { rgb = vec3<f32>(0.0, c, x); } | ||
| 343 | else if (h < 4.0) { rgb = vec3<f32>(0.0, x, c); } | ||
| 344 | else if (h < 5.0) { rgb = vec3<f32>(x, 0.0, c); } | ||
| 345 | else { rgb = vec3<f32>(c, 0.0, x); } | ||
| 346 | return rgb + vec3<f32>(m); | ||
| 347 | } | ||
| 348 | |||
| 349 | fn cs_rgb_to_xyz(c: vec3<f32>) -> vec3<f32> { | ||
| 350 | return vec3<f32>( | ||
| 351 | 0.4124564 * c.r + 0.3575761 * c.g + 0.1804375 * c.b, | ||
| 352 | 0.2126729 * c.r + 0.7151522 * c.g + 0.0721750 * c.b, | ||
| 353 | 0.0193339 * c.r + 0.1191920 * c.g + 0.9503041 * c.b, | ||
| 354 | ); | ||
| 355 | } | ||
| 356 | |||
| 357 | fn cs_xyz_to_rgb(xyz: vec3<f32>) -> vec3<f32> { | ||
| 358 | return vec3<f32>( | ||
| 359 | 3.2404542 * xyz.x - 1.5371385 * xyz.y - 0.4985314 * xyz.z, | ||
| 360 | -0.9692660 * xyz.x + 1.8760108 * xyz.y + 0.0415560 * xyz.z, | ||
| 361 | 0.0556434 * xyz.x - 0.2040259 * xyz.y + 1.0572252 * xyz.z, | ||
| 362 | ); | ||
| 363 | } | ||
| 364 | |||
| 365 | fn lab_f(t: f32) -> f32 { | ||
| 366 | let eps = 216.0 / 24389.0; | ||
| 367 | let k = 24389.0 / 27.0; | ||
| 368 | if (t > eps) { | ||
| 369 | return pow(t, 1.0 / 3.0); | ||
| 370 | } | ||
| 371 | return (k * t + 16.0) / 116.0; | ||
| 372 | } | ||
| 373 | |||
| 374 | fn lab_f_inv(t: f32) -> f32 { | ||
| 375 | let delta = 6.0 / 29.0; | ||
| 376 | if (t > delta) { | ||
| 377 | return t * t * t; | ||
| 378 | } | ||
| 379 | return 3.0 * delta * delta * (t - 4.0 / 29.0); | ||
| 380 | } | ||
| 381 | |||
| 382 | fn cs_rgb_to_lab(c: vec3<f32>) -> vec3<f32> { | ||
| 383 | let xyz = cs_rgb_to_xyz(c); | ||
| 384 | let fx = lab_f(xyz.x / 0.95047); | ||
| 385 | let fy = lab_f(xyz.y / 1.00000); | ||
| 386 | let fz = lab_f(xyz.z / 1.08883); | ||
| 387 | let l_star = 116.0 * fy - 16.0; | ||
| 388 | let a_star = 500.0 * (fx - fy); | ||
| 389 | let b_star = 200.0 * (fy - fz); | ||
| 390 | return vec3<f32>(l_star / 100.0, a_star / 256.0 + 0.5, b_star / 256.0 + 0.5); | ||
| 391 | } | ||
| 392 | |||
| 393 | fn cs_lab_to_rgb(lab: vec3<f32>) -> vec3<f32> { | ||
| 394 | let l_star = lab.x * 100.0; | ||
| 395 | let a_star = (lab.y - 0.5) * 256.0; | ||
| 396 | let b_star = (lab.z - 0.5) * 256.0; | ||
| 397 | let fy = (l_star + 16.0) / 116.0; | ||
| 398 | let fx = fy + a_star / 500.0; | ||
| 399 | let fz = fy - b_star / 200.0; | ||
| 400 | let xyz = vec3<f32>(0.95047 * lab_f_inv(fx), 1.00000 * lab_f_inv(fy), 1.08883 * lab_f_inv(fz)); | ||
| 401 | return cs_xyz_to_rgb(xyz); | ||
| 402 | } | ||
| 403 | |||
| 404 | fn cs_rgb_to_yuv_k(c: vec3<f32>, kr: f32, kg: f32, kb: f32) -> vec3<f32> { | ||
| 405 | let y = kr * c.r + kg * c.g + kb * c.b; | ||
| 406 | let u_ch = (c.b - y) / (2.0 * (1.0 - kb)) + 0.5; | ||
| 407 | let v_ch = (c.r - y) / (2.0 * (1.0 - kr)) + 0.5; | ||
| 408 | return vec3<f32>(y, u_ch, v_ch); | ||
| 409 | } | ||
| 410 | |||
| 411 | fn cs_yuv_to_rgb_k(yuv: vec3<f32>, kr: f32, kg: f32, kb: f32) -> vec3<f32> { | ||
| 412 | let y = yuv.x; | ||
| 413 | let u_ch = yuv.y - 0.5; | ||
| 414 | let v_ch = yuv.z - 0.5; | ||
| 415 | let r = y + 2.0 * (1.0 - kr) * v_ch; | ||
| 416 | let b = y + 2.0 * (1.0 - kb) * u_ch; | ||
| 417 | let g = (y - kr * r - kb * b) / kg; | ||
| 418 | return vec3<f32>(r, g, b); | ||
| 419 | } | ||
| 420 | |||
| 421 | fn cs_rgb_to_yiq(c: vec3<f32>) -> vec3<f32> { | ||
| 422 | let y = 0.299 * c.r + 0.587 * c.g + 0.114 * c.b; | ||
| 423 | let i = 0.595716 * c.r - 0.274453 * c.g - 0.321263 * c.b; | ||
| 424 | let q = 0.211456 * c.r - 0.522591 * c.g + 0.311135 * c.b; | ||
| 425 | return vec3<f32>(y, i * 0.5 + 0.5, q * 0.5 + 0.5); | ||
| 426 | } | ||
| 427 | |||
| 428 | fn cs_yiq_to_rgb(yiq: vec3<f32>) -> vec3<f32> { | ||
| 429 | let y = yiq.x; | ||
| 430 | let i = (yiq.y - 0.5) * 2.0; | ||
| 431 | let q = (yiq.z - 0.5) * 2.0; | ||
| 432 | return vec3<f32>( | ||
| 433 | y + 0.9562957 * i + 0.6210244 * q, | ||
| 434 | y - 0.2721221 * i - 0.6473806 * q, | ||
| 435 | y - 1.1069890 * i + 1.7046150 * q, | ||
| 436 | ); | ||
| 437 | } | ||
| 438 | |||
| 439 | @compute @workgroup_size(8, 8) | ||
| 440 | fn color_space_op(@builtin(global_invocation_id) gid: vec3<u32>) { | ||
| 441 | let dims = textureDimensions(dst_tex); | ||
| 442 | if (gid.x >= dims.x || gid.y >= dims.y) { return; } | ||
| 443 | let p = vec2<i32>(gid.xy); | ||
| 444 | let src = textureLoad(tex_a, p, 0); | ||
| 445 | |||
| 446 | let dir = i32(round(u.p[0].x)); | ||
| 447 | let ctype = i32(round(u.p[0].y)); | ||
| 448 | var rgb = src.rgb; | ||
| 449 | |||
| 450 | if (dir == 1) { | ||
| 451 | switch ctype { | ||
| 452 | case 0: { // BW | ||
| 453 | let l = dot(rgb, vec3<f32>(0.299, 0.587, 0.114)); | ||
| 454 | rgb = vec3<f32>(l); | ||
| 455 | } | ||
| 456 | case 1: { rgb = cs_rgb_to_yuv_k(rgb, 0.299, 0.587, 0.114); } | ||
| 457 | case 2: { rgb = cs_rgb_to_yiq(rgb); } | ||
| 458 | case 3: { rgb = vec3<f32>(1.0) - rgb; } | ||
| 459 | case 4: { rgb = cs_rgb_to_hls(rgb); } | ||
| 460 | case 5: { rgb = cs_rgb_to_hsv(rgb); } | ||
| 461 | case 6: { rgb = cs_rgb_to_xyz(rgb); } | ||
| 462 | case 7: { rgb = cs_rgb_to_lab(rgb); } | ||
| 463 | case 8: { rgb = cs_rgb_to_yuv_k(rgb, 0.2126, 0.7152, 0.0722); } | ||
| 464 | default: {} | ||
| 465 | } | ||
| 466 | } else if (dir == 2) { | ||
| 467 | switch ctype { | ||
| 468 | case 0: {} // BW -> RGB is already grayscale | ||
| 469 | case 1: { rgb = cs_yuv_to_rgb_k(rgb, 0.299, 0.587, 0.114); } | ||
| 470 | case 2: { rgb = cs_yiq_to_rgb(rgb); } | ||
| 471 | case 3: { rgb = vec3<f32>(1.0) - rgb; } | ||
| 472 | case 4: { rgb = cs_hls_to_rgb(rgb); } | ||
| 473 | case 5: { rgb = cs_hsv_to_rgb(rgb); } | ||
| 474 | case 6: { rgb = cs_xyz_to_rgb(rgb); } | ||
| 475 | case 7: { rgb = cs_lab_to_rgb(rgb); } | ||
| 476 | case 8: { rgb = cs_yuv_to_rgb_k(rgb, 0.2126, 0.7152, 0.0722); } | ||
| 477 | default: {} | ||
| 478 | } | ||
| 479 | } | ||
| 480 | |||
| 481 | let res = vec4<f32>(rgb, src.a); | ||
| 482 | let out_col = apply_mask_blend( | ||
| 483 | src, res, gid.xy, dims, u.p[0].z, u.p[0].w, u.p[1].x, u.p[1].y, u.p[2], | ||
| 484 | ); | ||
| 485 | store_dst(p, out_col); | ||
| 486 | } | ||
| 487 | |||
| 488 | // ============================================================================ | ||
| 489 | // 3. ColorMatrix (5x4 RGBA matrix + offset) | ||
| 490 | // p[0..3] = matrix rows R, G, B, A (each vec4(c_r, c_g, c_b, c_a)) | ||
| 491 | // p[4] = offsets (off_r, off_g, off_b, off_a) | ||
| 492 | // p[5] = (prediv, blend, has_mask, mask_inv) | ||
| 493 | // p[6] = (mbm, clip_black, clip_white, 0) | ||
| 494 | // p[7] = (skip_r, skip_g, skip_b, skip_a) | ||
| 495 | // ============================================================================ | ||
| 496 | @compute @workgroup_size(8, 8) | ||
| 497 | fn color_matrix_op(@builtin(global_invocation_id) gid: vec3<u32>) { | ||
| 498 | let dims = textureDimensions(dst_tex); | ||
| 499 | if (gid.x >= dims.x || gid.y >= dims.y) { return; } | ||
| 500 | let p = vec2<i32>(gid.xy); | ||
| 501 | let src = textureLoad(tex_a, p, 0); | ||
| 502 | |||
| 503 | let prediv = u.p[5].x > 0.5; | ||
| 504 | var c = src; | ||
| 505 | if (prediv && src.a > 1e-6) { | ||
| 506 | c = vec4<f32>(src.rgb / src.a, src.a); | ||
| 507 | } | ||
| 508 | |||
| 509 | var res = vec4<f32>( | ||
| 510 | dot(u.p[0], c) + u.p[4].x, | ||
| 511 | dot(u.p[1], c) + u.p[4].y, | ||
| 512 | dot(u.p[2], c) + u.p[4].z, | ||
| 513 | dot(u.p[3], c) + u.p[4].w, | ||
| 514 | ); | ||
| 515 | |||
| 516 | if (prediv) { | ||
| 517 | res = vec4<f32>(res.rgb * res.a, res.a); | ||
| 518 | } | ||
| 519 | if (u.p[6].y > 0.5) { | ||
| 520 | res = max(res, vec4<f32>(0.0)); | ||
| 521 | } | ||
| 522 | if (u.p[6].z > 0.5) { | ||
| 523 | res = min(res, vec4<f32>(1.0)); | ||
| 524 | } | ||
| 525 | |||
| 526 | let out_col = apply_mask_blend( | ||
| 527 | src, res, gid.xy, dims, u.p[5].y, u.p[5].z, u.p[5].w, u.p[6].x, u.p[7], | ||
| 528 | ); | ||
| 529 | store_dst(p, out_col); | ||
| 530 | } | ||
| 531 | |||
| 532 | // ============================================================================ | ||
| 533 | // 4. WhiteBalance (Kelvin temperature / tint / sampled white-point gains) | ||
| 534 | // p[0] = (gain_r, gain_g, gain_b, gamma_mode: 0=linear, 1=sRGB, 2=Rec709) | ||
| 535 | // p[1] = (prediv, blend, has_mask, mask_inv) | ||
| 536 | // p[2] = (mbm, 0, 0, 0) | ||
| 537 | // p[3] = (skip_r, skip_g, skip_b, skip_a) | ||
| 538 | // ============================================================================ | ||
| 539 | @compute @workgroup_size(8, 8) | ||
| 540 | fn white_balance_op(@builtin(global_invocation_id) gid: vec3<u32>) { | ||
| 541 | let dims = textureDimensions(dst_tex); | ||
| 542 | if (gid.x >= dims.x || gid.y >= dims.y) { return; } | ||
| 543 | let p = vec2<i32>(gid.xy); | ||
| 544 | let src = textureLoad(tex_a, p, 0); | ||
| 545 | |||
| 546 | let prediv = u.p[1].x > 0.5; | ||
| 547 | let gamma_mode = i32(round(u.p[0].w)); | ||
| 548 | var rgb = src.rgb; | ||
| 549 | if (prediv && src.a > 1e-6) { | ||
| 550 | rgb = rgb / src.a; | ||
| 551 | } | ||
| 552 | if (gamma_mode == 1) { | ||
| 553 | rgb = decode_transfer(rgb, 3); | ||
| 554 | } else if (gamma_mode == 2) { | ||
| 555 | rgb = decode_transfer(rgb, 4); | ||
| 556 | } | ||
| 557 | |||
| 558 | rgb = rgb * u.p[0].xyz; | ||
| 559 | |||
| 560 | if (gamma_mode == 1) { | ||
| 561 | rgb = encode_transfer(rgb, 3); | ||
| 562 | } else if (gamma_mode == 2) { | ||
| 563 | rgb = encode_transfer(rgb, 4); | ||
| 564 | } | ||
| 565 | if (prediv) { | ||
| 566 | rgb = rgb * src.a; | ||
| 567 | } | ||
| 568 | |||
| 569 | let res = vec4<f32>(rgb, src.a); | ||
| 570 | let out_col = apply_mask_blend( | ||
| 571 | src, res, gid.xy, dims, u.p[1].y, u.p[1].z, u.p[1].w, u.p[2].x, u.p[3], | ||
| 572 | ); | ||
| 573 | store_dst(p, out_col); | ||
| 574 | } | ||
| 575 | |||
| 576 | // ============================================================================ | ||
| 577 | // 5. MatteControl | ||
| 578 | // Pass A: matte_combine_op | ||
| 579 | // mode 0 (combine): tex_a = BG, tex_b = FG -> outputs vec4(m) | ||
| 580 | // p[0] = (mode=0, matte_combine: 0..5, combine_op: 0..6, has_fg) | ||
| 581 | // p[1] = (inv_fg, 0, 0, 0) | ||
| 582 | // mode 1 (refine): tex_a = matte, tex_c = garbage, mask_tex = solid -> outputs vec4(m) | ||
| 583 | // p[0] = (mode=1, thresh_lo, thresh_hi, matte_gamma) | ||
| 584 | // p[1] = (invert_matte, has_garbage, garbage_inv, has_solid) | ||
| 585 | // p[2] = (solid_inv, 0, 0, 0) | ||
| 586 | // ============================================================================ | ||
| 587 | @compute @workgroup_size(8, 8) | ||
| 588 | fn matte_combine_op(@builtin(global_invocation_id) gid: vec3<u32>) { | ||
| 589 | let dims = textureDimensions(dst_tex); | ||
| 590 | if (gid.x >= dims.x || gid.y >= dims.y) { return; } | ||
| 591 | let p = vec2<i32>(gid.xy); | ||
| 592 | let uv = (vec2<f32>(gid.xy) + vec2<f32>(0.5)) / vec2<f32>(dims); | ||
| 593 | let mode = i32(round(u.p[0].x)); | ||
| 594 | |||
| 595 | if (mode == 0) { | ||
| 596 | let bg_a = textureLoad(tex_a, p, 0).a; | ||
| 597 | let mc = i32(round(u.p[0].y)); | ||
| 598 | let op = i32(round(u.p[0].z)); | ||
| 599 | let has_fg = u.p[0].w > 0.5; | ||
| 600 | var m = bg_a; | ||
| 601 | if (has_fg && mc > 0) { | ||
| 602 | let fg = sample_bilinear(tex_b, uv); | ||
| 603 | var fg_m: f32; | ||
| 604 | switch mc { | ||
| 605 | case 1: { fg_m = fg.a; } | ||
| 606 | case 2: { fg_m = dot(fg.rgb, vec3<f32>(0.299, 0.587, 0.114)); } | ||
| 607 | case 3: { fg_m = fg.r; } | ||
| 608 | case 4: { fg_m = fg.g; } | ||
| 609 | case 5: { fg_m = fg.b; } | ||
| 610 | default: { fg_m = fg.a; } | ||
| 611 | } | ||
| 612 | if (u.p[1].x > 0.5) { | ||
| 613 | fg_m = 1.0 - fg_m; | ||
| 614 | } | ||
| 615 | switch op { | ||
| 616 | case 0: { m = fg_m; } // Copy | ||
| 617 | case 1: { m = clamp(bg_a + fg_m, 0.0, 1.0); } // Add | ||
| 618 | case 2: { m = clamp(bg_a - fg_m, 0.0, 1.0); } // Subtract | ||
| 619 | case 3: { m = min(bg_a, fg_m); } // And / Min | ||
| 620 | case 4: { m = max(bg_a, fg_m); } // Or / Max | ||
| 621 | case 5: { m = bg_a * (1.0 - fg_m) + fg_m * (1.0 - bg_a); } // Xor | ||
| 622 | case 6: { m = bg_a * fg_m; } // Multiply | ||
| 623 | default: { m = fg_m; } | ||
| 624 | } | ||
| 625 | } | ||
| 626 | store_dst(p, vec4<f32>(m, m, m, m)); | ||
| 627 | return; | ||
| 628 | } | ||
| 629 | |||
| 630 | // Refine pass: threshold, gamma, invert, Garbage.Matte, Solid.Matte | ||
| 631 | var m = textureLoad(tex_a, p, 0).a; | ||
| 632 | let lo = u.p[0].y; | ||
| 633 | let hi = u.p[0].z; | ||
| 634 | let gamma = max(u.p[0].w, 1e-4); | ||
| 635 | m = clamp((m - lo) / max(hi - lo, 1e-5), 0.0, 1.0); | ||
| 636 | if (abs(gamma - 1.0) > 1e-5) { | ||
| 637 | m = pow(m, 1.0 / gamma); | ||
| 638 | } | ||
| 639 | if (u.p[1].x > 0.5) { | ||
| 640 | m = 1.0 - m; | ||
| 641 | } | ||
| 642 | if (u.p[1].y > 0.5) { | ||
| 643 | var gm = sample_bilinear(tex_c, uv).a; | ||
| 644 | if (u.p[1].z > 0.5) { | ||
| 645 | gm = 1.0 - gm; | ||
| 646 | } | ||
| 647 | m = m * (1.0 - clamp(gm, 0.0, 1.0)); | ||
| 648 | } | ||
| 649 | if (u.p[1].w > 0.5) { | ||
| 650 | var sm = sample_bilinear(mask_tex, uv).a; | ||
| 651 | if (u.p[2].x > 0.5) { | ||
| 652 | sm = 1.0 - sm; | ||
| 653 | } | ||
| 654 | m = max(m, clamp(sm, 0.0, 1.0)); | ||
| 655 | } | ||
| 656 | store_dst(p, vec4<f32>(m, m, m, m)); | ||
| 657 | } | ||
| 658 | |||
| 659 | // Pass B: matte_finish_op | ||
| 660 | // tex_a = BG, tex_b = refined matte, mask_tex = EffectMask | ||
| 661 | // p[0] = (spill_amount, spill_color: 0=G 1=B 2=R, post_multiply, blend) | ||
| 662 | // p[1] = (has_mask, mask_inv, mbm, 0) | ||
| 663 | // p[2] = (skip_r, skip_g, skip_b, skip_a) | ||
| 664 | @compute @workgroup_size(8, 8) | ||
| 665 | fn matte_finish_op(@builtin(global_invocation_id) gid: vec3<u32>) { | ||
| 666 | let dims = textureDimensions(dst_tex); | ||
| 667 | if (gid.x >= dims.x || gid.y >= dims.y) { return; } | ||
| 668 | let p = vec2<i32>(gid.xy); | ||
| 669 | let src = textureLoad(tex_a, p, 0); | ||
| 670 | let m = clamp(textureLoad(tex_b, p, 0).a, 0.0, 1.0); | ||
| 671 | |||
| 672 | var rgb = src.rgb; | ||
| 673 | let spill = clamp(u.p[0].x, 0.0, 1.0); | ||
| 674 | if (spill > 1e-5) { | ||
| 675 | let sc = i32(round(u.p[0].y)); | ||
| 676 | if (sc == 1) { | ||
| 677 | let lim = 0.5 * (rgb.r + rgb.g); | ||
| 678 | let ex = max(rgb.b - lim, 0.0); | ||
| 679 | rgb.b = rgb.b - ex * spill; | ||
| 680 | } else if (sc == 2) { | ||
| 681 | let lim = 0.5 * (rgb.g + rgb.b); | ||
| 682 | let ex = max(rgb.r - lim, 0.0); | ||
| 683 | rgb.r = rgb.r - ex * spill; | ||
| 684 | } else { | ||
| 685 | let lim = 0.5 * (rgb.r + rgb.b); | ||
| 686 | let ex = max(rgb.g - lim, 0.0); | ||
| 687 | rgb.g = rgb.g - ex * spill; | ||
| 688 | } | ||
| 689 | } | ||
| 690 | |||
| 691 | if (u.p[0].z > 0.5) { | ||
| 692 | rgb = rgb * m; | ||
| 693 | } | ||
| 694 | |||
| 695 | let res = vec4<f32>(rgb, m); | ||
| 696 | let out_col = apply_mask_blend( | ||
| 697 | src, res, gid.xy, dims, u.p[0].w, u.p[1].x, u.p[1].y, u.p[1].z, u.p[2], | ||
| 698 | ); | ||
| 699 | store_dst(p, out_col); | ||
| 700 | } | ||
| 701 | |||
| 702 | // ============================================================================ | ||
| 703 | // 6. Global Blend/Mask combiner (used by MultiMerge when global Blend/EffectMask active) | ||
| 704 | // tex_a = original BG, tex_b = composited result, mask_tex = EffectMask | ||
| 705 | // p[0] = (blend, has_mask, mask_inv, mbm) | ||
| 706 | // p[1] = (skip_r, skip_g, skip_b, skip_a) | ||
| 707 | // ============================================================================ | ||
| 708 | @compute @workgroup_size(8, 8) | ||
| 709 | fn blend_mask_op(@builtin(global_invocation_id) gid: vec3<u32>) { | ||
| 710 | let dims = textureDimensions(dst_tex); | ||
| 711 | if (gid.x >= dims.x || gid.y >= dims.y) { return; } | ||
| 712 | let p = vec2<i32>(gid.xy); | ||
| 713 | let uv = (vec2<f32>(gid.xy) + vec2<f32>(0.5)) / vec2<f32>(dims); | ||
| 714 | let bg = sample_bilinear(tex_a, uv); | ||
| 715 | let fg = textureLoad(tex_b, p, 0); | ||
| 716 | let out_col = apply_mask_blend( | ||
| 717 | bg, fg, gid.xy, dims, u.p[0].x, u.p[0].y, u.p[0].z, u.p[0].w, u.p[1], | ||
| 718 | ); | ||
| 719 | store_dst(p, out_col); | ||
| 720 | } | ||