cvkg-render-gpu 0.2.9

Cyber Viking Kvasir Graph (CVKG) - High-fidelity agentic UI framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
//! Material graph — composable shader generation.
//!
//! Replaces the mode-based `if/else` dispatch in shapes.wgsl with
//! composable material graphs that compile to WGSL at startup.
//!
//! # Architecture
//!
//! - `MaterialGraph` is a DAG of `MaterialNode`s connected by typed sockets.
//! - `MaterialCompiler` topologically sorts nodes and emits a WGSL fragment function.
//! - Built-in materials (rounded rect, glass, text, etc.) are pre-compiled at renderer init.
//! - User materials compile on first use and are cached by hash.

use std::collections::HashMap;

/// A socket type on a material node.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MaterialSocket {
    Color,    // vec4<f32>
    Float,    // f32
    Vec2,     // vec2<f32>
    Vec3,     // vec3<f32>
    Mask,     // f32 (0..1 coverage)
}

/// An operation node in the material graph.
#[derive(Debug, Clone)]
pub enum MaterialOp {
    /// Input: base color from vertex.
    /// Output: Color
    InputColor,

    /// Output: constant color from uniform.
    /// Parameters: rgba
    /// Output: Color
    ConstantColor { r: f32, g: f32, b: f32, a: f32 },

    /// Input: UV from vertex.
    /// Output: sample result Color
    SampleTexture { tex_index: u32 },

    /// Premultiplied alpha blend (for font atlas).
    /// Inputs: color (Color), alpha (Float from texture)
    /// Output: Color
    PremultipliedBlend,

    /// SDF rounded rectangle mask.
    /// Inputs: none (reads vertex logical, size, radius)
    /// Output: Mask
    SDFRoundRect,

    /// SDF ellipse mask.
    /// Output: Mask
    SDFEllipse,

    /// Linear gradient between two colors.
    /// Input: t (Float, typically UV-based)
    /// Output: Color
    LinearGradient { start: [f32; 4], end: [f32; 4] },

    /// Radial gradient.
    /// Input: dist (Float)
    /// Output: Color
    RadialGradient { start: [f32; 4], end: [f32; 4] },

    /// Neon glow effect.
    /// Input: dist (Float), color (Color)
    /// Output: Color
    NeonGlow { radius: f32, intensity: f32 },

    /// Glass fresnel refraction.
    /// Inputs: uv (Vec2), blur_mip (Float)
    /// Output: Color
    GlassBlur,

    /// Layer two inputs with a blend mode.
    /// Inputs: bottom (Color), top (Color), opacity (Float)
    /// Output: Color
    LayerBlend { mode: BlendMode },

    /// PBR lighting.
    /// Input: normal (Vec3), metallic (Float), roughness (Float), opacity (Float)
    /// Output: Color
    PBRLighting,

    /// Drop shadow.
    /// Inputs: uv (Vec2), size (Vec2), radius (Float)
    /// Output: Mask
    DropShadow,

    /// 9-slice UV remapping.
    /// Input: uv (Vec2)
    /// Output: Vec2
    NineSlice,

    /// Heatmap palette lookup.
    /// Input: value (Float)
    /// Output: Color
    Heatmap,

    /// Raymarched SDF shape.
    /// Output: Color
    Raymarch { shape: RaymarchShape },
}

#[derive(Debug, Clone, Copy)]
pub enum BlendMode {
    Add,
    Screen,
    Multiply,
    Overlay,
}

#[derive(Debug, Clone, Copy)]
pub enum RaymarchShape {
    Sphere,
    Box,
}

/// Connection between two nodes.
#[derive(Debug, Clone)]
pub struct MaterialEdge {
    pub from_node: u32,
    pub from_socket: MaterialSocket,
    pub to_node: u32,
    pub to_socket: MaterialSocket,
}

/// Index into the material graph's node list.
pub type MatNodeId = u32;

/// A directed acyclic graph of material operations.
#[derive(Debug, Clone)]
pub struct MaterialGraph {
    pub nodes: Vec<(MatNodeId, MaterialOp)>,
    pub edges: Vec<MaterialEdge>,
    pub output: Option<MatNodeId>,
}

impl MaterialGraph {
    pub fn new() -> Self {
        Self {
            nodes: Vec::new(),
            edges: Vec::new(),
            output: None,
        }
    }

    pub fn add_node(&mut self, op: MaterialOp) -> MatNodeId {
        let id = self.nodes.len() as MatNodeId;
        self.nodes.push((id, op));
        id
    }

    pub fn connect(
        &mut self,
        from: MatNodeId,
        from_socket: MaterialSocket,
        to: MatNodeId,
        to_socket: MaterialSocket,
    ) {
        self.edges.push(MaterialEdge {
            from_node: from,
            from_socket,
            to_node: to,
            to_socket,
        });
    }

    pub fn set_output(&mut self, node: MatNodeId) {
        self.output = Some(node);
    }

    /// Validate the graph: no cycles, output connected, all inputs satisfied.
    pub fn validate(&self) -> Result<(), MaterialError> {
        if self.output.is_none() {
            return Err(MaterialError::NoOutput);
        }
        // Cycle detection via DFS
        let mut visited = vec![false; self.nodes.len()];
        let mut in_stack = vec![false; self.nodes.len()];

        for &(id, _) in &self.nodes {
            if !visited[id as usize] {
                self.dfs_check(id, &mut visited, &mut in_stack)?;
            }
        }
        Ok(())
    }

    fn dfs_check(
        &self,
        node: MatNodeId,
        visited: &mut [bool],
        in_stack: &mut [bool],
    ) -> Result<(), MaterialError> {
        let idx = node as usize;
        if in_stack[idx] {
            return Err(MaterialError::Cycle);
        }
        if visited[idx] {
            return Ok(());
        }
        visited[idx] = true;
        in_stack[idx] = true;

        // Find all edges where this node is the consumer (to_node)
        for edge in &self.edges {
            if edge.to_node == node {
                self.dfs_check(edge.from_node, visited, in_stack)?;
            }
        }

        in_stack[idx] = false;
        Ok(())
    }
}

impl Default for MaterialGraph {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Debug)]
pub enum MaterialError {
    NoOutput,
    Cycle,
    DisconnectedInput { node: MatNodeId, socket: MaterialSocket },
    TypeMismatch { from: MaterialSocket, to: MaterialSocket },
    CompileError(String),
}

impl std::error::Error for MaterialError {}

impl std::fmt::Display for MaterialError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NoOutput => write!(f, "material graph has no output node"),
            Self::Cycle => write!(f, "material graph contains a cycle"),
            Self::DisconnectedInput { node, socket } => {
                write!(f, "node {:?} missing input {:?}", node, socket)
            }
            Self::TypeMismatch { from, to } => {
                write!(f, "type mismatch: {:?} -> {:?}", from, to)
            }
            Self::CompileError(msg) => write!(f, "compile error: {}", msg),
        }
    }
}

/// Compiled material — a WGSL function that can be included in the main shader.
#[derive(Debug, Clone)]
pub struct CompiledMaterial {
    /// The WGSL function body (everything between the `{` and `}` of the fragment function).
    pub wgsl_fn: String,
    /// The function name (unique per material).
    pub fn_name: String,
}

/// Compiles MaterialGraph → WGSL fragment function.
pub struct MaterialCompiler;

impl MaterialCompiler {
    /// Compile a material graph into a WGSL function.
    ///
    /// The emitted function has the signature:
    ///
    /// ```text
    /// fn material_<id>(in: VertexOutput, col: vec4<f32>) -> vec4<f32>
    /// ```
    ///
    /// where `in` provides UV/position/size/etc. from the vertex output,
    /// and `col` is the base vertex color.
    pub fn compile(graph: &MaterialGraph) -> Result<CompiledMaterial, MaterialError> {
        graph.validate()?;

        // Topological sort
        let order = Self::topo_sort(graph)?;

        // Generate WGSL for each node in order
        let mut lines: Vec<String> = Vec::new();
        let mut var_names: HashMap<(MatNodeId, MaterialSocket), String> = HashMap::new();
        let mut next_var = 0;

        let mut mk_var = |prefix: &str| -> String {
            let v = format!("{}_{}", prefix, next_var);
            next_var += 1;
            v
        };

        for &node_id in &order {
            let (_, op) = &graph.nodes[node_id as usize];
            let result_var = mk_var("v");

            let expr = match op {
                MaterialOp::InputColor => {
                    "col".to_string()
                }
                MaterialOp::ConstantColor { r, g, b, a } => {
                    format!("vec4<f32>({:.6}, {:.6}, {:.6}, {:.6})", r, g, b, a)
                }
                MaterialOp::SampleTexture { tex_index } => {
                    format!(
                        "textureSample(t_diffuse[{}u], s_diffuse, in.uv)",
                        tex_index
                    )
                }
                MaterialOp::PremultipliedBlend => {
                    let color_var = Self::find_input(&var_names, node_id, MaterialSocket::Color, graph)
                        .unwrap_or_else(|| "col".to_string());
                    // Read alpha from a separate texture sample — for fonts this is the single channel
                    let alpha_var = Self::find_input(&var_names, node_id, MaterialSocket::Float, graph)
                        .unwrap_or_else(|| "1.0".to_string());
                    format!(
                        "vec4<f32>(({}).rgb, ({}).a * ({}))",
                        color_var, color_var, alpha_var
                    )
                }
                MaterialOp::SDFRoundRect => {
                    let half = "in.size * 0.5";
                    format!(
                        r#"
    let _d = sd_round_rect(in.logical - {0}, {0} - in.radius, in.radius);
    let _aa = fwidth(_d);
    vec4<f32>(col.rgb, col.a * (1.0 - smoothstep(0.0, _aa, _d)))"#,
                        half
                    ).trim().to_string()
                }
                MaterialOp::SDFEllipse => {
                    let half = "in.size * 0.5";
                    format!(
                        r#"
    let _sh = max({0}, vec2<f32>(0.001));
    let _d = length((in.logical - {0}) / _sh) - 1.0;
    let _aa = fwidth(_d);
    vec4<f32>(col.rgb, col.a * (1.0 - smoothstep(0.0, _aa, _d)))"#,
                        half
                    ).trim().to_string()
                }
                MaterialOp::LinearGradient { start, end } => {
                    let t_var = Self::find_input(&var_names, node_id, MaterialSocket::Float, graph)
                        .unwrap_or_else(|| "in.uv.x".to_string());
                    format!(
                        "mix(vec4<f32>({:.6},{:.6},{:.6},{:.6}), vec4<f32>({:.6},{:.6},{:.6},{:.6}), clamp({}, 0.0, 1.0))",
                        start[0], start[1], start[2], start[3],
                        end[0], end[1], end[2], end[3],
                        t_var
                    )
                }
                MaterialOp::RadialGradient { start, end } => {
                    format!(
                        r#"
    let _dist = length(in.uv - 0.5) * 2.0;
    mix(vec4<f32>({:.6},{:.6},{:.6},{:.6}), vec4<f32>({:.6},{:.6},{:.6},{:.6}), clamp(_dist, 0.0, 1.0))"#,
                        start[0], start[1], start[2], start[3],
                        end[0], end[1], end[2], end[3],
                    ).trim().to_string()
                }
                MaterialOp::NeonGlow { radius, intensity } => {
                    let dist_var = Self::find_input(&var_names, node_id, MaterialSocket::Float, graph)
                        .unwrap_or_else(|| "length(in.logical - in.size * 0.5) / max(in.size.x, in.size.y)".to_string());
                    format!(
                        "vec4<f32>(col.rgb * exp(-{} * {:.6}), col.a)",
                        dist_var, intensity / radius.max(0.001)
                    )
                }
                MaterialOp::GlassBlur => {
                    r#"
    let _uv = clamp(in.uv, vec2<f32>(0.0), vec2<f32>(1.0));
    let _blur_mip = theme.glass_blur_strength;
    let _env_base = textureSampleLevel(t_env, s_env, _uv, _blur_mip).rgb;
    vec4<f32>(_env_base, 0.02 + pow(length(in.logical / in.size - 0.5) * 1.8, 2.5) * 0.15)"#.trim().to_string()
                }
                MaterialOp::LayerBlend { mode } => {
                    let bottom = Self::find_input(&var_names, node_id, MaterialSocket::Color, graph)
                        .unwrap_or_else(|| "col".to_string());
                    let top = Self::find_input_map(&var_names, node_id, MaterialSocket::Color, graph, 1)
                        .unwrap_or_else(|| "col".to_string());
                    let opacity = Self::find_input(&var_names, node_id, MaterialSocket::Float, graph)
                        .unwrap_or_else(|| "1.0".to_string());
                    match mode {
                        BlendMode::Add => {
                            format!("mix({}, {}, {})", bottom, top, opacity)
                        }
                        BlendMode::Screen => {
                            format!("mix({}, 1.0 - (1.0 - {}) * (1.0 - {}), {})", bottom, bottom, top, opacity)
                        }
                        BlendMode::Multiply => {
                            format!("mix({}, {} * {}, {})", bottom, bottom, top, opacity)
                        }
                        BlendMode::Overlay => {
                            format!("mix({}, select(2.0 * {} * {}, 1.0 - 2.0 * (1.0 - {}) * (1.0 - {}), step(vec4<f32>(0.5), {})), {})", bottom, bottom, top, bottom, top, bottom, opacity)
                        }
                    }
                }
                MaterialOp::PBRLighting => {
                    r#"
    let _n = normalize(in.normal);
    let _metallic = in.slice.x;
    let _roughness = in.slice.y;
    let _opacity = in.slice.z;
    let _ld = normalize(vec3<f32>(0.5, 0.8, 0.6));
    let _lc = vec3<f32>(1.0, 0.95, 0.9);
    let _ndl = max(dot(_n, _ld), 0.0);
    let _diffuse = _ndl * _lc;
    let _vd = vec3<f32>(0.0, 0.0, 1.0);
    let _hd = normalize(_ld + _vd);
    let _ndh = max(dot(_n, _hd), 0.0);
    let _shiny = mix(8.0, 256.0, 1.0 - _roughness);
    let _spec = pow(_ndh, _shiny) * _lc;
    let _f0 = mix(vec3<f32>(0.04), col.rgb, _metallic);
    let _fresnel = _f0 + (vec3<f32>(1.0) - _f0) * pow(1.0 - max(dot(_n, -_vd), 0.0), 5.0);
    let _amb = vec3<f32>(0.06, 0.07, 0.1);
    var _lit = col.rgb * (_amb + _diffuse);
    _lit += _spec * mix(vec3<f32>(1.0), col.rgb, _metallic) * _fresnel;
    let _depth = in.clip_position.z;
    let _fog = clamp(1.0 - _depth * 0.0005, 0.7, 1.0);
    _lit *= _fog;
    vec4<f32>(_lit, col.a * _opacity)"#.trim().to_string()
                }
                MaterialOp::DropShadow => {
                    r#"
    let _margin = in.uv.x;
    let _blur = max(in.uv.y, 1.0);
    let _original_size = in.size - 2.0 * _margin;
    let _half_size = _original_size * 0.5;
    let _p = in.logical - _margin - _half_size;
    let _d = length(max(abs(_p) - (_half_size - in.radius), vec2(0.0))) + min(max(abs(_p).x - (_half_size - in.radius).x, abs(_p).y - (_half_size - in.radius).y), 0.0) - in.radius;
    vec4<f32>(col.rgb, col.a * smoothstep(_blur, 0.0, _d))"#.trim().to_string()
                }
                MaterialOp::NineSlice => {
                    "col".to_string() // Passthrough: 9-slice UV remapping is resolved on CPU
                }
                MaterialOp::Heatmap => {
                    let val_var = Self::find_input(&var_names, node_id, MaterialSocket::Float, graph)
                        .unwrap_or_else(|| "textureSample(t_diffuse[0], s_diffuse, in.uv).r".to_string());
                    format!("vec4<f32>(heatmap_palette({}), col.a)", val_var)
                }
                MaterialOp::Raymarch { shape } => {
                    match shape {
                        RaymarchShape::Box => {
                            r#"
    let _uv = (in.uv - 0.5) * 2.0;
    let _ro = vec3<f32>(0.0, 0.0, -2.5);
    let _rd = normalize(vec3<f32>(_uv.x, _uv.y, 1.5));
    let _m = rotX(in.slice.x) * rotY(in.slice.y) * rotZ(in.slice.z);
    var _t = 0.0;
    var _hit = false;
    var _d = 0.0;
    for (var _i = 0; _i < 40; _i++) {
        let _p = _m * (_ro + _rd * _t);
        _d = sd_box_3d(_p, vec3(0.5, 0.5, 0.5));
        if _d < 0.001 {
            _hit = true;
            break;
        }
        _t += _d;
        if _t > 5.0 { break; }
    }
    if _hit {
        let _p2 = _m * (_ro + _rd * _t);
        let _eps = vec2(0.001, 0.0);
        let _n = normalize(vec3(
            sd_box_3d(_p2 + _eps.xyy, vec3(0.5)) - sd_box_3d(_p2 - _eps.xyy, vec3(0.5)),
            sd_box_3d(_p2 + _eps.yxy, vec3(0.5)) - sd_box_3d(_p2 - _eps.yxy, vec3(0.5)),
            sd_box_3d(_p2 + _eps.yyx, vec3(0.5)) - sd_box_3d(_p2 - _eps.yyx, vec3(0.5))
        ));
        let _ld2 = normalize(vec3(1.0, 1.0, -2.0));
        let _diff2 = max(dot(_n, _ld2), 0.1);
        let _rim = pow(1.0 - max(dot(_n, -_rd), 0.0), 3.0) * 0.5;
        vec4<f32>(col.rgb * _diff2 + _rim, col.a)
    } else {
        discard;
    }"#.trim().to_string()
                        }
                        RaymarchShape::Sphere => {
                            r#"
    let _ro = vec3<f32>(in.uv * 2.0 - 1.0, -2.0);
    let _rd = normalize(vec3<f32>(0.0, 0.0, 1.0));
    var _t = 0.0;
    var _hit = false;
    for (var i = 0; i < 32; i++) {
        let _p = _ro + _rd * _t;
        let _d = length(_p) - 1.0;
        if _d < 0.01 { _hit = true; break; }
        _t += _d;
    }
    if _hit {
        let _p = _ro + _rd * _t;
        let _n = normalize(_p);
        let _ld = normalize(vec3<f32>(1.0, 1.0, -1.0));
        let _diff = max(dot(_n, _ld), 0.0);
        vec4<f32>(col.rgb * _diff, col.a)
    } else {
        discard;
    }"#.trim().to_string()
                        }
                    }
                }
            };

            lines.push(format!("    var {} = {};", result_var, expr));
            var_names.insert((node_id, MaterialSocket::Color), result_var);
        }

        let body = lines.join("\n");
        let out_id = graph.output.ok_or(MaterialError::NoOutput)?;
        let fn_name = format!("material_{}", out_id);

        let wgsl_fn = format!(
            "fn {}(in: VertexOutput, col: vec4<f32>) -> vec4<f32> {{\n{}\n    return v_{};\n}}",
            fn_name, body, out_id
        );

        Ok(CompiledMaterial { wgsl_fn, fn_name })
    }

    fn find_input(
        names: &HashMap<(MatNodeId, MaterialSocket), String>,
        node: MatNodeId,
        socket: MaterialSocket,
        graph: &MaterialGraph,
    ) -> Option<String> {
        for edge in &graph.edges {
            if edge.to_node == node && edge.to_socket == socket {
                return names.get(&(edge.from_node, edge.from_socket)).cloned();
            }
        }
        None
    }

    fn find_input_map(
        names: &HashMap<(MatNodeId, MaterialSocket), String>,
        node: MatNodeId,
        socket: MaterialSocket,
        graph: &MaterialGraph,
        offset: usize,
    ) -> Option<String> {
        let mut matches = graph.edges.iter().filter(|e| e.to_node == node && e.to_socket == socket);
        let edge = matches.nth(offset)?;
        names.get(&(edge.from_node, edge.from_socket)).cloned()
    }

    fn topo_sort(graph: &MaterialGraph) -> Result<Vec<MatNodeId>, MaterialError> {
        let n = graph.nodes.len();
        let mut in_degree = vec![0u32; n];
        let mut adj: Vec<Vec<MatNodeId>> = vec![Vec::new(); n];

        for edge in &graph.edges {
            adj[edge.from_node as usize].push(edge.to_node);
            in_degree[edge.to_node as usize] += 1;
        }

        let mut queue: std::collections::VecDeque<MatNodeId> = std::collections::VecDeque::new();
        for (i, &deg) in in_degree.iter().enumerate() {
            if deg == 0 {
                queue.push_back(i as MatNodeId);
            }
        }

        let mut order = Vec::with_capacity(n);
        while let Some(node) = queue.pop_front() {
            order.push(node);
            for &next in &adj[node as usize] {
                in_degree[next as usize] -= 1;
                if in_degree[next as usize] == 0 {
                    queue.push_back(next);
                }
            }
        }

        if order.len() != n {
            return Err(MaterialError::Cycle);
        }

        Ok(order)
    }
}

/// Pre-built material graphs for the built-in modes.
/// These replace the if/else chains in shapes.wgsl.
pub mod builtins {
    use super::*;

    /// Build a rounded rectangle material (old mode 3).
    pub fn rounded_rect() -> MaterialGraph {
        let mut g = MaterialGraph::new();
        let input = g.add_node(MaterialOp::InputColor);
        let sdf = g.add_node(MaterialOp::SDFRoundRect);
        // The SDF node reads vertex data directly; input color provides the base
        g.connect(input, MaterialSocket::Color, sdf, MaterialSocket::Color);
        g.set_output(sdf);
        g
    }

    /// Build a glass material (old mode 7).
    pub fn glass() -> MaterialGraph {
        let mut g = MaterialGraph::new();
        let glass = g.add_node(MaterialOp::GlassBlur);
        g.set_output(glass);
        g
    }

    /// Build a solid color material (old mode 0 / default).
    pub fn solid() -> MaterialGraph {
        let mut g = MaterialGraph::new();
        let input = g.add_node(MaterialOp::InputColor);
        g.set_output(input);
        g
    }

    /// Build a PBR material (old mode 13).
    pub fn pbr() -> MaterialGraph {
        let mut g = MaterialGraph::new();
        let input = g.add_node(MaterialOp::InputColor);
        let pbr = g.add_node(MaterialOp::PBRLighting);
        g.connect(input, MaterialSocket::Color, pbr, MaterialSocket::Color);
        g.set_output(pbr);
        g
    }

    /// Build a text material (old mode 6) with premultiplied alpha.
    pub fn text(tex_index: u32) -> MaterialGraph {
        let mut g = MaterialGraph::new();
        let input = g.add_node(MaterialOp::InputColor);
        let tex = g.add_node(MaterialOp::SampleTexture { tex_index });
        let blend = g.add_node(MaterialOp::PremultipliedBlend);
        g.connect(input, MaterialSocket::Color, blend, MaterialSocket::Color);
        g.connect(tex, MaterialSocket::Float, blend, MaterialSocket::Float);
        g.set_output(blend);
        g
    }

    /// Build a texture sample material (old mode 2).
    pub fn textured(tex_index: u32) -> MaterialGraph {
        let mut g = MaterialGraph::new();
        let input = g.add_node(MaterialOp::InputColor);
        let tex = g.add_node(MaterialOp::SampleTexture { tex_index });
        let blend = g.add_node(MaterialOp::LayerBlend { mode: BlendMode::Multiply });
        g.connect(input, MaterialSocket::Color, blend, MaterialSocket::Color);
        g.connect(tex, MaterialSocket::Color, blend, MaterialSocket::Color);
        g.set_output(blend);
        g
    }

    /// Build a neon glow material (old mode 8).
    pub fn neon_glow(radius: f32, intensity: f32) -> MaterialGraph {
        let mut g = MaterialGraph::new();
        let input = g.add_node(MaterialOp::InputColor);
        let glow = g.add_node(MaterialOp::NeonGlow { radius, intensity });
        g.connect(input, MaterialSocket::Color, glow, MaterialSocket::Color);
        g.set_output(glow);
        g
    }

    /// Build a linear gradient material (old mode 15).
    pub fn linear_gradient(start: [f32; 4], end: [f32; 4]) -> MaterialGraph {
        let mut g = MaterialGraph::new();
        let grad = g.add_node(MaterialOp::LinearGradient { start, end });
        g.set_output(grad);
        g
    }

    /// Build a radial gradient material (old mode 16).
    pub fn radial_gradient(start: [f32; 4], end: [f32; 4]) -> MaterialGraph {
        let mut g = MaterialGraph::new();
        let grad = g.add_node(MaterialOp::RadialGradient { start, end });
        g.set_output(grad);
        g
    }

    /// Build an ellipse material (old mode 4).
    pub fn ellipse() -> MaterialGraph {
        let mut g = MaterialGraph::new();
        let input = g.add_node(MaterialOp::InputColor);
        let sdf = g.add_node(MaterialOp::SDFEllipse);
        g.connect(input, MaterialSocket::Color, sdf, MaterialSocket::Color);
        g.set_output(sdf);
        g
    }

    /// Build a neon line material (old mode 1).
    pub fn neon_line() -> MaterialGraph {
        let mut g = MaterialGraph::new();
        let color = g.add_node(MaterialOp::ConstantColor { r: 1.5, g: 1.5, b: 1.5, a: 1.0 });
        g.set_output(color);
        g
    }

    /// Build a heatmap material (old mode 12).
    pub fn heatmap(tex_index: u32) -> MaterialGraph {
        let mut g = MaterialGraph::new();
        let tex = g.add_node(MaterialOp::SampleTexture { tex_index });
        let hm = g.add_node(MaterialOp::Heatmap);
        g.connect(tex, MaterialSocket::Float, hm, MaterialSocket::Float);
        g.set_output(hm);
        g
    }

    /// Build a 9-slice material (old mode 20).
    pub fn nine_slice(tex_index: u32) -> MaterialGraph {
        let mut g = MaterialGraph::new();
        let input = g.add_node(MaterialOp::InputColor);
        let tex = g.add_node(MaterialOp::SampleTexture { tex_index });
        let blend = g.add_node(MaterialOp::LayerBlend { mode: BlendMode::Multiply });
        g.connect(input, MaterialSocket::Color, blend, MaterialSocket::Color);
        g.connect(tex, MaterialSocket::Color, blend, MaterialSocket::Color);
        g.set_output(blend);
        g
    }

    /// Build a raymarched cube material (old mode 21).
    pub fn raymarch_cube() -> MaterialGraph {
        let mut g = MaterialGraph::new();
        let input = g.add_node(MaterialOp::InputColor);
        let rm = g.add_node(MaterialOp::Raymarch { shape: RaymarchShape::Box });
        g.connect(input, MaterialSocket::Color, rm, MaterialSocket::Color);
        g.set_output(rm);
        g
    }

    /// Build a stroke material (old mode 17).
    pub fn stroke() -> MaterialGraph {
        let mut g = MaterialGraph::new();
        let input = g.add_node(MaterialOp::InputColor);
        let sdf = g.add_node(MaterialOp::SDFRoundRect);
        g.connect(input, MaterialSocket::Color, sdf, MaterialSocket::Color);
        g.set_output(sdf);
        g
    }

    /// Build a drop shadow material (old mode 18).
    pub fn drop_shadow() -> MaterialGraph {
        let mut g = MaterialGraph::new();
        let input = g.add_node(MaterialOp::InputColor);
        let shadow = g.add_node(MaterialOp::DropShadow);
        g.connect(input, MaterialSocket::Color, shadow, MaterialSocket::Color);
        g.set_output(shadow);
        g
    }

    /// Build a dashed stroke material (old mode 19).
    pub fn dashed_stroke() -> MaterialGraph {
        let mut g = MaterialGraph::new();
        let input = g.add_node(MaterialOp::InputColor);
        let sdf = g.add_node(MaterialOp::SDFRoundRect);
        g.connect(input, MaterialSocket::Color, sdf, MaterialSocket::Color);
        g.set_output(sdf);
        g
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_solid_material_compiles() {
        let graph = builtins::solid();
        let compiled = MaterialCompiler::compile(&graph).unwrap();
        assert!(compiled.wgsl_fn.contains("fn material_"));
        assert!(compiled.wgsl_fn.contains("col"));
    }

    #[test]
    fn test_rounded_rect_compiles() {
        let graph = builtins::rounded_rect();
        let compiled = MaterialCompiler::compile(&graph).unwrap();
        assert!(compiled.wgsl_fn.contains("sd_round_rect"));
    }

    #[test]
    fn test_pbr_compiles() {
        let graph = builtins::pbr();
        let compiled = MaterialCompiler::compile(&graph).unwrap();
        assert!(compiled.wgsl_fn.contains("PBRLighting") || compiled.wgsl_fn.contains("_n"));
    }

    #[test]
    fn test_graph_validation_no_output() {
        let mut g = MaterialGraph::new();
        g.add_node(MaterialOp::InputColor);
        assert!(g.validate().is_err());
    }

    #[test]
    fn test_graph_validation_cycle() {
        let mut g = MaterialGraph::new();
        let a = g.add_node(MaterialOp::InputColor);
        let b = g.add_node(MaterialOp::NeonGlow { radius: 1.0, intensity: 1.0 });
        g.connect(a, MaterialSocket::Color, b, MaterialSocket::Color);
        g.connect(b, MaterialSocket::Color, a, MaterialSocket::Color); // cycle!
        g.set_output(b);
        assert!(g.validate().is_err());
    }

    #[test]
    fn test_all_builtins_compile() {
        let graphs: Vec<MaterialGraph> = vec![
            builtins::solid(),
            builtins::rounded_rect(),
            builtins::glass(),
            builtins::pbr(),
            builtins::text(0),
            builtins::textured(0),
            builtins::neon_glow(4.0, 1.5),
            builtins::linear_gradient([1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0]),
            builtins::radial_gradient([1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0]),
            builtins::ellipse(),
            builtins::neon_line(),
            builtins::heatmap(0),
            builtins::nine_slice(0),
            builtins::raymarch_cube(),
            builtins::stroke(),
            builtins::drop_shadow(),
            builtins::dashed_stroke(),
        ];

        for (i, graph) in graphs.iter().enumerate() {
            match MaterialCompiler::compile(graph) {
                Ok(compiled) => {
                    assert!(!compiled.wgsl_fn.is_empty(), "graph {} produced empty WGSL", i);
                    assert!(!compiled.fn_name.is_empty(), "graph {} produced empty fn name", i);
                }
                Err(e) => {
                    panic!("graph {} failed to compile: {}", i, e);
                }
            }
        }
    }
}