Note that the method of adding objects is very repetitive. As a result, all of the repetitive code may be put into a general function that will do all that is required for making the molecule. The code is provided below. As usual, it builds upon the previous code.
#! /usr/bin/python
from vtk import *
from math import cos, sin
pi = 3.141592
###### Functions for making objects ################
#---------------------------------------------
# Make a sphere of a certain radius, position
# and color. This will represent an atom.
#---------------------------------------------
def makeSphere(radius, position, color):
 # create the object to be drawn
 sphere = vtkSphereSource()
 sphere.SetRadius( radius )
 sphere.SetThetaResolution(30)
 sphere.SetPhiResolution(30)
 sphere.SetCenter(position[0], position[1], position[2])
 # Convert the sphere into polygons
 sphereMapper = vtkPolyDataMapper()
 sphereMapper.SetInput(sphere.GetOutput())
 #Create an actor for the sphere 
 sphereActor = vtkActor()
 sphereActor.SetMapper(sphereMapper)
 (sphereActor.GetProperty()).SetColor(color[0], color[1], color[2])
 return sphereActor
#---------------------------------------------
# Make a cylinder of a certain radius, position
# orientation and color. This will represent an
# atom.
#---------------------------------------------
def makeCylinder(radius, height, position, color, rotation):
 # create the object to be drawn
 cylinder = vtkCylinderSource()
 cylinder.SetRadius(radius)
 cylinder.SetHeight(height)
 cylinder.SetResolution(30)
 cylinder.SetCenter(position[0], position[1], position[2])
 # Convert the sphere into polygons
 cylinderMapper = vtkPolyDataMapper()
 cylinderMapper.SetInput(cylinder.GetOutput())
 #Create an actor for the sphere 
 cylinderActor = vtkActor()
 cylinderActor.SetMapper(cylinderMapper)
 (cylinderActor.GetProperty()).SetColor(color[0], color[1], color[2])
 cylinderActor.RotateX(rotation[0])
 cylinderActor.RotateY(rotation[1])
 cylinderActor.RotateZ(rotation[2])
 return cylinderActor
###### The Main Program Starts Here ################
# create a rendering window and renderer
ren = vtkRenderer()
renWin = vtkRenderWindow()
renWin.AddRenderer(ren)
renWin.SetSize(300,300)
renWin.StereoCapableWindowOn()
iren = vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
x_ox = 0; y_ox = 0; z_ox = 0
x_h1 = 10; y_h1 = 0; z_h1 = 0
x_h2 = 10*cos(104.5*pi/180); y_h2 = 10*sin(104.5*pi/180); z_h2 = 0
# Create the molecules
ren.AddActor( makeSphere(5, [x_ox, y_ox, z_ox], [1,0,0]) ) # Oxygen
ren.AddActor( makeSphere(2, [x_h1, y_h1, z_h1], [1,1,1]) ) # Hydrogen
ren.AddActor( makeSphere(2, [x_h2, y_h2, z_h2], [1,1,1]) ) # Hydrogen
# Create the connectors
ren.AddActor( makeCylinder(1, 10, [0, 5, 0], [0,0,1], [0,0,-90]) ) 
ren.AddActor( makeCylinder(1, 10, [0, 5, 0], [0,0,1], [0,0, 14.5]) ) 
# enable user interface interactor
iren.Initialize()
iren.Start()

 
1 comments:
Thank you for your work
Post a Comment