<commit_before>#include "client.h"

CLIENT::CLIENT (char *IP)
{
	struct sockaddr_in dest_addr;

        name_verified = false;

	sockfd = socket (AF_INET, SOCK_STREAM, 0);
	if(sockfd == -1){
		perror ("socket");
		exit (EXIT_FAILURE);	// v. pthread_exit
	}

	dest_addr.sin_family = AF_INET;
	dest_addr.sin_port = htons(PORT);
	dest_addr.sin_addr.s_addr = inet_addr(IP);
	memset(&(dest_addr.sin_zero), 0, 8);

	if (connect(sockfd, (struct sockaddr *)&dest_addr, sizeof(struct sockaddr)) == -1){
		if(write (STDERR_FILENO, "Couldn't connect to the server\n", 31) != 31){
                        perror ("write");
                        exit (EXIT_FAILURE);
                }
		if(close(sockfd) == -1){
			perror ("close");
			exit (EXIT_FAILURE);	// v. pthread_exit
		}
	}
}

CLIENT::~CLIENT ()
{

}

void CLIENT::Play ()
{
        server = exchangeCIandName ();

        std::thread (writeLoop, this).detach();

        std::thread (readLoop, this).detach();
}

SERVER CLIENT::exchangeCIandName ()
{
        std::string server_pk;
        std::string server_nonce;
        ssize_t br;
        char buf[64];
        char responce;

        server_pk = recvPK ();
        server_nonce =  recvNonce ();

        sendPK();
        sendNonce();

        while(!name_verified){
                if(write (STDOUT_FILENO, "Please select a username: ", 26) != 26){
                    perror ("write");
                    exit (EXIT_FAILURE);
                }

                memset (buf, 0, 64);

                if((br = read (STDIN_FILENO, buf, 64)) == -1){
                        perror ("read");
                        exit (EXIT_FAILURE);
                }

                if(!br){}   //EOF

                if(write (sockfd, buf, sizeof(buf)) != sizeof(buf)){
                        perror ("write");
                        exit (EXIT_FAILURE);
                }

                if(read (sockfd, &responce, 1) != 1){
                        perror ("read");
                        exit (EXIT_FAILURE);
                }

                if(responce == 'Y')
                        name_verified = true;
        }

        CRYPTO cryptinfo (server_pk, server_nonce);
        SERVER server (cryptinfo);

        return server;
}

void CLIENT::sendPK ()
{
        if(write (sockfd, cryptinfo.getPK().c_str(), crypto_box_PUBLICKEYBYTES ) != crypto_box_PUBLICKEYBYTES){
                perror ("write");
                exit (EXIT_FAILURE);
        }
}

void CLIENT::sendNonce ()
{
        if(write (sockfd, cryptinfo.getNonce().c_str(), crypto_box_NONCEBYTES) != crypto_box_NONCEBYTES){
                perror ("write");
                exit (EXIT_FAILURE);
        }
}

std::string CLIENT::recvPK ()
{
        std::string server_pk;
        char buf[crypto_box_PUBLICKEYBYTES];

        memset (buf, 0, crypto_box_PUBLICKEYBYTES);

        if(read (sockfd, buf, crypto_box_PUBLICKEYBYTES) != crypto_box_PUBLICKEYBYTES){
                perror ("read");
                exit (EXIT_FAILURE);
        }

        server_pk = buf;

        return server_pk;
}

std::string CLIENT::recvNonce ()
{
        std::string server_nonce;
        char buf[crypto_box_NONCEBYTES];

        memset (buf, 0, crypto_box_NONCEBYTES);

        if(read (sockfd, buf, crypto_box_NONCEBYTES) != crypto_box_NONCEBYTES){
                perror ("read");
                exit (EXIT_FAILURE);
        }

        server_nonce = buf;

        return server_nonce;
}

int CLIENT::getSFD ()
{
        return sockfd;
}

void readLoop (CLIENT *client_p)
{
        char buf[1024];
        ssize_t br;

        while(1){
                memset (buf, 0, 1024);

                if((br = read (client_p->getSFD(), buf, 1024)) == -1){
                        perror ("read");
                        exit (EXIT_FAILURE);
                }
                if(!br)
                        return;
                if(write(STDOUT_FILENO, buf, br) != br){
                        perror ("write");
                        exit (EXIT_FAILURE);
                }
        }
}

void writeLoop (CLIENT *client_p)
{
        char buf[1024];
        ssize_t br;

        while(1){
                memset (buf, 0, 1024);

                if((br = read (STDIN_FILENO, buf, 1024)) == -1){
                        perror ("read");
                        exit (EXIT_FAILURE);
                }
                if(!br){
                        //EOF
                        close (client_p->getSFD());
                        return;
                }
                if(write (client_p->getSFD(), buf, br) != br){
                        perror ("write");
                        exit (EXIT_FAILURE);
                }

        }
}<commit_msg>completed client Play () interface<commit_after>#include "client.h"

CLIENT::CLIENT (char *IP)
{
	struct sockaddr_in dest_addr;

        name_verified = false;

	sockfd = socket (AF_INET, SOCK_STREAM, 0);
	if(sockfd == -1){
		perror ("socket");
		exit (EXIT_FAILURE);	// v. pthread_exit
	}

	dest_addr.sin_family = AF_INET;
	dest_addr.sin_port = htons(PORT);
	dest_addr.sin_addr.s_addr = inet_addr(IP);
	memset(&(dest_addr.sin_zero), 0, 8);

	if (connect(sockfd, (struct sockaddr *)&dest_addr, sizeof(struct sockaddr)) == -1){
		if(write (STDERR_FILENO, "Couldn't connect to the server\n", 31) != 31){
                        perror ("write");
                        exit (EXIT_FAILURE);
                }
		if(close(sockfd) == -1){
			perror ("close");
			exit (EXIT_FAILURE);	// v. pthread_exit
		}
	}
}

CLIENT::~CLIENT ()
{

}

void CLIENT::Play ()
{
        server = exchangeCIandName ();

        std::thread (writeLoop, this).detach();

        std::thread (readLoop, this).detach();

        while(true){ sleep(5); }
}

SERVER CLIENT::exchangeCIandName ()
{
        std::string server_pk;
        std::string server_nonce;
        ssize_t br;
        char buf[64];
        char responce;

        server_pk = recvPK ();
        server_nonce =  recvNonce ();

        sendPK();
        sendNonce();

        while(!name_verified){
                if(write (STDOUT_FILENO, "Please select a username: ", 26) != 26){
                    perror ("write");
                    exit (EXIT_FAILURE);
                }

                memset (buf, 0, 64);

                if((br = read (STDIN_FILENO, buf, 64)) == -1){
                        perror ("read");
                        exit (EXIT_FAILURE);
                }

                if(!br){}   //EOF

                if(write (sockfd, buf, sizeof(buf)) != sizeof(buf)){
                        perror ("write");
                        exit (EXIT_FAILURE);
                }

                if(read (sockfd, &responce, 1) != 1){
                        perror ("read");
                        exit (EXIT_FAILURE);
                }

                if(responce == 'Y')
                        name_verified = true;
        }

        CRYPTO cryptinfo (server_pk, server_nonce);
        SERVER server (cryptinfo);

        return server;
}

void CLIENT::sendPK ()
{
        if(write (sockfd, cryptinfo.getPK().c_str(), crypto_box_PUBLICKEYBYTES ) != crypto_box_PUBLICKEYBYTES){
                perror ("write");
                exit (EXIT_FAILURE);
        }
}

void CLIENT::sendNonce ()
{
        if(write (sockfd, cryptinfo.getNonce().c_str(), crypto_box_NONCEBYTES) != crypto_box_NONCEBYTES){
                perror ("write");
                exit (EXIT_FAILURE);
        }
}

std::string CLIENT::recvPK ()
{
        std::string server_pk;
        char buf[crypto_box_PUBLICKEYBYTES];

        memset (buf, 0, crypto_box_PUBLICKEYBYTES);

        if(read (sockfd, buf, crypto_box_PUBLICKEYBYTES) != crypto_box_PUBLICKEYBYTES){
                perror ("read");
                exit (EXIT_FAILURE);
        }

        server_pk = buf;

        return server_pk;
}

std::string CLIENT::recvNonce ()
{
        std::string server_nonce;
        char buf[crypto_box_NONCEBYTES];

        memset (buf, 0, crypto_box_NONCEBYTES);

        if(read (sockfd, buf, crypto_box_NONCEBYTES) != crypto_box_NONCEBYTES){
                perror ("read");
                exit (EXIT_FAILURE);
        }

        server_nonce = buf;

        return server_nonce;
}

int CLIENT::getSFD ()
{
        return sockfd;
}

void readLoop (CLIENT *client_p)
{
        char buf[1024];
        ssize_t br;

        while(1){
                memset (buf, 0, 1024);

                if((br = read (client_p->getSFD(), buf, 1024)) == -1){
                        perror ("read");
                        exit (EXIT_FAILURE);
                }
                if(!br)
                        return;
                if(write(STDOUT_FILENO, buf, br) != br){
                        perror ("write");
                        exit (EXIT_FAILURE);
                }
        }
}

void writeLoop (CLIENT *client_p)
{
        char buf[1024];
        ssize_t br;

        while(1){
                memset (buf, 0, 1024);

                if((br = read (STDIN_FILENO, buf, 1024)) == -1){
                        perror ("read");
                        exit (EXIT_FAILURE);
                }
                if(!br){
                        //EOF
                        close (client_p->getSFD());
                        return;
                }
                if(write (client_p->getSFD(), buf, br) != br){
                        perror ("write");
                        exit (EXIT_FAILURE);
                }

        }
}<|endoftext|>


<commit_before>// -*- c++ -*-
/********************************************************************
 * AUTHORS: Vijay Ganesh
 *
 * BEGIN DATE: November, 2005
 *
 * LICENSE: Please view LICENSE file in the home dir of this Program
 ********************************************************************/

#include "STP.h"

namespace BEEV {

  //Acceps a query, calls the SAT solver and generates Valid/InValid.
  //if returned 0 then input is INVALID if returned 1 then input is
  //VALID if returned 2 then UNDECIDED
  SOLVER_RETURN_TYPE STP::TopLevelSTPAux(const ASTNode& inputasserts_and_query)
  {
    ASTNode inputToSAT = inputasserts_and_query;
    ASTNode orig_input = inputToSAT;
    bm->ASTNodeStats("input asserts and query: ", inputToSAT);

    ASTNode simplified_solved_InputToSAT = inputToSAT;
    //round of substitution, solving, and simplification. ensures that
    //DAG is minimized as much as possibly, and ideally should
    //garuntee that all liketerms in BVPLUSes have been combined.
    bm->SimplifyWrites_InPlace_Flag = false;
    bm->Begin_RemoveWrites = false;
    bm->start_abstracting = false;
    bm->TermsAlreadySeenMap_Clear();
    do
      {
        inputToSAT = simplified_solved_InputToSAT;

        if(bm->UserFlags.optimize_flag)
          {
            bm->GetRunTimes()->start(RunTimes::CreateSubstitutionMap);
            simplified_solved_InputToSAT =
              arrayTransformer->
	      CreateSubstitutionMap(simplified_solved_InputToSAT);

            bm->GetRunTimes()->stop(RunTimes::CreateSubstitutionMap);
            //printf("##################################################\n");
            bm->ASTNodeStats("after pure substitution: ",
			     simplified_solved_InputToSAT);

            simplified_solved_InputToSAT =
              simp->SimplifyFormula_TopLevel(simplified_solved_InputToSAT,
					     false);

            bm->ASTNodeStats("after simplification: ",
			     simplified_solved_InputToSAT);
          }

        if(bm->UserFlags.wordlevel_solve_flag)
          {
            simplified_solved_InputToSAT =
              bvsolver->TopLevelBVSolve(simplified_solved_InputToSAT);
            bm->ASTNodeStats("after solving: ", simplified_solved_InputToSAT);
          }

      }
    while (inputToSAT != simplified_solved_InputToSAT);

    bm->ASTNodeStats("Before SimplifyWrites_Inplace begins: ",
                     simplified_solved_InputToSAT);

    bm->SimplifyWrites_InPlace_Flag = true;
    bm->Begin_RemoveWrites = false;
    bm->start_abstracting = false;
    bm->TermsAlreadySeenMap_Clear();
    do
      {
        inputToSAT = simplified_solved_InputToSAT;

        if(bm->UserFlags.optimize_flag)
          {
            bm->GetRunTimes()->start(RunTimes::CreateSubstitutionMap);
            simplified_solved_InputToSAT =
              arrayTransformer->
	      CreateSubstitutionMap(simplified_solved_InputToSAT);
            bm->GetRunTimes()->stop(RunTimes::CreateSubstitutionMap);
            bm->ASTNodeStats("after pure substitution: ",
			     simplified_solved_InputToSAT);

            simplified_solved_InputToSAT =
              simp->SimplifyFormula_TopLevel(simplified_solved_InputToSAT,
					     false);
            bm->ASTNodeStats("after simplification: ",
			     simplified_solved_InputToSAT);
          }

        if(bm->UserFlags.wordlevel_solve_flag)
          {
            simplified_solved_InputToSAT =
              bvsolver->TopLevelBVSolve(simplified_solved_InputToSAT);
            bm->ASTNodeStats("after solving: ", simplified_solved_InputToSAT);
          }
      } while (inputToSAT != simplified_solved_InputToSAT);

    bm->ASTNodeStats("After SimplifyWrites_Inplace: ",
                     simplified_solved_InputToSAT);

    bm->start_abstracting =
      (bm->UserFlags.arraywrite_refinement_flag) ? true : false;
    bm->SimplifyWrites_InPlace_Flag = false;
    bm->Begin_RemoveWrites = (bm->start_abstracting) ? false : true;
    if (bm->start_abstracting)
      {
        bm->ASTNodeStats("before abstraction round begins: ",
                         simplified_solved_InputToSAT);
      }

    bm->TermsAlreadySeenMap_Clear();
    if (bm->start_abstracting)
      {
        bm->ASTNodeStats("After abstraction: ", simplified_solved_InputToSAT);
      }
    bm->start_abstracting = false;
    bm->SimplifyWrites_InPlace_Flag = false;
    bm->Begin_RemoveWrites = false;

    simplified_solved_InputToSAT =
      arrayTransformer->TransformFormula_TopLevel(simplified_solved_InputToSAT);
    bm->ASTNodeStats("after transformation: ", simplified_solved_InputToSAT);
    bm->TermsAlreadySeenMap_Clear();

    SOLVER_RETURN_TYPE res;

    //solver instantiated here
#ifdef CORE
    MINISAT::Solver newS;
#endif
#ifdef CRYPTOMINISAT
    MINISAT::Solver newS;
#endif
#ifdef SIMP
    MINISAT::SimpSolver newS;
#endif
#ifdef UNSOUND
    MINISAT::UnsoundSimpSolver newS;
#endif

    if (bm->UserFlags.arrayread_refinement_flag)
      {
        bm->counterexample_checking_during_refinement = true;
      }

    res =
      Ctr_Example->CallSAT_ResultCheck(newS,
                                       simplified_solved_InputToSAT,
                                       orig_input);
    if (SOLVER_UNDECIDED != res)
      {
        CountersAndStats("print_func_stats", bm);
        return res;
      }

    // res = SATBased_AllFiniteLoops_Refinement(newS, orig_input);
    //     if (SOLVER_UNDECIDED != res)
    //       {
    //  CountersAndStats("print_func_stats");
    //         return res;
    //       }

    res =
      Ctr_Example->SATBased_ArrayReadRefinement(newS,
                                                simplified_solved_InputToSAT,
                                                orig_input);
    if (SOLVER_UNDECIDED != res)
      {
        CountersAndStats("print_func_stats", bm);
        return res;
      }

    res =
      Ctr_Example->SATBased_ArrayWriteRefinement(newS, orig_input);
    if (SOLVER_UNDECIDED != res)
      {
        CountersAndStats("print_func_stats", bm);
        return res;
      }

    res =
      Ctr_Example->SATBased_ArrayReadRefinement(newS,
                                                simplified_solved_InputToSAT,
                                                orig_input);
    if (SOLVER_UNDECIDED != res)
      {
        CountersAndStats("print_func_stats", bm);
        return res;
      }

    FatalError("TopLevelSTPAux: reached the end without proper conclusion:"
               "either a divide by zero in the input or a bug in STP");
    //bogus return to make the compiler shut up
    return SOLVER_ERROR;
  } //End of TopLevelSTPAux

  //   void STP::ClearAllTables(void)
  //   {
  // //     //Clear STPManager caches

  // //     //Clear ArrayTransformer caches

  // //     //Clear Simplifier caches

  // //     //Clear BVSolver caches

  // //     //Clear AbsRefine_CounterExample caches

  // //     //clear all tables before calling toplevelsat
  // //     //_ASTNode_to_SATVar.clear();
  // //     //_SATVar_to_AST.clear();

  // //     //     for (ASTtoBitvectorMap::iterator it = _ASTNode_to_Bitvector.begin(),
  // //     //     itend = _ASTNode_to_Bitvector.end(); it != itend; it++)
  // //     //       {
  // //     //         (it->second)->clear();
  // //     //         delete (it->second);
  // //     //       }
  // //     //     _ASTNode_to_Bitvector.clear();

  // //     NodeLetVarMap.clear();
  // //     NodeLetVarMap1.clear();
  // //     PLPrintNodeSet.clear();
  // //     AlreadyPrintedSet.clear();
  // //     //ReferenceCount->clear();
  // //     //_arrayread_ite.clear();
  // //     //_introduced_symbols.clear();
  // //     //CounterExampleMap.clear();
  // //     //ComputeFormulaMap.clear();
  // //     StatInfoSet.clear();

  // //     _asserts.clear();

  // //     //     for (ASTNodeToVecMap::iterator iset =
  // //     //     _arrayname_readindices.begin(), iset_end =
  // //     //     _arrayname_readindices.end(); iset != iset_end; iset++) {
  // //     //     iset->second.clear(); }
  // //     //     _arrayname_readindices.clear();

  // //     _interior_unique_table.clear();
  // //     _symbol_unique_table->clear();
  // //     _bvconst_unique_table.clear();
  //   }

  //   void STP::ClearAllCaches(void)
  //   {
  // //     //clear all tables before calling toplevelsat
  // //     //_ASTNode_to_SATVar.clear();
  // //     //_SATVar_to_AST.clear();

  // //     // for (ASTtoBitvectorMap::iterator it = _ASTNode_to_Bitvector.begin(),
  // //     //     itend = _ASTNode_to_Bitvector.end(); it != itend; it++)
  // //     //       {
  // //     //         (it->second)->clear();
  // //     //         delete (it->second);
  // //     //       }
  // //     //     _ASTNode_to_Bitvector.clear();

  // //     NodeLetVarMap.clear();
  // //     NodeLetVarMap1.clear();
  // //     PLPrintNodeSet.clear();
  // //     AlreadyPrintedSet.clear();
  // //     // SimplifyMap->clear();
  // //     //     SimplifyNegMap->clear();
  // //     //     ReferenceCount->clear();
  // //     //     SolverMap.clear();
  // //     //AlwaysTrueFormMap.clear();
  // //     //_arrayread_ite.clear();
  // //     //_arrayread_symbol.clear();
  // //     //_introduced_symbols.clear();
  // //     //CounterExampleMap.clear();
  // //     //ComputeFormulaMap.clear();
  // //     StatInfoSet.clear();

  // //     // for (ASTNodeToVecMap::iterator iset = _arrayname_readindices.begin(), iset_end = _arrayname_readindices.end(); iset != iset_end; iset++)
  // //     //       {
  // //     //         iset->second.clear();
  // //     //       }

  // //     //     _arrayname_readindices.clear();
  // //     //_interior_unique_table.clear();
  // //     //_symbol_unique_table.clear();
  // //     //_bvconst_unique_table.clear();
  //   }
}; //end of namespace
<commit_msg>removed some deadcode relating to previous versions of cleartable and clearcache functions<commit_after>// -*- c++ -*-
/********************************************************************
 * AUTHORS: Vijay Ganesh
 *
 * BEGIN DATE: November, 2005
 *
 * LICENSE: Please view LICENSE file in the home dir of this Program
 ********************************************************************/

#include "STP.h"

namespace BEEV {

  //Acceps a query, calls the SAT solver and generates Valid/InValid.
  //if returned 0 then input is INVALID if returned 1 then input is
  //VALID if returned 2 then UNDECIDED
  SOLVER_RETURN_TYPE STP::TopLevelSTPAux(const ASTNode& inputasserts_and_query)
  {
    ASTNode inputToSAT = inputasserts_and_query;
    ASTNode orig_input = inputToSAT;
    bm->ASTNodeStats("input asserts and query: ", inputToSAT);

    ASTNode simplified_solved_InputToSAT = inputToSAT;
    //round of substitution, solving, and simplification. ensures that
    //DAG is minimized as much as possibly, and ideally should
    //garuntee that all liketerms in BVPLUSes have been combined.
    bm->SimplifyWrites_InPlace_Flag = false;
    bm->Begin_RemoveWrites = false;
    bm->start_abstracting = false;
    bm->TermsAlreadySeenMap_Clear();
    do
      {
        inputToSAT = simplified_solved_InputToSAT;

        if(bm->UserFlags.optimize_flag)
          {
            bm->GetRunTimes()->start(RunTimes::CreateSubstitutionMap);
            simplified_solved_InputToSAT =
              arrayTransformer->
	      CreateSubstitutionMap(simplified_solved_InputToSAT);

            bm->GetRunTimes()->stop(RunTimes::CreateSubstitutionMap);
            //printf("##################################################\n");
            bm->ASTNodeStats("after pure substitution: ",
			     simplified_solved_InputToSAT);

            simplified_solved_InputToSAT =
              simp->SimplifyFormula_TopLevel(simplified_solved_InputToSAT,
					     false);

            bm->ASTNodeStats("after simplification: ",
			     simplified_solved_InputToSAT);
          }

        if(bm->UserFlags.wordlevel_solve_flag)
          {
            simplified_solved_InputToSAT =
              bvsolver->TopLevelBVSolve(simplified_solved_InputToSAT);
            bm->ASTNodeStats("after solving: ", simplified_solved_InputToSAT);
          }

      }
    while (inputToSAT != simplified_solved_InputToSAT);

    bm->ASTNodeStats("Before SimplifyWrites_Inplace begins: ",
                     simplified_solved_InputToSAT);

    bm->SimplifyWrites_InPlace_Flag = true;
    bm->Begin_RemoveWrites = false;
    bm->start_abstracting = false;
    bm->TermsAlreadySeenMap_Clear();
    do
      {
        inputToSAT = simplified_solved_InputToSAT;

        if(bm->UserFlags.optimize_flag)
          {
            bm->GetRunTimes()->start(RunTimes::CreateSubstitutionMap);
            simplified_solved_InputToSAT =
              arrayTransformer->
	      CreateSubstitutionMap(simplified_solved_InputToSAT);
            bm->GetRunTimes()->stop(RunTimes::CreateSubstitutionMap);
            bm->ASTNodeStats("after pure substitution: ",
			     simplified_solved_InputToSAT);

            simplified_solved_InputToSAT =
              simp->SimplifyFormula_TopLevel(simplified_solved_InputToSAT,
					     false);
            bm->ASTNodeStats("after simplification: ",
			     simplified_solved_InputToSAT);
          }

        if(bm->UserFlags.wordlevel_solve_flag)
          {
            simplified_solved_InputToSAT =
              bvsolver->TopLevelBVSolve(simplified_solved_InputToSAT);
            bm->ASTNodeStats("after solving: ", simplified_solved_InputToSAT);
          }
      } while (inputToSAT != simplified_solved_InputToSAT);

    bm->ASTNodeStats("After SimplifyWrites_Inplace: ",
                     simplified_solved_InputToSAT);

    bm->start_abstracting =
      (bm->UserFlags.arraywrite_refinement_flag) ? true : false;
    bm->SimplifyWrites_InPlace_Flag = false;
    bm->Begin_RemoveWrites = (bm->start_abstracting) ? false : true;
    if (bm->start_abstracting)
      {
        bm->ASTNodeStats("before abstraction round begins: ",
                         simplified_solved_InputToSAT);
      }

    bm->TermsAlreadySeenMap_Clear();
    if (bm->start_abstracting)
      {
        bm->ASTNodeStats("After abstraction: ", simplified_solved_InputToSAT);
      }
    bm->start_abstracting = false;
    bm->SimplifyWrites_InPlace_Flag = false;
    bm->Begin_RemoveWrites = false;

    simplified_solved_InputToSAT =
      arrayTransformer->TransformFormula_TopLevel(simplified_solved_InputToSAT);
    bm->ASTNodeStats("after transformation: ", simplified_solved_InputToSAT);
    bm->TermsAlreadySeenMap_Clear();

    SOLVER_RETURN_TYPE res;

    //solver instantiated here
#ifdef CORE
    MINISAT::Solver newS;
#endif
#ifdef CRYPTOMINISAT
    MINISAT::Solver newS;
#endif
#ifdef SIMP
    MINISAT::SimpSolver newS;
#endif
#ifdef UNSOUND
    MINISAT::UnsoundSimpSolver newS;
#endif

    if (bm->UserFlags.arrayread_refinement_flag)
      {
        bm->counterexample_checking_during_refinement = true;
      }

    res =
      Ctr_Example->CallSAT_ResultCheck(newS,
                                       simplified_solved_InputToSAT,
                                       orig_input);
    if (SOLVER_UNDECIDED != res)
      {
        CountersAndStats("print_func_stats", bm);
        return res;
      }

    // res = SATBased_AllFiniteLoops_Refinement(newS, orig_input);
    //     if (SOLVER_UNDECIDED != res)
    //       {
    //  CountersAndStats("print_func_stats");
    //         return res;
    //       }

    res =
      Ctr_Example->SATBased_ArrayReadRefinement(newS,
                                                simplified_solved_InputToSAT,
                                                orig_input);
    if (SOLVER_UNDECIDED != res)
      {
        CountersAndStats("print_func_stats", bm);
        return res;
      }

    res =
      Ctr_Example->SATBased_ArrayWriteRefinement(newS, orig_input);
    if (SOLVER_UNDECIDED != res)
      {
        CountersAndStats("print_func_stats", bm);
        return res;
      }

    res =
      Ctr_Example->SATBased_ArrayReadRefinement(newS,
                                                simplified_solved_InputToSAT,
                                                orig_input);
    if (SOLVER_UNDECIDED != res)
      {
        CountersAndStats("print_func_stats", bm);
        return res;
      }

    FatalError("TopLevelSTPAux: reached the end without proper conclusion:"
               "either a divide by zero in the input or a bug in STP");
    //bogus return to make the compiler shut up
    return SOLVER_ERROR;
  } //End of TopLevelSTPAux
}; //end of namespace
<|endoftext|>


<commit_before>#include "common.h"
#include "watcher.h"
#include <stdlib.h>
#include <stdio.h>
#include <Psapi.h>
#pragma comment (lib, "psapi.lib")

namespace NodeJudger {

#define EXCEPTION_WX86_BREAKPOINT 0x4000001F
#define MAX_TIME_LIMIT_DELAY 200
const bool __WATCHER_PRINT_DEBUG = (GetEnvironmentVar("JUDGE_DEBUG") == "true");

inline __int64 GetRunTime_(HANDLE process)
{
    _FILETIME create_time, exit_time, kernel_time, user_time;
    __int64* ut;

    if(GetProcessTimes(process, &create_time, &exit_time, &kernel_time, &user_time))
    {
        ut = reinterpret_cast<__int64*>(&user_time);
        return (__int64)((*ut) / 10000);
    }

    return -1;
}

__int64 GetRunMemo_(HANDLE process)
{
    PROCESS_MEMORY_COUNTERS memo_counter;
    memo_counter.cb = sizeof(PROCESS_MEMORY_COUNTERS);

    if(GetProcessMemoryInfo(process, &memo_counter, sizeof(PROCESS_MEMORY_COUNTERS)))
    {
        return memo_counter.PagefileUsage / 1024;
    }

    return -1;
}

void ExitAndSetError(HANDLE process, CodeState& code_state, StateEnum state_enum, const char* code = NULL)
{
    DWORD process_id = GetProcessId(process);
    if(process_id) DebugActiveProcessStop(process_id);

    // refer to https://msdn.microsoft.com/en-us/library/windows/desktop/ms686714(v=vs.85).aspx
    //
    // TerminateProcess is asynchronous; it initiates termination and returns immediately. If you
    // need to be sure the process has terminated, call the WaitForSingleObject function with a
    // handle to the process.
    TerminateProcess(process, 4);
    WaitForSingleObject(process, 2000);

    code_state.state = state_enum;
    if(code && strlen(code) != 0)
    {
        strcpy(code_state.error_code, code);
    }
}

void SetRuntimeErrorCode_(CodeState& code_state, DWORD code)
{
    switch(code)
    {
    case EXCEPTION_ACCESS_VIOLATION:
    {
        strcpy(code_state.error_code, "ACCESS_VIOLATION");
        break;
    }

    case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
    {
        strcpy(code_state.error_code, "ARRAY_BOUNDS_EXCEEDED");
        break;
    }

    case EXCEPTION_FLT_DENORMAL_OPERAND:
    {
        strcpy(code_state.error_code, "FLOAT_DENORMAL_OPERAND");
        break;
    }

    case EXCEPTION_FLT_DIVIDE_BY_ZERO:
    {
        strcpy(code_state.error_code, "FLOAT_DIVIDE_BY_ZERO");
        break;
    }

    case EXCEPTION_FLT_OVERFLOW:
    {
        strcpy(code_state.error_code, "FLOAT_OVERFLOW");
        break;
    }

    case EXCEPTION_FLT_UNDERFLOW:
    {
        strcpy(code_state.error_code, "FLOAT_UNDERFLOW");
        break;
    }

    case EXCEPTION_INT_DIVIDE_BY_ZERO:
    {
        strcpy(code_state.error_code, "INTEGER_DIVIDE_BY_ZERO");
        break;
    }

    case EXCEPTION_INT_OVERFLOW:
    {
        strcpy(code_state.error_code, "INTEGER_OVERFLOW");
        break;
    }

    case EXCEPTION_STACK_OVERFLOW:
    {
        strcpy(code_state.error_code, "STACK_OVERFLOW");
        break;
    }

    default:
    {
        char temp[32];
        sprintf(temp, "OTHER_ERRORS_0x%.8X", code);
        strcpy(code_state.error_code, temp);
        break;
    }
    }
}

bool WatchProcess(const HANDLE process,
        const __int64 time_limit,
        const __size memo_limit,
        CodeState& code_state)
{
    __int64 run_time = 0;
    __size run_memo = 0;

    // refer to https://msdn.microsoft.com/en-us/library/windows/desktop/ms679308(v=vs.85).aspx
    //
    // Describes a debugging event.
    //
    // typedef struct _DEBUG_EVENT {
    //     DWORD dwDebugEventCode;
    //     DWORD dwProcessId;
    //     DWORD dwThreadId;
    //     union {
    //         EXCEPTION_DEBUG_INFO      Exception;
    //         CREATE_THREAD_DEBUG_INFO  CreateThread;
    //         CREATE_PROCESS_DEBUG_INFO CreateProcessInfo;
    //         EXIT_THREAD_DEBUG_INFO    ExitThread;
    //         EXIT_PROCESS_DEBUG_INFO   ExitProcess;
    //         LOAD_DLL_DEBUG_INFO       LoadDll;
    //         UNLOAD_DLL_DEBUG_INFO     UnloadDll;
    //         OUTPUT_DEBUG_STRING_INFO  DebugString;
    //         RIP_INFO                  RipInfo;
    //     } u;
    // } DEBUG_EVENT, *LPDEBUG_EVENT;
    DEBUG_EVENT dbe;

    while(true)
    {
        // refer to https://msdn.microsoft.com/en-us/library/windows/desktop/ms681423(v=vs.85).aspx
        //
        // Waits for a debugging event to occur in a process being debugged.
        //
        // If the function succeeds, the return value is nonzero.
        // If the function fails, the return value is zero.To get extended error information, call GetLastError.
        BOOL flag = WaitForDebugEvent(&dbe, (DWORD)time_limit + MAX_TIME_LIMIT_DELAY - run_time);
        if(!flag)
        {
            std::string error = "Cannot wait for debug event: " + GetLastErrorAsString();
            code_state.exe_time = time_limit + MAX_TIME_LIMIT_DELAY;
            code_state.exe_memory = GetRunMemo_(process);
            ExitAndSetError(process, code_state, TIME_LIMIT_EXCEEDED_2, error.c_str());
            return false;
        }

        // refer to http://www.debuginfo.com/examples/src/DebugEvents.cpp
        //
        // close some handles inside dbe
        switch(dbe.dwDebugEventCode)
        {
        case CREATE_PROCESS_DEBUG_EVENT:
            if(__WATCHER_PRINT_DEBUG)
            {
                printf("Event: Process creation\n");
                printf("  CREATE_PROCESS_DEBUG_INFO members:\n");
                printf("    hFile:                  %08p\n", dbe.u.CreateProcessInfo.hFile);
                printf("    hProcess:               %08p\n", dbe.u.CreateProcessInfo.hProcess);
                printf("    hThread                 %08p\n", dbe.u.CreateProcessInfo.hThread);
            }

            // With this event, the debugger receives the following handles:
            //   CREATE_PROCESS_DEBUG_INFO.hProcess - debuggee process handle
            //   CREATE_PROCESS_DEBUG_INFO.hThread  - handle to the initial thread of the debuggee process
            //   CREATE_PROCESS_DEBUG_INFO.hFile    - handle to the executable file that was
            //                                        used to create the debuggee process (.EXE file)
            //
            // hProcess and hThread handles will be closed by the operating system
            // when the debugger calls ContinueDebugEvent after receiving
            // EXIT_PROCESS_DEBUG_EVENT for the given process
            //
            // hFile handle should be closed by the debugger, when the handle
            // is no longer needed
            SAFE_CLOSE_HANDLE(dbe.u.CreateProcessInfo.hFile);
            break;

        case CREATE_THREAD_DEBUG_EVENT:
            // With this event, the debugger receives the following handle:
            //   CREATE_THREAD_DEBUG_INFO.hThread  - handle to the thread that has been created
            //
            // This handle will be closed by the operating system
            // when the debugger calls ContinueDebugEvent after receiving
            // EXIT_THREAD_DEBUG_EVENT for the given thread
            break;

        case LOAD_DLL_DEBUG_EVENT:
        {
            std::string dll_name = GetDLLNameFromDebug(dbe.u.LoadDll);
            if(__WATCHER_PRINT_DEBUG)
            {
                printf("Event: DLL loaded\n");
                printf("  LOAD_DLL_DEBUG_INFO members:\n");
                printf("    hFile:                  %08p\n", dbe.u.LoadDll.hFile);
                printf("    lpBaseOfDll:            %08p\n", dbe.u.LoadDll.lpBaseOfDll);
                printf("    DLLName:                %s\n", dll_name.c_str());
            }

            // With this event, the debugger receives the following handle:
            //   LOAD_DLL_DEBUG_INFO.hFile    - handle to the DLL file
            //
            // This handle should be closed by the debugger, when the handle
            // is no longer needed
            SAFE_CLOSE_HANDLE(dbe.u.LoadDll.hFile);

            // And what's more
            // users are not allowed to load DLL
            if(dll_name.find("\\ntdll.dll") == std::string::npos &&
                    dll_name.find("\\kernel32.dll") == std::string::npos &&
                    dll_name.find("\\KernelBase.dll") == std::string::npos &&
                    dll_name.find("\\msvcrt.dll") == std::string::npos &&
                    dll_name.find("\\wow64.dll") == std::string::npos &&
                    dll_name.find("\\wow64win.dll") == std::string::npos &&
                    dll_name.find("\\wow64cpu.dll") == std::string::npos &&
                    dll_name.find("\\user32.dll") == std::string::npos)
            {
                std::string error = "Code is up to load DLL.";
                code_state.exe_time = -1;
                code_state.exe_memory = -1;
                ExitAndSetError(process, code_state, DANGEROUS_CODE, error.c_str());
                return false;
            }
        }

        default: break;
        }

        // get the run time
        run_time = GetRunTime_(process);
        if(-1 == run_time)
        {
            std::string error = "Cannot get running time: " + GetLastErrorAsString();
            code_state.exe_time = -1;
            code_state.exe_memory = GetRunMemo_(process);
            ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
            ExitAndSetError(process, code_state, SYSTEM_ERROR, error.c_str());
            return false;
        }

        // get the run memory
        run_memo = GetRunMemo_(process);
        if(-1 == run_memo)
        {
            std::string error = "Cannot get occupied memory: " + GetLastErrorAsString();
            code_state.exe_time = run_time;
            code_state.exe_memory = -1;
            ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
            ExitAndSetError(process, code_state, SYSTEM_ERROR, error.c_str());
            return false;
        }

        code_state.exe_time = run_time;
        code_state.exe_memory = run_memo;

        if(run_time > time_limit)
        {
            ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
            ExitAndSetError(process, code_state, TIME_LIMIT_EXCEEDED_1);
            return false;
        }

        if(run_memo > memo_limit)
        {
            ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
            ExitAndSetError(process, code_state, MEMORY_LIMIT_EXCEEDED);
            return false;
        }

        // do some reaction via each DEBUG_EVENT
        switch(dbe.dwDebugEventCode)
        {
        case EXIT_PROCESS_DEBUG_EVENT:
            code_state.state = FINISHED;
            ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
            return true;

        case EXCEPTION_DEBUG_EVENT:
            if(dbe.u.Exception.ExceptionRecord.ExceptionCode != EXCEPTION_BREAKPOINT &&
                    dbe.u.Exception.ExceptionRecord.ExceptionCode != EXCEPTION_WX86_BREAKPOINT)
            {
                SetRuntimeErrorCode_(code_state, dbe.u.Exception.ExceptionRecord.ExceptionCode);
                ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_EXCEPTION_NOT_HANDLED);
                ExitAndSetError(process, code_state, RUNTIME_ERROR);
                return false;
            }
            break;

        default: break;
        }

        ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
        code_state.state = CONTINUE;
    }
}

};<commit_msg>feat: use max memory<commit_after>#include "common.h"
#include "watcher.h"
#include <stdlib.h>
#include <stdio.h>
#include <Psapi.h>
#pragma comment (lib, "psapi.lib")

namespace NodeJudger {

#define EXCEPTION_WX86_BREAKPOINT 0x4000001F
#define MAX_TIME_LIMIT_DELAY 200
const bool __WATCHER_PRINT_DEBUG = (GetEnvironmentVar("JUDGE_DEBUG") == "true");
#define MAX(a, b) ((a) > (b) ? (a) : (b)

inline __int64 GetRunTime_(HANDLE process)
{
    _FILETIME create_time, exit_time, kernel_time, user_time;
    __int64* ut;

    if(GetProcessTimes(process, &create_time, &exit_time, &kernel_time, &user_time))
    {
        ut = reinterpret_cast<__int64*>(&user_time);
        return (__int64)((*ut) / 10000);
    }

    return -1;
}

__int64 GetRunMemo_(HANDLE process)
{
    PROCESS_MEMORY_COUNTERS memo_counter;
    memo_counter.cb = sizeof(PROCESS_MEMORY_COUNTERS);

    if(GetProcessMemoryInfo(process, &memo_counter, sizeof(PROCESS_MEMORY_COUNTERS)))
    {
        return memo_counter.PagefileUsage / 1024;
    }

    return -1;
}

void ExitAndSetError(HANDLE process, CodeState& code_state, StateEnum state_enum, const char* code = NULL)
{
    DWORD process_id = GetProcessId(process);
    if(process_id) DebugActiveProcessStop(process_id);

    // refer to https://msdn.microsoft.com/en-us/library/windows/desktop/ms686714(v=vs.85).aspx
    //
    // TerminateProcess is asynchronous; it initiates termination and returns immediately. If you
    // need to be sure the process has terminated, call the WaitForSingleObject function with a
    // handle to the process.
    TerminateProcess(process, 4);
    WaitForSingleObject(process, 2000);

    code_state.state = state_enum;
    if(code && strlen(code) != 0)
    {
        strcpy(code_state.error_code, code);
    }
}

void SetRuntimeErrorCode_(CodeState& code_state, DWORD code)
{
    switch(code)
    {
    case EXCEPTION_ACCESS_VIOLATION:
    {
        strcpy(code_state.error_code, "ACCESS_VIOLATION");
        break;
    }

    case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
    {
        strcpy(code_state.error_code, "ARRAY_BOUNDS_EXCEEDED");
        break;
    }

    case EXCEPTION_FLT_DENORMAL_OPERAND:
    {
        strcpy(code_state.error_code, "FLOAT_DENORMAL_OPERAND");
        break;
    }

    case EXCEPTION_FLT_DIVIDE_BY_ZERO:
    {
        strcpy(code_state.error_code, "FLOAT_DIVIDE_BY_ZERO");
        break;
    }

    case EXCEPTION_FLT_OVERFLOW:
    {
        strcpy(code_state.error_code, "FLOAT_OVERFLOW");
        break;
    }

    case EXCEPTION_FLT_UNDERFLOW:
    {
        strcpy(code_state.error_code, "FLOAT_UNDERFLOW");
        break;
    }

    case EXCEPTION_INT_DIVIDE_BY_ZERO:
    {
        strcpy(code_state.error_code, "INTEGER_DIVIDE_BY_ZERO");
        break;
    }

    case EXCEPTION_INT_OVERFLOW:
    {
        strcpy(code_state.error_code, "INTEGER_OVERFLOW");
        break;
    }

    case EXCEPTION_STACK_OVERFLOW:
    {
        strcpy(code_state.error_code, "STACK_OVERFLOW");
        break;
    }

    default:
    {
        char temp[32];
        sprintf(temp, "OTHER_ERRORS_0x%.8X", code);
        strcpy(code_state.error_code, temp);
        break;
    }
    }
}

bool WatchProcess(const HANDLE process,
        const __int64 time_limit,
        const __size memo_limit,
        CodeState& code_state)
{
    __int64 run_time = 0;
    __size run_memo = 0;

    // refer to https://msdn.microsoft.com/en-us/library/windows/desktop/ms679308(v=vs.85).aspx
    //
    // Describes a debugging event.
    //
    // typedef struct _DEBUG_EVENT {
    //     DWORD dwDebugEventCode;
    //     DWORD dwProcessId;
    //     DWORD dwThreadId;
    //     union {
    //         EXCEPTION_DEBUG_INFO      Exception;
    //         CREATE_THREAD_DEBUG_INFO  CreateThread;
    //         CREATE_PROCESS_DEBUG_INFO CreateProcessInfo;
    //         EXIT_THREAD_DEBUG_INFO    ExitThread;
    //         EXIT_PROCESS_DEBUG_INFO   ExitProcess;
    //         LOAD_DLL_DEBUG_INFO       LoadDll;
    //         UNLOAD_DLL_DEBUG_INFO     UnloadDll;
    //         OUTPUT_DEBUG_STRING_INFO  DebugString;
    //         RIP_INFO                  RipInfo;
    //     } u;
    // } DEBUG_EVENT, *LPDEBUG_EVENT;
    DEBUG_EVENT dbe;

    while(true)
    {
        // refer to https://msdn.microsoft.com/en-us/library/windows/desktop/ms681423(v=vs.85).aspx
        //
        // Waits for a debugging event to occur in a process being debugged.
        //
        // If the function succeeds, the return value is nonzero.
        // If the function fails, the return value is zero.To get extended error information, call GetLastError.
        BOOL flag = WaitForDebugEvent(&dbe, (DWORD)time_limit + MAX_TIME_LIMIT_DELAY - run_time);
        if(!flag)
        {
            std::string error = "Cannot wait for debug event: " + GetLastErrorAsString();
            code_state.exe_time = time_limit + MAX_TIME_LIMIT_DELAY;
            code_state.exe_memory = MAX(GetRunMemo_(process), code_state.exe_memory);
            ExitAndSetError(process, code_state, TIME_LIMIT_EXCEEDED_2, error.c_str());
            return false;
        }

        // refer to http://www.debuginfo.com/examples/src/DebugEvents.cpp
        //
        // close some handles inside dbe
        switch(dbe.dwDebugEventCode)
        {
        case CREATE_PROCESS_DEBUG_EVENT:
            if(__WATCHER_PRINT_DEBUG)
            {
                printf("Event: Process creation\n");
                printf("  CREATE_PROCESS_DEBUG_INFO members:\n");
                printf("    hFile:                  %08p\n", dbe.u.CreateProcessInfo.hFile);
                printf("    hProcess:               %08p\n", dbe.u.CreateProcessInfo.hProcess);
                printf("    hThread                 %08p\n", dbe.u.CreateProcessInfo.hThread);
            }

            // With this event, the debugger receives the following handles:
            //   CREATE_PROCESS_DEBUG_INFO.hProcess - debuggee process handle
            //   CREATE_PROCESS_DEBUG_INFO.hThread  - handle to the initial thread of the debuggee process
            //   CREATE_PROCESS_DEBUG_INFO.hFile    - handle to the executable file that was
            //                                        used to create the debuggee process (.EXE file)
            //
            // hProcess and hThread handles will be closed by the operating system
            // when the debugger calls ContinueDebugEvent after receiving
            // EXIT_PROCESS_DEBUG_EVENT for the given process
            //
            // hFile handle should be closed by the debugger, when the handle
            // is no longer needed
            SAFE_CLOSE_HANDLE(dbe.u.CreateProcessInfo.hFile);
            break;

        case CREATE_THREAD_DEBUG_EVENT:
            // With this event, the debugger receives the following handle:
            //   CREATE_THREAD_DEBUG_INFO.hThread  - handle to the thread that has been created
            //
            // This handle will be closed by the operating system
            // when the debugger calls ContinueDebugEvent after receiving
            // EXIT_THREAD_DEBUG_EVENT for the given thread
            break;

        case LOAD_DLL_DEBUG_EVENT:
        {
            std::string dll_name = GetDLLNameFromDebug(dbe.u.LoadDll);
            if(__WATCHER_PRINT_DEBUG)
            {
                printf("Event: DLL loaded\n");
                printf("  LOAD_DLL_DEBUG_INFO members:\n");
                printf("    hFile:                  %08p\n", dbe.u.LoadDll.hFile);
                printf("    lpBaseOfDll:            %08p\n", dbe.u.LoadDll.lpBaseOfDll);
                printf("    DLLName:                %s\n", dll_name.c_str());
            }

            // With this event, the debugger receives the following handle:
            //   LOAD_DLL_DEBUG_INFO.hFile    - handle to the DLL file
            //
            // This handle should be closed by the debugger, when the handle
            // is no longer needed
            SAFE_CLOSE_HANDLE(dbe.u.LoadDll.hFile);

            // And what's more
            // users are not allowed to load DLL
            if(dll_name.find("\\ntdll.dll") == std::string::npos &&
                    dll_name.find("\\kernel32.dll") == std::string::npos &&
                    dll_name.find("\\KernelBase.dll") == std::string::npos &&
                    dll_name.find("\\msvcrt.dll") == std::string::npos &&
                    dll_name.find("\\wow64.dll") == std::string::npos &&
                    dll_name.find("\\wow64win.dll") == std::string::npos &&
                    dll_name.find("\\wow64cpu.dll") == std::string::npos &&
                    dll_name.find("\\user32.dll") == std::string::npos)
            {
                std::string error = "Code is up to load DLL.";
                code_state.exe_time = 0;
                code_state.exe_memory = 0;
                ExitAndSetError(process, code_state, DANGEROUS_CODE, error.c_str());
                return false;
            }
        }

        default: break;
        }

        // get the run time
        run_time = GetRunTime_(process);
        if(-1 == run_time)
        {
            std::string error = "Cannot get running time: " + GetLastErrorAsString();
            code_state.exe_time = 0;
            code_state.exe_memory = MAX(GetRunMemo_(process), code_state.exe_memory);
            ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
            ExitAndSetError(process, code_state, SYSTEM_ERROR, error.c_str());
            return false;
        }

        // get the run memory
        run_memo = GetRunMemo_(process);
        if(-1 == run_memo)
        {
            std::string error = "Cannot get occupied memory: " + GetLastErrorAsString();
            code_state.exe_time = run_time;
            code_state.exe_memory = 0;
            ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
            ExitAndSetError(process, code_state, SYSTEM_ERROR, error.c_str());
            return false;
        }

        code_state.exe_time = run_time;
        code_state.exe_memory = MAX(code_state.exe_memory, run_memo);

        if(run_time > time_limit)
        {
            ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
            ExitAndSetError(process, code_state, TIME_LIMIT_EXCEEDED_1);
            return false;
        }

        if(run_memo > memo_limit)
        {
            ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
            ExitAndSetError(process, code_state, MEMORY_LIMIT_EXCEEDED);
            return false;
        }

        // do some reaction via each DEBUG_EVENT
        switch(dbe.dwDebugEventCode)
        {
        case EXIT_PROCESS_DEBUG_EVENT:
            code_state.state = FINISHED;
            ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
            return true;

        case EXCEPTION_DEBUG_EVENT:
            if(dbe.u.Exception.ExceptionRecord.ExceptionCode != EXCEPTION_BREAKPOINT &&
                    dbe.u.Exception.ExceptionRecord.ExceptionCode != EXCEPTION_WX86_BREAKPOINT)
            {
                SetRuntimeErrorCode_(code_state, dbe.u.Exception.ExceptionRecord.ExceptionCode);
                ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_EXCEPTION_NOT_HANDLED);
                ExitAndSetError(process, code_state, RUNTIME_ERROR);
                return false;
            }
            break;

        default: break;
        }

        ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
        code_state.state = CONTINUE;
    }
}

};<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011, Ben Noordhuis <info@bnoordhuis.nl>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <stdlib.h>
#include "v8.h"
#include "node.h"

using namespace v8;
using namespace node;

namespace {

typedef struct proxy_container {
  Persistent<Object> target;
  Persistent<Object> proxy;
  Persistent<Array>  callbacks;
} proxy_container;

Persistent<ObjectTemplate> proxyClass;

bool IsDead(Handle<Object> proxy) {
  assert(proxy->InternalFieldCount() == 1);
  proxy_container *cont = reinterpret_cast<proxy_container*>(
      proxy->GetPointerFromInternalField(0));
  assert(cont != NULL);
  return cont->target.IsEmpty();
}

Handle<Object> Unwrap(Handle<Object> proxy) {
  assert(!IsDead(proxy));
  proxy_container *cont = reinterpret_cast<proxy_container*>(
      proxy->GetPointerFromInternalField(0));
  assert(cont != NULL);
  return cont->target;
}

Handle<Array> GetCallbacks(Handle<Object> proxy) {

  proxy_container *cont = reinterpret_cast<proxy_container*>(
      proxy->GetPointerFromInternalField(0));
  assert(cont != NULL);
  return cont->callbacks;
}

#define UNWRAP                            \
  HandleScope scope;                      \
  Handle<Object> obj;                     \
  const bool dead = IsDead(info.This());  \
  if (!dead) obj = Unwrap(info.This());   \

Handle<Value> WeakNamedPropertyGetter(Local<String> property,
                                      const AccessorInfo& info) {
  UNWRAP
  return dead ? Local<Value>() : obj->Get(property);
}

Handle<Value> WeakNamedPropertySetter(Local<String> property,
                                      Local<Value> value,
                                      const AccessorInfo& info) {
  UNWRAP
  if (!dead) obj->Set(property, value);
  return value;
}

Handle<Integer> WeakNamedPropertyQuery(Local<String> property,
                                       const AccessorInfo& info) {
  return HandleScope().Close(Integer::New(None));
}

Handle<Boolean> WeakNamedPropertyDeleter(Local<String> property,
                                         const AccessorInfo& info) {
  UNWRAP
  return Boolean::New(!dead && obj->Delete(property));
}

Handle<Value> WeakIndexedPropertyGetter(uint32_t index,
                                        const AccessorInfo& info) {
  UNWRAP
  return dead ? Local<Value>() : obj->Get(index);
}

Handle<Value> WeakIndexedPropertySetter(uint32_t index,
                                        Local<Value> value,
                                        const AccessorInfo& info) {
  UNWRAP
  if (!dead) obj->Set(index, value);
  return value;
}

Handle<Integer> WeakIndexedPropertyQuery(uint32_t index,
                                         const AccessorInfo& info) {
  return HandleScope().Close(Integer::New(None));
}

Handle<Boolean> WeakIndexedPropertyDeleter(uint32_t index,
                                           const AccessorInfo& info) {
  UNWRAP
  return Boolean::New(!dead && obj->Delete(index));
}

Handle<Array> WeakPropertyEnumerator(const AccessorInfo& info) {
  UNWRAP
  return HandleScope().Close(dead ? Array::New(0) : obj->GetPropertyNames());
}

void AddCallback(Handle<Object> proxy, Handle<Function> callback) {
  Handle<Array> callbacks = GetCallbacks(proxy);
  callbacks->Set(Integer::New(callbacks->Length()), callback);
}

void TargetCallback(Persistent<Value> target, void* arg) {
  HandleScope scope;

  assert(target.IsNearDeath());

  proxy_container *cont = reinterpret_cast<proxy_container*>(arg);

  // invoke any listening callbacks
  uint32_t len = cont->callbacks->Length();
  Handle<Value> argv[1];
  argv[0] = target;
  for (uint32_t i=0; i<len; i++) {

    Handle<Function> cb = Handle<Function>::Cast(
        cont->callbacks->Get(Integer::New(i)));

    TryCatch try_catch;

    cb->Call(target->ToObject(), 1, argv);

    if (try_catch.HasCaught()) {
      FatalException(try_catch);
    }
  }

  if (target.IsNearDeath()) {
    cont->target.Dispose();
    cont->target.Clear();

    cont->proxy.Dispose();
    cont->proxy.Clear();
  }
}

void ProxyCallback(Persistent<Value> proxy, void* arg) {
  assert(proxy.IsNearDeath());

  proxy_container *cont = reinterpret_cast<proxy_container*>(arg);

  // Clear the Persistent handle to the "proxy" object, no longer needed.
  assert(!cont->proxy.IsEmpty());
  cont->proxy.Dispose();
  cont->proxy.Clear();
  assert(cont->proxy.IsEmpty());

  // If there are no callbacks, then clear the other handles as well
  if (cont->callbacks->Length() == 0) {
    cont->target.Dispose();
    cont->target.Clear();
    cont->callbacks.Dispose();
    cont->callbacks.Clear();
    assert(cont->proxy.IsEmpty());
    assert(cont->target.IsEmpty());
    assert(cont->callbacks.IsEmpty());
    free(cont);
  }
}

Handle<Value> Create(const Arguments& args) {
  HandleScope scope;

  if (!args[0]->IsObject()) {
    Local<String> message = String::New("Object expected");
    return ThrowException(Exception::TypeError(message));
  }

  proxy_container *cont = (proxy_container *)
    malloc(sizeof(proxy_container));

  cont->target = Persistent<Object>::New(args[0]->ToObject());
  cont->proxy  = Persistent<Object>::New(proxyClass->NewInstance());
  cont->callbacks = Persistent<Array>::New(Array::New());

  cont->proxy->SetPointerInInternalField(0, cont);

  cont->target.MakeWeak(cont, TargetCallback);
  cont->proxy.MakeWeak(cont, ProxyCallback);

  if (args.Length() >= 2) {
    AddCallback(cont->proxy, Handle<Function>::Cast(args[1]));
  }

  return cont->proxy;
}

Handle<Value> Get(const Arguments& args) {
  HandleScope scope;

  if (!args[0]->IsObject()
         || args[0]->ToObject()->InternalFieldCount() != 1) {
    Local<String> message = String::New("Weakref instance expected");
    return ThrowException(Exception::TypeError(message));
  }
  Local<Object> proxy = args[0]->ToObject();
  assert(proxy->InternalFieldCount() == 1);

  const bool dead = IsDead(proxy);
  if (dead) return Undefined();

  Handle<Object> obj = Unwrap(proxy);
  return scope.Close(obj);
}

Handle<Value> IsDead(const Arguments& args) {
  HandleScope scope;

  if (!args[0]->IsObject()
         || args[0]->ToObject()->InternalFieldCount() != 1) {
    Local<String> message = String::New("Weakref instance expected");
    return ThrowException(Exception::TypeError(message));
  }
  Local<Object> proxy = args[0]->ToObject();
  assert(proxy->InternalFieldCount() == 1);

  const bool dead = IsDead(proxy);
  return Boolean::New(dead);
}

Handle<Value> AddCallback(const Arguments& args) {
  HandleScope scope;
  if (!args[0]->IsObject()
         || args[0]->ToObject()->InternalFieldCount() != 1) {
    Local<String> message = String::New("Weakref instance expected");
    return ThrowException(Exception::TypeError(message));
  }
  Local<Object> proxy = args[0]->ToObject();
  assert(proxy->InternalFieldCount() == 1);

  AddCallback(proxy, Handle<Function>::Cast(args[1]));

  return Undefined();
}

Handle<Value> Callbacks(const Arguments& args) {
  HandleScope scope;
  if (!args[0]->IsObject()
         || args[0]->ToObject()->InternalFieldCount() != 1) {
    Local<String> message = String::New("Weakref instance expected");
    return ThrowException(Exception::TypeError(message));
  }
  Local<Object> proxy = args[0]->ToObject();
  assert(proxy->InternalFieldCount() == 1);

  return scope.Close(GetCallbacks(proxy));
}

void Initialize(Handle<Object> target) {
  HandleScope scope;

  proxyClass = Persistent<ObjectTemplate>::New(ObjectTemplate::New());
  proxyClass->SetNamedPropertyHandler(WeakNamedPropertyGetter,
                                      WeakNamedPropertySetter,
                                      WeakNamedPropertyQuery,
                                      WeakNamedPropertyDeleter,
                                      WeakPropertyEnumerator);
  proxyClass->SetIndexedPropertyHandler(WeakIndexedPropertyGetter,
                                        WeakIndexedPropertySetter,
                                        WeakIndexedPropertyQuery,
                                        WeakIndexedPropertyDeleter,
                                        WeakPropertyEnumerator);
  proxyClass->SetInternalFieldCount(1);

  NODE_SET_METHOD(target, "get", Get);
  NODE_SET_METHOD(target, "create", Create);
  NODE_SET_METHOD(target, "isDead", IsDead);
  NODE_SET_METHOD(target, "callbacks", Callbacks);
  NODE_SET_METHOD(target, "addCallback", AddCallback);

}

} // anonymous namespace

NODE_MODULE(weakref, Initialize);
<commit_msg>Properly free the underlying struct.<commit_after>/*
 * Copyright (c) 2011, Ben Noordhuis <info@bnoordhuis.nl>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <stdlib.h>
#include "v8.h"
#include "node.h"

using namespace v8;
using namespace node;

namespace {

typedef struct proxy_container {
  Persistent<Object> target;
  Persistent<Array>  callbacks;
} proxy_container;

Persistent<ObjectTemplate> proxyClass;

bool IsDead(Handle<Object> proxy) {
  assert(proxy->InternalFieldCount() == 1);
  proxy_container *cont = reinterpret_cast<proxy_container*>(
      proxy->GetPointerFromInternalField(0));
  assert(cont != NULL);
  return cont->target.IsEmpty();
}

Handle<Object> Unwrap(Handle<Object> proxy) {
  assert(!IsDead(proxy));
  proxy_container *cont = reinterpret_cast<proxy_container*>(
      proxy->GetPointerFromInternalField(0));
  assert(cont != NULL);
  return cont->target;
}

Handle<Array> GetCallbacks(Handle<Object> proxy) {
  proxy_container *cont = reinterpret_cast<proxy_container*>(
      proxy->GetPointerFromInternalField(0));
  assert(cont != NULL);
  return cont->callbacks;
}

#define UNWRAP                            \
  HandleScope scope;                      \
  Handle<Object> obj;                     \
  const bool dead = IsDead(info.This());  \
  if (!dead) obj = Unwrap(info.This());   \

Handle<Value> WeakNamedPropertyGetter(Local<String> property,
                                      const AccessorInfo& info) {
  UNWRAP
  return dead ? Local<Value>() : obj->Get(property);
}

Handle<Value> WeakNamedPropertySetter(Local<String> property,
                                      Local<Value> value,
                                      const AccessorInfo& info) {
  UNWRAP
  if (!dead) obj->Set(property, value);
  return value;
}

Handle<Integer> WeakNamedPropertyQuery(Local<String> property,
                                       const AccessorInfo& info) {
  return HandleScope().Close(Integer::New(None));
}

Handle<Boolean> WeakNamedPropertyDeleter(Local<String> property,
                                         const AccessorInfo& info) {
  UNWRAP
  return Boolean::New(!dead && obj->Delete(property));
}

Handle<Value> WeakIndexedPropertyGetter(uint32_t index,
                                        const AccessorInfo& info) {
  UNWRAP
  return dead ? Local<Value>() : obj->Get(index);
}

Handle<Value> WeakIndexedPropertySetter(uint32_t index,
                                        Local<Value> value,
                                        const AccessorInfo& info) {
  UNWRAP
  if (!dead) obj->Set(index, value);
  return value;
}

Handle<Integer> WeakIndexedPropertyQuery(uint32_t index,
                                         const AccessorInfo& info) {
  return HandleScope().Close(Integer::New(None));
}

Handle<Boolean> WeakIndexedPropertyDeleter(uint32_t index,
                                           const AccessorInfo& info) {
  UNWRAP
  return Boolean::New(!dead && obj->Delete(index));
}

Handle<Array> WeakPropertyEnumerator(const AccessorInfo& info) {
  UNWRAP
  return HandleScope().Close(dead ? Array::New(0) : obj->GetPropertyNames());
}

void AddCallback(Handle<Object> proxy, Handle<Function> callback) {
  Handle<Array> callbacks = GetCallbacks(proxy);
  callbacks->Set(Integer::New(callbacks->Length()), callback);
}

void TargetCallback(Persistent<Value> target, void* arg) {
  HandleScope scope;

  assert(target.IsNearDeath());

  proxy_container *cont = reinterpret_cast<proxy_container*>(arg);

  // invoke any listening callbacks
  uint32_t len = cont->callbacks->Length();
  Handle<Value> argv[1];
  argv[0] = target;
  for (uint32_t i=0; i<len; i++) {

    Handle<Function> cb = Handle<Function>::Cast(
        cont->callbacks->Get(Integer::New(i)));

    TryCatch try_catch;

    cb->Call(target->ToObject(), 1, argv);

    if (try_catch.HasCaught()) {
      FatalException(try_catch);
    }
  }

  if (target.IsNearDeath()) {
    cont->target.Dispose();
    cont->target.Clear();
    free(cont);
  }
}

Handle<Value> Create(const Arguments& args) {
  HandleScope scope;

  if (!args[0]->IsObject()) {
    Local<String> message = String::New("Object expected");
    return ThrowException(Exception::TypeError(message));
  }

  proxy_container *cont = (proxy_container *)
    malloc(sizeof(proxy_container));

  cont->target = Persistent<Object>::New(args[0]->ToObject());
  cont->callbacks = Persistent<Array>::New(Array::New());

  Local<Object> proxy  = proxyClass->NewInstance();
  proxy->SetPointerInInternalField(0, cont);

  cont->target.MakeWeak(cont, TargetCallback);

  if (args.Length() >= 2) {
    AddCallback(proxy, Handle<Function>::Cast(args[1]));
  }

  return proxy;
}

Handle<Value> Get(const Arguments& args) {
  HandleScope scope;

  if (!args[0]->IsObject()
         || args[0]->ToObject()->InternalFieldCount() != 1) {
    Local<String> message = String::New("Weakref instance expected");
    return ThrowException(Exception::TypeError(message));
  }
  Local<Object> proxy = args[0]->ToObject();
  assert(proxy->InternalFieldCount() == 1);

  const bool dead = IsDead(proxy);
  if (dead) return Undefined();

  Handle<Object> obj = Unwrap(proxy);
  return scope.Close(obj);
}

Handle<Value> IsDead(const Arguments& args) {
  HandleScope scope;

  if (!args[0]->IsObject()
         || args[0]->ToObject()->InternalFieldCount() != 1) {
    Local<String> message = String::New("Weakref instance expected");
    return ThrowException(Exception::TypeError(message));
  }
  Local<Object> proxy = args[0]->ToObject();
  assert(proxy->InternalFieldCount() == 1);

  const bool dead = IsDead(proxy);
  return Boolean::New(dead);
}

Handle<Value> AddCallback(const Arguments& args) {
  HandleScope scope;
  if (!args[0]->IsObject()
         || args[0]->ToObject()->InternalFieldCount() != 1) {
    Local<String> message = String::New("Weakref instance expected");
    return ThrowException(Exception::TypeError(message));
  }
  Local<Object> proxy = args[0]->ToObject();
  assert(proxy->InternalFieldCount() == 1);

  AddCallback(proxy, Handle<Function>::Cast(args[1]));

  return Undefined();
}

Handle<Value> Callbacks(const Arguments& args) {
  HandleScope scope;
  if (!args[0]->IsObject()
         || args[0]->ToObject()->InternalFieldCount() != 1) {
    Local<String> message = String::New("Weakref instance expected");
    return ThrowException(Exception::TypeError(message));
  }
  Local<Object> proxy = args[0]->ToObject();
  assert(proxy->InternalFieldCount() == 1);

  return scope.Close(GetCallbacks(proxy));
}

void Initialize(Handle<Object> target) {
  HandleScope scope;

  proxyClass = Persistent<ObjectTemplate>::New(ObjectTemplate::New());
  proxyClass->SetNamedPropertyHandler(WeakNamedPropertyGetter,
                                      WeakNamedPropertySetter,
                                      WeakNamedPropertyQuery,
                                      WeakNamedPropertyDeleter,
                                      WeakPropertyEnumerator);
  proxyClass->SetIndexedPropertyHandler(WeakIndexedPropertyGetter,
                                        WeakIndexedPropertySetter,
                                        WeakIndexedPropertyQuery,
                                        WeakIndexedPropertyDeleter,
                                        WeakPropertyEnumerator);
  proxyClass->SetInternalFieldCount(1);

  NODE_SET_METHOD(target, "get", Get);
  NODE_SET_METHOD(target, "create", Create);
  NODE_SET_METHOD(target, "isDead", IsDead);
  NODE_SET_METHOD(target, "callbacks", Callbacks);
  NODE_SET_METHOD(target, "addCallback", AddCallback);

}

} // anonymous namespace

NODE_MODULE(weakref, Initialize);
<|endoftext|>


<commit_before>#include "MainLogic.h"

#include "MotorDriver.h"
#include "DualEncoderDriver.h"
#include "FrontLiftedDetection.h"
#include "ProximitySensors.h"

#include <cmath>

#define STANDARD_SPEED				       170
#define SPEED_CHANGE_STEP			       1
#define DISTANCE_BETWEEN_MOTORS		       85.00
#define HALF_DISTANCE_BETWEEN_MOTORS       (DISTANCE_BETWEEN_MOTORS / 2.00)

#define SAMPLE_FREQUENCY        250

enum {
	SEARCH_INITIAL,
	SEARCH_TURNING,
	SEARCH_FORWARD,

	FOUND_LEFT,
	FOUND_RIGHT,
	FOUND_STRAIGHT,

	STOP_MOVING
} STATE = SEARCH_INITIAL;

enum {
	MOVEMENT_SYSTEM_STATUS_OFF,
	MOVEMENT_SYSTEM_STATUS_LINEAR_MOVEMENT,
	MOVEMENT_SYSTEM_STATUS_ROUND_MOVEMENT
} movementSystemStatus = MOVEMENT_SYSTEM_STATUS_OFF;

static float distanceExpectedByLeftTire, distanceExpectedByRightTire;

static int16_t leftMotorSpeed, rightMotorSpeed, leftMotorDir, rightMotorDir;
static int8_t directionOfLinearMovement;
static float circleMotorSpeedDifference;

void HandleControlledMovement(float leftTyreSpeed, float rightTyreSpeed)
{
	switch(movementSystemStatus)
	{
		case MOVEMENT_SYSTEM_STATUS_OFF:
			// stop the motors, they should not be moving
			setMotors(0, 0);
			break;

		case MOVEMENT_SYSTEM_STATUS_LINEAR_MOVEMENT:
		{
			// check if the speeds are the same if not correct the speed of the slower motors
			if(leftTyreSpeed > rightTyreSpeed)
			{
				leftMotorSpeed -= SPEED_CHANGE_STEP;
			}
			else if(leftTyreSpeed < rightTyreSpeed)
			{
				leftMotorSpeed += SPEED_CHANGE_STEP;
			}

			// update moved distance
			distanceExpectedByLeftTire -= (float)(leftTyreSpeed / SAMPLE_FREQUENCY);
			distanceExpectedByRightTire -= (float)(rightTyreSpeed / SAMPLE_FREQUENCY);

			if(	(distanceExpectedByLeftTire < 0 && directionOfLinearMovement > 0) ||
				(distanceExpectedByLeftTire > 0 && directionOfLinearMovement < 0) )
			{
				leftMotorSpeed = 0;
			}

			if(	(distanceExpectedByRightTire < 0 && directionOfLinearMovement > 0) ||
				(distanceExpectedByRightTire > 0 && directionOfLinearMovement < 0) )
			{
				rightMotorSpeed = 0;
			}

			if(leftMotorSpeed == 0 && rightMotorSpeed == 0)
			{
				movementSystemStatus = MOVEMENT_SYSTEM_STATUS_OFF;
			}

			setMotors(leftMotorSpeed, rightMotorSpeed);

			break;
		}

		case MOVEMENT_SYSTEM_STATUS_ROUND_MOVEMENT:
		{
			// check if the speeds are the same if not correct the speed of the slower motors
			if(leftTyreSpeed / rightTyreSpeed > circleMotorSpeedDifference)
			{
				leftMotorSpeed -= SPEED_CHANGE_STEP;
				rightMotorSpeed += SPEED_CHANGE_STEP;
			}
			else if(leftTyreSpeed / rightTyreSpeed < circleMotorSpeedDifference)
			{
				leftMotorSpeed += SPEED_CHANGE_STEP;
				rightMotorSpeed -= SPEED_CHANGE_STEP;
			}

			// update moved distance
			distanceExpectedByLeftTire -= leftTyreSpeed / SAMPLE_FREQUENCY;
			distanceExpectedByRightTire -= rightTyreSpeed / SAMPLE_FREQUENCY;

			if(	(distanceExpectedByLeftTire < 0 && leftMotorDir > 0) ||
				(distanceExpectedByLeftTire > 0 && leftMotorDir < 0) )
			{
				leftMotorSpeed = 0;
			}

			if(	(distanceExpectedByRightTire < 0 && rightMotorDir > 0) ||
				(distanceExpectedByRightTire > 0 && rightMotorDir < 0) )
			{
				rightMotorSpeed = 0;
			}

			if(leftMotorSpeed == 0 && rightMotorSpeed == 0)
			{
				movementSystemStatus = MOVEMENT_SYSTEM_STATUS_OFF;
			}

			setMotors(leftMotorSpeed, rightMotorSpeed);

			break;
		}
	}
}

inline bool IsMovementComplete()
{
	return movementSystemStatus == MOVEMENT_SYSTEM_STATUS_OFF;
}

void LinearMovement(int32_t distanceInMMWithDirection) // TODO: Fix backwards
{
	// evaluate direction and pass to drivers the start state
	if(0 < distanceInMMWithDirection)
	{
		directionOfLinearMovement = 1;
		setMotors(STANDARD_SPEED, STANDARD_SPEED);
	}
	else
	{
		directionOfLinearMovement = -1;
		setMotors(-STANDARD_SPEED, -STANDARD_SPEED);
	}

	// set setpoints for end of movement, used in handler
	distanceExpectedByRightTire = (float)distanceInMMWithDirection;
	distanceExpectedByLeftTire = (float)distanceInMMWithDirection;

	// set motor speeds, used in handler
	rightMotorSpeed = STANDARD_SPEED;
	leftMotorSpeed = STANDARD_SPEED;

	// set state on state machine
	movementSystemStatus = MOVEMENT_SYSTEM_STATUS_LINEAR_MOVEMENT;
}

void Turn(int turnRadius, int turnDegrees)
{
	if(turnDegrees == 0) return;

	distanceExpectedByLeftTire  = 2.00 * ((float)turnRadius + HALF_DISTANCE_BETWEEN_MOTORS) * M_PI * (float)turnDegrees / 360;
	distanceExpectedByRightTire = 2.00 * ((float)turnRadius - HALF_DISTANCE_BETWEEN_MOTORS) * M_PI * (float)turnDegrees / 360;
	if(turnDegrees < 0)
	{
		auto temp = -distanceExpectedByLeftTire;
		distanceExpectedByLeftTire = -distanceExpectedByRightTire;
		distanceExpectedByRightTire = temp;
	}

	circleMotorSpeedDifference = distanceExpectedByLeftTire / distanceExpectedByRightTire;

	leftMotorDir = (turnDegrees > 0 || distanceExpectedByLeftTire > 0) ? 1 : -1;
	rightMotorDir = (turnDegrees < 0 || distanceExpectedByRightTire > 0) ? 1 : -1;

	leftMotorSpeed = STANDARD_SPEED * leftMotorDir;
	rightMotorSpeed = STANDARD_SPEED * rightMotorDir;

	if(turnDegrees > 0) leftMotorSpeed *= STANDARD_SPEED;
	else rightMotorSpeed *= STANDARD_SPEED;

	setMotors(leftMotorSpeed, rightMotorSpeed);

	// set state on state machine
	movementSystemStatus = MOVEMENT_SYSTEM_STATUS_ROUND_MOVEMENT;
}

void MovePattern()
{
	switch(STATE)
	{
		case SEARCH_INITIAL:
			if(IsMovementComplete())
			{
				Turn(0, -90);
				STATE = SEARCH_TURNING;
			}
			break;

		case SEARCH_TURNING:
			if(IsMovementComplete())
			{
				LinearMovement(200);
				STATE = SEARCH_FORWARD;
			}
			break;

		case SEARCH_FORWARD:
			if(IsMovementComplete())
			{
				Turn(50, 270);
				STATE = SEARCH_TURNING;
			}
			break;

		case FOUND_LEFT:
			Turn(0, -90);
			STATE = FOUND_STRAIGHT;
			break;

		case FOUND_RIGHT:
			Turn(0, 90);
			STATE = FOUND_STRAIGHT;
			break;

		case FOUND_STRAIGHT:
			if(IsMovementComplete())
			{
				LinearMovement(1000);
				STATE = FOUND_STRAIGHT;
			}
			break;

		default:
			if(IsMovementComplete())
			{
				setMotors(0, 0);
			}
			break;
	}
}

/*
void RoundPattern()
{
	switch(STATE)
	{
		case INITIAL_STATE:
			{
				Turn(200,360);
				STATE = STATE_TURNING;
			}
			break;

		case STATE_TURNING:
			if(IsMovementComplete())
			{
				// keep turning
				Turn(200,360);
			}
			break;

		default:
			setMotors(0, 0);
			break;
	}
	// if( digitalRead(LEFT_SENSOR_PIN) ^ 1 == 1 || digitalRead(RIGHT_SENSOR_PIN) ^ 1 == 1)
	// {
	// 	STATE = EXIT_STATE_ON_SIDE;
	// }

	// if(OutOfRing())
	// {
	// 	STATE = EXIT_STATE_OUT_OF_RING;
	// }

	// if(Impact())
	// {
	// 	STATE = EXIT_STATE_ON_IMPACT;
	// }
}
*/

void MainLogic(float left_speed, float right_speed)
{
	uint8_t left, right;
	readProximitySensors(left, right);

	if(left) STATE = FOUND_LEFT;
	else if(right) STATE = FOUND_RIGHT;

	MovePattern();
	HandleControlledMovement(left_speed, right_speed);
}
<commit_msg>Typo fixes<commit_after>#include "MainLogic.h"

#include "MotorDriver.h"
#include "DualEncoderDriver.h"
#include "FrontLiftedDetection.h"
#include "ProximitySensors.h"

#include <cmath>

#define STANDARD_SPEED				       170
#define SPEED_CHANGE_STEP			       1
#define DISTANCE_BETWEEN_MOTORS		       85.00
#define HALF_DISTANCE_BETWEEN_MOTORS       (DISTANCE_BETWEEN_MOTORS / 2.00)

#define SAMPLE_FREQUENCY        250

enum {
	SEARCH_INITIAL,
	SEARCH_TURNING,
	SEARCH_FORWARD,

	FOUND_LEFT,
	FOUND_RIGHT,
	FOUND_STRAIGHT,

	STOP_MOVING
} STATE = SEARCH_INITIAL;

enum {
	MOVEMENT_SYSTEM_STATUS_OFF,
	MOVEMENT_SYSTEM_STATUS_LINEAR_MOVEMENT,
	MOVEMENT_SYSTEM_STATUS_ROUND_MOVEMENT
} movementSystemStatus = MOVEMENT_SYSTEM_STATUS_OFF;

static float distanceExpectedByLeftTire, distanceExpectedByRightTire;

static int16_t leftMotorSpeed, rightMotorSpeed, leftMotorDir, rightMotorDir;
static int8_t directionOfLinearMovement;
static float circleMotorSpeedDifference;

void HandleControlledMovement(float leftTireSpeed, float rightTireSpeed)
{
	switch(movementSystemStatus)
	{
		case MOVEMENT_SYSTEM_STATUS_OFF:
			// stop the motors, they should not be moving
			setMotors(0, 0);
			break;

		case MOVEMENT_SYSTEM_STATUS_LINEAR_MOVEMENT:
		{
			// check if the speeds are the same if not correct the speed of the slower motors
			if(leftTireSpeed > rightTireSpeed)
			{
				leftMotorSpeed -= SPEED_CHANGE_STEP;
			}
			else if(leftTireSpeed < rightTireSpeed)
			{
				leftMotorSpeed += SPEED_CHANGE_STEP;
			}

			// update moved distance
			distanceExpectedByLeftTire -= (float)(leftTireSpeed / SAMPLE_FREQUENCY);
			distanceExpectedByRightTire -= (float)(rightTireSpeed / SAMPLE_FREQUENCY);

			if(	(distanceExpectedByLeftTire < 0 && directionOfLinearMovement > 0) ||
				(distanceExpectedByLeftTire > 0 && directionOfLinearMovement < 0) )
			{
				leftMotorSpeed = 0;
			}

			if(	(distanceExpectedByRightTire < 0 && directionOfLinearMovement > 0) ||
				(distanceExpectedByRightTire > 0 && directionOfLinearMovement < 0) )
			{
				rightMotorSpeed = 0;
			}

			if(leftMotorSpeed == 0 && rightMotorSpeed == 0)
			{
				movementSystemStatus = MOVEMENT_SYSTEM_STATUS_OFF;
			}

			setMotors(leftMotorSpeed, rightMotorSpeed);

			break;
		}

		case MOVEMENT_SYSTEM_STATUS_ROUND_MOVEMENT:
		{
			// check if the speeds are the same if not correct the speed of the slower motors
			if(leftTireSpeed / rightTireSpeed > circleMotorSpeedDifference)
			{
				leftMotorSpeed -= SPEED_CHANGE_STEP;
				rightMotorSpeed += SPEED_CHANGE_STEP;
			}
			else if(leftTireSpeed / rightTireSpeed < circleMotorSpeedDifference)
			{
				leftMotorSpeed += SPEED_CHANGE_STEP;
				rightMotorSpeed -= SPEED_CHANGE_STEP;
			}

			// update moved distance
			distanceExpectedByLeftTire -= leftTireSpeed / SAMPLE_FREQUENCY;
			distanceExpectedByRightTire -= rightTireSpeed / SAMPLE_FREQUENCY;

			if(	(distanceExpectedByLeftTire < 0 && leftMotorDir > 0) ||
				(distanceExpectedByLeftTire > 0 && leftMotorDir < 0) )
			{
				leftMotorSpeed = 0;
			}

			if(	(distanceExpectedByRightTire < 0 && rightMotorDir > 0) ||
				(distanceExpectedByRightTire > 0 && rightMotorDir < 0) )
			{
				rightMotorSpeed = 0;
			}

			if(leftMotorSpeed == 0 && rightMotorSpeed == 0)
			{
				movementSystemStatus = MOVEMENT_SYSTEM_STATUS_OFF;
			}

			setMotors(leftMotorSpeed, rightMotorSpeed);

			break;
		}
	}
}

inline bool IsMovementComplete()
{
	return movementSystemStatus == MOVEMENT_SYSTEM_STATUS_OFF;
}

void LinearMovement(int32_t distanceInMMWithDirection) // TODO: Fix backwards
{
	// evaluate direction and pass to drivers the start state
	if(0 < distanceInMMWithDirection)
	{
		directionOfLinearMovement = 1;
		setMotors(STANDARD_SPEED, STANDARD_SPEED);
	}
	else
	{
		directionOfLinearMovement = -1;
		setMotors(-STANDARD_SPEED, -STANDARD_SPEED);
	}

	// set setpoints for end of movement, used in handler
	distanceExpectedByRightTire = (float)distanceInMMWithDirection;
	distanceExpectedByLeftTire = (float)distanceInMMWithDirection;

	// set motor speeds, used in handler
	rightMotorSpeed = STANDARD_SPEED;
	leftMotorSpeed = STANDARD_SPEED;

	// set state on state machine
	movementSystemStatus = MOVEMENT_SYSTEM_STATUS_LINEAR_MOVEMENT;
}

void Turn(int turnRadius, int turnDegrees)
{
	if(turnDegrees == 0) return;

	distanceExpectedByLeftTire  = 2.00 * ((float)turnRadius + HALF_DISTANCE_BETWEEN_MOTORS) * M_PI * (float)turnDegrees / 360;
	distanceExpectedByRightTire = 2.00 * ((float)turnRadius - HALF_DISTANCE_BETWEEN_MOTORS) * M_PI * (float)turnDegrees / 360;
	if(turnDegrees < 0)
	{
		auto temp = -distanceExpectedByLeftTire;
		distanceExpectedByLeftTire = -distanceExpectedByRightTire;
		distanceExpectedByRightTire = temp;
	}

	circleMotorSpeedDifference = distanceExpectedByLeftTire / distanceExpectedByRightTire;

	leftMotorDir = (turnDegrees > 0 || distanceExpectedByLeftTire > 0) ? 1 : -1;
	rightMotorDir = (turnDegrees < 0 || distanceExpectedByRightTire > 0) ? 1 : -1;

	leftMotorSpeed = STANDARD_SPEED * leftMotorDir;
	rightMotorSpeed = STANDARD_SPEED * rightMotorDir;

	if(turnDegrees > 0) leftMotorSpeed *= STANDARD_SPEED;
	else rightMotorSpeed *= STANDARD_SPEED;

	setMotors(leftMotorSpeed, rightMotorSpeed);

	// set state on state machine
	movementSystemStatus = MOVEMENT_SYSTEM_STATUS_ROUND_MOVEMENT;
}

void MovePattern()
{
	switch(STATE)
	{
		case SEARCH_INITIAL:
			if(IsMovementComplete())
			{
				Turn(0, -90);
				STATE = SEARCH_TURNING;
			}
			break;

		case SEARCH_TURNING:
			if(IsMovementComplete())
			{
				LinearMovement(200);
				STATE = SEARCH_FORWARD;
			}
			break;

		case SEARCH_FORWARD:
			if(IsMovementComplete())
			{
				Turn(50, 270);
				STATE = SEARCH_TURNING;
			}
			break;

		case FOUND_LEFT:
			Turn(0, -90);
			STATE = FOUND_STRAIGHT;
			break;

		case FOUND_RIGHT:
			Turn(0, 90);
			STATE = FOUND_STRAIGHT;
			break;

		case FOUND_STRAIGHT:
			if(IsMovementComplete())
			{
				LinearMovement(1000);
				STATE = FOUND_STRAIGHT;
			}
			break;

		default:
			if(IsMovementComplete())
			{
				setMotors(0, 0);
			}
			break;
	}
}

/*
void RoundPattern()
{
	switch(STATE)
	{
		case INITIAL_STATE:
			{
				Turn(200,360);
				STATE = STATE_TURNING;
			}
			break;

		case STATE_TURNING:
			if(IsMovementComplete())
			{
				// keep turning
				Turn(200,360);
			}
			break;

		default:
			setMotors(0, 0);
			break;
	}
	// if( digitalRead(LEFT_SENSOR_PIN) ^ 1 == 1 || digitalRead(RIGHT_SENSOR_PIN) ^ 1 == 1)
	// {
	// 	STATE = EXIT_STATE_ON_SIDE;
	// }

	// if(OutOfRing())
	// {
	// 	STATE = EXIT_STATE_OUT_OF_RING;
	// }

	// if(Impact())
	// {
	// 	STATE = EXIT_STATE_ON_IMPACT;
	// }
}
*/

void MainLogic(float left_speed, float right_speed)
{
	uint8_t left, right;
	readProximitySensors(left, right);

	if(left) STATE = FOUND_LEFT;
	else if(right) STATE = FOUND_RIGHT;

	MovePattern();
	HandleControlledMovement(left_speed, right_speed);
}
<|endoftext|>


<commit_before>/* This file is part of the Palabos library.
 *
 * Copyright (C) 2011-2015 FlowKit Sarl
 * Route d'Oron 2
 * 1010 Lausanne, Switzerland
 * E-mail contact: contact@flowkit.com
 *
 * The most recent release of Palabos can be downloaded at
 * <http://www.palabos.org/>
 *
 * The library Palabos is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * The library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

/* Code 1.1 in the Palabos tutorial
 */

#include "palabos2D.h"
#ifndef PLB_PRECOMPILED // Unless precompiled version is used,
#include "palabos2D.hh"   // include full template code
#endif

#include <vector>
#include <cmath>
#include <iostream>
#include <fstream>
#include <iomanip>

using namespace plb;
using namespace std;

typedef double T;
#define DESCRIPTOR plb::descriptors::D2Q9Descriptor
#define PI 3.14159265

// ---------------------------------------------
// Includes of acoustics resources
#include "acoustics/acoustics2D.h"
using namespace plb_acoustics;
// ---------------------------------------------

T rho0 = 1.;
T deltaRho = 1.e-4;
T lattice_speed_sound = 1/sqrt(3);

int main(int argc, char* argv[]) {
    plbInit(&argc, &argv);
    global::directories().setOutputDir("./tmp/");

    plint numCores = global::mpi().getSize();
    pcout << "Number of MPI threads: " << numCores << std::endl;

    const plint maxIter = 10000; // 120000 Iterate during 1000 steps.
    const plint nx = 1000;       // Choice of lattice dimensions.
    const plint ny = 670;
    const T omega = 1.98;        // Choice of the relaxation parameter

    pcout << "Total iteration: " << maxIter << std::endl;
    MultiBlockLattice2D<T, DESCRIPTOR> lattice(nx, ny, new CompleteBGKdynamics<T,DESCRIPTOR>(omega));

    Array<T,2> u0((T)0,(T)0);

    // Initialize constant density everywhere.
    initializeAtEquilibrium(lattice, lattice.getBoundingBox(), rho0, u0);

    lattice.initialize();

    plint size_square = 2;
    Box2D square(nx/2 - size_square/2, nx/2 + size_square/2,
    ny/2 - size_square/2, ny/2 + size_square/2);
    defineDynamics(lattice, square, new BounceBack<T,DESCRIPTOR>(rho0));

    // Anechoic Condition
    T size_anechoic_buffer = 30;
    T rhoBar_target = 0;
    Array<T,2> j_target(0.11/std::sqrt(3), 0.0/std::sqrt(3));
    //left
    plint orientation = 3;
    Array<T,2> position_anechoic_wall((T)0,(T)0);
    plint length_anechoic_wall = ny + 1;
    defineAnechoicWall(nx, ny, lattice, size_anechoic_buffer, orientation,
    omega, position_anechoic_wall, length_anechoic_wall,
    rhoBar_target, j_target);

    //right
    orientation = 1;
    Array<T,2> position_anechoic_wall_2((T)nx - 30,(T)0);
    length_anechoic_wall = ny + 1;
    defineAnechoicWall(nx, ny, lattice, size_anechoic_buffer, orientation,
    omega, position_anechoic_wall_2, length_anechoic_wall,
    rhoBar_target, j_target);

    //top
    orientation = 4;
    Array<T,2> position_anechoic_wall_3((T) 0, (T)ny - 30);
    length_anechoic_wall = nx + 1;
    defineAnechoicWall(nx, ny, lattice, size_anechoic_buffer, orientation,
    omega, position_anechoic_wall_3, length_anechoic_wall,
    rhoBar_target, u0);

    //bottom
    orientation = 2;
    Array<T,2> position_anechoic_wall_1((T)0,(T)0);
    length_anechoic_wall = nx + 1;
    defineAnechoicWall(nx, ny, lattice, size_anechoic_buffer, orientation,
    omega, position_anechoic_wall_1, length_anechoic_wall,
    rhoBar_target, u0);

    Box2D cima(0, nx, ny - 1, ny);
    //defineDynamics(lattice, cima, new BounceBack<T,DESCRIPTOR>(rho0));
    Box2D baixo(0, nx, 0, 1);
    //defineDynamics(lattice, baixo, new BounceBack<T,DESCRIPTOR>(rho0));

    // Main loop over time iterations.
    plb_ofstream pressure_file("pressure_50000.dat");
    plb_ofstream velocities_file("velocities_50000.dat");
    for (plint iT=0; iT<maxIter; ++iT) {
        Box2D centralSquare (nx/2, nx/2, ny/2, ny/2);

        plb_ofstream pressures_space_file("pressures_space_file.dat");
        for (int i = 0; i < ny; i++){
            T pressure = lattice_speed_sound*lattice_speed_sound*(lattice.get(nx/2, i).computeDensity() - rho0);
            pressures_space_file << setprecision(10) << pressure << endl;
            pcout << i << " " << pressure << endl;
        }

        //T rho_changing = 1. + deltaRho*sin(2*PI*(lattice_speed_sound/200)*iT);
        if (iT != 0){
            //initializeAtEquilibrium (lattice, centralSquare, rho_changing, u0);
        }

        if (iT>=60000){
            T pressure = lattice_speed_sound*lattice_speed_sound*(lattice.get(680, 460).computeDensity() - rho0);
            pressure_file << setprecision(10) << pressure << endl;

             Array<T,2> u;
             lattice.get(300, ny/2).computeVelocity(u);
             velocities_file << setprecision(10) << u[0] << " " << u[1] << endl;

             if (iT%1000==0) {  // Write an image every 40th time step.
                pcout << "iT= " << iT << endl;
                ImageWriter<T> imageWriter("leeloo");
                imageWriter.writeScaledGif(createFileName("velocity", iT, 6),
                                   *computeVelocityNorm(lattice) );
                imageWriter.writeGif(createFileName("density", iT, 6),
                *computeDensity(lattice), (T) rho0 - deltaRho/1000, (T) rho0 + deltaRho/1000);

            }

        }

       if (iT%1000==0) {  // Write an image every 40th time step.
            pcout << "iT= " << iT << endl;
            ImageWriter<T> imageWriter("leeloo");
            imageWriter.writeScaledGif(createFileName("velocity", iT, 6),
                               *computeVelocityNorm(lattice) );
            imageWriter.writeGif(createFileName("density", iT, 6),
            *computeDensity(lattice), (T) rho0 - deltaRho/100, (T) rho0 + deltaRho/100);

            /*ImageWriter<T> imageWriter("leeloo");
            imageWriter.writeScaledGif(createFileName("u", iT, 6),
                               *computeVelocityNorm(lattice) );*/

           // imageWriter.writeScaledGif(createFileName("u", iT, 6), *computeVorticity(*computeVelocity(lattice)));
            //imageWriter.writeScaledGif(createFileName("u", iT, 6), *computeDensity(lattice));
           //imageWriter.writeGif(createFileName("u", iT, 6), *computeDensity(lattice), (T) rho0 - deltaRho/1000, (T) rho0 + deltaRho/1000);
             pcout << " energy ="
                  << setprecision(10) << getStoredAverageEnergy<T>(lattice)
                  << " rho ="
                  << getStoredAverageDensity<T>(lattice)
                  << " max_velocity ="
                  << setprecision(10) << getStoredMaxVelocity<T>(lattice)
                  << endl;
        }

        // Execute lattice Boltzmann iteration.
        lattice.collideAndStream();

    }

}
<commit_msg>Doing directivity<commit_after>/* This file is part of the Palabos library.
 *
 * Copyright (C) 2011-2015 FlowKit Sarl
 * Route d'Oron 2
 * 1010 Lausanne, Switzerland
 * E-mail contact: contact@flowkit.com
 *
 * The most recent release of Palabos can be downloaded at
 * <http://www.palabos.org/>
 *
 * The library Palabos is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * The library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

/* Code 1.1 in the Palabos tutorial
 */

#include "palabos2D.h"
#ifndef PLB_PRECOMPILED // Unless precompiled version is used,
#include "palabos2D.hh"   // include full template code
#endif

#include <vector>
#include <cmath>
#include <iostream>
#include <fstream>
#include <iomanip>

using namespace plb;
using namespace std;

typedef double T;
#define DESCRIPTOR plb::descriptors::D2Q9Descriptor
#define PI 3.14159265

// ---------------------------------------------
// Includes of acoustics resources
#include "acoustics/acoustics2D.h"
using namespace plb_acoustics;
// ---------------------------------------------

T rho0 = 1.;
T deltaRho = 1.e-4;
T lattice_speed_sound = 1/sqrt(3);

class polar
{
    public:
        float r,th;
        polar(){}
        polar(int a,int b)
        {
            r=a;
            th=b;
        }
        void show()
        {
            cout<<"In polar form:\nr="<<r<<" and theta="<<th;

        }
};
class rectangular
{
    public:
        float x,y;
        rectangular(){}
        rectangular(polar p)
        {
            x=p.r*cos(p.th);
            y=p.r*sin(p.th);
        }
        void show()
        {
            cout<<"\nIn Rectangular form:\nx="<<x<<"and y="<<y;

        }
};

int main(int argc, char* argv[]) {
    plbInit(&argc, &argv);
    global::directories().setOutputDir("./tmp/");

    plint numCores = global::mpi().getSize();
    pcout << "Number of MPI threads: " << numCores << std::endl;

    const plint maxIter = 40000; // 120000 Iterate during 1000 steps.
    const plint nx = 1000;       // Choice of lattice dimensions.
    const plint ny = 670;
    const T omega = 1.98;        // Choice of the relaxation parameter

    pcout << "Total iteration: " << maxIter << std::endl;
    MultiBlockLattice2D<T, DESCRIPTOR> lattice(nx, ny, new CompleteBGKdynamics<T,DESCRIPTOR>(omega));

    Array<T,2> u0((T)0,(T)0);

    // Initialize constant density everywhere.
    initializeAtEquilibrium(lattice, lattice.getBoundingBox(), rho0, u0);

    lattice.initialize();

    plint size_square = 2;
    Box2D square(nx/2 - size_square/2, nx/2 + size_square/2,
    ny/2 - size_square/2, ny/2 + size_square/2);
    defineDynamics(lattice, square, new BounceBack<T,DESCRIPTOR>(rho0));

    // Anechoic Condition
    T size_anechoic_buffer = 30;
    T rhoBar_target = 0;
    Array<T,2> j_target(0.12/std::sqrt(3), 0.0/std::sqrt(3));
    //left
    plint orientation = 3;
    Array<T,2> position_anechoic_wall((T)0,(T)0);
    plint length_anechoic_wall = ny + 1;
    defineAnechoicWall(nx, ny, lattice, size_anechoic_buffer, orientation,
    omega, position_anechoic_wall, length_anechoic_wall,
    rhoBar_target, j_target);

    //right
    orientation = 1;
    Array<T,2> position_anechoic_wall_2((T)nx - 30,(T)0);
    length_anechoic_wall = ny + 1;
    defineAnechoicWall(nx, ny, lattice, size_anechoic_buffer, orientation,
    omega, position_anechoic_wall_2, length_anechoic_wall,
    rhoBar_target, j_target);

    //top
    orientation = 4;
    Array<T,2> position_anechoic_wall_3((T) 0, (T)ny - 30);
    length_anechoic_wall = nx + 1;
    defineAnechoicWall(nx, ny, lattice, size_anechoic_buffer, orientation,
    omega, position_anechoic_wall_3, length_anechoic_wall,
    rhoBar_target, u0);

    //bottom
    orientation = 2;
    Array<T,2> position_anechoic_wall_1((T)0,(T)0);
    length_anechoic_wall = nx + 1;
    defineAnechoicWall(nx, ny, lattice, size_anechoic_buffer, orientation,
    omega, position_anechoic_wall_1, length_anechoic_wall,
    rhoBar_target, u0);

    Box2D cima(0, nx, ny - 1, ny);
    //defineDynamics(lattice, cima, new BounceBack<T,DESCRIPTOR>(rho0));
    Box2D baixo(0, nx, 0, 1);
    //defineDynamics(lattice, baixo, new BounceBack<T,DESCRIPTOR>(rho0));

    // Main loop over time iterations.
    plb_ofstream pressures_time_file("pressures_time.dat");
    plb_ofstream velocities_file("velocities_50000.dat");
    for (plint iT=0; iT<maxIter; ++iT) {
        Box2D centralSquare (nx/2, nx/2, ny/2, ny/2);

        //T rho_changing = 1. + deltaRho*sin(2*PI*(lattice_speed_sound/200)*iT);
        if (iT != 0){
            //initializeAtEquilibrium (lattice, centralSquare, rho_changing, u0);
        }

       if (iT%1000==0) {  // Write an image every 40th time step.
            pcout << "iT= " << iT << endl;

            if (iT>=0){
                ImageWriter<T> imageWriter("leeloo");
                imageWriter.writeScaledGif(createFileName("velocity", iT, 6),
                                   *computeVelocityNorm(lattice) );
                imageWriter.writeGif(createFileName("density", iT, 6),
                *computeDensity(lattice), (T) rho0 + -9e-06, (T) rho0 + 4e-05);

                // Capturing pressures over time
                T pressure = lattice_speed_sound*lattice_speed_sound*(lattice.get(nx/2, ny - 40).computeDensity() - rho0);
                pressures_time_file << setprecision(10) << pressure << endl;

                // Capturing pressures over space
                plb_ofstream pressures_space_file("pressures_space.dat");
                for (int i = 0; i < ny; i++){
                    T pressure = lattice_speed_sound*lattice_speed_sound*(lattice.get(nx/2, i).computeDensity() - rho0);
                    pressures_space_file << setprecision(10) << pressure << endl;
                }

                // Calculating directivity
                /*plb_ofstream directivity_file("directivity.dat");
                T theta;
                pcout << "Start to calculate directivity .... " << endl;
                for (T i = 0; i < 630; i++){
                    theta = i/100;
                    polar polar_obj(ny/2 - 40, theta);
                    rectangular rectangular_obj;
                    rectangular_obj = polar_obj;
                    plint position_x = nx/2 + (plint) rectangular_obj.x;
                    pcout << position_x << endl;
                    plint position_y = ny/2 + (plint) rectangular_obj.y;
                    pcout << position_y << endl;
                    T pressure = lattice_speed_sound*lattice_speed_sound*
                    (lattice.get(position_x, position_y).computeDensity() - rho0);
                    directivity_file << setprecision(10) << pressure << endl;
                }
                pcout << "Finish calculate directivity .... " << endl;*/
            }

            /*plb_ofstream matrix_pressure_file("matrix_pressure.dat");
            if (iT == 30000){
                matrix_pressure_file << setprecision(10) <<
            }*/

            /*ImageWriter<T> imageWriter("leeloo");
            imageWriter.writeScaledGif(createFileName("u", iT, 6),
                               *computeVelocityNorm(lattice) );*/

           // imageWriter.writeScaledGif(createFileName("u", iT, 6), *computeVorticity(*computeVelocity(lattice)));
            //imageWriter.writeScaledGif(createFileName("u", iT, 6), *computeDensity(lattice));
           //imageWriter.writeGif(createFileName("u", iT, 6), *computeDensity(lattice), (T) rho0 - deltaRho/1000, (T) rho0 + deltaRho/1000);
             pcout << " energy ="
                  << setprecision(10) << getStoredAverageEnergy<T>(lattice)
                  << " rho ="
                  << getStoredAverageDensity<T>(lattice)
                  << " max_velocity ="
                  << setprecision(10) << getStoredMaxVelocity<T>(lattice)
                  << endl;
        }

        // Execute lattice Boltzmann iteration.
        lattice.collideAndStream();

    }

}
<|endoftext|>