void eval(jit::array<To> &out, const jit::array<Ti> &in, int lim) const { for (int i = 0; i < lim; i++) { out[i] = To(in[i]); } }
void BigNum::MulInt(int x) { if (x == 0) { To(0); return; } int c = 0; for (int i = 0; i < size_; i++){ ll t = (ll)d_[i] * x + c; c = static_cast<int>(t / kBase); d_[i] = t % kBase; } for (; c; c /= kBase) d_[size_++] = c % kBase; }
// Returns temperature as localized string std::string CSpeed::ToString(Unit speedUnit) const { if (!IsValid()) return ""; return StringUtils::Format("%2.0f", To(speedUnit)); }
inline To implicit_lexical_cast(const From &f, const To &defval = To()) { try { return lexical_cast<To>(f); } catch (const boost::bad_lexical_cast &) { return defval; } }
static void test(const char* FromName, const char* ToName) { for (long x = 0; x <= N; x++) { for (long y = 0; y <= N; y++) { for (long z = 0; z <= N; z++) { for (long a = 0; a <= 3; a++) { From c1 = From( double(x) / double(N), double(y) / double(N), double(z) / double(N), double(a) / 3.0); To c2 = To(c1); From c3 = From(c2); To c4 = To(c3); if (c1 != c3) { printf("A: %ld - %ld - %ld - %ld -- Not equal %s -> %s {%.5lf, %.5lf, %.5lf, %.5lf} -> {%.5lf, %.5lf, %.5lf, %.5lf} -> {%.5lf, %.5lf, %.5lf, %.5lf}\n", x, y, z, a, FromName, ToName, c1.x, c1.y, c1.z, c1.a, c2.x, c2.y, c2.z, c2.a, c3.x, c3.y, c3.z, c3.a ); return; } if (c2 != c4) { printf("B: %ld - %ld - %ld - %ld -- Not equal %s -> %s {%.5lf, %.5lf, %.5lf, %.5lf} -> {%.5lf, %.5lf, %.5lf, %.5lf} -> {%.5lf, %.5lf, %.5lf, %.5lf}\n", x, y, z, a, ToName, FromName, c2.x, c2.y, c2.z, c2.a, c3.x, c3.y, c3.z, c3.a, c4.x, c4.y, c4.z, c4.a ); return; } } } } } printf("Success %s -> %s\n", FromName, ToName); }
inline SPROUT_CONSTEXPR To iceil(FloatType x) { return x == 0 ? To(0) : std::numeric_limits<To>::max() < x || std::numeric_limits<To>::min() > x ? SPROUT_MATH_THROW_LARGE_FLOAT_ROUNDING(std::runtime_error("iceil: large float rounding."), static_cast<To>(x)) : sprout::math::detail::iceil_impl(x, static_cast<To>(x)) ; }
inline SPROUT_CONSTEXPR To itrunc(FloatType x) { return sprout::math::isnan(x) || sprout::math::isinf(x) ? sprout::numeric_limits<To>::min() : x == 0 ? To(0) : sprout::numeric_limits<To>::max() < x || sprout::numeric_limits<To>::min() > x ? SPROUT_MATH_THROW_LARGE_FLOAT_ROUNDING(std::runtime_error("itrunc: large float rounding."), static_cast<To>(x)) : static_cast<To>(x) ; }
void Tester12306::Test() { auto p1 = std::make_shared<Cozy::BlockedUrlGeneraterRunner>(); auto p2 = std::make_shared<Cozy::BlockedUrl2ResultRunner>(); auto gen = std::make_shared<Generater12306>(); for (int i = 0; i < m_times; ++i) { gen->Add(MakeUrl()); } auto res = std::make_shared<JpgDownloader>(); p1->From(gen); p1->To(p2); p2->To(res); p2->Start(); p1->Start(); }
To lexical_cast(From a) { To res = To(); std::stringstream str; if(str << a && str >> res) { return res; } else { throw bad_lexical_cast();
inline SPROUT_CONSTEXPR To iround(FloatType x) { return sprout::math::isnan(x) || sprout::math::isinf(x) ? sprout::numeric_limits<To>::min() : x == 0 ? To(0) : sprout::numeric_limits<To>::max() < x || sprout::numeric_limits<To>::min() > x ? SPROUT_MATH_THROW_LARGE_FLOAT_ROUNDING(std::runtime_error("iround: large float irounding."), x) : x < 0 ? sprout::math::detail::iround_impl_nagative(x, static_cast<To>(x)) : sprout::math::detail::iround_impl_positive(x, static_cast<To>(x)) ; }
SPRIG_INLINE typename boost::enable_if< boost::mpl::and_< str_cast_detail::is_specialized<To>, str_cast_detail::is_not_convertible<From, To>, str_cast_detail::has_c_str<From>, str_cast_detail::is_convertible_from_c_str<From, To> >, To >::type str_cast(From const& from) { return To(str_cast_traits<From>::c_str(from)); }
inline To as( From f ) { To t = static_cast<To>( f ); // Casting between arithmetic types assert( std::is_arithmetic<To>::value ); assert( std::is_arithmetic<From>::value ); // is "safe" if (a) it's reversible, and assert( f == static_cast<From>( t ) ); // (b) both values have the same sign. assert( ( From() < f ) == ( To() < t ) ); return t; }
SPRIG_INLINE typename boost::enable_if< boost::mpl::and_< str_cast_detail::is_specialized<To>, str_cast_detail::is_convertible<From, To>, boost::mpl::or_< str_cast_detail::is_c_str<From>, str_cast_detail::is_specialized<From> > >, To >::type str_cast(From from) { return To(from); }
BigNum::BigNum(const char *s) { while (*s == '0')s++; if (!*s){ To(0); return; } int l = strlen(s); size_ = (l - 1) / kDigits + 1; int p = size_ - 1; d_[p] = 0; for (int i = 0; i < l; i++) { if (i == l - p * kDigits)d_[--p] = 0; d_[p] = d_[p] * 10 + s[i] - '0'; } }
SPRIG_INLINE typename boost::enable_if< is_wchar_c_str<From>, To >::type convert(From from) { sprig::locale_saver saver; std::setlocale(LC_CTYPE, ""); std::size_t const size = /*std*/::wcstombs(0, from, 0) + 1; if (size == static_cast<std::size_t>(-1)) { throw bad_str_cast("error in std::wcstombs()"); } boost::shared_array<char> dest(new char[size]); /*std*/::wcstombs(dest.get(), from, size); return To(dest.get()); }
BEmailMessage * BEmailMessage::ForwardMessage(bool accountFromMail, bool includeAttachments) { BString header = "------ Forwarded Message: ------\n"; header << "To: " << To() << '\n'; header << "From: " << From() << '\n'; if (CC() != NULL) { // Can use CC rather than "Cc" since display only. header << "CC: " << CC() << '\n'; } header << "Subject: " << Subject() << '\n'; header << "Date: " << Date() << "\n\n"; if (_text_body != NULL) header << _text_body->Text() << '\n'; BEmailMessage *message = new BEmailMessage(); message->SetBodyTextTo(header.String()); // set the subject BString subject = Subject(); if (subject.IFindFirst("fwd") == B_ERROR && subject.IFindFirst("forward") == B_ERROR && subject.FindFirst("FW") == B_ERROR) subject << " (fwd)"; message->SetSubject(subject.String()); if (includeAttachments) { for (int32 i = 0; i < CountComponents(); i++) { BMailComponent *cmpt = GetComponent(i); if (cmpt == _text_body || cmpt == NULL) continue; //---I am ashamed to have the written the code between here and the next comment // ... and you still managed to get it wrong ;-)), axeld. // we should really move this stuff into copy constructors // or something like that BMallocIO io; cmpt->RenderToRFC822(&io); BMailComponent *clone = cmpt->WhatIsThis(); io.Seek(0, SEEK_SET); clone->SetToRFC822(&io, io.BufferLength(), true); message->AddComponent(clone); } } if (accountFromMail) message->SendViaAccountFrom(this); return message; }
static ews_recurrence * To(calIRecurrenceInfo * info, calIDateTime * dtStart) { nsCOMPtr<calIRecurrenceRule> rule; uint32_t count; calIRecurrenceItem ** items; nsresult rv = info->GetRecurrenceItems(&count, &items); if (NS_FAILED(rv) || count == 0) { return nullptr; } for(uint32_t i = 0; i < count; i++) { rule = do_QueryInterface(items[i]); if (rule) break; } if (!rule) return nullptr; ews_recurrence * r = (ews_recurrence*)malloc(sizeof(ews_recurrence)); memset(r, 0, sizeof(ews_recurrence)); To(rule, dtStart, &r->pattern); To(rule, &r->range); return r; }
void CALLBACK PacketRuleCallback (LPVOID lpContext, const CKAHFW::PacketRuleNotify *pNotify) { CString strMessage; FILETIME ft; SYSTEMTIME st; TCHAR szTime[0x100]; FileTimeToLocalFileTime ((FILETIME *)&pNotify->Time, &ft); FileTimeToSystemTime (&ft, &st); GetTimeFormat (LOCALE_USER_DEFAULT, 0, &st, NULL, szTime, 0x100); CString From (CKAHUM_IPTOA (pNotify->LocalAddress)), To (CKAHUM_IPTOA (pNotify->RemoteAddress)), Proto; if (pNotify->Proto == 6 || pNotify->Proto == 17) { From.Format (_T("%s:%d"), CString (From), pNotify->TCPUDPLocalPort); To.Format (_T("%s:%d"), CString (To), pNotify->TCPUDPRemotePort); } if (pNotify->Proto == 6) Proto = _T("TCP"); else if (pNotify->Proto == 17) Proto = _T("UDP"); else if (pNotify->Proto == 1) Proto.Format (_T("ICMP (%d,%d)"), pNotify->ICMPType, pNotify->ICMPCode); else Proto.Format (_T("proto %d"), pNotify->Proto); strMessage.Format (_T("[%s %c%c] %s, %s %s %s %s packet %s by '%ls' rule"), szTime, pNotify->Notify ? _T('n') : _T(' '), pNotify->Log ? _T('l') : _T(' '), Proto, From, pNotify->IsIncoming ? _T("<-") : _T("->"), To, pNotify->IsStream ? (pNotify->IsStreamIncoming ? _T("(<<)") : _T("(>>)")) : _T("(\?\?)"), pNotify->IsBlocking ? _T("blocked") : _T("allowed"), pNotify->RuleName); CCKAHUMTESTUI2Dlg *pThis = (CCKAHUMTESTUI2Dlg *)lpContext; pThis->AddStringToLog (strMessage); }
ConversionEx() : Conversion(From(), To()) { }
To duration_cast(duration const& d) { rational dstr(To::period::num, To::period::den); rational tr = d.ratio() / dstr; return To(tr.numerator() / tr.denominator()); }
bool RobboMove(typePos *Position, uint32 *am, int *v, int *cap) { int va, v2, av = 0xff, zv = 0x00, cp; typeMoveList move_list[256]; typeMoveList *q; uint32 m; if (Position->Dyn->oo) return false; if (!RobboTotalBaseScore(Position, &va) || va == dLoss) return false; Mobility(Position); if (IsCheck) EvasionMoves(Position, move_list, 0xffffffffffffffff); else { q = CaptureMoves(Position, move_list, 0xffffffffffffffff); OrdinaryMoves(Position, q); } for (q = move_list; q->move; q++) { m = q->move & 0x7fff; Position->StackHeight = 0; Make(Position, m); Position->StackHeight = 1; Mobility(Position); if (IsIllegal) { Undo(Position, m); Position->StackHeight = 1; continue; } if (!RobboTotalBaseScore(Position, &v2)) { Undo(Position, m); Position->StackHeight = 1; return false; } if (DiskLoss(va)) { uint32 m3; int v3; if (!RobboMove(Position, &m3, &v3, &cp)) { Undo(Position, m); Position->StackHeight = 1; return false; } if (v3 > zv && ((!Position->Dyn->cp && !(m & FlagMask) && ((!cp && (!(m3 & FlagMask))))) || va <= dLoss + 1)) { *am = m; *v = zv = v3; *cap = Position->Dyn->cp; } } Undo(Position, m); Position->StackHeight = 1; if (DiskDraw(va) && DiskDraw(v2)) { *am = m; *v = dDraw; *cap = false; return true; } if (DiskWin(va) && DiskLoss(v2)) { if (Position->sq[To(m)] || (m & FlagMask)) { *am = m; *v = v2; *cap = true; return true; } if (v2 < av) { *am = m; *v = av = v2; *cap = false; } } } return true; }
static To cast(From X) { return To(X); }
To duration_cast(From const& dt) { return To(From::period::num * dt.count(), From::period::den); }
void CTeleport::Tick() { const int MAX_TILES = 5; for(int i = 0; i < 4; i++) { const int STEPS = 32; int X, Y; switch(i) { case 0: X = -STEPS; Y = 0; break; case 1: X = 0; Y = -STEPS; break; case 2: X = STEPS; Y = 0; break; case 3: X = 0; Y = STEPS; break; } if(!m_ItemID[i]) { for(int j = 1; j <= MAX_TILES+1; j++) { int Number = -1; if(j < MAX_TILES) { vec2 TestPos = vec2(m_Pos.x+X*j, m_Pos.y +Y*j); Number = GameServer()->Collision()->Number(TestPos); } if(Number != -1 && j < MAX_TILES+1) { if(i == 2 || i == 3) { m_ItemID[i] += Number*pow(10.0f, MAX_TILES-j); } else { m_ItemID[i] += Number*pow(10.0f, j-1); } } else { if((i == 2 || i == 3) && j < MAX_TILES+1) m_ItemID[i] = m_ItemID[i]/pow(10.0f, MAX_TILES+1-j); if(!m_ItemID[i]) m_ItemID[i] = -1; break; } } } } /*for(int j = 0; j < 4; j++) { if(m_ItemID[j] > 0) dbg_msg("...", "%s %d) %d", m_Type?"From":"To", j, m_ItemID[j]); }*/ if(m_Type) From(); else To(); }
bool Aircraft::Step(float FT, sf::Vector2f Wind) { bool Die = false; Time += FT; const sf::Vector2f &Me = Shape.getPosition(); TakeoffSound.setPosition(Me.x, Me.y, 0.f); FlySound.setPosition(Me.x, Me.y, 0.f); LandingSound.setPosition(Me.x, Me.y, 0.f); Shape.update(FT); float Turning = 0.f; switch (State) { case FlyingIn: { sf::Vector2f To(400.f, 300.f); Shape.setRotation(Angle(Me - To)); if (P.NumPoints() > 0) { State = FlyingPath; } else if (Me.x > 100 && Me.x < 700 && Me.y > 100 && Me.y < 500) { State = FlyingFree; Turning = 0.2f; } break; } case FlyingOut: { sf::Vector2f From(400.f, 300.f); Shape.rotate(AngleDiff(Shape.getRotation(), Angle(From - Me)) * FT); float Scale = Map(Speed / Template.Speed, 0.f, 1.f, 1.f, 0.9f); float ShadowRadius = Radius * Scale; sf::Vector2f Shadow = sf::Transform().scale(sf::Vector2f(Scale, Scale), sf::Vector2f(800 / 2, 600 * 0.8f)).transformPoint(Me); if ((Me.x < -Radius || Me.x > (800 + Radius) || Me.y < -Radius || Me.y > (600 + Radius)) && (Shadow.x < -ShadowRadius || Shadow.x > (800 + ShadowRadius) || Shadow.y < -ShadowRadius || Shadow.y > (600 + ShadowRadius))) { Die = true; } break; } case FlyingFree: { float Angle = AngleFix(Shape.getRotation()), AddAngle; if ((Me.x < 100 && Angle > 180) || (Me.x > 700 && Angle < 180) || (Me.y < 100 && (Angle > 90 && Angle < 270)) || (Me.y > 500 && (Angle > 270 || Angle < 90))) { AddAngle = Turn; Turning = Turn / 10; } else if ((Me.x < 100 && Angle <= 180) || (Me.x > 700 && Angle >= 180) || (Me.y < 100 && (Angle <= 90 || Angle >= 270)) || (Me.y > 500 && (Angle <= 270 && Angle >= 90))) { AddAngle = -Turn; Turning = -Turn / 10; } else { AddAngle = Turning; } Angle += AddAngle; Shape.setRotation(AngleFix(Angle)); if (P.NumPoints() > 0) { State = FlyingPath; } break; } case FlyingPath: { if (P.NumPoints() > 0) { const sf::Vector2f To = P[0]; // might crash if (InRange(Me, To, 5)) P.RemovePoint(0); float Target = Angle(Me - To); Shape.setRotation(Target); if (Land && P.NumPoints() == 0 && /*Land->OnMe(Me) &&*/ P.Highlight /*abs(AngleDiff(GetAngle(), Land->GetAngle())) <= Land->GetTemplate().LandAngle*/) { FlySound.stop(); LandingSound.play(); State = Landing; LandPoint = Me; } else if (P.NumPoints() == 0) { if (Direction == Out && ((OutDirection == OutUp && To.y < 50) || (OutDirection == OutDown && To.y > 550) || (OutDirection == OutLeft && To.x < 50) || (OutDirection == OutRight && To.x > 750))) { State = FlyingOut; } else { State = FlyingFree; } } } break; } case Landing: { sf::Vector2f Runway = Land->GetPos() + PolarToRect(sf::Vector2f(Land->GetLength() * 1.5f, Land->GetAngle())); float Dist = Distance(Me, LandPoint); Speed = Map(Dist, 0.f, Land->GetLength() * 1.1f, Template.Speed, 0.f); if (Land->GetTemplate().Directional) { Shape.rotate(AngleDiff(Shape.getRotation(), Angle(Me - Runway)) * 3 * FT); } float Scale = Map2(Dist, 0.f, Land->GetLength() * 1.1f, 1.f, 0.65f); Shape.setScale(Scale, Scale); Radius = Template.Radius * Scale; if (Dist > Land->GetLength()) { Die = true; } break; } case TakingOff: { sf::Vector2f Runway = Land->GetPos() + PolarToRect(sf::Vector2f(Land->GetLength() * 1.5f, Land->GetAngle())); float Dist = Distance(Me, Land->GetPos()); Speed = Map(Dist, 0.f, Land->GetLength() * 1.1f, 10.f, Template.Speed); if (Land->GetTemplate().Directional) { Shape.rotate(AngleDiff(Shape.getRotation(), Angle(Me - Runway)) * 3 * FT); } float Scale = Map2(Dist, 0.f, Land->GetLength() * 1.1f, 0.65f, 1.f); Shape.setScale(Scale, Scale); Radius = Template.Radius * Scale; if (Dist > Land->GetLength()) { FlySound.play(); State = FlyingFree; Land = 0; } break; } } Shape.move(PolarToRect(sf::Vector2f(Speed, Shape.getRotation())) * FT); Shape.move(Wind * FT * Magnitude(Shape.getScale()) / sqrt(2.f)); return Die; }
/** \brief Load all the initial dictionary words. */ void init_dictionary(int dictsize) { init_compiler(dictsize); memory_words(); compile_primitives(); compile_core_constants(); core_words(); core_extension_words(); compile_dictionary_words(); controlflow_words(); more_core_words(); compile_double(); string_words(); exception_words(); file_words(); format_words(); compile_stack_words(); implementation_words(); vocabulary_words(); interpreter_words(); platform_words(); /* FIX - NEED TO DO THESE */ // Primitive( "d<", &lesser ); /* ( d1 d2 -- f ) */ // Primitive( "d>", &lesser ); /* ( d1 d2 -- f ) */ // Primitive( "u*", &um_star ); /* ( x y -- x*y ) */ // Primitive( "du*", &um_star ); /* ( x y -- x*y ) */ // Primitive( "du/mod", &um_star ); /* ( x y -- x*y ) */ // Primitive( "du<", &um_star ); /* ( x y -- x*y ) */ // Primitive( "m+", &um_star ); /* ( x y -- x*y ) */ // Primitive( "m-", &um_star ); /* ( x y -- x*y ) */ // Primitive( "m*", &um_star ); /* ( x y -- x*y ) */ // Primitive( "m*/", &um_star ); /* ( x y -- x*y ) */ // Primitive( "m/", &um_star ); /* ( x y -- x*y ) */ // Primitive( "m/mod", &um_star ); /* ( x y -- x*y ) */ /* FIX - NEED TO DO THESE */ /* FIX - these two words are no longer used - why are they here ?? */ // Primitive( "um*", &um_star ); /* ( x y -- x*y ) */ // Colon( "udm*" ); /* ( d.lo d.hi n -- d.lo' d.hi' ) */ // c("tuck"); c("um*"); c("drop"); c("-rot"); c("um*"); // c("rot"); c("+"); End(); Colon( ".version" ); DotQuote("Portable ANS Forth - [email protected]"); c("cr"); End(); Colon( "rstrace" ); DotQuote("( R: "); c("rp@"); c("rp0"); c("@"); Do(); c("i"); c("."); c("space"); c("/cell"); PlusLoop(); DotQuote(" )"); c("cr"); End(); Variable( "argument-hook" ); /* To( Tick("ndrop"), "argument-hook" ); */ ACF x = find("unnest"); To( (Cell)x, "argument-hook" ); Colon( "cold" ); c(".version"); c("cold-chain"); /* included may be replaced with path-included which reads FORTH_PATH environment variable to look in selected directories */ c("debug"); c("@"); If(); DotQuote("Loading Forth files..."); Then(); /* StringLiteral("base.fth"); c("included"); */ DotQuote("loading base.fth"); c("cr"); StringLiteral("base.fth"); Tick("included"); c("catch"); c("?aborted"); If(); DotQuote("Failed to load."); c("cr"); Then(); c("debug"); c("@"); If(); DotQuote("done."); c("cr"); Then(); c("hex"); #if 0 c("argument-hook"); c("@"); Tick("execute"); c("catch"); c("?aborted"); If(); DotQuote("argument-hook failed"); c("cr"); Then(); #endif c("read-eval-loop"); End(); Colon( "warm" ); DotQuote( "Warm Started." ); c("cr"); c("rstrace"); c("quit"); End(); /* header */ Colon( "name," ); c("dup"); c("1+"); c("talign"); c("allot"); c("dup"); c("here"); c("1-"); c("c!"); c("here"); c("1-"); c("over"); c("-"); c("swap"); c("cmove"); End(); Colon( "header" ); c("name,"); c("link"); c("do-create"); c(","); End(); Colon( "create" ); c("parse-word"); c("header"); End(); Colon( "codefield" ); /* ( codefield -- ) */ c("lastacf"); c("!"); End(); Colon( ":" ); c("create"); c("hide"); c("do-colon"); c("codefield"); c("]"); End(); Colon( ";" ); c("compile"); c("unnest"); c("["); c("reveal"); End(); immediate(); }
/* ******************************************************************************** * * * Search() is the recursive routine used to implement the alpha/beta * * negamax search (similar to minimax but simpler to code.) Search() is * * called whenever there is "depth" remaining so that all moves are subject * * to searching, or when the side to move is in check, to make sure that this * * side isn't mated. Search() recursively calls itself until depth is ex- * * hausted, at which time it calls Quiesce() instead. * * * ******************************************************************************** */ int Search(int alpha, int beta, int wtm, int depth, int ply, int do_null) { register int first_move=1; register BITBOARD save_hash_key; register int initial_alpha, value; register int extensions; /* ---------------------------------------------------------- | | | check to see if we have searched enough nodes that it | | is time to peek at how much time has been used, or if | | is time to check for operator keyboard input. this is | | usually enough nodes to force a time/input check about | | once per second, except when the target time per move | | is very small, in which case we try to check the time | | at least 10 times during the search. | | | ---------------------------------------------------------- */ if (ply >= MAXPLY-2) return(beta); nodes_searched++; if (--next_time_check <= 0) { next_time_check=nodes_between_time_checks; if (CheckInput()) Interrupt(ply); time_abort+=TimeCheck(0); if (time_abort) { abort_search=1; return(0); } } /* ---------------------------------------------------------- | | | check for draw by repetition. | | | ---------------------------------------------------------- */ if (RepetitionCheck(ply,wtm)) { value=(wtm==root_wtm) ? DrawScore() : -DrawScore(); if (value < beta) SavePV(ply,value,0); #if !defined(FAST) if(ply <= trace_level) printf("draw by repetition detected, ply=%d.\n",ply); #endif return(value); } /* ---------------------------------------------------------- | | | now call LookUp() to see if this position has been | | searched before. if so, we may get a real score, | | produce a cutoff, or get nothing more than a good move | | to try first. there are four cases to handle: | | | | 1. LookUp() returned "EXACT_SCORE" if this score is | | greater than beta, return beta. otherwise, return the | | score. In either case, no further searching is needed | | from this position. note that lookup verified that | | the table position has sufficient "draft" to meet the | | requirements of the current search depth remaining. | | | | 2. LookUp() returned "LOWER_BOUND" which means that | | when this position was searched previously, every move | | was "refuted" by one of its descendents. as a result, | | when the search was completed, we returned alpha at | | that point. we simply return alpha here as well. | | | | 3. LookUp() returned "UPPER_BOUND" which means that | | when we encountered this position before, we searched | | one branch (probably) which promptly refuted the move | | at the previous ply. | | | | 4. LookUp() returned "AVOID_NULL_MOVE" which means | | the hashed score/bound was no good, but it indicated | | that trying a null-move in this position will be a | | waste of time. | | | ---------------------------------------------------------- */ switch (LookUp(ply,depth,wtm,&alpha,beta)) { case EXACT_SCORE: if(alpha >= beta) return(beta); else { SavePV(ply,alpha,1); return(alpha); } case LOWER_BOUND: return(alpha); case UPPER_BOUND: return(beta); case AVOID_NULL_MOVE: do_null=0; } /* ---------------------------------------------------------- | | | now it's time to try a probe into the endgame table- | | base files. this is done if (a) the previous move was | | a capture or promotion, unless we are at very shallow | | plies (<4) in the search; (b) there are less than 5 | | pieces left (currently all interesting 4 piece endings | | are available.) | | | ---------------------------------------------------------- */ #if defined(TABLEBASES) if (TotalPieces < 5) do { register int wpawn, bpawn; int tb_value; if (TotalWhitePawns && TotalBlackPawns) { wpawn=FirstOne(WhitePawns); bpawn=FirstOne(BlackPawns); if (FileDistance(wpawn,bpawn) == 1) { if(((Rank(wpawn)==1) && (Rank(bpawn)>2)) || ((Rank(bpawn)==6) && (Rank(wpawn)<5)) || EnPassant(ply)) break; } } tb_probes++; if (EGTBScore(ply, wtm, &tb_value)) { tb_probes_successful++; alpha=tb_value; if (abs(alpha) > MATE-100) alpha+=(alpha > 0) ? -(ply-1) : +(ply-1); else if (alpha == 0) alpha=(wtm==root_wtm) ? DrawScore() : -DrawScore(); if(alpha >= beta) return(beta); else { SavePV(ply,alpha,2); return(alpha); } } } while(0); # endif /* ---------------------------------------------------------- | | | initialize. | | | ---------------------------------------------------------- */ in_check[ply+1]=0; extended_reason[ply+1]=no_extension; initial_alpha=alpha; last[ply]=last[ply-1]; killer_count1[ply+1]=0; killer_count2[ply+1]=0; /* ---------------------------------------------------------- | | | first, we try a null move to see if we can get a quick | | cutoff with only a little work. this operates as | | follows. instead of making a legal move, the side on | | move 'passes' and does nothing. the resulting position | | is searched to a shallower depth than normal (usually | | one ply less but settable by the operator) this should | | result in a cutoff or at least should set the lower | | bound better since anything should be better than not | | doing anything. | | | | this is skipped for any of the following reasons: | | | | 1. the side on move is in check. the null move | | results in an illegal position. | | 2. no more than one null move can appear in succession | | or else the search will degenerate into nothing. | | 3. the side on move has little material left making | | zugzwang positions more likely. | | | ---------------------------------------------------------- */ # if defined(NULL_MOVE_DEPTH) if (do_null && !in_check[ply] && ((wtm) ? TotalWhitePieces : TotalBlackPieces)>2) { current_move[ply]=0; current_phase[ply]=NULL_MOVE; #if !defined(FAST) if (ply <= trace_level) SearchTrace(ply,depth,wtm,alpha,beta,"Search",0); #endif position[ply+1]=position[ply]; Rule50Moves(ply+1)++; save_hash_key=HashKey; if (EnPassant(ply)) { HashEP(EnPassant(ply+1),HashKey); EnPassant(ply+1)=0; } if ((depth-NULL_MOVE_DEPTH-INCREMENT_PLY) >= INCREMENT_PLY) value=-Search(-beta,-alpha,ChangeSide(wtm),depth-NULL_MOVE_DEPTH-INCREMENT_PLY,ply+1,NO_NULL); else value=-Quiesce(-beta,-alpha,ChangeSide(wtm),ply+1); HashKey=save_hash_key; if (abort_search) return(0); if (value >= beta) { StoreRefutation(ply,depth,wtm,beta); return(beta); } } # endif /* ---------------------------------------------------------- | | | if there is no best move from the hash table, and this | | is a PV node, then we need a good move to search | | first. while killers and history moves are good, they | | are not "good enough". the simplest action is to try | | a shallow search (depth-2) to get a move. note that | | when we call Search() with depth-2, it, too, will | | not have a hash move, and will therefore recursively | | continue this process, hence the name "internal | | iterative deepening." | | | ---------------------------------------------------------- */ next_status[ply].phase=FIRST_PHASE; if (hash_move[ply]==0 && (depth > 2*INCREMENT_PLY) && (((ply & 1) && alpha == root_alpha && beta == root_beta) || (!(ply & 1) && alpha == -root_beta && beta == -root_alpha))) { current_move[ply]=0; value=Search(alpha,beta,wtm,depth-2*INCREMENT_PLY,ply,DO_NULL); if (abort_search) return(0); if (value <= alpha) { value=Search(-MATE,beta,wtm,depth-2*INCREMENT_PLY,ply,DO_NULL); if (abort_search) return(0); } else if (value < beta) { if ((int) pv[ply-1].path_length >= ply) hash_move[ply]=pv[ply-1].path[ply]; } else hash_move[ply]=current_move[ply]; last[ply]=last[ply-1]; next_status[ply].phase=FIRST_PHASE; } /* ---------------------------------------------------------- | | | now iterate through the move list and search the | | resulting positions. note that Search() culls any | | move that is not legal by using Check(). the special | | case is that we must find one legal move to search to | | confirm that it's not a mate or draw. | | | ---------------------------------------------------------- */ while ((current_phase[ply]=(in_check[ply]) ? NextEvasion(ply,wtm) : NextMove(depth,ply,wtm))) { extended_reason[ply]&=check_extension; #if !defined(FAST) if (ply <= trace_level) SearchTrace(ply,depth,wtm,alpha,beta,"Search",current_phase[ply]); #endif /* ---------------------------------------------------------- | | | if two successive moves are capture / re-capture so | | that the material score is restored, extend the search | | by one ply on the re-capture since it is pretty much | | forced and easy to analyze. | | | ---------------------------------------------------------- */ extensions=-INCREMENT_PLY; if (Captured(current_move[ply]) && Captured(current_move[ply-1]) && To(current_move[ply-1]) == To(current_move[ply]) && (p_values[Captured(current_move[ply-1])+7] == p_values[Captured(current_move[ply])+7] || Promote(current_move[ply-1])) && !(extended_reason[ply-1]&recapture_extension)) { extended_reason[ply]|=recapture_extension; recapture_extensions_done++; extensions+=RECAPTURE; } /* ---------------------------------------------------------- | | | if we push a passed pawn, we need to look deeper to | | see if it is a legitimate threat. | | | ---------------------------------------------------------- */ if (Piece(current_move[ply])==pawn && !FutileAhead(wtm) && ((wtm && To(current_move[ply])>H5 && TotalBlackPieces<16 && !And(mask_pawn_passed_w[To(current_move[ply])],BlackPawns)) || (!wtm && To(current_move[ply])<A4 && TotalWhitePieces<16 && !And(mask_pawn_passed_b[To(current_move[ply])],WhitePawns)) || push_extensions[To(current_move[ply])]) && Swap(From(current_move[ply]),To(current_move[ply]),wtm) >= 0) { extended_reason[ply]|=passed_pawn_extension; passed_pawn_extensions_done++; extensions+=PASSED_PAWN_PUSH; } /* ---------------------------------------------------------- | | | now make the move and search the resulting position. | | if we are in check, the current move must be legal | | since NextEvasion ensures this, otherwise we have to | | make sure the side-on-move is not in check after the | | move to weed out illegal moves and save time. | | | ---------------------------------------------------------- */ MakeMove(ply,current_move[ply],wtm); if (in_check[ply] || !Check(wtm)) { /* ---------------------------------------------------------- | | | if the move to be made checks the opponent, then we | | need to remember that he's in check and also extend | | the depth by one ply for him to get out. | | | ---------------------------------------------------------- */ if (Check(ChangeSide(wtm))) { in_check[ply+1]=1; extended_reason[ply+1]=check_extension; check_extensions_done++; extensions+=IN_CHECK; } else { in_check[ply+1]=0; extended_reason[ply+1]=no_extension; } /* ---------------------------------------------------------- | | | now we toss in the "razoring" trick, which simply says | | if we are doing fairly badly, we can reduce the depth | | an additional ply, if there was nothing at the current | | ply that caused an extension. | | | ---------------------------------------------------------- */ if (depth < 3*INCREMENT_PLY && !in_check[ply] && extensions == -INCREMENT_PLY) { register int val=(wtm) ? Material : -Material; if (val+1500 < alpha) extensions-=INCREMENT_PLY; } /* ---------------------------------------------------------- | | | if there's only one legal move, extend the search one | | additional ply since this node is very easy to search. | | | ---------------------------------------------------------- */ if (first_move) { if (last[ply]-last[ply-1] == 1) { extended_reason[ply]|=one_reply_extension; one_reply_extensions_done++; extensions+=ONE_REPLY_TO_CHECK; } if (depth+MaxExtensions(extensions) >= INCREMENT_PLY) value=-Search(-beta,-alpha,ChangeSide(wtm),depth+MaxExtensions(extensions),ply+1,DO_NULL); else { value=-Quiesce(-beta,-alpha,ChangeSide(wtm),ply+1); } if (abort_search) { UnMakeMove(ply,current_move[ply],wtm); return(0); } first_move=0; } else { if (depth+MaxExtensions(extensions) >= INCREMENT_PLY) value=-Search(-alpha-1,-alpha,ChangeSide(wtm),depth+MaxExtensions(extensions),ply+1,DO_NULL); else { value=-Quiesce(-alpha-1,-alpha,ChangeSide(wtm),ply+1); } if (abort_search) { UnMakeMove(ply,current_move[ply],wtm); return(0); } if (value>alpha && value<beta) { if (depth+MaxExtensions(extensions) >= INCREMENT_PLY) value=-Search(-beta,-alpha,ChangeSide(wtm),depth+MaxExtensions(extensions),ply+1,DO_NULL); else value=-Quiesce(-beta,-alpha,ChangeSide(wtm),ply+1); if (abort_search) { UnMakeMove(ply,current_move[ply],wtm); return(0); } } } if (value > alpha) { if(value >= beta) { HistoryRefutation(ply,depth,wtm); UnMakeMove(ply,current_move[ply],wtm); StoreRefutation(ply,depth,wtm,beta); return(beta); } alpha=value; } } UnMakeMove(ply,current_move[ply],wtm); } /* ---------------------------------------------------------- | | | all moves have been searched. if none were legal, | | return either MATE or DRAW depending on whether the | | side to move is in check or not. | | | ---------------------------------------------------------- */ if (first_move == 1) { value=(Check(wtm)) ? -(MATE-ply) : ((wtm==root_wtm) ? DrawScore() : -DrawScore()); if(value > beta) value=beta; else if (value < alpha) value=alpha; if (value >=alpha && value <beta) { SavePV(ply,value,0); #if !defined(FAST) if (ply <= trace_level) printf("Search() no moves! ply=%d\n",ply); #endif } return(value); } else { if (alpha != initial_alpha) { memcpy(&pv[ply-1].path[ply],&pv[ply].path[ply],(pv[ply].path_length-ply+1)*4); memcpy(&pv[ply-1].path_hashed,&pv[ply].path_hashed,3); pv[ply-1].path[ply-1]=current_move[ply-1]; HistoryBest(ply,depth,wtm); } StoreBest(ply,depth,wtm,alpha,initial_alpha); /* ---------------------------------------------------------- | | | if the 50-move rule is drawing close, then adjust the | | score to reflect the impending draw. | | | ---------------------------------------------------------- */ if (Rule50Moves(ply) > 99) { value=(wtm==root_wtm) ? DrawScore() : -DrawScore(); if (value < beta) SavePV(ply,value,0); #if !defined(FAST) if(ply <= trace_level) printf("draw by 50-move rule detected, ply=%d.\n",ply); #endif return(value); } return(alpha); } }
To operator()(void) const { return To(); // use default value }
operator String() const { String to; To(to); return to; }
* * ************************************************************ */ HashKey = tree->save_hash_key[ply]; PawnHashKey = tree->save_pawn_hash_key[ply]; /* ************************************************************ * * * Now do the things that are common to all pieces, such * * as updating the bitboards and hash signature. * * * ************************************************************ */ piece = Piece(move); from = From(move); to = To(move); captured = Captured(move); promote = Promote(move); bit_move = SetMask(from) | SetMask(to); ClearSet(bit_move, Pieces(side, piece)); ClearSet(bit_move, Occupied(side)); PcOnSq(to) = 0; PcOnSq(from) = pieces[side][piece]; /* ************************************************************ * * * Now do the piece-specific things by jumping to the * * appropriate routine (this only has to deal with pawns * * and king moves that are castling moves. * * * ************************************************************