I am trying to programmatically create a Cocoa window with an OpenGL context for an OS X application. I have been unable to find an example online which does not use the Interface Builder for creating a window and OpenGL view.
All I want is for glClear to make my window magenta (0xFF00FF). However, the window remains white.
Here is my project:
AppDelegate.h
#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject <NSApplicationDelegate> {
NSWindow *window;
NSOpenGLContext *openGLContext;
}
@property (assign) NSWindow *window;
@property (assign) NSOpenGLContext *openGLContext;
- (void)draw;
@end
AppDelegate.m
#import "AppDelegate.h"
@implementation AppDelegate
@synthesize window;
@synthesize openGLContext;
static NSOpenGLPixelFormatAttribute glAttributes[] = {
0
};
- (void)draw {
NSLog(@"Drawing...");
[self.openGLContext makeCurrentContext];
glClearColor(1, 0, 1, 1);
glClear(GL_COLOR_BUFFER_BIT);
[self.openGLContext flushBuffer];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSRect frame = NSMakeRect(0, 0, 200, 200);
self.window = [[[NSWindow alloc]
initWithContentRect:frame
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered
defer:NO] autorelease];
[self.window makeKeyAndOrderFront:nil];
NSOpenGLPixelFormat *pixelFormat
= [[NSOpenGLPixelFormat alloc] initWithAttributes:glAttributes];
self.openGLContext = [[NSOpenGLContext alloc]
initWithFormat:pixelFormat shareContext:nil];
[self.openGLContext setView:[self.window contentView]];
[NSTimer
scheduledTimerWithTimeInterval:.1
target:self
selector:@selector(draw)
userInfo:nil
repeats:YES];
}
- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)_app {
return YES;
}
@end
main.m
#import "AppDelegate.h"
#import <Cocoa/Cocoa.h>
int main(int argc, char **argv) {
AppDelegate *appDelegate = [[AppDelegate alloc] init];
return NSApplicationMain(argc, (const char **) argv);
}
The documentation for
-[NSOpenGLContext flushBuffer]says:You can cause your context to be double-buffered by including
NSOpenGLPFADoubleBufferin your pixel format attributes. Alternatively, you can callglFlush()instead of-[NSOpenGLContext flushBuffer]and leave your context single-buffered.