EventLoop

Struct EventLoop 

Source
pub struct EventLoop<T>
where T: 'static,
{ /* private fields */ }
Expand description

Provides a way to retrieve events from the system and from the windows that were registered to the events loop.

An EventLoop can be seen more or less as a “context”. Calling EventLoop::new initializes everything that will be required to create windows. For example on Linux creating an event loop opens a connection to the X or Wayland server.

To wake up an EventLoop from a another thread, see the EventLoopProxy docs.

Note that this cannot be shared across threads (due to platform-dependant logic forbidding it), as such it is neither Send nor Sync. If you need cross-thread access, the Window created from this can be sent to an other thread, and the EventLoopProxy allows you to wake up an EventLoop from another thread.

Implementations§

Source§

impl EventLoop<()>

Source

pub fn new() -> EventLoop<()>

Examples found in repository?
examples/scene_example.rs (line 20)
19fn example() {
20    let el = EventLoop::new();
21    let (vk, window) = Vk::new(&el);
22    window.set_cursor_grab(winit::window::CursorGrabMode::Confined).unwrap();
23    window.set_cursor_visible(false);
24    window.set_title("CHAOS-VK");
25    window.set_window_icon({
26        let w = 8;
27        let h = 8;
28
29        Some(Icon::from_rgba(
30            (0..w*h*4).map(|_| rand_betw(0, 255)).collect(), 
31            w, 
32            h
33        ).unwrap())
34    });
35    window.set_theme(Some(Theme::Dark));
36    window.set_inner_size(PhysicalSize::new(1200, 900));
37    let size = window.inner_size();
38
39    
40    let mut presenter = Presenter::new(vk.clone(), window.clone());
41    let mut renderer = Renderer::new();
42    let mut imgui = ImGui::new(vk.clone(), &presenter);
43
44    renderer.camera.proj = Mat4::perspective_lh(
45        80.0f32.to_radians(), 
46        size.width as f32 / size.height as f32, 0.1, 1000.0
47    );
48
49    let vs = shaders::vs::load(vk.device.clone()).unwrap();
50    let fs = shaders::fs::load(vk.device.clone()).unwrap();
51
52    let rp = render_pass_with_depth(vk.clone(), Some(presenter.swapchain.clone()));
53
54    let pipeline = instancing_pipeline(vk.clone(), vs.clone(), fs.clone(), rp.clone(), Viewport {
55        offset: [0.0, 0.0],
56        extent: size.into(),
57        depth_range: 0.0..=1.0,
58    });
59
60    presenter.window_resized = true;
61    presenter.recreate(vk.clone(), rp.clone(), window.clone());
62
63    let sphere = sphere(5, 1.0);
64    renderer.meshes.push(Mesh::new(vk.clone(), &sphere.vertices, &sphere.indices));
65
66    let mut cursor_x = 0.0;
67    let mut cursor_y = 0.0;
68
69    let data = (0..250).map(|_| { PosInstanceData {
70            ofs: [rand_betw(-100.0, 100.0), rand_betw(-10.0, 10.0), rand_betw(-100.0, 100.0)]
71        }
72    }).collect::<Vec<PosInstanceData>>();
73    renderer.meshes[0].instances = data.clone();
74    let instance_buffer = VkIterBuffer::vertex(vk.allocators.clone(), data);
75    renderer.meshes[0].ibo = instance_buffer;
76
77    let mut dt = 0.0;
78
79    el.run(move |event, _target, control_flow| {
80        control_flow.set_poll();
81
82        match event {
83            Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => {
84                control_flow.set_exit();
85            },
86            Event::WindowEvent { event, .. } => {
87                renderer.camera.input(&event);
88
89                match event {
90                    WindowEvent::KeyboardInput { input, .. } => {
91                        if input.virtual_keycode == Some(VirtualKeyCode::Escape) {
92                            control_flow.set_exit();
93                        }
94
95                        if input.modifiers.ctrl() && input.virtual_keycode == Some(VirtualKeyCode::S) {
96                            Scene::write("assets/scene.cf", &renderer).expect("Failed to write scene");
97                        }
98
99                        if input.modifiers.ctrl() && input.virtual_keycode == Some(VirtualKeyCode::L) {
100                            Scene::read("assets/scene.cf", &mut renderer, vk.clone()).expect("Failed to load scene");
101                        }
102
103                       window.set_cursor_visible(input.modifiers.alt());
104                    },
105
106                    WindowEvent::CursorMoved { position, .. } => {
107                        imgui.on_mouse_move(position.x as f32, position.y as f32);
108                    }
109
110                    WindowEvent::MouseInput { button, state, .. } => {
111                        imgui.on_mouse_click(button, state);
112                    }
113
114                    WindowEvent::MouseWheel { delta: MouseScrollDelta::PixelDelta(pos), .. } => {
115                        imgui.on_mouse_scroll(pos.x as f32, pos.y as f32);
116                    }
117
118                    _ => ()
119                }
120            }
121
122            Event::DeviceEvent {
123                event: DeviceEvent::Text { codepoint }, ..
124            } => {
125                dbg!(codepoint);
126            }
127
128            Event::DeviceEvent { event: DeviceEvent::MouseMotion { delta },.. } => {
129                cursor_x += delta.0 as f32;
130                cursor_y += delta.1 as f32;
131
132                renderer.camera.mouse_callback(cursor_x, cursor_y);
133            }
134
135            Event::MainEventsCleared => {
136                let now = std::time::Instant::now();
137                
138                let frame = imgui.frame(&window);
139                frame.text("hello, world!");
140                frame.text(format!("dt:{:.1}", dt*1000.0));
141                
142                presenter.recreate(vk.clone(), rp.clone(), window.clone());
143
144                renderer.update(dt);
145                presenter.cmd_bufs = get_cmd_bufs(
146                    vk.clone(), 
147                    &renderer,
148                    &mut imgui,
149                    &presenter, 
150                    pipeline.clone()
151                );
152                
153                presenter.present(vk.clone());
154                
155                sleep(Duration::from_millis(16).saturating_sub(Duration::from_millis((dt * 1000.0) as u64)));
156                dt = now.elapsed().as_secs_f32();
157            }
158
159            Event::LoopDestroyed => {println!("EXIT");}
160            _ => {}
161        }
162    });
163}
Source§

impl<T> EventLoop<T>

Source

pub fn with_user_event() -> EventLoop<T>

👎Deprecated: Use EventLoopBuilder::<T>::with_user_event().build() instead.
Source

pub fn run<F>(self, event_handler: F) -> !
where F: 'static + FnMut(Event<'_, T>, &EventLoopWindowTarget<T>, &mut ControlFlow),

Hijacks the calling thread and initializes the winit event loop with the provided closure. Since the closure is 'static, it must be a move closure if it needs to access any data from the calling context.

See the ControlFlow docs for information on how changes to &mut ControlFlow impact the event loop’s behavior.

Any values not passed to this function will not be dropped.

§Platform-specific
  • X11 / Wayland: The program terminates with exit code 1 if the display server disconnects.
Examples found in repository?
examples/scene_example.rs (lines 79-162)
19fn example() {
20    let el = EventLoop::new();
21    let (vk, window) = Vk::new(&el);
22    window.set_cursor_grab(winit::window::CursorGrabMode::Confined).unwrap();
23    window.set_cursor_visible(false);
24    window.set_title("CHAOS-VK");
25    window.set_window_icon({
26        let w = 8;
27        let h = 8;
28
29        Some(Icon::from_rgba(
30            (0..w*h*4).map(|_| rand_betw(0, 255)).collect(), 
31            w, 
32            h
33        ).unwrap())
34    });
35    window.set_theme(Some(Theme::Dark));
36    window.set_inner_size(PhysicalSize::new(1200, 900));
37    let size = window.inner_size();
38
39    
40    let mut presenter = Presenter::new(vk.clone(), window.clone());
41    let mut renderer = Renderer::new();
42    let mut imgui = ImGui::new(vk.clone(), &presenter);
43
44    renderer.camera.proj = Mat4::perspective_lh(
45        80.0f32.to_radians(), 
46        size.width as f32 / size.height as f32, 0.1, 1000.0
47    );
48
49    let vs = shaders::vs::load(vk.device.clone()).unwrap();
50    let fs = shaders::fs::load(vk.device.clone()).unwrap();
51
52    let rp = render_pass_with_depth(vk.clone(), Some(presenter.swapchain.clone()));
53
54    let pipeline = instancing_pipeline(vk.clone(), vs.clone(), fs.clone(), rp.clone(), Viewport {
55        offset: [0.0, 0.0],
56        extent: size.into(),
57        depth_range: 0.0..=1.0,
58    });
59
60    presenter.window_resized = true;
61    presenter.recreate(vk.clone(), rp.clone(), window.clone());
62
63    let sphere = sphere(5, 1.0);
64    renderer.meshes.push(Mesh::new(vk.clone(), &sphere.vertices, &sphere.indices));
65
66    let mut cursor_x = 0.0;
67    let mut cursor_y = 0.0;
68
69    let data = (0..250).map(|_| { PosInstanceData {
70            ofs: [rand_betw(-100.0, 100.0), rand_betw(-10.0, 10.0), rand_betw(-100.0, 100.0)]
71        }
72    }).collect::<Vec<PosInstanceData>>();
73    renderer.meshes[0].instances = data.clone();
74    let instance_buffer = VkIterBuffer::vertex(vk.allocators.clone(), data);
75    renderer.meshes[0].ibo = instance_buffer;
76
77    let mut dt = 0.0;
78
79    el.run(move |event, _target, control_flow| {
80        control_flow.set_poll();
81
82        match event {
83            Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => {
84                control_flow.set_exit();
85            },
86            Event::WindowEvent { event, .. } => {
87                renderer.camera.input(&event);
88
89                match event {
90                    WindowEvent::KeyboardInput { input, .. } => {
91                        if input.virtual_keycode == Some(VirtualKeyCode::Escape) {
92                            control_flow.set_exit();
93                        }
94
95                        if input.modifiers.ctrl() && input.virtual_keycode == Some(VirtualKeyCode::S) {
96                            Scene::write("assets/scene.cf", &renderer).expect("Failed to write scene");
97                        }
98
99                        if input.modifiers.ctrl() && input.virtual_keycode == Some(VirtualKeyCode::L) {
100                            Scene::read("assets/scene.cf", &mut renderer, vk.clone()).expect("Failed to load scene");
101                        }
102
103                       window.set_cursor_visible(input.modifiers.alt());
104                    },
105
106                    WindowEvent::CursorMoved { position, .. } => {
107                        imgui.on_mouse_move(position.x as f32, position.y as f32);
108                    }
109
110                    WindowEvent::MouseInput { button, state, .. } => {
111                        imgui.on_mouse_click(button, state);
112                    }
113
114                    WindowEvent::MouseWheel { delta: MouseScrollDelta::PixelDelta(pos), .. } => {
115                        imgui.on_mouse_scroll(pos.x as f32, pos.y as f32);
116                    }
117
118                    _ => ()
119                }
120            }
121
122            Event::DeviceEvent {
123                event: DeviceEvent::Text { codepoint }, ..
124            } => {
125                dbg!(codepoint);
126            }
127
128            Event::DeviceEvent { event: DeviceEvent::MouseMotion { delta },.. } => {
129                cursor_x += delta.0 as f32;
130                cursor_y += delta.1 as f32;
131
132                renderer.camera.mouse_callback(cursor_x, cursor_y);
133            }
134
135            Event::MainEventsCleared => {
136                let now = std::time::Instant::now();
137                
138                let frame = imgui.frame(&window);
139                frame.text("hello, world!");
140                frame.text(format!("dt:{:.1}", dt*1000.0));
141                
142                presenter.recreate(vk.clone(), rp.clone(), window.clone());
143
144                renderer.update(dt);
145                presenter.cmd_bufs = get_cmd_bufs(
146                    vk.clone(), 
147                    &renderer,
148                    &mut imgui,
149                    &presenter, 
150                    pipeline.clone()
151                );
152                
153                presenter.present(vk.clone());
154                
155                sleep(Duration::from_millis(16).saturating_sub(Duration::from_millis((dt * 1000.0) as u64)));
156                dt = now.elapsed().as_secs_f32();
157            }
158
159            Event::LoopDestroyed => {println!("EXIT");}
160            _ => {}
161        }
162    });
163}
Source

pub fn create_proxy(&self) -> EventLoopProxy<T>

Creates an EventLoopProxy that can be used to dispatch user events to the main event loop.

Methods from Deref<Target = EventLoopWindowTarget<T>>§

Source

pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle>

Returns the list of all the monitors available on the system.

Source

pub fn primary_monitor(&self) -> Option<MonitorHandle>

Returns the primary monitor of the system.

Returns None if it can’t identify any monitor as a primary one.

§Platform-specific

Wayland: Always returns None.

Source

pub fn set_device_event_filter(&self, _filter: DeviceEventFilter)

Change DeviceEvent filter mode.

Since the DeviceEvent capture can lead to high CPU usage for unfocused windows, winit will ignore them by default for unfocused windows on Linux/BSD. This method allows changing this filter at runtime to explicitly capture them again.

§Platform-specific
  • Wayland / macOS / iOS / Android / Web / Orbital: Unsupported.

Trait Implementations§

Source§

impl<T> Debug for EventLoop<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for EventLoop<()>

Source§

fn default() -> EventLoop<()>

Returns the “default value” for a type. Read more
Source§

impl<T> Deref for EventLoop<T>

Source§

type Target = EventLoopWindowTarget<T>

The resulting type after dereferencing.
Source§

fn deref(&self) -> &EventLoopWindowTarget<T>

Dereferences the value.
Source§

impl<T> EventLoopExtRunReturn for EventLoop<T>

Source§

type UserEvent = T

A type provided by the user that can be passed through Event::UserEvent.
Source§

fn run_return<F>(&mut self, event_handler: F) -> i32

Initializes the winit event loop. Read more
Source§

impl<T> HasRawDisplayHandle for EventLoop<T>

Auto Trait Implementations§

§

impl<T> !Freeze for EventLoop<T>

§

impl<T> !RefUnwindSafe for EventLoop<T>

§

impl<T> !Send for EventLoop<T>

§

impl<T> !Sync for EventLoop<T>

§

impl<T> Unpin for EventLoop<T>
where T: Unpin,

§

impl<T> !UnwindSafe for EventLoop<T>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.