summaryrefslogtreecommitdiff
path: root/texture.c
blob: 6b63f5c04489599baeff845e04ef3235c0a3f585 (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
#include "texture.h"

i32
load_texture(struct arena *arena, struct texture *texture, const char *filename, i32 gamma)
{
    stbi_set_flip_vertically_on_load(1);
    i32 nchannels;
    u8 *data = stbi_load(filename, &texture->width, &texture->height, &nchannels, 0);
    if (!data) {
        info("failed to load \"%s\"", filename);
        return 0;
    }
    u32 internal_format, data_format;
    switch (nchannels) {
    case 1:
        texture->type = texture_r;
        internal_format = data_format = gl_red;
        break;
    case 3:
        texture->type = texture_rgb;
        internal_format = gamma ? gl_srgb : gl_rgb;
        data_format = gl_rgb;
        break;
    case 4:
        texture->type = texture_rgba;
        internal_format = gamma ? gl_srgb_alpha : gl_rgba;
        data_format = gl_rgba;
        break;
    default:
        printf("\"%s\" unsupported texture format %i", filename, nchannels);
        return 0;
    }
    u64 size = texture->type * texture->width * texture->height;
    texture->data = push_arena(arena, size);
    memmove(texture->data, data, size);
    stbi_image_free(data);

    gl_gen_textures(1, &texture->id);
    gl_bind_texture(gl_texture_2d, texture->id);
    gl_tex_image_2d(gl_texture_2d, 0, internal_format, texture->width,
                    texture->height, 0, data_format, gl_unsigned_byte,
                    texture->data);
    gl_gen_mipmap(gl_texture_2d);
    gl_tex_parami(gl_texture_2d, gl_texture_wrap_s, gl_repeat);
    gl_tex_parami(gl_texture_2d, gl_texture_wrap_t, gl_repeat);
    gl_tex_parami(gl_texture_2d, gl_texture_min_filter, gl_linear_mipmap_linear);
    gl_tex_parami(gl_texture_2d, gl_texture_mag_filter, gl_linear);
    gl_bind_texture(gl_texture_2d, 0);

    info("\"%s\" loaded successfully", filename);

    return texture->id;
}