Compare commits

..

410 Commits

Author SHA1 Message Date
Marco Costalba
21de03fad7 Revert "Another PSQT tuning round"
At longer TC of 1'+0" patch fails:
Orig - Mod: 841 - 819 (-6 elo!)

Just before the release ;-)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-02 06:55:03 +01:00
Marco Costalba
2d635f7b74 Stockfish 1.8
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-02 06:23:15 +01:00
Marco Costalba
b50dc1647f Mark CheckInfo c'tor as explicit
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-01 22:21:09 +01:00
Marco Costalba
971c591be7 Move singleEvasion assignment out of move's loop
We don't need to recheck after every move.

Spotted by Ralph Stoesser.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-01 22:18:53 +01:00
Joona Kiiski
b24a2dfc72 Another PSQT tuning round
This time with a new algorithm by Joona.

It works basically like this:

repeat
{
   1) pick 8000 random positions from qsearch
   2) "go depth 8" to get the true evaluation.
   3) "eval" to get the stand pat score
   4) Adjusting parameters one by one to minimize deltasum between
true evaluation and stand  pat scores.
}

* Good news: method seems to converge
* Bad news: Point where it converges is not optimum.

So it's more or less trial and error... sometimes works, sometimes
doesn't. It can give you the right direction, but if you let it run
too long, it fails. Far from scientific ;)

After 14800 games with 5s/game
Orig - Mod: 3318 - 3570 - 7626 (+6 elo)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-29 18:52:51 +01:00
Marco Costalba
4d170725ab Remove a redundant check in passed pawn eval
When first condition is met then second one is
always true.

Spotted by Ralph Stoesser.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-29 18:35:54 +01:00
Marco Costalba
aad8c82cf6 Code style triviality in san.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-29 18:33:43 +01:00
Marco Costalba
6c0a37bbf2 Rename TranspositionTable 'writes' in 'overwrites'
Better documents what that variable means.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-29 18:23:45 +01:00
Marco Costalba
5c3ebd1fbf Extract only exact scores to get the PV
This should allow to skip overwritten nodes because
only in PV we store in TT with VALUE_TYPE_EXACT flag.

Test result for the whole series is:

After 3627 games at 5"
Mod vs Orig +1037 =1605 -985 +5 ELO

After 1311 games at 1'+0"
Mod vs Orig +234 =850 -227 +2 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-29 18:23:28 +01:00
Marco Costalba
62c68c2d21 Retire update_pv() and sp_update_pv()
Expand inline instead.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-26 15:43:54 +01:00
Marco Costalba
adb43cc0cc Retire pv[] from SearchStack
Extract PV info from TT instead of using
a set of arrays. This is almost equivalent
except for cases when TT is full and the PV entry
is overwritten, but this is very rare.

(Almost) No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-26 15:13:39 +01:00
Marco Costalba
0a687b2cf0 Introduce bestMove to store PV move
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-26 14:42:44 +01:00
Marco Costalba
eb48c54687 Cleanup code that stores score in TT
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-26 11:01:43 +01:00
Joona Kiiski
3c3b129e7b Fix some wrong documentation
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-26 10:23:31 +01:00
Joona Kiiski
918533dc06 Remove unused constant
Fixes warning on ICC

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-26 10:22:26 +01:00
Marco Costalba
0ac44b40c9 Stockfish 1.8 beta 2
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-25 18:56:42 +01:00
Joona Kiiski
b839ea6c0c Hack to fix GCC/ICC rounding difference
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-25 18:54:33 +01:00
Marco Costalba
726df58131 Stockfish 1.8 beta 1
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-24 18:00:14 +01:00
Marco Costalba
d9a8dd0f7a Revert "Do IID also when we already have a ttMove"
Joona's testing reports very bad results at 5s, 30s and
even 1 minute TC, so revert.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-24 18:00:03 +01:00
Marco Costalba
6776f76d20 Call apply_weight() for both colors in one go
Due to rounding errors in apply_weight() where we divide
by 0x100 it is not possible to keep some functionality.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-24 17:53:01 +01:00
Marco Costalba
74db0f0f40 Tweak unstoppable pawns detection
A pawn is unstoppable also if enemy king can reach it
but path to queening is protected.

Original idea by Ralph Stoesser fixed by me.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-24 17:52:56 +01:00
Marco Costalba
a010d438a2 Merge branch 'master' of free2.projectlocker.com:sf 2010-06-21 20:50:20 +01:00
Tord Romstad
a4988fecee Moved a misplaced #endif in misc.cpp, which broke compilation in
Mac OS X.

No functional change.
2010-06-21 11:25:06 +02:00
Marco Costalba
dc5caff638 Test killer for legality earlier
Many killers moves, around 40%, are not legal, so
skip earlier in this case.

Some Movepicker c'tor cleanup while there.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-19 17:27:10 +01:00
Marco Costalba
4e7a898d7e Optimize for king moves in see_sign()
Because we only test legal moves, a king move
cannot have negative SEE.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-19 15:58:14 +01:00
Marco Costalba
47ee6d9fa4 Move prefetch() out of TT
This code is platform specific and has nothing to
do with TT class, so move to misc.cpp

This patch is a prerequisite to use extend prefetch use
also to other hash tables apart from Transposition Table.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-19 11:10:54 +01:00
Marco Costalba
221f41c2df Extend checks only if SEE is non-negative
Idea from Dr. Hyatt

After 10k games at 5"+0 on my QUAD
Mod vs Orig +2750 =4601 -2649 +4 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-15 07:02:09 +01:00
Marco Costalba
a8b9c11f56 Revert "Use ply counter in Position object"
Search ply and game ply are rwo different things !

Revert bogus commit.

No functional change on bench, but it changes in real games
when engine sends all the moves up to current one.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-13 02:38:16 +01:00
Marco Costalba
e9eea87341 Set LSNTime to 100 ms
This is a timeout compatible with very short TC of 5 sec/game.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-12 10:29:50 +01:00
Marco Costalba
a128faf0b0 Remove a wrong FIXME
If we are there it means we already had that info stored in TT,
so we don't need to overwrite with the same content !

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-06 00:17:33 +01:00
Marco Costalba
ed2754227a Avoid a double copy when saving a TTEntry
In statement:

*tte = TTEntry(posKey32, v, t, d, m, generation, statV, kingD);

We first create a TTEntry, then we copy the temporary entry to
its final destination in *tte then we discard the TTEntry.

Instead of this assign the fields directly to the destination TTEntry.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-05 12:35:44 +01:00
Marco Costalba
287b46aa63 Avoid calling evaluate() while razoring
Micro optimization that gives a 0.5% speed improvment

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-05 09:42:16 +02:00
Marco Costalba
a04dcce628 Offset pv[] always from 0
We don't need to offset from current ply.

Also rewritten a bit update_pv()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-04 19:41:41 +01:00
Marco Costalba
452f0d1696 Big qsearch() cleanup
It is more clear and should be a bit faster too.

Reverted also previous optimization patch because
seems do not increase actual speed.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-03 19:15:44 +01:00
Marco Costalba
9337c6da46 Extend intermediate LMR to root search
Almost no change, but it is in sync with what we do in search
and in any case the ELO difference is very small (because the
events when the intermediate research triggers are very rare),
too small to be measured, we just verify we don't have any
unexpected regressions.

After 802 games at 1+0 full QUAD
Mod vs Orig +114 =581 -107 +3 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-03 12:17:05 +01:00
Marco Costalba
5f3c660d5d Shortcut futility pruning in qsearch
If we have pruned one capture due to its final value
we can prune also following ones because captures are
MVV ordered.

Also avoid a compare when not in PV because in that
case is always false.

No functional change.
2010-06-03 12:10:57 +01:00
Marco Costalba
ab127028ed Do not pass threadID as argument of search() and evaluate()
Get it from the position instead.

A good semplification of function calling and a speedup too.

No functional change also with faked split.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-02 20:48:40 +01:00
Marco Costalba
2f6927ac08 Save threadID info in Position
This is the best place because when we split we do a
copy of the position and also threadID, once set in a
given position, never changes anymore.

Forbid use of Position's default and copy c'tor to avoid
nasty bugs in case a position is created without explicitly
setting the threadID.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-02 20:19:43 +01:00
Marco Costalba
f148a8f6cc Don't initialize excludedMove and skipNullMove at each node
Do it once at the beginning becuase they are always reset
after use in the calling place where are set.

No functional change also with faked split.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-02 19:41:45 +01:00
Marco Costalba
c51e12200a Use SearchStack to pass allowNullmove
Also renamed allowNullmove in skipNullMove to reverse
the logic so that the field is initialized to 0 (false)
instead of 1 (true).

No functional change also with faked split.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-02 13:49:48 +01:00
Marco Costalba
5804bef824 Use SearchStack to pass excludedMove
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-02 13:22:48 +01:00
Marco Costalba
2572055c87 Fix white space breakage
No functional change with faked split.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-02 11:25:02 +01:00
Marco Costalba
c6ba14b7c9 Sync sp_search() with main search()
And fix qserahc() dispatch also there.

No functional change tested wit Faked Split.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-02 10:49:34 +01:00
Marco Costalba
5212995563 Retire bitScanReverse32()
Use log() instead because we are not in speed
critical paths.

Also a bit of renaming and code shuffle while there.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-01 21:58:54 +01:00
Marco Costalba
50e094ef8d Retire ok_to_do_nullmove()
Has been remained the same from ages also with the FIXME.

Retire for now and rearrange the conditions order for
maximum performance.

Also a small touch at null zugzwang verification.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-01 20:50:08 +01:00
Marco Costalba
7903495b0a Move invariant of singular ext. check out of loop
It is almost always false.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-01 15:47:28 +01:00
Marco Costalba
a3819188de Rename ok_to_prune() in connected_threat()
It is more up to the point. Also small speedup
due to checking for threat move before calling
the function. This saves more then 90% of function calls.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-01 15:12:31 +01:00
Marco Costalba
c0136fb728 Avoid double function dispatch
In 44% of cases we call search() just to call
qsearch() one moment later, avoid this double dispatch.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-01 14:47:55 +01:00
Marco Costalba
9b17083912 Retire init_node()
Also don't poll in qsearch()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-01 12:34:49 +01:00
Marco Costalba
05c5f08372 Don't init SplitPointStack[i][j].parent
It is already set to zero because is allocated in
the global storage area.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-06-01 07:36:30 +01:00
Marco Costalba
6716337f40 Use ply counter in Position object
And avoid a redundant one passed as argument in
search calls.

Also renamed gamePly in ply to better clarify this
is used as search ply and is set to zero at the
beginning of the search.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-31 22:03:22 +01:00
Marco Costalba
ee8ccac622 Fix SearchStack and ply misalignment in RootMoveList
In RootMoveList c'tor we call qsearch() with
ply == 1 but SearchStack at 0.

We never noticed before because in qsearch we don't access
previous's ply SearchStack, otherwise we would have got
a nice crash ;-)

This bug is a fall down of previous patch.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-31 18:33:43 +01:00
Marco Costalba
e4e12ed595 Convert SearchStack ss[] to SearchStack*
Use a pointer to current SearchStack to avoid ss[ply]
address calculation.

Gives 1% speedup on Intel compiler

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-31 17:36:16 +01:00
Marco Costalba
d81def4fa9 Add function to get ply from position
It will be used by future patches.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-31 12:10:39 +01:00
Marco Costalba
9446dd6da3 Move gamePly among the StateInfo data
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-31 12:09:18 +01:00
Marco Costalba
b7bc0d4c57 Move promotion and ep under pawn handling
And remove from main do_move() flow. Just a small speedup
because we avoid two branches in the common case.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-31 12:08:34 +01:00
Marco Costalba
c35c18a705 Thread::splitPoint is a volatile pointer
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-31 06:16:50 +01:00
Marco Costalba
2ea323aec6 Do IID also when we already have a ttMove
In case tte->depth() is far lower the current depth
and we are in a PV node.

Almost 45% of researches give a different ttMove !

After 999 games at 1+0
Mod vs Orig +174 =694 -131 +15 ELO !!!!!!!

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-31 06:15:39 +01:00
Marco Costalba
ec0f0eba6b If LMR search fails high research at intemediate depth
Do not search immediately at full depth, but try a second
chance at lower depth. This is a feature that should scale
well because become important at high depths where we have
big reductions and also big savings in avoiding a costly
full depth search.

After 942 games at 1+0
Mod vs Orig +158 =645 -139  +7 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-29 23:35:12 +01:00
Marco Costalba
0719470e50 Fix IIDMargin description
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-29 11:19:53 +01:00
Marco Costalba
3ccdb57d6f Retire zobMaterial[]
Use zobrist[] array to compute material key.

Space save of 2KB in L1 cache.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-29 08:54:15 +01:00
Marco Costalba
03cfd94414 Change zobMaterial[] index 0 definition
The index at 0 was reserved for no-pieces
information. But we don't need that.

This is a prerequisite for next patch.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-29 08:49:16 +01:00
Marco Costalba
8c32878701 Use Key type instead of Bitboard
They are both 64 bits unsigned integer, but it
is correct to use the proper type.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-29 08:11:36 +01:00
Marco Costalba
0c5e89e3e1 Revert non-linear threats evaluation
After 999 games at 1+0
Mod vs Orig +148 =712 -139 +3 ELO

The added complexity doesn't seems to pay off and could
even scale worst with longer TC. So revert.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-23 14:53:04 +01:00
Marco Costalba
4a081280ed Remove an useless assert in evaluate_passed_pawns()
The tested square comes from a bitboard anded with
pos.pieces_of_color(Us), so assert is useless.

Another nitpick report by Marek Kwiatkowski  ;-)

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-22 19:14:19 +01:00
Marco Costalba
ee9e162dd5 Account for double pawn push in evaluate_unstoppable_pawns()
One of the most nitpicking patches I have ever seen.

Of course almost no functional change, but added just
becasue we are very pedantic ;-)

Spotted by Marek Kwiatkowski

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-22 18:42:00 +01:00
Marco Costalba
7e82f793b8 Fix StormOpenFileBonus[] bug
It was erroneusly reversed. Bug from Glaurung times.
Probably a full re-tuning is needed anyhow.

Spotted and fixed by Ralph Stoesser.

After 999 games almost no change, but modified anyway
for documentation reasons.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-22 18:35:00 +01:00
Marco Costalba
a7bfaede91 Fix a warning on array of size 0 under Windows
And better document new reality.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-22 12:45:05 +01:00
Joona Kiiski
1afbe1a1d7 Drop completely illogical ei.kingDanger == 0 requirement
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-22 12:37:19 +01:00
Joona Kiiski
226bd54064 Always save static value and kingDanger to TT
Around 5% speed-up

No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-22 12:37:11 +01:00
Joona Kiiski
de0c9e84ca Drop TTClusterSize from 5 to 4
Very small obvious functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-22 12:37:02 +01:00
Marco Costalba
66b751713e Add non-linear threats evaluation
Increase threats score according to the number of
threats and to the side to move.

Constants have been balanced after ~34k iterations.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-22 12:01:51 +01:00
Marco Costalba
ecc100d1bb Revert "Simple implementation of strong YBWC"
It does not seem to increase anything even with a QUAD,
so revert.

After 1000 games with a QUAD
Mod - Orig: 500 - 497 (+1 elo)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-22 11:36:51 +01:00
Joona Kiiski
85559cc597 Add some automatic detection for Windows
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-21 23:09:53 +01:00
Joona Kiiski
187451294f Documentation fix
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-21 06:56:57 +01:00
Joona Kiiski
ac4c971e06 Correct 'prefetch' handling for Makefile
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-21 06:56:48 +01:00
Marco Costalba
cab8b78846 Let prefetch to be enabled by default on Windows
When compiling with MSVC we don't use the Makefile
so tweak a bit the Makefile to allow to let prefetch
in by default so that it works under Windows.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-20 21:37:37 +01:00
Joona Kiiski
efdd1e697a Small tweaks to install gcc-profile-clean targets
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-20 21:23:00 +01:00
Joona Kiiski
09884756d8 Modify source to follow new Makefile
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-20 21:22:51 +01:00
Joona Kiiski
32590884df Rewrite Makefile
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-20 21:22:42 +01:00
Marco Costalba
977cd9520a Simple implementation of strong YBWC
No gain in the worst case of 2 threads, but also no
loss and good potential for QUAD or OCTAL machines.

After 922 games at 1+0 with 2 threads

Mod vs Orig +143 =533 -143 +0 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-20 21:17:47 +01:00
Marco Costalba
471e745a91 Remove an assert in evaluate_passed_pawns()
We already tested few lines before with:

assert(pos.pawn_is_passed(Us, s));

Spotted by Marek Kwiatkowski.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-20 17:48:55 +01:00
Marco Costalba
8dc4396477 Indentation fix in middle-game evaluation
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-17 17:32:31 +01:00
Marco Costalba
6181e01c2a Introduce init_attack_tables() in evaluate()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-17 06:45:59 +01:00
Marco Costalba
0d207ec2c6 Do not consider discovered checks in king safety
Does not help and it slows downs a bit because it
is not cheap to get the possible discovered checks
out of a position.

After 997 games at 1+0
Mod vs orig +153 =692 -152  +0 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-16 15:37:42 +01:00
Marco Costalba
93f64577c3 Fix RootMove::operator<() description
Reported by Melvin Sprague.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-16 08:56:58 +01:00
Marco Costalba
8b6bcd9731 Remove an useless Max() in passed pawns evaluation
There is no reason for that since tr cannot become negative.

Spotted by Ralph Stoesser.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-16 00:56:05 +01:00
Marco Costalba
6c0b2f5003 Threath tuning results
Final values for threath tuning (after ~30k iterations)

Verified to be equivalent with tuning branch.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-15 21:44:57 +01:00
Marco Costalba
52fd1a3d37 Add support for gcc-profile
It's now possible to build PGO builds with GCC

Patch from Oystein Johansen

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-15 07:51:46 +02:00
Marco Costalba
0c9c5032e8 Rename OutpostMask[] in AttackSpanMask[]
This is a more standard naming (see chessprogramming wiki)
and is more stick to what table is and not what is used for.

Code in pawns.cpp is a bit more readable now, at least for me ;-)

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-14 16:55:35 +01:00
Marco Costalba
9079bab84c Micro optimization in evaluate_pawns()
Avoid a double bitcount in test for candidate passed
pawn when we don't have any supporting pawn.

Also use outpost_mask() instead of build it up on
the fly.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-14 12:59:03 +01:00
Marco Costalba
ea5af9b8c0 Introduce evaluate_pawn_storm() to unify redundant code
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-14 12:08:48 +01:00
Marco Costalba
0b49ec9822 Code style tweaks to pawns.cpp
Also a small speedup.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-14 12:05:17 +01:00
Marco Costalba
6c27bf1880 Change color argument of square_is_weak()
Pass the color for which the square is to be
considered weak, not the opposite.

It is more natural and intuitive in this way.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-14 11:59:25 +01:00
Marco Costalba
da1165ae5d Space inflate marsenne
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-13 21:53:56 +01:00
Marco Costalba
6e5bb3279f Another split() tweak session
Function split() doesn't need to return a value, also
remove useless 'master' field.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-13 21:53:55 +01:00
Joona Kiiski
e63ab4bd03 Document old test result
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-12 17:33:56 +01:00
Joona Kiiski
d72e862a5b Remove one hack caused by misunderstanding
No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-12 17:33:42 +01:00
Marco Costalba
02fe05cd0d Fix a possible out of range access in previous patch
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-12 12:30:00 +01:00
Marco Costalba
16d6faf479 Retire splitPoint->cpus field
It is redundant with splitPoint->slaves[].

Also move slaves[MAX_THREADS] among the shared data in
SplitPoint definition as it should have been already.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-12 12:17:01 +01:00
Marco Costalba
2cec7347db Syncing sp_search() and search()
Small twekas to make the two searches as similar as
possible.

Also removed an useless setting of mateKiller in sp_search()

No functional change (tested with FakeSplit)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-12 07:01:50 +01:00
Marco Costalba
1288a5a10a Simplify init_safety()
In this for is also ready to be tuned....to be continued ;-)

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-11 12:03:32 +01:00
Marco Costalba
7f095b0a36 Greatly simplify weight_option()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-11 11:59:50 +01:00
Marco Costalba
2aa455ce95 Small evaluate_passed_pawns() cleanup
Mainly renamed local variables with sensible names.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-11 07:06:48 +01:00
Marco Costalba
c053f0b838 Better integration of faked split
We don't need to comment/uncomment code, just
set FakeSplit bool to true to enable faked split.

Also reintroduced some asserts and cleaned up a bit.

Tested that with FakeSplit = true we have reproducible
finger printing even in SMP.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-11 07:05:31 +01:00
Joona Kiiski
7abe5f12ef Disable fake-mode
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-11 07:05:30 +01:00
Joona Kiiski
253428bb3f Unite sp_search() and sp_search_pv()
Also introduce a new rule:
In sp_search() always must hold: sp->alpha < sp->beta
Should fix some rear but very nasty races

To keep everything in sync, search() is also modified to
obey this rule. Because this affects only PV-nodes, should
have zero meaning to speed.

No functional change in fake mode

Regression test after 854 games
Mod vs Orig 433 - 421, no crashes.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-11 07:05:17 +01:00
Joona Kiiski
36f4fe52f0 Introduce fake-mode for split
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-09 23:06:13 +01:00
Marco Costalba
e4ad6a38ee Revert to old prefetch detection logic
It was broken on Windows 64bit with MSVC and possibly
on other platforms, so revert to old proven one.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-09 13:05:21 +01:00
Marco Costalba
6c6b6cd1a4 Fix an off-by-one bug in ThreatBonus[] table
We need a retuning anyhow.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-09 11:30:50 +02:00
Joona Kiiski
c20a41c9cf Templatize qsearch
No functional change and 2% speed-up on GCC.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-08 23:32:31 +01:00
Marco Costalba
e0e4bdc991 Retire mate threat detection from evaluation
Remove a lot of complex, obscure and useless code.

After 999 games at 1+0
Mod vs Orig +162 =673 -164 -1 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-08 23:09:40 +01:00
Marco Costalba
35e39a196d Add a comment and a FIXME
And fix indentation too.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-08 13:36:44 +01:00
Marco Costalba
276513c19f Lookup TT for eval also in PV nodes
We don't need to evaluate the position if it
is already cached in TT. We already do this
in non-PV case.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-08 13:12:46 +01:00
Marco Costalba
9643d7524e Fix an obsoleted descrption comment
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-08 13:06:55 +01:00
Marco Costalba
b763b40101 Unify Internal iterative deepening
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-08 13:00:07 +01:00
Marco Costalba
b4870595a5 Templetize extension() function
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-08 12:41:36 +01:00
Marco Costalba
f010685136 Templetize reduction() functions
No functional or speed change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-08 12:26:34 +01:00
Marco Costalba
91ce930b28 Use enum NodeType instead of opaque true/false
Increase readibility.

No functional and speed change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-08 11:49:55 +01:00
Joona Kiiski
b075d8ca53 Unite search_pv() and search()
A lot of redundant code removed: -182 lines of code

No functional and speed change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-08 11:48:45 +01:00
Marco Costalba
c0334c7bac Rename AttackWeight[] in KingAttackWeights[]
Also simplify a bit the code removing useless
named constants.

No functional change.
2010-05-07 12:04:23 +01:00
Marco Costalba
0f712ad4fd Array ThreatBonus[] is initialized at zero by compiler
We don't need to do the job.

No functional change.
2010-05-07 12:04:23 +01:00
Marco Costalba
7488d216fd Properly indent evaluate_king()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-07 12:04:22 +01:00
Marco Costalba
b95b1a9705 Rename futilityMargin in kingDanger in EvalInfo
This is what actually is.

A standard naming convention suggests to name a variable
with someting resembling _what_ the variable is and not
_how_ the variable is used. This normally results
in easier to read code.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-07 12:04:22 +01:00
Marco Costalba
b14846b6d7 Simplify some obsolete code in king safety
Now that QueenCheckBonus and friends are always > 0
we can remove a bunch of useless 'if' statements.

No functional change.
2010-05-07 12:04:21 +01:00
Marco Costalba
921bd87280 Rename king "safety" to king "danger"
A bigger "safety" value is actually a bigger
threat for the king, so it is a bigger "danger"

With this renaming "Cowardice" and "Aggressiveness"
UCI parameters become easier to understand.

It is also easier to understand why the once "safety"
value (that is a "danger") is subtracted from evaluation
instead of being added.

No functional change.
2010-05-07 12:04:21 +01:00
Marco Costalba
569bc75eb8 Evaluation weights cleanup
Use a Weights[] array instead of named variables to
store evaluation weights.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-07 12:04:20 +01:00
Marco Costalba
0544d6c8f7 Set Mate Threat Extension to OnePly
For both PV and non-PV nodes.

After 981 games at 1+0
Mod vs Orig +153 =686 -142 +4 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-07 12:04:08 +01:00
Marco Costalba
fe76787a77 Avoid a call to apply_weight() in evaluate_king()
Precompute scores in SafetyTable[] instead of calculate
them on the fly.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-05 13:56:54 +02:00
Joona Kiiski
8e269d781a Further push the LMR pedal
More aggressive LMR reductions.

Tested at different time controls:

- Tested with 1CPU 1+0, after 3000 games, result was +12 ELO

- Tested this with 4CPU 1+0 and got sth around 5-10 ELO increase

- Last one at long time control,after ~1000 games with 10+0 result is:

Orig - Mod: 491 - 520 (+10 elo)

A testing marathon by Joona for this important change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-05 12:20:39 +01:00
Marco Costalba
df7cd94aee A promotion piece cannot be a king or a pawn
Or any other garbage value bigger then QUEEN.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-05 12:16:16 +01:00
Marco Costalba
f16c231bc9 Do not return from idle_loop() with lock held
Master thread returns from idle_loop() when sp->cpus == 0,
but cpus is decremented by slave threads under sp->lock,
so it could happen that we return in split(), where we release
the split point, with sp->lock still held.

This patch guarantees that sp->lock is released when returning
to split().

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-05 12:16:12 +01:00
Marco Costalba
b89733b46c Reverse the logic used to detect prefetch
Explicitly search for x86 architecture instead of
excluding the others.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-05 12:16:10 +01:00
Marco Costalba
67f611f3eb Allow a static evaluation to overwrite an exsisting entry
The idea here is that if we cut-off after a stand pat the
already exsisting TT entry was not usable with current
beta, so overwrite anyway.

After 999 games at 1+0
Mod vs Orig +173 =665 -161  + 4 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-05 12:15:40 +01:00
Marco Costalba
80f5ca88f6 Do not refresh TT in qsearch
Almost no change and simplifies a bit the code.

After 961 games at 1+0
Mod vs Orig +156 =650 -146  +4 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-02 07:50:19 +01:00
Marco Costalba
8425b2b499 Refresh TT entry after a cut-off to avoid aging
Re-save the same TT entry if value is usable and allow
us to cut-off, it means that entry is valuable and
we want to keep it fresh updating the 'generation'
parameter up to the current value.

Patch suggested by J. Wesley Cleveland and better
clarified by Miguel A. Ballicora.

After 999 games at 1+0 64MB hash size
Mod vs Orig +167 =677 -155 +4 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-05-01 05:09:55 +01:00
Joona Kiiski
a086f34f36 Fix compile error on GCC
Add missing prototype.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-28 12:01:00 +02:00
Marco Costalba
83631c89ce Endgame's apply() method can be 'const'
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-27 06:17:32 +01:00
Marco Costalba
bedf80a4c0 Remove an obsolete comment
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-27 06:09:04 +01:00
Marco Costalba
cb9399445f Another small material tweak
In this case we avoid to name the 'black' version of the
endgame function but use a vector indexed by color instead.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-26 18:45:28 +01:00
Marco Costalba
fe7e0a425e Cleanup material distribution detectors
No functional change (verified each function)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-26 12:21:22 +01:00
Marco Costalba
fb0e19dc8b Do not call exit_threads() in Application d'tor
Because exit_threads() references the global object TM, we
need to call the function when still inside main(), otherwise,
due to undefined global object initialization and destruction
we could end up with referencing an already destroyed object.

Actually this should not happen because Application singleton
is initialized _only_ after all the other globals due to how
Application::initialize() is defined, but this is very tricky
C++ and not easy to follow, even for me ;-)

Also rearranged a bit main() code flow.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-25 10:35:55 +01:00
Marco Costalba
e6b5d03cc4 Small passed pawns evaluation cleanup
Moved evaluation of unstoppable pawns out of
evauation of passed pawns because event frequency is
much lower. Added evaluate_unstoppable_pawns() that
is called very seldom and contains all the unstoppable
pawn logic.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-25 09:50:27 +01:00
Marco Costalba
b2c1e15698 Simplify a bit futility marging formula
Should be a very minor change, but there is a small
functional change because futility_margin() is used in more
places then in the pruning formula.

After 999 games at 1+0
Mod vs Orig +167 =678 -154  +5 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-23 18:52:22 +01:00
Marco Costalba
11207f7c1f Revert scale factor in pawn evaluation
It simply doesn't seems to work both in direct matches
and in balance tuning.

So revert the idea.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-21 20:35:47 +01:00
Marco Costalba
97f5d19bdc Introduce PawnsQtyTable[] to refine pawn's drawish calculation
Also fix dimension of UnpairedPawnsTable[] to accomodate the
case in which we have 8 unpaired pawns, i.e. only one side has
pawns, the other side has no pawns.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-19 12:24:26 +01:00
Marco Costalba
fc89dbcab2 First attempt at tweaking UnpairedPawnsTable[] values
Values by Joona.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-19 06:37:07 +01:00
Marco Costalba
6b7efa0cd1 Introduce scale factor in pawn evaluation
The idea is to reduce the score if we have many
pawns opposing an enemy pawn so that the draw
possibility increases.

Just introduced the logic, but no functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-19 06:21:13 +01:00
Marco Costalba
c23cd4d90a Fix candidate passed pawn definition
A pawn is candidate to be passed if doesn't have enemy pawns
in just front of him, not also behind !

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-18 10:09:12 +01:00
Marco Costalba
a9fa1fc7f7 Retire Position::pawn_is_passed() and friends
Absolutely no useful at all, just code obfuscation so
use real definition instead.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-18 09:58:57 +01:00
Marco Costalba
1f1ef0897c Introduce table SquaresInFrontMask[2][64]
It will be used to lookup squares in front of
a given square. Same concept of PassedPawnMask[]
and OutpostMask[].

Also small tweaks in bitboard.h

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-18 09:47:31 +01:00
Marco Costalba
a49e4fac98 Better perft integration in benchmark
Now with:

   stockfish bench 128 1 5 default perft

it is possible to get perft 5 results of each position and
the first 3 positions correspond to the well known test
position in:

http://chessprogramming.wikispaces.com/Perft+Results

This allow to quickly check for perft consistency running
the 'bench' command.

No functional change but signature has changed because
bench default positions 2 and 3 have changed.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-18 09:18:49 +01:00
Marco Costalba
87379c2929 Space inflate bitboard.cpp
This file, somehow, avoided the "space inflate" treatment...until now ;-)

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-18 08:58:26 +01:00
Marco Costalba
53b522d95d Convert polyglot.ini to use Linux line ending
Instead of Windows cr/lf

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-17 11:24:25 +01:00
Marco Costalba
ef0bbe6e18 Teach polyglot the new "Best Book Move" UCI option
Also turn off log by default as is in UCI case.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-17 11:22:40 +01:00
Marco Costalba
65c2715d9a Revert saving of null search value in TT
Revert all the patches that introduced the change and
more or less fixed the zugzwang issue.

There is a gain against last current version and we
can remove a lot of code.

After 979 games at 1+0 on my QUAD
Mod vs Orig +152 =688 -139 +5 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-17 10:57:37 +01:00
Marco Costalba
ec0a650dff Don't overwrite exsisting TT with null search value
Real search is considered of higher quality then null
search one.

This allows to fix the zugzwang issue with a minimal
impact on ELO.

Zugzwang verified on position:

8/7P/8/8/K2b4/p7/1k6/1B6 b - -

After 999 games at 1+0 on my QUAD
Mod vs Orig(94bb196) +168 =657 -174  -2 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-16 05:52:18 +01:00
Joona Kiiski
abae3c5678 Prevent the use of nullmove TT value only at verification search
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-16 05:47:31 +01:00
Joona Kiiski
f3809f2a18 Introduce NullStatus enum
No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-16 05:47:29 +01:00
Joona Kiiski
81ae7cad2d Revert "Introduce "Zugzwang detection" temporary hack for 1.7.1"
This reverts commit f9d3b48ad0.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-16 05:47:28 +01:00
Marco Costalba
94bb1964f6 Add "Best Book Move" UCI option
Is a boolean option that when set allows Stockfish
to select the best book move across the possible ones.

Feature requested by Salvo Spitaleri.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-16 05:45:30 +01:00
Joona Kiiski
13431922a3 Fix overflow in init_safety
Also write the code in more clean way

No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-14 19:19:11 +01:00
Joona Kiiski
9a3fc4d3fb Fix evasion pruning condition
Avoid incorrect mate scores in positions like

BK5/1R4b1/2k1Np2/3p3b/2p3pq/p1rB4/n2n1p2/8 w - -

Thanks for Jouni Uski for reporting the problem

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-13 20:28:49 +01:00
Marco Costalba
a4a0ffce71 Fix some warnings under +w1 HP-UX compile
This is the world's fussiest compiler with +w1

Warnings reported by Richard Lloyd.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-11 17:03:03 +01:00
Marco Costalba
e81108a855 Restore development version
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-10 20:42:31 +01:00
Marco Costalba
f967f1a25e Update polyglot.ini
Remove obsolete options and add a few ones.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-10 20:41:10 +01:00
Marco Costalba
86c2d2fc3b Stockfish 1.7.1
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-10 16:48:25 +01:00
Marco Costalba
f9d3b48ad0 Introduce "Zugzwang detection" temporary hack for 1.7.1
Add an UCI option "Zugzwang detection" OFF by default that
enables correct detection of zugzwang.

This is just to let 1.7.1 be 100% compatible with 1.7 and
should be removed after release.

Verified 100% functional equivalent to 1.7

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-10 16:41:40 +01:00
Marco Costalba
d720778b2b Revert HT detection
Fall back on 1.6.3 behaviour.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-10 11:35:30 +01:00
Marco Costalba
e2880f9b8e Revert last patch
It fails in test position:

8/7P/8/8/K2b4/p7/1k6/1B6 b - -

Not clear why but we revert because it fixes the issue.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-10 11:16:55 +01:00
Marco Costalba
909e3adede Relax TT condition for zugzwang verified null values
In this case use a normal VALUE_TYPE_LOWER TT type instead of
VALUE_TYPE_NS_LO. This allow us to TT cut-off in a bit more nodes.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-10 10:48:08 +01:00
Marco Costalba
626b1f8c6a Avoid TT cutoffs at root of null zugzwang verification
This patch fixes an issue with zugzwang well explained by Tord:

"Assume that a zugzwang position occurs at iteration N,
at a search depth d, with d < 6*OnePly. The null move search
fails high, and no verification search is done, because the
depth is too small. The position gets stored in the transposition
table with a good score and a depth of d.

Now, consider what happens when the same position occurs at iteration
N+1, this time with a depth of d+OnePly (i.e. one ply deeper than at
the previous iteration). Once again, the null move search fails
high. The point is that the verification search will also fail high,
because of an instant transposition table cutoff caused by the value
stored in the TT during the previous iteration."

With this patch we simply do not allow TT cutoffs at the root node
of a null move verification search if the TT value was found by a
null search.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-10 10:35:29 +01:00
Marco Costalba
06a350f1ae Use a flag in TT to track null search values
Add VALUE_TYPE_NS_LO to enum ValueType and use it when
saving in TT a value from a null search.

Currently no action is performed, the next patch will enable
the new type.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-10 10:07:53 +01:00
Marco Costalba
a9e9746495 Fix a warning under HP-UX ANSI C++
Reported warning is:

warning #2514-D: pointless comparison of unsigned
                 integer with a negative constant

Spotted by Richard Lloyd.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-09 07:54:00 +01:00
Marco Costalba
a7fcdfd6bf Stockfish 1.7
Signatures are:

./stockfish bench 128 1 12 default depth
8299338

./stockfish bench 128 1 13 default depth
15694903

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-07 13:08:50 +02:00
Tord Romstad
41816b7ced Fix PowerPC and ARM compatibility. 2010-04-06 10:19:09 +02:00
Tord Romstad
13224e1d9d Add -mdynamic-no-pic to CFLAGS when compiling with GCC under OS X.
Without this flag, the __cpuid() function doesn't compile correctly
in 32-bit mode.
2010-04-05 21:47:28 +02:00
Marco Costalba
10c1ae8da0 Fix one gcc 4.4 warning
Properly fix previous warning. Patch from Joona.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-05 20:11:41 +01:00
Marco Costalba
3a62738174 Fix a warning in HT_enabled()
Under gcc we have:

warning: dereferencing type-punned pointer will break
strict-aliasing rules

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-05 15:36:06 +01:00
Marco Costalba
84451191f3 Store score in TT when null search fails high
Use full depth, not reduced one. This allows
to avoid to do a null search when in the same
position and at the same or bigger depth the
null search failed high.

A very small increase, if any.

After 963 games at 1+0
Mod vs Orig: +158 =657 -147  +4 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-04 11:23:18 +01:00
Marco Costalba
2ed3358faf Cleanup pawn storm code
In this form it is even more evident we have some
issue there to be fixed sooner then later....

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-02 11:51:39 +01:00
Marco Costalba
08634b06a3 Fix a comment in evaluate.cpp
Function name is wrong.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-04-02 11:45:12 +01:00
Marco Costalba
0e33fc6fd4 Change poll() signature
After previous patch we don't need any more the call parameters.

This fixes a couple of warnings under MSVC.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-31 06:43:12 +01:00
Tord Romstad
a5a8830e97 Remove several unnecessary UCI options: All king safety options
except "Aggressiveness" and "Cowardice", and "UCI_ShowCurrLine".
No functional change compared to the previous version with the
default settings.
2010-03-30 15:15:01 +02:00
Marco Costalba
2a14123550 Revert LMR reduction based on thinking time
After 500 games at 5+0 on my QUAD (3 days) there
is no difference with old version, so probably it
is a feature that doesn't scale with search depth.

So revert for now, perhaps we should readd under a
different form.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-28 12:04:41 +01:00
Marco Costalba
8fabd69d4a Small comments tweaks in search.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-28 11:53:30 +01:00
Marco Costalba
1fc88071d1 Sync static null conditions with real one
Almost no functional change, but it seems more
in line with the meaning of static null pruning.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-28 11:53:16 +01:00
Marco Costalba
7dca461927 Silence a couple of warnings
MSVC complains about an implicit conversion from double to int.

Also small comments tweaks.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-23 23:34:31 +01:00
Joona Kiiski
7618ee2df1 Vary reduction aggressiveness as a function of thinking time
In the beginning use milder reduction and at the end be
more aggressive.

After 1500 games on Joona's QUAD
Mod - Orig: 791 - 720 +16 elo

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-23 23:29:23 +01:00
Joona Kiiski
661d48c27b Base work for different reduction schemes
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-23 23:25:58 +01:00
Joona Kiiski
42de93ac15 Do not return unproven mate scores from null move search
Causes very small functional change which is not observable with
our usual set of test positions.

However change is observable fx. with following position:
4k3/3r4/5Q2/6K1/8/8/8/8 w - - 0 1
go depth 24

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-22 07:27:05 +01:00
Marco Costalba
426f55b78d Use fail soft in null search
If null search fails high return null value instead of beta.

With TT hash there may be a small advantage for fail-soft since
storing slightly better bounds may cause slightly more hash hits.

After 990 games at 1+0
Mod vs Orig +171 =665 -154  +6 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-21 15:12:44 +01:00
Marco Costalba
b638f6b035 Remove castleRightsMask[] hack
Array castleRightsMask[] is not static because it can
be different for different positions, so let it be
a Position member data. This allows to remove tricky
hacks to take in account that although it was defined
static it could change.

Theoretically now copying a position is a bit slower because
we need to copy also an array of 64 integers, but because in
split() we don't copy the position anymore, but just keep the
pointer, the added burden is not mesurable even in MP case.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-20 11:59:22 +01:00
Marco Costalba
3de0bc43a2 Retire Position::fast_copy()
It is never used and could be tricky, so remove it.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-20 11:45:04 +01:00
Marco Costalba
9fc602bae7 Updated copyright year to 2010
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-20 11:27:07 +01:00
Marco Costalba
49c50399fe Fix POPCNT detection gcc compile error
Also don't use __cpuid() intrinsic for Intel under
Linux because gives wrong results when detecting HT,
use the gcc version instead. Finally clean up the code.

Error was due to changed __cpuid() signature for
gcc compiler.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-17 21:04:56 +01:00
Marco Costalba
a4551c59e0 Fix __cpuid() compile error with gcc
Use same __cpuid() signature used under Windows.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-17 13:22:28 +01:00
Marco Costalba
c853b87c08 Add hyper-threading detection
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-14 12:52:58 +01:00
Marco Costalba
92bada1a32 Move __cpuid() definition for gcc in types.h
This will allow to use the function also for other
purposes then detecting POPCNT.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-14 12:52:56 +01:00
Marco Costalba
eaed535c5f Introduce captured_piece()
It will be used by future patches and also rearranges some
half cooked code that mistakenly ended up in master in the
past.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-13 11:07:10 +01:00
Marco Costalba
49dfc50b12 Reduce increase progression of aspiration window
Currently, in case of fail high/low we research with
a window increased by 2*AspirationDelta at first
attempt, this patch instead makes the research be
done with an increase of just AspirationDelta size,
in case of a consecutive fail we will widen to
2*AspirationDelta and so on.

After Joona's test:
Orig - Mod: 850 - 890

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-13 11:05:27 +01:00
Marco Costalba
c835ee8853 Use separated research counters in root_search()
One for failing highs and one for failing lows, this
should reduce average window size in case of positions
that fail first high and then low (or the contrary).

After ~2000 games on Joona's quad we have:

Mod - Orig: 1012- 975 (+6 elo)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-13 11:00:12 +01:00
Marco Costalba
7ff9678651 Group time management globals initialization
Instead to leave uninitialized or scattered in the code
as is the case for ExtraSearchTime.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-13 10:59:03 +01:00
Marco Costalba
4ef068a506 Highlight that alpha and beta could change in root_search()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-06 18:17:04 +01:00
Marco Costalba
f23a9e8f88 Fix a comment and add an assert in root_search()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-06 17:51:56 +01:00
Marco Costalba
cc2a249952 Retire RootMoveNumber and use FirstRootMove instead
It is more clear why we use that global flag.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-06 17:34:36 +01:00
Joona Kiiski
55f0d6377f Save mateThreat flag in splitPoint and make use of it
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-06 12:18:03 +01:00
Joona Kiiski
aeb664e0ea Document one test result
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-06 12:17:41 +01:00
Joona Kiiski
8abdb131c8 Synchronize root_search() with other search routines
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-06 12:14:46 +01:00
Joona Kiiski
43c93cb151 Remove obsolete code snippet from root_search
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-06 12:07:37 +01:00
Marco Costalba
8d1d9f7181 Sort again root moves after a fail low
Currently we use original sorting after a fail low to
research at wider window. This patch instead sorts the
moves according to the last available move's scores.

Strangely no functional change, but should be.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-06 11:43:31 +01:00
Marco Costalba
a303bde26c Additional search.cpp cleanup
Changed FutilityMarginsMatrix dimensions to be a power of two
so that compiler can produce a faster accessing code.

Introduced print_pv_info() to remove some redundant code in
root_search()

Remaining stuff is triviality and documentation tweaks.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-03-06 11:14:38 +01:00
Marco Costalba
0f50f10327 Destroy all locks before to exit
And use platform-independent functions
where possible.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-28 23:36:02 +01:00
Marco Costalba
8286e6ded2 We don't need lpThreadId parameter in CreateThread()
Under Windows we use CreateThread() to setup threads and
we pass a pointer to a variable that receives the thread
identifier, but this parameter is optional and we don't
use it, so remove it.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-28 23:36:01 +01:00
Marco Costalba
3a558a3d8b Function init_thread() should return an integer under Windows
It happens that NULL is 0, but the conventional meaning is of
a zero pointer, so repleace with an explicit 0 integer value.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-28 23:36:01 +01:00
Marco Costalba
14dbeb22dd Try bad captures before non-captures
Consider sligtly negative captures as good if at low
depth and far from beta.

After 999 games at 1+0
Mod vs Orig +169 =694 -136  +11 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-28 23:35:51 +01:00
Marco Costalba
68eb7e77f1 Revert previous patch
It raises an assert under Windows, it is not clear why but it
happens that idle_loop() is called with incorrect threadID and
the assert triggered is:

assert(threadID >= 0 && threadID < MAX_THREADS);

So revert the patch for now, but we should understand why it
fails.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-27 17:24:58 +01:00
Marco Costalba
57340c109b Do not wait for sleeping in init_threads()
We can't do it with full guarantee anyway because
there is always a possible race between the setting of
state to THREAD_SLEEPING and actual sleeping.

So just remove the not perfect code to avoid misunderstandings.
This reflects what we have done in wake_sleeping_threads() in
the previous patch.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-27 13:26:04 +01:00
Marco Costalba
111aa44662 Remove an incorrect assert in wake_sleeping_threads()
Currently there is no guarantee that threads are sleeping
when calling wake_sleeping_threads() because put_threads_to_sleep()
returns without waiting for threads to actually sleep.

Assert can be easily triggered calling put_threads_to_sleep() and
wake_sleeping_threads() in a tight loop.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-27 12:01:07 +01:00
Joona Kiiski
29fb389760 Add some commentary
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-26 00:43:19 +01:00
Joona Kiiski
0d292d1a2d Clean up common adjustments
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-26 00:41:40 +01:00
Joona Kiiski
5bb9da9287 Remove "Threat Depth" ucioption
This option likely has very low meaning for playing strength and style,
so I see no need to keep this configurable

No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-26 00:41:31 +01:00
Joona Kiiski
34c7f1387d Cleanup steps 12, 14
No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-26 00:39:08 +01:00
Joona Kiiski
fc23466236 Clean up step 11
No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-26 00:38:34 +01:00
Joona Kiiski
01b228b5e1 Clean steps 8 and 9.
No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-26 00:37:56 +01:00
Joona Kiiski
2142be7d7f Clean razoring code (step 6)
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-26 00:37:09 +01:00
Joona Kiiski
3888d14bd4 Synchronize variable listing of 4 different search routines
search() is used as a "leading star" and other routines
are modified according to it.

No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-26 00:36:29 +01:00
Joona Kiiski
7bcd97933a Remove current line printing in SMP mode
Was broken and fixing would be too messy.
Now this option is only activated in single thread mode

No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-26 00:35:35 +01:00
Joona Kiiski
9d4abbc6eb Synchronize sp_search() with search() part I
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-25 07:30:19 +01:00
Joona Kiiski
c3b3dcc31a Rename staticValue to refinedValue
Just to avoid misunderstandings.
True staticValue is available through search stack

No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-25 07:30:09 +01:00
Joona Kiiski
e6f2d43b8a Fix repetition detection bug
Bug spotted by Jouni Uski and fix suggested by Pablo Vazquez

Also add note that we are not always handling fifty move rule correctly

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-24 19:56:48 +01:00
Joona Kiiski
1a03f0b0d3 Synchronize sp_search_pv() with search_pv()
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-24 19:42:24 +01:00
Joona Kiiski
62f6d39204 Synchronize sp_search() with search() part II
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-24 19:41:51 +01:00
Joona Kiiski
936cd5b83d Simplify locking in splitpoint search
One rule: Always lock before picking up a move.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-24 19:37:05 +01:00
Joona Kiiski
3c31776a20 Synchronize search_pv() with search take II
No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-24 19:36:21 +01:00
Joona Kiiski
0980f43ab0 Synchronize search_pv() with search take I
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-24 19:34:55 +01:00
Joona Kiiski
9eedc0a463 Search code documentation, take III
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-24 19:30:02 +01:00
Joona Kiiski
195b54c312 Search code documentation take II
No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-24 19:26:05 +01:00
Joona Kiiski
89b4ad6433 Separate razoring from null move
I cannot see connection between the two.

Also add one FIXME for illogical behaviour

No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-24 19:24:10 +01:00
Joona Kiiski
77bb9a94ae Split search() in independent sections
I don't know if enumerating sections is a good idea,
but for me code is more readable this way

No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-24 19:20:26 +01:00
Joona Kiiski
8a78ac84f3 Avoid research in case thread has already been asked to stop
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-24 19:19:52 +01:00
Joona Kiiski
5c944fb3b4 Add one assert
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-24 07:28:50 +01:00
Joona Kiiski
c974d9ef33 Do not wait for threads falling asleep
I cannot see any reason to do this. Even this is not enough to fix
theoretical race case on Windows which doesn't seem to cause any
problems in practice anyhow

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-24 07:27:45 +01:00
Joona Kiiski
12feb5866f Remove unnecessary conditions from if-clauses and replace them with asserts
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-24 07:26:28 +01:00
Joona Kiiski
80810e4951 Fix crash in debug mode
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-23 07:23:03 +01:00
Joona Kiiski
c67b9916f1 Fix some races
Resurrect extra check for sleeping in POSIX code.
This necessary to prevent ugly races between
thread_broadcast and thread_cond_wait.

After thread has woken up, it marks itself as available.
Another thread must not do this, because of possible race.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-23 07:22:56 +01:00
Joona Kiiski
78c6bb1079 Fix one assert
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-23 07:22:49 +01:00
Joona Kiiski
85e60bfc8e Fix compile errors in debug mode
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-23 07:22:42 +01:00
Marco Costalba
79b57dd4ca Document struct SplitPoint fields constness
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-21 16:10:19 +01:00
Marco Costalba
b9537edbb0 Beta is never changed after an sp_search()
So we can use a const value instead of a pointer in
split().

Also pass NULL instead of a faked address of alpha in
case split is called from a non-PV node.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-21 15:32:39 +01:00
Marco Costalba
d38f4f61e7 Supress make warning on missing .depend file
This is generated by make itself, so the warning
is useless.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-21 15:18:35 +01:00
Marco Costalba
27c74c5245 Fix an icc warning
remark #1599: declaration hides variable "i" (declared at line 2651)

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-21 15:07:53 +01:00
Marco Costalba
2f2e8a68d8 Code style triviality in split()
No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-21 14:05:38 +01:00
Marco Costalba
1ea70dd9dd Fix a warning with POPCNT and MSVC
Intrinsic __popcnt64() returns an unsigned __int64, cast
to an integer and silence the warning.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-21 13:44:36 +01:00
Marco Costalba
13c096f839 Revert "Recursive lock"
Joona says that sp_update_pv() does not pass the split point
boundaries, so there is no risk to corrupt data from another
split point. Also the race on thread_should_stop() is harmless
because of this.

So revert the patch and come back to single lock.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-20 23:59:47 +01:00
Marco Costalba
2de2b76896 Remove a couple of useless thread_should_stop() calls
We test for it anyway few lines below and even under lock
protection.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-20 23:48:54 +01:00
Marco Costalba
8b99e94562 Revert small state change optimization in idle_loop()
Joona says:

1. We should not be afraid of "AllThreadsShouldExit" flag.
Because when this is set to true we _must_not_ be searching (= All
splits must have been undone).
And if we are not searching it's impossible that some other thread
could give us work to do. So setting state to THREAD_AVAILABLE
doesn't do any harm. If you want to add check for this, you could do
it like this:

 if (threads[threadID].state == THREAD_WORKISWAITING)
 {
+    assert(!AllThreadsShouldExit)
     threads[threadID].state = THREAD_SEARCHING;

2a. If waitSp->cpus == 0, setting state to THREAD_AVAILABLE makes
no harm either, because helpful master concept dictates that _only_
our own slave can book us. If we don't have any slaves, noone has the
right to book us.

2b. If point (2a) is not correct then your extra check only adds extra race:
In smp code checking for waitSp->cpus > 0 is not enough. It's possible that
our slave immediately exits and another thread
books us as a slave when our state is still
THREAD_AVAILABLE. So instead of adding extra level of security we have
just introduced extra race.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-20 18:36:07 +01:00
Marco Costalba
512a4e4ff0 Recursive lock all split point's chain
When we found a cut-off then lock all the split point chain,
not only current one to avoid races in case two threads running
on different split points where one is ancestor then the other,
find a beta cut-off at the same time, in this case we want only
one to call sp_update_pv().

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-20 18:29:53 +01:00
Marco Costalba
2da290d72b Retire per-thread stopRequest flag
This is a per split-point request, not per-thread. When we find
a beta cut-off in current thread's split point or in or in some
ancestor of the current split point then threads should stop
immediately the search and return to idle_loop().

The check is done by thread_should_stop() that now looks only
at split point's chain.

No functional change and a good semplification.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-20 17:52:09 +01:00
Marco Costalba
b39a24ecca Use state instead of flags to track threads
This is easier to follow and also reduces the points
where state changes to mainly idle_loop() and split().

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-20 16:57:24 +01:00
Marco Costalba
189a005a0b Rename THREAD_MAX in MAX_THREADS
Also rename idle_thread_exists() in available_thread_exists()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-20 13:38:04 +01:00
Joona Kiiski
7c61b8ad2a Search negative SEE moves in qsearch in PV
After 2704 games on slow single core
mod - orig: 1381 - 1323

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-15 19:15:44 +01:00
Joona Kiiski
a093f33154 Use zero null move margin when depth < 4 * OnePly
This is because when we are below 4 * OnePly, the null move
will directly jump to qsearch and if we are below beta,
our opponent is above beta and will get immediate
stand pat cut off.

So basically this patch is just optimizing away useless
evaluation calls. dbg_hit_on() runs show that this heuristic
is correct >99% of cases. Transposition table probably causes
some inaccurary?

After 1148 games on QUAD
mod-orig: 583 - 565 +5 elo

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-15 19:14:41 +01:00
Marco Costalba
0895f1ac71 Fix another setting of a flag out of lock protection
In this case is dangerous because in split() we reset the flag to
false, but if it was set due to a cut-off higher in the tree we
completely miss that and go on with the full search.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-14 16:31:30 +01:00
Marco Costalba
b29198354c Rename flag 'stop' in 'stopRequest'
Instead of other flags this is not a state flag, i.e. does
not defines a state for the thread, but a request because
after we raise 'stopRequest' flag the corresponding thread is
not stopped, but continues to run for a while until it returns
from sp_search() in idle_loop.

It is important the name reflects this.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-14 16:04:53 +01:00
Marco Costalba
40a7ffd53f Reset thread flags to a known state before to exit think()
Among them 'stop' and 'printCurrentLineRequest' could have
random value, so reset to a known state before to leave the
search.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-14 15:59:12 +01:00
Marco Costalba
8eae6a95fb Fix 'stop' flag changed out of lock protection
This is the first nice effect of previous patch !

Because thread_should_stop() should be declared 'const' we
need to remove the setting of 'stop' flag to true that
turns out to be a bug because thread_should_stop() is called
outside from lock protection while 'stop' flag is a volatile
shared variable so cannot be changed when not in lock.

Note that this bugs fires ONLY when we use more then 2 threads,
so commonly only in a QUAD or OCTAL machine.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-14 13:43:26 +01:00
Marco Costalba
2b740f5495 Introduce ThreadsManager class
Main aim of this patch is to consolidate all the thread related stuff
behind a single class interface so to avoid messing with global flags
and having thread code scattered among non-thread related stuff.

Another advantage is that now access to thread's variables is
more controlled, in particular we can differentiate between
read and write accesses by the mean of different interfaces, it
is so simpler to understand how a function is related to threads.

Lastly this rewrite is the base for future code consolidations and
semplifications that are easier now that we have only one thread's
access point.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-14 12:53:27 +01:00
Marco Costalba
fb5ba1d329 Fix compile error under gcc
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-13 13:40:23 +01:00
Marco Costalba
78e494fcbc Ensure function boundaries for threads state changes
Ensure threads are sleeping when leaving init_threads() and
the newly introduced put_threads_to_sleep().

Also ensure threads are not sleeping when leaving
wake_sleeping_threads().

As a side effect we now leave think() with all the threads
(but the main one) guaranteed to sleep. So when we enter
again in think(), after the opponent next move, we know
threads must be sleeping.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-13 12:40:29 +01:00
Marco Costalba
a16415f44d Rename stop_threads() to exit_threads()
More stick to what actually happens.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-13 12:07:13 +01:00
Marco Costalba
8a504d36f9 Be sure threads are woken in wake_sleeping_threads()
Wait inside wake_sleeping_threads() for the threads to be
effectively and reliably woken up.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-13 12:02:34 +01:00
Marco Costalba
093dd8fe88 Use Thread c'tor to properly init the struct
This is what c'tors are for.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-13 11:41:34 +01:00
Marco Costalba
6382324afd Add 'sleeping' flag to struct Thread
Will be used by future patches. Also:

- Renamed Idle in AllThreadsShouldSleep

- Explicitly inited AllThreadsShouldExit and AllThreadsShouldSleep
  in init_thread() instead of use an anonymous global initialization.

- Rewritten idle_loop() while condition to avoid a 'break' statement

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-13 11:28:33 +01:00
Marco Costalba
cb08413dc4 Allow build on HP-UX 11.X
Patch from Richard Lloyd (slightly edited from me), following the list
of changes as described by the author:

src/Makefile:
- Added PREFIX and BINDIR for the install: rule.
- Added a "make hpux" line to the help: rule.
- Added "make test"/"make check" rule that runs the $(PGOBENCH) command.
- "make clean" now additionally removes core and bench.txt.
- Added an hpux: rule.
- Added an install: rule to mkdir $(BINDIR), copy $(EXE) to $(BINDIR) and
 then strip it.
- "make strip" now ensures that $(EXE) is built first before trying to
 strip it.
- Hide errors and output from the g++ command used by the .depend: rule and
 then touch .depend in case g++ isn't available.
- Hide errors from the "include .depend" in case .depend doesn't exist
 (e.g. directly after a "make clean").

src/book.cpp and src/book.h:
- HP-UX's aCC really didn't like the const keywords used for the
 Book::file_name() definitions, so they were removed. I checked that this
 didn't affect a Linux build and it was still fine.

src/misc.cpp:
- HP-UX uses <sys/pstat.h> and pstat_getdynamic() to determine the number of
 CPU cores, so added conditional code for that (if pstat_getdynamic() fails,
 set the number of cores to 1).

src/tt.cpp:
- <xmmintrin.h> and _mm_prefetch() seem highly specific to the Intel x86(_64)
 and gcc platforms - neither exist in HP-UX, so conditionally avoid that
 code in HP-UX's case. Perhaps some sort of define is needed here
 such as -DHAS_MM_PREFETCH that could be #ifdef'ed for instead?

Even after these changes, it's more convenient for HP-UX users to edit the
default: rule in the Makefile to run "$(MAKE) hpux" before they build
stockfish, but that's not a big deal if they're warned about that first (the
same applies to all other builds other than the standard "$(MAKE) gcc" one).

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-12 06:49:16 +01:00
Marco Costalba
711ef615c7 Fix a couple of new MSVC 2010 warnings
Compiler complains because in Book we have a d'tor but not
copy c'tor and assignement operator (warning C4511 and C4512),
note that after adding them (just declared) you now need also
default c'tor !

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-10 21:27:44 +01:00
Marco Costalba
74203e181d Retire EvalInfo* in SearchStack
It is an hidden bug waiting to fire. The main problem is
that ss[ply] is overwritten by search() and qsearch() called
from IID and razoring, so that we cannot hold a pointer to a
local EvalInfo variable.

For instance if we go razoring then we overwrite the pointer
with the address of a variable local to qsearch(), when we return
from qsearch() variable goes out of scope and now ss[ply].evalInfo
holds a stale pointer !

Because we are not looking for troubles we go through the
safe route and we remove it entirely.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-08 10:50:17 +01:00
Marco Costalba
97fe0ac777 Small code style triviality
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-07 13:23:00 +01:00
Joona Kiiski
7ae16a193b Implement init_search()
No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-07 13:09:03 +01:00
Joona Kiiski
8261f61964 Document lookup tables
No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-07 13:08:56 +01:00
Joona Kiiski
6e1cb6e45b Implement futility move count array
No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-07 13:08:48 +01:00
Joona Kiiski
4bfa0c429e Implement futility margins matrix
No functinal change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-07 13:08:40 +01:00
Marco Costalba
2e70a2873f Use gain table to order non-captures
Gain value is multiplied by 16 to be of comparable magnitudo
of negative history, on average.

This patch shows very good results in tactical tests, but
started very bad in real games, so I have run two test matches.

After 896 games at 1+0
Mod vs Orig +187 =525 -184 +1 ELO

After 999 games at 1+0
Mod vs Orig +223 =590 -186 +13 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-07 08:55:51 +01:00
Joona Kiiski
9429d2d028 Use posKey instead of pos.get_key() after NonPVIID
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-06 17:40:01 +01:00
Joona Kiiski
d44fa46082 Use opening book when pondering
Otherwise we will not use move given by opening book
when we receive 'ponderhit'-command.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-06 17:39:53 +01:00
Marco Costalba
c7866a4215 Delay sorting of negative scored non-captures
We can do this only when needed, if we get a cut-off
before we skip sorting entirely. This reduces sorting
time of about 20%.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-05 18:31:09 +01:00
Joona Kiiski
69644d3f73 Copy 4 SearchStack items in split()
In search routines we use information from previous ply
and init killers two plies ahead.

So for me it seems correct to copy 4 searchstack items
in split:

ply - 1, ply, ply + 1, ply + 2

Because
a) we do not split at root (ply == 0)
b) ply < PLY_MAX and SearchStack size is PLY_MAX_PLUS_2
there should be no risk of underflows or overflows

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-05 18:06:41 +01:00
Marco Costalba
b0858877ae Remove sorting optimization for many zeroes
With negative history we don't have anymore a
lot of zeroes to score, so just split moves in
positives and non-positives sets.

Speed up is almost zero, we cannot test speed directly
because node count changed due to reorder, but I have
verified sorting is correct. With a profiler I have
seen we gain a little in sort_moves() and lose a little
in insertion_sort(), so the net effect is almost zero,
but code is simpler.

No real change, just move reordering.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-05 18:04:08 +01:00
Joona Kiiski
321f6d1d19 Give FailLow flag more descriptive name
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-05 15:21:21 +01:00
Joona Kiiski
e738fa7d10 Remove Problem variable
It was only used to control StopOnPonderHit variable.
Now use FailLow variable instead.

Patch has a minor effect on time management when ponder is on.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-05 15:21:12 +01:00
Joona Kiiski
c5d546e18e Remove unused failHighPly1 flag
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-05 15:21:05 +01:00
Joona Kiiski
8d65fcc0f3 Remove unused FailHigh flag
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-05 15:20:57 +01:00
Joona Kiiski
d8e5b8c133 Simplify time management
noProblemFound condition is never true.
This was verified by running 800 games 1+0 match in 1 CPU computer.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-05 15:20:47 +01:00
Marco Costalba
6fe36d13de Be sure negative see evasions are at the bottom
Because H.move_ordering_score() can return negative values
some negative see moves could be searched before non-negative
see moves with negative history.

This patch restores proper ordering.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-05 08:19:39 +01:00
Marco Costalba
337ec0f3d0 Score non-captures only by history
Now that history can go negative and is almost alwyas
non zero we have no more reasons to use also psqt term.

After 994 games at 1+0
Mod vs Orig +204 =597 -193 +4 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-05 00:34:17 +01:00
Joona Kiiski
5b1043ee11 Reduction lookup table
No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-04 19:09:51 +01:00
Marco Costalba
439aea9ab7 Convert gains to use a piece-to mapping
Instead of piece-from-to, in this way it is similar
to what we already do for history.

Almost no change, but seems a bit simpler in this way.

After 995 games at 1+0
Mod vs Orig +207 =596 -192 +5 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-03 19:33:59 +01:00
Marco Costalba
770db27164 Fix a compile error from previous patch
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-02 19:01:24 +01:00
Joona Kiiski
21d32aa7fe Fix indentations
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-02 18:58:00 +01:00
Joona Kiiski
95d33aef9f Retire outdated aspiration search code
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-02 18:57:50 +01:00
Marco Costalba
b5a4edd86f Renamed stand pat as 'static null move pruning'
It seems more standard conformant. Also added a bit of
description directly from Tord.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-02 08:51:54 +01:00
Marco Costalba
35ada63174 Save futilityMargin for both colors
It will be needed by future patches.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-01 20:06:56 +01:00
Marco Costalba
06a695d5b8 Fix duplicated scaling function
We erroneusly added two times the same scaling function
to endgame's map.

Fix detected by valgrind becasue resulted in a memleak
of the first added scaling function.

Bug introduced by 30e8f0c9ad6a473 of 13/02/2009

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-01 19:33:02 +01:00
Marco Costalba
4b55d3d883 Increase TT size limit to 8 GB
We had an overflow due to use an integer for hash size,
now we use a size_t as we should, so we can increase to
an higher limit.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-01 16:53:10 +01:00
Marco Costalba
8008f78415 Check bounds in set_option_value()
Normally it's up to the GUI to check for option's limits,
but we could receive the new value directly from the user
by teminal window. So let's check the bounds anyway.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-02-01 14:17:37 +01:00
Marco Costalba
3941e4bdb3 Some code style triviality in root search
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-31 11:14:42 +01:00
Marco Costalba
d7d2c1b7e3 Add hardware POPCNT support for gcc
With new target 'make gcc-popcnt' it is now
possible to compile with enabled hardware POPCNT
support also with gcc. Until now was possible only
for Intel and MSVC compilers.

When this instruction is supported by CPU, for instance
on Intel i7 or i5 family, produced binary is a bit faster.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-31 09:39:32 +01:00
Marco Costalba
17502a5659 Revert "Remove pointless gcc flag when generating dependencies"
This reverts commit c43c5fe9e0.

Produces following build error after 'make clean', 'make icc' under Mandriva
with icc version 11.0

Makefile:306: .depend: No such file or directory
In file included from tt.cpp:28:
/usr/lib/gcc/i586-manbo-linux-gnu/4.3.2/include/xmmintrin.h:35:3: error: #error "SSE instruction set not enabled"

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-30 10:37:03 +01:00
Marco Costalba
e84488ed6b Retire captures pruning
Futility captures alone does not seem an improvment.

Perhaps is a combination of stand pat + futility that is winning,
so revert for now and continue testing starting from a standard
base until we find the correct receipe.

After 999 games at 1+0
Mod vs Orig +231 0506 -201  +10 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-30 09:59:28 +01:00
Marco Costalba
252844e899 Avoid search tree explosion in qsearch
Under some rare cases we can have a search tree explosion
due to a perpetual check or to a very long non-capture TT
sequence.

This avoids the tree explosion not following TT moves that
are not captures or promotions when we are below the
'generate checks' depth.

Idea suggested by Richard Vida.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-29 16:47:04 +01:00
Joona Kiiski
b651e5334b Correct qsearch() TT save
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-29 11:03:06 +01:00
Marco Costalba
bd358533a4 Stricter conditions in main search stand pat
Not a biggie but is a reduced pruned patch that doesn't
seems to hurt, so it is welcomed ;-)

After 999 games at 1+0
Mod vs Orig +207 =601 -191  +6 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-29 00:12:03 +01:00
Marco Costalba
e4d3a15656 Use float instead of double in reduction parameters
This is faster on 32 bit CPU and precision is enough.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-28 12:47:48 +01:00
Marco Costalba
1d7a3f26e0 Micro optimize reduction_parameters()
At ply == OnePly (common case) we avoid some useless
floating point computation.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-28 12:39:15 +01:00
Marco Costalba
a0005ba45f Avoid to calculate reduction for each move
This is slow because some floating point operation is
involved.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-28 12:34:28 +01:00
Joona Kiiski
bdd61b1744 Remove useless variable 'PostFutilityValueMargin'
No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-28 11:17:59 +01:00
Joona Kiiski
973e574e1f Precalculate FutilityMargins
This way we don't need to copy+paste formula everywhere

No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-28 11:16:56 +01:00
Joona Kiiski
27393ebae2 Use calculate_reduction() function to simplify code
No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-28 11:15:41 +01:00
Joona Kiiski
3c7eebb48d Bugfix: reduction was not set to zero in full depth search
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-28 11:15:18 +01:00
Joona Kiiski
548bae80bd Implement calculate_reduction function
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-28 11:14:43 +01:00
Joona Kiiski
2360c8aa2f Standardize set_option function
Previously input like "setoption name Use Search Log value true "
(note space at the end of the line) didn't work.

Now parse value same way as option name. This way we implicitly
left- and right-trim value.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-27 20:03:44 +01:00
Joona Kiiski
32bd6e44f0 Do not initialize RootPosition at startup
Initializing high-level object at startup is very dangerous,
because low-level snippets are not yet initialized.

For example Position's constructor calls find_checkers() which
calls attackers_to() which depends on various global bitboard arrays
which are not yet initialized. I think we are lucky not to crash.

RootPosition.from_fen(StartPosition); is called immediately after
all initializations are made at uci_main_loop() which is the
correct behaviour

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-27 20:00:28 +01:00
Marco Costalba
c83fd08fd4 Aspiration window rewrite
Joona new aspiration window. Main idea is to always
research aspiration fail highs/low at the same
ply and use much smaller aspiration window than previously.

Testing result is very positive.

1CPU:
953-1149

4CPU:
545 - 656

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-27 19:59:34 +01:00
Marco Costalba
62b43130e2 Be sure we exit while loop with lock held
This fixes an hang introduced by recent locking
rewrite patch.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-27 19:23:16 +01:00
Joona Kiiski
cd112ee8eb Fix capture pruning
We forgot to update bestValue previously

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-27 18:58:42 +01:00
Marco Costalba
bb968fd42a Simplify locking in sp_search and sp_search_pv
Avoid to take the lock two times in a tight sequence, the first
in get_next_move() and the second to update sp->moves.

Do all with one lock and so retire the now useless locked version
of get_next_move().

Also fix some theorical race due to comparison sp->bestValue < sp->beta
is done out of lock protection. Finally fix another (harmless but time
waster) race that coudl occur because thread_should_stop() is also
called outside of lock protection.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-27 17:58:04 +01:00
Marco Costalba
307909bed8 Temporary revert "captures pruning" due to an assert
In debug run with 2 threads it happens to be following
assert after some minutes:

assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);

in search(), line 1615.

I am not able to understand why, anyhow reverted for the moment.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-27 17:57:04 +01:00
Marco Costalba
b95ba7b37e Added some FIXME to track needed tests
This avoid us to forget some very needed tests now that
futility has changed in a whole big chunk we need to fine
tuning every splitted change.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-27 11:49:03 +01:00
Marco Costalba
f37741cc83 Integrate gains table in History
This will be useful to use gains table in move
ordering along with history table.

No functional change and big code remove.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-27 11:22:38 +01:00
Marco Costalba
54b3d44194 Introduce update_gains() and refactor some code
No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-27 11:09:07 +01:00
Joona Kiiski
ea53006a9d Fix some silly bugs
SelectiveDepth was ignored

Test results for the whole futility pruning series:

4CPU:
Orig - Mod: 959 - 1027 (+12 elo)

1CPU:
Orig - Mod: 763 - 830 (+15 elo)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-27 10:14:20 +01:00
Joona Kiiski
6247f27a05 MaxGain based futility pruning for captures
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-27 09:57:51 +01:00
Joona Kiiski
5b2fc1e1c0 MaxGain based pruning
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-27 09:57:41 +01:00
Joona Kiiski
05a8c318b8 Implement post futility pruning
and prevent futility pruning from pruning
castling moves

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-27 09:57:31 +01:00
Joona Kiiski
22b8dc8c98 Collect MaxGain statistics
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-27 09:57:24 +01:00
Joona Kiiski
cfe59de27d Implement MaxGain table
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-27 09:57:14 +01:00
Joona Kiiski
c43c5fe9e0 Remove pointless gcc flag when generating dependencies
When generating dependencies there is absolutely no point
to pass -msse flag to gcc, so remove it.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-27 09:53:30 +01:00
Joona Kiiski
d0daa16769 Remove InfiniteSearch hack
With current search control system, I can see absolutely no
reason to classify fixed time search as infinite search.

So remove old dated hack

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-27 09:52:47 +01:00
Joona Kiiski
87303d7ed3 Remove last use of uip.eof()
Value of uip.eof() should not be trusted.
input like "go infinite searchmoves " (note space in the end of line)
causes problems.

Check the return value of (uip >> token) instead

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-27 09:52:15 +01:00
Marco Costalba
cf9bf4e58f Reduce lock contention in sp_search_pv()
In less then 1% of cases value > sp->bestValue, so avoid
an useless lock in the common case. This is the same change
already applied to sp_search().

Also SplitPoint futilityValue is not volatile because
never changes after has been assigned in split()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-26 12:12:11 +01:00
Marco Costalba
5ca4284027 Fix a possible crash in thread_is_available()
When we have more then 2 threads then we do an array
access with index 'Threads[slave].activeSplitPoints - 1'
This should be >= 0 because we tested the variable just
few statements before, but because is a shared variable
it could be that the 'slave' thread set the value to zero
just after we test it, so that when we use the decremented
variable for array access we crash.

Bug spotted by Bruno Causse.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-25 23:34:21 +01:00
Marco Costalba
dac1bcab90 Small split() cleanup
Unify start loop for master and slave threads. Also guarantee
that all the 'stop' flags are set to false before first slave
is started, should be no harm because only master thread can
reset 'stop' flag of slaves to true, so should be no race but
better safe then sorry.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-25 19:59:33 +01:00
Marco Costalba
81cfd81366 Prune evasions with negative SEE in qsearch
Only pure blocking evasions are candidate
for pruning.

After 998 games at 1+0

Mod vs Orig +215 =596 -187  +10 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-25 16:31:56 +01:00
Marco Costalba
d844a75d2c Avoid copy a Position to get a move's san notation
In move_to_san() we create by copy a new position just
to detect if move gives check. This could be very costly in
line_to_san() that calls move_to_san() for every move, so
create the position only once and pass a reference to move_to_san()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-25 16:22:50 +01:00
Marco Costalba
c5e71f5150 Fix a race in idle_loop() exiting
When pondering threads are put to sleep, but when thinking
the threads are parked in idle_loop in a tight polling loop
checking for workIsWaiting falg.

So before we set the slave's flag workIsWaiting we have to
guarantee that all the slave data is already setup because
slave can start in any moment from there.

Rearrange the last loop to fix this race.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-25 15:02:06 +01:00
Marco Costalba
c5858ff9ae In split() release the lock before slow search stack copy
Once we have allocated our slave threads and we have removed
master from available threads we can safely remove the lock
so that the lenghty search stack copy operation will not
impact lock contention.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-25 14:12:30 +01:00
Marco Costalba
0ff91e16da Do not copy master position in split()
A pointer is enough because after a split point has been
setup master and slaves thread end up calling sp_search() or
sp_search_pv() and here a full copy of split point position is
done again, note that even master does another copy (of itself)
and this is done before any do_move() call so that master Position
is never updated between split() and sp_search().

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-25 12:46:08 +01:00
Marco Costalba
c2df60048e Use fast_copy() instead of full copy in sp_search
And detach splitPoint Position from the master one.

So we duplicate StateInfo only once in split() instead
of one for each thread in sp_search

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-25 12:13:16 +01:00
Marco Costalba
84ec1f7331 Better document how Position c'tor works
Renamed a bit the functions to be more clear what
we actually are doing when we craete a Position object
and explained how StateInfo works.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-25 12:04:00 +01:00
Marco Costalba
b1ac6c69a0 Fix a couple of MSVC casting warnings
Also removed some trailing whitespaces and aligned
indentation to current standard.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-25 11:27:32 +01:00
Marco Costalba
56e09b4cc8 Copy only the search stack tail in split()
Only the previous, the current and the next ply SearchStack
are copied.

This reduces split overhead especially at low depth (high ply)
and with many threads.

Possibly no functional change (it is not easy to prove in SMP)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-25 11:11:22 +01:00
Tord Romstad
5ed0a60203 Merge branch 'master' of ssh://free2.projectlocker.com/sf 2010-01-24 16:09:54 +01:00
Tord Romstad
1588a4e846 Fixes a Chess960 bug when playing with more than one search thread.
The init_eval() function corrupted the static array castleRightsMask[]
in the Position class, resulting in instant crashes in most Chess960
games. Fixed by repairing the damage directly after the function is
called. Also modified the Position::to_fen() function to display
castle rights correctly for Chess960 positions, and added sanity checks
for uncastled rook files in Position::is_ok().
2010-01-24 16:09:32 +01:00
Marco Costalba
5894c759cd Check for thread creation successful completion
It is a good programming practice to verify a system
call has indeed succeed.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-24 14:33:51 +01:00
Marco Costalba
3975a2b94f Fix some races in SMP code
When a search fails high then sp->alpha is increased and
slave threads are requested to stop.

So we have to check for a stop request before to start a search
otherwise we could end up with sp->alpha >= sp->beta
leading to an assert in debug run in search_pv().

This patch fixes the assert and get rid of some of possible races.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-24 14:30:09 +01:00
Tord Romstad
eb6ddd54f1 Make sure we make a move at the end of the search when reaching
maximum depth during a "go movetime ..." search. This prevents
Stockfish from hanging forever after finding a mate in two or
three while running a test suite at a level of a few seconds
per move.

No functional change when playing games at normal time controls.
2010-01-22 13:42:33 +01:00
Marco Costalba
01ebb3d996 If near beta generate checks at -OnePly
In qsearch() try to get a cutoff with the help of an
extra check if we are already very near.

Small increase in actual games but a good result in tactical
test sets where this patch makes SF more tactical.

Mod vs Orig +197 =620 -181 +6 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-21 00:31:01 +01:00
Marco Costalba
285df57a9a Retire LMRPVMoves and LMRNonPVMoves
Are no used anymore.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-20 18:43:29 +01:00
Marco Costalba
806c1d8723 Fix enum Value issue with gcc 4.4
Louis Zulli reports a miscompile with g++-4.4 from MacPorts.

Namely enum Value is compiled as unsigned instead of signed integer
and this yields an issue in score_string() where float(v) is incorrectly
casted when Value v is negative.

This patch ensure that compiler choses a signed variable to store a Value.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-19 23:30:23 +01:00
Marco Costalba
a1b8c8109b Small lnArray[] cleanup
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-19 11:52:13 +01:00
Marco Costalba
c01af56769 Silence some silly MSVC warnings
Value is never used un-initialized, but MSVC is not
smart enough to detect itself :-(

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-19 11:23:00 +01:00
Marco Costalba
66d5c13a88 Order check moves used in qsearch
Use the same scoring system used for evasions. Small if any
increase, but should be in at least for completeness.

After 999 games at 1+0
Mod vs Orig +208 =601 -190 +6 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-19 11:22:49 +01:00
Marco Costalba
0edad63b44 Avoid an useless evaluate() call
Now that we have position static score we don't
need to call evaluate() a second time.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-18 15:47:43 +01:00
Marco Costalba
b833c8247a Allow SearchStack to link an EvalInfo object
This will allow to have wider access to attack
information, for instance from MovePicker.

Note that 'eval' field become obsolete, it is kept
just becasue when we get a position score from TT
we update 'eval' even without an EvalInfo object.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-18 10:03:09 +01:00
Joona Kiiski
419c5b69ca Make reduction search code SMP-friendly
In sp_search_pv() we do a LMR search using sp->alpha, at the end
we detect a fail high with condition (value > sp->alpha), but if
another thread has increased sp->alpha during our LMR search we
could miss to detect a fail high event becasue value will be equal
to old alpha and so smaller then new one.

This patch fixes this SMP-bug and changes also the non SMP versions
of the search to keep code style in sync.

Bug spotted by Bruno Causse.

No functional change (for single CPU case)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-18 09:11:58 +01:00
Joona Kiiski
72e1e9b986 Small cleanup of unused code in sp_search
futilityValue is now calculated immediately after
staticValue, so remove small bunch of unused code

No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-17 14:21:14 +01:00
Marco Costalba
1062459029 Fix silly MSVC warning
MSVC raises an "use of partially uninitialized variable" for futilityValue
and staticValue but this is not rue becasue when !isCheck variables
are never used, anyhow silence the warning.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-17 13:54:52 +01:00
Marco Costalba
b5d38ad1e5 Initialize futilityMargin in EvalInfo c'tor
This is less prone to bugs because now it's up to the
compiler don't forget this important initialization.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-17 13:24:40 +01:00
Joona Kiiski
000a975eaf Retire quick_evaluate()
No change in functionality signature

The only functional change is that when we reach PLY_MAX,
we now return VALUE_DRAW instead of evaluating position.

But we reach PLY_MAX only when position is dead drawn and
transposition table is filled with draw scores, so this
shouldn't matter at all.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-17 13:15:44 +01:00
Joona Kiiski
d457594197 Razor at depth one, but do razoring only when not in check
This way razoring is always based on exact evaluation and
follows simple formula.

Joona's test results are positive:

32-bit 1CPU:

Mod - Orig: 1073 - 993

64-bit 4CPU:

Mod - Orig: 759 - 721

Functionality Signature: 11448962

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-17 11:46:40 +01:00
Marco Costalba
942c18ef66 Allow negative history values
Don't clamp to zero if a move continues to fail.

After 946 games at 1+0
Mod vs Orig +208 =562 -176 +12 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-13 22:10:43 +01:00
Marco Costalba
007285be2d Store node evaluation in SearchStack
This info will be used by future patches.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-11 21:18:30 +01:00
Marco Costalba
e817a55bc6 Decrease NullMoveMargin and adjust razoring
Also retire razoring margins vector and use
a simpler formula instead.

Now that we use a more accurate static evaluation
try to avoid useless null searches when we are well
below beta. And for teh same reason increase a bit
the razoring.

After 972 games at 1+0
Mod vs Orig +224 =558 -190 +12 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-11 21:17:02 +01:00
Marco Costalba
638f3d31cc Do not wait when AbortSearch is set
It means we have already received "stop" or "quit" commands.

This fixes an hang in tactical test in Fritz GUI. Bug
introduced by previous bug fix :-(

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-11 11:19:12 +01:00
Marco Costalba
55745f4105 Fix sending of best move during an infinite search
According to UCI standard once engine receives 'go infinite'
command it should search until the "stop" command and do not exit
the search without being told so, even if PLY_MAX has been reached.

Patch is quite invasive because it cleanups some hacks used
by fixed depth and fixed nodes modes, mainly during benchmarks.

Bug found by Pascal Georges.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-10 13:18:43 +01:00
Marco Costalba
968c3de8e0 Fix threads count setting
Was broken after "Optimal tune for 8 cores" patch.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-09 16:49:54 +01:00
Marco Costalba
6a6facc058 Optimal tune for 8 cores
After deep tests Louis Zulli found on his OCTAL machine that
best setup for an 8 core CPU is as following

"Threads" = 8
"Minimum Split Depth" = 6 or 7 (mSD)
"Maximum Number of Threads per Split Point" = not important (MNTpSP)

Here are testing results:

mSD7 (8 threads) vs mSD4 (8 threads): 291 - 120 - 589
mSD6 vs mSD7: 168 - 188 - 644
mSD6-MNTpSP5 vs mSD6-MNTpSP6: 172 - 172 - 656
SF-7threads vs SF-8threads: 179 - 204 - 617

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-08 12:58:51 +01:00
Marco Costalba
5b21c10afb Sync qsearch with search
So to have the same layout and be as much similar as
possible. The only functional change is that now we
try ttMove as first also in PV nodes and at the end
we save the ttMove, as it happens in search. This
should have almost zero impact on ELO but it seems
the correct thing to do.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-08 12:03:47 +01:00
Marco Costalba
dba072c449 Use full evaluation in null search
This is an important design change because we know
compute evaluation in each node.

This is a 2.0 type change!

After 977 games at 1+0

Mod vs Orig +236 =538 -202 51.74%  +12 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-08 10:20:35 +01:00
Joona Kiiski
e2e360fcbc Slow down reductions
After testing on Joona QUAD the whole LMR series:

Orig - Mod: 335 - 405 (+33 elo)

Functionality Signature: 12581900

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-07 15:49:48 +01:00
Joona Kiiski
49b1c5dccd Use logarithmic LMR also at root
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-07 15:40:04 +01:00
Joona Kiiski
c99d963fa5 Logarithmic LMR
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-07 15:35:57 +01:00
Marco Costalba
7c0679ad61 Fix 'position ..... moves ' parsing bug
If after 'moves' there is a space then we crash.

The problem is that operator>>() trims whitespaces so that
after 'moves' has been extract we are still not at eof()
but remaining string contains only spaces. So that the next
extarction operation uip >> token ends up with unchanged token
value that remains 'moves', this garbage value is then feeded
to RootPosition.do_move() through move_from_string() that does
not detect the invalid move value leading to a crash.

This bug is triggered by Shredder 12 interface under Mac that
puts a space after 'moves' without any actual move list.

Bug fixed by Justin Blanchard

After reviewing UCI parsing code I spotted other possible weak
points due to the fact that we don't test if the last extract
operation has been succesful. So I have extended Justing patch
to fix the remaining possible holes in uci.cpp

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-07 11:59:32 +01:00
Marco Costalba
cc974fa7a4 Fix en-passant parsing from fen string
According to standard en-passant is recorded in fen string regardless
of whether there is a pawn in position to make an en passant capture.

Instead internally we set ep square only if the pawn can be captured.
So teach from_fen() to correctly handle this difference.

Bug reported and fixed by Justin Blanchard.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-06 10:07:07 +01:00
Marco Costalba
807844eab1 Introduce refine_eval()
Try to get a position evaluation better then
the quick one with the help of the TT table.

This allows the null search conditions and
chosen reductions to be more accurate.

After 908 games at 1+0
Mod vs Orig +209 =526 -173 +14 ELO

Functionality Signature: 16627355

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-05 14:57:59 +01:00
Marco Costalba
860260c3b1 Increase null reduction at high depths
Linear rule, less aggressive then Dann's one.

It seems it scales well with depth. We will need to
verify against weaker engine if it keeps the score.

After 999 games at 1+0 on my Dual Core
Mod vs Orig +232 =534 -207  +9 ELO

After 1000 games by Martin Thoresen on his QUAD at 1+0
Mod vs Orig 521/479 52.10%

Functionality Signature: 17655312

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-05 08:09:09 +01:00
Marco Costalba
d11af1de11 Fix a compile error under gcc
And some warnings on the picky icc.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-04 17:19:42 +01:00
Marco Costalba
721d557681 Last round of search.cpp cleanup
The most interesting thing is a bit of rewrite
and semplification in connected_moves()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-04 12:39:13 +01:00
Marco Costalba
0e15b0f1d3 Space inflate bottom part of search.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-03 21:30:46 +01:00
Marco Costalba
9e6d38d224 Rename MaxActiveSplitPoints
And move in thread.h togheter with THREAD_MAX

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-03 15:37:23 +01:00
Marco Costalba
c8af7a867e Retire 'finished' from MovePicker
It is not useful becasue it is safe to call
get_next_move() multiple times when phase == PH_STOP

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-03 15:37:17 +01:00
Marco Costalba
5c8f571459 Rename SingleReplyExtension in SingleEvasionExtension
Because that's the correct meaning. Note that also the
corresponding UCI option has been renamed.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-03 15:37:03 +01:00
Marco Costalba
0256db2a11 Small cleanup in search.cpp
Also clarify some comments.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-03 15:36:40 +01:00
Marco Costalba
12d8f74242 Retire approximateEval field from SplitPoint
It is not used anymore after the futility pruning
rewrite in a66f31f12.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-01-02 10:30:05 +01:00
Marco Costalba
7824603549 Double HistoryMax and reduce aging
After history accounting rewrite in 1.6, a small
tweak of history parameters seems positive.

Note that these are not to be considered the optimal
values, just a wild guess that proved good.

Finding the optimal values would require a much longer
testing time.

After 967 games at 1+0

Mod vs Orig 240 529 198 +15 ELO

Functionality Signature: 21222553

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-12-31 13:45:57 +01:00
Marco Costalba
0f39e5c4ff Fix a little warning under gcc compiler
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-12-30 13:25:22 +01:00
Marco Costalba
990d83a72d Optimized bitScanReverse32()
Should be a bit faster then previous one.
Hacked by Pascal Georges.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-12-30 13:25:21 +01:00
Marco Costalba
cf486cf229 Restore development version
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-12-30 13:25:21 +01:00
Marco Costalba
e0a8b36436 Stockfish 1.6.2
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-12-30 13:25:20 +01:00
Marco Costalba
8d724220a7 Better fix for gcc optimization issue
According to the standard, compiler is free to choose
the enum type as long as can keep its data.
Also cast to short and right shift are implementation
defined in case of a signed integer.

Normally all the compilers implement this stuff in
the "usual" way, but gcc with -O3 and -O2 pushes
aggressively the language to its limits to squeeze
even the last bit of speed. And this broke our
not 100% standard conforming code.

The fix is to rewrite the Score enum and the 16 bits
word extracting functions in a way that is 100% standard
compliant and with no speed regression on gcc and also on
the other compilers.

Verified it works on all compilers and with equivalent
functionality.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-12-30 13:25:02 +01:00
Marco Costalba
0973cc2ef6 Score enum should be at least 32 bits
The compiler is allowed to chose the size of an enum variable
based on the values it is expected to store. So force the compiler
to use at least a 32 bit integer type for the Score.

MSVC and Intel do not change, while gcc under -O3 is affected
by this change.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-12-27 19:45:19 +01:00
Marco Costalba
3f14f9a478 Revert small pop_1st_bit() optimization
We cannot cast a pointer type to an unrelated pointer type.
This is a violation of the strict aliasing rules.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-12-27 14:07:08 +01:00
Marco Costalba
aa86d81f79 Remove a bogus assert
It is not clear why is not true, even in single thread
case, but as a matter of fact it is not!

So remove it.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-12-27 13:54:46 +01:00
Marco Costalba
b884351cc7 Use THREAD_MAX instead of hardcoded 8
This will allow to change THREAD_MAX value in the future.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-12-27 13:52:29 +01:00
Marco Costalba
4d9e9ac3d4 Restore development version
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-12-27 08:35:44 +01:00
Marco Costalba
3dc9f95225 Set maximum hash table size to 2GB
We cannot allocate more then 2 GB, so let the limit
reflect this.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-12-27 00:44:08 +01:00
Marco Costalba
bc0871acbc Stockfish 1.6.1
Workaround a gcc optimization bug.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-12-26 19:39:22 +01:00
Marco Costalba
2643f1552f Workaround optimization bug in gcc
Unfortunatly we need to slow down to -O1 to be sure
it works always.

Note that sometime it works also with -O2 or even -O3,
but user has to try himself.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-12-26 19:39:13 +01:00
Marco Costalba
ba07b95ee0 Fix description of Score enum
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-12-26 19:39:04 +01:00
Marco Costalba
ef58551a2d Fix a typo in ReducedStateInfo
It happened to work by accident because Score and
Value are both integer.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-12-26 19:38:53 +01:00
60 changed files with 3767 additions and 3797 deletions

View File

@@ -1,63 +1,48 @@
[PolyGlot]
EngineDir = .
EngineCommand = ./stockfish
Book = false
BookFile = book.bin
Log = true
LogFile = stockfish.log
Resign = true
ResignScore = 600
[Engine]
Hash = 128
Threads = 1
OwnBook = false
Book File = book.bin
Use Search Log = false
Mobility (Middle Game) = 100
Mobility (Endgame) = 100
Pawn Structure (Middle Game) = 100
Pawn Structure (Endgame) = 100
Passed Pawns (Middle Game) = 100
Passed Pawns (Endgame) = 100
Aggressiveness = 100
Cowardice = 100
King Safety Curve = Quadratic
Quadratic = Linear
King Safety Coefficient = 40
King Safety X Intercept = 0
King Safety Max Slope = 30
King Safety Max Value = 500
Queen Contact Check Bonus = 3
Queen Check Bonus = 2
Rook Check Bonus = 1
Bishop Check Bonus = 1
Knight Check Bonus = 1
Discovered Check Bonus = 3
Mate Threat Bonus = 3
Check Extension (PV nodes) = 2
Check Extension (non-PV nodes) = 1
Single Reply Extension (PV nodes) = 2
Single Reply Extension (non-PV nodes) = 2
Mate Threat Extension (PV nodes) = 0
Mate Threat Extension (non-PV nodes) = 0
Pawn Push to 7th Extension (PV nodes) = 1
Pawn Push to 7th Extension (non-PV nodes) = 1
Passed Pawn Extension (PV nodes) = 1
Passed Pawn Extension (non-PV nodes) = 0
Pawn Endgame Extension (PV nodes) = 2
Pawn Endgame Extension (non-PV nodes) = 2
Full Depth Moves (PV nodes) = 14
Full Depth Moves (non-PV nodes) = 3
Threat Depth = 5
Futility Pruning (Main Search) = true
Futility Pruning (Quiescence Search) = true
Randomness = 0
Minimum Split Depth = 4
Maximum Number of Threads per Split Point = 5
[PolyGlot]
EngineDir = .
EngineCommand = ./stockfish
Book = false
BookFile = book.bin
Log = false
LogFile = stockfish.log
Resign = true
ResignScore = 600
[Engine]
Hash = 128
Threads = 1
OwnBook = false
Book File = book.bin
Best Book Move = false
Use Search Log = false
Search Log Filename = SearchLog.txt
Mobility (Middle Game) = 100
Mobility (Endgame) = 100
Pawn Structure (Middle Game) = 100
Pawn Structure (Endgame) = 100
Passed Pawns (Middle Game) = 100
Passed Pawns (Endgame) = 100
Space = 100
Aggressiveness = 100
Cowardice = 100
Check Extension (PV nodes) = 2
Check Extension (non-PV nodes) = 1
Single Reply Extension (PV nodes) = 2
Single Reply Extension (non-PV nodes) = 2
Mate Threat Extension (PV nodes) = 0
Mate Threat Extension (non-PV nodes) = 0
Pawn Push to 7th Extension (PV nodes) = 1
Pawn Push to 7th Extension (non-PV nodes) = 1
Passed Pawn Extension (PV nodes) = 1
Passed Pawn Extension (non-PV nodes) = 0
Pawn Endgame Extension (PV nodes) = 2
Pawn Endgame Extension (non-PV nodes) = 2
Randomness = 0
Minimum Split Depth = 4
Maximum Number of Threads per Split Point = 5

View File

@@ -1,7 +1,7 @@
# Stockfish, a UCI chess playing engine derived from Glaurung 2.1
# Copyright (C) 2004-2007 Tord Romstad
# Copyright (C) 2008 Marco Costalba
# Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
# Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
#
# This file is part of Stockfish.
#
# Stockfish is free software: you can redistribute it and/or modify
@@ -18,289 +18,490 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
### Executable name. Do not change
### ==========================================================================
### Section 1. General Configuration
### ==========================================================================
### Executable name
EXE = stockfish
### Installation dir definitions
PREFIX = /usr/local
BINDIR = $(PREFIX)/bin
### ==========================================================================
### Compiler speed switches for both GCC and ICC. These settings are generally
### fast on a broad range of systems, but may be changed experimentally
### ==========================================================================
GCCFLAGS = -O3 -msse
ICCFLAGS = -fast -msse
ICCFLAGS-OSX = -fast -mdynamic-no-pic
### ==========================================================================
### Enable/disable debugging, disabled by default
### ==========================================================================
GCCFLAGS += -DNDEBUG
ICCFLAGS += -DNDEBUG
ICCFLAGS-OSX += -DNDEBUG
### ==========================================================================
### Remove below comments to compile for a big-endian machine
### ==========================================================================
#GCCFLAGS += -DBIGENDIAN
#ICCFLAGS += -DBIGENDIAN
#ICCFLAGS-OSX += -DBIGENDIAN
### ==========================================================================
### Run built-in benchmark for pgo-builds with: 32MB hash 1 thread 10 depth
### These settings are generally fast, but may be changed experimentally
### ==========================================================================
### Built-in benchmark for pgo-builds
PGOBENCH = ./$(EXE) bench 32 1 10 default depth
### General compiler settings. Do not change
GCCFLAGS += -g -Wall -fno-exceptions -fno-rtti
ICCFLAGS += -g -Wall -fno-exceptions -fno-rtti -wd383,869,981,10187,10188,11505,11503
ICCFLAGS-OSX += -g -Wall -fno-exceptions -fno-rtti -wd383,869,981,10187,10188,11505,11503
### General linker settings. Do not change
LDFLAGS = -lpthread
### Object files. Do not change
### Object files
OBJS = application.o bitboard.o pawns.o material.o endgame.o evaluate.o main.o \
misc.o move.o movegen.o history.o movepick.o search.o piece.o \
position.o direction.o tt.o value.o uci.o ucioption.o \
mersenne.o book.o bitbase.o san.o benchmark.o
### General rules. Do not change
### ==========================================================================
### Section 2. High-level Configuration
### ==========================================================================
#
# flag --- Comp switch --- Description
# ----------------------------------------------------------------------------
#
# debug = no/yes --- -DNDEBUG --- Enable/Disable debug mode
# optimize = yes/no --- (-O3/-fast etc.) --- Enable/Disable optimizations
# arch = (name) --- (-arch) --- Target architecture
# os = (name) --- --- Target operating system
# bits = 64/32 --- -DIS_64BIT --- 64-/32-bit operating system
# bigendian = no/yes --- -DBIGENDIAN --- big/little-endian byte order
# prefetch = no/yes --- -DUSE_PREFETCH --- Use prefetch x86 asm-instruction
# bsfq = no/yes --- -DUSE_BSFQ --- Use bsfq x86_64 asm-instruction
# --- (Works only with GCC and ICC 64-bit)
# popcnt = no/yes --- -DUSE_POPCNT --- Use popcnt x86_64 asm-instruction
#
# Note that Makefile is space sensitive, so when adding new architectures
# or modifying existing flags, you have to make sure there are no extra spaces
# at the end of the line for flag values.
### 2.1. General
debug = no
optimize = yes
### 2.2 Architecture specific
# General-section
ifeq ($(ARCH),general-64)
arch = any
os = any
bits = 64
bigendian = no
prefetch = no
bsfq = no
popcnt = no
endif
ifeq ($(ARCH),general-32)
arch = any
os = any
bits = 32
bigendian = no
prefetch = no
bsfq = no
popcnt = no
endif
ifeq ($(ARCH),bigendian-64)
arch = any
os = any
bits = 64
bigendian = yes
prefetch = no
bsfq = no
popcnt = no
endif
ifeq ($(ARCH),bigendian-32)
arch = any
os = any
bits = 32
bigendian = yes
prefetch = no
bsfq = no
popcnt = no
endif
# x86-section
ifeq ($(ARCH),x86-64)
arch = x86_64
os = any
bits = 64
bigendian = no
prefetch = yes
bsfq = yes
popcnt = no
endif
ifeq ($(ARCH),x86-64-modern)
arch = x86_64
os = any
bits = 64
bigendian = no
prefetch = yes
bsfq = yes
popcnt = yes
endif
ifeq ($(ARCH),x86-32)
arch = i386
os = any
bits = 32
bigendian = no
prefetch = yes
bsfq = no
popcnt = no
endif
ifeq ($(ARCH),x86-32-old)
arch = i386
os = any
bits = 32
bigendian = no
prefetch = no
bsfq = no
popcnt = no
endif
# osx-section
ifeq ($(ARCH),osx-ppc-64)
arch = ppc64
os = osx
bits = 64
bigendian = yes
prefetch = no
bsfq = no
popcnt = no
endif
ifeq ($(ARCH),osx-ppc-32)
arch = ppc
os = osx
bits = 32
bigendian = yes
prefetch = no
bsfq = no
popcnt = no
endif
ifeq ($(ARCH),osx-x86-64)
arch = x86_64
os = osx
bits = 64
bigendian = no
prefetch = yes
bsfq = yes
popcnt = no
endif
ifeq ($(ARCH),osx-x86-32)
arch = i386
os = osx
bits = 32
bigendian = no
prefetch = yes
bsfq = no
popcnt = no
endif
### ==========================================================================
### Section 3. Low-level configuration
### ==========================================================================
### 3.1 Selecting compiler (default = gcc)
ifeq ($(COMP),)
COMP=gcc
endif
ifeq ($(COMP),gcc)
comp=gcc
CXX=g++
profile_prepare = gcc-profile-prepare
profile_make = gcc-profile-make
profile_use = gcc-profile-use
profile_clean = gcc-profile-clean
endif
ifeq ($(COMP),icc)
comp=icc
CXX=icpc
profile_prepare = icc-profile-prepare
profile_make = icc-profile-make
profile_use = icc-profile-use
profile_clean = icc-profile-clean
endif
### 3.2 General compiler settings
CXXFLAGS += -g -Wall -fno-exceptions -fno-rtti $(EXTRACXXFLAGS)
ifeq ($(comp),icc)
CXXFLAGS += -wd383,869,981,10187,10188,11505,11503
endif
ifeq ($(os),osx)
CXXFLAGS += -arch $(arch)
endif
### 3.3 General linker settings
LDFLAGS += -lpthread $(EXTRALDFLAGS)
ifeq ($(os),osx)
LDFLAGS += -arch $(arch)
endif
### 3.4 Debugging
ifeq ($(debug),no)
CXXFLAGS += -DNDEBUG
endif
### 3.5 Optimization
ifeq ($(optimize),yes)
ifeq ($(comp),gcc)
CXXFLAGS += -O3
ifeq ($(os),osx)
ifeq ($(arch),i386)
CXXFLAGS += -mdynamic-no-pic
endif
ifeq ($(arch),x86_64)
CXXFLAGS += -mdynamic-no-pic
endif
endif
endif
ifeq ($(comp),icc)
CXXFLAGS += -fast
ifeq ($(os),osx)
CXXFLAGS += -mdynamic-no-pic
endif
endif
endif
### 3.6. Bits
ifeq ($(bits),64)
CXXFLAGS += -DIS_64BIT
endif
### 3.7 Endianess
ifeq ($(bigendian),yes)
CXXFLAGS += -DBIGENDIAN
endif
### 3.8 prefetch
ifeq ($(prefetch),yes)
CXXFLAGS += -msse
DEPENDFLAGS += -msse
else
CXXFLAGS += -DNO_PREFETCH
endif
### 3.9 bsfq
ifeq ($(bsfq),yes)
CXXFLAGS += -DUSE_BSFQ
endif
### 3.10 popcnt
ifeq ($(popcnt),yes)
CXXFLAGS += -DUSE_POPCNT
endif
### ==========================================================================
### Section 4. Public targets
### ==========================================================================
default:
$(MAKE) gcc
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) build
help:
@echo ""
@echo "Makefile options:"
@echo "To compile stockfish, type: "
@echo ""
@echo "make > Default: Compiler = g++"
@echo "make icc > Compiler = icpc"
@echo "make icc-profile > Compiler = icpc + automatic pgo-build"
@echo "make icc-profile-popcnt > Compiler = icpc + automatic pgo-build + popcnt-support"
@echo "make osx-ppc32 > PPC-Mac OS X 32 bit. Compiler = g++"
@echo "make osx-ppc64 > PPC-Mac OS X 64 bit. Compiler = g++"
@echo "make osx-x86 > x86-Mac OS X 32 bit. Compiler = g++"
@echo "make osx-x86_64 > x86-Mac OS X 64 bit. Compiler = g++"
@echo "make osx-icc32 > x86-Mac OS X 32 bit. Compiler = icpc"
@echo "make osx-icc64 > x86-Mac OS X 64 bit. Compiler = icpc"
@echo "make osx-icc32-profile > OSX 32 bit. Compiler = icpc + automatic pgo-build"
@echo "make osx-icc64-profile > OSX 64 bit. Compiler = icpc + automatic pgo-build"
@echo "make strip > Strip executable"
@echo "make clean > Clean up"
@echo "make target ARCH=arch [COMP=comp]"
@echo ""
@echo "Supported targets:"
@echo ""
@echo "build > Build unoptimized version"
@echo "profile-build > Build PGO-optimized version"
@echo "popcnt-profile-build > Build PGO-optimized version with optional popcnt-support"
@echo "strip > Strip executable"
@echo "install > Install executable"
@echo "clean > Clean up"
@echo "testrun > Make sample run"
@echo ""
@echo "Supported archs:"
@echo ""
@echo "x86-64 > x86 64-bit"
@echo "x86-64-modern > x86 64-bit with runtime support for popcnt-instruction"
@echo "x86-32 > x86 32-bit excluding very old hardware without SSE-support"
@echo "x86-32-old > x86 32-bit including also very old hardware"
@echo "osx-ppc-64 > PPC-Mac OS X 64 bit"
@echo "osx-ppc-32 > PPC-Mac OS X 32 bit"
@echo "osx-x86-64 > x86-Mac OS X 64 bit"
@echo "osx-x86-32 > x86-Mac OS X 32 bit"
@echo "general-64 > unspecified 64-bit"
@echo "general-32 > unspecified 32-bit"
@echo "bigendian-64 > unspecified 64-bit with bigendian byte order"
@echo "bigendian-32 > unspecified 32-bit with bigendian byte order"
@echo ""
@echo "Supported comps:"
@echo ""
@echo "gcc > Gnu compiler (default)"
@echo "icc > Intel compiler"
@echo ""
@echo "Non-standard targets:"
@echo ""
@echo "make hpux > Compile for HP-UX. Compiler = aCC"
@echo ""
@echo "Examples. If you don't know what to do, you likely want to run: "
@echo ""
@echo "make profile-build ARCH=x86-64 (This is for 64-bit systems)"
@echo "make profile-build ARCH=x86-32 (This is for 32-bit systems)"
@echo ""
all: $(EXE) .depend
build:
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) config-sanity
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) all
clean:
$(RM) *.o .depend *~ $(EXE)
### Possible targets. You may add your own ones here
gcc:
$(MAKE) \
CXX='g++' \
CXXFLAGS="$(GCCFLAGS)" \
all
icc:
$(MAKE) \
CXX='icpc' \
CXXFLAGS="$(ICCFLAGS)" \
all
icc-profile-make:
$(MAKE) \
CXX='icpc' \
CXXFLAGS="$(ICCFLAGS)" \
CXXFLAGS+='-prof-gen=srcpos -prof_dir ./profdir' \
all
icc-profile-use:
$(MAKE) \
CXX='icpc' \
CXXFLAGS="$(ICCFLAGS)" \
CXXFLAGS+='-prof_use -prof_dir ./profdir' \
all
icc-profile:
@rm -rf profdir
@mkdir profdir
profile-build:
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) config-sanity
@echo ""
@echo "Step 0/4. Preparing for profile build."
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) $(profile_prepare)
@echo ""
@echo "Step 1/4. Building executable for benchmark ..."
@touch *.cpp *.h
$(MAKE) icc-profile-make
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) $(profile_make)
@echo ""
@echo "Running benchmark for pgo-build ..."
@echo "Step 2/4. Running benchmark for pgo-build ..."
@$(PGOBENCH) > /dev/null
@echo "Benchmark finished. Build final executable now ..."
@echo ""
@touch *.cpp *.h
$(MAKE) icc-profile-use
@rm -rf profdir bench.txt
icc-profile-make-with-popcnt:
$(MAKE) \
CXX='icpc' \
CXXFLAGS="$(ICCFLAGS) -DUSE_POPCNT" \
CXXFLAGS+='-prof-gen=srcpos -prof_dir ./profdir' \
all
icc-profile-use-with-popcnt:
$(MAKE) \
CXX='icpc' \
CXXFLAGS="$(ICCFLAGS) -DUSE_POPCNT" \
CXXFLAGS+='-prof_use -prof_dir ./profdir' \
all
icc-profile-popcnt:
@rm -rf profdir
@mkdir profdir
@touch *.cpp *.h
$(MAKE) icc-profile-make
@echo "Step 3/4. Building final executable ..."
@touch *.cpp
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) $(profile_use)
@echo ""
@echo "Running benchmark for pgo-build (popcnt disabled)..."
@echo "Step 4/4. Deleting profile data ..."
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) $(profile_clean)
popcnt-profile-build:
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) config-sanity
@echo ""
@echo "Step 0/6. Preparing for profile build."
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) $(profile_prepare)
@echo ""
@echo "Step 1/6. Building executable for benchmark (popcnt disabled)..."
@touch *.cpp *.h
$(MAKE) ARCH=x86-64 COMP=$(COMP) $(profile_make)
@echo ""
@echo "Step 2/6. Running benchmark for pgo-build (popcnt disabled)..."
@$(PGOBENCH) > /dev/null
@touch *.cpp *.h
$(MAKE) icc-profile-make-with-popcnt
@echo ""
@echo "Running benchmark for pgo-build (popcnt enabled)..."
@echo "Step 3/6. Building executable for benchmark (popcnt enabled)..."
@touch *.cpp *.h
$(MAKE) ARCH=x86-64-modern COMP=$(COMP) $(profile_make)
@echo ""
@echo "Step 4/6. Running benchmark for pgo-build (popcnt enabled)..."
@$(PGOBENCH) > /dev/null
@echo "Benchmarks finished. Build final executable now ..."
@echo ""
@echo "Step 5/6. Building final executable ..."
@touch *.cpp *.h
$(MAKE) icc-profile-use-with-popcnt
@rm -rf profdir bench.txt
osx-ppc32:
$(MAKE) \
CXX='g++' \
CXXFLAGS="$(GCCFLAGS)" \
CXXFLAGS+='-arch ppc' \
LDFLAGS+='-arch ppc' \
all
osx-ppc64:
$(MAKE) \
CXX='g++' \
CXXFLAGS="$(GCCFLAGS)" \
CXXFLAGS+='-arch ppc64' \
LDFLAGS+='-arch ppc64' \
all
osx-x86:
$(MAKE) \
CXX='g++' \
CXXFLAGS="$(GCCFLAGS)" \
CXXFLAGS+='-arch i386' \
LDFLAGS+='-arch i386' \
all
osx-x86_64:
$(MAKE) \
CXX='g++' \
CXXFLAGS="$(GCCFLAGS)" \
CXXFLAGS+='-arch x86_64' \
LDFLAGS+='-arch x86_64' \
all
osx-icc32:
$(MAKE) \
CXX='icpc' \
CXXFLAGS="$(ICCFLAGS-OSX)" \
CXXFLAGS+='-arch i386' \
LDFLAGS+='-arch i386' \
all
osx-icc64:
$(MAKE) \
CXX='icpc' \
CXXFLAGS="$(ICCFLAGS-OSX)" \
CXXFLAGS+='-arch x86_64' \
LDFLAGS+='-arch x86_64' \
all
osx-icc32-profile-make:
$(MAKE) \
CXX='icpc' \
CXXFLAGS="$(ICCFLAGS-OSX)" \
CXXFLAGS+='-arch i386' \
CXXFLAGS+='-prof_gen -prof_dir ./profdir' \
LDFLAGS+='-arch i386' \
all
osx-icc32-profile-use:
$(MAKE) \
CXX='icpc' \
CXXFLAGS="$(ICCFLAGS-OSX)" \
CXXFLAGS+='-arch i386' \
CXXFLAGS+='-prof_use -prof_dir ./profdir' \
LDFLAGS+='-arch i386' \
all
osx-icc32-profile:
@rm -rf profdir
@mkdir profdir
@touch *.cpp *.h
$(MAKE) osx-icc32-profile-make
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) $(profile_use)
@echo ""
@echo "Running benchmark for pgo-build ..."
@$(PGOBENCH) > /dev/null
@echo "Benchmark finished. Build final executable now ..."
@echo "Step 6/6. Deleting profile data ..."
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) $(profile_clean)
@echo ""
@touch *.cpp *.h
$(MAKE) osx-icc32-profile-use
@rm -rf profdir bench.txt
osx-icc64-profile-make:
$(MAKE) \
CXX='icpc' \
CXXFLAGS="$(ICCFLAGS-OSX)" \
CXXFLAGS+='-arch x86_64' \
CXXFLAGS+='-prof_gen -prof_dir ./profdir' \
LDFLAGS+='-arch x86_64' \
all
osx-icc64-profile-use:
$(MAKE) \
CXX='icpc' \
CXXFLAGS="$(ICCFLAGS-OSX)" \
CXXFLAGS+='-arch x86_64' \
CXXFLAGS+='-prof_use -prof_dir ./profdir' \
LDFLAGS+='-arch x86_64' \
all
osx-icc64-profile:
@rm -rf profdir
@mkdir profdir
@touch *.cpp *.h
$(MAKE) osx-icc64-profile-make
@echo ""
@echo "Running benchmark for pgo-build ..."
@$(PGOBENCH) > /dev/null
@echo "Benchmark finished. Build final executable now ..."
@echo ""
@touch *.cpp *.h
$(MAKE) osx-icc64-profile-use
@rm -rf profdir bench.txt
strip:
strip $(EXE)
install:
-mkdir -p -m 755 $(BINDIR)
-cp $(EXE) $(BINDIR)
-strip $(BINDIR)/$(EXE)
clean:
$(RM) $(EXE) *.o .depend *~ core bench.txt
testrun:
@$(PGOBENCH)
### ==========================================================================
### Section 5. Private targets
### ==========================================================================
all: $(EXE) .depend
config-sanity:
@echo ""
@echo "Config:"
@echo "debug: '$(debug)'"
@echo "optimize: '$(optimize)'"
@echo "arch: '$(arch)'"
@echo "os: '$(os)'"
@echo "bits: '$(bits)'"
@echo "bigendian: '$(bigendian)'"
@echo "prefetch: '$(prefetch)'"
@echo "bsfq: '$(bsfq)'"
@echo "popcnt: '$(popcnt)'"
@echo ""
@echo "Flags:"
@echo "CXX: $(CXX)"
@echo "CXXFLAGS: $(CXXFLAGS)"
@echo "LDFLAGS: $(LDFLAGS)"
@echo ""
@echo "Testing config sanity. If this fails, try 'make help' ..."
@echo ""
@test "$(debug)" = "yes" || test "$(debug)" = "no"
@test "$(optimize)" = "yes" || test "$(optimize)" = "no"
@test "$(arch)" = "any" || test "$(arch)" = "x86_64" || test "$(arch)" = "i386" || \
test "$(arch)" = "ppc64" || test "$(arch)" = "ppc"
@test "$(os)" = "any" || test "$(os)" = "osx"
@test "$(bits)" = "32" || test "$(bits)" = "64"
@test "$(bigendian)" = "yes" || test "$(bigendian)" = "no"
@test "$(prefetch)" = "yes" || test "$(prefetch)" = "no"
@test "$(bsfq)" = "yes" || test "$(bsfq)" = "no"
@test "$(popcnt)" = "yes" || test "$(popcnt)" = "no"
@test "$(comp)" = "gcc" || test "$(comp)" = "icc"
### Compilation. Do not change
$(EXE): $(OBJS)
$(CXX) $(LDFLAGS) -o $@ $(OBJS)
$(CXX) -o $@ $(OBJS) $(LDFLAGS)
gcc-profile-prepare:
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) gcc-profile-clean
gcc-profile-make:
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) \
EXTRACXXFLAGS='-fprofile-generate' \
EXTRALDFLAGS='-lgcov' \
all
gcc-profile-use:
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) \
EXTRACXXFLAGS='-fprofile-use' \
all
gcc-profile-clean:
@rm -rf *.gcda *.gcno bench.txt
icc-profile-prepare:
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) icc-profile-clean
@mkdir profdir
icc-profile-make:
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) \
EXTRACXXFLAGS='-prof-gen=srcpos -prof_dir ./profdir' \
all
icc-profile-use:
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) \
EXTRACXXFLAGS='-prof_use -prof_dir ./profdir' \
all
icc-profile-clean:
@rm -rf profdir bench.txt
### Dependencies. Do not change
.depend:
$(CXX) -msse -MM $(OBJS:.o=.cpp) > $@
-@$(CXX) $(DEPENDFLAGS) -MM $(OBJS:.o=.cpp) > $@ 2> /dev/null
-include .depend
### ==========================================================================
### Section 6. Non-standard targets
### ==========================================================================
hpux:
$(MAKE) \
CXX='/opt/aCC/bin/aCC -AA +hpxstd98 -DBIGENDIAN -mt +O3 -DNDEBUG' \
CXXFLAGS="" \
LDFLAGS="" \
all
include .depend

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -49,6 +49,7 @@ Application::Application() {
Position::init_piece_square_tables();
init_eval(1);
init_bitbases();
init_search();
init_threads();
// Make random number generation less deterministic, for book moves
@@ -56,12 +57,6 @@ Application::Application() {
genrand_int32();
}
Application::~Application() {
stop_threads();
quit_eval();
}
void Application::initialize() {
// A static Application object is allocated
@@ -69,7 +64,15 @@ void Application::initialize() {
static Application singleton;
}
void Application::free_resources() {
// Warning, following functions reference global objects that
// must be still alive when free_resources() is called.
exit_threads();
quit_eval();
}
void Application::exit_with_failure() {
exit(EXIT_FAILURE); // d'tor will be called automatically
exit(EXIT_FAILURE);
}

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -29,10 +29,10 @@ class Application {
Application();
Application(const Application&);
~Application();
public:
static void initialize();
static void free_resources();
static void exit_with_failure();
};

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -38,8 +38,8 @@ using namespace std;
const string BenchmarkPositions[] = {
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
"r4rk1/1b2qppp/p1n1p3/1p6/1b1PN3/3BRN2/PP3PPP/R2Q2K1 b - - 7 16",
"4r1k1/ppq3pp/3b4/2pP4/2Q1p3/4B1P1/PP5P/R5K1 b - - 0 20",
"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq -",
"8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - -",
"4rrk1/pp1n3p/3q2pQ/2p1pb2/2PP4/2P3N1/P2B2PP/4RRK1 b - - 7 19",
"rq3rk1/ppp2ppp/1bnpb3/3N2B1/3NP3/7P/PPPQ1PP1/2KR3R w - - 7 14",
"r1bq1r1k/1pp1n1pp/1p1p4/4p2Q/4Pp2/1BNP4/PPP2PPP/3R1RK1 w - - 2 14",
@@ -84,9 +84,9 @@ void benchmark(const string& commandLine) {
}
csStr >> threads;
csVal >> val;
if (val < 1 || val > THREAD_MAX)
if (val < 1 || val > MAX_THREADS)
{
cerr << "The number of threads must be between 1 and " << THREAD_MAX << endl;
cerr << "The number of threads must be between 1 and " << MAX_THREADS << endl;
Application::exit_with_failure();
}
set_option_value("Hash", ttSize);
@@ -151,13 +151,18 @@ void benchmark(const string& commandLine) {
{
Move moves[1] = {MOVE_NONE};
int dummy[2] = {0, 0};
Position pos(*it);
Position pos(*it, 0);
cerr << "\nBench position: " << cnt << '/' << positions.size() << endl << endl;
if (limitType == "perft")
totalNodes += perft(pos, maxDepth * OnePly);
else if (!think(pos, true, false, 0, dummy, dummy, 0, maxDepth, maxNodes, secsPerPos, moves))
break;
totalNodes += nodes_searched();
{
int64_t perftCnt = perft(pos, maxDepth * OnePly);
cerr << "\nPerft " << maxDepth << " result (nodes searched): " << perftCnt << endl << endl;
totalNodes += perftCnt;
} else {
if (!think(pos, false, false, 0, dummy, dummy, 0, maxDepth, maxNodes, secsPerPos, moves))
break;
totalNodes += nodes_searched();
}
}
cnt = get_system_time() - startTime;

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -226,8 +226,9 @@ Bitboard StepAttackBB[16][64];
Bitboard RayBB[64][8];
Bitboard BetweenBB[64][64];
Bitboard SquaresInFrontMask[2][64];
Bitboard PassedPawnMask[2][64];
Bitboard OutpostMask[2][64];
Bitboard AttackSpanMask[2][64];
Bitboard BishopPseudoAttacks[64];
Bitboard RookPseudoAttacks[64];
@@ -246,14 +247,12 @@ namespace {
void init_ray_bitboards();
void init_attacks();
void init_between_bitboards();
void init_pseudo_attacks();
Bitboard index_to_bitboard(int index, Bitboard mask);
Bitboard sliding_attacks(int sq, Bitboard block, int dirs, int deltas[][2],
int fmin, int fmax, int rmin, int rmax);
Bitboard index_to_bitboard(int index, Bitboard mask);
void init_sliding_attacks(Bitboard attacks[],
int attackIndex[], Bitboard mask[],
const int shift[2], const Bitboard mult[],
int deltas[][2]);
void init_pseudo_attacks();
void init_sliding_attacks(Bitboard attacks[], int attackIndex[], Bitboard mask[],
const int shift[], const Bitboard mult[], int deltas[][2]);
}
@@ -265,11 +264,14 @@ namespace {
/// standard output. This is sometimes useful for debugging.
void print_bitboard(Bitboard b) {
for(Rank r = RANK_8; r >= RANK_1; r--) {
std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
for(File f = FILE_A; f <= FILE_H; f++)
std::cout << "| " << (bit_is_set(b, make_square(f, r))? 'X' : ' ') << ' ';
std::cout << "|" << std::endl;
for (Rank r = RANK_8; r >= RANK_1; r--)
{
std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
for (File f = FILE_A; f <= FILE_H; f++)
std::cout << "| " << (bit_is_set(b, make_square(f, r))? 'X' : ' ') << ' ';
std::cout << "|" << std::endl;
}
std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
}
@@ -279,8 +281,10 @@ void print_bitboard(Bitboard b) {
/// program initialization.
void init_bitboards() {
int rookDeltas[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
int bishopDeltas[4][2] = {{1,1},{-1,1},{1,-1},{-1,-1}};
init_masks();
init_ray_bitboards();
init_attacks();
@@ -297,8 +301,8 @@ void init_bitboards() {
#if defined(IS_64BIT) && !defined(USE_BSFQ)
CACHE_LINE_ALIGNMENT
static const int BitTable[64] = {
static CACHE_LINE_ALIGNMENT
const int BitTable[64] = {
0, 1, 2, 7, 3, 13, 8, 19, 4, 25, 14, 28, 9, 34, 20, 40, 5, 17, 26, 38, 15,
46, 29, 48, 10, 31, 35, 54, 21, 50, 41, 57, 63, 6, 12, 18, 24, 27, 33, 39,
16, 37, 45, 47, 30, 53, 49, 56, 62, 11, 23, 32, 36, 44, 52, 55, 61, 22, 43,
@@ -326,6 +330,7 @@ const int BitTable[64] = {
};
Square first_1(Bitboard b) {
b ^= (b - 1);
uint32_t fold = int(b) ^ int(b >> 32);
return Square(BitTable[(fold * 0x783a9b23) >> 26]);
@@ -348,46 +353,26 @@ union b_union {
Square pop_1st_bit(Bitboard* bb) {
b_union* u;
b_union u;
Square ret;
u = (b_union*)bb;
u.b = *bb;
if (u->dw.l)
if (u.dw.l)
{
ret = Square(BitTable[((u->dw.l ^ (u->dw.l - 1)) * 0x783a9b23) >> 26]);
u->dw.l &= (u->dw.l - 1);
ret = Square(BitTable[((u.dw.l ^ (u.dw.l - 1)) * 0x783a9b23) >> 26]);
u.dw.l &= (u.dw.l - 1);
*bb = u.b;
return ret;
}
ret = Square(BitTable[((~(u->dw.h ^ (u->dw.h - 1))) * 0x783a9b23) >> 26]);
u->dw.h &= (u->dw.h - 1);
ret = Square(BitTable[((~(u.dw.h ^ (u.dw.h - 1))) * 0x783a9b23) >> 26]);
u.dw.h &= (u.dw.h - 1);
*bb = u.b;
return ret;
}
#endif
int bitScanReverse32(uint32_t b)
{
int result = 0;
if (b > 0xFFFF) {
b >>= 16;
result += 16;
}
if (b > 0xFF) {
b >>= 8;
result += 8;
}
if (b > 0xF) {
b >>= 4;
result += 4;
}
if (b > 0x3) {
b >>= 2;
result += 2;
}
return result + (b > 0) + (b > 1);
}
namespace {
@@ -397,39 +382,46 @@ namespace {
// be necessary to touch any of them.
void init_masks() {
SetMaskBB[SQ_NONE] = 0ULL;
ClearMaskBB[SQ_NONE] = ~SetMaskBB[SQ_NONE];
for(Square s = SQ_A1; s <= SQ_H8; s++) {
SetMaskBB[s] = (1ULL << s);
ClearMaskBB[s] = ~SetMaskBB[s];
for (Square s = SQ_A1; s <= SQ_H8; s++)
{
SetMaskBB[s] = (1ULL << s);
ClearMaskBB[s] = ~SetMaskBB[s];
}
for(Color c = WHITE; c <= BLACK; c++)
for(Square s = SQ_A1; s <= SQ_H8; s++) {
PassedPawnMask[c][s] =
in_front_bb(c, s) & this_and_neighboring_files_bb(s);
OutpostMask[c][s] = in_front_bb(c, s) & neighboring_files_bb(s);
}
for (Color c = WHITE; c <= BLACK; c++)
for (Square s = SQ_A1; s <= SQ_H8; s++)
{
SquaresInFrontMask[c][s] = in_front_bb(c, s) & file_bb(s);
PassedPawnMask[c][s] = in_front_bb(c, s) & this_and_neighboring_files_bb(s);
AttackSpanMask[c][s] = in_front_bb(c, s) & neighboring_files_bb(s);
}
for (Bitboard b = 0ULL; b < 256ULL; b++)
BitCount8Bit[b] = (uint8_t)count_1s(b);
}
int remove_bit_8(int i) { return ((i & ~15) >> 1) | (i & 7); }
void init_ray_bitboards() {
int d[8] = {1, -1, 16, -16, 17, -17, 15, -15};
for(int i = 0; i < 128; i = (i + 9) & ~8) {
for(int j = 0; j < 8; j++) {
RayBB[(i&7)|((i>>4)<<3)][j] = EmptyBoardBB;
for(int k = i + d[j]; (k & 0x88) == 0; k += d[j])
set_bit(&(RayBB[(i&7)|((i>>4)<<3)][j]), Square((k&7)|((k>>4)<<3)));
}
}
for (int i = 0; i < 128; i = (i + 9) & ~8)
for (int j = 0; j < 8; j++)
{
RayBB[remove_bit_8(i)][j] = EmptyBoardBB;
for (int k = i + d[j]; (k & 0x88) == 0; k += d[j])
set_bit(&(RayBB[remove_bit_8(i)][j]), Square(remove_bit_8(k)));
}
}
void init_attacks() {
int i, j, k, l;
int step[16][8] = {
const int step[16][8] = {
{0},
{7,9,0}, {17,15,10,6,-6,-10,-15,-17}, {9,7,-7,-9,0}, {8,1,-1,-8,0},
{9,7,-7,-9,8,1,-1,-8}, {9,7,-7,-9,8,1,-1,-8}, {0}, {0},
@@ -437,105 +429,115 @@ namespace {
{9,7,-7,-9,8,1,-1,-8}, {9,7,-7,-9,8,1,-1,-8}
};
for(i = 0; i < 64; i++) {
for(j = 0; j <= int(BK); j++) {
StepAttackBB[j][i] = EmptyBoardBB;
for(k = 0; k < 8 && step[j][k] != 0; k++) {
l = i + step[j][k];
if(l >= 0 && l < 64 && abs((i&7) - (l&7)) < 3)
StepAttackBB[j][i] |= (1ULL << l);
for (int i = 0; i < 64; i++)
for (int j = 0; j <= int(BK); j++)
{
StepAttackBB[j][i] = EmptyBoardBB;
for (int k = 0; k < 8 && step[j][k] != 0; k++)
{
int l = i + step[j][k];
if (l >= 0 && l < 64 && abs((i & 7) - (l & 7)) < 3)
StepAttackBB[j][i] |= (1ULL << l);
}
}
}
}
}
Bitboard sliding_attacks(int sq, Bitboard block, int dirs, int deltas[][2],
int fmin=0, int fmax=7, int rmin=0, int rmax=7) {
Bitboard result = 0ULL;
int rk = sq / 8, fl = sq % 8, r, f, i;
for(i = 0; i < dirs; i++) {
int dx = deltas[i][0], dy = deltas[i][1];
for(f = fl+dx, r = rk+dy;
(dx==0 || (f>=fmin && f<=fmax)) && (dy==0 || (r>=rmin && r<=rmax));
f += dx, r += dy) {
result |= (1ULL << (f + r*8));
if(block & (1ULL << (f + r*8))) break;
}
int rk = sq / 8;
int fl = sq % 8;
for (int i = 0; i < dirs; i++)
{
int dx = deltas[i][0];
int dy = deltas[i][1];
int f = fl + dx;
int r = rk + dy;
while ( (dx == 0 || (f >= fmin && f <= fmax))
&& (dy == 0 || (r >= rmin && r <= rmax)))
{
result |= (1ULL << (f + r*8));
if (block & (1ULL << (f + r*8)))
break;
f += dx;
r += dy;
}
}
return result;
}
void init_between_bitboards() {
SquareDelta step[8] = {
DELTA_E, DELTA_W, DELTA_N, DELTA_S, DELTA_NE, DELTA_SW, DELTA_NW, DELTA_SE
};
SignedDirection d;
for(Square s1 = SQ_A1; s1 <= SQ_H8; s1++)
for(Square s2 = SQ_A1; s2 <= SQ_H8; s2++) {
BetweenBB[s1][s2] = EmptyBoardBB;
d = signed_direction_between_squares(s1, s2);
if(d != SIGNED_DIR_NONE)
for(Square s3 = s1 + step[d]; s3 != s2; s3 += step[d])
set_bit(&(BetweenBB[s1][s2]), s3);
const SquareDelta step[8] = { DELTA_E, DELTA_W, DELTA_N, DELTA_S,
DELTA_NE, DELTA_SW, DELTA_NW, DELTA_SE };
for (Square s1 = SQ_A1; s1 <= SQ_H8; s1++)
for (Square s2 = SQ_A1; s2 <= SQ_H8; s2++)
{
BetweenBB[s1][s2] = EmptyBoardBB;
SignedDirection d = signed_direction_between_squares(s1, s2);
if (d != SIGNED_DIR_NONE)
{
for (Square s3 = s1 + step[d]; s3 != s2; s3 += step[d])
set_bit(&(BetweenBB[s1][s2]), s3);
}
}
}
Bitboard index_to_bitboard(int index, Bitboard mask) {
int i, j, bits = count_1s(mask);
Bitboard result = 0ULL;
for(i = 0; i < bits; i++) {
j = pop_1st_bit(&mask);
if(index & (1 << i)) result |= (1ULL << j);
int bits = count_1s(mask);
for (int i = 0; i < bits; i++)
{
int j = pop_1st_bit(&mask);
if (index & (1 << i))
result |= (1ULL << j);
}
return result;
}
void init_sliding_attacks(Bitboard attacks[], int attackIndex[], Bitboard mask[],
const int shift[], const Bitboard mult[], int deltas[][2]) {
void init_sliding_attacks(Bitboard attacks[],
int attackIndex[], Bitboard mask[],
const int shift[2], const Bitboard mult[],
int deltas[][2]) {
int i, j, k, index = 0;
Bitboard b;
for(i = 0; i < 64; i++) {
attackIndex[i] = index;
mask[i] = sliding_attacks(i, 0ULL, 4, deltas, 1, 6, 1, 6);
for (int i = 0, index = 0; i < 64; i++)
{
attackIndex[i] = index;
mask[i] = sliding_attacks(i, 0ULL, 4, deltas, 1, 6, 1, 6);
#if defined(IS_64BIT)
j = (1 << (64 - shift[i]));
int j = (1 << (64 - shift[i]));
#else
j = (1 << (32 - shift[i]));
int j = (1 << (32 - shift[i]));
#endif
for(k = 0; k < j; k++) {
for (int k = 0; k < j; k++)
{
#if defined(IS_64BIT)
b = index_to_bitboard(k, mask[i]);
attacks[index + ((b * mult[i]) >> shift[i])] =
sliding_attacks(i, b, 4, deltas);
Bitboard b = index_to_bitboard(k, mask[i]);
attacks[index + ((b * mult[i]) >> shift[i])] = sliding_attacks(i, b, 4, deltas);
#else
b = index_to_bitboard(k, mask[i]);
attacks[index +
(unsigned(int(b) * int(mult[i]) ^
int(b >> 32) * int(mult[i] >> 32))
>> shift[i])] =
sliding_attacks(i, b, 4, deltas);
Bitboard b = index_to_bitboard(k, mask[i]);
unsigned v = int(b) * int(mult[i]) ^ int(b >> 32) * int(mult[i] >> 32);
attacks[index + (v >> shift[i])] = sliding_attacks(i, b, 4, deltas);
#endif
}
index += j;
}
index += j;
}
}
void init_pseudo_attacks() {
Square s;
for(s = SQ_A1; s <= SQ_H8; s++) {
BishopPseudoAttacks[s] = bishop_attacks_bb(s, EmptyBoardBB);
RookPseudoAttacks[s] = rook_attacks_bb(s, EmptyBoardBB);
QueenPseudoAttacks[s] = queen_attacks_bb(s, EmptyBoardBB);
for (Square s = SQ_A1; s <= SQ_H8; s++)
{
BishopPseudoAttacks[s] = bishop_attacks_bb(s, EmptyBoardBB);
RookPseudoAttacks[s] = rook_attacks_bb(s, EmptyBoardBB);
QueenPseudoAttacks[s] = queen_attacks_bb(s, EmptyBoardBB);
}
}

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -74,8 +74,9 @@ extern Bitboard StepAttackBB[16][64];
extern Bitboard RayBB[64][8];
extern Bitboard BetweenBB[64][64];
extern Bitboard SquaresInFrontMask[2][64];
extern Bitboard PassedPawnMask[2][64];
extern Bitboard OutpostMask[2][64];
extern Bitboard AttackSpanMask[2][64];
extern const uint64_t RMult[64];
extern const int RShift[64];
@@ -127,9 +128,8 @@ inline void do_move_bb(Bitboard *b, Bitboard move_bb) {
*b ^= move_bb;
}
/// rank_bb() and file_bb() gives a bitboard containing all squares on a given
/// file or rank. It is also possible to pass a square as input to these
/// functions.
/// rank_bb() and file_bb() take a file or a square as input, and return
/// a bitboard representing all squares on the given file or rank.
inline Bitboard rank_bb(Rank r) {
return RankBB[r];
@@ -156,7 +156,7 @@ inline Bitboard neighboring_files_bb(File f) {
}
inline Bitboard neighboring_files_bb(Square s) {
return neighboring_files_bb(square_file(s));
return NeighboringFilesBB[square_file(s)];
}
@@ -169,7 +169,7 @@ inline Bitboard this_and_neighboring_files_bb(File f) {
}
inline Bitboard this_and_neighboring_files_bb(Square s) {
return this_and_neighboring_files_bb(square_file(s));
return ThisAndNeighboringFilesBB[square_file(s)];
}
@@ -195,7 +195,7 @@ inline Bitboard in_front_bb(Color c, Rank r) {
}
inline Bitboard in_front_bb(Color c, Square s) {
return in_front_bb(c, square_rank(s));
return InFrontBB[c][square_rank(s)];
}
@@ -208,7 +208,7 @@ inline Bitboard behind_bb(Color c, Rank r) {
}
inline Bitboard behind_bb(Color c, Square s) {
return in_front_bb(opposite_color(c), square_rank(s));
return InFrontBB[opposite_color(c)][square_rank(s)];
}
@@ -274,12 +274,11 @@ inline Bitboard squares_between(Square s1, Square s2) {
/// squares_in_front_of takes a color and a square as input, and returns a
/// bitboard representing all squares along the line in front of the square,
/// from the point of view of the given color. For instance,
/// squares_in_front_of(BLACK, SQ_E4) returns a bitboard with the squares
/// e3, e2 and e1 set.
/// from the point of view of the given color. Definition of the table is:
/// SquaresInFrontOf[c][s] = in_front_bb(c, s) & file_bb(s)
inline Bitboard squares_in_front_of(Color c, Square s) {
return in_front_bb(c, s) & file_bb(s);
return SquaresInFrontMask[c][s];
}
@@ -287,33 +286,27 @@ inline Bitboard squares_in_front_of(Color c, Square s) {
/// behind the square instead of in front of the square.
inline Bitboard squares_behind(Color c, Square s) {
return in_front_bb(opposite_color(c), s) & file_bb(s);
return SquaresInFrontMask[opposite_color(c)][s];
}
/// passed_pawn_mask takes a color and a square as input, and returns a
/// bitboard mask which can be used to test if a pawn of the given color on
/// the given square is a passed pawn.
/// the given square is a passed pawn. Definition of the table is:
/// PassedPawnMask[c][s] = in_front_bb(c, s) & this_and_neighboring_files_bb(s)
inline Bitboard passed_pawn_mask(Color c, Square s) {
return PassedPawnMask[c][s];
}
/// outpost_mask takes a color and a square as input, and returns a bitboard
/// mask which can be used to test whether a piece on the square can possibly
/// be driven away by an enemy pawn.
/// attack_span_mask takes a color and a square as input, and returns a bitboard
/// representing all squares that can be attacked by a pawn of the given color
/// when it moves along its file starting from the given square. Definition is:
/// AttackSpanMask[c][s] = in_front_bb(c, s) & neighboring_files_bb(s);
inline Bitboard outpost_mask(Color c, Square s) {
return OutpostMask[c][s];
}
/// isolated_pawn_mask takes a square as input, and returns a bitboard mask
/// which can be used to test whether a pawn on the given square is isolated.
inline Bitboard isolated_pawn_mask(Square s) {
return neighboring_files_bb(s);
inline Bitboard attack_span_mask(Color c, Square s) {
return AttackSpanMask[c][s];
}
@@ -349,7 +342,6 @@ extern Square pop_1st_bit(Bitboard* b);
extern void print_bitboard(Bitboard b);
extern void init_bitboards();
extern int bitScanReverse32(uint32_t b);
#endif // !defined(BITBOARD_H_INCLUDED)

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -26,40 +26,18 @@
// Select type of intrinsic bit count instruction to use, see
// README.txt on how to pgo compile with POPCNT support.
#if defined(__INTEL_COMPILER) && defined(USE_POPCNT) // Intel compiler
#include <nmmintrin.h>
inline bool cpu_has_popcnt() {
int CPUInfo[4] = {-1};
__cpuid(CPUInfo, 0x00000001);
return (CPUInfo[2] >> 23) & 1;
}
#define POPCNT_INTRINSIC(x) _mm_popcnt_u64(x)
#elif defined(_MSC_VER) && defined(USE_POPCNT) // Microsoft compiler
#include <intrin.h>
inline bool cpu_has_popcnt() {
int CPUInfo[4] = {-1};
__cpuid(CPUInfo, 0x00000001);
return (CPUInfo[2] >> 23) & 1;
}
#define POPCNT_INTRINSIC(x) __popcnt64(x)
#else // Safe fallback for unsupported compilers or when USE_POPCNT is disabled
inline bool cpu_has_popcnt() { return false; }
#if !defined(USE_POPCNT)
#define POPCNT_INTRINSIC(x) 0
#elif defined(_MSC_VER)
#define POPCNT_INTRINSIC(x) (int)__popcnt64(x)
#elif defined(__GNUC__)
#endif // cpu_has_popcnt() and POPCNT_INTRINSIC() definitions
#define POPCNT_INTRINSIC(x) ({ \
unsigned long __ret; \
__asm__("popcnt %1, %0" : "=r" (__ret) : "r" (x)); \
__ret; })
#endif
/// Software implementation of bit count functions
@@ -126,10 +104,23 @@ inline int count_1s_max_15(Bitboard b) {
}
// Detect hardware POPCNT support
inline bool cpu_has_popcnt() {
int CPUInfo[4] = {-1};
__cpuid(CPUInfo, 0x00000001);
return (CPUInfo[2] >> 23) & 1;
}
// Global constant initialized at startup that is set to true if
// CPU on which application runs supports POPCNT intrinsic. Unless
// USE_POPCNT is not defined.
#if defined(USE_POPCNT)
const bool CpuHasPOPCNT = cpu_has_popcnt();
#else
const bool CpuHasPOPCNT = false;
#endif
// Global constant used to print info about the use of 64 optimized

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -390,7 +390,7 @@ void Book::close() {
/// Book::file_name() returns the file name of the currently active book,
/// or the empty string if no book is open.
const string Book::file_name() const {
const string Book::file_name() { // Not const to compile on HP-UX 11.X
return is_open() ? fileName : "";
}
@@ -399,14 +399,15 @@ const string Book::file_name() const {
/// Book::get_move() gets a book move for a given position. Returns
/// MOVE_NONE if no book move is found.
Move Book::get_move(const Position& pos) {
Move Book::get_move(const Position& pos, bool findBestMove) {
if (!is_open() || bookSize == 0)
return MOVE_NONE;
int bookMove = 0, scoresSum = 0;
uint64_t key = book_key(pos);
BookEntry entry;
int bookMove = MOVE_NONE;
int scoresSum = 0, bestScore = 0;
uint64_t key = book_key(pos);
// Choose a book move among the possible moves for the given position
for (int idx = find_key(key); idx < bookSize; idx++)
@@ -419,6 +420,17 @@ Move Book::get_move(const Position& pos) {
assert(score > 0);
// If findBestMove is true choose highest rated book move
if (findBestMove)
{
if (score > bestScore)
{
bestScore = score;
bookMove = entry.move;
}
continue;
}
// Choose book move according to its score. If a move has a very
// high score it has more probability to be choosen then a one with
// lower score. Note that first entry is always chosen.

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -53,12 +53,15 @@ struct BookEntry {
};
class Book : private std::ifstream {
Book(const Book&); // just decleared..
Book& operator=(const Book&); // ..to avoid a warning
public:
Book() {}
~Book();
void open(const std::string& fName);
void close();
const std::string file_name() const;
Move get_move(const Position& pos);
const std::string file_name();
Move get_move(const Position& pos, bool findBestMove);
private:
Book& operator>>(uint64_t& n) { n = read_integer(8); return *this; }

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -27,7 +27,8 @@
enum Depth {
DEPTH_ZERO = 0,
DEPTH_MAX = 200 // 100 * OnePly;
DEPTH_MAX = 200, // 100 * OnePly;
DEPTH_ENSURE_SIGNED = -1
};
@@ -48,7 +49,8 @@ inline void operator+= (Depth &d, int i) { d = Depth(int(d) + i); }
inline void operator+= (Depth &d1, Depth d2) { d1 += int(d2); }
inline Depth operator- (Depth d, int i) { return Depth(int(d) - i); }
inline Depth operator- (Depth d1, Depth d2) { return Depth(int(d1) - int(d2)); }
inline void operator-= (Depth & d, int i) { d = Depth(int(d) - i); }
inline void operator-= (Depth &d, int i) { d = Depth(int(d) - i); }
inline void operator-= (Depth &d1, Depth d2) { d1 -= int(d2); }
inline Depth operator* (Depth d, int i) { return Depth(int(d) * i); }
inline Depth operator* (int i, Depth d) { return Depth(int(d) * i); }
inline void operator*= (Depth &d, int i) { d = Depth(int(d) * i); }

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -104,7 +104,7 @@ namespace {
/// attacking side a bonus for driving the defending king towards the edge
/// of the board, and for keeping the distance between the two kings small.
template<>
Value EvaluationFunction<KXK>::apply(const Position& pos) {
Value EvaluationFunction<KXK>::apply(const Position& pos) const {
assert(pos.non_pawn_material(weakerSide) == Value(0));
assert(pos.piece_count(weakerSide, PAWN) == Value(0));
@@ -130,7 +130,7 @@ Value EvaluationFunction<KXK>::apply(const Position& pos) {
/// Mate with KBN vs K. This is similar to KX vs K, but we have to drive the
/// defending king towards a corner square of the right color.
template<>
Value EvaluationFunction<KBNK>::apply(const Position& pos) {
Value EvaluationFunction<KBNK>::apply(const Position& pos) const {
assert(pos.non_pawn_material(weakerSide) == Value(0));
assert(pos.piece_count(weakerSide, PAWN) == Value(0));
@@ -159,7 +159,7 @@ Value EvaluationFunction<KBNK>::apply(const Position& pos) {
/// KP vs K. This endgame is evaluated with the help of a bitbase.
template<>
Value EvaluationFunction<KPK>::apply(const Position& pos) {
Value EvaluationFunction<KPK>::apply(const Position& pos) const {
assert(pos.non_pawn_material(strongerSide) == Value(0));
assert(pos.non_pawn_material(weakerSide) == Value(0));
@@ -207,7 +207,7 @@ Value EvaluationFunction<KPK>::apply(const Position& pos) {
/// far advanced with support of the king, while the attacking king is far
/// away.
template<>
Value EvaluationFunction<KRKP>::apply(const Position& pos) {
Value EvaluationFunction<KRKP>::apply(const Position& pos) const {
assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
assert(pos.piece_count(strongerSide, PAWN) == 0);
@@ -264,7 +264,7 @@ Value EvaluationFunction<KRKP>::apply(const Position& pos) {
/// KR vs KB. This is very simple, and always returns drawish scores. The
/// score is slightly bigger when the defending king is close to the edge.
template<>
Value EvaluationFunction<KRKB>::apply(const Position& pos) {
Value EvaluationFunction<KRKB>::apply(const Position& pos) const {
assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
assert(pos.piece_count(strongerSide, PAWN) == 0);
@@ -280,7 +280,7 @@ Value EvaluationFunction<KRKB>::apply(const Position& pos) {
/// KR vs KN. The attacking side has slightly better winning chances than
/// in KR vs KB, particularly if the king and the knight are far apart.
template<>
Value EvaluationFunction<KRKN>::apply(const Position& pos) {
Value EvaluationFunction<KRKN>::apply(const Position& pos) const {
assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
assert(pos.piece_count(strongerSide, PAWN) == 0);
@@ -304,7 +304,7 @@ Value EvaluationFunction<KRKN>::apply(const Position& pos) {
/// for the defending side in the search, this is usually sufficient to be
/// able to win KQ vs KR.
template<>
Value EvaluationFunction<KQKR>::apply(const Position& pos) {
Value EvaluationFunction<KQKR>::apply(const Position& pos) const {
assert(pos.non_pawn_material(strongerSide) == QueenValueMidgame);
assert(pos.piece_count(strongerSide, PAWN) == 0);
@@ -323,7 +323,7 @@ Value EvaluationFunction<KQKR>::apply(const Position& pos) {
}
template<>
Value EvaluationFunction<KBBKN>::apply(const Position& pos) {
Value EvaluationFunction<KBBKN>::apply(const Position& pos) const {
assert(pos.piece_count(strongerSide, BISHOP) == 2);
assert(pos.non_pawn_material(strongerSide) == 2*BishopValueMidgame);
@@ -352,12 +352,12 @@ Value EvaluationFunction<KBBKN>::apply(const Position& pos) {
/// K and two minors vs K and one or two minors or K and two knights against
/// king alone are always draw.
template<>
Value EvaluationFunction<KmmKm>::apply(const Position&) {
Value EvaluationFunction<KmmKm>::apply(const Position&) const {
return Value(0);
}
template<>
Value EvaluationFunction<KNNK>::apply(const Position&) {
Value EvaluationFunction<KNNK>::apply(const Position&) const {
return Value(0);
}
@@ -367,7 +367,7 @@ Value EvaluationFunction<KNNK>::apply(const Position&) {
/// returned. If not, the return value is SCALE_FACTOR_NONE, i.e. no scaling
/// will be used.
template<>
ScaleFactor ScalingFunction<KBPsK>::apply(const Position& pos) {
ScaleFactor ScalingFunction<KBPsK>::apply(const Position& pos) const {
assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
assert(pos.piece_count(strongerSide, BISHOP) == 1);
@@ -421,7 +421,7 @@ ScaleFactor ScalingFunction<KBPsK>::apply(const Position& pos) {
/// It tests for fortress draws with a rook on the third rank defended by
/// a pawn.
template<>
ScaleFactor ScalingFunction<KQKRPs>::apply(const Position& pos) {
ScaleFactor ScalingFunction<KQKRPs>::apply(const Position& pos) const {
assert(pos.non_pawn_material(strongerSide) == QueenValueMidgame);
assert(pos.piece_count(strongerSide, QUEEN) == 1);
@@ -452,7 +452,7 @@ ScaleFactor ScalingFunction<KQKRPs>::apply(const Position& pos) {
/// It would also be nice to rewrite the actual code for this function,
/// which is mostly copied from Glaurung 1.x, and not very pretty.
template<>
ScaleFactor ScalingFunction<KRPKR>::apply(const Position &pos) {
ScaleFactor ScalingFunction<KRPKR>::apply(const Position& pos) const {
assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
assert(pos.piece_count(strongerSide, PAWN) == 1);
@@ -570,7 +570,7 @@ ScaleFactor ScalingFunction<KRPKR>::apply(const Position &pos) {
/// single pattern: If the stronger side has no pawns and the defending king
/// is actively placed, the position is drawish.
template<>
ScaleFactor ScalingFunction<KRPPKRP>::apply(const Position &pos) {
ScaleFactor ScalingFunction<KRPPKRP>::apply(const Position& pos) const {
assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
assert(pos.piece_count(strongerSide, PAWN) == 2);
@@ -609,7 +609,7 @@ ScaleFactor ScalingFunction<KRPPKRP>::apply(const Position &pos) {
/// against king. There is just a single rule here: If all pawns are on
/// the same rook file and are blocked by the defending king, it's a draw.
template<>
ScaleFactor ScalingFunction<KPsK>::apply(const Position &pos) {
ScaleFactor ScalingFunction<KPsK>::apply(const Position& pos) const {
assert(pos.non_pawn_material(strongerSide) == Value(0));
assert(pos.piece_count(strongerSide, PAWN) >= 2);
@@ -655,7 +655,7 @@ ScaleFactor ScalingFunction<KPsK>::apply(const Position &pos) {
/// it's a draw. If the two bishops have opposite color, it's almost always
/// a draw.
template<>
ScaleFactor ScalingFunction<KBPKB>::apply(const Position &pos) {
ScaleFactor ScalingFunction<KBPKB>::apply(const Position& pos) const {
assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
assert(pos.piece_count(strongerSide, BISHOP) == 1);
@@ -708,7 +708,7 @@ ScaleFactor ScalingFunction<KBPKB>::apply(const Position &pos) {
/// KBPPKBScalingFunction scales KBPP vs KB endgames. It detects a few basic
/// draws with opposite-colored bishops.
template<>
ScaleFactor ScalingFunction<KBPPKB>::apply(const Position& pos) {
ScaleFactor ScalingFunction<KBPPKB>::apply(const Position& pos) const {
assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
assert(pos.piece_count(strongerSide, BISHOP) == 1);
@@ -784,7 +784,7 @@ ScaleFactor ScalingFunction<KBPPKB>::apply(const Position& pos) {
/// square of the king is not of the same color as the stronger side's bishop,
/// it's a draw.
template<>
ScaleFactor ScalingFunction<KBPKN>::apply(const Position &pos) {
ScaleFactor ScalingFunction<KBPKN>::apply(const Position& pos) const {
assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
assert(pos.piece_count(strongerSide, BISHOP) == 1);
@@ -811,7 +811,7 @@ ScaleFactor ScalingFunction<KBPKN>::apply(const Position &pos) {
/// If the pawn is a rook pawn on the 7th rank and the defending king prevents
/// the pawn from advancing, the position is drawn.
template<>
ScaleFactor ScalingFunction<KNPK>::apply(const Position &pos) {
ScaleFactor ScalingFunction<KNPK>::apply(const Position& pos) const {
assert(pos.non_pawn_material(strongerSide) == KnightValueMidgame);
assert(pos.piece_count(strongerSide, KNIGHT) == 1);
@@ -841,7 +841,7 @@ ScaleFactor ScalingFunction<KNPK>::apply(const Position &pos) {
/// advanced and not on a rook file; in this case it is often possible to win
/// (e.g. 8/4k3/3p4/3P4/6K1/8/8/8 w - - 0 1).
template<>
ScaleFactor ScalingFunction<KPKP>::apply(const Position &pos) {
ScaleFactor ScalingFunction<KPKP>::apply(const Position& pos) const {
assert(pos.non_pawn_material(strongerSide) == Value(0));
assert(pos.non_pawn_material(weakerSide) == Value(0));

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -68,7 +68,7 @@ class EndgameFunctionBase {
public:
EndgameFunctionBase(Color c) : strongerSide(c), weakerSide(opposite_color(c)) {}
virtual ~EndgameFunctionBase() {}
virtual T apply(const Position&) = 0;
virtual T apply(const Position&) const = 0;
Color color() const { return strongerSide; }
protected:
@@ -85,14 +85,14 @@ template<EndgameType>
struct EvaluationFunction : public EndgameEvaluationFunctionBase {
typedef EndgameEvaluationFunctionBase Base;
explicit EvaluationFunction(Color c): EndgameEvaluationFunctionBase(c) {}
Value apply(const Position&);
Value apply(const Position&) const;
};
template<EndgameType>
struct ScalingFunction : public EndgameScalingFunctionBase {
typedef EndgameScalingFunctionBase Base;
explicit ScalingFunction(Color c) : EndgameScalingFunctionBase(c) {}
ScaleFactor apply(const Position&);
ScaleFactor apply(const Position&) const;
};

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -46,9 +46,11 @@ namespace {
const int GrainSize = 8;
// Evaluation weights, initialized from UCI options
Score WeightMobility, WeightPawnStructure;
Score WeightPassedPawns, WeightSpace;
Score WeightKingSafety[2];
enum { Mobility, PawnStructure, PassedPawns, Space, KingDangerUs, KingDangerThem };
Score Weights[6];
typedef Value V;
#define S(mg, eg) make_score(mg, eg)
// Internal evaluation weights. These are applied on top of the evaluation
// weights read from UCI parameters. The purpose is to be able to change
@@ -56,19 +58,9 @@ namespace {
// parameters at 100, which looks prettier.
//
// Values modified by Joona Kiiski
const Score WeightMobilityInternal = make_score(248, 271);
const Score WeightPawnStructureInternal = make_score(233, 201);
const Score WeightPassedPawnsInternal = make_score(252, 259);
const Score WeightSpaceInternal = make_score( 46, 0);
const Score WeightKingSafetyInternal = make_score(247, 0);
const Score WeightKingOppSafetyInternal = make_score(259, 0);
// Mobility and outposts bonus modified by Joona Kiiski
typedef Value V;
#define S(mg, eg) make_score(mg, eg)
CACHE_LINE_ALIGNMENT
const Score WeightsInternal[] = {
S(248, 271), S(233, 201), S(252, 259), S(46, 0), S(247, 0), S(259, 0)
};
// Knight mobility bonus in middle game and endgame, indexed by the number
// of attacked squares not occupied by friendly piecess.
@@ -138,28 +130,22 @@ namespace {
V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0) // 8
};
// ThreatBonus[][] contains bonus according to which piece type
// attacks which one.
#define Z S(0, 0)
// ThreatBonus[attacking][attacked] contains bonus according to which
// piece type attacks which one.
const Score ThreatBonus[8][8] = {
{ Z, Z, Z, Z, Z, Z, Z, Z }, // not used
{ Z, S(18,37), Z, S(37,47), S(55,97), S(55,97), Z, Z }, // KNIGHT attacks
{ Z, S(18,37), S(37,47), Z, S(55,97), S(55,97), Z, Z }, // BISHOP attacks
{ Z, S( 9,27), S(27,47), S(27,47), Z, S(37,47), Z, Z }, // ROOK attacks
{ Z, S(27,37), S(27,37), S(27,37), S(27,37), Z, Z, Z }, // QUEEN attacks
{ Z, Z, Z, Z, Z, Z, Z, Z }, // not used
{ Z, Z, Z, Z, Z, Z, Z, Z }, // not used
{ Z, Z, Z, Z, Z, Z, Z, Z } // not used
{}, {},
{ S(0, 0), S( 7, 39), S( 0, 0), S(24, 49), S(41,100), S(41,100) }, // KNIGHT
{ S(0, 0), S( 7, 39), S(24, 49), S( 0, 0), S(41,100), S(41,100) }, // BISHOP
{ S(0, 0), S(-1, 29), S(15, 49), S(15, 49), S( 0, 0), S(24, 49) }, // ROOK
{ S(0, 0), S(15, 39), S(15, 39), S(15, 39), S(15, 39), S( 0, 0) } // QUEEN
};
// ThreatedByPawnPenalty[] contains a penalty according to which piece
// type is attacked by an enemy pawn.
const Score ThreatedByPawnPenalty[8] = {
Z, Z, S(56, 70), S(56, 70), S(76, 99), S(86, 118), Z, Z
S(0, 0), S(0, 0), S(56, 70), S(56, 70), S(76, 99), S(86, 118)
};
#undef Z
#undef S
// Bonus for unstoppable passed pawns
@@ -211,28 +197,20 @@ namespace {
(1ULL<<SQ_C5) | (1ULL<<SQ_D5) | (1ULL<<SQ_E5) | (1ULL<<SQ_F5)
};
/// King safety constants and variables. The king safety scores are taken
/// from the array SafetyTable[]. Various little "meta-bonuses" measuring
/// the strength of the attack are added up into an integer, which is used
/// as an index to SafetyTable[].
/// King danger constants and variables. The king danger scores are taken
/// from the KingDangerTable[]. Various little "meta-bonuses" measuring
/// the strength of the enemy attack are added up into an integer, which
/// is used as an index to KingDangerTable[].
// Attack weights for each piece type and table indexed on piece type
const int QueenAttackWeight = 5;
const int RookAttackWeight = 3;
const int BishopAttackWeight = 2;
const int KnightAttackWeight = 2;
// KingAttackWeights[] contains king attack weights by piece type
const int KingAttackWeights[8] = { 0, 0, 2, 2, 3, 5 };
const int AttackWeight[] = { 0, 0, KnightAttackWeight, BishopAttackWeight, RookAttackWeight, QueenAttackWeight };
// Bonuses for safe checks, initialized from UCI options
int QueenContactCheckBonus, DiscoveredCheckBonus;
int QueenCheckBonus, RookCheckBonus, BishopCheckBonus, KnightCheckBonus;
// Scan for queen contact mates?
const bool QueenContactMates = true;
// Bonus for having a mate threat, initialized from UCI options
int MateThreatBonus;
// Bonuses for enemy's safe checks
const int QueenContactCheckBonus = 3;
const int QueenCheckBonus = 2;
const int RookCheckBonus = 1;
const int BishopCheckBonus = 1;
const int KnightCheckBonus = 1;
// InitKingDanger[] contains bonuses based on the position of the defending
// king.
@@ -247,13 +225,13 @@ namespace {
15, 15, 15, 15, 15, 15, 15, 15
};
// SafetyTable[] contains the actual king safety scores. It is initialized
// in init_safety().
Value SafetyTable[100];
// KingDangerTable[color][] contains the actual king danger weighted scores
Score KingDangerTable[2][128];
// Pawn and material hash tables, indexed by the current thread id
MaterialInfoTable* MaterialTable[8] = {0, 0, 0, 0, 0, 0, 0, 0};
PawnInfoTable* PawnTable[8] = {0, 0, 0, 0, 0, 0, 0, 0};
// Pawn and material hash tables, indexed by the current thread id.
// Note that they will be initialized at 0 being global variables.
MaterialInfoTable* MaterialTable[MAX_THREADS];
PawnInfoTable* PawnTable[MAX_THREADS];
// Sizes of pawn and material hash tables
const int PawnTableSize = 16384;
@@ -261,7 +239,10 @@ namespace {
// Function prototypes
template<bool HasPopCnt>
Value do_evaluate(const Position& pos, EvalInfo& ei, int threadID);
Value do_evaluate(const Position& pos, EvalInfo& ei);
template<Color Us, bool HasPopCnt>
void init_attack_tables(const Position& pos, EvalInfo& ei);
template<Color Us, bool HasPopCnt>
void evaluate_pieces_of_color(const Position& pos, EvalInfo& ei);
@@ -273,9 +254,12 @@ namespace {
void evaluate_threats(const Position& pos, EvalInfo& ei);
template<Color Us, bool HasPopCnt>
void evaluate_space(const Position& pos, EvalInfo& ei);
int evaluate_space(const Position& pos, EvalInfo& ei);
template<Color Us>
void evaluate_passed_pawns(const Position& pos, EvalInfo& ei);
void evaluate_unstoppable_pawns(const Position& pos, EvalInfo& ei);
void evaluate_trapped_bishop_a7h7(const Position& pos, Square s, Color us, EvalInfo& ei);
void evaluate_trapped_bishop_a1h1(const Position& pos, Square s, Color us, EvalInfo& ei);
inline Score apply_weight(Score v, Score weight);
@@ -292,19 +276,21 @@ namespace {
/// evaluate() is the main evaluation function. It always computes two
/// values, an endgame score and a middle game score, and interpolates
/// between them based on the remaining material.
Value evaluate(const Position& pos, EvalInfo& ei, int threadID) {
Value evaluate(const Position& pos, EvalInfo& ei) {
return CpuHasPOPCNT ? do_evaluate<true>(pos, ei, threadID)
: do_evaluate<false>(pos, ei, threadID);
return CpuHasPOPCNT ? do_evaluate<true>(pos, ei)
: do_evaluate<false>(pos, ei);
}
namespace {
template<bool HasPopCnt>
Value do_evaluate(const Position& pos, EvalInfo& ei, int threadID) {
Value do_evaluate(const Position& pos, EvalInfo& ei) {
ScaleFactor factor[2];
assert(pos.is_ok());
assert(threadID >= 0 && threadID < THREAD_MAX);
assert(pos.thread() >= 0 && pos.thread() < MAX_THREADS);
assert(!pos.is_check());
memset(&ei, 0, sizeof(EvalInfo));
@@ -314,7 +300,7 @@ Value do_evaluate(const Position& pos, EvalInfo& ei, int threadID) {
ei.value = pos.value();
// Probe the material hash table
ei.mi = MaterialTable[threadID]->get_material_info(pos);
ei.mi = MaterialTable[pos.thread()]->get_material_info(pos);
ei.value += ei.mi->material_value();
// If we have a specialized evaluation function for the current material
@@ -323,30 +309,16 @@ Value do_evaluate(const Position& pos, EvalInfo& ei, int threadID) {
return ei.mi->evaluate(pos);
// After get_material_info() call that modifies them
ScaleFactor factor[2];
factor[WHITE] = ei.mi->scale_factor(pos, WHITE);
factor[BLACK] = ei.mi->scale_factor(pos, BLACK);
// Probe the pawn hash table
ei.pi = PawnTable[threadID]->get_pawn_info(pos);
ei.value += apply_weight(ei.pi->pawns_value(), WeightPawnStructure);
ei.pi = PawnTable[pos.thread()]->get_pawn_info(pos);
ei.value += apply_weight(ei.pi->pawns_value(), Weights[PawnStructure]);
// Initialize king attack bitboards and king attack zones for both sides
ei.attackedBy[WHITE][KING] = pos.attacks_from<KING>(pos.king_square(WHITE));
ei.attackedBy[BLACK][KING] = pos.attacks_from<KING>(pos.king_square(BLACK));
ei.kingZone[WHITE] = ei.attackedBy[BLACK][KING] | (ei.attackedBy[BLACK][KING] >> 8);
ei.kingZone[BLACK] = ei.attackedBy[WHITE][KING] | (ei.attackedBy[WHITE][KING] << 8);
// Initialize pawn attack bitboards for both sides
ei.attackedBy[WHITE][PAWN] = ei.pi->pawn_attacks(WHITE);
ei.attackedBy[BLACK][PAWN] = ei.pi->pawn_attacks(BLACK);
Bitboard b1 = ei.attackedBy[WHITE][PAWN] & ei.attackedBy[BLACK][KING];
Bitboard b2 = ei.attackedBy[BLACK][PAWN] & ei.attackedBy[WHITE][KING];
if (b1)
ei.kingAttackersCount[WHITE] = count_1s_max_15<HasPopCnt>(b1)/2;
if (b2)
ei.kingAttackersCount[BLACK] = count_1s_max_15<HasPopCnt>(b2)/2;
// Initialize attack bitboards with pawns evaluation
init_attack_tables<WHITE, HasPopCnt>(pos, ei);
init_attack_tables<BLACK, HasPopCnt>(pos, ei);
// Evaluate pieces
evaluate_pieces_of_color<WHITE, HasPopCnt>(pos, ei);
@@ -358,43 +330,44 @@ Value do_evaluate(const Position& pos, EvalInfo& ei, int threadID) {
evaluate_king<WHITE, HasPopCnt>(pos, ei);
evaluate_king<BLACK, HasPopCnt>(pos, ei);
// Evaluate tactical threats, we need full attack info
// Evaluate tactical threats, we need full attack info including king
evaluate_threats<WHITE>(pos, ei);
evaluate_threats<BLACK>(pos, ei);
// Evaluate passed pawns. We evaluate passed pawns for both sides at once,
// because we need to know which side promotes first in positions where
// both sides have an unstoppable passed pawn. To be called after all attacks
// are computed, included king.
if (ei.pi->passed_pawns())
evaluate_passed_pawns(pos, ei);
// Evaluate passed pawns, we need full attack info including king
evaluate_passed_pawns<WHITE>(pos, ei);
evaluate_passed_pawns<BLACK>(pos, ei);
// If one side has only a king, check whether exsists any unstoppable passed pawn
if (!pos.non_pawn_material(WHITE) || !pos.non_pawn_material(BLACK))
evaluate_unstoppable_pawns(pos, ei);
Phase phase = ei.mi->game_phase();
// Middle-game specific evaluation terms
if (phase > PHASE_ENDGAME)
{
// Pawn storms in positions with opposite castling.
if ( square_file(pos.king_square(WHITE)) >= FILE_E
&& square_file(pos.king_square(BLACK)) <= FILE_D)
// Pawn storms in positions with opposite castling
if ( square_file(pos.king_square(WHITE)) >= FILE_E
&& square_file(pos.king_square(BLACK)) <= FILE_D)
ei.value += make_score(ei.pi->queenside_storm_value(WHITE) - ei.pi->kingside_storm_value(BLACK), 0);
ei.value += make_score(ei.pi->queenside_storm_value(WHITE) - ei.pi->kingside_storm_value(BLACK), 0);
else if ( square_file(pos.king_square(WHITE)) <= FILE_D
&& square_file(pos.king_square(BLACK)) >= FILE_E)
else if ( square_file(pos.king_square(WHITE)) <= FILE_D
&& square_file(pos.king_square(BLACK)) >= FILE_E)
ei.value += make_score(ei.pi->kingside_storm_value(WHITE) - ei.pi->queenside_storm_value(BLACK), 0);
ei.value += make_score(ei.pi->kingside_storm_value(WHITE) - ei.pi->queenside_storm_value(BLACK), 0);
// Evaluate space for both sides
if (ei.mi->space_weight() > 0)
{
evaluate_space<WHITE, HasPopCnt>(pos, ei);
evaluate_space<BLACK, HasPopCnt>(pos, ei);
}
// Evaluate space for both sides
if (ei.mi->space_weight() > 0)
{
int s = evaluate_space<WHITE, HasPopCnt>(pos, ei) - evaluate_space<BLACK, HasPopCnt>(pos, ei);
ei.value += apply_weight(make_score(s * ei.mi->space_weight(), 0), Weights[Space]);
}
}
// Mobility
ei.value += apply_weight(ei.mobility, WeightMobility);
ei.value += apply_weight(ei.mobility, Weights[Mobility]);
// If we don't already have an unusual scale factor, check for opposite
// colored bishop endgames, and use a lower scale for those
@@ -426,37 +399,18 @@ Value do_evaluate(const Position& pos, EvalInfo& ei, int threadID) {
}
// Interpolate between the middle game and the endgame score
Color stm = pos.side_to_move();
Value v = Sign[stm] * scale_by_game_phase(ei.value, phase, factor);
return (ei.mateThreat[stm] == MOVE_NONE ? v : 8 * QueenValueMidgame - v);
return Sign[pos.side_to_move()] * scale_by_game_phase(ei.value, phase, factor);
}
} // namespace
/// quick_evaluate() does a very approximate evaluation of the current position.
/// It currently considers only material and piece square table scores. Perhaps
/// we should add scores from the pawn and material hash tables?
Value quick_evaluate(const Position &pos) {
assert(pos.is_ok());
static const ScaleFactor sf[2] = {SCALE_FACTOR_NORMAL, SCALE_FACTOR_NORMAL};
Value v = scale_by_game_phase(pos.value(), MaterialInfoTable::game_phase(pos), sf);
return (pos.side_to_move() == WHITE ? v : -v);
}
/// init_eval() initializes various tables used by the evaluation function
void init_eval(int threads) {
assert(threads <= THREAD_MAX);
assert(threads <= MAX_THREADS);
for (int i = 0; i < THREAD_MAX; i++)
for (int i = 0; i < MAX_THREADS; i++)
{
if (i >= threads)
{
@@ -478,7 +432,7 @@ void init_eval(int threads) {
void quit_eval() {
for (int i = 0; i < THREAD_MAX; i++)
for (int i = 0; i < MAX_THREADS; i++)
{
delete PawnTable[i];
delete MaterialTable[i];
@@ -492,28 +446,46 @@ void quit_eval() {
void read_weights(Color us) {
Color them = opposite_color(us);
// King safety is asymmetrical. Our king danger level is weighted by
// "Cowardice" UCI parameter, instead the opponent one by "Aggressiveness".
const int kingDangerUs = (us == WHITE ? KingDangerUs : KingDangerThem);
const int kingDangerThem = (us == WHITE ? KingDangerThem : KingDangerUs);
WeightMobility = weight_option("Mobility (Middle Game)", "Mobility (Endgame)", WeightMobilityInternal);
WeightPawnStructure = weight_option("Pawn Structure (Middle Game)", "Pawn Structure (Endgame)", WeightPawnStructureInternal);
WeightPassedPawns = weight_option("Passed Pawns (Middle Game)", "Passed Pawns (Endgame)", WeightPassedPawnsInternal);
WeightSpace = weight_option("Space", "Space", WeightSpaceInternal);
WeightKingSafety[us] = weight_option("Cowardice", "Cowardice", WeightKingSafetyInternal);
WeightKingSafety[them] = weight_option("Aggressiveness", "Aggressiveness", WeightKingOppSafetyInternal);
Weights[Mobility] = weight_option("Mobility (Middle Game)", "Mobility (Endgame)", WeightsInternal[Mobility]);
Weights[PawnStructure] = weight_option("Pawn Structure (Middle Game)", "Pawn Structure (Endgame)", WeightsInternal[PawnStructure]);
Weights[PassedPawns] = weight_option("Passed Pawns (Middle Game)", "Passed Pawns (Endgame)", WeightsInternal[PassedPawns]);
Weights[Space] = weight_option("Space", "Space", WeightsInternal[Space]);
Weights[kingDangerUs] = weight_option("Cowardice", "Cowardice", WeightsInternal[KingDangerUs]);
Weights[kingDangerThem] = weight_option("Aggressiveness", "Aggressiveness", WeightsInternal[KingDangerThem]);
// If running in analysis mode, make sure we use symmetrical king safety. We do this
// by replacing both WeightKingSafety[us] and WeightKingSafety[them] by their average.
// by replacing both Weights[kingDangerUs] and Weights[kingDangerThem] by their average.
if (get_option_value_bool("UCI_AnalyseMode"))
{
WeightKingSafety[us] = (WeightKingSafety[us] + WeightKingSafety[them]) / 2;
WeightKingSafety[them] = WeightKingSafety[us];
}
Weights[kingDangerUs] = Weights[kingDangerThem] = (Weights[kingDangerUs] + Weights[kingDangerThem]) / 2;
init_safety();
}
namespace {
// init_attack_tables() initializes king bitboards for both sides adding
// pawn attacks. To be done before other evaluations.
template<Color Us, bool HasPopCnt>
void init_attack_tables(const Position& pos, EvalInfo& ei) {
const Color Them = (Us == WHITE ? BLACK : WHITE);
Bitboard b = ei.attackedBy[Them][KING] = pos.attacks_from<KING>(pos.king_square(Them));
ei.kingZone[Us] = (b | (Us == WHITE ? b >> 8 : b << 8));
ei.attackedBy[Us][PAWN] = ei.pi->pawn_attacks(Us);
b &= ei.attackedBy[Us][PAWN];
if (b)
ei.kingAttackersCount[Us] = count_1s_max_15<HasPopCnt>(b) / 2;
}
// evaluate_outposts() evaluates bishop and knight outposts squares
template<PieceType Piece, Color Us>
@@ -571,7 +543,7 @@ namespace {
if (b & ei.kingZone[Us])
{
ei.kingAttackersCount[Us]++;
ei.kingAttackersWeight[Us] += AttackWeight[Piece];
ei.kingAttackersWeight[Us] += KingAttackWeights[Piece];
Bitboard bb = (b & ei.attackedBy[Them][KING]);
if (bb)
ei.kingAdjacentZoneAttacksCount[Us] += count_1s_max_15<HasPopCnt>(bb);
@@ -589,7 +561,7 @@ namespace {
ei.value -= Sign[Us] * ThreatedByPawnPenalty[Piece];
// Bishop and knight outposts squares
if ((Piece == BISHOP || Piece == KNIGHT) && pos.square_is_weak(s, Them))
if ((Piece == BISHOP || Piece == KNIGHT) && pos.square_is_weak(s, Us))
evaluate_outposts<Piece, Us>(pos, ei, s);
// Special patterns: trapped bishops on a7/h7/a2/h2
@@ -717,279 +689,170 @@ namespace {
const Color Them = (Us == WHITE ? BLACK : WHITE);
Bitboard undefended, attackedByOthers, escapeSquares, occ, b, b2, safe;
Square from, to;
Bitboard undefended, b, b1, b2, safe;
bool sente;
int attackUnits, count, shelter = 0;
const Square s = pos.king_square(Us);
int attackUnits, shelter = 0;
const Square ksq = pos.king_square(Us);
// King shelter
if (relative_rank(Us, s) <= RANK_4)
if (relative_rank(Us, ksq) <= RANK_4)
{
shelter = ei.pi->get_king_shelter(pos, Us, s);
shelter = ei.pi->get_king_shelter(pos, Us, ksq);
ei.value += Sign[Us] * make_score(shelter, 0);
}
// King safety. This is quite complicated, and is almost certainly far
// from optimally tuned.
if ( pos.piece_count(Them, QUEEN) >= 1
&& ei.kingAttackersCount[Them] >= 2
&& pos.non_pawn_material(Them) >= QueenValueMidgame + RookValueMidgame
&& ei.kingAttackersCount[Them] >= 2
&& pos.non_pawn_material(Them) >= QueenValueMidgame + RookValueMidgame
&& ei.kingAdjacentZoneAttacksCount[Them])
{
// Is it the attackers turn to move?
sente = (Them == pos.side_to_move());
// Is it the attackers turn to move?
sente = (Them == pos.side_to_move());
// Find the attacked squares around the king which has no defenders
// apart from the king itself
undefended = ei.attacked_by(Them) & ei.attacked_by(Us, KING);
undefended &= ~( ei.attacked_by(Us, PAWN) | ei.attacked_by(Us, KNIGHT)
| ei.attacked_by(Us, BISHOP) | ei.attacked_by(Us, ROOK)
| ei.attacked_by(Us, QUEEN));
// Find the attacked squares around the king which has no defenders
// apart from the king itself
undefended = ei.attacked_by(Them) & ei.attacked_by(Us, KING);
undefended &= ~( ei.attacked_by(Us, PAWN) | ei.attacked_by(Us, KNIGHT)
| ei.attacked_by(Us, BISHOP) | ei.attacked_by(Us, ROOK)
| ei.attacked_by(Us, QUEEN));
// Initialize the 'attackUnits' variable, which is used later on as an
// index to the SafetyTable[] array. The initial value is based on the
// number and types of the attacking pieces, the number of attacked and
// undefended squares around the king, the square of the king, and the
// quality of the pawn shelter.
attackUnits = Min(25, (ei.kingAttackersCount[Them] * ei.kingAttackersWeight[Them]) / 2)
+ 3 * (ei.kingAdjacentZoneAttacksCount[Them] + count_1s_max_15<HasPopCnt>(undefended))
+ InitKingDanger[relative_square(Us, s)]
- (shelter >> 5);
// Initialize the 'attackUnits' variable, which is used later on as an
// index to the KingDangerTable[] array. The initial value is based on
// the number and types of the enemy's attacking pieces, the number of
// attacked and undefended squares around our king, the square of the
// king, and the quality of the pawn shelter.
attackUnits = Min(25, (ei.kingAttackersCount[Them] * ei.kingAttackersWeight[Them]) / 2)
+ 3 * (ei.kingAdjacentZoneAttacksCount[Them] + count_1s_max_15<HasPopCnt>(undefended))
+ InitKingDanger[relative_square(Us, ksq)]
- shelter / 32;
// Analyse safe queen contact checks
b = undefended & ei.attacked_by(Them, QUEEN) & ~pos.pieces_of_color(Them);
if (b)
{
attackedByOthers = ei.attacked_by(Them, PAWN) | ei.attacked_by(Them, KNIGHT)
| ei.attacked_by(Them, BISHOP) | ei.attacked_by(Them, ROOK);
b &= attackedByOthers;
// Squares attacked by the queen and supported by another enemy piece and
// not defended by other pieces but our king.
// Analyse enemy's safe queen contact checks. First find undefended
// squares around the king attacked by enemy queen...
b = undefended & ei.attacked_by(Them, QUEEN) & ~pos.pieces_of_color(Them);
if (b)
{
// The bitboard b now contains the squares available for safe queen
// contact checks.
count = count_1s_max_15<HasPopCnt>(b);
attackUnits += QueenContactCheckBonus * count * (sente ? 2 : 1);
// Is there a mate threat?
if (QueenContactMates && !pos.is_check())
{
escapeSquares = pos.attacks_from<KING>(s) & ~pos.pieces_of_color(Us) & ~attackedByOthers;
occ = pos.occupied_squares();
while (b)
{
to = pop_1st_bit(&b);
// Do we have escape squares from queen contact check attack ?
if (!(escapeSquares & ~queen_attacks_bb(to, occ & ClearMaskBB[s])))
{
// We have a mate, unless the queen is pinned or there
// is an X-ray attack through the queen.
for (int i = 0; i < pos.piece_count(Them, QUEEN); i++)
{
from = pos.piece_list(Them, QUEEN, i);
if ( bit_is_set(pos.attacks_from<QUEEN>(from), to)
&& !bit_is_set(pos.pinned_pieces(Them), from)
&& !(rook_attacks_bb(to, occ & ClearMaskBB[from]) & pos.pieces(ROOK, QUEEN, Us))
&& !(bishop_attacks_bb(to, occ & ClearMaskBB[from]) & pos.pieces(BISHOP, QUEEN, Us)))
// Set the mate threat move
ei.mateThreat[Them] = make_move(from, to);
}
}
}
}
// ...then remove squares not supported by another enemy piece
b &= ( ei.attacked_by(Them, PAWN) | ei.attacked_by(Them, KNIGHT)
| ei.attacked_by(Them, BISHOP) | ei.attacked_by(Them, ROOK));
if (b)
attackUnits += QueenContactCheckBonus * count_1s_max_15<HasPopCnt>(b) * (sente ? 2 : 1);
}
}
// Analyse safe distance checks
safe = ~(pos.pieces_of_color(Them) | ei.attacked_by(Us));
// Analyse enemy's safe distance checks for sliders and knights
safe = ~(pos.pieces_of_color(Them) | ei.attacked_by(Us));
if (QueenCheckBonus > 0 || RookCheckBonus > 0)
{
b = pos.attacks_from<ROOK>(s) & safe;
b1 = pos.attacks_from<ROOK>(ksq) & safe;
b2 = pos.attacks_from<BISHOP>(ksq) & safe;
// Queen checks
b2 = b & ei.attacked_by(Them, QUEEN);
if (b2)
attackUnits += QueenCheckBonus * count_1s_max_15<HasPopCnt>(b2);
// Enemy queen safe checks
b = (b1 | b2) & ei.attacked_by(Them, QUEEN);
if (b)
attackUnits += QueenCheckBonus * count_1s_max_15<HasPopCnt>(b);
// Rook checks
b2 = b & ei.attacked_by(Them, ROOK);
if (b2)
attackUnits += RookCheckBonus * count_1s_max_15<HasPopCnt>(b2);
}
if (QueenCheckBonus > 0 || BishopCheckBonus > 0)
{
b = pos.attacks_from<BISHOP>(s) & safe;
// Enemy rooks safe checks
b = b1 & ei.attacked_by(Them, ROOK);
if (b)
attackUnits += RookCheckBonus * count_1s_max_15<HasPopCnt>(b);
// Queen checks
b2 = b & ei.attacked_by(Them, QUEEN);
if (b2)
attackUnits += QueenCheckBonus * count_1s_max_15<HasPopCnt>(b2);
// Enemy bishops safe checks
b = b2 & ei.attacked_by(Them, BISHOP);
if (b)
attackUnits += BishopCheckBonus * count_1s_max_15<HasPopCnt>(b);
// Bishop checks
b2 = b & ei.attacked_by(Them, BISHOP);
if (b2)
attackUnits += BishopCheckBonus * count_1s_max_15<HasPopCnt>(b2);
}
if (KnightCheckBonus > 0)
{
b = pos.attacks_from<KNIGHT>(s) & safe;
// Enemy knights safe checks
b = pos.attacks_from<KNIGHT>(ksq) & ei.attacked_by(Them, KNIGHT) & safe;
if (b)
attackUnits += KnightCheckBonus * count_1s_max_15<HasPopCnt>(b);
// Knight checks
b2 = b & ei.attacked_by(Them, KNIGHT);
if (b2)
attackUnits += KnightCheckBonus * count_1s_max_15<HasPopCnt>(b2);
}
// To index KingDangerTable[] attackUnits must be in [0, 99] range
attackUnits = Min(99, Max(0, attackUnits));
// Analyse discovered checks (only for non-pawns right now, consider
// adding pawns later).
if (DiscoveredCheckBonus)
{
b = pos.discovered_check_candidates(Them) & ~pos.pieces(PAWN);
if (b)
attackUnits += DiscoveredCheckBonus * count_1s_max_15<HasPopCnt>(b) * (sente ? 2 : 1);
}
// Has a mate threat been found? We don't do anything here if the
// side with the mating move is the side to move, because in that
// case the mating side will get a huge bonus at the end of the main
// evaluation function instead.
if (ei.mateThreat[Them] != MOVE_NONE)
attackUnits += MateThreatBonus;
// Ensure that attackUnits is between 0 and 99, in order to avoid array
// out of bounds errors.
attackUnits = Min(99, Max(0, attackUnits));
// Finally, extract the king safety score from the SafetyTable[] array.
// Add the score to the evaluation, and also to ei.futilityMargin. The
// reason for adding the king safety score to the futility margin is
// that the king safety scores can sometimes be very big, and that
// capturing a single attacking piece can therefore result in a score
// change far bigger than the value of the captured piece.
Score v = apply_weight(make_score(SafetyTable[attackUnits], 0), WeightKingSafety[Us]);
ei.value -= Sign[Us] * v;
if (Us == pos.side_to_move())
ei.futilityMargin += mg_value(v);
// Finally, extract the king danger score from the KingDangerTable[]
// array and subtract the score from evaluation. Set also ei.kingDanger[]
// value that will be used for pruning because this value can sometimes
// be very big, and so capturing a single attacking piece can therefore
// result in a score change far bigger than the value of the captured piece.
ei.value -= Sign[Us] * KingDangerTable[Us][attackUnits];
ei.kingDanger[Us] = mg_value(KingDangerTable[Us][attackUnits]);
}
}
// evaluate_passed_pawns() evaluates the passed pawns of the given color
// evaluate_passed_pawns<>() evaluates the passed pawns of the given color
template<Color Us>
void evaluate_passed_pawns_of_color(const Position& pos, int movesToGo[], Square pawnToGo[], EvalInfo& ei) {
void evaluate_passed_pawns(const Position& pos, EvalInfo& ei) {
const Color Them = (Us == WHITE ? BLACK : WHITE);
Bitboard b2, b3, b4;
Square ourKingSq = pos.king_square(Us);
Square theirKingSq = pos.king_square(Them);
Bitboard b = ei.pi->passed_pawns() & pos.pieces(PAWN, Us);
Bitboard squaresToQueen, defendedSquares, unsafeSquares, supportingPawns;
Bitboard b = ei.pi->passed_pawns() & pos.pieces_of_color(Us);
while (b)
{
Square s = pop_1st_bit(&b);
assert(pos.piece_on(s) == piece_of_color_and_type(Us, PAWN));
assert(pos.pawn_is_passed(Us, s));
int r = int(relative_rank(Us, s) - RANK_2);
int tr = Max(0, r * (r - 1));
int tr = r * (r - 1);
// Base bonus based on rank
Value mbonus = Value(20 * tr);
Value ebonus = Value(10 + r * r * 10);
// Adjust bonus based on king proximity
if (tr)
{
Square blockSq = s + pawn_push(Us);
ebonus -= Value(square_distance(ourKingSq, blockSq) * 3 * tr);
ebonus -= Value(square_distance(ourKingSq, blockSq + pawn_push(Us)) * 1 * tr);
ebonus += Value(square_distance(theirKingSq, blockSq) * 6 * tr);
// Adjust bonus based on kings proximity
ebonus -= Value(square_distance(pos.king_square(Us), blockSq) * 3 * tr);
ebonus -= Value(square_distance(pos.king_square(Us), blockSq + pawn_push(Us)) * 1 * tr);
ebonus += Value(square_distance(pos.king_square(Them), blockSq) * 6 * tr);
// If the pawn is free to advance, increase bonus
if (pos.square_is_empty(blockSq))
{
// There are no enemy pawns in the pawn's path
b2 = squares_in_front_of(Us, s);
assert((b2 & pos.pieces(PAWN, Them)) == EmptyBoardBB);
// Squares attacked by us
b4 = b2 & ei.attacked_by(Us);
// Squares attacked or occupied by enemy pieces
b3 = b2 & (ei.attacked_by(Them) | pos.pieces_of_color(Them));
squaresToQueen = squares_in_front_of(Us, s);
defendedSquares = squaresToQueen & ei.attacked_by(Us);
// If there is an enemy rook or queen attacking the pawn from behind,
// add all X-ray attacks by the rook or queen.
// add all X-ray attacks by the rook or queen. Otherwise consider only
// the squares in the pawn's path attacked or occupied by the enemy.
if ( (squares_behind(Us, s) & pos.pieces(ROOK, QUEEN, Them))
&& (squares_behind(Us, s) & pos.pieces(ROOK, QUEEN, Them) & pos.attacks_from<QUEEN>(s)))
b3 = b2;
unsafeSquares = squaresToQueen;
else
unsafeSquares = squaresToQueen & (ei.attacked_by(Them) | pos.pieces_of_color(Them));
// Are any of the squares in the pawn's path attacked or occupied by the enemy?
if (b3 == EmptyBoardBB)
// No enemy attacks or pieces, huge bonus!
// Even bigger if we protect the pawn's path
ebonus += Value(tr * (b2 == b4 ? 17 : 15));
// If there aren't enemy attacks or pieces along the path to queen give
// huge bonus. Even bigger if we protect the pawn's path.
if (!unsafeSquares)
ebonus += Value(tr * (squaresToQueen == defendedSquares ? 17 : 15));
else
// OK, there are enemy attacks or pieces (but not pawns). Are those
// squares which are attacked by the enemy also attacked by us ?
// If yes, big bonus (but smaller than when there are no enemy attacks),
// if no, somewhat smaller bonus.
ebonus += Value(tr * ((b3 & b4) == b3 ? 13 : 8));
ebonus += Value(tr * ((unsafeSquares & defendedSquares) == unsafeSquares ? 13 : 8));
// At last, add a small bonus when there are no *friendly* pieces
// in the pawn's path.
if ((b2 & pos.pieces_of_color(Us)) == EmptyBoardBB)
if (!(squaresToQueen & pos.pieces_of_color(Us)))
ebonus += Value(tr);
}
} // tr != 0
// If the pawn is supported by a friendly pawn, increase bonus
b2 = pos.pieces(PAWN, Us) & neighboring_files_bb(s);
if (b2 & rank_bb(s))
// Increase the bonus if the passed pawn is supported by a friendly pawn
// on the same rank and a bit smaller if it's on the previous rank.
supportingPawns = pos.pieces(PAWN, Us) & neighboring_files_bb(s);
if (supportingPawns & rank_bb(s))
ebonus += Value(r * 20);
else if (pos.attacks_from<PAWN>(s, Them) & b2)
else if (supportingPawns & rank_bb(s - pawn_push(Us)))
ebonus += Value(r * 12);
// If the other side has only a king, check whether the pawn is
// unstoppable
if (pos.non_pawn_material(Them) == Value(0))
{
Square qsq;
int d;
qsq = relative_square(Us, make_square(square_file(s), RANK_8));
d = square_distance(s, qsq)
- square_distance(theirKingSq, qsq)
+ (Us != pos.side_to_move());
if (d < 0)
{
int mtg = RANK_8 - relative_rank(Us, s);
int blockerCount = count_1s_max_15(squares_in_front_of(Us,s) & pos.occupied_squares());
mtg += blockerCount;
d += blockerCount;
if (d < 0 && (!movesToGo[Us] || movesToGo[Us] > mtg))
{
movesToGo[Us] = mtg;
pawnToGo[Us] = s;
}
}
}
// Rook pawns are a special case: They are sometimes worse, and
// sometimes better than other passed pawns. It is difficult to find
// good rules for determining whether they are good or bad. For now,
@@ -998,30 +861,60 @@ namespace {
// value if the other side has a rook or queen.
if (square_file(s) == FILE_A || square_file(s) == FILE_H)
{
if ( pos.non_pawn_material(Them) <= KnightValueMidgame
&& pos.piece_count(Them, KNIGHT) <= 1)
if (pos.non_pawn_material(Them) <= KnightValueMidgame)
ebonus += ebonus / 4;
else if (pos.pieces(ROOK, QUEEN, Them))
ebonus -= ebonus / 4;
}
// Add the scores for this pawn to the middle game and endgame eval.
ei.value += Sign[Us] * apply_weight(make_score(mbonus, ebonus), WeightPassedPawns);
// Add the scores for this pawn to the middle game and endgame eval
ei.value += Sign[Us] * apply_weight(make_score(mbonus, ebonus), Weights[PassedPawns]);
} // while
}
// evaluate_passed_pawns() evaluates the passed pawns for both sides
// evaluate_unstoppable_pawns() evaluates the unstoppable passed pawns for both sides
void evaluate_passed_pawns(const Position& pos, EvalInfo& ei) {
void evaluate_unstoppable_pawns(const Position& pos, EvalInfo& ei) {
int movesToGo[2] = {0, 0};
Square pawnToGo[2] = {SQ_NONE, SQ_NONE};
// Evaluate pawns for each color
evaluate_passed_pawns_of_color<WHITE>(pos, movesToGo, pawnToGo, ei);
evaluate_passed_pawns_of_color<BLACK>(pos, movesToGo, pawnToGo, ei);
for (Color c = WHITE; c <= BLACK; c++)
{
// Skip evaluation if other side has non-pawn pieces
if (pos.non_pawn_material(opposite_color(c)))
continue;
Bitboard b = ei.pi->passed_pawns() & pos.pieces_of_color(c);
while (b)
{
Square s = pop_1st_bit(&b);
Square queeningSquare = relative_square(c, make_square(square_file(s), RANK_8));
int d = square_distance(s, queeningSquare)
- (relative_rank(c, s) == RANK_2) // Double pawn push
- square_distance(pos.king_square(opposite_color(c)), queeningSquare)
+ int(c != pos.side_to_move());
// Do we protect the path to queening ?
bool pathDefended = (ei.attacked_by(c) & squares_in_front_of(c, s)) == squares_in_front_of(c, s);
if (d < 0 || pathDefended)
{
int mtg = RANK_8 - relative_rank(c, s);
int blockerCount = count_1s_max_15(squares_in_front_of(c, s) & pos.occupied_squares());
mtg += blockerCount;
d += blockerCount;
if ((d < 0 || pathDefended) && (!movesToGo[c] || movesToGo[c] > mtg))
{
movesToGo[c] = mtg;
pawnToGo[c] = s;
}
}
}
}
// Neither side has an unstoppable passed pawn?
if (!(movesToGo[WHITE] | movesToGo[BLACK]))
@@ -1144,29 +1037,24 @@ namespace {
// twice. Finally, the space bonus is scaled by a weight taken from the
// material hash table.
template<Color Us, bool HasPopCnt>
void evaluate_space(const Position& pos, EvalInfo& ei) {
int evaluate_space(const Position& pos, EvalInfo& ei) {
const Color Them = (Us == WHITE ? BLACK : WHITE);
// Find the safe squares for our pieces inside the area defined by
// SpaceMask[us]. A square is unsafe if it is attacked by an enemy
// pawn, or if it is undefended and attacked by an enemy piece.
Bitboard safe = SpaceMask[Us]
& ~pos.pieces(PAWN, Us)
& ~ei.attacked_by(Them, PAWN)
& (ei.attacked_by(Us) | ~ei.attacked_by(Them));
Bitboard safeSquares = SpaceMask[Us]
& ~pos.pieces(PAWN, Us)
& ~ei.attacked_by(Them, PAWN)
& ~(~ei.attacked_by(Us) & ei.attacked_by(Them));
// Find all squares which are at most three squares behind some friendly pawn
Bitboard behind = pos.pieces(PAWN, Us);
behind |= (Us == WHITE ? behind >> 8 : behind << 8);
behind |= (Us == WHITE ? behind >> 16 : behind << 16);
// Find all squares which are at most three squares behind some friendly
// pawn.
Bitboard behindFriendlyPawns = pos.pieces(PAWN, Us);
behindFriendlyPawns |= (Us == WHITE ? behindFriendlyPawns >> 8 : behindFriendlyPawns << 8);
behindFriendlyPawns |= (Us == WHITE ? behindFriendlyPawns >> 16 : behindFriendlyPawns << 16);
int space = count_1s_max_15<HasPopCnt>(safeSquares)
+ count_1s_max_15<HasPopCnt>(behindFriendlyPawns & safeSquares);
ei.value += Sign[Us] * apply_weight(make_score(space * ei.mi->space_weight(), 0), WeightSpace);
return count_1s_max_15<HasPopCnt>(safe) + count_1s_max_15<HasPopCnt>(behind & safe);
}
@@ -1199,57 +1087,36 @@ namespace {
Score weight_option(const std::string& mgOpt, const std::string& egOpt, Score internalWeight) {
Score uciWeight = make_score(get_option_value_int(mgOpt), get_option_value_int(egOpt));
// Scale option value from 100 to 256
int mg = get_option_value_int(mgOpt) * 256 / 100;
int eg = get_option_value_int(egOpt) * 256 / 100;
// Convert to integer to prevent overflow
int mg = mg_value(uciWeight);
int eg = eg_value(uciWeight);
mg = (mg * 0x100) / 100;
eg = (eg * 0x100) / 100;
mg = (mg * mg_value(internalWeight)) / 0x100;
eg = (eg * eg_value(internalWeight)) / 0x100;
return make_score(mg, eg);
return apply_weight(make_score(mg, eg), internalWeight);
}
// init_safety() initizes the king safety evaluation, based on UCI
// parameters. It is called from read_weights().
// parameters. It is called from read_weights().
void init_safety() {
QueenContactCheckBonus = get_option_value_int("Queen Contact Check Bonus");
QueenCheckBonus = get_option_value_int("Queen Check Bonus");
RookCheckBonus = get_option_value_int("Rook Check Bonus");
BishopCheckBonus = get_option_value_int("Bishop Check Bonus");
KnightCheckBonus = get_option_value_int("Knight Check Bonus");
DiscoveredCheckBonus = get_option_value_int("Discovered Check Bonus");
MateThreatBonus = get_option_value_int("Mate Threat Bonus");
int maxSlope = get_option_value_int("King Safety Max Slope");
int peak = get_option_value_int("King Safety Max Value") * 256 / 100;
double a = get_option_value_int("King Safety Coefficient") / 100.0;
double b = get_option_value_int("King Safety X Intercept");
bool quad = (get_option_value_string("King Safety Curve") == "Quadratic");
bool linear = (get_option_value_string("King Safety Curve") == "Linear");
const Value MaxSlope = Value(30);
const Value Peak = Value(1280);
Value t[100];
// First setup the base table
for (int i = 0; i < 100; i++)
{
if (i < b)
SafetyTable[i] = Value(0);
else if (quad)
SafetyTable[i] = Value((int)(a * (i - b) * (i - b)));
else if (linear)
SafetyTable[i] = Value((int)(100 * a * (i - b)));
t[i] = Value(int(0.4 * i * i));
if (i > 0)
t[i] = Min(t[i], t[i - 1] + MaxSlope);
t[i] = Min(t[i], Peak);
}
for (int i = 0; i < 100; i++)
{
if (SafetyTable[i+1] - SafetyTable[i] > maxSlope)
for (int j = i + 1; j < 100; j++)
SafetyTable[j] = SafetyTable[j-1] + Value(maxSlope);
if (SafetyTable[i] > Value(peak))
SafetyTable[i] = Value(peak);
}
// Then apply the weights and get the final KingDangerTable[] array
for (Color c = WHITE; c <= BLACK; c++)
for (int i = 0; i < 100; i++)
KingDangerTable[c][i] = apply_weight(make_score(t[i], 0), Weights[KingDangerUs + c]);
}
}

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -47,6 +47,8 @@ class Position;
struct EvalInfo {
EvalInfo() { kingDanger[0] = kingDanger[1] = Value(0); }
// Middle game and endgame evaluations
Score value;
@@ -87,15 +89,11 @@ struct EvalInfo {
// 2 to kingAdjacentZoneAttacksCount[BLACK].
int kingAdjacentZoneAttacksCount[2];
// mateThreat[color] is a move for the given side which gives a direct mate.
Move mateThreat[2];
// Middle game and endgame mobility scores.
// Middle game and endgame mobility scores
Score mobility;
// Extra futility margin. This is added to the standard futility margin
// in the quiescence search.
Value futilityMargin;
// Value of the danger for the king of the given color
Value kingDanger[2];
};
@@ -103,8 +101,7 @@ struct EvalInfo {
//// Prototypes
////
extern Value evaluate(const Position& pos, EvalInfo& ei, int threadID);
extern Value quick_evaluate(const Position& pos);
extern Value evaluate(const Position& pos, EvalInfo& ei);
extern void init_eval(int threads);
extern void quit_eval();
extern void read_weights(Color sideToMove);

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -42,6 +42,7 @@ History::History() { clear(); }
void History::clear() {
memset(history, 0, 2 * 8 * 64 * sizeof(int));
memset(maxStaticValueDelta, 0, 2 * 8 * 64 * sizeof(int));
}
@@ -61,7 +62,7 @@ void History::success(Piece p, Square to, Depth d) {
if (history[p][to] >= HistoryMax)
for (int i = 0; i < 16; i++)
for (int j = 0; j < 64; j++)
history[i][j] /= 4;
history[i][j] /= 2;
}
@@ -75,8 +76,12 @@ void History::failure(Piece p, Square to, Depth d) {
assert(square_is_ok(to));
history[p][to] -= int(d) * int(d);
if (history[p][to] < 0)
history[p][to] = 0;
// Prevent history underflow
if (history[p][to] <= -HistoryMax)
for (int i = 0; i < 16; i++)
for (int j = 0; j < 64; j++)
history[i][j] /= 2;
}
@@ -90,3 +95,21 @@ int History::move_ordering_score(Piece p, Square to) const {
return history[p][to];
}
/// History::set_gain() and History::gain() store and retrieve the
/// gain of a move given the delta of the static position evaluations
/// before and after the move.
void History::set_gain(Piece p, Square to, Value delta)
{
if (delta >= maxStaticValueDelta[p][to])
maxStaticValueDelta[p][to] = delta;
else
maxStaticValueDelta[p][to]--;
}
Value History::gain(Piece p, Square to) const
{
return Value(maxStaticValueDelta[p][to]);
}

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -28,6 +28,7 @@
#include "depth.h"
#include "move.h"
#include "piece.h"
#include "value.h"
////
@@ -49,9 +50,12 @@ public:
void success(Piece p, Square to, Depth d);
void failure(Piece p, Square to, Depth d);
int move_ordering_score(Piece p, Square to) const;
void set_gain(Piece p, Square to, Value delta);
Value gain(Piece p, Square to) const;
private:
int history[16][64]; // [piece][square]
int maxStaticValueDelta[16][64]; // [piece][from_square][to_square]
};
@@ -61,13 +65,13 @@ private:
/// HistoryMax controls how often the history counters will be scaled down:
/// When the history score for a move gets bigger than HistoryMax, all
/// entries in the table are divided by 4. It is difficult to guess what
/// entries in the table are divided by 2. It is difficult to guess what
/// the ideal value of this constant is. Scaling down the scores often has
/// the effect that parts of the search tree which have been searched
/// recently have a bigger importance for move ordering than the moves which
/// have been searched a long time ago.
const int HistoryMax = 25000 * OnePly;
const int HistoryMax = 50000 * OnePly;
#endif // !defined(HISTORY_H_INCLUDED)

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -99,5 +99,4 @@ typedef CRITICAL_SECTION Lock;
#endif
#endif // !defined(LOCK_H_INCLUDED)

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -57,8 +57,19 @@ int main(int argc, char *argv[]) {
CALLGRIND_START_INSTRUMENTATION;
#endif
// Process command line arguments if any
if (argc > 1)
if (argc <= 1)
{
// Print copyright notice
cout << engine_name()
<< " by Tord Romstad, Marco Costalba, Joona Kiiski" << endl;
if (CpuHasPOPCNT)
cout << "Good! CPU has hardware POPCNT." << endl;
// Enter UCI mode
uci_main_loop();
}
else // Process command line arguments
{
if (string(argv[1]) != "bench" || argc < 4 || argc > 8)
cout << "Usage: stockfish bench <hash size> <threads> "
@@ -68,22 +79,13 @@ int main(int argc, char *argv[]) {
else
{
string time = argc > 4 ? argv[4] : "60";
string fen = argc > 5 ? argv[5] : "default";
string lim = argc > 6 ? argv[6] : "time";
string tim = argc > 7 ? argv[7] : "";
string fen = argc > 5 ? argv[5] : "default";
string lim = argc > 6 ? argv[6] : "time";
string tim = argc > 7 ? argv[7] : "";
benchmark(string(argv[2]) + " " + string(argv[3]) + " " + time + " " + fen + " " + lim + " " + tim);
}
return 0;
}
// Print copyright notice
cout << engine_name()
<< ". By Tord Romstad, Marco Costalba, Joona Kiiski." << endl;
if (CpuHasPOPCNT)
cout << "Good! CPU has hardware POPCNT. We will use it." << endl;
// Enter UCI mode
uci_main_loop();
Application::free_resources();
return 0;
}

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -55,17 +55,40 @@ namespace {
{ 41, 41, 41, 41, 41, 41 }, { 37, 41, 41, 41, 41, 41 }, { 10, 62, 41, 41, 41, 41 },
{ 57, 64, 39, 41, 41, 41 }, { 50, 40, 23, -22, 41, 41 }, { 106, 101, 3, 151, 171, 41 } };
// Named endgame evaluation and scaling functions, these
// are accessed direcly and not through the function maps.
EvaluationFunction<KmmKm> EvaluateKmmKm(WHITE);
EvaluationFunction<KXK> EvaluateKXK(WHITE), EvaluateKKX(BLACK);
ScalingFunction<KBPsK> ScaleKBPsK(WHITE), ScaleKKBPs(BLACK);
ScalingFunction<KQKRPs> ScaleKQKRPs(WHITE), ScaleKRPsKQ(BLACK);
ScalingFunction<KPsK> ScaleKPsK(WHITE), ScaleKKPs(BLACK);
ScalingFunction<KPKP> ScaleKPKPw(WHITE), ScaleKPKPb(BLACK);
typedef EndgameEvaluationFunctionBase EF;
typedef EndgameScalingFunctionBase SF;
// Endgame evaluation and scaling functions accessed direcly and not through
// the function maps because correspond to more then one material hash key.
EvaluationFunction<KmmKm> EvaluateKmmKm[] = { EvaluationFunction<KmmKm>(WHITE), EvaluationFunction<KmmKm>(BLACK) };
EvaluationFunction<KXK> EvaluateKXK[] = { EvaluationFunction<KXK>(WHITE), EvaluationFunction<KXK>(BLACK) };
ScalingFunction<KBPsK> ScaleKBPsK[] = { ScalingFunction<KBPsK>(WHITE), ScalingFunction<KBPsK>(BLACK) };
ScalingFunction<KQKRPs> ScaleKQKRPs[] = { ScalingFunction<KQKRPs>(WHITE), ScalingFunction<KQKRPs>(BLACK) };
ScalingFunction<KPsK> ScaleKPsK[] = { ScalingFunction<KPsK>(WHITE), ScalingFunction<KPsK>(BLACK) };
ScalingFunction<KPKP> ScaleKPKP[] = { ScalingFunction<KPKP>(WHITE), ScalingFunction<KPKP>(BLACK) };
// Helper templates used to detect a given material distribution
template<Color Us> bool is_KXK(const Position& pos) {
const Color Them = (Us == WHITE ? BLACK : WHITE);
return pos.non_pawn_material(Them) == Value(0)
&& pos.piece_count(Them, PAWN) == 0
&& pos.non_pawn_material(Us) >= RookValueMidgame;
}
template<Color Us> bool is_KBPsK(const Position& pos) {
return pos.non_pawn_material(Us) == BishopValueMidgame
&& pos.piece_count(Us, BISHOP) == 1
&& pos.piece_count(Us, PAWN) >= 1;
}
template<Color Us> bool is_KQKRPs(const Position& pos) {
const Color Them = (Us == WHITE ? BLACK : WHITE);
return pos.piece_count(Us, PAWN) == 0
&& pos.non_pawn_material(Us) == QueenValueMidgame
&& pos.piece_count(Us, QUEEN) == 1
&& pos.piece_count(Them, ROOK) == 1
&& pos.piece_count(Them, PAWN) >= 1;
}
}
@@ -181,22 +204,13 @@ MaterialInfo* MaterialInfoTable::get_material_info(const Position& pos) {
if ((mi->evaluationFunction = funcs->get<EF>(key)) != NULL)
return mi;
else if ( pos.non_pawn_material(BLACK) == Value(0)
&& pos.piece_count(BLACK, PAWN) == 0
&& pos.non_pawn_material(WHITE) >= RookValueMidgame)
else if (is_KXK<WHITE>(pos) || is_KXK<BLACK>(pos))
{
mi->evaluationFunction = &EvaluateKXK;
mi->evaluationFunction = is_KXK<WHITE>(pos) ? &EvaluateKXK[WHITE] : &EvaluateKXK[BLACK];
return mi;
}
else if ( pos.non_pawn_material(WHITE) == Value(0)
&& pos.piece_count(WHITE, PAWN) == 0
&& pos.non_pawn_material(BLACK) >= RookValueMidgame)
{
mi->evaluationFunction = &EvaluateKKX;
return mi;
}
else if ( pos.pieces(PAWN) == EmptyBoardBB
&& pos.pieces(ROOK) == EmptyBoardBB
else if ( pos.pieces(PAWN) == EmptyBoardBB
&& pos.pieces(ROOK) == EmptyBoardBB
&& pos.pieces(QUEEN) == EmptyBoardBB)
{
// Minor piece endgame with at least one minor piece per side and
@@ -207,7 +221,7 @@ MaterialInfo* MaterialInfoTable::get_material_info(const Position& pos) {
if ( pos.piece_count(WHITE, BISHOP) + pos.piece_count(WHITE, KNIGHT) <= 2
&& pos.piece_count(BLACK, BISHOP) + pos.piece_count(BLACK, KNIGHT) <= 2)
{
mi->evaluationFunction = &EvaluateKmmKm;
mi->evaluationFunction = &EvaluateKmmKm[WHITE];
return mi;
}
}
@@ -215,10 +229,8 @@ MaterialInfo* MaterialInfoTable::get_material_info(const Position& pos) {
// OK, we didn't find any special evaluation function for the current
// material configuration. Is there a suitable scaling function?
//
// The code below is rather messy, and it could easily get worse later,
// if we decide to add more special cases. We face problems when there
// are several conflicting applicable scaling functions and we need to
// decide which one to use.
// We face problems when there are several conflicting applicable
// scaling functions and we need to decide which one to use.
SF* sf;
if ((sf = funcs->get<SF>(key)) != NULL)
@@ -230,48 +242,36 @@ MaterialInfo* MaterialInfoTable::get_material_info(const Position& pos) {
// Generic scaling functions that refer to more then one material
// distribution. Should be probed after the specialized ones.
// Note that these ones don't return after setting the function.
if ( pos.non_pawn_material(WHITE) == BishopValueMidgame
&& pos.piece_count(WHITE, BISHOP) == 1
&& pos.piece_count(WHITE, PAWN) >= 1)
mi->scalingFunction[WHITE] = &ScaleKBPsK;
if (is_KBPsK<WHITE>(pos))
mi->scalingFunction[WHITE] = &ScaleKBPsK[WHITE];
if ( pos.non_pawn_material(BLACK) == BishopValueMidgame
&& pos.piece_count(BLACK, BISHOP) == 1
&& pos.piece_count(BLACK, PAWN) >= 1)
mi->scalingFunction[BLACK] = &ScaleKKBPs;
if (is_KBPsK<BLACK>(pos))
mi->scalingFunction[BLACK] = &ScaleKBPsK[BLACK];
if ( pos.piece_count(WHITE, PAWN) == 0
&& pos.non_pawn_material(WHITE) == QueenValueMidgame
&& pos.piece_count(WHITE, QUEEN) == 1
&& pos.piece_count(BLACK, ROOK) == 1
&& pos.piece_count(BLACK, PAWN) >= 1)
mi->scalingFunction[WHITE] = &ScaleKQKRPs;
if (is_KQKRPs<WHITE>(pos))
mi->scalingFunction[WHITE] = &ScaleKQKRPs[WHITE];
else if ( pos.piece_count(BLACK, PAWN) == 0
&& pos.non_pawn_material(BLACK) == QueenValueMidgame
&& pos.piece_count(BLACK, QUEEN) == 1
&& pos.piece_count(WHITE, ROOK) == 1
&& pos.piece_count(WHITE, PAWN) >= 1)
mi->scalingFunction[BLACK] = &ScaleKRPsKQ;
else if (is_KQKRPs<BLACK>(pos))
mi->scalingFunction[BLACK] = &ScaleKQKRPs[BLACK];
if (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) == Value(0))
{
if (pos.piece_count(BLACK, PAWN) == 0)
{
assert(pos.piece_count(WHITE, PAWN) >= 2);
mi->scalingFunction[WHITE] = &ScaleKPsK;
mi->scalingFunction[WHITE] = &ScaleKPsK[WHITE];
}
else if (pos.piece_count(WHITE, PAWN) == 0)
{
assert(pos.piece_count(BLACK, PAWN) >= 2);
mi->scalingFunction[BLACK] = &ScaleKKPs;
mi->scalingFunction[BLACK] = &ScaleKPsK[BLACK];
}
else if (pos.piece_count(WHITE, PAWN) == 1 && pos.piece_count(BLACK, PAWN) == 1)
{
// This is a special case because we set scaling functions
// for both colors instead of only one.
mi->scalingFunction[WHITE] = &ScaleKPKPw;
mi->scalingFunction[BLACK] = &ScaleKPKPb;
mi->scalingFunction[WHITE] = &ScaleKPKP[WHITE];
mi->scalingFunction[BLACK] = &ScaleKPKP[BLACK];
}
}
@@ -374,7 +374,6 @@ EndgameFunctions::EndgameFunctions() {
add<ScalingFunction<KBPPKB> >("KBPPKB");
add<ScalingFunction<KBPKN> >("KBPKN");
add<ScalingFunction<KRPPKRP> >("KRPPKRP");
add<ScalingFunction<KRPPKRP> >("KRPPKRP");
}
EndgameFunctions::~EndgameFunctions() {
@@ -404,7 +403,7 @@ Key EndgameFunctions::buildKey(const string& keyCode) {
s << char(upcase? toupper(keyCode[i]) : tolower(keyCode[i]));
}
s << 8 - keyCode.length() << "/8/8/8/8/8/8/8 w -";
return Position(s.str()).get_material_key();
return Position(s.str(), 0).get_material_key();
}
const string EndgameFunctions::swapColors(const string& keyCode) {

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by

View File

@@ -41,109 +41,131 @@
email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
*/
#include "types.h"
#include "mersenne.h"
/* Period parameters */
#define N 624
#define M 397
#define MATRIX_A 0x9908b0dfUL /* constant vector a */
#define UPPER_MASK 0x80000000UL /* most significant w-r bits */
#define LOWER_MASK 0x7fffffffUL /* least significant r bits */
namespace {
static unsigned long mt[N]; /* the array for the state vector */
static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */
// Period parameters
const int N = 624;
const int M = 397;
const unsigned long MATRIX_A = 0x9908b0dfUL; // Constant vector a
const unsigned long UPPER_MASK = 0x80000000UL; // Most significant w-r bits
const unsigned long LOWER_MASK = 0x7fffffffUL; // Least significant r bits
/* initializes mt[N] with a seed */
static void init_genrand(unsigned long s)
{
mt[0]= s & 0xffffffffUL;
for (mti=1; mti<N; mti++) {
mt[mti] =
(1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
/* In the previous versions, MSBs of the seed affect */
/* only MSBs of the array mt[]. */
/* 2002/01/09 modified by Makoto Matsumoto */
mt[mti] &= 0xffffffffUL;
/* for >32 bit machines */
}
}
unsigned long mt[N]; // The array for the state vector
int mti = N + 1; // mti == N+1 means mt[N] is not initialized
/* initialize by an array with array-length */
/* init_key is the array for initializing keys */
/* key_length is its length */
/* slight change for C++, 2004/2/26 */
static void init_by_array(unsigned long init_key[], int key_length)
{
int i, j, k;
init_genrand(19650218UL);
i=1; j=0;
k = (N>key_length ? N : key_length);
for (; k; k--) {
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL))
+ init_key[j] + j; /* non linear */
mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
i++; j++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
if (j>=key_length) j=0;
}
for (k=N-1; k; k--) {
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL))
- i; /* non linear */
mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
i++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
}
// Initializes mt[N] with a seed
void init_genrand(unsigned long s) {
mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */
}
mt[0]= s & 0xffffffffUL;
for (mti = 1; mti < N; mti++)
{
// See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier.
// In the previous versions, MSBs of the seed affect
// only MSBs of the array mt[].
// 2002/01/09 modified by Makoto Matsumoto
mt[mti] = 1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti;
mt[mti] &= 0xffffffffUL; // For > 32 bit machines
}
}
// Initialize by an array with array-length
// init_key is the array for initializing keys
// key_length is its length
// slight change for C++, 2004/2/26
void init_by_array(unsigned long init_key[], int key_length) {
int i = 1;
int j = 0;
int k = (N > key_length ? N : key_length);
init_genrand(19650218UL);
for ( ; k; k--)
{
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL)) + init_key[j] + j; // Non linear
mt[i] &= 0xffffffffUL; // For WORDSIZE > 32 machines
i++; j++;
if (i >= N)
{
mt[0] = mt[N-1];
i = 1;
}
if (j >= key_length)
j = 0;
}
for (k = N-1; k; k--)
{
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL)) - i; // Non linear
mt[i] &= 0xffffffffUL; // For WORDSIZE > 32 machines
i++;
if (i >= N)
{
mt[0] = mt[N-1];
i = 1;
}
}
mt[0] = 0x80000000UL; // MSB is 1; assuring non-zero initial array
}
} // namespace
// Generates a random number on [0,0xffffffff]-interval
uint32_t genrand_int32() {
/* generates a random number on [0,0xffffffff]-interval */
uint32_t genrand_int32(void) {
unsigned long y;
static unsigned long mag01[2]={0x0UL, MATRIX_A};
static unsigned long mag01[2] = {0x0UL, MATRIX_A};
/* mag01[x] = x * MATRIX_A for x=0,1 */
if (mti >= N) { /* generate N words at one time */
int kk;
// Generate N words at one time
if (mti >= N)
{
int kk;
if (mti == N+1) /* if init_genrand() has not been called, */
init_genrand(5489UL); /* a default initial seed is used */
if (mti == N+1) // If init_genrand() has not been called,
init_genrand(5489UL); // a default initial seed is used.
for (kk=0;kk<N-M;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
for (;kk<N-1;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];
mti = 0;
for (kk = 0; kk < N-M; kk++)
{
y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);
mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
for ( ; kk < N-1; kk++)
{
y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);
mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);
mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];
mti = 0;
}
y = mt[mti++];
/* Tempering */
// Tempering
y ^= (y >> 11);
y ^= (y << 7) & 0x9d2c5680UL;
y ^= (y << 7) & 0x9d2c5680UL;
y ^= (y << 15) & 0xefc60000UL;
y ^= (y >> 18);
return y;
}
uint64_t genrand_int64(void) {
uint64_t genrand_int64() {
uint64_t x, y;
x = genrand_int32(); y = genrand_int32();
return (x<<32)|y;
x = genrand_int32();
y = genrand_int32();
return (x << 32) | y;
}
void init_mersenne(void) {
unsigned long init[4]={0x123, 0x234, 0x345, 0x456}, length=4;
void init_mersenne() {
unsigned long init[4] = {0x123, 0x234, 0x345, 0x456};
unsigned long length = 4;
init_by_array(init, length);
}

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -32,9 +32,9 @@
//// Prototypes
////
extern uint32_t genrand_int32(void);
extern uint64_t genrand_int64(void);
extern void init_mersenne(void);
extern uint32_t genrand_int32();
extern uint64_t genrand_int64();
extern void init_mersenne();
#endif // !defined(MERSENNE_H_INCLUDED)

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -27,6 +27,9 @@
# include <sys/time.h>
# include <sys/types.h>
# include <unistd.h>
# if defined(__hpux)
# include <sys/pstat.h>
# endif
#else
@@ -36,6 +39,10 @@
#endif
#if !defined(NO_PREFETCH)
# include <xmmintrin.h>
#endif
#include <cassert>
#include <cstdio>
#include <iomanip>
@@ -44,13 +51,14 @@
#include "bitcount.h"
#include "misc.h"
#include "thread.h"
using namespace std;
/// Version number. If this is left empty, the current date (in the format
/// YYMMDD) is used as a version number.
static const string EngineVersion = "1.6";
static const string EngineVersion = "1.8";
static const string AppName = "Stockfish";
static const string AppTag = "";
@@ -143,7 +151,7 @@ const string engine_name() {
const string cpu64(CpuHas64BitPath ? " 64bit" : "");
if (!EngineVersion.empty())
return AppName+ " " + EngineVersion + cpu64;
return AppName + " " + EngineVersion + cpu64;
string date(__DATE__); // From compiler, format is "Sep 21 2008"
string months("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec");
@@ -185,7 +193,15 @@ int get_system_time() {
# if defined(_SC_NPROCESSORS_ONLN)
int cpu_count() {
return Min(sysconf(_SC_NPROCESSORS_ONLN), 8);
return Min(sysconf(_SC_NPROCESSORS_ONLN), MAX_THREADS);
}
# elif defined(__hpux)
int cpu_count() {
struct pst_dynamic psd;
if (pstat_getdynamic(&psd, sizeof(psd), (size_t)1, 0) == -1)
return 1;
return Min(psd.psd_proc_cnt, MAX_THREADS);
}
# else
int cpu_count() {
@@ -198,7 +214,7 @@ int cpu_count() {
int cpu_count() {
SYSTEM_INFO s;
GetSystemInfo(&s);
return Min(s.dwNumberOfProcessors, 8);
return Min(s.dwNumberOfProcessors, MAX_THREADS);
}
#endif
@@ -275,4 +291,27 @@ int Bioskey()
return 0;
}
}
#endif
/// prefetch() preloads the given address in L1/L2 cache. This is a non
/// blocking function and do not stalls the CPU waiting for data to be
/// loaded from RAM, that can be very slow.
#if defined(NO_PREFETCH)
void prefetch(char*) {}
#else
void prefetch(char* addr) {
#if defined(__INTEL_COMPILER) || defined(__ICL)
// This hack prevents prefetches to be optimized away by
// Intel compiler. Both MSVC and gcc seems not affected.
__asm__ ("");
#endif
_mm_prefetch(addr, _MM_HINT_T2);
_mm_prefetch(addr+64, _MM_HINT_T2); // 64 bytes ahead
}
#endif

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -55,6 +55,7 @@ extern const std::string engine_name();
extern int get_system_time();
extern int cpu_count();
extern int Bioskey();
extern void prefetch(char* addr);
////

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -86,10 +86,10 @@ inline void insertion_sort(T* firstMove, T* lastMove)
}
}
// Our dedicated sort in range [firstMove, lastMove), it is well
// tuned for non-captures where we have a lot of zero scored moves.
// Our dedicated sort in range [firstMove, lastMove), first splits
// positive scores from ramining then order seaprately the two sets.
template<typename T>
inline void sort_moves(T* firstMove, T* lastMove)
inline void sort_moves(T* firstMove, T* lastMove, T** lastPositive)
{
T tmp;
T *p, *d;
@@ -101,11 +101,11 @@ inline void sort_moves(T* firstMove, T* lastMove)
// Split positives vs non-positives
do {
while ((++p)->score > 0);
while ((++p)->score > 0) {}
if (p != d)
{
while (--d != p && d->score <= 0);
while (--d != p && d->score <= 0) {}
tmp = *p;
*p = *d;
@@ -114,29 +114,9 @@ inline void sort_moves(T* firstMove, T* lastMove)
} while (p != d);
// Sort positives
// Sort just positive scored moves, remaining only when we get there
insertion_sort<T>(firstMove, p);
d = lastMove;
p--;
// Split zero vs negatives
do {
while ((++p)->score == 0);
if (p != d)
{
while (--d != p && d->score < 0);
tmp = *p;
*p = *d;
*d = tmp;
}
} while (p != d);
// Sort negatives
insertion_sort<T>(p, lastMove);
*lastPositive = p;
}
// Picks up the best move in range [curMove, lastMove), one per cycle.

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -338,6 +338,10 @@ bool move_is_legal(const Position& pos, const Move m, Bitboard pinned) {
||(square_rank(to) == RANK_1 && us != WHITE)) != bool(move_is_promotion(m)))
return false;
// The promotion piece, if any, must be valid
if (move_promotion_piece(m) > QUEEN || move_promotion_piece(m) == PAWN)
return false;
// Proceed according to the square delta between the origin and
// destination squares.
switch (direction)

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -70,18 +70,18 @@ namespace {
/// search captures, promotions and some checks) and about how important good
/// move ordering is at the current node.
MovePicker::MovePicker(const Position& p, Move ttm, Depth d,
const History& h, SearchStack* ss) : pos(p), H(h) {
MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const History& h,
SearchStack* ss, Value beta) : pos(p), H(h) {
int searchTT = ttm;
ttMoves[0].move = ttm;
finished = false;
badCaptureThreshold = 0;
lastBadCapture = badCaptures;
pinned = p.pinned_pieces(pos.side_to_move());
if (ss && !p.is_check())
{
ttMoves[1].move = (ss->mateKiller == ttm)? MOVE_NONE : ss->mateKiller;
ttMoves[1].move = (ss->mateKiller == ttm) ? MOVE_NONE : ss->mateKiller;
searchTT |= ttMoves[1].move;
killers[0].move = ss->killers[0];
killers[1].move = ss->killers[1];
@@ -91,13 +91,28 @@ MovePicker::MovePicker(const Position& p, Move ttm, Depth d,
if (p.is_check())
phasePtr = EvasionsPhaseTable;
else if (d > Depth(0))
{
// Consider sligtly negative captures as good if at low
// depth and far from beta.
if (ss && ss->eval < beta - PawnValueMidgame && d < 3 * OnePly)
badCaptureThreshold = -PawnValueMidgame;
phasePtr = MainSearchPhaseTable;
}
else if (d == Depth(0))
phasePtr = QsearchWithChecksPhaseTable;
else
{
phasePtr = QsearchWithoutChecksPhaseTable;
phasePtr += !searchTT - 1;
// Skip TT move if is not a capture or a promotion, this avoids
// qsearch tree explosion due to a possible perpetual check or
// similar rare cases when TT table is full.
if (ttm != MOVE_NONE && !pos.move_is_capture_or_promotion(ttm))
searchTT = ttMoves[0].move = MOVE_NONE;
}
phasePtr += int(!searchTT) - 1;
go_next_phase();
}
@@ -129,7 +144,7 @@ void MovePicker::go_next_phase() {
case PH_NONCAPTURES:
lastMove = generate_noncaptures(pos, moves);
score_noncaptures();
sort_moves(moves, lastMove);
sort_moves(moves, lastMove, &lastGoodNonCapture);
return;
case PH_BAD_CAPTURES:
@@ -142,7 +157,7 @@ void MovePicker::go_next_phase() {
case PH_EVASIONS:
assert(pos.is_check());
lastMove = generate_evasions(pos, moves);
score_evasions();
score_evasions_or_checks();
return;
case PH_QCAPTURES:
@@ -151,12 +166,12 @@ void MovePicker::go_next_phase() {
return;
case PH_QCHECKS:
// Perhaps we should order moves move here? FIXME
lastMove = generate_non_capture_checks(pos, moves);
score_evasions_or_checks();
return;
case PH_STOP:
lastMove = curMove + 1; // hack to be friendly for get_next_move()
lastMove = curMove + 1; // Avoids another go_next_phase() call
return;
default:
@@ -216,16 +231,16 @@ void MovePicker::score_noncaptures() {
piece = pos.piece_on(from);
hs = H.move_ordering_score(piece, to);
// Ensure history is always preferred to pst
// Ensure history has always highest priority
if (hs > 0)
hs += 1000;
hs += 10000;
// pst based scoring
cur->score = hs + mg_value(pos.pst_delta(piece, from, to));
// Gain table based scoring
cur->score = hs + 16 * H.gain(piece, to);
}
}
void MovePicker::score_evasions() {
void MovePicker::score_evasions_or_checks() {
// Try good captures ordered by MVV/LVA, then non-captures if
// destination square is not under attack, ordered by history
// value, and at the end bad-captures and non-captures with a
@@ -233,11 +248,15 @@ void MovePicker::score_evasions() {
Move m;
int seeScore;
// Skip if we don't have at least two moves to order
if (lastMove < moves + 2)
return;
for (MoveStack* cur = moves; cur != lastMove; cur++)
{
m = cur->move;
if ((seeScore = pos.see_sign(m)) < 0)
cur->score = seeScore;
cur->score = seeScore - HistoryMax; // Be sure are at the bottom
else if (pos.move_is_capture(m))
cur->score = pos.midgame_value_of_piece_on(move_to(m))
- pos.type_of_piece_on(move_from(m)) + HistoryMax;
@@ -251,6 +270,8 @@ void MovePicker::score_evasions() {
/// are no more moves left.
/// It picks the move with the biggest score from a list of generated moves taking
/// care not to return the tt move if has already been searched previously.
/// Note that this function is not thread safe so should be lock protected by
/// caller when accessed through a shared MovePicker object.
Move MovePicker::get_next_move() {
@@ -277,7 +298,7 @@ Move MovePicker::get_next_move() {
{
// Check for a non negative SEE now
int seeValue = pos.see_sign(move);
if (seeValue >= 0)
if (seeValue >= badCaptureThreshold)
return move;
// Losing capture, move it to the badCaptures[] array, note
@@ -292,14 +313,19 @@ Move MovePicker::get_next_move() {
case PH_KILLERS:
move = (curMove++)->move;
if ( move != MOVE_NONE
&& move_is_legal(pos, move, pinned)
&& move != ttMoves[0].move
&& move != ttMoves[1].move
&& move_is_legal(pos, move, pinned)
&& !pos.move_is_capture(move))
return move;
break;
case PH_NONCAPTURES:
// Sort negative scored moves only when we get there
if (curMove == lastGoodNonCapture)
insertion_sort(lastGoodNonCapture, lastMove);
move = (curMove++)->move;
if ( move != ttMoves[0].move
&& move != ttMoves[1].move
@@ -340,21 +366,3 @@ Move MovePicker::get_next_move() {
}
}
/// A variant of get_next_move() which takes a lock as a parameter, used to
/// prevent multiple threads from picking the same move at a split point.
Move MovePicker::get_next_move(Lock &lock) {
lock_grab(&lock);
if (finished)
{
lock_release(&lock);
return MOVE_NONE;
}
Move m = get_next_move();
if (m == MOVE_NONE)
finished = true;
lock_release(&lock);
return m;
}

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -27,7 +27,6 @@
#include "depth.h"
#include "history.h"
#include "lock.h"
#include "position.h"
@@ -50,25 +49,23 @@ class MovePicker {
MovePicker& operator=(const MovePicker&); // silence a warning under MSVC
public:
MovePicker(const Position& p, Move ttm, Depth d, const History& h, SearchStack* ss = NULL);
MovePicker(const Position& p, Move ttm, Depth d, const History& h, SearchStack* ss = NULL, Value beta = -VALUE_INFINITE);
Move get_next_move();
Move get_next_move(Lock& lock);
int number_of_evasions() const;
private:
void score_captures();
void score_noncaptures();
void score_evasions();
void score_evasions_or_checks();
void go_next_phase();
const Position& pos;
const History& H;
MoveStack ttMoves[2], killers[2];
bool finished;
int phase;
const uint8_t* phasePtr;
MoveStack *curMove, *lastMove, *lastBadCapture;
Bitboard pinned;
MoveStack ttMoves[2], killers[2];
int badCaptureThreshold, phase;
const uint8_t* phasePtr;
MoveStack *curMove, *lastMove, *lastGoodNonCapture, *lastBadCapture;
MoveStack moves[256], badCaptures[64];
};

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -94,12 +94,13 @@ namespace {
};
// Pawn storm open file bonuses by file
const int16_t KStormOpenFileBonus[8] = { 31, 31, 18, 0, 0, 0, 0, 0 };
const int16_t QStormOpenFileBonus[8] = { 0, 0, 0, 0, 0, 26, 42, 26 };
const int16_t QStormOpenFileBonus[8] = { 31, 31, 18, 0, 0, 0, 0, 0 };
const int16_t KStormOpenFileBonus[8] = { 0, 0, 0, 0, 0, 26, 42, 26 };
// Pawn storm lever bonuses by file
const int StormLeverBonus[8] = { -8, -8, -13, 0, 0, -13, -8, -8 };
#undef S
}
@@ -107,11 +108,10 @@ namespace {
//// Functions
////
/// Constructor
/// PawnInfoTable c'tor and d'tor instantiated one each thread
PawnInfoTable::PawnInfoTable(unsigned numOfEntries) {
PawnInfoTable::PawnInfoTable(unsigned numOfEntries) : size(numOfEntries) {
size = numOfEntries;
entries = new PawnInfo[size];
if (!entries)
{
@@ -122,9 +122,8 @@ PawnInfoTable::PawnInfoTable(unsigned numOfEntries) {
}
/// Destructor
PawnInfoTable::~PawnInfoTable() {
delete [] entries;
}
@@ -140,11 +139,11 @@ void PawnInfo::clear() {
/// PawnInfoTable::get_pawn_info() takes a position object as input, computes
/// a PawnInfo object, and returns a pointer to it. The result is also
/// stored in a hash table, so we don't have to recompute everything when
/// the same pawn structure occurs again.
/// a PawnInfo object, and returns a pointer to it. The result is also stored
/// in a hash table, so we don't have to recompute everything when the same
/// pawn structure occurs again.
PawnInfo* PawnInfoTable::get_pawn_info(const Position& pos) {
PawnInfo* PawnInfoTable::get_pawn_info(const Position& pos) const {
assert(pos.is_ok());
@@ -179,12 +178,13 @@ PawnInfo* PawnInfoTable::get_pawn_info(const Position& pos) {
template<Color Us>
Score PawnInfoTable::evaluate_pawns(const Position& pos, Bitboard ourPawns,
Bitboard theirPawns, PawnInfo* pi) {
Bitboard theirPawns, PawnInfo* pi) const {
Bitboard b;
Square s;
File f;
Rank r;
bool passed, isolated, doubled, chain, backward, candidate;
int bonus;
bool passed, isolated, doubled, opposed, chain, backward, candidate;
Score value = make_score(0, 0);
const Square* ptr = pos.piece_list_begin(Us, PAWN);
@@ -205,79 +205,24 @@ Score PawnInfoTable::evaluate_pawns(const Position& pos, Bitboard ourPawns,
assert(pos.piece_on(s) == piece_of_color_and_type(Us, PAWN));
// Passed, isolated or doubled pawn?
passed = Position::pawn_is_passed(theirPawns, Us, s);
isolated = Position::pawn_is_isolated(ourPawns, s);
doubled = Position::pawn_is_doubled(ourPawns, Us, s);
// Calculate kingside and queenside pawn storm scores for both colors to be
// used when evaluating middle game positions with opposite side castling.
bonus = (f >= FILE_F ? evaluate_pawn_storm<Us, KingSide>(s, r, f, theirPawns) : 0);
pi->ksStormValue[Us] += KStormTable[relative_square(Us, s)] + bonus;
// We calculate kingside and queenside pawn storm
// scores for both colors. These are used when evaluating
// middle game positions with opposite side castling.
//
// Each pawn is given a base score given by a piece square table
// (KStormTable[] or QStormTable[]). Pawns which seem to have good
// chances of creating an open file by exchanging itself against an
// enemy pawn on an adjacent file gets an additional bonus.
bonus = (f <= FILE_C ? evaluate_pawn_storm<Us, QueenSide>(s, r, f, theirPawns) : 0);
pi->qsStormValue[Us] += QStormTable[relative_square(Us, s)] + bonus;
// Kingside pawn storms
bonus = KStormTable[relative_square(Us, s)];
if (f >= FILE_F)
{
Bitboard b = outpost_mask(Us, s) & theirPawns & (FileFBB | FileGBB | FileHBB);
while (b)
{
Square s2 = pop_1st_bit(&b);
if (!(theirPawns & neighboring_files_bb(s2) & rank_bb(s2)))
{
// The enemy pawn has no pawn beside itself, which makes it
// particularly vulnerable. Big bonus, especially against a
// weakness on the rook file.
if (square_file(s2) == FILE_H)
bonus += 4*StormLeverBonus[f] - 8*square_distance(s, s2);
else
bonus += 2*StormLeverBonus[f] - 4*square_distance(s, s2);
} else
// There is at least one enemy pawn beside the enemy pawn we look
// at, which means that the pawn has somewhat better chances of
// defending itself by advancing. Smaller bonus.
bonus += StormLeverBonus[f] - 2*square_distance(s, s2);
}
}
pi->ksStormValue[Us] += bonus;
// Our rank plus previous one. Used for chain detection.
b = rank_bb(r) | rank_bb(r + (Us == WHITE ? -1 : 1));
// Queenside pawn storms
bonus = QStormTable[relative_square(Us, s)];
if (f <= FILE_C)
{
Bitboard b = outpost_mask(Us, s) & theirPawns & (FileABB | FileBBB | FileCBB);
while (b)
{
Square s2 = pop_1st_bit(&b);
if (!(theirPawns & neighboring_files_bb(s2) & rank_bb(s2)))
{
// The enemy pawn has no pawn beside itself, which makes it
// particularly vulnerable. Big bonus, especially against a
// weakness on the rook file.
if (square_file(s2) == FILE_A)
bonus += 4*StormLeverBonus[f] - 16*square_distance(s, s2);
else
bonus += 2*StormLeverBonus[f] - 8*square_distance(s, s2);
} else
// There is at least one enemy pawn beside the enemy pawn we look
// at, which means that the pawn has somewhat better chances of
// defending itself by advancing. Smaller bonus.
bonus += StormLeverBonus[f] - 4*square_distance(s, s2);
}
}
pi->qsStormValue[Us] += bonus;
// Member of a pawn chain (but not the backward one)? We could speed up
// the test a little by introducing an array of masks indexed by color
// and square for doing the test, but because everything is hashed,
// it probably won't make any noticable difference.
chain = ourPawns
& neighboring_files_bb(f)
& (rank_bb(r) | rank_bb(r - (Us == WHITE ? 1 : -1)));
// Passed, isolated, doubled or member of a pawn
// chain (but not the backward one) ?
passed = !(theirPawns & passed_pawn_mask(Us, s));
doubled = ourPawns & squares_behind(Us, s);
opposed = theirPawns & squares_in_front_of(Us, s);
isolated = !(ourPawns & neighboring_files_bb(f));
chain = ourPawns & neighboring_files_bb(f) & b;
// Test for backward pawn
//
@@ -286,7 +231,7 @@ Score PawnInfoTable::evaluate_pawns(const Position& pos, Bitboard ourPawns,
// there are friendly pawns behind on neighboring files it cannot
// be backward either.
if ( (passed | isolated | chain)
|| (ourPawns & behind_bb(Us, r) & neighboring_files_bb(f))
|| (ourPawns & attack_span_mask(opposite_color(Us), s))
|| (pos.attacks_from<PAWN>(s, Us) & theirPawns))
backward = false;
else
@@ -295,7 +240,7 @@ Score PawnInfoTable::evaluate_pawns(const Position& pos, Bitboard ourPawns,
// pawn on neighboring files. We now check whether the pawn is
// backward by looking in the forward direction on the neighboring
// files, and seeing whether we meet a friendly or an enemy pawn first.
Bitboard b = pos.attacks_from<PAWN>(s, Us);
b = pos.attacks_from<PAWN>(s, Us);
// Note that we are sure to find something because pawn is not passed
// nor isolated, so loop is potentially infinite, but it isn't.
@@ -307,12 +252,12 @@ Score PawnInfoTable::evaluate_pawns(const Position& pos, Bitboard ourPawns,
backward = (b | (Us == WHITE ? b << 8 : b >> 8)) & theirPawns;
}
assert(passed | opposed | (attack_span_mask(Us, s) & theirPawns));
// Test for candidate passed pawn
candidate = !passed
&& !(theirPawns & file_bb(f))
&& ( count_1s_max_15(neighboring_files_bb(f) & (behind_bb(Us, r) | rank_bb(r)) & ourPawns)
- count_1s_max_15(neighboring_files_bb(f) & in_front_bb(Us, r) & theirPawns)
>= 0);
candidate = !(opposed | passed)
&& (b = attack_span_mask(opposite_color(Us), s + pawn_push(Us)) & ourPawns) != EmptyBoardBB
&& count_1s_max_15(b) >= count_1s_max_15(attack_span_mask(Us, s) & theirPawns);
// In order to prevent doubled passed pawns from receiving a too big
// bonus, only the frontmost passed pawn on each file is considered as
@@ -320,10 +265,12 @@ Score PawnInfoTable::evaluate_pawns(const Position& pos, Bitboard ourPawns,
if (passed && (ourPawns & squares_in_front_of(Us, s)))
passed = false;
// Score this pawn
// Mark the pawn as passed. Pawn will be properly scored in evaluation
// because we need full attack info to evaluate passed pawns.
if (passed)
set_bit(&(pi->passedPawns), s);
// Score this pawn
if (isolated)
{
value -= IsolatedPawnPenalty[f];
@@ -350,13 +297,47 @@ Score PawnInfoTable::evaluate_pawns(const Position& pos, Bitboard ourPawns,
}
/// PawnInfoTable::evaluate_pawn_storm() evaluates each pawn which seems
/// to have good chances of creating an open file by exchanging itself
/// against an enemy pawn on an adjacent file.
template<Color Us, PawnInfoTable::SideType Side>
int PawnInfoTable::evaluate_pawn_storm(Square s, Rank r, File f, Bitboard theirPawns) const {
const Bitboard StormFilesBB = (Side == KingSide ? FileFBB | FileGBB | FileHBB
: FileABB | FileBBB | FileCBB);
const int K = (Side == KingSide ? 2 : 4);
const File RookFile = (Side == KingSide ? FILE_H : FILE_A);
Bitboard b = attack_span_mask(Us, s) & theirPawns & StormFilesBB;
int bonus = 0;
while (b)
{
// Give a bonus according to the distance of the nearest enemy pawn
Square s2 = pop_1st_bit(&b);
Rank r2 = square_rank(s2);
int v = StormLeverBonus[f] - K * rank_distance(r, r2);
// If enemy pawn has no pawn beside itself is particularly vulnerable.
// Big bonus, especially against a weakness on the rook file
if (!(theirPawns & neighboring_files_bb(s2) & rank_bb(s2)))
v *= (square_file(s2) == RookFile ? 4 : 2);
bonus += v;
}
return bonus;
}
/// PawnInfo::updateShelter calculates and caches king shelter. It is called
/// only when king square changes, about 20% of total get_king_shelter() calls.
int PawnInfo::updateShelter(const Position& pos, Color c, Square ksq) {
unsigned shelter = 0;
Bitboard pawns = pos.pieces(PAWN, c) & this_and_neighboring_files_bb(ksq);
unsigned shelter = 0;
unsigned r = ksq & (7 << 3);
for (int i = 1, k = (c ? -8 : 8); i < 4; i++)
{
r += k;

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -64,10 +64,10 @@ private:
Key key;
Bitboard passedPawns;
Bitboard pawnAttacks[2];
Square kingSquares[2];
Score value;
int16_t ksStormValue[2], qsStormValue[2];
uint8_t halfOpenFiles[2];
Square kingSquares[2];
uint8_t kingShelters[2];
};
@@ -78,14 +78,19 @@ private:
class PawnInfoTable {
enum SideType { KingSide, QueenSide };
public:
PawnInfoTable(unsigned numOfEntries);
~PawnInfoTable();
PawnInfo* get_pawn_info(const Position& pos);
PawnInfo* get_pawn_info(const Position& pos) const;
private:
template<Color Us>
Score evaluate_pawns(const Position& pos, Bitboard ourPawns, Bitboard theirPawns, PawnInfo* pi);
Score evaluate_pawns(const Position& pos, Bitboard ourPawns, Bitboard theirPawns, PawnInfo* pi) const;
template<Color Us, SideType Side>
int evaluate_pawn_storm(Square s, Rank r, File f, Bitboard theirPawns) const;
unsigned size;
PawnInfo* entries;

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -38,7 +38,7 @@ static const string PieceChars(" pnbrqk PNBRQK");
char piece_type_to_char(PieceType pt, bool upcase) {
return PieceChars[pt + upcase * 7];
return PieceChars[pt + int(upcase) * 7];
}
PieceType piece_type_from_char(char c) {

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -44,12 +44,9 @@ using std::string;
//// Variables
////
int Position::castleRightsMask[64];
Key Position::zobrist[2][8][64];
Key Position::zobEp[64];
Key Position::zobCastle[16];
Key Position::zobMaterial[2][8][16];
Key Position::zobSideToMove;
Key Position::zobExclusion;
@@ -76,12 +73,36 @@ CheckInfo::CheckInfo(const Position& pos) {
checkSq[KING] = EmptyBoardBB;
}
Position::Position(const Position& pos) {
copy(pos);
/// Position c'tors. Here we always create a copy of the original position
/// or the FEN string, we want the new born Position object do not depend
/// on any external data so we detach state pointer from the source one.
Position::Position(int th) : threadID(th) {}
Position::Position(const Position& pos, int th) {
memcpy(this, &pos, sizeof(Position));
detach(); // Always detach() in copy c'tor to avoid surprises
threadID = th;
}
Position::Position(const string& fen) {
Position::Position(const string& fen, int th) {
from_fen(fen);
threadID = th;
}
/// Position::detach() copies the content of the current state and castling
/// masks inside the position itself. This is needed when the st pointee could
/// become stale, as example because the caller is about to going out of scope.
void Position::detach() {
startState = *st;
st = &startState;
st->previous = NULL; // as a safe guard
}
@@ -143,72 +164,77 @@ void Position::from_fen(const string& fen) {
}
i++;
while(strchr("KQkqabcdefghABCDEFGH-", fen[i])) {
if (fen[i] == '-')
{
while (strchr("KQkqabcdefghABCDEFGH-", fen[i])) {
if (fen[i] == '-')
{
i++;
break;
}
else if (fen[i] == 'K') allow_oo(WHITE);
else if (fen[i] == 'Q') allow_ooo(WHITE);
else if (fen[i] == 'k') allow_oo(BLACK);
else if (fen[i] == 'q') allow_ooo(BLACK);
else if (fen[i] >= 'A' && fen[i] <= 'H') {
File rookFile, kingFile = FILE_NONE;
for (Square square = SQ_B1; square <= SQ_G1; square++)
if (piece_on(square) == WK)
kingFile = square_file(square);
if (kingFile == FILE_NONE) {
std::cout << "Error in FEN at character " << i << std::endl;
return;
}
initialKFile = kingFile;
rookFile = File(fen[i] - 'A') + FILE_A;
if (rookFile < initialKFile) {
allow_ooo(WHITE);
initialQRFile = rookFile;
}
else {
allow_oo(WHITE);
initialKRFile = rookFile;
}
}
else if (fen[i] >= 'a' && fen[i] <= 'h') {
File rookFile, kingFile = FILE_NONE;
for (Square square = SQ_B8; square <= SQ_G8; square++)
if (piece_on(square) == BK)
kingFile = square_file(square);
if (kingFile == FILE_NONE) {
std::cout << "Error in FEN at character " << i << std::endl;
return;
}
initialKFile = kingFile;
rookFile = File(fen[i] - 'a') + FILE_A;
if (rookFile < initialKFile) {
allow_ooo(BLACK);
initialQRFile = rookFile;
}
else {
allow_oo(BLACK);
initialKRFile = rookFile;
}
}
else {
std::cout << "Error in FEN at character " << i << std::endl;
return;
}
i++;
break;
}
else if(fen[i] == 'K') allow_oo(WHITE);
else if(fen[i] == 'Q') allow_ooo(WHITE);
else if(fen[i] == 'k') allow_oo(BLACK);
else if(fen[i] == 'q') allow_ooo(BLACK);
else if(fen[i] >= 'A' && fen[i] <= 'H') {
File rookFile, kingFile = FILE_NONE;
for(Square square = SQ_B1; square <= SQ_G1; square++)
if(piece_on(square) == WK)
kingFile = square_file(square);
if(kingFile == FILE_NONE) {
std::cout << "Error in FEN at character " << i << std::endl;
return;
}
initialKFile = kingFile;
rookFile = File(fen[i] - 'A') + FILE_A;
if(rookFile < initialKFile) {
allow_ooo(WHITE);
initialQRFile = rookFile;
}
else {
allow_oo(WHITE);
initialKRFile = rookFile;
}
}
else if(fen[i] >= 'a' && fen[i] <= 'h') {
File rookFile, kingFile = FILE_NONE;
for(Square square = SQ_B8; square <= SQ_G8; square++)
if(piece_on(square) == BK)
kingFile = square_file(square);
if(kingFile == FILE_NONE) {
std::cout << "Error in FEN at character " << i << std::endl;
return;
}
initialKFile = kingFile;
rookFile = File(fen[i] - 'a') + FILE_A;
if(rookFile < initialKFile) {
allow_ooo(BLACK);
initialQRFile = rookFile;
}
else {
allow_oo(BLACK);
initialKRFile = rookFile;
}
}
else {
std::cout << "Error in FEN at character " << i << std::endl;
return;
}
i++;
}
// Skip blanks
while (fen[i] == ' ')
i++;
// En passant square
// En passant square -- ignore if no capture is possible
if ( i <= fen.length() - 2
&& (fen[i] >= 'a' && fen[i] <= 'h')
&& (fen[i+1] == '3' || fen[i+1] == '6'))
st->epSquare = square_from_string(fen.substr(i, 2));
{
Square fenEpSquare = square_from_string(fen.substr(i, 2));
Color them = opposite_color(sideToMove);
if (attacks_from<PAWN>(fenEpSquare, them) & this->pieces(PAWN, sideToMove))
st->epSquare = square_from_string(fen.substr(i, 2));
}
// Various initialisation
for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
@@ -266,10 +292,24 @@ const string Position::to_fen() const {
fen += (sideToMove == WHITE ? "w " : "b ");
if (st->castleRights != NO_CASTLES)
{
if (can_castle_kingside(WHITE)) fen += 'K';
if (can_castle_queenside(WHITE)) fen += 'Q';
if (can_castle_kingside(BLACK)) fen += 'k';
if (can_castle_queenside(BLACK)) fen += 'q';
if (initialKFile == FILE_E && initialQRFile == FILE_A && initialKRFile == FILE_H)
{
if (can_castle_kingside(WHITE)) fen += 'K';
if (can_castle_queenside(WHITE)) fen += 'Q';
if (can_castle_kingside(BLACK)) fen += 'k';
if (can_castle_queenside(BLACK)) fen += 'q';
}
else
{
if (can_castle_kingside(WHITE))
fen += char(toupper(file_to_char(initialKRFile)));
if (can_castle_queenside(WHITE))
fen += char(toupper(file_to_char(initialQRFile)));
if (can_castle_kingside(BLACK))
fen += file_to_char(initialKRFile);
if (can_castle_queenside(BLACK))
fen += file_to_char(initialQRFile);
}
} else
fen += '-';
@@ -300,8 +340,9 @@ void Position::print(Move m) const {
std::cout << std::endl;
if (m != MOVE_NONE)
{
Position p(*this, thread());
string col = (color_of_piece_on(move_from(m)) == BLACK ? ".." : "");
std::cout << "Move is: " << col << move_to_san(*this, m) << std::endl;
std::cout << "Move is: " << col << move_to_san(p, m) << std::endl;
}
for (Rank rank = RANK_8; rank >= RANK_1; rank--)
{
@@ -326,20 +367,11 @@ void Position::print(Move m) const {
}
/// Position::copy() creates a copy of the input position.
void Position::copy(const Position& pos) {
memcpy(this, &pos, sizeof(Position));
saveState(); // detach and copy state info
}
/// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
/// king) pieces for the given color and for the given pinner type. Or, when
/// template parameter FindPinned is false, the pieces of the given color
/// candidate for a discovery check against the enemy king.
/// Note that checkersBB bitboard must be already updated.
/// Bitboard checkersBB must be already updated when looking for pinners.
template<bool FindPinned>
Bitboard Position::hidden_checkers(Color c) const {
@@ -373,7 +405,8 @@ Bitboard Position::hidden_checkers(Color c) const {
/// Position:pinned_pieces() returns a bitboard of all pinned (against the
/// king) pieces for the given color.
/// king) pieces for the given color. Note that checkersBB bitboard must
/// be already updated.
Bitboard Position::pinned_pieces(Color c) const {
@@ -383,7 +416,8 @@ Bitboard Position::pinned_pieces(Color c) const {
/// Position:discovered_check_candidates() returns a bitboard containing all
/// pieces for the given side which are candidates for giving a discovered
/// check.
/// check. Contrary to pinned_pieces() here there is no need of checkersBB
/// to be already updated.
Bitboard Position::discovered_check_candidates(Color c) const {
@@ -607,10 +641,10 @@ bool Position::move_is_check(Move m, const CheckInfo& ci) const {
}
}
// En passant capture with check? We have already handled the case
// En passant capture with check ? We have already handled the case
// of direct checks and ordinary discovered check, the only case we
// need to handle is the unusual case of a discovered check through the
// captured pawn.
// need to handle is the unusual case of a discovered check through
// the captured pawn.
if (move_is_ep(m))
{
Square capsq = make_square(square_file(to), square_rank(from));
@@ -662,16 +696,16 @@ void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveI
assert(is_ok());
assert(move_is_ok(m));
Bitboard key = st->key;
Key key = st->key;
// Copy some fields of old state to our new StateInfo object except the
// ones which are recalculated from scratch anyway, then switch our state
// pointer to point to the new, ready to be updated, state.
struct ReducedStateInfo {
Key pawnKey, materialKey;
int castleRights, rule50, pliesFromNull;
int castleRights, rule50, gamePly, pliesFromNull;
Square epSquare;
Value value;
Score value;
Value npMaterial[2];
};
@@ -681,8 +715,7 @@ void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveI
// Save the current key to the history[] array, in order to be able to
// detect repetition draws.
history[gamePly] = key;
gamePly++;
history[st->gamePly++] = key;
// Update side to move
key ^= zobSideToMove;
@@ -739,7 +772,7 @@ void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveI
}
// Prefetch TT access as soon as we know key is updated
TT.prefetch(key);
prefetch((char*)TT.first_entry(key));
// Move the piece
Bitboard move_bb = make_move_bb(from, to);
@@ -774,6 +807,46 @@ void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveI
key ^= zobEp[st->epSquare];
}
}
if (pm) // promotion ?
{
PieceType promotion = move_promotion_piece(m);
assert(promotion >= KNIGHT && promotion <= QUEEN);
// Insert promoted piece instead of pawn
clear_bit(&(byTypeBB[PAWN]), to);
set_bit(&(byTypeBB[promotion]), to);
board[to] = piece_of_color_and_type(us, promotion);
// Update piece counts
pieceCount[us][promotion]++;
pieceCount[us][PAWN]--;
// Update material key
st->materialKey ^= zobrist[us][PAWN][pieceCount[us][PAWN]];
st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]-1];
// Update piece lists, move the last pawn at index[to] position
// and shrink the list. Add a new promotion piece to the list.
Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
index[lastPawnSquare] = index[to];
pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
index[to] = pieceCount[us][promotion] - 1;
pieceList[us][promotion][index[to]] = to;
// Partially revert hash keys update
key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
st->pawnKey ^= zobrist[us][PAWN][to];
// Partially revert and update incremental scores
st->value -= pst(us, PAWN, to);
st->value += pst(us, promotion, to);
// Update material
st->npMaterial[us] += piece_value_midgame(promotion);
}
}
// Update incremental scores
@@ -782,46 +855,6 @@ void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveI
// Set capture piece
st->capture = capture;
if (pm) // promotion ?
{
PieceType promotion = move_promotion_piece(m);
assert(promotion >= KNIGHT && promotion <= QUEEN);
// Insert promoted piece instead of pawn
clear_bit(&(byTypeBB[PAWN]), to);
set_bit(&(byTypeBB[promotion]), to);
board[to] = piece_of_color_and_type(us, promotion);
// Update material key
st->materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
st->materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
// Update piece counts
pieceCount[us][PAWN]--;
pieceCount[us][promotion]++;
// Update piece lists, move the last pawn at index[to] position
// and shrink the list. Add a new promotion piece to the list.
Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
index[lastPawnSquare] = index[to];
pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
index[to] = pieceCount[us][promotion] - 1;
pieceList[us][promotion][index[to]] = to;
// Partially revert hash keys update
key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
st->pawnKey ^= zobrist[us][PAWN][to];
// Partially revert and update incremental scores
st->value -= pst(us, PAWN, to);
st->value += pst(us, promotion, to);
// Update material
st->npMaterial[us] += piece_value_midgame(promotion);
}
// Update the key with the final value
st->key = key;
@@ -861,23 +894,31 @@ void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveI
/// Position::do_capture_move() is a private method used to update captured
/// piece info. It is called from the main Position::do_move function.
void Position::do_capture_move(Bitboard& key, PieceType capture, Color them, Square to, bool ep) {
void Position::do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep) {
assert(capture != KING);
Square capsq = to;
if (ep) // en passant ?
// If the captured piece was a pawn, update pawn hash key,
// otherwise update non-pawn material.
if (capture == PAWN)
{
capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
if (ep) // en passant ?
{
capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
assert(to == st->epSquare);
assert(relative_rank(opposite_color(them), to) == RANK_6);
assert(piece_on(to) == EMPTY);
assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
assert(to == st->epSquare);
assert(relative_rank(opposite_color(them), to) == RANK_6);
assert(piece_on(to) == EMPTY);
assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
board[capsq] = EMPTY;
board[capsq] = EMPTY;
}
st->pawnKey ^= zobrist[them][PAWN][capsq];
}
else
st->npMaterial[them] -= piece_value_midgame(capture);
// Remove captured piece
clear_bit(&(byColorBB[them]), capsq);
@@ -890,19 +931,12 @@ void Position::do_capture_move(Bitboard& key, PieceType capture, Color them, Squ
// Update incremental scores
st->value -= pst(them, capture, capsq);
// If the captured piece was a pawn, update pawn hash key,
// otherwise update non-pawn material.
if (capture == PAWN)
st->pawnKey ^= zobrist[them][PAWN][capsq];
else
st->npMaterial[them] -= piece_value_midgame(capture);
// Update material hash key
st->materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
// Update piece count
pieceCount[them][capture]--;
// Update material hash key
st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
// Update piece list, move the last piece at index[capsq] position
//
// WARNING: This is a not perfectly revresible operation. When we
@@ -969,7 +1003,7 @@ void Position::do_castle_move(Move m) {
set_bit(&(byColorBB[us]), rto);
set_bit(&(byTypeBB[ROOK]), rto);
set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
// Update board array
Piece king = piece_of_color_and_type(us, KING);
Piece rook = piece_of_color_and_type(us, ROOK);
@@ -1026,7 +1060,6 @@ void Position::undo_move(Move m) {
assert(is_ok());
assert(move_is_ok(m));
gamePly--;
sideToMove = opposite_color(sideToMove);
if (move_is_castle(m))
@@ -1076,7 +1109,6 @@ void Position::undo_move(Move m) {
pieceList[us][PAWN][index[to]] = to;
}
// Put the piece back at the source square
Bitboard move_bb = make_move_bb(to, from);
do_move_bb(&(byColorBB[us]), move_bb);
@@ -1154,7 +1186,7 @@ void Position::undo_castle_move(Move m) {
assert(piece_on(kto) == piece_of_color_and_type(us, KING));
assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
// Remove pieces from destination squares:
clear_bit(&(byColorBB[us]), kto);
clear_bit(&(byTypeBB[KING]), kto);
@@ -1162,7 +1194,7 @@ void Position::undo_castle_move(Move m) {
clear_bit(&(byColorBB[us]), rto);
clear_bit(&(byTypeBB[ROOK]), rto);
clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
// Put pieces on source squares:
set_bit(&(byColorBB[us]), kfrom);
set_bit(&(byTypeBB[KING]), kfrom);
@@ -1211,21 +1243,20 @@ void Position::do_null_move(StateInfo& backupSt) {
// Save the current key to the history[] array, in order to be able to
// detect repetition draws.
history[gamePly] = st->key;
history[st->gamePly++] = st->key;
// Update the necessary information
if (st->epSquare != SQ_NONE)
st->key ^= zobEp[st->epSquare];
st->key ^= zobSideToMove;
TT.prefetch(st->key);
prefetch((char*)TT.first_entry(st->key));
sideToMove = opposite_color(sideToMove);
st->epSquare = SQ_NONE;
st->rule50++;
st->pliesFromNull = 0;
st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
gamePly++;
}
@@ -1247,7 +1278,7 @@ void Position::undo_null_move() {
// Update the necessary information
sideToMove = opposite_color(sideToMove);
st->rule50--;
gamePly--;
st->gamePly--;
}
@@ -1276,11 +1307,11 @@ int Position::see_sign(Move m) const {
Square from = move_from(m);
Square to = move_to(m);
// Early return if SEE cannot be negative because capturing piece value
// is not bigger then captured one.
if ( midgame_value_of_piece_on(from) <= midgame_value_of_piece_on(to)
&& type_of_piece_on(from) != KING)
return 1;
// Early return if SEE cannot be negative because captured piece value
// is not less then capturing one. Note that king moves always return
// here because king midgame value is set to 0.
if (midgame_value_of_piece_on(to) >= midgame_value_of_piece_on(from))
return 1;
return see(from, to);
}
@@ -1422,19 +1453,6 @@ int Position::see(Square from, Square to) const {
}
/// Position::saveState() copies the content of the current state
/// inside startState and makes st point to it. This is needed
/// when the st pointee could become stale, as example because
/// the caller is about to going out of scope.
void Position::saveState() {
startState = *st;
st = &startState;
st->previous = NULL; // as a safe guard
}
/// Position::clear() erases the position object to a pristine state, with an
/// empty board, white to move, and no castling rights.
@@ -1457,7 +1475,6 @@ void Position::clear() {
pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
sideToMove = WHITE;
gamePly = 0;
initialKFile = FILE_E;
initialKRFile = FILE_H;
initialQRFile = FILE_A;
@@ -1472,7 +1489,7 @@ void Position::clear() {
void Position::reset_game_ply() {
gamePly = 0;
st->gamePly = 0;
}
@@ -1553,7 +1570,7 @@ Key Position::compute_pawn_key() const {
for (Color c = WHITE; c <= BLACK; c++)
{
b = pieces(PAWN, c);
while(b)
while (b)
{
s = pop_1st_bit(&b);
result ^= zobrist[c][PAWN][s];
@@ -1576,8 +1593,8 @@ Key Position::compute_material_key() const {
for (PieceType pt = PAWN; pt <= QUEEN; pt++)
{
int count = piece_count(c, pt);
for (int i = 0; i <= count; i++)
result ^= zobMaterial[c][pt][i];
for (int i = 0; i < count; i++)
result ^= zobrist[c][pt][i];
}
return result;
}
@@ -1597,7 +1614,7 @@ Score Position::compute_value() const {
for (PieceType pt = PAWN; pt <= KING; pt++)
{
b = pieces(pt, c);
while(b)
while (b)
{
s = pop_1st_bit(&b);
assert(piece_on(s) == piece_of_color_and_type(c, pt));
@@ -1636,6 +1653,7 @@ Value Position::compute_non_pawn_material(Color c) const {
/// Position::is_draw() tests whether the position is drawn by material,
/// repetition, or the 50 moves rule. It does not detect stalemates, this
/// must be done by the search.
// FIXME: Currently we are not handling 50 move rule correctly when in check
bool Position::is_draw() const {
@@ -1649,8 +1667,8 @@ bool Position::is_draw() const {
return true;
// Draw by repetition?
for (int i = 2; i < Min(Min(gamePly, st->rule50), st->pliesFromNull); i += 2)
if (history[gamePly - i] == st->key)
for (int i = 4, e = Min(Min(st->gamePly, st->rule50), st->pliesFromNull); i <= e; i += 2)
if (history[st->gamePly - i] == st->key)
return true;
return false;
@@ -1729,15 +1747,6 @@ void Position::init_zobrist() {
zobCastle[i] = genrand_int64();
zobSideToMove = genrand_int64();
for (int i = 0; i < 2; i++)
for (int j = 0; j < 8; j++)
for (int k = 0; k < 16; k++)
zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
for (int i = 0; i < 16; i++)
zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
zobExclusion = genrand_int64();
}
@@ -1774,6 +1783,7 @@ void Position::flipped_copy(const Position& pos) {
assert(pos.is_ok());
clear();
threadID = pos.thread();
// Board
for (Square s = SQ_A1; s <= SQ_H8; s++)
@@ -1843,6 +1853,7 @@ bool Position::is_ok(int* failedStep) const {
static const bool debugNonPawnMaterial = false;
static const bool debugPieceCounts = false;
static const bool debugPieceList = false;
static const bool debugCastleSquares = false;
if (failedStep) *failedStep = 1;
@@ -1968,9 +1979,9 @@ bool Position::is_ok(int* failedStep) const {
if (failedStep) (*failedStep)++;
if (debugPieceList)
{
for(Color c = WHITE; c <= BLACK; c++)
for(PieceType pt = PAWN; pt <= KING; pt++)
for(int i = 0; i < pieceCount[c][pt]; i++)
for (Color c = WHITE; c <= BLACK; c++)
for (PieceType pt = PAWN; pt <= KING; pt++)
for (int i = 0; i < pieceCount[c][pt]; i++)
{
if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
return false;
@@ -1979,6 +1990,25 @@ bool Position::is_ok(int* failedStep) const {
return false;
}
}
if (failedStep) (*failedStep)++;
if (debugCastleSquares) {
for (Color c = WHITE; c <= BLACK; c++) {
if (can_castle_kingside(c) && piece_on(initial_kr_square(c)) != piece_of_color_and_type(c, ROOK))
return false;
if (can_castle_queenside(c) && piece_on(initial_qr_square(c)) != piece_of_color_and_type(c, ROOK))
return false;
}
if (castleRightsMask[initial_kr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OO))
return false;
if (castleRightsMask[initial_qr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OOO))
return false;
if (castleRightsMask[initial_kr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OO))
return false;
if (castleRightsMask[initial_qr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OOO))
return false;
}
if (failedStep) *failedStep = 0;
return true;
}

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -68,11 +68,11 @@ const int MaxGameLength = 220;
struct CheckInfo {
CheckInfo(const Position&);
explicit CheckInfo(const Position&);
Square ksq;
Bitboard dcCandidates;
Bitboard checkSq[8];
Square ksq;
};
/// Castle rights, encoded as bit fields
@@ -100,13 +100,13 @@ enum Phase {
struct StateInfo {
Key pawnKey, materialKey;
int castleRights, rule50, pliesFromNull;
int castleRights, rule50, gamePly, pliesFromNull;
Square epSquare;
Score value;
Value npMaterial[2];
Key key;
PieceType capture;
Key key;
Bitboard checkersBB;
StateInfo* previous;
};
@@ -139,6 +139,9 @@ class Position {
friend class MaterialInfo;
friend class EndgameFunctions;
Position(); // No default or copy c'tor allowed
Position(const Position& pos);
public:
enum GamePhase {
MidGame,
@@ -146,9 +149,9 @@ public:
};
// Constructors
Position() {}
Position(const Position& pos);
Position(const std::string& fen);
explicit Position(int threadID);
Position(const Position& pos, int threadID);
Position(const std::string& fen, int threadID);
// Text input/output
void from_fen(const std::string& fen);
@@ -156,7 +159,6 @@ public:
void print(Move m = MOVE_NONE) const;
// Copying
void copy(const Position& pos);
void flipped_copy(const Position& pos);
// The piece on a given square
@@ -224,17 +226,17 @@ public:
bool move_is_passed_pawn_push(Move m) const;
bool move_attacks_square(Move m, Square s) const;
// Piece captured with previous moves
PieceType captured_piece() const;
// Information about pawns
bool pawn_is_passed(Color c, Square s) const;
static bool pawn_is_passed(Bitboard theirPawns, Color c, Square s);
static bool pawn_is_isolated(Bitboard ourPawns, Square s);
static bool pawn_is_doubled(Bitboard ourPawns, Color c, Square s);
// Weak squares
bool square_is_weak(Square s, Color c) const;
// Doing and undoing moves
void saveState();
void detach();
void do_move(Move m, StateInfo& st);
void do_move(Move m, StateInfo& st, const CheckInfo& ci, bool moveIsCheck);
void undo_move(Move m);
@@ -272,6 +274,9 @@ public:
bool opposite_colored_bishops() const;
bool has_pawn_on_7th(Color c) const;
// Current thread ID searching on the position
int thread() const;
// Reset the gamePly variable to 0
void reset_game_ply();
@@ -291,7 +296,7 @@ private:
void allow_ooo(Color c);
// Helper functions for doing and undoing moves
void do_capture_move(Bitboard& key, PieceType capture, Color them, Square to, bool ep);
void do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep);
void do_castle_move(Move m);
void undo_castle_move(Move m);
void find_checkers();
@@ -324,18 +329,17 @@ private:
// Other info
Color sideToMove;
int gamePly;
Key history[MaxGameLength];
File initialKFile, initialKRFile, initialQRFile;
int castleRightsMask[64];
StateInfo startState;
File initialKFile, initialKRFile, initialQRFile;
int threadID;
StateInfo* st;
// Static variables
static int castleRightsMask[64];
static Key zobrist[2][8][64];
static Key zobEp[64];
static Key zobCastle[16];
static Key zobMaterial[2][8][16];
static Key zobSideToMove;
static Score PieceSquareTable[16][64];
static Key zobExclusion;
@@ -410,8 +414,8 @@ inline int Position::piece_count(Color c, PieceType pt) const {
return pieceCount[c][pt];
}
inline Square Position::piece_list(Color c, PieceType pt, int index) const {
return pieceList[c][pt][index];
inline Square Position::piece_list(Color c, PieceType pt, int idx) const {
return pieceList[c][pt][idx];
}
inline const Square* Position::piece_list_begin(Color c, PieceType pt) const {
@@ -483,20 +487,8 @@ inline bool Position::pawn_is_passed(Color c, Square s) const {
return !(pieces(PAWN, opposite_color(c)) & passed_pawn_mask(c, s));
}
inline bool Position::pawn_is_passed(Bitboard theirPawns, Color c, Square s) {
return !(theirPawns & passed_pawn_mask(c, s));
}
inline bool Position::pawn_is_isolated(Bitboard ourPawns, Square s) {
return !(ourPawns & neighboring_files_bb(s));
}
inline bool Position::pawn_is_doubled(Bitboard ourPawns, Color c, Square s) {
return ourPawns & squares_behind(c, s);
}
inline bool Position::square_is_weak(Square s, Color c) const {
return !(pieces(PAWN, c) & outpost_mask(opposite_color(c), s));
return !(pieces(PAWN, opposite_color(c)) & attack_span_mask(c, s));
}
inline Key Position::get_key() const {
@@ -567,4 +559,12 @@ inline bool Position::move_is_capture_or_promotion(Move m) const {
return (m & (0x1F << 12)) ? !move_is_castle(m) : !square_is_empty(move_to(m));
}
inline PieceType Position::captured_piece() const {
return st->capture;
}
inline int Position::thread() const {
return threadID;
}
#endif // !defined(POSITION_H_INCLUDED)

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -47,7 +47,7 @@ namespace {
AMBIGUITY_BOTH
};
const History H; // used as dummy argument for MovePicker c'tor
const History H; // Used as dummy argument for MovePicker c'tor
Ambiguity move_ambiguity(const Position& pos, Move m);
const string time_string(int milliseconds);
@@ -63,33 +63,30 @@ namespace {
/// that the move is a legal move from the position. The return value is
/// a string containing the move in short algebraic notation.
const string move_to_san(const Position& pos, Move m) {
const string move_to_san(Position& pos, Move m) {
assert(pos.is_ok());
assert(move_is_ok(m));
Square from, to;
PieceType pt;
from = move_from(m);
to = move_to(m);
pt = type_of_piece(pos.piece_on(move_from(m)));
string san = "";
string san;
Square from = move_from(m);
Square to = move_to(m);
PieceType pt = type_of_piece(pos.piece_on(move_from(m)));
if (m == MOVE_NONE)
return "(none)";
else if (m == MOVE_NULL)
return "(null)";
else if (move_is_long_castle(m) || (int(to - from) == -2 && pt == KING))
else if (move_is_long_castle(m) || (int(to - from) == -2 && pt == KING))
san = "O-O-O";
else if (move_is_short_castle(m) || (int(to - from) == 2 && pt == KING))
else if (move_is_short_castle(m) || (int(to - from) == 2 && pt == KING))
san = "O-O";
else
{
if (pt != PAWN)
{
san += piece_type_to_char(pt, true);
switch (move_ambiguity(pos, m)) {
case AMBIGUITY_NONE:
break;
@@ -115,18 +112,18 @@ const string move_to_san(const Position& pos, Move m) {
san += square_to_string(move_to(m));
if (move_is_promotion(m))
{
san += '=';
san += "=";
san += piece_type_to_char(move_promotion_piece(m), true);
}
}
// Is the move check? We don't use pos.move_is_check(m) here, because
// Position::move_is_check doesn't detect all checks (not castling moves,
// promotions and en passant captures).
// The move gives check ? We don't use pos.move_is_check() here
// because we need to test for mate after the move is done.
StateInfo st;
Position p(pos);
p.do_move(m, st);
if (p.is_check())
san += p.is_mate()? "#" : "+";
pos.do_move(m, st);
if (pos.is_check())
san += pos.is_mate() ? "#" : "+";
pos.undo_move(m);
return san;
}
@@ -299,23 +296,23 @@ const string line_to_san(const Position& pos, Move line[], int startColumn, bool
string moveStr;
size_t length = 0;
size_t maxLength = 80 - startColumn;
Position p(pos);
Position p(pos, pos.thread());
for (int i = 0; line[i] != MOVE_NONE; i++)
for (Move* m = line; *m != MOVE_NONE; m++)
{
moveStr = move_to_san(p, line[i]);
moveStr = move_to_san(p, *m);
length += moveStr.length() + 1;
if (breakLines && length > maxLength)
{
s << '\n' << std::setw(startColumn) << ' ';
s << "\n" << std::setw(startColumn) << " ";
length = moveStr.length() + 1;
}
s << moveStr << ' ';
if (line[i] == MOVE_NULL)
if (*m == MOVE_NULL)
p.do_null_move(st);
else
p.do_move(line[i], st);
p.do_move(*m, st);
}
return s.str();
}
@@ -325,27 +322,31 @@ const string line_to_san(const Position& pos, Move line[], int startColumn, bool
/// It is used to write search information to the log file (which is created
/// when the UCI parameter "Use Search Log" is "true").
const string pretty_pv(const Position& pos, int time, int depth,
uint64_t nodes, Value score, ValueType type, Move pv[]) {
const string pretty_pv(const Position& pos, int time, int depth, uint64_t nodes,
Value score, ValueType type, Move pv[]) {
const uint64_t K = 1000;
const uint64_t M = 1000000;
std::stringstream s;
// Depth
s << std::setw(2) << depth << " ";
// Score
s << ((type == VALUE_TYPE_LOWER)? ">" : ((type == VALUE_TYPE_UPPER)? "<" : " "));
s << std::setw(7) << score_string(score);
s << (type == VALUE_TYPE_LOWER ? ">" : type == VALUE_TYPE_UPPER ? "<" : " ")
<< std::setw(7) << score_string(score);
// Time
s << std::setw(8) << time_string(time) << " ";
// Nodes
if (nodes < 1000000ULL)
s << std::setw(8) << nodes << " ";
else if (nodes < 1000000000ULL)
s << std::setw(7) << nodes/1000ULL << 'k' << " ";
if (nodes < M)
s << std::setw(8) << nodes / 1 << " ";
else if (nodes < K * M)
s << std::setw(7) << nodes / K << "K ";
else
s << std::setw(7) << nodes/1000000ULL << 'M' << " ";
s << std::setw(7) << nodes / M << "M ";
// PV
s << line_to_san(pos, pv, 30, true);
@@ -398,14 +399,17 @@ namespace {
}
const string time_string(int milliseconds) {
const string time_string(int millisecs) {
const int MSecMinute = 1000 * 60;
const int MSecHour = 1000 * 60 * 60;
std::stringstream s;
s << std::setfill('0');
int hours = milliseconds / (1000*60*60);
int minutes = (milliseconds - hours*1000*60*60) / (1000*60);
int seconds = (milliseconds - hours*1000*60*60 - minutes*1000*60) / 1000;
int hours = millisecs / MSecHour;
int minutes = (millisecs - hours * MSecHour) / MSecMinute;
int seconds = (millisecs - hours * MSecHour - minutes * MSecMinute) / 1000;
if (hours)
s << hours << ':';
@@ -421,7 +425,7 @@ namespace {
if (v >= VALUE_MATE - 200)
s << "#" << (VALUE_MATE - v + 1) / 2;
else if(v <= -VALUE_MATE + 200)
else if (v <= -VALUE_MATE + 200)
s << "-#" << (VALUE_MATE + v) / 2;
else
{

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -36,7 +36,7 @@
//// Prototypes
////
extern const std::string move_to_san(const Position& pos, Move m);
extern const std::string move_to_san(Position& pos, Move m);
extern Move move_from_san(const Position& pos, const std::string& str);
extern const std::string line_to_san(const Position& pos, Move line[], int startColumn, bool breakLines);
extern const std::string pretty_pv(const Position& pos, int time, int depth, uint64_t nodes, Value score, ValueType type, Move pv[]);

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -27,6 +27,7 @@
#include "depth.h"
#include "move.h"
#include "value.h"
////
@@ -46,16 +47,20 @@ const int KILLER_MAX = 2;
/// from nodes shallower and deeper in the tree during the search. Each
/// search thread has its own array of SearchStack objects, indexed by the
/// current ply.
struct EvalInfo;
struct SearchStack {
Move pv[PLY_MAX_PLUS_2];
Move currentMove;
Move mateKiller;
Move threatMove;
Move excludedMove;
Move bestMove;
Move killers[KILLER_MAX];
Depth reduction;
Value eval;
bool skipNullMove;
void init(int ply);
void init();
void initKillers();
};
@@ -64,8 +69,9 @@ struct SearchStack {
//// Prototypes
////
extern void init_search();
extern void init_threads();
extern void stop_threads();
extern void exit_threads();
extern bool think(const Position &pos, bool infinite, bool ponder, int side_to_move,
int time[], int increment[], int movesToGo, int maxDepth,
int maxNodes, int maxTime, Move searchMoves[]);

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -26,6 +26,8 @@
//// Includes
////
#include <cstring>
#include "lock.h"
#include "movepick.h"
#include "position.h"
@@ -36,7 +38,8 @@
//// Constants and variables
////
const int THREAD_MAX = 8;
const int MAX_THREADS = 8;
const int ACTIVE_SPLIT_POINTS_MAX = 8;
////
@@ -44,35 +47,47 @@ const int THREAD_MAX = 8;
////
struct SplitPoint {
SplitPoint *parent;
Position pos;
SearchStack sstack[THREAD_MAX][PLY_MAX_PLUS_2];
SearchStack *parentSstack;
int ply;
// Const data after splitPoint has been setup
SplitPoint* parent;
const Position* pos;
Depth depth;
volatile Value alpha, beta, bestValue, futilityValue;
Value approximateEval;
bool pvNode;
int master, slaves[THREAD_MAX];
bool pvNode, mateThreat;
Value beta;
int ply;
SearchStack sstack[MAX_THREADS][PLY_MAX_PLUS_2];
// Const pointers to shared data
MovePicker* mp;
SearchStack* parentSstack;
// Shared data
Lock lock;
MovePicker *mp;
volatile int moves;
volatile int cpus;
bool finished;
volatile Value alpha;
volatile Value bestValue;
volatile int moveCount;
volatile bool stopRequest;
volatile int slaves[MAX_THREADS];
};
// ThreadState type is used to represent thread's current state
enum ThreadState
{
THREAD_SEARCHING, // thread is performing work
THREAD_AVAILABLE, // thread is polling for work
THREAD_SLEEPING, // we are not thinking, so thread is sleeping
THREAD_BOOKED, // other thread (master) has booked us as a slave
THREAD_WORKISWAITING, // master has ordered us to start
THREAD_TERMINATED // we are quitting and thread is terminated
};
struct Thread {
SplitPoint *splitPoint;
int activeSplitPoints;
SplitPoint* volatile splitPoint;
volatile int activeSplitPoints;
uint64_t nodes;
uint64_t betaCutOffs[2];
bool failHighPly1;
volatile bool stop;
volatile bool running;
volatile bool idle;
volatile bool workIsWaiting;
volatile bool printCurrentLine;
volatile ThreadState state;
unsigned char pad[64]; // set some distance among local data for each thread
};

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -25,7 +25,6 @@
#include <cassert>
#include <cmath>
#include <cstring>
#include <xmmintrin.h>
#include "movegen.h"
#include "tt.h"
@@ -39,7 +38,7 @@ TranspositionTable TT;
TranspositionTable::TranspositionTable() {
size = writes = 0;
size = overwrites = 0;
entries = 0;
generation = 0;
}
@@ -53,11 +52,9 @@ TranspositionTable::~TranspositionTable() {
/// TranspositionTable::set_size sets the size of the transposition table,
/// measured in megabytes.
void TranspositionTable::set_size(unsigned mbSize) {
void TranspositionTable::set_size(size_t mbSize) {
assert(mbSize >= 4 && mbSize <= 4096);
unsigned newSize = 1024;
size_t newSize = 1024;
// We store a cluster of ClusterSize number of TTEntry for each position
// and newSize is the maximum number of storable positions.
@@ -91,16 +88,6 @@ void TranspositionTable::clear() {
}
/// TranspositionTable::first_entry returns a pointer to the first
/// entry of a cluster given a position. The low 32 bits of the key
/// are used to get the index in the table.
inline TTEntry* TranspositionTable::first_entry(const Key posKey) const {
return entries[uint32_t(posKey) & (size - 1)].data;
}
/// TranspositionTable::store writes a new entry containing a position,
/// a value, a value type, a search depth, and a best move to the
/// transposition table. Transposition table is organized in clusters of
@@ -111,8 +98,9 @@ inline TTEntry* TranspositionTable::first_entry(const Key posKey) const {
/// is bigger than the depth of t2. A TTEntry of type VALUE_TYPE_EVAL
/// never replaces another entry for the same position.
void TranspositionTable::store(const Key posKey, Value v, ValueType t, Depth d, Move m) {
void TranspositionTable::store(const Key posKey, Value v, ValueType t, Depth d, Move m, Value statV, Value kingD) {
int c1, c2, c3;
TTEntry *tte, *replace;
uint32_t posKey32 = posKey >> 32; // Use the high 32 bits as key
@@ -121,28 +109,26 @@ void TranspositionTable::store(const Key posKey, Value v, ValueType t, Depth d,
{
if (!tte->key() || tte->key() == posKey32) // empty or overwrite old
{
// Do not overwrite when new type is VALUE_TYPE_EV_LO
if (tte->key() && t == VALUE_TYPE_EV_LO)
return;
// Preserve any exsisting ttMove
if (m == MOVE_NONE)
m = tte->move();
*tte = TTEntry(posKey32, v, t, d, m, generation);
tte->save(posKey32, v, t, d, m, generation, statV, kingD);
return;
}
else if (i == 0) // replace would be a no-op in this common case
if (i == 0) // replace would be a no-op in this common case
continue;
int c1 = (replace->generation() == generation ? 2 : 0);
int c2 = (tte->generation() == generation ? -2 : 0);
int c3 = (tte->depth() < replace->depth() ? 1 : 0);
c1 = (replace->generation() == generation ? 2 : 0);
c2 = (tte->generation() == generation ? -2 : 0);
c3 = (tte->depth() < replace->depth() ? 1 : 0);
if (c1 + c2 + c3 > 0)
replace = tte;
}
*replace = TTEntry(posKey32, v, t, d, m, generation);
writes++;
replace->save(posKey32, v, t, d, m, generation, statV, kingD);
overwrites++;
}
@@ -163,27 +149,6 @@ TTEntry* TranspositionTable::retrieve(const Key posKey) const {
}
/// TranspositionTable::prefetch looks up the current position in the
/// transposition table and load it in L1/L2 cache. This is a non
/// blocking function and do not stalls the CPU waiting for data
/// to be loaded from RAM, that can be very slow. When we will
/// subsequently call retrieve() the TT data will be already
/// quickly accessible in L1/L2 CPU cache.
void TranspositionTable::prefetch(const Key posKey) const {
#if defined(__INTEL_COMPILER) || defined(__ICL)
// This hack prevents prefetches to be optimized away by the
// Intel compiler. Both MSVC and gcc seems not affected.
__asm__ ("");
#endif
char const* addr = (char*)first_entry(posKey);
_mm_prefetch(addr, _MM_HINT_T2);
_mm_prefetch(addr+64, _MM_HINT_T2); // 64 bytes ahead
}
/// TranspositionTable::new_search() is called at the beginning of every new
/// search. It increments the "generation" variable, which is used to
/// distinguish transposition table entries from previous searches from
@@ -192,7 +157,7 @@ void TranspositionTable::prefetch(const Key posKey) const {
void TranspositionTable::new_search() {
generation++;
writes = 0;
overwrites = 0;
}
@@ -204,13 +169,13 @@ void TranspositionTable::new_search() {
void TranspositionTable::insert_pv(const Position& pos, Move pv[]) {
StateInfo st;
Position p(pos);
Position p(pos, pos.thread());
for (int i = 0; pv[i] != MOVE_NONE; i++)
{
TTEntry *tte = retrieve(p.get_key());
if (!tte || tte->move() != pv[i])
store(p.get_key(), VALUE_NONE, VALUE_TYPE_NONE, Depth(-127*OnePly), pv[i]);
store(p.get_key(), VALUE_NONE, VALUE_TYPE_NONE, Depth(-127*OnePly), pv[i], VALUE_NONE, VALUE_NONE);
p.do_move(pv[i], st);
}
}
@@ -222,20 +187,23 @@ void TranspositionTable::insert_pv(const Position& pos, Move pv[]) {
/// will often get single-move PVs when the search stops while failing high,
/// and a single-move PV means that we don't have a ponder move.
void TranspositionTable::extract_pv(const Position& pos, Move pv[], const int PLY_MAX) {
void TranspositionTable::extract_pv(const Position& pos, Move bestMove, Move pv[], const int PLY_MAX) {
const TTEntry* tte;
StateInfo st;
Position p(pos);
Position p(pos, pos.thread());
int ply = 0;
// Update position to the end of current PV
while (pv[ply] != MOVE_NONE)
p.do_move(pv[ply++], st);
assert(bestMove != MOVE_NONE);
// Try to add moves from TT while possible
pv[ply] = bestMove;
p.do_move(pv[ply++], st);
// Extract moves from TT when possible. We try hard to always
// get a ponder move, that's the reason of ply < 2 conditions.
while ( (tte = retrieve(p.get_key())) != NULL
&& tte->move() != MOVE_NONE
&& (tte->type() == VALUE_TYPE_EXACT || ply < 2)
&& move_is_legal(p, tte->move())
&& (!p.is_draw() || ply < 2)
&& ply < PLY_MAX)
@@ -248,11 +216,11 @@ void TranspositionTable::extract_pv(const Position& pos, Move pv[], const int PL
/// TranspositionTable::full() returns the permill of all transposition table
/// entries which have received at least one write during the current search.
/// entries which have received at least one overwrite during the current search.
/// It is used to display the "info hashfull ..." information in UCI.
int TranspositionTable::full() const {
double N = double(size) * ClusterSize;
return int(1000 * (1 - exp(writes * log(1.0 - 1.0/N))));
return int(1000 * (1 - exp(overwrites * log(1.0 - 1.0/N))));
}

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -53,36 +53,45 @@
class TTEntry {
public:
TTEntry() {}
TTEntry(uint32_t k, Value v, ValueType t, Depth d, Move m, int generation)
: key_ (k), data((m & 0x1FFFF) | (t << 20) | (generation << 23)),
value_(int16_t(v)), depth_(int16_t(d)) {}
void save(uint32_t k, Value v, ValueType t, Depth d, Move m, int g, Value statV, Value kd) {
uint32_t key() const { return key_; }
Depth depth() const { return Depth(depth_); }
key32 = k;
data = (m & 0x1FFFF) | (t << 20) | (g << 23);
value16 = int16_t(v);
depth16 = int16_t(d);
staticValue = int16_t(statV);
kingDanger = int16_t(kd);
}
uint32_t key() const { return key32; }
Depth depth() const { return Depth(depth16); }
Move move() const { return Move(data & 0x1FFFF); }
Value value() const { return Value(value_); }
Value value() const { return Value(value16); }
ValueType type() const { return ValueType((data >> 20) & 7); }
int generation() const { return (data >> 23); }
int generation() const { return data >> 23; }
Value static_value() const { return Value(staticValue); }
Value king_danger() const { return Value(kingDanger); }
private:
uint32_t key_;
uint32_t key32;
uint32_t data;
int16_t value_;
int16_t depth_;
int16_t value16;
int16_t depth16;
int16_t staticValue;
int16_t kingDanger;
};
/// This is the number of TTEntry slots for each position
const int ClusterSize = 5;
const int ClusterSize = 4;
/// Each group of ClusterSize number of TTEntry form a TTCluster
/// that is indexed by a single position key. Cluster is padded
/// to a cache line size so to guarantee always aligned accesses.
/// that is indexed by a single position key. TTCluster size must
/// be not bigger then a cache line size, in case it is less then
/// it should be padded to guarantee always aligned accesses.
struct TTCluster {
TTEntry data[ClusterSize];
char cache_line_padding[64 - sizeof(TTEntry[ClusterSize])];
};
@@ -95,30 +104,38 @@ class TranspositionTable {
public:
TranspositionTable();
~TranspositionTable();
void set_size(unsigned mbSize);
void set_size(size_t mbSize);
void clear();
void store(const Key posKey, Value v, ValueType type, Depth d, Move m);
void store(const Key posKey, Value v, ValueType type, Depth d, Move m, Value statV, Value kingD);
TTEntry* retrieve(const Key posKey) const;
void prefetch(const Key posKey) const;
void new_search();
void insert_pv(const Position& pos, Move pv[]);
void extract_pv(const Position& pos, Move pv[], const int PLY_MAX);
void extract_pv(const Position& pos, Move bestMove, Move pv[], const int PLY_MAX);
int full() const;
TTEntry* first_entry(const Key posKey) const;
private:
inline TTEntry* first_entry(const Key posKey) const;
// Be sure 'writes' is at least one cache line away
// Be sure 'overwrites' is at least one cache line away
// from read only variables.
unsigned char pad_before[64 - sizeof(unsigned)];
unsigned writes; // heavy SMP read/write access here
unsigned overwrites; // heavy SMP read/write access here
unsigned char pad_after[64];
unsigned size;
size_t size;
TTCluster* entries;
uint8_t generation;
};
extern TranspositionTable TT;
/// TranspositionTable::first_entry returns a pointer to the first
/// entry of a cluster given a position. The low 32 bits of the key
/// are used to get the index in the table.
inline TTEntry* TranspositionTable::first_entry(const Key posKey) const {
return entries[uint32_t(posKey) & (size - 1)].data;
}
#endif // !defined(TT_H_INCLUDED)

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -49,20 +49,32 @@ typedef uint64_t Bitboard;
////
//// Compiler specific defines
//// Configuration
////
// Quiet a warning on Intel compiler
#if !defined(__SIZEOF_INT__ )
#define __SIZEOF_INT__ 0
#endif
//// For Linux and OSX configuration is done automatically using Makefile.
//// To get started type "make help".
////
//// For windows part of the configuration is detected automatically, but
//// some switches need to be set manually:
////
//// -DNDEBUG | Disable debugging mode. Use always.
////
//// -DNO_PREFETCH | Disable use of prefetch asm-instruction. A must if you want the
//// | executable to run on some very old machines.
////
//// -DUSE_POPCNT | Add runtime support for use of popcnt asm-instruction.
//// | Works only in 64-bit mode. For compiling requires hardware
//// | with popcnt support. Around 4% speed-up.
// Check for 64 bits for different compilers: Intel, MSVC and gcc
#if defined(__x86_64) || defined(_M_X64) || defined(_WIN64) || (__SIZEOF_INT__ > 4)
// Automatic detection for 64-bit under Windows
#if defined(_WIN64)
#define IS_64BIT
#endif
#if defined(IS_64BIT) && (defined(__GNUC__) || defined(__INTEL_COMPILER))
// Automatic detection for use of bsfq asm-instruction under Windows.
// Works only in 64-bit mode. Does not work with MSVC.
#if defined(_WIN64) && defined(__INTEL_COMPILER)
#define USE_BSFQ
#endif
@@ -73,4 +85,28 @@ typedef uint64_t Bitboard;
#define CACHE_LINE_ALIGNMENT __attribute__ ((aligned(64)))
#endif
// Define a __cpuid() function for gcc compilers, for Intel and MSVC
// is already available as an intrinsic.
#if defined(_MSC_VER)
#include <intrin.h>
#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
inline void __cpuid(int CPUInfo[4], int InfoType)
{
int* eax = CPUInfo + 0;
int* ebx = CPUInfo + 1;
int* ecx = CPUInfo + 2;
int* edx = CPUInfo + 3;
*eax = InfoType;
*ecx = 0;
__asm__("cpuid" : "=a" (*eax), "=b" (*ebx), "=c" (*ecx), "=d" (*edx)
: "0" (*eax), "2" (*ecx));
}
#else
inline void __cpuid(int CPUInfo[4], int)
{
CPUInfo[0] = CPUInfo[1] = CPUInfo[2] = CPUInfo[3] = 0;
}
#endif
#endif // !defined(TYPES_H_INCLUDED)

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -54,7 +54,7 @@ namespace {
// The root position. This is set up when the user (or in practice, the GUI)
// sends the "position" UCI command. The root position is sent to the think()
// function when the program receives the "go" command.
Position RootPosition;
Position RootPosition(0);
// Local functions
bool handle_command(const string& command);
@@ -107,7 +107,8 @@ namespace {
UCIInputParser uip(command);
string token;
uip >> token; // operator>>() skips any whitespace
if (!(uip >> token)) // operator>>() skips any whitespace
return true;
if (token == "quit")
return false;
@@ -142,7 +143,7 @@ namespace {
RootPosition.print();
else if (token == "flip")
{
Position p(RootPosition);
Position p(RootPosition, RootPosition.thread());
RootPosition.flipped_copy(p);
}
else if (token == "eval")
@@ -150,7 +151,7 @@ namespace {
EvalInfo ei;
cout << "Incremental mg: " << mg_value(RootPosition.value())
<< "\nIncremental eg: " << eg_value(RootPosition.value())
<< "\nFull eval: " << evaluate(RootPosition, ei, 0) << endl;
<< "\nFull eval: " << evaluate(RootPosition, ei) << endl;
}
else if (token == "key")
cout << "key: " << hex << RootPosition.get_key()
@@ -159,14 +160,8 @@ namespace {
else if (token == "perft")
perft(uip);
else
{
cout << "Unknown command: " << command << endl;
while (!uip.eof())
{
uip >> token;
cout << token << endl;
}
}
return true;
}
@@ -181,33 +176,33 @@ namespace {
string token;
uip >> token; // operator>>() skips any whitespace
if (!(uip >> token)) // operator>>() skips any whitespace
return;
if (token == "startpos")
RootPosition.from_fen(StartPosition);
else if (token == "fen")
{
string fen;
while (token != "moves" && !uip.eof())
while (uip >> token && token != "moves")
{
uip >> token;
fen += token;
fen += ' ';
}
RootPosition.from_fen(fen);
}
if (!uip.eof())
if (uip.good())
{
if (token != "moves")
uip >> token;
if (token == "moves")
{
Move move;
StateInfo st;
while (!uip.eof())
while (uip >> token)
{
uip >> token;
move = move_from_string(RootPosition, token);
RootPosition.do_move(move, st);
if (RootPosition.rule_50_counter() == 0)
@@ -215,7 +210,7 @@ namespace {
}
// Our StateInfo st is about going out of scope so copy
// its content inside RootPosition before they disappear.
RootPosition.saveState();
RootPosition.detach();
}
}
}
@@ -229,27 +224,22 @@ namespace {
void set_option(UCIInputParser& uip) {
string token, name;
string token, name, value;
uip >> token;
if (token == "name")
if (!(uip >> token)) // operator>>() skips any whitespace
return;
if (token == "name" && uip >> name)
{
uip >> name;
while (!uip.eof())
{
uip >> token;
if (token == "value")
break;
while (uip >> token && token != "value")
name += (" " + token);
}
if (token == "value")
{
// Reads until end of line and left trim white space
getline(uip, token);
token.erase(0, token.find_first_not_of(" \n\r\t"));
set_option_value(name, token);
if (token == "value" && uip >> value)
{
while (uip >> token)
value += (" " + token);
set_option_value(name, value);
} else
push_button(name);
}
@@ -276,10 +266,8 @@ namespace {
searchMoves[0] = MOVE_NONE;
while (!uip.eof())
while (uip >> token)
{
uip >> token;
if (token == "infinite")
infinite = true;
else if (token == "ponder")
@@ -303,18 +291,13 @@ namespace {
else if (token == "searchmoves")
{
int numOfMoves = 0;
while (!uip.eof())
{
uip >> token;
while (uip >> token)
searchMoves[numOfMoves++] = move_from_string(RootPosition, token);
}
searchMoves[numOfMoves] = MOVE_NONE;
}
}
if (moveTime)
infinite = true; // HACK
assert(RootPosition.is_ok());
return think(RootPosition, infinite, ponder, RootPosition.side_to_move(),
@@ -325,12 +308,11 @@ namespace {
string token;
int depth, tm, n;
Position pos = RootPosition;
Position pos(RootPosition, RootPosition.thread());
if (uip.eof())
if (!(uip >> depth))
return;
uip >> depth;
tm = get_system_time();
n = perft(pos, depth * OnePly);

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -79,6 +79,7 @@ namespace {
o["Use Search Log"] = Option(false);
o["Search Log Filename"] = Option("SearchLog.txt");
o["Book File"] = Option("book.bin");
o["Best Book Move"] = Option(false);
o["Mobility (Middle Game)"] = Option(100, 0, 200);
o["Mobility (Endgame)"] = Option(100, 0, 200);
o["Pawn Structure (Middle Game)"] = Option(100, 0, 200);
@@ -88,48 +89,28 @@ namespace {
o["Space"] = Option(100, 0, 200);
o["Aggressiveness"] = Option(100, 0, 200);
o["Cowardice"] = Option(100, 0, 200);
o["King Safety Curve"] = Option("Quadratic", COMBO);
o["King Safety Curve"].comboValues.push_back("Quadratic");
o["King Safety Curve"].comboValues.push_back("Linear"); /*, "From File"*/
o["King Safety Coefficient"] = Option(40, 1, 100);
o["King Safety X Intercept"] = Option(0, 0, 20);
o["King Safety Max Slope"] = Option(30, 10, 100);
o["King Safety Max Value"] = Option(500, 100, 1000);
o["Queen Contact Check Bonus"] = Option(3, 0, 8);
o["Queen Check Bonus"] = Option(2, 0, 4);
o["Rook Check Bonus"] = Option(1, 0, 4);
o["Bishop Check Bonus"] = Option(1, 0, 4);
o["Knight Check Bonus"] = Option(1, 0, 4);
o["Discovered Check Bonus"] = Option(3, 0, 8);
o["Mate Threat Bonus"] = Option(3, 0, 8);
o["Check Extension (PV nodes)"] = Option(2, 0, 2);
o["Check Extension (non-PV nodes)"] = Option(1, 0, 2);
o["Single Reply Extension (PV nodes)"] = Option(2, 0, 2);
o["Single Reply Extension (non-PV nodes)"] = Option(2, 0, 2);
o["Mate Threat Extension (PV nodes)"] = Option(0, 0, 2);
o["Mate Threat Extension (non-PV nodes)"] = Option(0, 0, 2);
o["Single Evasion Extension (PV nodes)"] = Option(2, 0, 2);
o["Single Evasion Extension (non-PV nodes)"] = Option(2, 0, 2);
o["Mate Threat Extension (PV nodes)"] = Option(2, 0, 2);
o["Mate Threat Extension (non-PV nodes)"] = Option(2, 0, 2);
o["Pawn Push to 7th Extension (PV nodes)"] = Option(1, 0, 2);
o["Pawn Push to 7th Extension (non-PV nodes)"] = Option(1, 0, 2);
o["Passed Pawn Extension (PV nodes)"] = Option(1, 0, 2);
o["Passed Pawn Extension (non-PV nodes)"] = Option(0, 0, 2);
o["Pawn Endgame Extension (PV nodes)"] = Option(2, 0, 2);
o["Pawn Endgame Extension (non-PV nodes)"] = Option(2, 0, 2);
o["Full Depth Moves (PV nodes)"] = Option(10, 1, 100);
o["Full Depth Moves (non-PV nodes)"] = Option(3, 1, 100);
o["Threat Depth"] = Option(5, 0, 100);
o["Randomness"] = Option(0, 0, 10);
o["Minimum Split Depth"] = Option(4, 4, 7);
o["Maximum Number of Threads per Split Point"] = Option(5, 4, 8);
o["Threads"] = Option(1, 1, 8);
o["Hash"] = Option(32, 4, 4096);
o["Threads"] = Option(1, 1, MAX_THREADS);
o["Hash"] = Option(32, 4, 8192);
o["Clear Hash"] = Option(false, BUTTON);
o["New Game"] = Option(false, BUTTON);
o["Ponder"] = Option(true);
o["OwnBook"] = Option(true);
o["MultiPV"] = Option(1, 1, 500);
o["UCI_ShowCurrLine"] = Option(false);
o["UCI_Chess960"] = Option(false);
o["UCI_AnalyseMode"] = Option(false);
@@ -196,15 +177,18 @@ void init_uci_options() {
load_defaults(options);
// Limit the default value of "Threads" to 7 even if we have 8 CPU cores.
// According to Ken Dail's tests, Glaurung plays much better with 7 than
// with 8 threads. This is weird, but it is probably difficult to find out
// why before I have a 8-core computer to experiment with myself.
// Set optimal value for parameter "Minimum Split Depth"
// according to number of available cores.
assert(options.find("Threads") != options.end());
assert(options.find("Minimum Split Depth") != options.end());
options["Threads"].defaultValue = stringify(Min(cpu_count(), 7));
options["Threads"].currentValue = stringify(Min(cpu_count(), 7));
Option& thr = options["Threads"];
Option& msd = options["Minimum Split Depth"];
thr.defaultValue = thr.currentValue = stringify(cpu_count());
if (cpu_count() >= 8)
msd.defaultValue = msd.currentValue = stringify(7);
}
@@ -292,10 +276,28 @@ void set_option_value(const string& name, const string& value) {
else if (v == "false")
v = "0";
if (options.find(name) != options.end())
options[name].currentValue = v;
else
if (options.find(name) == options.end())
{
std::cout << "No such option: " << name << std::endl;
return;
}
// Normally it's up to the GUI to check for option's limits,
// but we could receive the new value directly from the user
// by teminal window. So let's check the bounds anyway.
Option& opt = options[name];
if (opt.type == CHECK && v != "0" && v != "1")
return;
else if (opt.type == SPIN)
{
int val = atoi(v.c_str());
if (val < opt.minValue || val > opt.maxValue)
return;
}
opt.currentValue = v;
}
@@ -315,7 +317,7 @@ void push_button(const string& buttonName) {
bool button_was_pressed(const string& buttonName) {
if (!get_option_value<bool>(buttonName))
return false;
return false;
set_option_value(buttonName, "false");
return true;

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -33,13 +33,10 @@
////
enum ValueType {
VALUE_TYPE_NONE = 0,
VALUE_TYPE_NONE = 0,
VALUE_TYPE_UPPER = 1, // Upper bound
VALUE_TYPE_LOWER = 2, // Lower bound
VALUE_TYPE_EXACT = 3, // Exact score
VALUE_TYPE_EVAL = 4, // Evaluation cache
VALUE_TYPE_EV_UP = 5, // Evaluation cache for upper bound
VALUE_TYPE_EV_LO = 6 // Evaluation cache for lower bound
VALUE_TYPE_EXACT = VALUE_TYPE_UPPER | VALUE_TYPE_LOWER
};
@@ -48,17 +45,31 @@ enum Value {
VALUE_KNOWN_WIN = 15000,
VALUE_MATE = 30000,
VALUE_INFINITE = 30001,
VALUE_NONE = 30002
VALUE_NONE = 30002,
VALUE_ENSURE_SIGNED = -1
};
/// Score struct keeps a midgame and an endgame value in a single
/// ScoreValue 64 bit union.
/// Score enum keeps a midgame and an endgame value in a single
/// integer (enum), first LSB 16 bits are used to store endgame
/// value, while upper bits are used for midgame value.
enum Score {};
// Compiler is free to choose the enum type as long as can keep
// its data, so ensure Score to be an integer type.
enum Score { ENSURE_32_BITS_SIZE_P = (1 << 16), ENSURE_32_BITS_SIZE_N = -(1 << 16)};
// Extracting the _signed_ lower and upper 16 bits it not so trivial
// because according to the standard a simple cast to short is
// implementation defined and so is a right shift of a signed integer.
inline Value mg_value(Score s) { return Value(((int(s) + 32768) & ~0xffff) / 0x10000); }
// Unfortunatly on Intel 64 bit we have a small speed regression, so use a faster code in
// this case, although not 100% standard compliant it seems to work for Intel and MSVC.
#if defined(IS_64BIT) && (!defined(__GNUC__) || defined(__INTEL_COMPILER))
inline Value eg_value(Score s) { return Value(int16_t(s & 0xffff)); }
inline Value mg_value(Score s) { return Value((int(s) + 32768) >> 16); }
#else
inline Value eg_value(Score s) { return Value((int)(unsigned(s) & 0x7fffu) - (int)(unsigned(s) & 0x8000u)); }
#endif
inline Score make_score(int mg, int eg) { return Score((mg << 16) + eg); }