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