1"""OpenGLDemo.py -- A simple demo of using OpenGL with Cocoa
2
3To build the demo program, run this line in Terminal.app:
4
5    $ python setup.py py2app -A
6
7This creates a directory "dist" containing OpenGLDemo.app. (The
8-A option causes the files to be symlinked to the .app bundle instead
9of copied. This means you don't have to rebuild the app if you edit the
10sources or nibs.)
11
12This example requires PyOpenGL
13"""
14
15from Cocoa import *
16from OpenGL.GL import *
17from PyObjCTools import AppHelper
18
19
20ClearColors = redIndex, greenIndex, blueIndex, alphaIndex = range(4)
21
22class OpenGLDemoView(NSOpenGLView):
23
24    def awakeFromNib(self):
25        self.color_index = alphaIndex
26
27    def initWithFrame_(self, frame):
28        attribs = [
29            NSOpenGLPFANoRecovery,
30            NSOpenGLPFAWindow,
31            NSOpenGLPFAAccelerated,
32            NSOpenGLPFADoubleBuffer,
33            NSOpenGLPFAColorSize, 24,
34            NSOpenGLPFAAlphaSize, 8,
35            NSOpenGLPFADepthSize, 24,
36            NSOpenGLPFAStencilSize, 8,
37            NSOpenGLPFAAccumSize, 0,
38        ]
39        fmt = NSOpenGLPixelFormat.alloc().initWithAttributes_(attribs)
40        self = super(OpenGLDemoView, self).initWithFrame_pixelFormat_(frame, fmt)
41        return self
42
43    @objc.IBAction
44    def setClearColor_(self, sender):
45        self.color_index = sender.tag()
46        self.setNeedsDisplay_(True)
47
48    def drawRect_(self, ((x, y), (w, h))):
49        glViewport(0, 0, w, h)
50        clear_color = [0.0]*4
51        clear_color[self.color_index] = 1.0
52        glClearColor(*clear_color)
53        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT)
54        self.openGLContext().flushBuffer()
55
56if __name__ == "__main__":
57    AppHelper.runEventLoop()
58