Vertex Array#
VertexArray
is something like a pipeline, where as arguments Context.vertex_array()
takes a Program
, a Buffer
with input data, and the names of input variables for this program.
VertexArray
in ModernGL can be initialized in two ways: one buffer for all input variables or multiple buffers for all input variables.
One input buffer for all input variables (simple VertexArray
version):
vao = ctx.vertex_array(program, buffer, 'input_var1', 'input_var2')
Multiple input buffers for all input variables:
vao = ctx.vertex_array(
program,
[
(buffer1, '3f 2f', 'input_var1', 'input_var2'),
(buffer2, '4f', 'input_var3')
]
)
You can understand '3f 2f'
and '4f'
as the type of the input variable (or variables), that is, 3 floats and 2 floats, which form, for example, vec3 + vec2
and 4 floats, which form vec4
.
In our example we use a simple implementation of this method.
Entire source
1import moderngl
2import numpy as np
3
4ctx = moderngl.create_context(standalone=True)
5
6prog = ctx.program(
7 vertex_shader="""
8 #version 330
9
10 in vec2 in_vert;
11 in vec3 in_color;
12
13 out vec3 v_color;
14
15 void main() {
16 v_color = in_color;
17 gl_Position = vec4(in_vert, 0.0, 1.0);
18 }
19 """,
20 fragment_shader="""
21 #version 330
22
23 in vec3 v_color;
24
25 out vec3 f_color;
26
27 void main() {
28 f_color = v_color;
29 }
30 """,
31)
32
33x = np.linspace(-1.0, 1.0, 50)
34y = np.random.rand(50) - 0.5
35r = np.zeros(50)
36g = np.ones(50)
37b = np.zeros(50)
38
39vertices = np.dstack([x, y, r, g, b])
40
41vbo = ctx.buffer(vertices.astype("f4").tobytes())
42vao = ctx.vertex_array(prog, vbo, "in_vert", "in_color")
Proceed to the next step.