-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtriangles.rs
More file actions
295 lines (268 loc) · 7.75 KB
/
triangles.rs
File metadata and controls
295 lines (268 loc) · 7.75 KB
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
#![allow(clippy::needless_return)]
use lambda::{
component::Component,
events::{
Events,
Key,
VirtualKey,
WindowEvent,
},
render::{
command::RenderCommand,
pipeline::{
self,
PipelineStage,
},
render_pass,
shader::{
Shader,
ShaderBuilder,
ShaderKind,
VirtualShader,
},
viewport,
RenderContext,
},
runtime::start_runtime,
runtimes::{
application::ComponentResult,
ApplicationRuntimeBuilder,
},
};
pub struct TrianglesComponent {
triangle_vertex: Shader,
vertex_shader: Shader,
render_pass: Option<lambda::render::ResourceId>,
render_pipeline: Option<lambda::render::ResourceId>,
width: u32,
height: u32,
animation_scalar: f32,
position: (f32, f32),
}
impl Component<ComponentResult, String> for TrianglesComponent {
fn on_attach(
&mut self,
render_context: &mut RenderContext,
) -> Result<ComponentResult, String> {
let render_pass = render_pass::RenderPassBuilder::new().build(
render_context.gpu(),
render_context.surface_format(),
render_context.depth_format(),
);
let push_constants_size = std::mem::size_of::<PushConstant>() as u32;
let pipeline = pipeline::RenderPipelineBuilder::new()
.with_culling(pipeline::CullingMode::None)
.with_push_constant(PipelineStage::VERTEX, push_constants_size)
.build(
render_context.gpu(),
render_context.surface_format(),
render_context.depth_format(),
&render_pass,
&self.vertex_shader,
Some(&self.triangle_vertex),
);
self.render_pass = Some(render_context.attach_render_pass(render_pass));
self.render_pipeline = Some(render_context.attach_pipeline(pipeline));
logging::info!("Attached the DemoComponent.");
return Ok(ComponentResult::Success);
}
fn on_detach(
&mut self,
_render_context: &mut RenderContext,
) -> Result<ComponentResult, String> {
return Ok(ComponentResult::Success);
}
fn on_render(
&mut self,
_render_context: &mut lambda::render::RenderContext,
) -> Vec<RenderCommand> {
let viewport =
viewport::ViewportBuilder::new().build(self.width, self.height);
let (x, y) = self.position;
let triangle_data = &[
PushConstant {
color: [
1.0,
1.0 * self.animation_scalar,
0.5 * self.animation_scalar,
1.0,
],
pos: [x, y],
scale: [0.3, 0.3],
},
PushConstant {
color: [0.0, 1.0, 0.0, 1.0],
pos: [0.5, 0.0],
scale: [0.4, 0.4],
},
PushConstant {
color: [0.0, 0.0, 1.0, 1.0],
pos: [0.25, 0.5],
scale: [0.5, 0.5],
},
PushConstant {
color: [1.0, 1.0, 1.0, 1.0],
pos: [0.0, 0.0],
scale: [0.5, 0.5],
},
];
let render_pipeline = self
.render_pipeline
.expect("No render pipeline actively set for rendering.");
// All state setting must be inside the render pass
let mut commands = vec![RenderCommand::BeginRenderPass {
render_pass: self
.render_pass
.expect("Cannot begin the render pass when it doesn't exist.")
.clone(),
viewport: viewport.clone(),
}];
commands.push(RenderCommand::SetPipeline {
pipeline: render_pipeline.clone(),
});
commands.push(RenderCommand::SetViewports {
start_at: 0,
viewports: vec![viewport.clone()],
});
commands.push(RenderCommand::SetScissors {
start_at: 0,
viewports: vec![viewport.clone()],
});
// Upload triangle data into the the GPU at the vertex stage of the pipeline
// before requesting to draw each triangle.
for triangle in triangle_data {
commands.push(RenderCommand::PushConstants {
pipeline: render_pipeline.clone(),
stage: PipelineStage::VERTEX,
offset: 0,
bytes: Vec::from(push_constants_to_bytes(triangle)),
});
commands.push(RenderCommand::Draw {
vertices: 0..3,
instances: 0..1,
});
}
commands.push(RenderCommand::EndRenderPass);
return commands;
}
fn on_event(&mut self, event: Events) -> Result<ComponentResult, String> {
match event {
Events::Runtime { event, issued_at } => match event {
lambda::events::RuntimeEvent::Shutdown => {
logging::info!("Shutting down the runtime");
}
_ => {}
},
Events::Window { event, issued_at } => match event {
WindowEvent::Resize { width, height } => {
logging::info!("Window resized to {}x{}", width, height);
self.width = width;
self.height = height;
}
WindowEvent::Close => {
logging::info!("Window closed");
}
},
Events::Component { event, issued_at } => todo!(),
Events::Keyboard { event, issued_at } => match event {
Key::Pressed {
scan_code,
virtual_key,
} => match virtual_key {
Some(VirtualKey::KeyW) => {
self.position.1 -= 0.01;
}
Some(VirtualKey::KeyS) => {
self.position.1 += 0.01;
}
Some(VirtualKey::KeyA) => {
self.position.0 -= 0.01;
}
Some(VirtualKey::KeyD) => {
self.position.0 += 0.01;
}
_ => {}
},
_ => {}
},
_ => {}
};
return Ok(ComponentResult::Success);
}
fn on_update(
&mut self,
last_frame: &std::time::Duration,
) -> Result<ComponentResult, String> {
match last_frame.as_millis() > 20 {
true => {
logging::warn!("Last frame took {}ms", last_frame.as_millis());
}
false => {}
};
return Ok(ComponentResult::Success);
}
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct PushConstant {
color: [f32; 4],
pos: [f32; 2],
scale: [f32; 2],
}
pub fn push_constants_to_bytes(push_constants: &PushConstant) -> &[u32] {
let bytes = unsafe {
let size_in_bytes = std::mem::size_of::<PushConstant>();
let size_in_u32 = size_in_bytes / std::mem::size_of::<u32>();
let ptr = push_constants as *const PushConstant as *const u32;
std::slice::from_raw_parts(ptr, size_in_u32)
};
return bytes;
}
impl Default for TrianglesComponent {
/// Load in shaders upon creation.
fn default() -> Self {
// Specify virtual shaders to use for rendering
let triangle_vertex = VirtualShader::Source {
source: include_str!("../assets/shaders/triangles.vert").to_string(),
kind: ShaderKind::Vertex,
name: String::from("triangles"),
entry_point: String::from("main"),
};
let triangle_fragment = VirtualShader::Source {
source: include_str!("../assets/shaders/triangles.frag").to_string(),
kind: ShaderKind::Fragment,
name: String::from("triangles"),
entry_point: String::from("main"),
};
// Create a shader builder to compile the shaders.
let mut builder = ShaderBuilder::new();
let vs = builder.build(triangle_vertex);
let fs = builder.build(triangle_fragment);
return TrianglesComponent {
vertex_shader: vs,
triangle_vertex: fs,
render_pass: None,
render_pipeline: None,
width: 800,
height: 600,
animation_scalar: 0.0,
position: (0.0, 0.0),
};
}
}
fn main() {
let runtime = ApplicationRuntimeBuilder::new("Multiple Triangles Demo")
.with_renderer_configured_as(move |render_context_builder| {
return render_context_builder.with_render_timeout(1_000_000_000);
})
.with_window_configured_as(move |window_builder| {
return window_builder
.with_dimensions(800, 600)
.with_name("Triangles");
})
.with_component(move |runtime, triangles: TrianglesComponent| {
return (runtime, triangles);
})
.build();
start_runtime(runtime);
}