package jocode;

import java.awt.*;
import java.nio.*;
import javax.media.opengl.*;

/**
 *  Wrap the functionality of a FrameBufferObject.  A GLFrameBuffer is a virtual
 *  screen that can be rendered to just like the real screen, but can be
 *  any dimensions.  Rendered results are stored in a texture.
 *
 *  By default this class creates a FBO with a renderBuffer attached to provide
 *  depth test, and one texture to hold the rendered image.  Can attach more
 *  textures and pick which will be rendered to.
 *
 *  Example:
 *		GLFrameBuffer FBO;
 *
 *		init() {
 *			FBO = new GLFrameBuffer();    // by default setup a depth buffer and texture same size as display
 *		}
 *
 *		draw() {
 *			FBO.activate();
 *			// further rendering goes into FBO texture...
 *
 *			FBO.deactivate();
 *			// further rendering goes to screen
 *
 *			GLApp.activateTexture(FBO.getTexture(0));
 *			//... do more rendering with FBO texture...
 *		}
 *
 */
public class JOFrameBuffer {
	int FBOhandle = 0;     // FrameBuffer Object
	int RBhandle = 0;      // RenderBuffer Object (provides depth buffer)
	int Thandle = 0;       // Texture that we'll render into

	int width;				// dimensions of framebuffer
	int height;

	int[] renderTargets = new int[4];        // handles to additional textures that are attached
	int[] renderTargetTypes = new int[] {
	    GL.GL_COLOR_ATTACHMENT0_EXT,
	    GL.GL_COLOR_ATTACHMENT1_EXT,
	    GL.GL_COLOR_ATTACHMENT2_EXT,
	    GL.GL_COLOR_ATTACHMENT3_EXT
	};
	int targetCount = 0;

	int status = 0;  // status returned by OpenGL after FBO init
				// if this isn't == GL_FRAMEBUFFER_COMPLETE_EXT then init() had a problem

	int[] attachmentPoint = new int[] {
	    GL.GL_COLOR_ATTACHMENT0_EXT, 
	    GL.GL_COLOR_ATTACHMENT1_EXT,
	    GL.GL_COLOR_ATTACHMENT2_EXT,
	    GL.GL_COLOR_ATTACHMENT3_EXT 
	};

	/**
	 *  Create a framebuffer the same dimensions as current screen
	 */
	public JOFrameBuffer() {
	    DisplayMode DM = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayMode();  // current display settings
        width = DM.getWidth();
		height = DM.getHeight();
		init();
	}

	/**
	 *  Create a framebuffer with the given dimensions
	 */
	public JOFrameBuffer(int w, int h) {
		// use given width, height
		width = w;
		height = h;
		init();
	}

	/**
	 *  Prepare framebuffer for use.  Width and height should be set to rational values
	 *  before calling this function.  Creates framebuffer with depth buffer and one texture.
	 */
	public int init() {
		// create a FBO handle
		FBOhandle = allocateFBO();

		// Bind this FBO to our current OpenGL context, so we can perform operations on it
		JOApp.gl.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, FBOhandle);

		// create renderbuffer
		RBhandle = makeRenderBuffer(width,height);

		// attach to framebuffer
		addRenderBuffer(RBhandle);

		// make texture the same size as framebuffer
		Thandle = makeTexture();

		// attach texture to framebuffer
		addTexture(Thandle);

		// !!! add a second texture
		Thandle = makeTexture();
		addTexture(Thandle);

		// check for error condition
		status = checkStatus();

		// switch back to window-system-provided framebuffer
		JOApp.gl.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, 0);

		return status;
	}

	/**
	 *  return a new framebufferObject handle
	 */
    public static int allocateFBO() {
        IntBuffer handle = JOApp.allocInts(1);
		JOApp.gl.glGenFramebuffersEXT(1, handle);
        return handle.get(0);
    }

	/**
	 *  Return a handle to a new texture the same size as the framebuffer.
	 */
	public int makeTexture() {
		//int thandle = GLApp.makeTexture(width,height);  // hack!!!
		int thandle = makeTexture(width,height);
		return thandle;
	}

    //================================================================================
    // HACK!!!  code from new GLApp
	
    /**
     * Create a blank texture with the given width and height.
     * @return  the texture handle
     */
    public static int makeTexture(int w, int h) {
        ByteBuffer pixels = JOApp.allocBytes(w*h*JOApp.SIZE_INT);  // allocate 4 bytes per pixel
        return JOApp.makeTexture(pixels, w, h, false);
	}

    //================================================================================
    
    /**
	 *  Attach a texture to framebuffer.  Texture must be same dimensions as framebuffer.
	 *  To render to different textures, create one FrameBufferObject and attach/detach
	 *  the textures to render to each.  It's faster to swap textures than to bind/unbind
	 *  FrameBuffers.
	 *
	 *  @see makeTexture
	 */
	public int addTexture(int thandle) {		
		// attach texture to the FBO so we can render to it
		// for now only attaches one texture to first attachment point
		JOApp.gl.glFramebufferTexture2DEXT(GL.GL_FRAMEBUFFER_EXT, attachmentPoint[targetCount], GL.GL_TEXTURE_2D, thandle, 0);

		// generate mipmaps for texture
		JOApp.gl.glGenerateMipmapEXT(GL.GL_TEXTURE_2D);

		System.out.println("FBO add thandle=" + thandle + " at rendertarget=" +targetCount );

		// update render targets array
		renderTargets[targetCount] = thandle;
		targetCount++;

		//GLApp.msg("FBO add thandle=" + thandle);
		return thandle;
	}


	/**
	 *  Remove a texture from the framebuffer.  Texture still exists, but will no
	 *  longer be rendered to.
	 */
	public void removeTexture() {
		// attach texture 0 to the FBO
		// for now assumes one texture only on the first attachment point
	    JOApp.gl.glFramebufferTexture2DEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_COLOR_ATTACHMENT0_EXT, GL.GL_TEXTURE_2D, 0, 0);
	}


	// should this take the attachment point as an arg (assuming depth buffer here)
	// renderbuffer was made with only gl_depth_component storage, so has to attach to depth_attachment.
	// if renderbuffer had RGB, BGRA, RGBA storage then it should be attached to a color_attachment point.
	public void addRenderBuffer(int rbhandle) {
		// attach renderbuffer to the FBO
	    JOApp.gl.glFramebufferRenderbufferEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_DEPTH_ATTACHMENT_EXT, GL.GL_RENDERBUFFER_EXT, rbhandle);
	}


	/**
	 *  Return the handle to a new renderBuffer, configured as a depth buffer
	 */
	 // assuming this is for depth buffer only (can render buffer also have color info in it?)
	public int makeRenderBuffer(int width, int height) {
		// get a handle to a renderbuffer:
		int bufferHandle = 0;
		IntBuffer depthbuffer = JOApp.allocInts(1);
		JOApp.gl.glGenRenderbuffersEXT(1, depthbuffer);
		bufferHandle = depthbuffer.get(0);

		// bind the renderbuffer so that we can operate on it.
		JOApp.gl.glBindRenderbufferEXT(GL.GL_RENDERBUFFER_EXT, bufferHandle);

		// allocate storage space for the depth buffer
		// allocating only depth storage here (so should attach this rb to the depth attach point only)
		JOApp.gl.glRenderbufferStorageEXT(GL.GL_RENDERBUFFER_EXT, GL.GL_DEPTH_COMPONENT, width, height);

		return bufferHandle;
	}


	/**
	 *  Return the error code from the FBO
	 */
	public int checkStatus() {
		// return the status of the currently bound FBO
		int status = JOApp.gl.glCheckFramebufferStatusEXT(GL.GL_FRAMEBUFFER_EXT);
		if (status != GL.GL_FRAMEBUFFER_COMPLETE_EXT) {
			//GLApp.err("FrameBufferObject.checkStatus(): framebuffer init failed, status is " + status);
			System.out.println("FrameBufferObject.checkStatus(): framebuffer init failed, status is " + status);
		}
		return status; 
	}


	/**
	 *  Once activated() all further rendering will go to the framebufferobject
	 *  @see deactivate()
	 */
	public void activate() {
		// Select the framebuffer for subsequent rendering operations
	    JOApp.gl.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, FBOhandle);

		// do I need to include the renderBuffer as a draw target?
		//glDrawBuffer(1, new int[] {GL_COLOR_ATTACHMENT0_EXT});
	    JOApp.gl.glDrawBuffer(GL.GL_COLOR_ATTACHMENT0_EXT);

		// Set viewport to match fbo dimensions
	    JOApp.gl.glPushAttrib(GL.GL_VIEWPORT_BIT);
	    JOApp.gl.glViewport(0, 0, width, height);
	}


	/**
	 *  Once deactivated all further rendering goes to the screen
	 */
	public void deactivate() {
		// return viewport to previous state
	    JOApp.gl.glPopAttrib();

		// Stop rendering to FBO
	    JOApp.gl.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, 0);
	}


	// return a bytebuffer containing pixels from renderbuffer
	// does this make sense?  does a renderbuffer have color pixel values?
	public ByteBuffer getFramePixels(ByteBuffer pixels) {
		// fill pixels with renderbuffer pixels
		return null;
	}

	public ByteBuffer getFramePixels() {
		//return ByteBuffer pixels;
		return null;
	}


	/**
	 *  return handle of texture attached to framebuffer
	 * textures are numbered 0-N
	 */
	public int getTexture(int targetIndex) {
		if (targetIndex >= 0 && targetIndex < renderTargets.length) {
			return renderTargets[targetIndex];
		}
		return 0;
	}


	/**
	 *  delete the framebufferobject and renderbufferobject
	 */
	public void cleanup() {
		// FBO
		deleteFBO(FBOhandle);

		// render buffer
		deleteRenderBuffer(RBhandle);
	}


    /**
     * De-allocate the given FrameBufferObject.
     */
    public static void deleteFBO(int handle)
    {
        IntBuffer handleBuff = JOApp.allocInts(1).put(handle);
        JOApp.gl.glDeleteFramebuffersEXT(1, handleBuff);
    }


    /**
     * De-allocate the given RenderBuffer.
     */
    public static void deleteRenderBuffer(int handle)
    {
        IntBuffer handleBuff = JOApp.allocInts(1).put(handle);
        JOApp.gl.glDeleteRenderbuffersEXT(1, handleBuff);
    }


    public int getWidth() {
		return width;
	}


	public int getHeight() {
		return height;
	}


	public void drawTo(int targetNumber) {
		// need an array of all targets, created by addTexture()
		// this function creates an array of 1-4 renderTargets (ints)
		// renderTargets = new int[1];
		// activate() will call glDrawBuffer() with the renderTargets array
		// or maybe do it here once, leave it out of activate()

	    JOApp.gl.glDrawBuffer(attachmentPoint[targetNumber]);
	}


	public void drawTo(int tn1, int tn2) {
		// renderTargets = new int[2];
	}


	public void drawTo(int tn1, int tn2, int tn3) {
		// renderTargets = new int[3];
	}


	public void drawTo(int[] targets) {
		// renderTargets = targets;
	}

}


