#SPACEHANDLER.VIEW3D.DRAW
from Blender import Image, Window, Mathutils, Draw
from Blender.BGL import *

# Draw the background
def drawImage():
	# Load image and data
	img.glLoad()
	width, height = [i for i in img.properties['OnionSkinning']['size']]
	offset = [i for i in img.properties['OnionSkinning']['offset']]
	zoom = img.properties['OnionSkinning']['zoom']
	zf = Window.GetPerspMatrix().scalePart().length/float(zoom)

	# Translate the view if window is offset, but rotation is correct
	if Window.GetViewOffset() != offset:
		#dehomogenizes a vector
		def dehom(v):
			ret = Mathutils.Vector(v[0]/v[3],v[1]/v[3],v[2]/v[3])
			return ret
		
		offset_vec = Mathutils.Vector(offset)
		world_x, world_y, world_z = Mathutils.Vector(Window.GetViewOffset()) - offset_vec
		mid_x = width/2.0
		mid_y = height/2.0
		win_width = width + 1.0
		win_height = height + 1.0
		pm = Window.GetPerspMatrix()
		
		coords = Mathutils.Vector(world_x,world_y,world_z,1.0)
		val = coords*pm
		val = dehom(val)
		zero = Mathutils.Vector(0,0,0,1)
		zeroval = zero*pm
		zeroval = dehom(zeroval)
		
		offx = val[0]*win_width/2.0
		offy = val[1]*win_height/2.0
		zerox = zeroval[0]*win_width/2.0
		zeroy = zeroval[1]*win_height/2.0
		wo = offx - zerox
		ho = offy - zeroy
	else:
		wo = 0
		ho = 0
	
	width *= zf
	height *= zf
	wo -= (width-(width/zf))/2.0
	ho -= (height-(height/zf))/2.0

	glEnable(GL_BLEND)
	Draw.Image(img, wo, ho, zf, zf)
	glDisable(GL_BLEND)
	
# Check if the image can be drawn
def main():
	global img
	
	try:
		img = Image.Get("OnionSkinning")
		finished = img.properties['OnionSkinning']['zoom']
	except:
		return
	
	if Window.GetViewQuat() == [q for q in img.properties['OnionSkinning']['view']]:
		drawImage()

main()