Write 2D text game engine on C++, using SDL3, OpenGL and any other libraries on your wish.
- User
Write 2D text game engine on C++, using SDL3, OpenGL and any other libraries on your wish.
- Assistant
Here's a basic 2D text game engine in C++ using SDL3, OpenGL, and the
stb_truetypelibrary for font rendering. This example sets up an SDL window with an OpenGL context, loads a TrueType font, creates a texture atlas for the font glyphs, and renders text on the screen.Prerequisites:
- SDL3 library installed.
- GLEW library for managing OpenGL extensions.
stb_truetype.hheader file (you can download it from here).- A TrueType font file (e.g.,
arial.ttf) available in your working directory.
Code:
#include <SDL3/SDL.h> #include <GL/glew.h> #include <cstdio> #include <cstdlib> #include <iostream> #include <string> #define STB_TRUETYPE_IMPLEMENTATION #include "stb_truetype.h" const int screenWidth = 800; const int screenHeight = 600; const int FONT_BITMAP_WIDTH = 512; const int FONT_BITMAP_HEIGHT = 512; GLuint fontTexture; stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs void renderText(float x, float y, const char* text) { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, fontTexture); glBegin(GL_QUADS); while (*text) { if (*text >= 32 && *text < 128) { stbtt_aligned_quad q; stbtt_GetBakedQuad(cdata, FONT_BITMAP_WIDTH, FONT_BITMAP_HEIGHT, *text - 32, &x, &y, &q, 1); glTexCoord2f(q.s0, q.t0); glVertex2f(q.x0, q.y0); glTexCoord2f(q.s1, q.t0); glVertex2f(q.x1, q.y0); glTexCoord2f(q.s1, q.t1); glVertex2f(q.x1, q.y1); glTexCoord2f(q.s0, q.t1); glVertex2f(q.x0, q.y1); } ++text; } glEnd(); } int main(int argc, char* argv[]) { // Initialize SDL if (SDL_Init(SDL_INIT_VIDEO) != 0) { std::cerr << "SDL_Init Error: " << SDL_GetError() << std::endl; return 1; } // Set OpenGL attributes SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); // Create window SDL_Window* window = SDL_CreateWindow( "2D Text Game Engine", screenWidth, screenHeight, SDL_WINDOW_OPENGL); if (window == nullptr) { std::cerr << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } // Create OpenGL context SDL_GLContext glContext = SDL_GL_CreateContext(window); if (glContext == nullptr) { std::cerr << "SDL_GL_CreateContext Error: " << SDL_GetError() << std::endl; SDL_DestroyWindow(window); SDL_Quit(); return 1; } // Initialize GLEW glewExperimental = GL_TRUE; GLenum glewInitResult = glewInit(); if (glewInitResult != GLEW_OK) { std::cerr << "GLEW init failed: " << glewGetErrorString(glewInitResult) << std::endl; SDL_GL_DeleteContext(glContext); SDL_DestroyWindow(window); SDL_Quit(); return 1; } // Set up viewport and orthographic projection glViewport(0, 0, screenWidth, screenHeight); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, screenWidth, screenHeight, 0, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Load font using stb_truetype unsigned char ttf_buffer[1<<20]; FILE* fontFile = fopen("arial.ttf", "rb"); if (!fontFile) { std::cerr << "Failed to open font file" << std::endl; SDL_GL_DeleteContext(glContext); SDL_DestroyWindow(window); SDL_Quit(); return 1; } fread(ttf_buffer, 1, 1<<20, fontFile); fclose(fontFile); stbtt_fontinfo font; if (!stbtt_InitFont(&font, ttf_buffer, 0)) { std::cerr << "Failed to initialize font" << std::endl; SDL_GL_DeleteContext(glContext); SDL_DestroyWindow(window); SDL_Quit(); return 1; } // Bake font bitmap unsigned char temp_bitmap[FONT_BITMAP_WIDTH * FONT_BITMAP_HEIGHT]; if (stbtt_BakeFontBitmap(ttf_buffer, 0, 32.0f, temp_bitmap, FONT_BITMAP_WIDTH, FONT_BITMAP_HEIGHT, 32, 96, cdata) <= 0) { std::cerr << "Failed to bake font bitmap" << std::endl; SDL_GL_DeleteContext(glContext); SDL_DestroyWindow(window); SDL_Quit(); return 1; } // Create OpenGL texture glGenTextures(1, &fontTexture); glBindTexture(GL_TEXTURE_2D, fontTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, FONT_BITMAP_WIDTH, FONT_BITMAP_HEIGHT, 0, GL_RED, GL_UNSIGNED_BYTE, temp_bitmap); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Main loop bool quit = false; SDL_Event event; while (!quit) { while (SDL_PollEvent(&event)) { if (event.type == SDL_EVENT_QUIT) { quit = true; } } // Clear the screen glClearColor(0.0f, 0.0f, 0.0f, 1.f); glClear(GL_COLOR_BUFFER_BIT); // Render text float x = 20.0f; float y = 50.0f; renderText(x, y, "Hello, World!"); // Swap buffers SDL_GL_SwapWindow(window); } // Cleanup glDeleteTextures(1, &fontTexture); SDL_GL_DeleteContext(glContext); SDL_DestroyWindow(window); SDL_Quit(); return 0; }Explanation:
- SDL Initialization: Initializes SDL with video support.
- OpenGL Context Creation: Sets up an OpenGL context with a specified version (3.3 core profile).
- Viewport and Projection Setup: Configures the viewport and sets up an orthographic projection suitable for 2D rendering.
- Font Loading and Texture Creation:
- Uses
stb_truetypeto load and bake a TrueType font into a bitmap. - Creates an OpenGL texture from the bitmap containing the font glyphs.
- Uses
- Render Function (
renderText):- Renders text by mapping character glyphs from the texture atlas onto quads.
- Positions the text on the screen using the provided
xandycoordinates.
- Main Loop:
- Handles events (e.g., window close).
- Clears the screen and calls
renderTextto draw the text. - Swaps the window buffer to display the rendered frame.
Note:
- Replace
"arial.ttf"with the path to your TrueType font file. - This example uses immediate mode OpenGL (deprecated in modern OpenGL). For a production-quality game engine, consider using shaders and vertex buffers.
- Error handling is minimal for brevity.
Compiling the Code:
Make sure to link against SDL3, OpenGL, and GLEW libraries. Here’s an example command using
g++:g++ -o text_game_engine main.cpp -lSDL3 -lGL -lGLEWDependencies:
- SDL3: Make sure SDL3 is properly installed and linked.
- GLEW: Used for managing OpenGL extensions.
- stb_truetype.h: Include it in your project directory.
Further Improvements:
- Event Handling: Add keyboard and mouse input handling to interact with the game.
- Game Loop Enhancements: Implement timing control to manage frame rate.
- Modern OpenGL: Update the rendering code to use shaders and buffer objects.
- Texture Atlas Optimization: Preload and cache textures for all game assets.
- Game Engine Structure: Organize code into classes and modules for better maintainability.
Conclusion:
This basic setup provides a starting point for a 2D text game engine. From here, you can expand the engine by adding game objects, handling input, implementing game logic, and improving the rendering pipeline.