我正在尝试使用openGL计算着色器在gpu上计算一些东西。但是我想把这个程序保留在终端中,所以我不想要任何类型的小部件。
现在,看起来我将无法调用initializeOpenGLFunctions()或任何其他与ogl相关的函数而不会出现Segmentation fault。
头
#include <QOpenGLShaderProgram>
#include <QOpenGLFunctions_4_5_Core>
class SolverGPU : public QObject,
protected QOpenGLFunctions_4_5_Core
{
Q_OBJECT
public:
SolverGPU();
private:
QOpenGLShaderProgram* program;
};
SRC
SolverGPU::SolverGPU()
{
initializeOpenGLFunctions();
program = new QOpenGLShaderProgram();
program->addShaderFromSourceFile(QOpenGLShader::Compute, ":/shaders/compute.glsl");
program->link();
program->bind();
}
我已经尝试过使用QOpenGLFunctions而不是QOpenGLFunctions_4_5_Core,但是没有用。
以下代码适用于我。我现在正在使用的盒子不支持OpenGL 4.5,因此``降级'到3.3。但原则是一样的。
#include <cstdlib>
#include <iostream>
#include <QApplication>
#include <QOffscreenSurface>
#include <QOpenGLContext>
#include <QOpenGLFunctions_3_3_Core>
#include <QOpenGLShader>
#include <QOpenGLShaderProgram>
int main (int argc, char **argv)
{
try {
QApplication app(argc, argv);
QSurfaceFormat format;
format.setMajorVersion(3);
format.setMinorVersion(3);
format.setProfile(QSurfaceFormat::CoreProfile);
QOpenGLContext gl_ctx;
gl_ctx.setFormat(format);
if (!gl_ctx.create())
throw std::runtime_error("context creation failed");
QOffscreenSurface surface;
surface.create();
gl_ctx.makeCurrent(&surface);
QOpenGLFunctions_3_3_Core opengl_functions;
if (!opengl_functions.initializeOpenGLFunctions())
throw std::runtime_error("initialization failed");
QOpenGLShader vertex_shader(QOpenGLShader::Vertex);
if (!vertex_shader.compileSourceCode(
"#version 330 core\n"
"\n"
"void main ()\n"
"{\n"
" gl_Position = vec4(0.0, 0.0, 0.0, 1.0);\n"
"}\n"
)) {
throw std::runtime_error("vertex shader compilaton failed");
}
QOpenGLShader fragment_shader(QOpenGLShader::Fragment);
if (!fragment_shader.compileSourceCode(
"#version 330 core\n"
"\n"
"layout(location = 0) out vec4 colour;\n"
"\n"
"void main ()\n"
"{\n"
" colour = vec4(0.0, 0.0, 0.0, 1.0);\n"
"}\n"
)) {
throw std::runtime_error("fragment shader compilaton failed");
}
QOpenGLShaderProgram program;
if (!program.addShader(&vertex_shader))
throw std::runtime_error("failed to add vertex shader to program");
if (!program.addShader(&fragment_shader))
throw std::runtime_error("failed to add fragment shader to program");
if (!program.link())
throw std::runtime_error("failed to link failed");
if (!program.bind())
throw std::runtime_error("glUseProgram failed");
app.exec();
}
catch (std::exception &ex) {
std::clog << "\n" << ex.what();
}
catch (...) {
std::clog << "\nunrecognized exception";
}
exit(0);
}
我只执行了最少的测试,但显示的代码创建了一个合适的上下文,初始化3.30核心功能集并成功编译和链接着色器程序。