aboutsummaryrefslogtreecommitdiff
path: root/src/libjin/render/texture.cpp
blob: d9abe406339d5650f44a79840f0f04fb8691f2b3 (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
#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 render
{

    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)
    {
        if (without(x, 0, width) || without(y, 0, height))
        {
            return { 0 };
        }
        return pixels[x + y * width];
    }
    
    bool Texture::loadb(const void* b, size_t size)
    {
        // ʹstbi_load_from_memory
        unsigned char* textureData = stbi_load_from_memory((unsigned char *)b, size, &width, &height, NULL, STBI_rgb_alpha);
        if (textureData == 0) return false;
        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, width,
            height, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData);

        // set render vertices 
        Drawable::setVertices(
            new float [DRAWABLE_V_SIZE] {
            0, 0,
            0, (float)height,
            (float)width, (float)height,
            (float)width, 0,
        },
            new float [DRAWABLE_V_SIZE] {
                0, 0,
                0, 1,
                1, 1,
                1, 0
            }
            );

        return true; 
    }
}
}

#endif // JIN_MODULES_RENDER