We continue with introduction of 2 new functions:
resizeWindow :: GLFW.WindowSizeCallback
=
resizeWindow win w h do
$= (GL.Position 0 0, GL.Size (fromIntegral w) (fromIntegral h))
GL.viewport $= GL.Projection
GL.matrixMode
GL.loadIdentity0 (realToFrac w) (realToFrac h) 0 GL.ortho2D
This function adds a callback script for resizing the window, telling OpenGL to reload the context in case the window size was changed.
keyPressed :: GLFW.KeyCallback
GLFW.Key'Escape _ GLFW.KeyState'Pressed _ = shutdown win
keyPressed win = return () keyPressed _ _ _ _ _
This function closes the main window whenever the Esc.Key is pressed.
Now the whole program:
import Graphics.Rendering.OpenGL as GL
import Graphics.UI.GLFW as GLFW
import Control.Monad
import System.Exit ( exitWith, ExitCode(..) )
resizeWindow :: GLFW.WindowSizeCallback
=
resizeWindow win w h do
$= (GL.Position 0 0, GL.Size (fromIntegral w) (fromIntegral h))
GL.viewport $= GL.Projection
GL.matrixMode
GL.loadIdentity0 (realToFrac w) (realToFrac h) 0
GL.ortho2D
keyPressed :: GLFW.KeyCallback
GLFW.Key'Escape _ GLFW.KeyState'Pressed _ = shutdown win
keyPressed win = return ()
keyPressed _ _ _ _ _
shutdown :: GLFW.WindowCloseCallback
= do
shutdown win
GLFW.destroyWindow win
GLFW.terminate<- exitWith ExitSuccess
_ return ()
main :: IO ()
= do
main
GLFW.init
GLFW.defaultWindowHintsJust win <- GLFW.createWindow 640 480 "GLFW Demo" Nothing Nothing
Just win)
GLFW.makeContextCurrent (Just resizeWindow)
GLFW.setWindowSizeCallback win (Just keyPressed)
GLFW.setKeyCallback win (Just shutdown)
GLFW.setWindowCloseCallback win (
onDisplay win
GLFW.destroyWindow win
GLFW.terminate
onDisplay :: Window -> IO ()
= do
onDisplay win $= Color4 1 0 0 1
GL.clearColor ColorBuffer]
GL.clear [
GLFW.swapBuffers win
$ do
forever
GLFW.pollEvents
onDisplay win
The program opens the same window as in the previous tutorial, but now it reacts to basic events: if the window is resized or Escape key pressed.
tutorial files on GitHub
next: Haskell OpenGL Tutorial: drawing 2 triangles.
previous: Post-Post Modern OpenGL in Haskell