tweak_runner 0.4.0

a runner for the tweak shader library.
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
use crate::RunnerMessage;

use tweak_shader::input_type::{InputVariant, MutInputInt};

use egui_plot::{Plot, PlotPoint, PlotPoints, Points};
use egui_winit::egui::Color32;

use egui_winit::egui::RichText;
use egui_winit::egui::ScrollArea;
use egui_winit::egui::Slider;

use egui_winit::egui::Ui;

use std::cmp::Ord;
use std::collections::BTreeMap;
use std::sync::mpsc;

use egui_notify::Toasts;

pub struct UiOptions {
    pub paused: bool,
    pub halt_recompilation: bool,
    pub lock_aspect_ratio: Option<[u32; 2]>,
    pub use_screen_size_for_screenshots: bool,
    pub resize_debounce: Option<std::time::Instant>,
}

impl Default for UiOptions {
    fn default() -> Self {
        Self {
            resize_debounce: None,
            paused: false,
            use_screen_size_for_screenshots: true,
            halt_recompilation: false,
            lock_aspect_ratio: Some([640, 480]),
        }
    }
}

#[derive(Default)]
pub struct UiState {
    pub options: UiOptions,
    pub show_options: bool,
    pub input_panel_hidden: bool,
    pub screen_shot_scheduled: Option<std::path::PathBuf>,
    // map of variable names to file names
    pub current_loaded_files: BTreeMap<String, String>,
    pub notifications: Vec<String>,
    pub toasts: Toasts,
    pub compute_target: usize,
}

impl UiState {
    pub fn new() -> Self {
        Default::default()
    }
}

pub fn side_panel(
    render_ctx: &mut tweak_shader::RenderContext,
    message_sender: &mpsc::Sender<RunnerMessage>,
    ui_state: &mut UiState,
    ctx: &egui_winit::egui::Context,
) {
    egui_winit::egui::SidePanel::new(egui_winit::egui::panel::Side::Left, "User Inputs")
        .show_animated(ctx, !ui_state.input_panel_hidden, |ui| {
            ScrollArea::vertical().show(ui, |ui| {
                // Label and close button.
                ui.vertical_centered_justified(|ui| {
                    ui.horizontal(|ui| {
                        ui.label(RichText::new("User Inputs").size(15.0));
                        if ui.button("Options").clicked() {
                            ui_state.show_options = !ui_state.show_options;
                        };
                        if ui.button("<< [Esc]").clicked() {
                            ui_state.input_panel_hidden = true;
                        }
                    });

                    ui.separator();
                    if ui_state.show_options {
                        option_panel(ui_state, message_sender, ui);
                    }
                });

                if render_ctx.is_compute() {
                    let name = render_ctx
                        .iter_targets()
                        .nth(ui_state.compute_target)
                        .unwrap()
                        .name;

                    let names = render_ctx.iter_targets().enumerate();

                    let before = ui_state.compute_target;
                    egui_winit::egui::ComboBox::from_label("Current Target")
                        .selected_text(name)
                        .show_ui(ui, |ui| {
                            for (idx, targ) in names {
                                ui.selectable_value(&mut ui_state.compute_target, idx, targ.name);
                            }
                        });
                    if before != ui_state.compute_target {
                        let targ = render_ctx
                            .iter_targets()
                            .nth(ui_state.compute_target)
                            .unwrap()
                            .name
                            .to_owned();

                        let _ = render_ctx.set_compute_target(&targ);
                    }
                }

                let mut inputs = render_ctx.iter_inputs_mut().collect::<Vec<_>>();

                inputs.sort_by(|(_, a), (_, b)| (a.variant() as u32).cmp(&(b.variant() as u32)));

                let mut last_variant = inputs
                    .first()
                    .map(|(_, val)| val.variant())
                    .unwrap_or(InputVariant::Point);

                for (name, mut val) in inputs {
                    let variant = val.variant();

                    if last_variant != variant {
                        last_variant = variant;
                        ui.separator();
                    };

                    input_widget(name, &mut val, ui_state, message_sender, ui);
                }
            });
        });
}

fn option_panel(ui_state: &mut UiState, message_sender: &mpsc::Sender<RunnerMessage>, ui: &mut Ui) {
    ui.vertical_centered_justified(|ui| {
        ui.horizontal(|ui| {
            if ui
                .radio(ui_state.options.halt_recompilation, "Pause Recompilation")
                .clicked()
            {
                ui_state.options.halt_recompilation = !ui_state.options.halt_recompilation;
            }
            if ui.radio(ui_state.options.paused, "Pause").clicked() {
                ui_state.options.paused = !ui_state.options.paused
            }
        });

        if ui
            .radio(
                ui_state.options.use_screen_size_for_screenshots,
                "Use screen aspect for screenshots",
            )
            .clicked()
        {
            ui_state.options.use_screen_size_for_screenshots =
                !ui_state.options.use_screen_size_for_screenshots
        }

        if ui.button("take screenshot").clicked() {
            launch_screenshot_dialog(message_sender.clone());
        }

        ui.horizontal(|ui| {
            if ui
                .radio(
                    ui_state.options.lock_aspect_ratio.is_some(),
                    "Lock Aspect Ratio",
                )
                .clicked()
            {
                if ui_state.options.lock_aspect_ratio.is_none() {
                    ui_state.options.lock_aspect_ratio = Some([640, 480]);
                } else {
                    ui_state.options.lock_aspect_ratio = None;
                }
                let _ = message_sender.send(RunnerMessage::AspectChanged);
            }

            if let Some([ref mut w, ref mut h]) = ui_state.options.lock_aspect_ratio.as_mut() {
                let (pre_w, pre_h) = (*w, *h);
                ui.add(egui_winit::egui::DragValue::new(w));
                ui.add(egui_winit::egui::DragValue::new(h));

                *w = (*w).max(1);
                *h = (*h).max(1);

                if (pre_w != *w) || (pre_h != *h) {
                    ui_state.options.resize_debounce = Some(std::time::Instant::now());
                }

                if let Some(last_call) = ui_state.options.resize_debounce {
                    if last_call.elapsed() > std::time::Duration::from_millis(250) {
                        ui_state.options.resize_debounce = None;
                        let _ = message_sender.send(RunnerMessage::AspectChanged);
                    }
                }
            } else {
                let mut placeholder = 0.0;
                ui.add(
                    egui_winit::egui::DragValue::new(&mut placeholder)
                        .custom_formatter(|_, _| "—".into()),
                );
                ui.add(
                    egui_winit::egui::DragValue::new(&mut placeholder)
                        .custom_formatter(|_, _| "—".into()),
                );
            }
        });
    });
    ui.separator();
}

pub fn toasts(ui_state: &mut UiState, ctx: &egui_winit::egui::Context) {
    while let Some(notification) = ui_state.notifications.pop() {
        ui_state
            .toasts
            .error(notification)
            .duration(Some(std::time::Duration::from_secs(10)));
    }
    ui_state.toasts.show(ctx);
}

fn input_widget(
    name: &str,
    val: &mut tweak_shader::input_type::MutInput,
    ui_state: &mut UiState,
    message_sender: &mpsc::Sender<RunnerMessage>,
    ui: &mut Ui,
) {
    match val.variant() {
        InputVariant::Image => {
            file_selector(ui, val, name, ui_state, message_sender.clone());
        }
        InputVariant::Float => {
            let v = val.as_float().unwrap();
            ui.add(Slider::new(&mut v.current, v.min..=v.max).text(name));
            ui.add_space(10.0);
        }
        InputVariant::Bool => {
            let v = val.as_bool().unwrap();
            if ui.radio(v.current.is_true(), name).clicked() {
                if v.current.is_true() {
                    v.current = tweak_shader::input_type::ShaderBool::False;
                } else {
                    v.current = tweak_shader::input_type::ShaderBool::True;
                }
            }
        }
        InputVariant::Color => {
            let v = val.as_color().unwrap();
            let _ = ui.horizontal(|ui| {
                ui.color_edit_button_rgba_unmultiplied(&mut v.current);
                ui.label(name);
            });
        }
        InputVariant::Int => {
            let MutInputInt { value: v, labels } = val.as_int().unwrap();
            if let Some(list) = labels {
                let current =
                    list.iter()
                        .find_map(|(str, val)| if v.current == *val { Some(str) } else { None });

                egui_winit::egui::ComboBox::from_label(name)
                    .selected_text(current.unwrap())
                    .show_ui(ui, |ui| {
                        for opt in list {
                            ui.selectable_value(&mut v.current, opt.1, &opt.0);
                        }
                    });
            } else {
                ui.add(Slider::new(&mut v.current, v.min..=v.max).text(name));
                ui.add_space(10.0);
            }
        }
        InputVariant::Point => {
            let val = val.as_point().unwrap();
            point_selector(ui, name, val);
        }
        _ => {}
    };
}

fn file_selector(
    ui: &mut Ui,
    val: &mut tweak_shader::input_type::MutInput,
    name: &str,
    ui_state: &mut UiState,
    sender: std::sync::mpsc::Sender<RunnerMessage>,
) {
    let meta = val.texture_status().unwrap();
    ui.horizontal(|ui| {
        ui.label(name);
        if let tweak_shader::input_type::TextureStatus::Loaded { .. } = meta {
            if let Some(path) = ui_state.current_loaded_files.get(name) {
                if path.len() > 20 {
                    let path = format!("...{}", &path[path.len().saturating_sub(20)..]);
                    ui.label(&path);
                } else {
                    ui.label(path);
                };
            } else {
                ui.label("[ERROR]");
            }

            if ui.button("X").clicked() {
                if val.variant() == InputVariant::Image {
                    let _ = sender.send(RunnerMessage::UnloadImage {
                        var: name.to_owned(),
                    });
                }
                ui_state.current_loaded_files.remove(name);
            }
        } else if ui.button("Select File").clicked() && val.variant() == InputVariant::Image {
            launch_image_or_video_dialog(sender, name.to_owned());
        }
    });
}

fn point_selector(
    ui: &mut Ui,
    name: &str,
    input: &mut tweak_shader::input_type::BoundedInput<[f32; 2]>,
) {
    ui.horizontal(|ui| {
        ui.label(name);
        ui.label("X");
        ui.add(
            egui_winit::egui::DragValue::new(&mut input.current[0])
                .range(input.min[0]..=input.max[0]),
        );
        ui.label("Y");
        ui.add(
            egui_winit::egui::DragValue::new(&mut input.current[1])
                .range(input.min[1]..=input.max[1]),
        );
    });

    Plot::new(name)
        .include_x(input.max[0])
        .include_x(input.min[0])
        .include_y(input.max[1])
        .include_y(input.min[1])
        .allow_zoom(false)
        .allow_scroll(false)
        .allow_drag(false)
        .allow_double_click_reset(false)
        .view_aspect(2.0)
        .show(ui, |plot_ui| {
            if plot_ui.response().clicked()
                || plot_ui.pointer_coordinate_drag_delta() != egui_winit::egui::Vec2::ZERO
            {
                if let Some(p) = plot_ui.pointer_coordinate() {
                    input.current = [
                        p.x.clamp(input.min[0] as f64, input.max[0] as f64) as f32,
                        p.y.clamp(input.min[1] as f64, input.max[1] as f64) as f32,
                    ];
                }
            }
            let point = Points::new(
                "",
                PlotPoints::Owned(vec![PlotPoint::new(input.current[0], input.current[1])]),
            )
            .radius(5.0);
            plot_ui.points(point);
        });
}

pub fn diagnostic_message(ctx: &egui_winit::egui::Context, e: &str) {
    egui_winit::egui::TopBottomPanel::bottom("")
        .min_height(3.0)
        .show(ctx, |ui| {
            ui.vertical_centered(|ui| {
                ui.add_space(15.0);
                ui.label(
                    RichText::new(e)
                        .color(Color32::from_rgb(255, 10, 0))
                        .background_color(Color32::BLACK),
                );
            });
        });
}

fn launch_screenshot_dialog(sender: std::sync::mpsc::Sender<RunnerMessage>) {
    std::thread::spawn(move || {
        let file_path = tinyfiledialogs::save_file_dialog("select screen shot location", "/");

        if let Some(path) = file_path {
            let mut buf: std::path::PathBuf = path.into();
            if buf.extension().is_none() {
                buf.set_extension("png");
            }
            let _ = sender.send(RunnerMessage::ScreenShot(buf));
        }
    });
}

fn launch_image_or_video_dialog(sender: std::sync::mpsc::Sender<RunnerMessage>, var: String) {
    std::thread::spawn(move || {
        let file_path = tinyfiledialogs::open_file_dialog("Load an Image or Video", "/", None);

        if let Some(file_path) = file_path {
            let _ = sender.send(RunnerMessage::LoadImage {
                path: std::path::PathBuf::from(file_path),
                var,
            });
        }
    });
}