
"Reading pixels from GPU memory."

from __future__ import absolute_import
import OpenGL.GL as gl

import glitch

class Read(glitch.Node):
    """Read pixels from GPU memory.

    After each render, the C{pixels} attribute is updated with the contents of
    the back buffer.
    """

    def __init__(self, **kw):
        glitch.Node.__init__(self, **kw)
        self.width = None
        self.height = None
        self.pixels = None

    def render(self, ctx):
        glitch.Node.render(self, ctx)
        self.width = ctx['w']
        self.height = ctx['h']
        self.pixels = gl.glReadPixels(
            0, 0, ctx['w'], ctx['h'], gl.GL_RGB, gl.GL_UNSIGNED_BYTE)
        assert len(self.pixels) == self.width * self.height * 3

    def get_pixbuf(self):
        # mainly useful for flipping pixel coordinate system
        import gtk
        pixbuf = gtk.gdk.pixbuf_new_from_data(self.pixels,
            gtk.gdk.COLORSPACE_RGB, False, 8, self.width, self.height,
            self.width * 3)
        return pixbuf.flip(False)
