1use crate::ops::{Form, OpDef};
13
14pub const ENTRY: &str = "ENTRY_POINT";
17const NSID: &str = "NSID";
20
21pub const LIBRARY: &str = include_str!("../shaders/lib.slang");
23
24#[derive(Debug, Clone)]
25pub enum Child {
26 Node(usize),
28 External(usize),
30}
31
32#[derive(Debug, Clone)]
33pub struct SpecNode {
34 pub def: &'static OpDef,
35 pub children: Vec<Child>,
37 pub resource: Option<usize>,
39 pub code: Option<String>,
41 pub tables: usize,
44 pub tag: usize,
46 pub gated: bool,
49}
50
51#[derive(Debug, Clone)]
52pub struct Generated {
53 pub body: String,
55 pub bindings: Vec<usize>,
57 pub layout: Vec<Slot>,
59 pub runs: Vec<RunLayout>,
61 pub param_len: usize,
64 pub pad_textures: bool,
67 pub key: String,
69}
70
71#[derive(Debug, Clone, PartialEq)]
73pub enum Slot {
74 Node(usize),
77 Run(usize),
80 Value(f32),
82 Pad(usize),
84 Origins,
86}
87
88const MIN_RUN: usize = 4;
91
92struct Run {
95 links: Vec<usize>,
97 base: Child,
99}
100
101#[derive(Debug, Clone)]
105pub struct RunLayout {
106 pub stride: usize,
107 pub payload: usize,
110 pub layers: Vec<RunLayer>,
111}
112
113#[derive(Debug, Clone)]
114pub struct RunLayer {
115 pub kind: usize,
117 pub composite: usize,
119 pub layer: LayerRef,
120}
121
122#[derive(Debug, Clone, PartialEq)]
123pub enum LayerRef {
124 Texture(usize),
126 Gen(usize),
128}
129
130struct Emitter<'a> {
131 spec: &'a [SpecNode],
132 decls: String,
133 code: String,
134 vars: usize,
135 bindings: Vec<usize>,
136 layout: Vec<Slot>,
137 runs: Vec<RunLayout>,
140 offsets: Vec<Option<usize>>,
141 next_offset: usize,
142 memo: std::collections::HashMap<(usize, String, bool), String>,
146 declared: std::collections::HashSet<usize>,
148}
149
150impl Emitter<'_> {
151 fn var(&mut self) -> String {
152 self.vars += 1;
153 format!("v{}", self.vars)
154 }
155
156 fn texture(&mut self, ext: usize) -> String {
157 let i = self.bindings.iter().position(|&b| b == ext).unwrap_or_else(|| {
158 self.bindings.push(ext);
159 self.bindings.len() - 1
160 });
161 format!("T{i}")
162 }
163
164 fn origin(&self, texture: &str) -> String {
167 format!("ORIGIN_{texture}_")
168 }
169
170 fn offset(&mut self, n: usize) -> usize {
171 if let Some(o) = self.offsets[n] {
172 return o;
173 }
174 let o = self.next_offset;
175 self.offsets[n] = Some(o);
176 self.layout.push(Slot::Node(n));
177 self.next_offset += self.block(n) + self.spec[n].tables;
178 o
179 }
180
181 fn block(&self, n: usize) -> usize {
184 self.spec[n].def.params
185 + self.spec[n].gated as usize
186 + if crate::ops::guarded(self.spec[n].def) { 4 } else { 0 }
187 }
188
189 fn child(&mut self, c: &Child, ctx: &str, identity: bool) -> String {
190 match c {
191 Child::Node(n) => self.node(*n, ctx, identity),
192 Child::External(e) => {
193 let t = self.texture(*e);
194 let v = self.var();
195 let o = self.origin(&t);
196 if identity {
197 self.code += &format!(" float4 {v} = load_t({t}, gid.xy, {o});\n");
198 } else {
199 self.code += &format!(" float4 {v} = sample_t({t}, {ctx}.pos, {o});\n");
200 }
201 v
202 }
203 }
204 }
205
206 fn node(&mut self, n: usize, ctx: &str, identity: bool) -> String {
211 let key = (n, ctx.to_string(), identity);
212 if let Some(v) = self.memo.get(&key) {
213 return v.clone();
214 }
215 if let Some(run) = self.run_at(n) {
216 let v = self.emit_run(run, ctx, identity);
217 self.memo.insert(key, v.clone());
218 return v;
219 }
220 let v = if !self.spec[n].gated {
221 self.node_inner(n, ctx, identity)
222 } else {
223 let pass = crate::ops::passthrough(self.spec[n].def, self.spec[n].children.len());
227 let pv = pass.map(|i| {
228 let child = self.spec[n].children[i].clone();
229 self.child(&child, ctx, identity)
230 });
231 let active = self.offset(n) + self.spec[n].def.params;
232 let v = self.var();
233 self.code += &format!(
234 " float4 {v} = {};\n if (P[{active}] > 0.5) {{\n",
235 pv.as_deref().unwrap_or("float4(0.0)")
236 );
237 let saved = self.memo.clone();
238 let inner = self.node_inner(n, ctx, identity);
239 self.memo = saved;
240 self.code += &format!(" {v} = {inner};\n }}\n");
241 v
242 };
243 self.memo.insert(key, v.clone());
244 v
245 }
246
247 fn run_at(&self, n: usize) -> Option<Run> {
255 let top = &self.spec[n];
256 if top.def.form != Form::Map || !crate::ops::guarded(top.def) {
257 return None;
258 }
259 let layer_ok = |c: &Child| match c {
260 Child::External(_) => true,
261 Child::Node(g) => {
262 let g = &self.spec[*g];
263 g.def.form == Form::Gen && g.children.is_empty() && g.resource.is_none() && g.code.is_none()
264 }
265 };
266 let mut links = Vec::new();
267 let mut cur = n;
268 let base = loop {
269 let s = &self.spec[cur];
270 if s.def.name != top.def.name || !s.gated || s.children.len() != 2 || !layer_ok(&s.children[0]) {
271 break Child::Node(cur);
272 }
273 links.push(cur);
274 match &s.children[1] {
275 Child::Node(b) => cur = *b,
276 c @ Child::External(_) => break c.clone(),
277 }
278 };
279 if links.len() < MIN_RUN {
280 return None;
281 }
282 links.reverse();
283 Some(Run { links, base })
284 }
285
286 fn emit_run(&mut self, run: Run, ctx: &str, identity: bool) -> String {
293 let bgv = self.child(&run.base, ctx, identity);
294 let cdef = self.spec[run.links[0]].def;
295 let mut kinds: Vec<&'static OpDef> = Vec::new();
298 let mut textures = false;
299 for &l in &run.links {
300 match &self.spec[l].children[0] {
301 Child::External(_) => textures = true,
302 Child::Node(g) => {
303 let d = self.spec[*g].def;
305 if !kinds.iter().any(|k| k.func == d.func) {
306 kinds.push(d);
307 }
308 }
309 }
310 }
311 kinds.sort_by_key(|d| d.func);
312 let payload = kinds
314 .iter()
315 .map(|d| d.params)
316 .chain(textures.then_some(3))
317 .max()
318 .unwrap_or(1)
319 .max(1);
320 let stride = 1 + cdef.params + 4 + payload;
321 let layers = run
322 .links
323 .iter()
324 .map(|&l| match &self.spec[l].children[0] {
325 Child::External(e) => RunLayer {
326 kind: 0,
327 composite: l,
328 layer: LayerRef::Texture(*e),
329 },
330 Child::Node(g) => RunLayer {
331 kind: 1 + kinds
332 .iter()
333 .position(|d| d.func == self.spec[*g].def.func)
334 .expect("kind collected above"),
335 composite: l,
336 layer: LayerRef::Gen(*g),
337 },
338 })
339 .collect();
340 let slot = self.next_offset;
342 self.next_offset += 2;
343 self.layout.push(Slot::Run(self.runs.len()));
344 self.runs.push(RunLayout {
345 stride,
346 payload,
347 layers,
348 });
349 let v = self.var();
350 let id = self.vars;
351 let (i, o, q, k, f) = (
352 format!("i{id}"),
353 format!("o{id}"),
354 format!("q{id}"),
355 format!("k{id}"),
356 format!("f{id}"),
357 );
358 let mut code = format!(
359 " float4 {v} = {bgv};\n for (uint {i} = 0; {i} < uint(P[{count}]); {i}++) {{\n \
360 uint {o} = uint(P[{slot}]) + {i} * {stride};\n \
361 if (!in_rect({ctx}.pos, pf4({o} + {guard}))) continue;\n \
362 uint {k} = uint(P[{o}]);\n uint {q} = {o} + {layer};\n float4 {f} = float4(0.0);\n",
363 count = slot + 1,
364 guard = 1 + cdef.params,
365 layer = 1 + cdef.params + 4
366 );
367 let mut reads: Vec<(usize, String)> = Vec::new();
369 if textures {
370 let sample = self.texture_picker(false);
374 let sampled = format!(
375 "{f} = {sample}(b, ({ctx}.pos - pf2(ORIGINS_BASE_ + 3 * b)) / (pf2({q} + 1) * P[ORIGINS_BASE_ + 3 * b + 2]));"
376 );
377 reads.push((
378 0,
379 if identity {
380 let load = self.texture_picker(true);
381 format!(
382 "uint b = uint(P[{q}]); if (P[ORIGINS_BASE_ + 3 * b + 2] == P[1]) {{ \
383 int2 p = int2(gid.xy) - int2(round(pf2(ORIGINS_BASE_ + 3 * b) / P[1])); \
384 if (p.x >= 0 && p.y >= 0 && p.x < int(P[{q} + 1]) && p.y < int(P[{q} + 2])) {f} = {load}(b, p); }} \
385 else {{ {sampled} }}"
386 )
387 } else {
388 format!("uint b = uint(P[{q}]); {sampled}")
389 },
390 ));
391 }
392 for (x, d) in kinds.iter().enumerate() {
393 reads.push((x + 1, format!("{f} = g_{}({ctx}, {q});", d.func)));
394 }
395 if reads.len() == 1 {
396 code += &format!(" {}\n", reads[0].1);
397 } else {
398 for (x, (kind, read)) in reads.iter().enumerate() {
399 let branch = if x == 0 { "if" } else { "else if" };
400 code += &format!(" {branch} ({k} == {kind}) {{ {read} }}\n");
401 }
402 }
403 code += &format!(" {v} = f_{}({ctx}, {f}, {v}, {o} + 1);\n }}\n", cdef.func);
404 self.code += &code;
405 v
406 }
407
408 fn texture_picker(&mut self, identity: bool) -> String {
412 let name = format!("{NSID}_layer_{}", if identity { "load" } else { "sample" });
413 if !self.decls.contains(&format!("float4 {name}(")) {
414 let mut cases = String::new();
415 for t in 0..16 {
416 let read = if identity {
417 format!("T{t}.Load(int3(p, 0))")
418 } else {
419 format!("T{t}.SampleLevel(S, uv, 0)")
420 };
421 cases += &format!(" case {t}: return {read};\n");
422 }
423 let arg = if identity { "int2 p" } else { "float2 uv" };
424 self.decls += &format!(
425 "float4 {name}(uint b, {arg}) {{\n switch (b) {{\n{cases} default: return float4(0.0);\n }}\n}}\n"
426 );
427 }
428 name
429 }
430
431 fn node_inner(&mut self, n: usize, ctx: &str, identity: bool) -> String {
432 let s = &self.spec[n];
433 let def = s.def;
434 match def.form {
435 Form::Gen => {
436 let o = self.offset(n);
437 let v = self.var();
438 self.code += &format!(" float4 {v} = g_{}({ctx}, {o});\n", def.func);
439 v
440 }
441 Form::GenResource => {
442 let o = self.offset(n);
443 let t = self.texture(s.resource.expect("resource op without resource"));
444 let v = self.var();
445 self.code += &format!(" float4 {v} = g_{}({ctx}, {o}, {t});\n", def.func);
446 v
447 }
448 Form::Map if crate::ops::guarded(def) => {
449 let (fg, bg) = (s.children[0].clone(), s.children[1].clone());
453 let bgv = self.child(&bg, ctx, identity);
454 let o = self.offset(n);
455 let guard = o + def.params + s.gated as usize;
456 let v = self.var();
457 self.code += &format!(" float4 {v} = {bgv};\n if (in_rect({ctx}.pos, pf4({guard}))) {{\n");
458 let saved = self.memo.clone();
459 let fgv = self.child(&fg, ctx, identity);
460 self.memo = saved;
461 self.code += &format!(" {v} = f_{}({ctx}, {fgv}, {bgv}, {o});\n }}\n", def.func);
462 v
463 }
464 Form::Map => {
465 let children = s.children.clone();
466 let args: Vec<String> = children.iter().map(|c| self.child(c, ctx, identity)).collect();
467 let o = self.offset(n);
468 let res = match s.resource {
470 Some(r) => format!(", {}", self.texture(r)),
471 None => String::new(),
472 };
473 let v = self.var();
474 self.code += &format!(
475 " float4 {v} = f_{}({ctx}, {}, {o}{res});\n",
476 def.func,
477 args.join(", ")
478 );
479 v
480 }
481 Form::Warp => {
482 let o = self.offset(n);
483 let c = format!("c{}", self.vars + 1);
484 self.vars += 1;
485 self.code += &format!(" Ctx {c} = w_{}({ctx}, {o});\n", def.func);
486 let child = s.children[0].clone();
487 self.child(&child, &c, false)
488 }
489 Form::Displace => {
490 let (source, map) = (s.children[0].clone(), s.children[1].clone());
491 let m = self.child(&map, ctx, identity);
492 let o = self.offset(n);
493 let c = format!("c{}", self.vars + 1);
494 self.vars += 1;
495 self.code += &format!(" Ctx {c} = w_displace({ctx}, {m}, {o});\n");
496 self.child(&source, &c, false)
497 }
498 Form::Custom => {
499 let o = self.offset(n);
500 let ns = format!("{NSID}_cs{n}");
501 let mut cases = String::new();
502 for (port, c) in s.children.clone().iter().enumerate() {
503 let Child::External(e) = c else {
504 unreachable!("custom shader inputs are always materialized")
505 };
506 let t = self.texture(*e);
507 let o = self.origin(&t);
508 cases += &format!(" case {port}: return sample_t({t}, pos, {o});\n");
509 }
510 let code = s.code.clone().unwrap_or_default();
511 let tables = if s.tables > 0 {
512 crate::tables::declare_base(o + self.block(n))
513 } else {
514 String::new()
515 };
516 if self.declared.insert(n) {
517 self.decls += &format!(
518 "namespace {ns} {{\n\
519 static const uint PO = {o};\n\
520 {tables}\
521 float param(int i) {{ return P[PO + uint(i)]; }}\n\
522 float time() {{ return P[PO + 16]; }}\n\
523 float2 size() {{ return resolution(); }}\n\
524 float4 input(int i, float2 pos) {{\n switch (i) {{\n{cases} default: return float4(0.0);\n }}\n}}\n\
525 float4 from_srgb(float4 c) {{ return float4(srgb_to_linear(saturate(c.rgb)) * c.a, c.a); }}\n\
526 #line 1 \"shader\"\n\
527 {code}\n\
528 }}\n"
529 );
530 }
531 let v = self.var();
532 self.code += &format!(" float4 {v} = {ns}::shade({ctx}.pos, {ctx}.px);\n");
533 v
534 }
535 Form::Blur | Form::Raster | Form::Object | Form::Render3D | Form::Particles | Form::Sim => {
536 unreachable!("barriers and scene objects are never inlined")
537 }
538 }
539 }
540}
541
542pub fn generate(spec: &[SpecNode], root: usize) -> Generated {
544 let mut e = Emitter {
545 spec,
546 decls: String::new(),
547 code: String::new(),
548 vars: 0,
549 bindings: Vec::new(),
550 layout: Vec::new(),
551 runs: Vec::new(),
552 offsets: vec![None; spec.len()],
553 next_offset: 4,
554 memo: std::collections::HashMap::new(),
555 declared: std::collections::HashSet::new(),
556 };
557 let v = e.node(root, "c0", true);
558 let mut pad_textures = false;
561 let mut runs = std::mem::take(&mut e.runs);
562 for run in &mut runs {
563 for layer in &mut run.layers {
564 if let LayerRef::Texture(ext) = layer.layer {
565 pad_textures = true;
566 let b = e.bindings.iter().position(|&x| x == ext).unwrap_or_else(|| {
567 e.bindings.push(ext);
568 e.bindings.len() - 1
569 });
570 layer.layer = LayerRef::Texture(b);
571 }
572 }
573 }
574 let origins = e.next_offset;
576 for k in 0..e.bindings.len() {
577 let off = origins + 3 * k;
578 let ph = format!("ORIGIN_T{k}_");
579 e.code = e.code.replace(&ph, &off.to_string());
580 e.decls = e.decls.replace(&ph, &off.to_string());
581 }
582 e.code = e.code.replace("ORIGINS_BASE_", &origins.to_string());
583 e.layout.push(Slot::Origins);
584 let param_len = origins + 3 * e.bindings.len() + runs.iter().map(|r| r.stride * r.layers.len()).sum::<usize>();
586 let body = format!(
587 "{}\n[shader(\"compute\")]\n[numthreads(16, 16, 1)]\nvoid {ENTRY}(uint3 gid: SV_DispatchThreadID) {{\n \
588 if (outside_frame(gid.xy)) return;\n Ctx c0 = root_ctx(gid.xy);\n{} OUT.Store(gid.xy, {v});\n}}\n",
589 e.decls, e.code
590 );
591 let key = blake3::hash(body.as_bytes()).to_hex()[..24].to_string();
592 Generated {
593 body,
594 bindings: e.bindings,
595 layout: e.layout,
596 runs,
597 param_len,
598 pad_textures,
599 key,
600 }
601}
602
603pub fn single_op(def: &'static OpDef) -> Option<Generated> {
606 if matches!(
607 def.form,
608 Form::Blur | Form::Custom | Form::Raster | Form::Object | Form::Render3D | Form::Particles | Form::Sim
609 ) {
610 return None;
611 }
612 let spec = [SpecNode {
613 def,
614 children: (0..def.ports.len()).map(Child::External).collect(),
615 resource: crate::ops::uses_resource(def).then_some(def.ports.len()),
616 code: None,
617 tables: 0,
618 tag: 0,
619 gated: false,
620 }];
621 Some(generate(&spec, 0))
622}
623
624pub fn entry_name(key: &str) -> String {
626 format!("k_{key}")
627}
628
629pub fn module(kernels: &[(&str, &str)]) -> String {
632 let mut s = String::with_capacity(LIBRARY.len() + kernels.iter().map(|k| k.1.len() + 64).sum::<usize>());
633 s += LIBRARY;
634 let mut seen = std::collections::HashSet::new();
636 for (key, body) in kernels {
637 if !seen.insert(*key) {
638 continue;
639 }
640 let name = entry_name(key);
641 s += "\n";
642 s += &body.replace(ENTRY, &name).replace(NSID, &format!("k{key}"));
643 }
644 s
645}
646
647#[cfg(test)]
648mod tests {
649 use super::*;
650 use crate::ops::OPS;
651
652 fn def(func: &str) -> &'static OpDef {
653 OPS.iter().find(|d| d.func == func).unwrap()
654 }
655
656 #[test]
657 fn warp_over_generator_is_analytic() {
658 let spec = vec![
659 SpecNode {
660 def: def("shape"),
661 children: vec![],
662 resource: None,
663 code: None,
664 tables: 0,
665 tag: 0,
666 gated: false,
667 },
668 SpecNode {
669 def: def("transform"),
670 children: vec![Child::Node(0)],
671 resource: None,
672 code: None,
673 tables: 0,
674 tag: 1,
675 gated: false,
676 },
677 SpecNode {
678 def: def("over"),
679 children: vec![Child::Node(1), Child::External(7)],
680 resource: None,
681 code: None,
682 tables: 0,
683 tag: 2,
684 gated: false,
685 },
686 ];
687 let g = generate(&spec, 2);
688 assert!(g.body.contains("w_transform(c0, 10)"), "{}", g.body);
689 assert!(g.body.contains("if (in_rect(c0.pos, pf4(6)))"), "{}", g.body);
691 assert!(g.body.contains("g_shape(c"), "{}", g.body);
692 assert!(g.body.contains("load_t(T0, gid.xy, 30)"), "{}", g.body);
694 assert_eq!(g.bindings, vec![7]);
695 assert_eq!(g.param_len, 4 + 7 + 13 + 2 + 4 + 3);
698 }
699
700 fn chain(n: usize, texture_every: usize) -> Vec<SpecNode> {
701 let mut spec = Vec::new();
703 let mut below = Child::External(0);
704 for i in 0..n {
705 let layer = if texture_every > 0 && i % texture_every == 1 {
706 Child::External(10 + i)
707 } else {
708 spec.push(SpecNode {
709 def: def("shape"),
710 children: vec![],
711 resource: None,
712 code: None,
713 tables: 0,
714 tag: spec.len(),
715 gated: false,
716 });
717 Child::Node(spec.len() - 1)
718 };
719 spec.push(SpecNode {
720 def: def("over"),
721 children: vec![layer, below],
722 resource: None,
723 code: None,
724 tables: 0,
725 tag: spec.len(),
726 gated: true,
727 });
728 below = Child::Node(spec.len() - 1);
729 }
730 spec
731 }
732
733 #[test]
734 fn repeated_layers_loop_and_share_a_kernel_at_any_count() {
735 let a = chain(6, 0);
736 let b = chain(9, 0);
737 let (ga, gb) = (generate(&a, a.len() - 1), generate(&b, b.len() - 1));
738 assert!(ga.body.contains("for (uint"), "{}", ga.body);
739 assert_eq!(ga.key, gb.key);
740 assert_ne!(ga.param_len, gb.param_len);
741 assert!(!ga.pad_textures);
742 let c = chain(8, 3);
744 let d = chain(11, 3);
745 let (gc, gd) = (generate(&c, c.len() - 1), generate(&d, d.len() - 1));
746 assert_eq!(gc.key, gd.key);
747 assert!(gc.pad_textures);
748 assert_eq!(gc.bindings[0], 0);
749 let e = chain(3, 0);
751 assert!(!generate(&e, e.len() - 1).body.contains("for (uint"));
752 }
753
754 #[test]
755 fn same_structure_same_key() {
756 let a = single_op(def("over")).unwrap();
757 let b = single_op(def("over")).unwrap();
758 assert_eq!(a.key, b.key);
759 assert_ne!(a.key, single_op(def("mask")).unwrap().key);
760 }
761}
762
763pub mod feedback_params {
766 pub const U: usize = 4;
768 pub const TIME: usize = 20;
769 pub const DT: usize = 21;
770 pub const STEP: usize = 22;
772 pub const ORIGINS: usize = 24;
774 pub const SCALES: usize = 32;
776 pub const LEN: usize = 36;
777}
778
779pub fn feedback(code: &str, tables: bool) -> (String, String) {
784 use feedback_params::*;
785 let mut cases = String::new();
786 for i in 0..4 {
787 cases += &format!(
788 " case {i}: return sample_region(T{}, pos, pf2({}), P[{}]);\n",
789 i + 1,
790 ORIGINS + 2 * i,
791 SCALES + i
792 );
793 }
794 let tables = if tables {
795 crate::tables::declare_base(LEN)
796 } else {
797 String::new()
798 };
799 let body = format!(
800 "namespace {NSID}_fb {{\n\
801 {tables}\
802 float param(int i) {{ return P[{U} + uint(i)]; }}\n\
803 float time() {{ return P[{TIME}]; }}\n\
804 float dt() {{ return P[{DT}]; }}\n\
805 int step_index() {{ return int(P[{STEP}] + 0.5); }}\n\
806 float2 size() {{ return resolution(); }}\n\
807 float4 prev(float2 pos) {{ return sample_region(T0, pos, float2(0.0), P[1]); }}\n\
808 float4 prev_sharp(float2 pos) {{ return sample_sharp(T0, pos / P[1]); }}\n\
809 float4 input(int i, float2 pos) {{\n switch (i) {{\n{cases} default: return float4(0.0);\n }}\n}}\n\
810 float4 from_srgb(float4 c) {{ return float4(srgb_to_linear(saturate(c.rgb)) * c.a, c.a); }}\n\
811 #line 1 \"shader\"\n\
812 {code}\n\
813 }}\n\
814 [shader(\"compute\")]\n[numthreads(16, 16, 1)]\nvoid {ENTRY}(uint3 gid: SV_DispatchThreadID) {{\n \
815 if (outside_grid(gid.xy)) return;\n Ctx c0 = root_ctx(gid.xy);\n \
816 OUT.Store(gid.xy, {NSID}_fb::update(c0.pos, c0.px));\n}}\n"
817 );
818 let key = blake3::hash(body.as_bytes()).to_hex()[..24].to_string();
819 (key, body)
820}