source: trunk/src/font.cpp @ 121

Last change on this file since 121 was 121, checked in by sam, 10 years ago

Implement naive bold font printing.

  • Property svn:keywords set to Id
File size: 2.3 KB
Line 
1//
2// Deus Hax (working title)
3// Copyright (c) 2010 Sam Hocevar <sam@hocevar.net>
4//
5
6#if defined HAVE_CONFIG_H
7#   include "config.h"
8#endif
9
10#ifdef WIN32
11#   define WIN32_LEAN_AND_MEAN
12#   include <windows.h>
13#endif
14#if defined __APPLE__ && defined __MACH__
15#   include <OpenGL/gl.h>
16#else
17#   define GL_GLEXT_PROTOTYPES
18#   include <GL/gl.h>
19#endif
20
21#include <SDL.h>
22#include <SDL_image.h>
23
24#include "font.h"
25
26/*
27 * Font implementation class
28 */
29
30class FontData
31{
32    friend class Font;
33
34private:
35    char *name;
36
37    SDL_Surface *img;
38    GLuint texture[1];
39};
40
41/*
42 * Public Font class
43 */
44
45Font::Font(char const *path)
46{
47    data = new FontData();
48    data->name = strdup(path);
49    data->img = NULL;
50
51    for (char const *name = path; *name; name++)
52        if ((data->img = IMG_Load(name)))
53            break;
54
55    if (!data->img)
56    {
57        SDL_Quit();
58        exit(1);
59    }
60
61    glGenTextures(1, data->texture);
62    glBindTexture(GL_TEXTURE_2D, data->texture[0]);
63
64    glTexImage2D(GL_TEXTURE_2D, 0, 4, data->img->w, data->img->h, 0,
65                 GL_RGBA, GL_UNSIGNED_BYTE, data->img->pixels);
66
67    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
68    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
69}
70
71Font::~Font()
72{
73    glDeleteTextures(1, data->texture);
74    SDL_FreeSurface(data->img);
75
76    delete data;
77}
78
79Asset::Group Font::GetGroup()
80{
81    return GROUP_BEFORE;
82}
83
84void Font::TickRender(float delta_time)
85{
86    Asset::TickRender(delta_time);
87}
88
89char const *Font::GetName()
90{
91    return data->name;
92}
93
94void Font::Print(int x, int y, char const *str)
95{
96    int w = data->img->w / 16;
97    int h = data->img->h / 16;
98
99    glBindTexture(GL_TEXTURE_2D, data->texture[0]);
100    glBegin(GL_QUADS);
101    while (*str)
102    {
103        uint32_t ch = (uint8_t)*str++;
104        float tx = .0625f * (ch & 0xf);
105        float ty = .0625f * ((ch >> 4) & 0xf);
106
107        glTexCoord2f(tx, ty);
108        glVertex2f(x, y);
109        glTexCoord2f(tx + .0625f, ty);
110        glVertex2f(x + w, y);
111        glTexCoord2f(tx + .0625f, ty + .0625f);
112        glVertex2f(x + w, y + h);
113        glTexCoord2f(tx, ty + .0625f);
114        glVertex2f(x, y + h);
115
116        x += w;
117    }
118    glEnd();
119}
120
121void Font::PrintBold(int x, int y, char const *str)
122{
123    Print(x, y, str);
124    Print(x + 1, y, str);
125    Print(x, y + 1, str);
126}
127
Note: See TracBrowser for help on using the repository browser.