-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmod.rs
305 lines (252 loc) · 10 KB
/
mod.rs
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
use imgui::{Context, FontConfig, FontGlyphRanges, FontSource, Ui};
use imgui_winit_support::{HiDpiMode, WinitPlatform};
use std::time::Instant;
use std::time::Duration;
use vulkano::command_buffer::AutoCommandBufferBuilder;
use vulkano::image::view::ImageView;
use vulkano::device::{Device, DeviceExtensions};
use vulkano::image::{ImageUsage, SwapchainImage};
use vulkano::instance::{Instance, PhysicalDevice};
use vulkano::swapchain;
use vulkano::swapchain::{
AcquireError, ColorSpace, FullscreenExclusive, PresentMode, SurfaceTransform, Swapchain,
SwapchainCreationError,
};
use vulkano::format::Format;
use vulkano::sync;
use vulkano::device::Queue;
use vulkano::sync::{FlushError, GpuFuture};
use vulkano::swapchain::Surface;
use vulkano_win::VkSurfaceBuild;
use winit::event::{Event, WindowEvent};
use winit::event_loop::{ControlFlow, EventLoop};
use winit::window::{Window, WindowBuilder};
use std::sync::Arc;
use imgui_vulkano_renderer::Renderer;
mod clipboard;
pub struct System {
pub event_loop: EventLoop<()>,
pub device : Arc<Device>,
pub queue : Arc<Queue>,
pub surface: Arc<Surface<Window>>,
pub swapchain : Arc<Swapchain<Window>>,
pub images : Vec<Arc<SwapchainImage<Window>>>,
pub imgui: Context,
pub platform: WinitPlatform,
pub renderer: Renderer,
pub font_size: f32,
}
pub fn init(title: &str) -> System {
let required_extensions = vulkano_win::required_extensions();
let instance = Instance::new(None, &required_extensions, None).unwrap();
let physical = PhysicalDevice::enumerate(&instance).next().unwrap();
let title = match title.rfind('/') {
Some(idx) => title.split_at(idx + 1).1,
None => title,
};
let event_loop = EventLoop::new();
let surface = WindowBuilder::new()
.with_title(title.to_owned())
.build_vk_surface(&event_loop, instance.clone())
.expect("Failed to create a window");
let queue_family = physical
.queue_families()
.find(|&q| {
// We take the first queue that supports drawing to our window.
q.supports_graphics() && surface.is_supported(q).unwrap_or(false)
})
.unwrap();
let device_ext = DeviceExtensions {
khr_swapchain: true,
..DeviceExtensions::none()
};
let (device, mut queues) = Device::new(
physical,
physical.supported_features(),
&device_ext,
[(queue_family, 0.5)].iter().cloned(),
)
.unwrap();
let queue = queues.next().unwrap();
// not sure why this was needed
#[allow(unused_assignments)]
let mut format = Format::R8G8B8A8Srgb;
let (swapchain, images) = {
let caps = surface.capabilities(physical).unwrap();
let alpha = caps.supported_composite_alpha.iter().next().unwrap();
format = caps.supported_formats[0].0;
let dimensions: [u32; 2] = surface.window().inner_size().into();
let image_usage = ImageUsage {
transfer_destination : true,
..ImageUsage::color_attachment()
};
Swapchain::start(device.clone(), surface.clone())
.num_images(caps.min_image_count)
.format(format)
.dimensions(dimensions)
.layers(1)
.usage(image_usage)
.transform(SurfaceTransform::Identity)
.composite_alpha(alpha)
.present_mode(PresentMode::Fifo)
.fullscreen_exclusive(FullscreenExclusive::Default)
.clipped(true)
.color_space(ColorSpace::SrgbNonLinear)
.build()
.expect("Failed to create swapchain")
};
let mut imgui = Context::create();
imgui.set_ini_filename(None);
if let Some(backend) = clipboard::init() {
imgui.set_clipboard_backend(Box::new(backend));
} else {
eprintln!("Failed to initialize clipboard");
}
let mut platform = WinitPlatform::init(&mut imgui);
platform.attach_window(imgui.io_mut(), &surface.window(), HiDpiMode::Rounded);
let hidpi_factor = platform.hidpi_factor();
let font_size = (13.0 * hidpi_factor) as f32;
imgui.fonts().add_font(&[
FontSource::DefaultFontData {
config: Some(FontConfig {
size_pixels: font_size,
..FontConfig::default()
}),
},
FontSource::TtfData {
data: include_bytes!("../resources/mplus-1p-regular.ttf"),
size_pixels: font_size,
config: Some(FontConfig {
rasterizer_multiply: 1.75,
glyph_ranges: FontGlyphRanges::japanese(),
..FontConfig::default()
}),
},
]);
imgui.io_mut().font_global_scale = (1.0 / hidpi_factor) as f32;
let renderer = Renderer::init(&mut imgui, device.clone(), queue.clone(), format).expect("Failed to initialize renderer");
System {
event_loop,
device,
queue,
surface,
swapchain,
images,
imgui,
platform,
renderer,
font_size,
}
}
impl System {
pub fn main_loop<F: FnMut(&mut bool, &mut Ui) + 'static>(self, mut run_ui: F) {
let System {
event_loop,
device,
queue,
surface,
mut swapchain,
mut images,
mut imgui,
mut platform,
mut renderer,
..
} = self;
let mut recreate_swapchain = false;
let mut previous_frame_end = Some(sync::now(device.clone()).boxed());
let mut last_redraw = Instant::now();
// target 60 fps
let target_frame_time = Duration::from_millis(1000 / 60);
event_loop.run(move |event, _, control_flow| match event {
Event::NewEvents(_) => {
// imgui.io_mut().update_delta_time(Instant::now());
}
Event::MainEventsCleared => {
platform
.prepare_frame(imgui.io_mut(), &surface.window())
.expect("Failed to prepare frame");
surface.window().request_redraw();
}
Event::RedrawRequested(_) => {
let t = Instant::now();
let since_last = t.duration_since(last_redraw);
last_redraw = t;
if since_last > target_frame_time {
if since_last < target_frame_time {
std::thread::sleep(target_frame_time - since_last);
}
}
previous_frame_end.as_mut().unwrap().cleanup_finished();
if recreate_swapchain {
let dimensions: [u32; 2] = surface.window().inner_size().into();
let (new_swapchain, new_images) =
match swapchain.recreate().dimensions(dimensions).build() {
Ok(r) => r,
Err(SwapchainCreationError::UnsupportedDimensions) => return,
Err(e) => panic!("Failed to recreate swapchain: {:?}", e),
};
images = new_images;
swapchain = new_swapchain;
recreate_swapchain = false;
}
let mut ui = imgui.frame();
let mut run = true;
run_ui(&mut run, &mut ui);
if !run {
*control_flow = ControlFlow::Exit;
}
let (image_num, suboptimal, acquire_future) =
match swapchain::acquire_next_image(swapchain.clone(), None) {
Ok(r) => r,
Err(AcquireError::OutOfDate) => {
recreate_swapchain = true;
return;
}
Err(e) => panic!("Failed to acquire next image: {:?}", e),
};
if suboptimal {
recreate_swapchain = true;
}
platform.prepare_render(&ui, surface.window());
let draw_data = ui.render();
let mut cmd_buf_builder = AutoCommandBufferBuilder::primary(device.clone(), queue.family(), vulkano::command_buffer::CommandBufferUsage::OneTimeSubmit)
.expect("Failed to create command buffer");
cmd_buf_builder.clear_color_image(images[image_num].clone(), [0.0; 4].into())
.expect("Failed to create image clear command");
renderer
.draw_commands(&mut cmd_buf_builder, queue.clone(), ImageView::new(images[image_num].clone()).unwrap(), draw_data)
.expect("Rendering failed");
let cmd_buf = cmd_buf_builder.build()
.expect("Failed to build command buffer");
let future = previous_frame_end
.take()
.unwrap()
.join(acquire_future)
.then_execute(queue.clone(), cmd_buf)
.unwrap()
.then_signal_fence()
.then_swapchain_present(queue.clone(), swapchain.clone(), image_num);
match future.flush() {
Ok(_) => {
previous_frame_end = Some(future.boxed());
}
Err(FlushError::OutOfDate) => {
recreate_swapchain = true;
previous_frame_end = Some(sync::now(device.clone()).boxed());
}
Err(e) => {
println!("Failed to flush future: {:?}", e);
previous_frame_end = Some(sync::now(device.clone()).boxed());
}
}
}
Event::WindowEvent {
event: WindowEvent::CloseRequested,
..
} => *control_flow = ControlFlow::Exit,
event => {
platform.handle_event(imgui.io_mut(), surface.window(), &event);
}
})
}
}