一、OpenGL简介

OpenGL(全写Open Graphics Library)是个定义了一个跨编程语言、跨平台的编程接口(Application programming interface)的规格,它用于生成二维、三维图像。这个接口由近三百五十个不同的函数调用组成,用来从简单的图元绘制复杂的三维景象。OpenGL常用于CAD、虚拟实境、科学可视化程式和电子游戏开发。

二、Python的OpenGL平台搭建

一)、PyOpenGL的安装(以Python3.6.2版本为例)

1、在网址 http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyopengl 下载PyOpenGL‑3.1.2‑cp36‑cp36m‑win32.whl

2、拷贝上面文件到python文件夹下,在c:\ python>下运行命令:

pip install PyOpenGL‑3.1.2‑cp36‑cp36m‑win32.whl

二)、Python窗口工具包GLFW的安装

1、下载GLFW。它可以在http://www.glfw.org/download.html 这个网页上下载。

2、将下载的压缩文件glfw-3.2.1.bin.WIN32 .zip解压到我的文件夹内,D:\OpenGL\Glew文件夹\glfw-3.2.1.bin.WIN32 \glfw-3.2.1.bin.WIN32。

3、将GLFW的库文件位置添加到环境变量中的path中。点击“我的电脑”右键选择“属性”,弹出窗口,然后依次点击“高级系统设置”,“高级”,“环境变量”,点击“编辑”,“新建”,将D:\OpenGL\Glew文件夹\glfw-3.2.1.bin.WIN32\glfw-3.2.1.bin.WIN32\lib-vc2015 文件夹添加进去.(注意:此处的目录应该是读者自己下载的GLFW安装目录。其中目录lib-vc2015是库文件所在文件夹)。

4、路径设置完成后,要关闭你的python编译软件然后重新打开,你就可以在python中使用GLFW了。

5、导入glfw。     >>> import glfw

6、查看包帮助。   >>> help(glfw)

7、运行例子程序,因为导入的glfw中的函数名都不带GLFW,所以将simple.py中相应函数都做了对应的修改,运行结果及源程序simple.py如下:

#simple.py

if __name__ == '__main__':

import sys

import glfw

import OpenGL.GL as gl

def on_key(window, key, scancode, action, mods):

if key == glfw.KEY_ESCAPE and action == glfw.PRESS:

glfw.set_window_should_close(window,1)

# Initialize the library

if not glfw.init():

sys.exit()

# Create a windowed mode window and its OpenGL context

window = glfw.create_window(640, 480, "Hello World", None, None)

if not window:

glfw.terminate()

sys.exit()

# Make the window's context current

glfw.make_context_current(window)

# Install a key handler

glfw.set_key_callback(window, on_key)

# Loop until the user closes the window

while not glfw.window_should_close(window):

# Render here

width, height = glfw.get_framebuffer_size(window)

ratio = width / float(height)

gl.glViewport(0, 0, width, height)

gl.glClear(gl.GL_COLOR_BUFFER_BIT)

gl.glMatrixMode(gl.GL_PROJECTION)

gl.glLoadIdentity()

gl.glOrtho(-ratio, ratio, -1, 1, 1, -1)

gl.glMatrixMode(gl.GL_MODELVIEW)

gl.glLoadIdentity()

# gl.glRotatef(glfw.get_time() * 50, 0, 0, 1)

gl.glBegin(gl.GL_TRIANGLES)

gl.glColor3f(1, 0, 0)

gl.glVertex3f(-0.6, -0.4, 0)

gl.glColor3f(0, 1, 0)

gl.glVertex3f(0.6, -0.4, 0)

gl.glColor3f(0, 0, 1)

gl.glVertex3f(0, 0.6, 0)

gl.glEnd()

# Swap front and back buffers

glfw.swap_buffers(window)

# Poll for and process events

glfw.poll_events()

glfw.terminate()

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐