
from __future__ import with_statement

"A camera that renders to an image file."

import Image

from glitch.camera import Camera
from glitch.read import Read
from glitch.fbo import BufferCamera
from glitch.glx import GLXContext

class ImageCamera(Camera):
    "A camera that renders to an image file."

    def __init__(self, width, height, out, *args, **kwargs):
        self.out = out
        Camera.__init__(self, *args, **kwargs)
        self.context['w'] = width
        self.context['h'] = height
        self.context['frame'] = 0
        self.glx_context = GLXContext()

    def render(self, parent_ctx=None):
        with self.glx_context:
            read = Read(children=self.children)
            bc = BufferCamera(
                # XXX: Nicer way to pass values through?
                eye=self.eye, ref=self.ref, up=self.up, fovy=self.fovy,
                fovx=self.fovx, zNear=self.zNear, zFar=self.zFar,
                clear=self.clear,
                width=self.context['w'], height=self.context['h'],
                children=[read])
            bc.render(None)

        im = Image.fromstring('RGB', (self.context['w'], self.context['h']),
            read.get_pixbuf().get_pixels())
        # XXX: Return the image somehow instead of saving it.
        im.save(self.out % (self.context['frame']))
        self.context['frame'] += 1

