Moderngl Readthedocs Io en 5.6.1
Moderngl Readthedocs Io en 5.6.1
Release 5.6.1
Szabolcs Dombi
1 Install 3
1.1 From PyPI (pip) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Development environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2 The Guide 5
2.1 A short introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 Install ModernGL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.3 Context Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.4 Buffer Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.5 Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.6 VertexArray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.7 Rendering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.8 Headless on Ubuntu 18 Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3 Reference 19
3.1 Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.2 Buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.3 VertexArray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.4 Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.5 Sampler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
3.6 Texture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.7 TextureArray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
3.8 Texture3D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
3.9 TextureCube . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
3.10 Framebuffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
3.11 Renderbuffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
3.12 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
3.13 Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
3.14 ConditionalRender . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
3.15 ComputeShader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
4 Miscellaneous 83
4.1 Differences between ModernGL5 and ModernGL4 . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
i
Index 93
ii
ModernGL Documentation, Release 5.6.1
Contents 1
ModernGL Documentation, Release 5.6.1
2 Contents
CHAPTER 1
Install
ModernGL is available on PyPI for Windows, OS X and Linux as pre-built wheels. No complication is needed unless
you are setting up a development environment.
$ python -m moderngl
moderngl 5.6.0
--------------
vendor: NVIDIA Corporation
renderer: GeForce RTX 2080 SUPER/PCIe/SSE2
version: 3.3.0 NVIDIA 441.87
python: 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit
˓→(AMD64)]
platform: win32
code: 330
Note: If you can only run in headless mode this might not work out of the box. You might need to set up xvfb and
possibly supply more arguments during context creation. More info can be found in later sections.
3
ModernGL Documentation, Release 5.6.1
4 Chapter 1. Install
CHAPTER 2
The Guide
1. Install ModernGL.
2. Create a Context.
3. Create a Program object.
4. Create a VertexArray object.
Proceed to the next step.
This tutorial will also use numpy to generate data and Pillow to save the final image.
5
ModernGL Documentation, Release 5.6.1
Note: From moderngl 5.6 context creation is handled by the glcontext package. This makes expanding context
support easier for users lowering the bar for contributions. It also means context creation is no longer limited by a
moderngl releases.
Note: This page might not list all supported backends as the glcontext project keeps evolving. If using anything
outside of the default contexts provided per OS, please check the listed backends in the glcontext project.
2.3.1 Introduction
A context is an object giving moderngl access to opengl instructions (greatly simplified). How a context is created
depends on your operating system and what kind of platform you want to target.
In the vast majority of cases you’ll be using the default context backend supported by your operating system. This
backend will be automatically selected unless a specific backend parameter is used.
Default backend per OS
• Windows: wgl / opengl32.dll
• Linux: x11/glx/libGL
• OS X: CGL
These default backends support two modes:
• Detecting an exiting active context possibly created by a window library such as glfw, sdl2, pyglet etc.
• Creating a headless context (No visible window)
Attaching to an existing active context created by a window library:
import moderngl
# .. do window initialization here
ctx = moderngl.create_context()
# If successful we can now render to the window
print("Default framebuffer is:", ctx.screen)
import moderngl
# Create the context
ctx = moderngl.create_context(standalone=True)
# Create a framebuffer we can render to
fbo = ctx.simple_framebuffer((100, 100), 4)
fbo.use()
ModernGL only support 3.3+ contexts. By default version 3.3 is passed in as the minimum required version of the
context returned by the backend.
To require a specific version:
moderngl.create_context(require=430)
This will require OpenGL 4.3. If a lower context version is returned the context creation will fail.
This attribute can be accessed in Context.version_code and will be updated to contain the actual version code
of the context (If higher than required).
Note: Each backend supports additional keyword arguments for more advanced configuration. This can for example
be the exact name of the library to load. More information in the glcontext docs.
Some context support the share parameters enabling object sharing between contexts. This is not needed if you are
attaching to existing context with share mode enabled. For example if you create two windows with glfw enabling
object sharing.
ModernGL objects (such as moderngl.Buffer, moderngl.Texture, ..) has a ctx property containing the
context they were created in. Still ModernGL do not check what context is currently active when accessing these
objects. This means the object can be used in both contexts when sharing is enabled.
This should in theory work fine with object sharing enabled:
data1 = numpy.array([1, 2, 3, 4], dtype='u1')
data2 = numpy.array([4, 3, 2, 1], dtype='u1')
ctx1 = moderngl.create_context(standalone=True)
ctx2 = moderngl.create_context(standalone=True, share=True)
print(b1.glo) # Displays: 1
(continues on next page)
with ctx1:
print(b1.read())
print(b2.read())
with ctx2:
print(b1.read())
print(b2.read())
Still, there are some limitations to object sharing. Especially objects that reference other objects (framebuffer, vertex
array object, etc.)
More information for a deeper dive:
• https://www.khronos.org/opengl/wiki/OpenGL_Object#Object_Sharing
• https://www.khronos.org/opengl/wiki/Memory_Model
2.4.1 Description
A buffer format is a short string describing the layout of data in a vertex buffer object (VBO).
A VBO often contains a homogeneous array of C-like structures. The buffer format describes what each element of
the array looks like. For example, a buffer containing an array of high-precision 2D vertex positions might have the
format "2f8" - each element of the array consists of two floats, each float being 8 bytes wide, ie. a double.
Buffer formats are used in the Context.vertex_array() constructor, as the 2nd component of the content arg.
See the Example of simple usage below.
2.4.2 Syntax
• /usage is optional. It should be preceded by a space, and then consists of a slash followed by a single character,
indicating how successive values in the buffer should be passed to the shader:
– /v per vertex. Successive values from the buffer are passed to each vertex. This is the default behavior if
usage is omitted.
– /i per instance. Successive values from the buffer are passed to each instance.
– /r per render. the first buffer value is passed to every vertex of every instance. ie. behaves like a uniform.
When passing multiple VBOs to a VAO, the first one must be of usage /v, as shown in the Example of multiple
arrays with differing /usage.
Valid combinations of type and size are:
size
type 1 2 4 8
f Unsigned byte (normalized) Half float Float Double
i Byte Short Int -
u Unsigned byte Unsigned short Unsigned int -
x 1 byte 2 bytes 4 bytes 8 bytes
2.4.3 Examples
"2f" has a count of 2 and a type of f (float). Hence it describes two floats, passed to a vertex shader’s vec2 attribute.
The size of the floats is unspecified, so defaults to 4 bytes. The usage of the buffer is unspecified, so defaults to /v
(vertex), meaning each successive pair of floats in the array are passed to successive vertices during the render call.
"3i2/i" means three i (integers). The size of each integer is 2 bytes, ie. they are shorts, passed to an ivec3
attribute. The trailing /i means that consecutive values in the buffer are passed to successive instances during an
instanced render call. So the same value is passed to every vertex within a particular instance.
Buffers contining interleaved values are represented by multiple space separated count-type-size triples. Hence:
"2f 3u x /v" means:
• 2f: two floats, passed to a vec2 attribute, followed by
• 3u: three unsigned bytes, passed to a uvec3, then
The line (vbo, "2f", "in_vert"), known as the VAO content, indicates that vbo contains an array of values,
each of which consists of two floats. These values are passed to an in_vert attribute, declared in the vertex shader
as:
in vec2 in_vert;
The "2f" format omits a size component, so the floats default to 4-bytes each. The format also omits the trailing
/usage component, which defaults to /v, so successive (x, y) rows from the buffer are passed to successive vertices
during the render call.
Such a buffer, however you choose to contruct it, would then be passed into a VAO using:
vao = ctx.vertex_array(
shader_program,
[
(vbo, "2f 3f1 x", "in_vert", "in_color")
]
index_buffer_object
)
The format starts with 2f, for the two position floats, which will be passed to the shader’s in_vert attribute, declared
as:
in vec2 in_vert;
Next, after a space, is 3f1, for the three color unsigned bytes, which get normalized to floats by f1. These floats will
be passed to the shader’s in_color attribute:
in vec3 in_color;
Finally, the format ends with x, a single byte of padding, which needs no shader attribute name.
To illustrate the trailing /usage portion, consider rendering a dozen cubes with instanced rendering. We will use:
• vbo_verts_normals contains vertices (3 floats) and normals (3 floats) for the vertices within a single cube.
• vbo_offset_orientation contains offsets (3 floats) and orientations (9 float matrices) that are used to
position and orient each cube.
• vbo_colors contains colors (3 floats). In this example, there is only one color in the buffer, that will be used
for every vertex of every cube.
Our shader will take all the above values as attributes.
We bind the above VBOs in a single VAO, to prepare for an instanced rendering call:
vao = ctx.vertex_array(
shader_program,
[
(vbo_verts_normals, "3f 3f /v", "in_vert", "in_norm"),
(vbo_offset_orientation, "3f 9f /i", "in_offset", "in_orientation"),
(vbo_colors, "3f /r", "in_color"),
]
index_buffer_object
)
So, the vertices and normals, using /v, are passed to each vertex within an instance. This fulfills the rule tha the first
VBO in a VAO must have usage /v. These are passed to vertex attributes as:
in vec3 in_vert;
in vec3 in_norm;
The offsets and orientations pass the same value to each vertex within an instance, but then pass the next value in the
buffer to the vertices of the next instance. Passed as:
in vec3 in_offset;
in mat3 in_orientation;
The single color is passed to every vertex of every instance. If we had stored the color with /v or /i, then we would
have had to store duplicate identical color values in vbo_colors - one per instance or one per vertex. To render all our
cubes in a single color, this is needless duplication. Using /r, only one color is require the buffer, and it is passed to
every vertex of every instance for the whole render call:
in vec3 in_color;
An alternative approach would be to pass in the color as a uniform, since it is constant. But doing it as an attribute is
more flexible. It allows us to reuse the same shader program, bound to a different buffer, to pass in color data which
varies per instance, or per vertex.
2.5 Program
ModernGL is different from standard plotting libraries. You can define your own shader program to render stuff. This
could complicate things, but also provides freedom on how you render your data.
Here is a sample program that passes the input vertex coordinates as is to screen coordinates.
Screen coordinates are in the [-1, 1], [-1, 1] range for x and y axes. The (-1, 1) point is the lower left corner of the
screen.
Entire source
1 import moderngl
2
3 ctx = moderngl.create_standalone_context()
4
5 prog = ctx.program(
6 vertex_shader='''
7 #version 330
8
9 in vec2 in_vert;
10 in vec3 in_color;
11
14 void main() {
15 v_color = in_color;
16 gl_Position = vec4(in_vert, 0.0, 1.0);
17 }
18 ''',
19 fragment_shader='''
20 #version 330
21
22 in vec3 v_color;
23
26 void main() {
27 f_color = v_color;
28 }
29 ''',
30 )
Vertex Shader
in vec2 in_vert;
in vec3 in_color;
void main() {
v_color = in_color;
gl_Position = vec4(in_vert, 0.0, 1.0);
}
Fragment Shader
in vec3 v_color;
void main() {
f_color = v_color;
}
2.5. Program 13
ModernGL Documentation, Release 5.6.1
2.6 VertexArray
1 import moderngl
2 import numpy as np
3
4 ctx = moderngl.create_standalone_context()
5
6 prog = ctx.program(
7 vertex_shader='''
8 #version 330
9
10 in vec2 in_vert;
11 in vec3 in_color;
12
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
27 void main() {
28 f_color = v_color;
29 }
30 ''',
31 )
32
41 vbo = ctx.buffer(vertices.astype('f4').tobytes())
42 vao = ctx.simple_vertex_array(prog, vbo, 'in_vert', 'in_color')
2.7 Rendering
1 import moderngl
2 import numpy as np
3
8 prog = ctx.program(
9 vertex_shader='''
10 #version 330
11
12 in vec2 in_vert;
13 in vec3 in_color;
14
17 void main() {
18 v_color = in_color;
19 gl_Position = vec4(in_vert, 0.0, 1.0);
20 }
21 ''',
22 fragment_shader='''
23 #version 330
24
25 in vec3 v_color;
26
29 void main() {
30 f_color = v_color;
31 }
32 ''',
33 )
34
43 vbo = ctx.buffer(vertices.astype('f4').tobytes())
44 vao = ctx.simple_vertex_array(prog, vbo, 'in_vert', 'in_color')
45
2.8.1 Dependencies
Headless rendering can be achieved with EGL or X11. We’ll cover both cases.
Starting with fresh ubuntu 18 server install we need to install required packages:
The libraries we are going to interact with has the following locations:
/usr/lib/x86_64-linux-gnu/libGL.so.1
/usr/lib/x86_64-linux-gnu/libX11.so.6
/usr/lib/x86_64-linux-gnu/libEGL.so.1
Double check what library versions you actually have installed and make modifications to what versions we refer to
below. moderngl will attempt to load libGL.so, libX11.so and libEGL.so by default. Optionally you can
create symlinks or use python to locate the desired lib files. For simplicity we will be using the exact library names.
Before we can create a context we to run a virtual display:
export DISPLAY=:99.0
Xvfb :99 -screen 0 640x480x24 &
# X11
import moderngl
ctx = moderngl.create_context(
standalone=True,
libgl='libGL.so.1',
libx11='libX11.so.6',
)
# EGL
import moderngl
ctx = moderngl.create_context(
standalone=True,
backend='egl',
libgl='libGL.so.1',
libegl='libEGL.so.1',
)
Checking that everything works can be done with a basic triangle example.
Install dependencies:
The following example renders a triangle and writes it to a png file so we can verify the contents.
import moderngl
import numpy as np
from PIL import Image
from pyrr import Matrix44
# -------------------
# CREATE CONTEXT HERE
# -------------------
prog = ctx.program(vertex_shader="""
#version 330
uniform mat4 model;
in vec2 in_vert;
in vec3 in_color;
(continues on next page)
vertices = np.array([
-0.6, -0.6,
1.0, 0.0, 0.0,
0.6, -0.6,
0.0, 1.0, 0.0,
0.0, 0.6,
0.0, 0.0, 1.0,
], dtype='f4')
vbo = ctx.buffer(vertices)
vao = ctx.simple_vertex_array(prog, vbo, 'in_vert', 'in_color')
fbo = ctx.framebuffer(color_attachments=[ctx.texture((512, 512), 4)])
fbo.use()
ctx.clear()
prog['model'].write(Matrix44.from_eulers((0.0, 0.1, 0.0), dtype='f4'))
vao.render(moderngl.TRIANGLES)
data = fbo.read(components=3)
image = Image.frombytes('RGB', fbo.size, data)
image = image.transpose(Image.FLIP_TOP_BOTTOM)
image.save('output.png')
Reference
3.1 Context
class moderngl.Context
Class exposing OpenGL features. ModernGL objects can be created from this class.
3.1.1 Create
moderngl.create_context(require=None) → Context
Create a ModernGL context by loading OpenGL functions from an existing OpenGL context. An OpenGL
context must exists.
Example:
Keyword Arguments
• require (int) – OpenGL version code (default: 330)
• standalone (bool) – Headless flag
• **settings – Other backend specific settings
Returns Context object
19
ModernGL Documentation, Release 5.6.1
moderngl.create_standalone_context(require=None) → Context
Create a standalone ModernGL context. The preferred way to make a context ‘‘
Example:
Warning: This method is deprecated and may be removed in the future. Use Context.
vertex_array() instead. It also supports the argument format this method describes.
Parameters
• program (Program) – The program used when rendering.
• buffer (Buffer) – The buffer.
• attributes (list) – A list of attribute names.
Keyword Arguments
• index_element_size (int) – byte size of each index element, 1, 2 or 4.
• index_buffer (Buffer) – An index buffer.
Returns VertexArray object
20 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
3.1. Context 21
ModernGL Documentation, Release 5.6.1
22 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
3.1. Context 23
ModernGL Documentation, Release 5.6.1
24 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
Example:
Context.release()
Release the ModernGL context.
If the context is not standalone the standard backends in glcontext will not do anything because the context
was not created by moderngl.
Standalone contexts can normally be released.
3.1.3 Methods
3.1. Context 25
ModernGL Documentation, Release 5.6.1
Examples:
Context.enable(flags)
Enable flags.
Note that the enum values defined in moderngl are not the same as the ones in opengl. These are defined as bit
flags so we can logical or them together.
For valid flags, please see enable_only().
Examples:
Context.disable(flags)
Disable flags.
For valid flags, please see enable_only().
Examples:
Context.finish()
Wait for all drawing commands to finish.
Context.copy_buffer(dst, src, size=-1, read_offset=0, write_offset=0)
Copy buffer content.
Parameters
• dst (Buffer) – The destination buffer.
• src (Buffer) – The source buffer.
• size (int) – The number of bytes to copy.
Keyword Arguments
• read_offset (int) – The read offset.
26 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
Parameters
• dst (Framebuffer or Texture) – Destination framebuffer or texture.
• src (Framebuffer) – Source framebuffer.
Context.detect_framebuffer(glo=None) → Framebuffer
Detect framebuffer.
Parameters glo (int) – Framebuffer object.
Returns Framebuffer object
Context.__enter__()
Enters the context.
This should ideally be used with the with statement:
When exiting the context the previously bound context is activated again.
Warning: Context switching can be risky unless you know what you are doing. ModernGL objects are not
aware of what context is currently active. Use with care.
3.1.4 Attributes
Context.line_width
Set the default line width.
Type float
Context.point_size
Set/get the default point size.
Type float
3.1. Context 27
ModernGL Documentation, Release 5.6.1
Context.depth_func
Set the default depth func. The depth function is set using a string.
Example:
ctx.depth_func = '<=' # GL_LEQUAL
ctx.depth_func = '<' # GL_LESS
ctx.depth_func = '>=' # GL_GEQUAL
ctx.depth_func = '>' # GL_GREATER
ctx.depth_func = '==' # GL_EQUAL
ctx.depth_func = '!=' # GL_NOTEQUAL
ctx.depth_func = '0' # GL_NEVER
ctx.depth_func = '1' # GL_ALWAYS
Type int
Context.blend_func
Set the blend func (write only) Blend func can be set for rgb and alpha separately if needed.
Supported blend functions are:
moderngl.ZERO
moderngl.ONE
moderngl.SRC_COLOR
moderngl.ONE_MINUS_SRC_COLOR
moderngl.DST_COLOR
moderngl.ONE_MINUS_DST_COLOR
moderngl.SRC_ALPHA
moderngl.ONE_MINUS_SRC_ALPHA
moderngl.DST_ALPHA
moderngl.ONE_MINUS_DST_ALPHA
Example:
# For both rgb and alpha
ctx.blend_func = moderngl.SRC_ALPHA, moderngl.ONE_MINUS_SRC_ALPHA
Type tuple
Context.blend_equation
Set the blend equation (write only).
Blend equations specify how source and destination colors are combined in blending operations. By default
FUNC_ADD is used.
Blend equation can be set for rgb and alpha separately if needed.
Supported functions are:
moderngl.FUNC_ADD # source + destination
moderngl.FUNC_SUBTRACT # source - destination
moderngl.FUNC_REVERSE_SUBTRACT # destination - source
(continues on next page)
28 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
Example:
Type tuple
Context.viewport
Get or set the viewport of the active framebuffer.
Example:
>>> ctx.viewport
(0, 0, 1280, 720)
>>> ctx.viewport = (0, 0, 640, 360)
>>> ctx.viewport
(0, 0, 640, 360)
3.1. Context 29
ModernGL Documentation, Release 5.6.1
Context.fbo
The active framebuffer. Set every time Framebuffer.use() is called.
Type Framebuffer
Context.front_face
The front_face. Acceptable values are 'ccw' (default) or 'cw'.
Face culling must be enabled for this to have any effect: ctx.enable(moderngl.CULL_FACE).
Example:
Type str
Context.cull_face
The face side to cull. Acceptable values are 'back' (default) 'front' or 'front_and_back'.
This is similar to Context.front_face()
Face culling must be enabled for this to have any effect: ctx.enable(moderngl.CULL_FACE).
Example:
#
ctx.cull_face = 'front'
#
ctx.cull_face = 'back'
#
ctx.cull_face = 'front_and_back'
Type str
Context.wireframe
Wireframe settings for debugging.
Type bool
Context.max_samples
The maximum supported number of samples for multisampling
Type int
Context.max_integer_samples
The max integer samples.
Type int
Context.max_texture_units
The max texture units.
Type int
Context.default_texture_unit
The default texture unit.
Type int
30 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
Context.max_anisotropy
The maximum value supported for anisotropic filtering.
Type float
Context.multisample
Enable/disable multisample mode (GL_MULTISAMPLE). This property is write only.
Example:
# Enable
ctx.multisample = True
# Disable
ctx.multisample = False
Type bool
Context.patch_vertices
The number of vertices that will be used to make up a single patch primitive.
Type int
Context.provoking_vertex
Specifies the vertex to be used as the source of data for flat shaded varyings.
Flatshading a vertex shader varying output (ie. flat out vec3 pos) means to assign all vetices of the
primitive the same value for that output. The vertex from which these values is derived is known as the provoking
vertex.
It can be configured to be the first or the last vertex.
This property is write only.
Example:
Type int
Context.error
The result of glGetError() but human readable. This values is provided for debug purposes only and is
likely to reduce performace when used in a draw loop.
Type str
Context.info
Information about the context
Example:
{
'GL_VENDOR': 'NVIDIA Corporation',
'GL_RENDERER': 'NVIDIA GeForce GT 650M OpenGL Engine',
'GL_VERSION': '4.1 NVIDIA-10.32.0 355.11.10.10.40.102',
'GL_POINT_SIZE_RANGE': (1.0, 2047.0),
'GL_SMOOTH_LINE_WIDTH_RANGE': (0.5, 1.0),
(continues on next page)
3.1. Context 31
ModernGL Documentation, Release 5.6.1
32 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
Type dict
Context.mglo
Internal representation for debug purposes only.
Context.extra
Any - Attribute for storing user defined objects
Context flags are used to enable or disable states in the context. These are not the same enum values as in opengl, but
are rather bit flags so we can or them together setting multiple states in a simple way.
These values are available in the Context object and in the moderngl module when you don’t have access to the
context.
import moderngl
# From moderngl
ctx.enable_only(moderngl.DEPTH_TEST | moderngl.CULL_FACE)
# From context
ctx.enable_only(ctx.DEPTH_TEST | ctx.CULL_FACE)
Context.NOTHING = 0
Represents no states. Can be used with Context.enable_only() to disable all states.
Context.BLEND = 1
Enable/disable blending
Context.DEPTH_TEST = 2
Enable/disable depth testing
Context.CULL_FACE = 4
Enable/disable face culling
Context.RASTERIZER_DISCARD = 8
Enable/disable rasterization
Context.PROGRAM_POINT_SIZE = 16
When enabled we can write to gl_PointSize in the vertex shader to specify the point size. When disabled
Context.point_size is used.
3.1. Context 33
ModernGL Documentation, Release 5.6.1
# Default value
ctx.blend_func = ctx.SRC_ALPHA, ctx.ONE_MINUS_SRC_ALPHA
Context.ZERO = 0
Context.ONE = 1
Context.SRC_COLOR = 768
Context.ONE_MINUS_SRC_COLOR = 769
Context.SRC_ALPHA = 770
Context.ONE_MINUS_SRC_ALPHA = 771
Context.DST_ALPHA = 772
Context.ONE_MINUS_DST_ALPHA = 773
Context.DST_COLOR = 774
Context.ONE_MINUS_DST_COLOR = 775
34 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
Context.FIRST_VERTEX_CONVENTION = 36429
Specifies the first vertex should be used as the source of data for flat shaded varyings. Used with Context.
provoking_vertex.
Context.LAST_VERTEX_CONVENTION = 36430
Specifies the last vertex should be used as the source of data for flat shaded varyings. Used with Context.
provoking_vertex.
3.1.10 Examples
ModernGL Context
import moderngl
# create a window
ctx = moderngl.create_context()
print(ctx.version_code)
import moderngl
ctx = moderngl.create_standalone_context()
print(ctx.version_code)
ContextManager
context_manager.py
1 import moderngl
2
4 class ContextManager:
5 ctx = None
6
7 @staticmethod
8 def get_default_context(allow_fallback_standalone_context=True) -> moderngl.
˓→Context:
9 '''
10 Default context
11 '''
12
13 if ContextManager.ctx is None:
14 try:
15 ContextManager.ctx = moderngl.create_context()
16 except:
17 if allow_fallback_standalone_context:
18 ContextManager.ctx = moderngl.create_standalone_context()
19 else:
20 raise
21
22 return ContextManager.ctx
3.1. Context 35
ModernGL Documentation, Release 5.6.1
example.py
3 ctx = ContextManager.get_default_context()
4 print(ctx.version_code)
3.2 Buffer
class moderngl.Buffer
Buffer objects are OpenGL objects that store an array of unformatted memory allocated by the OpenGL context,
(data allocated on the GPU). These can be used to store vertex data, pixel data retrieved from images or the
framebuffer, and a variety of other things.
A Buffer object cannot be instantiated directly, it requires a context. Use Context.buffer() to create one.
Copy buffer content using Context.copy_buffer().
3.2.1 Create
3.2.2 Methods
Buffer.assign(index)
Helper method for assigning a buffer.
Returns (self, index) tuple
Buffer.bind(*attribs, layout=None)
Helper method for binding a buffer.
Returns (self, layout, *attribs) tuple
Buffer.write(data, offset=0)
Write the content.
Parameters data (bytes) – The data.
Keyword Arguments offset (int) – The offset.
Buffer.write_chunks(data, start, step, count)
Split data to count equal parts.
Write the chunks using offsets calculated from start, step and stop.
Parameters
36 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
3.2. Buffer 37
ModernGL Documentation, Release 5.6.1
Example
>>> vbo.write(some_temporary_data)
>>> vao.render(...)
38 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
# Issue another render call without waiting for the previous one
>>> vbo.write(some_temporary_data)
>>> vao.render(...)
# We can also resize the buffer. In this case we double the size
>> vbo.orphan(vbo.size * 2)
Buffer.release()
Release the ModernGL object.
3.2.3 Attributes
Buffer.size
The size of the buffer.
Type int
Buffer.dynamic
Is the buffer created with the dynamic flag?
Type bool
Buffer.glo
The internal OpenGL object. This values is provided for debug purposes only.
Type int
Buffer.mglo
Internal representation for debug purposes only.
Buffer.extra
Any - Attribute for storing user defined objects
Buffer.ctx
The context this object belongs to
3.3 VertexArray
class moderngl.VertexArray
A VertexArray object is an OpenGL object that stores all of the state needed to supply vertex data. It stores the
format of the vertex data as well as the Buffer objects providing the vertex data arrays.
In ModernGL, the VertexArray object also stores a reference for a Program object, and some Subroutine
information.
A VertexArray object cannot be instantiated directly, it requires a context. Use Context.vertex_array()
or Context.simple_vertex_array() to create one.
3.3. VertexArray 39
ModernGL Documentation, Release 5.6.1
3.3.1 Create
Warning: This method is deprecated and may be removed in the future. Use Context.
vertex_array() instead. It also supports the argument format this method describes.
Parameters
• program (Program) – The program used when rendering.
• buffer (Buffer) – The buffer.
• attributes (list) – A list of attribute names.
Keyword Arguments
• index_element_size (int) – byte size of each index element, 1, 2 or 4.
• index_buffer (Buffer) – An index buffer.
Returns VertexArray object
Context.vertex_array(*args, **kwargs) → VertexArray
Create a VertexArray object.
This method also supports arguments for Context.simple_vertex_array().
Parameters
• program (Program) – The program used when rendering.
• content (list) – A list of (buffer, format, attributes). See Buffer Format.
• index_buffer (Buffer) – An index buffer.
Keyword Arguments
• index_element_size (int) – byte size of each index element, 1, 2 or 4.
• skip_errors (bool) – Ignore skip_errors varyings.
Returns VertexArray object
3.3.2 Methods
40 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
3.3. VertexArray 41
ModernGL Documentation, Release 5.6.1
3.3.3 Attributes
VertexArray.program
The program assigned to the VertexArray. The program used when rendering or transforming primitives.
Type Program
VertexArray.index_buffer
The index buffer if the index_buffer is set, otherwise None.
Type Buffer
VertexArray.index_element_size
The byte size of each element in the index buffer
Type int
VertexArray.scope
The moderngl.Scope.
VertexArray.vertices
The number of vertices detected. This is the minimum of the number of vertices possible per Buffer. The size of
the index_buffer determines the number of vertices. Per instance vertex attributes does not affect this number.
Type int
VertexArray.instances
Get or set the number of instances to render
Type int
VertexArray.subroutines
The subroutines assigned to the VertexArray. The subroutines used when rendering or transforming primitives.
Type tuple
VertexArray.glo
The internal OpenGL object. This values is provided for debug purposes only.
Type int
VertexArray.mglo
Internal representation for debug purposes only.
VertexArray.extra
Any - Attribute for storing user defined objects
VertexArray.ctx
The context this object belongs to
3.4 Program
class moderngl.Program
A Program object represents fully processed executable code in the OpenGL Shading Language, for one or more
Shader stages.
In ModernGL, a Program object can be assigned to VertexArray objects. The VertexArray object is capable
of binding the Program object once the VertexArray.render() or VertexArray.transform() is
called.
Program objects has no method called use(), VertexArrays encapsulate this mechanism.
42 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
A Program object cannot be instantiated directly, it requires a context. Use Context.program() to create
one.
Uniform buffers can be bound using Buffer.bind_to_uniform_block() or can be set individually. For
more complex binding yielding higher performance consider using moderngl.Scope.
3.4.1 Create
3.4.2 Methods
# Get a uniform
uniform = program['color']
# Still when writing byte data we need to use the `write()` method
program['color'].write(buffer)
Program.__setitem__(key, value)
Set a value of uniform or uniform block
# Optionally we can store references to a member and set the value directly
uniform = program['color']
uniform.value = 1.0, 0.0, 0.0, 0.0
3.4. Program 43
ModernGL Documentation, Release 5.6.1
Output:
Output:
Program.__eq__(other) → bool
Compares two programs opengl names (mglo).
Returns If the programs have the same opengl name
Return type bool
Example:
Program.release()
Release the ModernGL object.
44 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
3.4.3 Attributes
Program.geometry_input
The geometry input primitive. The GeometryShader’s input primitive if the GeometryShader exists. The geom-
etry input primitive will be used for validation.
Type int
Program.geometry_output
The geometry output primitive. The GeometryShader’s output primitive if the GeometryShader exists.
Type int
Program.geometry_vertices
The maximum number of vertices that the geometry shader will output.
Type int
Program.subroutines
The subroutine uniforms.
Type tuple
Program.glo
The internal OpenGL object. This values is provided for debug purposes only.
Type int
Program.mglo
Internal representation for debug purposes only.
Program.extra
Any - Attribute for storing user defined objects
Program.ctx
The context this object belongs to
3.4.4 Examples
1 my_render_program = ctx.program(
2 vertex_shader='''
3 #version 330
4
5 in vec2 vert;
6
7 void main() {
8 gl_Position = vec4(vert, 0.0, 1.0);
9 }
10 ''',
11 fragment_shader='''
12 #version 330
13
16 void main() {
17 color = vec4(0.3, 0.5, 1.0, 1.0);
18 }
(continues on next page)
3.4. Program 45
ModernGL Documentation, Release 5.6.1
1 my_transform_program = ctx.program(
2 vertex_shader='''
3 #version 330
4
5 in vec4 vert;
6 out float vert_length;
7
8 void main() {
9 vert_length = length(vert);
10 }
11 ''',
12 varyings=['vert_length']
13 )
Uniform
class moderngl.Uniform
A uniform is a global GLSL variable declared with the “uniform” storage qualifier. These act as parameters that
the user of a shader program can pass to that program.
In ModernGL, Uniforms can be accessed using Program.__getitem__() or Program.__iter__()
Methods
Uniform.read() → bytes
Read the value of the uniform.
Uniform.write(data)
Write the value of the uniform.
Attributes
Uniform.location
The location of the uniform. The location holds the value returned by the glGetUniformLocation. To set the
value of the uniform use the value instead.
Type int
Uniform.dimension
The dimension of the uniform.
46 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
Type int
Uniform.array_length
The length of the array of the uniform. The array_length is 1 for non array uniforms.
Type int
Uniform.name
The name of the uniform. The name does not contain leading [0]. The name may contain [ ] when the uniform
is part of a struct.
3.4. Program 47
ModernGL Documentation, Release 5.6.1
Type str
Uniform.value
The value of the uniform. Reading the value of the uniform may force the GPU to sync.
The value must be a tuple for non array uniforms. The value must be a list of tuples for array uniforms.
Uniform.extra
Any - Attribute for storing user defined objects
Uniform.mglo
Internal representation for debug purposes only.
UniformBlock
class moderngl.UniformBlock
UniformBlock.binding
The binding of the uniform block.
Type int
UniformBlock.value
The value of the uniform block.
Type int
UniformBlock.name
The name of the uniform block.
Type str
UniformBlock.index
The index of the uniform block.
Type int
UniformBlock.size
The size of the uniform block.
Type int
UniformBlock.extra
Any - Attribute for storing user defined objects
UniformBlock.mglo
Internal representation for debug purposes only.
Subroutine
class moderngl.Subroutine
This class represents a program subroutine.
Subroutine.index
The index of the subroutine.
Type int
Subroutine.name
The name of the subroutine.
Type str
48 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
Subroutine.extra
Any - Attribute for storing user defined objects
Attribute
class moderngl.Attribute
This class represents a program attribute.
Attribute.location
The location of the attribute. The result of the glGetAttribLocation.
Type int
Attribute.array_length
If the attribute is an array the array_length is the length of the array otherwise 1.
Type int
Attribute.dimension
The attribute dimension.
3.4. Program 49
ModernGL Documentation, Release 5.6.1
Type int
Attribute.shape
The shape is a single character, representing the scalar type of the attribute.
Type str
Attribute.name
The attribute name. The name will be filtered to have no array syntax on it’s end. Attribute name without '[0]'
ending if any.
Type str
Attribute.extra
Any - Attribute for storing user defined objects
Varying
class moderngl.Varying
This class represents a program varying.
Varying.name
The name of the varying.
Type str
Varying.number
The number of the varying.
Type int
Varying.extra
Any - Attribute for storing user defined objects
50 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
3.5 Sampler
class moderngl.Sampler
A Sampler Object is an OpenGL Object that stores the sampling parameters for a Texture access inside of a
shader. When a sampler object is bound to a texture image unit, the internal sampling parameters for a texture
bound to the same image unit are all ignored. Instead, the sampling parameters are taken from this sampler
object.
Unlike textures, a samplers state can also be changed freely be at any time without the sampler object being
bound/in use.
Samplers are bound to a texture unit and not a texture itself. Be careful with leaving samplers bound to texture
units as it can cause texture incompleteness issues (the texture bind is ignored).
Sampler bindings do clear automatically between every frame so a texture unit need at least one bind/use per
frame.
3.5.1 Create
3.5.2 Methods
Sampler.use(location=0)
Bind the sampler to a texture unit
Parameters location (int) – The texture unit
Sampler.clear(location=0)
Clear the sampler binding on a texture unit
3.5. Sampler 51
ModernGL Documentation, Release 5.6.1
s1 = ctx.sampler(...)
s2 = ctx.sampler(...)
ctx.scope(samplers=(s1.assign(0), s1.assign(1)), ...)
Sampler.release()
Release/destroy the ModernGL object.
3.5.3 Attributes
Sampler.texture
Sampler.repeat_x
The x repeat flag for the sampler (Default True)
Example:
Type bool
Sampler.repeat_y
The y repeat flag for the sampler (Default True)
Example:
Type bool
Sampler.repeat_z
The z repeat flag for the sampler (Default True)
Example:
52 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
Type bool
Sampler.filter
The minification and magnification filter for the sampler. (Default (moderngl.LINEAR. moderngl.
LINEAR))
Example:
sampler.filter == (moderngl.NEAREST, moderngl.NEAREST)
sampler.filter == (moderngl.LINEAR_MIPMAP_LINEAR, moderngl.LINEAR)
sampler.filter == (moderngl.NEAREST_MIPMAP_LINEAR, moderngl.NEAREST)
sampler.filter == (moderngl.LINEAR_MIPMAP_NEAREST, moderngl.NEAREST)
Type tuple
Sampler.compare_func
The compare function for a depth textures (Default '?')
By default samplers don’t have depth comparison mode enabled. This means that depth texture values can be
read as a sampler2D using texture() in a GLSL shader by default.
When setting this property to a valid compare mode, GL_TEXTURE_COMPARE_MODE is set to
GL_COMPARE_REF_TO_TEXTURE so that texture lookup functions in GLSL will return a depth compari-
son result instead of the actual depth value.
Accepted compare functions:
.compare_func = '' # Disale depth comparison completely
sampler.compare_func = '<=' # GL_LEQUAL
sampler.compare_func = '<' # GL_LESS
sampler.compare_func = '>=' # GL_GEQUAL
sampler.compare_func = '>' # GL_GREATER
sampler.compare_func = '==' # GL_EQUAL
sampler.compare_func = '!=' # GL_NOTEQUAL
sampler.compare_func = '0' # GL_NEVER
sampler.compare_func = '1' # GL_ALWAYS
Type tuple
Sampler.anisotropy
Number of samples for anisotropic filtering (Default 1.0). The value will be clamped in range 1.0 and ctx.
max_anisotropy.
Any value greater than 1.0 counts as a use of anisotropic filtering:
# Disable anisotropic filtering
sampler.anisotropy = 1.0
Type float
Sampler.border_color
When setting this value the repeat_ values are overridden setting the texture wrap to return the border color
when outside [0, 1] range.
Example:
3.5. Sampler 53
ModernGL Documentation, Release 5.6.1
Sampler.min_lod
Minimum level-of-detail parameter (Default -1000.0). This floating-point value limits the selection of highest
resolution mipmap (lowest mipmap level)
Type float
Sampler.max_lod
Minimum level-of-detail parameter (Default 1000.0). This floating-point value limits the selection of the
lowest resolution mipmap (highest mipmap level)
Type float
Sampler.extra
Any - Attribute for storing user defined objects
Sampler.mglo
Internal representation for debug purposes only.
Sampler.ctx
The context this object belongs to
3.6 Texture
class moderngl.Texture
A Texture is an OpenGL object that contains one or more images that all have the same image format. A texture
can be used in two ways. It can be the source of a texture access from a Shader, or it can be used as a render
target.
A Texture object cannot be instantiated directly, it requires a context. Use Context.texture() or
Context.depth_texture() to create one.
3.6.1 Create
54 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
Parameters
• size (tuple) – The width and height of the texture.
• data (bytes) – Content of the texture.
Keyword Arguments
• samples (int) – The number of samples. Value 0 means no multisample format.
• alignment (int) – The byte alignment 1, 2, 4 or 8.
Returns Texture object
3.6.2 Methods
3.6. Texture 55
ModernGL Documentation, Release 5.6.1
Texture.bind_to_image(unit: int, read: bool = True, write: bool = True, level: int = 0, format: int =
0)
Bind a texture to an image unit (OpenGL 4.2 required)
This is used to bind textures to image units for shaders. The idea with image load/store is that the user can bind
one of the images in a Texture to a number of image binding points (which are separate from texture image
units). Shaders can read information from these images and write information to them, in ways that they cannot
with textures.
It’s important to specify the right access type for the image. This can be set with the read and write argu-
ments. Allowed combinations are:
• Read-only: read=True and write=False
• Write-only: read=False and write=True
• Read-write: read=True and write=True
format specifies the format that is to be used when performing formatted stores into the image from shaders.
format must be compatible with the texture’s internal format. By default the format of the texture is passed
in. The format parameter is only needed when overriding this behavior.
More information:
• https://www.khronos.org/opengl/wiki/Image_Load_Store
• https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glBindImageTexture.xhtml
Parameters
• unit (int) – Specifies the index of the image unit to which to bind the texture
• texture (moderngl.Texture) – The texture to bind
Keyword Arguments
• read (bool) – Allows the shader to read the image (default: True)
• write (bool) – Allows the shader to write to the image (default: True)
• level (int) – Level of the texture to bind (default: 0).
• format (int) – (optional) The OpenGL enum value representing the format (defaults to
the texture’s format)
Texture.use(location=0)
Bind the texture to a texture unit.
The location is the texture unit we want to bind the texture. This should correspond with the value of the
sampler2D uniform in the shader because samplers read from the texture unit we assign to them:
# Define what texture unit our two sampler2D uniforms should represent
program['texture_a'] = 0
program['texture_b'] = 1
# Bind textures to the texture units
first_texture.use(location=0)
second_texture.use(location=1)
Texture.release()
Release the ModernGL object.
56 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
3.6.3 Attributes
Texture.repeat_x
The x repeat flag for the texture (Default True)
Example:
Type bool
Texture.repeat_y
The y repeat flag for the texture (Default True)
Example:
Type bool
Texture.filter
The minification and magnification filter for the texture. (Default (moderngl.LINEAR. moderngl.
LINEAR))
Example:
Type tuple
Texture.swizzle
The swizzle mask of the texture (Default 'RGBA').
The swizzle mask change/reorder the vec4 value returned by the texture() function in a GLSL shaders.
This is represented by a 4 character string were each character can be:
'R' GL_RED
'G' GL_GREEN
'B' GL_BLUE
'A' GL_ALPHA
'0' GL_ZERO
'1' GL_ONE
Example:
3.6. Texture 57
ModernGL Documentation, Release 5.6.1
Type str
Texture.compare_func
The compare function of the depth texture (Default '<=')
By default depth textures have GL_TEXTURE_COMPARE_MODE set to GL_COMPARE_REF_TO_TEXTURE,
meaning any texture lookup will return a depth comparison value.
If you need to read the actual depth value in shaders, setting compare_func to a blank string will set
GL_TEXTURE_COMPARE_MODE to GL_NONE making you able to read the depth texture as a sampler2D:
void main() {
float raw_depth_nonlinear = texture(depth, uv);
fragColor = vec4(raw_depth_nonlinear);
}
Type tuple
Texture.anisotropy
Number of samples for anisotropic filtering (Default 1.0). The value will be clamped in range 1.0 and ctx.
max_anisotropy.
Any value greater than 1.0 counts as a use of anisotropic filtering:
Type float
58 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
Texture.width
The width of the texture.
Type int
Texture.height
The height of the texture.
Type int
Texture.size
The size of the texture.
Type tuple
Texture.dtype
Data type.
Type str
Texture.components
The number of components of the texture.
Type int
Texture.samples
The number of samples set for the texture used in multisampling.
Type int
Texture.depth
Is the texture a depth texture?
Type bool
Texture.glo
The internal OpenGL object. This values is provided for debug purposes only.
Type int
Texture.mglo
Internal representation for debug purposes only.
Texture.extra
Any - Attribute for storing user defined objects
Texture.ctx
The context this object belongs to
3.7 TextureArray
class moderngl.TextureArray
An Array Texture is a Texture where each mipmap level contains an array of images of the same size. Array
textures may have Mipmaps, but each mipmap in the texture has the same number of levels.
A TextureArray object cannot be instantiated directly, it requires a context. Use Context.
texture_array() to create one.
3.7. TextureArray 59
ModernGL Documentation, Release 5.6.1
3.7.1 Create
3.7.2 Methods
TextureArray.read(alignment=1) → bytes
Read the content of the texture array into a buffer.
Keyword Arguments alignment (int) – The byte alignment of the pixels.
Returns bytes
TextureArray.read_into(buffer, alignment=1, write_offset=0)
Read the content of the texture array into a buffer.
Parameters buffer (bytearray) – The buffer that will receive the pixels.
Keyword Arguments
• alignment (int) – The byte alignment of the pixels.
• write_offset (int) – The write offset.
TextureArray.write(data, viewport=None, alignment=1)
Update the content of the texture array.
Parameters
• data (bytes) – The pixel data.
• viewport (tuple) – The viewport.
Keyword Arguments alignment (int) – The byte alignment of the pixels.
TextureArray.build_mipmaps(base=0, max_level=1000)
Generate mipmaps.
This also changes the texture filter to LINEAR_MIPMAP_LINEAR, LINEAR (Will be removed in 6.x)
Keyword Arguments
• base (int) – The base level
• max_level (int) – The maximum levels to generate
60 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
TextureArray.use(location=0)
Bind the texture to a texture unit.
The location is the texture unit we want to bind the texture. This should correspond with the value of the
sampler2DArray uniform in the shader because samplers read from the texture unit we assign to them:
# Define what texture unit our two sampler2DArray uniforms should represent
program['texture_a'] = 0
program['texture_b'] = 1
# Bind textures to the texture units
first_texture.use(location=0)
second_texture.use(location=1)
TextureArray.release()
Release the ModernGL object.
3.7.3 Attributes
TextureArray.repeat_x
The x repeat flag for the texture (Default True)
Example:
# Enable texture repeat (GL_REPEAT)
texture.repeat_x = True
Type bool
TextureArray.repeat_y
The y repeat flag for the texture (Default True)
Example:
# Enable texture repeat (GL_REPEAT)
texture.repeat_y = True
Type bool
TextureArray.filter
The minification and magnification filter for the texture. (Default (moderngl.LINEAR. moderngl.
LINEAR))
Example:
texture.filter == (moderngl.NEAREST, moderngl.NEAREST)
texture.filter == (moderngl.LINEAR_MIPMAP_LINEAR, moderngl.LINEAR)
texture.filter == (moderngl.NEAREST_MIPMAP_LINEAR, moderngl.NEAREST)
texture.filter == (moderngl.LINEAR_MIPMAP_NEAREST, moderngl.NEAREST)
3.7. TextureArray 61
ModernGL Documentation, Release 5.6.1
Type tuple
TextureArray.swizzle
The swizzle mask of the texture (Default 'RGBA').
The swizzle mask change/reorder the vec4 value returned by the texture() function in a GLSL shaders.
This is represented by a 4 character string were each character can be:
'R' GL_RED
'G' GL_GREEN
'B' GL_BLUE
'A' GL_ALPHA
'0' GL_ZERO
'1' GL_ONE
Example:
Type str
TextureArray.anisotropy
Number of samples for anisotropic filtering (Default 1.0). The value will be clamped in range 1.0 and ctx.
max_anisotropy.
Any value greater than 1.0 counts as a use of anisotropic filtering:
Type float
TextureArray.width
The width of the texture array.
Type int
TextureArray.height
The height of the texture array.
Type int
TextureArray.layers
The number of layers of the texture array.
Type int
TextureArray.size
The size of the texture array.
62 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
Type tuple
TextureArray.dtype
Data type.
Type str
TextureArray.components
The number of components of the texture array.
Type int
TextureArray.glo
The internal OpenGL object. This values is provided for debug purposes only.
Type int
TextureArray.mglo
Internal representation for debug purposes only.
TextureArray.extra
Any - Attribute for storing user defined objects
TextureArray.ctx
The context this object belongs to
3.8 Texture3D
class moderngl.Texture3D
A Texture is an OpenGL object that contains one or more images that all have the same image format. A texture
can be used in two ways. It can be the source of a texture access from a Shader, or it can be used as a render
target.
A Texture3D object cannot be instantiated directly, it requires a context. Use Context.texture3d() to
create one.
3.8.1 Create
3.8. Texture3D 63
ModernGL Documentation, Release 5.6.1
3.8.2 Methods
Texture3D.read(alignment=1) → bytes
Read the content of the texture into a buffer.
Keyword Arguments alignment (int) – The byte alignment of the pixels.
Returns bytes
Texture3D.read_into(buffer, alignment=1, write_offset=0)
Read the content of the texture into a buffer.
Parameters buffer (bytearray) – The buffer that will receive the pixels.
Keyword Arguments
• alignment (int) – The byte alignment of the pixels.
• write_offset (int) – The write offset.
Texture3D.write(data, viewport=None, alignment=1)
Update the content of the texture.
Parameters
• data (bytes) – The pixel data.
• viewport (tuple) – The viewport.
Keyword Arguments alignment (int) – The byte alignment of the pixels.
Texture3D.build_mipmaps(base=0, max_level=1000)
Generate mipmaps.
This also changes the texture filter to LINEAR_MIPMAP_LINEAR, LINEAR (Will be removed in 6.x)
Keyword Arguments
• base (int) – The base level
• max_level (int) – The maximum levels to generate
Texture3D.use(location=0)
Bind the texture to a texture unit.
The location is the texture unit we want to bind the texture. This should correspond with the value of the
sampler3D uniform in the shader because samplers read from the texture unit we assign to them:
# Define what texture unit our two sampler3D uniforms should represent
program['texture_a'] = 0
program['texture_b'] = 1
# Bind textures to the texture units
first_texture.use(location=0)
second_texture.use(location=1)
Texture3D.release()
Release the ModernGL object.
64 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
3.8.3 Attributes
Texture3D.repeat_x
The x repeat flag for the texture (Default True)
Example:
# Enable texture repeat (GL_REPEAT)
texture.repeat_x = True
Type bool
Texture3D.repeat_y
The y repeat flag for the texture (Default True)
Example:
# Enable texture repeat (GL_REPEAT)
texture.repeat_y = True
Type bool
Texture3D.repeat_z
The z repeat flag for the texture (Default True)
Example:
# Enable texture repeat (GL_REPEAT)
texture.repeat_z = True
Type bool
Texture3D.filter
The filter of the texture.
Type tuple
Texture3D.swizzle
The swizzle mask of the texture (Default 'RGBA').
The swizzle mask change/reorder the vec4 value returned by the texture() function in a GLSL shaders.
This is represented by a 4 character string were each character can be:
'R' GL_RED
'G' GL_GREEN
'B' GL_BLUE
'A' GL_ALPHA
'0' GL_ZERO
'1' GL_ONE
3.8. Texture3D 65
ModernGL Documentation, Release 5.6.1
Example:
Type str
Texture3D.width
The width of the texture.
Type int
Texture3D.height
The height of the texture.
Type int
Texture3D.depth
The depth of the texture.
Type int
Texture3D.size
The size of the texture.
Type tuple
Texture3D.dtype
Data type.
Type str
Texture3D.components
The number of components of the texture.
Type int
Texture3D.glo
The internal OpenGL object. This values is provided for debug purposes only.
Type int
Texture3D.mglo
Internal representation for debug purposes only.
Texture3D.extra
Any - Attribute for storing user defined objects
Texture3D.ctx
The context this object belongs to
3.9 TextureCube
class moderngl.TextureCube
A Texture is an OpenGL object that contains one or more images that all have the same image format. A texture
66 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
can be used in two ways. It can be the source of a texture access from a Shader, or it can be used as a render
target.
3.9.1 Create
3.9.2 Methods
3.9. TextureCube 67
ModernGL Documentation, Release 5.6.1
# Define what texture unit our two samplerCube uniforms should represent
program['texture_a'] = 0
program['texture_b'] = 1
# Bind textures to the texture units
first_texture.use(location=0)
second_texture.use(location=1)
TextureCube.release()
Release the ModernGL object.
3.9.3 Attributes
TextureCube.size
The size of the texture.
Type tuple
TextureCube.dtype
Data type.
Type str
TextureCube.components
The number of components of the texture.
Type int
TextureCube.filter
The minification and magnification filter for the texture. (Default (moderngl.LINEAR. moderngl.
LINEAR))
Example:
Type tuple
TextureCube.swizzle
The swizzle mask of the texture (Default 'RGBA').
The swizzle mask change/reorder the vec4 value returned by the texture() function in a GLSL shaders.
This is represented by a 4 character string were each character can be:
68 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
'R' GL_RED
'G' GL_GREEN
'B' GL_BLUE
'A' GL_ALPHA
'0' GL_ZERO
'1' GL_ONE
Example:
Type str
TextureCube.anisotropy
Number of samples for anisotropic filtering (Default 1.0). The value will be clamped in range 1.0 and ctx.
max_anisotropy.
Any value greater than 1.0 counts as a use of anisotropic filtering:
Type float
TextureCube.glo
The internal OpenGL object. This values is provided for debug purposes only.
Type int
TextureCube.mglo
Internal representation for debug purposes only.
TextureCube.extra
Any - Attribute for storing user defined objects
TextureCube.ctx
The context this object belongs to
3.10 Framebuffer
class moderngl.Framebuffer
A Framebuffer is a collection of buffers that can be used as the destination for rendering. The buffers for
Framebuffer objects reference images from either Textures or Renderbuffers.
Create a Framebuffer using Context.framebuffer().
3.10. Framebuffer 69
ModernGL Documentation, Release 5.6.1
3.10.1 Create
3.10.2 Methods
70 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
3.10.3 Attributes
Framebuffer.viewport
Get or set the viewport of the framebuffer.
Type tuple
Framebuffer.scissor
Get or set the scissor box of the framebuffer.
When scissor testing is enabled fragments outside the defined scissor box will be discarded. This applies to
rendered geometry or Framebuffer.clear().
Setting is value enables scissor testing in the framebuffer. Setting the scissor to None disables scissor testing
and reverts the scissor box to match the framebuffer size.
Example:
3.10. Framebuffer 71
ModernGL Documentation, Release 5.6.1
Type tuple
Framebuffer.color_mask
The color mask of the framebuffer.
Color masking controls what components in color attachments will be affected by fragment write operations.
This includes rendering geometry and clearing the framebuffer.
Default value: (True, True, True, True).
Examples:
Type tuple
Framebuffer.depth_mask
The depth mask of the framebuffer.
Depth mask enables or disables write operations to the depth buffer. This also applies when clearing the frame-
buffer. If depth testing is enabled fragments will still be culled, but the depth buffer will not be updated with
new values. This is a very useful tool in many rendering techniques.
Default value: True
Type bool
Framebuffer.width
The width of the framebuffer.
Framebuffers created by a window will only report its initial size. It’s better get size information from the
window itself.
Type int
Framebuffer.height
The height of the framebuffer.
Framebuffers created by a window will only report its initial size. It’s better get size information from the
window itself.
Type int
Framebuffer.size
The size of the framebuffer.
Framebuffers created by a window will only report its initial size. It’s better get size information from the
window itself.
72 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
Type tuple
Framebuffer.samples
The samples of the framebuffer.
Type int
Framebuffer.bits
The bits of the framebuffer.
Type dict
Framebuffer.color_attachments
The color attachments of the framebuffer.
Type tuple
Framebuffer.depth_attachment
The depth attachment of the framebuffer.
Type Texture or Renderbuffer
Framebuffer.glo
The internal OpenGL object. This values is provided for debug purposes only.
Type int
Framebuffer.mglo
Internal representation for debug purposes only.
Framebuffer.extra
Any - Attribute for storing user defined objects
Framebuffer.ctx
The context this object belongs to
3.11 Renderbuffer
class moderngl.Renderbuffer
Renderbuffer objects are OpenGL objects that contain images. They are created and used specifically with
Framebuffer objects. They are optimized for use as render targets, while Texture objects may not be, and
are the logical choice when you do not need to sample from the produced image. If you need to resample, use
Textures instead. Renderbuffer objects also natively accommodate multisampling.
A Renderbuffer object cannot be instantiated directly, it requires a context. Use Context.renderbuffer()
or Context.depth_renderbuffer() to create one.
3.11.1 Create
3.11. Renderbuffer 73
ModernGL Documentation, Release 5.6.1
3.11.2 Methods
Renderbuffer.release()
Release the ModernGL object.
3.11.3 Attributes
Renderbuffer.width
The width of the renderbuffer.
Type int
Renderbuffer.height
The height of the renderbuffer.
Type int
Renderbuffer.size
The size of the renderbuffer.
Type tuple
Renderbuffer.samples
The samples of the renderbuffer.
Type int
Renderbuffer.components
The components of the renderbuffer.
Type int
Renderbuffer.depth
Is the renderbuffer a depth renderbuffer?
Type bool
Renderbuffer.dtype
Data type.
Type str
Renderbuffer.glo
The internal OpenGL object. This values is provided for debug purposes only.
Type int
74 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
Renderbuffer.mglo
Internal representation for debug purposes only.
Renderbuffer.extra
Any - Attribute for storing user defined objects
Renderbuffer.ctx
The context this object belongs to
3.12 Scope
class moderngl.Scope
This class represents a Scope object.
Responsibilities on enter:
• Set the enable flags.
• Bind the framebuffer.
• Assigning textures to texture locations.
• Assigning buffers to uniform buffers.
• Assigning buffers to shader storage buffers.
Responsibilities on exit:
• Restore the enable flags.
• Restore the framebuffer.
3.12.1 Create
3.12.2 Attributes
Scope.extra
Any - Attribute for storing user defined objects
3.12. Scope 75
ModernGL Documentation, Release 5.6.1
Scope.mglo
Internal representation for debug purposes only.
Scope.ctx
The context this object belongs to
3.12.3 Examples
with scope1:
# do some rendering
with scope2:
# do some rendering
query = ctx.query(samples=True)
scope = ctx.scope(ctx.screen, moderngl.DEPTH_TEST | moderngl.RASTERIZER_DISCARD)
print(query.samples)
scope = ctx.scope(
framebuffer=framebuffer1,
enable_only=moderngl.BLEND,
textures=[
(texture1, 4),
(texture2, 3),
],
uniform_buffers=[
(buffer1, 6),
(buffer2, 5),
],
storage_buffers=[
(buffer3, 8),
],
)
76 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
with scope:
# on __enter__
# framebuffer1.use()
# ctx.enable_only(moderngl.BLEND)
# texture1.use(4)
# texture2.use(3)
# buffer1.bind_to_uniform_block(6)
# buffer2.bind_to_uniform_block(5)
# buffer3.bind_to_storage_buffer(8)
# do some rendering
# on __exit__
# some_random_framebuffer.use()
# ctx.enable_only(moderngl.DEPTH_TEST)
3.13 Query
class moderngl.Query
This class represents a Query object.
3.13.1 Create
3.13.2 Attributes
Query.samples
The number of samples passed.
3.13. Query 77
ModernGL Documentation, Release 5.6.1
Type int
Query.primitives
The number of primitives generated.
Type int
Query.elapsed
The time elapsed in nanoseconds.
Type int
Query.crender
Can be used in a with statement.
Type ConditionalRender
Query.extra
Any - Attribute for storing user defined objects
Query.mglo
Internal representation for debug purposes only.
Query.ctx
The context this object belongs to
3.13.3 Examples
1 import moderngl
2 import numpy as np
3
4 ctx = moderngl.create_standalone_context()
5 prog = ctx.program(
6 vertex_shader='''
7 #version 330
8
9 in vec2 in_vert;
10
11 void main() {
12 gl_Position = vec4(in_vert, 0.0, 1.0);
13 }
14 ''',
15 fragment_shader='''
16 #version 330
17
20 void main() {
21 color = vec4(1.0, 0.0, 0.0, 1.0);
22 }
23 ''',
24 )
25
26 vertices = np.array([
27 0.0, 0.0,
28 1.0, 0.0,
29 0.0, 1.0,
(continues on next page)
78 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
32 vbo = ctx.buffer(vertices.tobytes())
33 vao = ctx.simple_vertex_array(prog, vbo, 'in_vert')
34
40 with query:
41 vao.render()
42
Output
3.14 ConditionalRender
class moderngl.ConditionalRender
This class represents a ConditionalRender object.
ConditionalRender objects can only be accessed from Query objects.
3.14.1 Attributes
ConditionalRender.mglo
Internal representation for debug purposes only.
3.14.2 Examples
query = ctx.query(any_samples=True)
with query:
vao1.render()
with query.crender:
print('This will always get printed')
vao2.render() # But this will be rendered only if vao1 has passing samples.
3.14. ConditionalRender 79
ModernGL Documentation, Release 5.6.1
3.15 ComputeShader
class moderngl.ComputeShader
A Compute Shader is a Shader Stage that is used entirely for computing arbitrary information. While it can do
rendering, it is generally used for tasks not directly related to drawing.
• Compute shaders support uniforms are other member object just like a moderngl.Program.
• Storage buffers can be bound using Buffer.bind_to_storage_buffer().
• Uniform buffers can be bound using Buffer.bind_to_uniform_block().
• Images can be bound using Texture.bind_to_image().
3.15.1 Create
Context.compute_shader(source) → ComputeShader
A ComputeShader is a Shader Stage that is used entirely for computing arbitrary information. While it can
do rendering, it is generally used for tasks not directly related to drawing.
Parameters source (str) – The source of the compute shader.
Returns ComputeShader object
3.15.2 Methods
80 Chapter 3. Reference
ModernGL Documentation, Release 5.6.1
ComputeShader.__setitem__(key, value)
Set a value of uniform or uniform block
# Optionally we can store references to a member and set the value directly
uniform = program['color']
uniform.value = 1.0, 0.0, 0.0, 0.0
uniform = program['cameraMatrix']
uniform.write(camera_matrix)
3.15.3 Attributes
ComputeShader.glo
The internal OpenGL object. This values is provided for debug purposes only.
Type int
ComputeShader.mglo
Internal representation for debug purposes only.
ComputeShader.extra
Any - Attribute for storing user defined objects
ComputeShader.ctx
The context this object belongs to
3.15. ComputeShader 81
ModernGL Documentation, Release 5.6.1
82 Chapter 3. Reference
CHAPTER 4
Miscellaneous
ModernGL4
ModernGL5
ModernGL4
83
ModernGL Documentation, Release 5.6.1
ModernGL5
ModernGL4
my_program = ctx.program(
ctx.vertex_shader('''
...
'''),
['out_vert', 'out_norm'] # no keyword argument needed
])
ModernGL5
my_program = ctx.program(
vertex_shader='''
...
''',
varyings=['out_vert', 'out_norm'], # varyings are explicitly given
)
84 Chapter 4. Miscellaneous
ModernGL Documentation, Release 5.6.1
ModernGL4
my_program.uniforms['ModelViewMatrix'].value = ...
my_program.uniform_buffers['UniformBuffer'].binding = ...
ModernGL5
my_program['ModelViewMatrix'].value = ...
my_program['UniformBuffer'].binding = ...
ModernGL4
ModernGL5
ModernGL4
my_vertex_array = ctx.vertex_array(prog, [
(vbo1, '3f3f', ['in_vert', 'in_norm']), # extra list object
# ^ no space between the attributes
...
])
ModernGL5
my_vertex_array = ctx.vertex_array(prog, [
(vbo1, '3f 3f', 'in_vert', 'in_norm'), # no list needed
# ^ space is obligatory
...
])
ModernGL4
ModernGL5
my_vertex_array = ctx.vertex_array(prog, [
(vbo1, '3f2 3f2', 'in_vert', 'in_norm'), # '3f2' means '3' of 'f2', where 'f2'
˓→is a half-float
...
])
ModernGL4
my_vertex_array = ctx.vertex_array(prog, [
(vbo1, '3f12x', ['in_vert']), # same as above, in_norm was replaced with padding
...
])
ModernGL5
my_vertex_array = ctx.vertex_array(prog, [
(vbo1, '3f 3x4', ['in_vert']), # '3x4' means '3' of 'x4', where 'x4' means 4
˓→bytes of padding
...
])
86 Chapter 4. Miscellaneous
ModernGL Documentation, Release 5.6.1
ModernGL4
my_vertex_array = ctx.vertex_array(prog, [
(vbo1, '3f', ['in_vert']), # throws an error (3 != 4)
...
])
my_vertex_array = ctx.vertex_array(prog, [
(vbo1, '4i', ['in_vert']), # throws an error (float != int)
...
])
ModernGL5
my_vertex_array = ctx.vertex_array(prog, [
(vbo1, '3f', 'in_vert'), # totally fine
...
])
my_vertex_array = ctx.vertex_array(prog, [
(vbo1, '4i', 'in_vert'), # totally fine
...
])
88 Chapter 4. Miscellaneous
CHAPTER 5
• genindex
• modindex
• search
89
ModernGL Documentation, Release 5.6.1
m
moderngl, 14
moderngl.conditional_renderer, 79
91
ModernGL Documentation, Release 5.6.1
93
ModernGL Documentation, Release 5.6.1
D F
DEFAULT_BLENDING (moderngl.Context attribute), 34 fbo (moderngl.Context attribute), 29
default_texture_unit (moderngl.Context at- filter (moderngl.Sampler attribute), 53
tribute), 30 filter (moderngl.Texture attribute), 57
depth (moderngl.Renderbuffer attribute), 74 filter (moderngl.Texture3D attribute), 65
depth (moderngl.Texture attribute), 59 filter (moderngl.TextureArray attribute), 61
depth (moderngl.Texture3D attribute), 66 filter (moderngl.TextureCube attribute), 68
depth_attachment (moderngl.Framebuffer at- finish() (moderngl.Context method), 26
tribute), 73 FIRST_VERTEX_CONVENTION (moderngl.Context at-
depth_func (moderngl.Context attribute), 27 tribute), 35
depth_mask (moderngl.Framebuffer attribute), 72 Framebuffer (class in moderngl), 69
depth_renderbuffer() (moderngl.Context framebuffer() (moderngl.Context method), 23
method), 23 front_face (moderngl.Context attribute), 30
DEPTH_TEST (moderngl.Context attribute), 33 FUNC_ADD (moderngl.Context attribute), 34
depth_texture() (moderngl.Context method), 21 FUNC_REVERSE_SUBTRACT (moderngl.Context at-
detect_framebuffer() (moderngl.Context tribute), 34
method), 27 FUNC_SUBTRACT (moderngl.Context attribute), 34
dimension (moderngl.Attribute attribute), 49
dimension (moderngl.Uniform attribute), 46 G
disable() (moderngl.Context method), 26 geometry_input (moderngl.Program attribute), 45
DST_ALPHA (moderngl.Context attribute), 34 geometry_output (moderngl.Program attribute), 45
DST_COLOR (moderngl.Context attribute), 34 geometry_vertices (moderngl.Program attribute),
dtype (moderngl.Renderbuffer attribute), 74 45
dtype (moderngl.Texture attribute), 59 get() (moderngl.ComputeShader method), 80
dtype (moderngl.Texture3D attribute), 66 get() (moderngl.Program method), 43
dtype (moderngl.TextureArray attribute), 63 glo (moderngl.Buffer attribute), 39
dtype (moderngl.TextureCube attribute), 68 glo (moderngl.ComputeShader attribute), 81
dynamic (moderngl.Buffer attribute), 39 glo (moderngl.Framebuffer attribute), 73
glo (moderngl.Program attribute), 45
E glo (moderngl.Renderbuffer attribute), 74
elapsed (moderngl.Query attribute), 78 glo (moderngl.Texture attribute), 59
enable() (moderngl.Context method), 26 glo (moderngl.Texture3D attribute), 66
enable_only() (moderngl.Context method), 25 glo (moderngl.TextureArray attribute), 63
error (moderngl.Context attribute), 31 glo (moderngl.TextureCube attribute), 69
extra (moderngl.Attribute attribute), 50 glo (moderngl.VertexArray attribute), 42
extra (moderngl.Buffer attribute), 39
extra (moderngl.ComputeShader attribute), 81 H
extra (moderngl.Context attribute), 33 height (moderngl.Framebuffer attribute), 72
extra (moderngl.Framebuffer attribute), 73 height (moderngl.Renderbuffer attribute), 74
extra (moderngl.Program attribute), 45 height (moderngl.Texture attribute), 59
extra (moderngl.Query attribute), 78 height (moderngl.Texture3D attribute), 66
extra (moderngl.Renderbuffer attribute), 75 height (moderngl.TextureArray attribute), 62
94 Index
ModernGL Documentation, Release 5.6.1
Index 95
ModernGL Documentation, Release 5.6.1
96 Index
ModernGL Documentation, Release 5.6.1
Z
ZERO (moderngl.Context attribute), 34
Index 97