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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
use std::ptr;
use crate::BufferExt;
use crate::BufferSliceExt;
use crate::ProgramExt;
use crate::DrawError;
use crate::UniformsExt;
use crate::context::Context;
use crate::ContextExt;
use crate::TransformFeedbackSessionExt;
use crate::fbo::{self, ValidatedAttachments};
use crate::uniforms::Uniforms;
use crate::{Program, ToGlEnum};
use crate::index::{self, IndicesSource};
use crate::vertex::{MultiVerticesSource, VerticesSource, TransformFeedbackSession};
use crate::vertex_array_object::VertexAttributesSystem;
use crate::draw_parameters::DrawParameters;
use crate::{gl, context, draw_parameters};
use crate::version::Version;
use crate::version::Api;
/// Draws everything.
pub fn draw<'a, U, V>(context: &Context, framebuffer: Option<&ValidatedAttachments<'_>>,
vertex_buffers: V, indices: IndicesSource<'_>,
program: &Program, uniforms: &U, draw_parameters: &DrawParameters<'_>,
dimensions: (u32, u32)) -> Result<(), DrawError>
where U: Uniforms, V: MultiVerticesSource<'a>
{
// this contains the list of fences that will need to be fulfilled after the draw command
// has started
let mut fences = Vec::with_capacity(0);
// handling tessellation
let vertices_per_patch = match indices.get_primitives_type() {
index::PrimitiveType::Patches { vertices_per_patch } => {
if let Some(max) = context.capabilities().max_patch_vertices {
if vertices_per_patch == 0 || vertices_per_patch as gl::types::GLint > max {
return Err(DrawError::UnsupportedVerticesPerPatch);
}
} else {
return Err(DrawError::TessellationNotSupported);
}
// TODO: programs created from binaries have the wrong value
// for `has_tessellation_shaders`
/*if !program.has_tessellation_shaders() { // TODO:
panic!("Default tessellation level is not supported yet");
}*/
Some(vertices_per_patch)
},
_ => {
// TODO: programs created from binaries have the wrong value
// for `has_tessellation_shaders`
/*if program.has_tessellation_shaders() {
return Err(DrawError::TessellationWithoutPatches);
}*/
None
},
};
// starting the state changes
let mut ctxt = context.make_current();
// handling vertices source
let (vertices_count, instances_count, base_vertex) = {
let index_buffer = match indices {
IndicesSource::IndexBuffer { buffer, .. } => Some(buffer),
IndicesSource::MultidrawArray { .. } => None,
IndicesSource::MultidrawElement { indices, .. } => Some(indices),
IndicesSource::NoIndices { .. } => None,
};
// determining whether we can use the `base_vertex` variants for drawing
let use_base_vertex = match indices {
IndicesSource::MultidrawArray { .. } => false,
IndicesSource::MultidrawElement { .. } => false,
IndicesSource::NoIndices { .. } => true,
_ => ctxt.version >= &Version(Api::Gl, 3, 2) ||
ctxt.version >= &Version(Api::GlEs, 3, 2) ||
ctxt.extensions.gl_arb_draw_elements_base_vertex ||
ctxt.extensions.gl_oes_draw_elements_base_vertex
};
// object that is used to build the bindings
let mut binder = VertexAttributesSystem::start(&mut ctxt, program, index_buffer,
use_base_vertex);
// number of vertices in the vertices sources, or `None` if there is a mismatch
let mut vertices_count: Option<usize> = None;
// number of instances to draw
let mut instances_count: Option<usize> = None;
for src in vertex_buffers.iter() {
// Allow single match for consistency with the match below.
// Integrating the two matches wouldn't improve the code either.
#[allow(clippy::single_match)]
match src {
VerticesSource::VertexBuffer(buffer, format, per_instance) => {
// TODO: assert!(buffer.get_elements_size() == total_size(format));
if let Some(fence) = buffer.add_fence() {
fences.push(fence);
}
binder = binder.add(&buffer, format, if per_instance { Some(1) } else { None });
},
_ => {}
}
match src {
VerticesSource::VertexBuffer(ref buffer, _, false) => {
if let Some(curr) = vertices_count {
if curr != buffer.get_elements_count() {
vertices_count = None;
break;
}
} else {
vertices_count = Some(buffer.get_elements_count());
}
},
VerticesSource::VertexBuffer(ref buffer, _, true) => {
if let Some(curr) = instances_count {
if curr != buffer.get_elements_count() {
return Err(DrawError::InstancesCountMismatch);
}
} else {
instances_count = Some(buffer.get_elements_count());
}
},
VerticesSource::Marker { len, per_instance } if !per_instance => {
if let Some(curr) = vertices_count {
if curr != len {
vertices_count = None;
break;
}
} else {
vertices_count = Some(len);
}
},
VerticesSource::Marker { len, per_instance } if per_instance => {
if let Some(curr) = instances_count {
if curr != len {
return Err(DrawError::InstancesCountMismatch);
}
} else {
instances_count = Some(len);
}
},
_ => ()
}
}
(vertices_count, instances_count, binder.bind().unwrap_or(0))
};
// binding the FBO to draw upon
{
let fbo_id = fbo::FramebuffersContainer::get_framebuffer_for_drawing(&mut ctxt, framebuffer);
unsafe { fbo::bind_framebuffer(&mut ctxt, fbo_id, true, false) };
};
// binding the program and uniforms
program.use_program(&mut ctxt);
uniforms.bind_uniforms(&mut ctxt, program, &mut fences)?;
// sync-ing draw_parameters
unsafe {
draw_parameters::sync(&mut ctxt, draw_parameters, dimensions, indices.get_primitives_type())?;
sync_vertices_per_patch(&mut ctxt, vertices_per_patch);
// TODO: make sure that the program is the right one
// TODO: changing the current transform feedback requires pausing/unbinding before changing the program
if let Some(ref tf) = draw_parameters.transform_feedback {
tf.bind(&mut ctxt, indices.get_primitives_type());
} else {
TransformFeedbackSession::unbind(&mut ctxt);
}
}
// drawing
// TODO: make this code more readable
{
match &indices {
IndicesSource::IndexBuffer { ref buffer, data_type, primitives } => {
let ptr: *const u8 = ptr::null_mut();
let ptr = unsafe { ptr.add(buffer.get_offset_bytes()) };
if let Some(fence) = buffer.add_fence() {
fences.push(fence);
}
unsafe {
if let Some(instances_count) = instances_count {
if base_vertex != 0 {
if ctxt.version >= &Version(Api::Gl, 3, 2) ||
ctxt.version >= &Version(Api::GlEs, 3, 2) ||
ctxt.extensions.gl_arb_draw_elements_base_vertex
{
ctxt.gl.DrawElementsInstancedBaseVertex(primitives.to_glenum(),
buffer.get_elements_count() as
gl::types::GLsizei,
data_type.to_glenum(),
ptr as *const _,
instances_count as
gl::types::GLsizei,
base_vertex);
} else if ctxt.extensions.gl_oes_draw_elements_base_vertex {
ctxt.gl.DrawElementsInstancedBaseVertexOES(primitives.to_glenum(),
buffer.get_elements_count() as
gl::types::GLsizei,
data_type.to_glenum(),
ptr as *const _,
instances_count as
gl::types::GLsizei,
base_vertex);
} else {
unreachable!();
}
} else {
ctxt.gl.DrawElementsInstanced(primitives.to_glenum(),
buffer.get_elements_count() as
gl::types::GLsizei,
data_type.to_glenum(),
ptr as *const _,
instances_count as gl::types::GLsizei);
}
} else if base_vertex != 0 {
if ctxt.version >= &Version(Api::Gl, 3, 2) ||
ctxt.version >= &Version(Api::GlEs, 3, 2) ||
ctxt.extensions.gl_arb_draw_elements_base_vertex
{
ctxt.gl.DrawElementsBaseVertex(primitives.to_glenum(),
buffer.get_elements_count() as
gl::types::GLsizei,
data_type.to_glenum(),
ptr as *const _,
base_vertex);
} else if ctxt.extensions.gl_oes_draw_elements_base_vertex {
ctxt.gl.DrawElementsBaseVertexOES(primitives.to_glenum(),
buffer.get_elements_count() as
gl::types::GLsizei,
data_type.to_glenum(),
ptr as *const _,
base_vertex);
} else {
unreachable!();
}
} else {
ctxt.gl.DrawElements(primitives.to_glenum(),
buffer.get_elements_count() as gl::types::GLsizei,
data_type.to_glenum(),
ptr as *const _);
}
}
},
IndicesSource::MultidrawArray { ref buffer, primitives } => {
let ptr: *const u8 = ptr::null_mut();
let ptr = unsafe { ptr.add(buffer.get_offset_bytes()) };
debug_assert_eq!(base_vertex, 0); // enforced earlier in this function
if let Some(fence) = buffer.add_fence() {
fences.push(fence);
}
unsafe {
buffer.prepare_and_bind_for_draw_indirect(&mut ctxt);
ctxt.gl.MultiDrawArraysIndirect(primitives.to_glenum(), ptr as *const _,
buffer.get_elements_count() as gl::types::GLsizei,
0);
}
},
IndicesSource::MultidrawElement { ref commands, ref indices, data_type, primitives } => {
let cmd_ptr: *const u8 = ptr::null_mut();
let cmd_ptr = unsafe { cmd_ptr.add(commands.get_offset_bytes()) };
if let Some(fence) = commands.add_fence() {
fences.push(fence);
}
if let Some(fence) = indices.add_fence() {
fences.push(fence);
}
unsafe {
commands.prepare_and_bind_for_draw_indirect(&mut ctxt);
debug_assert_eq!(base_vertex, 0); // enforced earlier in this function
ctxt.gl.MultiDrawElementsIndirect(primitives.to_glenum(), data_type.to_glenum(),
cmd_ptr as *const _,
commands.get_elements_count() as gl::types::GLsizei,
0);
}
},
IndicesSource::NoIndices { primitives } => {
let vertices_count = match vertices_count {
Some(c) => c,
None => return Err(DrawError::VerticesSourcesLengthMismatch)
};
unsafe {
if let Some(instances_count) = instances_count {
ctxt.gl.DrawArraysInstanced(primitives.to_glenum(), base_vertex,
vertices_count as gl::types::GLsizei,
instances_count as gl::types::GLsizei);
} else {
ctxt.gl.DrawArrays(primitives.to_glenum(), base_vertex,
vertices_count as gl::types::GLsizei);
}
}
},
};
};
ctxt.state.next_draw_call_id += 1;
// fulfilling the fences
for fence in fences.into_iter() {
fence.insert(&mut ctxt);
}
Ok(())
}
unsafe fn sync_vertices_per_patch(ctxt: &mut context::CommandContext<'_>, vertices_per_patch: Option<u16>) {
if let Some(vertices_per_patch) = vertices_per_patch {
let vertices_per_patch = vertices_per_patch as gl::types::GLint;
if ctxt.state.patch_patch_vertices != vertices_per_patch {
ctxt.gl.PatchParameteri(gl::PATCH_VERTICES, vertices_per_patch);
ctxt.state.patch_patch_vertices = vertices_per_patch;
}
}
}