Ejemplo n.º 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();
    }
Ejemplo n.º 2
0
/**
    Creates a new shader program from a vert shader only
  **/
QGLShaderProgram * ResourceLoader::newVertShaderProgram(const QGLContext *context, QString vertShader)
{
    QGLShaderProgram *program = new QGLShaderProgram(context);
    program->addShaderFromSourceFile(QGLShader::Vertex, vertShader);
    program->link();
    return program;
}
Ejemplo n.º 3
0
static void blitTexture(QGLContext *ctx, GLuint texture, const QSize &viewport, const QSize &texSize, const QRect &targetRect, const QRect &sourceRect)
{
    glDisable(GL_DEPTH_TEST);
    glDisable(GL_SCISSOR_TEST);
    glDisable(GL_BLEND);
    glViewport(0, 0, viewport.width(), viewport.height());

    QGLShaderProgram *blitProgram =
        QGLEngineSharedShaders::shadersForContext(ctx)->blitProgram();
    blitProgram->bind();
    blitProgram->setUniformValue("imageTexture", 0 /*QT_IMAGE_TEXTURE_UNIT*/);

    // The shader manager's blit program does not multiply the
    // vertices by the pmv matrix, so we need to do the effect
    // of the orthographic projection here ourselves.
    QRectF r;
    qreal w = viewport.width();
    qreal h = viewport.height();
    r.setLeft((targetRect.left() / w) * 2.0f - 1.0f);
    if (targetRect.right() == (viewport.width() - 1))
        r.setRight(1.0f);
    else
        r.setRight((targetRect.right() / w) * 2.0f - 1.0f);
    r.setBottom((targetRect.top() / h) * 2.0f - 1.0f);
    if (targetRect.bottom() == (viewport.height() - 1))
        r.setTop(1.0f);
    else
        r.setTop((targetRect.bottom() / w) * 2.0f - 1.0f);

    drawTexture(r, texture, texSize, sourceRect);
}
Ejemplo n.º 4
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();
}
Ejemplo n.º 5
0
/**
    Creates a new shader program from a frag shader only
  **/
QGLShaderProgram * ResourceLoader::newFragShaderProgram(const QGLContext *context, QString fragShader)
{
    QGLShaderProgram *program = new QGLShaderProgram(context);
    program->addShaderFromSourceFile(QGLShader::Fragment, fragShader);
    program->link();
    return program;
}
Ejemplo n.º 6
0
void SliceRenderer::setShaderVars( QString target )
{
    QGLShaderProgram* program = GLFunctions::getShader( "slice" );
    int vertexLocation = program->attributeLocation( "a_position" );
    program->enableAttributeArray( vertexLocation );
    glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 3, 0 );
    GLFunctions::setTextureUniforms( program, target );
}
Ejemplo n.º 7
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();
 }
Ejemplo n.º 8
0
static void drawTree(QGLShaderProgram& prog, const TransformState& transState, const OctreeNode* node)
{
    Imath::Box3f bbox(node->center - Imath::V3f(node->halfWidth),
                      node->center + Imath::V3f(node->halfWidth));

    drawBox(transState, bbox, Imath::C3f(1), prog.programId());
    drawBox(transState, node->bbox, Imath::C3f(1,0,0), prog.programId());

    for (int i = 0; i < 8; ++i)
    {
        OctreeNode* n = node->children[i];
        if (n)
            drawTree(prog, transState, n);
    }
}
Ejemplo n.º 9
0
void Annotation::draw(QGLShaderProgram& annotationShaderProg,
                      const TransformState& transState) const
{
    glBindVertexArray(m_vao);
    GLint texture0 = glGetUniformLocation(annotationShaderProg.programId(),
                                          "texture0");
    m_texture->bind(texture0);
    annotationShaderProg.setUniformValue("annotationSize",
                                        m_texture->width(),
                                        m_texture->height());
    transState.translate(m_position)
              .setUniforms(annotationShaderProg.programId());
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    glBindTexture(GL_TEXTURE_2D, 0);
    glBindVertexArray(0);
}
Ejemplo n.º 10
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();
}
Ejemplo n.º 11
0
void AxisRenderer::drawBrush(const M3DEditLevel::Box &brush, QGLShaderProgram &program, const AxisCamera &camera)
{
    QVector<QVector3D> temp = brush.getVerticies();
    QVector<GLfloat> verts;

    //fill vector with brush verticies
    for(int i = 0; i < temp.size(); ++i){
        QVector3D vert = temp[i];
        verts.push_back(vert.x());
        verts.push_back(vert.y());
        verts.push_back(vert.z());
        verts.push_back(1.0f);
    }

    QVector<unsigned int> indicies = brush.getLineIndex();

    //bind brush buffer and fill with verticies
    QGLBuffer brushBuffer(QGLBuffer::VertexBuffer);
    brushBuffer.create();
    brushBuffer.bind();
    brushBuffer.allocate(verts.data(), sizeof(GLfloat) * verts.size());

    //bind index buffer and fill with indicies
    QGLBuffer brushIndex(QGLBuffer::IndexBuffer);
    brushIndex.create();
    brushIndex.bind();
    brushIndex.allocate(indicies.data(), sizeof(unsigned int) * indicies.size());

    //set up uniforms
    program.bind();
    program.setUniformValueArray("color", &QVector4D(1.0f, 1.0f, 1.0f, 1.0f), 1);
    program.setUniformValueArray("modelToCamera", &camera.getProjMatrix(), 1);

    //set up buffers
    brushBuffer.bind();
    program.enableAttributeArray("vertex");
    program.setAttributeBuffer("vertex", GL_FLOAT, 0, 4);

    //draw brush. NOTE: Fixed 24 indicies for a box only!
    brushIndex.bind();
    glDrawElements(GL_LINES, 24, GL_UNSIGNED_INT, 0);


}
Ejemplo n.º 12
0
void AxisRenderer::render(const AxisCamera &camera, QGLShaderProgram &program, QGLBuffer &vertBuffer, QGLBuffer &indexBuffer, bool selected)
{
    qDebug()<<"[AxisRender] start of render";

    initializeGLFunctions();

    //bind the program for use
    if(!program.bind()){
        QMessageBox::critical(0, "Error", "Could not bind program for use");
        qFatal("Could not bind program for use");
    }

    qDebug()<<"[AxisRender] Drawing";

    //set up shader locations
    program.bind();
    GLint vertLoc = program.attributeLocation("vertex");
    Q_ASSERT(vertLoc != -1);
    GLint colorLoc = program.uniformLocation("color");
    Q_ASSERT(colorLoc != -1);
    GLint mvpLoc = program.uniformLocation("modelToCamera");
    Q_ASSERT(mvpLoc != -1);

    //set default color to a cyan
    QVector4D color(0.0f, .5f, 1.0f, 1.0f);

    //modify the color for selected geometry
    if(selected){
        qDebug()<<"[AxisRender] adding selection color";
        color = color + QVector4D(1.0f, 0.0f, 0.0f, 0.0f);
    }

    //set the uniform values
    program.setUniformValueArray(colorLoc, &color, 1);
    program.setUniformValueArray(mvpLoc, &camera.getProjMatrix(), 1);

    //bind and set the vertex buffer for attribute
    vertBuffer.bind();
    program.enableAttributeArray(vertLoc);
    program.setAttributeBuffer(vertLoc, GL_FLOAT, 0, 4);

    //bind the index buffer for the draw call
    indexBuffer.bind();

    qDebug()<<"[AxisRender] Drawing";

    //draw the index buffer NOTE: Hard set to 24 values for a box!
    glDrawElements(GL_LINES, 24, GL_UNSIGNED_INT, NULL);
}
Ejemplo n.º 13
0
/*!
  Draw the particle, if effect was given in the constructor, we set the
  diffuse value for the shader in order to color the particle as same
  as the ball that hit the particle.
*/
void ExplosionParticle::draw(QGLPainter *painter)
{
    if (userEffect()) {
        QGLShaderProgram *program =
                static_cast<QGLShaderProgramEffect*>(userEffect())->program();

        if (m_DiffuseLoc == -1) {
            m_DiffuseLoc = program->uniformLocation("diffuse");
        }

        program->setUniformValue(m_DiffuseLoc, material()->diffuseColor());

        QGLSceneNode::draw(painter);

        program->setUniformValue(m_DiffuseLoc,
                                 QVector4D(1.0f, 1.0f, 1.0f, 1.0f));
    }
    else {
        QGLSceneNode::draw(painter);
    }
}
Ejemplo n.º 14
0
void TriMesh::drawFaces(QGLShaderProgram& prog,
                        const TransformState& transState) const
{
    transState.translate(offset()).setUniforms(prog.programId());
    prog.enableAttributeArray("position");
    prog.enableAttributeArray("normal");
    prog.setAttributeArray("position", GL_FLOAT, &m_verts[0], 3);
    prog.setAttributeArray("normal", GL_FLOAT, &m_normals[0], 3);
    if (m_colors.size() == m_verts.size())
    {
        prog.enableAttributeArray("color");
        prog.setAttributeArray("color", GL_FLOAT, &m_colors[0], 3);
    }
    else
        prog.setAttributeValue("color", GLfloat(1), GLfloat(1), GLfloat(1));
    glDrawElements(GL_TRIANGLES, (GLsizei)m_faces.size(),
                   GL_UNSIGNED_INT, &m_faces[0]);
    prog.disableAttributeArray("color");
    prog.disableAttributeArray("position");
    prog.disableAttributeArray("normal");
}
Ejemplo n.º 15
0
void TriMesh::drawFaces(QGLShaderProgram& prog,
                        const TransformState& transState) const
{
    // TODO: The hasTexture uniform shader variable would be unnecessary if we
    // supported more than one mesh face shader...
    GLint hasTextureLoc = glGetUniformLocation(prog.programId(), "hasTexture");
    if (m_texture)
    {
        GLint textureSamplerLoc = glGetUniformLocation(prog.programId(), "texture0");
        if (textureSamplerLoc != -1)
            m_texture->bind(textureSamplerLoc);
    }
    if (hasTextureLoc != -1)
        glUniform1i(hasTextureLoc, m_texture ? 1 : 0);
    unsigned int vertexShaderId = shaderId("meshface");
    unsigned int vertexArray = getVAO("meshface");

    transState.translate(offset()).setUniforms(vertexShaderId);

    glBindVertexArray(vertexArray);
    glDrawElements(GL_TRIANGLES, (GLsizei)m_triangles.size(), GL_UNSIGNED_INT, 0);
    glBindVertexArray(0);
}
Ejemplo n.º 16
0
// --------------------------------------------------------
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();
}
Ejemplo n.º 17
0
// See programCache doc comments to see how caching works here.
bool StelQGLGLSLShader::build()
{
	// Unlocked - i.e. not Modified
	if(state == State_Unlocked && program != NULL)
	{
		state = State_Built;
		return true;
	}

	QGLShaderProgram* cached = getProgramFromCache();
	// No matching program in cache, need to link a new program.
	if(cached == NULL)
	{
		uintptr_t id = 0;
		QGLShaderProgram* newProgram = new QGLShaderProgram(renderer->getGLContext());

		// Add all the shaders to the program.
		foreach(QGLShader* shader, defaultVertexShaders)
		{
			if(!newProgram->addShader(shader)) {goto FAILED;}
			id += reinterpret_cast<uintptr_t>(shader);
		}
		foreach(OptionalShader shader, namedVertexShaders)
		{
			if(shader.enabled)
			{
				if(!newProgram->addShader(shader.shader)) {goto FAILED;}
				id += reinterpret_cast<uintptr_t>(shader.shader);
			}
		}
		foreach(QGLShader* shader, defaultFragmentShaders)
		{
			if(!newProgram->addShader(shader)) {goto FAILED;}
			id += reinterpret_cast<uintptr_t>(shader);
		}
		Q_ASSERT_X(id > 0, Q_FUNC_INFO, "Trying to build() a StelQGLGLSLShader "
		           "but no vertex or fragment shaders were added");

		// Link the program.
		if(!newProgram->link()) {goto FAILED;}

		aggregatedLog += "Built successfully";
		// Add the program to the cache, and set the current program to it.
		programCache.insert(id, newProgram);
		program = newProgram;
		state = State_Built;
		return true;

		// And here I present to you a viable application of the fabled GOTO statement and a label.
		// (good way to do error recovery in plan C and when using return codes, BTW)
FAILED:
		aggregatedLog += newProgram->log();
		delete newProgram;
		return false;
	}
Ejemplo n.º 18
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);
 }
Ejemplo n.º 19
0
//
//  Load shader
//
void Ex07opengl::Shader(QGLShaderProgram& shader,QString vert,QString frag)
{
    //  Vertex shader
    if (vert.length() && !shader.addShaderFromSourceFile(QGLShader::Vertex,vert))
        Fatal("Error compiling "+vert+"\n"+shader.log());
    //  Fragment shader
    if (frag.length() && !shader.addShaderFromSourceFile(QGLShader::Fragment,frag))
        Fatal("Error compiling "+frag+"\n"+shader.log());
    //  Link
    if (!shader.link())
        Fatal("Error linking shader\n"+shader.log());
}
Ejemplo n.º 20
0
void BinghamRenderer::setShaderVars( PropertyGroup& props )
{
    QGLShaderProgram* program = GLFunctions::getShader( "qball" );
    program->bind();

    intptr_t offset = 0;
    // Tell OpenGL programmable pipeline how to locate vertex position data
    int vertexLocation = program->attributeLocation( "a_position" );
    program->enableAttributeArray( vertexLocation );
    glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 7, (const void *) offset );

    offset += sizeof(float) * 3;
    int offsetLocation = program->attributeLocation( "a_offset" );
    program->enableAttributeArray( offsetLocation );
    glVertexAttribPointer( offsetLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 7, (const void *) offset );

    offset += sizeof(float) * 3;
    int radiusLocation = program->attributeLocation( "a_radius" );
    program->enableAttributeArray( radiusLocation );
    glVertexAttribPointer( radiusLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 7, (const void *) offset );
}
Ejemplo n.º 21
0
void AxisRenderer::drawCamLine(QVector3D from, QVector3D to, QGLShaderProgram &program, const AxisCamera &camera)
{
    const GLfloat color[] ={1.0f, 0.0f, 0.0f, 1.0f}; //default red color

    //temp vector to hold line verticies
    std::vector<GLfloat> bufferData;

    //from verticies
    bufferData.push_back(from.x());
    bufferData.push_back(from.y());
    bufferData.push_back(from.z());
    bufferData.push_back(1.0f);

    //to verticies
    bufferData.push_back(to.x());
    bufferData.push_back(to.y());
    bufferData.push_back(to.z());
    bufferData.push_back(1.0f);

    program.bind();

    //create and fill line buffer with verticies
    QGLBuffer line(QGLBuffer::VertexBuffer);
    line.create();
    line.bind();
    line.allocate(bufferData.data(), sizeof(GLfloat) * 8);

    //get locations
    GLuint colorLoc = program.uniformLocation("color");
    Q_ASSERT(colorLoc != -1);
    GLuint mvpLoc = program.uniformLocation("modelToCamera");
    Q_ASSERT(mvpLoc != -1);

    //setup line for drawing
    line.bind();
    program.enableAttributeArray("vertex");
    program.setAttributeBuffer("vertex", GL_FLOAT, 0, 4);
    program.setUniformValueArray(colorLoc, color, 1, 4);
    program.setUniformValueArray(mvpLoc, &(camera.getProjMatrix()), 1);

    glDrawArrays(GL_LINES, 0, 2);
}
Ejemplo n.º 22
0
bool GLWidgetRendererPrivate::releaseShaderProgram()
{
    video_format.setPixelFormat(VideoFormat::Format_Invalid);
#if NO_QGL_SHADER
    if (vert) {
        if (program)
            glDetachShader(program, vert);
        glDeleteShader(vert);
    }
    if (frag) {
        if (program)
            glDetachShader(program, frag);
        glDeleteShader(frag);
    }
    if (program) {
        glDeleteProgram(program);
        program = 0;
    }
#else
    shader_program->removeAllShaders();
#endif
    return true;
}
Ejemplo n.º 23
0
bool prepareShaderProgram( QGLShaderProgram& program,
                           const QString& vertexShaderPath,
                           const QString& fragmentShaderPath )
{
    // First we load and compile the vertex shader...
    bool result = program.addShaderFromSourceFile( QGLShader::Vertex, vertexShaderPath );
    if ( !result )
        qWarning() << program.log();

    // ...now the fragment shader...
    result = program.addShaderFromSourceFile( QGLShader::Fragment, fragmentShaderPath );
    if ( !result )
        qWarning() << program.log();

    // ...and finally we link them to resolve any references.
    result = program.link();
    if ( !result )
        qWarning() << "Could not link shader program:" << program.log();

    return result;
}
Ejemplo n.º 24
0
// --------------------------------------------------------
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();
}
Ejemplo n.º 25
0
void QGLTextureGlyphCache::resizeTextureData(int width, int height)
{
    if (ctx == 0) {
        qWarning("QGLTextureGlyphCache::resizeTextureData: Called with no context");
        return;
    }
    QGLGlyphTexture *glyphTexture = m_textureResource.value(ctx);

    int oldWidth = glyphTexture->m_width;
    int oldHeight = glyphTexture->m_height;

    // Make the lower glyph texture size 16 x 16.
    if (width < 16)
        width = 16;
    if (height < 16)
        height = 16;

    GLuint oldTexture = glyphTexture->m_texture;
    createTextureData(width, height);

    if (ctx->d_ptr->workaround_brokenFBOReadBack) {
        QImageTextureGlyphCache::resizeTextureData(width, height);
        Q_ASSERT(image().depth() == 8);
        glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, oldHeight, GL_ALPHA, GL_UNSIGNED_BYTE, image().constBits());
        glDeleteTextures(1, &oldTexture);
        return;
    }

    // ### the QTextureGlyphCache API needs to be reworked to allow
    // ### resizeTextureData to fail

    glBindFramebuffer(GL_FRAMEBUFFER_EXT, glyphTexture->m_fbo);

    GLuint tmp_texture;
    glGenTextures(1, &tmp_texture);
    glBindTexture(GL_TEXTURE_2D, tmp_texture);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, oldWidth, oldHeight, 0,
                 GL_RGBA, GL_UNSIGNED_BYTE, NULL);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    m_filterMode = Nearest;
    glBindTexture(GL_TEXTURE_2D, 0);
    glFramebufferTexture2D(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
                           GL_TEXTURE_2D, tmp_texture, 0);

    glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
    glBindTexture(GL_TEXTURE_2D, oldTexture);

    if (pex != 0)
        pex->transferMode(BrushDrawingMode);

    glDisable(GL_STENCIL_TEST);
    glDisable(GL_DEPTH_TEST);
    glDisable(GL_SCISSOR_TEST);
    glDisable(GL_BLEND);

    glViewport(0, 0, oldWidth, oldHeight);

    QGLShaderProgram *blitProgram = 0;
    if (pex == 0) {
        if (m_blitProgram == 0) {
            m_blitProgram = new QGLShaderProgram(ctx);

            {
                QString source;
                source.append(QLatin1String(qglslMainWithTexCoordsVertexShader));
                source.append(QLatin1String(qglslUntransformedPositionVertexShader));

                QGLShader *vertexShader = new QGLShader(QGLShader::Vertex, m_blitProgram);
                vertexShader->compileSourceCode(source);

                m_blitProgram->addShader(vertexShader);
            }

            {
                QString source;
                source.append(QLatin1String(qglslMainFragmentShader));
                source.append(QLatin1String(qglslImageSrcFragmentShader));

                QGLShader *fragmentShader = new QGLShader(QGLShader::Fragment, m_blitProgram);
                fragmentShader->compileSourceCode(source);

                m_blitProgram->addShader(fragmentShader);
            }

            m_blitProgram->bindAttributeLocation("vertexCoordsArray", QT_VERTEX_COORDS_ATTR);
            m_blitProgram->bindAttributeLocation("textureCoordArray", QT_TEXTURE_COORDS_ATTR);

            m_blitProgram->link();
        }

        glVertexAttribPointer(QT_VERTEX_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, m_vertexCoordinateArray);
        glVertexAttribPointer(QT_TEXTURE_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, m_textureCoordinateArray);

        m_blitProgram->bind();
        m_blitProgram->enableAttributeArray(int(QT_VERTEX_COORDS_ATTR));
        m_blitProgram->enableAttributeArray(int(QT_TEXTURE_COORDS_ATTR));
        m_blitProgram->disableAttributeArray(int(QT_OPACITY_ATTR));

        blitProgram = m_blitProgram;

    } else {
        pex->setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, m_vertexCoordinateArray);
        pex->setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, m_textureCoordinateArray);

        pex->shaderManager->useBlitProgram();
        blitProgram = pex->shaderManager->blitProgram();
    }

    blitProgram->setUniformValue("imageTexture", QT_IMAGE_TEXTURE_UNIT);

    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

    glBindTexture(GL_TEXTURE_2D, glyphTexture->m_texture);

    glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, oldWidth, oldHeight);

    glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
                              GL_RENDERBUFFER_EXT, 0);
    glDeleteTextures(1, &tmp_texture);
    glDeleteTextures(1, &oldTexture);

    glBindFramebuffer(GL_FRAMEBUFFER_EXT, ctx->d_ptr->current_fbo);

    if (pex != 0) {
        glViewport(0, 0, pex->width, pex->height);
        pex->updateClipScissorTest();
    }
}
Ejemplo n.º 26
0
void DatasetPlane::draw( QMatrix4x4 pMatrix, QMatrix4x4 mvMatrix, int width, int height, int renderMode, QString target )
{
    if ( !properties( target ).get( Fn::Property::D_ACTIVE ).toBool() )
    {
        return;
    }

    QVector3D h0 = m_properties["maingl"].get( Fn::Property::D_HANDLE_0 ).value<QVector3D>();
    QVector3D h1 = m_properties["maingl"].get( Fn::Property::D_HANDLE_1 ).value<QVector3D>();
    QVector3D h2 = m_properties["maingl"].get( Fn::Property::D_HANDLE_2 ).value<QVector3D>();

    if ( m_properties["maingl"].get( Fn::Property::D_SHOW_PLANE_HANDLES ).toBool() )
    {
        QColor color = m_properties["maingl"].get( Fn::Property::D_HANDLE_COLOR ).value<QColor>();
        color.setAlpha( 254 );
        GLFunctions::renderSphere( pMatrix, mvMatrix, h0.x(), h0.y(), h0.z(), 5, 5, 5,
                                  color, m_handle0, width, height, renderMode );
        GLFunctions::renderSphere( pMatrix, mvMatrix, h1.x(), h1.y(), h1.z(), 5, 5, 5,
                                  color, m_handle1, width, height, renderMode );
        GLFunctions::renderSphere( pMatrix, mvMatrix, h2.x(), h2.y(), h2.z(), 5, 5, 5,
                                  color, m_handle2, width, height, renderMode );
    }

    if ( dirty )
    {
        initGeometry();
    }

    float alpha = GLFunctions::sliceAlpha[target];

    switch ( renderMode )
    {
        case 0:
            break;
        case 1:
        {
            if ( alpha < 1.0 ) // obviously not opaque
            {
                return;
            }
            break;
        }
        default:
        {
            if ( alpha == 1.0  ) // not transparent
            {
                return;
            }
            break;
        }
    }

    if ( !GLFunctions::setupTextures() )
    {
        return;
    }
    QGLShaderProgram* program = GLFunctions::getShader( "slice" );

    program->bind();
    GLFunctions::f->glBindBuffer( GL_ARRAY_BUFFER, vbo0 );

    intptr_t offset = 0;
    // Tell OpenGL programmable pipeline how to locate vertex position data
    int vertexLocation = program->attributeLocation( "a_position" );
    program->enableAttributeArray( vertexLocation );
    GLFunctions::f->glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 3, (const void *) offset );

    // Set modelview-projection matrix
    program->setUniformValue( "mvp_matrix", pMatrix * mvMatrix );

    program->setUniformValue( "u_alpha", alpha );
    program->setUniformValue( "u_renderMode", renderMode );
    program->setUniformValue( "u_canvasSize", width, height );
    program->setUniformValue( "D0", 9 );
    program->setUniformValue( "D1", 10 );
    program->setUniformValue( "D2", 11 );
    program->setUniformValue( "P0", 12 );

    GLFunctions::setTextureUniforms( program, target );

    // Draw cube geometry using indices from VBO 0
    glDrawArrays( GL_TRIANGLE_STRIP, 0, 4 );
    GLFunctions::f->glBindBuffer( GL_ARRAY_BUFFER, 0 );

}
Ejemplo n.º 27
0
Object *SceneParser::loadObject(KeyValues *data)
{
  const char *format = data->getString("format");
  if(!format) {
    fprintf(stderr, "Key 'format' not found on Object\n");
    return NULL;
  }

  Mesh *mesh;
  if(strcmp("OFF", format) == 0 || strcmp("PLY", format) == 0) {
    const char *file = data->getString("file");
    if(!file) {
      fprintf(stderr, "Key 'file' not found on Object\n");
      return NULL;
    }
    char *filename = resolvePath(file);

    MeshData *meshData;

    if(strcmp("OFF", format) == 0) {
      meshData = MeshLoaderOFF::load(filename);
    }
    else if(strcmp("PLY", format) == 0) {
      meshData = MeshLoaderPLY::load(filename);
    }

    if(!meshData) {
      fprintf(stderr, "Failed to load MeshData of %s\n", filename);
      delete[] filename;
      return NULL;
    }

    if(data->getInt("normalize", 1)) {
      meshData->normalize();
    }
    if(data->getInt("normals", 0)) {
      meshData->computeNormals();
    }

    const char *texcoords = data->getString("texcoords");
    if(texcoords) {
      MeshData::TexCoordsMethod method;
      if(strcmp(texcoords, "sphere") == 0) {
        method = MeshData::TexCoordsSphere;
      }
      else if(strcmp(texcoords, "cylinder") == 0) {
        method = MeshData::TexCoordsCylinder;
      }
      meshData->genTexCoords(method);
    }

    if(data->getInt("tangents", 0)) {
      meshData->genTangents();
    }

    mesh = new Mesh(meshData);

    delete meshData;
    delete[] filename;
  }
  else {
    fprintf(stderr, "Invalid object format: %s\n", format);
    return NULL;
  }

  Material *material = NULL;
  QGLShaderProgram *shaderProgram = new QGLShaderProgram();

  KeyValues *key;

  bool error = false;
  key = data->firstSubKey();
  while(key) {
    if(strcmp(key->name(), "shader") == 0) {
      QGLShader *shader = loadShader(key);
      if(shader) {
        shaderProgram->addShader(shader);
      }
      else {
        fprintf(stderr, "Failed to load shader\n");
        error = true;
        break;
      }
    }
    else if (strcmp(key->name(), "material") == 0) {
      if(material) {
        fprintf(stderr, "Duplicated material definition\n");
      }
      else {
        material = loadMaterial(key);
      }
    }
    key = key->nextKey();
  }

  if(!shaderProgram->link()) {
    fprintf(stderr, "Failed to link shader program\n");
    error = true;
  }

  if(error) {
    if(material) {
      delete material;
    }
    delete shaderProgram;
    delete mesh;
    return NULL;
  }

  Object *object = new Object(mesh, shaderProgram, material);

  object->scale(data->getFloat("scale", 1.0));

  float pitch = data->getFloat("pitch", 0.0);
  float yaw = data->getFloat("yaw", 0.0);
  object->rotation(pitch, yaw);

  const char *position = data->getString("position");
  if(position) {
    object->position(strtoV3D(position));
  }

  key = data->firstSubKey();
  while(key) {
    if (strcmp(key->name(), "texture") == 0) {
      Texture *texture = loadTexture(key);
      if(texture) {
        object->addTexture(texture);
      }
      else {
        fprintf(stderr, "Failed to load texture\n");
        error = true;
        break;
      }
    }
    key = key->nextKey();
  }

  if(error) {
    return object;
  }

  return object;
}
Ejemplo n.º 28
0
DrawCount PointArray::drawPoints(QGLShaderProgram& prog, const TransformState& transState,
                                 double quality, bool incrementalDraw) const
{
    TransformState relativeTrans = transState.translate(offset());
    relativeTrans.setUniforms(prog.programId());
    //printActiveShaderAttributes(prog.programId());
    std::vector<ShaderAttribute> activeAttrs = activeShaderAttributes(prog.programId());
    // Figure out shader locations for each point field
    // TODO: attributeLocation() forces the OpenGL usage here to be
    // synchronous.  Does this matter?  (Alternative: bind them ourselves.)
    std::vector<const ShaderAttribute*> attributes;
    for (size_t i = 0; i < m_fields.size(); ++i)
    {
        const GeomField& field = m_fields[i];
        if (field.spec.isArray())
        {
            for (int j = 0; j < field.spec.count; ++j)
            {
                std::string name = tfm::format("%s[%d]", field.name, j);
                attributes.push_back(findAttr(name, activeAttrs));
            }
        }
        else
        {
            attributes.push_back(findAttr(field.name, activeAttrs));
        }
    }
    // Zero out active attributes in case they don't have associated fields
    GLfloat zeros[16] = {0};
    for (size_t i = 0; i < activeAttrs.size(); ++i)
    {
        prog.setAttributeValue((int)i, zeros, activeAttrs[i].rows,
                               activeAttrs[i].cols);
    }
    // Enable attributes which have associated fields
    for (size_t i = 0; i < attributes.size(); ++i)
    {
        if (attributes[i])
            prog.enableAttributeArray(attributes[i]->location);
    }

    DrawCount drawCount;
    ClipBox clipBox(relativeTrans);

    // Draw points in each bucket, with total number drawn depending on how far
    // away the bucket is.  Since the points are shuffled, this corresponds to
    // a stochastic simplification of the full point cloud.
    V3f relCamera = relativeTrans.cameraPos();
    std::vector<const OctreeNode*> nodeStack;
    nodeStack.push_back(m_rootNode.get());
    while (!nodeStack.empty())
    {
        const OctreeNode* node = nodeStack.back();
        nodeStack.pop_back();
        if (clipBox.canCull(node->bbox))
            continue;
        if (!node->isLeaf())
        {
            for (int i = 0; i < 8; ++i)
            {
                OctreeNode* n = node->children[i];
                if (n)
                    nodeStack.push_back(n);
            }
            continue;
        }
        size_t idx = node->beginIndex;
        if (!incrementalDraw)
            node->nextBeginIndex = node->beginIndex;

        DrawCount nodeDrawCount = node->drawCount(relCamera, quality, incrementalDraw);
        drawCount += nodeDrawCount;

        idx = node->nextBeginIndex;
        if (nodeDrawCount.numVertices == 0)
            continue;
        for (size_t i = 0, k = 0; i < m_fields.size(); k+=m_fields[i].spec.arraySize(), ++i)
        {
            const GeomField& field = m_fields[i];
            int arraySize = field.spec.arraySize();
            int vecSize = field.spec.vectorSize();
            for (int j = 0; j < arraySize; ++j)
            {
                const ShaderAttribute* attr = attributes[k+j];
                if (!attr)
                    continue;
                char* data = field.data.get() + idx*field.spec.size() +
                             j*field.spec.elsize;
                if (attr->baseType == TypeSpec::Int || attr->baseType == TypeSpec::Uint)
                {
                    glVertexAttribIPointer(attr->location, vecSize,
                                           glBaseType(field.spec), 0, data);
                }
                else
                {
                    glVertexAttribPointer(attr->location, vecSize,
                                          glBaseType(field.spec),
                                          field.spec.fixedPoint, 0, data);
                }
            }
        }
        glDrawArrays(GL_POINTS, 0, (GLsizei)nodeDrawCount.numVertices);
        node->nextBeginIndex += nodeDrawCount.numVertices;
    }
    //tfm::printf("Drew %d of total points %d, quality %f\n", totDraw, m_npoints, quality);

    // Disable all attribute arrays - leaving these enabled seems to screw with
    // the OpenGL fixed function pipeline in unusual ways.
    for (size_t i = 0; i < attributes.size(); ++i)
    {
        if (attributes[i])
            prog.disableAttributeArray(attributes[i]->location);
    }
    return drawCount;
}
Ejemplo n.º 29
0
Archivo: glwidget.cpp Proyecto: 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;
    }

}
Ejemplo n.º 30
0
bool GLWidgetRendererPrivate::prepareShaderProgram(const VideoFormat &fmt, ColorTransform::ColorSpace cs)
{
    // isSupported(pixfmt)
    if (!fmt.isValid())
        return false;
    releaseShaderProgram();
    video_format.setPixelFormatFFmpeg(fmt.pixelFormatFFmpeg());
    colorTransform.setInputColorSpace(cs);
    // TODO: only to kinds, packed.glsl, planar.glsl
    QString frag;
    if (fmt.isPlanar()) {
        frag = getShaderFromFile("shaders/planar.f.glsl");
    } else {
        frag = getShaderFromFile("shaders/rgb.f.glsl");
    }
    if (frag.isEmpty())
        return false;
    if (fmt.isRGB()) {
        frag.prepend("#define INPUT_RGB\n");
    } else {
        frag.prepend(QString("#define YUV%1P\n").arg(fmt.bitsPerPixel(0)));
    }
    if (fmt.isPlanar() && fmt.bytesPerPixel(0) == 2) {
        if (fmt.isBigEndian())
            frag.prepend("#define LA_16BITS_BE\n");
        else
            frag.prepend("#define LA_16BITS_LE\n");
    }
    if (cs == ColorTransform::BT601) {
        frag.prepend("#define CS_BT601\n");
    } else if (cs == ColorTransform::BT709) {
        frag.prepend("#define CS_BT709\n");
    }
#if NO_QGL_SHADER
    program = createProgram(kVertexShader, frag.toUtf8().constData());
    if (!program) {
        qWarning("Could not create shader program.");
        return false;
    }
    // vertex shader. we can set attribute locations calling glBindAttribLocation
    a_Position = glGetAttribLocation(program, "a_Position");
    a_TexCoords = glGetAttribLocation(program, "a_TexCoords");
    u_matrix = glGetUniformLocation(program, "u_MVP_matrix");
    u_bpp = glGetUniformLocation(program, "u_bpp");
    u_opacity = glGetUniformLocation(program, "u_opacity");
    // fragment shader
    u_colorMatrix = glGetUniformLocation(program, "u_colorMatrix");
#else
    if (!shader_program->addShaderFromSourceCode(QGLShader::Vertex, kVertexShader)) {
        qWarning("Failed to add vertex shader: %s", shader_program->log().toUtf8().constData());
        return false;
    }
    if (!shader_program->addShaderFromSourceCode(QGLShader::Fragment, frag)) {
        qWarning("Failed to add fragment shader: %s", shader_program->log().toUtf8().constData());
        return false;
    }
    if (!shader_program->link()) {
        qWarning("Failed to link shader program...%s", shader_program->log().toUtf8().constData());
        return false;
    }
    // vertex shader
    a_Position = shader_program->attributeLocation("a_Position");
    a_TexCoords = shader_program->attributeLocation("a_TexCoords");
    u_matrix = shader_program->uniformLocation("u_MVP_matrix");
    u_bpp = shader_program->uniformLocation("u_bpp");
    u_opacity = shader_program->uniformLocation("u_opacity");
    // fragment shader
    u_colorMatrix = shader_program->uniformLocation("u_colorMatrix");
#endif //NO_QGL_SHADER
    qDebug("glGetAttribLocation(\"a_Position\") = %d\n", a_Position);
    qDebug("glGetAttribLocation(\"a_TexCoords\") = %d\n", a_TexCoords);
    qDebug("glGetUniformLocation(\"u_MVP_matrix\") = %d\n", u_matrix);
    qDebug("glGetUniformLocation(\"u_bpp\") = %d\n", u_bpp);
    qDebug("glGetUniformLocation(\"u_opacity\") = %d\n", u_opacity);
    qDebug("glGetUniformLocation(\"u_colorMatrix\") = %d\n", u_colorMatrix);

    if (fmt.isRGB())
        u_Texture.resize(1);
    else
        u_Texture.resize(fmt.channels());
    for (int i = 0; i < u_Texture.size(); ++i) {
        QString tex_var = QString("u_Texture%1").arg(i);
#if NO_QGL_SHADER
        u_Texture[i] = glGetUniformLocation(program, tex_var.toUtf8().constData());
#else
        u_Texture[i] = shader_program->uniformLocation(tex_var);
#endif
        qDebug("glGetUniformLocation(\"%s\") = %d\n", tex_var.toUtf8().constData(), u_Texture[i]);
    }
    return true;
}