def vtkdisk(c=(0, 0, 1)): # create a rendering window and renderer # ren = vtk.vtkRenderer() # renWin = vtk.vtkRenderWindow() # renWin.AddRenderer(ren) # create a renderwindowinteractor # iren = vtk.vtkRenderWindowInteractor() # iren.SetRenderWindow(renWin) # create source source = vtk.vtkDiskSource() source = vtk.vtkCylinderSource() source.SetCenter(c) source.SetRadius(0.01) # source.SetOuterRadius(.2) source.SetResolution(10) source.SetHeight(0.001) # source.SetCircumferentialResolution(100) source.Update() # source2.SetCenter(.3,0,0) # source2.Update() # mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInput(source.GetOutput()) # actor diskactor = vtk.vtkActor() diskactor.SetMapper(mapper) return diskactor
def getActorCircle(radius_inner=100, radius_outer=99, color=(1, 0, 0)): """""" # create source source = vtk.vtkDiskSource() source.SetInnerRadius(radius_inner) source.SetOuterRadius(radius_outer) source.SetRadialResolution(100) source.SetCircumferentialResolution(100) # Transformer transform = vtk.vtkTransform() transform.RotateWXYZ(90, 1, 0, 0) transformFilter = vtk.vtkTransformPolyDataFilter() transformFilter.SetTransform(transform) transformFilter.SetInputConnection(source.GetOutputPort()) transformFilter.Update() # mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(transformFilter.GetOutputPort()) # actor actor = vtk.vtkActor() actor.GetProperty().SetColor(color) actor.SetMapper(mapper) return actor
def Disc(center=(0.,0.,0.), inner=0.25, outer=0.5, normal=(0,0,1), r_res=1, c_res=6): """ Createa a polygonal disk with a hole in the center. The disk has zero height. The user can specify the inner and outer radius of the disk, and the radial and circumferential resolution of the polygonal representation. Parameters ---------- center : np.ndarray or list Center in [x, y, z]. middle of the axis of the disc. inner : flaot The inner radius outer : float The outer radius normal : np.ndarray or list direction vector in [x, y, z]. orientation vector of the cone. r_res: int number of points in radius direction. r_res: int number of points in circumferential direction. """ src = vtk.vtkDiskSource() src.SetInnerRadius(inner) src.SetOuterRadius(outer) src.SetRadialResolution(r_res) src.SetCircumferentialResolution(c_res) src.Update() return pyvista.wrap(src.GetOutput())
def Disc( pos=(0, 0, 0), r1=0.5, r2=1, c="coral", alpha=1, res=12, resphi=None, ): """ Build a 2D disc of internal radius `r1` and outer radius `r2`, oriented perpendicular to `normal`. |Disk| """ ps = vtk.vtkDiskSource() ps.SetInnerRadius(r1) ps.SetOuterRadius(r2) ps.SetRadialResolution(res) if not resphi: resphi = 6 * res ps.SetCircumferentialResolution(resphi) ps.Update() actor = Actor(ps.GetOutput(), c, alpha).flat() actor.SetPosition(pos) settings.collectable_actors.append(actor) return actor
def main(): colors = vtk.vtkNamedColors() diskSource = vtk.vtkDiskSource() # Create a mapper and actor. mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(diskSource.GetOutputPort()) actor = vtk.vtkActor() actor.GetProperty().SetColor(colors.GetColor3d("Cornsilk")) actor.SetMapper(mapper) # Create a renderer, render window, and interactor renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.SetWindowName("Disk") renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) # Add the actors to the scene renderer.AddActor(actor) renderer.SetBackground(colors.GetColor3d("DarkGreen")) # Render and interact renderWindow.Render() renderWindowInteractor.Start()
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkDiskSource(), 'Processing.', (), ('vtkPolyData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def make_disk(outer, inner): source = vtk.vtkDiskSource() source.SetInnerRadius(1) source.SetOuterRadius(1.1) source.SetRadialResolution(20) source.SetCircumferentialResolution(20) source.Update() return source
def make_disk(outer, inner): source = vtk.vtkDiskSource() source.SetInnerRadius(1) source.SetOuterRadius(1.1) source.SetRadialResolution(20) source.SetCircumferentialResolution(20) source.Update() return source
def __init__(self, geom, ident=None): self.src = vtkDiskSource() ODE_Object.__init__(self, geom, ident) self.size = 2000 self.src.SetOuterRadius(self.size) self.src.SetInnerRadius(0) self.src.SetCircumferentialResolution(30)
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkDiskSource(), 'Processing.', (), ('vtkPolyData', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def disc(pos=[0, 0, 0], normal=[0, 0, 1], r1=0.5, r2=1, c='coral', bc='darkgreen', lw=1, alpha=1, legend=None, texture=None, res=12): '''Build a 2D disc of internal radius r1 and outer radius r2, oriented perpendicular to normal''' ps = vtk.vtkDiskSource() ps.SetInnerRadius(r1) ps.SetOuterRadius(r2) ps.SetRadialResolution(res) ps.SetCircumferentialResolution(res * 4) ps.Update() tr = vtk.vtkTriangleFilter() vu.setInput(tr, ps.GetOutputPort()) tr.Update() axis = np.array(normal) / np.linalg.norm(normal) theta = np.arccos(axis[2]) phi = np.arctan2(axis[1], axis[0]) t = vtk.vtkTransform() t.PostMultiply() t.RotateY(theta * 57.3) t.RotateZ(phi * 57.3) tf = vtk.vtkTransformPolyDataFilter() vu.setInput(tf, tr.GetOutput()) tf.SetTransform(t) tf.Update() pd = tf.GetOutput() mapper = vtk.vtkPolyDataMapper() vu.setInput(mapper, pd) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(vc.getColor(c)) # check if color string contains a float, in this case ignore alpha al = vc.getAlpha(c) if al: alpha = al actor.GetProperty().SetOpacity(alpha) actor.GetProperty().SetLineWidth(lw) actor.GetProperty().SetInterpolationToFlat() if bc: # defines a specific color for the backface backProp = vtk.vtkProperty() backProp.SetDiffuseColor(vc.getColor(bc)) backProp.SetOpacity(alpha) actor.SetBackfaceProperty(backProp) if texture: vu.assignTexture(actor, texture) vu.assignPhysicsMethods(actor) vu.assignConvenienceMethods(actor, legend) actor.SetPosition(pos) return actor
def Disc(center=(0., 0., 0.), inner=0.25, outer=0.5, normal=(0, 0, 1), r_res=1, c_res=6): """Create a polygonal disk with a hole in the center. The disk has zero height. The user can specify the inner and outer radius of the disk, and the radial and circumferential resolution of the polygonal representation. Parameters ---------- center : np.ndarray or list Center in [x, y, z]. middle of the axis of the disc. inner : float The inner radius outer : float The outer radius normal : np.ndarray or list Direction vector in [x, y, z]. orientation vector of the cone. r_res: int Number of points in radius direction. r_res: int Number of points in circumferential direction. """ src = vtk.vtkDiskSource() src.SetInnerRadius(inner) src.SetOuterRadius(outer) src.SetRadialResolution(r_res) src.SetCircumferentialResolution(c_res) src.Update() default_normal = np.array([0, 0, 1]) normal = np.array(normal) center = np.array(center) axis = np.cross(default_normal, normal) angle = np.rad2deg( np.arccos(np.clip(np.dot(normal, default_normal), -1, 1))) transform = vtk.vtkTransform() transform.RotateWXYZ(angle, axis) transform.Translate(center) transform_filter = vtk.vtkTransformFilter() transform_filter.SetInputConnection(src.GetOutputPort()) transform_filter.SetTransform(transform) transform_filter.Update() return pyvista.wrap(transform_filter.GetOutput())
def Disc( pos=(0, 0, 0), normal=(0, 0, 1), r1=0.5, r2=1, c="coral", bc="darkgreen", lw=1, alpha=1, res=12, resphi=None, ): """ Build a 2D disc of internal radius `r1` and outer radius `r2`, oriented perpendicular to `normal`. |Disk| """ ps = vtk.vtkDiskSource() ps.SetInnerRadius(r1) ps.SetOuterRadius(r2) ps.SetRadialResolution(res) if not resphi: resphi = 6 * res ps.SetCircumferentialResolution(resphi) ps.Update() axis = np.array(normal) / np.linalg.norm(normal) theta = np.arccos(axis[2]) phi = np.arctan2(axis[1], axis[0]) t = vtk.vtkTransform() t.PostMultiply() t.RotateY(np.rad2deg(theta)) t.RotateZ(np.rad2deg(phi)) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(ps.GetOutput()) tf.SetTransform(t) tf.Update() pd = tf.GetOutput() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(pd) actor = Actor() # vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(colors.getColor(c)) actor.GetProperty().SetOpacity(alpha) actor.GetProperty().SetLineWidth(lw) actor.GetProperty().SetInterpolationToFlat() if bc: # defines a specific color for the backface backProp = vtk.vtkProperty() backProp.SetDiffuseColor(colors.getColor(bc)) backProp.SetOpacity(alpha) actor.SetBackfaceProperty(backProp) actor.SetPosition(pos) settings.collectable_actors.append(actor) return actor
def display_disk(self, actorName, vec3_origin, vec3_direction, outer_radius, inner_radius, vec3_color): disk = vtk.vtkDiskSource() disk.SetInnerRadius(inner_radius) disk.SetOuterRadius(outer_radius) disk.SetRadialResolution(30) disk.SetCircumferentialResolution(30) disk.Update() # transform to center with orientation according to normal axis1 = [vec3_direction[0], vec3_direction[1], vec3_direction[2]] axis2 = np.cross(axis1, [1, 1, 1]) axis2 = axis2 / np.linalg.norm(axis2) axis3 = np.cross(axis1, axis2) # print axis1 # print axis2 # print axis3 trans = np.eye(4) trans[0, 0] = axis3[0] trans[0, 1] = axis2[0] trans[0, 2] = axis1[0] trans[0, 3] = vec3_origin[0] trans[1, 0] = axis3[1] trans[1, 1] = axis2[1] trans[1, 2] = axis1[1] trans[1, 3] = vec3_origin[1] trans[2, 0] = axis3[2] trans[2, 1] = axis2[2] trans[2, 2] = axis1[2] trans[2, 3] = vec3_origin[2] trans[3, 0] = 0 trans[3, 1] = 0 trans[3, 2] = 0 trans[3, 3] = 1 vtk_trans = vtk.vtkMatrix4x4() for i in range(0, 4): for j in range(0, 4): vtk_trans.SetElement(i, j, trans[i, j]) ar_trans = vtk.vtkTransform() ar_trans.SetMatrix(vtk_trans) ar_trans_filter = vtk.vtkTransformPolyDataFilter() ar_trans_filter.SetTransform(ar_trans) ar_trans_filter.SetInputConnection(disk.GetOutputPort()) diskMapper = vtk.vtkPolyDataMapper() diskMapper.SetInputConnection(ar_trans_filter.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(diskMapper) actor.GetProperty().SetColor(vec3_color[0], vec3_color[1], vec3_color[2]) self.ren.AddActor(actor) self.name2actor[actorName] = actor return
def initialize (self, valid_coord): """ Initializes the seed given an array of valid co-ordinate directions. [x-axis, y-axis, z_axis] is the format. For instance if x-axis == 0 then the data is along the YZ plane. This method is responsible for actually creating the seed. """ debug ("In SeedManager::initialize ()") assert len (valid_coord) == 3 self.dim = reduce (lambda x, y: x+y, valid_coord) if self.dim == 3: self.seed = vtk.vtkPointSource () else: self.seed = vtk.vtkDiskSource () self.seed.SetRadialResolution (1) self.seed.SetInnerRadius (0.0) self.transform = vtk.vtkTransformFilter () self.transform.SetTransform (vtk.vtkTransform ()) self.transform.SetInput (self.seed.GetOutput ()) self.orient_2d (valid_coord)
def add_node(self, source, name="", resize=1.0): """Appends a node to the nodes list.""" # Poly-data self.node_ids.append(name) poly = vtkDiskSource() # Set initial size and resize factor self.resize_factor.append(resize) try: size = self.data[-1][source] except: size = 0 poly.SetOuterRadius(size) poly.SetInnerRadius(size - 0.4) poly.SetRadialResolution(30) poly.SetCircumferentialResolution(30) self.poly_data.append(poly) # Mapper poly_mapper = vtkPolyDataMapper() poly_mapper.SetInputConnection(poly.GetOutputPort()) self.poly_mappers.append(poly_mapper)
def DiskSource(self, currentElement): source = vtk.vtkDiskSource() try: source.SetInnerRadius( float(currentElement.get('SetInnerRadius')) ) except: self.logger.error(' .. <DiskSource> failed to SetInnerRadius') try: source.SetOuterRadius( float(currentElement.get('SetOuterRadius')) ) except: self.logger.error(' .. <DiskSource> failed to SetOuterRadius') if 'SetRadialResolution' in currentElement.keys(): try: source.SetRadialResolution( int(currentElement.get('SetRadialResolution')) ) except: self.logger.error(' .. <CylinderSource> failed to SetRadialResolution') if 'SetCircumferentialResolution' in currentElement.keys(): try: source.SetCircumferentialResolution( int(currentElement.get('SetCircumferentialResolution')) ) except: self.logger.error(' .. <CylinderSource> failed to SetCircumferentialResolution') return source
def main(): colors = vtk.vtkNamedColors() diskSource = vtk.vtkDiskSource() diskSource.Update() featureEdges = vtk.vtkFeatureEdges() featureEdges.SetInputConnection(diskSource.GetOutputPort()) featureEdges.BoundaryEdgesOn() featureEdges.FeatureEdgesOff() featureEdges.ManifoldEdgesOff() featureEdges.NonManifoldEdgesOff() featureEdges.ColoringOn() featureEdges.Update() # Visualize edgeMapper = vtk.vtkPolyDataMapper() edgeMapper.SetInputConnection(featureEdges.GetOutputPort()) edgeActor = vtk.vtkActor() edgeActor.SetMapper(edgeMapper) diskMapper = vtk.vtkPolyDataMapper() diskMapper.SetInputConnection(diskSource.GetOutputPort()) diskActor = vtk.vtkActor() diskActor.SetMapper(diskMapper) diskActor.GetProperty().SetColor(colors.GetColor3d('Gray')) # Create a renderer, render window, and interactor renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.SetWindowName('BoundaryEdges') renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderer.AddActor(edgeActor) renderer.AddActor(diskActor) renderer.SetBackground(colors.GetColor3d('DimGray')) renderWindow.Render() renderWindowInteractor.Start()
def _setup(self): """Setup this UI component. Creating the disk actor used internally. """ # Setting up disk actor. self._disk = vtk.vtkDiskSource() self._disk.SetRadialResolution(10) self._disk.SetCircumferentialResolution(50) self._disk.Update() # Mapper mapper = vtk.vtkPolyDataMapper2D() mapper = set_input(mapper, self._disk.GetOutputPort()) # Actor self.actor = vtk.vtkActor2D() self.actor.SetMapper(mapper) # Add default events listener to the VTK actor. self.handle_events(self.actor)
def write_tube(self, tube, position, rotation): diskSource = vtk.vtkDiskSource() diskSource.SetInnerRadius(tube.rmin) diskSource.SetOuterRadius(tube.rmax) circumfrence = 2 * pi * tube.rmax # now in cm. diskSource.SetCircumferentialResolution(100) diskSource.Update() linearExtrusion = vtk.vtkLinearExtrusionFilter() linearExtrusion.SetInputConnection(diskSource.GetOutputPort()) linearExtrusion.SetExtrusionTypeToNormalExtrusion() linearExtrusion.SetVector(0, 0, 1) linearExtrusion.SetScaleFactor(tube.z) linearExtrusion.Update() implicit_transform = self.apply_transformations( linearExtrusion.GetOutputPort(), [0, 0, -tube.z / 2.], [0, 0, 0]) data = self.apply_transformations(implicit_transform.GetOutputPort(), position, rotation) self.logger.debug("Writing Tube") return data
transform.Translate(0.0, 0.0, 3.5) axes = vtk.vtkAxesActor() # The axes are positioned with a user transform axes.SetUserTransform(transform) # properties of the axes labels can be set as follows # this sets the x axis label to red # axes->GetXAxisCaptionActor2D()->GetCaptionTextProperty()->SetColor(1,0,0); # the actual text of the axis label can be changed: # axes->SetXAxisLabelText("test"); ren.AddActor(axes) source = vtk.vtkDiskSource() source.SetInnerRadius(1.6) source.SetOuterRadius(3) source.SetRadialResolution(100) source.SetCircumferentialResolution(100) source.Update() # mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInput(source.GetOutput()) # actor actor = vtk.vtkActor() actor.SetMapper(mapper) actor.SetOrigin(0, 0, 0) # assign actor to the renderer
def __init__(self, parent=None): super(VTKFrame, self).__init__(parent) self.vtkWidget = QVTKRenderWindowInteractor(self) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() vl = QtGui.QVBoxLayout(self) vl.addWidget(self.vtkWidget) vl.setContentsMargins(0, 0, 0, 0) # Create source geometricObjects = list() geometricObjects.append(vtk.vtkArrowSource()) geometricObjects.append(vtk.vtkConeSource()) geometricObjects.append(vtk.vtkCubeSource()) geometricObjects.append(vtk.vtkCylinderSource()) geometricObjects.append(vtk.vtkDiskSource()) geometricObjects.append(vtk.vtkLineSource()) geometricObjects.append(vtk.vtkRegularPolygonSource()) geometricObjects.append(vtk.vtkSphereSource()) renderers = list() mappers = list() actors = list() textmappers = list() textactors = list() # Create a common text property. textProperty = vtk.vtkTextProperty() textProperty.SetFontSize(10) textProperty.SetJustificationToCentered() # Create a parametric function source, renderer, mapper # and actor for each object. for idx, item in enumerate(geometricObjects): geometricObjects[idx].Update() mappers.append(vtk.vtkPolyDataMapper()) mappers[idx].SetInputConnection( geometricObjects[idx].GetOutputPort()) actors.append(vtk.vtkActor()) actors[idx].SetMapper(mappers[idx]) textmappers.append(vtk.vtkTextMapper()) textmappers[idx].SetInput(item.GetClassName()) textmappers[idx].SetTextProperty(textProperty) textactors.append(vtk.vtkActor2D()) textactors[idx].SetMapper(textmappers[idx]) textactors[idx].SetPosition(150, 16) renderers.append(vtk.vtkRenderer()) gridDimensions = 3 for idx in range(len(geometricObjects)): if idx < gridDimensions * gridDimensions: renderers.append(vtk.vtkRenderer()) rendererSize = 300 # Setup the RenderWindow self.vtkWidget.GetRenderWindow().SetSize(rendererSize * gridDimensions, rendererSize * gridDimensions) # Add and position the renders to the render window. viewport = list() for row in range(gridDimensions): for col in range(gridDimensions): idx = row * gridDimensions + col viewport[:] = [] viewport.append( float(col) * rendererSize / (gridDimensions * rendererSize)) viewport.append( float(gridDimensions - (row + 1)) * rendererSize / (gridDimensions * rendererSize)) viewport.append( float(col + 1) * rendererSize / (gridDimensions * rendererSize)) viewport.append( float(gridDimensions - row) * rendererSize / (gridDimensions * rendererSize)) if idx > (len(geometricObjects) - 1): continue renderers[idx].SetViewport(viewport) self.vtkWidget.GetRenderWindow().AddRenderer(renderers[idx]) renderers[idx].AddActor(actors[idx]) renderers[idx].AddActor(textactors[idx]) renderers[idx].SetBackground(0.4, 0.3, 0.2) self._initialized = False
def prepMarker(renWin,marker,cmap=None): n=prepPrimitive(marker) if n==0: return actors=[] for i in range(n): ## Creates the glyph g = vtk.vtkGlyph2D() markers = vtk.vtkPolyData() x = marker.x[i] y=marker.y[i] c=marker.color[i] s=marker.size[i]*.5 t=marker.type[i] N = max(len(x),len(y)) for a in [x,y]: while len(a)<n: a.append(a[-1]) pts = vtk.vtkPoints() geo,pts = project(pts,marker.projection,marker.worldcoordinate) for j in range(N): pts.InsertNextPoint(x[j],y[j],0.) markers.SetPoints(pts) # Type ## Ok at this point generates the source for glpyh gs = vtk.vtkGlyphSource2D() pd = None if t=='dot': gs.SetGlyphTypeToCircle() gs.FilledOn() elif t=='circle': gs.SetGlyphTypeToCircle() gs.FilledOff() elif t=='plus': gs.SetGlyphTypeToCross() gs.FilledOff() elif t=='cross': gs.SetGlyphTypeToCross() gs.SetRotationAngle(45) gs.FilledOff() elif t[:6]=='square': gs.SetGlyphTypeToSquare() gs.FilledOff() elif t[:7]=='diamond': gs.SetGlyphTypeToDiamond() gs.FilledOff() elif t[:8]=='triangle': gs.SetGlyphTypeToTriangle() gs.FilledOff() if t[9]=="d": gs.SetRotationAngle(180) elif t[9]=="l": gs.SetRotationAngle(90) elif t[9]=="r": gs.SetRotationAngle(-90) elif t[9]=="u": gs.SetRotationAngle(0) elif t == "hurricane": s =s/5. ds = vtk.vtkDiskSource() ds.SetInnerRadius(.55*s) ds.SetOuterRadius(1.01*s) ds.SetCircumferentialResolution(90) ds.SetRadialResolution(30) gf = vtk.vtkGeometryFilter() gf.SetInputConnection(ds.GetOutputPort()) gf.Update() pd1 = gf.GetOutput() apd = vtk.vtkAppendPolyData() apd.AddInputData(pd1) pts = vtk.vtkPoints() pd = vtk.vtkPolyData() polygons = vtk.vtkCellArray() add_angle = numpy.pi/360. coords = [] angle1 = .6*numpy.pi angle2 = .88*numpy.pi while angle1<=angle2: coords.append([s*2+2*s*numpy.cos(angle1),2*s*numpy.sin(angle1)]) angle1+=add_angle angle1=.79*numpy.pi angle2=.6*numpy.pi while angle1>=angle2: coords.append([s*2.25+s*4*numpy.cos(angle1),-s*2+s*4*numpy.sin(angle1)]) angle1-=add_angle poly = genPoly(coords,pts,filled=True) polygons.InsertNextCell(poly) coords=[] angle1 = 1.6*numpy.pi angle2 = 1.9*numpy.pi while angle1 <= angle2: coords.append( [- s*2 + s*2*numpy.cos(angle1),s*2*numpy.sin(angle1)]) angle1 += add_angle angle1 = 1.8*numpy.pi angle2 = 1.6*numpy.pi while angle1 >= angle2: coords.append( [- s*2.27 + s*4*numpy.cos(angle1), s*2 + s*4*numpy.sin(angle1)]) angle1 -= add_angle poly = genPoly(coords,pts,filled=True) polygons.InsertNextCell(poly) pd.SetPoints(pts) pd.SetPolys(polygons) apd.AddInputData(pd) apd.Update() g.SetSourceData(apd.GetOutput()) elif t[:4] == "star": np = 5 points = starPoints(.001 * s, 0, 0, np) pts = vtk.vtkPoints() # Add all perimeter points for point in points: pts.InsertNextPoint((point[0], point[1], 0)) center_id = len(points) # Add center point pts.InsertNextPoint((0,0,0)) polygons = vtk.vtkCellArray() for ind in range(0, np*2, 2): poly = vtk.vtkPolygon() pid = poly.GetPointIds() pid.SetNumberOfIds(4) pid.SetId(0, ind) pid.SetId(1, (ind - 1) % len(points)) pid.SetId(2, center_id) pid.SetId(3, (ind + 1) % len(points)) polygons.InsertNextCell(poly) pd = vtk.vtkPolyData() pd.SetPoints(pts) pd.SetPolys(polygons) g.SetSourceData(pd) elif t in ["w%.2i" % x for x in range(203)]: ## WMO marker params = wmo[t] pts = vtk.vtkPoints() pd = vtk.vtkPolyData() polys = vtk.vtkCellArray() lines = vtk.vtkCellArray() s*=3 #Lines first for l in params["line"]: coords = numpy.array(zip(*l))*s/30. line = genPoly(coords.tolist(),pts,filled=False) lines.InsertNextCell(line) for l in params["poly"]: coords = numpy.array(zip(*l))*s/30. line = genPoly(coords.tolist(),pts,filled=True) polys.InsertNextCell(line) geo,pts = project(pts,marker.projection,marker.worldcoordinate) pd.SetPoints(pts) pd.SetPolys(polys) pd.SetLines(lines) g.SetSourceData(pd) else: warnings.warn("unknown marker type: %s, using dot" % t) gs.SetGlyphTypeToCircle() gs.FilledOn() if t[-5:]=="_fill": gs.FilledOn() if pd is None: # Use the difference in x to scale the point, as later we'll use the # x range to correct the aspect ratio: dx = marker.worldcoordinate[1] - marker.worldcoordinate[0] s *= abs(float(dx))/500. gs.SetScale(s) gs.Update() if pd is None: g.SetSourceConnection(gs.GetOutputPort()) g.SetInputData(markers) a = vtk.vtkActor() m = vtk.vtkPolyDataMapper() m.SetInputConnection(g.GetOutputPort()) m.Update() a.SetMapper(m) p = a.GetProperty() #Color if cmap is None: if marker.colormap is not None: cmap = marker.colormap else: cmap = 'default' if isinstance(cmap,str): cmap = vcs.elements["colormap"][cmap] color = cmap.index[c] p.SetColor([C/100. for C in color]) actors.append((g,gs,pd,a,geo)) return actors
def execute_module(self): if self._giaHumerus and self._giaGlenoid and \ len(self._glenoidEdge) >= 6 and self._inputPolyData: # _glenoidEdgeImplicitFunction # construct eight planes with the insertion axis as mid-line # the planes should go somewhat further proximally than the # proximal insertion axis point # first calculate the distal-proximal glenoid insertion axis gia = tuple(map(operator.sub, self._giaGlenoid, self._giaHumerus)) # and in one swift move, we normalize it and get the magnitude giaN = list(gia) giaM = vtk.vtkMath.Normalize(giaN) # extend gia with a few millimetres giaM += 5 gia = tuple([giaM * i for i in giaN]) stuff = [] yN = [0,0,0] zN = [0,0,0] angleIncr = 2.0 * vtk.vtkMath.Pi() / 8.0 for i in range(4): angle = float(i) * angleIncr vtk.vtkMath.Perpendiculars(gia, yN, zN, angle) # each ridge is 1 cm (10 mm) - we'll change this later y = [10.0 * j for j in yN] origin = map(operator.add, self._giaHumerus, y) point1 = map(operator.add, origin, [-2.0 * k for k in y]) point2 = map(operator.add, origin, gia) # now create the plane source ps = vtk.vtkPlaneSource() ps.SetOrigin(origin) ps.SetPoint1(point1) ps.SetPoint2(point2) ps.Update() plane = vtk.vtkPlane() plane.SetOrigin(ps.GetOrigin()) plane.SetNormal(ps.GetNormal()) pdn = vtk.vtkPolyDataNormals() pdn.SetInput(self._inputPolyData) cut = vtk.vtkCutter() cut.SetInput(pdn.GetOutput()) cut.SetCutFunction(plane) cut.GenerateCutScalarsOn() cut.SetValue(0,0) cut.Update() contour = cut.GetOutput() # now find line segment closest to self._giaGlenoid pl = vtk.vtkPointLocator() pl.SetDataSet(contour) pl.BuildLocator() startPtId = pl.FindClosestPoint(self._giaGlenoid) cellIds = vtk.vtkIdList() contour.GetPointCells(startPtId, cellIds) twoLineIds = cellIds.GetId(0), cellIds.GetId(1) ptIds = vtk.vtkIdList() cellIds = vtk.vtkIdList() # we'll use these to store tuples: # (ptId, (pt0, pt1, pt2), (n0, n1, n2)) lines = [[],[]] lineIdx = 0 for startLineId in twoLineIds: # we have a startLineId, a startPtId and polyData curStartPtId = startPtId curLineId = startLineId onGlenoid = True offCount = 0 while onGlenoid: contour.GetCellPoints(curLineId, ptIds) if ptIds.GetNumberOfIds() != 2: print 'aaaaaaaaaaaaack!' ptId0 = ptIds.GetId(0) ptId1 = ptIds.GetId(1) nextPointId = [ptId0, ptId1]\ [bool(ptId0 == curStartPtId)] contour.GetPointCells(nextPointId, cellIds) if cellIds.GetNumberOfIds() != 2: print 'aaaaaaaaaaaaaaaack2!' cId0 = cellIds.GetId(0) cId1 = cellIds.GetId(1) nextLineId = [cId0, cId1]\ [bool(cId0 == curLineId)] # get the normal for the current point n = contour.GetPointData().GetNormals().GetTuple3( curStartPtId) # get the current point pt0 = contour.GetPoints().GetPoint(curStartPtId) # store the real ptid, point coords and normal lines[lineIdx].append((curStartPtId, tuple(pt0), tuple(n))) if vtk.vtkMath.Dot(giaN, n) > -0.9: # this means that this point could be falling off # the glenoid, let's make a note of the incident offCount += 1 # if the last N points have been "off" the glenoid, # it could mean we've really fallen off! if offCount >= 40: del lines[lineIdx][-40:] onGlenoid = False # get ready for next iteration curStartPtId = nextPointId curLineId = nextLineId # closes: while onGlenoid lineIdx += 1 # closes: for startLineId in twoLineIds # we now have two line lists... we have to combine them and # make sure it still constitutes one long line lines[0].reverse() edgeLine = lines[0] + lines[1] # do line extrusion resulting in a list of 5-element tuples, # each tuple representing the 5 3-d vertices of a "house" houses = self._lineExtrudeHouse(edgeLine, plane) # we will dump ALL the new points in here newPoints = vtk.vtkPoints() newPoints.SetDataType(contour.GetPoints().GetDataType()) # but we're going to create 5 lines idLists = [vtk.vtkIdList() for i in range(5)] for house in houses: for vertexIdx in range(5): ptId = newPoints.InsertNextPoint(house[vertexIdx]) idLists[vertexIdx].InsertNextId(ptId) # create a cell with the 5 lines newCellArray = vtk.vtkCellArray() for idList in idLists: newCellArray.InsertNextCell(idList) newPolyData = vtk.vtkPolyData() newPolyData.SetLines(newCellArray) newPolyData.SetPoints(newPoints) rsf = vtk.vtkRuledSurfaceFilter() rsf.CloseSurfaceOn() #rsf.SetRuledModeToPointWalk() rsf.SetRuledModeToResample() rsf.SetResolution(128, 4) rsf.SetInput(newPolyData) rsf.Update() stuff.append(rsf.GetOutput()) # also add two housies to cap all the ends capHousePoints = vtk.vtkPoints() capHouses = [] if len(houses) > 1: # we only cap if there are at least two houses capHouses.append(houses[0]) capHouses.append(houses[-1]) capHouseIdLists = [vtk.vtkIdList() for dummy in capHouses] for capHouseIdx in range(len(capHouseIdLists)): house = capHouses[capHouseIdx] for vertexIdx in range(5): ptId = capHousePoints.InsertNextPoint(house[vertexIdx]) capHouseIdLists[capHouseIdx].InsertNextId(ptId) if capHouseIdLists: newPolyArray = vtk.vtkCellArray() for capHouseIdList in capHouseIdLists: newPolyArray.InsertNextCell(capHouseIdList) capPolyData = vtk.vtkPolyData() capPolyData.SetPoints(capHousePoints) capPolyData.SetPolys(newPolyArray) # FIXME: put back stuff.append(capPolyData) # closes: for i in range(4) ap = vtk.vtkAppendPolyData() # copy everything to output (for testing) for thing in stuff: ap.AddInput(thing) #ap.AddInput(stuff[0]) # seems to be important for vtkAppendPolyData ap.Update() # now cut it with the FBZ planes fbzSupPlane = self._fbzCutPlane(self._fbzSup, giaN, self._giaGlenoid) fbzSupClip = vtk.vtkClipPolyData() fbzSupClip.SetClipFunction(fbzSupPlane) fbzSupClip.SetValue(0) fbzSupClip.SetInput(ap.GetOutput()) fbzInfPlane = self._fbzCutPlane(self._fbzInf, giaN, self._giaGlenoid) fbzInfClip = vtk.vtkClipPolyData() fbzInfClip.SetClipFunction(fbzInfPlane) fbzInfClip.SetValue(0) fbzInfClip.SetInput(fbzSupClip.GetOutput()) cylinder = vtk.vtkCylinder() cylinder.SetCenter([0,0,0]) # we make the cut-cylinder slightly larger... it's only there # to cut away the surface edges, so precision is not relevant cylinder.SetRadius(self.drillGuideInnerDiameter / 2.0) # cylinder is oriented along y-axis (0,1,0) - # we need to calculate the angle between the y-axis and the gia # 1. calc dot product (|a||b|cos(\phi)) cylDotGia = - giaN[1] # 2. because both factors are normals, angle == acos phiRads = math.acos(cylDotGia) # 3. cp is the vector around which gia can be turned to # coincide with the y-axis cp = [0,0,0] vtk.vtkMath.Cross((-giaN[0], -giaN[1], -giaN[2]), (0.0, 1.0, 0.0), cp) # this transform will be applied to all points BEFORE they are # tested on the cylinder implicit function trfm = vtk.vtkTransform() # it's premultiply by default, so the last operation will get # applied FIRST: # THEN rotate it around the cp axis so it's relative to the # y-axis instead of the gia-axis trfm.RotateWXYZ(phiRads * vtk.vtkMath.RadiansToDegrees(), cp[0], cp[1], cp[2]) # first translate the point back to the origin trfm.Translate(-self._giaGlenoid[0], -self._giaGlenoid[1], -self._giaGlenoid[2]) cylinder.SetTransform(trfm) cylinderClip = vtk.vtkClipPolyData() cylinderClip.SetClipFunction(cylinder) cylinderClip.SetValue(0) cylinderClip.SetInput(fbzInfClip.GetOutput()) cylinderClip.GenerateClipScalarsOn() ap2 = vtk.vtkAppendPolyData() ap2.AddInput(cylinderClip.GetOutput()) # this will cap the just cut polydata ap2.AddInput(self._capCutPolyData(fbzSupClip)) ap2.AddInput(self._capCutPolyData(fbzInfClip)) # thees one she dosint werk so gooood #ap2.AddInput(self._capCutPolyData(cylinderClip)) # now add outer guide cylinder, NOT capped cs1 = vtk.vtkCylinderSource() cs1.SetResolution(32) cs1.SetRadius(self.drillGuideOuterDiameter / 2.0) cs1.CappingOff() cs1.SetHeight(self.drillGuideHeight) # 15 mm height cs1.SetCenter(0,0,0) cs1.Update() # inner cylinder cs2 = vtk.vtkCylinderSource() cs2.SetResolution(32) cs2.SetRadius(self.drillGuideInnerDiameter / 2.0) cs2.CappingOff() cs2.SetHeight(self.drillGuideHeight) # 15 mm height cs2.SetCenter(0,0,0) cs2.Update() # top cap tc = vtk.vtkDiskSource() tc.SetInnerRadius(self.drillGuideInnerDiameter / 2.0) tc.SetOuterRadius(self.drillGuideOuterDiameter / 2.0) tc.SetCircumferentialResolution(64) tcTrfm = vtk.vtkTransform() # THEN flip it so that its centre-line is the y-axis tcTrfm.RotateX(90) # FIRST translate the disc tcTrfm.Translate(0,0,- self.drillGuideHeight / 2.0) tcTPDF = vtk.vtkTransformPolyDataFilter() tcTPDF.SetTransform(tcTrfm) tcTPDF.SetInput(tc.GetOutput()) # bottom cap bc = vtk.vtkDiskSource() bc.SetInnerRadius(self.drillGuideInnerDiameter / 2.0) bc.SetOuterRadius(self.drillGuideOuterDiameter / 2.0) bc.SetCircumferentialResolution(64) bcTrfm = vtk.vtkTransform() # THEN flip it so that its centre-line is the y-axis bcTrfm.RotateX(90) # FIRST translate the disc bcTrfm.Translate(0,0, self.drillGuideHeight / 2.0) bcTPDF = vtk.vtkTransformPolyDataFilter() bcTPDF.SetTransform(bcTrfm) bcTPDF.SetInput(bc.GetOutput()) tubeAP = vtk.vtkAppendPolyData() tubeAP.AddInput(cs1.GetOutput()) tubeAP.AddInput(cs2.GetOutput()) tubeAP.AddInput(tcTPDF.GetOutput()) tubeAP.AddInput(bcTPDF.GetOutput()) # we have to transform this f****r as well csTrfm = vtk.vtkTransform() # go half the height + 2mm upwards from surface drillGuideCentre = - 1.0 * self.drillGuideHeight / 2.0 - 2 cs1Centre = map(operator.add, self._giaGlenoid, [drillGuideCentre * i for i in giaN]) # once again, this is performed LAST csTrfm.Translate(cs1Centre) # and this FIRST (we have to rotate the OTHER way than for # the implicit cylinder cutting, because the cylinder is # transformed from y-axis to gia, not the other way round) csTrfm.RotateWXYZ(-phiRads * vtk.vtkMath.RadiansToDegrees(), cp[0], cp[1], cp[2]) # actually perform the transform csTPDF = vtk.vtkTransformPolyDataFilter() csTPDF.SetTransform(csTrfm) csTPDF.SetInput(tubeAP.GetOutput()) csTPDF.Update() ap2.AddInput(csTPDF.GetOutput()) ap2.Update() self._outputPolyData.DeepCopy(ap2.GetOutput())
def __init__(self): """ Called when the logic class is instantiated. Can be used for initializing member variables. """ ScriptedLoadableModuleLogic.__init__(self) self.inputCurveNode = None self.inputCurveNodeObservations = [] self.inputSurfacePointsNode = None self.inputSurfacePointsNodeObservations = [] self.numberOfCurveLandmarkPoints = 80 self.printThreeDViewNode = None self.printThreeDWidget = None self.printViewWidth = 1024 self.printViewHeight = 1024 self.printXResolutionDpi = 300 self.printYResolutionDpi = 300 self.printScale = 2.0 #TODO: Workaround for scaling problem, see https://github.com/SlicerFab/SlicerFab/issues/13 self.printTransparentBackground = False # Create triangulated flat disk that will be warped self.surfaceUnitDisk = vtk.vtkDiskSource() self.surfaceUnitDisk.SetOuterRadius(1.0) self.surfaceUnitDisk.SetInnerRadius(0.0) self.surfaceUnitDisk.SetCircumferentialResolution( self.numberOfCurveLandmarkPoints) self.surfaceUnitDisk.SetRadialResolution(60) self.surfaceTriangulator = vtk.vtkDelaunay2D() self.surfaceTriangulator.SetTolerance( 0.01 ) # get rid of the small triangles near the center of the unit disk self.surfaceTriangulator.SetInputConnection( self.surfaceUnitDisk.GetOutputPort()) # Prepare transform object # points on the unit disk (circumference and surface) self.surfaceTransformSourcePoints = vtk.vtkPoints() self.surfaceTransformSourceCurvePoints = vtk.vtkPoints() self.surfaceTransformSourceCurvePoints.SetNumberOfPoints( self.numberOfCurveLandmarkPoints) import math angleIncrement = 2.0 * math.pi / float( self.numberOfCurveLandmarkPoints) for pointIndex in range(self.numberOfCurveLandmarkPoints): angle = float(pointIndex) * angleIncrement self.surfaceTransformSourceCurvePoints.SetPoint( pointIndex, math.cos(angle), math.sin(angle), 0) # points on the warped surface (curve points and surface points) self.surfaceTransformTargetPoints = vtk.vtkPoints() self.surfaceTransform = vtk.vtkThinPlateSplineTransform() self.surfaceTransform.SetSourceLandmarks( self.surfaceTransformSourcePoints) self.surfaceTransform.SetTargetLandmarks( self.surfaceTransformTargetPoints) # Transform polydata self.surfaceTransformFilter = vtk.vtkTransformPolyDataFilter() self.surfaceTransformFilter.SetTransform(self.surfaceTransform) self.surfaceTransformFilter.SetInputConnection( self.surfaceTriangulator.GetOutputPort()) self.cleanPolyDataFilter = vtk.vtkCleanPolyData() self.cleanPolyDataFilter.SetInputConnection( self.surfaceTransformFilter.GetOutputPort()) # self.surfacePolyDataNormalsThin = vtk.vtkPolyDataNormals() self.surfacePolyDataNormalsThin.SetInputConnection( self.cleanPolyDataFilter.GetOutputPort()) # There are a few triangles in the triangulated unit disk with inconsistent # orientation. Enabling consistency check fixes them. self.surfacePolyDataNormalsThin.ConsistencyOn( ) # TODO: check if needed, probably not self.surfacePolyDataNormalsThin.SplittingOff( ) # this prevents stray normals at the edge TODO: check # Add thickness to warped surface (if needed) # self.surfacePolyDataNormals = vtk.vtkPolyDataNormals() # self.surfacePolyDataNormals.SetInputConnection(self.cleanPolyDataFilter.GetOutputPort()) # self.surfacePolyDataNormals.SplittingOff() # this prevents stray normals at the edge TODO: check self.surfaceOffset = vtk.vtkWarpVector() self.surfaceOffset.SetInputConnection( self.surfacePolyDataNormalsThin.GetOutputPort()) self.surfaceOffset.SetInputArrayToProcess( 0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, vtk.vtkDataSetAttributes.NORMALS) self.surfaceExtrude = vtk.vtkLinearExtrusionFilter() self.surfaceExtrude.SetInputConnection( self.surfaceOffset.GetOutputPort()) self.surfaceExtrude.SetExtrusionTypeToNormalExtrusion() self.surfacePolyDataNormalsThick = vtk.vtkPolyDataNormals() self.surfacePolyDataNormalsThick.SetInputConnection( self.surfaceExtrude.GetOutputPort()) self.surfacePolyDataNormalsThick.AutoOrientNormalsOn()
import vtk # create a rendering window and renderer ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) # create a renderwindowinteractor iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # create source source = vtk.vtkDiskSource() source.SetInnerRadius(1) source.SetOuterRadius(2) source.SetRadialResolution(100) source.SetCircumferentialResolution(100) source.Update() # mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInput(source.GetOutput()) # actor actor = vtk.vtkActor() actor.SetMapper(mapper) # assign actor to the renderer ren.AddActor(actor) # enable user interface interactor
import vtk # create a rendering window and renderer ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) # create a renderwindowinteractor iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) i=1 sourc=[] mapper=[] actor=[] for i in range(0,100): sourc.append(vtk.vtkDiskSource()) sourc[i].SetInnerRadius(1.5) sourc[i].SetOuterRadius(2) sourc[i].SetRadialResolution(100) sourc[i].SetCircumferentialResolution(100) sourc[i].Update() mapper.append(vtk.vtkPolyDataMapper()) mapper[i].SetInput(sourc[i].GetOutput()) actor.append(vtk.vtkActor()) actor[i].SetMapper(mapper[i]) actor[i].SetPosition(0,0,i/10) ren.AddActor(actor[i]) i=i+1
def main(): colors = vtk.vtkNamedColors() # Set the background color. colors.SetColor("BkgColor", [51, 77, 102, 255]) sourceObjects = list() sourceObjects.append(vtk.vtkSphereSource()) sourceObjects[-1].SetPhiResolution(21) sourceObjects[-1].SetThetaResolution(21) sourceObjects.append(vtk.vtkConeSource()) sourceObjects[-1].SetResolution(51) sourceObjects.append(vtk.vtkCylinderSource()) sourceObjects[-1].SetResolution(51) sourceObjects.append(vtk.vtkCubeSource()) sourceObjects.append(vtk.vtkPlaneSource()) sourceObjects.append(vtk.vtkTextSource()) sourceObjects[-1].SetText("Hello") sourceObjects[-1].BackingOff() sourceObjects.append(vtk.vtkPointSource()) sourceObjects[-1].SetNumberOfPoints(500) sourceObjects.append(vtk.vtkDiskSource()) sourceObjects[-1].SetCircumferentialResolution(51) sourceObjects.append(vtk.vtkLineSource()) renderers = list() mappers = list() actors = list() textmappers = list() textactors = list() # Create one text property for all. textProperty = vtk.vtkTextProperty() textProperty.SetFontSize(16) textProperty.SetJustificationToCentered() backProperty = vtk.vtkProperty() backProperty.SetColor(colors.GetColor3d("Red")) # Create a source, renderer, mapper, and actor # for each object. for i in range(0, len(sourceObjects)): mappers.append(vtk.vtkPolyDataMapper()) mappers[i].SetInputConnection(sourceObjects[i].GetOutputPort()) actors.append(vtk.vtkActor()) actors[i].SetMapper(mappers[i]) actors[i].GetProperty().SetColor(colors.GetColor3d("Seashell")) actors[i].SetBackfaceProperty(backProperty) textmappers.append(vtk.vtkTextMapper()) textmappers[i].SetInput(sourceObjects[i].GetClassName()) textmappers[i].SetTextProperty(textProperty) textactors.append(vtk.vtkActor2D()) textactors[i].SetMapper(textmappers[i]) textactors[i].SetPosition(120, 16) renderers.append(vtk.vtkRenderer()) gridDimensions = 3 # We need a renderer even if there is no actor. for i in range(len(sourceObjects), gridDimensions ** 2): renderers.append(vtk.vtkRenderer()) renderWindow = vtk.vtkRenderWindow() renderWindow.SetWindowName("Source Objects Demo") rendererSize = 300 renderWindow.SetSize(rendererSize * gridDimensions, rendererSize * gridDimensions) for row in range(0, gridDimensions): for col in range(0, gridDimensions): index = row * gridDimensions + col x0 = float(col) / gridDimensions y0 = float(gridDimensions - row - 1) / gridDimensions x1 = float(col + 1) / gridDimensions y1 = float(gridDimensions - row) / gridDimensions renderWindow.AddRenderer(renderers[index]) renderers[index].SetViewport(x0, y0, x1, y1) if index > (len(sourceObjects) - 1): continue renderers[index].AddActor(actors[index]) renderers[index].AddActor(textactors[index]) renderers[index].SetBackground(colors.GetColor3d("BkgColor")) renderers[index].ResetCamera() renderers[index].GetActiveCamera().Azimuth(30) renderers[index].GetActiveCamera().Elevation(30) renderers[index].GetActiveCamera().Zoom(0.8) renderers[index].ResetCameraClippingRange() interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renderWindow) renderWindow.Render() interactor.Start()
def prepGlyph(g, marker, index=0): t, s = marker.type[index], marker.size[index] * .5 gs = vtk.vtkGlyphSource2D() pd = None if t=='dot': gs.SetGlyphTypeToCircle() gs.FilledOn() elif t=='circle': gs.SetGlyphTypeToCircle() gs.FilledOff() elif t=='plus': gs.SetGlyphTypeToCross() gs.FilledOff() elif t=='cross': gs.SetGlyphTypeToCross() gs.SetRotationAngle(45) gs.FilledOff() elif t[:6]=='square': gs.SetGlyphTypeToSquare() gs.FilledOff() elif t[:7]=='diamond': gs.SetGlyphTypeToDiamond() gs.FilledOff() elif t[:8]=='triangle': gs.SetGlyphTypeToTriangle() gs.FilledOff() if t[9]=="d": gs.SetRotationAngle(180) elif t[9]=="l": gs.SetRotationAngle(90) elif t[9]=="r": gs.SetRotationAngle(-90) elif t[9]=="u": gs.SetRotationAngle(0) elif t == "hurricane": s =s/5. ds = vtk.vtkDiskSource() ds.SetInnerRadius(.55*s) ds.SetOuterRadius(1.01*s) ds.SetCircumferentialResolution(90) ds.SetRadialResolution(30) gf = vtk.vtkGeometryFilter() gf.SetInputConnection(ds.GetOutputPort()) gf.Update() pd1 = gf.GetOutput() apd = vtk.vtkAppendPolyData() apd.AddInputData(pd1) pts = vtk.vtkPoints() pd = vtk.vtkPolyData() polygons = vtk.vtkCellArray() add_angle = numpy.pi/360. coords = [] angle1 = .6*numpy.pi angle2 = .88*numpy.pi while angle1<=angle2: coords.append([s*2+2*s*numpy.cos(angle1),2*s*numpy.sin(angle1)]) angle1+=add_angle angle1=.79*numpy.pi angle2=.6*numpy.pi while angle1>=angle2: coords.append([s*2.25+s*4*numpy.cos(angle1),-s*2+s*4*numpy.sin(angle1)]) angle1-=add_angle poly = genPoly(coords,pts,filled=True) polygons.InsertNextCell(poly) coords=[] angle1 = 1.6*numpy.pi angle2 = 1.9*numpy.pi while angle1 <= angle2: coords.append( [- s*2 + s*2*numpy.cos(angle1),s*2*numpy.sin(angle1)]) angle1 += add_angle angle1 = 1.8*numpy.pi angle2 = 1.6*numpy.pi while angle1 >= angle2: coords.append( [- s*2.27 + s*4*numpy.cos(angle1), s*2 + s*4*numpy.sin(angle1)]) angle1 -= add_angle poly = genPoly(coords,pts,filled=True) polygons.InsertNextCell(poly) pd.SetPoints(pts) pd.SetPolys(polygons) apd.AddInputData(pd) apd.Update() g.SetSourceData(apd.GetOutput()) elif t[:4] == "star": np = 5 points = starPoints(.001 * s, 0, 0, np) pts = vtk.vtkPoints() # Add all perimeter points for point in points: pts.InsertNextPoint((point[0], point[1], 0)) center_id = len(points) # Add center point pts.InsertNextPoint((0,0,0)) polygons = vtk.vtkCellArray() for ind in range(0, np*2, 2): poly = vtk.vtkPolygon() pid = poly.GetPointIds() pid.SetNumberOfIds(4) pid.SetId(0, ind) pid.SetId(1, (ind - 1) % len(points)) pid.SetId(2, center_id) pid.SetId(3, (ind + 1) % len(points)) polygons.InsertNextCell(poly) pd = vtk.vtkPolyData() pd.SetPoints(pts) pd.SetPolys(polygons) g.SetSourceData(pd) elif t in ["w%.2i" % x for x in range(203)]: ## WMO marker params = wmo[t] pts = vtk.vtkPoints() pd = vtk.vtkPolyData() polys = vtk.vtkCellArray() lines = vtk.vtkCellArray() s*=3 #Lines first for l in params["line"]: coords = numpy.array(zip(*l))*s/30. line = genPoly(coords.tolist(),pts,filled=False) lines.InsertNextCell(line) for l in params["poly"]: coords = numpy.array(zip(*l))*s/30. line = genPoly(coords.tolist(),pts,filled=True) polys.InsertNextCell(line) geo,pts = project(pts,marker.projection,marker.worldcoordinate) pd.SetPoints(pts) pd.SetPolys(polys) pd.SetLines(lines) g.SetSourceData(pd) else: warnings.warn("unknown marker type: %s, using dot" % t) gs.SetGlyphTypeToCircle() gs.FilledOn() if t[-5:]=="_fill": gs.FilledOn() if pd is None: # Use the difference in x to scale the point, as later we'll use the # x range to correct the aspect ratio: dx = marker.worldcoordinate[1] - marker.worldcoordinate[0] s *= abs(float(dx))/500. gs.SetScale(s) gs.Update() g.SetSourceConnection(gs.GetOutputPort()) return gs, pd
def GeometricObjects(self): GeometricObjects = list() GeometricObjects.append(vtk.vtkArrowSource()) GeometricObjects.append(vtk.vtkConeSource()) GeometricObjects.append(vtk.vtkCubeSource()) GeometricObjects.append(vtk.vtkCylinderSource()) GeometricObjects.append(vtk.vtkDiskSource()) GeometricObjects.append(vtk.vtkLineSource()) GeometricObjects.append(vtk.vtkRegularPolygonSource()) GeometricObjects.append(vtk.vtkSphereSource()) renderers = list() mappers = list() actors = list() textmappers = list() textactors = list() # Create a common text property. textProperty = vtk.vtkTextProperty() textProperty.SetFontSize(10) textProperty.SetJustificationToCentered() # Create a parametric function source, renderer, mapper # and actor for each object. for idx, item in enumerate(GeometricObjects): GeometricObjects[idx].Update() mappers.append(vtk.vtkPolyDataMapper()) mappers[idx].SetInputConnection( GeometricObjects[idx].GetOutputPort()) actors.append(vtk.vtkActor()) actors[idx].SetMapper(mappers[idx]) textmappers.append(vtk.vtkTextMapper()) textmappers[idx].SetInput(item.GetClassName()) textmappers[idx].SetTextProperty(textProperty) textactors.append(vtk.vtkActor2D()) textactors[idx].SetMapper(textmappers[idx]) textactors[idx].SetPosition(150, 16) renderers.append(vtk.vtkRenderer()) gridDimensions = 3 for idx in range(len(GeometricObjects)): if idx < gridDimensions * gridDimensions: renderers.append(vtk.vtkRenderer) rendererSize = 300 # Create the RenderWindow # renderWindow = vtk.vtkRenderWindow() renderWindow.SetSize(rendererSize * gridDimensions, rendererSize * gridDimensions) # Add and position the renders to the render window. viewport = list() for row in range(gridDimensions): for col in range(gridDimensions): idx = row * gridDimensions + col viewport[:] = [] viewport.append( float(col) * rendererSize / (gridDimensions * rendererSize)) viewport.append( float(gridDimensions - (row + 1)) * rendererSize / (gridDimensions * rendererSize)) viewport.append( float(col + 1) * rendererSize / (gridDimensions * rendererSize)) viewport.append( float(gridDimensions - row) * rendererSize / (gridDimensions * rendererSize)) if idx > (len(GeometricObjects) - 1): continue renderers[idx].SetViewport(viewport) renderWindow.AddRenderer(renderers[idx]) renderers[idx].AddActor(actors[idx]) renderers[idx].AddActor(textactors[idx]) renderers[idx].SetBackground(0.4, 0.3, 0.2) interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renderWindow) renderWindow.Render() interactor.Start()
import vtk # create a rendering window and renderer ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) # create a renderwindowinteractor iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) i = 1 sourc = [] mapper = [] actor = [] for i in range(0, 100): sourc.append(vtk.vtkDiskSource()) sourc[i].SetInnerRadius(1.5) sourc[i].SetOuterRadius(2) sourc[i].SetRadialResolution(100) sourc[i].SetCircumferentialResolution(100) sourc[i].Update() mapper.append(vtk.vtkPolyDataMapper()) mapper[i].SetInput(sourc[i].GetOutput()) actor.append(vtk.vtkActor()) actor[i].SetMapper(mapper[i]) actor[i].SetPosition(0, 0, i / 10) ren.AddActor(actor[i]) i = i + 1
def prepMarker(renWin, ren, marker, cmap=None): n = prepPrimitive(marker) if n == 0: return for i in range(n): ## Creates the glyph g = vtk.vtkGlyph2D() markers = vtk.vtkPolyData() x = marker.x[i] y = marker.y[i] c = marker.color[i] s = marker.size[i] / float(max(marker.worldcoordinate)) * 10. t = marker.type[i] N = max(len(x), len(y)) for a in [x, y]: while len(a) < n: a.append(a[-1]) pts = vtk.vtkPoints() geo, pts = project(pts, marker.projection, marker.worldcoordinate) for j in range(N): pts.InsertNextPoint(x[j], y[j], 0.) markers.SetPoints(pts) # Type ## Ok at this point generates the source for glpyh gs = vtk.vtkGlyphSource2D() pd = None if t == 'dot': gs.SetGlyphTypeToCircle() gs.FilledOn() elif t == 'circle': gs.SetGlyphTypeToCircle() gs.FilledOff() elif t == 'plus': gs.SetGlyphTypeToCross() gs.FilledOff() elif t == 'cross': gs.SetGlyphTypeToCross() gs.SetRotationAngle(45) gs.FilledOff() elif t[:6] == 'square': gs.SetGlyphTypeToSquare() gs.FilledOff() elif t[:7] == 'diamond': gs.SetGlyphTypeToDiamond() gs.FilledOff() elif t[:8] == 'triangle': gs.SetGlyphTypeToTriangle() if t[9] == "d": gs.SetRotationAngle(180) elif t[9] == "l": gs.SetRotationAngle(90) elif t[9] == "r": gs.SetRotationAngle(-90) elif t[9] == "u": gs.SetRotationAngle(0) elif t == "hurricane": s = s / 10. ds = vtk.vtkDiskSource() ds.SetInnerRadius(.55 * s) ds.SetOuterRadius(1.01 * s) ds.SetCircumferentialResolution(90) ds.SetRadialResolution(30) gf = vtk.vtkGeometryFilter() gf.SetInputConnection(ds.GetOutputPort()) gf.Update() pd1 = gf.GetOutput() apd = vtk.vtkAppendPolyData() apd.AddInputData(pd1) pts = vtk.vtkPoints() pd = vtk.vtkPolyData() polygons = vtk.vtkCellArray() add_angle = numpy.pi / 360. coords = [] angle1 = .6 * numpy.pi angle2 = .88 * numpy.pi while angle1 <= angle2: coords.append([ s * 2 + 2 * s * numpy.cos(angle1), 2 * s * numpy.sin(angle1) ]) angle1 += add_angle angle1 = .79 * numpy.pi angle2 = .6 * numpy.pi while angle1 >= angle2: coords.append([ s * 2.25 + s * 4 * numpy.cos(angle1), -s * 2 + s * 4 * numpy.sin(angle1) ]) angle1 -= add_angle poly = genPoly(coords, pts, filled=True) polygons.InsertNextCell(poly) coords = [] angle1 = 1.6 * numpy.pi angle2 = 1.9 * numpy.pi while angle1 <= angle2: coords.append([ -s * 2 + s * 2 * numpy.cos(angle1), s * 2 * numpy.sin(angle1) ]) angle1 += add_angle angle1 = 1.8 * numpy.pi angle2 = 1.6 * numpy.pi while angle1 >= angle2: coords.append([ -s * 2.27 + s * 4 * numpy.cos(angle1), s * 2 + s * 4 * numpy.sin(angle1) ]) angle1 -= add_angle poly = genPoly(coords, pts, filled=True) polygons.InsertNextCell(poly) pd.SetPoints(pts) pd.SetPolys(polygons) apd.AddInputData(pd) apd.Update() g.SetSourceData(apd.GetOutput()) elif t in ["w%.2i" % x for x in range(203)]: ## WMO marker params = wmo[t] pts = vtk.vtkPoints() pd = vtk.vtkPolyData() polys = vtk.vtkCellArray() lines = vtk.vtkCellArray() #Lines first for l in params["line"]: coords = numpy.array(zip(*l)) * s / 30. line = genPoly(coords.tolist(), pts, filled=False) lines.InsertNextCell(line) for l in params["poly"]: coords = numpy.array(zip(*l)) * s / 30. line = genPoly(coords.tolist(), pts, filled=True) polys.InsertNextCell(line) geo, pts = project(pts, marker.projection, marker.worldcoordinate) pd.SetPoints(pts) pd.SetPolys(polys) pd.SetLines(lines) g.SetSourceData(pd) else: warnings.warn("unknown marker type: %s, using dot" % t) gs.SetGlyphTypeToCircle() gs.FilledOn() if t[-5:] == "_fill": gs.FilledOn() gs.SetScale(s) gs.Update() if pd is None: g.SetSourceConnection(gs.GetOutputPort()) g.SetInputData(markers) a = vtk.vtkActor() m = vtk.vtkPolyDataMapper() m.SetInputConnection(g.GetOutputPort()) m.Update() a.SetMapper(m) p = a.GetProperty() #Color if cmap is None: if marker.colormap is not None: cmap = marker.colormap else: cmap = 'default' if isinstance(cmap, str): cmap = vcs.elements["colormap"][cmap] color = cmap.index[c] p.SetColor([C / 100. for C in color]) ren.AddActor(a) fitToViewport(a, ren, marker.viewport, wc=marker.worldcoordinate, geo=geo) return
#!/usr/bin/env python import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # Create the RenderWindow, Renderer and both Actors # ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) disk = vtk.vtkDiskSource() disk.SetInnerRadius(1.0) disk.SetOuterRadius(2.0) disk.SetRadialResolution(1) disk.SetCircumferentialResolution(20) diskMapper = vtk.vtkPolyDataMapper() diskMapper.SetInputConnection(disk.GetOutputPort()) diskActor = vtk.vtkActor() diskActor.SetMapper(diskMapper) # Add the actors to the renderer, set the background and size # ren1.AddActor(diskActor) ren1.SetBackground(0.1,0.2,0.4) renWin.SetSize(200,200) # Get handles to some useful objects # iren.Initialize() renWin.Render()
def Initialize(self): """Prepare the class to work.""" self.Initialized = True # Radius self.r = r = 0.1 # Disk self.diskSrc = diskSrc = vtk.vtkDiskSource() diskSrc.SetCircumferentialResolution(50) diskSrc.SetInnerRadius(r) diskSrc.SetOuterRadius(3*r) diskSrc.Update() # Lens Triangle self.trianglePoints = trianglePoints = vtk.vtkPoints() trianglePoints.InsertNextPoint(0,-r*0.9,0) trianglePoints.InsertNextPoint(-r*0.05,-r,0) trianglePoints.InsertNextPoint(r*0.05,-r,0) self.triangleSrc = triangleSrc = vtk.vtkTriangle() for i in range(3): triangleSrc.GetPointIds().SetId(i,i) self.triangleCells = triangleCells = vtk.vtkCellArray() triangleCells.InsertNextCell(triangleSrc) self.trianglePD = trianglePD = vtk.vtkPolyData() trianglePD.SetPoints(trianglePoints) trianglePD.SetPolys(triangleCells) # Mappers self.diskMapper = diskMapper = vtk.vtkPolyDataMapper() diskMapper.SetInputConnection(diskSrc.GetOutputPort()) self.triangleMapper = triangleMapper = vtk.vtkPolyDataMapper() triangleMapper.SetInput(trianglePD) # Actors self.diskActor = diskActor = vtk.vtkFollower() diskActor.SetMapper(diskMapper) diskActor.GetProperty().SetColor(0,0,0) self.triangleActor = triangleActor = vtk.vtkFollower() triangleActor.SetMapper(triangleMapper) triangleActor.GetProperty().SetColor(0,0,0) # Positioning self.cam = self.sc.GetCamera() self.p = self.cam.GetPosition() self.d = d = self.cam.GetDirectionOfProjection() factor = 0.2 diskActor.AddPosition(self.p[0] + factor*d[0], \ self.p[1] + factor*d[1], self.p[2] + factor*d[2]) triangleActor.AddPosition(self.p[0] + factor*d[0], \ self.p[1] + factor*d[1], self.p[2] + factor*d[2]) self.ren = ren = self.sc.GetRenderWindow().GetRenderers().GetFirstRenderer() ren.AddActor(diskActor) ren.AddActor(triangleActor) diskActor.SetCamera(self.cam) triangleActor.SetCamera(self.cam)
cellId = intersectingCellIds.GetId(i) point = np.array(peel_centers.GetPoint(cellId)) distance = np.linalg.norm(point - cc) if distance < closestDist: closestDist = distance closestPoint = point normal = np.array(peel_normals.GetTuple(cellId)) angle = np.rad2deg(np.arccos(np.dot(normal, -no))) print(angle) #---------------------------------------------------------------------------------- # ↓↓ This part just draws things # Create a disk to show target disk = vtk.vtkDiskSource() disk.SetInnerRadius(2) disk.SetOuterRadius(4) disk.SetRadialResolution(100) disk.SetCircumferentialResolution(100) disk.Update() disk_mapper = vtk.vtkPolyDataMapper() disk_mapper.SetInputData(disk.GetOutput()) disk_actor = vtk.vtkActor() disk_actor.SetMapper(disk_mapper) disk_actor.GetProperty().SetColor(1, 0, 0) disk_actor.GetProperty().SetOpacity(0.4) disk_actor.SetPosition(closestPoint[0], closestPoint[1], closestPoint[2]) disk_actor.SetOrientation(cd[0], cd[1], cd[2])
def main(): colors = vtk.vtkNamedColors() # Set the background color. colors.SetColor("BkgColor", [51, 77, 102, 255]) # Create container to hold the 3D object generators (sources) geometricObjectSources = list() # Populate the container with the various object sources to be demonstrated geometricObjectSources.append(vtk.vtkArrowSource()) geometricObjectSources.append(vtk.vtkConeSource()) geometricObjectSources.append(vtk.vtkCubeSource()) geometricObjectSources.append(vtk.vtkCylinderSource()) geometricObjectSources.append(vtk.vtkDiskSource()) geometricObjectSources.append(vtk.vtkLineSource()) geometricObjectSources.append(vtk.vtkRegularPolygonSource()) geometricObjectSources.append(vtk.vtkSphereSource()) # Create containers for the remaining nodes of each pipeline mappers = list() actors = list() textmappers = list() textactors = list() # Create a common text property. textProperty = vtk.vtkTextProperty() textProperty.SetFontSize(16) textProperty.SetJustificationToCentered() # Create a mapper and actor for each object and the corresponding text label for i in range(0, len(geometricObjectSources)): geometricObjectSources[i].Update() mappers.append(vtk.vtkPolyDataMapper()) mappers[i].SetInputConnection(geometricObjectSources[i].GetOutputPort()) actors.append(vtk.vtkActor()) actors[i].SetMapper(mappers[i]) actors[i].GetProperty().SetColor( colors.GetColor3d("Seashell")) textmappers.append(vtk.vtkTextMapper()) textmappers[i].SetInput( geometricObjectSources[i].GetClassName()) # set text label to the name of the object source textmappers[i].SetTextProperty(textProperty) textactors.append(vtk.vtkActor2D()) textactors[i].SetMapper(textmappers[i]) textactors[i].SetPosition(120, 16) # Note: the position of an Actor2D is specified in display coordinates # Define size of the grid that will hold the objects gridCols = 3 gridRows = 3 # Define side length (in pixels) of each renderer square rendererSize = 300 renderWindow = vtk.vtkRenderWindow() renderWindow.SetWindowName("Geometric Objects Demo") renderWindow.SetSize(rendererSize * gridCols, rendererSize * gridRows) # Set up a grid of viewports for each renderer for row in range(0, gridRows): for col in range(0, gridCols): index = row * gridCols + col # Create a renderer for this grid cell renderer = vtk.vtkRenderer() renderer.SetBackground(colors.GetColor3d("BkgColor")) # Set the renderer's viewport dimensions (xmin, ymin, xmax, ymax) within the render window. # Note that for the Y values, we need to subtract the row index from gridRows # because the viewport Y axis points upwards, but we want to draw the grid from top to down viewport = [ float(col) / gridCols, float(gridRows - row - 1) / gridRows, float(col + 1) / gridCols, float(gridRows - row) / gridRows ] renderer.SetViewport(viewport) # Add the corresponding actor and label for this grid cell, if they exist if index < len(geometricObjectSources): renderer.AddActor(actors[index]) renderer.AddActor(textactors[index]) renderer.ResetCameraClippingRange() renderWindow.AddRenderer(renderer) interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renderWindow) renderWindow.Render() interactor.Start()
def GeometricObjects(self): GeometricObjects = list() GeometricObjects.append(vtk.vtkArrowSource()) GeometricObjects.append(vtk.vtkConeSource()) GeometricObjects.append(vtk.vtkCubeSource()) GeometricObjects.append(vtk.vtkCylinderSource()) GeometricObjects.append(vtk.vtkDiskSource()) GeometricObjects.append(vtk.vtkLineSource()) GeometricObjects.append(vtk.vtkRegularPolygonSource()) GeometricObjects.append(vtk.vtkSphereSource()) renderers = list() mappers = list() actors = list() textmappers = list() textactors = list() # Create a common text property. textProperty = vtk.vtkTextProperty() textProperty.SetFontSize(10) textProperty.SetJustificationToCentered() # Create a parametric function source, renderer, mapper # and actor for each object. for idx, item in enumerate(GeometricObjects): GeometricObjects[idx].Update() mappers.append(vtk.vtkPolyDataMapper()) mappers[idx].SetInputConnection(GeometricObjects[idx].GetOutputPort()) actors.append(vtk.vtkActor()) actors[idx].SetMapper(mappers[idx]) textmappers.append(vtk.vtkTextMapper()) textmappers[idx].SetInput(item.GetClassName()) textmappers[idx].SetTextProperty(textProperty) textactors.append(vtk.vtkActor2D()) textactors[idx].SetMapper(textmappers[idx]) textactors[idx].SetPosition(150, 16) renderers.append(vtk.vtkRenderer()) gridDimensions = 3 for idx in range(len(GeometricObjects)): if idx < gridDimensions * gridDimensions: renderers.append(vtk.vtkRenderer) rendererSize = 300 # Create the RenderWindow # renderWindow = vtk.vtkRenderWindow() renderWindow.SetSize(rendererSize * gridDimensions, rendererSize * gridDimensions) # Add and position the renders to the render window. viewport = list() for row in range(gridDimensions): for col in range(gridDimensions): idx = row * gridDimensions + col viewport[:] = [] viewport.append(float(col) * rendererSize / (gridDimensions * rendererSize)) viewport.append(float(gridDimensions - (row+1)) * rendererSize / (gridDimensions * rendererSize)) viewport.append(float(col+1)*rendererSize / (gridDimensions * rendererSize)) viewport.append(float(gridDimensions - row) * rendererSize / (gridDimensions * rendererSize)) if idx > (len(GeometricObjects) - 1): continue renderers[idx].SetViewport(viewport) renderWindow.AddRenderer(renderers[idx]) renderers[idx].AddActor(actors[idx]) renderers[idx].AddActor(textactors[idx]) renderers[idx].SetBackground(0.4,0.3,0.2) interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renderWindow) renderWindow.Render() interactor.Start()
vxz = bestfit([[pt[0], pt[2]] for pt in pts]) if vxz[0] == 0.0: print "Error: surface has infinite slope when projected onto x-z plane" a = vxz[1] / vxz[0] vyz = bestfit([[pt[1], pt[2]] for pt in pts]) if vyz[0] == 0.0: print "Error: surface has infinite slope when projected onto y-z plane" b = vyz[1] / vyz[0] if opts.verbose: print "Slope params =", a, b # generate points on a annulus if opts.verbose: print "Generating points on an annulus around data" dist_between_pts = outer_radius / opts.res circumferential_resolution = int(2 * 3.1415 * outer_radius / dist_between_pts) ann = vtk.vtkDiskSource() ann.SetInnerRadius(0.0) ann.SetOuterRadius(outer_radius) ann.SetRadialResolution(opts.res) ann.SetCircumferentialResolution(circumferential_resolution) ann.Update() # transform this annulus to the data (xmin, xmax, ymin, ymax, zmin, zmax) = orig.GetBounds() (x_centre, y_centre) = (0.5 * (xmax + xmin), 0.5 * (ymax + ymin)) trans = vtk.vtkTransform() trans.Translate(x_centre, y_centre, 0) newpts = vtk.vtkTransformFilter() newpts.SetInput(ann.GetOutput()) newpts.SetTransform(trans) newpts.Update()
def prepMarker(renWin,ren,marker,cmap=None): n=prepPrimitive(marker) if n==0: return for i in range(n): ## Creates the glyph g = vtk.vtkGlyph2D() markers = vtk.vtkPolyData() x = marker.x[i] y=marker.y[i] c=marker.color[i] s=marker.size[i]/float(max(marker.worldcoordinate))*10. t=marker.type[i] N = max(len(x),len(y)) for a in [x,y]: while len(a)<n: a.append(a[-1]) pts = vtk.vtkPoints() for j in range(N): pts.InsertNextPoint(x[j],y[j],0.) markers.SetPoints(pts) # Type ## Ok at this point generates the source for glpyh gs = vtk.vtkGlyphSource2D() pd = None if t=='dot': gs.SetGlyphTypeToCircle() gs.FilledOn() elif t=='circle': gs.SetGlyphTypeToCircle() gs.FilledOff() elif t=='plus': gs.SetGlyphTypeToCross() gs.FilledOff() elif t=='cross': gs.SetGlyphTypeToCross() gs.SetRotationAngle(45) gs.FilledOff() elif t[:6]=='square': gs.SetGlyphTypeToSquare() gs.FilledOff() elif t[:7]=='diamond': gs.SetGlyphTypeToDiamond() gs.FilledOff() elif t[:8]=='triangle': gs.SetGlyphTypeToTriangle() if t[9]=="d": gs.SetRotationAngle(180) elif t[9]=="l": gs.SetRotationAngle(90) elif t[9]=="r": gs.SetRotationAngle(-90) elif t[9]=="u": gs.SetRotationAngle(0) elif t == "hurricane": s =s/100. ds = vtk.vtkDiskSource() ds.SetInnerRadius(.55*s) ds.SetOuterRadius(1.01*s) ds.SetCircumferentialResolution(90) ds.SetRadialResolution(30) gf = vtk.vtkGeometryFilter() gf.SetInputConnection(ds.GetOutputPort()) gf.Update() pd1 = gf.GetOutput() apd = vtk.vtkAppendPolyData() apd.AddInputData(pd1) pts = vtk.vtkPoints() pd = vtk.vtkPolyData() polygons = vtk.vtkCellArray() add_angle = numpy.pi/360. coords = [] angle1 = .6*numpy.pi angle2 = .88*numpy.pi while angle1<=angle2: coords.append([s*2+2*s*numpy.cos(angle1),2*s*numpy.sin(angle1)]) angle1+=add_angle angle1=.79*numpy.pi angle2=.6*numpy.pi while angle1>=angle2: coords.append([s*2.25+s*4*numpy.cos(angle1),-s*2+s*4*numpy.sin(angle1)]) angle1-=add_angle poly = genPoly(coords,pts,filled=True) polygons.InsertNextCell(poly) coords=[] angle1 = 1.6*numpy.pi angle2 = 1.9*numpy.pi while angle1 <= angle2: coords.append( [- s*2 + s*2*numpy.cos(angle1),s*2*numpy.sin(angle1)]) angle1 += add_angle angle1 = 1.8*numpy.pi angle2 = 1.6*numpy.pi while angle1 >= angle2: coords.append( [- s*2.27 + s*4*numpy.cos(angle1), s*2 + s*4*numpy.sin(angle1)]) angle1 -= add_angle poly = genPoly(coords,pts,filled=True) polygons.InsertNextCell(poly) pd.SetPoints(pts) pd.SetPolys(polygons) apd.AddInputData(pd) apd.Update() g.SetSourceData(apd.GetOutput()) elif t in ["w%.2i" % x for x in range(203)]: ## WMO marker params = wmo[t] pts = vtk.vtkPoints() pd = vtk.vtkPolyData() polys = vtk.vtkCellArray() lines = vtk.vtkCellArray() #Lines first for l in params["line"]: coords = numpy.array(zip(*l))*s/30. line = genPoly(coords.tolist(),pts,filled=False) lines.InsertNextCell(line) for l in params["poly"]: coords = numpy.array(zip(*l))*s/30. line = genPoly(coords.tolist(),pts,filled=True) polys.InsertNextCell(line) pd.SetPoints(pts) pd.SetPolys(polys) pd.SetLines(lines) g.SetSourceData(pd) else: warnings.warn("unknown marker type: %s, using dot" % t) gs.SetGlyphTypeToCircle() gs.FilledOn() if t[-5:]=="_fill": gs.FilledOn() gs.SetScale(s) gs.Update() if pd is None: g.SetSourceConnection(gs.GetOutputPort()) g.SetInputData(markers) a = vtk.vtkActor() m = vtk.vtkPolyDataMapper() m.SetInputConnection(g.GetOutputPort()) m.Update() a.SetMapper(m) p = a.GetProperty() #Color if cmap is None: if marker.colormap is not None: cmap = marker.colormap else: cmap = 'default' if isinstance(cmap,str): cmap = vcs.elements["colormap"][cmap] color = cmap.index[c] p.SetColor([C/100. for C in color]) ren.AddActor(a) fitToViewport(a,ren,marker.viewport,marker.worldcoordinate) return
def __init__(self, parent = None): super(VTKFrame, self).__init__(parent) self.vtkWidget = QVTKRenderWindowInteractor(self) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() vl = QtGui.QVBoxLayout(self) vl.addWidget(self.vtkWidget) vl.setContentsMargins(0, 0, 0, 0) # Create source geometricObjects = list() geometricObjects.append(vtk.vtkArrowSource()) geometricObjects.append(vtk.vtkConeSource()) geometricObjects.append(vtk.vtkCubeSource()) geometricObjects.append(vtk.vtkCylinderSource()) geometricObjects.append(vtk.vtkDiskSource()) geometricObjects.append(vtk.vtkLineSource()) geometricObjects.append(vtk.vtkRegularPolygonSource()) geometricObjects.append(vtk.vtkSphereSource()) renderers = list() mappers = list() actors = list() textmappers = list() textactors = list() # Create a common text property. textProperty = vtk.vtkTextProperty() textProperty.SetFontSize(10) textProperty.SetJustificationToCentered() # Create a parametric function source, renderer, mapper # and actor for each object. for idx, item in enumerate(geometricObjects): geometricObjects[idx].Update() mappers.append(vtk.vtkPolyDataMapper()) mappers[idx].SetInputConnection(geometricObjects[idx].GetOutputPort()) actors.append(vtk.vtkActor()) actors[idx].SetMapper(mappers[idx]) textmappers.append(vtk.vtkTextMapper()) textmappers[idx].SetInput(item.GetClassName()) textmappers[idx].SetTextProperty(textProperty) textactors.append(vtk.vtkActor2D()) textactors[idx].SetMapper(textmappers[idx]) textactors[idx].SetPosition(150, 16) renderers.append(vtk.vtkRenderer()) gridDimensions = 3 for idx in range(len(geometricObjects)): if idx < gridDimensions * gridDimensions: renderers.append(vtk.vtkRenderer()) rendererSize = 300 # Setup the RenderWindow self.vtkWidget.GetRenderWindow().SetSize(rendererSize * gridDimensions, rendererSize * gridDimensions) # Add and position the renders to the render window. viewport = list() for row in range(gridDimensions): for col in range(gridDimensions): idx = row * gridDimensions + col viewport[:] = [] viewport.append(float(col) * rendererSize / (gridDimensions * rendererSize)) viewport.append(float(gridDimensions - (row+1)) * rendererSize / (gridDimensions * rendererSize)) viewport.append(float(col+1)*rendererSize / (gridDimensions * rendererSize)) viewport.append(float(gridDimensions - row) * rendererSize / (gridDimensions * rendererSize)) if idx > (len(geometricObjects) - 1): continue renderers[idx].SetViewport(viewport) self.vtkWidget.GetRenderWindow().AddRenderer(renderers[idx]) renderers[idx].AddActor(actors[idx]) renderers[idx].AddActor(textactors[idx]) renderers[idx].SetBackground(0.4,0.3,0.2) self._initialized = False
"MouseMoveEvent 158 176 0 0 0 0 i" \ "MouseMoveEvent 160 178 0 0 0 0 i" \ "MouseMoveEvent 163 181 0 0 0 0 i" \ "MouseMoveEvent 168 188 0 0 0 0 i" \ "MouseMoveEvent 178 197 0 0 0 0 i" \ "MouseMoveEvent 195 209 0 0 0 0 i" \ "MouseMoveEvent 207 228 0 0 0 0 i" \ "MouseMoveEvent 220 247 0 0 0 0 i" \ "MouseMoveEvent 235 264 0 0 0 0 i" \ "MouseMoveEvent 246 283 0 0 0 0 i" \ "MouseMoveEvent 256 292 0 0 0 0 i" \ "LeaveEvent 256 292 0 0 0 0 i" \ "ExitEvent 256 292 0 0 0 0 i" # Create two widgets diskSource = vtk.vtkDiskSource() diskSource.SetInnerRadius(0.0) diskSource.SetOuterRadius(2) diskMapper = vtk.vtkPolyDataMapper2D() diskMapper.SetInput(diskSource.GetOutput()) diskActor = vtk.vtkActor2D() diskActor.SetMapper(diskMapper) diskActor.SetPosition(165, 180) diskSource2 = vtk.vtkDiskSource() diskSource2.SetInnerRadius(0.0) diskSource2.SetOuterRadius(2) diskMapper2 = vtk.vtkPolyDataMapper2D()