scallop dome pyformex logo

Previous topic

4. script — Basic pyFormex script functions

Next topic

6. colors — Definition of some RGB colors and color conversion functions

[FSF Associate Member]

Valid XHTML 1.0 Transitional

5. draw — Create 3D graphical representations.

The draw module provides the basic user interface to the OpenGL rendering capabilities of pyFormex. The full contents of this module is available to scripts running in the pyFormex GUI without the need to import it.

Classes defined in module draw

Functions defined in module draw

draw.closeGui()

Close the GUI.

Calling this function from a script closes the GUI and terminates pyFormex.

draw.closeDialog(name)

Close the named dialog.

Closes the InputDialog with the given name. If multiple dialogs are open with the same name, all these dialogs are closed.

This only works for dialogs owned by the pyFormex GUI.

draw.showMessage(text, actions=['OK'], level='info', modal=True, **kargs)

Show a short message widget and wait for user acknowledgement.

There are three levels of messages: ‘info’, ‘warning’ and ‘error’. They differ only in the icon that is shown next to the test. By default, the message widget has a single button with the text ‘OK’. The dialog is closed if the user clicks a button. The return value is the button text.

draw.showInfo(text, actions=['OK'], modal=True)

Show an informational message and wait for user acknowledgement.

draw.warning(text, actions=['OK'])

Show a warning message and wait for user acknowledgement.

draw.error(text, actions=['OK'])

Show an error message and wait for user acknowledgement.

draw.ask(question, choices=None, **kargs)

Ask a question and present possible answers.

Return answer if accepted or default if rejected. The remaining arguments are passed to the InputDialog getResult method.

draw.ack(question, **kargs)

Show a Yes/No question and return True/False depending on answer.

draw.showText(text, type=None, actions=[('OK', None)], modal=True, mono=False)

Display a text and wait for user response.

This opens a TextBox widget and displays the text in the widget. Scrollbars will be added if the text is too large to display at once.

The text can be plain text format. Some rich text formats will be recognized and rendered appropriately. See widgets.TextBox.

mono=True forces the use of a monospaced font.

draw.showFile(filename, mono=False, **kargs)

Display a text file.

This will use the showText() function to display a text read from a file. By default this uses a monospaced font. Other arguments may also be passed to ShowText.

draw.showDescription(filename=None)

Show the Description part of the docstring of a pyFormex script.

If no file name is specified, the current script is used. If the script’s docstring has no Description part, a default text is shown.

draw.askItems(items, caption=None, timeout=None, **kargs)

Ask the value of some items to the user.

Create an interactive widget to let the user set the value of some items. ‘items’ is a list of input items (basically [key,value] pairs). See the widgets.InputDialog class for complete description of the available input items.

Two InputDialog classes are defined in gui.widgets. The OldInputDialog class is deprecated in favor of InputDialog, which has become the default as of pyFormex 0.8.3. The two classes differ in how the input is specified. In the new format, each input item is either a simpleInputItem, a groupInputItem or a tabInputItem.

You can specify ‘legacy=False’ to indicate that you are using the new format, or ‘legacy=True’ if your data are in the old format. The default (‘legacy = None’), will make this function try to detect the format and convert the input items to the proper new format. This conversion will work on most, but not all legacy formats that have been used in the past by pyFormex. Since the legacy format is scheduled to be withdrawn in future, users are encouraged to change their input to the new format.

The remaining arguments are keyword arguments that are passed to the InputDialog.getResult method. A timeout (in seconds) can be specified to have the input dialog interrupted automatically.

Return a dictionary with the results: for each input item there is a (key,value) pair. Returns an empty dictionary if the dialog was canceled. Sets the dialog timeout and accepted status in global variables.

draw.currentDialog()

Returns the current dialog widget.

This returns the dialog widget created by the askItems() function, while the dialog is still active. If no askItems() has been called or if the user already closed the dialog, None is returned.

draw.dialogAccepted()

Returns True if the last askItems() dialog was accepted.

draw.dialogRejected()

Returns True if the last askItems() dialog was rejected.

draw.dialogTimedOut()

Returns True if the last askItems() dialog timed out.

draw.askFilename(cur=None, filter='All files (*.*)', exist=True, multi=False, change=True)

Ask for a file name or multiple file names using a file dialog.

cur is a directory or filename. All the files matching the filter in that directory (or that file’s directory) will be shown. If cur is a file, it will be selected as the current filename.

Unless the user cancels the operation, or the change parameter was set to False, the parent directory of the selected file will become the new working directory.

draw.askNewFilename(cur=None, filter='All files (*.*)')

Ask a single new filename.

This is a convenience function for calling askFilename with the arguments exist=False.

draw.askDirname(path=None, change=True)

Interactively select a directory and change the current workdir.

The user is asked to select a directory through the standard file dialog. Initially, the dialog shows all the subdirectories in the specified path, or by default in the current working directory.

The selected directory becomes the new working directory, unless the user canceled the operation, or the change parameter was set to False.

draw.checkWorkdir()

Ask the user to change the current workdir if it is not writable.

Returns True if the new workdir is writable.

draw.printMessage(s)

Print a message on the message board.

If a logfile was opened, the message is also written to the log file.

draw.message(s)

Print a message on the message board.

If a logfile was opened, the message is also written to the log file.

draw.flatten(objects, recurse=True)

Flatten a list of geometric objects.

Each item in the list should be either:

  • a drawable object,
  • a string with the name of such an object,
  • a list of any of these three.

This function will flatten the lists and replace the string items with the object they point to. The result is a single list of drawable objects. This function does not enforce the objects to be drawable. That should be done by the caller.

draw.drawable(objects)

Filters the drawable objects from a list.

The input is a list, usually of drawable objects. For each item in the list, the following is done:

  • if the item is drawable, it is kept as is,
  • if the item is not drawable but can be converted to a Formex, it is converted,
  • if it is neither drawable nor convertible to Formex, it is removed.

The result is a list of drawable objects (since a Formex is drawable).

draw.draw(F, view=None, bbox=None, color='prop', colormap=None, bkcolor=None, bkcolormap=None, alpha=None, mode=None, linewidth=None, linestipple=None, shrink=None, marksize=None, wait=True, clear=None, allviews=False, highlight=False, nolight=False, ontop=False, silent=True, **kargs)

Draw object(s) with specified settings and direct camera to it.

The first argument is an object to be drawn. All other arguments are settings that influence how the object is being drawn.

F is one of:

  • a drawable object (a geometry object like Formex, Mesh or TriSurface),
  • the name of a global pyFormex variable refering to such an object,
  • a list of any of these three items.

The variables are replaced with their value and the lists are flattened, to create a single list of objects. This then filtered for the drawable objects, and the resulting list of drawables is drawn using the remaining arguments.

The remaining arguments are drawing options. If None, they are filled in from the current viewport drawing options.

view is either the name of a defined view or ‘last’ or None. Predefined views are ‘front’,’back’,’top’,’bottom’,’left’,’right’,’iso’. With view=None the camera settings remain unchanged (but might be changed interactively through the user interface). This may make the drawn object out of view! With view=’last’, the camera angles will be set to the same camera angles as in the last draw operation, undoing any interactive changes. The initial default view is ‘front’ (looking in the -z direction).

bbox specifies the 3D volume at which the camera will be aimed (using the angles set by view). The camera position wil be set so that the volume comes in view using the current lens (default 45 degrees). bbox is a list of two points or compatible (array with shape (2,3)). Setting the bbox to a volume not enclosing the object may make the object invisible on the canvas. The special value bbox=’auto’ will use the bounding box of the objects getting drawn (object.bbox()), thus ensuring that the camera will focus on these objects. The special value bbox=None will use the bounding box of the previous drawing operation, thus ensuring that the camera’s target volume remains unchanged.

color,colormap,linewidth,alpha,marksize are passed to the creation of the 3D actor.

if color is None, it is drawn with the color specified on creation. if color == ‘prop’ and a colormap was installed, props define color. else, color should be an array of RGB values, either with shape (3,) for a single color, or (nelems,3) for differently colored elements

shrink is a floating point shrink factor that will be applied to object before drawing it.

If the Formex has properties and a color list is specified, then the the properties will be used as an index in the color list and each member will be drawn with the resulting color. If color is one color value, the whole Formex will be drawn with that color. Finally, if color=None is specified, the whole Formex is drawn in black.

Each draw action activates a locking mechanism for the next draw action, which will only be allowed after drawdelay seconds have elapsed. This makes it easier to see subsequent images and is far more elegant that an explicit sleep() operation, because all script processing will continue up to the next drawing instruction. The value of drawdelay is set in the config, or 2 seconds by default. The user can disable the wait cycle for the next draw operation by specifying wait=False. Setting drawdelay=0 will disable the waiting mechanism for all subsequent draw statements (until set >0 again).

draw.focus(object)

Move the camera thus that object comes fully into view.

object can be anything having a bbox() method or a list thereof. if no view is given, the default is used.

The camera is moved with fixed axis directions to a place where the whole object can be viewed using a 45. degrees lens opening. This technique may change in future!

draw.setDrawOptions(kargs0={}, **kargs)

Set default values for the draw options.

Draw options are a set of options that hold default values for the draw() function arguments and for some canvas settings. The draw options can be specified either as a dictionary, or as keyword arguments.

draw.askDrawOptions(d={})

Interactively ask the Drawing options from the user.

A dictionary may be specified to override the current defaults.

draw.drawVectors(P, v, size=None, nolight=True, **drawOptions)

Draw a set of vectors.

If size==None, draws the vectors v at the points P. If size is specified, draws the vectors size*normalize(v) P, v and size are single points or sets of points. If sets, they should be of the same size.

Other drawoptions can be specified and will be passed to the draw function.

draw.drawMarks(X, M, color='black', leader='', ontop=True)

Draw a list of marks at points X.

X is a Coords array. M is a list with the same length as X. The string representation of the marks are drawn at the corresponding 3D coordinate.

draw.drawFreeEdges(M, color='black')

Draw the feature edges of a Mesh

draw.drawNumbers(F, numbers=None, color='black', trl=None, offset=0, leader='', ontop=True)

Draw numbers on all elements of F.

numbers is an array with F.nelems() integer numbers. If no numbers are given, the range from 0 to nelems()-1 is used. Normally, the numbers are drawn at the centroids of the elements. A translation may be given to put the numbers out of the centroids, e.g. to put them in front of the objects to make them visible, or to allow to view a mark at the centroids. If an offset is specified, it is added to the shown numbers.

draw.drawPropNumbers(F, **kargs)

Draw property numbers on all elements of F.

This calls drawNumbers to draw the property numbers on the elements. All arguments of drawNumbers except numbers may be passed. If the object F thus not have property numbers, -1 values are drawn.

draw.drawVertexNumbers(F, color='black', trl=None, ontop=False)

Draw (local) numbers on all vertices of F.

Normally, the numbers are drawn at the location of the vertices. A translation may be given to put the numbers out of the location, e.g. to put them in front of the objects to make them visible, or to allow to view a mark at the vertices.

draw.drawText3D(P, text, color=None, font='sans', size=18, ontop=True)

Draw a text at a 3D point P.

draw.drawAxes(*args, **kargs)

Draw the axes of a CoordinateSystem.

This draws an AxesActor corresponding to the specified Coordinatesystem. The arguments are the same as those of the AxesActor constructor.

draw.drawImage(image, nx=-1, ny=-1, pixel='dot')

Draw an image as a colored Formex

Draws a raster image as a colored Formex. While there are other and better ways to display an image in pyFormex (such as using the imageView widget), this function allows for interactive handling the image using the OpenGL infrastructure.

Parameters:

  • image: a QImage holding a raster image. An image can be loaded from most standard image files using the loadImage() function
  • nx,`ny`: resolution you want to use for the display
  • pixel: the Formex representing a single pixel. It should be either a single element Formex, or one of the strings ‘dot’ or ‘quad’. If ‘dot’ a single point will be used, if ‘quad’ a unit square. The difference will be important when zooming in. The default is ‘dot’.
draw.drawViewportAxes3D(pos, color=None)

Draw two viewport axes at a 3D position.

draw.drawBbox(A)

Draw the bbox of the actor A.

draw.drawActor(A)

Draw an actor and update the screen.

draw.undraw(itemlist)

Remove an item or a number of items from the canvas.

Use the return value from one of the draw... functions to remove the item that was drawn from the canvas. A single item or a list of items may be specified.

draw.view(v, wait=True)

Show a named view, either a builtin or a user defined.

This shows the current scene from another viewing angle. Switching views of a scene is much faster than redrawing a scene. Therefore this function is prefered over draw() when the actors in the scene remain unchanged and only the camera viewpoint changes.

Just like draw(), this function obeys the drawing lock mechanism, and by default it will restart the lock to retard the next draing operation.

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

Toggle the display of the global axes on or off.

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

draw.drawText(text, x, y, gravity='E', font='helvetica', size=14, color=None, zoom=None)

Show a text at position x,y using font.

draw.annotate(annot)

Draw an annotation.

draw.decorate(decor)

Draw a decoration.

draw.createView(name, angles, addtogui=False)

Create a new named view (or redefine an old).

The angles are (longitude, latitude, twist). By default, the view is local to the script’s viewport. If gui is True, it is also added to the GUI.

draw.setView(name, angles=None)

Set the default view for future drawing operations.

If no angles are specified, the name should be an existing view, or the predefined value ‘last’. If angles are specified, this is equivalent to createView(name,angles) followed by setView(name).

draw.bgcolor(color, color2=None, mode='h')

Change the background color (and redraw).

If one color is given, the background is a solid color. If two colors are given, the background color will get a vertical gradient with color on top and color2 at the bottom.

draw.fgcolor(color)

Set the default foreground color.

draw.colormap(color=None)

Gets/Sets the current canvas color map

draw.lights(state=True)

Set the lights on or off

draw.transparent(state=True)

Set the transparency mode on or off.

draw.set_material_value(typ, val)

Set the value of one of the material lighting parameters

typ is one of ‘ambient’,’specular’,’emission’,’shininess’ val is a value between 0.0 and 1.0

draw.linewidth(wid)

Set the linewidth to be used in line drawings.

draw.linestipple(factor, pattern)

Set the linewidth to be used in line drawings.

draw.pointsize(siz)

Set the size to be used in point drawings.

draw.canvasSize(width, height)

Resize the canvas to (width x height).

draw.clear_canvas()

Clear the canvas.

This is a low level function not intended for the user.

draw.clear()

Clear the canvas.

Removes everything from the current scene and displays an empty background.

This function waits for the drawing lock to be released, but will not reset it.

draw.delay(s=None)

Get/Set the draw delay time.

Returns the current setting of the draw wait time (in seconds). This drawing delay is obeyed by drawing and viewing operations.

A parameter may be given to set the delay time to a new value. It should be convertable to a float. The function still returns the old setting. This may be practical to save that value to restore it later.

draw.wait(relock=True)

Wait until the drawing lock is released.

This uses the drawing lock mechanism to pause. The drawing lock ensures that subsequent draws are retarded to give the user the time to view. This use of this function is prefered over that of pause() or sleep(), because it allows your script to continue the numerical computations while waiting to draw the next screen.

This function can be used to retard other functions than `

draw.fforward()

Releases the drawing lock mechanism indefinely.

Releasing the drawing lock indefinely means that the lock will not be set again and your script will execute till the end.

draw.step()

Perform one step of a script.

A step is a set of instructions until the next draw operation. If a script is running, this just releases the draw lock. Else, it starts the script in step mode.

draw.pause(msg='Use the Step or Continue button to proceed', timeout=None)

Pause the execution until an external event occurs or timeout.

When the pause statement is executed, execution of the pyformex script is suspended until some external event forces it to proceed again. Clicking the STEP or CONTINUE button will produce such an event.

draw.sleep(timeout=None)

Sleep until key/mouse press in the canvas or until timeout

draw.wakeup(mode=0)

Wake up from the sleep function.

This is the only way to exit the sleep() function. Default is to wake up from the current sleep. A mode > 0 forces wakeup for longer period.

draw.zoomRectangle()

Zoom a rectangle selected by the user.

draw.zoomBbox(bb)

Zoom thus that the specified bbox becomes visible.

draw.zoomAll()

Zoom thus that all actors become visible.

draw.flyAlong(path, upvector=[0.0, 1.0, 0.0], sleeptime=None)

Fly through the current scene along the specified path.

  • path: a plex-2 or plex-3 Formex (or convertibel to such Formex) specifying the paths of camera eye and center (and upvector).
  • upvector: the direction of the vertical axis of the camera, in case of a 2-plex camera path.
  • sleeptime: a delay between subsequent images, to slow down the camera movement.

This function moves the camera through the subsequent elements of the Formex. For each element the first point is used as the center of the camera and the second point as the eye (the center of the scene looked at). For a 3-plex Formex, the third point is used to define the upvector (i.e. the vertical axis of the image) of the camera. For a 2-plex Formex, the upvector is constant as specified in the arguments.

draw.viewport(n=None)

Select the current viewport.

n is an integer number in the range of the number of viewports, or is one of the viewport objects in pyformex.GUI.viewports

if n is None, selects the current GUI viewport for drawing

draw.layout(nvps=None, ncols=None, nrows=None, pos=None, rstretch=None, cstretch=None)

Set the viewports layout.

draw.addViewport()

Add a new viewport.

draw.removeViewport()

Remove the last viewport.

draw.linkViewport(vp, tovp)

Link viewport vp to viewport tovp.

Both vp and tovp should be numbers of viewports.

draw.updateGUI()

Update the GUI.

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

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

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

draw.highlightPoints(K)

Highlight a selection of actor elements on the canvas.

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

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

draw.removeHighlights()

Remove the highlights from the current viewport

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

Enter interactive picking mode and return selection.

See viewport.py for more details. This function differs in that it provides default highlighting during the picking operation, a button to stop the selection operation

Parameters:

  • mode: one of the pick modes
  • filter: one of the selection_filters. The default picking filter activated on entering the pick mode. All available filters are presented in a combobox.
draw.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.

draw.set_edit_mode(s)

Set the drawing edit mode.

draw.drawLinesInter(mode='line', single=False, func=None)

Enter interactive drawing mode and return the line drawing.

See viewport.py for more details. This function differs in that it provides default displaying during the drawing operation and a button to stop the drawing operation.

The drawing can be edited using the methods ‘undo’, ‘clear’ and ‘close’, which are presented in a combobox.

draw.showLineDrawing(L)

Show a line drawing.

L is usually the return value of an interactive draw operation, but might also be set by the user.