<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2016-2019 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#if defined(HAVE_CONFIG_H)
#include "config/pivx-config.h"
#endif

#include "tinyformat.h"
#include "utiltime.h"

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread.hpp>

static int64_t nMockTime = 0; //! For unit testing

int64_t GetTime()
{
    if (nMockTime) return nMockTime;

    return time(NULL);
}

void SetMockTime(int64_t nMockTimeIn)
{
    nMockTime = nMockTimeIn;
}

int64_t GetTimeMillis()
{
    return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
            boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1)))
        .total_milliseconds();
}

int64_t GetTimeMicros()
{
    return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
            boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1)))
        .total_microseconds();
}

void MilliSleep(int64_t n)
{
    boost::this_thread::sleep_for(boost::chrono::milliseconds(n));
}

std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
{
    // std::locale takes ownership of the pointer
    std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat));
    std::stringstream ss;
    ss.imbue(loc);
    ss << boost::posix_time::from_time_t(nTime);
    return ss.str();
}

std::string DurationToDHMS(int64_t nDurationTime)
{
    int seconds = nDurationTime % 60;
    nDurationTime /= 60;
    int minutes = nDurationTime % 60;
    nDurationTime /= 60;
    int hours = nDurationTime % 24;
    int days = nDurationTime / 24;
    if (days)
        return strprintf("%dd %02dh:%02dm:%02ds", days, hours, minutes, seconds);
    if (hours)
        return strprintf("%02dh:%02dm:%02ds", hours, minutes, seconds);
    return strprintf("%02dm:%02ds", minutes, seconds);
}
<commit_msg>fix tsan: utiltime race on nMockTime<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2016-2019 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#if defined(HAVE_CONFIG_H)
#include "config/pivx-config.h"
#endif

#include "tinyformat.h"
#include "utiltime.h"

#include <atomic>

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread.hpp>

static std::atomic<int64_t> nMockTime(0); //!< For unit testing

int64_t GetTime()
{
    int64_t mocktime = nMockTime.load(std::memory_order_relaxed);
    if (mocktime) return mocktime;

    time_t now = time(nullptr);
    assert(now > 0);
    return now;
}

void SetMockTime(int64_t nMockTimeIn)
{
    nMockTime.store(nMockTimeIn, std::memory_order_relaxed);
}

int64_t GetTimeMillis()
{
    int64_t now = (boost::posix_time::microsec_clock::universal_time() -
                   boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
    assert(now > 0);
    return now;
}

int64_t GetTimeMicros()
{
    int64_t now = (boost::posix_time::microsec_clock::universal_time() -
                   boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds();
    assert(now > 0);
    return now;
}

void MilliSleep(int64_t n)
{
    boost::this_thread::sleep_for(boost::chrono::milliseconds(n));
}

std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
{
    // std::locale takes ownership of the pointer
    std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat));
    std::stringstream ss;
    ss.imbue(loc);
    ss << boost::posix_time::from_time_t(nTime);
    return ss.str();
}

std::string DurationToDHMS(int64_t nDurationTime)
{
    int seconds = nDurationTime % 60;
    nDurationTime /= 60;
    int minutes = nDurationTime % 60;
    nDurationTime /= 60;
    int hours = nDurationTime % 24;
    int days = nDurationTime / 24;
    if (days)
        return strprintf("%dd %02dh:%02dm:%02ds", days, hours, minutes, seconds);
    if (hours)
        return strprintf("%02dh:%02dm:%02ds", hours, minutes, seconds);
    return strprintf("%02dm:%02ds", minutes, seconds);
}
<|endoftext|>


<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#if defined(HAVE_CONFIG_H)
#include "config/bitcoin-config.h"
#endif

#include "utiltime.h"

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread.hpp>

using namespace std;

static int64_t nMockTime = 0;  //! For unit testing

int64_t GetTime()
{
    if (nMockTime) return nMockTime;

    return time(NULL);
}

void SetMockTime(int64_t nMockTimeIn)
{
    nMockTime = nMockTimeIn;
}

int64_t GetTimeMillis()
{
    return (boost::posix_time::microsec_clock::universal_time() -
            boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
}

int64_t GetTimeMicros()
{
    return (boost::posix_time::microsec_clock::universal_time() -
            boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds();
}

/** Return a time useful for the debug log */
int64_t GetLogTimeMicros()
{
    if (nMockTime) return nMockTime*1000000;

    return GetTimeMicros();
}

void MilliSleep(int64_t n)
{

/**
 * Boost's sleep_for was uninterruptable when backed by nanosleep from 1.50
 * until fixed in 1.52. Use the deprecated sleep method for the broken case.
 * See: https://svn.boost.org/trac/boost/ticket/7238
 */
#if defined(HAVE_WORKING_BOOST_SLEEP_FOR)
    boost::this_thread::sleep_for(boost::chrono::milliseconds(n));
#elif defined(HAVE_WORKING_BOOST_SLEEP)
    boost::this_thread::sleep(boost::posix_time::milliseconds(n));
#else
//should never get here
#error missing boost sleep implementation
#endif
}

std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
{
    // std::locale takes ownership of the pointer
    std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat));
    std::stringstream ss;
    ss.imbue(loc);
    ss << boost::posix_time::from_time_t(nTime);
    return ss.str();
}
<commit_msg>Assert now > 0 in GetTime GetTimeMillis GetTimeMicros<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#if defined(HAVE_CONFIG_H)
#include "config/bitcoin-config.h"
#endif

#include "utiltime.h"

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread.hpp>

using namespace std;

static int64_t nMockTime = 0;  //! For unit testing

int64_t GetTime()
{
    if (nMockTime) return nMockTime;

    time_t now = time(NULL);
    assert(now > 0);
    return now;
}

void SetMockTime(int64_t nMockTimeIn)
{
    nMockTime = nMockTimeIn;
}

int64_t GetTimeMillis()
{
    int64_t now = (boost::posix_time::microsec_clock::universal_time() -
                   boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
    assert(now > 0);
    return now;
}

int64_t GetTimeMicros()
{
    int64_t now = (boost::posix_time::microsec_clock::universal_time() -
                   boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds();
    assert(now > 0);
    return now;
}

/** Return a time useful for the debug log */
int64_t GetLogTimeMicros()
{
    if (nMockTime) return nMockTime*1000000;

    return GetTimeMicros();
}

void MilliSleep(int64_t n)
{

/**
 * Boost's sleep_for was uninterruptable when backed by nanosleep from 1.50
 * until fixed in 1.52. Use the deprecated sleep method for the broken case.
 * See: https://svn.boost.org/trac/boost/ticket/7238
 */
#if defined(HAVE_WORKING_BOOST_SLEEP_FOR)
    boost::this_thread::sleep_for(boost::chrono::milliseconds(n));
#elif defined(HAVE_WORKING_BOOST_SLEEP)
    boost::this_thread::sleep(boost::posix_time::milliseconds(n));
#else
//should never get here
#error missing boost sleep implementation
#endif
}

std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
{
    // std::locale takes ownership of the pointer
    std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat));
    std::stringstream ss;
    ss.imbue(loc);
    ss << boost::posix_time::from_time_t(nTime);
    return ss.str();
}
<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2005 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/* interface header */
#include "EffectsMenu.h"

/* system implementation headers */
#include <string>
#include <vector>

/* common implementation headers */
#include "BundleMgr.h"
#include "BZDBCache.h"
#include "TextUtils.h"
#include "FontManager.h"
#include "SceneRenderer.h"

/* local implementation headers */
#include "MainMenu.h"
#include "MainWindow.h"
#include "TrackMarks.h"
#include "HUDDialogStack.h"
#include "HUDuiControl.h"
#include "HUDuiList.h"
#include "HUDuiLabel.h"

EffectsMenu::EffectsMenu()
{
  // add controls
  std::vector<HUDuiControl*>& list = getControls();

  // cache font face ID
  int fontFace = MainMenu::getFontFace();

  // the menu label
  HUDuiLabel* label = new HUDuiLabel;
  label->setFontFace(fontFace);
  label->setString("Effects Settings");
  list.push_back(label);

  // the menu options
  HUDuiList* option;
  std::vector<std::string>* options;

  // Rain Scale
  option = new HUDuiList;
  option->setFontFace(MainMenu::getFontFace());
  option->setLabel("Rain:");
  option->setCallback(callback, (void*)"r");
  options = &option->getList();
  options->push_back(std::string("Off"));
  option->createSlider(10);
  option->update();
  list.push_back(option);

  // The Mirror
  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Mirror:");
  option->setCallback(callback, (void*)"m");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("On"));
  option->update();
  list.push_back(option);

  // Animated Treads
  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Animated Treads:");
  option->setCallback(callback, (void*)"a");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("On"));
  option->update();
  list.push_back(option);

  // Display Treads
  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Display Treads:");
  option->setCallback(callback, (void*)"T");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("On"));
  option->update();
  list.push_back(option);

  // Track Mark Fading Scale
  option = new HUDuiList;
  option->setFontFace(MainMenu::getFontFace());
  option->setLabel("Track Marks :");
  option->setCallback(callback, (void*)"t");
  options = &option->getList();
  options->push_back(std::string("Off"));
  option->createSlider(10);
  option->update();
  list.push_back(option);

  // Track Mark Culling Type
  option = new HUDuiList;
  option->setFontFace(MainMenu::getFontFace());
  option->setLabel("Track Mark Culling:");
  option->setCallback(callback, (void*)"c");
  options = &option->getList();
  options->push_back(std::string("None"));
  options->push_back(std::string("Fast"));
  options->push_back(std::string("Best"));
  option->update();
  list.push_back(option);

  initNavigation(list, 1, list.size() - 1);
}

EffectsMenu::~EffectsMenu()
{
}

void EffectsMenu::execute()
{
}

void EffectsMenu::resize(int width, int height)
{
  HUDDialog::resize(width, height);

  // use a big font for title, smaller font for the rest
  const float titleFontSize = (float)height / 15.0f;
  const float fontSize = (float)height / 45.0f;
  FontManager &fm = FontManager::instance();

  // reposition title
  std::vector<HUDuiControl*>& list = getControls();
  HUDuiLabel* title = (HUDuiLabel*)list[0];
  title->setFontSize(titleFontSize);
  const float titleWidth =
    fm.getStrLength(MainMenu::getFontFace(), titleFontSize, title->getString());
  const float titleHeight =
    fm.getStrHeight(MainMenu::getFontFace(), titleFontSize, " ");
  float x = 0.5f * ((float)width - titleWidth);
  float y = (float)height - titleHeight;
  title->setPosition(x, y);

  // reposition options
  x = 0.5f * (float)width;
  y -= 0.6f * titleHeight;
  const float h = fm.getStrHeight(MainMenu::getFontFace(), fontSize, " ");
  const int count = list.size();
  int i;
  for (i = 1; i < count; i++) {
    list[i]->setFontSize(fontSize);
    list[i]->setPosition(x, y);
    y -= 1.0f * h;
  }

  // load current settings
  i = 1;
  ((HUDuiList*)list[i++])->setIndex(int((BZDB.eval("userRainScale") * 10.0f) + 0.5f));
  ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("userMirror") ? 1 : 0);
  ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("animatedTreads") ? 1 : 0);
  ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("showTreads") ? 1 : 0);
  ((HUDuiList*)list[i++])->setIndex(int((TrackMarks::getUserFade() * 10.0f) + 0.5f));
  TrackMarks::AirCullStyle style = TrackMarks::getAirCulling();
  if (style == TrackMarks::NoAirCull) {
    ((HUDuiList*)list[i++])->setIndex(0);
  } else if (style != TrackMarks::FullAirCull) {
    ((HUDuiList*)list[i++])->setIndex(1);
  } else {
    ((HUDuiList*)list[i++])->setIndex(2);
  }
}

void EffectsMenu::callback(HUDuiControl* w, void* data)
{
  HUDuiList* list = (HUDuiList*)w;

  switch (((const char*)data)[0]) {
    case 'r': {
      int scale = list->getIndex();
      BZDB.setFloat("userRainScale", float(scale) / 10.0f);
      break;
    }
    case 'm': {
      BZDB.set("userMirror", list->getIndex() ? "1" : "0");
      break;
    }
    case 'a': {
      BZDB.set("animatedTreads", list->getIndex() ? "1" : "0");
      RENDERER.setRebuildTanks();
      break;
    }
    case 'T': {
      BZDB.set("showTreads", list->getIndex() ? "1" : "0");
      break;
    }
    case 't': {
      int fade = list->getIndex();
      TrackMarks::setUserFade(float(fade) / 10.0f);
      break;
    }
    case 'c': {
      int culling = list->getIndex();
      if (culling <= 0) {
	TrackMarks::setAirCulling(TrackMarks::NoAirCull);
      } else if (culling == 1) {
	TrackMarks::setAirCulling(TrackMarks::InitAirCull);
      } else {
	TrackMarks::setAirCulling(TrackMarks::FullAirCull);
      }
      break;
    }
  }
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>breakup the Effects menu a little<commit_after>/* bzflag
 * Copyright (c) 1993 - 2005 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/* interface header */
#include "EffectsMenu.h"

/* system implementation headers */
#include <string>
#include <vector>

/* common implementation headers */
#include "BundleMgr.h"
#include "BZDBCache.h"
#include "TextUtils.h"
#include "FontManager.h"
#include "SceneRenderer.h"

/* local implementation headers */
#include "MainMenu.h"
#include "MainWindow.h"
#include "TrackMarks.h"
#include "HUDDialogStack.h"
#include "HUDuiControl.h"
#include "HUDuiList.h"
#include "HUDuiLabel.h"

EffectsMenu::EffectsMenu()
{
  // add controls
  std::vector<HUDuiControl*>& list = getControls();

  // cache font face ID
  int fontFace = MainMenu::getFontFace();

  // the menu label
  HUDuiLabel* label = new HUDuiLabel;
  label->setFontFace(fontFace);
  label->setString("Effects Settings");
  list.push_back(label);

  // the menu options
  HUDuiList* option;
  std::vector<std::string>* options;

  // Rain Scale
  option = new HUDuiList;
  option->setFontFace(MainMenu::getFontFace());
  option->setLabel("Rain:");
  option->setCallback(callback, (void*)"r");
  options = &option->getList();
  options->push_back(std::string("Off"));
  option->createSlider(10);
  option->update();
  list.push_back(option);

  // The Mirror
  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Mirror:");
  option->setCallback(callback, (void*)"m");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("On"));
  option->update();
  list.push_back(option);

  // Display Treads
  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Display Treads:");
  option->setCallback(callback, (void*)"T");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("On"));
  option->update();
  list.push_back(option);

  // Animated Treads
  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Animated Treads:");
  option->setCallback(callback, (void*)"a");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("On"));
  option->update();
  list.push_back(option);

  // Track Mark Fading Scale
  option = new HUDuiList;
  option->setFontFace(MainMenu::getFontFace());
  option->setLabel("Track Marks :");
  option->setCallback(callback, (void*)"t");
  options = &option->getList();
  options->push_back(std::string("Off"));
  option->createSlider(10);
  option->update();
  list.push_back(option);

  // Track Mark Culling Type
  option = new HUDuiList;
  option->setFontFace(MainMenu::getFontFace());
  option->setLabel("Track Mark Culling:");
  option->setCallback(callback, (void*)"c");
  options = &option->getList();
  options->push_back(std::string("None"));
  options->push_back(std::string("Fast"));
  options->push_back(std::string("Best"));
  option->update();
  list.push_back(option);

  initNavigation(list, 1, list.size() - 1);
}

EffectsMenu::~EffectsMenu()
{
}

void EffectsMenu::execute()
{
}

void EffectsMenu::resize(int width, int height)
{
  HUDDialog::resize(width, height);

  // use a big font for title, smaller font for the rest
  const float titleFontSize = (float)height / 15.0f;
  const float fontSize = (float)height / 45.0f;
  FontManager &fm = FontManager::instance();

  // reposition title
  std::vector<HUDuiControl*>& list = getControls();
  HUDuiLabel* title = (HUDuiLabel*)list[0];
  title->setFontSize(titleFontSize);
  const float titleWidth =
    fm.getStrLength(MainMenu::getFontFace(), titleFontSize, title->getString());
  const float titleHeight =
    fm.getStrHeight(MainMenu::getFontFace(), titleFontSize, " ");
  float x = 0.5f * ((float)width - titleWidth);
  float y = (float)height - titleHeight;
  title->setPosition(x, y);

  // reposition options
  x = 0.5f * (float)width;
  y -= 0.6f * titleHeight;
  const float h = fm.getStrHeight(MainMenu::getFontFace(), fontSize, " ");
  const int count = list.size();
  int i;
  for (i = 1; i < count; i++) {
    list[i]->setFontSize(fontSize);
    list[i]->setPosition(x, y);
    if ((i == 2) || (i == 4)) {
      y -= 1.75f * h;
    } else {
      y -= 1.0f * h;
    }
  }

  // load current settings
  i = 1;
  ((HUDuiList*)list[i++])->setIndex(int((BZDB.eval("userRainScale") * 10.0f) + 0.5f));
  ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("userMirror") ? 1 : 0);
  ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("showTreads") ? 1 : 0);
  ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("animatedTreads") ? 1 : 0);
  ((HUDuiList*)list[i++])->setIndex(int((TrackMarks::getUserFade() * 10.0f) + 0.5f));
  TrackMarks::AirCullStyle style = TrackMarks::getAirCulling();
  if (style == TrackMarks::NoAirCull) {
    ((HUDuiList*)list[i++])->setIndex(0);
  } else if (style != TrackMarks::FullAirCull) {
    ((HUDuiList*)list[i++])->setIndex(1);
  } else {
    ((HUDuiList*)list[i++])->setIndex(2);
  }
}

void EffectsMenu::callback(HUDuiControl* w, void* data)
{
  HUDuiList* list = (HUDuiList*)w;

  switch (((const char*)data)[0]) {
    case 'r': {
      int scale = list->getIndex();
      BZDB.setFloat("userRainScale", float(scale) / 10.0f);
      break;
    }
    case 'm': {
      BZDB.set("userMirror", list->getIndex() ? "1" : "0");
      break;
    }
    case 'T': {
      BZDB.set("showTreads", list->getIndex() ? "1" : "0");
      break;
    }
    case 'a': {
      BZDB.set("animatedTreads", list->getIndex() ? "1" : "0");
      RENDERER.setRebuildTanks();
      break;
    }
    case 't': {
      int fade = list->getIndex();
      TrackMarks::setUserFade(float(fade) / 10.0f);
      break;
    }
    case 'c': {
      int culling = list->getIndex();
      if (culling <= 0) {
	TrackMarks::setAirCulling(TrackMarks::NoAirCull);
      } else if (culling == 1) {
	TrackMarks::setAirCulling(TrackMarks::InitAirCull);
      } else {
	TrackMarks::setAirCulling(TrackMarks::FullAirCull);
      }
      break;
    }
  }
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <strings.h>

//#include "notas.h"

#define N 0x100

struct TStack{
    struct TAlumno *data[N];
    int cima;
};

void push(struct TStack *pila, struct TAlumno *al){}
struct TAlumno *pop(struct TStack *pila){}

int main(int argc, char *argv[]){

    struct TAlumno *alumno;
    struct TStack pila;
    pila.cima = 0;

    alumno = (struct TAlumno *) malloc(sizeof (struct TAlumno));
    pila.data[0] = alumno;
    pila.cima++;

    return EXIT_SUCCESS;
}
<commit_msg>struct<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <strings.h>

//#include "notas.h"
//hacer una pila que empuje alumnos o lo que queramos.

#define N 0x100

struct TStack{
    struct TAlumno *reg[1000*N];
    struct TAlumno *data[N];
    int cima;
};

void push(struct TStack *pila, struct TAlumno *al){}
struct TAlumno *pop(struct TStack *pila){}

int main(int argc, char *argv[]){

    struct TAlumno *alumno;
    struct TStack pila;
    pila.cima = 0;

    alumno = (struct TAlumno *) malloc(sizeof (struct TAlumno));
    pila.data[0] = alumno;
    pila.cima++;

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "SDL.h"
#include "SDL_image.h"

bool done;
int board[3][3];
int player, winner;
int winXSize = 300;
int winYSize = 300;
SDL_Texture* textureSheet[2];		// Array with the textures
SDL_Window*   window;				// The window
SDL_Renderer* renderer;				// The renderer

void ApplySurface(int x, int y, SDL_Texture *tex, SDL_Renderer *rend) { // Parameters, x and y, define position in the projected window.
	SDL_Rect pos;
    pos.x = x;
    pos.y = y;
	SDL_QueryTexture(tex, NULL, NULL, &pos.w, &pos.h); // Setup ups the image and shows it.
    SDL_RenderCopy(rend, tex, NULL, &pos);
}

SDL_Texture* loadImage(char* _file) { // Returns a pointer to the texture.
	SDL_Texture* tex = nullptr;
	tex = IMG_LoadTexture(renderer, _file);
    if (tex == nullptr) { // Checks the pointer and print error.
		printf("Failed to load image: %s %s\n", _file, IMG_GetError());
		getchar();
	}
    return tex;
}

bool InitSDL() {

	if (SDL_Init(SDL_INIT_EVERYTHING) == -1){
		return false;
	}

	// Creating the window
	window = SDL_CreateWindow("Tick Tack Toe", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, winXSize, winYSize, NULL);
    if (window == nullptr){
		return false;
    }

	// Creating the renderer
	renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    if (renderer == nullptr){
		return false;
    }

	// Loads all the pictures.
	textureSheet[0] = loadImage("blank.png");
	textureSheet[1] = loadImage("O.png");
	textureSheet[2] = loadImage("X.png");

	// Everything went ok
	return true;
}

void select(int &X, int &Y) { // Retrieves the clicked position and prepares it for usage.

	bool click = false;
	SDL_Event _event;

	while (click == false){
		while (SDL_PollEvent(&_event)) {

			// Get the mouse position on click.
			if (_event.type == SDL_MOUSEBUTTONDOWN && _event.button.button == SDL_BUTTON_LEFT){
				SDL_GetMouseState(&Y, &X);
				X = X/100;	Y = Y/100;
				click = true;
			}
			// On closing the window, exit.
			if (_event.type == SDL_QUIT){
				exit(0);
			}
		}
	}
}

void Draw(int _x, int _y, int _i) {
	// Draws to back buffer
	ApplySurface(_x, _y, textureSheet[_i], renderer);
}

int X(int pos) {
	return pos % 3;
}

int Y(int pos) {
	return pos / 3;
}

void set(int pos, int who) {
	board[Y(pos)][X(pos)] = who;
}

void set(int posX, int posY, int who) {
	board[posY][posX] = who;
}

void unset(int pos) {
	board[Y(pos)][X(pos)] = -1;
}

void unset(int posX, int posY) {
	board[posY][posX] = -1;
}

void printIntro() {
	printf(" _____ _           _____               _____          \n");
	printf("|_   _(_)         |_   _|             |_   _|         \n");
	printf("  | |  _  ___ ______| | __ _  ___ ______| | ___   ___ \n");
	printf("  | | | |/ __|______| |/ _` |/ __|______| |/ _ \\ / _ \\\n");
	printf("  | | | | (__       | | (_| | (__       | | (_) |  __/\n");
	printf("  \\_/ |_|\\___|      \\_/\\__,_|\\___|      \\_/\\___/ \\___|\n");
	printf("                                                      \n");
}

void setup() { // Prepares the board and set ups the order of plays for the algorithm.
	printf("Input starting player(0 = AI first, 1 = Human first): "); // 0 = Ai first, 1 = Human first.
	scanf_s("%d", &player);
	if (player != 0) {
		player = 1;
	}

	int i, j;
	for (i = 0; i < 3; i++) {
		for (j = 0; j < 3; j++) {

			board[i][j] = -1;
		}
	}
	done = false;

	printf("\n\tStart Game...\n\n\n");
}

void printBoard() { // Prints the image related to the value in the array.

	int i, j;
	SDL_RenderClear(renderer); // Clears the screen before projecting images.
	for (i = 0; i < 3; i++) {
		for (j = 0; j < 3; j++) {
			Draw(i * 100, j * 100, board[i][j]+1); // Draws the designated image.
		}
	}
	SDL_RenderPresent(renderer); // Renders the prepared images.
}

int checkGame() {
	int i, j;

	// Checking if the game is won Vertically
	for (i = 0; i < 3; i++) {
		int fl = board[i][0];
		for (j = 1; j < 3; j++) {
			if (board[i][j] != fl) {
				fl = -1;
			}
		}
		if (fl == -1) {
			continue;
		}
		winner = fl;
		return 1;
	}

	// Check if the game is won Horizontal
	for (i = 0; i < 3; i++) {
		int fl = board[0][i];
		for (j = 1; j < 3; j++) {
			if (board[j][i] != fl) {
				fl = -1;
			}
		}
		if (fl == -1) {
			continue;
		}
		winner = fl;
		return 1;
	}

	// Checking the game for diagonal winning
	if (board[0][0] == board[1][1] && board[2][2] == board[1][1] && board[0][0] != -1) {
		winner = board[0][0];
		return 1;
	}
	if (board[0][2] == board[1][1] && board[2][0] == board[1][1] && board[1][1] != -1) {
		winner = board[1][1];
		return 1;
	}

	// If there is a free spot left
	for (i = 0; i < 3; i++) {
		for (j = 0; j < 3; j++) {
			if (board[i][j] == -1) {
				return 0;
			}
		}
	}
	winner = -1;
	return 1;
}

int testGame() {
	int i, j;

	// Checks if there is 3 in a row Vertically, and returns the winner if it's not empty
	for (i = 0; i < 3; i++) {
		int fl = board[i][0];
		for (j = 1; j < 3; j++) {
			if (board[i][j] != fl) {
				fl = -1;
			}
		}
		if (fl == -1) {
			continue;
		}
	return fl;
	}

	// Checks if there is 3 in a row Horizontally, and returns the winner if it's not empty
	for (i = 0; i < 3; i++) {

		int fl = board[0][i];
		for (j = 1; j < 3; j++) {
			if (board[j][i] != fl) {
				fl = -1;
			}
		}
		if (fl == -1) {
			continue;
		}
	return fl;
	}

	// Returns the winner if there is 3 in a row diagonally
	if (board[0][0] == board[1][1] && board[2][2] == board[1][1] && board[0][0] != -1) {
		return board[0][0];
	}
	if (board[0][2] == board[1][1] && board[2][0] == board[1][1] && board[1][1] != -1) {
		return board[1][1];
	}

	// Returns 2 if there is a free square
	for (i = 0; i < 3; i++) {
		for (j = 0; j < 3; j++) {
			if (board[i][j] == -1){
				return 2;
			}
		}
	}

	// Otherwise returns -1
	return -1;
}

void playerPlay() {

	// Print the board
	printBoard();
	// Register the spot to play in.
	int x; int y;
	do{
		printf("Click on a free square to play in.\n");
		select(x, y);
	}while (board[y][x] != -1);

	// Change the selected square
	set(x, y, player);
	printf("Played in: %d %d\n", x, y);
}

int AlphaBetaNegamax(int who, int &move, int a, int b) {

	int D = testGame(); // Checks the state of the game.

	// If the game have ended.
	if (D != 2) {

		// Returns a score, 0 = draw, 1 = wictory, -1 = lose
		if (D == -1) {
			return 0;
		} else if (D == who) {
			return 1;
		} else {
			return -1;
		}
	}

	// If the game haven't ended.
	int i, flag = 0;

	// Iterate trough all the possible moves, if they're possible
	for (i = 0; i < 9; i++) {
		if (board[Y(i)][X(i)] == -1) {

			// Tries a move
			set(i, who);
			int tmp;
			int score = -AlphaBetaNegamax(1 - who, tmp, -b, -a); // Recursive tries next move until a score is returned.

			// Undo the move
			unset(i);

			// If the result is victory or better
			if (score >= b) {
				move = i;
				return score;
			}
			// Finds the best possible solution that's not a victory.
			if (score > a || (score == a && flag == 0)) {
				move = i;
				a = score;
				flag = 1;
			}
		}
	}
	return a;
}

void aiPlay() { // Ai calculates his move and plays.
  int bx = 0;
  AlphaBetaNegamax(player, bx, -1, 1); // Calculates optimal move. Maximizes own score, minimazes human score.
  set(bx, player); // Sets the Ai's move.
  printf("Played in: %d %d\n", X(bx), Y(bx));
}

void play() {

	// It is the players turn
	if (player == 1) {
		playerPlay();
	} else {    // Its the AI's turn
		aiPlay();
	}
}

void printOutro() {
	// Prints the winner of the game.
	if( winner == 2) {
		printf("Game Winner: AI");
	} else {
		printf("Game Winner: Player");
	}
}

int main(int argc, char* argv[]) {
	// Initiates SDL
	if(!InitSDL()) {
		printf("Error!");
		return 0;
	}

	// Play game!
	bool restart;
	do{
		// Initiates game
		printIntro();
		setup();

		// While game is still playing
		while (!done) {
			play();
			player = 1 - player;
			if (checkGame()) {

				done = true;
			}
			printBoard();
		}

		// After game have ended, print winner and ask for restart.
		printOutro();
		char holder;
		printf("\nDo you want to try again? Y/N ");
		scanf_s(" %c", &holder, 1);

		// If yes, set the restart bool.
		if(toupper(holder) != 'Y') {
			restart = false;
		} else {
			restart = true;
			system("CLS");
		}
	} while (restart);
	return 0;
}
<commit_msg>Added some error outputs<commit_after>// STD
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
// SDL
#include "SDL.h"
#include "SDL_image.h"

bool done;
int board[3][3];
int player, winner;
int winXSize = 300;
int winYSize = 300;
SDL_Texture* textureSheet[2];		// Array with the textures
SDL_Window*   window;				// The window
SDL_Renderer* renderer;				// The renderer

void ApplySurface(int x, int y, SDL_Texture *tex, SDL_Renderer *rend) { // Parameters, x and y, define position in the projected window.
	SDL_Rect pos;
    pos.x = x;
    pos.y = y;
	SDL_QueryTexture(tex, NULL, NULL, &pos.w, &pos.h); // Setup ups the image and shows it.
    SDL_RenderCopy(rend, tex, NULL, &pos);
}

SDL_Texture* loadImage(char* _file) { // Returns a pointer to the texture.
	SDL_Texture* tex = nullptr;
	tex = IMG_LoadTexture(renderer, _file);
    if (tex == nullptr) { // Checks the pointer and print error.
		printf("Failed to load image: %s %s\n", _file, IMG_GetError());
		getchar();
	}
    return tex;
}

bool InitSDL() {

	if (SDL_Init(SDL_INIT_EVERYTHING) == -1){
		return false;
	}

	// Creating the window
	window = SDL_CreateWindow("Tick Tack Toe", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, winXSize, winYSize, NULL);
    if (window == nullptr){
		printf("Something went wrong, with making the window for SDL");
		getchar();
		return false;
    }

	// Creating the renderer
	renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    if (renderer == nullptr){
		printf("Something went wrong, with making the renderer for SDL");
		getchar();
		return false;
    }

	// Loads all the pictures.
	textureSheet[0] = loadImage("blank.png");
	textureSheet[1] = loadImage("O.png");
	textureSheet[2] = loadImage("X.png");

	// Everything went ok
	return true;
}

void select(int &X, int &Y) { // Retrieves the clicked position and prepares it for usage.

	bool click = false;
	SDL_Event _event;

	while (click == false){
		while (SDL_PollEvent(&_event)) {

			// Get the mouse position on click.
			if (_event.type == SDL_MOUSEBUTTONDOWN && _event.button.button == SDL_BUTTON_LEFT){
				SDL_GetMouseState(&Y, &X);
				X = X/100;	Y = Y/100;
				click = true;
			}
			// On closing the window, exit.
			if (_event.type == SDL_QUIT){
				exit(0);
			}
		}
	}
}

void Draw(int _x, int _y, int _i) {
	// Draws to back buffer
	ApplySurface(_x, _y, textureSheet[_i], renderer);
}

int X(int pos) {
	return pos % 3;
}

int Y(int pos) {
	return pos / 3;
}

void set(int pos, int who) {
	board[Y(pos)][X(pos)] = who;
}

void set(int posX, int posY, int who) {
	board[posY][posX] = who;
}

void unset(int pos) {
	board[Y(pos)][X(pos)] = -1;
}

void unset(int posX, int posY) {
	board[posY][posX] = -1;
}

void printIntro() {
	printf(" _____ _           _____               _____          \n");
	printf("|_   _(_)         |_   _|             |_   _|         \n");
	printf("  | |  _  ___ ______| | __ _  ___ ______| | ___   ___ \n");
	printf("  | | | |/ __|______| |/ _` |/ __|______| |/ _ \\ / _ \\\n");
	printf("  | | | | (__       | | (_| | (__       | | (_) |  __/\n");
	printf("  \\_/ |_|\\___|      \\_/\\__,_|\\___|      \\_/\\___/ \\___|\n");
	printf("                                                      \n");
}

void setup() { // Prepares the board and set ups the order of plays for the algorithm.
	printf("Input starting player(0 = AI first, 1 = Human first): "); // 0 = Ai first, 1 = Human first.
	scanf_s("%d", &player);
	if (player != 0) {
		player = 1;
	}

	int i, j;
	for (i = 0; i < 3; i++) {
		for (j = 0; j < 3; j++) {

			board[i][j] = -1;
		}
	}
	done = false;

	printf("\n\tStart Game...\n\n\n");
}

void printBoard() { // Prints the image related to the value in the array.

	int i, j;
	SDL_RenderClear(renderer); // Clears the screen before projecting images.
	for (i = 0; i < 3; i++) {
		for (j = 0; j < 3; j++) {
			Draw(i * 100, j * 100, board[i][j]+1); // Draws the designated image.
		}
	}
	SDL_RenderPresent(renderer); // Renders the prepared images.
}

int checkGame() {
	int i, j;

	// Checking if the game is won Vertically
	for (i = 0; i < 3; i++) {
		int fl = board[i][0];
		for (j = 1; j < 3; j++) {
			if (board[i][j] != fl) {
				fl = -1;
			}
		}
		if (fl == -1) {
			continue;
		}
		winner = fl;
		return 1;
	}

	// Check if the game is won Horizontal
	for (i = 0; i < 3; i++) {
		int fl = board[0][i];
		for (j = 1; j < 3; j++) {
			if (board[j][i] != fl) {
				fl = -1;
			}
		}
		if (fl == -1) {
			continue;
		}
		winner = fl;
		return 1;
	}

	// Checking the game for diagonal winning
	if (board[0][0] == board[1][1] && board[2][2] == board[1][1] && board[0][0] != -1) {
		winner = board[0][0];
		return 1;
	}
	if (board[0][2] == board[1][1] && board[2][0] == board[1][1] && board[1][1] != -1) {
		winner = board[1][1];
		return 1;
	}

	// If there is a free spot left
	for (i = 0; i < 3; i++) {
		for (j = 0; j < 3; j++) {
			if (board[i][j] == -1) {
				return 0;
			}
		}
	}
	winner = -1;
	return 1;
}

int testGame() {
	int i, j;

	// Checks if there is 3 in a row Vertically, and returns the winner if it's not empty
	for (i = 0; i < 3; i++) {
		int fl = board[i][0];
		for (j = 1; j < 3; j++) {
			if (board[i][j] != fl) {
				fl = -1;
			}
		}
		if (fl == -1) {
			continue;
		}
	return fl;
	}

	// Checks if there is 3 in a row Horizontally, and returns the winner if it's not empty
	for (i = 0; i < 3; i++) {

		int fl = board[0][i];
		for (j = 1; j < 3; j++) {
			if (board[j][i] != fl) {
				fl = -1;
			}
		}
		if (fl == -1) {
			continue;
		}
	return fl;
	}

	// Returns the winner if there is 3 in a row diagonally
	if (board[0][0] == board[1][1] && board[2][2] == board[1][1] && board[0][0] != -1) {
		return board[0][0];
	}
	if (board[0][2] == board[1][1] && board[2][0] == board[1][1] && board[1][1] != -1) {
		return board[1][1];
	}

	// Returns 2 if there is a free square
	for (i = 0; i < 3; i++) {
		for (j = 0; j < 3; j++) {
			if (board[i][j] == -1){
				return 2;
			}
		}
	}

	// Otherwise returns -1
	return -1;
}

void playerPlay() {

	// Print the board
	printBoard();
	// Register the spot to play in.
	int x; int y;
	do{
		printf("Click on a free square to play in.\n");
		select(x, y);
	}while (board[y][x] != -1);

	// Change the selected square
	set(x, y, player);
	printf("Played in: %d %d\n", x, y);
}

int AlphaBetaNegamax(int who, int &move, int a, int b) {

	int D = testGame(); // Checks the state of the game.

	// If the game have ended.
	if (D != 2) {

		// Returns a score, 0 = draw, 1 = wictory, -1 = lose
		if (D == -1) {
			return 0;
		} else if (D == who) {
			return 1;
		} else {
			return -1;
		}
	}

	// If the game haven't ended.
	int i, flag = 0;

	// Iterate trough all the possible moves, if they're possible
	for (i = 0; i < 9; i++) {
		if (board[Y(i)][X(i)] == -1) {

			// Tries a move
			set(i, who);
			int tmp;
			int score = -AlphaBetaNegamax(1 - who, tmp, -b, -a); // Recursive tries next move until a score is returned.

			// Undo the move
			unset(i);

			// If the result is victory or better
			if (score >= b) {
				move = i;
				return score;
			}
			// Finds the best possible solution that's not a victory.
			if (score > a || (score == a && flag == 0)) {
				move = i;
				a = score;
				flag = 1;
			}
		}
	}
	return a;
}

void aiPlay() { // Ai calculates his move and plays.
  int bx = 0;
  AlphaBetaNegamax(player, bx, -1, 1); // Calculates optimal move. Maximizes own score, minimazes human score.
  set(bx, player); // Sets the Ai's move.
  printf("Played in: %d %d\n", X(bx), Y(bx));
}

void play() {

	// It is the players turn
	if (player == 1) {
		playerPlay();
	} else {    // Its the AI's turn
		aiPlay();
	}
}

void printOutro() {
	// Prints the winner of the game.
	if( winner == 2) {
		printf("Game Winner: AI");
	} else {
		printf("Game Winner: Player");
	}
}

int main(int argc, char* argv[]) {
	// Initiates SDL
	if(!InitSDL()) {
		printf("Error!");
		return 0;
	}

	// Play game!
	bool restart;
	do{
		// Initiates game
		printIntro();
		setup();

		// While game is still playing
		while (!done) {
			play();
			player = 1 - player;
			if (checkGame()) {

				done = true;
			}
			printBoard();
		}

		// After game have ended, print winner and ask for restart.
		printOutro();
		char holder;
		printf("\nDo you want to try again? Y/N ");
		scanf_s(" %c", &holder, 1);

		// If yes, set the restart bool.
		if(toupper(holder) != 'Y') {
			restart = false;
		} else {
			restart = true;
			system("CLS");
		}
	} while (restart);
	return 0;
}
<|endoftext|>


<commit_before>//=====================================================================//
/*! @file
    @brief  ファースト・サンプル（LED 点滅） @n
			RX64M, RX71M, RX72M: @n
					12MHz のベースクロックを使用する @n
			　　　　P07 ピンにLEDを接続する @n
			RX65N (Renesas Envision kit RX65N): @n
					12MHz のベースクロックを使用する @n
			　　　　P70 に接続された LED を利用する @n
			RX63T @n
					12MHz のベースクロックを使用する @n
					PB7 に接続された LED を利用する @n
			RX24T: @n
					10MHz のベースクロックを使用する @n
			　　　　P00 ピンにLEDを接続する @n
			RX66T: @n
					10MHz のベースクロックを使用する @n
			　　　　P00 ピンにLEDを接続する
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"

#include "common/fixed_fifo.hpp"
#include "common/sci_io.hpp"
#include "common/cmt_io.hpp"

#include "common/format.hpp"
#include "common/input.hpp"

#include "FreeRTOS.h"
#include "task.h"

#ifdef SIG_RX64M
// RX64Mで、GR-KAEDE の場合有効にする
#define GR_KAEDE
#endif

namespace {

/// ベースクリスタルの定義
/// LED 接続ポートの定義
#if defined(SIG_RX71M)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
	typedef device::SCI1 SCI_CH;
	static const char* system_str_ = { "RX71M" };
#elif defined(SIG_RX72M)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
	typedef device::SCI1 SCI_CH;
	static const char* system_str_ = { "RX72M" };
#elif defined(SIG_RX64M)
	typedef device::system_io<12000000> SYSTEM_IO;
#ifdef GR_KAEDE
	typedef device::PORT<device::PORTC, device::bitpos::B1> LED;
	typedef device::PORT<device::PORTC, device::bitpos::B0> LED2;
	typedef device::SCI7 SCI_CH;
	static const char* system_str_ = { "GR-KAEDE" };
#else
	typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
	typedef device::SCI1 SCI_CH;
	static const char* system_str_ = { "RX64M" };
#endif
#elif defined(SIG_RX65N)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORT7, device::bitpos::B0> LED;
	typedef device::SCI9 SCI_CH;
	static const char* system_str_ = { "RX65N" };
#elif defined(SIG_RX63T)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORTB, device::bitpos::B7> LED;
	typedef device::SCI1 SCI_CH;
	static const char* system_str_ = { "RX63T" };
#elif defined(SIG_RX24T)
	typedef device::system_io<10000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
	typedef device::SCI1 SCI_CH;
	static const char* system_str_ = { "RX24T" };
#elif defined(SIG_RX66T)
	typedef device::system_io<10000000, 160000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
	typedef device::SCI1 SCI_CH;
	static const char* system_str_ = { "RX66T" };
#endif

	typedef device::cmt_io<device::CMT0> CMT;
	CMT			cmt_;

	typedef utils::fixed_fifo<char, 512> RXB;  // RX (RECV) バッファの定義
	typedef utils::fixed_fifo<char, 256> TXB;  // TX (SEND) バッファの定義

	typedef device::sci_io<SCI_CH, RXB, TXB> SCI;
	SCI			sci_;
}

extern "C" {

	// syscalls.c から呼ばれる、標準出力（stdout, stderr）
	void sci_putch(char ch)
	{
	   	volatile static bool lock_ = false;
		while(lock_) ;
		lock_ = true;
		sci_.putch(ch);
		lock_ = false;
	}

	void sci_puts(const char* str)
	{
		volatile static bool lock_ = false;
		while(lock_) ;
		lock_ = true;
		sci_.puts(str);
		lock_ = false;
	}

	// syscalls.c から呼ばれる、標準入力（stdin）
	char sci_getch(void)
	{
		volatile static bool lock_ = false;
		while(lock_) ;
		lock_ = true;
		auto ch = sci_.getch();
		lock_ = false;
		return ch;
	}

	uint16_t sci_length()
	{
		return sci_.recv_length();
	}

	void vApplicationMallocFailedHook(void)
	{
		/* Called if a call to pvPortMalloc() fails because there is insufficient
		free memory available in the FreeRTOS heap.  pvPortMalloc() is called
		internally by FreeRTOS API functions that create tasks, queues, software
		timers, and semaphores.  The size of the FreeRTOS heap is set by the
		configTOTAL_HEAP_SIZE configuration constant in FreeRTOSConfig.h. */
		taskDISABLE_INTERRUPTS();
		for( ;; );
	}

	void vApplicationStackOverflowHook(TaskHandle_t pxTask, char *pcTaskName)
	{
		( void ) pcTaskName;
		( void ) pxTask;

		/* Run time stack overflow checking is performed if
		configCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2.  This hook
		function is called if a stack overflow is detected. */
		taskDISABLE_INTERRUPTS();
		for( ;; );
	}

	void vApplicationIdleHook(void)
	{
///		volatile size_t xFreeHeapSpace;

		/* This is just a trivial example of an idle hook.  It is called on each
		cycle of the idle task.  It must *NOT* attempt to block.  In this case the
		idle task just queries the amount of FreeRTOS heap that remains.  See the
		memory management section on the http://www.FreeRTOS.org web site for memory
		management options.  If there is a lot of heap memory free then the
		configTOTAL_HEAP_SIZE value in FreeRTOSConfig.h can be reduced to free up
		RAM. */
///		xFreeHeapSpace = xPortGetFreeHeapSize();

		/* Remove compiler warning about xFreeHeapSpace being set but never used. */
///		( void ) xFreeHeapSpace;
	}

	void vApplicationTickHook(void)
	{
	}

	void vAssertCalled(void)
	{
		volatile unsigned long ul = 0;

		taskENTER_CRITICAL();
		{
			/* Use the debugger to set ul to a non-zero value in order to step out
			of this function to determine why it was called. */
			while( ul == 0 )
			{
				portNOP();
			}
		}
		taskEXIT_CRITICAL();
	}

	extern void vTickISR(void);
	extern void vSoftwareInterruptISR(void);

	void vApplicationSetupTimerInterrupt(void)
	{
		uint8_t intr = configKERNEL_INTERRUPT_PRIORITY;
		cmt_.start(configTICK_RATE_HZ, intr, vTickISR);

		device::icu_mgr::set_task(device::ICU::VECTOR::SWINT, vSoftwareInterruptISR);
		device::icu_mgr::set_level(device::ICU::VECTOR::SWINT, configKERNEL_INTERRUPT_PRIORITY);
	}
};

namespace {

	void vTask1(void *pvParameters)
	{
		uint32_t loop = 0;
		uint32_t cnt = 0;
		while(1) {
			vTaskEnterCritical();
			LED::P = !LED::P();
			vTaskExitCritical();
			vTaskDelay(500 / portTICK_PERIOD_MS);
			++loop;
			if(loop >= 10) {
				loop = 0;
				utils::format("Task1: %u\n") % cnt;
				++cnt;
			}
		}
	}

	void vTask2(void *pvParameters)
	{
		uint32_t loop = 0;
		uint32_t cnt = 0;
		while(1) {
			vTaskEnterCritical();
#ifdef GR_KAEDE
			LED2::P = !LED2::P();
#else
			LED::P = !LED::P();
#endif
			vTaskExitCritical();
			vTaskDelay(100 / portTICK_PERIOD_MS);
			++loop;
			if(loop >= 12) {
				loop = 0;
				utils::format("Task2: %u\n") % cnt;
				++cnt;
			}
		}
	}

	void vTask3(void *pvParameters)
	{
		uint32_t cnt = 0;
		while(1) {
			utils::format("Task3: %u\n") % cnt;
			++cnt;
			vTaskDelay(1000 / portTICK_PERIOD_MS);
		}
	}
}

int main(int argc, char** argv);

int main(int argc, char** argv)
{
	SYSTEM_IO::setup_system_clock();

	LED::OUTPUT();  // LED ポートを出力に設定
	LED::P = 1;		// Off
#ifdef GR_KAEDE
	LED2::OUTPUT();
	LED2::P = 1;
#endif

	{  // SCI の開始
		uint8_t intr = 2;        // 割り込みレベル
		uint32_t baud = 115200;  // ボーレート
		sci_.start(baud, intr);
	}

	auto clk = F_ICLK / 1000000;
	utils::format("Start FreeRTOS sample for '%s' %d[MHz]\n") % system_str_ % clk;

	{
		uint32_t stack_size = 512;
		void* param = nullptr;
		uint32_t prio = 1;
		xTaskCreate(vTask1, "Task1", stack_size, param, prio, nullptr);
		xTaskCreate(vTask2, "Task2", stack_size, param, prio, nullptr);
		xTaskCreate(vTask3, "Task3", stack_size, param, prio, nullptr);
	}

	vTaskStartScheduler();

	// タスクスケジューラーが正常なら実行されない
	while(1) {
		utils::delay::milli_second(250);
		LED::P = !LED::P();
		utils::delay::milli_second(250);
		LED::P = !LED::P();
	}
}
<commit_msg>Update: cleanup<commit_after>//=====================================================================//
/*! @file
    @brief  FreeRTOS Simple Sample（Flash LED, Output SCI） @n
			RX64M, RX71M, RX72M: @n
					12MHz のベースクロックを使用する @n
			　　　　P07 ピンにLEDを接続する @n
			RX65N (Renesas Envision kit RX65N): @n
					12MHz のベースクロックを使用する @n
			　　　　P70 に接続された LED を利用する @n
			RX63T @n
					12MHz のベースクロックを使用する @n
					PB7 に接続された LED を利用する @n
			RX24T: @n
					10MHz のベースクロックを使用する @n
			　　　　P00 ピンにLEDを接続する @n
			RX66T: @n
					10MHz のベースクロックを使用する @n
			　　　　P00 ピンにLEDを接続する
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"

#include "common/fixed_fifo.hpp"
#include "common/sci_io.hpp"
#include "common/cmt_io.hpp"

#include "common/format.hpp"
#include "common/input.hpp"

#include "FreeRTOS.h"
#include "task.h"

#ifdef SIG_RX64M
// RX64Mで、GR-KAEDE の場合有効にする
// #define GR_KAEDE
#endif

namespace {

/// ベースクリスタルの定義
/// LED 接続ポートの定義
#if defined(SIG_RX71M)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
	typedef device::SCI1 SCI_CH;
	static const char* system_str_ = { "RX71M" };
#elif defined(SIG_RX72M)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
	typedef device::SCI1 SCI_CH;
	static const char* system_str_ = { "RX72M" };
#elif defined(SIG_RX64M)
	typedef device::system_io<12000000> SYSTEM_IO;
#ifdef GR_KAEDE
	typedef device::PORT<device::PORTC, device::bitpos::B1> LED;
	typedef device::PORT<device::PORTC, device::bitpos::B0> LED2;
	typedef device::SCI7 SCI_CH;
	static const char* system_str_ = { "GR-KAEDE" };
#else
	typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
	typedef device::SCI1 SCI_CH;
	static const char* system_str_ = { "RX64M" };
#endif
#elif defined(SIG_RX65N)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORT7, device::bitpos::B0> LED;
	typedef device::SCI9 SCI_CH;
	static const char* system_str_ = { "RX65N" };
#elif defined(SIG_RX63T)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORTB, device::bitpos::B7> LED;
	typedef device::SCI1 SCI_CH;
	static const char* system_str_ = { "RX63T" };
#elif defined(SIG_RX24T)
	typedef device::system_io<10000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
	typedef device::SCI1 SCI_CH;
	static const char* system_str_ = { "RX24T" };
#elif defined(SIG_RX66T)
	typedef device::system_io<10000000, 160000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
	typedef device::SCI1 SCI_CH;
	static const char* system_str_ = { "RX66T" };
#endif

	typedef device::cmt_io<device::CMT0> CMT;
	CMT			cmt_;

	typedef utils::fixed_fifo<char, 512> RXB;  // RX (RECV) バッファの定義
	typedef utils::fixed_fifo<char, 256> TXB;  // TX (SEND) バッファの定義

	typedef device::sci_io<SCI_CH, RXB, TXB> SCI;
	SCI			sci_;
}

extern "C" {

	// syscalls.c から呼ばれる、標準出力（stdout, stderr）
	void sci_putch(char ch)
	{
		static volatile bool lock_ = false;
		while(lock_) ;
		lock_ = true;
		sci_.putch(ch);
		lock_ = false;
	}

	void sci_puts(const char* str)
	{
		static volatile bool lock_ = false;
		while(lock_) ;
		lock_ = true;
		sci_.puts(str);
		lock_ = false;
	}

	// syscalls.c から呼ばれる、標準入力（stdin）
	char sci_getch(void)
	{
		static volatile bool lock_ = false;
		while(lock_) ;
		lock_ = true;
		auto ch = sci_.getch();
		lock_ = false;
		return ch;
	}

	uint16_t sci_length()
	{
		return sci_.recv_length();
	}

	void vApplicationMallocFailedHook(void)
	{
		/* Called if a call to pvPortMalloc() fails because there is insufficient
		free memory available in the FreeRTOS heap.  pvPortMalloc() is called
		internally by FreeRTOS API functions that create tasks, queues, software
		timers, and semaphores.  The size of the FreeRTOS heap is set by the
		configTOTAL_HEAP_SIZE configuration constant in FreeRTOSConfig.h. */
		taskDISABLE_INTERRUPTS();
		for( ;; );
	}

	void vApplicationStackOverflowHook(TaskHandle_t pxTask, char *pcTaskName)
	{
		( void ) pcTaskName;
		( void ) pxTask;

		/* Run time stack overflow checking is performed if
		configCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2.  This hook
		function is called if a stack overflow is detected. */
		taskDISABLE_INTERRUPTS();
		for( ;; );
	}

	void vApplicationIdleHook(void)
	{
///		volatile size_t xFreeHeapSpace;

		/* This is just a trivial example of an idle hook.  It is called on each
		cycle of the idle task.  It must *NOT* attempt to block.  In this case the
		idle task just queries the amount of FreeRTOS heap that remains.  See the
		memory management section on the http://www.FreeRTOS.org web site for memory
		management options.  If there is a lot of heap memory free then the
		configTOTAL_HEAP_SIZE value in FreeRTOSConfig.h can be reduced to free up
		RAM. */
///		xFreeHeapSpace = xPortGetFreeHeapSize();

		/* Remove compiler warning about xFreeHeapSpace being set but never used. */
///		( void ) xFreeHeapSpace;
	}

	void vApplicationTickHook(void)
	{
	}

	void vAssertCalled(void)
	{
		volatile unsigned long ul = 0;

		taskENTER_CRITICAL();
		{
			/* Use the debugger to set ul to a non-zero value in order to step out
			of this function to determine why it was called. */
			while( ul == 0 )
			{
				portNOP();
			}
		}
		taskEXIT_CRITICAL();
	}

	extern void vTickISR(void);
	extern void vSoftwareInterruptISR(void);

	void vApplicationSetupTimerInterrupt(void)
	{
		uint8_t intr = configKERNEL_INTERRUPT_PRIORITY;
		cmt_.start(configTICK_RATE_HZ, intr, vTickISR);

		device::icu_mgr::set_task(device::ICU::VECTOR::SWINT, vSoftwareInterruptISR);
		device::icu_mgr::set_level(device::ICU::VECTOR::SWINT, configKERNEL_INTERRUPT_PRIORITY);
	}
};

namespace {

	void vTask1(void *pvParameters)
	{
		uint32_t loop = 0;
		uint32_t cnt = 0;
		while(1) {
			vTaskEnterCritical();
			LED::P = !LED::P();
			vTaskExitCritical();
			vTaskDelay(500 / portTICK_PERIOD_MS);
			++loop;
			if(loop >= 10) {
				loop = 0;
				utils::format("Task1: %u\n") % cnt;
				++cnt;
			}
		}
	}

	void vTask2(void *pvParameters)
	{
		uint32_t loop = 0;
		uint32_t cnt = 0;
		while(1) {
			vTaskEnterCritical();
#ifdef GR_KAEDE
			LED2::P = !LED2::P();
#else
			LED::P = !LED::P();
#endif
			vTaskExitCritical();
			vTaskDelay(100 / portTICK_PERIOD_MS);
			++loop;
			if(loop >= 12) {
				loop = 0;
				utils::format("Task2: %u\n") % cnt;
				++cnt;
			}
		}
	}

	void vTask3(void *pvParameters)
	{
		uint32_t cnt = 0;
		while(1) {
			utils::format("Task3: %u\n") % cnt;
			++cnt;
			vTaskDelay(1000 / portTICK_PERIOD_MS);
		}
	}
}

int main(int argc, char** argv);

int main(int argc, char** argv)
{
	SYSTEM_IO::setup_system_clock();

	LED::OUTPUT();  // LED ポートを出力に設定
	LED::P = 1;		// Off
#ifdef GR_KAEDE
	LED2::OUTPUT();
	LED2::P = 1;
#endif

	{  // SCI の開始
		uint8_t intr = 2;        // 割り込みレベル
		uint32_t baud = 115200;  // ボーレート
		sci_.start(baud, intr);
	}

	auto clk = F_ICLK / 1000000;
	utils::format("Start FreeRTOS sample for '%s' %d[MHz]\n") % system_str_ % clk;

	{
		uint32_t stack_size = 512;
		void* param = nullptr;
		uint32_t prio = 1;
		xTaskCreate(vTask1, "Task1", stack_size, param, prio, nullptr);
		xTaskCreate(vTask2, "Task2", stack_size, param, prio, nullptr);
		xTaskCreate(vTask3, "Task3", stack_size, param, prio, nullptr);
	}

	vTaskStartScheduler();

	// タスクスケジューラーが正常なら実行されない
	while(1) {
		utils::delay::milli_second(250);
		LED::P = !LED::P();
		utils::delay::milli_second(250);
		LED::P = !LED::P();
	}
}
<|endoftext|>


<commit_before>#ifndef SILICIUM_STEADY_CLOCK_HPP
#define SILICIUM_STEADY_CLOCK_HPP

#include <silicium/config.hpp>
#include <boost/chrono/system_clocks.hpp>
#include <chrono>

namespace Si
{
#if defined(BOOST_CHRONO_HAS_STEADY_CLOCK)
#define SILICIUM_HAS_STEADY_CLOCK 1
	using boost::chrono::steady_clock;
	namespace chrono = boost::chrono;
#elif !SILICIUM_GCC46
#define SILICIUM_HAS_STEADY_CLOCK 1
	using std::chrono::steady_clock;
	namespace chrono = std::chrono;
#else
#define SILICIUM_HAS_STEADY_CLOCK 0
	namespace chrono = boost::chrono;
#endif

#if SILICIUM_HAS_STEADY_CLOCK
	typedef steady_clock steady_clock_if_available;
#else
	typedef boost::chrono::system_clock steady_clock_if_available;
#endif
}

#endif
<commit_msg>detect boost::chrono::steady_clock correctly<commit_after>#ifndef SILICIUM_STEADY_CLOCK_HPP
#define SILICIUM_STEADY_CLOCK_HPP

#include <silicium/config.hpp>
#include <boost/chrono/system_clocks.hpp>
#include <chrono>

namespace Si
{
#if defined(BOOST_CHRONO_HAS_CLOCK_STEADY)
#define SILICIUM_HAS_STEADY_CLOCK 1
	using boost::chrono::steady_clock;
	namespace chrono = boost::chrono;
#elif !SILICIUM_GCC46
#define SILICIUM_HAS_STEADY_CLOCK 1
	using std::chrono::steady_clock;
	namespace chrono = std::chrono;
#else
#define SILICIUM_HAS_STEADY_CLOCK 0
	namespace chrono = boost::chrono;
#endif

#if SILICIUM_HAS_STEADY_CLOCK
	typedef steady_clock steady_clock_if_available;
#else
	typedef boost::chrono::system_clock steady_clock_if_available;
#endif
}

#endif
<|endoftext|>


<commit_before>#include "testApp.h"

#include "ofxAlembic.h"

ofEasyCam cam;

ofxAlembic::Reader abc;

//--------------------------------------------------------------
void testApp::setup()
{
	ofSetVerticalSync(true);
	ofSetFrameRate(60);
	ofBackground(0);

	string path = "sample.abc";

	{
		ofxAlembic::Writer writer;

		if (writer.open(path, 30)) // export at 30fps
		{
			for (int f = 0; f < 60; f++)
			{
				// points
				{
					vector<ofVec3f> points;

					for (int i = 0; i < 10; i++)
					{
						ofVec3f p;
						p.x = ofRandom(-300, 300);
						p.y = ofRandom(-300, 300);
						p.z = ofRandom(-300, 300);
						points.push_back(p);
					}

					writer.addPoints("/points", points);
				}

				// curves
				{
					vector<ofPolyline> curves;

					for (int i = 0; i < 10; i++)
					{
						ofPolyline poly;

						for (int n = 0; n < 100; n++)
						{
							ofVec3f v;
							v.x = ofSignedNoise(1, 0, 0, n * 0.01 + f * 10 + i) * 300;
							v.y = ofSignedNoise(0, 1, 0, n * 0.01 + f * 10 + i) * 300;
							v.z = ofSignedNoise(0, 0, 1, n * 0.01 + f * 10 + i) * 300;
							poly.addVertex(v);
						}

						curves.push_back(poly);
					}

					writer.addCurves("/curves", curves);
				}

				// mesh
				{
					ofMesh mesh;

					int num = ofRandom(1, 10) * 3;

					for (int i = 0; i < num; i++)
					{
						ofVec3f p;
						p.x = ofRandom(-300, 300);
						p.y = ofRandom(-300, 300);
						p.z = ofRandom(-300, 300);
						mesh.addVertex(p);
					}

					writer.addPolyMesh("/polymesh", mesh);
				}
			}
		}
	}

	abc.open(path);

	abc.dumpNames();
}

void testApp::exit()
{
	abc.close();
}

//--------------------------------------------------------------
void testApp::update()
{
	float t = fmodf(ofGetElapsedTimef(), abc.getMaxTime());
	abc.setTime(t);
}

//--------------------------------------------------------------
void testApp::draw()
{
	cam.begin();

	glPointSize(4);

	{
		ofMesh mesh;
		abc.get("/polymesh", mesh);

		ofSetColor(255, 0, 0);
		mesh.draw();
	}

	{
		vector<ofVec3f> points;
		abc.get("/points", points);

		ofSetColor(0, 255, 0);
		glBegin(GL_POINTS);
		for (int i = 0; i < points.size(); i++)
			glVertex3fv(points[i].getPtr());
		glEnd();
	}

	{
		vector<ofPolyline> curves;
		abc.get("/curves", curves);

		ofSetColor(0, 0, 255);
		for (int i = 0; i < curves.size(); i++)
			curves[i].draw();
	}

	// or simply, abc.draw();

	cam.end();

	ofSetColor(255);

	ofDrawBitmapString(ofToString(abc.getTime()) + "/" + ofToString(abc.getMaxTime()), 10, 20);
}

//--------------------------------------------------------------
void testApp::keyPressed(int key)
{

}

//--------------------------------------------------------------
void testApp::keyReleased(int key)
{

}

//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y)
{

}

//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button)
{

}

//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button)
{

}

//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button)
{

}

//--------------------------------------------------------------
void testApp::windowResized(int w, int h)
{

}

//--------------------------------------------------------------
void testApp::gotMessage(ofMessage msg)
{

}

//--------------------------------------------------------------
void testApp::dragEvent(ofDragInfo dragInfo)
{

}<commit_msg>Add XForm export example<commit_after>#include "testApp.h"

#include "ofxAlembic.h"

ofEasyCam cam;

ofxAlembic::Reader abc;

//--------------------------------------------------------------
void testApp::setup()
{
	ofSetVerticalSync(true);
	ofSetFrameRate(60);
	ofBackground(0);

	string path = "sample.abc";

	{
		ofxAlembic::Writer writer;

		if (writer.open(path, 30)) // export at 30fps
		{
			for (int f = 0; f < 60; f++)
			{
				// points
				{
					vector<ofVec3f> points;

					for (int i = 0; i < 10; i++)
					{
						ofVec3f p;
						p.x = ofRandom(-300, 300);
						p.y = ofRandom(-300, 300);
						p.z = ofRandom(-300, 300);
						points.push_back(p);
					}

					writer.addPoints("/points", points);
				}

				// curves
				{
					vector<ofPolyline> curves;

					for (int i = 0; i < 10; i++)
					{
						ofPolyline poly;

						for (int n = 0; n < 100; n++)
						{
							ofVec3f v;
							v.x = ofSignedNoise(1, 0, 0, n * 0.01 + f * 10 + i) * 300;
							v.y = ofSignedNoise(0, 1, 0, n * 0.01 + f * 10 + i) * 300;
							v.z = ofSignedNoise(0, 0, 1, n * 0.01 + f * 10 + i) * 300;
							poly.addVertex(v);
						}

						curves.push_back(poly);
					}

					writer.addCurves("/curves", curves);
				}

				// mesh
				{
					ofMesh mesh;

					int num = ofRandom(1, 10) * 3;

					for (int i = 0; i < num; i++)
					{
						ofVec3f p;
						p.x = ofRandom(-300, 300);
						p.y = ofRandom(-300, 300);
						p.z = ofRandom(-300, 300);
						mesh.addVertex(p);
					}

					writer.addPolyMesh("/polymesh", mesh);
				}

				// mesh with xform
				{
					ofMatrix4x4 mat;
					mat.glRotate(f * 5, 0, 1, 0);
					writer.addXform("/box", mat);

					if (f == 0)
					{
						// write only first frame

						ofBoxPrimitive box;
						box.set(100);
						writer.addPolyMesh("/box/boxShape", box.getMesh());
					}
				}
			}
		}
	}

	abc.open(path);

	abc.dumpNames();
}

void testApp::exit()
{
	abc.close();
}

//--------------------------------------------------------------
void testApp::update()
{
	float t = fmodf(ofGetElapsedTimef(), abc.getMaxTime());
	abc.setTime(t);
}

//--------------------------------------------------------------
void testApp::draw()
{
	cam.begin();

	glPointSize(4);

	{
		ofMesh mesh;
		abc.get("/polymesh", mesh);

		ofSetColor(255, 0, 0);
		mesh.draw();
	}

	{
		vector<ofVec3f> points;
		abc.get("/points", points);

		ofSetColor(0, 255, 0);
		glBegin(GL_POINTS);
		for (int i = 0; i < points.size(); i++)
			glVertex3fv(points[i].getPtr());
		glEnd();
	}

	{
		vector<ofPolyline> curves;
		abc.get("/curves", curves);

		ofSetColor(0, 0, 255);
		for (int i = 0; i < curves.size(); i++)
			curves[i].draw();
	}

	{
		ofSetColor(255, 255, 0);
		abc.get("/box")->draw(); // draw box with xform
	}

	// or simply, abc.draw();

	cam.end();

	ofSetColor(255);

	ofDrawBitmapString(ofToString(abc.getTime()) + "/" + ofToString(abc.getMaxTime()), 10, 20);
}

//--------------------------------------------------------------
void testApp::keyPressed(int key)
{

}

//--------------------------------------------------------------
void testApp::keyReleased(int key)
{

}

//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y)
{

}

//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button)
{

}

//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button)
{

}

//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button)
{

}

//--------------------------------------------------------------
void testApp::windowResized(int w, int h)
{

}

//--------------------------------------------------------------
void testApp::gotMessage(ofMessage msg)
{

}

//--------------------------------------------------------------
void testApp::dragEvent(ofDragInfo dragInfo)
{

}<|endoftext|>


<commit_before>// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ozone/ui/desktop_aura/desktop_factory_ozone_wayland.h"

#include "ozone/ui/desktop_aura/desktop_screen_wayland.h"
#include "ozone/ui/desktop_aura/desktop_window_tree_host_ozone.cc"

namespace views {

DesktopWindowTreeHost* DesktopFactoryOzoneWayland::CreateWindowTreeHost(
    internal::NativeWidgetDelegate* native_widget_delegate,
    DesktopNativeWidgetAura* desktop_native_widget_aura) {
  return new DesktopWindowTreeHostOzone(native_widget_delegate,
                                        desktop_native_widget_aura);
}

gfx::Screen* DesktopFactoryOzoneWayland::CreateDesktopScreen() {
  return new DesktopScreenWayland;
}

DesktopFactoryOzone* CreateDesktopFactoryOzoneWayland() {
  return new DesktopFactoryOzoneWayland;
}

}  // namespace views
<commit_msg>Fix multiple definition link error<commit_after>// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ozone/ui/desktop_aura/desktop_factory_ozone_wayland.h"

#include "ozone/ui/desktop_aura/desktop_screen_wayland.h"
#include "ozone/ui/desktop_aura/desktop_window_tree_host_ozone.h"

namespace views {

DesktopWindowTreeHost* DesktopFactoryOzoneWayland::CreateWindowTreeHost(
    internal::NativeWidgetDelegate* native_widget_delegate,
    DesktopNativeWidgetAura* desktop_native_widget_aura) {
  return new DesktopWindowTreeHostOzone(native_widget_delegate,
                                        desktop_native_widget_aura);
}

gfx::Screen* DesktopFactoryOzoneWayland::CreateDesktopScreen() {
  return new DesktopScreenWayland;
}

DesktopFactoryOzone* CreateDesktopFactoryOzoneWayland() {
  return new DesktopFactoryOzoneWayland;
}

}  // namespace views
<|endoftext|>


<commit_before>/*
 * OgreBitesConfigDialog.cpp
 *
 *  Created on: 06.12.2016
 *      Author: pavel
 */

#include "OgreBitesConfigDialog.h"
#include "OgreConfigDialogImp.h"

namespace OgreBites {
    Ogre::ConfigDialog* getNativeConfigDialog() {
#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX || OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_APPLE
        static ConfigDialog dialog;
        return &dialog;
#else
        return NULL;
#endif
    }
} /* namespace OgreBites */
<commit_msg>Bites: disable ConfigDialog on MinGW until we have resolved #1064<commit_after>/*
 * OgreBitesConfigDialog.cpp
 *
 *  Created on: 06.12.2016
 *      Author: pavel
 */

#include "OgreBitesConfigDialog.h"
#include "OgreConfigDialogImp.h"

namespace OgreBites {
    Ogre::ConfigDialog* getNativeConfigDialog() {
#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX || (OGRE_PLATFORM == OGRE_PLATFORM_WIN32 && !defined(__MINGW32__)) || OGRE_PLATFORM == OGRE_PLATFORM_APPLE
        static ConfigDialog dialog;
        return &dialog;
#else
        return NULL;
#endif
    }
} /* namespace OgreBites */
<|endoftext|>


<commit_before>//==============================================================================
// Single cell simulation view graph panel widget
//==============================================================================

#include "singlecellsimulationviewgraphpanelplotwidget.h"
#include "singlecellsimulationviewgraphpanelwidget.h"

//==============================================================================

#include <QHBoxLayout>
#include <QMouseEvent>

//==============================================================================

#include "qwt_plot_curve.h"

//==============================================================================

#include "ui_singlecellsimulationviewgraphpanelwidget.h"

//==============================================================================

namespace OpenCOR {
namespace SingleCellSimulationView {

//==============================================================================

SingleCellSimulationViewGraphPanelWidget::SingleCellSimulationViewGraphPanelWidget(QWidget *pParent) :
    Widget(pParent),
    mGui(new Ui::SingleCellSimulationViewGraphPanelWidget),
    mActive(false)
{
    // Set up the GUI

    mGui->setupUi(this);

    // Create, customise and add an inactive marker to our layout

    static const int MarkerWidth = 3;

    mMarker = new QFrame(this);

    mMarker->setFrameShape(QFrame::VLine);
    mMarker->setLineWidth(MarkerWidth);
    mMarker->setMinimumWidth(MarkerWidth);

    setActive(false);

    mGui->layout->addWidget(mMarker);

    // Create and add a plot widget to our layout

    mPlot = new SingleCellSimulationViewGraphPanelPlotWidget(this);

    mGui->layout->addWidget(mPlot);

    // Allow the graph panel to be of any vertical size

    setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Ignored);
}

//==============================================================================

SingleCellSimulationViewGraphPanelWidget::~SingleCellSimulationViewGraphPanelWidget()
{
    // Delete the GUI

    delete mGui;
}

//==============================================================================

void SingleCellSimulationViewGraphPanelWidget::changeEvent(QEvent *pEvent)
{
    // Default handling of the event

    Widget::changeEvent(pEvent);

    // Check whether the palette has changed and if so then update the colour
    // used to highlight the active graph panel

    if (pEvent->type() == QEvent::PaletteChange)
        updateMarkerColor();
}

//==============================================================================

void SingleCellSimulationViewGraphPanelWidget::mousePressEvent(QMouseEvent *pEvent)
{
    // Default handling of the event

    QWidget::mousePressEvent(pEvent);

    // Activate/inactivate the graph panel
    // Note: we do it through setActive() because we want the graph panel to let
    //       people know that our active state has changed...

    setActive(true);
}

//==============================================================================

SingleCellSimulationViewGraphPanelPlotWidget * SingleCellSimulationViewGraphPanelWidget::plot()
{
    // Return the pointer to our plot widget

    return mPlot;
}

//==============================================================================

bool SingleCellSimulationViewGraphPanelWidget::isActive() const
{
    // Return whether the graph panel as active

    return mActive;
}

//==============================================================================

void SingleCellSimulationViewGraphPanelWidget::updateMarkerColor()
{
    // Update the marker's colour based on whether the graph panel is active

    QPalette newPalette = palette();

    newPalette.setColor(QPalette::WindowText,
                        mActive?
                            CommonWidget::highlightColor():
                            CommonWidget::windowColor());

    mMarker->setPalette(newPalette);
}

//==============================================================================

void SingleCellSimulationViewGraphPanelWidget::setActive(const bool &pActive)
{
    if (pActive == mActive)
        return;

    // Set the graph panel's active state

    mActive = pActive;

    // Update the marker's colour

    updateMarkerColor();

    // Let people know if the graph panel has been activated or inactivated

    if (pActive)
        emit activated(this);
    else
        emit inactivated(this);
}

//==============================================================================

}   // namespace SingleCellSimulationView
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<commit_msg>Temporarily removed the marker in our graph panel (#112).<commit_after>//==============================================================================
// Single cell simulation view graph panel widget
//==============================================================================

#include "singlecellsimulationviewgraphpanelplotwidget.h"
#include "singlecellsimulationviewgraphpanelwidget.h"

//==============================================================================

#include <QHBoxLayout>
#include <QMouseEvent>

//==============================================================================

#include "qwt_plot_curve.h"

//==============================================================================

#include "ui_singlecellsimulationviewgraphpanelwidget.h"

//==============================================================================

namespace OpenCOR {
namespace SingleCellSimulationView {

//==============================================================================

SingleCellSimulationViewGraphPanelWidget::SingleCellSimulationViewGraphPanelWidget(QWidget *pParent) :
    Widget(pParent),
    mGui(new Ui::SingleCellSimulationViewGraphPanelWidget),
    mActive(false)
{
    // Set up the GUI

    mGui->setupUi(this);

    // Create, customise and add an inactive marker to our layout

    static const int MarkerWidth = 3;

    mMarker = new QFrame(this);

    mMarker->setFrameShape(QFrame::VLine);
    mMarker->setLineWidth(MarkerWidth);
    mMarker->setMinimumWidth(MarkerWidth);

    setActive(false);

//    mGui->layout->addWidget(mMarker);
//---GRY--- THIS IS TEMPORARY, I.E. WHILE WE SUPPORT ONLY ONE GRAPH PANEL...

    // Create and add a plot widget to our layout

    mPlot = new SingleCellSimulationViewGraphPanelPlotWidget(this);

    mGui->layout->addWidget(mPlot);

    // Allow the graph panel to be of any vertical size

    setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Ignored);
}

//==============================================================================

SingleCellSimulationViewGraphPanelWidget::~SingleCellSimulationViewGraphPanelWidget()
{
    // Delete the GUI

    delete mGui;
}

//==============================================================================

void SingleCellSimulationViewGraphPanelWidget::changeEvent(QEvent *pEvent)
{
    // Default handling of the event

    Widget::changeEvent(pEvent);

    // Check whether the palette has changed and if so then update the colour
    // used to highlight the active graph panel

    if (pEvent->type() == QEvent::PaletteChange)
        updateMarkerColor();
}

//==============================================================================

void SingleCellSimulationViewGraphPanelWidget::mousePressEvent(QMouseEvent *pEvent)
{
    // Default handling of the event

    QWidget::mousePressEvent(pEvent);

    // Activate/inactivate the graph panel
    // Note: we do it through setActive() because we want the graph panel to let
    //       people know that our active state has changed...

    setActive(true);
}

//==============================================================================

SingleCellSimulationViewGraphPanelPlotWidget * SingleCellSimulationViewGraphPanelWidget::plot()
{
    // Return the pointer to our plot widget

    return mPlot;
}

//==============================================================================

bool SingleCellSimulationViewGraphPanelWidget::isActive() const
{
    // Return whether the graph panel as active

    return mActive;
}

//==============================================================================

void SingleCellSimulationViewGraphPanelWidget::updateMarkerColor()
{
    // Update the marker's colour based on whether the graph panel is active

    QPalette newPalette = palette();

    newPalette.setColor(QPalette::WindowText,
                        mActive?
                            CommonWidget::highlightColor():
                            CommonWidget::windowColor());

    mMarker->setPalette(newPalette);
}

//==============================================================================

void SingleCellSimulationViewGraphPanelWidget::setActive(const bool &pActive)
{
    if (pActive == mActive)
        return;

    // Set the graph panel's active state

    mActive = pActive;

    // Update the marker's colour

    updateMarkerColor();

    // Let people know if the graph panel has been activated or inactivated

    if (pActive)
        emit activated(this);
    else
        emit inactivated(this);
}

//==============================================================================

}   // namespace SingleCellSimulationView
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<|endoftext|>


<commit_before>#include "aiplayer.h"
#include "game.h"

#include <iostream>

AIPlayer::AIPlayer()
{
    // int *tmp = new int[4];
    // tmp[0] = 1;
    // tmp[1] = 2;
    // tmp[2] = 3;
    // tmp[3] = 4;

    // int **out = calculateOrderPermutations(tmp, 4);

    // for (int i = 0; i < calculateNumberOfOrderPermutations(4); i++)
    // {
    //     for (int j = 0; j < 4; j++)
    //     {
    //         std::cout << out[i][j] << "   ";
    //     }
    //     std::cout << "\n";
    // }
}

bool AIPlayer::playRound(int grid[GAME_BOARD_GRID_SIZE][GAME_BOARD_GRID_SIZE],
                         int piece[NUMBER_OF_PIECES_PER_ROUND],
                         int x[NUMBER_OF_PIECES_PER_ROUND],
                         int y[NUMBER_OF_PIECES_PER_ROUND])
{

    int numberOfPermutations = calculateNumberOfOrderPermutations(NUMBER_OF_PIECES_PER_ROUND);
    int **permutations = calculateOrderPermutations(piece, NUMBER_OF_PIECES_PER_ROUND);

    std::vector<int*> permutationsVector = std::vector<int*>();

    for (int i = 0; i < numberOfPermutations; i++)
    {
        bool inAlready = false;
        for (size_t j = 0; j < permutationsVector.size(); j++)
        {
            if (permutationsVector.at(j) == permutations[i])
            {
                inAlready = true;
                break;
            }

            inAlready = true;
            for (int k = 0; k < NUMBER_OF_PIECES_PER_ROUND; k++)
            {
                if (permutations[i][k] != permutationsVector.at(j)[k])
                {
                    inAlready = false;
                    break;
                }
            }

            if (inAlready)
            {
                break;
            }
        }

        if (!inAlready)
        {
            permutationsVector.push_back(permutations[i]);
        }
    }

    delete [] permutations;

    std::vector<Move*> *moves = new std::vector<Move*>();

    for (size_t i = 0; i < permutationsVector.size(); i++)
    {
        calculateMoves(permutationsVector.at(i), grid, moves);
        delete [] permutationsVector.at(i);
    }

    if (moves->size() == 0)
    {
        delete moves;
        std::cout << "No Moves \n";
        return false;
    }

    std::cout << "Number of Moves: " << moves->size() << "\n";

    int bestMoveScore = 0;
    int bestMoveIndex = 0;
    for (size_t m = 0; m < moves->size(); m++)
    {
        evaluateMove(moves->at(m));

        if (moves->at(m)->moveScore > bestMoveScore)
        {
            bestMoveIndex = m;
        }
    }

    for (int i = 0; i < NUMBER_OF_PIECES_PER_ROUND; i++)
    {
        piece[i] = moves->at(bestMoveIndex)->piece[i];
        // piece[i] = 16;//moves->at(bestMoveIndex)->piece[i];
        x[i] = moves->at(bestMoveIndex)->x[i];
        y[i] = moves->at(bestMoveIndex)->y[i];
    }

    for (size_t m = 0; m < moves->size(); m++)
    {
        for (int i = 0; i < GAME_BOARD_GRID_SIZE; i++)
        {
            delete [] moves->at(m)->grid[i];
        }
        delete [] moves->at(m)->grid;
        delete moves->at(m);
    }

    delete moves;
    return true;
}

int AIPlayer::processGrid(int **grid)
{

    int linesCleared = 0;

    bool rowsToClear[GAME_BOARD_GRID_SIZE];
    bool columnsToClear[GAME_BOARD_GRID_SIZE];

    for (int i = 0; i < GAME_BOARD_GRID_SIZE; i++)
    {
        bool didFindHole = false;

        for (int j = 0; j < GAME_BOARD_GRID_SIZE; j++)
        {
            if (grid[i][j] == 0)
            {
                didFindHole = true;
                break;
            }
        }

        rowsToClear[i] = !didFindHole;
    }

    for (int i = 0; i < GAME_BOARD_GRID_SIZE; i++)
    {
        bool didFindHole = false;

        for (int j = 0; j < GAME_BOARD_GRID_SIZE; j++)
        {
            if (grid[j][i] == 0)
            {
                didFindHole = true;
                break;
            }
        }

        columnsToClear[i] = !didFindHole;
    }

    for (int i = 0; i < GAME_BOARD_GRID_SIZE; i++)
    {
        if (!rowsToClear[i])
        {
            continue;
        }

        linesCleared++;

        for (int j = 0; j < GAME_BOARD_GRID_SIZE; j++)
        {
            grid[i][j] = 0;
        }
    }

    for (int i = 0; i < GAME_BOARD_GRID_SIZE; i++)
    {
        if (!columnsToClear[i])
        {
            continue;
        }
        linesCleared++;

        for (int j = 0; j < GAME_BOARD_GRID_SIZE; j++)
        {
            grid[j][i] = 0;
        }
    }

    return linesCleared;
}

void AIPlayer::calculateMoves(int pieces[NUMBER_OF_PIECES_PER_ROUND], int origGrid[GAME_BOARD_GRID_SIZE][GAME_BOARD_GRID_SIZE],  std::vector<Move*> *moves)
{

    // Make an initial empty move
    Move  *initMove = new Move();

    // Clear everything
    initMove->moveScore = 0;
    initMove->numberOfLinesCleared = 0;
    initMove->grid = new int*[GAME_BOARD_GRID_SIZE];

    for (int i = 0; i < NUMBER_OF_PIECES_PER_ROUND; i++)
    {
        initMove->piece[i] = pieces[i];
    }

    for (int j = 0; j < GAME_BOARD_GRID_SIZE; j++)
    {
        // Allocate memory
        initMove->grid[j] = new int[GAME_BOARD_GRID_SIZE];

        // Copy into the new array;
        for (int t = 0; t < GAME_BOARD_GRID_SIZE; t++)
        {
            initMove->grid[j][t] = origGrid[j][t];
        }
    }

    std::vector<Move*> moveTmp = std::vector<Move*>();
    moveTmp.push_back(initMove);

    // Do all additional pieces
    for (int i = 0; i < NUMBER_OF_PIECES_PER_ROUND; i++)
    {
        std::vector<Move*> movetmpOrig = std::vector<Move*>(moveTmp);
        moveTmp.clear();

        // Get the piece data
        int pWidth = 0;
        int pHeight = 0;
        int pGrid[5][5];

        // Get the piece data
        Game::getGridForPiece(pieces[i], pWidth, pHeight, pGrid);

        for (size_t m = 0; m < movetmpOrig.size(); m++)
        {
            Move  *currentMove = movetmpOrig.at(m);
            for (int piecePlacementX = 0; piecePlacementX < (GAME_BOARD_GRID_SIZE - pWidth + 1); piecePlacementX++)
            {
                for (int piecePlacementY = 0; piecePlacementY < (GAME_BOARD_GRID_SIZE - pHeight + 1); piecePlacementY++)
                {
                    bool isValidMove = true;

                    // Check if it is a valid move
                    for (int pX = 0; pX < pWidth; pX++)
                    {
                        for (int pY = 0; pY < pHeight; pY++)
                        {
                            if (currentMove->grid[piecePlacementY + pY][piecePlacementX + pX] == 1)
                            {
                                isValidMove = false;
                                break;
                            }
                        }

                        if (!isValidMove)
                        {
                            break;
                        }
                    }

                    if (!isValidMove)
                    {
                        continue;
                    }

                    Move  *newMove = new Move(*currentMove);

                    for (int pI = 0;  pI < NUMBER_OF_PIECES_PER_ROUND; pI++)
                    {
                        newMove->piece[pI] = currentMove->piece[pI];
                    }

                    newMove->numberOfLinesCleared = currentMove->numberOfLinesCleared;
                    newMove->x[i] = piecePlacementX;
                    newMove->y[i] = piecePlacementY;

                    newMove->grid = new int*[GAME_BOARD_GRID_SIZE];

                    for (int j = 0; j < GAME_BOARD_GRID_SIZE; j++)
                    {
                        // Allocate memory
                        newMove->grid[j] = new int[GAME_BOARD_GRID_SIZE];

                        // Copy into the new array;
                        for (int t = 0; t < GAME_BOARD_GRID_SIZE; t++)
                        {
                            newMove->grid[j][t] = currentMove->grid[j][t];
                        }
                    }

                    // Place the piece since valid
                    for (int pX = 0; pX < pWidth; pX++)
                    {
                        for (int pY = 0; pY < pHeight; pY++)
                        {
                            newMove->grid[piecePlacementY + pY][piecePlacementX + pX] += pGrid[pY][pX];
                        }
                    }

                    newMove->numberOfLinesCleared += processGrid(newMove->grid);

                    moveTmp.push_back(newMove);
                }
            }

            for (int g = 0; g < GAME_BOARD_GRID_SIZE; g++)
            {
                delete [] currentMove->grid[g];
            }
            delete [] currentMove->grid;
            delete movetmpOrig.at(m);
        }
    }

    for (size_t m = 0; m < moveTmp.size(); m++)
    {
        moves->push_back(moveTmp.at(m));
    }

    moveTmp.clear();

}

void AIPlayer::evaluateMove(Move *m)
{

    m->moveScore = m->numberOfLinesCleared;

    // int numberOfHoles = 0;
    // int numberOfFreeLines = 0;

    // for (int x = 0; x < GAME_BOARD_GRID_SIZE; x++)
    // {
    //     for (int y = 0; y < GAME_BOARD_GRID_SIZE; y++)
    //     {

    //     }
    // }
}

int AIPlayer::calculateNumberOfOrderPermutations(int c)
{
    int fact = 1;
    for (int i = c; i > 0; i--)
    {
        fact *= i;
    }

    return fact;
}

int** AIPlayer::calculateOrderPermutations(int *p, int count)
{
    if (count == 1)
    {
        int **ret = new int*[1];
        ret[0] = new int[1];
        ret[0][0] = p[0];
        return ret;
    }

    int lowerPermNum = calculateNumberOfOrderPermutations(count - 1);

    int **ret = new int*[lowerPermNum * count];

    int permPos = 0;
    for (int i = 0; i < count; i++)
    {
        int *par = new int[count - 1];
        int c = 0;
        for (int j = 0; j < count; j++)
        {
            if (j == i)
            {
                continue;
            }
            par[c] = p[j];
            c++;
        }

        int **lowerPerms = calculateOrderPermutations(par, count - 1);
        delete [] par;

        for (int j = 0; j < lowerPermNum; j++)
        {
            ret[permPos] = new int[count];

            for (int t = 0; t < count - 1; t++)
            {
                ret[permPos][t] = lowerPerms[j][t];
            }

            ret[permPos][count - 1] = p[i];
            permPos++;

            delete [] lowerPerms[j];
        }

        delete [] lowerPerms;
    }

    return ret;
}<commit_msg>Added AI logic<commit_after>#include "aiplayer.h"
#include "game.h"

#include <iostream>

AIPlayer::AIPlayer()
{
    // int *tmp = new int[4];
    // tmp[0] = 1;
    // tmp[1] = 2;
    // tmp[2] = 3;
    // tmp[3] = 4;

    // int **out = calculateOrderPermutations(tmp, 4);

    // for (int i = 0; i < calculateNumberOfOrderPermutations(4); i++)
    // {
    //     for (int j = 0; j < 4; j++)
    //     {
    //         std::cout << out[i][j] << "   ";
    //     }
    //     std::cout << "\n";
    // }
}

bool AIPlayer::playRound(int grid[GAME_BOARD_GRID_SIZE][GAME_BOARD_GRID_SIZE],
                         int piece[NUMBER_OF_PIECES_PER_ROUND],
                         int x[NUMBER_OF_PIECES_PER_ROUND],
                         int y[NUMBER_OF_PIECES_PER_ROUND])
{

    int numberOfPermutations = calculateNumberOfOrderPermutations(NUMBER_OF_PIECES_PER_ROUND);
    int **permutations = calculateOrderPermutations(piece, NUMBER_OF_PIECES_PER_ROUND);

    std::vector<int*> permutationsVector = std::vector<int*>();

    for (int i = 0; i < numberOfPermutations; i++)
    {
        bool inAlready = false;
        for (size_t j = 0; j < permutationsVector.size(); j++)
        {
            if (permutationsVector.at(j) == permutations[i])
            {
                inAlready = true;
                break;
            }

            inAlready = true;
            for (int k = 0; k < NUMBER_OF_PIECES_PER_ROUND; k++)
            {
                if (permutations[i][k] != permutationsVector.at(j)[k])
                {
                    inAlready = false;
                    break;
                }
            }

            if (inAlready)
            {
                break;
            }
        }

        if (!inAlready)
        {
            permutationsVector.push_back(permutations[i]);
        }
    }

    delete [] permutations;

    std::vector<Move*> *moves = new std::vector<Move*>();

    for (size_t i = 0; i < permutationsVector.size(); i++)
    {
        calculateMoves(permutationsVector.at(i), grid, moves);
        delete [] permutationsVector.at(i);
    }

    if (moves->size() == 0)
    {
        delete moves;
        std::cout << "No Moves \n";
        return false;
    }

    std::cout << "Number of Moves: " << moves->size() << "\n";

    int bestMoveScore = 0;
    int bestMoveIndex = 0;
    for (size_t m = 0; m < moves->size(); m++)
    {
        evaluateMove(moves->at(m));

        if (moves->at(m)->moveScore > bestMoveScore)
        {
            bestMoveIndex = m;
        }
    }

    for (int i = 0; i < NUMBER_OF_PIECES_PER_ROUND; i++)
    {
        piece[i] = moves->at(bestMoveIndex)->piece[i];
        x[i] = moves->at(bestMoveIndex)->x[i];
        y[i] = moves->at(bestMoveIndex)->y[i];
    }

    for (size_t m = 0; m < moves->size(); m++)
    {
        for (int i = 0; i < GAME_BOARD_GRID_SIZE; i++)
        {
            delete [] moves->at(m)->grid[i];
        }
        delete [] moves->at(m)->grid;
        delete moves->at(m);
    }

    delete moves;
    return true;
}

int AIPlayer::processGrid(int **grid)
{

    int linesCleared = 0;

    bool rowsToClear[GAME_BOARD_GRID_SIZE];
    bool columnsToClear[GAME_BOARD_GRID_SIZE];

    for (int i = 0; i < GAME_BOARD_GRID_SIZE; i++)
    {
        bool didFindHole = false;

        for (int j = 0; j < GAME_BOARD_GRID_SIZE; j++)
        {
            if (grid[i][j] == 0)
            {
                didFindHole = true;
                break;
            }
        }

        rowsToClear[i] = !didFindHole;
    }

    for (int i = 0; i < GAME_BOARD_GRID_SIZE; i++)
    {
        bool didFindHole = false;

        for (int j = 0; j < GAME_BOARD_GRID_SIZE; j++)
        {
            if (grid[j][i] == 0)
            {
                didFindHole = true;
                break;
            }
        }

        columnsToClear[i] = !didFindHole;
    }

    for (int i = 0; i < GAME_BOARD_GRID_SIZE; i++)
    {
        if (!rowsToClear[i])
        {
            continue;
        }

        linesCleared++;

        for (int j = 0; j < GAME_BOARD_GRID_SIZE; j++)
        {
            grid[i][j] = 0;
        }
    }

    for (int i = 0; i < GAME_BOARD_GRID_SIZE; i++)
    {
        if (!columnsToClear[i])
        {
            continue;
        }
        linesCleared++;

        for (int j = 0; j < GAME_BOARD_GRID_SIZE; j++)
        {
            grid[j][i] = 0;
        }
    }

    return linesCleared;
}

void AIPlayer::calculateMoves(int pieces[NUMBER_OF_PIECES_PER_ROUND], int origGrid[GAME_BOARD_GRID_SIZE][GAME_BOARD_GRID_SIZE],  std::vector<Move*> *moves)
{

    // Make an initial empty move
    Move  *initMove = new Move();

    // Clear everything
    initMove->moveScore = 0;
    initMove->numberOfLinesCleared = 0;
    initMove->grid = new int*[GAME_BOARD_GRID_SIZE];

    for (int i = 0; i < NUMBER_OF_PIECES_PER_ROUND; i++)
    {
        initMove->piece[i] = pieces[i];
    }

    for (int j = 0; j < GAME_BOARD_GRID_SIZE; j++)
    {
        // Allocate memory
        initMove->grid[j] = new int[GAME_BOARD_GRID_SIZE];

        // Copy into the new array;
        for (int t = 0; t < GAME_BOARD_GRID_SIZE; t++)
        {
            initMove->grid[j][t] = origGrid[j][t];
        }
    }

    std::vector<Move*> *moveTmp = new std::vector<Move*>();
    moveTmp->push_back(initMove);

    // Do all additional pieces
    for (int i = 0; i < NUMBER_OF_PIECES_PER_ROUND; i++)
    {
        std::vector<Move*> *movetmpOrig = moveTmp;
        moveTmp = new std::vector<Move*>();

        // Get the piece data
        int pWidth = 0;
        int pHeight = 0;
        int pGrid[5][5];

        // Get the piece data
        Game::getGridForPiece(pieces[i], pWidth, pHeight, pGrid);

        for (size_t m = 0; m < movetmpOrig->size(); m++)
        {
            Move  *currentMove = movetmpOrig->at(m);
            for (int piecePlacementX = 0; piecePlacementX < (GAME_BOARD_GRID_SIZE - pWidth + 1); piecePlacementX++)
            {
                for (int piecePlacementY = 0; piecePlacementY < (GAME_BOARD_GRID_SIZE - pHeight + 1); piecePlacementY++)
                {
                    bool isValidMove = true;

                    // Check if it is a valid move
                    for (int pX = 0; pX < pWidth; pX++)
                    {
                        for (int pY = 0; pY < pHeight; pY++)
                        {
                            if (currentMove->grid[piecePlacementY + pY][piecePlacementX + pX] == 1)
                            {
                                isValidMove = false;
                                break;
                            }
                        }

                        if (!isValidMove)
                        {
                            break;
                        }
                    }

                    if (!isValidMove)
                    {
                        continue;
                    }

                    Move  *newMove = new Move(*currentMove);

                    for (int pI = 0;  pI < NUMBER_OF_PIECES_PER_ROUND; pI++)
                    {
                        newMove->piece[pI] = currentMove->piece[pI];
                    }

                    newMove->numberOfLinesCleared = currentMove->numberOfLinesCleared;
                    newMove->x[i] = piecePlacementX;
                    newMove->y[i] = piecePlacementY;

                    newMove->grid = new int*[GAME_BOARD_GRID_SIZE];

                    for (int j = 0; j < GAME_BOARD_GRID_SIZE; j++)
                    {
                        // Allocate memory
                        newMove->grid[j] = new int[GAME_BOARD_GRID_SIZE];

                        // Copy into the new array;
                        for (int t = 0; t < GAME_BOARD_GRID_SIZE; t++)
                        {
                            newMove->grid[j][t] = currentMove->grid[j][t];
                        }
                    }

                    // Place the piece since valid
                    for (int pX = 0; pX < pWidth; pX++)
                    {
                        for (int pY = 0; pY < pHeight; pY++)
                        {
                            newMove->grid[piecePlacementY + pY][piecePlacementX + pX] += pGrid[pY][pX];
                        }
                    }

                    newMove->numberOfLinesCleared += processGrid(newMove->grid);

                    moveTmp->push_back(newMove);
                }
            }

            for (int g = 0; g < GAME_BOARD_GRID_SIZE; g++)
            {
                delete [] currentMove->grid[g];
            }
            delete [] currentMove->grid;
            delete movetmpOrig.at(m);
        }

        delete movetmpOrig;
    }

    for (size_t m = 0; m < moveTmp->size(); m++)
    {
        moves->push_back(moveTmp->at(m));
    }

    delete moveTmp;
    moveTmp->clear();

}

void AIPlayer::evaluateMove(Move *m)
{

    m->moveScore = m->numberOfLinesCleared;

    // int numberOfHoles = 0;
    // int numberOfFreeLines = 0;

    // for (int x = 0; x < GAME_BOARD_GRID_SIZE; x++)
    // {
    //     for (int y = 0; y < GAME_BOARD_GRID_SIZE; y++)
    //     {

    //     }
    // }
}

int AIPlayer::calculateNumberOfOrderPermutations(int c)
{
    int fact = 1;
    for (int i = c; i > 0; i--)
    {
        fact *= i;
    }

    return fact;
}

int** AIPlayer::calculateOrderPermutations(int *p, int count)
{
    if (count == 1)
    {
        int **ret = new int*[1];
        ret[0] = new int[1];
        ret[0][0] = p[0];
        return ret;
    }

    int lowerPermNum = calculateNumberOfOrderPermutations(count - 1);

    int **ret = new int*[lowerPermNum * count];

    int permPos = 0;
    for (int i = 0; i < count; i++)
    {
        int *par = new int[count - 1];
        int c = 0;
        for (int j = 0; j < count; j++)
        {
            if (j == i)
            {
                continue;
            }
            par[c] = p[j];
            c++;
        }

        int **lowerPerms = calculateOrderPermutations(par, count - 1);
        delete [] par;

        for (int j = 0; j < lowerPermNum; j++)
        {
            ret[permPos] = new int[count];

            for (int t = 0; t < count - 1; t++)
            {
                ret[permPos][t] = lowerPerms[j][t];
            }

            ret[permPos][count - 1] = p[i];
            permPos++;

            delete [] lowerPerms[j];
        }

        delete [] lowerPerms;
    }

    return ret;
}<|endoftext|>