
from __future__ import with_statement

import gtk

import glitch, glitch.gtk
from glitch.selectable import Selectable
from glitch.limbo.lights import LightSwitch, AmbientLight, DiffuseLight
from glitch.limbo.material import Material
from glitch.limbo.objects import Cube, Sphere, Teapot

def has_descendent(x, y):
    if y in x.children:
        return True
    else:
        for child in x.children:
            if has_descendent(child, y):
                return True

    return False

def on_click(window, event, camera):
    global selected
    (x, y) = event.get_coords()
    old_selected = selected
    selected = None

    # XXX: This might cause a buffer swap that's redundant.

    with camera as (w, h):
        hits = camera.select(camera.context, x, (h - y))

        if hits:
            for o in [teapot, cube, sphere]:
                if has_descendent(o, hits[-1]):
                    selected = o

        if selected != old_selected:
            if old_selected is not None:
                (old_selected.r, old_selected.g, old_selected.b) = \
                    (0.2, 0.2, 0.3)

            if selected is not None:
                (selected.r, selected.g, selected.b) = (0.2, 0.2, 1.0)

            camera.refresh_now()

if __name__=='__main__':
    selected = None
    teapot = Material(0.2, 0.2, 0.3, children=[
        glitch.Translate(-2, children=[
            Selectable(children=[Teapot(size=0.5)])])])
    cube = Material(0.2, 0.2, 0.3, children=[
        glitch.Translate(x=2, children=[
            Selectable(children=[Cube()])])])
    sphere = Material(0.2, 0.2, 0.3, children=[
        glitch.Translate(z=-2, children=[
            Selectable(children=[Sphere()])])])
    camera = glitch.gtk.GtkCamera(eye=[0, 1, 3], children=[
        LightSwitch(children=[
            AmbientLight(intensity=0.3, children=[
            DiffuseLight(intensity=0.4, children=
                [teapot, cube, sphere])])])])

    w = camera.make_window()
    w.show_all()

    camera.add_events(
        gtk.gdk.POINTER_MOTION_MASK |
        gtk.gdk.POINTER_MOTION_HINT_MASK)
    camera.connect('motion-notify-event', on_click, camera)

    gtk.main()

