demos/plyreader.py
author Radek Brich <radek.brich@devl.cz>
Tue, 29 Apr 2008 23:31:08 +0200
branchpyrit
changeset 90 f6a72eb99631
parent 75 20dee9819b17
child 97 2a853d284a6a
permissions -rw-r--r--
rename Python module from 'raytracer' to 'pyrit' improve Python binding: - new objects: Container, Octree, KdTree, Shape, Pixmap, Sampler, DefaultSampler - all shapes are now subclasses of Shape - clean, remove redundant Getattr's - Raytracer render method now just wraps C++ method without doing any additional work adjust all demos for changes in Python binding, remove PIL dependency add demo_PIL.py as a example of pyrit + PIL usage render_nff.py now either loads file given as a argument or reads input from stdin otherwise fix bug in pixmap float to char conversion

# Stanford .ply file loader

from pyrit import Triangle, NormalVertex

def LoadStanfordPlyFile(rt, filename, mat, scale=(1,1,1), trans=(0,0,0)):
	if (type(scale) == float or type(scale) == int):
		scale = (scale,)*3
	vertices = []
	normals = []
	vertex_face_num = []
	fp = file(filename)
	# read header
	tokens = (0,)
	while (tokens[0] != "end_header"):
		tokens = fp.readline().split()
		if (tokens[0] == "element"):
			if (tokens[1] == "vertex"):
				vertex_num = int(tokens[2])
			if (tokens[1] == "face"):
				face_num = int(tokens[2])

	# read vertices
	num = vertex_num
	while (num):
		tokens = fp.readline().split()
		v = [float(x) for x in tokens[0:3]]
		v[0] = scale[0]*v[0] + trans[0]
		v[1] = scale[1]*v[1] + trans[1]
		v[2] = scale[2]*v[2] + trans[2]
		vertices.append(NormalVertex(tuple(v)))
		normals.append([0.,0.,0.])
		vertex_face_num.append(0)
		num -= 1

	# read faces
	while (face_num):
		tokens = fp.readline().split()
		if (tokens[0] != "3"):
			print "ply warning: faces of %d vertices not supported" % tokens[0]
		v = [vertices[int(x)] for x in tokens[1:4]]
		face = Triangle(v[0], v[2], v[1], mat)
		n = face.getNormal()
		for x in tokens[1:4]:
			for i in range(3):
				normals[int(x)][i] += n[i]
			vertex_face_num[int(x)] += 1
		rt.addShape(face)
		face_num -= 1

	# interpolate normals at vertices
	num = 0
	while (num < vertex_num):
		if (vertex_face_num[num] > 0):
			for i in range(3):
				normals[num][i] /= vertex_face_num[num]
		vertices[num].setNormal(tuple(normals[num]))
		num += 1