mirror of
https://github.com/opelly27/Stockfish.git
synced 2026-05-20 13:17:44 +00:00
Compare commits
441 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 369eff437c | |||
| 344616e917 | |||
| 40b1b27178 | |||
| bf51b4796a | |||
| e18e557e77 | |||
| 818b4a126d | |||
| e77f38c431 | |||
| e18321f55a | |||
| ca67752645 | |||
| 3686e719a1 | |||
| 9893e7fd53 | |||
| 99f3ad6858 | |||
| e27d3bb884 | |||
| 16e1881126 | |||
| e1f600f186 | |||
| a3fe80c36a | |||
| fdf3a51c68 | |||
| e61f7b1e6d | |||
| f799610d4b | |||
| 073eed590e | |||
| 1e586288ca | |||
| 0162fb83c2 | |||
| ab26c61971 | |||
| eccccba0ce | |||
| b77bae0529 | |||
| 7ae3c05795 | |||
| 351844061e | |||
| 8662bdfa12 | |||
| 28240d375c | |||
| 943ae89be1 | |||
| 4b0043ae7c | |||
| 92f01aa2bd | |||
| ea41f18e6e | |||
| 057d710fc2 | |||
| 01f2466f6e | |||
| 5c58d1f5cb | |||
| b96dd754ed | |||
| 01ee509a5c | |||
| 95ad2b51b7 | |||
| 438805aee8 | |||
| ace8e951d7 | |||
| 90ce24b11e | |||
| 4c95edddbf | |||
| 602d7fbb07 | |||
| d909d10f33 | |||
| 38428ada54 | |||
| e340ce221c | |||
| ca6c9f85a5 | |||
| c5828c4eba | |||
| d37dfe9ae4 | |||
| 13b4444d9e | |||
| 7f2eb10e93 | |||
| 5cffc032da | |||
| 2731bbaf6b | |||
| 6aa9308f08 | |||
| b4f6728e61 | |||
| 2b57b61cb1 | |||
| 1ee2838214 | |||
| 0b944c7186 | |||
| 805afcbf3d | |||
| 4c5cbb1b14 | |||
| 133808851d | |||
| 9bd856e28e | |||
| 3e739f883f | |||
| 0b4f6e562b | |||
| 5596492f6e | |||
| 8493c8c6b8 | |||
| e3af492142 | |||
| 9585f8ef58 | |||
| 7396c08b79 | |||
| 3d10cfcdd2 | |||
| 8abb98455f | |||
| b3525fa9ea | |||
| 85924db496 | |||
| f2f3a06a1a | |||
| 714329dbdc | |||
| 76971d8acb | |||
| f619f1d38c | |||
| 82d02a3133 | |||
| 1d09ee70f7 | |||
| eb20a87c67 | |||
| ade3bb9a4e | |||
| 716a145a6c | |||
| 190d2ea4bc | |||
| c2c0e6b07d | |||
| c94145b65c | |||
| 09efbf915e | |||
| 6d58bf777c | |||
| 1c0c4db677 | |||
| 8e45e70e55 | |||
| 126036abb0 | |||
| ca14345ba2 | |||
| 7d2a79f037 | |||
| 7c5d724724 | |||
| 6fed8ff22a | |||
| 0c076f1136 | |||
| e48c7547c5 | |||
| 6e2ca97d93 | |||
| 5f096e9bef | |||
| 20023ac9b8 | |||
| 3549d98d07 | |||
| 07b247f943 | |||
| abac509ccb | |||
| ab0f4c0353 | |||
| 71bfbb22fc | |||
| 7cb8cbb403 | |||
| 0784bd542b | |||
| 16c603ce9b | |||
| 969982406c | |||
| 4b9ed6566a | |||
| 5e4cd3fc0d | |||
| 5486911e01 | |||
| 3487eb9f9e | |||
| dc0030de4f | |||
| 2dd24dc4e6 | |||
| 8f934dff9a | |||
| 2694ef23c3 | |||
| e082112cfe | |||
| 4048bae47b | |||
| c737062436 | |||
| 94e41274bb | |||
| ec6aab0136 | |||
| 7eaea3848c | |||
| ee7a68ea5f | |||
| d30994ecd5 | |||
| bd04f9a0f1 | |||
| 1cbba8d6fa | |||
| e9e5f72c74 | |||
| 29b5842da8 | |||
| 8fb45caade | |||
| 900279a06f | |||
| d5b24ad77b | |||
| f256388e08 | |||
| db4b0d8b7d | |||
| 24dac5ccd3 | |||
| 8788612828 | |||
| 5d1644ba69 | |||
| 60590577f2 | |||
| 04be84e0e2 | |||
| 647402ff79 | |||
| a273b6ef8c | |||
| e1a7d135b2 | |||
| c1be0c68c7 | |||
| c13052f344 | |||
| 8de29390f2 | |||
| 45a309d92e | |||
| d5ba8e827d | |||
| 77fa960f89 | |||
| bfe9044ad9 | |||
| 744ed85a4d | |||
| 56dd58e6f9 | |||
| 4f6aa15228 | |||
| aedebe35cf | |||
| 9a10313a9d | |||
| 8c3a5bbc52 | |||
| 28933a580e | |||
| 12eb345ebd | |||
| ebec2fa48e | |||
| 552b3ccb66 | |||
| 356147d99a | |||
| 89723339d9 | |||
| 74e2fa97b7 | |||
| dcd8ce7094 | |||
| 4d1220d672 | |||
| aa31f7f096 | |||
| 1de97337c2 | |||
| 9eceb894ac | |||
| 5972c4a678 | |||
| dd9cf30581 | |||
| d4af15f682 | |||
| 9742fb10fd | |||
| 7cafbab529 | |||
| 6a79d5d10e | |||
| 3e4fed3a91 | |||
| a5c76d69c3 | |||
| 1b5b900a29 | |||
| 90f5937373 | |||
| 1e8836d921 | |||
| e3c85c314d | |||
| da34023cfc | |||
| ed72a1e9ba | |||
| 5bbd944099 | |||
| 38adb487ca | |||
| 2c1797ab81 | |||
| 9fac5774f4 | |||
| 69240a982d | |||
| 7904a7d930 | |||
| 8315620522 | |||
| 52eac1e535 | |||
| 5d077bb482 | |||
| 5a42427cb8 | |||
| 5339ab57d8 | |||
| 388630ae28 | |||
| 79f393084a | |||
| 328098d027 | |||
| 93195555ed | |||
| 07e0741dfb | |||
| 27ca89d479 | |||
| cccf3c815c | |||
| 76ed0ab501 | |||
| ce84ab6e9d | |||
| fca8dbc029 | |||
| e6eeb17aa6 | |||
| 9c9205860c | |||
| 27c5cb5912 | |||
| 86f04dbcc0 | |||
| aa242d2f84 | |||
| 8d858783e1 | |||
| 80d7556af7 | |||
| 00d9e9fd28 | |||
| 3428a28751 | |||
| 307a5a4f63 | |||
| 55758344d3 | |||
| 4eca981e55 | |||
| 5066e17eba | |||
| 328d314f2f | |||
| ecc5ff6693 | |||
| 7ea5659c5f | |||
| 8fd34d7763 | |||
| 55b46ffa90 | |||
| 08d6465d90 | |||
| 5f4d9309c8 | |||
| 436c303731 | |||
| 540b49a152 | |||
| 2e45447957 | |||
| dc3508d157 | |||
| ca38358574 | |||
| 83e19fbed5 | |||
| 9f5b31c21d | |||
| 3c0fe1d9b2 | |||
| 77b4f4c2e7 | |||
| 68fbb1e052 | |||
| 01fab4d432 | |||
| 660c38f781 | |||
| 613dc66c12 | |||
| 3e2591d83c | |||
| 46b5a5f0db | |||
| 84a641b8bb | |||
| 7f300a7698 | |||
| 087b638f6c | |||
| 7ad85fca6d | |||
| bf6bc1b37b | |||
| c052e03426 | |||
| 69a1a808c8 | |||
| 600234f2e2 | |||
| 9dbb3ae8b2 | |||
| f4ace94f91 | |||
| 1aae35b8b7 | |||
| e6310b3469 | |||
| 68d61b80c6 | |||
| a2410227cc | |||
| 4a6d59c6c7 | |||
| 51330414c4 | |||
| 42b77ea7ee | |||
| 4095ff0ee5 | |||
| 1d977aa79e | |||
| d8aeaab79c | |||
| 3054db989d | |||
| b2edac7075 | |||
| aa0dc16b75 | |||
| 112607bf49 | |||
| 7e9f776fca | |||
| 3f1bc9e013 | |||
| e8cc5c9968 | |||
| 00563be5cc | |||
| ad87d707ff | |||
| 7b8ffe0f5d | |||
| c1d3bd2dba | |||
| 5ebdf2f8c8 | |||
| 4502a1934f | |||
| 2795aedbc3 | |||
| 8e95c39bfa | |||
| 80a759d544 | |||
| 2e0ec4ad6f | |||
| e14046517e | |||
| 411e704fdf | |||
| ee0371f86e | |||
| eaeb63f1d0 | |||
| 92dbee7875 | |||
| 2e86d1febc | |||
| 946fa47625 | |||
| 7231b18af1 | |||
| 578b21bbee | |||
| 59f64fda4f | |||
| cc54a91ca5 | |||
| b7063ef65b | |||
| 078625e333 | |||
| 6c040c821a | |||
| 20e92895af | |||
| fb03188fc7 | |||
| a66c73deef | |||
| 27efc5ac99 | |||
| 36f2133df3 | |||
| ef4d89c9bd | |||
| aaf17326e2 | |||
| 2ca142a5b4 | |||
| ffbaa1c5a8 | |||
| 57dfe41ddb | |||
| 926f215061 | |||
| df722521ba | |||
| 5d1b92e8f9 | |||
| 6661a31541 | |||
| 6c42575208 | |||
| 61a6e46664 | |||
| 60beb18efc | |||
| 8463fa479e | |||
| 63500274db | |||
| 1d5eaba573 | |||
| ac8e6ff000 | |||
| 3a6753328c | |||
| 50182f1100 | |||
| e51965aa57 | |||
| a7381d5e81 | |||
| dc3a5f791e | |||
| 35a082064f | |||
| be77406a55 | |||
| 26dabb1e6b | |||
| 35b6079852 | |||
| ebf3735754 | |||
| 966bc477af | |||
| c6f987d1ad | |||
| d477a0d611 | |||
| 54889618c2 | |||
| 9a6cfee73b | |||
| 2e8552db76 | |||
| a4b2eeea75 | |||
| 13d4df95cd | |||
| bae4679de2 | |||
| a3943b2aa7 | |||
| f04f50b368 | |||
| a4b98a052e | |||
| e5da0e4b79 | |||
| d71f707040 | |||
| 558b0c848c | |||
| 062ca91db5 | |||
| 13c11f4048 | |||
| 81c7975dcd | |||
| 4b59347194 | |||
| 6027652773 | |||
| 04372316b3 | |||
| 8725494966 | |||
| be50952533 | |||
| e53774bc49 | |||
| 3017e8c604 | |||
| 8fcaa78a04 | |||
| a590d1d52d | |||
| 856a5f3aaa | |||
| 6fa6da3ee1 | |||
| cb2111f0b6 | |||
| 6645115377 | |||
| 63a5fc2366 | |||
| 0da7295795 | |||
| 1e6d21dbb6 | |||
| 9369f4963d | |||
| a459709fcc | |||
| 2dbb1adf2a | |||
| 8a2c4134a6 | |||
| fce799294c | |||
| 0b36ba74fc | |||
| 153fb216a1 | |||
| d3d26a94b3 | |||
| 38112060dc | |||
| 775f8239d3 | |||
| 098f645d26 | |||
| 29ff925fd8 | |||
| 8d16111ffd | |||
| e2226cbb20 | |||
| 5fd5453e59 | |||
| e74c2df907 | |||
| 41ccc885ec | |||
| 2f46592736 | |||
| 7ff965eebf | |||
| a6f873cd8d | |||
| 40548c9153 | |||
| 667f350737 | |||
| 950c8436ed | |||
| 8d47caa16e | |||
| b9d4e6f7fd | |||
| 193a7ae35b | |||
| 4f906a2589 | |||
| dccaa145d2 | |||
| 6656ed8904 | |||
| d65f75c153 | |||
| f8f5dcbb68 | |||
| 686b45e121 | |||
| dc13004283 | |||
| 901bfb1f55 | |||
| 20a5c07472 | |||
| e38eb2302d | |||
| 0af24a1445 | |||
| a8f9c7a790 | |||
| c0a80afe89 | |||
| 44a571c1c7 | |||
| ce8ac7997c | |||
| e118570038 | |||
| 8f10f6c9cd | |||
| 3184852bdc | |||
| 99c9cae586 | |||
| 152a4dc5cd | |||
| 47a0768102 | |||
| 170bdf40cd | |||
| 8b0fee9998 | |||
| 1277a42823 | |||
| 35aa21c1fe | |||
| 18b0809639 | |||
| f4136c5434 | |||
| ddccb5355c | |||
| 1c7a727795 | |||
| e56e5045dd | |||
| 20d6a8e57f | |||
| 0dc6f16992 | |||
| 21120288a3 | |||
| 519b2fe849 | |||
| f3189bdc9a | |||
| 65f46794af | |||
| 81d6c4a0d6 | |||
| 60c121f3b1 | |||
| 45eac9507c | |||
| bfd0f95f06 | |||
| 1b947aafbf | |||
| a7592e69d7 | |||
| a3b4e9e23c | |||
| f6f1d24223 | |||
| ce0a95c2c0 | |||
| 8aa8608c2a | |||
| 7837fb2aca | |||
| 9f0d5241bf | |||
| 14f7d9a629 | |||
| 69407ae9b8 | |||
| 18375e3bfb | |||
| 6390a3da94 | |||
| 36f8814aa6 | |||
| 96e36a7897 | |||
| 2ca2c3f35b | |||
| f54c44e6be | |||
| ca3622f8e8 | |||
| 712bbb052e | |||
| fe4fda474f | |||
| f7d8ea3866 | |||
| f53aea45e3 | |||
| 3c07603dac |
+55
@@ -0,0 +1,55 @@
|
||||
language: cpp
|
||||
sudo: required
|
||||
dist: trusty
|
||||
|
||||
matrix:
|
||||
include:
|
||||
- os: linux
|
||||
compiler: gcc
|
||||
addons:
|
||||
apt:
|
||||
sources: ['ubuntu-toolchain-r-test']
|
||||
packages: ['g++-6', 'g++-6-multilib', 'g++-multilib', 'valgrind']
|
||||
env:
|
||||
- COMPILER=g++-6
|
||||
- COMP=gcc
|
||||
|
||||
- os: linux
|
||||
compiler: clang
|
||||
addons:
|
||||
apt:
|
||||
sources: ['ubuntu-toolchain-r-test']
|
||||
packages: ['clang', 'g++-multilib', 'valgrind']
|
||||
env:
|
||||
- COMPILER=clang++
|
||||
- COMP=clang
|
||||
|
||||
- os: osx
|
||||
compiler: gcc
|
||||
env:
|
||||
- COMPILER=g++
|
||||
- COMP=gcc
|
||||
|
||||
- os: osx
|
||||
compiler: clang
|
||||
env:
|
||||
- COMPILER=clang++ V='Apple LLVM 6.0' # Apple LLVM version 6.0 (clang-600.0.54) (based on LLVM 3.5svn)
|
||||
- COMP=clang
|
||||
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
|
||||
before_script:
|
||||
- cd src
|
||||
|
||||
script:
|
||||
- make clean && make build ARCH=x86-64 && ./stockfish bench 2>&1 >/dev/null | grep 'Nodes searched' | tee bench1
|
||||
- make clean && make build ARCH=x86-32 && ./stockfish bench 2>&1 >/dev/null | grep 'Nodes searched' | tee bench2
|
||||
- echo "Checking for same bench numbers..."
|
||||
- diff bench1 bench2 > result
|
||||
- test ! -s result
|
||||
# if valgrind is available check the build is without error, reduce depth to speedup testing, but not too shallow to catch more cases.
|
||||
- if [ -x "$(command -v valgrind )" ] ; then make clean && make ARCH=x86-64 debug=yes build && valgrind --error-exitcode=42 ./stockfish bench 128 1 10 default depth 1>/dev/null ; fi
|
||||
# use g++-6 as a proxy for having sanitizers ... might need revision as they become available for more recent versions of clang/gcc than trusty provides
|
||||
- if [[ "$COMPILER" == "g++-6" ]]; then make clean && make ARCH=x86-64 sanitize=yes build && ! ./stockfish bench 2>&1 | grep "runtime error:" ; fi
|
||||
@@ -1,64 +1,98 @@
|
||||
# Generated with git shortlog -sn | cut -c8-', which sorts by commits (manually moved Tord to top)
|
||||
# Generated with git shortlog -sn | cut -c8-', which sorts by commits (manually ordered the first four authors)
|
||||
|
||||
Tord Romstad
|
||||
Marco Costalba
|
||||
Joona Kiiski
|
||||
Gary Linscott
|
||||
lucasart
|
||||
mstembera
|
||||
Lucas Braesch
|
||||
Stefan Geschwentner
|
||||
Reuven Peleg
|
||||
Chris Caino
|
||||
homoSapiensSapiens
|
||||
joergoster
|
||||
VoyagerOne
|
||||
Jean-Francois Romang
|
||||
jundery
|
||||
homoSapiensSapiens
|
||||
Alain SAVARD
|
||||
Arjun Temurnikar
|
||||
Stéphane Nicolet
|
||||
Uri Blass
|
||||
jundery
|
||||
Ralph Stößer
|
||||
Stefan Geschwentner
|
||||
Ajith
|
||||
Leonid Pechenik
|
||||
Stefano80
|
||||
Tom Vijlbrief
|
||||
hxim
|
||||
snicolet
|
||||
Daylen Yang
|
||||
Henri Wiechers
|
||||
Leonid Pechenik
|
||||
mstembera
|
||||
Jonathan Calovski
|
||||
mbootsector
|
||||
David Zar
|
||||
Eelco de Groot
|
||||
Jerry Donald
|
||||
Joerg Oster
|
||||
Jörg Oster
|
||||
Ryan Schmitt
|
||||
mcostalba
|
||||
Alexander Kure
|
||||
Dan Schmidt
|
||||
H. Felix Wittmann
|
||||
Joseph R. Prostko
|
||||
Justin Blanchard
|
||||
Linus Arver
|
||||
NicklasPersson
|
||||
Rodrigo Exterckötter Tjäder
|
||||
Ron Britvich
|
||||
Ronald de Man
|
||||
RyanTaker
|
||||
Vince Negri
|
||||
ceebo
|
||||
Joseph H Ellis
|
||||
Stephane Nicolet
|
||||
Ajith
|
||||
jhellis3
|
||||
ppigazzini
|
||||
shane31
|
||||
Andy Duplain
|
||||
Auguste Pop
|
||||
Balint Pfliegel
|
||||
Chris Cain
|
||||
DU-jdto
|
||||
Dariusz Orzechowski
|
||||
DiscanX
|
||||
Ernesto Gatti
|
||||
Gregor Cramer
|
||||
Guenther Demetz
|
||||
Hiraoka Takuya
|
||||
Hongzhi Cheng
|
||||
Jonathan Calovski
|
||||
Joseph R. Prostko
|
||||
Joseph Hellis
|
||||
Kelly Wilson
|
||||
Ken T Takusagawa
|
||||
Kojirion
|
||||
Luca Brivio
|
||||
Matt Sullivan
|
||||
Matthew Lai
|
||||
Matthew Sullivan
|
||||
Michel Van den Bergh
|
||||
Mysseno
|
||||
Oskar Werkelin Ahlin
|
||||
Pablo Vazquez
|
||||
Pascal Romaret
|
||||
Ralph Stoesser
|
||||
Ralph Stößer
|
||||
Raminder Singh
|
||||
Richard Lloyd
|
||||
Ron Britvich
|
||||
Ronald de Man
|
||||
Ryan Takker
|
||||
Stephane Nicolet
|
||||
Thanar2
|
||||
absimaldata
|
||||
braich
|
||||
gguliash
|
||||
kinderchocolate
|
||||
loco-loco
|
||||
pellanda
|
||||
renouve
|
||||
shane31
|
||||
sf-x
|
||||
thaspel
|
||||
unknown
|
||||
uriblass
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
### Overview
|
||||
|
||||
[](https://travis-ci.org/official-stockfish/Stockfish)
|
||||
[](https://ci.appveyor.com/project/mcostalba/stockfish)
|
||||
|
||||
Stockfish is a free UCI chess engine derived from Glaurung 2.1. It is
|
||||
not a complete chess program and requires some UCI-compatible GUI
|
||||
(e.g. XBoard with PolyGlot, eboard, Arena, Sigma Chess, Shredder, Chess
|
||||
@@ -54,7 +57,7 @@ for correspondence games (because of tablebase adjudication).
|
||||
|
||||
The "SyzygyProbeLimit" option should normally be left at its default value.
|
||||
|
||||
**What to expect**
|
||||
**What to expect**
|
||||
If the engine is searching a position that is not in the tablebases (e.g.
|
||||
a position with 7 pieces), it will access the tablebases during the search.
|
||||
If the engine reports a very large score (typically 123.xx), this means
|
||||
@@ -109,4 +112,4 @@ to where the source code can be found. If you make any changes to the
|
||||
source code, these changes must also be made available under the GPL.
|
||||
|
||||
For full details, read the copy of the GPL found in the file named
|
||||
*Copying.txt*
|
||||
*Copying.txt*.
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
version: 1.0.{build}
|
||||
clone_depth: 5
|
||||
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
- appveyor
|
||||
|
||||
# Operating system (build VM template)
|
||||
os: Visual Studio 2015
|
||||
|
||||
# Build platform, i.e. x86, x64, AnyCPU. This setting is optional.
|
||||
platform:
|
||||
- x86
|
||||
- x64
|
||||
- Any CPU
|
||||
|
||||
# build Configuration, i.e. Debug, Release, etc.
|
||||
configuration: Debug
|
||||
|
||||
matrix:
|
||||
# The build fail immediately once one of the job fails
|
||||
fast_finish: true
|
||||
|
||||
# Scripts that are called at very beginning, before repo cloning
|
||||
init:
|
||||
- cmake --version
|
||||
- msbuild /version
|
||||
|
||||
before_build:
|
||||
- cd src
|
||||
- echo project (Stockfish) >> CMakeLists.txt
|
||||
- echo add_executable(stockfish benchmark.cpp bitbase.cpp bitboard.cpp endgame.cpp evaluate.cpp >> CMakeLists.txt
|
||||
- echo main.cpp material.cpp misc.cpp movegen.cpp movepick.cpp pawns.cpp position.cpp psqt.cpp >> CMakeLists.txt
|
||||
- echo search.cpp thread.cpp timeman.cpp tt.cpp uci.cpp ucioption.cpp syzygy/tbprobe.cpp) >> CMakeLists.txt
|
||||
- echo set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/src) >> CMakeLists.txt
|
||||
# - echo target_compile_options(stockfish PUBLIC "/Ox") >> CMakeLists.txt
|
||||
|
||||
build_script:
|
||||
- cmake -G "Visual Studio 14 2015 Win64" .
|
||||
- cmake --build .
|
||||
|
||||
before_test:
|
||||
- cd Debug
|
||||
- stockfish.exe bench > null
|
||||
+126
-68
@@ -1,6 +1,7 @@
|
||||
# Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
# Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
# Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
# Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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
|
||||
@@ -21,7 +22,10 @@
|
||||
### ==========================================================================
|
||||
|
||||
### Establish the operating system name
|
||||
UNAME = $(shell uname)
|
||||
KERNEL = $(shell uname -s)
|
||||
ifeq ($(KERNEL),Linux)
|
||||
OS = $(shell uname -o)
|
||||
endif
|
||||
|
||||
### Executable name
|
||||
EXE = stockfish
|
||||
@@ -31,11 +35,11 @@ PREFIX = /usr/local
|
||||
BINDIR = $(PREFIX)/bin
|
||||
|
||||
### Built-in benchmark for pgo-builds
|
||||
PGOBENCH = ./$(EXE) bench 16 1 1000 default time
|
||||
PGOBENCH = ./$(EXE) bench
|
||||
|
||||
### Object files
|
||||
OBJS = benchmark.o bitbase.o bitboard.o endgame.o evaluate.o main.o \
|
||||
material.o misc.o movegen.o movepick.o pawns.o position.o \
|
||||
material.o misc.o movegen.o movepick.o pawns.o position.o psqt.o \
|
||||
search.o thread.o timeman.o tt.o uci.o ucioption.o syzygy/tbprobe.o
|
||||
|
||||
### ==========================================================================
|
||||
@@ -46,13 +50,12 @@ OBJS = benchmark.o bitbase.o bitboard.o endgame.o evaluate.o main.o \
|
||||
# ----------------------------------------------------------------------------
|
||||
#
|
||||
# debug = yes/no --- -DNDEBUG --- Enable/Disable debug mode
|
||||
# sanitize = yes/no --- (-fsanitize ) --- enable undefined behavior checks
|
||||
# optimize = yes/no --- (-O3/-fast etc.) --- Enable/Disable optimizations
|
||||
# arch = (name) --- (-arch) --- Target architecture
|
||||
# bits = 64/32 --- -DIS_64BIT --- 64-/32-bit operating system
|
||||
# prefetch = yes/no --- -DUSE_PREFETCH --- Use prefetch x86 asm-instruction
|
||||
# bsfq = yes/no --- -DUSE_BSFQ --- Use bsfq x86_64 asm-instruction (only
|
||||
# with GCC and ICC 64-bit)
|
||||
# popcnt = yes/no --- -DUSE_POPCNT --- Use popcnt x86_64 asm-instruction
|
||||
# prefetch = yes/no --- -DUSE_PREFETCH --- Use prefetch asm-instruction
|
||||
# popcnt = yes/no --- -DUSE_POPCNT --- Use popcnt asm-instruction
|
||||
# sse = yes/no --- -msse --- Use Intel Streaming SIMD Extensions
|
||||
# pext = yes/no --- -DUSE_PEXT --- Use pext x86_64 asm-instruction
|
||||
#
|
||||
@@ -63,9 +66,9 @@ OBJS = benchmark.o bitbase.o bitboard.o endgame.o evaluate.o main.o \
|
||||
### 2.1. General and architecture defaults
|
||||
optimize = yes
|
||||
debug = no
|
||||
sanitize = no
|
||||
bits = 32
|
||||
prefetch = no
|
||||
bsfq = no
|
||||
popcnt = no
|
||||
sse = no
|
||||
pext = no
|
||||
@@ -95,7 +98,6 @@ ifeq ($(ARCH),x86-64)
|
||||
arch = x86_64
|
||||
bits = 64
|
||||
prefetch = yes
|
||||
bsfq = yes
|
||||
sse = yes
|
||||
endif
|
||||
|
||||
@@ -103,7 +105,6 @@ ifeq ($(ARCH),x86-64-modern)
|
||||
arch = x86_64
|
||||
bits = 64
|
||||
prefetch = yes
|
||||
bsfq = yes
|
||||
popcnt = yes
|
||||
sse = yes
|
||||
endif
|
||||
@@ -112,7 +113,6 @@ ifeq ($(ARCH),x86-64-bmi2)
|
||||
arch = x86_64
|
||||
bits = 64
|
||||
prefetch = yes
|
||||
bsfq = yes
|
||||
popcnt = yes
|
||||
sse = yes
|
||||
pext = yes
|
||||
@@ -121,7 +121,6 @@ endif
|
||||
ifeq ($(ARCH),armv7)
|
||||
arch = armv7
|
||||
prefetch = yes
|
||||
bsfq = yes
|
||||
endif
|
||||
|
||||
ifeq ($(ARCH),ppc-32)
|
||||
@@ -140,7 +139,8 @@ endif
|
||||
|
||||
### 3.1 Selecting compiler (default = gcc)
|
||||
|
||||
CXXFLAGS += -Wall -Wcast-qual -fno-exceptions -fno-rtti $(EXTRACXXFLAGS)
|
||||
CXXFLAGS += -Wall -Wcast-qual -fno-exceptions -fno-rtti -std=c++11 $(EXTRACXXFLAGS)
|
||||
DEPENDFLAGS += -std=c++11
|
||||
LDFLAGS += $(EXTRALDFLAGS)
|
||||
|
||||
ifeq ($(COMP),)
|
||||
@@ -150,14 +150,44 @@ endif
|
||||
ifeq ($(COMP),gcc)
|
||||
comp=gcc
|
||||
CXX=g++
|
||||
CXXFLAGS += -ansi -pedantic -Wno-long-long -Wextra -Wshadow
|
||||
CXXFLAGS += -pedantic -Wextra -Wshadow
|
||||
|
||||
ifeq ($(ARCH),armv7)
|
||||
ifeq ($(OS),Android)
|
||||
CXXFLAGS += -m$(bits)
|
||||
endif
|
||||
else
|
||||
CXXFLAGS += -m$(bits)
|
||||
endif
|
||||
|
||||
ifneq ($(KERNEL),Darwin)
|
||||
LDFLAGS += -Wl,--no-as-needed
|
||||
endif
|
||||
endif
|
||||
|
||||
ifeq ($(COMP),mingw)
|
||||
comp=mingw
|
||||
CXX=g++
|
||||
|
||||
ifeq ($(KERNEL),Linux)
|
||||
ifeq ($(bits),64)
|
||||
ifeq ($(shell which x86_64-w64-mingw32-c++-posix),)
|
||||
CXX=x86_64-w64-mingw32-c++
|
||||
else
|
||||
CXX=x86_64-w64-mingw32-c++-posix
|
||||
endif
|
||||
else
|
||||
ifeq ($(shell which i686-w64-mingw32-c++-posix),)
|
||||
CXX=i686-w64-mingw32-c++
|
||||
else
|
||||
CXX=i686-w64-mingw32-c++-posix
|
||||
endif
|
||||
endif
|
||||
else
|
||||
CXX=g++
|
||||
endif
|
||||
|
||||
CXXFLAGS += -Wextra -Wshadow
|
||||
LDFLAGS += -static-libstdc++ -static-libgcc
|
||||
LDFLAGS += -static
|
||||
endif
|
||||
|
||||
ifeq ($(COMP),icc)
|
||||
@@ -169,7 +199,22 @@ endif
|
||||
ifeq ($(COMP),clang)
|
||||
comp=clang
|
||||
CXX=clang++
|
||||
CXXFLAGS += -pedantic -Wno-long-long -Wextra -Wshadow
|
||||
CXXFLAGS += -pedantic -Wextra -Wshadow
|
||||
|
||||
ifeq ($(ARCH),armv7)
|
||||
ifeq ($(OS),Android)
|
||||
CXXFLAGS += -m$(bits)
|
||||
LDFLAGS += -m$(bits)
|
||||
endif
|
||||
else
|
||||
CXXFLAGS += -m$(bits)
|
||||
LDFLAGS += -m$(bits)
|
||||
endif
|
||||
|
||||
ifeq ($(KERNEL),Darwin)
|
||||
CXXFLAGS += -stdlib=libc++
|
||||
DEPENDFLAGS += -stdlib=libc++
|
||||
endif
|
||||
endif
|
||||
|
||||
ifeq ($(comp),icc)
|
||||
@@ -184,36 +229,52 @@ else
|
||||
profile_clean = gcc-profile-clean
|
||||
endif
|
||||
|
||||
ifeq ($(UNAME),Darwin)
|
||||
CXXFLAGS += -arch $(arch) -mmacosx-version-min=10.6
|
||||
LDFLAGS += -arch $(arch) -mmacosx-version-min=10.6
|
||||
ifeq ($(KERNEL),Darwin)
|
||||
CXXFLAGS += -arch $(arch) -mmacosx-version-min=10.9
|
||||
LDFLAGS += -arch $(arch) -mmacosx-version-min=10.9
|
||||
endif
|
||||
|
||||
### Travis CI script uses COMPILER to overwrite CXX
|
||||
ifdef COMPILER
|
||||
COMPCXX=$(COMPILER)
|
||||
endif
|
||||
|
||||
### Allow overwriting CXX from command line
|
||||
ifdef COMPCXX
|
||||
CXX=$(COMPCXX)
|
||||
endif
|
||||
|
||||
### On mingw use Windows threads, otherwise POSIX
|
||||
ifneq ($(comp),mingw)
|
||||
# On Android Bionic's C library comes with its own pthread implementation bundled in
|
||||
ifneq ($(arch),armv7)
|
||||
ifneq ($(OS),Android)
|
||||
# Haiku has pthreads in its libroot, so only link it in on other platforms
|
||||
ifneq ($(UNAME),Haiku)
|
||||
ifneq ($(KERNEL),Haiku)
|
||||
LDFLAGS += -lpthread
|
||||
endif
|
||||
endif
|
||||
endif
|
||||
|
||||
### 3.4 Debugging
|
||||
### 3.2.1 Debugging
|
||||
ifeq ($(debug),no)
|
||||
CXXFLAGS += -DNDEBUG
|
||||
else
|
||||
CXXFLAGS += -g
|
||||
endif
|
||||
|
||||
### 3.5 Optimization
|
||||
### 3.2.2 Debugging with undefined behavior sanitizers
|
||||
ifeq ($(sanitize),yes)
|
||||
CXXFLAGS += -g3 -fsanitize=undefined
|
||||
endif
|
||||
|
||||
### 3.3 Optimization
|
||||
ifeq ($(optimize),yes)
|
||||
|
||||
ifeq ($(comp),gcc)
|
||||
CXXFLAGS += -O3
|
||||
CXXFLAGS += -O3
|
||||
|
||||
ifeq ($(UNAME),Darwin)
|
||||
ifeq ($(comp),gcc)
|
||||
|
||||
ifeq ($(KERNEL),Darwin)
|
||||
ifeq ($(arch),i386)
|
||||
CXXFLAGS += -mdynamic-no-pic
|
||||
endif
|
||||
@@ -222,27 +283,19 @@ ifeq ($(optimize),yes)
|
||||
endif
|
||||
endif
|
||||
|
||||
ifeq ($(arch),armv7)
|
||||
ifeq ($(OS), Android)
|
||||
CXXFLAGS += -fno-gcse -mthumb -march=armv7-a -mfloat-abi=softfp
|
||||
endif
|
||||
endif
|
||||
|
||||
ifeq ($(comp),mingw)
|
||||
CXXFLAGS += -O3
|
||||
endif
|
||||
|
||||
ifeq ($(comp),icc)
|
||||
ifeq ($(UNAME),Darwin)
|
||||
CXXFLAGS += -fast -mdynamic-no-pic
|
||||
else
|
||||
CXXFLAGS += -fast
|
||||
ifeq ($(KERNEL),Darwin)
|
||||
CXXFLAGS += -mdynamic-no-pic
|
||||
endif
|
||||
endif
|
||||
|
||||
ifeq ($(comp),clang)
|
||||
CXXFLAGS += -O3
|
||||
|
||||
ifeq ($(UNAME),Darwin)
|
||||
ifeq ($(KERNEL),Darwin)
|
||||
ifeq ($(pext),no)
|
||||
CXXFLAGS += -flto
|
||||
LDFLAGS += $(CXXFLAGS)
|
||||
@@ -257,12 +310,12 @@ ifeq ($(optimize),yes)
|
||||
endif
|
||||
endif
|
||||
|
||||
### 3.6. Bits
|
||||
### 3.4 Bits
|
||||
ifeq ($(bits),64)
|
||||
CXXFLAGS += -DIS_64BIT
|
||||
endif
|
||||
|
||||
### 3.7 prefetch
|
||||
### 3.5 prefetch
|
||||
ifeq ($(prefetch),yes)
|
||||
ifeq ($(sse),yes)
|
||||
CXXFLAGS += -msse
|
||||
@@ -272,12 +325,7 @@ else
|
||||
CXXFLAGS += -DNO_PREFETCH
|
||||
endif
|
||||
|
||||
### 3.8 bsfq
|
||||
ifeq ($(bsfq),yes)
|
||||
CXXFLAGS += -DUSE_BSFQ
|
||||
endif
|
||||
|
||||
### 3.9 popcnt
|
||||
### 3.6 popcnt
|
||||
ifeq ($(popcnt),yes)
|
||||
ifeq ($(comp),icc)
|
||||
CXXFLAGS += -msse3 -DUSE_POPCNT
|
||||
@@ -286,33 +334,40 @@ ifeq ($(popcnt),yes)
|
||||
endif
|
||||
endif
|
||||
|
||||
### 3.10 pext
|
||||
### 3.7 pext
|
||||
ifeq ($(pext),yes)
|
||||
CXXFLAGS += -DUSE_PEXT
|
||||
ifeq ($(comp),$(filter $(comp),gcc clang mingw))
|
||||
CXXFLAGS += -mbmi -mbmi2
|
||||
CXXFLAGS += -mbmi2
|
||||
endif
|
||||
endif
|
||||
|
||||
### 3.11 Link Time Optimization, it works since gcc 4.5 but not on mingw.
|
||||
### 3.8 Link Time Optimization, it works since gcc 4.5 but not on mingw under Windows.
|
||||
### This is a mix of compile and link time options because the lto link phase
|
||||
### needs access to the optimization flags.
|
||||
ifeq ($(comp),gcc)
|
||||
ifeq ($(optimize),yes)
|
||||
ifeq ($(debug),no)
|
||||
GCC_MAJOR := `$(CXX) -dumpversion | cut -f1 -d.`
|
||||
GCC_MINOR := `$(CXX) -dumpversion | cut -f2 -d.`
|
||||
ifeq (1,$(shell expr \( $(GCC_MAJOR) \> 4 \) \| \( $(GCC_MAJOR) \= 4 \& $(GCC_MINOR) \>= 5 \)))
|
||||
CXXFLAGS += -flto
|
||||
LDFLAGS += $(CXXFLAGS)
|
||||
endif
|
||||
CXXFLAGS += -flto
|
||||
LDFLAGS += $(CXXFLAGS)
|
||||
endif
|
||||
endif
|
||||
endif
|
||||
|
||||
### 3.12 Android 5 can only run position independent executables. Note that this
|
||||
ifeq ($(comp),mingw)
|
||||
ifeq ($(KERNEL),Linux)
|
||||
ifeq ($(optimize),yes)
|
||||
ifeq ($(debug),no)
|
||||
CXXFLAGS += -flto
|
||||
LDFLAGS += $(CXXFLAGS)
|
||||
endif
|
||||
endif
|
||||
endif
|
||||
endif
|
||||
|
||||
### 3.9 Android 5 can only run position independent executables. Note that this
|
||||
### breaks Android 4.0 and earlier.
|
||||
ifeq ($(arch),armv7)
|
||||
ifeq ($(OS), Android)
|
||||
CXXFLAGS += -fPIE
|
||||
LDFLAGS += -fPIE -pie
|
||||
endif
|
||||
@@ -326,7 +381,7 @@ help:
|
||||
@echo ""
|
||||
@echo "To compile stockfish, type: "
|
||||
@echo ""
|
||||
@echo "make target ARCH=arch [COMP=comp]"
|
||||
@echo "make target ARCH=arch [COMP=compiler] [COMPCXX=cxx]"
|
||||
@echo ""
|
||||
@echo "Supported targets:"
|
||||
@echo ""
|
||||
@@ -356,11 +411,17 @@ help:
|
||||
@echo "clang > LLVM Clang compiler"
|
||||
@echo "icc > Intel compiler"
|
||||
@echo ""
|
||||
@echo "Examples. If you don't know what to do, you likely want to run: "
|
||||
@echo "Simple examples. If you don't know what to do, you likely want to run: "
|
||||
@echo ""
|
||||
@echo "make build ARCH=x86-64 (This is for 64-bit systems)"
|
||||
@echo "make build ARCH=x86-32 (This is for 32-bit systems)"
|
||||
@echo ""
|
||||
@echo "Advanced examples, for experienced users: "
|
||||
@echo ""
|
||||
@echo "make build ARCH=x86-64 COMP=clang"
|
||||
@echo "make profile-build ARCH=x86-64-modern COMP=gcc COMPCXX=g++-4.8"
|
||||
@echo ""
|
||||
|
||||
|
||||
.PHONY: build profile-build
|
||||
build:
|
||||
@@ -378,7 +439,7 @@ profile-build:
|
||||
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) $(profile_make)
|
||||
@echo ""
|
||||
@echo "Step 2/4. Running benchmark for pgo-build ..."
|
||||
@$(PGOBENCH) > /dev/null
|
||||
$(PGOBENCH) > /dev/null
|
||||
@echo ""
|
||||
@echo "Step 3/4. Building final executable ..."
|
||||
@touch *.cpp *.h syzygy/*.cpp syzygy/*.h
|
||||
@@ -414,8 +475,9 @@ config-sanity:
|
||||
@echo "optimize: '$(optimize)'"
|
||||
@echo "arch: '$(arch)'"
|
||||
@echo "bits: '$(bits)'"
|
||||
@echo "kernel: '$(KERNEL)'"
|
||||
@echo "os: '$(OS)'"
|
||||
@echo "prefetch: '$(prefetch)'"
|
||||
@echo "bsfq: '$(bsfq)'"
|
||||
@echo "popcnt: '$(popcnt)'"
|
||||
@echo "sse: '$(sse)'"
|
||||
@echo "pext: '$(pext)'"
|
||||
@@ -433,7 +495,6 @@ config-sanity:
|
||||
test "$(arch)" = "ppc64" || test "$(arch)" = "ppc" || test "$(arch)" = "armv7"
|
||||
@test "$(bits)" = "32" || test "$(bits)" = "64"
|
||||
@test "$(prefetch)" = "yes" || test "$(prefetch)" = "no"
|
||||
@test "$(bsfq)" = "yes" || test "$(bsfq)" = "no"
|
||||
@test "$(popcnt)" = "yes" || test "$(popcnt)" = "no"
|
||||
@test "$(sse)" = "yes" || test "$(sse)" = "no"
|
||||
@test "$(pext)" = "yes" || test "$(pext)" = "no"
|
||||
@@ -447,16 +508,13 @@ gcc-profile-prepare:
|
||||
|
||||
gcc-profile-make:
|
||||
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) \
|
||||
EXTRACXXFLAGS='-fprofile-arcs' \
|
||||
EXTRACXXFLAGS='-fprofile-generate' \
|
||||
EXTRALDFLAGS='-lgcov' \
|
||||
all
|
||||
|
||||
gcc-profile-use:
|
||||
# Deleting corrupt ucioption.gc* profile files is necessary to avoid an
|
||||
# "internal compiler error" for gcc versions 4.7.x
|
||||
@rm -f ucioption.gc*
|
||||
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) \
|
||||
EXTRACXXFLAGS='-fbranch-probabilities' \
|
||||
EXTRACXXFLAGS='-fprofile-use -fno-peel-loops -fno-tracer' \
|
||||
EXTRALDFLAGS='-lgcov' \
|
||||
all
|
||||
|
||||
|
||||
+28
-20
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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
|
||||
@@ -17,7 +18,6 @@
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include <algorithm>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <istream>
|
||||
@@ -27,14 +27,13 @@
|
||||
#include "position.h"
|
||||
#include "search.h"
|
||||
#include "thread.h"
|
||||
#include "tt.h"
|
||||
#include "uci.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
namespace {
|
||||
|
||||
const char* Defaults[] = {
|
||||
const vector<string> Defaults = {
|
||||
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
|
||||
"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 10",
|
||||
"8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 11",
|
||||
@@ -78,6 +77,13 @@ const char* Defaults[] = {
|
||||
|
||||
// 7-man positions
|
||||
"8/R7/2q5/8/6k1/8/1P5p/K6R w - - 0 124", // Draw
|
||||
|
||||
// Mate and stalemate positions
|
||||
"8/8/8/8/8/6k1/6p1/6K1 w - -",
|
||||
"5k2/5P2/5K2/8/8/8/8/8 b - -",
|
||||
"8/8/8/8/8/4k3/4p3/4K3 w - -",
|
||||
"8/8/8/8/8/5K2/8/3Q1k2 b - -",
|
||||
"7k/7P/6K1/8/3B4/8/8/8 b - -"
|
||||
};
|
||||
|
||||
} // namespace
|
||||
@@ -93,8 +99,8 @@ const char* Defaults[] = {
|
||||
void benchmark(const Position& current, istream& is) {
|
||||
|
||||
string token;
|
||||
Search::LimitsType limits;
|
||||
vector<string> fens;
|
||||
Search::LimitsType limits;
|
||||
|
||||
// Assign default values to missing arguments
|
||||
string ttSize = (is >> token) ? token : "16";
|
||||
@@ -105,22 +111,22 @@ void benchmark(const Position& current, istream& is) {
|
||||
|
||||
Options["Hash"] = ttSize;
|
||||
Options["Threads"] = threads;
|
||||
TT.clear();
|
||||
Search::clear();
|
||||
|
||||
if (limitType == "time")
|
||||
limits.movetime = atoi(limit.c_str()); // movetime is in ms
|
||||
limits.movetime = stoi(limit); // movetime is in millisecs
|
||||
|
||||
else if (limitType == "nodes")
|
||||
limits.nodes = atoi(limit.c_str());
|
||||
limits.nodes = stoi(limit);
|
||||
|
||||
else if (limitType == "mate")
|
||||
limits.mate = atoi(limit.c_str());
|
||||
limits.mate = stoi(limit);
|
||||
|
||||
else
|
||||
limits.depth = atoi(limit.c_str());
|
||||
limits.depth = stoi(limit);
|
||||
|
||||
if (fenFile == "default")
|
||||
fens.assign(Defaults, Defaults + 37);
|
||||
fens = Defaults;
|
||||
|
||||
else if (fenFile == "current")
|
||||
fens.push_back(current.fen());
|
||||
@@ -128,7 +134,7 @@ void benchmark(const Position& current, istream& is) {
|
||||
else
|
||||
{
|
||||
string fen;
|
||||
ifstream file(fenFile.c_str());
|
||||
ifstream file(fenFile);
|
||||
|
||||
if (!file.is_open())
|
||||
{
|
||||
@@ -144,29 +150,31 @@ void benchmark(const Position& current, istream& is) {
|
||||
}
|
||||
|
||||
uint64_t nodes = 0;
|
||||
Search::StateStackPtr st;
|
||||
Time::point elapsed = Time::now();
|
||||
TimePoint elapsed = now();
|
||||
Position pos;
|
||||
|
||||
for (size_t i = 0; i < fens.size(); ++i)
|
||||
{
|
||||
Position pos(fens[i], Options["UCI_Chess960"], Threads.main());
|
||||
StateListPtr states(new std::deque<StateInfo>(1));
|
||||
pos.set(fens[i], Options["UCI_Chess960"], &states->back(), Threads.main());
|
||||
|
||||
cerr << "\nPosition: " << i + 1 << '/' << fens.size() << endl;
|
||||
|
||||
if (limitType == "perft")
|
||||
nodes += Search::perft<true>(pos, limits.depth * ONE_PLY);
|
||||
nodes += Search::perft(pos, limits.depth * ONE_PLY);
|
||||
|
||||
else
|
||||
{
|
||||
Threads.start_thinking(pos, limits, st);
|
||||
Threads.wait_for_think_finished();
|
||||
nodes += Search::RootPos.nodes_searched();
|
||||
limits.startTime = now();
|
||||
Threads.start_thinking(pos, states, limits);
|
||||
Threads.main()->wait_for_search_finished();
|
||||
nodes += Threads.nodes_searched();
|
||||
}
|
||||
}
|
||||
|
||||
elapsed = std::max(Time::now() - elapsed, Time::point(1)); // Avoid a 'divide by zero'
|
||||
elapsed = now() - elapsed + 1; // Ensure positivity to avoid a 'divide by zero'
|
||||
|
||||
dbg_print(); // Just before to exit
|
||||
dbg_print(); // Just before exiting
|
||||
|
||||
cerr << "\n==========================="
|
||||
<< "\nTotal time (ms) : " << elapsed
|
||||
|
||||
+51
-46
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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
|
||||
@@ -17,7 +18,9 @@
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <numeric>
|
||||
#include <vector>
|
||||
|
||||
#include "bitboard.h"
|
||||
@@ -51,20 +54,19 @@ namespace {
|
||||
WIN = 4
|
||||
};
|
||||
|
||||
inline Result& operator|=(Result& r, Result v) { return r = Result(r | v); }
|
||||
Result& operator|=(Result& r, Result v) { return r = Result(r | v); }
|
||||
|
||||
struct KPKPosition {
|
||||
|
||||
KPKPosition(unsigned idx);
|
||||
KPKPosition() = default;
|
||||
explicit KPKPosition(unsigned idx);
|
||||
operator Result() const { return result; }
|
||||
Result classify(const std::vector<KPKPosition>& db)
|
||||
{ return us == WHITE ? classify<WHITE>(db) : classify<BLACK>(db); }
|
||||
|
||||
private:
|
||||
template<Color Us> Result classify(const std::vector<KPKPosition>& db);
|
||||
|
||||
Color us;
|
||||
Square bksq, wksq, psq;
|
||||
Square ksq[COLOR_NB], psq;
|
||||
Result result;
|
||||
};
|
||||
|
||||
@@ -82,13 +84,12 @@ bool Bitbases::probe(Square wksq, Square wpsq, Square bksq, Color us) {
|
||||
|
||||
void Bitbases::init() {
|
||||
|
||||
std::vector<KPKPosition> db(MAX_INDEX);
|
||||
unsigned idx, repeat = 1;
|
||||
std::vector<KPKPosition> db;
|
||||
db.reserve(MAX_INDEX);
|
||||
|
||||
// Initialize db with known win / draw positions
|
||||
for (idx = 0; idx < MAX_INDEX; ++idx)
|
||||
db.push_back(KPKPosition(idx));
|
||||
db[idx] = KPKPosition(idx);
|
||||
|
||||
// Iterate through the positions until none of the unknown positions can be
|
||||
// changed to either wins or draws (15 cycles needed).
|
||||
@@ -107,69 +108,73 @@ namespace {
|
||||
|
||||
KPKPosition::KPKPosition(unsigned idx) {
|
||||
|
||||
wksq = Square((idx >> 0) & 0x3F);
|
||||
bksq = Square((idx >> 6) & 0x3F);
|
||||
us = Color ((idx >> 12) & 0x01);
|
||||
psq = make_square(File((idx >> 13) & 0x3), RANK_7 - Rank((idx >> 15) & 0x7));
|
||||
result = UNKNOWN;
|
||||
ksq[WHITE] = Square((idx >> 0) & 0x3F);
|
||||
ksq[BLACK] = Square((idx >> 6) & 0x3F);
|
||||
us = Color ((idx >> 12) & 0x01);
|
||||
psq = make_square(File((idx >> 13) & 0x3), RANK_7 - Rank((idx >> 15) & 0x7));
|
||||
|
||||
// Check if two pieces are on the same square or if a king can be captured
|
||||
if ( distance(wksq, bksq) <= 1
|
||||
|| wksq == psq
|
||||
|| bksq == psq
|
||||
|| (us == WHITE && (StepAttacksBB[PAWN][psq] & bksq)))
|
||||
if ( distance(ksq[WHITE], ksq[BLACK]) <= 1
|
||||
|| ksq[WHITE] == psq
|
||||
|| ksq[BLACK] == psq
|
||||
|| (us == WHITE && (StepAttacksBB[PAWN][psq] & ksq[BLACK])))
|
||||
result = INVALID;
|
||||
|
||||
else if (us == WHITE)
|
||||
{
|
||||
// Immediate win if a pawn can be promoted without getting captured
|
||||
if ( rank_of(psq) == RANK_7
|
||||
&& wksq != psq + DELTA_N
|
||||
&& ( distance(bksq, psq + DELTA_N) > 1
|
||||
||(StepAttacksBB[KING][wksq] & (psq + DELTA_N))))
|
||||
result = WIN;
|
||||
}
|
||||
// Immediate win if a pawn can be promoted without getting captured
|
||||
else if ( us == WHITE
|
||||
&& rank_of(psq) == RANK_7
|
||||
&& ksq[us] != psq + NORTH
|
||||
&& ( distance(ksq[~us], psq + NORTH) > 1
|
||||
|| (StepAttacksBB[KING][ksq[us]] & (psq + NORTH))))
|
||||
result = WIN;
|
||||
|
||||
// Immediate draw if it is a stalemate or a king captures undefended pawn
|
||||
else if ( !(StepAttacksBB[KING][bksq] & ~(StepAttacksBB[KING][wksq] | StepAttacksBB[PAWN][psq]))
|
||||
|| (StepAttacksBB[KING][bksq] & psq & ~StepAttacksBB[KING][wksq]))
|
||||
else if ( us == BLACK
|
||||
&& ( !(StepAttacksBB[KING][ksq[us]] & ~(StepAttacksBB[KING][ksq[~us]] | StepAttacksBB[PAWN][psq]))
|
||||
|| (StepAttacksBB[KING][ksq[us]] & psq & ~StepAttacksBB[KING][ksq[~us]])))
|
||||
result = DRAW;
|
||||
|
||||
// Position will be classified later
|
||||
else
|
||||
result = UNKNOWN;
|
||||
}
|
||||
|
||||
template<Color Us>
|
||||
Result KPKPosition::classify(const std::vector<KPKPosition>& db) {
|
||||
|
||||
// White to Move: If one move leads to a position classified as WIN, the result
|
||||
// White to move: If one move leads to a position classified as WIN, the result
|
||||
// of the current position is WIN. If all moves lead to positions classified
|
||||
// as DRAW, the current position is classified as DRAW, otherwise the current
|
||||
// position is classified as UNKNOWN.
|
||||
//
|
||||
// Black to Move: If one move leads to a position classified as DRAW, the result
|
||||
// Black to move: If one move leads to a position classified as DRAW, the result
|
||||
// of the current position is DRAW. If all moves lead to positions classified
|
||||
// as WIN, the position is classified as WIN, otherwise the current position is
|
||||
// classified as UNKNOWN.
|
||||
|
||||
const Color Them = (Us == WHITE ? BLACK : WHITE);
|
||||
const Color Them = (Us == WHITE ? BLACK : WHITE);
|
||||
const Result Good = (Us == WHITE ? WIN : DRAW);
|
||||
const Result Bad = (Us == WHITE ? DRAW : WIN);
|
||||
|
||||
Result r = INVALID;
|
||||
Bitboard b = StepAttacksBB[KING][Us == WHITE ? wksq : bksq];
|
||||
Bitboard b = StepAttacksBB[KING][ksq[Us]];
|
||||
|
||||
while (b)
|
||||
r |= Us == WHITE ? db[index(Them, bksq, pop_lsb(&b), psq)]
|
||||
: db[index(Them, pop_lsb(&b), wksq, psq)];
|
||||
|
||||
if (Us == WHITE && rank_of(psq) < RANK_7)
|
||||
{
|
||||
Square s = psq + DELTA_N;
|
||||
r |= db[index(BLACK, bksq, wksq, s)]; // Single push
|
||||
|
||||
if (rank_of(psq) == RANK_2 && s != wksq && s != bksq)
|
||||
r |= db[index(BLACK, bksq, wksq, s + DELTA_N)]; // Double push
|
||||
}
|
||||
r |= Us == WHITE ? db[index(Them, ksq[Them] , pop_lsb(&b), psq)]
|
||||
: db[index(Them, pop_lsb(&b), ksq[Them] , psq)];
|
||||
|
||||
if (Us == WHITE)
|
||||
return result = r & WIN ? WIN : r & UNKNOWN ? UNKNOWN : DRAW;
|
||||
else
|
||||
return result = r & DRAW ? DRAW : r & UNKNOWN ? UNKNOWN : WIN;
|
||||
{
|
||||
if (rank_of(psq) < RANK_7) // Single push
|
||||
r |= db[index(Them, ksq[Them], ksq[Us], psq + NORTH)];
|
||||
|
||||
if ( rank_of(psq) == RANK_2 // Double push
|
||||
&& psq + NORTH != ksq[Us]
|
||||
&& psq + NORTH != ksq[Them])
|
||||
r |= db[index(Them, ksq[Them], ksq[Us], psq + NORTH + NORTH)];
|
||||
}
|
||||
|
||||
return result = r & Good ? Good : r & UNKNOWN ? UNKNOWN : Bad;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
+47
-35
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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
|
||||
@@ -18,12 +19,11 @@
|
||||
*/
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring> // For std::memset
|
||||
|
||||
#include "bitboard.h"
|
||||
#include "bitcount.h"
|
||||
#include "misc.h"
|
||||
|
||||
uint8_t PopCnt16[1 << 16];
|
||||
int SquareDistance[SQUARE_NB][SQUARE_NB];
|
||||
|
||||
Bitboard RookMasks [SQUARE_NB];
|
||||
@@ -56,7 +56,7 @@ namespace {
|
||||
const uint64_t DeBruijn64 = 0x3F79D71B4CB0A89ULL;
|
||||
const uint32_t DeBruijn32 = 0x783A9B23;
|
||||
|
||||
int MS1BTable[256]; // To implement software msb()
|
||||
int MSBTable[256]; // To implement software msb()
|
||||
Square BSFTable[SQUARE_NB]; // To implement software bitscan
|
||||
Bitboard RookTable[0x19000]; // To store rook attacks
|
||||
Bitboard BishopTable[0x1480]; // To store bishop attacks
|
||||
@@ -69,23 +69,35 @@ namespace {
|
||||
// bsf_index() returns the index into BSFTable[] to look up the bitscan. Uses
|
||||
// Matt Taylor's folding for 32 bit case, extended to 64 bit by Kim Walisch.
|
||||
|
||||
FORCE_INLINE unsigned bsf_index(Bitboard b) {
|
||||
unsigned bsf_index(Bitboard b) {
|
||||
b ^= b - 1;
|
||||
return Is64Bit ? (b * DeBruijn64) >> 58
|
||||
: ((unsigned(b) ^ unsigned(b >> 32)) * DeBruijn32) >> 26;
|
||||
}
|
||||
|
||||
|
||||
// popcount16() counts the non-zero bits using SWAR-Popcount algorithm
|
||||
|
||||
unsigned popcount16(unsigned u) {
|
||||
u -= (u >> 1) & 0x5555U;
|
||||
u = ((u >> 2) & 0x3333U) + (u & 0x3333U);
|
||||
u = ((u >> 4) + u) & 0x0F0FU;
|
||||
return (u * 0x0101U) >> 8;
|
||||
}
|
||||
}
|
||||
|
||||
#ifndef USE_BSFQ
|
||||
#ifdef NO_BSF
|
||||
|
||||
/// Software fall-back of lsb() and msb() for CPU lacking hardware support
|
||||
|
||||
Square lsb(Bitboard b) {
|
||||
assert(b);
|
||||
return BSFTable[bsf_index(b)];
|
||||
}
|
||||
|
||||
Square msb(Bitboard b) {
|
||||
|
||||
assert(b);
|
||||
unsigned b32;
|
||||
int result = 0;
|
||||
|
||||
@@ -109,10 +121,10 @@ Square msb(Bitboard b) {
|
||||
result += 8;
|
||||
}
|
||||
|
||||
return Square(result + MS1BTable[b32]);
|
||||
return Square(result + MSBTable[b32]);
|
||||
}
|
||||
|
||||
#endif // ifndef USE_BSFQ
|
||||
#endif // ifdef NO_BSF
|
||||
|
||||
|
||||
/// Bitboards::pretty() returns an ASCII representation of a bitboard suitable
|
||||
@@ -125,9 +137,9 @@ const std::string Bitboards::pretty(Bitboard b) {
|
||||
for (Rank r = RANK_8; r >= RANK_1; --r)
|
||||
{
|
||||
for (File f = FILE_A; f <= FILE_H; ++f)
|
||||
s.append(b & make_square(f, r) ? "| X " : "| ");
|
||||
s += b & make_square(f, r) ? "| X " : "| ";
|
||||
|
||||
s.append("|\n+---+---+---+---+---+---+---+---+\n");
|
||||
s += "|\n+---+---+---+---+---+---+---+---+\n";
|
||||
}
|
||||
|
||||
return s;
|
||||
@@ -139,14 +151,17 @@ const std::string Bitboards::pretty(Bitboard b) {
|
||||
|
||||
void Bitboards::init() {
|
||||
|
||||
for (unsigned i = 0; i < (1 << 16); ++i)
|
||||
PopCnt16[i] = (uint8_t) popcount16(i);
|
||||
|
||||
for (Square s = SQ_A1; s <= SQ_H8; ++s)
|
||||
{
|
||||
SquareBB[s] = 1ULL << s;
|
||||
BSFTable[bsf_index(SquareBB[s])] = s;
|
||||
}
|
||||
|
||||
for (Bitboard b = 1; b < 256; ++b)
|
||||
MS1BTable[b] = more_than_one(b) ? MS1BTable[b - 1] : lsb(b);
|
||||
for (Bitboard b = 2; b < 256; ++b)
|
||||
MSBTable[b] = MSBTable[b - 1] + !more_than_one(b);
|
||||
|
||||
for (File f = FILE_A; f <= FILE_H; ++f)
|
||||
FileBB[f] = f > FILE_A ? FileBB[f - 1] << 1 : FileABB;
|
||||
@@ -190,8 +205,8 @@ void Bitboards::init() {
|
||||
StepAttacksBB[make_piece(c, pt)][s] |= to;
|
||||
}
|
||||
|
||||
Square RookDeltas[] = { DELTA_N, DELTA_E, DELTA_S, DELTA_W };
|
||||
Square BishopDeltas[] = { DELTA_NE, DELTA_SE, DELTA_SW, DELTA_NW };
|
||||
Square RookDeltas[] = { NORTH, EAST, SOUTH, WEST };
|
||||
Square BishopDeltas[] = { NORTH_EAST, SOUTH_EAST, SOUTH_WEST, NORTH_WEST };
|
||||
|
||||
init_magics(RookTable, RookAttacks, RookMagics, RookMasks, RookShifts, RookDeltas, magic_index<ROOK>);
|
||||
init_magics(BishopTable, BishopAttacks, BishopMagics, BishopMasks, BishopShifts, BishopDeltas, magic_index<BISHOP>);
|
||||
@@ -201,17 +216,15 @@ void Bitboards::init() {
|
||||
PseudoAttacks[QUEEN][s1] = PseudoAttacks[BISHOP][s1] = attacks_bb<BISHOP>(s1, 0);
|
||||
PseudoAttacks[QUEEN][s1] |= PseudoAttacks[ ROOK][s1] = attacks_bb< ROOK>(s1, 0);
|
||||
|
||||
for (Square s2 = SQ_A1; s2 <= SQ_H8; ++s2)
|
||||
{
|
||||
Piece pc = (PseudoAttacks[BISHOP][s1] & s2) ? W_BISHOP :
|
||||
(PseudoAttacks[ROOK][s1] & s2) ? W_ROOK : NO_PIECE;
|
||||
for (Piece pc = W_BISHOP; pc <= W_ROOK; ++pc)
|
||||
for (Square s2 = SQ_A1; s2 <= SQ_H8; ++s2)
|
||||
{
|
||||
if (!(PseudoAttacks[pc][s1] & s2))
|
||||
continue;
|
||||
|
||||
if (pc == NO_PIECE)
|
||||
continue;
|
||||
|
||||
LineBB[s1][s2] = (attacks_bb(pc, s1, 0) & attacks_bb(pc, s2, 0)) | s1 | s2;
|
||||
BetweenBB[s1][s2] = attacks_bb(pc, s1, SquareBB[s2]) & attacks_bb(pc, s2, SquareBB[s1]);
|
||||
}
|
||||
LineBB[s1][s2] = (attacks_bb(pc, s1, 0) & attacks_bb(pc, s2, 0)) | s1 | s2;
|
||||
BetweenBB[s1][s2] = attacks_bb(pc, s1, SquareBB[s2]) & attacks_bb(pc, s2, SquareBB[s1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -249,7 +262,7 @@ namespace {
|
||||
{ 728, 10316, 55013, 32803, 12281, 15100, 16645, 255 } };
|
||||
|
||||
Bitboard occupancy[4096], reference[4096], edges, b;
|
||||
int i, size;
|
||||
int age[4096] = {0}, current = 0, i, size;
|
||||
|
||||
// attacks[s] is a pointer to the beginning of the attacks table for square 's'
|
||||
attacks[SQ_A1] = table;
|
||||
@@ -265,7 +278,7 @@ namespace {
|
||||
// the number of 1s of the mask. Hence we deduce the size of the shift to
|
||||
// apply to the 64 or 32 bits word to get the index.
|
||||
masks[s] = sliding_attack(deltas, s, 0) & ~edges;
|
||||
shifts[s] = (Is64Bit ? 64 : 32) - popcount<Max15>(masks[s]);
|
||||
shifts[s] = (Is64Bit ? 64 : 32) - popcount(masks[s]);
|
||||
|
||||
// Use Carry-Rippler trick to enumerate all subsets of masks[s] and
|
||||
// store the corresponding sliding attack bitboard in reference[].
|
||||
@@ -296,24 +309,23 @@ namespace {
|
||||
do {
|
||||
do
|
||||
magics[s] = rng.sparse_rand<Bitboard>();
|
||||
while (popcount<Max15>((magics[s] * masks[s]) >> 56) < 6);
|
||||
|
||||
std::memset(attacks[s], 0, size * sizeof(Bitboard));
|
||||
while (popcount((magics[s] * masks[s]) >> 56) < 6);
|
||||
|
||||
// A good magic must map every possible occupancy to an index that
|
||||
// looks up the correct sliding attack in the attacks[s] database.
|
||||
// Note that we build up the database for square 's' as a side
|
||||
// effect of verifying the magic.
|
||||
for (i = 0; i < size; ++i)
|
||||
for (++current, i = 0; i < size; ++i)
|
||||
{
|
||||
Bitboard& attack = attacks[s][index(s, occupancy[i])];
|
||||
unsigned idx = index(s, occupancy[i]);
|
||||
|
||||
if (attack && attack != reference[i])
|
||||
if (age[idx] < current)
|
||||
{
|
||||
age[idx] = current;
|
||||
attacks[s][idx] = reference[i];
|
||||
}
|
||||
else if (attacks[s][idx] != reference[i])
|
||||
break;
|
||||
|
||||
assert(reference[i]);
|
||||
|
||||
attack = reference[i];
|
||||
}
|
||||
} while (i < size);
|
||||
}
|
||||
|
||||
+60
-62
@@ -2,13 +2,13 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
|
||||
Stockfish is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
@@ -61,16 +61,6 @@ const Bitboard Rank8BB = Rank1BB << (8 * 7);
|
||||
|
||||
extern int SquareDistance[SQUARE_NB][SQUARE_NB];
|
||||
|
||||
extern Bitboard RookMasks [SQUARE_NB];
|
||||
extern Bitboard RookMagics [SQUARE_NB];
|
||||
extern Bitboard* RookAttacks[SQUARE_NB];
|
||||
extern unsigned RookShifts [SQUARE_NB];
|
||||
|
||||
extern Bitboard BishopMasks [SQUARE_NB];
|
||||
extern Bitboard BishopMagics [SQUARE_NB];
|
||||
extern Bitboard* BishopAttacks[SQUARE_NB];
|
||||
extern unsigned BishopShifts [SQUARE_NB];
|
||||
|
||||
extern Bitboard SquareBB[SQUARE_NB];
|
||||
extern Bitboard FileBB[FILE_NB];
|
||||
extern Bitboard RankBB[RANK_NB];
|
||||
@@ -134,13 +124,13 @@ inline Bitboard file_bb(Square s) {
|
||||
}
|
||||
|
||||
|
||||
/// shift_bb() moves a bitboard one step along direction Delta. Mainly for pawns
|
||||
/// shift() moves a bitboard one step along direction D. Mainly for pawns
|
||||
|
||||
template<Square Delta>
|
||||
inline Bitboard shift_bb(Bitboard b) {
|
||||
return Delta == DELTA_N ? b << 8 : Delta == DELTA_S ? b >> 8
|
||||
: Delta == DELTA_NE ? (b & ~FileHBB) << 9 : Delta == DELTA_SE ? (b & ~FileHBB) >> 7
|
||||
: Delta == DELTA_NW ? (b & ~FileABB) << 7 : Delta == DELTA_SW ? (b & ~FileABB) >> 9
|
||||
template<Square D>
|
||||
inline Bitboard shift(Bitboard b) {
|
||||
return D == NORTH ? b << 8 : D == SOUTH ? b >> 8
|
||||
: D == NORTH_EAST ? (b & ~FileHBB) << 9 : D == SOUTH_EAST ? (b & ~FileHBB) >> 7
|
||||
: D == NORTH_WEST ? (b & ~FileABB) << 7 : D == SOUTH_WEST ? (b & ~FileABB) >> 9
|
||||
: 0;
|
||||
}
|
||||
|
||||
@@ -200,14 +190,6 @@ inline Bitboard passed_pawn_mask(Color c, Square s) {
|
||||
}
|
||||
|
||||
|
||||
/// squares_of_color() returns a bitboard representing all the squares of the
|
||||
/// same color of the given one.
|
||||
|
||||
inline Bitboard squares_of_color(Square s) {
|
||||
return DarkSquares & s ? DarkSquares : ~DarkSquares;
|
||||
}
|
||||
|
||||
|
||||
/// aligned() returns true if the squares s1, s2 and s3 are aligned either on a
|
||||
/// straight or on a diagonal line.
|
||||
|
||||
@@ -231,7 +213,14 @@ template<> inline int distance<Rank>(Square x, Square y) { return distance(rank_
|
||||
/// piece of type Pt (bishop or rook) placed on 's'. The helper magic_index()
|
||||
/// looks up the index using the 'magic bitboards' approach.
|
||||
template<PieceType Pt>
|
||||
FORCE_INLINE unsigned magic_index(Square s, Bitboard occupied) {
|
||||
inline unsigned magic_index(Square s, Bitboard occupied) {
|
||||
|
||||
extern Bitboard RookMasks[SQUARE_NB];
|
||||
extern Bitboard RookMagics[SQUARE_NB];
|
||||
extern unsigned RookShifts[SQUARE_NB];
|
||||
extern Bitboard BishopMasks[SQUARE_NB];
|
||||
extern Bitboard BishopMagics[SQUARE_NB];
|
||||
extern unsigned BishopShifts[SQUARE_NB];
|
||||
|
||||
Bitboard* const Masks = Pt == ROOK ? RookMasks : BishopMasks;
|
||||
Bitboard* const Magics = Pt == ROOK ? RookMagics : BishopMagics;
|
||||
@@ -250,6 +239,10 @@ FORCE_INLINE unsigned magic_index(Square s, Bitboard occupied) {
|
||||
|
||||
template<PieceType Pt>
|
||||
inline Bitboard attacks_bb(Square s, Bitboard occupied) {
|
||||
|
||||
extern Bitboard* RookAttacks[SQUARE_NB];
|
||||
extern Bitboard* BishopAttacks[SQUARE_NB];
|
||||
|
||||
return (Pt == ROOK ? RookAttacks : BishopAttacks)[s][magic_index<Pt>(s, occupied)];
|
||||
}
|
||||
|
||||
@@ -265,56 +258,61 @@ inline Bitboard attacks_bb(Piece pc, Square s, Bitboard occupied) {
|
||||
}
|
||||
|
||||
|
||||
/// popcount() counts the number of non-zero bits in a bitboard
|
||||
|
||||
inline int popcount(Bitboard b) {
|
||||
|
||||
#ifndef USE_POPCNT
|
||||
|
||||
extern uint8_t PopCnt16[1 << 16];
|
||||
union { Bitboard bb; uint16_t u[4]; } v = { b };
|
||||
return PopCnt16[v.u[0]] + PopCnt16[v.u[1]] + PopCnt16[v.u[2]] + PopCnt16[v.u[3]];
|
||||
|
||||
#elif defined(_MSC_VER) || defined(__INTEL_COMPILER)
|
||||
|
||||
return (int)_mm_popcnt_u64(b);
|
||||
|
||||
#else // Assumed gcc or compatible compiler
|
||||
|
||||
return __builtin_popcountll(b);
|
||||
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
/// lsb() and msb() return the least/most significant bit in a non-zero bitboard
|
||||
|
||||
#ifdef USE_BSFQ
|
||||
#if defined(__GNUC__)
|
||||
|
||||
# if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
|
||||
inline Square lsb(Bitboard b) {
|
||||
assert(b);
|
||||
return Square(__builtin_ctzll(b));
|
||||
}
|
||||
|
||||
FORCE_INLINE Square lsb(Bitboard b) {
|
||||
inline Square msb(Bitboard b) {
|
||||
assert(b);
|
||||
return Square(63 - __builtin_clzll(b));
|
||||
}
|
||||
|
||||
#elif defined(_WIN64) && defined(_MSC_VER)
|
||||
|
||||
inline Square lsb(Bitboard b) {
|
||||
assert(b);
|
||||
unsigned long idx;
|
||||
_BitScanForward64(&idx, b);
|
||||
return (Square) idx;
|
||||
}
|
||||
|
||||
FORCE_INLINE Square msb(Bitboard b) {
|
||||
inline Square msb(Bitboard b) {
|
||||
assert(b);
|
||||
unsigned long idx;
|
||||
_BitScanReverse64(&idx, b);
|
||||
return (Square) idx;
|
||||
}
|
||||
|
||||
# elif defined(__arm__)
|
||||
#else
|
||||
|
||||
FORCE_INLINE int lsb32(uint32_t v) {
|
||||
__asm__("rbit %0, %1" : "=r"(v) : "r"(v));
|
||||
return __builtin_clz(v);
|
||||
}
|
||||
|
||||
FORCE_INLINE Square msb(Bitboard b) {
|
||||
return (Square) (63 - __builtin_clzll(b));
|
||||
}
|
||||
|
||||
FORCE_INLINE Square lsb(Bitboard b) {
|
||||
return (Square) (uint32_t(b) ? lsb32(uint32_t(b)) : 32 + lsb32(uint32_t(b >> 32)));
|
||||
}
|
||||
|
||||
# else // Assumed gcc or compatible compiler
|
||||
|
||||
FORCE_INLINE Square lsb(Bitboard b) { // Assembly code by Heinz van Saanen
|
||||
Bitboard idx;
|
||||
__asm__("bsfq %1, %0": "=r"(idx): "rm"(b) );
|
||||
return (Square) idx;
|
||||
}
|
||||
|
||||
FORCE_INLINE Square msb(Bitboard b) {
|
||||
Bitboard idx;
|
||||
__asm__("bsrq %1, %0": "=r"(idx): "rm"(b) );
|
||||
return (Square) idx;
|
||||
}
|
||||
|
||||
# endif
|
||||
|
||||
#else // ifdef(USE_BSFQ)
|
||||
#define NO_BSF // Fallback on software implementation for other cases
|
||||
|
||||
Square lsb(Bitboard b);
|
||||
Square msb(Bitboard b);
|
||||
@@ -324,7 +322,7 @@ Square msb(Bitboard b);
|
||||
|
||||
/// pop_lsb() finds and clears the least significant bit in a non-zero bitboard
|
||||
|
||||
FORCE_INLINE Square pop_lsb(Bitboard* b) {
|
||||
inline Square pop_lsb(Bitboard* b) {
|
||||
const Square s = lsb(*b);
|
||||
*b &= *b - 1;
|
||||
return s;
|
||||
|
||||
-105
@@ -1,105 +0,0 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 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
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
|
||||
Stockfish is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef BITCOUNT_H_INCLUDED
|
||||
#define BITCOUNT_H_INCLUDED
|
||||
|
||||
#include <cassert>
|
||||
|
||||
#include "types.h"
|
||||
|
||||
enum BitCountType {
|
||||
CNT_64,
|
||||
CNT_64_MAX15,
|
||||
CNT_32,
|
||||
CNT_32_MAX15,
|
||||
CNT_HW_POPCNT
|
||||
};
|
||||
|
||||
/// Determine at compile time the best popcount<> specialization according to
|
||||
/// whether the platform is 32 or 64 bit, the maximum number of non-zero
|
||||
/// bits to count and if the hardware popcnt instruction is available.
|
||||
const BitCountType Full = HasPopCnt ? CNT_HW_POPCNT : Is64Bit ? CNT_64 : CNT_32;
|
||||
const BitCountType Max15 = HasPopCnt ? CNT_HW_POPCNT : Is64Bit ? CNT_64_MAX15 : CNT_32_MAX15;
|
||||
|
||||
|
||||
/// popcount() counts the number of non-zero bits in a bitboard
|
||||
template<BitCountType> inline int popcount(Bitboard);
|
||||
|
||||
template<>
|
||||
inline int popcount<CNT_64>(Bitboard b) {
|
||||
b -= (b >> 1) & 0x5555555555555555ULL;
|
||||
b = ((b >> 2) & 0x3333333333333333ULL) + (b & 0x3333333333333333ULL);
|
||||
b = ((b >> 4) + b) & 0x0F0F0F0F0F0F0F0FULL;
|
||||
return (b * 0x0101010101010101ULL) >> 56;
|
||||
}
|
||||
|
||||
template<>
|
||||
inline int popcount<CNT_64_MAX15>(Bitboard b) {
|
||||
b -= (b >> 1) & 0x5555555555555555ULL;
|
||||
b = ((b >> 2) & 0x3333333333333333ULL) + (b & 0x3333333333333333ULL);
|
||||
return (b * 0x1111111111111111ULL) >> 60;
|
||||
}
|
||||
|
||||
template<>
|
||||
inline int popcount<CNT_32>(Bitboard b) {
|
||||
unsigned w = unsigned(b >> 32), v = unsigned(b);
|
||||
v -= (v >> 1) & 0x55555555; // 0-2 in 2 bits
|
||||
w -= (w >> 1) & 0x55555555;
|
||||
v = ((v >> 2) & 0x33333333) + (v & 0x33333333); // 0-4 in 4 bits
|
||||
w = ((w >> 2) & 0x33333333) + (w & 0x33333333);
|
||||
v = ((v >> 4) + v + (w >> 4) + w) & 0x0F0F0F0F;
|
||||
return (v * 0x01010101) >> 24;
|
||||
}
|
||||
|
||||
template<>
|
||||
inline int popcount<CNT_32_MAX15>(Bitboard b) {
|
||||
unsigned w = unsigned(b >> 32), v = unsigned(b);
|
||||
v -= (v >> 1) & 0x55555555; // 0-2 in 2 bits
|
||||
w -= (w >> 1) & 0x55555555;
|
||||
v = ((v >> 2) & 0x33333333) + (v & 0x33333333); // 0-4 in 4 bits
|
||||
w = ((w >> 2) & 0x33333333) + (w & 0x33333333);
|
||||
return ((v + w) * 0x11111111) >> 28;
|
||||
}
|
||||
|
||||
template<>
|
||||
inline int popcount<CNT_HW_POPCNT>(Bitboard b) {
|
||||
|
||||
#ifndef USE_POPCNT
|
||||
|
||||
assert(false);
|
||||
return b != 0; // Avoid 'b not used' warning
|
||||
|
||||
#elif defined(_MSC_VER) && defined(__INTEL_COMPILER)
|
||||
|
||||
return _mm_popcnt_u64(b);
|
||||
|
||||
#elif defined(_MSC_VER)
|
||||
|
||||
return (int)__popcnt64(b);
|
||||
|
||||
#else // Assumed gcc or compatible compiler
|
||||
|
||||
return __builtin_popcountll(b);
|
||||
|
||||
#endif
|
||||
}
|
||||
|
||||
#endif // #ifndef BITCOUNT_H_INCLUDED
|
||||
+91
-103
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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
|
||||
@@ -21,7 +22,6 @@
|
||||
#include <cassert>
|
||||
|
||||
#include "bitboard.h"
|
||||
#include "bitcount.h"
|
||||
#include "endgame.h"
|
||||
#include "movegen.h"
|
||||
|
||||
@@ -39,7 +39,7 @@ namespace {
|
||||
70, 50, 30, 20, 20, 30, 50, 70,
|
||||
80, 60, 40, 30, 30, 40, 60, 80,
|
||||
90, 70, 60, 50, 50, 60, 70, 90,
|
||||
100, 90, 80, 70, 70, 80, 90, 100,
|
||||
100, 90, 80, 70, 70, 80, 90, 100
|
||||
};
|
||||
|
||||
// Table used to drive the king towards a corner square of the
|
||||
@@ -59,6 +59,9 @@ namespace {
|
||||
const int PushClose[8] = { 0, 0, 100, 80, 60, 40, 20, 10 };
|
||||
const int PushAway [8] = { 0, 5, 20, 40, 60, 80, 90, 100 };
|
||||
|
||||
// Pawn Rank based scaling factors used in KRPPKRP endgame
|
||||
const int KRPPKRPScaleFactors[RANK_NB] = { 0, 9, 10, 14, 21, 44, 0, 0 };
|
||||
|
||||
#ifndef NDEBUG
|
||||
bool verify_material(const Position& pos, Color c, Value npm, int pawnsCnt) {
|
||||
return pos.non_pawn_material(c) == npm && pos.count<PAWN>(c) == pawnsCnt;
|
||||
@@ -71,7 +74,7 @@ namespace {
|
||||
|
||||
assert(pos.count<PAWN>(strongSide) == 1);
|
||||
|
||||
if (file_of(pos.list<PAWN>(strongSide)[0]) >= FILE_E)
|
||||
if (file_of(pos.square<PAWN>(strongSide)) >= FILE_E)
|
||||
sq = Square(sq ^ 7); // Mirror SQ_H1 -> SQ_A1
|
||||
|
||||
if (strongSide == BLACK)
|
||||
@@ -96,12 +99,10 @@ namespace {
|
||||
string fen = sides[0] + char(8 - sides[0].length() + '0') + "/8/8/8/8/8/8/"
|
||||
+ sides[1] + char(8 - sides[1].length() + '0') + " w - - 0 10";
|
||||
|
||||
return Position(fen, false, NULL).material_key();
|
||||
StateInfo st;
|
||||
return Position().set(fen, false, &st, nullptr).material_key();
|
||||
}
|
||||
|
||||
template<typename M>
|
||||
void delete_endgame(const typename M::value_type& p) { delete p.second; }
|
||||
|
||||
} // namespace
|
||||
|
||||
|
||||
@@ -128,17 +129,11 @@ Endgames::Endgames() {
|
||||
add<KRPPKRP>("KRPPKRP");
|
||||
}
|
||||
|
||||
Endgames::~Endgames() {
|
||||
|
||||
for_each(m1.begin(), m1.end(), delete_endgame<M1>);
|
||||
for_each(m2.begin(), m2.end(), delete_endgame<M2>);
|
||||
}
|
||||
|
||||
template<EndgameType E>
|
||||
template<EndgameType E, typename T>
|
||||
void Endgames::add(const string& code) {
|
||||
|
||||
map((Endgame<E>*)0)[key(code, WHITE)] = new Endgame<E>(WHITE);
|
||||
map((Endgame<E>*)0)[key(code, BLACK)] = new Endgame<E>(BLACK);
|
||||
map<T>()[key(code, WHITE)] = std::unique_ptr<EndgameBase<T>>(new Endgame<E>(WHITE));
|
||||
map<T>()[key(code, BLACK)] = std::unique_ptr<EndgameBase<T>>(new Endgame<E>(BLACK));
|
||||
}
|
||||
|
||||
|
||||
@@ -156,8 +151,8 @@ Value Endgame<KXK>::operator()(const Position& pos) const {
|
||||
if (pos.side_to_move() == weakSide && !MoveList<LEGAL>(pos).size())
|
||||
return VALUE_DRAW;
|
||||
|
||||
Square winnerKSq = pos.king_square(strongSide);
|
||||
Square loserKSq = pos.king_square(weakSide);
|
||||
Square winnerKSq = pos.square<KING>(strongSide);
|
||||
Square loserKSq = pos.square<KING>(weakSide);
|
||||
|
||||
Value result = pos.non_pawn_material(strongSide)
|
||||
+ pos.count<PAWN>(strongSide) * PawnValueEg
|
||||
@@ -167,9 +162,9 @@ Value Endgame<KXK>::operator()(const Position& pos) const {
|
||||
if ( pos.count<QUEEN>(strongSide)
|
||||
|| pos.count<ROOK>(strongSide)
|
||||
||(pos.count<BISHOP>(strongSide) && pos.count<KNIGHT>(strongSide))
|
||||
||(pos.count<BISHOP>(strongSide) > 1 && opposite_colors(pos.list<BISHOP>(strongSide)[0],
|
||||
pos.list<BISHOP>(strongSide)[1])))
|
||||
result += VALUE_KNOWN_WIN;
|
||||
||(pos.count<BISHOP>(strongSide) > 1 && opposite_colors(pos.squares<BISHOP>(strongSide)[0],
|
||||
pos.squares<BISHOP>(strongSide)[1])))
|
||||
result = std::min(result + VALUE_KNOWN_WIN, VALUE_MATE_IN_MAX_PLY - 1);
|
||||
|
||||
return strongSide == pos.side_to_move() ? result : -result;
|
||||
}
|
||||
@@ -183,9 +178,9 @@ Value Endgame<KBNK>::operator()(const Position& pos) const {
|
||||
assert(verify_material(pos, strongSide, KnightValueMg + BishopValueMg, 0));
|
||||
assert(verify_material(pos, weakSide, VALUE_ZERO, 0));
|
||||
|
||||
Square winnerKSq = pos.king_square(strongSide);
|
||||
Square loserKSq = pos.king_square(weakSide);
|
||||
Square bishopSq = pos.list<BISHOP>(strongSide)[0];
|
||||
Square winnerKSq = pos.square<KING>(strongSide);
|
||||
Square loserKSq = pos.square<KING>(weakSide);
|
||||
Square bishopSq = pos.square<BISHOP>(strongSide);
|
||||
|
||||
// kbnk_mate_table() tries to drive toward corners A1 or H8. If we have a
|
||||
// bishop that cannot reach the above squares, we flip the kings in order
|
||||
@@ -212,9 +207,9 @@ Value Endgame<KPK>::operator()(const Position& pos) const {
|
||||
assert(verify_material(pos, weakSide, VALUE_ZERO, 0));
|
||||
|
||||
// Assume strongSide is white and the pawn is on files A-D
|
||||
Square wksq = normalize(pos, strongSide, pos.king_square(strongSide));
|
||||
Square bksq = normalize(pos, strongSide, pos.king_square(weakSide));
|
||||
Square psq = normalize(pos, strongSide, pos.list<PAWN>(strongSide)[0]);
|
||||
Square wksq = normalize(pos, strongSide, pos.square<KING>(strongSide));
|
||||
Square bksq = normalize(pos, strongSide, pos.square<KING>(weakSide));
|
||||
Square psq = normalize(pos, strongSide, pos.square<PAWN>(strongSide));
|
||||
|
||||
Color us = strongSide == pos.side_to_move() ? WHITE : BLACK;
|
||||
|
||||
@@ -237,10 +232,10 @@ Value Endgame<KRKP>::operator()(const Position& pos) const {
|
||||
assert(verify_material(pos, strongSide, RookValueMg, 0));
|
||||
assert(verify_material(pos, weakSide, VALUE_ZERO, 1));
|
||||
|
||||
Square wksq = relative_square(strongSide, pos.king_square(strongSide));
|
||||
Square bksq = relative_square(strongSide, pos.king_square(weakSide));
|
||||
Square rsq = relative_square(strongSide, pos.list<ROOK>(strongSide)[0]);
|
||||
Square psq = relative_square(strongSide, pos.list<PAWN>(weakSide)[0]);
|
||||
Square wksq = relative_square(strongSide, pos.square<KING>(strongSide));
|
||||
Square bksq = relative_square(strongSide, pos.square<KING>(weakSide));
|
||||
Square rsq = relative_square(strongSide, pos.square<ROOK>(strongSide));
|
||||
Square psq = relative_square(strongSide, pos.square<PAWN>(weakSide));
|
||||
|
||||
Square queeningSq = make_square(file_of(psq), RANK_1);
|
||||
Value result;
|
||||
@@ -264,8 +259,8 @@ Value Endgame<KRKP>::operator()(const Position& pos) const {
|
||||
result = Value(80) - 8 * distance(wksq, psq);
|
||||
|
||||
else
|
||||
result = Value(200) - 8 * ( distance(wksq, psq + DELTA_S)
|
||||
- distance(bksq, psq + DELTA_S)
|
||||
result = Value(200) - 8 * ( distance(wksq, psq + SOUTH)
|
||||
- distance(bksq, psq + SOUTH)
|
||||
- distance(psq, queeningSq));
|
||||
|
||||
return strongSide == pos.side_to_move() ? result : -result;
|
||||
@@ -280,7 +275,7 @@ Value Endgame<KRKB>::operator()(const Position& pos) const {
|
||||
assert(verify_material(pos, strongSide, RookValueMg, 0));
|
||||
assert(verify_material(pos, weakSide, BishopValueMg, 0));
|
||||
|
||||
Value result = Value(PushToEdges[pos.king_square(weakSide)]);
|
||||
Value result = Value(PushToEdges[pos.square<KING>(weakSide)]);
|
||||
return strongSide == pos.side_to_move() ? result : -result;
|
||||
}
|
||||
|
||||
@@ -293,8 +288,8 @@ Value Endgame<KRKN>::operator()(const Position& pos) const {
|
||||
assert(verify_material(pos, strongSide, RookValueMg, 0));
|
||||
assert(verify_material(pos, weakSide, KnightValueMg, 0));
|
||||
|
||||
Square bksq = pos.king_square(weakSide);
|
||||
Square bnsq = pos.list<KNIGHT>(weakSide)[0];
|
||||
Square bksq = pos.square<KING>(weakSide);
|
||||
Square bnsq = pos.square<KNIGHT>(weakSide);
|
||||
Value result = Value(PushToEdges[bksq] + PushAway[distance(bksq, bnsq)]);
|
||||
return strongSide == pos.side_to_move() ? result : -result;
|
||||
}
|
||||
@@ -310,9 +305,9 @@ Value Endgame<KQKP>::operator()(const Position& pos) const {
|
||||
assert(verify_material(pos, strongSide, QueenValueMg, 0));
|
||||
assert(verify_material(pos, weakSide, VALUE_ZERO, 1));
|
||||
|
||||
Square winnerKSq = pos.king_square(strongSide);
|
||||
Square loserKSq = pos.king_square(weakSide);
|
||||
Square pawnSq = pos.list<PAWN>(weakSide)[0];
|
||||
Square winnerKSq = pos.square<KING>(strongSide);
|
||||
Square loserKSq = pos.square<KING>(weakSide);
|
||||
Square pawnSq = pos.square<PAWN>(weakSide);
|
||||
|
||||
Value result = Value(PushClose[distance(winnerKSq, loserKSq)]);
|
||||
|
||||
@@ -335,8 +330,8 @@ Value Endgame<KQKR>::operator()(const Position& pos) const {
|
||||
assert(verify_material(pos, strongSide, QueenValueMg, 0));
|
||||
assert(verify_material(pos, weakSide, RookValueMg, 0));
|
||||
|
||||
Square winnerKSq = pos.king_square(strongSide);
|
||||
Square loserKSq = pos.king_square(weakSide);
|
||||
Square winnerKSq = pos.square<KING>(strongSide);
|
||||
Square loserKSq = pos.square<KING>(weakSide);
|
||||
|
||||
Value result = QueenValueEg
|
||||
- RookValueEg
|
||||
@@ -365,15 +360,15 @@ ScaleFactor Endgame<KBPsK>::operator()(const Position& pos) const {
|
||||
// be detected even when the weaker side has some pawns.
|
||||
|
||||
Bitboard pawns = pos.pieces(strongSide, PAWN);
|
||||
File pawnFile = file_of(pos.list<PAWN>(strongSide)[0]);
|
||||
File pawnsFile = file_of(lsb(pawns));
|
||||
|
||||
// All pawns are on a single rook file ?
|
||||
if ( (pawnFile == FILE_A || pawnFile == FILE_H)
|
||||
&& !(pawns & ~file_bb(pawnFile)))
|
||||
// All pawns are on a single rook file?
|
||||
if ( (pawnsFile == FILE_A || pawnsFile == FILE_H)
|
||||
&& !(pawns & ~file_bb(pawnsFile)))
|
||||
{
|
||||
Square bishopSq = pos.list<BISHOP>(strongSide)[0];
|
||||
Square queeningSq = relative_square(strongSide, make_square(pawnFile, RANK_8));
|
||||
Square kingSq = pos.king_square(weakSide);
|
||||
Square bishopSq = pos.square<BISHOP>(strongSide);
|
||||
Square queeningSq = relative_square(strongSide, make_square(pawnsFile, RANK_8));
|
||||
Square kingSq = pos.square<KING>(weakSide);
|
||||
|
||||
if ( opposite_colors(queeningSq, bishopSq)
|
||||
&& distance(queeningSq, kingSq) <= 1)
|
||||
@@ -381,17 +376,17 @@ ScaleFactor Endgame<KBPsK>::operator()(const Position& pos) const {
|
||||
}
|
||||
|
||||
// If all the pawns are on the same B or G file, then it's potentially a draw
|
||||
if ( (pawnFile == FILE_B || pawnFile == FILE_G)
|
||||
&& !(pos.pieces(PAWN) & ~file_bb(pawnFile))
|
||||
if ( (pawnsFile == FILE_B || pawnsFile == FILE_G)
|
||||
&& !(pos.pieces(PAWN) & ~file_bb(pawnsFile))
|
||||
&& pos.non_pawn_material(weakSide) == 0
|
||||
&& pos.count<PAWN>(weakSide) >= 1)
|
||||
{
|
||||
// Get weakSide pawn that is closest to the home rank
|
||||
Square weakPawnSq = backmost_sq(weakSide, pos.pieces(weakSide, PAWN));
|
||||
|
||||
Square strongKingSq = pos.king_square(strongSide);
|
||||
Square weakKingSq = pos.king_square(weakSide);
|
||||
Square bishopSq = pos.list<BISHOP>(strongSide)[0];
|
||||
Square strongKingSq = pos.square<KING>(strongSide);
|
||||
Square weakKingSq = pos.square<KING>(weakSide);
|
||||
Square bishopSq = pos.square<BISHOP>(strongSide);
|
||||
|
||||
// There's potential for a draw if our pawn is blocked on the 7th rank,
|
||||
// the bishop cannot attack it or they only have one pawn left
|
||||
@@ -428,11 +423,11 @@ ScaleFactor Endgame<KQKRPs>::operator()(const Position& pos) const {
|
||||
assert(pos.count<ROOK>(weakSide) == 1);
|
||||
assert(pos.count<PAWN>(weakSide) >= 1);
|
||||
|
||||
Square kingSq = pos.king_square(weakSide);
|
||||
Square rsq = pos.list<ROOK>(weakSide)[0];
|
||||
Square kingSq = pos.square<KING>(weakSide);
|
||||
Square rsq = pos.square<ROOK>(weakSide);
|
||||
|
||||
if ( relative_rank(weakSide, kingSq) <= RANK_2
|
||||
&& relative_rank(weakSide, pos.king_square(strongSide)) >= RANK_4
|
||||
&& relative_rank(weakSide, pos.square<KING>(strongSide)) >= RANK_4
|
||||
&& relative_rank(weakSide, rsq) == RANK_3
|
||||
&& ( pos.pieces(weakSide, PAWN)
|
||||
& pos.attacks_from<KING>(kingSq)
|
||||
@@ -456,11 +451,11 @@ ScaleFactor Endgame<KRPKR>::operator()(const Position& pos) const {
|
||||
assert(verify_material(pos, weakSide, RookValueMg, 0));
|
||||
|
||||
// Assume strongSide is white and the pawn is on files A-D
|
||||
Square wksq = normalize(pos, strongSide, pos.king_square(strongSide));
|
||||
Square bksq = normalize(pos, strongSide, pos.king_square(weakSide));
|
||||
Square wrsq = normalize(pos, strongSide, pos.list<ROOK>(strongSide)[0]);
|
||||
Square wpsq = normalize(pos, strongSide, pos.list<PAWN>(strongSide)[0]);
|
||||
Square brsq = normalize(pos, strongSide, pos.list<ROOK>(weakSide)[0]);
|
||||
Square wksq = normalize(pos, strongSide, pos.square<KING>(strongSide));
|
||||
Square bksq = normalize(pos, strongSide, pos.square<KING>(weakSide));
|
||||
Square wrsq = normalize(pos, strongSide, pos.square<ROOK>(strongSide));
|
||||
Square wpsq = normalize(pos, strongSide, pos.square<PAWN>(strongSide));
|
||||
Square brsq = normalize(pos, strongSide, pos.square<ROOK>(weakSide));
|
||||
|
||||
File f = file_of(wpsq);
|
||||
Rank r = rank_of(wpsq);
|
||||
@@ -480,7 +475,7 @@ ScaleFactor Endgame<KRPKR>::operator()(const Position& pos) const {
|
||||
if ( r == RANK_6
|
||||
&& distance(bksq, queeningSq) <= 1
|
||||
&& rank_of(wksq) + tempo <= RANK_6
|
||||
&& (rank_of(brsq) == RANK_1 || (!tempo && distance(file_of(brsq), f) >= 3)))
|
||||
&& (rank_of(brsq) == RANK_1 || (!tempo && distance<File>(brsq, wpsq) >= 3)))
|
||||
return SCALE_FACTOR_DRAW;
|
||||
|
||||
if ( r >= RANK_6
|
||||
@@ -501,7 +496,7 @@ ScaleFactor Endgame<KRPKR>::operator()(const Position& pos) const {
|
||||
// If the defending king blocks the pawn and the attacking king is too far
|
||||
// away, it's a draw.
|
||||
if ( r <= RANK_5
|
||||
&& bksq == wpsq + DELTA_N
|
||||
&& bksq == wpsq + NORTH
|
||||
&& distance(wksq, wpsq) - tempo >= 2
|
||||
&& distance(wksq, brsq) - tempo >= 2)
|
||||
return SCALE_FACTOR_DRAW;
|
||||
@@ -522,10 +517,10 @@ ScaleFactor Endgame<KRPKR>::operator()(const Position& pos) const {
|
||||
&& file_of(wrsq) == f
|
||||
&& wrsq < wpsq
|
||||
&& (distance(wksq, queeningSq) < distance(bksq, queeningSq) - 2 + tempo)
|
||||
&& (distance(wksq, wpsq + DELTA_N) < distance(bksq, wpsq + DELTA_N) - 2 + tempo)
|
||||
&& (distance(wksq, wpsq + NORTH) < distance(bksq, wpsq + NORTH) - 2 + tempo)
|
||||
&& ( distance(bksq, wrsq) + tempo >= 3
|
||||
|| ( distance(wksq, queeningSq) < distance(bksq, wrsq) + tempo
|
||||
&& (distance(wksq, wpsq + DELTA_N) < distance(bksq, wrsq) + tempo))))
|
||||
&& (distance(wksq, wpsq + NORTH) < distance(bksq, wrsq) + tempo))))
|
||||
return ScaleFactor( SCALE_FACTOR_MAX
|
||||
- 8 * distance(wpsq, queeningSq)
|
||||
- 2 * distance(wksq, queeningSq));
|
||||
@@ -552,9 +547,9 @@ ScaleFactor Endgame<KRPKB>::operator()(const Position& pos) const {
|
||||
// Test for a rook pawn
|
||||
if (pos.pieces(PAWN) & (FileABB | FileHBB))
|
||||
{
|
||||
Square ksq = pos.king_square(weakSide);
|
||||
Square bsq = pos.list<BISHOP>(weakSide)[0];
|
||||
Square psq = pos.list<PAWN>(strongSide)[0];
|
||||
Square ksq = pos.square<KING>(weakSide);
|
||||
Square bsq = pos.square<BISHOP>(weakSide);
|
||||
Square psq = pos.square<PAWN>(strongSide);
|
||||
Rank rk = relative_rank(strongSide, psq);
|
||||
Square push = pawn_push(strongSide);
|
||||
|
||||
@@ -567,7 +562,7 @@ ScaleFactor Endgame<KRPKB>::operator()(const Position& pos) const {
|
||||
{
|
||||
int d = distance(psq + 3 * push, ksq);
|
||||
|
||||
if (d <= 2 && !(d == 0 && ksq == pos.king_square(strongSide) + 2 * push))
|
||||
if (d <= 2 && !(d == 0 && ksq == pos.square<KING>(strongSide) + 2 * push))
|
||||
return ScaleFactor(24);
|
||||
else
|
||||
return ScaleFactor(48);
|
||||
@@ -595,9 +590,9 @@ ScaleFactor Endgame<KRPPKRP>::operator()(const Position& pos) const {
|
||||
assert(verify_material(pos, strongSide, RookValueMg, 2));
|
||||
assert(verify_material(pos, weakSide, RookValueMg, 1));
|
||||
|
||||
Square wpsq1 = pos.list<PAWN>(strongSide)[0];
|
||||
Square wpsq2 = pos.list<PAWN>(strongSide)[1];
|
||||
Square bksq = pos.king_square(weakSide);
|
||||
Square wpsq1 = pos.squares<PAWN>(strongSide)[0];
|
||||
Square wpsq2 = pos.squares<PAWN>(strongSide)[1];
|
||||
Square bksq = pos.square<KING>(weakSide);
|
||||
|
||||
// Does the stronger side have a passed pawn?
|
||||
if (pos.pawn_passed(strongSide, wpsq1) || pos.pawn_passed(strongSide, wpsq2))
|
||||
@@ -609,14 +604,8 @@ ScaleFactor Endgame<KRPPKRP>::operator()(const Position& pos) const {
|
||||
&& distance<File>(bksq, wpsq2) <= 1
|
||||
&& relative_rank(strongSide, bksq) > r)
|
||||
{
|
||||
switch (r) {
|
||||
case RANK_2: return ScaleFactor(10);
|
||||
case RANK_3: return ScaleFactor(10);
|
||||
case RANK_4: return ScaleFactor(15);
|
||||
case RANK_5: return ScaleFactor(20);
|
||||
case RANK_6: return ScaleFactor(40);
|
||||
default: assert(false);
|
||||
}
|
||||
assert(r > RANK_1 && r < RANK_7);
|
||||
return ScaleFactor(KRPPKRPScaleFactors[r]);
|
||||
}
|
||||
return SCALE_FACTOR_NONE;
|
||||
}
|
||||
@@ -631,15 +620,14 @@ ScaleFactor Endgame<KPsK>::operator()(const Position& pos) const {
|
||||
assert(pos.count<PAWN>(strongSide) >= 2);
|
||||
assert(verify_material(pos, weakSide, VALUE_ZERO, 0));
|
||||
|
||||
Square ksq = pos.king_square(weakSide);
|
||||
Square ksq = pos.square<KING>(weakSide);
|
||||
Bitboard pawns = pos.pieces(strongSide, PAWN);
|
||||
Square psq = pos.list<PAWN>(strongSide)[0];
|
||||
|
||||
// If all pawns are ahead of the king, on a single rook file and
|
||||
// the king is within one file of the pawns, it's a draw.
|
||||
if ( !(pawns & ~in_front_bb(weakSide, rank_of(ksq)))
|
||||
&& !((pawns & ~FileABB) && (pawns & ~FileHBB))
|
||||
&& distance<File>(ksq, psq) <= 1)
|
||||
&& distance<File>(ksq, lsb(pawns)) <= 1)
|
||||
return SCALE_FACTOR_DRAW;
|
||||
|
||||
return SCALE_FACTOR_NONE;
|
||||
@@ -656,10 +644,10 @@ ScaleFactor Endgame<KBPKB>::operator()(const Position& pos) const {
|
||||
assert(verify_material(pos, strongSide, BishopValueMg, 1));
|
||||
assert(verify_material(pos, weakSide, BishopValueMg, 0));
|
||||
|
||||
Square pawnSq = pos.list<PAWN>(strongSide)[0];
|
||||
Square strongBishopSq = pos.list<BISHOP>(strongSide)[0];
|
||||
Square weakBishopSq = pos.list<BISHOP>(weakSide)[0];
|
||||
Square weakKingSq = pos.king_square(weakSide);
|
||||
Square pawnSq = pos.square<PAWN>(strongSide);
|
||||
Square strongBishopSq = pos.square<BISHOP>(strongSide);
|
||||
Square weakBishopSq = pos.square<BISHOP>(weakSide);
|
||||
Square weakKingSq = pos.square<KING>(weakSide);
|
||||
|
||||
// Case 1: Defending king blocks the pawn, and cannot be driven away
|
||||
if ( file_of(weakKingSq) == file_of(pawnSq)
|
||||
@@ -706,15 +694,15 @@ ScaleFactor Endgame<KBPPKB>::operator()(const Position& pos) const {
|
||||
assert(verify_material(pos, strongSide, BishopValueMg, 2));
|
||||
assert(verify_material(pos, weakSide, BishopValueMg, 0));
|
||||
|
||||
Square wbsq = pos.list<BISHOP>(strongSide)[0];
|
||||
Square bbsq = pos.list<BISHOP>(weakSide)[0];
|
||||
Square wbsq = pos.square<BISHOP>(strongSide);
|
||||
Square bbsq = pos.square<BISHOP>(weakSide);
|
||||
|
||||
if (!opposite_colors(wbsq, bbsq))
|
||||
return SCALE_FACTOR_NONE;
|
||||
|
||||
Square ksq = pos.king_square(weakSide);
|
||||
Square psq1 = pos.list<PAWN>(strongSide)[0];
|
||||
Square psq2 = pos.list<PAWN>(strongSide)[1];
|
||||
Square ksq = pos.square<KING>(weakSide);
|
||||
Square psq1 = pos.squares<PAWN>(strongSide)[0];
|
||||
Square psq2 = pos.squares<PAWN>(strongSide)[1];
|
||||
Rank r1 = rank_of(psq1);
|
||||
Rank r2 = rank_of(psq2);
|
||||
Square blockSq1, blockSq2;
|
||||
@@ -777,9 +765,9 @@ ScaleFactor Endgame<KBPKN>::operator()(const Position& pos) const {
|
||||
assert(verify_material(pos, strongSide, BishopValueMg, 1));
|
||||
assert(verify_material(pos, weakSide, KnightValueMg, 0));
|
||||
|
||||
Square pawnSq = pos.list<PAWN>(strongSide)[0];
|
||||
Square strongBishopSq = pos.list<BISHOP>(strongSide)[0];
|
||||
Square weakKingSq = pos.king_square(weakSide);
|
||||
Square pawnSq = pos.square<PAWN>(strongSide);
|
||||
Square strongBishopSq = pos.square<BISHOP>(strongSide);
|
||||
Square weakKingSq = pos.square<KING>(weakSide);
|
||||
|
||||
if ( file_of(weakKingSq) == file_of(pawnSq)
|
||||
&& relative_rank(strongSide, pawnSq) < relative_rank(strongSide, weakKingSq)
|
||||
@@ -800,8 +788,8 @@ ScaleFactor Endgame<KNPK>::operator()(const Position& pos) const {
|
||||
assert(verify_material(pos, weakSide, VALUE_ZERO, 0));
|
||||
|
||||
// Assume strongSide is white and the pawn is on files A-D
|
||||
Square pawnSq = normalize(pos, strongSide, pos.list<PAWN>(strongSide)[0]);
|
||||
Square weakKingSq = normalize(pos, strongSide, pos.king_square(weakSide));
|
||||
Square pawnSq = normalize(pos, strongSide, pos.square<PAWN>(strongSide));
|
||||
Square weakKingSq = normalize(pos, strongSide, pos.square<KING>(weakSide));
|
||||
|
||||
if (pawnSq == SQ_A7 && distance(SQ_A8, weakKingSq) <= 1)
|
||||
return SCALE_FACTOR_DRAW;
|
||||
@@ -815,9 +803,9 @@ ScaleFactor Endgame<KNPK>::operator()(const Position& pos) const {
|
||||
template<>
|
||||
ScaleFactor Endgame<KNPKB>::operator()(const Position& pos) const {
|
||||
|
||||
Square pawnSq = pos.list<PAWN>(strongSide)[0];
|
||||
Square bishopSq = pos.list<BISHOP>(weakSide)[0];
|
||||
Square weakKingSq = pos.king_square(weakSide);
|
||||
Square pawnSq = pos.square<PAWN>(strongSide);
|
||||
Square bishopSq = pos.square<BISHOP>(weakSide);
|
||||
Square weakKingSq = pos.square<KING>(weakSide);
|
||||
|
||||
// King needs to get close to promoting pawn to prevent knight from blocking.
|
||||
// Rules for this are very tricky, so just approximate.
|
||||
@@ -840,9 +828,9 @@ ScaleFactor Endgame<KPKP>::operator()(const Position& pos) const {
|
||||
assert(verify_material(pos, weakSide, VALUE_ZERO, 1));
|
||||
|
||||
// Assume strongSide is white and the pawn is on files A-D
|
||||
Square wksq = normalize(pos, strongSide, pos.king_square(strongSide));
|
||||
Square bksq = normalize(pos, strongSide, pos.king_square(weakSide));
|
||||
Square psq = normalize(pos, strongSide, pos.list<PAWN>(strongSide)[0]);
|
||||
Square wksq = normalize(pos, strongSide, pos.square<KING>(strongSide));
|
||||
Square bksq = normalize(pos, strongSide, pos.square<KING>(weakSide));
|
||||
Square psq = normalize(pos, strongSide, pos.square<PAWN>(strongSide));
|
||||
|
||||
Color us = strongSide == pos.side_to_move() ? WHITE : BLACK;
|
||||
|
||||
|
||||
+20
-17
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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
|
||||
@@ -21,7 +22,10 @@
|
||||
#define ENDGAME_H_INCLUDED
|
||||
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
#include "position.h"
|
||||
#include "types.h"
|
||||
@@ -63,11 +67,9 @@ enum EndgameType {
|
||||
|
||||
|
||||
/// Endgame functions can be of two types depending on whether they return a
|
||||
/// Value or a ScaleFactor. Type eg_fun<int>::type returns either ScaleFactor
|
||||
/// or Value depending on whether the template parameter is 0 or 1.
|
||||
|
||||
template<int> struct eg_fun { typedef Value type; };
|
||||
template<> struct eg_fun<1> { typedef ScaleFactor type; };
|
||||
/// Value or a ScaleFactor.
|
||||
template<EndgameType E> using
|
||||
eg_type = typename std::conditional<(E < SCALING_FUNCTIONS), Value, ScaleFactor>::type;
|
||||
|
||||
|
||||
/// Base and derived templates for endgame evaluation and scaling functions
|
||||
@@ -75,13 +77,13 @@ template<> struct eg_fun<1> { typedef ScaleFactor type; };
|
||||
template<typename T>
|
||||
struct EndgameBase {
|
||||
|
||||
virtual ~EndgameBase() {}
|
||||
virtual ~EndgameBase() = default;
|
||||
virtual Color strong_side() const = 0;
|
||||
virtual T operator()(const Position&) const = 0;
|
||||
};
|
||||
|
||||
|
||||
template<EndgameType E, typename T = typename eg_fun<(E > SCALING_FUNCTIONS)>::type>
|
||||
template<EndgameType E, typename T = eg_type<E>>
|
||||
struct Endgame : public EndgameBase<T> {
|
||||
|
||||
explicit Endgame(Color c) : strongSide(c), weakSide(~c) {}
|
||||
@@ -99,23 +101,24 @@ private:
|
||||
|
||||
class Endgames {
|
||||
|
||||
typedef std::map<Key, EndgameBase<eg_fun<0>::type>*> M1;
|
||||
typedef std::map<Key, EndgameBase<eg_fun<1>::type>*> M2;
|
||||
template<typename T> using Map = std::map<Key, std::unique_ptr<EndgameBase<T>>>;
|
||||
|
||||
M1 m1;
|
||||
M2 m2;
|
||||
template<EndgameType E, typename T = eg_type<E>>
|
||||
void add(const std::string& code);
|
||||
|
||||
M1& map(M1::mapped_type) { return m1; }
|
||||
M2& map(M2::mapped_type) { return m2; }
|
||||
template<typename T>
|
||||
Map<T>& map() {
|
||||
return std::get<std::is_same<T, ScaleFactor>::value>(maps);
|
||||
}
|
||||
|
||||
template<EndgameType E> void add(const std::string& code);
|
||||
std::pair<Map<Value>, Map<ScaleFactor>> maps;
|
||||
|
||||
public:
|
||||
Endgames();
|
||||
~Endgames();
|
||||
|
||||
template<typename T> T probe(Key key, T& eg) {
|
||||
return eg = map(eg).count(key) ? map(eg)[key] : NULL;
|
||||
template<typename T>
|
||||
EndgameBase<T>* probe(Key key) {
|
||||
return map<T>().count(key) ? map<T>()[key].get() : nullptr;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
+528
-506
File diff suppressed because it is too large
Load Diff
+4
-3
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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,12 +29,12 @@ class Position;
|
||||
|
||||
namespace Eval {
|
||||
|
||||
const Value Tempo = Value(17); // Must be visible to search
|
||||
const Value Tempo = Value(20); // Must be visible to search
|
||||
|
||||
void init();
|
||||
Value evaluate(const Position& pos);
|
||||
std::string trace(const Position& pos);
|
||||
|
||||
template<bool DoTrace = false>
|
||||
Value evaluate(const Position& pos);
|
||||
}
|
||||
|
||||
#endif // #ifndef EVALUATE_H_INCLUDED
|
||||
|
||||
+7
-2
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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
|
||||
@@ -20,7 +21,6 @@
|
||||
#include <iostream>
|
||||
|
||||
#include "bitboard.h"
|
||||
#include "evaluate.h"
|
||||
#include "position.h"
|
||||
#include "search.h"
|
||||
#include "thread.h"
|
||||
@@ -28,16 +28,20 @@
|
||||
#include "uci.h"
|
||||
#include "syzygy/tbprobe.h"
|
||||
|
||||
namespace PSQT {
|
||||
void init();
|
||||
}
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
|
||||
std::cout << engine_info() << std::endl;
|
||||
|
||||
UCI::init(Options);
|
||||
PSQT::init();
|
||||
Bitboards::init();
|
||||
Position::init();
|
||||
Bitbases::init();
|
||||
Search::init();
|
||||
Eval::init();
|
||||
Pawns::init();
|
||||
Threads.init();
|
||||
Tablebases::init(Options["SyzygyPath"]);
|
||||
@@ -46,4 +50,5 @@ int main(int argc, char* argv[]) {
|
||||
UCI::loop(argc, argv);
|
||||
|
||||
Threads.exit();
|
||||
return 0;
|
||||
}
|
||||
|
||||
+44
-57
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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
|
||||
@@ -30,29 +31,26 @@ namespace {
|
||||
|
||||
// Polynomial material imbalance parameters
|
||||
|
||||
// pair pawn knight bishop rook queen
|
||||
const int Linear[6] = { 1852, -162, -1122, -183, 249, -154 };
|
||||
|
||||
const int QuadraticOurs[][PIECE_TYPE_NB] = {
|
||||
// OUR PIECES
|
||||
// pair pawn knight bishop rook queen
|
||||
{ 0 }, // Bishop pair
|
||||
{ 39, 2 }, // Pawn
|
||||
{ 35, 271, -4 }, // Knight OUR PIECES
|
||||
{ 0, 105, 4, 0 }, // Bishop
|
||||
{ -27, -2, 46, 100, -141 }, // Rook
|
||||
{-177, 25, 129, 142, -137, 0 } // Queen
|
||||
{1667 }, // Bishop pair
|
||||
{ 40, 2 }, // Pawn
|
||||
{ 32, 255, -3 }, // Knight OUR PIECES
|
||||
{ 0, 104, 4, 0 }, // Bishop
|
||||
{ -26, -2, 47, 105, -149 }, // Rook
|
||||
{-185, 24, 122, 137, -134, 0 } // Queen
|
||||
};
|
||||
|
||||
const int QuadraticTheirs[][PIECE_TYPE_NB] = {
|
||||
// THEIR PIECES
|
||||
// pair pawn knight bishop rook queen
|
||||
{ 0 }, // Bishop pair
|
||||
{ 37, 0 }, // Pawn
|
||||
{ 10, 62, 0 }, // Knight OUR PIECES
|
||||
{ 57, 64, 39, 0 }, // Bishop
|
||||
{ 50, 40, 23, -22, 0 }, // Rook
|
||||
{ 98, 105, -39, 141, 274, 0 } // Queen
|
||||
{ 36, 0 }, // Pawn
|
||||
{ 9, 63, 0 }, // Knight OUR PIECES
|
||||
{ 59, 65, 42, 0 }, // Bishop
|
||||
{ 46, 39, 24, -24, 0 }, // Rook
|
||||
{ 101, 100, -37, 141, 268, 0 } // Queen
|
||||
};
|
||||
|
||||
// Endgame evaluation and scaling functions are accessed directly and not through
|
||||
@@ -64,31 +62,28 @@ namespace {
|
||||
Endgame<KPsK> ScaleKPsK[] = { Endgame<KPsK>(WHITE), Endgame<KPsK>(BLACK) };
|
||||
Endgame<KPKP> ScaleKPKP[] = { Endgame<KPKP>(WHITE), Endgame<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 !more_than_one(pos.pieces(Them))
|
||||
&& pos.non_pawn_material(Us) >= RookValueMg;
|
||||
// Helper used to detect a given material distribution
|
||||
bool is_KXK(const Position& pos, Color us) {
|
||||
return !more_than_one(pos.pieces(~us))
|
||||
&& pos.non_pawn_material(us) >= RookValueMg;
|
||||
}
|
||||
|
||||
template<Color Us> bool is_KBPsKs(const Position& pos) {
|
||||
return pos.non_pawn_material(Us) == BishopValueMg
|
||||
&& pos.count<BISHOP>(Us) == 1
|
||||
&& pos.count<PAWN >(Us) >= 1;
|
||||
bool is_KBPsKs(const Position& pos, Color us) {
|
||||
return pos.non_pawn_material(us) == BishopValueMg
|
||||
&& pos.count<BISHOP>(us) == 1
|
||||
&& pos.count<PAWN >(us) >= 1;
|
||||
}
|
||||
|
||||
template<Color Us> bool is_KQKRPs(const Position& pos) {
|
||||
const Color Them = (Us == WHITE ? BLACK : WHITE);
|
||||
return !pos.count<PAWN>(Us)
|
||||
&& pos.non_pawn_material(Us) == QueenValueMg
|
||||
&& pos.count<QUEEN>(Us) == 1
|
||||
&& pos.count<ROOK>(Them) == 1
|
||||
&& pos.count<PAWN>(Them) >= 1;
|
||||
bool is_KQKRPs(const Position& pos, Color us) {
|
||||
return !pos.count<PAWN>(us)
|
||||
&& pos.non_pawn_material(us) == QueenValueMg
|
||||
&& pos.count<QUEEN>(us) == 1
|
||||
&& pos.count<ROOK>(~us) == 1
|
||||
&& pos.count<PAWN>(~us) >= 1;
|
||||
}
|
||||
|
||||
/// imbalance() calculates the imbalance by comparing the piece count of each
|
||||
/// piece type for both colors.
|
||||
|
||||
template<Color Us>
|
||||
int imbalance(const int pieceCount[][PIECE_TYPE_NB]) {
|
||||
|
||||
@@ -102,7 +97,7 @@ namespace {
|
||||
if (!pieceCount[Us][pt1])
|
||||
continue;
|
||||
|
||||
int v = Linear[pt1];
|
||||
int v = 0;
|
||||
|
||||
for (int pt2 = NO_PIECE_TYPE; pt2 <= pt1; ++pt2)
|
||||
v += QuadraticOurs[pt1][pt2] * pieceCount[Us][pt2]
|
||||
@@ -139,26 +134,21 @@ Entry* probe(const Position& pos) {
|
||||
// Let's look if we have a specialized evaluation function for this particular
|
||||
// material configuration. Firstly we look for a fixed configuration one, then
|
||||
// for a generic one if the previous search failed.
|
||||
if (pos.this_thread()->endgames.probe(key, e->evaluationFunction))
|
||||
if ((e->evaluationFunction = pos.this_thread()->endgames.probe<Value>(key)) != nullptr)
|
||||
return e;
|
||||
|
||||
if (is_KXK<WHITE>(pos))
|
||||
{
|
||||
e->evaluationFunction = &EvaluateKXK[WHITE];
|
||||
return e;
|
||||
}
|
||||
|
||||
if (is_KXK<BLACK>(pos))
|
||||
{
|
||||
e->evaluationFunction = &EvaluateKXK[BLACK];
|
||||
return e;
|
||||
}
|
||||
for (Color c = WHITE; c <= BLACK; ++c)
|
||||
if (is_KXK(pos, c))
|
||||
{
|
||||
e->evaluationFunction = &EvaluateKXK[c];
|
||||
return e;
|
||||
}
|
||||
|
||||
// OK, we didn't find any special evaluation function for the current material
|
||||
// configuration. Is there a suitable specialized scaling function?
|
||||
EndgameBase<ScaleFactor>* sf;
|
||||
|
||||
if (pos.this_thread()->endgames.probe(key, sf))
|
||||
if ((sf = pos.this_thread()->endgames.probe<ScaleFactor>(key)) != nullptr)
|
||||
{
|
||||
e->scalingFunction[sf->strong_side()] = sf; // Only strong color assigned
|
||||
return e;
|
||||
@@ -167,17 +157,14 @@ Entry* probe(const Position& pos) {
|
||||
// We didn't find any specialized scaling function, so fall back on generic
|
||||
// ones that refer to more than one material distribution. Note that in this
|
||||
// case we don't return after setting the function.
|
||||
if (is_KBPsKs<WHITE>(pos))
|
||||
e->scalingFunction[WHITE] = &ScaleKBPsK[WHITE];
|
||||
for (Color c = WHITE; c <= BLACK; ++c)
|
||||
{
|
||||
if (is_KBPsKs(pos, c))
|
||||
e->scalingFunction[c] = &ScaleKBPsK[c];
|
||||
|
||||
if (is_KBPsKs<BLACK>(pos))
|
||||
e->scalingFunction[BLACK] = &ScaleKBPsK[BLACK];
|
||||
|
||||
if (is_KQKRPs<WHITE>(pos))
|
||||
e->scalingFunction[WHITE] = &ScaleKQKRPs[WHITE];
|
||||
|
||||
else if (is_KQKRPs<BLACK>(pos))
|
||||
e->scalingFunction[BLACK] = &ScaleKQKRPs[BLACK];
|
||||
else if (is_KQKRPs(pos, c))
|
||||
e->scalingFunction[c] = &ScaleKQKRPs[c];
|
||||
}
|
||||
|
||||
Value npm_w = pos.non_pawn_material(WHITE);
|
||||
Value npm_b = pos.non_pawn_material(BLACK);
|
||||
@@ -210,11 +197,11 @@ Entry* probe(const Position& pos) {
|
||||
// drawish scale factor for cases such as KRKBP and KmmKm (except for KBBKN).
|
||||
if (!pos.count<PAWN>(WHITE) && npm_w - npm_b <= BishopValueMg)
|
||||
e->factor[WHITE] = uint8_t(npm_w < RookValueMg ? SCALE_FACTOR_DRAW :
|
||||
npm_b <= BishopValueMg ? 4 : 12);
|
||||
npm_b <= BishopValueMg ? 4 : 14);
|
||||
|
||||
if (!pos.count<PAWN>(BLACK) && npm_b - npm_w <= BishopValueMg)
|
||||
e->factor[BLACK] = uint8_t(npm_b < RookValueMg ? SCALE_FACTOR_DRAW :
|
||||
npm_w <= BishopValueMg ? 4 : 12);
|
||||
npm_w <= BishopValueMg ? 4 : 14);
|
||||
|
||||
if (pos.count<PAWN>(WHITE) == 1 && npm_w - npm_b <= BishopValueMg)
|
||||
e->factor[WHITE] = (uint8_t) SCALE_FACTOR_ONEPAWN;
|
||||
|
||||
+5
-4
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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
|
||||
@@ -40,7 +41,7 @@ struct Entry {
|
||||
|
||||
Score imbalance() const { return make_score(value, value); }
|
||||
Phase game_phase() const { return gamePhase; }
|
||||
bool specialized_eval_exists() const { return evaluationFunction != NULL; }
|
||||
bool specialized_eval_exists() const { return evaluationFunction != nullptr; }
|
||||
Value evaluate(const Position& pos) const { return (*evaluationFunction)(pos); }
|
||||
|
||||
// scale_factor takes a position and a color as input and returns a scale factor
|
||||
@@ -49,9 +50,9 @@ struct Entry {
|
||||
// the position. For instance, in KBP vs K endgames, the scaling function looks
|
||||
// for rook pawns and wrong-colored bishops.
|
||||
ScaleFactor scale_factor(const Position& pos, Color c) const {
|
||||
return !scalingFunction[c]
|
||||
|| (*scalingFunction[c])(pos) == SCALE_FACTOR_NONE ? ScaleFactor(factor[c])
|
||||
: (*scalingFunction[c])(pos);
|
||||
ScaleFactor sf = scalingFunction[c] ? (*scalingFunction[c])(pos)
|
||||
: SCALE_FACTOR_NONE;
|
||||
return sf != SCALE_FACTOR_NONE ? sf : ScaleFactor(factor[c]);
|
||||
}
|
||||
|
||||
Key key;
|
||||
|
||||
+23
-44
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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
|
||||
@@ -31,60 +32,56 @@ namespace {
|
||||
|
||||
/// Version number. If Version is left empty, then compile date in the format
|
||||
/// DD-MM-YY and show in engine_info.
|
||||
const string Version = "6";
|
||||
|
||||
/// Debug counters
|
||||
int64_t hits[2], means[2];
|
||||
const string Version = "8";
|
||||
|
||||
/// Our fancy logging facility. The trick here is to replace cin.rdbuf() and
|
||||
/// cout.rdbuf() with two Tie objects that tie cin and cout to a file stream. We
|
||||
/// can toggle the logging of std::cout and std:cin at runtime whilst preserving
|
||||
/// usual i/o functionality, all without changing a single line of code!
|
||||
/// usual I/O functionality, all without changing a single line of code!
|
||||
/// Idea from http://groups.google.com/group/comp.lang.c++/msg/1d941c0f26ea0d81
|
||||
|
||||
struct Tie: public streambuf { // MSVC requires splitted streambuf for cin and cout
|
||||
struct Tie: public streambuf { // MSVC requires split streambuf for cin and cout
|
||||
|
||||
Tie(streambuf* b, ofstream* f) : buf(b), file(f) {}
|
||||
Tie(streambuf* b, streambuf* l) : buf(b), logBuf(l) {}
|
||||
|
||||
int sync() { return file->rdbuf()->pubsync(), buf->pubsync(); }
|
||||
int sync() { return logBuf->pubsync(), buf->pubsync(); }
|
||||
int overflow(int c) { return log(buf->sputc((char)c), "<< "); }
|
||||
int underflow() { return buf->sgetc(); }
|
||||
int uflow() { return log(buf->sbumpc(), ">> "); }
|
||||
|
||||
streambuf* buf;
|
||||
ofstream* file;
|
||||
streambuf *buf, *logBuf;
|
||||
|
||||
int log(int c, const char* prefix) {
|
||||
|
||||
static int last = '\n';
|
||||
static int last = '\n'; // Single log file
|
||||
|
||||
if (last == '\n')
|
||||
file->rdbuf()->sputn(prefix, 3);
|
||||
logBuf->sputn(prefix, 3);
|
||||
|
||||
return last = file->rdbuf()->sputc((char)c);
|
||||
return last = logBuf->sputc((char)c);
|
||||
}
|
||||
};
|
||||
|
||||
class Logger {
|
||||
|
||||
Logger() : in(cin.rdbuf(), &file), out(cout.rdbuf(), &file) {}
|
||||
~Logger() { start(false); }
|
||||
Logger() : in(cin.rdbuf(), file.rdbuf()), out(cout.rdbuf(), file.rdbuf()) {}
|
||||
~Logger() { start(""); }
|
||||
|
||||
ofstream file;
|
||||
Tie in, out;
|
||||
|
||||
public:
|
||||
static void start(bool b) {
|
||||
static void start(const std::string& fname) {
|
||||
|
||||
static Logger l;
|
||||
|
||||
if (b && !l.file.is_open())
|
||||
if (!fname.empty() && !l.file.is_open())
|
||||
{
|
||||
l.file.open("io_log.txt", ifstream::out | ifstream::app);
|
||||
l.file.open(fname, ifstream::out);
|
||||
cin.rdbuf(&l.in);
|
||||
cout.rdbuf(&l.out);
|
||||
}
|
||||
else if (!b && l.file.is_open())
|
||||
else if (fname.empty() && l.file.is_open())
|
||||
{
|
||||
cout.rdbuf(l.out.buf);
|
||||
cin.rdbuf(l.in.buf);
|
||||
@@ -117,16 +114,17 @@ const string engine_info(bool to_uci) {
|
||||
ss << (Is64Bit ? " 64" : "")
|
||||
<< (HasPext ? " BMI2" : (HasPopCnt ? " POPCNT" : ""))
|
||||
<< (to_uci ? "\nid author ": " by ")
|
||||
<< "Tord Romstad, Marco Costalba and Joona Kiiski";
|
||||
<< "T. Romstad, M. Costalba, J. Kiiski, G. Linscott";
|
||||
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
|
||||
/// Debug functions used mainly to collect run-time statistics
|
||||
static int64_t hits[2], means[2];
|
||||
|
||||
void dbg_hit_on(bool b) { ++hits[0]; if (b) ++hits[1]; }
|
||||
void dbg_hit_on_c(bool c, bool b) { if (c) dbg_hit_on(b); }
|
||||
void dbg_hit_on(bool c, bool b) { if (c) dbg_hit_on(b); }
|
||||
void dbg_mean_of(int v) { ++means[0]; means[1] += v; }
|
||||
|
||||
void dbg_print() {
|
||||
@@ -159,26 +157,7 @@ std::ostream& operator<<(std::ostream& os, SyncCout sc) {
|
||||
|
||||
|
||||
/// Trampoline helper to avoid moving Logger to misc.h
|
||||
void start_logger(bool b) { Logger::start(b); }
|
||||
|
||||
|
||||
/// timed_wait() waits for msec milliseconds. It is mainly a helper to wrap
|
||||
/// the conversion from milliseconds to struct timespec, as used by pthreads.
|
||||
|
||||
void timed_wait(WaitCondition& sleepCond, Lock& sleepLock, int msec) {
|
||||
|
||||
#ifdef _WIN32
|
||||
int tm = msec;
|
||||
#else
|
||||
timespec ts, *tm = &ts;
|
||||
uint64_t ms = Time::now() + msec;
|
||||
|
||||
ts.tv_sec = ms / 1000;
|
||||
ts.tv_nsec = (ms % 1000) * 1000000LL;
|
||||
#endif
|
||||
|
||||
cond_timedwait(sleepCond, sleepLock, tm);
|
||||
}
|
||||
void start_logger(const std::string& fname) { Logger::start(fname); }
|
||||
|
||||
|
||||
/// prefetch() preloads the given address in L1/L2 cache. This is a non-blocking
|
||||
@@ -186,11 +165,11 @@ void timed_wait(WaitCondition& sleepCond, Lock& sleepLock, int msec) {
|
||||
/// which can be quite slow.
|
||||
#ifdef NO_PREFETCH
|
||||
|
||||
void prefetch(char*) {}
|
||||
void prefetch(void*) {}
|
||||
|
||||
#else
|
||||
|
||||
void prefetch(char* addr) {
|
||||
void prefetch(void* addr) {
|
||||
|
||||
# if defined(__INTEL_COMPILER)
|
||||
// This hack prevents prefetches from being optimized away by
|
||||
@@ -199,7 +178,7 @@ void prefetch(char* addr) {
|
||||
# endif
|
||||
|
||||
# if defined(__INTEL_COMPILER) || defined(_MSC_VER)
|
||||
_mm_prefetch(addr, _MM_HINT_T0);
|
||||
_mm_prefetch((char*)addr, _MM_HINT_T0);
|
||||
# else
|
||||
__builtin_prefetch(addr);
|
||||
# endif
|
||||
|
||||
+10
-10
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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
|
||||
@@ -21,6 +22,7 @@
|
||||
#define MISC_H_INCLUDED
|
||||
|
||||
#include <cassert>
|
||||
#include <chrono>
|
||||
#include <ostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
@@ -28,29 +30,27 @@
|
||||
#include "types.h"
|
||||
|
||||
const std::string engine_info(bool to_uci = false);
|
||||
void timed_wait(WaitCondition&, Lock&, int);
|
||||
void prefetch(char* addr);
|
||||
void start_logger(bool b);
|
||||
void prefetch(void* addr);
|
||||
void start_logger(const std::string& fname);
|
||||
|
||||
void dbg_hit_on(bool b);
|
||||
void dbg_hit_on_c(bool c, bool b);
|
||||
void dbg_hit_on(bool c, bool b);
|
||||
void dbg_mean_of(int v);
|
||||
void dbg_print();
|
||||
|
||||
typedef std::chrono::milliseconds::rep TimePoint; // A value in milliseconds
|
||||
|
||||
namespace Time {
|
||||
typedef int64_t point;
|
||||
inline point now() { return system_time_to_msec(); }
|
||||
inline TimePoint now() {
|
||||
return std::chrono::duration_cast<std::chrono::milliseconds>
|
||||
(std::chrono::steady_clock::now().time_since_epoch()).count();
|
||||
}
|
||||
|
||||
|
||||
template<class Entry, int Size>
|
||||
struct HashTable {
|
||||
HashTable() : table(Size, Entry()) {}
|
||||
Entry* operator[](Key key) { return &table[(uint32_t)key & (Size - 1)]; }
|
||||
|
||||
private:
|
||||
std::vector<Entry> table;
|
||||
std::vector<Entry> table = std::vector<Entry>(Size);
|
||||
};
|
||||
|
||||
|
||||
|
||||
+80
-78
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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 +26,7 @@
|
||||
namespace {
|
||||
|
||||
template<CastlingRight Cr, bool Checks, bool Chess960>
|
||||
ExtMove* generate_castling(const Position& pos, ExtMove* moveList, Color us, const CheckInfo* ci) {
|
||||
ExtMove* generate_castling(const Position& pos, ExtMove* moveList, Color us) {
|
||||
|
||||
static const bool KingSide = (Cr == WHITE_OO || Cr == BLACK_OO);
|
||||
|
||||
@@ -34,15 +35,15 @@ namespace {
|
||||
|
||||
// After castling, the rook and king final positions are the same in Chess960
|
||||
// as they would be in standard chess.
|
||||
Square kfrom = pos.king_square(us);
|
||||
Square kfrom = pos.square<KING>(us);
|
||||
Square rfrom = pos.castling_rook_square(Cr);
|
||||
Square kto = relative_square(us, KingSide ? SQ_G1 : SQ_C1);
|
||||
Bitboard enemies = pos.pieces(~us);
|
||||
|
||||
assert(!pos.checkers());
|
||||
|
||||
const Square K = Chess960 ? kto > kfrom ? DELTA_W : DELTA_E
|
||||
: KingSide ? DELTA_W : DELTA_E;
|
||||
const Square K = Chess960 ? kto > kfrom ? WEST : EAST
|
||||
: KingSide ? WEST : EAST;
|
||||
|
||||
for (Square s = kto; s != kfrom; s += K)
|
||||
if (pos.attackers_to(s) & enemies)
|
||||
@@ -56,52 +57,50 @@ namespace {
|
||||
|
||||
Move m = make<CASTLING>(kfrom, rfrom);
|
||||
|
||||
if (Checks && !pos.gives_check(m, *ci))
|
||||
if (Checks && !pos.gives_check(m))
|
||||
return moveList;
|
||||
|
||||
(moveList++)->move = m;
|
||||
|
||||
*moveList++ = m;
|
||||
return moveList;
|
||||
}
|
||||
|
||||
|
||||
template<GenType Type, Square Delta>
|
||||
inline ExtMove* make_promotions(ExtMove* moveList, Square to, const CheckInfo* ci) {
|
||||
template<GenType Type, Square D>
|
||||
ExtMove* make_promotions(ExtMove* moveList, Square to, Square ksq) {
|
||||
|
||||
if (Type == CAPTURES || Type == EVASIONS || Type == NON_EVASIONS)
|
||||
(moveList++)->move = make<PROMOTION>(to - Delta, to, QUEEN);
|
||||
*moveList++ = make<PROMOTION>(to - D, to, QUEEN);
|
||||
|
||||
if (Type == QUIETS || Type == EVASIONS || Type == NON_EVASIONS)
|
||||
{
|
||||
(moveList++)->move = make<PROMOTION>(to - Delta, to, ROOK);
|
||||
(moveList++)->move = make<PROMOTION>(to - Delta, to, BISHOP);
|
||||
(moveList++)->move = make<PROMOTION>(to - Delta, to, KNIGHT);
|
||||
*moveList++ = make<PROMOTION>(to - D, to, ROOK);
|
||||
*moveList++ = make<PROMOTION>(to - D, to, BISHOP);
|
||||
*moveList++ = make<PROMOTION>(to - D, to, KNIGHT);
|
||||
}
|
||||
|
||||
// Knight promotion is the only promotion that can give a direct check
|
||||
// that's not already included in the queen promotion.
|
||||
if (Type == QUIET_CHECKS && (StepAttacksBB[W_KNIGHT][to] & ci->ksq))
|
||||
(moveList++)->move = make<PROMOTION>(to - Delta, to, KNIGHT);
|
||||
if (Type == QUIET_CHECKS && (StepAttacksBB[W_KNIGHT][to] & ksq))
|
||||
*moveList++ = make<PROMOTION>(to - D, to, KNIGHT);
|
||||
else
|
||||
(void)ci; // Silence a warning under MSVC
|
||||
(void)ksq; // Silence a warning under MSVC
|
||||
|
||||
return moveList;
|
||||
}
|
||||
|
||||
|
||||
template<Color Us, GenType Type>
|
||||
ExtMove* generate_pawn_moves(const Position& pos, ExtMove* moveList,
|
||||
Bitboard target, const CheckInfo* ci) {
|
||||
ExtMove* generate_pawn_moves(const Position& pos, ExtMove* moveList, Bitboard target) {
|
||||
|
||||
// Compute our parametrized parameters at compile time, named according to
|
||||
// the point of view of white side.
|
||||
const Color Them = (Us == WHITE ? BLACK : WHITE);
|
||||
const Bitboard TRank8BB = (Us == WHITE ? Rank8BB : Rank1BB);
|
||||
const Bitboard TRank7BB = (Us == WHITE ? Rank7BB : Rank2BB);
|
||||
const Bitboard TRank3BB = (Us == WHITE ? Rank3BB : Rank6BB);
|
||||
const Square Up = (Us == WHITE ? DELTA_N : DELTA_S);
|
||||
const Square Right = (Us == WHITE ? DELTA_NE : DELTA_SW);
|
||||
const Square Left = (Us == WHITE ? DELTA_NW : DELTA_SE);
|
||||
const Color Them = (Us == WHITE ? BLACK : WHITE);
|
||||
const Bitboard TRank8BB = (Us == WHITE ? Rank8BB : Rank1BB);
|
||||
const Bitboard TRank7BB = (Us == WHITE ? Rank7BB : Rank2BB);
|
||||
const Bitboard TRank3BB = (Us == WHITE ? Rank3BB : Rank6BB);
|
||||
const Square Up = (Us == WHITE ? NORTH : SOUTH);
|
||||
const Square Right = (Us == WHITE ? NORTH_EAST : SOUTH_WEST);
|
||||
const Square Left = (Us == WHITE ? NORTH_WEST : SOUTH_EAST);
|
||||
|
||||
Bitboard emptySquares;
|
||||
|
||||
@@ -116,8 +115,8 @@ namespace {
|
||||
{
|
||||
emptySquares = (Type == QUIETS || Type == QUIET_CHECKS ? target : ~pos.pieces());
|
||||
|
||||
Bitboard b1 = shift_bb<Up>(pawnsNotOn7) & emptySquares;
|
||||
Bitboard b2 = shift_bb<Up>(b1 & TRank3BB) & emptySquares;
|
||||
Bitboard b1 = shift<Up>(pawnsNotOn7) & emptySquares;
|
||||
Bitboard b2 = shift<Up>(b1 & TRank3BB) & emptySquares;
|
||||
|
||||
if (Type == EVASIONS) // Consider only blocking squares
|
||||
{
|
||||
@@ -127,17 +126,20 @@ namespace {
|
||||
|
||||
if (Type == QUIET_CHECKS)
|
||||
{
|
||||
b1 &= pos.attacks_from<PAWN>(ci->ksq, Them);
|
||||
b2 &= pos.attacks_from<PAWN>(ci->ksq, Them);
|
||||
Square ksq = pos.square<KING>(Them);
|
||||
|
||||
b1 &= pos.attacks_from<PAWN>(ksq, Them);
|
||||
b2 &= pos.attacks_from<PAWN>(ksq, Them);
|
||||
|
||||
// Add pawn pushes which give discovered check. This is possible only
|
||||
// if the pawn is not on the same file as the enemy king, because we
|
||||
// don't generate captures. Note that a possible discovery check
|
||||
// promotion has been already generated amongst the captures.
|
||||
if (pawnsNotOn7 & ci->dcCandidates)
|
||||
Bitboard dcCandidates = pos.discovered_check_candidates();
|
||||
if (pawnsNotOn7 & dcCandidates)
|
||||
{
|
||||
Bitboard dc1 = shift_bb<Up>(pawnsNotOn7 & ci->dcCandidates) & emptySquares & ~file_bb(ci->ksq);
|
||||
Bitboard dc2 = shift_bb<Up>(dc1 & TRank3BB) & emptySquares;
|
||||
Bitboard dc1 = shift<Up>(pawnsNotOn7 & dcCandidates) & emptySquares & ~file_bb(ksq);
|
||||
Bitboard dc2 = shift<Up>(dc1 & TRank3BB) & emptySquares;
|
||||
|
||||
b1 |= dc1;
|
||||
b2 |= dc2;
|
||||
@@ -147,13 +149,13 @@ namespace {
|
||||
while (b1)
|
||||
{
|
||||
Square to = pop_lsb(&b1);
|
||||
(moveList++)->move = make_move(to - Up, to);
|
||||
*moveList++ = make_move(to - Up, to);
|
||||
}
|
||||
|
||||
while (b2)
|
||||
{
|
||||
Square to = pop_lsb(&b2);
|
||||
(moveList++)->move = make_move(to - Up - Up, to);
|
||||
*moveList++ = make_move(to - Up - Up, to);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,36 +168,38 @@ namespace {
|
||||
if (Type == EVASIONS)
|
||||
emptySquares &= target;
|
||||
|
||||
Bitboard b1 = shift_bb<Right>(pawnsOn7) & enemies;
|
||||
Bitboard b2 = shift_bb<Left >(pawnsOn7) & enemies;
|
||||
Bitboard b3 = shift_bb<Up >(pawnsOn7) & emptySquares;
|
||||
Bitboard b1 = shift<Right>(pawnsOn7) & enemies;
|
||||
Bitboard b2 = shift<Left >(pawnsOn7) & enemies;
|
||||
Bitboard b3 = shift<Up >(pawnsOn7) & emptySquares;
|
||||
|
||||
Square ksq = pos.square<KING>(Them);
|
||||
|
||||
while (b1)
|
||||
moveList = make_promotions<Type, Right>(moveList, pop_lsb(&b1), ci);
|
||||
moveList = make_promotions<Type, Right>(moveList, pop_lsb(&b1), ksq);
|
||||
|
||||
while (b2)
|
||||
moveList = make_promotions<Type, Left >(moveList, pop_lsb(&b2), ci);
|
||||
moveList = make_promotions<Type, Left >(moveList, pop_lsb(&b2), ksq);
|
||||
|
||||
while (b3)
|
||||
moveList = make_promotions<Type, Up >(moveList, pop_lsb(&b3), ci);
|
||||
moveList = make_promotions<Type, Up >(moveList, pop_lsb(&b3), ksq);
|
||||
}
|
||||
|
||||
// Standard and en-passant captures
|
||||
if (Type == CAPTURES || Type == EVASIONS || Type == NON_EVASIONS)
|
||||
{
|
||||
Bitboard b1 = shift_bb<Right>(pawnsNotOn7) & enemies;
|
||||
Bitboard b2 = shift_bb<Left >(pawnsNotOn7) & enemies;
|
||||
Bitboard b1 = shift<Right>(pawnsNotOn7) & enemies;
|
||||
Bitboard b2 = shift<Left >(pawnsNotOn7) & enemies;
|
||||
|
||||
while (b1)
|
||||
{
|
||||
Square to = pop_lsb(&b1);
|
||||
(moveList++)->move = make_move(to - Right, to);
|
||||
*moveList++ = make_move(to - Right, to);
|
||||
}
|
||||
|
||||
while (b2)
|
||||
{
|
||||
Square to = pop_lsb(&b2);
|
||||
(moveList++)->move = make_move(to - Left, to);
|
||||
*moveList++ = make_move(to - Left, to);
|
||||
}
|
||||
|
||||
if (pos.ep_square() != SQ_NONE)
|
||||
@@ -213,7 +217,7 @@ namespace {
|
||||
assert(b1);
|
||||
|
||||
while (b1)
|
||||
(moveList++)->move = make<ENPASSANT>(pop_lsb(&b1), pos.ep_square());
|
||||
*moveList++ = make<ENPASSANT>(pop_lsb(&b1), pos.ep_square());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -221,70 +225,69 @@ namespace {
|
||||
}
|
||||
|
||||
|
||||
template<PieceType Pt, bool Checks> FORCE_INLINE
|
||||
template<PieceType Pt, bool Checks>
|
||||
ExtMove* generate_moves(const Position& pos, ExtMove* moveList, Color us,
|
||||
Bitboard target, const CheckInfo* ci) {
|
||||
Bitboard target) {
|
||||
|
||||
assert(Pt != KING && Pt != PAWN);
|
||||
|
||||
const Square* pl = pos.list<Pt>(us);
|
||||
const Square* pl = pos.squares<Pt>(us);
|
||||
|
||||
for (Square from = *pl; from != SQ_NONE; from = *++pl)
|
||||
{
|
||||
if (Checks)
|
||||
{
|
||||
if ( (Pt == BISHOP || Pt == ROOK || Pt == QUEEN)
|
||||
&& !(PseudoAttacks[Pt][from] & target & ci->checkSq[Pt]))
|
||||
&& !(PseudoAttacks[Pt][from] & target & pos.check_squares(Pt)))
|
||||
continue;
|
||||
|
||||
if (ci->dcCandidates && (ci->dcCandidates & from))
|
||||
if (pos.discovered_check_candidates() & from)
|
||||
continue;
|
||||
}
|
||||
|
||||
Bitboard b = pos.attacks_from<Pt>(from) & target;
|
||||
|
||||
if (Checks)
|
||||
b &= ci->checkSq[Pt];
|
||||
b &= pos.check_squares(Pt);
|
||||
|
||||
while (b)
|
||||
(moveList++)->move = make_move(from, pop_lsb(&b));
|
||||
*moveList++ = make_move(from, pop_lsb(&b));
|
||||
}
|
||||
|
||||
return moveList;
|
||||
}
|
||||
|
||||
|
||||
template<Color Us, GenType Type> FORCE_INLINE
|
||||
ExtMove* generate_all(const Position& pos, ExtMove* moveList, Bitboard target,
|
||||
const CheckInfo* ci = NULL) {
|
||||
template<Color Us, GenType Type>
|
||||
ExtMove* generate_all(const Position& pos, ExtMove* moveList, Bitboard target) {
|
||||
|
||||
const bool Checks = Type == QUIET_CHECKS;
|
||||
|
||||
moveList = generate_pawn_moves<Us, Type>(pos, moveList, target, ci);
|
||||
moveList = generate_moves<KNIGHT, Checks>(pos, moveList, Us, target, ci);
|
||||
moveList = generate_moves<BISHOP, Checks>(pos, moveList, Us, target, ci);
|
||||
moveList = generate_moves< ROOK, Checks>(pos, moveList, Us, target, ci);
|
||||
moveList = generate_moves< QUEEN, Checks>(pos, moveList, Us, target, ci);
|
||||
moveList = generate_pawn_moves<Us, Type>(pos, moveList, target);
|
||||
moveList = generate_moves<KNIGHT, Checks>(pos, moveList, Us, target);
|
||||
moveList = generate_moves<BISHOP, Checks>(pos, moveList, Us, target);
|
||||
moveList = generate_moves< ROOK, Checks>(pos, moveList, Us, target);
|
||||
moveList = generate_moves< QUEEN, Checks>(pos, moveList, Us, target);
|
||||
|
||||
if (Type != QUIET_CHECKS && Type != EVASIONS)
|
||||
{
|
||||
Square ksq = pos.king_square(Us);
|
||||
Square ksq = pos.square<KING>(Us);
|
||||
Bitboard b = pos.attacks_from<KING>(ksq) & target;
|
||||
while (b)
|
||||
(moveList++)->move = make_move(ksq, pop_lsb(&b));
|
||||
*moveList++ = make_move(ksq, pop_lsb(&b));
|
||||
}
|
||||
|
||||
if (Type != CAPTURES && Type != EVASIONS && pos.can_castle(Us))
|
||||
{
|
||||
if (pos.is_chess960())
|
||||
{
|
||||
moveList = generate_castling<MakeCastling<Us, KING_SIDE>::right, Checks, true>(pos, moveList, Us, ci);
|
||||
moveList = generate_castling<MakeCastling<Us, QUEEN_SIDE>::right, Checks, true>(pos, moveList, Us, ci);
|
||||
moveList = generate_castling<MakeCastling<Us, KING_SIDE>::right, Checks, true>(pos, moveList, Us);
|
||||
moveList = generate_castling<MakeCastling<Us, QUEEN_SIDE>::right, Checks, true>(pos, moveList, Us);
|
||||
}
|
||||
else
|
||||
{
|
||||
moveList = generate_castling<MakeCastling<Us, KING_SIDE>::right, Checks, false>(pos, moveList, Us, ci);
|
||||
moveList = generate_castling<MakeCastling<Us, QUEEN_SIDE>::right, Checks, false>(pos, moveList, Us, ci);
|
||||
moveList = generate_castling<MakeCastling<Us, KING_SIDE>::right, Checks, false>(pos, moveList, Us);
|
||||
moveList = generate_castling<MakeCastling<Us, QUEEN_SIDE>::right, Checks, false>(pos, moveList, Us);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -333,8 +336,7 @@ ExtMove* generate<QUIET_CHECKS>(const Position& pos, ExtMove* moveList) {
|
||||
assert(!pos.checkers());
|
||||
|
||||
Color us = pos.side_to_move();
|
||||
CheckInfo ci(pos);
|
||||
Bitboard dc = ci.dcCandidates;
|
||||
Bitboard dc = pos.discovered_check_candidates();
|
||||
|
||||
while (dc)
|
||||
{
|
||||
@@ -347,14 +349,14 @@ ExtMove* generate<QUIET_CHECKS>(const Position& pos, ExtMove* moveList) {
|
||||
Bitboard b = pos.attacks_from(Piece(pt), from) & ~pos.pieces();
|
||||
|
||||
if (pt == KING)
|
||||
b &= ~PseudoAttacks[QUEEN][ci.ksq];
|
||||
b &= ~PseudoAttacks[QUEEN][pos.square<KING>(~us)];
|
||||
|
||||
while (b)
|
||||
(moveList++)->move = make_move(from, pop_lsb(&b));
|
||||
*moveList++ = make_move(from, pop_lsb(&b));
|
||||
}
|
||||
|
||||
return us == WHITE ? generate_all<WHITE, QUIET_CHECKS>(pos, moveList, ~pos.pieces(), &ci)
|
||||
: generate_all<BLACK, QUIET_CHECKS>(pos, moveList, ~pos.pieces(), &ci);
|
||||
return us == WHITE ? generate_all<WHITE, QUIET_CHECKS>(pos, moveList, ~pos.pieces())
|
||||
: generate_all<BLACK, QUIET_CHECKS>(pos, moveList, ~pos.pieces());
|
||||
}
|
||||
|
||||
|
||||
@@ -366,7 +368,7 @@ ExtMove* generate<EVASIONS>(const Position& pos, ExtMove* moveList) {
|
||||
assert(pos.checkers());
|
||||
|
||||
Color us = pos.side_to_move();
|
||||
Square ksq = pos.king_square(us);
|
||||
Square ksq = pos.square<KING>(us);
|
||||
Bitboard sliderAttacks = 0;
|
||||
Bitboard sliders = pos.checkers() & ~pos.pieces(KNIGHT, PAWN);
|
||||
|
||||
@@ -382,7 +384,7 @@ ExtMove* generate<EVASIONS>(const Position& pos, ExtMove* moveList) {
|
||||
// Generate evasions for king, capture and non capture moves
|
||||
Bitboard b = pos.attacks_from<KING>(ksq) & ~pos.pieces(us) & ~sliderAttacks;
|
||||
while (b)
|
||||
(moveList++)->move = make_move(ksq, pop_lsb(&b));
|
||||
*moveList++ = make_move(ksq, pop_lsb(&b));
|
||||
|
||||
if (more_than_one(pos.checkers()))
|
||||
return moveList; // Double check, only a king move can save the day
|
||||
@@ -402,15 +404,15 @@ template<>
|
||||
ExtMove* generate<LEGAL>(const Position& pos, ExtMove* moveList) {
|
||||
|
||||
Bitboard pinned = pos.pinned_pieces(pos.side_to_move());
|
||||
Square ksq = pos.king_square(pos.side_to_move());
|
||||
Square ksq = pos.square<KING>(pos.side_to_move());
|
||||
ExtMove* cur = moveList;
|
||||
|
||||
moveList = pos.checkers() ? generate<EVASIONS >(pos, moveList)
|
||||
: generate<NON_EVASIONS>(pos, moveList);
|
||||
while (cur != moveList)
|
||||
if ( (pinned || from_sq(cur->move) == ksq || type_of(cur->move) == ENPASSANT)
|
||||
&& !pos.legal(cur->move, pinned))
|
||||
cur->move = (--moveList)->move;
|
||||
if ( (pinned || from_sq(*cur) == ksq || type_of(*cur) == ENPASSANT)
|
||||
&& !pos.legal(*cur))
|
||||
*cur = (--moveList)->move;
|
||||
else
|
||||
++cur;
|
||||
|
||||
|
||||
+10
-7
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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,6 +37,9 @@ enum GenType {
|
||||
struct ExtMove {
|
||||
Move move;
|
||||
Value value;
|
||||
|
||||
operator Move() const { return move; }
|
||||
void operator=(Move m) { move = m; }
|
||||
};
|
||||
|
||||
inline bool operator<(const ExtMove& f, const ExtMove& s) {
|
||||
@@ -50,18 +54,17 @@ ExtMove* generate(const Position& pos, ExtMove* moveList);
|
||||
template<GenType T>
|
||||
struct MoveList {
|
||||
|
||||
explicit MoveList(const Position& pos) : cur(moveList), last(generate<T>(pos, moveList)) { last->move = MOVE_NONE; }
|
||||
void operator++() { ++cur; }
|
||||
Move operator*() const { return cur->move; }
|
||||
explicit MoveList(const Position& pos) : last(generate<T>(pos, moveList)) {}
|
||||
const ExtMove* begin() const { return moveList; }
|
||||
const ExtMove* end() const { return last; }
|
||||
size_t size() const { return last - moveList; }
|
||||
bool contains(Move m) const {
|
||||
for (const ExtMove* it(moveList); it != last; ++it) if (it->move == m) return true;
|
||||
bool contains(Move move) const {
|
||||
for (const auto& m : *this) if (m == move) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private:
|
||||
ExtMove moveList[MAX_MOVES];
|
||||
ExtMove *cur, *last;
|
||||
ExtMove moveList[MAX_MOVES], *last;
|
||||
};
|
||||
|
||||
#endif // #ifndef MOVEGEN_H_INCLUDED
|
||||
|
||||
+215
-250
@@ -2,13 +2,13 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
|
||||
Stockfish is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
@@ -26,16 +26,15 @@
|
||||
namespace {
|
||||
|
||||
enum Stages {
|
||||
MAIN_SEARCH, CAPTURES_S1, KILLERS_S1, QUIETS_1_S1, QUIETS_2_S1, BAD_CAPTURES_S1,
|
||||
EVASION, EVASIONS_S2,
|
||||
QSEARCH_0, CAPTURES_S3, QUIET_CHECKS_S3,
|
||||
QSEARCH_1, CAPTURES_S4,
|
||||
PROBCUT, CAPTURES_S5,
|
||||
RECAPTURE, CAPTURES_S6,
|
||||
STOP
|
||||
MAIN_SEARCH, CAPTURES_INIT, GOOD_CAPTURES, KILLERS, COUNTERMOVE, QUIET_INIT, QUIET, BAD_CAPTURES,
|
||||
EVASION, EVASIONS_INIT, ALL_EVASIONS,
|
||||
PROBCUT, PROBCUT_INIT, PROBCUT_CAPTURES,
|
||||
QSEARCH_WITH_CHECKS, QCAPTURES_1_INIT, QCAPTURES_1, QCHECKS,
|
||||
QSEARCH_NO_CHECKS, QCAPTURES_2_INIT, QCAPTURES_2,
|
||||
QSEARCH_RECAPTURES, QRECAPTURES
|
||||
};
|
||||
|
||||
// Our insertion sort, which is guaranteed (and also needed) to be stable
|
||||
// Our insertion sort, which is guaranteed to be stable, as it should be
|
||||
void insertion_sort(ExtMove* begin, ExtMove* end)
|
||||
{
|
||||
ExtMove tmp, *p, *q;
|
||||
@@ -49,50 +48,39 @@ namespace {
|
||||
}
|
||||
}
|
||||
|
||||
// Unary predicate used by std::partition to split positive values from remaining
|
||||
// ones so as to sort the two sets separately, with the second sort delayed.
|
||||
inline bool has_positive_value(const ExtMove& move) { return move.value > VALUE_ZERO; }
|
||||
|
||||
// Picks the best move in the range (begin, end) and moves it to the front.
|
||||
// It's faster than sorting all the moves in advance when there are few
|
||||
// moves e.g. possible captures.
|
||||
inline ExtMove* pick_best(ExtMove* begin, ExtMove* end)
|
||||
// pick_best() finds the best move in the range (begin, end) and moves it to
|
||||
// the front. It's faster than sorting all the moves in advance when there
|
||||
// are few moves, e.g., the possible captures.
|
||||
Move pick_best(ExtMove* begin, ExtMove* end)
|
||||
{
|
||||
std::swap(*begin, *std::max_element(begin, end));
|
||||
return begin;
|
||||
return *begin;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
|
||||
/// Constructors of the MovePicker class. As arguments we pass information
|
||||
/// to help it to return the (presumably) good moves first, to decide which
|
||||
/// moves to return (in the quiescence search, for instance, we only want to
|
||||
/// search captures, promotions and some checks) and how important good move
|
||||
/// search captures, promotions, and some checks) and how important good move
|
||||
/// ordering is at the current node.
|
||||
|
||||
MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const HistoryStats& h,
|
||||
Move* cm, Move* fm, Search::Stack* s) : pos(p), history(h), depth(d) {
|
||||
MovePicker::MovePicker(const Position& p, Move ttm, Depth d, Search::Stack* s)
|
||||
: pos(p), ss(s), depth(d) {
|
||||
|
||||
assert(d > DEPTH_ZERO);
|
||||
|
||||
cur = end = moves;
|
||||
endBadCaptures = moves + MAX_MOVES - 1;
|
||||
countermoves = cm;
|
||||
followupmoves = fm;
|
||||
ss = s;
|
||||
Square prevSq = to_sq((ss-1)->currentMove);
|
||||
countermove = pos.this_thread()->counterMoves[pos.piece_on(prevSq)][prevSq];
|
||||
|
||||
if (pos.checkers())
|
||||
stage = EVASION;
|
||||
|
||||
else
|
||||
stage = MAIN_SEARCH;
|
||||
|
||||
ttMove = (ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE);
|
||||
end += (ttMove != MOVE_NONE);
|
||||
stage = pos.checkers() ? EVASION : MAIN_SEARCH;
|
||||
ttMove = ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE;
|
||||
stage += (ttMove == MOVE_NONE);
|
||||
}
|
||||
|
||||
MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const HistoryStats& h,
|
||||
Square s) : pos(p), history(h), cur(moves), end(moves) {
|
||||
MovePicker::MovePicker(const Position& p, Move ttm, Depth d, Square s)
|
||||
: pos(p) {
|
||||
|
||||
assert(d <= DEPTH_ZERO);
|
||||
|
||||
@@ -100,191 +88,88 @@ MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const HistoryStats&
|
||||
stage = EVASION;
|
||||
|
||||
else if (d > DEPTH_QS_NO_CHECKS)
|
||||
stage = QSEARCH_0;
|
||||
stage = QSEARCH_WITH_CHECKS;
|
||||
|
||||
else if (d > DEPTH_QS_RECAPTURES)
|
||||
stage = QSEARCH_1;
|
||||
stage = QSEARCH_NO_CHECKS;
|
||||
|
||||
else
|
||||
{
|
||||
stage = RECAPTURE;
|
||||
stage = QSEARCH_RECAPTURES;
|
||||
recaptureSquare = s;
|
||||
ttm = MOVE_NONE;
|
||||
return;
|
||||
}
|
||||
|
||||
ttMove = (ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE);
|
||||
end += (ttMove != MOVE_NONE);
|
||||
ttMove = ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE;
|
||||
stage += (ttMove == MOVE_NONE);
|
||||
}
|
||||
|
||||
MovePicker::MovePicker(const Position& p, Move ttm, const HistoryStats& h, PieceType pt)
|
||||
: pos(p), history(h), cur(moves), end(moves) {
|
||||
MovePicker::MovePicker(const Position& p, Move ttm, Value th)
|
||||
: pos(p), threshold(th) {
|
||||
|
||||
assert(!pos.checkers());
|
||||
|
||||
stage = PROBCUT;
|
||||
|
||||
// In ProbCut we generate only captures that are better than the parent's
|
||||
// captured piece.
|
||||
captureThreshold = PieceValue[MG][pt];
|
||||
ttMove = (ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE);
|
||||
// In ProbCut we generate captures with SEE higher than the given threshold
|
||||
ttMove = ttm
|
||||
&& pos.pseudo_legal(ttm)
|
||||
&& pos.capture(ttm)
|
||||
&& pos.see_ge(ttm, threshold + 1)? ttm : MOVE_NONE;
|
||||
|
||||
if (ttMove && (!pos.capture(ttMove) || pos.see(ttMove) <= captureThreshold))
|
||||
ttMove = MOVE_NONE;
|
||||
|
||||
end += (ttMove != MOVE_NONE);
|
||||
stage += (ttMove == MOVE_NONE);
|
||||
}
|
||||
|
||||
|
||||
/// score() assign a numerical value to each move in a move list. The moves with
|
||||
/// score() assigns a numerical value to each move in a move list. The moves with
|
||||
/// highest values will be picked first.
|
||||
template<>
|
||||
void MovePicker::score<CAPTURES>() {
|
||||
// Winning and equal captures in the main search are ordered by MVV/LVA.
|
||||
// Suprisingly, this appears to perform slightly better than SEE based
|
||||
// move ordering. The reason is probably that in a position with a winning
|
||||
// capture, capturing a more valuable (but sufficiently defended) piece
|
||||
// first usually doesn't hurt. The opponent will have to recapture, and
|
||||
// the hanging piece will still be hanging (except in the unusual cases
|
||||
// where it is possible to recapture with the hanging piece). Exchanging
|
||||
// big pieces before capturing a hanging piece probably helps to reduce
|
||||
// the subtree size.
|
||||
// In main search we want to push captures with negative SEE values to the
|
||||
// Winning and equal captures in the main search are ordered by MVV, preferring
|
||||
// captures near our home rank. Surprisingly, this appears to perform slightly
|
||||
// better than SEE-based move ordering: exchanging big pieces before capturing
|
||||
// a hanging piece probably helps to reduce the subtree size.
|
||||
// In the main search we want to push captures with negative SEE values to the
|
||||
// badCaptures[] array, but instead of doing it now we delay until the move
|
||||
// has been picked up in pick_move_from_list(). This way we save some SEE
|
||||
// calls in case we get a cutoff.
|
||||
Move m;
|
||||
|
||||
for (ExtMove* it = moves; it != end; ++it)
|
||||
{
|
||||
m = it->move;
|
||||
it->value = PieceValue[MG][pos.piece_on(to_sq(m))]
|
||||
- Value(type_of(pos.moved_piece(m)));
|
||||
|
||||
if (type_of(m) == ENPASSANT)
|
||||
it->value += PieceValue[MG][PAWN];
|
||||
|
||||
else if (type_of(m) == PROMOTION)
|
||||
it->value += PieceValue[MG][promotion_type(m)] - PieceValue[MG][PAWN];
|
||||
}
|
||||
// has been picked up, saving some SEE calls in case we get a cutoff.
|
||||
for (auto& m : *this)
|
||||
m.value = PieceValue[MG][pos.piece_on(to_sq(m))]
|
||||
- Value(200 * relative_rank(pos.side_to_move(), to_sq(m)));
|
||||
}
|
||||
|
||||
template<>
|
||||
void MovePicker::score<QUIETS>() {
|
||||
|
||||
Move m;
|
||||
const HistoryStats& history = pos.this_thread()->history;
|
||||
const FromToStats& fromTo = pos.this_thread()->fromTo;
|
||||
|
||||
for (ExtMove* it = moves; it != end; ++it)
|
||||
{
|
||||
m = it->move;
|
||||
it->value = history[pos.moved_piece(m)][to_sq(m)];
|
||||
}
|
||||
const CounterMoveStats* cm = (ss-1)->counterMoves;
|
||||
const CounterMoveStats* fm = (ss-2)->counterMoves;
|
||||
const CounterMoveStats* f2 = (ss-4)->counterMoves;
|
||||
|
||||
Color c = pos.side_to_move();
|
||||
|
||||
for (auto& m : *this)
|
||||
m.value = history[pos.moved_piece(m)][to_sq(m)]
|
||||
+ (cm ? (*cm)[pos.moved_piece(m)][to_sq(m)] : VALUE_ZERO)
|
||||
+ (fm ? (*fm)[pos.moved_piece(m)][to_sq(m)] : VALUE_ZERO)
|
||||
+ (f2 ? (*f2)[pos.moved_piece(m)][to_sq(m)] : VALUE_ZERO)
|
||||
+ fromTo.get(c, m);
|
||||
}
|
||||
|
||||
template<>
|
||||
void MovePicker::score<EVASIONS>() {
|
||||
// Try good captures ordered by MVV/LVA, then non-captures if destination square
|
||||
// is not under attack, ordered by history value, then bad-captures and quiet
|
||||
// moves with a negative SEE. This last group is ordered by the SEE value.
|
||||
Move m;
|
||||
Value see;
|
||||
// Try captures ordered by MVV/LVA, then non-captures ordered by history value
|
||||
const HistoryStats& history = pos.this_thread()->history;
|
||||
const FromToStats& fromTo = pos.this_thread()->fromTo;
|
||||
Color c = pos.side_to_move();
|
||||
|
||||
for (ExtMove* it = moves; it != end; ++it)
|
||||
{
|
||||
m = it->move;
|
||||
if ((see = pos.see_sign(m)) < VALUE_ZERO)
|
||||
it->value = see - HistoryStats::Max; // At the bottom
|
||||
|
||||
else if (pos.capture(m))
|
||||
it->value = PieceValue[MG][pos.piece_on(to_sq(m))]
|
||||
- Value(type_of(pos.moved_piece(m))) + HistoryStats::Max;
|
||||
for (auto& m : *this)
|
||||
if (pos.capture(m))
|
||||
m.value = PieceValue[MG][pos.piece_on(to_sq(m))]
|
||||
- Value(type_of(pos.moved_piece(m))) + HistoryStats::Max;
|
||||
else
|
||||
it->value = history[pos.moved_piece(m)][to_sq(m)];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// generate_next_stage() generates, scores and sorts the next bunch of moves,
|
||||
/// when there are no more moves to try for the current stage.
|
||||
|
||||
void MovePicker::generate_next_stage() {
|
||||
|
||||
cur = moves;
|
||||
|
||||
switch (++stage) {
|
||||
|
||||
case CAPTURES_S1: case CAPTURES_S3: case CAPTURES_S4: case CAPTURES_S5: case CAPTURES_S6:
|
||||
end = generate<CAPTURES>(pos, moves);
|
||||
score<CAPTURES>();
|
||||
return;
|
||||
|
||||
case KILLERS_S1:
|
||||
cur = killers;
|
||||
end = cur + 2;
|
||||
|
||||
killers[0].move = ss->killers[0];
|
||||
killers[1].move = ss->killers[1];
|
||||
killers[2].move = killers[3].move = MOVE_NONE;
|
||||
killers[4].move = killers[5].move = MOVE_NONE;
|
||||
|
||||
// Please note that following code is racy and could yield to rare (less
|
||||
// than 1 out of a million) duplicated entries in SMP case. This is harmless.
|
||||
|
||||
// Be sure countermoves are different from killers
|
||||
for (int i = 0; i < 2; ++i)
|
||||
if ( countermoves[i] != (cur+0)->move
|
||||
&& countermoves[i] != (cur+1)->move)
|
||||
(end++)->move = countermoves[i];
|
||||
|
||||
// Be sure followupmoves are different from killers and countermoves
|
||||
for (int i = 0; i < 2; ++i)
|
||||
if ( followupmoves[i] != (cur+0)->move
|
||||
&& followupmoves[i] != (cur+1)->move
|
||||
&& followupmoves[i] != (cur+2)->move
|
||||
&& followupmoves[i] != (cur+3)->move)
|
||||
(end++)->move = followupmoves[i];
|
||||
return;
|
||||
|
||||
case QUIETS_1_S1:
|
||||
endQuiets = end = generate<QUIETS>(pos, moves);
|
||||
score<QUIETS>();
|
||||
end = std::partition(cur, end, has_positive_value);
|
||||
insertion_sort(cur, end);
|
||||
return;
|
||||
|
||||
case QUIETS_2_S1:
|
||||
cur = end;
|
||||
end = endQuiets;
|
||||
if (depth >= 3 * ONE_PLY)
|
||||
insertion_sort(cur, end);
|
||||
return;
|
||||
|
||||
case BAD_CAPTURES_S1:
|
||||
// Just pick them in reverse order to get MVV/LVA ordering
|
||||
cur = moves + MAX_MOVES - 1;
|
||||
end = endBadCaptures;
|
||||
return;
|
||||
|
||||
case EVASIONS_S2:
|
||||
end = generate<EVASIONS>(pos, moves);
|
||||
if (end > moves + 1)
|
||||
score<EVASIONS>();
|
||||
return;
|
||||
|
||||
case QUIET_CHECKS_S3:
|
||||
end = generate<QUIET_CHECKS>(pos, moves);
|
||||
return;
|
||||
|
||||
case EVASION: case QSEARCH_0: case QSEARCH_1: case PROBCUT: case RECAPTURE:
|
||||
stage = STOP;
|
||||
/* Fall through */
|
||||
|
||||
case STOP:
|
||||
end = cur + 1; // Avoid another next_phase() call
|
||||
return;
|
||||
|
||||
default:
|
||||
assert(false);
|
||||
}
|
||||
m.value = history[pos.moved_piece(m)][to_sq(m)] + fromTo.get(c, m);
|
||||
}
|
||||
|
||||
|
||||
@@ -292,94 +177,174 @@ void MovePicker::generate_next_stage() {
|
||||
/// a new pseudo legal move every time it is called, until there are no more moves
|
||||
/// left. It picks the move with the biggest value from a list of generated moves
|
||||
/// taking care not to return the ttMove if it has already been searched.
|
||||
template<>
|
||||
Move MovePicker::next_move<false>() {
|
||||
|
||||
Move MovePicker::next_move() {
|
||||
|
||||
Move move;
|
||||
|
||||
while (true)
|
||||
{
|
||||
while (cur == end)
|
||||
generate_next_stage();
|
||||
switch (stage) {
|
||||
|
||||
switch (stage) {
|
||||
case MAIN_SEARCH: case EVASION: case QSEARCH_WITH_CHECKS:
|
||||
case QSEARCH_NO_CHECKS: case PROBCUT:
|
||||
++stage;
|
||||
return ttMove;
|
||||
|
||||
case MAIN_SEARCH: case EVASION: case QSEARCH_0: case QSEARCH_1: case PROBCUT:
|
||||
++cur;
|
||||
return ttMove;
|
||||
case CAPTURES_INIT:
|
||||
endBadCaptures = cur = moves;
|
||||
endMoves = generate<CAPTURES>(pos, cur);
|
||||
score<CAPTURES>();
|
||||
++stage;
|
||||
|
||||
case CAPTURES_S1:
|
||||
move = pick_best(cur++, end)->move;
|
||||
case GOOD_CAPTURES:
|
||||
while (cur < endMoves)
|
||||
{
|
||||
move = pick_best(cur++, endMoves);
|
||||
if (move != ttMove)
|
||||
{
|
||||
if (pos.see_sign(move) >= VALUE_ZERO)
|
||||
if (pos.see_ge(move, VALUE_ZERO))
|
||||
return move;
|
||||
|
||||
// Losing capture, move it to the tail of the array
|
||||
(endBadCaptures--)->move = move;
|
||||
// Losing capture, move it to the beginning of the array
|
||||
*endBadCaptures++ = move;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case KILLERS_S1:
|
||||
move = (cur++)->move;
|
||||
if ( move != MOVE_NONE
|
||||
&& move != ttMove
|
||||
&& pos.pseudo_legal(move)
|
||||
&& !pos.capture(move))
|
||||
return move;
|
||||
break;
|
||||
++stage;
|
||||
move = ss->killers[0]; // First killer move
|
||||
if ( move != MOVE_NONE
|
||||
&& move != ttMove
|
||||
&& pos.pseudo_legal(move)
|
||||
&& !pos.capture(move))
|
||||
return move;
|
||||
|
||||
case QUIETS_1_S1: case QUIETS_2_S1:
|
||||
move = (cur++)->move;
|
||||
case KILLERS:
|
||||
++stage;
|
||||
move = ss->killers[1]; // Second killer move
|
||||
if ( move != MOVE_NONE
|
||||
&& move != ttMove
|
||||
&& pos.pseudo_legal(move)
|
||||
&& !pos.capture(move))
|
||||
return move;
|
||||
|
||||
case COUNTERMOVE:
|
||||
++stage;
|
||||
move = countermove;
|
||||
if ( move != MOVE_NONE
|
||||
&& move != ttMove
|
||||
&& move != ss->killers[0]
|
||||
&& move != ss->killers[1]
|
||||
&& pos.pseudo_legal(move)
|
||||
&& !pos.capture(move))
|
||||
return move;
|
||||
|
||||
case QUIET_INIT:
|
||||
cur = endBadCaptures;
|
||||
endMoves = generate<QUIETS>(pos, cur);
|
||||
score<QUIETS>();
|
||||
if (depth < 3 * ONE_PLY)
|
||||
{
|
||||
ExtMove* goodQuiet = std::partition(cur, endMoves, [](const ExtMove& m)
|
||||
{ return m.value > VALUE_ZERO; });
|
||||
insertion_sort(cur, goodQuiet);
|
||||
} else
|
||||
insertion_sort(cur, endMoves);
|
||||
++stage;
|
||||
|
||||
case QUIET:
|
||||
while (cur < endMoves)
|
||||
{
|
||||
move = *cur++;
|
||||
if ( move != ttMove
|
||||
&& move != killers[0].move
|
||||
&& move != killers[1].move
|
||||
&& move != killers[2].move
|
||||
&& move != killers[3].move
|
||||
&& move != killers[4].move
|
||||
&& move != killers[5].move)
|
||||
&& move != ss->killers[0]
|
||||
&& move != ss->killers[1]
|
||||
&& move != countermove)
|
||||
return move;
|
||||
break;
|
||||
}
|
||||
++stage;
|
||||
cur = moves; // Point to beginning of bad captures
|
||||
|
||||
case BAD_CAPTURES_S1:
|
||||
return (cur--)->move;
|
||||
case BAD_CAPTURES:
|
||||
if (cur < endBadCaptures)
|
||||
return *cur++;
|
||||
break;
|
||||
|
||||
case EVASIONS_S2: case CAPTURES_S3: case CAPTURES_S4:
|
||||
move = pick_best(cur++, end)->move;
|
||||
case EVASIONS_INIT:
|
||||
cur = moves;
|
||||
endMoves = generate<EVASIONS>(pos, cur);
|
||||
score<EVASIONS>();
|
||||
++stage;
|
||||
|
||||
case ALL_EVASIONS:
|
||||
while (cur < endMoves)
|
||||
{
|
||||
move = pick_best(cur++, endMoves);
|
||||
if (move != ttMove)
|
||||
return move;
|
||||
}
|
||||
break;
|
||||
|
||||
case PROBCUT_INIT:
|
||||
cur = moves;
|
||||
endMoves = generate<CAPTURES>(pos, cur);
|
||||
score<CAPTURES>();
|
||||
++stage;
|
||||
|
||||
case PROBCUT_CAPTURES:
|
||||
while (cur < endMoves)
|
||||
{
|
||||
move = pick_best(cur++, endMoves);
|
||||
if ( move != ttMove
|
||||
&& pos.see_ge(move, threshold + 1))
|
||||
return move;
|
||||
}
|
||||
break;
|
||||
|
||||
case QCAPTURES_1_INIT: case QCAPTURES_2_INIT:
|
||||
cur = moves;
|
||||
endMoves = generate<CAPTURES>(pos, cur);
|
||||
score<CAPTURES>();
|
||||
++stage;
|
||||
|
||||
case QCAPTURES_1: case QCAPTURES_2:
|
||||
while (cur < endMoves)
|
||||
{
|
||||
move = pick_best(cur++, endMoves);
|
||||
if (move != ttMove)
|
||||
return move;
|
||||
}
|
||||
if (stage == QCAPTURES_2)
|
||||
break;
|
||||
cur = moves;
|
||||
endMoves = generate<QUIET_CHECKS>(pos, cur);
|
||||
++stage;
|
||||
|
||||
case CAPTURES_S5:
|
||||
move = pick_best(cur++, end)->move;
|
||||
if (move != ttMove && pos.see(move) > captureThreshold)
|
||||
return move;
|
||||
break;
|
||||
case QCHECKS:
|
||||
while (cur < endMoves)
|
||||
{
|
||||
move = cur++->move;
|
||||
if (move != ttMove)
|
||||
return move;
|
||||
}
|
||||
break;
|
||||
|
||||
case CAPTURES_S6:
|
||||
move = pick_best(cur++, end)->move;
|
||||
case QSEARCH_RECAPTURES:
|
||||
cur = moves;
|
||||
endMoves = generate<CAPTURES>(pos, cur);
|
||||
score<CAPTURES>();
|
||||
++stage;
|
||||
|
||||
case QRECAPTURES:
|
||||
while (cur < endMoves)
|
||||
{
|
||||
move = pick_best(cur++, endMoves);
|
||||
if (to_sq(move) == recaptureSquare)
|
||||
return move;
|
||||
break;
|
||||
|
||||
case QUIET_CHECKS_S3:
|
||||
move = (cur++)->move;
|
||||
if (move != ttMove)
|
||||
return move;
|
||||
break;
|
||||
|
||||
case STOP:
|
||||
return MOVE_NONE;
|
||||
|
||||
default:
|
||||
assert(false);
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
assert(false);
|
||||
}
|
||||
|
||||
return MOVE_NONE;
|
||||
}
|
||||
|
||||
|
||||
/// Version of next_move() to use at split point nodes where the move is grabbed
|
||||
/// from the split point's shared MovePicker object. This function is not thread
|
||||
/// safe so must be lock protected by the caller.
|
||||
template<>
|
||||
Move MovePicker::next_move<true>() { return ss->splitPoint->movePicker->next_move<false>(); }
|
||||
|
||||
+49
-38
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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,51 +26,62 @@
|
||||
|
||||
#include "movegen.h"
|
||||
#include "position.h"
|
||||
#include "search.h"
|
||||
#include "types.h"
|
||||
|
||||
|
||||
/// The Stats struct stores moves statistics. According to the template parameter
|
||||
/// the class can store History, Gains and Countermoves. History records how often
|
||||
/// the class can store History and Countermoves. History records how often
|
||||
/// different moves have been successful or unsuccessful during the current search
|
||||
/// and is used for reduction and move ordering decisions. Gains records the move's
|
||||
/// best evaluation gain from one ply to the next and is used for pruning decisions.
|
||||
/// and is used for reduction and move ordering decisions.
|
||||
/// Countermoves store the move that refute a previous one. Entries are stored
|
||||
/// using only the moving piece and destination square, hence two moves with
|
||||
/// different origin but same destination and piece will be considered identical.
|
||||
template<bool Gain, typename T>
|
||||
template<typename T, bool CM = false>
|
||||
struct Stats {
|
||||
|
||||
static const Value Max = Value(250);
|
||||
static const Value Max = Value(1 << 28);
|
||||
|
||||
const T* operator[](Piece pc) const { return table[pc]; }
|
||||
T* operator[](Piece pc) { return table[pc]; }
|
||||
void clear() { std::memset(table, 0, sizeof(table)); }
|
||||
|
||||
void update(Piece pc, Square to, Move m) {
|
||||
|
||||
if (m == table[pc][to].first)
|
||||
return;
|
||||
|
||||
table[pc][to].second = table[pc][to].first;
|
||||
table[pc][to].first = m;
|
||||
}
|
||||
|
||||
void update(Piece pc, Square to, Move m) { table[pc][to] = m; }
|
||||
void update(Piece pc, Square to, Value v) {
|
||||
|
||||
if (Gain)
|
||||
table[pc][to] = std::max(v, table[pc][to] - 1);
|
||||
if (abs(int(v)) >= 324)
|
||||
return;
|
||||
|
||||
else if (abs(table[pc][to] + v) < Max)
|
||||
table[pc][to] += v;
|
||||
table[pc][to] -= table[pc][to] * abs(int(v)) / (CM ? 936 : 324);
|
||||
table[pc][to] += int(v) * 32;
|
||||
}
|
||||
|
||||
private:
|
||||
T table[PIECE_NB][SQUARE_NB];
|
||||
};
|
||||
|
||||
typedef Stats< true, Value> GainsStats;
|
||||
typedef Stats<false, Value> HistoryStats;
|
||||
typedef Stats<false, std::pair<Move, Move> > MovesStats;
|
||||
typedef Stats<Move> MoveStats;
|
||||
typedef Stats<Value, false> HistoryStats;
|
||||
typedef Stats<Value, true> CounterMoveStats;
|
||||
typedef Stats<CounterMoveStats> CounterMoveHistoryStats;
|
||||
|
||||
struct FromToStats {
|
||||
|
||||
Value get(Color c, Move m) const { return table[c][from_sq(m)][to_sq(m)]; }
|
||||
void clear() { std::memset(table, 0, sizeof(table)); }
|
||||
void update(Color c, Move m, Value v) {
|
||||
|
||||
if (abs(int(v)) >= 324)
|
||||
return;
|
||||
|
||||
Square from = from_sq(m);
|
||||
Square to = to_sq(m);
|
||||
|
||||
table[c][from][to] -= table[c][from][to] * abs(int(v)) / 324;
|
||||
table[c][from][to] += int(v) * 32;
|
||||
}
|
||||
|
||||
private:
|
||||
Value table[COLOR_NB][SQUARE_NB][SQUARE_NB];
|
||||
};
|
||||
|
||||
|
||||
/// MovePicker class is used to pick one pseudo legal move at a time from the
|
||||
@@ -78,34 +90,33 @@ typedef Stats<false, std::pair<Move, Move> > MovesStats;
|
||||
/// when MOVE_NONE is returned. In order to improve the efficiency of the alpha
|
||||
/// beta algorithm, MovePicker attempts to return the moves which are most likely
|
||||
/// to get a cut-off first.
|
||||
namespace Search { struct Stack; }
|
||||
|
||||
class MovePicker {
|
||||
|
||||
MovePicker& operator=(const MovePicker&); // Silence a warning under MSVC
|
||||
|
||||
public:
|
||||
MovePicker(const Position&, Move, Depth, const HistoryStats&, Square);
|
||||
MovePicker(const Position&, Move, const HistoryStats&, PieceType);
|
||||
MovePicker(const Position&, Move, Depth, const HistoryStats&, Move*, Move*, Search::Stack*);
|
||||
MovePicker(const MovePicker&) = delete;
|
||||
MovePicker& operator=(const MovePicker&) = delete;
|
||||
|
||||
template<bool SpNode> Move next_move();
|
||||
MovePicker(const Position&, Move, Value);
|
||||
MovePicker(const Position&, Move, Depth, Square);
|
||||
MovePicker(const Position&, Move, Depth, Search::Stack*);
|
||||
|
||||
Move next_move();
|
||||
|
||||
private:
|
||||
template<GenType> void score();
|
||||
void generate_next_stage();
|
||||
ExtMove* begin() { return cur; }
|
||||
ExtMove* end() { return endMoves; }
|
||||
|
||||
const Position& pos;
|
||||
const HistoryStats& history;
|
||||
Search::Stack* ss;
|
||||
Move* countermoves;
|
||||
Move* followupmoves;
|
||||
const Search::Stack* ss;
|
||||
Move countermove;
|
||||
Depth depth;
|
||||
Move ttMove;
|
||||
ExtMove killers[6];
|
||||
Square recaptureSquare;
|
||||
Value captureThreshold;
|
||||
Value threshold;
|
||||
int stage;
|
||||
ExtMove *cur, *end, *endQuiets, *endBadCaptures;
|
||||
ExtMove *cur, *endMoves, *endBadCaptures;
|
||||
ExtMove moves[MAX_MOVES];
|
||||
};
|
||||
|
||||
|
||||
+99
-120
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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
|
||||
@@ -21,7 +22,6 @@
|
||||
#include <cassert>
|
||||
|
||||
#include "bitboard.h"
|
||||
#include "bitcount.h"
|
||||
#include "pawns.h"
|
||||
#include "position.h"
|
||||
#include "thread.h"
|
||||
@@ -31,65 +31,58 @@ namespace {
|
||||
#define V Value
|
||||
#define S(mg, eg) make_score(mg, eg)
|
||||
|
||||
// Doubled pawn penalty by file
|
||||
const Score Doubled[FILE_NB] = {
|
||||
S(13, 43), S(20, 48), S(23, 48), S(23, 48),
|
||||
S(23, 48), S(23, 48), S(20, 48), S(13, 43) };
|
||||
// Isolated pawn penalty by opposed flag
|
||||
const Score Isolated[2] = { S(45, 40), S(30, 27) };
|
||||
|
||||
// Isolated pawn penalty by opposed flag and file
|
||||
const Score Isolated[2][FILE_NB] = {
|
||||
{ S(37, 45), S(54, 52), S(60, 52), S(60, 52),
|
||||
S(60, 52), S(60, 52), S(54, 52), S(37, 45) },
|
||||
{ S(25, 30), S(36, 35), S(40, 35), S(40, 35),
|
||||
S(40, 35), S(40, 35), S(36, 35), S(25, 30) } };
|
||||
// Backward pawn penalty by opposed flag
|
||||
const Score Backward[2] = { S(56, 33), S(41, 19) };
|
||||
|
||||
// Backward pawn penalty by opposed flag and file
|
||||
const Score Backward[2][FILE_NB] = {
|
||||
{ S(30, 42), S(43, 46), S(49, 46), S(49, 46),
|
||||
S(49, 46), S(49, 46), S(43, 46), S(30, 42) },
|
||||
{ S(20, 28), S(29, 31), S(33, 31), S(33, 31),
|
||||
S(33, 31), S(33, 31), S(29, 31), S(20, 28) } };
|
||||
// Unsupported pawn penalty for pawns which are neither isolated or backward
|
||||
const Score Unsupported = S(17, 8);
|
||||
|
||||
// Connected pawn bonus by opposed, phalanx flags and rank
|
||||
Score Connected[2][2][RANK_NB];
|
||||
// Connected pawn bonus by opposed, phalanx, twice supported and rank
|
||||
Score Connected[2][2][2][RANK_NB];
|
||||
|
||||
// Levers bonus by rank
|
||||
// Doubled pawn penalty
|
||||
const Score Doubled = S(18,38);
|
||||
|
||||
// Lever bonus by rank
|
||||
const Score Lever[RANK_NB] = {
|
||||
S( 0, 0), S( 0, 0), S(0, 0), S(0, 0),
|
||||
S(20,20), S(40,40), S(0, 0), S(0, 0) };
|
||||
|
||||
// Unsupported pawn penalty
|
||||
const Score UnsupportedPawnPenalty = S(20, 10);
|
||||
S( 0, 0), S( 0, 0), S(0, 0), S(0, 0),
|
||||
S(17, 16), S(33, 32), S(0, 0), S(0, 0)
|
||||
};
|
||||
|
||||
// Weakness of our pawn shelter in front of the king by [distance from edge][rank]
|
||||
const Value ShelterWeakness[][RANK_NB] = {
|
||||
{ V(100), V(13), V(24), V(64), V(89), V( 93), V(104) },
|
||||
{ V(110), V( 1), V(29), V(75), V(96), V(102), V(107) },
|
||||
{ V(102), V( 0), V(39), V(74), V(88), V(101), V( 98) },
|
||||
{ V( 88), V( 4), V(33), V(67), V(92), V( 94), V(107) } };
|
||||
{ V( 97), V(21), V(26), V(51), V(87), V( 89), V( 99) },
|
||||
{ V(120), V( 0), V(28), V(76), V(88), V(103), V(104) },
|
||||
{ V(101), V( 7), V(54), V(78), V(77), V( 92), V(101) },
|
||||
{ V( 80), V(11), V(44), V(68), V(87), V( 90), V(119) }
|
||||
};
|
||||
|
||||
// Danger of enemy pawns moving toward our king by [type][distance from edge][rank]
|
||||
const Value StormDanger[][4][RANK_NB] = {
|
||||
{ { V( 0), V( 63), V( 128), V(43), V(27) },
|
||||
{ V( 0), V( 62), V( 131), V(44), V(26) },
|
||||
{ V( 0), V( 59), V( 121), V(50), V(28) },
|
||||
{ V( 0), V( 62), V( 127), V(54), V(28) } },
|
||||
{ { V(24), V( 40), V( 93), V(42), V(22) },
|
||||
{ V(24), V( 28), V( 101), V(38), V(20) },
|
||||
{ V(24), V( 32), V( 95), V(36), V(23) },
|
||||
{ V(27), V( 24), V( 99), V(36), V(24) } },
|
||||
{ { V( 0), V( 0), V( 81), V(16), V( 6) },
|
||||
{ V( 0), V( 0), V( 165), V(29), V( 9) },
|
||||
{ V( 0), V( 0), V( 163), V(23), V(12) },
|
||||
{ V( 0), V( 0), V( 161), V(28), V(13) } },
|
||||
{ { V( 0), V(-296), V(-299), V(55), V(25) },
|
||||
{ V( 0), V( 67), V( 131), V(46), V(21) },
|
||||
{ V( 0), V( 65), V( 135), V(50), V(31) },
|
||||
{ V( 0), V( 62), V( 128), V(51), V(24) } } };
|
||||
{ { V( 0), V( 67), V( 134), V(38), V(32) },
|
||||
{ V( 0), V( 57), V( 139), V(37), V(22) },
|
||||
{ V( 0), V( 43), V( 115), V(43), V(27) },
|
||||
{ V( 0), V( 68), V( 124), V(57), V(32) } },
|
||||
{ { V(20), V( 43), V( 100), V(56), V(20) },
|
||||
{ V(23), V( 20), V( 98), V(40), V(15) },
|
||||
{ V(23), V( 39), V( 103), V(36), V(18) },
|
||||
{ V(28), V( 19), V( 108), V(42), V(26) } },
|
||||
{ { V( 0), V( 0), V( 75), V(14), V( 2) },
|
||||
{ V( 0), V( 0), V( 150), V(30), V( 4) },
|
||||
{ V( 0), V( 0), V( 160), V(22), V( 5) },
|
||||
{ V( 0), V( 0), V( 166), V(24), V(13) } },
|
||||
{ { V( 0), V(-283), V(-281), V(57), V(31) },
|
||||
{ V( 0), V( 58), V( 141), V(39), V(18) },
|
||||
{ V( 0), V( 65), V( 142), V(48), V(32) },
|
||||
{ V( 0), V( 60), V( 126), V(51), V(19) } }
|
||||
};
|
||||
|
||||
// Max bonus for king safety. Corresponds to start position with all the pawns
|
||||
// in front of the king and no enemy pawn on the horizon.
|
||||
const Value MaxSafetyBonus = V(257);
|
||||
const Value MaxSafetyBonus = V(258);
|
||||
|
||||
#undef S
|
||||
#undef V
|
||||
@@ -97,26 +90,26 @@ namespace {
|
||||
template<Color Us>
|
||||
Score evaluate(const Position& pos, Pawns::Entry* e) {
|
||||
|
||||
const Color Them = (Us == WHITE ? BLACK : WHITE);
|
||||
const Square Up = (Us == WHITE ? DELTA_N : DELTA_S);
|
||||
const Square Right = (Us == WHITE ? DELTA_NE : DELTA_SW);
|
||||
const Square Left = (Us == WHITE ? DELTA_NW : DELTA_SE);
|
||||
const Color Them = (Us == WHITE ? BLACK : WHITE);
|
||||
const Square Up = (Us == WHITE ? NORTH : SOUTH);
|
||||
const Square Right = (Us == WHITE ? NORTH_EAST : SOUTH_WEST);
|
||||
const Square Left = (Us == WHITE ? NORTH_WEST : SOUTH_EAST);
|
||||
|
||||
Bitboard b, p, doubled, connected;
|
||||
Bitboard b, neighbours, stoppers, doubled, supported, phalanx;
|
||||
Square s;
|
||||
bool passed, isolated, opposed, phalanx, backward, unsupported, lever;
|
||||
bool opposed, lever, connected, backward;
|
||||
Score score = SCORE_ZERO;
|
||||
const Square* pl = pos.list<PAWN>(Us);
|
||||
const Square* pl = pos.squares<PAWN>(Us);
|
||||
const Bitboard* pawnAttacksBB = StepAttacksBB[make_piece(Us, PAWN)];
|
||||
|
||||
Bitboard ourPawns = pos.pieces(Us , PAWN);
|
||||
Bitboard theirPawns = pos.pieces(Them, PAWN);
|
||||
|
||||
e->passedPawns[Us] = 0;
|
||||
e->kingSquares[Us] = SQ_NONE;
|
||||
e->passedPawns[Us] = e->pawnAttacksSpan[Us] = 0;
|
||||
e->semiopenFiles[Us] = 0xFF;
|
||||
e->pawnAttacks[Us] = shift_bb<Right>(ourPawns) | shift_bb<Left>(ourPawns);
|
||||
e->pawnsOnSquares[Us][BLACK] = popcount<Max15>(ourPawns & DarkSquares);
|
||||
e->kingSquares[Us] = SQ_NONE;
|
||||
e->pawnAttacks[Us] = shift<Right>(ourPawns) | shift<Left>(ourPawns);
|
||||
e->pawnsOnSquares[Us][BLACK] = popcount(ourPawns & DarkSquares);
|
||||
e->pawnsOnSquares[Us][WHITE] = pos.count<PAWN>(Us) - e->pawnsOnSquares[Us][BLACK];
|
||||
|
||||
// Loop through all pawns of the current color and score each pawn
|
||||
@@ -126,76 +119,61 @@ namespace {
|
||||
|
||||
File f = file_of(s);
|
||||
|
||||
// This file cannot be semi-open
|
||||
e->semiopenFiles[Us] &= ~(1 << f);
|
||||
e->semiopenFiles[Us] &= ~(1 << f);
|
||||
e->pawnAttacksSpan[Us] |= pawn_attack_span(Us, s);
|
||||
|
||||
// Previous rank
|
||||
p = rank_bb(s - pawn_push(Us));
|
||||
// Flag the pawn
|
||||
opposed = theirPawns & forward_bb(Us, s);
|
||||
stoppers = theirPawns & passed_pawn_mask(Us, s);
|
||||
lever = theirPawns & pawnAttacksBB[s];
|
||||
doubled = ourPawns & (s + Up);
|
||||
neighbours = ourPawns & adjacent_files_bb(f);
|
||||
phalanx = neighbours & rank_bb(s);
|
||||
supported = neighbours & rank_bb(s - Up);
|
||||
connected = supported | phalanx;
|
||||
|
||||
// Flag the pawn as passed, isolated, doubled,
|
||||
// unsupported or connected (but not the backward one).
|
||||
connected = ourPawns & adjacent_files_bb(f) & (rank_bb(s) | p);
|
||||
phalanx = connected & rank_bb(s);
|
||||
unsupported = !(ourPawns & adjacent_files_bb(f) & p);
|
||||
isolated = !(ourPawns & adjacent_files_bb(f));
|
||||
doubled = ourPawns & forward_bb(Us, s);
|
||||
opposed = theirPawns & forward_bb(Us, s);
|
||||
passed = !(theirPawns & passed_pawn_mask(Us, s));
|
||||
lever = theirPawns & pawnAttacksBB[s];
|
||||
|
||||
// Test for backward pawn.
|
||||
// If the pawn is passed, isolated, or connected it cannot be
|
||||
// backward. If there are friendly pawns behind on adjacent files
|
||||
// or if it can capture an enemy pawn it cannot be backward either.
|
||||
if ( (passed | isolated | connected)
|
||||
|| (ourPawns & pawn_attack_span(Them, s))
|
||||
|| (pos.attacks_from<PAWN>(s, Us) & theirPawns))
|
||||
// A pawn is backward when it is behind all pawns of the same color on the
|
||||
// adjacent files and cannot be safely advanced.
|
||||
if (!neighbours || lever || relative_rank(Us, s) >= RANK_5)
|
||||
backward = false;
|
||||
else
|
||||
{
|
||||
// We now know that there are no friendly pawns beside or behind this
|
||||
// pawn on adjacent files. We now check whether the pawn is
|
||||
// backward by looking in the forward direction on the adjacent
|
||||
// files, and picking the closest pawn there.
|
||||
b = pawn_attack_span(Us, s) & (ourPawns | theirPawns);
|
||||
b = pawn_attack_span(Us, s) & rank_bb(backmost_sq(Us, b));
|
||||
// Find the backmost rank with neighbours or stoppers
|
||||
b = rank_bb(backmost_sq(Us, neighbours | stoppers));
|
||||
|
||||
// If we have an enemy pawn in the same or next rank, the pawn is
|
||||
// backward because it cannot advance without being captured.
|
||||
backward = (b | shift_bb<Up>(b)) & theirPawns;
|
||||
// The pawn is backward when it cannot safely progress to that rank:
|
||||
// either there is a stopper in the way on this rank, or there is a
|
||||
// stopper on adjacent file which controls the way to that rank.
|
||||
backward = (b | shift<Up>(b & adjacent_files_bb(f))) & stoppers;
|
||||
|
||||
assert(!backward || !(pawn_attack_span(Them, s + Up) & neighbours));
|
||||
}
|
||||
|
||||
assert(opposed | passed | (pawn_attack_span(Us, s) & theirPawns));
|
||||
|
||||
// Passed pawns will be properly scored in evaluation because we need
|
||||
// full attack info to evaluate passed pawns. Only the frontmost passed
|
||||
// pawn on each file is considered a true passed pawn.
|
||||
if (passed && !doubled)
|
||||
// full attack info to evaluate them.
|
||||
if (!stoppers && !(ourPawns & forward_bb(Us, s)))
|
||||
e->passedPawns[Us] |= s;
|
||||
|
||||
// Score this pawn
|
||||
if (isolated)
|
||||
score -= Isolated[opposed][f];
|
||||
if (!neighbours)
|
||||
score -= Isolated[opposed];
|
||||
|
||||
if (unsupported && !isolated)
|
||||
score -= UnsupportedPawnPenalty;
|
||||
else if (backward)
|
||||
score -= Backward[opposed];
|
||||
|
||||
if (doubled)
|
||||
score -= Doubled[f] / distance<Rank>(s, frontmost_sq(Us, doubled));
|
||||
|
||||
if (backward)
|
||||
score -= Backward[opposed][f];
|
||||
else if (!supported)
|
||||
score -= Unsupported;
|
||||
|
||||
if (connected)
|
||||
score += Connected[opposed][phalanx][relative_rank(Us, s)];
|
||||
score += Connected[opposed][!!phalanx][more_than_one(supported)][relative_rank(Us, s)];
|
||||
|
||||
if (doubled)
|
||||
score -= Doubled;
|
||||
|
||||
if (lever)
|
||||
score += Lever[relative_rank(Us, s)];
|
||||
}
|
||||
|
||||
b = e->semiopenFiles[Us] ^ 0xFF;
|
||||
e->pawnSpan[Us] = b ? int(msb(b) - lsb(b)) : 0;
|
||||
|
||||
return score;
|
||||
}
|
||||
|
||||
@@ -207,17 +185,19 @@ namespace Pawns {
|
||||
/// hard-coded tables, when makes sense, we prefer to calculate them with a formula
|
||||
/// to reduce independent parameters and to allow easier tuning and better insight.
|
||||
|
||||
void init()
|
||||
{
|
||||
static const int Seed[RANK_NB] = { 0, 6, 15, 10, 57, 75, 135, 258 };
|
||||
void init() {
|
||||
|
||||
static const int Seed[RANK_NB] = { 0, 8, 19, 13, 71, 94, 169, 324 };
|
||||
|
||||
for (int opposed = 0; opposed <= 1; ++opposed)
|
||||
for (int phalanx = 0; phalanx <= 1; ++phalanx)
|
||||
for (Rank r = RANK_2; r < RANK_8; ++r)
|
||||
{
|
||||
int bonus = Seed[r] + (phalanx ? (Seed[r + 1] - Seed[r]) / 2 : 0);
|
||||
Connected[opposed][phalanx][r] = make_score(bonus / 2, bonus >> opposed);
|
||||
}
|
||||
for (int apex = 0; apex <= 1; ++apex)
|
||||
for (Rank r = RANK_2; r < RANK_8; ++r)
|
||||
{
|
||||
int v = (Seed[r] + (phalanx ? (Seed[r + 1] - Seed[r]) / 2 : 0)) >> opposed;
|
||||
v += (apex ? v / 2 : 0);
|
||||
Connected[opposed][phalanx][apex][r] = make_score(v, v * 5 / 8);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -236,6 +216,8 @@ Entry* probe(const Position& pos) {
|
||||
|
||||
e->key = key;
|
||||
e->score = evaluate<WHITE>(pos, e) - evaluate<BLACK>(pos, e);
|
||||
e->asymmetry = popcount(e->semiopenFiles[WHITE] ^ e->semiopenFiles[BLACK]);
|
||||
e->openFiles = popcount(e->semiopenFiles[WHITE] & e->semiopenFiles[BLACK]);
|
||||
return e;
|
||||
}
|
||||
|
||||
@@ -284,14 +266,11 @@ Score Entry::do_king_safety(const Position& pos, Square ksq) {
|
||||
|
||||
kingSquares[Us] = ksq;
|
||||
castlingRights[Us] = pos.can_castle(Us);
|
||||
minKingPawnDistance[Us] = 0;
|
||||
int minKingPawnDistance = 0;
|
||||
|
||||
Bitboard pawns = pos.pieces(Us, PAWN);
|
||||
if (pawns)
|
||||
while (!(DistanceRingBB[ksq][minKingPawnDistance[Us]++] & pawns)) {}
|
||||
|
||||
if (relative_rank(Us, ksq) > RANK_4)
|
||||
return make_score(0, -16 * minKingPawnDistance[Us]);
|
||||
while (!(DistanceRingBB[ksq][minKingPawnDistance++] & pawns)) {}
|
||||
|
||||
Value bonus = shelter_storm<Us>(pos, ksq);
|
||||
|
||||
@@ -302,7 +281,7 @@ Score Entry::do_king_safety(const Position& pos, Square ksq) {
|
||||
if (pos.can_castle(MakeCastling<Us, QUEEN_SIDE>::right))
|
||||
bonus = std::max(bonus, shelter_storm<Us>(pos, relative_square(Us, SQ_C1)));
|
||||
|
||||
return make_score(bonus, -16 * minKingPawnDistance[Us]);
|
||||
return make_score(bonus, -16 * minKingPawnDistance);
|
||||
}
|
||||
|
||||
// Explicit template instantiation
|
||||
|
||||
+8
-4
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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
|
||||
@@ -35,7 +36,9 @@ struct Entry {
|
||||
Score pawns_score() const { return score; }
|
||||
Bitboard pawn_attacks(Color c) const { return pawnAttacks[c]; }
|
||||
Bitboard passed_pawns(Color c) const { return passedPawns[c]; }
|
||||
int pawn_span(Color c) const { return pawnSpan[c]; }
|
||||
Bitboard pawn_attacks_span(Color c) const { return pawnAttacksSpan[c]; }
|
||||
int pawn_asymmetry() const { return asymmetry; }
|
||||
int open_files() const { return openFiles; }
|
||||
|
||||
int semiopen_file(Color c, File f) const {
|
||||
return semiopenFiles[c] & (1 << f);
|
||||
@@ -50,7 +53,7 @@ struct Entry {
|
||||
}
|
||||
|
||||
template<Color Us>
|
||||
Score king_safety(const Position& pos, Square ksq) {
|
||||
Score king_safety(const Position& pos, Square ksq) {
|
||||
return kingSquares[Us] == ksq && castlingRights[Us] == pos.can_castle(Us)
|
||||
? kingSafety[Us] : (kingSafety[Us] = do_king_safety<Us>(pos, ksq));
|
||||
}
|
||||
@@ -65,13 +68,14 @@ struct Entry {
|
||||
Score score;
|
||||
Bitboard passedPawns[COLOR_NB];
|
||||
Bitboard pawnAttacks[COLOR_NB];
|
||||
Bitboard pawnAttacksSpan[COLOR_NB];
|
||||
Square kingSquares[COLOR_NB];
|
||||
Score kingSafety[COLOR_NB];
|
||||
int minKingPawnDistance[COLOR_NB];
|
||||
int castlingRights[COLOR_NB];
|
||||
int semiopenFiles[COLOR_NB];
|
||||
int pawnSpan[COLOR_NB];
|
||||
int pawnsOnSquares[COLOR_NB][COLOR_NB]; // [color][light/dark squares]
|
||||
int asymmetry;
|
||||
int openFiles;
|
||||
};
|
||||
|
||||
typedef HashTable<Entry, 16384> Table;
|
||||
|
||||
-116
@@ -1,116 +0,0 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 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
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
Stockfish is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef PLATFORM_H_INCLUDED
|
||||
#define PLATFORM_H_INCLUDED
|
||||
|
||||
#ifdef _MSC_VER
|
||||
|
||||
// Disable some silly and noisy warnings from MSVC compiler
|
||||
#pragma warning(disable: 4127) // Conditional expression is constant
|
||||
#pragma warning(disable: 4146) // Unary minus operator applied to unsigned type
|
||||
#pragma warning(disable: 4800) // Forcing value to bool 'true' or 'false'
|
||||
#pragma warning(disable: 4996) // Function _ftime() may be unsafe
|
||||
|
||||
// MSVC does not support <inttypes.h>
|
||||
typedef signed __int8 int8_t;
|
||||
typedef unsigned __int8 uint8_t;
|
||||
typedef signed __int16 int16_t;
|
||||
typedef unsigned __int16 uint16_t;
|
||||
typedef signed __int32 int32_t;
|
||||
typedef unsigned __int32 uint32_t;
|
||||
typedef signed __int64 int64_t;
|
||||
typedef unsigned __int64 uint64_t;
|
||||
|
||||
#else
|
||||
# include <inttypes.h>
|
||||
#endif
|
||||
|
||||
#ifndef _WIN32 // Linux - Unix
|
||||
|
||||
# include <sys/time.h>
|
||||
|
||||
inline int64_t system_time_to_msec() {
|
||||
timeval t;
|
||||
gettimeofday(&t, NULL);
|
||||
return t.tv_sec * 1000LL + t.tv_usec / 1000;
|
||||
}
|
||||
|
||||
# include <pthread.h>
|
||||
typedef pthread_mutex_t Lock;
|
||||
typedef pthread_cond_t WaitCondition;
|
||||
typedef pthread_t NativeHandle;
|
||||
typedef void*(*pt_start_fn)(void*);
|
||||
|
||||
# define lock_init(x) pthread_mutex_init(&(x), NULL)
|
||||
# define lock_grab(x) pthread_mutex_lock(&(x))
|
||||
# define lock_release(x) pthread_mutex_unlock(&(x))
|
||||
# define lock_destroy(x) pthread_mutex_destroy(&(x))
|
||||
# define cond_destroy(x) pthread_cond_destroy(&(x))
|
||||
# define cond_init(x) pthread_cond_init(&(x), NULL)
|
||||
# define cond_signal(x) pthread_cond_signal(&(x))
|
||||
# define cond_wait(x,y) pthread_cond_wait(&(x),&(y))
|
||||
# define cond_timedwait(x,y,z) pthread_cond_timedwait(&(x),&(y),z)
|
||||
# define thread_create(x,f,t) pthread_create(&(x),NULL,(pt_start_fn)f,t)
|
||||
# define thread_join(x) pthread_join(x, NULL)
|
||||
|
||||
#else // Windows and MinGW
|
||||
|
||||
# include <sys/timeb.h>
|
||||
|
||||
inline int64_t system_time_to_msec() {
|
||||
_timeb t;
|
||||
_ftime(&t);
|
||||
return t.time * 1000LL + t.millitm;
|
||||
}
|
||||
|
||||
#ifndef NOMINMAX
|
||||
# define NOMINMAX // disable macros min() and max()
|
||||
#endif
|
||||
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
#undef WIN32_LEAN_AND_MEAN
|
||||
#undef NOMINMAX
|
||||
|
||||
// We use critical sections on Windows to support Windows XP and older versions.
|
||||
// Unfortunately, cond_wait() is racy between lock_release() and WaitForSingleObject()
|
||||
// but apart from this they have the same speed performance of SRW locks.
|
||||
typedef CRITICAL_SECTION Lock;
|
||||
typedef HANDLE WaitCondition;
|
||||
typedef HANDLE NativeHandle;
|
||||
|
||||
// On Windows 95 and 98 parameter lpThreadId may not be null
|
||||
inline DWORD* dwWin9xKludge() { static DWORD dw; return &dw; }
|
||||
|
||||
# define lock_init(x) InitializeCriticalSection(&(x))
|
||||
# define lock_grab(x) EnterCriticalSection(&(x))
|
||||
# define lock_release(x) LeaveCriticalSection(&(x))
|
||||
# define lock_destroy(x) DeleteCriticalSection(&(x))
|
||||
# define cond_init(x) { x = CreateEvent(0, FALSE, FALSE, 0); }
|
||||
# define cond_destroy(x) CloseHandle(x)
|
||||
# define cond_signal(x) SetEvent(x)
|
||||
# define cond_wait(x,y) { lock_release(y); WaitForSingleObject(x, INFINITE); lock_grab(y); }
|
||||
# define cond_timedwait(x,y,z) { lock_release(y); WaitForSingleObject(x,z); lock_grab(y); }
|
||||
# define thread_create(x,f,t) (x = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)f,t,0,dwWin9xKludge()))
|
||||
# define thread_join(x) { WaitForSingleObject(x, INFINITE); CloseHandle(x); }
|
||||
|
||||
#endif
|
||||
|
||||
#endif // #ifndef PLATFORM_H_INCLUDED
|
||||
+295
-407
File diff suppressed because it is too large
Load Diff
+82
-108
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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
|
||||
@@ -21,28 +22,13 @@
|
||||
#define POSITION_H_INCLUDED
|
||||
|
||||
#include <cassert>
|
||||
#include <cstddef> // For offsetof()
|
||||
#include <deque>
|
||||
#include <memory> // For std::unique_ptr
|
||||
#include <string>
|
||||
|
||||
#include "bitboard.h"
|
||||
#include "types.h"
|
||||
|
||||
class Position;
|
||||
struct Thread;
|
||||
|
||||
/// CheckInfo struct is initialized at c'tor time and keeps info used to detect
|
||||
/// if a move gives check.
|
||||
|
||||
struct CheckInfo {
|
||||
|
||||
explicit CheckInfo(const Position&);
|
||||
|
||||
Bitboard dcCandidates;
|
||||
Bitboard pinned;
|
||||
Bitboard checkSq[PIECE_TYPE_NB];
|
||||
Square ksq;
|
||||
};
|
||||
|
||||
|
||||
/// StateInfo struct stores information needed to restore a Position object to
|
||||
/// its previous state when we retract a move. Whenever a move is made on the
|
||||
@@ -60,40 +46,36 @@ struct StateInfo {
|
||||
Score psq;
|
||||
Square epSquare;
|
||||
|
||||
// Not copied when making a move
|
||||
// Not copied when making a move (will be recomputed anyhow)
|
||||
Key key;
|
||||
Bitboard checkersBB;
|
||||
PieceType capturedType;
|
||||
Piece capturedPiece;
|
||||
StateInfo* previous;
|
||||
Bitboard blockersForKing[COLOR_NB];
|
||||
Bitboard pinnersForKing[COLOR_NB];
|
||||
Bitboard checkSquares[PIECE_TYPE_NB];
|
||||
};
|
||||
|
||||
|
||||
/// When making a move the current StateInfo up to 'key' excluded is copied to
|
||||
/// the new one. Here we calculate the quad words (64 bit) needed to be copied.
|
||||
const size_t StateCopySize64 = offsetof(StateInfo, key) / sizeof(uint64_t) + 1;
|
||||
// In a std::deque references to elements are unaffected upon resizing
|
||||
typedef std::unique_ptr<std::deque<StateInfo>> StateListPtr;
|
||||
|
||||
|
||||
/// Position class stores information regarding the board representation as
|
||||
/// pieces, side to move, hash keys, castling info, etc. Important methods are
|
||||
/// do_move() and undo_move(), used by the search to update node info when
|
||||
/// traversing the search tree.
|
||||
class Thread;
|
||||
|
||||
class Position {
|
||||
|
||||
friend std::ostream& operator<<(std::ostream&, const Position&);
|
||||
|
||||
Position(const Position&); // Disable the default copy constructor
|
||||
|
||||
public:
|
||||
static void init();
|
||||
|
||||
Position() {} // To define the global object RootPos
|
||||
Position(const Position& pos, Thread* th) { *this = pos; thisThread = th; }
|
||||
Position(const std::string& f, bool c960, Thread* th) { set(f, c960, th); }
|
||||
Position& operator=(const Position&); // To assign RootPos from UCI
|
||||
Position() = default;
|
||||
Position(const Position&) = delete;
|
||||
Position& operator=(const Position&) = delete;
|
||||
|
||||
// FEN string input/output
|
||||
void set(const std::string& fenStr, bool isChess960, Thread* th);
|
||||
Position& set(const std::string& fenStr, bool isChess960, StateInfo* si, Thread* th);
|
||||
const std::string fen() const;
|
||||
|
||||
// Position representation
|
||||
@@ -104,11 +86,11 @@ public:
|
||||
Bitboard pieces(Color c, PieceType pt) const;
|
||||
Bitboard pieces(Color c, PieceType pt1, PieceType pt2) const;
|
||||
Piece piece_on(Square s) const;
|
||||
Square king_square(Color c) const;
|
||||
Square ep_square() const;
|
||||
bool empty(Square s) const;
|
||||
template<PieceType Pt> int count(Color c) const;
|
||||
template<PieceType Pt> const Square* list(Color c) const;
|
||||
template<PieceType Pt> const Square* squares(Color c) const;
|
||||
template<PieceType Pt> Square square(Color c) const;
|
||||
|
||||
// Castling
|
||||
int can_castle(Color c) const;
|
||||
@@ -120,6 +102,7 @@ public:
|
||||
Bitboard checkers() const;
|
||||
Bitboard discovered_check_candidates() const;
|
||||
Bitboard pinned_pieces(Color c) const;
|
||||
Bitboard check_squares(PieceType pt) const;
|
||||
|
||||
// Attacks to/from a given square
|
||||
Bitboard attackers_to(Square s) const;
|
||||
@@ -127,37 +110,34 @@ public:
|
||||
Bitboard attacks_from(Piece pc, Square s) const;
|
||||
template<PieceType> Bitboard attacks_from(Square s) const;
|
||||
template<PieceType> Bitboard attacks_from(Square s, Color c) const;
|
||||
Bitboard slider_blockers(Bitboard sliders, Square s, Bitboard& pinners) const;
|
||||
|
||||
// Properties of moves
|
||||
bool legal(Move m, Bitboard pinned) const;
|
||||
bool legal(Move m) const;
|
||||
bool pseudo_legal(const Move m) const;
|
||||
bool capture(Move m) const;
|
||||
bool capture_or_promotion(Move m) const;
|
||||
bool gives_check(Move m, const CheckInfo& ci) const;
|
||||
bool gives_check(Move m) const;
|
||||
bool advanced_pawn_push(Move m) const;
|
||||
Piece moved_piece(Move m) const;
|
||||
PieceType captured_piece_type() const;
|
||||
Piece captured_piece() const;
|
||||
|
||||
// Piece specific
|
||||
bool pawn_passed(Color c, Square s) const;
|
||||
bool pawn_on_7th(Color c) const;
|
||||
bool opposite_bishops() const;
|
||||
|
||||
// Doing and undoing moves
|
||||
void do_move(Move m, StateInfo& st);
|
||||
void do_move(Move m, StateInfo& st, const CheckInfo& ci, bool moveIsCheck);
|
||||
void do_move(Move m, StateInfo& st, bool givesCheck);
|
||||
void undo_move(Move m);
|
||||
void do_null_move(StateInfo& st);
|
||||
void undo_null_move();
|
||||
|
||||
// Static exchange evaluation
|
||||
Value see(Move m) const;
|
||||
Value see_sign(Move m) const;
|
||||
// Static Exchange Evaluation
|
||||
bool see_ge(Move m, Value value) const;
|
||||
|
||||
// Accessing hash keys
|
||||
Key key() const;
|
||||
Key key_after(Move m) const;
|
||||
Key exclusion_key() const;
|
||||
Key material_key() const;
|
||||
Key pawn_key() const;
|
||||
|
||||
@@ -168,41 +148,38 @@ public:
|
||||
bool is_chess960() const;
|
||||
Thread* this_thread() const;
|
||||
uint64_t nodes_searched() const;
|
||||
void set_nodes_searched(uint64_t n);
|
||||
bool is_draw() const;
|
||||
int rule50_count() const;
|
||||
Score psq_score() const;
|
||||
Value non_pawn_material(Color c) const;
|
||||
|
||||
// Position consistency check, for debugging
|
||||
bool pos_is_ok(int* step = NULL) const;
|
||||
bool pos_is_ok(int* failedStep = nullptr) const;
|
||||
void flip();
|
||||
|
||||
private:
|
||||
// Initialization helpers (used while setting up a position)
|
||||
void clear();
|
||||
void set_castling_right(Color c, Square rfrom);
|
||||
void set_state(StateInfo* si) const;
|
||||
void set_check_info(StateInfo* si) const;
|
||||
|
||||
// Other helpers
|
||||
Bitboard check_blockers(Color c, Color kingColor) const;
|
||||
void put_piece(Square s, Color c, PieceType pt);
|
||||
void remove_piece(Square s, Color c, PieceType pt);
|
||||
void move_piece(Square from, Square to, Color c, PieceType pt);
|
||||
void put_piece(Piece pc, Square s);
|
||||
void remove_piece(Piece pc, Square s);
|
||||
void move_piece(Piece pc, Square from, Square to);
|
||||
template<bool Do>
|
||||
void do_castling(Square from, Square& to, Square& rfrom, Square& rto);
|
||||
void do_castling(Color us, Square from, Square& to, Square& rfrom, Square& rto);
|
||||
|
||||
// Data members
|
||||
Piece board[SQUARE_NB];
|
||||
Bitboard byTypeBB[PIECE_TYPE_NB];
|
||||
Bitboard byColorBB[COLOR_NB];
|
||||
int pieceCount[COLOR_NB][PIECE_TYPE_NB];
|
||||
Square pieceList[COLOR_NB][PIECE_TYPE_NB][16];
|
||||
int pieceCount[PIECE_NB];
|
||||
Square pieceList[PIECE_NB][16];
|
||||
int index[SQUARE_NB];
|
||||
int castlingRightsMask[SQUARE_NB];
|
||||
Square castlingRookSquare[CASTLING_RIGHT_NB];
|
||||
Bitboard castlingPath[CASTLING_RIGHT_NB];
|
||||
StateInfo startState;
|
||||
uint64_t nodes;
|
||||
int gamePly;
|
||||
Color sideToMove;
|
||||
@@ -211,6 +188,8 @@ private:
|
||||
bool chess960;
|
||||
};
|
||||
|
||||
extern std::ostream& operator<<(std::ostream& os, const Position& pos);
|
||||
|
||||
inline Color Position::side_to_move() const {
|
||||
return sideToMove;
|
||||
}
|
||||
@@ -252,15 +231,16 @@ inline Bitboard Position::pieces(Color c, PieceType pt1, PieceType pt2) const {
|
||||
}
|
||||
|
||||
template<PieceType Pt> inline int Position::count(Color c) const {
|
||||
return pieceCount[c][Pt];
|
||||
return pieceCount[make_piece(c, Pt)];
|
||||
}
|
||||
|
||||
template<PieceType Pt> inline const Square* Position::list(Color c) const {
|
||||
return pieceList[c][Pt];
|
||||
template<PieceType Pt> inline const Square* Position::squares(Color c) const {
|
||||
return pieceList[make_piece(c, Pt)];
|
||||
}
|
||||
|
||||
inline Square Position::king_square(Color c) const {
|
||||
return pieceList[c][KING][0];
|
||||
template<PieceType Pt> inline Square Position::square(Color c) const {
|
||||
assert(pieceCount[make_piece(c, Pt)] == 1);
|
||||
return pieceList[make_piece(c, Pt)][0];
|
||||
}
|
||||
|
||||
inline Square Position::ep_square() const {
|
||||
@@ -308,11 +288,15 @@ inline Bitboard Position::checkers() const {
|
||||
}
|
||||
|
||||
inline Bitboard Position::discovered_check_candidates() const {
|
||||
return check_blockers(sideToMove, ~sideToMove);
|
||||
return st->blockersForKing[~sideToMove] & pieces(sideToMove);
|
||||
}
|
||||
|
||||
inline Bitboard Position::pinned_pieces(Color c) const {
|
||||
return check_blockers(c, c);
|
||||
return st->blockersForKing[c] & pieces(c);
|
||||
}
|
||||
|
||||
inline Bitboard Position::check_squares(PieceType pt) const {
|
||||
return st->checkSquares[pt];
|
||||
}
|
||||
|
||||
inline bool Position::pawn_passed(Color c, Square s) const {
|
||||
@@ -356,18 +340,10 @@ inline uint64_t Position::nodes_searched() const {
|
||||
return nodes;
|
||||
}
|
||||
|
||||
inline void Position::set_nodes_searched(uint64_t n) {
|
||||
nodes = n;
|
||||
}
|
||||
|
||||
inline bool Position::opposite_bishops() const {
|
||||
return pieceCount[WHITE][BISHOP] == 1
|
||||
&& pieceCount[BLACK][BISHOP] == 1
|
||||
&& opposite_colors(pieceList[WHITE][BISHOP][0], pieceList[BLACK][BISHOP][0]);
|
||||
}
|
||||
|
||||
inline bool Position::pawn_on_7th(Color c) const {
|
||||
return pieces(c, PAWN) & rank_bb(relative_rank(c, RANK_7));
|
||||
return pieceCount[W_BISHOP] == 1
|
||||
&& pieceCount[B_BISHOP] == 1
|
||||
&& opposite_colors(square<BISHOP>(WHITE), square<BISHOP>(BLACK));
|
||||
}
|
||||
|
||||
inline bool Position::is_chess960() const {
|
||||
@@ -375,66 +351,64 @@ inline bool Position::is_chess960() const {
|
||||
}
|
||||
|
||||
inline bool Position::capture_or_promotion(Move m) const {
|
||||
|
||||
assert(is_ok(m));
|
||||
return type_of(m) != NORMAL ? type_of(m) != CASTLING : !empty(to_sq(m));
|
||||
}
|
||||
|
||||
inline bool Position::capture(Move m) const {
|
||||
|
||||
// Castling is encoded as "king captures the rook"
|
||||
assert(is_ok(m));
|
||||
// Castling is encoded as "king captures rook"
|
||||
return (!empty(to_sq(m)) && type_of(m) != CASTLING) || type_of(m) == ENPASSANT;
|
||||
}
|
||||
|
||||
inline PieceType Position::captured_piece_type() const {
|
||||
return st->capturedType;
|
||||
inline Piece Position::captured_piece() const {
|
||||
return st->capturedPiece;
|
||||
}
|
||||
|
||||
inline Thread* Position::this_thread() const {
|
||||
return thisThread;
|
||||
}
|
||||
|
||||
inline void Position::put_piece(Square s, Color c, PieceType pt) {
|
||||
inline void Position::put_piece(Piece pc, Square s) {
|
||||
|
||||
board[s] = make_piece(c, pt);
|
||||
board[s] = pc;
|
||||
byTypeBB[ALL_PIECES] |= s;
|
||||
byTypeBB[pt] |= s;
|
||||
byColorBB[c] |= s;
|
||||
index[s] = pieceCount[c][pt]++;
|
||||
pieceList[c][pt][index[s]] = s;
|
||||
pieceCount[c][ALL_PIECES]++;
|
||||
byTypeBB[type_of(pc)] |= s;
|
||||
byColorBB[color_of(pc)] |= s;
|
||||
index[s] = pieceCount[pc]++;
|
||||
pieceList[pc][index[s]] = s;
|
||||
pieceCount[make_piece(color_of(pc), ALL_PIECES)]++;
|
||||
}
|
||||
|
||||
inline void Position::move_piece(Square from, Square to, Color c, PieceType pt) {
|
||||
inline void Position::remove_piece(Piece pc, Square s) {
|
||||
|
||||
// WARNING: This is not a reversible operation. If we remove a piece in
|
||||
// do_move() and then replace it in undo_move() we will put it at the end of
|
||||
// the list and not in its original place, it means index[] and pieceList[]
|
||||
// are not invariant to a do_move() + undo_move() sequence.
|
||||
byTypeBB[ALL_PIECES] ^= s;
|
||||
byTypeBB[type_of(pc)] ^= s;
|
||||
byColorBB[color_of(pc)] ^= s;
|
||||
/* board[s] = NO_PIECE; Not needed, overwritten by the capturing one */
|
||||
Square lastSquare = pieceList[pc][--pieceCount[pc]];
|
||||
index[lastSquare] = index[s];
|
||||
pieceList[pc][index[lastSquare]] = lastSquare;
|
||||
pieceList[pc][pieceCount[pc]] = SQ_NONE;
|
||||
pieceCount[make_piece(color_of(pc), ALL_PIECES)]--;
|
||||
}
|
||||
|
||||
inline void Position::move_piece(Piece pc, Square from, Square to) {
|
||||
|
||||
// index[from] is not updated and becomes stale. This works as long as index[]
|
||||
// is accessed just by known occupied squares.
|
||||
Bitboard from_to_bb = SquareBB[from] ^ SquareBB[to];
|
||||
byTypeBB[ALL_PIECES] ^= from_to_bb;
|
||||
byTypeBB[pt] ^= from_to_bb;
|
||||
byColorBB[c] ^= from_to_bb;
|
||||
byTypeBB[type_of(pc)] ^= from_to_bb;
|
||||
byColorBB[color_of(pc)] ^= from_to_bb;
|
||||
board[from] = NO_PIECE;
|
||||
board[to] = make_piece(c, pt);
|
||||
board[to] = pc;
|
||||
index[to] = index[from];
|
||||
pieceList[c][pt][index[to]] = to;
|
||||
}
|
||||
|
||||
inline void Position::remove_piece(Square s, Color c, PieceType pt) {
|
||||
|
||||
// WARNING: This is not a reversible operation. If we remove a piece in
|
||||
// do_move() and then replace it in undo_move() we will put it at the end of
|
||||
// the list and not in its original place, it means index[] and pieceList[]
|
||||
// are not guaranteed to be invariant to a do_move() + undo_move() sequence.
|
||||
byTypeBB[ALL_PIECES] ^= s;
|
||||
byTypeBB[pt] ^= s;
|
||||
byColorBB[c] ^= s;
|
||||
/* board[s] = NO_PIECE; Not needed, overwritten by the capturing one */
|
||||
Square lastSquare = pieceList[c][pt][--pieceCount[c][pt]];
|
||||
index[lastSquare] = index[s];
|
||||
pieceList[c][pt][index[lastSquare]] = lastSquare;
|
||||
pieceList[c][pt][pieceCount[c][pt]] = SQ_NONE;
|
||||
pieceCount[c][ALL_PIECES]--;
|
||||
pieceList[pc][index[to]] = to;
|
||||
}
|
||||
|
||||
#endif // #ifndef POSITION_H_INCLUDED
|
||||
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
Stockfish is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include "types.h"
|
||||
|
||||
Value PieceValue[PHASE_NB][PIECE_NB] = {
|
||||
{ VALUE_ZERO, PawnValueMg, KnightValueMg, BishopValueMg, RookValueMg, QueenValueMg },
|
||||
{ VALUE_ZERO, PawnValueEg, KnightValueEg, BishopValueEg, RookValueEg, QueenValueEg }
|
||||
};
|
||||
|
||||
namespace PSQT {
|
||||
|
||||
#define S(mg, eg) make_score(mg, eg)
|
||||
|
||||
// Bonus[PieceType][Square / 2] contains Piece-Square scores. For each piece
|
||||
// type on a given square a (middlegame, endgame) score pair is assigned. Table
|
||||
// is defined for files A..D and white side: it is symmetric for black side and
|
||||
// second half of the files.
|
||||
const Score Bonus[][RANK_NB][int(FILE_NB) / 2] = {
|
||||
{ },
|
||||
{ // Pawn
|
||||
{ S( 0, 0), S( 0, 0), S( 0, 0), S( 0, 0) },
|
||||
{ S(-16, 7), S( 1,-4), S( 7, 8), S( 3,-2) },
|
||||
{ S(-23,-4), S( -7,-5), S( 19, 5), S(24, 4) },
|
||||
{ S(-22, 3), S(-14, 3), S( 20,-8), S(35,-3) },
|
||||
{ S(-11, 8), S( 0, 9), S( 3, 7), S(21,-6) },
|
||||
{ S(-11, 8), S(-13,-5), S( -6, 2), S(-2, 4) },
|
||||
{ S( -9, 3), S( 15,-9), S( -8, 1), S(-4,18) }
|
||||
},
|
||||
{ // Knight
|
||||
{ S(-143, -97), S(-96,-82), S(-80,-46), S(-73,-14) },
|
||||
{ S( -83, -69), S(-43,-55), S(-21,-17), S(-10, 9) },
|
||||
{ S( -71, -50), S(-22,-39), S( 0, -8), S( 9, 28) },
|
||||
{ S( -25, -41), S( 18,-25), S( 43, 7), S( 47, 38) },
|
||||
{ S( -26, -46), S( 16,-25), S( 38, 2), S( 50, 41) },
|
||||
{ S( -11, -55), S( 37,-38), S( 56, -8), S( 71, 27) },
|
||||
{ S( -62, -64), S(-17,-50), S( 5,-24), S( 14, 13) },
|
||||
{ S(-195,-110), S(-66,-90), S(-42,-50), S(-29,-13) }
|
||||
},
|
||||
{ // Bishop
|
||||
{ S(-54,-68), S(-23,-40), S(-35,-46), S(-44,-28) },
|
||||
{ S(-30,-43), S( 10,-17), S( 2,-23), S( -9, -5) },
|
||||
{ S(-19,-32), S( 17, -9), S( 11,-13), S( 1, 8) },
|
||||
{ S(-21,-36), S( 18,-13), S( 11,-15), S( 0, 7) },
|
||||
{ S(-21,-36), S( 14,-14), S( 6,-17), S( -1, 3) },
|
||||
{ S(-27,-35), S( 6,-13), S( 2,-10), S( -8, 1) },
|
||||
{ S(-33,-44), S( 7,-21), S( -4,-22), S(-12, -4) },
|
||||
{ S(-45,-65), S(-21,-42), S(-29,-46), S(-39,-27) }
|
||||
},
|
||||
{ // Rook
|
||||
{ S(-25, 0), S(-16, 0), S(-16, 0), S(-9, 0) },
|
||||
{ S(-21, 0), S( -8, 0), S( -3, 0), S( 0, 0) },
|
||||
{ S(-21, 0), S( -9, 0), S( -4, 0), S( 2, 0) },
|
||||
{ S(-22, 0), S( -6, 0), S( -1, 0), S( 2, 0) },
|
||||
{ S(-22, 0), S( -7, 0), S( 0, 0), S( 1, 0) },
|
||||
{ S(-21, 0), S( -7, 0), S( 0, 0), S( 2, 0) },
|
||||
{ S(-12, 0), S( 4, 0), S( 8, 0), S(12, 0) },
|
||||
{ S(-23, 0), S(-15, 0), S(-11, 0), S(-5, 0) }
|
||||
},
|
||||
{ // Queen
|
||||
{ S( 0,-70), S(-3,-57), S(-4,-41), S(-1,-29) },
|
||||
{ S(-4,-58), S( 6,-30), S( 9,-21), S( 8, -4) },
|
||||
{ S(-2,-39), S( 6,-17), S( 9, -7), S( 9, 5) },
|
||||
{ S(-1,-29), S( 8, -5), S(10, 9), S( 7, 17) },
|
||||
{ S(-3,-27), S( 9, -5), S( 8, 10), S( 7, 23) },
|
||||
{ S(-2,-40), S( 6,-16), S( 8,-11), S(10, 3) },
|
||||
{ S(-2,-54), S( 7,-30), S( 7,-21), S( 6, -7) },
|
||||
{ S(-1,-75), S(-4,-54), S(-1,-44), S( 0,-30) }
|
||||
},
|
||||
{ // King
|
||||
{ S(291, 28), S(344, 76), S(294,103), S(219,112) },
|
||||
{ S(289, 70), S(329,119), S(263,170), S(205,159) },
|
||||
{ S(226,109), S(271,164), S(202,195), S(136,191) },
|
||||
{ S(204,131), S(212,194), S(175,194), S(137,204) },
|
||||
{ S(177,132), S(205,187), S(143,224), S( 94,227) },
|
||||
{ S(147,118), S(188,178), S(113,199), S( 70,197) },
|
||||
{ S(116, 72), S(158,121), S( 93,142), S( 48,161) },
|
||||
{ S( 94, 30), S(120, 76), S( 78,101), S( 31,111) }
|
||||
}
|
||||
};
|
||||
|
||||
#undef S
|
||||
|
||||
Score psq[PIECE_NB][SQUARE_NB];
|
||||
|
||||
// init() initializes piece-square tables: the white halves of the tables are
|
||||
// copied from Bonus[] adding the piece value, then the black halves of the
|
||||
// tables are initialized by flipping and changing the sign of the white scores.
|
||||
void init() {
|
||||
|
||||
for (Piece pc = W_PAWN; pc <= W_KING; ++pc)
|
||||
{
|
||||
PieceValue[MG][~pc] = PieceValue[MG][pc];
|
||||
PieceValue[EG][~pc] = PieceValue[EG][pc];
|
||||
|
||||
Score v = make_score(PieceValue[MG][pc], PieceValue[EG][pc]);
|
||||
|
||||
for (Square s = SQ_A1; s <= SQ_H8; ++s)
|
||||
{
|
||||
File f = std::min(file_of(s), FILE_H - file_of(s));
|
||||
psq[ pc][ s] = v + Bonus[pc][rank_of(s)][f];
|
||||
psq[~pc][~s] = -psq[pc][s];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace PSQT
|
||||
@@ -1,98 +0,0 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 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
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
Stockfish is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef PSQTAB_H_INCLUDED
|
||||
#define PSQTAB_H_INCLUDED
|
||||
|
||||
#include "types.h"
|
||||
|
||||
#define S(mg, eg) make_score(mg, eg)
|
||||
|
||||
|
||||
/// PSQT[PieceType][Square] contains Piece-Square scores. For each piece type on
|
||||
/// a given square a (middlegame, endgame) score pair is assigned. PSQT is defined
|
||||
/// for the white side and the tables are symmetric for the black side.
|
||||
|
||||
static const Score PSQT[][SQUARE_NB] = {
|
||||
{ },
|
||||
{ // Pawn
|
||||
S( 0, 0), S( 0, 0), S( 0, 0), S( 0, 0), S(0, 0), S( 0, 0), S( 0, 0), S( 0, 0),
|
||||
S(-20, 0), S( 0, 0), S( 0, 0), S( 0, 0), S(0, 0), S( 0, 0), S( 0, 0), S(-20, 0),
|
||||
S(-20, 0), S( 0, 0), S(10, 0), S(20, 0), S(20, 0), S(10, 0), S( 0, 0), S(-20, 0),
|
||||
S(-20, 0), S( 0, 0), S(20, 0), S(40, 0), S(40, 0), S(20, 0), S( 0, 0), S(-20, 0),
|
||||
S(-20, 0), S( 0, 0), S(10, 0), S(20, 0), S(20, 0), S(10, 0), S( 0, 0), S(-20, 0),
|
||||
S(-20, 0), S( 0, 0), S( 0, 0), S( 0, 0), S(0, 0), S( 0, 0), S( 0, 0), S(-20, 0),
|
||||
S(-20, 0), S( 0, 0), S( 0, 0), S( 0, 0), S(0, 0), S( 0, 0), S( 0, 0), S(-20, 0),
|
||||
S( 0, 0), S( 0, 0), S( 0, 0), S( 0, 0), S(0, 0), S( 0, 0), S( 0, 0), S( 0, 0)
|
||||
},
|
||||
{ // Knight
|
||||
S(-144,-98), S(-109,-83), S(-85,-51), S(-73,-16), S(-73,-16), S(-85,-51), S(-109,-83), S(-144,-98),
|
||||
S( -88,-68), S( -43,-53), S(-19,-21), S( -7, 14), S( -7, 14), S(-19,-21), S( -43,-53), S( -88,-68),
|
||||
S( -69,-53), S( -24,-38), S( 0, -6), S( 12, 29), S( 12, 29), S( 0, -6), S( -24,-38), S( -69,-53),
|
||||
S( -28,-42), S( 17,-27), S( 41, 5), S( 53, 40), S( 53, 40), S( 41, 5), S( 17,-27), S( -28,-42),
|
||||
S( -30,-42), S( 15,-27), S( 39, 5), S( 51, 40), S( 51, 40), S( 39, 5), S( 15,-27), S( -30,-42),
|
||||
S( -10,-53), S( 35,-38), S( 59, -6), S( 71, 29), S( 71, 29), S( 59, -6), S( 35,-38), S( -10,-53),
|
||||
S( -64,-68), S( -19,-53), S( 5,-21), S( 17, 14), S( 17, 14), S( 5,-21), S( -19,-53), S( -64,-68),
|
||||
S(-200,-98), S( -65,-83), S(-41,-51), S(-29,-16), S(-29,-16), S(-41,-51), S( -65,-83), S(-200,-98)
|
||||
},
|
||||
{ // Bishop
|
||||
S(-54,-65), S(-27,-42), S(-34,-44), S(-43,-26), S(-43,-26), S(-34,-44), S(-27,-42), S(-54,-65),
|
||||
S(-29,-43), S( 8,-20), S( 1,-22), S( -8, -4), S( -8, -4), S( 1,-22), S( 8,-20), S(-29,-43),
|
||||
S(-20,-33), S( 17,-10), S( 10,-12), S( 1, 6), S( 1, 6), S( 10,-12), S( 17,-10), S(-20,-33),
|
||||
S(-19,-35), S( 18,-12), S( 11,-14), S( 2, 4), S( 2, 4), S( 11,-14), S( 18,-12), S(-19,-35),
|
||||
S(-22,-35), S( 15,-12), S( 8,-14), S( -1, 4), S( -1, 4), S( 8,-14), S( 15,-12), S(-22,-35),
|
||||
S(-28,-33), S( 9,-10), S( 2,-12), S( -7, 6), S( -7, 6), S( 2,-12), S( 9,-10), S(-28,-33),
|
||||
S(-32,-43), S( 5,-20), S( -2,-22), S(-11, -4), S(-11, -4), S( -2,-22), S( 5,-20), S(-32,-43),
|
||||
S(-49,-65), S(-22,-42), S(-29,-44), S(-38,-26), S(-38,-26), S(-29,-44), S(-22,-42), S(-49,-65)
|
||||
},
|
||||
{ // Rook
|
||||
S(-22, 3), S(-17, 3), S(-12, 3), S(-8, 3), S(-8, 3), S(-12, 3), S(-17, 3), S(-22, 3),
|
||||
S(-22, 3), S( -7, 3), S( -2, 3), S( 2, 3), S( 2, 3), S( -2, 3), S( -7, 3), S(-22, 3),
|
||||
S(-22, 3), S( -7, 3), S( -2, 3), S( 2, 3), S( 2, 3), S( -2, 3), S( -7, 3), S(-22, 3),
|
||||
S(-22, 3), S( -7, 3), S( -2, 3), S( 2, 3), S( 2, 3), S( -2, 3), S( -7, 3), S(-22, 3),
|
||||
S(-22, 3), S( -7, 3), S( -2, 3), S( 2, 3), S( 2, 3), S( -2, 3), S( -7, 3), S(-22, 3),
|
||||
S(-22, 3), S( -7, 3), S( -2, 3), S( 2, 3), S( 2, 3), S( -2, 3), S( -7, 3), S(-22, 3),
|
||||
S(-11, 3), S( 4, 3), S( 9, 3), S(13, 3), S(13, 3), S( 9, 3), S( 4, 3), S(-11, 3),
|
||||
S(-22, 3), S(-17, 3), S(-12, 3), S(-8, 3), S(-8, 3), S(-12, 3), S(-17, 3), S(-22, 3)
|
||||
},
|
||||
{ // Queen
|
||||
S(-2,-80), S(-2,-54), S(-2,-42), S(-2,-30), S(-2,-30), S(-2,-42), S(-2,-54), S(-2,-80),
|
||||
S(-2,-54), S( 8,-30), S( 8,-18), S( 8, -6), S( 8, -6), S( 8,-18), S( 8,-30), S(-2,-54),
|
||||
S(-2,-42), S( 8,-18), S( 8, -6), S( 8, 6), S( 8, 6), S( 8, -6), S( 8,-18), S(-2,-42),
|
||||
S(-2,-30), S( 8, -6), S( 8, 6), S( 8, 18), S( 8, 18), S( 8, 6), S( 8, -6), S(-2,-30),
|
||||
S(-2,-30), S( 8, -6), S( 8, 6), S( 8, 18), S( 8, 18), S( 8, 6), S( 8, -6), S(-2,-30),
|
||||
S(-2,-42), S( 8,-18), S( 8, -6), S( 8, 6), S( 8, 6), S( 8, -6), S( 8,-18), S(-2,-42),
|
||||
S(-2,-54), S( 8,-30), S( 8,-18), S( 8, -6), S( 8, -6), S( 8,-18), S( 8,-30), S(-2,-54),
|
||||
S(-2,-80), S(-2,-54), S(-2,-42), S(-2,-30), S(-2,-30), S(-2,-42), S(-2,-54), S(-2,-80)
|
||||
},
|
||||
{ // King
|
||||
S(298, 27), S(332, 81), S(273,108), S(225,116), S(225,116), S(273,108), S(332, 81), S(298, 27),
|
||||
S(287, 74), S(321,128), S(262,155), S(214,163), S(214,163), S(262,155), S(321,128), S(287, 74),
|
||||
S(224,111), S(258,165), S(199,192), S(151,200), S(151,200), S(199,192), S(258,165), S(224,111),
|
||||
S(196,135), S(230,189), S(171,216), S(123,224), S(123,224), S(171,216), S(230,189), S(196,135),
|
||||
S(173,135), S(207,189), S(148,216), S(100,224), S(100,224), S(148,216), S(207,189), S(173,135),
|
||||
S(146,111), S(180,165), S(121,192), S( 73,200), S( 73,200), S(121,192), S(180,165), S(146,111),
|
||||
S(119, 74), S(153,128), S( 94,155), S( 46,163), S( 46,163), S( 94,155), S(153,128), S(119, 74),
|
||||
S( 98, 27), S(132, 81), S( 73,108), S( 25,116), S( 25,116), S( 73,108), S(132, 81), S( 98, 27)
|
||||
}
|
||||
};
|
||||
|
||||
#undef S
|
||||
|
||||
#endif // #ifndef PSQTAB_H_INCLUDED
|
||||
+824
-869
File diff suppressed because it is too large
Load Diff
+26
-29
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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
|
||||
@@ -20,15 +21,14 @@
|
||||
#ifndef SEARCH_H_INCLUDED
|
||||
#define SEARCH_H_INCLUDED
|
||||
|
||||
#include <memory> // For std::auto_ptr
|
||||
#include <stack>
|
||||
#include <atomic>
|
||||
#include <vector>
|
||||
|
||||
#include "misc.h"
|
||||
#include "position.h"
|
||||
#include "movepick.h"
|
||||
#include "types.h"
|
||||
|
||||
struct SplitPoint;
|
||||
class Position;
|
||||
|
||||
namespace Search {
|
||||
|
||||
@@ -37,37 +37,38 @@ namespace Search {
|
||||
/// its own array of Stack objects, indexed by the current ply.
|
||||
|
||||
struct Stack {
|
||||
SplitPoint* splitPoint;
|
||||
Move* pv;
|
||||
int ply;
|
||||
Move currentMove;
|
||||
Move ttMove;
|
||||
Move excludedMove;
|
||||
Move killers[2];
|
||||
Depth reduction;
|
||||
Value staticEval;
|
||||
Value history;
|
||||
bool skipEarlyPruning;
|
||||
int moveCount;
|
||||
CounterMoveStats* counterMoves;
|
||||
};
|
||||
|
||||
|
||||
/// RootMove struct is used for moves at the root of the tree. For each root move
|
||||
/// we store a score and a PV (really a refutation in the case of moves which
|
||||
/// fail low). Score is normally set at -VALUE_INFINITE for all non-pv moves.
|
||||
|
||||
struct RootMove {
|
||||
|
||||
RootMove(Move m) : score(-VALUE_INFINITE), previousScore(-VALUE_INFINITE), pv(1, m) {}
|
||||
explicit RootMove(Move m) : pv(1, m) {}
|
||||
|
||||
bool operator<(const RootMove& m) const { return score > m.score; } // Ascending sort
|
||||
bool operator<(const RootMove& m) const { return m.score < score; } // Descending sort
|
||||
bool operator==(const Move& m) const { return pv[0] == m; }
|
||||
void insert_pv_in_tt(Position& pos);
|
||||
Move extract_ponder_from_tt(Position& pos);
|
||||
bool extract_ponder_from_tt(Position& pos);
|
||||
|
||||
Value score;
|
||||
Value previousScore;
|
||||
Value score = -VALUE_INFINITE;
|
||||
Value previousScore = -VALUE_INFINITE;
|
||||
std::vector<Move> pv;
|
||||
};
|
||||
|
||||
typedef std::vector<RootMove> RootMoveVector;
|
||||
typedef std::vector<RootMove> RootMoves;
|
||||
|
||||
|
||||
/// LimitsType struct stores information sent by GUI about available time to
|
||||
/// search the current move, maximum depth/time, if we are in analysis mode or
|
||||
@@ -76,8 +77,8 @@ typedef std::vector<RootMove> RootMoveVector;
|
||||
struct LimitsType {
|
||||
|
||||
LimitsType() { // Init explicitly due to broken value-initialization of non POD in MSVC
|
||||
nodes = time[WHITE] = time[BLACK] = inc[WHITE] = inc[BLACK] = movestogo =
|
||||
depth = movetime = mate = infinite = ponder = 0;
|
||||
nodes = time[WHITE] = time[BLACK] = inc[WHITE] = inc[BLACK] =
|
||||
npmsec = movestogo = depth = movetime = mate = infinite = ponder = 0;
|
||||
}
|
||||
|
||||
bool use_time_management() const {
|
||||
@@ -85,29 +86,25 @@ struct LimitsType {
|
||||
}
|
||||
|
||||
std::vector<Move> searchmoves;
|
||||
int time[COLOR_NB], inc[COLOR_NB], movestogo, depth, movetime, mate, infinite, ponder;
|
||||
int time[COLOR_NB], inc[COLOR_NB], npmsec, movestogo, depth, movetime, mate, infinite, ponder;
|
||||
int64_t nodes;
|
||||
TimePoint startTime;
|
||||
};
|
||||
|
||||
/// The SignalsType struct stores volatile flags updated during the search
|
||||
/// typically in an async fashion e.g. to stop the search by the GUI.
|
||||
|
||||
/// SignalsType struct stores atomic flags updated during the search, typically
|
||||
/// in an async fashion e.g. to stop the search by the GUI.
|
||||
|
||||
struct SignalsType {
|
||||
bool stop, stopOnPonderhit, firstRootMove, failedLowAtRoot;
|
||||
std::atomic_bool stop, stopOnPonderhit;
|
||||
};
|
||||
|
||||
typedef std::auto_ptr<std::stack<StateInfo> > StateStackPtr;
|
||||
|
||||
extern volatile SignalsType Signals;
|
||||
extern SignalsType Signals;
|
||||
extern LimitsType Limits;
|
||||
extern RootMoveVector RootMoves;
|
||||
extern Position RootPos;
|
||||
extern Time::point SearchTime;
|
||||
extern StateStackPtr SetupStates;
|
||||
|
||||
void init();
|
||||
void think();
|
||||
template<bool Root> uint64_t perft(Position& pos, Depth depth);
|
||||
void clear();
|
||||
template<bool Root = true> uint64_t perft(Position& pos, Depth depth);
|
||||
|
||||
} // namespace Search
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
This file may be redistributed and/or modified without restrictions.
|
||||
|
||||
tbcore.c contains engine-independent routines of the tablebase probing code.
|
||||
This file should not need to much adaptation to add tablebase probing to
|
||||
This file should not need too much adaptation to add tablebase probing to
|
||||
a particular engine, provided the engine is written in C or C++.
|
||||
*/
|
||||
|
||||
|
||||
+34
-41
@@ -7,13 +7,14 @@
|
||||
this code to other chess engines.
|
||||
*/
|
||||
|
||||
#define NOMINMAX
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include "../position.h"
|
||||
#include "../movegen.h"
|
||||
#include "../bitboard.h"
|
||||
#include "../search.h"
|
||||
#include "../bitcount.h"
|
||||
|
||||
#include "tbprobe.h"
|
||||
#include "tbcore.h"
|
||||
@@ -21,7 +22,7 @@
|
||||
#include "tbcore.cpp"
|
||||
|
||||
namespace Zobrist {
|
||||
extern Key psq[COLOR_NB][PIECE_TYPE_NB][SQUARE_NB];
|
||||
extern Key psq[PIECE_NB][SQUARE_NB];
|
||||
}
|
||||
|
||||
int Tablebases::MaxCardinality = 0;
|
||||
@@ -37,12 +38,12 @@ static void prt_str(Position& pos, char *str, int mirror)
|
||||
|
||||
color = !mirror ? WHITE : BLACK;
|
||||
for (pt = KING; pt >= PAWN; --pt)
|
||||
for (i = popcount<Max15>(pos.pieces(color, pt)); i > 0; i--)
|
||||
for (i = popcount(pos.pieces(color, pt)); i > 0; i--)
|
||||
*str++ = pchr[6 - pt];
|
||||
*str++ = 'v';
|
||||
color = ~color;
|
||||
for (pt = KING; pt >= PAWN; --pt)
|
||||
for (i = popcount<Max15>(pos.pieces(color, pt)); i > 0; i--)
|
||||
for (i = popcount(pos.pieces(color, pt)); i > 0; i--)
|
||||
*str++ = pchr[6 - pt];
|
||||
*str++ = 0;
|
||||
}
|
||||
@@ -58,12 +59,12 @@ static uint64 calc_key(Position& pos, int mirror)
|
||||
|
||||
color = !mirror ? WHITE : BLACK;
|
||||
for (pt = PAWN; pt <= KING; ++pt)
|
||||
for (i = popcount<Max15>(pos.pieces(color, pt)); i > 0; i--)
|
||||
key ^= Zobrist::psq[WHITE][pt][i - 1];
|
||||
for (i = popcount(pos.pieces(color, pt)); i > 0; i--)
|
||||
key ^= Zobrist::psq[make_piece(WHITE, pt)][i - 1];
|
||||
color = ~color;
|
||||
for (pt = PAWN; pt <= KING; ++pt)
|
||||
for (i = popcount<Max15>(pos.pieces(color, pt)); i > 0; i--)
|
||||
key ^= Zobrist::psq[BLACK][pt][i - 1];
|
||||
for (i = popcount(pos.pieces(color, pt)); i > 0; i--)
|
||||
key ^= Zobrist::psq[make_piece(BLACK, pt)][i - 1];
|
||||
|
||||
return key;
|
||||
}
|
||||
@@ -82,11 +83,11 @@ static uint64 calc_key_from_pcs(int *pcs, int mirror)
|
||||
color = !mirror ? 0 : 8;
|
||||
for (pt = PAWN; pt <= KING; ++pt)
|
||||
for (i = 0; i < pcs[color + pt]; i++)
|
||||
key ^= Zobrist::psq[WHITE][pt][i];
|
||||
key ^= Zobrist::psq[make_piece(WHITE, pt)][i];
|
||||
color ^= 8;
|
||||
for (pt = PAWN; pt <= KING; ++pt)
|
||||
for (i = 0; i < pcs[color + pt]; i++)
|
||||
key ^= Zobrist::psq[BLACK][pt][i];
|
||||
key ^= Zobrist::psq[make_piece(BLACK, pt)][i];
|
||||
|
||||
return key;
|
||||
}
|
||||
@@ -122,7 +123,7 @@ static int probe_wdl_table(Position& pos, int *success)
|
||||
key = pos.material_key();
|
||||
|
||||
// Test for KvK.
|
||||
if (key == (Zobrist::psq[WHITE][KING][0] ^ Zobrist::psq[BLACK][KING][0]))
|
||||
if (key == (Zobrist::psq[W_KING][0] ^ Zobrist::psq[B_KING][0]))
|
||||
return 0;
|
||||
|
||||
ptr2 = TB_hash[key >> (64 - TBHASHBITS)];
|
||||
@@ -360,14 +361,12 @@ static int probe_ab(Position& pos, int alpha, int beta, int *success)
|
||||
} else
|
||||
end = generate<EVASIONS>(pos, stack);
|
||||
|
||||
CheckInfo ci(pos);
|
||||
|
||||
for (moves = stack; moves < end; moves++) {
|
||||
Move capture = moves->move;
|
||||
if (!pos.capture(capture) || type_of(capture) == ENPASSANT
|
||||
|| !pos.legal(capture, ci.pinned))
|
||||
|| !pos.legal(capture))
|
||||
continue;
|
||||
pos.do_move(capture, st, ci, pos.gives_check(capture, ci));
|
||||
pos.do_move(capture, st, pos.gives_check(capture));
|
||||
v = -probe_ab(pos, -beta, -alpha, success);
|
||||
pos.undo_move(capture);
|
||||
if (*success == 0) return 0;
|
||||
@@ -423,14 +422,12 @@ int Tablebases::probe_wdl(Position& pos, int *success)
|
||||
else
|
||||
end = generate<EVASIONS>(pos, stack);
|
||||
|
||||
CheckInfo ci(pos);
|
||||
|
||||
for (moves = stack; moves < end; moves++) {
|
||||
Move capture = moves->move;
|
||||
if (type_of(capture) != ENPASSANT
|
||||
|| !pos.legal(capture, ci.pinned))
|
||||
|| !pos.legal(capture))
|
||||
continue;
|
||||
pos.do_move(capture, st, ci, pos.gives_check(capture, ci));
|
||||
pos.do_move(capture, st, pos.gives_check(capture));
|
||||
int v0 = -probe_ab(pos, -2, 2, success);
|
||||
pos.undo_move(capture);
|
||||
if (*success == 0) return 0;
|
||||
@@ -443,13 +440,13 @@ int Tablebases::probe_wdl(Position& pos, int *success)
|
||||
for (moves = stack; moves < end; moves++) {
|
||||
Move capture = moves->move;
|
||||
if (type_of(capture) == ENPASSANT) continue;
|
||||
if (pos.legal(capture, ci.pinned)) break;
|
||||
if (pos.legal(capture)) break;
|
||||
}
|
||||
if (moves == end && !pos.checkers()) {
|
||||
end = generate<QUIETS>(pos, end);
|
||||
for (; moves < end; moves++) {
|
||||
Move move = moves->move;
|
||||
if (pos.legal(move, ci.pinned))
|
||||
if (pos.legal(move))
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -478,7 +475,6 @@ static int probe_dtz_no_ep(Position& pos, int *success)
|
||||
ExtMove stack[192];
|
||||
ExtMove *moves, *end = NULL;
|
||||
StateInfo st;
|
||||
CheckInfo ci(pos);
|
||||
|
||||
if (wdl > 0) {
|
||||
// Generate at least all legal non-capturing pawn moves
|
||||
@@ -491,10 +487,10 @@ static int probe_dtz_no_ep(Position& pos, int *success)
|
||||
for (moves = stack; moves < end; moves++) {
|
||||
Move move = moves->move;
|
||||
if (type_of(pos.moved_piece(move)) != PAWN || pos.capture(move)
|
||||
|| !pos.legal(move, ci.pinned))
|
||||
|| !pos.legal(move))
|
||||
continue;
|
||||
pos.do_move(move, st, ci, pos.gives_check(move, ci));
|
||||
int v = -probe_ab(pos, -2, -wdl + 1, success);
|
||||
pos.do_move(move, st, pos.gives_check(move));
|
||||
int v = -Tablebases::probe_wdl(pos, success);
|
||||
pos.undo_move(move);
|
||||
if (*success == 0) return 0;
|
||||
if (v == wdl)
|
||||
@@ -513,9 +509,9 @@ static int probe_dtz_no_ep(Position& pos, int *success)
|
||||
for (moves = stack; moves < end; moves++) {
|
||||
Move move = moves->move;
|
||||
if (pos.capture(move) || type_of(pos.moved_piece(move)) == PAWN
|
||||
|| !pos.legal(move, ci.pinned))
|
||||
|| !pos.legal(move))
|
||||
continue;
|
||||
pos.do_move(move, st, ci, pos.gives_check(move, ci));
|
||||
pos.do_move(move, st, pos.gives_check(move));
|
||||
int v = -Tablebases::probe_dtz(pos, success);
|
||||
pos.undo_move(move);
|
||||
if (*success == 0) return 0;
|
||||
@@ -532,9 +528,9 @@ static int probe_dtz_no_ep(Position& pos, int *success)
|
||||
for (moves = stack; moves < end; moves++) {
|
||||
int v;
|
||||
Move move = moves->move;
|
||||
if (!pos.legal(move, ci.pinned))
|
||||
if (!pos.legal(move))
|
||||
continue;
|
||||
pos.do_move(move, st, ci, pos.gives_check(move, ci));
|
||||
pos.do_move(move, st, pos.gives_check(move));
|
||||
if (st.rule50 == 0) {
|
||||
if (wdl == -2) v = -1;
|
||||
else {
|
||||
@@ -603,14 +599,13 @@ int Tablebases::probe_dtz(Position& pos, int *success)
|
||||
end = generate<CAPTURES>(pos, stack);
|
||||
else
|
||||
end = generate<EVASIONS>(pos, stack);
|
||||
CheckInfo ci(pos);
|
||||
|
||||
for (moves = stack; moves < end; moves++) {
|
||||
Move capture = moves->move;
|
||||
if (type_of(capture) != ENPASSANT
|
||||
|| !pos.legal(capture, ci.pinned))
|
||||
|| !pos.legal(capture))
|
||||
continue;
|
||||
pos.do_move(capture, st, ci, pos.gives_check(capture, ci));
|
||||
pos.do_move(capture, st, pos.gives_check(capture));
|
||||
int v0 = -probe_ab(pos, -2, 2, success);
|
||||
pos.undo_move(capture);
|
||||
if (*success == 0) return 0;
|
||||
@@ -622,7 +617,7 @@ int Tablebases::probe_dtz(Position& pos, int *success)
|
||||
if (v1 >= 0)
|
||||
v = v1;
|
||||
} else if (v < 0) {
|
||||
if (v1 >= 0 || v1 < 100)
|
||||
if (v1 >= 0 || v1 < -100)
|
||||
v = v1;
|
||||
} else if (v > 100) {
|
||||
if (v1 > 0)
|
||||
@@ -636,13 +631,13 @@ int Tablebases::probe_dtz(Position& pos, int *success)
|
||||
for (moves = stack; moves < end; moves++) {
|
||||
Move move = moves->move;
|
||||
if (type_of(move) == ENPASSANT) continue;
|
||||
if (pos.legal(move, ci.pinned)) break;
|
||||
if (pos.legal(move)) break;
|
||||
}
|
||||
if (moves == end && !pos.checkers()) {
|
||||
end = generate<QUIETS>(pos, end);
|
||||
for (; moves < end; moves++) {
|
||||
Move move = moves->move;
|
||||
if (pos.legal(move, ci.pinned))
|
||||
if (pos.legal(move))
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -687,7 +682,7 @@ static Value wdl_to_Value[5] = {
|
||||
//
|
||||
// A return value false indicates that not all probes were successful and that
|
||||
// no moves were filtered out.
|
||||
bool Tablebases::root_probe(Position& pos, Search::RootMoveVector& rootMoves, Value& score)
|
||||
bool Tablebases::root_probe(Position& pos, Search::RootMoves& rootMoves, Value& score)
|
||||
{
|
||||
int success;
|
||||
|
||||
@@ -695,12 +690,11 @@ bool Tablebases::root_probe(Position& pos, Search::RootMoveVector& rootMoves, Va
|
||||
if (!success) return false;
|
||||
|
||||
StateInfo st;
|
||||
CheckInfo ci(pos);
|
||||
|
||||
// Probe each move.
|
||||
for (size_t i = 0; i < rootMoves.size(); i++) {
|
||||
Move move = rootMoves[i].pv[0];
|
||||
pos.do_move(move, st, ci, pos.gives_check(move, ci));
|
||||
pos.do_move(move, st, pos.gives_check(move));
|
||||
int v = 0;
|
||||
if (pos.checkers() && dtz > 0) {
|
||||
ExtMove s[192];
|
||||
@@ -794,7 +788,7 @@ bool Tablebases::root_probe(Position& pos, Search::RootMoveVector& rootMoves, Va
|
||||
//
|
||||
// A return value false indicates that not all probes were successful and that
|
||||
// no moves were filtered out.
|
||||
bool Tablebases::root_probe_wdl(Position& pos, Search::RootMoveVector& rootMoves, Value& score)
|
||||
bool Tablebases::root_probe_wdl(Position& pos, Search::RootMoves& rootMoves, Value& score)
|
||||
{
|
||||
int success;
|
||||
|
||||
@@ -803,14 +797,13 @@ bool Tablebases::root_probe_wdl(Position& pos, Search::RootMoveVector& rootMoves
|
||||
score = wdl_to_Value[wdl + 2];
|
||||
|
||||
StateInfo st;
|
||||
CheckInfo ci(pos);
|
||||
|
||||
int best = -2;
|
||||
|
||||
// Probe each move.
|
||||
for (size_t i = 0; i < rootMoves.size(); i++) {
|
||||
Move move = rootMoves[i].pv[0];
|
||||
pos.do_move(move, st, ci, pos.gives_check(move, ci));
|
||||
pos.do_move(move, st, pos.gives_check(move));
|
||||
int v = -Tablebases::probe_wdl(pos, &success);
|
||||
pos.undo_move(move);
|
||||
if (!success) return false;
|
||||
|
||||
@@ -10,8 +10,9 @@ extern int MaxCardinality;
|
||||
void init(const std::string& path);
|
||||
int probe_wdl(Position& pos, int *success);
|
||||
int probe_dtz(Position& pos, int *success);
|
||||
bool root_probe(Position& pos, Search::RootMoveVector& rootMoves, Value& score);
|
||||
bool root_probe_wdl(Position& pos, Search::RootMoveVector& rootMoves, Value& score);
|
||||
bool root_probe(Position& pos, Search::RootMoves& rootMoves, Value& score);
|
||||
bool root_probe_wdl(Position& pos, Search::RootMoves& rootMoves, Value& score);
|
||||
void filter_root_moves(Position& pos, Search::RootMoves& rootMoves);
|
||||
|
||||
}
|
||||
|
||||
|
||||
+112
-274
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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
|
||||
@@ -24,362 +25,199 @@
|
||||
#include "search.h"
|
||||
#include "thread.h"
|
||||
#include "uci.h"
|
||||
|
||||
using namespace Search;
|
||||
#include "syzygy/tbprobe.h"
|
||||
|
||||
ThreadPool Threads; // Global object
|
||||
|
||||
extern void check_time();
|
||||
/// Thread constructor launches the thread and then waits until it goes to sleep
|
||||
/// in idle_loop().
|
||||
|
||||
namespace {
|
||||
Thread::Thread() {
|
||||
|
||||
// start_routine() is the C function which is called when a new thread
|
||||
// is launched. It is a wrapper to the virtual function idle_loop().
|
||||
|
||||
extern "C" { long start_routine(ThreadBase* th) { th->idle_loop(); return 0; } }
|
||||
|
||||
|
||||
// Helpers to launch a thread after creation and joining before delete. Must be
|
||||
// outside Thread c'tor and d'tor because the object must be fully initialized
|
||||
// when start_routine (and hence virtual idle_loop) is called and when joining.
|
||||
|
||||
template<typename T> T* new_thread() {
|
||||
T* th = new T();
|
||||
thread_create(th->handle, start_routine, th); // Will go to sleep
|
||||
return th;
|
||||
}
|
||||
|
||||
void delete_thread(ThreadBase* th) {
|
||||
|
||||
th->mutex.lock();
|
||||
th->exit = true; // Search must be already finished
|
||||
th->mutex.unlock();
|
||||
|
||||
th->notify_one();
|
||||
thread_join(th->handle); // Wait for thread termination
|
||||
delete th;
|
||||
}
|
||||
resetCalls = exit = false;
|
||||
maxPly = callsCnt = 0;
|
||||
tbHits = 0;
|
||||
history.clear();
|
||||
counterMoves.clear();
|
||||
idx = Threads.size(); // Start from 0
|
||||
|
||||
std::unique_lock<Mutex> lk(mutex);
|
||||
searching = true;
|
||||
nativeThread = std::thread(&Thread::idle_loop, this);
|
||||
sleepCondition.wait(lk, [&]{ return !searching; });
|
||||
}
|
||||
|
||||
|
||||
// ThreadBase::notify_one() wakes up the thread when there is some work to do
|
||||
/// Thread destructor waits for thread termination before returning
|
||||
|
||||
void ThreadBase::notify_one() {
|
||||
Thread::~Thread() {
|
||||
|
||||
mutex.lock();
|
||||
exit = true;
|
||||
sleepCondition.notify_one();
|
||||
mutex.unlock();
|
||||
nativeThread.join();
|
||||
}
|
||||
|
||||
|
||||
// ThreadBase::wait_for() set the thread to sleep until 'condition' turns true
|
||||
/// Thread::wait_for_search_finished() waits on sleep condition
|
||||
/// until not searching
|
||||
|
||||
void ThreadBase::wait_for(volatile const bool& condition) {
|
||||
void Thread::wait_for_search_finished() {
|
||||
|
||||
mutex.lock();
|
||||
while (!condition) sleepCondition.wait(mutex);
|
||||
mutex.unlock();
|
||||
std::unique_lock<Mutex> lk(mutex);
|
||||
sleepCondition.wait(lk, [&]{ return !searching; });
|
||||
}
|
||||
|
||||
|
||||
// Thread c'tor makes some init but does not launch any execution thread that
|
||||
// will be started only when c'tor returns.
|
||||
/// Thread::wait() waits on sleep condition until condition is true
|
||||
|
||||
Thread::Thread() /* : splitPoints() */ { // Initialization of non POD broken in MSVC
|
||||
void Thread::wait(std::atomic_bool& condition) {
|
||||
|
||||
searching = false;
|
||||
maxPly = splitPointsSize = 0;
|
||||
activeSplitPoint = NULL;
|
||||
activePosition = NULL;
|
||||
idx = Threads.size(); // Starts from 0
|
||||
std::unique_lock<Mutex> lk(mutex);
|
||||
sleepCondition.wait(lk, [&]{ return bool(condition); });
|
||||
}
|
||||
|
||||
|
||||
// Thread::cutoff_occurred() checks whether a beta cutoff has occurred in the
|
||||
// current active split point, or in some ancestor of the split point.
|
||||
/// Thread::start_searching() wakes up the thread that will start the search
|
||||
|
||||
bool Thread::cutoff_occurred() const {
|
||||
void Thread::start_searching(bool resume) {
|
||||
|
||||
for (SplitPoint* sp = activeSplitPoint; sp; sp = sp->parentSplitPoint)
|
||||
if (sp->cutoff)
|
||||
return true;
|
||||
std::unique_lock<Mutex> lk(mutex);
|
||||
|
||||
return false;
|
||||
if (!resume)
|
||||
searching = true;
|
||||
|
||||
sleepCondition.notify_one();
|
||||
}
|
||||
|
||||
|
||||
// Thread::available_to() checks whether the thread is available to help the
|
||||
// thread 'master' at a split point. An obvious requirement is that thread must
|
||||
// be idle. With more than two threads, this is not sufficient: If the thread is
|
||||
// the master of some split point, it is only available as a slave to the slaves
|
||||
// which are busy searching the split point at the top of slave's split point
|
||||
// stack (the "helpful master concept" in YBWC terminology).
|
||||
/// Thread::idle_loop() is where the thread is parked when it has no work to do
|
||||
|
||||
bool Thread::available_to(const Thread* master) const {
|
||||
|
||||
if (searching)
|
||||
return false;
|
||||
|
||||
// Make a local copy to be sure it doesn't become zero under our feet while
|
||||
// testing next condition and so leading to an out of bounds access.
|
||||
const int size = splitPointsSize;
|
||||
|
||||
// No split points means that the thread is available as a slave for any
|
||||
// other thread otherwise apply the "helpful master" concept if possible.
|
||||
return !size || splitPoints[size - 1].slavesMask.test(master->idx);
|
||||
}
|
||||
|
||||
|
||||
// Thread::split() does the actual work of distributing the work at a node between
|
||||
// several available threads. If it does not succeed in splitting the node
|
||||
// (because no idle threads are available), the function immediately returns.
|
||||
// If splitting is possible, a SplitPoint object is initialized with all the
|
||||
// data that must be copied to the helper threads and then helper threads are
|
||||
// informed that they have been assigned work. This will cause them to instantly
|
||||
// leave their idle loops and call search(). When all threads have returned from
|
||||
// search() then split() returns.
|
||||
|
||||
void Thread::split(Position& pos, Stack* ss, Value alpha, Value beta, Value* bestValue,
|
||||
Move* bestMove, Depth depth, int moveCount,
|
||||
MovePicker* movePicker, int nodeType, bool cutNode) {
|
||||
|
||||
assert(searching);
|
||||
assert(-VALUE_INFINITE < *bestValue && *bestValue <= alpha && alpha < beta && beta <= VALUE_INFINITE);
|
||||
assert(depth >= Threads.minimumSplitDepth);
|
||||
assert(splitPointsSize < MAX_SPLITPOINTS_PER_THREAD);
|
||||
|
||||
// Pick and init the next available split point
|
||||
SplitPoint& sp = splitPoints[splitPointsSize];
|
||||
|
||||
sp.masterThread = this;
|
||||
sp.parentSplitPoint = activeSplitPoint;
|
||||
sp.slavesMask = 0, sp.slavesMask.set(idx);
|
||||
sp.depth = depth;
|
||||
sp.bestValue = *bestValue;
|
||||
sp.bestMove = *bestMove;
|
||||
sp.alpha = alpha;
|
||||
sp.beta = beta;
|
||||
sp.nodeType = nodeType;
|
||||
sp.cutNode = cutNode;
|
||||
sp.movePicker = movePicker;
|
||||
sp.moveCount = moveCount;
|
||||
sp.pos = &pos;
|
||||
sp.nodes = 0;
|
||||
sp.cutoff = false;
|
||||
sp.ss = ss;
|
||||
|
||||
// Try to allocate available threads and ask them to start searching setting
|
||||
// 'searching' flag. This must be done under lock protection to avoid concurrent
|
||||
// allocation of the same slave by another master.
|
||||
Threads.mutex.lock();
|
||||
sp.mutex.lock();
|
||||
|
||||
sp.allSlavesSearching = true; // Must be set under lock protection
|
||||
++splitPointsSize;
|
||||
activeSplitPoint = &sp;
|
||||
activePosition = NULL;
|
||||
|
||||
Thread* slave;
|
||||
|
||||
while ((slave = Threads.available_slave(this)) != NULL)
|
||||
{
|
||||
sp.slavesMask.set(slave->idx);
|
||||
slave->activeSplitPoint = &sp;
|
||||
slave->searching = true; // Slave leaves idle_loop()
|
||||
slave->notify_one(); // Could be sleeping
|
||||
}
|
||||
|
||||
// Everything is set up. The master thread enters the idle loop, from which
|
||||
// it will instantly launch a search, because its 'searching' flag is set.
|
||||
// The thread will return from the idle loop when all slaves have finished
|
||||
// their work at this split point.
|
||||
sp.mutex.unlock();
|
||||
Threads.mutex.unlock();
|
||||
|
||||
Thread::idle_loop(); // Force a call to base class idle_loop()
|
||||
|
||||
// In the helpful master concept, a master can help only a sub-tree of its
|
||||
// split point and because everything is finished here, it's not possible
|
||||
// for the master to be booked.
|
||||
assert(!searching);
|
||||
assert(!activePosition);
|
||||
|
||||
// We have returned from the idle loop, which means that all threads are
|
||||
// finished. Note that setting 'searching' and decreasing splitPointsSize must
|
||||
// be done under lock protection to avoid a race with Thread::available_to().
|
||||
Threads.mutex.lock();
|
||||
sp.mutex.lock();
|
||||
|
||||
searching = true;
|
||||
--splitPointsSize;
|
||||
activeSplitPoint = sp.parentSplitPoint;
|
||||
activePosition = &pos;
|
||||
pos.set_nodes_searched(pos.nodes_searched() + sp.nodes);
|
||||
*bestMove = sp.bestMove;
|
||||
*bestValue = sp.bestValue;
|
||||
|
||||
sp.mutex.unlock();
|
||||
Threads.mutex.unlock();
|
||||
}
|
||||
|
||||
|
||||
// TimerThread::idle_loop() is where the timer thread waits Resolution milliseconds
|
||||
// and then calls check_time(). When not searching, thread sleeps until it's woken up.
|
||||
|
||||
void TimerThread::idle_loop() {
|
||||
void Thread::idle_loop() {
|
||||
|
||||
while (!exit)
|
||||
{
|
||||
mutex.lock();
|
||||
std::unique_lock<Mutex> lk(mutex);
|
||||
|
||||
searching = false;
|
||||
|
||||
while (!searching && !exit)
|
||||
{
|
||||
sleepCondition.notify_one(); // Wake up any waiting thread
|
||||
sleepCondition.wait(lk);
|
||||
}
|
||||
|
||||
lk.unlock();
|
||||
|
||||
if (!exit)
|
||||
sleepCondition.wait_for(mutex, run ? Resolution : INT_MAX);
|
||||
|
||||
mutex.unlock();
|
||||
|
||||
if (run)
|
||||
check_time();
|
||||
search();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MainThread::idle_loop() is where the main thread is parked waiting to be started
|
||||
// when there is a new search. The main thread will launch all the slave threads.
|
||||
|
||||
void MainThread::idle_loop() {
|
||||
|
||||
while (!exit)
|
||||
{
|
||||
mutex.lock();
|
||||
|
||||
thinking = false;
|
||||
|
||||
while (!thinking && !exit)
|
||||
{
|
||||
Threads.sleepCondition.notify_one(); // Wake up the UI thread if needed
|
||||
sleepCondition.wait(mutex);
|
||||
}
|
||||
|
||||
mutex.unlock();
|
||||
|
||||
if (!exit)
|
||||
{
|
||||
searching = true;
|
||||
|
||||
Search::think();
|
||||
|
||||
assert(searching);
|
||||
|
||||
searching = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ThreadPool::init() is called at startup to create and launch requested threads,
|
||||
// that will go immediately to sleep. We cannot use a c'tor because Threads is a
|
||||
// static object and we need a fully initialized engine at this point due to
|
||||
// allocation of Endgames in Thread c'tor.
|
||||
/// ThreadPool::init() creates and launches requested threads that will go
|
||||
/// immediately to sleep. We cannot use a constructor because Threads is a
|
||||
/// static object and we need a fully initialized engine at this point due to
|
||||
/// allocation of Endgames in the Thread constructor.
|
||||
|
||||
void ThreadPool::init() {
|
||||
|
||||
timer = new_thread<TimerThread>();
|
||||
push_back(new_thread<MainThread>());
|
||||
push_back(new MainThread);
|
||||
read_uci_options();
|
||||
}
|
||||
|
||||
|
||||
// ThreadPool::exit() terminates the threads before the program exits. Cannot be
|
||||
// done in d'tor because threads must be terminated before freeing us.
|
||||
/// ThreadPool::exit() terminates threads before the program exits. Cannot be
|
||||
/// done in destructor because threads must be terminated before deleting any
|
||||
/// static objects while still in main().
|
||||
|
||||
void ThreadPool::exit() {
|
||||
|
||||
delete_thread(timer); // As first because check_time() accesses threads data
|
||||
|
||||
for (iterator it = begin(); it != end(); ++it)
|
||||
delete_thread(*it);
|
||||
while (size())
|
||||
delete back(), pop_back();
|
||||
}
|
||||
|
||||
|
||||
// ThreadPool::read_uci_options() updates internal threads parameters from the
|
||||
// corresponding UCI options and creates/destroys threads to match the requested
|
||||
// number. Thread objects are dynamically allocated to avoid creating all possible
|
||||
// threads in advance (which include pawns and material tables), even if only a
|
||||
// few are to be used.
|
||||
/// ThreadPool::read_uci_options() updates internal threads parameters from the
|
||||
/// corresponding UCI options and creates/destroys threads to match requested
|
||||
/// number. Thread objects are dynamically allocated.
|
||||
|
||||
void ThreadPool::read_uci_options() {
|
||||
|
||||
minimumSplitDepth = Options["Min Split Depth"] * ONE_PLY;
|
||||
size_t requested = Options["Threads"];
|
||||
size_t requested = Options["Threads"];
|
||||
|
||||
assert(requested > 0);
|
||||
|
||||
// If zero (default) then set best minimum split depth automatically
|
||||
if (!minimumSplitDepth)
|
||||
minimumSplitDepth = requested < 8 ? 4 * ONE_PLY : 7 * ONE_PLY;
|
||||
|
||||
while (size() < requested)
|
||||
push_back(new_thread<Thread>());
|
||||
push_back(new Thread);
|
||||
|
||||
while (size() > requested)
|
||||
{
|
||||
delete_thread(back());
|
||||
pop_back();
|
||||
}
|
||||
delete back(), pop_back();
|
||||
}
|
||||
|
||||
|
||||
// ThreadPool::available_slave() tries to find an idle thread which is available
|
||||
// as a slave for the thread 'master'.
|
||||
/// ThreadPool::nodes_searched() returns the number of nodes searched
|
||||
|
||||
Thread* ThreadPool::available_slave(const Thread* master) const {
|
||||
uint64_t ThreadPool::nodes_searched() const {
|
||||
|
||||
for (const_iterator it = begin(); it != end(); ++it)
|
||||
if ((*it)->available_to(master))
|
||||
return *it;
|
||||
|
||||
return NULL;
|
||||
uint64_t nodes = 0;
|
||||
for (Thread* th : *this)
|
||||
nodes += th->rootPos.nodes_searched();
|
||||
return nodes;
|
||||
}
|
||||
|
||||
|
||||
// ThreadPool::wait_for_think_finished() waits for main thread to finish the search
|
||||
/// ThreadPool::tb_hits() returns the number of TB hits
|
||||
|
||||
void ThreadPool::wait_for_think_finished() {
|
||||
uint64_t ThreadPool::tb_hits() const {
|
||||
|
||||
MainThread* th = main();
|
||||
th->mutex.lock();
|
||||
while (th->thinking) sleepCondition.wait(th->mutex);
|
||||
th->mutex.unlock();
|
||||
uint64_t hits = 0;
|
||||
for (Thread* th : *this)
|
||||
hits += th->tbHits;
|
||||
return hits;
|
||||
}
|
||||
|
||||
|
||||
// ThreadPool::start_thinking() wakes up the main thread sleeping in
|
||||
// MainThread::idle_loop() and starts a new search, then returns immediately.
|
||||
/// ThreadPool::start_thinking() wakes up the main thread sleeping in idle_loop()
|
||||
/// and starts a new search, then returns immediately.
|
||||
|
||||
void ThreadPool::start_thinking(const Position& pos, const LimitsType& limits,
|
||||
StateStackPtr& states) {
|
||||
wait_for_think_finished();
|
||||
void ThreadPool::start_thinking(Position& pos, StateListPtr& states,
|
||||
const Search::LimitsType& limits) {
|
||||
|
||||
SearchTime = Time::now(); // As early as possible
|
||||
main()->wait_for_search_finished();
|
||||
|
||||
Signals.stopOnPonderhit = Signals.firstRootMove = false;
|
||||
Signals.stop = Signals.failedLowAtRoot = false;
|
||||
Search::Signals.stopOnPonderhit = Search::Signals.stop = false;
|
||||
Search::Limits = limits;
|
||||
Search::RootMoves rootMoves;
|
||||
|
||||
RootMoves.clear();
|
||||
RootPos = pos;
|
||||
Limits = limits;
|
||||
if (states.get()) // If we don't set a new position, preserve current state
|
||||
{
|
||||
SetupStates = states; // Ownership transfer here
|
||||
assert(!states.get());
|
||||
}
|
||||
|
||||
for (MoveList<LEGAL> it(pos); *it; ++it)
|
||||
for (const auto& m : MoveList<LEGAL>(pos))
|
||||
if ( limits.searchmoves.empty()
|
||||
|| std::count(limits.searchmoves.begin(), limits.searchmoves.end(), *it))
|
||||
RootMoves.push_back(RootMove(*it));
|
||||
|| std::count(limits.searchmoves.begin(), limits.searchmoves.end(), m))
|
||||
rootMoves.push_back(Search::RootMove(m));
|
||||
|
||||
main()->thinking = true;
|
||||
main()->notify_one(); // Starts main thread
|
||||
if (!rootMoves.empty())
|
||||
Tablebases::filter_root_moves(pos, rootMoves);
|
||||
|
||||
// After ownership transfer 'states' becomes empty, so if we stop the search
|
||||
// and call 'go' again without setting a new position states.get() == NULL.
|
||||
assert(states.get() || setupStates.get());
|
||||
|
||||
if (states.get())
|
||||
setupStates = std::move(states); // Ownership transfer, states is now empty
|
||||
|
||||
StateInfo tmp = setupStates->back();
|
||||
|
||||
for (Thread* th : Threads)
|
||||
{
|
||||
th->maxPly = 0;
|
||||
th->tbHits = 0;
|
||||
th->rootDepth = DEPTH_ZERO;
|
||||
th->rootMoves = rootMoves;
|
||||
th->rootPos.set(pos.fen(), pos.is_chess960(), &setupStates->back(), th);
|
||||
}
|
||||
|
||||
setupStates->back() = tmp; // Restore st->previous, cleared by Position::set()
|
||||
|
||||
main()->start_searching();
|
||||
}
|
||||
|
||||
+48
-123
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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
|
||||
@@ -20,7 +21,11 @@
|
||||
#ifndef THREAD_H_INCLUDED
|
||||
#define THREAD_H_INCLUDED
|
||||
|
||||
#include <atomic>
|
||||
#include <bitset>
|
||||
#include <condition_variable>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "material.h"
|
||||
@@ -28,157 +33,77 @@
|
||||
#include "pawns.h"
|
||||
#include "position.h"
|
||||
#include "search.h"
|
||||
|
||||
struct Thread;
|
||||
|
||||
const int MAX_THREADS = 128;
|
||||
const int MAX_SPLITPOINTS_PER_THREAD = 8;
|
||||
|
||||
/// Mutex and ConditionVariable struct are wrappers of the low level locking
|
||||
/// machinery and are modeled after the corresponding C++11 classes.
|
||||
|
||||
struct Mutex {
|
||||
Mutex() { lock_init(l); }
|
||||
~Mutex() { lock_destroy(l); }
|
||||
|
||||
void lock() { lock_grab(l); }
|
||||
void unlock() { lock_release(l); }
|
||||
|
||||
private:
|
||||
friend struct ConditionVariable;
|
||||
|
||||
Lock l;
|
||||
};
|
||||
|
||||
struct ConditionVariable {
|
||||
ConditionVariable() { cond_init(c); }
|
||||
~ConditionVariable() { cond_destroy(c); }
|
||||
|
||||
void wait(Mutex& m) { cond_wait(c, m.l); }
|
||||
void wait_for(Mutex& m, int ms) { timed_wait(c, m.l, ms); }
|
||||
void notify_one() { cond_signal(c); }
|
||||
|
||||
private:
|
||||
WaitCondition c;
|
||||
};
|
||||
#include "thread_win32.h"
|
||||
|
||||
|
||||
/// SplitPoint struct stores information shared by the threads searching in
|
||||
/// parallel below the same split point. It is populated at splitting time.
|
||||
/// Thread struct keeps together all the thread-related stuff. We also use
|
||||
/// per-thread pawn and material hash tables so that once we get a pointer to an
|
||||
/// entry its life time is unlimited and we don't have to care about someone
|
||||
/// changing the entry under our feet.
|
||||
|
||||
struct SplitPoint {
|
||||
|
||||
// Const data after split point has been setup
|
||||
const Position* pos;
|
||||
Search::Stack* ss;
|
||||
Thread* masterThread;
|
||||
Depth depth;
|
||||
Value beta;
|
||||
int nodeType;
|
||||
bool cutNode;
|
||||
|
||||
// Const pointers to shared data
|
||||
MovePicker* movePicker;
|
||||
SplitPoint* parentSplitPoint;
|
||||
|
||||
// Shared variable data
|
||||
Mutex mutex;
|
||||
std::bitset<MAX_THREADS> slavesMask;
|
||||
volatile bool allSlavesSearching;
|
||||
volatile uint64_t nodes;
|
||||
volatile Value alpha;
|
||||
volatile Value bestValue;
|
||||
volatile Move bestMove;
|
||||
volatile int moveCount;
|
||||
volatile bool cutoff;
|
||||
};
|
||||
|
||||
|
||||
/// ThreadBase struct is the base of the hierarchy from where we derive all the
|
||||
/// specialized thread classes.
|
||||
|
||||
struct ThreadBase {
|
||||
|
||||
ThreadBase() : handle(NativeHandle()), exit(false) {}
|
||||
virtual ~ThreadBase() {}
|
||||
virtual void idle_loop() = 0;
|
||||
void notify_one();
|
||||
void wait_for(volatile const bool& b);
|
||||
class Thread {
|
||||
|
||||
std::thread nativeThread;
|
||||
Mutex mutex;
|
||||
ConditionVariable sleepCondition;
|
||||
NativeHandle handle;
|
||||
volatile bool exit;
|
||||
};
|
||||
|
||||
|
||||
/// Thread struct keeps together all the thread related stuff like locks, state
|
||||
/// and especially split points. We also use per-thread pawn and material hash
|
||||
/// tables so that once we get a pointer to an entry its life time is unlimited
|
||||
/// and we don't have to care about someone changing the entry under our feet.
|
||||
|
||||
struct Thread : public ThreadBase {
|
||||
bool exit, searching;
|
||||
|
||||
public:
|
||||
Thread();
|
||||
virtual void idle_loop();
|
||||
bool cutoff_occurred() const;
|
||||
bool available_to(const Thread* master) const;
|
||||
virtual ~Thread();
|
||||
virtual void search();
|
||||
void idle_loop();
|
||||
void start_searching(bool resume = false);
|
||||
void wait_for_search_finished();
|
||||
void wait(std::atomic_bool& b);
|
||||
|
||||
void split(Position& pos, Search::Stack* ss, Value alpha, Value beta, Value* bestValue, Move* bestMove,
|
||||
Depth depth, int moveCount, MovePicker* movePicker, int nodeType, bool cutNode);
|
||||
|
||||
SplitPoint splitPoints[MAX_SPLITPOINTS_PER_THREAD];
|
||||
Pawns::Table pawnsTable;
|
||||
Material::Table materialTable;
|
||||
Endgames endgames;
|
||||
Position* activePosition;
|
||||
size_t idx;
|
||||
int maxPly;
|
||||
SplitPoint* volatile activeSplitPoint;
|
||||
volatile int splitPointsSize;
|
||||
volatile bool searching;
|
||||
size_t idx, PVIdx;
|
||||
int maxPly, callsCnt;
|
||||
uint64_t tbHits;
|
||||
|
||||
Position rootPos;
|
||||
Search::RootMoves rootMoves;
|
||||
Depth rootDepth;
|
||||
Depth completedDepth;
|
||||
std::atomic_bool resetCalls;
|
||||
HistoryStats history;
|
||||
MoveStats counterMoves;
|
||||
FromToStats fromTo;
|
||||
CounterMoveHistoryStats counterMoveHistory;
|
||||
};
|
||||
|
||||
|
||||
/// MainThread and TimerThread are derived classes used to characterize the two
|
||||
/// special threads: the main one and the recurring timer.
|
||||
/// MainThread is a derived class with a specific overload for the main thread
|
||||
|
||||
struct MainThread : public Thread {
|
||||
MainThread() : thinking(true) {} // Avoid a race with start_thinking()
|
||||
virtual void idle_loop();
|
||||
volatile bool thinking;
|
||||
};
|
||||
virtual void search();
|
||||
|
||||
struct TimerThread : public ThreadBase {
|
||||
|
||||
static const int Resolution = 5; // Millisec between two check_time() calls
|
||||
|
||||
TimerThread() : run(false) {}
|
||||
virtual void idle_loop();
|
||||
|
||||
bool run;
|
||||
bool easyMovePlayed, failedLow;
|
||||
double bestMoveChanges;
|
||||
Value previousScore;
|
||||
};
|
||||
|
||||
|
||||
/// ThreadPool struct handles all the threads related stuff like init, starting,
|
||||
/// parking and, most importantly, launching a slave thread at a split point.
|
||||
/// All the access to shared thread data is done through this class.
|
||||
/// ThreadPool struct handles all the threads-related stuff like init, starting,
|
||||
/// parking and, most importantly, launching a thread. All the access to threads
|
||||
/// data is done through this class.
|
||||
|
||||
struct ThreadPool : public std::vector<Thread*> {
|
||||
|
||||
void init(); // No c'tor and d'tor, threads rely on globals that should be
|
||||
void exit(); // initialized and are valid during the whole thread lifetime.
|
||||
void init(); // No constructor and destructor, threads rely on globals that should
|
||||
void exit(); // be initialized and valid during the whole thread lifetime.
|
||||
|
||||
MainThread* main() { return static_cast<MainThread*>(at(0)); }
|
||||
void start_thinking(Position&, StateListPtr&, const Search::LimitsType&);
|
||||
void read_uci_options();
|
||||
Thread* available_slave(const Thread* master) const;
|
||||
void wait_for_think_finished();
|
||||
void start_thinking(const Position&, const Search::LimitsType&, Search::StateStackPtr&);
|
||||
uint64_t nodes_searched() const;
|
||||
uint64_t tb_hits() const;
|
||||
|
||||
Depth minimumSplitDepth;
|
||||
Mutex mutex;
|
||||
ConditionVariable sleepCondition;
|
||||
TimerThread* timer;
|
||||
private:
|
||||
StateListPtr setupStates;
|
||||
};
|
||||
|
||||
extern ThreadPool Threads;
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
Stockfish is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef THREAD_WIN32_H_INCLUDED
|
||||
#define THREAD_WIN32_H_INCLUDED
|
||||
|
||||
/// STL thread library used by mingw and gcc when cross compiling for Windows
|
||||
/// relies on libwinpthread. Currently libwinpthread implements mutexes directly
|
||||
/// on top of Windows semaphores. Semaphores, being kernel objects, require kernel
|
||||
/// mode transition in order to lock or unlock, which is very slow compared to
|
||||
/// interlocked operations (about 30% slower on bench test). To work around this
|
||||
/// issue, we define our wrappers to the low level Win32 calls. We use critical
|
||||
/// sections to support Windows XP and older versions. Unfortunately, cond_wait()
|
||||
/// is racy between unlock() and WaitForSingleObject() but they have the same
|
||||
/// speed performance as the SRW locks.
|
||||
|
||||
#include <condition_variable>
|
||||
#include <mutex>
|
||||
|
||||
#if defined(_WIN32) && !defined(_MSC_VER)
|
||||
|
||||
#ifndef NOMINMAX
|
||||
# define NOMINMAX // Disable macros min() and max()
|
||||
#endif
|
||||
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
#undef WIN32_LEAN_AND_MEAN
|
||||
#undef NOMINMAX
|
||||
|
||||
/// Mutex and ConditionVariable struct are wrappers of the low level locking
|
||||
/// machinery and are modeled after the corresponding C++11 classes.
|
||||
|
||||
struct Mutex {
|
||||
Mutex() { InitializeCriticalSection(&cs); }
|
||||
~Mutex() { DeleteCriticalSection(&cs); }
|
||||
void lock() { EnterCriticalSection(&cs); }
|
||||
void unlock() { LeaveCriticalSection(&cs); }
|
||||
|
||||
private:
|
||||
CRITICAL_SECTION cs;
|
||||
};
|
||||
|
||||
typedef std::condition_variable_any ConditionVariable;
|
||||
|
||||
#else // Default case: use STL classes
|
||||
|
||||
typedef std::mutex Mutex;
|
||||
typedef std::condition_variable ConditionVariable;
|
||||
|
||||
#endif
|
||||
|
||||
#endif // #ifndef THREAD_WIN32_H_INCLUDED
|
||||
+35
-19
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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,32 +26,34 @@
|
||||
#include "timeman.h"
|
||||
#include "uci.h"
|
||||
|
||||
TimeManagement Time; // Our global time management object
|
||||
|
||||
namespace {
|
||||
|
||||
enum TimeType { OptimumTime, MaxTime };
|
||||
|
||||
const int MoveHorizon = 50; // Plan time management at most this many moves ahead
|
||||
const double MaxRatio = 7.0; // When in trouble, we can step over reserved time with this ratio
|
||||
const double StealRatio = 0.33; // However we must not steal time from remaining moves over this ratio
|
||||
const double MaxRatio = 7.09; // When in trouble, we can step over reserved time with this ratio
|
||||
const double StealRatio = 0.35; // However we must not steal time from remaining moves over this ratio
|
||||
|
||||
|
||||
// move_importance() is a skew-logistic function based on naive statistical
|
||||
// analysis of "how many games are still undecided after n half-moves". Game
|
||||
// is considered "undecided" as long as neither side has >275cp advantage.
|
||||
// Data was extracted from CCRL game database with some simple filtering criteria.
|
||||
// Data was extracted from the CCRL game database with some simple filtering criteria.
|
||||
|
||||
double move_importance(int ply) {
|
||||
|
||||
const double XScale = 9.3;
|
||||
const double XShift = 59.8;
|
||||
const double Skew = 0.172;
|
||||
const double XScale = 7.64;
|
||||
const double XShift = 58.4;
|
||||
const double Skew = 0.183;
|
||||
|
||||
return pow((1 + exp((ply - XShift) / XScale)), -Skew) + DBL_MIN; // Ensure non-zero
|
||||
}
|
||||
|
||||
template<TimeType T>
|
||||
int remaining(int myTime, int movesToGo, int ply, int slowMover)
|
||||
{
|
||||
int remaining(int myTime, int movesToGo, int ply, int slowMover) {
|
||||
|
||||
const double TMaxRatio = (T == OptimumTime ? 1 : MaxRatio);
|
||||
const double TStealRatio = (T == OptimumTime ? 0 : StealRatio);
|
||||
|
||||
@@ -63,7 +66,7 @@ namespace {
|
||||
double ratio1 = (TMaxRatio * moveImportance) / (TMaxRatio * moveImportance + otherMovesImportance);
|
||||
double ratio2 = (moveImportance + TStealRatio * otherMovesImportance) / (moveImportance + otherMovesImportance);
|
||||
|
||||
return int(myTime * std::min(ratio1, ratio2)); // Intel C++ asks an explicit cast
|
||||
return int(myTime * std::min(ratio1, ratio2)); // Intel C++ asks for an explicit cast
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -78,15 +81,30 @@ namespace {
|
||||
/// inc > 0 && movestogo == 0 means: x basetime + z increment
|
||||
/// inc > 0 && movestogo != 0 means: x moves in y minutes + z increment
|
||||
|
||||
void TimeManager::init(const Search::LimitsType& limits, Color us, int ply)
|
||||
{
|
||||
void TimeManagement::init(Search::LimitsType& limits, Color us, int ply) {
|
||||
|
||||
int minThinkingTime = Options["Minimum Thinking Time"];
|
||||
int moveOverhead = Options["Move Overhead"];
|
||||
int slowMover = Options["Slow Mover"];
|
||||
int npmsec = Options["nodestime"];
|
||||
|
||||
// Initialize unstablePvFactor to 1 and search times to maximum values
|
||||
unstablePvFactor = 1;
|
||||
optimumSearchTime = maximumSearchTime = std::max(limits.time[us], minThinkingTime);
|
||||
// If we have to play in 'nodes as time' mode, then convert from time
|
||||
// to nodes, and use resulting values in time management formulas.
|
||||
// WARNING: Given npms (nodes per millisecond) must be much lower then
|
||||
// the real engine speed to avoid time losses.
|
||||
if (npmsec)
|
||||
{
|
||||
if (!availableNodes) // Only once at game start
|
||||
availableNodes = npmsec * limits.time[us]; // Time is in msec
|
||||
|
||||
// Convert from millisecs to nodes
|
||||
limits.time[us] = (int)availableNodes;
|
||||
limits.inc[us] *= npmsec;
|
||||
limits.npmsec = npmsec;
|
||||
}
|
||||
|
||||
startTime = limits.startTime;
|
||||
optimumTime = maximumTime = std::max(limits.time[us], minThinkingTime);
|
||||
|
||||
const int MaxMTG = limits.movestogo ? std::min(limits.movestogo, MoveHorizon) : MoveHorizon;
|
||||
|
||||
@@ -105,12 +123,10 @@ void TimeManager::init(const Search::LimitsType& limits, Color us, int ply)
|
||||
int t1 = minThinkingTime + remaining<OptimumTime>(hypMyTime, hypMTG, ply, slowMover);
|
||||
int t2 = minThinkingTime + remaining<MaxTime >(hypMyTime, hypMTG, ply, slowMover);
|
||||
|
||||
optimumSearchTime = std::min(t1, optimumSearchTime);
|
||||
maximumSearchTime = std::min(t2, maximumSearchTime);
|
||||
optimumTime = std::min(t1, optimumTime);
|
||||
maximumTime = std::min(t2, maximumTime);
|
||||
}
|
||||
|
||||
if (Options["Ponder"])
|
||||
optimumSearchTime += optimumSearchTime / 4;
|
||||
|
||||
optimumSearchTime = std::min(optimumSearchTime, maximumSearchTime);
|
||||
optimumTime += optimumTime / 4;
|
||||
}
|
||||
|
||||
+19
-10
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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
|
||||
@@ -20,20 +21,28 @@
|
||||
#ifndef TIMEMAN_H_INCLUDED
|
||||
#define TIMEMAN_H_INCLUDED
|
||||
|
||||
/// The TimeManager class computes the optimal time to think depending on the
|
||||
/// maximum available time, the game move number and other parameters.
|
||||
#include "misc.h"
|
||||
#include "search.h"
|
||||
#include "thread.h"
|
||||
|
||||
class TimeManager {
|
||||
/// The TimeManagement class computes the optimal time to think depending on
|
||||
/// the maximum available time, the game move number and other parameters.
|
||||
|
||||
class TimeManagement {
|
||||
public:
|
||||
void init(const Search::LimitsType& limits, Color us, int ply);
|
||||
void pv_instability(double bestMoveChanges) { unstablePvFactor = 1 + bestMoveChanges; }
|
||||
int available_time() const { return int(optimumSearchTime * unstablePvFactor * 0.71); }
|
||||
int maximum_time() const { return maximumSearchTime; }
|
||||
void init(Search::LimitsType& limits, Color us, int ply);
|
||||
int optimum() const { return optimumTime; }
|
||||
int maximum() const { return maximumTime; }
|
||||
int elapsed() const { return int(Search::Limits.npmsec ? Threads.nodes_searched() : now() - startTime); }
|
||||
|
||||
int64_t availableNodes; // When in 'nodes as time' mode
|
||||
|
||||
private:
|
||||
int optimumSearchTime;
|
||||
int maximumSearchTime;
|
||||
double unstablePvFactor;
|
||||
TimePoint startTime;
|
||||
int optimumTime;
|
||||
int maximumTime;
|
||||
};
|
||||
|
||||
extern TimeManagement Time;
|
||||
|
||||
#endif // #ifndef TIMEMAN_H_INCLUDED
|
||||
|
||||
+28
-9
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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,8 +33,6 @@ TranspositionTable TT; // Our global transposition table
|
||||
|
||||
void TranspositionTable::resize(size_t mbSize) {
|
||||
|
||||
assert(sizeof(Cluster) == CacheLineSize / 2);
|
||||
|
||||
size_t newClusterCount = size_t(1) << msb((mbSize * 1024 * 1024) / sizeof(Cluster));
|
||||
|
||||
if (newClusterCount == clusterCount)
|
||||
@@ -68,9 +67,9 @@ void TranspositionTable::clear() {
|
||||
/// TranspositionTable::probe() looks up the current position in the transposition
|
||||
/// table. It returns true and a pointer to the TTEntry if the position is found.
|
||||
/// Otherwise, it returns false and a pointer to an empty or least valuable TTEntry
|
||||
/// to be replaced later. A TTEntry t1 is considered to be more valuable than a
|
||||
/// TTEntry t2 if t1 is from the current search and t2 is from a previous search,
|
||||
/// or if the depth of t1 is bigger than the depth of t2.
|
||||
/// to be replaced later. The replace value of an entry is calculated as its depth
|
||||
/// minus 8 times its relative age. TTEntry t1 is considered more valuable than
|
||||
/// TTEntry t2 if its replace value is greater than that of t2.
|
||||
|
||||
TTEntry* TranspositionTable::probe(const Key key, bool& found) const {
|
||||
|
||||
@@ -80,7 +79,7 @@ TTEntry* TranspositionTable::probe(const Key key, bool& found) const {
|
||||
for (int i = 0; i < ClusterSize; ++i)
|
||||
if (!tte[i].key16 || tte[i].key16 == key16)
|
||||
{
|
||||
if (tte[i].key16)
|
||||
if ((tte[i].genBound8 & 0xFC) != generation8 && tte[i].key16)
|
||||
tte[i].genBound8 = uint8_t(generation8 | tte[i].bound()); // Refresh
|
||||
|
||||
return found = (bool)tte[i].key16, &tte[i];
|
||||
@@ -89,10 +88,30 @@ TTEntry* TranspositionTable::probe(const Key key, bool& found) const {
|
||||
// Find an entry to be replaced according to the replacement strategy
|
||||
TTEntry* replace = tte;
|
||||
for (int i = 1; i < ClusterSize; ++i)
|
||||
if ( (( tte[i].genBound8 & 0xFC) == generation8 || tte[i].bound() == BOUND_EXACT)
|
||||
- ((replace->genBound8 & 0xFC) == generation8)
|
||||
- (tte[i].depth8 < replace->depth8) < 0)
|
||||
// Due to our packed storage format for generation and its cyclic
|
||||
// nature we add 259 (256 is the modulus plus 3 to keep the lowest
|
||||
// two bound bits from affecting the result) to calculate the entry
|
||||
// age correctly even after generation8 overflows into the next cycle.
|
||||
if ( replace->depth8 - ((259 + generation8 - replace->genBound8) & 0xFC) * 2
|
||||
> tte[i].depth8 - ((259 + generation8 - tte[i].genBound8) & 0xFC) * 2)
|
||||
replace = &tte[i];
|
||||
|
||||
return found = false, replace;
|
||||
}
|
||||
|
||||
|
||||
/// TranspositionTable::hashfull() returns an approximation of the hashtable
|
||||
/// occupation during a search. The hash is x permill full, as per UCI protocol.
|
||||
|
||||
int TranspositionTable::hashfull() const {
|
||||
|
||||
int cnt = 0;
|
||||
for (int i = 0; i < 1000 / ClusterSize; i++)
|
||||
{
|
||||
const TTEntry* tte = &table[i].entry[0];
|
||||
for (int j = 0; j < ClusterSize; j++)
|
||||
if ((tte[j].genBound8 & 0xFC) == generation8)
|
||||
cnt++;
|
||||
}
|
||||
return cnt;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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,19 +39,29 @@ struct TTEntry {
|
||||
Move move() const { return (Move )move16; }
|
||||
Value value() const { return (Value)value16; }
|
||||
Value eval() const { return (Value)eval16; }
|
||||
Depth depth() const { return (Depth)depth8; }
|
||||
Depth depth() const { return (Depth)(depth8 * int(ONE_PLY)); }
|
||||
Bound bound() const { return (Bound)(genBound8 & 0x3); }
|
||||
|
||||
void save(Key k, Value v, Bound b, Depth d, Move m, Value ev, uint8_t g) {
|
||||
|
||||
if (m || (k >> 48) != key16) // Preserve any existing move for the same position
|
||||
assert(d / ONE_PLY * ONE_PLY == d);
|
||||
|
||||
// Preserve any existing move for the same position
|
||||
if (m || (k >> 48) != key16)
|
||||
move16 = (uint16_t)m;
|
||||
|
||||
key16 = (uint16_t)(k >> 48);
|
||||
value16 = (int16_t)v;
|
||||
eval16 = (int16_t)ev;
|
||||
genBound8 = (uint8_t)(g | b);
|
||||
depth8 = (int8_t)d;
|
||||
// Don't overwrite more valuable entries
|
||||
if ( (k >> 48) != key16
|
||||
|| d / ONE_PLY > depth8 - 4
|
||||
/* || g != (genBound8 & 0xFC) // Matching non-zero keys are already refreshed by probe() */
|
||||
|| b == BOUND_EXACT)
|
||||
{
|
||||
key16 = (uint16_t)(k >> 48);
|
||||
value16 = (int16_t)v;
|
||||
eval16 = (int16_t)ev;
|
||||
genBound8 = (uint8_t)(g | b);
|
||||
depth8 = (int8_t)(d / ONE_PLY);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
@@ -68,8 +79,9 @@ private:
|
||||
/// A TranspositionTable consists of a power of 2 number of clusters and each
|
||||
/// cluster consists of ClusterSize number of TTEntry. Each non-empty entry
|
||||
/// contains information of exactly one position. The size of a cluster should
|
||||
/// not be bigger than a cache line size. In case it is less, it should be padded
|
||||
/// to guarantee always aligned accesses.
|
||||
/// divide the size of a cache line size, to ensure that clusters never cross
|
||||
/// cache lines. This ensures best cache performance, as the cacheline is
|
||||
/// prefetched, as soon as possible.
|
||||
|
||||
class TranspositionTable {
|
||||
|
||||
@@ -78,14 +90,17 @@ class TranspositionTable {
|
||||
|
||||
struct Cluster {
|
||||
TTEntry entry[ClusterSize];
|
||||
char padding[2]; // Align to the cache line size
|
||||
char padding[2]; // Align to a divisor of the cache line size
|
||||
};
|
||||
|
||||
static_assert(CacheLineSize % sizeof(Cluster) == 0, "Cluster size incorrect");
|
||||
|
||||
public:
|
||||
~TranspositionTable() { free(mem); }
|
||||
void new_search() { generation8 += 4; } // Lower 2 bits are used by Bound
|
||||
uint8_t generation() const { return generation8; }
|
||||
TTEntry* probe(const Key key, bool& found) const;
|
||||
int hashfull() const;
|
||||
void resize(size_t mbSize);
|
||||
void clear();
|
||||
|
||||
|
||||
+70
-71
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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 +34,22 @@
|
||||
///
|
||||
/// -DUSE_POPCNT | Add runtime support for use of popcnt asm-instruction. Works
|
||||
/// | only in 64-bit mode and requires hardware with popcnt support.
|
||||
///
|
||||
/// -DUSE_PEXT | Add runtime support for use of pext asm-instruction. Works
|
||||
/// | only in 64-bit mode and requires hardware with pext support.
|
||||
|
||||
#include <cassert>
|
||||
#include <cctype>
|
||||
#include <climits>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
|
||||
#include "platform.h"
|
||||
#if defined(_MSC_VER)
|
||||
// Disable some silly and noisy warning from MSVC compiler
|
||||
#pragma warning(disable: 4127) // Conditional expression is constant
|
||||
#pragma warning(disable: 4146) // Unary minus operator applied to unsigned type
|
||||
#pragma warning(disable: 4800) // Forcing value to bool 'true' or 'false'
|
||||
#endif
|
||||
|
||||
/// Predefined macros hell:
|
||||
///
|
||||
@@ -49,14 +59,13 @@
|
||||
/// _WIN32 Building on Windows (any)
|
||||
/// _WIN64 Building on Windows 64 bit
|
||||
|
||||
#if defined(_WIN64) && !defined(IS_64BIT) // Last condition means Makefile is not used
|
||||
# include <intrin.h> // MSVC popcnt and bsfq instrinsics
|
||||
#if defined(_WIN64) && defined(_MSC_VER) // No Makefile used
|
||||
# include <intrin.h> // Microsoft header for _BitScanForward64()
|
||||
# define IS_64BIT
|
||||
# define USE_BSFQ
|
||||
#endif
|
||||
|
||||
#if defined(USE_POPCNT) && defined(__INTEL_COMPILER) && defined(_MSC_VER)
|
||||
# include <nmmintrin.h> // Intel header for _mm_popcnt_u64() intrinsic
|
||||
#if defined(USE_POPCNT) && (defined(__INTEL_COMPILER) || defined(_MSC_VER))
|
||||
# include <nmmintrin.h> // Intel and Microsoft header for _mm_popcnt_u64()
|
||||
#endif
|
||||
|
||||
#if !defined(NO_PREFETCH) && (defined(__INTEL_COMPILER) || defined(_MSC_VER))
|
||||
@@ -70,14 +79,6 @@
|
||||
# define pext(b, m) (0)
|
||||
#endif
|
||||
|
||||
#ifdef _MSC_VER
|
||||
# define FORCE_INLINE __forceinline
|
||||
#elif defined(__GNUC__)
|
||||
# define FORCE_INLINE inline __attribute__((always_inline))
|
||||
#else
|
||||
# define FORCE_INLINE inline
|
||||
#endif
|
||||
|
||||
#ifdef USE_POPCNT
|
||||
const bool HasPopCnt = true;
|
||||
#else
|
||||
@@ -114,7 +115,7 @@ const int MAX_PLY = 128;
|
||||
/// any normal move destination square is always different from origin square
|
||||
/// while MOVE_NONE and MOVE_NULL have the same origin and destination square.
|
||||
|
||||
enum Move {
|
||||
enum Move : int {
|
||||
MOVE_NONE,
|
||||
MOVE_NULL = 65
|
||||
};
|
||||
@@ -171,7 +172,7 @@ enum Bound {
|
||||
BOUND_EXACT = BOUND_UPPER | BOUND_LOWER
|
||||
};
|
||||
|
||||
enum Value {
|
||||
enum Value : int {
|
||||
VALUE_ZERO = 0,
|
||||
VALUE_DRAW = 0,
|
||||
VALUE_KNOWN_WIN = 10000,
|
||||
@@ -182,16 +183,13 @@ enum Value {
|
||||
VALUE_MATE_IN_MAX_PLY = VALUE_MATE - 2 * MAX_PLY,
|
||||
VALUE_MATED_IN_MAX_PLY = -VALUE_MATE + 2 * MAX_PLY,
|
||||
|
||||
VALUE_ENSURE_INTEGER_SIZE_P = INT_MAX,
|
||||
VALUE_ENSURE_INTEGER_SIZE_N = INT_MIN,
|
||||
PawnValueMg = 188, PawnValueEg = 248,
|
||||
KnightValueMg = 753, KnightValueEg = 832,
|
||||
BishopValueMg = 826, BishopValueEg = 897,
|
||||
RookValueMg = 1285, RookValueEg = 1371,
|
||||
QueenValueMg = 2513, QueenValueEg = 2650,
|
||||
|
||||
PawnValueMg = 198, PawnValueEg = 258,
|
||||
KnightValueMg = 817, KnightValueEg = 846,
|
||||
BishopValueMg = 836, BishopValueEg = 857,
|
||||
RookValueMg = 1270, RookValueEg = 1278,
|
||||
QueenValueMg = 2521, QueenValueEg = 2558,
|
||||
|
||||
MidgameLimit = 15581, EndgameLimit = 3998
|
||||
MidgameLimit = 15258, EndgameLimit = 3915
|
||||
};
|
||||
|
||||
enum PieceType {
|
||||
@@ -207,19 +205,25 @@ enum Piece {
|
||||
PIECE_NB = 16
|
||||
};
|
||||
|
||||
const Piece Pieces[] = { W_PAWN, W_KNIGHT, W_BISHOP, W_ROOK, W_QUEEN, W_KING,
|
||||
B_PAWN, B_KNIGHT, B_BISHOP, B_ROOK, B_QUEEN, B_KING };
|
||||
extern Value PieceValue[PHASE_NB][PIECE_NB];
|
||||
|
||||
enum Depth {
|
||||
|
||||
ONE_PLY = 1,
|
||||
|
||||
DEPTH_ZERO = 0,
|
||||
DEPTH_QS_CHECKS = 0,
|
||||
DEPTH_QS_NO_CHECKS = -1,
|
||||
DEPTH_QS_RECAPTURES = -5,
|
||||
DEPTH_ZERO = 0 * ONE_PLY,
|
||||
DEPTH_QS_CHECKS = 0 * ONE_PLY,
|
||||
DEPTH_QS_NO_CHECKS = -1 * ONE_PLY,
|
||||
DEPTH_QS_RECAPTURES = -5 * ONE_PLY,
|
||||
|
||||
DEPTH_NONE = -6,
|
||||
DEPTH_MAX = MAX_PLY
|
||||
DEPTH_NONE = -6 * ONE_PLY,
|
||||
DEPTH_MAX = MAX_PLY * ONE_PLY
|
||||
};
|
||||
|
||||
static_assert(!(ONE_PLY & (ONE_PLY - 1)), "ONE_PLY is not a power of 2");
|
||||
|
||||
enum Square {
|
||||
SQ_A1, SQ_B1, SQ_C1, SQ_D1, SQ_E1, SQ_F1, SQ_G1, SQ_H1,
|
||||
SQ_A2, SQ_B2, SQ_C2, SQ_D2, SQ_E2, SQ_F2, SQ_G2, SQ_H2,
|
||||
@@ -233,58 +237,51 @@ enum Square {
|
||||
|
||||
SQUARE_NB = 64,
|
||||
|
||||
DELTA_N = 8,
|
||||
DELTA_E = 1,
|
||||
DELTA_S = -8,
|
||||
DELTA_W = -1,
|
||||
NORTH = 8,
|
||||
EAST = 1,
|
||||
SOUTH = -8,
|
||||
WEST = -1,
|
||||
|
||||
DELTA_NN = DELTA_N + DELTA_N,
|
||||
DELTA_NE = DELTA_N + DELTA_E,
|
||||
DELTA_SE = DELTA_S + DELTA_E,
|
||||
DELTA_SS = DELTA_S + DELTA_S,
|
||||
DELTA_SW = DELTA_S + DELTA_W,
|
||||
DELTA_NW = DELTA_N + DELTA_W
|
||||
NORTH_EAST = NORTH + EAST,
|
||||
SOUTH_EAST = SOUTH + EAST,
|
||||
SOUTH_WEST = SOUTH + WEST,
|
||||
NORTH_WEST = NORTH + WEST
|
||||
};
|
||||
|
||||
enum File {
|
||||
enum File : int {
|
||||
FILE_A, FILE_B, FILE_C, FILE_D, FILE_E, FILE_F, FILE_G, FILE_H, FILE_NB
|
||||
};
|
||||
|
||||
enum Rank {
|
||||
enum Rank : int {
|
||||
RANK_1, RANK_2, RANK_3, RANK_4, RANK_5, RANK_6, RANK_7, RANK_8, RANK_NB
|
||||
};
|
||||
|
||||
|
||||
/// Score enum stores a middlegame and an endgame value in a single integer.
|
||||
/// The least significant 16 bits are used to store the endgame value and
|
||||
/// the upper 16 bits are used to store the middlegame value. The compiler
|
||||
/// is free to choose the enum type as long as it can store the data, so we
|
||||
/// ensure that Score is an integer type by assigning some big int values.
|
||||
enum Score {
|
||||
SCORE_ZERO,
|
||||
SCORE_ENSURE_INTEGER_SIZE_P = INT_MAX,
|
||||
SCORE_ENSURE_INTEGER_SIZE_N = INT_MIN
|
||||
};
|
||||
/// Score enum stores a middlegame and an endgame value in a single integer
|
||||
/// (enum). The least significant 16 bits are used to store the endgame value
|
||||
/// and the upper 16 bits are used to store the middlegame value. Take some
|
||||
/// care to avoid left-shifting a signed int to avoid undefined behavior.
|
||||
enum Score : int { SCORE_ZERO };
|
||||
|
||||
inline Score make_score(int mg, int eg) {
|
||||
return Score((mg << 16) + eg);
|
||||
return Score((int)((unsigned int)eg << 16) + mg);
|
||||
}
|
||||
|
||||
/// Extracting the signed lower and upper 16 bits is 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) {
|
||||
|
||||
union { uint16_t u; int16_t s; } mg = { uint16_t(unsigned(s + 0x8000) >> 16) };
|
||||
return Value(mg.s);
|
||||
}
|
||||
|
||||
inline Value eg_value(Score s) {
|
||||
|
||||
union { uint16_t u; int16_t s; } eg = { uint16_t(unsigned(s)) };
|
||||
union { uint16_t u; int16_t s; } eg = { uint16_t(unsigned(s + 0x8000) >> 16) };
|
||||
return Value(eg.s);
|
||||
}
|
||||
|
||||
inline Value mg_value(Score s) {
|
||||
|
||||
union { uint16_t u; int16_t s; } mg = { uint16_t(unsigned(s)) };
|
||||
return Value(mg.s);
|
||||
}
|
||||
|
||||
#define ENABLE_BASE_OPERATORS_ON(T) \
|
||||
inline T operator+(T d1, T d2) { return T(int(d1) + int(d2)); } \
|
||||
inline T operator-(T d1, T d2) { return T(int(d1) - int(d2)); } \
|
||||
@@ -332,16 +329,18 @@ inline Score operator/(Score s, int i) {
|
||||
return make_score(mg_value(s) / i, eg_value(s) / i);
|
||||
}
|
||||
|
||||
extern Value PieceValue[PHASE_NB][PIECE_NB];
|
||||
|
||||
inline Color operator~(Color c) {
|
||||
return Color(c ^ BLACK);
|
||||
return Color(c ^ BLACK); // Toggle color
|
||||
}
|
||||
|
||||
inline Square operator~(Square s) {
|
||||
return Square(s ^ SQ_A8); // Vertical flip SQ_A1 -> SQ_A8
|
||||
}
|
||||
|
||||
inline Piece operator~(Piece pc) {
|
||||
return Piece(pc ^ 8); // Swap color of piece B_KNIGHT -> W_KNIGHT
|
||||
}
|
||||
|
||||
inline CastlingRight operator|(Color c, CastlingSide s) {
|
||||
return CastlingRight(WHITE_OO << ((s == QUEEN_SIDE) + 2 * c));
|
||||
}
|
||||
@@ -355,14 +354,14 @@ inline Value mated_in(int ply) {
|
||||
}
|
||||
|
||||
inline Square make_square(File f, Rank r) {
|
||||
return Square((r << 3) | f);
|
||||
return Square((r << 3) + f);
|
||||
}
|
||||
|
||||
inline Piece make_piece(Color c, PieceType pt) {
|
||||
return Piece((c << 3) | pt);
|
||||
return Piece((c << 3) + pt);
|
||||
}
|
||||
|
||||
inline PieceType type_of(Piece pc) {
|
||||
inline PieceType type_of(Piece pc) {
|
||||
return PieceType(pc & 7);
|
||||
}
|
||||
|
||||
@@ -401,7 +400,7 @@ inline bool opposite_colors(Square s1, Square s2) {
|
||||
}
|
||||
|
||||
inline Square pawn_push(Color c) {
|
||||
return c == WHITE ? DELTA_N : DELTA_S;
|
||||
return c == WHITE ? NORTH : SOUTH;
|
||||
}
|
||||
|
||||
inline Square from_sq(Move m) {
|
||||
@@ -417,16 +416,16 @@ inline MoveType type_of(Move m) {
|
||||
}
|
||||
|
||||
inline PieceType promotion_type(Move m) {
|
||||
return PieceType(((m >> 12) & 3) + 2);
|
||||
return PieceType(((m >> 12) & 3) + KNIGHT);
|
||||
}
|
||||
|
||||
inline Move make_move(Square from, Square to) {
|
||||
return Move(to | (from << 6));
|
||||
return Move((from << 6) + to);
|
||||
}
|
||||
|
||||
template<MoveType T>
|
||||
inline Move make(Square from, Square to, PieceType pt = KNIGHT) {
|
||||
return Move(to | (from << 6) | T | ((pt - KNIGHT) << 12));
|
||||
return Move(T + ((pt - KNIGHT) << 12) + (from << 6) + to);
|
||||
}
|
||||
|
||||
inline bool is_ok(Move m) {
|
||||
|
||||
+31
-24
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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,7 +27,7 @@
|
||||
#include "position.h"
|
||||
#include "search.h"
|
||||
#include "thread.h"
|
||||
#include "tt.h"
|
||||
#include "timeman.h"
|
||||
#include "uci.h"
|
||||
|
||||
using namespace std;
|
||||
@@ -38,10 +39,10 @@ namespace {
|
||||
// FEN string of the initial position, normal chess
|
||||
const char* StartFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
|
||||
|
||||
// Stack to keep track of the position states along the setup moves (from the
|
||||
// A list to keep track of the position states along the setup moves (from the
|
||||
// start position to the position just before the search starts). Needed by
|
||||
// 'draw by repetition' detection.
|
||||
Search::StateStackPtr SetupStates;
|
||||
StateListPtr States(new std::deque<StateInfo>(1));
|
||||
|
||||
|
||||
// position() is called when engine receives the "position" UCI command.
|
||||
@@ -67,14 +68,14 @@ namespace {
|
||||
else
|
||||
return;
|
||||
|
||||
pos.set(fen, Options["UCI_Chess960"], Threads.main());
|
||||
SetupStates = Search::StateStackPtr(new std::stack<StateInfo>());
|
||||
States = StateListPtr(new std::deque<StateInfo>(1));
|
||||
pos.set(fen, Options["UCI_Chess960"], &States->back(), Threads.main());
|
||||
|
||||
// Parse move list (if any)
|
||||
while (is >> token && (m = UCI::to_move(pos, token)) != MOVE_NONE)
|
||||
{
|
||||
SetupStates->push(StateInfo());
|
||||
pos.do_move(m, SetupStates->top());
|
||||
States->push_back(StateInfo());
|
||||
pos.do_move(m, States->back(), pos.gives_check(m));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,11 +91,11 @@ namespace {
|
||||
|
||||
// Read option name (can contain spaces)
|
||||
while (is >> token && token != "value")
|
||||
name += string(" ", !name.empty()) + token;
|
||||
name += string(" ", name.empty() ? 0 : 1) + token;
|
||||
|
||||
// Read option value (can contain spaces)
|
||||
while (is >> token)
|
||||
value += string(" ", !value.empty()) + token;
|
||||
value += string(" ", value.empty() ? 0 : 1) + token;
|
||||
|
||||
if (Options.count(name))
|
||||
Options[name] = value;
|
||||
@@ -107,11 +108,13 @@ namespace {
|
||||
// the thinking time and other parameters from the input string, then starts
|
||||
// the search.
|
||||
|
||||
void go(const Position& pos, istringstream& is) {
|
||||
void go(Position& pos, istringstream& is) {
|
||||
|
||||
Search::LimitsType limits;
|
||||
string token;
|
||||
|
||||
limits.startTime = now(); // As early as possible!
|
||||
|
||||
while (is >> token)
|
||||
if (token == "searchmoves")
|
||||
while (is >> token)
|
||||
@@ -126,10 +129,10 @@ namespace {
|
||||
else if (token == "nodes") is >> limits.nodes;
|
||||
else if (token == "movetime") is >> limits.movetime;
|
||||
else if (token == "mate") is >> limits.mate;
|
||||
else if (token == "infinite") limits.infinite = true;
|
||||
else if (token == "ponder") limits.ponder = true;
|
||||
else if (token == "infinite") limits.infinite = 1;
|
||||
else if (token == "ponder") limits.ponder = 1;
|
||||
|
||||
Threads.start_thinking(pos, limits, SetupStates);
|
||||
Threads.start_thinking(pos, States, limits);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -143,9 +146,11 @@ namespace {
|
||||
|
||||
void UCI::loop(int argc, char* argv[]) {
|
||||
|
||||
Position pos(StartFEN, false, Threads.main()); // The root position
|
||||
Position pos;
|
||||
string token, cmd;
|
||||
|
||||
pos.set(StartFEN, false, &States->back(), Threads.main());
|
||||
|
||||
for (int i = 1; i < argc; ++i)
|
||||
cmd += std::string(argv[i]) + " ";
|
||||
|
||||
@@ -168,18 +173,22 @@ void UCI::loop(int argc, char* argv[]) {
|
||||
|| (token == "ponderhit" && Search::Signals.stopOnPonderhit))
|
||||
{
|
||||
Search::Signals.stop = true;
|
||||
Threads.main()->notify_one(); // Could be sleeping
|
||||
Threads.main()->start_searching(true); // Could be sleeping
|
||||
}
|
||||
else if (token == "ponderhit")
|
||||
Search::Limits.ponder = false; // Switch to normal search
|
||||
Search::Limits.ponder = 0; // Switch to normal search
|
||||
|
||||
else if (token == "uci")
|
||||
sync_cout << "id name " << engine_info(true)
|
||||
<< "\n" << Options
|
||||
<< "\nuciok" << sync_endl;
|
||||
|
||||
else if (token == "ucinewgame")
|
||||
{
|
||||
Search::clear();
|
||||
Time.availableNodes = 0;
|
||||
}
|
||||
else if (token == "isready") sync_cout << "readyok" << sync_endl;
|
||||
else if (token == "ucinewgame") TT.clear();
|
||||
else if (token == "go") go(pos, is);
|
||||
else if (token == "position") position(pos, is);
|
||||
else if (token == "setoption") setoption(is);
|
||||
@@ -205,7 +214,7 @@ void UCI::loop(int argc, char* argv[]) {
|
||||
|
||||
} while (token != "quit" && argc == 1); // Passed args have one-shot behaviour
|
||||
|
||||
Threads.wait_for_think_finished(); // Cannot quit whilst the search is running
|
||||
Threads.main()->wait_for_search_finished();
|
||||
}
|
||||
|
||||
|
||||
@@ -232,9 +241,7 @@ string UCI::value(Value v) {
|
||||
/// UCI::square() converts a Square to a string in algebraic notation (g1, a7, etc.)
|
||||
|
||||
std::string UCI::square(Square s) {
|
||||
|
||||
char sq[] = { char('a' + file_of(s)), char('1' + rank_of(s)), 0 }; // NULL terminated
|
||||
return sq;
|
||||
return std::string{ char('a' + file_of(s)), char('1' + rank_of(s)) };
|
||||
}
|
||||
|
||||
|
||||
@@ -274,9 +281,9 @@ Move UCI::to_move(const Position& pos, string& str) {
|
||||
if (str.length() == 5) // Junior could send promotion piece in uppercase
|
||||
str[4] = char(tolower(str[4]));
|
||||
|
||||
for (MoveList<LEGAL> it(pos); *it; ++it)
|
||||
if (str == UCI::move(*it, pos.is_chess960()))
|
||||
return *it;
|
||||
for (const auto& m : MoveList<LEGAL>(pos))
|
||||
if (str == UCI::move(m, pos.is_chess960()))
|
||||
return m;
|
||||
|
||||
return MOVE_NONE;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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
|
||||
@@ -17,8 +18,8 @@
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef UCIOPTION_H_INCLUDED
|
||||
#define UCIOPTION_H_INCLUDED
|
||||
#ifndef UCI_H_INCLUDED
|
||||
#define UCI_H_INCLUDED
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
@@ -45,10 +46,10 @@ class Option {
|
||||
typedef void (*OnChange)(const Option&);
|
||||
|
||||
public:
|
||||
Option(OnChange = NULL);
|
||||
Option(bool v, OnChange = NULL);
|
||||
Option(const char* v, OnChange = NULL);
|
||||
Option(int v, int min, int max, OnChange = NULL);
|
||||
Option(OnChange = nullptr);
|
||||
Option(bool v, OnChange = nullptr);
|
||||
Option(const char* v, OnChange = nullptr);
|
||||
Option(int v, int min, int max, OnChange = nullptr);
|
||||
|
||||
Option& operator=(const std::string&);
|
||||
void operator<<(const Option&);
|
||||
@@ -69,10 +70,11 @@ void loop(int argc, char* argv[]);
|
||||
std::string value(Value v);
|
||||
std::string square(Square s);
|
||||
std::string move(Move m, bool chess960);
|
||||
std::string pv(const Position& pos, Depth depth, Value alpha, Value beta);
|
||||
Move to_move(const Position& pos, std::string& str);
|
||||
|
||||
} // namespace UCI
|
||||
|
||||
extern UCI::OptionsMap Options;
|
||||
|
||||
#endif // #ifndef UCIOPTION_H_INCLUDED
|
||||
#endif // #ifndef UCI_H_INCLUDED
|
||||
|
||||
+20
-19
@@ -2,6 +2,7 @@
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, 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
|
||||
@@ -19,10 +20,10 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <cstdlib>
|
||||
#include <sstream>
|
||||
#include <ostream>
|
||||
|
||||
#include "misc.h"
|
||||
#include "search.h"
|
||||
#include "thread.h"
|
||||
#include "tt.h"
|
||||
#include "uci.h"
|
||||
@@ -35,7 +36,7 @@ UCI::OptionsMap Options; // Global object
|
||||
namespace UCI {
|
||||
|
||||
/// 'On change' actions, triggered by an option's value change
|
||||
void on_clear_hash(const Option&) { TT.clear(); }
|
||||
void on_clear_hash(const Option&) { Search::clear(); }
|
||||
void on_hash_size(const Option& o) { TT.resize(o); }
|
||||
void on_logger(const Option& o) { start_logger(o); }
|
||||
void on_threads(const Option&) { Threads.read_uci_options(); }
|
||||
@@ -43,10 +44,10 @@ void on_tb_path(const Option& o) { Tablebases::init(o); }
|
||||
|
||||
|
||||
/// Our case insensitive less() function as required by UCI protocol
|
||||
bool ci_less(char c1, char c2) { return tolower(c1) < tolower(c2); }
|
||||
|
||||
bool CaseInsensitiveLess::operator() (const string& s1, const string& s2) const {
|
||||
return std::lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end(), ci_less);
|
||||
|
||||
return std::lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end(),
|
||||
[](char c1, char c2) { return tolower(c1) < tolower(c2); });
|
||||
}
|
||||
|
||||
|
||||
@@ -56,18 +57,18 @@ void init(OptionsMap& o) {
|
||||
|
||||
const int MaxHashMB = Is64Bit ? 1024 * 1024 : 2048;
|
||||
|
||||
o["Write Debug Log"] << Option(false, on_logger);
|
||||
o["Debug Log File"] << Option("", on_logger);
|
||||
o["Contempt"] << Option(0, -100, 100);
|
||||
o["Min Split Depth"] << Option(0, 0, 12, on_threads);
|
||||
o["Threads"] << Option(1, 1, MAX_THREADS, on_threads);
|
||||
o["Threads"] << Option(1, 1, 128, on_threads);
|
||||
o["Hash"] << Option(16, 1, MaxHashMB, on_hash_size);
|
||||
o["Clear Hash"] << Option(on_clear_hash);
|
||||
o["Ponder"] << Option(true);
|
||||
o["Ponder"] << Option(false);
|
||||
o["MultiPV"] << Option(1, 1, 500);
|
||||
o["Skill Level"] << Option(20, 0, 20);
|
||||
o["Move Overhead"] << Option(30, 0, 5000);
|
||||
o["Minimum Thinking Time"] << Option(20, 0, 5000);
|
||||
o["Slow Mover"] << Option(80, 10, 1000);
|
||||
o["Slow Mover"] << Option(89, 10, 1000);
|
||||
o["nodestime"] << Option(0, 0, 10000);
|
||||
o["UCI_Chess960"] << Option(false);
|
||||
o["SyzygyPath"] << Option("<empty>", on_tb_path);
|
||||
o["SyzygyProbeDepth"] << Option(1, 1, 100);
|
||||
@@ -82,11 +83,11 @@ void init(OptionsMap& o) {
|
||||
std::ostream& operator<<(std::ostream& os, const OptionsMap& om) {
|
||||
|
||||
for (size_t idx = 0; idx < om.size(); ++idx)
|
||||
for (OptionsMap::const_iterator it = om.begin(); it != om.end(); ++it)
|
||||
if (it->second.idx == idx)
|
||||
for (const auto& it : om)
|
||||
if (it.second.idx == idx)
|
||||
{
|
||||
const Option& o = it->second;
|
||||
os << "\noption name " << it->first << " type " << o.type;
|
||||
const Option& o = it.second;
|
||||
os << "\noption name " << it.first << " type " << o.type;
|
||||
|
||||
if (o.type != "button")
|
||||
os << " default " << o.defaultValue;
|
||||
@@ -96,6 +97,7 @@ std::ostream& operator<<(std::ostream& os, const OptionsMap& om) {
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
return os;
|
||||
}
|
||||
|
||||
@@ -112,12 +114,11 @@ Option::Option(OnChange f) : type("button"), min(0), max(0), on_change(f)
|
||||
{}
|
||||
|
||||
Option::Option(int v, int minv, int maxv, OnChange f) : type("spin"), min(minv), max(maxv), on_change(f)
|
||||
{ std::ostringstream ss; ss << v; defaultValue = currentValue = ss.str(); }
|
||||
|
||||
{ defaultValue = currentValue = std::to_string(v); }
|
||||
|
||||
Option::operator int() const {
|
||||
assert(type == "check" || type == "spin");
|
||||
return (type == "spin" ? atoi(currentValue.c_str()) : currentValue == "true");
|
||||
return (type == "spin" ? stoi(currentValue) : currentValue == "true");
|
||||
}
|
||||
|
||||
Option::operator std::string() const {
|
||||
@@ -147,7 +148,7 @@ Option& Option::operator=(const string& v) {
|
||||
|
||||
if ( (type != "button" && v.empty())
|
||||
|| (type == "check" && v != "true" && v != "false")
|
||||
|| (type == "spin" && (atoi(v.c_str()) < min || atoi(v.c_str()) > max)))
|
||||
|| (type == "spin" && (stoi(v) < min || stoi(v) > max)))
|
||||
return *this;
|
||||
|
||||
if (type != "button")
|
||||
|
||||
Reference in New Issue
Block a user