1"""Seeded randomized DAG fuzzer: graph model, Lua emission, and random graph generation."""
2
3import random
4from dataclasses import dataclass, field
5from typing import Any, Dict, List, Optional, Tuple
6
7from .assets import linear_spline, lut_bezier, make_loader, step_spline
8
9@dataclass
10class MaskNodeSpec:
11 name: str
12 kind: str # EllipseMask | RectangleMask | PolylineMask
13 params: Dict[str, Any]
14 paint_mode: Optional[str] = None
15 prev_mask: Optional[str] = None
16
17
18@dataclass
19class MaskChainSpec:
20 nodes: List[MaskNodeSpec]
21 apply_inverted: int = 0
22 multiply_by_mask: int = 0
23
24 def output_name(self) -> str:
25 return self.nodes[-1].name
26
27
28@dataclass
29class SplineParam:
30 spline_name: str
31 kind: str # step | linear | expr_num | expr_pt
32 keyframes: Optional[Dict[int, float]] = None
33 expr_inputs: Optional[Dict[str, Any]] = None
34
35 def eval_at(self, frame: int) -> Any:
36 if self.kind in ("step", "linear") and self.keyframes:
37 pts = sorted(self.keyframes.items())
38 if frame <= pts[0][0]:
39 return pts[0][1]
40 if frame >= pts[-1][0]:
41 return pts[-1][1]
42 for (f0, v0), (f1, v1) in zip(pts, pts[1:]):
43 if f0 <= frame <= f1:
44 if self.kind == "step" or f1 == f0:
45 return v0
46 t = (frame - f0) / (f1 - f0)
47 return round(v0 + (v1 - v0) * t, 5)
48 return 0.5
49
50
51@dataclass
52class DagNode:
53 name: str
54 kind: str
55 is_source: bool
56 primary_port: Optional[str] = None
57 primary_src: Optional[str] = None
58 secondary_port: Optional[str] = None
59 secondary_src: Optional[str] = None
60 params: Dict[str, Any] = field(default_factory=dict)
61 raw_inputs: List[str] = field(default_factory=list)
62 aux_templates: List[str] = field(default_factory=list)
63 source_op: Optional[str] = None
64 mask: Optional[MaskChainSpec] = None
65 loader_path: Optional[str] = None
66 loader_post_mult: int = 1
67
68
69def _fmt_val(v: Any, prefix: str, frame_shift: int) -> Tuple[str, List[str]]:
70 """Formats a Fusion Input value and returns (lua_rhs, extra_aux_defs)."""
71 if isinstance(v, SplineParam):
72 sname = f"{prefix}{v.spline_name}"
73 if v.kind == "step" and v.keyframes is not None:
74 shifted = {k + frame_shift: val for k, val in v.keyframes.items()}
75 return f'Input {{ SourceOp = "{sname}", Source = "Value", }}', [step_spline(sname, shifted)]
76 if v.kind == "linear" and v.keyframes is not None:
77 shifted = {k + frame_shift: val for k, val in v.keyframes.items()}
78 return f'Input {{ SourceOp = "{sname}", Source = "Value", }}', [linear_spline(sname, shifted)]
79 if v.kind in ("expr_num", "expr_pt") and v.expr_inputs is not None:
80 src_port = "NumberResult" if v.kind == "expr_num" else "PointResult"
81 lines = []
82 for ek, ev in v.expr_inputs.items():
83 if isinstance(ev, str):
84 lines.append(f'{ek} = Input {{ Value = "{ev}", }},')
85 elif isinstance(ev, tuple):
86 lines.append(f"{ek} = Input {{ Value = {{ {ev[0]}, {ev[1]} }}, }},")
87 else:
88 lines.append(f"{ek} = Input {{ Value = {ev}, }},")
89 expr_def = f"\t\t{sname} = Expression {{\n\t\t\tInputs = {{\n\t\t\t\t" + "\n\t\t\t\t".join(lines) + "\n\t\t\t},\n\t\t},"
90 return f'Input {{ SourceOp = "{sname}", Source = "{src_port}", }}', [expr_def]
91 if isinstance(v, tuple) and len(v) == 2 and v[0] == "FuID":
92 return f'Input {{ Value = FuID {{ "{v[1]}" }}, }}', []
93 if isinstance(v, tuple) and len(v) == 2:
94 return f"Input {{ Value = {{ {v[0]}, {v[1]} }}, }}", []
95 if isinstance(v, str):
96 return f'Input {{ Value = "{v}", }}', []
97 return f"Input {{ Value = {v}, }}", []
98
99
100@dataclass
101class FuzzGraph:
102 seed: int
103 eval_frame: int
104 nodes: List[DagNode]
105
106 def clone(self) -> "FuzzGraph":
107 import copy
108 return copy.deepcopy(self)
109
110 def output_node(self) -> str:
111 return self.nodes[-1].name
112
113 def active_cone_set(self, target_name: str) -> set:
114 by_name = {n.name: n for n in self.nodes}
115 seen = set()
116 stack = [target_name]
117 while stack:
118 cur = stack.pop()
119 if cur in seen or cur not in by_name:
120 continue
121 seen.add(cur)
122 nd = by_name[cur]
123 if nd.primary_src:
124 stack.append(nd.primary_src)
125 if nd.secondary_src:
126 stack.append(nd.secondary_src)
127 if nd.source_op:
128 stack.append(nd.source_op)
129 return seen
130
131 def prune_to(self, target_name: str) -> "FuzzGraph":
132 g = self.clone()
133 cone = g.active_cone_set(target_name)
134 g.nodes = [n for n in g.nodes if n.name in cone]
135 return g
136
137 def bypass_node(self, node_name: str) -> Optional["FuzzGraph"]:
138 g = self.clone()
139 target = next((n for n in g.nodes if n.name == node_name), None)
140 if target is None or target.is_source or target.primary_src is None:
141 return None
142 if any(n.source_op == node_name for n in g.nodes if n.name != node_name):
143 return None
144 repl = target.primary_src
145 for n in g.nodes:
146 if n.primary_src == node_name:
147 n.primary_src = repl
148 if n.secondary_src == node_name:
149 n.secondary_src = repl
150 g.nodes = [n for n in g.nodes if n.name != node_name]
151 if not g.nodes:
152 return None
153 return g.prune_to(g.nodes[-1].name)
154
155 def strip_mask(self, node_name: str) -> Optional["FuzzGraph"]:
156 g = self.clone()
157 for n in g.nodes:
158 if n.name == node_name and n.mask is not None:
159 n.mask = None
160 return g
161 return None
162
163 def flatten_splines(self) -> Optional["FuzzGraph"]:
164 g = self.clone()
165 changed = False
166 for n in g.nodes:
167 for k, v in list(n.params.items()):
168 if isinstance(v, SplineParam):
169 changed = True
170 if v.kind in ("step", "linear"):
171 n.params[k] = v.eval_at(g.eval_frame)
172 elif v.kind == "expr_num":
173 n.params[k] = 0.75
174 else:
175 n.params[k] = (0.45, 0.55)
176 return g if changed else None
177
178 def summary_tools(self) -> List[Dict[str, Any]]:
179 out = []
180 for n in self.nodes:
181 p_short = {}
182 for k, v in n.params.items():
183 if isinstance(v, SplineParam):
184 p_short[k] = f"<{v.kind}>"
185 elif isinstance(v, tuple) and len(v) == 2 and v[0] == "FuID":
186 p_short[k] = v[1]
187 else:
188 p_short[k] = v
189 entry: Dict[str, Any] = {"name": n.name, "kind": n.kind, "params": p_short}
190 if n.mask is not None:
191 entry["mask"] = [m.kind for m in n.mask.nodes]
192 out.append(entry)
193 return out
194
195 def to_lua_defs(self, prefix: str = "", frame_shift: int = 0) -> Tuple[List[str], List[str], str]:
196 """Emits (tool_blocks, aux_splines_or_exprs, final_output_name)."""
197 tool_blocks: List[str] = []
198 aux_blocks: List[str] = []
199
200 for n in self.nodes:
201 full_name = f"{prefix}{n.name}"
202 if n.kind == "Loader":
203 assert n.loader_path is not None
204 tool_blocks.append(make_loader(full_name, n.loader_path, post_mult=n.loader_post_mult))
205 continue
206
207 # Emit mask chain if present
208 if n.mask is not None:
209 for mi, mn in enumerate(n.mask.nodes):
210 mname = f"{prefix}{mn.name}"
211 in_lines = []
212 if mn.prev_mask:
213 in_lines.append(f'EffectMask = Input {{ SourceOp = "{prefix}{mn.prev_mask}", Source = "Mask", }},')
214 if mn.paint_mode:
215 in_lines.append(f'PaintMode = Input {{ Value = FuID {{ "{mn.paint_mode}" }}, }},')
216 for pk, pv in mn.params.items():
217 if pk == "Polyline":
218 in_lines.append(pv)
219 else:
220 rhs, extra = _fmt_val(pv, prefix, frame_shift)
221 in_lines.append(f"{pk} = {rhs},")
222 aux_blocks.extend(extra)
223 tool_blocks.append(
224 f"\t\t{mname} = {mn.kind} {{\n\t\t\tInputs = {{\n\t\t\t\t"
225 + "\n\t\t\t\t".join(in_lines)
226 + "\n\t\t\t},\n\t\t},"
227 )
228
229 in_lines = []
230 if n.primary_port and n.primary_src:
231 in_lines.append(f'{n.primary_port} = Input {{ SourceOp = "{prefix}{n.primary_src}", Source = "Output", }},')
232 if n.secondary_port and n.secondary_src:
233 in_lines.append(f'{n.secondary_port} = Input {{ SourceOp = "{prefix}{n.secondary_src}", Source = "Output", }},')
234 if n.mask is not None:
235 in_lines.append(f'EffectMask = Input {{ SourceOp = "{prefix}{n.mask.output_name()}", Source = "Mask", }},')
236 if n.mask.apply_inverted:
237 in_lines.append("ApplyMaskInverted = Input { Value = 1, },")
238 if n.mask.multiply_by_mask:
239 in_lines.append("MultiplyByMask = Input { Value = 1, },")
240
241 for pk, pv in n.params.items():
242 rhs, extra = _fmt_val(pv, prefix, frame_shift)
243 in_lines.append(f"{pk} = {rhs},")
244 aux_blocks.extend(extra)
245 for ri in n.raw_inputs:
246 in_lines.append(ri.replace("{pfx}", prefix))
247 for tmpl in n.aux_templates:
248 aux_blocks.append(tmpl.replace("{pfx}", prefix))
249
250 src_op_line = f'\t\t\tSourceOp = "{prefix}{n.source_op}",\n' if n.source_op else ""
251 tool_blocks.append(
252 f"\t\t{full_name} = {n.kind} {{\n{src_op_line}\t\t\tInputs = {{\n\t\t\t\t"
253 + "\n\t\t\t\t".join(in_lines)
254 + "\n\t\t\t},\n\t\t},"
255 )
256
257 return tool_blocks, aux_blocks, f"{prefix}{self.nodes[-1].name}"
258
259
260def _gen_mask_chain(rng: random.Random, tag: str) -> MaskChainSpec:
261 def one_mask(name: str, prev: Optional[str]) -> MaskNodeSpec:
262 kind = rng.choice(["EllipseMask", "RectangleMask", "PolylineMask"])
263 soft = rng.choice([0.0, 0.015, 0.04, 0.09])
264 inv = rng.choice([0, 0, 1])
265 lvl = round(rng.uniform(0.55, 1.0), 3)
266 params: Dict[str, Any] = {
267 "MaskWidth": 256,
268 "MaskHeight": 256,
269 "SoftEdge": soft,
270 "Invert": inv,
271 "Level": lvl,
272 }
273 if kind in ("EllipseMask", "RectangleMask"):
274 params["Center"] = (round(rng.uniform(0.3, 0.7), 3), round(rng.uniform(0.3, 0.7), 3))
275 params["Width"] = round(rng.uniform(0.25, 0.65), 3)
276 params["Height"] = round(rng.uniform(0.25, 0.65), 3)
277 params["Angle"] = round(rng.uniform(-45.0, 45.0), 1)
278 if kind == "RectangleMask" and rng.random() < 0.4:
279 params["CornerRadius"] = round(rng.uniform(0.1, 0.4), 2)
280 if rng.random() < 0.25:
281 params["Solid"] = 0
282 params["BorderWidth"] = round(rng.uniform(0.02, 0.06), 3)
283 else:
284 x0 = round(rng.uniform(-0.35, -0.1), 3)
285 y0 = round(rng.uniform(-0.35, -0.1), 3)
286 x1 = round(rng.uniform(0.1, 0.35), 3)
287 y1 = round(rng.uniform(-0.3, 0.05), 3)
288 y2 = round(rng.uniform(0.15, 0.38), 3)
289 params["Polyline"] = (
290 f"Polyline = Input {{ Value = Polyline {{ Closed = true, Points = {{ "
291 f"{{ Linear = true, X = {x0}, Y = {y0} }}, "
292 f"{{ Linear = true, X = {x1}, Y = {y1} }}, "
293 f"{{ Linear = true, X = 0.0, Y = {y2} }} }} }}, }},"
294 )
295 pm = (
296 rng.choice(["Merge", "Add", "Subtract", "Minimum", "Maximum", "Average", "Multiply", "Replace", "Invert", "Ignore"])
297 if prev
298 else None
299 )
300 return MaskNodeSpec(name=name, kind=kind, params=params, paint_mode=pm, prev_mask=prev)
301
302 m0 = one_mask(f"{tag}_M0", None)
303 chain = [m0]
304 if rng.random() < 0.45:
305 chain.append(one_mask(f"{tag}_M1", m0.name))
306 return MaskChainSpec(
307 nodes=chain,
308 apply_inverted=1 if rng.random() < 0.3 else 0,
309 multiply_by_mask=1 if rng.random() < 0.25 else 0,
310 )
311
312
313def generate_random_dag(seed: int, assets: Dict[str, str], deterministic: bool = True) -> FuzzGraph:
314 """Csmith-style seeded generator producing valid 4-9 node Fusion DAGs."""
315 rng = random.Random(seed)
316 eval_frame = rng.choice([0, 1, 2])
317 nodes: List[DagNode] = []
318
319 def make_source(idx: int) -> DagNode:
320 name = f"S{idx}"
321 src_pool = ["Loader", "Loader", "Background", "Plasma", "sRender", "DaySky"]
322 if not deterministic:
323 src_pool.append("FastNoise")
324 stype = rng.choice(src_pool)
325 if stype == "Loader":
326 plate = rng.choice(["color", "fg", "small", "bump"])
327 pm = rng.choice([1, 1, 0])
328 return DagNode(name=name, kind="Loader", is_source=True, loader_path=assets[plate], loader_post_mult=pm)
329 if stype == "Background":
330 btype = rng.choice(["Solid", "Horizontal", "Vertical", "Corner"])
331 p: Dict[str, Any] = {
332 "Width": 256,
333 "Height": 256,
334 "Type": ("FuID", btype),
335 "TopLeftRed": round(rng.uniform(0.05, 0.95), 3),
336 "TopLeftGreen": round(rng.uniform(0.05, 0.95), 3),
337 "TopLeftBlue": round(rng.uniform(0.05, 0.95), 3),
338 "TopLeftAlpha": round(rng.uniform(0.4, 1.0), 3),
339 }
340 if btype != "Solid":
341 p["TopRightRed"] = round(rng.uniform(0.05, 0.95), 3)
342 p["TopRightGreen"] = round(rng.uniform(0.05, 0.95), 3)
343 p["TopRightBlue"] = round(rng.uniform(0.05, 0.95), 3)
344 p["BottomLeftRed"] = round(rng.uniform(0.05, 0.95), 3)
345 p["BottomLeftGreen"] = round(rng.uniform(0.05, 0.95), 3)
346 p["BottomLeftBlue"] = round(rng.uniform(0.05, 0.95), 3)
347 if rng.random() < 0.35:
348 p["Depth"] = rng.choice([1, 3, 4])
349 return DagNode(name=name, kind="Background", is_source=True, params=p)
350 if stype == "sRender":
351 shape_mode = rng.choice(["sNGon", "sGrid", "sBoolean", "sOutline"])
352 aux: List[str] = []
353 c_r, c_g, c_b = round(rng.uniform(0.2, 1.0), 2), round(rng.uniform(0.2, 1.0), 2), round(rng.uniform(0.2, 1.0), 2)
354 base_el = f"{{pfx}}{name}_ShapeA"
355 prim = rng.choice(["sNGon", "sRectangle", "sEllipse"])
356 extra_shape = "Sides = Input { Value = " + str(rng.randint(3, 8)) + ", }," if prim == "sNGon" else ""
357 aux.append(
358 f"\t\t{base_el} = {prim} {{\n\t\t\tInputs = {{\n"
359 f"\t\t\t\tWidth = Input {{ Value = {round(rng.uniform(0.18, 0.45), 2)}, }},\n"
360 f"\t\t\t\tHeight = Input {{ Value = {round(rng.uniform(0.18, 0.45), 2)}, }},\n"
361 f"\t\t\t\tRed = Input {{ Value = {c_r}, }}, Green = Input {{ Value = {c_g}, }}, Blue = Input {{ Value = {c_b}, }},\n"
362 + (f"\t\t\t\t{extra_shape}\n" if extra_shape else "")
363 + "\t\t\t},\n\t\t},"
364 )
365 head_shape = base_el
366 if shape_mode == "sGrid":
367 grid_n = f"{{pfx}}{name}_Grid"
368 aux.append(
369 f"\t\t{grid_n} = sGrid {{\n\t\t\tInputs = {{\n"
370 f'\t\t\t\tInput = Input {{ SourceOp = "{base_el}", Source = "Output", }},\n'
371 f"\t\t\t\tCellsX = Input {{ Value = {rng.randint(2, 4)}, }}, CellsY = Input {{ Value = {rng.randint(2, 3)}, }},\n"
372 f"\t\t\t\tXOffset = Input {{ Value = {round(rng.uniform(0.15, 0.28), 2)}, }}, YOffset = Input {{ Value = {round(rng.uniform(0.15, 0.28), 2)}, }},\n"
373 "\t\t\t},\n\t\t},"
374 )
375 head_shape = grid_n
376 elif shape_mode == "sBoolean":
377 b_el = f"{{pfx}}{name}_ShapeB"
378 bool_n = f"{{pfx}}{name}_Bool"
379 bop = rng.choice(["Union", "Intersection", "Subtract", "Xor"])
380 aux.append(
381 f"\t\t{b_el} = sEllipse {{\n\t\t\tInputs = {{\n"
382 f"\t\t\t\t[\"Translate.X\"] = Input {{ Value = {round(rng.uniform(-0.12, 0.12), 2)}, }},\n"
383 f"\t\t\t\tWidth = Input {{ Value = 0.32, }}, Height = Input {{ Value = 0.32, }},\n"
384 "\t\t\t},\n\t\t},"
385 )
386 aux.append(
387 f"\t\t{bool_n} = sBoolean {{\n\t\t\tInputs = {{\n"
388 f'\t\t\t\tOperation = Input {{ Value = FuID {{ "{bop}" }}, }},\n'
389 f'\t\t\t\tInput1 = Input {{ SourceOp = "{base_el}", Source = "Output", }},\n'
390 f'\t\t\t\tInput2 = Input {{ SourceOp = "{b_el}", Source = "Output", }},\n'
391 "\t\t\t},\n\t\t},"
392 )
393 head_shape = bool_n
394 elif shape_mode == "sOutline":
395 ol_n = f"{{pfx}}{name}_Outline"
396 aux.append(
397 f"\t\t{ol_n} = sOutline {{\n\t\t\tInputs = {{\n"
398 f'\t\t\t\tInput = Input {{ SourceOp = "{base_el}", Source = "Output", }},\n'
399 f"\t\t\t\tThickness = Input {{ Value = {round(rng.uniform(0.015, 0.04), 3)}, }},\n"
400 "\t\t\t},\n\t\t},"
401 )
402 head_shape = ol_n
403 p_sr: Dict[str, Any] = {"Width": 256, "Height": 256}
404 if rng.random() < 0.3:
405 p_sr["Depth"] = rng.choice([3, 4])
406 return DagNode(
407 name=name,
408 kind="sRender",
409 is_source=True,
410 params=p_sr,
411 raw_inputs=[f'Input = Input {{ SourceOp = "{head_shape}", Source = "Output", }},'],
412 aux_templates=aux,
413 )
414 if stype == "DaySky":
415 p_ds: Dict[str, Any] = {
416 "Width": 256,
417 "Height": 256,
418 "Latitude": round(rng.uniform(10.0, 52.0), 1),
419 "Longitude": round(rng.uniform(-60.0, 60.0), 1),
420 "Month": ("FuID", rng.choice(["January", "March", "June", "September"])),
421 "Time": round(rng.uniform(8.0, 17.0), 2),
422 "Turbidity": round(rng.uniform(0.0, 0.8), 2),
423 "Exposure": round(rng.uniform(0.7, 2.0), 2),
424 }
425 if rng.random() < 0.3:
426 p_ds["Depth"] = rng.choice([3, 4])
427 return DagNode(name=name, kind="DaySky", is_source=True, params=p_ds)
428 if stype == "FastNoise":
429 return DagNode(
430 name=name,
431 kind="FastNoise",
432 is_source=True,
433 params={
434 "Width": 256,
435 "Height": 256,
436 "Detail": round(rng.uniform(0.5, 6.0), 2),
437 "Contrast": round(rng.uniform(0.4, 2.2), 2),
438 "Brightness": round(rng.uniform(-0.3, 0.3), 2),
439 "XScale": round(rng.uniform(2.0, 18.0), 2),
440 "YScale": round(rng.uniform(2.0, 18.0), 2),
441 "Seethe": round(rng.uniform(0.0, 50.0), 2),
442 "Discontinuous": rng.choice([0, 1]),
443 "Color1Alpha": 1,
444 },
445 )
446 return DagNode(
447 name=name,
448 kind="Plasma",
449 is_source=True,
450 params={
451 "Width": 256,
452 "Height": 256,
453 "Phase": round(rng.uniform(0.0, 1.0), 3),
454 "Scale": round(rng.uniform(0.6, 2.5), 2),
455 },
456 )
457
458 num_sources = rng.choice([1, 2, 2])
459 for si in range(num_sources):
460 nodes.append(make_source(si))
461
462 op_pool = [
463 "Transform", "Merge", "Dissolve", "Switch",
464 "BrightnessContrast", "ColorCorrector", "ColorGain", "HueCurves",
465 "ChannelBoolean", "Blur", "Glow", "SoftGlow", "DirectionalBlur",
466 "DVE", "CornerPositioner", "PerspectivePositioner", "Displace", "Vortex", "Drip", "Dent",
467 "Paint", "ChangeDepth", "GamutConvert", "Custom",
468 ]
469 num_internal = rng.randint(4, 9)
470 has_anim = rng.random() < 0.30
471 has_inf_edges = False
472
473 for ni in range(num_internal):
474 nname = f"N{ni}"
475 kind = rng.choice(op_pool)
476 if kind == "Drip" and has_inf_edges:
477 kind = "Dent"
478 # Prefer chaining mostly from recent nodes while allowing DAG forks from earlier nodes
479 avail = [n.name for n in nodes]
480 src_a = avail[-1] if rng.random() < 0.65 else rng.choice(avail)
481 src_b = rng.choice(avail)
482
483 # Occasional SourceOp instancing from an existing unary color node
484 inst_cands = [n for n in nodes if not n.is_source and n.kind in ("BrightnessContrast", "ColorCorrector", "ColorGain") and n.source_op is None]
485 if inst_cands and rng.random() < 0.10:
486 proto = rng.choice(inst_cands)
487 nodes.append(
488 DagNode(
489 name=nname,
490 kind=proto.kind,
491 is_source=False,
492 primary_port="Input",
493 primary_src=src_a,
494 params={"Blend": round(rng.uniform(0.5, 1.0), 2)},
495 source_op=proto.name,
496 )
497 )
498 continue
499
500 mask = _gen_mask_chain(rng, nname) if (kind not in ("ChangeDepth", "Switch") and rng.random() < 0.32) else None
501 blend = round(rng.uniform(0.55, 1.0), 2) if rng.random() < 0.25 else 1.0
502
503 prim_port = "Input"
504 sec_port: Optional[str] = None
505 sec_src: Optional[str] = None
506 params: Dict[str, Any] = {}
507 raw_inputs: List[str] = []
508 aux_templates: List[str] = []
509
510 if kind == "Transform":
511 ang: Any = round(rng.uniform(-45.0, 45.0), 1)
512 if has_anim and ni == 0:
513 ang = SplineParam(f"{nname}_Ang", "linear", keyframes={0: -15.0, 2: 35.0})
514 ed_val = rng.choice([0, 1, 2, 3])
515 if ed_val in (1, 3):
516 has_inf_edges = True
517 params = {
518 "Center": (round(rng.uniform(0.32, 0.68), 3), round(rng.uniform(0.32, 0.68), 3)),
519 "Pivot": (round(rng.uniform(0.25, 0.75), 3), round(rng.uniform(0.25, 0.75), 3)),
520 "Size": round(rng.uniform(0.65, 1.35), 3),
521 "Aspect": round(rng.uniform(0.75, 1.35), 3),
522 "Angle": ang,
523 "Edges": ed_val,
524 "Blend": blend,
525 }
526 elif kind == "Merge":
527 prim_port = "Background"
528 sec_port = "Foreground"
529 sec_src = src_b
530 m_edges = rng.choice([0, 1, 2, 3]) if rng.random() < 0.3 else 0
531 if m_edges in (1, 3):
532 has_inf_edges = True
533 params = {
534 "ApplyMode": ("FuID", rng.choice([
535 "Normal", "Screen", "Multiply", "Dissolve", "Darken", "Lighten",
536 "Difference", "Exclusion", "Overlay", "Hard Light", "Soft Light",
537 "LinearLight", "Color Dodge", "LinearDodge", "VividLight", "Hypotenuse",
538 "DarkerColor", "LighterColor", "PinLight", "Color Burn", "LinearBurn",
539 "Geometric", "Hue", "Saturation", "Color", "Luminosity",
540 ])),
541 "Operator": ("FuID", rng.choice(["Over", "Over", "Under", "In", "Held Out", "Atop", "XOr", "Conjoint", "Disjoint"])),
542 "Size": round(rng.uniform(0.55, 1.15), 3),
543 "Angle": round(rng.uniform(-25.0, 25.0), 1),
544 "Center": (round(rng.uniform(0.35, 0.65), 3), round(rng.uniform(0.35, 0.65), 3)),
545 "Gain": round(rng.uniform(0.35, 1.25), 2),
546 "SubtractiveAdditive": rng.choice([0.0, 0.5, 1.0]),
547 "BurnIn": round(rng.uniform(0.0, 0.4), 2) if rng.random() < 0.35 else 0.0,
548 "Edges": m_edges,
549 "PerformDepthMerge": 0,
550 "Blend": blend,
551 }
552 elif kind == "Switch":
553 prim_port = "Input0"
554 sec_port = "Input1"
555 sec_src = src_b
556 params = {"Source": rng.choice([0, 1])}
557 elif kind == "Dissolve":
558 prim_port = "Background"
559 sec_port = "Foreground"
560 sec_src = src_b
561 params = {"Mix": round(rng.uniform(0.2, 0.85), 2), "Blend": blend}
562 elif kind == "BrightnessContrast":
563 g_val: Any = round(rng.uniform(0.5, 2.2), 2)
564 if has_anim and ni == 1:
565 g_val = SplineParam(
566 f"{nname}_ExprG",
567 "expr_num",
568 expr_inputs={"n1": round(rng.uniform(0.6, 1.6), 2), "NumberExpression": "n1 * 0.8 + 0.35"},
569 )
570 params = {
571 "Gain": g_val,
572 "Lift": round(rng.uniform(-0.15, 0.2), 2),
573 "Gamma": round(rng.uniform(0.6, 1.6), 2),
574 "Contrast": round(rng.uniform(-0.25, 0.45), 2),
575 "Brightness": round(rng.uniform(-0.2, 0.2), 2),
576 "Saturation": round(rng.uniform(0.3, 1.6), 2),
577 "PreDividePostMultiply": rng.choice([0, 1]),
578 "Blend": blend,
579 }
580 elif kind == "ColorCorrector":
581 params = {
582 "WheelHue1": round(rng.uniform(-0.35, 0.35), 3),
583 "WheelSaturation1": round(rng.uniform(0.5, 1.6), 2),
584 "WheelTintAngle1": round(rng.uniform(-0.5, 0.5), 3),
585 "WheelTintLength1": round(rng.uniform(0.0, 0.7), 2),
586 "TintMode": rng.choice([0, 1, 2]),
587 "MasterRGBGain": round(rng.uniform(0.65, 1.45), 2),
588 "ShadowsRGBGain": round(rng.uniform(0.65, 1.35), 2),
589 "HighlightsRGBGain": round(rng.uniform(0.65, 1.35), 2),
590 "PreDividePostMultiply": rng.choice([0, 1]),
591 "Blend": blend,
592 }
593 elif kind == "ChannelBoolean":
594 prim_port = "Background"
595 sec_port = "Foreground"
596 sec_src = src_b
597 params = {
598 "Operation": rng.choice([0, 1, 2, 6, 8, 9, 10, 13]),
599 "ToRed": rng.choice([0, 1, 2, 5, 10]),
600 "ToGreen": rng.choice([0, 1, 2, 6, 10]),
601 "ToBlue": rng.choice([0, 1, 2, 7, 10]),
602 "ToAlpha": rng.choice([3, 8, 16]),
603 "Blend": blend,
604 }
605 elif kind == "Blur":
606 params = {
607 "Filter": ("FuID", rng.choice(["Gaussian", "Box", "Fast Gaussian"])),
608 "LockBlurXY": 0,
609 "XBlurSize": round(rng.uniform(2.0, 18.0), 1),
610 "YBlurSize": round(rng.uniform(2.0, 18.0), 1),
611 "ClippingMode": ("FuID", rng.choice(["Frame", "None"])),
612 "Blend": blend,
613 }
614 elif kind == "Glow":
615 params = {
616 "LockGlowSize": 0,
617 "XGlowSize": round(rng.uniform(4.0, 20.0), 1),
618 "YGlowSize": round(rng.uniform(2.0, 14.0), 1),
619 "Glow": round(rng.uniform(0.4, 0.88), 2),
620 "Blend": blend,
621 }
622 elif kind == "SoftGlow":
623 params = {
624 "LockGlowSize": 0,
625 "XGlowSize": round(rng.uniform(4.0, 20.0), 1),
626 "YGlowSize": round(rng.uniform(2.0, 16.0), 1),
627 "Gain": round(rng.uniform(0.8, 2.5), 2),
628 "Threshold": round(rng.uniform(0.1, 0.65), 2),
629 "Blend": blend,
630 }
631 elif kind == "DirectionalBlur":
632 params = {
633 "Type": rng.choice([0, 1, 2]),
634 "Length": round(rng.uniform(0.02, 0.12), 3),
635 "Angle": round(rng.uniform(-90.0, 90.0), 1),
636 "Glow": round(rng.uniform(0.0, 0.4), 2),
637 "Blend": blend,
638 }
639 elif kind == "DVE":
640 params = {
641 "XRotation": round(rng.uniform(-35.0, 35.0), 1),
642 "YRotation": round(rng.uniform(-35.0, 35.0), 1),
643 "ZRotation": round(rng.uniform(-25.0, 25.0), 1),
644 "ZMove": round(rng.uniform(0.95, 1.6), 2),
645 "Pivot": (round(rng.uniform(0.3, 0.7), 2), round(rng.uniform(0.3, 0.7), 2)),
646 "Center": (round(rng.uniform(0.4, 0.6), 2), round(rng.uniform(0.4, 0.6), 2)),
647 "Blend": blend,
648 }
649 elif kind == "CornerPositioner":
650 params = {
651 "TopLeft": (round(rng.uniform(0.05, 0.28), 3), round(rng.uniform(0.72, 0.95), 3)),
652 "TopRight": (round(rng.uniform(0.72, 0.95), 3), round(rng.uniform(0.72, 0.95), 3)),
653 "BottomLeft": (round(rng.uniform(0.05, 0.28), 3), round(rng.uniform(0.05, 0.28), 3)),
654 "BottomRight": (round(rng.uniform(0.72, 0.95), 3), round(rng.uniform(0.05, 0.28), 3)),
655 "Blend": blend,
656 }
657 elif kind == "PerspectivePositioner":
658 params = {
659 "MappingType": rng.choice([0, 1]),
660 "TopLeft": (round(rng.uniform(0.12, 0.32), 3), round(rng.uniform(0.68, 0.88), 3)),
661 "TopRight": (round(rng.uniform(0.68, 0.88), 3), round(rng.uniform(0.68, 0.88), 3)),
662 "BottomLeft": (round(rng.uniform(0.12, 0.32), 3), round(rng.uniform(0.12, 0.32), 3)),
663 "BottomRight": (round(rng.uniform(0.68, 0.88), 3), round(rng.uniform(0.12, 0.32), 3)),
664 "Blend": blend,
665 }
666 elif kind == "HueCurves":
667 h_sp = f"{{pfx}}{nname}_Hue"
668 s_sp = f"{{pfx}}{nname}_Sat"
669 l_sp = f"{{pfx}}{nname}_Lum"
670 aux_templates.append(lut_bezier(h_sp, [(0, 1.0), (2, round(rng.uniform(0.75, 1.25), 2)), (4, round(rng.uniform(0.75, 1.25), 2)), (6, 1.0)]))
671 aux_templates.append(lut_bezier(s_sp, [(0, 1.0), (2, round(rng.uniform(0.5, 1.6), 2)), (5, round(rng.uniform(0.5, 1.6), 2)), (6, 1.0)]))
672 aux_templates.append(lut_bezier(l_sp, [(0, 1.0), (3, round(rng.uniform(0.7, 1.3), 2)), (6, 1.0)]))
673 raw_inputs.extend([
674 f'Hue = Input {{ SourceOp = "{h_sp}", Source = "Value", }},',
675 f'Sat = Input {{ SourceOp = "{s_sp}", Source = "Value", }},',
676 f'Lum = Input {{ SourceOp = "{l_sp}", Source = "Value", }},',
677 ])
678 params = {"Blend": blend}
679 elif kind == "Paint":
680 ps_n = f"{{pfx}}{nname}_PS"
681 btype = rng.choice(["SoftBrush", "CircleBrush"])
682 bsize = round(rng.uniform(0.03, 0.11), 3)
683 bsoft = round(rng.uniform(0.0, 0.8), 2)
684 cr = round(rng.uniform(0.2, 1.0), 2)
685 cg = round(rng.uniform(0.2, 1.0), 2)
686 cb = round(rng.uniform(0.2, 1.0), 2)
687 opac = round(rng.uniform(0.6, 1.0), 2)
688 wo0 = round(rng.uniform(0.0, 0.2), 2)
689 wo1 = round(rng.uniform(0.75, 1.0), 2)
690 x0, y0 = round(rng.uniform(-0.35, -0.05), 3), round(rng.uniform(-0.35, 0.35), 3)
691 x1, y1 = round(rng.uniform(0.05, 0.35), 3), round(rng.uniform(-0.35, 0.35), 3)
692 soft_line = f'\t\t\t\t["{btype}.Softness"] = Input {{ Value = {bsoft}, }},\n' if btype == "SoftBrush" else ""
693 aux_templates.append(
694 f'\t\t{ps_n} = PolylineStroke {{\n'
695 f'\t\t\tBrushes = {{ "{btype}" }},\n'
696 f'\t\t\tApplyModes = {{ "PaintApplyColor" }},\n'
697 f'\t\t\tInputs = {{\n'
698 f'\t\t\t\tBrushShape = Input {{ Value = FuID {{ "{btype}" }}, }},\n'
699 f'\t\t\t\tApplyMode = Input {{ Value = FuID {{ "PaintApplyColor" }}, }},\n'
700 f'\t\t\t\t["{btype}.Size"] = Input {{ Value = {bsize}, }},\n'
701 f'{soft_line}'
702 f'\t\t\t\t["PaintApplyColor.Red"] = Input {{ Value = {cr}, }},\n'
703 f'\t\t\t\t["PaintApplyColor.Green"] = Input {{ Value = {cg}, }},\n'
704 f'\t\t\t\t["PaintApplyColor.Blue"] = Input {{ Value = {cb}, }},\n'
705 f'\t\t\t\t["PaintApplyColor.Opacity"] = Input {{ Value = {opac}, }},\n'
706 f'\t\t\t\tWriteOnStart = Input {{ Value = {wo0}, }},\n'
707 f'\t\t\t\tWriteOnEnd = Input {{ Value = {wo1}, }},\n'
708 f'\t\t\t\tPolyline = Input {{ Value = Polyline {{ Points = {{ '
709 f'{{ Linear = true, X = {x0}, Y = {y0} }}, {{ Linear = true, X = {x1}, Y = {y1} }} '
710 f'}} }}, }},\n'
711 f'\t\t\t}},\n'
712 f'\t\t}},'
713 )
714 raw_inputs.append(f'Paint = Input {{ SourceOp = "{ps_n}", Source = "Out", }},')
715 params = {"Blend": blend}
716 elif kind == "Displace":
717 sec_port = "Foreground"
718 sec_src = src_b
719 dtype = rng.choice([0, 1])
720 if dtype == 0:
721 params = {
722 "Type": 0,
723 "RefractionStrength": round(rng.uniform(0.04, 0.16), 3),
724 "Spread": round(rng.uniform(0.0, 0.35), 2),
725 "LightPower": round(rng.uniform(0.0, 0.6), 2),
726 "Blend": blend,
727 }
728 else:
729 params = {
730 "Type": 1,
731 "XChannel": rng.choice([0, 1, 2]),
732 "YChannel": rng.choice([0, 1, 2]),
733 "XOffset": -0.5,
734 "YOffset": -0.5,
735 "XRefraction": round(rng.uniform(-0.12, 0.12), 3),
736 "YRefraction": round(rng.uniform(-0.12, 0.12), 3),
737 "Blend": blend,
738 }
739 elif kind == "Vortex":
740 params = {
741 "Center": (round(rng.uniform(0.35, 0.65), 2), round(rng.uniform(0.35, 0.65), 2)),
742 "Size": round(rng.uniform(0.35, 1.2), 2),
743 "Angle": round(rng.uniform(-2.5, 2.5), 2),
744 "Power": round(rng.uniform(0.8, 3.0), 2),
745 "Blend": blend,
746 }
747 elif kind == "Drip":
748 params = {
749 "Center": (round(rng.uniform(0.35, 0.65), 2), round(rng.uniform(0.35, 0.65), 2)),
750 "Strength": round(rng.uniform(0.4, 1.0), 2),
751 "Amplitude": round(rng.uniform(0.04, 0.14), 3),
752 "Frequency": round(rng.uniform(2.0, 7.0), 1),
753 "Phase": round(rng.uniform(0.0, 1.0), 2),
754 "Shape": rng.choice([0, 1]),
755 "Blend": blend,
756 }
757 elif kind == "Dent":
758 params = {
759 "Center": (round(rng.uniform(0.35, 0.65), 2), round(rng.uniform(0.35, 0.65), 2)),
760 "Size": round(rng.uniform(0.35, 0.85), 2),
761 "Strength": round(rng.uniform(0.3, 0.9), 2),
762 "Type": rng.choice([0, 1, 2, 3]),
763 "Blend": blend,
764 }
765 elif kind == "ChangeDepth":
766 params = {"Depth": rng.choice([1, 2, 3, 4])}
767 elif kind == "GamutConvert":
768 params = {
769 "SourceSpace": ("FuID", rng.choice(["NoChange", "sRGB", "Rec709"])),
770 "OutputSpace": ("FuID", rng.choice(["NoChange", "sRGB", "Rec709"])),
771 "RemoveGamma": rng.choice([0, 1]),
772 "AddGamma": rng.choice([0, 1]),
773 "PreDividePostMultiply": rng.choice([0, 1]),
774 "Blend": blend,
775 }
776 elif kind == "ColorGain":
777 params = {
778 "GainRed": round(rng.uniform(0.6, 1.5), 2),
779 "GainGreen": round(rng.uniform(0.6, 1.5), 2),
780 "GainBlue": round(rng.uniform(0.6, 1.5), 2),
781 "LiftGreen": round(rng.uniform(-0.1, 0.15), 2),
782 "GammaBlue": round(rng.uniform(0.7, 1.4), 2),
783 "MidHue": round(rng.uniform(0.1, 0.9), 2),
784 "PreDividePostMultiply": rng.choice([0, 1]),
785 "Blend": blend,
786 }
787 elif kind == "Custom":
788 prim_port = "Image1"
789 sec_port = "Image2"
790 sec_src = src_b
791 params = {
792 "NumberIn1": round(rng.uniform(0.3, 0.8), 2),
793 "PointIn1": (round(rng.uniform(0.3, 0.7), 2), round(rng.uniform(0.3, 0.7), 2)),
794 "Setup1": "1 - n1",
795 "Intermediate1": "max(0, 1 - dist(x, y, p1x, p1y) * 1.8)",
796 "RedExpression": "if(x > p1x, getr1b(x - 0.08, y) * i1 + r2 * s1, r1)",
797 "GreenExpression": "g1 * (1 - i1) + g2 * i1",
798 "BlueExpression": "b1 * n1 + b2 * (1 - n1)",
799 "AlphaExpression": "a1",
800 "Blend": blend,
801 }
802
803 nodes.append(
804 DagNode(
805 name=nname,
806 kind=kind,
807 is_source=False,
808 primary_port=prim_port,
809 primary_src=src_a,
810 secondary_port=sec_port,
811 secondary_src=sec_src,
812 params=params,
813 raw_inputs=raw_inputs,
814 aux_templates=aux_templates,
815 mask=mask,
816 )
817 )
818
819 return FuzzGraph(seed=seed, eval_frame=eval_frame, nodes=nodes)
820
821