Programming Guide Next: Installation pyglet Programming Guide The pyglet Programming Guide provides in-depth documentation for writing applications that use pyglet. Many topics described here reference the pyglet API reference, provided separately. If this is your first time reading about pyglet, we suggest you start at Writing a pyglet application. Sections • Installation • Writing a pyglet application • Creating an OpenGL context • The OpenGL interface • Graphics • Windowing • The application event loop • The pyglet event framework • Working with the keyboard • Working with the mouse • Keeping track of time • Displaying text • Images • Sound and video • Application resources • Debugging tools • Appendix: Migrating to pyglet 1.1 Table of contents • Installation ¤ Installing using setup.py ¤ Installation from the runtime eggs • Writing a pyglet application ¤ Hello, World ¤ Image viewer ¤ Handling mouse and keyboard events ¤ Playing sounds and music ¤ Where to next? • Creating an OpenGL context ¤ Displays, screens, configs and contexts (cid:224) Contexts and configs (cid:224) Displays (cid:224) Screens ¤ OpenGL configuration options (cid:224) The default configuration ¤ Simple context configuration ¤ Selecting the best configuration ¤ Sharing objects between contexts • The OpenGL interface ¤ Using OpenGL pyglet Programming Guide 1 Programming Guide ¤ Resizing the window ¤ Error checking ¤ Using extension functions ¤ Using multiple windows ¤ AGL, GLX and WGL • Graphics ¤ Drawing primitives ¤ Vertex attributes ¤ Vertex lists (cid:224) Updating vertex data (cid:224) Data usage (cid:224) Indexed vertex lists ¤ Batched rendering (cid:224) Setting the OpenGL state (cid:224) Hierarchical state (cid:224) Sorting vertex lists ¤ Batches and groups in other modules • Windowing ¤ Creating a window (cid:224) Context configuration (cid:224) Fullscreen windows ¤ Size and position ¤ Appearance (cid:224) Window style (cid:224) Caption (cid:224) Icon ¤ Visibility ¤ Subclassing Window ¤ Windows and OpenGL contexts (cid:224) Double-buffering (cid:224) Vertical retrace synchronisation • The application event loop ¤ Customising the event loop (cid:224) Event loop events (cid:224) Overriding the default idle policy ¤ Dispatching events manually • The pyglet event framework ¤ Setting event handlers ¤ Stacking event handlers ¤ Creating your own event dispatcher (cid:224) Implementing the Observer pattern (cid:224) Documenting events • Working with the keyboard ¤ Keyboard events (cid:224) Defined key symbols (cid:224) Modifiers (cid:224) User-defined key symbols (cid:224) Remembering key state ¤ Text and motion events (cid:224) Motion events ¤ Keyboard exclusivity pyglet Programming Guide 2 Programming Guide • Working with the mouse ¤ Mouse events ¤ Changing the mouse cursor ¤ Mouse exclusivity • Keeping track of time ¤ Calling functions periodically ¤ Animation techniques ¤ The frame rate (cid:224) Displaying the frame rate ¤ User-defined clocks • Displaying text ¤ Simple text rendering ¤ The document/layout model (cid:224) Documents (cid:224) Layouts ¤ Formatted text (cid:224) Character styles (cid:224) Paragraph styles (cid:224) Attributed text (cid:224) HTML ¤ Custom elements ¤ User-editable text ¤ Loading system fonts ¤ Font sizes (cid:224) Font resolution (cid:224) Determining font size ¤ Loading custom fonts (cid:224) Supported font formats ¤ OpenGL font considerations (cid:224) Context affinity (cid:224) Blend state • Images ¤ Loading an image ¤ Supported image formats ¤ Working with images ¤ The AbstractImage hierarchy ¤ Accessing or providing pixel data (cid:224) Performance concerns ¤ Image sequences and atlases (cid:224) Image grids (cid:224) 3D textures (cid:224) Texture bins and atlases ¤ Animations ¤ Buffer images ¤ Displaying images (cid:224) Sprites (cid:224) Simple image blitting ¤ OpenGL imaging (cid:224) Texture dimensions (cid:224) Texture internal format ¤ Saving an image pyglet Programming Guide 3 Programming Guide • Sound and video ¤ Audio drivers (cid:224) DirectSound (cid:224) OpenAL (cid:224) ALSA (cid:224) Linux Issues ¤ Supported media types ¤ Loading media ¤ Simple audio playback ¤ Controlling playback ¤ Incorporating video ¤ Positional audio • Application resources ¤ Loading resources (cid:224) Resource locations ¤ Specifying the resource path ¤ Multiple loaders ¤ Saving user preferences • Debugging tools ¤ Debugging OpenGL (cid:224) Error checking (cid:224) Tracing ¤ Tracing execution ¤ Platform-specific debugging (cid:224) Linux (cid:224) Windows • Appendix: Migrating to pyglet 1.1 ¤ Compatibility and deprecation ¤ Deprecated methods ¤ New features replacing standard practice (cid:224) Importing pyglet (cid:224) Application event loop (cid:224) Loading resources ¤ New graphics features ¤ New text features ¤ Other new features Next: Installation pyglet Programming Guide 4 Programming Guide Previous: The AbstractImage hierarchyNext: Image sequences ...Programming Guide » Images » Accessing or ... Accessing or providing pixel data The ImageData class represents an image as a string or sequence of pixel data, or as a ctypes pointer. Details such as the pitch and component layout are also stored in the class. You can access an ImageData object for any image with get_image_data: kitten = pyglet.image.load('kitten.png').get_image_data() The design of ImageData is to allow applications to access the detail in the format they prefer, rather than having to understand the many formats that each operating system and OpenGL make use of. The pitch and format properties determine how the bytes are arranged. pitch gives the number of bytes between each consecutive row. The data is assumed to run from left-to-right, bottom-to-top, unless pitch is negative, in which case it runs from left-to-right, top-to-bottom. There is no need for rows to be tightly packed; larger pitch values are often used to align each row to machine word boundaries. The format property gives the number and order of color components. It is a string of one or more of the letters corresponding to the components in the following table: R Red G Green B Blue A Alpha L Luminance I Intensity For example, a format string of "RGBA" corresponds to four bytes of colour data, in the order red, green, blue, alpha. Note that machine endianness has no impact on the interpretation of a format string. The length of a format string always gives the number of bytes per pixel. So, the minimum absolute pitch for a given image is len(kitten.format) * kitten.width. To retrieve pixel data in a particular format, use the get_data method, specifying the desired format and pitch. The following example reads tightly packed rows in RGB format (the alpha component, if any, will be discarded): kitten = kitten.get_image_data() data = kitten.get_data('RGB', kitten.width * 3) data always returns a string, however it can be set to a ctypes array, stdlib array, list of byte data, string, or ctypes pointer. To set the image data use set_data, again specifying the format and pitch: kitten.set_data('RGB', kitten.width * 3, data) You can also create ImageData directly, by providing each of these attributes to the constructor. This is any easy way to load textures into OpenGL from other programs or libraries. Accessing or providing pixel data 5 Programming Guide Performance concerns pyglet can use several methods to transform pixel data from one format to another. It will always try to select the most efficient means. For example, when providing texture data to OpenGL, the following possibilities are examined in order: 1. Can the data be provided directly using a built-in OpenGL pixel format such as GL_RGB or GL_RGBA? 2. Is there an extension present that handles this pixel format? 3. Can the data be transformed with a single regular expression? 4. If none of the above are possible, the image will be split into separate scanlines and a regular expression replacement done on each; then the lines will be joined together again. The following table shows which image formats can be used directly with steps 1 and 2 above, as long as the image rows are tightly packed (that is, the pitch is equal to the width times the number of components). Format Required extensions "I" "L" "LA" "R" "G" "B" "A" "RGB" "RGBA" "ARGB" GL_EXT_bgra and GL_APPLE_packed_pixels "ABGR" GL_EXT_abgr "BGR" GL_EXT_bgra "BGRA" GL_EXT_bgra If the image data is not in one of these formats, a regular expression will be constructed to pull it into one. If the rows are not tightly packed, or if the image is ordered from top-to-bottom, the rows will be split before the regular expression is applied. Each of these may incur a performance penalty -- you should avoid such formats for real-time texture updates if possible. Previous: The AbstractImage hierarchyNext: Image sequences ...Programming Guide » Images » Accessing or ... Performance concerns 6 Programming Guide Previous: Using multiple windowsNext: GraphicsProgramming Guide » The OpenGL interface » AGL, GLX ... AGL, GLX and WGL The OpenGL context itself is managed by an operating-system specific library: AGL on OS X, GLX under X11 and WGL on Windows. pyglet handles these details when a window is created, but you may need to use the functions directly (for example, to use pbuffers) or an extension function. The modules are named pyglet.gl.agl, pyglet.gl.glx and pyglet.gl.wgl. You must only import the correct module for the running operating system: if sys.platform == 'linux2': from pyglet.gl.glx import * glxCreatePbuffer(...) elif sys.platform == 'darwin': from pyglet.gl.agl import * aglCreatePbuffer(...) There are convenience modules for querying the version and extensions of WGL and GLX named pyglet.gl.wgl_info and pyglet.gl.glx_info, respectively. AGL does not have such a module, just query the version of OS X instead. If using GLX extensions, you can import pyglet.gl.glxext_arb for the registered extensions or pyglet.gl.glxext_nv for the latest nVidia extensions. Similarly, if using WGL extensions, import pyglet.gl.wglext_arb or pyglet.gl.wglext_nv. Previous: Using multiple windowsNext: GraphicsProgramming Guide » The OpenGL interface » AGL, GLX ... AGL, GLX and WGL 7 Programming Guide Previous: Calling functions periodicallyNext: The frame rateProgramming Guide » Keeping track ... » Animation techniques Animation techniques Every scheduled function takes a dt parameter, giving the actual "wall clock" time that passed since the previous invocation (or the time the function was scheduled, if it's the first period). This parameter can be used for numerical integration. For example, a non-accelerating particle with velocity v will travel some distance over a change in time dt. This distance is calculated as v * dt. Similarly, a particle under constant acceleration a will have a change in velocity of a * dt. The following example demonstrates a simple way to move a sprite across the screen at exactly 10 pixels per second: sprite = pyglet.sprite.Sprite(image) sprite.dx = 10.0 def update(dt): sprite.x += sprite.dx * dt pyglet.clock.schedule_interval(update, 1/60.0) # update at 60Hz This is a robust technique for simple animation, as the velocity will remain constant regardless of the speed or load of the computer. Some examples of other common animation variables are given in the table below. Animation parameter Distance Velocity Rotation Degrees Degrees per second Position Pixels Pixels per second Keyframes Frame number Frames per second Previous: Calling functions periodicallyNext: The frame rateProgramming Guide » Keeping track ... » Animation techniques Animation techniques 8 Programming Guide Previous: Image sequences ...Next: Buffer imagesProgramming Guide » Images » Animations Animations While image sequences and atlases provide storage for related images, they alone are not enough to describe a complete animation. The Animation class manages a list of AnimationFrame objects, each of which references an image and a duration, in seconds. The storage of the images is up to the application developer: they can each be discrete, or packed into a texture atlas, or any other technique. An animation can be loaded directly from a GIF 89a image file with load_animation (supported on Linux, Mac OS X and Windows) or constructed manually from a list of images or an image sequence using the class methods (in which case the timing information will also need to be provided). The add_to_texture_bin method provides a convenient way to pack the image frames into a texture bin for efficient access. Individual frames can be accessed by the application for use with any kind of rendering, or the entire animation can be used directly with a Sprite (see next section). The following example loads a GIF animation and packs the images in that animation into a texture bin. A sprite is used to display the animation in the window: animation = pyglet.image.load_animation('animation.gif') bin = pyglet.image.TextureBin() animation.add_to_texture_bin(bin) sprite = pyglet.sprite.Sprite(animation) window = pyglet.window.Window() @window.event def on_draw(): sprite.draw() pyglet.app.run() When animations are loaded with pyglet.resource (see Application resources) the frames are automatically packed into a texture bin. This example program is located in examples/programming_guide/animation.py, along with a sample GIF animation file. Previous: Image sequences ...Next: Buffer imagesProgramming Guide » Images » Animations Animations 9 Programming Guide Previous: Size and positionNext: VisibilityProgramming Guide » Windowing » Appearance Appearance Window style Non-fullscreen windows can be created in one of four styles: default, dialog, tool or borderless. Examples of the appearances of each of these styles under Windows XP and Mac OS X 10.4 are shown below. Style Windows XP Mac OS X WINDOW_STYLE_DEFAULT WINDOW_STYLE_DIALOG WINDOW_STYLE_TOOL Non-resizable variants of these window styles may appear slightly different (for example, the maximize button will either be disabled or absent). Besides the change in appearance, the window styles affect how the window behaves. For example, tool windows do not usually appear in the task bar and cannot receive keyboard focus. Dialog windows cannot be minimized. Selecting the appropriate window style for your windows means your application will behave correctly for the platform on which it is running, however that behaviour may not be consistent across Windows, Linux and Mac OS X. The appearance and behaviour of windows in Linux will vary greatly depending on the distribution, window manager and user preferences. Borderless windows (WINDOW_STYLE_BORDERLESS) are not decorated by the operating system at all, and have no way to be resized or moved around the desktop. These are useful for implementing splash screens or custom window borders. Window style 10
Description: