+
+
+template<Color Us>
+int PawnInfo::shelter_storm(const Position& pos, Square ksq) {
+
+ const Color Them = (Us == WHITE ? BLACK : WHITE);
+
+ int safety = 0;
+ Bitboard b = pos.pieces(PAWN) & (in_front_bb(Us, ksq) | RankBB[rank_of(ksq)]);
+ Bitboard ourPawns = b & pos.pieces(Us) & ~RankBB[rank_of(ksq)];
+ Bitboard theirPawns = b & pos.pieces(Them);
+ Rank rkUs, rkThem;
+ File kf = file_of(ksq);
+
+ // Compute shelter and storm values for the file the king is on, as well as
+ // the two adjacent files. Computation is done from the white point of view.
+ kf = (kf == FILE_A) ? kf++ : (kf == FILE_H) ? kf-- : kf;
+
+ for (int f = kf - 1; f <= kf + 1; f++)
+ {
+ // Shelter penalty is higher for the pawn in front of the king
+ b = ourPawns & FileBB[f];
+ rkUs = b ? rank_of(Us == WHITE ? first_1(b) : ~last_1(b)) : RANK_1;
+ safety -= ShelterWeakness[f != kf][rkUs];
+
+ // Storm danger is smaller if enemy pawn is blocked
+ b = theirPawns & FileBB[f];
+ rkThem = b ? rank_of(Us == WHITE ? first_1(b) : ~last_1(b)) : RANK_1;
+ safety -= StormDanger[rkThem == rkUs + 1][rkThem];
+ }
+
+ return safety;
+}
+
+
+/// PawnInfo::update_safety() calculates and caches a bonus for king safety. It is
+/// called only when king square changes, about 20% of total king_safety() calls.
+
+template<Color Us>
+Score PawnInfo::update_safety(const Position& pos, Square ksq) {
+
+ int bonus = 0;
+
+ if (relative_rank(Us, ksq) <= RANK_4)
+ {
+ bonus = shelter_storm<Us>(pos, ksq);
+
+ // If we can castle use the bonus after the castle if is bigger
+ if (pos.can_castle(Us == WHITE ? WHITE_OO : BLACK_OO))
+ bonus = std::max(bonus, shelter_storm<Us>(pos, relative_square(Us, SQ_G1)));
+
+ if (pos.can_castle(Us == WHITE ? WHITE_OOO : BLACK_OOO))
+ bonus = std::max(bonus, shelter_storm<Us>(pos, relative_square(Us, SQ_C1)));
+
+ bonus += MaxSafetyBonus; // Offset to be sure bonus is always positive
+ }
+
+ kingSquares[Us] = ksq;
+ kingShelters[Us] = make_score(bonus, 0);
+ return kingShelters[Us];
+}
+
+// Explicit template instantiation
+template Score PawnInfo::update_safety<WHITE>(const Position& pos, Square ksq);
+template Score PawnInfo::update_safety<BLACK>(const Position& pos, Square ksq);