1//! Wave 35B — Depth, Optical & Filter FX GPU pipelines and evaluators:
2//! - `DepthBlur` (depth-driven CoC blur from `BlurImage`/`BlurChannel` or `aux.z`)
3//! - `Fog` (depth-driven atmospheric fog from `aux.z`, colored by the optional `Fog` image)
4//! - `Highlight` (2-pass bright-threshold extraction + exponential starburst streaks)
5//! - `HotSpot` (radial primary glow + secondary optical lens flare elements)
6//! - `RankFilter` (GPU order-statistic Min/Median/Max/Percentile filter)
7//!
8//! WebGPU safety: `R32Float` depth textures are bound with `filterable: false` and read
9//! exclusively via `textureLoad`; output storage textures are `WriteOnly`.
10
11use super::*;
12use crate::cache::{AuxChannelTex, EMPTY_Z_SENTINEL};
13use std::num::NonZeroU64;
14
15const DEPTH_OPTICAL_WGSL: &str = include_str!("../shaders/depth_optical.wgsl");
16const UNIFORM_SLOTS_PER_CHUNK: u32 = 512;
17const MAX_RANK_RADIUS: f32 = 5.0;
18
19#[derive(Clone, Copy)]
20enum DepthOpticalOp {
21 DepthBlur,
22 Fog,
23 HighlightExtract,
24 HighlightStreaks,
25 HotSpot,
26 RankFilter,
27}
28
29fn build_wgsl(format: wgpu::TextureFormat, hdr_float: bool) -> String {
30 let storage_fmt = match format {
31 wgpu::TextureFormat::Rgba16Float => "rgba16float",
32 wgpu::TextureFormat::Rgba32Float => "rgba32float",
33 _ => "rgba8unorm",
34 };
35 let mut src = DEPTH_OPTICAL_WGSL.to_owned();
36 if storage_fmt != "rgba8unorm" {
37 src = src.replace(
38 "texture_storage_2d<rgba8unorm, write>",
39 &format!("texture_storage_2d<{storage_fmt}, write>"),
40 );
41 }
42 if hdr_float {
43 src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;");
44 }
45 src
46}
47
48fn tex_entry(binding: u32, filterable: bool) -> wgpu::BindGroupLayoutEntry {
49 wgpu::BindGroupLayoutEntry {
50 binding,
51 visibility: wgpu::ShaderStages::COMPUTE,
52 ty: wgpu::BindingType::Texture {
53 sample_type: wgpu::TextureSampleType::Float { filterable },
54 view_dimension: wgpu::TextureViewDimension::D2,
55 multisampled: false,
56 },
57 count: None,
58 }
59}
60
61struct FormatPipelines {
62 bgl: wgpu::BindGroupLayout,
63 depth_blur: wgpu::ComputePipeline,
64 fog: wgpu::ComputePipeline,
65 highlight_extract: wgpu::ComputePipeline,
66 highlight_streaks: wgpu::ComputePipeline,
67 hot_spot: wgpu::ComputePipeline,
68 rank_filter: wgpu::ComputePipeline,
69}
70
71pub(super) struct DepthOpticalPipelines {
72 sampler: wgpu::Sampler,
73 uniform_stride: u32,
74 uniform_chunks: Vec<wgpu::Buffer>,
75 uniform_cursor: u32,
76 dummy_z: AuxChannelTex,
77 formats: HashMap<(wgpu::TextureFormat, bool), FormatPipelines>,
78}
79
80impl DepthOpticalPipelines {
81 pub(super) fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self {
82 let uniform_size = std::mem::size_of::<UniformParams>() as u32;
83 let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1);
84 let uniform_stride = uniform_size.div_ceil(min_align) * min_align;
85
86 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
87 label: Some("depth-optical-linear"),
88 address_mode_u: wgpu::AddressMode::ClampToEdge,
89 address_mode_v: wgpu::AddressMode::ClampToEdge,
90 mag_filter: wgpu::FilterMode::Linear,
91 min_filter: wgpu::FilterMode::Linear,
92 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
93 ..Default::default()
94 });
95
96 let dummy_z = AuxChannelTex::new(device, [1, 1], wgpu::TextureFormat::R32Float, "do-dummy-z");
97 queue.write_texture(
98 dummy_z.texture.as_image_copy(),
99 &EMPTY_Z_SENTINEL.to_le_bytes(),
100 wgpu::TexelCopyBufferLayout {
101 offset: 0,
102 bytes_per_row: Some(4),
103 rows_per_image: Some(1),
104 },
105 wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },
106 );
107
108 Self {
109 sampler,
110 uniform_stride,
111 uniform_chunks: Vec::new(),
112 uniform_cursor: 0,
113 dummy_z,
114 formats: HashMap::new(),
115 }
116 }
117
118 pub(super) fn reset_uniform_cursor(&mut self) {
119 self.uniform_cursor = 0;
120 }
121
122 pub(super) fn trim_uniform_chunks(&mut self, max_chunks: usize) {
123 self.uniform_cursor = 0;
124 if self.uniform_chunks.len() > max_chunks {
125 self.uniform_chunks.truncate(max_chunks);
126 }
127 }
128
129 fn alloc_uniform_slot(
130 &mut self,
131 device: &wgpu::Device,
132 queue: &wgpu::Queue,
133 params: &UniformParams,
134 ) -> (usize, u32) {
135 let slot_global = self.uniform_cursor;
136 let chunk_idx = (slot_global / UNIFORM_SLOTS_PER_CHUNK) as usize;
137 let slot_in_chunk = slot_global % UNIFORM_SLOTS_PER_CHUNK;
138 while chunk_idx >= self.uniform_chunks.len() {
139 let size = u64::from(UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride);
140 let buf = device.create_buffer(&wgpu::BufferDescriptor {
141 label: Some("depth-optical-params-ring"),
142 size,
143 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
144 mapped_at_creation: false,
145 });
146 self.uniform_chunks.push(buf);
147 }
148 let offset = slot_in_chunk * self.uniform_stride;
149 queue.write_buffer(
150 &self.uniform_chunks[chunk_idx],
151 u64::from(offset),
152 bytemuck::bytes_of(params),
153 );
154 self.uniform_cursor = slot_global + 1;
155 (chunk_idx, offset)
156 }
157
158 fn ensure_format(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) {
159 if self.formats.contains_key(&(format, hdr_float)) {
160 return;
161 }
162 let u_size = std::mem::size_of::<UniformParams>() as u64;
163 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
164 label: Some("depth-optical-bgl"),
165 entries: &[
166 tex_entry(0, true),
167 tex_entry(1, true),
168 tex_entry(2, false), // R32Float depth: MUST be unfilterable for WebGPU/wasm32!
169 tex_entry(3, true),
170 wgpu::BindGroupLayoutEntry {
171 binding: 4,
172 visibility: wgpu::ShaderStages::COMPUTE,
173 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
174 count: None,
175 },
176 wgpu::BindGroupLayoutEntry {
177 binding: 5,
178 visibility: wgpu::ShaderStages::COMPUTE,
179 ty: wgpu::BindingType::StorageTexture {
180 access: wgpu::StorageTextureAccess::WriteOnly,
181 format,
182 view_dimension: wgpu::TextureViewDimension::D2,
183 },
184 count: None,
185 },
186 wgpu::BindGroupLayoutEntry {
187 binding: 6,
188 visibility: wgpu::ShaderStages::COMPUTE,
189 ty: wgpu::BindingType::Buffer {
190 ty: wgpu::BufferBindingType::Uniform,
191 has_dynamic_offset: true,
192 min_binding_size: NonZeroU64::new(u_size),
193 },
194 count: None,
195 },
196 ],
197 });
198 let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
199 label: Some("depth-optical-pl"),
200 bind_group_layouts: &[Some(&bgl)],
201 immediate_size: 0,
202 });
203 let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
204 label: Some("depth-optical-wgsl"),
205 source: wgpu::ShaderSource::Wgsl(build_wgsl(format, hdr_float).into()),
206 });
207 let mk = |entry: &str| {
208 device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
209 label: Some(entry),
210 layout: Some(&pl),
211 module: &module,
212 entry_point: Some(entry),
213 compilation_options: Default::default(),
214 cache: None,
215 })
216 };
217 self.formats.insert(
218 (format, hdr_float),
219 FormatPipelines {
220 bgl,
221 depth_blur: mk("depth_blur_op"),
222 fog: mk("fog_op"),
223 highlight_extract: mk("highlight_extract_op"),
224 highlight_streaks: mk("highlight_streaks_op"),
225 hot_spot: mk("hot_spot_op"),
226 rank_filter: mk("rank_filter_op"),
227 },
228 );
229 }
230
231 #[allow(clippy::too_many_arguments)]
232 fn dispatch(
233 &mut self,
234 device: &wgpu::Device,
235 queue: &wgpu::Queue,
236 enc: &mut wgpu::CommandEncoder,
237 op: DepthOpticalOp,
238 src_view: &wgpu::TextureView,
239 aux_img_view: &wgpu::TextureView,
240 z_view: Option<&wgpu::TextureView>,
241 mask_view: &wgpu::TextureView,
242 dst: &CachedTexture,
243 params: &UniformParams,
244 ) {
245 let format = dst.texture.format();
246 let hdr_float = dst.depth.is_float();
247 self.ensure_format(device, format, hdr_float);
248 let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params);
249 let fp = &self.formats[&(format, hdr_float)];
250 let zv = z_view.unwrap_or(&self.dummy_z.view);
251 let u_size = NonZeroU64::new(std::mem::size_of::<UniformParams>() as u64);
252 let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
253 label: Some("depth-optical-bg"),
254 layout: &fp.bgl,
255 entries: &[
256 wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_view) },
257 wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(aux_img_view) },
258 wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(zv) },
259 wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(mask_view) },
260 wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::Sampler(&self.sampler) },
261 wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(&dst.view) },
262 wgpu::BindGroupEntry {
263 binding: 6,
264 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
265 buffer: &self.uniform_chunks[chunk_idx],
266 offset: 0,
267 size: u_size,
268 }),
269 },
270 ],
271 });
272 let pipeline = match op {
273 DepthOpticalOp::DepthBlur => &fp.depth_blur,
274 DepthOpticalOp::Fog => &fp.fog,
275 DepthOpticalOp::HighlightExtract => &fp.highlight_extract,
276 DepthOpticalOp::HighlightStreaks => &fp.highlight_streaks,
277 DepthOpticalOp::HotSpot => &fp.hot_spot,
278 DepthOpticalOp::RankFilter => &fp.rank_filter,
279 };
280 let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
281 label: Some("depth-optical-pass"),
282 timestamp_writes: None,
283 });
284 pass.set_pipeline(pipeline);
285 pass.set_bind_group(0, &bg, &[offset]);
286 pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1);
287 }
288}
289
290fn parse_depth_blur_channel(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> i32 {
291 if let Some(s) = node.static_str("BlurChannel") {
292 return match s {
293 "Red" => 0,
294 "Green" => 1,
295 "Blue" => 2,
296 "Alpha" => 3,
297 "Z" | "ZBuffer" | "Z-Buffer" => 4,
298 "Luminance" | "Luma" => 5,
299 _ => 4,
300 };
301 }
302 comp.eval_number(node, "BlurChannel", time, 4.0, expr).round().clamp(0.0, 5.0) as i32
303}
304
305fn parse_depth_blur_filter(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> i32 {
306 if let Some(s) = node.static_str("Filter") {
307 return match s {
308 "Box" => 1,
309 "Gaussian" | "Fast Gaussian" => 2,
310 "Lens" | "Bokeh" => 3,
311 _ => 0,
312 };
313 }
314 comp.eval_number(node, "Filter", time, 0.0, expr).round().clamp(0.0, 3.0) as i32
315}
316
317fn parse_hotspot_apply_mode(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> i32 {
318 if let Some(s) = node.static_str("ApplyMode") {
319 return match s {
320 "Screen" => 1,
321 "Normal" | "Over" => 2,
322 "Multiply" => 3,
323 "Lighten" | "Max" => 4,
324 "Overlay" => 5,
325 _ => 0, // Add / LinearDodge
326 };
327 }
328 comp.eval_number(node, "ApplyMode", time, 0.0, expr).round().clamp(0.0, 5.0) as i32
329}
330
331fn parse_rank_filter_type(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> i32 {
332 if let Some(s) = node.static_str("FilterType") {
333 return match s {
334 "Circle" | "Circular" | "Disc" => 1,
335 "Cross" | "Plus" => 2,
336 "Diamond" => 3,
337 _ => 0, // Box / Square
338 };
339 }
340 comp.eval_number(node, "FilterType", time, 0.0, expr).round().clamp(0.0, 3.0) as i32
341}
342
343impl Engine {
344 pub(super) fn depth_optical_pipelines(&self) -> &RefCell<DepthOpticalPipelines> {
345 self.depth_optical_pipelines
346 .get_or_init(|| RefCell::new(DepthOpticalPipelines::new(&self.device, &self.queue)))
347 }
348
349 fn eval_num_alias(&self, comp: &Comp, node: &Node, primary: &str, fallback: &str, time: f64, default: f64) -> f32 {
350 if node.inputs.contains_key(primary) {
351 comp.eval_number(node, primary, time, default, &self.expr) as f32
352 } else {
353 comp.eval_number(node, fallback, time, default, &self.expr) as f32
354 }
355 }
356
357 fn combined_skip(&self, comp: &Comp, node: &Node, time: f64) -> [f32; 4] {
358 let p_skip = self.process_skip(comp, node, time);
359 let c_names = ["Red", "Green", "Blue", "Alpha"];
360 let mut out = p_skip;
361 for i in 0..4 {
362 if node.inputs.contains_key(c_names[i])
363 && comp.eval_number(node, c_names[i], time, 1.0, &self.expr) <= 0.5
364 {
365 out[i] = 1.0;
366 }
367 }
368 out
369 }
370
371 /// 1. `DepthBlur`: circle-of-confusion blur driven by `BlurImage`/`BlurChannel` or `aux.z`.
372 #[allow(clippy::too_many_arguments)]
373 pub(super) fn eval_depth_blur(
374 &mut self,
375 comp: &Comp,
376 node: &Node,
377 time: f64,
378 frame_i: i64,
379 enc: &mut wgpu::CommandEncoder,
380 visiting: &mut HashSet<(NodeId, i64)>,
381 stats: &mut EvalStats,
382 ) -> CachedTexture {
383 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
384 return self.dummy.clone();
385 };
386 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
387 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
388 let mbm = self.multiplies_by_mask(comp, node, time);
389 let blur_raw = self.eval_num_alias(comp, node, "XBlurSize", "BlurSize", time, 1.0).max(0.0);
390 // Fusion blur size uses 720px-width reference; src.canvas_size already reflects proxy_scale.
391 let max_r = (blur_raw * (src.canvas_size[0] as f32 / 720.0)).min(96.0);
392 if (blend <= 1e-6 || max_r < 0.25) && !mbm {
393 return src;
394 }
395
396 let src_aux = src.aux.clone();
397 let src = self.crop_to_canvas(enc, src);
398 let blur_img = node
399 .connected_node("BlurImage")
400 .and_then(|s| comp.find_node(s))
401 .map(|bid| {
402 let t = self.eval_node(comp, bid, time, enc, visiting, stats);
403 self.crop_to_canvas(enc, t)
404 });
405
406 let mut channel = parse_depth_blur_channel(comp, node, time, &self.expr);
407 let (depth_src_mode, z_tex_opt): (i32, Option<AuxChannelTex>) = if channel == 4 {
408 if let Some(bi) = &blur_img {
409 if let Some(bz) = bi.aux.as_ref().and_then(|a| a.z.clone()) {
410 (0, Some(bz))
411 } else {
412 channel = 5; // BlurImage without aux.z -> use luminance
413 (1, None)
414 }
415 } else if let Some(sz) = src_aux.as_ref().and_then(|a| a.z.clone()) {
416 (0, Some(sz))
417 } else {
418 // No depth source available -> pass through unless MultiplyByMask is active.
419 if !mbm {
420 let mut out = src;
421 out.set_aux(src_aux);
422 return out;
423 }
424 (0, None)
425 }
426 } else if blur_img.is_some() {
427 (1, None)
428 } else {
429 (2, None)
430 };
431
432 let focal = comp.eval_number(node, "FocalPoint", time, 0.0, &self.expr) as f32;
433 let dof = comp.eval_number(node, "DepthOfField", time, 0.0, &self.expr) as f32;
434 let z_scale = comp.eval_number(node, "ZScale", time, 1.0, &self.expr) as f32;
435 let filter_mode = parse_depth_blur_filter(comp, node, time, &self.expr);
436 let clamp_edges = if node.static_str("ClippingMode").unwrap_or("Frame") == "None" { 0.0 } else { 1.0 };
437 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
438 let skip = self.combined_skip(comp, node, time);
439 let taps = match (filter_mode, self.hiq) {
440 (1, true) => 3.0,
441 (1, false) => 2.0,
442 (_, true) => 36.0,
443 (_, false) => 16.0,
444 };
445
446 let mut u = UniformParams::default();
447 u.p[0] = [if depth_src_mode == 0 && z_tex_opt.is_none() { 0.0 } else { max_r }, focal, dof, z_scale];
448 u.p[1] = [filter_mode as f32, depth_src_mode as f32, channel as f32, clamp_edges];
449 u.p[2] = [blend, mask.is_some() as u8 as f32, mask_inv as u8 as f32, mbm as u8 as f32];
450 u.p[3] = skip;
451 u.p[4] = [taps, z_tex_opt.is_some() as u8 as f32, 0.0, 0.0];
452
453 let bi_hash = blur_img.as_ref().map_or(0, |b| b.content_hash);
454 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
455 let key = self.make_key(
456 node,
457 "DepthBlur",
458 src.size,
459 &[src.content_hash, bi_hash, mask_hash],
460 bytemuck::cast_slice(&u.p[..5]),
461 );
462 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
463 stats.cache_hits += 1;
464 return hit;
465 }
466 stats.cache_misses += 1;
467 stats.nodes_evaluated += 1;
468
469 let mut dst = self.alloc_tex_like(&src, src.depth, key);
470 dst.set_aux(src_aux);
471 let bv = blur_img.as_ref().map_or(&self.dummy.view, |b| &b.view);
472 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
473 let zv = z_tex_opt.as_ref().map(|z| z.view.as_ref());
474 self.depth_optical_pipelines().borrow_mut().dispatch(
475 &self.device,
476 &self.queue,
477 enc,
478 DepthOpticalOp::DepthBlur,
479 &src.view,
480 bv,
481 zv,
482 mv,
483 &dst,
484 &u,
485 );
486 self.cache.insert(key, dst.clone(), node.id, frame_i);
487 dst
488 }
489
490 /// 2. `Fog`: depth-driven atmospheric fog from `aux.z`, colored by the optional `Fog` image.
491 #[allow(clippy::too_many_arguments)]
492 pub(super) fn eval_fog(
493 &mut self,
494 comp: &Comp,
495 node: &Node,
496 time: f64,
497 frame_i: i64,
498 enc: &mut wgpu::CommandEncoder,
499 visiting: &mut HashSet<(NodeId, i64)>,
500 stats: &mut EvalStats,
501 ) -> CachedTexture {
502 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
503 return self.dummy.clone();
504 };
505 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
506 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
507 let fog_opacity = comp.eval_number(node, "FogOpacity", time, 1.0, &self.expr) as f32;
508 let mbm = self.multiplies_by_mask(comp, node, time);
509 if (blend <= 1e-6 || fog_opacity <= 1e-6) && !mbm {
510 return src;
511 }
512
513 let src_aux = src.aux.clone();
514 let src = self.crop_to_canvas(enc, src);
515 let fog_img = node
516 .connected_node("Fog")
517 .and_then(|s| comp.find_node(s))
518 .map(|fid| {
519 let t = self.eval_node(comp, fid, time, enc, visiting, stats);
520 self.crop_to_canvas(enc, t)
521 });
522
523 let (depth_mode, has_fog_color_img, z_tex_opt): (i32, bool, Option<AuxChannelTex>) =
524 if let Some(sz) = src_aux.as_ref().and_then(|a| a.z.clone()) {
525 (0, fog_img.is_some(), Some(sz))
526 } else if let Some(fi) = &fog_img {
527 if let Some(fz) = fi.aux.as_ref().and_then(|a| a.z.clone()) {
528 (0, false, Some(fz))
529 } else {
530 (1, true, None)
531 }
532 } else {
533 (1, false, None)
534 };
535
536 let near_p = self.eval_num_alias(comp, node, "ZNearPlane", "NearPlane", time, 0.0);
537 let far_p = self.eval_num_alias(comp, node, "ZFarPlane", "FarPlane", time, -500.0);
538 let falloff = comp.eval_number(node, "Falloff", time, 1.0, &self.expr) as f32;
539 let z_scale = comp.eval_number(node, "ZScale", time, 1.0, &self.expr) as f32;
540 let fog_r = comp.eval_number(node, "FogRed", time, 0.7, &self.expr) as f32;
541 let fog_g = comp.eval_number(node, "FogGreen", time, 0.7, &self.expr) as f32;
542 let fog_b = comp.eval_number(node, "FogBlue", time, 0.8, &self.expr) as f32;
543 let fog_a = comp.eval_number(node, "FogAlpha", time, 1.0, &self.expr) as f32;
544 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
545 let skip = self.process_skip(comp, node, time);
546
547 let mut u = UniformParams::default();
548 u.p[0] = [near_p, far_p, falloff, z_scale];
549 u.p[1] = [fog_r, fog_g, fog_b, fog_a];
550 u.p[2] = [fog_opacity, depth_mode as f32, has_fog_color_img as u8 as f32, z_tex_opt.is_some() as u8 as f32];
551 u.p[3] = [blend, mask.is_some() as u8 as f32, mask_inv as u8 as f32, mbm as u8 as f32];
552 u.p[4] = skip;
553
554 let fi_hash = fog_img.as_ref().map_or(0, |f| f.content_hash);
555 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
556 let key = self.make_key(
557 node,
558 "Fog",
559 src.size,
560 &[src.content_hash, fi_hash, mask_hash],
561 bytemuck::cast_slice(&u.p[..5]),
562 );
563 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
564 stats.cache_hits += 1;
565 return hit;
566 }
567 stats.cache_misses += 1;
568 stats.nodes_evaluated += 1;
569
570 let mut dst = self.alloc_tex_like(&src, src.depth, key);
571 dst.set_aux(src_aux);
572 let fv = fog_img.as_ref().map_or(&self.dummy.view, |f| &f.view);
573 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
574 let zv = z_tex_opt.as_ref().map(|z| z.view.as_ref());
575 self.depth_optical_pipelines().borrow_mut().dispatch(
576 &self.device,
577 &self.queue,
578 enc,
579 DepthOpticalOp::Fog,
580 &src.view,
581 fv,
582 zv,
583 mv,
584 &dst,
585 &u,
586 );
587 self.cache.insert(key, dst.clone(), node.id, frame_i);
588 dst
589 }
590
591 /// 3. `Highlight`: threshold bright pixels (`Low`/`High`/`Curve`) + exponential starburst streaks.
592 #[allow(clippy::too_many_arguments)]
593 pub(super) fn eval_highlight(
594 &mut self,
595 comp: &Comp,
596 node: &Node,
597 time: f64,
598 frame_i: i64,
599 enc: &mut wgpu::CommandEncoder,
600 visiting: &mut HashSet<(NodeId, i64)>,
601 stats: &mut EvalStats,
602 ) -> CachedTexture {
603 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
604 return self.dummy.clone();
605 };
606 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
607 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
608 let mbm = self.multiplies_by_mask(comp, node, time);
609 if blend <= 1e-6 && !mbm {
610 return src;
611 }
612 let src = self.crop_to_canvas(enc, src);
613 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
614 let skip = self.process_skip(comp, node, time);
615 let num = |id: &str, default: f64| comp.eval_number(node, id, time, default, &self.expr) as f32;
616
617 // Each streak tap s pixels away weighs d^s with d = log10((1 + 9 * Length) * ChannelScale), independent of resolution.
618 let length_gain = 1.0 + 9.0 * num("Length", 0.8);
619 let decay = ["RedScale", "GreenScale", "BlueScale", "AlphaScale"].map(|id| (length_gain * num(id, 1.0)).log10().max(0.0));
620 let d_max = decay.into_iter().fold(0.0, f32::max);
621 let reach = (src.size[0] as f32).hypot(src.size[1] as f32).ceil();
622 // Fusion stops once the strongest weight falls below e^-10 or would exceed 32768.
623 let taps = match d_max {
624 d if d <= 0.0 => 0.0,
625 d if d < 1.0 => (-10.0 / d.ln()).floor().min(reach),
626 d if d > 1.0 => (32768f32.ln() / d.ln()).floor().min(reach),
627 _ => reach,
628 };
629
630 let mut u_ext = UniformParams::default();
631 u_ext.p[0] = [num("Low", 0.9), num("High", 1.0), num("Curve", 1.0), (src.depth == BitDepth::Int8) as u8 as f32];
632
633 let mut u_str = UniformParams::default();
634 u_str.p[0] = [
635 num("NumberOfPoints", 4.0).round().clamp(1.0, 64.0),
636 num("Angle", 0.0).to_radians(),
637 taps,
638 (num("MergeOver", 1.0) > 0.5) as u8 as f32,
639 ];
640 u_str.p[1] = decay;
641 u_str.p[2] = [blend, mask.is_some() as u8 as f32, mask_inv as u8 as f32, mbm as u8 as f32];
642 u_str.p[3] = skip;
643 u_str.p[4] = u_ext.p[0];
644
645 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
646 let key = self.make_key(
647 node,
648 "Highlight",
649 src.size,
650 &[src.content_hash, mask_hash],
651 bytemuck::cast_slice(&u_str.p[..5]),
652 );
653 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
654 stats.cache_hits += 1;
655 return hit;
656 }
657 stats.cache_misses += 1;
658 stats.nodes_evaluated += 1;
659
660 let bright = self.alloc_tex(src.size, src.depth.max(BitDepth::Float32), 0);
661 let mut dst = self.alloc_tex_like(&src, src.depth, key);
662 if src.aux.is_some() && dst.size == src.size && dst.origin == src.origin {
663 dst.set_aux(src.aux.clone());
664 }
665 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
666 let mut pipes = self.depth_optical_pipelines().borrow_mut();
667 pipes.dispatch(
668 &self.device,
669 &self.queue,
670 enc,
671 DepthOpticalOp::HighlightExtract,
672 &src.view,
673 &self.dummy.view,
674 None,
675 &self.dummy.view,
676 &bright,
677 &u_ext,
678 );
679 pipes.dispatch(
680 &self.device,
681 &self.queue,
682 enc,
683 DepthOpticalOp::HighlightStreaks,
684 &src.view,
685 &bright.view,
686 None,
687 mv,
688 &dst,
689 &u_str,
690 );
691 drop(pipes);
692 self.cache.insert(key, dst.clone(), node.id, frame_i);
693 dst
694 }
695
696 /// 4. `HotSpot`: radial primary glow + optional secondary optical lens flare elements.
697 #[allow(clippy::too_many_arguments)]
698 pub(super) fn eval_hot_spot(
699 &mut self,
700 comp: &Comp,
701 node: &Node,
702 time: f64,
703 frame_i: i64,
704 enc: &mut wgpu::CommandEncoder,
705 visiting: &mut HashSet<(NodeId, i64)>,
706 stats: &mut EvalStats,
707 ) -> CachedTexture {
708 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
709 return self.dummy.clone();
710 };
711 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
712 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
713 let mbm = self.multiplies_by_mask(comp, node, time);
714 if blend <= 1e-6 && !mbm {
715 return src;
716 }
717 let src = self.crop_to_canvas(enc, src);
718
719 let p_center = if node.inputs.contains_key("Center") {
720 comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr)
721 } else {
722 comp.eval_point(node, "PrimaryPosition", time, [0.5, 0.5], &self.expr)
723 };
724 let default_sec = [1.0 - p_center[0], 1.0 - p_center[1]];
725 let has_explicit_sec = node.inputs.contains_key("SecondaryCenter")
726 || node.inputs.contains_key("SecondaryPosition")
727 || node.inputs.contains_key("SecondaryStrength");
728 let s_center = if node.inputs.contains_key("SecondaryCenter") {
729 comp.eval_point(node, "SecondaryCenter", time, default_sec, &self.expr)
730 } else if node.inputs.contains_key("SecondaryPosition") {
731 comp.eval_point(node, "SecondaryPosition", time, default_sec, &self.expr)
732 } else {
733 default_sec
734 };
735
736 let primary_size = self.eval_num_alias(comp, node, "PrimarySize", "HotSpotSize", time, 0.25);
737 let primary_strength = comp.eval_number(node, "PrimaryStrength", time, 1.0, &self.expr) as f32;
738 let primary_aspect = self.eval_num_alias(comp, node, "PrimaryAspect", "Aspect", time, 1.0);
739 let primary_r = self.eval_num_alias(comp, node, "PrimaryRed", "ColorRed", time, 1.0);
740 let primary_g = self.eval_num_alias(comp, node, "PrimaryGreen", "ColorGreen", time, 1.0);
741 let primary_b = self.eval_num_alias(comp, node, "PrimaryBlue", "ColorBlue", time, 1.0);
742 let default_sec_elems = if has_explicit_sec { 4.0 } else { 0.0 };
743 let sec_elements = self
744 .eval_num_alias(comp, node, "SecondaryElements", "Elements", time, default_sec_elems)
745 .clamp(0.0, 16.0);
746 let sec_strength = comp.eval_number(node, "SecondaryStrength", time, 0.5, &self.expr) as f32;
747 let sec_size = comp.eval_number(node, "SecondarySize", time, (primary_size * 0.45) as f64, &self.expr) as f32;
748 let apply_mode = parse_hotspot_apply_mode(comp, node, time, &self.expr);
749 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
750 let skip = self.process_skip(comp, node, time);
751
752 let mut u = UniformParams::default();
753 u.p[0] = [p_center[0] as f32, p_center[1] as f32, s_center[0] as f32, s_center[1] as f32];
754 u.p[1] = [primary_size, primary_strength, primary_aspect, sec_elements];
755 u.p[2] = [primary_r, primary_g, primary_b, apply_mode as f32];
756 u.p[3] = [sec_strength, sec_size, blend, mask.is_some() as u8 as f32];
757 u.p[4] = [mask_inv as u8 as f32, mbm as u8 as f32, 0.0, 0.0];
758 u.p[5] = skip;
759
760 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
761 let key = self.make_key(
762 node,
763 "HotSpot",
764 src.size,
765 &[src.content_hash, mask_hash],
766 bytemuck::cast_slice(&u.p[..6]),
767 );
768 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
769 stats.cache_hits += 1;
770 return hit;
771 }
772 stats.cache_misses += 1;
773 stats.nodes_evaluated += 1;
774
775 let mut dst = self.alloc_tex_like(&src, src.depth, key);
776 if src.aux.is_some() && dst.size == src.size && dst.origin == src.origin {
777 dst.set_aux(src.aux.clone());
778 }
779 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
780 self.depth_optical_pipelines().borrow_mut().dispatch(
781 &self.device,
782 &self.queue,
783 enc,
784 DepthOpticalOp::HotSpot,
785 &src.view,
786 &self.dummy.view,
787 None,
788 mv,
789 &dst,
790 &u,
791 );
792 self.cache.insert(key, dst.clone(), node.id, frame_i);
793 dst
794 }
795
796 /// 5. `RankFilter`: GPU order-statistic filter (Min / Median / Max / Percentile).
797 #[allow(clippy::too_many_arguments)]
798 pub(super) fn eval_rank_filter(
799 &mut self,
800 comp: &Comp,
801 node: &Node,
802 time: f64,
803 frame_i: i64,
804 enc: &mut wgpu::CommandEncoder,
805 visiting: &mut HashSet<(NodeId, i64)>,
806 stats: &mut EvalStats,
807 ) -> CachedTexture {
808 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
809 return self.dummy.clone();
810 };
811 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
812 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
813 let mbm = self.multiplies_by_mask(comp, node, time);
814 let raw_size = self.eval_num_alias(comp, node, "Size", "FilterSize", time, 1.0).max(0.0);
815 let proxy = self.proxy_scale.max(1) as f32;
816 let radius = (raw_size / proxy).round().clamp(0.0, MAX_RANK_RADIUS);
817 let skip = self.combined_skip(comp, node, time);
818 let all_skipped = skip.iter().all(|&s| s > 0.5);
819 if (blend <= 1e-6 || radius < 0.5 || all_skipped) && !mbm {
820 return src;
821 }
822
823 let src = self.crop_to_canvas(enc, src);
824 let rank = comp.eval_number(node, "Rank", time, 0.5, &self.expr).clamp(0.0, 1.0) as f32;
825 let ftype = parse_rank_filter_type(comp, node, time, &self.expr);
826 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
827
828 let mut u = UniformParams::default();
829 u.p[0] = [radius, rank, ftype as f32, 0.0];
830 u.p[1] = [blend, mask.is_some() as u8 as f32, mask_inv as u8 as f32, mbm as u8 as f32];
831 u.p[2] = skip;
832
833 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
834 let key = self.make_key(
835 node,
836 "RankFilter",
837 src.size,
838 &[src.content_hash, mask_hash],
839 bytemuck::cast_slice(&u.p[..3]),
840 );
841 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
842 stats.cache_hits += 1;
843 return hit;
844 }
845 stats.cache_misses += 1;
846 stats.nodes_evaluated += 1;
847
848 let mut dst = self.alloc_tex_like(&src, src.depth, key);
849 if src.aux.is_some() && dst.size == src.size && dst.origin == src.origin {
850 dst.set_aux(src.aux.clone());
851 }
852 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
853 self.depth_optical_pipelines().borrow_mut().dispatch(
854 &self.device,
855 &self.queue,
856 enc,
857 DepthOpticalOp::RankFilter,
858 &src.view,
859 &self.dummy.view,
860 None,
861 mv,
862 &dst,
863 &u,
864 );
865 self.cache.insert(key, dst.clone(), node.id, frame_i);
866 dst
867 }
868}
869
870#[cfg(test)]
871mod tests {
872 use super::*;
873
874 fn px_at(rgba: &[u8], w: u32, x: u32, y: u32) -> [u8; 4] {
875 let i = ((y * w + x) * 4) as usize;
876 [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]]
877 }
878
879 fn eval_px(eng: &mut Engine, comp: &Comp, name: &str) -> (CachedTexture, Vec<u8>) {
880 let id = comp.find_node(name).unwrap_or_else(|| panic!("missing node {name}"));
881 let (tex, stats) = eng.evaluate(comp, id, 0.0);
882 assert!(stats.unsupported_nodes.is_empty(), "unexpected unsupported: {:?}", stats.unsupported_nodes);
883 let rgba = eng.readback_rgba(&tex).expect("readback rgba");
884 (tex, rgba)
885 }
886
887 fn z_bg_nodes(prefix: &str, w: u32, h: u32, rgba: [f32; 4], z: f32) -> String {
888 format!(
889 r#"
890 {prefix}Col = Background {{
891 Inputs = {{
892 Width = Input {{ Value = {w}, }}, Height = Input {{ Value = {h}, }}, Depth = Input {{ Value = 4, }},
893 TopLeftRed = Input {{ Value = {}, }}, TopLeftGreen = Input {{ Value = {}, }},
894 TopLeftBlue = Input {{ Value = {}, }}, TopLeftAlpha = Input {{ Value = {}, }},
895 }},
896 }},
897 {prefix}Z = Background {{
898 Inputs = {{
899 Width = Input {{ Value = {w}, }}, Height = Input {{ Value = {h}, }}, Depth = Input {{ Value = 4, }},
900 TopLeftRed = Input {{ Value = {z}, }}, TopLeftAlpha = Input {{ Value = 1.0, }},
901 }},
902 }},
903 {prefix}ZAux = Dimension.CopyAux {{
904 Inputs = {{
905 Mode = Input {{ Value = 1, }},
906 Channel = Input {{ Value = FuID {{ "Z" }}, }},
907 Input = Input {{ SourceOp = "{prefix}Z", Source = "Output", }},
908 }},
909 }},
910 {prefix} = ChannelBoolean {{
911 Inputs = {{
912 ToRed = Input {{ Value = 5, }}, ToGreen = Input {{ Value = 6, }},
913 ToBlue = Input {{ Value = 7, }}, ToAlpha = Input {{ Value = 8, }},
914 EnableExtraChannels = Input {{ Value = 1, }}, ToZBuffer = Input {{ Value = 18, }},
915 Background = Input {{ SourceOp = "{prefix}Col", Source = "Output", }},
916 Foreground = Input {{ SourceOp = "{prefix}ZAux", Source = "Output", }},
917 }},
918 }},
919 "#,
920 rgba[0], rgba[1], rgba[2], rgba[3]
921 )
922 }
923
924 #[test]
925 fn depth_blur_aux_z_focal_sharp_far_and_sky_blurred() {
926 let Ok(mut eng) = Engine::new_headless() else { return };
927 // 64x64 sharp vertical stripe across two depth layers:
928 // top half (y<32 in texture = Fusion Y>0.5) has focal z=-5.0, bottom half has far z=-25.0.
929 let src = format!(
930 r#"Composition {{
931 CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }},
932 Tools = ordered() {{
933 {}
934 {}
935 MTop = RectangleMask {{
936 Inputs = {{ Center = Input {{ Value = {{ 0.5, 0.75 }}, }}, Width = Input {{ Value = 1.0, }}, Height = Input {{ Value = 0.5, }}, }},
937 }},
938 MStripe = RectangleMask {{
939 Inputs = {{ Center = Input {{ Value = {{ 0.5, 0.5 }}, }}, Width = Input {{ Value = 0.125, }}, Height = Input {{ Value = 1.0, }}, }},
940 }},
941 White = Background {{
942 Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }},
943 TopLeftRed = Input {{ Value = 1.0, }}, TopLeftGreen = Input {{ Value = 1.0, }}, TopLeftBlue = Input {{ Value = 1.0, }},
944 EffectMask = Input {{ SourceOp = "MStripe", Source = "Mask", }}, }},
945 }},
946 Black = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }},
947 Striped = Merge {{
948 Inputs = {{ Background = Input {{ SourceOp = "Black", Source = "Output", }}, Foreground = Input {{ SourceOp = "White", Source = "Output", }}, }},
949 }},
950 DepthSplit = Merge {{
951 Inputs = {{
952 Background = Input {{ SourceOp = "FarZ", Source = "Output", }},
953 Foreground = Input {{ SourceOp = "NearZ", Source = "Output", }},
954 EffectMask = Input {{ SourceOp = "MTop", Source = "Mask", }},
955 PerformDepthMerge = Input {{ Value = 1, }},
956 }},
957 }},
958 Scene = ChannelBoolean {{
959 Inputs = {{
960 ToRed = Input {{ Value = 5, }}, ToGreen = Input {{ Value = 6, }},
961 ToBlue = Input {{ Value = 7, }}, ToAlpha = Input {{ Value = 8, }},
962 EnableExtraChannels = Input {{ Value = 1, }}, ToZBuffer = Input {{ Value = 18, }},
963 Background = Input {{ SourceOp = "Striped", Source = "Output", }},
964 Foreground = Input {{ SourceOp = "DepthSplit", Source = "Output", }},
965 }},
966 }},
967 DB = DepthBlur {{
968 Inputs = {{
969 Input = Input {{ SourceOp = "Scene", Source = "Output", }},
970 XBlurSize = Input {{ Value = 60.0, }},
971 FocalPoint = Input {{ Value = -5.0, }},
972 DepthOfField = Input {{ Value = 1.0, }},
973 ZScale = Input {{ Value = 20.0, }},
974 }},
975 }},
976 }},
977 }}"#,
978 z_bg_nodes("NearZ", 64, 64, [0.0, 0.0, 0.0, 1.0], -5.0),
979 z_bg_nodes("FarZ", 64, 64, [0.0, 0.0, 0.0, 1.0], -25.0),
980 );
981 let comp = Comp::from_fusion_str(&src).expect("parse DepthBlur aux.z comp");
982 let (tex, px) = eval_px(&mut eng, &comp, "DB");
983 assert!(tex.aux.as_ref().and_then(|a| a.z.as_ref()).is_some(), "DepthBlur must preserve aux.z");
984
985 // Stripe occupies x in [28..36]; check 2px outside stripe edge (x=25):
986 // Near row (y=12) is at focal plane -> stays black (0); Far row (y=52) is out of focus -> blurred (>15)!
987 let near_outside = px_at(&px, 64, 25, 12)[0];
988 let far_outside = px_at(&px, 64, 25, 52)[0];
989 let near_inside = px_at(&px, 64, 32, 12)[0];
990 let far_inside = px_at(&px, 64, 32, 52)[0];
991 assert!(near_outside <= 2, "focal plane outside stripe must stay sharp black, got {near_outside}");
992 assert!(near_inside >= 250, "focal plane inside stripe must stay crisp white, got {near_inside}");
993 assert!(far_outside >= 15, "far depth outside stripe must receive blur bleed, got {far_outside}");
994 assert!(far_inside < near_inside, "far depth inside stripe must soften ({far_inside} vs {near_inside})");
995
996 // Verify EMPTY_Z_SENTINEL (-1e30) in aux.z is treated as far background (full CoC blur).
997 let sky_src = format!(
998 r#"Composition {{
999 CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }},
1000 Tools = ordered() {{
1001 {}
1002 MStripe = RectangleMask {{ Inputs = {{ Center = Input {{ Value = {{ 0.5, 0.5 }}, }}, Width = Input {{ Value = 0.125, }}, Height = Input {{ Value = 1.0, }}, }}, }},
1003 Black = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }},
1004 White = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }},
1005 TopLeftRed = Input {{ Value = 1.0, }}, TopLeftGreen = Input {{ Value = 1.0, }}, TopLeftBlue = Input {{ Value = 1.0, }},
1006 EffectMask = Input {{ SourceOp = "MStripe", Source = "Mask", }}, }}, }},
1007 Striped = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "Black", Source = "Output", }}, Foreground = Input {{ SourceOp = "White", Source = "Output", }}, }}, }},
1008 Scene = ChannelBoolean {{
1009 Inputs = {{
1010 ToRed = Input {{ Value = 5, }}, ToGreen = Input {{ Value = 6, }},
1011 ToBlue = Input {{ Value = 7, }}, ToAlpha = Input {{ Value = 8, }},
1012 EnableExtraChannels = Input {{ Value = 1, }}, ToZBuffer = Input {{ Value = 18, }},
1013 Background = Input {{ SourceOp = "Striped", Source = "Output", }},
1014 Foreground = Input {{ SourceOp = "SkyZ", Source = "Output", }},
1015 }},
1016 }},
1017 DB = DepthBlur {{
1018 Inputs = {{
1019 Input = Input {{ SourceOp = "Scene", Source = "Output", }},
1020 XBlurSize = Input {{ Value = 60.0, }},
1021 FocalPoint = Input {{ Value = -5.0, }},
1022 ZScale = Input {{ Value = 20.0, }},
1023 }},
1024 }},
1025 }},
1026 }}"#,
1027 z_bg_nodes("SkyZ", 64, 64, [0.0, 0.0, 0.0, 1.0], EMPTY_Z_SENTINEL),
1028 );
1029 let sky_comp = Comp::from_fusion_str(&sky_src).expect("parse DepthBlur sky comp");
1030 let (_, sky_px) = eval_px(&mut eng, &sky_comp, "DB");
1031 assert!(px_at(&sky_px, 64, 25, 32)[0] >= 15, "EMPTY_Z_SENTINEL sky must blur as far background");
1032 }
1033
1034 #[test]
1035 fn depth_blur_external_blur_image_and_proxy_scale() {
1036 let Ok(mut eng) = Engine::new_headless() else { return };
1037 // BlurImage has black top half (depth=0, sharp) and white bottom half (depth=1, blurred).
1038 let src = r#"Composition {
1039 CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 },
1040 Tools = ordered() {
1041 MStripe = RectangleMask { Inputs = { Center = Input { Value = { 0.5, 0.5 }, }, Width = Input { Value = 0.125, }, Height = Input { Value = 1.0, }, }, },
1042 Black = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, }, },
1043 Stripe = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, },
1044 TopLeftRed = Input { Value = 1.0, }, TopLeftGreen = Input { Value = 1.0, }, TopLeftBlue = Input { Value = 1.0, },
1045 EffectMask = Input { SourceOp = "MStripe", Source = "Mask", }, }, },
1046 Img = Merge { Inputs = { Background = Input { SourceOp = "Black", Source = "Output", }, Foreground = Input { SourceOp = "Stripe", Source = "Output", }, }, },
1047 MBot = RectangleMask { Inputs = { Center = Input { Value = { 0.5, 0.25 }, }, Width = Input { Value = 1.0, }, Height = Input { Value = 0.5, }, }, },
1048 DepthMap = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, },
1049 TopLeftRed = Input { Value = 1.0, }, TopLeftGreen = Input { Value = 1.0, }, TopLeftBlue = Input { Value = 1.0, },
1050 EffectMask = Input { SourceOp = "MBot", Source = "Mask", }, }, },
1051 DB = DepthBlur {
1052 Inputs = {
1053 Input = Input { SourceOp = "Img", Source = "Output", },
1054 BlurImage = Input { SourceOp = "DepthMap", Source = "Output", },
1055 BlurChannel = Input { Value = 5, },
1056 Filter = Input { Value = 1, },
1057 BlurSize = Input { Value = 72.0, },
1058 FocalPoint = Input { Value = 0.0, },
1059 ZScale = Input { Value = 1.0, },
1060 },
1061 },
1062 },
1063 }"#;
1064 let comp = Comp::from_fusion_str(src).expect("parse DepthBlur BlurImage comp");
1065 let (_, px) = eval_px(&mut eng, &comp, "DB");
1066 assert!(px_at(&px, 64, 24, 12)[0] <= 2, "top half depth=0 must stay sharp");
1067 assert!(px_at(&px, 64, 24, 52)[0] >= 15, "bottom half depth=1 must blur");
1068
1069 eng.proxy_scale = 2;
1070 let (tex_p, px_p) = eval_px(&mut eng, &comp, "DB");
1071 assert_eq!(tex_p.size, [32, 32]);
1072 assert!(px_at(&px_p, 32, 12, 6)[0] <= 2, "proxy top half must stay sharp");
1073 assert!(px_at(&px_p, 32, 12, 26)[0] >= 15, "proxy bottom half must blur");
1074 }
1075
1076 #[test]
1077 fn fog_aux_z_near_far_falloff_alpha_and_fog_image() {
1078 let Ok(mut eng) = Engine::new_headless() else { return };
1079 // Left=near(-2, red), Middle=mid(-16, green), Right=far(-30, blue).
1080 let src = format!(
1081 r#"Composition {{
1082 CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }},
1083 Tools = ordered() {{
1084 {}
1085 {}
1086 {}
1087 MLeft = RectangleMask {{ Inputs = {{ Center = Input {{ Value = {{ 0.16, 0.5 }}, }}, Width = Input {{ Value = 0.34, }}, Height = Input {{ Value = 1.0, }}, }}, }},
1088 MMid = RectangleMask {{ Inputs = {{ Center = Input {{ Value = {{ 0.5, 0.5 }}, }}, Width = Input {{ Value = 0.34, }}, Height = Input {{ Value = 1.0, }}, }}, }},
1089 M1 = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "Far", Source = "Output", }}, Foreground = Input {{ SourceOp = "Mid", Source = "Output", }}, EffectMask = Input {{ SourceOp = "MMid", Source = "Mask", }}, PerformDepthMerge = Input {{ Value = 1, }}, }}, }},
1090 Scene = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "M1", Source = "Output", }}, Foreground = Input {{ SourceOp = "Near", Source = "Output", }}, EffectMask = Input {{ SourceOp = "MLeft", Source = "Mask", }}, PerformDepthMerge = Input {{ Value = 1, }}, }}, }},
1091 FogSolid = Fog {{
1092 Inputs = {{
1093 Input = Input {{ SourceOp = "Scene", Source = "Output", }},
1094 ZNearPlane = Input {{ Value = -2.0, }},
1095 ZFarPlane = Input {{ Value = -30.0, }},
1096 Falloff = Input {{ Value = 1.0, }},
1097 FogRed = Input {{ Value = 1.0, }}, FogGreen = Input {{ Value = 1.0, }}, FogBlue = Input {{ Value = 1.0, }},
1098 }},
1099 }},
1100 TintImg = Background {{ Inputs = {{ Width = Input {{ Value = 32, }}, Height = Input {{ Value = 32, }},
1101 TopLeftRed = Input {{ Value = 0.0, }}, TopLeftGreen = Input {{ Value = 1.0, }}, TopLeftBlue = Input {{ Value = 1.0, }}, }}, }},
1102 FogTex = Fog {{
1103 Inputs = {{
1104 Input = Input {{ SourceOp = "Scene", Source = "Output", }},
1105 Fog = Input {{ SourceOp = "TintImg", Source = "Output", }},
1106 NearPlane = Input {{ Value = -2.0, }},
1107 FarPlane = Input {{ Value = -30.0, }},
1108 }},
1109 }},
1110 EmptySky = Background {{ Inputs = {{ Width = Input {{ Value = 16, }}, Height = Input {{ Value = 16, }}, TopLeftAlpha = Input {{ Value = 0.0, }}, }}, }},
1111 FogSkyZeroA = Fog {{ Inputs = {{ Input = Input {{ SourceOp = "EmptySky", Source = "Output", }}, FogAlpha = Input {{ Value = 0.0, }}, }}, }},
1112 FogSkyFullA = Fog {{ Inputs = {{ Input = Input {{ SourceOp = "EmptySky", Source = "Output", }}, FogAlpha = Input {{ Value = 1.0, }}, FogRed = Input {{ Value = 0.5, }}, FogGreen = Input {{ Value = 0.5, }}, FogBlue = Input {{ Value = 0.5, }}, }}, }},
1113 }},
1114 }}"#,
1115 z_bg_nodes("Near", 32, 32, [1.0, 0.0, 0.0, 1.0], -2.0),
1116 z_bg_nodes("Mid", 32, 32, [0.0, 1.0, 0.0, 1.0], -16.0),
1117 z_bg_nodes("Far", 32, 32, [0.0, 0.0, 1.0, 1.0], -30.0),
1118 );
1119 let comp = Comp::from_fusion_str(&src).expect("parse Fog comp");
1120 let (tex, px) = eval_px(&mut eng, &comp, "FogSolid");
1121 assert!(tex.aux.as_ref().and_then(|a| a.z.as_ref()).is_some(), "Fog must preserve aux.z for chaining");
1122
1123 let near_c = px_at(&px, 32, 4, 16);
1124 let mid_c = px_at(&px, 32, 16, 16);
1125 let far_c = px_at(&px, 32, 28, 16);
1126 assert!(near_c[0] >= 250 && near_c[1] <= 3 && near_c[2] <= 3, "near plane must have 0% fog, got {near_c:?}");
1127 assert!((mid_c[0] as i32 - 128).abs() <= 6 && mid_c[1] >= 250, "mid plane must have ~50% white fog on green, got {mid_c:?}");
1128 assert!(far_c[0] >= 250 && far_c[1] >= 250 && far_c[2] >= 250, "far plane must have 100% white fog, got {far_c:?}");
1129
1130 let (_, px_t) = eval_px(&mut eng, &comp, "FogTex");
1131 let far_t = px_at(&px_t, 32, 28, 16);
1132 assert!(far_t[0] <= 3 && far_t[1] >= 250 && far_t[2] >= 250, "Fog image cyan must replace the far fog color, got {far_t:?}");
1133
1134 let (_, sky0) = eval_px(&mut eng, &comp, "FogSkyZeroA");
1135 assert_eq!(px_at(&sky0, 16, 8, 8)[3], 0, "FogAlpha=0 must keep empty sky transparent");
1136 let (_, sky1) = eval_px(&mut eng, &comp, "FogSkyFullA");
1137 assert!(px_at(&sky1, 16, 8, 8)[3] >= 250 && (px_at(&sky1, 16, 8, 8)[0] as i32 - 128).abs() <= 4);
1138 }
1139
1140 #[test]
1141 fn highlight_thresholds_and_casts_directional_streaks() {
1142 let Ok(mut eng) = Engine::new_headless() else { return };
1143 let src = r#"Composition {
1144 CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 },
1145 Tools = ordered() {
1146 Bg = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, }, },
1147 MBright = RectangleMask { Inputs = { Center = Input { Value = { 0.5, 0.5 }, }, Width = Input { Value = 0.08, }, Height = Input { Value = 0.08, }, }, },
1148 MDim = RectangleMask { Inputs = { Center = Input { Value = { 0.15, 0.15 }, }, Width = Input { Value = 0.1, }, Height = Input { Value = 0.1, }, }, },
1149 Bright = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, },
1150 TopLeftRed = Input { Value = 1.0, }, TopLeftGreen = Input { Value = 1.0, }, TopLeftBlue = Input { Value = 1.0, },
1151 EffectMask = Input { SourceOp = "MBright", Source = "Mask", }, }, },
1152 Dim = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, },
1153 TopLeftRed = Input { Value = 0.3, }, TopLeftGreen = Input { Value = 0.3, }, TopLeftBlue = Input { Value = 0.3, },
1154 EffectMask = Input { SourceOp = "MDim", Source = "Mask", }, }, },
1155 M1 = Merge { Inputs = { Background = Input { SourceOp = "Bg", Source = "Output", }, Foreground = Input { SourceOp = "Dim", Source = "Output", }, }, },
1156 Scene = Merge { Inputs = { Background = Input { SourceOp = "M1", Source = "Output", }, Foreground = Input { SourceOp = "Bright", Source = "Output", }, }, },
1157 HL = Highlight {
1158 Inputs = {
1159 Input = Input { SourceOp = "Scene", Source = "Output", },
1160 Low = Input { Value = 0.6, }, High = Input { Value = 0.9, },
1161 NumberOfPoints = Input { Value = 4, }, Angle = Input { Value = 0.0, },
1162 Length = Input { Value = 0.5, },
1163 GreenScale = Input { Value = 0.7, }, BlueScale = Input { Value = 0.5, },
1164 },
1165 },
1166 HLOnly = Highlight {
1167 Inputs = {
1168 Input = Input { SourceOp = "Scene", Source = "Output", },
1169 Low = Input { Value = 0.6, }, High = Input { Value = 0.9, },
1170 NumberOfPoints = Input { Value = 4, }, Length = Input { Value = 0.5, },
1171 MergeOver = Input { Value = 0, },
1172 },
1173 },
1174 },
1175 }"#;
1176 let comp = Comp::from_fusion_str(src).expect("parse Highlight comp");
1177 let (_, px) = eval_px(&mut eng, &comp, "HL");
1178 // Along +X ray from center (32,32): (40,32) must receive warm tinted streak (R > G > B > 0).
1179 let ray_x = px_at(&px, 64, 40, 32);
1180 let ray_y = px_at(&px, 64, 32, 40);
1181 let off_diag = px_at(&px, 64, 44, 44);
1182 assert!(ray_x[0] >= 20 && ray_x[0] > ray_x[1] && ray_x[1] > ray_x[2], "X ray must glow warm, got {ray_x:?}");
1183 assert!(ray_y[0] >= 20, "Y ray must glow for 4-point star, got {ray_y:?}");
1184 assert!(off_diag[0] <= 2, "off-ray diagonal must stay dark, got {off_diag:?}");
1185
1186 // MergeOver=0 must drop the dim patch (lum=0.3 < Low=0.6).
1187 let (_, px_only) = eval_px(&mut eng, &comp, "HLOnly");
1188 let dim_px = px_at(&px_only, 64, 10, 54);
1189 assert!(dim_px[0] <= 2 && dim_px[1] <= 2 && dim_px[2] <= 2, "dim spot below Low must not highlight, got {dim_px:?}");
1190
1191 eng.proxy_scale = 2;
1192 let (tex_p, px_p) = eval_px(&mut eng, &comp, "HL");
1193 assert_eq!(tex_p.size, [32, 32]);
1194 assert!(px_at(&px_p, 32, 20, 16)[0] >= 15, "proxy Highlight must still streak");
1195 }
1196
1197 #[test]
1198 fn hot_spot_primary_secondary_apply_mode_and_mask() {
1199 let Ok(mut eng) = Engine::new_headless() else { return };
1200 let src = r#"Composition {
1201 CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 },
1202 Tools = ordered() {
1203 Bg = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, },
1204 TopLeftRed = Input { Value = 0.05, }, TopLeftGreen = Input { Value = 0.05, }, TopLeftBlue = Input { Value = 0.05, }, }, },
1205 HS = HotSpot {
1206 Inputs = {
1207 Input = Input { SourceOp = "Bg", Source = "Output", },
1208 Center = Input { Value = { 0.25, 0.25 }, },
1209 SecondaryCenter = Input { Value = { 0.75, 0.75 }, },
1210 PrimarySize = Input { Value = 0.14, },
1211 PrimaryStrength = Input { Value = 1.0, },
1212 PrimaryRed = Input { Value = 1.0, }, PrimaryGreen = Input { Value = 0.5, }, PrimaryBlue = Input { Value = 0.2, },
1213 SecondaryElements = Input { Value = 4, },
1214 ApplyMode = Input { Value = FuID { "Add" }, },
1215 },
1216 },
1217 MLeft = RectangleMask { Inputs = { Center = Input { Value = { 0.25, 0.5 }, }, Width = Input { Value = 0.5, }, Height = Input { Value = 1.0, }, }, },
1218 HSMasked = HotSpot {
1219 Inputs = {
1220 Input = Input { SourceOp = "Bg", Source = "Output", },
1221 Center = Input { Value = { 0.75, 0.5 }, },
1222 PrimarySize = Input { Value = 0.2, },
1223 EffectMask = Input { SourceOp = "MLeft", Source = "Mask", },
1224 },
1225 },
1226 },
1227 }"#;
1228 let comp = Comp::from_fusion_str(src).expect("parse HotSpot comp");
1229 let (_, px) = eval_px(&mut eng, &comp, "HS");
1230 // Primary at Fusion (0.25, 0.25) -> texture pixel (16, 48)
1231 let primary = px_at(&px, 64, 16, 48);
1232 assert!(primary[0] >= 240 && primary[0] > primary[1] && primary[1] > primary[2], "primary core must be bright warm, got {primary:?}");
1233
1234 // Sample along secondary axis (0.5..0.85, 0.5..0.85) vs far off-axis corner (0.85, 0.15 -> px 54, 54).
1235 let mut max_axis = 0u8;
1236 for step in 32..56 {
1237 let y = 63 - step;
1238 let p = px_at(&px, 64, step, y);
1239 max_axis = max_axis.max(p[0]).max(p[1]).max(p[2]);
1240 }
1241 let off_corner = px_at(&px, 64, 56, 56);
1242 assert!(max_axis > off_corner[0] + 20, "secondary elements must brighten optical axis ({max_axis} vs {off_corner:?})");
1243
1244 let (_, px_m) = eval_px(&mut eng, &comp, "HSMasked");
1245 // Center of flare is at x=48 (outside left-half mask) -> must remain background (~13).
1246 assert!(px_at(&px_m, 64, 48, 32)[0] <= 16, "EffectMask must block HotSpot outside mask");
1247 }
1248
1249 #[test]
1250 fn rank_filter_min_median_max_filter_type_channels_and_proxy() {
1251 let Ok(mut eng) = Engine::new_headless() else { return };
1252 // 32x32 mid-gray (0.5) field with a 1px white impulse at center (16,16).
1253 let src = r#"Composition {
1254 CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 },
1255 Tools = ordered() {
1256 Gray = Background { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, },
1257 TopLeftRed = Input { Value = 0.5, }, TopLeftGreen = Input { Value = 0.5, }, TopLeftBlue = Input { Value = 0.5, }, }, },
1258 DotMask = RectangleMask { Inputs = { Center = Input { Value = { 0.515625, 0.484375 }, }, Width = Input { Value = 0.03125, }, Height = Input { Value = 0.03125, }, }, },
1259 White = Background { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, },
1260 TopLeftRed = Input { Value = 1.0, }, TopLeftGreen = Input { Value = 1.0, }, TopLeftBlue = Input { Value = 1.0, },
1261 EffectMask = Input { SourceOp = "DotMask", Source = "Mask", }, }, },
1262 Scene = Merge { Inputs = { Background = Input { SourceOp = "Gray", Source = "Output", }, Foreground = Input { SourceOp = "White", Source = "Output", }, }, },
1263 RMin = RankFilter { Inputs = { Input = Input { SourceOp = "Scene", Source = "Output", }, Size = Input { Value = 1, }, Rank = Input { Value = 0.0, }, }, },
1264 RMed = RankFilter { Inputs = { Input = Input { SourceOp = "Scene", Source = "Output", }, Size = Input { Value = 1, }, Rank = Input { Value = 0.5, }, }, },
1265 RPct = RankFilter { Inputs = { Input = Input { SourceOp = "Scene", Source = "Output", }, Size = Input { Value = 1, }, Rank = Input { Value = 0.9375, }, }, },
1266 RMaxBox = RankFilter { Inputs = { Input = Input { SourceOp = "Scene", Source = "Output", }, Size = Input { Value = 1, }, Rank = Input { Value = 1.0, }, FilterType = Input { Value = 0, }, }, },
1267 RMaxCir = RankFilter { Inputs = { Input = Input { SourceOp = "Scene", Source = "Output", }, Size = Input { Value = 1, }, Rank = Input { Value = 1.0, }, FilterType = Input { Value = 1, }, }, },
1268 RSkipR = RankFilter { Inputs = { Input = Input { SourceOp = "Scene", Source = "Output", }, Size = Input { Value = 1, }, Rank = Input { Value = 1.0, }, ProcessRed = Input { Value = 0, }, }, },
1269 RBig = RankFilter { Inputs = { Input = Input { SourceOp = "Scene", Source = "Output", }, FilterSize = Input { Value = 4, }, Rank = Input { Value = 1.0, }, }, },
1270 },
1271 }"#;
1272 let comp = Comp::from_fusion_str(src).expect("parse RankFilter comp");
1273 let (_, scene_px) = eval_px(&mut eng, &comp, "Scene");
1274 assert!(px_at(&scene_px, 32, 16, 16)[0] >= 250, "sanity: center impulse must be white");
1275
1276 let (_, min_px) = eval_px(&mut eng, &comp, "RMin");
1277 assert!((px_at(&min_px, 32, 16, 16)[0] as i32 - 128).abs() <= 4, "Min must erode 1px white impulse to 0.5");
1278
1279 let (_, med_px) = eval_px(&mut eng, &comp, "RMed");
1280 assert!((px_at(&med_px, 32, 16, 16)[0] as i32 - 128).abs() <= 4, "Median must remove 1px white impulse");
1281
1282 // In 3x3 (9 samples: eight 0.5 + one 1.0), Rank=0.9375 -> pos = 7.5 -> midpoint between 0.5 and 1.0 (~0.75 = 191)!
1283 let (_, pct_px) = eval_px(&mut eng, &comp, "RPct");
1284 assert!((px_at(&pct_px, 32, 16, 16)[0] as i32 - 191).abs() <= 4, "Percentile rank=0.9375 must interpolate to ~191, got {:?}", px_at(&pct_px, 32, 16, 16));
1285
1286 let (_, box_px) = eval_px(&mut eng, &comp, "RMaxBox");
1287 assert!(px_at(&box_px, 32, 17, 17)[0] >= 250, "Max Box(r=1) must dilate impulse to diagonal corner (17,17)");
1288
1289 let (_, cir_px) = eval_px(&mut eng, &comp, "RMaxCir");
1290 assert!(px_at(&cir_px, 32, 17, 16)[0] >= 250, "Max Circle(r=1) must dilate impulse to cardinal neighbor");
1291 assert!((px_at(&cir_px, 32, 17, 17)[0] as i32 - 128).abs() <= 4, "Max Circle(r=1) must exclude diagonal corner");
1292
1293 let (_, skip_px) = eval_px(&mut eng, &comp, "RSkipR");
1294 let n_px = px_at(&skip_px, 32, 17, 16);
1295 assert!((n_px[0] as i32 - 128).abs() <= 4 && n_px[1] >= 250, "ProcessRed=0 must skip R while filtering G: {n_px:?}");
1296
1297 eng.proxy_scale = 2;
1298 let (tex_p, _) = eval_px(&mut eng, &comp, "RBig");
1299 assert_eq!(tex_p.size, [16, 16]);
1300 }
1301
1302 #[test]
1303 fn uniform_ring_growth_reset_trim_and_hdr_float16() {
1304 let Ok(mut eng) = Engine::new_headless() else { return };
1305 {
1306 let mut pipes = eng.depth_optical_pipelines().borrow_mut();
1307 let u = UniformParams::default();
1308 for _ in 0..520 {
1309 pipes.alloc_uniform_slot(&eng.device, &eng.queue, &u);
1310 }
1311 assert_eq!(pipes.uniform_chunks.len(), 2, "520 slots must allocate 2x512 chunks");
1312 pipes.reset_uniform_cursor();
1313 assert_eq!(pipes.uniform_cursor, 0);
1314 pipes.trim_uniform_chunks(1);
1315 assert_eq!(pipes.uniform_chunks.len(), 1);
1316 }
1317
1318 // Verify Float16 HDR compilation & execution across all 5 ops.
1319 let src = r#"Composition {
1320 CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 },
1321 Tools = ordered() {
1322 Bg = Background { Inputs = { Width = Input { Value = 16, }, Height = Input { Value = 16, }, Depth = Input { Value = 3, },
1323 TopLeftRed = Input { Value = 0.8, }, TopLeftGreen = Input { Value = 0.4, }, TopLeftBlue = Input { Value = 0.2, }, }, },
1324 F = Fog { Inputs = { Input = Input { SourceOp = "Bg", Source = "Output", }, FogOpacity = Input { Value = 0.25, }, }, },
1325 H = Highlight { Inputs = { Input = Input { SourceOp = "F", Source = "Output", }, Low = Input { Value = 0.3, }, }, },
1326 S = HotSpot { Inputs = { Input = Input { SourceOp = "H", Source = "Output", }, PrimarySize = Input { Value = 0.3, }, }, },
1327 R = RankFilter { Inputs = { Input = Input { SourceOp = "S", Source = "Output", }, Size = Input { Value = 1, }, Rank = Input { Value = 0.5, }, }, },
1328 D = DepthBlur { Inputs = { Input = Input { SourceOp = "R", Source = "Output", }, BlurChannel = Input { Value = 5, }, BlurSize = Input { Value = 16.0, }, }, },
1329 },
1330 }"#;
1331 let comp = Comp::from_fusion_str(src).expect("parse HDR chain");
1332 let (tex, _) = eval_px(&mut eng, &comp, "D");
1333 assert_eq!(tex.depth, BitDepth::Float16);
1334 }
1335}