Exemple #1
0
def CreateCoords_versore(o, r):
    """ Ritorna una lista di attori contenenti i il sistema di coordinate:
    o = origine
    r = versore"""
    points = []
    Lines=[]
    Polygon = vtk.vtkPolyData()
    ac=[]
    
    points = vtk.vtkPoints()
            
    points.SetNumberOfPoints(4)

    points.SetPoint(0, self.midPoint)
    points.SetPoint(1, [self.FrenetBinormalArray[0]+self.midPoint[0], self.FrenetBinormalArray[1]+self.midPoint[1], self.FrenetBinormalArray[2]+self.midPoint[2]])
    points.SetPoint(2, [self.FrenetNormalArray[0]+self.midPoint[0], self.FrenetNormalArray[1]+self.midPoint[1], self.FrenetNormalArray[2]+self.midPoint[2]])
    points.SetPoint(3, [self.FrenetTangentArray[0]+self.midPoint[0], self.FrenetTangentArray[1]+self.midPoint[1], self.FrenetTangentArray[2]+self.midPoint[2]])
     
    points.SetPoint(0, o)
    points.SetPoint(1, [o[0]+r[0], o[1]         , o[2]])
    points.SetPoint(2, [o[0]        , o[1]+r[1] ,  o[2]])
    points.SetPoint(3, [o[0]        , o[1]         ,  o[2]+r[2]])
    
    polyLine0 = vtk.vtkPolyLine()
    polyLine0.GetPointIds().SetNumberOfIds(2)
    polyLine0.GetPointIds().SetId(0,0)
    polyLine0.GetPointIds().SetId(1,1)
        
    polyLine1 = vtk.vtkPolyLine()
    polyLine1.GetPointIds().SetNumberOfIds(2)
    polyLine1.GetPointIds().SetId(0,0)
    polyLine1.GetPointIds().SetId(1,2)
    
    polyLine2 = vtk.vtkPolyLine()
    polyLine2.GetPointIds().SetNumberOfIds(2)
    polyLine2.GetPointIds().SetId(0,0)
    polyLine2.GetPointIds().SetId(1,3)
    
    cells0 = vtk.vtkCellArray()
    cells0.InsertNextCell(polyLine0)
    cells0.InsertNextCell(polyLine1)
    cells0.InsertNextCell(polyLine2)
    
    polyData = vtk.vtkPolyData()
    polyData.SetPoints(points)
    polyData.SetLines(cells0)
    
    ac=[]
        
    
    ac.append(CreateSphere(points.GetPoint(0), 0.05, [1, 1, 1]))
    ac.append(CreateSphere(points.GetPoint(1), 0.1, [1, 0, 0]))
    ac.append(CreateSphere(points.GetPoint(2), 0.1, [0, 1, 0]))
    ac.append(CreateSphere(points.GetPoint(3), 0.1, [0, 0, 1]))
        
                
    ac.append(CreateActor(polyData))
    return ac
Exemple #2
0
def create_polyline(points: List[Point3D]) -> PolyData:
    """Create a polyline from a list of points."""
    # Create a vtkPoints container and store the points for all the lines
    pts = vtk.vtkPoints()
    for pt in points:
        pts.InsertNextPoint(tuple(pt))

    # add all the points to lines dataset
    polyline = vtk.vtkPolyLine()
    polyline.GetPointIds().SetNumberOfIds(len(points))
    for i in range(len(points)):
        polyline.GetPointIds().SetId(i, i)

    # Create a cell array to store the lines in and add the lines to it
    cells = vtk.vtkCellArray()
    cells.InsertNextCell(polyline)

    # Create a polydata to store everything in
    polydata = PolyData()

    # Add the points to the dataset
    polydata.SetPoints(pts)

    # Add the lines to the dataset
    polydata.SetLines(cells)

    return polydata
Exemple #3
0
    def __init__(self, parent, visualizer, **kws):
        """
		Initialization
		"""
        self.x, self.y, self.z = -1, -1, -1
        VisualizationModule.__init__(self, parent, visualizer, **kws)
        #self.name = "Scale bar"
        self.renew = 1
        self.mapper = vtk.vtkDataSetMapper()

        self.actor = vtk.vtkActor()
        self.actor.SetMapper(self.mapper)
        self.width = 10
        self.widthPx = 100
        self.voxelSize = (1, 1, 1)

        self.renderer = self.parent.getRenderer()
        self.renderer.AddActor(self.actor)

        self.polyLine = vtk.vtkPolyLine()
        #self.mapper.SetInput(self.polyLine.GetOutput())
        self.actor.GetProperty().SetColor(1, 1, 1)

        self.textActor = vtk.vtkTextActor()
        #self.textActor.ScaledTextOn()
        self.renderer.AddActor2D(self.textActor)

        iactor = self.wxrenwin.GetRenderWindow().GetInteractor()
        style = iactor.GetInteractorStyle()
        #        style.AddObserver("StartInteractionEvent",self.updateLine)
        style.AddObserver("EndInteractionEvent", self.updateRendering)
Exemple #4
0
    def make_vtu_grid(self):
        all_points = vtkPoints()

        displacement = vtkDoubleArray()
        displacement.SetName('displacement')

        velocity = vtkDoubleArray()
        velocity.SetName('velocity')
        velocity.SetNumberOfComponents(3)

        ug = vtkUnstructuredGrid()
        ug.SetPoints(all_points)
        ug.GetPointData().SetScalars(displacement)
        ug.GetPointData().SetVectors(velocity)

        current_idx = 0
        for fiber in itertools.chain(self.weft.fibers, self.warp.fibers):
            polyline = vtkPolyLine()
            for point in fiber.points:
                all_points.InsertNextPoint(point.coords.x, point.coords.y,
                                           point.coords.z)
                polyline.GetPointIds().InsertNextId(current_idx)
                displacement.InsertNextValue(point.data)
                velocity.InsertNextTuple3(point.velocity.x, point.velocity.y,
                                          point.velocity.z)
                current_idx += 1

            ug.InsertNextCell(polyline.GetCellType(), polyline.GetPointIds())

        return ug
Exemple #5
0
def continentsVCS2VTK(fnm):
  """ This converts vcs continents files to vtkpolydata
  Author: Charles Doutriaux
  Input: vcs continent file name
  """
  poly =vtk.vtkPolyData()
  cells = vtk.vtkCellArray()
  pts = vtk.vtkPoints()
  f=open(fnm)
  ln=f.readline()
  while ln.strip().split()!=["-99","-99"]:
    # Many lines, need to know number of points
    N = int(ln.split()[0])
    # Now create and store these points
    n=0
    npts = pts.GetNumberOfPoints()
    while n<N:
        ln=f.readline()
        while len(ln)>2:
          l,L=float(ln[:8]),float(ln[8:16])
          pts.InsertNextPoint(L,l,0.0001)
          ln=ln[16:]
          n+=2
    ln = vtk.vtkPolyLine()
    ln.GetPointIds().SetNumberOfIds(N/2)
    for i in range(N/2): ln.GetPointIds().SetId(i,i+npts)
    cells.InsertNextCell(ln)
    ln=f.readline()
  poly.SetPoints(pts)
  poly.SetLines(cells)
  return poly
Exemple #6
0
    def new_mesh_set(self, all_meshes):
        """
        Define a new mesh set. This function must be called each time the number of meshes change
        Parameters
        ----------
        all_meshes : MeshCollection
            One frame of mesh

        """
        if isinstance(all_meshes, Mesh):
            mesh_tp = []
            mesh_tp.append(all_meshes)
            all_meshes = mesh_tp

        if not isinstance(all_meshes, list):
            raise TypeError("Please send a list of mesh to update_mesh")
        self.all_meshes = all_meshes

        # Remove previous actors from the scene
        for actor in self.mesh_actors:
            self.parent_window.ren.RemoveActor(actor)
        self.mesh_actors = list()

        # Create the geometry of a point (the coordinate) points = vtkPoints()
        for (i, mesh) in enumerate(self.all_meshes):
            if mesh.time.size != 1:
                raise IndexError("Mesh should be from one frame only")

            points = vtkPoints()
            for j in range(mesh.channel.size):
                points.InsertNextPoint([0, 0, 0])

            # Create an array for each triangle
            cell = vtkCellArray()
            for j in range(mesh.triangles.shape[1]):  # For each triangle
                line = vtkPolyLine()
                line.GetPointIds().SetNumberOfIds(4)
                for k in range(len(mesh.triangles[:, j])):  # For each index
                    line.GetPointIds().SetId(k, mesh.triangles[k, j])
                line.GetPointIds().SetId(3, mesh.triangles[0, j])  # Close the triangle
                cell.InsertNextCell(line)
            poly_line = vtkPolyData()
            poly_line.SetPoints(points)
            poly_line.SetLines(cell)

            # Create a mapper
            mapper = vtkPolyDataMapper()
            mapper.SetInputData(poly_line)

            # Create an actor
            self.mesh_actors.append(vtkActor())
            self.mesh_actors[i].SetMapper(mapper)
            self.mesh_actors[i].GetProperty().SetColor(self.mesh_color)
            self.mesh_actors[i].GetProperty().SetOpacity(self.mesh_opacity)

            self.parent_window.ren.AddActor(self.mesh_actors[i])
            self.parent_window.ren.ResetCamera()

        # Update marker position
        self.update_mesh(self.all_meshes)
	def __init__(self, parent, visualizer, **kws):
		"""
		Initialization
		"""     
		self.x, self.y, self.z = -1, -1, -1
		VisualizationModule.__init__(self, parent, visualizer, **kws)   
		#self.name = "Scale bar"
		self.renew = 1
		self.mapper = vtk.vtkDataSetMapper()
		
		self.actor = vtk.vtkActor()
		self.actor.SetMapper(self.mapper)
		self.width = 10
		self.widthPx = 100
		self.voxelSize = (1, 1, 1)
		
		self.renderer = self.parent.getRenderer()
		self.renderer.AddActor(self.actor)
		

		self.polyLine = vtk.vtkPolyLine()
		#self.mapper.SetInput(self.polyLine.GetOutput())
		self.actor.GetProperty().SetColor(1, 1, 1)
			   
		self.textActor = vtk.vtkTextActor()
		#self.textActor.ScaledTextOn()
		self.renderer.AddActor2D(self.textActor)
		
		iactor = self.wxrenwin.GetRenderWindow().GetInteractor()
		style = iactor.GetInteractorStyle()
#        style.AddObserver("StartInteractionEvent",self.updateLine)
		style.AddObserver("EndInteractionEvent", self.updateRendering)
Exemple #8
0
def skippoints(polydata,nskippoints):
    """Generate a single cell line from points in idlist."""

    # derive number of nodes
    numberofnodes = polydata.GetNumberOfPoints() - nskippoints

    # define points and line
    points = vtk.vtkPoints()
    polyline = vtk.vtkPolyLine()
    polyline.GetPointIds().SetNumberOfIds(numberofnodes)

    # assign id and x,y,z coordinates
    for i in range(nskippoints,polydata.GetNumberOfPoints()):
        pointid = i - nskippoints
        polyline.GetPointIds().SetId(pointid,pointid)
        point = polydata.GetPoint(i)
        points.InsertNextPoint(point)


    # define cell
    cells = vtk.vtkCellArray()
    cells.InsertNextCell(polyline)

    # add to polydata
    polyout = vtk.vtkPolyData()
    polyout.SetPoints(points)
    polyout.SetLines(cells)

    return polyout
Exemple #9
0
def ArcActor(fromValue, to, rad=1.0, axis='z', n=20):
    fromValue = fromValue * pi / 180
    to = to * pi / 180
    angle = to - fromValue

    ppnts = vtk.vtkPoints()
    ppnts.SetNumberOfPoints(n)

    for i in range(0, n):
        theta = fromValue + i * angle / (n - 1)
        if axis == 'x':
            ppnts.InsertPoint(i, 0.0, cos(theta), sin(theta))
        elif axis == 'y':
            ppnts.InsertPoint(i, sin(theta), 0.0, cos(theta))
        elif axis == 'z':
            ppnts.InsertPoint(i, cos(theta), sin(theta), 0.0)

    pline = vtk.vtkPolyLine()
    pline.GetPointIds().SetNumberOfIds(n)
    for i in range(0, n):
        pline.GetPointIds().SetId(i, i)

    pdata = vtk.vtkPolyData()
    pdata.Allocate(1, 1)
    pdata.InsertNextCell(pline.GetCellType(), pline.GetPointIds())
    pdata.SetPoints(ppnts)

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInput(pdata)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(1, 0, 0)
    return actor
Exemple #10
0
def createLineCells(Nx, Ny, **kwargs):
	''' Create lines corresponding to a Nx x Ny grid. 
	Parameters:
		:Nx (int): Number of points in the first dimension
		:Ny (int): Number of points in the second dimension
	Keyword arguments:
		:cutsectionIsClosed (bool or [bool]): Flag to indicate whether to wrap around the indices
		This is useful for creating a cell distribution for a cylinder
		Can also be an array of bools each indicating whether each of the sections in the x-direction should be wrapped 
	'''
	cells = vtk.vtkCellArray()
	cutsectionIsClosed = kwargs.get('cutsectionIsClosed', True)

	for i in range(Nx):
		if isinstance(cutsectionIsClosed, bool):
			wrapAround = cutsectionIsClosed
		else:
			# Assume array like
			wrapAround = cutsectionIsClosed[i] and cutsectionIsClosed[i-1]

		cell = vtk.vtkPolyLine()
		startId = i*Ny

		if wrapAround:
			cell.GetPointIds().SetNumberOfIds(Ny+1)
			cell.GetPointIds().SetId(Ny, startId)
		else:
			cell.GetPointIds().SetNumberOfIds(Ny)

		for j in range(Ny):
			cell.GetPointIds().SetId(j, startId+j)

		cells.InsertNextCell(cell)
	return cells
    def drawPolyLine(self, currentAnimationTime):

        #remove polyline cells older than lifetime
        if self.lifetimeEnabled and self.lifetime >= self.lifetimeMin:
            if (self.pdo.GetNumberOfCells() - self.lifetime) >= 0:
                #remove from the polyline cells older than lifetime
                self.pdo.DeleteCell(0)
                self.pdo.RemoveDeletedCells()

        aPolyLine = vtk.vtkPolyLine()
        aPolyLine.GetPointIds().SetNumberOfIds(self.heightCount)

        for j in range(0, self.heightCount):
            x = self.lon[currentAnimationTime]
            y = self.lat[currentAnimationTime]
            z = self.height[j]

            self.newPoints.InsertPoint(self.polyIndex + j, x, y, z)
            aPolyLine.GetPointIds().SetId(j, self.polyIndex + j)

        self.polyIndex += self.heightCount

        #Update the output polyline
        self.pdo.SetPoints(self.newPoints)
        self.pdo.InsertNextCell(aPolyLine.GetCellType(),
                                aPolyLine.GetPointIds())

        #timeCompare is unused for now, will be used to figure out wether the timesteps are played forward or backward
        self.timeCompare = currentAnimationTime
Exemple #12
0
def createSegNodeFromContourPoints(segmentationNode, contours, name):
    # set up contour objects
    contoursPolyData = vtk.vtkPolyData()
    contourPoints = vtk.vtkPoints()
    contourLines = vtk.vtkCellArray()
    contoursPolyData.SetLines(contourLines)
    contoursPolyData.SetPoints(contourPoints)

    for contour in contours:
        startPointIndex = contourPoints.GetNumberOfPoints()
        contourLine = vtk.vtkPolyLine()
        linePointIds = contourLine.GetPointIds()
        for point in contour:
            linePointIds.InsertNextId(contourPoints.InsertNextPoint(point))
        linePointIds.InsertNextId(
            startPointIndex)  # make the contour line closed
        contourLines.InsertNextCell(contourLine)

    segment = slicer.vtkSegment()
    segment.SetName(name)
    # segment.SetColor(segmentColor)
    segment.AddRepresentation("Planar contour", contoursPolyData)
    segmentationNode.GetSegmentation().SetMasterRepresentationName(
        "Planar contour")
    segmentationNode.GetSegmentation().AddSegment(segment)
Exemple #13
0
def main():
    # Parse commandline arguments.
    args = _parse_args()

    # Check input file extensions.
    for fname in args.input:
        if not (fname.endswith('.h5') or fname.endswith('.binary')):
            raise ValueError("Input file names must either end with '.h5' or"
                             "'.binary'.")

    # Make sure that the output filename ends with '.pvtp'.
    if not args.out:
        args.out = 'tracks.pvtp'
    elif os.path.splitext(args.out)[1] != '.pvtp':
        args.out = ''.join([args.out, '.pvtp'])

    # Import HDF library if HDF files are present
    for fname in args.input:
        if fname.endswith('.h5'):
            import h5py
            break

    # Initialize data arrays and offset.
    points = vtk.vtkPoints()
    cells = vtk.vtkCellArray()
    point_offset = 0
    for fname in args.input:
        # Write coordinate values to points array.
        if fname.endswith('.binary'):
            track = open(fname, 'rb').read()
            coords = [
                struct.unpack("ddd", track[24 * i:24 * (i + 1)])
                for i in range(len(track) / 24)
            ]
            n_points = len(coords)
            for triplet in coords:
                points.InsertNextPoint(triplet)
        else:
            coords = h5py.File(fname).get('coordinates')
            n_points = coords.shape[0]
            for i in range(n_points):
                points.InsertNextPoint(coords[i, :])

        # Create VTK line and assign points to line.
        line = vtk.vtkPolyLine()
        line.GetPointIds().SetNumberOfIds(n_points)
        for i in range(n_points):
            line.GetPointIds().SetId(i, point_offset + i)

        cells.InsertNextCell(line)
        point_offset += n_points
    data = vtk.vtkPolyData()
    data.SetPoints(points)
    data.SetLines(cells)

    writer = vtk.vtkXMLPPolyDataWriter()
    writer.SetInput(data)
    writer.SetFileName(args.out)
    writer.Write()
Exemple #14
0
    def draw(self, graphics):
        cell, pointnums = super(Line, self).draw(graphics)

        line = vtk.vtkPolyLine()
        line.GetPointIds().SetNumberOfIds(len(pointnums))
        for i, p in enumerate(pointnums):
            line.GetPointIds().SetId(i, p)
        cell.InsertNextCell(line)
Exemple #15
0
    def write_vtk(self, datadir='data', file_name='spines.vtk', binary=False):
        """
        Write the spines into a vtk file.

        call signature:

            write_vtk(datadir='data', file_name='spines.vtk', binary=False)

        Arguments:

        *datadir*:
            Target data directory.

        *file_name*:
            Target file name.

        *binary*:
            Write file in binary or ASCII format.
        """

        import os as os
        try:
            import vtk as vtk
        except:
            print("Warning: no vtk library found.")

        writer = vtk.vtkPolyDataWriter()
        if binary:
            writer.SetFileTypeToBinary()
        else:
            writer.SetFileTypeToASCII()
        writer.SetFileName(os.path.join(datadir, file_name))
        poly_data = vtk.vtkPolyData()
        points = vtk.vtkPoints()
        # Create the cell to store the lines in.
        cells = vtk.vtkCellArray()
        poly_lines = []
        offset = 0
        for line_idx in range(len(self.spines)):
            n_points = self.spines[line_idx].shape[0]
            poly_lines.append(vtk.vtkPolyLine())
            poly_lines[-1].GetPointIds().SetNumberOfIds(n_points)
            for point_idx in range(n_points):
                points.InsertNextPoint(self.spines[line_idx][point_idx])
                poly_lines[-1].GetPointIds().SetId(point_idx,
                                                   point_idx + offset)
            cells.InsertNextCell(poly_lines[-1])
            offset += n_points

        poly_data.SetPoints(points)
        poly_data.SetLines(cells)

        # Insure compatability between vtk 5 and 6.
        try:
            writer.SetInputData(poly_data)
        except:
            writer.SetInput(poly_data)
        writer.Write()
Exemple #16
0
def main():
    # Parse commandline arguments.
    args = _parse_args()

    # Check input file extensions.
    for fname in args.input:
        if not (fname.endswith('.h5') or fname.endswith('.binary')):
            raise ValueError("Input file names must either end with '.h5' or"
                             "'.binary'.")
    
    # Make sure that the output filename ends with '.pvtp'.
    if not args.out:
        args.out = 'tracks.pvtp'
    elif os.path.splitext(args.out)[1] != '.pvtp':
        args.out = ''.join([args.out, '.pvtp'])

    # Import HDF library if HDF files are present
    for fname in args.input:
        if fname.endswith('.h5'):
            import h5py
            break

    # Initialize data arrays and offset.
    points = vtk.vtkPoints()
    cells = vtk.vtkCellArray()
    point_offset = 0
    for fname in args.input:
        # Write coordinate values to points array.
        if fname.endswith('.binary'):
            track = open(fname, 'rb').read()
            coords = [struct.unpack("ddd", track[24*i : 24*(i+1)])
                      for i in range(len(track)/24)]
            n_points = len(coords)
            for triplet in coords:
                points.InsertNextPoint(triplet)
        else:
            coords = h5py.File(fname).get('coordinates')
            n_points = coords.shape[0]
            for i in range(n_points):
                points.InsertNextPoint(coords[i,:])
                
        # Create VTK line and assign points to line.
        line = vtk.vtkPolyLine()
        line.GetPointIds().SetNumberOfIds(n_points)
        for i in range(n_points):
            line.GetPointIds().SetId(i, point_offset+i)
        
        cells.InsertNextCell(line)
        point_offset += n_points
    data = vtk.vtkPolyData()
    data.SetPoints(points)
    data.SetLines(cells)
    
    writer = vtk.vtkXMLPPolyDataWriter()
    writer.SetInput(data)
    writer.SetFileName(args.out)
    writer.Write()
Exemple #17
0
    def runPlugin(self):
        global ariadne
        global CubeLoader

	skelvp=ariadne.QRWin.viewports["skeleton_viewport"]
	arbitvp=ariadne.QRWin.viewports["Orth_viewport"];

	arbitpl=arbitvp.ViewportPlane;
	tempLines = vtk.vtkPolyLine()
	tempLines.GetPointIds().SetNumberOfIds(2)
	tempLines.GetPointIds().SetId(0,0*3+0)
	tempLines.GetPointIds().SetId(1,0*3+1)

	for icell in range(arbitpl.ScaleBar.GetNumberOfCells()):
		arbitpl.ScaleBar.DeleteCell(icell);

	arbitpl.ScaleBar.RemoveDeletedCells();
	arbitpl.ScaleBar.InsertNextCell(tempLines.GetCellType(),tempLines.GetPointIds());

	ariadne.ChangeSynZoom(1);
	ariadne.SynchronizedZoom(0.034);
	ariadne.QRWin.Render();

	ariadne.RegionAlpha.setValue(15);
	ariadne.SomaAlpha.setValue(40);

	ariadne.ckbx_HideBorder.setChecked(0)
	ariadne.ckbx_ShowYXScaleBar.setChecked(0)
	ariadne.ckbx_ShowYZScaleBar.setChecked(0)
	ariadne.ckbx_ShowZXScaleBar.setChecked(0)
	ariadne.ckbx_ShowArbitScaleBar.setChecked(1)
	ariadne.ckbx_HideBorder.setChecked(1)

	FPoint=  (78233.9332778213, 61601.67070863842, 64849.07703562547) ;
	CamPos =  (237350.73945325083, 80656.08301123015, -39741.523057454404) ;
	ViewUp=  (0.12355078296512695, 0.9260262916142512, 0.3566658257639244) ;
	
	ariadne.SpinBox_ScaleBarWidth.setValue(2000)
	ariadne.radioBtn_tubesflat.setChecked(1)
	ariadne.SpinBox_Radius.setValue(150.0)
	ariadne.HideSkelNodes.setChecked(1)
	ariadne.ckbx_HideSomaLabels.setChecked(1)

	skelvp.Camera.SetViewUp(ViewUp)
	skelvp.Camera.SetFocalPoint(FPoint)
	skelvp.Camera.SetPosition(CamPos)
	skelvp.ResetCameraClippingRange();

	vDir=np.array(ViewUp)*1.0;
	vtk.vtkMath.Normalize(vDir)
	cDir=np.array(FPoint)-np.array(CamPos);
	vtk.vtkMath.Normalize(cDir)
	arbitvp.ViewportPlane.JumpToPoint(np.array(FPoint),np.array(cDir),np.array(vDir));

	skelvp.ResetCameraClippingRange();
	ariadne.QRWin.Render();
Exemple #18
0
def main():
    colors = vtk.vtkNamedColors()

    # Create five points.
    origin = [0.0, 0.0, 0.0]
    p0 = [1.0, 0.0, 0.0]
    p1 = [0.0, 1.0, 0.0]
    p2 = [0.0, 1.0, 2.0]
    p3 = [1.0, 2.0, 3.0]

    # Create a vtkPoints object and store the points in it
    points = vtk.vtkPoints()
    points.InsertNextPoint(origin)
    points.InsertNextPoint(p0)
    points.InsertNextPoint(p1)
    points.InsertNextPoint(p2)
    points.InsertNextPoint(p3)

    polyLine = vtk.vtkPolyLine()
    polyLine.GetPointIds().SetNumberOfIds(5)
    for i in range(0, 5):
        polyLine.GetPointIds().SetId(i, i)

    # Create a cell array to store the lines in and add the lines to it
    cells = vtk.vtkCellArray()
    cells.InsertNextCell(polyLine)

    # Create a polydata to store everything in
    polyData = vtk.vtkPolyData()

    # Add the points to the dataset
    polyData.SetPoints(points)

    # Add the lines to the dataset
    polyData.SetLines(cells)

    # Setup actor and mapper
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(polyData)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(colors.GetColor3d('Tomato'))

    # Setup render window, renderer, and interactor
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetWindowName('PolyLine')
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)
    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d('DarkOliveGreen'))

    renderWindow.Render()
    renderWindowInteractor.Start()
Exemple #19
0
    def drawTrajectoryFoldVTK(self, qTrajectories, animate = False, trajectoryColor = [1.0,0.0,1.0]):


        self.trajectory = self.createTrajectory(qTrajectories[0], qTrajectories[1], N =20)

        for i in range(1,len(qTrajectories)-1):
            qi = qTrajectories[i]
            qe = qTrajectories[i+1]
            self.trajectory = numpy.concatenate((self.trajectory,self.createTrajectory(qi, qe, N =20)))


        Npoints, Nparams = self.trajectory.shape
        points = numpy.zeros((Npoints,3))

        for i in range(Npoints):
            q = self.trajectory[i,:]
            self.moveRobot(q)
            points[i,:] = self.JointList[-1].Axis[0:3,3]


        pointsVTK = vtk.vtkPoints()
        polyLine = vtk.vtkPolyLine()
        polyLine.GetPointIds().SetNumberOfIds(Npoints)

        for i in range(Npoints):
            pointsVTK.InsertNextPoint(points[i,0],points[i,1],points[i,2])
            polyLine.GetPointIds().SetId(i,i)

        cells = vtk.vtkCellArray()
        cells.InsertNextCell(polyLine)
        polyData = vtk.vtkPolyData()
        polyData.SetPoints(pointsVTK)
        polyData.SetLines(cells)
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputData(polyData)
        trajectoryActor = vtk.vtkActor()
        trajectoryActor.SetMapper(mapper)
        trajectoryActor.GetProperty().SetColor(trajectoryColor[0],trajectoryColor[1],trajectoryColor[2])


        # Init to first point
        q = self.trajectory[0,:]
        self.moveRobot(q)

        # Update robot segments and models
        self.JointList[-1].update()

        # Add trajectory to axis
        if animate:
            self.timer_count = 0
            self.timer_countMax = Npoints
            self.timerBool = 1.0

        self.drawVTK(drawAxis = True, actorsToAdd = [trajectoryActor], animate = animate)
Exemple #20
0
    def __init__(self, radius=1.0):
        """
        Constructor
        @param radius earth's radius
        """

        self.sf = shapefile.Reader('ne_10m_coastline')

        self.pts = []
        self.lines = []
        self.ugrids = []

        self.appendFilter = vtk.vtkAppendFilter()

        for s in self.sf.shapes():

            numPoints = len(s.points)

            # skip some smaller features
            if numPoints < 100:
                # skip
                continue

            vpts = vtk.vtkPoints()
            line = vtk.vtkPolyLine()
            ug = vtk.vtkUnstructuredGrid()

            vpts.SetNumberOfPoints(numPoints)

            ptIds = line.GetPointIds()
            ptIds.SetNumberOfIds(numPoints)
            index = 0
            for p in s.points:
                lam, the = p[0] * np.pi / 180., p[1] * np.pi / 180.
                x = radius * np.cos(the) * np.cos(lam)
                y = radius * np.cos(the) * np.sin(lam)
                z = radius * np.sin(the)
                vpts.InsertPoint(index, x, y, z)
                ptIds.SetId(index, index)
                index += 1

            # one cell
            ug.InsertNextCell(line.GetCellType(), ptIds)
            ug.SetPoints(vpts)

            # append to list to prevent Python from delete referenced objects
            self.pts.append(vpts)
            self.lines.append(line)
            self.ugrids.append(ug)

            self.appendFilter.AddInputData(ug)

        self.appendFilter.Update()
        self.ugrid = self.appendFilter.GetOutput()
Exemple #21
0
    def createLine(self, x1: float, y1: float, z1: float, x2: float, y2: float,
                   z2: float, points: vtk.vtkPoints, cells: vtk.vtkCellArray):
        line = vtk.vtkPolyLine()
        line.GetPointIds().SetNumberOfIds(2)

        id_1 = points.InsertNextPoint(x1, y1, z1)  # vtkIdType
        id_2 = points.InsertNextPoint(x2, y2, z2)  # vtkIdType

        line.GetPointIds().SetId(0, id_1)
        line.GetPointIds().SetId(1, id_2)
        cells.InsertNextCell(line)
Exemple #22
0
            def ViewportBorder(renderer, color, last):
                # points start at upper right and proceed anti-clockwise
                points = vtk.vtkPoints()
                points.SetNumberOfPoints(4)
                points.InsertPoint(0, 1, 1, 0)
                points.InsertPoint(1, 0, 1, 0)
                points.InsertPoint(2, 0, 0, 0)
                points.InsertPoint(3, 1, 0, 0)

                # create cells, and lines
                cells = vtk.vtkCellArray()
                cells.Initialize()

                lines = vtk.vtkPolyLine()

                # only draw last line if this is the last viewport
                # this prevents double vertical lines at right border
                # if different colors are used for each border, then do
                # not specify last
                if (last):
                    lines.GetPointIds().SetNumberOfIds(5)
                else:
                    lines.GetPointIds().SetNumberOfIds(4)

                for i in range(0, 4):
                    lines.GetPointIds().SetId(i, i)

                if (last):
                    lines.GetPointIds().SetId(4, 0)

                cells.InsertNextCell(lines)

                # now make tge polydata and display it
                poly = vtk.vtkPolyData()
                poly.Initialize()
                poly.SetPoints(points)
                poly.SetLines(cells)

                # use normalized viewport coordinates since
                # they are independent of window size
                coordinate = vtk.vtkCoordinate()
                coordinate.SetCoordinateSystemToNormalizedViewport()

                mapper = vtk.vtkPolyDataMapper2D()
                mapper.SetInputData(poly)
                mapper.SetTransformCoordinate(coordinate)

                actor = vtk.vtkActor2D()
                actor.SetMapper(mapper)
                actor.GetProperty().SetColor(color)
                actor.GetProperty().SetLineWidth(2.0)

                renderer.AddViewProp(actor)
Exemple #23
0
    def _createTubePolyData(self, tube):
        '''Generates polydata from an itk.VesselTubeSpatialObject.'''
        points = GetTubePoints(tube)

        # Convert points to world space.
        tube.ComputeObjectToWorldTransform()
        transform = tube.GetIndexToWorldTransform()
        # Get scaling vector from transform matrix diagonal.
        scaling = [transform.GetMatrix()(i, i) for i in range(3)]
        # Use average of scaling vector for scale since TubeFilter
        # doesn't seem to support ellipsoid.
        scale = sum(scaling) / len(scaling)

        for i in range(len(points)):
            pt, radius = points[i]
            pt = transform.TransformPoint(pt)
            points[i] = (pt, radius * scale)

        vpoints = vtk.vtkPoints()
        vpoints.SetNumberOfPoints(len(points))
        scalars = vtk.vtkFloatArray()
        scalars.SetNumberOfValues(len(points))
        scalars.SetName('Radii')

        minRadius = float('inf')
        maxRadius = float('-inf')
        for i, (pt, r) in enumerate(points):
            vpoints.SetPoint(i, pt)
            scalars.SetValue(i, r)
            minRadius = min(r, minRadius)
            maxRadius = max(r, maxRadius)

        pl = vtk.vtkPolyLine()
        pl.Initialize(len(points), range(len(points)), vpoints)

        ca = vtk.vtkCellArray()
        ca.InsertNextCell(pl)

        pd = vtk.vtkPolyData()
        pd.SetLines(ca)
        pd.SetPoints(vpoints)
        pd.GetPointData().SetScalars(scalars)
        pd.GetPointData().SetActiveScalars('Radii')

        tf = vtk.vtkTubeFilter()
        tf.SetInputData(pd)
        tf.SetVaryRadiusToVaryRadiusByAbsoluteScalar()
        tf.SetRadius(minRadius)
        tf.SetRadiusFactor(maxRadius / minRadius)
        tf.SetNumberOfSides(20)
        tf.Update()

        return tf.GetOutput()
    def write_vtk(self, data_dir='./data', file_name='spines.vtk', binary=False):
        """
        Write the spines into a vtk file.

        call signature:

            write_vtk(data_dir='./data', file_name='spines.vtk', binary=False)

        Arguments:

        *data_dir*:
            Target data directory.

        *file_name*:
            Target file name.

        *binary*:
            Write file in binary or ASCII format.
        """

        writer = vtk.vtkPolyDataWriter()
        if binary:
            writer.SetFileTypeToBinary()
        else:
            writer.SetFileTypeToASCII()
        writer.SetFileName(os.path.join(data_dir, file_name))
        poly_data = vtk.vtkPolyData()
        points = vtk.vtkPoints()
        # Create the cell to store the lines in.
        cells = vtk.vtkCellArray()
        poly_lines = []
        offset = 0
        for line_idx in range(len(self.spines)):
            n_points = self.spines[line_idx].shape[0]
            poly_lines.append(vtk.vtkPolyLine())
            poly_lines[-1].GetPointIds().SetNumberOfIds(n_points)
            for point_idx in range(n_points):
                points.InsertNextPoint(self.spines[line_idx][point_idx])
                poly_lines[-1].GetPointIds().SetId(point_idx,
                                                   point_idx + offset)
            cells.InsertNextCell(poly_lines[-1])
            offset += n_points

        poly_data.SetPoints(points)
        poly_data.SetLines(cells)

        # Insure compatability between vtk 5 and 6.
        try:
            writer.SetInputData(poly_data)
        except:
            writer.SetInput(poly_data)
        writer.Write()
def makeVTKWells(fname_base, welltracks_df, xml=False):
    """Creates a vtk Unstructured Grid file (*.vtk, *.vtu) from a welltracks DataFrame 
    
    Parameters:
        fname_base -- the output filename will be [fname_base].vtk or [fname_base].vtu for xml format
        welltracks_df -- DataFrame contaning 'X', 'Y', and 'Elev_mASL' columns.
                         This is created using the transformCoords function.
        xml -- set to True if xml format is preferred
    """ 
    numpoints = welltracks_df.shape[0]
    wells = welltracks_df['Well'].unique().tolist()
    numwells = len(wells)

    grid = vtkUnstructuredGrid()
    points = vtkPoints()  
    
    for i in range(numpoints):
        points.InsertNextPoint(welltracks_df.loc[i,'X'], welltracks_df.loc[i,'Y'], welltracks_df.loc[i,'Z'])
    
    cells = vtkCellArray()
    wellname = vtkStringArray()
    wellname.SetName('Well')
    
    for well in wells:
        print well
        polyline = vtkPolyLine()
        indices = welltracks_df[welltracks_df['Well']==well].index.tolist()
        for i, j in enumerate(indices):
            polyline.GetPointIds().SetNumberOfIds(len(indices))
            polyline.GetPointIds().SetId(i,j)
            
        cells.InsertNextCell(polyline)
        wellname.InsertNextValue(well)
        
    grid.SetPoints(points)
    grid.SetCells(VTK_POLY_LINE, cells)
    grid.GetCellData().AddArray(wellname)
    
    if xml:
        writer = vtkXMLUnstructuredGridWriter()
        writer.SetFileName('{}.vtu'.format(fname_base))
        writer.SetDataModeToAscii()
        writer.SetInputData(grid)
        writer.Write()
        
    else:
        writer = vtkUnstructuredGridWriter()
        writer.SetFileName('{}.vtk'.format(fname_base))
        writer.SetInputData(grid)
        writer.Write()
Exemple #26
0
def create_actor_mesh(pts, lines, color, **kwargs):
    """ Creates a VTK actor for rendering quadrilateral plots.

    :param pts: points
    :type pts: vtkFloatArray
    :param lines: point connectivity information
    :type lines: vtkIntArray
    :param color: actor color
    :type color: list
    :return: a VTK actor
    :rtype: vtkActor
    """
    # Keyword arguments
    array_name = kwargs.get('name', "")
    array_index = kwargs.get('index', 0)
    line_width = kwargs.get('size', 0.5)

    # Create points
    points = vtk.vtkPoints()
    points.SetData(pts)

    # Create lines
    cells = vtk.vtkCellArray()
    for line in lines:
        pline = vtk.vtkPolyLine()
        pline.GetPointIds().SetNumberOfIds(5)
        for i in range(len(line)):
            pline.GetPointIds().SetId(i, line[i])
        pline.GetPointIds().SetId(4, line[0])
        cells.InsertNextCell(pline)

    # Create a PolyData object and add points & lines
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)
    polydata.SetLines(cells)

    # Map poly data to the graphics primitives
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputDataObject(polydata)
    mapper.SetArrayName(array_name)
    mapper.SetArrayId(array_index)

    # Create an actor and set its properties
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(*color)
    actor.GetProperty().SetLineWidth(line_width)

    # Return the actor
    return actor
Exemple #27
0
def create_actor_mesh(pts, lines, color, **kwargs):
    """ Creates a VTK actor for rendering quadrilateral plots.

    :param pts: points
    :type pts: vtkFloatArray
    :param lines: point connectivity information
    :type lines: vtkIntArray
    :param color: actor color
    :type color: list
    :return: a VTK actor
    :rtype: vtkActor
    """
    # Keyword arguments
    array_name = kwargs.get('name', "")
    array_index = kwargs.get('index', 0)
    line_width = kwargs.get('size', 0.5)

    # Create points
    points = vtk.vtkPoints()
    points.SetData(pts)

    # Create lines
    cells = vtk.vtkCellArray()
    for line in lines:
        pline = vtk.vtkPolyLine()
        pline.GetPointIds().SetNumberOfIds(5)
        for i in range(len(line)):
            pline.GetPointIds().SetId(i, line[i])
        pline.GetPointIds().SetId(4, line[0])
        cells.InsertNextCell(pline)

    # Create a PolyData object and add points & lines
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)
    polydata.SetLines(cells)

    # Map poly data to the graphics primitives
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputDataObject(polydata)
    mapper.SetArrayName(array_name)
    mapper.SetArrayId(array_index)

    # Create an actor and set its properties
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(*color)
    actor.GetProperty().SetLineWidth(line_width)

    # Return the actor
    return actor
Exemple #28
0
def prepContinents(fnm):
  """ This converts vcs continents files to vtkpolydata
  Author: Charles Doutriaux
  Input: vcs continent file name
  """
  if vcsContinents.has_key(fnm):
    return vcsContinents[fnm]
  poly =vtk.vtkPolyData()
  cells = vtk.vtkCellArray()
  pts = vtk.vtkPoints()
  f=open(fnm)
  ln=f.readline()
  while ln.strip().split()!=["-99","-99"]:
    # Many lines, need to know number of points
    N = int(ln.split()[0])
    # Now create and store these points
    n=0
    npts = pts.GetNumberOfPoints()
    while n<N:
        ln=f.readline()
        sp=ln.split()
        sn = len(sp)
        didIt = False
        if sn%2 == 0:
          try:
            spts = []
            for i in range(sn/2):
              l,L = float(sp[i*2]),float(sp[i*2+1])
              spts.append([l,L])
            for p in spts:
              pts.InsertNextPoint(p[1],p[0],0.)
            n+=sn
            didIt = True
          except:
            didIt = False
        if didIt is False:
          while len(ln)>2:
            l,L=float(ln[:8]),float(ln[8:16])
            pts.InsertNextPoint(L,l,0.)
            ln=ln[16:]
            n+=2
    ln = vtk.vtkPolyLine()
    ln.GetPointIds().SetNumberOfIds(N/2)
    for i in range(N/2): ln.GetPointIds().SetId(i,i+npts)
    cells.InsertNextCell(ln)
    ln=f.readline()
  poly.SetPoints(pts)
  poly.SetLines(cells)
  vcsContinents[fnm]=poly
  return poly
Exemple #29
0
def createPolyLine(points):
    pd = createPolyData(points)

    # Create cells
    cell = vtk.vtkPolyLine()
    cell.GetPointIds().SetNumberOfIds(pd.GetNumberOfPoints())

    for i in range(pd.GetNumberOfPoints()):
        cell.GetPointIds().SetId(i, i)

    cells = vtk.vtkCellArray()
    cells.InsertNextCell(cell)
    pd.SetLines(cells)

    return pd
Exemple #30
0
def prepContinents(fnm):
    """ This converts vcs continents files to vtkpolydata
  Author: Charles Doutriaux
  Input: vcs continent file name
  """
    poly = vtk.vtkPolyData()
    cells = vtk.vtkCellArray()
    pts = vtk.vtkPoints()
    f = open(fnm)
    ln = f.readline()
    while ln.strip().split() != ["-99", "-99"]:
        # Many lines, need to know number of points
        N = int(ln.split()[0])
        # Now create and store these points
        n = 0
        npts = pts.GetNumberOfPoints()
        while n < N:
            ln = f.readline()
            sp = ln.split()
            sn = len(sp)
            didIt = False
            if sn % 2 == 0:
                try:
                    spts = []
                    for i in range(sn / 2):
                        l, L = float(sp[i * 2]), float(sp[i * 2 + 1])
                        spts.append([l, L])
                    for p in spts:
                        pts.InsertNextPoint(p[1], p[0], 0.0001)
                    n += sn
                    didIt = True
                except:
                    didIt = False
            if didIt is False:
                while len(ln) > 2:
                    l, L = float(ln[:8]), float(ln[8:16])
                    pts.InsertNextPoint(L, l, 0.0001)
                    ln = ln[16:]
                    n += 2
        ln = vtk.vtkPolyLine()
        ln.GetPointIds().SetNumberOfIds(N / 2)
        for i in range(N / 2):
            ln.GetPointIds().SetId(i, i + npts)
        cells.InsertNextCell(ln)
        ln = f.readline()
    poly.SetPoints(pts)
    poly.SetLines(cells)
    return poly
Exemple #31
0
    def UpdateTimeIndex( self, time_index ):
        (edgelist, verts, fibers) = read_fibers( time_index );

        self.polylinePoints.SetNumberOfPoints( verts.size )
        for i,X in enumerate(verts):
            self.polylinePoints.InsertPoint(i, X[0], X[1], X[2] )

        self.cells.Reset()
        for f in fibers:
            self.polyline = vtk.vtkPolyLine()
            self.polyline.GetPointIds().SetNumberOfIds( len(f) )
            for i,v in enumerate(f):
                self.polyline.GetPointIds().SetId( i, v )
            self.cells.InsertNextCell( self.polyline )

        self.polydata.Modified()
Exemple #32
0
def genPoly(coords, pts, filled=True):
    N = pts.GetNumberOfPoints()
    if filled:
        poly = vtk.vtkPolygon()
    else:
        poly = vtk.vtkPolyLine()
    pid = poly.GetPointIds()
    n = len(coords)
    pid.SetNumberOfIds(n)
    for j in range(n):
        c = list(coords[j])
        if len(c) == 2:
            c.append(0)
        pts.InsertNextPoint(*c)
        pid.SetId(j, j + N)
    return poly
Exemple #33
0
def addPolyLineToDataSet(polyData, points):
    origNumPts = polyData.GetNumberOfPoints()

    # Verify that the polyDataSet has a point array
    if origNumPts == 0:
        polyData.SetPoints(vtk.vtkPoints())
        polyData.SetLines(vtk.vtkCellArray())

    cell = vtk.vtkPolyLine()
    cell.GetPointIds().SetNumberOfIds(points.shape[0])
    for i, pt in enumerate(points):
        # Insert point
        polyData.GetPoints().InsertNextPoint(pt[0], pt[1], pt[2])
        # Associate point id to line
        cell.GetPointIds().SetId(i, origNumPts + i)
    lines = polyData.GetLines().InsertNextCell(cell)
Exemple #34
0
def genPoly(coords,pts,filled=True):
  N = pts.GetNumberOfPoints()
  if filled:
    poly = vtk.vtkPolygon()
  else:
    poly = vtk.vtkPolyLine()
  pid = poly.GetPointIds()
  n = len(coords)
  pid.SetNumberOfIds(n)
  for j in range(n):
    c = list(coords[j])
    if len(c)==2:
      c.append(0)
    pts.InsertNextPoint(*c)
    pid.SetId(j,j+N)
  return poly
    def _Execute(self, *args):
        """Do the work. Do not call this method in user code, it will be called
        by the VTK executive.
        """
        # Clear out any old centreline data
        self.Centerline.PrepareForNewData()

        nSegments = self._GetNz()
        h = self.GetHeight()
        dz = self._GetDz()
        c = self.GetCenter()
        n = self.GetDirection()
        
        # These points define the line
        points = vtk.vtkPoints()
        # nSeg + 1 fence posts for nSeg sections of fence
        points.SetNumberOfPoints(nSegments + 1)
        # This will hold the ids of points in 'points'
        line = vtk.vtkPolyLine()
        line.GetPointIds().SetNumberOfIds(nSegments + 1)

        # Set the coordinates along the line and the ids
        for i in range(nSegments + 1):
            # Points start at -h/2 along the axis and advance in steps of dz 
            # along the direction (n, a unit vector)
            x = c + (i*dz - 0.5*h) * n
            points.SetPoint(i, x[0], x[1], x[2])
            line.GetPointIds().SetId(i, i)
            continue

        # Create the vtkPolyData
        self.Centerline.Allocate(1,1)
        self.Centerline.SetPoints(points)
        self.Centerline.InsertNextCell(line.GetCellType(),
                                       line.GetPointIds())
        
        # Pass it into the vtkTubeFilter
        self.Tuber.SetInputData(self.Centerline)
        # Get the output
        self.Triangulator.Update()

        # Copy to our output
        out = self.GetPolyDataOutput()
        out.ShallowCopy(self.Triangulator.GetOutput())
        return
    def __init__(self, lambdaFunction, thetaFunction, nt=11, radius=1.0):
        """
        Create a polyline 
        @param lambdaFunction lambda (longitude) function of t (0 <= t <= 1)
        @param thetaFunction theta (latitude) functuon of t (0 <= t <= 1)
        """
        self.ptData = vtk.vtkDoubleArray()
        self.pts = vtk.vtkPoints()
        self.line = vtk.vtkPolyLine()
        self.grid = vtk.vtkUnstructuredGrid()
        self.poly = vtk.vtkPolyData()
        self.cells = vtk.vtkCellArray()

        ts = numpy.linspace(0., 1., nt)
        lams = lambdaFunction(ts)
        thes = thetaFunction(ts)
        xs = radius * numpy.cos(thes) * numpy.cos(lams)
        ys = radius * numpy.cos(thes) * numpy.sin(lams)
        zs = radius * numpy.sin(thes)
        self.xyz = numpy.zeros((nt, 3), numpy.float64)
        self.xyz[:, 0] = xs
        self.xyz[:, 1] = ys
        self.xyz[:, 2] = zs

        self.ptData.SetNumberOfComponents(3)
        self.ptData.SetNumberOfTuples(nt)
        self.ptData.SetVoidArray(self.xyz, nt * 3, 1)

        self.pts.SetNumberOfPoints(nt)
        self.pts.SetData(self.ptData)

        ptIds = self.line.GetPointIds()
        ptIds.SetNumberOfIds(nt)
        for i in range(ptIds.GetNumberOfIds()):
            ptIds.SetId(i, i)

        self.grid.SetPoints(self.pts)
        self.grid.Allocate(1, 1)
        # one cell
        self.grid.InsertNextCell(self.line.GetCellType(), ptIds)

        self.cells.InsertNextCell(self.line)

        self.poly.SetPoints(self.pts)
        self.poly.SetLines(self.cells)
Exemple #37
0
def generate_plane_path():
    """
    Generate the plane path
    :return: the actor of the plane path
    """
    size, coordinates = read_txt(VTK_PLANE_GPS)

    plane_points = vtk.vtkPoints()
    plane_lines = vtk.vtkPolyLine()
    plane_lines.GetPointIds().SetNumberOfIds(int(size))
    scalar = vtk.vtkFloatArray()

    previous_alt = coordinates[0][2]

    for i, (x, y, alt) in enumerate(coordinates):
        lat, long = convert_rt90_to_gps_coordinate(x, y)
        plane_points.InsertNextPoint(coordinate_earth(lat, long, alt))
        plane_lines.GetPointIds().SetId(i, i)

        delta_alt = previous_alt - alt
        scalar.InsertNextValue(delta_alt)
        previous_alt = alt

    min_scalar, max_scalar = scalar.GetValueRange()

    plane_cells = vtk.vtkCellArray()
    plane_cells.InsertNextCell(plane_lines)

    plane_data = vtk.vtkPolyData()
    plane_data.SetPoints(plane_points)
    plane_data.SetLines(plane_cells)
    plane_data.GetPointData().SetScalars(scalar)

    plane_tube = vtk.vtkTubeFilter()
    plane_tube.SetRadius(35)
    plane_tube.SetInputData(plane_data)

    plane_mapper = vtk.vtkPolyDataMapper()
    plane_mapper.SetInputConnection(plane_tube.GetOutputPort())
    plane_mapper.SetScalarRange(min_scalar, max_scalar)

    plane_actor = vtk.vtkActor()
    plane_actor.SetMapper(plane_mapper)

    return plane_actor
Exemple #38
0
    def create_line(self, pos, color):
        _points = pos
        _color = color
        _line = vtk.vtkPolyLine()

        # we have _points
        _total_points_in_track = len(_points)
        _line.GetPointIds().SetNumberOfIds(_total_points_in_track)
        # set color to line

        self.colors.SetNumberOfComponents(4)

        for index, p in enumerate(_points):
            self.points.InsertNextPoint(p)
            _line.GetPointIds().SetId(index, self.points.GetNumberOfPoints() - 1)
            self.colors.InsertNextTuple(_color)

        self.lines_cells.InsertNextCell(_line)
Exemple #39
0
def as_polyline(points, level):
    """
    Koch Snowflake as a vtkPolyLine
    """
    # Use the points from the previous iteration to create the points of the next
    # level. There is an assumption on my part that the curve is traversed in a
    # counterclockwise fashion. If the initial triangle above is written to
    # describe clockwise motion, the points will face inward instead of outward.
    for i in range(level):
        temp = vtk.vtkPoints()
        # The first point of the previous vtkPoints is the first point of the next vtkPoints.
        temp.InsertNextPoint(*points.GetPoint(0))

        # Iterate over "edges" in the vtkPoints
        for i in range(1, points.GetNumberOfPoints()):
            x0, y0, z0 = points.GetPoint(i - 1)
            x1, y1, z1 = points.GetPoint(i)
            t = sqrt((x1 - x0)**2 + (y1 - y0)**2)
            nx = (x1 - x0) / t  # x-component of edge unit tangent
            ny = (y1 - y0) / t  # y-component of edge unit tangent

            # the points describing the Koch snowflake edge
            temp.InsertNextPoint(x0 + nx * t / 3, y0 + ny * t / 3, 0.)
            temp.InsertNextPoint(x0 + nx * t / 2 + ny * t * sqrt(3) / 6,
                                 y0 + ny * t / 2 - nx * t * sqrt(3) / 6, 0.)
            temp.InsertNextPoint(x0 + nx * 2 * t / 3, y0 + ny * 2 * t / 3, 0.)
            temp.InsertNextPoint(x0 + nx * t, y0 + ny * t, 0.)

        points = temp

    # draw the outline
    lines = vtk.vtkCellArray()
    pl = vtk.vtkPolyLine()
    pl.GetPointIds().SetNumberOfIds(points.GetNumberOfPoints())
    for i in range(points.GetNumberOfPoints()):
        pl.GetPointIds().SetId(i, i)
    lines.InsertNextCell(pl)

    # complete the polydata
    polydata = vtk.vtkPolyData()
    polydata.SetLines(lines)
    polydata.SetPoints(points)

    return polydata
Exemple #40
0
    def _Execute(self, *args):
        """Do the work. Do not call this method in user code, it will be called
        by the VTK executive.
        """
        # Clear out any old centreline data
        self.Centerline.PrepareForNewData()

        nSegments = self._GetNz()
        h = self.GetHeight()
        dz = self._GetDz()
        c = self.GetCenter()
        n = self.GetDirection()

        # These points define the line
        points = vtk.vtkPoints()
        # nSeg + 1 fence posts for nSeg sections of fence
        points.SetNumberOfPoints(nSegments + 1)
        # This will hold the ids of points in 'points'
        line = vtk.vtkPolyLine()
        line.GetPointIds().SetNumberOfIds(nSegments + 1)

        # Set the coordinates along the line and the ids
        for i in range(nSegments + 1):
            # Points start at -h/2 along the axis and advance in steps of dz
            # along the direction (n, a unit vector)
            x = c + (i * dz - 0.5 * h) * n
            points.SetPoint(i, x[0], x[1], x[2])
            line.GetPointIds().SetId(i, i)
            continue

        # Create the vtkPolyData
        self.Centerline.Allocate(1, 1)
        self.Centerline.SetPoints(points)
        self.Centerline.InsertNextCell(line.GetCellType(), line.GetPointIds())

        # Pass it into the vtkTubeFilter
        self.Tuber.SetInputData(self.Centerline)
        # Get the output
        self.Triangulator.Update()

        # Copy to our output
        out = self.GetPolyDataOutput()
        out.ShallowCopy(self.Triangulator.GetOutput())
        return
Exemple #41
0
def makeVTKWellsUsingModule(fname_base, welltracks_df, xml=False):
    
    numpoints = welltracks_df.shape[0]
    wells = welltracks_df['Well'].unique().tolist()
    numwells = len(wells)

    grid = vtkUnstructuredGrid()
    points = vtkPoints()  
    
    for i in range(numpoints):
        points.InsertNextPoint(welltracks_df.loc[i,'X'], welltracks_df.loc[i,'Y'], welltracks_df.loc[i,'Elev_mASL'])
    
    cells = vtkCellArray()
    wellname = vtkStringArray()
    wellname.SetName('Well')
    
    for well in wells:
        print well
        polyline = vtkPolyLine()
        indices = welltracks_df[welltracks_df['Well']==well].index.tolist()
        for i, j in enumerate(indices):
            polyline.GetPointIds().SetNumberOfIds(len(indices))
            polyline.GetPointIds().SetId(i,j)
            
        cells.InsertNextCell(polyline)
        wellname.InsertNextValue(well)
        
    grid.SetPoints(points)
    grid.SetCells(VTK_POLY_LINE, cells)
    grid.GetCellData().AddArray(wellname)
    
    if xml:
        writer = vtkXMLUnstructuredGridWriter()
        writer.SetFileName('{}.vtu'.format(fname_base))
        writer.SetDataModeToAscii()
        writer.SetInputData(grid)
        writer.Write()
        
    else:
        writer = vtkUnstructuredGridWriter()
        writer.SetFileName('{}.vtk'.format(fname_base))
        writer.SetInputData(grid)
        writer.Write()
Exemple #42
0
def createLineVTKData(pts, col):
    points = vtk.vtkPoints()
    for p in pts:
        points.InsertNextPoint(p)
    lines = vtk.vtkCellArray()
    pl = vtk.vtkPolyLine()
    pl.GetPointIds().SetNumberOfIds(points.GetNumberOfPoints())
    for i in range(points.GetNumberOfPoints()):
        pl.GetPointIds().SetId(i, i)
    lines.InsertNextCell(pl)
    polydata = vtk.vtkPolyData()
    polydata.SetLines(lines)
    polydata.SetPoints(points)
    colors = vtk.vtkUnsignedCharArray()
    colors.SetNumberOfComponents(3)
    colors.SetName("Colors")
    colors.InsertNextTupleValue(col)
    polydata.GetCellData().SetScalars(colors)
    return polydata
Exemple #43
0
def UpdateData( time_index ):
    print time_index

    textActor.SetInput( "Dynamics Test:" + str(time_index) )
    
    (edgelist, verts, fibers) = read_fibers( time_index );

    polylinePoints.SetNumberOfPoints( verts.size )
    for i,X in enumerate(verts):
        polylinePoints.InsertPoint(i, X[0], X[1], X[2] )

    cells.SetNumberOfCells(0)
    for f in fibers:
        polyline = vtk.vtkPolyLine()
        polyline.GetPointIds().SetNumberOfIds( len(f) )
        for i,v in enumerate(f):
            polyline.GetPointIds().SetId( i, v )
        cells.InsertNextCell( polyline )

    polydata.Modified()
def as_polyline(points, level):
  # Use the points from the previous iteration to create the points of the next
  # level. There is an assumption on my part that the curve is traversed in a
  # counterclockwise fashion. If the initial triangle above is written to
  # describe clockwise motion, the points will face inward instead of outward.
  for i in range(level):
    temp = vtk.vtkPoints()
    # The first point of the previous vtkPoints is the first point of the next vtkPoints.
    temp.InsertNextPoint(*points.GetPoint(0))

    # Iterate over "edges" in the vtkPoints
    for i in range(1, points.GetNumberOfPoints()):
      x0, y0, z0 = points.GetPoint(i - 1)
      x1, y1, z1 = points.GetPoint(i)
      t = sqrt((x1 - x0)**2 + (y1 - y0)**2)
      nx = (x1 - x0)/t # x-component of edge unit tangent
      ny = (y1 - y0)/t # y-component of edge unit tangent

      # the points describing the Koch snowflake edge
      temp.InsertNextPoint(x0 + nx*t/3, y0 + ny*t/3, 0.)
      temp.InsertNextPoint(x0 + nx*t/2 + ny*t*sqrt(3)/6, y0 + ny*t/2 - nx*t*sqrt(3)/6, 0.)
      temp.InsertNextPoint(x0 + nx*2*t/3, y0 + ny*2*t/3, 0.)
      temp.InsertNextPoint(x0 + nx*t, y0 + ny*t, 0.)

    points = temp

  # draw the outline
  lines = vtk.vtkCellArray()
  pl = vtk.vtkPolyLine()
  pl.GetPointIds().SetNumberOfIds(points.GetNumberOfPoints())
  for i in range(points.GetNumberOfPoints()):
    pl.GetPointIds().SetId(i, i)
  lines.InsertNextCell(pl)

  # complete the polydata
  polydata = vtk.vtkPolyData()
  polydata.SetLines(lines)
  polydata.SetPoints(points)

  return polydata
Exemple #45
0
def CreateVersor(o, r, color=[0, 0, 0]):
    """ Ritorna una lista di attori contenetni un versore
   o = origine
  r= versore """
    points = []
    Lines=[]
    Polygon = vtk.vtkPolyData()
    ac=[]
    
    points = vtk.vtkPoints()
            
    points.SetNumberOfPoints(2)
    
    r = normalize(r)
         
    points.SetPoint(0, o)
    points.SetPoint(1, [o[0]+r[0], o[1]+r[1], o[2]+r[2]])
    
    polyLine0 = vtk.vtkPolyLine()
    polyLine0.GetPointIds().SetNumberOfIds(2)
    polyLine0.GetPointIds().SetId(0,0)
    polyLine0.GetPointIds().SetId(1,1)
    
    cells0 = vtk.vtkCellArray()
    cells0.InsertNextCell(polyLine0)
    
    polyData = vtk.vtkPolyData()
    polyData.SetPoints(points)
    polyData.SetLines(cells0)
    
    ac=[]
        
    
    ac.append(CreateSphere(points.GetPoint(0), 0.05, [1, 1, 1]))
    ac.append(CreateSphere(points.GetPoint(1), 0.1, color))
    
    ac.append(CreateActor(polyData))
    return ac
Exemple #46
0
def make_polyline(def_tup):
    global sorted_residues
    (start_res, end_res) = def_tup
#    print "start res", start_res, "end res", end_res
#    print "Looking for helix, from >%s< -> >%s<" % (start_res, end_res)
#    print "\n".join(map(lambda r: ">"+r[0]+"<", sorted_residues))
    #"len sorted reses: ", len(sorted_residues)
    (start_idx, end_idx) = residue_index(start_res, end_res)
    assert -1 < start_idx and -1 < end_idx, "strt: %s, end %s" % (start_res, end_res)
    # +1 as we want /inclusive/
#    print "start idx", start_idx, "end", end_idx
    residues = sorted_residues[start_idx : end_idx + 1]

    polyLinePoints = vtk.vtkPoints()
    polyLinePoints.SetNumberOfPoints(len(residues))
    aPolyLine = vtk.vtkPolyLine()
    aPolyLine.GetPointIds().SetNumberOfIds(len(residues))
    for i,r in enumerate(residues):
        (x, y, z) = r[1]
#        print "pt: ", x, y, z
        polyLinePoints.InsertPoint(i, x, y, z)
        aPolyLine.GetPointIds().SetId(i, i)
    return (polyLinePoints, aPolyLine)
Exemple #47
0
	def load(self, srcfn):
		sfh = file(srcfn, 'r')
		if None == sfh:
			raise Exception, "Failed to open file - %s." % (srcfn)

		try:
			curline = "#"
			LNo = 0
			while curline:
				curline = sfh.readline()
				LNo += 1
				curline = curline.lstrip().rstrip('\r\n')
				if len(split(curline)) == 1 and curline not in ["#","//","/*","%"]:
					break

			lnTotal = int(curline)
			lnCnt = 0
			ptCnt = 0

			while curline and lnCnt < lnTotal:
				# read line by line, in order to avoid the memory swelling by otherwise loading all lines once
				curline = sfh.readline()
				LNo += 1
				curline = curline.lstrip().rstrip('\r\n')
				if len(curline) < 1 or curline in ["#","//","/*","%"]:
					continue

				vtTotal = int(curline)
				vtCnt = 0
				startPtId = ptCnt

				while curline and vtCnt < vtTotal:
					curline = sfh.readline()
					LNo += 1
					curline = curline.lstrip().rstrip('\r\n')
					if len(curline) < 1 or curline in ["#","//","/*","%"]:
						continue

					# alway splitting a line with whitespace as the delimiter
					words = split(curline)
					if len(words) < 6: # not a vertex line
						continue

					self.allPoints.InsertNextPoint( float(words[0]), float(words[1]), float(words[2]) )
					ptCnt += 1

					vtCnt += 1

				if vtCnt < vtTotal :
					raise IOError, "Insufficient points on line No.%d, at file Line %d, aborted.\n" % (lnCnt, LNo)

				vtkln = vtk.vtkPolyLine()
				vtkln.GetPointIds().SetNumberOfIds(vtTotal)
				for id in range(0, vtTotal):
					vtkln.GetPointIds().SetId( id, id + startPtId )

				self.allLines.InsertNextCell( vtkln )
				lnCnt += 1

			if lnCnt < lnTotal:
				raise IOError, "Error encountered at file Line %d - Insufficient lines.\n" % (LNo)

			self.SetPoints( self.allPoints )
			self.SetLines ( self.allLines )

			self.fndata = srcfn 

		finally:
			sfh.close()
Exemple #48
0
aLineGrid.Allocate(1,1)
aLineGrid.InsertNextCell(aLine.GetCellType(),aLine.GetPointIds())
aLineGrid.SetPoints(linePoints)
aLineMapper = vtk.vtkDataSetMapper()
aLineMapper.SetInputData(aLineGrid)
aLineActor = vtk.vtkActor()
aLineActor.SetMapper(aLineMapper)
aLineActor.AddPosition(0,0,4)
aLineActor.GetProperty().BackfaceCullingOn()
# Polyline
polyLinePoints = vtk.vtkPoints()
polyLinePoints.SetNumberOfPoints(3)
polyLinePoints.InsertPoint(0,0,0,0)
polyLinePoints.InsertPoint(1,1,1,0)
polyLinePoints.InsertPoint(2,1,0,0)
aPolyLine = vtk.vtkPolyLine()
aPolyLine.GetPointIds().SetNumberOfIds(3)
aPolyLine.GetPointIds().SetId(0,0)
aPolyLine.GetPointIds().SetId(1,1)
aPolyLine.GetPointIds().SetId(2,2)
aPolyLineGrid = vtk.vtkUnstructuredGrid()
aPolyLineGrid.Allocate(1,1)
aPolyLineGrid.InsertNextCell(aPolyLine.GetCellType(),aPolyLine.GetPointIds())
aPolyLineGrid.SetPoints(polyLinePoints)
aPolyLineMapper = vtk.vtkDataSetMapper()
aPolyLineMapper.SetInputData(aPolyLineGrid)
aPolyLineActor = vtk.vtkActor()
aPolyLineActor.SetMapper(aPolyLineMapper)
aPolyLineActor.AddPosition(2,0,4)
aPolyLineActor.GetProperty().BackfaceCullingOn()
# Vertex
Exemple #49
0
	def display_tube(self,gfx,caller):
		if gfx.ps != None:
			gfx.renderer.RemoveActor(gfx.ps.acteur)
		if self.c!='' and self.T!='' and self.U!='' and self.henttype=='cTU':#CTU CASE
			ptype='delta'
			self.enttype='cTU'
			deltaz = (self.c/self.U)
			deltaphi = (self.T * 360.0)/self.U
			self.dphi = deltaphi
			self.dz = deltaz
		elif self.dphi!='' and self.dz!='' and self.henttype=='Elm-Hel':#DELTA CASE
			ptype = 'delta'
			self.enttype='Elm-Hel'
			deltaphi = self.dphi
			deltaz =self.dz
		else :
			MB.showwarning('Info','Configure symmetry setting')
			return
		try:
			zmax = gfx.map[0].box.GetBounds()[5]
			zmin = gfx.map[0].box.GetBounds()[4]
			z = zmax - zmin
		except:
			z= 4*360*abs(self.dz/self.dphi)
		#ici exeption 'fit' calcule de dz avec ratio !!!
		if 'fit' in caller:
			self.c = self.c * gfx.map[0].ratio
			self.dz = self.dz * gfx.map[0].ratio
			deltaz =self.dz
		numPts = int(z/deltaz)
		self.numpts = numPts#definition du nombre de sm
		self.cptsymops_tube(ptype,numPts) #ptype est tjs = a delta on calcule toujours de la même maniere dans symmetry
		#parameter definition :
		shifta = radians(deltaphi)
		phizero = radians(self.phizero)
		###definition des boules selon les parametres
		pdo = vtk.vtkPolyData()
		newPts = vtk.vtkPoints() #This will store the points for the Helix
		vals = vtk.vtkDoubleArray()
		for i in range(0, numPts):
			try :
				x = self.radius * gfx.map[0].scale * cos(i*shifta + phizero)
				y = self.radius * gfx.map[0].scale * sin(i*shifta + phizero)
				z = zmin + i*deltaz
			except :
				x = self.radius *  cos(i*shifta + phizero)
				y = self.radius * sin(i*shifta + phizero)
				z =  i*deltaz
			newPts.InsertPoint(i, x,y,z)
			vals.InsertNextValue(i)
		pdo.SetPoints(newPts)
		pdo.GetPointData().SetScalars(vals)
		sphere = vtk.vtkSphereSource()
		sphere.SetCenter(0, 0, 0)
		try :
			sphere.SetRadius(self.radius*gfx.map[0].scale/5.0)
		except:
			sphere.SetRadius(self.radius*(1/5.))
		sphere.SetThetaResolution(8)
		sphere.SetStartTheta(0)
		sphere.SetEndTheta(360)
		sphere.SetPhiResolution(8)
		sphere.SetStartPhi(0)
		sphere.SetEndPhi(180)
		glyph = vtk.vtkGlyph3D()
		glyph.SetInput(pdo)
		glyph.SetColorMode(1)
		glyph.ScalingOn()
		glyph.SetScaleMode(2)
		glyph.SetScaleFactor(0.25)
		glyph.SetSource(sphere.GetOutput())
		self.spheremapper = vtk.vtkPolyDataMapper()
		self.spheremapper.SetInputConnection(glyph.GetOutputPort())
		self.spheremapper.UseLookupTableScalarRangeOff()
		self.spheremapper.SetScalarVisibility(0)
		self.sphact = vtk.vtkActor()
		self.sphact.PickableOff()
		self.sphact.DragableOff()
		self.sphact.SetMapper(self.spheremapper)
		self.sphact.GetProperty().SetRepresentationToSurface()
		self.sphact.GetProperty().SetInterpolationToGouraud()
		self.sphact.GetProperty().SetAmbient(0.15)
		self.sphact.GetProperty().SetDiffuse(0.85)
		self.sphact.GetProperty().SetSpecular(0.1)
		self.sphact.GetProperty().SetSpecularPower(100)
		self.sphact.GetProperty().SetSpecularColor(1, 1, 1)
		self.sphact.GetProperty().SetColor(1,1,1)
		###definition de l helice continue
		enhance=100
		hlxpdo = vtk.vtkPolyData()
		hlxnewPts = vtk.vtkPoints() #This will store the points for the Helix
		hlxvals = vtk.vtkDoubleArray()
		hlxnumPts = int(numPts*enhance)
		for i in range(0, hlxnumPts):
			try :
				x = self.radius * gfx.map[0].scale * cos(i*shifta/enhance + phizero)
				y = self.radius * gfx.map[0].scale * sin(i*shifta/enhance + phizero)
				z = zmin + i*deltaz/enhance
			except :
				x = self.radius  * cos(i*shifta/enhance + phizero)
				y = self.radius  * sin(i*shifta/enhance + phizero)
				z = i*deltaz/enhance
			hlxnewPts.InsertPoint(i, x,y,z)
			hlxvals.InsertNextValue(i)
		hlxpdo.SetPoints(hlxnewPts)
		hlxpdo.GetPointData().SetScalars(hlxvals)
		aPolyLine = vtk.vtkPolyLine()
		aPolyLine.GetPointIds().SetNumberOfIds(hlxnumPts)
		for i in range(0,hlxnumPts):
			aPolyLine.GetPointIds().SetId(i, i)
		hlxpdo.Allocate(1, 1)
		hlxpdo.InsertNextCell(aPolyLine.GetCellType(), aPolyLine.GetPointIds())
		self.mapper = vtk.vtkPolyDataMapper()
		self.mapper.SetScalarVisibility(0)
		self.mapper.SetInput(hlxpdo)
		self.helact = vtk.vtkActor()
		self.helact.PickableOff()
		self.helact.DragableOff()
		self.helact.GetProperty().SetColor(1,1,1)
		self.helact.GetProperty().SetRepresentationToWireframe()
		self.helact.GetProperty().SetLineWidth(5)
		self.helact.GetProperty().SetLineWidth(1)
		self.helact.GetProperty().SetSpecular(.4)
		self.helact.GetProperty().SetSpecularPower(10)
		self.helact.SetMapper(self.mapper)
		assembly = vtk.vtkAssembly()
		assembly.AddPart(self.sphact)
		assembly.AddPart(self.helact)
		helcol = [(1,1,1),(1,0,0.3),(0.3,0,1),(0,1,0.3)]
		for i in range(1,self.s+1):
			if i == 1:
				continue
			else :
				tmp_sphact= vtk.vtkActor()
				tmp_helact= vtk.vtkActor()
				tmp_sphact.ShallowCopy(self.sphact)
				tmp_helact.ShallowCopy(self.helact)
				ps=vtk.vtkProperty()
				ph=vtk.vtkProperty()
				ps.SetColor(helcol[(i-1)%4])
				ph.SetColor(helcol[(i-1)%4])
				tmp_sphact.SetProperty(ps)
				tmp_helact.SetProperty(ph)
				tmp_sphact.RotateWXYZ((360/self.s)*(i-1),0,0,1)
				tmp_helact.RotateWXYZ((360/self.s)*(i-1),0,0,1)
				assembly.AddPart(tmp_sphact)
				assembly.AddPart(tmp_helact)
		self.acteur=assembly
		gfx.renderer.AddActor(self.acteur)
		gfx.renwin.Render()
		gfx.ps = self
		return ptype
Exemple #50
0
	def display_Xn(self,gfx):
		if gfx.ps != None:
			gfx.renderer.RemoveActor(gfx.ps.acteur)
		try:
			zmax = gfx.map[0].box.GetBounds()[5]
			zmin = gfx.map[0].box.GetBounds()[4]
			ymax = gfx.map[0].box.GetBounds()[3]
			ymin = gfx.map[0].box.GetBounds()[2]
			c = (zmax - zmin)/2.
			b = (ymax - ymin)/2.
		except:
				b = c = self.radius
		dist = self.radius
		phizero = radians(self.phizero)
		if self.solidtype=='Cn':
			numPts = self.cnn
			shifta = radians(360./numPts)
			pdo = vtk.vtkPolyData()
			cirpdo = vtk.vtkPolyData()
			newPts = vtk.vtkPoints()
			vals = vtk.vtkDoubleArray()
			for i in range(0, numPts):
				try :
					if self.axe=='Z':
						x = dist * gfx.map[0].scale * cos(i*shifta + phizero)
						y = dist * gfx.map[0].scale * sin(i*shifta + phizero)
						z = 0
					elif self.axe == 'Y':
						x = dist * gfx.map[0].scale * cos(i*shifta + phizero)
						y = 0
						z = dist * gfx.map[0].scale * sin(i*shifta + phizero)
					elif self.axe == 'X':
						x = 0
						y = dist * gfx.map[0].scale * cos(i*shifta + phizero)
						z = dist * gfx.map[0].scale * sin(i*shifta + phizero)
				except :
					if self.axe=='Z':
						x = dist  * cos(i*shifta + phizero)
						y = dist  * sin(i*shifta + phizero)
						z = 0
					elif self.axe == 'Y':
						x = dist  * cos(i*shifta + phizero)
						y = 0
						z = dist  * sin(i*shifta + phizero)
					elif self.axe == 'X':
						x = 0
						y = dist * cos(i*shifta + phizero)
						z = dist * sin(i*shifta + phizero)
				newPts.InsertPoint(i, x,y,z)
				vals.InsertNextValue(i)
			pdo.SetPoints(newPts)
			pdo.GetPointData().SetScalars(vals)
			cirpdo.SetPoints(newPts)
			cirpdo.GetPointData().SetScalars(vals)
			aPolyLine = vtk.vtkPolyLine()
			aPolyLine.GetPointIds().SetNumberOfIds(numPts+1)
			for i in range(0,numPts):
				aPolyLine.GetPointIds().SetId(i, i)
			aPolyLine.GetPointIds().SetId(numPts, 0)
			cirpdo.Allocate(1, 1)
			cirpdo.InsertNextCell(aPolyLine.GetCellType(), aPolyLine.GetPointIds())
			sphere = vtk.vtkSphereSource()
			sphere.SetCenter(0, 0, 0)
			try :
				sphere.SetRadius(self.radius*gfx.map[0].scale/5.0)
			except:
				sphere.SetRadius(self.radius/5.0)
			sphere.SetThetaResolution(8)
			sphere.SetStartTheta(0)
			sphere.SetEndTheta(360)
			sphere.SetPhiResolution(8)
			sphere.SetStartPhi(0)
			sphere.SetEndPhi(180)
			glyph = vtk.vtkGlyph3D()
			glyph.SetInput(pdo)
			glyph.SetColorMode(1)
			glyph.ScalingOn()
			glyph.SetScaleMode(2)
			glyph.SetScaleFactor(0.25)
			glyph.SetSource(sphere.GetOutput())
			self.spheremapper = vtk.vtkPolyDataMapper()
			self.spheremapper.SetInputConnection(glyph.GetOutputPort())
			self.spheremapper.UseLookupTableScalarRangeOff()
			self.spheremapper.SetScalarVisibility(0)
			self.sphact = vtk.vtkActor()
			self.sphact.PickableOff()
			self.sphact.DragableOff()
			self.sphact.SetMapper(self.spheremapper)
			self.sphact.GetProperty().SetRepresentationToSurface()
			self.sphact.GetProperty().SetInterpolationToGouraud()
			self.sphact.GetProperty().SetAmbient(0.15)
			self.sphact.GetProperty().SetDiffuse(0.85)
			self.sphact.GetProperty().SetSpecular(0.1)
			self.sphact.GetProperty().SetSpecularPower(100)
			self.sphact.GetProperty().SetSpecularColor(1, 1, 1)
			self.sphact.GetProperty().SetColor(1,1,1)
			self.mapper = vtk.vtkPolyDataMapper()
			self.mapper.SetScalarVisibility(0)
			self.mapper.SetInput(cirpdo)
			self.helact = vtk.vtkActor()
			self.helact.PickableOff()
			self.helact.DragableOff()
			self.helact.GetProperty().SetColor(1,1,1)
			self.helact.GetProperty().SetRepresentationToWireframe()
			self.helact.GetProperty().SetLineWidth(5)
			self.helact.GetProperty().SetLineWidth(1)
			self.helact.GetProperty().SetSpecular(.4)
			self.helact.GetProperty().SetSpecularPower(10)
			self.helact.SetMapper(self.mapper)
			assembly = vtk.vtkAssembly()
			assembly.AddPart(self.sphact)
			assembly.AddPart(self.helact)
			self.acteur=assembly
			gfx.renderer.AddActor(self.acteur)
			gfx.renwin.Render()
			gfx.ps = self
		elif self.solidtype=='Dn':
			numPts = self.dnn
			shifta = radians(360./numPts)
			cirpdo = vtk.vtkPolyData()
			pdo = vtk.vtkPolyData()
			newPts = vtk.vtkPoints()
			vals = vtk.vtkDoubleArray()
			for i in range(0, numPts):
				try:
					x = dist * gfx.map[0].scale * cos(i*shifta)
					y = dist * gfx.map[0].scale * sin(i*shifta)
					z = 0
				except:
					x = dist * cos(i*shifta)
					y = dist * sin(i*shifta)
					z = 0
				newPts.InsertPoint(i, x,y,z)
				vals.InsertNextValue(i)
			pdo.SetPoints(newPts)
			pdo.GetPointData().SetScalars(vals)
			cirpdo.SetPoints(newPts)
			cirpdo.GetPointData().SetScalars(vals)
			aPolyLine = vtk.vtkPolyLine()
			aPolyLine.GetPointIds().SetNumberOfIds(numPts+1)
			for i in range(0,numPts):
				aPolyLine.GetPointIds().SetId(i, i)
			aPolyLine.GetPointIds().SetId(numPts, 0)
			cirpdo.Allocate(1, 1)
			cirpdo.InsertNextCell(aPolyLine.GetCellType(), aPolyLine.GetPointIds())
			sphere = vtk.vtkSphereSource()
			sphere.SetCenter(0, 0, 0)
			try:
				sphere.SetRadius(self.radius*gfx.map[0].scale/5.0)
			except:
				sphere.SetRadius(self.radius/5.0)
			sphere.SetThetaResolution(8)
			sphere.SetStartTheta(0)
			sphere.SetEndTheta(360)
			sphere.SetPhiResolution(8)
			sphere.SetStartPhi(0)
			sphere.SetEndPhi(180)
			glyph = vtk.vtkGlyph3D()
			glyph.SetInput(pdo)
			glyph.SetColorMode(1)
			glyph.ScalingOn()
			glyph.SetScaleMode(2)
			glyph.SetScaleFactor(0.25)
			glyph.SetSource(sphere.GetOutput())
			self.spheremapper = vtk.vtkPolyDataMapper()
			self.spheremapper.SetInputConnection(glyph.GetOutputPort())
			self.spheremapper.UseLookupTableScalarRangeOff()
			self.spheremapper.SetScalarVisibility(0)
			self.sphact = vtk.vtkActor()
			self.sphact.PickableOff()
			self.sphact.DragableOff()
			self.sphact.SetMapper(self.spheremapper)
			self.sphact.GetProperty().SetRepresentationToSurface()
			self.sphact.GetProperty().SetInterpolationToGouraud()
			self.sphact.GetProperty().SetAmbient(0.15)
			self.sphact.GetProperty().SetDiffuse(0.85)
			self.sphact.GetProperty().SetSpecular(0.1)
			self.sphact.GetProperty().SetSpecularPower(100)
			self.sphact.GetProperty().SetSpecularColor(1, 1, 1)
			self.sphact.GetProperty().SetColor(1,1,1)
			self.mapper = vtk.vtkPolyDataMapper()
			self.mapper.SetScalarVisibility(0)
			self.mapper.SetInput(cirpdo)
			self.helact = vtk.vtkActor()
			self.helact.PickableOff()
			self.helact.DragableOff()
			self.helact.GetProperty().SetColor(1,1,1)
			self.helact.GetProperty().SetRepresentationToWireframe()
			self.helact.GetProperty().SetLineWidth(5)
			self.helact.GetProperty().SetLineWidth(1)
			self.helact.GetProperty().SetSpecular(.4)
			self.helact.GetProperty().SetSpecularPower(10)
			self.helact.SetMapper(self.mapper)
			sphact2 = vtk.vtkActor()
			helact2 = vtk.vtkActor()
			sphact2.ShallowCopy(self.sphact)
			helact2.ShallowCopy(self.helact)
			self.sphact.AddPosition(0,0,dist*c/b)
			self.helact.AddPosition(0,0,dist*c/b)
			sphact2.AddPosition(0,0,-dist*c/b)
			helact2.AddPosition(0,0,-dist*c/b)
			assembly = vtk.vtkAssembly()
			assembly.AddPart(self.sphact)
			assembly.AddPart(self.helact)
			assembly.AddPart(sphact2)
			assembly.AddPart(helact2)
			self.acteur=assembly
			gfx.renderer.AddActor(self.acteur)
			gfx.renwin.Render()
			gfx.ps = self
Exemple #51
0
def prepContinents(fnm):
  """ This converts vcs continents files to vtkpolydata
  Author: Charles Doutriaux
  Input: vcs continent file name
  """
  if vcsContinents.has_key(fnm):
    return vcsContinents[fnm]
  poly =vtk.vtkPolyData()
  cells = vtk.vtkCellArray()
  pts = vtk.vtkPoints()
  f=open(fnm)
  ln=f.readline()
  while ln.strip().split()!=["-99","-99"]:
    # Many lines, need to know number of points
    N = int(ln.split()[0])
    # Now create and store these points
    n=0
    npts = pts.GetNumberOfPoints()
    while n<N:
        ln=f.readline()
        sp=ln.split()
        sn = len(sp)
        didIt = False
        if sn%2 == 0:
          try:
            spts = []
            for i in range(sn/2):
              l,L = float(sp[i*2]),float(sp[i*2+1])
              spts.append([l,L])
            for p in spts:
              pts.InsertNextPoint(p[1],p[0],0.)
            n+=sn
            didIt = True
          except:
            didIt = False
        if didIt is False:
          while len(ln)>2:
            l,L=float(ln[:8]),float(ln[8:16])
            pts.InsertNextPoint(L,l,0.)
            ln=ln[16:]
            n+=2
    ln = vtk.vtkPolyLine()
    ln.GetPointIds().SetNumberOfIds(N/2)
    for i in range(N/2): ln.GetPointIds().SetId(i,i+npts)
    cells.InsertNextCell(ln)
    ln=f.readline()
  poly.SetPoints(pts)
  poly.SetLines(cells)

  # The dataset has some duplicate lines that extend outside of x=[-180, 180],
  # which will cause wrapping artifacts for certain projections (e.g.
  # Robinson). Clip out the duplicate data:
  box = vtk.vtkBox()
  box.SetXMin(-180., -90., 0.)
  box.SetXMax(180., 90., 1.)
  clipper = vtk.vtkClipPolyData()
  clipper.SetInputData(poly)
  clipper.InsideOutOn()
  clipper.SetClipFunction(box)
  clipper.Update()
  poly = clipper.GetOutput()

  vcsContinents[fnm]=poly
  return poly
Exemple #52
0
    def testCells(self):

        # Demonstrates all cell types
        #
        # NOTE: the use of NewInstance/DeepCopy is included to increase
        # regression coverage.  It is not required in most applications.

        ren = vtk.vtkRenderer()
        # turn off all cullers
        ren.GetCullers().RemoveAllItems()

        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)
        renWin.SetSize(300, 150)
        iRen = vtk.vtkRenderWindowInteractor()
        iRen.SetRenderWindow(renWin)

        # create a scene with one of each cell type

        # Voxel

        voxelPoints = vtk.vtkPoints()
        voxelPoints.SetNumberOfPoints(8)
        voxelPoints.InsertPoint(0, 0, 0, 0)
        voxelPoints.InsertPoint(1, 1, 0, 0)
        voxelPoints.InsertPoint(2, 0, 1, 0)
        voxelPoints.InsertPoint(3, 1, 1, 0)
        voxelPoints.InsertPoint(4, 0, 0, 1)
        voxelPoints.InsertPoint(5, 1, 0, 1)
        voxelPoints.InsertPoint(6, 0, 1, 1)
        voxelPoints.InsertPoint(7, 1, 1, 1)

        aVoxel = vtk.vtkVoxel()
        aVoxel.GetPointIds().SetId(0, 0)
        aVoxel.GetPointIds().SetId(1, 1)
        aVoxel.GetPointIds().SetId(2, 2)
        aVoxel.GetPointIds().SetId(3, 3)
        aVoxel.GetPointIds().SetId(4, 4)
        aVoxel.GetPointIds().SetId(5, 5)
        aVoxel.GetPointIds().SetId(6, 6)
        aVoxel.GetPointIds().SetId(7, 7)

        bVoxel = aVoxel.NewInstance()
        bVoxel.DeepCopy(aVoxel)

        aVoxelGrid = vtk.vtkUnstructuredGrid()
        aVoxelGrid.Allocate(1, 1)
        aVoxelGrid.InsertNextCell(aVoxel.GetCellType(), aVoxel.GetPointIds())
        aVoxelGrid.SetPoints(voxelPoints)

        aVoxelMapper = vtk.vtkDataSetMapper()
        aVoxelMapper.SetInputData(aVoxelGrid)

        aVoxelActor = vtk.vtkActor()
        aVoxelActor.SetMapper(aVoxelMapper)
        aVoxelActor.GetProperty().BackfaceCullingOn()

        # Hexahedron

        hexahedronPoints = vtk.vtkPoints()
        hexahedronPoints.SetNumberOfPoints(8)
        hexahedronPoints.InsertPoint(0, 0, 0, 0)
        hexahedronPoints.InsertPoint(1, 1, 0, 0)
        hexahedronPoints.InsertPoint(2, 1, 1, 0)
        hexahedronPoints.InsertPoint(3, 0, 1, 0)
        hexahedronPoints.InsertPoint(4, 0, 0, 1)
        hexahedronPoints.InsertPoint(5, 1, 0, 1)
        hexahedronPoints.InsertPoint(6, 1, 1, 1)
        hexahedronPoints.InsertPoint(7, 0, 1, 1)

        aHexahedron = vtk.vtkHexahedron()
        aHexahedron.GetPointIds().SetId(0, 0)
        aHexahedron.GetPointIds().SetId(1, 1)
        aHexahedron.GetPointIds().SetId(2, 2)
        aHexahedron.GetPointIds().SetId(3, 3)
        aHexahedron.GetPointIds().SetId(4, 4)
        aHexahedron.GetPointIds().SetId(5, 5)
        aHexahedron.GetPointIds().SetId(6, 6)
        aHexahedron.GetPointIds().SetId(7, 7)

        bHexahedron = aHexahedron.NewInstance()
        bHexahedron.DeepCopy(aHexahedron)

        aHexahedronGrid = vtk.vtkUnstructuredGrid()
        aHexahedronGrid.Allocate(1, 1)
        aHexahedronGrid.InsertNextCell(aHexahedron.GetCellType(), aHexahedron.GetPointIds())
        aHexahedronGrid.SetPoints(hexahedronPoints)

        aHexahedronMapper = vtk.vtkDataSetMapper()
        aHexahedronMapper.SetInputData(aHexahedronGrid)

        aHexahedronActor = vtk.vtkActor()
        aHexahedronActor.SetMapper(aHexahedronMapper)
        aHexahedronActor.AddPosition(2, 0, 0)
        aHexahedronActor.GetProperty().BackfaceCullingOn()

        # Tetra

        tetraPoints = vtk.vtkPoints()
        tetraPoints.SetNumberOfPoints(4)
        tetraPoints.InsertPoint(0, 0, 0, 0)
        tetraPoints.InsertPoint(1, 1, 0, 0)
        tetraPoints.InsertPoint(2, 0.5, 1, 0)
        tetraPoints.InsertPoint(3, 0.5, 0.5, 1)

        aTetra = vtk.vtkTetra()
        aTetra.GetPointIds().SetId(0, 0)
        aTetra.GetPointIds().SetId(1, 1)
        aTetra.GetPointIds().SetId(2, 2)
        aTetra.GetPointIds().SetId(3, 3)

        bTetra = aTetra.NewInstance()
        bTetra.DeepCopy(aTetra)

        aTetraGrid = vtk.vtkUnstructuredGrid()
        aTetraGrid.Allocate(1, 1)
        aTetraGrid.InsertNextCell(aTetra.GetCellType(), aTetra.GetPointIds())
        aTetraGrid.SetPoints(tetraPoints)

        aTetraCopy = vtk.vtkUnstructuredGrid()
        aTetraCopy.ShallowCopy(aTetraGrid)

        aTetraMapper = vtk.vtkDataSetMapper()
        aTetraMapper.SetInputData(aTetraCopy)

        aTetraActor = vtk.vtkActor()
        aTetraActor.SetMapper(aTetraMapper)
        aTetraActor.AddPosition(4, 0, 0)
        aTetraActor.GetProperty().BackfaceCullingOn()

        # Wedge

        wedgePoints = vtk.vtkPoints()
        wedgePoints.SetNumberOfPoints(6)
        wedgePoints.InsertPoint(0, 0, 1, 0)
        wedgePoints.InsertPoint(1, 0, 0, 0)
        wedgePoints.InsertPoint(2, 0, 0.5, 0.5)
        wedgePoints.InsertPoint(3, 1, 1, 0)
        wedgePoints.InsertPoint(4, 1, 0, 0)
        wedgePoints.InsertPoint(5, 1, 0.5, 0.5)

        aWedge = vtk.vtkWedge()
        aWedge.GetPointIds().SetId(0, 0)
        aWedge.GetPointIds().SetId(1, 1)
        aWedge.GetPointIds().SetId(2, 2)
        aWedge.GetPointIds().SetId(3, 3)
        aWedge.GetPointIds().SetId(4, 4)
        aWedge.GetPointIds().SetId(5, 5)

        bWedge = aWedge.NewInstance()
        bWedge.DeepCopy(aWedge)

        aWedgeGrid = vtk.vtkUnstructuredGrid()
        aWedgeGrid.Allocate(1, 1)
        aWedgeGrid.InsertNextCell(aWedge.GetCellType(), aWedge.GetPointIds())
        aWedgeGrid.SetPoints(wedgePoints)

        aWedgeCopy = vtk.vtkUnstructuredGrid()
        aWedgeCopy.DeepCopy(aWedgeGrid)

        aWedgeMapper = vtk.vtkDataSetMapper()
        aWedgeMapper.SetInputData(aWedgeCopy)

        aWedgeActor = vtk.vtkActor()
        aWedgeActor.SetMapper(aWedgeMapper)
        aWedgeActor.AddPosition(6, 0, 0)
        aWedgeActor.GetProperty().BackfaceCullingOn()

        # Pyramid

        pyramidPoints = vtk.vtkPoints()
        pyramidPoints.SetNumberOfPoints(5)
        pyramidPoints.InsertPoint(0, 0, 0, 0)
        pyramidPoints.InsertPoint(1, 1, 0, 0)
        pyramidPoints.InsertPoint(2, 1, 1, 0)
        pyramidPoints.InsertPoint(3, 0, 1, 0)
        pyramidPoints.InsertPoint(4, 0.5, 0.5, 1)

        aPyramid = vtk.vtkPyramid()
        aPyramid.GetPointIds().SetId(0, 0)
        aPyramid.GetPointIds().SetId(1, 1)
        aPyramid.GetPointIds().SetId(2, 2)
        aPyramid.GetPointIds().SetId(3, 3)
        aPyramid.GetPointIds().SetId(4, 4)

        bPyramid = aPyramid.NewInstance()
        bPyramid.DeepCopy(aPyramid)

        aPyramidGrid = vtk.vtkUnstructuredGrid()
        aPyramidGrid.Allocate(1, 1)
        aPyramidGrid.InsertNextCell(aPyramid.GetCellType(), aPyramid.GetPointIds())
        aPyramidGrid.SetPoints(pyramidPoints)

        aPyramidMapper = vtk.vtkDataSetMapper()
        aPyramidMapper.SetInputData(aPyramidGrid)

        aPyramidActor = vtk.vtkActor()
        aPyramidActor.SetMapper(aPyramidMapper)
        aPyramidActor.AddPosition(8, 0, 0)
        aPyramidActor.GetProperty().BackfaceCullingOn()

        # Pixel

        pixelPoints = vtk.vtkPoints()
        pixelPoints.SetNumberOfPoints(4)
        pixelPoints.InsertPoint(0, 0, 0, 0)
        pixelPoints.InsertPoint(1, 1, 0, 0)
        pixelPoints.InsertPoint(2, 0, 1, 0)
        pixelPoints.InsertPoint(3, 1, 1, 0)

        aPixel = vtk.vtkPixel()
        aPixel.GetPointIds().SetId(0, 0)
        aPixel.GetPointIds().SetId(1, 1)
        aPixel.GetPointIds().SetId(2, 2)
        aPixel.GetPointIds().SetId(3, 3)

        bPixel = aPixel.NewInstance()
        bPixel.DeepCopy(aPixel)

        aPixelGrid = vtk.vtkUnstructuredGrid()
        aPixelGrid.Allocate(1, 1)
        aPixelGrid.InsertNextCell(aPixel.GetCellType(), aPixel.GetPointIds())
        aPixelGrid.SetPoints(pixelPoints)

        aPixelMapper = vtk.vtkDataSetMapper()
        aPixelMapper.SetInputData(aPixelGrid)

        aPixelActor = vtk.vtkActor()
        aPixelActor.SetMapper(aPixelMapper)
        aPixelActor.AddPosition(0, 0, 2)
        aPixelActor.GetProperty().BackfaceCullingOn()

        # Quad

        quadPoints = vtk.vtkPoints()
        quadPoints.SetNumberOfPoints(4)
        quadPoints.InsertPoint(0, 0, 0, 0)
        quadPoints.InsertPoint(1, 1, 0, 0)
        quadPoints.InsertPoint(2, 1, 1, 0)
        quadPoints.InsertPoint(3, 0, 1, 0)

        aQuad = vtk.vtkQuad()
        aQuad.GetPointIds().SetId(0, 0)
        aQuad.GetPointIds().SetId(1, 1)
        aQuad.GetPointIds().SetId(2, 2)
        aQuad.GetPointIds().SetId(3, 3)

        bQuad = aQuad.NewInstance()
        bQuad.DeepCopy(aQuad)

        aQuadGrid = vtk.vtkUnstructuredGrid()
        aQuadGrid.Allocate(1, 1)
        aQuadGrid.InsertNextCell(aQuad.GetCellType(), aQuad.GetPointIds())
        aQuadGrid.SetPoints(quadPoints)

        aQuadMapper = vtk.vtkDataSetMapper()
        aQuadMapper.SetInputData(aQuadGrid)

        aQuadActor = vtk.vtkActor()
        aQuadActor.SetMapper(aQuadMapper)
        aQuadActor.AddPosition(2, 0, 2)
        aQuadActor.GetProperty().BackfaceCullingOn()

        # Triangle

        trianglePoints = vtk.vtkPoints()
        trianglePoints.SetNumberOfPoints(3)
        trianglePoints.InsertPoint(0, 0, 0, 0)
        trianglePoints.InsertPoint(1, 1, 0, 0)
        trianglePoints.InsertPoint(2, 0.5, 0.5, 0)

        triangleTCoords = vtk.vtkFloatArray()
        triangleTCoords.SetNumberOfComponents(2)
        triangleTCoords.SetNumberOfTuples(3)
        triangleTCoords.InsertTuple2(0, 1, 1)
        triangleTCoords.InsertTuple2(1, 2, 2)
        triangleTCoords.InsertTuple2(2, 3, 3)

        aTriangle = vtk.vtkTriangle()
        aTriangle.GetPointIds().SetId(0, 0)
        aTriangle.GetPointIds().SetId(1, 1)
        aTriangle.GetPointIds().SetId(2, 2)

        bTriangle = aTriangle.NewInstance()
        bTriangle.DeepCopy(aTriangle)

        aTriangleGrid = vtk.vtkUnstructuredGrid()
        aTriangleGrid.Allocate(1, 1)
        aTriangleGrid.InsertNextCell(aTriangle.GetCellType(), aTriangle.GetPointIds())
        aTriangleGrid.SetPoints(trianglePoints)
        aTriangleGrid.GetPointData().SetTCoords(triangleTCoords)

        aTriangleMapper = vtk.vtkDataSetMapper()
        aTriangleMapper.SetInputData(aTriangleGrid)

        aTriangleActor = vtk.vtkActor()
        aTriangleActor.SetMapper(aTriangleMapper)
        aTriangleActor.AddPosition(4, 0, 2)
        aTriangleActor.GetProperty().BackfaceCullingOn()

        # Polygon

        polygonPoints = vtk.vtkPoints()
        polygonPoints.SetNumberOfPoints(4)
        polygonPoints.InsertPoint(0, 0, 0, 0)
        polygonPoints.InsertPoint(1, 1, 0, 0)
        polygonPoints.InsertPoint(2, 1, 1, 0)
        polygonPoints.InsertPoint(3, 0, 1, 0)

        aPolygon = vtk.vtkPolygon()
        aPolygon.GetPointIds().SetNumberOfIds(4)
        aPolygon.GetPointIds().SetId(0, 0)
        aPolygon.GetPointIds().SetId(1, 1)
        aPolygon.GetPointIds().SetId(2, 2)
        aPolygon.GetPointIds().SetId(3, 3)

        bPolygon = aPolygon.NewInstance()
        bPolygon.DeepCopy(aPolygon)

        aPolygonGrid = vtk.vtkUnstructuredGrid()
        aPolygonGrid.Allocate(1, 1)
        aPolygonGrid.InsertNextCell(aPolygon.GetCellType(), aPolygon.GetPointIds())
        aPolygonGrid.SetPoints(polygonPoints)

        aPolygonMapper = vtk.vtkDataSetMapper()
        aPolygonMapper.SetInputData(aPolygonGrid)

        aPolygonActor = vtk.vtkActor()
        aPolygonActor.SetMapper(aPolygonMapper)
        aPolygonActor.AddPosition(6, 0, 2)
        aPolygonActor.GetProperty().BackfaceCullingOn()

        # Triangle Strip

        triangleStripPoints = vtk.vtkPoints()
        triangleStripPoints.SetNumberOfPoints(5)
        triangleStripPoints.InsertPoint(0, 0, 1, 0)
        triangleStripPoints.InsertPoint(1, 0, 0, 0)
        triangleStripPoints.InsertPoint(2, 1, 1, 0)
        triangleStripPoints.InsertPoint(3, 1, 0, 0)
        triangleStripPoints.InsertPoint(4, 2, 1, 0)

        triangleStripTCoords = vtk.vtkFloatArray()
        triangleStripTCoords.SetNumberOfComponents(2)
        triangleStripTCoords.SetNumberOfTuples(3)
        triangleStripTCoords.InsertTuple2(0, 1, 1)
        triangleStripTCoords.InsertTuple2(1, 2, 2)
        triangleStripTCoords.InsertTuple2(2, 3, 3)
        triangleStripTCoords.InsertTuple2(3, 4, 4)
        triangleStripTCoords.InsertTuple2(4, 5, 5)

        aTriangleStrip = vtk.vtkTriangleStrip()
        aTriangleStrip.GetPointIds().SetNumberOfIds(5)
        aTriangleStrip.GetPointIds().SetId(0, 0)
        aTriangleStrip.GetPointIds().SetId(1, 1)
        aTriangleStrip.GetPointIds().SetId(2, 2)
        aTriangleStrip.GetPointIds().SetId(3, 3)
        aTriangleStrip.GetPointIds().SetId(4, 4)

        bTriangleStrip = aTriangleStrip.NewInstance()
        bTriangleStrip.DeepCopy(aTriangleStrip)

        aTriangleStripGrid = vtk.vtkUnstructuredGrid()
        aTriangleStripGrid.Allocate(1, 1)
        aTriangleStripGrid.InsertNextCell(aTriangleStrip.GetCellType(), aTriangleStrip.GetPointIds())
        aTriangleStripGrid.SetPoints(triangleStripPoints)
        aTriangleStripGrid.GetPointData().SetTCoords(triangleStripTCoords)

        aTriangleStripMapper = vtk.vtkDataSetMapper()
        aTriangleStripMapper.SetInputData(aTriangleStripGrid)

        aTriangleStripActor = vtk.vtkActor()
        aTriangleStripActor.SetMapper(aTriangleStripMapper)
        aTriangleStripActor.AddPosition(8, 0, 2)
        aTriangleStripActor.GetProperty().BackfaceCullingOn()

        # Line

        linePoints = vtk.vtkPoints()
        linePoints.SetNumberOfPoints(2)
        linePoints.InsertPoint(0, 0, 0, 0)
        linePoints.InsertPoint(1, 1, 1, 0)

        aLine = vtk.vtkLine()
        aLine.GetPointIds().SetId(0, 0)
        aLine.GetPointIds().SetId(1, 1)

        bLine = aLine.NewInstance()
        bLine.DeepCopy(aLine)

        aLineGrid = vtk.vtkUnstructuredGrid()
        aLineGrid.Allocate(1, 1)
        aLineGrid.InsertNextCell(aLine.GetCellType(), aLine.GetPointIds())
        aLineGrid.SetPoints(linePoints)

        aLineMapper = vtk.vtkDataSetMapper()
        aLineMapper.SetInputData(aLineGrid)

        aLineActor = vtk.vtkActor()
        aLineActor.SetMapper(aLineMapper)
        aLineActor.AddPosition(0, 0, 4)
        aLineActor.GetProperty().BackfaceCullingOn()

        # Poly line

        polyLinePoints = vtk.vtkPoints()
        polyLinePoints.SetNumberOfPoints(3)
        polyLinePoints.InsertPoint(0, 0, 0, 0)
        polyLinePoints.InsertPoint(1, 1, 1, 0)
        polyLinePoints.InsertPoint(2, 1, 0, 0)

        aPolyLine = vtk.vtkPolyLine()
        aPolyLine.GetPointIds().SetNumberOfIds(3)
        aPolyLine.GetPointIds().SetId(0, 0)
        aPolyLine.GetPointIds().SetId(1, 1)
        aPolyLine.GetPointIds().SetId(2, 2)

        bPolyLine = aPolyLine.NewInstance()
        bPolyLine.DeepCopy(aPolyLine)

        aPolyLineGrid = vtk.vtkUnstructuredGrid()
        aPolyLineGrid.Allocate(1, 1)
        aPolyLineGrid.InsertNextCell(aPolyLine.GetCellType(), aPolyLine.GetPointIds())
        aPolyLineGrid.SetPoints(polyLinePoints)

        aPolyLineMapper = vtk.vtkDataSetMapper()
        aPolyLineMapper.SetInputData(aPolyLineGrid)

        aPolyLineActor = vtk.vtkActor()
        aPolyLineActor.SetMapper(aPolyLineMapper)
        aPolyLineActor.AddPosition(2, 0, 4)
        aPolyLineActor.GetProperty().BackfaceCullingOn()

        # Vertex

        vertexPoints = vtk.vtkPoints()
        vertexPoints.SetNumberOfPoints(1)
        vertexPoints.InsertPoint(0, 0, 0, 0)

        aVertex = vtk.vtkVertex()
        aVertex.GetPointIds().SetId(0, 0)

        bVertex = aVertex.NewInstance()
        bVertex.DeepCopy(aVertex)

        aVertexGrid = vtk.vtkUnstructuredGrid()
        aVertexGrid.Allocate(1, 1)
        aVertexGrid.InsertNextCell(aVertex.GetCellType(), aVertex.GetPointIds())
        aVertexGrid.SetPoints(vertexPoints)

        aVertexMapper = vtk.vtkDataSetMapper()
        aVertexMapper.SetInputData(aVertexGrid)

        aVertexActor = vtk.vtkActor()
        aVertexActor.SetMapper(aVertexMapper)
        aVertexActor.AddPosition(0, 0, 6)
        aVertexActor.GetProperty().BackfaceCullingOn()

        # Poly Vertex

        polyVertexPoints = vtk.vtkPoints()
        polyVertexPoints.SetNumberOfPoints(3)
        polyVertexPoints.InsertPoint(0, 0, 0, 0)
        polyVertexPoints.InsertPoint(1, 1, 0, 0)
        polyVertexPoints.InsertPoint(2, 1, 1, 0)

        aPolyVertex = vtk.vtkPolyVertex()
        aPolyVertex.GetPointIds().SetNumberOfIds(3)
        aPolyVertex.GetPointIds().SetId(0, 0)
        aPolyVertex.GetPointIds().SetId(1, 1)
        aPolyVertex.GetPointIds().SetId(2, 2)

        bPolyVertex = aPolyVertex.NewInstance()
        bPolyVertex.DeepCopy(aPolyVertex)

        aPolyVertexGrid = vtk.vtkUnstructuredGrid()
        aPolyVertexGrid.Allocate(1, 1)
        aPolyVertexGrid.InsertNextCell(aPolyVertex.GetCellType(), aPolyVertex.GetPointIds())
        aPolyVertexGrid.SetPoints(polyVertexPoints)

        aPolyVertexMapper = vtk.vtkDataSetMapper()
        aPolyVertexMapper.SetInputData(aPolyVertexGrid)

        aPolyVertexActor = vtk.vtkActor()
        aPolyVertexActor.SetMapper(aPolyVertexMapper)
        aPolyVertexActor.AddPosition(2, 0, 6)
        aPolyVertexActor.GetProperty().BackfaceCullingOn()

        # Pentagonal prism

        pentaPoints = vtk.vtkPoints()
        pentaPoints.SetNumberOfPoints(10)
        pentaPoints.InsertPoint(0, 0.25, 0.0, 0.0)
        pentaPoints.InsertPoint(1, 0.75, 0.0, 0.0)
        pentaPoints.InsertPoint(2, 1.0, 0.5, 0.0)
        pentaPoints.InsertPoint(3, 0.5, 1.0, 0.0)
        pentaPoints.InsertPoint(4, 0.0, 0.5, 0.0)
        pentaPoints.InsertPoint(5, 0.25, 0.0, 1.0)
        pentaPoints.InsertPoint(6, 0.75, 0.0, 1.0)
        pentaPoints.InsertPoint(7, 1.0, 0.5, 1.0)
        pentaPoints.InsertPoint(8, 0.5, 1.0, 1.0)
        pentaPoints.InsertPoint(9, 0.0, 0.5, 1.0)

        aPenta = vtk.vtkPentagonalPrism()
        aPenta.GetPointIds().SetId(0, 0)
        aPenta.GetPointIds().SetId(1, 1)
        aPenta.GetPointIds().SetId(2, 2)
        aPenta.GetPointIds().SetId(3, 3)
        aPenta.GetPointIds().SetId(4, 4)
        aPenta.GetPointIds().SetId(5, 5)
        aPenta.GetPointIds().SetId(6, 6)
        aPenta.GetPointIds().SetId(7, 7)
        aPenta.GetPointIds().SetId(8, 8)
        aPenta.GetPointIds().SetId(9, 9)

        bPenta = aPenta.NewInstance()
        bPenta.DeepCopy(aPenta)

        aPentaGrid = vtk.vtkUnstructuredGrid()
        aPentaGrid.Allocate(1, 1)
        aPentaGrid.InsertNextCell(aPenta.GetCellType(), aPenta.GetPointIds())
        aPentaGrid.SetPoints(pentaPoints)

        aPentaCopy = vtk.vtkUnstructuredGrid()
        aPentaCopy.DeepCopy(aPentaGrid)

        aPentaMapper = vtk.vtkDataSetMapper()
        aPentaMapper.SetInputData(aPentaCopy)

        aPentaActor = vtk.vtkActor()
        aPentaActor.SetMapper(aPentaMapper)
        aPentaActor.AddPosition(10, 0, 0)
        aPentaActor.GetProperty().BackfaceCullingOn()

        # Hexagonal prism

        hexaPoints = vtk.vtkPoints()
        hexaPoints.SetNumberOfPoints(12)
        hexaPoints.InsertPoint(0, 0.0, 0.0, 0.0)
        hexaPoints.InsertPoint(1, 0.5, 0.0, 0.0)
        hexaPoints.InsertPoint(2, 1.0, 0.5, 0.0)
        hexaPoints.InsertPoint(3, 1.0, 1.0, 0.0)
        hexaPoints.InsertPoint(4, 0.5, 1.0, 0.0)
        hexaPoints.InsertPoint(5, 0.0, 0.5, 0.0)
        hexaPoints.InsertPoint(6, 0.0, 0.0, 1.0)
        hexaPoints.InsertPoint(7, 0.5, 0.0, 1.0)
        hexaPoints.InsertPoint(8, 1.0, 0.5, 1.0)
        hexaPoints.InsertPoint(9, 1.0, 1.0, 1.0)
        hexaPoints.InsertPoint(10, 0.5, 1.0, 1.0)
        hexaPoints.InsertPoint(11, 0.0, 0.5, 1.0)

        aHexa = vtk.vtkHexagonalPrism()
        aHexa.GetPointIds().SetId(0, 0)
        aHexa.GetPointIds().SetId(1, 1)
        aHexa.GetPointIds().SetId(2, 2)
        aHexa.GetPointIds().SetId(3, 3)
        aHexa.GetPointIds().SetId(4, 4)
        aHexa.GetPointIds().SetId(5, 5)
        aHexa.GetPointIds().SetId(6, 6)
        aHexa.GetPointIds().SetId(7, 7)
        aHexa.GetPointIds().SetId(8, 8)
        aHexa.GetPointIds().SetId(9, 9)
        aHexa.GetPointIds().SetId(10, 10)
        aHexa.GetPointIds().SetId(11, 11)

        bHexa = aHexa.NewInstance()
        bHexa.DeepCopy(aHexa)

        aHexaGrid = vtk.vtkUnstructuredGrid()
        aHexaGrid.Allocate(1, 1)
        aHexaGrid.InsertNextCell(aHexa.GetCellType(), aHexa.GetPointIds())
        aHexaGrid.SetPoints(hexaPoints)

        aHexaCopy = vtk.vtkUnstructuredGrid()
        aHexaCopy.DeepCopy(aHexaGrid)

        aHexaMapper = vtk.vtkDataSetMapper()
        aHexaMapper.SetInputData(aHexaCopy)

        aHexaActor = vtk.vtkActor()
        aHexaActor.SetMapper(aHexaMapper)
        aHexaActor.AddPosition(12, 0, 0)
        aHexaActor.GetProperty().BackfaceCullingOn()

        # RIB property
        aRIBProperty = vtk.vtkRIBProperty()
        aRIBProperty.SetVariable("Km", "float")
        aRIBProperty.SetSurfaceShader("LGVeinedmarble")
        aRIBProperty.SetVariable("veinfreq", "float")
        aRIBProperty.AddVariable("warpfreq", "float")
        aRIBProperty.AddVariable("veincolor", "color")
        aRIBProperty.AddParameter("veinfreq", " 2")
        aRIBProperty.AddParameter("veincolor", "1.0000 1.0000 0.9412")
        bRIBProperty = vtk.vtkRIBProperty()
        bRIBProperty.SetVariable("Km", "float")
        bRIBProperty.SetParameter("Km", "1.0")
        bRIBProperty.SetDisplacementShader("dented")
        bRIBProperty.SetSurfaceShader("plastic")
        aProperty = vtk.vtkProperty()
        bProperty = vtk.vtkProperty()

        aTriangleActor.SetProperty(aProperty)
        aTriangleStripActor.SetProperty(bProperty)

        ren.SetBackground(0.1, 0.2, 0.4)

        ren.AddActor(aVoxelActor)
        aVoxelActor.GetProperty().SetDiffuseColor(1, 0, 0)
        ren.AddActor(aHexahedronActor)
        aHexahedronActor.GetProperty().SetDiffuseColor(1, 1, 0)
        ren.AddActor(aTetraActor)
        aTetraActor.GetProperty().SetDiffuseColor(0, 1, 0)
        ren.AddActor(aWedgeActor)
        aWedgeActor.GetProperty().SetDiffuseColor(0, 1, 1)
        ren.AddActor(aPyramidActor)
        aPyramidActor.GetProperty().SetDiffuseColor(1, 0, 1)
        ren.AddActor(aPixelActor)
        aPixelActor.GetProperty().SetDiffuseColor(0, 1, 1)
        ren.AddActor(aQuadActor)
        aQuadActor.GetProperty().SetDiffuseColor(1, 0, 1)
        ren.AddActor(aTriangleActor)
        aTriangleActor.GetProperty().SetDiffuseColor(0.3, 1, 0.5)
        ren.AddActor(aPolygonActor)
        aPolygonActor.GetProperty().SetDiffuseColor(1, 0.4, 0.5)
        ren.AddActor(aTriangleStripActor)
        aTriangleStripActor.GetProperty().SetDiffuseColor(0.3, 0.7, 1)
        ren.AddActor(aLineActor)
        aLineActor.GetProperty().SetDiffuseColor(0.2, 1, 1)
        ren.AddActor(aPolyLineActor)
        aPolyLineActor.GetProperty().SetDiffuseColor(1, 1, 1)
        ren.AddActor(aVertexActor)
        aVertexActor.GetProperty().SetDiffuseColor(1, 1, 1)
        ren.AddActor(aPolyVertexActor)
        aPolyVertexActor.GetProperty().SetDiffuseColor(1, 1, 1)
        ren.AddActor(aPentaActor)
        aPentaActor.GetProperty().SetDiffuseColor(0.2, 0.4, 0.7)
        ren.AddActor(aHexaActor)
        aHexaActor.GetProperty().SetDiffuseColor(0.7, 0.5, 1)

        aRIBLight = vtk.vtkRIBLight()
        aRIBLight.ShadowsOn()
        aLight = vtk.vtkLight()

        aLight.PositionalOn()
        aLight.SetConeAngle(25)

        ren.AddLight(aLight)

        ren.ResetCamera()
        ren.GetActiveCamera().Azimuth(30)
        ren.GetActiveCamera().Elevation(20)
        ren.GetActiveCamera().Dolly(2.8)
        ren.ResetCameraClippingRange()

        aLight.SetFocalPoint(ren.GetActiveCamera().GetFocalPoint())
        aLight.SetPosition(ren.GetActiveCamera().GetPosition())

        # write to the temp directory if possible, otherwise use .
        dir = tempfile.gettempdir()

        atext = vtk.vtkTexture()
        pnmReader = vtk.vtkBMPReader()
        pnmReader.SetFileName(VTK_DATA_ROOT + "/Data/masonry.bmp")
        atext.SetInputConnection(pnmReader.GetOutputPort())
        atext.InterpolateOff()
        aTriangleActor.SetTexture(atext)
        rib = vtk.vtkRIBExporter()
        rib.SetInput(renWin)
        rib.SetFilePrefix(dir + "/cells")
        rib.SetTexturePrefix(dir + "/cells")
        rib.Write()
        os.remove(dir + "/cells.rib")

        iv = vtk.vtkIVExporter()
        iv.SetInput(renWin)
        iv.SetFileName(dir + "/cells.iv")
        iv.Write()
        os.remove(dir + "/cells.iv")

        obj = vtk.vtkOBJExporter()
        obj.SetInput(renWin)
        obj.SetFilePrefix(dir + "/cells")
        obj.Write()
        os.remove(dir + "/cells.obj")
        os.remove(dir + "/cells.mtl")

        vrml = vtk.vtkVRMLExporter()
        vrml.SetInput(renWin)
        # vrml.SetStartWrite(vrml.SetFileName(dir + "/cells.wrl"))
        # vrml.SetEndWrite(vrml.SetFileName("/a/acells.wrl"))
        vrml.SetFileName(dir + "/cells.wrl")
        vrml.SetSpeed(5.5)
        vrml.Write()
        os.remove(dir + "/cells.wrl")

        oogl = vtk.vtkOOGLExporter()
        oogl.SetInput(renWin)
        oogl.SetFileName(dir + "/cells.oogl")
        oogl.Write()
        os.remove(dir + "/cells.oogl")

        # the UnRegister calls are because make object is the same as New,
        # and causes memory leaks. (Python does not treat NewInstance the same as New).
        def DeleteCopies():
            bVoxel.UnRegister(None)
            bHexahedron.UnRegister(None)
            bTetra.UnRegister(None)
            bWedge.UnRegister(None)
            bPyramid.UnRegister(None)
            bPixel.UnRegister(None)
            bQuad.UnRegister(None)
            bTriangle.UnRegister(None)
            bPolygon.UnRegister(None)
            bTriangleStrip.UnRegister(None)
            bLine.UnRegister(None)
            bPolyLine.UnRegister(None)
            bVertex.UnRegister(None)
            bPolyVertex.UnRegister(None)
            bPenta.UnRegister(None)
            bHexa.UnRegister(None)

        DeleteCopies()

        # render and interact with data

        renWin.Render()

        img_file = "cells.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
def BuildCentreline(segmentList, firstId = 0, firstPt = (0.0,0.0,0.0), direction = 0.0):
    print 'Processing centreline:', segmentList
    
    domain = None

    try:
        domain = segmentList[0]
    except IndexError:
        sys.exit("Missing domain length in list " + str(list) + ".")
        
    if isinstance(domain, tuple):
        domainLength = domain[0]
        angle = math.radians(domain[1])
    else:    
        if not isinstance(domain, (int, float, long)):
            sys.exit("Domain length should be a number, not a(an) " + str(type(domainLength)) + ".")
        angle = branchAngle
        domainLength = domain
    
    leftBranch = None
    try:
        leftBranch = segmentList[1]
    except IndexError:
        pass
    
    rightBranch = None
    try:
        rightBranch = segmentList[2]
    except IndexError:
        pass
    
    line = vtk.vtkPolyLine()
    
    if  direction < 0:
        angle = math.pi - angle
    
    for pId in range (0, int(domainLength / step) + 1):
            nextPt = ((firstPt[0] + (1.0 if direction == 0.0 else math.sin(angle)) * (step * pId)) * scaling, \
                        (firstPt[1] + (1.0 if direction == 0.0 else math.cos(angle)) * (step * pId) * direction) * scaling , \
                        firstPt[2] * scaling)
                        
            if sphereRadius != None:
                longitude = nextPt[0] / sphereRadius
                latitude = 2 * math.atan(math.exp(nextPt[1] / sphereRadius)) - math.pi / 2.0
                nextPtS = (sphereRadius * math.cos(latitude) * math.cos(longitude),\
                            sphereRadius * math.cos(latitude) * math.sin(longitude),\
                            sphereRadius * math.sin(latitude))
            
                if firstId == 0 or pId > 0:
                    nextId = points.InsertNextPoint(nextPtS)
                else:
                    nextId = firstId
            else:
                if firstId == 0 or pId > 0:
                    nextId = points.InsertNextPoint(nextPt)
                else:
                    nextId = firstId
            
            line.GetPointIds().InsertNextId(nextId)
            
    lines.InsertNextCell(line)
    
    if isinstance(leftBranch, list):
        BuildCentreline(leftBranch, nextId, nextPt, 1.0)

    if isinstance(rightBranch, list):
        BuildCentreline(rightBranch, nextId, nextPt, -1.0)
Exemple #54
0
    def init_draw(self, fiber, ren, **kwargs):
        # Convert color to rgb.
        my_color = kwargs.get('color', 'b')
        label = kwargs.get('label', '')
        rgb_color = 255 * colorConverter.to_rgba(my_color)

        # Create a vtkPoints instance.
        points = vtk.vtkPoints()
        self.points = points
        poly_line = vtk.vtkPolyLine()
        nb_points = fiber.get_nb_points()
        poly_line.GetPointIds().SetNumberOfIds(nb_points)
        for i in range(nb_points):
            poly_line.GetPointIds().SetId(i, i)
            self.points.InsertNextPoint(fiber.get_points()[i])
        cells = vtk.vtkCellArray()
        cells.InsertNextCell(poly_line)
        poly_data = vtk.vtkPolyData()
        poly_data.SetPoints(points)
        poly_data.SetLines(cells)

        # The tube is wrapped around the generated streamline.
        stream_tube = vtk.vtkTubeFilter()
        self.tube = stream_tube
        if major_version <= 5:
            stream_tube.SetInput(poly_data)
        else:
            stream_tube.SetInputData(poly_data)
        stream_tube.SetRadius(fiber.get_radius())
        stream_tube.SetNumberOfSides(12)
        stream_tube.SetCapping(True)
        map_stream_tube = vtk.vtkPolyDataMapper()
        map_stream_tube.SetInputConnection(stream_tube.GetOutputPort())
        actor = vtk.vtkActor()
        actor.SetMapper(map_stream_tube)
        actor.GetProperty().SetColor(rgb_color[0], rgb_color[1], rgb_color[2])
        ren.AddActor(actor)
        self.actor = actor

        # Add label to the figure
        text_source = vtk.vtkVectorText()
        text_source.SetText(label)
        text_source.Update()
        text_mapper = vtk.vtkPolyDataMapper()
        text_mapper.SetInputConnection(text_source.GetOutputPort())         

        text_actor1 = vtk.vtkActor()
        text_actor1.SetMapper(text_mapper)
        text_actor1.GetProperty().SetColor(rgb_color[0], 
                                           rgb_color[1], 
                                           rgb_color[2])
        text_actor1.SetScale(1.0)
        center1 = text_actor1.GetCenter()
        text_actor1.RotateX(90)
        text_actor1.AddPosition(fiber.get_points()[-1] * 1.2 - center1)

        text_actor2 = vtk.vtkActor()
        text_actor2.SetMapper(text_mapper)
        text_actor2.GetProperty().SetColor(rgb_color[0], 
                                           rgb_color[1], 
                                           rgb_color[2])
        text_actor2.SetScale(1.0)
        center2 = text_actor2.GetCenter()
        text_actor2.RotateX(90)
        text_actor2.AddPosition(fiber.get_points()[0] * 1.2 - center2)

        ren.AddActor(text_actor1)
        ren.AddActor(text_actor2)