1 2typedef struct { 3 size_t sizeX, sizeY; 4 GLubyte *data; 5} PPMImage; 6 7static PPMImage *LoadPPM(const char *filename) 8{ 9 char buff[16]; 10 PPMImage *result; 11 FILE *fp; 12 int maxval, w, h; 13 14 fp = fopen(filename, "rb"); 15 if (!fp) 16 { 17 fprintf(stderr, "Unable to open file `%s'\n", filename); 18 exit(1); 19 } 20 21 if (!fgets(buff, sizeof(buff), fp)) 22 { 23 perror(filename); 24 exit(1); 25 } 26 27 if (buff[0] != 'P' || buff[1] != '6') 28 { 29 fprintf(stderr, "Invalid image format (must be `P6')\n"); 30 exit(1); 31 } 32 33 result = (PPMImage *) malloc(sizeof(PPMImage)); 34 if (!result) 35 { 36 fprintf(stderr, "Unable to allocate memory\n"); 37 exit(1); 38 } 39 40 if (fscanf(fp, "%d %d", &w, &h) != 2) 41 { 42 fprintf(stderr, "Error loading image `%s'\n", filename); 43 exit(1); 44 } 45 result->sizeX = w; 46 result->sizeY = h; 47 48 if (fscanf(fp, "%d", &maxval) != 1) 49 { 50 fprintf(stderr, "Error loading image `%s'\n", filename); 51 exit(1); 52 } 53 54 while (fgetc(fp) != '\n') 55 ; 56 57 result->data = (GLubyte *) malloc(3 * result->sizeX * result->sizeY); 58 if (!result) 59 { 60 fprintf(stderr, "Unable to allocate memory\n"); 61 exit(1); 62 } 63 64 if (fread(result->data, 3 * result->sizeX, result->sizeY, fp) != result->sizeY) 65 { 66 fprintf(stderr, "Error loading image `%s'\n", filename); 67 exit(1); 68 } 69 70 fclose(fp); 71 72 return result; 73} 74 75