-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path2
436 lines (409 loc) · 15 KB
/
2
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
// This attribute indicates that if the code is not compiled with debug assertions (i.e., in release mode),
// the application should run with a "windows" subsystem (i.e., without a console window in Windows OS).
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
// Importing required modules and traits from the `bevy` crate.
use bevy::prelude::*;
// Local module import for custom camera controls.
mod pancam;
use crate::pancam::{PanCamConfig, PanCamPlugin, PanCamState};
// Additional imports from the `bevy` crate, useful for rendering and diagnostics.
use bevy::diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin};
use bevy::input::common_conditions::input_toggle_active;
use bevy::reflect::TypePath;
use bevy::reflect::TypeUuid;
use bevy::render::render_resource::{AsBindGroup, ShaderRef};
use bevy::sprite::{Material2d, Material2dPlugin, MaterialMesh2dBundle, Mesh2dHandle};
use bevy_inspector_egui::quick::WorldInspectorPlugin;
use bevy_egui::{egui, EguiContexts, EguiPlugin};
use bevy::audio::*;
// The main function to initialize and run the Bevy app.
fn main() {
// Initializing the Bevy app and adding various plugins.
let _app = App::new()
// Uncomment to set a custom clear color for the renderer.
//.insert_resource(ClearColor(Color::hex("071f3c").unwrap()))
.init_resource::<FractalType>()
.init_resource::<MandelbrotEntity>()
.init_resource::<JuliaEntity>()
.init_resource::<MandelbrotUpdateToggle>()
.add_plugins(DefaultPlugins)
//.add_plugins(
// // Add an inspector that can be toggled using the Escape key.
// WorldInspectorPlugin::default().run_if(input_toggle_active(false, KeyCode::Escape)),
//)
.add_plugins(EguiPlugin)
.add_plugins(PanCamPlugin::default()) // Custom camera control plugin.
.add_plugins(LogDiagnosticsPlugin::default()) // For logging diagnostics.
.add_plugins(FrameTimeDiagnosticsPlugin::default()) // Diagnostics for frame time.
.add_systems(Startup, setup) // Setup function called at startup.
.add_plugins(Material2dPlugin::<MandelbrotMaterial>::default()) // Plugin for 2D materials.
.add_plugins(Material2dPlugin::<JuliaMaterial>::default()) // Plugin for 2D materials.
.add_systems(
Update,
(mandelbrot_uniform_update_system, mandelbrot_toggle_system),
) // Update system for Mandelbrot material.
.add_systems(Update, fractal_toggle_system) // Update system for Mandelbrot material.
.add_systems(Update, fractal_update_system)
.add_systems(Update, uniform_update_ui_system)
.run();
}
fn setup_audio(mut commands: Commands, asset_server: Res<AssetServer>) {
let music_handle = asset_server.load("sounds/Windless_Slopes.ogg");
commands.spawn().insert_bundle((
AudioSourceBundle {
source: music_handle,
..Default::default()
},
MyMusic,
));
}
fn uniform_update_ui_system(
mut ctx: EguiContexts,
mut materials: ResMut<Assets<MandelbrotMaterial>>,
mut julia_materials: ResMut<Assets<JuliaMaterial>>,
mut pancam_query: Query<&mut PanCamState>,
) {
let context = ctx.ctx_mut();
egui::Window::new("Update Uniforms").show(context, |ui| {
if let Some(mandelbrot_material) = materials.iter_mut().next() {
ui.horizontal(|ui| {
ui.label("Mandelbrot Color Scale:");
ui.add(egui::Slider::new(
&mut mandelbrot_material.1.color_scale,
0.0..=1.0,
));
});
ui.horizontal(|ui| {
ui.label("Mandelbrot Iterations:");
ui.add(egui::Slider::new(
&mut mandelbrot_material.1.max_iterations,
0.0..=100000.0,
));
});
ui.horizontal(|ui| {
ui.label("Mandelbrot Zoom:");
ui.add(egui::Slider::new(
&mut pancam_query.get_single_mut().unwrap().target_zoom,
0.0..=100.0,
));
});
}
if let Some(julia_material) = julia_materials.iter_mut().next() {
ui.horizontal(|ui| {
ui.label("Julia Color Scale:");
ui.add(egui::Slider::new(
&mut julia_material.1.color_scale,
0.0..=1.0,
));
});
ui.horizontal(|ui| {
ui.label("Julia Iterations:");
ui.add(egui::Slider::new(
&mut julia_material.1.max_iterations,
0.0..=100000.0,
));
});
ui.horizontal(|ui| {
ui.label("Julia c.x:");
ui.add(egui::Slider::new(&mut julia_material.1.c.x, -2.0..=2.0));
});
ui.horizontal(|ui| {
ui.label("Julia c.y:");
ui.add(egui::Slider::new(&mut julia_material.1.c.y, -2.0..=2.0));
});
}
});
}
// These handles will store the references to our spawned entities.
#[derive(Resource)]
struct MandelbrotEntity(Option<Entity>);
impl Default for MandelbrotEntity {
fn default() -> Self {
MandelbrotEntity(None)
}
}
#[derive(Resource)]
struct JuliaEntity(Option<Entity>);
impl Default for JuliaEntity {
fn default() -> Self {
JuliaEntity(None)
}
}
// New component to determine the current fractal type
#[derive(Resource)]
enum FractalType {
Mandelbrot,
Julia,
}
impl Default for FractalType {
fn default() -> Self {
FractalType::Mandelbrot
}
}
#[derive(Resource)]
struct MandelbrotUpdateToggle {
active: bool,
}
impl Default for MandelbrotUpdateToggle {
fn default() -> Self {
MandelbrotUpdateToggle { active: true }
}
}
// Struct to store uniform parameters for the Mandelbrot fractal.
struct MandelbrotUniforms {
color_scale: f32,
max_iterations: f32,
}
// Mandelbrot material definition. It holds parameters and texture for the Mandelbrot fractal.
#[derive(Component, Debug, Clone, AsBindGroup, TypeUuid, TypePath)]
#[uuid = "148ef22b-c53e-4bc2-982c-bb2b102e38f8"]
struct MandelbrotMaterial {
#[uniform(0)]
color_scale: f32,
#[uniform(1)]
max_iterations: f32,
#[uniform(2)]
zoom: f32,
#[uniform(3)]
offset: Vec2,
#[uniform(6)]
global_offset: Vec2,
#[texture(4)]
#[sampler(5)]
colormap_texture: Handle<Image>,
}
// Julia material definition. It holds parameters and texture for the Julia fractal.
#[derive(Component, Debug, Clone, AsBindGroup, TypeUuid, TypePath)]
#[uuid = "258ef34b-d54f-4bc3-993b-bc3e203a48f9"]
struct JuliaMaterial {
#[uniform(0)]
color_scale: f32,
#[uniform(1)]
max_iterations: f32,
#[uniform(2)]
c: Vec2, // Julia constant
#[texture(4)]
#[sampler(5)]
colormap_texture: Handle<Image>,
}
impl Material2d for MandelbrotMaterial {
fn fragment_shader() -> ShaderRef {
"shaders/mandelbrot_fragment.wgsl".into()
}
}
impl Material2d for JuliaMaterial {
fn fragment_shader() -> ShaderRef {
"shaders/julia_fragment.wgsl".into()
}
}
fn mandelbrot_toggle_system(
keyboard_input: Res<Input<KeyCode>>,
mut toggle: ResMut<MandelbrotUpdateToggle>,
) {
if keyboard_input.just_pressed(KeyCode::A) {
// You can choose another key if needed
toggle.active = !toggle.active;
}
}
// System to update the Mandelbrot material's color_scale based on time.
fn mandelbrot_uniform_update_system(
time: Res<Time>,
mut materials: ResMut<Assets<MandelbrotMaterial>>,
mut julia_materials: ResMut<Assets<JuliaMaterial>>, // For Julia material
toggle: Res<MandelbrotUpdateToggle>,
pancam_query: Query<&PanCamState>,
) {
if !toggle.active {
return;
}
for (_, mut material) in materials.iter_mut() {
material.color_scale = (0.5 * (1.0 + (time.raw_elapsed_seconds_f64() as f32 * 0.01).sin()))
.min(0.8)
.max(0.2);
let pancam = pancam_query.get_single().unwrap();
material.zoom = pancam.current_zoom;
let offset = Vec2::new(
pancam
.target_translation
.unwrap_or(Vec3::new(0.0, 0.0, 0.0))
.x,
pancam
.target_translation
.unwrap_or(Vec3::new(0.0, 0.0, 0.0))
.y,
);
material.offset = offset;
material.global_offset = offset / pancam.current_zoom;
}
for (_, mut material) in julia_materials.iter_mut() {
// Different frequencies and phase shifts for x and y components
material.color_scale = (0.5 * (1.0 + (time.raw_elapsed_seconds_f64() as f32 * 0.01).sin()))
.min(0.8)
.max(0.2);
material.c.y =
0.8 * 0.5 * (1.0 - (time.raw_elapsed_seconds_f64() as f32 * 0.15 + 0.5).cos());
material.c.x =
0.2 * 0.5 * (1.0 - (time.raw_elapsed_seconds_f64() as f32 * 0.1 - 0.5).cos());
//println!("X: {}, Y: {}", material.c.x, material.c.y);
}
}
use bevy::ecs::entity::Entities;
// System to update the material based on the current fractal type
// System to update the material based on the current fractal type
fn fractal_update_system(
entities: &Entities,
mut commands: Commands,
asset_server: Res<AssetServer>, // For loading assets
mut materials: ResMut<Assets<MandelbrotMaterial>>, // For Mandelbrot material
mut julia_materials: ResMut<Assets<JuliaMaterial>>, // For Julia material
mut meshes: ResMut<Assets<Mesh>>, // For meshes
fractal_type: Res<FractalType>,
mut mandelbrot_entity: ResMut<MandelbrotEntity>,
mut julia_entity: ResMut<JuliaEntity>,
) {
if fractal_type.is_changed() {
println!("Fractal Type Changed");
let colormap_texture_handle = asset_server.load("gradient.png");
// Define uniform values for the Mandelbrot material.
let uniforms = MandelbrotUniforms {
color_scale: 0.5,
max_iterations: 5000.0,
};
let mesh = Mesh::from(shape::Quad {
size: Vec2::new(100000.0, 100000.0),
flip: false,
});
let mandelbrot_mesh: Mesh2dHandle = Mesh2dHandle(meshes.add(mesh.clone()));
match *fractal_type {
FractalType::Mandelbrot => {
if let Some(entity) = julia_entity.0 {
if entities.contains(entity) {
commands.entity(entity).despawn();
}
}
// Spawn Mandelbrot entity
let mandelbrot_material_handle = prepare_mandelbrot_material(
&uniforms,
colormap_texture_handle.clone(),
&mut materials,
);
mandelbrot_entity.0 = Some(
commands
.spawn(MaterialMesh2dBundle {
mesh: mandelbrot_mesh.clone(),
material: mandelbrot_material_handle,
transform: Transform::from_xyz(0.0, 0.5, 0.0),
..Default::default()
})
.id(),
);
}
FractalType::Julia => {
if let Some(entity) = mandelbrot_entity.0 {
if entities.contains(entity) {
commands.entity(entity).despawn();
}
}
// Spawn Julia entity
let julia_material_handle = prepare_julia_material(
&uniforms,
colormap_texture_handle,
&mut julia_materials,
);
julia_entity.0 = Some(
commands
.spawn(MaterialMesh2dBundle {
mesh: mandelbrot_mesh.clone(),
material: julia_material_handle,
transform: Transform::from_xyz(0.0, 0.5, 0.0),
..Default::default()
})
.id(),
);
}
}
}
}
// System to toggle between Mandelbrot and Julia fractals
fn fractal_toggle_system(
keyboard_input: Res<Input<KeyCode>>,
mut fractal_type: ResMut<FractalType>,
) {
if keyboard_input.just_pressed(KeyCode::Space) {
println!("Space was pressed");
*fractal_type = match *fractal_type {
FractalType::Mandelbrot => FractalType::Julia,
FractalType::Julia => FractalType::Mandelbrot,
};
}
}
// Utility function to prepare and return a Mandelbrot material with the given uniforms.
fn prepare_mandelbrot_material(
uniforms: &MandelbrotUniforms,
colormap_texture_handle: Handle<Image>,
materials: &mut ResMut<Assets<MandelbrotMaterial>>,
) -> Handle<MandelbrotMaterial> {
let material = MandelbrotMaterial {
max_iterations: uniforms.max_iterations,
color_scale: uniforms.color_scale,
zoom: 4.5,
offset: Vec2 { x: 0.0, y: 0.0 },
global_offset: Vec2 { x: 0.0, y: 0.0 } / 4.5,
colormap_texture: colormap_texture_handle,
};
materials.add(material)
}
// Utility function to prepare and return a Mandelbrot material with the given uniforms.
fn prepare_julia_material(
uniforms: &MandelbrotUniforms,
colormap_texture_handle: Handle<Image>,
materials: &mut ResMut<Assets<JuliaMaterial>>,
) -> Handle<JuliaMaterial> {
let material = JuliaMaterial {
color_scale: uniforms.color_scale,
max_iterations: uniforms.max_iterations,
c: Vec2 { x: 0.3, y: 0.8 },
colormap_texture: colormap_texture_handle,
};
materials.add(material)
}
// The setup function initializes entities in the Bevy app, such as the Mandelbrot mesh and camera.
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<MandelbrotMaterial>>,
mut julia_materials: ResMut<Assets<JuliaMaterial>>,
mut mandelbrot_entity: ResMut<MandelbrotEntity>,
mut julia_entity: ResMut<JuliaEntity>,
) {
// Add a camera with custom pan and zoom capabilities.
commands.spawn((
Camera2dBundle::default(),
PanCamConfig {
grab_buttons: vec![MouseButton::Left, MouseButton::Middle],
enabled: true,
zoom_to_cursor: true,
min_scale: 0.00012,
max_scale: Some(100.0),
min_x: Some(-50000.0),
min_y: Some(-50000.0),
max_x: Some(50000.0),
max_y: Some(50000.0),
pixels_per_line: 10.0,
base_zoom_multiplier: 10.0,
shift_multiplier_normal: 10.0,
shift_multiplier_shifted: 100.0,
animation_scale: 3.0,
..default()
},
PanCamState {
current_zoom: 1.0,
target_zoom: 75.0,
is_zooming: true,
target_translation: None,
delta_zoom_translation: None,
..default()
},
));
}