-
-
Notifications
You must be signed in to change notification settings - Fork 119
/
renderer.rs
301 lines (253 loc) · 9.07 KB
/
renderer.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
use std::{io, mem::size_of};
use thiserror::Error;
use tracing::debug;
use wgpu::util::DeviceExt as _;
use wgpu_glyph::ab_glyph::InvalidFont;
use winit::{dpi::PhysicalSize, window::Window};
use super::{
config_ui::ConfigUi, draw_config::DrawConfig, drawables::Drawables,
geometries::Geometries, mesh::Mesh, pipelines::Pipelines,
transform::Transform, uniforms::Uniforms, COLOR_FORMAT, DEPTH_FORMAT,
};
#[derive(Debug)]
pub struct Renderer {
surface: wgpu::Surface,
device: wgpu::Device,
queue: wgpu::Queue,
surface_config: wgpu::SurfaceConfiguration,
depth_view: wgpu::TextureView,
uniform_buffer: wgpu::Buffer,
bind_group: wgpu::BindGroup,
geometries: Geometries,
pipelines: Pipelines,
config_ui: ConfigUi,
}
impl Renderer {
pub async fn new(window: &Window) -> Result<Self, InitError> {
let instance = wgpu::Instance::new(wgpu::Backends::VULKAN);
// This is sound, as `window` is an object to create a surface upon.
let surface = unsafe { instance.create_surface(window) };
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
force_fallback_adapter: false,
compatible_surface: Some(&surface),
})
.await
.ok_or(InitError::RequestAdapter)?;
let (device, queue) = adapter
.request_device(
&wgpu::DeviceDescriptor {
label: None,
// TASK: Check available features via `Adapter::features`
// before requesting them here. Otherwise, the call
// to `request_device` might fail.
//
// In addition, the available features must be stored
// somewhere, so code that requires any unavailable
// ones isn't run.
features: wgpu::Features::POLYGON_MODE_LINE,
limits: wgpu::Limits::default(),
},
None,
)
.await?;
let size = window.inner_size();
let surface_config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: COLOR_FORMAT,
width: size.width,
height: size.height,
present_mode: wgpu::PresentMode::Fifo,
};
surface.configure(&device, &surface_config);
let depth_view = Self::create_depth_buffer(&device, &surface_config);
let uniform_buffer =
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: None,
contents: bytemuck::cast_slice(&[Uniforms::default()]),
usage: wgpu::BufferUsages::UNIFORM
| wgpu::BufferUsages::COPY_DST,
});
let bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::all(),
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: wgpu::BufferSize::new(size_of::<
Uniforms,
>(
)
as u64),
},
count: None,
}],
label: None,
});
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &bind_group_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
buffer: &uniform_buffer,
offset: 0,
size: None,
}),
}],
label: None,
});
let geometries = Geometries::new(&device, &Mesh::empty());
let pipelines = Pipelines::new(&device, &bind_group_layout);
let config_ui = ConfigUi::new(&device)?;
Ok(Self {
surface,
device,
queue,
surface_config,
depth_view,
uniform_buffer,
bind_group,
geometries,
pipelines,
config_ui,
})
}
pub fn update_geometry(&mut self, mesh: Mesh) {
self.geometries = Geometries::new(&self.device, &mesh);
}
pub fn handle_resize(&mut self, size: PhysicalSize<u32>) {
self.surface_config.width = size.width;
self.surface_config.height = size.height;
self.surface.configure(&self.device, &self.surface_config);
let depth_view =
Self::create_depth_buffer(&self.device, &self.surface_config);
self.depth_view = depth_view;
}
pub fn draw(
&mut self,
transform: &Transform,
config: &DrawConfig,
) -> Result<(), DrawError> {
let uniforms = Uniforms {
transform: transform.to_native(self.aspect_ratio()),
transform_normals: transform.to_normals_transform(),
..Uniforms::default()
};
self.queue.write_buffer(
&self.uniform_buffer,
0,
bytemuck::cast_slice(&[uniforms]),
);
let surface_texture = self.surface.get_current_texture()?;
let color_view = surface_texture
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder = self.device.create_command_encoder(
&wgpu::CommandEncoderDescriptor { label: None },
);
self.clear_views(&mut encoder, &color_view);
let drawables = Drawables::new(&self.geometries, &self.pipelines);
if config.draw_model {
drawables.model.draw(
&mut encoder,
&color_view,
&self.depth_view,
&self.bind_group,
);
}
if config.draw_mesh {
drawables.mesh.draw(
&mut encoder,
&color_view,
&self.depth_view,
&self.bind_group,
);
}
self.config_ui
.draw(
&self.device,
&mut encoder,
&color_view,
&self.surface_config,
config,
)
.map_err(|err| DrawError::Text(err))?;
let command_buffer = encoder.finish();
self.queue.submit(Some(command_buffer));
debug!("Presenting...");
surface_texture.present();
debug!("Finished drawing.");
Ok(())
}
fn create_depth_buffer(
device: &wgpu::Device,
surface_config: &wgpu::SurfaceConfiguration,
) -> wgpu::TextureView {
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width: surface_config.width,
height: surface_config.height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: DEPTH_FORMAT,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
});
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
view
}
fn aspect_ratio(&self) -> f32 {
self.surface_config.width as f32 / self.surface_config.height as f32
}
fn clear_views(
&self,
encoder: &mut wgpu::CommandEncoder,
view: &wgpu::TextureView,
) {
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[wgpu::RenderPassColorAttachment {
view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::WHITE),
store: true,
},
}],
depth_stencil_attachment: Some(
wgpu::RenderPassDepthStencilAttachment {
view: &self.depth_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: true,
}),
stencil_ops: None,
},
),
});
}
}
#[derive(Error, Debug)]
pub enum InitError {
#[error("I/O error")]
Io(#[from] io::Error),
#[error("Error request adapter")]
RequestAdapter,
#[error("Error requesting device")]
RequestDevice(#[from] wgpu::RequestDeviceError),
#[error("Error loading font")]
InvalidFont(#[from] InvalidFont),
}
#[derive(Error, Debug)]
pub enum DrawError {
#[error("Error acquiring output surface")]
Surface(#[from] wgpu::SurfaceError),
#[error("Error drawing text")]
Text(String),
}