1 /* common.h
2 
3    GNU Chess frontend
4 
5    Copyright (C) 2001-2020 Free Software Foundation, Inc.
6 
7    GNU Chess is based on the two research programs
8    Cobalt by Chua Kong-Sian and Gazebo by Stuart Cracraft.
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    Contact Info:
24      bug-gnu-chess@gnu.org
25      cracraft@ai.mit.edu, cracraft@stanfordalumni.org, cracraft@earthlink.net
26 */
27 
28 #ifndef COMMON_H
29 #define COMMON_H
30 
31 #include <config.h>
32 #include <pthread.h>
33 
34 #ifndef __GNUC__
35 # define __attribute__(x)
36 #endif
37 
38 /*
39  * Include "uint64_t" and similar types using the ac_need_stdint_h ac macro
40  */
41 
42 #include "GCint.h"
43 
44 #include <stdio.h>
45 #include <sys/types.h>
46 
47  /*
48   * Define time structures to get timeval for Timer
49   */
50 
51 #include <sys/time.h>
52 
53  /*
54   * Define macro for declaring 64bit constants for compilers not using ULL
55   */
56 
57 #ifdef _MSC_VER
58    #define ULL(x) ((uint64_t)(x))
59 #else
60    #define ULL(x) x ## ULL
61 #endif
62 
63 /*
64  * BitBoard is a key data type.  It is a 64-bit value, in which each
65  * bit represents a square on the board as defined by "enum Square".
66  * Thus, bit position 0 represents a fact about square a1, and bit
67  * position 63 represents a fact about square h8.  For example, the
68  * bitboard representing "white rook" positions will have a bit set
69  * for every position occupied on the board by a white rook.
70  */
71 
72 typedef uint64_t BitBoard;
73 typedef uint64_t HashType;
74 typedef uint32_t KeyType;
75 
76 /*
77  * Board represents an entire board's state, and is structured to
78  * simplify analysis:
79  */
80 
81 typedef struct
82 {
83    BitBoard b[2][7];      /* piece/pawn positions by side (0=white, 1=black)
84                              and then by piece (1=pawn..6=king). For example,
85                              b[white][knight] has bits set for every board
86                              position occupied by a White Knight. */
87    BitBoard friends[2];   /* Friendly (this side's) pieces */
88    BitBoard blocker;
89    BitBoard blockerr90;   /* rotated 90 degrees */
90    BitBoard blockerr45;   /* rotated 45 degrees */
91    BitBoard blockerr315;  /* rotated 315 degrees */
92    short ep;              /* Location of en passant square */
93    short flag;            /* Flags related to castle privileges */
94    short side;            /* Color of side on move: 0=white, 1=black */
95    short material[2];     /* Total material by side not inc. king */
96    short pmaterial[2];    /* Total pawn material by side not inc. king */
97    short castled[2];      /* True (1) if side is castled */
98    short king[2];         /* Location of king 0 - a1 .. 63 - h8 */
99 } Board;
100 
101 /* leaf describes a leaf-level analysis result */
102 
103 typedef struct
104 {
105    int move;   /* the move that produced this particular board */
106    int score;  /* the scored value of this leaf */
107 } leaf;
108 
109 /*
110  * GameRec records an individual move made in the game; an entire
111  * Game is a set of GameRec's:
112  */
113 
114 #define SANSZ 8 /* longest move is "exf8=Q+" so 7+1 */
115 
116 typedef struct
117 {
118    int move;    /* The actual move made; this is NOT the move count! */
119    short epsq;  /* en passant square */
120    short bflag; /* Flags for castle privs, see Board.flag */
121    short Game50; /* The last value of GameCnt (a count of half-moves)
122                     that castled, captured, or moved a pawn */
123    short mvboard;
124    float et;     /* elapsed time */
125    HashType hashkey;
126    HashType phashkey;
127    char SANmv[SANSZ];  /* The move in SAN notation */
128    char *comments;
129 } GameRec;
130 
131 
132 /*  MACRO definitions */
133 
134 #ifndef MAX
135 #define MAX(a,b)     ((a) > (b) ? (a) : (b))
136 #endif
137 #ifndef MIN
138 #define MIN(a,b)     ((a) < (b) ? (a) : (b))
139 #endif
140 #define SET(a,b)                     \
141   do {                               \
142     (a) |= (b);                      \
143     dbg_printf("Set   0x%x\n", (b)); \
144   } while (0)
145 #define CLEAR(a,b)                   \
146   do {                               \
147     (a) &= ~(b);                     \
148     dbg_printf("Clear 0x%x\n", (b)); \
149   } while (0)
150 
151 /* Draw score can be used to penalise draws if desired */
152 #define PHASE	     (8 - (board.material[white]+board.material[black]) / 1150)
153 
154 /*  Attack MACROS */
155 
156 #define BishopAttack(sq) \
157 	(Bishop45Atak[sq][(board.blockerr45 >> Shift45[sq]) & Mask45[sq]] | \
158 	 Bishop315Atak[sq][(board.blockerr315 >> Shift315[sq]) & Mask315[sq]])
159 #define RookAttack(sq)	\
160 	(Rook00Atak[sq][(board.blocker >> Shift00[sq]) & 0xFF] | \
161          Rook90Atak[sq][(board.blockerr90 >> Shift90[sq]) & 0xFF])
162 #define QueenAttack(sq)	\
163 	(BishopAttack(sq) | RookAttack(sq))
164 
165 
166 /*  Some bit macros  */
167 
168 /*
169  * gcc 2.95.4 completely screws up the macros with lookup tables
170  * with -O2 on PPC, maybe this check has to be refined. (I don't know
171  * whether other architectures also suffer from this gcc bug.) However,
172  * with gcc 3.0, the lookup tables are _much_ faster than this direct
173  * calculation.
174  */
175 #if defined(__GNUC__) && defined(__PPC__) && __GNUC__ < 3
176 #  define SETBIT(b,i)   ((b) |=  ((ULL(1)<<63)>>(i)))
177 #  define CLEARBIT(b,i) ((b) &= ~((ULL(1)<<63)>>(i)))
178 #else
179 #  define SETBIT(b,i)   ((b) |= BitPosArray[i])
180 #  define CLEARBIT(b,i) ((b) &= NotBitPosArray[i])
181 #endif
182 
183 #define RANK(i) ((i) >> 3)
184 #define ROW(i) ((i) & 7)
185 #define trailz(b) (leadz ((b) & ((~b) + 1)))
186 
187 /* Move Descriptions (moves) are represented internally as integers.
188  * The lowest 6 bits define the destination ("TO") square, and
189  * the next lowest 6 bits define the source ("FROM") square,
190  * using the values defined by "enum Square" (0=a1, 63=h8).
191  * Upper bits are used to identify other move information such as
192  * a promotion (and to what), a capture (and of what),
193  * CASTLING moves, and ENPASSANT moves; see the "constants for
194  * move description" below for more information on these upper bits.
195  */
196 #define PROMOTEPIECE(a) ((a >> 12) & 0x0007)
197 #define CAPTUREPIECE(a) ((a >> 15) & 0x0007)
198 #define TOSQ(a)         ((a) & 0x003F)
199 #define FROMSQ(a)       ((a >> 6) & 0x003F)
200 #define MOVE(a,b)       (((a) << 6) | (b))
201 
202 /* constants for move description */
203 #define KNIGHTPRM     0x00002000
204 #define BISHOPPRM     0x00003000
205 #define ROOKPRM       0x00004000
206 #define QUEENPRM      0x00005000
207 #define PROMOTION     0x00007000
208 #define PAWNCAP       0x00008000
209 #define KNIGHTCAP     0x00010000
210 #define BISHOPCAP     0x00018000
211 #define ROOKCAP       0x00020000
212 #define QUEENCAP      0x00028000
213 #define CAPTURE       0x00038000
214 #define NULLMOVE      0x00100000
215 #define CASTLING      0x00200000
216 #define ENPASSANT     0x00400000
217 #define MOVEMASK      (CASTLING | ENPASSANT | PROMOTION | 0x0FFF)
218 
219 #define white  0
220 #define black  1
221 #define false  0
222 #define true   1
223 #define ks 0
224 #define qs 1
225 #define MATE	  32767
226 #define MATESCORE(a)	((a) > MATE-255  || (a) < -MATE+255)
227 
228 /* constants for Board */
229 #define WKINGCASTLE   0x0001
230 #define WQUEENCASTLE  0x0002
231 #define BKINGCASTLE   0x0004
232 #define BQUEENCASTLE  0x0008
233 #define WCASTLE	      (WKINGCASTLE | WQUEENCASTLE)
234 #define BCASTLE	      (BKINGCASTLE | BQUEENCASTLE)
235 
236 /* Material values */
237 #define ValueP   100
238 #define ValueN   350
239 #define ValueB   350
240 #define ValueR   550
241 #define ValueQ   1100
242 #define ValueK   2000
243 
244 
245 /*  Some special BitBoards  */
246 #define NULLBITBOARD  ( ULL(0x0000000000000000))
247 #define WHITESQUARES  ( ULL(0x55AA55AA55AA55AA))
248 #define BLACKSQUARES  ( ULL(0xAA55AA55AA55AA55))
249 #define CENTRESQUARES ( ULL(0x0000001818000000))
250 #define COMPUTERHALF  ( ULL(0xFFFFFFFF00000000))
251 #define OPPONENTHALF  ( ULL(0x00000000FFFFFFFF))
252 
253 /*  Game flags */
254 #define QUIT    0x0001
255 #define TESTT   0x0002
256 #define THINK   0x0004
257 #define MANUAL  0x0008
258 #define TIMEOUT 0x0010
259 #define UCI     0x0020
260 #define WEAK    0x0020
261 #define ENDED   0x0040
262 #define USEHASH 0x0080
263 #define SOLVE   0x0100
264 #define USENULL 0x0200
265 #define XBOARD  0x0400
266 #define TIMECTL 0x0800
267 #define POST    0x1000
268 #define PONDER  0x2000 /* We are in pondering (during search) */
269 #define HARD    0x4000 /* Pondering is turned on */
270 #define ANALYZE 0x8000 /* In ANALYZE mode */
271 
272 /*  Book modes */
273 #define BOOKOFF 0
274 #define BOOKRAND 1
275 #define BOOKBEST 2
276 #define BOOKWORST 3
277 #define BOOKPREFER 4
278 
279 #define MAXTREEDEPTH  2000
280 #define MAXPLYDEPTH   65
281 #define MAXGAMEDEPTH  600
282 
283 #define R_WHITE_WINS 1
284 #define R_BLACK_WINS 2
285 #define R_DRAW 3
286 #define R_NORESULT 4
287 
288 extern unsigned char lzArray[65536];
289 extern short Shift00[64];
290 extern short Shift90[64];
291 extern short Shift45[64];
292 extern short Shift315[64];
293 extern BitBoard BitPosArray[64];
294 extern BitBoard NotBitPosArray[64];
295 extern BitBoard MoveArray[8][64];
296 extern BitBoard Ray[64][8];
297 extern BitBoard FromToRay[64][64];
298 extern BitBoard RankBit[8];
299 extern BitBoard FileBit[8];
300 extern BitBoard Ataks[2][7];
301 extern BitBoard Rook00Atak[64][256];
302 extern BitBoard Rook90Atak[64][256];
303 extern BitBoard Bishop45Atak[64][256];
304 extern BitBoard Bishop315Atak[64][256];
305 extern short directions[64][64];
306 extern unsigned char BitCount[65536];
307 extern leaf Tree[MAXTREEDEPTH];
308 extern leaf *TreePtr[MAXPLYDEPTH];
309 extern GameRec Game[MAXGAMEDEPTH];
310 extern int RealGameCnt;
311 extern short RealSide;
312 extern int GameCnt;
313 extern int computer;
314 extern unsigned int flags;
315 extern unsigned int preanalyze_flags;
316 extern Board board;
317 extern int cboard[64];
318 extern int Mvboard[64];
319 extern HashType hashcode[2][7][64];
320 extern HashType ephash[64];
321 extern HashType WKCastlehash;
322 extern HashType WQCastlehash;
323 extern HashType BKCastlehash;
324 extern HashType BQCastlehash;
325 extern HashType Sidehash;
326 extern HashType HashKey;
327 extern HashType PawnHashKey;
328 extern int Game50;
329 extern unsigned long GenCnt;
330 extern int slider[8];
331 extern int Value[7];
332 extern char SANmv[SANSZ];
333 extern char id[32];
334 extern char solution[64];
335 extern float SearchTime;
336 extern int MoveLimit[2];
337 extern float TimeLimit[2];
338 extern int TCMove;
339 extern int TCinc;
340 extern float TCTime;
341 extern int phase;
342 
343 extern short bookfirstlast;
344 extern short graphicmodeoutput;
345 extern short coords;
346 extern short pgnloaded; /* was pgn game loaded by command pgnreplay */
347 extern int pgncnt; /* total moves loaded in pgn game */
348 
349 extern int range[8];
350 extern int ptype[2];
351 extern char algbr[64][3];
352 extern char algbrfile[9];
353 extern char algbrrank[9];
354 extern char notation[8];
355 extern char lnotation[8];
356 extern int r90[64];
357 extern int r45[64];
358 extern int r315[64];
359 extern int Mask45[64];
360 extern int Mask315[64];
361 
362 extern char *progname;
363 extern FILE *ofp;
364 extern int myrating, opprating;
365 
366 #define MAXNAMESZ 50
367 extern char name[MAXNAMESZ];
368 extern int computerplays;
369 extern int n; 		/* Last mobility returned by CTL */
370 extern int ExchCnt[2];
371 
372 enum Piece { empty, pawn, knight, bishop, rook, queen, king, bpawn };
373 
374 enum Square { A1, B1, C1, D1, E1, F1, G1, H1,
375 	      A2, B2, C2, D2, E2, F2, G2, H2,
376 	      A3, B3, C3, D3, E3, F3, G3, H3,
377 	      A4, B4, C4, D4, E4, F4, G4, H4,
378 	      A5, B5, C5, D5, E5, F5, G5, H5,
379 	      A6, B6, C6, D6, E6, F6, G6, H6,
380 	      A7, B7, C7, D7, E7, F7, G7, H7,
381 	      A8, B8, C8, D8, E8, F8, G8, H8 };
382 
383 enum File { A_FILE, B_FILE, C_FILE, D_FILE, E_FILE, F_FILE, G_FILE, H_FILE };
384 
385 /****************************************************************************
386  *
387  *  The various function prototypes.  They are group into the *.c files
388  *  in which they are defined.
389  *
390  ****************************************************************************/
391 
392 /*
393  * Explanation of the #ifdef NO_INLINE conditionals:
394  *
395  * Define NO_INLINE only if you really must, implementations will be
396  * provided by the corresponding *.c files. The better solution is to
397  * not define it, in which case inlines.h will be included which
398  * provides static inline version of these functions.
399  */
400 
401 /*  The initialization routines  */
402 void Initialize (void);
403 void InitLzArray (void);
404 void InitBitPosArray (void);
405 void InitMoveArray (void);
406 void InitRay (void);
407 void InitFromToRay (void);
408 void InitRankFileBit (void);
409 void InitBitCount (void);
410 void InitPassedPawnMask (void);
411 void InitIsolaniMask (void);
412 void InitSquarePawnMask (void);
413 void InitRandomMasks (void);
414 void InitRotAtak (void);
415 void InitDistance (void);
416 void InitVars (void);
417 void InitHashCode (void);
418 void InitHashTable (void);
419 void NewPosition (void);
420 void InitInput (void);
421 
422 /*  The move generation routines  */
423 void GenMoves (short);
424 void GenCaptures (short);
425 void GenNonCaptures (short);
426 void GenCheckEscapes (short);
427 void FilterIllegalMoves (short);
428 
429 /*  The move routines  */
430 void MakeMove (int, int *);
431 void UnmakeMove (int, int *);
432 void SANMove (int, int);
433 leaf *ValidateMove (char *, char *cleanMove=0);
434 leaf *IsInMoveList (int, int, int, char);
435 char *AlgbrMove (int);
436 
437 /*  The attack routines  */
438 short SqAtakd (short sq, short side);
439 BitBoard AttackTo (int, int);
440 int PinnedOnKing (int, int);
441 
442 /*  The swap routines  */
443 int SwapOff (int);
444 void AddXrayPiece (int, int, int, BitBoard *, BitBoard *);
445 
446 /*  The EPD routines  */
447 short ReadEPDFile (const char *, short);
448 int ParseEPD (char *);
449 void LoadEPD (char *);
450 void SaveEPD (char *);
451 void EPD2str (char *);
452 
453 /* Error codes for ParseEPD */
454 enum {
455    EPD_SUCCESS,
456    EPD_ERROR
457 };
458 
459 void UpdateFriends (void);
460 void UpdateCBoard (void);
461 void UpdateMvboard (void);
462 short ValidateBoard (void);
463 
464 /*  PGN routines  */
465 void PGNSaveToFile (const char *, const char *);
466 void PGNReadFromFile (const char *, int showheading);
467 
468 /*  Some output routines */
469 void ShowMoveList (int);
470 void ShowBoard (void);
471 void ShowCBoard (void);
472 void ShowMvboard (void);
473 
474 void ShowGame (void);
475 void ShowTime (void);
476 
477 /*  Solver routines  */
478 void Solve (char *);
479 
480 /* Player database */
481 void DBSortPlayer (const char *style);
482 void DBListPlayer (const char *style);
483 void DBReadPlayer (void);
484 void DBWritePlayer (void);
485 int DBSearchPlayer (const char *player);
486 void DBUpdatePlayer (const char *player, const char *resultstr);
487 
488 /* Input thread and thread function */
489 extern pthread_t input_thread;
490 void *input_func(void *);
491 
492 /*
493  * Status variable used by the input thread to signal
494  * pending input. Thought about using flags for this
495  * but this can be refined and is conceptually different
496  * from flags.
497  */
498 enum {
499   INPUT_NONE,
500   INPUT_AVAILABLE
501 };
502 extern volatile int input_status;
503 
504 /*
505  * Function to wake up the input thread, should be called after
506  * input has been parsed.
507  */
508 void input_wakeup(void);
509 
510 /* Wait for input. */
511 
512 //void wait_for_input(void);
513 
514 /*
515  * Input routine, initialized to one of the specific
516  * input routines. The given argument is the prompt.
517  */
518 extern void (*get_line) (char *);
519 
520 #define BUF_SIZE 4096
521 
522 #define MAXSTR 128
523 extern char inputstr[BUF_SIZE];
524 
525 /* Input parser */
526 void parse_input(void);
527 
528 /* Check Board to avoid analysis of incorrectly input positions */
529 void check_board(void);
530 
531 /* Commands from the input engine */
532 void cmd_activate(void);
533 void cmd_analyze(void);
534 void cmd_bk(void);
535 void cmd_black(void);
536 void cmd_book(void);
537 void cmd_computer(void);
538 void cmd_depth(void);
539 void cmd_draw(void);
540 void cmd_easy(void);
541 void cmd_edit(void);
542 void cmd_epd(void);
543 void cmd_exit(void);
544 void cmd_force(void);
545 void cmd_go(void);
546 void cmd_graphic(void);
547 void cmd_hard(void);
548 void cmd_hash(void);
549 void cmd_help (void);
550 void cmd_hint(void);
551 void cmd_last(void);
552 void cmd_level(void);
553 void cmd_list(void);
554 void cmd_load(void);
555 void cmd_manual(void);
556 void cmd_movenow(void);
557 void cmd_name(void);
558 void cmd_next(void);
559 void cmd_new(void);
560 void cmd_nographic(void);
561 void cmd_nopost(void);
562 void cmd_null(void);
563 void cmd_otim(void);
564 void cmd_pgnload(void);
565 void cmd_pgnreplay(void);
566 void cmd_pgnsave(void);
567 void cmd_ping(void);
568 void cmd_post(void);
569 void cmd_previous(void);
570 void cmd_first(void);
571 void cmd_protover(void);
572 void cmd_quit(void);
573 void cmd_random(void);
574 void cmd_rating(void);
575 void cmd_rejected(void);
576 void cmd_remove(void);
577 void cmd_result(void);
578 void cmd_save(void);
579 void cmd_setboard(void);
580 void cmd_show (void);
581 void cmd_solve(void);
582 void cmd_st(void);
583 void cmd_switch(void);
584 void cmd_test (void);
585 void cmd_time(void);
586 void cmd_undo(void);
587 void cmd_usage(void);
588 void cmd_variant(void);
589 void cmd_version(void);
590 void cmd_white(void);
591 void cmd_xboard(void);
592 
593 
594 /*
595  * Define NO_INLINE only if you really must, implementations will be
596  * provided by the corresponding *.c files. The better solution is to
597  * not define it, in which case inlines.h will be included which
598  * provides static inline version of these functions.
599  */
600 
601 /*  Some utility routines  */
602 #ifdef NO_INLINE
603 unsigned char leadz (BitBoard);
604 unsigned char nbits (BitBoard);
605 #else
606 # include "inlines.h"
607 #endif
608 
609 /* More elaborate debugging output to logfile */
610 
611 /* All the following functions are no-ops if DEBUG is not defined */
612 
613 /*
614  * dbg_open() can be called with NULL as argument, using a default
615  * filename, defined in debug.c, for the debug log. Otherwise the
616  * argument is the filename. If dbg_open() fails or is not called at
617  * all, debugging output goes to stderr by default.
618  */
619 int dbg_open(const char *name);
620 
621 /* Same format rules as printf() */
622 int dbg_printf(const char *fmt, ...);
623 
624 /* Closes the debugging log, if it is not stderr */
625 int dbg_close(void);
626 
627 # ifdef DEBUG
628 #  include <assert.h>
629 #  define ASSERT(x) assert(x)
630 # else
631 #  define ASSERT(x)
632 # endif
633 
634 /*
635  * Initializes data used in the frontend.
636  */
637 void InitFrontend( void );
638 
639 /*
640  * Reads a char string entered by the user.
641 */
642 void ReadFromUser( void );
643 
644 /*
645  * Sends a message to the adapter/engine.
646 */
647 int SendToEngine( char msg[] );
648 
649 /*
650  * Reads a char string message from the adapter/engine.
651 */
652 int ReadFromEngine( void );
653 
654 /*
655  * Saves in global variable 'dataToEngine' the data to be sent to the engine.
656  */
657 void SetDataToEngine( const char data[] );
658 
659 /*
660  * Stores in a global flag variable whether an answer is expected from
661  * the engine (1) or not (0).
662  */
663 void ExpectAnswerFromEngine( int );
664 
665 /*
666  * Extracts a command from the user input buffer.
667  */
668 void NextUserCmd( void );
669 
670 /*
671  * Extracts a command from the engine input buffer.
672  */
673 void NextEngineCmd( void );
674 
675 /*
676  * Stores in a global flag variable whether an input from the user is a
677  * valid move (1) or not (0).
678  */
679 void SetUserInputValidMove( int valid );
680 
681 /*
682  * Flags whether the color must be changed, e.g. due to an undo command.
683  */
684 void ChangeColor( int change );
685 
686 /*
687  * Sets the autoGo flag, meaning that after a user move a go command will be
688  * sent to the engine. This may be necessary after an undo.
689  */
690 void SetAutoGo( int go );
691 
692 /*
693  * Checks whether the autoGo flag is set or not.
694  */
695 int GetAutoGo( void );
696 
697 /*
698  * Reads a char string entered by the user.
699  * The string must be a command or a move.
700  * The string is sent to the engine straight away.
701  */
702 void ForwardUserInputToEngine( void );
703 
704 /*
705  * Reads a char string message from the engine.
706  * The message is output'd straight away.
707  */
708 void ForwardEngineOutputToUser( void );
709 
710 #endif /* !COMMON_H */
711