Example #1
9
    /// @overload QGLWidget
    void paintGL(){
        vao.bind();
        program.bind();
        {
            
        ///--- Update modelview
#ifdef WITH_QGLVIEWER
            /// use the trackball to specify the matrices
            setup_modelview(camera(), program);
#else
            ///--- simple unit cube orthographic view
            static Eigen::Matrix4f M = Eigen::Matrix4f::Identity();
            static Eigen::Matrix4f P = Eigen::ortho(-1.0f, +1.0f, -1.0f, +1.0f, -1.0f, +1.0f);
            static Eigen::Matrix4f V = Eigen::Matrix4f::Identity();
            static Eigen::Matrix4f MV = V*M;
            static Eigen::Matrix4f MVP = P*MV;
            GLint MVP_id = glGetUniformLocation(program.programId(), "MVP");
            glUniformMatrix4fv(MVP_id, 1, GL_FALSE, MVP.data());
            GLint MV_id = glGetUniformLocation(program.programId(), "MV");
            glUniformMatrix4fv(MV_id, 1, GL_FALSE, MV.data());
#endif      
                        
            ///--- clear & draw
            glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
            glDrawElements(GL_TRIANGLES, triangles.size(), GL_UNSIGNED_INT, 0);
        }
        vao.release();
        program.release();
    }
Example #2
0
void Exercise20::paintGL()
{
    glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

    QGLShaderProgram* currentProg;
    if (m_shadingMode == Toon_Shading)
    {
        currentProg = m_prog_toon;
    }
    else
    {
        currentProg = m_prog_phong;
    }

    currentProg->bind();

    setupLightUniforms(currentProg);
    setupMaterialUniforms(currentProg);

    glLoadMatrixf(m_view.data());

    glPushMatrix();

    glRotatef(static_cast<float>(m_frame % (4 * 360)) * 0.25f, 0.f, 1.f, 0.f);
    glScalef(1.f, 1.f, 1.f);

    draw();

    glPopMatrix();
    currentProg->release();
}
Example #3
0
void NightModeGraphicsEffect::draw(QPainter* painter)
{
	int pixelRatio = painter->device()->devicePixelRatio();
	QSize size(painter->device()->width() * pixelRatio, painter->device()->height() * pixelRatio);
	if (fbo && fbo->size() != size)
	{
		delete fbo;
		fbo = NULL;
	}
	if (!fbo)
	{
		QGLFramebufferObjectFormat format;
		format.setAttachment(QGLFramebufferObject::CombinedDepthStencil);
		format.setInternalTextureFormat(GL_RGBA);
		fbo = new NightModeGraphicsEffectFbo(size, format, pixelRatio);
	}
	QPainter fboPainter(fbo);
	drawSource(&fboPainter);

	painter->save();
	painter->beginNativePainting();
	program->bind();
	const GLfloat pos[] = {-1, -1, +1, -1, -1, +1, +1, +1};
	const GLfloat texCoord[] = {0, 0, 1, 0, 0, 1, 1, 1};
	program->setUniformValue(vars.source, 0);
	program->setAttributeArray(vars.pos, pos, 2);
	program->setAttributeArray(vars.texCoord, texCoord, 2);
	program->enableAttributeArray(vars.pos);
	program->enableAttributeArray(vars.texCoord);
	glBindTexture(GL_TEXTURE_2D, fbo->texture());
	glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
	program->release();
	painter->endNativePainting();
	painter->restore();
}
Example #4
0
 /// @overload QGLWidget
 void paintGL(){
     program.bind();
     vao.bind();
         glClear(GL_COLOR_BUFFER_BIT);
         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); ///< we have 4 verts
     vao.release();
     program.release();
 }
// --------------------------------------------------------
void TouchWidgetRenderer::drawHollowCircle( GLResourceContainer * container, const QPointF & pos, qreal radius, qreal alpha, const QColor & color, qreal thickness, qreal blur_multiplier ) const
{
	QSizeF size(2*radius, 2*radius);
	QGLShaderProgram * shader = container->shaderProgram("circle");
	shader->bind();
	shader->setUniformValue("thickness", 1.0f/(GLfloat)size.width()*(float)thickness);
	shader->setUniformValue("blur", (float) thickness*(float)blur_multiplier);
	//shader->setUniformValue("blur", (float) radius);
	shader->setUniformValue("alpha", (float) (this->alpha()*alpha));
	shader->setUniformValue("color", color);
	drawQuad(pos, size, 0, 1.0f /* ignored by shader anyway */);
	shader->release();
}
Example #6
0
 /// @overload QGLWidget
 void initializeGL(){     
     printf("OpenGL %d.%d\n",this->format().majorVersion(),this->format().minorVersion());
     
     ///--- Create an array object to store properties
     {
         bool success = vao.create();
         Q_ASSERT(success);
         vao.bind();
     }
     
     ///--- Load/compile shaders
     {
         bool vok = program.addShaderFromSourceCode(QGLShader::Vertex, vshader);
         bool fok = program.addShaderFromSourceCode(QGLShader::Fragment, fshader);
         bool lok = program.link ();
         Q_ASSERT(lok && vok && fok);
         bool success = program.bind();
         Q_ASSERT(success);
     }
     
     ///--- Create vertex buffer/attributes "position"
     {
         static float vertices[] = {
             -1.0000,-1.0000,+0.0000,
             +1.0000,-1.0000,+0.0000,
             -1.0000,+1.0000,+0.0000,
             +1.0000,+1.0000,+0.0000,};
         
         vertexbuffer = QGLBuffer(QGLBuffer::VertexBuffer);
         bool success = vertexbuffer.create();
         Q_ASSERT(success);
         vertexbuffer.setUsagePattern( QGLBuffer::StaticDraw ); 
         success = vertexbuffer.bind();
         Q_ASSERT(success);
         vertexbuffer.allocate( vertices, sizeof(vertices) );
         program.setAttributeBuffer("position", GL_FLOAT, 0, 3 );
         program.enableAttributeArray("position");
     }
     
     ///--- Unbind to avoid pollution
     vao.release();
     program.release();
     
     ///--- Background
     glClearColor(1.0, 1.0, 1.0, 1.0);
             
     ///--- Setup opengl flags
     glDisable(GL_DEPTH_TEST);
 }
// --------------------------------------------------------
void TouchWidgetRenderer::drawMagnifyingGlass(
	GLResourceContainer * container,
	const MagnifyingGlass * mg,
	float alpha ) const
{
	// draw contents to fbo
	QGLFramebufferObject * fbo = container->framebufferObject("mg_fbo");
	drawSceneToFbo(fbo,	mg->srcCenter(), mg->srcSize(), mg->angle());

	//qDebug() << "drawing mg " << mg << mg->dstCenter() << mg->dstSize();

	// draw magnifying glass including contents
	QGLShaderProgram * shader = container->shaderProgram("mglass");
	shader->bind();
	shader->setUniformValue("mglass_tex", 0);
	shader->setUniformValue("content_tex", 1);
	shader->setUniformValue("alpha", this->alpha()*alpha);
	glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, container->texture("mglass"));
	glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, fbo->texture());
	drawQuad(mg->dstCenter(), mg->dstSize(), -mg->angle(), this->alpha()*alpha);
	shader->release();
}
Example #8
0
File: glwidget.cpp Project: tv/cg
void GLWidget::paintGL()
{
    GLenum errCode;

    // First pass for shadowmapping

    QGLShaderProgram * p;
    Camera * cam;
    Light * light;


    if (this->debugMode != 3) {



    for (int i = 0; i < this->_lights.size(); i++) {
        light = this->_lights.at(i);
        if (!light->initializedFBO) {
            light->initializeShadowFBO(QSize(this->_screenWidth, this->_screenHeight));
            return;
        }

        if (this->debugMode != 4) {
            light->bindFBO();
        }

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glCullFace(GL_FRONT);

        if (this->debugMode == 4) {

            p = this->_program;
            p = this->_shadowProgram;


        } else {

            glViewport(0,0, this->_screenWidth/2, this->_screenHeight/2);
            p = this->_shadowProgram;

        }

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        cam = this->_lights.at(i)->camera;

        p->bind();

        // wont be used in shadow program
        p->setUniformValue("debug_mode", 4);

        cam->injectToShader(p);

        for (int i = 0; i < this->_objects.size(); i++) {
            this->_objects.at(i)->injectToShader(p);
        }

        if (this->debugMode == 4) {
            p->release();
            return;
        }

        light->releaseFBO();

        p->release();
    }
    }

    if (this->showDebug) {

        // DEBUG only. this piece of code draw the depth buffer onscreen

        glBindFramebuffer(GL_FRAMEBUFFER,0);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        this->_shadowProgram->release();
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(-this->_screenWidth/2, this->_screenWidth/2, -this->_screenHeight/2, this->_screenHeight/2, 1, 60);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        glColor4f(1,1,1,1);

        this->_lights.at(0)->bindDebugShadowMap();

        glEnable(GL_TEXTURE_2D);
        glTranslated(0,0,-1);
        glBegin(GL_QUADS);
        glTexCoord2d(0,0);glVertex3f(0,0,0);
        glTexCoord2d(1,0);glVertex3f(_screenWidth/2,0,0);
        glTexCoord2d(1,1);glVertex3f(_screenWidth/2,_screenHeight/2,0);
        glTexCoord2d(0,1);glVertex3f(0,_screenHeight/2,0);
        glEnd();
        glDisable(GL_TEXTURE_2D);

        //glutSwapBuffers();
        return;
    }



    // Second pass
    p = this->_program;
    cam = this->camera;


    glViewport(0,0, this->_screenWidth, this->_screenHeight);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    if ((errCode = glGetError()) != GL_NO_ERROR) {
        qDebug() << "GLWidget::draw after clear: " << errCode;
    }

    p->bind();

    cam->injectToShader(p);
    if ((errCode = glGetError()) != GL_NO_ERROR) {

        qDebug() << "GLWidget::draw  after cam: " << errCode;
    }

    p->setUniformValue("debug_mode", this->debugMode);

    for (int i = 0; i < this->_lights.size(); i++) {
        this->_lights.at(i)->injectToShader(p, i);
    }

    for (int i = 0; i < this->_objects.size(); i++) {
        this->_objects.at(i)->injectToShader(p);
    }

    this->_program->release();

    if ((errCode = glGetError()) != GL_NO_ERROR) {

        qDebug() << "GLWidget  after  2nd pas: " << errCode;
    }

}
/*!
    \reimp
*/
void QGLPerVertexColorEffect::setActive(QGLPainter *painter, bool flag)
{
#if defined(QGL_FIXED_FUNCTION_ONLY)
    Q_UNUSED(painter);
    if (flag) {
        glEnableClientState(GL_VERTEX_ARRAY);
        glEnableClientState(GL_COLOR_ARRAY);
    } else {
        glDisableClientState(GL_VERTEX_ARRAY);
        glDisableClientState(GL_COLOR_ARRAY);
    }
#else
    Q_UNUSED(painter);
    Q_D(QGLPerVertexColorEffect);
#if !defined(QGL_SHADERS_ONLY)
    if (painter->isFixedFunction()) {
        d->isFixedFunction = true;
        if (flag) {
            glEnableClientState(GL_VERTEX_ARRAY);
            glEnableClientState(GL_COLOR_ARRAY);
        } else {
            glDisableClientState(GL_VERTEX_ARRAY);
            glDisableClientState(GL_COLOR_ARRAY);
        }
        return;
    }
#endif
    static char const pvColorVertexShader[] =
        "attribute highp vec4 vertex;\n"
        "attribute mediump vec4 color;\n"
        "uniform highp mat4 matrix;\n"
        "varying mediump vec4 qColor;\n"
        "void main(void)\n"
        "{\n"
        "    gl_Position = matrix * vertex;\n"
        "    qColor = color;\n"
        "}\n";

    static char const pvColorFragmentShader[] =
        "varying mediump vec4 qColor;\n"
        "void main(void)\n"
        "{\n"
        "    gl_FragColor = qColor;\n"
        "}\n";

    QGLShaderProgram *program =
        painter->cachedProgram(QLatin1String("qt.color.pervertex"));
    d->program = program;
    if (!program) {
        if (!flag)
            return;
        program = new QGLShaderProgram();
        program->addShaderFromSourceCode(QGLShader::Vertex, pvColorVertexShader);
        program->addShaderFromSourceCode(QGLShader::Fragment, pvColorFragmentShader);
        program->bindAttributeLocation("vertex", QGL::Position);
        program->bindAttributeLocation("color", QGL::Color);
        if (!program->link()) {
            qWarning("QGLPerVertexColorEffect::setActive(): could not link shader program");
            delete program;
            program = 0;
            return;
        }
        painter->setCachedProgram(QLatin1String("qt.color.pervertex"), program);
        d->program = program;
        d->matrixUniform = program->uniformLocation("matrix");
        program->bind();
        program->enableAttributeArray(QGL::Position);
        program->enableAttributeArray(QGL::Color);
    } else if (flag) {
        d->matrixUniform = program->uniformLocation("matrix");
        program->bind();
        program->enableAttributeArray(QGL::Position);
        program->enableAttributeArray(QGL::Color);
    } else {
        program->disableAttributeArray(QGL::Position);
        program->disableAttributeArray(QGL::Color);
        program->release();
    }
#endif
}
Example #10
0
void View::renderScene()
{
    QGLShaderProgram *shader = m_shaderPrograms["snow"];

    // Render the wireframes if enabled
    if( m_isWireframe ) {
        glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
        for(vector<SceneObject *>::iterator it = m_objects.begin(); it != m_objects.end(); it++) {
            (*it)->render(m_useVbo);
        }
    }

    // Render the solid scene
    if( m_isSolid ) {
        glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );

        // Enable cube maps and draw the skybox
        if( m_showSkybox )
        {
            glDisable(GL_LIGHTING);
            glEnable(GL_TEXTURE_CUBE_MAP);
            glBindTexture(GL_TEXTURE_CUBE_MAP, m_cubeMap);
            GLuint sky = ResourceLoader::loadSkybox();
            glCallList(sky);
            glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
            glDisable(GL_TEXTURE_CUBE_MAP);
            glEnable(GL_LIGHTING);
        }

        for(vector<SceneObject *>::iterator it = m_objects.begin(); it != m_objects.end(); it++) {

            SceneObject *obj = *it;

            if(m_useShader){
                glEnable(GL_BLEND);
                glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

                shader->bind();
                shader->setUniformValue("snowTexture", 1);
                shader->setUniformValue("snowDisplacement", 2);
                shader->setUniformValue("localTexture", 3);
                shader->setUniformValue("snowSurfaceTexture", 4);
                shader->setUniformValue("useDisplacement", m_useDisplacement);
                Vector4 color = obj->getColor();
                shader->setUniformValue("color",color.x, color.y, color.z, color.w);
                Vector3 scale = obj->getOriginalScale();
                shader->setUniformValue("scale",scale.x, scale.y, scale.z);
                shader->setUniformValue("tesselationParam", obj->getShape()->getParamOne());

                // Set the blur data
                int radius = 6;
                int dim = radius * 2 + 1;
                GLfloat kernel[dim * dim];
                GLfloat offsets[dim * dim * 2];
                GLfloat ambientAry[4] = {0.7, 0.7, 0.7, 1.0};
                GLfloat diffuseAry[4] = {color.x, color.y, color.z, color.w};
                GLfloat specularAry[4] = {0.9, 0.9, 0.9, 0.0};
                GLfloat m = 0.55;
                GLfloat r0 = 0.7;
                ShaderAssistant::createBlurKernel(radius, width(), height(), &kernel[0], &offsets[0]);
                shader->setUniformValue("arraySize", dim * dim);
                shader->setUniformValueArray("offsets", offsets, 2 * dim * dim, 2);
                shader->setUniformValueArray("ambient", ambientAry, 1, 4);
                shader->setUniformValueArray("diffuse", diffuseAry, 1, 4);
                shader->setUniformValueArray("specular", specularAry, 1, 4);
                shader->setUniformValue("m", m);
                shader->setUniformValue("r0", r0);

                // Displacement
                ResourceLoader::reloadHeightMapTexture(obj->getDisplacementMap(),obj->getDisplacementMapId());
                glActiveTexture(GL_TEXTURE2);
                //glUniform1i(glGetUniformLocation(shader->programId(), "snowDisplacement"), 0);
                glBindTexture(GL_TEXTURE_2D,obj->getDisplacementMapId());


                // Bump
                glActiveTexture(GL_TEXTURE1);
                //QImage img = QGLWidget::convertToGLFormat((* obj->getBumpMap()).mirrored(false,true));
                if(!m_usePbo){
                    ResourceLoader::reloadHeightMapTexture(obj->getBumpMap(),obj->getBumpMapId());
                    glBindTexture(GL_TEXTURE_2D,obj->getBumpMapId());
                }else{
                    m_pboIndexA = (m_pboIndexA + 1) % 2;
                    m_pboIndexB = (m_pboIndexA + 1) % 2;

                    glBindTexture(GL_TEXTURE_2D,obj->getBumpMapId());
                    glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, obj->getPboBuffers()[m_pboIndexA]);

                    //PBO -> Texture
                    int width = obj->getBumpMap()->width();
                    int height = obj->getBumpMap()->height();
                    glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, height, width, GL_BGRA, GL_UNSIGNED_BYTE, 0);

                    int imgSize = width * height* sizeof(BGRA);
                    glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, obj->getPboBuffers()[m_pboIndexB]);
                    glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, imgSize, 0, GL_STREAM_DRAW_ARB);
                    GLubyte* ptr = (GLubyte*)glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_WRITE_ONLY_ARB);
                    if(ptr){
                        unsigned char *pixel = (unsigned char *)ptr;
                        /*for (int i = 0; i < img.height(); i++) {
                            memcpy(pixel, img.scanLine(i), img.bytesPerLine());
                            pixel += img.bytesPerLine();
                        }*/
                        memcpy(pixel, obj->getBumpMap()->bits(), obj->getBumpMap()->byteCount());
                        glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB);
                    }
                    glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
                }

                if( obj->getColorTexture() != 0 ) {
                    shader->setUniformValue("useLocalTexture", true);
                    glActiveTexture(GL_TEXTURE3);
                    glBindTexture(GL_TEXTURE_2D, obj->getColorTexture());
                } else {
                    shader->setUniformValue("useLocalTexture", false);
                }

                glActiveTexture(GL_TEXTURE4);
                glBindTexture(GL_TEXTURE_2D, m_snowTextureId);

                glActiveTexture(GL_TEXTURE0);
            }
            (*it)->render(m_useVbo);
            if( m_useShader )
            {
                shader->release();
                glBindTexture(GL_TEXTURE_2D,0);
                glDisable(GL_BLEND);
            }
        }


    }
    glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
}
Example #11
0
    /// @overload QGLWidget
    void initializeGL(){     
        printf("OpenGL %d.%d\n",this->format().majorVersion(),this->format().minorVersion());
 
        ///--- Background
        glClearColor(1.0, 1.0, 1.0, 1.0);
        
        ///--- Viewport (simple, for unresizeable window)
        glViewport(0, 0, this->width(), this->height());
        
        ///--- Setup opengl flags
        glEnable(GL_DEPTH_TEST);
        
        ///--- Create the triangle index buffer
        {
            assert(mesh.is_triangle_mesh());
            triangles.clear();
            for(auto f: mesh.faces())
                for(auto v: mesh.vertices(f))
                    triangles.push_back(v.idx());
        }
        
        ///--- Create an array object to store properties
        {
            bool success = vao.create();
            assert(success);
            vao.bind();
        }
        
        ///--- Load/compile shaders
        {
            bool vok = program.addShaderFromSourceFile(QGLShader::Vertex, ":/vshader.glsl");
            bool fok = program.addShaderFromSourceFile(QGLShader::Fragment, ":/fshader.glsl");
            bool lok = program.link ();
            assert(lok && vok && fok);
            bool success = program.bind();
            assert(success);
        }
        
        ///--- Create vertex buffer/attributes "position"
        {
            auto vpoints = mesh.get_vertex_property<Vec3>("v:point");
            bool success = vertexbuffer.create();
            assert(success);
            vertexbuffer.setUsagePattern( QGLBuffer::StaticDraw ); 
            success = vertexbuffer.bind();
            assert(success);
            vertexbuffer.allocate( vpoints.data(), sizeof(Vec3) * mesh.n_vertices() );
            program.setAttributeBuffer("vpoint", GL_FLOAT, 0, 3 );
            program.enableAttributeArray("vpoint");
        }
        
        ///--- Create vertex buffer/attributes "normal"
        {
            auto vnormal = mesh.get_vertex_property<Vec3>("v:normal");
            bool success = normalbuffer.create();
            assert(success);
            normalbuffer.setUsagePattern( QGLBuffer::StaticDraw ); 
            success = normalbuffer.bind();
            assert(success);
            normalbuffer.allocate( vnormal.data(), sizeof(Vec3) * mesh.n_vertices() );
            program.setAttributeBuffer("vnormal", GL_FLOAT, 0, 3 );
            program.enableAttributeArray("vnormal");
        }
        
        ///--- Create the index "triangle" buffer
        {
            bool success = indexbuffer.create();
            assert(success);
            indexbuffer.setUsagePattern( QGLBuffer::StaticDraw ); 
            success = indexbuffer.bind();
            assert(success);
            indexbuffer.allocate(&triangles[0], triangles.size()*sizeof(unsigned int));
        }
        
#ifdef WITH_QGLVIEWER
        ///--- Setup camera
        {        
            Box3 bbox = OpenGP::bounding_box(mesh);
            camera()->setType(qglviewer::Camera::ORTHOGRAPHIC);
            camera()->setSceneCenter(qglviewer::tr(bbox.center()));
            camera()->setSceneRadius(bbox.diagonal().norm()/2.0);
            camera()->showEntireScene();
        }
#endif
        
        ///--- Unbind to avoid pollution
        vao.release();
        program.release();
    }
Example #12
0
void GLWidget::drawPoint(const Vector& pos, float r, float g, float b) 
{
    static bool created = false;
    static QGLShaderProgram program;
    static GLuint VAO;

    if (!created)
    {
        created = true;
        // 1. Create shaders
        QGLShader vs(QGLShader::Vertex);
        vs.compileSourceCode("#version 330 core \n in vec3 vertex; in vec3 color; uniform mat4 modelViewProjectionMatrix; out vec4 frontColor;    void main() { frontColor = vec4(color,1); gl_Position = modelViewProjectionMatrix * vec4(vertex, 1.0); }");
        QGLShader fs(QGLShader::Fragment);
        fs.compileSourceCode("#version 330 core \n in vec4 frontColor; out vec4 FragColor; void main() {FragColor = frontColor;}");	
        program.addShader(&vs);
        program.addShader(&fs);
        program.link();

        // Get location of VS attributes
        GLuint vertexLoc = program.attributeLocation("vertex");
        GLuint colorLoc  = program.attributeLocation("color");

        // 2. Create VBO Buffers

        // Create & bind empty VAO
        glGenVertexArrays(1, &VAO);
        glBindVertexArray(VAO);
        // Create VBO with (x,y,z) coordinates
        float coords[] = { 0, 0, 0}; 
        GLuint VBO_coords;
        glGenBuffers(1, &VBO_coords);
        glBindBuffer(GL_ARRAY_BUFFER, VBO_coords);
        glBufferData(GL_ARRAY_BUFFER, sizeof(coords), coords, GL_STATIC_DRAW);
        glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
        glEnableVertexAttribArray(vertexLoc);
        // Create VBO with (r,g,b) color
        float colors[] = {r, g, b};
        GLuint VBO_colors;
        glGenBuffers(1, &VBO_colors);
        glBindBuffer(GL_ARRAY_BUFFER, VBO_colors);
        glBufferData(GL_ARRAY_BUFFER, sizeof(colors), colors, GL_STATIC_DRAW);
        glVertexAttribPointer(colorLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
        glEnableVertexAttribArray(colorLoc);

        glBindVertexArray(0);
    }

    program.bind();

    // 1. Define uniforms
    QMatrix4x4 T;
    T.translate(pos); 
    QMatrix4x4 MVP = camera()->projectionMatrix() * camera()->modelviewMatrix()*T;
    program.setUniformValue("modelViewProjectionMatrix", MVP);    

    // 2. Draw
    glPointSize(8);
    glBindVertexArray (VAO);
    glDrawArrays(GL_POINTS, 0, 1);
    glBindVertexArray(0);
    program.release();
}
Example #13
0
void GLWidget::drawAxes() 
{
    float L = 1;

    static bool created = false;
    static QGLShaderProgram program;
    static GLuint VAO_axes;

    if (!created)
    {
        created = true;
        // 1. Create shaders

        // VS 
        QGLShader vs(QGLShader::Vertex);
        vs.compileSourceCode("#version 330 core \n in vec3 vertex; in vec3 color; uniform mat4 modelViewProjectionMatrix; out vec4 frontColor;    void main() { frontColor = vec4(color,1); gl_Position = modelViewProjectionMatrix * vec4(vertex, 1.0); }");

        // FS    
        QGLShader fs(QGLShader::Fragment);
        fs.compileSourceCode("#version 330 core \n in vec4 frontColor; out vec4 FragColor; void main() {FragColor = frontColor;}");	

        // Program
        program.addShader(&vs);
        program.addShader(&fs);
        program.link();

        // Get location of VS attributes
        GLuint vertexLoc = program.attributeLocation("vertex");
        GLuint colorLoc  = program.attributeLocation("color");

        // 2. Create VBO Buffers

        // Create & bind empty VAO
        glGenVertexArrays(1, &VAO_axes);
        glBindVertexArray(VAO_axes);


        // Create VBO with (x,y,z) coordinates
        
        float coords[] = { 0, 0, 0, 
                           L, 0, 0, 
                           0, 0, 0, 
                           0, L, 0,
                           0, 0, 0,
                           0, 0, L};

        GLuint VBO_coords;
        glGenBuffers(1, &VBO_coords);
        glBindBuffer(GL_ARRAY_BUFFER, VBO_coords);
        glBufferData(GL_ARRAY_BUFFER, sizeof(coords), coords, GL_STATIC_DRAW);
        glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
        glEnableVertexAttribArray(vertexLoc);

        // Create VBO with (r,g,b) color
        float colors[] = {1, 0, 0, 1, 0, 0, 
                          0, 1, 0, 0, 1, 0,
                          0, 0, 1, 0, 0, 1};
        GLuint VBO_colors;
        glGenBuffers(1, &VBO_colors);
        glBindBuffer(GL_ARRAY_BUFFER, VBO_colors);
        glBufferData(GL_ARRAY_BUFFER, sizeof(colors), colors, GL_STATIC_DRAW);
        glVertexAttribPointer(colorLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
        glEnableVertexAttribArray(colorLoc);

        glBindVertexArray(0);


    }

    program.bind();

    // 1. Define uniforms 
    float r = max(MIN_AXES_LENGTH, scene()->boundingBox().radius());
    QMatrix4x4 scale;
    scale.scale(r,r,r);
    QMatrix4x4 MVP = camera()->projectionMatrix() * camera()->modelviewMatrix()*scale;
    program.setUniformValue("modelViewProjectionMatrix", MVP);    

    // 2. Draw
    glBindVertexArray (VAO_axes);
    glDrawArrays(GL_LINES, 0, 6);
    glBindVertexArray(0);

    program.release();

    // 5. CleanUp
    /*
    glDeleteVertexArrays(1, &VAO_axes);
    glDeleteBuffers(1, &VBO_coords);
    glDeleteBuffers(1, &VBO_colors);
    */
    
/* 
    glDisable(GL_LIGHTING);
    glBegin(GL_LINES);
    glColor3f(1,0,0); glVertex3f(0,0,0); glVertex3f(L,0,0); // X
    glColor3f(0,1,0); glVertex3f(0,0,0); glVertex3f(0,L,0); // Y
    glColor3f(0,0,1); glVertex3f(0,0,0); glVertex3f(0,0,L); // Z
    glEnd();
    glEnable(GL_LIGHTING);
   */ 

}
void PerspectiveView::glPass(GLResourceContext &ctx)
{
    glEnable(GL_DEPTH_TEST);

    QMatrix4x4 cameraProjM = _camera->getProjMatrix(width(), height());
    QMatrix4x4 cameraViewM = _camera->getViewMatrix(width(), height());
    QMatrix4x4 cameraProjViewM = cameraProjM * cameraViewM;
    QMatrix4x4 objToWorld;

    Scene* scene = Scene::activeScene();

    // render each mesh
    QHashIterator<QString,Mesh*> meshes = scene->meshes();
    while (meshes.hasNext()) {
        meshes.next();
        Mesh* mesh = meshes.value();

        // make sure a texture exists for this mesh
        if (!hasMeshTexture(mesh)) {
            std::cout << "creating mesh texture" << std::endl;

            QOpenGLFramebufferObject* transferFbo = ctx.transferFbo();

            transferFbo->bind();

            GLuint textureId;
            glGenTextures(1, &textureId);

            glActiveTexture(GL_TEXTURE0);
            glBindTexture(GL_TEXTURE_2D, textureId);
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 256, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);

            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

            glClearColor(.5,.5,.5,1);
            glClear(GL_COLOR_BUFFER_BIT);

            glMatrixMode(GL_PROJECTION);
            glLoadIdentity();
            glOrtho(0,1,0,1,-1,1);
            glMatrixMode(GL_MODELVIEW);
            glLoadIdentity();

            glViewport(0, 0, 256, 256);

            glColor3f(.8,.8,.8);
            glBegin(GL_QUADS);
            {
                glVertex2f(.25,.25);
                glVertex2f(.75,.25);
                glVertex2f(.75,.75);
                glVertex2f(.25,.75);
            }
            glEnd();

            glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, 256, 256, 0);


            transferFbo->release();

            //glActiveTexture(GL_TEXTURE0);
            //QImage img("/tmp/lena.jpg");
            //QImage image = QGLWidget::convertToGLFormat(img);
            //glTexSubImage2D(GL_TEXTURE_2D, 0, 0,0 , image.width(), image.height(),  GL_RGB, GL_UNSIGNED_BYTE, image.bits() );


            glViewport(0, 0, width(), height());

            setMeshTexture(mesh, textureId);
        }

        QOpenGLFramebufferObject* paintFbo = ctx.paintFbo();

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, meshTexture(mesh));
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, paintFbo->texture());
        glActiveTexture(GL_TEXTURE0);

        QGLShaderProgram* meshShader = ctx.meshShader();
        meshShader->bind();
        meshShader->setUniformValue("objToWorld", objToWorld);
        meshShader->setUniformValue("cameraPV", cameraProjViewM);
        meshShader->setUniformValue("paintFboWidth", PAINT_FBO_WIDTH);
        meshShader->setUniformValue("brushColor", _brushColor.redF(), _brushColor.greenF(), _brushColor.blueF(), 1);
        meshShader->setUniformValue("meshTexture", 0);
        meshShader->setUniformValue("paintTexture", 1);

        renderMesh(mesh);

        meshShader->release();


    }

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glLoadMatrixf(cameraProjM.data());
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glLoadMatrixf(cameraViewM.data());

    glBegin(GL_LINES);
    for (int i = -10; i <= 10; i++) {
        glVertex3f(-10, 0, i);
        glVertex3f(10, 0, i);
    }
    glEnd();

    glDisable(GL_DEPTH_TEST);

    drawPaintStrokes(ctx);

    if (_bakePaintLayer) {
        bakePaintLayer(ctx);
    }
}