shadertoy-cli 2.4.3

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
use super::state::{
    ReloadPreservation, clear_error, project_render_dimensions, reload, reload_changed_sources,
    set_error, update_status,
};
use super::*;

pub(super) fn render_loop(
    root: PathBuf,
    preset: Option<String>,
    shared: Shared,
    controls: mpsc::Receiver<Control>,
    preserve_reload_state: bool,
    runtime: &mut Runtime<'_>,
    mut recorder: Option<ReplayRecorder>,
) {
    let mut preset = preset;
    let mut loaded: Option<LoadedManifest> = None;
    let mut sources: Option<SourceGraph> = None;
    let mut changed_paths = BTreeSet::new();
    let mut width = 1280u32;
    let mut height = 720u32;
    let mut resolution_override: Option<(u32, u32)> = None;
    let mut fps = 60.0f32;
    let mut paused = false;
    let mut view = String::from("image");
    let mut uniform_values = BTreeMap::new();
    let mut media = crate::media::MediaInputs::default();
    let mut fresh = true;
    let mut force_render = true;
    let mut reload_due: Option<Instant> = None;
    let mut next_frame = Instant::now();

    match reload(
        &root,
        preset.as_deref(),
        runtime,
        &mut loaded,
        &mut sources,
        &mut width,
        &mut height,
        resolution_override,
        &mut fps,
        &mut view,
        &mut uniform_values,
        if preserve_reload_state {
            ReloadPreservation::RUNTIME_STATE
        } else {
            ReloadPreservation::RESET
        },
    ) {
        Ok(()) => {
            if let Some(project) = loaded.as_ref()
                && let Ok(next_media) = crate::media::MediaInputs::new(project)
            {
                media = next_media;
            }
            update_status(
                &shared,
                loaded.as_ref(),
                runtime,
                width,
                height,
                resolution_override.is_some(),
                fps,
                paused,
                &view,
                &uniform_values,
                None,
                false,
            );
        }
        Err(error) => {
            update_status(
                &shared,
                loaded.as_ref(),
                runtime,
                width,
                height,
                resolution_override.is_some(),
                fps,
                paused,
                &view,
                &uniform_values,
                Some(error.to_string()),
                false,
            );
        }
    }
    'main: loop {
        let mut pending = Vec::new();
        while let Ok(control) = controls.try_recv() {
            pending.push(control);
        }
        for control in pending {
            if !handle_control(
                control,
                &root,
                &mut preset,
                &shared,
                runtime,
                &mut recorder,
                &mut loaded,
                &mut sources,
                &mut changed_paths,
                &mut width,
                &mut height,
                &mut resolution_override,
                &mut fps,
                &mut paused,
                &mut view,
                &mut uniform_values,
                &mut fresh,
                &mut force_render,
                &mut reload_due,
                &mut next_frame,
            ) {
                break 'main;
            }
        }

        if let Some(due) = reload_due
            && Instant::now() >= due
        {
            reload_due = None;
            let changed = std::mem::take(&mut changed_paths);
            let incremental = match (&loaded, &mut sources) {
                (Some(current), Some(current_sources)) => {
                    reload_changed_sources(&root, runtime, current, current_sources, &changed)
                }
                _ => Ok(false),
            };
            match incremental {
                Ok(true) => {
                    force_render = true;
                    clear_error(&shared);
                }
                Ok(false) => {
                    match reload(
                        &root,
                        preset.as_deref(),
                        runtime,
                        &mut loaded,
                        &mut sources,
                        &mut width,
                        &mut height,
                        resolution_override,
                        &mut fps,
                        &mut view,
                        &mut uniform_values,
                        if preserve_reload_state {
                            ReloadPreservation::RUNTIME_STATE
                        } else {
                            ReloadPreservation::RESET
                        },
                    ) {
                        Ok(()) => {
                            if let Some(project) = loaded.as_ref() {
                                match crate::media::MediaInputs::new(project) {
                                    Ok(next_media) => media = next_media,
                                    Err(error) => set_error(&shared, format!("{error:#}")),
                                }
                            }
                            fresh = true;
                            force_render = true;
                            clear_error(&shared);
                        }
                        Err(error) => {
                            // Full project reload compiles before replacing the active pipeline.
                            // Keep rendering the last good project and frame.
                            set_error(&shared, format!("{error:#}"));
                        }
                    }
                }
                Err(error) => {
                    // Per-pass reload is transactional and rolls back earlier impacted passes.
                    set_error(&shared, format!("{error:#}"));
                }
            }
        }

        let now = Instant::now();
        let clients = shared.clients.load(Ordering::Relaxed);
        let scheduled = !paused && clients > 0 && now >= next_frame;
        if loaded.is_some() && (force_render || scheduled) {
            let should_advance = !fresh && !paused && scheduled;
            if should_advance && let Err(error) = runtime.tick_fixed(1.0 / fps, fps) {
                set_error(&shared, error.to_string());
            }

            let media_time = runtime.time();
            if let Err(error) = media.update(runtime, media_time) {
                set_error(&shared, format!("{error:#}"));
            }
            match runtime.render(width, height) {
                Ok(final_image) => {
                    let selected = if let Some(project) = &loaded {
                        if view == project.manifest.final_pass().name {
                            Some(final_image)
                        } else {
                            let dimensions = project
                                .manifest
                                .passes
                                .iter()
                                .find(|pass| pass.name == view)
                                .map(|pass| project.manifest.pass_dimensions(pass, width, height));
                            match dimensions {
                                Some((pass_width, pass_height)) => {
                                    match runtime.snapshot_pass_rgb(&view, pass_width, pass_height)
                                    {
                                        Ok(image) => Some(image),
                                        Err(error) => {
                                            set_error(&shared, error.to_string());
                                            None
                                        }
                                    }
                                }
                                None => {
                                    set_error(&shared, format!("unknown preview pass '{view}'"));
                                    None
                                }
                            }
                        }
                    } else {
                        None
                    };

                    if let Some(image) = selected {
                        match rgb_png_bytes(&image) {
                            Ok(png) => {
                                let png = Bytes::from(png);
                                *shared
                                    .frame_png
                                    .write()
                                    .expect("preview frame lock poisoned") = png.clone();
                                update_status(
                                    &shared,
                                    loaded.as_ref(),
                                    runtime,
                                    width,
                                    height,
                                    resolution_override.is_some(),
                                    fps,
                                    paused,
                                    &view,
                                    &uniform_values,
                                    None,
                                    true,
                                );
                                let _ = shared.frames.send(png);
                            }
                            Err(error) => set_error(&shared, error.to_string()),
                        }
                    }
                    if let Some(recorder) = &mut recorder
                        && let Err(error) = recorder.record_frame(
                            runtime.frame(),
                            runtime.time(),
                            runtime.time_delta(),
                            runtime.frame_rate(),
                        )
                    {
                        set_error(&shared, format!("replay recording failed: {error:#}"));
                    }
                    let _ = runtime.clear_key_transients();
                }
                Err(error) => set_error(&shared, error.to_string()),
            }
            fresh = false;
            force_render = false;
            next_frame = Instant::now() + Duration::from_secs_f64(1.0 / f64::from(fps.max(1.0)));
        }

        let timeout = if !paused && shared.clients.load(Ordering::Relaxed) > 0 {
            next_frame
                .saturating_duration_since(Instant::now())
                .min(Duration::from_millis(50))
        } else {
            Duration::from_millis(50)
        };
        match controls.recv_timeout(timeout) {
            Ok(control) => {
                if !handle_control(
                    control,
                    &root,
                    &mut preset,
                    &shared,
                    runtime,
                    &mut recorder,
                    &mut loaded,
                    &mut sources,
                    &mut changed_paths,
                    &mut width,
                    &mut height,
                    &mut resolution_override,
                    &mut fps,
                    &mut paused,
                    &mut view,
                    &mut uniform_values,
                    &mut fresh,
                    &mut force_render,
                    &mut reload_due,
                    &mut next_frame,
                ) {
                    break;
                }
            }
            Err(mpsc::RecvTimeoutError::Timeout) => {}
            Err(mpsc::RecvTimeoutError::Disconnected) => break,
        }
    }
    if let Some(recorder) = &mut recorder
        && let Err(error) = recorder.flush()
    {
        set_error(&shared, format!("replay recording flush failed: {error:#}"));
    }
}

#[allow(clippy::too_many_arguments)]
fn handle_control(
    control: Control,
    root: &Path,
    preset: &mut Option<String>,
    shared: &Shared,
    runtime: &mut Runtime<'_>,
    recorder: &mut Option<ReplayRecorder>,
    loaded: &mut Option<LoadedManifest>,
    sources: &mut Option<SourceGraph>,
    changed_paths: &mut BTreeSet<PathBuf>,
    width: &mut u32,
    height: &mut u32,
    resolution_override: &mut Option<(u32, u32)>,
    fps: &mut f32,
    paused: &mut bool,
    view: &mut String,
    uniform_values: &mut BTreeMap<String, crate::uniforms::UniformValue>,
    fresh: &mut bool,
    force_render: &mut bool,
    reload_due: &mut Option<Instant>,
    next_frame: &mut Instant,
) -> bool {
    match control {
        Control::Shutdown => return false,
        Control::FilesChanged(paths) => {
            if let Some(recorder) = recorder
                && let Err(error) = recorder.invalidate(
                    "project files changed during recording; restart preview to capture a reproducible session",
                )
            {
                set_error(shared, format!("replay recording invalidation failed: {error:#}"));
            }
            changed_paths.extend(paths);
            *reload_due = Some(Instant::now() + Duration::from_millis(120));
        }
        Control::Pause => {
            if let Err(error) = runtime.pause() {
                set_error(shared, error.to_string());
            } else {
                *paused = true;
                *force_render = true;
            }
        }
        Control::Resume => {
            if let Err(error) = runtime.resume() {
                set_error(shared, error.to_string());
            } else {
                *paused = false;
                *next_frame = Instant::now();
            }
        }
        Control::Reset => match reload(
            root,
            preset.as_deref(),
            runtime,
            loaded,
            sources,
            width,
            height,
            *resolution_override,
            fps,
            view,
            uniform_values,
            ReloadPreservation::RESET,
        ) {
            Ok(()) => {
                *fresh = true;
                *force_render = true;
                clear_error(shared);
                record_action(recorder, shared, ReplayAction::Reset);
            }
            Err(error) => set_error(shared, error.to_string()),
        },
        Control::Step => {
            let was_paused = *paused;
            if was_paused {
                let _ = runtime.resume();
            }
            if let Err(error) = runtime.tick_fixed(1.0 / *fps, *fps) {
                set_error(shared, error.to_string());
            } else {
                *fresh = true;
                *force_render = true;
            }
            if was_paused {
                let _ = runtime.pause();
            }
        }
        Control::Preset(requested) => {
            if requested == *preset {
                clear_error(shared);
            } else {
                if let Some(recorder) = recorder
                    && let Err(error) = recorder.invalidate(
                        "quality preset changed during recording; restart preview to capture a reproducible session",
                    )
                {
                    set_error(
                        shared,
                        format!("replay recording invalidation failed: {error:#}"),
                    );
                }
                match reload(
                    root,
                    requested.as_deref(),
                    runtime,
                    loaded,
                    sources,
                    width,
                    height,
                    *resolution_override,
                    fps,
                    view,
                    uniform_values,
                    // A quality preset is a different graph configuration, not a
                    // hot reload of the same simulation. Rebuild from zeroed GPU
                    // resources and frame history just like a cold preview while
                    // keeping explicit custom-uniform choices made by the reviewer.
                    ReloadPreservation::PRESET_SWITCH,
                ) {
                    Ok(()) => {
                        *preset = requested;
                        if let Ok(mut status) = shared.status.write() {
                            status.preset = preset.clone();
                        }
                        *fresh = true;
                        *force_render = true;
                        *next_frame = Instant::now();
                        clear_error(shared);
                    }
                    Err(error) => set_error(shared, format!("{error:#}")),
                }
            }
        }
        Control::View(pass) => {
            if let Some(project) = loaded {
                if project.manifest.passes.iter().any(|candidate| {
                    candidate.name == pass
                        && !matches!(candidate.kind, PassKind::Cubemap | PassKind::Sound)
                }) {
                    *view = pass;
                    *force_render = true;
                } else {
                    set_error(shared, format!("unknown/non-2D preview pass '{pass}'"));
                }
            }
        }
        Control::Resolution(new_width, new_height) => {
            if new_width == 0
                || new_height == 0
                || new_width > MAX_PREVIEW_DIMENSION
                || new_height > MAX_PREVIEW_DIMENSION
            {
                set_error(
                    shared,
                    format!(
                        "preview resolution must be between 1x1 and {0}x{0}",
                        MAX_PREVIEW_DIMENSION
                    ),
                );
            } else {
                *width = new_width;
                *height = new_height;
                *resolution_override = Some((new_width, new_height));
                // Keep the active runtime so fixed-size offscreen targets and their
                // feedback history survive output-resolution changes. Dynamic
                // output-sized buffers will resize on their next render.
                *force_render = true;
                clear_error(shared);
                record_action(
                    recorder,
                    shared,
                    ReplayAction::Resolution {
                        width: new_width,
                        height: new_height,
                    },
                );
            }
        }
        Control::ResolutionDefault => match project_render_dimensions(root) {
            Ok((new_width, new_height)) => {
                *width = new_width;
                *height = new_height;
                *resolution_override = None;
                *force_render = true;
                clear_error(shared);
                record_action(
                    recorder,
                    shared,
                    ReplayAction::Resolution {
                        width: new_width,
                        height: new_height,
                    },
                );
            }
            Err(error) => set_error(shared, format!("{error:#}")),
        },
        Control::TimeScale(value) => {
            if value.is_finite() && (-8.0..=8.0).contains(&value) {
                if let Err(error) = runtime.set_time_scale(value) {
                    set_error(shared, error.to_string());
                } else {
                    *force_render = true;
                    record_action(recorder, shared, ReplayAction::TimeScale { value });
                }
            } else {
                set_error(
                    shared,
                    "time scale must be a finite log2 value in [-8, 8]".into(),
                );
            }
        }
        Control::Uniform { name, value } => {
            let result = (|| -> Result<()> {
                let project = loaded.as_ref().context("preview project is not loaded")?;
                let definition = project
                    .manifest
                    .uniforms
                    .iter()
                    .find(|definition| definition.name() == name)
                    .with_context(|| format!("unknown custom uniform '{name}'"))?;
                definition.validate_value(&value)?;
                let mut one = BTreeMap::new();
                one.insert(name.clone(), value.clone());
                crate::uniforms::apply_to_runtime(runtime, &one)?;
                uniform_values.insert(name.clone(), value.clone());
                Ok(())
            })();
            match result {
                Ok(()) => {
                    *force_render = true;
                    clear_error(shared);
                    record_action(recorder, shared, ReplayAction::Uniform { name, value });
                }
                Err(error) => set_error(shared, format!("{error:#}")),
            }
        }
        Control::WebcamFrame(rgba) => {
            let result = (|| -> Result<()> {
                let project = loaded.as_ref().context("preview project is not loaded")?;
                if !crate::media::manifest_uses_webcam(project) {
                    bail!("project does not declare a webcam input");
                }
                runtime.update_texture_rgba8(
                    crate::media::WEBCAM_NAME,
                    crate::media::WEBCAM_WIDTH,
                    crate::media::WEBCAM_HEIGHT,
                    &rgba,
                )?;
                Ok(())
            })();
            match result {
                Ok(()) => {
                    *force_render = true;
                    clear_error(shared);
                }
                Err(error) => set_error(shared, format!("{error:#}")),
            }
        }
        Control::Mouse {
            x,
            y,
            down,
            clicked,
        } => {
            if let Err(error) = runtime.set_mouse(x, y, down, clicked) {
                set_error(shared, error.to_string());
            } else {
                record_action(
                    recorder,
                    shared,
                    ReplayAction::Mouse {
                        x,
                        y,
                        down,
                        clicked,
                    },
                );
                if *paused {
                    *force_render = true;
                }
            }
        }
        Control::Key {
            code,
            down,
            pressed,
        } => {
            if let Err(error) = runtime.set_key(code, down, pressed) {
                set_error(shared, error.to_string());
            } else {
                record_action(
                    recorder,
                    shared,
                    ReplayAction::Key {
                        code,
                        down,
                        pressed,
                    },
                );
                if *paused {
                    *force_render = true;
                }
            }
        }
    }
    true
}

fn record_action(recorder: &mut Option<ReplayRecorder>, shared: &Shared, action: ReplayAction) {
    if let Some(recorder) = recorder
        && let Err(error) = recorder.record(action)
    {
        set_error(shared, format!("replay recording failed: {error:#}"));
    }
}