1//! Comprehensive tests for DCTL→WGSL transpilation, sandboxed Fusion Lua execution,
2//! real Reactor `.fuse` execution (GPU DCTL + CPU Lua), and `Engine::evaluate` fallback.
3
4use super::dctl::{ParamType, parse_param_block, transpile_dctl_to_wgsl};
5use super::{FuseRegistry, extract_register_class_id};
6use crate::{Engine, EvalStats};
7use model::Comp;
8use std::collections::HashSet;
9use std::path::Path;
10
11#[test]
12fn dctl_param_block_layout_handles_arrays_vectors_and_typedef() {
13 let def = r#"
14 typedef struct {
15 float color[3];
16 int mode;
17 float2 offset;
18 float4 tint;
19 unsigned int flags;
20 } MyParams;
21 "#;
22 let layout = parse_param_block(def).expect("parse param block");
23 assert_eq!(layout.fields.len(), 5);
24 assert_eq!(layout.fields[0].name, "color");
25 assert_eq!(layout.fields[0].array_len, Some(3));
26 assert_eq!(layout.fields[0].offset, 0);
27 assert_eq!(layout.fields[0].size, 12);
28
29 assert_eq!(layout.fields[1].name, "mode");
30 assert_eq!(layout.fields[1].ty, ParamType::I32);
31 assert_eq!(layout.fields[1].offset, 12);
32
33 assert_eq!(layout.fields[2].name, "offset");
34 assert_eq!(layout.fields[2].ty, ParamType::Vec2F);
35 assert_eq!(layout.fields[2].offset, 16);
36
37 assert_eq!(layout.fields[3].name, "tint");
38 assert_eq!(layout.fields[3].ty, ParamType::Vec4F);
39 assert_eq!(layout.fields[3].offset, 32);
40
41 assert_eq!(layout.fields[4].name, "flags");
42 assert_eq!(layout.fields[4].ty, ParamType::U32);
43 assert_eq!(layout.fields[4].offset, 48);
44 assert_eq!(layout.total_size, 64);
45
46 let mut buf = vec![0u8; layout.buffer_size()];
47 layout.write_scalar(&mut buf, "color", Some(0), 0.25);
48 layout.write_scalar(&mut buf, "color", Some(1), 0.50);
49 layout.write_scalar(&mut buf, "color", Some(2), 0.75);
50 layout.write_scalar(&mut buf, "mode", None, 2.0);
51 assert!((layout.read_scalar(&buf, "color", Some(1)).unwrap() - 0.50).abs() < 1e-6);
52 assert_eq!(layout.read_scalar(&buf, "mode", None).unwrap(), 2.0);
53}
54
55#[test]
56fn dctl_transpiler_handles_helpers_intrinsics_swizzles_casts_and_compiles_on_wgpu() {
57 let dctl_src = r#"
58 typedef struct {
59 float gain;
60 float bias[3];
61 int steps;
62 int compOrder;
63 } FullParams;
64
65 __DEVICE__ float3 adjustColor(float3 c, float g, int steps) {
66 for (int i = 0; i < steps; i++) {
67 c.x = _clampf(c.x * g, 0.0f, 1.0f);
68 }
69 float s = _sinf(c.x) + _cosf(c.y) + _tanf(0.1f) + _atan2f(c.y, c.x + 0.01f);
70 float m = _sqrtf(_fabs(s)) + _powf(_fmaxf(c.z, 0.01f), 0.5f);
71 float f = _fmod(m, 1.0f) + _floorf(0.9f) + _ceilf(0.1f);
72 float e = _expf(0.0f) + _logf(1.0f) + _copysignf(0.1f, -1.0f);
73 float k = _saturatef(_mix(0.0f, 1.0f, 0.5f) + _fminf(f, e) * 0.0f);
74 return to_float3(c.x * k, c.y, c.z);
75 }
76
77 __KERNEL__ void FullKernel(__CONSTANTREF__ FullParams *params, __TEXTURE2D__ src, __TEXTURE2D_WRITE__ dst) {
78 DEFINE_KERNEL_ITERATORS_XY(x, y);
79 float4 col = _tex2DVecN(src, x, y, params->compOrder);
80 float4 direct = _tex2DVec4(src, (float)x, (float)y);
81 float3 rgb = swi3(col, x, y, z);
82 float3 bias = to_float3_v(params->bias);
83 rgb = adjustColor(rgb + bias, params->gain, params->steps);
84 float4 outCol = make_float4(rgb.x, rgb.y, rgb.z, direct.w);
85 float4 swizzled = swi4(outCol, x, y, z, w);
86 if (params->steps > 0) {
87 _tex2DVec4Write(dst, x, y, swizzled);
88 } else {
89 _tex2DVec4Write(dst, x, y, to_float4(0.0f, 0.0f, 0.0f, 1.0f));
90 }
91 }
92 "#;
93
94 let transpiled = transpile_dctl_to_wgsl(
95 dctl_src,
96 "FullKernel",
97 Some("FullParams"),
98 None,
99 wgpu::TextureFormat::Rgba8Unorm,
100 )
101 .expect("transpile full DCTL");
102
103 assert!(transpiled.wgsl.contains("@compute @workgroup_size(8, 8)"));
104 assert!(transpiled.wgsl.contains("fn adjustColor("));
105 assert!(transpiled.wgsl.contains("params.gain"));
106 assert!(transpiled.wgsl.contains("((col).xyz)"));
107 assert!(transpiled.wgsl.contains("((outCol).xyzw)"));
108 assert!(transpiled.wgsl.contains("f32(x)"));
109 assert!(transpiled.wgsl.contains("textureStore(dst"));
110 assert_eq!(transpiled.input_textures, vec!["src"]);
111 assert_eq!(transpiled.output_textures, vec!["dst"]);
112
113 #[cfg(not(target_arch = "wasm32"))]
114 if let Ok(eng) = Engine::new_headless() {
115 super::lua_host::compile_dctl_pipeline(
116 eng.device(),
117 &transpiled,
118 wgpu::TextureFormat::Rgba8Unorm,
119 )
120 .expect("WGSL must compile cleanly in wgpu");
121 }
122}
123
124#[cfg(not(target_arch = "wasm32"))]
125#[test]
126fn dctl_multi_input_fuse_executes_on_gpu_and_caches_pipeline() {
127 let Ok(mut eng) = Engine::new_headless() else {
128 return;
129 };
130 let fuse_src = r#"
131FuRegisterClass("BlendMixDctl", CT_Tool, {
132 REG_Name = "BlendMixDctl",
133 REG_OpNoMask = true,
134})
135
136MixParams = [[
137 float mixAmt;
138 float tint[3];
139 int swapRB;
140]]
141
142MixKernel = [[
143__DEVICE__ float3 applyTint(float3 c, float3 t) {
144 c.x *= t.x;
145 c.y *= t.y;
146 c.z *= t.z;
147 return c;
148}
149
150__KERNEL__ void MixKernel(__CONSTANTREF__ MixParams *params, __TEXTURE2D__ srcA, __TEXTURE2D__ srcB, __TEXTURE2D_WRITE__ dst) {
151 DEFINE_KERNEL_ITERATORS_XY(x, y);
152 float4 a = _tex2DVec4(srcA, x, y);
153 float4 b = _tex2DVec4(srcB, x, y);
154 float3 mixed = to_float3(
155 _mix(a.x, b.x, params->mixAmt),
156 _mix(a.y, b.y, params->mixAmt),
157 _mix(a.z, b.z, params->mixAmt)
158 );
159 float3 tint = to_float3_v(params->tint);
160 mixed = applyTint(mixed, tint);
161 if (params->swapRB == 1) {
162 mixed = swi3(mixed, z, y, x);
163 }
164 _tex2DVec4Write(dst, x, y, to_float4(mixed.x, mixed.y, mixed.z, 1.0f));
165}
166]]
167
168function Create()
169 InMix = self:AddInput("Mix", "Mix", { LINKID_DataType = "Number", INP_Default = 0.5 })
170 InTintR = self:AddInput("TintR", "TintR", { LINKID_DataType = "Number", INP_Default = 1.0 })
171 InTintG = self:AddInput("TintG", "TintG", { LINKID_DataType = "Number", INP_Default = 1.0 })
172 InTintB = self:AddInput("TintB", "TintB", { LINKID_DataType = "Number", INP_Default = 1.0 })
173 InSwap = self:AddInput("SwapRB", "SwapRB", { LINKID_DataType = "Number", INP_Default = 0 })
174 InA = self:AddInput("InputA", "InputA", { LINKID_DataType = "Image", LINK_Main = 1 })
175 InB = self:AddInput("InputB", "InputB", { LINKID_DataType = "Image", LINK_Main = 2 })
176 OutImage = self:AddOutput("Output", "Output", { LINKID_DataType = "Image", LINK_Main = 1 })
177end
178
179function Process(req)
180 local a = InA:GetValue(req)
181 local b = InB:GetValue(req)
182 local dst = Image{ IMG_Like = a, IMG_DeferAlloc = true }
183 local node = DVIPComputeNode(req, "MixKernel", MixKernel, "MixParams", MixParams)
184 local params = node:GetParamBlock(MixParams)
185 params.mixAmt = InMix:GetValue(req).Value
186 params.tint[0] = InTintR:GetValue(req).Value
187 params.tint[1] = InTintG:GetValue(req).Value
188 params.tint[2] = InTintB:GetValue(req).Value
189 params.swapRB = InSwap:GetValue(req).Value
190 node:SetParamBlock(params)
191 node:AddInput("srcA", a)
192 node:AddInput("srcB", b)
193 node:AddOutput("dst", dst)
194 local ok = node:RunSession(req)
195 if ok then
196 OutImage:Set(req, dst)
197 end
198end
199"#;
200
201 eng.fuse_registry.register_source("BlendMixDctl", fuse_src);
202 let comp_src = r#"
203Composition {
204 CurrentTime = 0,
205 RenderRange = { 0, 1 },
206 GlobalRange = { 0, 1 },
207 Tools = ordered() {
208 BgA = Background {
209 Inputs = {
210 Width = Input { Value = 16, },
211 Height = Input { Value = 16, },
212 TopLeftRed = Input { Value = 0.8, },
213 TopLeftGreen = Input { Value = 0.2, },
214 TopLeftBlue = Input { Value = 0.0, },
215 TopLeftAlpha = Input { Value = 1.0, },
216 },
217 },
218 BgB = Background {
219 Inputs = {
220 Width = Input { Value = 16, },
221 Height = Input { Value = 16, },
222 TopLeftRed = Input { Value = 0.0, },
223 TopLeftGreen = Input { Value = 0.6, },
224 TopLeftBlue = Input { Value = 1.0, },
225 TopLeftAlpha = Input { Value = 1.0, },
226 },
227 },
228 Mix1 = Fuse.BlendMixDctl {
229 Inputs = {
230 InputA = Input { SourceOp = "BgA", Source = "Output", },
231 InputB = Input { SourceOp = "BgB", Source = "Output", },
232 Mix = Input { Value = 0.5, },
233 TintR = Input { Value = 0.5, },
234 TintG = Input { Value = 1.0, },
235 TintB = Input { Value = 1.0, },
236 SwapRB = Input { Value = 1, },
237 },
238 },
239 },
240}
241"#;
242
243 let comp = Comp::from_fusion_str(comp_src).expect("parse multi-input DCTL comp");
244 let mix_id = comp.find_node("Mix1").unwrap();
245 let (tex, stats) = eng.evaluate(&comp, mix_id, 0.0);
246 assert!(
247 stats.unsupported_nodes.is_empty(),
248 "Fuse.BlendMixDctl should execute natively, got unsupported: {:?}",
249 stats.unsupported_nodes
250 );
251 let rgba = eng.readback_rgba(&tex).expect("readback");
252 // Expected before swap: R = mix(0.8, 0.0, 0.5)*0.5 = 0.20, G = mix(0.2, 0.6, 0.5)*1.0 = 0.40, B = mix(0.0, 1.0, 0.5)*1.0 = 0.50
253 // After SwapRB=1: R = 0.50 (128), G = 0.40 (102), B = 0.20 (51), A = 1.0 (255)
254 assert!((rgba[0] as i32 - 128).abs() <= 2, "R got {}", rgba[0]);
255 assert!((rgba[1] as i32 - 102).abs() <= 2, "G got {}", rgba[1]);
256 assert!((rgba[2] as i32 - 51).abs() <= 2, "B got {}", rgba[2]);
257 assert_eq!(rgba[3], 255);
258 assert!(eng.fuse_registry.pipeline_cache.lock().unwrap().len() >= 1);
259}
260
261#[cfg(not(target_arch = "wasm32"))]
262#[test]
263fn real_reactor_tintensity_fuse_executes_on_gpu() {
264 let tintensity_path = Path::new(
265 "/Library/Application Support/Blackmagic Design/Fusion/Reactor/Deploy/Fuses/Color/Tintensity.fuse",
266 );
267 if !tintensity_path.is_file() {
268 return;
269 }
270 let Ok(mut eng) = Engine::new_headless() else {
271 return;
272 };
273 assert!(
274 eng.fuse_registry.has_fuse("Fuse.Tintensity"),
275 "FuseRegistry::new() should auto-discover Reactor Tintensity.fuse"
276 );
277
278 // Input color: (0.2, 0.4, 0.6, 1.0).
279 // With PreGain=1.5, Red=0.5 (color picker adds color.r * col.r), PostGain=1.0:
280 // After PreGain: (0.3, 0.6, 0.9)
281 // After Color Picker (Red=0.5, Green=0, Blue=0): R = 0.3 + 0.5*0.3 = 0.45, G = 0.6, B = 0.9
282 // Vibrance=0 => EvaluateVibrance adds 0 => (0.45, 0.6, 0.9, 1.0) -> (~115, ~153, ~230, 255)
283 let comp_src = r#"
284Composition {
285 CurrentTime = 0,
286 RenderRange = { 0, 1 },
287 GlobalRange = { 0, 1 },
288 Tools = ordered() {
289 BG = Background {
290 Inputs = {
291 Width = Input { Value = 16, },
292 Height = Input { Value = 16, },
293 TopLeftRed = Input { Value = 0.2, },
294 TopLeftGreen = Input { Value = 0.4, },
295 TopLeftBlue = Input { Value = 0.6, },
296 TopLeftAlpha = Input { Value = 1.0, },
297 },
298 },
299 TnT = Fuse.Tintensity {
300 Inputs = {
301 Image = Input { SourceOp = "BG", Source = "Output", },
302 PreGain = Input { Value = 1.5, },
303 Red = Input { Value = 0.5, },
304 },
305 },
306 },
307}
308"#;
309 let comp = Comp::from_fusion_str(comp_src).expect("parse Tintensity comp");
310 let tnt_id = comp.find_node("TnT").unwrap();
311 let (tex, stats) = eng.evaluate(&comp, tnt_id, 0.0);
312 assert!(
313 stats.unsupported_nodes.is_empty(),
314 "Fuse.Tintensity should execute natively on GPU, got unsupported: {:?}",
315 stats.unsupported_nodes
316 );
317 let rgba = eng.readback_rgba(&tex).expect("readback Tintensity");
318 assert!((rgba[0] as i32 - 115).abs() <= 3, "Tintensity R got {}", rgba[0]);
319 assert!((rgba[1] as i32 - 153).abs() <= 3, "Tintensity G got {}", rgba[1]);
320 assert!((rgba[2] as i32 - 230).abs() <= 3, "Tintensity B got {}", rgba[2]);
321 assert_eq!(rgba[3], 255);
322}
323
324#[cfg(not(target_arch = "wasm32"))]
325#[test]
326fn cpu_lua_fuse_image_pixel_apis_and_sandboxing_work() {
327 let Ok(mut eng) = Engine::new_headless() else {
328 return;
329 };
330 let fuse_src = r#"
331FuRegisterClass("CpuPixelDemo", CT_Tool, {
332 REG_Name = "CpuPixelDemo",
333 REG_TimeVariant = true,
334})
335
336function Create()
337 InBoost = self:AddInput("Boost", "Boost", { LINKID_DataType = "Number", INP_Default = 0.25 })
338 InImg = self:AddInput("Input", "Input", { LINKID_DataType = "Image", LINK_Main = 1 })
339 OutImage = self:AddOutput("Output", "Output", { LINKID_DataType = "Image", LINK_Main = 1 })
340end
341
342function Process(req)
343 -- Verify sandboxing: io and os are unavailable
344 assert(io == nil, "io must be sandboxed")
345 assert(os == nil, "os must be sandboxed")
346
347 -- Verify Matrix4 and ImgRectI APIs
348 local m = Matrix4()
349 m:Identity()
350 m:Move(2, 3, 0)
351 local v = Vector4(1, 2, 0, 1) * m
352 assert(math.abs(v.X - 3) < 1e-6 and math.abs(v.Y - 5) < 1e-6)
353 local r = ImgRectI(0, 0, 8, 8):Intersect(ImgRectI(2, 2, 10, 10))
354 assert(r:Width() == 6 and r:Height() == 6)
355
356 local src = InImg:GetValue(req)
357 local boost = InBoost:GetValue(req).Value
358 local dst = Image({ IMG_Width = src.Width, IMG_Height = src.Height })
359 dst:Fill(Pixel({ R = 0, G = 0, B = 0, A = 1 }))
360 local copy = dst:CopyOf()
361 copy:Clear()
362 local p = Pixel({ R = 0, G = 0, B = 0, A = 1 })
363 for y = 0, src.Height - 1 do
364 for x = 0, src.Width - 1 do
365 src:GetPixel(x, y, p)
366 -- Flip R and B, add boost + frame-time nudge to G
367 local nr = p.B
368 local ng = math.min(1.0, p.G + boost + req.Time * 0.1)
369 local nb = p.R
370 p.R = nr
371 p.G = ng
372 p.B = nb
373 p.A = 1.0
374 copy:SetPixel(x, y, p)
375 end
376 end
377 local rows_seen = 0
378 self:DoMultiProcess(nil, {}, 2, function(y) rows_seen = rows_seen + 1 end)
379 assert(rows_seen == 2)
380 copy:MultiProcessPixels(nil, { delta = 0.0 }, 0, 0, src.Width, src.Height, function(x, y, px)
381 px.G = px.G + delta
382 return px
383 end)
384 OutImage:Set(req, copy)
385end
386"#;
387 eng.fuse_registry.register_source("CpuPixelDemo", fuse_src);
388
389 let comp_src = r#"
390Composition {
391 CurrentTime = 0,
392 RenderRange = { 0, 2 },
393 GlobalRange = { 0, 2 },
394 Tools = ordered() {
395 BG = Background {
396 Inputs = {
397 Width = Input { Value = 16, },
398 Height = Input { Value = 16, },
399 TopLeftRed = Input { Value = 0.2, },
400 TopLeftGreen = Input { Value = 0.3, },
401 TopLeftBlue = Input { Value = 0.8, },
402 TopLeftAlpha = Input { Value = 1.0, },
403 },
404 },
405 Demo = Fuse.CpuPixelDemo {
406 Inputs = {
407 Input = Input { SourceOp = "BG", Source = "Output", },
408 Boost = Input { Value = 0.2, },
409 },
410 },
411 },
412}
413"#;
414 let comp = Comp::from_fusion_str(comp_src).expect("parse CPU Lua comp");
415 let demo_id = comp.find_node("Demo").unwrap();
416
417 // Frame 0: R=0.8 (204), G=0.3+0.2=0.5 (128), B=0.2 (51)
418 let (tex0, stats0) = eng.evaluate(&comp, demo_id, 0.0);
419 assert!(
420 stats0.unsupported_nodes.is_empty(),
421 "CpuPixelDemo failed: {:?}",
422 eng.fuse_registry.last_error
423 );
424 let px0 = eng.readback_rgba(&tex0).expect("readback frame 0");
425 assert!((px0[0] as i32 - 204).abs() <= 2, "R0 got {}", px0[0]);
426 assert!((px0[1] as i32 - 128).abs() <= 2, "G0 got {}", px0[1]);
427 assert!((px0[2] as i32 - 51).abs() <= 2, "B0 got {}", px0[2]);
428
429 // Frame 2: G = 0.3 + 0.2 + 0.2 = 0.7 (179)
430 let (tex2, _) = eng.evaluate(&comp, demo_id, 2.0);
431 let px2 = eng.readback_rgba(&tex2).expect("readback frame 2");
432 assert!((px2[1] as i32 - 179).abs() <= 2, "G2 got {}", px2[1]);
433}
434
435#[cfg(not(target_arch = "wasm32"))]
436#[test]
437fn real_reactor_hexagon_tiles_cpu_lua_matches_native_gpu_shader() {
438 let hex_path = Path::new(
439 "/Library/Application Support/Blackmagic Design/Fusion/Reactor/Deploy/Fuses/Creator/HexagonTiles.fuse",
440 );
441 if !hex_path.is_file() {
442 return;
443 }
444 let Ok(mut eng) = Engine::new_headless() else {
445 return;
446 };
447 assert!(eng.fuse_registry.has_fuse("HexagonTiles"));
448
449 let comp_src = r#"
450Composition {
451 CurrentTime = 0,
452 RenderRange = { 0, 0 },
453 GlobalRange = { 0, 0 },
454 Tools = ordered() {
455 Hex = Fuse.HexagonTiles {
456 Inputs = {
457 Width = Input { Value = 32, },
458 Height = Input { Value = 32, },
459 Size = Input { Value = 4.0, },
460 BorderSize = Input { Value = 2.0, },
461 Red1 = Input { Value = 0.2, },
462 Green1 = Input { Value = 0.4, },
463 Blue1 = Input { Value = 0.8, },
464 Red2 = Input { Value = 0.9, },
465 Green2 = Input { Value = 0.1, },
466 Blue2 = Input { Value = 0.2, },
467 },
468 },
469 },
470}
471"#;
472 let comp = Comp::from_fusion_str(comp_src).expect("parse HexagonTiles comp");
473 let hex_id = comp.find_node("Hex").unwrap();
474
475 // 1. Native fast-path GPU HexagonTiles output
476 let (gpu_tex, _) = eng.evaluate(&comp, hex_id, 0.0);
477 let gpu_rgba = eng.readback_rgba(&gpu_tex).expect("readback GPU HexagonTiles");
478
479 // 2. Real HexagonTiles.fuse executed via sandboxed Lua CPU runtime
480 let mut enc = eng.device().create_command_encoder(&Default::default());
481 let mut visiting = HashSet::new();
482 let mut stats = EvalStats::default();
483 let lua_tex = eng
484 .eval_fuse_by_id(
485 "HexagonTiles",
486 &comp,
487 comp.node(hex_id),
488 0.0,
489 0,
490 [32, 32],
491 &mut enc,
492 &mut visiting,
493 &mut stats,
494 )
495 .expect("HexagonTiles.fuse must succeed via Lua runtime");
496 eng.queue().submit(Some(enc.finish()));
497 let lua_rgba = eng.readback_rgba(&lua_tex).expect("readback Lua HexagonTiles");
498
499 assert_eq!(gpu_rgba.len(), lua_rgba.len());
500 // Allow rare float boundary tie on exact hexagon edge (<= 2% of pixels); interior must match within 2/255.
501 let mut mismatched = 0usize;
502 for (g, l) in gpu_rgba.chunks_exact(4).zip(lua_rgba.chunks_exact(4)) {
503 if (0..4).any(|c| (g[c] as i32 - l[c] as i32).abs() > 2) {
504 mismatched += 1;
505 }
506 }
507 let total = (32 * 32) as usize;
508 assert!(
509 mismatched * 100 <= total * 2,
510 "HexagonTiles.fuse Lua runtime diverged from GPU fast path on {mismatched}/{total} pixels"
511 );
512}
513
514#[cfg(not(target_arch = "wasm32"))]
515#[test]
516fn engine_evaluate_fallback_runs_custom_dctl_and_gracefully_handles_broken_fuses() {
517 let Ok(mut eng) = Engine::new_headless() else {
518 return;
519 };
520 let custom_demo = r#"
521FuRegisterClass("CustomDemoDctl", CT_Tool, { REG_Name = "CustomDemoDctl" })
522DemoParams = [[
523 float scaleR;
524 float addB;
525]]
526DemoKernel = [[
527__KERNEL__ void DemoKernel(__CONSTANTREF__ DemoParams *params, __TEXTURE2D__ src, __TEXTURE2D_WRITE__ dst) {
528 DEFINE_KERNEL_ITERATORS_XY(x, y);
529 float4 c = _tex2DVec4(src, x, y);
530 c.x = _saturatef(c.x * params->scaleR);
531 c.z = _saturatef(c.z + params->addB);
532 _tex2DVec4Write(dst, x, y, c);
533}
534]]
535function Create()
536 InScaleR = self:AddInput("ScaleR", "ScaleR", { LINKID_DataType = "Number", INP_Default = 1.0 })
537 InAddB = self:AddInput("AddB", "AddB", { LINKID_DataType = "Number", INP_Default = 0.0 })
538 InImg = self:AddInput("Input", "Input", { LINKID_DataType = "Image", LINK_Main = 1 })
539 OutImage = self:AddOutput("Output", "Output", { LINKID_DataType = "Image", LINK_Main = 1 })
540end
541function Process(req)
542 local src = InImg:GetValue(req)
543 local dst = Image{ IMG_Like = src, IMG_DeferAlloc = true }
544 local node = DVIPComputeNode(req, "DemoKernel", DemoKernel, "DemoParams", DemoParams)
545 local p = node:GetParamBlock(DemoParams)
546 p.scaleR = InScaleR:GetValue(req).Value
547 p.addB = InAddB:GetValue(req).Value
548 node:SetParamBlock(p)
549 node:AddInput("src", src)
550 node:AddOutput("dst", dst)
551 if node:RunSession(req) then
552 OutImage:Set(req, dst)
553 end
554end
555"#;
556 let broken_dctl = r#"
557FuRegisterClass("BrokenDemoDctl", CT_Tool, {})
558function Create()
559 InImg = self:AddInput("Input", "Input", { LINKID_DataType = "Image", LINK_Main = 1 })
560 OutImage = self:AddOutput("Output", "Output", { LINKID_DataType = "Image", LINK_Main = 1 })
561end
562function Process(req)
563 local src = InImg:GetValue(req)
564 local dst = Image{ IMG_Like = src, IMG_DeferAlloc = true }
565 local node = DVIPComputeNode(req, "Bad", "__KERNEL__ void Bad(__TEXTURE2D__ src, __TEXTURE2D_WRITE__ dst) { this is invalid wgsl syntax ???; }", "P", "")
566 node:AddInput("src", src)
567 node:AddOutput("dst", dst)
568 if node:RunSession(req) then
569 OutImage:Set(req, dst)
570 end
571end
572"#;
573
574 eng.fuse_registry.register_source("CustomDemoDctl", custom_demo);
575 eng.fuse_registry.register_source("BrokenDemoDctl", broken_dctl);
576 assert_eq!(extract_register_class_id(custom_demo).as_deref(), Some("CustomDemoDctl"));
577
578 let comp_src = r#"
579Composition {
580 CurrentTime = 0,
581 RenderRange = { 0, 0 },
582 GlobalRange = { 0, 0 },
583 Tools = ordered() {
584 BG = Background {
585 Inputs = {
586 Width = Input { Value = 16, },
587 Height = Input { Value = 16, },
588 TopLeftRed = Input { Value = 0.25, },
589 TopLeftGreen = Input { Value = 0.50, },
590 TopLeftBlue = Input { Value = 0.10, },
591 TopLeftAlpha = Input { Value = 1.0, },
592 },
593 },
594 Demo = Fuse.CustomDemoDctl {
595 Inputs = {
596 Input = Input { SourceOp = "BG", Source = "Output", },
597 ScaleR = Input { Value = 3.0, },
598 AddB = Input { Value = 0.4, },
599 },
600 },
601 Broken = Fuse.BrokenDemoDctl {
602 Inputs = {
603 Input = Input { SourceOp = "BG", Source = "Output", },
604 },
605 },
606 },
607}
608"#;
609 let comp = Comp::from_fusion_str(comp_src).expect("parse fallback comp");
610
611 // 1. Registered CustomDemoDctl executes on GPU via fallback
612 let (tex, stats) = eng.evaluate(&comp, comp.find_node("Demo").unwrap(), 0.0);
613 assert!(stats.unsupported_nodes.is_empty());
614 let px = eng.readback_rgba(&tex).expect("readback CustomDemoDctl");
615 // R = 0.25*3 = 0.75 (191), G = 0.50 (128), B = 0.10+0.40 = 0.50 (128)
616 assert!((px[0] as i32 - 191).abs() <= 2, "R got {}", px[0]);
617 assert!((px[1] as i32 - 128).abs() <= 2, "G got {}", px[1]);
618 assert!((px[2] as i32 - 128).abs() <= 2, "B got {}", px[2]);
619
620 // 2. Broken Fuse never panics and falls back cleanly to passthrough + unsupported_nodes
621 let (b_tex, b_stats) = eng.evaluate(&comp, comp.find_node("Broken").unwrap(), 0.0);
622 assert!(
623 b_stats.unsupported_nodes.iter().any(|s| s == "Fuse.BrokenDemoDctl"),
624 "broken fuse should be recorded in unsupported_nodes: {:?}",
625 b_stats.unsupported_nodes
626 );
627 let b_px = eng.readback_rgba(&b_tex).expect("readback passthrough");
628 assert!((b_px[0] as i32 - 64).abs() <= 2, "passthrough R got {}", b_px[0]);
629 assert!((b_px[1] as i32 - 128).abs() <= 2, "passthrough G got {}", b_px[1]);
630
631 // 3. FuseRegistry::empty() starts empty
632 let empty_reg = FuseRegistry::empty();
633 assert!(empty_reg.is_empty());
634}