Context

class moderngl.Context

Class exposing OpenGL features. ModernGL objects can be created from this class.

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:

# Accept the current context version
ctx = moderngl.create_context()

# Require at least OpenGL 4.3
ctx = moderngl.create_context(require=430)

# Create a headless context requiring OpenGL 4.3
ctx = moderngl.create_context(require=430, standalone=True)
Keyword Arguments:
 
  • require (int) – OpenGL version code (default: 330)
  • standalone (bool) – Headless flag
  • **settings – Other backend specific settings
Returns:

Context object

moderngl.create_standalone_context(require=None) → Context

Create a standalone/headless ModernGL context. The preferred way of making a context is through moderngl.create_context().

Example:

# Create a context with highest possible supported version
ctx = moderngl.create_context()

# Require at least OpenGL 4.3
ctx = moderngl.create_context(require=430)
Keyword Arguments:
 require (int) – OpenGL version code.
Returns:Context object

ModernGL Objects

Context.program(vertex_shader, fragment_shader=None, geometry_shader=None, tess_control_shader=None, tess_evaluation_shader=None, varyings=()) → Program

Create a Program object.

Only linked programs will be returned.

A single shader in the shaders parameter is also accepted. The varyings are only used when a transform program is created.

Parameters:
  • shaders (list) – A list of Shader objects.
  • varyings (list) – A list of varying names.
Returns:

Program object

Context.simple_vertex_array(program, buffer, *attributes, index_buffer=None, index_element_size=4) → VertexArray

Create a VertexArray object.

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

Context.buffer(data=None, reserve=0, dynamic=False) → Buffer

Create a Buffer object.

Parameters:

data (bytes) – Content of the new buffer.

Keyword Arguments:
 
  • reserve (int) – The number of bytes to reserve.
  • dynamic (bool) – Treat buffer as dynamic.
Returns:

Buffer object

Context.texture(size, components, data=None, samples=0, alignment=1, dtype='f1', internal_format=None) → Texture

Create a Texture object.

Warning

Do not play with internal_format unless you know exactly you are doing. This is an override to support sRGB and compressed textures if needed.

Parameters:
  • size (tuple) – The width and height of the texture.
  • components (int) – The number of components 1, 2, 3 or 4.
  • 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.
  • dtype (str) – Data type.
  • internal_format (int) – Override the internalformat of the texture (IF needed)
Returns:

Texture object

Context.depth_texture(size, data=None, samples=0, alignment=4) → Texture

Create a Texture object.

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

Context.texture3d(size, components, data=None, alignment=1, dtype='f1') → Texture3D

Create a Texture3D object.

Parameters:
  • size (tuple) – The width, height and depth of the texture.
  • components (int) – The number of components 1, 2, 3 or 4.
  • data (bytes) – Content of the texture.
Keyword Arguments:
 
  • alignment (int) – The byte alignment 1, 2, 4 or 8.
  • dtype (str) – Data type.
Returns:

Texture3D object

Context.texture_array(size, components, data=None, alignment=1, dtype='f1') → TextureArray

Create a TextureArray object.

Parameters:
  • size (tuple) – The (width, height, layers) of the texture.
  • components (int) – The number of components 1, 2, 3 or 4.
  • data (bytes) – Content of the texture. The size must be (width, height * layers) so each layer is stacked vertically.
Keyword Arguments:
 
  • alignment (int) – The byte alignment 1, 2, 4 or 8.
  • dtype (str) – Data type.
Returns:

Texture3D object

Context.texture_cube(size, components, data=None, alignment=1, dtype='f1') → TextureCube

Create a TextureCube object.

Parameters:
  • size (tuple) – The width, height of the texture. Each side of the cube will have this size.
  • components (int) – The number of components 1, 2, 3 or 4.
  • data (bytes) – Content of the texture. The data should be have the following ordering: positive_x, negative_x, positive_y, negative_y, positive_z + negative_z
Keyword Arguments:
 
  • alignment (int) – The byte alignment 1, 2, 4 or 8.
  • dtype (str) – Data type.
Returns:

TextureCube object

Context.simple_framebuffer(size, components=4, samples=0, dtype='f1') → Framebuffer

Creates a Framebuffer with a single color attachment and depth buffer using moderngl.Renderbuffer attachments.

Parameters:
  • size (tuple) – The width and height of the renderbuffer.
  • components (int) – The number of components 1, 2, 3 or 4.
Keyword Arguments:
 
  • samples (int) – The number of samples. Value 0 means no multisample format.
  • dtype (str) – Data type.
Returns:

Framebuffer object

Context.framebuffer(color_attachments=(), depth_attachment=None) → 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.

Parameters:
Returns:

Framebuffer object

Context.renderbuffer(size, components=4, samples=0, dtype='f1') → Renderbuffer

Renderbuffer objects are OpenGL objects that contain images. They are created and used specifically with Framebuffer objects.

Parameters:
  • size (tuple) – The width and height of the renderbuffer.
  • components (int) – The number of components 1, 2, 3 or 4.
Keyword Arguments:
 
  • samples (int) – The number of samples. Value 0 means no multisample format.
  • dtype (str) – Data type.
Returns:

Renderbuffer object

Context.depth_renderbuffer(size, samples=0) → Renderbuffer

Renderbuffer objects are OpenGL objects that contain images. They are created and used specifically with Framebuffer objects.

Parameters:size (tuple) – The width and height of the renderbuffer.
Keyword Arguments:
 samples (int) – The number of samples. Value 0 means no multisample format.
Returns:Renderbuffer object
Context.scope(framebuffer=None, enable_only=None, textures=(), uniform_buffers=(), storage_buffers=(), samplers=(), enable=None) → Scope

Create a Scope object.

Parameters:
  • framebuffer (Framebuffer) – The framebuffer to use when entering.
  • enable_only (int) – The enable_only flags to set when entering.
Keyword Arguments:
 
  • textures (list) – List of (texture, binding) tuples.
  • uniform_buffers (list) – List of (buffer, binding) tuples.
  • storage_buffers (list) – List of (buffer, binding) tuples.
  • samplers (list) – List of sampler bindings
  • enable (int) – Flags to enable for this vao such as depth testing and blending
Context.query(samples=False, any_samples=False, time=False, primitives=False) → Query

Create a Query object.

Keyword Arguments:
 
  • samples (bool) – Query GL_SAMPLES_PASSED or not.
  • any_samples (bool) – Query GL_ANY_SAMPLES_PASSED or not.
  • time (bool) – Query GL_TIME_ELAPSED or not.
  • primitives (bool) – Query GL_PRIMITIVES_GENERATED or not.
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
Context.sampler(repeat_x=True, repeat_y=True, repeat_z=True, filter=None, anisotropy=1.0, compare_func='?', border_color=None, min_lod=-1000.0, max_lod=1000.0, texture=None) → Sampler

Create a Sampler object.

Keyword Arguments:
 
  • repeat_x (bool) – Repeat texture on x
  • repeat_y (bool) – Repeat texture on y
  • repeat_z (bool) – Repeat texture on z
  • filter (tuple) – The min and max filter
  • anisotropy (float) – Number of samples for anisotropic filtering. Any value greater than 1.0 counts as a use of anisotropic filtering
  • compare_func – Compare function for depth textures
  • border_color (tuple) – The (r, g, b, a) color for the texture border. When this value is set the repeat_ values are overridden setting the texture wrap to return the border color when outside [0, 1] range.
  • min_lod (float) – Minimum level-of-detail parameter (Default -1000.0). This floating-point value limits the selection of highest resolution mipmap (lowest mipmap level)
  • max_lod (float) – Minimum level-of-detail parameter (Default 1000.0). This floating-point value limits the selection of the lowest resolution mipmap (highest mipmap level)
  • texture (Texture) – The texture for this sampler
Context.clear_samplers(start=0, end=-1)

Unbinds samplers from texture units. Sampler bindings do clear automatically between every frame, but lingering samplers can still be a source of weird bugs during the frame rendering. This methods provides a fairly brute force and efficient way to ensure texture units are clear.

Keyword Arguments:
 
  • start (int) – The texture unit index to start the clearing samplers
  • stop (int) – The texture unit index to stop clearing samplers

Example:

# Clear texture unit 0, 1, 2, 3, 4
ctx.clear_samplers(start=0, end=5)

# Clear texture unit 4, 5, 6, 7
ctx.clear_samplers(start=4, end=8)
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.

Methods

Context.clear(red=0.0, green=0.0, blue=0.0, alpha=0.0, depth=1.0, viewport=None, color=None)

Clear the bound framebuffer.

If a viewport passed in, a scissor test will be used to clear the given viewport. This viewport take prescense over the framebuffers scissor. Clearing can still be done with scissor if no viewport is passed in.

This method also respects the color_mask and depth_mask. It can for example be used to only clear the depth or color buffer or specific components in the color buffer.

If the viewport is a 2-tuple it will clear the (0, 0, width, height) where (width, height) is the 2-tuple.

If the viewport is a 4-tuple it will clear the given viewport.

Parameters:
  • red (float) – color component.
  • green (float) – color component.
  • blue (float) – color component.
  • alpha (float) – alpha component.
  • depth (float) – depth value.
Keyword Arguments:
 

viewport (tuple) – The viewport.

Context.enable_only(flags)

Clears all existing flags applying new ones.

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.

Available flags:

  • moderngl.NOTHING
  • moderngl.BLEND
  • moderngl.DEPTH_TEST
  • moderngl.CULL_FACE
  • moderngl.RASTERIZER_DISCARD
  • moderngl.PROGRAM_POINT_SIZE

Examples:

# Disable all flags
ctx.enable_only(moderngl.NOTHING)

# Ensure only depth testing and face culling is enabled
ctx.enable_only(moderngl.DEPTH_TEST | moderngl.CULL_FACE)
Parameters:flags (EnableFlag) – The flags to enable
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:

# Enable a single flag
ctx.enable(moderngl.DEPTH_TEST)

# Enable multiple flags
ctx.enable(moderngl.DEPTH_TEST | moderngl.CULL_FACE | moderngl.BLEND)
Parameters:flag (int) – The flags to enable.
Context.disable(flags)

Disable flags.

For valid flags, please see enable_only().

Examples:

# Only disable depth testing
ctx.disable(moderngl.DEPTH_TEST)

# Disable depth testing and face culling
ctx.disable(moderngl.DEPTH_TEST | moderngl.CULL_FACE)
Parameters:flag (int) – The flags to disable.
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.
  • write_offset (int) – The write offset.
Context.copy_framebuffer(dst, src)

Copy framebuffer content.

Use this method to:

  • blit framebuffers.
  • copy framebuffer content into a texture.
  • downsample framebuffers. (it will allow to read the framebuffer’s content)
  • downsample a framebuffer directly to a texture.
Parameters:
Context.detect_framebuffer(glo=None) → Framebuffer

Detect framebuffer. This is already done when creating a context, but if the underlying window library for some changes the default framebuffer during the lifetime of the application this might be necessary.

Parameters:glo (int) – Framebuffer object.
Returns:Framebuffer object
Context.__enter__()

Enters the context.

This should ideally be used with the with statement:

with other_context as ctx:
    # Do something in this context

When exiting the context the previously bound context is activated again.

Warning

Context switching can be risky unless you know what you are doing. Use with care.

Context.__exit__(exc_type, exc_val, exc_tb)

Exit the context.

See Context.__enter__()

Attributes

Context.line_width

Warning

A line width other than 1.0 is not guaranteed to work across different OpenGL implementations. For wide lines you should be using geometry shaders.

float: Set the default line width.

Context.point_size

Set/get the default point size.

Type:float
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

# Separate for rgb and alpha
ctx.blend_func = (
    moderngl.SRC_ALPHA, moderngl.ONE_MINUS_SRC_ALPHA,
    moderngl.ONE, moderngl.ONE
)
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
moderngl.MIN                    # Minimum of source and destination
moderngl.MAX                    # Maximum of source and destination

Example:

# For both rgb and alpha channel
ctx.blend_func = moderngl.FUNC_ADD

# Separate for rgb and alpha channel
ctx.blend_func = moderngl.FUNC_ADD, moderngl.MAX
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)

If no framebuffer is bound (0, 0, 0, 0) will be returned.

Type:tuple
Context.scissor

Get or set the scissor box for the active framebuffer

When scissor testing is enabled fragments outside the defined scissor box will be discarded. This applies to rendered geometry or Context.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:

# Enable scissor testing
>>> ctx.scissor = 100, 100, 200, 100
# Disable scissor testing
>>> ctx.scissor = None

If no framebuffer is bound (0, 0, 0, 0) will be returned.

Type:tuple
Context.version_code

The OpenGL version code. Reports 410 for OpenGL 4.1

Type:int
Context.screen

A Framebuffer instance representing the screen usually set when creating a context with create_context() attaching to an existing context. This is the special system framebuffer represented by framebuffer id=0.

When creating a standalone context this property is not set.

Type:Framebuffer
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:

# Triangles winded counter-clockwise considered front facing
ctx.front_face = 'ccw'
# Triangles winded clockwise considered front facing
ctx.front_face = 'cw'
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
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:

# Use first vertex
ctx.provoking_vertex = moderngl.FIRST_VERTEX_CONVENTION

# Use last vertex
ctx.provoking_vertex = moderngl.LAST_VERTEX_CONVENTION
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.extensions

The extensions supported by the context

All extensions names have a GL_ prefix, so if the spec refers to ARB_compute_shader we need to look for GL_ARB_compute_shader:

# If compute shaders are supported ...
>> "GL_ARB_compute_shader" in ctx.extensions
True

Example data:

{
    'GL_ARB_multi_bind',
    'GL_ARB_shader_objects',
    'GL_ARB_half_float_vertex',
    'GL_ARB_map_buffer_alignment',
    'GL_ARB_arrays_of_arrays',
    'GL_ARB_pipeline_statistics_query',
    'GL_ARB_provoking_vertex',
    'GL_ARB_gpu_shader5',
    'GL_ARB_uniform_buffer_object',
    'GL_EXT_blend_equation_separate',
    'GL_ARB_tessellation_shader',
    'GL_ARB_multi_draw_indirect',
    'GL_ARB_multisample',
    .. etc ..
}
Type:Set[str]
Context.info

OpenGL Limits and information about the context

Example:

# The maximum width and height of a texture
>> ctx.info["GL_MAX_TEXTURE_SIZE"]
16384

# Vendor and renderer
>> ctx.info["GL_VENDOR"]
NVIDIA Corporation
>> ctx.info["GL_RENDERER"]
NVIDIA GeForce GT 650M OpenGL Engine

Example data:

{
    '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),
    'GL_ALIASED_LINE_WIDTH_RANGE': (1.0, 1.0),
    'GL_POINT_FADE_THRESHOLD_SIZE': 1.0,
    'GL_POINT_SIZE_GRANULARITY': 0.125,
    'GL_SMOOTH_LINE_WIDTH_GRANULARITY': 0.125,
    'GL_MIN_PROGRAM_TEXEL_OFFSET': -8.0,
    'GL_MAX_PROGRAM_TEXEL_OFFSET': 7.0,
    'GL_MINOR_VERSION': 1,
    'GL_MAJOR_VERSION': 4,
    'GL_SAMPLE_BUFFERS': 0,
    'GL_SUBPIXEL_BITS': 8,
    'GL_CONTEXT_PROFILE_MASK': 1,
    'GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT': 256,
    'GL_DOUBLEBUFFER': False,
    'GL_STEREO': False,
    'GL_MAX_VIEWPORT_DIMS': (16384, 16384),
    'GL_MAX_3D_TEXTURE_SIZE': 2048,
    'GL_MAX_ARRAY_TEXTURE_LAYERS': 2048,
    'GL_MAX_CLIP_DISTANCES': 8,
    'GL_MAX_COLOR_ATTACHMENTS': 8,
    'GL_MAX_COLOR_TEXTURE_SAMPLES': 8,
    'GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS': 233472,
    'GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS': 231424,
    'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS': 80,
    'GL_MAX_COMBINED_UNIFORM_BLOCKS': 70,
    'GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS': 233472,
    'GL_MAX_CUBE_MAP_TEXTURE_SIZE': 16384,
    'GL_MAX_DEPTH_TEXTURE_SAMPLES': 8,
    'GL_MAX_DRAW_BUFFERS': 8,
    'GL_MAX_DUAL_SOURCE_DRAW_BUFFERS': 1,
    'GL_MAX_ELEMENTS_INDICES': 150000,
    'GL_MAX_ELEMENTS_VERTICES': 1048575,
    'GL_MAX_FRAGMENT_INPUT_COMPONENTS': 128,
    'GL_MAX_FRAGMENT_UNIFORM_COMPONENTS': 4096,
    'GL_MAX_FRAGMENT_UNIFORM_VECTORS': 1024,
    'GL_MAX_FRAGMENT_UNIFORM_BLOCKS': 14,
    'GL_MAX_GEOMETRY_INPUT_COMPONENTS': 128,
    'GL_MAX_GEOMETRY_OUTPUT_COMPONENTS': 128,
    'GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS': 16,
    'GL_MAX_GEOMETRY_UNIFORM_BLOCKS': 14,
    'GL_MAX_GEOMETRY_UNIFORM_COMPONENTS': 2048,
    'GL_MAX_INTEGER_SAMPLES': 1,
    'GL_MAX_SAMPLES': 8,
    'GL_MAX_RECTANGLE_TEXTURE_SIZE': 16384,
    'GL_MAX_RENDERBUFFER_SIZE': 16384,
    'GL_MAX_SAMPLE_MASK_WORDS': 1,
    'GL_MAX_SERVER_WAIT_TIMEOUT': -1,
    'GL_MAX_TEXTURE_BUFFER_SIZE': 134217728,
    'GL_MAX_TEXTURE_IMAGE_UNITS': 16,
    'GL_MAX_TEXTURE_LOD_BIAS': 15,
    'GL_MAX_TEXTURE_SIZE': 16384,
    'GL_MAX_UNIFORM_BUFFER_BINDINGS': 70,
    'GL_MAX_UNIFORM_BLOCK_SIZE': 65536,
    'GL_MAX_VARYING_COMPONENTS': 0,
    'GL_MAX_VARYING_VECTORS': 31,
    'GL_MAX_VARYING_FLOATS': 0,
    'GL_MAX_VERTEX_ATTRIBS': 16,
    'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS': 16,
    'GL_MAX_VERTEX_UNIFORM_COMPONENTS': 4096,
    'GL_MAX_VERTEX_UNIFORM_VECTORS': 1024,
    'GL_MAX_VERTEX_OUTPUT_COMPONENTS': 128,
    'GL_MAX_VERTEX_UNIFORM_BLOCKS': 14,
    'GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET': 0,
    'GL_MAX_VERTEX_ATTRIB_BINDINGS': 0,
    'GL_VIEWPORT_BOUNDS_RANGE': (-32768, 32768),
    'GL_VIEWPORT_SUBPIXEL_BITS': 0,
    'GL_MAX_VIEWPORTS': 16
}
Type:dict
Context.mglo

Internal representation for debug purposes only.

Context.extra

Any - Attribute for storing user defined objects

Context Flags

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.

Primitive Modes

Context.POINTS = 0

Each vertex represents a point

Context.LINES = 1

Vertices 0 and 1 are considered a line. Vertices 2 and 3 are considered a line. And so on. If the user specifies a non-even number of vertices, then the extra vertex is ignored.

Context.LINE_LOOP = 2

As line strips, except that the first and last vertices are also used as a line. Thus, you get n lines for n input vertices. If the user only specifies 1 vertex, the drawing command is ignored. The line between the first and last vertices happens after all of the previous lines in the sequence.

Context.LINE_STRIP = 3

The adjacent vertices are considered lines. Thus, if you pass n vertices, you will get n-1 lines. If the user only specifies 1 vertex, the drawing command is ignored.

Context.TRIANGLES = 4

Vertices 0, 1, and 2 form a triangle. Vertices 3, 4, and 5 form a triangle. And so on.

Context.TRIANGLE_STRIP = 5

Every group of 3 adjacent vertices forms a triangle. The face direction of the strip is determined by the winding of the first triangle. Each successive triangle will have its effective face order reversed, so the system compensates for that by testing it in the opposite way. A vertex stream of n length will generate n-2 triangles.

Context.TRIANGLE_FAN = 6

The first vertex is always held fixed. From there on, every group of 2 adjacent vertices form a triangle with the first. So with a vertex stream, you get a list of triangles like so: (0, 1, 2) (0, 2, 3), (0, 3, 4), etc. A vertex stream of n length will generate n-2 triangles.

Context.LINES_ADJACENCY = 10

These are special primitives that are expected to be used specifically with geomtry shaders. These primitives give the geometry shader more vertices to work with for each input primitive. Data needs to be duplicated in buffers.

Context.LINE_STRIP_ADJACENCY = 11

These are special primitives that are expected to be used specifically with geomtry shaders. These primitives give the geometry shader more vertices to work with for each input primitive. Data needs to be duplicated in buffers.

Context.TRIANGLES_ADJACENCY = 12

These are special primitives that are expected to be used specifically with geomtry shaders. These primitives give the geometry shader more vertices to work with for each input primitive. Data needs to be duplicated in buffers.

Context.TRIANGLE_STRIP_ADJACENCY = 13

These are special primitives that are expected to be used specifically with geomtry shaders. These primitives give the geometry shader more vertices to work with for each input primitive. Data needs to be duplicated in buffers.

Context.PATCHES = 14

primitive type can only be used when Tessellation is active. It is a primitive with a user-defined number of vertices, which is then tessellated based on the control and evaluation shaders into regular points, lines, or triangles, depending on the TES’s settings.

Texture Filters

Also available in the Context instance including mode details.

Context.NEAREST = 9728

Returns the value of the texture element that is nearest (in Manhattan distance) to the specified texture coordinates.

Context.LINEAR = 9729

Returns the weighted average of the four texture elements that are closest to the specified texture coordinates. These can include items wrapped or repeated from other parts of a texture, depending on the values of texture repeat mode, and on the exact mapping.

Context.NEAREST_MIPMAP_NEAREST = 9984

Chooses the mipmap that most closely matches the size of the pixel being textured and uses the NEAREST criterion (the texture element closest to the specified texture coordinates) to produce a texture value.

Context.LINEAR_MIPMAP_NEAREST = 9985

Chooses the mipmap that most closely matches the size of the pixel being textured and uses the LINEAR criterion (a weighted average of the four texture elements that are closest to the specified texture coordinates) to produce a texture value.

Context.NEAREST_MIPMAP_LINEAR = 9986

Chooses the two mipmaps that most closely match the size of the pixel being textured and uses the NEAREST criterion (the texture element closest to the specified texture coordinates ) to produce a texture value from each mipmap. The final texture value is a weighted average of those two values.

Context.LINEAR_MIPMAP_LINEAR = 9987

Chooses the two mipmaps that most closely match the size of the pixel being textured and uses the LINEAR criterion (a weighted average of the texture elements that are closest to the specified texture coordinates) to produce a texture value from each mipmap. The final texture value is a weighted average of those two values.

Blend Functions

Blend functions are used with Context.blend_func to control blending operations.

# Default value
ctx.blend_func = ctx.SRC_ALPHA, ctx.ONE_MINUS_SRC_ALPHA
Context.ZERO = 0

(0,0,0,0)

Context.ONE = 1

(1,1,1,1)

Context.SRC_COLOR = 768

(Rs0/kR,Gs0/kG,Bs0/kB,As0/kA)

Context.ONE_MINUS_SRC_COLOR = 769

(1,1,1,1) − (Rs0/kR,Gs0/kG,Bs0/kB,As0/kA)

Context.SRC_ALPHA = 770

(As0/kA,As0/kA,As0/kA,As0/kA)

Context.ONE_MINUS_SRC_ALPHA = 771

(1,1,1,1) − (As0/kA,As0/kA,As0/kA,As0/kA)

Context.DST_ALPHA = 772

(Ad/kA,Ad/kA,Ad/kA,Ad/kA)

Context.ONE_MINUS_DST_ALPHA = 773

(1,1,1,1) − (Ad/kA,Ad/kA,Ad/kA,Ad/kA)

Context.DST_COLOR = 774

(Rd/kR,Gd/kG,Bd/kB,Ad/kA)

Context.ONE_MINUS_DST_COLOR = 775

(1,1,1,1) − (Rd/kR,Gd/kG,Bd/kB,Ad/kA)

Blend Function Shortcuts

Context.DEFAULT_BLENDING = (770, 771)

Shotcut for the default blending SRC_ALPHA, ONE_MINUS_SRC_ALPHA

Context.ADDITIVE_BLENDING = (1, 1)

Shotcut for additive blending ONE, ONE

Context.PREMULTIPLIED_ALPHA = (770, 1)

Shotcut for blend mode when using premultiplied alpha SRC_ALPHA, ONE

Blend Equations

Used with Context.blend_equation.

Context.FUNC_ADD = 32774

source + destination

Context.FUNC_SUBTRACT = 32778

source - destination

Context.FUNC_REVERSE_SUBTRACT = 32779

destination - source

Context.MIN = 32775

Minimum of source and destination

Context.MAX = 32776

Maximum of source and destination

Other Enums

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.

Examples

import moderngl
# create a window
ctx = moderngl.create_context()
print(ctx.version_code)
import moderngl
ctx = moderngl.create_standalone_context()
print(ctx.version_code)

context_manager.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import moderngl


class ContextManager:
    ctx = None

    @staticmethod
    def get_default_context(allow_fallback_standalone_context=True) -> moderngl.Context:
        '''
            Default context
        '''

        if ContextManager.ctx is None:
            try:
                ContextManager.ctx = moderngl.create_context()
            except:
                if allow_fallback_standalone_context:
                    ContextManager.ctx = moderngl.create_standalone_context()
                else:
                    raise

        return ContextManager.ctx

example.py

1
2
3
4
from context_manager import ContextManager

ctx = ContextManager.get_default_context()
print(ctx.version_code)