Subversion Repositories Games.Chess Giants

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
112 pmbaty 1
/*
2
    Protector -- a UCI chess engine
3
 
4
    Copyright (C) 2009-2010 Raimund Heid (Raimund_Heid@yahoo.com)
5
 
6
    This program is free software: you can redistribute it and/or modify
7
    it under the terms of the GNU General Public License as published by
8
    the Free Software Foundation, either version 3 of the License, or
9
    (at your option) any later version.
10
 
11
    This program is distributed in the hope that it will be useful,
12
    but WITHOUT ANY WARRANTY; without even the implied warranty of
13
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
    GNU General Public License for more details.
15
 
16
    You should have received a copy of the GNU General Public License
17
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
 
19
*/
20
 
21
#ifndef _position_h_
22
#define _position_h_
23
 
24
#include "protector.h"
25
#include "bitboard.h"
26
#include <string.h>
27
#include <stdlib.h>
28
#include <assert.h>
29
 
30
#define MAX_DEPTH 96
31
#define MAX_DEPTH_ARRAY_SIZE (MAX_DEPTH + 2)
32
#define POSITION_HISTORY_OFFSET 100
33
#define DEFAULT_HASHTABLE_EXPONENT   16
34
 
35
#define SEARCHEVENT_SEARCH_FINISHED    1
36
#define SEARCHEVENT_PLY_FINISHED       2
37
#define SEARCHEVENT_NEW_PV             3
38
#define SEARCHEVENT_NEW_BASEMOVE       4
39
#define SEARCHEVENT_STATISTICS_UPDATE  5
40
 
41
#define DEFAULTVALUE_PAWN_OPENING     (85)
42
#define DEFAULTVALUE_PAWN_ENDGAME     (123)
43
 
44
#define PHASE_MAX 62
45
#define PHASE_INDEX_MAX 256
46
#define PIECE_WEIGHT_ENDGAME 16
47
#define DELTA (-3)
48
 
49
#define DEFAULTVALUE_KNIGHT_OPENING    (343)
50
#define DEFAULTVALUE_KNIGHT_ENDGAME    (396)
51
#define DEFAULTVALUE_BISHOP_OPENING    (358)
52
#define DEFAULTVALUE_BISHOP_ENDGAME    (413)
53
#define DEFAULTVALUE_ROOK_OPENING      (580)
54
#define DEFAULTVALUE_ROOK_ENDGAME      (613)
55
#define DEFAULTVALUE_QUEEN_OPENING     (1151)
56
#define DEFAULTVALUE_QUEEN_ENDGAME     (1191)
57
 
58
#define DEFAULTVALUE_BISHOP_PAIR_OPENING  (47)
59
#define DEFAULTVALUE_BISHOP_PAIR_ENDGAME  (55)
60
#define DEFAULTVALUE_PIECE_UP_OPENING  16
61
#define DEFAULTVALUE_PIECE_UP_ENDGAME   4
62
 
63
extern int VALUE_QUEEN_OPENING;
64
extern int VALUE_QUEEN_ENDGAME;
65
extern int VALUE_ROOK_OPENING;
66
extern int VALUE_ROOK_ENDGAME;
67
extern int VALUE_BISHOP_OPENING;
68
extern int VALUE_BISHOP_ENDGAME;
69
extern int VALUE_KNIGHT_OPENING;
70
extern int VALUE_KNIGHT_ENDGAME;
71
extern int VALUE_PAWN_OPENING;
72
extern int VALUE_PAWN_ENDGAME;
73
extern int VALUE_BISHOP_PAIR_OPENING;
74
extern int VALUE_BISHOP_PAIR_ENDGAME;
75
 
76
#define OPENING 0
77
#define ENDGAME 1
78
 
79
extern int basicValue[16], simplePieceValue[16];
80
extern INT32 pieceSquareBonus[16][_64_];
81
extern int pieceCountShift[16];
82
extern int krqIndexWhite[4096], bbpIndexWhite[4096];
83
extern int krqIndexBlack[4096], bbpIndexBlack[4096];
84
extern const int materialUpPawnCountWeight[9];
85
 
86
typedef struct
87
{
88
   Piece piece[_64_];
89
   Color activeColor;
90
   BYTE castlingRights;
91
   Square enPassantSquare;
92
   int moveNumber, halfMoveClock;
93
 
94
   /**
95
    * Redundant data
96
    */
97
   Bitboard allPieces;
98
   Bitboard piecesOfColor[2];
99
   Bitboard piecesOfType[16];
100
   Square king[2];
101
   int numberOfPieces[2];
102
   int numberOfPawns[2];
103
   UINT64 pieceCount;
104
   INT32 balance;
105
   UINT64 hashKey, pawnHashKey;
106
}
107
Position;
108
 
109
typedef UINT32 Move;
110
 
111
typedef struct
112
{
113
   Square square;
114
   Bitboard moves;
115
}
116
MovesOfPiece;
117
 
118
typedef struct
119
{
120
   Bitboard diaAttackers, orthoAttackers, knightAttackers, pawnAttackers[2];
121
   Square attackedByDia[_64_], attackedByOrtho[_64_];
122
}
123
KingAttacks;
124
 
125
#define HASHVALUE_UPPER_LIMIT 0
126
#define HASHVALUE_EXACT 1
127
#define HASHVALUE_LOWER_LIMIT 2
128
#define HASHVALUE_EVAL 3
129
 
130
typedef struct
131
{
132
   UINT16 move[MAX_DEPTH_ARRAY_SIZE];
133
   int length, score, scoreType;
134
}
135
PrincipalVariation;
136
 
137
typedef struct
138
{
139
   Move killerMove1, killerMove2, killerMove3, killerMove4, killerMove5,
140
      killerMove6;
141
   Move currentMove;
142
   int indexCurrentMove;
143
   bool currentMoveIsCheck;
144
   Piece captured, restorePiece1, restorePiece2;
145
   Square enPassantSquare, restoreSquare1, restoreSquare2, kingSquare;
146
   BYTE castlingRights;
147
   int halfMoveClock;
148
   Bitboard allPieces, whitePieces, blackPieces, hashKey, pawnHashKey;
149
   INT32 balance;
150
   int staticValue, refinedStaticValue;
151
   bool staticValueAvailable, gainsUpdated;
152
   bool quietMove, isHashMove;
153
   UINT64 pieceCount;
154
   PrincipalVariation pv;
155
}
156
PlyInfo;
157
 
158
typedef struct
159
{
160
   Position *position;
161
   PlyInfo *plyInfo;
162
   Move hashMove;
163
   Move moves[MAX_MOVES_PER_POSITION];
164
   Move badCaptures[MAX_MOVES_PER_POSITION];
165
   bool killer1Executed, killer2Executed, killer3Executed, killer4Executed,
166
      killer5Executed, killer6Executed;
167
   MovesOfPiece movesOfPiece[16];
168
   int numberOfMoves, numberOfBadCaptures;
169
   int nextMove, currentStage, numberOfPieces;
170
   UINT16 *historyValue;
171
   INT16 *positionalGain;
172
}
173
Movelist;
174
 
175
typedef struct
176
{
177
   UINT64 key;
178
   UINT64 data;
179
}
180
Hashentry;
181
 
182
typedef struct
183
{
184
   UINT64 key;
185
   UINT8 depth;
186
}
187
Nodeentry;
188
 
189
typedef struct
190
{
191
   Hashentry *table;
192
   UINT64 tableSize, entriesUsed;
193
   UINT8 date;
194
}
195
Hashtable;
196
 
197
typedef enum
198
{
199
   SEARCH_STATUS_RUNNING,
200
   SEARCH_STATUS_TERMINATE,
201
   SEARCH_STATUS_ABORT,
202
   SEARCH_STATUS_FINISHED
203
}
204
SearchStatus;
205
 
206
#define HISTORY_SIZE (16*64)
207
#define HISTORY_MAX  16384
208
#define HISTORY_LIMIT 60        /* (60%) */
209
#define PAWN_HASHTABLE_MASK 0xffff
210
#define PAWN_HASHTABLE_SIZE ((PAWN_HASHTABLE_MASK)+0x0001)
211
#define KINGSAFETY_HASHTABLE_MASK 0x07ffff
212
#define KINGSAFETY_HASHTABLE_SIZE ((KINGSAFETY_HASHTABLE_MASK)+0x0001)
213
 
214
typedef struct
215
{
216
   Bitboard hashKey;
217
   Bitboard pawnProtectedSquares[2];
218
   Bitboard passedPawns[2];
219
   Bitboard pawnAttackableSquares[2];
220
   bool hasPassersOrCandidates[2];
221
   INT32 balance;
222
}
223
PawnHashInfo;
224
 
225
typedef struct
226
{
227
   Bitboard hashKey;
228
   INT32 safetyMalus;
229
}
230
KingSafetyHashInfo;
231
 
232
extern KingSafetyHashInfo
233
   kingSafetyHashtable[MAX_THREADS][KINGSAFETY_HASHTABLE_SIZE];
234
 
235
#define BONUS_HIDDEN_PASSER
236
 
237
typedef enum
238
{
239
   Se_None,
240
   Se_KpK,
241
   Se_KnnKp,
242
   Se_KbpK,
243
   Se_KrpKb,
244
   Se_KrpKr,
245
   Se_KrppKr,
246
   Se_KqpKq,
247
   Se_KqppKq,
248
   Se_KppxKx,
249
   Se_KpxKpx
250
} SpecialEvalType;
251
 
252
typedef struct
253
{
254
   UINT8 chancesWhite, chancesBlack;
255
   SpecialEvalType specialEvalWhite, specialEvalBlack;
256
   INT32 materialBalance;
257
   int phaseIndex;
258
}
259
MaterialInfo;
260
 
261
typedef struct
262
{
263
   Bitboard upwardRealm[2];
264
   Bitboard downwardRealm[2];
265
   Bitboard pawnAttackableSquares[2];
266
   Bitboard pawnProtectedSquares[2];
267
   Bitboard doubledPawns[2];
268
   Bitboard passedPawns[2];
269
   Bitboard candidatePawns[2];
270
 
271
#ifdef BONUS_HIDDEN_PASSER
272
   Bitboard hiddenCandidatePawns[2];
273
   bool hasPassersOrCandidates[2];
274
#endif
275
 
276
#ifdef MALUS_SLIGHTLY_BACKWARD
277
   Bitboard slightlyBackward[2];
278
#endif
279
 
280
   Bitboard weakPawns[2];
281
   Bitboard fixedPawns[2];
282
   Bitboard countedSquares[2];
283
   Bitboard unprotectedPieces[2];
284
   Bitboard kingAttackSquares[2];
285
   Bitboard attackedSquares[2];
286
   Bitboard knightAttackedSquares[2];
287
   Bitboard bishopAttackedSquares[2];
288
   Bitboard rookAttackedSquares[2];
289
   Bitboard rookDoubleAttackedSquares[2];
290
   Bitboard queenAttackedSquares[2];
291
   Bitboard queenSupportedSquares[2];
292
   Bitboard chainPawns[2];
293
   Bitboard pinnedCandidatesDia[2];
294
   Bitboard pinnedCandidatesOrtho[2];
295
   Bitboard pinnedPieces[2];
296
   INT32 attackInfo[2];
297
   int kingSquaresAttackCount[2];
298
   int spaceAttackPoints[2];
299
   bool evaluateKingSafety[2];
300
   KingSafetyHashInfo *kingsafetyHashtable;
301
   INT32 balance, materialBalance;
302
   MaterialInfo *materialInfo;
303
   Color ownColor;
304
}
305
EvaluationBase;
306
 
307
typedef struct
308
{
309
   int ply, iteration, selDepth;
310
   int numberOfBaseMoves, numberOfCurrentBaseMove;
311
   Move currentBaseMove, bestBaseMove;
312
   Position singlePosition, startPosition;
313
   PlyInfo plyInfo[MAX_DEPTH_ARRAY_SIZE];
314
   PrincipalVariation completePv;
315
   PrincipalVariation pv[MAX_NUM_PV];
316
   int pvId;
317
   PawnHashInfo *pawnHashtable;
318
   KingSafetyHashInfo *kingsafetyHashtable;
319
   UINT64 positionHistory[POSITION_HISTORY_OFFSET + MAX_DEPTH_ARRAY_SIZE];
320
   UINT64 nodes, nodesAtTimeCheck, nodesBetweenTimecheck;
321
   UINT16 historyValue[HISTORY_SIZE];
322
   INT16 positionalGain[HISTORY_SIZE];
323
   Move counterMove1[HISTORY_SIZE], counterMove2[HISTORY_SIZE];
324
   Move followupMove1[HISTORY_SIZE], followupMove2[HISTORY_SIZE];
325
   long startTime, timeTarget, timeLimit, finishTime, timestamp;
326
   long startTimeProcess, finishTimeProcess, hashSendTimestamp;
327
   unsigned long tbHits;
328
   void (*handleSearchEvent) (int, void *);
329
   SearchStatus searchStatus;
330
   int drawScore[2];
331
   int bestMoveChangeCount;
332
   bool terminate, ponderMode, terminateSearchOnPonderhit, failingLow;
333
   int previousBest;
334
   long numPvUpdates;
335
   unsigned int threadNumber;
336
   Color ownColor;
337
#ifdef _MSC_VER
338
   bool finished; // Pierre-Marie Baty -- for Win32 thread control
339
#endif // _MSC_VER
340
}
341
Variation;
342
 
343
#define TIME_CHECK_INTERVALL_IN_MS 100
344
#define NODES_BETWEEN_TIMECHECK_DEFAULT 25000
345
 
346
#define V(op,eg) ( (op) + ( (eg) << 16 ) )
347
#define HV(op,eg) ( (((op)*100)/256) + ( (((eg)*100)/256) << 16 ) )
348
 
349
/**
350
 * Flip the specified position.
351
 */
352
void flipPosition(Position * position);
353
 
354
/**
355
 * Remove all pieces from the specified position.
356
 */
357
void clearPosition(Position * position);
358
 
359
/**
360
 * Calculate the redundant data of the specified position.
361
 */
362
void initializePosition(Position * position);
363
 
364
/**
365
 * Prepare a search with the specified variation.
366
 */
367
void prepareSearch(Variation * variation);
368
 
369
/**
370
 * Reset history values.
371
 */
372
void resetHistoryValues(Variation * variation);
373
 
374
/**
375
 * Reset history hit values.
376
 */
377
void resetHistoryHitValues(Variation * variation);
378
 
379
/**
380
 * Reset gain values.
381
 */
382
void resetGainValues(Variation * variation);
383
 
384
/**
385
 * Shrink all history values.
386
 */
387
void shrinkHistoryValues(Variation * variation);
388
 
389
/**
390
 * Shrink all history hit values.
391
 */
392
void shrinkHistoryHitValues(Variation * variation);
393
 
394
/**
395
 * Initialize a variation with the position specified by 'fen'.
396
 * Prepare a search.
397
 */
398
void initializeVariation(Variation * variation, const char *fen);
399
 
400
/**
401
 * Initialize a variation with the position specified by 'position'.
402
 * To perform a search, call 'prepareSearch' afterwards.
403
 */
404
void setBasePosition(Variation * variation, const Position * position);
405
 
406
/**
407
 * Set the value of a definite draw.
408
 */
409
void setDrawScore(Variation * variation, int score, Color color);
410
 
411
/**
412
 * Get the pieces interested in moving to 'square'.
413
 */
414
Bitboard getInterestedPieces(const Position * position, const Square square,
415
                             const Color attackerColor);
416
 
417
/**
418
 * Make the specified move at the current end of the specified variation.
419
 *
420
 * @return 1 if the move was an illegal castling move, 0 otherwise
421
 */
422
int makeMove(Variation * variation, const Move move);
423
 
424
/**
425
 * Make the specified move at the current end of the specified variation.
426
 *
427
 * @return 1 if the move was an illegal castling move, 0 otherwise
428
 */
429
int makeMoveFast(Variation * variation, const Move move);
430
 
431
/**
432
 * Unmake the last move.
433
 */
434
void unmakeLastMove(Variation * variation);
435
 
436
/**
437
 * Test if a move attacks the opponent's king.
438
 *
439
 * @return FALSE if the specified move doesn't attack
440
 *         the opponent's king, TRUE otherwise
441
 */
442
bool moveIsCheck(const Move move, const Position * position);
443
 
444
/**
445
 * Check if the specified position is consistent.
446
 *
447
 * @return 0 if the specified position is consistent
448
 */
449
int checkConsistency(const Position * position);
450
 
451
/**
452
 * Check if the specified variation is consistent.
453
 *
454
 * @return 0 if the specified variation is consistent
455
 */
456
int checkVariation(Variation * variation);
457
 
458
/**
459
 * Check if the given position is legal.
460
 */
461
bool positionIsLegal(const Position * position);
462
 
463
/**
464
 * Check if the specified position are identical (excluding move numbers).
465
 */
466
bool positionsAreIdentical(const Position * position1,
467
                           const Position * position2);
468
 
469
/**
470
 * Calculate the signature for a given set of piece counters.
471
 */
472
UINT32 materialSignature(const UINT32 numQueens, const UINT32 numRooks,
473
                         const UINT32 numLightSquareBishops,
474
                         const UINT32 numDarkSquareBishops,
475
                         const UINT32 numKnights, const UINT32 numPawns);
476
 
477
Square relativeSquare(const Square square, const Color color);
478
INT32 evalBonus(INT32 openingBonus, INT32 endgameBonus);
479
int getOpeningValue(INT32 value);
480
int getEndgameValue(INT32 value);
481
void addBonusForColor(const INT32 bonus, Position * position,
482
                      const Color color);
483
UINT16 packedMove(const Move move);
484
Move getMove(const Square from, const Square to,
485
             const Piece newPiece, const INT16 value);
486
Move getOrdinaryMove(const Square from, const Square to);
487
Move getPackedMove(const Square from, const Square to, const Piece newPiece);
488
Square getFromSquare(const Move move);
489
Square getToSquare(const Move move);
490
Piece getNewPiece(const Move move);
491
INT16 getMoveValue(const Move move);
492
void setMoveValue(Move * move, const int value);
493
Color opponent(Color color);
494
Bitboard getDirectAttackers(const Position * position,
495
                            const Square square,
496
                            const Color attackerColor,
497
                            const Bitboard obstacles);
498
Bitboard getDiaSquaresBehind(const Position * position,
499
                             const Square targetSquare,
500
                             const Square viewPoint);
501
Bitboard getOrthoSquaresBehind(const Position * position,
502
                               const Square targetSquare,
503
                               const Square viewPoint);
504
void initializePlyInfo(Variation * variation);
505
void initializePv(PrincipalVariation * pv);
506
void initializePvsOfVariation(Variation * variation);
507
void resetPvsOfVariation(Variation * variation);
508
void addPvByScore(Variation * variation, PrincipalVariation * pv);
509
bool pvListContainsMove(Variation * variation, PrincipalVariation * pv);
510
void resetPlyInfo(Variation * variation);
511
int numberOfNonPawnPieces(const Position * position, const Color color);
512
bool hasOrthoPieces(const Position * position, const Color color);
513
bool hasQueen(const Position * position, const Color color);
514
void appendMoveToPv(const PrincipalVariation * oldPv,
515
                    PrincipalVariation * newPv, const Move move);
516
INT16 calcHashtableValue(const int value, const int ply);
517
int calcEffectiveValue(const int value, const int ply);
518
Bitboard getOrdinaryPieces(const Position * position, const Color color);
519
Bitboard getNonPawnPieces(const Position * position, const Color color);
520
Bitboard getOrthoPieces(const Position * position, const Color color);
521
bool movesAreEqual(const Move m1, const Move m2);
522
int getPieceCount(const Position * position, const Piece piece);
523
bool pieceIsPresent(const Position * position, const Piece piece);
524
int historyIndex(const Move move, const Position * position);
525
int moveIndex(const Move move, const Position * position);
526
int getMinimalDistance(const Position * position,
527
                       const Square origin, const Piece piece);
528
int getMinimalTaxiDistance(const Position * position,
529
                           const Square origin, const Piece piece);
530
int getPieceWeight(const Position * position, const Color color);
531
int phaseIndex(const Position * position);
532
void getPieceCounters(UINT32 materialSignature,
533
                      int *numWhiteQueens, int *numWhiteRooks,
534
                      int *numWhiteLightSquareBishops,
535
                      int *numWhiteDarkSquareBishops,
536
                      int *numWhiteKnights, int *numWhitePawns,
537
                      int *numBlackQueens, int *numBlackRooks,
538
                      int *numBlackLightSquareBishops,
539
                      int *numBlackDarkSquareBishops,
540
                      int *numBlackKnights, int *numBlackPawns);
541
UINT32 calculateMaterialSignature(const Position * position);
542
UINT32 bilateralSignature(const UINT32 signatureWhite,
543
                          const UINT32 signatureBlack);
544
UINT32 getMaterialSignature(const int numWhiteQueens,
545
                            const int numWhiteRooks,
546
                            const int numWhiteLightSquareBishops,
547
                            const int numWhiteDarkSquareBishops,
548
                            const int numWhiteKnights,
549
                            const int numWhitePawns,
550
                            const int numBlackQueens,
551
                            const int numBlackRooks,
552
                            const int numBlackLightSquareBishops,
553
                            const int numBlackDarkSquareBishops,
554
                            const int numBlackKnights,
555
                            const int numBlackPawns);
556
UINT32 getSingleMaterialSignature(const int numQueens,
557
                                  const int numRooks,
558
                                  const int numLightSquareBishops,
559
                                  const int numDarkSquareBishops,
560
                                  const int numKnights, const int numPawns);
561
UINT32 getMaterialSignatureFromPieceCount(const Position * position);
562
 
563
/**
564
 * Initialize this module.
565
 *
566
 * @return 0 if no errors occurred.
567
 */
568
int initializeModulePosition(void);
569
 
570
/**
571
 * Test this module.
572
 *
573
 * @return 0 if all tests succeed.
574
 */
575
int testModulePosition(void);
576
 
577
#endif