import Blender
import sys
if sys.platform == "win32":
	import nt
else:
	import os

class Morph(object):
	
	originalPoints = []
	targetUsed = {}

	def __init__(self,thePath):

		self.path = thePath
		file = open(self.path+"base.mesh")
		vertexData = file.readline()
		while vertexData:
			PointToDraw = []
			vertexCoo = vertexData.split(',')
			PointToDraw.append(float(vertexCoo[0]))
			PointToDraw.append(float(vertexCoo[1]))
			PointToDraw.append(float(vertexCoo[2]))				
			self.originalPoints.append(PointToDraw)
			vertexData = file.readline()
		file.close()

	def doMorph(self,targetPath,Value):
		
		if self.targetUsed.has_key(targetPath):
			morphFactor = Value - self.targetUsed[targetPath]
		else:
			morphFactor = Value

		self.targetUsed[targetPath] = Value
		actual_obj = Blender.Object.Get("Base")
		actual_mesh = actual_obj.getData()

		try:
			fileDescriptor = open(targetPath)
		except IOError, (errno,strerror):
			print "I/O error(%s): %s" % (errno, strerror)
		try:
			stringData = fileDescriptor.readline()
		except IOError, (errno,strerror):
			print "I/O error(%s): %s" % (errno, strerror)

					
		while stringData:
			if stringData.find("#") == -1 and stringData.find(",") != -1: 
				#The second condition above is to check the line is not empty
				listData = stringData.split(',')
				try:
					pointIndex = int(listData[0])
					pointX = float(listData[1])
					pointY = float(listData[2])
					pointZ = float(listData[3])

					actual_mesh.verts[pointIndex].co[0] += (pointX-self.originalPoints[pointIndex][0])*morphFactor
					actual_mesh.verts[pointIndex].co[1] += (pointY-self.originalPoints[pointIndex][1])*morphFactor
					actual_mesh.verts[pointIndex].co[2] += (pointZ-self.originalPoints[pointIndex][2])*morphFactor
				except ValueError:
					print "the target file", fileName, "have some imperfection"
			else:
				print "COMMENT",stringData.replace("#"," ")
			stringData = fileDescriptor.readline()
					
		fileDescriptor.close()
		actual_mesh.update(1)
		actual_obj.makeDisplayList()				# added
		Blender.Window.RedrawAll()					# added