我正在尝试使用OpenGL创建围棋棋盘。为此,我试图绘制一堆线条以创建网格。然而,每个教程网站(包括OpenGL的)都是用C ++编写的示例,并且Haskell维基百科没有很好地解释它。我是OpenGL的新手,希望能找到一个教程。
glBegin(GL_LINES);
glVertex3f(1, 2, 3);
glVertex3f(5, 6, 7);
glEnd();
在 Haskell 中,您可以这样编写等效的代码:
renderPrimitive Lines $ do
vertex $ Vertex3 1 2 3
vertex $ Vertex3 5 6 7
使用这段代码时,如果我使用例如1
而不是一些变量,您可能会遇到有关模糊类型的错误(所以您应该将 1
替换为(1 :: GLfloat)
),但是如果您使用已经具有类型GLfloat
的实际变量,您就不必这样做。
这是一个完整的程序,在窗口中绘制白色对角线:
import Graphics.Rendering.OpenGL
import Graphics.UI.GLUT
main :: IO ()
main = do
-- Initialize OpenGL via GLUT
(progname, _) <- getArgsAndInitialize
-- Create the output window
createWindow progname
-- Every time the window needs to be updated, call the display function
displayCallback $= display
-- Let GLUT handle the window events, calling the displayCallback as fast as it can
mainLoop
display :: IO ()
display = do
-- Clear the screen with the default clear color (black)
clear [ ColorBuffer ]
-- Render a line from the bottom left to the top right
renderPrimitive Lines $ do
vertex $ (Vertex3 (-1) (-1) 0 :: Vertex3 GLfloat)
vertex $ (Vertex3 1 1 0 :: Vertex3 GLfloat)
-- Send all of the drawing commands to the OpenGL server
flush
默认的OpenGL固定功能投影使用(-1,-1)作为窗口左下角,(1,1)作为窗口右上角。您需要更改投影矩阵以获取不同的坐标空间。
有关此类更完整的示例,请参见NEHE教程的Haskell端口。它们使用原始的OpenGL绑定,更像C绑定。