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