Write 2D text game engine on C++, using SDL2, OpenGL ES 3.0, GLM and Freetype. Any other…
- User
Write 2D text game engine on C++, using SDL2, OpenGL ES 3.0, GLM and Freetype. Any other lib you can give on your wish.
- Assistant
Write 2D text game engine on C++, using SDL2, OpenGL ES 3.0, GLM and Freetype. Any other lib you can give on your wish.
Sure! Below is a simple 2D text game engine written in C++ using SDL2, OpenGL ES 3.0, GLM, and FreeType. This engine initializes a window, sets up OpenGL ES for rendering, loads fonts using FreeType, and renders text on the screen. You can build upon this foundation to create your own 2D text-based games.
First, make sure you have the necessary libraries installed and set up in your development environment:
For OpenGL function loading, we'll use GLAD tailored for OpenGL ES. You can generate a loader for OpenGL ES 3.0 from GLAD's website.
Here's the complete code:
// main.cpp
#include <iostream>
#include <map>
#include <ft2build.h>
#include FT_FREETYPE_H
#include <SDL2/SDL.h>
#include <glad/glad.h> // Make sure this is the GLAD loader for OpenGL ES
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
struct Character {
GLuint TextureID; // ID handle of the glyph texture
glm::ivec2 Size; // Size of glyph
glm::ivec2 Bearing; // Offset from baseline to left/top of glyph
GLuint Advance; // Offset to advance to next glyph
};
std::map<GLchar, Character> Characters;
GLuint VAO, VBO;
void RenderText(Shader &shader, std::string text, GLfloat x, GLfloat y, GLfloat scale, glm::vec3 color);
const GLuint WIDTH = 800, HEIGHT = 600;
int main(int argc, char* argv[])
{
// Initialize SDL2
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
std::cerr << "Failed to initialize SDL2\n";
return -1;
}
// Set OpenGL ES attributes
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
// Create window
SDL_Window* window = SDL_CreateWindow("2D Text Game Engine", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WIDTH, HEIGHT, SDL_WINDOW_OPENGL);
if (!window) {
std::cerr << "Failed to create window\n";
return -1;
}
// Create OpenGL context
SDL_GLContext context = SDL_GL_CreateContext(window);
if (!context) {
std::cerr << "Failed to create OpenGL context\n";
return -1;
}
// Load OpenGL functions using GLAD
if (!gladLoadGLES2Loader((GLADloadproc)SDL_GL_GetProcAddress)) {
std::cerr << "Failed to initialize GLAD\n";
return -1;
}
// Enable blending
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Compile and setup the shader
Shader textShader("text_vertex_shader.glsl", "text_fragment_shader.glsl");
glm::mat4 projection = glm::ortho(0.0f, static_cast<GLfloat>(WIDTH), 0.0f, static_cast<GLfloat>(HEIGHT));
textShader.Use();
glUniformMatrix4fv(glGetUniformLocation(textShader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection));
// FreeType
FT_Library ft;
if (FT_Init_FreeType(&ft)) {
std::cerr << "Could not init FreeType Library\n";
return -1;
}
// Load font
FT_Face face;
if (FT_New_Face(ft, "fonts/arial.ttf", 0, &face)) {
std::cerr << "Failed to load font\n";
return -1;
}
FT_Set_Pixel_Sizes(face, 0, 48);
// Disable byte-alignment restriction
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
// Load first 128 characters of ASCII
for (GLubyte c = 0; c < 128; c++)
{
// Load character glyph
if (FT_Load_Char(face, c, FT_LOAD_RENDER))
{
std::cerr << "Failed to load Glyph\n";
continue;
}
// Generate texture
GLuint 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
);
// Set texture options
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);
// Now store character for later use
Character character = {
texture,
glm::ivec2(face->glyph->bitmap.width, face->glyph->bitmap.rows),
glm::ivec2(face->glyph->bitmap_left, face->glyph->bitmap_top),
static_cast<GLuint>(face->glyph->advance.x)
};
Characters.insert(std::pair<GLchar, Character>(c, character));
}
glBindTexture(GL_TEXTURE_2D, 0);
// Destroy FreeType
FT_Done_Face(face);
FT_Done_FreeType(ft);
// Configure VAO/VBO for texture quads
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6 * 4, NULL, GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
// Game loop
bool quit = false;
SDL_Event e;
while (!quit)
{
// Event handling
while (SDL_PollEvent(&e) != 0)
{
if (e.type == SDL_QUIT)
quit = true;
// Handle other events like keyboard input here
}
// Clear the screen
glClearColor(0.1f, 0.1f, 0.15f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// Render text
textShader.Use();
RenderText(textShader, "Hello, World!", 25.0f, HEIGHT - 50.0f, 1.0f, glm::vec3(0.5, 0.8f, 0.2f));
// Update screen
SDL_GL_SwapWindow(window);
}
// Cleanup
SDL_GL_DeleteContext(context);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
Helper Functions and Classes
You'll need a simple shader class to manage the shaders:
Shader Source Files
Create a vertex shader file named text_vertex_shader.glsl:
#version 300 es
layout (location = 0) in vec4 vertex; // <vec2 pos, vec2 tex>
out vec2 TexCoords;
uniform mat4 projection;
void main()
{
gl_Position = projection * vec4(vertex.xy, 0.0, 1.0);
TexCoords = vertex.zw;
}
And a fragment shader file named text_fragment_shader.glsl:
#version 300 es
precision mediump float;
in vec2 TexCoords;
out vec4 color;
uniform sampler2D text;
uniform vec3 textColor;
void main()
{
float alpha = texture(text, TexCoords).r;
color = vec4(textColor, alpha);
}
RenderText Function
Here's the implementation for RenderText:
void RenderText(Shader &shader, std::string text, GLfloat x, GLfloat y, GLfloat scale, glm::vec3 color)
{
// Activate corresponding render state
shader.Use();
glUniform3f(glGetUniformLocation(shader.Program, "textColor"), color.x, color.y, color.z);
glActiveTexture(GL_TEXTURE0);
glBindVertexArray(VAO);
// Iterate through all characters
std::string::const_iterator c;
for (c = text.begin(); c != text.end(); c++)
{
Character ch = Characters[*c];
GLfloat xpos = x + ch.Bearing.x * scale;
GLfloat ypos = y - (ch.Size.y - ch.Bearing.y) * scale;
GLfloat w = ch.Size.x * scale;
GLfloat h = ch.Size.y * scale;
// Update VBO for each character
GLfloat vertices[6][4] = {
{ xpos, ypos + h, 0.0, 1.0 },
{ xpos + w, ypos, 1.0, 0.0 },
{ xpos, ypos, 0.0, 0.0 },
{ xpos, ypos + h, 0.0, 1.0 },
{ xpos + w, ypos + h, 1.0, 1.0 },
{ xpos + w, ypos, 1.0, 0.0 }
};
// Render glyph texture over quad
glBindTexture(GL_TEXTURE_2D, ch.TextureID);
// Update content of VBO memory
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// Render quad
glDrawArrays(GL_TRIANGLES, 0, 6);
// Advance cursors for next glyph
x += (ch.Advance >> 6) * scale; // Bitshift by 6 to get value in pixels (2^6 = 64)
}
glBindVertexArray(0);
glBindTexture(GL_TEXTURE_2D, 0);
}
Notes:
Ensure that the font file (arial.ttf in this case) is placed in a fonts directory relative to your executable.
The shaders are very basic and suitable for rendering 2D text. If you wish to add more graphical features, you can extend them.
GLAD should be configured for OpenGL ES 3.0. When generating the loader from GLAD's website:
Error handling is kept minimal for brevity, but in a robust engine, make sure to include comprehensive checks.
The code is intended to create a window that renders "Hello, World!" using the loaded font.
Building the Project
Make sure to link against the following libraries when compiling:
SDL2GLMFreeTypeGLAD (for OpenGL ES)OpenGL ES libraries (platform-dependent, e.g., -lGLESv2 on some systems)An example command using g++ might look like:
g++ main.cpp -o gameengine -lSDL2 -lGLEStest -lGL -lEGL -lfreetype -I/path/to/includes -L/path/to/libs
Adjust include paths (-I) and library paths (-L) as per your environment.
Extending the Engine
This basic engine sets the groundwork for rendering text in a 2D space. From here, you can:
Final Thoughts
Feel free to customize and expand upon this code to suit your game's needs. The combination of SDL2 for window management and input, OpenGL ES for rendering, GLM for math, and FreeType for font loading provides a powerful yet flexible foundation for a 2D text game engine.
If you have any questions or need further assistance, don't hesitate to ask!
Not yet included in a published release.
// Shader.h
#ifndef SHADER_H
#define SHADER_H
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <glad/glad.h>
class Shader
{
public:
GLuint Program;
// Constructor generates the shader on the fly
Shader(const GLchar* vertexPath, const GLchar* fragmentPath)
{
// 1. Retrieve 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::badbit);
fShaderFile.exceptions(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 GLchar array
vertexCode = vShaderStream.str();
fragmentCode = fShaderStream.str();
}
catch (std::ifstream::failure& e)
{
std::cerr << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ\n";
}
const GLchar* vShaderCode = vertexCode.c_str();
const GLchar * fShaderCode = fragmentCode.c_str();
// 2. Compile shaders
GLuint vertex, fragment;
GLint success;
GLchar infoLog[512];
// Vertex Shader
vertex = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex, 1, &vShaderCode, NULL);
glCompileShader(vertex);
// Print compile errors if any
glGetShaderiv(vertex, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(vertex, 512, NULL, infoLog);
std::cerr << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << "\n";
}
// Fragment Shader
fragment = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment, 1, &fShaderCode, NULL);
glCompileShader(fragment);
// Print compile errors if any
glGetShaderiv(fragment, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(fragment, 512, NULL, infoLog);
std::cerr << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << "\n";
}
// Shader Program
this->Program = glCreateProgram();
glAttachShader(this->Program, vertex);
glAttachShader(this->Program, fragment);
glLinkProgram(this->Program);
// Print linking errors if any
glGetProgramiv(this->Program, GL_LINK_STATUS, &success);
if (!success) {
glGetProgramInfoLog(this->Program, 512, NULL, infoLog);
std::cerr << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << "\n";
}
// Delete the shaders as they're linked into our program now and no longer necessery
glDeleteShader(vertex);
glDeleteShader(fragment);
}
// Uses the current shader
void Use()
{
glUseProgram(this->Program);
}
};
#endif