~starkingdoms/starkingdoms

ref: e2f6d6a71c2f56b85c4727217dddf2e19040326e starkingdoms/crates/unified/src/particle_editor/mod.rs -rw-r--r-- 12.0 KiB
e2f6d6a7 — core fix: ui 28 days ago
                                                                                
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
use crate::{
    particle_editor::{hooks::hooks_plugin, spawn::spawn_plugin},
    particles::{LifetimeCurve, ParticleEffect, RandF32, RandUsize, RandVec2},
};
use bevy::prelude::*;
use bevy_egui::{EguiContexts, EguiPlugin, EguiPrimaryContextPass, egui};
use bevy_rapier2d::plugin::{NoUserData, RapierPhysicsPlugin};
use ordered_float::OrderedFloat;
use std::collections::BTreeMap;

mod ecs;
mod hooks;
mod spawn;

pub fn particle_editor_plugin(app: &mut App) {
    app.add_plugins(DefaultPlugins);
    app.add_plugins(EguiPlugin::default());
    app.add_plugins(RapierPhysicsPlugin::<NoUserData>::pixels_per_meter(10.0));
    app.add_systems(Startup, setup_camera_system);
    app.add_systems(EguiPrimaryContextPass, editor_ui);
    app.add_systems(Startup, setup_editor_effect);
    app.add_plugins(spawn_plugin);
    app.add_plugins(hooks_plugin);
    app.insert_resource(EditorResource {
        ser_field: String::new(),
        status: "Ready".to_string(),
        add_scale_t: 0.0,
        add_scale_v: 0.0,
        add_color_t: 0.0,
        add_color_v: [0u8; 4],
        scale_curve: LifetimeCurve::new(&[(0.0f32, 5.0), (2.0, 0.0)])
            .0
            .iter()
            .map(|u| (*u.0, *u.1))
            .collect::<Vec<_>>(),
        color_curve: vec![(OrderedFloat(0.0f32), [255, 0, 0, 255])],
    });
}

fn setup_editor_effect(mut commands: Commands) {
    commands.spawn((
        ParticleEffect {
            lifetime_seconds: RandF32 {
                value: 2.0,
                randomness: 0.1,
            },
            batch_spawn_delay_seconds: RandF32 {
                value: 0.1,
                randomness: 0.05,
            },
            particles_in_batch: RandUsize {
                value: 1,
                randomness: 1,
            },
            initial_linear_velocity: RandVec2 {
                x: RandF32 {
                    value: 0.0,
                    randomness: 0.5,
                },
                y: RandF32 {
                    value: 10.0,
                    randomness: 1.0,
                },
            },
            initial_angular_velocity: RandF32 {
                value: 1.0,
                randomness: 0.5,
            },
            scale: LifetimeCurve::new(&[(0.0f32, 5.0), (2.0, 0.0)]),
            color: LifetimeCurve::new(&[(0.0f32, Srgba::new(1.0, 0.0, 0.0, 1.0).into())]),
        },
        Transform::from_xyz(0.0, 0.0, 0.0),
    ));
}

fn setup_camera_system(mut commands: Commands) {
    commands.spawn((Camera2d, Transform::from_scale(Vec3::splat(0.1))));
}

#[derive(Resource)]
struct EditorResource {
    ser_field: String,
    status: String,

    add_scale_t: f32,
    add_scale_v: f32,

    add_color_t: f32,
    add_color_v: [u8; 4],

    scale_curve: Vec<(OrderedFloat<f32>, f32)>,
    color_curve: Vec<(OrderedFloat<f32>, [u8; 4])>,
}

fn editor_ui(
    mut contexts: EguiContexts,
    effect: Single<&mut ParticleEffect>,
    mut editor_resource: ResMut<EditorResource>,
) -> Result {
    let mut effect = effect.into_inner();
    egui::Window::new("Particle Effect")
        .resizable(false)
        .show(contexts.ctx_mut()?, |ui| {
            egui::Grid::new("effect").striped(true).show(ui, |ui| {
                draw_rand_f32(&mut effect.lifetime_seconds, "Lifetime (seconds): ", ui);
                draw_rand_f32(
                    &mut effect.batch_spawn_delay_seconds,
                    "Delay in between batches (seconds): ",
                    ui,
                );
                draw_rand_usize(
                    &mut effect.particles_in_batch,
                    "Number of particles in batch: ",
                    ui,
                );

                draw_rand_f32(
                    &mut effect.initial_linear_velocity.x,
                    "Linear velocity (x-axis, m/s): ",
                    ui,
                );
                draw_rand_f32(
                    &mut effect.initial_linear_velocity.y,
                    "Linear velocity (y-axis, m/s): ",
                    ui,
                );
                draw_rand_f32(
                    &mut effect.initial_angular_velocity,
                    "Angular velocity (radians/second): ",
                    ui,
                );

                ui.separator();
                ui.label("Scale curve");
                if ui.button("sort").clicked() {
                    editor_resource.scale_curve.sort_by_key(|u| u.0);
                }
                ui.end_row();

                editor_resource.scale_curve.retain_mut(|(k, v)| {
                    ui.label("scale t=");
                    ui.add(
                        egui::DragValue::new(k.as_mut())
                            .speed(0.01)
                            .range(0.0f32..=effect.lifetime_seconds.value),
                    );
                    ui.label("v=");
                    ui.add(egui::DragValue::new(v).speed(0.01));
                    let r = ui.button("-");
                    ui.end_row();
                    !r.clicked()
                });

                ui.separator();
                ui.end_row();

                ui.label("new scale: t=");
                ui.add(
                    egui::DragValue::new(&mut editor_resource.add_scale_t)
                        .speed(0.01)
                        .range(0.0f32..=effect.lifetime_seconds.value),
                );
                ui.label("v=");
                ui.add(egui::DragValue::new(&mut editor_resource.add_scale_v).speed(0.01));
                if ui.button("+").clicked() {
                    let new_v = (
                        OrderedFloat(editor_resource.add_scale_t),
                        editor_resource.add_scale_v,
                    );
                    editor_resource.scale_curve.push(new_v);
                }
                ui.end_row();

                effect.scale = LifetimeCurve(
                    editor_resource
                        .scale_curve
                        .iter()
                        .copied()
                        .collect::<BTreeMap<_, _>>(),
                );

                ui.separator();
                ui.end_row();

                ui.separator();
                ui.label("Color curve");
                if ui.button("sort").clicked() {
                    editor_resource.color_curve.sort_by_key(|u| u.0);
                }
                ui.end_row();

                editor_resource.color_curve.retain_mut(|(k, v)| {
                    ui.label("color t=");
                    ui.add(
                        egui::DragValue::new(k.as_mut())
                            .speed(0.01)
                            .range(0.0f32..=effect.lifetime_seconds.value),
                    );
                    ui.label("v=");
                    ui.color_edit_button_srgba_unmultiplied(v);
                    let r = ui.button("-");
                    ui.end_row();
                    !r.clicked()
                });

                ui.separator();
                ui.end_row();

                ui.label("new color: t=");
                ui.add(
                    egui::DragValue::new(&mut editor_resource.add_color_t)
                        .speed(0.01)
                        .range(0.0f32..=effect.lifetime_seconds.value),
                );
                ui.label("v=");
                ui.color_edit_button_srgba_unmultiplied(&mut editor_resource.add_color_v);
                if ui.button("+").clicked() {
                    let new_v = (
                        OrderedFloat(editor_resource.add_color_t),
                        editor_resource.add_color_v,
                    );
                    editor_resource.color_curve.push(new_v);
                }
                ui.end_row();

                let curve_copied = editor_resource.color_curve.clone();
                effect.color = LifetimeCurve(
                    curve_copied
                        .iter()
                        .map(|(u, v)| {
                            (
                                *u,
                                Color::Srgba(Srgba::new(
                                    f32::from(v[0]) / 256.0,
                                    f32::from(v[1]) / 256.0,
                                    f32::from(v[2]) / 256.0,
                                    f32::from(v[3]) / 256.0,
                                )),
                            )
                        })
                        .collect::<BTreeMap<_, _>>(),
                );

                ui.separator();
                ui.end_row();
            });
            ui.horizontal(|ui| {
                if ui.button("Generate").clicked() {
                    effect.scale = LifetimeCurve(
                        editor_resource
                            .scale_curve
                            .iter()
                            .copied()
                            .collect::<BTreeMap<_, _>>(),
                    );
                    let curve_copied = editor_resource.color_curve.clone();
                    effect.color = LifetimeCurve(
                        curve_copied
                            .iter()
                            .map(|(u, v)| {
                                (
                                    *u,
                                    Color::Srgba(Srgba::new(
                                        f32::from(v[0]) / 256.0,
                                        f32::from(v[1]) / 256.0,
                                        f32::from(v[2]) / 256.0,
                                        f32::from(v[3]) / 256.0,
                                    )),
                                )
                            })
                            .collect::<BTreeMap<_, _>>(),
                    );

                    editor_resource.ser_field = ron::ser::to_string(effect.as_ref()).unwrap();
                    editor_resource.status = "Ready; Generated OK".to_string();
                }
                if ui.button("Load").clicked() {
                    match ron::from_str(&editor_resource.ser_field) {
                        Ok(e) => {
                            *effect = e;
                            editor_resource.scale_curve = effect
                                .scale
                                .0
                                .iter()
                                .map(|u| (*u.0, *u.1))
                                .collect::<Vec<_>>();
                            editor_resource.color_curve = effect
                                .color
                                .0
                                .iter()
                                .map(|u| {
                                    (*u.0, {
                                        let mut r = [0u8; 4];
                                        let srgba: Srgba = (*u.1).into();
                                        r[0] = (srgba.red * 256.0).floor() as u8;
                                        r[1] = (srgba.green * 256.0).floor() as u8;
                                        r[2] = (srgba.blue * 256.0).floor() as u8;
                                        r[3] = (srgba.alpha * 256.0).floor() as u8;
                                        r
                                    })
                                })
                                .collect::<Vec<_>>();
                        }
                        Err(e) => {
                            editor_resource.status = e.to_string();
                        }
                    }
                }
            });
            ui.text_edit_multiline(&mut editor_resource.ser_field);
            ui.text_edit_multiline(&mut editor_resource.status.as_str());
        });
    Ok(())
}

fn draw_rand_f32(v: &mut RandF32, l: &str, ui: &mut egui::Ui) {
    ui.label(l);
    ui.add(egui::DragValue::new(&mut v.value).speed(0.01));
    ui.label("variance:");
    ui.add(egui::DragValue::new(&mut v.randomness).speed(0.01));
    ui.end_row();
}
fn draw_rand_usize(v: &mut RandUsize, l: &str, ui: &mut egui::Ui) {
    ui.label(l);
    ui.add(egui::DragValue::new(&mut v.value).speed(0.1));
    ui.label("variance:");
    ui.add(egui::DragValue::new(&mut v.randomness).speed(0.1));
    ui.end_row();
}