source: trunk/src/tileset.cpp @ 79

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

Rendering starts to work again. There is no Z-sorting yet.

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