본문 바로가기

Application Programming Interface/Cocoa

macOS Application에서 OpenGL 사용 예제

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

macOS Desktop Application에서 OpenGL 사용 예제

 

View.h


/* MainView.h : View 영역에 발생하는 각종 호출과 이벤트 처리 */
#import <Cocoa/Cocoa.h>
#import <OpenGL/gl.h>

@interface MainView : NSOpenGLView

@end

 

View.m


/* MainView.m : 위 클래스의 구현 부분 */
#import "MainView.h"

@implementation MainView

/* OpenGLView 파생 클래스들은 defaultPixelFormat이 내부적으로 호출된다. Pixel Format을 가져올 때 호출된다. */
+ (NSOpenGLPixelFormat *) defaultPixelFormat {
    static NSOpenGLPixelFormatAttribute pixelFormatAttribute[] = {
        NSOpenGLPFAOpenGLProfile, NSOpenGLProfileVersion3_2Core, // OpenGL Profile 설정
        NSOpenGLPFAColorSize    , (NSOpenGLPixelFormatAttribute)(24), // 24비트 컬러 사이즈 설정 (R: 8비트, G: 8비트, B: 8비트)
        NSOpenGLPFAAlphaSize    , (NSOpenGLPixelFormatAttribute)(8), // 알파 채널의 사이즈 설정 (A: 8비트)
        NSOpenGLPFADoubleBuffer , // 더블 버퍼링 사용
        NSOpenGLPFAAccelerated  ,
        NSOpenGLPFANoRecovery   ,
        (NSOpenGLPixelFormatAttribute)(nil) // 픽셀 포맷 설정 끝
    };
    
    static NSOpenGLPixelFormat * pixelFormat = nil;
    
    NSLog(@"+ defaultPixelFormat");
    
    if (pixelFormat == nil) {
        pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:pixelFormatAttribute];
    }
    
    return pixelFormat;
}

/* View가 NIB 파일에서 불러올 때 호출됨 */
- (void) awakeFromNib {
    NSLog(@"- awakeFromNib");
    
    [[self openGLContext] makeCurrentContext]; // 이 View가 OpenGL이 사용 가능하게 함
}

/* 화면을 그릴 때 사용 */
- (void) drawRect:(NSRect)dirtyRect {
    NSLog(@"- drawRect:");
    
    glViewport(0, 0, (GLsizei)(dirtyRect.size.width), (GLsizei)(dirtyRect.size.height));
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
    
    // ... 이하 각종 OpenGL 함수 호출

    [self.openGLContext flushBuffer]; // 더블 버퍼링 사용중이므로 다 그린 버퍼의 교환
}

@end

 

xib 또는 nib에서 Custom Class 지정하기


 

실행 결과