
import constants
from constants import *

from OpenGL.GL import *
from OpenGL.GLU import *
import pygame
from pygame.locals import *


global texGroup

def initializeDisplay(w, h):
    pygame.display.set_mode((w,h), OPENGL|DOUBLEBUF)
    # glShadeModel(GL_SMOOTH)
    glClearColor(0.0, 0.0, 0.0, 1.0)
    glClear(GL_COLOR_BUFFER_BIT)

    # switch to projection mode
    glMatrixMode(GL_PROJECTION);
    # save previous matrix which contains the
    # settings for the perspective projection
    # glPushMatrix();
    # reset matrix 
    glLoadIdentity(); 
    # set a 2D orthographic projection
    gluOrtho2D(0, w, 0, h);

    glMatrixMode(GL_MODELVIEW);
    
    #set up texturing
    glEnable(GL_TEXTURE_2D)
    glEnable (GL_BLEND);
    glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
    
    # determine and set optimal max texture size:
    bigd = SWIDTH
    if SHEIGHT > bigd:
        bigd = SHEIGHT

    # create an empty texture for a texture group
    global texGroup
    texGroup = glGenTextures(1)
    setTex(texGroup)
    emptyList = "\x00\x00\x00\x00" * TEXGROUPWIDTH * TEXGROUPHEIGHT #* 4
    glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, TEXGROUPWIDTH, TEXGROUPHEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, emptyList )
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)

    # Enable vertex arrays
    """glEnableClientState(GL_VERTEX_ARRAY)
    glEnableClientState(GL_TEXTURE_COORD_ARRAY)        
    glEnableClientState(GL_COLOR_ARRAY)"""

    # Determine and set max practical texture size    
    size = glGetIntegerv(GL_MAX_TEXTURE_SIZE)
    done = 0
    while size / 2 > bigd:
        size = size / 2
    constants.max_tex_size = size


groupTexCount = {'total':0, 16:0, 32:0}
texCoords = []
spriteList = []
def loadTextureG(image, colorkey=None):
    global texCoords, groupTexCount, texGroup, spriteList

    textureSurface = pygame.image.load(image)
    if colorkey:
        if colorkey == -1:
            colorkey = textureSurface.get_at((0,0))
        textureSurface.set_colorkey(colorkey, RLEACCEL)
    textureData = pygame.image.tostring(textureSurface, "RGBA", 1)

    width = textureSurface.get_width()
    height = textureSurface.get_height()

    if width != height:
        print "Non square textures probably can't be grouped, but I'll try anyway."

    size = width
    if size != 16 and size != 32:
        print "textures that aren't 16*16 or 32*32 probably won't work grouped."

    offset = 0
    if size == 32:
        offset = TEXGROUPHEIGHT / 2

    setTex(texGroup)

    x, y= getGroupPosition(groupTexCount[size],size)

    y = y + offset

    glTexSubImage2D( GL_TEXTURE_2D, 0, x, y, size, size, GL_RGBA, GL_UNSIGNED_BYTE, textureData )

    # calculate and cache texture coords, with a fudge factor to prevent ghosting around the edges
    # of the textures.
    xTex = x / (TEXGROUPWIDTH * 1.0) + 0.001
    yTex = y / (TEXGROUPWIDTH * 1.0) + 0.001
    sizeTex = size / (TEXGROUPWIDTH * 1.0) - 0.002                                                      
    texCoords.append((xTex,yTex,xTex+sizeTex,yTex+sizeTex))                                             
                                                                                                        
    groupTexCount[size] += 1
    groupTexCount['total'] += 1
    (x,y,dx,dy) = (xTex,yTex,xTex+sizeTex,yTex+sizeTex)
    newList = glGenLists(1)
    spriteList.append(newList)
    glNewList(newList,GL_COMPILE);
    glBegin(GL_QUADS)
    glTexCoord2f(x, y); glVertex2f(0, constants.TEXSIZE)    # Bottom Left Of The Texture and Quad
    glTexCoord2f(dx, y); glVertex2f( constants.TEXSIZE, constants.TEXSIZE)    # Bottom Right Of The Texture and Quad
    glTexCoord2f(dx, dy); glVertex2f( constants.TEXSIZE,  0)    # Top Right Of The Texture and Quad
    glTexCoord2f(x, dy); glVertex2f(0, 0)    # Top Left Of The Texture and Quad
    glEnd()
    glEndList()

    return (newList)


curTexture = None
def setTex(texture):
    global curTexture#, switchCount
   
    if curTexture != texture:
        glBindTexture(GL_TEXTURE_2D, texture)
        curTexture = texture

def getGroupPosition(number, size):
    x = number * size % TEXGROUPWIDTH
    y = number * size / TEXGROUPWIDTH * size

    return x,y

def drawTileG(width=TEXSIZE, height=TEXSIZE, texture=None):
    global texCoords, texGroup

    setTex(texGroup)

    if(width != TEXSIZE or height != TEXSIZE):
        glScalef(width/TEXSIZE, height/TEXSIZE, 1.0)
        glCallList(texture)
        glLoadIdentity()
    else:
        glCallList(texture)

