OpenGL學習筆記——搭建OpenGL程序框架

一、程序及運行效果

from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *

def drawFunc():
	glClear(GL_COLOR_BUFFER_BIT)
	#glRotatef(1, 0, 1, 0)
	glutWireTeapot(0.5)
	glFlush()

glutInit()
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA)
glutInitWindowSize(600, 600)
glutCreateWindow("Teapot")
glutDisplayFunc(drawFunc)
#glutIdleFunc(drawFunc)
glutMainLoop()

這個程序繪製了一個猶他茶壺:



二、使用OpenGL

模塊導入
使用OpenGL的函數之前導入需要的所有函數

from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *

函數命名
OpenGL的函數的一般命名規則爲:<前綴><根函數><參數數目><參數類型>
舉個例子: glColor3f() 表示該函數屬於gl庫,含有3個參數,參數類型爲float指針


初始化窗口
下面6行代碼基本上是固定的

glutInit()
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA)
glutInitWindowSize(600, 600)
glutCreateWindow("Teapot")
glutDisplayFunc(drawFunc)
glutMainLoop()
函數名 描述
glutInit() 初始化OpenGL
glutInitDisplayMode(Mode) 其參數GLUT_RGBA使用(r, g, b)格式,GLUT_SINGLE意味着所有的繪圖操作都直接在顯示的窗口執行
glutInitWindowSize(400, 400) 設置窗口大小
glutInitWindowPosition 設置窗口位置
glutCreateWindow(“Teapot”) 生成一個窗口,命名爲Teapot
glueDisplayFunc(func) 參數爲一個函數名,用來繪製OpenGL窗口,函數裏包含很大OpenGL的繪圖指令
glutMainLoop() 主循環,調用後OpenGL就一直運行下去

其中,glutInitDisplayMode()還有其他可選的參數:


繪製函數
在drawFunc函數定義中,包含了實際繪圖的函數:
glClear(GL_COLOR_BUFFER_BIT):吧先前的畫面清除,避免重疊,參數知名要清楚的buffer
glutWireTeapot(0.5):一個glut中繪製猶他茶壺的函數,使用的是線模型
glFlush():刷新屏幕上的更新,處理OpenGL的渲染流水線,讓所有排隊的指令得到執行


旋轉的茶壺:將被註釋掉的兩行語句取消註釋,就可以看到一個旋轉的茶壺了



三、OpenGL程序框架

from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *

def init():
	glClearColor(0.0, 0.0, 0.0, 1.0)	# 設置背默認景色爲黑色
	glColor3f(1.0, 1.0, 1.0)			# 設置默認繪製顏色爲白色
	glMatrixMode(GL_PROJECTION)			# 是否受後續變換函數影響
	glLoadIdentity()					# 初始化爲單位矩陣
	gluOrtho2D(-1.0, 1.0, -1.0, 1.0)	# 設置座標範圍


def display():
	glClear(GL_COLOR_BUFFER_BIT)		# 繪製前清屏,防止重疊

	glBegin(GL_MODE)
	GL_Vertex(a, b, c)
	glEnd()

	glFlush()							# 時緩衝區指令得到執行,刷新屏幕


def main():
	glutInit()
	glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA)
	glutInitWindowSize(500, 500)
	glutInitWindowPosition(200, 100)
	glutCreateWindow("simple")
	glutDisplayFunc(display)
	init()
	glutMainLoop()						# 回調函數

main()


完結 cheers ?
參考:目光博客從零開始pyOpenGL

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章