I'm trying to display some simple text in OpenGL, but all I get is a black screen. I'm using cglm (glm for c), glad, and glfw. Here is my code:
#include <iostream>
#include <map>
#include <string>
#include <vendor/glad/glad.h>
#include <vendor/GLFW/glfw3.h>
#include <vendor/cglm/cglm.h>
#include <ft2build.h>
#include FT_FREETYPE_H
// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
const char *vertexShaderSource =
"#version 330 core\n"
"layout (location = 0) in vec4 vertex; // <vec2 pos, vec2 tex>\n"
"out vec2 TexCoords;\n"
"uniform mat4 projection;\n"
"void main()\n"
"{\n"
" gl_Position = projection * vec4(vertex.xy, 0.0, 1.0);\n"
" TexCoords = vertex.zw;\n"
"};\n";
const char *fragmentShaderSource =
"#version 330 core\n"
"in vec2 TexCoords;\n"
"out vec4 color;\n"
"uniform sampler2D text;\n"
"uniform vec3 textColor;\n"
"void main()\n"
"{ \n"
" vec4 sampled = vec4(1.0, 1.0, 1.0, texture(text, TexCoords).r);\n"
" color = vec4(textColor, 1.0) * sampled;\n"
"};\n";
typedef struct my_vec3
{
float x;
float y;
float z;
} my_vec3;
typedef struct my_vec2
{
int x;
int y;
} my_vec2;
typedef struct Character
{
unsigned int TextureID; // ID handle of the glyph texture
my_vec2 Size; // Size of glyph
my_vec2 Bearing; // Offset from baseline to left/top of glyph
unsigned int Advance; // Horizontal offset to advance to next glyph
} Character;
void framebuffer_size_callback(GLFWwindow *window, int width, int height);
void processInput(GLFWwindow *window);
void RenderText(GLuint shader, std::string text, float x, float y, float scale, my_vec3 color);
unsigned int VAO, VBO;
std::map<GLchar, Character> Characters;
int main()
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
GLFWwindow *window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
if (window == NULL)
{
printf("Failed to create GLFW window");
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
printf("Failed to initialize GLAD");
return -1;
}
glEnable(GL_CULL_FACE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
int success;
char infoLog[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
printf("ERROR::SHADER::VERTEX::COMPILATION_FAILED %s\n", infoLog);
}
unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
printf("ERROR::SHADER::FRAGMENT::COMPILATION_FAILED %s\n", infoLog);
}
unsigned int shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success)
{
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
printf("ERROR::SHADER::PROGRAM::LINKING_FAILED %s\n", infoLog);
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
mat4 projection;
glm_mat4_identity(projection);
glm_ortho(0.0, static_cast<float>(SCR_WIDTH), 0.0f, static_cast<float>(SCR_HEIGHT), 0.01, 100.0, projection);
// glm_perspective(4.8, (float)SCR_WIDTH/(float)SCR_WIDTH, 0.01, 100.0, projection);
glUseProgram(shaderProgram);
glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "projection"), 1, GL_FALSE, &projection[0][0]);
FT_Library ft;
if (FT_Init_FreeType(&ft))
{
std::cout << "ERROR::FREETYPE: Could not init FreeType Library" << std::endl;
return -1;
}
std::string font_name = "/home/filip/Downloads/arial/arial.ttf";
FT_Face face;
if (FT_New_Face(ft, font_name.c_str(), 0, &face))
{
std::cout << "ERROR::FREETYPE: Failed to load font" << std::endl;
return -1;
}
else
{
FT_Set_Pixel_Sizes(face, 0, 48);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
for (unsigned char c = 0; c < 128; c++)
{
if (FT_Load_Char(face, c, FT_LOAD_RENDER))
{
std::cout << "ERROR::FREETYTPE: Failed to load Glyph" << std::endl;
continue;
}
unsigned int texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RED,
face->glyph->bitmap.width,
face->glyph->bitmap.rows,
0,
GL_RED,
GL_UNSIGNED_BYTE,
face->glyph->bitmap.buffer);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
my_vec2 size;
size.x = face->glyph->bitmap.width;
size.y = face->glyph->bitmap.rows;
my_vec2 bearing;
bearing.x = face->glyph->bitmap_left;
bearing.y = face->glyph->bitmap_top;
Character character = {
texture,
size,
bearing,
static_cast<unsigned int>(face->glyph->advance.x)};
Characters.insert(std::pair<char, Character>(c, character));
}
glBindTexture(GL_TEXTURE_2D, 0);
}
FT_Done_Face(face);
FT_Done_FreeType(ft);
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 6 * 4, NULL, GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(float), 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
while (!glfwWindowShouldClose(window))
{
processInput(window);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
my_vec3 color1;
color1.x = 0.5;
color1.y = 0.8;
color1.z = 0.2;
my_vec3 color2;
color2.x = 0.3;
color2.y = 0.7;
color2.z = 0.9;
RenderText(shaderProgram, "This is sample text", 125.0f, 125.0f, 1.0f, color1);
RenderText(shaderProgram, "(C) LearnOpenGL123.com", 370.0f, 370.0f, 0.5f, color2);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
return 0;
}
void processInput(GLFWwindow *window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
void framebuffer_size_callback(GLFWwindow *window, int width, int height)
{
glViewport(0, 0, width, height);
}
void RenderText(GLuint shader, std::string text, float x, float y, float scale, my_vec3 color)
{
glUseProgram(shader);
glUniform3f(glGetUniformLocation(shader, "textColor"), color.x, color.y, color.z);
glActiveTexture(GL_TEXTURE0);
glBindVertexArray(VAO);
std::string::const_iterator c;
for (c = text.begin(); c != text.end(); c++)
{
Character ch = Characters[*c];
float xpos = x + ch.Bearing.x * scale;
float ypos = y - (ch.Size.y - ch.Bearing.y) * scale;
float w = ch.Size.x * scale;
float h = ch.Size.y * scale;
float vertices[6][4] = {
{xpos, ypos + h, 0.0f, 0.0f},
{xpos, ypos, 0.0f, 1.0f},
{xpos + w, ypos, 1.0f, 1.0f},
{xpos, ypos + h, 0.0f, 0.0f},
{xpos + w, ypos, 1.0f, 1.0f},
{xpos + w, ypos + h, 1.0f, 0.0f}};
glBindTexture(GL_TEXTURE_2D, ch.TextureID);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices); // be sure to use glBufferSubData and not glBufferData
glBindBuffer(GL_ARRAY_BUFFER, 0);
glDrawArrays(GL_TRIANGLES, 0, 6);
x += (ch.Advance >> 6) * scale; // bitshift by 6 to get value in pixels (2^6 = 64 (divide amount of 1/64th pixels by 64 to get amount of pixels))
}
glBindVertexArray(0);
glBindTexture(GL_TEXTURE_2D, 0);
}
I've been following this tutorial. The program compiles and runs without any errors, except that it does not render anything and I can not seem to figure out why.
It seems that you are placing your text on plane z=0
" gl_Position = projection * vec4(vertex.xy, **0.0**, 1.0);\n"
But your camera is looking to -Z (standard camera) from -0.01 to -100.0f.
glm_ortho(0.0, static_cast<float>(SCR_WIDTH), 0.0f, static_cast<float>(SCR_HEIGHT), **0.01, 100.0**, projection);
You can solve it just moving your text a little bit to the -Z axis. A value between the range you have specified in the Zmin, Zmax parameters of the glm_ortho function. Just to be inside the box that ortho is defining.
" gl_Position = projection * vec4(vertex.xy, **-3.0**, 1.0);\n"
It doesn't mind because it is an orthographic projection. Objects have the same size no matter how depth they are.
More details about projection can be found here http://www.songho.ca/opengl/gl_transform.html
Related
I am trying to display a texture, but for some reason it's not shown correctly it's distorted.
This is my source code:
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
void processInput(GLFWwindow *window)
{
if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
int main(void)
{
int success;
char infoLog[512];
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
GLFWwindow* window = glfwCreateWindow(800, 600, "LearnOpenGL", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
glViewport(0, 0, 800, 600);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
const char *vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 aPos;\n"
"layout (location = 1) in vec2 aTexCoord;\n"
"out vec2 TexCoord;\n"
"void main()\n"
"{\n"
" gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
"TexCoord = aTexCoord;"
"}\0";
unsigned int vertexShader;
vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if(!success)
{
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
}
const char* fragmentShaderSource = "#version 330 core\n"
"out vec4 FragColor;\n"
"in vec2 TexCoord;\n"
"uniform sampler2D ourTexture;\n"
"void main()\n"
"{\n"
"FragColor = texture(ourTexture, TexCoord);\n"
"}\0";
unsigned int fragmentShader;
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if(!success)
{
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
}
unsigned int shaderProgram;
shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if(!success) {
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
}
float vertices[] = {
//positions //texture coords
1.0f, 1.0f, 0.0f, 1.0f, 1.0f,// top right
1.0f, -1.0f, 0.0f, 1.0f, 0.0f,// bottom right
-1.0f, -1.0f, 0.0f, 0.0f, 0.0f,// bottom left
-1.0f, 1.0f, 0.0f, 0.0f, 1.0f// top left
};
unsigned int indices[] = {
0, 1, 3, // first triangle
1, 2, 3 // second triangle
};
unsigned int VBO;
unsigned int EBO;
unsigned int VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &EBO);
glGenBuffers(1, &VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
unsigned int texture;
glGenTextures(1, &texture);
//glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_TEXTURE_WRAP_S);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_TEXTURE_WRAP_T);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
int width, height, nrChannels;
stbi_set_flip_vertically_on_load(1);
unsigned char *data = stbi_load("../asd.jpg", &width, &height,&nrChannels, 0);
if (data)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
}
else
{
if(stbi_failure_reason())
std::cout << stbi_failure_reason();
}
while(!glfwWindowShouldClose(window))
{
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glBindTexture(GL_TEXTURE_2D, texture);
glUseProgram(shaderProgram);
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
processInput(window);
glfwSwapBuffers(window);
glfwPollEvents();
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
glfwTerminate();
return 0;
}
Result:
Expected result:
I checked all coordinates and positions and everything looks correct. I have no idea why the texture is not shown correctly.
The vertex and fragment shaders also seems to be correct.
By default OpenGL assumes that the start of each row of an image is aligned to 4 bytes. This is because the GL_UNPACK_ALIGNMENT parameter by default is 4. Since the image has 3 color channels (GL_RGB), and is tightly packed the size of a row of the image may not be aligned to 4 bytes.
When a RGB image with 3 color channels is loaded to a texture object and 3*width is not divisible by 4, GL_UNPACK_ALIGNMENT has to be set to 1, before specifying the texture image with glTexImage2D:
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
I'm trying to render JPG image using "stb_image.h" library. Im using GLEW and GLFW, here is the code:
#include "glew.h"
#include "glfw3.h"
#include <iostream>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define WIDTH 800
#define HEIGHT 600
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
int main(){
GLFWwindow *window;
if (!glfwInit())
{
std::cout << "Failed to Init GLFW" << std::endl;
return -1;
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
window = glfwCreateWindow(WIDTH, HEIGHT, "OpenGL CPP", NULL, NULL);
if (!window)
{
std::cout << "Failed to create GLFW Window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
GLenum err = glewInit();
if (GLEW_OK != err)
{
std::cout << "Failed to Init GLEW" << std::endl;
glfwTerminate();
return -1;
}
float vertices[] = {
// positions // colors // texture coords
0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top right
0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom right
-0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom left
-0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f // top left
};
float indices[] = {
0, 1, 3, // first triangle
1, 2, 3 // second triangle
};
const char *vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 aPos;\n"
"layout (location = 1) in vec3 aColor;\n"
"layout (location = 2) in vec2 aTexCoord;\n"
"out vec3 ourColor;\n"
"out vec2 TexCoord;\n"
"void main()\n"
"{\n"
" gl_Position = vec4(aPos, 1.0);\n"
" ourColor = aColor;\n"
" TexCoord = vec2(aTexCoord.x, aTexCoord.y);\n"
"}\0";
const char *fragmentShaderSource = "#version 330 core\n"
"out vec4 FragColor;\n"
"in vec3 ourColor;\n"
"in vec2 TexCoord;\n"
"uniform sampler2D ourTexture;\n"
"void main()\n"
"{\n"
" FragColor = texture(ourTexture, TexCoord);\n"
"}\n\0";
unsigned int vertexShader;
vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
int success;
char infoLog[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cout << "ERROR COMPILING VERTEX SHADER" << infoLog << std::endl;
}
unsigned int fragmentShader;
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
std::cout << "ERROR COMPILING FRAGMENT SHADER" << infoLog << std::endl;
}
unsigned int shaderProgram;
shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
unsigned int VBO, VAO, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
// position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// color attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
// texture coord attribute
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
glEnableVertexAttribArray(2);
unsigned int texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// set texture filtering parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
int width, height, nrChannels;
unsigned char *data = stbi_load("C:/Users/user3/Documents/cppopengl/res/container.jpg", &width, &height, &nrChannels, 0);
if (data)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
std::cout << "data loaded successfully"<< std::endl;
}
else
{
std::cout << "Failed to load texture" << std::endl;
}
stbi_image_free(data);
glUseProgram(shaderProgram);
//std::cout << glGetUniformLocation(shaderProgram, "ourTexture") << std::endl;
glUniform1i(glGetUniformLocation(shaderProgram, "ourTexture"), 0);
while (!glfwWindowShouldClose(window))
{
err = glGetError();
glClearColor(0.5, 0.5, 0.5, 1);
glClear(GL_COLOR_BUFFER_BIT);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glUseProgram(shaderProgram);
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glfwPollEvents();
if (((err = glGetError()) != GL_NO_ERROR))
{
std::cout << err << std::endl;
}
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
glDeleteProgram(shaderProgram);
return 0;
}
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
Code compiles just fine, without errors and warnings. When I start the executable it shows white screen. Both vertex shader and fragment shader compile and link without errors. stbi_load() does not return error and glGetError() does not return error, glGetUniformLocation() returns uniform location just fine. Can you please help me out? Thanks in advance.
EDIT:
indices must be unsigned int instead of float, thanks #Rabbid76
unsigned int indices[] = {
0, 1, 3, // first triangle
1, 2, 3 // second triangle
};
I'm having issues rendering a 2D object in the 3D space in OpenGL. Whenever I compile my code I get a purple background, which is what I set it to. However, I do not see the object that I should be able to see. I think it's something wrong with the vertex shader, however, I am not completely sure.
Here is my code:
#pragma once
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <vector>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#ifndef STBI_INCLUDE_STB_IMAGE_H
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#endif
#include "Shader.h"
class Render3D {
private:
GLFWwindow* window;
const int windowWidth = 1920;
const int windowHeigth = 1080;
Render3D(Render3D& render){}
Render3D operator=(Render3D& render) {}
void processInput(GLFWwindow* window) {
}
void privateInit() {
if (!glfwInit()) {
throw(-1);
std::cout << "Error: GLFW Init Failed" << std::endl;
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
window = glfwCreateWindow(windowWidth, windowHeigth, "HAHAH BRRR", NULL, NULL);
if (window == NULL) {
std::cout << "Failed to create GLFW Window \n";
glfwTerminate();
throw (-1);
}
glfwMakeContextCurrent(window);
glewExperimental = true;
if (glewInit() != GLEW_OK) {
std::cout << "GLEW INIT FAILED\n";
exit(1);
}
//The first two parameters set the position of the lower left corner
glViewport(0, 0, windowWidth, windowHeigth);
}
void render() {
float positions[] = {
// positions // colors // texture
0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top right
0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom right
-0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom left
-0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f // top left
};
unsigned int indices[] = {
0, 1, 3,
1, 2, 3
};
const char* vertexShader =
"#version 330 core\n"
"\n"
"layout (location = 0) vec3 aPos;\n"
"layout (location = 1) vec3 aColors;\n"
"layout (location = 2) vec2 aTex;\n"
"\n"
"uniform mat4 model;\n"
"uniform mat4 view;\n"
"uniform mat4 projection;\n"
"\n"
"out vec3 Colors;\n"
"out vec2 TextureCoords;\n"
"\n"
"void main(){\n"
"\n"
"gl_Position = projection * view * model * vec4(aPos, 1.0f);\n"
"Colors = aColors;\n"
"TextureCoords = aTex;\n"
"\n"
"}\0";
const char* fragmentShader =
"#version 330 core\n"
"\n"
"out vec4 ourFrag;\n"
"\n"
"in vec3 Colors;\n"
"in vec2 TextureCoords;\n"
"\n"
"uniform sampler2D texture1;\n"
"uniform sampler2D texture2;\n"
"\n"
"void main(){\n"
"\n"
"ourFrag = mix(texture(texture1, TextureCoords), texture(texture2, TextureCoords), 0.2) * vec4(Colors, 1.0f);;\n"
"\n"
"\n"
"}\0";
unsigned int VAO, VBO, EBO;
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(positions), positions, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(0));
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
glEnableVertexAttribArray(2);
glBindVertexArray(0);
unsigned int Texture1, Texture2;
glGenTextures(1, &Texture1);
glGenTextures(1, &Texture2);
glBindTexture(GL_TEXTURE_2D, Texture1);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
int width, height, nrChannels;
unsigned char* data = stbi_load("src/Images/woodblock.jpg", &width, &height, &nrChannels, 4);
if (data) {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
}
else {
std::cout << "TEXTURE FAILED:";
std::cout << stbi_failure_reason() << std::endl;
}
glBindTexture(GL_TEXTURE_2D, Texture2);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
stbi_set_flip_vertically_on_load(1);
data = stbi_load("src/Images/awesomeface.png", &width, &height, &nrChannels, 4);
if (data) {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
}
else {
std::cout << "TEXTURE FAILED:";
std::cout << stbi_failure_reason() << std::endl;
}
Shader render3D_Program(vertexShader, fragmentShader, 1);
render3D_Program.use();
glUniform1i(glGetUniformLocation(render3D_Program.ID, "texture1"), 0);
glUniform1i(glGetUniformLocation(render3D_Program.ID, "texture2"), 1);
while (!glfwWindowShouldClose(window)) {
processInput(window);
glClearColor(0.5f, 0.2f, 0.6f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, Texture1);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, Texture2);
render3D_Program.use();
glm::mat4 model = glm::mat4(1.0f);
glm::mat4 view1 = glm::mat4(1.0f);
glm::mat4 projection = glm::mat4(1.0f);
model = glm::rotate(model, glm::radians(-55.0f), glm::vec3(1.0f, 0.0f, 0.0f));
view1 = glm::translate(view1, glm::vec3(0.0f, 0.0f, -3.0f));
projection = glm::perspective(glm::radians(45.0f), (float)windowWidth / (float)windowHeigth, 0.1f, 100.0f);
glUniformMatrix4fv(glGetUniformLocation(render3D_Program.ID, "model"), 1, GL_FALSE, value_ptr(model));
glUniformMatrix4fv(glGetUniformLocation(render3D_Program.ID, "view"), 1, GL_FALSE, value_ptr(view1));
glUniformMatrix4fv(glGetUniformLocation(render3D_Program.ID, "projection"), 1, GL_FALSE, value_ptr(projection));
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glfwSwapBuffers(window);
glfwPollEvents();
}
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glDeleteBuffers(1, &VBO);
glfwTerminate();
}
public:
Render3D(){}
void Init() {
privateInit();
}
void Run() {
render();
}
};
Additionally, here is the Shader class:
#ifndef SHADER_H
#define SHADER_H
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
class Shader
{
public:
unsigned int ID;
// constructor generates the shader on the fly
// ------------------------------------------------------------------------
Shader(const char* vertexPath, const char* fragmentPath)
{
// 1. retrieve the vertex/fragment source code from filePath
std::string vertexCode;
std::string fragmentCode;
std::ifstream vShaderFile;
std::ifstream fShaderFile;
// ensure ifstream objects can throw exceptions:
vShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
fShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try
{
// open files
vShaderFile.open(vertexPath);
fShaderFile.open(fragmentPath);
std::stringstream vShaderStream, fShaderStream;
// read file's buffer contents into streams
vShaderStream << vShaderFile.rdbuf();
fShaderStream << fShaderFile.rdbuf();
// close file handlers
vShaderFile.close();
fShaderFile.close();
// convert stream into string
vertexCode = vShaderStream.str();
fragmentCode = fShaderStream.str();
}
catch (std::ifstream::failure& e)
{
std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl;
}
const char* vShaderCode = vertexCode.c_str();
const char* fShaderCode = fragmentCode.c_str();
// 2. compile shaders
unsigned int vertex, fragment;
// vertex shader
vertex = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex, 1, &vShaderCode, NULL);
glCompileShader(vertex);
checkCompileErrors(vertex, "VERTEX");
// fragment Shader
fragment = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment, 1, &fShaderCode, NULL);
glCompileShader(fragment);
checkCompileErrors(fragment, "FRAGMENT");
// shader Program
ID = glCreateProgram();
glAttachShader(ID, vertex);
glAttachShader(ID, fragment);
glLinkProgram(ID);
checkCompileErrors(ID, "PROGRAM");
// delete the shaders as they're linked into our program now and no longer necessary
glDeleteShader(vertex);
glDeleteShader(fragment);
}
Shader(const char* VertexShader, const char* FragmentShader, bool Specifier) {
unsigned int vertex = glCreateShader(GL_VERTEX_SHADER);
unsigned int fragment = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(vertex, 1, &VertexShader, NULL);
glShaderSource(fragment, 1, &FragmentShader, NULL);
glCompileShader(vertex);
int successVertex;
char infoLogVertex[512];
glGetShaderiv(vertex, GL_COMPILE_STATUS, &successVertex);
if (!successVertex) {
glGetShaderInfoLog(vertex, 512, NULL, infoLogVertex);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLogVertex << std::endl;
}
glCompileShader(fragment);
int successFragment;
glGetShaderiv(fragment, GL_COMPILE_STATUS, &successFragment);
if (!successFragment){
glGetShaderInfoLog(fragment, 512, NULL, infoLogVertex);
std::cout << "ERROR::SHADER:FRAGMENT::COMPILATION_FAILED\n" << infoLogVertex << std::endl;
}
ID = glCreateProgram();
glAttachShader(ID, vertex);
glAttachShader(ID, fragment);
glLinkProgram(ID);
checkCompileErrors(ID, "PROGRAM");
glDeleteShader(vertex);
glDeleteShader(fragment);
}
// activate the shader
// ------------------------------------------------------------------------
void use()
{
glUseProgram(ID);
}
// utility uniform functions
// ------------------------------------------------------------------------
void setBool(const std::string& name, bool value) const
{
glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value);
}
// ------------------------------------------------------------------------
void setInt(const std::string& name, int value) const
{
glUniform1i(glGetUniformLocation(ID, name.c_str()), value);
}
// ------------------------------------------------------------------------
void setFloat(const std::string& name, float value) const
{
glUniform1f(glGetUniformLocation(ID, name.c_str()), value);
}
private:
// utility function for checking shader compilation/linking errors.
// ------------------------------------------------------------------------
void checkCompileErrors(unsigned int shader, std::string type)
{
int success;
char infoLog[1024];
if (type != "PROGRAM")
{
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(shader, 1024, NULL, infoLog);
std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl;
}
}
else
{
glGetProgramiv(shader, GL_LINK_STATUS, &success);
if (!success)
{
glGetProgramInfoLog(shader, 1024, NULL, infoLog);
std::cout << "ERROR::PROGRAM_LINKING_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl;
}
}
}
};
#endif
Your vertex shader fails to compiled because you missed the in type qualifier for the vertex shader inputs (attributes):
layout (location = 0) vec3 aPos;
layout (location = 1) vec3 aColors;
layout (location = 2) vec2 aTex;
It has to be:
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColors;
layout (location = 2) in vec2 aTex;
I am trying to get a square on the screen. This code should draw a square, however it omits the last vertex and only draws a triangle.
Where have I gone wrong?
#include <glad/gl.h>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include "linmath.h"
#include <stdlib.h>
#include <stdio.h>
static const struct
{
float x, y;
float r, g, b;
} vertices[4] =
{
{ -0.5f, -0.5f, 1.f, 0.f, 0.f },
{ 0.5f, -0.5f, 0.f, 1.f, 0.f },
{ -0.5f, 0.5f, 0.f, 0.f, 1.f },
{ 0.5f, 0.5f, 0.f, 1.f, 1.f}
};
static const char* vertex_shader_text =
"#version 110\n"
"uniform mat4 MVP;\n"
"attribute vec3 vCol;\n"
"attribute vec2 vPos;\n"
"varying vec3 color;\n"
"void main()\n"
"{\n"
" gl_Position = MVP * vec4(vPos, 0.0, 1.0);\n"
" color = vCol;\n"
"}\n";
static const char* fragment_shader_text =
"#version 110\n"
"varying vec3 color;\n"
"void main()\n"
"{\n"
" gl_FragColor = vec4(color, 1.0);\n"
"}\n";
static void error_callback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
int main(void)
{
GLFWwindow* window;
GLuint vertex_buffer,edge_buffer, vertex_shader, fragment_shader, program;
GLint mvp_location, vpos_location, vcol_location;
glfwSetErrorCallback(error_callback);
if (!glfwInit())
exit(EXIT_FAILURE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
window = glfwCreateWindow(640, 480, "Simple example", NULL, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwSetKeyCallback(window, key_callback);
glfwMakeContextCurrent(window);
gladLoadGL(glfwGetProcAddress);
glfwSwapInterval(1);
// NOTE: OpenGL error checks have been omitted for brevity
glGenBuffers(1, &vertex_buffer);
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
vertex_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader, 1, &vertex_shader_text, NULL);
glCompileShader(vertex_shader);
fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader, 1, &fragment_shader_text, NULL);
glCompileShader(fragment_shader);
program = glCreateProgram();
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glLinkProgram(program);
mvp_location = glGetUniformLocation(program, "MVP");
vpos_location = glGetAttribLocation(program, "vPos");
vcol_location = glGetAttribLocation(program, "vCol");
glEnableVertexAttribArray(vpos_location);
glVertexAttribPointer(vpos_location, 2, GL_FLOAT, GL_FALSE,
sizeof(vertices[0]), (void*) 0);
glEnableVertexAttribArray(vcol_location);
glVertexAttribPointer(vcol_location, 3, GL_FLOAT, GL_FALSE,
sizeof(vertices[0]), (void*) (sizeof(float) * 2));
while (!glfwWindowShouldClose(window))
{
float ratio;
int width, height;
mat4x4 m, p, mvp;
glfwGetFramebufferSize(window, &width, &height);
ratio = width / (float) height;
glViewport(0, 0, width, height);
glClear(GL_COLOR_BUFFER_BIT);
mat4x4_identity(m);
mat4x4_rotate_Z(m, m, (float) glfwGetTime());
mat4x4_ortho(p, -ratio, ratio, -1.f, 1.f, 1.f, -1.f);
mat4x4_mul(mvp, p, m);
glUseProgram(program);
glUniformMatrix4fv(mvp_location, 1, GL_FALSE, (const GLfloat*) mvp);
glDrawArrays(GL_POLYGON, 0, 3);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
I only have 3 of the 4 vertices rendering, thus resulting in a triangle instead of a square.
You're telling opengl to render 3 vertices instead of 4 with glDrawArrays(GL_POLYGON, 0, 3);
Change it to glDrawArrays(GL_POLYGON, 0, 4);
I have written application that runs on an embedded device, but all I see on display is the surface area filled with color as specified by me in glViewPort.
Text does not appear.
I have glError prints to see if some gl API call has failed, but nothing is failing.
I also do not have FT library error.
Though my prints show face->glyph->bitmap.width face->glyph->bitmap_left as zero for any character that I load.
// ******** CODE BELOW ******//
int OpenGlInit()
{
/* Here is the Init code for embedded graphics
This works fine.*/
glViewport(0, 0, 800, 600);
PrintGlError();
char vShaderStr[] =
"attribute vec4 vertex;\n"
"varying vec2 TexCoords;\n"
"uniform vec4 projection;\n"
"void main()\n"
"{\n"
"gl_Position = projection * vec4(vertex.xy, 0, 1);\n"
"TexCoords = vertex.zw;\n"
"}\n";
char fShaderStr[]=
"varying vec2 TexCoords;\n"
"uniform sampler2D text;\n"
"uniform vec4 color;\n"
"void main(void) {\n"
"gl_FragColor = vec4(1, 1, 1, texture2D(text, TexCoords).r) * color;\n"
"}\n";
GLuint vertexShader;
GLuint fragmentShader;
GLint linked;
vertexShader = LoadShader(GL_VERTEX_SHADER, vShaderStr);
fragmentShader = LoadShader(GL_FRAGMENT_SHADER, fShaderStr);
ProgramObject = glCreateProgram();
PrintGlError();
if (ProgramObject == 0) {
printf("DEBUG- glCreateProgram() returned 0\n");
return 0;
}
glAttachShader( ProgramObject, vertexShader );
PrintGlError();
glAttachShader( ProgramObject, fragmentShader );
PrintGlError();
glLinkProgram( ProgramObject );
PrintGlError();
glGetProgramiv( ProgramObject, GL_LINK_STATUS, &linked );
PrintGlError();
if (!linked)
{
printf("failed to link program\n");
GLint infoLen = 0;
glGetProgramiv( ProgramObject, GL_INFO_LOG_LENGTH, &infoLen);
PrintGlError();
if (infoLen > 1)
{
char infoLog[infoLen];
glGetProgramInfoLog( ProgramObject, infoLen, NULL, infoLog );
PrintGlError();
printf("Error linking program:\n%s\n", infoLog);
}
glDeleteProgram( ProgramObject );
PrintGlError();
return GL_FALSE;
}
printf("\nAfter Linked ProgramObject and compiled shaders");
printf("\nBefore Gen Buffers");
glGenBuffers(1, &VBO);
PrintGlError();
printf("\nAfter Gen Buffers");
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
PrintGlError();
glClear(GL_COLOR_BUFFER_BIT);
PrintGlError();
glEnable(GL_BLEND);
PrintGlError();
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
PrintGlError();
if(glGetUniformLocation(ProgramObject, "color") == -1)
printf("\n ERROR uniform color is -1");
GLfloat black[4] = {1, 0, 0, 1};
glUniform4fv(glGetUniformLocation(ProgramObject, "color"), 1, black);
PrintGlError();
printf("\nAfter Matrix4fv");
float sx = 2.0 / 800;
float sy = 2.0 / 600;
RenderText("This is sample text", -1 + 8 * sx, 1 - 50 * sy, sx, sy);
printf("DEBUG\n\n\n\n\n\n\n\n\n\n\n");
RenderText("(C) LearnOpenGL.com", -1 + 8.5 * sx, 1 - 100.5 * sy, sx, sy);
eglSwapBuffers(egldisplay, eglsurface);
PrintGlError();
sleep(30);
glDeleteProgram(ProgramObject);
}
void RenderText(std::string message, GLfloat x, GLfloat y, GLfloat sx, GLfloat sy)
{
FT_Library ft;
FT_Face face;
if(FT_Init_FreeType(&ft))
std::cout << "ERROR::FREETYPE: Could not init FreeType Library" << std::endl;
if(FT_New_Face(ft, "/usr/share/fonts/tt7268mi_.ttf", 0, &face))
std::cout << "ERROR::FREETYPE: Failed to load calibri display" << std::endl;
if(FT_Set_Char_Size(face, 0, 16*64, 300, 300))
std::cout << "ERROR::FREETYPE: Failed to set char size" << std::endl;
printf("\nDEBUG after freetype\n");
if(FT_Set_Pixel_Sizes(face, 0, 48))
std::cout << "ERROR::FREETYPE: Failed to set pixel size" << std::endl;
printf("DEBUG after pixel sizes\n");
glActiveTexture(GL_TEXTURE0);
PrintGlError();
GLuint text;
glGenTextures(1, &text);
PrintGlError();
glBindTexture(GL_TEXTURE_2D, text);
PrintGlError();
if (glGetUniformLocation(ProgramObject, "text") == -1)
printf("\n ERROR uniform text is -1");
glUniform1i(glGetUniformLocation(ProgramObject, "text"), 0);
PrintGlError();
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
PrintGlError();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
PrintGlError();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
PrintGlError();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
PrintGlError();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
PrintGlError();
int vPosition = glGetAttribLocation(ProgramObject, "vertex");
if (vPosition == -1)
printf("\nERROR vPosition is -1");
PrintGlError();
glEnableVertexAttribArray(vPosition);
PrintGlError();
glBindBuffer(GL_ARRAY_BUFFER, VBO);
PrintGlError();
//glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6 * 4, NULL, GL_DYNAMIC_DRAW);
glVertexAttribPointer(vPosition, 4, GL_FLOAT, GL_FALSE, 0, 0);
PrintGlError();
std::string::const_iterator ch;
for (ch = message.begin(); ch != message.end(); ch++)
{
const char c = *ch;
if (FT_Load_Char(face, c, FT_LOAD_RENDER))
{
std::cout << "ERROR::FREETYTPE: Failed to load Glyph" << std::endl;
continue;
}
FT_UInt glyph_index = FT_Get_Char_Index(face, c);
printf("\nglyphindex is: %u",glyph_index);
FT_Load_Glyph(face, glyph_index, FT_LOAD_RENDER);
printf("\nChar: %c, facewidth:%f, faceheight:%f", c, (face->glyph->bitmap.width), (face->glyph->bitmap.rows));
printf("\nfaceleft:%f, facetop:%f ", (face->glyph->bitmap_left), (face->glyph->bitmap_top));
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RGBA,
face->glyph->bitmap.width,
face->glyph->bitmap.rows,
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
face->glyph->bitmap.buffer
);
PrintGlError();
GLfloat xpos = x + (face->glyph->bitmap_left) * sx;
GLfloat ypos = -y - (face->glyph->bitmap_top) * sy;
GLfloat w = (face->glyph->bitmap.width) * sx;
GLfloat h = (face->glyph->bitmap.rows) * sy;
printf("\n xpos:%f ypos:%f w:%f h:%f", xpos, ypos, w, h);
/*GLfloat vertices[6][4] = {
{ xpos, ypos + h, 0.0, 0.0 },
{ xpos, ypos, 0.0, 1.0 },
{ xpos + w, ypos, 1.0, 1.0 },
{ xpos, ypos + h, 0.0, 0.0 },
{ xpos + w, ypos, 1.0, 1.0 },
{ xpos + w, ypos + h, 1.0, 0.0 }
};*/
point vertices[4] = {
{xpos, -ypos , 0, 0},
{xpos + w, -ypos , 1, 0},
{xpos, -ypos - h, 0, 1},
{xpos + w, -ypos - h, 1, 1},
};
glBufferData(GL_ARRAY_BUFFER, sizeof vertices, vertices, GL_DYNAMIC_DRAW);
PrintGlError();
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
PrintGlError();
x += (face->glyph->advance.x/64) * sx;
y += (face->glyph->advance.y/64) * sy;
}
glDeleteTextures(1, &text);
glDisableVertexAttribArray(vPosition);
FT_Done_Face(face);
FT_Done_FreeType(ft);
}
void PrintGlError()
{
GLenum ErrorCheckValue = glGetError();
if (ErrorCheckValue != GL_NO_ERROR)
{
fprintf(stderr,"\nGL ERROR:%d", ErrorCheckValue);
}
}
GLuint LoadShader(GLenum type, const char *shaderSrc)
{
GLuint shader;
GLint compiled;
shader = glCreateShader( type );
if (shader == 0) {
return 0;
}
glShaderSource( shader, 1, &shaderSrc, NULL);
PrintGlError();
glCompileShader(shader);
PrintGlError();
glGetShaderiv( shader, GL_COMPILE_STATUS, &compiled);
PrintGlError();
if (!compiled)
{
printf("failed to compile shader\n");
GLint infoLen = 0;
glGetShaderiv(shader,GL_INFO_LOG_LENGTH, &infoLen);
PrintGlError();
if (infoLen > 1) {
char infoLog[infoLen];
glGetProgramInfoLog( ProgramObject, infoLen, NULL, infoLog );
PrintGlError();
printf("Error compiling shader:\n%s\n", infoLog);
}
glDeleteShader(shader);
PrintGlError();
return 0;
}
return shader;
}
There are some issues in your program.
The bitmap which is generated by FT_Load_Glyph has only one color channel. This means that the 7th parameter of glTexImage2D has to be GL_RED, when you define the texture image:
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RGBA,
face->glyph->bitmap.width,
face->glyph->bitmap.rows,
0,
GL_RED, // <--------------- GL_RED instead of GL_RGBA
GL_UNSIGNED_BYTE,
face->glyph->bitmap.buffer
);
You have missed to install the shader program object as part of current rendering state by glUseProgram. This has to be done after the program is linked ([glLinkProgram])(https://www.khronos.org/registry/OpenGL-Refpages/es3.0/html/glLinkProgram.xhtml) and before any value of a uniform is specified (glUniform*):
glLinkProgram( ProgramObject );
GLint color_location = glGetUniformLocation(ProgramObject, "color");
....
glUseProgram( ProgramObject );
GLfloat black[4] = {1, 0, 0, 1};
glUniform4fv(color_location, 1, black);
the GLSL data type of the projection matrix has to be mat4. Note, a multiplication of 2 variables of type vec4, would lead to a component-wise multiplication to all components of the vector. See GLSL Programming/Vector and Matrix Operations.
But since you have initialized the vertex coordinates in normalized device space, you don't need any projection:
attribute vec4 vertex;
varying vec2 TexCoords;
void main()
{
gl_Position = vec4(vertex.xy, 0, 1);
TexCoords = vertex.zw;
}
Preview:
But I am using gl2 library and (gl2.h) does not have GL_RED defined.
Since GL_RED is not supported in OpenGL ES 2.0, you have to do a workaround. GL_ALPHA is supported in OpneGL ES 2.0, see glTexImage2D.
Use the GL_ALPHA format specifier:
glTexImage2D(
GL_TEXTURE_2D, 0, GL_RGBA,
face->glyph->bitmap.width, face->glyph->bitmap.rows, 0,
GL_ALPHA,
GL_UNSIGNED_BYTE,
face->glyph->bitmap.buffer
);
And read the alpha channel form the a component, when looking up the texture in the fragment shader:
float alpha = texture2D(text, TexCoords).a;
gl_FragColor = vec4(1.0, 1.0, 1.0, alpha) * color;