1. 程式人生 > >python下學習opengl之簡單窗口

python下學習opengl之簡單窗口

proc .org github 教程 col 默認 nco setw pen

最近在看一個opengl教程:https://learnopengl.com/Introduction,寫的深入淺出,非常不錯,而且有中文的翻譯版:https://learnopengl-cn.github.io/

出於加深學習效果,自己試著用Python重新實現原教程中的C++代碼

1. 操作系統:Windows 10

2. 安裝Python: https://www.python.org/downloads/, 我用的是3.6.3

3. 安裝pyOpenGl: 安裝完python後默認會同時安裝pip, 將pip加入默認路徑,在windows命令行窗口輸入 pip install PyOpenGL

4. 下載GLFW:在http://www.glfw.org/download.html 下載 32-bit Windows binaries,下到的壓縮文件解壓後,得到庫文件lib-vc2015/glfw3.dll

5. 下載GLFW的python 接口文件:在https://github.com/rougier/pyglfw 下載glfw.py,並將其和上一步得到的庫文件放到python默認的庫目錄或當前開發代碼的同級目錄中

6. 創建window.py文件,代碼如下:

#! /usr/bin/env python
# -*- coding: utf-8 -*-

import sys, os
import OpenGL.GL as gl
import glfw

WIN_WIDTH = 800
WIN_HEIGHT = 600

def framebuffer_size_callback(window, width, height):
    gl.glViewport(0, 0, width, height)

def processInput(window): if glfw.glfwGetKey(window, glfw.GLFW_KEY_ESCAPE) == glfw.GLFW_PRESS: glfw.glfwSetWindowShouldClose() def main(): glfw.glfwInit() glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MAJOR, 3) glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MINOR, 3) glfw.glfwWindowHint(glfw.GLFW_OPENGL_PROFILE, glfw.GLFW_OPENGL_CORE_PROFILE) window
= glfw.glfwCreateWindow(WIN_WIDTH, WIN_HEIGHT, "學習OpenGL".encode(), 0, 0) if window == 0: print("failed to create window") glfw.glfwTerminate() glfw.glfwMakeContextCurrent(window) glfw.glfwSetFramebufferSizeCallback(window, framebuffer_size_callback) while not glfw.glfwWindowShouldClose(window): processInput(window) gl.glClearColor(0.2, 0.3, 0.3, 1.0) gl.glClear(gl.GL_COLOR_BUFFER_BIT) glfw.glfwSwapBuffers(window) glfw.glfwPollEvents() glfw.glfwTerminate() if __name__ == "__main__": main()

該段代碼執行後得到的效果如下:

技術分享圖片

以上代碼是對opengl教程中hello window章節的python實現,原來的C++代碼見 https://learnopengl.com/Getting-started/Hello-Window

python下學習opengl之簡單窗口