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.

property
tickColor
¶ Color of ticks and text labels.
This does NOT set bounding box color. Use
color
for the bounding box.

property
font
¶ Font of axes text labels (Font)

property
xlabel
¶ Text label of the X axis (str)

property
ylabel
¶ Text label of the Y axis (str)

property
zlabel
¶ Text label of the Z axis (str)

property
boxVisible
¶ Returns bounding box, axes labels and grid visibility.

property
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.ndarraylike of 3 float32.) – Coordinates of the point of view.
direction (numpy.ndarraylike of 3 float32.) – Sight direction vector.
up (numpy.ndarraylike of 3 float32.) – Vector pointing upward in the image plane.

setOrientation
(direction=None, up=None)[source]¶ Set the rotation of the point of view.
 Parameters
direction (numpy.ndarraylike of 3 float32 or None.) – Sight direction vector or None to keep the current one.
up (numpy.ndarraylike 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.

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

property
direction
¶ Sight direction (ndarray of 3 float32).

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

property
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]¶ Firstperson 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.ndarraylike of 3 float32.) – Position around which to rotate the point of view.
angle (float) – he angle in degrees of the rotation.

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
andCameraExtrinsic
. Parameters
fovy (float) – Vertical fieldofview in degrees.
near (float) – The near clipping plane Z coord (strictly positive).
far (float) – The far clipping plane Z coord (> near).
size (2tuple of float) – Viewport’s size used to compute the aspect ratio (width, height).
position (numpy.ndarraylike of 3 float32.) – Coordinates of the point of view.
direction (numpy.ndarraylike of 3 float32.) – Sight direction vector.
up (numpy.ndarraylike 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 axesaligned bounds to include.

property
intrinsic
¶ Intrinsic camera parameters, i.e., projection matrix.

property
extrinsic
¶ Extrinsic camera parameters, i.e., position and orientation.
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.

property
visible
¶ Visibility flag of the node

property
pickable
¶ True to make node pickable

property
parent
¶ Parent or None if no parent

property
path
¶ Tuple of scene nodes, from the tip of the tree down to this node.
If this tree is attached to a
Viewport
, then theViewport
is the first element of path.

property
viewport
¶ The viewport this node is attached to or None.

property
root
¶ The root node of the scene.
If attached to a
Viewport
, this is the item right under it

property
objectToNDCTransform
¶ Transform from object to normalized device coordinates.
Do not forget perspective divide.

property
objectToSceneTransform
¶ Transform from object to scene.
Combine transforms up to the Viewport (not including it).

property
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.

property

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.
cutplane
: Cutting plane primitive¶
A cut plane in a 3D texture: hackish implementation…

class
ColormapMesh3D
(position, normal, data, copy=True, mode='triangles', indices=None, colormap=None)[source]¶ A 3D mesh with color from a 3D texture.

textureOffset
¶ Offset to add to texture coordinates

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

property
alpha
¶ Transparency of the plane, float in [0, 1]

property
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

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

prepareGL2
(ctx)[source]¶ Called before the rendering to prepare OpenGL resources.
Override in subclass.

property
contourVertices
¶ The vertices of the contour of the plane/bounds intersection.

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

property
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.


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.

remove
(*args, **kwargs)[source]¶ Remove first occurrence of value.
Raises ValueError if the value is not present.

pop
(*args, **kwargs)[source]¶ Remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.

sort
(*args, **kwargs)[source]¶ Sort the list in ascending order and return None.
The sort is inplace (i.e. the list itself is modified) and stable (i.e. the order of two equal elements is maintained).
If a key function is given, apply it once to each list item and sort them, ascending or descending, according to their function values.
The reverse flag can be set to sort in descending order.

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]¶ Setsup uniforms of a program using this shader function.
 Parameters
context (RenderContext) – The current rendering context
program (GLProgram) – The program to setup. It MUST be in use and using this function.


class
Fog
[source]¶ Linear fog over the whole scene content.
The background of the viewport is used as fog color, otherwise it defaults to white.

property
isOn
¶ True to enable fog, False to disable (bool)

setupProgram
(context, program)[source]¶ Setsup uniforms of a program using this shader function.
 Parameters
context (RenderContext) – The current rendering context
program (GLProgram) – The program to setup. It MUST be in use and using this function.

property

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.ndarraylike of 3 float32) – Local coordinates of a point on the plane.
normal (numpy.ndarraylike of 3 float32) – Local coordinates of the plane normal.

property
plane
¶ Plane parameters in camera space.

setupProgram
(context, program)[source]¶ Setsup uniforms of a program using this shader function.
 Parameters
context (RenderContext) – The current rendering context
program (GLProgram) – The program to setup. 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.

property
isOn
¶ True if light is on, False otherwise.

turnOff
()[source]¶ Context manager to temporary turn off lighting during rendering.
>>> with light.turnOff(): ... # Do some rendering without lighting

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

property
fragmentDef
¶ Definition to add to fragment shader

property
fragmentCall
¶ Function name to call in fragment shader

setupProgram
(context, program)[source]¶ Setsup uniforms of a program using this shader function.
 Parameters
context (RenderContext) – The current rendering context
program (GLProgram) – The program to setup. It MUST be in use and using this function.

class
Colormap
(colormap=None, norm='linear', gamma=0.0, range_=(1.0, 10.0))[source]¶ 
NORMS
= ('linear', 'log', 'sqrt', 'gamma', 'arcsinh')¶ Tuple of supported normalizations.

property
decl
¶ Source code of the function declaration

property
colormap
¶ Color lookup table to use.

property
nancolor
¶ RGBA color to use for NotANumber values as 4 float in [0., 1.]

property
norm
¶ Normalization to use for colormap mapping.
One of ‘linear’ (the default), ‘log’ for log10 mapping or ‘sqrt’. Invalid values (e.g., negative values with ‘log’ or ‘sqrt’) are mapped to 0.

property
gamma
¶ Gamma correction normalization parameter (float >= 0.)

property
range_
¶ Range of values to map to the colormap.
2tuple of floats: (begin, end). The begin value is mapped to the origin of the colormap and the end value is mapped to the other end of the colormap. The colormap is reversed if begin > end.

property
displayValuesBelowMin
¶ True to display values below colormap min, False to discard them.

setupProgram
(context, program)[source]¶ Setsup uniforms of a program using this shader function.
 Parameters
context (RenderContext) – The current rendering context
program (GLProgram) – The program to setup. 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
ClickOrDrag
(machine)[source]¶

class
Drag
(machine)[source]¶

class

class
CameraSelectRotate
(viewport, orbitAroundCenter=True, button='right', selectCB=None)[source]¶ Camera rotation using an arcballlike interaction.

class
CameraSelectPan
(viewport, button='left', selectCB=None)[source]¶ Picking on click and pan camera on drag.

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
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 threedimensional orientation using a mouse. In Proc. GI ‘92. (1992). pp. 151156.

class
PlanePan
(viewport, plane, button='left')[source]¶ Pan a plane along its normal on drag.

class
PlaneControl
(viewport, plane, mode='center', scaleTransform=None)[source]¶ Combine wheel, selectPan and rotate state machine for plane control.
primitives
: Base rendering primitives¶

class
Geometry
(mode, indices=None, copy=True, attrib0='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.

property
drawMode
¶ Kind of primitive to render, in
_MODES
(str)

property
nbVertices
¶ Returns the number of vertices of current attributes.
It returns None if there is no attributes.

property
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 – Arraylike 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 – Arraylike 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

property
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='lines', width=1.0)[source]¶ A set of segments

property
width
¶ Width of the line in pixels.

property
smooth
¶ Smooth line rendering enabled (bool, default: True)

property

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).

property
dash
¶ Dash of the line as a 2tuple 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)

property

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

property
size
¶ Size of the box (sx, sy, sz)

property
strokeSmooth
¶ True to draw smooth stroke, False otherwise

property
strokeWidth
¶ Width of the stroke (float)

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

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

classmethod

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

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

property
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.

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

property
width
¶ Width of the plane stroke in pixels

property
strokeVisible
¶ Whether surrounding stroke is visible or not (bool).

property
plane
¶ The plane parameters in the frame of the object.

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

property
contourVertices
¶ The vertices of the contour of the plane/bounds intersection.

property
center
¶ The center of the plane/bounds intersection points.

property
isValid
¶ True if a contour is defined, False otherwise.

property

class
BoundedGroup
(children=())[source]¶ Group with data bounds

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

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

property

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.

property
colormap
¶ The colormap used to render the image

property

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.

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 nonuniform 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='triangles', indices=None, copy=True)[source]¶ A conventional 3D mesh

property
culling
¶ Face culling (str)
One of ‘back’, ‘front’ or None.

property

class
ColormapMesh3D
(position, value, colormap=None, normal=None, mode='triangles', indices=None, copy=True)[source]¶ A 3D mesh with color computed from a colormap

property
lineWidth
¶ Width of the line in pixels.

property
lineSmooth
¶ Smooth line rendering enabled (bool, default: True)

property
alpha
¶ Transparency of the mesh, float in [0, 1]

property
culling
¶ Face culling (str)
One of ‘back’, ‘front’ or None.

property
colormap
¶ The colormap used to render the image

property

class
ImageData
(data, copy=True, colormap=None)[source]¶ Display a 2x2 data array with a texture.

property
colormap
¶ The colormap used to render the image

property

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 2pass rendering and glDepthRange to avoid Zfighting

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.

prepareGL2
(ctx)[source]¶ Called before the rendering to prepare OpenGL resources.
Override in subclass.

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

property
strokeWidth
¶ The width of the stroke lines in pixels (float)

property
axesVisible
¶ Whether axes are displayed or not (bool)

property
boxVisible
¶ Whether bounding box is displayed or not (bool)

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

property
name
¶ Name of the font (str)

property
size
¶ Font size in points (int)

property
weight
¶ Font size in points (int)

property
italic
¶ True for italic (bool)

class
Text2D
(text='', font=None)[source]¶ Text field as a 2D texture displayed with billboarding
 Parameters
text (str) – Text to display
font (Font) – The font to use

property
text
¶ Text displayed by this primitive (str)

property
font
¶ Font to use to raster text (Font)

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

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

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

property
align
¶ Horizontal anchor position of the text field (str).
Either ‘left’ (default), ‘center’ or ‘right’.

property
valign
¶ Vertical anchor position of the text field (str).
Either ‘top’, ‘baseline’ (default), ‘center’ or ‘bottom’
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 – Arraylike 3 coordinates of the point of view position.
direction – Arraylike 3 coordinates of the sight direction vector.
up – Arraylike 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 – Arraylike 3 coordinates of the point of view position.
center – Arraylike 3 coordinates of the center of the scene.
up – Arraylike 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.

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 – Arraylike 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
Transform
(static=False)[source]¶ 
inverse
()[source]¶ Return the Transform of the inverse.
The returned Transform is static, it is not updated when this Transform is modified.
 Returns
A Transform which is the inverse of this Transform.

getMatrix
(copy=True)[source]¶ The 4x4 matrix of this transform.
 Parameters
copy (bool) – True (the default) to get a copy of the matrix, False to get the internal matrix, do not modify!
 Returns
4x4 matrix of this transform.

property
matrix
¶ The 4x4 matrix of this transform.

getInverseMatrix
(copy=False)[source]¶ The 4x4 matrix of the inverse of this transform.
 Parameters
copy (bool) – True (the default) to get a copy of the matrix, False to get the internal matrix, do not modify!
 Returns
4x4 matrix of the inverse of this transform.

property
inverseMatrix
¶ The 4x4 matrix of the inverse of this transform.

transformPoints
(points, direct=True, perspectiveDivide=False)[source]¶ Apply the transform to an array of points.
 Parameters
points – 2D array of N vectors of 3 or 4 coordinates
direct (bool) – Whether to apply the direct (True, the default) or inverse (False) transform.
perspectiveDivide (bool) – Whether to apply the perspective divide (True) or not (False, the default).
 Returns
The transformed points.
 Return type
numpy.ndarray of same shape as points.

transformPoint
(point, direct=True, perspectiveDivide=False)[source]¶ Apply the transform to a point.
 Parameters
point – Arraylike vector of 3 or 4 coordinates.
direct (bool) – Whether to apply the direct (True, the default) or inverse (False) transform.
perspectiveDivide (bool) – Whether to apply the perspective divide (True) or not (False, the default).
 Returns
The transformed point.
 Return type
numpy.ndarray of same length as point.

transformDir
(direction, direct=True)[source]¶ Apply the transform to a direction.
 Parameters
direction – Arraylike vector of 3 coordinates.
direct (bool) – Whether to apply the direct (True, the default) or inverse (False) transform.
 Returns
The transformed direction.
 Return type
numpy.ndarray of length 3.

transformNormal
(normal, direct=True)[source]¶ Apply the transform to a normal: R = (M1)t * V.
 Parameters
normal – Arraylike vector of 3 coordinates.
direct (bool) – Whether to apply the direct (True, the default) or inverse (False) transform.
 Returns
The transformed normal.
 Return type
numpy.ndarray of length 3.

transformBounds
(bounds, direct=True)[source]¶ Apply the transform to an axesaligned rectangular box.
 Parameters
bounds (2x3 numpy.ndarray) – Min and max coords of the box for each axes.
direct (bool) – Whether to apply the direct (True, the default) or inverse (False) transform.
 Returns
Axesaligned rectangular box including the transformed box.
 Return type
2x3 numpy.ndarray of float32


class
Inverse
(transform)[source]¶ Transform which is the inverse of another one.
Static: It never gets updated.

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
Matrix
(matrix=None)[source]¶ 
setMatrix
(matrix=None)[source]¶ Update the 4x4 Matrix.
 Parameters
matrix – 4x4 arraylike matrix or None for identity matrix.

property
matrix
¶ The 4x4 matrix of this transform.


class
Rotate
(angle=0.0, ax=0.0, ay=0.0, az=1.0)[source]¶ 
property
angle
¶ The rotation angle in degrees.

property
axis
¶ The normalized rotation axis as a numpy.ndarray.

setAngleAxis
(angle=None, axis=None)[source]¶ Update the angle and/or axis of the rotation.
 Parameters
angle (float) – The rotation angle in degrees.
axis – Arraylike axis vector (3 coordinates).

property
quaternion
¶ Rotation unit quaternion as (x, y, z, w).
Where: (x, y, z) = sin(angle/2), w = cos(angle/2).

property

class
Shear
(axis, sx=0.0, sy=0.0, sz=0.0)[source]¶ 
property
axis
¶ The axis against which other axes are skewed.

property
factors
¶ The shear factors: shearFactor = tan(shearAngle)

property

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), keepaspect=True)[source]¶ Orthographic (i.e., parallel) projection which can keep aspect ratio.
Clipping planes are adjusted to match the aspect ratio of the
size
attribute ifkeepaspect
is True.In this case, 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 (2tuple of float) – Viewport’s size used to compute the aspect ratio (width, height).
keepaspect (bool) – True (default) to keep aspect ratio, False otherwise.

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.

property
left
¶ Coord of the left clipping plane.

property
right
¶ Coord of the right clipping plane.

property
bottom
¶ Coord of the bottom clipping plane.

property
top
¶ Coord of the top clipping plane.

property
size
¶ Viewport size as a 2tuple of float (width, height)

property
keepaspect
¶ True to keep aspect ratio, False otherwise.

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 (2tuple 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 fieldofview in degrees.
near (float) – The near clipping plane Z coord (stricly positive).
far (float) – The far clipping plane Z coord (> near).
size (2tuple of float) – Viewport’s size used to compute the aspect ratio (width, height).

property
fovy
¶ Vertical fieldofview 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 arraylike of coordinates along the first dimension.
dim1Array – 1D arraylike 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 rowmajor (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 rowmajor (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.ndarraylike of length 3) – First end of the segment
s1 (1D numpy.ndarraylike 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.ndarraylike 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]

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 (3tuple of float.) – A point on the plane.
normal (3tuple of float.) – Normal of the plane.

setPlane
(point=None, normal=None)[source]¶ Set plane point and normal and notify.
 Parameters
point (3tuple of float or None.) – A point on the plane.
normal (3tuple of float or None.) – Normal of the plane.

property
point
¶ A point on the plane.

property
normal
¶ The (normalized) normal of the plane.

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

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

segmentIntersection
(s0, s1)[source]¶ Compute the plane intersection with segment [s0, s1].
 Parameters
s0 (1D numpy.ndarraylike of length 3) – First end of the segment
s1 (1D numpy.ndarraylike 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

cache
(key, factory, *args, **kwargs)[source]¶ Lazyloading cache to store values in the context for rendering
 Parameters
key – The key to retrieve
factory – A callback taking args and kwargs as arguments and returning the value to store.
 Returns
The stored or newly allocated value

property
viewport
¶ Viewport doing the current rendering

property
glCtx
¶ The OpenGL context in use

property
objectToCamera
¶ The current transform from object to camera coords.
Do not modify.

property
projection
¶ Projection transform.
Do not modify.

property
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.

property
clipper
¶ The current clipping plane (ClippingPlane)

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 (3tuple of float) – A point of the plane
normal (3tuple of float) – Normal vector of the plane or (0, 0, 0) for no clipping

setupProgram
(program)[source]¶ Setsup uniforms of a program using the context shader functions.
 Parameters
program (GLProgram) – The program to setup. It MUST be in use and using the context function.

property
fragDecl
¶ Fragment shader declaration for scene shader functions

property
fragCallPre
¶ Fragment shader call for scene shader functions (to do first)
It takes the camera position (vec4) as argument.

property
fragCallPost
¶ Fragment shader call for scene shader functions (to do last)
It takes the camera position (vec4) as argument.

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

property
transforms
¶ Proxy of camera transforms.
Do not modify the list.

property
dirty
¶ True if scene is dirty and needs redisplay.

property
background
¶ Viewport’s background color (4tuple of float in [0, 1] or None)
The background color is used to clear to viewport. If None, the viewport is not cleared

property
camera
¶ The camera used to render the scene.

property
light
¶ The light used to render the scene.

property
fog
¶ The fog function used to render the scene

property
origin
¶ Origin (ox, oy) of the viewport in pixels

property
size
¶ Size (width, height) of the viewport in pixels

property
shape
¶ Shape (height, width) of the viewport in pixels.
This is a convenient wrapper to the inverse of size.

property
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 topleft, x to the right, y goes downward.
window
: Onscreen 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 offscreen 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.

property
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.

property
devicePixelRatio
¶ Ratio between device and device independent pixels (float)
This is useful for font rendering.

property
glContext
¶ The handle to the OpenGL context provided by the system.

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='position')[source]¶ Cache program within context.
WARNING: No cleanup.
 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.

class
Window
(mode='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.

property
dirty
¶ True if this object or any attached viewports is dirty.

property
size
¶ Size (width, height) of the window in pixels

property
shape
¶ Shape (height, width) of the window in pixels.
This is a convenient wrapper to the reverse of size.

property
viewports
¶ List of viewports to render in the corresponding framebuffer

property
framebufferid
¶ Framebuffer ID used to perform rendering