Exemple #1
0
int main(void){
    static const int width(1280), height(720);

    sf::Window window(sf::VideoMode(width, height), "OpenGL", sf::Style::Default, sf::ContextSettings(32));
    window.setFramerateLimit(60);

    GLint error;
    if(GLEW_OK != (error = glewInit())) {
        std::cerr << "Glew init failed" << std::endl;
        return EXIT_FAILURE;
    }

    // RAW CPU DATA
    int count = 12;
    int index[] = {0, 1, 2, 2, 1, 3, 4, 5, 6, 6, 5, 7, 8, 9, 10, 10, 9, 11, 12, 13, 14, 14, 13, 15, 16, 17, 18, 19, 17, 20, 21, 22, 23, 24, 25, 26, };
    float uv[] = {0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f,  1.f, 0.f,  1.f, 1.f,  0.f, 1.f,  1.f, 1.f,  0.f, 0.f, 0.f, 0.f, 1.f, 1.f,  1.f, 0.f,  };
    float vertices[] = {-0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5 };
    float normals[] = {0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, };
    int   quad_triangleCount = 2;
    int   quad_triangleList[] = {0, 1, 2, 2, 1, 3};
    float quad_vertices[] =  {-1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0};

    // Creatin Buffer Objects
    hglt::VAO vao;
    hglt::VAO quadVAO;

    hglt::VBO quadIndexVBO;
    hglt::VBO quadVerticesVBO;
    hglt::VBO indexVBO;
    hglt::VBO verticesVBO;
    hglt::VBO normalsVBO;
    hglt::VBO uvVBO;

    // Send RAW Data from CPU to BO in GPU
    /// Quad
    quadVAO.bind();
    quadIndexVBO.bind(GL_ELEMENT_ARRAY_BUFFER);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quad_triangleList), quad_triangleList, GL_STATIC_DRAW);

    quadVerticesVBO.bind();
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*2, (void*)0);
    glBufferData(GL_ARRAY_BUFFER, sizeof(quad_vertices), quad_vertices, GL_STATIC_DRAW);
    quadVAO.unbind();

    /// Index
    indexVBO.bind(GL_ELEMENT_ARRAY_BUFFER);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(index), index, GL_STATIC_DRAW);
    hglt::VBO::unbind(GL_ELEMENT_ARRAY_BUFFER);

    /// Vertices
    verticesVBO.bind();
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    hglt::VBO::unbind();

    /// Normals
    normalsVBO.bind();
    glBufferData(GL_ARRAY_BUFFER, sizeof(normals), normals, GL_STATIC_DRAW);
    hglt::VBO::unbind();

    /// UV
    uvVBO.bind();
    glBufferData(GL_ARRAY_BUFFER, sizeof(uv), uv, GL_STATIC_DRAW);
    hglt::VBO::unbind();

    // Build VAO
    vao.bind();

    // Set Index GL_ELEMENT_ARRAY_BUFFER
    indexVBO.bind(GL_ELEMENT_ARRAY_BUFFER);

    // Set Buffer Object GL_ARRAY_BUFFER
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glEnableVertexAttribArray(2);

    verticesVBO.bind(GL_ARRAY_BUFFER);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (const GLvoid*) (0 * sizeof(GLfloat)));
    hglt::VBO::unbind();

    normalsVBO.bind();
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (const GLvoid*) (0 * sizeof(GLfloat)));
    hglt::VBO::unbind();

    uvVBO.bind();
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), (const GLvoid*) (0 * sizeof(GLfloat)));
    hglt::VBO::unbind();

    hglt::VAO::unbind();

    // LOAD SHADER
    hglt::Program geometryShader = hglt::loadProgram("shader/simple.vs.glsl", "shader/simple.fs.glsl");
    hglt::Program laccumShader = hglt::loadProgram( "shader/lightAccumulation.vs.glsl",
                                                    "shader/lightAccumulation.fs.glsl");
    hglt::Program blitShader = hglt::loadProgram( "shader/blit.vs.glsl", "shader/blit.fs.glsl");
    // LOAD TEXTURE
    hglt::Texture spec = hglt::loadTexture2D("texture/spec.tga");
    hglt::Texture diff = hglt::loadTexture2D("texture/diff.tga", GL_TEXTURE1);

    // Get Uniform Location
    GLint ksLocation = glGetUniformLocation(geometryShader.getGLId(), "uMat.ks");
    GLint kdLocation = glGetUniformLocation(geometryShader.getGLId(), "uMat.kd");
    GLint shininessLocation = glGetUniformLocation(geometryShader.getGLId(), "uMat.shininess");

    GLint laccumMaterialLocation = glGetUniformLocation(laccumShader.getGLId(), "uMaterial");
    GLint laccumNormalLocation = glGetUniformLocation(laccumShader.getGLId(), "uNormal");
    GLint laccumDepthLocation = glGetUniformLocation(laccumShader.getGLId(), "uDepth");
    GLint laccumCameraPositionLocation = glGetUniformLocation(laccumShader.getGLId(), "uCameraPosition");
    GLint laccumInverseViewProjectionLocation = glGetUniformLocation(laccumShader.getGLId(), "uInvViewProjection");
    GLint laccumLightPositionLocation = glGetUniformLocation(laccumShader.getGLId(), "uLightPosition");
    GLint laccumLightColorLocation = glGetUniformLocation(laccumShader.getGLId(), "uLightColor");
    GLint laccumLightIntensityLocation = glGetUniformLocation(laccumShader.getGLId(), "uLightIntensity");

    GLuint blitTex1Location = glGetUniformLocation(blitShader.getGLId(), "uTexture1");


    glUniform1i(kdLocation, 0);
    glUniform1i(ksLocation, 1);


    // TRANSORMATION MATRIX
    glm::mat4 model(1.0);
    glm::mat4 view(1.0);
    glm::mat4 projection(1.0);

    GLint modelLocation = glGetUniformLocation(geometryShader.getGLId(), "uModel");
    GLint viewLocation = glGetUniformLocation(geometryShader.getGLId(), "uView");
    GLint projectionLocation = glGetUniformLocation(geometryShader.getGLId(), "uProjection");

    GLint cameraPositionLocation = glGetUniformLocation(geometryShader.getGLId(), "uCameraPosition");
    GLint timeLocation = glGetUniformLocation(geometryShader.getGLId(), "uTime");

    //std::cout << glm::to_string(model) << std::endl;

    sf::Clock clock;
    sf::Clock clock2;

    // Create Camera
    hglt::Camera camera;
    glEnable(GL_DEPTH_TEST);

    // Alloc FrameBuffer
    hglt::FrameBuffer gbuffer(width, height, 2);
    if(!gbuffer.isValid()){
        std::cerr << "Can't build FrameBuffer." << std::endl;
        return EXIT_FAILURE;
    }

    // Main Loop
    while (window.isOpen()){
        sf::Time frameTime = clock.restart();
        float framerate = 1 / (frameTime.asMilliseconds() * 0.001);
        //std::cout << framerate << "FPS" << std::endl;

        // GEOMETRY PASS
        gbuffer.bind();
        glDrawBuffers(gbuffer.outCount, gbuffer.drawBuffers);

        glViewport( 0, 0, width, height  );

        glEnable(GL_DEPTH_TEST);

        // Reset
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // Use Geometry Shader
        geometryShader.use();

        // Upload Uniform
        glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, glm::value_ptr(camera.getProjectionMatrix()));
        glUniformMatrix4fv(viewLocation, 1, GL_FALSE, glm::value_ptr(camera.getViewMatrix()));
        glUniformMatrix4fv(modelLocation, 1, GL_FALSE, glm::value_ptr(model));
        glUniform3fv(cameraPositionLocation, 1, glm::value_ptr(camera.getPosition()));
        glUniform1f(timeLocation, clock2.getElapsedTime().asMilliseconds()* 0.001);
        glUniform1f(shininessLocation, 1000.0f);

        // Draw
        /// Bind Texture
        diff.bind(GL_TEXTURE0);
        spec.bind(GL_TEXTURE1);

        vao.bind();
        //glDrawArrays(GL_TRIANGLES, 0, 3);
        glDrawElements(GL_TRIANGLES, count*3, GL_UNSIGNED_INT, 0);
        hglt::VAO::unbind();

        hglt::Texture::unbind();

        hglt::FrameBuffer::unbind();

        // LIGHT ACCUMULATION PASS

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        laccumShader.use();

        glUniform1i(laccumMaterialLocation, 0);
        glUniform1i(laccumNormalLocation, 1);
        glUniform1i(laccumDepthLocation, 2);
        glUniform3fv(laccumCameraPositionLocation, 1, glm::value_ptr(camera.getPosition()));
        glUniformMatrix4fv( laccumInverseViewProjectionLocation, 1, 0,
                            glm::value_ptr(glm::inverse(camera.getProjectionMatrix())));

        // Bind color to unit 0
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, gbuffer.colorTexId[0]);
        // Bind normal to unit 1
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, gbuffer.colorTexId[1]);
        // Bind depth to unit 2
        glActiveTexture(GL_TEXTURE2);
        glBindTexture(GL_TEXTURE_2D, gbuffer.depthTexId);

        // Blit above the rest
        glDisable(GL_DEPTH_TEST);

        glEnable(GL_BLEND);
        glBlendFunc(GL_ONE, GL_ONE);

        for (unsigned int i = 0; i < 10; ++i) {
            float tl = clock2.getElapsedTime().asMilliseconds()* 0.0001 * i;

            //Update light uniforms
            float lightPosition[3] = { sinf(tl) * 10.0f, 0.5f, cosf(tl) * 10.0f};
            float lightColor[3] = {sinf(tl) *  1.0f, 1.0f - cosf(tl), -sinf(tl)};
            float lightIntensity = 10.0f;

            glUniform3fv(laccumLightPositionLocation, 1, lightPosition);
            glUniform3fv(laccumLightColorLocation, 1, lightColor);
            glUniform1f(laccumLightIntensityLocation, lightIntensity);

            // Draw quad
            glBindVertexArray(quadVAO.getGLId());
            glDrawElements(GL_TRIANGLES, quad_triangleCount * 3, GL_UNSIGNED_INT, (void*)0);
        }

        glDisable(GL_BLEND);

        // Bind blit shader
        blitShader.use();
        // Upload uniforms
        glUniform1i(blitTex1Location, 0);
        // use only unit 0
        glActiveTexture(GL_TEXTURE0);

        // Viewport
        glViewport( 0, 0, width/3, height/4  );
        // Bind texture
        glBindTexture(GL_TEXTURE_2D, gbuffer.colorTexId[0]);
        // Draw quad
        quadVAO.bind();
        glDrawElements(GL_TRIANGLES, quad_triangleCount * 3, GL_UNSIGNED_INT, (void*)0);
        // Viewport
        glViewport( width/3, 0, width/3, height/4  );
        // Bind texture
        glBindTexture(GL_TEXTURE_2D, gbuffer.colorTexId[1]);
        // Draw quad
        quadVAO.bind();
        glDrawElements(GL_TRIANGLES, quad_triangleCount * 3, GL_UNSIGNED_INT, (void*)0);
        // Viewport
        glViewport( width/3 * 2, 0, width/3, height/4  );
        // Bind texture
        glBindTexture(GL_TEXTURE_2D, gbuffer.depthTexId);
        // Draw quad
        quadVAO.bind();
        glDrawElements(GL_TRIANGLES, quad_triangleCount * 3, GL_UNSIGNED_INT, (void*)0);

        // Check for OpenGL errors
        GLenum err = glGetError();
        if(err != GL_NO_ERROR)
            std::cerr << "OpenGL Error" << gluErrorString(err);

        sf::Event event;
        while(window.pollEvent(event)){
            if(event.type == sf::Event::Closed)
                window.close();

            else if(event.type == sf::Event::Resized)
                glViewport(0, 0, event.size.width, event.size.height);
        }

        { // Keyboard Manager
            static bool shiftLock(false);

            if( sf::Keyboard::isKeyPressed(sf::Keyboard::Escape) )
                window.close();

            if( sf::Keyboard::isKeyPressed(sf::Keyboard::Z) )
                camera.moveFront(-0.1);

            if( sf::Keyboard::isKeyPressed(sf::Keyboard::S) )
                camera.moveFront(0.1);

            if( sf::Keyboard::isKeyPressed(sf::Keyboard::LShift) ){
                static sf::Vector2i lockMousePos;
                if( shiftLock ){
                    sf::Vector2i mouse = sf::Mouse::getPosition(window);

                    camera.rotateLeft(float(mouse.x - lockMousePos.x) / 10.0);
                    camera.rotateUp(float(mouse.y - lockMousePos.y) / 10.0);
                    sf::Mouse::setPosition(lockMousePos, window);
                }
                else{
                    shiftLock = true;
                    lockMousePos = sf::Mouse::getPosition(window);
                    window.setMouseCursorVisible(false);
                }
            }
            else{
                shiftLock = false;
                window.setMouseCursorVisible(true);
            }
        }

        window.display();
    }

    return EXIT_SUCCESS;
}
Exemple #2
0
void init()
{

   GLint maxBuffers;
   glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT, &maxBuffers);
   printf("MAX_COLOR_ATTACHMENTS: %d\n", maxBuffers);


   glShadeModel(GL_SMOOTH);
   glClearColor(0.0f, 0.0f, 0.2f, 0.5f);
   glClearDepth(1.0f);
   glEnable(GL_DEPTH_TEST);
   glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
   glDepthFunc(GL_LEQUAL);
   glViewport(0, 0, sWidth, sHeight);

   // setup the FBO
   glGenFramebuffersEXT(1, &fbo);
   glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);

   // create the render buffer for depth
   glGenRenderbuffersEXT(1, &depthBuffer);
   glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depthBuffer);
   glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, texWidth, texHeight);

   // IMAGE TEXTURE
   glGenTextures(1, &imgTexture);
   glBindTexture(GL_TEXTURE_2D, imgTexture);
   glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16, texWidth, texHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

   // attach texture
   glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, imgTexture, 0);


   // DEPTH TEXTURE
   glGenTextures(1, &depthTexture);
   glBindTexture(GL_TEXTURE_2D, depthTexture);
   glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16, texWidth, texHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

   // Attach the texture to the FBO for rendering
   glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_TEXTURE_2D, depthTexture, 0);


   // NORMAL TEXTURE
   glGenTextures(1, &normalTexture);
   glBindTexture(GL_TEXTURE_2D, normalTexture);
   glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA16, texWidth, texHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

   // attach the second texture
   glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT2_EXT, GL_TEXTURE_2D, normalTexture, 0);

   // attach the depth buffer to the FBO
   glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depthBuffer);

   // define the render targets
   GLenum mrt[] = {GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_COLOR_ATTACHMENT2_EXT};
   glDrawBuffers(3, mrt);

   // check the FBO status
   GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
   if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
   {
      printf("ERROR: FBO status not complete\n");
      exit(1);
   }

   //// setup the FBO
   //glGenFramebuffersEXT(1, &fbo2);
   //glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);

   //glGenTextures(1, &outlineTexture);
   //glBindTexture(GL_TEXTURE_2D, outlineTexture);
   //glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA16, texWidth, texHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
   //glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
   //glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
   //glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
   //glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

   //glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, outlineTexture, 0);

   //glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depthBuffer);

   //status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
   //if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
   //{
   //   printf("ERROR: FBO status not complete\n");
   //   exit(1);
   //}

   // detach the FBO
   glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
}
Exemple #3
0
void PezRender()
{
    glGetError();

    // Pass 1: draw into offscreen FBO
    if (ShowAO || ComputeAO)
    {
        glUseProgram(Scene.OffscreenProgram);
        SetUniforms();
        glBindFramebuffer(GL_FRAMEBUFFER, Scene.Surfaces.FboHandle);
        GLenum renderTargets[3] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2};
        glDrawBuffers(3, &renderTargets[0]);
        DrawScene();
    }

    pezCheck(glGetError() == GL_NO_ERROR, "OpenGL error.\n");

    // Read the offscreen buffers into CPU memory
    if (ComputeAO) 
    {
        ComputeAO = 0;
        PezConfig cfg = PezGetConfig();

        static float* PositionData = (float*) malloc(sizeof(float) * 3 * cfg.Width * cfg.Height);
        glReadBuffer(GL_COLOR_ATTACHMENT0 + FboDesc::Positions);
        glReadPixels(0, 0, cfg.Width, cfg.Height, GL_RGB, GL_FLOAT, PositionData);

        static float* NormalData = (float*) malloc(sizeof(float) * 3 * cfg.Width * cfg.Height);
        glReadBuffer(GL_COLOR_ATTACHMENT0 + FboDesc::Normals);
        glReadPixels(0, 0, cfg.Width, cfg.Height, GL_RGB, GL_FLOAT, NormalData);

        static float* ColorData = (float*) malloc(sizeof(float) * 3 * cfg.Width * cfg.Height);
        glReadBuffer(GL_COLOR_ATTACHMENT0 + FboDesc::Colors);
        glReadPixels(0, 0, cfg.Width, cfg.Height, GL_RGB, GL_FLOAT, ColorData);

        static float* CompositeData = (float*) malloc(sizeof(float) * 4 * cfg.Width * cfg.Height);

        float* pPosition = PositionData;
        float* pNormal = NormalData;
        float* pColor = ColorData;
        float* pComposite = CompositeData;
        for (int x = 0; x < cfg.Width; ++x) {
            for (int y = 0; y < cfg.Height; ++y) {
                
                AO_MaxDist = 0.025f;
                AO_NumPoints = 16;

                if (pColor[0] > 0.0f || pColor[1] > 0.0f || pColor[2] > 0.0f) {
                    float occlusion = 0.5f;
                    PtcGetNearestPointsData(Scene.PointCloud, pPosition, pNormal, AO_MaxDist, AO_NumPoints, &occlusion);
                    occlusion = 1.0f - occlusion;
                    pComposite[0] = pColor[0] * occlusion;
                    pComposite[1] = pColor[1] * occlusion;
                    pComposite[2] = pColor[2] * occlusion;
                    pComposite[3] = 1.0f;
                } else {
                    pComposite[0] = 0;
                    pComposite[1] = 0;
                    pComposite[2] = 0;
                    pComposite[3] = 0;
                }

                pPosition += 3;
                pNormal += 3;
                pColor += 3;
                pComposite += 4;
            }
        }

        pezCheck(glGetError() == GL_NO_ERROR, "OpenGL error.\n");
 
        glBindTexture(GL_TEXTURE_2D, Scene.CompositeTexture);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, cfg.Width, cfg.Height, GL_FALSE, GL_RGBA, GL_FLOAT, CompositeData);

        pezCheck(glGetError() == GL_NO_ERROR, "OpenGL error.\n");
        glBindFramebuffer(GL_FRAMEBUFFER, 0);
    }

    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    GLenum renderTargets[3] = {GL_BACK_LEFT, GL_NONE, GL_NONE};
    glDrawBuffers(3, &renderTargets[0]);

    pezCheck(glGetError() == GL_NO_ERROR, "OpenGL error.\n");

    // Draw into backbuffer
    if (ShowAO) {
        glBindTexture(GL_TEXTURE_2D, Scene.CompositeTexture);
        glUseProgram(Scene.QuadProgram);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glBindVertexArray(Scene.QuadVao);
        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    } else {
        glUseProgram(Scene.DisplayProgram);
        SetUniforms();
        DrawScene();
    }

    pezCheck(glGetError() == GL_NO_ERROR, "OpenGL error.\n");
    glUseProgram(0);
    glBindVertexArray(0);
    TwDraw();
    glGetError();
}
Exemple #4
0
void NGLScene::paintGL()
{

  glBindFramebuffer (GL_FRAMEBUFFER, m_gbuffer);
  /*************************************************************************************************/
  // Geo Pass
  /*************************************************************************************************/

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  GLenum drawBuffers[] = { GL_COLOR_ATTACHMENT0,GL_COLOR_ATTACHMENT1,GL_COLOR_ATTACHMENT2,GL_COLOR_ATTACHMENT3};
  glDrawBuffers (4, drawBuffers);

  drawScene("Pass1");
  /*************************************************************************************************/
  // now do the light pass
  /*************************************************************************************************/
/*  glBindFramebuffer (GL_FRAMEBUFFER, m_lightBuffer);
  GLenum lightBuffers[] = { GL_COLOR_ATTACHMENT0};
  glDrawBuffers (1, lightBuffers);

  glClear (GL_COLOR_BUFFER_BIT);

  // map the texture buffers so light pass can read them
 glActiveTexture (GL_TEXTURE0);
 glBindTexture (GL_TEXTURE_2D, m_pointTexID);
 glActiveTexture (GL_TEXTURE1);
 glBindTexture (GL_TEXTURE_2D, m_normalTexID);
 glActiveTexture (GL_TEXTURE2);
 glBindTexture (GL_TEXTURE_2D, m_colourTexID);
 glActiveTexture (GL_TEXTURE3);
 glBindTexture (GL_TEXTURE_2D, m_shadingTexID);
// glActiveTexture (GL_TEXTURE4);
// glBindTexture (GL_TEXTURE_2D, m_lightPassTexID);



 glGenerateMipmap(GL_TEXTURE_2D);

 glClear(GL_COLOR_BUFFER_BIT);

// renderLightPass("Lighting");

  glActiveTexture (GL_TEXTURE0);
  glBindTexture (GL_TEXTURE_2D, m_pointTexID);
  glActiveTexture (GL_TEXTURE1);
  glBindTexture (GL_TEXTURE_2D, m_normalTexID);
  glActiveTexture (GL_TEXTURE2);
  glBindTexture (GL_TEXTURE_2D, m_colourTexID);
  glActiveTexture (GL_TEXTURE3);
  glBindTexture (GL_TEXTURE_2D, m_shadingTexID);
//  glActiveTexture (GL_TEXTURE4);
//  glBindTexture (GL_TEXTURE_2D, m_lightPassTexID);

*/
/*
  // now blit
  glActiveTexture (GL_TEXTURE0);
  glBindTexture (GL_TEXTURE_2D, m_pointTexID);
  glActiveTexture (GL_TEXTURE1);
  glBindTexture (GL_TEXTURE_2D, m_normalTexID);
  glActiveTexture (GL_TEXTURE2);
  glBindTexture (GL_TEXTURE_2D, m_colourTexID);
  glActiveTexture (GL_TEXTURE3);
  glBindTexture (GL_TEXTURE_2D, m_shadingTexID);

  glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
  glBindFramebuffer(GL_READ_FRAMEBUFFER, m_lightBuffer);

  glReadBuffer(GL_COLOR_ATTACHMENT0+m_debugMode);
  int w=width()*devicePixelRatio();
  int h=height()*devicePixelRatio();

  glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_COLOR_BUFFER_BIT, GL_NEAREST);
*/

  if(m_debug==true)
  {
    glBindFramebuffer (GL_FRAMEBUFFER, 0);
    glActiveTexture (GL_TEXTURE0);
    glBindTexture (GL_TEXTURE_2D, m_pointTexID);
    glActiveTexture (GL_TEXTURE1);
    glBindTexture (GL_TEXTURE_2D, m_normalTexID);
    glActiveTexture (GL_TEXTURE2);
    glBindTexture (GL_TEXTURE_2D, m_colourTexID);
    glActiveTexture (GL_TEXTURE3);
    glBindTexture (GL_TEXTURE_2D, m_shadingTexID);
    glActiveTexture (GL_TEXTURE4);
    glBindTexture (GL_TEXTURE_2D, m_lightPassTexID);

    glGenerateMipmap(GL_TEXTURE_2D);

    glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    ngl::ShaderLib *shader = ngl::ShaderLib::instance();

    shader->use("Debug");
    //shader->setUniform("cam",m_cam->getEye().toVec3());
    shader->setShaderParam1i("mode",m_debugMode);
    m_screenQuad->draw();

  }

  // calculate and draw FPS
  glBindFramebuffer (GL_FRAMEBUFFER, 0);

  ++m_frames;
  glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
  m_text->setColour(1,1,0);
  QString text=QString("%1 fps using %2 to draw").arg(m_fps).arg(m_debug ? "ScreenQuad" : "glBlitFramebuffer");
  m_text->renderText(10,20,text);

}
Exemple #5
0
int Splat_Prepare(SDL_Window *userWindow, int userViewportWidth, int userViewportHeight) {
  int width, height;
  window = userWindow;
  viewportWidth = userViewportWidth;
  viewportHeight = userViewportHeight;
  SDL_GetWindowSize(userWindow, &width, &height);

  SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 4);
  SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 4);
  SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 4);
  SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 4);
  SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
  SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

  window_glcontext = SDL_GL_CreateContext(window);
  if (!window_glcontext) {
    Splat_SetError("OpenGL context creation failed.  Check glGetError() and/or SDL_GetError() for more information.");
    Splat_Finish();
    return -1;
  }

  // Our shading model--Flat
  glShadeModel(GL_FLAT);

  // Default the clear color to black.
  glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

  // Setup our viewport.
  glViewport(0, 0, viewportWidth, viewportHeight);

  // Change to the projection matrix and set up our ortho view
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluOrtho2D(0, width, 0, height);

  // Set up modelview for 2D integer coordinates
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  glTranslatef(0.375f, height + 0.375f, 0.0f);
  glScalef(1.0f, -1.0f, 0.001f); // Make the positive Z-axis point "out" from the view (e.g images at depth 4 will be higher than those at depth 0), and swap the Y axis

  /* Deactivate the system cursor */
  SDL_ShowCursor(SDL_DISABLE);

  glDisable(GL_DITHER);

  /* Create the frame buffer for rendering to texture*/
  glGenFramebuffers(1, &framebuffer);

  glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);

  /* Set up the texture to which we're going to render */
  glGenTextures(1, &frameTexture);
  glBindTexture(GL_TEXTURE_2D, frameTexture);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, viewportWidth, viewportHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

  /* Configure the framebuffer texture */
  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, frameTexture, 0);
  GLenum DrawBuffers[1] = { GL_COLOR_ATTACHMENT0 };
  glDrawBuffers(1, DrawBuffers);

  GLenum err = glGetError();
  if (err != GL_NO_ERROR) {
    Splat_SetError("OpenGL error occurred during initialization");
    Splat_Finish();
    return -1;
  }

  return 0;
}
Exemple #6
0
void display(){

	glClearColor(0.17f, 0.4f, 0.6f, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	if(recalcLabyrinth){
		int level = dataBuffer->getLevels() - 1;
		dataBuffer->setRenderTarget(level);
		GLenum ca = GL_COLOR_ATTACHMENT0; glDrawBuffers(1, &ca);
		glClearColor(1,0,1,0); glClear(GL_COLOR_BUFFER_BIT);
		ca = GL_COLOR_ATTACHMENT1; glDrawBuffers(1, &ca);
		glClearColor(0.5,0.5,0.5,0.5); glClear(GL_COLOR_BUFFER_BIT);
		float scale = noiseStart;
		for(level = level - 1; level >= 0; level--){
			dataBuffer->setRenderTarget(level);
			generateShader->enable();
			generateShader->bindUniformInt("level", level);
			generateShader->bindUniformFloat("noiseScale", scale);
			generateShader->bindUniformFloat("noiseSeed", noiseSeed * 16.0);
			generateShader->bindUniformTexture("inputTex1", dataBuffer->getColorBuffer(0),0);
			generateShader->bindUniformTexture("inputTex2", dataBuffer->getColorBuffer(1),1);
			generateShader->bindUniformTexture("noiseTex", noiseTexture->getTextureHandle(),2);
			fullscreenQuad->render(generateShader);
			generateShader->disable();
			scale *= noiseScale;
		}
		dataBuffer->disableRenderTarget();
		recalcLabyrinth = false;
		startPointChanged = true;
	}

	if(startPointChanged)
	{
		endpointChanged = true;
		shortestPath->setRenderTarget();
		glClearColor(0,0,0,0);
		glClear(GL_COLOR_BUFFER_BIT);

		searchShader->enable();
		searchShader->bindUniformTexture("inputTex1", dataBuffer->getColorBuffer(0), 0);
		searchShader->bindUniformTexture("inputTex2", shortestPath->getColorBuffer(0), 1);

		recursion(startX, startY, 0, 5);

		searchShader->disable();
		shortestPath->disableRenderTarget();
		startPointChanged = false;
	}

	if(endpointChanged)
	{
		visualizeTex->setRenderTarget();

		visualizeShader->enable();
		visualizeShader->bindUniformTexture("inputTex", dataBuffer->getColorBuffer(0),0);
		fullscreenQuad->render(visualizeShader);
		visualizeShader->disable();

		walkPathShader->enable();
		walkPathShader->bindUniformTexture("inputTex1", shortestPath->getColorBuffer(0), 0);
		recursion(endX, endY, 0, 5);
		walkPathShader->disable();

		glBegin(GL_POINTS);
		glColor3f(0,0,1);
		glVertex3f((float)(startX * 2 + 1) / (float)(2 * labyrinthSize) * 2.0f - 1.0f,
					(float)(startY  * 2 + 1) / (float)(2 * labyrinthSize) * 2.0f - 1.0f,
					0);
		glColor3f(0,1,0);
		glVertex3f((float)(endX * 2 + 1) / (float)(2 * labyrinthSize) * 2.0f - 1.0f,
					(float)(endY  * 2 + 1) / (float)(2 * labyrinthSize) * 2.0f - 1.0f,
					0);
		glEnd();

		visualizeTex->disableRenderTarget();

		endpointChanged = false;
	}

	glViewport(0,0,windowWidth, windowHeight);
	simpleShader->enable();
	simpleShader->bindUniformTexture("inputTex", visualizeTex->getColorBuffer(0),0);
	fullscreenQuad->render(simpleShader);
	simpleShader->disable();

	glutSwapBuffers();
}
OculusManager& OculusManager::getOculusManager()
{

	static OculusManager* oculusManager = NULL;

	if (oculusManager == NULL)
	{
		oculusManager = new OculusManager();
		if (!ovr_Initialize()) {
			fprintf(stderr, "Failed to initialize the Oculus SDK");
		}

		//= *OculusManager::getHmd();

		g_Hmd = ovrHmd_Create(0);
		if (!g_Hmd)
		{
			printf("No Oculus Rift device attached, using virtual version...\n");
			g_Hmd = ovrHmd_CreateDebug(ovrHmd_DK2);
		}
		printf("initialized HMD: %s - %s\n", g_Hmd->Manufacturer, g_Hmd->ProductName);

		if (!glfwInit()) exit(EXIT_FAILURE);

		if (l_MultiSampling) glfwWindowHint(GLFW_SAMPLES, 4); else glfwWindowHint(GLFW_SAMPLES, 0);

		bool l_DirectMode = ((g_Hmd->HmdCaps & ovrHmdCap_ExtendDesktop) == 0);

		GLFWmonitor* l_Monitor;
		ovrSizei l_ClientSize;
		if (l_DirectMode)
		{
			printf("Running in \"Direct\" mode...\n");
			l_Monitor = NULL;

			l_ClientSize.w = g_Hmd->Resolution.w / 2; // Something reasonable, smaller, but maintain aspect ratio...
			l_ClientSize.h = g_Hmd->Resolution.h / 2; // Something reasonable, smaller, but maintain aspect ratio...
		}
		else // Extended Desktop mode...
		{
			printf("Running in \"Extended Desktop\" mode...\n");
			int l_Count;
			GLFWmonitor** l_Monitors = glfwGetMonitors(&l_Count);
			switch (l_Count)
			{
			case 0:
				printf("No monitors found, exiting...\n");
				exit(EXIT_FAILURE);
				break;
			case 1:
				printf("Two monitors expected, found only one, using primary...\n");
				l_Monitor = glfwGetPrimaryMonitor();
				break;
			case 2:
				printf("Two monitors found, using second monitor...\n");
				l_Monitor = l_Monitors[1];
				break;
			default:
				printf("More than two monitors found, using second monitor...\n");
				l_Monitor = l_Monitors[1];
			}

			l_ClientSize.w = g_Hmd->Resolution.w; // 1920 for DK2...
			l_ClientSize.h = g_Hmd->Resolution.h; // 1080 for DK2...
		}

		l_Window = glfwCreateWindow(l_ClientSize.w, l_ClientSize.h, "GLFW Oculus Rift Test", l_Monitor, NULL);

		if (!l_Window)
		{
			glfwTerminate();
			exit(EXIT_FAILURE);
		}

#if defined(_WIN32)
		if (l_DirectMode)
		{
			ovrBool l_AttachResult = ovrHmd_AttachToWindow(g_Hmd, glfwGetWin32Window(l_Window), NULL, NULL);
			if (!l_AttachResult)
			{
				printf("Could not attach to window...");
				exit(EXIT_FAILURE);
			}
		}
#endif

		glfwMakeContextCurrent(l_Window);

		glewExperimental = GL_TRUE;
		GLenum l_GlewResult = glewInit();
		if (l_GlewResult != GLEW_OK)
		{
			printf("glewInit() error.\n");
			exit(EXIT_FAILURE);
		}

		int l_Major = glfwGetWindowAttrib(l_Window, GLFW_CONTEXT_VERSION_MAJOR);
		int l_Minor = glfwGetWindowAttrib(l_Window, GLFW_CONTEXT_VERSION_MINOR);
		int l_Profile = glfwGetWindowAttrib(l_Window, GLFW_OPENGL_PROFILE);
		printf("OpenGL: %d.%d ", l_Major, l_Minor);
		if (l_Major >= 3) // Profiles introduced in OpenGL 3.0...
		{
			if (l_Profile == GLFW_OPENGL_COMPAT_PROFILE) printf("GLFW_OPENGL_COMPAT_PROFILE\n"); else printf("GLFW_OPENGL_CORE_PROFILE\n");
		}
		printf("Vendor: %s\n", (char*)glGetString(GL_VENDOR));
		printf("Renderer: %s\n", (char*)glGetString(GL_RENDERER));

		ovrSizei l_EyeTextureSizes[2];

		l_EyeTextureSizes[ovrEye_Left] = ovrHmd_GetFovTextureSize(g_Hmd, ovrEye_Left, g_Hmd->MaxEyeFov[ovrEye_Left], 1.0f);
		l_EyeTextureSizes[ovrEye_Right] = ovrHmd_GetFovTextureSize(g_Hmd, ovrEye_Right, g_Hmd->MaxEyeFov[ovrEye_Right], 1.0f);

		// Combine for one texture for both eyes...
		g_RenderTargetSize.w = l_EyeTextureSizes[ovrEye_Left].w + l_EyeTextureSizes[ovrEye_Right].w;
		g_RenderTargetSize.h = (l_EyeTextureSizes[ovrEye_Left].h > l_EyeTextureSizes[ovrEye_Right].h ? l_EyeTextureSizes[ovrEye_Left].h : l_EyeTextureSizes[ovrEye_Right].h);

		// Create the FBO being a single one for both eyes (this is open for debate)...
		glGenFramebuffers(1, &l_FBOId);
		glBindFramebuffer(GL_FRAMEBUFFER, l_FBOId);

		// The texture we're going to render to...
		glGenTextures(1, &l_TextureId);
		// "Bind" the newly created texture : all future texture functions will modify this texture...
		glBindTexture(GL_TEXTURE_2D, l_TextureId);
		// Give an empty image to OpenGL (the last "0")
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, g_RenderTargetSize.w, g_RenderTargetSize.h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
		// Linear filtering...
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

		// Create Depth Buffer...
		glGenRenderbuffers(1, &l_DepthBufferId);
		glBindRenderbuffer(GL_RENDERBUFFER, l_DepthBufferId);
		glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, g_RenderTargetSize.w, g_RenderTargetSize.h);
		glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, l_DepthBufferId);

		// Set the texture as our colour attachment #0...
		glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, l_TextureId, 0);

		// Set the list of draw buffers...
		GLenum l_GLDrawBuffers[1] = { GL_COLOR_ATTACHMENT0 };
		glDrawBuffers(1, l_GLDrawBuffers); // "1" is the size of DrawBuffers

		// Check if everything is OK...
		GLenum l_Check = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER);
		if (l_Check != GL_FRAMEBUFFER_COMPLETE)
		{
			printf("There is a problem with the FBO.\n");
			exit(EXIT_FAILURE);
		}

		// Unbind...
		glBindRenderbuffer(GL_RENDERBUFFER, 0);
		glBindTexture(GL_TEXTURE_2D, 0);
		glBindFramebuffer(GL_FRAMEBUFFER, 0);

		// Setup textures for each eye...

		// Left eye...
		g_EyeTextures[ovrEye_Left].Header.API = ovrRenderAPI_OpenGL;
		g_EyeTextures[ovrEye_Left].Header.TextureSize = g_RenderTargetSize;
		g_EyeTextures[ovrEye_Left].Header.RenderViewport.Pos.x = 0;
		g_EyeTextures[ovrEye_Left].Header.RenderViewport.Pos.y = 0;
		g_EyeTextures[ovrEye_Left].Header.RenderViewport.Size = l_EyeTextureSizes[ovrEye_Left];
		((ovrGLTexture&)(g_EyeTextures[ovrEye_Left])).OGL.TexId = l_TextureId;

		// Right eye (mostly the same as left but with the viewport on the right side of the texture)...
		g_EyeTextures[ovrEye_Right] = g_EyeTextures[ovrEye_Left];
		g_EyeTextures[ovrEye_Right].Header.RenderViewport.Pos.x = (g_RenderTargetSize.w + 1) / 2;
		g_EyeTextures[ovrEye_Right].Header.RenderViewport.Pos.y = 0;

		// Oculus Rift eye configurations...
		g_Cfg.OGL.Header.API = ovrRenderAPI_OpenGL;
		g_Cfg.OGL.Header.RTSize.w = l_ClientSize.w;
		g_Cfg.OGL.Header.RTSize.h = l_ClientSize.h;
		g_Cfg.OGL.Header.Multisample = (l_MultiSampling ? 1 : 0);
#if defined(_WIN32)
		g_Cfg.OGL.Window = glfwGetWin32Window(l_Window);
		g_Cfg.OGL.DC = GetDC(g_Cfg.OGL.Window);
#elif defined(__linux__)
		l_Cfg.OGL.Win = glfwGetX11Window(l_Window);
		l_Cfg.OGL.Disp = glfwGetX11Display();
#endif

		// Enable capabilities...
		// ovrHmd_SetEnabledCaps(g_Hmd, ovrHmdCap_LowPersistence | ovrHmdCap_DynamicPrediction);

		ovrBool l_ConfigureResult = ovrHmd_ConfigureRendering(g_Hmd, &g_Cfg.Config, g_DistortionCaps, g_Hmd->MaxEyeFov, g_EyeRenderDesc);
		glUseProgram(0); // Avoid OpenGL state leak in ovrHmd_ConfigureRendering...
		if (!l_ConfigureResult)
		{
			printf("Configure failed.\n");
			exit(EXIT_FAILURE);
		}

		// Start the sensor which provides the Rift’s pose and motion...
		uint32_t l_SupportedSensorCaps = ovrTrackingCap_Orientation | ovrTrackingCap_MagYawCorrection | ovrTrackingCap_Position;
		uint32_t l_RequiredTrackingCaps = 0;
		ovrBool l_TrackingResult = ovrHmd_ConfigureTracking(g_Hmd, l_SupportedSensorCaps, l_RequiredTrackingCaps);
		if (!l_TrackingResult)
		{
			printf("Could not start tracking...");
			exit(EXIT_FAILURE);
		}

		// Projection matrici for each eye will not change at runtime, we can set them here...
		g_ProjectionMatrici[ovrEye_Left] = ovrMatrix4f_Projection(g_EyeRenderDesc[ovrEye_Left].Fov, 0.3f, 100.0f, true);
		g_ProjectionMatrici[ovrEye_Right] = ovrMatrix4f_Projection(g_EyeRenderDesc[ovrEye_Right].Fov, 0.3f, 100.0f, true);

		// IPD offset values will not change at runtime, we can set them here...
		g_EyeOffsets[ovrEye_Left] = g_EyeRenderDesc[ovrEye_Left].HmdToEyeViewOffset;
		g_EyeOffsets[ovrEye_Right] = g_EyeRenderDesc[ovrEye_Right].HmdToEyeViewOffset;

		ovrHmd_RecenterPose(g_Hmd);


		return *oculusManager;
	}
}
void OpenglES3Device::drawFrameBufferToBackBuffer(){
	GLenum drawBuffers[] = { GL_NONE, GL_BACK };
	glDrawBuffers(2, drawBuffers);
	this->evaluateErrorsAndLogOnlyInDebugMode("drawFrameBufferToBackBuffer");
}
void GBuffer::BindForGeomPass()
{
    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo);
    GLenum DrawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 };
    glDrawBuffers(ARRAY_SIZE_IN_ELEMENTS(DrawBuffers), DrawBuffers);
}
void GLWidget3D::render() {
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glMatrixMode(GL_MODELVIEW);

	////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// PASS 1: Render to texture
	glUseProgram(renderManager.programs["pass1"]);

	glBindFramebuffer(GL_FRAMEBUFFER, renderManager.fragDataFB);
	glClearColor(0.95, 0.95, 0.95, 1);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, renderManager.fragDataTex[0], 0);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, renderManager.fragDataTex[1], 0);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, renderManager.fragDataTex[2], 0);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, GL_TEXTURE_2D, renderManager.fragDataTex[3], 0);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, renderManager.fragDepthTex, 0);

	// Set the list of draw buffers.
	GLenum DrawBuffers[4] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 };
	glDrawBuffers(4, DrawBuffers); // "3" is the size of DrawBuffers
	// Always check that our framebuffer is ok
	if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
		printf("+ERROR: GL_FRAMEBUFFER_COMPLETE false\n");
		exit(0);
	}

	glUniformMatrix4fv(glGetUniformLocation(renderManager.programs["pass1"], "mvpMatrix"), 1, false, &camera.mvpMatrix[0][0]);
	glUniform3f(glGetUniformLocation(renderManager.programs["pass1"], "lightDir"), light_dir.x, light_dir.y, light_dir.z);
	glUniformMatrix4fv(glGetUniformLocation(renderManager.programs["pass1"], "light_mvpMatrix"), 1, false, &light_mvpMatrix[0][0]);

	glUniform1i(glGetUniformLocation(renderManager.programs["pass1"], "shadowMap"), 6);
	glActiveTexture(GL_TEXTURE6);
	glBindTexture(GL_TEXTURE_2D, renderManager.shadow.textureDepth);

	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);
	drawScene();

	////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// PASS 2: Create AO
	if (renderManager.renderingMode == RenderManager::RENDERING_MODE_SSAO) {
		glUseProgram(renderManager.programs["ssao"]);
		glBindFramebuffer(GL_FRAMEBUFFER, renderManager.fragDataFB_AO);

		glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, renderManager.fragAOTex, 0);
		glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, renderManager.fragDepthTex_AO, 0);
		GLenum DrawBuffers[1] = { GL_COLOR_ATTACHMENT0 };
		glDrawBuffers(1, DrawBuffers); // "1" is the size of DrawBuffers

		glClearColor(1, 1, 1, 1);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		// Always check that our framebuffer is ok
		if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
			printf("++ERROR: GL_FRAMEBUFFER_COMPLETE false\n");
			exit(0);
		}

		glDisable(GL_DEPTH_TEST);
		glDepthFunc(GL_ALWAYS);

		glUniform2f(glGetUniformLocation(renderManager.programs["ssao"], "pixelSize"), 2.0f / this->width(), 2.0f / this->height());

		glUniform1i(glGetUniformLocation(renderManager.programs["ssao"], "tex0"), 1);
		glActiveTexture(GL_TEXTURE1);
		glBindTexture(GL_TEXTURE_2D, renderManager.fragDataTex[0]);

		glUniform1i(glGetUniformLocation(renderManager.programs["ssao"], "tex1"), 2);
		glActiveTexture(GL_TEXTURE2);
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, renderManager.fragDataTex[1]);

		glUniform1i(glGetUniformLocation(renderManager.programs["ssao"], "tex2"), 3);
		glActiveTexture(GL_TEXTURE3);
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, renderManager.fragDataTex[2]);

		glUniform1i(glGetUniformLocation(renderManager.programs["ssao"], "depthTex"), 8);
		glActiveTexture(GL_TEXTURE8);
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, renderManager.fragDepthTex);

		glUniform1i(glGetUniformLocation(renderManager.programs["ssao"], "noiseTex"), 7);
		glActiveTexture(GL_TEXTURE7);
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, renderManager.fragNoiseTex);

		{
			glUniformMatrix4fv(glGetUniformLocation(renderManager.programs["ssao"], "mvpMatrix"), 1, false, &camera.mvpMatrix[0][0]);
			glUniformMatrix4fv(glGetUniformLocation(renderManager.programs["ssao"], "pMatrix"), 1, false, &camera.pMatrix[0][0]);
		}

		glUniform1i(glGetUniformLocation(renderManager.programs["ssao"], "uKernelSize"), renderManager.uKernelSize);
		glUniform3fv(glGetUniformLocation(renderManager.programs["ssao"], "uKernelOffsets"), renderManager.uKernelOffsets.size(), (const GLfloat*)renderManager.uKernelOffsets.data());

		glUniform1f(glGetUniformLocation(renderManager.programs["ssao"], "uPower"), renderManager.uPower);
		glUniform1f(glGetUniformLocation(renderManager.programs["ssao"], "uRadius"), renderManager.uRadius);

		glBindVertexArray(renderManager.secondPassVAO);

		glDrawArrays(GL_QUADS, 0, 4);
		glBindVertexArray(0);
		glDepthFunc(GL_LEQUAL);
	}
	else if (renderManager.renderingMode == RenderManager::RENDERING_MODE_LINE || renderManager.renderingMode == RenderManager::RENDERING_MODE_HATCHING) {
		glUseProgram(renderManager.programs["line"]);

		glBindFramebuffer(GL_FRAMEBUFFER, 0);
		glClearColor(1, 1, 1, 1);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		glDisable(GL_DEPTH_TEST);
		glDepthFunc(GL_ALWAYS);

		glUniform2f(glGetUniformLocation(renderManager.programs["line"], "pixelSize"), 1.0f / this->width(), 1.0f / this->height());
		glUniformMatrix4fv(glGetUniformLocation(renderManager.programs["line"], "pMatrix"), 1, false, &camera.pMatrix[0][0]);
		if (renderManager.renderingMode == RenderManager::RENDERING_MODE_LINE) {
			glUniform1i(glGetUniformLocation(renderManager.programs["line"], "useHatching"), 0);
		}
		else {
			glUniform1i(glGetUniformLocation(renderManager.programs["line"], "useHatching"), 1);
		}

		glUniform1i(glGetUniformLocation(renderManager.programs["line"], "tex0"), 1);
		glActiveTexture(GL_TEXTURE1);
		glBindTexture(GL_TEXTURE_2D, renderManager.fragDataTex[0]);

		glUniform1i(glGetUniformLocation(renderManager.programs["line"], "tex1"), 2);
		glActiveTexture(GL_TEXTURE2);
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, renderManager.fragDataTex[1]);

		glUniform1i(glGetUniformLocation(renderManager.programs["line"], "tex2"), 3);
		glActiveTexture(GL_TEXTURE3);
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, renderManager.fragDataTex[2]);

		glUniform1i(glGetUniformLocation(renderManager.programs["line"], "tex3"), 4);
		glActiveTexture(GL_TEXTURE4);
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, renderManager.fragDataTex[3]);

		glUniform1i(glGetUniformLocation(renderManager.programs["line"], "depthTex"), 8);
		glActiveTexture(GL_TEXTURE8);
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, renderManager.fragDepthTex);

		glUniform1i(glGetUniformLocation(renderManager.programs["line"], "hatchingTexture"), 5);
		glActiveTexture(GL_TEXTURE5);
		glBindTexture(GL_TEXTURE_3D, renderManager.hatchingTextures);
		glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

		glBindVertexArray(renderManager.secondPassVAO);

		glDrawArrays(GL_QUADS, 0, 4);
		glBindVertexArray(0);
		glDepthFunc(GL_LEQUAL);
	}

	////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// Blur

	if (renderManager.renderingMode != RenderManager::RENDERING_MODE_LINE && renderManager.renderingMode != RenderManager::RENDERING_MODE_HATCHING) {
		glBindFramebuffer(GL_FRAMEBUFFER, 0);
		qglClearColor(QColor(0xFF, 0xFF, 0xFF));
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		glDisable(GL_DEPTH_TEST);
		glDepthFunc(GL_ALWAYS);

		glUseProgram(renderManager.programs["blur"]);
		glUniform2f(glGetUniformLocation(renderManager.programs["blur"], "pixelSize"), 2.0f / this->width(), 2.0f / this->height());
		//printf("pixelSize loc %d\n", glGetUniformLocation(vboRenderManager.programs["blur"], "pixelSize"));

		glUniform1i(glGetUniformLocation(renderManager.programs["blur"], "tex0"), 1);//COLOR
		glActiveTexture(GL_TEXTURE1);
		glBindTexture(GL_TEXTURE_2D, renderManager.fragDataTex[0]);

		glUniform1i(glGetUniformLocation(renderManager.programs["blur"], "tex1"), 2);//NORMAL
		glActiveTexture(GL_TEXTURE2);
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, renderManager.fragDataTex[1]);

		/*glUniform1i(glGetUniformLocation(renderManager.programs["blur"], "tex2"), 3);
		glActiveTexture(GL_TEXTURE3);
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, renderManager.fragDataTex[2]);*/

		glUniform1i(glGetUniformLocation(renderManager.programs["blur"], "depthTex"), 8);
		glActiveTexture(GL_TEXTURE8);
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, renderManager.fragDepthTex);

		glUniform1i(glGetUniformLocation(renderManager.programs["blur"], "tex3"), 4);//AO
		glActiveTexture(GL_TEXTURE4);
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, renderManager.fragAOTex);

		if (renderManager.renderingMode == RenderManager::RENDERING_MODE_SSAO) {
			glUniform1i(glGetUniformLocation(renderManager.programs["blur"], "ssao_used"), 1); // ssao used
		}
		else {
			glUniform1i(glGetUniformLocation(renderManager.programs["blur"], "ssao_used"), 0); // no ssao
		}

		glBindVertexArray(renderManager.secondPassVAO);

		glDrawArrays(GL_QUADS, 0, 4);
		glBindVertexArray(0);
		glDepthFunc(GL_LEQUAL);

	}

	// REMOVE
	glActiveTexture(GL_TEXTURE0);
}
Exemple #11
0
void GLGSRender::ExecCMD()
{
	//return;
	if(!LoadProgram())
	{
		ConLog.Error("LoadProgram failed.");
		Emu.Pause();
		return;
	}

	if(!m_fbo.IsCreated() || RSXThread::m_width != last_width || RSXThread::m_height != last_height || last_depth_format != m_surface_depth_format)
	{
		ConLog.Warning("New FBO (%dx%d)", RSXThread::m_width, RSXThread::m_height);
		last_width = RSXThread::m_width;
		last_height = RSXThread::m_height;
		last_depth_format = m_surface_depth_format;

		m_fbo.Create();
		checkForGlError("m_fbo.Create");
		m_fbo.Bind();

		m_rbo.Create(4 + 1);
		checkForGlError("m_rbo.Create");

		for(int i=0; i<4; ++i)
		{
			m_rbo.Bind(i);
			m_rbo.Storage(GL_RGBA, RSXThread::m_width, RSXThread::m_height);
			checkForGlError("m_rbo.Storage(GL_RGBA)");
		}

		m_rbo.Bind(4);

		switch(m_surface_depth_format)
		{
		case 1:
			m_rbo.Storage(GL_DEPTH_COMPONENT16, RSXThread::m_width, RSXThread::m_height);
			checkForGlError("m_rbo.Storage(GL_DEPTH_COMPONENT16)");
		break;

		case 2:
			m_rbo.Storage(GL_DEPTH24_STENCIL8, RSXThread::m_width, RSXThread::m_height);
			checkForGlError("m_rbo.Storage(GL_DEPTH24_STENCIL8)");
		break;

		default:
			ConLog.Error("Bad depth format! (%d)", m_surface_depth_format);
			assert(0);
		break;
		}

		for(int i=0; i<4; ++i)
		{
			m_fbo.Renderbuffer(GL_COLOR_ATTACHMENT0 + i, m_rbo.GetId(i));
			checkForGlError(wxString::Format("m_fbo.Renderbuffer(GL_COLOR_ATTACHMENT%d)", i));
		}

		m_fbo.Renderbuffer(GL_DEPTH_ATTACHMENT, m_rbo.GetId(4));
		checkForGlError("m_fbo.Renderbuffer(GL_DEPTH_ATTACHMENT)");

		if(m_surface_depth_format == 2)
		{
			m_fbo.Renderbuffer(GL_STENCIL_ATTACHMENT, m_rbo.GetId(4));
			checkForGlError("m_fbo.Renderbuffer(GL_STENCIL_ATTACHMENT)");
		}
	}

	if(!m_set_surface_clip_horizontal)
	{
		m_surface_clip_x = 0;
		m_surface_clip_w = RSXThread::m_width;
	}

	if(!m_set_surface_clip_vertical)
	{
		m_surface_clip_y = 0;
		m_surface_clip_h = RSXThread::m_height;
	}
		
	m_fbo.Bind();
	if(Ini.GSDumpDepthBuffer.GetValue())
		WriteDepthBuffer();
	static const GLenum draw_buffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 };

	switch(m_surface_colour_target)
	{
	case 0x0:
		break;

	case 0x1:
		glDrawBuffer(draw_buffers[0]);
	break;

	case 0x2:
		glDrawBuffer(draw_buffers[1]);
	break;

	case 0x13:
		glDrawBuffers(2, draw_buffers);
	break;

	case 0x17:
		glDrawBuffers(3, draw_buffers);
	break;

	case 0x1f:
		glDrawBuffers(4, draw_buffers);
	break;

	default:
		ConLog.Error("Bad surface colour target: %d", m_surface_colour_target);
	break;
	}

	if(m_set_color_mask)
	{
		glColorMask(m_color_mask_r, m_color_mask_g, m_color_mask_b, m_color_mask_a);
		checkForGlError("glColorMask");
	}

	if(m_set_viewport_horizontal && m_set_viewport_vertical)
	{
		glViewport(m_viewport_x, RSXThread::m_height-m_viewport_y-m_viewport_h, m_viewport_w, m_viewport_h);
		checkForGlError("glViewport");
	}

	if(m_set_scissor_horizontal && m_set_scissor_vertical)
	{
		glScissor(m_scissor_x, RSXThread::m_height-m_scissor_y-m_scissor_h, m_scissor_w, m_scissor_h);
		checkForGlError("glScissor");
	}

	if(m_clear_surface_mask)
	{
		GLbitfield f = 0;

		if (m_clear_surface_mask & 0x1)
		{
			glClearDepth(m_clear_surface_z / (float)0xffffff);

			f |= GL_DEPTH_BUFFER_BIT;
		}

		if (m_clear_surface_mask & 0x2)
		{
			glClearStencil(m_clear_surface_s);

			f |= GL_STENCIL_BUFFER_BIT;
		}

		if (m_clear_surface_mask & 0xF0)
		{
			glClearColor(
				m_clear_surface_color_r / 255.0f,
				m_clear_surface_color_g / 255.0f,
				m_clear_surface_color_b / 255.0f,
				m_clear_surface_color_a / 255.0f);

			f |= GL_COLOR_BUFFER_BIT;
		}

		glClear(f);
	}

	if(m_set_front_polygon_mode)
	{
		glPolygonMode(GL_FRONT, m_front_polygon_mode);
		checkForGlError("glPolygonMode");
	}

	Enable(m_depth_test_enable, GL_DEPTH_TEST);
	Enable(m_set_alpha_test, GL_ALPHA_TEST);
	Enable(m_set_depth_bounds_test, GL_DEPTH_BOUNDS_TEST_EXT);
	Enable(m_set_blend, GL_BLEND);
	Enable(m_set_logic_op, GL_LOGIC_OP);
	Enable(m_set_cull_face_enable, GL_CULL_FACE);
	Enable(m_set_dither, GL_DITHER);
	Enable(m_set_stencil_test, GL_STENCIL_TEST);
	Enable(m_set_line_smooth, GL_LINE_SMOOTH);
	Enable(m_set_poly_smooth, GL_POLYGON_SMOOTH);
	Enable(m_set_poly_offset_fill, GL_POLYGON_OFFSET_FILL);
	Enable(m_set_poly_offset_line, GL_POLYGON_OFFSET_LINE);
	Enable(m_set_poly_offset_point, GL_POLYGON_OFFSET_POINT);
	//Enable(m_set_restart_index, GL_PRIMITIVE_RESTART); //Requires OpenGL 3.1+

	if(m_set_clip_plane)
	{
		Enable(m_clip_plane_0, GL_CLIP_PLANE0);
		Enable(m_clip_plane_1, GL_CLIP_PLANE1);
		Enable(m_clip_plane_2, GL_CLIP_PLANE2);
		Enable(m_clip_plane_3, GL_CLIP_PLANE3);
		Enable(m_clip_plane_4, GL_CLIP_PLANE4);
		Enable(m_clip_plane_5, GL_CLIP_PLANE5);

		checkForGlError("m_set_clip_plane");
	}

	checkForGlError("glEnable");

	if(m_set_two_sided_stencil_test_enable)
	{
		if(m_set_stencil_fail && m_set_stencil_zfail && m_set_stencil_zpass)
		{
			glStencilOpSeparate(GL_FRONT, m_stencil_fail, m_stencil_zfail, m_stencil_zpass);
			checkForGlError("glStencilOpSeparate");
		}

		if(m_set_stencil_mask)
		{
			glStencilMaskSeparate(GL_FRONT, m_stencil_mask);
			checkForGlError("glStencilMaskSeparate");
		}

		if(m_set_stencil_func && m_set_stencil_func_ref && m_set_stencil_func_mask)
		{
			glStencilFuncSeparate(GL_FRONT, m_stencil_func, m_stencil_func_ref, m_stencil_func_mask);
			checkForGlError("glStencilFuncSeparate");
		}

		if(m_set_back_stencil_fail && m_set_back_stencil_zfail && m_set_back_stencil_zpass)
		{
			glStencilOpSeparate(GL_BACK, m_back_stencil_fail, m_back_stencil_zfail, m_back_stencil_zpass);
			checkForGlError("glStencilOpSeparate(GL_BACK)");
		}

		if(m_set_back_stencil_mask)
		{
			glStencilMaskSeparate(GL_BACK, m_back_stencil_mask);
			checkForGlError("glStencilMaskSeparate(GL_BACK)");
		}

		if(m_set_back_stencil_func && m_set_back_stencil_func_ref && m_set_back_stencil_func_mask)
		{
			glStencilFuncSeparate(GL_BACK, m_back_stencil_func, m_back_stencil_func_ref, m_back_stencil_func_mask);
			checkForGlError("glStencilFuncSeparate(GL_BACK)");
		}
	}
	else
	{
		if(m_set_stencil_fail && m_set_stencil_zfail && m_set_stencil_zpass)
		{
			glStencilOp(m_stencil_fail, m_stencil_zfail, m_stencil_zpass);
			checkForGlError("glStencilOp");
		}

		if(m_set_stencil_mask)
		{
			glStencilMask(m_stencil_mask);
			checkForGlError("glStencilMask");
		}

		if(m_set_stencil_func && m_set_stencil_func_ref && m_set_stencil_func_mask)
		{
			glStencilFunc(m_stencil_func, m_stencil_func_ref, m_stencil_func_mask);
			checkForGlError("glStencilFunc");
		}
	}

	if(m_set_shade_mode)
	{
		glShadeModel(m_shade_mode);
		checkForGlError("glShadeModel");
	}

	if(m_set_depth_mask)
	{
		glDepthMask(m_depth_mask);
		checkForGlError("glDepthMask");
	}

	if(m_set_depth_func)
	{
		glDepthFunc(m_depth_func);
		//ConLog.Warning("glDepthFunc(0x%x)", m_depth_func);
		checkForGlError("glDepthFunc");
	}

	if(m_set_depth_bounds)
	{
		//ConLog.Warning("glDepthBounds(%f, %f)", m_depth_bounds_min, m_depth_bounds_max);
		glDepthBounds(m_depth_bounds_min, m_depth_bounds_max);
		checkForGlError("glDepthBounds");
	}

	if(m_set_clip)
	{
		//ConLog.Warning("glDepthRangef(%f, %f)", m_clip_min, m_clip_max);
		glDepthRangef(m_clip_min, m_clip_max);
		checkForGlError("glDepthRangef");
	}

	if(m_set_line_width)
	{
		glLineWidth(m_line_width / 255.f);
		checkForGlError("glLineWidth");
	}

	if(m_set_blend_equation)
	{
		glBlendEquationSeparate(m_blend_equation_rgb, m_blend_equation_alpha);
		checkForGlError("glBlendEquationSeparate");
	}

	if(m_set_blend_sfactor && m_set_blend_dfactor)
	{
		glBlendFuncSeparate(m_blend_sfactor_rgb, m_blend_dfactor_rgb, m_blend_sfactor_alpha, m_blend_dfactor_alpha);
		checkForGlError("glBlendFuncSeparate");
	}

	if(m_set_blend_color)
	{
		glBlendColor(m_blend_color_r, m_blend_color_g, m_blend_color_b, m_blend_color_a);
		checkForGlError("glBlendColor");
	}

	if(m_set_cull_face)
	{
		glCullFace(m_cull_face);
		checkForGlError("glCullFace");
	}

	if(m_set_alpha_func && m_set_alpha_ref)
	{
		glAlphaFunc(m_alpha_func, m_alpha_ref);
		checkForGlError("glAlphaFunc");
	}

	if(m_set_fog_mode)
	{
		glFogi(GL_FOG_MODE, m_fog_mode);
		checkForGlError("glFogi(GL_FOG_MODE)");
	}

	if(m_set_fog_params)
	{
		glFogf(GL_FOG_START, m_fog_param0);
		checkForGlError("glFogf(GL_FOG_START)");
		glFogf(GL_FOG_END, m_fog_param1);
		checkForGlError("glFogf(GL_FOG_END)");
	}

	if(m_set_restart_index)
	{
		ConLog.Warning("m_set_restart_index requires glPrimitiveRestartIndex()");
		//glPrimitiveRestartIndex(m_restart_index); //Requires OpenGL 3.1+
		//checkForGlError("glPrimitiveRestartIndex");
	}

	if(m_indexed_array.m_count && m_draw_array_count)
	{
		ConLog.Warning("m_indexed_array.m_count && draw_array_count");
	}

	for(u32 i=0; i<m_textures_count; ++i)
	{
		if(!m_textures[i].IsEnabled()) continue;

		glActiveTexture(GL_TEXTURE0 + i);
		checkForGlError("glActiveTexture");
		m_gl_textures[i].Create();
		m_gl_textures[i].Bind();
		checkForGlError(wxString::Format("m_gl_textures[%d].Bind", i));
		m_program.SetTex(i);
		m_gl_textures[i].Init(m_textures[i]);
		checkForGlError(wxString::Format("m_gl_textures[%d].Init", i));
	}

	m_vao.Bind();
	if(m_indexed_array.m_count)
	{
		LoadVertexData(m_indexed_array.index_min, m_indexed_array.index_max - m_indexed_array.index_min + 1);
	}

	EnableVertexData(m_indexed_array.m_count ? true : false);

	InitVertexData();
	InitFragmentData();

	if(m_indexed_array.m_count)
	{
		switch(m_indexed_array.m_type)
		{
		case 0:
			glDrawElements(m_draw_mode - 1, m_indexed_array.m_count, GL_UNSIGNED_INT, nullptr);
			checkForGlError("glDrawElements #4");
		break;

		case 1:
			glDrawElements(m_draw_mode - 1, m_indexed_array.m_count, GL_UNSIGNED_SHORT, nullptr);
			checkForGlError("glDrawElements #2");
		break;

		default:
			ConLog.Error("Bad indexed array type (%d)", m_indexed_array.m_type);
		break;
		}

		DisableVertexData();
		m_indexed_array.Reset();
	}

	if(m_draw_array_count)
	{
		//ConLog.Warning("glDrawArrays(%d,%d,%d)", m_draw_mode - 1, m_draw_array_first, m_draw_array_count);
		glDrawArrays(m_draw_mode - 1, 0, m_draw_array_count);
		checkForGlError("glDrawArrays");
		DisableVertexData();
	}

	if(Ini.GSDumpColorBuffers.GetValue())
		WriteBuffers();
}
void raytracer_app::render(double currentTime)
{
    static const GLfloat zeros[] = { 0.0f, 0.0f, 0.0f, 0.0f };
    static const GLfloat gray[] = { 0.1f, 0.1f, 0.1f, 0.0f };
    static const GLfloat ones[] = { 1.0f };
    static double last_time = 0.0;
    static double total_time = 0.0;

    if (!paused)
        total_time += (currentTime - last_time);
    last_time = currentTime;

    float f = (float)total_time;

    vmath::vec3 view_position = vmath::vec3(sinf(f * 0.3234f) * 28.0f, cosf(f * 0.4234f) * 28.0f, cosf(f * 0.1234f) * 28.0f); // sinf(f * 0.2341f) * 20.0f - 8.0f);
    vmath::vec3 lookat_point = vmath::vec3(sinf(f * 0.214f) * 8.0f, cosf(f * 0.153f) * 8.0f, sinf(f * 0.734f) * 8.0f);
    vmath::mat4 view_matrix = vmath::lookat(view_position,
                                            lookat_point,
                                            vmath::vec3(0.0f, 1.0f, 0.0f));

    glBindBufferBase(GL_UNIFORM_BUFFER, 0, uniforms_buffer);
    uniforms_block * block = (uniforms_block *)glMapBufferRange(GL_UNIFORM_BUFFER,
                                                                0,
                                                                sizeof(uniforms_block),
                                                                GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT);

    vmath::mat4 model_matrix = vmath::scale(7.0f);

    // f = 0.0f;

    block->mv_matrix = view_matrix * model_matrix;
    block->view_matrix = view_matrix;
    block->proj_matrix = vmath::perspective(50.0f,
                                            (float)info.windowWidth / (float)info.windowHeight,
                                            0.1f,
                                            1000.0f);

    glUnmapBuffer(GL_UNIFORM_BUFFER);

    glBindBufferBase(GL_UNIFORM_BUFFER, 1, sphere_buffer);
    sphere * s = (sphere *)glMapBufferRange(GL_UNIFORM_BUFFER, 0, 128 * sizeof(sphere), GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT);

    int i;

    for (i = 0; i < 128; i++)
    {
        // float f = 0.0f;
        float fi = (float)i / 128.0f;
        s[i].center = vmath::vec3(sinf(fi * 123.0f + f) * 15.75f, cosf(fi * 456.0f + f) * 15.75f, (sinf(fi * 300.0f + f) * cosf(fi * 200.0f + f)) * 20.0f);
        s[i].radius = fi * 2.3f + 3.5f;
        float r = fi * 61.0f;
        float g = r + 0.25f;
        float b = g + 0.25f;
        r = (r - floorf(r)) * 0.8f + 0.2f;
        g = (g - floorf(g)) * 0.8f + 0.2f;
        b = (b - floorf(b)) * 0.8f + 0.2f;
        s[i].color = vmath::vec4(r, g, b, 1.0f);
    }

    glUnmapBuffer(GL_UNIFORM_BUFFER);

    glBindBufferBase(GL_UNIFORM_BUFFER, 2, plane_buffer);
    plane * p = (plane *)glMapBufferRange(GL_UNIFORM_BUFFER, 0, 128 * sizeof(plane), GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT);

    //for (i = 0; i < 1; i++)
    {
        p[0].normal = vmath::vec3(0.0f, 0.0f, -1.0f);
        p[0].d = 30.0f;

        p[1].normal = vmath::vec3(0.0f, 0.0f, 1.0f);
        p[1].d = 30.0f;

        p[2].normal = vmath::vec3(-1.0f, 0.0f, 0.0f);
        p[2].d = 30.0f;

        p[3].normal = vmath::vec3(1.0f, 0.0f, 0.0f);
        p[3].d = 30.0f;

        p[4].normal = vmath::vec3(0.0f, -1.0f, 0.0f);
        p[4].d = 30.0f;

        p[5].normal = vmath::vec3(0.0f, 1.0f, 0.0f);
        p[5].d = 30.0f;
    }

    glUnmapBuffer(GL_UNIFORM_BUFFER);

    glBindBufferBase(GL_UNIFORM_BUFFER, 3, light_buffer);
    light * l = (light *)glMapBufferRange(GL_UNIFORM_BUFFER, 0, 128 * sizeof(light), GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT);

    f *= 1.0f;

    for (i = 0; i < 128; i++)
    {
        float fi = 3.33f - (float)i; //  / 35.0f;
        l[i].position = vmath::vec3(sinf(fi * 2.0f - f) * 15.75f,
                                    cosf(fi * 5.0f - f) * 5.75f,
                                    (sinf(fi * 3.0f - f) * cosf(fi * 2.5f - f)) * 19.4f);
    }

    glUnmapBuffer(GL_UNIFORM_BUFFER);

    glBindVertexArray(vao);
    glViewport(0, 0, info.windowWidth, info.windowHeight);

    glUseProgram(prepare_program);
    glUniformMatrix4fv(uniforms.ray_lookat, 1, GL_FALSE, view_matrix);
    glUniform3fv(uniforms.ray_origin, 1, view_position);
    glUniform1f(uniforms.aspect, (float)info.windowHeight / (float)info.windowWidth);
    glBindFramebuffer(GL_FRAMEBUFFER, ray_fbo[0]);
    static const GLenum draw_buffers[] =
    {
        GL_COLOR_ATTACHMENT0,
        GL_COLOR_ATTACHMENT1,
        GL_COLOR_ATTACHMENT2,
        GL_COLOR_ATTACHMENT3,
        GL_COLOR_ATTACHMENT4,
        GL_COLOR_ATTACHMENT5
    };
    glDrawBuffers(6, draw_buffers);

    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

    glUseProgram(trace_program);
    recurse(0);

    glUseProgram(blit_program);
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glDrawBuffer(GL_BACK);

    glActiveTexture(GL_TEXTURE0);
    switch (debug_mode)
    {
        case DEBUG_NONE:
            glBindTexture(GL_TEXTURE_2D, tex_composite);
            break;
        case DEBUG_REFLECTED:
            glBindTexture(GL_TEXTURE_2D, tex_reflected[debug_depth]);
            break;
        case DEBUG_REFRACTED:
            glBindTexture(GL_TEXTURE_2D, tex_refracted[debug_depth]);
            break;
        case DEBUG_REFLECTED_COLOR:
            glBindTexture(GL_TEXTURE_2D, tex_reflection_intensity[debug_depth]);
            break;
        case DEBUG_REFRACTED_COLOR:
            glBindTexture(GL_TEXTURE_2D, tex_refraction_intensity[debug_depth]);
            break;
    }
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

    /*
    glClearBufferfv(GL_COLOR, 0, gray);
    glClearBufferfv(GL_DEPTH, 0, ones);


    glBindVertexArray(vao);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    */
}
Exemple #13
0
int RFBufferGo( struct RFBuffer *rb, int width, int height, int texturecount, struct Texture ** textures, int do_clear )
{
	int i;
	static const GLenum buffers[8] = {   GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_COLOR_ATTACHMENT2_EXT,
			GL_COLOR_ATTACHMENT3_EXT, GL_COLOR_ATTACHMENT4_EXT, GL_COLOR_ATTACHMENT5_EXT,
			GL_COLOR_ATTACHMENT6_EXT, GL_COLOR_ATTACHMENT7_EXT };

	for( i = 0; i < texturecount; i++ )
	{
		struct Texture * t = textures[i];
		if( t->width != width || t->height != height )
		{
			MakeDynamicTexture2D( t, width, height, rb->mtt );
		}
	}

	RenderW = width;
	RenderH = height;

	rb->width = width;
	rb->height = height;
	rb->outextures = texturecount;

	if( rb->use_depth_buffer )
	{
		glBindRenderbuffer( GL_RENDERBUFFER, rb->renderbuffer );
		glRenderbufferStorage( GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, width, height );
	}

	glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, rb->outputbuffer );
	for( i = 0; i < texturecount; i++ )
	{
		struct Texture * t = textures[i];
		glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + i, 
			GL_TEXTURE_2D, t->texture, 0 );
	}

	if( rb->use_depth_buffer )
		glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, 
			GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, rb->renderbuffer );

	glDrawBuffers( texturecount, buffers );
	glViewport( 0, 0, width, height );

	//Check to see if there were any errors with the framebuffer
	switch( (GLenum)glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) )
	{
		case GL_FRAMEBUFFER_COMPLETE_EXT: break;  //GOOD!
		case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT:
			fprintf( stderr, "OpenGL Framebuffer error: GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT\n");
			return -1;
		case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
			fprintf( stderr, "OpenGL Framebuffer error: GL_FRAMEBUFFER_UNSUPPORTED_EXT\n");
			return -2;
		case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT:
			fprintf( stderr, "OpenGL Framebuffer error: GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT\n");
			return -3;
		case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT:
			fprintf( stderr, "OpenGL Framebuffer error: GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT\n");
			return -4;
		case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT:
			fprintf( stderr, "OpenGL Framebuffer error: GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT\n");
			return -5;
		case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT:
			fprintf( stderr, "OpenGL Framebuffer error: GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT\n");
			return -6;
		case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT:
			fprintf( stderr, "OpenGL Framebuffer error: GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT\n");
			return -7;
		default:
			fprintf( stderr, "UNKNWON error with OpenGL Framebuffer\n");
			return -8;
	}

	if( do_clear )
		glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );


	return 0;
}
void PointLightnigRenderPass::perform()
{
    if (!m_initialized) {
        return;
    }

    m_pPointLightsSelector->select(Object::Type_PointLight);
    const std::vector<Object*> &lights = m_pPointLightsSelector->selectedObjects();
    if (lights.size() == 0) {
        // No lights selected
        return;
    }

    glBindFramebuffer(GL_FRAMEBUFFER, m_fbo);
    glViewport(0, 0, m_pRenderer->width(), m_pRenderer->height());

    // clear frame buffer
    glClearDepth(1.0f);
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    GLenum buffers[] = {
        GL_COLOR_ATTACHMENT0
    };
    glDrawBuffers(1, buffers);

    m_pShaderProgram->use();
    Camera *pCamera = m_pScene->activeCamera();

    glm::mat4 cameraWorldMatrix = pCamera->worldMatrix();
    glm::vec3 cameraPosition = cameraWorldMatrix[3].xyz();
    (*m_pShaderProgram)["CameraPosition"] = cameraPosition;

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, *m_pColorTexureHandle);
    (*m_pShaderProgram)["ColorTexture"] = 0;

    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, *m_pPositionTextureHandle);
    (*m_pShaderProgram)["PositionTexture"] = 1;

    glActiveTexture(GL_TEXTURE2);
    glBindTexture(GL_TEXTURE_2D, *m_pNormalTextureHandle);
    (*m_pShaderProgram)["NormalTexture"] = 2;

    glDisable(GL_DEPTH_TEST);
    glEnable(GL_BLEND);
    glBlendFunc(GL_ONE, GL_ONE);

    DS_CHECK_GL_ERROR

    glViewport(0, 0, m_pRenderer->width(), m_pRenderer->height());

    glBindVertexArray(m_vertexArray);

    for (int i = 0; i < lights.size(); i++) {
        PointLight *pLight = dynamic_cast<PointLight*>(lights[i]);
        if (pLight != nullptr) {
            (*m_pShaderProgram)["LightPosition"] = pLight->worldMatrix()[3].xyz();
            (*m_pShaderProgram)["LightColor"] = pLight->color();
        }

        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
    }

    glBindVertexArray(0);
    glDisable(GL_BLEND);

    glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void GBuffer::BindBuffer() {
	static const GLenum mrt[] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2};
	glDrawBuffers(3, mrt);
}
enum piglit_result
piglit_display(void)
{
    GLuint vao = 0;
    GLuint fbo = 0;
    GLuint *fboTextures = NULL;
    GLenum *colorBuffers = NULL;
    GLuint attribLoc;
    GLfloat result[4];
    int i = 0;

    /*
     * Reserve memory for the FBO texture objects.
     */
    fboTextures = calloc(g_maxColorAttachments, sizeof(GLuint));

    if (NULL == fboTextures) {
        fprintf(stderr, "Failed to create FBO texture object container.\n");
        goto fail;
    }

    /*
     * Build the color attachments
     */
    colorBuffers = calloc(g_maxColorAttachments, sizeof(GLenum));

    if (NULL == colorBuffers) {
        fprintf(stderr, "Failed to create draw buffers descriptor.\n");
        goto fail;
    }

    /*
     * Generate an FBO container to hold the color attachment hierarchy.
     */
    glGenFramebuffers(1, &fbo);
    glBindFramebuffer(GL_FRAMEBUFFER, fbo);

    for (i = 0; i < g_maxColorAttachments; i++) {
        setup_fbo_2d(i, GL_RGBA32F, GL_RGBA, GL_FLOAT,
        BUFFER_WIDTH, BUFFER_HEIGHT,
        fbo, &fboTextures[i]);
        colorBuffers[i] = GL_COLOR_ATTACHMENT0 + i;
    }

    /*
     * Build the textures sampled by the shaders
     */
    for (i = 0; i < g_maxCombinedTextureImageUnits; i++) {
        GLuint tex;
        GLuint uniformLoc;
        char strTemp[16];

        glGenTextures(1, &tex);
        glActiveTexture(GL_TEXTURE0 + i);
        glBindTexture(GL_TEXTURE_2D, tex);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

        if (((i+1) * MAX_COMPONENTS) > sizeof(g_primes)) {
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, 1, 1, 0,
            GL_RGBA, GL_UNSIGNED_BYTE, NULL);
        } else {
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, 1, 1, 0,
                         GL_RGBA, GL_FLOAT,
                         &g_primes[i * MAX_COMPONENTS]);
        }

        if (!piglit_check_gl_error(GL_NO_ERROR)) {
            fprintf(stderr, "Failed to create texture %u.\n", i);
            goto fail;
        }

        snprintf(strTemp, sizeof(strTemp), "Texture[%u]", i);
        uniformLoc = glGetUniformLocation(g_program, strTemp);
        glUniform1i(uniformLoc, i);

        if (!piglit_check_gl_error(GL_NO_ERROR)) {
            fprintf(stderr, "Unable to assign texture %u uniform.\n", i);
            goto fail;
        }
    }

    /*
     * Setup the vertex and element buffers for drawing our points.
     */
    if (g_drawMode != DRAW_IMMEDIATE) {
        glGenVertexArrays(1, &vao);
        glBindVertexArray(vao);

        if (!piglit_check_gl_error(GL_NO_ERROR)) {
            fprintf(stderr, "Unable to create VAO.\n");
            goto fail;
        }

        setup_vertex_element_buffers();
    }

    /*
     * Setup the raster state.
     */
    glBindFramebuffer(GL_FRAMEBUFFER, fbo);
    glDrawBuffers(g_maxColorAttachments, colorBuffers);

    if (!piglit_check_gl_error(GL_NO_ERROR)) {
        fprintf(stderr, "Unable to assign draw buffers.\n");
        goto fail;
    }

    glClearColor(0.0, 1.0, 0.0, 0.0);
    glClear(GL_COLOR_BUFFER_BIT);

    /*
     * Bind the vertex array and enable each attribute.
     */
    if (g_drawMode != DRAW_IMMEDIATE) {
        glBindVertexArray(vao);
        attribLoc = glGetAttribLocation(g_program, "InPosition");
        glEnableVertexAttribArray(attribLoc);

        if (!piglit_check_gl_error(GL_NO_ERROR)) {
            fprintf(stderr,
                    "Unable to enable vertex array attribute %u.\n",
                    attribLoc);
            goto fail;
        }

        /*
         * Enable the rest of the attributes.
         */
        for (i = 0; i < g_maxVertexAttribs - 1; i++) {
            char strTemp[16];

            snprintf(strTemp, sizeof(strTemp), "InValue%u", i);
            attribLoc = glGetAttribLocation(g_program, strTemp);
            glEnableVertexAttribArray(attribLoc);

            if (!piglit_check_gl_error(GL_NO_ERROR)) {
                fprintf(stderr,
                        "Unable to enable vertex array attribute %u.\n",
                        attribLoc);
                goto fail;
            }
        }

        if (g_drawMode == DRAW_ARRAYS_VBO) {
            if (g_debugMask & DEBUG_DRAW) {
                fprintf(stderr, "Draw mode DRAW_ARRAYS_VBO\n");
            }
            glDrawArrays(GL_TRIANGLES, 0, NUM_VERTICES);
        }

        if (g_drawMode == DRAW_ELEMENTS_VBO) {
            if (g_debugMask & DEBUG_DRAW) {
                fprintf(stderr,
                        "Draw mode DRAW_ELEMENTS_VBO\n");
            }
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_elementVBO);
            glDrawElements(GL_TRIANGLES, NUM_VERTICES,
                           GL_UNSIGNED_SHORT, 0);
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
        }

        /*
         * Blindly reset all the attributes.
         */
        for (i = 0; i < g_maxVertexAttribs; i++) {
            glDisableVertexAttribArray(i);
        }
    } else {
        glBegin(GL_TRIANGLES);
        glVertex3f(-1.0, -1.0, 0.0);
        glVertex3f(-1.0, 1.0, 0.0);
        glVertex3f(1.0, 1.0, 0.0);
        glEnd();
    }

    if (!piglit_check_gl_error(GL_NO_ERROR))
        goto fail;

    /*
     * Read back the FBO contents.
     */

    /*
     * Disable color clamping so we don't encounter result
     * collisions attempting to use a normalized color space.
     *
     * Requires OpenGL 3.0
     */
    glClampColor(GL_CLAMP_READ_COLOR, GL_FALSE);

    for (i = 0; i < g_maxColorAttachments; i++) {
        if (g_debugMask & DEBUG_READBACK) {
            printf("GL_READ_FRAMEBUFFER <- fbo=%u\n", fbo);
        }

        glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo);

        if (!piglit_check_gl_error(GL_NO_ERROR))
            goto fail;

        glFramebufferTexture2D(GL_READ_FRAMEBUFFER,
                               GL_COLOR_ATTACHMENT0,
                               GL_TEXTURE_2D,
                               fboTextures[i],
                               0);

        if (!piglit_check_gl_error(GL_NO_ERROR))
            goto fail;

        glPixelStorei(GL_PACK_ALIGNMENT, 1);
        glReadBuffer(GL_COLOR_ATTACHMENT0);

        if (!piglit_check_gl_error(GL_NO_ERROR))
            goto fail;

        glReadPixels(0, BUFFER_HEIGHT - 1,
                     1, 1, GL_RGBA, GL_FLOAT, result);

        if ((g_expected[(i * MAX_COMPONENTS) + 0] != result[0]) ||
                (g_expected[(i * MAX_COMPONENTS) + 1] != result[1]) ||
                (g_expected[(i * MAX_COMPONENTS) + 2] != result[2]) ||
                (g_expected[(i * MAX_COMPONENTS) + 3] != result[3])) {
            fprintf(stderr, "GL_COLOR_ATTACHMENT%u: expected "
                    "(%f, %f, %f, %f) != (%f, %f, %f, %f)\n",
                    i, g_expected[(i * MAX_COMPONENTS) + 0],
                    g_expected[(i * MAX_COMPONENTS) + 1],
                    g_expected[(i * MAX_COMPONENTS) + 2],
                    g_expected[(i * MAX_COMPONENTS) + 3],
                    result[0], result[1], result[2], result[3]);

            goto fail;
        }
    }

    piglit_present_results();

    /*
     * Cleanup the allocations.
     */
    free(colorBuffers);
    free(fboTextures);

    piglit_report_result(PIGLIT_PASS);

    return PIGLIT_PASS;

fail:

    if (colorBuffers)
        free(colorBuffers);

    if (fboTextures)
        free(fboTextures);

    piglit_report_result(PIGLIT_FAIL);

    return PIGLIT_FAIL;
}
void
piglit_init(int argc, char **argv)
{
	bool pass = true;
	int i, max_draw_bufs;

	if (argc != 2) {
		printf("Expected one parameter, got %i.\n", argc-1);
		piglit_report_result(PIGLIT_FAIL);
	}
	test_name = argv[1];

	piglit_require_gl_version(21);
	piglit_require_extension("GL_ARB_framebuffer_object");

	glGetIntegerv(GL_MAX_DRAW_BUFFERS_ARB, &max_draw_bufs);
	if (max_draw_bufs < 4) {
		puts("At least 4 draw buffers are required.");
		piglit_report_result(PIGLIT_SKIP);
	}

	printf("Testing %s.\n", test_name);

	/* Begin testing. */
	create_shaders();
	create_and_bind_fbo();

	for (i = 0; i < ARRAY_SIZE(drawbuf_config); i++) {
		clear_all_attachments_to_initial_value();

		glDrawBuffers(4, drawbuf_config[i]);

		if (strcmp(test_name, "glClear") == 0) {
			pass = test_glClear(drawbuf_config[i]) && pass;
		}
		else if (strcmp(test_name, "glClearBuffer") == 0) {
			piglit_require_gl_version(30);
			pass = test_glClearBuffer(drawbuf_config[i]) && pass;
		}
		else if (strcmp(test_name, "gl_FragColor") == 0) {
			pass = test_fragcolor(drawbuf_config[i]) && pass;
		}
		else if (strcmp(test_name, "gl_FragData") == 0) {
			pass = test_fragdata(drawbuf_config[i]) && pass;
		}
		else if (strcmp(test_name, "glColorMaskIndexed") == 0) {
			piglit_require_extension("GL_EXT_draw_buffers2");
			pass = test_glColorMaskIndexed(drawbuf_config[i]) && pass;
		}
		else if (strcmp(test_name, "glBlendFunci") == 0) {
			piglit_require_extension("GL_ARB_draw_buffers_blend");
			pass = test_glBlendFunci(drawbuf_config[i]) && pass;
		}
		else if (strcmp(test_name, "glDrawPixels") == 0) {
			pass = test_glDrawPixels(drawbuf_config[i]) && pass;
		}
		else if (strcmp(test_name, "glBlitFramebuffer") == 0) {
			pass = test_glBlitFramebuffer(drawbuf_config[i]) && pass;
		}
		else {
			printf("Unknown subtest: %s\n", test_name);
			piglit_report_result(PIGLIT_FAIL);
		}
	}

	pass = piglit_check_gl_error(GL_NO_ERROR) && pass;
	piglit_report_result(pass ? PIGLIT_PASS : PIGLIT_FAIL);
}
void OpenglES3Device::drawBuffer(unsigned int colorAttachmentNumber){
	unsigned int attachements[] = { GL_COLOR_ATTACHMENT0 + colorAttachmentNumber };
	glDrawBuffers(1, attachements );
	this->evaluateErrorsAndLogOnlyInDebugMode("drawBuffer");
}
Exemple #19
0
void CRenderTarget::addTarget(const string& format, uint texUnit, int attachment)
{
	GLenum type, filter;
	GLint n;

	assert( !format.empty() );

	if (attachment==-1)
		attachment = texUnit;

	m_vTexUnits.push_back(texUnit);

	if (format.find("rect") != string::npos)
		type = GL_TEXTURE_RECTANGLE_ARB;
	else
		if (format.find("2D") != string::npos)
			type = GL_TEXTURE_2D;
		else
			if (format.find("cube") == string::npos)
				cerr << "(EE) Render target type error" << endl;

	if (format.find("nearest") != string::npos)
		filter = GL_NEAREST;
	else
		if (format.find("linear") != string::npos)
			filter = GL_LINEAR;
		else
			filter = GL_NEAREST;

//    glTexImage2D(m_type, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
//    case 0 : glTexImage2D(m_type, 0, GL_RGB32F_ARB, width, height, 0, GL_RGBA, GL_FLOAT, NULL); break;
//    case 1 : glTexImage2D(m_type, 0, GL_FLOAT_RG16_NV, width, height, 0, GL_FLOAT_RG16_NV, GL_UNSIGNED_BYTE, NULL); break;
//    case 2 : glTexImage2D(m_type, 0, GL_RGB10_A2, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); break;

	if (format.find("color") != string::npos)
	{
		glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT, &n);
		assert( m_vTexUnits.size() <= (uint)n);

		glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, m_uiFrameBuffer );
		if (format.find("rgba16f") != string::npos)
		{
			ITexture *tex=new CRenderTexture(type,filter,m_uiWidth,m_uiHeight, 0);
			m_vRenderTextures.push_back(tex);
			glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT+attachment, type, tex->getTexture(), 0 );
		}
		else
			if (format.find("rgba") != string::npos)
			{
				ITexture *tex=new CRenderTexture(type,filter,m_uiWidth,m_uiHeight, 1);
				m_vRenderTextures.push_back(tex);
				glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT+attachment, type, tex->getTexture(), 0 );
			}
			else
				if (format.find("rgb10a2") != string::npos)
				{
					ITexture *tex=new CRenderTexture(type,filter,m_uiWidth,m_uiHeight, 2);
					m_vRenderTextures.push_back(tex);
					glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT+attachment, type, tex->getTexture(), 0 );
				}else
					if (format.find("cube") != string::npos)
					{
						ITexture *tex=new CCubeTexture(m_uiWidth,m_uiHeight);
						m_vRenderTextures.push_back(tex);
						for (uint j=0; j < 6; j++)
							glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT+j,
							                           CCubeTexture::s_cubeMapTarget[j], tex->getTexture(), 0 );
					}
					else
						cerr << "(EE) Render target format error" << endl;

		/** Activation du rendu dans tous les attachements
		 *  Pour l'instant on le fait à chaque nouvelle cible pour éviter un appel supplémentaire
		 */
		if (m_vTexUnits.size() > 1)
		{
			vector<GLenum> m_vAttachements;
			for (uint i=0; i < m_vTexUnits.size(); i++)
				m_vAttachements.push_back(GL_COLOR_ATTACHMENT0_EXT+i);
			glDrawBuffers(m_vAttachements.size(), &m_vAttachements[0] );
		}
	}else

		if (format.find("depth") != string::npos )
		{
			if (m_bDepthRenderBuffer)
				cerr << "(EE) Can't bind depth to texture, since it is always bound to a render buffer" << endl;

			assert(m_bDepthTexture == false);

			m_bDepthTexture = true;

			bool shadow = format.find("shadow") != string::npos;

			bool customFunc = false;
			GLenum func;
			// Format comparison
			if (format.find("greater") != string::npos)
			{
				func = GL_GREATER;
				customFunc = true;
			}else
				if (format.find("equal") != string::npos)
				{
					func = GL_EQUAL;
					customFunc = true;
				}else
					if (format.find("less") != string::npos)
					{
						func = GL_LESS;
						customFunc = true;
					}else
						if (format.find("less") != string::npos)
						{
							func = GL_LESS;
							customFunc = true;
						}

			glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, m_uiFrameBuffer );

			ITexture *tex;
			if (customFunc)
				tex=new CDepthTexture(type, m_uiWidth,m_uiHeight, filter, func);
			else
				tex=new CDepthTexture(type, m_uiWidth,m_uiHeight, filter, shadow);

			m_vRenderTextures.push_back(tex);

			glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, type, tex->getTexture(), 0 );

			/** Si le nombre de texture est égal à 1 alors on suppose qu'on a qu'une depth texture */
			if (m_vRenderTextures.size() == 1)
			{
				glDrawBuffer (GL_NONE);
				glReadBuffer (GL_NONE);
			}

		}else
			cerr << "(EE) Render target format error : should be at least a depth or color texture." << endl;

	assert( CheckStatus() );
	bindDefaultTarget();
}
void Effects::setup(int w, int h) {
	width = w;
	height = h;
	
	cracks.setup(w,h);
	
	// create fbo
	glGenFramebuffers(1, &fbo_handle); eglGetError();
	glBindFramebuffer(GL_FRAMEBUFFER, fbo_handle);
	
	// create texture.
	glGenTextures(1, &fbo_tex); eglGetError();
	glActiveTexture(GL_TEXTURE0); eglGetError();
	glBindTexture(GL_TEXTURE_2D, fbo_tex); eglGetError();
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); eglGetError();
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); eglGetError();
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); eglGetError();

	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo_tex, 0); eglGetError();
	glGenRenderbuffers(1, &fbo_depth); eglGetError();

	// render buffer
	glBindRenderbuffer(GL_RENDERBUFFER, fbo_depth); eglGetError();	
	glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, w, h);
	glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo_depth); eglGetError();

	GLenum drawbufs[] = {GL_COLOR_ATTACHMENT0};
	glDrawBuffers(1, drawbufs);
	glBindFramebuffer(GL_FRAMEBUFFER, 0);
	
	if(!shader.load("effects/effects")) {
		printf("Error loading effects shader.\n");
	}
	
	vertices[0].setPos(-1, -1, 0);
	vertices[1].setPos(1, -1, 0);
	vertices[2].setPos(1, 1, 0);
	vertices[3].setPos(-1, 1, 0);
	
	float mw = 1;
	float mh = 1;
	vertices[0].setTex(0, 0);
	vertices[1].setTex(mw, 0);
	vertices[2].setTex(mw, mh);
	vertices[3].setTex(0, mh);
	
	glGenVertexArraysAPPLE(1, &vao); eglGetError();
	glBindVertexArrayAPPLE(vao); eglGetError();

	GLint pos_attrib = glGetAttribLocation(shader.getProgram(), "pos");
	GLint tex_attrib = glGetAttribLocation(shader.getProgram(), "tex");
	glEnableVertexAttribArray(pos_attrib);
	glEnableVertexAttribArray(tex_attrib);

	glGenBuffers(1, &vbo); eglGetError();
	glBindBuffer(GL_ARRAY_BUFFER, vbo); eglGetError();
	
	glBufferData(
		GL_ARRAY_BUFFER	
		,sizeof(Vertex) * 4
		,vertices[0].pos
		,GL_STATIC_DRAW
	); eglGetError();
	
	glVertexAttribPointer(
		pos_attrib
		,3
		,GL_FLOAT
		,GL_FALSE
		,sizeof(Vertex)
		,offsetof(Vertex, pos)
	);
	
	glVertexAttribPointer(
		tex_attrib
		,2
		,GL_FLOAT
		,GL_FALSE
		,sizeof(Vertex)
		,(GLvoid*)offsetof(Vertex, tex)
	);
	
	calcCenter();	
	
	unbind();
	
	flip(false);
	mirror(false);	
	crack(false);
}
// Render the world from the specified point of view.
void RenderView(
    const osvr::renderkit::RenderInfo& renderInfo, //< Info needed to render
    GLuint frameBuffer, //< Frame buffer object to bind our buffers to
    GLuint colorBuffer, //< Color buffer to render into
    GLuint depthBuffer  //< Depth buffer to render into
    ) {
    // Make sure our pointers are filled in correctly.  The config file selects
    // the graphics library to use, and may not match our needs.
    if (renderInfo.library.OpenGL == nullptr) {
        std::cerr
            << "RenderView: No OpenGL GraphicsLibrary, this should not happen"
            << std::endl;
        return;
    }

    // Render to our framebuffer
    glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);

    // Set color and depth buffers for the frame buffer
    glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, colorBuffer, 0);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
                              GL_RENDERBUFFER, depthBuffer);

    // Set the list of draw buffers.
    GLenum DrawBuffers[1] = {GL_COLOR_ATTACHMENT0};
    glDrawBuffers(1, DrawBuffers); // "1" is the size of DrawBuffers

    // Always check that our framebuffer is ok
    if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
        std::cerr << "RenderView: Incomplete Framebuffer" << std::endl;
        return;
    }

    // Set the viewport to cover our entire render texture.
    glViewport(0, 0, static_cast<GLsizei>(renderInfo.viewport.width),
               static_cast<GLsizei>(renderInfo.viewport.height));

    // Set the OpenGL projection matrix
    GLdouble projection[16];
    osvr::renderkit::OSVR_Projection_to_OpenGL(projection,
                                               renderInfo.projection);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glMultMatrixd(projection);

    /// Put the transform into the OpenGL ModelView matrix
    GLdouble modelView[16];
    osvr::renderkit::OSVR_PoseState_to_OpenGL(modelView, renderInfo.pose);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glMultMatrixd(modelView);

    // Clear the screen to black and clear depth
    glClearColor(0, 0, 0, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // =================================================================
    // This is where we draw our world and hands and any other objects.
    // We're in World Space.  To find out about where to render objects
    // in OSVR spaces (like left/right hand space) we need to query the
    // interface and handle the coordinate tranforms ourselves.

    // Draw a cube with a 5-meter radius as the room we are floating in.
    draw_cube(5.0);
}
SdfPath
My_TestGLDrawing::PickScene(int pickX, int pickY,
        int * outInstanceIndex,
        int * outElementIndex)
{
    int width = 128;
    int height = 128;

    GlfDrawTargetRefPtr drawTarget = GlfDrawTarget::New(GfVec2i(width, height));
    drawTarget->Bind();
    drawTarget->AddAttachment(
        "primId", GL_RGBA, GL_UNSIGNED_BYTE, GL_RGBA8);
    drawTarget->AddAttachment(
        "instanceId", GL_RGBA, GL_UNSIGNED_BYTE, GL_RGBA8);
    drawTarget->AddAttachment(
        "elementId", GL_RGBA, GL_UNSIGNED_BYTE, GL_RGBA8);
    drawTarget->AddAttachment(
        "depth", GL_DEPTH_COMPONENT, GL_FLOAT, GL_DEPTH_COMPONENT32F);
    drawTarget->Unbind();

    drawTarget->Bind();

    GLenum drawBuffers[] = { 
        GL_COLOR_ATTACHMENT0,
        GL_COLOR_ATTACHMENT1,
        GL_COLOR_ATTACHMENT2
    };
    glDrawBuffers(3, drawBuffers);

    glEnable(GL_DEPTH_TEST);

    GLfloat clearColor[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
    glClearBufferfv(GL_COLOR, 0, clearColor);
    glClearBufferfv(GL_COLOR, 1, clearColor);

    GLfloat clearDepth[1] = { 1.0f };
    glClearBufferfv(GL_DEPTH, 0, clearDepth);

    PickParam pickParam;
    pickParam.location = GfVec2d(pickX, pickY);
    pickParam.viewport = GfVec4d(0, 0, width, height);

    DrawScene(&pickParam);

    drawTarget->Unbind();

    GLubyte primId[width*height*4];
    glBindTexture(GL_TEXTURE_2D,
        drawTarget->GetAttachments().at("primId")->GetGlTextureName());
    glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, primId);

    GLubyte instanceId[width*height*4];
    glBindTexture(GL_TEXTURE_2D,
        drawTarget->GetAttachments().at("instanceId")->GetGlTextureName());
    glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, instanceId);

    GLubyte elementId[width*height*4];
    glBindTexture(GL_TEXTURE_2D,
        drawTarget->GetAttachments().at("elementId")->GetGlTextureName());
    glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, elementId);

    GLfloat depths[width*height];
    glBindTexture(GL_TEXTURE_2D,
        drawTarget->GetAttachments().at("depth")->GetGlTextureName());
    glGetTexImage(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, GL_FLOAT, depths);

    double zMin = 1.0;
    int zMinIndex = -1;
    for (int y=0, i=0; y<height; y++) {
        for (int x=0; x<width; x++, i++) {
            if (depths[i] < zMin) {
                    zMin = depths[i];
                    zMinIndex = i;
            }
        }
    }

    bool didHit = (zMin < 1.0);

    SdfPath result;
    if (didHit) {
        int idIndex = zMinIndex*4;

        result = _delegate->GetRenderIndex().GetRprimPathFromPrimId(
                HdxIntersector::DecodeIDRenderColor(&primId[idIndex]));
        if (outInstanceIndex) {
            *outInstanceIndex = HdxIntersector::DecodeIDRenderColor(
                    &instanceId[idIndex]);
        }
        if (outElementIndex) {
            *outElementIndex = HdxIntersector::DecodeIDRenderColor(
                    &elementId[idIndex]);
        }
    }

    return result;
}
Exemple #23
0
bool 
GBuffer::initialize( const Viewport& vp, bool multisample, int samples ) {

	int width =vp.width - vp.x;
	int height =vp.height - vp.y;

	/* First time initialize? */
	if( !m_fbo ) {
		glEnable( GL_MULTISAMPLE );
		glGenFramebuffers(1, &m_fbo); 
	}
	else {
		glDeleteTextures( NUM_TEXTURES, m_textures);
	}
	
	glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo);
//	glRenderbufferStorageMultisample( GL_RENDERBUFFER, 2, GL_DEPTH24_STENCIL8, width, height );
	glGenTextures( NUM_TEXTURES, m_textures );
	
	/* Depth */
	
	if( multisample ) {
		glBindTexture( GL_TEXTURE_2D_MULTISAMPLE, m_textures[DEPTH_TEXTURE] );
		glTexImage2DMultisample( GL_TEXTURE_2D_MULTISAMPLE, samples, GL_DEPTH_COMPONENT32F, width, height, false );
/*		glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_LUMINANCE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);*/
		glFramebufferTexture2D( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D_MULTISAMPLE, m_textures[DEPTH_TEXTURE], 0 );
  } else {
		glBindTexture(GL_TEXTURE_2D, m_textures[DEPTH_TEXTURE]);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT,
									NULL);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_textures[DEPTH_TEXTURE], 0);
	}	
  
	
	/* Diffuse + spec */
	if( multisample ) {
	  glBindTexture( GL_TEXTURE_2D_MULTISAMPLE, m_textures[DIFFUSE_SPEC_TEXTURE] );
  	glTexImage2DMultisample( GL_TEXTURE_2D_MULTISAMPLE, samples, GL_RGBA16F, width, height, false );
  	glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, m_textures[DIFFUSE_SPEC_TEXTURE], 0 );
  } else {
		glBindTexture(GL_TEXTURE_2D, m_textures[DIFFUSE_SPEC_TEXTURE]);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, width, height, 0, GL_RGBA, GL_FLOAT, NULL);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_textures[DIFFUSE_SPEC_TEXTURE], 0);
  }
  
/*  printf("GL error, status: 0x%x\n", glGetError());*/
	
	/* Normals */
	if( multisample ) {
		glBindTexture( GL_TEXTURE_2D_MULTISAMPLE, m_textures[NORMAL_TEXTURE] );
		glTexImage2DMultisample( GL_TEXTURE_2D_MULTISAMPLE, samples, GL_RGB16F, width, height, false );
		glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D_MULTISAMPLE, m_textures[NORMAL_TEXTURE], 0 );
	} else {	
		glBindTexture(GL_TEXTURE_2D, m_textures[NORMAL_TEXTURE]);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, width, height, 0, GL_RGB, GL_FLOAT, NULL);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, m_textures[NORMAL_TEXTURE], 0);
  }
  
  /* Position */
	if( multisample ) {
		glBindTexture( GL_TEXTURE_2D_MULTISAMPLE, m_textures[POSITION_TEXTURE] );
		glTexImage2DMultisample( GL_TEXTURE_2D_MULTISAMPLE, samples, GL_RGBA16F, width, height, false );
		glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D_MULTISAMPLE, m_textures[POSITION_TEXTURE], 0 );
	} else {	
		glBindTexture(GL_TEXTURE_2D, m_textures[POSITION_TEXTURE]);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, width, height, 0, GL_RGBA, GL_FLOAT, NULL);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, m_textures[POSITION_TEXTURE], 0);
  }
	
	GLenum DrawBuffers[] = { /*GL_DEPTH_ATTACHMENT, */GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2/*, GL_COLOR_ATTACHMENT3 */}; 
  glDrawBuffers(NUM_TEXTURES-1, DrawBuffers);

	GLenum Status = glCheckFramebufferStatus(GL_FRAMEBUFFER);

    if (Status != GL_FRAMEBUFFER_COMPLETE) {
        printf("FB error, status: 0x%x\n", Status);
        return false;
    }
    
  m_width =width;
  m_height =height;
  m_multisample =multisample;
	glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
	return true;
}
bool setupDeferred(int w, int h) {
  std::cout << "setupDeferred " << w << " " << h << std::endl;
  glBindFramebuffer(GL_DRAW_FRAMEBUFFER, deferredFbo);

  //color
  glBindTexture(GL_TEXTURE_2D, deferredColorTex);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,w,h,0,GL_RGBA,GL_FLOAT,0);
  glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,
                         GL_TEXTURE_2D,deferredColorTex,0);

  //normal
  GLenum normalInnerFormat;
  GLenum normalType;

  normalInnerFormat=GL_RGBA32F;
  normalType=GL_FLOAT;

  // normalInnerFormat=GL_RGBA16F;
  // normalType=GL_HALF_FLOAT;

  glBindTexture(GL_TEXTURE_2D, deferredNormalTex);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexImage2D(GL_TEXTURE_2D,0,normalInnerFormat,w,h,0,GL_RGBA,normalType,0);

  glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER,GL_COLOR_ATTACHMENT1,
                         GL_TEXTURE_2D,deferredNormalTex,0);

  //depth
  glBindTexture(GL_TEXTURE_2D, deferredDepthTex);
  glTexImage2D(GL_TEXTURE_2D,0,GL_DEPTH_COMPONENT32F,w,h,0,GL_DEPTH_COMPONENT,GL_FLOAT,0);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_INTENSITY);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);

  glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER,GL_DEPTH_ATTACHMENT,
                         GL_TEXTURE_2D,deferredDepthTex,0);

  //
  GLenum drawBufs[]={GL_COLOR_ATTACHMENT0,GL_COLOR_ATTACHMENT1};
  glDrawBuffers(2,drawBufs);

  //check fbo status
  GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);

  if(status == GL_FRAMEBUFFER_COMPLETE) {
    //restore default FBO
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    return true;
  } else if(status==GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT) {
    std::cout << "fbo error: incomplete attachment\n";
  } else if(status==GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT) {
    std::cout << "fbo error: incomplete missing attachment\n";
  } else if(status==GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER) {
    std::cout << "fbo error: incomplete draw buffer\n";
  } else if(status==GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER) {
    std::cout << "fbo error: incomplete read buffer\n";
  } else if(status==GL_FRAMEBUFFER_UNSUPPORTED) {
    std::cout << "fbo error: unsupported\n";
  }

  return false;
}
Exemple #25
0
void NGLScene::createFrameBuffer()
{

  // create a framebuffer object this is deleted in the dtor
  int w=width()*devicePixelRatio();
  int h=height()*devicePixelRatio();

  glGenFramebuffers(1, &m_gbuffer);
  glBindFramebuffer(GL_FRAMEBUFFER, m_gbuffer);

  // create a renderbuffer object to store depth info
  GLuint m_rboID;
  glGenRenderbuffers(1, &m_rboID);
  glBindRenderbuffer(GL_RENDERBUFFER, m_rboID);

  glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, w, h);
  glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_rboID);

  // create a texture object
  glGenTextures(1, &m_pointTexID);
  // bind it to make it active
  glBindTexture(GL_TEXTURE_2D, m_pointTexID);
  // set params
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);

  // create a texture object
  glGenTextures(1, &m_normalTexID);
  // bind it to make it active
  glBindTexture(GL_TEXTURE_2D, m_normalTexID);
  // set params
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);

  glGenTextures(1, &m_colourTexID);
  // bind it to make it active
  glBindTexture(GL_TEXTURE_2D, m_colourTexID);
  // set params
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);

  glGenTextures(1, &m_shadingTexID);
  // bind it to make it active
  glBindTexture(GL_TEXTURE_2D, m_shadingTexID);
  // set params
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);


  // The depth buffer
//	glGenTextures(1, &m_depthTex);
//	glBindTexture(GL_TEXTURE_2D, m_depthTex);
//	glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH32F_STENCIL8, w, h, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
//	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
//	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);


  // attatch the texture we created earlier to the FBO
  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_pointTexID, 0);
  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, m_normalTexID, 0);
  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, m_colourTexID, 0);
  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, GL_TEXTURE_2D, m_shadingTexID, 0);

  // glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, m_depthTex, 0);

  // now attach a renderbuffer to depth attachment point
//  GLenum drawBuffers[] = { GL_COLOR_ATTACHMENT0,GL_COLOR_ATTACHMENT1,GL_COLOR_ATTACHMENT2};
//  glDrawBuffers (3, drawBuffers);


  // now we are going to create a buffer for the lighting pass

  // create a framebuffer object this is deleted in the dtor

  glGenFramebuffers(1, &m_lightBuffer);
  glBindFramebuffer(GL_FRAMEBUFFER, m_lightBuffer);

  // create a renderbuffer object to store depth info
  glGenRenderbuffers(1, &m_rboID);
  glBindRenderbuffer(GL_RENDERBUFFER, m_rboID);

  glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, w, h);
  glGenTextures(1, &m_lightPassTexID);
  // bind it to make it active
  glBindTexture(GL_TEXTURE_2D, m_lightPassTexID);
  // set params
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);





  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_lightPassTexID, 0);
  GLuint lightBuffers[] = { GL_COLOR_ATTACHMENT0};
  glDrawBuffers (1, lightBuffers);

  // now got back to the default render context
  glBindFramebuffer(GL_FRAMEBUFFER, 0);


}