
import OpenGL.GL as gl

import glitch
from glitch.limbo.point import Point, normal

class Mesh(glitch.Node):
    def __init__(self):
        glitch.Node.__init__(self)
        self.vertices = []
        self.edges = []

    def draw(self, ctx):
        if ctx.get('debug', False):
            gl.glPushAttrib(gl.GL_POLYGON_BIT | gl.GL_LIGHTING_BIT)
            gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE)

        gl.glBegin(gl.GL_TRIANGLES)

        for (i1, i2, i3) in self.faces:
            (v1, v2, v3) = (
                Point(*self.vertices[i1]),
                Point(*self.vertices[i2]),
                Point(*self.vertices[i3]))
            # XXX: Precalculate normals.
            n = normal(v1, v2, v3)
            gl.glNormal(*n.normalize())
            gl.glVertex(*v1)
            gl.glVertex(*v2)
            gl.glVertex(*v3)

        gl.glEnd()

        if ctx.get('debug', False):
            # Draw normals.
            gl.glBegin(gl.GL_LINES)
            gl.glMaterial(
                gl.GL_FRONT, gl.GL_AMBIENT_AND_DIFFUSE, (0, 1, 0, 1)),

            for (i1, i2, i3) in self.faces:
                (v1, v2, v3) = (
                    Point(*self.vertices[i1]),
                    Point(*self.vertices[i2]),
                    Point(*self.vertices[i3]))
                n = normal(v1, v2, v3)
                p1 = Point(
                    (float(v1.px) + v2.px + v3.px) / 3,
                    (float(v1.py) + v2.py + v3.py) / 3,
                    (float(v1.pz) + v2.pz + v3.pz) / 3)
                p2 = p1 + n.normalize() / 10
                gl.glVertex(*p1)
                gl.glVertex(*p2)

            gl.glEnd()
            gl.glPopAttrib()

