/Richter/Collage.py
from Sprite import Sprite
from OpenGL.GL import *
from Numeric import array
import pygame

import TexMan

class Collage:
	tiles = None
	displaylist = None
	bbox = None

	def __init__(self, file):
		self.parse(file)
	

	def parse(self, file):
		if self.displaylist == None:
			self.displaylist = glGenLists(1)
		glNewList(self.displaylist, GL_COMPILE)
		glEnable(GL_TEXTURE_2D)
		glColor3f(1.0,1.0,1.0)
		ctexture = None
		ctexsize = None
		vertexarray = []
		texcoordarray = []
		nvertices = 0
		#maxvertices = glGetIntegerv(GL_MAX_ELEMENTS_VERTICES)
		#maxindexes = glGetIntegerv(GL_MAX_ELEMENTS_INDICES)

		self.tiles = []
		mf = (1,1)
		f = open(file,'r')
		for line in f:
			args = line.split()
			if not args:
				continue
			cmd = args[0]
			args = args[1:]
			if cmd == 'tilesize':
				mf = (int(args[0]),int(args[1]))
			elif cmd == 'bbox':
				self.bbox = pygame.Rect(0, 0, mf[0] * int(args[0]), mf[1] * int(args[1]))
			elif cmd == 'texture':
				if nvertices > 0:	# dump vertex array
					glVertexPointer(3, GL_FLOAT, 0, array(vertexarray,'f'))
					glTexCoordPointer(2, GL_FLOAT, 0, array(texcoordarray,'f'))
					glDrawArrays(GL_QUADS, 0, nvertices)
					vertexarray = []
					texcoordarray = []
					nvertices = 0
				d = TexMan.load(args[0])
				ctexture = d['texture']
				ctexsize = d['tsize']
				glBindTexture(GL_TEXTURE_2D, ctexture)
			elif cmd == 'tile':
				x = int(args[0]) * mf[0]
				y = int(args[1]) * mf[1]
				vertexarray += [
					(x,y,0),
					(x+ctexsize[0],y,0),
					(x+ctexsize[0],y+ctexsize[1],0),
					(x,y+ctexsize[1],0)
				]
				texcoordarray += [
					(0.0,0.0),(1.0,0.0),(1.0,1.0),(0.0,1.0)
				]
				nvertices += 4
		f.close()
		# Finally,
		glVertexPointer(3, GL_FLOAT, 0, array(vertexarray,'f'))
		glTexCoordPointer(2, GL_FLOAT, 0, array(texcoordarray,'f'))
		glDrawArrays(GL_QUADS, 0, nvertices)
		glEndList()


	def draw(self):
		glCallList(self.displaylist)