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
|
mod camera;
mod config;
mod sim;
mod ui;
use egui::Id;
use egui_wgpu::{RendererOptions, ScreenDescriptor};
use egui_winit::egui::{self, Context};
use futures::executor;
use rand::random_range;
use std::{collections::VecDeque, sync::Arc, time::Instant};
use wgpu::Origin3d;
use winit::{
application::ApplicationHandler,
event::{
ElementState, KeyEvent, MouseButton,
WindowEvent::{self},
},
event_loop::{ActiveEventLoop, ControlFlow, EventLoop},
keyboard::{KeyCode, PhysicalKey},
window::Window,
};
use crate::{
camera::Camera,
config::{CELLS_IN_CHUNK, CHUNK_SIZE, WINDOW_TITLE},
sim::{cell::Cell, materials::MaterialId, sim::sim_tick, world::World},
ui::draw_egui,
};
pub type Error = Box<dyn std::error::Error>;
pub type Result<T> = std::result::Result<T, Error>;
struct Config {
fps: u16,
brush_radius: u8,
brush_material: MaterialId,
use_threading: bool,
}
struct Input {
last_mouse_pos_on_screen: Option<(f64, f64)>,
last_mouse_pos_on_board: Option<(i32, i32)>,
is_lmb_pressed: bool,
// keybindings
is_up_pressed: bool,
is_left_pressed: bool,
is_down_pressed: bool,
is_right_pressed: bool,
}
struct Diagnostics {
frame_times: VecDeque<f32>,
fps: f32,
}
struct RendererChunk {
texture: wgpu::Texture,
bind_group: wgpu::BindGroup,
}
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct ChunkData {
origin: [i32; 2],
}
struct RendererState {
window: Arc<Window>,
surface: wgpu::Surface<'static>,
device: wgpu::Device,
queue: wgpu::Queue,
config: wgpu::SurfaceConfiguration,
is_surface_configured: bool,
// egui
egui_context: egui::Context,
egui_state: egui_winit::State,
egui_renderer: egui_wgpu::Renderer,
// world pixels
renderer_chunks: Vec<RendererChunk>,
pixels_pipeline: wgpu::RenderPipeline,
camera_uniform_buffer: wgpu::Buffer,
camera_uniform_bind_group: wgpu::BindGroup,
}
impl RendererState {
// https://sotrh.github.io/learn-wgpu/beginner/tutorial1-window
pub async fn new(window: Arc<Window>) -> Self {
let size = window.inner_size();
println!("Got window! ({}x{})", size.width, size.height);
let instance = wgpu::Instance::default();
let surface = instance.create_surface(window.clone()).unwrap();
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
compatible_surface: Some(&surface),
..wgpu::RequestAdapterOptions::default()
})
.await
.unwrap();
println!(
"Initialized adapter, using GPU '{}'",
adapter.get_info().name
);
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor {
required_features: wgpu::Features::default() | wgpu::Features::IMMEDIATES,
required_limits: wgpu::Limits {
max_immediate_size: 16,
..wgpu::Limits::defaults()
},
..wgpu::DeviceDescriptor::default()
})
.await
.unwrap();
device.on_uncaptured_error(Arc::new(|err| panic!("{err}")));
let surface_caps = surface.get_capabilities(&adapter);
let surface_format = surface_caps
.formats
.iter()
.find(|f| f.is_srgb())
.copied()
.unwrap_or(surface_caps.formats[0]);
let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: surface_format,
width: size.width,
height: size.height,
present_mode: wgpu::PresentMode::AutoNoVsync,
alpha_mode: surface_caps.alpha_modes[0],
view_formats: vec![],
desired_maximum_frame_latency: 2,
};
let egui_context = Context::default();
let egui_state = egui_winit::State::new(
egui_context.clone(),
egui_context.viewport_id(),
&window,
None,
None,
None,
);
let egui_renderer = egui_wgpu::Renderer::new(&device, surface_format, {
RendererOptions {
msaa_samples: 1,
..RendererOptions::default()
}
});
let camera_uniform_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: None,
entries: &[wgpu::BindGroupLayoutEntry {
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
binding: 0,
count: None,
visibility: wgpu::ShaderStages::VERTEX,
}],
});
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: None,
entries: &[wgpu::BindGroupLayoutEntry {
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
binding: 0,
count: None,
visibility: wgpu::ShaderStages::FRAGMENT,
}],
});
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Shader"),
source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()),
});
let pixels_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
immediate_size: 16,
bind_group_layouts: &[
Some(&camera_uniform_bind_group_layout),
Some(&bind_group_layout),
],
});
let pixels_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: None,
layout: Some(&pixels_pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: wgpu::PipelineCompilationOptions::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: config.format,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: wgpu::PipelineCompilationOptions::default(),
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleStrip,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: None,
polygon_mode: wgpu::PolygonMode::Fill,
unclipped_depth: false,
conservative: false,
},
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
let camera_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Camera uniform buffer"),
size: 16,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let camera_uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &camera_uniform_bind_group_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: camera_uniform_buffer.as_entire_binding(),
}],
});
let mut renderer_chunks: Vec<RendererChunk> = Vec::new();
// match number of world chunks
// TODO refactor so that this implicit
for _ in -10..10 {
for _ in -10..10 {
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: None,
mip_level_count: 1,
sample_count: 1,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
format: wgpu_types::TextureFormat::Rgba8UnormSrgb,
size: wgpu::Extent3d {
width: size.width,
height: size.height,
depth_or_array_layers: 1,
},
dimension: wgpu::TextureDimension::D2,
view_formats: &[],
});
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &bind_group_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&texture.create_view(
&wgpu::TextureViewDescriptor {
dimension: Some(wgpu::TextureViewDimension::D2),
usage: Some(
wgpu::TextureUsages::TEXTURE_BINDING
| wgpu::TextureUsages::COPY_DST,
),
..wgpu::TextureViewDescriptor::default()
},
)),
}],
});
renderer_chunks.push(RendererChunk {
texture,
bind_group,
})
}
}
RendererState {
window,
surface,
device,
queue,
config,
is_surface_configured: false,
egui_context,
egui_state,
egui_renderer,
renderer_chunks,
pixels_pipeline,
camera_uniform_bind_group,
camera_uniform_buffer,
}
}
pub fn resize(&mut self, width: u32, height: u32) {
if width > 0 && height > 0 {
self.config.width = width;
self.config.height = height;
self.surface.configure(&self.device, &self.config);
self.is_surface_configured = true;
}
}
pub fn render(
&mut self,
world: &mut World,
camera: &mut Camera,
config: &mut Config,
diagnostics: &Diagnostics,
input: &Input,
) {
puffin::profile_function!();
self.window.request_redraw();
if !self.is_surface_configured {
return;
}
let output = {
puffin::profile_scope!("Get current surface texture");
match self.surface.get_current_texture() {
wgpu::CurrentSurfaceTexture::Success(surface_texture) => surface_texture,
wgpu::CurrentSurfaceTexture::Suboptimal(surface_texture) => surface_texture,
wgpu::CurrentSurfaceTexture::Timeout
| wgpu::CurrentSurfaceTexture::Occluded
| wgpu::CurrentSurfaceTexture::Validation => {
// Skip this frame
return;
}
wgpu::CurrentSurfaceTexture::Outdated => {
self.surface.configure(&self.device, &self.config);
return;
}
wgpu::CurrentSurfaceTexture::Lost => {
panic!("Lost device?");
}
}
};
let view = output
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Render Encoder"),
});
let raw_input = self.egui_state.take_egui_input(&self.window);
let full_output = self.egui_context.run_ui(raw_input, |ui| {
let right_panel = egui::Panel::right(Id::new("right_panel"));
right_panel
.resizable(false)
// TODO collapse button
.show_collapsible(ui, &mut true, |panel_ui| {
draw_egui(panel_ui, config, camera, diagnostics, input)
});
});
self.egui_state
.handle_platform_output(&self.window, full_output.platform_output);
let clipped_primitives = self
.egui_context
.tessellate(full_output.shapes, full_output.pixels_per_point);
let pixels_per_point = full_output.pixels_per_point;
let size = self.window.inner_size();
let screen_descriptor = ScreenDescriptor {
size_in_pixels: [size.width, size.height],
pixels_per_point,
};
for (id, delta) in &full_output.textures_delta.set {
self.egui_renderer
.update_texture(&self.device, &self.queue, *id, delta);
}
self.egui_renderer.update_buffers(
&self.device,
&self.queue,
&mut encoder,
&clipped_primitives,
&screen_descriptor,
);
// write the camera buffer
self.queue.write_buffer(
&self.camera_uniform_buffer,
0,
bytemuck::bytes_of(&camera.to_uniform()),
);
// write the chunk textures
let mut chunk_buffer: [u8; (CELLS_IN_CHUNK * 4) as usize] =
[0; (CELLS_IN_CHUNK * 4) as usize];
{
puffin::profile_scope!("Upload chunk textures");
for &idx in world.chunk_position_to_chunk_idx.values() {
let chunk = &mut world.chunks[idx];
if !chunk.needs_texture_update {
continue;
}
chunk.needs_texture_update = false;
// TODO use material palette to improve bandwidth of upload
for i in 0..CELLS_IN_CHUNK {
let material = chunk.cells[i].material.def();
chunk_buffer[i * 4] = material.color.0;
chunk_buffer[i * 4 + 1] = material.color.1;
chunk_buffer[i * 4 + 2] = material.color.2;
chunk_buffer[i * 4 + 3] = material.color.3;
}
let render_chunk = &self.renderer_chunks[idx];
self.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &render_chunk.texture,
aspect: wgpu::TextureAspect::All,
mip_level: 0,
origin: Origin3d::ZERO,
},
&chunk_buffer,
wgpu::TexelCopyBufferLayout {
bytes_per_row: Some(CHUNK_SIZE as u32 * 4),
offset: 0,
rows_per_image: Some(CHUNK_SIZE as u32),
},
wgpu::Extent3d {
width: CHUNK_SIZE as u32,
height: CHUNK_SIZE as u32,
depth_or_array_layers: 1,
},
);
}
}
{
puffin::profile_scope!("Main render pass");
let mut render_pass: wgpu::RenderPass<'_> =
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Render Pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color {
r: 0.0,
g: 0.0,
b: 0.0,
a: 1.0,
}),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
occlusion_query_set: None,
timestamp_writes: None,
multiview_mask: None,
});
render_pass.set_pipeline(&self.pixels_pipeline);
render_pass.set_bind_group(0, &self.camera_uniform_bind_group, &[]);
// TODO only visible chunks
for cx in -10..10 {
for cy in -10..10 {
if let Some(idx) = world.chunk_position_to_chunk_idx.get(&(cx, cy)) {
let render_chunk = &self.renderer_chunks[*idx];
render_pass.set_bind_group(1, &render_chunk.bind_group, &[]);
render_pass
.set_immediates(0, bytemuck::bytes_of(&ChunkData { origin: [cx, cy] }));
render_pass.draw(0..4, 0..1);
}
}
}
}
{
puffin::profile_scope!("Egui render pass");
let mut egui_pass = encoder
.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("egui pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
})
.forget_lifetime();
self.egui_renderer
.render(&mut egui_pass, &clipped_primitives, &screen_descriptor);
}
{
puffin::profile_scope!("Submit queue and present");
self.queue.submit(std::iter::once(encoder.finish()));
output.present();
}
}
}
struct App {
window: Option<Arc<Window>>,
renderer_state: Option<RendererState>,
input: Input,
camera: Option<Camera>,
world: Option<World>,
// sim state
// the last/current (not yet completed) seqno
sim_seqno: u64,
sim_paused: bool,
ignore_pause_next_tick: bool,
// used to compute delta_time
last_frame_real: Instant,
config: Config,
diagnostics: Diagnostics,
}
impl Default for App {
fn default() -> Self {
Self {
window: None,
renderer_state: None,
input: Input {
last_mouse_pos_on_screen: None,
last_mouse_pos_on_board: None,
is_lmb_pressed: false,
is_up_pressed: false,
is_left_pressed: false,
is_down_pressed: false,
is_right_pressed: false,
},
camera: None,
world: Some(World::from_default_size()),
sim_seqno: 0,
sim_paused: false,
ignore_pause_next_tick: false,
last_frame_real: Instant::now(),
config: Config {
fps: 120,
use_threading: true,
brush_radius: 10,
brush_material: MaterialId::Sand,
},
diagnostics: Diagnostics {
fps: 0.0,
frame_times: VecDeque::new(),
},
}
}
}
impl ApplicationHandler for App {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
let window = Arc::new(
event_loop
.create_window(Window::default_attributes().with_title(WINDOW_TITLE))
.unwrap(),
);
self.window = Some(window.clone());
self.renderer_state = Some(executor::block_on(RendererState::new(window.clone())));
let size = window.inner_size();
self.camera = Some(Camera::new((size.width as i32, size.height as i32)));
// let surface = SurfaceTexture::new(size.width, size.height, window_ref);
// let mut pixels = Pixels::new(PIXEL_BUFFER_WIDTH, PIXEL_BUFFER_HEIGHT, surface).unwrap();
// pixels.set_scaling_mode(ScalingMode::Fill);
}
fn window_event(
&mut self,
event_loop: &ActiveEventLoop,
_: winit::window::WindowId,
event: WindowEvent,
) {
if let Some(window) = &self.window
&& let Some(renderer_state) = &mut self.renderer_state
&& let Some(world) = &mut self.world
&& let Some(camera) = &mut self.camera
{
let egui_response = renderer_state.egui_state.on_window_event(window, &event);
// if egui consumed the event, it means we shouldn't treat any e.g., mouse clicks
if egui_response.consumed {
return;
}
match event {
WindowEvent::KeyboardInput {
event:
KeyEvent {
physical_key: PhysicalKey::Code(code),
state,
..
},
..
} => {
let pressed = state.is_pressed();
match code {
KeyCode::KeyW => self.input.is_up_pressed = pressed,
KeyCode::KeyA => self.input.is_left_pressed = pressed,
KeyCode::KeyS => self.input.is_down_pressed = pressed,
KeyCode::KeyD => self.input.is_right_pressed = pressed,
KeyCode::KeyC => self.world = Some(World::from_default_size()),
KeyCode::Space => {
if pressed {
self.sim_paused = !self.sim_paused
}
}
KeyCode::KeyX => {
if pressed {
self.ignore_pause_next_tick = true
}
}
_ => {}
}
}
WindowEvent::CursorMoved { position, .. } => {
self.input.last_mouse_pos_on_screen = Some((position.x, position.y));
let world_pos =
camera.screen_position_to_world(position.x as f32, position.y as f32);
self.input.last_mouse_pos_on_board =
Some((world_pos.0 as i32, world_pos.1 as i32))
}
WindowEvent::MouseInput { state, button, .. } => {
if button == MouseButton::Left {
self.input.is_lmb_pressed = state == ElementState::Pressed
}
}
WindowEvent::Resized(size) => {
renderer_state.resize(size.width, size.height);
camera.resize((size.width as i32, size.height as i32));
}
WindowEvent::CloseRequested => {
event_loop.exit();
}
WindowEvent::RedrawRequested => {
#[cfg(feature = "profiler")]
puffin::GlobalProfiler::lock().new_frame();
puffin::profile_scope!("redraw_requested");
// compute frame delta
let now = Instant::now();
let secs_since_last_frame = (now - self.last_frame_real).as_secs_f32();
let delta_time = secs_since_last_frame / (1.0 / 60.0);
self.last_frame_real = now;
self.diagnostics
.frame_times
.push_back(secs_since_last_frame);
if self.diagnostics.frame_times.len() > 30 {
self.diagnostics.frame_times.pop_front();
}
let average_frame_time = self.diagnostics.frame_times.iter().sum::<f32>()
/ self.diagnostics.frame_times.len() as f32;
self.diagnostics.fps = 1.0 / average_frame_time;
// apply inputs
camera.handle_camera_input(&self.input, delta_time);
// // --TEST DRAWING--
if self.input.is_lmb_pressed
&& let Some(lm) = self.input.last_mouse_pos_on_board
{
// start with the bounding box of the drawing brush circle + some margin
// clamp the bounding box to the board sie
let bb_xl = lm.0 - self.config.brush_radius as i32;
let bb_xu = lm.0 + self.config.brush_radius as i32;
let bb_yl = lm.1 - self.config.brush_radius as i32;
let bb_yu = lm.1 + self.config.brush_radius as i32;
// for each point, check if the distance is less than the brush size and write the pixel
for x in bb_xl..bb_xu {
for y in bb_yl..bb_yu {
let r = random_range(0.0..1.0);
if ((x - lm.0).pow(2) + (y - lm.1).pow(2))
< (self.config.brush_radius as i32).pow(2)
&& r > 0.9
{
let mut cell = Cell::from_material(self.config.brush_material);
cell.flags = (self.sim_seqno as u8) & 0b1;
world.set_cell_from_game_position(
x, y, cell, // wake the chunk
false,
);
}
}
}
}
// TODO check if we need to run another sim tick given the sim speed + delta_time
// SIM logic
if !self.sim_paused || self.ignore_pause_next_tick {
sim_tick(world, self.sim_seqno, self.config.use_threading);
self.sim_seqno += 1;
self.ignore_pause_next_tick = false;
}
renderer_state.render(
world,
camera,
&mut self.config,
&self.diagnostics,
&mut self.input,
);
}
_ => {}
}
}
}
fn about_to_wait(&mut self, _: &ActiveEventLoop) {
// let frame_duration: Duration = Duration::from_micros(1_000_000 / self.config.fps as u64);
// limit our internal redraw requests to (fps)
if let Some(window) = &self.window {
window.request_redraw();
} else {
panic!("No window!")
}
}
}
#[cfg(feature = "profiler")]
fn start_profiler() {
let _server = puffin_http::Server::new("127.0.0.1:8585").unwrap();
puffin::set_scopes_on(true);
std::mem::forget(_server); // keep serving for the process lifetime
std::process::Command::new("puffin_viewer")
.args(["--url", "127.0.0.1:8585"])
.spawn()
.ok(); // don't die if it isn't installed
}
fn main() -> Result<()> {
#[cfg(feature = "profiler")]
start_profiler();
let event_loop = EventLoop::new()?;
event_loop.set_control_flow(ControlFlow::Poll);
let mut app = App::default();
event_loop.run_app(&mut app)?;
Ok(())
}
|