chiark / gitweb /
0fbfb40e6eb076b5dd7081635362e1dabc1fead7
[ypp-sc-tools.web-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 DEBUG_DEFINE_DEBUGF(struct)
36
37 #define START_MAIN {200,100}
38 #define MIN_COLUMNS         6
39 #define INTERESTING_COLUMNS 7
40 #define TEXT_COLUMNS        2
41 #define MAX_COLUMNS         7
42
43 static Rect mainr = { START_MAIN,START_MAIN };
44 static int commbasey, comminty;
45 static int colrightx[INTERESTING_COLUMNS];
46 static int text_h=-1, columns=-1;
47 static OcrReader *rd;
48
49 const CanonColourInfo canoncolourinfos[]= {
50   { 0x475A5E, '*' }, /* edge */
51   { 0x2C5F7A, '*' }, /* edge just under box heading shadow */
52   { 0xC5C7Ae, '*' }, /* blank area of partial commodities list */
53   { 0x7D9094, '+' }, /* interbox */
54
55   { 0xBDC5BF, ' ' }, /* background - pale  Sugar cane, etc. */
56   { 0xADB5AF, ' ' }, /* background - dark                   */
57   { 0xC7E1C3, ' ' }, /* background - pale  Swill, etc.      */
58   { 0xB5CFB1, ' ' }, /* background - dark                   */
59   { 0xD6CEB0, ' ' }, /* background - pale  Madder, etc.     */
60   { 0xC8C0A2, ' ' }, /* background - dark                   */
61   { 0xE0E1D3, ' ' }, /* background - pale  Lorandite, etc.  */
62   { 0xD0D1C3, ' ' }, /* background - dark                   */
63   { 0xE5E6C1, ' ' }, /* background - pale  Cloth            */
64   { 0xD7D8B3, ' ' }, /* background - dark                   */
65   { 0xEDDED9, ' ' }, /* background - pale  Dye              */
66   { 0xDACBC6, ' ' }, /* background - dark                   */
67   { 0xD3DEDF, ' ' }, /* background - pale  Paint            */
68   { 0xC5D0D1, ' ' }, /* background - dark                   */
69   { 0xDCD1CF, ' ' }, /* background - pale  Enamel           */
70   { 0xCEC3C1, ' ' }, /* background - dark                   */
71   { 0xF3F6F5, ' ' }, /* background - pale  fruit            */
72   { 0xE2E7E5, ' ' }, /* background - dark                   */
73
74   { 0x000000, 'o' }, /* foreground */
75   { 0xD4B356, ' ' }, /* background (cursor) */
76   { 0xFFFFFF, 'o' }, /* foreground (cursor) */
77
78   { 0x5B93BF, '_' }, /* selector dropdown background */
79   { 0xD7C94F, 'X' }, /* selector dropdown foreground */
80   { 0,0 }
81 };
82
83
84 static void mustfail1(const char *file, int line, const char *what) {
85   fprintf(stderr,
86           "\n\n"
87           "Unable to figure out contents of YPP client display.\n"
88           " Check that your client is logged in has the correct display.\n"
89           " If that isn't the problem, please report this as a fault.\n\n"
90           "Technical details:"
91           " %s:%d: requirement failed: %s\n",
92           file, line, what);
93 }
94 static void mustfail2(void) NORET;
95 static void mustfail2(void) {
96   fprintf(stderr, "\n\nGiving up.\n");
97   exit(8);
98 }
99
100 #define MUST(x, ifnot) do{                      \
101     if (!(x)) {                                 \
102       mustfail1(__FILE__,__LINE__,#x);          \
103       ifnot;                                    \
104       mustfail2();                              \
105     }                                           \
106   }while(0)
107
108 #define MP(v) fprintf(stderr," %s=%d,%d",#v,(v).x,(v).y)
109 #define MI(v) fprintf(stderr," %s=%d",   #v,(v))
110 #define MC(v) fprintf(stderr," %s='%c'", #v,(v))
111 #define MS(v) fprintf(stderr," %s=\"%s\"", #v,(v))
112 #define MSB(v) fprintf(stderr," %s", (v))
113 #define MR(v) fprintf(stderr," %s=%d,%d..%d,%d",\
114                       #v,(v).tl.x,(v).tl.y,(v).br.x,(v).br.y)
115
116
117 #define REQUIRE_RECTANGLE(tlx,tly,brx,bry,ok) \
118  require_rectangle(tlx, tly, brx, bry, ok, __LINE__);
119
120 static void require_rectangle(int tlx, int tly, int brx, int bry,
121                               const char *ok, int lineno) {
122   Point p;
123   for (p.x=tlx; p.x<=brx; p.x++)
124     for (p.y=tly; p.y<=bry; p.y++) {
125       int c= get_p(p);
126       MUST( strchr(ok,c), ({
127              Rect rm={{tlx,tly},{brx,bry}};
128              MI(lineno),MR(rm);MP(p);MS(ok);
129       }));
130     }
131 }
132 static void require_rectangle_r(Rect rr, const char *ok, int lineno) {
133   require_rectangle(rr.tl.x,rr.tl.y, rr.br.x,rr.br.y, ok, lineno);
134 }
135
136 static void debug_rect(const char *what, int whati, Rect rr) {
137   if (!DEBUGP(rect)) return;
138   int y,w;
139   fprintf(debug, "%s %d: %d,%d..%d,%d:\n", what, whati,
140           rr.tl.x,rr.tl.y, rr.br.x,rr.br.y);
141   w= rr.br.x - rr.tl.x + 1;
142   for (y=rr.tl.y; y<=rr.br.y; y++) {
143     fprintf(debug, "%4d%*s|", y, rr.tl.x,"");
144     fwrite(cim->d + y*cim->w + rr.tl.x, 1, w, debug);
145     fputc('|',debug);
146     fputc('\n',debug);
147   }
148   debug_flush();
149 }
150
151 #define WALK_UNTIL(point,coord,increm,last,edge)                        \
152   for (;;) {                                                            \
153     if ((point).coord == (last)+(increm)) break;                        \
154     if (get_p((point)) == (edge)) { (point).coord -= (increm); break; } \
155     (point).coord += (increm);                                          \
156   }
157
158 #define WALK_UNTIL_MUST(point,coord,increm,last,edge)   \
159   do {                                                  \
160     WALK_UNTIL(point,coord,increm,last,edge);           \
161     MUST( (point).coord != (last)+(increm),             \
162           MP(point); MI(increm); MI(last); MC(edge);    \
163           );                                            \
164   }while(0)
165
166 void find_structure(CanonImage *im, int *max_relevant_y_r) {
167   cim= im;
168   
169   Rect whole = { {0,0}, {cim->w-1,cim->h-1} };
170
171   WALK_UNTIL_MUST(mainr.tl, x,-1, whole.tl.x, '*');
172   WALK_UNTIL_MUST(mainr.tl, y,-1, whole.tl.y, '*');
173   WALK_UNTIL_MUST(mainr.br, x,+1, whole.br.x, '*');
174   WALK_UNTIL_MUST(mainr.br, y,+1, whole.br.y, '*');
175
176   REQUIRE_RECTANGLE(mainr.tl.x-1, mainr.tl.y, mainr.tl.x-1, mainr.br.y, "*");
177   REQUIRE_RECTANGLE(mainr.br.x+1, mainr.tl.y, mainr.br.x+1, mainr.br.y, "*");
178   REQUIRE_RECTANGLE(mainr.tl.x, mainr.tl.y-1, mainr.br.x, mainr.tl.y-1, "*");
179   REQUIRE_RECTANGLE(mainr.tl.x, mainr.br.y+1, mainr.br.x, mainr.br.y+1, "*");
180
181 #define CHECK_STRIP_BORDER(tlbr,xy,increm)              \
182   do {                                                  \
183     Point csb_p;                                        \
184     Rect csb_r;                                         \
185     csb_p= mainr.tl;                                    \
186     csb_p.xy= mainr.tlbr.xy;                            \
187     if (get_p(csb_p)=='+') {                            \
188       csb_r= mainr;                                     \
189       csb_r.tl.xy= csb_p.xy;                            \
190       csb_r.br.xy= csb_p.xy;                            \
191       require_rectangle_r(csb_r, "+", __LINE__);        \
192       mainr.tlbr.xy += increm;                          \
193     }                                                   \
194   } while(0)
195
196   debug_rect("mainr",0, mainr);
197
198   CHECK_STRIP_BORDER(tl,x,+1);
199   CHECK_STRIP_BORDER(tl,y,+1);
200   CHECK_STRIP_BORDER(br,x,-1);
201   CHECK_STRIP_BORDER(br,y,-1);
202
203   debug_rect("mainr",1, mainr);
204
205   Point up = START_MAIN;
206   WALK_UNTIL_MUST(up, y,-1, mainr.tl.y, '+');
207
208   Point down = START_MAIN;
209   down.y++;
210   WALK_UNTIL_MUST(down, y,+1, mainr.br.y, '+');
211
212   if (DEBUGP(rect)) {
213     int xscaleunit, y,x;
214     for (y=0, xscaleunit=1; y<4; y++, xscaleunit*=10) {
215       fprintf(debug,"     ");
216       for (x=0; x<=cim->w; x++) {
217         if (x % xscaleunit) fputc(' ',debug);
218         else fprintf(debug,"%d",(x / xscaleunit)%10);
219       }
220       fputc('\n',debug);
221     }
222   }
223
224   commbasey= up.y;
225   comminty= down.y - up.y + 2;
226
227   Point across= { mainr.tl.x, commbasey };
228   int colno=0;
229   for (;;) {
230     MUST( get_p(across) != '+', MI(colno);MP(across);MR(mainr);MI(commbasey) );
231     WALK_UNTIL(across, x,+1, mainr.br.x, '+');
232     MUST( colno < MAX_COLUMNS, MP(across);MR(mainr);MI(commbasey); );
233     int colrx= across.x;
234     if (colrx > mainr.br.x) colrx= mainr.br.x;
235     if (colno < INTERESTING_COLUMNS)
236       colrightx[colno]= colrx;
237       
238     colno++;
239     
240     if (across.x >= mainr.br.x-1)
241       break;
242
243     across.x++;
244     REQUIRE_RECTANGLE(across.x,mainr.tl.y, across.x,mainr.br.y, "+");
245     across.x++;
246   }
247   MUST( colno >= MIN_COLUMNS, MI(colno);MR(mainr);MP(across); );
248
249 #define SET_ONCE(var,val) do{                                           \
250     int v= (val);                                                       \
251     if ((var)==-1) (var)= v;                                            \
252     else MUST( (var) == v, MSB(#var);MI((var));MI(v);MR(mainr); );      \
253   }while(0)
254
255   SET_ONCE(columns, colno);
256   SET_ONCE(text_h, comminty - 1);
257   if (max_relevant_y_r)
258     SET_ONCE(*max_relevant_y_r, mainr.br.y + 10);
259 }                   
260
261 void check_correct_commodities(void) {
262   Rect search= { { 50,39 }, { 130,59 } };
263
264 #define SEARCH_UPDOWN(this,increm)                              \
265   for (;;) {                                                    \
266     MUST( search.tl.y != search.br.y, MR(search);MSB(#this); ); \
267     int x, got=0;                                               \
268     for (x=search.tl.x; x<=search.br.x; x++)                    \
269       got += (get(x,this.y) == '_');                            \
270     if (got > 10)                                               \
271       break;                                                    \
272     this.y += increm;                                           \
273   }
274     
275   SEARCH_UPDOWN(search.tl, +1);
276   SEARCH_UPDOWN(search.br, -1);
277
278   debug_rect("commodselr",1, search);
279
280   static const char *all[]= {
281     "   ___________________________________   ",
282     "  ________X____X__X____________________  ",
283     " ________ X___ X_ X_____XXXXXXXXXXX_____ ",
284     "_________X_X__ X_ X______XXXXXXXXX_______",
285     "________ X X__ X_ X_______XXXXXXX________",
286     "________X_ _X_ X_ X________XXXXX_________",
287     "_______ X__ X_ X_ X_________XXX__________",
288     "_______XXXXXXX X_ X__________X___________",
289     " _____ X     X X_ X______________________",
290     "  ____X_____ _XX_ X______________________",
291     "   __ _______  __ ______________________ ",
292   };
293
294   static int allh= sizeof(all)/sizeof(all[0]);
295   const int allw= strlen(all[0]);
296
297   int alloffy, alloffx;
298   for (alloffy=0; alloffy < search.br.y; alloffy++) {
299     if (alloffy+allh-1 < search.tl.y) continue;
300     for (alloffx=search.tl.x; alloffx+allw-1 <= search.br.x; alloffx++) {
301       int good=0, bad=0;
302       int x,y;
303       for (x=0; x<allw; x++)
304         for (y=0; y<allh; y++) {
305           int want= all[y][x];
306           if (want==' ') continue;
307           if (get(alloffx+x, alloffy+y) == want)
308             good++;
309           else
310             bad++;
311         }
312       debugf("CHECKCOMMOD alloff=%d,%d good=%d bad=%d\n",
313              alloffx,alloffy, good,bad);
314       if (good > 20*bad)
315         goto all_found;
316     }
317   }
318   fatal("Commodities selector not set to `All'.");
319
320  all_found:;
321 }
322
323 CanonImage *alloc_canon_image(int w, int h) {
324   CanonImage *im= mmalloc(sizeof(CanonImage) + w*h);
325   im->w= w;
326   im->h= h;
327   memset(im->d,'?',w*h);
328   return im;
329 }
330
331 static void file_read_image_ppm(FILE *f) {
332   struct pam inpam;
333   unsigned char rgb_buf[3];
334   CanonImage *im;
335
336   pnm_readpaminit(f, &inpam, sizeof(inpam));
337   if (!(inpam.maxval == 255 &&
338         inpam.bytes_per_sample == 1 &&
339         inpam.format == RPPM_FORMAT))
340     fatal("PNM screenshot(s) file must be 8bpp 1 byte per sample RGB");
341
342   CANONICALISE_IMAGE(im, inpam.width, inpam.height, {
343     int r= fread(&rgb_buf,1,3,f);
344     sysassert(!ferror(f));
345     if (r!=3) fatal("PNM screenshot(s) file ends unexpectedly");
346
347     rgb=
348         ((unsigned long)rgb_buf[0]<<16) |
349         ((unsigned long)rgb_buf[1]<<8) |
350                        (rgb_buf[2]);
351   });
352
353   sysassert(!ferror(screenshot_file));
354
355   if (!(npages < MAX_PAGES))
356     fatal("Too many images in screenshots file; max is %d.\n", MAX_PAGES);
357
358   page_images[npages++]= im;
359 }
360
361 void read_one_screenshot(void) {
362   progress("reading screenshot...");
363   file_read_image_ppm(screenshot_file);
364   progress_log("read screenshot.");
365 }
366
367 void read_screenshots(void) {
368   struct stat stab;
369   
370   sysassert(! fstat(fileno(screenshot_file), &stab) );
371   
372   for (;;) {
373     if (S_ISREG(stab.st_mode)) {
374       long pos= ftell(screenshot_file);
375       if (pos == stab.st_size) break;
376     } else {
377       int c= fgetc(screenshot_file);
378       if (c==EOF) break;
379       ungetc(c, screenshot_file);
380     }
381     progress("reading screenshot %d...",npages);
382     file_read_image_ppm(screenshot_file);
383   }
384   sysassert(!ferror(screenshot_file));
385   progress_log("read %d screenshots.",npages);
386 }
387
388 static void find_commodity(int offset, Rect *rr) {
389   /* rr->tl.x==-1 if offset out of range */
390   rr->tl.y= commbasey - offset*comminty;
391   rr->br.y= rr->tl.y + comminty-2;
392   if (rr->tl.y < mainr.tl.y || rr->br.y > mainr.br.y) { rr->tl.x=-1; return; }
393   
394   rr->tl.x= mainr.tl.x;
395   rr->br.x= mainr.br.x;
396
397   if (rr->tl.y > mainr.tl.y)
398     REQUIRE_RECTANGLE(rr->tl.x,rr->tl.y-1, rr->br.x,rr->tl.y-1, "+");
399   if (rr->br.y < mainr.tl.y)
400     REQUIRE_RECTANGLE(rr->tl.x,rr->br.y+1, rr->br.x,rr->br.y+1, "+");
401 }
402
403 static void find_table_entry(Rect commod, int colno, Rect *cellr) {
404   cellr->tl.y= commod.tl.y;
405   cellr->br.y= commod.br.y;
406   cellr->tl.x= !colno ? commod.tl.x : colrightx[colno-1]+2;
407   cellr->br.x=                        colrightx[colno];
408   debug_rect("cell", colno, *cellr);
409   require_rectangle_r(*cellr, " o", __LINE__);
410 }
411
412 static void ocr_rectangle(Rect r, const OcrCellType ct, FILE *tsv_output) {
413   OcrResultGlyph *results, *res;
414
415   int w= r.br.x - r.tl.x + 1;
416   Pixcol cols[w+1];
417   int x,y;
418   for (x=0; x<w; x++) {
419     Pixcol cx, rv;
420     for (y=0, cx=0, rv=1; y<text_h; y++, rv<<=1) {
421       Point here= { x+r.tl.x, y+r.tl.y };
422       int pixel= get_p(here);
423       switch (pixel) {
424       case ' ':           break;
425       case 'o': cx |= rv; break;
426       default:
427         MUST(!"wrong pixel",
428              MC(pixel);MP(here);MSB(ocr_celltype_name(ct));MR(r); );
429       }
430     }
431     cols[x]= cx;
432   }
433   cols[w]= 0;
434
435   results= ocr(rd,ct,w,cols);
436   for (res=results; res->s; res++)
437     fputs(res->s,tsv_output);
438 }
439
440 void analyse(FILE *tsv_output) {
441   Rect thisr, entryr;
442   int page, tryrect, colno;
443
444   for (page=0; page<npages; page++) {
445     find_structure(page_images[page], 0);
446
447     if (!page)
448       check_correct_commodities();
449
450     if (!rd)
451       rd= ocr_init(text_h);
452
453     for (tryrect= +cim->h; tryrect >= -cim->h; tryrect--) {
454       find_commodity(tryrect, &thisr);
455       if (thisr.tl.x < 0)
456         continue;
457       debug_rect("commod",tryrect, thisr);
458
459       const char *tab= "";
460       for (colno=0; colno<columns; colno++) {
461         find_table_entry(thisr,colno,&entryr);
462         fputs(tab, tsv_output);
463         ocr_rectangle(entryr,
464                       colno<TEXT_COLUMNS
465                       ? &ocr_celltype_text
466                       : &ocr_celltype_number,
467                       tsv_output);
468         tab= "\t";
469       }
470       fputs("\n", tsv_output);
471       sysassert(!ferror(tsv_output));
472       sysassert(!fflush(tsv_output));
473     }
474   }
475 }