VTK官方示例
-vtk字體
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingFreeType
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkPoints
from vtkmodules.vtkCommonDataModel import (
vtkCellArray,
vtkPolyData
)
from vtkmodules.vtkRenderingCore import (
vtkActor2D,
vtkCoordinate,
vtkPolyDataMapper2D,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer,
vtkTextMapper,
vtkTextProperty
)
def main():
font_size = 24
# Create the text mappers and the associated Actor2Ds.
# The font and text properties (except justification) are the same for
# each single line mapper. Let's create a common text property object
singleLineTextProp = vtkTextProperty()
singleLineTextProp.SetFontSize(font_size)
singleLineTextProp.SetFontFamilyToArial()
singleLineTextProp.BoldOff()
singleLineTextProp.ItalicOff()
singleLineTextProp.ShadowOff()
# The font and text properties (except justification) are the same for
# each multi line mapper. Let's create a common text property object
multiLineTextProp = vtkTextProperty()
multiLineTextProp.ShallowCopy(singleLineTextProp)
multiLineTextProp.BoldOn()
multiLineTextProp.ItalicOn()
multiLineTextProp.ShadowOn()
multiLineTextProp.SetLineSpacing(0.8)
colors = vtkNamedColors()
# The text is on a single line and bottom-justified.
singleLineTextB = vtkTextMapper()
singleLineTextB.SetInput('Single line (bottom)')
tprop = singleLineTextB.GetTextProperty()
tprop.ShallowCopy(singleLineTextProp)
tprop.SetVerticalJustificationToBottom()
tprop.SetColor(colors.GetColor3d('Tomato'))
singleLineTextActorB = vtkActor2D()
singleLineTextActorB.SetMapper(singleLineTextB)
singleLineTextActorB.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
singleLineTextActorB.GetPositionCoordinate().SetValue(0.05, 0.85)
# The text is on a single line and center-justified (vertical justification).
singleLineTextC = vtkTextMapper()
singleLineTextC.SetInput('Single line (centered)')
tprop = singleLineTextC.GetTextProperty()
tprop.ShallowCopy(singleLineTextProp)
tprop.SetVerticalJustificationToCentered()
tprop.SetColor(colors.GetColor3d('DarkGreen'))
singleLineTextActorC = vtkActor2D()
singleLineTextActorC.SetMapper(singleLineTextC)
singleLineTextActorC.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
singleLineTextActorC.GetPositionCoordinate().SetValue(0.05, 0.75)
# The text is on a single line and top-justified.
singleLineTextT = vtkTextMapper()
singleLineTextT.SetInput('Single line (top)')
tprop = singleLineTextT.GetTextProperty()
tprop.ShallowCopy(singleLineTextProp)
tprop.SetVerticalJustificationToTop()
tprop.SetColor(colors.GetColor3d('Peacock'))
singleLineTextActorT = vtkActor2D()
singleLineTextActorT.SetMapper(singleLineTextT)
singleLineTextActorT.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
singleLineTextActorT.GetPositionCoordinate().SetValue(0.05, 0.65)
# The text is on multiple lines and left- and top-justified.
textMapperL = vtkTextMapper()
textMapperL.SetInput('This is\nmulti-line\ntext output\n(left-top)')
tprop = textMapperL.GetTextProperty()
tprop.ShallowCopy(multiLineTextProp)
tprop.SetJustificationToLeft()
tprop.SetVerticalJustificationToTop()
tprop.SetColor(colors.GetColor3d('Tomato'))
textActorL = vtkActor2D()
textActorL.SetMapper(textMapperL)
textActorL.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
textActorL.GetPositionCoordinate().SetValue(0.05, 0.5)
# The text is on multiple lines and center-justified (both horizontal and vertical).
textMapperC = vtkTextMapper()
textMapperC.SetInput('This is\nmulti-line\ntext output\n(centered)')
tprop = textMapperC.GetTextProperty()
tprop.ShallowCopy(multiLineTextProp)
tprop.SetJustificationToCentered()
tprop.SetVerticalJustificationToCentered()
tprop.SetColor(colors.GetColor3d('DarkGreen'))
textActorC = vtkActor2D()
textActorC.SetMapper(textMapperC)
textActorC.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
textActorC.GetPositionCoordinate().SetValue(0.5, 0.5)
# The text is on multiple lines and right- and bottom-justified.
textMapperR = vtkTextMapper()
textMapperR.SetInput('This is\nmulti-line\ntext output\n(right-bottom)')
tprop = textMapperR.GetTextProperty()
tprop.ShallowCopy(multiLineTextProp)
tprop.SetJustificationToRight()
tprop.SetVerticalJustificationToBottom()
tprop.SetColor(colors.GetColor3d('Peacock'))
textActorR = vtkActor2D()
textActorR.SetMapper(textMapperR)
textActorR.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
textActorR.GetPositionCoordinate().SetValue(0.95, 0.5)
# Draw the grid to demonstrate the placement of the text.
# Set up the necessary points.
Pts = vtkPoints()
Pts.InsertNextPoint(0.05, 0.0, 0.0)
Pts.InsertNextPoint(0.05, 1.0, 0.0)
Pts.InsertNextPoint(0.5, 0.0, 0.0)
Pts.InsertNextPoint(0.5, 1.0, 0.0)
Pts.InsertNextPoint(0.95, 0.0, 0.0)
Pts.InsertNextPoint(0.95, 1.0, 0.0)
Pts.InsertNextPoint(0.0, 0.5, 0.0)
Pts.InsertNextPoint(1.0, 0.5, 0.0)
Pts.InsertNextPoint(0.00, 0.85, 0.0)
Pts.InsertNextPoint(0.50, 0.85, 0.0)
Pts.InsertNextPoint(0.00, 0.75, 0.0)
Pts.InsertNextPoint(0.50, 0.75, 0.0)
Pts.InsertNextPoint(0.00, 0.65, 0.0)
Pts.InsertNextPoint(0.50, 0.65, 0.0)
# Set up the lines that use these points.
Lines = vtkCellArray()
Lines.InsertNextCell(2)
Lines.InsertCellPoint(0)
Lines.InsertCellPoint(1)
Lines.InsertNextCell(2)
Lines.InsertCellPoint(2)
Lines.InsertCellPoint(3)
Lines.InsertNextCell(2)
Lines.InsertCellPoint(4)
Lines.InsertCellPoint(5)
Lines.InsertNextCell(2)
Lines.InsertCellPoint(6)
Lines.InsertCellPoint(7)
Lines.InsertNextCell(2)
Lines.InsertCellPoint(8)
Lines.InsertCellPoint(9)
Lines.InsertNextCell(2)
Lines.InsertCellPoint(10)
Lines.InsertCellPoint(11)
Lines.InsertNextCell(2)
Lines.InsertCellPoint(12)
Lines.InsertCellPoint(13)
# Create a grid that uses these points and lines.
Grid = vtkPolyData()
Grid.SetPoints(Pts)
Grid.SetLines(Lines)
# Set up the coordinate system.
normCoords = vtkCoordinate()
normCoords.SetCoordinateSystemToNormalizedViewport()
# Set up the mapper and actor (2D) for the grid.
mapper = vtkPolyDataMapper2D()
mapper.SetInputData(Grid)
mapper.SetTransformCoordinate(normCoords)
gridActor = vtkActor2D()
gridActor.SetMapper(mapper)
gridActor.GetProperty().SetColor(colors.GetColor3d('DimGray'))
# Create the Renderer, RenderWindow, and RenderWindowInteractor
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.AddRenderer(renderer)
interactor = vtkRenderWindowInteractor()
interactor.SetRenderWindow(renderWindow)
# Add the actors to the renderer set the background and size zoom in closer to the image render
renderer.AddActor2D(textActorL)
renderer.AddActor2D(textActorC)
renderer.AddActor2D(textActorR)
renderer.AddActor2D(singleLineTextActorB)
renderer.AddActor2D(singleLineTextActorC)
renderer.AddActor2D(singleLineTextActorT)
renderer.AddActor2D(gridActor)
renderer.SetBackground(colors.GetColor3d('Silver'))
renderWindow.SetSize(640, 480)
renderer.GetActiveCamera().Zoom(1.5)
# Enable user interface interactor
interactor.Initialize()
renderWindow.SetWindowName('MultiLineText')
renderWindow.Render()
interactor.Start()
if __name__ == '__main__':
main()
Text origin
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkFiltersGeneral import vtkAxes
from vtkmodules.vtkInteractionStyle import vtkInteractorStyleTrackballCamera
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkFollower,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
from vtkmodules.vtkRenderingFreeType import vtkVectorText
def main():
colors = vtkNamedColors()
# Create the axes and the associated mapper and actor.
axes = vtkAxes()
axes.SetOrigin(0, 0, 0)
axesMapper = vtkPolyDataMapper()
axesMapper.SetInputConnection(axes.GetOutputPort())
axesActor = vtkActor()
axesActor.SetMapper(axesMapper)
# Create the 3D text and the associated mapper and follower (a type of actor). Position the text so it is displayed over the origin of the axes.
atext = vtkVectorText()
atext.SetText('Origin')
textMapper = vtkPolyDataMapper()
textMapper.SetInputConnection(atext.GetOutputPort())
textActor = vtkFollower()
textActor.SetMapper(textMapper)
textActor.SetScale(0.2, 0.2, 0.2)
textActor.AddPosition(0, -0.1, 0)
textActor.GetProperty().SetColor(colors.GetColor3d('Peacock'))
# Create the Renderer, RenderWindow, and RenderWindowInteractor.
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindow.SetSize(640, 480)
interactor = vtkRenderWindowInteractor()
interactor.SetRenderWindow(renderWindow)
style = vtkInteractorStyleTrackballCamera()
interactor.SetInteractorStyle(style)
# Add the actors to the renderer.
renderer.AddActor(axesActor)
renderer.AddActor(textActor)
renderer.SetBackground(colors.GetColor3d('Silver'))
# Zoom in closer.
renderer.ResetCamera()
renderer.GetActiveCamera().Zoom(1.6)
renderer.SetBackground(colors.GetColor3d('Silver'))
# Reset the clipping range of the camera; set the camera of the follower; render.
renderer.ResetCameraClippingRange()
textActor.SetCamera(renderer.GetActiveCamera())
interactor.Initialize()
renderWindow.SetWindowName('TextOrigin')
renderWindow.Render()
interactor.Start()
if __name__ == '__main__':
main()
將actor保存成vtk文件
#!/usr/bin/env python
from vtkmodules.vtkCommonDataModel import vtkPolyData
from vtkmodules.vtkFiltersSources import vtkSphereSource
from vtkmodules.vtkIOXML import vtkXMLPolyDataWriter
def main():
# setup sphere
sphereSource = vtkSphereSource()
sphereSource.Update()
polydata = vtkPolyData()
polydata.ShallowCopy(sphereSource.GetOutput())
normals = polydata.GetPointData().GetNormals()
normals.SetName('TestN')
writer = vtkXMLPolyDataWriter()
writer.SetFileName('Test.vtp')
writer.SetInputData(polydata)
writer.Write()
if __name__ == '__main__':
main()
结果:'Test.vtp'
<?xml version="1.0"?>
<VTKFile type="PolyData" version="0.1" byte_order="LittleEndian" header_type="UInt32" compressor="vtkZLibDataCompressor">
<PolyData>
<Piece NumberOfPoints="50" NumberOfVerts="0" NumberOfLines="0" NumberOfStrips="0" NumberOfPolys="96" >
<PointData Normals="TestN">
<DataArray type="Float32" Name="TestN" NumberOfComponents="3" format="appended" RangeMin="0.99999997719" RangeMax="1.000000013" offset="0" />
</PointData>
<CellData>
</CellData>
<Points>
<DataArray type="Float32" Name="Points" NumberOfComponents="3" format="appended" RangeMin="0.49999998859" RangeMax="0.50000000651" offset="336" />
</Points>
<Verts>
<DataArray type="Int64" Name="connectivity" format="appended" RangeMin="" RangeMax="" offset="668" />
<DataArray type="Int64" Name="offsets" format="appended" RangeMin="" RangeMax="" offset="684" />
</Verts>
<Lines>
<DataArray type="Int64" Name="connectivity" format="appended" RangeMin="" RangeMax="" offset="700" />
<DataArray type="Int64" Name="offsets" format="appended" RangeMin="" RangeMax="" offset="716" />
</Lines>
<Strips>
<DataArray type="Int64" Name="connectivity" format="appended" RangeMin="" RangeMax="" offset="732" />
<DataArray type="Int64" Name="offsets" format="appended" RangeMin="" RangeMax="" offset="748" />
</Strips>
<Polys>
<DataArray type="Int64" Name="connectivity" format="appended" RangeMin="" RangeMax="" offset="764" />
<DataArray type="Int64" Name="offsets" format="appended" RangeMin="" RangeMax="" offset="1240" />
</Polys>
</Piece>
</PolyData>
<AppendedData encoding="base64">
_AQAAAACAAABYAgAA6AAAAA==eJxNkaEKAkEURReLyGLUJBhcLSL4BTvV5BfYBKsWg1pMil2jzfUXbO+2xegHiFjEL9gud9jBO/Dgwrx75s57URTO1kV/jUrvlVJ9splr9Ub+rnpuu/dx5fX+OU1Fm/SoF/3GOWWR89jVfZHT3Ax9kSPapEe9cHHRIZecbz5J+B45xfWQMAc5ok161EumSR5IHkgeSB5InuDlH83Fy6ScD775Mynng+Ja65bzCdqkR72BaZIHkgeSB5IHkodezO+3C7nkDE7djO+Rs1iPM+YgR7RJj3rDzE32BdkXZF+QfUH25Tk/IcXzPQ==AQAAAACAAABYAgAA5gAAAA==eJxNkSEOwlAQRBsMIWhQoNrUEDSK9iKEK4DBgIcgcCAJpq3mAn9wTRXhABUkBHqCChzMTwvTZJMRO+9Pdxzn94V/6Vwa/jSgeMavoOdnVjePp+C+f1u9yR9j0UZ2IF4MOv2AQ85tvbNDTnd1tkOOaCM76kXYXrjkklOkucv3yCmTlscc5Ig2sqNeMiF5IHkgeSB5IHlqL//xyy3d6j4o0olX3QdlsvWq+9TayI56ayYkDyQPJA8kDyQPvZhlo4hccoaHOOJ75MyX14g5yBFtZEe99c0hfUH6gvQF6QvSl+V8AO4bFuI=AAAAAACAAAAAAAAAAAAAAACAAAAAAAAAAAAAAACAAAAAAAAAAAAAAACAAAAAAAAAAAAAAACAAAAAAAAAAAAAAACAAAAAAAAAAQAAAACAAAAACQAAUgEAAA==eJxdz0VuQ1EUBNHEEGZmh+ww7X9zGeSfQepNrqrUT+oeLf29taX/D+/E46N4fBGPb+PxIh6/x+NR/Opwl4e7ncsf5vLnufwsl5/n8m+5/E8ur7c94+Gux+O15CbD3YjH68lNh7sZjzeSWxnuVjzeTM6e7Xjsnx367cbjneT024vHu8nptx+P95LT7yAe7ydn12E89s8O/Y7j8VFy+p3E4+Pk9DuNxyfJ6XcWj0+Ts+s8Hvtnh36X8fgiOf2u4vFlcvpdx+Or5PS7icfXydk1i8f+2aHfXTy+TU6/+3h8l5x+D/H4Pjn9HuPxQ3J2zeOxf3bo9xSPF8np9xyPn5LT7yUePyen32s8fknOrrd47J8d+n3E4/fk9PuMxx/J6fcVjz+T0+87Hn8lZ9dPPPbPDv3G8XiUnH6TeDxOTr9pPJ4kp99KPJ4mZ9dqPPbvF4aPGyE=AQAAAACAAAAAAwAAyAAAAA==eJwtxVtEAwAAAMAeltKUTWlKKSIiRsSIMcYYERExYoyIiIgYY0RERESMETEiIiIiIiJGjBgjIsaIiKiP3f1cd0dbj/sc9KDDHnbEY57wlKc941nPOep5LzjmRcedcNIpp73kZa941WvOeN1Z57zhTW952zve9Z7zLrjofR/40Ec+9olPfeaSyz73hSu+9JWvfeNb3/neD370k5/94qpfXfOb62743R/+dNMtf/nbP/71n7s62wfc634POOQhj3jU4570P6sgK5w=
</AppendedData>
</VTKFile>
vtkCompositePolyDataMapper和vtkMultiBlockDataSet将多个数据绑定成一个
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonDataModel import vtkMultiBlockDataSet
from vtkmodules.vtkFiltersSources import vtkSphereSource
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkCompositeDataDisplayAttributes,
vtkCompositePolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
# Create Sphere 1.
sphere1 = vtkSphereSource()
sphere1.SetRadius(3)
sphere1.SetCenter(0, 0, 0)
sphere1.Update()
# Create Sphere 2.
sphere2 = vtkSphereSource()
sphere2.SetRadius(2)
sphere2.SetCenter(2, 0, 0)
sphere2.Update()
mbds = vtkMultiBlockDataSet()
mbds.SetNumberOfBlocks(3)
mbds.SetBlock(0, sphere1.GetOutput())
# Leave block 1 NULL. NULL blocks are valid and should be handled by
# algorithms that process multiblock datasets. Especially when
# running in parallel where the blocks owned by other processes are
# NULL in this process.
mbds.SetBlock(2, sphere2.GetOutput())
# Use vtkCompositePolyDataMapper2 if VTK Version < 90020230516
mapper = vtkCompositePolyDataMapper()
mapper.SetInputDataObject(mbds)
cdsa = vtkCompositeDataDisplayAttributes()
mapper.SetCompositeDataDisplayAttributes(cdsa)
# You can use the vtkCompositeDataDisplayAttributes to set the color,
# opacity and visibiliy of individual blocks of the multiblock dataset.
# Attributes are mapped by block pointers (vtkDataObject*), so these can
# be queried by their flat index through a convenience function in the
# attribute class (vtkCompositeDataDisplayAttributes::DataObjectFromIndex).
# Alternatively, one can set attributes directly through the mapper using
# flat indices.
#
# This sets the block at flat index 3 red
# Note that the index is the flat index in the tree, so the whole multiblock
# is index 0 and the blocks are flat indexes 1, 2 and 3. This affects
# the block returned by mbds.GetBlock(2).
mapper.SetBlockColor(3, colors.GetColor3d('Red'))
# Color the spheres.
mapper.SetBlockColor(1, colors.GetColor3d('LavenderBlush'))
mapper.SetBlockColor(2, colors.GetColor3d('Lavender'))
actor = vtkActor()
actor.SetMapper(mapper)
# Create the Renderer, RenderWindow, and RenderWindowInteractor.
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
# Enable user interface interactor.
renderer.AddActor(actor)
renderer.SetBackground(colors.GetColor3d('SteelBlue'))
renderWindow.SetWindowName('CompositePolyDataMapper')
renderWindow.Render()
renderWindowInteractor.Start()
if __name__ == '__main__':
main()
vtkMultiBlockDataSet
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonDataModel import vtkMultiBlockDataSet
# vtkExtractEdges moved from vtkFiltersExtraction to vtkFiltersCore in
# VTK commit d9981b9aeb93b42d1371c6e295d76bfdc18430bd
try:
from vtkmodules.vtkFiltersCore import vtkExtractEdges
except ImportError:
from vtkmodules.vtkFiltersExtraction import vtkExtractEdges
from vtkmodules.vtkFiltersGeometry import vtkCompositeDataGeometryFilter
from vtkmodules.vtkFiltersSources import vtkSphereSource
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
# PART 1 Make some Data.
# Make a tree.
root = vtkMultiBlockDataSet()
branch = vtkMultiBlockDataSet()
root.SetBlock(0, branch)
# Make some leaves.
leaf1 = vtkSphereSource()
leaf1.SetCenter(0, 0, 0)
leaf1.Update()
branch.SetBlock(0, leaf1.GetOutput())
leaf2 = vtkSphereSource()
leaf2.SetCenter(1.75, 2.5, 0)
leaf2.SetRadius(1.5)
leaf2.Update()
branch.SetBlock(1, leaf2.GetOutput())
leaf3 = vtkSphereSource()
leaf3.SetCenter(4, 0, 0)
leaf3.SetRadius(2)
leaf3.Update()
root.SetBlock(1, leaf3.GetOutput())
# PART 2 Do something with the data
# a non composite aware filter, the pipeline will iterate
edges = vtkExtractEdges()
edges.SetInputData(root)
# PART 3 Show the data
# also demonstrate a composite aware filter
# this filter aggregates all blocks into one polydata
# this is handy for display, although fairly limited.
polydata = vtkCompositeDataGeometryFilter()
polydata.SetInputConnection(edges.GetOutputPort())
# Create the Renderer, RenderWindow, and RenderWindowInteractor.
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
mapper = vtkPolyDataMapper()
mapper.SetInputConnection(0, polydata.GetOutputPort(0))
actor = vtkActor()
actor.GetProperty().SetColor(colors.GetColor3d('Yellow'))
actor.GetProperty().SetLineWidth(2)
actor.SetMapper(mapper)
# Enable user interface interactor.
renderer.AddActor(actor)
renderer.SetBackground(colors.GetColor3d('CornflowerBlue'))
renderWindow.SetWindowName('MultiBlockDataSet')
renderWindow.Render()
renderWindowInteractor.Start()
if __name__ == '__main__':
main()
vtkOverlappingAMR
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkFloatArray
from vtkmodules.vtkCommonDataModel import (
vtkAMRBox,
vtkOverlappingAMR,
vtkSphere,
vtkUniformGrid
)
from vtkmodules.vtkFiltersCore import vtkContourFilter
from vtkmodules.vtkFiltersGeometry import vtkCompositeDataGeometryFilter
from vtkmodules.vtkFiltersModeling import vtkOutlineFilter
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def MakeScalars(dims, origin, spacing, scalars):
# Implicit function used to compute scalars
sphere = vtkSphere()
sphere.SetRadius(3)
sphere.SetCenter(5, 5, 5)
scalars.SetNumberOfTuples(dims[0] * dims[1] * dims[2])
for k in range(0, dims[2]):
z = origin[2] + spacing[2] * k
for j in range(0, dims[1]):
y = origin[1] + spacing[1] * j
for i in range(0, dims[0]):
x = origin[0] + spacing[0] * i
scalars.SetValue(k * dims[0] * dims[1] + j * dims[0] + i, sphere.EvaluateFunction(x, y, z))
def main():
colors = vtkNamedColors()
# Create and populate the AMR dataset
# The dataset should look like
# Level 0
# uniform grid, dimensions 11, 11, 11, AMR box (0, 0, 0) - (9, 9, 9)
# Level 1 - refinement ratio : 2
# uniform grid, dimensions 11, 11, 11, AMR box (0, 0, 0) - (9, 9, 9)
# uniform grid, dimensions 11, 11, 11, AMR box (10, 10, 10) - (19, 19, 19)
# Use MakeScalars() above to fill the scalar arrays
amr = vtkOverlappingAMR()
blocksPerLevel = [1, 2]
amr.Initialize(2, blocksPerLevel)
origin = [0.0, 0.0, 0.0]
spacing = [1.0, 1.0, 1.0]
dims = [11, 11, 11]
ug1 = vtkUniformGrid()
# Geometry
ug1.SetOrigin(origin)
ug1.SetSpacing(spacing)
ug1.SetDimensions(dims)
# Data
scalars = vtkFloatArray()
ug1.GetPointData().SetScalars(scalars)
MakeScalars(dims, origin, spacing, scalars)
lo = [0, 0, 0]
hi = [9, 9, 9]
box1 = vtkAMRBox()
amr.SetAMRBox(0, 0, box1)
amr.SetDataSet(0, 0, ug1)
spacing2 = [0.5, 0.5, 0.5]
ug2 = vtkUniformGrid()
# Geometry
ug2.SetOrigin(origin)
ug2.SetSpacing(spacing2)
ug2.SetDimensions(dims)
# Data
scalars2 = vtkFloatArray()
ug2.GetPointData().SetScalars(scalars2)
MakeScalars(dims, origin, spacing2, scalars2)
lo2 = [0, 0, 0]
hi2 = [9, 9, 9]
box2 = vtkAMRBox()
amr.SetAMRBox(1, 0, box2)
amr.SetDataSet(1, 0, ug2)
origin3 = [5, 5, 5]
ug3 = vtkUniformGrid()
# Geometry
ug3.SetOrigin(origin3)
ug3.SetSpacing(spacing2)
ug3.SetDimensions(dims)
# Data
scalars3 = vtkFloatArray()
ug3.GetPointData().SetScalars(scalars3)
MakeScalars(dims, origin3, spacing2, scalars3)
lo3 = [10, 10, 10]
hi3 = [19, 19, 19]
box3 = vtkAMRBox()
amr.SetAMRBox(1, 1, box3)
amr.SetDataSet(1, 1, ug3)
amr.SetRefinementRatio(0, 2)
# Render the amr data here.
of = vtkOutlineFilter()
of.SetInputData(amr)
geomFilter = vtkCompositeDataGeometryFilter()
geomFilter.SetInputConnection(of.GetOutputPort())
# Create an iso-surface - at 10.
cf = vtkContourFilter()
cf.SetInputData(amr)
cf.SetNumberOfContours(1)
cf.SetValue(0, 10.0)
geomFilter2 = vtkCompositeDataGeometryFilter()
geomFilter2.SetInputConnection(cf.GetOutputPort())
# Create the render window, renderer, and interactor.
aren = vtkRenderer()
renWin = vtkRenderWindow()
renWin.AddRenderer(aren)
iren = vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# Associate the geometry with a mapper and the mapper to an actor.
mapper = vtkPolyDataMapper()
mapper.SetInputConnection(of.GetOutputPort())
actor1 = vtkActor()
actor1.GetProperty().SetColor(colors.GetColor3d('Yellow'))
actor1.SetMapper(mapper)
# Associate the geometry with a mapper and the mapper to an actor.
mapper2 = vtkPolyDataMapper()
mapper2.SetInputConnection(geomFilter2.GetOutputPort())
actor2 = vtkActor()
actor2.SetMapper(mapper2)
# Add the actor to the renderer and start handling events.
aren.AddActor(actor1)
aren.AddActor(actor2)
aren.SetBackground(colors.GetColor3d('CornflowerBlue'))
renWin.SetWindowName('OverlappingAMR')
renWin.Render()
iren.Start()
if __name__ == '__main__':
main()
vtkLoopSubdivisionFilter Use a filter to smooth the data (will add triangles and smooth).
#!/usr/bin/env python
import numpy as np
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonComputationalGeometry import vtkParametricSpline
from vtkmodules.vtkCommonCore import (
mutable,
vtkPoints,
vtkUnsignedCharArray
)
from vtkmodules.vtkCommonDataModel import (
vtkCellArray,
vtkCellLocator,
vtkPolyData,
vtkTriangle
)
from vtkmodules.vtkFiltersCore import vtkCleanPolyData
from vtkmodules.vtkFiltersModeling import vtkLoopSubdivisionFilter
from vtkmodules.vtkFiltersSources import vtkParametricFunctionSource
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
named_colors = vtkNamedColors()
# Make a 32 x 32 grid.
size = 32
# Define z values for the topography.
# Comment out the following line if you want a different random
# distribution each time the script is run.
np.random.seed(3)
topography = np.random.randint(0, 5, (size, size))
# Define points, triangles and colors
colors = vtkUnsignedCharArray()
colors.SetNumberOfComponents(3)
points = vtkPoints()
triangles = vtkCellArray()
# Build the meshgrid manually.
count = 0
for i in range(size - 1):
for j in range(size - 1):
z1 = topography[i][j]
z2 = topography[i][j + 1]
z3 = topography[i + 1][j]
# Triangle 1
points.InsertNextPoint(i, j, z1)
points.InsertNextPoint(i, (j + 1), z2)
points.InsertNextPoint((i + 1), j, z3)
triangle = vtkTriangle()
triangle.GetPointIds().SetId(0, count)
triangle.GetPointIds().SetId(1, count + 1)
triangle.GetPointIds().SetId(2, count + 2)
triangles.InsertNextCell(triangle)
z1 = topography[i][j + 1]
z2 = topography[i + 1][j + 1]
z3 = topography[i + 1][j]
# Triangle 2
points.InsertNextPoint(i, (j + 1), z1)
points.InsertNextPoint((i + 1), (j + 1), z2)
points.InsertNextPoint((i + 1), j, z3)
triangle = vtkTriangle()
triangle.GetPointIds().SetId(0, count + 3)
triangle.GetPointIds().SetId(1, count + 4)
triangle.GetPointIds().SetId(2, count + 5)
count += 6
triangles.InsertNextCell(triangle)
# Add some color.
r = [int(i / float(size) * 255), int(j / float(size) * 255), 0]
colors.InsertNextTypedTuple(r)
colors.InsertNextTypedTuple(r)
colors.InsertNextTypedTuple(r)
colors.InsertNextTypedTuple(r)
colors.InsertNextTypedTuple(r)
colors.InsertNextTypedTuple(r)
# Create a polydata object.
trianglePolyData = vtkPolyData()
# Add the geometry and topology to the polydata.
trianglePolyData.SetPoints(points)
trianglePolyData.GetPointData().SetScalars(colors)
trianglePolyData.SetPolys(triangles)
# Clean the polydata so that the edges are shared!
cleanPolyData = vtkCleanPolyData()
cleanPolyData.SetInputData(trianglePolyData)
# Use a filter to smooth the data (will add triangles and smooth).
smooth_loop = vtkLoopSubdivisionFilter()
smooth_loop.SetNumberOfSubdivisions(3)
smooth_loop.SetInputConnection(cleanPolyData.GetOutputPort())
# Create a mapper and actor for smoothed dataset.
mapper = vtkPolyDataMapper()
mapper.SetInputConnection(smooth_loop.GetOutputPort())
actor_loop = vtkActor()
actor_loop.SetMapper(mapper)
actor_loop.GetProperty().SetInterpolationToFlat()
# Update the pipeline so that vtkCellLocator finds cells!
smooth_loop.Update()
# Define a cellLocator to be able to compute intersections between lines.
# and the surface
locator = vtkCellLocator()
locator.SetDataSet(smooth_loop.GetOutput())
locator.BuildLocator()
maxloop = 1000
dist = 20.0 / maxloop
tolerance = 0.001
# Make a list of points. Each point is the intersection of a vertical line
# defined by p1 and p2 and the surface.
points = vtkPoints()
for i in range(maxloop):
p1 = [2 + i * dist, 16, -1]
p2 = [2 + i * dist, 16, 6]
# Outputs (we need only pos which is the x, y, z position
# of the intersection)
t = mutable(0)
pos = [0.0, 0.0, 0.0]
pcoords = [0.0, 0.0, 0.0]
subId = mutable(0)
locator.IntersectWithLine(p1, p2, tolerance, t, pos, pcoords, subId)
# Add a slight offset in z.
pos[2] += 0.01
# Add the x, y, z position of the intersection.
points.InsertNextPoint(pos)
# Create a spline and add the points
spline = vtkParametricSpline()
spline.SetPoints(points)
functionSource = vtkParametricFunctionSource()
functionSource.SetUResolution(maxloop)
functionSource.SetParametricFunction(spline)
# Map the spline
mapper = vtkPolyDataMapper()
mapper.SetInputConnection(functionSource.GetOutputPort())
# Define the line actor
actor = vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetColor(named_colors.GetColor3d('Red'))
actor.GetProperty().SetLineWidth(3)
# Visualize
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
# Add actors and render
renderer.AddActor(actor)
renderer.AddActor(actor_loop)
renderer.SetBackground(named_colors.GetColor3d('Cornsilk'))
renderWindow.SetSize(800, 800)
renderWindow.Render()
renderer.GetActiveCamera().SetPosition(-32.471276, 53.258788, 61.209332)
renderer.GetActiveCamera().SetFocalPoint(15.500000, 15.500000, 2.000000)
renderer.GetActiveCamera().SetViewUp(0.348057, -0.636740, 0.688055)
renderer.ResetCameraClippingRange()
renderWindow.SetWindowName('LineOnMesh')
renderWindow.Render()
renderWindowInteractor.Start()
if __name__ == '__main__':
main()
mesh label image color
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import (
vtkLookupTable,
vtkVersion
)
from vtkmodules.vtkFiltersCore import (
vtkPolyDataNormals,
vtkWindowedSincPolyDataFilter
)
from vtkmodules.vtkFiltersGeneral import (
vtkDiscreteFlyingEdges3D,
vtkDiscreteMarchingCubes
)
from vtkmodules.vtkIOImage import vtkMetaImageReader
from vtkmodules.vtkImagingCore import vtkExtractVOI
from vtkmodules.vtkRenderingCore import (
vtkColorTransferFunction,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
from vtkmodules.vtkRenderingLOD import vtkLODActor
def main():
# vtkFlyingEdges3D was introduced in VTK >= 8.2
use_flying_edges = vtk_version_ok(8, 2, 0)
colors = vtkNamedColors()
#ifn, index = get_program_parameters()
ifn = "D:/vtk/vtk-examples-master/src/Testing/Data/labels.mhd"
index = 0;
# Prepare to read the file.
reader_volume = vtkMetaImageReader()
reader_volume.SetFileName(ifn)
reader_volume.Update()
# Extract the region of interest.
voi = vtkExtractVOI()
voi.SetInputConnection(reader_volume.GetOutputPort())
voi.SetVOI(0, 517, 0, 228, 0, 392)
voi.SetSampleRate(1, 1, 1)
voi.Update() # Necessary for GetScalarRange().
srange = voi.GetOutput().GetScalarRange() # Needs Update() before!
print('Range', srange)
# Prepare surface generation.
# For label images.
if use_flying_edges:
try:
contour = vtkDiscreteFlyingEdges3D()
except AttributeError:
contour = vtkDiscreteMarchingCubes()
else:
contour = vtkDiscreteMarchingCubes()
contour.SetInputConnection(voi.GetOutputPort())
# contour.ComputeNormalsOn()
print('Doing label', index)
contour.SetValue(0, index)
contour.Update() # Needed for GetNumberOfPolys()!!!
smoother = vtkWindowedSincPolyDataFilter()
smoother.SetInputConnection(contour.GetOutputPort())
smoother.SetNumberOfIterations(30) # This has little effect on the error!
# smoother.BoundarySmoothingOff()
# smoother.FeatureEdgeSmoothingOff()
# smoother.SetFeatureAngle(120.0)
# smoother.SetPassBand(0.001) # This increases the error a lot!
smoother.NonManifoldSmoothingOn()
smoother.NormalizeCoordinatesOn()
smoother.GenerateErrorScalarsOn()
# smoother.GenerateErrorVectorsOn()
smoother.Update()
# Find min and max of the smoother error.
se_range = smoother.GetOutput().GetPointData().GetScalars().GetRange()
print('Smoother error range:', se_range)
if se_range[1] > 1:
print('Big smoother error: min/max:', se_range[0], se_range[1])
lut = get_diverging_lut(4)
# Calculate cell normals.
normals = vtkPolyDataNormals()
normals.SetInputConnection(smoother.GetOutputPort())
normals.ComputeCellNormalsOn()
normals.ComputePointNormalsOff()
normals.ConsistencyOn()
normals.AutoOrientNormalsOn()
normals.Update() # Creates vtkPolyData.
normals.SetFeatureAngle(60.0)
mapper = vtkPolyDataMapper()
# mapper.SetInputConnection(smoother.GetOutputPort()) # This has no normals.
mapper.SetInputConnection(normals.GetOutputPort()) # This is better for visibility.)
mapper.ScalarVisibilityOn() # Show colour.
mapper.SetScalarRange(se_range)
# mapper.SetScalarModeToUseCellData() # Contains the label eg. 31
mapper.SetScalarModeToUsePointData() # The smoother error relates to the verts.
mapper.SetLookupTable(lut)
# Take the isosurface data and create geometry.
actor = vtkLODActor()
actor.SetNumberOfCloudPoints(100000)
actor.SetMapper(mapper)
# Create the renderer.
ren = vtkRenderer()
ren.SetBackground(colors.GetColor3d('DimGray'))
ren.AddActor(actor)
# Create a window for the renderer of size 600X600
ren_win = vtkRenderWindow()
ren_win.AddRenderer(ren)
ren_win.SetSize(600, 600)
ren_win.SetWindowName('MeshLabelImageColor')
ren_win.Render()
# Set a user interface interactor for the render window.
iren = vtkRenderWindowInteractor()
iren.SetRenderWindow(ren_win)
# Start the initialization and rendering.
iren.Initialize()
iren.Start()
def get_program_parameters():
import argparse
description = 'MeshLabelImageColor.'
epilogue = '''
Takes a label image in Meta format and meshes a single label of it.
'''
parser = argparse.ArgumentParser(description=description, epilog=epilogue)
parser.add_argument('filename', help='labels.mhd')
parser.add_argument('label', nargs='?', const=1, type=int, default=31, help='The label to use e.g 31')
args = parser.parse_args()
return args.filename, args.label
def get_diverging_lut(ct=0):
"""
See: [Diverging Color Maps for Scientific Visualization](https://www.kennethmoreland.com/color-maps/)
:param ct: The index of the color map to use.
:return: The lookup table.
"""
cm = dict()
# Start point = 0.0, mid point = 0.5 and end point = 1.0.
# Each value is a list with three sublists corresponding to the start point,
# mid point and end point along with the rgb color values for the respective point.
# cool to warm
cm[0] = [[0.0, 0.230, 0.299, 0.754], [0.5, 0.865, 0.865, 0.865], [1.0, 0.706, 0.016, 0.150]]
# purple to orange
cm[1] = [[0.0, 0.436, 0.308, 0.631], [0.5, 0.865, 0.865, 0.865], [1.0, 0.759, 0.334, 0.046]]
# green to purple
cm[2] = [[0.0, 0.085, 0.532, 0.201], [0.5, 0.865, 0.865, 0.865], [1.0, 0.436, 0.308, 0.631]]
# blue to brown
cm[3] = [[0.0, 0.217, 0.525, 0.910], [0.5, 0.865, 0.865, 0.865], [1.0, 0.677, 0.492, 0.093]]
# green to red
cm[4] = [[0.0, 0.085, 0.532, 0.201], [0.5, 0.865, 0.865, 0.865], [1.0, 0.758, 0.214, 0.233]]
ct = abs(ct)
if ct > len(cm) - 1:
ct = 0
print('The selected diverging color map is unavailable. Using the default cool to warm one.')
ctf = vtkColorTransferFunction()
ctf.SetColorSpaceToDiverging()
for scheme in cm[ct]:
ctf.AddRGBPoint(*scheme)
table_size = 256
lut = vtkLookupTable()
lut.SetNumberOfTableValues(table_size)
lut.Build()
for i in range(0, table_size):
rgba = list(ctf.GetColor(float(i) / table_size))
rgba.append(1)
lut.SetTableValue(i, rgba)
return lut
def vtk_version_ok(major, minor, build):
"""
Check the VTK version.
:param major: Requested major version.
:param minor: Requested minor version.
:param build: Requested build version.
:return: True if the requested VTK version is >= the actual VTK version.
"""
requested_version = (100 * int(major) + int(minor)) * 100000000 + int(build)
ver = vtkVersion()
actual_version = (100 * ver.GetVTKMajorVersion() + ver.GetVTKMinorVersion()) \
* 100000000 + ver.GetVTKBuildVersion()
if actual_version >= requested_version:
return True
else:
return False
if __name__ == '__main__':
main()
vtkParametricFunctionSource
# !/usr/bin/env python
# -*- coding: utf-8 -*-
import vtkmodules.all as vtk
def main():
colors = vtk.vtkNamedColors()
colors.SetColor("BkgColor", [26, 51, 102, 255])
parametricObjects = list()
parametricObjects.append(vtk.vtkParametricBoy())
parametricObjects.append(vtk.vtkParametricConicSpiral())
parametricObjects.append(vtk.vtkParametricCrossCap())
parametricObjects.append(vtk.vtkParametricDini())
parametricObjects.append(vtk.vtkParametricEllipsoid())
parametricObjects[-1].SetXRadius(0.5)
parametricObjects[-1].SetYRadius(2.0)
parametricObjects.append(vtk.vtkParametricEnneper())
parametricObjects.append(vtk.vtkParametricFigure8Klein())
parametricObjects.append(vtk.vtkParametricKlein())
parametricObjects.append(vtk.vtkParametricMobius())
parametricObjects[-1].SetRadius(2)
parametricObjects[-1].SetMinimumV(-0.5)
parametricObjects[-1].SetMaximumV(0.5)
parametricObjects.append(vtk.vtkParametricRandomHills())
parametricObjects[-1].AllowRandomGenerationOff()
parametricObjects.append(vtk.vtkParametricRoman())
parametricObjects.append(vtk.vtkParametricSuperEllipsoid())
parametricObjects[-1].SetN1(0.5)
parametricObjects[-1].SetN2(0.1)
parametricObjects.append(vtk.vtkParametricSuperToroid())
parametricObjects[-1].SetN1(0.2)
parametricObjects[-1].SetN2(3.0)
parametricObjects.append(vtk.vtkParametricTorus())
parametricObjects.append(vtk.vtkParametricSpline())
# Add some points to the parametric spline.
inputPoints = vtk.vtkPoints()
rng = vtk.vtkMinimalStandardRandomSequence()
rng.SetSeed(8775070)
for i in range(0, 10):
rng.Next()
x = rng.GetRangeValue(0.0, 1.0)
rng.Next()
y = rng.GetRangeValue(0.0, 1.0)
rng.Next()
z = rng.GetRangeValue(0.0, 1.0)
inputPoints.InsertNextPoint(x, y, z)
parametricObjects[-1].SetPoints(inputPoints)
parametricFunctionSources = list()
renderers = list()
mappers = list()
actors = list()
textmappers = list()
textactors = list()
# Create one text property for all
textProperty = vtk.vtkTextProperty()
textProperty.SetFontSize(12)
textProperty.SetJustificationToCentered()
backProperty = vtk.vtkProperty()
backProperty.SetColor(colors.GetColor3d("Tomato"))
# Create a parametric function source, renderer, mapper, and actor
# for each object
for i in range(0, len(parametricObjects)):
parametricFunctionSources.append(vtk.vtkParametricFunctionSource())
parametricFunctionSources[i].SetParametricFunction(parametricObjects[i])
parametricFunctionSources[i].SetUResolution(51)
parametricFunctionSources[i].SetVResolution(51)
parametricFunctionSources[i].SetWResolution(51)
parametricFunctionSources[i].Update()
mappers.append(vtk.vtkPolyDataMapper())
mappers[i].SetInputConnection(parametricFunctionSources[i].GetOutputPort())
actors.append(vtk.vtkActor())
actors[i].SetMapper(mappers[i])
actors[i].GetProperty().SetColor(colors.GetColor3d("Banana"))
actors[i].GetProperty().SetSpecular(.5)
actors[i].GetProperty().SetSpecularPower(20)
actors[i].SetBackfaceProperty(backProperty)
textmappers.append(vtk.vtkTextMapper())
textmappers[i].SetInput(parametricObjects[i].GetClassName())
textmappers[i].SetTextProperty(textProperty)
textactors.append(vtk.vtkActor2D())
textactors[i].SetMapper(textmappers[i])
textactors[i].SetPosition(100, 16)
renderers.append(vtk.vtkRenderer())
renderers[i].AddActor(actors[i])
renderers[i].AddActor(textactors[i])
renderers[i].SetBackground(colors.GetColor3d("BkgColor"))
# Setup the viewports
xGridDimensions = 4
yGridDimensions = 4
rendererSize = 200
renderWindow = vtk.vtkRenderWindow()
renderWindow.SetWindowName("Parametric Objects Demonstration")
renderWindow.SetSize(rendererSize * xGridDimensions, rendererSize * yGridDimensions)
for row in range(0, yGridDimensions):
for col in range(0, xGridDimensions):
index = row * xGridDimensions + col
# (xmin, ymin, xmax, ymax)
viewport = [float(col) / xGridDimensions,
float(yGridDimensions - (row + 1)) / yGridDimensions,
float(col + 1) / xGridDimensions,
float(yGridDimensions - row) / yGridDimensions]
if index > (len(actors) - 1):
# Add a renderer even if there is no actor.
# This makes the render window background all the same color.
ren = vtk.vtkRenderer()
ren.SetBackground(colors.GetColor3d("BkgColor"))
ren.SetViewport(viewport)
renderWindow.AddRenderer(ren)
continue
renderers[index].SetViewport(viewport)
renderers[index].ResetCamera()
renderers[index].GetActiveCamera().Azimuth(30)
renderers[index].GetActiveCamera().Elevation(-30)
renderers[index].GetActiveCamera().Zoom(0.9)
renderers[index].ResetCameraClippingRange()
renderWindow.AddRenderer(renderers[index])
interactor = vtk.vtkRenderWindowInteractor()
interactor.SetRenderWindow(renderWindow)
renderWindow.Render()
interactor.Start()
if __name__ == '__main__':
main()
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/17f8039637cc4149866acee2798eaa70.png
This example demonstrates how (1) to create an explicit structured grid and (2) to convert an explicit structured grid into an unstructured grid or vice versa.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import vtkmodules.all as vtk
def main():
colors = vtk.vtkNamedColors()
colors.SetColor("BkgColor", [26, 51, 102, 255])
parametricObjects = list()
parametricObjects.append(vtk.vtkParametricBohemianDome())
parametricObjects[-1].SetA(5.0)
parametricObjects[-1].SetB(1.0)
parametricObjects[-1].SetC(2.0)
parametricObjects.append(vtk.vtkParametricBour())
parametricObjects.append(vtk.vtkParametricCatalanMinimal())
parametricObjects.append(vtk.vtkParametricHenneberg())
parametricObjects.append(vtk.vtkParametricKuen())
parametricObjects.append(vtk.vtkParametricPluckerConoid())
parametricObjects.append(vtk.vtkParametricPseudosphere())
parametricFunctionSources = list()
renderers = list()
mappers = list()
actors = list()
textmappers = list()
textactors = list()
# Create one text property for all
textProperty = vtk.vtkTextProperty()
textProperty.SetFontSize(12)
textProperty.SetJustificationToCentered()
backProperty = vtk.vtkProperty()
backProperty.SetColor(colors.GetColor3d("Tomato"))
# Create a parametric function source, renderer, mapper, and actor
# for each object
for i in range(0, len(parametricObjects)):
parametricFunctionSources.append(
vtk.vtkParametricFunctionSource())
parametricFunctionSources[i].SetParametricFunction(parametricObjects[i])
parametricFunctionSources[i].Update()
mappers.append(vtk.vtkPolyDataMapper())
mappers[i].SetInputConnection(
parametricFunctionSources[i].GetOutputPort())
actors.append(vtk.vtkActor())
actors[i].SetMapper(mappers[i])
actors[i].GetProperty().SetColor(colors.GetColor3d("Banana"))
actors[i].GetProperty().SetSpecular(.5)
actors[i].GetProperty().SetSpecularPower(20)
actors[i].SetBackfaceProperty(backProperty)
textmappers.append(vtk.vtkTextMapper())
textmappers[i].SetInput(parametricObjects[i].GetClassName())
textmappers[i].SetTextProperty(textProperty)
textactors.append(vtk.vtkActor2D())
textactors[i].SetMapper(textmappers[i])
textactors[i].SetPosition(100, 16)
renderers.append(vtk.vtkRenderer())
renderers[i].AddActor(actors[i])
renderers[i].AddActor(textactors[i])
renderers[i].SetBackground(colors.GetColor3d("BkgColor"))
# Setup the viewports
xGridDimensions = 4
yGridDimensions = 2
rendererSize = 200
renderWindow = vtk.vtkRenderWindow()
renderWindow.SetWindowName("Parametric Objects Demonstration2")
renderWindow.SetSize(rendererSize * xGridDimensions,
rendererSize * yGridDimensions)
for row in range(0, yGridDimensions):
for col in range(0, xGridDimensions):
index = row * xGridDimensions + col
# (xmin, ymin, xmax, ymax)
viewport = [float(col) / xGridDimensions,
float(yGridDimensions - (row + 1)) / yGridDimensions,
float(col + 1) / xGridDimensions,
float(yGridDimensions - row) / yGridDimensions]
if index > (len(actors) - 1):
# Add a renderer even if there is no actor.
# This makes the render window background all the same color.
ren = vtk.vtkRenderer()
ren.SetBackground(colors.GetColor3d("BkgColor"))
ren.SetViewport(viewport)
renderWindow.AddRenderer(ren)
continue
renderers[index].SetViewport(viewport)
renderers[index].ResetCamera()
renderers[index].GetActiveCamera().Azimuth(30)
renderers[index].GetActiveCamera().Elevation(-30)
renderers[index].GetActiveCamera().Zoom(0.9)
renderers[index].ResetCameraClippingRange()
renderWindow.AddRenderer(renderers[index])
interactor = vtk.vtkRenderWindowInteractor()
interactor.SetRenderWindow(renderWindow)
renderWindow.Render()
interactor.Start()
if __name__ == '__main__':
main()
#!/usr/bin/env python
import numpy as np
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkPoints
from vtkmodules.vtkCommonDataModel import (
vtkCellArray,
vtkExplicitStructuredGrid
)
from vtkmodules.vtkFiltersCore import (
vtkExplicitStructuredGridToUnstructuredGrid,
vtkUnstructuredGridToExplicitStructuredGrid
)
from vtkmodules.vtkInteractionStyle import vtkInteractorStyleRubberBandPick
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkDataSetMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def create_explicit_structured_grid(dimensions, spacing=(1, 1, 1)):
"""Create an explicit structured grid.
Parameters
----------
dimensions : tuple(int, int, int)
The number of points in the I, J and K directions.
spacing : tuple(int, int, int)
The spacing between points in the I, J and K directions.
Returns
-------
grid : vtkExplicitStructuredGrid
An explicit structured grid.
"""
ni, nj, nk = dimensions
si, sj, sk = spacing
points = vtkPoints()
for z in range(0, nk * sk, sk):
for y in range(0, nj * sj, sj):
for x in range(0, ni * si, si):
points.InsertNextPoint((x, y, z))
cells = vtkCellArray()
for k in range(0, nk - 1):
for j in range(0, nj - 1):
for i in range(0, ni - 1):
multi_index = ([i, i + 1, i + 1, i, i, i + 1, i + 1, i],
[j, j, j + 1, j + 1, j, j, j + 1, j + 1],
[k, k, k, k, k + 1, k + 1, k + 1, k + 1])
pts = np.ravel_multi_index(multi_index, dimensions, order='F')
cells.InsertNextCell(8, pts)
grid = vtkExplicitStructuredGrid()
grid.SetDimensions(ni, nj, nk)
grid.SetPoints(points)
grid.SetCells(cells)
return grid
def convert_to_unstructured_grid(grid):
"""Convert explicit structured grid to unstructured grid.
Parameters
----------
grid : vtkExplicitStructuredGrid
An explicit structured grid.
Returns
-------
vtkUnstructuredGrid
An unstructured grid.
"""
converter = vtkExplicitStructuredGridToUnstructuredGrid()
converter.SetInputData(grid)
converter.Update()
return converter.GetOutput()
def convert_to_explicit_structured_grid(grid):
"""Convert unstructured grid to explicit structured grid.
Parameters
----------
grid : UnstructuredGrid
An unstructured grid.
Returns
-------
vtkExplicitStructuredGrid
An explicit structured grid. The ``'BLOCK_I'``, ``'BLOCK_J'`` and
``'BLOCK_K'`` cell arrays are required.
"""
converter = vtkUnstructuredGridToExplicitStructuredGrid()
converter.SetInputData(grid)
converter.SetInputArrayToProcess(0, 0, 0, 1, 'BLOCK_I')
converter.SetInputArrayToProcess(1, 0, 0, 1, 'BLOCK_J')
converter.SetInputArrayToProcess(2, 0, 0, 1, 'BLOCK_K')
converter.Update()
return converter.GetOutput()
def main():
grid = create_explicit_structured_grid((5, 6, 7), (20, 10, 1))
grid = convert_to_unstructured_grid(grid)
grid = convert_to_explicit_structured_grid(grid)
mapper = vtkDataSetMapper()
mapper.SetInputData(grid)
colors = vtkNamedColors()
actor = vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().EdgeVisibilityOn()
actor.GetProperty().LightingOff()
actor.GetProperty().SetColor(colors.GetColor3d('Seashell'))
renderer = vtkRenderer()
renderer.AddActor(actor)
renderer.SetBackground(colors.GetColor3d('DarkSlateGray'))
window = vtkRenderWindow()
window.AddRenderer(renderer)
window.SetWindowName('CreateESGrid')
window.SetSize(1024, 768)
window.Render()
camera = renderer.GetActiveCamera()
camera.SetPosition(8.383354, -72.468670, 94.262605)
camera.SetFocalPoint(42.295234, 21.111537, -0.863606)
camera.SetViewUp(0.152863, 0.676710, 0.720206)
camera.SetDistance(137.681759)
camera.SetClippingRange(78.173985, 211.583658)
interactor = vtkRenderWindowInteractor()
interactor.SetRenderWindow(window)
interactor.SetInteractorStyle(vtkInteractorStyleRubberBandPick())
window.Render()
interactor.Start()
if __name__ == '__main__':
main()
This example displays the using the vtkExplicitStructuredGrid class.
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkFiltersCore import vtkUnstructuredGridToExplicitStructuredGrid
from vtkmodules.vtkIOXML import vtkXMLUnstructuredGridReader
from vtkmodules.vtkInteractionStyle import vtkInteractorStyleRubberBandPick
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkDataSetMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def get_program_parameters(argv):
import argparse
description = 'Load an explicit structured grid from a file'
epilogue = '''
'''
parser = argparse.ArgumentParser(description=description, epilog=epilogue,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('fn', help='The explicit structured grid file name e.g. UNISIM-II-D.vtu.')
args = parser.parse_args()
return args.fn
def main(fn):
reader = vtkXMLUnstructuredGridReader()
reader.SetFileName(fn)
reader.Update()
converter = vtkUnstructuredGridToExplicitStructuredGrid()
converter.GlobalWarningDisplayOff() # hide VTK errors
converter.SetInputConnection(reader.GetOutputPort())
converter.SetInputArrayToProcess(0, 0, 0, 1, 'BLOCK_I')
converter.SetInputArrayToProcess(1, 0, 0, 1, 'BLOCK_J')
converter.SetInputArrayToProcess(2, 0, 0, 1, 'BLOCK_K')
converter.Update()
grid = converter.GetOutput()
grid.ComputeFacesConnectivityFlagsArray()
grid.GetCellData().SetActiveScalars('ConnectivityFlags')
scalars = grid.GetCellData().GetArray('ConnectivityFlags')
mapper = vtkDataSetMapper()
mapper.SetInputData(grid)
mapper.SetColorModeToMapScalars()
mapper.SetScalarRange(scalars.GetRange())
actor = vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().EdgeVisibilityOn()
colors = vtkNamedColors()
renderer = vtkRenderer()
renderer.AddActor(actor)
renderer.SetBackground(colors.GetColor3d('DimGray'))
window = vtkRenderWindow()
window.AddRenderer(renderer)
window.SetWindowName('LoadESGrid')
window.SetSize(1024, 768)
window.Render()
camera = renderer.GetActiveCamera()
camera.SetPosition(312452.407650, 7474760.406373, 3507.364723)
camera.SetFocalPoint(314388.388434, 7481520.509575, -2287.477388)
camera.SetViewUp(0.089920, 0.633216, 0.768734)
camera.SetDistance(9111.926908)
camera.SetClippingRange(595.217338, 19595.429475)
interactor = vtkRenderWindowInteractor()
interactor.SetRenderWindow(window)
interactor.SetInteractorStyle(vtkInteractorStyleRubberBandPick())
window.Render()
interactor.Start()
if __name__ == '__main__':
import sys
fn = get_program_parameters(sys.argv)
main(fn)
This example loads points into a polydata and an unstructured grid then combines them.The example should be extended to show cells being combined as well.
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkPoints
from vtkmodules.vtkCommonDataModel import (
vtkPolyData,
vtkUnstructuredGrid
)
from vtkmodules.vtkFiltersCore import vtkAppendFilter
from vtkmodules.vtkFiltersSources import (
vtkPointSource,
vtkSphereSource
)
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkDataSetMapper,
vtkGlyph3DMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
# Create 5 points (vtkPolyData)
pointSource = vtkPointSource()
pointSource.SetNumberOfPoints(5)
pointSource.Update()
polydata = pointSource.GetOutput()
print('There are', polydata.GetNumberOfPoints(), 'points in the polydata.')
# Create 2 points in a vtkUnstructuredGrid
points = vtkPoints()
points = vtkPoints()
points.InsertNextPoint(0, 0, 0)
points.InsertNextPoint(0, 0, 1)
ug = vtkUnstructuredGrid()
ug.SetPoints(points)
print('There are', ug.GetNumberOfPoints(), 'points in the unstructured.')
# Combine the two data sets
appendFilter = vtkAppendFilter()
appendFilter.AddInputData(polydata)
appendFilter.AddInputData(ug)
appendFilter.Update()
combined = vtkUnstructuredGrid()
combined = appendFilter.GetOutput()
print('There are', combined.GetNumberOfPoints(), 'points combined.')
# Create a mapper and actor
mapper = vtkDataSetMapper()
mapper.SetInputConnection(appendFilter.GetOutputPort())
actor = vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetPointSize(5)
# Map the points to spheres
sphereActor = point_to_glyph(appendFilter.GetOutput().GetPoints(), 0.05)
sphereActor.GetProperty().SetColor(colors.GetColor3d("Gold"))
# Create a renderer, render window, and interactor
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
# Add the actor to the scene
renderer.AddActor(actor)
renderer.AddActor(sphereActor)
renderer.SetBackground(colors.GetColor3d('RoyalBlue'))
# Render and interact
renderWindow.SetWindowName('AppendFilter')
renderWindow.Render()
renderWindowInteractor.Start()
def point_to_glyph(points, scale):
"""
Convert points to glyphs.
:param points: The points to glyph.
:param scale: The scale, used to determine the size of the
glyph representing the point, expressed as a
fraction of the largest side of the bounding
box surrounding the points. e.g. 0.05
:return: The actor.
"""
bounds = points.GetBounds()
max_len = 0.0
for i in range(0, 3):
max_len = max(bounds[i + 1] - bounds[i], max_len)
sphere_source = vtkSphereSource()
sphere_source.SetRadius(scale * max_len)
pd = vtkPolyData()
pd.SetPoints(points)
mapper = vtkGlyph3DMapper()
mapper.SetInputData(pd)
mapper.SetSourceConnection(sphere_source.GetOutputPort())
mapper.ScalarVisibilityOff()
mapper.ScalingOff()
actor = vtkActor()
actor.SetMapper(mapper)
return actor
if __name__ == '__main__':
main()
This example reads two .vtp files (or produces them if not specified as command line arguments), combines them, and
displays the result to the screen.
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonDataModel import vtkPolyData
from vtkmodules.vtkFiltersCore import (
vtkAppendPolyData,
vtkCleanPolyData
)
from vtkmodules.vtkFiltersSources import (
vtkConeSource,
vtkSphereSource
)
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
# Set the background color.
colors.SetColor('BkgColor', [0.3, 0.2, 0.1, 1.0])
input1 = vtkPolyData()
input2 = vtkPolyData()
sphereSource = vtkSphereSource()
sphereSource.SetCenter(5, 0, 0)
sphereSource.Update()
input1.ShallowCopy(sphereSource.GetOutput())
coneSource = vtkConeSource()
coneSource.Update()
input2.ShallowCopy(coneSource.GetOutput())
# Append the two meshes
appendFilter = vtkAppendPolyData()
appendFilter.AddInputData(input1)
appendFilter.AddInputData(input2)
appendFilter.Update()
# Remove any duplicate points.
cleanFilter = vtkCleanPolyData()
cleanFilter.SetInputConnection(appendFilter.GetOutputPort())
cleanFilter.Update()
# Create a mapper and actor
mapper = vtkPolyDataMapper()
mapper.SetInputConnection(cleanFilter.GetOutputPort())
actor = vtkActor()
actor.SetMapper(mapper)
# Create a renderer, render window, and interactor
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
# Add the actors to the scene
renderer.AddActor(actor)
# Render and interact
renderWindowInteractor.Initialize()
renderWindow.Render()
renderWindow.SetWindowName('CombinePolyData')
renderer.SetBackground(colors.GetColor3d('deep_ochre'))
renderer.GetActiveCamera().Zoom(0.9)
renderWindow.Render()
renderWindowInteractor.Start()
if __name__ == '__main__':
main()
CombinePolyData
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkFiltersCore import (
vtkAppendFilter,
vtkConnectivityFilter,
vtkDelaunay3D
)
from vtkmodules.vtkFiltersSources import vtkSphereSource
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkDataSetMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
sphereSource1 = vtkSphereSource()
sphereSource1.Update()
delaunay1 = vtkDelaunay3D()
delaunay1.SetInputConnection(sphereSource1.GetOutputPort())
delaunay1.Update()
sphereSource2 = vtkSphereSource()
sphereSource2.SetCenter(5, 0, 0)
sphereSource2.Update()
delaunay2 = vtkDelaunay3D()
delaunay2.SetInputConnection(sphereSource2.GetOutputPort())
delaunay2.Update()
appendFilter = vtkAppendFilter()
appendFilter.AddInputConnection(delaunay1.GetOutputPort())
appendFilter.AddInputConnection(delaunay2.GetOutputPort())
appendFilter.Update()
connectivityFilter = vtkConnectivityFilter()
connectivityFilter.SetInputConnection(appendFilter.GetOutputPort())
connectivityFilter.SetExtractionModeToAllRegions()
connectivityFilter.ColorRegionsOn()
connectivityFilter.Update()
# Visualize
mapper = vtkDataSetMapper()
mapper.SetInputConnection(connectivityFilter.GetOutputPort())
mapper.Update()
actor = vtkActor()
actor.SetMapper(mapper)
renderer = vtkRenderer()
renderer.AddActor(actor)
# renWindow = vtkRenderWindow()
# renWindow.AddRenderer(renderer)
# iren = vtkRenderWindowInteractor()
# iren.SetRenderWindow(renWindow)
# iren.Initialize()
# iren.Start()
renWindow = vtkRenderWindow()
renWindow.AddRenderer(renderer)
iren = vtkRenderWindowInteractor()
iren.SetRenderWindow(renWindow)
iren.Initialize()
renWindow.Render()
renWindow.SetWindowName('ConnectivityFilter')
renderer.SetBackground(colors.GetColor3d('deep_ochre'))
renderer.GetActiveCamera().Zoom(0.9)
renWindow.Render()
iren.Start()
if __name__ == '__main__':
main()
ConstrainedDelaunay2D
Description
Perform a 2D Delaunay triangulation respecting a specified boundary. This examples constructs a 10x10 grid of points. It
then defines a polygon that uses the points in the grid. We want to triangulate all of the points except the region
inside the boundary of the polygon. We expect a rectangular hole of size 4x3 in the resulting triangulated plane.
#!/usr/bin/python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import (
vtkMinimalStandardRandomSequence,
vtkPoints
)
from vtkmodules.vtkCommonDataModel import (
vtkCellArray,
vtkPolyData,
vtkPolygon
)
from vtkmodules.vtkFiltersCore import vtkDelaunay2D
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
# Generate a 10 x 10 grid of points
points = vtkPoints()
gridSize = 10
seed = 0
randomSequence = vtkMinimalStandardRandomSequence()
randomSequence.Initialize(seed)
for x in range(gridSize):
for y in range(gridSize):
d1 = randomSequence.GetValue() / 2.0 - 0.25
randomSequence.Next()
d2 = randomSequence.GetValue() / 2.0 - 0.25
randomSequence.Next()
points.InsertNextPoint(x + d1, y + d2, 0)
aPolyData = vtkPolyData()
aPolyData.SetPoints(points)
# Create a cell array to store the polygon in
aCellArray = vtkCellArray()
# Define a polygonal hole with a clockwise polygon
aPolygon = vtkPolygon()
aPolygon.GetPointIds().InsertNextId(22)
aPolygon.GetPointIds().InsertNextId(23)
aPolygon.GetPointIds().InsertNextId(24)
aPolygon.GetPointIds().InsertNextId(25)
aPolygon.GetPointIds().InsertNextId(35)
aPolygon.GetPointIds().InsertNextId(45)
aPolygon.GetPointIds().InsertNextId(44)
aPolygon.GetPointIds().InsertNextId(43)
aPolygon.GetPointIds().InsertNextId(42)
aPolygon.GetPointIds().InsertNextId(32)
aCellArray.InsertNextCell(aPolygon)
# Create a polydata to store the boundary. The points must be the
# same as the points we will triangulate.
boundary = vtkPolyData()
boundary.SetPoints(aPolyData.GetPoints())
boundary.SetPolys(aCellArray)
# Triangulate the grid points
delaunay = vtkDelaunay2D()
delaunay.SetInputData(aPolyData)
delaunay.SetSourceData(boundary)
# Visualize
meshMapper = vtkPolyDataMapper()
meshMapper.SetInputConnection(delaunay.GetOutputPort())
meshActor = vtkActor()
meshActor.SetMapper(meshMapper)
meshActor.GetProperty().EdgeVisibilityOn()
meshActor.GetProperty().SetEdgeColor(colors.GetColor3d('Peacock'))
meshActor.GetProperty().SetInterpolationToFlat()
boundaryMapper = vtkPolyDataMapper()
boundaryMapper.SetInputData(boundary)
boundaryActor = vtkActor()
boundaryActor.SetMapper(boundaryMapper)
boundaryActor.GetProperty().SetColor(colors.GetColor3d('Raspberry'))
boundaryActor.GetProperty().SetLineWidth(3)
boundaryActor.GetProperty().EdgeVisibilityOn()
boundaryActor.GetProperty().SetEdgeColor(colors.GetColor3d('Red'))
boundaryActor.GetProperty().SetRepresentationToWireframe()
# Create a renderer, render window, and interactor
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
# Add the actor to the scene
renderer.AddActor(meshActor)
renderer.AddActor(boundaryActor)
renderer.SetBackground(colors.GetColor3d('Mint'))
# Render and interact
renderWindow.SetSize(640, 480)
renderWindow.SetWindowName('ConstrainedDelaunay2D')
renderWindow.Render()
renderWindowInteractor.Start()
if __name__ == '__main__':
main()
Delaunay2D
#!/usr/bin/python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkPoints
from vtkmodules.vtkCommonDataModel import vtkPolyData
from vtkmodules.vtkFiltersCore import vtkDelaunay2D
from vtkmodules.vtkFiltersGeneral import vtkVertexGlyphFilter
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
# Create a set of heights on a grid.
# This is often called a "terrain map".
points = vtkPoints()
gridSize = 10
for x in range(gridSize):
for y in range(gridSize):
points.InsertNextPoint(x, y, int((x + y) / (y + 1)))
# Add the grid points to a polydata object
polydata = vtkPolyData()
polydata.SetPoints(points)
delaunay = vtkDelaunay2D()
delaunay.SetInputData(polydata)
# Visualize
meshMapper = vtkPolyDataMapper()
meshMapper.SetInputConnection(delaunay.GetOutputPort())
meshActor = vtkActor()
meshActor.SetMapper(meshMapper)
meshActor.GetProperty().SetColor(colors.GetColor3d('Banana'))
meshActor.GetProperty().EdgeVisibilityOn()
glyphFilter = vtkVertexGlyphFilter()
glyphFilter.SetInputData(polydata)
pointMapper = vtkPolyDataMapper()
pointMapper.SetInputConnection(glyphFilter.GetOutputPort())
pointActor = vtkActor()
pointActor.GetProperty().SetColor(colors.GetColor3d('Tomato'))
pointActor.GetProperty().SetPointSize(5)
pointActor.SetMapper(pointMapper)
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
renderer.AddActor(meshActor)
renderer.AddActor(pointActor)
renderer.SetBackground(colors.GetColor3d('Mint'))
renderWindowInteractor.Initialize()
renderWindow.SetWindowName('Delaunay2D')
renderWindow.Render()
renderWindowInteractor.Start()
if __name__ == '__main__':
main()
GaussianSplat
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonDataModel import vtkPolyData
from vtkmodules.vtkFiltersCore import vtkContourFilter
from vtkmodules.vtkFiltersSources import vtkSphereSource
from vtkmodules.vtkImagingHybrid import vtkGaussianSplatter
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
# Create points on a sphere
sphereSource = vtkSphereSource()
sphereSource.Update()
colors = vtkNamedColors()
polydata = vtkPolyData()
polydata.SetPoints(sphereSource.GetOutput().GetPoints())
splatter = vtkGaussianSplatter()
splatter.SetInputData(polydata)
splatter.SetSampleDimensions(50, 50, 50)
splatter.SetRadius(0.5)
splatter.ScalarWarpingOff()
surface = vtkContourFilter()
surface.SetInputConnection(splatter.GetOutputPort())
surface.SetValue(0, 0.01)
# Create a mapper and actor
mapper = vtkPolyDataMapper()
mapper.SetInputConnection(surface.GetOutputPort())
actor = vtkActor()
actor.SetMapper(mapper)
# Visualize
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
renderer.AddActor(actor)
renderer.SetBackground(colors.GetColor3d('SteelBlue'))
renderWindow.SetWindowName('GaussianSplat')
renderWindow.Render()
renderWindowInteractor.Start()
if __name__ == '__main__':
main()
Glyph2D
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkPoints
from vtkmodules.vtkCommonDataModel import vtkPolyData
from vtkmodules.vtkFiltersCore import vtkGlyph2D
from vtkmodules.vtkFiltersSources import vtkRegularPolygonSource
from vtkmodules.vtkInteractionStyle import vtkInteractorStyleImage
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
points = vtkPoints()
points.InsertNextPoint(0, 0, 0)
points.InsertNextPoint(1, 1, 0)
points.InsertNextPoint(2, 2, 0)
polydata = vtkPolyData()
polydata.SetPoints(points)
# Create anything you want here, we will use a polygon for the demo.
polygonSource = vtkRegularPolygonSource() # default is 6 sides
glyph2D = vtkGlyph2D()
glyph2D.SetSourceConnection(polygonSource.GetOutputPort())
glyph2D.SetInputData(polydata)
glyph2D.Update()
mapper = vtkPolyDataMapper()
mapper.SetInputConnection(glyph2D.GetOutputPort())
mapper.Update()
actor = vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetColor(colors.GetColor3d('Salmon'))
# Visualize
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
renderer.AddActor(actor)
renderer.SetBackground(colors.GetColor3d('SlateGray'))
style = vtkInteractorStyleImage()
renderWindowInteractor.SetInteractorStyle(style)
renderWindow.SetWindowName('Glyph2D');
renderWindow.Render()
renderWindowInteractor.Start()
if __name__ == '__main__':
main()
Glyph3D
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkPoints
from vtkmodules.vtkCommonDataModel import vtkPolyData
from vtkmodules.vtkFiltersCore import vtkGlyph3D
from vtkmodules.vtkFiltersSources import vtkCubeSource
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
points = vtkPoints()
points.InsertNextPoint(0, 0, 0)
points.InsertNextPoint(1, 1, 1)
points.InsertNextPoint(2, 2, 2)
polydata = vtkPolyData()
polydata.SetPoints(points)
# Create anything you want here, we will use a cube for the demo.
cubeSource = vtkCubeSource()
glyph3D = vtkGlyph3D()
glyph3D.SetSourceConnection(cubeSource.GetOutputPort())
glyph3D.SetInputData(polydata)
glyph3D.Update()
# Visualize
mapper = vtkPolyDataMapper()
mapper.SetInputConnection(glyph3D.GetOutputPort())
actor = vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetColor(colors.GetColor3d('Salmon'))
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
renderer.AddActor(actor)
renderer.SetBackground(colors.GetColor3d('SlateGray')) # Background Slate Gray
renderWindow.SetWindowName('Glyph2D');
renderWindow.Render()
renderWindowInteractor.Start()
if __name__ == '__main__':
main()
PerlinNoise
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonDataModel import vtkPerlinNoise
from vtkmodules.vtkFiltersCore import vtkContourFilter
from vtkmodules.vtkImagingHybrid import vtkSampleFunction
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
perlinNoise = vtkPerlinNoise()
perlinNoise.SetFrequency(2, 1.25, 1.5)
perlinNoise.SetPhase(0, 0, 0)
sample = vtkSampleFunction()
sample.SetImplicitFunction(perlinNoise)
sample.SetSampleDimensions(65, 65, 20)
sample.ComputeNormalsOff()
surface = vtkContourFilter()
surface.SetInputConnection(sample.GetOutputPort())
surface.SetValue(0, 0.0)
mapper = vtkPolyDataMapper()
mapper.SetInputConnection(surface.GetOutputPort())
mapper.ScalarVisibilityOff()
actor = vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetColor(colors.GetColor3d('SteelBlue'))
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.AddRenderer(renderer)
interactor = vtkRenderWindowInteractor()
interactor.SetRenderWindow(renderWindow)
# Add the actors to the renderer, set the background and size
renderer.AddActor(actor)
renderer.SetBackground(colors.GetColor3d('SlateGray'))
renderWindow.SetWindowName('PerlinNoise')
renderWindow.SetSize(300, 300)
renderer.ResetCamera()
renderWindow.Render()
interactor.Start()
if __name__ == '__main__':
main()
TransformPolyData
Description
This example demonstrates how to apply a transform to a data set. It uses vtkTransformPolyDataFilter, but it can be
replaced with vtkTransformFilter for different types of data sets, including vtkUnstructuredGrid and vtkStructuredGrid.
vtkTransformFilter will work with vtkPolyData, too).
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonTransforms import vtkTransform
from vtkmodules.vtkFiltersGeneral import vtkTransformPolyDataFilter
from vtkmodules.vtkFiltersSources import vtkSphereSource
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
# Create the polydata geometry
sphereSource = vtkSphereSource()
sphereSource.Update()
# Set up the actor to display the untransformed polydata
originalMapper = vtkPolyDataMapper()
originalMapper.SetInputConnection(sphereSource.GetOutputPort())
originalActor = vtkActor()
originalActor.SetMapper(originalMapper)
originalActor.GetProperty().SetColor(colors.GetColor3d('Blue'))
# Set up the transform filter
translation = vtkTransform()
translation.Translate(1.0, 2.0, 3.0)
transformFilter = vtkTransformPolyDataFilter()
transformFilter.SetInputConnection(sphereSource.GetOutputPort())
transformFilter.SetTransform(translation)
transformFilter.Update()
# Set up the actor to display the transformed polydata
transformedMapper = vtkPolyDataMapper()
transformedMapper.SetInputConnection(transformFilter.GetOutputPort())
transformedActor = vtkActor()
transformedActor.SetMapper(transformedMapper)
transformedActor.GetProperty().SetColor(colors.GetColor3d('Red'))
# Set up the rest of the visualization pipeline
renderer = vtkRenderer()
renderer.AddActor(originalActor)
renderer.AddActor(transformedActor)
renderer.SetBackground(colors.GetColor3d('Green'))
renderWindow = vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
renderWindow.SetWindowName('TransformPolyData')
renderWindow.Render()
renderWindowInteractor.Start()
if __name__ == '__main__':
main()
TriangulateTerrainMap
Description
This example generates heights (z-values) on a 10x10 grid (a terrain map) and triangulates the points.
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import (
vtkMinimalStandardRandomSequence,
vtkPoints
)
from vtkmodules.vtkCommonDataModel import vtkPolyData
from vtkmodules.vtkFiltersCore import vtkDelaunay2D
from vtkmodules.vtkFiltersGeneral import vtkVertexGlyphFilter
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
# Create points on an XY grid with random Z coordinate
points = vtkPoints()
gridSize = 10
seed = 0
randomSequence = vtkMinimalStandardRandomSequence()
randomSequence.Initialize(seed)
for x in range(0, gridSize):
for y in range(0, gridSize):
d = randomSequence.GetValue()
randomSequence.Next()
points.InsertNextPoint(x, y, d * 3)
# Add the grid points to a polydata object
polydata = vtkPolyData()
polydata.SetPoints(points)
glyphFilter = vtkVertexGlyphFilter()
glyphFilter.SetInputData(polydata)
glyphFilter.Update()
# Create a mapper and actor
pointsMapper = vtkPolyDataMapper()
pointsMapper.SetInputConnection(glyphFilter.GetOutputPort())
pointsActor = vtkActor()
pointsActor.SetMapper(pointsMapper)
pointsActor.GetProperty().SetPointSize(3)
pointsActor.GetProperty().SetColor(colors.GetColor3d("Red"))
# Triangulate the grid points
delaunay = vtkDelaunay2D()
delaunay.SetInputData(polydata)
delaunay.Update()
# Create a mapper and actor
triangulatedMapper = vtkPolyDataMapper()
triangulatedMapper.SetInputConnection(delaunay.GetOutputPort())
triangulatedActor = vtkActor()
triangulatedActor.SetMapper(triangulatedMapper)
# Create a renderer, render window, and interactor
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
# Add the actor to the scene
renderer.AddActor(pointsActor)
renderer.AddActor(triangulatedActor)
renderer.SetBackground(colors.GetColor3d("Green")) # Background color green
# Render and interact
renderWindow.SetWindowName('TriangulateTerrainMap')
renderWindow.Render()
renderWindowInteractor.Start()
if __name__ == '__main__':
main()
VertexGlyphFilter
Description
This example creates a set of points and adds a vertex at each point using vtkVertexGlyphFilter.
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkPoints
from vtkmodules.vtkCommonDataModel import vtkPolyData
from vtkmodules.vtkFiltersGeneral import vtkVertexGlyphFilter
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
points = vtkPoints()
points.InsertNextPoint(0, 0, 0)
points.InsertNextPoint(1, 1, 1)
points.InsertNextPoint(2, 2, 2)
polydata = vtkPolyData()
polydata.SetPoints(points)
vertexGlyphFilter = vtkVertexGlyphFilter()
vertexGlyphFilter.AddInputData(polydata)
vertexGlyphFilter.Update()
# Create a mapper and actor
mapper = vtkPolyDataMapper()
mapper.SetInputConnection(vertexGlyphFilter.GetOutputPort())
actor = vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetPointSize(10)
actor.GetProperty().SetColor(colors.GetColor3d('Yellow'))
# Create a renderer, render window, and interactor
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
# Add the actor to the scene
renderer.AddActor(actor)
renderer.SetBackground(colors.GetColor3d('Green'))
# Render and interact
renderWindow.SetWindowName('VertexGlyphFilter')
renderWindow.Render()
renderWindowInteractor.Start()
if __name__ == '__main__':
main()
WarpTo
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkFiltersCore import vtkTubeFilter
from vtkmodules.vtkFiltersGeneral import vtkWarpTo
from vtkmodules.vtkFiltersSources import vtkLineSource
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkDataSetMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
# Create the RenderWindow, Renderer and both Actors
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
# Create a line
lineSource = vtkLineSource()
lineSource.SetPoint1(0.0, 0.0, 0.0)
lineSource.SetPoint2(0.0, 1.0, 0.0)
lineSource.SetResolution(20)
lineSource.Update()
# Create a tube (cylinder) around the line
tubeFilter = vtkTubeFilter()
tubeFilter.SetInputConnection(lineSource.GetOutputPort())
tubeFilter.SetRadius(.01) # default is .5
tubeFilter.SetNumberOfSides(50)
tubeFilter.Update()
warpTo = vtkWarpTo()
warpTo.SetInputConnection(tubeFilter.GetOutputPort())
warpTo.SetPosition(10, 1, 0)
warpTo.SetScaleFactor(5)
warpTo.AbsoluteOn()
mapper = vtkDataSetMapper()
mapper.SetInputConnection(warpTo.GetOutputPort())
mapper.ScalarVisibilityOff()
actor = vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetColor(colors.GetColor3d('Gold'))
renderer.SetBackground(colors.GetColor3d('Green'))
renderer.AddActor(actor)
renderWindow.SetWindowName('WarpTo')
renderWindow.Render()
renderWindowInteractor.Initialize()
renderWindowInteractor.Start()
if __name__ == '__main__':
main()
Arrow
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkFiltersSources import vtkArrowSource
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
arrowSource = vtkArrowSource()
# arrowSource.SetShaftRadius(0.01)
# arrowSource.SetTipLength(.9)
# Create a mapper and actor
mapper = vtkPolyDataMapper()
mapper.SetInputConnection(arrowSource.GetOutputPort())
actor = vtkActor()
actor.SetMapper(mapper)
# Visualize
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.SetWindowName('Arrow')
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
renderer.AddActor(actor)
renderer.SetBackground(colors.GetColor3d('MidnightBlue'))
renderWindow.SetWindowName('Arrow')
renderWindow.Render()
renderWindowInteractor.Start()
if __name__ == '__main__':
main()
Axes
Description
This example shows how to position an vtkAxesActor in 3D. Notice that position and orientation of the vtkAxesActor is
done with a user transform.
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonTransforms import vtkTransform
from vtkmodules.vtkFiltersSources import vtkSphereSource
from vtkmodules.vtkRenderingAnnotation import vtkAxesActor
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
# create a Sphere
sphereSource = vtkSphereSource()
sphereSource.SetCenter(0.0, 0.0, 0.0)
sphereSource.SetRadius(0.5)
# create a mapper
sphereMapper = vtkPolyDataMapper()
sphereMapper.SetInputConnection(sphereSource.GetOutputPort())
# create an actor
sphereActor = vtkActor()
sphereActor.SetMapper(sphereMapper)
# a renderer and render window
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.SetWindowName('Axes')
renderWindow.AddRenderer(renderer)
# an interactor
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
# add the actors to the scene
renderer.AddActor(sphereActor)
renderer.SetBackground(colors.GetColor3d('SlateGray'))
transform = vtkTransform()
transform.Translate(1.0, 0.0, 0.0)
axes = vtkAxesActor()
# The axes are positioned with a user transform
axes.SetUserTransform(transform)
# properties of the axes labels can be set as follows
# this sets the x axis label to red
# axes.GetXAxisCaptionActor2D().GetCaptionTextProperty().SetColor(colors.GetColor3d('Red'));
# the actual text of the axis label can be changed:
# axes->SetXAxisLabelText('test');
renderer.AddActor(axes)
renderer.GetActiveCamera().Azimuth(50)
renderer.GetActiveCamera().Elevation(-30)
renderer.ResetCamera()
renderWindow.SetWindowName('Axes')
renderWindow.Render()
# begin mouse interaction
renderWindowInteractor.Start()
if __name__ == '__main__':
main()
Cell3DDemonstration
Description
This is a demonstration of how to construct and display geometric objects using the classes derived from vtkCell3D. For
each object we specify the points and cell Ids.
From this we create an unstructured grid. In some cases a vtkCellArray is used and the result is added to the
unstructured grid, see: MakePolyhedron() and MakeTetrahedron().
Also demonstrated is the use of vectors to hold the unstructured grids, mappers, actors and renderers.
The resultant objects are then displayed in a grid.
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingFreeType
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import (
vtkIdList,
vtkPoints
)
from vtkmodules.vtkCommonDataModel import (
VTK_POLYHEDRON,
VTK_TETRA,
vtkCellArray,
vtkHexagonalPrism,
vtkHexahedron,
vtkPentagonalPrism,
vtkPyramid,
vtkTetra,
vtkUnstructuredGrid,
vtkVoxel,
vtkWedge
)
from vtkmodules.vtkIOImage import vtkPNGWriter
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkActor2D,
vtkDataSetMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer,
vtkTextMapper,
vtkTextProperty,
vtkWindowToImageFilter
)
def main():
colors = vtkNamedColors()
# Set the background color.
colors.SetColor('BkgColor', [51, 77, 102, 255])
titles = list()
textMappers = list()
textActors = list()
uGrids = list()
mappers = list()
actors = list()
renderers = list()
uGrids.append(MakeHexagonalPrism())
titles.append('Hexagonal Prism')
uGrids.append(MakeHexahedron())
titles.append('Hexahedron')
uGrids.append(MakePentagonalPrism())
titles.append('Pentagonal Prism')
uGrids.append(MakePolyhedron())
titles.append('Polyhedron')
uGrids.append(MakePyramid())
titles.append('Pyramid')
uGrids.append(MakeTetrahedron())
titles.append('Tetrahedron')
uGrids.append(MakeVoxel())
titles.append('Voxel')
uGrids.append(MakeWedge())
titles.append('Wedge')
renWin = vtkRenderWindow()
renWin.SetWindowName('Cell3DDemonstration')
iRen = vtkRenderWindowInteractor()
iRen.SetRenderWindow(renWin)
# Create one text property for all
textProperty = vtkTextProperty()
textProperty.SetFontSize(16)
textProperty.SetJustificationToCentered()
textProperty.SetColor(colors.GetColor3d('LightGoldenrodYellow'))
# Create and link the mappers actors and renderers together.
for i in range(0, len(uGrids)):
textMappers.append(vtkTextMapper())
textActors.append(vtkActor2D())
mappers.append(vtkDataSetMapper())
actors.append(vtkActor())
renderers.append(vtkRenderer())
mappers[i].SetInputData(uGrids[i])
actors[i].SetMapper(mappers[i])
actors[i].GetProperty().SetColor(colors.GetColor3d('PeachPuff'))
renderers[i].AddViewProp(actors[i])
textMappers[i].SetInput(titles[i])
textMappers[i].SetTextProperty(textProperty)
textActors[i].SetMapper(textMappers[i])
textActors[i].SetPosition(120, 16)
renderers[i].AddViewProp(textActors[i])
renWin.AddRenderer(renderers[i])
gridDimensions = 3
rendererSize = 300
renWin.SetSize(rendererSize * gridDimensions,
rendererSize * gridDimensions)
for row in range(0, gridDimensions):
for col in range(0, gridDimensions):
index = row * gridDimensions + col
# (xmin, ymin, xmax, ymax)
viewport = [
float(col) * rendererSize /
(gridDimensions * rendererSize),
float(gridDimensions - (row + 1)) * rendererSize /
(gridDimensions * rendererSize),
float(col + 1) * rendererSize /
(gridDimensions * rendererSize),
float(gridDimensions - row) * rendererSize /
(gridDimensions * rendererSize)]
if index > len(actors) - 1:
# Add a renderer even if there is no actor.
# This makes the render window background all the same color.
ren = vtkRenderer()
ren.SetBackground(colors.GetColor3d('BkgColor'))
ren.SetViewport(viewport)
renWin.AddRenderer(ren)
continue
renderers[index].SetViewport(viewport)
renderers[index].SetBackground(colors.GetColor3d('BkgColor'))
renderers[index].ResetCamera()
renderers[index].GetActiveCamera().Azimuth(30)
renderers[index].GetActiveCamera().Elevation(-30)
renderers[index].GetActiveCamera().Zoom(0.85)
renderers[index].ResetCameraClippingRange()
iRen.Initialize()
renWin.SetWindowName('Cell3DDemonstration')
renWin.Render()
iRen.Start()
def MakeHexagonalPrism():
"""
3D: hexagonal prism: a wedge with an hexagonal base.
Be careful, the base face ordering is different from wedge.
"""
numberOfVertices = 12
points = vtkPoints()
points.InsertNextPoint(0.0, 0.0, 1.0)
points.InsertNextPoint(1.0, 0.0, 1.0)
points.InsertNextPoint(1.5, 0.5, 1.0)
points.InsertNextPoint(1.0, 1.0, 1.0)
points.InsertNextPoint(0.0, 1.0, 1.0)
points.InsertNextPoint(-0.5, 0.5, 1.0)
points.InsertNextPoint(0.0, 0.0, 0.0)
points.InsertNextPoint(1.0, 0.0, 0.0)
points.InsertNextPoint(1.5, 0.5, 0.0)
points.InsertNextPoint(1.0, 1.0, 0.0)
points.InsertNextPoint(0.0, 1.0, 0.0)
points.InsertNextPoint(-0.5, 0.5, 0.0)
hexagonalPrism = vtkHexagonalPrism()
for i in range(0, numberOfVertices):
hexagonalPrism.GetPointIds().SetId(i, i)
ug = vtkUnstructuredGrid()
ug.InsertNextCell(hexagonalPrism.GetCellType(),
hexagonalPrism.GetPointIds())
ug.SetPoints(points)
return ug
def MakeHexahedron():
"""
A regular hexagon (cube) with all faces square and three squares around
each vertex is created below.
Setup the coordinates of eight points
(the two faces must be in counter clockwise
order as viewed from the outside).
As an exercise you can modify the coordinates of the points to create
seven topologically distinct convex hexahedras.
"""
numberOfVertices = 8
# Create the points
points = vtkPoints()
points.InsertNextPoint(0.0, 0.0, 0.0)
points.InsertNextPoint(1.0, 0.0, 0.0)
points.InsertNextPoint(1.0, 1.0, 0.0)
points.InsertNextPoint(0.0, 1.0, 0.0)
points.InsertNextPoint(0.0, 0.0, 1.0)
points.InsertNextPoint(1.0, 0.0, 1.0)
points.InsertNextPoint(1.0, 1.0, 1.0)
points.InsertNextPoint(0.0, 1.0, 1.0)
# Create a hexahedron from the points
hex_ = vtkHexahedron()
for i in range(0, numberOfVertices):
hex_.GetPointIds().SetId(i, i)
# Add the points and hexahedron to an unstructured grid
uGrid = vtkUnstructuredGrid()
uGrid.SetPoints(points)
uGrid.InsertNextCell(hex_.GetCellType(), hex_.GetPointIds())
return uGrid
def MakePentagonalPrism():
numberOfVertices = 10
# Create the points
points = vtkPoints()
points.InsertNextPoint(11, 10, 10)
points.InsertNextPoint(13, 10, 10)
points.InsertNextPoint(14, 12, 10)
points.InsertNextPoint(12, 14, 10)
points.InsertNextPoint(10, 12, 10)
points.InsertNextPoint(11, 10, 14)
points.InsertNextPoint(13, 10, 14)
points.InsertNextPoint(14, 12, 14)
points.InsertNextPoint(12, 14, 14)
points.InsertNextPoint(10, 12, 14)
# Pentagonal Prism
pentagonalPrism = vtkPentagonalPrism()
for i in range(0, numberOfVertices):
pentagonalPrism.GetPointIds().SetId(i, i)
# Add the points and hexahedron to an unstructured grid
uGrid = vtkUnstructuredGrid()
uGrid.SetPoints(points)
uGrid.InsertNextCell(pentagonalPrism.GetCellType(),
pentagonalPrism.GetPointIds())
return uGrid
def MakePolyhedron():
"""
Make a regular dodecahedron. It consists of twelve regular pentagonal
faces with three faces meeting at each vertex.
"""
# numberOfVertices = 20
numberOfFaces = 12
# numberOfFaceVertices = 5
points = vtkPoints()
points.InsertNextPoint(1.21412, 0, 1.58931)
points.InsertNextPoint(0.375185, 1.1547, 1.58931)
points.InsertNextPoint(-0.982247, 0.713644, 1.58931)
points.InsertNextPoint(-0.982247, -0.713644, 1.58931)
points.InsertNextPoint(0.375185, -1.1547, 1.58931)
points.InsertNextPoint(1.96449, 0, 0.375185)
points.InsertNextPoint(0.607062, 1.86835, 0.375185)
points.InsertNextPoint(-1.58931, 1.1547, 0.375185)
points.InsertNextPoint(-1.58931, -1.1547, 0.375185)
points.InsertNextPoint(0.607062, -1.86835, 0.375185)
points.InsertNextPoint(1.58931, 1.1547, -0.375185)
points.InsertNextPoint(-0.607062, 1.86835, -0.375185)
points.InsertNextPoint(-1.96449, 0, -0.375185)
points.InsertNextPoint(-0.607062, -1.86835, -0.375185)
points.InsertNextPoint(1.58931, -1.1547, -0.375185)
points.InsertNextPoint(0.982247, 0.713644, -1.58931)
points.InsertNextPoint(-0.375185, 1.1547, -1.58931)
points.InsertNextPoint(-1.21412, 0, -1.58931)
points.InsertNextPoint(-0.375185, -1.1547, -1.58931)
points.InsertNextPoint(0.982247, -0.713644, -1.58931)
# Dimensions are [numberOfFaces][numberOfFaceVertices]
dodechedronFace = [
[0, 1, 2, 3, 4],
[0, 5, 10, 6, 1],
[1, 6, 11, 7, 2],
[2, 7, 12, 8, 3],
[3, 8, 13, 9, 4],
[4, 9, 14, 5, 0],
[15, 10, 5, 14, 19],
[16, 11, 6, 10, 15],
[17, 12, 7, 11, 16],
[18, 13, 8, 12, 17],
[19, 14, 9, 13, 18],
[19, 18, 17, 16, 15]
]
dodechedronFacesIdList = vtkIdList()
# Number faces that make up the cell.
dodechedronFacesIdList.InsertNextId(numberOfFaces)
for face in dodechedronFace:
# Number of points in the face == numberOfFaceVertices
dodechedronFacesIdList.InsertNextId(len(face))
# Insert the pointIds for that face.
[dodechedronFacesIdList.InsertNextId(i) for i in face]
uGrid = vtkUnstructuredGrid()
uGrid.InsertNextCell(VTK_POLYHEDRON, dodechedronFacesIdList)
uGrid.SetPoints(points)
return uGrid
def MakePyramid():
"""
Make a regular square pyramid.
"""
numberOfVertices = 5
points = vtkPoints()
p = [
[1.0, 1.0, 0.0],
[-1.0, 1.0, 0.0],
[-1.0, -1.0, 0.0],
[1.0, -1.0, 0.0],
[0.0, 0.0, 1.0]
]
for pt in p:
points.InsertNextPoint(pt)
pyramid = vtkPyramid()
for i in range(0, numberOfVertices):
pyramid.GetPointIds().SetId(i, i)
ug = vtkUnstructuredGrid()
ug.SetPoints(points)
ug.InsertNextCell(pyramid.GetCellType(), pyramid.GetPointIds())
return ug
def MakeTetrahedron():
"""
Make a tetrahedron.
"""
numberOfVertices = 4
points = vtkPoints()
points.InsertNextPoint(0, 0, 0)
points.InsertNextPoint(1, 0, 0)
points.InsertNextPoint(1, 1, 0)
points.InsertNextPoint(0, 1, 1)
tetra = vtkTetra()
for i in range(0, numberOfVertices):
tetra.GetPointIds().SetId(i, i)
cellArray = vtkCellArray()
cellArray.InsertNextCell(tetra)
unstructuredGrid = vtkUnstructuredGrid()
unstructuredGrid.SetPoints(points)
unstructuredGrid.SetCells(VTK_TETRA, cellArray)
return unstructuredGrid
def MakeVoxel():
"""
A voxel is a representation of a regular grid in 3-D space.
"""
numberOfVertices = 8
points = vtkPoints()
points.InsertNextPoint(0, 0, 0)
points.InsertNextPoint(1, 0, 0)
points.InsertNextPoint(0, 1, 0)
points.InsertNextPoint(1, 1, 0)
points.InsertNextPoint(0, 0, 1)
points.InsertNextPoint(1, 0, 1)
points.InsertNextPoint(0, 1, 1)
points.InsertNextPoint(1, 1, 1)
voxel = vtkVoxel()
for i in range(0, numberOfVertices):
voxel.GetPointIds().SetId(i, i)
ug = vtkUnstructuredGrid()
ug.SetPoints(points)
ug.InsertNextCell(voxel.GetCellType(), voxel.GetPointIds())
return ug
def MakeWedge():
"""
A wedge consists of two triangular ends and three rectangular faces.
"""
numberOfVertices = 6
points = vtkPoints()
points.InsertNextPoint(0, 1, 0)
points.InsertNextPoint(0, 0, 0)
points.InsertNextPoint(0, .5, .5)
points.InsertNextPoint(1, 1, 0)
points.InsertNextPoint(1, 0.0, 0.0)
points.InsertNextPoint(1, .5, .5)
wedge = vtkWedge()
for i in range(0, numberOfVertices):
wedge.GetPointIds().SetId(i, i)
ug = vtkUnstructuredGrid()
ug.SetPoints(points)
ug.InsertNextCell(wedge.GetCellType(), wedge.GetPointIds())
return ug
def WritePNG(renWin, fn, magnification=1):
"""
Screenshot
Write out a png corresponding to the render window.
:param: renWin - the render window.
:param: fn - the file name.
:param: magnification - the magnification.
"""
windowToImageFilter = vtkWindowToImageFilter()
windowToImageFilter.SetInput(renWin)
windowToImageFilter.SetMagnification(magnification)
# Record the alpha (transparency) channel
# windowToImageFilter.SetInputBufferTypeToRGBA()
windowToImageFilter.SetInputBufferTypeToRGB()
# Read from the back buffer
windowToImageFilter.ReadFrontBufferOff()
windowToImageFilter.Update()
writer = vtkPNGWriter()
writer.SetFileName(fn)
writer.SetInputConnection(windowToImageFilter.GetOutputPort())
writer.Write()
if __name__ == '__main__':
main()
CellTypeSource
Description
This example uses vtkCellTypeSource to generate a vtkUnstructuredGrid. If a cell does not fill a rectangular area or
volume, then multiple cells will be generated. For example, a vtkTetra requires 12 cells to fill a cube. A vtkTriangle
requires two cells to fill a square. vtkCellTypeSource generates a uniform set of coordinates. The example perturbs
those coordinates to illustrate the results of the vtkTessellatorFilter. Also, each cell is passed through
vtkShrinkFilter to help identify the cells. Each generated cell also has a unique color.
The example takes an optional argument, a vtkCell name.
For example, to generate vtkTriangles, run
CellTypeSource vtkTriangle
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingFreeType
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import (
vtkColorSeries,
vtkNamedColors
)
from vtkmodules.vtkCommonCore import (
vtkIntArray,
vtkLookupTable,
vtkMinimalStandardRandomSequence,
vtkPoints
)
from vtkmodules.vtkCommonDataModel import (
VTK_CUBIC_LINE,
VTK_HEXAHEDRON,
VTK_LINE,
VTK_PYRAMID,
VTK_QUAD,
VTK_QUADRATIC_EDGE,
VTK_QUADRATIC_HEXAHEDRON,
VTK_QUADRATIC_PYRAMID,
VTK_QUADRATIC_QUAD,
VTK_QUADRATIC_TETRA,
VTK_QUADRATIC_TRIANGLE,
VTK_QUADRATIC_WEDGE,
VTK_TETRA,
VTK_TRIANGLE,
VTK_WEDGE,
vtkCellTypes
)
from vtkmodules.vtkFiltersGeneral import (
vtkShrinkFilter,
vtkTessellatorFilter
)
from vtkmodules.vtkFiltersSources import vtkCellTypeSource
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkActor2D,
vtkDataSetMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer,
vtkTextMapper,
vtkTextProperty
)
def main():
cellName = get_program_parameters()
# Store the cell class names in a dictionary.
cellMap = dict()
cellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_LINE)] = VTK_LINE
cellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_QUADRATIC_EDGE)] = VTK_QUADRATIC_EDGE
cellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_CUBIC_LINE)] = VTK_CUBIC_LINE
cellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_TRIANGLE)] = VTK_TRIANGLE
cellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_QUADRATIC_TRIANGLE)] = VTK_QUADRATIC_TRIANGLE
cellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_QUAD)] = VTK_QUAD
cellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_QUADRATIC_QUAD)] = VTK_QUADRATIC_QUAD
cellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_TETRA)] = VTK_TETRA
cellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_HEXAHEDRON)] = VTK_HEXAHEDRON
cellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_WEDGE)] = VTK_WEDGE
cellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_PYRAMID)] = VTK_PYRAMID
cellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_QUADRATIC_WEDGE)] = VTK_QUADRATIC_WEDGE
cellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_QUADRATIC_PYRAMID)] = VTK_QUADRATIC_PYRAMID
cellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_QUADRATIC_HEXAHEDRON)] = VTK_QUADRATIC_HEXAHEDRON
cellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_QUADRATIC_TETRA)] = VTK_QUADRATIC_TETRA
if cellName not in cellMap:
print('Cell type ', cellName, ' is not supported.')
return
source = vtkCellTypeSource()
source.SetCellType(cellMap[cellName])
source.Update()
print('Cell: ', cellName)
originalPoints = source.GetOutput().GetPoints()
points = vtkPoints()
points.SetNumberOfPoints(source.GetOutput().GetNumberOfPoints())
rng = vtkMinimalStandardRandomSequence()
rng.SetSeed(5070) # for testing
for i in range(0, points.GetNumberOfPoints()):
perturbation = [0.0] * 3
for j in range(0, 3):
rng.Next()
perturbation[j] = rng.GetRangeValue(-0.1, 0.1)
currentPoint = [0.0] * 3
originalPoints.GetPoint(i, currentPoint)
points.SetPoint(i, currentPoint[0] + perturbation[0],
currentPoint[1] + perturbation[1],
currentPoint[2] + perturbation[2])
source.GetOutput().SetPoints(points)
numCells = source.GetOutput().GetNumberOfCells()
print('Number of cells: ', numCells)
idArray = vtkIntArray()
idArray.SetNumberOfTuples(numCells)
for i in range(0, numCells):
idArray.InsertTuple1(i, i + 1)
idArray.SetName('Ids')
source.GetOutput().GetCellData().AddArray(idArray)
source.GetOutput().GetCellData().SetActiveScalars('Ids')
shrink = vtkShrinkFilter()
shrink.SetInputConnection(source.GetOutputPort())
shrink.SetShrinkFactor(.8)
tessellate = vtkTessellatorFilter()
tessellate.SetInputConnection(shrink.GetOutputPort())
tessellate.SetMaximumNumberOfSubdivisions(3)
# Create a lookup table to map cell data to colors.
lut = vtkLookupTable()
colorSeries = vtkColorSeries()
seriesEnum = colorSeries.BREWER_QUALITATIVE_SET3
colorSeries.SetColorScheme(seriesEnum)
colorSeries.BuildLookupTable(lut, colorSeries.ORDINAL)
# Fill in a few known colors, the rest will be generated if needed.
colors = vtkNamedColors()
# Create a mapper and actor.
mapper = vtkDataSetMapper()
mapper.SetInputConnection(source.GetOutputPort())
mapper.SetInputConnection(shrink.GetOutputPort())
mapper.SetScalarRange(0, numCells + 1)
mapper.SetLookupTable(lut)
mapper.SetScalarModeToUseCellData()
mapper.SetResolveCoincidentTopologyToPolygonOffset()
if (source.GetCellType() == VTK_QUADRATIC_PYRAMID or
source.GetCellType() == VTK_QUADRATIC_WEDGE):
mapper.SetInputConnection(shrink.GetOutputPort())
else:
mapper.SetInputConnection(tessellate.GetOutputPort())
actor = vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().EdgeVisibilityOn()
# actor.GetProperty().SetLineWidth(3)
textProperty = vtkTextProperty()
textProperty.SetFontSize(20)
textProperty.SetJustificationToCentered()
textProperty.SetColor(colors.GetColor3d('Lamp_Black'))
textMapper = vtkTextMapper()
textMapper.SetInput(cellName)
textMapper.SetTextProperty(textProperty)
textActor = vtkActor2D()
textActor.SetMapper(textMapper)
textActor.SetPosition(320, 20)
# Create a renderer, render window, and interactor.
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.SetWindowName('CellTypeSource')
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
# Add the actors to the scene.
renderer.AddViewProp(textActor)
renderer.AddActor(actor)
renderer.SetBackground(colors.GetColor3d('Silver'))
renderer.ResetCamera()
renderer.GetActiveCamera().Azimuth(30)
renderer.GetActiveCamera().Elevation(30)
renderer.ResetCameraClippingRange()
# Render and interact.
renderWindow.SetSize(640, 480)
renderWindow.Render()
renderWindowInteractor.Start()
def get_program_parameters():
import argparse
description = 'Cell Type Source.'
epilogue = '''
You can supply an optional argument consisting of a vtkCell name e.g: vtkTriangle.
The default is vtkTetra.
'''
parser = argparse.ArgumentParser(description=description, epilog=epilogue,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('cell_name', nargs='?', const='vtkTetra', default='vtkTetra', type=str, help='The cell name.')
args = parser.parse_args()
return args.cell_name
if __name__ == '__main__':
main()
ConvexPointSet
Description
vtkConvexPointSet object represents a 3D cell defined by a convex set of points. An example of such a cell is an
octant (from an octree).
vtkConvexPointSet uses the ordered triangulations approach (vtkOrderedTriangulator) to create triangulations guaranteed
to be compatible across shared faces.
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkPoints
from vtkmodules.vtkCommonDataModel import (
vtkConvexPointSet,
vtkPolyData,
vtkUnstructuredGrid
)
from vtkmodules.vtkFiltersSources import vtkSphereSource
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkDataSetMapper,
vtkGlyph3DMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
cps = vtkConvexPointSet()
points = vtkPoints()
points.InsertNextPoint(0, 0, 0)
points.InsertNextPoint(1, 0, 0)
points.InsertNextPoint(1, 1, 0)
points.InsertNextPoint(0, 1, 0)
points.InsertNextPoint(0, 0, 1)
points.InsertNextPoint(1, 0, 1)
points.InsertNextPoint(1, 1, 1)
points.InsertNextPoint(0, 1, 1)
points.InsertNextPoint(0.5, 0, 0)
points.InsertNextPoint(1, 0.5, 0)
points.InsertNextPoint(0.5, 1, 0)
points.InsertNextPoint(0, 0.5, 0)
points.InsertNextPoint(0.5, 0.5, 0)
for i in range(0, 13):
cps.GetPointIds().InsertId(i, i)
ug = vtkUnstructuredGrid()
ug.Allocate(1, 1)
ug.InsertNextCell(cps.GetCellType(), cps.GetPointIds())
ug.SetPoints(points)
colors = vtkNamedColors()
mapper = vtkDataSetMapper()
mapper.SetInputData(ug)
actor = vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetColor(colors.GetColor3d("Tomato"))
actor.GetProperty().SetLineWidth(3)
actor.GetProperty().EdgeVisibilityOn()
# Glyph the points
sphere = vtkSphereSource()
sphere.SetPhiResolution(21)
sphere.SetThetaResolution(21)
sphere.SetRadius(.03)
# Create a polydata to store everything in
polyData = vtkPolyData()
polyData.SetPoints(points)
pointMapper = vtkGlyph3DMapper()
pointMapper.SetInputData(polyData)
pointMapper.SetSourceConnection(sphere.GetOutputPort())
pointActor = vtkActor()
pointActor.SetMapper(pointMapper)
pointActor.GetProperty().SetColor(colors.GetColor3d("Peacock"))
# Create a renderer, render window, and interactor
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.SetWindowName("ConvexPointSet")
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
# Add the actors to the scene
renderer.AddActor(actor)
renderer.AddActor(pointActor)
renderer.SetBackground(colors.GetColor3d("Silver"))
renderer.ResetCamera()
renderer.GetActiveCamera().Azimuth(210)
renderer.GetActiveCamera().Elevation(30)
renderer.ResetCameraClippingRange()
# Render and interact
renderWindow.SetSize(640, 480)
renderWindow.Render()
renderWindowInteractor.Start()
if __name__ == '__main__':
main()
Disk
Description
vtkDiskSource objects creates a polygonal disk with a hole in the center.
The disk has zero height. The user can specify the inner and outer radius of the disk, and the radial and
circumferential resolution of the polygonal representation.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkFiltersSources import vtkDiskSource
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
diskSource = vtkDiskSource()
# Create a mapper and actor.
mapper = vtkPolyDataMapper()
mapper.SetInputConnection(diskSource.GetOutputPort())
actor = vtkActor()
actor.GetProperty().SetColor(colors.GetColor3d("Cornsilk"))
actor.SetMapper(mapper)
# Create a renderer, render window, and interactor
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.SetWindowName("Disk")
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
# Add the actors to the scene
renderer.AddActor(actor)
renderer.SetBackground(colors.GetColor3d("DarkGreen"))
# Render and interact
renderWindow.Render()
renderWindowInteractor.Start()
if __name__ == '__main__':
main()
ShrinkCube
Description
Generates a cube using vtkCubeSource, then a shrink filter is applied.
vtkShrinkFilter object shrinks cells composing an arbitrary data set towards their centroid. The centroid of a cell is computed as the average position of the cell points. Shrinking results in disconnecting the cells from one another.
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkFiltersGeneral import vtkShrinkFilter
from vtkmodules.vtkFiltersSources import vtkCubeSource
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkDataSetMapper,
vtkProperty,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
# Create a cube.
cubeSource = vtkCubeSource()
shrink = vtkShrinkFilter()
shrink.SetInputConnection(cubeSource.GetOutputPort())
shrink.SetShrinkFactor(0.9)
# Create a mapper and actor.
mapper = vtkDataSetMapper()
mapper.SetInputConnection(shrink.GetOutputPort())
back = vtkProperty()
back.SetColor(colors.GetColor3d('Tomato'))
actor = vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().EdgeVisibilityOn()
actor.GetProperty().SetColor(colors.GetColor3d('Banana'))
actor.SetBackfaceProperty(back)
# Create a renderer, render window, and interactor.
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
# Add the actors to the scene
renderer.AddActor(actor)
renderer.SetBackground(colors.GetColor3d('Silver'))
renderer.ResetCamera()
renderer.GetActiveCamera().Azimuth(30)
renderer.GetActiveCamera().Elevation(30)
renderer.ResetCameraClippingRange()
# Render and interact
renderWindow.SetWindowName('ShrinkCube')
renderWindow.Render()
renderWindowInteractor.Start()
if __name__ == '__main__':
main()
SourceObjectsDemo
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingFreeType
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkFiltersSources import (
vtkConeSource,
vtkCubeSource,
vtkCylinderSource,
vtkDiskSource,
vtkLineSource,
vtkPlaneSource,
vtkPointSource,
vtkSphereSource,
vtkTextSource
)
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkActor2D,
vtkPolyDataMapper,
vtkProperty,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer,
vtkTextMapper,
vtkTextProperty
)
def main():
colors = vtkNamedColors()
# Set the background color.
colors.SetColor('BkgColor', [51, 77, 102, 255])
sourceObjects = list()
sourceObjects.append(vtkSphereSource())
sourceObjects[-1].SetPhiResolution(21)
sourceObjects[-1].SetThetaResolution(21)
sourceObjects.append(vtkConeSource())
sourceObjects[-1].SetResolution(51)
sourceObjects.append(vtkCylinderSource())
sourceObjects[-1].SetResolution(51)
sourceObjects.append(vtkCubeSource())
sourceObjects.append(vtkPlaneSource())
sourceObjects.append(vtkTextSource())
sourceObjects[-1].SetText('Hello')
sourceObjects[-1].BackingOff()
sourceObjects.append(vtkPointSource())
sourceObjects[-1].SetNumberOfPoints(500)
sourceObjects.append(vtkDiskSource())
sourceObjects[-1].SetCircumferentialResolution(51)
sourceObjects.append(vtkLineSource())
renderers = list()
mappers = list()
actors = list()
textmappers = list()
textactors = list()
# Create one text property for all.
textProperty = vtkTextProperty()
textProperty.SetFontSize(16)
textProperty.SetJustificationToCentered()
textProperty.SetColor(colors.GetColor3d('LightGoldenrodYellow'))
backProperty = vtkProperty()
backProperty.SetColor(colors.GetColor3d('Tomato'))
# Create a source, renderer, mapper, and actor
# for each object.
for i in range(0, len(sourceObjects)):
mappers.append(vtkPolyDataMapper())
mappers[i].SetInputConnection(sourceObjects[i].GetOutputPort())
actors.append(vtkActor())
actors[i].SetMapper(mappers[i])
actors[i].GetProperty().SetColor(colors.GetColor3d('PeachPuff'))
actors[i].SetBackfaceProperty(backProperty)
textmappers.append(vtkTextMapper())
textmappers[i].SetInput(sourceObjects[i].GetClassName())
textmappers[i].SetTextProperty(textProperty)
textactors.append(vtkActor2D())
textactors[i].SetMapper(textmappers[i])
textactors[i].SetPosition(120, 16)
renderers.append(vtkRenderer())
gridDimensions = 3
# We need a renderer even if there is no actor.
for i in range(len(sourceObjects), gridDimensions ** 2):
renderers.append(vtkRenderer())
renderWindow = vtkRenderWindow()
renderWindow.SetWindowName('SourceObjectsDemo')
rendererSize = 300
renderWindow.SetSize(rendererSize * gridDimensions, rendererSize * gridDimensions)
for row in range(0, gridDimensions):
for col in range(0, gridDimensions):
index = row * gridDimensions + col
x0 = float(col) / gridDimensions
y0 = float(gridDimensions - row - 1) / gridDimensions
x1 = float(col + 1) / gridDimensions
y1 = float(gridDimensions - row) / gridDimensions
renderWindow.AddRenderer(renderers[index])
renderers[index].SetViewport(x0, y0, x1, y1)
if index > (len(sourceObjects) - 1):
continue
renderers[index].AddActor(actors[index])
renderers[index].AddActor(textactors[index])
renderers[index].SetBackground(colors.GetColor3d('BkgColor'))
renderers[index].ResetCamera()
renderers[index].GetActiveCamera().Azimuth(30)
renderers[index].GetActiveCamera().Elevation(30)
renderers[index].GetActiveCamera().Zoom(0.8)
renderers[index].ResetCameraClippingRange()
interactor = vtkRenderWindowInteractor()
interactor.SetRenderWindow(renderWindow)
renderWindow.Render()
interactor.Start()
if __name__ == '__main__':
main()
OrientedArrow
Description
This example illustrates how to create and display an arrow that passes through two points.
It demonstrates two different ways to apply the transform:
-
Use vtkTransformPolyDataFilter to create a new transformed polydata. This method is useful if the transformed
polydata is needed later in the pipeline, e.g. vtkGlyph3DFilter. -
Apply the transform directly to the actor using vtkProp3D’s SetUserMatrix. No new data is produced.
Switch between the two methods by #defining USER_MATRIX or leaving out the #define.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import (
vtkMath,
vtkMinimalStandardRandomSequence
)
from vtkmodules.vtkCommonMath import vtkMatrix4x4
from vtkmodules.vtkCommonTransforms import vtkTransform
from vtkmodules.vtkFiltersGeneral import vtkTransformPolyDataFilter
from vtkmodules.vtkFiltersSources import (
vtkArrowSource,
vtkSphereSource
)
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
"""
There are two alternative ways to apply the transform.
1) Use vtkTransformPolyDataFilter to create a new transformed polydata.
This method is useful if the transformed polydata is needed
later in the pipeline
To do this, set USER_MATRIX = True
2) Apply the transform directly to the actor using vtkProp3D's SetUserMatrix.
No new data is produced.
To do this, set USER_MATRIX = False
"""
USER_MATRIX = True
def main():
colors = vtkNamedColors()
# Set the background color.
colors.SetColor('BkgColor', [26, 51, 77, 255])
# Create an arrow.
arrowSource = vtkArrowSource()
# Generate a random start and end point
startPoint = [0] * 3
endPoint = [0] * 3
rng = vtkMinimalStandardRandomSequence()
rng.SetSeed(8775070) # For testing.
for i in range(0, 3):
rng.Next()
startPoint[i] = rng.GetRangeValue(-10, 10)
rng.Next()
endPoint[i] = rng.GetRangeValue(-10, 10)
# Compute a basis
normalizedX = [0] * 3
normalizedY = [0] * 3
normalizedZ = [0] * 3
# The X axis is a vector from start to end
vtkMath.Subtract(endPoint, startPoint, normalizedX)
length = vtkMath.Norm(normalizedX)
vtkMath.Normalize(normalizedX)
# The Z axis is an arbitrary vector cross X
arbitrary = [0] * 3
for i in range(0, 3):
rng.Next()
arbitrary[i] = rng.GetRangeValue(-10, 10)
vtkMath.Cross(normalizedX, arbitrary, normalizedZ)
vtkMath.Normalize(normalizedZ)
# The Y axis is Z cross X
vtkMath.Cross(normalizedZ, normalizedX, normalizedY)
matrix = vtkMatrix4x4()
# Create the direction cosine matrix
matrix.Identity()
for i in range(0, 3):
matrix.SetElement(i, 0, normalizedX[i])
matrix.SetElement(i, 1, normalizedY[i])
matrix.SetElement(i, 2, normalizedZ[i])
# Apply the transforms
transform = vtkTransform()
transform.Translate(startPoint)
transform.Concatenate(matrix)
transform.Scale(length, length, length)
# Transform the polydata
transformPD = vtkTransformPolyDataFilter()
transformPD.SetTransform(transform)
transformPD.SetInputConnection(arrowSource.GetOutputPort())
# Create a mapper and actor for the arrow
mapper = vtkPolyDataMapper()
actor = vtkActor()
if USER_MATRIX:
mapper.SetInputConnection(arrowSource.GetOutputPort())
actor.SetUserMatrix(transform.GetMatrix())
else:
mapper.SetInputConnection(transformPD.GetOutputPort())
actor.SetMapper(mapper)
actor.GetProperty().SetColor(colors.GetColor3d('Cyan'))
# Create spheres for start and end point
sphereStartSource = vtkSphereSource()
sphereStartSource.SetCenter(startPoint)
sphereStartSource.SetRadius(0.8)
sphereStartMapper = vtkPolyDataMapper()
sphereStartMapper.SetInputConnection(sphereStartSource.GetOutputPort())
sphereStart = vtkActor()
sphereStart.SetMapper(sphereStartMapper)
sphereStart.GetProperty().SetColor(colors.GetColor3d('Yellow'))
sphereEndSource = vtkSphereSource()
sphereEndSource.SetCenter(endPoint)
sphereEndSource.SetRadius(0.8)
sphereEndMapper = vtkPolyDataMapper()
sphereEndMapper.SetInputConnection(sphereEndSource.GetOutputPort())
sphereEnd = vtkActor()
sphereEnd.SetMapper(sphereEndMapper)
sphereEnd.GetProperty().SetColor(colors.GetColor3d('Magenta'))
# Create a renderer, render window, and interactor
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.SetWindowName('OrientedArrow')
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
# Add the actor to the scene
renderer.AddActor(actor)
renderer.AddActor(sphereStart)
renderer.AddActor(sphereEnd)
renderer.SetBackground(colors.GetColor3d('BkgColor'))
# Render and interact
renderWindow.Render()
renderWindowInteractor.Start()
if __name__ == '__main__':
main()
vtkShrinkPolyData
Description
This example gets the frustum from a camera and displays it on the screen.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonDataModel import vtkPlanes
from vtkmodules.vtkFiltersGeneral import vtkShrinkPolyData
from vtkmodules.vtkFiltersSources import vtkFrustumSource
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkCamera,
vtkPolyDataMapper,
vtkProperty,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
camera = vtkCamera()
camera.SetClippingRange(0.1, 0.4)
planesArray = [0] * 24
camera.GetFrustumPlanes(1.0, planesArray)
planes = vtkPlanes()
planes.SetFrustumPlanes(planesArray)
frustumSource = vtkFrustumSource()
frustumSource.ShowLinesOff()
frustumSource.SetPlanes(planes)
shrink = vtkShrinkPolyData()
shrink.SetInputConnection(frustumSource.GetOutputPort())
shrink.SetShrinkFactor(.9)
mapper = vtkPolyDataMapper()
mapper.SetInputConnection(shrink.GetOutputPort())
back = vtkProperty()
back.SetColor(colors.GetColor3d("Tomato"))
actor = vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().EdgeVisibilityOn()
actor.GetProperty().SetColor(colors.GetColor3d("Banana"))
actor.SetBackfaceProperty(back)
# a renderer and render window
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.SetWindowName("Frustum")
renderWindow.AddRenderer(renderer)
# an interactor
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
# add the actors to the scene
renderer.AddActor(actor)
renderer.SetBackground(colors.GetColor3d("Silver"))
# Position the camera so that we can see the frustum
renderer.GetActiveCamera().SetPosition(1, 0, 0)
renderer.GetActiveCamera().SetFocalPoint(0, 0, 0)
renderer.GetActiveCamera().SetViewUp(0, 1, 0)
renderer.GetActiveCamera().Azimuth(30)
renderer.GetActiveCamera().Elevation(30)
renderer.ResetCamera()
# render an image (lights and cameras are created automatically)
renderWindow.Render()
# begin mouse interaction
renderWindowInteractor.Start()
if __name__ == '__main__':
main()
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkPoints
from vtkmodules.vtkCommonDataModel import (
# VTK_HEXAGONAL_PRISM,
# VTK_HEXAHEDRON,
# VTK_LINE,
# VTK_PENTAGONAL_PRISM,
# VTK_PIXEL,
# VTK_POLY_LINE,
# VTK_POLY_VERTEX,
# VTK_POLYGON,
# VTK_PYRAMID,
# VTK_QUAD,
VTK_TETRA,
# VTK_TRIANGLE,
# VTK_TRIANGLE_STRIP,
# VTK_VERTEX,
# VTK_VOXEL,
# VTK_WEDGE,
vtkCellArray,
vtkHexagonalPrism,
vtkHexahedron,
vtkLine,
vtkPentagonalPrism,
vtkPixel,
vtkPolyLine,
vtkPolyVertex,
vtkPolygon,
vtkPyramid,
vtkQuad,
vtkTetra,
vtkTriangle,
vtkTriangleStrip,
vtkUnstructuredGrid,
vtkVertex,
vtkVoxel,
vtkWedge
)
from vtkmodules.vtkFiltersSources import vtkSphereSource
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkActor2D,
vtkDataSetMapper,
vtkGlyph3DMapper,
vtkProperty,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer,
vtkTextMapper,
vtkTextProperty
)
from vtkmodules.vtkRenderingLabel import vtkLabeledDataMapper
def get_program_parameters():
import argparse
description = 'Demonstrate the linear cell types found in VTK. Numbers define ordering of the defining points.'
epilogue = '''
'''
parser = argparse.ArgumentParser(description=description, epilog=epilogue,
formatter_class=argparse.RawDescriptionHelpFormatter)
group1 = parser.add_mutually_exclusive_group()
group1.add_argument('-w', '--wireframe', action='store_true',
help='Render a wireframe.')
group1.add_argument('-b', '--backface', action='store_true',
help='Display the back face in a different colour.')
args = parser.parse_args()
return args.wireframe, args.backface
def main():
wireframe_on, backface_on = get_program_parameters()
titles = list()
text_mappers = list()
text_actors = list()
u_grids = list()
mappers = list()
actors = list()
renderers = list()
u_grids.append(make_vertex())
titles.append('VTK_VERTEX (=1)')
u_grids.append(make_poly_vertex())
titles.append('VTK_POLY_VERTEX (=2)')
u_grids.append(make_line())
titles.append('VTK_LINE (=3)')
u_grids.append(make_polyline())
titles.append('VTK_POLY_LINE (=4)')
u_grids.append(make_triangle())
titles.append('VTK_TRIANGLE (=5)')
u_grids.append(make_triangle_strip())
titles.append('VTK_TRIANGLE_STRIP (=6)')
u_grids.append(make_polygon())
titles.append('VTK_POLYGON (=7)')
u_grids.append(make_pixel())
titles.append('VTK_PIXEL (=8)')
u_grids.append(make_quad())
titles.append('VTK_QUAD (=9)')
u_grids.append(make_tetra())
titles.append('VTK_TETRA (=10)')
u_grids.append(make_voxel())
titles.append('VTK_VOXEL (=11)')
u_grids.append(make_hexahedron())
titles.append('VTK_HEXAHEDRON (=12)')
u_grids.append(make_wedge())
titles.append('VTK_WEDGE (=13)')
u_grids.append(make_pyramid())
titles.append('VTK_PYRAMID (=14)')
u_grids.append(make_pentagonal_prism())
titles.append('VTK_PENTAGONAL_PRISM (=15)')
u_grids.append(make_hexagonal_prism())
titles.append('VTK_HEXAGONAL_PRISM (=16)')
colors = vtkNamedColors()
ren_win = vtkRenderWindow()
ren_win.SetWindowName('LinearCellDemo')
iren = vtkRenderWindowInteractor()
iren.SetRenderWindow(ren_win)
# Create one sphere for all
sphere = vtkSphereSource()
sphere.SetPhiResolution(21)
sphere.SetThetaResolution(21)
sphere.SetRadius(.08)
# Create one text property for all
text_property = vtkTextProperty()
text_property.SetFontSize(10)
text_property.SetJustificationToCentered()
text_property.SetColor(colors.GetColor3d('Black'))
back_property = vtkProperty()
back_property.SetColor(colors.GetColor3d('MediumSeaGreen'))
# Create and link the mappers actors and renderers together.
for i in range(0, len(u_grids)):
print('Creating:', titles[i])
text_mappers.append(vtkTextMapper())
text_actors.append(vtkActor2D())
mappers.append(vtkDataSetMapper())
actors.append(vtkActor())
renderers.append(vtkRenderer())
mappers[i].SetInputData(u_grids[i])
actors[i].SetMapper(mappers[i])
if wireframe_on:
actors[i].GetProperty().SetRepresentationToWireframe()
actors[i].GetProperty().SetLineWidth(2)
actors[i].GetProperty().SetOpacity(1)
actors[i].GetProperty().SetColor(colors.GetColor3d('Black'))
else:
actors[i].GetProperty().EdgeVisibilityOn()
actors[i].GetProperty().SetLineWidth(3)
actors[i].GetProperty().SetColor(colors.GetColor3d('Tomato'))
if backface_on:
actors[i].SetBackfaceProperty(back_property)
actors[i].GetProperty().SetOpacity(1)
else:
actors[i].GetProperty().SetOpacity(0.5)
renderers[i].AddViewProp(actors[i])
text_mappers[i].SetInput(titles[i])
text_actors[i].SetMapper(text_mappers[i])
text_actors[i].SetPosition(50, 10)
if wireframe_on:
text_actors[i].GetProperty().SetColor(colors.GetColor3d('Black'))
renderers[i].AddViewProp(text_actors[i])
# Label the points
label_mapper = vtkLabeledDataMapper()
label_mapper.SetInputData(u_grids[i])
label_actor = vtkActor2D()
label_actor.SetMapper(label_mapper)
if wireframe_on:
label_actor.GetProperty().SetColor(colors.GetColor3d('Snow'))
renderers[i].AddViewProp(label_actor)
# Glyph the points
point_mapper = vtkGlyph3DMapper()
point_mapper.SetInputData(u_grids[i])
point_mapper.SetSourceConnection(sphere.GetOutputPort())
point_mapper.ScalingOn()
point_mapper.ScalarVisibilityOff()
point_actor = vtkActor()
point_actor.SetMapper(point_mapper)
if wireframe_on:
point_actor.GetProperty().SetColor(colors.GetColor3d('Banana'))
else:
point_actor.GetProperty().SetColor(colors.GetColor3d('Banana'))
point_actor.GetProperty().SetSpecular(.6)
point_actor.GetProperty().SetSpecularColor(1.0, 1.0, 1.0)
point_actor.GetProperty().SetSpecularPower(100)
renderers[i].AddViewProp(point_actor)
ren_win.AddRenderer(renderers[i])
# Set up the viewports
grid_dimensions_x = 4
grid_dimensions_y = 4
renderer_size = 300
ren_win.SetSize(renderer_size * grid_dimensions_x, renderer_size * grid_dimensions_y)
for row in range(0, grid_dimensions_y):
for col in range(0, grid_dimensions_x):
index = row * grid_dimensions_x + col
# (xmin, ymin, xmax, ymax)
viewport = [float(col) / grid_dimensions_x,
float(grid_dimensions_y - (row + 1)) / grid_dimensions_y,
float(col + 1) / grid_dimensions_x,
float(grid_dimensions_y - row) / grid_dimensions_y]
if index > (len(actors) - 1):
# Add a renderer even if there is no actor.
# This makes the render window background all the same color.
ren = vtkRenderer()
if wireframe_on:
ren.SetBackground(colors.GetColor3d('LightSlateGray'))
else:
ren.SetBackground(colors.GetColor3d('SlateGray'))
ren.SetViewport(viewport)
ren_win.AddRenderer(ren)
continue
if wireframe_on:
renderers[index].SetBackground(colors.GetColor3d('LightSlateGray'))
else:
renderers[index].SetBackground(colors.GetColor3d('SlateGray'))
renderers[index].SetViewport(viewport)
renderers[index].ResetCamera()
if index == 0:
renderers[index].GetActiveCamera().Dolly(0.1)
renderers[index].GetActiveCamera().Azimuth(30)
renderers[index].GetActiveCamera().Elevation(-30)
elif index == 1:
renderers[index].GetActiveCamera().Dolly(0.8)
renderers[index].GetActiveCamera().Azimuth(30)
renderers[index].GetActiveCamera().Elevation(-30)
elif index == 2:
renderers[index].GetActiveCamera().Dolly(0.4)
renderers[index].GetActiveCamera().Azimuth(30)
renderers[index].GetActiveCamera().Elevation(-30)
elif index == 4:
renderers[index].GetActiveCamera().Dolly(0.7)
renderers[index].GetActiveCamera().Azimuth(30)
renderers[index].GetActiveCamera().Elevation(-30)
elif index == 5:
renderers[index].GetActiveCamera().Dolly(1.1)
renderers[index].GetActiveCamera().Azimuth(30)
renderers[index].GetActiveCamera().Elevation(-30)
elif index == 6:
renderers[index].GetActiveCamera().Azimuth(0)
renderers[index].GetActiveCamera().Elevation(-45)
elif index == 7:
renderers[index].GetActiveCamera().Azimuth(0)
renderers[index].GetActiveCamera().Elevation(-45)
elif index == 8:
renderers[index].GetActiveCamera().Azimuth(0)
renderers[index].GetActiveCamera().Elevation(-45)
elif index == 9:
renderers[index].GetActiveCamera().Azimuth(0)
renderers[index].GetActiveCamera().Elevation(-22.5)
elif index == 10:
renderers[index].GetActiveCamera().Azimuth(-22.5)
renderers[index].GetActiveCamera().Elevation(15)
elif index == 11:
renderers[index].GetActiveCamera().Azimuth(-22.5)
renderers[index].GetActiveCamera().Elevation(15)
elif index == 12:
renderers[index].GetActiveCamera().Azimuth(-45)
renderers[index].GetActiveCamera().Elevation(15)
elif index == 13:
renderers[index].GetActiveCamera().Azimuth(0)
renderers[index].GetActiveCamera().Elevation(-30)
elif index == 14:
renderers[index].GetActiveCamera().Azimuth(-22.5)
renderers[index].GetActiveCamera().Elevation(10)
elif index == 15:
renderers[index].GetActiveCamera().Azimuth(-30)
renderers[index].GetActiveCamera().Elevation(15)
else:
renderers[index].GetActiveCamera().Azimuth(30)
renderers[index].GetActiveCamera().Elevation(-30)
renderers[index].ResetCameraClippingRange()
ren_win.Render()
iren.Initialize()
iren.Start()
# These functions return a vtkUnstructured grid corresponding to the object.
def make_vertex():
# A vertex is a cell that represents a 3D point
number_of_vertices = 1
points = vtkPoints()
points.InsertNextPoint(0, 0, 0)
vertex = vtkVertex()
for i in range(0, number_of_vertices):
vertex.GetPointIds().SetId(i, i)
ug = vtkUnstructuredGrid()
ug.SetPoints(points)
ug.InsertNextCell(vertex.GetCellType(), vertex.GetPointIds())
return ug
def make_poly_vertex():
# A polyvertex is a cell represents a set of 0D vertices
number_of_vertices = 6
points = vtkPoints()
points.InsertNextPoint(0, 0, 0)
points.InsertNextPoint(1, 0, 0)
points.InsertNextPoint(0, 1, 0)
points.InsertNextPoint(0, 0, 1)
points.InsertNextPoint(1, 0, 0.4)
points.InsertNextPoint(0, 1, 0.6)
poly_vertex = vtkPolyVertex()
poly_vertex.GetPointIds().SetNumberOfIds(number_of_vertices)
for i in range(0, number_of_vertices):
poly_vertex.GetPointIds().SetId(i, i)
ug = vtkUnstructuredGrid()
ug.SetPoints(points)
ug.InsertNextCell(poly_vertex.GetCellType(), poly_vertex.GetPointIds())
return ug
def make_line():
# A line is a cell that represents a 1D point
number_of_vertices = 2
points = vtkPoints()
points.InsertNextPoint(0, 0, 0)
points.InsertNextPoint(0.5, 0.5, 0)
line = vtkLine()
for i in range(0, number_of_vertices):
line.GetPointIds().SetId(i, i)
ug = vtkUnstructuredGrid()
ug.SetPoints(points)
ug.InsertNextCell(line.GetCellType(), line.GetPointIds())
return ug
def make_polyline():
# A polyline is a cell that represents a set of 1D lines
number_of_vertices = 5
points = vtkPoints()
points.InsertNextPoint(0, 0.5, 0)
points.InsertNextPoint(0.5, 0, 0)
points.InsertNextPoint(1, 0.3, 0)
points.InsertNextPoint(1.5, 0.4, 0)
points.InsertNextPoint(2.0, 0.4, 0)
polyline = vtkPolyLine()
polyline.GetPointIds().SetNumberOfIds(number_of_vertices)
for i in range(0, number_of_vertices):
polyline.GetPointIds().SetId(i, i)
ug = vtkUnstructuredGrid()
ug.SetPoints(points)
ug.InsertNextCell(polyline.GetCellType(), polyline.GetPointIds())
return ug
def make_triangle():
# A triangle is a cell that represents a 1D point
number_of_vertices = 3
points = vtkPoints()
points.InsertNextPoint(0, 0, 0)
points.InsertNextPoint(0.5, 0.5, 0)
points.InsertNextPoint(.2, 1, 0)
triangle = vtkTriangle()
for i in range(0, number_of_vertices):
triangle.GetPointIds().SetId(i, i)
ug = vtkUnstructuredGrid()
ug.SetPoints(points)
ug.InsertNextCell(triangle.GetCellType(), triangle.GetPointIds())
return ug
def make_triangle_strip():
# A triangle is a cell that represents a triangle strip
number_of_vertices = 10
points = vtkPoints()
points.InsertNextPoint(0, 0, 0)
points.InsertNextPoint(1, -.1, 0)
points.InsertNextPoint(0.5, 1, 0)
points.InsertNextPoint(2.0, -0.1, 0)
points.InsertNextPoint(1.5, 0.8, 0)
points.InsertNextPoint(3.0, 0, 0)
points.InsertNextPoint(2.5, 0.9, 0)
points.InsertNextPoint(4.0, -0.2, 0)
points.InsertNextPoint(3.5, 0.8, 0)
points.InsertNextPoint(4.5, 1.1, 0)
trianglestrip = vtkTriangleStrip()
trianglestrip.GetPointIds().SetNumberOfIds(number_of_vertices)
for i in range(0, number_of_vertices):
trianglestrip.GetPointIds().SetId(i, i)
ug = vtkUnstructuredGrid()
ug.SetPoints(points)
ug.InsertNextCell(trianglestrip.GetCellType(), trianglestrip.GetPointIds())
return ug
def make_polygon():
# A polygon is a cell that represents a polygon
number_of_vertices = 6
points = vtkPoints()
points.InsertNextPoint(0, 0, 0)
points.InsertNextPoint(1, -0.1, 0)
points.InsertNextPoint(0.8, 0.5, 0)
points.InsertNextPoint(1, 1, 0)
points.InsertNextPoint(0.6, 1.2, 0)
points.InsertNextPoint(0, 0.8, 0)
polygon = vtkPolygon()
polygon.GetPointIds().SetNumberOfIds(number_of_vertices)
for i in range(0, number_of_vertices):
polygon.GetPointIds().SetId(i, i)
ug = vtkUnstructuredGrid()
ug.SetPoints(points)
ug.InsertNextCell(polygon.GetCellType(), polygon.GetPointIds())
return ug
def make_pixel():
# A pixel is a cell that represents a pixel
pixel = vtkPixel()
pixel.GetPoints().SetPoint(0, 0, 0, 0)
pixel.GetPoints().SetPoint(1, 1, 0, 0)
pixel.GetPoints().SetPoint(2, 0, 1, 0)
pixel.GetPoints().SetPoint(3, 1, 1, 0)
pixel.GetPointIds().SetId(0, 0)
pixel.GetPointIds().SetId(1, 1)
pixel.GetPointIds().SetId(2, 2)
pixel.GetPointIds().SetId(3, 3)
ug = vtkUnstructuredGrid()
ug.SetPoints(pixel.GetPoints())
ug.InsertNextCell(pixel.GetCellType(), pixel.GetPointIds())
return ug
def make_quad():
# A quad is a cell that represents a quad
quad = vtkQuad()
quad.GetPoints().SetPoint(0, 0, 0, 0)
quad.GetPoints().SetPoint(1, 1, 0, 0)
quad.GetPoints().SetPoint(2, 1, 1, 0)
quad.GetPoints().SetPoint(3, 0, 1, 0)
quad.GetPointIds().SetId(0, 0)
quad.GetPointIds().SetId(1, 1)
quad.GetPointIds().SetId(2, 2)
quad.GetPointIds().SetId(3, 3)
ug = vtkUnstructuredGrid()
ug.SetPoints(quad.GetPoints())
ug.InsertNextCell(quad.GetCellType(), quad.GetPointIds())
return ug
def make_tetra():
# Make a tetrahedron.
number_of_vertices = 4
points = vtkPoints()
points.InsertNextPoint(0, 0, 0)
points.InsertNextPoint(1, 0, 0)
points.InsertNextPoint(1, 1, 0)
points.InsertNextPoint(0, 1, 1)
tetra = vtkTetra()
for i in range(0, number_of_vertices):
tetra.GetPointIds().SetId(i, i)
cell_array = vtkCellArray()
cell_array.InsertNextCell(tetra)
ug = vtkUnstructuredGrid()
ug.SetPoints(points)
ug.SetCells(VTK_TETRA, cell_array)
return ug
def make_voxel():
# A voxel is a representation of a regular grid in 3-D space.
number_of_vertices = 8
points = vtkPoints()
points.InsertNextPoint(0, 0, 0)
points.InsertNextPoint(1, 0, 0)
points.InsertNextPoint(0, 1, 0)
points.InsertNextPoint(1, 1, 0)
points.InsertNextPoint(0, 0, 1)
points.InsertNextPoint(1, 0, 1)
points.InsertNextPoint(0, 1, 1)
points.InsertNextPoint(1, 1, 1)
voxel = vtkVoxel()
for i in range(0, number_of_vertices):
voxel.GetPointIds().SetId(i, i)
ug = vtkUnstructuredGrid()
ug.SetPoints(points)
ug.InsertNextCell(voxel.GetCellType(), voxel.GetPointIds())
return ug
def make_hexahedron():
# A regular hexagon (cube) with all faces square and three squares around
# each vertex is created below.
# Set up the coordinates of eight points
# (the two faces must be in counter-clockwise
# order as viewed from the outside).
number_of_vertices = 8
# Create the points
points = vtkPoints()
points.InsertNextPoint(0, 0, 0)
points.InsertNextPoint(1, 0, 0)
points.InsertNextPoint(1, 1, 0)
points.InsertNextPoint(0, 1, 0)
points.InsertNextPoint(0, 0, 1)
points.InsertNextPoint(1, 0, 1)
points.InsertNextPoint(1, 1, 1)
points.InsertNextPoint(0, 1, 1)
# Create a hexahedron from the points
hexhedr = vtkHexahedron()
for i in range(0, number_of_vertices):
hexhedr.GetPointIds().SetId(i, i)
# Add the points and hexahedron to an unstructured grid
ug = vtkUnstructuredGrid()
ug.SetPoints(points)
ug.InsertNextCell(hexhedr.GetCellType(), hexhedr.GetPointIds())
return ug
def make_wedge():
# A wedge consists of two triangular ends and three rectangular faces.
number_of_vertices = 6
points = vtkPoints()
points.InsertNextPoint(0, 1, 0)
points.InsertNextPoint(0, 0, 0)
points.InsertNextPoint(0, 0.5, 0.5)
points.InsertNextPoint(1, 1, 0)
points.InsertNextPoint(1, 0.0, 0.0)
points.InsertNextPoint(1, 0.5, 0.5)
wedge = vtkWedge()
for i in range(0, number_of_vertices):
wedge.GetPointIds().SetId(i, i)
ug = vtkUnstructuredGrid()
ug.SetPoints(points)
ug.InsertNextCell(wedge.GetCellType(), wedge.GetPointIds())
return ug
def make_pyramid():
# Make a regular square pyramid.
number_of_vertices = 5
points = vtkPoints()
p0 = [1.0, 1.0, 0.0]
p1 = [-1.0, 1.0, 0.0]
p2 = [-1.0, -1.0, 0.0]
p3 = [1.0, -1.0, 0.0]
p4 = [0.0, 0.0, 1.0]
points.InsertNextPoint(p0)
points.InsertNextPoint(p1)
points.InsertNextPoint(p2)
points.InsertNextPoint(p3)
points.InsertNextPoint(p4)
pyramid = vtkPyramid()
for i in range(0, number_of_vertices):
pyramid.GetPointIds().SetId(i, i)
ug = vtkUnstructuredGrid()
ug.SetPoints(points)
ug.InsertNextCell(pyramid.GetCellType(), pyramid.GetPointIds())
return ug
def make_pentagonal_prism():
pentagonal_prism = vtkPentagonalPrism()
pentagonal_prism.GetPointIds().SetId(0, 0)
pentagonal_prism.GetPointIds().SetId(1, 1)
pentagonal_prism.GetPointIds().SetId(2, 2)
pentagonal_prism.GetPointIds().SetId(3, 3)
pentagonal_prism.GetPointIds().SetId(4, 4)
pentagonal_prism.GetPointIds().SetId(5, 5)
pentagonal_prism.GetPointIds().SetId(6, 6)
pentagonal_prism.GetPointIds().SetId(7, 7)
pentagonal_prism.GetPointIds().SetId(8, 8)
pentagonal_prism.GetPointIds().SetId(9, 9)
scale = 2.0
pentagonal_prism.GetPoints().SetPoint(0, 11 / scale, 10 / scale, 10 / scale)
pentagonal_prism.GetPoints().SetPoint(1, 13 / scale, 10 / scale, 10 / scale)
pentagonal_prism.GetPoints().SetPoint(2, 14 / scale, 12 / scale, 10 / scale)
pentagonal_prism.GetPoints().SetPoint(3, 12 / scale, 14 / scale, 10 / scale)
pentagonal_prism.GetPoints().SetPoint(4, 10 / scale, 12 / scale, 10 / scale)
pentagonal_prism.GetPoints().SetPoint(5, 11 / scale, 10 / scale, 14 / scale)
pentagonal_prism.GetPoints().SetPoint(6, 13 / scale, 10 / scale, 14 / scale)
pentagonal_prism.GetPoints().SetPoint(7, 14 / scale, 12 / scale, 14 / scale)
pentagonal_prism.GetPoints().SetPoint(8, 12 / scale, 14 / scale, 14 / scale)
pentagonal_prism.GetPoints().SetPoint(9, 10 / scale, 12 / scale, 14 / scale)
ug = vtkUnstructuredGrid()
ug.SetPoints(pentagonal_prism.GetPoints())
ug.InsertNextCell(pentagonal_prism.GetCellType(), pentagonal_prism.GetPointIds())
return ug
def make_hexagonal_prism():
hexagonal_prism = vtkHexagonalPrism()
hexagonal_prism.GetPointIds().SetId(0, 0)
hexagonal_prism.GetPointIds().SetId(1, 1)
hexagonal_prism.GetPointIds().SetId(2, 2)
hexagonal_prism.GetPointIds().SetId(3, 3)
hexagonal_prism.GetPointIds().SetId(4, 4)
hexagonal_prism.GetPointIds().SetId(5, 5)
hexagonal_prism.GetPointIds().SetId(6, 6)
hexagonal_prism.GetPointIds().SetId(7, 7)
hexagonal_prism.GetPointIds().SetId(8, 8)
hexagonal_prism.GetPointIds().SetId(9, 9)
hexagonal_prism.GetPointIds().SetId(10, 10)
hexagonal_prism.GetPointIds().SetId(11, 11)
scale = 2.0
hexagonal_prism.GetPoints().SetPoint(0, 11 / scale, 10 / scale, 10 / scale)
hexagonal_prism.GetPoints().SetPoint(1, 13 / scale, 10 / scale, 10 / scale)
hexagonal_prism.GetPoints().SetPoint(2, 14 / scale, 12 / scale, 10 / scale)
hexagonal_prism.GetPoints().SetPoint(3, 13 / scale, 14 / scale, 10 / scale)
hexagonal_prism.GetPoints().SetPoint(4, 11 / scale, 14 / scale, 10 / scale)
hexagonal_prism.GetPoints().SetPoint(5, 10 / scale, 12 / scale, 10 / scale)
hexagonal_prism.GetPoints().SetPoint(6, 11 / scale, 10 / scale, 14 / scale)
hexagonal_prism.GetPoints().SetPoint(7, 13 / scale, 10 / scale, 14 / scale)
hexagonal_prism.GetPoints().SetPoint(8, 14 / scale, 12 / scale, 14 / scale)
hexagonal_prism.GetPoints().SetPoint(9, 13 / scale, 14 / scale, 14 / scale)
hexagonal_prism.GetPoints().SetPoint(10, 11 / scale, 14 / scale, 14 / scale)
hexagonal_prism.GetPoints().SetPoint(11, 10 / scale, 12 / scale, 14 / scale)
ug = vtkUnstructuredGrid()
ug.SetPoints(hexagonal_prism.GetPoints())
ug.InsertNextCell(hexagonal_prism.GetCellType(), hexagonal_prism.GetPointIds())
return ug
if __name__ == '__main__':
main()
RegularPolygonSource
Description
This example creates a pentagon
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkFiltersGeneral import vtkShrinkPolyData
from vtkmodules.vtkFiltersSources import vtkRegularPolygonSource
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkProperty,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
# Create a pentagon
polygonSource = vtkRegularPolygonSource()
polygonSource.SetNumberOfSides(5)
polygonSource.SetRadius(5)
polygonSource.SetCenter(0, 0, 0)
shrink = vtkShrinkPolyData()
shrink.SetInputConnection(polygonSource.GetOutputPort())
shrink.SetShrinkFactor(0.9)
mapper = vtkPolyDataMapper()
mapper.SetInputConnection(shrink.GetOutputPort())
back = vtkProperty()
back.SetColor(colors.GetColor3d('Tomato'))
actor = vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().EdgeVisibilityOn()
actor.GetProperty().SetLineWidth(5)
actor.GetProperty().SetColor(colors.GetColor3d('Banana'))
actor.SetBackfaceProperty(back)
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.SetWindowName('RegularPolygonSource')
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
renderer.AddActor(actor)
renderer.SetBackground(colors.GetColor3d('Silver'))
renderWindow.Render()
renderWindowInteractor.Start()
if __name__ == '__main__':
main()
Vertex
Description
The vertex is a primary zero-dimensional cell. It is defined by a single point.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkPoints
from vtkmodules.vtkCommonDataModel import (
vtkCellArray,
vtkPolyData,
vtkVertex
)
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
points = vtkPoints()
points.InsertNextPoint(0, 0, 0)
vertex = vtkVertex()
vertex.GetPointIds().SetId(0, 0)
vertices = vtkCellArray()
vertices.InsertNextCell(vertex)
polydata = vtkPolyData()
polydata.SetPoints(points)
polydata.SetVerts(vertices)
# Setup actor and mapper
mapper = vtkPolyDataMapper()
mapper.SetInputData(polydata)
actor = vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetPointSize(30)
actor.GetProperty().SetColor(colors.GetColor3d('PeachPuff'))
# Setup render window, renderer, and interactor
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.SetWindowName('Vertex')
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
renderer.AddActor(actor)
renderer.SetBackground(colors.GetColor3d('DarkGreen'))
renderWindow.Render()
renderWindowInteractor.Start()
if __name__ == '__main__':
main()
ParametricSuperEllipsoidDemo
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonComputationalGeometry import vtkParametricSuperEllipsoid
from vtkmodules.vtkCommonCore import (
vtkCommand,
vtkMath
)
from vtkmodules.vtkFiltersSources import vtkParametricFunctionSource
from vtkmodules.vtkInteractionWidgets import (
vtkSliderRepresentation2D,
vtkSliderWidget
)
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkProperty,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
# Set the background color.
colors.SetColor('BkgColor', [26, 51, 102, 255])
surface = vtkParametricSuperEllipsoid()
source = vtkParametricFunctionSource()
renderer = vtkRenderer()
mapper = vtkPolyDataMapper()
actor = vtkActor()
backProperty = vtkProperty()
backProperty.SetColor(colors.GetColor3d('Tomato'))
# Create a parametric function source, renderer, mapper, and actor
source.SetParametricFunction(surface)
mapper.SetInputConnection(source.GetOutputPort())
actor.SetMapper(mapper)
actor.SetBackfaceProperty(backProperty)
actor.GetProperty().SetDiffuseColor(colors.GetColor3d('Banana'))
actor.GetProperty().SetSpecular(.5)
actor.GetProperty().SetSpecularPower(20)
renderWindow = vtkRenderWindow()
renderWindow.SetWindowName('ParametricSuperEllipsoidDemo')
renderWindow.AddRenderer(renderer)
renderWindow.SetSize(640, 480)
renderer.AddActor(actor)
renderer.SetBackground(colors.GetColor3d('BkgColor'))
renderer.ResetCamera()
renderer.GetActiveCamera().Azimuth(30)
renderer.GetActiveCamera().Elevation(-30)
renderer.GetActiveCamera().Zoom(0.9)
renderer.ResetCameraClippingRange()
interactor = vtkRenderWindowInteractor()
interactor.SetRenderWindow(renderWindow)
# Setup a slider widget for each varying parameter
tubeWidth = 0.008
sliderLength = 0.008
titleHeight = 0.04
labelHeight = 0.04
sliderRepN1 = vtkSliderRepresentation2D()
sliderRepN1.SetMinimumValue(0.0)
sliderRepN1.SetMaximumValue(4.0)
sliderRepN1.SetValue(1.0)
sliderRepN1.SetTitleText('Z squareness')
sliderRepN1.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay()
sliderRepN1.GetPoint1Coordinate().SetValue(.1, .1)
sliderRepN1.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay()
sliderRepN1.GetPoint2Coordinate().SetValue(.9, .1)
sliderRepN1.SetTubeWidth(tubeWidth)
sliderRepN1.SetSliderLength(sliderLength)
sliderRepN1.SetTitleHeight(titleHeight)
sliderRepN1.SetLabelHeight(labelHeight)
sliderWidgetN1 = vtkSliderWidget()
sliderWidgetN1.SetInteractor(interactor)
sliderWidgetN1.SetRepresentation(sliderRepN1)
sliderWidgetN1.SetAnimationModeToAnimate()
sliderWidgetN1.EnabledOn()
sliderWidgetN1.AddObserver(vtkCommand.InteractionEvent, SliderCallbackN1(surface))
sliderRepN2 = vtkSliderRepresentation2D()
sliderRepN2.SetMinimumValue(0.0001)
sliderRepN2.SetMaximumValue(4.0)
sliderRepN2.SetValue(1.0)
sliderRepN2.SetTitleText('XY squareness')
sliderRepN2.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay()
sliderRepN2.GetPoint1Coordinate().SetValue(.1, .9)
sliderRepN2.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay()
sliderRepN2.GetPoint2Coordinate().SetValue(.9, .9)
sliderRepN2.SetTubeWidth(tubeWidth)
sliderRepN2.SetSliderLength(sliderLength)
sliderRepN2.SetTitleHeight(titleHeight)
sliderRepN2.SetLabelHeight(labelHeight)
sliderWidgetN2 = vtkSliderWidget()
sliderWidgetN2.SetInteractor(interactor)
sliderWidgetN2.SetRepresentation(sliderRepN2)
sliderWidgetN2.SetAnimationModeToAnimate()
sliderWidgetN2.EnabledOn()
sliderWidgetN2.AddObserver(vtkCommand.InteractionEvent, SliderCallbackN2(surface))
sliderRepMinimumV = vtkSliderRepresentation2D()
sliderRepN1.SetMinimumValue(.0001)
sliderRepMinimumV.SetMaximumValue(.9999 * vtkMath.Pi())
sliderRepMinimumV.SetValue(.0001)
sliderRepMinimumV.SetTitleText('V min')
sliderRepMinimumV.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay()
sliderRepMinimumV.GetPoint1Coordinate().SetValue(.1, .1)
sliderRepMinimumV.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay()
sliderRepMinimumV.GetPoint2Coordinate().SetValue(.1, .9)
sliderRepMinimumV.SetTubeWidth(tubeWidth)
sliderRepMinimumV.SetSliderLength(sliderLength)
sliderRepMinimumV.SetTitleHeight(titleHeight)
sliderRepMinimumV.SetLabelHeight(labelHeight)
surface.SetN1(1.0)
surface.SetN2(1.0)
renderer.ResetCamera()
renderer.GetActiveCamera().Azimuth(30)
renderer.GetActiveCamera().Elevation(-30)
renderer.GetActiveCamera().Zoom(0.9)
renderer.ResetCameraClippingRange()
renderWindow.Render()
interactor.Initialize()
interactor.Start()
# These callbacks do the actual work.
# Callbacks for the interactions
class SliderCallbackN1():
def __init__(self, superEllipsoid):
self.superEllipsoid = superEllipsoid
def __call__(self, caller, ev):
sliderWidget = caller
value = sliderWidget.GetRepresentation().GetValue()
self.superEllipsoid.SetN1(value)
class SliderCallbackN2():
def __init__(self, superEllipsoid):
self.superEllipsoid = superEllipsoid
def __call__(self, caller, ev):
sliderWidget = caller
value = sliderWidget.GetRepresentation().GetValue()
self.superEllipsoid.SetN2(value)
if __name__ == '__main__':
main()
vtkEarthSource
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkFiltersHybrid import vtkEarthSource
from vtkmodules.vtkFiltersSources import vtkSphereSource
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
# Earth source
earthSource = vtkEarthSource()
earthSource.OutlineOn()
earthSource.Update()
r = earthSource.GetRadius()
# Create a sphere
sphere = vtkSphereSource()
sphere.SetThetaResolution(100)
sphere.SetPhiResolution(100)
sphere.SetRadius(earthSource.GetRadius())
# Create a mapper and actor
mapper = vtkPolyDataMapper()
mapper.SetInputConnection(earthSource.GetOutputPort())
actor = vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetColor(colors.GetColor3d('Black'))
sphereMapper = vtkPolyDataMapper()
sphereMapper.SetInputConnection(sphere.GetOutputPort())
sphereActor = vtkActor()
sphereActor.SetMapper(sphereMapper)
sphereActor.GetProperty().SetColor(colors.GetColor3d('PeachPuff'))
# Create a renderer, render window, and interactor
renderer = vtkRenderer()
renderWindow = vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
# Add the actor to the scene
renderer.AddActor(actor)
renderer.AddActor(sphereActor)
renderer.SetBackground(colors.GetColor3d('Black'))
renderWindow.SetSize(640, 480)
renderWindow.SetWindowName('EarthSource')
# Render and interact
renderWindow.Render()
# # screenshot code:
# w2if = vtkWindowToImageFilter()
# w2if.SetInput(renderWindow)
# w2if.Update()
#
# writer = vtkPNGWriter()
# writer.SetFileName('TestEarthSource.png')
# writer.SetInputConnection(w2if.GetOutputPort())
# writer.Write()
# begin interaction
renderWindowInteractor.Start()
if __name__ == '__main__':
main()