6429d1bfaf0bfae457fb36ccc9ee35de46c2a545
[gnushogi.git] / gnushogi / gnushogi.h
1 /*
2  * FILE: gnushogi.h
3  *
4  *     Main header file for GNU Shogi.
5  *
6  * ----------------------------------------------------------------------
7  * Copyright (c) 1993, 1994, 1995 Matthias Mutz
8  * Copyright (c) 1999 Michael Vanier and the Free Software Foundation
9  * Copyright (c) 2008, 2013, 2014 Yann Dirson and the Free Software Foundation
10  *
11  * GNU SHOGI is based on GNU CHESS
12  *
13  * Copyright (c) 1988, 1989, 1990 John Stanback
14  * Copyright (c) 1992 Free Software Foundation
15  *
16  * This file is part of GNU SHOGI.
17  *
18  * GNU Shogi is free software; you can redistribute it and/or modify it
19  * under the terms of the GNU General Public License as published by the
20  * Free Software Foundation; either version 3 of the License,
21  * or (at your option) any later version.
22  *
23  * GNU Shogi is distributed in the hope that it will be useful, but WITHOUT
24  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
25  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
26  * for more details.
27  *
28  * You should have received a copy of the GNU General Public License along
29  * with GNU Shogi; see the file COPYING. If not, see
30  * <http://www.gnu.org/licenses/>.
31  * ----------------------------------------------------------------------
32  *
33  */
34
35 /* Hack for anal-retentive ANSI-compliance if desired: */
36 #define inline
37
38 /* FIXME: this file needs to be reorganized in some rational manner. */
39
40 #ifndef _GNUSHOGI_H_
41 #define _GNUSHOGI_H_
42
43 #include "config.h"        /* Portability #defines. */
44 #include "debug.h"
45 #include "opts.h"          /* Various option-setting #defines.  */
46
47 #include <stdarg.h>
48
49 /*
50  * Display options.
51  */
52
53 typedef enum {
54   DISPLAY_RAW,
55 #ifdef HAVE_LIBCURSES
56   DISPLAY_CURSES,
57 #endif
58   DISPLAY_X
59 } display_t;
60 extern display_t display_type;
61
62 #define XSHOGI     (display_type == DISPLAY_X)
63
64
65 /* Miscellaneous globals. */
66
67 extern short hard_time_limit; /* If you exceed time limit, you lose.   */
68 extern short nolist;          /* Don't list game after exit.           */
69
70
71 /*
72  * Options for various compilers/OSs.
73  */
74
75 /*
76  * type small_short must cover -128 .. 127.  In case of trouble,
77  * try commenting out "signed".  If this doesn't help, use short.
78  */
79
80 #define small_short  signed char
81 #define small_ushort unsigned char
82
83
84 typedef small_ushort   UBYTE;
85 typedef short          SHORT;
86 typedef unsigned short USHORT;
87 typedef int            INT;
88 typedef unsigned int   UINT;
89 typedef long           LONG;
90 typedef unsigned long  ULONG;
91
92
93 #if !defined(HAVE_MEMCPY) && !defined(HAVE_BCOPY)
94 #  define array_copy(src, dst, len) \
95    { \
96        long i; \
97        char  *psrc = (char  *)src, *pdst = (char  *)dst; \
98        for (i = len; i; pdst[--i] = psrc[i]); \
99    }
100 #  define array_zero(dst, len) \
101   { \
102       long i; \
103       char  *pdst = (char  *)dst; \
104       for (i = len; i; pdst[--i] = 0); \
105   }
106 #elif !defined(HAVE_MEMCPY)   /* BSD and derivatives */
107 #  define array_copy(src, dst, len) bcopy(src, dst, len)
108 #  define array_zero(dst, len)      bzero(dst, len)
109 #else /* System V and derivatives */
110 #  define array_copy(src, dst, len) memcpy(dst, src, len)
111 #  define array_zero(dst, len)      memset(dst, 0, len)
112 #endif
113
114
115 #ifndef __GNUC__
116 #  define inline
117 #endif
118
119
120 /*
121  * Standard header files.
122  */
123
124 #include <stdio.h>
125 #include <ctype.h>
126 #include <stdlib.h>
127 #include <assert.h>
128 #include <string.h>
129
130 #include <sys/param.h>
131 #include <sys/types.h>
132 #ifdef WIN32
133 #  include <windows.h>
134 #else
135    typedef small_short    BYTE;
136 #  include <sys/times.h>
137 #  include <sys/ioctl.h>
138 #endif
139
140 #if TIME_WITH_SYS_TIME
141 #  include <sys/time.h>
142 #  include <time.h>
143 #else
144 #  if HAVE_SYS_TIME_H
145 #    include <sys/time.h>
146 #  else
147 #    include <time.h>
148 #  endif
149 #endif
150
151 #define RWA_ACC "r+"
152 #define WA_ACC "w+"
153 #ifdef BINBOOK
154 extern char *binbookfile;
155 #endif
156
157 extern char *bookfile;
158 extern short ahead;
159 extern char  *xwin;
160 extern char  *Lang;
161 extern void movealgbr(short m, char *s);
162
163
164 #define SEEK_SET 0
165 #define SEEK_END 2
166
167 #ifdef MINISHOGI
168 #define NO_PIECES       11
169 #define MAX_CAPTURED    19
170 #define NO_PTYPE_PIECES 11
171 #define NO_COLS          5
172 #define NO_ROWS          5
173 #define NO_CAMP_ROWS     1
174 #else
175 #define NO_PIECES       15
176 #define MAX_CAPTURED    19
177 #define NO_PTYPE_PIECES 15
178 #define NO_COLS          9
179 #define NO_ROWS          9
180 #define NO_CAMP_ROWS     3
181 #endif
182 #define NO_SQUARES      (NO_COLS*NO_ROWS)
183
184 #define ROW_NAME(n) ('a' + NO_ROWS - 1 - n)
185 #define COL_NAME(n) ('1' + NO_COLS - 1 - n)
186
187 #if defined HASHFILE || defined CACHE
188 #  define PTBLBDSIZE (NO_SQUARES + NO_PIECES)
189 #endif
190
191 #include "eval.h"
192
193 #define SCORE_LIMIT 12000
194
195 /* masks into upper 16 bits of attacks array */
196 /* observe order of relative piece values */
197 #define CNT_MASK 0x000000FF
198 #define ctlP  0x00200000
199 #define ctlPp 0x00100000
200 #define ctlL  0x00080000
201 #define ctlN  0x00040000
202 #define ctlLp 0x00020000
203 #define ctlNp 0x00010000
204 #define ctlS  0x00008000
205 #define ctlSp 0x00004000
206 #define ctlG  0x00002000
207 #define ctlB  0x00001000
208 #define ctlBp 0x00000800
209 #define ctlR  0x00000400
210 #define ctlRp 0x00000200
211 #define ctlK  0x00000100
212
213 /* attack functions */
214 #define Pattack(c, u)   (attack[c][u] > ctlP)
215 #define Anyattack(c, u) (attack[c][u] != 0)
216
217 /* hashtable flags */
218 #define truescore   0x0001
219 #define lowerbound  0x0002
220 #define upperbound  0x0004
221 #define kingcastle  0x0008
222 #define queencastle 0x0010
223 #define evalflag    0x0020
224
225 /* King positions */
226 #define BlackKing PieceList[black][0]
227 #define WhiteKing PieceList[white][0]
228 #define OwnKing   PieceList[c1][0]
229 #define EnemyKing PieceList[c2][0]
230
231
232 /* board properties */
233 #define InBlackCamp(sq) ((sq) < (NO_COLS * NO_CAMP_ROWS))
234 #define InWhiteCamp(sq) ((sq) >= (NO_COLS * (NO_ROWS - NO_CAMP_ROWS)))
235 #define InPromotionZone(side, sq) \
236 (((side) == black) ? InWhiteCamp(sq) : InBlackCamp(sq))
237
238 /* constants */
239 /* FIXME ? */
240 #define OPENING_HINT 0x141d /* P7g-7f (20->29) */
241
242 /* truth values */
243 #ifndef false
244 #define false 0
245 #endif
246
247 #ifndef true
248 #define true  1
249 #endif
250
251 /* colors */
252 #define black   0
253 #define white   1
254 #define neutral 2
255
256 /* piece code defines */
257 enum {
258     no_piece = 0,
259     pawn,
260 #ifndef MINISHOGI
261     lance,
262     knight,
263 #endif
264     /* start of pieces that can be dropped at any square */
265     silver,
266     gold,
267     bishop,
268     rook,
269     ppawn,
270 #ifndef MINISHOGI
271     plance,
272     pknight,
273 #endif
274     psilver,
275     pbishop,
276     prook,
277     king
278 };
279
280 /* move types */
281 enum {
282     ptype_no_piece = 0,
283     ptype_pawn = 0,
284 #ifndef MINISHOGI
285     ptype_lance,
286     ptype_knight,
287 #endif
288     ptype_silver,
289     ptype_gold,
290     ptype_bishop,
291     ptype_rook,
292     ptype_pbishop,
293     ptype_prook,
294     ptype_king,
295     ptype_wpawn,
296 #ifndef MINISHOGI
297     ptype_wlance,
298     ptype_wknight,
299 #endif
300     ptype_wsilver,
301     ptype_wgold
302 };
303
304 /* node flags */
305 #define pmask        0x000f /*    15 */
306 #define promote      0x0010 /*    16 */
307 #define dropmask     0x0020 /*    32 */
308 #define exact        0x0040 /*    64 */
309 #define tesuji       0x0080 /*   128 */
310 #define check        0x0100 /*   256 */
311 #define capture      0x0200 /*   512 */
312 #define draw         0x0400 /*  1024 */
313 #define stupid       0x0800 /*  2048 */
314 #define questionable 0x1000 /*  4096 */
315 #define kingattack   0x2000 /*  8192 */
316 #define book         0x4000 /* 16384 */
317
318 /* move quality flags */
319 #define goodmove     tesuji
320 #define badmove      stupid
321 #ifdef EASY_OPENINGS
322 #define difficult    questionable
323 #endif
324
325 /* move symbols */
326 #ifndef MINISHOGI
327 #define pxx (" PLNSGBRPLNSBRK ")
328 #define qxx (" plnsgbrplnsbrk ")
329 #define rxx ("ihgfedcba")
330 #define cxx ("987654321")
331 #else
332 #define pxx (" PSGBRPSBRK ")
333 #define qxx (" psgbrpsbrk ")
334 #define rxx ("edcba")
335 #define cxx ("54321")
336 #endif
337
338 /***************** Table limits ********************************************/
339
340 /*
341  * ttblsz must be a power of 2. Setting ttblsz 0 removes the transposition
342  * tables.
343  */
344
345 #if defined NOTTABLE
346 #  define vttblsz 0
347 #elif defined SMALL_MEMORY
348 #  if defined SAVE_SSCORE
349 #    define vttblsz (1 << 12)
350 #  else
351 #    if defined EXTRA_2MB
352 #      define vttblsz (1 << 12)
353 #    else
354 #      define vttblsz (1 << 10)
355 #    endif
356 #  endif
357 #else
358 #  define vttblsz (100001)
359 #endif
360
361 #if defined SMALL_MEMORY
362 #  define MINTTABLE (0)
363 #else
364 #  define MINTTABLE (8000)    /* min ttable size -1 */
365 #endif
366
367 #define ttblsz vttblsz
368
369 #if defined SMALL_MEMORY
370 #  if !defined SAVE_SSCORE
371 #    define TREE 1500             /* max number of tree entries */
372 #  else
373 #    define TREE 2500             /* max number of tree entries */
374 #  endif
375 #else
376 #  define TREE 4000               /* max number of tree entries */
377 #endif
378
379 #define MAXDEPTH  40            /* max depth a search can be carried */
380 #define MINDEPTH   2            /* min search depth =1 (no hint), >1 hint */
381 #define MAXMOVES 300            /* max number of half moves in a game */
382 #define CPSIZE   241            /* size of lang file max */
383
384 #if defined SMALL_MEMORY
385 #  if defined SAVE_SSCORE
386 #    define ETABLE (1 << 10)      /* static eval cache */
387 #  else
388 #    if defined EXTRA_2MB
389 #      define ETABLE (1 << 10)    /* static eval cache */
390 #    else
391 #      define ETABLE (1 << 8)     /* static eval cache */
392 #    endif
393 #  endif
394 #else
395 #  define ETABLE (10001)          /* static eval cache */
396 #endif
397
398 /***************** tuning paramaters *******************/
399
400 #if defined VERY_SLOW_CPU
401 #  define MINRESPONSETIME 300
402 #elif defined SLOW_CPU
403 #  define MINRESPONSETIME 200
404 #else
405 #  define MINRESPONSETIME 100     /* 1 s */
406 #endif
407
408 #define MINGAMEIN  4
409 #define MINMOVES  15
410 #define CHKDEPTH   1   /* always look forward CHKDEPTH
411                         * half-moves if in check */
412
413 #if defined SLOW_CPU || defined VERY_SLOW_CPU
414 #  define DEPTHBEYOND 7     /* Max to go beyond Sdepth */
415 #else
416 #  define DEPTHBEYOND 11    /* Max to go beyond Sdepth */
417 #endif
418
419 #define HASHDEPTH      4  /* depth above which to use HashFile */
420 #define HASHMOVELIMIT 40  /* Use HashFile only for this many moves */
421 #define PTVALUE        0  /* material value below which pawn threats at
422                            * 5 & 3 are used */
423 #define ZDEPTH 3          /* depth beyond which to check
424                            * ZDELTA for extra time */
425 #define ZDELTA 10         /* score delta per ply to cause
426                            * extra time to be given */
427 #define BESTDELTA 90
428
429 /* about 1/2 second worth of nodes for your machine */
430 #if defined VERY_SLOW_CPU
431 /* check the time every ZNODES positions */
432 #  define ZNODES (flag.tsume ? 20 : 50)
433 #elif defined SLOW_CPU
434 #  define ZNODES (flag.tsume ? 40 : 100)
435 #else
436 #  define ZNODES (flag.tsume ? 400 : 1000)
437 #endif
438
439 #define MAXTCCOUNTX  10  /* max number of time clicks
440                           * per search to complete ply */
441 #define MAXTCCOUNTR   4  /* max number of time clicks
442                           * per search extensions*/
443 #define SCORESPLIM    8  /* Score space doesn't apply after this stage */
444 #define SDEPTHLIM    (Sdepth + 1)
445 #define HISTORYLIM 4096  /* Max value of history killer */
446
447 #ifdef EXACTHISTORY
448 #  if defined SMALL_MEMORY
449 #    define HISTORY_MASK 0x8000     /* mask to MSB of history index */
450 #    define HISTORY_SIZE 0x10000    /* size of history table */
451 #  else
452 #    define HISTORY_MASK (1 << 15)  /* mask to MSB of history index */
453 #    define HISTORY_SIZE (1 << 16)  /* size of history table */
454 #  endif
455 #else
456 /* smaller history table, but dangerous because of collisions */
457 #  define HISTORY_MASK 0x3fff     /* mask to significant bits
458                                    * of history index */
459 #  if defined SMALL_MEMORY
460 #    define HISTORY_SIZE 0x4000 /* size of history table */
461 #  else
462 #    define HISTORY_SIZE (1 << 14)  /* size of history table */
463 #  endif
464 #endif
465
466 #define sizeof_history (sizeof(unsigned short) * (size_t)HISTORY_SIZE)
467
468 #ifdef EXACTHISTORY
469 /* Map from.to (8bit.8bit) to from.to (0.7bit.8bit) */
470 #  define khmove(mv) (mv & 0x7fff)
471 #  define hmove(mv) ((mv & 0x7fff) ^ 0x5555)
472 #else
473 /* Map from.to (8bit.8bit) to from.to (00.7bit.7bit) */
474 /* Swap bits of ToSquare in case of promotions, hoping that
475    no catastrophic collision occurs. */
476 #  define khmove(mv) (((mv & 0x7f00) >> 1) | \
477            ((mv & 0x0080) ? ((mv & 0x007f) ^ 0x007f) : (mv & 0x007f)))
478 #  define hmove(mv) (khmove(mv) ^ 0x2aaa)
479 #endif
480
481 /* mask color to 15th bit */
482 #ifdef EXACTHISTORY
483 #  define hindex(c, mv) ((c ? HISTORY_MASK : 0) | hmove(mv))
484 #else
485 /* for white, swap bits, hoping that no catastrophic collision occurs. */
486 #  define hindex(c, mv) (c ? ((~hmove(mv)) & HISTORY_MASK) : hmove(mv))
487 #endif
488
489 #define EWNDW  10    /* Eval window to force position scoring at depth
490                       * greater than (Sdepth + 2)        */
491 #define WAWNDW 90    /* alpha window when computer black */
492 #define WBWNDW 90    /* beta window when computer black  */
493 #define BAWNDW 90    /* alpha window when computer white */
494 #define BBWNDW 90    /* beta window when computer white  */
495 #define BXWNDW 90    /* window to force position scoring at lower */
496 #define WXWNDW 90    /* window to force position scoring at lower */
497
498 #define DITHER  5    /* max amount random can alter a pos value */
499 #define LBONUS  1    /* points per stage value of L increases   */
500 #define BBONUS  2    /* points per stage value of B increases   */
501 #define RBONUS  2    /* points per stage value of R increases   */
502
503 #define QUESTIONABLE (valueK)   /* Penalty for questionable moves. */
504
505 #if defined STUPID
506 #  undef STUPID
507 #endif
508
509 #define STUPID (valueR << 1)    /* Penalty for stupid moves. */
510
511 #define KINGPOSLIMIT (-1)      /* King positional scoring limit */
512 #define KINGSAFETY  32
513 #define MAXrehash (7)
514
515 /******* parameters for Opening Book ****************/
516
517 #define BOOKSIZE   8000  /* Number of unique position/move
518                           * combinations allowed */
519 #define BOOKMAXPLY   40           /* Max plys to keep in book database */
520 #define BOOKFAIL (BOOKMAXPLY / 2) /* if no book move found for BOOKFAIL
521                                    * turns stop using book */
522 #define BOOKPOCKET          64
523 #define BOOKRAND          1000  /* used to select an opening move
524                                  * from a list */
525 #define BOOKENDPCT         950  /* 5 % chance a BOOKEND will stop the book */
526 #define DONTUSE         -32760  /* flag move as don't use */
527 #define ILLEGAL_TRAPPED -32761  /* flag move as illegal:
528                                  * no move from this square */
529 #define ILLEGAL_DOUBLED -32762  /* flag move as illegal:
530                                  * two pawns on one column */
531 #define ILLEGAL_MATE    -32763  /* flag move as illegal:
532                                  * pawn drop with mate */
533
534 /*****************************************************/
535
536 struct hashval
537 {
538     unsigned long key, bd;
539 };
540
541 struct hashentry
542 {
543     unsigned long hashbd;
544     unsigned short mv;
545     unsigned char depth; /* unsigned char saves some space */
546     unsigned char flags;
547 #ifdef notdef
548     unsigned short age;
549 #endif
550     short score;
551 #ifdef HASHTEST
552     unsigned char bd[PTBLBDSIZE];
553 #endif /* HASHTEST */
554 };
555
556 #if defined HASHFILE || defined CACHE
557 struct etable
558 {
559     unsigned long ehashbd;
560     short escore[2];
561 #if !defined SAVE_SSCORE
562     short sscore[NO_SQUARES];
563 #endif
564     short score;
565     small_short hung[2];
566 #ifdef CACHETEST
567     unsigned char bd[PTBLBDSIZE];
568 #endif /* CACHETEST */
569 };
570
571 #if defined CACHE
572 extern short use_etable;
573 typedef struct etable etable_field[ETABLE];
574 extern etable_field  *etab[2];
575 #endif
576
577 /*
578  * CHECKME! Is this valid?
579  *
580  * persistent transposition table. By default, the size is (1 << vfilesz).
581  * If you change the size, be sure to run gnushogi -c [vfilesz]
582  * before anything else.
583  */
584
585 #define frehash 6
586
587 #if defined SMALL_MEMORY
588 #  define vfilesz 10
589 #else
590 #  define vfilesz 14
591 #endif
592
593 struct fileentry
594 {
595     unsigned char bd[PTBLBDSIZE];
596     unsigned char f, t, flags, depth, sh, sl;
597 };
598
599 #endif /* HASHFILE */
600
601
602 struct leaf
603 {
604     small_ushort f, t;
605     short score, reply, width;
606     short INCscore;
607     unsigned short flags;
608 };
609
610
611 struct GameRec
612 {
613     unsigned short gmove;    /* this move */
614     short score;             /* score after this move */
615     short depth;             /* search depth this move */
616     long  time;               /* search time this move */
617     short fpiece;            /* moved or dropped piece */
618     short piece;             /* piece captured */
619     short color;             /* color */
620     short flags;             /* move flags capture, promote, castle */
621     short Game50;            /* flag for repetition */
622     long  nodes;              /* nodes searched for this move */
623     unsigned long hashkey, hashbd;   /* board key before this move */
624 };
625
626
627 struct TimeControlRec
628 {
629     short moves[2];
630     long  clock[2];
631 };
632
633
634 struct flags
635 {
636     short mate;              /* the game is over */
637     short post;              /* show principle variation */
638     short quit;              /* quit/exit */
639     short regularstart;      /* did the game start from standard
640                               * initial board ? */
641     short reverse;           /* reverse board display */
642     short bothsides;         /* computer plays both sides */
643     short hash;              /* enable/disable transposition table */
644     short force;             /* enter moves */
645     short easy;              /* disable thinking on opponents time */
646     short beep;              /* enable/disable beep */
647     short timeout;           /* time to make a move */
648     short musttimeout;       /* time to make a move */
649     short back;              /* time to make a move */
650     short rcptr;             /* enable/disable recapture heuristics */
651     short rv;                /* reverse video */
652     short stars;             /* add stars to uxdsp screen */
653     short coords;            /* add coords to visual screen */
654     short shade;
655     short material;          /* draw on lack of material */
656     short illegal;           /* illegal position */
657     short onemove;           /* timing is onemove */
658     short gamein;            /* timing is gamein */
659     short tsume;             /* first consider checks */
660 };
661
662 extern FILE *debugfile;
663
664 #ifndef EVALFILE
665 #define EVALFILE "/tmp/EVAL"
666 #endif
667
668 extern FILE *debug_eval_file;
669 extern short debug_moves;
670
671
672 #ifdef HISTORY
673 extern short use_history;
674 extern unsigned short  *history;
675 #endif
676
677 extern long znodes;
678
679 extern char ColorStr[2][10];
680
681 extern char mvstr[4][6];
682 extern int mycnt1, mycnt2;
683 extern short ahead;
684 extern struct leaf rootnode;
685 extern struct leaf  *Tree;
686 extern struct leaf  *root;
687 extern char savefile[], listfile[];
688 extern short TrPnt[];
689 extern small_short board[], color[];
690 extern const small_short sweep[NO_PIECES];
691 extern small_short PieceList[2][NO_SQUARES], PawnCnt[2][NO_COLS];
692 extern small_short Captured[2][NO_PIECES];
693
694 #ifndef HAVE_MEMSET
695 #  define ClearCaptured() \
696   { \
697       short piece, color; \
698       for (color = black; color <= white; color++) \
699           for (piece = 0; piece < NO_PIECES; piece++) \
700               Captured[color][piece] = 0; \
701   }
702 #else
703 #  define ClearCaptured() \
704   memset((char *)Captured, 0, (unsigned long)sizeof(Captured))
705 #endif /* HAVE_MEMSET */
706
707 extern small_short Mvboard[];
708
709 #if !defined SAVE_SVALUE
710 extern short svalue[NO_SQUARES];
711 #endif
712
713 extern short pscore[2]; /* eval.c */
714 extern int EADD; /* eval.c */
715 extern int EGET; /* eval.c */
716 extern struct flags flag;
717 extern short opponent, computer, INCscore;
718 extern short WAwindow, BAwindow, WBwindow, BBwindow;
719 extern short dither, player;
720 extern short xwndw, contempt;
721 extern long  ResponseTime, ExtraTime, TCleft,
722     MaxResponseTime, et, et0, time0, ft;
723 extern int   TCcount;
724
725 #ifdef INTERRUPT_TEST
726 extern long itime0, it;
727 #endif
728
729 extern long  reminus, replus;
730 extern long  GenCnt, NodeCnt, ETnodes, EvalNodes, HashAdd, HashCnt,
731     HashCol, THashCol, FHashCnt, FHashAdd;
732 extern short HashDepth, HashMoveLimit;
733 extern struct GameRec  *GameList;
734 extern short GameCnt, Game50;
735 extern short Sdepth, MaxSearchDepth;
736 extern int   Book;
737 extern struct TimeControlRec TimeControl;
738 extern int   TCadd;
739 extern short TCflag, TCmoves, TCminutes, TCseconds, OperatorTime;
740 extern int   timecomp[MINGAMEIN], timeopp[MINGAMEIN];
741 extern int   compptr, oppptr;
742 extern short XCmore, XCmoves[], XCminutes[], XCseconds[], XC;
743 extern const short otherside[];
744 extern const small_short Stboard[];
745 extern const small_short Stcolor[];
746 extern unsigned short hint;
747 extern short TOflag;
748 extern short stage, stage2;
749
750 #define in_opening_stage    (!flag.tsume && (stage < 33))
751 #define in_middlegame_stage (!flag.tsume && (stage >= 33) && (stage <= 66))
752 #define in_endgame_stage    (flag.tsume || (stage > 66))
753
754 extern short ahead, hash;
755 extern short balance[2];
756 extern small_short ChkFlag[], CptrFlag[], TesujiFlag[];
757 extern short Pscore[], Tscore[];
758 extern /*unsigned*/ short rehash;  /* -1 is used as a flag --tpm */
759 extern unsigned int ttbllimit;
760 extern unsigned int TTadd;
761 extern unsigned int ttblsize;
762 extern short mtl[], hung[];
763 extern small_short Pindex[];
764 extern small_short PieceCnt[];
765 extern short FROMsquare, TOsquare;
766 extern small_short HasPiece[2][NO_PIECES];
767 extern const short kingP[];
768 extern unsigned short killr0[], killr1[];
769 extern unsigned short killr2[], killr3[];
770 extern unsigned short PrVar[MAXDEPTH];
771 extern unsigned short PV, SwagHt, Swag0, Swag1, Swag2, Swag3, Swag4, sidebit;
772 extern short mtl[2], pmtl[2], hung[2];
773 extern const small_short relative_value[];
774 extern const long control[];
775 extern small_short diagonal(short delta);
776 extern const small_short promoted[NO_PIECES], unpromoted[NO_PIECES];
777 extern const small_short is_promoted[NO_PIECES];
778
779 typedef unsigned char next_array[NO_SQUARES][NO_SQUARES];
780 typedef small_short distdata_array[NO_SQUARES][NO_SQUARES];
781
782 extern const small_short inunmap[NO_SQUARES];
783 #ifndef MINISHOGI
784 extern const small_short nunmap[(NO_COLS + 2)*(NO_ROWS + 4)];
785 #else
786 extern const small_short nunmap[(NO_COLS + 2)*(NO_ROWS + 2)];
787 #endif
788
789 #if defined SAVE_NEXTPOS
790 extern const small_short direc[NO_PTYPE_PIECES][8];
791 extern short first_direction(short ptyp, short *d, short sq);
792 extern short next_direction(short ptyp, short *d, short sq);
793 extern short next_position(short ptyp, short *d, short sq, short u);
794 #else
795 extern short use_nextpos;
796 extern next_array  *nextpos[NO_PTYPE_PIECES];
797 extern next_array  *nextdir[NO_PTYPE_PIECES];
798 #endif
799
800 extern value_array   *value;
801 extern fscore_array  *fscore;
802
803 #ifndef SAVE_DISTDATA
804 extern short use_distdata;
805 extern distdata_array  *distdata;
806 #endif
807
808 #ifndef SAVE_PTYPE_DISTDATA
809 extern short use_ptype_distdata;
810 extern distdata_array  *ptype_distdata[NO_PTYPE_PIECES];
811 #endif
812
813 extern const small_short ptype[2][NO_PIECES];
814
815 extern long filesz, hashmask, hashbase;
816 extern FILE *hashfile;
817 extern unsigned int starttime;
818
819 /* eval.c */
820 typedef small_short Mpiece_array[2][NO_SQUARES];
821 extern Mpiece_array *Mpiece[NO_PIECES];
822 extern short ADVNCM[NO_PIECES];
823
824 #define computed_distance(a, b) \
825     ((abs(column(a) - column(b)) > abs(row(a) - row(b))) \
826     ? abs(column(a) - column(b)) : abs(row(a) - row(b)))
827
828 extern short distance(short a, short b);
829 extern short ptype_distance(short ptyp, short f, short t);
830 extern short piece_distance(short side, short piece, short f, short t);
831
832 #if defined UNKNOWN
833 #  undef UNKNOWN
834 #endif
835
836 #define UNKNOWN      'U'
837 #define STATIC_ROOK  'S'
838 #define RANGING_ROOK 'R'
839
840 extern char GameType[2];
841 void ShowGameType(void);
842
843 extern unsigned short bookmaxply;
844 extern unsigned int bookcount;
845 extern unsigned int booksize;
846 extern unsigned long hashkey, hashbd;
847
848 typedef struct hashval hashcode_array[2][NO_PIECES][NO_SQUARES];
849 typedef struct hashval drop_hashcode_array[2][NO_PIECES][NO_SQUARES];
850
851 extern hashcode_array  *hashcode;
852 extern drop_hashcode_array  *drop_hashcode;
853
854 #ifdef QUIETBACKGROUND
855 extern short background;
856 #endif /* QUIETBACKGROUND */
857
858 #if ttblsz
859 extern short use_ttable;
860 extern struct hashentry  *ttable[2];
861 #endif
862
863 /*
864  * hashbd contains a 32 bit "signature" of the board position. hashkey
865  * contains a 16 bit code used to address the hash table. When a move is
866  * made, XOR'ing the hashcode of moved piece on the from and to squares with
867  * the hashbd and hashkey values keeps things current.
868  */
869
870 #define UpdateHashbd(side, piece, f, t) \
871 { \
872   if ((f) >= 0) \
873     { \
874       hashbd  ^= (*hashcode)[side][piece][f].bd;  \
875       hashkey ^= (*hashcode)[side][piece][f].key; \
876     } \
877  \
878   if ((t) >= 0) \
879     { \
880       hashbd  ^= (*hashcode)[side][piece][t].bd;  \
881       hashkey ^= (*hashcode)[side][piece][t].key; \
882     } \
883 }
884
885 #define UpdateDropHashbd(side, piece, count) \
886 { \
887   hashbd  ^= (*drop_hashcode)[side][piece][count].bd;  \
888   hashkey ^= (*drop_hashcode)[side][piece][count].key; \
889 }
890
891
892 extern short rpthash[2][256];
893 extern char *DRAW;
894
895 extern char* DRAW_REPETITION;
896 extern char *DRAW_MAXMOVES;
897 extern char *DRAW_JUSTDRAW;
898
899 #define row(a)     ((a) / NO_COLS)
900 #define column(a)  ((a) % NO_COLS)
901 #define locn(a, b) (((a) * NO_COLS) + b)
902
903 /* init external functions */
904 extern void InitConst(char *lang); /* init.c */
905 extern int  Initialize_data(void); /* init.c */
906 extern void Free_data(void);       /* init.c */
907 extern int  Lock_data(void);       /* init.c */
908 extern void Unlock_data(void);     /* init.c */
909 extern void Initialize_dist(void); /* init.c */
910 extern void Initialize_eval(void); /* eval.c */
911 extern void NewGame(void);
912 extern void GetOpenings(void);
913 extern int  OpeningBook(unsigned short *hint);
914
915 typedef enum
916 {
917     REMOVE_PIECE = 1, ADD_PIECE
918 } UpdatePieceList_mode;
919
920 extern void
921 UpdatePieceList(short side, short sq, UpdatePieceList_mode iop);
922
923 typedef enum
924 {
925     FOREGROUND_MODE = 1, BACKGROUND_MODE
926 } SelectMove_mode;
927
928 extern void
929 SelectMove(short side, SelectMove_mode iop);
930
931 extern int
932 search(short side,
933        short ply,
934        short depth,
935        short alpha,
936        short beta,
937        unsigned short *bstline,
938        short *rpt);
939
940 #ifdef CACHE
941 void PutInEETable(short side, int score);
942 int  CheckEETable(short side);
943 int  ProbeEETable(short side, short *score);
944 #endif
945
946 #if ttblsz
947 extern int
948 ProbeTTable(short side,
949             short depth,
950             short ply,
951             short *alpha,
952             short *beta,
953             short *score);
954
955 extern int
956 PutInTTable(short side,
957             short score,
958             short depth,
959             short ply,
960             short beta,
961             unsigned short mv);
962
963 extern void ZeroTTable(void);
964 extern void ZeroRPT(void);
965 extern void Initialize_ttable(void);
966 extern unsigned int urand(void);
967
968 #  ifdef HASHFILE
969 extern void gsrand(unsigned int);
970
971 extern int
972 ProbeFTable(short side,
973             short depth,
974             short ply,
975             short *alpha,
976             short *beta,
977             short *score);
978
979 extern void
980 PutInFTable(short side,
981             short score,
982             short depth,
983             short ply,
984             short alpha,
985             short beta,
986             unsigned short f,
987             unsigned short t);
988
989 #  endif /* HASHFILE */
990 #endif /* ttblsz */
991
992 #if !defined SAVE_NEXTPOS
993 extern void Initialize_moves(void);
994 #endif
995
996 extern short generate_move_flags;
997
998 extern void MoveList(short side, short ply,
999                      short in_check, short blockable);
1000 extern void CaptureList(short side, short ply,
1001                         short in_check, short blockable);
1002
1003 /* from attacks.c */
1004 extern int
1005 SqAttacked(short square, short side, short *blockable);
1006
1007 extern void
1008 MakeMove(short side,
1009          struct leaf  *node,
1010          short *tempb,
1011          short *tempc,
1012          short *tempsf,
1013          short *tempst,
1014          short *INCscore);
1015
1016 extern void
1017 UnmakeMove(short side,
1018            struct leaf  *node,
1019            short *tempb,
1020            short *tempc,
1021            short *tempsf,
1022            short *tempst);
1023
1024 extern void
1025 InitializeStats(void);
1026
1027 extern int
1028 evaluate(short side,
1029          short ply,
1030          short alpha,
1031          short beta,
1032          short INCscore,
1033          short *InChk,
1034          short *blockable);
1035
1036 extern short ScorePosition(short side);
1037 extern void  ExaminePosition(short side);
1038 extern short ScorePatternDistance(short side);
1039 extern void  DetermineStage(short side);
1040 extern void  UpdateWeights(short side);
1041 extern int   InitMain(void);
1042 extern void  ExitMain(void);
1043 extern void  Initialize(void);
1044 extern void  InputCommand(char *command);
1045 extern void  ExitShogi(void);
1046 extern void  ClearScreen(void);
1047 extern void  SetTimeControl(void);
1048 extern void  SelectLevel(char *sx);
1049
1050 extern void
1051 UpdateDisplay(short f,
1052               short t,
1053               short flag,
1054               short iscastle);
1055
1056 typedef enum
1057 {
1058     COMPUTE_AND_INIT_MODE = 1, COMPUTE_MODE
1059 #ifdef INTERRUPT_TEST
1060     , INIT_INTERRUPT_MODE, COMPUTE_INTERRUPT_MODE
1061 #endif
1062 } ElapsedTime_mode;
1063
1064 extern void  SetResponseTime(short side);
1065 extern void  CheckForTimeout(int score, int globalscore,
1066                              int Jscore, int zwndw);
1067 extern void  ShowSidetoMove(void);
1068 extern void  ShowResponseTime(void);
1069 extern void  ShowPatternCount(short side, short n);
1070 extern void  SearchStartStuff(short side);
1071 extern void  ShowDepth(char ch);
1072 extern void  TerminateSearch(int);
1073 extern void  ShowResults(short score, unsigned short *bstline, char ch);
1074 extern void  SetupBoard(void);
1075 extern void  algbr(short f, short t, short flag);
1076 extern void  OutputMove(void);
1077 extern void  ShowCurrentMove(short pnt, short f, short t);
1078 extern void  ListGame(void);
1079 extern void  ShowMessage(char *s);
1080 extern void  ClearScreen(void);
1081 extern void  DoDebug(void);
1082 extern void  DoTable(short table[NO_SQUARES]);
1083 extern void  ShowPostnValues(void);
1084 extern void  ChangeXwindow(void);
1085 extern void  SetContempt(void);
1086 extern void  ChangeHashDepth(void);
1087 extern void  ChangeBetaWindow(void);
1088 extern void  GiveHint(void);
1089 extern void  ShowPrompt(void);
1090 extern void  EditBoard(void);
1091 extern void  help(void);
1092 extern void  ChangeSearchDepth(void);
1093 extern void  skip(void);
1094 extern void  skipb(void);
1095 extern void  EnPassant(short xside, short f, short t, short iop);
1096 extern void  ShowNodeCnt(long NodeCnt);
1097 extern void  ShowLine(unsigned short *bstline);
1098 extern int   pick(short p1, short p2);
1099 extern short repetition(void);
1100 extern void  TimeCalc(void);
1101 extern void  ElapsedTime(ElapsedTime_mode iop);
1102
1103 extern short
1104 DropPossible(short piece, short side, short sq); /* genmoves.c */
1105
1106 extern short
1107 IsCheckmate(short side, short in_check,
1108             short blockable); /* genmoves.c */
1109
1110
1111 typedef enum
1112 {
1113     VERIFY_AND_MAKE_MODE, VERIFY_AND_TRY_MODE, UNMAKE_MODE
1114 } VerifyMove_mode;
1115
1116 extern int VerifyMove(char *s, VerifyMove_mode iop, unsigned short *mv);
1117 extern unsigned short TTage;
1118
1119 /* display driver framework */
1120
1121 struct display
1122 {
1123     void (*ChangeAlphaWindow)(void);
1124     void (*ChangeBetaWindow)(void);
1125     void (*ChangeHashDepth)(void);
1126     void (*ChangeSearchDepth)(char *sx);
1127     void (*ChangeXwindow)(void);
1128     void (*ClearScreen)(void);
1129     void (*DoDebug)(void);
1130     void (*DoTable)(short table[NO_SQUARES]);
1131     void (*EditBoard)(void);
1132     void (*ExitShogi)(void);
1133     void (*GiveHint)(void);
1134     void (*Initialize)(void);
1135     void (*ShowNodeCnt)(long NodeCnt);
1136     void (*OutputMove)(void);
1137     void (*PollForInput)(void);
1138     void (*SetContempt)(void);
1139     void (*SearchStartStuff)(short side);
1140     void (*SelectLevel)(char *sx);
1141     void (*ShowCurrentMove)(short pnt, short f, short t);
1142     void (*ShowDepth)(char ch);
1143     void (*ShowGameType)(void);
1144     void (*ShowLine)(unsigned short *bstline);
1145     void (*ShowMessage)(char *s);
1146     void (*AlwaysShowMessage)(const char *format, ...);
1147     void (*Printf)(const char *format, ...);
1148     void (*doRequestInputString)(const char* fmt, char* buffer);
1149     int  (*GetString)(char* sx);
1150     void (*SetupBoard)(void);
1151     void (*ShowPatternCount)(short side, short n);
1152     void (*ShowPostnValue)(short sq);
1153     void (*ShowPostnValues)(void);
1154     void (*ShowPrompt)(void);
1155     void (*ShowResponseTime)(void);
1156     void (*ShowResults)(short score, unsigned short *bstline, char ch);
1157     void (*ShowSidetoMove)(void);
1158     void (*ShowStage)(void);
1159     void (*TerminateSearch)(int sig);
1160     void (*UpdateClocks)(void);
1161     void (*UpdateDisplay)(short f, short t, short redraw, short isspec);
1162     void (*help)(void);
1163 };
1164
1165 extern struct display *dsp;
1166
1167 extern struct display raw_display;
1168 extern struct display curses_display;
1169
1170 #endif /* _GNUSHOGI_H_ */