在本教程的帮助下,我使用freetype显示文字: http://en.wikibooks.org/wiki/OpenGL_Programming/Modern_OpenGL_Tutorial_Text_Rendering_01
但我看到的只是空方块,我用着色器玩了很多,并得出结论,方块的alpha值总是0.0也因为某些原因程序在第一次编译编辑的文本着色器后崩溃
这是代码: 顶点着色器
#version 420
//vertexData.xy contains pos vertexData.zw contains uv coords
in vec4 vertexData;
out vec2 TexCoord;
void main(){
gl_Position = vec4(vertexData.x, vertexData.y, 0.0, 1.0);
TexCoord = vertexData.zw;
}
片段着色器
#version 420
in vec2 TexCoord;
out vec4 fragData;
uniform sampler2D tex;
uniform vec4 TextColor;
void main(){
//TextColor.rgb is the color texture(tex, TexCoord).r is texture alpha value
fragData = vec4(TextColor.rgb, texture(tex, TexCoord).r * TextColor.a);
}
的FreeType
//Freetype init and face creation is in func Font::init()
void Font::renderText(const char *text, float x, float y, float sx, float sy, float rgba[4]){
//Attribute and Uniform Locations
GLint vDataLoc = ShaderResource::TextProgram->getAttributeLocation("vertexData");
GLint textColLoc = ShaderResource::TextProgram->getUniformLocation("TextColor");
GLint texSamplerLoc = ShaderResource::TextProgram->getUniformLocation("tex");
const char *p;
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
FT_Set_Pixel_Sizes(face, 0, 48);
//iterate through text
for(p = text; *p; p++) {
if(FT_Load_Char(face, *p, FT_LOAD_RENDER))
continue;
FT_GlyphSlot g = face->glyph;
int width = to_nearest_pow2( g->bitmap.width );
int height = to_nearest_pow2( g->bitmap.rows );
glUniform4fv(textColLoc, 1, rgba);
glEnable(GL_TEXTURE_2D);
Texture Tex;
Tex = Texture();
Tex.bind();
Tex.setParameter(GL_TEXTURE_WRAP_S, GL_CLAMP);
Tex.setParameter(GL_TEXTURE_WRAP_T, GL_CLAMP);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
//At first I thought I was passing wrong formats to glteximage2d so I played around with it using gl alpha, gl luminance alpha, gl luminance8 alpha8 etc...
//I believe the issue is that g->bitmap.buffer was not created properly i must not be loading that char correctly??
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RED,
width,
height,
0,
GL_RED,
GL_UNSIGNED_BYTE,
g->bitmap.buffer
);
Tex.active(0);
glUniform1i(texSamplerLoc, 0);
//Then I create textbox and draw it using a vertex array obj and vbos using gl triangle strip etc...
Main.cpp Freetype Func调用
//Disable Normal Shader Enable Text Shader
mainProgram->disable();
textProgram->use();
//Scale x & Scale y / window get screen width and height
float sx = 2.0 / window->getFrameBufferWidth();
float sy = 2.0 / window->getFrameBufferHeight();
//Text color
float color[4] = {0.0,0.0,0.0,1.0};
IHateComicSans.renderText("Hello World!", 0.0, 0.0, sx, sy, color);
textProgram->disable();
mainProgram->use();
gltexImage2d之后glGetError返回GL_INVALID_OPERATION但仅在文本的最后一次迭代期间
答案 0 :(得分:0)
问题出在我的Texture类中,只使用opengl函数修复。