00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029 #include <types.h>
00030 #include <errno.h>
00031
00032 #include "ppm.h"
00033
00034 static void skip_whitespace(unsigned char **data)
00035 {
00036 retry:
00037 while (**data == ' ' || **data == '\t' || **data == '\n' || **data == '\r')
00038 (*data)++;
00039 if (**data == '#') {
00040 while (1) {
00041 if (**data == '\n' || **data == '\r')
00042 break;
00043 (*data)++;
00044 }
00045 goto retry;
00046 }
00047 }
00048
00049 static void read_num(unsigned char **data, unsigned int *num)
00050 {
00051 *num = 0;
00052 while (**data >= '0' && **data <= '9') {
00053 *num *= 10;
00054 *num += **data - '0';
00055 (*data)++;
00056 }
00057 }
00058
00059 int ppm_get_data(unsigned char *data, size_t dtsz, unsigned int *width, unsigned int *height)
00060 {
00061
00062 if (data[0] != 'P' || data[1] != '6')
00063 return EINVAL;
00064
00065 data+=2;
00066 skip_whitespace(&data);
00067 read_num(&data, width);
00068 skip_whitespace(&data);
00069 read_num(&data,height);
00070
00071 return 0;
00072 }
00073
00084 int ppm_draw(unsigned char *data, size_t datasz, unsigned int sx,
00085 unsigned int sy,
00086 unsigned int maxwidth, unsigned int maxheight,
00087 putpixel_cb_t putpixel, void *vport)
00088 {
00089 unsigned int width, height;
00090 unsigned int maxcolor;
00091 int i;
00092 unsigned int color;
00093 unsigned int coef;
00094
00095
00096 if (data[0] != 'P' || data[1] != '6')
00097 return EINVAL;
00098
00099 data+=2;
00100 skip_whitespace(&data);
00101 read_num(&data, &width);
00102 skip_whitespace(&data);
00103 read_num(&data,&height);
00104 skip_whitespace(&data);
00105 read_num(&data,&maxcolor);
00106 data++;
00107
00108 if (maxcolor == 0 || maxcolor > 255 || width*height > datasz) {
00109 return EINVAL;
00110 }
00111 coef = 255/maxcolor;
00112 if (coef*maxcolor > 255)
00113 coef -= 1;
00114
00115 for (i=0; i < width*height; i++) {
00116
00117 if (i % width > maxwidth || i/width > maxheight) {
00118 data += 3;
00119 continue;
00120 }
00121 color = ((data[0]*coef) << 16) + ((data[1]*coef) << 8) + data[2]*coef;
00122
00123 (*putpixel)(vport, sx+(i % width), sy+(i / width), color);
00124 data += 3;
00125 }
00126
00127 return 0;
00128 }