from gi.repository import Clutter, Cogl

class TextureReflection (Clutter.Clone):
	# taken from the reflection.py example of pyClutter
	__gtype_name__ = 'TextureReflection'

	def __init__ (self, parent):
		Clutter.Clone.__init__(self)
		self.set_source(parent)
		self._reflection_height = -1

	def set_reflection_height (self, height):
		self._reflection_height = height
		self.queue_redraw()

	def get_reflection_height (self):
		return self._reflection_height

	def do_paint (self):
		parent = self.get_source()
		if (parent is None):
			return
		# get the Cogl handle for the parent texture
		Cogl_tex = parent.get_cogl_texture()
		if not Cogl_tex:
			return
		(width, height) = self.get_size()
		# clamp the reflection height if needed
		r_height = self._reflection_height
		if (r_height < 0 or r_height > height):
			r_height = height

		rty = float(r_height / height)

		opacity = self.get_paint_opacity()

		color1 = Cogl.color_premultiply((1, 1, 1, opacity/255.))
		color2 = Cogl.color_premultiply((1, 1, 1, 0))
		vertices = ( \
			(    0,        0, 0, 0.0, 1.0,   color1), \
			(width,        0, 0, 1.0, 1.0,   color1), \
			(width, r_height, 0, 1.0, 1.0-rty, color2), \
			(    0, r_height, 0, 0.0, 1.0-rty, color2), \
		)

		Cogl.push_matrix()

		Cogl.set_source_texture(Cogl_tex)
		Cogl.polygon(vertices=vertices, use_color=True)

		Cogl.pop_matrix()

if __name__ == "__main__":
	import sys
	def do_quit(*args):
		Clutter.main_quit()
	image_filename = sys.argv.pop(1)
	Clutter.init(sys.argv)
	stage = Clutter.Stage()
	stage.set_size(800,600)
	stage.connect('destroy', do_quit)
	stage.set_color(Clutter.Color.new(0, 0, 0, 255))
	stage.set_title('TextureReflection')
	tex = Clutter.Texture.new_from_file(image_filename)
	reflect = TextureReflection(tex)
	stage.add_actor(tex)
	stage.add_actor(reflect)
	stage.show()
	Clutter.main()


