textures, overlay images, libimago
[demo_prior] / src / texture.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include "opengl.h"
4 #include "texture.h"
5 #include "imago2.h"
6 #include "opt.h"
7
8 static unsigned int gl_ifmt[2][NUM_IMG_FMT] = {
9         /* opt.srgb == 0 */
10         {GL_LUMINANCE, GL_RGB, GL_RGBA, GL_LUMINANCE16F_ARB, GL_RGB16F, GL_RGBA16F, GL_RGBA, GL_RGB},
11         /* opt.srgb == 1 */
12         {GL_SLUMINANCE, GL_SRGB, GL_SRGB_ALPHA, GL_LUMINANCE16F_ARB, GL_RGB16F, GL_RGBA16F, GL_SRGB_ALPHA, GL_SRGB}
13 };
14 static unsigned int gl_fmt[] = {
15         GL_LUMINANCE, GL_RGB, GL_RGBA, GL_LUMINANCE, GL_RGB, GL_RGBA, GL_BGRA, GL_RGB
16 };
17 static unsigned int gl_type[] = {
18         GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE, GL_FLOAT, GL_FLOAT, GL_FLOAT, GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT_5_6_5
19 };
20
21 struct texture *load_texture(const char *fname)
22 {
23         struct img_pixmap img;
24         struct texture *tex;
25         int ifmt;
26
27         img_init(&img);
28         if(img_load(&img, fname) == -1) {
29                 fprintf(stderr, "failed to load texture: %s\n", fname);
30                 return 0;
31         }
32         ifmt = gl_ifmt[opt.srgb][img.fmt];
33
34         if(!(tex = malloc(sizeof *tex))) {
35                 img_destroy(&img);
36                 fprintf(stderr, "failed to allocate texture\n");
37                 return 0;
38         }
39
40         glGenTextures(1, &tex->id);
41         glBindTexture(GL_TEXTURE_2D, tex->id);
42         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
43         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
44         glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS, 1);
45         glTexImage2D(GL_TEXTURE_2D, 0, ifmt, img.width, img.height, 0, gl_fmt[img.fmt],
46                         gl_type[img.fmt], img.pixels);
47
48         tex->width = img.width;
49         tex->height = img.height;
50         tex->pixels = img.pixels;
51         return tex;
52 }
53
54 void free_texture(struct texture *tex)
55 {
56         if(!tex) return;
57
58         if(tex->id) {
59                 glDeleteTextures(1, &tex->id);
60         }
61
62         free(tex->pixels);
63         free(tex);
64 }