Краткое введение в OpenGL в Python с Pyopencl
В этом уроке мы узнаем, как использовать библиотеку PyOpenGL в Python. OpenGL-это графическая библиотека, которая поддерживается несколькими платформами, включая Windows, Linux и macOS, а также доступна для использования на нескольких других языках; однако объем этой статьи будет ограничен ее использованием на языке программирования Python.
OpenGL, по сравнению с другими подобными графическими библиотеками, довольно прост. Мы начнем с настройки его в нашей системе, а затем напишем простой пример, демонстрирующий использование библиотеки.
Установка
Самый простой способ установить OpenGL с помощью Python-это через менеджер пакетов pip . Если в вашей системе установлен pip, выполните следующую команду, чтобы загрузить и установить OpenGL:
$ pip install PyOpenGL PyOpenGL_accelerate
Я бы рекомендовал скопировать приведенную выше команду, чтобы избежать опечаток.
Как только эта команда завершит выполнение, если установка будет успешной, вы должны получить следующий вывод в конце:
Successfully installed PyOpenGL-3.1.0 PyOpenGL-accelerate-3.1.0
Если это не сработает, вы также можете загрузить его вручную. Для этого эта ссылка прокрутите вниз до заголовка “загрузка и установка” и загрузите все файлы оттуда. После этого перейдите в папку, в которую вы загрузили эти файлы, и выполните следующую команду в терминале или командной строке:
Уместно отметить, что для работы с библиотеками OpenGL в Python вам требуются инструменты сборки Visual C++ 14.0, установленные в вашей системе.
Теперь, когда мы успешно установили OpenGL в нашей системе, давайте запачкаем им руки.
Упражнение по кодированию
Первое, что нам нужно сделать, чтобы использовать OpenGL в нашем коде, – это импортировать его. Для этого выполните следующую команду:
Прежде чем мы продолжим, есть несколько других библиотек, которые вам нужно импортировать всякий раз, когда вы собираетесь использовать эту библиотеку в своей программе. Ниже приведен код для этих импортных операций:
import OpenGL.GL import OpenGL.GLUT import OpenGL.GLU print("Imports successful!") # If you see this printed to the console then installation was successful
Теперь, когда мы закончили с необходимым импортом, давайте сначала создадим окно, в котором будет показана наша графика. Код для этого приведен ниже, а также его объяснение в комментариях:
def showScreen(): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Remove everything from screen (i.e. displays all white) glutInit() # Initialize a glut instance which will allow us to customize our window glutInitDisplayMode(GLUT_RGBA) # Set the display mode to be colored glutInitWindowSize(500, 500) # Set the width and height of your window glutInitWindowPosition(0, 0) # Set the position at which this windows should appear wind = glutCreateWindow("OpenGL Coding Practice") # Give your window a title glutDisplayFunc(showScreen) # Tell OpenGL to call the showScreen method continuously glutIdleFunc(showScreen) # Draw any graphics or shapes in the showScreen function at all times glutMainLoop() # Keeps the window created above displaying/running in a loop
Скопируйте импорт выше, а также этот код в один файл python (.py) и выполните его. Вы должны увидеть всплывающий экран белого квадратного размера. Теперь, если мы хотим нарисовать какие-либо фигуры или сделать какой-либо другой вид графики, мы должны сделать это в нашей функции “showScreen”.
Давайте теперь попробуем сделать квадрат с помощью OpenGL, но прежде чем мы это сделаем, нам нужно понять систему координат, которой следует OpenGL.
Точка (0,0)-это нижняя левая часть окна, если вы поднимаетесь оттуда, вы двигаетесь вдоль оси y, а если вы идете прямо оттуда, вы двигаетесь вдоль оси x. Таким образом, верхняя левая точка вашего окна будет (0, 500), верхняя правая – (500, 500), нижняя правая – (500, 0).
Примечание : Мы говорим об окне, которое мы создали выше, которое имело размер 500 x 500 в нашем примере, а не полный экран вашего компьютера.
Теперь, когда мы с этим покончили, давайте закодируем квадрат. Объяснение кода можно найти в комментариях.
from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * w, h = 500,500 # ---Section 1--- def square(): # We have to declare the points in this sequence: bottom left, bottom right, top right, top left glBegin(GL_QUADS) # Begin the sketch glVertex2f(100, 100) # Coordinates for the bottom left point glVertex2f(200, 100) # Coordinates for the bottom right point glVertex2f(200, 200) # Coordinates for the top right point glVertex2f(100, 200) # Coordinates for the top left point glEnd() # Mark the end of drawing # This alone isn't enough to draw our square # ---Section 2--- def showScreen(): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Remove everything from screen (i.e. displays all white) glLoadIdentity() # Reset all graphic/shape's position square() # Draw a square using our function glutSwapBuffers() #---Section 3--- glutInit() glutInitDisplayMode(GLUT_RGBA) # Set the display mode to be colored glutInitWindowSize(500, 500) # Set the w and h of your window glutInitWindowPosition(0, 0) # Set the position at which this windows should appear wind = glutCreateWindow("OpenGL Coding Practice") # Set a window title glutDisplayFunc(showScreen) glutIdleFunc(showScreen) # Keeps the window open glutMainLoop() # Keeps the above created window displaying/running in a loop
Запуск кода выше будет рисовать квадрат, но этот квадрат не будет виден, так как его цвет будет таким же, как цвет нашего окна, поэтому нам нужно назначить ему другой цвет, для этого мы внесем некоторые изменения в “Раздел 2” кода выше, то есть в функцию showScreen . Добавьте следующую строку ниже оператора glLoadIdentity и выше оператора square() :
glColor3f(1.0, 0.0, 3.0) # Set the color to pink
Однако наш код все еще не завершен. В настоящее время он рисует квадрат один раз, а затем снова очищает экран. Мы этого не хотим. На самом деле, мы даже не сможем определить момент, когда он действительно рисует квадрат, потому что он появится и исчезнет за долю секунды. Давайте напишем еще одну функцию, чтобы избежать этого.
# Add this function before Section 2 of the code above i.e. the showScreen function def iterate(): glViewport(0, 0, 500,500) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0, 500, 0.0, 500, 0.0, 1.0) glMatrixMode (GL_MODELVIEW) glLoadIdentity()
Вызовите эту функцию итерации в “Разделе 2” приведенного выше кода. Добавьте его ниже glLoadIdentity и выше оператора glColor3d в функции showScreen .
Давайте теперь скомпилируем все это в один файл кода, чтобы не было никаких двусмысленностей:
from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * w,h= 500,500 def square(): glBegin(GL_QUADS) glVertex2f(100, 100) glVertex2f(200, 100) glVertex2f(200, 200) glVertex2f(100, 200) glEnd() def iterate(): glViewport(0, 0, 500, 500) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0, 500, 0.0, 500, 0.0, 1.0) glMatrixMode (GL_MODELVIEW) glLoadIdentity() def showScreen(): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() iterate() glColor3f(1.0, 0.0, 3.0) square() glutSwapBuffers() glutInit() glutInitDisplayMode(GLUT_RGBA) glutInitWindowSize(500, 500) glutInitWindowPosition(0, 0) wind = glutCreateWindow("OpenGL Coding Practice") glutDisplayFunc(showScreen) glutIdleFunc(showScreen) glutMainLoop()
Когда вы запустите эту программу, должно появиться окно с квадратной коробкой розового цвета.
Вывод
В этом уроке мы узнали об OpenGL, как его скачать и установить, а затем использовали его в качестве короткого примера программы. В этом примере мы также практиковались в создании базовой формы с помощью OpenGL, что дало нам представление о некоторых сложных вызовах функций, которые необходимо выполнять всякий раз, когда нам нужно что-то нарисовать с помощью этой библиотеки. В заключение следует отметить, что OpenGL очень изобретателен и становится все более и более сложным по мере того, как мы погружаемся в него глубже.
PyOpenGL Installation
Most users of PyOpenGL should use pip to install PyOpenGL automatically. It can be installed either to the system Python or a Virtualenv.
$ pip install PyOpenGL PyOpenGL_accelerate
Manual Installation
If you cannot, or would prefer not to, use pip , you can download the package from PyPI.
The package uses Setuptools for its installation.
$ tar -zxvf PyOpenGL-3.1.0.tar.gz $ cd PyOpenGL-3.1.0 $ python setup.py install
If you would like the (optional) PyOpenGL-accelerate package, download it from the PyOpenGL_accelerate PyPI page and follow the same basic steps:
Note that you will require a working C compiler to compile the PyOpenGL-accelerate package. Pre-built packages are available for MS Windows 32 and MS Windows 64 users.
$ tar -zxvf PyOpenGL-accelerate-3.1.0.tar.gz $ cd PyOpenGL-accelerate-3.1.0 $ python setup.py install
Recommended Enhancements for PyOpenGL
- Numpy
- GLUT or FreeGLUT
- Available as an rpm/deb/ebuild for most modern Linux machines
- The Win32 and Win64 binary installers for PyOpenGL include a copy of GLUT
- The GL Extrusion library, available on most Linux distributions (libgle3)
- The Win32 package of PyOpenGL includes a copy of GLE compiled as a DLL
Note that Togl support is deprecated, it’s there for legacy code (once you compile Togl), but you should choose a GUI library that has OpenGL support built-in for any new development. Togl support has been dropped due to the complexity of compilation and the headache of maintenance. There are projects which attempt to provide Togl support, feel free to install those into your Python’s Tk installation if you need Togl under Python.
OpenGLContext Installation
OpenGLContext is a very large package that depends on a large number of other packages to function. You do NOT need OpenGLContext to work with PyOpenGL.
Basic installation of OpenGLContext is as follows (note that you must explicitly specify the OpenGLContext and PyVRML97 releases as they are not currently in final/production releases on PyPI):
$ virtualenv oglc-env $ source oglc-env/bin/activate (oglc-env)$ pip install PyOpenGL PyOpenGL_accelerate "PyVRML97==2.3.0a4" simpleparse numpy "OpenGLContext==2.2.0a3" pydispatcher pillow
Once you have the dependencies, you can install OpenGLContext itself
$ pip install PyDispatcher PyVRML97 OpenGLContext
Recommended Enhancements for OpenGLContext
- TTFQuery and
- FontTools
- Provide access to TrueType fonts stored in the file system, used by the «toolsfont» and «pygamefont» modules in the scenegraph/text package. Without these modules, you will not have access to extruded fonts (toolsfont) or antialiased bitmap fonts (pygamefont)
- Additional contexts/windowing environments, only GLUT contexts are available otherwise.
- PyGame also provides antialiased bitmap fonts, while wxPython can provide aliased bitmap fonts if necessary
- win32ui and win32con provide support for WGL-based polygonal text, only available for Win32 systems of course. The WGL polygonal text is not used by the scenegraph engine, so it is not required for anything save playing with the WGL polygonal text demonstration module.
BZR (Developer) Install
If you would like to contribute to PyOpenGL development or just need to ride the bleeding edge, you will likely want to work with a source-code checkout. You will need the Bazaar (bzr) tool to work with the repository:
$ bzr branch lp:pyopengl $ cd pyopengl $ python setup.py develop --user $ cd OpenGL_accelerate $ python setup.py develop --user $ cd ../../
To contribute to OpenGLContext development (or to run the tests, for instance):
$ bzr branch lp:pyvrml97 $ cd pyvrml97 $ python setup.py develop --user $ cd ../ $ bzr branch lp:openglcontext $ cd openglcontext $ python setup.py develop --user
To contribute your changes back, either publish your branch publicly (for instance on LaunchPad) or create a «merge directive» to send to pyopengl-devel@lists.sourceforge.net:
Note that you’ll need to subscribe to pyopengl-devel to post changes to it. If you prefer you can send them to Mike Fletcher instead.
Building Documentation
The documentation build system is completely rewritten for PyOpenGL 3.x and is far easier to use and faster (at least a couple of orders of magnitude) than the old Java-based docbook processor.
bzr branch lp:~mcfletch/pyopengl/directdocs
cd directdocs
./samples.py
./references.py
./generate.py
./upload.pyThe last command will not work unless you happen to be me. You need the lxml.etree and kid packages installed to run the generator (also bzr, svn, PyOpenGL, cvs, etceteras).
A SourceForge Open-Source project: