def assignElements2Dlin(mesh, elements): numRows, numCols = elements.shape # TODO can we do this faster? for i in range(numRows): v0, v1, v2, v3, v4, v5 = elements[i, :] tri1 = vtk.vtkTriangle() tri1.GetPointIds().SetId(0, v0) tri1.GetPointIds().SetId(1, v3) tri1.GetPointIds().SetId(2, v4) tri2 = vtk.vtkTriangle() tri2.GetPointIds().SetId(0, v3) tri2.GetPointIds().SetId(1, v1) tri2.GetPointIds().SetId(2, v5) tri3 = vtk.vtkTriangle() tri3.GetPointIds().SetId(0, v3) tri3.GetPointIds().SetId(1, v5) tri3.GetPointIds().SetId(2, v4) tri4 = vtk.vtkTriangle() tri4.GetPointIds().SetId(0, v4) tri4.GetPointIds().SetId(1, v5) tri4.GetPointIds().SetId(2, v2) mesh.InsertNextCell(tri1.GetCellType(), tri1.GetPointIds()) mesh.InsertNextCell(tri1.GetCellType(), tri2.GetPointIds()) mesh.InsertNextCell(tri1.GetCellType(), tri3.GetPointIds()) mesh.InsertNextCell(tri1.GetCellType(), tri4.GetPointIds()) return mesh
def setup_topography(x, y, topography, xmax=None, ymax=None, decimation=1): # Define points, triangles and colors x = x[::decimation] y = y[::decimation] lonsize = len(x)-1 if not xmax else xmax latsize = len(y)-1 if not ymax else ymax colors = vtk.vtkUnsignedCharArray() # colors.SetNumberOfComponents(3) colors.SetNumberOfComponents(1) points = vtk.vtkPoints() triangles = vtk.vtkCellArray() zmax = topography.max() zmin = topography.min() zrange = zmax - zmin xmesh, ymesh = scaled_mesh(x, y) count = 0 t1 = time.time() topography = topography.T topo_new = num.zeros((len(y), len(x))) for iy in xrange(len(y)): topo_new[iy, :] = topography[iy*decimation, ::decimation] topography = topo_new for i in xrange(latsize): print '%i / %i' % (i+1, latsize) for j in xrange(lonsize-3): d = (ymesh[i][j], xmesh[i][j], topography[i][j]) c = (ymesh[i][j+1], xmesh[i][j+1], topography[i][j+1]) b = (ymesh[i+1][j+1], xmesh[i+1][j+1], topography[i+1][j+1]) a = (ymesh[i+1][j], xmesh[i+1][j], topography[i+1][j]) points.InsertNextPoint(*a) points.InsertNextPoint(*b) points.InsertNextPoint(*c) triangle = vtk.vtkTriangle() triangle.GetPointIds().SetId(0, count) triangle.GetPointIds().SetId(1, count + 1) triangle.GetPointIds().SetId(2, count + 2) triangles.InsertNextCell(triangle) points.InsertNextPoint(*a) points.InsertNextPoint(*d) points.InsertNextPoint(*c) triangle = vtk.vtkTriangle() triangle.GetPointIds().SetId(0, count + 3) triangle.GetPointIds().SetId(1, count + 4) triangle.GetPointIds().SetId(2, count + 5) count += 6 triangles.InsertNextCell(triangle) # rs = [[int((zmax-topography[j][i])/zrange*255)]]*6 rs = [[int((zmax-topography[i][j])/zrange*255)]]*6 map(colors.InsertNextTupleValue, rs) print 'total time needed ', time.time()-t1 return points, triangles, colors
def vtkTile(tile, min_temp, max_temp): # calcula a intensidade da cor para representar a temperatura. # vermelho, com pastilha. azul, estourou intensity = 255 - int(((tile.last_temp - min_temp) / (max_temp - min_temp)) * 256) if tile.bursted: color = (intensity, intensity, 255) else: color = (255, intensity, intensity) Points = vtk.vtkPoints() Triangles = vtk.vtkCellArray() Points.InsertNextPoint(*tile.edges[0]) Points.InsertNextPoint(*tile.edges[1]) Points.InsertNextPoint(*tile.edges[2]) Points.InsertNextPoint(*tile.edges[3]) Triangle1 = vtk.vtkTriangle(); Triangle1.GetPointIds().SetId(0, 0); Triangle1.GetPointIds().SetId(1, 1); Triangle1.GetPointIds().SetId(2, 2); Triangles.InsertNextCell(Triangle1); Triangle2 = vtk.vtkTriangle(); Triangle2.GetPointIds().SetId(0, 1); Triangle2.GetPointIds().SetId(1, 3); Triangle2.GetPointIds().SetId(2, 2); Triangles.InsertNextCell(Triangle2); Colors = vtk.vtkUnsignedCharArray(); Colors.SetNumberOfComponents(3); Colors.SetName("Colors"); Colors.InsertNextTuple3(*color); Colors.InsertNextTuple3(*color); polydata = vtk.vtkPolyData() polydata.SetPoints(Points) polydata.SetPolys(Triangles) polydata.GetCellData().SetScalars(Colors); polydata.Modified() polydata.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInput(polydata) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetAmbient(1.0) actor.GetProperty().SetDiffuse(0.0) return actor
def Gen_uGrid(new_pt, new_fc): """ Generates a vtk unstructured grid given points and triangular faces""" ints = np.ones(len(new_fc), 'int') * 3 cells = np.hstack((ints.reshape(-1, 1), np.vstack(new_fc))) # Generate vtk mesh # Convert points to vtkfloat object points = np.vstack(new_pt) vtkArray = VN.numpy_to_vtk(np.ascontiguousarray(points), deep=True) #, deep=True) points = vtk.vtkPoints() points.SetData(vtkArray) # Convert to vtk arrays tritype = vtk.vtkTriangle().GetCellType() * np.ones(len(new_fc), 'int') cell_type = np.ascontiguousarray(tritype).astype('uint8') cell_type = VN.numpy_to_vtk(cell_type, deep=True) offset = np.cumsum(np.hstack(ints + 1)) offset = np.ascontiguousarray(np.delete(np.insert(offset, 0, 0), -1)).astype('int64') # shift offset = VN.numpy_to_vtkIdTypeArray(offset, deep=True) cells = np.ascontiguousarray(np.hstack(cells).astype('int64')) vtkcells = vtk.vtkCellArray() vtkcells.SetCells(cells.shape[0], VN.numpy_to_vtkIdTypeArray(cells, deep=True)) # Create unstructured grid uGrid = vtk.vtkUnstructuredGrid() uGrid.SetPoints(points) uGrid.SetCells(cell_type, offset, vtkcells) return uGrid
def _build_vtkPolyData(vertices, faces): """Builds a vtkPolyData object from vertices and faces""" import vtk # Create a vtkPoints object and store the points in it points = vtk.vtkPoints() for point in vertices: points.InsertNextPoint(point) # Create a vtkCellArray to store faces cell_array = vtk.vtkCellArray() for face_ids in faces: if face_ids[0] == face_ids[-1]: # Triangle curface = face_ids[:3] vtk_face = vtk.vtkTriangle() else: # Quadrangle curface = face_ids[:4] vtk_face = vtk.vtkQuad() for idx, id in enumerate(curface): vtk_face.GetPointIds().SetId(idx, id) cell_array.InsertNextCell(vtk_face) polydata_mesh = vtk.vtkPolyData() polydata_mesh.SetPoints(points) polydata_mesh.SetPolys(cell_array) return polydata_mesh
def getMembraneVtkGrid(visMesh): assert isinstance(visMesh, VisMesh) vtkpoints = vtk.vtkPoints() for visPoint in visMesh.surfacePoints: vtkpoints.InsertNextPoint(visPoint.x, visPoint.y, visPoint.z) vtkgrid = vtk.vtkUnstructuredGrid() vtkgrid.Allocate(len(visMesh.surfacePoints), len(visMesh.surfacePoints)) vtkgrid.SetPoints(vtkpoints) if visMesh.dimension == 2: vtkline = vtk.vtkLine() lineType = vtkline.GetCellType() for line in visMesh.visLines: pts = vtk.vtkIdList() pts.InsertNextId(line.p1) pts.InsertNextId(line.p2) vtkgrid.InsertNextCell(lineType, pts) else: vtktriangle = vtk.vtkTriangle() triangleType = vtktriangle.GetCellType() for surfaceTriangle in visMesh.surfaceTriangles: pts = vtk.vtkIdList() for pi in surfaceTriangle.pointIndices: pts.InsertNextId(pi) # each triangle is a cell vtkgrid.InsertNextCell(triangleType, pts) vtkgrid.BuildLinks() return vtkgrid
def getPolyData(self, faces, vertices): points = vtk.vtkPoints() for v in vertices: points.InsertNextPoint(*v) triangles = vtk.vtkCellArray() for f in faces: triangle = vtk.vtkTriangle() for j in range(3): triangle.GetPointIds().SetId(j, int(f[j]) - 1) # fix 1based matlab index triangles.InsertNextCell(triangle) pd = vtk.vtkPolyData() pd.SetPoints(points) pd.SetPolys(triangles) # Compute surface normals for better appearance normals = vtk.vtkPolyDataNormals() normals.SetInputData(pd) normals.ConsistencyOn() normals.AutoOrientNormalsOn() normals.Update() return normals.GetOutput()
def make_poly_data(points, faces, color): vtk_points = vtk.vtkPoints() vtk_faces = vtk.vtkCellArray() colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) colors.SetName('colors') for i, p in enumerate(points): vtk_points.InsertNextPoint(p) colors.InsertNextTypedTuple(color) for i, f in enumerate(faces): triangle = vtk.vtkTriangle() triangle.GetPointIds().SetId(0, f[0]) triangle.GetPointIds().SetId(1, f[1]) triangle.GetPointIds().SetId(2, f[2]) vtk_faces.InsertNextCell(triangle) poly_data = vtk.vtkPolyData() poly_data.SetPoints(vtk_points) poly_data.SetPolys(vtk_faces) poly_data.GetPointData().SetScalars(colors) poly_data.Modified() return poly_data
def CreatePolyData( pts, faces ): """ Creates vtkPolyData from vertices and faces pts numpy.array: Nx3 array of vertices faces numpy.array: Mx3 array of faces Return vtkPolyData """ (nv,mv) = pts.shape (nf,mf) = faces.shape cells = vtk.vtkCellArray() for j in range(nf): cell = vtk.vtkTriangle() cell.GetPointIds().SetNumberOfIds(3) cell.GetPointIds().SetId( 0, faces[j,0] ) cell.GetPointIds().SetId( 1, faces[j,1] ) cell.GetPointIds().SetId( 2, faces[j,2] ) cells.InsertNextCell( cell ) points = vtk.vtkPoints() points.SetNumberOfPoints(nv) for j in range(nv): points.SetPoint( j, pts[j,0], pts[j,1], pts[j,2] ) new_mesh = vtk.vtkPolyData() new_mesh.SetPoints( points ) new_mesh.SetPolys( cells ) new_mesh.BuildCells() return new_mesh
def Gen_uGrid(new_pt, new_fc): """ Generates a vtk unstructured grid given points and triangular faces""" ints = np.ones(len(new_fc), 'int')*3 cells = np.hstack((ints.reshape(-1, 1), np.vstack(new_fc))) # Generate vtk mesh # Convert points to vtkfloat object points = np.vstack(new_pt) vtkArray = VN.numpy_to_vtk(np.ascontiguousarray(points), deep=True)#, deep=True) points = vtk.vtkPoints() points.SetData(vtkArray) # Convert to vtk arrays tritype = vtk.vtkTriangle().GetCellType()*np.ones(len(new_fc), 'int') cell_type = np.ascontiguousarray(tritype).astype('uint8') cell_type = VN.numpy_to_vtk(cell_type, deep=True) offset = np.cumsum(np.hstack(ints + 1)) offset = np.ascontiguousarray(np.delete(np.insert(offset, 0, 0), -1)).astype('int64') # shift offset = VN.numpy_to_vtkIdTypeArray(offset, deep=True) cells = np.ascontiguousarray(np.hstack(cells).astype('int64')) vtkcells = vtk.vtkCellArray() vtkcells.SetCells(cells.shape[0], VN.numpy_to_vtkIdTypeArray(cells, deep=True)) # Create unstructured grid uGrid = vtk.vtkUnstructuredGrid() uGrid.SetPoints(points) uGrid.SetCells(cell_type, offset, vtkcells) return uGrid
def _create_tecplot_shells(self, is_quads, quads, is_tris, tris): if is_quads: elements = quads for iface, face in enumerate(quads): elem = vtkQuad() epoints = elem.GetPointIds() epoints.SetId(0, face[0]) epoints.SetId(1, face[1]) epoints.SetId(2, face[2]) epoints.SetId(3, face[3]) self.grid.InsertNextCell( elem.GetCellType(), elem.GetPointIds()) #elem.GetCellType() = 5 # vtkTriangle #break if is_tris: elements = tris for iface, face in enumerate(tris): elem = vtkTriangle() epoints = elem.GetPointIds() epoints.SetId(0, face[0]) epoints.SetId(1, face[1]) epoints.SetId(2, face[2]) self.grid.InsertNextCell( 5, elem.GetPointIds()) #elem.GetCellType() = 5 # vtkTriangle
def __init__(self, filename=None, triangleList=[], color=(1,1,1) ): self.src=[] points = vtk.vtkPoints() triangles = vtk.vtkCellArray() n=0 for t in triangleList: triangle = vtk.vtkTriangle() for p in t: points.InsertNextPoint(p.x, p.y, p.z) triangle.GetPointIds().SetId(0,n) n=n+1 triangle.GetPointIds().SetId(1,n) n=n+1 triangle.GetPointIds().SetId(2,n) n=n+1 triangles.InsertNextCell(triangle) polydata= vtk.vtkPolyData() polydata.SetPoints(points) polydata.SetPolys(triangles) polydata.Modified() polydata.Update() self.src=polydata self.mapper = vtk.vtkPolyDataMapper() self.mapper.SetInput(self.src) self.SetMapper(self.mapper) self.SetColor(color)
def createPolyData(faces, vtList, verts, tcoords): points = vtk.vtkPoints() points.SetDataTypeToDouble() points.SetNumberOfPoints(len(vtList)) tcoordArray = vtk.vtkDoubleArray() tcoordArray.SetName('tcoords') tcoordArray.SetNumberOfComponents(2) tcoordArray.SetNumberOfTuples(len(vtList)) for i, vt in enumerate(vtList): vi, ti = vt xyz = verts[vi] uv = tcoords[ti] points.SetPoint(i, xyz) tcoordArray.SetTuple2(i, uv[0], uv[1]) cells = vtk.vtkCellArray() for i, face in enumerate(faces): tri = vtk.vtkTriangle() tri.GetPointIds().SetId(0, face[0]) tri.GetPointIds().SetId(1, face[1]) tri.GetPointIds().SetId(2, face[2]) cells.InsertNextCell(tri) polyData = vtk.vtkPolyData() polyData.SetPoints(points) polyData.SetPolys(cells) polyData.GetPointData().SetTCoords(tcoordArray) return polyData
def create_cell(elem): triangle = vtk.vtkTriangle() ids = triangle.GetPointIds() ids.SetId(0, elem[0]) ids.SetId(1, elem[1]) ids.SetId(2, elem[2]) return triangle
def get_polydata_from(points, tr_re): numberPoints = len(points) Points = vtkPoints() ntype = get_numpy_array_type(Points.GetDataType()) points_vtk = numpy_to_vtk(np.asarray(points, order='C',dtype=ntype), deep=1) Points.SetNumberOfPoints(numberPoints) Points.SetData(points_vtk) Triangles = vtkCellArray() for item in tr_re: Triangle = vtkTriangle() Triangle.GetPointIds().SetId(0,item[0]) Triangle.GetPointIds().SetId(1,item[1]) Triangle.GetPointIds().SetId(2,item[2]) Triangles.InsertNextCell(Triangle) polydata = vtkPolyData() polydata.SetPoints(Points) polydata.SetPolys(Triangles) polydata.Modified() polydata.Update() return polydata
def _create_cart3d_group(self, name, model, element_id): points = vtk.vtkPoints() points.SetNumberOfPoints(self.nNodes) nelements = len(element_id) self.grid.Allocate(nelements, 1000) nodes = self.model.get_nodes_associated_with_elements(element_id) nodes.sort() nid = 0 all_nodes = self.nodes for i in all_nodes: #if nid in nodes: points.InsertPoint(nid, all_nodes[i, :]) nid += 1 from vtk import vtkTriangle for eid in element_id: elem = vtkTriangle() node_ids = elements[eid, :] elem_nodes = searchsorted(nodes, node_ids) elem.GetPointIds().SetId(0, elem_nodes[0]) elem.GetPointIds().SetId(1, elem_nodes[1]) elem.GetPointIds().SetId(2, elem_nodes[2]) self.grid.InsertNextCell(5, elem.GetPointIds()) self.grid[name].SetPoints(points) self.grid[name].Modified() self.grid[name].Update()
def main(): filenames = list() uGrids = list() uGrids.append(MakeUnstructuredGrid(vtk.vtkVertex())) filenames.append('Vertex.vtu') uGrids.append(MakePolyVertex()) filenames.append('PolyVertex.vtu') uGrids.append(MakeUnstructuredGrid(vtk.vtkLine())) filenames.append('Line.vtu') uGrids.append(MakePolyLine()) filenames.append('PolyLine.vtu') uGrids.append(MakeUnstructuredGrid(vtk.vtkTriangle())) filenames.append('Triangle.vtu') uGrids.append(MakeTriangleStrip()) filenames.append('TriangleStrip.vtu') uGrids.append(MakePolygon()) filenames.append('Polygon.vtu') uGrids.append(MakeUnstructuredGrid(vtk.vtkPixel())) filenames.append('Pixel.vtu') uGrids.append(MakeUnstructuredGrid(vtk.vtkQuad())) filenames.append('Quad.vtu') uGrids.append(MakeUnstructuredGrid(vtk.vtkTetra())) filenames.append('Tetra.vtu') uGrids.append(MakeUnstructuredGrid(vtk.vtkVoxel())) filenames.append('Voxel.vtu') uGrids.append(MakeUnstructuredGrid(vtk.vtkHexahedron())) filenames.append('Hexahedron.vtu') uGrids.append(MakeUnstructuredGrid(vtk.vtkWedge())) filenames.append('Wedge.vtu') uGrids.append(MakeUnstructuredGrid(vtk.vtkPyramid())) filenames.append('Pyramid.vtu') uGrids.append(MakeUnstructuredGrid(vtk.vtkPentagonalPrism())) filenames.append('PentagonalPrism.vtu') uGrids.append(MakeUnstructuredGrid(vtk.vtkHexagonalPrism())) filenames.append('HexagonalPrism.vtu') # Write each grid into a file for i in range(0, len(uGrids)): print('Writing: ', filenames[i]) writer = vtk.vtkXMLDataSetWriter() writer.SetFileName(filenames[i]) writer.SetInputData(uGrids[i]) writer.Write()
def add_user_geometry(alt_grid: vtk.vtkUnstructuredGrid, geom_grid: vtk.vtkUnstructuredGrid, xyz: np.ndarray, nid_map: Dict[int, int], nnodes: int, bars: np.ndarray, tris: np.ndarray, quads: np.ndarray, nelements: int, nbars: int, ntris: int, nquads: int) -> vtk.vtkPoints: """helper method for ``_add_user_geometry``""" # set points points = numpy_to_vtk_points(xyz, dtype='<f') if nelements > 0: for i in range(nnodes): elem = vtk.vtkVertex() elem.GetPointIds().SetId(0, i) alt_grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) geom_grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) else: for i in range(nnodes): elem = vtk.vtkVertex() elem.GetPointIds().SetId(0, i) alt_grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) if nbars: for i, bar in enumerate(bars[:, 1:]): g1 = nid_map[bar[0]] g2 = nid_map[bar[1]] elem = vtk.vtkLine() elem.GetPointIds().SetId(0, g1) elem.GetPointIds().SetId(1, g2) geom_grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) if ntris: for i, tri in enumerate(tris[:, 1:]): g1 = nid_map[tri[0]] g2 = nid_map[tri[1]] g3 = nid_map[tri[2]] elem = vtk.vtkTriangle() elem.GetPointIds().SetId(0, g1) elem.GetPointIds().SetId(1, g2) elem.GetPointIds().SetId(2, g3) geom_grid.InsertNextCell(5, elem.GetPointIds()) if nquads: for i, quad in enumerate(quads[:, 1:]): g1 = nid_map[quad[0]] g2 = nid_map[quad[1]] g3 = nid_map[quad[2]] g4 = nid_map[quad[3]] elem = vtk.vtkQuad() point_ids = elem.GetPointIds() point_ids.SetId(0, g1) point_ids.SetId(1, g2) point_ids.SetId(2, g3) point_ids.SetId(3, g4) geom_grid.InsertNextCell(9, elem.GetPointIds()) alt_grid.SetPoints(points) if nelements > 0: geom_grid.SetPoints(points) return points
def main(): filenames = list() uGrids = list() uGrids.append(MakeUnstructuredGrid(vtk.vtkVertex())) filenames.append("Vertex.vtk") uGrids.append(MakePolyVertex()) filenames.append("PolyVertex.vtk") uGrids.append(MakeUnstructuredGrid(vtk.vtkLine())) filenames.append("Line.vtk") uGrids.append(MakePolyLine()) filenames.append("PolyLine.vtk") uGrids.append(MakeUnstructuredGrid(vtk.vtkTriangle())) filenames.append("Triangle.vtk") uGrids.append(MakeTriangleStrip()) filenames.append("TriangleStrip.vtk") uGrids.append(MakePolygon()) filenames.append("Polygon.vtk") uGrids.append(MakeUnstructuredGrid(vtk.vtkPixel())) filenames.append("Pixel.vtk") uGrids.append(MakeUnstructuredGrid(vtk.vtkQuad())) filenames.append("Quad.vtk") uGrids.append(MakeUnstructuredGrid(vtk.vtkTetra())) filenames.append("Tetra.vtk") uGrids.append(MakeUnstructuredGrid(vtk.vtkVoxel())) filenames.append("Voxel.vtk") uGrids.append(MakeUnstructuredGrid(vtk.vtkHexahedron())) filenames.append("Hexahedron.vtk") uGrids.append(MakeUnstructuredGrid(vtk.vtkWedge())) filenames.append("Wedge.vtk") uGrids.append(MakeUnstructuredGrid(vtk.vtkPyramid())) filenames.append("Pyramid.vtk") uGrids.append(MakeUnstructuredGrid(vtk.vtkPentagonalPrism())) filenames.append("PentagonalPrism.vtk") uGrids.append(MakeUnstructuredGrid(vtk.vtkHexagonalPrism())) filenames.append("HexagonalPrism.vtk") # Write each grid into a file for i in range(0, len(uGrids)): print("Writing: ", filenames[i]) writer = vtk.vtkUnstructuredGridWriter() writer.SetFileName(filenames[i]) writer.SetInputData(uGrids[i]) writer.Write()
def save_frame_depth(self, path): #setup camera camera = vtkCamera() camera.SetPosition(self.cx, self.cy, self.cz) camera.SetFocalPoint(self.fx, self.fy, self.fz) camera.SetViewUp(self.ux, self.uy, self.uz) camera.SetViewAngle(self.fovy) #setup renderer renderer = vtkRenderer() renderWindow = vtkRenderWindow() renderWindow.SetOffScreenRendering(1) renderWindow.AddRenderer(renderer) renderWindow.SetSize(self.w, self.h) for i in xrange(-1, self.expert.nr_obstacles_c()): vss, nss, iss = self.save_frame_mesh(i) #geometry pts = vtkPoints() for i in xrange(len(vss)): pts.InsertNextPoint(vss[i][0], vss[i][1], vss[i][2]) tris = vtkCellArray() for i in xrange(len(iss)): triangle = vtkTriangle() triangle.GetPointIds().SetId(0, iss[i][0]) triangle.GetPointIds().SetId(1, iss[i][1]) triangle.GetPointIds().SetId(2, iss[i][2]) tris.InsertNextCell(triangle) poly = vtkPolyData() poly.SetPoints(pts) poly.SetPolys(tris) #actor mapper = vtkPolyDataMapper() mapper.SetInput(poly) actor = vtkActor() actor.SetMapper(mapper) renderer.AddActor(actor) renderer.SetBackground(self.bk_r, self.bk_g, self.bk_b) renderer.SetActiveCamera(camera) renderWindow.Render() #output options windowToImageFilter = vtkWindowToImageFilter() windowToImageFilter.SetInput(renderWindow) windowToImageFilter.SetMagnification(1) windowToImageFilter.SetInputBufferTypeToZBuffer() #Extract z buffer value windowToImageFilter.Update() #scale and shift scale = vtkImageShiftScale() scale.SetOutputScalarTypeToUnsignedChar() scale.SetInputConnection(windowToImageFilter.GetOutputPort()) scale.SetShift(0) scale.SetScale(-255) #output writer = vtkBMPWriter() writer.SetFileName(path) writer.SetInputConnection(scale.GetOutputPort()) writer.Write()
def create_single_legend_actor(color, line_style): points = vtk.vtkPoints() raw_points = [ [0, 0], [1, 0], [0, 0.25], [1, 0.25], [0, 0.5], [1, 0.5], [0, 0.75], [1, 0.75], [0, 1], [1, 1], [0.5, 1], [0.5, 0] ] for point in raw_points: points.InsertNextPoint([ point[1], point[0], 1.0 ]) p1 = [ [0, 2, 3], [0, 3, 1] ] p2 = [ [2, 4, 5], [2, 5, 3] ] p3 = [ [4, 6, 7], [4, 7, 5] ] p4 = [ [6, 8, 9], [6, 9, 7] ] triangles_raw = [ [0, 10, 11], [0, 9, 10] ] triangles_raw += p1 + p2 + p3 + p4 if line_style == 0xF0F0: triangles_raw = p1 + p3 elif line_style == 0xFF00: triangles_raw = p1 + p2 elif line_style == 0x000F: triangles_raw = p4 triangles = vtk.vtkCellArray() for t in triangles_raw: triangle = vtk.vtkTriangle() triangle.GetPointIds().SetId(0, t[0]) triangle.GetPointIds().SetId(1, t[1]) triangle.GetPointIds().SetId(2, t[2]) triangles.InsertNextCell(triangle) polydata = vtk.vtkPolyData() polydata.SetPoints(points) polydata.SetPolys(triangles) return polydata
def add_triangle(self, neighbors, color, center=None, opacity=0.4, draw_edges=False, edges_color=[0.0, 0.0, 0.0], edges_linewidth=2): """ Adds a triangular surface between three atoms. Args: atoms: Atoms between which a triangle will be drawn. color: Color for triangle as RGB. center: The "central atom" of the triangle opacity: opacity of the triangle draw_edges: If set to True, the a line will be drawn at each edge edges_color: Color of the line for the edges edges_linewidth: Width of the line drawn for the edges """ points = vtk.vtkPoints() triangle = vtk.vtkTriangle() for ii in range(3): points.InsertNextPoint(neighbors[ii].x, neighbors[ii].y, neighbors[ii].z) triangle.GetPointIds().SetId(ii, ii) triangles = vtk.vtkCellArray() triangles.InsertNextCell(triangle) # polydata object trianglePolyData = vtk.vtkPolyData() trianglePolyData.SetPoints(points) trianglePolyData.SetPolys(triangles) # mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInput(trianglePolyData) ac = vtk.vtkActor() ac.SetMapper(mapper) ac.GetProperty().SetOpacity(opacity) if color == 'element': if center is None: raise ValueError( 'Color should be chosen according to the central atom, ' 'and central atom is not provided') # If partial occupations are involved, the color of the specie with # the highest occupation is used myoccu = 0.0 for specie, occu in center.species.items(): if occu > myoccu: myspecie = specie myoccu = occu color = [i / 255 for i in self.el_color_mapping[myspecie.symbol]] ac.GetProperty().SetColor(color) else: ac.GetProperty().SetColor(color) if draw_edges: ac.GetProperty().SetEdgeColor(edges_color) ac.GetProperty().SetLineWidth(edges_linewidth) ac.GetProperty().EdgeVisibilityOn() self.ren.AddActor(ac)
def add_triangle(self, neighbors, color, center=None, opacity=0.4, draw_edges=False, edges_color=[0.0, 0.0, 0.0], edges_linewidth=2): """ Adds a triangular surface between three atoms. Args: atoms: Atoms between which a triangle will be drawn. color: Color for triangle as RGB. center: The "central atom" of the triangle opacity: opacity of the triangle draw_edges: If set to True, the a line will be drawn at each edge edges_color: Color of the line for the edges edges_linewidth: Width of the line drawn for the edges """ points = vtk.vtkPoints() triangle = vtk.vtkTriangle() for ii in range(3): points.InsertNextPoint(neighbors[ii].x, neighbors[ii].y, neighbors[ii].z) triangle.GetPointIds().SetId(ii, ii) triangles = vtk.vtkCellArray() triangles.InsertNextCell(triangle) # polydata object trianglePolyData = vtk.vtkPolyData() trianglePolyData.SetPoints( points ) trianglePolyData.SetPolys( triangles ) # mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInput(trianglePolyData) ac = vtk.vtkActor() ac.SetMapper(mapper) ac.GetProperty().SetOpacity(opacity) if color == 'element': if center is None: raise ValueError( 'Color should be chosen according to the central atom, ' 'and central atom is not provided') # If partial occupations are involved, the color of the specie with # the highest occupation is used myoccu = 0.0 for specie, occu in center.species_and_occu.items(): if occu > myoccu: myspecie = specie myoccu = occu color = [i / 255 for i in self.el_color_mapping[myspecie.symbol]] ac.GetProperty().SetColor(color) else: ac.GetProperty().SetColor(color) if draw_edges: ac.GetProperty().SetEdgeColor(edges_color) ac.GetProperty().SetLineWidth(edges_linewidth) ac.GetProperty().EdgeVisibilityOn() self.ren.AddActor(ac)
def meshToUnstructeredGrid(mesh): """Converts a FiPy mesh structure to a vtkUnstructuredGrid. Works for 2D and 3D meshes. Args: mesh (fipy.GmshImporter3D): Some Fipy mesh object. Returns: vtk.vtkUnstructuredGrid """ # Get vertex coordinates coords=mesh.vertexCoords if len(coords)==2: x,y=coords dim=2 else: x,y,z=coords dim=3 # Insert them as points points = vtk.vtkPoints() for i in range(len(x)): if dim==2: points.InsertNextPoint(x[i], y[i],0) else: points.InsertNextPoint(x[i], y[i],z[i]) # Insert tetrahedrons verts=mesh._getOrderedCellVertexIDs().T cellArray = vtk.vtkCellArray() for j,vert in enumerate(verts): if dim==3: tetra = vtk.vtkTetra() else: tetra = vtk.vtkTriangle() for i,v in enumerate(vert): tetra.GetPointIds().SetId(i, v) cellArray.InsertNextCell(tetra) # Grid grid = vtk.vtkUnstructuredGrid() grid.SetPoints(points) if dim==3: grid.SetCells(vtk.VTK_TETRA, cellArray) else: grid.SetCells(vtk.VTK_TRIANGLE, cellArray) return grid
def __init__(self): super(Tria3, self).__init__() self.vtk_cell = vtk.vtkTriangle() self.point_ids = self.vtk_cell.GetPointIds() self.nodes = None self.center = None self.order = None self.id = None
def createPlaneActor2(): xsize = params.PlaneXSize ysize = params.PlaneYSize center = params.PlaneCenter points = vtk.vtkPoints() points.InsertNextPoint( (center[0] - xsize / 2, center[1] - ysize / 2, center[2] - 0.1)) points.InsertNextPoint( (center[0] + xsize / 2, center[1] - ysize / 2, center[2] - 0.1)) points.InsertNextPoint( (center[0] + xsize / 2, center[1] + ysize / 2, center[2] - 0.1)) points.InsertNextPoint( (center[0] - xsize / 2, center[1] + ysize / 2, center[2] - 0.1)) triangle = vtk.vtkTriangle() triangle.GetPointIds().SetId(0, 0) triangle.GetPointIds().SetId(1, 1) triangle.GetPointIds().SetId(2, 2) triangle2 = vtk.vtkTriangle() triangle2.GetPointIds().SetId(0, 2) triangle2.GetPointIds().SetId(1, 3) triangle2.GetPointIds().SetId(2, 0) triangles = vtk.vtkCellArray() triangles.InsertNextCell(triangle) triangles.InsertNextCell(triangle2) colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) colors.SetName("Colors") colors.InsertNextTuple3(255, 0, 0) colors.InsertNextTuple3(0, 255, 0) colors.InsertNextTuple3(0, 0, 255) colors.InsertNextTuple3(0, 255, 0) trianglePolyData = vtk.vtkPolyData() trianglePolyData.SetPoints(points) trianglePolyData.SetPolys(triangles) trianglePolyData.GetPointData().SetScalars(colors) return build_actor(trianglePolyData, True)
def AddTriangle(p1, p2, p3): Draw.vtkpoints.InsertNextPoint(*p1) Draw.vtkpoints.InsertNextPoint(*p2) Draw.vtkpoints.InsertNextPoint(*p3) Draw.top += 3 triangle = vtk.vtkTriangle() triangle.GetPointIds().SetId(0, Draw.top - 1) triangle.GetPointIds().SetId(1, Draw.top - 2) triangle.GetPointIds().SetId(2, Draw.top - 3) Draw.vtktriangles.InsertNextCell(triangle)
def meshToUnstructeredGrid(mesh): """Converts a FiPy mesh structure to a vtkUnstructuredGrid. Works for 2D and 3D meshes. Args: mesh (fipy.GmshImporter3D): Some Fipy mesh object. Returns: vtk.vtkUnstructuredGrid """ # Get vertex coordinates coords = mesh.vertexCoords if len(coords) == 2: x, y = coords dim = 2 else: x, y, z = coords dim = 3 # Insert them as points points = vtk.vtkPoints() for i in range(len(x)): if dim == 2: points.InsertNextPoint(x[i], y[i], 0) else: points.InsertNextPoint(x[i], y[i], z[i]) # Insert tetrahedrons verts = mesh._getOrderedCellVertexIDs().T cellArray = vtk.vtkCellArray() for j, vert in enumerate(verts): if dim == 3: tetra = vtk.vtkTetra() else: tetra = vtk.vtkTriangle() for i, v in enumerate(vert): tetra.GetPointIds().SetId(i, v) cellArray.InsertNextCell(tetra) # Grid grid = vtk.vtkUnstructuredGrid() grid.SetPoints(points) if dim == 3: grid.SetCells(vtk.VTK_TETRA, cellArray) else: grid.SetCells(vtk.VTK_TRIANGLE, cellArray) return grid
def trim_mesh_with_cone(mesh, cone_point, cone_normal, cone_radius): """ returns a mesh that contains only the triangles that where inside of the cone """ cone_end = cone_point + cone_normal*100.0 sq_radius = cone_radius*cone_radius w = cone_point v = cone_end n = w - v v_w_sq_len = dist2(v, w) points = mesh.GetPoints().GetData() cell_array = mesh.GetPolys() polygons = cell_array.GetData() triangles = vtk.vtkCellArray() for i in xrange(0, cell_array.GetNumberOfCells()): triangle = [polygons.GetValue(j) for j in xrange(i*4+1, i*4+4)] p = points.GetTuple(triangle[0]) delta = p - (v + (((p - v).dot(n)) / v_w_sq_len) * n) if delta.dot(delta) > sq_radius: continue p = points.GetTuple(triangle[1]) delta = p - (v + (((p - v).dot(n)) / v_w_sq_len) * n) if delta.dot(delta) > sq_radius: continue p = points.GetTuple(triangle[2]) delta = p - (v + (((p - v).dot(n)) / v_w_sq_len) * n) if delta.dot(delta) > sq_radius: continue cell = vtk.vtkTriangle() pointIds = cell.GetPointIds() pointIds.SetId(0, triangle[0]) pointIds.SetId(1, triangle[1]) pointIds.SetId(2, triangle[2]) triangles.InsertNextCell(cell) # Create a polydata object trianglePolyData = vtk.vtkPolyData() # Add the geometry and topology to the polydata trianglePolyData.SetPoints(mesh.GetPoints()) trianglePolyData.SetPolys(triangles) trianglePolyData.Update() #run the clean function here to remove the points that are not used cleanPolyData = vtk.vtkCleanPolyData() cleanPolyData.SetInput(trianglePolyData) cleanPolyData.Update() trimmed_mesh = cleanPolyData.GetOutput() return trimmed_mesh
def Vtk_cell_types(): vtk_types = [ ] #(vtk_type, vtk_id, vtkCell) <= linear cell types found in VTK vtk_types.append(("VTK_TRIANGLE", 5, vtk.vtkTriangle())) vtk_types.append(("VTK_QUAD", 9, vtk.vtkQuad())) vtk_types.append(("VTK_TETRA", 10, vtk.vtkTetra())) vtk_types.append(("VTK_PYRAMID", 14, vtk.vtkPyramid())) vtk_types.append(("VTK_WEDGE", 13, vtk.vtkWedge())) vtk_types.append(("VTK_HEXAHEDRON", 12, vtk.vtkHexahedron())) return vtk_types
def defineMesh(self,nodes,elements): self._points = vtk.vtkPoints() self._triangles = vtk.vtkCellArray() for i in range(len(nodes)): self._points.InsertNextPoint(nodes[i].x(),nodes[i].y(),0.) for el in elements: tri = vtk.vtkTriangle() conn = el.connectivite() for ii,n in enumerate(conn): tri.GetPointIds().SetId(ii,n) self._triangles.InsertNextCell(tri)
def RenderTriangleAsPolygon(points, triangleNumber): print '* * * RenderTriangle: ', triangleNumber print 'Triangle points: ', tri p_triangles.InsertNextPoint(points[0]) p_triangles.InsertNextPoint(points[1]) p_triangles.InsertNextPoint(points[2]) triangle = vtk.vtkTriangle(); triangle.GetPointIds().SetId(0, 0+(triangleNumber-1)*3); triangle.GetPointIds().SetId(1, 1+(triangleNumber-1)*3); triangle.GetPointIds().SetId(2, 2+(triangleNumber-1)*3); triangles.InsertNextCell(triangle);
def defineMesh(self, nodes, elements): self._points = vtk.vtkPoints() self._triangles = vtk.vtkCellArray() for i in range(len(nodes)): self._points.InsertNextPoint(nodes[i].x(), nodes[i].y(), 0.) for el in elements: tri = vtk.vtkTriangle() conn = el.connectivite() for ii, n in enumerate(conn): tri.GetPointIds().SetId(ii, n) self._triangles.InsertNextCell(tri)
def create_surface_triangles(self, simpleces): Triangles = vtk.vtkCellArray() Triangle = vtk.vtkTriangle() for s in simpleces: Triangle.GetPointIds().SetId(0, s[0]) Triangle.GetPointIds().SetId(1, s[1]) Triangle.GetPointIds().SetId(2, s[2]) Triangles.InsertNextCell(Triangle) return Triangles
def mesh_from_arcs(arcs): #create all of the points so they have sensible, shared indices points = vtk.vtkPoints() num_points_in_arc = len(arcs[0]) for i in range(0, len(arcs)): arc = arcs[i] assert len(arc) == num_points_in_arc, "All arcs must be the same length" for j in range(0, len(arc)): point = arc[j] points.InsertNextPoint(point[0], point[1], point[2]) # Build the meshgrid manually triangles = vtk.vtkCellArray() for i in range(1, len(arcs)): for j in range(0, len(arc)-1): triangle = vtk.vtkTriangle() pointIds = triangle.GetPointIds() pointIds.SetId(0, i * num_points_in_arc + j) pointIds.SetId(1, i * num_points_in_arc + j + 1) pointIds.SetId(2, (i-1) * num_points_in_arc + j + 1) triangles.InsertNextCell(triangle) triangle = vtk.vtkTriangle() pointIds = triangle.GetPointIds() pointIds.SetId(0, i * num_points_in_arc + j) pointIds.SetId(1, (i-1) * num_points_in_arc + j + 1) pointIds.SetId(2, (i-1) * num_points_in_arc + j) triangles.InsertNextCell(triangle) # Create a polydata object trianglePolyData = vtk.vtkPolyData() # Add the geometry and topology to the polydata trianglePolyData.SetPoints(points) trianglePolyData.SetPolys(triangles) trianglePolyData.Update() return trianglePolyData
def to_vtk(vertices, simplices=None): ''' Creates a VTK mesh (vtkPolyData object) from a given point set utilizing Delaunay triangulation in the first place. Arguments: vertices: pandas DataFrame of xyz coordinates simplices: pandas DataFrame of simplices from Delaunay triangulation, if None basic triangulation will be performed Returns: polydata: vtkPolyData object which serves as input for subsequent vtk simplification / decimation operations ''' if simplices is None: ## Delaunay # triangulation = Delaunay(vertices.iloc[:,:2].values) # simplices = triangulation.simplices simplices = triangulate(vertices) else: simplices = simplices ## VTK polygons # initiate points and read vertices points = vtkPoints() for p in vertices.values: points.InsertNextPoint(p) # initiate triangles and read simplices # Unfortunately in this simple example the following lines are ambiguous. # The first 0 is the index of the triangle vertex which is ALWAYS 0-2. # The second 0 is the index into the point (geometry) array, so this can range from 0-(NumPoints-1) # i.e. a more general statement is triangle->GetPointIds()->SetId(0, PointId); triangle = vtkTriangle() triangles = vtkCellArray() for i in simplices.values: triangle.GetPointIds().SetId(0, i[0]) triangle.GetPointIds().SetId(1, i[1]) triangle.GetPointIds().SetId(2, i[2]) triangles.InsertNextCell(triangle) # combine in PolyData object polydata = vtkPolyData() polydata.SetPoints(points) polydata.SetPolys(triangles) # check polydata.Modified() return polydata
def vtk_cells(t): """ Creates vtkCells from an numpy array """ cellArray = vtk.vtkCellArray() for vert in t: if t.shape[1] == 2: tetra = vtk.vtkLine() if t.shape[1] == 3: tetra = vtk.vtkTriangle() elif t.shape[1] == 4: tetra = vtk.vtkTetra() for i, v in enumerate(vert): tetra.GetPointIds().SetId(i, int(v)) cellArray.InsertNextCell(tetra) return cellArray
def CalculateManifold(polydata, resolution=1000): #Get Vertex and Face Array nPoints = polydata.GetNumberOfPoints() nFaces = polydata.GetNumberOfCells() v = [] f = [] for i in range(nPoints): v.append(polydata.GetPoint(i)) for i in range(nFaces): cell = polydata.GetCell(i) cell.GetPointId(0) f.append([cell.GetPointId(0), cell.GetPointId(1), cell.GetPointId(2)]) v = np.array(v) f = np.array(f) #Calculate calculated = lib.Calculate(v.ctypes.data_as(POINTER(c_double)), v.size, f.ctypes.data_as(POINTER(c_int)), f.size, c_int(resolution)) vertices = np.array(calculated['vertices']) vertices = vertices.reshape(int(vertices.size / 3), 3) faces = np.array(calculated['faces']) faces = faces.reshape(int(faces.size / 3), 3) result = vtk.vtkPolyData() points = vtk.vtkPoints() points.SetNumberOfPoints(vertices.shape[0]) for i in range(vertices.shape[0]): points.SetPoint(i, vertices[i]) result.SetPoints(points) cells = vtk.vtkCellArray() for i in range(faces.shape[0]): cell = vtk.vtkTriangle() cell.GetPointIds().SetId(0, faces[i][0]) cell.GetPointIds().SetId(1, faces[i][1]) cell.GetPointIds().SetId(2, faces[i][2]) cells.InsertNextCell(cell) result.SetPolys(cells) return result
def interpolate(self, x, y, z): aCell = vtk.vtkTriangle() pcoords = [0, 0, 0] weights = [0, 0, 0] cid = self.loc.FindCell((x, y, z)) if cid > -1: aCell = self.pd2.GetCell(cid) pts = [(aCell.GetPoints().GetPoint(k)[0], aCell.GetPoints().GetPoint(k)[1]) for k in range(3)] res = aCell.BarycentricCoords((x, y), pts[0], pts[1], pts[2], pcoords) v = [self.values[aCell.GetPointId(k)] for k in range(3)] return sum([pcoords[kk] * v[kk] for kk in range(3)])
def _polydata(self, inflated=False): """ Compute a vtk polydata of the TriSurface. This code uses vtk. Parameters ---------- inflated: bool (optional, default False) If True use the inflated vertices. Returns ------- polydata: vtkPolyData the TriSurface vtk polydata. """ import vtk # Select the vertices to use labels = copy.deepcopy(self.labels) if inflated: vertices = self.inflated_vertices else: vertices = self.vertices # First setup points, triangles and colors. vtk_points = vtk.vtkPoints() vtk_triangles = vtk.vtkCellArray() vtk_colors = vtk.vtkUnsignedCharArray() vtk_colors.SetNumberOfComponents(1) nb_of_labels = len(set(self.labels)) labels[numpy.where(labels < 0)] = 0 for index in range(len(vertices)): vtk_points.InsertNextPoint(vertices[index]) vtk_colors.InsertNextTuple1(labels[index]) for triangle in self.triangles: vtk_triangle = vtk.vtkTriangle() vtk_triangle.GetPointIds().SetId(0, triangle[0]) vtk_triangle.GetPointIds().SetId(1, triangle[1]) vtk_triangle.GetPointIds().SetId(2, triangle[2]) vtk_triangles.InsertNextCell(vtk_triangle) # Create (geometry and topology) the associated polydata polydata = vtk.vtkPolyData() polydata.SetPoints(vtk_points) polydata.GetPointData().SetScalars(vtk_colors) polydata.SetPolys(vtk_triangles) return polydata
def GetVtkPoly(self, fid, fdata, n, bytesMirrored, type): geo = [] pid = [] fill, out, trans, multi = ReadFlags(fid, fdata) for i in range(0, n): geo.append(ReadFloats(fid, fdata, np.float32, 3, bytesMirrored)) color, tr = ReadColorAndTrans(fid, fdata, fill, out, multi, trans, n, bytesMirrored) for i in range(0, n): pid.append(self.points.InsertNextPoint(geo[i])) if multi: t = [color[i][0]] self.temps.InsertNextTypedTuple(t) col = tuple(color[i]) self.colors.InsertNextTypedTuple(col) else: t = [color[0][0]] self.temps.InsertNextTypedTuple(t) col = tuple(color[0]) self.colors.InsertNextTypedTuple(col) if type == 'P': return pid[0] elif type == 'L': line = vtk.vtkLine() line.GetPointIds().SetId(0, pid[0]) line.GetPointIds().SetId(1, pid[1]) return line elif type == 'T': tri = vtk.vtkTriangle() tri.GetPointIds().SetId(0, pid[0]) tri.GetPointIds().SetId(1, pid[1]) tri.GetPointIds().SetId(2, pid[2]) return tri elif type == 'Q': quad = vtk.vtkQuad() quad.GetPointIds().SetId(0, pid[0]) quad.GetPointIds().SetId(1, pid[1]) quad.GetPointIds().SetId(2, pid[2]) quad.GetPointIds().SetId(3, pid[3]) return quad
def buildPolyData(vertices, faces=None, indexOffset=0): ''' Build a ``vtkPolyData`` object from a list of vertices where faces represents the connectivity of the polygonal mesh. E.g. : - ``vertices=[[x1,y1,z1],[x2,y2,z2], ...]`` - ``faces=[[0,1,2], [1,2,3], ...]`` Use ``indexOffset=1`` if face numbering starts from 1 instead of 0. .. hint:: Example: `buildpolydata.py <https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/buildpolydata.py>`_ .. image:: https://user-images.githubusercontent.com/32848391/51032546-bf4dac00-15a0-11e9-9e1e-035fff9c05eb.png ''' sourcePoints = vtk.vtkPoints() sourceVertices = vtk.vtkCellArray() sourcePolygons = vtk.vtkCellArray() for pt in vertices: if len(pt) > 2: aid = sourcePoints.InsertNextPoint(pt[0], pt[1], pt[2]) else: aid = sourcePoints.InsertNextPoint(pt[0], pt[1], 0) sourceVertices.InsertNextCell(1) sourceVertices.InsertCellPoint(aid) if faces: for f in faces: n = len(f) if n == 4: plg = vtk.vtkTetra() elif n == 3: plg = vtk.vtkTriangle() else: plg = vtk.vtkPolygon() plg.GetPointIds().SetNumberOfIds(n) for i in range(n): plg.GetPointIds().SetId(i, f[i] - indexOffset) sourcePolygons.InsertNextCell(plg) poly = vtk.vtkPolyData() poly.SetPoints(sourcePoints) poly.SetVerts(sourceVertices) if faces: poly.SetPolys(sourcePolygons) clp = vtk.vtkCleanPolyData() clp.SetInputData(poly) clp.PointMergingOn() clp.Update() return clp.GetOutput()
def getVtkUnstructuredGrid(self): tPts = vtk.vtkPoints() ugrid = vtk.vtkUnstructuredGrid() tPts.SetNumberOfPoints(self.nodes.shape[0]) for n in np.arange(self.nodes.shape[0]): tPts.InsertPoint(n, self.nodes[n, 0], self.nodes[n, 1], self.nodes[n, 2]) ugrid.SetPoints(tPts) tri = vtk.vtkTriangle() for n in np.arange(self.cells.shape[0]): tri.GetPointIds().SetId(0, self.cells[n, 0]) tri.GetPointIds().SetId(1, self.cells[n, 1]) tri.GetPointIds().SetId(2, self.cells[n, 2]) ugrid.InsertNextCell(tri.GetCellType(), tri.GetPointIds()) return ugrid
def initTriangles(self): """Sets up triangles describing mesh.""" verts = self.embryo.simulation.mesh.mesh._getOrderedCellVertexIDs().T cellArray = vtk.vtkCellArray() for j, vert in enumerate(verts): tetra = vtk.vtkTriangle() for i, v in enumerate(vert): tetra.GetPointIds().SetId(i, v) cellArray.InsertNextCell(tetra) self.grid.SetCells(vtk.VTK_TRIANGLE, cellArray)
def buildFullVTKGrid(self): # Create the points for VTK points = vtk.vtkPoints() for i in range(0, len(self.mesh.coords) / 3): p = self.mesh.coords[(i * 3):(i * 3 + 3)] points.InsertNextPoint(p) #add the points and cells to unstructured grid vtkgrid = vtk.vtkUnstructuredGrid() vtkgrid.SetPoints(points) #add the VTK elements to the mesh for element in self.mesh.elements: type = element.getType() nodes = element.nodes cell = vtk.vtkTriangle() if type == eTypes.TRI: cell = vtk.vtkTriangle() elif type == eTypes.QUAD: cell = vtk.vtkQuad() elif type == eTypes.TET: cell = vtk.vtkTetra() elif type == eTypes.PYRAMID: cell = vtk.vtkPyramid() elif type == eTypes.PRISM: cell = vtk.vtkWedge() #prism elif type == eTypes.HEX: cell = vtk.vtkHexahedron() else: raise # throw an exception j = 0 for n in nodes: cell.GetPointIds().SetId(j, n) j = j + 1 vtkgrid.InsertNextCell(cell.GetCellType(), cell.GetPointIds()) return vtkgrid
def vtk_cells(t): """ creates vtkCells from an numpy array @param t, currently vtkLine, vtkTriangle, andn vtkTetra are implemented""" cellArray = vtk.vtkCellArray() for vert in t: if t.shape[1] == 2: tetra = vtk.vtkLine() if t.shape[1] == 3: tetra = vtk.vtkTriangle() elif t.shape[1] == 4: tetra = vtk.vtkTetra() for i, v in enumerate(vert): tetra.GetPointIds().SetId(i, int(v)) cellArray.InsertNextCell(tetra) return cellArray
def buildFullVTKGrid(self): # Create the points for VTK points = vtk.vtkPoints() for i in range(0, len(self.mesh.coords)/3): p = self.mesh.coords[(i*3):(i*3+3)] points.InsertNextPoint(p) #add the points and cells to unstructured grid vtkgrid = vtk.vtkUnstructuredGrid() vtkgrid.SetPoints(points) #add the VTK elements to the mesh for element in self.mesh.elements: type = element.getType() nodes = element.nodes cell = vtk.vtkTriangle() if type == eTypes.TRI: cell = vtk.vtkTriangle() elif type == eTypes.QUAD: cell = vtk.vtkQuad() elif type == eTypes.TET: cell = vtk.vtkTetra() elif type == eTypes.PYRAMID: cell = vtk.vtkPyramid() elif type == eTypes.PRISM: cell = vtk.vtkWedge() #prism elif type == eTypes.HEX: cell = vtk.vtkHexahedron() else: raise # throw an exception j = 0 for n in nodes: cell.GetPointIds().SetId(j,n) j = j+1 vtkgrid.InsertNextCell(cell.GetCellType(), cell.GetPointIds()) return vtkgrid
def getVtkUnstructuredGrid(self): tPts = vtk.vtkPoints() ugrid = vtk.vtkUnstructuredGrid() tPts.SetNumberOfPoints(self.nodes.shape[0]) for n in np.arange(self.nodes.shape[0]): tPts.InsertPoint(n, self.nodes[n,0], self.nodes[n,1], self.nodes[n,2]) ugrid.SetPoints(tPts) tri = vtk.vtkTriangle() for n in np.arange(self.cells.shape[0]): tri.GetPointIds().SetId(0, self.cells[n,0]) tri.GetPointIds().SetId(1, self.cells[n,1]) tri.GetPointIds().SetId(2, self.cells[n,2]) ugrid.InsertNextCell( tri.GetCellType(), tri.GetPointIds() ) return ugrid
def _polydata(self, inflated=False): """ Compute a vtk polydata of the TriSurface. This code uses vtk. Parameters ---------- inflated: bool (optional, default False) If True use the inflated vertices. Returns ------- polydata: vtkPolyData the TriSurface vtk polydata. """ # Import here since vtk is not required by the package import vtk # Select the vertices to use labels = copy.deepcopy(self.labels) if inflated: vertices = self.inflated_vertices else: vertices = self.vertices # First setup points, triangles and colors. vtk_points = vtk.vtkPoints() vtk_triangles = vtk.vtkCellArray() vtk_colors = vtk.vtkUnsignedCharArray() vtk_colors.SetNumberOfComponents(1) labels[numpy.where(labels < 0)] = 0 for index in range(len(vertices)): vtk_points.InsertNextPoint(vertices[index]) vtk_colors.InsertNextTuple1(labels[index]) for triangle in self.triangles: vtk_triangle = vtk.vtkTriangle() vtk_triangle.GetPointIds().SetId(0, triangle[0]) vtk_triangle.GetPointIds().SetId(1, triangle[1]) vtk_triangle.GetPointIds().SetId(2, triangle[2]) vtk_triangles.InsertNextCell(vtk_triangle) # Create (geometry and topology) the associated polydata polydata = vtk.vtkPolyData() polydata.SetPoints(vtk_points) polydata.GetPointData().SetScalars(vtk_colors) polydata.SetPolys(vtk_triangles) return polydata
def unstructuredgrid( self, points, npars=None ): """add unstructured grid""" points = _nansplit( points ) #assert isinstance( points, (list,tuple,numpy.ndarray) ), 'Expected list of point arrays' import vtk vtkPoints = vtk.vtkPoints() vtkPoints.SetNumberOfPoints( sum(pts.shape[0] for pts in points) ) cnt = 0 for pts in points: np, ndims = pts.shape if not npars: npars = ndims vtkelem = None if np == 2: vtkelem = vtk.vtkLine() elif np == 3: vtkelem = vtk.vtkTriangle() elif np == 4: if npars == 2: vtkelem = vtk.vtkQuad() elif npars == 3: vtkelem = vtk.vtkTetra() elif np == 8: vtkelem = vtk.vtkVoxel() # TODO hexahedron for not rectilinear NOTE ordering changes! if not vtkelem: raise Exception( 'not sure what to do with cells with ndims=%d and npoints=%d' % (ndims,np) ) if ndims < 3: pts = numpy.concatenate([pts,numpy.zeros(shape=(pts.shape[0],3-ndims))],axis=1) cellpoints = vtkelem.GetPointIds() for i,point in enumerate(pts): vtkPoints .SetPoint( cnt, point ) cellpoints.SetId( i, cnt ) cnt +=1 self.vtkMesh.InsertNextCell( vtkelem.GetCellType(), cellpoints ) self.vtkMesh.SetPoints( vtkPoints )
def initTriangles(self): """Sets up triangles describing mesh.""" verts=self.embryo.simulation.mesh.mesh._getOrderedCellVertexIDs().T cellArray = vtk.vtkCellArray() for j,vert in enumerate(verts): tetra = vtk.vtkTriangle() for i,v in enumerate(vert): tetra.GetPointIds().SetId(i, v) cellArray.InsertNextCell(tetra) self.grid.SetCells(vtk.VTK_TRIANGLE, cellArray)
def create_actor_tri(pts, tris, color, **kwargs): """ Creates a VTK actor for rendering triangulated surface plots. :param pts: points :type pts: vtkFloatArray :param tris: list of triangle indices :type tris: ndarray :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) # Create points points = vtk.vtkPoints() points.SetData(pts) # Create triangles triangles = vtk.vtkCellArray() for tri in tris: tmp = vtk.vtkTriangle() for i, v in enumerate(tri): tmp.GetPointIds().SetId(i, v) triangles.InsertNextCell(tmp) # Create a PolyData object and add points & triangles polydata = vtk.vtkPolyData() polydata.SetPoints(points) polydata.SetPolys(triangles) # 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) # Return the actor return actor
def buildPartialVTKGrid(self, factag): #get points required for factag pointsList = self.getPointsWithFactag(factag) #create a lookup table so we can map the #cells from the global list to a local list points = vtk.vtkPoints() localIdx = 0 ptMap = {} for pt in pointsList: ptMap[int(pt)] = localIdx localIdx = localIdx + 1 p = self.mesh.coords[(pt*3):(pt*3+3)] points.InsertNextPoint(p) vtkgrid = vtk.vtkUnstructuredGrid() vtkgrid.SetPoints(points) #get elements that have desired factag felements = self.getElementsWithFactag(factag) #build the vtk elements for element in felements: type = element.getType() nodes = element.nodes if type == eTypes.TRI: cell = vtk.vtkTriangle() elif type == eTypes.QUAD: cell = vtk.vtkQuad() elif type == eTypes.TET: cell = vtk.vtkTetra() elif type == eTypes.PYRAMID: cell = vtk.vtkPyramid() elif type == eTypes.PRISM: cell = vtk.vtkWedge() #prism elif type == eTypes.HEX: cell = vtk.vtkHexahedron() else: raise # throw an exception j = 0 for n in nodes: localId = ptMap[int(n)] cell.GetPointIds().SetId(j,localId) j = j+1 vtkgrid.InsertNextCell(cell.GetCellType(), cell.GetPointIds()) return vtkgrid
def as_triangles(indices, cellarray, level, data): if len(indices) >= 3: stride = len(indices)//4 indices.append(indices[-1] + 1) triangle = vtk.vtkTriangle() triangle.GetPointIds().SetId(0, indices[ stride]) triangle.GetPointIds().SetId(1, indices[2*stride]) triangle.GetPointIds().SetId(2, indices[3*stride]) cellarray.InsertNextCell(triangle) data.InsertNextValue(level) as_triangles(indices[ 0: stride], cellarray, level + 1, data) as_triangles(indices[ stride: 2*stride], cellarray, level + 1, data) as_triangles(indices[2*stride: 3*stride], cellarray, level + 1, data) as_triangles(indices[3*stride: -1], cellarray, level + 1, data)
def get_linear_cell(cell): """ Get equivalent linear cell to vtkCell cell""" if cell.GetCellType() in (vtk.VTK_POLY_LINE,): linear_cell = vtk.vtkLine() linear_cell.GetPoints().SetPoint(0, cell.GetPoints().GetPoint(0)) linear_cell.GetPoints().SetPoint(1, cell.GetPoints().GetPoint(1)) elif cell.GetCellType() in (vtk.VTK_QUADRATIC_TRIANGLE,): linear_cell = vtk.vtkTriangle() linear_cell.GetPoints().SetPoint(0, cell.GetPoints().GetPoint(0)) linear_cell.GetPoints().SetPoint(1, cell.GetPoints().GetPoint(1)) linear_cell.GetPoints().SetPoint(2, cell.GetPoints().GetPoint(2)) elif cell.GetCellType() in (vtk.VTK_QUADRATIC_TETRA,): linear_cell = vtk.vtkTetra() linear_cell.GetPoints().SetPoint(0, cell.GetPoints().GetPoint(0)) linear_cell.GetPoints().SetPoint(1, cell.GetPoints().GetPoint(1)) linear_cell.GetPoints().SetPoint(2, cell.GetPoints().GetPoint(2)) linear_cell.GetPoints().SetPoint(3, cell.GetPoints().GetPoint(3)) else: linear_cell = cell return linear_cell
def _create_tecplot_shells(self, is_quads, quads, is_tris, tris): if is_quads: elements = quads for iface, face in enumerate(quads): elem = vtkQuad() epoints = elem.GetPointIds() epoints.SetId(0, face[0]) epoints.SetId(1, face[1]) epoints.SetId(2, face[2]) epoints.SetId(3, face[3]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) #elem.GetCellType() = 5 # vtkTriangle #break if is_tris: elements = tris for iface, face in enumerate(tris): elem = vtkTriangle() epoints = elem.GetPointIds() epoints.SetId(0, face[0]) epoints.SetId(1, face[1]) epoints.SetId(2, face[2]) self.grid.InsertNextCell(5, elem.GetPointIds()) #elem.GetCellType() = 5 # vtkTriangle
def get3Dpolyactor(final_tripoints): polys = [] for i in xrange(len(final_tripoints)/3): poly = [] poly.append(final_tripoints[3*i]) poly.append(final_tripoints[3*i+1]) poly.append(final_tripoints[3*i+2]) polys.append(poly) # print 'polys: ', polys points = vtk.vtkPoints() print 'len(tris): ', len(polys) for p in polys: points.InsertNextPoint(p[0]) points.InsertNextPoint(p[1]) points.InsertNextPoint(p[2]) tris = vtk.vtkCellArray() for i in range(len(polys)): tri = vtk.vtkTriangle() tri.GetPointIds().SetId(0, 3*i) tri.GetPointIds().SetId(1, 3*i+1) tri.GetPointIds().SetId(2, 3*i+2) tris.InsertNextCell(tri) trisPolyData = vtk.vtkPolyData() trisPolyData.SetPoints(points) trisPolyData.SetPolys(tris) mapper = vtk.vtkPolyDataMapper() if vtk.VTK_MAJOR_VERSION <= 5: mapper.SetInput(trisPolyData) else: mapper.SetInputData(trisPolyData) actor = vtk.vtkActor() actor.SetMapper(mapper) return actor
def CreateCrossSectionPolyDataFromFile(file): with open(file, 'r') as f: read_data = f.read() tokens = string.split(read_data) numPts = int(tokens[0]) numCells = int(tokens[1]) print numPts, numCells newPoints = vtk.vtkPoints() newPoints.SetNumberOfPoints(numPts) offset = 2 for ptId in xrange(numPts): x = float(tokens[ptId*3 + 0 + offset]) y = float(tokens[ptId*3 + 1 + offset]) z = float(tokens[ptId*3 + 2 + offset]) newPoints.SetPoint(ptId, x, y, z) output = vtk.vtkPolyData() output.SetPoints(newPoints) output.Allocate(3*numCells) offset = 2 + 3*numPts triangle = vtk.vtkTriangle() pointIds = triangle.GetPointIds() pointIds.SetNumberOfIds(3) for cellId in xrange(numCells): for i in xrange(3): pointIds.SetId(i, int(tokens[cellId*3 + i + offset])) output.InsertNextCell(triangle.GetCellType(), pointIds) return output
def renderClusterFacets(self, clusterSize, clusterPos, lattice, neighbourRadius, appendPolyData): """ Render facets of a cluster. """ # get facets facets = clusters.findConvexHullFacets(clusterSize, clusterPos) # now render if facets is not None: # TODO: make sure not facets more than neighbour rad from cell facets = clusters.checkFacetsPBCs(facets, clusterPos, 2.0 * neighbourRadius, lattice.PBC, lattice.cellDims) # create vtk points from cluster positions points = vtk.vtkPoints() for i in xrange(clusterSize): points.InsertNextPoint(clusterPos[3 * i], clusterPos[3 * i + 1], clusterPos[3 * i + 2]) # create triangles triangles = vtk.vtkCellArray() for facet in facets: triangle = vtk.vtkTriangle() for j in xrange(3): triangle.GetPointIds().SetId(j, facet[j]) triangles.InsertNextCell(triangle) # polydata object trianglePolyData = vtk.vtkPolyData() trianglePolyData.SetPoints(points) trianglePolyData.SetPolys(triangles) # add polydata if vtk.vtkVersion.GetVTKMajorVersion() <= 5: appendPolyData.AddInputConnection(trianglePolyData.GetProducerPort()) else: appendPolyData.AddInputData(trianglePolyData)