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<()>
impl EventLoop<()>
Sourcepub fn new() -> EventLoop<()>
pub fn new() -> EventLoop<()>
Alias for EventLoopBuilder::new().build().
Examples found in repository?
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>
impl<T> EventLoop<T>
pub fn with_user_event() -> EventLoop<T>
EventLoopBuilder::<T>::with_user_event().build() instead.Sourcepub fn run<F>(self, event_handler: F) -> !
pub fn run<F>(self, event_handler: F) -> !
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?
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}Sourcepub fn create_proxy(&self) -> EventLoopProxy<T>
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>>§
Sourcepub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle>
pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle>
Returns the list of all the monitors available on the system.
Sourcepub fn primary_monitor(&self) -> Option<MonitorHandle>
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.
Sourcepub fn set_device_event_filter(&self, _filter: DeviceEventFilter)
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> Deref for EventLoop<T>
impl<T> Deref for EventLoop<T>
Source§type Target = EventLoopWindowTarget<T>
type Target = EventLoopWindowTarget<T>
Source§fn deref(&self) -> &EventLoopWindowTarget<T>
fn deref(&self) -> &EventLoopWindowTarget<T>
Source§impl<T> EventLoopExtRunReturn for EventLoop<T>
impl<T> EventLoopExtRunReturn for EventLoop<T>
Source§type UserEvent = T
type UserEvent = T
Event::UserEvent.Source§fn run_return<F>(&mut self, event_handler: F) -> i32where
F: FnMut(Event<'_, <EventLoop<T> as EventLoopExtRunReturn>::UserEvent>, &EventLoopWindowTarget<<EventLoop<T> as EventLoopExtRunReturn>::UserEvent>, &mut ControlFlow),
fn run_return<F>(&mut self, event_handler: F) -> i32where
F: FnMut(Event<'_, <EventLoop<T> as EventLoopExtRunReturn>::UserEvent>, &EventLoopWindowTarget<<EventLoop<T> as EventLoopExtRunReturn>::UserEvent>, &mut ControlFlow),
winit event loop. Read moreSource§impl<T> HasRawDisplayHandle for EventLoop<T>
impl<T> HasRawDisplayHandle for EventLoop<T>
Source§fn raw_display_handle(&self) -> RawDisplayHandle
fn raw_display_handle(&self) -> RawDisplayHandle
Returns a raw_window_handle::RawDisplayHandle for the event loop.