嗨,我一直在尝试使用NSOpenGLView在可可中制作我的第一个opengl“ app”。我想用蓝色清除背景并绘制红色点,但视图为白色。而且它不会绘制红点。也许我应该在核心视频中使用它来循环刷新它。这是《 OpenGL Superbible》一书中的代码,所以我认为这是可可的错。

#import <Cocoa/Cocoa.h>

@interface View : NSOpenGLView

@end

//---------------------------------

#import "View.h"
#include <OpenGL/gl3.h>

@implementation View

GLuint rendering_program;
GLuint VAO;


-(void)awakeFromNib{

    NSOpenGLPixelFormatAttribute pixelFormatAttributes[] =
    {
        NSOpenGLPFAOpenGLProfile, NSOpenGLProfileVersion3_2Core,
        NSOpenGLPFAColorSize    , 24                           ,
        NSOpenGLPFAAlphaSize    , 8                            ,
        NSOpenGLPFADoubleBuffer ,
        NSOpenGLPFAAccelerated  ,
        NSOpenGLPFANoRecovery   ,
        0
    };
    NSOpenGLPixelFormat *pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:pixelFormatAttributes] ;
    NSOpenGLContext* glc = [[NSOpenGLContext  alloc]initWithFormat:pixelFormat shareContext:nil];
    [self setOpenGLContext:glc];


}


-(void)prepareOpenGL{
    GLuint vs;
    GLuint fs;
    const GLchar*vss[] = {
      "#version 330 core \n"
    "void main (void)\n"
    "{\n"
    "gl_Position = vec4(0.0,0.0,0.5,1.0);\n"
    "}\n"

    };

    vs = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vs, 1, vss, 0);
    glCompileShader(vs);
    int s;
    glGetShaderiv(vs, GL_COMPILE_STATUS, &s);
    if(!s)printf("ok");

    const GLchar*fss[] = {
        "#version 330 core \n"
        "out vec4 color;"
        "void main (void)\n"
        "{\n"
        "color = vec4(1.0,0.0,0.0,1.0);\n"
        "}\n"

    };

    fs = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fs, 1,fss, 0);
    glCompileShader(fs);
    int k;
    glGetShaderiv(fs, GL_COMPILE_STATUS, &k);
    if(!k)printf("okkk");

    rendering_program = glCreateProgram();
    glAttachShader(rendering_program,vs );
    glAttachShader(rendering_program,fs );
    glLinkProgram(rendering_program);
    int n;
    glGetProgramiv(rendering_program, GL_LINK_STATUS, &n);
    glDeleteShader(vs);
    glDeleteShader(fs);
    glGenVertexArrays(1, &VAO);
    glBindVertexArray(VAO);













}

-(void)drawRect:(NSRect)dirtyRect{
    glPointSize(40);
    glClearColor(0, 0, 1, 1);
    glClear(GL_COLOR_BUFFER_BIT);
    glUseProgram(rendering_program);
    glDrawArrays(GL_POINTS, 0, 1);
    glFlush();


}

@end


这是屏幕截图:
objective-c - NSOpengl View 不起作用-LMLPHP

最佳答案

由于您正在使用双缓冲(NSOpenGLPFADoubleBuffer),因此必须在渲染后交换缓冲区:

[[self openGLContext] flushBuffer]


如果没有双缓冲(单缓冲),glFlush()就足够了。
另请参见glFlush() vs [[self openGLContext] flushBuffer]

10-07 12:22