scene

This module provides a 3D graphics scene graph structure.

axes: Bounding Box with axes ticks and labels

Primitive displaying a text field in the scene.

class LabelledAxes[source]

A group displaying a bounding box with axes labels around its children.

tickColor

Color of ticks and text labels.

This does NOT set bounding box color. Use color for the bounding box.

font

Font of axes text labels (Font)

xlabel

Text label of the X axis (str)

ylabel

Text label of the Y axis (str)

zlabel

Text label of the Z axis (str)

boxVisible

Returns bounding box, axes labels and grid visibility.

camera: Projection management classes

This module provides classes to handle a perspective projection in 3D.

class CameraExtrinsic(position=(0.0, 0.0, 0.0), direction=(0.0, 0.0, -1.0), up=(0.0, 1.0, 0.0))[source]

Transform matrix to handle camera position and orientation.

Parameters:
  • position (numpy.ndarray-like of 3 float32.) – Coordinates of the point of view.
  • direction (numpy.ndarray-like of 3 float32.) – Sight direction vector.
  • up (numpy.ndarray-like of 3 float32.) – Vector pointing upward in the image plane.
copy()[source]

Return an independent copy

setOrientation(direction=None, up=None)[source]

Set the rotation of the point of view.

Parameters:
  • direction (numpy.ndarray-like of 3 float32 or None.) – Sight direction vector or None to keep the current one.
  • up (numpy.ndarray-like of 3 float32 or None.) – Vector pointing upward in the image plane or None to keep the current one.
Raises:

RuntimeError – if the direction and up are parallel.

position

Coordinates of the point of view as a numpy.ndarray of 3 float32.

direction

Sight direction (ndarray of 3 float32).

up

Vector pointing upward in the image plane (ndarray of 3 float32).

side

Vector pointing towards the side of the image plane.

ndarray of 3 float32

move(direction, step=1.0)[source]

Move the camera relative to the image plane.

Parameters:
  • direction (str) – Direction relative to image plane. One of: ‘up’, ‘down’, ‘left’, ‘right’, ‘forward’, ‘backward’.
  • step (float) – The step of the pan to perform in the coordinate in which the camera position is defined.
rotate(direction, angle=1.0)[source]

First-person rotation of the camera towards the direction.

Parameters:
  • direction (str) – Direction of movement relative to image plane. In: ‘up’, ‘down’, ‘left’, ‘right’.
  • angle (float) – The angle in degrees of the rotation.
orbit(direction, center=(0.0, 0.0, 0.0), angle=1.0)[source]

Rotate the camera around a point.

Parameters:
  • direction (str) – Direction of movement relative to image plane. In: ‘up’, ‘down’, ‘left’, ‘right’.
  • center (numpy.ndarray-like of 3 float32.) – Position around which to rotate the point of view.
  • angle (float) – he angle in degrees of the rotation.
reset(face=None)[source]

Reset the camera position to pre-defined orientations.

Parameters:face (str) – The direction of the camera in: side, front, back, top, bottom, right, left.
class Camera(fovy=30.0, near=0.1, far=1.0, size=(1.0, 1.0), position=(0.0, 0.0, 0.0), direction=(0.0, 0.0, -1.0), up=(0.0, 1.0, 0.0))[source]

Combination of camera projection and position.

See Perspective and CameraExtrinsic.

Parameters:
  • fovy (float) – Vertical field-of-view in degrees.
  • near (float) – The near clipping plane Z coord (strictly positive).
  • far (float) – The far clipping plane Z coord (> near).
  • size (2-tuple of float) – Viewport’s size used to compute the aspect ratio (width, height).
  • position (numpy.ndarray-like of 3 float32.) – Coordinates of the point of view.
  • direction (numpy.ndarray-like of 3 float32.) – Sight direction vector.
  • up (numpy.ndarray-like of 3 float32.) – Vector pointing upward in the image plane.
resetCamera(bounds)[source]

Change camera to have the bounds in the viewing frustum.

It updates the camera position and depth extent. Camera sight direction and up are not affected.

Parameters:bounds (numpy.ndarray: ((xMin, yMin, zMin), (xMax, yMax, zMax))) – The axes-aligned bounds to include.
intrinsic

Intrinsic camera parameters, i.e., projection matrix.

extrinsic

Extrinsic camera parameters, i.e., position and orientation.

move(*args, **kwargs)[source]

See CameraExtrinsic.move().

rotate(*args, **kwargs)[source]

See CameraExtrinsic.rotate().

orbit(*args, **kwargs)[source]

See CameraExtrinsic.orbit().

core: Base class of the scene nodes

This module provides the base scene structure.

This module provides the classes for describing a tree structure with rendering and picking API. All nodes inherit from Base. Nodes with children are provided with PrivateGroup and Group classes. Leaf rendering nodes should inherit from Elem.

class Base[source]

A scene node with common features.

visible

Visibility flag of the node

pickable

True to make node pickable

parent

Parent or None if no parent

path

Tuple of scene nodes, from the tip of the tree down to this node.

If this tree is attached to a Viewport, then the Viewport is the first element of path.

viewport

The viewport this node is attached to or None.

objectToNDCTransform

Transform from object to normalized device coordinates.

Do not forget perspective divide.

objectToSceneTransform

Transform from object to scene.

Combine transforms up to the Viewport (not including it).

transforms

List of transforms defining the frame of this node relative to its parent.

bounds(transformed=False, dataBounds=False)[source]

Returns the bounds of this node aligned with the axis, with or without transform applied.

Parameters:
  • transformed (bool) – False to give bounds in object coordinates (the default), True to apply this object’s transforms.
  • dataBounds (bool) – False to give bounds of vertices (the default), True to give bounds of the represented data.
Returns:

The bounds: ((xMin, yMin, zMin), (xMax, yMax, zMax)) or None if no bounds.

Return type:

numpy.ndarray of float

prepareGL2(ctx)[source]

Called before the rendering to prepare OpenGL resources.

Override in subclass.

renderGL2(ctx)[source]

Called to perform the OpenGL rendering.

Override in subclass.

render(ctx)[source]

Called internally to perform rendering.

postRender(ctx)[source]

Hook called when parent’s node render is finished.

Called in the reverse of rendering order (i.e., last child first).

Meant for nodes that modify the RenderContext ctx to reset their modifications.

pick(ctx, x, y, depth=None)[source]

True/False picking, should be fast

pickRay(ctx, ray)[source]

Picking returning list of ray intersections.

class Elem[source]

A scene node that does some rendering.

class PrivateGroup(children=())[source]

A scene node that renders its (private) childern.

Parameters:children (iterable) – Base nodes to add as children
class ChildrenList(parent, children)[source]

List of children with notification and children’s parent update.

renderGL2(ctx)[source]

Render all children

class Group(children=())[source]

A scene node that renders its (public) children.

children

List of children to be rendered.

cutplane: Cutting plane primitive

A cut plane in a 3D texture: hackish implementation…

class ColormapMesh3D(position, normal, data, copy=True, mode=u'triangles', indices=None, colormap=None)[source]

A 3D mesh with color from a 3D texture.

textureOffset = None

Offset to add to texture coordinates

interpolation

The texture interpolation mode: ‘linear’ or ‘nearest’

alpha

Transparency of the plane, float in [0, 1]

colormap

The colormap used by this primitive

class CutPlane(point=(0.0, 0.0, 0.0), normal=(0.0, 0.0, 1.0))[source]

A cutting plane in a 3D texture

interpolation

The texture interpolation mode: ‘linear’ (default) or ‘nearest’

contourVertices

The vertices of the contour of the plane/bounds intersection.

event: Scene event system

This module provides a simple generic notification system.

class Notifier[source]

Base class for object with notification mechanism.

addListener(listener)[source]

Register a listener.

Adding an already registered listener has no effect.

Parameters:listener (callable) – The function or method to register.
removeListener(listener)[source]

Remove a previously registered listener.

Parameters:listener (callable) – The function or method to unregister.
notify(*args, **kwargs)[source]

Notify all registered listeners with the given parameters.

Listeners are called directly in this method. Listeners are called in the order they were registered.

notifyProperty(attrName, copy=False, converter=None, doc=None)[source]

Create a property that adds notification to an attribute.

Parameters:
  • attrName (str) – The name of the attribute to wrap.
  • copy (bool) – Whether to return a copy of the attribute or not (the default).
  • converter – Function converting input value to appropriate type This function takes a single argument and return the converted value. It can be used to perform some asserts.
  • doc (str) – The docstring of the property
Returns:

A property with getter and setter

class HookList(iterable)[source]

List with hooks before and after modification.

append(*args, **kwargs)[source]

L.append(object) – append object to end

extend(*args, **kwargs)[source]

L.extend(iterable) – extend list by appending elements from the iterable

insert(*args, **kwargs)[source]

L.insert(index, object) – insert object before index

remove(*args, **kwargs)[source]

L.remove(value) – remove first occurrence of value. Raises ValueError if the value is not present.

pop([index]) → item -- remove and return item at index (default last).[source]

Raises IndexError if list is empty or index is out of range.

sort(*args, **kwargs)[source]

L.sort(cmp=None, key=None, reverse=False) – stable sort IN PLACE; cmp(x, y) -> -1, 0, 1

reverse(*args, **kwargs)[source]

L.reverse() – reverse IN PLACE

class NotifierList(iterable=())[source]

List of Notifiers with notification mechanism.

This class registers itself as a listener of the list items.

The default listener method forward notification from list items to the listeners of the list.

function: OpenGL shader functions

This module provides functions to add to shaders.

class ProgramFunction[source]

Class providing a function to add to a GLProgram shaders.

setupProgram(context, program)[source]

Sets-up uniforms of a program using this shader function.

Parameters:
  • context (RenderContext) – The current rendering context
  • program (GLProgram) – The program to set-up. It MUST be in use and using this function.
class ClippingPlane(point=(0.0, 0.0, 0.0), normal=(0.0, 0.0, 0.0))[source]

Description of a clipping plane and rendering.

Convention: Clipping is performed in camera/eye space.

Parameters:
  • point (numpy.ndarray-like of 3 float32) – Local coordinates of a point on the plane.
  • normal (numpy.ndarray-like of 3 float32) – Local coordinates of the plane normal.
plane

Plane parameters in camera space.

setupProgram(context, program)[source]

Sets-up uniforms of a program using this shader function.

Parameters:
  • context (RenderContext) – The current rendering context
  • program (GLProgram) – The program to set-up. It MUST be in use and using this function.
class DirectionalLight(direction=None, ambient=(1.0, 1.0, 1.0), diffuse=(0.0, 0.0, 0.0), specular=(1.0, 1.0, 1.0), shininess=0)[source]

Description of a directional Phong light.

Parameters:
  • direction (ndarray of 3 floats or None) – The direction of the light or None to disable light
  • ambient (ndarray of 3 floats in [0, 1], default: (1., 1., 1.)) – RGB ambient light
  • diffuse (ndarray of 3 floats in [0, 1], default: (0., 0., 0.)) – RGB diffuse light parameter
  • specular (ndarray of 3 floats in [0, 1], default: (1., 1., 1.)) – RGB specular light parameter
  • shininess (int) – The shininess of the material for specular term, default: 0 which disables specular component.
isOn

True if light is on, False otherwise.

turnOff(**kwds)[source]

Context manager to temporary turn off lighting during rendering.

>>> with light.turnOff():
...     # Do some rendering without lighting
direction

The direction of the light, or None if light is not on.

fragmentDef

Definition to add to fragment shader

fragmentCall

Function name to call in fragment shader

setupProgram(context, program)[source]

Sets-up uniforms of a program using this shader function.

Parameters:
  • context (RenderContext) – The current rendering context
  • program (GLProgram) – The program to set-up. It MUST be in use and using this function.

interaction: User interaction implementation

This module provides interaction to plug on the scene graph.

class ClickOrDrag(button='left')[source]

Click or drag interaction for a given button.

class Idle(machine)[source]
class ClickOrDrag(machine)[source]
enterState(x, y)[source]

Called when the state machine enters this state.

Arguments are those provided to the goto() method that triggered the transition to this state.

enter(x, y)

Called when the state machine enters this state.

Arguments are those provided to the goto() method that triggered the transition to this state.

class Drag(machine)[source]
enterState(initPos, curPos)[source]

Called when the state machine enters this state.

Arguments are those provided to the goto() method that triggered the transition to this state.

enter(initPos, curPos)

Called when the state machine enters this state.

Arguments are those provided to the goto() method that triggered the transition to this state.

click(x, y)[source]

Called upon a left or right button click. To override in a subclass.

beginDrag(x, y)[source]

Called at the beginning of a drag gesture with left button pressed. To override in a subclass.

drag(x, y)[source]

Called on mouse moved during a drag gesture. To override in a subclass.

endDrag(x, y)[source]

Called at the end of a drag gesture when the left button is released. To override in a subclass.

class CameraRotate(viewport, orbitAroundCenter=True, button='right')[source]

Camera rotation using an arcball-like interaction.

click(x, y)[source]

Called upon a left or right button click. To override in a subclass.

beginDrag(x, y)[source]

Called at the beginning of a drag gesture with left button pressed. To override in a subclass.

drag(x, y)[source]

Called on mouse moved during a drag gesture. To override in a subclass.

endDrag(x, y)[source]

Called at the end of a drag gesture when the left button is released. To override in a subclass.

class CameraSelectPan(viewport, button='left', selectCB=None)[source]

Picking on click and pan camera on drag.

click(x, y)[source]

Called upon a left or right button click. To override in a subclass.

beginDrag(x, y)[source]

Called at the beginning of a drag gesture with left button pressed. To override in a subclass.

drag(x, y)[source]

Called on mouse moved during a drag gesture. To override in a subclass.

endDrag(x, y)[source]

Called at the end of a drag gesture when the left button is released. To override in a subclass.

class CameraWheel(viewport, mode='center', scaleTransform=None)[source]

StateMachine like class, just handling wheel events.

class FocusManager(eventHandlers=(), ctrlEventHandlers=None)[source]

Manages focus across multiple event handlers

On press an event handler can acquire focus. By default it looses focus when all buttons are released.

class Idle(machine)[source]
class Focus(machine)[source]
enterState(eventHandler, btn)[source]

Called when the state machine enters this state.

Arguments are those provided to the goto() method that triggered the transition to this state.

enter(eventHandler, btn)

Called when the state machine enters this state.

Arguments are those provided to the goto() method that triggered the transition to this state.

class RotateCameraControl(viewport, orbitAroundCenter=False, mode='center', scaleTransform=None, selectCB=None)[source]

Combine wheel and rotate state machine for left button and pan when ctrl is pressed

class PanCameraControl(viewport, orbitAroundCenter=False, mode='center', scaleTransform=None, selectCB=None)[source]

Combine wheel, selectPan and rotate state machine for left button and rotate when ctrl is pressed

class CameraControl(viewport, orbitAroundCenter=False, mode='center', scaleTransform=None, selectCB=None)[source]

Combine wheel, selectPan and rotate state machine.

class PlaneRotate(viewport, plane, button='right')[source]

Plane rotation using arcball interaction.

Arcball ref.: Ken Shoemake. ARCBALL: A user interface for specifying three-dimensional orientation using a mouse. In Proc. GI ‘92. (1992). pp. 151-156.

click(x, y)[source]

Called upon a left or right button click. To override in a subclass.

beginDrag(x, y)[source]

Called at the beginning of a drag gesture with left button pressed. To override in a subclass.

drag(x, y)[source]

Called on mouse moved during a drag gesture. To override in a subclass.

endDrag(x, y)[source]

Called at the end of a drag gesture when the left button is released. To override in a subclass.

class PlanePan(viewport, plane, button='left')[source]

Pan a plane along its normal on drag.

click(x, y)[source]

Called upon a left or right button click. To override in a subclass.

beginDrag(x, y)[source]

Called at the beginning of a drag gesture with left button pressed. To override in a subclass.

drag(x, y)[source]

Called on mouse moved during a drag gesture. To override in a subclass.

endDrag(x, y)[source]

Called at the end of a drag gesture when the left button is released. To override in a subclass.

class PlaneControl(viewport, plane, mode='center', scaleTransform=None)[source]

Combine wheel, selectPan and rotate state machine for plane control.

class PanPlaneRotateCameraControl(viewport, plane, mode='center', scaleTransform=None)[source]

Combine wheel, pan plane and camera rotate state machine.

class PanPlaneZoomOnWheelControl(viewport, plane, mode='center', orbitAroundCenter=False, scaleTransform=None)[source]

Combine zoom on wheel and pan plane state machines.

primitives: Base rendering primitives

class Geometry(mode, indices=None, copy=True, attrib0=u'position', **attributes)[source]

Set of vertices with normals and colors.

Parameters:
  • mode (str) – OpenGL drawing mode: lines, line_strip, loop, triangles, triangle_strip, fan
  • indices – Array of vertex indices or None
  • copy (bool) – True (default) to copy the data, False to use as is.
  • attrib0 (str) – Name of the attribute that MUST be an array.
  • attributes – Provide list of attributes as extra parameters.
drawMode

Kind of primitive to render, in _MODES (str)

nbVertices

Returns the number of vertices of current attributes.

It returns None if there is no attributes.

attrib0

Attribute name that MUST be an array (str)

setAttribute(name, array, copy=True)[source]

Set attribute with provided array.

Parameters:
  • name (str) – The name of the attribute
  • array – Array-like attribute data or None to remove attribute
  • copy (bool) – True (default) to copy the data, False to use as is
getAttribute(name, copy=True)[source]

Returns the numpy.ndarray corresponding to the name attribute.

Parameters:
  • name (str) – The name of the attribute to get.
  • copy (bool) – True to get a copy (default), False to get internal array (DO NOT MODIFY)
Returns:

The corresponding array or None if no corresponding attribute.

Return type:

numpy.ndarray

useAttribute(program, name=None)[source]

Enable and bind attribute(s) for a specific program.

This MUST be called with OpenGL context active and after prepareGL2 has been called.

Parameters:
  • program (GLProgram) – The program for which to set the attributes
  • name (str) – The attribute name to set or None to set then all
setIndices(indices, copy=True)[source]

Set the primitive indices to use.

Parameters:
  • indices – Array-like of uint primitive indices or None to unset
  • copy (bool) – True (default) to copy the data, False to use as is
getIndices(copy=True)[source]

Returns the numpy.ndarray corresponding to the indices.

Parameters:copy (bool) – True to get a copy (default), False to get internal array (DO NOT MODIFY)
Returns:The primitive indices array or None if not set.
Return type:numpy.ndarray or None
boundsAttributeNames

Tuple of attribute names defining the bounds of the object.

Attributes name are taken in the given order to compute the (x, y, z) the bounding box, e.g.:

geometry.boundsAttributeNames = 'position'
geometry.boundsAttributeNames = 'x', 'y', 'z'
class Lines(positions, normals=None, colors=(1.0, 1.0, 1.0, 1.0), indices=None, mode=u'lines', width=1.0)[source]

A set of segments

width

Width of the line in pixels.

smooth

Smooth line rendering enabled (bool, default: True)

class DashedLines(positions, colors=(1.0, 1.0, 1.0, 1.0), indices=None, width=1.0)[source]

Set of dashed lines

This MUST be defined as a set of lines (no strip or loop).

dash

Dash of the line as a 2-tuple of lengths in pixels: (on, off)

getPositions(copy=True)[source]

Get coordinates of lines.

Parameters:copy (bool) – True to get a copy, False otherwise
Returns:Coordinates of lines
Return type:numpy.ndarray of float32 of shape (N, 2, Ndim)
setPositions(positions, copy=True)[source]

Set line coordinates.

Parameters:
  • positions – Array of line coordinates
  • copy (bool) – True to copy input array, False to use as is
class Box(stroke=(1.0, 1.0, 1.0, 1.0), fill=(1.0, 1.0, 1.0, 0.0))[source]

Rectangular box

classmethod getLineIndices(copy=True)[source]

Returns 2D array of Box lines indices

Parameters:copy – True (default) to get a copy, False to get internal array (Do not modify!)
Return type:numpy.ndarray
classmethod getVertices(copy=True)[source]

Returns 2D array of Box corner coordinates.

Parameters:copy – True (default) to get a copy, False to get internal array (Do not modify!)
Return type:numpy.ndarray
size

Size of the box (sx, sy, sz)

strokeSmooth

True to draw smooth stroke, False otherwise

strokeWidth

Width of the stroke (float)

strokeColor

RGBA color of the box lines (4-tuple of float in [0, 1])

fillColor

RGBA color of the box faces (4-tuple of float in [0, 1])

class Axes[source]

3D RGB orthogonal axes

size

Size of the axes (sx, sy, sz)

class BoxWithAxes(color=(1.0, 1.0, 1.0, 1.0))[source]

Rectangular box with RGB OX, OY, OZ axes

Parameters:color – RGBA color of the box
color

The RGBA color to use for the box: 4 float in [0, 1]

size

Size of the axes (sx, sy, sz)

class PlaneInGroup(point=(0.0, 0.0, 0.0), normal=(0.0, 0.0, 1.0))[source]

A plane using its parent bounds to display a contour.

If plane is outside the bounds of its parent, it is not visible.

Cannot set the transform attribute of this primitive. This primitive never has any bounds.

moveToCenter()[source]

Place the plane at the center of the data, not changing orientation.

color

Plane outline color (array of 4 float in [0, 1]).

width

Width of the plane stroke in pixels

strokeVisible

Whether surrounding stroke is visible or not (bool).

plane

The plane parameters in the frame of the object.

contourVertices

The vertices of the contour of the plane/bounds intersection.

center

The center of the plane/bounds intersection points.

isValid

True if a contour is defined, False otherwise.

class BoundedGroup(children=())[source]

Group with data bounds

shape

Data shape (depth, height, width) of this group or None

size

Data size (width, height, depth) of this group or None

class Points(x, y, z, value=0.0, size=1.0, indices=None, colormap=None)[source]

A set of data points with an associated value and size.

colormap

The colormap used to render the image

class ColorPoints(x, y, z, color=(1.0, 1.0, 1.0, 1.0), size=1.0, indices=None)[source]

A set of points with an associated color and size.

setColor(color, copy=True)[source]

Set colors

Parameters:
  • color – Single RGBA color or 2D array of color of length number of points
  • copy (bool) – True to copy colors (default), False to use provided array (Do not modify!)
getColor(copy=True)[source]

Returns the color or array of colors of the points.

Parameters:copy – True to get a copy (default), False to return internal array (Do not modify!)
Returns:Color or array of colors
Return type:numpy.ndarray
class GridPoints(values=0.0, shape=None, sizes=1.0, indices=None, minValue=None, maxValue=None)[source]

Data points on a regular grid with an associated value and size.

class Spheres(positions, radius=1.0, colors=(1.0, 1.0, 1.0, 1.0))[source]

A set of spheres.

Spheres are rendered as circles using points. This brings some limitations: - Do not support non-uniform scaling. - Assume the projection keeps ratio. - Do not render distorion by perspective projection. - If the sphere center is clipped, the whole sphere is not displayed.

class Mesh3D(positions, colors, normals=None, mode=u'triangles', indices=None, copy=True)[source]

A conventional 3D mesh

culling

Face culling (str)

One of ‘back’, ‘front’ or None.

class ColormapMesh3D(position, value, colormap=None, normal=None, mode=u'triangles', indices=None, copy=True)[source]

A 3D mesh with color computed from a colormap

lineWidth

Width of the line in pixels.

lineSmooth

Smooth line rendering enabled (bool, default: True)

culling

Face culling (str)

One of ‘back’, ‘front’ or None.

colormap

The colormap used to render the image

class ImageData(data, copy=True, colormap=None)[source]

Display a 2x2 data array with a texture.

colormap

The colormap used to render the image

class ImageRgba(data, copy=True)[source]

Display a 2x2 RGBA image with a texture.

Supports images of float in [0, 1] and uint8.

class GroupDepthOffset(children=(), epsilon=None)[source]

A group using 2-pass rendering and glDepthRange to avoid Z-fighting

class GroupNoDepth(children=(), mask=True, notest=True)[source]

A group rendering its children without writing to the depth buffer

Parameters:
  • mask (bool) – True (default) to disable writing in the depth buffer
  • notest (bool) – True (default) to disable depth test
class GroupBBox(children=(), color=(1.0, 1.0, 1.0, 1.0))[source]

A group displaying a bounding box around the children.

color

The RGBA color to use for the box: 4 float in [0, 1]

strokeWidth

The width of the stroke lines in pixels (float)

axesVisible

Whether axes are displayed or not (bool)

boxVisible

Whether bounding box is displayed or not (bool)

class ClipPlane(point=(0.0, 0.0, 0.0), normal=(0.0, 0.0, 1.0))[source]

A clipping plane attached to a box

text: Text field rendering primitives

Primitive displaying a text field in the scene.

class Font(name=None, size=-1, weight=-1, italic=False)[source]

Description of a font.

Parameters:
  • name (str) – Family of the font
  • size (int) – Size of the font in points
  • weight (int) – Font weight
  • italic (bool) – True for italic font, False (default) otherwise
name

Name of the font (str)

size

Font size in points (int)

weight

Font size in points (int)

italic

True for italic (bool)

class Text2D(text=u'', font=None)[source]

Text field as a 2D texture displayed with bill-boarding

Parameters:
  • text (str) – Text to display
  • font (Font) – The font to use
text

Text displayed by this primitive (str)

font

Font to use to raster text (Font)

foreground

RGBA color of the text: 4 float in [0, 1]

background

RGBA background color of the text field: 4 float in [0, 1]

overlay

True to always display text on top of the scene (default: False)

align

Horizontal anchor position of the text field (str).

Either ‘left’ (default), ‘center’ or ‘right’.

valign

Vertical anchor position of the text field (str).

Either ‘top’, ‘baseline’ (default), ‘center’ or ‘bottom’

class LabelledAxes[source]

A group displaying a bounding box with axes labels around its children.

font

Font of axes text labels (Font)

xlabel

Text label of the X axis (str)

ylabel

Text label of the Y axis (str)

zlabel

Text label of the Z axis (str)

transform: Transformation matrix system

This module provides 4x4 matrix operation and classes to handle them.

mat4LookAtDir(position, direction, up)[source]

Creates matrix to look in direction from position.

Parameters:
  • position – Array-like 3 coordinates of the point of view position.
  • direction – Array-like 3 coordinates of the sight direction vector.
  • up – Array-like 3 coordinates of the upward direction in the image plane.
Returns:

Corresponding matrix.

Return type:

numpy.ndarray of shape (4, 4)

mat4LookAt(position, center, up)[source]

Creates matrix to look at center from position.

See gluLookAt.

Parameters:
  • position – Array-like 3 coordinates of the point of view position.
  • center – Array-like 3 coordinates of the center of the scene.
  • up – Array-like 3 coordinates of the upward direction in the image plane.
Returns:

Corresponding matrix.

Return type:

numpy.ndarray of shape (4, 4)

mat4Frustum(left, right, bottom, top, near, far)[source]

Creates a frustum projection matrix.

See glFrustum.

mat4Perspective(fovy, width, height, near, far)[source]

Creates a perspective projection matrix.

Similar to gluPerspective.

Parameters:
  • fovy (float) – Field of view angle in degrees in the y direction.
  • width (float) – Width of the viewport.
  • height (float) – Height of the viewport.
  • near (float) – Distance to the near plane (strictly positive).
  • far (float) – Distance to the far plane (strictly positive).
Returns:

Corresponding matrix.

Return type:

numpy.ndarray of shape (4, 4)

mat4Orthographic(left, right, bottom, top, near, far)[source]

Creates an orthographic (i.e., parallel) projection matrix.

See glOrtho.

mat4Translate(tx, ty, tz)[source]

4x4 translation matrix.

mat4Scale(sx, sy, sz)[source]

4x4 scale matrix.

mat4RotateFromAngleAxis(angle, x=0.0, y=0.0, z=1.0)[source]

4x4 rotation matrix from angle and axis.

Parameters:
  • angle (float) – The rotation angle in radians.
  • x (float) – The rotation vector x coordinate.
  • y (float) – The rotation vector y coordinate.
  • z (float) – The rotation vector z coordinate.
mat4RotateFromQuaternion(quaternion)[source]

4x4 rotation matrix from quaternion.

Parameters:quaternion – Array-like unit quaternion stored as (x, y, z, w)
mat4Shear(axis, sx=0.0, sy=0.0, sz=0.0)[source]

4x4 shear matrix: Skew two axes relative to a third fixed one.

shearFactor = tan(shearAngle)

Parameters:
  • axis (str) – The axis to keep constant and shear against. In ‘x’, ‘y’, ‘z’.
  • sx (float) – The shear factor for the X axis relative to axis.
  • sy (float) – The shear factor for the Y axis relative to axis.
  • sz (float) – The shear factor for the Z axis relative to axis.
class Inverse(transform)[source]

Transform which is the inverse of another one.

Static: It never gets updated.

class TransformList(iterable=())[source]

List of transforms.

class StaticTransformList(iterable=())[source]

Transform that is a snapshot of a list of Transforms

It does not keep reference to the list of Transforms.

Parameters:iterable – Iterable of Transform used for initialization
class Translate(tx=0.0, ty=0.0, tz=0.0)[source]

4x4 translation matrix.

class Scale(sx=1.0, sy=1.0, sz=1.0)[source]

4x4 scale matrix.

class Orthographic(left=0.0, right=1.0, bottom=1.0, top=0.0, near=-1.0, far=1.0, size=(1.0, 1.0))[source]

Orthographic (i.e., parallel) projection which keeps aspect ratio.

Clipping planes are adjusted to match the aspect ratio of the size attribute.

The left, right, bottom and top parameters defines the area which must always remain visible. Effective clipping planes are adjusted to keep the aspect ratio.

Parameters:
  • left (float) – Coord of the left clipping plane.
  • right (float) – Coord of the right clipping plane.
  • bottom (float) – Coord of the bottom clipping plane.
  • top (float) – Coord of the top clipping plane.
  • near (float) – Distance to the near plane.
  • far (float) – Distance to the far plane.
  • size (2-tuple of float) – Viewport’s size used to compute the aspect ratio (width, height).
setClipping(left=None, right=None, bottom=None, top=None)[source]

Set the clipping planes of the projection.

Parameters are adjusted to keep aspect ratio. If a clipping plane coord is not provided, it uses its current value

Parameters:
  • left (float) – Coord of the left clipping plane.
  • right (float) – Coord of the right clipping plane.
  • bottom (float) – Coord of the bottom clipping plane.
  • top (float) – Coord of the top clipping plane.
left

Coord of the left clipping plane.

right

Coord of the right clipping plane.

bottom

Coord of the bottom clipping plane.

top

Coord of the top clipping plane.

size

Viewport size as a 2-tuple of float (width, height) or None.

class Ortho2DWidget(near=-1.0, far=1.0, size=(1.0, 1.0))[source]

Orthographic projection with pixel as unit.

Provides same coordinates as widgets: origin: top left, X axis goes left, Y axis goes down.

Parameters:
  • near (float) – Z coordinate of the near clipping plane.
  • far (float) – Z coordinante of the far clipping plane.
  • size (2-tuple of float) – Viewport’s size used to compute the aspect ratio (width, height).
class Perspective(fovy=90.0, near=0.1, far=1.0, size=(1.0, 1.0))[source]

Perspective projection matrix defined by FOV and aspect ratio.

Parameters:
  • fovy (float) – Vertical field-of-view in degrees.
  • near (float) – The near clipping plane Z coord (stricly positive).
  • far (float) – The far clipping plane Z coord (> near).
  • size (2-tuple of float) – Viewport’s size used to compute the aspect ratio (width, height).
fovy

Vertical field-of-view in degrees.

utils: Miscellaneous

This module provides functions to generate indices, to check intersection and to handle planes.

triangleToLineIndices(triangleIndices, unicity=False)[source]

Generates lines indices from triangle indices.

This is generating lines indices for the edges of the triangles.

Parameters:
  • triangleIndices (numpy.ndarray) – The indices to draw a set of vertices as triangles.
  • unicity (bool) – If True remove duplicated lines, else (the default) returns all lines.
Returns:

The indices to draw the edges of the triangles as lines.

Return type:

1D numpy.ndarray of uint16 or uint32.

verticesNormalsToLines(vertices, normals, scale=1.0)[source]

Return vertices of lines representing normals at given positions.

Parameters:
  • vertices (numpy.ndarray with shape: (nbPoints, 3)) – Positions of the points.
  • normals (numpy.ndarray with shape: (nbPoints, 3)) – Corresponding normals at the points.
  • scale (float) – The scale factor to apply to normals.
Returns:

Array of vertices to draw corresponding lines.

Return type:

numpy.ndarray with shape: (nbPoints * 2, 3)

unindexArrays(mode, indices, *arrays)[source]

Convert indexed GL primitives to unindexed ones.

Given indices in arrays and the OpenGL primitive they represent, return the unindexed equivalent.

Parameters:
  • mode (str) – Kind of primitive represented by indices. In: points, lines, line_strip, loop, triangles, triangle_strip, fan.
  • indices (numpy.ndarray of dimension 1.) – Indices in other arrays
  • arrays – Remaining arguments are arrays to convert
Returns:

Converted arrays

Return type:

tuple of numpy.ndarray

triangleStripToTriangles(strip)[source]

Convert a triangle strip to a set of triangles.

The order of the corners is inverted for odd triangles.

Parameters:strip (numpy.ndarray) – Array of triangle corners of shape (N, 3). N must be at least 3.
Returns:Equivalent triangles corner as an array of shape (N, 3, 3)
Return type:numpy.ndarray
trianglesNormal(positions)[source]

Return normal for each triangle.

Parameters:positions (numpy.ndarray of shape (NbTriangles*3, 3)) – Serie of triangle’s corners
Returns:Normals corresponding to each position.
Return type:numpy.ndarray of shape (NbTriangles, 3)
gridVertices(dim0Array, dim1Array, dtype)[source]

Generate an array of 2D positions from 2 arrays of 1D coordinates.

Parameters:
  • dim0Array – 1D array-like of coordinates along the first dimension.
  • dim1Array – 1D array-like of coordinates along the second dimension.
  • dtype (numpy.dtype) – Data type of the output array.
Returns:

Array of grid coordinates.

Return type:

numpy.ndarray with shape: (len(dim0Array), len(dim1Array), 2)

triangleStripGridIndices(dim0, dim1)[source]

Generate indices to draw a grid of vertices as a triangle strip.

Vertices are expected to be stored as row-major (i.e., C contiguous).

Parameters:
  • dim0 (int) – The number of rows of vertices.
  • dim1 (int) – The number of columns of vertices.
Returns:

The vertex indices

Return type:

1D numpy.ndarray of uint32

linesGridIndices(dim0, dim1)[source]

Generate indices to draw a grid of vertices as lines.

Vertices are expected to be stored as row-major (i.e., C contiguous).

Parameters:
  • dim0 (int) – The number of rows of vertices.
  • dim1 (int) – The number of columns of vertices.
Returns:

The vertex indices.

Return type:

1D numpy.ndarray of uint32

angleBetweenVectors(refVector, vectors, norm=None)[source]

Return the angle between 2 vectors.

Parameters:
  • refVector (numpy.ndarray of shape: (NCoords,)) – Coordinates of the reference vector.
  • vectors (numpy.ndarray of shape: (NCoords,) or (NbVector, NCoords)) – Coordinates of the vector(s) to get angle from reference.
  • norm – A direction vector giving an orientation to the angles or None.
Returns:

The angles in radians in [0, pi] if norm is None else in [0, 2pi].

Return type:

float or numpy.ndarray of shape (NbVectors,)

segmentPlaneIntersect(s0, s1, planeNorm, planePt)[source]

Compute the intersection of a segment with a plane.

Parameters:
  • s0 (1D numpy.ndarray-like of length 3) – First end of the segment
  • s1 (1D numpy.ndarray-like of length 3) – Second end of the segment
  • planeNorm (numpy.ndarray of shape: (3,)) – Normal vector of the plane.
  • planePt (numpy.ndarray of shape: (3,)) – A point of the plane.
Returns:

The intersection points. The number of points goes from 0 (no intersection) to 2 (segment in the plane)

Return type:

list of numpy.ndarray

boxPlaneIntersect(boxVertices, boxLineIndices, planeNorm, planePt)[source]

Return intersection points between a box and a plane.

Parameters:
  • boxVertices (numpy.ndarray with shape: (8, 3)) – Position of the corners of the box.
  • boxLineIndices (numpy.ndarray-like with shape: (12, 2)) – Indices of the box edges.
  • planeNorm (numpy.ndarray of shape: (3,)) – Normal vector of the plane.
  • planePt (numpy.ndarray of shape: (3,)) – A point of the plane.
Returns:

The found intersection points

Return type:

numpy.ndarray with 2 dimensions

clipSegmentToBounds(segment, bounds)[source]

Clip segment to volume aligned with axes.

Parameters:
  • segment (numpy.ndarray) – (p0, p1)
  • bounds (numpy.ndarray) – (lower corner, upper corner)
Returns:

Either clipped (p0, p1) or None if outside volume

Return type:

Union[None,List[numpy.ndarray]]

segmentVolumeIntersect(segment, nbins)[source]

Get bin indices intersecting with segment

It should work with N dimensions. Coordinate convention (z, y, x) or (x, y, z) should not matter as long as segment and nbins are consistent.

Parameters:
  • segment (numpy.ndarray) – Segment end points as a 2xN array of coordinates
  • nbins (numpy.ndarray) – Shape of the volume with same coordinates order as segment
Returns:

List of bins indices as a 2D array or None if no bins

Return type:

Union[None,numpy.ndarray]

segmentTrianglesIntersection(segment, triangles)[source]

Check for segment/triangles intersection.

This is based on signed tetrahedron volume comparison.

See A. Kensler, A., Shirley, P. Optimizing Ray-Triangle Intersection via Automated Search. Symposium on Interactive Ray Tracing, vol. 0, p33-38 (2006)

Parameters:
  • segment (numpy.ndarray) – Segment end points as a 2x3 array of coordinates
  • triangles (numpy.ndarray) – Nx3x3 array of triangles
Returns:

(triangle indices, segment parameter, barycentric coord) Indices of intersected triangles, “depth” along the segment of the intersection point and barycentric coordinates of intersection point in the triangle.

Return type:

List[numpy.ndarray]

class Plane(point=(0.0, 0.0, 0.0), normal=(0.0, 0.0, 1.0))[source]

Object handling a plane and notifying plane changes.

Parameters:
  • point (3-tuple of float.) – A point on the plane.
  • normal (3-tuple of float.) – Normal of the plane.
setPlane(point=None, normal=None)[source]

Set plane point and normal and notify.

Parameters:
  • point (3-tuple of float or None.) – A point on the plane.
  • normal (3-tuple of float or None.) – Normal of the plane.
point

A point on the plane.

normal

The (normalized) normal of the plane.

parameters

Plane equation parameters: a*x + b*y + c*z + d = 0.

isPlane

True if a plane is defined (i.e., ||normal|| != 0).

move(step)[source]

Move the plane of step along the normal.

segmentIntersection(s0, s1)[source]

Compute the plane intersection with segment [s0, s1].

Parameters:
  • s0 (1D numpy.ndarray-like of length 3) – First end of the segment
  • s1 (1D numpy.ndarray-like of length 3) – Second end of the segment
Returns:

The intersection points. The number of points goes from 0 (no intersection) to 2 (segment in the plane)

Return type:

list of 1D numpy.ndarray

viewport: Root of a scene tree

This module provides a class to control a viewport on the rendering window.

The Viewport describes a Viewport rendering a scene. The attribute scene is the root group of the scene tree. RenderContext handles the current state during rendering.

class RenderContext(viewport, glContext)[source]

Handle a current rendering context.

An instance of this class is passed to rendering method through the scene during render.

User should NEVER use an instance of this class beyond the method it is passed to as an argument (i.e., do not keep a reference to it).

Parameters:
  • viewport (Viewport) – The viewport doing the rendering.
  • glContext (Context) – The operating system OpenGL context in use.
viewport

Viewport doing the current rendering

glCtx

The OpenGL context in use

objectToCamera

The current transform from object to camera coords.

Do not modify.

projection

Projection transform.

Do not modify.

objectToNDC

The transform from object to NDC (this includes projection).

Do not modify.

pushTransform(transform_, multiply=True)[source]

Push a Transform on the transform stack.

Parameters:
  • transform (Transform) – The transform to add to the stack.
  • multiply (bool) – True (the default) to multiply with the top of the stack, False to push the transform as is without multiplication.
popTransform()[source]

Pop the transform on top of the stack.

Returns:The Transform that is popped from the stack.
clipper

The current clipping plane

setClipPlane(point=(0.0, 0.0, 0.0), normal=(0.0, 0.0, 0.0))[source]

Set the clipping plane to use

For now only handles a single clipping plane.

Parameters:
  • point (3-tuple of float) – A point of the plane
  • normal (3-tuple of float) – Normal vector of the plane or (0, 0, 0) for no clipping
class Viewport(framebuffer=0)[source]

Rendering a single scene through a camera in part of a framebuffer.

Parameters:framebuffer (int) – The framebuffer ID this viewport is rendering into
transforms

Proxy of camera transforms.

Do not modify the list.

dirty

True if scene is dirty and needs redisplay.

resetDirty()[source]

Mark the scene as not being dirty.

To call after rendering.

background

Viewport’s background color (4-tuple of float in [0, 1] or None)

The background color is used to clear to viewport. If None, the viewport is not cleared

camera

The camera used to render the scene.

light

The light used to render the scene.

origin

Origin (ox, oy) of the viewport in pixels

size

Size (width, height) of the viewport in pixels

shape

Shape (height, width) of the viewport in pixels.

This is a convenient wrapper to the inverse of size.

framebuffer

The framebuffer ID this viewport is rendering into (int)

render(glContext)[source]

Perform the rendering of the viewport

Parameters:glContext (Context) – The context used for rendering
adjustCameraDepthExtent()[source]

Update camera depth extent to fit the scene bounds.

Only near and far planes are updated. The scene might still not be fully visible (e.g., if spanning behind the viewpoint with perspective projection).

resetCamera()[source]

Change camera to have the whole scene in the viewing frustum.

It updates the camera position and depth extent. Camera sight direction and up are not affected.

orbitCamera(direction, angle=1.0)[source]

Rotate the camera around center of the scene.

Parameters:
  • direction (str) – Direction of movement relative to image plane. In: ‘up’, ‘down’, ‘left’, ‘right’.
  • angle (float) – he angle in degrees of the rotation.
moveCamera(direction, step=0.1)[source]

Move the camera relative to the image plane.

Parameters:
  • direction (str) – Direction relative to image plane. One of: ‘up’, ‘down’, ‘left’, ‘right’, ‘forward’, ‘backward’.
  • step (float) – The ratio of data to step for each pan.
windowToNdc(winX, winY, checkInside=True)[source]

Convert position from window to normalized device coordinates.

If window coordinates are int, they are moved half a pixel to be positioned at the center of pixel.

Parameters:
  • winX – X window coord, origin left.
  • winY – Y window coord, origin top.
  • checkInside (bool) – If True, returns None if position is outside viewport.
Returns:

(x, y) Normalize device coordinates in [-1, 1] or None. Origin center, x to the right, y goes upward.

ndcToWindow(ndcX, ndcY, checkInside=True)[source]

Convert position from normalized device coordinates (NDC) to window.

Parameters:
  • ndcX (float) – X NDC coord.
  • ndcY (float) – Y NDC coord.
  • checkInside (bool) – If True, returns None if position is outside viewport.
Returns:

(x, y) window coordinates or None. Origin top-left, x to the right, y goes downward.

window: On-screen window

This module provides a class for Viewports rendering on the screen.

The Window renders a list of Viewports in the current framebuffer. The rendering can be performed in an off-screen framebuffer that is only updated when the scene has changed and not each time Qt is requiring a repaint.

The Context and ContextGL2 represent the operating system OpenGL context and handle OpenGL resources.

class Context(glContextHandle)[source]

Correspond to an operating system OpenGL context.

User should NEVER use an instance of this class beyond the method it is passed to as an argument (i.e., do not keep a reference to it).

Parameters:glContextHandle – System specific OpenGL context handle.
isCurrent

Whether this OpenGL context is the current one or not.

setCurrent(isCurrent=True)[source]

Set the state of the OpenGL context to reflect OpenGL state.

This should not be called from the scene graph, only in the wrapper that handle the OpenGL context to reflect its state.

Parameters:isCurrent (bool) – The state of the system OpenGL context.
devicePixelRatio

Ratio between device and device independent pixels (float)

This is useful for font rendering.

glContext

The handle to the OpenGL context provided by the system.

cleanGLGarbage()[source]

This is releasing OpenGL resource that are no longer used.

class ContextGL2(glContextHandle)[source]

Handle a system GL2 context.

User should NEVER use an instance of this class beyond the method it is passed to as an argument (i.e., do not keep a reference to it).

Parameters:glContextHandle – System specific OpenGL context handle.
prog(vertexShaderSrc, fragmentShaderSrc, attrib0=u'position')[source]

Cache program within context.

WARNING: No clean-up.

Parameters:
  • vertexShaderSrc (str) – Vertex shader source code
  • fragmentShaderSrc (str) – Fragment shader source code
  • attrib0 (str) – Attribute’s name to bind to position 0 (default: ‘position’). On some platform, this attribute MUST be active and with an array attached to it in order for the rendering to occur….
makeVbo(data=None, sizeInBytes=None, usage=None, target=None)[source]

Create a VBO in this context with the data.

Current limitations:

  • One array per VBO
  • Do not support sharing VertexBuffer across VboAttrib

Automatically discards the VBO when the returned VertexBuffer istance is deleted.

Parameters:
  • data (numpy.ndarray) – 2D array of data to store in VBO or None.
  • sizeInBytes (int) – Size of the VBO or None. It should be <= data.nbytes if both are given.
  • usage – OpenGL usage define in VertexBuffer._USAGES.
  • target – OpenGL target in VertexBuffer._TARGETS.
Returns:

The VertexBuffer created in this context.

makeVboAttrib(data, usage=None, target=None)[source]

Create a VBO from data and returns the associated VBOAttrib.

Automatically discards the VBO when the returned VBOAttrib istance is deleted.

Parameters:
  • data (numpy.ndarray) – 2D array of data to store in VBO or None.
  • usage – OpenGL usage define in VertexBuffer._USAGES.
  • target – OpenGL target in VertexBuffer._TARGETS.
Returns:

A VBOAttrib instance created in this context.

cleanGLGarbage()[source]

Delete OpenGL resources that are pending for destruction.

This requires the associated OpenGL context to be active. This is meant to be called before rendering.

class Window(mode=u'framebuffer')[source]

OpenGL Framebuffer where to render viewports

Parameters:mode (str) –

Rendering mode to use:

  • ’direct’ to render everything for each render call
  • ’framebuffer’ to cache viewport rendering in a texture and update the texture only when needed.
dirty

True if this object or any attached viewports is dirty.

size

Size (width, height) of the window in pixels

shape

Shape (height, width) of the window in pixels.

This is a convenient wrapper to the reverse of size.

viewports

List of viewports to render in the corresponding framebuffer

framebufferid

Framebuffer ID used to perform rendering

grab(glcontext)[source]

Returns the raster of the scene as an RGB numpy array

Returns:OpenGL scene RGB bitmap as an array of dimension (height, width, 3)
Return type:numpy.ndarray of uint8
render(glcontext, devicePixelRatio)[source]

Perform the rendering of attached viewports

Parameters:
  • glcontext – System identifier of the OpenGL context
  • devicePixelRatio (float) – Ratio between device and device-independent pixels