ObjMeshStim

Attributes

ObjMeshStim(win, objFile[, pos, ori, …]) Class for loading and presenting 3D stimuli in the Wavefront OBJ format.

Details

class psychopy.visual.ObjMeshStim(win, objFile, pos=(0, 0, 0), ori=(0, 0, 0, 1), useMaterial=None, loadMtllib=True, color=(0.0, 0.0, 0.0), colorSpace='rgb', contrast=1.0, opacity=1.0, useShaders=False, name='', autoLog=True)[source]

Class for loading and presenting 3D stimuli in the Wavefront OBJ format.

Calling the draw method will render the mesh to the current buffer. The render target (FBO or back buffer) must have a depth buffer attached to it for the object to be rendered correctly. Shading is used if the current window has light sources defined and lighting is enabled (by setting useLights=True before drawing the stimulus).

Vertex positions, texture coordinates, and normals are loaded and packed into a single vertex buffer object (VBO). Vertex array objects (VAO) are created for each material with an index buffer referencing vertices assigned that material in the VBO. For maximum performance, keep the number of materials per object as low as possible, as switching between VAOs has some overhead.

Material attributes are read from the material library file (*.MTL) associated with the *.OBJ file. This file will be automatically searched for and read during loading. Afterwards you can edit material properties by accessing the data structure of the materials attribute.

Keep in mind that OBJ shapes are rigid bodies, the mesh itself cannot be deformed during runtime. However, meshes can be positioned and rotated as desired by manipulating the RigidBodyPose instance accessed through the thePose attribute.

Warning

Loading an *.OBJ file is a slow process, be sure to do this outside of any time-critical routines! This class is experimental and may result in undefined behavior.

Examples

Loading an *.OBJ file from a disk location:

myObjStim = ObjMeshStim(win, '/path/to/file/model.obj')
Parameters:
  • win (~psychopy.visual.Window) – Window this stimulus is associated with. Stimuli cannot be shared across windows unless they share the same context.
  • size (tuple or float) – Dimensions of the mesh. If a single value is specified, the plane will be a square. Provide a tuple of floats to specify the width and length of the box (eg. size=(0.2, 1.3)).
  • pos (array_like) – Position vector [x, y, z] for the origin of the rigid body.
  • ori (array_like) – Orientation quaternion [x, y, z, w] where x, y, z are imaginary and w is real. If you prefer specifying rotations in axis-angle format, call setOriAxisAngle after initialization. By default, the plane is oriented with normal facing the +Z axis of the scene.
  • useMaterial (PhongMaterial, optional) – Material to use for all sub-meshes. The material can be configured by accessing the material attribute after initialization. If no material is specified, color will modulate the diffuse and ambient colors for all meshes in the model. If loadMtllib is True, this value should be None.
  • loadMtllib (bool) – Load materials from the MTL file associated with the mesh. This will override useMaterial if it is None. The value of materials after initialization will be a dictionary where keys are material names and values are materials. Any textures associated with the model will be loaded as per the material requirements.
  • useShaders (bool) – Use shaders when rendering.
_createVAO(vertices, textureCoords, normals, faces)

Create a vertex array object for handling vertex attribute data.

_getDesiredRGB(rgb, colorSpace, contrast)

Convert color to RGB while adding contrast. Requires self.rgb, self.colorSpace and self.contrast

_loadMtlLib(mtlFile)[source]

Load a material library associated with the OBJ file. This is usually called by the constructor for this class.

Parameters:mtlFile (str) – Path to MTL file.
_selectWindow(win)

Switch drawing to the specified window. Calls the window’s _setCurrent() method which handles the switch.

_updateList()

The user shouldn’t need this method since it gets called after every call to .set() Chooses between using and not using shaders each call.

color

Color of the stimulus

Value should be one of:

When color is specified using numbers, it is interpreted with respect to the stimulus’ current colorSpace. If color is given as a single value (scalar) then this will be applied to all 3 channels.

Examples

For whatever stim you have:

stim.color = 'white'
stim.color = 'RoyalBlue'  # (the case is actually ignored)
stim.color = '#DDA0DD'  # DDA0DD is hexadecimal for plum
stim.color = [1.0, -1.0, -1.0]  # if stim.colorSpace='rgb':
                # a red color in rgb space
stim.color = [0.0, 45.0, 1.0]  # if stim.colorSpace='dkl':
                # DKL space with elev=0, azimuth=45
stim.color = [0, 0, 255]  # if stim.colorSpace='rgb255':
                # a blue stimulus using rgb255 space
stim.color = 255  # interpreted as (255, 255, 255)
                  # which is white in rgb255.

Operations work as normal for all numeric colorSpaces (e.g. ‘rgb’, ‘hsv’ and ‘rgb255’) but not for strings, like named and hex. For example, assuming that colorSpace=’rgb’:

stim.color += [1, 1, 1]  # increment all guns by 1 value
stim.color *= -1  # multiply the color by -1 (which in this
                    # space inverts the contrast)
stim.color *= [0.5, 0, 1]  # decrease red, remove green, keep blue

You can use setColor if you want to set color and colorSpace in one line. These two are equivalent:

stim.setColor((0, 128, 255), 'rgb255')
# ... is equivalent to
stim.colorSpace = 'rgb255'
stim.color = (0, 128, 255)
colorSpace

The name of the color space currently being used

Value should be: a string or None

For strings and hex values this is not needed. If None the default colorSpace for the stimulus is used (defined during initialisation).

Please note that changing colorSpace does not change stimulus parameters. Thus you usually want to specify colorSpace before setting the color. Example:

# A light green text
stim = visual.TextStim(win, 'Color me!',
                       color=(0, 1, 0), colorSpace='rgb')

# An almost-black text
stim.colorSpace = 'rgb255'

# Make it light green again
stim.color = (128, 255, 128)
contrast

A value that is simply multiplied by the color

Value should be: a float between -1 (negative) and 1 (unchanged).
Operations supported.

Set the contrast of the stimulus, i.e. scales how far the stimulus deviates from the middle grey. You can also use the stimulus opacity to control contrast, but that cannot be negative.

Examples:

stim.contrast =  1.0  # unchanged contrast
stim.contrast =  0.5  # decrease contrast
stim.contrast =  0.0  # uniform, no contrast
stim.contrast = -0.5  # slightly inverted
stim.contrast = -1.0  # totally inverted

Setting contrast outside range -1 to 1 is permitted, but may produce strange results if color values exceeds the monitor limits.:

stim.contrast =  1.2  # increases contrast
stim.contrast = -1.2  # inverts with increased contrast
draw(win=None)[source]

Draw the mesh.

Parameters:win (~psychopy.visual.Window) – Window this stimulus is associated with. Stimuli cannot be shared across windows unless they share the same context.
getOri()
getOriAxisAngle(degrees=True)

Get the axis and angle of rotation for the 3D stimulus. Converts the orientation defined by the ori quaternion to and axis-angle representation.

Parameters:degrees (bool, optional) – Specify True if angle is in degrees, or else it will be treated as radians. Default is True.
Returns:Axis [rx, ry, rz] and angle.
Return type:tuple
getPos()
getRayIntersectBounds(rayOrig, rayDir)

Get the point which a ray intersects the bounding box of this mesh.

Parameters:
  • rayOrig (array_like) – Origin of the ray in space [x, y, z].
  • rayDir (array_like) – Direction vector of the ray [x, y, z], should be normalized.
Returns:

Coordinate in world space of the intersection and distance in scene units from rayOrig. Returns None if there is no intersection.

Return type:

tuple

isVisible()

Check if the object is visible to the observer.

Test if a pose’s bounding box or position falls outside of an eye’s view frustum.

Poses can be assigned bounding boxes which enclose any 3D models associated with them. A model is not visible if all the corners of the bounding box fall outside the viewing frustum. Therefore any primitives (i.e. triangles) associated with the pose can be culled during rendering to reduce CPU/GPU workload.

Returns:True if the object’s bounding box is visible.
Return type:bool

Examples

You can avoid running draw commands if the object is not visible by doing a visibility test first:

if myStim.isVisible():
    myStim.draw()
ori

Orientation quaternion (X, Y, Z, W).

pos

Position vector (X, Y, Z).

setColor(color, colorSpace=None, operation='', log=None)

Usually you can use ‘stim.attribute = value’ syntax instead, but use this method if you need to suppress the log message and/or set colorSpace simultaneously.

setContrast(newContrast, operation='', log=None)

Usually you can use ‘stim.attribute = value’ syntax instead, but use this method if you need to suppress the log message

setOri(ori)
setOriAxisAngle(axis, angle, degrees=True)

Set the orientation of the 3D stimulus using an axis and angle. This sets the quaternion at ori.

Parameters:
  • axis (array_like) – Axis of rotation [rx, ry, rz].
  • angle (float) – Angle of rotation.
  • degrees (bool, optional) – Specify True if angle is in degrees, or else it will be treated as radians. Default is True.
setPos(pos)
setUseShaders(value=True, log=None)

Usually you can use ‘stim.attribute = value’ syntax instead, but use this method if you need to suppress the log message

thePose

The pose of the rigid body. This is a class which has pos and ori attributes.

units

None, ‘norm’, ‘cm’, ‘deg’, ‘degFlat’, ‘degFlatPos’, or ‘pix’

If None then the current units of the Window will be used. See Units for the window and stimuli for explanation of other options.

Note that when you change units, you don’t change the stimulus parameters and it is likely to change appearance. Example:

# This stimulus is 20% wide and 50% tall with respect to window
stim = visual.PatchStim(win, units='norm', size=(0.2, 0.5)

# This stimulus is 0.2 degrees wide and 0.5 degrees tall.
stim.units = 'deg'
useShaders

Should shaders be used to render the stimulus (typically leave as True)

If the system support the use of OpenGL shader language then leaving this set to True is highly recommended. If shaders cannot be used then various operations will be slower (notably, changes to stimulus color or contrast)

win
The Window object in which the
stimulus will be rendered by default. (required)

Example, drawing same stimulus in two different windows and display simultaneously. Assuming that you have two windows and a stimulus (win1, win2 and stim):

   stim.win = win1  # stimulus will be drawn in win1
   stim.draw()  # stimulus is now drawn to win1
   stim.win = win2  # stimulus will be drawn in win2
   stim.draw()  # it is now drawn in win2
   win1.flip(waitBlanking=False)  # do not wait for next
                # monitor update
   win2.flip()  # wait for vertical blanking.

Note that this just changes **default** window for stimulus.
You could also specify window-to-draw-to when drawing::

   stim.draw(win1)
   stim.draw(win2)

Back to top