/*
 * Copyright (C) 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: cbUsrDataTest.c,v 1.2 2008/11/09 14:37:04 wes Exp $
 * $Revision: 1.2 $
 * $Name: v180-alpha-01 $
 * $Log: cbUsrDataTest.c,v $
 * Revision 1.2  2008/11/09 14:37:04  wes
 * Update dates to 2008
 *
 * Revision 1.1  2007/05/14 15:25:08  wes
 * Initial entry
 *
 */

/*
 * usage: cbUsrDataTest [-w imgWidthPixels -h imgHeightPixels]
 *
 * This sample application exercises the capability to provide and
 * access "user data" when using the rmauxSet*Callback routines.
 */

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

static RMpipe *myPipe=NULL;

#define DEFAULT_IMAGE_WIDTH 640
#define DEFAULT_IMAGE_HEIGHT 525

void
myInitFunc(RMpipe *pipe,
	   RMnode *addTo,
	   void *usrData)
{
    RMcolor4D darkGreen={0.0F, 0.2F, 0.0F, 1.0F};
    RMnode *n = rmNodeNew("textNode", RM_RENDERPASS_2D, RM_RENDERPASS_ALL);
    RMprimitive *p = rmPrimitiveNew(RM_TEXT);
    RMtextProps *tp = rmTextPropsNew();

    /* we can make assumptions about the default world coordinate system
     when we don't specify a camera, and set vertex values accordingly */
    RMvertex2D v = {0.0F, 0.0F};
    char s[] = {"With the pointer in the window, press mouse buttons or type some text. Type q to quit."};
    char *string = s;

    rmPrimitiveSetVertex2D(p, 1, &v, RM_COPY_DATA, NULL);
    rmPrimitiveSetText(p, 1, &string);
    rmNodeAddPrimitive(n, p);

    rmTextPropsSetAttribs(tp, RM_FONT_SANS, RM_FONT_S, RM_FALSE, RM_FALSE, RM_CENTER, RM_CENTER);
    rmNodeSetSceneTextProps(n, tp);

    rmNodeAddChild(addTo, n);

    rmPipeSetSceneBackgroundColor(pipe, &darkGreen);

    rmFrame(pipe, addTo);
}

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++;
	    ac--;
	    sscanf(av[i],"%d", imgWidth);
	}
	else if (strcmp(av[i],"-h") == 0)
	{
	    i++;
	    ac--;
	    sscanf(av[i],"%d", imgHeight);
	}
	else
	{
	    usage(av[0]);
	    exit(-1);
	}
	i++;
    }
}

int
myKeyFunc (RMpipe *currentPipe,
	   RMnode *n,
	   void *usrData,
	   char    key, 
	   KeySym  code)
{
    /* convert to lower case */
    if ((key >= 'A') && (key <= 'Z'))
	key = key - ('A' - 'a');


    /*
     * debug code to print out the key on the kbd that was pressed.
     * note that only printable ascii chars are processed by this
     * routine. refer to your Win32 dev documentation to learn
     * more about which keys actually generate an WM_CHAR message type.
     */

    {
	char buf[128];
	sprintf(buf, " key is <%c>. User data is <%s> \n", key, (usrData == NULL) ? "NULL" : (char *)usrData);
	rmNotice(buf);
    }

    /* take appropriate menu action */
    switch (key)
    {
       case 'q': /* quitting time */
	   return 0;
	   break;

       default: /* do nothing */
	   break;
    }


    /* foil compiler warnings */
    code = (KeySym) 0;
    currentPipe = NULL;
    n = NULL;
/*    usrData = NULL; */
    
    return 1;
}

int 
myButtonDownCallbackFunc(RMpipe *p, 
			 RMnode *n, 
			 void *usrData, 
			 int xb, 
			 int yb)
{
    if (usrData != NULL)
	rmNotice((char *)usrData);
    else
    {
	char buf[64];
	sprintf(buf, "button press callback with no user data. ");
	rmNotice(buf);
    }
    return 1;
}

int
myRenderCallbackFunc(RMpipe *p,
		     RMnode *n,
		     void *usrData)
{
    rmFrame(p, n);

    if (usrData != NULL)
	rmNotice((char *)usrData);
    else
    {
	char buf[64];
	sprintf(buf, "render callback with no user data. ");
	rmNotice(buf);
    }

    /* turn off render callback after it fires once. Otherwise, on Win32
     systems, you'll get a really annoying pile of rmNotice's to clean up */
    rmauxSetRenderCallbackFunc(NULL, NULL);

    return 1;

}

#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);

    /* set up callbacks with some text-based usrdata */
    rmauxSetButtonDownCallbackFunc(myButtonDownCallbackFunc, "button 1 down user data: One fish, two fish, red fish, blue fish. ", RM_BUTTON1, RM_NONE_MODMASK);
    rmauxSetButtonDownCallbackFunc(myButtonDownCallbackFunc, "button 2 down user data: Green Eggs and Ham. ", RM_BUTTON2, RM_NONE_MODMASK);

    rmauxSetButtonDownCallbackFunc(myButtonDownCallbackFunc, "button 3 down user data: Hunches in Bunches. ", RM_BUTTON3, RM_NONE_MODMASK);

#ifndef RM_WIN
    /* Windows is really annoying -- it will invoke the rendering function
     callback too many times before our callback function sets the
     rendering callback to NULL. Trust me -- the callback with user data
     works under Windows. */
    rmauxSetRenderCallbackFunc(myRenderCallbackFunc, "render callback user data: The Cat in the Hat Came Back");
#endif
    
    /*
     * set key handler function so this prog will exit on "q" key.
     */
    rmauxSetKeypressCallbackFunc(myKeyFunc, "testUserData"); 
/*    rmauxSetKeypressCallbackFunc(myKeyFunc, NULL); */
    
    rmauxEventLoop(myPipe,rmRootNode(), &msg);

    rmPipeDelete(myPipe);
    rmFinish();

    return(1);
}
   
/* EOF */ 
