使用tkinter框架用pyopengl绘制立方体

2024-10-02 16:35:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用tkinter frame opengl渲染立方体。 但我不知道问题出在哪里立方体没有显示expect 2行。 检查我的代码 请你帮我写代码,你有PDF教我opengl吗?我在网上找不到太多的资源

import tkinter as tk

from OpenGL.GL import *

from pyopengltk import 
OpenGLFrame

cubeVertices = 
((1,1,1),(1,1,-1), 
(1,-1,-1),(1,-1,1),. 
(-1,1,1),(-1,-1,-1), 
(-1,-1,1),(-1,1,-1))
cubeEdges = ((0,1),. 
(0,3),(0,4),(1,2),. 
(1,7),(2,5),(2,3),. 
(3,6),(4,6),(4,7),. 
(5,6),(5,7))
classframe(OpenGLFrame):

  def initgl(self):
        glViewport(0,0,250,250)
        

        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glOrtho(0,self.width,self.height,0,-1,1)

        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
  
  def redraw(self):
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
        glLoadIdentity()
        glPushMatrix()
        glRotatef(90,0.0,1.0,0.0)
        glBegin(GL_LINES)
        glColor3f(0.0,1.0,0.0)
        for cubeEdge in cubeEdges:
     for cubeVertex in cubeEdge:
               glVertex3fv(cubeVertices[cubeVertex])
        glEnd()
        glPopMatrix()            
root = tk.Tk()
app = frame(root,width=900, height=600)  
  app.pack( 
fill=tk.BOTH,expand=tk.YES)
app.mainloop()

enter image description here


Tags: 代码fromimportselfapptkinterdefframe
1条回答
网友
1楼 · 发布于 2024-10-02 16:35:18

你必须改变投影矩阵。由于立方体的尺寸为2x2x2,并且投影是窗口空间中的正交投影,因此立方体将仅覆盖窗口中的4个像素。 更改视图空间并增加到近平面和远平面的距离。注意,几何体必须位于近平面和远平面之间,否则几何体将被剪裁。例如:

glOrtho(-10, 10, -10, 10, -10, 10)

无论如何,我建议使用Perspective projection。投影矩阵定义投影到二维视口上的三维空间(剪辑空间)。在Perspective projection,这个空间是一个平截体(Viewing frustum)。矩阵可以通过^{}设置。例如:

classframe(OpenGLFrame):

  def initgl(self):
        glViewport(0,0,250,250)
        

        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        # glOrtho(-10, 10, -10, 10, -10, 10)
        gluPerspective(90, self.width/self.height, 0.1, 10.0)

        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

近平面和远平面的值必须大于0.0,远平面必须大于近平面0 < near < far。在上述示例中,近平面为0.1,远平面为10。绘制几何图形时,必须确保几何图形位于近平面和远平面之间(分别位于查看体积中的剪裁空间中),否则将剪裁几何图形

使用^{}定义具有与世界原点(0,0,0)有一定距离的视点(0,-3,0)的视图矩阵:

classframe(OpenGLFrame):
    # [...]

    def redraw(self):
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
        
        # define view matrix
        glLoadIdentity()
        gluLookAt(0, -3, 0, 0, 0, 0, 0, 0, 1)
        
        glPushMatrix()
        glRotatef(90,0.0,1.0,0.0)
        glBegin(GL_LINES)
        glColor3f(0.0,1.0,0.0)
        for cubeEdge in cubeEdges:
            for cubeVertex in cubeEdge:
               glVertex3fv(cubeVertices[cubeVertex])
        glEnd()
        glPopMatrix() 

What exactly are eye space coordinates?

相关问题 更多 >