Ejemplo n.º 1
0
Chapter::Chapter(const int chapter_number)
  :
    m_ball_game_chapter{*this},
    m_bye_text{},
    m_consequence{},
    m_chapter_number{chapter_number},
    m_chapter_type{ChapterType::normal},
    m_dice_game_chapter{*this},
    m_fighting_chapter{FightingChapter(*this)},
    m_game_lost_chapter{this},
    m_game_won_chapter{this},
    m_luck_chapter(*this),
    m_observer{nullptr},
    m_options_chapter{},
    m_pawn_shop_chapter(this),
    m_pill_game_chapter{*this},
    m_shop_chapter{this},
    m_skill_chapter{*this},
    m_text{},
    m_verbose{false}
{
  if (m_verbose) { std::clog << __func__ << std::endl; }
  Helper h;

  if (m_verbose) { std::clog << __func__ << std::endl; }

  #ifdef USE_TEXT_FILES_FOR_INPUT
  const std::string filename{h.GetFilesFolder() + h.ToStr(chapter_number) + ".txt"};
  if (!h.IsRegularFile(filename))
  {
    std::stringstream msg;
    msg << __func__ << ": ERROR: File " << filename << " does not exist";
    Helper().Cout(msg.str());
    throw std::runtime_error(msg.str());
  }
  const std::vector<std::string> lines{h.FileToVector(filename)};
  #else
  const std::vector<std::string> lines(1,GetFile(h.ToStr(chapter_number)));
  #endif
  std::stringstream s;
  std::copy(std::begin(lines),std::end(lines),std::ostream_iterator<std::string>(s," "));

  m_text = h.ReadText(s);

  m_chapter_type = ReadChapterType(s);

  switch (m_chapter_type)
  {
    case ChapterType::game_lost: return;
    case ChapterType::game_won: return;
    default: break;
  }

  while (!s.eof())
  {
    const std::string str{h.ReadString(s)};
    if (str.empty())
    {
      break;
    }
    else if (str == "Bye" || str == "bye")
    {
      m_bye_text = h.ReadText(s);
    }
    else if (str == "Change" || str == "change")
    {
      m_consequence.Add(ParseConsequence(s));
    }
    else if (str == "Escape" || str == "escape")
    {
      GetFighting().SetRoundsToEscape(h.ReadInt(s));
      GetFighting().SetEscapeToChapter(h.ReadInt(s));
    }
    else if (str == "Fight_both" || str == "fight_both")
    {
      GetFighting().SetFightSequentially(false);
    }
    else if (str == "Luck" || str == "luck")
    {
      assert(this->m_chapter_type == ChapterType::test_your_luck);
      const std::string luck_text{h.ReadText(s)};
      assert(!luck_text.empty());
      GetLuck().SetLuckText(luck_text);
      const std::string goto_str{h.ReadString(s)};
      assert(goto_str == "goto");
      const int luck_chapter{h.ReadInt(s)};
      assert(luck_chapter > 1);
      GetLuck().SetLuckChapter(luck_chapter);
    }
    else if (str == "Monster" || str == "monster")
    {
      this->m_chapter_type = ChapterType::fight;
      const Monster monster{ParseMonster(s)};
      GetFighting().AddMonster(monster);
    }
    else if (str == "Next_chapter" || str == "goto")
    {
      m_consequence.SetNextChapter(h.ReadInt(s));
    }
    else if (str == "No_luck" || str == "no_luck")
    {
      assert(this->m_chapter_type == ChapterType::test_your_luck);
      //s << std::noskipws; //Obligatory
      //Parse(s,' '); //You expect a space after a word
      const std::string no_luck_text{h.ReadText(s)};
      assert(!no_luck_text.empty());
      GetLuck().SetNoLuckText(no_luck_text);
      const std::string then{h.ReadString(s)};
      if (then == "change")
      {
        const Consequence no_luck_consequence{ParseConsequence(s)};
        GetLuck().SetNoLuckConsequence(no_luck_consequence);
        const std::string goto_str{h.ReadString(s)};
        assert(goto_str == "goto");
      }
      else
      {
        assert(then == "goto");
      }
      const int no_luck_chapter{h.ReadInt(s)};
      assert(no_luck_chapter > 1);
      GetLuck().SetNoLuckChapter(no_luck_chapter);
    }
    else if (str == "No_skill" || str == "no_skill")
    {
      assert(this->m_chapter_type == ChapterType::test_your_skill);
      //Parse(s,' '); //You expect a space after a word
      const std::string no_skill_text{h.ReadText(s)};
      assert(!no_skill_text.empty());
      GetSkill().SetNoSkillText(no_skill_text);
      const std::string then_str{h.ReadString(s)};
      Consequence consequence;
      if (then_str == "goto")
      {
        consequence.SetNextChapter(h.ReadInt(s));
      }
      else if (then_str == "change")
      {
        consequence = ParseConsequence(s);
        //Also read goto
        const std::string goto_str{h.ReadString(s)};
        assert(goto_str == "goto");
        consequence.SetNextChapter(h.ReadInt(s));
      }
      else
      {
        assert(!"Should not get here");
      }
      GetSkill().SetNoSkillConsequence(consequence);
    }
    else if (str == "Option" || str == "option")
    {
      const std::string option_text{h.ReadText(s)};
      const std::string t{h.ReadString(s)};
      if (t == "if")
      {
        const Condition condition{ParseCondition(s)};

        const std::string then_str{h.ReadString(s)};
        Consequence consequence;
        if (then_str == "goto")
        {
          consequence.SetNextChapter(h.ReadInt(s));
        }
        else if (then_str == "change")
        {
          consequence = ParseConsequence(s);
          //Also read goto
          const std::string goto_str{h.ReadString(s)};
          assert(goto_str == "goto");
          consequence.SetNextChapter(h.ReadInt(s));
        }
        else
        {
          assert(!"Should not get here");
        }
        Option option(option_text,consequence);
        option.SetCondition(condition);
        GetOptions().AddOption(option);
      }
      else if (t == "ifnot")
      {
        Condition condition;
        const std::string what{h.ReadString(s)};
        if (IsItem(what))
        {
          const Item item_not_needed{ToItem(what)};
          condition.AddItemNotNeeded(item_not_needed);
        }
        else
        {
          std::cerr << "Unknown item " << what << " in chapter " << chapter_number << std::endl;
          assert(!"Should not get here");
        }
        const std::string str_goto{h.ReadString(s)};
        assert(str_goto == "goto");
        Consequence consequence;
        consequence.SetNextChapter(h.ReadInt(s));
        Option option(option_text,consequence);
        option.SetCondition(condition);
        GetOptions().AddOption(option);
      }
      else if (t == "goto")
      {
        Consequence consequence;
        consequence.SetNextChapter(h.ReadInt(s));
        const Option option(option_text,consequence);
        GetOptions().AddOption(option);
      }
      else if (h.IsInt(t))
      {
        std::clog << "WARNING: goto omitted in chapter " << chapter_number << std::endl;
        //If no goto, just parse the number
        Consequence consequence;
        consequence.SetNextChapter(h.ToInt(t));
        const Option option(option_text,consequence);
        GetOptions().AddOption(option);
      }
      else
      {
        std::cerr << "Unknown option " << t << " in chapter " << chapter_number <<std::endl;
        assert(!"Should not get here");
      }
    }
    else if (str == "Random_monsters" || str == "random_monsters")
    {
      std::vector<Monster> monsters{ParseMonsters(s)};
      m_chapter_type = ChapterType::fight;
      const int which_monster_index{Dice::Get()->Throw() - 1};
      assert(which_monster_index >= 0);
      assert(which_monster_index < static_cast<int>(monsters.size()));
      const Monster monster{monsters[which_monster_index]};
      m_fighting_chapter.AddMonster(monster);
    }
    else if (str == "Sell_items" || str == "sell_items")
    {
      assert(this->m_chapter_type == ChapterType::pawn_shop);
      //m_chapter_type = ChapterType::pawn_shop;
      m_pawn_shop_chapter = ParsePawnShopChapter(s,this);
    }
    else if (str == "Shop_items" || str == "shop_items")
    {
      assert(this->m_chapter_type == ChapterType::shop);
      //m_chapter_type = ChapterType::shop;
      m_shop_chapter = ParseShopChapter(s,this);
    }
    else if (str == "Skill" || str == "skill")
    {
      assert(this->m_chapter_type == ChapterType::test_your_skill);
      this->m_chapter_type = ChapterType::test_your_skill;
      //Parse(s,' '); //You expect a space after a word
      const std::string skill_text{h.ReadText(s)};
      assert(!skill_text.empty());
      GetSkill().SetSkillText(skill_text);
      const std::string then_str{h.ReadString(s)};
      Consequence consequence;
      if (then_str == "goto")
      {
        consequence.SetNextChapter(h.ReadInt(s));
      }
      else if (then_str == "change")
      {
        consequence = ParseConsequence(s);
        //Also read goto
        const std::string goto_str{h.ReadString(s)};
        assert(goto_str == "goto");
        consequence.SetNextChapter(h.ReadInt(s));
      }
      else
      {
        assert(!"Should not get here");
      }
      GetSkill().SetSkillConsequence(consequence);

    }

    else
    {
      std::cerr
        << "Chapter cannot parse chapter " << chapter_number  << '\n'
        << "Unknown string: " << str << '\n'
      ;
      assert(!"Should not get here");
    }
  }

}
void ribi::fw::Helper::Test() noexcept
{
  {
    static bool is_tested {false};
    if (is_tested) return;
    is_tested = true;
  }
  //CreateTally
  {
    const std::vector<std::string> v = { "A"};
    const std::vector<std::pair<std::string,int>> m{Helper().CreateTally(v)};
    assert(m.size() == 1);
    assert(m[0].first == "A");
    assert(m[0].second == 1);
  }
  {
    const std::vector<std::string> v = { "A", "A" };
    const std::vector<std::pair<std::string,int>> m{Helper().CreateTally(v)};
    assert(m.size() == 1);
    assert(m[0].first == "A");
    assert(m[0].second == 2);
  }
  {
    const std::vector<std::string> v = { "A", "B" };
    const std::vector<std::pair<std::string,int>> m{Helper().CreateTally(v)};
    assert(m.size() == 2);
    assert(m[0].first == "A");
    assert(m[0].second == 1);
    assert(m[1].first == "B");
    assert(m[1].second == 1);
  }
  {
    const std::vector<std::string> v = { "B", "A", "B" };
    const std::vector<std::pair<std::string,int>> m{Helper().CreateTally(v)};
    assert(m.size() == 2);
    assert(m[0].first == "B");
    assert(m[0].second == 2);
    assert(m[1].first == "A");
    assert(m[1].second == 1);
  }
  {
    assert(Helper().GetFileBasenameBoostFilesystem("") == std::string(""));
    assert(Helper().GetFileBasenameBoostFilesystem("tmp.txt") == std::string("tmp"));
    assert(Helper().GetFileBasenameBoostFilesystem("test_output.fas") == std::string("test_output"));
    assert(Helper().GetFileBasenameBoostFilesystem("test_output_0.fas") == std::string("test_output_0"));
    assert(Helper().GetFileBasenameBoostFilesystem("tmp") == std::string("tmp"));
    assert(Helper().GetFileBasenameBoostFilesystem("MyFolder/tmp") == std::string("tmp"));
    assert(Helper().GetFileBasenameBoostFilesystem("MyFolder/tmp.txt") == std::string("tmp"));
    //assert(Helper().GetFileBasenameBoostFilesystem("MyFolder\\tmp.txt") == std::string("tmp"));
    assert(Helper().GetFileBasenameBoostFilesystem("MyFolder/MyFolder/tmp") == std::string("tmp"));
    assert(Helper().GetFileBasenameBoostFilesystem("MyFolder/MyFolder/tmp.txt") == std::string("tmp"));
    //assert(Helper().GetFileBasenameBoostFilesystem("MyFolder/MyFolder\\tmp.txt") == std::string("tmp"));

    assert(Helper().GetFileBasenameBoostXpressive("") == std::string(""));
    assert(Helper().GetFileBasenameBoostXpressive("tmp.txt") == std::string("tmp"));
    assert(Helper().GetFileBasenameBoostXpressive("test_output.fas") == std::string("test_output"));
    assert(Helper().GetFileBasenameBoostXpressive("test_output_0.fas") == std::string("test_output_0"));
    assert(Helper().GetFileBasenameBoostXpressive("tmp") == std::string("tmp"));
    assert(Helper().GetFileBasenameBoostXpressive("MyFolder/tmp") == std::string("tmp"));
    assert(Helper().GetFileBasenameBoostXpressive("MyFolder/tmp.txt") == std::string("tmp"));
    assert(Helper().GetFileBasenameBoostXpressive("MyFolder\\tmp.txt") == std::string("tmp"));
    assert(Helper().GetFileBasenameBoostXpressive("MyFolder/MyFolder/tmp") == std::string("tmp"));
    assert(Helper().GetFileBasenameBoostXpressive("MyFolder/MyFolder/tmp.txt") == std::string("tmp"));
    assert(Helper().GetFileBasenameBoostXpressive("MyFolder/MyFolder\\tmp.txt") == std::string("tmp"));
  }
  //ShowPhylogeny
  {

  }
}
Ejemplo n.º 3
0
void CLoginSession::CmdRegister (void)

//	CmdRegister
//
//	Handle register command

	{
	CUIHelper Helper(m_HI);

	//	Get the fields

	CString sUsername = GetPropertyString(ID_CTRL_USERNAME, PROP_TEXT);
	CString sPassword = GetPropertyString(ID_CTRL_PASSWORD, PROP_TEXT);
	CString sPasswordConfirm = GetPropertyString(ID_CTRL_PASSWORD_CONFIRM, PROP_TEXT);
	CString sEmail = GetPropertyString(ID_CTRL_EMAIL, PROP_TEXT);
	bool bAutoSignIn = GetPropertyBool(ID_CTRL_AUTO_SIGN_IN, PROP_CHECKED);

	//	Get the text for the username. If blank, then we have an error.

	if (sUsername.IsBlank())
		{
		Helper.CreateInputErrorMessage(this, m_rcInputError, CONSTLIT("Username Missing"), CONSTLIT("You must have a username to register."));
		return;
		}

	//	Make sure the passwords match

	else if (!strEquals(sPassword, sPasswordConfirm))
		{
		Helper.CreateInputErrorMessage(this, m_rcInputError, CONSTLIT("Password Does Not Match"), CONSTLIT("The password you entered does not match the confirmation password."));
		return;
		}

	//	Validate password complexity

	CString sError;
	if (!CHexarc::ValidatePasswordComplexity(sPassword, &sError))
		{
		Helper.CreateInputErrorMessage(this, m_rcInputError, CONSTLIT("Password Is Too Easy"), sError);
		return;
		}

	//	If email is blank, explain why we need it

	if (!m_bBlankEmailWarning && sEmail.IsBlank())
		{
		Helper.CreateInputErrorMessage(this, m_rcInputError, CONSTLIT("Email Address Is Optional, but..."), CONSTLIT("If you provide your email address we will be able to reset your password if you request it."));
		m_bBlankEmailWarning = true;
		return;
		}

	//	Register the name

	m_HI.AddBackgroundTask(new CRegisterUserTask(m_HI, m_Service, sUsername, sPassword, sEmail, bAutoSignIn), this, CMD_REGISTER_COMPLETE);

	//	Disable controls

	SetPropertyBool(ID_CTRL_USERNAME, PROP_ENABLED, false);
	SetPropertyBool(ID_CTRL_PASSWORD, PROP_ENABLED, false);
	SetPropertyBool(ID_CTRL_PASSWORD_CONFIRM, PROP_ENABLED, false);
	SetPropertyBool(ID_CTRL_MAIN_ACTION, PROP_ENABLED, false);
	SetPropertyBool(ID_CTRL_EMAIL, PROP_ENABLED, false);
	SetPropertyBool(ID_CTRL_AUTO_SIGN_IN, PROP_ENABLED, false);
	SetPropertyBool(CMD_SWITCH_TO_LOGIN, PROP_ENABLED, false);
	SetPropertyBool(CMD_TOS, PROP_ENABLED, false);
	}
Ejemplo n.º 4
0
  
  E e(10, c); // expected-warning{{cannot pass object of non-POD type 'C' through variadic constructor; call will abort at runtime}} \
    // expected-error{{calling a private constructor of class 'E'}}
  (void)E(10, c); // expected-warning{{cannot pass object of non-POD type 'C' through variadic constructor; call will abort at runtime}} \
    // expected-error{{calling a private constructor of class 'E'}}

}

// PR5761: unevaluated operands and the non-POD warning
class Foo {
 public:
  Foo() {}
};

int Helper(...);
const int size = sizeof(Helper(Foo()));

namespace std {
  class type_info { };
}

struct Base { virtual ~Base(); };
Base &get_base(...);
int eat_base(...);

void test_typeid(Base &base) {
  (void)typeid(get_base(base)); // expected-warning{{cannot pass object of non-POD type 'Base' through variadic function; call will abort at runtime}} expected-warning{{expression with side effects will be evaluated despite being used as an operand to 'typeid'}}
  (void)typeid(eat_base(base)); // okay
}

 int sumNumbers(TreeNode* root) {
     if(!root)   return 0;
     return Helper(root, 0);
 }
void ribi::bm::Process::Test() noexcept
{
  {
    static bool is_tested{false};
    if (is_tested) return;
    is_tested = true;
  }
  {
    Helper();
  }
  const TestTimer test_timer(__func__,__FILE__,1.0);

  const bool verbose{false};

  //Create a Brownian motion with volatility
  {
    const auto volatility = 1.0 / boost::units::si::second;
    bm::Process b(volatility);
    double x{0.0};
    std::vector<double> v = {x};
    for (int i=0; i!=100; ++i)
    {
      x = b.CalcNext(x);
      v.push_back(x);
    }
    //Are the likelihoods best at the true volatility?
    const auto good_likelihood
       = Helper().CalcLogLikelihood(v,volatility * volatility);
    const auto bad_likelihood
      = Helper().CalcLogLikelihood(v,volatility * volatility * 0.5);
    const auto worse_likelihood
      = Helper().CalcLogLikelihood(v,volatility * volatility * 1.5);
    assert(good_likelihood > worse_likelihood);
    assert(good_likelihood > bad_likelihood);
    //Is the max likelihood truly the max likelihood?
    auto volatility_hat = 0.0 / boost::units::si::second;
    Helper().CalcMaxLikelihood(v,volatility_hat);
    const auto max_likelihood
      = Helper().CalcLogLikelihood(v,volatility_hat * volatility_hat);
    assert(max_likelihood >= good_likelihood);
  }


  //Run a Brownian motion process
  {
    const std::vector<double> noises
      = {
       -1.0268,
       -0.4985,
        0.3825,
       -0.8102,
       -0.1206,
       -1.9604,
        0.2079,
        0.9134,
        2.1375,
        0.5461,
        1.4335,
        0.4414,
       -2.2912,
        0.3249,
       -1.3019,
       -0.8995,
        0.0281,
       -1.0959,
       -0.8118,
       -1.3890
      };
    const std::vector<double> xs_expected
     = {
          0.0,
        -10.268,
        -15.253,
        -11.428,
        -19.53,
        -20.736,
        -40.34,
        -38.261,
        -29.127,
        -7.752,
        -2.291,
        12.044,
        16.458,
        -6.454,
        -3.205,
        -16.224,
        -25.219,
        -24.938,
        -35.897,
        -44.015,
        -57.905
      };
    const auto volatility = 10.0 / boost::units::si::second;
    const double init_x{0.0};

    const ribi::bm::Parameters parameters(volatility);
    ribi::bm::Process sim(parameters);

    double x = init_x;
    std::vector<double> xs = {x};

    for (const double noise: noises)
    {
      x = sim.CalcNext(x,noise);
      xs.push_back(x);
    }
    assert(xs.size() == xs_expected.size());
    const int sz{static_cast<int>(xs.size())};
    for (int i=0; i!=sz; ++i)
    {
      assert(std::abs(xs[i]-xs_expected[i]) < 0.000000001);
    }
  }


  //Worked example
  {
    const auto volatility = 0.5 / boost::units::si::second;
    const double init_x{0.0};
    const int seed{83};
    std::normal_distribution<double> normal_distribution;
    std::mt19937 rng(seed);

    const ribi::bm::Parameters parameters(
      volatility,
      seed
    );
    ribi::bm::Process sim(parameters);

    double x = init_x;
    std::vector<double> xs = {x};

    std::vector<double> random_normals(10);
    std::generate(begin(random_normals),end(random_normals),
      [&normal_distribution,&rng]() { return normal_distribution(rng); }
    );
    if (!"Show randoms")
    {
      std::copy(begin(random_normals),end(random_normals),
        std::ostream_iterator<double>(std::cout,"\n")
      );
    }


    for (int i=0; i!=10; ++i)
    {
      const double random_normal{random_normals[i]};
      if (verbose) { std::cout << i << ": " << x << '\n'; }
      x = sim.CalcNext(x,random_normal);
      xs.push_back(x);
    }
    if (verbose) { std::cout << "10: " << x << '\n'; }

    //CalcMaxLikelihood: find best parameters
    auto cand_volatility = 0.0 / boost::units::si::second;
    Helper().CalcMaxLikelihood(xs,cand_volatility);
    const auto expected_cand_volatility
      = 0.38056299195796983  / boost::units::si::second;
    assert(std::abs(cand_volatility.value() - expected_cand_volatility.value()) < 0.0001);

    //CalcLogLikelihood: use parameters
    const double max_log_likelihood{
      Helper().CalcLogLikelihood(xs,cand_volatility * cand_volatility)
    };
    if (verbose)
    {
      std::cout << std::setprecision(20)
        << "cand_volatility: " << cand_volatility << '\n'
        << "max_log_likelihood: " << max_log_likelihood << '\n'
      ;
    }
    const double expected_max_log_likelihood{-4.9811786934375552605};
    assert(std::abs(max_log_likelihood - expected_max_log_likelihood) < 0.0001);
    assert(!std::isnan(cand_volatility.value()));

    //CalcMaxLogLikelihood: find best parameters and use them in one step
    const double max_log_likelihood_too{
      Helper().CalcMaxLogLikelihood(xs)
    };
    assert(std::abs(max_log_likelihood_too - expected_max_log_likelihood) < 0.0001);
  }

}
void ribi::tictactoe::Board::Test() noexcept
{
  {
    static bool is_tested{false};
    if (is_tested) return;
    is_tested = true;
  }
  const TestTimer test_timer(__func__,__FILE__,1.0);
  {
    //Check empty board state
    {
      Board t;
      const int s = t.GetSummarizedState();
      Board u(s);
      assert(u == t);
    }
    //Check one-move states
    for (int i=0; i!=9; ++i)
    {
      Board t;
      t.DoMove(i/3,i%3,Player::player1);
      const int s = t.GetSummarizedState();
      Board u(s);
      assert(u == t);
    }
    //Check two-move states
    for (int i=0; i!=8; ++i)
    {
      Board t;
      t.DoMove(i/3,i%3,Player::player1);
      t.DoMove(i/3,(i+1)%3,Player::player2);
      const int s = t.GetSummarizedState();
      Board u(s);
      assert(u == t);
    }
    //Check draw detection
    {
      Board t;
      t.DoMove(1,1,Player::player1);
      t.DoMove(0,0,Player::player2);
      t.DoMove(1,2,Player::player1);
      t.DoMove(1,0,Player::player2);
      t.DoMove(2,0,Player::player1);
      t.DoMove(0,2,Player::player2);
      t.DoMove(0,1,Player::player1);
      t.DoMove(2,1,Player::player2);
      t.DoMove(2,2,Player::player1);
      assert(t.GetWinner() == Winner::draw);
    }
    //Check player1 wins horizontally detection
    {
      Board t;
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(0,0,Player::player1);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(1,0,Player::player2);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(0,1,Player::player1);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(1,1,Player::player2);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(0,2,Player::player1);
      assert(t.GetWinner() == Winner::player1);
    }
    //Check player2 wins vertically detection
    {
      Board t;
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(0,0,Player::player1);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(1,0,Player::player2);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(0,1,Player::player1);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(1,1,Player::player2);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(2,2,Player::player1);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(1,2,Player::player2);
      assert(t.GetWinner() == Winner::player2);
    }
    //Check player1 wins diagonally detection
    {
      Board t;
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(0,0,Player::player1);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(1,0,Player::player2);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(1,1,Player::player1);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(1,2,Player::player2);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(2,2,Player::player1);
      assert(t.GetWinner() == Winner::player1);
    }
    //Check no-winner detection
    {
      Board t;
      t.DoMove(1,1,Player::player1);
      t.DoMove(0,0,Player::player2);
      t.DoMove(1,2,Player::player1);
      t.DoMove(1,0,Player::player2);
      t.DoMove(2,0,Player::player1);
      t.DoMove(0,2,Player::player2);
      t.DoMove(0,1,Player::player1);
      t.DoMove(2,1,Player::player2);
      //t.DoMove(2,2); //Final move to make a draw
      assert(t.GetWinner() == Winner::no_winner);
    }
    //Check CanDoMove
    for (int i=0; i!=9; ++i)
    {
      Board t;
      t.DoMove(i/3,i%3,Player::player1);
      assert(!t.CanDoMove(i/3,i%3));
    }
    //Check all states
    for (int i=0; i!=Helper().IntPower(3,9); ++i)
    {
      try
      {
        Board t(i);
        assert(t.GetSummarizedState() == i);
      }
      catch (std::exception&)
      {
        //No problem
      }
    }
  }
}
Ejemplo n.º 8
0
AboutDlg* createAboutDlg(QWidget* parent) {
	AboutDlg* dlg = new AboutDlg(parent);
	dlg->setWindowTitle(QObject::tr("About"));
	dlg->setProgramName(AppInfo::name() + " v" + AppInfo::version());
	QString text = QString("   %1   <br><br>").arg(QObject::tr("Advanced text editor"));
	text += "   Copyright &copy; 2007-2010 Mikhail Murzin   <br><br>";
	text += "<a href=\"http://juffed.com/\">http://juffed.com</a><br><br>";
	text += "<a href=\"http://sourceforge.net/tracker/?group_id=205470&atid=993768\">Report a bug</a><br><br>";
	text += "<a href=\"http://sourceforge.net/tracker/?group_id=205470&atid=993771\">Request a feature</a>";
	
	QString auth("<br>&nbsp;Mikhail Murzin a.k.a. Mezomish<br>&nbsp;&nbsp;<a href='mailto:[email protected]'>[email protected]</a>");

	QList<Helper> pluginDevs;
	pluginDevs
			<< Helper("Alexander Sokoloff", "*****@*****.**", "mailto:[email protected]", QObject::tr("SymbolBrowser plugin"))
			<< Helper("Petr Vanek", "*****@*****.**", "mailto:[email protected]", QObject::tr("XML Formatter plugin"))
			<< Helper("Alexey Romanenko", "*****@*****.**", "mailto:[email protected]", QObject::tr("Sort plugin"))
	;

	QList<Helper> translators;
	translators
			<< Helper("Michael Gangolf", "*****@*****.**", "mailto:[email protected]", QObject::tr("German translation"))
			<< Helper("Pavel Fric", "http://fripohled.blogspot.com/", "http://fripohled.blogspot.com/", QObject::tr("Czech translation"))
			<< Helper("Slavko (slavkozn)", "http://slavkozn.users.sourceforge.net/", "http://slavkozn.users.sourceforge.net/", QObject::tr("Slovak translation"))
			<< Helper("Marc Dumoulin", "*****@*****.**", "mailto:[email protected]", QObject::tr("French translation"))
			<< Helper("Jarek", "*****@*****.**", "mailto:[email protected]", QObject::tr("Polish translation"))
			<< Helper("Giuliano S. Nascimento", "*****@*****.**", "mailto:[email protected]", QObject::tr("Brazilian Portuguese translation"))
			<< Helper("YANG Weichun", "*****@*****.**", "mailto:[email protected]", QObject::tr("Chinese Simplified translation"))
	;

	QList<Helper> thanksTo;
	thanksTo
			<< Helper("Eugene Pivnev", "*****@*****.**", "mailto:[email protected]", QObject::tr("Packaging, testing"))
			<< Helper("Alexander Sokoloff", "*****@*****.**", "mailto:[email protected]", QObject::tr("Testing, design ideas, feature requests"))
			<< Helper("Petr Vanek", "*****@*****.**", "mailto:[email protected]", QObject::tr("Patches, Mac OS X port"))
			<< Helper("David Stegbauer", "*****@*****.**", "mailto:[email protected]", QObject::tr("Patches"))
			<< Helper("\"SoftIcon\"", "http://softicon.ru/", "http://softicon.ru/", QObject::tr("Application icon"))
			<< Helper("Evgeny Muravjev Studio", "http://emuravjev.ru/", "http://emuravjev.ru/", QObject::tr("Website"))
	;

	QString thanks("<br>");
	foreach(Helper helper, thanksTo) {
		thanks += QString("&nbsp;%1<br>").arg(helper.name);
		thanks += QString("&nbsp;&nbsp;<a href='%1'>%2</a><br>").arg(helper.urlHref).arg(helper.urlTitle);
		thanks += QString("&nbsp;&nbsp;%1<br><br>").arg(helper.contribution);
	}
Ejemplo n.º 9
0
ALERROR CNewGameSession::OnInit (CString *retsError)

//	OnInit
//
//	Initialize

	{
	ALERROR error;
	int i;

	const CVisualPalette &VI = m_HI.GetVisuals();

	//	The main pane is divided into three columns. Compute the size and
	//	position here.

	RECT rcCenter;
	VI.GetWidescreenRect(m_HI.GetScreen(), &rcCenter);

	m_cxLeftCol = RectWidth(rcCenter) / 3;
	m_cxRightCol = m_cxLeftCol;
	m_cxCenterCol = RectWidth(rcCenter) - (m_cxLeftCol + m_cxRightCol);

	m_xLeftCol = 0;
	m_xCenterCol = m_cxLeftCol;
	m_xRightCol = m_cxLeftCol + m_cxCenterCol;

	//	Compute the location of various elements (relative to the upper-left of
	//	the root vscroller).

	m_xPlayerName = m_xLeftCol;
	m_yPlayerName = MAJOR_PADDING_TOP;
	m_cxPlayerName = m_cxLeftCol;
	m_xPlayerGenome = m_xRightCol;
	m_yPlayerGenome = MAJOR_PADDING_TOP;
	m_cxPlayerGenome = m_cxRightCol;
	m_xShipClass = m_xLeftCol;
	m_yShipClass = MAJOR_PADDING_TOP;
	m_cxShipClass = RectWidth(rcCenter);

	//	Generate a list of ship classes

	CAdventureDesc *pAdventure = g_pUniverse->GetCurrentAdventureDesc();
	if (pAdventure == NULL)
		{
		*retsError = ERR_NO_ADVENTURE;
		return ERR_FAIL;
		}

	if (error = pAdventure->GetStartingShipClasses(&m_ShipClasses, retsError))
		return error;

	if (m_ShipClasses.GetCount() == 0)
		{
		*retsError = ERR_NO_SHIP_CLASSES;
		return ERR_FAIL;
		}

	//	Find the default ship class in the list

	m_iCurShipClass = 0;
	for (i = 0; i < m_ShipClasses.GetCount(); i++)
		if (m_ShipClasses[i]->GetUNID() == m_Settings.dwPlayerShip)
			{
			m_iCurShipClass = i;
			break;
			}

	//	Create the title

	CUIHelper Helper(m_HI);
	IAnimatron *pTitle;
	Helper.CreateSessionTitle(this, m_Service, pAdventure->GetName(), CUIHelper::OPTION_SESSION_OK_BUTTON, &pTitle);
	StartPerformance(pTitle, ID_CTRL_TITLE, CReanimator::SPR_FLAG_DELETE_WHEN_DONE);

	//	Create a scroller to hold all the settings

	m_pRoot = new CAniVScroller;
	m_pRoot->SetPropertyVector(PROP_POSITION, CVector(rcCenter.left, rcCenter.top));
	m_pRoot->SetPropertyMetric(PROP_VIEWPORT_HEIGHT, (Metric)RectHeight(rcCenter));
	m_pRoot->SetPropertyMetric(PROP_FADE_EDGE_HEIGHT, 0.0);
	m_pRoot->SetPropertyMetric(PROP_PADDING_BOTTOM, (Metric)MAJOR_PADDING_BOTTOM);

	//	Create the player name

	CreatePlayerName(m_Settings.sPlayerName, m_xPlayerName, m_yPlayerName, m_cxPlayerName);
	m_bEditingName = false;

	//	Create the player genome

	CreatePlayerGenome(m_Settings.iPlayerGenome, m_xPlayerGenome, m_yPlayerGenome, m_cxPlayerGenome);

	//	Create the ship class

	CreateShipClass(m_ShipClasses[m_iCurShipClass], m_xShipClass, m_yShipClass, m_cxShipClass);

	//	Start the settings pane

	StartPerformance(m_pRoot, ID_SETTINGS, CReanimator::SPR_FLAG_DELETE_WHEN_DONE);

	//	Done

	return NOERROR;
	}
std::vector<boost::shared_ptr<ribi::trim::Cell>> ribi::trim::CellsCreator::CreateCells(
  const boost::shared_ptr<const Template> t,
  const int n_face_layers,
  const boost::units::quantity<boost::units::si::length> layer_height,
  const CreateVerticalFacesStrategy strategy,
  const bool verbose
) noexcept
{
  assert(t);

  if (n_face_layers < 2
    || t->GetPoints().empty()
  )
  {
    std::vector<boost::shared_ptr<ribi::trim::Cell>> no_cells; return no_cells;
  }
  assert(n_face_layers >= 2);

  if (verbose)
  {
    std::clog << __FILE__ << "(" <<  (__LINE__) <<  ") : "
      << "Create points" << std::endl
    ;
  }
  const std::vector<boost::shared_ptr<Point>> all_points
    = CreatePoints(t,n_face_layers,layer_height);

  if (verbose)
  {
    std::clog << __FILE__ << "(" <<  (__LINE__) <<  ") : "
      << "Create horizontal faces" << std::endl
    ;
  }
  const std::vector<boost::shared_ptr<Face>> hor_faces
    = CreateHorizontalFaces(t,all_points,n_face_layers);

  if (verbose)
  {
    std::clog << __FILE__ << "(" <<  (__LINE__) <<  ") : "
      << "Create vertical faces" << std::endl
    ;
  }

  const std::vector<boost::shared_ptr<Face>> ver_faces
    = CreateVerticalFaces(t,all_points,n_face_layers,layer_height,strategy,verbose);

  if (verbose)
  {
    std::clog << __FILE__ << "(" <<  (__LINE__) <<  ") : "
      << "Created " << ver_faces.size() << " vertical faces" << std::endl
    ;
  }

  if (ver_faces.empty())
  {
    std::vector<boost::shared_ptr<ribi::trim::Cell>> no_cells;
    return no_cells;
  }

  #ifndef NDEBUG
  for(const auto f:ver_faces) { assert(f); }
  #endif

  const int n_hor_faces_per_layer = static_cast<int>(t->GetFaces().size());
  const int n_cells_per_layer = n_hor_faces_per_layer;

  if (verbose)
  {
    std::clog << __FILE__ << "(" <<  (__LINE__) <<  ") : "
      << "Creating cells" << std::endl
    ;
  }
  std::vector<boost::shared_ptr<Cell>> cells;
  for (int layer=0; layer!=n_face_layers-1; ++layer) //-1 because there are no points above the top layer
  {
    if (verbose) { std::clog << "."; }
    for (int i=0; i!=n_cells_per_layer; ++i)
    {

      const int bottom_face_index = ((layer + 0) * n_hor_faces_per_layer) + i;
      const int top_face_index    = ((layer + 1) * n_hor_faces_per_layer) + i;
      assert(bottom_face_index >= 0);
      assert(top_face_index    >= 0);
      assert(bottom_face_index < static_cast<int>(hor_faces.size()));
      assert(top_face_index    < static_cast<int>(hor_faces.size()));
      const std::vector<boost::shared_ptr<Face>> these_ver_faces {
        FindKnownFacesBetween(
          hor_faces[bottom_face_index],
          hor_faces[top_face_index]
        )
      };

      if (strategy == CreateVerticalFacesStrategy::one_face_per_square )
      {
        #ifndef NDEBUG
        if (these_ver_faces.size() != 3)
        {
          TRACE("BREAK");
        }
        #endif
        assert(these_ver_faces.size() == 3);
        assert(hor_faces[bottom_face_index]);
        assert(hor_faces[top_face_index]);
        assert(these_ver_faces[0]);
        assert(these_ver_faces[1]);
        assert(these_ver_faces[2]);
        const boost::shared_ptr<Cell> cell(
          CellFactory().Create(
            {
              hor_faces[bottom_face_index],
              hor_faces[top_face_index],
              these_ver_faces[0],
              these_ver_faces[1],
              these_ver_faces[2]
            },
            strategy
          )
        );
        assert(hor_faces[bottom_face_index]);
        assert(hor_faces[top_face_index]);
        assert(Helper().IsHorizontal(*hor_faces[bottom_face_index]));
        assert(Helper().IsHorizontal(*hor_faces[top_face_index]));
        assert(Helper().IsVertical(*these_ver_faces[0]));
        assert(Helper().IsVertical(*these_ver_faces[1]));
        assert(Helper().IsVertical(*these_ver_faces[2]));

        cells.push_back(cell);
      }
      else
      {
        assert(these_ver_faces.size() == 6);
        const boost::shared_ptr<Cell> cell {
          CellFactory().Create(
            {
              hor_faces[bottom_face_index],
              hor_faces[top_face_index],
              these_ver_faces[0],
              these_ver_faces[1],
              these_ver_faces[2],
              these_ver_faces[3],
              these_ver_faces[4],
              these_ver_faces[5]
            },
            strategy
          )
        };
        assert(hor_faces[bottom_face_index]);
        assert(hor_faces[top_face_index]);
        assert(Helper().IsHorizontal(*hor_faces[bottom_face_index]));
        assert(Helper().IsHorizontal(*hor_faces[top_face_index]));
        assert(Helper().IsVertical(*these_ver_faces[0]));
        assert(Helper().IsVertical(*these_ver_faces[1]));
        assert(Helper().IsVertical(*these_ver_faces[2]));
        assert(Helper().IsVertical(*these_ver_faces[3]));
        assert(Helper().IsVertical(*these_ver_faces[4]));
        assert(Helper().IsVertical(*these_ver_faces[5]));

        cells.push_back(cell);
      }
    }
  }
  #ifndef NDEBUG
  if (verbose)
  {
    std::clog << __FILE__ << "(" <<  (__LINE__) <<  ") : "
      << "Checking cells" << std::endl
    ;
  }
  CheckCells(cells);
  #endif // NDEBUG
  if (verbose)
  {
    std::clog << __FILE__ << "(" <<  (__LINE__) <<  ") : "
      << "Done creating cells" << std::endl
    ;
  }
  return cells;
}
void ribi::trim::CellsCreator::Test() noexcept
{
  {
    static bool is_tested{false};
    if (is_tested) return;
    is_tested = true;
  }
  CellFactory();
  FaceFactory();

  const TestTimer test_timer(__func__,__FILE__,1.0);
  const bool verbose{false};

  /*
  if (testing_depth > 1)
  {
    if (verbose) { TRACE("Trying out to build cells from the hardest testing templates"); }
    {
      //This is the longest test by far
      //const TestTimer test_timer(boost::lexical_cast<std::string>(__LINE__),__FILE__,1.0);
      for (CreateVerticalFacesStrategy strategy: CreateVerticalFacesStrategies().GetAll())
      {
        const boost::shared_ptr<Template> my_template {
          Template::CreateTest(3)
        };

        const int n_cell_layers = 2;
        const boost::shared_ptr<CellsCreator> cells_creator {
          CellsCreatorFactory().Create(
            my_template,
            n_cell_layers,
            1.0 * boost::units::si::meter,
            strategy,
            verbose
          )
        };
        const std::vector<boost::shared_ptr<Cell>> cells { cells_creator->GetCells() };
        assert(cells.size() > 0);
      }
    }
  }
  */
  if (verbose) { TRACE("Specific: check if a Face really loses its neighbour: remove a prism from a cube"); }
  {
    //const TestTimer test_timer(boost::lexical_cast<std::string>(__LINE__),__FILE__,1.0);
    for (CreateVerticalFacesStrategy strategy: CreateVerticalFacesStrategies().GetAll())
    {
      //Create a 2x1 cell block
      const boost::shared_ptr<Template> my_template {
        Template::CreateTest(1)
      };
      assert(my_template->CountFaces() == 2);
      const int n_cell_layers = 1;
      const boost::shared_ptr<CellsCreator> cells_creator {
        CellsCreatorFactory().Create(
          my_template,
          n_cell_layers,
          1.0 * boost::units::si::meter,
          strategy,
          verbose
        )
      };
      const std::vector<boost::shared_ptr<Cell>> cells { cells_creator->GetCells() };
      assert(cells.size() == 2);
      const std::vector<boost::shared_ptr<Face>> faces_1 { cells[0]->GetFaces() };
      const std::vector<boost::shared_ptr<Face>> faces_2 { cells[1]->GetFaces() };
      //Find the one/two Faces that have a neighbour
      {
        const int n_faces_with_neighbour {
          static_cast<int>(
            std::count_if(faces_1.begin(),faces_1.end(),
              [](const boost::shared_ptr<Face> face)
              {
                return face->GetNeighbour().get();
              }
            )
          )
        };
        assert(
             (strategy == CreateVerticalFacesStrategy::one_face_per_square
               && n_faces_with_neighbour == 1)
          || (strategy == CreateVerticalFacesStrategy::two_faces_per_square
               && n_faces_with_neighbour == 2)
        );
      }
      {
        const int n_faces_with_neighbour {
          static_cast<int>(
            std::count_if(faces_2.begin(),faces_2.end(),
              [](const boost::shared_ptr<Face> face)
              {
                return face->GetNeighbour().get();
              }
            )
          )
        };
        assert(
             (strategy == CreateVerticalFacesStrategy::one_face_per_square
               && n_faces_with_neighbour == 1)
          || (strategy == CreateVerticalFacesStrategy::two_faces_per_square
               && n_faces_with_neighbour == 2)
        );
      }
      if (verbose) { TRACE("Creating internal faces 1"); }

      Helper::FaceSet internal_faces_1 = Helper().CreateEmptyFaceSet();
      if (verbose) { TRACE("Creating internal faces 1, std::copy_if"); }
      std::copy_if(
        faces_1.begin(),faces_1.end(),
        std::inserter(internal_faces_1,internal_faces_1.begin()),
        [](const boost::shared_ptr<Face> face)
        {
          assert(face);
          const bool do_copy = face->GetNeighbour().get();
          return do_copy;
        }
      );

      if (verbose) { TRACE("Creating internal faces 2"); }
      Helper::FaceSet internal_faces_2 = Helper().CreateEmptyFaceSet();
      std::copy_if(faces_2.begin(),faces_2.end(),std::inserter(internal_faces_2,internal_faces_2.begin()),
        [](const boost::shared_ptr<Face> face)
        {
          return face->GetNeighbour().get();
        }
      );
      if (verbose) { TRACE("Creating internal faces 1"); }
      assert(
        std::equal(
          internal_faces_1.begin(),internal_faces_1.end(),
          internal_faces_2.begin(),
          [](boost::shared_ptr<Face> lhs, boost::shared_ptr<Face> rhs) { return *lhs == *rhs; }
        )
      );
    }
  }
  if (verbose) { TRACE("Create Face, from bug"); }
  {
    //const TestTimer test_timer(boost::lexical_cast<std::string>(__LINE__),__FILE__,1.0);
    /*
    (1.17557,2.35781,5.0)
    (2.35114,3.23607,5.0)
    (1.17557,2.35781,6.0)
    (2.35114,3.23607,6.0)
    */
    //Ordering cannot be known for sure to be convex from these indices
    typedef boost::geometry::model::d2::point_xy<double> Coordinat2D;
    std::vector<boost::shared_ptr<Point>> face_points {
      PointFactory().Create(boost::make_shared<Coordinat2D>(1.17557,2.35781)),
      PointFactory().Create(boost::make_shared<Coordinat2D>(2.35114,3.23607)),
      PointFactory().Create(boost::make_shared<Coordinat2D>(1.17557,2.35781)),
      PointFactory().Create(boost::make_shared<Coordinat2D>(2.35114,3.23607))
    };
    face_points[0]->SetZ(5.0 * boost::units::si::meter);
    face_points[1]->SetZ(5.0 * boost::units::si::meter);
    face_points[2]->SetZ(6.0 * boost::units::si::meter);
    face_points[3]->SetZ(6.0 * boost::units::si::meter);

    //Order face_points
    if (!Helper().IsConvex(face_points)) { Helper().MakeConvex(face_points); }

    #ifndef NDEBUG
    if (!Helper().IsConvex(face_points))
    {
      TRACE("ERROR");
      for (const auto& p: face_points) { TRACE(*p); }
      TRACE("BREAK");
    }
    #endif

    assert(Helper().IsConvex(face_points));

    //Cannot order face winding yet, need Cells for this
    const boost::shared_ptr<Face> face {
      FaceFactory().Create(
        face_points,
        FaceOrientation::vertical,
        verbose
      )
    };
  }

  //From bug
  {
    //const TestTimer test_timer(boost::lexical_cast<std::string>(__LINE__),__FILE__,1.0);
    typedef boost::geometry::model::d2::point_xy<double> Coordinat2D;
    const double x1 = 0.0004035051226622692510832834944523028752882964909076690673828125;
    const double y1 = 0.00023296416881187433805568132161312178141088224947452545166015625;
    const double z1 = 0; //left out the '.0' intentionally

    const double x2 = 0.000403505141811931846741734464245610070065595209598541259765625;
    const double y2 = 0.00023296414405748076185791173298156309101614169776439666748046875;
    const double z2 = 0; //left out the '.0' intentionally

    const double x3 = 0.0004035051226622692510832834944523028752882964909076690673828125;
    const double y3 = 0.00023296416881187433805568132161312178141088224947452545166015625;
    const double z3 = 0.00025000000000000000520417042793042128323577344417572021484375;

    const double x4 = 0.000403505141811931846741734464245610070065595209598541259765625;
    const double y4 = 0.00023296414405748076185791173298156309101614169776439666748046875;
    const double z4 = 0.00025000000000000000520417042793042128323577344417572021484375;
    const auto c1 = boost::make_shared<Coordinat2D>(x1,y1);
    const auto c2 = boost::make_shared<Coordinat2D>(x2,y2);
    const auto c3 = boost::make_shared<Coordinat2D>(x3,y3);
    const auto c4 = boost::make_shared<Coordinat2D>(x4,y4);
    const auto p1 = PointFactory().Create(c1);
    const auto p2 = PointFactory().Create(c2);
    const auto p3 = PointFactory().Create(c3);
    const auto p4 = PointFactory().Create(c4);
    p1->SetZ(z1 * boost::units::si::meter);
    p2->SetZ(z2 * boost::units::si::meter);
    p3->SetZ(z3 * boost::units::si::meter);
    p4->SetZ(z4 * boost::units::si::meter);
    std::vector<boost::shared_ptr<Point>> face_points;
    face_points.push_back(p1);
    face_points.push_back(p2);
    face_points.push_back(p3);
    face_points.push_back(p4);
    assert(IsPlane(face_points));
  }
}
std::vector<boost::shared_ptr<ribi::trim::Face>> ribi::trim::CellsCreator::CreateVerticalFaces(
  const boost::shared_ptr<const Template> t,
  const std::vector<boost::shared_ptr<Point>>& all_points,
  const int n_face_layers,
  const boost::units::quantity<boost::units::si::length> layer_height,
  const CreateVerticalFacesStrategy strategy,
  const bool verbose
) noexcept
{
  assert(t);

  assert(n_face_layers > 0);
  if (n_face_layers < 2)
  {
    if (verbose)
    {
      std::clog << __FILE__ << "(" <<  (__LINE__) <<  ") : "
        << "Too few layers to create vertical faces" << std::endl
      ;
    }
    std::vector<boost::shared_ptr<ribi::trim::Face>> no_faces;
    return no_faces;
  }
  #ifndef NDEBUG
  const FaceFactory face_factory;

  if (verbose)
  {
    std::clog << __FILE__ << "(" <<  (__LINE__) <<  ") : "
      << "Checking points" << std::endl
    ;
  }

  for (const auto& point: all_points) { assert(point); }

  if (verbose)
  {
    std::clog << __FILE__ << "(" <<  (__LINE__) <<  ") : "
      << "Get edges" << std::endl
    ;
  }
  #endif
  const std::vector<std::pair<int,int>> edges = t->GetEdges();


  assert(!edges.empty());
  const int n_edges = static_cast<int>(edges.size());
  const int n_points_per_layer = static_cast<int>(t->GetPoints().size());
  assert(n_points_per_layer > 0);
  const int n_ver_faces
    = strategy == CreateVerticalFacesStrategy::one_face_per_square
    ? 1 * n_edges
    : 2 * n_edges //For every horizontal edge, two triangles are used instead
  ;

  std::vector<boost::shared_ptr<Face>> v;
  #ifndef NDEBUG
  const int n_reserve = n_ver_faces * (n_face_layers - 1);
  #endif
  assert(n_reserve > 0);
  assert(n_reserve < static_cast<int>(v.max_size()));
  v.reserve(n_ver_faces * (n_face_layers - 1));

  assert(n_face_layers > 0);
  if (n_face_layers == 1)
  {
    std::vector<boost::shared_ptr<ribi::trim::Face>> no_faces;
    return no_faces;
  }

  if (verbose)
  {
    std::clog << __FILE__ << "(" <<  (__LINE__) <<  ") : "
      << "Start building " << (n_face_layers-1) //Number of cell layers
      << " layers" << std::endl
    ;
  }

  for (int layer=0; layer!=n_face_layers-1; ++layer) //-1 because there are no points above the top layer
  {
    if (verbose)
    {
      std::clog << __FILE__ << "(" <<  (__LINE__) <<  ") : "
        << (layer+1) //Human-based
        << "/" << (n_face_layers-1) //Number of cell layers
        << std::endl
      ;
    }

    const int points_offset = n_points_per_layer * layer;
    assert(points_offset >= 0);
    const auto z_here  = static_cast<double>(layer + 0) * layer_height;
    const auto z_above = static_cast<double>(layer + 1) * layer_height;
    for (const std::pair<int,int>& edge: edges)
    {
      assert(edge.first < edge.second);

      assert(points_offset + edge.first  < static_cast<int>(all_points.size()));
      assert(points_offset + edge.second < static_cast<int>(all_points.size()));
      assert(points_offset + edge.first  + n_points_per_layer < static_cast<int>(all_points.size()));
      assert(points_offset + edge.second + n_points_per_layer < static_cast<int>(all_points.size()));
      if (strategy == CreateVerticalFacesStrategy::one_face_per_square)
      {
        //Ordering cannot be known for sure to be convex from these indices
        assert(all_points[points_offset + edge.first]);
        assert(all_points[points_offset + edge.second]);
        assert(all_points[points_offset + edge.first  + n_points_per_layer]);
        assert(all_points[points_offset + edge.second + n_points_per_layer]);
        std::vector<boost::shared_ptr<Point>> face_points;
        face_points.push_back(all_points[points_offset + edge.first]);
        face_points.push_back(all_points[points_offset + edge.second]);
        face_points.push_back(all_points[points_offset + edge.first  + n_points_per_layer]);
        face_points.push_back(all_points[points_offset + edge.second + n_points_per_layer]);
        assert(face_points.size() == 4);
        assert(face_points[0]);
        assert(face_points[1]);
        assert(face_points[2]);
        assert(face_points[3]);
        assert(face_points[0] != face_points[1]);
        assert(face_points[0] != face_points[2]);
        assert(face_points[0] != face_points[3]);
        assert(face_points[1] != face_points[2]);
        assert(face_points[1] != face_points[3]);
        assert(face_points[2] != face_points[3]);
        face_points[0]->SetZ(z_here);
        face_points[1]->SetZ(z_here);
        face_points[2]->SetZ(z_above);
        face_points[3]->SetZ(z_above);
        #ifndef NDEBUG
        if(!IsPlane(face_points))
        {
          TRACE("ERROR");
          std::stringstream s;
          s
            << face_points.size() << '\n'
            << std::setprecision(99)
          ;
          for (const auto& point: face_points) { s << (*point) << " "; }
          TRACE(s.str());
          TRACE("BREAK");
        }
        #endif
        assert(IsPlane(face_points));

        //Order face_points
        if (!Helper().IsConvex(face_points))
        {
          Helper().MakeConvex(face_points);
        }

        assert(Helper().IsConvex(face_points));

        //Cannot order face winding yet, need Cells for this
        const boost::shared_ptr<Face> face {
          FaceFactory().Create(
            face_points,
            FaceOrientation::vertical,
            verbose
          )
        };
        assert(face);
        v.push_back(face);
      }
      else
      {
        assert(all_points[points_offset + edge.first]);
        assert(all_points[points_offset + edge.second]);
        assert(all_points[points_offset + edge.first + n_points_per_layer]);
        const std::vector<boost::shared_ptr<Point>> face_points_1 {
          all_points[points_offset + edge.first],
          all_points[points_offset + edge.second],
          all_points[points_offset + edge.first + n_points_per_layer]
        };
        assert(face_points_1[0] != face_points_1[1]);
        assert(face_points_1[0] != face_points_1[2]);
        assert(face_points_1[1] != face_points_1[2]);

        face_points_1[0]->SetZ(z_here);
        face_points_1[1]->SetZ(z_here);
        face_points_1[2]->SetZ(z_above);

        assert(Helper().IsConvex(face_points_1)
          && "FaceFactory expects convex ordered points");

        //Cannot order face winding yet, need Cells for this
        const boost::shared_ptr<Face> face_1 {
          FaceFactory().Create(
            face_points_1,
            FaceOrientation::vertical,
            verbose
          )
        };
        assert(face_1);
        v.push_back(face_1);


        assert(all_points[points_offset + edge.second]);
        assert(all_points[points_offset + edge.second + n_points_per_layer]);
        assert(all_points[points_offset + edge.first  + n_points_per_layer]);
        std::vector<boost::shared_ptr<Point>> face_points_2 {
          all_points[points_offset + edge.second],
          all_points[points_offset + edge.second + n_points_per_layer],
          all_points[points_offset + edge.first  + n_points_per_layer]
        };
        assert(face_points_2[0] != face_points_2[1]);
        assert(face_points_2[0] != face_points_2[2]);
        assert(face_points_2[1] != face_points_2[2]);

        face_points_2[0]->SetZ(z_here );
        face_points_2[1]->SetZ(z_above);
        face_points_2[2]->SetZ(z_above);

        #ifndef NDEBUG
        if (!Helper().IsConvex(face_points_2))
        {
          TRACE("ERROR");

          for (const auto& point:face_points_2) { TRACE(Geometry().ToStr(point->GetCoordinat3D())); }
        }
        #endif

        assert(Helper().IsConvex(face_points_2)
          && "FaceFactory expects convex ordered points");

        const boost::shared_ptr<Face> face_2 {
          FaceFactory().Create(
            face_points_2,
            FaceOrientation::vertical,
            verbose
          )
        };
        assert(face_2);
        v.push_back(face_2);
      }
    }
  }

  assert(n_ver_faces * (n_face_layers - 1) == static_cast<int>(v.size()));

  if (verbose)
  {
    std::clog << __FILE__ << "(" <<  (__LINE__) <<  ") : "
      << "Done building " << (n_face_layers-1) //Number of cell layers
      << " layers" << std::endl
    ;
  }

  return v;
}
std::vector<boost::shared_ptr<ribi::trim::Face>> ribi::trim::CellsCreator::CreateHorizontalFaces(
  const boost::shared_ptr<const Template> t,
  const std::vector<boost::shared_ptr<Point>>& all_points,
  const int n_face_layers
)
{
  const bool verbose{false};
  std::vector<boost::shared_ptr<Face>> v;
  assert(t);
  #ifndef NDEBUG
  if (all_points.empty())
  {
    TRACE("ERROR");
    TRACE("BREAK");
  }
  #endif
  assert(!all_points.empty());

  const int n_points_per_layer{static_cast<int>(t->GetPoints().size())};
  #ifndef NDEBUG
  const int n_faces_per_layer{static_cast<int>(t->GetFaces().size())};
  assert(n_face_layers > 0);
  #endif
  v.reserve(n_face_layers * n_points_per_layer);

  for (int layer=0; layer!=n_face_layers; ++layer)
  {
    const int point_offset{n_points_per_layer * layer};
    for (const std::vector<int>& face_point_indices: t->GetFacePointIndices())
    {
      #ifndef NDEBUG
      const int face_index{static_cast<int>(v.size())};
      assert(face_point_indices.size() == 3); //Triangulation
      #endif
      std::vector<boost::shared_ptr<Point>> face_points;
      for (int point_index: face_point_indices)
      {
        assert(point_index + point_offset < static_cast<int>(all_points.size()));
        face_points.push_back(all_points[point_index + point_offset]);
        #ifndef NDEBUG
        if (face_points.size() >= 2 && face_points[0]->CanGetZ())
        {
          assert(face_points.front()->GetZ() == face_points.back()->GetZ());
        }
        #endif
      }

      assert(layer == 0 || face_index - n_faces_per_layer >= 0);
      assert(layer == 0 || face_index - n_faces_per_layer < static_cast<int>(v.size()));
      if ( (layer % 2 == 0 && !Helper().IsClockwiseHorizontal(face_points))
        || (layer % 2 == 1 &&  Helper().IsClockwiseHorizontal(face_points))
      )
      {
        std::reverse(face_points.begin(),face_points.end());
      }

      if(!Helper().IsConvex(face_points)) { Helper().MakeConvex(face_points); }
      assert(Helper().IsConvex(face_points));
      //const FaceFactory face_factory;
      const boost::shared_ptr<Face> face {
        FaceFactory().Create(
          face_points,
          FaceOrientation::horizontal,
          verbose
        )
      };
      v.push_back(face);
    }
  }
  return v;
}
void UFindSessionsCallbackProxyAdvanced::OnCompleted(bool bSuccess)
{
	FOnlineSubsystemBPCallHelperAdvanced Helper(TEXT("FindSessionsCallback"), GEngine->GetWorldFromContextObject(WorldContextObject));
	Helper.QueryIDFromPlayerController(PlayerControllerWeakPtr.Get());

	if (Helper.IsValid())
	{
		auto Sessions = Helper.OnlineSub->GetSessionInterface();
		if (Sessions.IsValid())
		{
			Sessions->ClearOnFindSessionsCompleteDelegate_Handle(DelegateHandle);
		}
	}

	TArray<FBlueprintSessionResult> Results;

	if (bSuccess && SearchObject.IsValid())
	{
		// Just log the results for now, will need to add a blueprint-compatible search result struct
		for (auto& Result : SearchObject->SearchResults)
		{
		/*	bool bAddResult = true;

			// Filter results
			if (SearchSettings.Num() > 0)
			{
				FOnlineSessionSetting * setting;
				for (int i = 0; i < SearchSettings.Num(); i++)
				{
					setting = Result.Session.SessionSettings.Settings.Find(SearchSettings[i].PropertyKeyPair.Key);

					// Couldn't find this key
					if (!setting)
						continue;

					if (!CompareVariants(setting->Data, SearchSettings[i].PropertyKeyPair.Data, SearchSettings[i].ComparisonOp))
					{
						bAddResult = false;
						break;
					}
				}
			}*/

			//if (bAddResult)
			//{
				FString ResultText = FString::Printf(TEXT("Found a session. Ping is %d"), Result.PingInMs);

				FFrame::KismetExecutionMessage(*ResultText, ELogVerbosity::Log);

				FBlueprintSessionResult BPResult;
				BPResult.OnlineResult = Result;
				Results.Add(BPResult);
			//}
		}
		OnSuccess.Broadcast(Results);
	}
	else
	{
		OnFailure.Broadcast(Results);
	}
}
Ejemplo n.º 15
0
    // For each entry, find the independent group reachable by it. The independent group is
    // the entry itself, plus all the blocks it can reach that cannot be directly reached by another entry. Note that we
    // ignore directly reaching the entry itself by another entry.
    void FindIndependentGroups(BlockSet &Blocks, BlockSet &Entries, BlockBlockSetMap& IndependentGroups) {
      typedef std::map<Block*, Block*> BlockBlockMap;

      struct HelperClass {
        BlockBlockSetMap& IndependentGroups;
        BlockBlockMap Ownership; // For each block, which entry it belongs to. We have reached it from there.

        HelperClass(BlockBlockSetMap& IndependentGroupsInit) : IndependentGroups(IndependentGroupsInit) {}
        void InvalidateWithChildren(Block *New) { // TODO: rename New
          BlockList ToInvalidate; // Being in the list means you need to be invalidated
          ToInvalidate.push_back(New);
          while (ToInvalidate.size() > 0) {
            Block *Invalidatee = ToInvalidate.front();
            ToInvalidate.pop_front();
            Block *Owner = Ownership[Invalidatee];
            if (IndependentGroups.find(Owner) != IndependentGroups.end()) { // Owner may have been invalidated, do not add to IndependentGroups!
              IndependentGroups[Owner].erase(Invalidatee);
            }
            if (Ownership[Invalidatee]) { // may have been seen before and invalidated already
              Ownership[Invalidatee] = NULL;
              for (BlockBranchMap::iterator iter = Invalidatee->BranchesOut.begin(); iter != Invalidatee->BranchesOut.end(); iter++) {
                Block *Target = iter->first;
                BlockBlockMap::iterator Known = Ownership.find(Target);
                if (Known != Ownership.end()) {
                  Block *TargetOwner = Known->second;
                  if (TargetOwner) {
                    ToInvalidate.push_back(Target);
                  }
                }
              }
            }
          }
        }
      };
      HelperClass Helper(IndependentGroups);

      // We flow out from each of the entries, simultaneously.
      // When we reach a new block, we add it as belonging to the one we got to it from.
      // If we reach a new block that is already marked as belonging to someone, it is reachable by
      // two entries and is not valid for any of them. Remove it and all it can reach that have been
      // visited.

      BlockList Queue; // Being in the queue means we just added this item, and we need to add its children
      for (BlockSet::iterator iter = Entries.begin(); iter != Entries.end(); iter++) {
        Block *Entry = *iter;
        Helper.Ownership[Entry] = Entry;
        IndependentGroups[Entry].insert(Entry);
        Queue.push_back(Entry);
      }
      while (Queue.size() > 0) {
        Block *Curr = Queue.front();
        Queue.pop_front();
        Block *Owner = Helper.Ownership[Curr]; // Curr must be in the ownership map if we are in the queue
        if (!Owner) continue; // we have been invalidated meanwhile after being reached from two entries
        // Add all children
        for (BlockBranchMap::iterator iter = Curr->BranchesOut.begin(); iter != Curr->BranchesOut.end(); iter++) {
          Block *New = iter->first;
          BlockBlockMap::iterator Known = Helper.Ownership.find(New);
          if (Known == Helper.Ownership.end()) {
            // New node. Add it, and put it in the queue
            Helper.Ownership[New] = Owner;
            IndependentGroups[Owner].insert(New);
            Queue.push_back(New);
            continue;
          }
          Block *NewOwner = Known->second;
          if (!NewOwner) continue; // We reached an invalidated node
          if (NewOwner != Owner) {
            // Invalidate this and all reachable that we have seen - we reached this from two locations
            Helper.InvalidateWithChildren(New);
          }
          // otherwise, we have the same owner, so do nothing
        }
      }

      // Having processed all the interesting blocks, we remain with just one potential issue:
      // If a->b, and a was invalidated, but then b was later reached by someone else, we must
      // invalidate b. To check for this, we go over all elements in the independent groups,
      // if an element has a parent which does *not* have the same owner, we must remove it
      // and all its children.

      for (BlockSet::iterator iter = Entries.begin(); iter != Entries.end(); iter++) {
        BlockSet &CurrGroup = IndependentGroups[*iter];
        BlockList ToInvalidate;
        for (BlockSet::iterator iter = CurrGroup.begin(); iter != CurrGroup.end(); iter++) {
          Block *Child = *iter;
          for (BlockSet::iterator iter = Child->BranchesIn.begin(); iter != Child->BranchesIn.end(); iter++) {
            Block *Parent = *iter;
            if (Helper.Ownership[Parent] != Helper.Ownership[Child]) {
              ToInvalidate.push_back(Child);
            }
          }
        }
        while (ToInvalidate.size() > 0) {
          Block *Invalidatee = ToInvalidate.front();
          ToInvalidate.pop_front();
          Helper.InvalidateWithChildren(Invalidatee);
        }
      }

      // Remove empty groups
      for (BlockSet::iterator iter = Entries.begin(); iter != Entries.end(); iter++) {
        if (IndependentGroups[*iter].size() == 0) {
          IndependentGroups.erase(*iter);
        }
      }

#if DEBUG
      PrintDebug("Investigated independent groups:\n");
      for (BlockBlockSetMap::iterator iter = IndependentGroups.begin(); iter != IndependentGroups.end(); iter++) {
        DebugDump(iter->second, " group: ");
      }
#endif
    }
ribi::trim::Template::Template(
  const std::string& filename_node,
  const std::string& filename_ele,
  const bool verbose
)
  : m_edges{},
    m_faces{},
    m_face_point_indices{},
    m_points{}
{
  #ifndef NDEBUG
  Test();
  #endif

  if (verbose) { TRACE("Load the points and faces created by Triangle"); }
  {
    const std::vector<std::string> v {
      ribi::fileio::FileIo().FileToVector(
        filename_node
      )
    };
    const int sz = v.size();
    const int percent = sz / 100 ? sz / 100: 1;
    for(int n=0; n!=sz; ++n)
    {
      if (verbose) { if (n % percent == 0) std::clog << '%'; }
      const std::string line = v[n];
      if(n==0) continue; //No idea why this has to be skipped
      const std::vector<std::string> w { CleanAndSplitString(ConvertNumbersToEnglish(line)) };
      if (w.empty() || w[0].empty() ||  w[0] == "#")
      {
        //The final comment line
        continue;
      }
      assert(w.size() == 4);
      assert(CanLexicalCast<int>(w[0]));
      assert(CanLexicalCast<double>(w[1]));
      #ifndef NDEBUG
      if (!CanLexicalCast<double>(w[2]))
      {
        TRACE("ERROR");
        TRACE(line);
        TRACE(w[0]);
        TRACE(w[1]);
        TRACE(w[2]);
        TRACE(w[3]);
        TRACE("BREAK");
      }
      #endif
      assert(CanLexicalCast<double>(w[2]));
      assert(CanLexicalCast<int>(w[3]));
      const double x = boost::lexical_cast<double>(w[1]);
      const double y = boost::lexical_cast<double>(w[2]);
      const boost::shared_ptr<const ConstCoordinat2D> bottom(
        new ConstCoordinat2D(x,y)
      );

      const boost::shared_ptr<Point> node {
        PointFactory().Create(bottom)
      };
      m_points.push_back(node);
    }
  }

  if (verbose) { TRACE("Load and translate faces"); }
  {
    const std::vector<std::string> v
      = ribi::fileio::FileIo().FileToVector(filename_ele);
    const int sz = v.size();
    const int percent = sz / 100 ? sz / 100: 1;
    for(int n=0; n!=sz; ++n)
    {
      if (verbose)
      {
        if (n % percent == 0)
        {
          std::clog << '%';
        }
      }
      const std::string line = v[n];
      if(n==0) continue;
      const std::vector<std::string> w { CleanAndSplitString(line) };
      if (w.empty() || w[0].empty() ||  w[0] == "#")
      {
        //The final comment line
        continue;
      }
      assert(w.size() == 4);
      assert(CanLexicalCast<int>(w[0]));
      assert(CanLexicalCast<int>(w[1]));
      assert(CanLexicalCast<int>(w[2]));
      assert(CanLexicalCast<int>(w[3]));

      //I hope that I made the Triangle.exe output start at index 0..
      const int point1 = boost::lexical_cast<int>(w[1]);
      const int point2 = boost::lexical_cast<int>(w[2]);
      const int point3 = boost::lexical_cast<int>(w[3]);
      assert(point1 >= 0); //Start at index 0
      assert(point2 >= 0); //Start at index 0
      assert(point3 >= 0); //Start at index 0
      assert(point1 - 0 < static_cast<int>(m_points.size()));
      assert(point2 - 0 < static_cast<int>(m_points.size()));
      assert(point3 - 0 < static_cast<int>(m_points.size()));
      const std::vector<int> face_point_indices {
        point1-0, //Start at index 0
        point2-0, //Start at index 0
        point3-0  //Start at index 0
      };
      m_edges.push_back(std::make_pair(face_point_indices[0],face_point_indices[1]));
      m_edges.push_back(std::make_pair(face_point_indices[0],face_point_indices[2]));
      m_edges.push_back(std::make_pair(face_point_indices[1],face_point_indices[2]));

      std::vector<boost::shared_ptr<Point>> face_points {
        m_points[point1-0], //Start at index 0
        m_points[point2-0], //Start at index 0
        m_points[point3-0]  //Start at index 0
      };
      if (!Helper().IsClockwiseHorizontal(face_points))
      {
        std::reverse(face_points.begin(),face_points.end());
      }
      assert(Helper().IsClockwiseHorizontal(face_points));
      if (!Helper().IsConvex(face_points)) { Helper().MakeConvex(face_points); }
      assert(Helper().IsConvex(face_points) && "FaceFactory only accepts convex ordered points");

      const boost::shared_ptr<Face> face {
        FaceFactory().Create(
          face_points,
          FaceOrientation::horizontal,
          verbose
        )
      };
      m_faces.push_back(face);
      m_face_point_indices.push_back(face_point_indices);

      assert(std::unique(m_face_point_indices.begin(),m_face_point_indices.end())
        == m_face_point_indices.end()
        && "Every face should have unique point indices");
    }
  }

  #ifndef NDEBUG
  if (verbose) { TRACE("Checking the result"); }
  const int n_faces = static_cast<int>(m_faces.size());
  assert(m_faces.size() == m_face_point_indices.size());
  for (int i=0; i!=n_faces; ++i)
  {
    const auto face = m_faces[i];
    const auto indices = m_face_point_indices[i];
    assert(face->GetPoints().size() == indices.size());
  }
  #endif

  for (auto& p: m_edges)
  {
    if (p.first > p.second) std::swap(p.first,p.second);
    assert(p.first < p.second);
  }
  std::sort(m_edges.begin(),m_edges.end());

  auto new_end = std::unique(m_edges.begin(),m_edges.end());
  m_edges.erase(new_end,m_edges.end());

  if (verbose) { TRACE("Done checking the result"); }
}
 TreeNode* sortedArrayToBST(vector<int>& nums) {
     return Helper(nums, 0, nums.size());
 }
boost::shared_ptr<ribi::trim::Template> ribi::trim::Template::CreateTestTriangle2x2() noexcept
{
  std::vector<boost::shared_ptr<Face>> faces;
  std::vector<std::vector<int>> face_point_indices;
  std::vector<boost::shared_ptr<Point>> points;
  const int width{2};
  //const int height = 2;
  const int n_points{3}; //Triangle
  const bool verbose{false};
  points.reserve(n_points);

  //Create points
  {
    for(int i=0; i!=n_points; ++i)
    {
      const double x = static_cast<double>(i % width);
      const double y = static_cast<double>(i / width);
      const std::string boundary_type{"two_times_two"};
      const boost::shared_ptr<const ConstCoordinat2D> bottom {
        new ConstCoordinat2D(x,y)
      };
      const boost::shared_ptr<Point> point {
        PointFactory().Create(bottom)
      };
      points.push_back(point);
    }
  }
  #ifndef NDEBUG
  //Check that there is no coordinat present twice
  {
    for (int i=0; i!=n_points; ++i)
    {
      const boost::shared_ptr<const ConstCoordinat2D> a { points[i]->GetCoordinat() };
      for (int j=0; j!=n_points; ++j)
      {
        const boost::shared_ptr<const ConstCoordinat2D> b { points[j]->GetCoordinat() };
        if (a == b)
        {
          assert(boost::geometry::distance(*a,*b) < 0.001);
        }
        else
        {
          assert(boost::geometry::distance(*a,*b) > 0.001);
        }
      }
    }
  }
  #endif

  //Load and translate faces
  face_point_indices = {
    { 0,1,2 }
  };

  const std::vector<std::pair<int,int>> edges {
    { 0,1 },
    { 0,2 },
    { 1,2 }
  };

  {
    for(const auto v: face_point_indices)
    {
      assert(v.size() == 3);
      //I do not correct for one-base Triangle.exe output
      assert(v[0] >= 0);
      assert(v[1] >= 0);
      assert(v[2] >= 0);
      std::vector<boost::shared_ptr<Point>> face_points {
        points[ v[0] ],
        points[ v[1] ],
        points[ v[2] ]
      };
      
      if (!Helper().IsClockwiseHorizontal(face_points))
      {
        std::reverse(face_points.begin(),face_points.end());
      }
      #ifndef NDEBUG
      if (!Helper().IsClockwiseHorizontal(face_points))
      {
        TRACE("ERROR");
        TRACE(*face_points[0]);
        TRACE(*face_points[1]);
        TRACE(*face_points[2]);
        TRACE("BREAK");
      }
      #endif
      assert(Helper().IsClockwiseHorizontal(face_points));
      const boost::shared_ptr<Face> face {
        FaceFactory().Create(
          face_points,
          FaceOrientation::horizontal,
          verbose
        )
      };
      faces.push_back(face);
    }
  }

  #ifndef NDEBUG
  const int n_faces = static_cast<int>(faces.size());
  assert(faces.size() == face_point_indices.size());
  for (int i=0; i!=n_faces; ++i)
  {
    const auto face = faces[i];
    const auto indices = face_point_indices[i];
    assert(face->GetPoints().size() == indices.size());
  }
  #endif

  assert(faces.size()  == 1 && "A triangle is only 1 triangle");
  assert(edges.size()  == 3 && "A triangle has 3 edges");
  assert(points.size() == 3 && "A triangle has 3 nodes");

  const boost::shared_ptr<Template> my_template {
    new Template(
      edges,
      faces,
      face_point_indices,
      points
    )
  };
  assert(my_template);
  return my_template;
}
Ejemplo n.º 19
0
bool SortedAggregator::Advance(AbstractTuple *next_tuple) {
  bool start_new_agg = false;

  // Check if we are starting a new aggregate tuple
  if (delegate_tuple_values_.empty()) {  // No current group
    LOG_TRACE("Current group keys are empty!");
    start_new_agg = true;
  } else {  // Current group exists
    PL_ASSERT(delegate_tuple_values_.size() == num_input_columns_);
    // Check whether crossed group boundary
    for (oid_t grpColOffset = 0; grpColOffset < node->GetGroupbyColIds().size();
         grpColOffset++) {
      common::Value lval = (
          next_tuple->GetValue(node->GetGroupbyColIds()[grpColOffset]));
      common::Value rval = (
          delegate_tuple_.GetValue(node->GetGroupbyColIds()[grpColOffset]));
      common::Value cmp = (lval.CompareNotEquals(rval));
      bool not_equal = cmp.IsTrue();

      if (not_equal) {
        LOG_TRACE("Group-by columns changed.");

        // Call helper to output the current group result
        if (!Helper(node, aggregates, output_table, &delegate_tuple_,
                    this->executor_context)) {
          return false;
        }

        start_new_agg = true;
        break;
      }
    }
  }

  // If we have started a new aggregate tuple
  if (start_new_agg) {
    LOG_TRACE("Started a new group!");

    // Create aggregate
    for (oid_t aggno = 0; aggno < node->GetUniqueAggTerms().size(); aggno++) {
      // Clean up previous aggregate
      delete aggregates[aggno];
      aggregates[aggno] =
          GetAggInstance(node->GetUniqueAggTerms()[aggno].aggtype);

      bool distinct = node->GetUniqueAggTerms()[aggno].distinct;
      aggregates[aggno]->SetDistinct(distinct);
    }

    // Update delegate tuple values
    delegate_tuple_values_.clear();

    for (oid_t col_id = 0; col_id < num_input_columns_; col_id++) {
      // delegate_tuple_values_ has the ownership
      common::Value val = next_tuple->GetValue(col_id);
      delegate_tuple_values_.push_back(val);
    }
  }

  // Update the aggregation calculation
  for (oid_t aggno = 0; aggno < node->GetUniqueAggTerms().size(); aggno++) {
    auto predicate = node->GetUniqueAggTerms()[aggno].expression;
    common::Value value =
        common::ValueFactory::GetIntegerValue(1);
    if (predicate) {
      value = node->GetUniqueAggTerms()[aggno].expression->Evaluate(
          next_tuple, nullptr, this->executor_context);
    }
    aggregates[aggno]->Advance(value);
  }

  return true;
}
boost::shared_ptr<ribi::trim::Template> ribi::trim::Template::CreateTest3x3() noexcept
{
  std::vector<boost::shared_ptr<Face>> faces;
  std::vector<std::vector<int>> face_point_indices;
  std::vector<boost::shared_ptr<Point>> points;
  const int width{3};
  const int height{3};
  const int n_points{width * height};
  const bool verbose{false};
  points.reserve(n_points);

  //Create points
  {
    for(int i=0; i!=n_points; ++i)
    {
      const double x{static_cast<double>(i % width)};
      const double y{static_cast<double>(i / width)};
      const std::string boundary_type = "three_times_three";
      const boost::shared_ptr<const ConstCoordinat2D> bottom{
        new ConstCoordinat2D(x,y)
      };
      const auto point = PointFactory().Create(bottom);
      points.push_back(point);
    }
  }
  #ifndef NDEBUG
  //Check that there is no coordinat present twice
  {
    for (int i=0; i!=n_points; ++i)
    {
      const boost::shared_ptr<const ConstCoordinat2D> a { points[i]->GetCoordinat() };
      for (int j=0; j!=n_points; ++j)
      {
        const boost::shared_ptr<const ConstCoordinat2D> b { points[j]->GetCoordinat() };
        if (a == b)
        {
          assert(boost::geometry::distance(*a,*b) < 0.001);
        }
        else
        {
          assert(boost::geometry::distance(*a,*b) > 0.001);
        }
      }
    }
  }
  #endif

  //Load and translate faces
  face_point_indices = {
    { 0,1,3 },
    { 1,2,4 },
    { 1,3,4 },
    { 2,4,5 },
    { 3,4,6 },
    { 4,5,7 },
    { 4,6,7 },
    { 5,7,8 }
  };

  const std::vector<std::pair<int,int>> edges {
    { 0,1 },
    { 0,3 },
    { 1,2 },
    { 1,3 },
    { 1,4 },
    { 2,4 },
    { 2,5 },
    { 3,4 },
    { 3,6 },
    { 4,5 },
    { 4,6 },
    { 4,7 },
    { 5,7 },
    { 5,8 },
    { 6,7 },
    { 7,8 }
  };

  {
    for(const auto v: face_point_indices)
    {
      assert(v.size() == 3);
      //I do not correct for one-base Triangle.exe output
      const int point1 = v[0];
      const int point2 = v[1];
      const int point3 = v[2];
      assert(point1 >= 0);
      assert(point2 >= 0);
      assert(point3 >= 0);
      const std::vector<int> face_point_indices {
        point1,
        point2,
        point3
      };
      std::vector<boost::shared_ptr<Point>> face_points {
        points[point1],
        points[point2],
        points[point3]
      };
      
      if (!Helper().IsClockwiseHorizontal(face_points))
      {
        std::reverse(face_points.begin(),face_points.end());
      }
      assert(Helper().IsClockwiseHorizontal(face_points));
      const boost::shared_ptr<Face> face {
        FaceFactory().Create(
          face_points,
          FaceOrientation::horizontal,
          verbose
        )
      };
      faces.push_back(face);
    }
  }

  #ifndef NDEBUG
  const int n_faces = static_cast<int>(faces.size());
  assert(faces.size() == face_point_indices.size());
  for (int i=0; i!=n_faces; ++i)
  {
    const auto face = faces[i];
    const auto indices = face_point_indices[i];
    assert(face->GetPoints().size() == indices.size());
    /*
    const int n_points = static_cast<int>(indices.size());
    for (int j=0; j!=n_points; ++j)
    {
      //Only true when points are not reversed
      assert(face->GetPoints()[j] == points[ indices[j] ]);
    }
    */
  }
  #endif

  assert(faces.size()  ==  8 && "2x2 adjacent squares consist of 8 triangles");
  assert(edges.size()  == 16 && "2x2 adjacent squares (with diagonals) have 16 edges");
  assert(points.size() ==  9 && "2x2 adjacent squares have 9 nodes");

  const boost::shared_ptr<Template> my_template {
    new Template(
      edges,
      faces,
      face_point_indices,
      points
    )
  };
  assert(my_template);
  return my_template;
}
Ejemplo n.º 21
0
int findPeakElement(const vector<int> &num) {
    return Helper(num, 0, num.size()-1);
}
void ribi::trim::Template::Test() noexcept
{
  {
    static bool is_tested{false};
    if (is_tested) return;
    is_tested = true;
  }
  PointFactory();
  FaceFactory();

  const TestTimer test_timer(__func__,__FILE__,1.0);
  const bool verbose{false};
  if (verbose) { TRACE("IsClockWise, confirmation"); }
  {
    /*

    Cartesian plane

          |
          |
          A = (0,1)
         /|\
        / | \
    ---+--+--+----
      /   |   \
     C----+----B
          |
          |


    */
    //12 o'clock
    const boost::shared_ptr<const ConstCoordinat2D> a {
      new ConstCoordinat2D(0.0,1.0)
    };
    //4 o'clock
    const boost::shared_ptr<const ConstCoordinat2D> b {
      new ConstCoordinat2D(0.83,-0.5)
    };
    //8 o'clock
    const boost::shared_ptr<const ConstCoordinat2D> c {
      new ConstCoordinat2D(-0.83,-0.5)
    };
    std::vector<boost::shared_ptr<Point>> points {
      PointFactory().Create(a),
      PointFactory().Create(b),
      PointFactory().Create(c)
    };
    points[0]->SetZ(1.0 * boost::units::si::meter);
    points[1]->SetZ(1.0 * boost::units::si::meter);
    points[2]->SetZ(1.0 * boost::units::si::meter);
    assert( Helper().IsClockwiseHorizontal(points));
    std::reverse(points.begin(),points.end());
    assert(!Helper().IsClockwiseHorizontal(points));
  }
  if (verbose) { TRACE("IsClockWise, rejection"); }
  {
    /*

    Cartesian plane

          |
          |
          A = (0,1)
         /|\
        / | \
    ---+--+--+----
      /   |   \
     B----+----C
          |
          |


    */
    //12 o'clock
    const boost::shared_ptr<const ConstCoordinat2D> a {
      new ConstCoordinat2D(0.0,1.0)
    };
    //8 o'clock
    const boost::shared_ptr<const ConstCoordinat2D> b {
      new ConstCoordinat2D(-0.83,-0.5)
    };
    //4 o'clock
    const boost::shared_ptr<const ConstCoordinat2D> c {
      new ConstCoordinat2D(0.83,-0.5)
    };
    std::vector<boost::shared_ptr<Point>> points {
      PointFactory().Create(a),
      PointFactory().Create(b),
      PointFactory().Create(c)
    };
    points[0]->SetZ(1.0 * boost::units::si::meter);
    points[1]->SetZ(1.0 * boost::units::si::meter);
    points[2]->SetZ(1.0 * boost::units::si::meter);
    assert(!Helper().IsClockwiseHorizontal(points));
    std::reverse(points.begin(),points.end());
    assert(Helper().IsClockwiseHorizontal(points));
  }
  for (int i=0; i!=4; ++i)
  {
    const boost::shared_ptr<Template> my_template {
      CreateTest(i)
    };
    assert(my_template);
    for (const auto& face: my_template->GetFaces())
    {
      if (!Helper().IsClockwiseHorizontal(face->GetPoints()))
      {
        TRACE("BREAK");
      }
      assert(Helper().IsClockwiseHorizontal(face->GetPoints()));
    }
  }
}
Ejemplo n.º 23
0
int t9(int n) {
  // Make sure the error works in potentially-evaluated sizeof
  return (int)sizeof(*(Helper(Foo()), (int (*)[n])0)); // expected-warning{{cannot pass object of non-POD type}}
}
 vector<vector<int>> permuteUnique(vector<int>& nums) {
     vector<vector<int>> res;
     Helper(nums, 0, res);
     return res;
 }