istereo

view src/tex.c @ 25:206348366635

trying to figure out why the textures are looking crappy on ipod
author John Tsiombikas <nuclear@mutantstargoat.com>
date Thu, 08 Sep 2011 04:23:56 +0300
parents 4c20f10a7183
children 862a3329a8f0
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 unsigned char *pixels;
14 int xsz, ysz, sz, i;
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 * 4;
35 if(!(pixels = malloc(sz))) {
36 fprintf(stderr, "failed to allocate %d bytes\n", sz);
37 fclose(fp);
38 return 0;
39 }
40 for(i=0; i<sz; i++) {
41 int c;
43 if(i % 4 == 3) {
44 pixels[i] = 255;
45 continue;
46 }
48 if((c = fgetc(fp)) == -1) {
49 fprintf(stderr, "partial read: %s\n", fname);
50 free(pixels);
51 fclose(fp);
52 return 0;
53 }
54 pixels[i] = c;
55 }
56 fclose(fp);
58 glGenTextures(1, &tex);
59 glBindTexture(GL_TEXTURE_2D, tex);
60 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
61 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
62 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
63 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
64 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, xsz, ysz, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
65 free(pixels);
67 return tex;
68 }
70 void bind_texture(unsigned int tex, int unit)
71 {
72 glActiveTexture(GL_TEXTURE0 + unit);
74 #ifndef IPHONE
75 if(tex) {
76 glEnable(GL_TEXTURE_2D);
77 } else {
78 glDisable(GL_TEXTURE_2D);
79 }
80 #endif
82 glBindTexture(GL_TEXTURE_2D, tex);
83 }