/**
    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;
}
/**
    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;
}
Esempio n. 3
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;
	}
Esempio n. 4
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());
}
Esempio n. 5
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);
 }
Esempio n. 6
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;
}
Esempio n. 7
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;
}
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;
}
Esempio n. 9
0
QGLPEXShaderManager::QGLPEXShaderManager(const QGLContext* context)
{
    ctx = const_cast<QGLContext*>(context);

    defaultVertexShader= new QGLShader(QGLShader::VertexShader, context);
    defaultVertexShader->addSource(QLatin1String(qglslDefaultVertexShader));
    if (!defaultVertexShader->compile())
        qWarning() << "Default vertex shader failed to compile: " << defaultVertexShader->log();

    noBrushShader = new QGLShader(QGLShader::FragmentShader, context);
    noBrushShader->addSource(QLatin1String(qglslFragmentShaderMain));
    noBrushShader->addSource(QLatin1String(qglslNoBrushFragmentShader));
    if (!noBrushShader->compile())
        qWarning() << "No brush shader failed to compile:" << noBrushShader->log();


    // Create a program for noBrush:
    QGLShaderProgram* noBrushProg = new QGLShaderProgram(ctx);
    noBrushProg->addShader(defaultVertexShader);
    noBrushProg->addShader(noBrushShader);
    if (!noBrushProg->link())
        qWarning() << "NoBrush shader program failed to link:" << noBrushProg->log();

    // Add noBrush Program to cache:
    QGLCachedShaderProg cachedProg;
    cachedProg.vertexShader = defaultVertexShader;
    cachedProg.brushShader = noBrushShader;
    cachedProg.compositionShader = 0;
    cachedProg.shader = noBrushProg;
    cachedPrograms.append(cachedProg);


    // Set state
    useGlobalOpacity = true;
    currentBrushStyle = Qt::NoBrush;
    currentTransformType = FullTransform;
    shaderProgNeedsChanging = false;
    activeProgram = noBrushProg;

    solidBrushShader    = 0;

    conicalBrushVertexShader = 0;
    conicalBrushFragmentShader = 0;

    radialBrushVertexShader   = 0;
    radialBrushFragmentShader   = 0;

    linearBrushVertexShader = 0;
    linearBrushFragmentShader = 0;

    patternBrushVertexShader  = 0;
    patternBrushFragmentShader  = 0;

    textureBrushFragmentShader  = 0;
    textureBrushVertexShader  = 0;

    simpleFragmentShader = 0;
    simpleShaderProgram  = 0;

    imageVertexShader = 0;
    imageFragmentShader = 0;
    imageShaderProgram = 0;

    textVertexShader = 0;
    textFragmentShader = 0;
    textShaderProgram = 0;
}
Esempio n. 10
0
bool QGLPEXShaderManager::useCorrectShaderProg()
{
    if (!shaderProgNeedsChanging) {
        activeProgram->use();
        return false;
    }

    const char* fragmentShaderMainSrc = qglslFragmentShaderMain;
    QGLShader* vertexShader = defaultVertexShader;
    QGLShader* fragmentShader = noBrushShader;

    // Make sure we compile up the correct brush shader
    switch (currentBrushStyle) {
    case Qt::NoBrush:
        break;
    case Qt::SolidPattern:
        if (!solidBrushShader) {
            qDebug("Compiling qglslSolidBrushFragmentShader");
            solidBrushShader = new QGLShader(QGLShader::FragmentShader, ctx);
            solidBrushShader->addSource(QLatin1String(qglslNoOpacityFragmentShaderMain));
            solidBrushShader->addSource(QLatin1String(qglslSolidBrushFragmentShader));
            if (!solidBrushShader->compile())
                qWarning() << "qglslSolidBrush failed to compile:" << solidBrushShader->log();
        }
        fragmentShader = solidBrushShader;
        break;
    case Qt::TexturePattern:
        if (!textureBrushVertexShader) {
            qDebug("Compiling qglslTextureBrushVertexShader");
            textureBrushVertexShader = new QGLShader(QGLShader::VertexShader, ctx);
            textureBrushVertexShader->addSource(QLatin1String(qglslTextureBrushVertexShader));
            if (!textureBrushVertexShader->compile()) {
                qWarning() << "qglslTextureBrushVertexShader failed to compile: "
                           << textureBrushVertexShader->log();
            }
        }
        vertexShader = textureBrushVertexShader;

        if (!textureBrushFragmentShader) {
            qDebug("Compiling qglslTextureBrushFragmentShader");
            textureBrushFragmentShader = new QGLShader(QGLShader::FragmentShader, ctx);
            textureBrushFragmentShader->addSource(QLatin1String(fragmentShaderMainSrc));
            textureBrushFragmentShader->addSource(QLatin1String(qglslTextureBrushFragmentShader));
            if (!textureBrushFragmentShader->compile()) {
                qWarning() << "qglslTextureBrushFragmentShader failed to compile:"
                           << textureBrushFragmentShader->log();
            }
        }
        fragmentShader = textureBrushFragmentShader;
        break;
    case Qt::LinearGradientPattern:
        if (!linearBrushVertexShader) {
            qDebug("Compiling qglslLinearGradientBrushVertexShader");
            linearBrushVertexShader = new QGLShader(QGLShader::VertexShader, ctx);
            linearBrushVertexShader->addSource(QLatin1String(qglslLinearGradientBrushVertexShader));
            if (!linearBrushVertexShader->compile()) {
                qWarning() << "qglslLinearGradientBrushVertexShader failed to compile: "
                           << linearBrushVertexShader->log();
            }
        }
        vertexShader = linearBrushVertexShader;

        if (!linearBrushFragmentShader) {
            qDebug("Compiling qglslLinearGradientBrushFragmentShader");
            linearBrushFragmentShader = new QGLShader(QGLShader::FragmentShader, ctx);
            linearBrushFragmentShader->addSource(QLatin1String(fragmentShaderMainSrc));
            linearBrushFragmentShader->addSource(QLatin1String(qglslLinearGradientBrushFragmentShader));
            if (!linearBrushFragmentShader->compile()) {
                qWarning() << "qglslLinearGradientBrushFragmentShader failed to compile:"
                           << linearBrushFragmentShader->log();
            }
        }
        fragmentShader = linearBrushFragmentShader;
        break;
    case Qt::RadialGradientPattern:
        if (!radialBrushVertexShader) {
            qDebug("Compiling qglslRadialGradientBrushVertexShader");
            radialBrushVertexShader = new QGLShader(QGLShader::VertexShader, ctx);
            radialBrushVertexShader->addSource(QLatin1String(qglslRadialGradientBrushVertexShader));
            if (!radialBrushVertexShader->compile()) {
                qWarning() << "qglslRadialGradientBrushVertexShader failed to compile: "
                           << radialBrushVertexShader->log();
            }
        }
        vertexShader = radialBrushVertexShader;

        if (!radialBrushFragmentShader) {
            qDebug("Compiling qglslRadialGradientBrushFragmentShader");
            radialBrushFragmentShader = new QGLShader(QGLShader::FragmentShader, ctx);
            radialBrushFragmentShader->addSource(QLatin1String(fragmentShaderMainSrc));
            radialBrushFragmentShader->addSource(QLatin1String(qglslRadialGradientBrushFragmentShader));
            if (!radialBrushFragmentShader->compile()) {
                qWarning() << "qglslRadialGradientBrushFragmentShader failed to compile:"
                           << radialBrushFragmentShader->log();
            }
        }
        fragmentShader = radialBrushFragmentShader;
        break;
    case Qt::ConicalGradientPattern:
        // FIXME: We currently use the same vertex shader as radial brush
        if (!conicalBrushVertexShader) {
            qDebug("Compiling qglslConicalGradientBrushVertexShader");
            conicalBrushVertexShader = new QGLShader(QGLShader::VertexShader, ctx);
            conicalBrushVertexShader->addSource(QLatin1String(qglslConicalGradientBrushVertexShader));
            if (!conicalBrushVertexShader->compile()) {
                qWarning() << "qglslConicalGradientBrushVertexShader failed to compile: "
                           << conicalBrushVertexShader->log();
            }
        }
        vertexShader = conicalBrushVertexShader;

        if (!conicalBrushFragmentShader) {
            qDebug("Compiling qglslConicalGradientBrushFragmentShader");
            conicalBrushFragmentShader = new QGLShader(QGLShader::FragmentShader, ctx);
            conicalBrushFragmentShader->addSource(QLatin1String(fragmentShaderMainSrc));
            conicalBrushFragmentShader->addSource(QLatin1String(qglslConicalGradientBrushFragmentShader));
            if (!conicalBrushFragmentShader->compile()) {
                qWarning() << "qglslConicalGradientBrushFragmentShader failed to compile:"
                           << conicalBrushFragmentShader->log();
            }
        }
        fragmentShader = conicalBrushFragmentShader;
        break;
    case Qt::Dense1Pattern:
    case Qt::Dense2Pattern:
    case Qt::Dense3Pattern:
    case Qt::Dense4Pattern:
    case Qt::Dense5Pattern:
    case Qt::Dense6Pattern:
    case Qt::Dense7Pattern:
    case Qt::HorPattern:
    case Qt::VerPattern:
    case Qt::CrossPattern:
    case Qt::BDiagPattern:
    case Qt::FDiagPattern:
    case Qt::DiagCrossPattern:
        if (!patternBrushVertexShader) {
            qDebug("Compiling qglslPatternBrushVertexShader");
            patternBrushVertexShader = new QGLShader(QGLShader::VertexShader, ctx);
            patternBrushVertexShader->addSource(QLatin1String(qglslPatternBrushVertexShader));
            if (!patternBrushVertexShader->compile()) {
                qWarning() << "qglslPatternBrushVertexShader failed to compile: "
                           << patternBrushVertexShader->log();
            }
        }
        vertexShader = patternBrushVertexShader;

        if (!patternBrushFragmentShader) {
            qDebug("Compiling qglslPatternBrushFragmentShader");
            patternBrushFragmentShader = new QGLShader(QGLShader::FragmentShader, ctx);
            patternBrushFragmentShader->addSource(QLatin1String(qglslNoOpacityFragmentShaderMain));
            patternBrushFragmentShader->addSource(QLatin1String(qglslPatternBrushFragmentShader));
            if (!patternBrushFragmentShader->compile()) {
                qWarning() << "qglslPatternBrushFragmentShader failed to compile:"
                           << patternBrushFragmentShader->log();
            }
        }
        fragmentShader = patternBrushFragmentShader;
        break;
    default:
        qWarning("Unimplemented brush style (%d)", currentBrushStyle);
    }

    // Now newBrushShader is set correctly, check to see if we already have the program
    // already linked and ready to go in the cache:
    bool foundProgram = false;
    foreach (QGLCachedShaderProg cachedProg, cachedPrograms) {
        if ((cachedProg.vertexShader == vertexShader) &&
            (cachedProg.brushShader == fragmentShader) &&
            (cachedProg.compositionShader == 0) ) {

            activeProgram = cachedProg.shader;
            foundProgram = true;
            break;
        }
    }

    if (!foundProgram) {
        qDebug() << "Linking shader program for " << currentBrushStyle;
        // Required program not found - create it.
        QGLShaderProgram* newProg = new QGLShaderProgram(ctx);

        newProg->addShader(vertexShader);
        newProg->addShader(fragmentShader);

        if (!newProg->link())
            qWarning() << "Shader program for " << currentBrushStyle << "failed to link:" << newProg->log();

        QGLCachedShaderProg cachedProg;
        cachedProg.vertexShader = vertexShader;
        cachedProg.brushShader = fragmentShader;
        cachedProg.compositionShader = 0;
        cachedProg.shader = newProg;

        cachedPrograms.append(cachedProg);
        activeProgram = newProg;
    }

    activeProgram->use();
    shaderProgNeedsChanging = false;
    return true;
}
/*!
    \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
}
Esempio n. 12
0
//
//  Initialize
//
void Hw1opengl::initializeGL()
{
   if (init) return;
   init = true;

   //  Enable Z-buffer depth testing
   glEnable(GL_DEPTH_TEST);

   //  Build shaders
   QGLShaderProgram* shader = new QGLShaderProgram();
   if (!shader->addShaderFromSourceFile(QGLShader::Vertex,":/ex01.vert"))
      Fatal("Error compiling ex01.vert\n"+shader->log());
   if (!shader->addShaderFromSourceFile(QGLShader::Fragment,":/ex01.frag"))
      Fatal("Error compiling ex01.frag\n"+shader->log());
   if (!shader->link())
      Fatal("Error linking shader\n"+shader->log());
   shaders.push_back(shader);

   shader = new QGLShaderProgram();
   if (!shader->addShaderFromSourceFile(QGLShader::Vertex,":/hw1.vert"))
      Fatal("Error compiling hw1.vert\n"+shader->log());
   if (!shader->addShaderFromSourceFile(QGLShader::Fragment,":/hw1.frag"))
      Fatal("Error compiling hw1.frag\n"+shader->log());
   if (!shader->link())
      Fatal("Error linking shader\n"+shader->log());
   shaders.push_back(shader);

   // Cube
   objects.push_back(new Cube());

   // Teapot
   Teapot* pot = new Teapot(8);
   pot->scale(0.5);
   pot->color(0,1,1);
   objects.push_back(pot);

   // Tyra
   WaveOBJ* tyra=0;
   try
   {
      tyra = new WaveOBJ(":/tyra.obj");
   }
   catch (QString err)
   {
      Fatal("Error loading object\n"+err);
   }
   if (tyra)
   {
      tyra->color(1,1,0);
      objects.push_back(tyra);
   }

   //  Set initial object
   obj = objects[0];

   //  Start 100 fps timer connected to updateGL
   timer.setInterval(10);
   connect(&timer,SIGNAL(timeout()),this,SLOT(updateGL()));
   timer.start();
   time.start();
}
Esempio n. 13
0
void Visualizer::initializeGL()
{
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);

    qglClearColor(QColor(Qt::black));

    QFile file("../../../../RubicCubeSolver/objects/box3.obj");
    int x;
    for(int i=0;i<27;i++)
        x = ObjectLoader(&file);

    //Bind Fragment and Vertex Shader for the Cube
    QGLShaderProgram* tmpShaderProg = new QGLShaderProgram;
    tmpShaderProg->addShaderFromSourceFile(QGLShader::Vertex, "../../../../RubicCubeSolver/lightingVertexShader2.vs");
    tmpShaderProg->addShaderFromSourceFile(QGLShader::Fragment, "../../../../RubicCubeSolver/lightingFragmentShader2.fs");
    tmpShaderProg->link();

    lightingShaderProgram.addShaderFromSourceFile(QGLShader::Vertex, "../../../../RubicCubeSolver/lightingVertexShader.vs");
    lightingShaderProgram.addShaderFromSourceFile(QGLShader::Fragment, "../../../../RubicCubeSolver/lightingFragmentShader.fs");
    lightingShaderProgram.link();

    cubeVertices << QVector3D(-0.5, -0.5,  0.5) << QVector3D( 0.5, -0.5,  0.5) << QVector3D( 0.5,  0.5,  0.5) << QVector3D(-0.5,  0.5,  0.5) // Front
                 << QVector3D( 0.5, -0.5, -0.5) << QVector3D(-0.5, -0.5, -0.5) << QVector3D(-0.5,  0.5, -0.5) << QVector3D( 0.5,  0.5, -0.5) // Back
                 << QVector3D(-0.5, -0.5, -0.5) << QVector3D(-0.5, -0.5,  0.5) << QVector3D(-0.5,  0.5,  0.5) << QVector3D(-0.5,  0.5, -0.5) // Left
                 << QVector3D( 0.5, -0.5,  0.5) << QVector3D( 0.5, -0.5, -0.5) << QVector3D( 0.5,  0.5, -0.5) << QVector3D( 0.5,  0.5,  0.5) // Right
                 << QVector3D(-0.5,  0.5,  0.5) << QVector3D( 0.5,  0.5,  0.5) << QVector3D( 0.5,  0.5, -0.5) << QVector3D(-0.5,  0.5, -0.5) // Top
                 << QVector3D(-0.5, -0.5, -0.5) << QVector3D( 0.5, -0.5, -0.5) << QVector3D( 0.5, -0.5,  0.5) << QVector3D(-0.5, -0.5,  0.5);// Bottom

    cubeTextureCoordinates << QVector2D(0, 0) << QVector2D(1, 0) << QVector2D(1, 1) << QVector2D(0, 1) // Front
                           << QVector2D(0, 0) << QVector2D(1, 0) << QVector2D(1, 1) << QVector2D(0, 1) // Front
                           << QVector2D(0, 0) << QVector2D(1, 0) << QVector2D(1, 1) << QVector2D(0, 1) // Front
                           << QVector2D(0, 0) << QVector2D(1, 0) << QVector2D(1, 1) << QVector2D(0, 1) // Front
                           << QVector2D(0, 0) << QVector2D(1, 0) << QVector2D(1, 1) << QVector2D(0, 1) // Front
                           << QVector2D(0, 0) << QVector2D(1, 0) << QVector2D(1, 1) << QVector2D(0, 1);// Front

    cubeNormals << QVector3D( 0,  0,  1) << QVector3D( 0,  0,  1) << QVector3D( 0,  0,  1) << QVector3D( 0,  0,  1) // Front
                << QVector3D( 0,  0, -1) << QVector3D( 0,  0, -1) << QVector3D( 0,  0, -1) << QVector3D( 0,  0, -1) // Back
                << QVector3D(-1,  0,  0) << QVector3D(-1,  0,  0) << QVector3D(-1,  0,  0) << QVector3D(-1,  0,  0) // Left
                << QVector3D( 1,  0,  0) << QVector3D( 1,  0,  0) << QVector3D( 1,  0,  0) << QVector3D( 1,  0,  0) // Right
                << QVector3D( 0,  1,  0) << QVector3D( 0,  1,  0) << QVector3D( 0,  1,  0) << QVector3D( 0,  1,  0) // Top
                << QVector3D( 0, -1,  0) << QVector3D( 0, -1,  0) << QVector3D( 0, -1,  0) << QVector3D( 0, -1,  0); // Bottom

    cubeTexture = bindTexture(QPixmap("../../../../RubicCubeSolver/texture.png"));

//    QGLBuffer* tmpBuffer = WriteBufferData(cubeVertices,cubeNormals,cubeTextureCoordinates);
//    m_pBufferList.append(new m_pBufferShaderList(2, cubeVertices.size(), tmpBuffer, tmpShaderProg));
    for(int i=0;i<27;i++)
    {
    m_pBufferList[i]->shaderProgram = tmpShaderProg;
    m_pBufferList[i]->variable1 = "vertex";
    m_pBufferList[i]->variable2 = "normal";
    m_pBufferList[i]->variable3 = "color";
    m_pBufferList[i]->numVaiables = 3;
    }

    //Bind Fragment and Vertex shadet for the Rotating Spotlight

    coloringShaderProgram.addShaderFromSourceFile(QGLShader::Vertex, "../../../../RubicCubeSolver/coloringVertexShader.vs");
    coloringShaderProgram.addShaderFromSourceFile(QGLShader::Fragment, "../../../../RubicCubeSolver/coloringFragmentShader.fs");
    coloringShaderProgram.link();

    spotlightVertices << QVector3D(   0,    1,    0) << QVector3D(-0.5,    0,  0.5) << QVector3D( 0.5,    0,  0.5) // Front
                      << QVector3D(   0,    1,    0) << QVector3D( 0.5,    0, -0.5) << QVector3D(-0.5,    0, -0.5) // Back
                      << QVector3D(   0,    1,    0) << QVector3D(-0.5,    0, -0.5) << QVector3D(-0.5,    0,  0.5) // Left
                      << QVector3D(   0,    1,    0) << QVector3D( 0.5,    0,  0.5) << QVector3D( 0.5,    0, -0.5) // Right
                      << QVector3D(-0.5,    0, -0.5) << QVector3D( 0.5,    0, -0.5) << QVector3D( 0.5,    0,  0.5) // Bottom
                      << QVector3D( 0.5,    0,  0.5) << QVector3D(-0.5,    0,  0.5) << QVector3D(-0.5,    0, -0.5);
    spotlightColors << QVector3D(0.2, 0.2, 0.2) << QVector3D(0.2, 0.2, 0.2) << QVector3D(0.2, 0.2, 0.2) // Front
                    << QVector3D(0.2, 0.2, 0.2) << QVector3D(0.2, 0.2, 0.2) << QVector3D(0.2, 0.2, 0.2) // Back
                    << QVector3D(0.2, 0.2, 0.2) << QVector3D(0.2, 0.2, 0.2) << QVector3D(0.2, 0.2, 0.2) // Left
                    << QVector3D(0.2, 0.2, 0.2) << QVector3D(0.2, 0.2, 0.2) << QVector3D(0.2, 0.2, 0.2) // Right
                    << QVector3D(  1,   1,   1) << QVector3D(  1,   1,   1) << QVector3D(  1,   1,   1) // Bottom
                    << QVector3D(  1,   1,   1) << QVector3D(  1,   1,   1) << QVector3D(  1,   1,   1);

    //Bind Fragment and Vertex shadet for the non-Rotating left-Spotlight

    leftlightShaderProgram.addShaderFromSourceFile(QGLShader::Vertex, "../../../../RubicCubeSolver/leftlightVertexShader.vs");
    leftlightShaderProgram.addShaderFromSourceFile(QGLShader::Fragment, "../../../../RubicCubeSolver/leftlightFragmentShader.fs");
    leftlightShaderProgram.link();


    //Writing Buffer Vertices, Normals and textures for the Cube

    numCubeVertices = 24;
    cubeBuffer.create();
    cubeBuffer.bind();
    cubeBuffer.allocate(numCubeVertices * (3+3+2) * sizeof (GLfloat));
    int offset = 0;
    cubeBuffer.write(offset, cubeVertices.constData(), numCubeVertices * 3 * sizeof (GLfloat));
    offset += numCubeVertices * 3 * sizeof (GLfloat);
    cubeBuffer.write(offset, cubeNormals.constData(), numCubeVertices * 3 * sizeof (GLfloat));
    offset += numCubeVertices * 3 * sizeof (GLfloat);
    cubeBuffer.write(offset, cubeTextureCoordinates.constData(), numCubeVertices * 2 *sizeof (GLfloat));
    cubeBuffer.release();

    //Writting Buffer Vertices and Colors for the Rotating spotlight

    numSpotlightVertices = 18;
    spotlightBuffer.create();
    spotlightBuffer.bind();
    spotlightBuffer.allocate(numSpotlightVertices * (3+3) * sizeof (GLfloat));
    offset = 0;
    spotlightBuffer.write(offset, spotlightVertices.constData(), numSpotlightVertices * 3 * sizeof (GLfloat));
    offset += numSpotlightVertices * 3 * sizeof (GLfloat);
    spotlightBuffer.write(offset, spotlightColors.constData(), numSpotlightVertices * 3 * sizeof (GLfloat));
    offset += numSpotlightVertices * 3 * sizeof (GLfloat);
    spotlightBuffer.release();
}
Esempio n. 14
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();
    }
Esempio n. 15
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();
}
Esempio n. 16
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);
   */ 

}