6. gui.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.
6.1. Classes defined in module gui.draw¶
- class gui.draw.TempPalette(colormap=None)[source]¶
Context manager to set a temporary colormap for the canvas.
This can be used as follows:
M = Mesh(eltype='quad4').subdivide(3,2).setProp('range') with TempPalette([red,blue]): draw(M) # draws with only red and blue sleep(2) clear() draw(M) # draws with default colormap
If no colormap is specified (default), the context manager does nothing. This is convenient to use it as an optional colormap switcher.
6.2. Functions defined in module gui.draw¶
- gui.draw.ask(question, choices=None, **kargs)[source]¶
Ask a question and present possible answers.
Return answer if accepted or default if rejected. The remaining arguments are passed to
showMessage()
.
- gui.draw.ack(question, **kargs)[source]¶
Show a Yes/No question and return True/False depending on answer.
- gui.draw.showInfo(text, actions=['OK'], modal=True, **kargs)[source]¶
Show an informational message and wait for user acknowledgement.
- gui.draw.busyCursor()[source]¶
Context manager that changes the mouse cursor to a busy shape.
This can conveniently be used to display a busy cursor during execution of a block of statements that could take a long time to finish:
some_fast_code with busyCursor(): some_slow_code more_fast_code
- gui.draw.closeGui()[source]¶
Close the GUI.
Calling this function from a script closes the GUI and terminates pyFormex.
- gui.draw.closeDialog(name)[source]¶
Close the named dialog.
Closes the Dialog 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.
- gui.draw.showMessage(text, actions=['OK'], level='info', modal=True, align='00', **kargs)[source]¶
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.
- gui.draw.showWarning(text, actions=['OK'], **kargs)[source]¶
Show a warning message and wait for user acknowledgement.
- gui.draw.showError(text, actions=['OK'], **kargs)[source]¶
Show an error message and wait for user acknowledgement.
- gui.draw.showText(text, itemtype='text', actions=[('OK',)], modal=True, mono=False)[source]¶
Display a text in a dialog window.
Creates a dialog window displaying some text. The dialog can be modal (blocking user input to the main window) or modeless. Scrollbars are added if the text is too large to display at once. By default, the dialog has a single button to close the dialog.
- Parameters:
text (str) – A multiline text to be displayed. It can be plain text or html or reStructuredText (starting with ‘..’).
itemtype (str) – An
InputItem
type that can be used for text display. Currently this should be either ‘text’ of ‘info’.actions (list) – A list of action button definitions.
modal (bool) – If True, a modal dialog is constructed. Else, the dialog is modeless.
mono (bool) – If True, a monospace font will be used. This is only useful for plain text, e.g. to show the output of an external command.
- Returns:
If modal is True, the result of the dialog after closing.
This is a dictionary with a single key (‘text’ having the)
displayed text as a value. If an itemtype ‘text’ was used, it may
be a changed text.
If modal is False, return the open dialog window.
- gui.draw.showFile(filename, mono=None, **kargs)[source]¶
Display a text file.
Uses 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.
- gui.draw.showURL(url)[source]¶
Show an URL in the browser.
- Parameters:
url (URL) – The URL to be shown in the browser. The URL is checked with
utils.okURL()
. If this returns True, it is passed as parameter to the command configured in pf.cfg[‘browser’], which is executed as an external command without waiting for its result. Else, nothing is done.- Returns:
bool – True if
url
was actually passed to the browser command, False if not.
- gui.draw.showHtml(path=None, http=True)[source]¶
Show a local html file in the browser.
- Parameters:
path (path_like) – The path of the file to be displayed. This is normally a file with suffix .html. If not provided, a dialog is popped up to ask the user for a filename.
http (bool) – If True (default) a local web server is created to serve the file’s directory over http: protocol to the browser. If False, the file is directly served to the browser using the file: protocol.
Notes
Modern browsers with stricter security settings do not allow to include files (especially scripts) in the document that are coming from another origin. And with the file: protocol any other file, even in the same directory is considered another origin. Therefore the use of a web server and the http protocal is recommended and set as the default.
The browser command is configurable in the settings.
- gui.draw.showDoc(obj=None, rst=True, modal=False)[source]¶
Show the docstring of an object.
- Parameters:
obj (object) – Any object (module, class, method, function) that has a __doc__ attribute. If not provided, the docstring of the current script/app is shown.
rst (bool.) – If True (default) the docstring is treated as being reStructuredText and will be nicely formatted accordingly. If False, the docstring is shown as plain text.
- gui.draw.editFile(fn, exist=False)[source]¶
Load a file into the editor.
- Parameters:
Notes
Loading a file in the editor is done by executing an external command with the filename as argument. The command to be used can be set in the configuration. If it is not set, pyFormex will look at the EDITOR and VISUAL environment settings and use one of those.
The main author of pyFormex uses a custom script ‘edt’ as editor command, which either loads the files in a running copy of the Emacs editor, or starts a new Emacs session if none is running. Emacs
- gui.draw.askItems(items, *, modal=True, timeout=None, timeoutfunc=None, **kargs)[source]¶
Ask the value of some items to the user.
Create an interactive widget to let the user set the value of some items. The items are specified as a list of dictionaries. Each dictionary contains the input arguments for a widgets.InputItem. It is often convenient to use one of the _I, _G, ot _T functions to create these dictionaries. These will respectively create the input for a simpleInputItem, a groupInputItem or a tabInputItem.
For convenience, simple items can also be specified as a tuple. A tuple (key,value) will be transformed to a dict {‘key’:key, ‘value’:value}.
See
widgets.Dialog
and :widgets.InputItem for a more comprehensive description of the available arguments.A timeout (in seconds) can be specified to have the input dialog interrupted automatically and return the default values.
Also a timeoutfunc can be provided: it will be executed when the dialog times out.
The remaining arguments are keyword arguments that are passed to the widgets.Dialog.getResult method.
Returns 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.
- gui.draw.currentDialog()[source]¶
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.
- gui.draw.selectItems(choices, caption='Select from list', default=[], single=False, check=False, sort=False, **kargs)[source]¶
Ask the user to select one or more items from a list.
This is a convenience function presenting a dialog with a single input item: an InputList. It allows the user to select one or more items from a list.
- Returns:
list – A list with the selected items
- gui.draw.askFile(path=None, filter='all', *, mode='file', compr=False, timeout=None, caption=None, sidebar=None, extra=[], **kargs)[source]¶
Ask for one or more files using a customized file dialog.
Shows a modal
FileDialog
and allows the user to select file(s) according to the parameters. See theFileDialog
for the meaning of the parameters. The timeout parameter is passed toFileDialog.getresults()
.- Returns:
dict – A dict with the results of the
FileDialog
. If the user canceled the selection process, the dict is empty. If the user accepted the selection, the dict has at least a key ‘filename’ with the selection: a single Path, except for ‘multi’ mode, which returns a list of Path. More keys are present if the dialog contains more input items, either specified in the extra argument, or forced by some specific filter.
- gui.draw.askFilename(*args, **kargs)[source]¶
Ask for a file name or multiple file names using a file dialog.
- Parameters:
cur (path_like) – Path of the starting point of the selection dialog. It can be a directory or a file. All the files in the provided directory (or the file’s parent) that match the
filter
will be initially presented to the user. Ifcur
is a file, it will be set as the initial selection.filter (str or list of str) – Specifies a (set of) filter(s) to be applied on the files in the selected directory. This allows to narrow down the selection possibilities. The
filter
argument is passed through theutils.fileDescription()
function to create the actual filter set. If multiple filters are included, the user can switch between them in the dialog.mode (str) –
Determines what can be selected. One of:
’file’: select a file (existing or not). This is the default.
’exist’: select an existing file
’dir’: select an existing directory (widget allows to create a new)
’any’: select a file (existing or not) or a directory
’multi’: select multiple existing paths from the same directory
compr (bool) – If True, the specified filter pattern will be extended with the corresponding compressed file types. For example, a filter for ‘.pgf’ files will also allow to pick ‘.pgf.gz’ or ‘.pgf.bz2’ files.
change (bool) – If True (default), the current working directory will be changed to the parent directory of the selection.
caption (str) – A string to be displayed as the dialog title instead of the default one.
timeout (float) – If provided, the dialog will timeout after the specified number of seconds.
sidebar (list of path_like.) – If provided, these will be added to the sidebar (in addition to the configured paths).
kargs (keyword arguments) – More arguments to be passed to the FileDialog.
- Returns:
Path | list of Paths | None – The selected file Path(s) if the user accepted the dialog, or None if the user canceled the dialog.
- gui.draw.askNewFilename(cur=None, filter='All files (*.*)', compr=False, timeout=None, caption=None, sidebar=None, **kargs)[source]¶
Ask a single new filename.
This is a convenience function for calling askFilename with the argument exist=False.
- gui.draw.askDirname(path=None, change=True, byfile=False, **kargs)[source]¶
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.
- gui.draw.checkWorkdir()[source]¶
Ask the user to change the current workdir if it is not writable.
Returns True if the current workdir is writable.
- gui.draw.printc(*args, color=None, sep=' ', end='\n')[source]¶
Print in color to the console.
- Parameters:
*args – The things to be printed. Every argument is converted to a string using
str()
. The strings are joined using the separator sep and the end separator end is appended. The resulting string is printed to the console with the specified color.color (int | color_like) – The color to use when displaying the string. It can be anything that is accepted by QColor or an int. If an int, it is used as index in the current palette: pf.canvas.settings.colormap.
sep (str) – The separator between printed items in a single call.
end (str) – The separator added at the end of each call.
- gui.draw.printMessage(*args, color=None, sep=' ', end='\n')¶
Print in color to the console.
- Parameters:
*args – The things to be printed. Every argument is converted to a string using
str()
. The strings are joined using the separator sep and the end separator end is appended. The resulting string is printed to the console with the specified color.color (int | color_like) – The color to use when displaying the string. It can be anything that is accepted by QColor or an int. If an int, it is used as index in the current palette: pf.canvas.settings.colormap.
sep (str) – The separator between printed items in a single call.
end (str) – The separator added at the end of each call.
- gui.draw.delay(s=None)[source]¶
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.
- gui.draw.wait(relock=True)[source]¶
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. The use of this function is prefered over that of
pause()
orsleep()
, 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 and view.
- gui.draw.replay()[source]¶
Replay the current app.
This works pretty much like the play() function, but will reload the current application prior to running it. This function is especially interesting during development of an application. If the current application is a script, then it is equivalent with play().
- gui.draw.fforward()[source]¶
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.
- gui.draw.pause(timeout=None, msg=None)[source]¶
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 PLAY, STEP or CONTINUE button will produce such an event.
timeout: float: if specified, the pause will only last for this many seconds. It can still be interrupted by the STEP buttons.
msg: string: a message to write to the board to explain the user about the pause
- gui.draw.sleep(duration, granularity=0.01, func=None)[source]¶
Hold execution for some duration
This holds the execution of the thread where the function is called for the specified time (in seconds).
See also
Notes
Because of the setup of the operation, in case of very small duration times the actual duration may be considerably longer than the specified value. If the sleep is intended to slow down drawing instructions, you may consider the use of
delay()
. Even if you do not have a draw function in the block you want to delay, aview()
function could be added to apply the delay. Normally you should set granularity < duration.
- gui.draw.do_after(sec, func)[source]¶
Call a function in another thread after a specified elapsed time.
- Parameters:
sec (float) – Time in seconds to wait before starting the execution. As the function will be executed in a separate thread, the calling thread will immediately continue.
func (callable) – The function (or bound method) to be called.
- gui.draw.runLongTask(args, finished='info', **kargs)[source]¶
Run a long lasting subprocess without blocking the GUI
- gui.draw.zoomObj(object)[source]¶
Zoom thus that the specified object becomes visible.
object can be anything having a bbox() method or a list thereof.
- gui.draw.focus(point)[source]¶
Move the camera focus to the specified point.
- Parameters:
point (array_like) – A float (3,) array with the coordinates of the point that the camera should center on while keeping all other camera parameters unchanged. The focus point becomes the center of the screen and the center of camera rotations.
- gui.draw.flyAlong(path, upvector=[0.0, 1.0, 0.0], sleeptime=None)[source]¶
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.
- gui.draw.viewport(n=None)[source]¶
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
- gui.draw.layout(nvps=None, ncols=None, nrows=None, pos=None, rstretch=None, cstretch=None, reset=False)[source]¶
Set the viewports layout.
See
MultiCanvas.changeLayout()
.
- gui.draw.linkViewport(vp, tovp)[source]¶
Link viewport vp to viewport tovp.
Both vp and tovp should be numbers of viewports.
- gui.draw.pickProps(filter=None, oneshot=False, func=None, pickable=None, prompt=None)[source]¶
Pick property numbers
This is like pick(‘element’), but returns the (unique) property numbers of the picked elements of the actors instead.
- gui.draw.pickFocus()[source]¶
Enter interactive focus setting.
This enters interactive point picking mode and sets the focus to the center of the picked points.
- gui.draw.drawLinesInter(mode='line', single=False, func=None)[source]¶
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.
- gui.draw.showLineDrawing(L)[source]¶
Show a line drawing.
L is usually the return value of an interactive draw operation, but might also be set by the user.
- gui.draw.exportWebGL(fn, createdby=50, **kargs)[source]¶
Export the current scene to WebGL.
Parameters:
fn : string: the (relative or absolute) filename of the .html, .js and .pgf files comprising the WebGL model. It can contain a directory path and any extension. The latter is dropped and not used.
createdby: int: width in pixels of the ‘Created by pyFormex’ logo appearing on the page. If < 0, the logo is displayed at its natural width. If 0, the logo is suppressed.
**kargs: any other keyword parameteris passed to the
WebGL
initialization. The name can not be specified: it is derived from the fn parameter.
Returns the absolute pathname of the generated .html file.
- gui.draw.multiWebGL(name=None, fn=None, title=None, description=None, keywords=None, author=None, createdby=50)[source]¶
Export the current scene to WebGL.
fn is the (relative or absolute) pathname of the .html and .js files to be created.
When the export is finished, returns the absolute pathname of the generated .html file. Else, returns None.
- gui.draw.resetGUI()[source]¶
Reset the GUI to its default operating mode.
When an exception is raised during the execution of a script, the GUI may be left in a non-consistent state. This function may be called to reset most of the GUI components to their default operating mode.
- gui.draw.flatten(objects, recurse=True)[source]¶
Flatten a list of 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.
- gui.draw.drawn_as(object)[source]¶
Check how an object can be drawn.
An object can be drawn (using
draw()
) if it has a method ‘actor’, ‘toFormex’ or ‘toMesh’. In the first case, it has a nativeActor
, else, it is first transformed toFormex
orMesh
.- Parameters:
object (any object, though usually a
Geometry
instance) – An object to check for a drawing method.- Returns:
object (drawabable object or None) – If the object is drawable (directly or after conversion), returns a directly drawable object, else None.
- gui.draw.drawable(objects)[source]¶
Filters the drawable objects from a list of objects.
- Parameters:
objects (list or sequence of objects.) – The list of objects to filter for drawable objects.
- Returns:
list of objects – The list of objects that can be drawn.
- gui.draw.draw(F, clear=None, **kargs)[source]¶
Draw geometrical object(s) with specified drawing options and settings.
This is the generic drawing function in pyFormex. The function requires a single positional parameter specifying the geometry to be drawn. There are also a whole lot of optional keyword parameters, divided in two groups.
The first are the drawing options, which modify the way the draw function operates. If not specified, or a value None is specified, they are filled in from the current viewport drawing options, which can be changed using the
setDrawOptions()
function. The initial defaults are: clear=False, view=’last’, bbox=’auto’, shrink=False, shrinkfactor=0.8, wait=True, silent=True, single=False.The second group are rendering attributes that define the way the geometrical objects should be rendered. These have default values in
canvas.Canvas.settings
, and can be overridden per object by the object’s attrib() settings. These options are listed below under Notes.- Parameters:
F (object or list of objects) – The object(s) to be drawn. It can be a single item or a (possibly nested) list of items. The list will be flattened. Strings are looked up in the pyFormex global project dictionary and replaced with their value. Nondrawable objects are filtered out from the list (see also option
silent
). The resulting list of drawable objects is processed with the same drawing options and default rendering atributes.clear (bool, optional) – If True, the scene is cleared before drawing. The default is to add to the existing scene.
view (str) – Either the name of a defined view or ‘last’. This defines the orientation of the camera looking at the drawn objects. Predefined views are ‘front’, ‘back’, ‘top’, ‘bottom’, ‘left’, ‘right’, ‘iso’ and a whole list of other ones. * TODO: we should expand this * On creation of a viewport, the initial default view is ‘front’ (looking in the -z direction). With view=’last’, the camera angles will be set to the same camera angles as in the last draw operation, undoing any interactive changes. With view=None the camera settings remain unchanged (but still may be changed interactively through the user interface). This may make the drawn object out of view. See also
bbox
.bbox (array_like or str) – Specifies the 3D volume at which the camera will be aimed (using the angles set by
view
). The camera position will be set thus 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. This is the default when creating a new viewport. A value bbox=None will use the bounding box of the previous drawing operation, thus ensuring that the camera’s target volume is unchanged.shrink (bool) – If specified, each object will be transformed by the
Coords.shrink()
transformation (with the default or specified shrink_factor as a parameter), thus showing all the elements of the object separately (sometimes called an ‘exploded’ view).shrink_factor (float) – Overrides the default shrink_factor for the current draw operation. If provided, it forces
shrink=True
.wait (bool) – If True (initial default), the 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 renderings and is far more efficient than adding an explicit sleep() operation, because the script processing can continue up to the next drawing instruction. The value of drawdelay can be changed in the user settings or using the
delay()
function. Setting this value to 0 will disable the waiting mechanism for all subsequent draw statements (until set > 0 again). But often the user wants to specifically disable the waiting lock for some draw operation(s). This can be done without changing the drawdelay setting, by specifying wait=False. This means that the next draw operation does not have to wait.silent (bool) – If True (initial default), non-drawable objects are silently ignored. If set False, an error is raised if
F
contains an object that is not drawable.single (bool, optional) – If True, the return value will be a single Actor, corresponding with the first drawable object in the flattened list of
F
. The remainder of the drawable objects inF
are then set as children of the main return value. The default is to return a single Actor if F is a single drawable object, or a list of Actors if F is a list.kargs (keyword parameters) – The remaining keyword parameters are the default rendering attributes to be used for all the objects in
F
. They will apply unless overridden by attributes set in the object itself (seegeometry.Geometry.attrib()
). There is a long list of possible settings. The important ones are listed below (see Notes).
- Returns:
Actor
or list of Actors – If F is a single object orsingle==True
was provided, returns a single Actor instance. If F is a list andsingle==True
was not set, a list a Actors is returned.
Notes
This section is incomplete and needs an update *
Here is an (incomplete) list of rendering attributes that can be provided to the draw function and will be used as defaults for drawing the objects that do not have the needed values set as attributes on the object itself. While the list is long, in most cases only a few are used, and the remainder are taken from the canvas rendering defaults.
These arguments will be passed to the corresponding Actor for the object. The Actor is the graphical representation of the geometry. Not all Actors use all of the settings that can be specified here. But they all accept specifying any setting even if unused. The settings hereafter are thus a superset of the settings used by the different Actors. Settings have a default value per viewport, and if unspecified, most Actors will use the viewport default for that value.
color, colormap: specify the color of the object (see below)
alpha: float (0.0..1.0): alpha value to use in transparent mode. 0.0 means fully transparent (invisible), while 1.0 means opaque.
bkcolor, bkcolormap: color for the backside of surface type geometry, if it is to be different from the front side. Specifications are as for front color and colormap.
bkalpha: float (0.0..1.0): transparency alphe value for the back side.
linewidth: float, thickness of line drawing
linestipple: stipple pattern for line drawing
marksize: float: point size for dot drawing
nolight: bool: render object as unlighted in modes with lights on
ontop: bool: render object as if it is on top. This will make the object fully visible, even when it is hidden by other objects. If more than one objects is drawn with ontop=True the visibility of the object will depend on the order of drawing.
Specifying color: Color specification can take many different forms. Some Actors recognize up to six different color modes and the draw function adds even another mode (property color)
no color: color=None. The object will be drawn in the current viewport foreground color.
single color: the whole object is drawn with the specified color.
element color: each element of the object has its own color. The specified color will normally contain precisely nelems colors, but will be resized to the required size if not.
vertex color: each vertex of each element of the object has its color. In smooth shading modes intermediate points will get an interpolated color.
element index color: like element color, but the color values are not specified directly, but as indices in a color table (the colormap argument).
vertex index color: like vertex color, but the colors are indices in a color table (the colormap argument).
property color: as an extra mode in the draw function, if color=’prop’ is specified, and the object has an attribute ‘prop’, that attribute will be used as a color index and the object will be drawn in element index color mode. If the object has no such attribute, the object is drawn in no color mode.
Hey! What about nodal color? When drawing a
Mesh
, it is possible to draw with colors that are specified on the nodes instead of on the elements. To do that, just expand the colors to the element nodes as follows.M
is aMesh
, ncolors is an array containingM.ncoords()
colors or color indices:draw(M, color=ncolors[M.elems])
Element and vertex color modes are usually only used with a single object in the F parameter, because they require a matching set of colors. Though the color set will be automatically resized if not matching, the result will seldomly be what the user expects. If single colors are specified as a tuple of three float values (see below), the correct size of a color array for an object with nelems elements of plexitude nplex would be: (nelems,3) in element color mode, and (nelems,nplex,3) in vertex color mode. In the index modes, color would then be an integer array with shape respectively (nelems,) and (nelems,nplex). Their values are indices in the colormap array, which could then have shape (ncolors,3), where ncolors would be larger than the highest used value in the index. If the colormap is insufficiently large, it will again be wrapped around. If no colormap is specified, the current viewport colormap is used. The default contains eight colors: black=0, red=1, green=2, blue=3, cyan=4, magenta=5, yellow=6, white=7.
A color value can be specified in multiple ways, but should be convertible to a normalized OpenGL color using the
colors.GLcolor()
function. The normalized color value is a tuple of three values in the range 0.0..1.0. The values are the contributions of the red, green and blue components.
- gui.draw.setDrawOptions(kargs0={}, **kargs)[source]¶
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.
- gui.draw.setShrink(shrink=None)[source]¶
Set shrink mode on or off, and optionally the shrink factor.
In shrink mode, all elements are drawn shrinked around their centroid. This results in an exploded view showing individual elements and permitting look through the inter-element gaps to what is behind.
- Parameters:
shrink (float | bool | None) – If a float, switches shrink mode on and sets the shrink factor to the provided value. If True, switches on shrink mode with the current shrink factor (see notes). If False, switches off shrink mode.
Notes
Useful values for the shrink factor are in the range 0.0 to 1.0. The initial value is 0.8. The current shrink status and factor are stored in
pf.canvas.drawoptions['shrink_factor']
.
- gui.draw.drawVectors(P, v, size=None, nolight=True, **drawOptions)[source]¶
Draw a set of vectors.
If size is 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.
- gui.draw.drawMarks(X, M, *, colors=None, prefix='', ontop=True, fuse=False, color='black', **kargs)[source]¶
Draw a list of marks at points X.
- Parameters:
X (Coords) – The 3D coordinates of the points where to insert the marks.
M (list of str) – List of text marks to draw at points X. If the list is shorter than the array X, the list is cycled. If the list is longer, it is cut at the length of X. The string representation of the
colors (list of color_like) – List of colors to be used for the subsequent marks. If not long enough, the list will be cycled. If not provided, all marks are drawn with the same color, specified with the
color
argument, which defaults to the current foreground color. Ifcolors
is provided, it overrides any specifiedcolor
value and sets thetexmode
argument to 5.prefix (str, optional) – If specified, this string is prepended to all drawn strings.
ontop (bool, optional) – If True (default), the marks are drawn on top, meaning they will all be visible, even those drawn at points hidden by the geometry. If False, marks at hidden points can be hidden by the drawn geometry.
fuse (bool, optional) – If True, the drawing positions X will be fused, and marks for the fused points will be collected in a single string separated by commas. If False (default), labels at the same position are drawn on top of each other, likely making them unreadable. Note that using
fuse=True
together with acolors
list may garble up the order of the colors.**kargs – Other parameters that will be passed to the
actors.TextArray
class.
- Returns:
TextArray – The drawn actor.
- gui.draw.drawNumbers(G, numbers=None, *, offset=0, trl=None, ontop=True, **kargs)[source]¶
Draw numbers on all elements of a Geometry G.
- Parameters:
G (Coords | Geometry) – A Coords or Geometry (or any class having a ‘centroids’ method that returns a Coords. Specifies the coordinates of the points where the numbers are drawn.
numbers (int array_like, optional) – The numbers to be drawn at the points of G An int array of length G.nelems(). If not provided, the range from 0 to G.nelems()-1 is used.
offset (int, optional) – If provided, this constant value is added to the numbers. This can e.g. be used to create an image for comparison with systems using base 1 numbering.
trl (vector_like, optional) – If provided, the drawing positions are the centroids of G translated over this vector.
ontop (bool, optional) – If True, the marks are drawn on top, meaning they will all be visible, even those drawn at points hidden by the geometry. If False, marks at hidden points can be hidden by the drawn geometry. If None, the value of the configuration variable draw/numbersontop is used.
kargs (optional) – Other keywork parameters are passed to the
drawMarks()
function for doing the real work.
- gui.draw.drawPropNumbers(F, **kargs)[source]¶
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.
- gui.draw.drawVertexNumbers(F, color='black', trl=None, ontop=False)[source]¶
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.
- gui.draw.drawBbox(F, *, actor=None, color='black', **kargs)[source]¶
Draw the bounding box of the Geometry object F.
- Parameters:
F (Geometry) – Any object that has a ‘bbox’ method to compute its bounding box.
actor ('bbox' | 'grid') – The type of actor to be used to represent the bounding box. ‘bbox’ is simple cuboid drawn in line mode. ‘grid’ is a more complex actor that can show a series of planes and or lines. The default can be configured in the user settings.
- Returns:
The drawn Annotation(s).
- gui.draw.drawBboxGrid()[source]¶
Draw a grid in the bbox of the Geometry object F.
F is any object that has a bbox method. Returns the drawn Annotation.
- gui.draw.drawText(text, pos, **kargs)[source]¶
Draw a text at a given canvas or world position.
Draws a text at a given position. The position can be either a 2D canvas position, specified in pixel coordinates (int), or a 3D position, specified in global world coordinates (float). In the latter case the text is displayed on the canvas at the projected world point, and will move with that projection, while keeping the text unscaled and oriented to the viewer. The 3D mode is especially useful to annotate parts of the geometry with a label.
- Parameters:
text (str) – The string to be displayed
pos (array_like) – Defines where to show the text. Either a (2,) int array with the (fixed) canvas coordinates, or a (3,) float array with the world coordinates.
**kargs – Other parameters to be passed to
opengl.textext.Text
.
- gui.draw.drawAxes(cs=None, **kargs)[source]¶
Draw the axes of a coordinate system.
- Parameters:
cs (
coordsys.CoordSys
) – The coordinate system for which to draw the axes. If not specified, the global coordinate system is used.**kargs – Other arguments to be passed to the
candy.Axes()
. The defaults draw the positive parts of the axes in the colors R,G,B and the negative parts in C,M,Y.
- Returns:
List – The list of Actors drawn.
- gui.draw.drawPrincipal(F, weight=None, **kargs)[source]¶
Draw the principal axes of the geometric object F.
F is Coords or Geometry. If weight is specified, it is an array of weights attributed to the points of F. It should have the same length as F.coords. Other parameter are drawing attributes passed to
drawAxes()
.
- gui.draw.drawImage3D(image, nx=0, ny=0, pixel='dot')[source]¶
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 interactively handling and transforming the image using the OpenGL infrastructure.
- Parameters:
image – QImage or any data that can be converted to a QImage, e.g. the name of a raster image file.
nx (int, int) – Width and height the displayed image. If the provided image has a different size, it will be rescaled. Values <= 0 will be replaced with the corresponding actual size of the image.
ny (int, int) – Width and height the displayed image. If the provided image has a different size, it will be rescaled. Values <= 0 will be replaced with the corresponding actual size of the image.
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’.
- Returns:
An Actor with a the drawn image.
See also
drawImage()
.
- gui.draw.drawImage(image, w=0, h=0, x=-1, y=-1, color='white', ontop=False)[source]¶
Draws an image as a viewport decoration.
Parameters:
image: a QImage or any data that can be converted to a QImage, e.g. the name of a raster image file. See also the
loadImage()
function.w,`h`: width and height (in pixels) of the displayed image. If the supplied image has a different size, it will be rescaled. A value <= 0 will be replaced with the corresponding actual size of the image.
x,`y`: position of the lower left corner of the image. If negative, the image will be centered on the current viewport.
color: the color to mix in (AND) with the image. The default (white) will make all pixels appear as in the image.
ontop: determines whether the image will appear as a background (default) or at the front of the 3D scene (as on the camera glass).
Returns the Decoration drawn.
Note that the Decoration has a fixed size (and position) on the canvas and will not scale when the viewport size is changed. The
bgcolor()
function can be used to draw an image that completely fills the background.
- gui.draw.drawField(fld, comp=0, scale='RAINBOW', symmetric_scale=False, cvalues=None, clageom=None, **kargs)[source]¶
Draw intensity of a scalar field over a Mesh.
- Parameters:
fld (
Field
) – A Field, specifying some value over a Geometry.comp (int, optional) – Required if fld is a vectorial Field: specifies the component that is to be drawn.
scale (str) – One of the color palettes defined in
colorscale
. If an empty string is specified, the scale is not drawn.symmetric_scale (bool) – If True the mid value of the color scale will be set to the value corresponding to the middle value of the fld data range. If False the mid value of the color scale will be set to 0.0 if the range extends over negative and positive values.
cvalues (list, optional) – Specifies the min, max and mid values between which to span the color palette. It can be a list of 2 values (min, max) or 3 values (min, mid, max). If not provided, the values are taken from the field data.
clageom (list of int, optional) – If provided, it is a list of four integers (x, y, w, h) specifying the position and size (in pixels) of the colorscale. The default size is a height of 200 (adjusted down if the canvas is not high enough) and positioned near the lower left corner of the canvas.
**kargs – Other keyword arguments are passed to the draw function to draw the Geometry.
colors. (Draws the Field's Geometry with the Field data converted to) –
values. (A color legend is added to convert colors to) –
numpy.nan_to_num. (NAN data are converted to numerical values using) –
- gui.draw.undraw(items)[source]¶
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.
- gui.draw.view(v, wait=True)[source]¶
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.
- gui.draw.createView(name, angles, addtogui=False)[source]¶
Create a new named view (or redefine an old).
The angles are (longitude, latitude, twist). The named view is global to all viewports. If addtogui is True, a view button to set this view is added to the GUI.
- gui.draw.setView(name, angles=None)[source]¶
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).
- gui.draw.setTriade(on=None, pos='lb', siz=50, triade=None)[source]¶
Toggle the display of the global axes on or off.
This is a convenient feature to display the global axes directions with rotating actor at fixed viewport size and position.
Parameters:
on: boolean. If True, the global axes triade is displayed. If False, it is removed. The default (None) toggles between on and off. The remaining parameters are only used on enabling the triade.
pos: string of two characters. The characters define the horizontal (one of ‘l’, ‘c’, or ‘r’) and vertical (one of ‘t’, ‘c’, ‘b’) position on the camera’s viewport. Default is left-bottom.
siz: size (in pixels) of the triade.
triade: None, Geometry or str: defines the Geometry to be used for representing the global axes.
If None: use the previously set triade, or set a default if no previous.
If Geometry: use this to represent the axes. To be useful and properly displayed, the Geometry’s bbox should be around [(-1,-1,-1),(1,1,1)]. Drawing attributes may be set on the Geometry to influence the appearance. This allows to fully customize the Triade.
If str: use one of the predefined Triade Geometries. Currently, the following are available:
‘axes’: axes and coordinate planes as in
candy.Axes
‘man’: a model of a man as in data file ‘man.pgf’
- gui.draw.setGrid(on=None, d=None, s=None, **kargs)[source]¶
Toggle the display of the canvas grid on or off.
- Parameters:
on (bool.) – If True, the grid is displayed. If False, it is removed. The default (None) toggles between on and off.
d (None, int or (int,int), optional) – Only used when
on==True
. Distance in pixels between the grid lines. A tuple of two values specifies the distance in x,y direction. If not specified, the previous grid is used, or a default grid with d=100 is created.s (None, int or (int,int), optional) – Only used when
on==True
. The grid size in pixels. A tuple of two values specifies size in x,y direction. If not specified the size is set equal to the desktop screen size. This allows resizing the window while still seeing the grid on the full canvas.kargs (optional) –
Extra drawing parameters that influence the appearance of the grid. Example:
setGrid(d=200,linewidth=3,color=red,ontop=True)
Notes
This is a convenient function to display a grid on the canvas. The grid may someday become an integral part of the Canvas.
- gui.draw.bgcolor(color=None, image=None)[source]¶
Change the background color and image.
Parameters:
color: a single color or a list of 4 colors. A single color sets a solid background color. A list of four colors specifies a gradient. These 4 colors are those of the Bottom Left, Bottom Right, Top Right and Top Left corners respectively.
image: the name of an image file. If specified, the image will be overlayed on the background colors. Specify a solid white background color to sea the image unaltered.
- gui.draw.renderMode(mode, light=None)[source]¶
Change the rendering profile to a predefined mode.
Currently the following modes are defined:
wireframe
smooth
smoothwire
flat
flatwire
smooth_avg
- gui.draw.wireMode(mode)[source]¶
Change the wire rendering mode.
Currently the following modes are defined: ‘none’, ‘border’, ‘feature’,’all’
- gui.draw.set_material_value(typ, val)[source]¶
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
- gui.draw.canvasSize(width, height)[source]¶
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 changing the canvas size when multiple viewports are active is not approved.