使用Haskell的OpenGL绘制线条

5

我正在尝试使用OpenGL创建围棋棋盘。为此,我试图绘制一堆线条以创建网格。然而,每个教程网站(包括OpenGL的)都是用C ++编写的示例,并且Haskell维基百科没有很好地解释它。我是OpenGL的新手,希望能找到一个教程。

2个回答

12
我假设您想要使用OpenGL 2.1或更早版本。对于OpenGL 3.0,您需要不同的代码。
因此,在C中,您应该编写如下代码:
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绑定。


这看起来可以解决我想做的事情,但是它似乎不起作用。程序会编译,但是当我运行它时没有任何线条被绘制出来。也许我没有做对,或者把它放在了错误的区域。再次说明,我是opengl的新手,不太了解它的工作原理。你能否给我一个更完整的程序(一个初学者能够理解的)? - lewdsterthumbs
好的,我添加了一个完整的示例程序,在我的计算机上可以正常运行。 - dflemstr
2
@lewdsterthumbs 你可能会喜欢40种获取空白黑屏的方法 - Daniel Wagner
非常感谢。这正是我想要做的,而且教程网站看起来将来可能会有所帮助。 - lewdsterthumbs
对OpenGL一无所知,但是有40种方法可以得到一个空白的黑屏幕,这可能是我今天读过的最好的东西了... :-D - MathematicalOrchid

1
一个快速的谷歌搜索得到了这个:

http://www.haskell.org/haskellwiki/OpenGLTutorial1

在任何情况下,由于OpenGL最初是一种C库,因此您可能希望先尝试使用C(或C ++)进行实践,因为您将能够原样使用原始的OpenGL文档;之后,您可能希望深入研究Haskell绑定,并了解如何在Haskell中使用相同的OpenGL调用。

我已经看了这个。它有很多图片,但实际上并没有解释如何做任何事情。 - lewdsterthumbs
2
它确实有作用,但不是显而易见的。 - tdammers

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接