• Advertisement
Sign in to follow this  

OpenGL Text in openGL

This topic is 3649 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

At the minute I'm using bitmap fonts and print_bitmap_string() to display text on screen. The problem I have is that it only allows me to use 7 different fonts. These fonts are all too 'skinny' which is quite hard to see on screen, I need bold text really. The trouble is that this print_bitmap_string() function is absolutely perfect for what I need -apart from the limited fonts- it is easy to place on screen, it stays the same size and always rotates to face the camera etc. However I think I need to use another method to display my text. Is there any other method which is similar but has a wider range of fonts? Ideally what I need to do is draw the character in white and have a black outline round each letter. However, if that is quite hard then I should be able to cope with a simple "chunky" font. Any ideas? Thanks.

Share this post


Link to post
Share on other sites
Advertisement
there are a few tutorials on nehe.

but i thought with bitmap fonts you can have as many as you want...

Share this post


Link to post
Share on other sites
Well I've just looked for the function and I cant find it anywhere, I must of got it from some sample code or a tutorial somewhere. But anyhow, with the print_bitmap_string() function I can only use the following fonts:

GLUT_BITMAP_9_BY_15
GLUT_BITMAP_8_BY_13
GLUT_BITMAP_HELVETICA_18
GLUT_BITMAP_HELVETICA_12
GLUT_BITMAP_HELVETICA_10
GLUT_BITMAP_TIMES_ROMAN_24
GLUT_BITMAP_TIMES_ROMAN_10


The code I've got to print something is:

char string[0][256];
string[0][0] = 'H'; string[0][1] = 'e'; string[0][2] = 'l'; string[0][3] = 'p';

glRasterPos3f(42000, 75000, -3000);
print_bitmap_string( GLUT_BITMAP_9_BY_15 , string[0]);



That's all I do, I've not included any fancy libraries or anything.
I'll have to look through some tutorials, maybe I'm using the wrong type of function to use bitmap fonts.

***edit*** Sorry, just realised that the print_bitmap_string function actually makes a call to glutBitmapCharacter() function. No wonder I couldn't find it anywhere... :-S

[Edited by - mpledge52 on February 22, 2008 2:18:56 PM]

Share this post


Link to post
Share on other sites
Yeah, the GLUT has only few fonts hardcoded as (small) bitmaps. You can use font libraries like freetype or SDL_TTF to load and render any truetype font you want to image(s), then use it as texture. There is also a Nehe tutorial on bitmap fonts although it uses some os-specific functions.

Share this post


Link to post
Share on other sites
Thanks snoutmate, do you know if the bitmap fonts used in the Nehe tutorial (or any other fonts for that matter) behave in the same way as the bitmap fonts I have used so far? i.e. the stay the same size no matter where the camera is positioned, and (more importantly) the text rotates to face the camera at all times.

Thanks again.

Share this post


Link to post
Share on other sites
That is different thing alltogether - if you want something drawn this way (text, HUD in games, etc.), you simply draw your scene, then set orthogonal projection matrix (glOrtho) and render the text (you'd also want to disable things like depth buffer and lighting usually for this pass).

Share this post


Link to post
Share on other sites
You could always use freetype. Here's my simple wrapper I use for loading and drawing text.


#ifndef _FT_WRAPPER_H
#define _FT_WRAPPER_H

#include <string>
#include <vector>
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_GLYPH_H

namespace freetype
{
// Glyph entry structure
// stores data for a single ascii character
struct GlyphEntry
{
unsigned char ascii, width, height;
unsigned short x, y;
};

// Font data structure
// stores all infomration pertaining to a loaded font
struct FontData
{
std::string fontFile;
float fontSize;
int pixelSize;
bool antiAlias;
unsigned char* imagePixels;
size_t imageWidth;
size_t imageHeight;

std::vector<GlyphEntry> glyphEntries;
unsigned char glyphBase;
};

// Frees any memory associated with FontData object
void FreeFont(FontData* font)
{
delete[] font->imagePixels;
font->glyphEntries.clear();
delete font;
}

// Creates a truetype font from specified fontfile
FontData* LoadFont(const std::string& fontfile, float font_size, bool antialias)
{
// Create new FontData object
FontData* fontData = new FontData;
fontData->fontFile = fontfile;
fontData->fontSize = font_size;
fontData->antiAlias = antialias;

// Compute pixel size
size_t y_resolution = 96;
size_t pixel_size = font_size * y_resolution / 72;

// Margins around characters to prevent them from 'bleeding' into each other
const size_t margin = 3;
size_t image_height = 0;
size_t image_width = 256;

// Initialize FreeType
FT_Library library;
if (FT_Init_FreeType(&library) != 0)
throw "Could not initialize FreeType2 library.";

// Load the font
FT_Face face;
if (FT_New_Face(library, fontfile.c_str(), 0, &face) != 0)
throw "Could not load font file.";

// Abort if this is not a 'true type', scalable font
if (!(face->face_flags & FT_FACE_FLAG_SCALABLE) || !(face->face_flags && FT_FACE_FLAG_HORIZONTAL))
throw "Error setting font size.";

// Set the font size
FT_Set_Pixel_Sizes(face, pixel_size, 0);

// First we go over all the characters to find the max descent
// and ascent (space required above and below the base of a
// line of text) and needed image size. There are simpler methods
// to obtain these with FreeType but they are unreliable.
int max_descent = 0, max_ascent = 0;
size_t space_on_line = image_width - margin, lines = 1;

unsigned int startChar = 32;
unsigned int endChar = 126;
for (unsigned int i = startChar; i <= endChar; i++) {

// Look up the character in the font file
size_t char_index = FT_Get_Char_Index(face, i);

// Render the current glyph
FT_Load_Glyph(face, char_index, FT_LOAD_DEFAULT);
FT_Render_Glyph(face->glyph, FT_RENDER_MODE_NORMAL);

size_t advance = (face->glyph->metrics.horiAdvance >> 6) + margin;

// If the line is full, go to the next line
if (advance > space_on_line) {
space_on_line = image_width - margin;
lines++;
}

space_on_line -= advance;

max_ascent = max(face->glyph->bitmap_top, max_ascent);
max_descent = max(face->glyph->bitmap.rows - face->glyph->bitmap_top, max_descent);
}

// Compute how high the texture has to be
size_t needed_image_height = (max_ascent + max_descent + margin) * lines + margin;

// Get the first power of two in which it fits
image_height = 16;
while (image_height < needed_image_height)
image_height *= 2;

// Allocate memory for the texture
unsigned char* image = new unsigned char[image_width * image_height];
for (unsigned int i = 0; i < image_width * image_height; i++)
image = 0;

// Allocate space for the glyph entries
fontData->glyphEntries.resize(endChar - startChar + 1);
fontData->glyphBase = startChar;

// These are the positions at which to draw the next glyph
unsigned int x = margin, y = margin + max_ascent;

// Drawing loop
for (unsigned int i = startChar; i <= endChar; i++) {

unsigned int char_index = FT_Get_Char_Index(face, i);

// Handle antialias text
if (antialias == true) {

// Render the glyph
FT_Load_Glyph(face, char_index, FT_LOAD_DEFAULT);
FT_Render_Glyph(face->glyph, FT_RENDER_MODE_NORMAL);

// See whether the character fits on the current line
unsigned int advance = (face->glyph->metrics.horiAdvance >> 6) + margin;
if (advance > image_width - x) {
x = margin;
y += (max_ascent + max_descent + margin);
}

// Fill in the glyph entries
fontData->glyphEntries[i - startChar].ascii = (unsigned char)i;
fontData->glyphEntries[i - startChar].width = advance - margin;
fontData->glyphEntries[i - startChar].height = pixel_size;
fontData->glyphEntries[i - startChar].x = x;
fontData->glyphEntries[i - startChar].y = y - max_ascent;

// Copy the image gotten from FreeType onto the texture at the correct position
for (unsigned int row = 0; row < face->glyph->bitmap.rows; row++) {
for (unsigned int pixel = 0; pixel < face->glyph->bitmap.width; pixel++) {

image[(x + face->glyph->bitmap_left + pixel) + (y - face->glyph->bitmap_top + row) * image_width] =
face->glyph->bitmap.buffer[pixel + row * face->glyph->bitmap.pitch];
}
}

x += advance;
}
// Handle monochrome text
else {

// Render the glyph
FT_Bitmap* ft_bmp;
FT_Glyph glyph;
FT_BitmapGlyph bmp_glyph;

FT_Load_Glyph(face, char_index, FT_LOAD_DEFAULT);
FT_Render_Glyph(face->glyph, FT_RENDER_MODE_MONO);
FT_Get_Glyph(face->glyph, &glyph);

FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_MONO, 0, 1);

bmp_glyph = (FT_BitmapGlyph)glyph;
ft_bmp = &bmp_glyph->bitmap;

// See whether the character fits on the current line
unsigned int advance = (face->glyph->metrics.horiAdvance >> 6) + margin;
if (advance > image_width - x) {
x = margin;
y += (max_ascent + max_descent + margin);
}

// Fill in the glyph entries
fontData->glyphEntries[i - startChar].ascii = (unsigned char)i;
fontData->glyphEntries[i - startChar].width = advance - margin;
fontData->glyphEntries[i - startChar].height = pixel_size;
fontData->glyphEntries[i - startChar].x = x;
fontData->glyphEntries[i - startChar].y = y - max_ascent;

// Copy the image onto the texture at the correct position
unsigned char* monochromeData = ft_bmp->buffer;
int bit;

for (size_t row = 0; row < ft_bmp->rows; row++) {

unsigned char* nextPtr = monochromeData + ft_bmp->pitch;
bit = 7;

for (size_t pixel = 0; pixel < ft_bmp->width; pixel++) {

unsigned char value = (*monochromeData & (1 << bit)) >> bit;

image[(x + bmp_glyph->left + pixel) + (y - bmp_glyph->top + row) * image_width] = value;

bit--;
if (bit == -1) {
bit = 7;
monochromeData++;
}
}

bit = 7;
monochromeData = nextPtr;
}

x += advance;

}
}

// Return FT_FontData object
fontData->pixelSize = pixel_size;
fontData->imagePixels = image;
fontData->imageWidth = image_width;
fontData->imageHeight = image_height;
return fontData;
}
}

#endif





freetype::FontData* font;
GLuint texID;

void init()
{
font = freetype::LoadFont("c:\\windows\\fonts\\arial.ttf", 9.0f, false);
CreateTextureFromFont(&fontTexID, *font);
}

void CreateTextureFromFont(GLuint* texID, const freetype::FontData& font)
{
glGenTextures(1, texID);
glBindTexture(GL_TEXTURE_2D, *texID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, font.imageWidth, font.imageHeight, 0, GL_ALPHA, GL_UNSIGNED_BYTE, font.imagePixels);
}

void drawString(freetype::FontData* f, GLuint texID, std::string str)
{
if (f->antiAlias) {
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
else {
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER, 0);
}

glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texID);

glBegin(GL_QUADS);
glColor4f(0, 0, 1, 1);

float x = 0, y = 0;

for (int i = 0; i < str.size(); i++) {

freetype::GlyphEntry g = f->glyphEntries[str - f->glyphBase];

float tx1 = g.x / (float)f->imageWidth;
float ty1 = g.y / (float)f->imageHeight;
float tx2 = (g.x + g.width) / (float)f->imageWidth;
float ty2 = (g.y + g.height) / (float)f->imageHeight;

glTexCoord2f(tx1, ty1); glVertex2i(x, y);
glTexCoord2f(tx2, ty1); glVertex2i(x + g.width, y);
glTexCoord2f(tx2, ty2); glVertex2i(x + g.width, y + g.height);
glTexCoord2f(tx1, ty2); glVertex2i(x, y + g.height);

x += g.width;
}

glEnd();

if (f->antiAlias) {
glDisable(GL_BLEND);
}
else {
glDisable(GL_ALPHA_TEST);
}
}


Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Tags

  • Advertisement
  • Popular Now

  • Similar Content

    • By LifeArtist
      Good Evening,
      I want to make a 2D game which involves displaying some debug information. Especially for collision, enemy sights and so on ...
      First of I was thinking about all those shapes which I need will need for debugging purposes: circles, rectangles, lines, polygons.
      I am really stucked right now because of the fundamental question:
      Where do I store my vertices positions for each line (object)? Currently I am not using a model matrix because I am using orthographic projection and set the final position within the VBO. That means that if I add a new line I would have to expand the "points" array and re-upload (recall glBufferData) it every time. The other method would be to use a model matrix and a fixed vbo for a line but it would be also messy to exactly create a line from (0,0) to (100,20) calculating the rotation and scale to make it fit.
      If I proceed with option 1 "updating the array each frame" I was thinking of having 4 draw calls every frame for the lines vao, polygons vao and so on. 
      In addition to that I am planning to use some sort of ECS based architecture. So the other question would be:
      Should I treat those debug objects as entities/components?
      For me it would make sense to treat them as entities but that's creates a new issue with the previous array approach because it would have for example a transform and render component. A special render component for debug objects (no texture etc) ... For me the transform component is also just a matrix but how would I then define a line?
      Treating them as components would'nt be a good idea in my eyes because then I would always need an entity. Well entity is just an id !? So maybe its a component?
      Regards,
      LifeArtist
    • By QQemka
      Hello. I am coding a small thingy in my spare time. All i want to achieve is to load a heightmap (as the lowest possible walking terrain), some static meshes (elements of the environment) and a dynamic character (meaning i can move, collide with heightmap/static meshes and hold a varying item in a hand ). Got a bunch of questions, or rather problems i can't find solution to myself. Nearly all are deal with graphics/gpu, not the coding part. My c++ is on high enough level.
      Let's go:
      Heightmap - i obviously want it to be textured, size is hardcoded to 256x256 squares. I can't have one huge texture stretched over entire terrain cause every pixel would be enormous. Thats why i decided to use 2 specified textures. First will be a tileset consisting of 16 square tiles (u v range from 0 to 0.25 for first tile and so on) and second a 256x256 buffer with 0-15 value representing index of the tile from tileset for every heigtmap square. Problem is, how do i blend the edges nicely and make some computationally cheap changes so its not obvious there are only 16 tiles? Is it possible to generate such terrain with some existing program?
      Collisions - i want to use bounding sphere and aabb. But should i store them for a model or entity instance? Meaning i have 20 same trees spawned using the same tree model, but every entity got its own transformation (position, scale etc). Storing collision component per instance grats faster access + is precalculated and transformed (takes additional memory, but who cares?), so i stick with this, right? What should i do if object is dynamically rotated? The aabb is no longer aligned and calculating per vertex min/max everytime object rotates/scales is pretty expensive, right?
      Drawing aabb - problem similar to above (storing aabb data per instance or model). This time in my opinion per model is enough since every instance also does not have own vertex buffer but uses the shared one (so 20 trees share reference to one tree model). So rendering aabb is about taking the model's aabb, transforming with instance matrix and voila. What about aabb vertex buffer (this is more of a cosmetic question, just curious, bumped onto it in time of writing this). Is it better to make it as 8 points and index buffer (12 lines), or only 2 vertices with min/max x/y/z and having the shaders dynamically generate 6 other vertices and draw the box? Or maybe there should be just ONE 1x1x1 cube box template moved/scaled per entity?
      What if one model got a diffuse texture and a normal map, and other has only diffuse? Should i pass some bool flag to shader with that info, or just assume that my game supports only diffuse maps without fancy stuff?
      There were several more but i forgot/solved them at time of writing
      Thanks in advance
    • By RenanRR
      Hi All,
      I'm reading the tutorials from learnOpengl site (nice site) and I'm having a question on the camera (https://learnopengl.com/Getting-started/Camera).
      I always saw the camera being manipulated with the lookat, but in tutorial I saw the camera being changed through the MVP arrays, which do not seem to be camera, but rather the scene that changes:
      Vertex Shader:
      #version 330 core layout (location = 0) in vec3 aPos; layout (location = 1) in vec2 aTexCoord; out vec2 TexCoord; uniform mat4 model; uniform mat4 view; uniform mat4 projection; void main() { gl_Position = projection * view * model * vec4(aPos, 1.0f); TexCoord = vec2(aTexCoord.x, aTexCoord.y); } then, the matrix manipulated:
      ..... glm::mat4 projection = glm::perspective(glm::radians(fov), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); ourShader.setMat4("projection", projection); .... glm::mat4 view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); ourShader.setMat4("view", view); .... model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); ourShader.setMat4("model", model);  
      So, some doubts:
      - Why use it like that?
      - Is it okay to manipulate the camera that way?
      -in this way, are not the vertex's positions that changes instead of the camera?
      - I need to pass MVP to all shaders of object in my scenes ?
       
      What it seems, is that the camera stands still and the scenery that changes...
      it's right?
       
       
      Thank you
       
    • By dpadam450
      Sampling a floating point texture where the alpha channel holds 4-bytes of packed data into the float. I don't know how to cast the raw memory to treat it as an integer so I can perform bit-shifting operations.

      int rgbValue = int(textureSample.w);//4 bytes of data packed as color
      // algorithm might not be correct and endianness might need switching.
      vec3 extractedData = vec3(  rgbValue & 0xFF000000,  (rgbValue << 8) & 0xFF000000, (rgbValue << 16) & 0xFF000000);
      extractedData /= 255.0f;
    • By Devashish Khandelwal
      While writing a simple renderer using OpenGL, I faced an issue with the glGetUniformLocation function. For some reason, the location is coming to be -1.
      Anyone has any idea .. what should I do?
  • Advertisement