The object oriented OpenGL API (gloo)

Base class

Program class

Buffer classes

class vispy.gloo.buffer.Buffer(data=None, nbytes=None)[source]

Generic GPU buffer.

A generic buffer is an interface used to upload data to a GPU array buffer (ARRAY_BUFFER or ELEMENT_ARRAY_BUFFER). It keeps track of buffer size but does not have any CPU storage. You can consider it as write-only.

The set_data is a deferred operation: you can call it even if an OpenGL context is not available. The update function is responsible to upload pending data to GPU memory and requires an active GL context.

The Buffer class only deals with data in terms of bytes; it is not aware of data type or element size.

Parameters:
datandarray | None

Buffer data.

nbytesint | None

Buffer byte size.

property nbytes

Buffer size in bytes

resize_bytes(size)[source]

Resize this buffer (deferred operation).

Parameters:
sizeint

New buffer size in bytes.

set_data(data, copy=False)[source]

Set data in the buffer (deferred operation).

This completely resets the size and contents of the buffer.

Parameters:
datandarray

Data to be uploaded

copy: bool

Since the operation is deferred, data may change before data is actually uploaded to GPU memory. Asking explicitly for a copy will prevent this behavior.

set_subdata(data, offset=0, copy=False)[source]

Set a sub-region of the buffer (deferred operation).

Parameters:
datandarray

Data to be uploaded

offset: int

Offset in buffer where to start copying data (in bytes)

copy: bool

Since the operation is deferred, data may change before data is actually uploaded to GPU memory. Asking explicitly for a copy will prevent this behavior.

class vispy.gloo.buffer.DataBuffer(data=None)[source]

GPU data buffer that is aware of data type and elements size

Parameters:
datandarray | None

Buffer data.

property dtype

Buffer dtype

property glsl_type

GLSL declaration strings required for a variable to hold this data.

property itemsize

The total number of bytes required to store the array data

property offset

Buffer offset (in bytes) relative to base

resize_bytes(size)[source]

Resize the buffer (in-place, deferred operation)

Parameters:
sizeinteger

New buffer size in bytes

Notes

This clears any pending operations.

set_data(data, copy=False, **kwargs)[source]

Set data (deferred operation)

Parameters:
datandarray

Data to be uploaded

copy: bool

Since the operation is deferred, data may change before data is actually uploaded to GPU memory. Asking explicitly for a copy will prevent this behavior.

**kwargsdict

Additional arguments.

set_subdata(data, offset=0, copy=False, **kwargs)[source]

Set a sub-region of the buffer (deferred operation).

Parameters:
datandarray

Data to be uploaded

offset: int

Offset in buffer where to start copying data (in bytes)

copy: bool

Since the operation is deferred, data may change before data is actually uploaded to GPU memory. Asking explicitly for a copy will prevent this behavior.

**kwargsdict

Additional keyword arguments.

property size

Number of elements in the buffer

property stride

Stride of data in memory

Texture classes

class vispy.gloo.texture.BaseTexture(data=None, format=None, resizable=True, interpolation=None, wrapping=None, shape=None, internalformat=None, resizeable=None)[source]

A Texture is used to represent a topological set of scalar values.

Parameters:
datandarray | tuple | None

Texture data in the form of a numpy array (or something that can be turned into one). A tuple with the shape of the texture can also be given.

formatstr | enum | None

The format of the texture: ‘luminance’, ‘alpha’, ‘luminance_alpha’, ‘rgb’, or ‘rgba’. If not given the format is chosen automatically based on the number of channels. When the data has one channel, ‘luminance’ is assumed.

resizablebool

Indicates whether texture can be resized. Default True.

interpolationstr | None

Interpolation mode, must be one of: ‘nearest’, ‘linear’. Default ‘nearest’.

wrappingstr | None

Wrapping mode, must be one of: ‘repeat’, ‘clamp_to_edge’, ‘mirrored_repeat’. Default ‘clamp_to_edge’.

shapetuple | None

Optional. A tuple with the shape of the texture. If data is also a tuple, it will override the value of shape.

internalformatstr | None

Internal format to use.

resizeableNone

Deprecated version of resizable.

property format

The texture format (color channels).

property interpolation

Texture interpolation for minification and magnification.

resize(shape, format=None, internalformat=None)[source]

Set the texture size and format

Parameters:
shapetuple of integers

New texture shape in zyx order. Optionally, an extra dimention may be specified to indicate the number of color channels.

formatstr | enum | None

The format of the texture: ‘luminance’, ‘alpha’, ‘luminance_alpha’, ‘rgb’, or ‘rgba’. If not given the format is chosen automatically based on the number of channels. When the data has one channel, ‘luminance’ is assumed.

internalformatstr | enum | None

The internal (storage) format of the texture: ‘luminance’, ‘alpha’, ‘r8’, ‘r16’, ‘r16f’, ‘r32f’; ‘luminance_alpha’, ‘rg8’, ‘rg16’, ‘rg16f’, ‘rg32f’; ‘rgb’, ‘rgb8’, ‘rgb16’, ‘rgb16f’, ‘rgb32f’; ‘rgba’, ‘rgba8’, ‘rgba16’, ‘rgba16f’, ‘rgba32f’. If None, the internalformat is chosen automatically based on the number of channels. This is a hint which may be ignored by the OpenGL implementation.

set_data(data, offset=None, copy=False)[source]

Set texture data

Parameters:
datandarray

Data to be uploaded

offset: int | tuple of ints

Offset in texture where to start copying data

copy: bool

Since the operation is deferred, data may change before data is actually uploaded to GPU memory. Asking explicitly for a copy will prevent this behavior.

Notes

This operation implicitly resizes the texture to the shape of the data if given offset is None.

property shape

Data shape (last dimension indicates number of color channels)

property wrapping

Texture wrapping mode

State methods

class vispy.gloo.wrappers.GlooFunctions[source]
property glir

The GLIR queue corresponding to the current canvas

vispy.gloo.wrappers.clear(color=True, depth=True, stencil=True)[source]

Clear the screen buffers

This is a wrapper for gl.glClear.

Parameters:
colorbool | str | tuple | instance of Color

Clear the color buffer bit. If not bool, set_clear_color will be used to set the color clear value.

depthbool | float

Clear the depth buffer bit. If float, set_clear_depth will be used to set the depth clear value.

stencilbool | int

Clear the stencil buffer bit. If int, set_clear_stencil will be used to set the stencil clear index.

vispy.gloo.wrappers.finish()[source]

Wait for GL commands to to finish

This creates a GLIR command for glFinish and then processes the GLIR commands. If the GLIR interpreter is remote (e.g. WebGL), this function will return before GL has finished processing the commands.

vispy.gloo.wrappers.flush()[source]

Flush GL commands

This is a wrapper for glFlush(). This also flushes the GLIR command queue.

vispy.gloo.wrappers.get_gl_configuration()[source]

Read the current gl configuration

This function uses constants that are not in the OpenGL ES 2.1 namespace, so only use this on desktop systems.

Returns:
configdict

The currently active OpenGL configuration.

vispy.gloo.wrappers.get_state_presets()[source]

The available GL state presets

Returns:
presetsdict

The dictionary of presets usable with set_options.

vispy.gloo.wrappers.read_pixels(viewport=None, alpha=True, mode='color', out_type='unsigned_byte')[source]

Read pixels from the currently selected buffer.

Under most circumstances, this function reads from the front buffer. Unlike all other functions in vispy.gloo, this function directly executes an OpenGL command.

Parameters:
viewportarray-like | None

4-element list of x, y, w, h parameters. If None (default), the current GL viewport will be queried and used.

alphabool

If True (default), the returned array has 4 elements (RGBA). If False, it has 3 (RGB). This only effects the color mode.

modestr

Type of buffer data to read. Can be one of ‘colors’, ‘depth’, or ‘stencil’. See returns for more information.

out_typestr | dtype

Can be ‘unsigned_byte’ or ‘float’. Note that this does not use casting, but instead determines how values are read from the current buffer. Can also be numpy dtypes np.uint8, np.ubyte, or np.float32.

Returns:
pixelsarray

3D array of pixels in np.uint8 or np.float32 format. The array shape is (h, w, 3) or (h, w, 4) for colors mode, with the top-left corner of the framebuffer at index [0, 0] in the returned array. If ‘mode’ is depth or stencil then the last dimension is 1.

vispy.gloo.wrappers.set_blend_color(color)[source]

Set the blend color

Parameters:
colorstr | tuple | instance of Color

Color to use. See vispy.color.Color for options.

vispy.gloo.wrappers.set_blend_equation(mode_rgb, mode_alpha=None)[source]

Specify the equation for RGB and alpha blending

Parameters:
mode_rgbstr

Mode for RGB.

mode_alphastr | None

Mode for Alpha. If None, mode_rgb is used.

Notes

See set_blend_equation for valid modes.

vispy.gloo.wrappers.set_blend_func(srgb='one', drgb='zero', salpha=None, dalpha=None)[source]

Specify pixel arithmetic for RGB and alpha

Parameters:
srgbstr

Source RGB factor.

drgbstr

Destination RGB factor.

salphastr | None

Source alpha factor. If None, srgb is used.

dalphastr

Destination alpha factor. If None, drgb is used.

vispy.gloo.wrappers.set_clear_color(color='black', alpha=None)[source]

Set the screen clear color

This is a wrapper for gl.glClearColor.

Parameters:
colorstr | tuple | instance of Color

Color to use. See vispy.color.Color for options.

alphafloat | None

Alpha to use.

vispy.gloo.wrappers.set_clear_depth(depth=1.0)[source]

Set the clear value for the depth buffer

This is a wrapper for gl.glClearDepth.

Parameters:
depthfloat

The depth to use.

vispy.gloo.wrappers.set_clear_stencil(index=0)[source]

Set the clear value for the stencil buffer

This is a wrapper for gl.glClearStencil.

Parameters:
indexint

The index to use when the stencil buffer is cleared.

vispy.gloo.wrappers.set_color_mask(red, green, blue, alpha)[source]

Toggle writing of frame buffer color components

Parameters:
redbool

Red toggle.

greenbool

Green toggle.

bluebool

Blue toggle.

alphabool

Alpha toggle.

vispy.gloo.wrappers.set_cull_face(mode='back')[source]

Set front, back, or both faces to be culled

Parameters:
modestr

Culling mode. Can be “front”, “back”, or “front_and_back”.

vispy.gloo.wrappers.set_depth_func(func='less')[source]

Specify the value used for depth buffer comparisons

Parameters:
funcstr

The depth comparison function. Must be one of ‘never’, ‘less’, ‘equal’, ‘lequal’, ‘greater’, ‘gequal’, ‘notequal’, or ‘always’.

vispy.gloo.wrappers.set_depth_mask(flag)[source]

Toggle writing into the depth buffer

Parameters:
flagbool

Whether depth writing should be enabled.

vispy.gloo.wrappers.set_depth_range(near=0.0, far=1.0)[source]

Set depth values

Parameters:
nearfloat

Near clipping plane.

farfloat

Far clipping plane.

vispy.gloo.wrappers.set_front_face(mode='ccw')[source]

Set which faces are front-facing

Parameters:
modestr

Can be ‘cw’ for clockwise or ‘ccw’ for counter-clockwise.

vispy.gloo.wrappers.set_hint(target, mode)[source]

Set OpenGL drawing hint

Parameters:
targetstr

The target, e.g. ‘fog_hint’, ‘line_smooth_hint’, ‘point_smooth_hint’.

modestr

The mode to set (e.g., ‘fastest’, ‘nicest’, ‘dont_care’).

vispy.gloo.wrappers.set_line_width(width=1.0)[source]

Set line width

Parameters:
widthfloat

The line width.

vispy.gloo.wrappers.set_polygon_offset(factor=0.0, units=0.0)[source]

Set the scale and units used to calculate depth values

Parameters:
factorfloat

Scale factor used to create a variable depth offset for each polygon.

unitsfloat

Multiplied by an implementation-specific value to create a constant depth offset.

vispy.gloo.wrappers.set_sample_coverage(value=1.0, invert=False)[source]

Specify multisample coverage parameters

Parameters:
valuefloat

Sample coverage value (will be clamped between 0. and 1.).

invertbool

Specify if the coverage masks should be inverted.

vispy.gloo.wrappers.set_scissor(x, y, w, h)[source]

Define the scissor box

Parameters:
xint

Left corner of the box.

yint

Lower corner of the box.

wint

The width of the box.

hint

The height of the box.

vispy.gloo.wrappers.set_state(preset=None, **kwargs)[source]

Set OpenGL rendering state, optionally using a preset

Parameters:
presetstr | None

Can be one of (‘opaque’, ‘translucent’, ‘additive’) to use use reasonable defaults for these typical use cases.

**kwargskeyword arguments

Other supplied keyword arguments will override any preset defaults. Options to be enabled or disabled should be supplied as booleans (e.g., 'depth_test=True', cull_face=False), non-boolean entries will be passed as arguments to set_* functions (e.g., blend_func=('src_alpha', 'one') will call set_blend_func).

Notes

This serves three purposes:

  1. Set GL state using reasonable presets.
  2. Wrapping glEnable/glDisable functionality.
  3. Convienence wrapping of other gloo.set_* functions.

For example, one could do the following:

>>> from vispy import gloo
>>> gloo.set_state('translucent', depth_test=False, clear_color=(1, 1, 1, 1))  # noqa, doctest:+SKIP

This would take the preset defaults for ‘translucent’, turn depth testing off (which would normally be on for that preset), and additionally set the glClearColor parameter to be white.

Another example to showcase glEnable/glDisable wrapping:

>>> gloo.set_state(blend=True, depth_test=True, polygon_offset_fill=False)  # noqa, doctest:+SKIP

This would be equivalent to calling

>>> from vispy.gloo import gl
>>> gl.glDisable(gl.GL_BLEND)
>>> gl.glEnable(gl.GL_DEPTH_TEST)
>>> gl.glEnable(gl.GL_POLYGON_OFFSET_FILL)

Or here’s another example:

>>> gloo.set_state(clear_color=(0, 0, 0, 1), blend=True, blend_func=('src_alpha', 'one'))  # noqa, doctest:+SKIP

Thus arbitrary GL state components can be set directly using set_state. Note that individual functions are exposed e.g., as set_clear_color, with some more informative docstrings about those particular functions.

vispy.gloo.wrappers.set_stencil_func(func='always', ref=0, mask=8, face='front_and_back')[source]

Set front or back function and reference value

Parameters:
funcstr

See set_stencil_func.

refint

Reference value for the stencil test.

maskint

Mask that is ANDed with ref and stored stencil value.

facestr

Can be ‘front’, ‘back’, or ‘front_and_back’.

vispy.gloo.wrappers.set_stencil_mask(mask=8, face='front_and_back')[source]

Control the front or back writing of individual bits in the stencil

Parameters:
maskint

Mask that is ANDed with ref and stored stencil value.

facestr

Can be ‘front’, ‘back’, or ‘front_and_back’.

vispy.gloo.wrappers.set_stencil_op(sfail='keep', dpfail='keep', dppass='keep', face='front_and_back')[source]

Set front or back stencil test actions

Parameters:
sfailstr

Action to take when the stencil fails. Must be one of ‘keep’, ‘zero’, ‘replace’, ‘incr’, ‘incr_wrap’, ‘decr’, ‘decr_wrap’, or ‘invert’.

dpfailstr

Action to take when the stencil passes.

dppassstr

Action to take when both the stencil and depth tests pass, or when the stencil test passes and either there is no depth buffer or depth testing is not enabled.

facestr

Can be ‘front’, ‘back’, or ‘front_and_back’.

vispy.gloo.wrappers.set_viewport(*args)[source]

Set the OpenGL viewport

This is a wrapper for gl.glViewport.

Parameters:
*argstuple

X and Y coordinates, plus width and height. Can be passed in as individual components, or as a single tuple with four values.

The OpenGL context

Functionality to deal with GL Contexts in vispy. This module is defined in gloo, because gloo (and the layers that depend on it) need to be context aware. The vispy.app module “provides” a context, and therefore depends on this module. Although the GLContext class is aimed for use by vispy.app (for practical reasons), it should be possible to use GLContext without using vispy.app by overloading it in an appropriate manner.

An GLContext object acts as a placeholder on which different parts of vispy (or other systems) can keep track of information related to an OpenGL context.

class vispy.gloo.context.FakeCanvas[source]

Fake canvas to allow using gloo without vispy.app

Instantiate this class to collect GLIR commands from gloo interactions. Call flush() in your draw event handler to execute the commands in the active contect.

flush()[source]

Flush commands. Call this after setting to context to current.

class vispy.gloo.context.GLContext(config=None, shared=None)[source]

An object encapsulating data necessary for a OpenGL context

Parameters:
configdict | None

The requested configuration.

sharedinstance of GLContext | None

The shared context.

property capabilities

The OpenGL capabilities

property config

A dictionary describing the configuration of this GL context.

create_shared(name, ref)[source]

For the app backends to create the GLShared object.

Parameters:
namestr

The name.

refobject

The reference.

flush_commands(event=None)[source]

Flush

Parameters:
eventinstance of Event

The event.

property glir

The glir queue for the context. This queue is for objects that can be shared accross canvases (if they share a contex).

set_viewport(*args)[source]

Set the OpenGL viewport

This is a wrapper for gl.glViewport.

Parameters:
*argstuple

X and Y coordinates, plus width and height. Can be passed in as individual components, or as a single tuple with four values.

property shared

Get the object that represents the namespace that can potentially be shared between multiple contexts.

class vispy.gloo.context.GLShared[source]

Representation of a “namespace” that can be shared between different contexts. App backends can associate themselves with this object via add_ref().

This object can be used to establish whether two contexts/canvases share objects, and can be used as a placeholder to store shared information, such as glyph atlasses.

add_ref(name, ref)[source]

Add a reference for the backend object that gives access to the low level context. Used in vispy.app.canvas.backends. The given name must match with that of previously added references.

property name

The name of the canvas backend that this shared namespace is associated with. Can be None.

property parser

The GLIR parser (shared between contexts)

property ref

A reference (stored internally via a weakref) to an object that the backend system can use to obtain the low-level information of the “reference context”. In Vispy this will typically be the CanvasBackend object.

vispy.gloo.context.forget_canvas(canvas)[source]

Forget about the given canvas. Used by the canvas when closed.

vispy.gloo.context.get_current_canvas()[source]

Get the currently active canvas

Returns None if there is no canvas available. A canvas is made active on initialization and before the draw event is emitted.

When a gloo object is created, it is associated with the currently active Canvas, or with the next Canvas to be created if there is no current Canvas. Use Canvas.set_current() to manually activate a canvas.

vispy.gloo.context.get_default_config()[source]

Get the default OpenGL context configuration

Returns:
configdict

Dictionary of config values.

vispy.gloo.context.set_current_canvas(canvas)[source]

Make a canvas active. Used primarily by the canvas itself.

vispy.gloo.gl - low level GL API

Vispy also exposes a (low level) functional GL API.