- pfunc = servermanager.piecewise_functions.PiecewiseFunction()
- servermanager.Register(pfunc)
- SetProperties(pfunc, **params)
- return pfunc
-
-def CreateScalarBar(**params):
- """Create and return a scalar bar widget. The returned widget may
- be added to a render view by appending it to the view's representations
- The widget must have a valid lookup table before it is added to a view.
- It is possible to pass the lookup table (and other properties) as arguments
- to this method:
-
- lt = MakeBlueToRedLt(3.5, 7.5)
- bar = CreateScalarBar(LookupTable=lt, Title="Velocity")
- GetRenderView().Representations.append(bar)
-
- By default the returned widget is selectable and resizable.
- """
- 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":
- tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
- 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):
- for m in [servermanager.filters, servermanager.sources, servermanager.writers]:
- 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 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 LoadXML(xmlstring, ns=None):
- """Given a server manager XML as a string, parse and process it.
- If you loaded the simple module with from paraview.simple import *,
- make sure to pass globals() as the second arguments:
- LoadXML(xmlstring, globals())
- Otherwise, the new functions will not appear in the global namespace."""
- if not ns:
- ns = globals()
- servermanager.LoadXML(xmlstring)
- _add_functions(ns)
-
-def LoadPlugin(filename, remote=True, ns=None):
- """Loads a ParaView plugin and updates this module with new constructors
- if any. The remote argument (default to True) is to specify whether
- the plugin will be loaded on client (remote=False) or on server (remote=True).
- If you loaded the simple module with from paraview.simple import *,
- make sure to pass globals() as an argument:
- LoadPlugin("myplugin", False, globals()), to load on client;
- LoadPlugin("myplugin", True, globals()), to load on server;
- LoadPlugin("myplugin", ns=globals()), to load on server.
- Otherwise, the new functions will not appear in the global namespace."""
-
- if not ns:
- ns = globals()
- servermanager.LoadPlugin(filename, remote)
- _add_functions(ns)
-
-class ActiveObjects(object):
- """This class manages the active objects (source and view). The active
- objects are shared between Python and the user interface. This class
- is for internal use. Use the Set/Get methods for setting and getting
- active objects."""
- def __get_selection_model(self, name):
- "Internal method."
- pxm = servermanager.ProxyManager()
- model = pxm.GetSelectionModel(name)
- if not model:
- model = servermanager.vtkSMProxySelectionModel()
- pxm.RegisterSelectionModel(name, model)
- return model
-
- def set_view(self, view):
- "Sets the active view."
- active_view_model = self.__get_selection_model("ActiveView")
- if view:
- active_view_model.SetCurrentProxy(view.SMProxy, 0)
- else:
- active_view_model.SetCurrentProxy(None, 0)
-
- def get_view(self):
- "Returns the active view."
- return servermanager._getPyProxy(
- self.__get_selection_model("ActiveView").GetCurrentProxy())
-
- def set_source(self, source):
- "Sets the active source."
- active_sources_model = self.__get_selection_model("ActiveSources")
- if source:
- # 3 == CLEAR_AND_SELECT
- active_sources_model.SetCurrentProxy(source.SMProxy, 3)
- else:
- active_sources_model.SetCurrentProxy(None, 3)
-
- def __convert_proxy(self, px):
- "Internal method."
- if not px:
- return None
- if px.IsA("vtkSMSourceProxy"):
- return servermanager._getPyProxy(px)
- else:
- return servermanager.OutputPort(
- servermanager._getPyProxy(px.GetSourceProxy()),
- px.GetPortIndex())
-
- def get_source(self):
- "Returns the active source."
- return self.__convert_proxy(
- self.__get_selection_model("ActiveSources").GetCurrentProxy())
-
- def get_selected_sources(self):
- "Returns the set of sources selected in the pipeline browser."
- model = self.__get_selection_model("ActiveSources")
- proxies = []
- for i in xrange(model.GetNumberOfSelectedProxies()):
- proxies.append(self.__convert_proxy(model.GetSelectedProxy(i)))
- return proxies
-
- view = property(get_view, set_view)
- source = property(get_source, set_source)
-
-class _funcs_internals:
- "Internal class."
- first_render = True
- view_counter = 0
- rep_counter = 0
-
-def demo1():
- """Simple demo that create the following pipeline
- sphere - shrink - \
- - append
- cone - /