我正在創建一個OpenGL程序,它只是創建一個三角形並在屏幕上繪製它。我創建了一個名爲Drawable的類,其中包含繪圖函數,以及使用的VBO對象。我還創建了一個繼承自Drawable類的Triangle類。在Triangle類中,我有一個構造函數,它使用一組點和一個包含顏色的單個數組,並使用此數據初始化VBO(從Drawable繼承)。爲什麼我的Triangle對象不被繪製?
在我的主函數中,我使用點和顏色數據初始化三角形,然後調用三角形對象上的繪圖函數(該繪圖函數在Drawable中)。但最終,窗口打開,三角形未畫出。我在Drawable類中有一個簡單的構造函數,如果我使用這個構造函數初始化對象並調用draw函數,它將顯示對象,所以我不認爲它是我的繪圖函數。我唯一能想到的是,由於我如何訪問VAO & VBO對象,可能它們實際上並未初始化爲任何內容,但我不知道如何檢查它。
Drawable.h
class Drawable
{
public:
Drawable();
void draw();
GLuint objBuffer, VAO, program;
std::string vShaderName, fShaderName;
bool isUniform = false;
int numVertices = 0;
vec4 uniformColorVec;
};
Drawable.cpp
Drawable::Drawable()
{}
void Drawable::draw()
{
GLuint program = InitShader(vShaderName.c_str(), fShaderName.c_str());
glUseProgram(program);
GLuint color_loc = glGetUniformLocation(program, "color");
glBindVertexArray(VAO);
glUniform4fv(color_loc, 1, uniformColorVec);
glDrawArrays(GL_TRIANGLE_FAN, 0, numVertices);
}
Triangle.cpp
Triangle::Triangle(vec4 triPoints[3], vec4 color)
{
uniformColorVec = color;
vShaderName = "vshader00_v150.glsl";
fShaderName = "fshader00_v150.glsl";
numVertices = 3;
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glGenBuffers(1, &objBuffer);
glBindBuffer(GL_ARRAY_BUFFER, objBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(triPoints), triPoints, GL_STATIC_DRAW);
program = InitShader(vShaderName.c_str(), fShaderName.c_str());
glUseProgram(program);
GLuint vPosition = glGetAttribLocation(program, "vPosition");
GLuint color_loc = glGetUniformLocation(program, "color");
glEnableVertexAttribArray(vPosition);
glVertexAttribPointer(vPosition, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
glUniform4fv(color_loc, 1, uniformColorVec);
}
主文件
/* All the OpenGL windowing is intialized but I won't
include that since I know it's fine due to other objects being drawn
correctly */
vec4 triPoints2[3] = {
vec4(0.0, 0.0, 1.0, 1.0),
vec4(-0.75, -0.75, 1.0, 1.0),
vec4(0.0, -0.75, 1.0, 1.0)
};
vec4 blue_opaque = vec4(0.0, 0.0, 1.0, 1.0);
Triangle t;
t = Triangle(triPoints2, blue_opaque);
glClearColor(1.0, 1.0, 1.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
t.draw();
glFlush();
'glGetError'說什麼?另外我建議不要使用'GL_TRIANGLE_FAN',因爲這是歷史。 – ybungalobill
@ybungalobill'glGetError'顯示0,因此它不報告任何錯誤。 – user3358152
如果更改'Triangle t; t =三角形(triPoints2,blue_opaque);'到三角形t的線(triPoints2,blue_opaque);'? – ybungalobill