aboutsummaryrefslogtreecommitdiff
path: root/src/libjin/Graphics/Texture.cpp
blob: f3c08fbee8df0d81e7cf7c57098e6b5010ec6ce2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include "../modules.h"
#if JIN_MODULES_RENDER

#include <fstream>
#include "texture.h"
#include "../3rdparty/stb/stb_image.h"
#include "../utils/utils.h"
#include "../Math/Math.h"

namespace jin
{
namespace graphics
{

    using namespace jin::math;

    Texture* Texture::createTexture(const char* file)
    {
        std::ifstream fs; 
        fs.open(file, std::ios::binary);
        Texture* tex = nullptr;
        if (fs.is_open())
        {
            fs.seekg(0, std::ios::end); 
            int size = fs.tellg();
            fs.seekg(0, std::ios::beg); 
            char* buffer = (char*)malloc(size); 
            memset(buffer, 0, size);
            fs.read(buffer, size);
            tex = createTexture(buffer, size);
            free(buffer);
        }
        fs.close();
        return tex; 
    }

    Texture* Texture::createTexture(const void* mem, size_t size)
    {
        Texture* tex = new Texture(); 
        if(!tex->loadb(mem, size))
        {
            delete tex; 
            tex = nullptr;
        }
        return tex;
    }

    Texture::Texture()
        : Drawable(), pixels(0)
    {
    }

    Texture::~Texture()
    {
        stbi_image_free(pixels);
    }

    color Texture::getPixel(int x, int y)
    {
        int w = size.x; 
        int h = size.y;
        if (without(x, 0, w) || without(y, 0, h))
        {
            return { 0 };
        }
        return pixels[x + y * w];
    }
    
    bool Texture::loadb(const void* b, size_t s)
    {
        // ʹstbi_load_from_memory
        int w;
        int h;
        unsigned char* textureData = stbi_load_from_memory((unsigned char *)b, s, &w, &h, NULL, STBI_rgb_alpha);
        if (textureData == 0) return false;
        size.x = w; 
        size.y = h;
        pixels = (color*)textureData;

        glGenTextures(1, &texture);
        glBindTexture(GL_TEXTURE_2D, texture);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData);

        vertCoord[0] = 0; vertCoord[1] = 1;
        vertCoord[2] = 0; vertCoord[3] = h;
        vertCoord[4] = w; vertCoord[5] = h;
        vertCoord[6] = w; vertCoord[7] = 1;

        textCoord[0] = 0; textCoord[1] = 0;
        textCoord[2] = 0; textCoord[3] = 1;
        textCoord[4] = 1; textCoord[5] = 1;
        textCoord[6] = 1; textCoord[7] = 0;

        return true; 
    }

} // graphics
} // jin

#endif // JIN_MODULES_RENDER