shadertoy-cli 2.2.5

Agent-friendly ShaderToy project, rendering, debugging, and live-preview CLI
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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
use anyhow::{Context, Result, bail};
use schemars::{JsonSchema, schema_for};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap, HashSet};

use crate::uniforms::{UniformDefinition, UniformValue, validate_definitions};
use std::fs;
use std::path::{Component, Path, PathBuf};

pub const MANIFEST_NAME: &str = "ShaderToy.toml";
pub const FORMAT_VERSION: u32 = 1;
pub const MAX_RENDER_DIMENSION: u32 = 16384;
pub const MAX_RENDER_FPS: f32 = 1000.0;
const RESERVED_INPUT_NAMES: [&str; 3] = ["keyboard", "music", "webcam"];

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Manifest {
    /// Project manifest format version. Version 1 is the only supported value.
    pub format: u32,
    pub project: ProjectSection,
    #[serde(default)]
    pub render: RenderSection,
    #[serde(default)]
    pub shader: ShaderSection,
    #[serde(default, rename = "uniform", skip_serializing_if = "Vec::is_empty")]
    pub uniforms: Vec<UniformDefinition>,
    #[serde(default, rename = "asset", skip_serializing_if = "Vec::is_empty")]
    pub assets: Vec<Asset>,
    #[serde(rename = "pass")]
    pub passes: Vec<Pass>,
    #[serde(default, rename = "test", skip_serializing_if = "Vec::is_empty")]
    pub tests: Vec<TestCase>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ProjectSection {
    /// Human-readable project name.
    pub name: String,
    /// Original ShaderToy author, when this project was imported.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub author: Option<String>,
    /// Original ShaderToy description, when this project was imported.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Canonical source URL for imported projects.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_url: Option<String>,
    /// ShaderToy shader id for imported projects.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_id: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct RenderSection {
    /// Default render/preview width in pixels.
    pub width: u32,
    /// Default render/preview height in pixels.
    pub height: u32,
    /// Fixed timestep frame rate used by deterministic rendering.
    pub fps: f32,
    /// Representative time used by `shadertoy render` when no frame/time is supplied.
    pub preview_time: f32,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct ShaderSection {
    /// Project-relative directories searched after the including file's directory for quoted #include paths.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub include_dirs: Vec<String>,
}

impl Default for RenderSection {
    fn default() -> Self {
        Self {
            width: 1280,
            height: 720,
            fps: 60.0,
            preview_time: 1.0,
        }
    }
}

fn default_test_tolerance() -> f32 {
    0.002
}

fn is_zero_f32(value: &f32) -> bool {
    *value == 0.0
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct TestCase {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pass: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub frame: Option<i32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub time: Option<f32>,
    /// Additional deterministic frames. Mutually exclusive with frame/time.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub frames: Vec<i32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub width: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub height: Option<u32>,
    /// Output-resolution matrix. Mutually exclusive with width/height.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub resolutions: Vec<[u32; 2]>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reference: Option<String>,
    #[serde(default = "default_test_tolerance")]
    pub tolerance: f32,
    #[serde(default)]
    pub assert_no_nan: bool,
    #[serde(default)]
    pub assert_no_inf: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mean_range: Option<[f32; 2]>,
    /// Re-run every matrix entry from a fresh runtime and require identical output.
    #[serde(default)]
    pub assert_deterministic: bool,
    /// Require a fixed-size buffer/compute pass to be unchanged by output resolution.
    #[serde(default)]
    pub assert_resolution_independent: bool,
    /// Absolute tolerance for raw floating-point comparisons.
    #[serde(default, skip_serializing_if = "is_zero_f32")]
    pub raw_tolerance: f32,
    /// Per-test custom uniform overrides.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub uniforms: BTreeMap<String, UniformValue>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum PassKind {
    Image,
    Buffer,
    Cubemap,
    Compute,
    Sound,
}

#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum RenderFormat {
    R32f,
    Rg32f,
    Rgba16f,
    #[default]
    Rgba32f,
}

fn default_iterations() -> u32 {
    1
}

fn is_default_iterations(value: &u32) -> bool {
    *value == 1
}

fn is_default_render_format(value: &RenderFormat) -> bool {
    *value == RenderFormat::Rgba32f
}

fn is_zero_u8(value: &u8) -> bool {
    *value == 0
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct StorageBuffer {
    /// Shader storage binding index used by an explicit std430 binding.
    pub binding: u32,
    /// Shared resource name. Bindings with the same name share persistent GPU storage across passes.
    pub name: String,
    /// Persistent storage size in bytes.
    pub size: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Pass {
    /// Unique pass name. Names are used by inspect/render/debug commands.
    pub name: String,
    pub kind: PassKind,
    /// GLSL source path relative to the project root.
    pub source: String,
    /// Optional fixed width for a buffer/compute pass. Must be paired with height.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub width: Option<u32>,
    /// Optional fixed height for a buffer/compute pass. Must be paired with width.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub height: Option<u32>,
    /// Floating-point render-target format for buffer/compute outputs.
    #[serde(default, skip_serializing_if = "is_default_render_format")]
    pub format: RenderFormat,
    /// Additional render targets beyond output 0. Indices are 1-based after the primary format.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub extra_outputs: Vec<RenderFormat>,
    /// Number of compute dispatches per rendered frame. iIteration is 0-based.
    #[serde(
        default = "default_iterations",
        skip_serializing_if = "is_default_iterations"
    )]
    pub iterations: u32,
    /// Compute local workgroup dimensions. Defaults to [8, 8, 1]; Z must be 1 for the 2D mainCompute entrypoint.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub local_size: Option<[u32; 3]>,
    /// Persistent shader-storage buffers bound for this pass.
    #[serde(default, rename = "storage", skip_serializing_if = "Vec::is_empty")]
    pub storage: Vec<StorageBuffer>,
    #[serde(default, rename = "input", skip_serializing_if = "Vec::is_empty")]
    pub inputs: Vec<Input>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum InputKind {
    Pass,
    Texture,
    Cubemap,
    Volume,
    Keyboard,
    Music,
    Video,
    Webcam,
}

#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum FrameRef {
    #[default]
    Current,
    Previous,
}

#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum Filter {
    Mipmap,
    #[default]
    Linear,
    Nearest,
}

#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum Wrap {
    Clamp,
    #[default]
    Repeat,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Input {
    /// ShaderToy iChannel index. Must be between 0 and 3.
    pub channel: u8,
    /// Pass/asset name, or the reserved names "keyboard" and "music".
    pub source: String,
    /// Optional explicit source kind. Normally inferred from the source name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kind: Option<InputKind>,
    /// Render-target index when consuming another pass. Output 0 is the primary target.
    #[serde(default, skip_serializing_if = "is_zero_u8")]
    pub output: u8,
    #[serde(default)]
    pub frame: FrameRef,
    /// Per-input texture interpolation/minification mode.
    /// nearest = exact texel sampling, linear = bilinear interpolation,
    /// mipmap = trilinear minification with linear magnification.
    #[serde(default)]
    pub filter: Filter,
    /// Per-input texture coordinate addressing mode.
    #[serde(default)]
    pub wrap: Wrap,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum AssetKind {
    Texture,
    Cubemap,
    Volume,
    Video,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Asset {
    /// Unique asset name used by pass inputs.
    pub name: String,
    /// Asset decoder/layout selected for this file. Cubemap assets are horizontal six-face strips; volume assets use the ShaderToy 20-byte binary header documented by `shadertoy docs assets`.
    pub kind: AssetKind,
    /// Asset file path relative to the project root. See `shadertoy docs assets` for cubemap and volume on-disk layouts.
    pub path: String,
}

#[derive(Debug, Clone)]
pub struct LoadedManifest {
    pub root: PathBuf,
    pub manifest: Manifest,
}

impl Manifest {
    pub fn minimal(name: impl Into<String>) -> Self {
        Self {
            format: FORMAT_VERSION,
            project: ProjectSection {
                name: name.into(),
                author: None,
                description: None,
                source_url: None,
                source_id: None,
            },
            render: RenderSection::default(),
            shader: ShaderSection::default(),
            uniforms: Vec::new(),
            assets: Vec::new(),
            passes: vec![Pass {
                name: "image".into(),
                kind: PassKind::Image,
                source: "shaders/image.frag".into(),
                width: None,
                height: None,
                format: RenderFormat::default(),
                extra_outputs: Vec::new(),
                iterations: 1,
                local_size: None,
                storage: Vec::new(),
                inputs: Vec::new(),
            }],
            tests: Vec::new(),
        }
    }

    pub fn multipass(name: impl Into<String>) -> Self {
        Self {
            format: FORMAT_VERSION,
            project: ProjectSection {
                name: name.into(),
                author: None,
                description: None,
                source_url: None,
                source_id: None,
            },
            render: RenderSection::default(),
            shader: ShaderSection::default(),
            uniforms: Vec::new(),
            assets: Vec::new(),
            passes: vec![
                Pass {
                    name: "buffer-a".into(),
                    kind: PassKind::Buffer,
                    source: "shaders/buffer-a.frag".into(),
                    width: None,
                    height: None,
                    format: RenderFormat::default(),
                    extra_outputs: Vec::new(),
                    iterations: 1,
                    local_size: None,
                    storage: Vec::new(),
                    inputs: vec![Input {
                        channel: 0,
                        source: "buffer-a".into(),
                        kind: Some(InputKind::Pass),
                        output: 0,
                        frame: FrameRef::Previous,
                        filter: Filter::Linear,
                        wrap: Wrap::Clamp,
                    }],
                },
                Pass {
                    name: "image".into(),
                    kind: PassKind::Image,
                    source: "shaders/image.frag".into(),
                    width: None,
                    height: None,
                    format: RenderFormat::default(),
                    extra_outputs: Vec::new(),
                    iterations: 1,
                    local_size: None,
                    storage: Vec::new(),
                    inputs: vec![Input {
                        channel: 0,
                        source: "buffer-a".into(),
                        kind: Some(InputKind::Pass),
                        output: 0,
                        frame: FrameRef::Current,
                        filter: Filter::Linear,
                        wrap: Wrap::Clamp,
                    }],
                },
            ],
            tests: Vec::new(),
        }
    }

    pub fn validate_structure(&self) -> Result<()> {
        if self.format != FORMAT_VERSION {
            bail!(
                "unsupported ShaderToy.toml format {}; supported format is {}",
                self.format,
                FORMAT_VERSION
            );
        }
        if self.project.name.trim().is_empty() {
            bail!("project.name must not be empty");
        }
        if self.render.width == 0 || self.render.height == 0 {
            bail!("render width and height must be positive");
        }
        if self.render.width > MAX_RENDER_DIMENSION || self.render.height > MAX_RENDER_DIMENSION {
            bail!("render dimensions exceed the {MAX_RENDER_DIMENSION} pixel safety limit");
        }
        if !self.render.fps.is_finite()
            || self.render.fps <= 0.0
            || self.render.fps > MAX_RENDER_FPS
        {
            bail!("render.fps must be finite and in the range (0, {MAX_RENDER_FPS}]");
        }
        if !self.render.preview_time.is_finite() || self.render.preview_time < 0.0 {
            bail!("render.preview_time must be a finite non-negative number");
        }
        for include_dir in &self.shader.include_dirs {
            validate_project_relative_path(include_dir, "shader.include_dirs entry")?;
        }
        validate_definitions(&self.uniforms)?;
        if self.passes.is_empty() {
            bail!("project must contain at least one [[pass]]");
        }

        let mut names = HashSet::new();
        let mut pass_kinds = HashMap::new();
        let mut image_count = 0usize;
        for pass in &self.passes {
            if pass.name.trim().is_empty() {
                bail!("pass name must not be empty");
            }
            if is_reserved_input_name(&pass.name) {
                bail!("pass name '{}' is reserved for a built-in input", pass.name);
            }
            validate_project_relative_path(
                &pass.source,
                &format!("source for pass '{}'", pass.name),
            )?;
            if !names.insert(pass.name.as_str()) {
                bail!("duplicate pass/asset name '{}'", pass.name);
            }
            match (pass.width, pass.height) {
                (None, None) => {
                    if pass.kind == PassKind::Compute {
                        bail!("compute pass '{}' must specify width and height", pass.name);
                    }
                }
                (Some(width), Some(height)) => {
                    if pass.kind != PassKind::Buffer && pass.kind != PassKind::Compute {
                        bail!(
                            "fixed width/height are only supported for buffer/compute passes ('{}')",
                            pass.name
                        );
                    }
                    if width == 0 || height == 0 {
                        bail!("fixed pass dimensions must be positive ('{}')", pass.name);
                    }
                    if width > MAX_RENDER_DIMENSION || height > MAX_RENDER_DIMENSION {
                        bail!(
                            "fixed pass dimensions for '{}' exceed the {} pixel safety limit",
                            pass.name,
                            MAX_RENDER_DIMENSION
                        );
                    }
                }
                _ => bail!(
                    "pass '{}' must specify both width and height or neither",
                    pass.name
                ),
            }
            if !matches!(pass.kind, PassKind::Buffer | PassKind::Compute)
                && pass.format != RenderFormat::Rgba32f
            {
                bail!(
                    "pass '{}' can only set format on buffer/compute passes",
                    pass.name
                );
            }
            if !pass.extra_outputs.is_empty()
                && !matches!(pass.kind, PassKind::Buffer | PassKind::Compute)
            {
                bail!(
                    "pass '{}' extra_outputs are only valid for buffer/compute passes",
                    pass.name
                );
            }
            if pass.extra_outputs.len() > 7 {
                bail!("pass '{}' may expose at most 8 render targets", pass.name);
            }
            if pass.iterations == 0 || pass.iterations > 4096 {
                bail!("pass '{}' iterations must be in 1..=4096", pass.name);
            }
            if pass.kind != PassKind::Compute && pass.iterations != 1 {
                bail!(
                    "pass '{}' iterations are currently supported only for compute passes",
                    pass.name
                );
            }
            if let Some([x, y, z]) = pass.local_size {
                if pass.kind != PassKind::Compute {
                    bail!(
                        "pass '{}' local_size is only valid for compute passes",
                        pass.name
                    );
                }
                if x == 0 || y == 0 || z == 0 || u64::from(x) * u64::from(y) * u64::from(z) > 1024 {
                    bail!(
                        "pass '{}' local_size must be positive and at most 1024 total invocations",
                        pass.name
                    );
                }
                if z != 1 {
                    bail!(
                        "pass '{}' local_size z must be 1 because mainCompute receives 2D coordinates",
                        pass.name
                    );
                }
            }
            let mut storage_bindings = HashSet::new();
            for storage in &pass.storage {
                if storage.name.trim().is_empty() {
                    bail!(
                        "pass '{}' has a storage buffer with an empty name",
                        pass.name
                    );
                }
                if storage.size == 0 {
                    bail!(
                        "pass '{}' storage buffer '{}' must have a positive size",
                        pass.name,
                        storage.name
                    );
                }
                if !storage_bindings.insert(storage.binding) {
                    bail!(
                        "pass '{}' binds storage slot {} more than once",
                        pass.name,
                        storage.binding
                    );
                }
            }
            if pass.kind == PassKind::Image {
                image_count += 1;
            }
            pass_kinds.insert(pass.name.as_str(), pass.kind);
        }

        let mut asset_names = HashSet::new();
        let mut asset_kinds = HashMap::new();
        for asset in &self.assets {
            if asset.name.trim().is_empty() {
                bail!("asset name must not be empty");
            }
            if is_reserved_input_name(&asset.name) {
                bail!(
                    "asset name '{}' is reserved for a built-in input",
                    asset.name
                );
            }
            validate_project_relative_path(
                &asset.path,
                &format!("path for asset '{}'", asset.name),
            )?;
            if !names.insert(asset.name.as_str()) || !asset_names.insert(asset.name.as_str()) {
                bail!("duplicate pass/asset name '{}'", asset.name);
            }
            asset_kinds.insert(asset.name.as_str(), asset.kind);
        }

        if image_count != 1 {
            bail!("project must contain exactly one image pass (found {image_count})");
        }

        let mut storage_sizes = HashMap::new();
        for pass in &self.passes {
            for storage in &pass.storage {
                if let Some(existing) = storage_sizes.insert(storage.name.as_str(), storage.size)
                    && existing != storage.size
                {
                    bail!(
                        "storage buffer '{}' uses inconsistent sizes ({} vs {})",
                        storage.name,
                        existing,
                        storage.size
                    );
                }
            }
        }

        for pass in &self.passes {
            let mut channels = HashSet::new();
            for input in &pass.inputs {
                if input.channel > 3 {
                    bail!(
                        "pass '{}' uses invalid channel {}; valid channels are 0..3",
                        pass.name,
                        input.channel
                    );
                }
                if !channels.insert(input.channel) {
                    bail!(
                        "pass '{}' assigns iChannel{} more than once",
                        pass.name,
                        input.channel
                    );
                }
                let kind = self.infer_input_kind(input)?;
                if kind != InputKind::Pass && input.output != 0 {
                    bail!(
                        "pass '{}' channel {} selects output {} on a non-pass input",
                        pass.name,
                        input.channel,
                        input.output
                    );
                }
                if input.frame == FrameRef::Previous && kind != InputKind::Pass {
                    bail!(
                        "pass '{}' channel {} uses previous frame on a non-pass input",
                        pass.name,
                        input.channel
                    );
                }
                if input.frame == FrameRef::Previous && input.output != 0 {
                    bail!(
                        "pass '{}' channel {} uses previous-frame feedback from output {}; only output 0 is resumable",
                        pass.name,
                        input.channel,
                        input.output
                    );
                }
                if kind == InputKind::Pass {
                    let Some(source_kind) = pass_kinds.get(input.source.as_str()) else {
                        bail!(
                            "pass '{}' channel {} references unknown pass '{}'",
                            pass.name,
                            input.channel,
                            input.source
                        );
                    };
                    if input.frame == FrameRef::Previous && *source_kind == PassKind::Image {
                        bail!("the final image pass cannot be a previous-frame source");
                    }
                    if *source_kind == PassKind::Sound {
                        bail!("sound passes cannot be used as iChannel sources");
                    }
                    if pass.kind == PassKind::Sound {
                        bail!(
                            "sound passes currently support static/keyboard/music inputs, not pass inputs"
                        );
                    }
                    let source_pass = self
                        .passes
                        .iter()
                        .find(|candidate| candidate.name == input.source)
                        .expect("pass kind map and pass list stay in sync");
                    if usize::from(input.output) > source_pass.extra_outputs.len() {
                        bail!(
                            "pass '{}' channel {} selects output {} from '{}', which exposes outputs 0..{}",
                            pass.name,
                            input.channel,
                            input.output,
                            input.source,
                            source_pass.extra_outputs.len()
                        );
                    }
                }
                if matches!(
                    kind,
                    InputKind::Texture | InputKind::Cubemap | InputKind::Volume | InputKind::Video
                ) {
                    let Some(asset_kind) = asset_kinds.get(input.source.as_str()) else {
                        bail!(
                            "pass '{}' channel {} references unknown asset '{}'",
                            pass.name,
                            input.channel,
                            input.source
                        );
                    };
                    let expected = match kind {
                        InputKind::Texture => AssetKind::Texture,
                        InputKind::Cubemap => AssetKind::Cubemap,
                        InputKind::Volume => AssetKind::Volume,
                        InputKind::Video => AssetKind::Video,
                        _ => unreachable!(),
                    };
                    if *asset_kind != expected {
                        bail!(
                            "pass '{}' channel {} expects {:?} asset '{}' but it is {:?}",
                            pass.name,
                            input.channel,
                            expected,
                            input.source,
                            asset_kind
                        );
                    }
                }
                if kind == InputKind::Keyboard && input.source != "keyboard" {
                    bail!(
                        "pass '{}' channel {} uses keyboard input with source '{}'; use source 'keyboard'",
                        pass.name,
                        input.channel,
                        input.source
                    );
                }
                if kind == InputKind::Music && input.source != "music" {
                    bail!(
                        "pass '{}' channel {} uses music input with source '{}'; use source 'music'",
                        pass.name,
                        input.channel,
                        input.source
                    );
                }
                if kind == InputKind::Webcam && input.source != "webcam" {
                    bail!(
                        "pass '{}' channel {} uses webcam input with source '{}'; use source 'webcam'",
                        pass.name,
                        input.channel,
                        input.source
                    );
                }
            }
        }
        let mut test_names = HashSet::new();
        for test in &self.tests {
            if test.name.trim().is_empty() {
                bail!("test name must not be empty");
            }
            if !test_names.insert(test.name.as_str()) {
                bail!("duplicate test name '{}'", test.name);
            }
            if test.frame.is_some() && test.time.is_some() {
                bail!(
                    "test '{}' must use either frame or time, not both",
                    test.name
                );
            }
            if !test.frames.is_empty() && (test.frame.is_some() || test.time.is_some()) {
                bail!(
                    "test '{}' frames is mutually exclusive with frame/time",
                    test.name
                );
            }
            if test.frames.len() > 1024 {
                bail!("test '{}' may contain at most 1024 frames", test.name);
            }
            if test.frame.is_some_and(|frame| frame < 0)
                || test.frames.iter().any(|frame| *frame < 0)
            {
                bail!("test '{}' frame values must be non-negative", test.name);
            }
            let mut unique_frames = HashSet::new();
            if test
                .frames
                .iter()
                .any(|frame| !unique_frames.insert(*frame))
            {
                bail!("test '{}' frames contains duplicates", test.name);
            }
            if test
                .time
                .is_some_and(|time| !time.is_finite() || time < 0.0)
            {
                bail!("test '{}' time must be finite and non-negative", test.name);
            }
            if !test.resolutions.is_empty() && (test.width.is_some() || test.height.is_some()) {
                bail!(
                    "test '{}' resolutions is mutually exclusive with width/height",
                    test.name
                );
            }
            if test.resolutions.len() > 32 {
                bail!("test '{}' may contain at most 32 resolutions", test.name);
            }
            for [width, height] in &test.resolutions {
                if *width == 0
                    || *height == 0
                    || *width > MAX_RENDER_DIMENSION
                    || *height > MAX_RENDER_DIMENSION
                {
                    bail!(
                        "test '{}' resolution {}x{} must be positive and at most {}",
                        test.name,
                        width,
                        height,
                        MAX_RENDER_DIMENSION
                    );
                }
            }
            let matrix_frames = test.frames.len().max(1);
            let matrix_resolutions = test.resolutions.len().max(1);
            if matrix_frames.saturating_mul(matrix_resolutions) > 1024 {
                bail!(
                    "test '{}' expands to more than 1024 frame/resolution variants",
                    test.name
                );
            }
            match (test.width, test.height) {
                (None, None) => {}
                (Some(width), Some(height))
                    if width > 0
                        && height > 0
                        && width <= MAX_RENDER_DIMENSION
                        && height <= MAX_RENDER_DIMENSION => {}
                (Some(_), Some(_)) => bail!(
                    "test '{}' dimensions must be positive and at most {}",
                    test.name,
                    MAX_RENDER_DIMENSION
                ),
                _ => bail!(
                    "test '{}' must specify both width and height or neither",
                    test.name
                ),
            }
            if !test.tolerance.is_finite() || !(0.0..=1.0).contains(&test.tolerance) {
                bail!(
                    "test '{}' tolerance must be finite and in [0, 1]",
                    test.name
                );
            }
            if let Some(reference) = &test.reference {
                validate_project_relative_path(
                    reference,
                    &format!("reference for test '{}'", test.name),
                )?;
            }
            if test.reference.is_some() && (test.frames.len() > 1 || test.resolutions.len() > 1) {
                bail!(
                    "test '{}' uses a single reference image and therefore cannot also define a frame/resolution matrix",
                    test.name
                );
            }
            if let Some(pass) = &test.pass
                && !self.passes.iter().any(|candidate| candidate.name == *pass)
            {
                bail!("test '{}' references unknown pass '{}'", test.name, pass);
            }
            if let Some(pass) = &test.pass
                && self
                    .passes
                    .iter()
                    .any(|candidate| candidate.name == *pass && candidate.kind == PassKind::Sound)
            {
                bail!(
                    "test '{}' selects Sound pass '{}'; use render-audio for Sound validation",
                    test.name,
                    pass
                );
            }
            if !test.raw_tolerance.is_finite() || test.raw_tolerance < 0.0 {
                bail!(
                    "test '{}' raw_tolerance must be finite and non-negative",
                    test.name
                );
            }
            if test.assert_resolution_independent {
                if test.resolutions.len() < 2 {
                    bail!(
                        "test '{}' assert_resolution_independent requires at least two resolutions",
                        test.name
                    );
                }
                let selected = test
                    .pass
                    .as_deref()
                    .map(|name| {
                        self.passes
                            .iter()
                            .find(|candidate| candidate.name == name)
                            .expect("test pass was validated above")
                    })
                    .unwrap_or_else(|| self.final_pass());
                if !matches!(selected.kind, PassKind::Buffer | PassKind::Compute)
                    || selected.width.is_none()
                    || selected.height.is_none()
                {
                    bail!(
                        "test '{}' resolution independence requires a fixed-size buffer/compute pass",
                        test.name
                    );
                }
            }
            if let Some([min, max]) = test.mean_range
                && (!min.is_finite() || !max.is_finite() || min > max)
            {
                bail!(
                    "test '{}' mean_range must contain finite [min, max]",
                    test.name
                );
            }
            for (name, value) in &test.uniforms {
                let definition = self
                    .uniforms
                    .iter()
                    .find(|definition| definition.name() == name)
                    .with_context(|| {
                        format!(
                            "test '{}' references unknown custom uniform '{}'",
                            test.name, name
                        )
                    })?;
                definition.validate_value(value).with_context(|| {
                    format!("invalid custom uniform '{}' in test '{}'", name, test.name)
                })?;
            }
            if test.reference.is_none()
                && !test.assert_no_nan
                && !test.assert_no_inf
                && test.mean_range.is_none()
                && !test.assert_deterministic
                && !test.assert_resolution_independent
            {
                bail!(
                    "test '{}' must define a reference or at least one numeric assertion",
                    test.name
                );
            }
        }

        Ok(())
    }

    pub fn infer_input_kind(&self, input: &Input) -> Result<InputKind> {
        if let Some(kind) = input.kind {
            return Ok(kind);
        }
        if input.source == "keyboard" {
            return Ok(InputKind::Keyboard);
        }
        if input.source == "music" {
            return Ok(InputKind::Music);
        }
        if input.source == "webcam" {
            return Ok(InputKind::Webcam);
        }
        if let Some(asset) = self.assets.iter().find(|asset| asset.name == input.source) {
            return Ok(match asset.kind {
                AssetKind::Texture => InputKind::Texture,
                AssetKind::Cubemap => InputKind::Cubemap,
                AssetKind::Volume => InputKind::Volume,
                AssetKind::Video => InputKind::Video,
            });
        }
        if self.passes.iter().any(|pass| pass.name == input.source) {
            return Ok(InputKind::Pass);
        }
        bail!(
            "cannot infer input kind for unknown source '{}'",
            input.source
        )
    }

    pub fn pass_dimensions(
        &self,
        pass: &Pass,
        output_width: u32,
        output_height: u32,
    ) -> (u32, u32) {
        match (pass.width, pass.height) {
            (Some(width), Some(height)) => (width, height),
            _ => (output_width, output_height),
        }
    }

    pub fn final_pass(&self) -> &Pass {
        self.passes
            .iter()
            .find(|pass| pass.kind == PassKind::Image)
            .expect("validated manifest always has one image pass")
    }

    pub fn to_pretty_toml(&self) -> Result<String> {
        toml::to_string_pretty(self).context("failed to serialize ShaderToy.toml")
    }
}

impl LoadedManifest {
    pub fn load(path: impl AsRef<Path>) -> Result<Self> {
        let root = find_project_root(path.as_ref())?;
        let manifest_path = root.join(MANIFEST_NAME);
        let source = fs::read_to_string(&manifest_path)
            .with_context(|| format!("failed to read {}", manifest_path.display()))?;
        let manifest: Manifest = toml::from_str(&source)
            .with_context(|| format!("failed to parse {}", manifest_path.display()))?;
        manifest.validate_structure()?;
        crate::project_schema::refresh_existing(&root)?;
        Ok(Self { root, manifest })
    }
}

pub fn find_project_root(start: &Path) -> Result<PathBuf> {
    let start = if start.is_file() {
        start.parent().unwrap_or(start)
    } else {
        start
    };
    let absolute = if start.is_absolute() {
        start.to_path_buf()
    } else {
        std::env::current_dir()?.join(start)
    };

    for candidate in absolute.ancestors() {
        if candidate.join(MANIFEST_NAME).is_file() {
            return Ok(candidate.to_path_buf());
        }
    }
    bail!(
        "could not find {MANIFEST_NAME} from {}; run 'shadertoy new' or 'shadertoy init'",
        absolute.display()
    )
}

pub fn schema_json() -> Result<String> {
    serde_json::to_string_pretty(&schema_for!(Manifest))
        .context("failed to serialize manifest schema")
}

pub fn validate_project_relative_path(value: &str, label: &str) -> Result<()> {
    let value = value.trim();
    if value.is_empty() {
        bail!("{label} must not be empty");
    }

    // Manifests use portable project-relative paths. Normalize separators before
    // checking so a Windows traversal is rejected even when inspected on Unix.
    let normalized = value.replace('\\', "/");
    let bytes = normalized.as_bytes();
    let windows_drive = bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':';
    let path = Path::new(&normalized);
    if windows_drive
        || path.is_absolute()
        || path.components().any(|component| {
            matches!(
                component,
                Component::ParentDir | Component::RootDir | Component::Prefix(_)
            )
        })
    {
        bail!("{label} must stay relative to the project root");
    }
    Ok(())
}

fn is_reserved_input_name(value: &str) -> bool {
    RESERVED_INPUT_NAMES.contains(&value)
}

#[cfg(test)]
mod tests;