{-
   Planet.hs (adapted from planet.c which is (c) Silicon Graphics, Inc)
   This file is part of HOpenGL - a binding of OpenGL and GLUT for Haskell.
   Copyright (C) 2000  Sven Panne <Sven.Panne@informatik.uni-muenchen.de>

   This program shows how to composite modeling transformations
   to draw translated and rotated models.
   Interaction:  pressing the d and y keys (day and year)
   alters the rotation of the planet around the sun.
-}

import Data.IORef  ( IORef, newIORef, readIORef, modifyIORef )
import System.Exit ( exitWith, ExitCode(ExitSuccess) )

import GL
import GLU
import Graphics.UI.GLUT

myInit :: IO ()
myInit = do
   clearColor (Color4 0.0 0.0 0.0 0.0)
   shadeModel GL.Flat

display :: IORef Int -> IORef Int -> DisplayCallback
display day year = do
   clear [ColorBufferBit]
   color (Color3 1.0 1.0 1.0 :: Color3 GLfloat)
   pushMatrix
   renderObject Wireframe (Graphics.UI.GLUT.Sphere 1.0 20 16)   -- draw sun
   y <- readIORef year
   rotate (fromIntegral y :: GLfloat) (Vector3 0 1 0)
   translate (Vector3 2 0 0 :: Vector3 GLfloat)
   d <- readIORef day
   rotate (fromIntegral d :: GLfloat) (Vector3 0 1 0)
   renderObject Wireframe (Graphics.UI.GLUT.Sphere 0.2 10 8)    -- draw smaller planet
   popMatrix
   swapBuffers

reshape :: ReshapeCallback
reshape (WindowSize w h) = do
   viewport (0, 0) (fromIntegral w, fromIntegral h)
   matrixMode Projection
   loadIdentity
   perspective 60.0 (fromIntegral w / fromIntegral h) 1.0 20.0
   matrixMode Modelview
   loadIdentity
   lookAt (0.0, 0.0, 5.0) (0.0, 0.0, 0.0) (0.0, 1.0, 0.0)

keyboard :: IORef Int -> IORef Int -> KeyboardMouseCallback
keyboard day _    (Char 'd')   Down _ _ = do modifyIORef day  (\d -> (d+10) `mod` 360); postRedisplay
keyboard day _    (Char 'D')   Down _ _ = do modifyIORef day  (\d -> (d-10) `mod` 360); postRedisplay
keyboard _   year (Char 'y')   Down _ _ = do modifyIORef year (\y -> (y+ 5) `mod` 360); postRedisplay
keyboard _   year (Char 'Y')   Down _ _ = do modifyIORef year (\y -> (y- 5) `mod` 360); postRedisplay
keyboard _   _    (Char '\27') Down _ _ = exitWith ExitSuccess
keyboard _   _    _            _    _ _ = return ()

main :: IO ()
main = do
   (progName, _args) <- getArgsAndInitialize
   setInitialDisplayMode [ Graphics.UI.GLUT.Double, RGB ]
   setInitialWindowSize (WindowSize 500 500)
   setInitialWindowPosition (WindowPosition 100 100)
   createWindow progName
   myInit
   day  <- newIORef 0
   year <- newIORef 0
   setDisplayCallback (display day year)
   setReshapeCallback (Just reshape)
   setKeyboardMouseCallback (Just (keyboard day year))
   mainLoop
