| author | |
| committer | |
| log | d80d3a082ba92819399bcfbf040574904f9aa339 |
| tree | 8345403b6ed3a8052a817289b27fcad5e510daf2 |
| parent | 5fd17bff6a750204f867078cbf48d377f638ac2b |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
4 files changed, 2210 insertions(+), 0 deletions(-)
crates/engine/src/eval/archive_fx2.rs created+876| ... | @@ -0,0 +1,876 @@ | ||
| 1 | //! Wave 37 GPU pipelines & evaluators — High-Frequency Archive Fuses & Classic Built-in FX: | ||
| 2 | //! 1. `Fuse.Hexagon` — 3-color regular hexagonal lattice generator | ||
| 3 | //! 2. `Fuse.Lightning` — Procedural jagged fractal lightning bolt with forks & glow | ||
| 4 | //! 3. `Fuse.VORONOI_DIAGRAM` — Exact Euclidean Voronoi cells, edges & N-gon sites | ||
| 5 | //! 4. `Defocus` — Optical circular / polygonal N-gon bokeh blur with highlight bloom | ||
| 6 | //! 5. `AutoGain` — Pure-GPU 2-pass min/max reduction + auto-levels stretch | ||
| 7 | //! 6. `ColorBalance` — 3-way Shadows/Midtones/Highlights RGB balance + PreserveLuminance | ||
| 8 | //! 7. `SoftClip` — C1-smooth hyperbolic knee soft-clipping (HDR-safe) | ||
| 9 | //! 8. `Grain` — Classic Fusion RGB film grain | ||
| 10 | //! | ||
| 11 | //! WebGPU safety: all texture inputs use `TextureSampleType::Float { filterable: false }` | ||
| 12 | //! (read exclusively via `textureLoad`), outputs are `WriteOnly` storage textures, and | ||
| 13 | //! uniform slots grow in 512-slot chunks reset via `Engine::reset_uniform_cursors()`. | ||
| 14 | |||
| 15 | #[cfg(test)] | ||
| 16 | mod tests; | ||
| 17 | |||
| 18 | use super::*; | ||
| 19 | use std::num::NonZeroU64; | ||
| 20 | |||
| 21 | const ARCHIVE_FX2_WGSL: &str = include_str!("../shaders/archive_fx2.wgsl"); | ||
| 22 | const FX2_UNIFORM_SLOTS_PER_CHUNK: u32 = 512; | ||
| 23 | |||
| 24 | fn build_fx2_wgsl(format: wgpu::TextureFormat, hdr_float: bool) -> String { | ||
| 25 | let storage_fmt = match format { | ||
| 26 | wgpu::TextureFormat::Rgba16Float => "rgba16float", | ||
| 27 | wgpu::TextureFormat::Rgba32Float => "rgba32float", | ||
| 28 | _ => "rgba8unorm", | ||
| 29 | }; | ||
| 30 | let mut src = ARCHIVE_FX2_WGSL.to_owned(); | ||
| 31 | if storage_fmt != "rgba8unorm" { | ||
| 32 | src = src.replace( | ||
| 33 | "texture_storage_2d<rgba8unorm, write>", | ||
| 34 | &format!("texture_storage_2d<{storage_fmt}, write>"), | ||
| 35 | ); | ||
| 36 | } | ||
| 37 | if hdr_float { | ||
| 38 | src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;"); | ||
| 39 | } | ||
| 40 | src | ||
| 41 | } | ||
| 42 | |||
| 43 | fn unfilterable_tex_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { | ||
| 44 | wgpu::BindGroupLayoutEntry { | ||
| 45 | binding, | ||
| 46 | visibility: wgpu::ShaderStages::COMPUTE, | ||
| 47 | ty: wgpu::BindingType::Texture { | ||
| 48 | sample_type: wgpu::TextureSampleType::Float { filterable: false }, | ||
| 49 | view_dimension: wgpu::TextureViewDimension::D2, | ||
| 50 | multisampled: false, | ||
| 51 | }, | ||
| 52 | count: None, | ||
| 53 | } | ||
| 54 | } | ||
| 55 | |||
| 56 | #[derive(Clone, Copy)] | ||
| 57 | enum ArchiveFx2Op { | ||
| 58 | FuseHexagon, | ||
| 59 | FuseLightning, | ||
| 60 | FuseVoronoi, | ||
| 61 | Defocus, | ||
| 62 | AutoGainReduce1, | ||
| 63 | AutoGainReduce2, | ||
| 64 | AutoGainApply, | ||
| 65 | ColorBalance, | ||
| 66 | SoftClip, | ||
| 67 | Grain, | ||
| 68 | } | ||
| 69 | |||
| 70 | struct ArchiveFx2FormatPipelines { | ||
| 71 | bgl: wgpu::BindGroupLayout, | ||
| 72 | fuse_hexagon: wgpu::ComputePipeline, | ||
| 73 | fuse_lightning: wgpu::ComputePipeline, | ||
| 74 | fuse_voronoi: wgpu::ComputePipeline, | ||
| 75 | defocus: wgpu::ComputePipeline, | ||
| 76 | autogain_reduce1: wgpu::ComputePipeline, | ||
| 77 | autogain_reduce2: wgpu::ComputePipeline, | ||
| 78 | autogain_apply: wgpu::ComputePipeline, | ||
| 79 | color_balance: wgpu::ComputePipeline, | ||
| 80 | soft_clip: wgpu::ComputePipeline, | ||
| 81 | grain: wgpu::ComputePipeline, | ||
| 82 | } | ||
| 83 | |||
| 84 | impl ArchiveFx2FormatPipelines { | ||
| 85 | fn pipeline(&self, op: ArchiveFx2Op) -> &wgpu::ComputePipeline { | ||
| 86 | match op { | ||
| 87 | ArchiveFx2Op::FuseHexagon => &self.fuse_hexagon, | ||
| 88 | ArchiveFx2Op::FuseLightning => &self.fuse_lightning, | ||
| 89 | ArchiveFx2Op::FuseVoronoi => &self.fuse_voronoi, | ||
| 90 | ArchiveFx2Op::Defocus => &self.defocus, | ||
| 91 | ArchiveFx2Op::AutoGainReduce1 => &self.autogain_reduce1, | ||
| 92 | ArchiveFx2Op::AutoGainReduce2 => &self.autogain_reduce2, | ||
| 93 | ArchiveFx2Op::AutoGainApply => &self.autogain_apply, | ||
| 94 | ArchiveFx2Op::ColorBalance => &self.color_balance, | ||
| 95 | ArchiveFx2Op::SoftClip => &self.soft_clip, | ||
| 96 | ArchiveFx2Op::Grain => &self.grain, | ||
| 97 | } | ||
| 98 | } | ||
| 99 | } | ||
| 100 | |||
| 101 | pub(super) struct ArchiveFx2Pipelines { | ||
| 102 | uniform_stride: u32, | ||
| 103 | uniform_chunks: Vec<wgpu::Buffer>, | ||
| 104 | uniform_cursor: u32, | ||
| 105 | by_format: HashMap<(wgpu::TextureFormat, bool), ArchiveFx2FormatPipelines>, | ||
| 106 | } | ||
| 107 | |||
| 108 | impl ArchiveFx2Pipelines { | ||
| 109 | pub(super) fn new(device: &wgpu::Device) -> Self { | ||
| 110 | let uniform_size = std::mem::size_of::<UniformParams>() as u32; | ||
| 111 | let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1); | ||
| 112 | let uniform_stride = uniform_size.div_ceil(min_align) * min_align; | ||
| 113 | Self { | ||
| 114 | uniform_stride, | ||
| 115 | uniform_chunks: Vec::new(), | ||
| 116 | uniform_cursor: 0, | ||
| 117 | by_format: HashMap::new(), | ||
| 118 | } | ||
| 119 | } | ||
| 120 | |||
| 121 | pub(super) fn reset_uniform_cursor(&mut self) { | ||
| 122 | self.uniform_cursor = 0; | ||
| 123 | } | ||
| 124 | |||
| 125 | pub(super) fn trim_uniform_chunks(&mut self, max_chunks: usize) { | ||
| 126 | self.uniform_cursor = 0; | ||
| 127 | if self.uniform_chunks.len() > max_chunks { | ||
| 128 | self.uniform_chunks.truncate(max_chunks); | ||
| 129 | } | ||
| 130 | } | ||
| 131 | |||
| 132 | fn alloc_uniform_slot( | ||
| 133 | &mut self, | ||
| 134 | device: &wgpu::Device, | ||
| 135 | queue: &wgpu::Queue, | ||
| 136 | params: &UniformParams, | ||
| 137 | ) -> (usize, u32) { | ||
| 138 | let slot_global = self.uniform_cursor; | ||
| 139 | let chunk_idx = (slot_global / FX2_UNIFORM_SLOTS_PER_CHUNK) as usize; | ||
| 140 | let slot_in_chunk = slot_global % FX2_UNIFORM_SLOTS_PER_CHUNK; | ||
| 141 | while chunk_idx >= self.uniform_chunks.len() { | ||
| 142 | let size = u64::from(FX2_UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride); | ||
| 143 | let buf = device.create_buffer(&wgpu::BufferDescriptor { | ||
| 144 | label: Some("archive-fx2-params-ring"), | ||
| 145 | size, | ||
| 146 | usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, | ||
| 147 | mapped_at_creation: false, | ||
| 148 | }); | ||
| 149 | self.uniform_chunks.push(buf); | ||
| 150 | } | ||
| 151 | let offset = slot_in_chunk * self.uniform_stride; | ||
| 152 | queue.write_buffer(&self.uniform_chunks[chunk_idx], u64::from(offset), bytemuck::bytes_of(params)); | ||
| 153 | self.uniform_cursor = slot_global + 1; | ||
| 154 | (chunk_idx, offset) | ||
| 155 | } | ||
| 156 | |||
| 157 | fn ensure_format(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) { | ||
| 158 | if self.by_format.contains_key(&(format, hdr_float)) { | ||
| 159 | return; | ||
| 160 | } | ||
| 161 | let u_size = std::mem::size_of::<UniformParams>() as u64; | ||
| 162 | let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { | ||
| 163 | label: Some("archive-fx2-bgl"), | ||
| 164 | entries: &[ | ||
| 165 | unfilterable_tex_entry(0), | ||
| 166 | unfilterable_tex_entry(1), | ||
| 167 | unfilterable_tex_entry(2), | ||
| 168 | wgpu::BindGroupLayoutEntry { | ||
| 169 | binding: 3, | ||
| 170 | visibility: wgpu::ShaderStages::COMPUTE, | ||
| 171 | ty: wgpu::BindingType::StorageTexture { | ||
| 172 | access: wgpu::StorageTextureAccess::WriteOnly, | ||
| 173 | format, | ||
| 174 | view_dimension: wgpu::TextureViewDimension::D2, | ||
| 175 | }, | ||
| 176 | count: None, | ||
| 177 | }, | ||
| 178 | wgpu::BindGroupLayoutEntry { | ||
| 179 | binding: 4, | ||
| 180 | visibility: wgpu::ShaderStages::COMPUTE, | ||
| 181 | ty: wgpu::BindingType::Buffer { | ||
| 182 | ty: wgpu::BufferBindingType::Uniform, | ||
| 183 | has_dynamic_offset: true, | ||
| 184 | min_binding_size: NonZeroU64::new(u_size), | ||
| 185 | }, | ||
| 186 | count: None, | ||
| 187 | }, | ||
| 188 | ], | ||
| 189 | }); | ||
| 190 | let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { | ||
| 191 | label: Some("archive-fx2-pl"), | ||
| 192 | bind_group_layouts: &[Some(&bgl)], | ||
| 193 | immediate_size: 0, | ||
| 194 | }); | ||
| 195 | let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { | ||
| 196 | label: Some("archive-fx2-wgsl"), | ||
| 197 | source: wgpu::ShaderSource::Wgsl(build_fx2_wgsl(format, hdr_float).into()), | ||
| 198 | }); | ||
| 199 | let mk = |entry: &str| { | ||
| 200 | device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { | ||
| 201 | label: Some(entry), | ||
| 202 | layout: Some(&pl), | ||
| 203 | module: &module, | ||
| 204 | entry_point: Some(entry), | ||
| 205 | compilation_options: Default::default(), | ||
| 206 | cache: None, | ||
| 207 | }) | ||
| 208 | }; | ||
| 209 | self.by_format.insert( | ||
| 210 | (format, hdr_float), | ||
| 211 | ArchiveFx2FormatPipelines { | ||
| 212 | bgl, | ||
| 213 | fuse_hexagon: mk("fuse_hexagon_op"), | ||
| 214 | fuse_lightning: mk("fuse_lightning_op"), | ||
| 215 | fuse_voronoi: mk("fuse_voronoi_op"), | ||
| 216 | defocus: mk("defocus_op"), | ||
| 217 | autogain_reduce1: mk("autogain_reduce1_op"), | ||
| 218 | autogain_reduce2: mk("autogain_reduce2_op"), | ||
| 219 | autogain_apply: mk("autogain_apply_op"), | ||
| 220 | color_balance: mk("color_balance_op"), | ||
| 221 | soft_clip: mk("soft_clip_op"), | ||
| 222 | grain: mk("grain_op"), | ||
| 223 | }, | ||
| 224 | ); | ||
| 225 | } | ||
| 226 | |||
| 227 | #[allow(clippy::too_many_arguments)] | ||
| 228 | fn dispatch( | ||
| 229 | &mut self, | ||
| 230 | device: &wgpu::Device, | ||
| 231 | queue: &wgpu::Queue, | ||
| 232 | enc: &mut wgpu::CommandEncoder, | ||
| 233 | op: ArchiveFx2Op, | ||
| 234 | src_a: &wgpu::TextureView, | ||
| 235 | src_b: &wgpu::TextureView, | ||
| 236 | mask: &wgpu::TextureView, | ||
| 237 | dst: &CachedTexture, | ||
| 238 | params: &UniformParams, | ||
| 239 | ) { | ||
| 240 | let hdr_float = dst.depth.is_float(); | ||
| 241 | self.ensure_format(device, dst.format, hdr_float); | ||
| 242 | let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params); | ||
| 243 | let fp = &self.by_format[&(dst.format, hdr_float)]; | ||
| 244 | let u_size = NonZeroU64::new(std::mem::size_of::<UniformParams>() as u64); | ||
| 245 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { | ||
| 246 | label: Some("archive-fx2-bg"), | ||
| 247 | layout: &fp.bgl, | ||
| 248 | entries: &[ | ||
| 249 | wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_a) }, | ||
| 250 | wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_b) }, | ||
| 251 | wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(mask) }, | ||
| 252 | wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(&dst.view) }, | ||
| 253 | wgpu::BindGroupEntry { | ||
| 254 | binding: 4, | ||
| 255 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { | ||
| 256 | buffer: &self.uniform_chunks[chunk_idx], | ||
| 257 | offset: 0, | ||
| 258 | size: u_size, | ||
| 259 | }), | ||
| 260 | }, | ||
| 261 | ], | ||
| 262 | }); | ||
| 263 | let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { | ||
| 264 | label: Some("archive-fx2-pass"), | ||
| 265 | timestamp_writes: None, | ||
| 266 | }); | ||
| 267 | pass.set_pipeline(fp.pipeline(op)); | ||
| 268 | pass.set_bind_group(0, &bg, &[offset]); | ||
| 269 | pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1); | ||
| 270 | } | ||
| 271 | } | ||
| 272 | |||
| 273 | fn num_any(comp: &Comp, node: &Node, keys: &[&str], time: f64, default: f64, expr: &ExprEngine) -> f64 { | ||
| 274 | keys.iter() | ||
| 275 | .find(|&&k| node.inputs.contains_key(k)) | ||
| 276 | .map_or(default, |&k| comp.eval_number(node, k, time, default, expr)) | ||
| 277 | } | ||
| 278 | |||
| 279 | fn pt_any(comp: &Comp, node: &Node, keys: &[&str], time: f64, default: [f64; 2], expr: &ExprEngine) -> [f64; 2] { | ||
| 280 | keys.iter() | ||
| 281 | .find(|&&k| node.inputs.contains_key(k)) | ||
| 282 | .map_or(default, |&k| comp.eval_point(node, k, time, default, expr)) | ||
| 283 | } | ||
| 284 | |||
| 285 | fn conn_any(comp: &Comp, node: &Node, ports: &[&str]) -> Option<NodeId> { | ||
| 286 | ports.iter().find_map(|p| node.connected_node(p).and_then(|s| comp.find_node(s))) | ||
| 287 | } | ||
| 288 | |||
| 289 | fn str_any<'a>(node: &'a Node, keys: &[&str]) -> Option<&'a str> { | ||
| 290 | keys.iter().find_map(|k| node.static_str(k)) | ||
| 291 | } | ||
| 292 | |||
| 293 | fn b2f(v: bool) -> f32 { | ||
| 294 | if v { 1.0 } else { 0.0 } | ||
| 295 | } | ||
| 296 | |||
| 297 | impl Engine { | ||
| 298 | fn archive_fx2_pipelines(&self) -> &RefCell<ArchiveFx2Pipelines> { | ||
| 299 | self.archive_fx2_pipelines | ||
| 300 | .get_or_init(|| RefCell::new(ArchiveFx2Pipelines::new(&self.device))) | ||
| 301 | } | ||
| 302 | |||
| 303 | #[allow(clippy::too_many_arguments)] | ||
| 304 | fn dispatch_fx2( | ||
| 305 | &self, | ||
| 306 | enc: &mut wgpu::CommandEncoder, | ||
| 307 | op: ArchiveFx2Op, | ||
| 308 | src_a: &wgpu::TextureView, | ||
| 309 | src_b: &wgpu::TextureView, | ||
| 310 | mask: &wgpu::TextureView, | ||
| 311 | dst: &CachedTexture, | ||
| 312 | params: &UniformParams, | ||
| 313 | ) { | ||
| 314 | self.archive_fx2_pipelines() | ||
| 315 | .borrow_mut() | ||
| 316 | .dispatch(&self.device, &self.queue, enc, op, src_a, src_b, mask, dst, params); | ||
| 317 | } | ||
| 318 | |||
| 319 | fn fx2_gen_size(&self, comp: &Comp, node: &Node, time: f64, comp_dims: [u32; 2]) -> [u32; 2] { | ||
| 320 | let use_ff = comp.eval_number(node, "UseFrameFormatSettings", time, 0.0, &self.expr) > 0.5; | ||
| 321 | let w = if use_ff { | ||
| 322 | comp.width | ||
| 323 | } else { | ||
| 324 | comp.eval_number(node, "Width", time, comp.width as f64, &self.expr).round().max(1.0) as u32 | ||
| 325 | }; | ||
| 326 | let h = if use_ff { | ||
| 327 | comp.height | ||
| 328 | } else { | ||
| 329 | comp.eval_number(node, "Height", time, comp.height as f64, &self.expr).round().max(1.0) as u32 | ||
| 330 | }; | ||
| 331 | if w == comp.width && h == comp.height { comp_dims } else { self.scaled_dims(w, h) } | ||
| 332 | } | ||
| 333 | |||
| 334 | /// Evaluates single-input filter pass with cache lookup, aux preservation, and `ArchiveFx2Op` dispatch. | ||
| 335 | #[allow(clippy::too_many_arguments)] | ||
| 336 | fn run_fx2_filter( | ||
| 337 | &mut self, | ||
| 338 | node: &Node, | ||
| 339 | tag: &str, | ||
| 340 | op: ArchiveFx2Op, | ||
| 341 | src: &CachedTexture, | ||
| 342 | src_b: &wgpu::TextureView, | ||
| 343 | mask: Option<&CachedTexture>, | ||
| 344 | dst_depth: BitDepth, | ||
| 345 | u: &UniformParams, | ||
| 346 | u_vecs: usize, | ||
| 347 | frame_i: i64, | ||
| 348 | enc: &mut wgpu::CommandEncoder, | ||
| 349 | stats: &mut EvalStats, | ||
| 350 | ) -> CachedTexture { | ||
| 351 | let mask_hash = mask.map_or(0, |m| m.content_hash); | ||
| 352 | let key = self.make_key( | ||
| 353 | node, | ||
| 354 | tag, | ||
| 355 | src.size, | ||
| 356 | &[src.content_hash, mask_hash, dst_depth as u64], | ||
| 357 | bytemuck::cast_slice(&u.p[..u_vecs]), | ||
| 358 | ); | ||
| 359 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { | ||
| 360 | stats.cache_hits += 1; | ||
| 361 | return hit; | ||
| 362 | } | ||
| 363 | stats.cache_misses += 1; | ||
| 364 | stats.nodes_evaluated += 1; | ||
| 365 | let mut dst = self.alloc_tex(src.size, dst_depth, key); | ||
| 366 | let mv = mask.map_or(&self.dummy.view, |m| &m.view); | ||
| 367 | self.dispatch_fx2(enc, op, &src.view, src_b, mv, &dst, u); | ||
| 368 | dst.set_aux(src.aux.clone()); | ||
| 369 | self.cache.insert(key, dst.clone(), node.id, frame_i); | ||
| 370 | dst | ||
| 371 | } | ||
| 372 | |||
| 373 | // ------------------------------------------------------------------------ | ||
| 374 | // 1. Fuse.Hexagon | ||
| 375 | // ------------------------------------------------------------------------ | ||
| 376 | #[allow(clippy::too_many_arguments)] | ||
| 377 | pub(super) fn eval_fuse_hexagon( | ||
| 378 | &mut self, | ||
| 379 | comp: &Comp, | ||
| 380 | node: &Node, | ||
| 381 | time: f64, | ||
| 382 | frame_i: i64, | ||
| 383 | comp_dims: [u32; 2], | ||
| 384 | enc: &mut wgpu::CommandEncoder, | ||
| 385 | visiting: &mut HashSet<(NodeId, i64)>, | ||
| 386 | stats: &mut EvalStats, | ||
| 387 | ) -> CachedTexture { | ||
| 388 | let size = self.fx2_gen_size(comp, node, time, comp_dims); | ||
| 389 | let depth = self.node_depth(comp, node, time, None); | ||
| 390 | let hex_size = num_any(comp, node, &["Size", "HexSize", "Scale"], time, 10.0, &self.expr).max(0.1) as f32; | ||
| 391 | let border = num_any(comp, node, &["Border", "BorderSize"], time, 0.0, &self.expr).max(0.0) as f32; | ||
| 392 | let center = pt_any(comp, node, &["Center", "Offset"], time, [0.5, 0.5], &self.expr); | ||
| 393 | let angle = (num_any(comp, node, &["Angle", "Rotation"], time, 0.0, &self.expr) as f32).to_radians(); | ||
| 394 | let col = |i: u8, def: [f64; 3]| -> [f32; 4] { | ||
| 395 | [ | ||
| 396 | comp.eval_number(node, &format!("Red{i}"), time, def[0], &self.expr) as f32, | ||
| 397 | comp.eval_number(node, &format!("Green{i}"), time, def[1], &self.expr) as f32, | ||
| 398 | comp.eval_number(node, &format!("Blue{i}"), time, def[2], &self.expr) as f32, | ||
| 399 | comp.eval_number(node, &format!("Alpha{i}"), time, 1.0, &self.expr) as f32, | ||
| 400 | ] | ||
| 401 | }; | ||
| 402 | let (c1, c2, c3) = (col(1, [1.0, 1.0, 1.0]), col(2, [0.5, 0.5, 0.5]), col(3, [0.0, 0.0, 0.0])); | ||
| 403 | let br = num_any(comp, node, &["BorderRed", "LineRed"], time, 0.0, &self.expr) as f32; | ||
| 404 | let bg = num_any(comp, node, &["BorderGreen", "LineGreen"], time, 0.0, &self.expr) as f32; | ||
| 405 | let bb = num_any(comp, node, &["BorderBlue", "LineBlue"], time, 0.0, &self.expr) as f32; | ||
| 406 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; | ||
| 407 | let mbm_flag = self.multiplies_by_mask(comp, node, time); | ||
| 408 | let skip = self.process_skip(comp, node, time); | ||
| 409 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats); | ||
| 410 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); | ||
| 411 | |||
| 412 | let mut u = UniformParams::default(); | ||
| 413 | u.p[0] = [hex_size, border, center[0] as f32, center[1] as f32]; | ||
| 414 | u.p[1] = c1; | ||
| 415 | u.p[2] = c2; | ||
| 416 | u.p[3] = c3; | ||
| 417 | u.p[4] = [angle, blend, b2f(mask.is_some()), b2f(mask_inv)]; | ||
| 418 | u.p[5] = [b2f(mask.is_some() && mbm_flag), br, bg, bb]; | ||
| 419 | u.p[6] = skip; | ||
| 420 | |||
| 421 | let key = self.make_key(node, "FuseHexagon", size, &[mask_hash, depth as u64], bytemuck::cast_slice(&u.p[..7])); | ||
| 422 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { | ||
| 423 | stats.cache_hits += 1; | ||
| 424 | return hit; | ||
| 425 | } | ||
| 426 | stats.cache_misses += 1; | ||
| 427 | stats.nodes_evaluated += 1; | ||
| 428 | let dst = self.alloc_tex(size, depth, key); | ||
| 429 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); | ||
| 430 | self.dispatch_fx2(enc, ArchiveFx2Op::FuseHexagon, &self.dummy.view, &self.dummy.view, mv, &dst, &u); | ||
| 431 | self.cache.insert(key, dst.clone(), node.id, frame_i); | ||
| 432 | dst | ||
| 433 | } | ||
| 434 | |||
| 435 | // ------------------------------------------------------------------------ | ||
| 436 | // 2. Fuse.Lightning | ||
| 437 | // ------------------------------------------------------------------------ | ||
| 438 | #[allow(clippy::too_many_arguments)] | ||
| 439 | pub(super) fn eval_fuse_lightning( | ||
| 440 | &mut self, | ||
| 441 | comp: &Comp, | ||
| 442 | node: &Node, | ||
| 443 | time: f64, | ||
| 444 | frame_i: i64, | ||
| 445 | comp_dims: [u32; 2], | ||
| 446 | enc: &mut wgpu::CommandEncoder, | ||
| 447 | visiting: &mut HashSet<(NodeId, i64)>, | ||
| 448 | stats: &mut EvalStats, | ||
| 449 | ) -> CachedTexture { | ||
| 450 | let src_opt = conn_any(comp, node, &["Input", "Background", "Image"]) | ||
| 451 | .map(|id| self.eval_node(comp, id, time, enc, visiting, stats)); | ||
| 452 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; | ||
| 453 | let mbm_flag = self.multiplies_by_mask(comp, node, time); | ||
| 454 | if blend <= 1e-6 && !mbm_flag { | ||
| 455 | if let Some(s) = src_opt { | ||
| 456 | return s; | ||
| 457 | } | ||
| 458 | } | ||
| 459 | let src_c = src_opt.map(|s| self.crop_to_canvas(enc, s)); | ||
| 460 | let size = src_c.as_ref().map_or_else(|| self.fx2_gen_size(comp, node, time, comp_dims), |s| s.size); | ||
| 461 | let depth = self.node_depth(comp, node, time, src_c.as_ref().map(|s| s.depth)); | ||
| 462 | |||
| 463 | let start = pt_any(comp, node, &["StartPosition", "Start", "Point1"], time, [0.25, 0.5], &self.expr); | ||
| 464 | let end = pt_any(comp, node, &["EndPosition", "End", "Point2"], time, [0.75, 0.5], &self.expr); | ||
| 465 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats); | ||
| 466 | let src_hash = src_c.as_ref().map_or(0, |s| s.content_hash); | ||
| 467 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); | ||
| 468 | |||
| 469 | let mut u = UniformParams::default(); | ||
| 470 | u.p[0] = [start[0] as f32, start[1] as f32, end[0] as f32, end[1] as f32]; | ||
| 471 | u.p[1] = [ | ||
| 472 | num_any(comp, node, &["RandomSeed", "Seed"], time, 0.0, &self.expr) as f32, | ||
| 473 | num_any(comp, node, &["Detail", "Subdivisions"], time, 0.2, &self.expr).clamp(0.0, 2.0) as f32, | ||
| 474 | num_any(comp, node, &["Jagginess", "Jitter", "Deviation"], time, 0.2, &self.expr).max(0.0) as f32, | ||
| 475 | num_any(comp, node, &["Thickness", "Width", "BoltWidth"], time, 0.02, &self.expr).max(0.0005) as f32, | ||
| 476 | ]; | ||
| 477 | u.p[2] = [ | ||
| 478 | num_any(comp, node, &["ThicknessTapering", "Taper"], time, 0.5, &self.expr).clamp(0.0, 1.0) as f32, | ||
| 479 | num_any(comp, node, &["Softness", "Glow", "Blur"], time, 1.5, &self.expr).max(0.0) as f32, | ||
| 480 | num_any(comp, node, &["Crawling", "Phase", "Crawl"], time, 0.0, &self.expr) as f32, | ||
| 481 | num_any(comp, node, &["BranchProb", "BranchProbability", "Forks"], time, 0.2, &self.expr).clamp(0.0, 1.0) as f32, | ||
| 482 | ]; | ||
| 483 | u.p[3] = [ | ||
| 484 | num_any(comp, node, &["BranchLength", "ForkLength"], time, 0.15, &self.expr).max(0.0) as f32, | ||
| 485 | b2f(src_c.is_some()), | ||
| 486 | 0.0, | ||
| 487 | 0.0, | ||
| 488 | ]; | ||
| 489 | u.p[4] = [ | ||
| 490 | num_any(comp, node, &["Red", "GlowRed"], time, 0.45, &self.expr) as f32, | ||
| 491 | num_any(comp, node, &["Green", "GlowGreen"], time, 0.72, &self.expr) as f32, | ||
| 492 | num_any(comp, node, &["Blue", "GlowBlue"], time, 1.0, &self.expr) as f32, | ||
| 493 | num_any(comp, node, &["Alpha"], time, 1.0, &self.expr) as f32, | ||
| 494 | ]; | ||
| 495 | u.p[5] = [blend, b2f(mask.is_some()), b2f(mask_inv), b2f(mask.is_some() && mbm_flag)]; | ||
| 496 | u.p[6] = self.process_skip(comp, node, time); | ||
| 497 | |||
| 498 | let key = self.make_key(node, "FuseLightning", size, &[src_hash, mask_hash, depth as u64], bytemuck::cast_slice(&u.p[..7])); | ||
| 499 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { | ||
| 500 | stats.cache_hits += 1; | ||
| 501 | return hit; | ||
| 502 | } | ||
| 503 | stats.cache_misses += 1; | ||
| 504 | stats.nodes_evaluated += 1; | ||
| 505 | let dst = self.alloc_tex(size, depth, key); | ||
| 506 | let sv = src_c.as_ref().map_or(&self.dummy.view, |s| &s.view); | ||
| 507 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); | ||
| 508 | self.dispatch_fx2(enc, ArchiveFx2Op::FuseLightning, sv, &self.dummy.view, mv, &dst, &u); | ||
| 509 | self.cache.insert(key, dst.clone(), node.id, frame_i); | ||
| 510 | dst | ||
| 511 | } | ||
| 512 | |||
| 513 | // ------------------------------------------------------------------------ | ||
| 514 | // 3. Fuse.VORONOI_DIAGRAM | ||
| 515 | // ------------------------------------------------------------------------ | ||
| 516 | #[allow(clippy::too_many_arguments)] | ||
| 517 | pub(super) fn eval_fuse_voronoi_diagram( | ||
| 518 | &mut self, | ||
| 519 | comp: &Comp, | ||
| 520 | node: &Node, | ||
| 521 | time: f64, | ||
| 522 | frame_i: i64, | ||
| 523 | comp_dims: [u32; 2], | ||
| 524 | enc: &mut wgpu::CommandEncoder, | ||
| 525 | visiting: &mut HashSet<(NodeId, i64)>, | ||
| 526 | stats: &mut EvalStats, | ||
| 527 | ) -> CachedTexture { | ||
| 528 | let src_opt = conn_any(comp, node, &["Input", "Background", "Image"]) | ||
| 529 | .map(|id| self.eval_node(comp, id, time, enc, visiting, stats)); | ||
| 530 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; | ||
| 531 | let mbm_flag = self.multiplies_by_mask(comp, node, time); | ||
| 532 | if blend <= 1e-6 && !mbm_flag { | ||
| 533 | if let Some(s) = src_opt { | ||
| 534 | return s; | ||
| 535 | } | ||
| 536 | } | ||
| 537 | let src_c = src_opt.map(|s| self.crop_to_canvas(enc, s)); | ||
| 538 | let size = src_c.as_ref().map_or_else(|| self.fx2_gen_size(comp, node, time, comp_dims), |s| s.size); | ||
| 539 | let depth = self.node_depth(comp, node, time, src_c.as_ref().map(|s| s.depth)); | ||
| 540 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats); | ||
| 541 | let src_hash = src_c.as_ref().map_or(0, |s| s.content_hash); | ||
| 542 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); | ||
| 543 | |||
| 544 | let mut u = UniformParams::default(); | ||
| 545 | u.p[0] = [ | ||
| 546 | num_any(comp, node, &["RandomSeed", "Seed"], time, 0.0, &self.expr) as f32, | ||
| 547 | num_any(comp, node, &["Cell_Number", "CellNumber", "Cells", "Count"], time, 16.0, &self.expr).clamp(2.0, 64.0) as f32, | ||
| 548 | num_any(comp, node, &["Sides", "PointSides"], time, 6.0, &self.expr).clamp(3.0, 32.0) as f32, | ||
| 549 | num_any(comp, node, &["Size", "LineSize", "Thickness"], time, 0.006, &self.expr).max(0.0005) as f32, | ||
| 550 | ]; | ||
| 551 | u.p[1] = [ | ||
| 552 | num_any(comp, node, &["Scale", "Zoom"], time, 1.0, &self.expr).max(0.05) as f32, | ||
| 553 | num_any(comp, node, &["img_Width", "ImgWidth"], time, size[0] as f64, &self.expr).max(1.0) as f32, | ||
| 554 | num_any(comp, node, &["img_Height", "ImgHeight"], time, size[1] as f64, &self.expr).max(1.0) as f32, | ||
| 555 | num_any(comp, node, &["Line_Type", "LineType", "Style"], time, 0.0, &self.expr).round().clamp(0.0, 3.0) as f32, | ||
| 556 | ]; | ||
| 557 | u.p[2] = [ | ||
| 558 | b2f(src_c.is_some()), | ||
| 559 | num_any(comp, node, &["ShowCells", "FillCells"], time, 0.0, &self.expr) as f32, | ||
| 560 | num_any(comp, node, &["ShowSites", "ShowPoints"], time, 0.0, &self.expr) as f32, | ||
| 561 | 1.0, | ||
| 562 | ]; | ||
| 563 | u.p[3] = [ | ||
| 564 | num_any(comp, node, &["Red", "LineRed"], time, 1.0, &self.expr) as f32, | ||
| 565 | num_any(comp, node, &["Green", "LineGreen"], time, 1.0, &self.expr) as f32, | ||
| 566 | num_any(comp, node, &["Blue", "LineBlue"], time, 1.0, &self.expr) as f32, | ||
| 567 | num_any(comp, node, &["Alpha", "LineAlpha"], time, 1.0, &self.expr) as f32, | ||
| 568 | ]; | ||
| 569 | u.p[4] = [blend, b2f(mask.is_some()), b2f(mask_inv), b2f(mask.is_some() && mbm_flag)]; | ||
| 570 | u.p[5] = self.process_skip(comp, node, time); | ||
| 571 | |||
| 572 | let key = self.make_key(node, "FuseVoronoiDiagram", size, &[src_hash, mask_hash, depth as u64], bytemuck::cast_slice(&u.p[..6])); | ||
| 573 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { | ||
| 574 | stats.cache_hits += 1; | ||
| 575 | return hit; | ||
| 576 | } | ||
| 577 | stats.cache_misses += 1; | ||
| 578 | stats.nodes_evaluated += 1; | ||
| 579 | let dst = self.alloc_tex(size, depth, key); | ||
| 580 | let sv = src_c.as_ref().map_or(&self.dummy.view, |s| &s.view); | ||
| 581 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); | ||
| 582 | self.dispatch_fx2(enc, ArchiveFx2Op::FuseVoronoi, sv, &self.dummy.view, mv, &dst, &u); | ||
| 583 | self.cache.insert(key, dst.clone(), node.id, frame_i); | ||
| 584 | dst | ||
| 585 | } | ||
| 586 | |||
| 587 | // ------------------------------------------------------------------------ | ||
| 588 | // 4. Defocus | ||
| 589 | // ------------------------------------------------------------------------ | ||
| 590 | #[allow(clippy::too_many_arguments)] | ||
| 591 | pub(super) fn eval_defocus( | ||
| 592 | &mut self, | ||
| 593 | comp: &Comp, | ||
| 594 | node: &Node, | ||
| 595 | time: f64, | ||
| 596 | frame_i: i64, | ||
| 597 | enc: &mut wgpu::CommandEncoder, | ||
| 598 | visiting: &mut HashSet<(NodeId, i64)>, | ||
| 599 | stats: &mut EvalStats, | ||
| 600 | ) -> CachedTexture { | ||
| 601 | let Some(src_id) = conn_any(comp, node, &["Input", "Background", "Image"]) else { | ||
| 602 | return self.dummy.clone(); | ||
| 603 | }; | ||
| 604 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); | ||
| 605 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; | ||
| 606 | let mbm_flag = self.multiplies_by_mask(comp, node, time); | ||
| 607 | let raw_size = num_any(comp, node, &["DefocusSize", "Size", "BlurSize", "XBlurSize"], time, 2.0, &self.expr).max(0.0) as f32; | ||
| 608 | let radius_px = (raw_size / self.proxy_scale.max(1) as f32).min(48.0); | ||
| 609 | if (blend <= 1e-6 || radius_px < 0.25) && !mbm_flag { | ||
| 610 | return src; | ||
| 611 | } | ||
| 612 | let src_c = self.crop_to_canvas(enc, src); | ||
| 613 | let dst_depth = self.node_depth(comp, node, time, Some(src_c.depth)); | ||
| 614 | let filter_mode = match str_any(node, &["Filter", "FilterType", "Shape"]) { | ||
| 615 | Some(s) if s.eq_ignore_ascii_case("ngon") || s.eq_ignore_ascii_case("polygon") || s.eq_ignore_ascii_case("lens") => 1.0_f32, | ||
| 616 | Some(s) if s.eq_ignore_ascii_case("gaussian") => 2.0_f32, | ||
| 617 | Some(_) => 0.0_f32, | ||
| 618 | None => num_any(comp, node, &["Filter", "FilterType", "Shape"], time, 0.0, &self.expr).round().clamp(0.0, 2.0) as f32, | ||
| 619 | }; | ||
| 620 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src_c.size), enc, visiting, stats); | ||
| 621 | |||
| 622 | let mut u = UniformParams::default(); | ||
| 623 | u.p[0] = [ | ||
| 624 | radius_px, | ||
| 625 | filter_mode, | ||
| 626 | num_any(comp, node, &["Sides", "NumSides", "Blades"], time, 6.0, &self.expr).round().clamp(3.0, 16.0) as f32, | ||
| 627 | (num_any(comp, node, &["Rotation", "Angle", "IrisRotation"], time, 0.0, &self.expr) as f32).to_radians(), | ||
| 628 | ]; | ||
| 629 | u.p[1] = [ | ||
| 630 | num_any(comp, node, &["BloomLevel", "Bloom", "BloomStrength"], time, 0.0, &self.expr).max(0.0) as f32, | ||
| 631 | num_any(comp, node, &["BloomThreshold", "Threshold"], time, 0.9, &self.expr) as f32, | ||
| 632 | num_any(comp, node, &["Ratio", "Aspect"], time, 1.0, &self.expr).clamp(0.2, 5.0) as f32, | ||
| 633 | 0.0, | ||
| 634 | ]; | ||
| 635 | u.p[2] = [blend, b2f(mask.is_some()), b2f(mask_inv), b2f(mask.is_some() && mbm_flag)]; | ||
| 636 | u.p[3] = self.process_skip(comp, node, time); | ||
| 637 | |||
| 638 | let dummy_v = self.dummy.view.clone(); | ||
| 639 | self.run_fx2_filter(node, "Defocus", ArchiveFx2Op::Defocus, &src_c, &dummy_v, mask.as_ref(), dst_depth, &u, 4, frame_i, enc, stats) | ||
| 640 | } | ||
| 641 | |||
| 642 | // ------------------------------------------------------------------------ | ||
| 643 | // 5. AutoGain (pure-GPU 2-pass min/max reduction + auto-levels stretch) | ||
| 644 | // ------------------------------------------------------------------------ | ||
| 645 | #[allow(clippy::too_many_arguments)] | ||
| 646 | pub(super) fn eval_auto_gain( | ||
| 647 | &mut self, | ||
| 648 | comp: &Comp, | ||
| 649 | node: &Node, | ||
| 650 | time: f64, | ||
| 651 | frame_i: i64, | ||
| 652 | enc: &mut wgpu::CommandEncoder, | ||
| 653 | visiting: &mut HashSet<(NodeId, i64)>, | ||
| 654 | stats: &mut EvalStats, | ||
| 655 | ) -> CachedTexture { | ||
| 656 | let Some(src_id) = conn_any(comp, node, &["Input", "Background", "Image"]) else { | ||
| 657 | return self.dummy.clone(); | ||
| 658 | }; | ||
| 659 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); | ||
| 660 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; | ||
| 661 | let mbm_flag = self.multiplies_by_mask(comp, node, time); | ||
| 662 | if blend <= 1e-6 && !mbm_flag { | ||
| 663 | return src; | ||
| 664 | } | ||
| 665 | let src_c = self.crop_to_canvas(enc, src); | ||
| 666 | let dst_depth = self.node_depth(comp, node, time, Some(src_c.depth)); | ||
| 667 | let do_auto = num_any(comp, node, &["DoAutoGain", "AutoGain"], time, 1.0, &self.expr) > 0.5; | ||
| 668 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src_c.size), enc, visiting, stats); | ||
| 669 | |||
| 670 | let mut u = UniformParams::default(); | ||
| 671 | u.p[0] = [ | ||
| 672 | b2f(do_auto), | ||
| 673 | num_any(comp, node, &["Lift", "Low", "Black"], time, 0.0, &self.expr) as f32, | ||
| 674 | num_any(comp, node, &["Gain", "High", "White"], time, 1.0, &self.expr) as f32, | ||
| 675 | b2f(num_any(comp, node, &["IgnoreAlpha"], time, 1.0, &self.expr) > 0.5), | ||
| 676 | ]; | ||
| 677 | u.p[1] = [ | ||
| 678 | b2f(num_any(comp, node, &["PerChannel", "SeparateChannels"], time, 0.0, &self.expr) > 0.5), | ||
| 679 | blend, | ||
| 680 | b2f(mask.is_some()), | ||
| 681 | b2f(mask_inv), | ||
| 682 | ]; | ||
| 683 | u.p[2] = [b2f(mask.is_some() && mbm_flag), 0.0, 0.0, 0.0]; | ||
| 684 | u.p[3] = self.process_skip(comp, node, time); | ||
| 685 | |||
| 686 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); | ||
| 687 | let key = self.make_key(node, "AutoGain", src_c.size, &[src_c.content_hash, mask_hash, dst_depth as u64], bytemuck::cast_slice(&u.p[..4])); | ||
| 688 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { | ||
| 689 | stats.cache_hits += 1; | ||
| 690 | return hit; | ||
| 691 | } | ||
| 692 | stats.cache_misses += 1; | ||
| 693 | stats.nodes_evaluated += 1; | ||
| 694 | |||
| 695 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); | ||
| 696 | let stats_tex = if do_auto { | ||
| 697 | let tile_tex = self.alloc_tex([32, 16], BitDepth::Float32, 0); | ||
| 698 | let mut u_red = UniformParams::default(); | ||
| 699 | u_red.p[0] = [b2f(mask.is_some()), b2f(mask_inv), 0.0, 0.0]; | ||
| 700 | self.dispatch_fx2(enc, ArchiveFx2Op::AutoGainReduce1, &src_c.view, &self.dummy.view, mv, &tile_tex, &u_red); | ||
| 701 | let red2 = self.alloc_tex([4, 1], BitDepth::Float32, 0); | ||
| 702 | self.dispatch_fx2(enc, ArchiveFx2Op::AutoGainReduce2, &tile_tex.view, &self.dummy.view, &self.dummy.view, &red2, &u_red); | ||
| 703 | Some(red2) | ||
| 704 | } else { | ||
| 705 | None | ||
| 706 | }; | ||
| 707 | |||
| 708 | let mut dst = self.alloc_tex(src_c.size, dst_depth, key); | ||
| 709 | let st_view = stats_tex.as_ref().map_or(&self.dummy.view, |t| &t.view); | ||
| 710 | self.dispatch_fx2(enc, ArchiveFx2Op::AutoGainApply, &src_c.view, st_view, mv, &dst, &u); | ||
| 711 | dst.set_aux(src_c.aux.clone()); | ||
| 712 | self.cache.insert(key, dst.clone(), node.id, frame_i); | ||
| 713 | dst | ||
| 714 | } | ||
| 715 | |||
| 716 | // ------------------------------------------------------------------------ | ||
| 717 | // 6. ColorBalance | ||
| 718 | // ------------------------------------------------------------------------ | ||
| 719 | #[allow(clippy::too_many_arguments)] | ||
| 720 | pub(super) fn eval_color_balance( | ||
| 721 | &mut self, | ||
| 722 | comp: &Comp, | ||
| 723 | node: &Node, | ||
| 724 | time: f64, | ||
| 725 | frame_i: i64, | ||
| 726 | enc: &mut wgpu::CommandEncoder, | ||
| 727 | visiting: &mut HashSet<(NodeId, i64)>, | ||
| 728 | stats: &mut EvalStats, | ||
| 729 | ) -> CachedTexture { | ||
| 730 | let Some(src_id) = conn_any(comp, node, &["Input", "Background", "Image"]) else { | ||
| 731 | return self.dummy.clone(); | ||
| 732 | }; | ||
| 733 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); | ||
| 734 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; | ||
| 735 | let mbm_flag = self.multiplies_by_mask(comp, node, time); | ||
| 736 | if blend <= 1e-6 && !mbm_flag { | ||
| 737 | return src; | ||
| 738 | } | ||
| 739 | let src_c = self.crop_to_canvas(enc, src); | ||
| 740 | let dst_depth = self.node_depth(comp, node, time, Some(src_c.depth)); | ||
| 741 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src_c.size), enc, visiting, stats); | ||
| 742 | |||
| 743 | let mut u = UniformParams::default(); | ||
| 744 | u.p[0] = [ | ||
| 745 | num_any(comp, node, &["ShadowRed", "ShadowsRed", "LowRed", "LiftRed"], time, 0.0, &self.expr) as f32, | ||
| 746 | num_any(comp, node, &["ShadowGreen", "ShadowsGreen", "LowGreen", "LiftGreen"], time, 0.0, &self.expr) as f32, | ||
| 747 | num_any(comp, node, &["ShadowBlue", "ShadowsBlue", "LowBlue", "LiftBlue"], time, 0.0, &self.expr) as f32, | ||
| 748 | b2f(num_any(comp, node, &["PreserveLuminance", "PreserveLuma"], time, 1.0, &self.expr) > 0.5), | ||
| 749 | ]; | ||
| 750 | u.p[1] = [ | ||
| 751 | num_any(comp, node, &["MidtoneRed", "MidtonesRed", "MidRed", "GammaRed"], time, 0.0, &self.expr) as f32, | ||
| 752 | num_any(comp, node, &["MidtoneGreen", "MidtonesGreen", "MidGreen", "GammaGreen"], time, 0.0, &self.expr) as f32, | ||
| 753 | num_any(comp, node, &["MidtoneBlue", "MidtonesBlue", "MidBlue", "GammaBlue"], time, 0.0, &self.expr) as f32, | ||
| 754 | 0.0, | ||
| 755 | ]; | ||
| 756 | u.p[2] = [ | ||
| 757 | num_any(comp, node, &["HighlightRed", "HighlightsRed", "HighRed", "GainRed"], time, 0.0, &self.expr) as f32, | ||
| 758 | num_any(comp, node, &["HighlightGreen", "HighlightsGreen", "HighGreen", "GainGreen"], time, 0.0, &self.expr) as f32, | ||
| 759 | num_any(comp, node, &["HighlightBlue", "HighlightsBlue", "HighBlue", "GainBlue"], time, 0.0, &self.expr) as f32, | ||
| 760 | 0.0, | ||
| 761 | ]; | ||
| 762 | u.p[3] = [blend, b2f(mask.is_some()), b2f(mask_inv), b2f(mask.is_some() && mbm_flag)]; | ||
| 763 | u.p[4] = self.process_skip(comp, node, time); | ||
| 764 | |||
| 765 | let dummy_v = self.dummy.view.clone(); | ||
| 766 | self.run_fx2_filter(node, "ColorBalance", ArchiveFx2Op::ColorBalance, &src_c, &dummy_v, mask.as_ref(), dst_depth, &u, 5, frame_i, enc, stats) | ||
| 767 | } | ||
| 768 | |||
| 769 | // ------------------------------------------------------------------------ | ||
| 770 | // 7. SoftClip | ||
| 771 | // ------------------------------------------------------------------------ | ||
| 772 | #[allow(clippy::too_many_arguments)] | ||
| 773 | pub(super) fn eval_soft_clip( | ||
| 774 | &mut self, | ||
| 775 | comp: &Comp, | ||
| 776 | node: &Node, | ||
| 777 | time: f64, | ||
| 778 | frame_i: i64, | ||
| 779 | enc: &mut wgpu::CommandEncoder, | ||
| 780 | visiting: &mut HashSet<(NodeId, i64)>, | ||
| 781 | stats: &mut EvalStats, | ||
| 782 | ) -> CachedTexture { | ||
| 783 | let Some(src_id) = conn_any(comp, node, &["Input", "Background", "Image"]) else { | ||
| 784 | return self.dummy.clone(); | ||
| 785 | }; | ||
| 786 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); | ||
| 787 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; | ||
| 788 | let mbm_flag = self.multiplies_by_mask(comp, node, time); | ||
| 789 | if blend <= 1e-6 && !mbm_flag { | ||
| 790 | return src; | ||
| 791 | } | ||
| 792 | let src_c = self.crop_to_canvas(enc, src); | ||
| 793 | let dst_depth = self.node_depth(comp, node, time, Some(src_c.depth)); | ||
| 794 | let soft = num_any(comp, node, &["Softness", "Knee"], time, 0.0, &self.expr).max(0.0); | ||
| 795 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src_c.size), enc, visiting, stats); | ||
| 796 | |||
| 797 | let mut u = UniformParams::default(); | ||
| 798 | u.p[0] = [ | ||
| 799 | num_any(comp, node, &["Low", "LowClip", "BlackClip"], time, 0.0, &self.expr) as f32, | ||
| 800 | num_any(comp, node, &["High", "HighClip", "WhiteClip"], time, 1.0, &self.expr) as f32, | ||
| 801 | num_any(comp, node, &["LowKnee", "LowSoftness", "BlackKnee"], time, soft, &self.expr).max(0.0) as f32, | ||
| 802 | num_any(comp, node, &["HighKnee", "HighSoftness", "WhiteKnee"], time, soft, &self.expr).max(0.0) as f32, | ||
| 803 | ]; | ||
| 804 | u.p[1] = [ | ||
| 805 | b2f(num_any(comp, node, &["ClipAlpha"], time, 0.0, &self.expr) > 0.5), | ||
| 806 | blend, | ||
| 807 | b2f(mask.is_some()), | ||
| 808 | b2f(mask_inv), | ||
| 809 | ]; | ||
| 810 | u.p[2] = [b2f(mask.is_some() && mbm_flag), 0.0, 0.0, 0.0]; | ||
| 811 | u.p[3] = self.process_skip(comp, node, time); | ||
| 812 | |||
| 813 | let dummy_v = self.dummy.view.clone(); | ||
| 814 | self.run_fx2_filter(node, "SoftClip", ArchiveFx2Op::SoftClip, &src_c, &dummy_v, mask.as_ref(), dst_depth, &u, 4, frame_i, enc, stats) | ||
| 815 | } | ||
| 816 | |||
| 817 | // ------------------------------------------------------------------------ | ||
| 818 | // 8. Grain | ||
| 819 | // ------------------------------------------------------------------------ | ||
| 820 | #[allow(clippy::too_many_arguments)] | ||
| 821 | pub(super) fn eval_grain( | ||
| 822 | &mut self, | ||
| 823 | comp: &Comp, | ||
| 824 | node: &Node, | ||
| 825 | time: f64, | ||
| 826 | frame_i: i64, | ||
| 827 | enc: &mut wgpu::CommandEncoder, | ||
| 828 | visiting: &mut HashSet<(NodeId, i64)>, | ||
| 829 | stats: &mut EvalStats, | ||
| 830 | ) -> CachedTexture { | ||
| 831 | let Some(src_id) = conn_any(comp, node, &["Input", "Background", "Image"]) else { | ||
| 832 | return self.dummy.clone(); | ||
| 833 | }; | ||
| 834 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); | ||
| 835 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; | ||
| 836 | let mbm_flag = self.multiplies_by_mask(comp, node, time); | ||
| 837 | let power = num_any(comp, node, &["Power", "Strength", "Amount"], time, 1.0, &self.expr).max(0.0) as f32; | ||
| 838 | if (blend <= 1e-6 || power <= 1e-6) && !mbm_flag { | ||
| 839 | return src; | ||
| 840 | } | ||
| 841 | let src_c = self.crop_to_canvas(enc, src); | ||
| 842 | let dst_depth = self.node_depth(comp, node, time, Some(src_c.depth)); | ||
| 843 | let size = (num_any(comp, node, &["Size", "GrainSize", "Scale"], time, 1.0, &self.expr).max(0.25) as f32 | ||
| 844 | / self.proxy_scale.max(1) as f32) | ||
| 845 | .max(0.25); | ||
| 846 | let time_lock = num_any(comp, node, &["TimeLockSeed", "Static"], time, 0.0, &self.expr) > 0.5; | ||
| 847 | let base_seed = num_any(comp, node, &["Seed", "RandomSeed"], time, 0.0, &self.expr).round() as i32; | ||
| 848 | let seed = if time_lock { base_seed } else { base_seed.wrapping_add(frame_i as i32) }; | ||
| 849 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src_c.size), enc, visiting, stats); | ||
| 850 | |||
| 851 | let mut u = UniformParams::default(); | ||
| 852 | u.p[0] = [ | ||
| 853 | power, | ||
| 854 | size, | ||
| 855 | num_any(comp, node, &["Softness", "Blur"], time, 0.0, &self.expr).clamp(0.0, 1.0) as f32, | ||
| 856 | seed as f32, | ||
| 857 | ]; | ||
| 858 | u.p[1] = [ | ||
| 859 | num_any(comp, node, &["RedStrength", "Red", "StrengthRed"], time, 1.0, &self.expr) as f32, | ||
| 860 | num_any(comp, node, &["GreenStrength", "Green", "StrengthGreen"], time, 1.0, &self.expr) as f32, | ||
| 861 | num_any(comp, node, &["BlueStrength", "Blue", "StrengthBlue"], time, 1.0, &self.expr) as f32, | ||
| 862 | b2f(num_any(comp, node, &["Monochrome"], time, 0.0, &self.expr) > 0.5), | ||
| 863 | ]; | ||
| 864 | u.p[2] = [ | ||
| 865 | b2f(num_any(comp, node, &["AlphaMultiply"], time, 1.0, &self.expr) > 0.5), | ||
| 866 | blend, | ||
| 867 | b2f(mask.is_some()), | ||
| 868 | b2f(mask_inv), | ||
| 869 | ]; | ||
| 870 | u.p[3] = [b2f(mask.is_some() && mbm_flag), 0.0, 0.0, 0.0]; | ||
| 871 | u.p[4] = self.process_skip(comp, node, time); | ||
| 872 | |||
| 873 | let dummy_v = self.dummy.view.clone(); | ||
| 874 | self.run_fx2_filter(node, "Grain", ArchiveFx2Op::Grain, &src_c, &dummy_v, mask.as_ref(), dst_depth, &u, 5, frame_i, enc, stats) | ||
| 875 | } | ||
| 876 | } | ||
crates/engine/src/eval/archive_fx2/tests.rs created+403| ... | @@ -0,0 +1,403 @@ | ||
| 1 | use super::*; | ||
| 2 | |||
| 3 | fn mk_comp(tools: &str) -> Comp { | ||
| 4 | let src = format!( | ||
| 5 | "Composition {{ CurrentTime = 0, RenderRange = {{ 0, 10 }}, GlobalRange = {{ 0, 10 }}, Tools = ordered() {{ {tools} }} }}" | ||
| 6 | ); | ||
| 7 | Comp::from_fusion_str(&src).expect("parse archive_fx2 test comp") | ||
| 8 | } | ||
| 9 | |||
| 10 | fn render_rgba(comp: &Comp, name: &str, time: f64) -> Option<([u32; 2], Vec<u8>)> { | ||
| 11 | let mut eng = Engine::new_headless().ok()?; | ||
| 12 | let (tex, _) = eng.evaluate(comp, comp.find_node(name).unwrap(), time); | ||
| 13 | Some((tex.size, eng.readback_rgba(&tex).unwrap())) | ||
| 14 | } | ||
| 15 | |||
| 16 | fn render_f32(comp: &Comp, name: &str, time: f64) -> Option<([u32; 2], Vec<f32>)> { | ||
| 17 | let mut eng = Engine::new_headless().ok()?; | ||
| 18 | let (tex, _) = eng.evaluate(comp, comp.find_node(name).unwrap(), time); | ||
| 19 | Some((tex.size, eng.readback_rgba_f32(&tex).unwrap())) | ||
| 20 | } | ||
| 21 | |||
| 22 | fn px(buf: &[u8], w: u32, x: u32, y: u32) -> [u8; 4] { | ||
| 23 | let i = ((y * w + x) * 4) as usize; | ||
| 24 | buf[i..i + 4].try_into().unwrap() | ||
| 25 | } | ||
| 26 | |||
| 27 | #[test] | ||
| 28 | fn fuse_hexagon_three_colors_border_and_mask() { | ||
| 29 | let comp = mk_comp( | ||
| 30 | r#" | ||
| 31 | Hex = Fuse.Hexagon { | ||
| 32 | Inputs = { | ||
| 33 | Width = Input { Value = 64, }, Height = Input { Value = 64, }, | ||
| 34 | Size = Input { Value = 8, }, | ||
| 35 | Red1 = Input { Value = 1.0, }, Green1 = Input { Value = 0.0, }, Blue1 = Input { Value = 0.0, }, | ||
| 36 | Red2 = Input { Value = 0.0, }, Green2 = Input { Value = 1.0, }, Blue2 = Input { Value = 0.0, }, | ||
| 37 | Red3 = Input { Value = 0.0, }, Green3 = Input { Value = 0.0, }, Blue3 = Input { Value = 1.0, }, | ||
| 38 | }, | ||
| 39 | }, | ||
| 40 | HexBorder = Fuse.Hexagon { | ||
| 41 | Inputs = { | ||
| 42 | Width = Input { Value = 64, }, Height = Input { Value = 64, }, | ||
| 43 | Size = Input { Value = 8, }, Border = Input { Value = 2.0, }, | ||
| 44 | Red1 = Input { Value = 1.0, }, Green1 = Input { Value = 1.0, }, Blue1 = Input { Value = 1.0, }, | ||
| 45 | Red2 = Input { Value = 1.0, }, Green2 = Input { Value = 1.0, }, Blue2 = Input { Value = 1.0, }, | ||
| 46 | Red3 = Input { Value = 1.0, }, Green3 = Input { Value = 1.0, }, Blue3 = Input { Value = 1.0, }, | ||
| 47 | }, | ||
| 48 | }, | ||
| 49 | Mask = RectangleMask { | ||
| 50 | Inputs = { | ||
| 51 | MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, | ||
| 52 | Center = Input { Value = { 0.25, 0.5 }, }, Width = Input { Value = 0.5, }, Height = Input { Value = 1.0, }, | ||
| 53 | }, | ||
| 54 | }, | ||
| 55 | MaskedHex = Fuse.Hexagon { | ||
| 56 | Inputs = { | ||
| 57 | Width = Input { Value = 64, }, Height = Input { Value = 64, }, Size = Input { Value = 8, }, | ||
| 58 | Red1 = Input { Value = 1.0, }, Green1 = Input { Value = 1.0, }, Blue1 = Input { Value = 1.0, }, | ||
| 59 | Red2 = Input { Value = 1.0, }, Green2 = Input { Value = 1.0, }, Blue2 = Input { Value = 1.0, }, | ||
| 60 | Red3 = Input { Value = 1.0, }, Green3 = Input { Value = 1.0, }, Blue3 = Input { Value = 1.0, }, | ||
| 61 | EffectMask = Input { SourceOp = "Mask", Source = "Mask", }, | ||
| 62 | }, | ||
| 63 | }, | ||
| 64 | "#, | ||
| 65 | ); | ||
| 66 | let Some((sz, buf)) = render_rgba(&comp, "Hex", 0.0) else { return }; | ||
| 67 | assert_eq!(sz, [64, 64]); | ||
| 68 | let (mut c_r, mut c_g, mut c_b) = (0usize, 0usize, 0usize); | ||
| 69 | for p in buf.chunks_exact(4) { | ||
| 70 | if p[0] > 200 && p[1] < 50 && p[2] < 50 { c_r += 1; } | ||
| 71 | if p[1] > 200 && p[0] < 50 && p[2] < 50 { c_g += 1; } | ||
| 72 | if p[2] > 200 && p[0] < 50 && p[1] < 50 { c_b += 1; } | ||
| 73 | } | ||
| 74 | assert!(c_r > 500 && c_g > 500 && c_b > 500, "all 3 hex colors must appear evenly: r={c_r} g={c_g} b={c_b}"); | ||
| 75 | |||
| 76 | let (_, bbuf) = render_rgba(&comp, "HexBorder", 0.0).unwrap(); | ||
| 77 | let dark_borders = bbuf.chunks_exact(4).filter(|p| p[0] < 80).count(); | ||
| 78 | assert!(dark_borders > 150, "Border > 0 must draw dark hex borders: {dark_borders}"); | ||
| 79 | |||
| 80 | let (_, mbuf) = render_rgba(&comp, "MaskedHex", 0.0).unwrap(); | ||
| 81 | assert_eq!(px(&mbuf, 64, 8, 32)[3], 255, "inside mask must be opaque"); | ||
| 82 | assert_eq!(px(&mbuf, 64, 56, 32)[3], 0, "outside mask must be transparent"); | ||
| 83 | } | ||
| 84 | |||
| 85 | #[test] | ||
| 86 | fn fuse_lightning_endpoints_seed_crawling_branches_and_blend() { | ||
| 87 | let comp = mk_comp( | ||
| 88 | r#" | ||
| 89 | Bg = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftRed = Input { Value = 0.2, }, }, }, | ||
| 90 | L0 = Fuse.Lightning { | ||
| 91 | Inputs = { | ||
| 92 | Input = Input { SourceOp = "Bg", Source = "Output", }, | ||
| 93 | StartPosition = Input { Value = { 0.5, 1.05 }, }, | ||
| 94 | EndPosition = Input { Value = { 0.5, 0.05 }, }, | ||
| 95 | RandomSeed = Input { Value = 1139, }, | ||
| 96 | Detail = Input { Value = 0.24, }, | ||
| 97 | Jagginess = Input { Value = 0.18, }, | ||
| 98 | Thickness = Input { Value = 0.03, }, | ||
| 99 | ThicknessTapering = Input { Value = 0.85, }, | ||
| 100 | Softness = Input { Value = 1.5, }, | ||
| 101 | BranchProb = Input { Value = 0.5, }, | ||
| 102 | BranchLength = Input { Value = 0.2, }, | ||
| 103 | }, | ||
| 104 | }, | ||
| 105 | L1 = Fuse.Lightning { | ||
| 106 | Inputs = { | ||
| 107 | Input = Input { SourceOp = "Bg", Source = "Output", }, | ||
| 108 | StartPosition = Input { Value = { 0.5, 1.05 }, }, | ||
| 109 | EndPosition = Input { Value = { 0.5, 0.05 }, }, | ||
| 110 | RandomSeed = Input { Value = 2048, }, | ||
| 111 | Crawling = Input { Value = 1.25, }, | ||
| 112 | Thickness = Input { Value = 0.03, }, | ||
| 113 | }, | ||
| 114 | }, | ||
| 115 | LZero = Fuse.Lightning { | ||
| 116 | Inputs = { | ||
| 117 | Input = Input { SourceOp = "Bg", Source = "Output", }, | ||
| 118 | Blend = Input { Value = 0.0, }, | ||
| 119 | }, | ||
| 120 | }, | ||
| 121 | "#, | ||
| 122 | ); | ||
| 123 | let Some((_, b0)) = render_rgba(&comp, "L0", 0.0) else { return }; | ||
| 124 | let (_, b1) = render_rgba(&comp, "L1", 0.0).unwrap(); | ||
| 125 | let (_, bg) = render_rgba(&comp, "Bg", 0.0).unwrap(); | ||
| 126 | let (_, bz) = render_rgba(&comp, "LZero", 0.0).unwrap(); | ||
| 127 | let bright = b0.chunks_exact(4).filter(|p| p[2] > 180).count(); | ||
| 128 | let corner = px(&b0, 64, 2, 2); | ||
| 129 | assert!(bright > 40, "lightning bolt must draw visible glowing pixels: {bright}"); | ||
| 130 | assert!(corner[2] < 30, "far corner should stay dark in blue: {corner:?}"); | ||
| 131 | assert_ne!(b0, b1, "different seed/crawling must produce different bolt geometry"); | ||
| 132 | assert_eq!(bz, bg, "Blend=0 must pass input through untouched"); | ||
| 133 | } | ||
| 134 | |||
| 135 | #[test] | ||
| 136 | fn fuse_voronoi_diagram_edges_sites_cells_and_seed() { | ||
| 137 | let comp = mk_comp( | ||
| 138 | r#" | ||
| 139 | Bg = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, }, }, | ||
| 140 | V0 = Fuse.VORONOI_DIAGRAM { | ||
| 141 | Inputs = { | ||
| 142 | Input = Input { SourceOp = "Bg", Source = "Output", }, | ||
| 143 | RandomSeed = Input { Value = 1373, }, | ||
| 144 | img_Width = Input { Value = 39.4, }, | ||
| 145 | img_Height = Input { Value = 44.1, }, | ||
| 146 | Cell_Number = Input { Value = 11, }, | ||
| 147 | Sides = Input { Value = 12, }, | ||
| 148 | Size = Input { Value = 0.025, }, | ||
| 149 | Scale = Input { Value = 1.2, }, | ||
| 150 | Line_Type = Input { Value = 2, }, | ||
| 151 | }, | ||
| 152 | }, | ||
| 153 | V1 = Fuse.VORONOI_DIAGRAM { | ||
| 154 | Inputs = { | ||
| 155 | Input = Input { SourceOp = "Bg", Source = "Output", }, | ||
| 156 | RandomSeed = Input { Value = 9999, }, | ||
| 157 | Cell_Number = Input { Value = 11, }, | ||
| 158 | Size = Input { Value = 0.025, }, | ||
| 159 | Line_Type = Input { Value = 3, }, | ||
| 160 | }, | ||
| 161 | }, | ||
| 162 | "#, | ||
| 163 | ); | ||
| 164 | let Some((_, b0)) = render_rgba(&comp, "V0", 0.0) else { return }; | ||
| 165 | let (_, b1) = render_rgba(&comp, "V1", 0.0).unwrap(); | ||
| 166 | let lit = b0.chunks_exact(4).filter(|p| p[0] > 120).count(); | ||
| 167 | let dark = b0.chunks_exact(4).filter(|p| p[0] < 20).count(); | ||
| 168 | assert!(lit > 100 && dark > 1000, "voronoi edges/sites must draw over dark bg: lit={lit} dark={dark}"); | ||
| 169 | assert_ne!(b0, b1, "different seed & cell-fill line type must differ"); | ||
| 170 | } | ||
| 171 | |||
| 172 | #[test] | ||
| 173 | fn defocus_circle_ngon_bloom_and_mask() { | ||
| 174 | let comp = mk_comp( | ||
| 175 | r#" | ||
| 176 | DotMask = RectangleMask { | ||
| 177 | Inputs = { | ||
| 178 | MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, | ||
| 179 | Center = Input { Value = { 0.5, 0.5 }, }, Width = Input { Value = 0.06, }, Height = Input { Value = 0.06, }, | ||
| 180 | }, | ||
| 181 | }, | ||
| 182 | Dot = Background { | ||
| 183 | Inputs = { | ||
| 184 | Width = Input { Value = 64, }, Height = Input { Value = 64, }, | ||
| 185 | TopLeftRed = Input { Value = 1.0, }, TopLeftGreen = Input { Value = 1.0, }, TopLeftBlue = Input { Value = 1.0, }, | ||
| 186 | EffectMask = Input { SourceOp = "DotMask", Source = "Mask", }, | ||
| 187 | }, | ||
| 188 | }, | ||
| 189 | DCirc = Defocus { | ||
| 190 | Inputs = { | ||
| 191 | Input = Input { SourceOp = "Dot", Source = "Output", }, | ||
| 192 | DefocusSize = Input { Value = 8.0, }, Filter = Input { Value = 0, }, | ||
| 193 | BloomLevel = Input { Value = 0.0, }, | ||
| 194 | }, | ||
| 195 | }, | ||
| 196 | DBloom = Defocus { | ||
| 197 | Inputs = { | ||
| 198 | Input = Input { SourceOp = "Dot", Source = "Output", }, | ||
| 199 | DefocusSize = Input { Value = 8.0, }, Filter = Input { Value = 0, }, | ||
| 200 | BloomLevel = Input { Value = 2.0, }, BloomThreshold = Input { Value = 0.5, }, | ||
| 201 | }, | ||
| 202 | }, | ||
| 203 | DNGon = Defocus { | ||
| 204 | Inputs = { | ||
| 205 | Input = Input { SourceOp = "Dot", Source = "Output", }, | ||
| 206 | DefocusSize = Input { Value = 10.0, }, Filter = Input { Value = FuID { "NGon" }, }, | ||
| 207 | Sides = Input { Value = 3, }, Rotation = Input { Value = 30.0, }, | ||
| 208 | }, | ||
| 209 | }, | ||
| 210 | "#, | ||
| 211 | ); | ||
| 212 | let Some((_, bc)) = render_rgba(&comp, "DCirc", 0.0) else { return }; | ||
| 213 | let (_, bb) = render_rgba(&comp, "DBloom", 0.0).unwrap(); | ||
| 214 | let (_, bn) = render_rgba(&comp, "DNGon", 0.0).unwrap(); | ||
| 215 | let sum_c: u64 = bc.chunks_exact(4).map(|p| p[0] as u64).sum(); | ||
| 216 | let sum_b: u64 = bb.chunks_exact(4).map(|p| p[0] as u64).sum(); | ||
| 217 | assert!(px(&bc, 64, 36, 32)[0] > 5, "defocus must spread dot energy outward"); | ||
| 218 | assert!(sum_b > sum_c + 2000, "bloom must boost highlight bokeh energy: bloom={sum_b} vs base={sum_c}"); | ||
| 219 | assert_ne!(bc, bn, "polygonal NGon defocus must differ from circular defocus"); | ||
| 220 | } | ||
| 221 | |||
| 222 | #[test] | ||
| 223 | fn auto_gain_stretches_histogram_flat_safe_and_flags() { | ||
| 224 | let comp = mk_comp( | ||
| 225 | r#" | ||
| 226 | Grad = Background { | ||
| 227 | Inputs = { | ||
| 228 | Width = Input { Value = 64, }, Height = Input { Value = 64, }, | ||
| 229 | Type = Input { Value = FuID { "Horizontal" }, }, | ||
| 230 | TopLeftRed = Input { Value = 0.25, }, TopLeftGreen = Input { Value = 0.25, }, TopLeftBlue = Input { Value = 0.25, }, TopLeftAlpha = Input { Value = 0.3, }, | ||
| 231 | TopRightRed = Input { Value = 0.75, }, TopRightGreen = Input { Value = 0.75, }, TopRightBlue = Input { Value = 0.75, }, TopRightAlpha = Input { Value = 0.8, }, | ||
| 232 | }, | ||
| 233 | }, | ||
| 234 | Flat = Background { | ||
| 235 | Inputs = { | ||
| 236 | Width = Input { Value = 16, }, Height = Input { Value = 16, }, | ||
| 237 | TopLeftRed = Input { Value = 0.4, }, TopLeftGreen = Input { Value = 0.4, }, TopLeftBlue = Input { Value = 0.4, }, | ||
| 238 | }, | ||
| 239 | }, | ||
| 240 | AG = AutoGain { | ||
| 241 | Inputs = { Input = Input { SourceOp = "Grad", Source = "Output", }, DoAutoGain = Input { Value = 1, }, IgnoreAlpha = Input { Value = 1, }, }, | ||
| 242 | }, | ||
| 243 | AGAlpha = AutoGain { | ||
| 244 | Inputs = { Input = Input { SourceOp = "Grad", Source = "Output", }, DoAutoGain = Input { Value = 1, }, IgnoreAlpha = Input { Value = 0, }, }, | ||
| 245 | }, | ||
| 246 | AGOff = AutoGain { | ||
| 247 | Inputs = { Input = Input { SourceOp = "Grad", Source = "Output", }, DoAutoGain = Input { Value = 0, }, Lift = Input { Value = 0.0, }, Gain = Input { Value = 1.0, }, }, | ||
| 248 | }, | ||
| 249 | AGFlat = AutoGain { | ||
| 250 | Inputs = { Input = Input { SourceOp = "Flat", Source = "Output", }, DoAutoGain = Input { Value = 1, }, }, | ||
| 251 | }, | ||
| 252 | "#, | ||
| 253 | ); | ||
| 254 | let Some((_, b_ag)) = render_rgba(&comp, "AG", 0.0) else { return }; | ||
| 255 | let (_, b_aga) = render_rgba(&comp, "AGAlpha", 0.0).unwrap(); | ||
| 256 | let (_, b_off) = render_rgba(&comp, "AGOff", 0.0).unwrap(); | ||
| 257 | let (_, b_flat) = render_rgba(&comp, "AGFlat", 0.0).unwrap(); | ||
| 258 | assert!(px(&b_ag, 64, 0, 32)[0] <= 8, "min should stretch to ~0: {:?}", px(&b_ag, 64, 0, 32)); | ||
| 259 | assert!(px(&b_ag, 64, 63, 32)[0] >= 247, "max should stretch to ~255: {:?}", px(&b_ag, 64, 63, 32)); | ||
| 260 | assert!(px(&b_ag, 64, 0, 32)[3] > 60 && px(&b_ag, 64, 63, 32)[3] < 220); | ||
| 261 | assert!(px(&b_aga, 64, 0, 32)[3] <= 10 && px(&b_aga, 64, 63, 32)[3] >= 245); | ||
| 262 | assert!((px(&b_off, 64, 0, 32)[0] as i32 - 64).abs() <= 4); | ||
| 263 | assert!((px(&b_off, 64, 63, 32)[0] as i32 - 191).abs() <= 4); | ||
| 264 | assert!((px(&b_flat, 16, 8, 8)[0] as i32 - 102).abs() <= 2, "flat image must remain untouched (no div-by-zero)"); | ||
| 265 | } | ||
| 266 | |||
| 267 | #[test] | ||
| 268 | fn color_balance_three_way_zones_and_preserve_luminance() { | ||
| 269 | let comp = mk_comp( | ||
| 270 | r#" | ||
| 271 | Grad = Background { | ||
| 272 | Inputs = { | ||
| 273 | Width = Input { Value = 32, }, Height = Input { Value = 16, }, | ||
| 274 | Type = Input { Value = FuID { "Horizontal" }, }, | ||
| 275 | TopLeftRed = Input { Value = 0.1, }, TopLeftGreen = Input { Value = 0.1, }, TopLeftBlue = Input { Value = 0.1, }, | ||
| 276 | TopRightRed = Input { Value = 0.9, }, TopRightGreen = Input { Value = 0.9, }, TopRightBlue = Input { Value = 0.9, }, | ||
| 277 | }, | ||
| 278 | }, | ||
| 279 | Mid = Background { | ||
| 280 | Inputs = { | ||
| 281 | Width = Input { Value = 16, }, Height = Input { Value = 16, }, | ||
| 282 | TopLeftRed = Input { Value = 0.5, }, TopLeftGreen = Input { Value = 0.5, }, TopLeftBlue = Input { Value = 0.5, }, | ||
| 283 | }, | ||
| 284 | }, | ||
| 285 | CBZones = ColorBalance { | ||
| 286 | Inputs = { | ||
| 287 | Input = Input { SourceOp = "Grad", Source = "Output", }, | ||
| 288 | ShadowRed = Input { Value = 0.6, }, HighlightBlue = Input { Value = 0.6, }, | ||
| 289 | PreserveLuminance = Input { Value = 0, }, | ||
| 290 | }, | ||
| 291 | }, | ||
| 292 | CBNoLuma = ColorBalance { | ||
| 293 | Inputs = { | ||
| 294 | Input = Input { SourceOp = "Mid", Source = "Output", }, | ||
| 295 | MidtoneRed = Input { Value = 0.6, }, PreserveLuminance = Input { Value = 0, }, | ||
| 296 | }, | ||
| 297 | }, | ||
| 298 | CBLuma = ColorBalance { | ||
| 299 | Inputs = { | ||
| 300 | Input = Input { SourceOp = "Mid", Source = "Output", }, | ||
| 301 | MidtoneRed = Input { Value = 0.6, }, PreserveLuminance = Input { Value = 1, }, | ||
| 302 | }, | ||
| 303 | }, | ||
| 304 | "#, | ||
| 305 | ); | ||
| 306 | let Some((_, b_z)) = render_rgba(&comp, "CBZones", 0.0) else { return }; | ||
| 307 | let (_, b_no) = render_rgba(&comp, "CBNoLuma", 0.0).unwrap(); | ||
| 308 | let (_, b_lu) = render_rgba(&comp, "CBLuma", 0.0).unwrap(); | ||
| 309 | let dark_p = px(&b_z, 32, 0, 8); | ||
| 310 | let hi_p = px(&b_z, 32, 31, 8); | ||
| 311 | assert!(dark_p[0] > dark_p[2] + 40, "ShadowRed must shift shadows red: {dark_p:?}"); | ||
| 312 | assert!(hi_p[2] > hi_p[0] + 20, "HighlightBlue must shift highlights blue: {hi_p:?}"); | ||
| 313 | |||
| 314 | let p_no = px(&b_no, 16, 8, 8); | ||
| 315 | let p_lu = px(&b_lu, 16, 8, 8); | ||
| 316 | assert!(p_no[0] > 180 && (p_no[1] as i32 - 128).abs() <= 2); | ||
| 317 | let luma_lu = 0.2126 * p_lu[0] as f32 + 0.7152 * p_lu[1] as f32 + 0.0722 * p_lu[2] as f32; | ||
| 318 | assert!((luma_lu - 127.5).abs() <= 3.0, "PreserveLuminance must hold luma ~127.5: got {luma_lu} ({p_lu:?})"); | ||
| 319 | assert!(p_lu[0] > p_lu[1] + 40); | ||
| 320 | } | ||
| 321 | |||
| 322 | #[test] | ||
| 323 | fn soft_clip_hdr_knee_hard_clip_and_softness() { | ||
| 324 | let comp = mk_comp( | ||
| 325 | r#" | ||
| 326 | Hdr = Background { | ||
| 327 | Inputs = { | ||
| 328 | Width = Input { Value = 16, }, Height = Input { Value = 16, }, | ||
| 329 | Depth = Input { Value = 4, }, | ||
| 330 | TopLeftRed = Input { Value = 3.0, }, TopLeftGreen = Input { Value = 0.5, }, TopLeftBlue = Input { Value = -1.0, }, | ||
| 331 | }, | ||
| 332 | }, | ||
| 333 | SC = SoftClip { | ||
| 334 | Inputs = { | ||
| 335 | Input = Input { SourceOp = "Hdr", Source = "Output", }, | ||
| 336 | Low = Input { Value = 0.0, }, High = Input { Value = 1.0, }, | ||
| 337 | LowKnee = Input { Value = 0.2, }, HighKnee = Input { Value = 0.2, }, | ||
| 338 | }, | ||
| 339 | }, | ||
| 340 | SCHard = SoftClip { | ||
| 341 | Inputs = { | ||
| 342 | Input = Input { SourceOp = "Hdr", Source = "Output", }, | ||
| 343 | Low = Input { Value = 0.1, }, High = Input { Value = 0.8, }, | ||
| 344 | Softness = Input { Value = 0.0, }, | ||
| 345 | }, | ||
| 346 | }, | ||
| 347 | "#, | ||
| 348 | ); | ||
| 349 | let Some((_, f32_buf)) = render_f32(&comp, "SC", 0.0) else { return }; | ||
| 350 | let (_, hard_buf) = render_f32(&comp, "SCHard", 0.0).unwrap(); | ||
| 351 | assert!(f32_buf[0] > 0.95 && f32_buf[0] < 1.0, "HDR 3.0 must soft-clip smoothly below 1.0: {}", f32_buf[0]); | ||
| 352 | assert!((f32_buf[1] - 0.5).abs() < 1e-3, "midtone 0.5 outside knee must remain untouched"); | ||
| 353 | assert!(f32_buf[2] > 0.0 && f32_buf[2] < 0.06, "negative HDR -1.0 must soft-clip above 0.0: {}", f32_buf[2]); | ||
| 354 | assert!((f32_buf[3] - 1.0).abs() < 1e-3, "alpha must be preserved by default"); | ||
| 355 | assert!((hard_buf[0] - 0.8).abs() < 1e-3 && (hard_buf[2] - 0.1).abs() < 1e-3, "zero knee must hard-clip to [Low, High]"); | ||
| 356 | } | ||
| 357 | |||
| 358 | #[test] | ||
| 359 | fn grain_power_channel_strength_softness_mono_and_seed() { | ||
| 360 | let comp = mk_comp( | ||
| 361 | r#" | ||
| 362 | Mid = Background { | ||
| 363 | Inputs = { | ||
| 364 | Width = Input { Value = 32, }, Height = Input { Value = 32, }, | ||
| 365 | TopLeftRed = Input { Value = 0.5, }, TopLeftGreen = Input { Value = 0.5, }, TopLeftBlue = Input { Value = 0.5, }, | ||
| 366 | }, | ||
| 367 | }, | ||
| 368 | GRed = Grain { | ||
| 369 | Inputs = { | ||
| 370 | Input = Input { SourceOp = "Mid", Source = "Output", }, | ||
| 371 | Power = Input { Value = 2.0, }, Size = Input { Value = 1.0, }, | ||
| 372 | RedStrength = Input { Value = 1.0, }, GreenStrength = Input { Value = 0.0, }, BlueStrength = Input { Value = 0.0, }, | ||
| 373 | Seed = Input { Value = 42, }, TimeLockSeed = Input { Value = 1, }, | ||
| 374 | }, | ||
| 375 | }, | ||
| 376 | GSoft = Grain { | ||
| 377 | Inputs = { | ||
| 378 | Input = Input { SourceOp = "Mid", Source = "Output", }, | ||
| 379 | Power = Input { Value = 2.0, }, Size = Input { Value = 2.0, }, Softness = Input { Value = 1.0, }, | ||
| 380 | RedStrength = Input { Value = 1.0, }, GreenStrength = Input { Value = 0.0, }, BlueStrength = Input { Value = 0.0, }, | ||
| 381 | Seed = Input { Value = 42, }, TimeLockSeed = Input { Value = 1, }, | ||
| 382 | }, | ||
| 383 | }, | ||
| 384 | GMono = Grain { | ||
| 385 | Inputs = { | ||
| 386 | Input = Input { SourceOp = "Mid", Source = "Output", }, | ||
| 387 | Power = Input { Value = 2.0, }, Monochrome = Input { Value = 1, }, Seed = Input { Value = 7, }, | ||
| 388 | }, | ||
| 389 | }, | ||
| 390 | "#, | ||
| 391 | ); | ||
| 392 | let Some((_, b_red)) = render_rgba(&comp, "GRed", 0.0) else { return }; | ||
| 393 | let (_, b_soft) = render_rgba(&comp, "GSoft", 0.0).unwrap(); | ||
| 394 | let (_, b_m0) = render_rgba(&comp, "GMono", 0.0).unwrap(); | ||
| 395 | let (_, b_m1) = render_rgba(&comp, "GMono", 1.0).unwrap(); | ||
| 396 | let r_var: f64 = b_red.chunks_exact(4).map(|p| (p[0] as f64 - 128.0).powi(2)).sum::<f64>() / 1024.0; | ||
| 397 | let g_max_diff: i32 = b_red.chunks_exact(4).map(|p| (p[1] as i32 - 128).abs()).max().unwrap(); | ||
| 398 | assert!(r_var > 50.0, "red grain must add visible variance: {r_var}"); | ||
| 399 | assert!(g_max_diff <= 1, "GreenStrength=0 must keep green channel clean: max diff {g_max_diff}"); | ||
| 400 | assert_ne!(b_red, b_soft, "Size/Softness must change spatial grain structure"); | ||
| 401 | assert!(b_m0.chunks_exact(4).all(|p| p[0] == p[1] && p[1] == p[2]), "Monochrome grain must keep R==G==B"); | ||
| 402 | assert_ne!(b_m0, b_m1, "unlocked grain seed must vary across frames"); | ||
| 403 | } | ||
crates/engine/src/eval/mod.rs+17| ... | @@ -30,6 +30,7 @@ mod shapes; | ... | @@ -30,6 +30,7 @@ mod shapes; |
| 30 | mod warps; | 30 | mod warps; |
| 31 | mod warps_masks; | 31 | mod warps_masks; |
| 32 | mod fx_fuses; | 32 | mod fx_fuses; |
| 33 | mod archive_fx2; | ||
| 33 | mod text_3d; | 34 | mod text_3d; |
| 34 | mod registry; | 35 | mod registry; |
| 35 | mod dispatch; | 36 | mod dispatch; |
| ... | @@ -80,6 +81,7 @@ pub struct Engine { | ... | @@ -80,6 +81,7 @@ pub struct Engine { |
| 80 | depth_optical_pipelines: OnceCell<RefCell<depth_optical::DepthOpticalPipelines>>, | 81 | depth_optical_pipelines: OnceCell<RefCell<depth_optical::DepthOpticalPipelines>>, |
| 81 | warps_masks_pipelines: OnceCell<RefCell<warps_masks::WarpsMasksPipelines>>, | 82 | warps_masks_pipelines: OnceCell<RefCell<warps_masks::WarpsMasksPipelines>>, |
| 82 | fx_fuses_pipelines: OnceCell<RefCell<fx_fuses::FxFusesPipelines>>, | 83 | fx_fuses_pipelines: OnceCell<RefCell<fx_fuses::FxFusesPipelines>>, |
| 84 | archive_fx2_pipelines: OnceCell<RefCell<archive_fx2::ArchiveFx2Pipelines>>, | ||
| 83 | motion_blur: crate::motion_blur::MotionBlurPipelines, | 85 | motion_blur: crate::motion_blur::MotionBlurPipelines, |
| 84 | supports_f32_filter: bool, | 86 | supports_f32_filter: bool, |
| 85 | scene3d: crate::scene3d::Scene3DRenderer, | 87 | scene3d: crate::scene3d::Scene3DRenderer, |
| ... | @@ -191,6 +193,7 @@ impl Engine { | ... | @@ -191,6 +193,7 @@ impl Engine { |
| 191 | depth_optical_pipelines: OnceCell::new(), | 193 | depth_optical_pipelines: OnceCell::new(), |
| 192 | warps_masks_pipelines: OnceCell::new(), | 194 | warps_masks_pipelines: OnceCell::new(), |
| 193 | fx_fuses_pipelines: OnceCell::new(), | 195 | fx_fuses_pipelines: OnceCell::new(), |
| 196 | archive_fx2_pipelines: OnceCell::new(), | ||
| 194 | motion_blur: crate::motion_blur::MotionBlurPipelines::default(), | 197 | motion_blur: crate::motion_blur::MotionBlurPipelines::default(), |
| 195 | supports_f32_filter, | 198 | supports_f32_filter, |
| 196 | scene3d, | 199 | scene3d, |
| ... | @@ -348,6 +351,9 @@ impl Engine { | ... | @@ -348,6 +351,9 @@ impl Engine { |
| 348 | if let Some(ff) = self.fx_fuses_pipelines.get() { | 351 | if let Some(ff) = self.fx_fuses_pipelines.get() { |
| 349 | ff.borrow_mut().reset_uniform_cursor(); | 352 | ff.borrow_mut().reset_uniform_cursor(); |
| 350 | } | 353 | } |
| 354 | if let Some(fx2) = self.archive_fx2_pipelines.get() { | ||
| 355 | fx2.borrow_mut().reset_uniform_cursor(); | ||
| 356 | } | ||
| 351 | if let Some(of) = self.optflow.get() { | 357 | if let Some(of) = self.optflow.get() { |
| 352 | of.reset_uniform_cursor(); | 358 | of.reset_uniform_cursor(); |
| 353 | } | 359 | } |
| ... | @@ -374,6 +380,9 @@ impl Engine { | ... | @@ -374,6 +380,9 @@ impl Engine { |
| 374 | if let Some(ff) = self.fx_fuses_pipelines.get() { | 380 | if let Some(ff) = self.fx_fuses_pipelines.get() { |
| 375 | ff.borrow_mut().trim_uniform_chunks(2); | 381 | ff.borrow_mut().trim_uniform_chunks(2); |
| 376 | } | 382 | } |
| 383 | if let Some(fx2) = self.archive_fx2_pipelines.get() { | ||
| 384 | fx2.borrow_mut().trim_uniform_chunks(2); | ||
| 385 | } | ||
| 377 | self.media.trim_nv12_uniform_chunks(2); | 386 | self.media.trim_nv12_uniform_chunks(2); |
| 378 | } | 387 | } |
| 379 | 388 | ||
| ... | @@ -981,6 +990,14 @@ impl Engine { | ... | @@ -981,6 +990,14 @@ impl Engine { |
| 981 | "Fuse.SetMetaData" => self.eval_fuse_set_metadata(comp, node, time, enc, visiting, stats), | 990 | "Fuse.SetMetaData" => self.eval_fuse_set_metadata(comp, node, time, enc, visiting, stats), |
| 982 | "Fuse.Linger" => self.eval_fuse_linger(comp, node, time, frame_i, enc, visiting, stats), | 991 | "Fuse.Linger" => self.eval_fuse_linger(comp, node, time, frame_i, enc, visiting, stats), |
| 983 | "Fuse.OCLRays" => self.eval_fuse_ocl_rays(comp, node, time, frame_i, enc, visiting, stats), | 992 | "Fuse.OCLRays" => self.eval_fuse_ocl_rays(comp, node, time, frame_i, enc, visiting, stats), |
| 993 | "Fuse.Hexagon" => self.eval_fuse_hexagon(comp, node, time, frame_i, comp_dims, enc, visiting, stats), | ||
| 994 | "Fuse.Lightning" => self.eval_fuse_lightning(comp, node, time, frame_i, comp_dims, enc, visiting, stats), | ||
| 995 | "Fuse.VORONOI_DIAGRAM" => self.eval_fuse_voronoi_diagram(comp, node, time, frame_i, comp_dims, enc, visiting, stats), | ||
| 996 | "Defocus" => self.eval_defocus(comp, node, time, frame_i, enc, visiting, stats), | ||
| 997 | "AutoGain" => self.eval_auto_gain(comp, node, time, frame_i, enc, visiting, stats), | ||
| 998 | "ColorBalance" => self.eval_color_balance(comp, node, time, frame_i, enc, visiting, stats), | ||
| 999 | "SoftClip" => self.eval_soft_clip(comp, node, time, frame_i, enc, visiting, stats), | ||
| 1000 | "Grain" => self.eval_grain(comp, node, time, frame_i, enc, visiting, stats), | ||
| 984 | "sRender" => self.eval_s_render(comp, node, time, frame_i, comp_dims, enc, visiting, stats), | 1001 | "sRender" => self.eval_s_render(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 985 | "sNGon" | 1002 | "sNGon" |
| 986 | | "sRectangle" | 1003 | | "sRectangle" |
crates/engine/src/shaders/archive_fx2.wgsl created+914| ... | @@ -0,0 +1,914 @@ | ||
| 1 | // Wave 37 compute shaders: High-Frequency Archive Fuses & Classic Built-in FX Nodes | ||
| 2 | // 1. Fuse.Hexagon — 3-color regular hexagonal lattice generator | ||
| 3 | // 2. Fuse.Lightning — Procedural jagged fractal lightning bolt with forked branches & glow | ||
| 4 | // 3. Fuse.VORONOI_DIAGRAM — Exact Voronoi cell diagram (edges, sites, N-gon markers, distance) | ||
| 5 | // 4. Defocus — Optical circular / N-gon polygonal defocus bokeh with highlight bloom | ||
| 6 | // 5. AutoGain — Pure-GPU 2-pass min/max reduction + auto-levels stretch | ||
| 7 | // 6. ColorBalance — 3-way Shadows/Midtones/Highlights RGB balance + PreserveLuminance | ||
| 8 | // 7. SoftClip — C1-smooth hyperbolic knee soft-clipping (HDR-safe) | ||
| 9 | // 8. Grain — Classic RGB film grain with Power, Size, per-channel Strength, Softness, Seed | ||
| 10 | // | ||
| 11 | // WebGPU-safe (`wasm32` compatible): | ||
| 12 | // - All texture inputs are bound with `filterable: false` and read exclusively via `textureLoad`. | ||
| 13 | // - Output storage texture is WriteOnly (patched at pipeline build for rgba16float/rgba32float). | ||
| 14 | // - No `read_write` storage textures; 256-byte dynamic uniform ring buffer. | ||
| 15 | |||
| 16 | @group(0) @binding(0) var src_a: texture_2d<f32>; | ||
| 17 | @group(0) @binding(1) var src_b: texture_2d<f32>; | ||
| 18 | @group(0) @binding(2) var mask_tex: texture_2d<f32>; | ||
| 19 | @group(0) @binding(3) var dst_tex: texture_storage_2d<rgba8unorm, write>; | ||
| 20 | |||
| 21 | const HDR_FLOAT: bool = false; | ||
| 22 | const PI: f32 = 3.141592653589793; | ||
| 23 | const TAU: f32 = 6.283185307179586; | ||
| 24 | const LUMA_W: vec3<f32> = vec3<f32>(0.2126, 0.7152, 0.0722); | ||
| 25 | const REDUCE_SENTINEL: f32 = 60000.0; | ||
| 26 | |||
| 27 | struct Params { | ||
| 28 | p: array<vec4<f32>, 16>, | ||
| 29 | }; | ||
| 30 | @group(0) @binding(4) var<uniform> u: Params; | ||
| 31 | |||
| 32 | fn store_dst(p: vec2<i32>, col: vec4<f32>) { | ||
| 33 | if (HDR_FLOAT) { | ||
| 34 | textureStore(dst_tex, p, col); | ||
| 35 | } else { | ||
| 36 | textureStore(dst_tex, p, clamp(col, vec4<f32>(0.0), vec4<f32>(1.0))); | ||
| 37 | } | ||
| 38 | } | ||
| 39 | |||
| 40 | fn load_clamped(tex: texture_2d<f32>, p: vec2<i32>) -> vec4<f32> { | ||
| 41 | let dims = vec2<i32>(textureDimensions(tex)); | ||
| 42 | let c = clamp(p, vec2<i32>(0), max(dims - vec2<i32>(1), vec2<i32>(0))); | ||
| 43 | return textureLoad(tex, c, 0); | ||
| 44 | } | ||
| 45 | |||
| 46 | fn sample_bilinear(tex: texture_2d<f32>, uv: vec2<f32>) -> vec4<f32> { | ||
| 47 | let dims = vec2<i32>(textureDimensions(tex)); | ||
| 48 | let max_c = max(dims - vec2<i32>(1), vec2<i32>(0)); | ||
| 49 | let f = clamp(uv, vec2<f32>(0.0), vec2<f32>(1.0)) * vec2<f32>(dims) - vec2<f32>(0.5); | ||
| 50 | let i0 = clamp(vec2<i32>(floor(f)), vec2<i32>(0), max_c); | ||
| 51 | let i1 = clamp(i0 + vec2<i32>(1), vec2<i32>(0), max_c); | ||
| 52 | let t = clamp(f - floor(f), vec2<f32>(0.0), vec2<f32>(1.0)); | ||
| 53 | let c00 = textureLoad(tex, i0, 0); | ||
| 54 | let c10 = textureLoad(tex, vec2<i32>(i1.x, i0.y), 0); | ||
| 55 | let c01 = textureLoad(tex, vec2<i32>(i0.x, i1.y), 0); | ||
| 56 | let c11 = textureLoad(tex, i1, 0); | ||
| 57 | return mix(mix(c00, c10, t.x), mix(c01, c11, t.x), t.y); | ||
| 58 | } | ||
| 59 | |||
| 60 | fn pix_to_fu(gid: vec2<u32>, dims: vec2<u32>) -> vec2<f32> { | ||
| 61 | let f = vec2<f32>(dims); | ||
| 62 | return vec2<f32>((f32(gid.x) + 0.5) / f.x, 1.0 - (f32(gid.y) + 0.5) / f.y); | ||
| 63 | } | ||
| 64 | |||
| 65 | fn read_mask(gid: vec2<u32>, dims: vec2<u32>, has_mask: f32, invert: f32) -> f32 { | ||
| 66 | if (has_mask < 0.5) { | ||
| 67 | return 1.0; | ||
| 68 | } | ||
| 69 | let uv = (vec2<f32>(gid) + 0.5) / vec2<f32>(dims); | ||
| 70 | var m = 0.0; | ||
| 71 | if (uv.x >= 0.0 && uv.x <= 1.0 && uv.y >= 0.0 && uv.y <= 1.0) { | ||
| 72 | m = sample_bilinear(mask_tex, uv).a; | ||
| 73 | } | ||
| 74 | return select(m, 1.0 - m, invert > 0.5); | ||
| 75 | } | ||
| 76 | |||
| 77 | fn apply_channel_blend( | ||
| 78 | orig: vec4<f32>, | ||
| 79 | effect: vec4<f32>, | ||
| 80 | eff: f32, | ||
| 81 | mask_v: f32, | ||
| 82 | mbm: f32, | ||
| 83 | skip: vec4<f32>, | ||
| 84 | ) -> vec4<f32> { | ||
| 85 | var out_c = mix(orig, effect, eff); | ||
| 86 | if (mbm > 0.5) { | ||
| 87 | out_c = out_c * mask_v; | ||
| 88 | } | ||
| 89 | return vec4<f32>( | ||
| 90 | select(out_c.r, orig.r, skip.x > 0.5), | ||
| 91 | select(out_c.g, orig.g, skip.y > 0.5), | ||
| 92 | select(out_c.b, orig.b, skip.z > 0.5), | ||
| 93 | select(out_c.a, orig.a, skip.w > 0.5), | ||
| 94 | ); | ||
| 95 | } | ||
| 96 | |||
| 97 | fn hash_u32(x_in: u32) -> u32 { | ||
| 98 | var x = x_in; | ||
| 99 | x = (x ^ (x >> 16u)) * 0x7feb352du; | ||
| 100 | x = (x ^ (x >> 15u)) * 0x846ca68bu; | ||
| 101 | x = x ^ (x >> 16u); | ||
| 102 | return x; | ||
| 103 | } | ||
| 104 | |||
| 105 | fn hash11(idx: i32, seed: i32) -> f32 { | ||
| 106 | let h = hash_u32(bitcast<u32>(idx) * 374761393u + bitcast<u32>(seed) * 668265263u + 0x9e3779b9u); | ||
| 107 | return f32(h & 0x00ffffffu) / 16777216.0; | ||
| 108 | } | ||
| 109 | |||
| 110 | fn hash21(p: vec2<i32>, seed: i32) -> f32 { | ||
| 111 | let h = hash_u32( | ||
| 112 | bitcast<u32>(p.x) * 374761393u | ||
| 113 | + bitcast<u32>(p.y) * 668265263u | ||
| 114 | + bitcast<u32>(seed) * 1442695041u | ||
| 115 | + 0x9e3779b9u, | ||
| 116 | ); | ||
| 117 | return f32(h & 0x00ffffffu) / 16777216.0; | ||
| 118 | } | ||
| 119 | |||
| 120 | fn sanitize(v: f32) -> f32 { | ||
| 121 | if (!(v == v)) { | ||
| 122 | return 0.0; | ||
| 123 | } | ||
| 124 | return clamp(v, -REDUCE_SENTINEL, REDUCE_SENTINEL); | ||
| 125 | } | ||
| 126 | |||
| 127 | // ============================================================================ | ||
| 128 | // 1. Fuse.Hexagon — 3-color regular hexagonal lattice generator | ||
| 129 | // p[0] = (size, border, center_x, center_y) | ||
| 130 | // p[1] = color1 (r1, g1, b1, a1) | ||
| 131 | // p[2] = color2 (r2, g2, b2, a2) | ||
| 132 | // p[3] = color3 (r3, g3, b3, a3) | ||
| 133 | // p[4] = (angle_rad, blend, has_mask, mask_invert) | ||
| 134 | // p[5] = (mbm, border_r, border_g, border_b) | ||
| 135 | // p[6] = skip (r, g, b, a) | ||
| 136 | // ============================================================================ | ||
| 137 | |||
| 138 | @compute @workgroup_size(8, 8) | ||
| 139 | fn fuse_hexagon_op(@builtin(global_invocation_id) gid: vec3<u32>) { | ||
| 140 | let dims = textureDimensions(dst_tex); | ||
| 141 | if (gid.x >= dims.x || gid.y >= dims.y) { return; } | ||
| 142 | |||
| 143 | let p = vec2<i32>(gid.xy); | ||
| 144 | let blend = u.p[4].y; | ||
| 145 | let mask_v = read_mask(gid.xy, dims, u.p[4].z, u.p[4].w); | ||
| 146 | let eff = clamp(blend * mask_v, 0.0, 1.0); | ||
| 147 | if (eff <= 0.0 && u.p[5].x < 0.5) { | ||
| 148 | store_dst(p, vec4<f32>(0.0)); | ||
| 149 | return; | ||
| 150 | } | ||
| 151 | |||
| 152 | let fu = pix_to_fu(gid.xy, dims); | ||
| 153 | let aspect = f32(dims.x) / max(f32(dims.y), 1.0); | ||
| 154 | let center = vec2<f32>(u.p[0].z, u.p[0].w); | ||
| 155 | let d0 = vec2<f32>((fu.x - center.x) * aspect, fu.y - center.y); | ||
| 156 | let ang = u.p[4].x; | ||
| 157 | let ca = cos(ang); | ||
| 158 | let sa = sin(ang); | ||
| 159 | let rot = vec2<f32>(d0.x * ca - d0.y * sa, d0.x * sa + d0.y * ca); | ||
| 160 | |||
| 161 | let size = max(u.p[0].x, 0.1); | ||
| 162 | // Pointy-top regular hexagon axial coordinates scaled so `size` ~ tiles across width. | ||
| 163 | let s = rot * (size / max(aspect, 1e-4)) * 1.1547005; | ||
| 164 | let q_f = (0.577350269 * s.x - (1.0 / 3.0) * s.y); | ||
| 165 | let r_f = ((2.0 / 3.0) * s.y); | ||
| 166 | let s_f = -q_f - r_f; | ||
| 167 | |||
| 168 | var rq = round(q_f); | ||
| 169 | var rr = round(r_f); | ||
| 170 | var rs = round(s_f); | ||
| 171 | let dq = abs(rq - q_f); | ||
| 172 | let dr = abs(rr - r_f); | ||
| 173 | let ds = abs(rs - s_f); | ||
| 174 | if (dq > dr && dq > ds) { | ||
| 175 | rq = -rr - rs; | ||
| 176 | } else if (dr > ds) { | ||
| 177 | rr = -rq - rs; | ||
| 178 | } else { | ||
| 179 | rs = -rq - rr; | ||
| 180 | } | ||
| 181 | |||
| 182 | // Proper 3-coloring of the regular hexagonal tiling: adjacent cells never share a color. | ||
| 183 | let iq = i32(rq); | ||
| 184 | let ir = i32(rr); | ||
| 185 | let c_mod = ((iq - ir) % 3 + 3) % 3; | ||
| 186 | var col = u.p[1]; | ||
| 187 | if (c_mod == 1) { | ||
| 188 | col = u.p[2]; | ||
| 189 | } else if (c_mod == 2) { | ||
| 190 | col = u.p[3]; | ||
| 191 | } | ||
| 192 | |||
| 193 | // Optional border edge inset inside each hexagon. | ||
| 194 | let border = u.p[0].y; | ||
| 195 | if (border > 1e-4) { | ||
| 196 | let local_x = s.x - 1.7320508 * (rq + 0.5 * rr); | ||
| 197 | let local_y = s.y - 1.5 * rr; | ||
| 198 | let ax = abs(local_x); | ||
| 199 | let ay = abs(local_y); | ||
| 200 | // Distance to hex apothem boundary (apothem = sqrt(3)/2 = 0.8660254). | ||
| 201 | let hex_r = max(ax, 0.5 * ax + 0.8660254 * ay); | ||
| 202 | let edge_dist = 0.8660254 - hex_r; | ||
| 203 | let bw = clamp(border * 0.05, 0.0, 0.45); | ||
| 204 | let aa = max(1.0 / max(f32(dims.x), 1.0) * size, 0.005); | ||
| 205 | let b_fac = 1.0 - smoothstep(bw - aa, bw + aa, edge_dist); | ||
| 206 | col = mix(col, vec4<f32>(u.p[5].yzw, 1.0), b_fac); | ||
| 207 | } | ||
| 208 | |||
| 209 | let out_c = apply_channel_blend(vec4<f32>(0.0), col, eff, mask_v, u.p[5].x, u.p[6]); | ||
| 210 | store_dst(p, out_c); | ||
| 211 | } | ||
| 212 | |||
| 213 | // ============================================================================ | ||
| 214 | // 2. Fuse.Lightning — Procedural jagged fractal lightning bolt + forks & glow | ||
| 215 | // p[0] = (start_x, start_y, end_x, end_y) | ||
| 216 | // p[1] = (seed, detail, jagginess, thickness) | ||
| 217 | // p[2] = (tapering, softness, crawling, branch_prob) | ||
| 218 | // p[3] = (branch_len, has_input, aspect_unused, 0) | ||
| 219 | // p[4] = (red, green, blue, alpha) | ||
| 220 | // p[5] = (blend, has_mask, mask_invert, mbm) | ||
| 221 | // p[6] = skip (r, g, b, a) | ||
| 222 | // ============================================================================ | ||
| 223 | |||
| 224 | fn noise1d_lin(x: f32, seed: i32) -> f32 { | ||
| 225 | let i = i32(floor(x)); | ||
| 226 | let f = x - floor(x); | ||
| 227 | let v0 = hash11(i, seed) * 2.0 - 1.0; | ||
| 228 | let v1 = hash11(i + 1, seed) * 2.0 - 1.0; | ||
| 229 | return mix(v0, v1, f); | ||
| 230 | } | ||
| 231 | |||
| 232 | fn bolt_disp(s: f32, detail: f32, jagginess: f32, crawling: f32, seed: i32) -> f32 { | ||
| 233 | let env = sin(clamp(s, 0.0, 1.0) * PI); | ||
| 234 | let env_s = pow(max(env, 0.0), 0.75); | ||
| 235 | let freq_base = mix(4.0, 18.0, clamp(detail, 0.0, 1.0)); | ||
| 236 | let phase = crawling * 3.0; | ||
| 237 | var acc: f32 = 0.0; | ||
| 238 | var amp: f32 = 1.0; | ||
| 239 | var freq: f32 = freq_base; | ||
| 240 | var norm: f32 = 0.0; | ||
| 241 | for (var oct: i32 = 0; oct < 5; oct = oct + 1) { | ||
| 242 | acc = acc + amp * noise1d_lin(s * freq + phase * (1.0 + 0.35 * f32(oct)), seed + oct * 97); | ||
| 243 | norm = norm + amp; | ||
| 244 | amp = amp * 0.52; | ||
| 245 | freq = freq * 2.07; | ||
| 246 | } | ||
| 247 | return (acc / max(norm, 1e-4)) * jagginess * env_s; | ||
| 248 | } | ||
| 249 | |||
| 250 | fn bolt_sdf_contrib( | ||
| 251 | pt: vec2<f32>, | ||
| 252 | a: vec2<f32>, | ||
| 253 | b: vec2<f32>, | ||
| 254 | detail: f32, | ||
| 255 | jagginess: f32, | ||
| 256 | crawling: f32, | ||
| 257 | thickness: f32, | ||
| 258 | tapering: f32, | ||
| 259 | softness: f32, | ||
| 260 | seed: i32, | ||
| 261 | ) -> vec2<f32> { | ||
| 262 | let ab = b - a; | ||
| 263 | let seg_len = max(length(ab), 1e-4); | ||
| 264 | let dir = ab / seg_len; | ||
| 265 | let perp = vec2<f32>(-dir.y, dir.x); | ||
| 266 | let rel = pt - a; | ||
| 267 | let s = dot(rel, dir) / seg_len; | ||
| 268 | let d_perp = dot(rel, perp); | ||
| 269 | let s_clamped = clamp(s, 0.0, 1.0); | ||
| 270 | |||
| 271 | let eps = 0.005; | ||
| 272 | let disp = bolt_disp(s_clamped, detail, jagginess * seg_len, crawling, seed); | ||
| 273 | let disp_p = bolt_disp(clamp(s_clamped + eps, 0.0, 1.0), detail, jagginess * seg_len, crawling, seed); | ||
| 274 | let disp_m = bolt_disp(clamp(s_clamped - eps, 0.0, 1.0), detail, jagginess * seg_len, crawling, seed); | ||
| 275 | let slope = (disp_p - disp_m) / (2.0 * eps * seg_len); | ||
| 276 | let perp_dist = abs(d_perp - disp) / sqrt(1.0 + slope * slope); | ||
| 277 | |||
| 278 | let along_out = max(0.0, max(-s, s - 1.0)) * seg_len; | ||
| 279 | let dist = length(vec2<f32>(along_out, perp_dist)); | ||
| 280 | |||
| 281 | let local_thick = max(thickness * (1.0 - clamp(tapering, 0.0, 0.98) * s_clamped), 0.0005); | ||
| 282 | let core_w = max(local_thick * 0.45, 0.0004); | ||
| 283 | let glow_w = max(local_thick * (0.55 + max(softness, 0.0) * 1.45), 0.001); | ||
| 284 | let core = exp(-pow(dist / core_w, 2.0)); | ||
| 285 | let glow = exp(-dist / glow_w); | ||
| 286 | return vec2<f32>(core, glow); | ||
| 287 | } | ||
| 288 | |||
| 289 | @compute @workgroup_size(8, 8) | ||
| 290 | fn fuse_lightning_op(@builtin(global_invocation_id) gid: vec3<u32>) { | ||
| 291 | let dims = textureDimensions(dst_tex); | ||
| 292 | if (gid.x >= dims.x || gid.y >= dims.y) { return; } | ||
| 293 | |||
| 294 | let p = vec2<i32>(gid.xy); | ||
| 295 | let has_in = u.p[3].y > 0.5; | ||
| 296 | let orig = select(vec4<f32>(0.0), load_clamped(src_a, p), has_in); | ||
| 297 | let blend = u.p[5].x; | ||
| 298 | let mask_v = read_mask(gid.xy, dims, u.p[5].y, u.p[5].z); | ||
| 299 | let eff = clamp(blend * mask_v, 0.0, 1.0); | ||
| 300 | if (eff <= 0.0 && u.p[5].w < 0.5) { | ||
| 301 | store_dst(p, orig); | ||
| 302 | return; | ||
| 303 | } | ||
| 304 | |||
| 305 | let fu = pix_to_fu(gid.xy, dims); | ||
| 306 | let aspect = f32(dims.x) / max(f32(dims.y), 1.0); | ||
| 307 | let pt = vec2<f32>(fu.x * aspect, fu.y); | ||
| 308 | let a = vec2<f32>(u.p[0].x * aspect, u.p[0].y); | ||
| 309 | let b = vec2<f32>(u.p[0].z * aspect, u.p[0].w); | ||
| 310 | |||
| 311 | let seed = i32(round(u.p[1].x)); | ||
| 312 | let detail = u.p[1].y; | ||
| 313 | let jagginess = u.p[1].z; | ||
| 314 | let thickness = max(u.p[1].w, 0.0005); | ||
| 315 | let tapering = u.p[2].x; | ||
| 316 | let softness = u.p[2].y; | ||
| 317 | let crawling = u.p[2].z; | ||
| 318 | let branch_prob = clamp(u.p[2].w, 0.0, 1.0); | ||
| 319 | let branch_len = max(u.p[3].x, 0.0); | ||
| 320 | |||
| 321 | var best = bolt_sdf_contrib(pt, a, b, detail, jagginess, crawling, thickness, tapering, softness, seed); | ||
| 322 | |||
| 323 | // Deterministic secondary forked branches anchored along the main bolt. | ||
| 324 | if (branch_prob > 1e-4 && branch_len > 1e-4) { | ||
| 325 | let ab = b - a; | ||
| 326 | let main_len = max(length(ab), 1e-4); | ||
| 327 | let dir = ab / main_len; | ||
| 328 | let perp = vec2<f32>(-dir.y, dir.x); | ||
| 329 | for (var k: i32 = 0; k < 8; k = k + 1) { | ||
| 330 | if (hash11(k * 13 + 7, seed + 311) < branch_prob) { | ||
| 331 | let sk = 0.14 + 0.72 * hash11(k * 17 + 3, seed + 521); | ||
| 332 | let d_main = bolt_disp(sk, detail, jagginess * main_len, crawling, seed); | ||
| 333 | let b_start = a + dir * (sk * main_len) + perp * d_main; | ||
| 334 | let side = select(-1.0, 1.0, hash11(k * 23 + 1, seed + 701) > 0.5); | ||
| 335 | let ang = side * (0.42 + 0.48 * hash11(k * 29 + 5, seed + 907)); | ||
| 336 | let ca = cos(ang); | ||
| 337 | let sa = sin(ang); | ||
| 338 | let b_dir = vec2<f32>(dir.x * ca - dir.y * sa, dir.x * sa + dir.y * ca); | ||
| 339 | let blen = branch_len * main_len * (0.55 + 0.75 * hash11(k * 31 + 11, seed + 1103)); | ||
| 340 | let b_end = b_start + b_dir * blen; | ||
| 341 | let b_thick = thickness * (1.0 - clamp(tapering, 0.0, 0.9) * sk) * 0.58; | ||
| 342 | let c_br = bolt_sdf_contrib( | ||
| 343 | pt, b_start, b_end, detail, jagginess * 1.1, crawling, | ||
| 344 | b_thick, 0.92, softness * 0.85, seed + (k + 1) * 193, | ||
| 345 | ); | ||
| 346 | best = max(best, c_br * vec2<f32>(0.85, 0.82)); | ||
| 347 | } | ||
| 348 | } | ||
| 349 | } | ||
| 350 | |||
| 351 | let bolt_col = u.p[4]; | ||
| 352 | let core = best.x; | ||
| 353 | let glow = best.y; | ||
| 354 | let bolt_rgb = vec3<f32>(1.0) * core + bolt_col.rgb * glow * (1.0 - 0.35 * core); | ||
| 355 | let bolt_a = clamp((core + glow * 0.85) * bolt_col.a, 0.0, 1.0); | ||
| 356 | |||
| 357 | var effect = vec4<f32>(bolt_rgb * bolt_col.a, bolt_a); | ||
| 358 | if (has_in) { | ||
| 359 | // Luminous additive-over blend onto input background. | ||
| 360 | let out_rgb = orig.rgb + bolt_rgb * bolt_col.a; | ||
| 361 | let out_a = clamp(orig.a + bolt_a * (1.0 - orig.a), 0.0, 1.0); | ||
| 362 | effect = vec4<f32>(out_rgb, out_a); | ||
| 363 | } | ||
| 364 | |||
| 365 | let out_c = apply_channel_blend(orig, effect, eff, mask_v, u.p[5].w, u.p[6]); | ||
| 366 | store_dst(p, out_c); | ||
| 367 | } | ||
| 368 | |||
| 369 | // ============================================================================ | ||
| 370 | // 3. Fuse.VORONOI_DIAGRAM — Exact Euclidean Voronoi cells, edges & N-gon sites | ||
| 371 | // p[0] = (seed, cell_number, sides, line_size) | ||
| 372 | // p[1] = (scale, img_width, img_height, line_type) | ||
| 373 | // p[2] = (has_input, show_cells, show_sites, show_edges) | ||
| 374 | // p[3] = line_color (r, g, b, a) | ||
| 375 | // p[4] = (blend, has_mask, mask_invert, mbm) | ||
| 376 | // p[5] = skip (r, g, b, a) | ||
| 377 | // ============================================================================ | ||
| 378 | |||
| 379 | fn ngon_dist(rel: vec2<f32>, radius: f32, sides: f32) -> f32 { | ||
| 380 | let n = clamp(round(sides), 3.0, 32.0); | ||
| 381 | let r = length(rel); | ||
| 382 | if (n >= 24.0) { | ||
| 383 | return r - radius; | ||
| 384 | } | ||
| 385 | let sector = TAU / n; | ||
| 386 | let ang = atan2(rel.y, rel.x); | ||
| 387 | let a = (ang - sector * floor(ang / sector)) - 0.5 * sector; | ||
| 388 | return r * cos(a) - radius * cos(0.5 * sector); | ||
| 389 | } | ||
| 390 | |||
| 391 | @compute @workgroup_size(8, 8) | ||
| 392 | fn fuse_voronoi_op(@builtin(global_invocation_id) gid: vec3<u32>) { | ||
| 393 | let dims = textureDimensions(dst_tex); | ||
| 394 | if (gid.x >= dims.x || gid.y >= dims.y) { return; } | ||
| 395 | |||
| 396 | let p = vec2<i32>(gid.xy); | ||
| 397 | let has_in = u.p[2].x > 0.5; | ||
| 398 | let orig = select(vec4<f32>(0.0), load_clamped(src_a, p), has_in); | ||
| 399 | let blend = u.p[4].x; | ||
| 400 | let mask_v = read_mask(gid.xy, dims, u.p[4].y, u.p[4].z); | ||
| 401 | let eff = clamp(blend * mask_v, 0.0, 1.0); | ||
| 402 | if (eff <= 0.0 && u.p[4].w < 0.5) { | ||
| 403 | store_dst(p, orig); | ||
| 404 | return; | ||
| 405 | } | ||
| 406 | |||
| 407 | let fu = pix_to_fu(gid.xy, dims); | ||
| 408 | let img_w = max(u.p[1].y, 1.0); | ||
| 409 | let img_h = max(u.p[1].z, 1.0); | ||
| 410 | let dom_aspect = clamp(img_w / img_h, 0.1, 10.0); | ||
| 411 | let scale = max(u.p[1].x, 0.05); | ||
| 412 | // Map normalized UV around center into scaled Voronoi domain. | ||
| 413 | let pt = (fu - vec2<f32>(0.5)) * vec2<f32>(dom_aspect, 1.0) / scale + vec2<f32>(0.5 * dom_aspect, 0.5); | ||
| 414 | |||
| 415 | let seed_f = u.p[0].x; | ||
| 416 | let seed_i = i32(floor(seed_f)); | ||
| 417 | let cell_n = clamp(i32(round(u.p[0].y)), 2, 64); | ||
| 418 | let sides = u.p[0].z; | ||
| 419 | let line_size = max(u.p[0].w, 0.0005); | ||
| 420 | let line_type = i32(round(u.p[1].w)); | ||
| 421 | |||
| 422 | var min_d1: f32 = 1e9; | ||
| 423 | var best_id: i32 = 0; | ||
| 424 | var best_site = vec2<f32>(0.0); | ||
| 425 | |||
| 426 | // Pass A: locate closest Voronoi site. | ||
| 427 | for (var i: i32 = 0; i < 64; i = i + 1) { | ||
| 428 | if (i >= cell_n) { break; } | ||
| 429 | let sx = hash11(i * 2, seed_i) * dom_aspect; | ||
| 430 | let sy = hash11(i * 2 + 1, seed_i); | ||
| 431 | let site = vec2<f32>(sx, sy); | ||
| 432 | let d = length(pt - site); | ||
| 433 | if (d < min_d1) { | ||
| 434 | min_d1 = d; | ||
| 435 | best_id = i; | ||
| 436 | best_site = site; | ||
| 437 | } | ||
| 438 | } | ||
| 439 | |||
| 440 | // Pass B: exact Euclidean distance to nearest Voronoi cell boundary (perpendicular bisector). | ||
| 441 | var edge_d: f32 = 1e9; | ||
| 442 | for (var i: i32 = 0; i < 64; i = i + 1) { | ||
| 443 | if (i >= cell_n) { break; } | ||
| 444 | if (i == best_id) { continue; } | ||
| 445 | let sx = hash11(i * 2, seed_i) * dom_aspect; | ||
| 446 | let sy = hash11(i * 2 + 1, seed_i); | ||
| 447 | let site = vec2<f32>(sx, sy); | ||
| 448 | let mid = 0.5 * (best_site + site); | ||
| 449 | let diff = site - best_site; | ||
| 450 | let dlen = length(diff); | ||
| 451 | if (dlen > 1e-5) { | ||
| 452 | let bisector_d = dot(mid - pt, diff / dlen); | ||
| 453 | edge_d = min(edge_d, bisector_d); | ||
| 454 | } | ||
| 455 | } | ||
| 456 | |||
| 457 | let aa = max(1.0 / (max(f32(dims.y), 1.0) * scale), 0.0005); | ||
| 458 | let half_w = line_size * 0.5 / scale; | ||
| 459 | let edge_cov = 1.0 - smoothstep(half_w - aa, half_w + aa, edge_d); | ||
| 460 | let site_r = line_size * 1.4 / scale; | ||
| 461 | let site_d = ngon_dist(pt - best_site, site_r, sides); | ||
| 462 | let site_cov = 1.0 - smoothstep(-aa, aa, site_d); | ||
| 463 | |||
| 464 | let line_col = u.p[3]; | ||
| 465 | var effect = orig; | ||
| 466 | if (line_type == 3 || u.p[2].y > 0.5) { | ||
| 467 | // Shaded cells mode (unique per-cell grayscale/hue tint + crisp borders). | ||
| 468 | let shade = 0.25 + 0.65 * hash11(best_id * 7 + 13, seed_i + 41); | ||
| 469 | let cell_rgb = vec3<f32>( | ||
| 470 | 0.2 + 0.75 * hash11(best_id * 11 + 1, seed_i + 17), | ||
| 471 | 0.2 + 0.75 * hash11(best_id * 11 + 3, seed_i + 53), | ||
| 472 | 0.2 + 0.75 * hash11(best_id * 11 + 5, seed_i + 89), | ||
| 473 | ); | ||
| 474 | let base_c = select(vec3<f32>(shade), cell_rgb, line_type == 3); | ||
| 475 | let c_out = mix(base_c, line_col.rgb, edge_cov * line_col.a); | ||
| 476 | effect = vec4<f32>(c_out, 1.0); | ||
| 477 | } else { | ||
| 478 | // Line_Type 0 = edges only, 1 = dashed/soft edges, 2 = edges + N-gon site markers. | ||
| 479 | var cov = edge_cov; | ||
| 480 | if (line_type == 1) { | ||
| 481 | let dash = step(0.45, fract((pt.x + pt.y) * 28.0)); | ||
| 482 | cov = edge_cov * (0.35 + 0.65 * dash); | ||
| 483 | } else if (line_type == 2 || u.p[2].z > 0.5) { | ||
| 484 | cov = max(edge_cov, site_cov); | ||
| 485 | } | ||
| 486 | let a_draw = clamp(cov * line_col.a, 0.0, 1.0); | ||
| 487 | if (has_in) { | ||
| 488 | let out_rgb = mix(orig.rgb, line_col.rgb, a_draw); | ||
| 489 | let out_a = clamp(orig.a + a_draw * (1.0 - orig.a), 0.0, 1.0); | ||
| 490 | effect = vec4<f32>(out_rgb, out_a); | ||
| 491 | } else { | ||
| 492 | effect = vec4<f32>(line_col.rgb * a_draw, a_draw); | ||
| 493 | } | ||
| 494 | } | ||
| 495 | |||
| 496 | let out_c = apply_channel_blend(orig, effect, eff, mask_v, u.p[4].w, u.p[5]); | ||
| 497 | store_dst(p, out_c); | ||
| 498 | } | ||
| 499 | |||
| 500 | // ============================================================================ | ||
| 501 | // 4. Defocus — Optical circular / polygonal N-gon bokeh blur + highlight bloom | ||
| 502 | // p[0] = (radius_px, filter_mode, sides, rotation_rad) | ||
| 503 | // p[1] = (bloom_level, bloom_threshold, ratio, 0) | ||
| 504 | // p[2] = (blend, has_mask, mask_invert, mbm) | ||
| 505 | // p[3] = skip (r, g, b, a) | ||
| 506 | // ============================================================================ | ||
| 507 | |||
| 508 | @compute @workgroup_size(8, 8) | ||
| 509 | fn defocus_op(@builtin(global_invocation_id) gid: vec3<u32>) { | ||
| 510 | let dims = textureDimensions(dst_tex); | ||
| 511 | if (gid.x >= dims.x || gid.y >= dims.y) { return; } | ||
| 512 | |||
| 513 | let p = vec2<i32>(gid.xy); | ||
| 514 | let orig = load_clamped(src_a, p); | ||
| 515 | let blend = u.p[2].x; | ||
| 516 | let mask_v = read_mask(gid.xy, dims, u.p[2].y, u.p[2].z); | ||
| 517 | let eff = clamp(blend * mask_v, 0.0, 1.0); | ||
| 518 | let radius = max(u.p[0].x, 0.0); | ||
| 519 | if ((eff <= 0.0 || radius < 0.25) && u.p[2].w < 0.5) { | ||
| 520 | store_dst(p, orig); | ||
| 521 | return; | ||
| 522 | } | ||
| 523 | |||
| 524 | let filter_mode = i32(round(u.p[0].y)); // 0=Circle, 1=NGon, 2=Gaussian | ||
| 525 | let sides = clamp(round(u.p[0].z), 3.0, 16.0); | ||
| 526 | let rot = u.p[0].w; | ||
| 527 | let bloom_level = max(u.p[1].x, 0.0); | ||
| 528 | let bloom_thresh = u.p[1].y; | ||
| 529 | let ratio = clamp(u.p[1].z, 0.2, 5.0); | ||
| 530 | |||
| 531 | let rings = clamp(i32(ceil(radius * 0.75)), 1, 8); | ||
| 532 | let inv_dims = 1.0 / vec2<f32>(dims); | ||
| 533 | let center_uv = (vec2<f32>(gid.xy) + 0.5) * inv_dims; | ||
| 534 | let sector = TAU / sides; | ||
| 535 | let cos_half = cos(0.5 * sector); | ||
| 536 | |||
| 537 | // Center tap | ||
| 538 | var acc_rgb = vec3<f32>(0.0); | ||
| 539 | var acc_a: f32 = 0.0; | ||
| 540 | var w_sum: f32 = 0.0; | ||
| 541 | |||
| 542 | { | ||
| 543 | let c = orig; | ||
| 544 | let luma = dot(c.rgb, LUMA_W); | ||
| 545 | let boost = select(1.0, 1.0 + bloom_level * max(luma - bloom_thresh, 0.0) * 4.0, bloom_level > 1e-4 && luma > bloom_thresh); | ||
| 546 | acc_rgb = acc_rgb + c.rgb * boost; | ||
| 547 | acc_a = acc_a + c.a; | ||
| 548 | w_sum = w_sum + 1.0; | ||
| 549 | } | ||
| 550 | |||
| 551 | for (var r_i: i32 = 1; r_i <= 8; r_i = r_i + 1) { | ||
| 552 | if (r_i > rings) { break; } | ||
| 553 | let frac_r = f32(r_i) / f32(rings); | ||
| 554 | let n_ang = 6 * r_i; | ||
| 555 | let step_ang = TAU / f32(n_ang); | ||
| 556 | let base_w = select(1.0, exp(-2.2 * frac_r * frac_r), filter_mode == 2); | ||
| 557 | for (var k: i32 = 0; k < 48; k = k + 1) { | ||
| 558 | if (k >= n_ang) { break; } | ||
| 559 | let theta = f32(k) * step_ang + rot; | ||
| 560 | var r_shape = frac_r; | ||
| 561 | if (filter_mode == 1) { | ||
| 562 | let rel_a = theta - rot; | ||
| 563 | let a = (rel_a - sector * floor(rel_a / sector)) - 0.5 * sector; | ||
| 564 | r_shape = frac_r * (cos_half / max(cos(a), 0.15)); | ||
| 565 | } | ||
| 566 | let off_px = vec2<f32>(cos(theta) * r_shape * radius * ratio, sin(theta) * r_shape * radius); | ||
| 567 | let uv = clamp(center_uv + off_px * inv_dims, vec2<f32>(0.0), vec2<f32>(1.0)); | ||
| 568 | let c = sample_bilinear(src_a, uv); | ||
| 569 | let luma = dot(c.rgb, LUMA_W); | ||
| 570 | let boost = select(1.0, 1.0 + bloom_level * max(luma - bloom_thresh, 0.0) * 4.0, bloom_level > 1e-4 && luma > bloom_thresh); | ||
| 571 | acc_rgb = acc_rgb + c.rgb * (base_w * boost); | ||
| 572 | acc_a = acc_a + c.a * base_w; | ||
| 573 | w_sum = w_sum + base_w; | ||
| 574 | } | ||
| 575 | } | ||
| 576 | |||
| 577 | let inv_w = 1.0 / max(w_sum, 1e-5); | ||
| 578 | let effect = vec4<f32>(acc_rgb * inv_w, acc_a * inv_w); | ||
| 579 | let out_c = apply_channel_blend(orig, effect, eff, mask_v, u.p[2].w, u.p[3]); | ||
| 580 | store_dst(p, out_c); | ||
| 581 | } | ||
| 582 | |||
| 583 | // ============================================================================ | ||
| 584 | // 5. AutoGain — Pure-GPU 2-pass min/max reduction + auto-levels stretch | ||
| 585 | // Pass 1 (autogain_reduce1_op): dst is 32x16 float (x<16: tile min, x>=16: tile max) | ||
| 586 | // p[0] = (has_mask, mask_invert, 0, 0) | ||
| 587 | // Pass 2 (autogain_reduce2_op): dst is 4x1 float ((0,0)=min RGBA, (1,0)=max RGBA) | ||
| 588 | // Pass 3 (autogain_apply_op): reads src_a + src_b (4x1 stats) + mask_tex | ||
| 589 | // p[0] = (do_auto_gain, lift, gain, ignore_alpha) | ||
| 590 | // p[1] = (per_channel, blend, has_mask, mask_invert) | ||
| 591 | // p[2] = (mbm, 0, 0, 0) | ||
| 592 | // p[3] = skip (r, g, b, a) | ||
| 593 | // ============================================================================ | ||
| 594 | |||
| 595 | @compute @workgroup_size(8, 8) | ||
| 596 | fn autogain_reduce1_op(@builtin(global_invocation_id) gid: vec3<u32>) { | ||
| 597 | let d_dims = textureDimensions(dst_tex); | ||
| 598 | if (gid.x >= d_dims.x || gid.y >= d_dims.y) { return; } | ||
| 599 | |||
| 600 | let s_dims = textureDimensions(src_a); | ||
| 601 | let is_max = gid.x >= 16u; | ||
| 602 | let tx = select(gid.x, gid.x - 16u, is_max); | ||
| 603 | let ty = gid.y; | ||
| 604 | let has_mask = u.p[0].x; | ||
| 605 | let mask_inv = u.p[0].y; | ||
| 606 | |||
| 607 | var acc = select(vec4<f32>(REDUCE_SENTINEL), vec4<f32>(-REDUCE_SENTINEL), is_max); | ||
| 608 | var found = false; | ||
| 609 | |||
| 610 | for (var y: u32 = ty; y < s_dims.y; y = y + 16u) { | ||
| 611 | for (var x: u32 = tx; x < s_dims.x; x = x + 16u) { | ||
| 612 | if (has_mask > 0.5) { | ||
| 613 | let mv = read_mask(vec2<u32>(x, y), s_dims, has_mask, mask_inv); | ||
| 614 | if (mv <= 0.001) { continue; } | ||
| 615 | } | ||
| 616 | let raw = textureLoad(src_a, vec2<i32>(i32(x), i32(y)), 0); | ||
| 617 | let c = vec4<f32>(sanitize(raw.r), sanitize(raw.g), sanitize(raw.b), sanitize(raw.a)); | ||
| 618 | if (is_max) { | ||
| 619 | acc = max(acc, c); | ||
| 620 | } else { | ||
| 621 | acc = min(acc, c); | ||
| 622 | } | ||
| 623 | found = true; | ||
| 624 | } | ||
| 625 | } | ||
| 626 | |||
| 627 | if (!found) { | ||
| 628 | acc = select(vec4<f32>(REDUCE_SENTINEL), vec4<f32>(-REDUCE_SENTINEL), is_max); | ||
| 629 | } | ||
| 630 | textureStore(dst_tex, vec2<i32>(gid.xy), acc); | ||
| 631 | } | ||
| 632 | |||
| 633 | @compute @workgroup_size(8, 8) | ||
| 634 | fn autogain_reduce2_op(@builtin(global_invocation_id) gid: vec3<u32>) { | ||
| 635 | if (gid.x >= 2u || gid.y >= 1u) { return; } | ||
| 636 | |||
| 637 | let is_max = gid.x == 1u; | ||
| 638 | let x_base: i32 = select(0, 16, is_max); | ||
| 639 | var acc = select(vec4<f32>(REDUCE_SENTINEL), vec4<f32>(-REDUCE_SENTINEL), is_max); | ||
| 640 | |||
| 641 | for (var y: i32 = 0; y < 16; y = y + 1) { | ||
| 642 | for (var x: i32 = 0; x < 16; x = x + 1) { | ||
| 643 | let v = textureLoad(src_a, vec2<i32>(x_base + x, y), 0); | ||
| 644 | if (is_max) { | ||
| 645 | acc = max(acc, v); | ||
| 646 | } else { | ||
| 647 | acc = min(acc, v); | ||
| 648 | } | ||
| 649 | } | ||
| 650 | } | ||
| 651 | textureStore(dst_tex, vec2<i32>(i32(gid.x), 0), acc); | ||
| 652 | } | ||
| 653 | |||
| 654 | @compute @workgroup_size(8, 8) | ||
| 655 | fn autogain_apply_op(@builtin(global_invocation_id) gid: vec3<u32>) { | ||
| 656 | let dims = textureDimensions(dst_tex); | ||
| 657 | if (gid.x >= dims.x || gid.y >= dims.y) { return; } | ||
| 658 | |||
| 659 | let p = vec2<i32>(gid.xy); | ||
| 660 | let orig = load_clamped(src_a, p); | ||
| 661 | let blend = u.p[1].y; | ||
| 662 | let mask_v = read_mask(gid.xy, dims, u.p[1].z, u.p[1].w); | ||
| 663 | let eff = clamp(blend * mask_v, 0.0, 1.0); | ||
| 664 | if (eff <= 0.0 && u.p[2].x < 0.5) { | ||
| 665 | store_dst(p, orig); | ||
| 666 | return; | ||
| 667 | } | ||
| 668 | |||
| 669 | let do_auto = u.p[0].x > 0.5; | ||
| 670 | let lift = u.p[0].y; | ||
| 671 | let gain = u.p[0].z; | ||
| 672 | let ignore_alpha = u.p[0].w > 0.5; | ||
| 673 | let per_channel = u.p[1].x > 0.5; | ||
| 674 | |||
| 675 | var effect = orig; | ||
| 676 | if (do_auto) { | ||
| 677 | let mn = textureLoad(src_b, vec2<i32>(0, 0), 0); | ||
| 678 | let mx = textureLoad(src_b, vec2<i32>(1, 0), 0); | ||
| 679 | let valid = mn.r < REDUCE_SENTINEL * 0.5 && mx.r > -REDUCE_SENTINEL * 0.5; | ||
| 680 | if (valid) { | ||
| 681 | if (per_channel) { | ||
| 682 | let r = select(orig.r, lift + (orig.r - mn.r) / (mx.r - mn.r) * (gain - lift), mx.r - mn.r > 1e-5); | ||
| 683 | let g = select(orig.g, lift + (orig.g - mn.g) / (mx.g - mn.g) * (gain - lift), mx.g - mn.g > 1e-5); | ||
| 684 | let b = select(orig.b, lift + (orig.b - mn.b) / (mx.b - mn.b) * (gain - lift), mx.b - mn.b > 1e-5); | ||
| 685 | effect = vec4<f32>(r, g, b, orig.a); | ||
| 686 | } else { | ||
| 687 | let mn_rgb = min(mn.r, min(mn.g, mn.b)); | ||
| 688 | let mx_rgb = max(mx.r, max(mx.g, mx.b)); | ||
| 689 | if (mx_rgb - mn_rgb > 1e-5) { | ||
| 690 | let s = (gain - lift) / (mx_rgb - mn_rgb); | ||
| 691 | effect = vec4<f32>(lift + (orig.rgb - vec3<f32>(mn_rgb)) * s, orig.a); | ||
| 692 | } | ||
| 693 | } | ||
| 694 | if (!ignore_alpha && mx.a - mn.a > 1e-5) { | ||
| 695 | effect.a = lift + (orig.a - mn.a) / (mx.a - mn.a) * (gain - lift); | ||
| 696 | } | ||
| 697 | } | ||
| 698 | } else { | ||
| 699 | effect = vec4<f32>(lift + orig.rgb * (gain - lift), orig.a); | ||
| 700 | if (!ignore_alpha) { | ||
| 701 | effect.a = lift + orig.a * (gain - lift); | ||
| 702 | } | ||
| 703 | } | ||
| 704 | |||
| 705 | let out_c = apply_channel_blend(orig, effect, eff, mask_v, u.p[2].x, u.p[3]); | ||
| 706 | store_dst(p, out_c); | ||
| 707 | } | ||
| 708 | |||
| 709 | // ============================================================================ | ||
| 710 | // 6. ColorBalance — 3-way Shadows/Midtones/Highlights RGB + PreserveLuminance | ||
| 711 | // p[0] = (shadow_r, shadow_g, shadow_b, preserve_luma) | ||
| 712 | // p[1] = (mid_r, mid_g, mid_b, 0) | ||
| 713 | // p[2] = (high_r, high_g, high_b, 0) | ||
| 714 | // p[3] = (blend, has_mask, mask_invert, mbm) | ||
| 715 | // p[4] = skip (r, g, b, a) | ||
| 716 | // ============================================================================ | ||
| 717 | |||
| 718 | @compute @workgroup_size(8, 8) | ||
| 719 | fn color_balance_op(@builtin(global_invocation_id) gid: vec3<u32>) { | ||
| 720 | let dims = textureDimensions(dst_tex); | ||
| 721 | if (gid.x >= dims.x || gid.y >= dims.y) { return; } | ||
| 722 | |||
| 723 | let p = vec2<i32>(gid.xy); | ||
| 724 | let orig = load_clamped(src_a, p); | ||
| 725 | let blend = u.p[3].x; | ||
| 726 | let mask_v = read_mask(gid.xy, dims, u.p[3].y, u.p[3].z); | ||
| 727 | let eff = clamp(blend * mask_v, 0.0, 1.0); | ||
| 728 | if (eff <= 0.0 && u.p[3].w < 0.5) { | ||
| 729 | store_dst(p, orig); | ||
| 730 | return; | ||
| 731 | } | ||
| 732 | |||
| 733 | let sh = u.p[0].rgb; | ||
| 734 | let md = u.p[1].rgb; | ||
| 735 | let hi = u.p[2].rgb; | ||
| 736 | let preserve_luma = u.p[0].w > 0.5; | ||
| 737 | |||
| 738 | let c = clamp(orig.rgb, vec3<f32>(0.0), vec3<f32>(1.0)); | ||
| 739 | let w_s = (vec3<f32>(1.0) - c) * (vec3<f32>(1.0) - c); | ||
| 740 | let w_m = 4.0 * c * (vec3<f32>(1.0) - c); | ||
| 741 | let w_h = c * c; | ||
| 742 | let delta = 0.5 * (sh * w_s + md * w_m + hi * w_h); | ||
| 743 | var rgb = orig.rgb + delta; | ||
| 744 | |||
| 745 | if (preserve_luma) { | ||
| 746 | rgb = max(rgb, vec3<f32>(0.0)); | ||
| 747 | let orig_l = dot(orig.rgb, LUMA_W); | ||
| 748 | let new_l = dot(rgb, LUMA_W); | ||
| 749 | if (new_l > 1e-5 && orig_l > 1e-5) { | ||
| 750 | rgb = rgb * (orig_l / new_l); | ||
| 751 | } | ||
| 752 | } | ||
| 753 | |||
| 754 | let effect = vec4<f32>(rgb, orig.a); | ||
| 755 | let out_c = apply_channel_blend(orig, effect, eff, mask_v, u.p[3].w, u.p[4]); | ||
| 756 | store_dst(p, out_c); | ||
| 757 | } | ||
| 758 | |||
| 759 | // ============================================================================ | ||
| 760 | // 7. SoftClip — C1-smooth hyperbolic knee soft-clipping (HDR-safe) | ||
| 761 | // p[0] = (low, high, low_knee, high_knee) | ||
| 762 | // p[1] = (clip_alpha, blend, has_mask, mask_invert) | ||
| 763 | // p[2] = (mbm, 0, 0, 0) | ||
| 764 | // p[3] = skip (r, g, b, a) | ||
| 765 | // ============================================================================ | ||
| 766 | |||
| 767 | fn soft_clip_scalar(x_in: f32, lo: f32, hi: f32, k_lo_in: f32, k_hi_in: f32) -> f32 { | ||
| 768 | if (hi <= lo) { | ||
| 769 | return lo; | ||
| 770 | } | ||
| 771 | let span = hi - lo; | ||
| 772 | let k_sum = k_lo_in + k_hi_in; | ||
| 773 | let scale = select(1.0, span / k_sum, k_sum > span && k_sum > 1e-6); | ||
| 774 | let k_lo = max(k_lo_in * scale, 0.0); | ||
| 775 | let k_hi = max(k_hi_in * scale, 0.0); | ||
| 776 | |||
| 777 | var x = x_in; | ||
| 778 | let t_hi = hi - k_hi; | ||
| 779 | if (k_hi <= 1e-6) { | ||
| 780 | x = min(x, hi); | ||
| 781 | } else if (x > t_hi) { | ||
| 782 | let d = (x - t_hi) / k_hi; | ||
| 783 | x = t_hi + k_hi * (d / (1.0 + d)); | ||
| 784 | } | ||
| 785 | |||
| 786 | let t_lo = lo + k_lo; | ||
| 787 | if (k_lo <= 1e-6) { | ||
| 788 | x = max(x, lo); | ||
| 789 | } else if (x < t_lo) { | ||
| 790 | let d = (t_lo - x) / k_lo; | ||
| 791 | x = t_lo - k_lo * (d / (1.0 + d)); | ||
| 792 | } | ||
| 793 | return x; | ||
| 794 | } | ||
| 795 | |||
| 796 | @compute @workgroup_size(8, 8) | ||
| 797 | fn soft_clip_op(@builtin(global_invocation_id) gid: vec3<u32>) { | ||
| 798 | let dims = textureDimensions(dst_tex); | ||
| 799 | if (gid.x >= dims.x || gid.y >= dims.y) { return; } | ||
| 800 | |||
| 801 | let p = vec2<i32>(gid.xy); | ||
| 802 | let orig = load_clamped(src_a, p); | ||
| 803 | let blend = u.p[1].y; | ||
| 804 | let mask_v = read_mask(gid.xy, dims, u.p[1].z, u.p[1].w); | ||
| 805 | let eff = clamp(blend * mask_v, 0.0, 1.0); | ||
| 806 | if (eff <= 0.0 && u.p[2].x < 0.5) { | ||
| 807 | store_dst(p, orig); | ||
| 808 | return; | ||
| 809 | } | ||
| 810 | |||
| 811 | let lo = u.p[0].x; | ||
| 812 | let hi = u.p[0].y; | ||
| 813 | let k_lo = u.p[0].z; | ||
| 814 | let k_hi = u.p[0].w; | ||
| 815 | let clip_a = u.p[1].x > 0.5; | ||
| 816 | |||
| 817 | let r = soft_clip_scalar(orig.r, lo, hi, k_lo, k_hi); | ||
| 818 | let g = soft_clip_scalar(orig.g, lo, hi, k_lo, k_hi); | ||
| 819 | let b = soft_clip_scalar(orig.b, lo, hi, k_lo, k_hi); | ||
| 820 | let a = select(orig.a, soft_clip_scalar(orig.a, lo, hi, k_lo, k_hi), clip_a); | ||
| 821 | |||
| 822 | let out_c = apply_channel_blend(orig, vec4<f32>(r, g, b, a), eff, mask_v, u.p[2].x, u.p[3]); | ||
| 823 | store_dst(p, out_c); | ||
| 824 | } | ||
| 825 | |||
| 826 | // ============================================================================ | ||
| 827 | // 8. Grain — Classic Fusion RGB film grain | ||
| 828 | // p[0] = (power, size, softness, seed) | ||
| 829 | // p[1] = (red_str, green_str, blue_str, mono) | ||
| 830 | // p[2] = (alpha_mult, blend, has_mask, mask_invert) | ||
| 831 | // p[3] = (mbm, 0, 0, 0) | ||
| 832 | // p[4] = skip (r, g, b, a) | ||
| 833 | // ============================================================================ | ||
| 834 | |||
| 835 | fn grain_gauss(cell: vec2<i32>, seed: i32) -> f32 { | ||
| 836 | // 3-tap Irwin-Hall zero-mean Gaussian approximation (std dev = 1.0). | ||
| 837 | let a = hash21(cell, seed); | ||
| 838 | let b = hash21(cell + vec2<i32>(37, 91), seed + 1013); | ||
| 839 | let c = hash21(cell + vec2<i32>(113, 53), seed + 2027); | ||
| 840 | return (a + b + c - 1.5) * 2.0; | ||
| 841 | } | ||
| 842 | |||
| 843 | fn grain_sample(coord: vec2<f32>, size: f32, softness: f32, seed: i32) -> f32 { | ||
| 844 | let sc = coord / max(size, 0.25); | ||
| 845 | let i0 = vec2<i32>(floor(sc)); | ||
| 846 | let sharp = grain_gauss(i0, seed); | ||
| 847 | if (softness <= 1e-4) { | ||
| 848 | return sharp; | ||
| 849 | } | ||
| 850 | |||
| 851 | // Smooth Hermite-interpolated lattice noise + 3x3 binomial filter for Softness at any Size. | ||
| 852 | let f = sc - floor(sc); | ||
| 853 | let sm = f * f * (3.0 - 2.0 * f); | ||
| 854 | let g00 = grain_gauss(i0, seed); | ||
| 855 | let g10 = grain_gauss(i0 + vec2<i32>(1, 0), seed); | ||
| 856 | let g01 = grain_gauss(i0 + vec2<i32>(0, 1), seed); | ||
| 857 | let g11 = grain_gauss(i0 + vec2<i32>(1, 1), seed); | ||
| 858 | let interp = mix(mix(g00, g10, sm.x), mix(g01, g11, sm.x), sm.y); | ||
| 859 | |||
| 860 | // 3x3 binomial blur of cell noise (normalized to preserve variance under softness). | ||
| 861 | var bsum: f32 = 0.0; | ||
| 862 | for (var dy: i32 = -1; dy <= 1; dy = dy + 1) { | ||
| 863 | let wy = select(1.0, 2.0, dy == 0); | ||
| 864 | for (var dx: i32 = -1; dx <= 1; dx = dx + 1) { | ||
| 865 | let wx = select(1.0, 2.0, dx == 0); | ||
| 866 | bsum = bsum + wx * wy * grain_gauss(i0 + vec2<i32>(dx, dy), seed); | ||
| 867 | } | ||
| 868 | } | ||
| 869 | let soft_val = mix(bsum / 16.0, interp, clamp((size - 1.0) * 0.5, 0.0, 1.0)); | ||
| 870 | return mix(sharp, soft_val, clamp(softness, 0.0, 1.0)); | ||
| 871 | } | ||
| 872 | |||
| 873 | @compute @workgroup_size(8, 8) | ||
| 874 | fn grain_op(@builtin(global_invocation_id) gid: vec3<u32>) { | ||
| 875 | let dims = textureDimensions(dst_tex); | ||
| 876 | if (gid.x >= dims.x || gid.y >= dims.y) { return; } | ||
| 877 | |||
| 878 | let p = vec2<i32>(gid.xy); | ||
| 879 | let orig = load_clamped(src_a, p); | ||
| 880 | let blend = u.p[2].y; | ||
| 881 | let mask_v = read_mask(gid.xy, dims, u.p[2].z, u.p[2].w); | ||
| 882 | let eff = clamp(blend * mask_v, 0.0, 1.0); | ||
| 883 | let power = max(u.p[0].x, 0.0); | ||
| 884 | if ((eff <= 0.0 || power <= 1e-6) && u.p[3].x < 0.5) { | ||
| 885 | store_dst(p, orig); | ||
| 886 | return; | ||
| 887 | } | ||
| 888 | |||
| 889 | let size = max(u.p[0].y, 0.25); | ||
| 890 | let softness = clamp(u.p[0].z, 0.0, 1.0); | ||
| 891 | let seed = i32(round(u.p[0].w)); | ||
| 892 | let r_str = u.p[1].x; | ||
| 893 | let g_str = u.p[1].y; | ||
| 894 | let b_str = u.p[1].z; | ||
| 895 | let mono = u.p[1].w > 0.5; | ||
| 896 | let alpha_mult = u.p[2].x > 0.5; | ||
| 897 | |||
| 898 | let coord = vec2<f32>(gid.xy) + vec2<f32>(0.5); | ||
| 899 | let nr = grain_sample(coord, size, softness, seed + 17); | ||
| 900 | let ng = select(grain_sample(coord, size, softness, seed + 4099), nr, mono); | ||
| 901 | let nb = select(grain_sample(coord, size, softness, seed + 8191), nr, mono); | ||
| 902 | |||
| 903 | let a_scale = select(1.0, clamp(orig.a, 0.0, 1.0), alpha_mult); | ||
| 904 | let amp = 0.08 * power * a_scale; | ||
| 905 | let effect = vec4<f32>( | ||
| 906 | orig.r + nr * amp * r_str, | ||
| 907 | orig.g + ng * amp * g_str, | ||
| 908 | orig.b + nb * amp * b_str, | ||
| 909 | orig.a, | ||
| 910 | ); | ||
| 911 | |||
| 912 | let out_c = apply_channel_blend(orig, effect, eff, mask_v, u.p[3].x, u.p[4]); | ||
| 913 | store_dst(p, out_c); | ||
| 914 | } | ||