Добавление контекста OpenGL в окно какао
Я пытаюсь добавить контекст OpenGL в NSWindow, но по какой-то причине это не работает. Он правильно создает и отображает NSWindow при запуске приложения, но я ничего не могу сделать с контекстом OpenGL, поэтому я предполагаю, что контекст не был правильно добавлен в NSWindow.
Это мой код до сих пор:
import Foundation
import AppKit
import GLKit
let application = NSApplication.sharedApplication()
application.setActivationPolicy(NSApplicationActivationPolicy.Regular)
let window = NSWindow(contentRect: NSMakeRect(0, 0, 640, 480), styleMask: NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask, backing: .Buffered, defer: false)
window.center()
window.title = "Programmatically Created Window"
window.makeKeyAndOrderFront(window)
class WindowDelegate: NSObject, NSWindowDelegate {
func windowWillClose(notification: NSNotification) {
NSApplication.sharedApplication().terminate(0)
}
}
let windowDelegate = WindowDelegate()
window.delegate = windowDelegate
class AppDelegate: NSObject, NSApplicationDelegate {
var window: NSWindow
init(window: NSWindow) {
self.window = window
}
func applicationDidFinishLaunching(notification: NSNotification) {
let glContext = NSOpenGLView()
self.window.contentView.addSubview(glContext)
// let glAttributes: [NSOpenGLPixelFormatAttribute] = [
// UInt32(NSOpenGLPFAAccelerated),
// UInt32(NSOpenGLPFADoubleBuffer),
// UInt32(NSOpenGLPFAColorSize), UInt32(48),
// UInt32(NSOpenGLPFAAlphaSize), UInt32(16),
// UInt32(NSOpenGLPFAMultisample),
// UInt32(NSOpenGLPFASampleBuffers), UInt32(1),
// UInt32(NSOpenGLPFASamples), UInt32(4),
// UInt32(NSOpenGLPFAMinimumPolicy),
// UInt32(0)
// ]
//
// let pixelFormat = NSOpenGLPixelFormat(attributes: glAttributes)
// let glContext = NSOpenGLContext(format: pixelFormat, shareContext: nil)
// self.window.contentView.addSubview(glContext!.view)
// glContext!.view = self.window.contentView as NSView
}
}
let applicationDelegate = AppDelegate(window: window)
application.delegate = applicationDelegate
application.activateIgnoringOtherApps(true)
application.run()
glClearColor(0, 0, 0, 0)
1 ответ
Просто, чтобы проиллюстрировать мой комментарий, вот код. Этот OpenGLView инициализируется IB, поэтому существует метод awakeFromNib, но вы получите идею:
#import "WispView.h"
#import "AppController.h"
@implementation WispView
// *************************** Init **************************************
- (id)initWithFrame:(NSRect)frameRect
{
self = [super initWithFrame:frameRect];
return self;
}
// *********************** Awake From Nib *********************************
- (void)awakeFromNib;
{
// *********** Invoke OpenGL 4.1 and GLSL 4.1
// ********* Default is OpenGL 2.1 and GLSL 1.2
NSOpenGLPixelFormatAttribute attributes [] =
{
NSOpenGLPFAOpenGLProfile, NSOpenGLProfileVersion3_2Core,
NSOpenGLPFADoubleBuffer, // double buffered
NSOpenGLPFADepthSize, (NSOpenGLPixelFormatAttribute)32, // 32 bit depth buffer
NSOpenGLPFAAccelerated,
(NSOpenGLPixelFormatAttribute)nil
};
NSOpenGLPixelFormat * pf = [[NSOpenGLPixelFormat alloc] initWithAttributes:attributes];
[self setPixelFormat:pf];
tempFractalIsDisplayed = NO;
workingFractalIsDisplayed = NO;
gridIsDisplayed = NO;
attractorIsDisplayed = NO;
return;
}
// ******************** Init OpenGL Stuff Here **********************************
- (void) prepareOpenGL
{
[[self openGLContext] makeCurrentContext];
// *********** Log the Current OpenGL and GLSL Versions
NSLog(@"OpenGL version = %s", glGetString(GL_VERSION));
NSLog(@"GLSL version = %s", glGetString(GL_SHADING_LANGUAGE_VERSION));
//********************* General OpenGL Stuff
glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // ** Set Background Clear Color
glEnable(GL_DEPTH_TEST); // Hide hidden surfaces
glDepthFunc(GL_LEQUAL);
glClearDepth(1.0);
glEnable(GL_TEXTURE_2D);
glFrontFace(GL_CCW);
return;
}
// *************************** Draw Rect **********************************
- (void)drawRect:(NSRect)dirtyRect
{
[[self openGLContext] makeCurrentContext];
// ******************************************** Clear the Drawable
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if(tempFractalIsDisplayed)
{
[appController->flameFractals runTheFlameShadersWithColoringData:&appDelegate->tempColoringData];
}
if(workingFractalIsDisplayed)
{
[appController->flameFractals runTheFlameShadersWithColoringData:&appDelegate->workingColoringData];
}
if(gridIsDisplayed)
{
[appController->flameFractals runTheGridShaders];
}
if(attractorIsDisplayed)
{
[appController->flameFractals runTheFlameShadersWithColoringData:&appController->lyapunov->attractorColoringData];
}
[[self openGLContext] flushBuffer];
return;
}
Вам не нужно делать все свои рисунки из NSOpenGLClass. Другие классы также могут использовать его контекст для рисования, но вам по крайней мере нужен какой-то код обновления чертежа внутри метода drawRect, потому что этот метод вызывается во время изменения размера.
В этом методе drawRect изображения фактически рисуются в других классах. Этот код вызывается системой только во время изменения размера или перехода в полноэкранный режим.