1use crate::RenderError;
16use crate::codegen::{self, Child, SpecNode};
17use crate::ops::{self, Form, OpDef};
18use std::collections::HashMap;
19use std::sync::Arc;
20use ultrafast_graph::{Document, NodeId, Timing};
21
22const HEAVY_STATIC: usize = 4;
25pub const MAX_TEXTURES: usize = 16;
27
28#[derive(Debug, Clone)]
29pub struct PlanNode {
30 pub id: NodeId,
31 pub def: &'static OpDef,
32 pub chain: Vec<Timing>,
34 pub gated: bool,
36 pub inputs: Vec<usize>,
38 pub is_static: bool,
39 pub variant: String,
40 pub tables: Option<Arc<[f32]>>,
43}
44
45#[derive(Debug, Clone, PartialEq, Eq, Hash)]
47pub enum TexSource {
48 Group(usize),
50 Resource(String),
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum GroupKind {
56 Fused,
58 Blur,
60 Raster,
62 Render3D,
64 Particles,
66 Sim,
68}
69
70#[derive(Debug, Clone)]
73pub struct RasterChain {
74 pub node: usize,
75 pub transforms: Vec<usize>,
77}
78
79#[derive(Debug, Clone)]
81pub struct PlanRun {
82 pub stride: usize,
83 pub payload: usize,
84 pub layers: Vec<(usize, usize, codegen::LayerRef)>,
86}
87
88#[derive(Debug, Clone, PartialEq)]
91pub enum ParamSlot {
92 Node(usize),
94 Run(usize),
97 Value(f32),
98 Pad(usize),
100 Origins,
102}
103
104#[derive(Debug, Clone)]
105pub struct Group {
106 pub kind: GroupKind,
107 pub root: usize,
109 pub nodes: Vec<usize>,
111 pub textures: Vec<TexSource>,
113 pub params: Vec<ParamSlot>,
115 pub param_len: usize,
116 pub pad_textures: bool,
118 pub runs: Vec<PlanRun>,
121 pub is_static: bool,
122 pub output: usize,
124 pub key: String,
126 pub body: String,
128 pub raster: Option<RasterChain>,
129}
130
131#[derive(Debug, Clone)]
132pub struct Plan {
133 pub signature: u64,
134 pub nodes: Vec<PlanNode>,
135 pub groups: Vec<Group>,
136 pub group_of: Vec<usize>,
138 pub owner: Vec<usize>,
141 pub slot_count: usize,
142 pub output_slot: usize,
143 pub mb_split: Option<usize>,
147 pub post: Vec<bool>,
148 pub group_up: Vec<Vec<u64>>,
150 pub prefix: Vec<bool>,
152 pub overlay: Vec<bool>,
154 pub eliminated: Vec<NodeId>,
156 pub framed: Vec<bool>,
160}
161
162pub type Chains = HashMap<NodeId, Vec<Timing>>;
166
167fn gated(chains: Option<&Chains>, id: &str) -> bool {
168 chains
169 .and_then(|c| c.get(id))
170 .is_some_and(|c| c.iter().any(Timing::has_window))
171}
172
173pub fn signature(doc: &Document, chains: Option<&Chains>) -> u64 {
174 use std::hash::{Hash, Hasher};
175 let mut h = std::collections::hash_map::DefaultHasher::new();
176 doc.output.hash(&mut h);
177 (doc.format.width, doc.format.height).hash(&mut h);
178 doc.format.motion_blur.is_some_and(|m| m.samples > 1).hash(&mut h);
179 for (id, n) in &doc.nodes {
180 id.hash(&mut h);
181 n.op.hash(&mut h);
182 n.inputs.hash(&mut h);
183 if let Ok(def) = ops::resolve(id, n) {
186 def.func.hash(&mut h);
187 ops::variant_key(def, n).hash(&mut h);
188 }
189 for (k, p) in &n.params {
190 if p.is_animated() {
191 k.hash(&mut h);
192 }
193 }
194 ops::render_scale(n).is_some().hash(&mut h);
196 gated(chains, id).hash(&mut h);
197 }
198 h.finish()
199}
200
201pub fn compile(doc: &Document, chains: Option<&Chains>) -> Result<Plan, RenderError> {
202 let order = schedule(doc, &doc.reachable_topo_order()?);
203 let index: HashMap<&str, usize> = order.iter().enumerate().map(|(i, id)| (id.as_str(), i)).collect();
204
205 let mut nodes: Vec<PlanNode> = Vec::with_capacity(order.len());
206 for id in &order {
207 let node = &doc.nodes[id];
208 let def = ops::resolve(id, node)?;
209 let ports = ops::connected_ports(def, id, node)?;
210 let inputs: Vec<usize> = ports.iter().map(|p| index[node.inputs[p].as_str()]).collect();
211 let gated = gated(chains, id);
212 let is_static = !node.is_animated()
213 && !ops::time_varying(def, node)
214 && !gated
215 && inputs.iter().all(|&i| nodes[i].is_static);
216 let mut variant = if def.name == "video" || (def.name == "image" && ops::time_varying(def, node)) {
220 format!("{}\u{1f}{id}", ops::variant_key(def, node))
221 } else {
222 ops::variant_key(def, node)
223 };
224 let tables = if matches!(def.form, Form::Custom | Form::Sim) {
226 crate::tables::hoist(&variant).map(|h| {
227 variant = h.code;
228 h.data
229 })
230 } else {
231 None
232 };
233 nodes.push(PlanNode {
234 id: id.clone(),
235 def,
236 chain: chains.and_then(|c| c.get(id)).cloned().unwrap_or_default(),
237 gated,
238 inputs,
239 is_static,
240 variant,
241 tables,
242 });
243 }
244 let n = nodes.len();
245
246 let mut consumers: Vec<Vec<usize>> = vec![Vec::new(); n];
247 for (i, node) in nodes.iter().enumerate() {
248 for &s in &node.inputs {
249 consumers[s].push(i);
250 }
251 }
252 let mut weight = vec![1usize; n];
257 for i in 0..n {
258 if matches!(nodes[i].def.name, "shader" | "noise" | "marble") {
259 weight[i] = HEAVY_STATIC;
260 }
261 weight[i] += nodes[i].inputs.iter().map(|&s| weight[s]).sum::<usize>();
262 }
263
264 let mut chain_head = vec![usize::MAX; n];
267 let mut in_chain = vec![false; n];
268 for i in 0..n {
269 if nodes[i].def.form != Form::Raster {
270 continue;
271 }
272 let mut head = i;
273 while consumers[head].len() == 1 && nodes[consumers[head][0]].def.func == "transform" {
274 in_chain[head] = true;
275 head = consumers[head][0];
276 }
277 chain_head[head] = i;
278 }
279
280 if nodes.last().is_some_and(|o| o.def.form == Form::Object) {
282 let o = nodes.last().unwrap();
283 return Err(RenderError::BadParam {
284 node: o.id.clone(),
285 param: "output".into(),
286 reason: format!(
287 "`{}` is a 3D object, not an image: render it with a `render3d` node",
288 o.def.name
289 ),
290 });
291 }
292 let mut materialize: Vec<bool> = (0..n)
293 .map(|i| {
294 match nodes[i].def.form {
296 Form::Object => return false,
297 Form::Render3D | Form::Particles | Form::Sim => return true,
298 _ => {}
299 }
300 if ops::render_scale(&doc.nodes[&nodes[i].id]).is_some() {
301 return true;
302 }
303 if nodes[i].def.name == "shader" && nodes[i].gated {
309 return true;
310 }
311 if chain_head[i] != usize::MAX {
312 return true;
313 }
314 if in_chain[i] {
315 return false;
316 }
317 if i == n - 1 || consumers[i].len() != 1 || nodes[i].def.form == Form::Blur {
318 return true;
319 }
320 let c = &nodes[consumers[i][0]];
321 if matches!(
322 c.def.form,
323 Form::Blur | Form::Custom | Form::Object | Form::Render3D | Form::Particles | Form::Sim
324 ) {
325 return true;
326 }
327 nodes[i].is_static && !c.is_static && weight[i] >= HEAVY_STATIC
328 })
329 .collect();
330
331 let split = if doc.format.motion_blur.is_some_and(|m| m.samples > 1) {
334 finishing_split(&nodes).filter(|&x| !in_chain[x] && chain_head[x] == usize::MAX)
335 } else {
336 None
337 };
338 if let Some(x) = split {
339 materialize[x] = true;
340 }
341
342 let budget = MAX_TEXTURES - 1;
347 let mut contrib = vec![0usize; n];
348 for i in 0..n {
349 if nodes[i].def.form == Form::Object {
350 continue;
351 }
352 let resource = ops::uses_resource(nodes[i].def) as usize;
353 let child = |c: usize, m: &[bool], contrib: &[usize]| if m[c] { 1 } else { contrib[c] };
354 let mut own: usize = resource
355 + nodes[i]
356 .inputs
357 .iter()
358 .map(|&c| child(c, &materialize, &contrib))
359 .sum::<usize>();
360 while own > budget {
361 let heaviest = nodes[i]
362 .inputs
363 .iter()
364 .copied()
365 .filter(|&c| !materialize[c] && nodes[c].def.form != Form::Object)
366 .max_by_key(|&c| contrib[c]);
367 let Some(c) = heaviest else { break };
368 own = own - contrib[c] + 1;
369 materialize[c] = true;
370 }
371 contrib[i] = own;
372 }
373
374 let mut group_of = vec![usize::MAX; n];
375 let mut groups: Vec<Group> = Vec::new();
376 for root in 0..n {
377 if !materialize[root] {
378 continue;
379 }
380 let g = groups.len();
381 let group = if nodes[root].def.form == Form::Particles {
382 Group {
383 kind: GroupKind::Particles,
384 root,
385 is_static: false,
386 nodes: vec![root],
387 textures: nodes[root]
388 .inputs
389 .iter()
390 .map(|&s| TexSource::Group(group_of[s]))
391 .collect(),
392 params: Vec::new(),
393 pad_textures: false,
394 runs: Vec::new(),
395 param_len: 4,
396 output: usize::MAX,
397 key: String::new(),
398 body: String::new(),
399 raster: None,
400 }
401 } else if nodes[root].def.form == Form::Sim {
402 let (key, body) = if nodes[root].def.name == "feedback" {
404 crate::codegen::feedback(&nodes[root].variant, nodes[root].tables.is_some())
405 } else {
406 (String::new(), String::new())
407 };
408 Group {
409 kind: GroupKind::Sim,
410 root,
411 is_static: false,
412 nodes: vec![root],
413 textures: nodes[root]
414 .inputs
415 .iter()
416 .map(|&s| TexSource::Group(group_of[s]))
417 .collect(),
418 params: Vec::new(),
419 pad_textures: false,
420 runs: Vec::new(),
421 param_len: 4,
422 output: usize::MAX,
423 key,
424 body,
425 raster: None,
426 }
427 } else if nodes[root].def.form == Form::Render3D {
428 let objects: Vec<usize> = nodes[root]
430 .inputs
431 .iter()
432 .copied()
433 .filter(|&o| nodes[o].def.form == Form::Object)
434 .collect();
435 let mut textures = Vec::new();
436 let images = nodes[root]
439 .inputs
440 .iter()
441 .filter(|&&s| nodes[s].def.form != Form::Object);
442 for &src in images.chain(objects.iter().flat_map(|&o| nodes[o].inputs.iter())) {
443 let ts = TexSource::Group(group_of[src]);
444 if !textures.contains(&ts) {
445 textures.push(ts);
446 }
447 }
448 let mut members = objects.clone();
449 members.push(root);
450 Group {
451 kind: GroupKind::Render3D,
452 root,
453 is_static: members.iter().all(|&m| nodes[m].is_static),
454 nodes: members,
455 textures,
456 params: Vec::new(),
457 pad_textures: false,
458 runs: Vec::new(),
459 param_len: 4,
460 output: usize::MAX,
461 key: String::new(),
462 body: String::new(),
463 raster: None,
464 }
465 } else if chain_head[root] != usize::MAX {
466 let r = chain_head[root];
467 let mut transforms = Vec::new();
468 let mut cur = r;
469 while cur != root {
470 cur = consumers[cur][0];
471 transforms.push(cur);
472 }
473 let mut members = vec![r];
474 members.extend(&transforms);
475 Group {
476 kind: GroupKind::Raster,
477 root,
478 is_static: members.iter().all(|&m| nodes[m].is_static),
479 nodes: members,
480 textures: Vec::new(),
481 params: vec![ParamSlot::Node(r)],
482 pad_textures: false,
483 runs: Vec::new(),
484 param_len: 4 + nodes[r].def.params,
485 output: usize::MAX,
486 key: String::new(),
487 body: String::new(),
488 raster: Some(RasterChain { node: r, transforms }),
489 }
490 } else if nodes[root].def.form == Form::Blur {
491 let src = nodes[root].inputs[0];
492 Group {
493 kind: GroupKind::Blur,
494 root,
495 nodes: vec![root],
496 textures: vec![TexSource::Group(group_of[src])],
497 params: vec![ParamSlot::Node(root)],
498 pad_textures: false,
499 runs: Vec::new(),
500 param_len: 4 + nodes[root].def.params,
501 is_static: nodes[root].is_static,
502 output: usize::MAX,
503 key: String::new(),
504 body: String::new(),
505 raster: None,
506 }
507 } else {
508 build_fused(&nodes, &materialize, &group_of, root)?
509 };
510 group_of[root] = g;
511 groups.push(group);
512 }
513
514 if let Some(x) = split {
518 let up = upstream(&nodes, x);
519 let order: Vec<usize> = (0..groups.len())
520 .filter(|&g| up[groups[g].root])
521 .chain((0..groups.len()).filter(|&g| !up[groups[g].root]))
522 .collect();
523 let mut new_index = vec![0usize; groups.len()];
524 for (ni, &og) in order.iter().enumerate() {
525 new_index[og] = ni;
526 }
527 let mut old: Vec<Option<Group>> = std::mem::take(&mut groups).into_iter().map(Some).collect();
528 groups = order.iter().map(|&og| old[og].take().unwrap()).collect();
529 for g in &mut groups {
530 for t in &mut g.textures {
531 if let TexSource::Group(s) = t {
532 *s = new_index[*s];
533 }
534 }
535 }
536 for v in group_of.iter_mut() {
537 if *v != usize::MAX {
538 *v = new_index[*v];
539 }
540 }
541 }
542 let (slot_count, output_slot) = assign_slots(&mut groups);
543 let (mb_split, post) = match split {
544 Some(x) => {
545 let up = upstream(&nodes, x);
546 (Some(group_of[x]), groups.iter().map(|g| !up[g.root]).collect())
547 }
548 None => (None, vec![false; groups.len()]),
549 };
550 let words = n.div_ceil(64);
554 let mut up_nodes = vec![vec![0u64; words]; n];
555 for i in 0..n {
556 up_nodes[i][i / 64] |= 1 << (i % 64);
557 for k in 0..nodes[i].inputs.len() {
558 let s = nodes[i].inputs[k];
559 let (a, b) = up_nodes.split_at_mut(i);
560 for (w, v) in b[0].iter_mut().zip(&a[s]) {
561 *w |= *v;
562 }
563 }
564 }
565 let group_up: Vec<Vec<u64>> = groups.iter().map(|g| up_nodes[g.root].clone()).collect();
566 let prefix: Vec<bool> = (0..groups.len())
567 .map(|k| (0..groups.len()).all(|j| (j <= k) == bit(&group_up[k], groups[j].root)))
568 .collect();
569 let overlay = overlays(&nodes);
570 let eliminated = doc
571 .nodes
572 .keys()
573 .filter(|id| !index.contains_key(id.as_str()))
574 .cloned()
575 .collect();
576 let mut owner = vec![usize::MAX; nodes.len()];
577 for (gi, g) in groups.iter().enumerate() {
578 for &m in &g.nodes {
579 owner[m] = if owner[m] == usize::MAX || owner[m] == gi {
580 gi
581 } else {
582 SHARED
583 };
584 }
585 }
586 let framed = framed_groups(&nodes, &groups, &group_of);
587 Ok(Plan {
588 signature: signature(doc, chains),
589 framed,
590 nodes,
591 groups,
592 group_of,
593 owner,
594 slot_count,
595 output_slot,
596 eliminated,
597 mb_split,
598 post,
599 group_up,
600 prefix,
601 overlay,
602 })
603}
604
605fn framed_groups(nodes: &[PlanNode], groups: &[Group], group_of: &[usize]) -> Vec<bool> {
611 let n = groups.len();
612 let mut reads: Vec<Vec<(usize, bool)>> = vec![Vec::new(); n];
614 for (ci, c) in groups.iter().enumerate() {
615 if c.kind != GroupKind::Fused {
616 for t in &c.textures {
617 if let TexSource::Group(p) = t {
618 reads[*p].push((ci, false));
619 }
620 }
621 continue;
622 }
623 let mut here: HashMap<usize, bool> = HashMap::new();
625 here.insert(c.root, true);
626 for &m in c.nodes.iter().rev() {
627 let at = *here.get(&m).unwrap_or(&false);
628 let pn = &nodes[m];
629 for (port, &src) in pn.inputs.iter().enumerate() {
630 let passes = at
631 && match pn.def.form {
632 Form::Map => true,
633 Form::Displace => port == 1,
635 _ => false,
636 };
637 if c.nodes.contains(&src) {
638 let e = here.entry(src).or_insert(true);
641 *e &= passes;
642 } else if group_of[src] < n {
643 reads[group_of[src]].push((ci, passes));
644 }
645 }
646 }
647 }
648 let mut framed = vec![false; n];
649 for g in (0..n).rev() {
650 framed[g] = if g + 1 == n {
651 true
652 } else {
653 !reads[g].is_empty() && reads[g].iter().all(|&(c, here)| here && framed[c])
654 };
655 }
656 framed
657}
658
659pub const SHARED: usize = usize::MAX - 1;
661
662impl Plan {
663 pub fn in_group(&self, gi: usize, ni: usize) -> bool {
665 match self.owner[ni] {
666 SHARED => self.groups[gi].nodes.contains(&ni),
667 o => o == gi,
668 }
669 }
670}
671
672pub fn bit(set: &[u64], i: usize) -> bool {
674 set[i / 64] >> (i % 64) & 1 == 1
675}
676
677fn overlays(nodes: &[PlanNode]) -> Vec<bool> {
680 let n = nodes.len();
681 let mut consumers: Vec<Vec<usize>> = vec![Vec::new(); n];
682 for (i, node) in nodes.iter().enumerate() {
683 for &s in &node.inputs {
684 consumers[s].push(i);
685 }
686 }
687 (0..n)
688 .map(|i| {
689 matches!(nodes[i].def.form, Form::Custom | Form::Gen)
690 && nodes[i].inputs.is_empty()
691 && !consumers[i].is_empty()
692 && consumers[i]
693 .iter()
694 .all(|&c| nodes[c].def.name == "blend" && nodes[c].inputs.first() == Some(&i))
695 })
696 .collect()
697}
698
699fn upstream(nodes: &[PlanNode], x: usize) -> Vec<bool> {
701 let mut up = vec![false; nodes.len()];
702 let mut stack = vec![x];
703 while let Some(i) = stack.pop() {
704 if !std::mem::replace(&mut up[i], true) {
705 stack.extend(nodes[i].inputs.iter().copied());
706 }
707 }
708 up
709}
710
711fn finishing_split(nodes: &[PlanNode]) -> Option<usize> {
716 let n = nodes.len();
717 let mut consumers: Vec<Vec<usize>> = vec![Vec::new(); n];
718 for (i, node) in nodes.iter().enumerate() {
719 for &s in &node.inputs {
720 consumers[s].push(i);
721 }
722 }
723 let finishing = |i: usize| {
724 let d = nodes[i].def;
725 let generator = nodes[i].inputs.is_empty();
726 match d.form {
727 Form::Map | Form::Blur => true,
728 Form::Custom | Form::Gen if !generator || nodes[i].is_static => true,
730 Form::Custom | Form::Gen => {
733 !consumers[i].is_empty()
734 && consumers[i]
735 .iter()
736 .all(|&c| nodes[c].def.name == "blend" && nodes[c].inputs.first() == Some(&i))
737 }
738 _ => false,
739 }
740 };
741 let words = n.div_ceil(64);
743 let mut up = vec![vec![0u64; words]; n];
744 for i in 0..n {
745 up[i][i / 64] |= 1 << (i % 64);
746 for k in 0..nodes[i].inputs.len() {
747 let s = nodes[i].inputs[k];
748 let (a, b) = if s < i { up.split_at_mut(i) } else { continue };
749 for (w, v) in b[0].iter_mut().zip(&a[s]) {
750 *w |= *v;
751 }
752 }
753 }
754 let has = |set: &Vec<u64>, j: usize| set[j / 64] >> (j % 64) & 1 == 1;
755 let scene: Vec<usize> = (0..n).filter(|&i| !finishing(i)).collect();
756 let mut best: Option<(usize, u32)> = None;
757 for x in 0..n.saturating_sub(1) {
758 if !scene.iter().all(|&s| has(&up[x], s)) {
759 continue;
760 }
761 if !(0..n).all(|j| has(&up[x], j) || finishing(j)) {
762 continue;
763 }
764 let size: u32 = up[x].iter().map(|w| w.count_ones()).sum();
765 if best.is_none_or(|(_, b)| size < b) {
766 best = Some((x, size));
767 }
768 }
769 best.map(|(x, _)| x)
770}
771
772fn build_fused(
773 nodes: &[PlanNode],
774 materialize: &[bool],
775 group_of: &[usize],
776 root: usize,
777) -> Result<Group, RenderError> {
778 let mut spec: Vec<SpecNode> = Vec::new();
781 let mut externals: Vec<TexSource> = Vec::new();
782 let mut member: Vec<usize> = Vec::new();
783 fn ext(externals: &mut Vec<TexSource>, s: TexSource) -> usize {
784 externals.iter().position(|e| *e == s).unwrap_or_else(|| {
785 externals.push(s);
786 externals.len() - 1
787 })
788 }
789 fn walk(
790 nodes: &[PlanNode],
791 materialize: &[bool],
792 group_of: &[usize],
793 i: usize,
794 spec: &mut Vec<SpecNode>,
795 externals: &mut Vec<TexSource>,
796 member: &mut Vec<usize>,
797 ) -> usize {
798 let n = &nodes[i];
799 let children = n
800 .inputs
801 .iter()
802 .map(|&s| {
803 if materialize[s] {
804 Child::External(ext(externals, TexSource::Group(group_of[s])))
805 } else {
806 Child::Node(walk(nodes, materialize, group_of, s, spec, externals, member))
807 }
808 })
809 .collect();
810 let resource = ops::uses_resource(n.def).then(|| ext(externals, TexSource::Resource(n.variant.clone())));
811 let code = (n.def.form == Form::Custom).then(|| n.variant.clone());
812 spec.push(SpecNode {
813 def: n.def,
814 children,
815 resource,
816 code,
817 tables: n.tables.as_ref().map_or(0, |t| t.len()),
818 tag: i,
819 gated: n.gated,
820 });
821 member.push(i);
822 spec.len() - 1
823 }
824 let top = walk(
825 nodes,
826 materialize,
827 group_of,
828 root,
829 &mut spec,
830 &mut externals,
831 &mut member,
832 );
833 let k = codegen::generate(&spec, top);
834 if k.bindings.len() > MAX_TEXTURES {
835 return Err(RenderError::TooManyInputs {
836 node: nodes[root].id.clone(),
837 count: k.bindings.len(),
838 });
839 }
840 Ok(Group {
841 kind: GroupKind::Fused,
842 root,
843 is_static: member.iter().all(|&m| nodes[m].is_static),
845 nodes: member,
846 textures: k.bindings.iter().map(|&b| externals[b].clone()).collect(),
847 params: k
848 .layout
849 .iter()
850 .map(|s| match s {
851 codegen::Slot::Node(i) => ParamSlot::Node(spec[*i].tag),
852 codegen::Slot::Run(r) => ParamSlot::Run(*r),
853 codegen::Slot::Value(v) => ParamSlot::Value(*v),
854 codegen::Slot::Pad(n) => ParamSlot::Pad(*n),
855 codegen::Slot::Origins => ParamSlot::Origins,
856 })
857 .collect(),
858 param_len: k.param_len,
859 pad_textures: k.pad_textures,
860 runs: k
861 .runs
862 .iter()
863 .map(|r| PlanRun {
864 stride: r.stride,
865 payload: r.payload,
866 layers: r
867 .layers
868 .iter()
869 .map(|l| {
870 let layer = match l.layer {
871 codegen::LayerRef::Gen(g) => codegen::LayerRef::Gen(spec[g].tag),
872 ref t => t.clone(),
873 };
874 (l.kind, spec[l.composite].tag, layer)
875 })
876 .collect(),
877 })
878 .collect(),
879 output: usize::MAX,
880 key: k.key,
881 body: k.body,
882 raster: None,
883 })
884}
885
886fn assign_slots(groups: &mut [Group]) -> (usize, usize) {
890 let n = groups.len();
891 for g in 0..n {
893 let inputs_static = groups[g].textures.iter().all(|t| match t {
894 TexSource::Group(s) => groups[*s].is_static,
895 TexSource::Resource(_) => true,
896 });
897 groups[g].is_static &= inputs_static;
898 }
899 let mut last_use: Vec<usize> = (0..n).collect();
900 for g in 0..n {
901 for t in &groups[g].textures {
902 if let TexSource::Group(s) = t {
903 last_use[*s] = last_use[*s].max(g);
904 }
905 }
906 }
907 let mut count = 0;
908 let mut free: Vec<usize> = Vec::new();
909 let mut release_at: Vec<Vec<usize>> = vec![Vec::new(); n];
910 let new_slot = |count: &mut usize| {
911 *count += 1;
912 *count - 1
913 };
914 for g in 0..n {
915 let slot = if groups[g].is_static || groups[g].kind == GroupKind::Render3D {
918 new_slot(&mut count)
919 } else {
920 free.pop().unwrap_or_else(|| new_slot(&mut count))
921 };
922 groups[g].output = slot;
923 if !groups[g].is_static && groups[g].kind != GroupKind::Render3D && g != n - 1 {
924 release_at[last_use[g]].push(slot);
925 }
926 let released = std::mem::take(&mut release_at[g]);
927 free.extend(released);
928 }
929 (count, groups.last().map(|g| g.output).unwrap_or(0))
930}
931
932fn schedule(doc: &Document, topo: &[NodeId]) -> Vec<NodeId> {
936 let mut weight: HashMap<&str, usize> = HashMap::new();
937 for id in topo {
938 let w = 1 + doc.nodes[id].inputs.values().map(|s| weight[s.as_str()]).sum::<usize>();
939 weight.insert(id.as_str(), w);
940 }
941 let mut out = Vec::with_capacity(topo.len());
942 let mut done: HashMap<&str, ()> = HashMap::new();
943 let mut stack: Vec<(&str, bool)> = vec![(doc.output.as_str(), false)];
944 while let Some((id, expanded)) = stack.pop() {
945 if done.contains_key(id) {
946 continue;
947 }
948 if expanded {
949 done.insert(id, ());
950 out.push(id.to_string());
951 continue;
952 }
953 stack.push((id, true));
954 let mut inputs: Vec<&str> = doc.nodes[id].inputs.values().map(String::as_str).collect();
955 inputs.sort_by_key(|s| weight[s]);
957 for s in inputs {
958 if !done.contains_key(s) {
959 stack.push((s, false));
960 }
961 }
962 }
963 out
964}
965
966impl Plan {
967 pub fn describe(&self) -> String {
969 let mut s = format!(
970 "plan: {} nodes in {} kernels, {} texture slots, output slot {}\n",
971 self.nodes.len(),
972 self.groups.len(),
973 self.slot_count,
974 self.output_slot
975 );
976 for (gi, g) in self.groups.iter().enumerate() {
977 let ids: Vec<&str> = g.nodes.iter().map(|&i| self.nodes[i].id.as_str()).collect();
978 let tex: Vec<String> = g
979 .textures
980 .iter()
981 .map(|t| match t {
982 TexSource::Group(x) => format!("g{x}"),
983 TexSource::Resource(r) => format!("res:{r}"),
984 })
985 .collect();
986 s += &format!(
987 " g{gi:<3} {:<6} {} -> slot {}{} [{}]\n",
988 match g.kind {
989 GroupKind::Fused => "fused",
990 GroupKind::Blur => "blur",
991 GroupKind::Raster => "raster",
992 GroupKind::Render3D => "3d",
993 GroupKind::Particles => "particles",
994 GroupKind::Sim => "sim",
995 },
996 if tex.is_empty() {
997 String::new()
998 } else {
999 format!("reads {} ", tex.join(","))
1000 },
1001 g.output,
1002 if g.is_static { " static/cached" } else { "" },
1003 ids.join(" "),
1004 );
1005 }
1006 if let Some(sg) = self.mb_split {
1007 let post: Vec<String> = (0..self.groups.len())
1008 .filter(|&g| self.post[g])
1009 .map(|g| format!("g{g}"))
1010 .collect();
1011 s += &format!(
1012 " motion blur: samples up to g{sg}; once per frame on the blurred image: {}\n",
1013 post.join(" ")
1014 );
1015 }
1016 if !self.eliminated.is_empty() {
1017 s += &format!(" eliminated (unreachable): {}\n", self.eliminated.join(", "));
1018 }
1019 s
1020 }
1021}
1022
1023#[cfg(test)]
1024mod tests {
1025 use super::*;
1026
1027 fn layered(n: usize, animated: bool) -> Document {
1028 let anim = r#"{"keys":[{"t":0,"v":[0,0]},{"t":1,"v":[9,9]}]}"#;
1029 let center = if animated { anim } else { "[4,4]" };
1030 let mut nodes = format!(r#""s0": {{"op":"shape","params":{{"center":{center}}}}}"#);
1031 for i in 1..n {
1032 nodes += &format!(
1033 r#","s{i}": {{"op":"shape","params":{{"center":{center}}}}}
1034 ,"o{i}": {{"op":"over","inputs":{{"fg":"s{i}","bg":"{}"}}}}"#,
1035 if i == 1 {
1036 "s0".to_string()
1037 } else {
1038 format!("o{}", i - 1)
1039 }
1040 );
1041 }
1042 Document::from_json(&format!(
1043 r#"{{"version":1,"format":{{"width":8,"height":8,"fps":30,"duration":1}},"output":"o{}","nodes":{{{nodes}}}}}"#,
1044 n - 1
1045 ))
1046 .unwrap()
1047 }
1048
1049 #[test]
1050 fn layer_stack_fuses_into_one_kernel() {
1051 let plan = compile(&layered(20, true), None).unwrap();
1052 assert_eq!(plan.nodes.len(), 39);
1053 assert_eq!(plan.groups.len(), 1, "{}", plan.describe());
1054 assert_eq!(plan.slot_count, 1);
1055 }
1056
1057 #[test]
1058 fn shared_nodes_materialize_and_blur_is_a_barrier() {
1059 let doc = Document::from_json(
1060 r#"{"version":1,"format":{"width":8,"height":8,"fps":30,"duration":1},"output":"out","nodes":{
1061 "s": {"op":"shape"},
1062 "b": {"op":"blur","inputs":{"source":"s"}},
1063 "m": {"op":"mask","inputs":{"source":"b","matte":"s"}},
1064 "out": {"op":"transform","inputs":{"source":"m"}}}}"#,
1065 )
1066 .unwrap();
1067 let plan = compile(&doc, None).unwrap();
1068 assert_eq!(plan.groups.len(), 3, "{}", plan.describe());
1070 assert_eq!(plan.groups[1].kind, GroupKind::Blur);
1071 assert_eq!(plan.groups[2].nodes.len(), 2);
1072 for g in &plan.groups {
1073 for t in &g.textures {
1074 if let TexSource::Group(s) = t {
1075 assert_ne!(plan.groups[*s].output, g.output);
1076 }
1077 }
1078 }
1079 }
1080
1081 #[test]
1082 fn param_values_do_not_change_signature_but_animation_does() {
1083 let mut a = layered(3, false);
1084 let s0 = signature(&a, None);
1085 a.nodes
1086 .get_mut("s1")
1087 .unwrap()
1088 .params
1089 .insert("size".into(), ultrafast_graph::Param::Number(3.0));
1090 assert_eq!(signature(&a, None), s0);
1091 let b = layered(3, true);
1092 assert_ne!(signature(&b, None), s0);
1093 }
1094}