/*libCRWD Library based on 
  libC++RWD Library for C++ Rendering of White_dune Data (in Development)*/

/* Copyright (c) Stefan Wolf, 2010. */
/* Copyright (c) J. "MUFTI" Scheurich, 2010. */

/*
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <stdlib.h>
#include "CExport.c"
#include "libCRWD.h"
#define __USE_XOPEN 1 /* for M_PI */
#include <math.h>

#define Z_NEAR 0.05f
#define Z_FAR 7000.0f

static short viewpointRendered = 0;
static short lightRendered = 0;

static short pointLightexists = 0;
static short viewPointexists = 0;

static GLfloat viewpoint1Position[] = { 0, 0, 10 };

static short preRender = 0;
static short initRender = 0;

static struct X3dSceneGraph scenegraph;

static void error(const char *errormsg)
{
    #ifdef WIN32
    MessageBox(NULL, errormsg, NULL, MB_OK);
    #else
    fprintf(stderr, "%s\n", errormsg);
    #endif
}

void CRWDIndexedFaceSetRender(X3dNode *data, void *extraData)
{
    if(preRender)
    {
    }
    else if(initRender)
    {
    }
    else
    {
        struct X3dIndexedFaceSet *Xindexedfaceset = (struct X3dIndexedFaceSet*)data;
        struct X3dCoordinate *Xcoordinate = (struct X3dCoordinate*)Xindexedfaceset->coord;
        struct X3dNormal *Xnormal = (struct X3dNormal*)Xindexedfaceset->normal;
        struct X3dColor *Xcolor = (struct X3dColor*)Xindexedfaceset->color;
        struct X3dTextureCoordinate *Xtexturecoordinate = (struct X3dTextureCoordinate*)Xindexedfaceset->texCoord;
        GLint *faces = NULL;
        GLfloat *vertex = NULL;
        GLint *normalindex = NULL;
        GLfloat *normal = NULL;
        GLfloat *colors = NULL;
        GLint *colorindex = NULL;
        GLint *texturecoordinateindex = NULL;
        int faces_len, vertex_len, normalindex_len, normal_len, color_len, colorindex_len, texturecoordinateindex_len;
        short normalpervertex, colorpervertex;
        int i;
        int buffer, normalbuffer, texturebuffer;
        int facecounter = 0;

        if(Xcolor != NULL)
        {
            glEnable(GL_COLOR_MATERIAL); 
            glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE);
            colors = Xcolor->color;
            color_len = Xcolor->color_length;
            colorpervertex = Xindexedfaceset->colorPerVertex;
        }
        if(Xindexedfaceset->colorIndex != NULL)
        {
            colorindex = Xindexedfaceset->colorIndex;
            colorindex_len = Xindexedfaceset->colorIndex_length;
        }
        if(Xindexedfaceset->texCoordIndex != NULL)
        {
            texturecoordinateindex = Xindexedfaceset->texCoordIndex;
            texturecoordinateindex_len = Xindexedfaceset->texCoordIndex_length;
        }
        vertex = Xcoordinate->point;
        faces = Xindexedfaceset->coordIndex;
        normalindex = Xindexedfaceset->normalIndex;
        if(Xnormal!=NULL)normal = Xnormal->vector;
        vertex_len = Xcoordinate->point_length;
        faces_len = Xindexedfaceset->coordIndex_length;
        if(Xnormal != NULL)normal_len = Xnormal->vector_length;
        normalindex_len = Xindexedfaceset->normalIndex_length;
        normalpervertex = Xindexedfaceset->normalPerVertex;
        if (Xindexedfaceset->ccw != 0)
        {
           glFrontFace(GL_CCW);
        }
        else
        {
           glFrontFace(GL_CW);
        }
        if (Xindexedfaceset->solid == 0) 
        {
           glDisable(GL_CULL_FACE);
           glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
        } 
        else 
        {
           glEnable(GL_CULL_FACE);
           glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
        }

        glBegin(GL_POLYGON);
        if(colors && !colorpervertex)
            glColor3f(colors[facecounter], colors[facecounter + 1], colors[facecounter + 2]);

        for(i = 0; i != faces_len; i ++)
        {
            buffer = faces[i];
            if(normalindex != NULL)normalbuffer = normalindex[i];
            if(texturecoordinateindex != NULL)texturebuffer = texturecoordinateindex[i];
            if(buffer == -1 && (normalbuffer == -1 || normalindex != NULL))
            {
                facecounter++;
                glEnd();
                glBegin(GL_POLYGON);
                if(colors && !colorpervertex)
                        glColor3f(colors[3 * facecounter], colors[3 * facecounter + 1], colors[3 * facecounter + 2]);
            }
            else if(((buffer == -1 && normalbuffer != -1) || (buffer != -1 && normalbuffer == -1)) && normalindex != NULL)
                error("Error in normalIndex");
            else
            {
                if(normalpervertex && normal != NULL)glNormal3f(normal[normalbuffer*3], normal[normalbuffer*3+1], normal[normalbuffer*3+2]);
                if(colors && colorpervertex)glColor3f(colors[buffer*3], colors[buffer*3+1], colors[buffer*3+2]);
                if(texturecoordinateindex)glTexCoord2f(Xtexturecoordinate->point[texturebuffer*2], Xtexturecoordinate->point[texturebuffer*2+1]);
                glVertex3f(vertex[buffer*3], vertex[buffer*3+1], vertex[buffer*3+2]);
            }
        }
        glEnd();
    }
}

static int not2PowN(int number)
{
    int ret = -1;
    int i;
    for (i = 0; i < 32; i++)
        if (number == (1 << i))
        {
            ret = 0;
            break;
        }
    return ret;
}

static void renderTexture(int height, int width, int format, GLuint *data,
                          int repeatS, int repeatT)
{
    glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, 
                 GL_UNSIGNED_BYTE, data);
    if(repeatS)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    if(repeatT)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glEnable(GL_TEXTURE_2D);
}

void CRWDPixelTextureRender(X3dNode *data, void *extraData)
{
    int i;
    struct X3dPixelTexture *pixeltexture = (struct X3dPixelTexture*) data;
    if(preRender)
    {
    }
    else if(initRender)
    {
        int i;
        int bigEndian = 1;
        bigEndian = (*(unsigned char *)&bigEndian) == 0;

        if (not2PowN(pixeltexture->image[0]))
            error("warning: texture width is not 2 pow N");            
        if (not2PowN(pixeltexture->image[1]))
            error("warning: texture height is not 2 pow N");            
        if (pixeltexture->image[0] != pixeltexture->image[1])
            error("warning: texture width and height is not equal\n");
        /* store modified colors back to PixelTexture.image */
        for (i = 3; i < pixeltexture->image_length; i++) 
        {
            int a = 0xff;
            int r,g,b;
            switch (pixeltexture->image[2])
            {
              case 4:
                r = (pixeltexture->image[i]&0xFF000000) >> 24;
                g = (pixeltexture->image[i]&0x00FF0000) >> 16;
                b = (pixeltexture->image[i]&0x0000FF00) >> 8;
                a = (pixeltexture->image[i]&0x000000FF);
                break;
              case 3:
                r = (pixeltexture->image[i]&0x00FF0000) >> 16;
                g = (pixeltexture->image[i]&0x0000FF00) >> 8;
                b = (pixeltexture->image[i]&0x000000FF);
                break;
              case 2:
                r = g = b = (pixeltexture->image[i]&0x0000FF00) >> 8;
                a = (pixeltexture->image[i]&0x000000FF);
                break;
              case 1:
                r = g = b = (pixeltexture->image[i]&0xFF);
                break;
            }
            if (bigEndian)
            {
                pixeltexture->image[i] = a | 
                                         (b << 8) | (g << 16) | (r << 24);
            }
            else
            {
                pixeltexture->image[i] = r | (g << 8) | (b << 16) | 
                                         (a << 24);
            }
        }
    }
    else
        renderTexture(pixeltexture->image[0], pixeltexture->image[1], GL_RGBA, 
                      (GLuint *)&pixeltexture->image[3], 
                      pixeltexture->repeatS, pixeltexture->repeatT); 
}

void CRWDPointLightRender(X3dNode *data, void *extraData)
{
    if(preRender)
    {
        int i;
        struct X3dPointLight *light = (struct X3dPointLight*)data;
        GLfloat light_color[4];
        GLfloat light_ambient_color[4];
        GLfloat light_position[4];
        GLfloat light_attenuation[3];

        for (i = 0; i < 3; i++) 
            light_color[i] = light->color[i] * light->intensity;
        light_color[3] = 1;

        for (i = 0; i < 3; i++) 
            light_ambient_color[i] = light->color[i] * light->ambientIntensity;
        light_ambient_color[3] = 1;

        for (i = 0; i < 3; i++) 
            light_position[i] = light->location[i];
        light_position[3] = 1;

        for (i = 0; i < 3; i++) 
            light_attenuation[i] = light->attenuation[i];

        glEnable(GL_LIGHT0);
        glLightfv(GL_LIGHT0, GL_DIFFUSE, light_color);
        glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient_color);
        glLightfv(GL_LIGHT0, GL_POSITION, light_position);
        glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, light_attenuation[0]);
        glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, light_attenuation[1]);
        glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, light_attenuation[2]);
        glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 180.0f);
        glLightf(GL_LIGHT0, GL_SPOT_EXPONENT, 0.0f);
        lightRendered = -1;
    }
    else if(initRender)
    {
        pointLightexists = -1;
    }
    else
    {
    }
}

void CRWDMaterialRender(X3dNode *data, void *extraData)
{
    if(preRender)
    {
    }
    else if(initRender)
    {
    }
    else
    {
        int i;
        struct X3dMaterial *material = (struct X3dMaterial*)data;
        GLfloat diffuse_color[4];
        GLfloat ambient;
        GLfloat ambient_color[4];
        GLfloat emissive_color[4];
        GLfloat specuar_color[4];
        GLfloat shininess;

        for (i = 0; i < 3; i++)
            diffuse_color[i] = material->diffuseColor[i];
        diffuse_color[3] = 1;

        ambient = material->ambientIntensity; 

        for (i = 0; i < 3; i++)
            ambient_color[i] = ambient * material->diffuseColor[i];
        ambient_color[3] = 1;

        for (i = 0; i < 3; i++)
            emissive_color[i] = material->emissiveColor[i];
        emissive_color[3] = 1;

        for (i = 0; i < 3; i++)
            specuar_color[i] = material->specularColor[i];
        specuar_color[3] = 1;
        
        shininess = material->shininess*128.0f;

        glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diffuse_color);
        glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, ambient_color);
        glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, emissive_color);
        glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specuar_color);
        glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, shininess);
    }
}

void CRWDGroupTreeRender(X3dNode *data, void *extraData)
{
    struct X3dGroup *group = (struct X3dGroup*)data;
    int i;
    glPushMatrix();
    if (group->children)
       for (i = 0; i < group->children_length; i++)
           if (group->children[i])
           {
               if(!(preRender || initRender))
                   glDisable(GL_TEXTURE_2D);
               treeRenderCallback(group->children[i], extraData);
           }
    glPopMatrix();
}

void CRWDTransformTreeRender(X3dNode *data, void *extraData)
{
    struct X3dTransform *transform = (struct X3dTransform*)data;
    int i;
    if(preRender || initRender)
    {
        if (transform->children)
            for (i = 0; i < transform->children_length; i++)
                if (transform->children[i])
                    treeRenderCallback(transform->children[i], extraData);
    }
    else
    {
        glPushMatrix();
        glTranslatef(transform->translation[0], transform->translation[1], transform->translation[2]);
        glTranslatef(transform->center[0], transform->center[1], transform->center[2]);
        glRotatef( ( (transform->rotation[3] / (2*M_PI) ) * 360), transform->rotation[0], transform->rotation[1], transform->rotation[2]);
        glRotatef( ( (transform->scaleOrientation[3] / (2*M_PI) ) * 360), transform->scaleOrientation[0], transform->scaleOrientation[1], transform->scaleOrientation[2]);
        glScalef(transform->scale[0], transform->scale[1], transform->scale[2]);
        glRotatef( ( (transform->scaleOrientation[3] / (2*M_PI) ) * 360) * -1, transform->scaleOrientation[0], transform->scaleOrientation[1], transform->scaleOrientation[2]);
        glTranslatef(transform->center[0] * -1, transform->center[1] * -1, transform->center[2] * -1);
        if (transform->children)
            for (i = 0; i < transform->children_length; i++)
                if (transform->children[i])
                {
                    glDisable(GL_TEXTURE_2D);
                    treeRenderCallback(transform->children[i], extraData);
                }
        glPopMatrix();
    }
}

void CRWDViewpointRender(X3dNode *data, void* extraData)
{
    struct X3dViewpoint *viewpoint = (struct X3dViewpoint*)data;
    if(preRender)
    {
        if(!viewpointRendered)
        {
            glMatrixMode(GL_MODELVIEW);
            glRotatef( ( -(viewpoint->orientation[3] / (2*M_PI) ) * 360), viewpoint->orientation[0], viewpoint->orientation[1], viewpoint->orientation[2]);
            glTranslatef(-viewpoint->position[0], -viewpoint->position[1], -viewpoint->position[2]);
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
            viewpointRendered = -1;
        }
    }
    else if(initRender)
    {
        int i;
        float fieldOfViewdegree = ( (viewpoint->fieldOfView / (2*M_PI) ) * 360);

        glMatrixMode(GL_PROJECTION);
        gluPerspective(fieldOfViewdegree, 1.0, Z_NEAR, Z_FAR);  /* fieldOfView in degree, aspect radio, Z nearest, Z farest */

        viewPointexists = -1;
        for (i = 0; i < 3; i++)
            viewpoint1Position[i] = viewpoint->position[i];
    }
    else
    {
    }
}

X3dNode *rootNode = &scenegraph.root;
/*X3dNode *rootNode = &scenegraph.DEFNAME;*/

void CRWDdraw()
{
    glClearColor(0, 0, 0, 1);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    viewpointRendered = 0;
    
    preRender = -1;
    treeRenderCallback(rootNode, NULL);

    if(!viewPointexists)
    {
        struct X3dViewpoint viewpoint;
        viewpoint.fieldOfView = 0.79;
        viewpoint.position = malloc(3 * sizeof(float));
        viewpoint.position[0] = 0;
        viewpoint.position[1] = 0;
        viewpoint.position[2] = 10;
        viewpoint.orientation = malloc(4 * sizeof(float));
        viewpoint.orientation[0] = 0;
        viewpoint.orientation[1] = 0;
        viewpoint.orientation[2] = 1;
        viewpoint.orientation[3] = 0;
        X3dViewpointRenderCallback(&viewpoint, NULL);
        free(viewpoint.position);
        viewpoint.position = NULL;
        free(viewpoint.orientation);
        viewpoint.orientation = NULL;
    }

    if(!pointLightexists)
    {
        struct X3dPointLight pointlight;
        GLfloat attentuation[] = {1, 0, 0};
        GLfloat color[] = {1, 1, 1};
        GLfloat intensity = 1;
        GLfloat *position;
        position = viewpoint1Position;
        pointlight.attenuation = attentuation;
        pointlight.color = color;
        pointlight.intensity = intensity;
        pointlight.location = position;
        pointlight.ambientIntensity = 0;
        pointlight.on = -1;
        X3dPointLightRenderCallback(&pointlight, NULL);
    }

    preRender = 0;
    treeRenderCallback(rootNode, NULL);
}

void CRWDinit()
{
    GLint zero[4] = {0, 0, 0, 0};

    X3dIndexedFaceSetRenderCallback = CRWDIndexedFaceSetRender;
    X3dPointLightRenderCallback = CRWDPointLightRender;
    X3dMaterialRenderCallback = CRWDMaterialRender;
    X3dTransformTreeRenderCallback = CRWDTransformTreeRender;
    X3dGroupTreeRenderCallback = CRWDGroupTreeRender;
    X3dViewpointRenderCallback = CRWDViewpointRender;
    X3dPixelTextureRenderCallback = CRWDPixelTextureRender;

    glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT);
    glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE);
    glColorMaterial(GL_FRONT_AND_BACK, GL_EMISSION);
    glColorMaterial(GL_FRONT_AND_BACK, GL_SPECULAR);
    glColorMaterial(GL_FRONT_AND_BACK, GL_SHININESS);

    /*Enable light*/
    glEnable(GL_LIGHTING);

    glLightModeliv(GL_LIGHT_MODEL_AMBIENT, zero);

    /* Use depth buffering for hidden surface elimination. */

    glEnable(GL_DEPTH_TEST);
    glEnable(GL_NORMALIZE);

    glDepthMask(GL_TRUE);
    glDepthFunc(GL_LEQUAL);

    glEnable(GL_ALPHA_TEST);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glAlphaFunc(GL_NOTEQUAL, 0);

    glShadeModel(GL_SMOOTH);

    X3dSceneGraphInit(&scenegraph);

    preRender = 0;
    initRender = -1;
    treeRenderCallback(rootNode, NULL);
    if (!viewPointexists)
    {
        float fieldOfViewdegree = ( (0.79 / (2*M_PI) ) * 360);

        glMatrixMode(GL_PROJECTION);
        gluPerspective(fieldOfViewdegree, 1.0, Z_NEAR, Z_FAR);
    }
    initRender = 0;
}

void CRWDfinalize()
{
}
