scallop dome pyformex logo

Previous topic

25. canvas — This implements an OpenGL drawing widget for painting 3D scenes.

Next topic

27. camera — OpenGL camera handling

[FSF Associate Member]

Valid XHTML 1.0 Transitional

26. viewport — Interactive OpenGL Canvas embedded in a Qt4 widget.

This module implements user interaction with the OpenGL canvas defined in module canvas. QtCanvas is a single interactive OpenGL canvas, while MultiCanvas implements a dynamic array of multiple canvases.

Classes defined in module viewport

class viewport.CursorShapeHandler(widget)

A class for handling the mouse cursor shape on the Canvas.

setCursorShape(shape)

Set the cursor shape to shape

setCursorShapeFromFunc(func)

Set the cursor shape to shape

class viewport.CanvasMouseHandler

A class for handling the mouse events on the Canvas.

getMouseFunc()

Return the mouse function bound to self.button and self.mod

class viewport.QtCanvas(*args, **kargs)

A canvas for OpenGL rendering.

This class provides interactive functionality for the OpenGL canvas provided by the canvas.Canvas class.

Interactivity is highly dependent on Qt4. Putting the interactive functions in a separate class makes it esier to use the Canvas class in non-interactive situations or combining it with other GUI toolsets.

The QtCanvas constructor may have positional and keyword arguments. The positional arguments are passed to the QtOpenGL.QGLWidget constructor, while the keyword arguments are passed to the canvas.Canvas constructor.

getSize()

Return the size of this canvas

changeSize(width, height)

Resize the canvas to (width x height).

If a negative value is given for either width or height, the corresponding size is set equal to the maximum visible size (the size of the central widget of the main window).

Note that this may not have the expected result when multiple viewports are used.

resetOptions()

Reset the Drawing options to some defaults

setOptions(d)

Set the Drawing options to some values

setCursorShape(shape)

Set the cursor shape to shape

setCursorShapeFromFunc(func)

Set the cursor shape to shape

getMouseFunc()

Return the mouse function bound to self.button and self.mod

mouse_rectangle_zoom(x, y, action)

Process mouse events during interactive rectangle zooming.

On PRESS, record the mouse position. On MOVE, create a rectangular zoom window. On RELEASE, zoom to the picked rectangle.

setPickable(nrs=None)

Set the list of pickable actors

start_selection(mode, filter)

Start an interactive picking mode.

If selection mode was already started, mode is disregarded and this can be used to change the filter method.

wait_selection()

Wait for the user to interactively make a selection.

finish_selection()

End an interactive picking mode.

accept_selection(clear=False)

Accept or cancel an interactive picking mode.

If clear == True, the current selection is cleared.

cancel_selection()

Cancel an interactive picking mode and clear the selection.

pick(mode='actor', oneshot=False, func=None, filter=None)

Interactively pick objects from the viewport.

  • mode: defines what to pick : one of ['actor','element','point','number','edge']

  • oneshot: if True, the function returns as soon as the user ends a picking operation. The default is to let the user modify his selection and only to return after an explicit cancel (ESC or right mouse button).

  • func: if specified, this function will be called after each atomic pick operation. The Collection with the currently selected objects is passed as an argument. This can e.g. be used to highlight the selected objects during picking.

  • filter: defines what elements to retain from the selection: one of [None,'single','closest,'connected'].

    • None (default) will return the complete selection.

    • ‘closest’ will only keep the element closest to the user.

    • ‘connected’ will only keep elements connected to - the closest element (set picked) - what is already in the selection (add picked).

      Currently this only works when picking mode is ‘element’ and for Actors having a partitionByConnection method.

When the picking operation is finished, the selection is returned. The return value is always a Collection object.

pickNumbers(*args, **kargs)

Go into number picking mode and return the selection.

idraw(mode='point', npoints=-1, zplane=0.0, func=None, coords=None, preview=False)

Interactively draw on the canvas.

This function allows the user to interactively create points in 3D space and collects the subsequent points in a Coords object. The interpretation of these points is left to the caller.

  • mode: one of the drawing modes, specifying the kind of objects you want to draw. This is passed to the specified func.
  • npoints: If -1, the user can create any number of points. When >=0, the function will return when the total number of points in the collection reaches the specified value.
  • zplane: the depth of the z-plane on which the 2D drawing is done.
  • func: a function that is called after each atomic drawing operation. It is typically used to draw a preview using the current set of points. The function is passed the current Coords and the mode as arguments.
  • coords: an initial set of coordinates to which the newly created points should be added. If specified, npoints also counts these initial points.
  • preview: Experimental If True, the preview funcion will also be called during mouse movement with a pressed button, allowing to preview the result before a point is created.

The drawing operation is finished when the number of requested points has been reached, or when the user clicks the right mouse button or hits ‘ENTER’. The return value is a (n,3) shaped Coords array.

start_draw(mode, zplane, coords)

Start an interactive drawing mode.

finish_draw()

End an interactive drawing mode.

accept_draw(clear=False)

Cancel an interactive drawing mode.

If clear == True, the current drawing is cleared.

cancel_draw()

Cancel an interactive drawing mode and clear the drawing.

mouse_draw(x, y, action)

Process mouse events during interactive drawing.

On PRESS, do nothing. On MOVE, do nothing. On RELEASE, add the point to the point list.

drawLinesInter(mode='line', oneshot=False, func=None)

Interactively draw lines on the canvas.

  • oneshot: if True, the function returns as soon as the user ends a drawing operation. The default is to let the user draw multiple lines and only to return after an explicit cancel (ESC or right mouse button).
  • func: if specified, this function will be called after each atomic drawing operation. The current drawing is passed as an argument. This can e.g. be used to show the drawing.

When the drawing operation is finished, the drawing is returned. The return value is a (n,2,2) shaped array.

start_drawing(mode)

Start an interactive line drawing mode.

wait_drawing()

Wait for the user to interactively draw a line.

finish_drawing()

End an interactive drawing mode.

accept_drawing(clear=False)

Cancel an interactive drawing mode.

If clear == True, the current drawing is cleared.

cancel_drawing()

Cancel an interactive drawing mode and clear the drawing.

edit_drawing(mode)

Edit an interactive drawing.

dynarot(x, y, action)

Perform dynamic rotation operation.

This function processes mouse button events controlling a dynamic rotation operation. The action is one of PRESS, MOVE or RELEASE.

dynapan(x, y, action)

Perform dynamic pan operation.

This function processes mouse button events controlling a dynamic pan operation. The action is one of PRESS, MOVE or RELEASE.

dynazoom(x, y, action)

Perform dynamic zoom operation.

This function processes mouse button events controlling a dynamic zoom operation. The action is one of PRESS, MOVE or RELEASE.

wheel_zoom(delta)

Zoom by rotating a wheel over an angle delta

emit_done(x, y, action)

Emit a DONE event by clicking the mouse.

This is equivalent to pressing the ENTER button.

emit_cancel(x, y, action)

Emit a CANCEL event by clicking the mouse.

This is equivalent to pressing the ESC button.

draw_state_rect(x, y)

Store the pos and draw a rectangle to it.

mouse_pick(x, y, action)

Process mouse events during interactive picking.

On PRESS, record the mouse position. On MOVE, create a rectangular picking window. On RELEASE, pick the objects inside the rectangle.

draw_state_line(x, y)

Store the pos and draw a line to it.

mouse_draw_line(x, y, action)

Process mouse events during interactive drawing.

On PRESS, record the mouse position. On MOVE, draw a line. On RELEASE, add the line to the drawing.

mousePressEvent(e)

Process a mouse press event.

mouseMoveEvent(e)

Process a mouse move event.

mouseReleaseEvent(e)

Process a mouse release event.

wheelEvent(e)

Process a wheel event.

enable_lighting(state)

Toggle lights on/off.

has_lighting()

Return the status of the lighting.

resetDefaults(dict={})

Return all the settings to their default values.

setAmbient(ambient)

Set the global ambient lighting for the canvas

setMaterial(matname)

Set the default material light properties for the canvas

resetLighting()

Change the light parameters

setRenderMode(mode, lighting=None)

Set the rendering mode.

This sets or changes the rendermode and lighting attributes. If lighting is not specified, it is set depending on the rendermode.

If the canvas has not been initialized, this merely sets the attributes self.rendermode and self.settings.lighting. If the canvas was already initialized (it has a camera), and one of the specified settings is fdifferent from the existing, the new mode is set, the canvas is re-initialized according to the newly set mode, and everything is redrawn with the new mode.

setWireMode(state, mode=None)

Set the wire mode.

This toggles the drawing of edges on top of 2D and 3D geometry. Value is an integer. If positive, edges are shown, else not.

setToggle(attr, state)

Set or toggle a boolean settings attribute

Furthermore, if a Canvas method do_ATTR is defined, it will be called with the old and new toggle state as a parameter.

do_lighting(state, oldstate=None)

Toggle lights on/off.

setLineWidth(lw)

Set the linewidth for line rendering.

setLineStipple(repeat, pattern)

Set the linestipple for line rendering.

setPointSize(sz)

Set the size for point drawing.

setBackground(color=None, image=None)

Set the color(s) and image.

Change the background settings according to the specified parameters and set the canvas background accordingly. Only (and all) the specified parameters get a new value.

Parameters:

  • color: either a single color, a list of two colors or a list of four colors.
  • image: an image to be set.
createBackground()

Create the background object.

setFgColor(color)

Set the default foreground color.

setSlColor(color)

Set the highlight color.

setTriade(on=None, pos='lb', siz=100)

Toggle the display of the global axes on or off.

If on is True, a triade of global axes is displayed, if False it is removed. The default (None) toggles between on and off.

clear()

Clear the canvas to the background color.

setDefaults()

Activate the canvas settings in the GL machine.

overrideMode(mode)

Override some settings

glinit()

Initialize the rendering machine.

The rendering machine is initialized according to self.settings: - self.rendermode: one of - self.lighting

glupdate()

Flush all OpenGL commands, making sure the display is updated.

display()

(Re)display all the actors in the scene.

This should e.g. be used when actors are added to the scene, or after changing camera position/orientation or lens.

begin_2D_drawing()

Set up the canvas for 2D drawing on top of 3D canvas.

The 2D drawing operation should be ended by calling end_2D_drawing. It is assumed that you will not try to change/refresh the normal 3D drawing cycle during this operation.

end_2D_drawing()

Cancel the 2D drawing mode initiated by begin_2D_drawing.

sceneBbox()

Return the bbox of all actors in the scene

setBbox(bb=None)

Set the bounding box of the scene you want to be visible.

bb is a (2,3) shaped array specifying a bounding box. If no bbox is given, the bounding box of all the actors in the scene is used, or if the scene is empty, a default unit bounding box.

addActor(itemlist)

Add a 3D actor or a list thereof to the 3D scene.

addHighlight(itemlist)

Add a highlight or a list thereof to the 3D scene.

addAnnotation(itemlist)

Add an annotation or a list thereof to the 3D scene.

addDecoration(itemlist)

Add a 2D decoration or a list thereof to the canvas.

addAny(itemlist=None)

Add any item or list.

This will add any actor/annotation/decoration item or a list of any such items to the canvas. This is the prefered method to add an item to the canvas, because it makes sure that each item is added to the proper list. It can however not be used to add highlights.

If you have a long list of a single type, it is more efficient to use one of the type specific add methods.

removeActor(itemlist=None)

Remove a 3D actor or a list thereof from the 3D scene.

Without argument, removes all actors from the scene. This also resets the bounding box for the canvas autozoom.

removeHighlight(itemlist=None)

Remove a highlight or a list thereof from the 3D scene.

Without argument, removes all highlights from the scene.

removeAnnotation(itemlist=None)

Remove an annotation or a list thereof from the 3D scene.

Without argument, removes all annotations from the scene.

removeDecoration(itemlist=None)

Remove a 2D decoration or a list thereof from the canvas.

Without argument, removes all decorations from the scene.

removeAny(itemlist=None)

Remove a list of any actor/highlights/annotation/decoration items.

This will remove the items from any of the canvas lists in which the item appears. itemlist can also be a single item instead of a list. If None is specified, all items from all lists will be removed.

redrawAll()

Redraw all actors in the scene.

setCamera(bbox=None, angles=None)

Sets the camera looking under angles at bbox.

This function sets the camera parameters to view the specified bbox volume from the specified viewing direction.

Parameters:

  • bbox: the bbox of the volume looked at
  • angles: the camera angles specifying the viewing direction. It can also be a string, the key of one of the predefined camera directions

If no angles are specified, the viewing direction remains constant. The scene center (camera focus point), camera distance, fovy and clipping planes are adjusted to make the whole bbox viewed from the specified direction fit into the screen.

If no bbox is specified, the following remain constant: the center of the scene, the camera distance, the lens opening and aspect ratio, the clipping planes. In other words the camera is moving on a spherical surface and keeps focusing on the same point.

If both are specified, then first the scene center is set, then the camera angles, and finally the camera distance.

In the current implementation, the lens fovy and aspect are not changed by this function. Zoom adjusting is performed solely by changing the camera distance.

project(x, y, z, locked=False)

Map the object coordinates (x,y,z) to window coordinates.

unProject(x, y, z, locked=False)

Map the window coordinates (x,y,z) to object coordinates.

zoom(f, dolly=True)

Dolly zooming.

Zooms in with a factor f by moving the camera closer to the scene. This does noet change the camera’s FOV setting. It will change the perspective view though.

zoomRectangle(x0, y0, x1, y1)

Rectangle zooming.

Zooms in/out by changing the area and position of the visible part of the lens. Unlike zoom(), this does not change the perspective view.

x0,y0,x1,y1 are pixel coordinates of the lower left and upper right corners of the area of the lens that will be mapped on the canvas viewport. Specifying values that lead to smaller width/height will zoom in.

zoomCentered(w, h, x=None, y=None)

Rectangle zooming with specified center.

This is like zoomRectangle, but the zoom rectangle is specified by its center and size, which may be more appropriate when using off-center zooming.

zoomAll()

Rectangle zoom to make full scene visible.

saveBuffer()

Save the current OpenGL buffer

showBuffer()

Show the saved buffer

draw_focus_rectangle(ofs=0, color=(1.0, 0.2, 0.4))

Draw the focus rectangle.

The specified width is HALF of the line width

draw_cursor(x, y)

draw the cursor

pick_actors()

Set the list of actors inside the pick_window.

pick_parts(obj_type, max_objects, store_closest=False)

Set the list of actor parts inside the pick_window.

obj_type can be ‘element’, ‘face’, ‘edge’ or ‘point’. ‘face’ and ‘edge’ are only available for Mesh type geometry. max_objects specifies the maximum number of objects

The picked object numbers are stored in self.picked. If store_closest==True, the closest picked object is stored in as a tuple ( [actor,object] ,distance) in self.picked_closest

A list of actors from which can be picked may be given. If so, the resulting keys are indices in this list. By default, the full actor list is used.

pick_elements()

Set the list of actor elements inside the pick_window.

pick_points()

Set the list of actor points inside the pick_window.

pick_edges()

Set the list of actor edges inside the pick_window.

pick_faces()

Set the list of actor faces inside the pick_window.

pick_numbers()

Return the numbers inside the pick_window.

highlightActor(actor)

Highlight an actor in the scene.

highlightActors(K)

Highlight a selection of actors on the canvas.

K is Collection of actors as returned by the pick() method. colormap is a list of two colors, for the actors not in, resp. in the Collection K.

highlightElements(K)

Highlight a selection of actor elements on the canvas.

K is Collection of actor elements as returned by the pick() method. colormap is a list of two colors, for the elements not in, resp. in the Collection K.

highlightEdges(K)

Highlight a selection of actor edges on the canvas.

K is Collection of TriSurface actor edges as returned by the pick() method. colormap is a list of two colors, for the edges not in, resp. in the Collection K.

highlightPoints(K)

Highlight a selection of actor elements on the canvas.

K is Collection of actor elements as returned by the pick() method.

highlightPartitions(K)

Highlight a selection of partitions on the canvas.

K is a Collection of actor elements, where each actor element is connected to a collection of property numbers, as returned by the partitionCollection() method.

highlight(K, mode)

Highlight a Collection of actor/elements.

K is usually the return value of a pick operation, but might also be set by the user. mode is one of the pick modes.

class viewport.NewiMultiCanvas(parent=None)

An OpenGL canvas with multiple viewports and QT interaction.

The MultiCanvas implements a central QT widget containing one or more QtCanvas widgets.

changeLayout(nvps=None, ncols=None, nrows=None, pos=None, rstretch=None, cstretch=None)

Change the lay-out of the viewports on the OpenGL widget.

nvps: number of viewports ncols: number of columns nrows: number of rows pos: list holding the position and span of each viewport [[row,col,rowspan,colspan],...] rstretch: list holding the stretch factor for each row cstretch: list holding the stretch factor for each column (rows/columns with a higher stretch factor take more of the available space) Each of this parameters is optional.

If pos is given, it specifies all viewports and nvps, nrows and ncols are disregarded.

Else:

If nvps is given, it specifies the number of viewports in the layout. Else, nvps will be set to the current number of viewports.

If ncols is an int, viewports are laid out rowwise over ncols columns and nrows is ignored. If ncols is None and nrows is an int, viewports are laid out columnwise over nrows rows.

If nvps is not equal to the current number of viewports, viewports will be added or removed to match the requested number.

By default they are laid out rowwise over two columns.

createView(shared=None)

Create a new viewport

If another QtCanvas instance is passed, both will share the same display lists and textures.

addView(view, row, col, rowspan=1, colspan=1)

Add a new viewport and make it visible

removeView(view=None)

Remove a view from the canvas

If view is None, the last one is removed. You can not remove a view when there is only one left.

setCurrent(view)

Make the specified viewport the current one.

view can be either a viewport or viewport number. The current viewport is the one that will be used for drawing operations. This may be different from the viewport having GUI focus (pf.canvas).

setStretch(rowstretch, colstretch)

Set the row and column stretch factors.

rowstretch and colstretch are lists of stretch factors to be applied on the subsequent rows/columns. If the lists are shorter than the number of rows/columns, the

Link viewport vp to to

class viewport.FramedGridLayout(parent=None)

A QtGui.QGridLayout where each added widget is framed.

class viewport.MultiCanvas(parent=None)

An OpenGL canvas with multiple viewports and QT interaction.

The MultiCanvas implements a central QT widget containing one or more QtCanvas widgets.

newView(shared=None, settings=None)

Create a new viewport

If another QtCanvas instance is passed, both will share the same display lists and textures.

addView()

Add a new viewport to the widget

setCurrent(canv)

Make the specified viewport the current one.

canv can be either a viewport or viewport number.

viewIndex(view)

Return the index of the specified view

showWidget(w)

Show the view w.

changeLayout(nvps=None, ncols=None, nrows=None, pos=None, rstretch=None, cstretch=None)

Change the lay-out of the viewports on the OpenGL widget.

nvps: number of viewports ncols: number of columns nrows: number of rows pos: list holding the position and span of each viewport [[row,col,rowspan,colspan],...] rstretch: list holding the stretch factor for each row cstretch: list holding the stretch factor for each column (rows/columns with a higher stretch factor take more of the available space) Each of this parameters is optional.

If a number of viewports is given, viewports will be added or removed to match the requested number. By default they are laid out rowwise over two columns.

If ncols is an int, viewports are laid out rowwise over ncols columns and nrows is ignored. If ncols is None and nrows is an int, viewports are laid out columnwise over nrows rows. Alternatively, the pos argument can be used to specify the layout of the viewports.

Link viewport vp to to

Functions defined in module viewport

viewport.dotpr(v, w)

Return the dot product of vectors v and w

viewport.length(v)

Return the length of the vector v

viewport.projection(v, w)

Return the (signed) length of the projection of vector v on vector w.

viewport.setOpenGLFormat()

Set the correct OpenGL format.

On a correctly installed system, the default should do well. The default OpenGL format can be changed by command line options:

--dri   : use the Direct Rendering Infrastructure, if available
--nodri : do not use the DRI
--opengl : set the opengl version
viewport.OpenGLSupportedVersions(flags)

Return the supported OpenGL version.

flags is the return value of QGLFormat.OpenGLVersionFlag()

Returns a list with tuple (k,v) where k is a string describing an Opengl version and v is True or False.

viewport.OpenGLFormat(fmt=None)

Some information about the OpenGL format.