- sb = servermanager.rendering.ScalarBarWidgetRepresentation()
- servermanager.Register(sb)
- sb.Selectable = 1
- sb.Resizable = 1
- sb.Enabled = 1
- sb.Title = "Scalars"
- SetProperties(sb, **params)
- return sb
-
-# TODO: Change this to take the array name and number of components. Register
-# the lt under the name ncomp.array_name
-def MakeBlueToRedLT(min, max):
- # Define RGB points. These are tuples of 4 values. First one is
- # the scalar values, the other 3 the RGB values.
- rgbPoints = [min, 0, 0, 1, max, 1, 0, 0]
- return CreateLookupTable(RGBPoints=rgbPoints, ColorSpace="HSV")
-
-def _find_writer(filename):
- """Internal function."""
- extension = None
- parts = filename.split('.')
- if len(parts) > 1:
- extension = parts[-1]
- else:
- raise RuntimeError, "Filename has no extension, please specify a write"
-
- if extension == 'png':
- return 'vtkPNGWriter'
- elif extension == 'bmp':
- return 'vtkBMPWriter'
- elif extension == 'ppm':
- return 'vtkPNMWriter'
- elif extension == 'tif' or extension == 'tiff':
- return 'vtkTIFFWriter'
- elif extension == 'jpg' or extension == 'jpeg':
- return 'vtkJPEGWriter'
- else:
- raise RuntimeError, "Cannot infer filetype from extension:", extension
-
-def AddCameraLink(viewProxy, viewProxyOther, linkName):
- """Create a camera link between two view proxies. A name must be given
- so that the link can be referred to by name. If a link with the given
- name already exists it will be removed first."""
- if not viewProxyOther: viewProxyOther = GetActiveView()
- link = servermanager.vtkSMCameraLink()
- link.AddLinkedProxy(viewProxy.SMProxy, 1)
- link.AddLinkedProxy(viewProxyOther.SMProxy, 2)
- link.AddLinkedProxy(viewProxyOther.SMProxy, 1)
- link.AddLinkedProxy(viewProxy.SMProxy, 2)
- RemoveCameraLink(linkName)
- servermanager.ProxyManager().RegisterLink(linkName, link)
-
-def RemoveCameraLink(linkName):
- """Remove a camera link with the given name."""
- servermanager.ProxyManager().UnRegisterLink(linkName)
-
-def WriteImage(filename, view=None, **params):
- """Saves the given view (or the active one if none is given) as an
- image. Optionally, you can specify the writer and the magnification
- using the Writer and Magnification named arguments. For example:
- WriteImage("foo.mypng", aview, Writer=vtkPNGWriter, Magnification=2)
- If no writer is provided, the type is determined from the file extension.
- Currently supported extensions are png, bmp, ppm, tif, tiff, jpg and jpeg.
- The writer is a VTK class that is capable of writing images.
- Magnification is used to determine the size of the written image. The size
- is obtained by multiplying the size of the view with the magnification.
- Rendering may be done using tiling to obtain the correct size without
- resizing the view."""
- if not view:
- view = active_objects.view
- writer = None
- if params.has_key('Writer'):
- writer = params['Writer']
- mag = 1
- if params.has_key('Magnification'):
- mag = int(params['Magnification'])
- if not writer:
- writer = _find_writer(filename)
- view.WriteImage(filename, writer, mag)
-
-def AnimateReader(reader=None, view=None, filename=None):
- """This is a utility function that, given a reader and a view
- animates over all time steps of the reader. If the optional
- filename is provided, a movie is created (type depends on the
- extension of the filename."""
- if not reader:
- reader = active_objects.source
- if not view:
- view = active_objects.view
-
- return servermanager.AnimateReader(reader, view, filename)
-
-
-def _create_func(key, module):
- """Internal function."""
-
- def CreateObject(*input, **params):
- """This function creates a new proxy. For pipeline objects that accept inputs,
- all non-keyword arguments are assumed to be inputs. All keyword arguments are
- assumed to be property,value pairs and are passed to the new proxy."""
-
- # Instantiate the actual object from the given module.
- px = module.__dict__[key]()
-
- # Make sure non-keyword arguments are valid
- for inp in input:
- if inp != None and not isinstance(inp, servermanager.Proxy):
- if px.GetProperty("Input") != None:
- raise RuntimeError, "Expecting a proxy as input."
- else:
- raise RuntimeError, "This function does not accept non-keyword arguments."
-
- # Assign inputs
- if px.GetProperty("Input") != None:
- if len(input) > 0:
- px.Input = input
- else:
- # If no input is specified, try the active pipeline object
- if px.GetProperty("Input").GetRepeatable() and active_objects.get_selected_sources():
- px.Input = active_objects.get_selected_sources()
- elif active_objects.source:
- px.Input = active_objects.source
- else:
- if len(input) > 0:
- raise RuntimeError, "This function does not expect an input."
-
- registrationName = None
- for nameParam in ['registrationName', 'guiName']:
- if nameParam in params:
- registrationName = params[nameParam]
- del params[nameParam]
-
- # Pass all the named arguments as property,value pairs
- for param in params.keys():
- setattr(px, param, params[param])
-
- try:
- # Register the proxy with the proxy manager.
- if registrationName:
- group, name = servermanager.Register(px, registrationName=registrationName)
- else:
- group, name = servermanager.Register(px)
-
-
- # Register pipeline objects with the time keeper. This is used to extract time values
- # from sources. NOTE: This should really be in the servermanager controller layer.
- if group == "sources":
- has_tk = True
- try:
- tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
- except IndexError:
- has_tk = False
- if has_tk:
- sources = tk.TimeSources
- if not px in sources:
- sources.append(px)
-
- active_objects.source = px
- except servermanager.MissingRegistrationInformation:
- pass
-
- return px
-
- return CreateObject
-
-def _create_doc(new, old):
- """Internal function."""
- import string
- res = ""
- for doc in (new, old):
- ts = []
- strpd = doc.split('\n')
- for s in strpd:
- ts.append(s.lstrip())
- res += string.join(ts)
- res += '\n'
- return res
-
-def _func_name_valid(name):
- """Internal function."""
- valid = True
- for c in name:
- if c == '(' or c ==')':
- valid = False
- break
- return valid
-
-def _add_functions(g):
- activeModule = servermanager.ActiveConnection.Modules
- for m in [activeModule.filters, activeModule.sources,
- activeModule.writers, activeModule.animation]:
- dt = m.__dict__
- for key in dt.keys():
- cl = dt[key]
- if not isinstance(cl, str):
- if not key in g and _func_name_valid(key):
- g[key] = _create_func(key, m)
- exec "g[key].__doc__ = _create_doc(m.%s.__doc__, g[key].__doc__)" % key
-
-def _remove_functions(g):
- list = []
- if servermanager.ActiveConnection:
- list = [m for m in dir(servermanager.ActiveConnection.Modules) if m[0] != '_']
-
- for m in list:
- dt = servermanager.ActiveConnection.Modules.__dict__[m].__dict__
- for key in dt.keys():
- cl = dt[key]
- if not isinstance(cl, str) and g.has_key(key):
- g.pop(key)
- #print "remove %s function" % key
-
-def GetActiveView():
- """Returns the active view."""
- return active_objects.view
-
-def SetActiveView(view):
- """Sets the active view."""
- active_objects.view = view
-
-def GetActiveSource():
- """Returns the active source."""
- return active_objects.source
-
-def SetActiveSource(source):
- """Sets the active source."""
- active_objects.source = source
-
-def GetActiveCamera():
- """Returns the active camera for the active view. The returned object
- is an instance of vtkCamera."""
- return GetActiveView().GetActiveCamera()
-
-def GetAnimationScene():
- """Returns the application-wide animation scene. ParaView has only one
- global animation scene. This method provides access to that. Users are
- free to create additional animation scenes directly, but those scenes
- won't be shown in the ParaView GUI."""
- animation_proxies = servermanager.ProxyManager().GetProxiesInGroup("animation")
- scene = None
- for aProxy in animation_proxies.values():
- if aProxy.GetXMLName() == "AnimationScene":
- scene = aProxy
- break
- if not scene:
- raise servermanager.MissingProxy, "Could not locate global AnimationScene."
- return scene
-
-def WriteAnimation(filename, **params):
- """Writes the current animation as a file. Optionally one can specify
- arguments that qualify the saved animation files as keyword arguments.
- Accepted options are as follows:
- * Magnification (integer) : set the maginification factor for the saved
- animation.
- * Quality (0 [worst] or 1 or 2 [best]) : set the quality of the generated
- movie (if applicable).
- * Subsampling (integer) : setting whether the movie encoder should use
- subsampling of the chrome planes or not, if applicable. Since the human
- eye is more sensitive to brightness than color variations, subsampling
- can be useful to reduce the bitrate. Default value is 0.
- * BackgroundColor (3-tuple of doubles) : set the RGB background color to
- use to fill empty spaces in the image.
- * FrameRate (double): set the frame rate (if applicable)."""
- scene = GetAnimationScene()
- # ensures that the TimeKeeper track is created.
- GetTimeTrack()
- iw = servermanager.vtkSMAnimationSceneImageWriter()
- iw.SetAnimationScene(scene.SMProxy)
- iw.SetFileName(filename)
- if params.has_key("Magnification"):
- iw.SetMagnification(int(params["Magnification"]))
- if params.has_key("Quality"):
- iw.SetQuality(int(params["Quality"]))
- if params.has_key("Subsampling"):
- iw.SetSubsampling(int(params["Subsampling"]))
- if params.has_key("BackgroundColor"):
- iw.SetBackgroundColor(params["BackgroundColor"])
- if params.has_key("FrameRate"):
- iw.SetFrameRate(float(params["FrameRate"]))
- iw.Save()
-
-def _GetRepresentationAnimationHelper(sourceproxy):
- """Internal method that returns the representation animation helper for a
- source proxy. It creates a new one if none exists."""
- # ascertain that proxy is a source proxy
- if not sourceproxy in GetSources().values():
- return None
- for proxy in servermanager.ProxyManager():
- if proxy.GetXMLName() == "RepresentationAnimationHelper" and\
- proxy.GetProperty("Source").IsProxyAdded(sourceproxy.SMProxy):
- return proxy
- # create a new helper
- proxy = servermanager.misc.RepresentationAnimationHelper(
- Source=sourceproxy)
- servermanager.ProxyManager().RegisterProxy(
- "pq_helper_proxies.%s" % sourceproxy.GetGlobalIDAsString(),
- "RepresentationAnimationHelper", proxy)
- return proxy
-
-def GetAnimationTrack(propertyname_or_property, index=None, proxy=None):
- """Returns an animation cue for the property. If one doesn't exist then a
- new one will be created.
- Typical usage:
- track = GetAnimationTrack("Center", 0, sphere) or
- track = GetAnimationTrack(sphere.GetProperty("Radius")) or
-
- # this returns the track to animate visibility of the active source in
- # all views.
- track = GetAnimationTrack("Visibility")
-
- For animating properties on implicit planes etc., use the following
- signatures:
- track = GetAnimationTrack(slice.SliceType.GetProperty("Origin"), 0) or
- track = GetAnimationTrack("Origin", 0, slice.SliceType)
-