istereo

view src/tex.c @ 21:75a63f9ab7cc

ha!
author John Tsiombikas <nuclear@mutantstargoat.com>
date Wed, 07 Sep 2011 10:49:11 +0300
parents 32503603eb7d
children 206348366635
line source
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <errno.h>
5 #include "opengl.h"
6 #include "tex.h"
7 #include "config.h"
9 unsigned int load_texture(const char *fname)
10 {
11 unsigned int tex;
12 FILE *fp;
13 void *pixels;
14 int xsz, ysz, sz;
15 char buf[512];
17 if(!(fp = fopen(fname, "r"))) {
18 fprintf(stderr, "failed to open texture: %s: %s\n", fname, strerror(errno));
19 return 0;
20 }
22 if(!fgets(buf, sizeof buf, fp) || buf[0] != 'P' || buf[1] != '6') {
23 fprintf(stderr, "invalid format (1): %s\n", fname);
24 fclose(fp);
25 return 0;
26 }
27 if(!fgets(buf, sizeof buf, fp) || sscanf(buf, "%d %d", &xsz, &ysz) != 2) {
28 fprintf(stderr, "invalid format (2): %s\n", fname);
29 fclose(fp);
30 return 0;
31 }
32 fgets(buf, sizeof buf, fp);
34 sz = xsz * ysz * 3;
35 if(!(pixels = malloc(sz))) {
36 fprintf(stderr, "failed to allocate %d bytes\n", sz);
37 fclose(fp);
38 return 0;
39 }
40 if(fread(pixels, 1, xsz * ysz * 3, fp) < sz) {
41 fprintf(stderr, "partial read: %s\n", fname);
42 free(pixels);
43 fclose(fp);
44 return 0;
45 }
46 fclose(fp);
48 glGenTextures(1, &tex);
49 glBindTexture(GL_TEXTURE_2D, tex);
50 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
51 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
52 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
53 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
54 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, xsz, ysz, 0, GL_RGB, GL_UNSIGNED_BYTE, pixels);
55 free(pixels);
57 return tex;
58 }
60 void bind_texture(unsigned int tex, int unit)
61 {
62 glActiveTexture(GL_TEXTURE0 + unit);
64 #ifndef IPHONE
65 if(tex) {
66 glEnable(GL_TEXTURE_2D);
67 } else {
68 glDisable(GL_TEXTURE_2D);
69 }
70 #endif
72 glBindTexture(GL_TEXTURE_2D, tex);
73 }