/*
 * Copyright (C) 2001-2008, R3vis Corporation.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA,
 * or visit http://www.gnu.org/copyleft/gpl.html.
 *
 * Contributor(s):
 *   Wes Bethel, R3vis Corporation, Marin County, California
 *
 * The OpenRM project is located at http://openrm.sourceforge.net/.
 */
/*
 * $Id: autoTmap.c,v 1.4 2008/11/09 14:37:04 wes Exp $
 * $Revision: 1.4 $
 * $Name: v180-alpha-01 $
 * $Log: autoTmap.c,v $
 * Revision 1.4  2008/11/09 14:37:04  wes
 * Update dates to 2008
 *
 * Revision 1.3  2006/08/08 03:49:21  wes
 * Updates to reflect ergonomic changes to rmaux
 *
 * Revision 1.2  2005/06/08 18:31:08  wes
 * Code cleanup to eliminate compiler warnings.
 *
 * Revision 1.1  2004/08/07 17:20:12  wes
 * Initial entry.
 *
 */

/*
 * usage: autoTmap [-w imgWidthPixels -h imgHeightPixels]
 *
 */

#include <stdio.h>
#ifndef RM_WIN
#include <unistd.h>
#endif
#include <rm/rm.h>   
#include <rm/rmaux.h>
#include <rm/rmi.h>
#include "procmode.h"

static RMpipe *myPipe=NULL;

#define DEFAULT_IMAGE_WIDTH 640
#define DEFAULT_IMAGE_HEIGHT 525


int myPreTraversalCallback(const RMnode *n,
			   const RMstate *s)
{
#if 0
    glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
    glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
#endif
#if 1
    glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
    glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
    {
	GLfloat xEqualZero[] = {0., .60, 0., 0.5};
	glTexGenfv(GL_T, GL_OBJECT_PLANE, xEqualZero);
    }
#endif
#if 0
    glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
    glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
#endif    
    glEnable(GL_TEXTURE_GEN_S);
    glEnable(GL_TEXTURE_GEN_T);

    /* foil compiler warnings */
    n = NULL;
    s = NULL;
    
    return 1;
}

int myPostTraversalCallback(const RMnode *n,
			    const RMstate *s)
{
    glDisable(GL_TEXTURE_GEN_S);
    glDisable(GL_TEXTURE_GEN_T);

    /* foil compiler warnings */
    n = NULL;
    s = NULL;
	
    return 1;
}

void
makeTexturedSphere(RMnode *addTo)
{
/*    RMimage *i = rmiReadJPEG("data/earthLights.jpg"); */
    RMimage *i = rmiReadJPEG("data/seaSurfaceTemperature.jpg");
    RMtexture *t = rmTextureNew(2);
    RMnode *textureNode = rmNodeNew("textureNode", RM_RENDERPASS_3D, RM_RENDERPASS_ALL);
    RMnode *sphereNode = rmNodeNew("sphereNode", RM_RENDERPASS_3D, RM_RENDERPASS_OPAQUE);

#define SPHERES 1 
/*#define CONES 1  */
/* #define CYLINDERS 1 */

#if SPHERES
    RMprimitive *p = rmPrimitiveNew(RM_SPHERES);
    RMvertex3D v[1] = {{0.0, 0.0, 0.0}};
#elif CONES
    RMprimitive *p = rmPrimitiveNew(RM_CONES);
    RMvertex3D v[2] = {{0.0, -1.0, 0.0}, {0.0, 1.0, 0.0}};
#elif CYLINDERS
    RMprimitive *p = rmPrimitiveNew(RM_CYLINDERS);
    RMvertex3D v[2] = {{0.0, -2.0, 0.0}, {0.0, 2.0, 0.0}};
#endif
    RMcolor4D c = {1.0, 1.0, 1.0, 1.0};
    float radius=1.0F;

    if (i == NULL)
    {
	rmError("unable to read the texture image file. Bye!");
	exit(-1);
    }

#if SPHERES
    rmPrimitiveSetVertex3D(p, 1, v, RM_COPY_DATA, NULL);
    rmPrimitiveSetModelFlag(p, RM_SPHERES_512);
#elif CONES
    rmPrimitiveSetVertex3D(p, 2, v, RM_COPY_DATA, NULL);
    rmPrimitiveSetModelFlag(p, RM_CONES_128);
#elif CYLINDERS
    rmPrimitiveSetVertex3D(p, 2, v, RM_COPY_DATA, NULL);
    rmPrimitiveSetModelFlag(p, RM_CYLINDERS_128);
#endif
    rmPrimitiveSetRadii(p, 1, &radius, RM_COPY_DATA, NULL);
    rmPrimitiveSetColor4D(p, 1, &c, RM_COPY_DATA, NULL);
    rmNodeSetUnlitColor(sphereNode, &c);
    rmNodeAddPrimitive(sphereNode, p);
    rmNodeComputeBoundingBox(sphereNode);

    rmNodeAddChild(textureNode, sphereNode);
    rmNodeAddChild(addTo, textureNode);
    rmNodeUnionAllBoxes(addTo);

    rmImageMirror(i, RM_IMAGE_MIRROR_HEIGHT);
    rmTextureSetImages(t, &i, 1, 0);
    rmTextureSetEnv(t, GL_DECAL, NULL); 
    rmTextureSetEnv(t, GL_MODULATE, NULL);
    rmTextureSetWrapMode(t, GL_REPEAT);
    rmNodeSetSceneTexture(textureNode, t);  

    rmTextureDelete(t, RM_TRUE);

    rmNodeSetPreTraversalCallback(sphereNode, RM_RENDER, myPreTraversalCallback);
    rmNodeSetPostTraversalCallback(sphereNode, RM_RENDER, myPostTraversalCallback);
}

void
makeBackgroundClear(RMnode *addTo)
{
    RMcolor4D c={0.1, 0.1, 0.2, 1.0};
    RMnode *n = rmNodeNew("backgroundClear", RM_RENDERPASS_3D, RM_RENDERPASS_OPAQUE);
    rmNodeSetSceneBackgroundColor(n, &c);
    rmNodeAddChild(addTo, n);
}

void
computeSceneCamera(RMnode *addTo,
		   const RMpipe *p)
{
    RMcamera3D *c = rmCamera3DNew();
    int width, height;

    rmDefaultCamera3D(c);
    rmPipeGetWindowSize(p, &width, &height);
    rmCamera3DComputeViewFromGeometry(c, addTo, width, height);

    rmNodeSetSceneCamera3D(addTo, c);
}

void
myInitFunc(RMpipe *p,
	   RMnode *addTo,
	   void *usrData)
{
    RMnode *myRoot = rmNodeNew("myRoot", RM_RENDERPASS_3D, RM_RENDERPASS_OPAQUE);
    makeBackgroundClear(addTo);
    makeTexturedSphere(myRoot);
    rmNodeAddChild(addTo, myRoot);
    rmNodeUnionAllBoxes(addTo);
    
    computeSceneCamera(myRoot, p);
    
    rmDefaultLighting(addTo);
    rmauxSetGeomTransform(myRoot,p);  
    rmauxSetCamera3DTransform(myRoot, p); 

    rmFrame(p, addTo); 
}

int
myRenderFunc(RMpipe *myPipe,
	     RMnode *subTree,
	     void *usrData)
{
    /* insert code to call frame-based renderer here */
    rmFrame(myPipe, subTree);
    return 1;
}

void
usage(char *s)
{
    printf("usage: %s [-w imgWidthPixels ] [-h imgHeightPixels] \n",s);
}

void
parseArgs(int ac,
	  char *av[],
	  int *imgWidth,
	  int *imgHeight)
{
    int i;

    i = 1;
    while (i < ac)
    {
	if (strcmp(av[i],"-w") == 0)
	{
	    i++;
	    sscanf(av[i],"%d", imgWidth);
	}
	else if (strcmp(av[i],"-h") == 0)
	{
	    i++;
	    sscanf(av[i],"%d", imgHeight);
	}
	else
	{
	    usage(av[0]);
	    exit(-1);
	}
	i++;
    }
}

#ifdef RM_WIN
int WINAPI WinMain (HINSTANCE hInstance,
		    HINSTANCE hPrevInstance,
                    LPSTR lpszCmdLine, int nCmdShow)
{
    MSG      msg; 
    HWND     hWnd; 
    void *fptr;
    
    int imgWidth, imgHeight;
    RMenum processingMode = DEFAULT_PROCESSING_MODE; /* in procmode.h */
    RMenum targetPlatform = RM_PIPE_WGL;

    imgWidth = DEFAULT_IMAGE_WIDTH;
    imgHeight = DEFAULT_IMAGE_HEIGHT;
    
    parseArgs(__argc, __argv, &imgWidth, &imgHeight);
    
#else  /* assume RM_X */
int
main(int argc,
     char *argv[])
{
    void *msg;			/* needed for rmauxEventLoop
				 win32/unix API consistency */
    int imgWidth, imgHeight;
    RMenum processingMode = DEFAULT_PROCESSING_MODE; /* in procmode.h */
    RMenum targetPlatform = RM_PIPE_GLX;

    imgWidth = DEFAULT_IMAGE_WIDTH;
    imgHeight = DEFAULT_IMAGE_HEIGHT;
    
    parseArgs(argc, argv, &imgWidth, &imgHeight);
#endif

    /* 
     * first stage of RM initialization.
     */
    rmInit();

    /* 
     * create the rendering pipe. this step is required in both
     * Win32 and X.
     */
    myPipe = rmPipeNew(targetPlatform);
    
    processingMode = RM_PIPE_MULTISTAGE;
    rmPipeSetProcessingMode(myPipe, processingMode);

#ifdef RM_WIN
    {
        /*
	 * Win32: when a window is created, we have to tell windows the
	 * name of the "WndProc," the procedure that gets called by
	 * windows with events (the event loop) (contrast to the X model 
	 * where the name of the event loop is not part of the window). 
	 * Since we're using RMaux, we know about the event handling 
	 * procedure named "rmauxWndProc" and we provide that here. 
	 */

        fptr = (void *)(rmauxWndProc);
	hWnd = rmauxCreateW32Window(myPipe,
			       NULL, /* no parent window */
			       20,20,imgWidth,imgHeight,"RM for Windows",
			       hInstance,fptr);
	if (hWnd == 0)
	  exit(-1);

	/* 
	 * assign the new window handle to the rendering pipe.
	 */
	rmPipeSetWindow(myPipe,hWnd, imgWidth, imgHeight);
    }
#endif
#ifdef RM_X
    {
	Window w;

	w = rmauxCreateXWindow(myPipe,
			       (Window)NULL, /* parent window */
			       0,0,imgWidth,imgHeight,
			       "RM for X-Windows","RM for X-Windows",RM_TRUE);

	/* 
	 * assign the window to the rendering pipe.
	 */
	rmPipeSetWindow(myPipe,w,imgWidth,imgHeight);
    }
#endif

    /* 
     * X-ism: once the window is created and assigned to the 
     * rendering pipe, rmPipeMakeCurrent makes the OpenGL rendering context
     * current for the pipe+window combination. 
     *
     * this step is required for X. in these demo programs, it is not 
     * strictly required by Win32, as the newly created context is made
     * current as part of the OpenGL initialization sequence.
     */
    rmPipeMakeCurrent(myPipe);	

    rmauxSetInitCallbackFunc(myInitFunc, NULL);
    rmauxSetRenderCallbackFunc(myRenderFunc, NULL);
    
    /*
     * set key handler function so this prog will exit on "q" key.
     */
    rmauxSetKeypressCallbackFunc(rmauxDefaultKeyFunc, NULL);
    
    rmauxEventLoop(myPipe,rmRootNode(), &msg);

    rmPipeDelete(myPipe);
    rmFinish();

    return(1);
}
   
