chiark / gitweb /
49385a2fb8b89e822562ea7408118aeafc892a82
[ypp-sc-tools.db-live.git] / pctb / structure.c
1 /*
2  * Parsing of the structure of the YPP client's displayed image
3  */
4 /*
5  *  This is part of ypp-sc-tools, a set of third-party tools for assisting
6  *  players of Yohoho Puzzle Pirates.
7  * 
8  *  Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
9  * 
10  *  This program is free software: you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License as published by
12  *  the Free Software Foundation, either version 3 of the License, or
13  *  (at your option) any later version.
14  * 
15  *  This program is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU General Public License for more details.
19  * 
20  *  You should have received a copy of the GNU General Public License
21  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  * 
23  *  Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
24  *  are used without permission.  This program is not endorsed or
25  *  sponsored by Three Rings.
26  */
27
28 #include "structure.h"
29
30 static CanonImage *cim;
31
32 static inline char get(int x, int y) { return cim->d[y * cim->w + x]; }
33 static inline char get_p(Point p) { return get(p.x,p.y); }
34
35 #define START_MAIN {200,200}
36 #define MIN_COLUMNS         6
37 #define INTERESTING_COLUMNS 7
38 #define TEXT_COLUMNS        2
39 #define MAX_COLUMNS         7
40
41 static Rect mainr = { START_MAIN,START_MAIN };
42 static int commbasey, comminty;
43 static int colrightx[INTERESTING_COLUMNS];
44 static int text_h=-1, columns=-1;
45 static OcrReader *rd;
46
47 const CanonColourInfo canoncolourinfos[]= {
48   { 0x475A5E, '*' }, /* edge */
49   { 0x2C5F7A, '*' }, /* edge just under box heading shadow */
50   { 0xC5C7Ae, '*' }, /* blank area of partial commodities list */
51   { 0x7D9094, '+' }, /* interbox */
52
53   { 0xBDC5BF, ' ' }, /* background - pale  Sugar cane, etc. */
54   { 0xADB5AF, ' ' }, /* background - dark                   */
55   { 0xC7E1C3, ' ' }, /* background - pale  Swill, etc.      */
56   { 0xB5CFB1, ' ' }, /* background - dark                   */
57   { 0xD6CEB0, ' ' }, /* background - pale  Madder, etc.     */
58   { 0xC8C0A2, ' ' }, /* background - dark                   */
59   { 0xE0E1D3, ' ' }, /* background - pale  Lorandite, etc.  */
60   { 0xD0D1C3, ' ' }, /* background - dark                   */
61   { 0xE5E6C1, ' ' }, /* background - pale  Cloth            */
62   { 0xD7D8B3, ' ' }, /* background - dark                   */
63   { 0xEDDED9, ' ' }, /* background - pale  Dye              */
64   { 0xDACBC6, ' ' }, /* background - dark                   */
65   { 0xD3DEDF, ' ' }, /* background - pale  Paint            */
66   { 0xC5D0D1, ' ' }, /* background - dark                   */
67   { 0xDCD1CF, ' ' }, /* background - pale  Enamel           */
68   { 0xCEC3C1, ' ' }, /* background - dark                   */
69   { 0xF3F6F5, ' ' }, /* background - pale  fruit            */
70   { 0xE2E7E5, ' ' }, /* background - dark                   */
71
72   { 0x000000, 'o' }, /* foreground */
73   { 0xD4B356, ' ' }, /* background (cursor) */
74   { 0xFFFFFF, 'o' }, /* foreground (cursor) */
75
76   { 0x5B93BF, '_' }, /* selector dropdown background */
77   { 0xD7C94F, 'X' }, /* selector dropdown foreground */
78   { 0,0 }
79 };
80
81
82 static void mustfail1(const char *file, int line, const char *what) {
83   fprintf(stderr,
84           "\n\n"
85           "Unable to figure out contents YPP client display.\n"
86           " Check that your client is logged in has the correct display.\n"
87           " If that isn't the problem, please report this as a fault.\n\n"
88           "Technical details:"
89           " %s:%d: requirement failed: %s\n",
90           file, line, what);
91 }
92 static void mustfail2(void) NORET;
93 static void mustfail2(void) {
94   fprintf(stderr, "\n\nGiving up.\n");
95   exit(8);
96 }
97
98 #define MUST(x, ifnot) do{                      \
99     if (!(x)) {                                 \
100       mustfail1(__FILE__,__LINE__,#x);          \
101       ifnot;                                    \
102       mustfail2();                              \
103     }                                           \
104   }while(0)
105
106 #define MP(v) fprintf(stderr," %s=%d,%d",#v,(v).x,(v).y)
107 #define MI(v) fprintf(stderr," %s=%d",   #v,(v))
108 #define MC(v) fprintf(stderr," %s='%c'", #v,(v))
109 #define MS(v) fprintf(stderr," %s=\"%s\"", #v,(v))
110 #define MSB(v) fprintf(stderr," %s", (v))
111 #define MR(v) fprintf(stderr," %s=%d,%d..%d,%d",\
112                       #v,(v).tl.x,(v).tl.y,(v).br.x,(v).br.y)
113
114
115 #define REQUIRE_RECTANGLE(tlx,tly,brx,bry,ok) \
116  require_rectangle(tlx, tly, brx, bry, ok, __LINE__);
117
118 static void require_rectangle(int tlx, int tly, int brx, int bry,
119                               const char *ok, int lineno) {
120   Point p;
121   for (p.x=tlx; p.x<=brx; p.x++)
122     for (p.y=tly; p.y<=bry; p.y++) {
123       int c= get_p(p);
124       MUST( strchr(ok,c), ({
125              Rect rm={{tlx,tly},{brx,bry}};
126              MI(lineno),MR(rm);MP(p);MS(ok);
127       }));
128     }
129 }
130 static void require_rectangle_r(Rect rr, const char *ok, int lineno) {
131   require_rectangle(rr.tl.x,rr.tl.y, rr.br.x,rr.br.y, ok, lineno);
132 }
133
134 static void debug_rect(const char *what, int whati, Rect rr) {
135   if (!DEBUGP(rect)) return;
136   int y,w;
137   fprintf(debug, "%s %d: %d,%d..%d,%d:\n", what, whati,
138           rr.tl.x,rr.tl.y, rr.br.x,rr.br.y);
139   w= rr.br.x - rr.tl.x + 1;
140   for (y=rr.tl.y; y<=rr.br.y; y++) {
141     fprintf(debug, "%4d%*s|", y, rr.tl.x,"");
142     fwrite(cim->d + y*cim->w + rr.tl.x, 1, w, debug);
143     fputc('|',debug);
144     fputc('\n',debug);
145   }
146   debug_flush();
147 }
148
149 #define WALK_UNTIL(point,coord,increm,last,edge)                        \
150   for (;;) {                                                            \
151     if ((point).coord == (last)+(increm)) break;                        \
152     if (get_p((point)) == (edge)) { (point).coord -= (increm); break; } \
153     (point).coord += (increm);                                          \
154   }
155
156 #define WALK_UNTIL_MUST(point,coord,increm,last,edge)   \
157   do {                                                  \
158     WALK_UNTIL(point,coord,increm,last,edge);           \
159     MUST( (point).coord != (last)+(increm),             \
160           MP(point); MI(increm); MI(last); MC(edge);    \
161           );                                            \
162   }while(0)
163
164 void find_structure(CanonImage *im) {
165   cim= im;
166   
167   Rect whole = { {0,0}, {cim->w-1,cim->h-1} };
168
169   WALK_UNTIL_MUST(mainr.tl, x,-1, whole.tl.x, '*');
170   WALK_UNTIL_MUST(mainr.tl, y,-1, whole.tl.y, '*');
171   WALK_UNTIL_MUST(mainr.br, x,+1, whole.br.x, '*');
172   WALK_UNTIL_MUST(mainr.br, y,+1, whole.br.y, '*');
173
174   REQUIRE_RECTANGLE(mainr.tl.x-1, mainr.tl.y, mainr.tl.x-1, mainr.br.y, "*");
175   REQUIRE_RECTANGLE(mainr.br.x+1, mainr.tl.y, mainr.br.x+1, mainr.br.y, "*");
176   REQUIRE_RECTANGLE(mainr.tl.x, mainr.tl.y-1, mainr.br.x, mainr.tl.y-1, "*");
177   REQUIRE_RECTANGLE(mainr.tl.x, mainr.br.y+1, mainr.br.x, mainr.br.y+1, "*");
178
179 #define CHECK_STRIP_BORDER(tlbr,xy,increm)              \
180   do {                                                  \
181     Point csb_p;                                        \
182     Rect csb_r;                                         \
183     csb_p= mainr.tl;                                    \
184     csb_p.xy= mainr.tlbr.xy;                            \
185     if (get_p(csb_p)=='+') {                            \
186       csb_r= mainr;                                     \
187       csb_r.tl.xy= csb_p.xy;                            \
188       csb_r.br.xy= csb_p.xy;                            \
189       require_rectangle_r(csb_r, "+", __LINE__);        \
190       mainr.tlbr.xy += increm;                          \
191     }                                                   \
192   } while(0)
193
194   debug_rect("mainr",0, mainr);
195
196   CHECK_STRIP_BORDER(tl,x,+1);
197   CHECK_STRIP_BORDER(tl,y,+1);
198   CHECK_STRIP_BORDER(br,x,-1);
199   CHECK_STRIP_BORDER(br,y,-1);
200
201   debug_rect("mainr",1, mainr);
202
203   Point up = START_MAIN;
204   WALK_UNTIL_MUST(up, y,-1, mainr.tl.y, '+');
205
206   Point down = START_MAIN;
207   down.y++;
208   WALK_UNTIL_MUST(down, y,+1, mainr.br.y, '+');
209
210   if (DEBUGP(rect)) {
211     int xscaleunit, y,x;
212     for (y=0, xscaleunit=1; y<4; y++, xscaleunit*=10) {
213       fprintf(debug,"     ");
214       for (x=0; x<=cim->w; x++) {
215         if (x % xscaleunit) fputc(' ',debug);
216         else fprintf(debug,"%d",(x / xscaleunit)%10);
217       }
218       fputc('\n',debug);
219     }
220   }
221
222   commbasey= up.y;
223   comminty= down.y - up.y + 2;
224
225   Point across= { mainr.tl.x, commbasey };
226   int colno=0;
227   for (;;) {
228     MUST( get_p(across) != '+', MI(colno);MP(across);MR(mainr);MI(commbasey) );
229     WALK_UNTIL(across, x,+1, mainr.br.x, '+');
230     MUST( colno < MAX_COLUMNS, MP(across);MR(mainr);MI(commbasey); );
231     int colrx= across.x;
232     if (colrx > mainr.br.x) colrx= mainr.br.x;
233     if (colno < INTERESTING_COLUMNS)
234       colrightx[colno]= colrx;
235       
236     colno++;
237     
238     if (across.x >= mainr.br.x-1)
239       break;
240
241     across.x++;
242     REQUIRE_RECTANGLE(across.x,mainr.tl.y, across.x,mainr.br.y, "+");
243     across.x++;
244   }
245   MUST( colno >= MIN_COLUMNS, MI(colno);MR(mainr);MP(across); );
246
247 #define SET_ONCE(var,val) do{                                           \
248     int v= (val);                                                       \
249     if ((var)==-1) (var)= v;                                            \
250     else MUST( (var) == v, MSB(#var);MI((var));MI(v);MR(mainr); );      \
251   }while(0)
252
253   SET_ONCE(columns, colno);
254   SET_ONCE(text_h, comminty - 1);
255 }                   
256
257 CanonImage *alloc_canon_image(int w, int h) {
258   CanonImage *im= mmalloc(sizeof(CanonImage) + w*h);
259   im->w= w;
260   im->h= h;
261   memset(im->d,'?',w*h);
262   return im;
263 }
264
265 static void file_read_image_ppm(FILE *f) {
266   struct pam inpam;
267   unsigned char rgb_buf[3];
268   CanonImage *im;
269
270   pnm_readpaminit(f, &inpam, sizeof(inpam));
271   if (!(inpam.maxval == 255 &&
272         inpam.bytes_per_sample == 1 &&
273         inpam.format == RPPM_FORMAT))
274     fatal("PNM screenshot(s) file must be 8bpp 1 byte per sample RGB");
275
276   CANONICALISE_IMAGE(im, inpam.width, inpam.height, {
277     int r= fread(&rgb_buf,1,3,f);
278     sysassert(!ferror(f));
279     if (r!=3) fatal("PNM screenshot(s) file ends unexpectedly");
280
281     rgb=
282         ((unsigned long)rgb_buf[0]<<16) |
283         ((unsigned long)rgb_buf[1]<<8) |
284                        (rgb_buf[2]);
285   });
286
287   sysassert(!ferror(screenshot_file));
288
289   if (!(npages < MAX_PAGES))
290     fatal("Too many images in screenshots file; max is %d.\n", MAX_PAGES);
291
292   page_images[npages++]= im;
293 }
294
295 void read_one_screenshot(void) {
296   progress("reading screenshot...");
297   file_read_image_ppm(screenshot_file);
298   progress_log("read screenshot.");
299 }
300
301 void read_screenshots(void) {
302   struct stat stab;
303   
304   sysassert(! fstat(fileno(screenshot_file), &stab) );
305   
306   for (;;) {
307     if (S_ISREG(stab.st_mode)) {
308       long pos= ftell(screenshot_file);
309       if (pos == stab.st_size) break;
310     } else {
311       int c= fgetc(screenshot_file);
312       if (c==EOF) break;
313       ungetc(c, screenshot_file);
314     }
315     progress("reading screenshot %d...",npages);
316     file_read_image_ppm(screenshot_file);
317   }
318   sysassert(!ferror(screenshot_file));
319   progress_log("read %d screenshots.",npages);
320 }
321
322 static void find_commodity(int offset, Rect *rr) {
323   /* rr->tl.x==-1 if offset out of range */
324   rr->tl.y= commbasey - offset*comminty;
325   rr->br.y= rr->tl.y + comminty-2;
326   if (rr->tl.y < mainr.tl.y || rr->br.y > mainr.br.y) { rr->tl.x=-1; return; }
327   
328   rr->tl.x= mainr.tl.x;
329   rr->br.x= mainr.br.x;
330
331   if (rr->tl.y > mainr.tl.y)
332     REQUIRE_RECTANGLE(rr->tl.x,rr->tl.y-1, rr->br.x,rr->tl.y-1, "+");
333   if (rr->br.y < mainr.tl.y)
334     REQUIRE_RECTANGLE(rr->tl.x,rr->br.y+1, rr->br.x,rr->br.y+1, "+");
335 }
336
337 static void find_table_entry(Rect commod, int colno, Rect *cellr) {
338   cellr->tl.y= commod.tl.y;
339   cellr->br.y= commod.br.y;
340   cellr->tl.x= !colno ? commod.tl.x : colrightx[colno-1]+2;
341   cellr->br.x=                        colrightx[colno];
342   debug_rect("cell", colno, *cellr);
343   require_rectangle_r(*cellr, " o", __LINE__);
344 }
345
346 static void ocr_rectangle(Rect r, const OcrCellType ct, FILE *tsv_output) {
347   OcrResultGlyph *results, *res;
348
349   int w= r.br.x - r.tl.x + 1;
350   Pixcol cols[w+1];
351   int x,y;
352   for (x=0; x<w; x++) {
353     Pixcol cx, rv;
354     for (y=0, cx=0, rv=1; y<text_h; y++, rv<<=1) {
355       Point here= { x+r.tl.x, y+r.tl.y };
356       int pixel= get_p(here);
357       switch (pixel) {
358       case ' ':           break;
359       case 'o': cx |= rv; break;
360       default:
361         MUST(!"wrong pixel",
362              MC(pixel);MP(here);MSB(ocr_celltype_name(ct));MR(r); );
363       }
364     }
365     cols[x]= cx;
366   }
367   cols[w]= 0;
368
369   results= ocr(rd,ct,w,cols);
370   for (res=results; res->s; res++)
371     fputs(res->s,tsv_output);
372 }
373
374 void analyse(FILE *tsv_output) {
375   Rect thisr, entryr;
376   int page, tryrect, colno;
377
378   for (page=0; page<npages; page++) {
379     find_structure(page_images[page]);
380
381     if (!rd)
382       rd= ocr_init(text_h);
383
384     for (tryrect= +cim->h; tryrect >= -cim->h; tryrect--) {
385       find_commodity(tryrect, &thisr);
386       if (thisr.tl.x < 0)
387         continue;
388       debug_rect("commod",tryrect, thisr);
389
390       const char *tab= "";
391       for (colno=0; colno<columns; colno++) {
392         find_table_entry(thisr,colno,&entryr);
393         fputs(tab, tsv_output);
394         ocr_rectangle(entryr,
395                       colno<TEXT_COLUMNS
396                       ? &ocr_celltype_text
397                       : &ocr_celltype_number,
398                       tsv_output);
399         tab= "\t";
400       }
401       fputs("\n", tsv_output);
402       sysassert(!ferror(tsv_output));
403       sysassert(!fflush(tsv_output));
404     }
405   }
406 }