import pygame, OpenGL, math

from OpenGL.GLU import *
from OpenGL.GL import *

import platform

[w, h] = [0, 0]

def render(surface, overlay, font, showOverlay):
   #glEnable (GL_BLEND); glBlendFunc (GL_ONE, GL_ONE);

   # I should really figure out which attributes in the 2D rendering
   # break the 3d rendering and reset those back instead of resetting
   # all attributes
   glPushAttrib(GL_ALL_ATTRIB_BITS)
   render3d(surface)
   glPopAttrib()

   if showOverlay:
      renderOverlay(overlay, font)

      glPushAttrib(GL_ALL_ATTRIB_BITS)
      projectOverlay(surface, overlay)
      glPopAttrib()


def renderOverlay(overlay, font):
   #pygame.draw.rect(overlay, (0, 0, 255), pygame.Rect(0, 0, w, h))
   #pygame.draw.circle(overlay, (255, 0, 0), (int(w/2), int(h/2)), 540)
   #overlay.set_colorkey((255,0,0))
   overlay.fill((0, 0, 0, 255))

   text = font.render("2D drawing", True, (0, 128, 0))

   pygame.draw.rect(overlay, (0, 128, 255), pygame.Rect(30, 30, 60, 60))
   overlay.blit(text, (500, 100))

def projectOverlay(surface, overlay):
   
   glPushMatrix()

   glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

   glTranslatef(0.0,0.0,-zNear)

   textureData = pygame.image.tostring(overlay, "RGBA", 1)
   width = overlay.get_width()
   height = overlay.get_height()

   glEnable(GL_TEXTURE_2D)

   glBindTexture(GL_TEXTURE_2D, glGenTextures(1))
   glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData)

   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)

   glBegin(GL_QUADS)

   glTexCoord2f(0.0, 0.0)
   glVertex2f(-(w/h), -1)

   glTexCoord2f(1.0, 0.0)
   glVertex2f((w/h), -1)

   glTexCoord2f(1.0, 1.0)
   glVertex2f((w/h), 1)

   glTexCoord2f(0.0, 1.0)
   glVertex2f(-(w/h), 1)

   glEnd()

   glPopMatrix()

def render3d(surface):
   vertices = (
      (1, -1, -1),
      (1, 1, -1),
      (-1, 1, -1),
      (-1, -1, -1),
      (1, -1, 1),
      (1, 1, 1),
      (-1, -1, 1),
      (-1, 1, 1)
   )
   edges = (
      (0,1),
      (0,3),
      (0,4),
      (2,1),
      (2,3),
      (2,7),
      (6,3),
      (6,4),
      (6,7),
      (5,1),
      (5,4),
      (5,7)
   )
   
   glPushMatrix()

   glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

   glTranslatef(0.0,0.0,-2*zNear)
   glColor3f(1.0, 1.0, 1.0)

   glBegin(GL_LINES)
   for edge in edges:
      for vertex in edge:
         glVertex3fv(vertices[vertex])
   glEnd()

   glPopMatrix()

system = platform.system()

if system == 'Windows':
   print("Windows detected")

   import ctypes
   user32 = ctypes.windll.user32
   w = user32.GetSystemMetrics(0)
   h = user32.GetSystemMetrics(1)
elif system == 'Linux':
   print("Linux detected")

   import tkinter
   root = tkinter.Tk()
   w = root.winfo_screenwidth()
   h = root.winfo_screenheight()
elif system == 'Darwin':
   print("Mac detected")

   from AppKit import NSScreen
   res = NSScreen.mainScreen().frame().size
   w = int(res.width)
   h = int(res.height)
else:
   print("Unknown OS: " + system)

print("Detected native resolution: {:d}x{:d}".format(w, h))

pygame.init()

if w == 0 and h == 0:
   print("Not using fullscreen")
   gameDisplay = pygame.display.set_mode((800, 600))
else:
   gameDisplay = pygame.display.set_mode((w, h), pygame.FULLSCREEN|pygame.DOUBLEBUF|pygame.OPENGL)

# Look into pygame.HWSURFACE for hardware-accelerated surfaces
overlay = pygame.Surface((w, h), pygame.SRCALPHA)

pygame.display.set_caption('Space Game')

clock = pygame.time.Clock()
   
font = pygame.font.SysFont("comicsansms", 48)

running = True
showOverlay = False

zNear = 1.0/math.tan(math.radians(45.0/2))
gluPerspective(45, (w/h), zNear, 500.0)

'''
# Use glFrustum to focus the camera at a point other than the screen center
zNear = 1.0
glFrustum(-1.5, 0.5, -1.0, 1.0, zNear, 500.0)
glTranslatef(0.0,0.0,-5.0)
'''

while running:
   for event in pygame.event.get():
      if event.type == pygame.QUIT:
         running = False
      elif event.type == pygame.KEYDOWN:
         if event.key == pygame.K_ESCAPE:
            running = False
         elif event.key == pygame.K_SPACE:
            showOverlay = not showOverlay

   render(gameDisplay, overlay, font, showOverlay)

   pygame.display.flip()
   clock.tick(60)

pygame.quit()
print("Game ended")
quit()
