コード例 #1
0
//----------------------------------------------------------------------------
QFutureInterface<ctkCmdLineModuleResult> QFutureInterface<ctkCmdLineModuleResult>::canceledResult()
{
  return QFutureInterface(State(Started | Finished | Canceled));
}
コード例 #2
0
ファイル: Path.hpp プロジェクト: anibalanto/hyp
 State getDst() const { return State(); }
コード例 #3
0
ファイル: network_conn.cpp プロジェクト: wthnonck/tdtw
int CNetConnection::Update()
{
	int64 Now = time_get();

	if(State() == NET_CONNSTATE_OFFLINE || State() == NET_CONNSTATE_ERROR)
		return 0;
	
	// check for timeout
	if(State() != NET_CONNSTATE_OFFLINE &&
		State() != NET_CONNSTATE_CONNECT &&
		(Now-m_LastRecvTime) > time_freq()*10)
	{
		m_State = NET_CONNSTATE_ERROR;
		SetError("timeout");
	}

	// fix resends
	if(m_Buffer.First())
	{
		CNetChunkResend *pResend = m_Buffer.First();

		// check if we have some really old stuff laying around and abort if not acked
		if(Now-pResend->m_FirstSendTime > time_freq()*10)
		{
			m_State = NET_CONNSTATE_ERROR;
			SetError("too weak connection (not acked for 10 seconds)");
		}
		else
		{
			// resend packet if we havn't got it acked in 1 second
			if(Now-pResend->m_LastSendTime > time_freq())
				ResendChunk(pResend);
		}
	}
	
	// send keep alives if nothing has happend for 250ms
	if(State() == NET_CONNSTATE_ONLINE)
	{
		if(time_get()-m_LastSendTime > time_freq()/2) // flush connection after 500ms if needed
		{
			int NumFlushedChunks = Flush();
			if(NumFlushedChunks && g_Config.m_Debug)
				dbg_msg("connection", "flushed connection due to timeout. %d chunks.", NumFlushedChunks);
		}
			
		if(time_get()-m_LastSendTime > time_freq())
			SendControl(NET_CTRLMSG_KEEPALIVE, 0, 0);
	}
	else if(State() == NET_CONNSTATE_CONNECT)
	{
		if(time_get()-m_LastSendTime > time_freq()/2) // send a new connect every 500ms
			SendControl(NET_CTRLMSG_CONNECT, 0, 0);
	}
	else if(State() == NET_CONNSTATE_PENDING)
	{
		if(time_get()-m_LastSendTime > time_freq()/2) // send a new connect/accept every 500ms
			SendControl(NET_CTRLMSG_CONNECTACCEPT, 0, 0);
	}
	
	return 0;
}
コード例 #4
0
ファイル: DIVPRO_slow.cpp プロジェクト: alxsoares/OI
void prework() {
	HM.init();
	HM.add(State(1),1);
	HM.add(State(1, 0, 0, 0, 0),1);
	HM.add(State(1, 1, 0, 0, 0),1);
	HM.add(State(1, 0, 1, 0, 0),1);
	HM.add(State(1, 2, 0, 0, 0),1);
	HM.add(State(1, 0, 0, 1, 0),1);
	HM.add(State(1, 1, 1, 0, 0),1);
	HM.add(State(1, 0, 0, 0, 1),1);
	HM.add(State(1, 3, 0, 0, 0),1);
	HM.add(State(1, 0, 2, 0, 0),1);

	for ( int i = 0; i < HM.size; i ++ ) {
		State cs = HM.key[i];
		if ( cs.is0 || cs.n == 18 ) continue;
		if ( cs.n % 2 == 0 ) {
			//mul
			HM.add(State(cs.n+1), HM.val[i]);
			HM.add(cs.exp(0, 0, 0, 0), HM.val[i]);
			HM.add(cs.exp(1, 0, 0, 0), HM.val[i]);
			HM.add(cs.exp(0, 1, 0, 0), HM.val[i]);
			HM.add(cs.exp(2, 0, 0, 0), HM.val[i]);
			HM.add(cs.exp(0, 0, 1, 0), HM.val[i]);
			HM.add(cs.exp(1, 1, 0, 0), HM.val[i]);
			HM.add(cs.exp(0, 0, 0, 1), HM.val[i]);
			HM.add(cs.exp(3, 0, 0, 0), HM.val[i]);
			HM.add(cs.exp(0, 2, 0, 0), HM.val[i]);
		} else {
			//div
			HM.add(cs.exp(0, 0, 0, 0), HM.val[i]);
			HM.add(cs.exp(-1, 0, 0, 0), HM.val[i]);
			HM.add(cs.exp(0, -1, 0, 0), HM.val[i]);
			HM.add(cs.exp(-2, 0, 0, 0), HM.val[i]);
			HM.add(cs.exp(0, 0, -1, 0), HM.val[i]);
			HM.add(cs.exp(-1, -1, 0, 0), HM.val[i]);
			HM.add(cs.exp(0, 0, 0, -1), HM.val[i]);
			HM.add(cs.exp(-3, 0, 0, 0), HM.val[i]);
			HM.add(cs.exp(0, -2, 0, 0), HM.val[i]);
		}
	}
}
コード例 #5
0
ファイル: solution.cpp プロジェクト: Jornason/DieHard
void OneDimSolve::Flip()
{
   hpol=-hpol; vpol=-vpol; State(U,C,L);
   y[0] = -y[0]; y[1] = -y[1]; y[2] = -y[2];
}
コード例 #6
0
ファイル: vaspreader.cpp プロジェクト: imc-codeteam/v2c
/*
 * Read method
 *
 * Read in a VASP file referred to by <filename>. The state of the program
 * is changed according to which line is being read. First, the number
 * of atoms and the elements are read. Then the dimension of the unit cell
 * and finally the number of atoms and the energy of each of the states. All
 * information is collected and the VaspReader class can be accessed by the
 * Dataset class for data handling.
 */
bool VaspReader::read(const char* filename) {
  std::ifstream infile(filename);


  this->state |= (1 << VASP_OUTCAR_READ_STATE_ELEMENTS);
  this->state |= (1 << VASP_OUTCAR_READ_STATE_IONS_PER_ELEMENT);
  this->state |= (1 << VASP_OUTCAR_READ_STATE_OPEN);

  this->nr_atoms_total = 0;
  this->nr_states = 0;

  /*
   * For each type of regex pattern recognition, a new set of pcre variables
   * are constructed.
   */
  pcre *regex_compiled_vasp_version;
  pcre_extra *pcre_extra_vasp_version;
  pcre *regex_compiled_element;
  pcre_extra *pcre_extra_element;
  pcre *regex_compiled_ions_per_element;
  pcre_extra *pcre_extra_ions_per_element;
  pcre *regex_compiled_lattice_vectors;
  pcre_extra *pcre_extra_lattice_vectors;
  pcre *regex_compiled_atoms;
  pcre_extra *pcre_extra_atoms;
  pcre *regex_compiled_grab_numbers;
  pcre_extra *pcre_extra_grab_numbers;
  pcre *regex_compiled_grab_energy;
  pcre_extra *pcre_extra_grab_energy;

  const char *pcre_error_string;
  const char *pcre_substring_match_string;
  int pcre_error_offset = 0;
  int pcre_exec_ret = 0;
  int pcre_substring_vec[30];
  int pos = 2;

  /*
   * Define all the regex patterns
   */
  const char *string_regex_vasp_version = "^\\s*vasp.([0-9]).[0-9]+.[0-9]+.*$";
  const char *string_regex_element = "^\\s*(VRHFIN\\s+=)([A-Za-z]+)\\s*:.*$";
  const char *string_regex_ions_per_element = "^\\s*(ions per type =\\s+)([0-9 ]+)$";
  const char *string_regex_lattice_vectors = "^\\s*direct lattice vectors.*$";
  const char *string_regex_atoms = "^\\s*POSITION.*$";
  const char *string_regex_grab_numbers = "^\\s+([0-9.-]+)\\s+([0-9.-]+)\\s+([0-9.-]+)\\s+([0-9.-]+)\\s+([0-9.-]+)\\s+([0-9.-]+).*$";
  const char *string_regex_grab_energy = "^\\s+energy  without entropy=\\s+([0-9.-]+)\\s+energy\\(sigma->0\\) =\\s+([0-9.-]+).*$";

 /*
  * Compile all the regex patterns
  */
  regex_compiled_vasp_version = pcre_compile(string_regex_vasp_version, 0, &pcre_error_string, &pcre_error_offset, NULL);
  pcre_extra_vasp_version = pcre_study(regex_compiled_vasp_version, 0, &pcre_error_string);
  regex_compiled_element = pcre_compile(string_regex_element, 0, &pcre_error_string, &pcre_error_offset, NULL);
  pcre_extra_element = pcre_study(regex_compiled_element, 0, &pcre_error_string);
  regex_compiled_ions_per_element = pcre_compile(string_regex_ions_per_element, 0, &pcre_error_string, &pcre_error_offset, NULL);
  pcre_extra_ions_per_element = pcre_study(regex_compiled_ions_per_element, 0, &pcre_error_string);
  regex_compiled_lattice_vectors = pcre_compile(string_regex_lattice_vectors, 0, &pcre_error_string, &pcre_error_offset, NULL);
  pcre_extra_lattice_vectors = pcre_study(regex_compiled_lattice_vectors, 0, &pcre_error_string);
  regex_compiled_atoms = pcre_compile(string_regex_atoms, 0, &pcre_error_string, &pcre_error_offset, NULL);
  pcre_extra_atoms = pcre_study(regex_compiled_atoms, 0, &pcre_error_string);
  regex_compiled_grab_numbers = pcre_compile(string_regex_grab_numbers, 0, &pcre_error_string, &pcre_error_offset, NULL);
  pcre_extra_grab_numbers = pcre_study(regex_compiled_grab_numbers, 0, &pcre_error_string);
  regex_compiled_grab_energy = pcre_compile(string_regex_grab_energy, 0, &pcre_error_string, &pcre_error_offset, NULL);
  pcre_extra_grab_energy = pcre_study(regex_compiled_grab_energy, 0, &pcre_error_string);

  std::string line;
  while (std::getline(infile, line)) { // loop over all the lines in the file

    /*
     * Collect the vasp version (4 or 5)
     */
    if(this->state & (1 << VASP_OUTCAR_READ_STATE_ELEMENTS) ) {
      // get the elements and put these in an array
      pos = 1;
      pcre_exec_ret = pcre_exec(regex_compiled_vasp_version, pcre_extra_vasp_version, line.c_str(), line.length(),
                           0, 0, pcre_substring_vec, 30);
      if(pcre_exec_ret > 0) {
        pcre_get_substring(line.c_str(), pcre_substring_vec, pcre_exec_ret, pos, &(pcre_substring_match_string));
        this->vasp_version = atoi(pcre_substring_match_string);

      }
    }

    /*
     * Collect the elements
     */
    if(this->state & (1 << VASP_OUTCAR_READ_STATE_ELEMENTS) ) {
      // get the elements and put these in an array
      pos = 2;
      pcre_exec_ret = pcre_exec(regex_compiled_element, pcre_extra_element, line.c_str(), line.length(),
                           0, 0, pcre_substring_vec, 30);
      if(pcre_exec_ret > 0) {
        pcre_get_substring(line.c_str(), pcre_substring_vec, pcre_exec_ret, pos, &(pcre_substring_match_string));
        this->elements.push_back(pcre_substring_match_string);
      }
    }

    /*
     * Collect the number of ions of each element type
     */
    if(this->state & (1 << VASP_OUTCAR_READ_STATE_IONS_PER_ELEMENT) ) {
      // get the number of ions per element (type)
      pos = 2;
      pcre_exec_ret = pcre_exec(regex_compiled_ions_per_element, pcre_extra_ions_per_element, line.c_str(), line.length(),
                           0, 0, pcre_substring_vec, 30);
      if(pcre_exec_ret > 0) {
        pcre_get_substring(line.c_str(), pcre_substring_vec, pcre_exec_ret, pos, &(pcre_substring_match_string));
        std::vector<std::string> elements_vector = this->explode(pcre_substring_match_string, " ");
        for(unsigned int i=0; i<elements_vector.size(); i++) {
          if(elements_vector[i].empty() == false) {
            nr_atoms_per_elm.push_back(atoi(elements_vector[i].c_str() ) );
            nr_atoms_total += atoi(elements_vector[i].c_str() );
          }
        }

        // allocate element_uint vector
        for(unsigned int i=0; i<this->elements.size(); i++) {
          this->elements_uint.push_back(this->get_element_number_from_name(this->elements[i]));
        }

        // remove ions state and elements state
        this->state &= ~(1 << VASP_OUTCAR_READ_STATE_ELEMENTS);
        this->state &= ~(1 << VASP_OUTCAR_READ_STATE_IONS_PER_ELEMENT);
        this->state |= (1 << VASP_OUTCAR_READ_STATE_LATTICE_VECTORS);
      }
    }

    /*
     * Collect the dimensions of the unit cell. Note is an IBRION=3 calculation is
     * being run, this is not gathered by this class. It is assumed that each state
     * has the same unit cell. (that means, IBRION != 3 calculations)
     */
    if(this->state & (1 << VASP_OUTCAR_READ_STATE_LATTICE_VECTORS) ) {
      // get the dimensionality of the unit cell
      pos = 0;
      pcre_exec_ret = pcre_exec(regex_compiled_lattice_vectors, pcre_extra_lattice_vectors, line.c_str(), line.length(),
                           0, 0, pcre_substring_vec, 30);
      if(pcre_exec_ret > 0) {
        pcre_get_substring(line.c_str(), pcre_substring_vec, pcre_exec_ret, pos, &(pcre_substring_match_string));
        // grab three lines
        for(int i=0; i<3; i++) {
          std::getline(infile, line);
          pcre_exec_ret = pcre_exec(regex_compiled_grab_numbers, pcre_extra_grab_numbers, line.c_str(), line.length(),
                           0, 0, pcre_substring_vec, 30);
          if(pcre_exec_ret > 0) {
            pos = 1;
            pcre_get_substring(line.c_str(), pcre_substring_vec, pcre_exec_ret, pos, &(pcre_substring_match_string));
            this->dimensions.push_back(atof(pcre_substring_match_string));
            pos = 2;
            pcre_get_substring(line.c_str(), pcre_substring_vec, pcre_exec_ret, pos, &(pcre_substring_match_string));
            this->dimensions.push_back(atof(pcre_substring_match_string));
            pos = 3;
            pcre_get_substring(line.c_str(), pcre_substring_vec, pcre_exec_ret, pos, &(pcre_substring_match_string));
            this->dimensions.push_back(atof(pcre_substring_match_string));
          }
        }
        this->state &= ~(1 << VASP_OUTCAR_READ_STATE_LATTICE_VECTORS);
        this->state |= (1 << VASP_OUTCAR_READ_STATE_ATOMS);
      }
    }

    /*
     * Collect the energy of the state
     */
    if(this->state & (1 << VASP_OUTCAR_READ_STATE_ATOMS) ) {
      pos = 2;
      pcre_exec_ret = pcre_exec(regex_compiled_grab_energy, pcre_extra_grab_energy, line.c_str(), line.length(),
                           0, 0, pcre_substring_vec, 30);
      if(pcre_exec_ret > 0) {
        pcre_get_substring(line.c_str(), pcre_substring_vec, pcre_exec_ret, pos, &(pcre_substring_match_string));
        //std::cout << atof(pcre_substring_match_string) << std::endl;
        this->energies.push_back(atof(pcre_substring_match_string));

        if(this->vasp_version == 5) {
          this->states.push_back(State(this->energies[this->nr_states - 1], this->dimensions, this->atoms, this->elements, this->elements_uint, this->nr_atoms_per_elm, filename, this->nr_states));
          this->atoms.clear();
        }
      }
    }

    /*
     * Collect the atomic positions and forces for this state
     */
    if(this->state & (1 << VASP_OUTCAR_READ_STATE_ATOMS) ) {
      // get the atoms per state
      pos = 0;
      pcre_exec_ret = pcre_exec(regex_compiled_atoms, pcre_extra_atoms, line.c_str(), line.length(),
                           0, 0, pcre_substring_vec, 30);
      if(pcre_exec_ret > 0) {
        this->nr_states++;
        pcre_get_substring(line.c_str(), pcre_substring_vec, pcre_exec_ret, pos, &(pcre_substring_match_string));
        //printf("'%s'\n", pcre_substring_match_string);
        std::getline(infile, line); // discard this line
        for(unsigned i=0; i<this->nr_atoms_per_elm.size(); i++) {
          for(unsigned int j=0; j<this->nr_atoms_per_elm[i]; j++) {
            std::getline(infile, line);
            pcre_exec_ret = pcre_exec(regex_compiled_grab_numbers, pcre_extra_grab_numbers, line.c_str(), line.length(),
                             0, 0, pcre_substring_vec, 30);
            if(pcre_exec_ret > 0) {
              //std::cout << "Atom #" << (i+1) << std::endl;
              float x, y, z, fx, fy, fz;
              pos = 1;
              pcre_get_substring(line.c_str(), pcre_substring_vec, pcre_exec_ret, pos, &(pcre_substring_match_string));
              x = atof(pcre_substring_match_string);
              pos = 2;
              pcre_get_substring(line.c_str(), pcre_substring_vec, pcre_exec_ret, pos, &(pcre_substring_match_string));
              y = atof(pcre_substring_match_string);
              pos = 3;
              pcre_get_substring(line.c_str(), pcre_substring_vec, pcre_exec_ret, pos, &(pcre_substring_match_string));
              z = atof(pcre_substring_match_string);
              pos = 4;
              pcre_get_substring(line.c_str(), pcre_substring_vec, pcre_exec_ret, pos, &(pcre_substring_match_string));
              fx = atof(pcre_substring_match_string);
              pos = 5;
              pcre_get_substring(line.c_str(), pcre_substring_vec, pcre_exec_ret, pos, &(pcre_substring_match_string));
              fy = atof(pcre_substring_match_string);
              pos = 6;
              pcre_get_substring(line.c_str(), pcre_substring_vec, pcre_exec_ret, pos, &(pcre_substring_match_string));
              fz = atof(pcre_substring_match_string);
              this->atoms.push_back(Atom(
                  this->get_element_number_from_name(this->elements[i]),
                  x, y, z, fx, fy, fz
                ));
            }
          }
        }

        if(this->vasp_version == 4) {
          this->states.push_back(State(this->energies[this->nr_states - 1], this->dimensions, this->atoms, this->elements, this->elements_uint, this->nr_atoms_per_elm, filename, this->nr_states));
          this->atoms.clear();
        }
      }
    }
  }
  this->state = (1 << VASP_OUTCAR_READ_STATE_FINISHED);

  // output all information
  std::string elements_string;
  for(unsigned int i=0; i < this->elements.size(); i++) {
    elements_string.append(elements[i]);
    elements_string.append("(");
    elements_string.append(int2str(nr_atoms_per_elm[i]) );
    elements_string.append(")");
    elements_string.append(" ");
  }

  return true;
}
コード例 #7
0
int ReplicatorGob::ProcessStateMachineMessage(State st, Message *pmsg)
{
BeginStateMachine
	OnMsg(kmidPlaySfx)
		gsndm.PlaySfx((Sfx)pmsg->PlaySfx.sfx);

	State(kstIdle)
		OnUpdate
			// If a mobile unit is at either output, ask it to move on

			TPoint tpt;
			GetTilePosition(&tpt);
			Gid gid;

			// Clear left and right output bays
			Player *pplrNeedCredits = NULL;
			bool fJammed = ClearOutputBay(tpt.tx + kdtxReplicatorOutput1, tpt.ty + kdtyReplicatorOutput1, tpt.tx + kdtxReplicatorOutput1 - 1, tpt.ty + kdtyReplicatorOutput1 + 1);
			fJammed = ClearOutputBay(tpt.tx + kdtxReplicatorOutput2, tpt.ty + kdtyReplicatorOutput2, tpt.tx + kdtxReplicatorOutput2 + 1, tpt.ty + kdtyReplicatorOutput2 + 1) || fJammed;

			// If there's nothing clogging the outputs we can consider the input
			if (m_fEnabled && !fJammed) {
				// loop through all the gobs on this tile to find the mobile unit and ignore ourself, or
				// shots flying by
				for (gid = ggobm.GetFirstGid(tpt.tx + kdtxReplicatorInput, tpt.ty + kdtyReplicatorInput); gid != kgidNull; gid = ggobm.GetNextGid(gid)) {
					MobileUnitGob *pmunt = (MobileUnitGob *)ggobm.GetGob(gid);
					if (pmunt == NULL)
						continue;
					if (!(pmunt->GetFlags() & kfGobMobileUnit))
						continue;

					// Something there! If it's ready, clone it.

					if (!(pmunt->GetMobileUnitFlags() & kfMuntAtReplicatorInput))
						continue;

					// At the limit?
// TUNE:
#define kctIntervalLimitNotify 600

					if (!ggobm.IsBelowLimit(knLimitMobileUnit, pmunt->GetOwner())) {
						if (pmunt->GetOwner() == gpplrLocal) {
							static long s_tLastNotify;
							long tCurrent = gtimm.GetTickCount();
							if (abs((int)(s_tLastNotify - tCurrent)) >= kctIntervalLimitNotify) {
								s_tLastNotify = tCurrent;
								ShowAlert(kidsUnitLimitReached);
							}
						}
						continue;
					}

					// Does the player have enough credits to perform the replication?

					MobileUnitConsts *pmuntc = (MobileUnitConsts *)pmunt->GetConsts();
					Player *pplr = pmunt->GetOwner();
					int cCredits = pplr->GetCredits();

					int nCost = pmuntc->GetCost();
					int cReplicationCost = GetReplicationCost(nCost);
					if (cCredits < cReplicationCost) {
						pplrNeedCredits = pplr;
						break; 
					}

					// Take the money!

					pplr->SetCredits(cCredits - cReplicationCost, true);

                    // Remove highlight

                    pmunt->Hilight(false);

					// Start the replicating animation

					m_fReplicating = true;
					m_ifrmLights = -1;

					MobileUnitGob *pmuntClone = (MobileUnitGob *)CreateGob(pmunt->GetType());
					if (pmuntClone != NULL) {
						pmuntClone->Init(WcFromTc(tpt.tx + kdtxReplicatorOutput2), WcFromTc(tpt.ty + kdtyReplicatorOutput2), pmunt->GetOwner(), pmunt->GetHealth(), 0, NULL);

						// Clone acquires the selection state of the original

						if (pmunt->GetFlags() & kfGobSelected)
							pmuntClone->Select(true);

						// Replicated GalaxMiners lose their load of Galaxite
						// UNDONE: if there is more of this special casing go with virtual UnitGob::Replicate()

						if (pmunt->GetType() == kgtGalaxMiner)
							((MinerGob *)pmunt)->SetGalaxiteAmount(0);

						// If this unit is a member of a group add its clone to the group too

						UnitGroup *pug = gsim.GetLevel()->GetUnitGroupMgr()->GetUnitGroup(pmunt->GetId());
						if (pug != NULL)
							pug->AddUnit(pmuntClone, true);
					}

					// Warp the original Unit to the left output port

					TerrainMap *ptrmap = gsim.GetLevel()->GetTerrainMap();
					ptrmap->ClearFlags(tpt.tx + kdtxReplicatorInput, tpt.ty + kdtyReplicatorInput, 1, 1, kbfMobileUnit);
					ptrmap->SetFlags(tpt.tx + kdtxReplicatorOutput1, tpt.ty + kdtyReplicatorOutput1, 1, 1, kbfMobileUnit);
					pmunt->SetPosition(WcFromTc(tpt.tx + kdtxReplicatorOutput1) + kwcTileHalf, WcFromTc(tpt.ty + kdtyReplicatorOutput1) + kwcTileHalf);

					// Clear the bit

					pmunt->SetMobileUnitFlags(pmunt->GetMobileUnitFlags() & ~kfMuntAtReplicatorInput);

					// Let player know the replication process has happened
					// play cool replication sound effect

					gsndm.PlaySfx(ksfxReplicatorBuild);

					// wait a quarter second and let the new unit announce itself

					Sfx sfx = SfxFromCategory(pmuntc->sfxcSelect);
					Message msgT;
					memset(&msgT, 0, sizeof(msgT));
					msgT.mid = kmidPlaySfx;
					msgT.smidSender = m_gid;
					msgT.smidReceiver = m_gid;
					msgT.PlaySfx.sfx = sfx;
					gsmm.SendDelayedMsg(&msgT, 24);

					// Play it again in another quarter of a second to sound cool

					memset(&msgT, 0, sizeof(msgT));
					msgT.mid = kmidPlaySfx;
					msgT.smidSender = m_gid;
					msgT.smidReceiver = m_gid;
					msgT.PlaySfx.sfx = sfx;
					gsmm.SendDelayedMsg(&msgT, 48);
					break;
				}
			}

			if (m_fReplicating) {
				m_ifrmLights++;
				int nStrip = m_pmuntc->panid->GetStripIndex("l 0");
				if (m_ifrmLights / 2 >= m_pmuntc->panid->GetFrameCount(nStrip)) {
					m_ifrmLights = -1;
					m_fReplicating = false;
				}
				MarkRedraw();
			}
			WaitingForCredits(pplrNeedCredits != NULL, false, pplrNeedCredits);
			m_unvl.MinSkip();
			DefUpdate();

#if 0
EndStateMachineInherit(StructGob)
#else
            return knHandled;
        }
コード例 #8
0
ファイル: Npc.cpp プロジェクト: wujohnny80/2D-Fighter
void Npc::SetState()
{
	switch(State())
	{
	case AnimState::Idle:
		{
			mVelocity.x = 1.0f;
			Flip(false);
			mDirection = rand() % 2;
			if (mDirection == 1) ChangeDirection();
			SetAnimState(AnimState::Walk);
			break;
		}
	case AnimState::Walk:
		{
			if (OutOfScreen()) { ChangeDirection(); }
			break;
		}
	case AnimState::Punch:
		{
			Velocity() = Vector2();
			if (AnimDone())
			{
				SetActiveCollider(true);
				SetAnimState(AnimState::Idle);
			}
			break;
		}
	case AnimState::Kick:
		{
			Velocity() = Vector2();
			if (AnimDone())
			{
				SetActiveCollider(true);
				SetAnimState(AnimState::Idle);
			}
			break;
		}
	case AnimState::Block:
		{
			Velocity() = Vector2();
			if (AnimDone())
			{
				Animate() = false;
				mElapsedTime += (mTime - mPrevTime) / 1000.0f;
				if (mElapsedTime > 2.0f)
				{
					Animate() = true;
					SetAnimState(AnimState::Idle);
					mElapsedTime = 0;
				}
			}
			break;
		}
	case AnimState::Special:
		{
			Velocity() = Vector2();
			if (AnimDone())
			{
				SetActiveCollider(true);
				SetAnimState(AnimState::Idle);
			}
			break;
		}
	case AnimState::Hurt:
		{
			Velocity() = Vector2();
			SetActiveCollider(false);
			if (AnimDone())
			{
				SetActiveCollider(true);
				SetAnimState(AnimState::Idle);
			}
			break;
		}
	case AnimState::Death:
		{
			Velocity() = Vector2();
			SetActiveCollider(false);
			if (AnimDone())
			{
				Animate() = false;
			}
			break;
		}
	}
}
コード例 #9
0
void MicRecorderFilter::Process(const GenericSignal& Input, GenericSignal& Output)
{

	if(!mEnable) {
		Output = Input;
		return;
	}

	if(State("Running") == 1 && mMic.IsRecording() == false) {
		i++;

		BCIDirectory test = BCIDirectory()
			.SetDataDirectory( Parameter( "DataDirectory" ) )
			.SetSubjectName( Parameter( "SubjectName" ) )
			.SetSessionNumber( Parameter( "SubjectSession" ) )
			.SetRunNumber( Parameter( "SubjectRun" ) )
			.SetFileExtension( "dat" );

		std::string baseFileName = BCIDirectory()
			.SetDataDirectory( Parameter( "DataDirectory" ) )
			.SetSubjectName( Parameter( "SubjectName" ) )
			.SetSessionNumber( Parameter( "SubjectSession" ) )
			.SetFileExtension( "wav" )
			.SetRunNumber(test.RunNumber()-1)
			.CreatePath()
			.FilePath() + ".wav";

		bciout << "File name: " << baseFileName;
		//char test[256];
		//sprintf_s(test, 256, "C:\\Code\\bci2000_3.0\\batch\\output%02i.wav", 1);
		mMic.SetFileName(baseFileName);
		//mMic.SetFileName(test);
		mMic.OpenFileForRecording();
		mMic.Record();
	}

	if(State("Running") == 0 && mMic.IsRecording() == true) {
		mMic.Stop();
	}

	if(State("Running") == 1 && mMic.IsRecording() == true) {
		State("MicSample") = mMic.GetSamplesRecorded();
	}

	Output = Input;



  /*if (datagloveenable) {

    sensor_data[0]  = fdGetSensorRawCall(pGlove,FD_THUMBNEAR);
    sensor_data[1]  = fdGetSensorRawCall(pGlove,FD_INDEXNEAR);
    sensor_data[2]  = fdGetSensorRawCall(pGlove,FD_MIDDLENEAR);
    sensor_data[3]  = fdGetSensorRawCall(pGlove,FD_RINGNEAR);
    sensor_data[4]  = fdGetSensorRawCall(pGlove,FD_LITTLENEAR);

    if (glovetype == FD_GLOVE14U_USB) {
      sensor_data[5]  = fdGetSensorRawCall(pGlove,FD_THUMBFAR);
      sensor_data[6]  = fdGetSensorRawCall(pGlove,FD_INDEXFAR);
      sensor_data[7]  = fdGetSensorRawCall(pGlove,FD_MIDDLEFAR);
      sensor_data[8]  = fdGetSensorRawCall(pGlove,FD_RINGFAR);
      sensor_data[9]  = fdGetSensorRawCall(pGlove,FD_LITTLEFAR);
      sensor_data[10] = fdGetSensorRawCall(pGlove,FD_THUMBINDEX);
      sensor_data[11] = fdGetSensorRawCall(pGlove,FD_INDEXMIDDLE);
      sensor_data[12] = fdGetSensorRawCall(pGlove,FD_MIDDLERING);
      sensor_data[13] = fdGetSensorRawCall(pGlove,FD_RINGLITTLE);
    } else {
      sensor_data[5]  = 0;
      sensor_data[6]  = 0;
      sensor_data[7]  = 0;
      sensor_data[8]  = 0;
      sensor_data[9]  = 0;
      sensor_data[10] = 0;
      sensor_data[11] = 0;
      sensor_data[12] = 0;
      sensor_data[13] = 0;
    }

    State("GloveSensor1")=sensor_data[0];
    State("GloveSensor2")=sensor_data[1];
    State("GloveSensor3")=sensor_data[2];
    State("GloveSensor4")=sensor_data[3];
    State("GloveSensor5")=sensor_data[4];
    State("GloveSensor6")=sensor_data[5];
    State("GloveSensor7")=sensor_data[6];
    State("GloveSensor8")=sensor_data[7];
    State("GloveSensor9")=sensor_data[8];
    State("GloveSensor10")=sensor_data[9];
    State("GloveSensor11")=sensor_data[10];
    State("GloveSensor12")=sensor_data[11];
    State("GloveSensor13")=sensor_data[12];
    State("GloveSensor14")=sensor_data[13];

  } else {

    State("GloveSensor1")=0;
    State("GloveSensor2")=0;
    State("GloveSensor3")=0;
    State("GloveSensor4")=0;
    State("GloveSensor5")=0;
    State("GloveSensor6")=0;
    State("GloveSensor7")=0;
    State("GloveSensor8")=0;
    State("GloveSensor9")=0;
    State("GloveSensor10")=0;
    State("GloveSensor11")=0;
    State("GloveSensor12")=0;
    State("GloveSensor13")=0;
    State("GloveSensor14")=0;
  }*/ 

}
コード例 #10
0
ファイル: reverse_cons.hpp プロジェクト: ASMlover/study
 BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
 static State const &call(nil_ const &, State const &state = State())
 {
     return state;
 }
コード例 #11
0
ファイル: cart_pole.hpp プロジェクト: dasayan05/mlpack
 /**
  * Initial state representation is randomly generated within [-0.05, 0.05].
  *
  * @return Initial state for each episode.
  */
 State InitialSample() const
 {
   return State((arma::randu<arma::colvec>(4) - 0.5) / 10.0);
 }
コード例 #12
0
ファイル: reverse_cons.hpp プロジェクト: ASMlover/study
 BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
 static type call(cons<Car, Cdr> const &cons, State const &state = State())
 {
     typedef fusion::cons<Car, State> cdr_type;
     return impl::call(cons.cdr, cdr_type(cons.car, state));
 }
コード例 #13
0
ファイル: Protocol.cpp プロジェクト: DonCN/haiku
void
IPCP::RCREvent(struct mbuf *packet)
{
	TRACE("IPCP: RCREvent() state=%d\n", State());
	
	KPPPConfigurePacket request(packet);
	KPPPConfigurePacket nak(PPP_CONFIGURE_NAK);
	KPPPConfigurePacket reject(PPP_CONFIGURE_REJECT);
	
	// we should not use the same id as the peer
	if(fID == mtod(packet, ppp_lcp_packet*)->id)
		fID -= 128;
	
	nak.SetID(request.ID());
	reject.SetID(request.ID());
	
	// parse each item
	ppp_configure_item *item;
	in_addr_t *requestedAddress, *wishedAddress = NULL;
	for(int32 index = 0; index < request.CountItems(); index++) {
		item = request.ItemAt(index);
		if(!item)
			continue;
		
		// addresses have special handling to reduce code size
		switch(item->type) {
			case IPCP_ADDRESSES:
				// abandoned by the standard
			case IPCP_ADDRESS:
				wishedAddress = &fPeerRequests.address;
			break;
			
			case IPCP_PRIMARY_DNS:
				wishedAddress = &fPeerRequests.primaryDNS;
			break;
			
			case IPCP_SECONDARY_DNS:
				wishedAddress = &fPeerRequests.secondaryDNS;
			break;
		}
		
		// now parse item
		switch(item->type) {
			case IPCP_ADDRESSES:
				// abandoned by the standard
			case IPCP_ADDRESS:
			case IPCP_PRIMARY_DNS:
			case IPCP_SECONDARY_DNS:
				if(item->length != 6) {
					// the packet is invalid
					m_freem(packet);
					NewState(PPP_INITIAL_STATE);
					ReportUpFailedEvent();
					return;
				}
				
				requestedAddress = (in_addr_t*) item->data;
				if(*wishedAddress == INADDR_ANY) {
					if(*requestedAddress == INADDR_ANY) {
						// we do not have an address for you
						m_freem(packet);
						NewState(PPP_INITIAL_STATE);
						ReportUpFailedEvent();
						return;
					}
				} else if(*requestedAddress != *wishedAddress) {
					// we do not want this address
					ip_item ipItem;
					ipItem.type = item->type;
					ipItem.length = 6;
					ipItem.address = *wishedAddress;
					nak.AddItem((ppp_configure_item*) &ipItem);
				}
			break;
			
//			case IPCP_COMPRESSION_PROTOCOL:
				// TODO: implement me!
//			break;
			
			default:
				reject.AddItem(item);
		}
	}
	
	// append additional values to the nak
	if(!request.ItemWithType(IPCP_ADDRESS) && fPeerRequests.address == INADDR_ANY) {
		// The peer did not provide us his address. Tell him to do so.
		ip_item ipItem;
		ipItem.type = IPCP_ADDRESS;
		ipItem.length = 6;
		ipItem.address = INADDR_ANY;
		nak.AddItem((ppp_configure_item*) &ipItem);
	}
	
	if(nak.CountItems() > 0) {
		RCRBadEvent(nak.ToMbuf(Interface().MRU(), Interface().PacketOverhead()), NULL);
		m_freem(packet);
	} else if(reject.CountItems() > 0) {
		RCRBadEvent(NULL, reject.ToMbuf(Interface().MRU(),
			Interface().PacketOverhead()));
		m_freem(packet);
	} else
		RCRGoodEvent(packet);
}
コード例 #14
0
ファイル: Protocol.cpp プロジェクト: DonCN/haiku
void
IPCP::UpdateAddresses()
{
	RemoveRoutes();
	
	if(State() != PPP_OPENED_STATE && !Interface().DoesConnectOnDemand())
		return;
	
	struct in_aliasreq inreq;
	struct ifreq ifreqAddress, ifreqDestination;
	memset(&inreq, 0, sizeof(struct in_aliasreq));
	memset(&ifreqAddress, 0, sizeof(struct ifreq));
	memset(&ifreqDestination, 0, sizeof(struct ifreq));
	memset(&fGateway, 0, sizeof(struct sockaddr_in));
	
	// create local address
	inreq.ifra_addr.sin_family = AF_INET;
	if(fLocalRequests.address != INADDR_ANY)
		inreq.ifra_addr.sin_addr.s_addr = fLocalRequests.address;
	else if(fLocalConfiguration.address == INADDR_ANY)
		inreq.ifra_addr.sin_addr.s_addr = 0x010F0F0F; // was: INADDR_BROADCAST
	else
		inreq.ifra_addr.sin_addr.s_addr = fLocalConfiguration.address;
	inreq.ifra_addr.sin_len = sizeof(struct sockaddr_in);
	memcpy(&ifreqAddress.ifr_addr, &inreq.ifra_addr, sizeof(struct sockaddr_in));
	
	// create destination address
	fGateway.sin_family = AF_INET;
	if(fPeerRequests.address != INADDR_ANY)
		fGateway.sin_addr.s_addr = fPeerRequests.address;
	else if(fPeerConfiguration.address == INADDR_ANY)
		fGateway.sin_addr.s_addr = 0x020F0F0F; // was: INADDR_BROADCAST
	else
		fGateway.sin_addr.s_addr = fPeerConfiguration.address;
	fGateway.sin_len = sizeof(struct sockaddr_in);
	memcpy(&inreq.ifra_dstaddr, &fGateway,
		sizeof(struct sockaddr_in));
	memcpy(&ifreqDestination.ifr_dstaddr, &inreq.ifra_dstaddr,
		sizeof(struct sockaddr_in));
	
	// create netmask
	inreq.ifra_mask.sin_family = AF_INET;
	inreq.ifra_mask.sin_addr.s_addr = fLocalRequests.netmask;
	inreq.ifra_mask.sin_len = sizeof(struct sockaddr_in);
	
	// tell stack to use these values
	if(in_control(NULL, SIOCAIFADDR, (caddr_t) &inreq,
			Interface().Ifnet()) != B_OK)
		ERROR("IPCP: UpdateAddress(): SIOCAIFADDR returned error!\n");
	if(in_control(NULL, SIOCSIFADDR, (caddr_t) &ifreqAddress,
			Interface().Ifnet()) != B_OK)
		ERROR("IPCP: UpdateAddress(): SIOCSIFADDR returned error!\n");
	if(in_control(NULL, SIOCSIFDSTADDR, (caddr_t) &ifreqDestination,
			Interface().Ifnet()) != B_OK)
		ERROR("IPCP: UpdateAddress(): SIOCSIFDSTADDR returned error!\n");
	memcpy(&inreq.ifra_addr, &inreq.ifra_mask, sizeof(struct sockaddr_in));
		// SIOCISFNETMASK wants the netmask to be in ifra_addr
	if(in_control(NULL, SIOCSIFNETMASK, (caddr_t) &inreq,
			Interface().Ifnet()) != B_OK)
		ERROR("IPCP: UpdateAddress(): SIOCSIFNETMASK returned error!\n");
	
	// add default/subnet route
	if(Side() == PPP_LOCAL_SIDE) {
		if(rtrequest(RTM_ADD, (struct sockaddr*) &inreq.ifra_mask,
				(struct sockaddr*) &fGateway, (struct sockaddr*) &inreq.ifra_mask,
				RTF_UP | RTF_GATEWAY, &fDefaultRoute) != B_OK)
			ERROR("IPCP: UpdateAddress(): could not add default/subnet route!\n");
		
		--fDefaultRoute->rt_refcnt;
	}
}
コード例 #15
0
ファイル: ukf.cpp プロジェクト: nikhil9/ukf
/*
Follows section 3.3.
*/
void UnscentedKalmanFilter::apriori_estimate(real_t dt, ControlVector c) {
    uint32_t i;

    /*
    Run the sigma points through the process model as per equation 37.
    No need to make a new sigma point distribution, we won't need the old one
    again.
    */
    for(i = 0; i < UKF_NUM_SIGMA; i++) {
        sigma_points.col(i) = integrator.integrate(
            State(sigma_points.col(i)), dt);

        /* Orientation often doesn't stay normalized after integration */
        Quaternionr q(sigma_points.col(i).segment<4>(9));
        q.normalize();
        sigma_points.col(i).segment<4>(9) << q.vec(), q.w();
    }

    /*
    This is where the dynamics model should be run, which is effectively the
    control input part of the process model.
    If there's no dynamics model selected, then the acceleration and angular
    acceleration should be zeroed as there's no way to predict them.
    */
    if(dynamics != NULL) {
        for(i = 0; i < UKF_NUM_SIGMA; i++) {
            AccelerationVector temp = dynamics->evaluate(
                sigma_points.col(i), c);
            sigma_points.col(i).segment<3>(6) = temp.segment<3>(0);
            sigma_points.col(i).segment<3>(16) = temp.segment<3>(3);
        }
    } else {
        /*
        FIXME: may not be necessary/helpful to clear out linear acceleration
        in the absence of a dynamics model.

        sigma_points.block<3, UKF_NUM_SIGMA>(6, 0) =
            Eigen::Matrix<real_t, 3, UKF_NUM_SIGMA>::Zero();
        */
        sigma_points.block<3, UKF_NUM_SIGMA>(16, 0) =
            Eigen::Matrix<real_t, 3, UKF_NUM_SIGMA>::Zero();
    }

    /*
    Now, calculate the mean as described in section 3.4, using the weights
    from the scaled unscented transform.
    For calculating a priori attitude estimate, we use the algorithm for
    computing the quaternion mean found in "Unscented Filtering in a Unit
    Quaternion Space for Spacecraft Attitude Estimation" by Yee-Jin Cheon.
    The following algorithm implements equation (41d) from that paper.
    */
    apriori_mean.segment<UKF_STATE_DIM+1>(0) =
        UKF_SIGMA_WMI*sigma_points.block<
            UKF_STATE_DIM+1, UKF_NUM_SIGMA-1>(0, 1).rowwise().sum() +
        UKF_SIGMA_WM0*sigma_points.col(0);

    /*
    Calculate the covariance as described in section 3.5.1. Note that there is
    another error with equation 63; we want to operate on the transformed
    sigma points, not the untransformed ones.
    For the attitude error, we use the same error vectors calculated using the
    gradient descent algorithm above.
    */
    w_prime.topRows<9>() = sigma_points.topRows<9>().colwise() -
        sigma_points.col(0).segment<9>(0);
    w_prime.bottomRows<12>() = sigma_points.bottomRows<12>().colwise() -
        sigma_points.col(0).segment<12>(13);

    /*
    The attitude part of this set of vectors is calculated using equation (45)
    from the paper mentioned above.
    */
    for(i = 0; i < UKF_NUM_SIGMA; i++) {
        Quaternionr err_q =
            (Quaternionr(sigma_points.col(i).segment<4>(9)) *
            Quaternionr(sigma_points.col(0).segment<4>(9)).conjugate());

        w_prime.block<3, 1>(9, i) = UKF_MRP_F *
            (err_q.vec() / (UKF_MRP_A + err_q.w()));
    }

    /* Calculate the covariance using equation 64. */
    apriori_covariance =
        UKF_SIGMA_WC0 * (w_prime.col(0) * w_prime.col(0).transpose());
    for(i = 1; i < UKF_NUM_SIGMA; i++) {
        apriori_covariance +=
            UKF_SIGMA_WCI * (w_prime.col(i) * w_prime.col(i).transpose());
    }
}
コード例 #16
0
int CNetConnection::Feed(CNetPacketConstruct *pPacket, NETADDR *pAddr, SECURITY_TOKEN SecurityToken)
{
	if (State() != NET_CONNSTATE_OFFLINE && m_SecurityToken != NET_SECURITY_TOKEN_UNKNOWN && m_SecurityToken != NET_SECURITY_TOKEN_UNSUPPORTED)
	{
		// supposed to have a valid token in this packet, check it
		if (pPacket->m_DataSize < (int)sizeof(m_SecurityToken))
			return 0;
		pPacket->m_DataSize -= sizeof(m_SecurityToken);
		if (m_SecurityToken != ToSecurityToken(&pPacket->m_aChunkData[pPacket->m_DataSize]))
		{
			if(g_Config.m_Debug)
				dbg_msg("security", "token mismatch, expected %d got %d", m_SecurityToken, ToSecurityToken(&pPacket->m_aChunkData[pPacket->m_DataSize]));
			return 0;
		}
	}

	int64 Now = time_get();

	// check if resend is requested
	if(pPacket->m_Flags&NET_PACKETFLAG_RESEND)
		Resend();

	//
	if(pPacket->m_Flags&NET_PACKETFLAG_CONTROL)
	{
		int CtrlMsg = pPacket->m_aChunkData[0];

		if(CtrlMsg == NET_CTRLMSG_CLOSE)
		{
			if(net_addr_comp(&m_PeerAddr, pAddr) == 0)
			{
				m_State = NET_CONNSTATE_ERROR;
				m_RemoteClosed = 1;

				char Str[128] = {0};
				if(pPacket->m_DataSize > 1)
				{
					// make sure to sanitize the error string form the other party
					if(pPacket->m_DataSize < 128)
						str_copy(Str, (char *)&pPacket->m_aChunkData[1], pPacket->m_DataSize);
					else
						str_copy(Str, (char *)&pPacket->m_aChunkData[1], sizeof(Str));
					str_sanitize_strong(Str);
				}

				if(!m_BlockCloseMsg)
				{
					// set the error string
					SetError(Str);
				}

				if(g_Config.m_Debug)
					dbg_msg("conn", "closed reason='%s'", Str);
			}
			return 0;
		}
		else
		{
			if(State() == NET_CONNSTATE_OFFLINE)
			{
				if(CtrlMsg == NET_CTRLMSG_CONNECT)
				{
					NETADDR nAddr;
					mem_copy(&nAddr, pAddr, sizeof(nAddr));
					nAddr.port = 0;
					m_PeerAddr.port = 0;
#ifndef FUZZING
					if(net_addr_comp(&m_PeerAddr, &nAddr) == 0 && time_get() - m_LastUpdateTime < time_freq() * 3)
						return 0;
#endif

					// send response and init connection
					Reset();
					m_State = NET_CONNSTATE_PENDING;
					m_PeerAddr = *pAddr;
					mem_zero(m_ErrorString, sizeof(m_ErrorString));
					m_LastSendTime = Now;
					m_LastRecvTime = Now;
					m_LastUpdateTime = Now;
					if (m_SecurityToken == NET_SECURITY_TOKEN_UNKNOWN
						&& pPacket->m_DataSize >= (int)(1 + sizeof(SECURITY_TOKEN_MAGIC) + sizeof(m_SecurityToken))
						&& !mem_comp(&pPacket->m_aChunkData[1], SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC)))
					{
						m_SecurityToken = SecurityToken;
						if(g_Config.m_Debug)
							dbg_msg("security", "generated token %d", m_SecurityToken);
					}
					else
					{
						if(g_Config.m_Debug)
							dbg_msg("security", "token not supported by client (packet size %d)", pPacket->m_DataSize);
						m_SecurityToken = NET_SECURITY_TOKEN_UNSUPPORTED;
					}
					SendControl(NET_CTRLMSG_CONNECTACCEPT, SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC));
					if(g_Config.m_Debug)
						dbg_msg("connection", "got connection, sending connect+accept");
				}
			}
			else if(State() == NET_CONNSTATE_CONNECT)
			{
				// connection made
				if(CtrlMsg == NET_CTRLMSG_CONNECTACCEPT)
				{
					if (m_SecurityToken == NET_SECURITY_TOKEN_UNKNOWN
						&& pPacket->m_DataSize >= (int)(1 + sizeof(SECURITY_TOKEN_MAGIC) + sizeof(m_SecurityToken))
						&& !mem_comp(&pPacket->m_aChunkData[1], SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC)))
					{
						m_SecurityToken = ToSecurityToken(&pPacket->m_aChunkData[1 + sizeof(SECURITY_TOKEN_MAGIC)]);
						if(g_Config.m_Debug)
							dbg_msg("security", "got token %d", m_SecurityToken);
					}
					else
					{
						m_SecurityToken = NET_SECURITY_TOKEN_UNSUPPORTED;
						if(g_Config.m_Debug)
							dbg_msg("security", "token not supported by server");
					}
					m_LastRecvTime = Now;
					SendControl(NET_CTRLMSG_ACCEPT, 0, 0);
					m_State = NET_CONNSTATE_ONLINE;
					if(g_Config.m_Debug)
						dbg_msg("connection", "got connect+accept, sending accept. connection online");
				}
			}
		}
	}
	else
	{
		if(State() == NET_CONNSTATE_PENDING)
		{
			m_LastRecvTime = Now;
			m_State = NET_CONNSTATE_ONLINE;
			if(g_Config.m_Debug)
				dbg_msg("connection", "connecting online");
		}
	}

	if(State() == NET_CONNSTATE_ONLINE)
	{
		m_LastRecvTime = Now;
		AckChunks(pPacket->m_Ack);
	}

	return 1;
}
コード例 #17
0
ファイル: scanner.cpp プロジェクト: qtstc/YASL-Compiler
void scannerClass::buildStateMatrixCompact()
{
	int nonFinalStateNum = 0;

	for(int i = 0;i<MAX_STATE;++i)
		for(int j = 0;j<MAX_CHAR;++j)
			stateMatrix[i][j] = State();

	//Read carriage return and whitespace at state 0 lead to 0
	State zeroState(0);
	char whitespaces[6] = {' ','\t','\v','\f','\r','\n'};
	for(int i = 0;i<6;++i)
		stateMatrix[0][whitespaces[i]]=zeroState;
	stateMatrix[0][EOF_INDEX] = State(EOF_INDEX);//End of file indicator

	//Read *-+.,()~;& goes to the respective final state with action ACCEPT
	stateMatrix[0]['*'] = State(false,MULOP_T,MULTIPLY_ST,"*");
	stateMatrix[0]['-'] = State(false,ADDOP_T,SUBSTRACT_ST,"-");
	stateMatrix[0]['+'] = State(false,ADDOP_T,ADD_ST,"+");
	stateMatrix[0]['.'] = State(false,DOT_T,NONE_ST,".");
	stateMatrix[0][','] = State(false,COMMA_T,NONE_ST,",");
	stateMatrix[0]['('] = State(false,LEFTPAREN_T,NONE_ST,"(");
	stateMatrix[0][')'] = State(false,RIGHTPAREN_T,NONE_ST,")");
	stateMatrix[0]['~'] = State(false,TILDE_T,NONE_ST,"~");
	stateMatrix[0][';'] = State(false,SEMICOLON_T,NONE_ST,";");
	stateMatrix[0]['&'] = State(false,AMPERSAND_T,NONE_ST,"&");

	//Read "="
	int firstEqualStateNum = ++nonFinalStateNum;//State with number zero is reserved for the starting state
	stateMatrix[0]['='] = State(firstEqualStateNum);//Read first equal
	//Read "<"
	int firstLessThanStateNum = ++nonFinalStateNum;
	stateMatrix[0]['<'] = State(firstLessThanStateNum);
	//Read ">"
	int firstGreaterThanStateNum = ++nonFinalStateNum;
	stateMatrix[0]['>']=State(firstGreaterThanStateNum);
	//Read digit
	int firstDigitStateNum = ++nonFinalStateNum;
	string digits = "0123456789";
	for(int i = 0;i<digits.length();++i)
	{
		stateMatrix[0][digits[i]] = State(firstDigitStateNum);
	}
	//Read string
	int leftQuoteStateNum = ++nonFinalStateNum;
	stateMatrix[0]['\''] = State(leftQuoteStateNum);
	//Read double slash started comment
	int firstSlashStateNum = ++nonFinalStateNum;
	int secondSlashStateNum = ++nonFinalStateNum;
	stateMatrix[0]['/']=State(firstSlashStateNum);
	//Read identifier
	int firstLetterStateNum = ++nonFinalStateNum;
		string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
	for(int i = 0;i<letters.length();++i)
		stateMatrix[0][letters[i]]=State(firstLetterStateNum);
	//Read comment enclosed in brace
	int leftBraceStateNum = ++nonFinalStateNum;
	int secondDollarStateNum = ++nonFinalStateNum;
	int thirdLetterStateNum = ++nonFinalStateNum;
	int fourthAddMinusStateNum = ++nonFinalStateNum;
	int bracedCommentStateNum = ++nonFinalStateNum;
	stateMatrix[0]['{'] = State(leftBraceStateNum);

	for(int i = 0;i<MAX_CHAR;++i)
	{
		//"="
		if(i == '=')
			stateMatrix[firstEqualStateNum]['=']=State(false,RELOP_T,EQUAL_ST,"==");
		else
			stateMatrix[firstEqualStateNum][i] = State(true,ASSIGNMENT_T,NONE_ST,"=");
		//"<"
		if(i == '<')
			stateMatrix[firstLessThanStateNum]['<'] = State(false,BITLEFT_T,NONE_ST,"<<");
		else if(i=='>')
			stateMatrix[firstLessThanStateNum]['>'] = State(false,RELOP_T,UNEQUAL_ST,"<>");
		else if (i == '=')
			stateMatrix[firstLessThanStateNum]['='] = State(false,RELOP_T,LESSOREQUAL_ST,"<=");
		else
			stateMatrix[firstLessThanStateNum][i] = State(true,RELOP_T,LESS_ST,"<");
		//">"
		if(i == '>')
			stateMatrix[firstGreaterThanStateNum]['>'] = State(false,BITRIGHT_T,NONE_ST,">>");
		else if (i == '=')
			stateMatrix[firstGreaterThanStateNum]['='] = State(false,RELOP_T,GREATEROREQUAL_ST,">=");
		else
			stateMatrix[firstGreaterThanStateNum][i] = State(true,RELOP_T,GREATER_ST,">");
		if(i<= '9' && i >='0')
			stateMatrix[firstDigitStateNum][i] = State(firstDigitStateNum);
		else
			stateMatrix[firstDigitStateNum][i] = State(true,INTEGER_T,NONE_ST,"int_lexeme");
		//string
		if(i == '\'')
			stateMatrix[leftQuoteStateNum][i] = State(false,STRING_T,NONE_ST,"string_lexeme");
		else if(i=='\r'||i=='\n')
			stateMatrix[leftQuoteStateNum][i] = State("String cannot be split across lines.");
		else if (i == EOF_INDEX)
			stateMatrix[leftQuoteStateNum][i] = State("Single quote expected at the end of string.");
		else
			stateMatrix[leftQuoteStateNum][i]=State(leftQuoteStateNum);
		//double slash started comment
		if(i == '/')
			stateMatrix[firstSlashStateNum][i] = State(secondSlashStateNum);
		else 
			stateMatrix[firstSlashStateNum][i] = State("Comment should be started by double slashes.");
		if(i == '\r'||i == '\n')
			stateMatrix[secondSlashStateNum][i] = State(0);
		else if(i == EOF_INDEX)
			stateMatrix[secondSlashStateNum][i] = State(0,true);
		else
			stateMatrix[secondSlashStateNum][i] = State(secondSlashStateNum,CLEAR_BUFFER_ACTION);
		//Identifier
		if(('A'<=i&&i<='Z')||('a'<=i&&i<='z')||('0'<=i&&i<='9')||(i=='_'))
			stateMatrix[firstLetterStateNum][i] = State(firstLetterStateNum);
		else 
			stateMatrix[firstLetterStateNum][i] = State(true,IDENTIFIER_T,NONE_ST,"identifier_lexeme");
		//Braced comment
		if(i == '}')
			stateMatrix[leftBraceStateNum][i] = State(0);
		else if(i == '$')
			stateMatrix[leftBraceStateNum][i] = State(secondDollarStateNum);
		else if(i == EOF_INDEX)
			stateMatrix[leftBraceStateNum][i] = State("Comment or compiler directive needs to be ended with a right brace.");
		else 
			stateMatrix[leftBraceStateNum][i] = State(bracedCommentStateNum);

		if(i == '}')
			stateMatrix[secondDollarStateNum][i] = State(0);
		else if (i <= 'z' && i >= 'A')
			stateMatrix[secondDollarStateNum][i] = State(thirdLetterStateNum);
		else if (i == EOF_INDEX)
			stateMatrix[secondDollarStateNum][i] = State("Comment or compiler directive needs to be ended with a right brace.");
		else
			stateMatrix[secondDollarStateNum][i] = State(bracedCommentStateNum);

		if(i == '}')
			stateMatrix[thirdLetterStateNum][i] = State(0);
		else if(i == '+' ||i == '-')
			stateMatrix[thirdLetterStateNum][i] = State(fourthAddMinusStateNum);
		else if (i == EOF_INDEX)
			stateMatrix[thirdLetterStateNum][i] = State("Comment or compiler directive needs to be ended with a right brace.");
		else 
			stateMatrix[thirdLetterStateNum][i] = State(bracedCommentStateNum);

		if(i == '}')
			stateMatrix[fourthAddMinusStateNum][i] = State(0,CHECK_COMPILER_DIRECTIVE_ACTION);
		else if(i == EOF_INDEX)
			stateMatrix[fourthAddMinusStateNum][i] = State("Comment or compiler directive needs to be ended with a right brace.");
		else stateMatrix[fourthAddMinusStateNum][i] =State(bracedCommentStateNum);

		if(i == '}')
			stateMatrix[bracedCommentStateNum][i] = State(0);
		else if(i == EOF_INDEX)
			stateMatrix[bracedCommentStateNum][i] = State("Comment or compiler directive needs to be ended with a right brace.");
		else
			stateMatrix[bracedCommentStateNum][i] = State(bracedCommentStateNum,CLEAR_BUFFER_ACTION);
	}
}
コード例 #18
0
int CNetConnection::Update()
{
	int64 Now = time_get();

	if(State() == NET_CONNSTATE_ERROR && m_TimeoutSituation && (Now-m_LastRecvTime) > time_freq()*g_Config.m_ConnTimeoutProtection)
	{
		m_TimeoutSituation = false;
		SetError("Timeout Protection over");
	}

	if(State() == NET_CONNSTATE_OFFLINE || State() == NET_CONNSTATE_ERROR)
		return 0;

	m_TimeoutSituation = false;

	// check for timeout
	if(State() != NET_CONNSTATE_OFFLINE &&
		State() != NET_CONNSTATE_CONNECT &&
		(Now-m_LastRecvTime) > time_freq()*g_Config.m_ConnTimeout)
	{
		m_State = NET_CONNSTATE_ERROR;
		SetError("Timeout");
		m_TimeoutSituation = true;
	}

	// fix resends
	if(m_Buffer.First())
	{
		CNetChunkResend *pResend = m_Buffer.First();

		// check if we have some really old stuff laying around and abort if not acked
		if(Now-pResend->m_FirstSendTime > time_freq()*g_Config.m_ConnTimeout)
		{
			m_State = NET_CONNSTATE_ERROR;
			char aBuf[512];
			str_format(aBuf, sizeof(aBuf), "Too weak connection (not acked for %d seconds)", g_Config.m_ConnTimeout);
			SetError(aBuf);
			m_TimeoutSituation = true;
		}
		else
		{
			// resend packet if we havn't got it acked in 1 second
			if(Now-pResend->m_LastSendTime > time_freq())
				ResendChunk(pResend);
		}
	}

	// send keep alives if nothing has happend for 250ms
	if(State() == NET_CONNSTATE_ONLINE)
	{
		if(time_get()-m_LastSendTime > time_freq()/2) // flush connection after 500ms if needed
		{
			int NumFlushedChunks = Flush();
			if(NumFlushedChunks && g_Config.m_Debug)
				dbg_msg("connection", "flushed connection due to timeout. %d chunks.", NumFlushedChunks);
		}

		if(time_get()-m_LastSendTime > time_freq())
			SendControl(NET_CTRLMSG_KEEPALIVE, 0, 0);
	}
	else if(State() == NET_CONNSTATE_CONNECT)
	{
		if(time_get()-m_LastSendTime > time_freq()/2) // send a new connect every 500ms
			SendControl(NET_CTRLMSG_CONNECT, SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC));
	}
	else if(State() == NET_CONNSTATE_PENDING)
	{
		if(time_get()-m_LastSendTime > time_freq()/2) // send a new connect/accept every 500ms
			SendControl(NET_CTRLMSG_CONNECTACCEPT, SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC));
	}

	return 0;
}
コード例 #19
0
ファイル: stream_encoder.cpp プロジェクト: ACUVE/flac
		Stream::State Stream::get_state() const
		{
			FLAC__ASSERT(is_valid());
			return State(::FLAC__stream_encoder_get_state(encoder_));
		}
コード例 #20
0
void UIManager::UpdateOfMakingCharacter()
{
	if (Env().isPushButton(Mouse::LEFT) && isTouchCharaMakeMapChip == false)
	{
		if (GameManager::map.CheckCharaMakeMapChip(mousePosition) == CharaMakeMapChipType::CHARA_MAKE)
		{
			selectMapPosition = GameManager::map.SetCharaMakeMapChipPos(mousePosition);
			isTouchCharaMakeMapChip = true;
			isSelectSetPlayer = true;
			Env().flushInput();
		}
		else if (GameManager::map.CheckCharaMakeMapChip(mousePosition) == CharaMakeMapChipType::CHARA_MAKED)
		{
			selectMapPosition = GameManager::map.SetCharaMakeMapChipPos(mousePosition);
			isTouchCharaMakeMapChip = true;
			Env().flushInput();

			for (auto player = GameManager::players.begin(); player != GameManager::players.end(); ++player)
			{
				if (selectMapPosition == player->Position())
				{
					selectPlayerType = player->CharacterType();
					selectCharaStatus = player->State();
					selectCharaUI.SetTexture(charaUI[selectPlayerType].View());
				}
			}
		}
	}

	if (isTouchCharaMakeMapChip == true)
	{
		//UIBoxの部分
		if (isHitMouseToBox(Vec2f(-WINDOW_WIDTH / 2, -WINDOW_HEIGHT / 2), Vec2f(WINDOW_WIDTH, 280), mousePosition) != true
			&& Env().isPushButton(Mouse::LEFT))
		{
			isTouchCharaMakeMapChip = false;
			isSelectSetPlayer = false;
			Env().flushInput();
		}

		if (GameManager::map.CheckCharaMakeMapChip(selectMapPosition) == CharaMakeMapChipType::CHARA_MAKE)
		{
			for (int i = 0; i <4; ++i)
			{
				if (Env().isPushButton(Mouse::LEFT)
					&& isHitMouseToBox(charaUI[i].Position(), charaUI[i].Size(), mousePosition) == true
					)
				{
					switch (i)
					{
					case PlayerCharaType::TUBAKI:
						GameManager::totalSummonPoint -= charaCost[i];
						GameManager::MakePlayer(selectMapPosition, PlayerCharaType::TUBAKI);
						break;
					case PlayerCharaType::NOEL:
						GameManager::totalSummonPoint -= charaCost[i];
						GameManager::MakePlayer(selectMapPosition, PlayerCharaType::NOEL);
						break;
					case PlayerCharaType::RACHEL:
						GameManager::totalSummonPoint -= charaCost[i];
						GameManager::MakePlayer(selectMapPosition, PlayerCharaType::RACHEL);
						break;
					case PlayerCharaType::JIN:
						GameManager::totalSummonPoint -= charaCost[i];
						GameManager::MakePlayer(selectMapPosition, PlayerCharaType::JIN);
						break;
					default:
						break;
					}
					GameManager::map.SetCharaMakeMapChipType(CharaMakeMapChipType::CHARA_MAKED, selectMapPosition);
					isTouchCharaMakeMapChip = false;
					isSelectSetPlayer = false;
					isSummon = true;
					summonEffectPos = selectMapPosition;
					mediaManager.Find("Pop")->play();
					mediaManager.Find("Summon")->play();
					mediaManager.Find("Summon")->gain(0.4f);
					mediaManager.Find("Summon")->pitch(1.8f);
				}

			}
		}
		else if (GameManager::map.CheckCharaMakeMapChip(selectMapPosition) == CharaMakeMapChipType::CHARA_MAKED)
		{
			if (GameManager::totalSummonPoint >= selectCharaStatus.nextSummonPoint
				&& Env().isPushButton(Mouse::LEFT) && isHitMouseToBox(levelUpUI.Position(), levelUpUI.Size(), mousePosition) == true
				&& selectCharaStatus.level < PLAYER_MAX_LEVEL)
			{
				for (auto& player = GameManager::players.begin(); player != GameManager::players.end(); ++player)
				{
					if (selectMapPosition == player->Position())
					{
						player->LevelUp();
						mediaManager.Find("LevelUp")->play();
						GameManager::totalSummonPoint -= selectCharaStatus.nextSummonPoint;
						isTouchCharaMakeMapChip = false;
						isSelectSetPlayer = false;
					}
				}
			}

			if (Env().isPushButton(Mouse::LEFT) && isHitMouseToBox(resetSummonUI.Position(), resetSummonUI.Size(), mousePosition) == true)
			{
				for (auto& player = GameManager::players.begin(); player != GameManager::players.end(); ++player)
				{
					if (selectMapPosition == player->Position())
					{
						GameManager::totalSummonPoint += player->State().nowSummonPoint / 2;
						player = GameManager::players.erase(player);
						GameManager::map.SetCharaMakeMapChipType(CharaMakeMapChipType::CHARA_MAKE, selectMapPosition);
						isTouchCharaMakeMapChip = false;
						isSelectSetPlayer = false;
					}
				}
			}
		}
	}

}
コード例 #21
0
ファイル: DIVPRO_slow.cpp プロジェクト: alxsoares/OI
	State exp(int c0, int c1, int c2, int c3) {
		return State(n+1, a[0]+c0, a[1]+c1, a[2]+c2, a[3]+c3);
	}
コード例 #22
0
ファイル: Game.cpp プロジェクト: RevOliver/pioneer
Game::Game(Serializer::Reader &rd) :
	m_timeAccel(TIMEACCEL_PAUSED),
	m_requestedTimeAccel(TIMEACCEL_PAUSED),
	m_forceTimeAccel(false)
{
	// signature check
	for (Uint32 i = 0; i < strlen(s_saveStart)+1; i++)
		if (rd.Byte() != s_saveStart[i]) throw SavedGameCorruptException();

	// version check
	rd.SetStreamVersion(rd.Int32());
	fprintf(stderr, "savefile version: %d\n", rd.StreamVersion());
	if (rd.StreamVersion() != s_saveVersion) {
		fprintf(stderr, "can't load savefile, expected version: %d\n", s_saveVersion);
		throw SavedGameWrongVersionException();
	}

	Serializer::Reader section;

	// space, all the bodies and things
	section = rd.RdSection("Space");
	m_space.Reset(new Space(this, section));


	// game state and space transition state
	section = rd.RdSection("Game");

	m_player.Reset(static_cast<Player*>(m_space->GetBodyByIndex(section.Int32())));

	// hyperspace clouds being brought over from the previous system
	Uint32 nclouds = section.Int32();
	for (Uint32 i = 0; i < nclouds; i++)
		m_hyperspaceClouds.push_back(static_cast<HyperspaceCloud*>(Body::Unserialize(section, 0)));

	m_time = section.Double();
	m_state = State(section.Int32());

	m_wantHyperspace = section.Bool();
	m_hyperspaceProgress = section.Double();
	m_hyperspaceDuration = section.Double();
	m_hyperspaceEndTime = section.Double();


	// system political stuff
	section = rd.RdSection("Polit");
	Polit::Unserialize(section);


	// views
	LoadViews(rd);


	// lua
	section = rd.RdSection("LuaModules");
	Pi::luaSerializer->Unserialize(section);


	// signature check
	for (Uint32 i = 0; i < strlen(s_saveEnd)+1; i++)
		if (rd.Byte() != s_saveEnd[i]) throw SavedGameCorruptException();
}
コード例 #23
0
ファイル: solution.cpp プロジェクト: Jornason/DieHard
void OneDimSolve::HFlip() { hpol=-hpol; State(U,C,L); }
コード例 #24
0
PlatformGraphicsContext::PlatformGraphicsContext()
{
    m_stateStack.append(State());
    m_state = &m_stateStack.last();
}
コード例 #25
0
ファイル: solution.cpp プロジェクト: Jornason/DieHard
Real OneDimSolve::Solve(Real Y, Real X, Real Dev, int Lim)
{
   enum Loop { start, captured1, captured2, binary, finish };
   Tracer et("OneDimSolve::Solve");
   lim=Lim; Captured = false;
   if (Dev==0.0) Throw(SolutionException("Dev is zero"));
   L=0; C=1; U=2; vpol=1; hpol=1; y[C]=0.0; y[U]=0.0;
   if (Dev<0.0) { hpol=-1; Dev = -Dev; }
   YY=Y;                                // target value
   x[L] = X;                            // initial trial value
   if (!function.IsValid(X))
      Throw(SolutionException("Starting value is invalid"));
   Loop TheLoop = start;
   for (;;)
   {
      switch (TheLoop)
      {
      case start:
	 LookAt(L); if (Finish) { TheLoop = finish; break; }
	 if (y[L]>0.0) VFlip();               // so Y[L] < 0

         x[U] = X + Dev * hpol;
         if (!function.maxXinf && x[U] > function.maxX)
            x[U] = (function.maxX + X) / 2.0;
         if (!function.minXinf && x[U] < function.minX)
            x[U] = (function.minX + X) / 2.0;

	 LookAt(U); if (Finish) { TheLoop = finish; break; }
	 if (y[U] > 0.0) { TheLoop = captured1; Captured = true; break; }
	 if (y[U] == y[L])
	    Throw(SolutionException("Function is flat"));
	 if (y[U] < y[L]) HFlip();             // Change direction
	 State(L,U,C);
	 for (i=0; i<20; i++)
	 {
	    // cout << "Searching for crossing point\n";
	    // Have L C then crossing point, Y[L]<Y[C]<0
            x[U] = x[C] + Dev * hpol;
            if (!function.maxXinf && x[U] > function.maxX)
               x[U] = (function.maxX + x[C]) / 2.0;
            if (!function.minXinf && x[U] < function.minX)
               x[U] = (function.minX + x[C]) / 2.0;

	    LookAt(U); if (Finish) { TheLoop = finish; break; }
	    if (y[U] > 0) { TheLoop = captured2; Captured = true; break; }
	    if (y[U] < y[C])
	       Throw(SolutionException("Function is not monotone"));
	    Dev *= 2.0;
	    State(C,U,L);
	 }
	 if (TheLoop != start ) break;
	 Throw(SolutionException("Can't locate a crossing point"));

      case captured1:
	 // cout << "Captured - 1\n";
	 // We have 2 points L and U with crossing between them
	 Linear(L,C,U);                   // linear interpolation
					  // - result to C
	 LookAt(C); if (Finish) { TheLoop = finish; break; }
	 if (y[C] > 0.0) Flip();            // Want y[C] < 0
	 if (y[C] < 0.5*y[L]) { State(C,L,U); TheLoop = binary; break; }

      case captured2:
	 // cout << "Captured - 2\n";
	 // We have L,C before crossing, U after crossing
	 Quadratic(L,C,U);                // quad interpolation
					  // - result to L
	 State(C,L,U);
	 if ((x[C] - x[L])*hpol <= 0.0 || (x[C] - x[U])*hpol >= 0.0)
	    { TheLoop = captured1; break; }
	 LookAt(C); if (Finish) { TheLoop = finish; break; }
	 // cout << "Through first stage\n";
	 if (y[C] > 0.0) Flip();
	 if (y[C] > 0.5*y[L]) { TheLoop = captured2; break; }
	 else { State(C,L,U); TheLoop = captured1; break; }

      case binary:
	 // We have L, U around crossing - do binary search
	 // cout << "Binary\n";
	 for (i=3; i; i--)
	 {
	    x[C] = 0.5*(x[L]+x[U]);
	    LookAt(C); if (Finish) { TheLoop = finish; break; }
	    if (y[C]>0.0) State(L,U,C); else State(C,L,U);
	 }
	 if (TheLoop != binary) break;
	 TheLoop = captured1; break;

      case finish:
	 return x[Last];

      }
   }
}
コード例 #26
0
ファイル: data.cpp プロジェクト: ferustigris/code-generator
/*!\func
 * get state by id
 * \param no
 * \return no
 */
State Data::getState(const qint32 id) const
{
	if(states.contains(id))
		return states[id];
	else return State();
}
コード例 #27
0
ファイル: network_conn.cpp プロジェクト: wthnonck/tdtw
int CNetConnection::Feed(CNetPacketConstruct *pPacket, NETADDR *pAddr)
{
	int64 Now = time_get();
	m_LastRecvTime = Now;
	
	// check if resend is requested
	if(pPacket->m_Flags&NET_PACKETFLAG_RESEND)
		Resend();

	//
	if(pPacket->m_Flags&NET_PACKETFLAG_CONTROL)
	{
		int CtrlMsg = pPacket->m_aChunkData[0];
		
		if(CtrlMsg == NET_CTRLMSG_CLOSE)
		{
			if(net_addr_comp(&m_PeerAddr, pAddr) == 0)
			{
				m_State = NET_CONNSTATE_ERROR;
				m_RemoteClosed = 1;
				
				if(pPacket->m_DataSize)
				{
					// make sure to sanitize the error string form the other party
					char Str[128];
					if(pPacket->m_DataSize < 128)
						str_copy(Str, (char *)pPacket->m_aChunkData, pPacket->m_DataSize);
					else
						str_copy(Str, (char *)pPacket->m_aChunkData, sizeof(Str));
					str_sanitize_strong(Str);
					
					// set the error string
					SetError(Str);
				}
				else
					SetError("no reason given");
					
				if(g_Config.m_Debug)
					dbg_msg("conn", "closed reason='%s'", ErrorString());
			}
			return 0;			
		}
		else
		{
			if(State() == NET_CONNSTATE_OFFLINE)
			{
				if(CtrlMsg == NET_CTRLMSG_CONNECT)
				{
					// send response and init connection
					Reset();
					m_State = NET_CONNSTATE_PENDING;
					m_PeerAddr = *pAddr;
					m_LastSendTime = Now;
					m_LastRecvTime = Now;
					m_LastUpdateTime = Now;
					SendControl(NET_CTRLMSG_CONNECTACCEPT, 0, 0);
					if(g_Config.m_Debug)
						dbg_msg("connection", "got connection, sending connect+accept");			
				}
			}
			else if(State() == NET_CONNSTATE_CONNECT)
			{
				// connection made
				if(CtrlMsg == NET_CTRLMSG_CONNECTACCEPT)
				{
					SendControl(NET_CTRLMSG_ACCEPT, 0, 0);
					m_State = NET_CONNSTATE_ONLINE;
					if(g_Config.m_Debug)
						dbg_msg("connection", "got connect+accept, sending accept. connection online");
				}
			}
			else if(State() == NET_CONNSTATE_ONLINE)
			{
				// connection made
				/*
				if(ctrlmsg == NET_CTRLMSG_CONNECTACCEPT)
				{
					
				}*/
			}
		}
	}
	else
	{
		if(State() == NET_CONNSTATE_PENDING)
		{
			m_State = NET_CONNSTATE_ONLINE;
			if(g_Config.m_Debug)
				dbg_msg("connection", "connecting online");
		}
	}
	
	if(State() == NET_CONNSTATE_ONLINE)
	{
		AckChunks(pPacket->m_Ack);
	}
	
	return 1;
}
コード例 #28
0
// Copy constructor that copies the contents of the
// parameterized list of relationships into this neighborhood.
Neighborhood::Neighborhood(const vector<Relationship> &r)
{
    for (unsigned i = 0; i < r.size(); ++i)
        addNbr(r[i], State());
}
コード例 #29
0
ファイル: rx.c プロジェクト: gegel/pairphone
//*****************************************************************************
//receiving loop: grab 48KHz baseband samples from Line,
//demodulate, decrypt, decode, play 8KHz voice over Speaker
int rx(int typing)
{
 //input: -1 for no typing chars, 1 - exist some chars in input buffer
 //output: 0 - no any jobs doing, 1 - some jobs were doing
 int i;
 float f;
 int job=0; //flag of any job were doing 
 char lag_flag=0; //block lag is locked (modems synchronization complete)
 //char lock_flag=0; //phase of carrier (1333Hz, 6 samples per period) is locked
 //char sync_flag=0; //the difference of frequency transmitter-to-receiver sampling rate is locked
 //char current_lag=0;  //block lag (0-90, aligned to last bit position, the 6 samples for bit)

 char info[8]={0}; //call info

 //regularly play Speaker's buffer
 job=playjit(); //the first try to play a tail of samples in buffer
 //check for we have enough samples for demodulation
 if(cnt<180*6) //check we haven't enough of unprocessed samples
 {
  //move tail to start of receiving buffer
  if(samples>speech) //check for tail
  {
   for(i=0; i<cnt; i++) speech[i]=samples[i]; //move tail to start of buffer
   samples=speech; //set pointer to start of buffer
  }
  //record
  i=_soundgrab((char*)(samples+cnt), 180*6);  //try to grab new 48KHZ samples from Line

  if((i>0)&&(i<=(180*6))) //some samples grabbed
  {
   cnt+=i;  //add grabbed  samples to account
   job+=4;  //set job
  }
 }
 else //we have enough samples for processing
 {
  i=Demodulate(samples, buf); //process samples: 36*6 (35-37)*6 samples
  samples+=i; //move pointer to next samples (with frequency adjusting)
  cnt-=i; //decrease the number of unprocessed samples
  if(0x80&buf[11]) //checks flag for output data block is ready
  {
   //check for synck and averages BER
   lag_flag=!(!(buf[11]&0x40)); //block lag is locked (synchronization compleet)
   //lock_flag=!(!(buf[11]&0x20)); //phaze of carrier (1333Hz, 6 samples per period) is locked
   //sync_flag=!(!(buf[11]&0x10)); //the differency of frequency transmitter-to-receiver sampling rate is locked
   //current_lag=buf[10]>>1;  //block lag (0-90, aligned to last bit position, the 6 samples for bit)
   if(lag_flag) //check modem sync
   {
    //averages BER
    i=(0x0F&buf[11]); //count symbols errors (only 1 error per 9-bit symbol can be detected)
    fber*=0.99; //fber in range 0-900
    fber+=i;  //in range 0-9 errored bits per 90 bits treceived
   }
   //output statistics
   if(typing<0) //output call's info if no characters were typed by user
   {
    f=Mute(0);   //get packets counter value
    i=State(0); //get current connection step * vad flag 
	
	//notification of state and voice output 
    if(!i) strcpy(info, (char*)"IDLE"); 
    else if(abs(i)<8) strcpy(info, (char*)"CALL");  
    else if(f<=0) strcpy(info, (char*)"MUTE");
    else if(i<0) strcpy(info, (char*)"PAUS");
    else strcpy(info, (char*)"TALK");

    if(f<0) f=-f; //absolute value
    i=f*0.0675; //computes total time of the call in sec: each packet 67,5 ms

    f=fau/4-100; //computes authentification level in %
    if(f<0) f=0; //only positive results have reason
    //current state notification
    if(lag_flag) printf("%s %dmin %dsec BER:%0.02f AU:%d%%\r", info, i/60, i%60, fber/90, (int)f);
    else printf("%s %dmin %dsec BER:---- AU:%d%%\r", info, i/60, i%60, (int)f); //lost of sync in modem
   }

   //process received packet detects voice/silence type
   buf[11]=0xFE; //set flag default as for silence descriptor
   if(lag_flag) //check modem sync
   {
    i=ProcessPkt(buf);  //decode received packet
    if(i>=0) //received packet is a control type
    {
     fau*=0.99;  //fau in range 0-800 (400 for random data)
     fau+=i; //averages authentication level
    }
    else if(i==-3) 
	{
	 buf[11]=0xFF; //set flag for voice data received 
	}
   } //end of sync ok, packets processing
  } //end of data block received
 } //end of a portion of sampless processing

 //check we have received data and output buffer is empty for decoding
 if((0x0E&buf[11])&&(l_jit_buf<=180))
 {
  //decode voice data or set silency
  job+=16; //set job
  if(1&buf[11]) //this is a voice frame, decode it
  {
   melpe_s(sp, buf); //decode 81 bits in 11 bytes to 540 8KHz samples 
  }
  else memset(sp, 0, 1080); //or output 67.5 mS of silence
  buf[11]=0; //clears flag: data buffer is processed

  //computes average playing delay
  i=getdelay()+l_jit_buf; //total number of unplayed samples in buffers
  fdelay*=0.9; //averages
  fdelay+=i;
  //computes optimal resapling ratio for the optimum delay
  f=fabs(fdelay/10-720)/10000000; //correction rate due inconsistency
  if(i<360) qff-=f;  //adjust current ratio
  else if(i>1080) qff+=f;
  if(qff<0.888) qff=0.888; //restrictions
  else if(qff>1.142) qff=1.142;

  //resample and play to Headset
  if(l_jit_buf>180) l_jit_buf=0; //prevent overflow
  l_jit_buf+=resample(sp, jit_buf+l_jit_buf, qff); //resample buffer for playing
  playjit(); //immediately try to play buffer
 }
 return job;
}
コード例 #30
0
void makeTable(const Keyword keywords[])
{
    int i,c;
    bool pre = (keywords == pp_keywords);
    QList<State> states;
    states += State(pre?"PP_NOTOKEN":"NOTOKEN");

    // identifiers
    for (c = 'a'; c <= 'z'; ++c)
        newState(states, pre?"PP_CHARACTER":"CHARACTER", c);
    for (c = 'A'; c <= 'Z'; ++c)
        newState(states, pre?"PP_CHARACTER":"CHARACTER", c);

    newState(states, pre?"PP_CHARACTER":"CHARACTER", '_');
    newState(states, pre?"PP_CHARACTER":"CHARACTER", '$');

    // add digits
    for (c = '0'; c <= '9'; ++c)
        newState(states, pre?"PP_DIGIT":"DIGIT", c);

    // keywords
    for (i = 0; keywords[i].lexem; ++i)
        newState(states, keywords[i].token, keywords[i].lexem, pre);

    // some floats
    for (c = '0'; c <= '9'; ++c)
        newState(states, pre?"PP_FLOATING_LITERAL":"FLOATING_LITERAL",
                 QByteArray(".") + char(c), pre);

    // simplify table with default transitions
    int transindex = -1;
    for (i = 0; i < states.size(); ++i) {
        int n = 0;
        int defchar = -1;
        for (c = 0; c < 128; ++c)
            if (states[i].next[c]) {
                ++n;
                defchar = c;
            }
        if (!n)
            continue;
        if (n == 1) {
            states[i].defnext = states[i].next[defchar];
            states[i].defchar = defchar;
            continue;
        }
        states[i].nextindex = ++transindex;
    }

#if 1
    // compress table
    int j, k;
    for (i = 0; i < states.size(); ++i) {
        for (j = i + 1; j < states.size(); ++j) {
            if ( states[i] == states[j] ) {
                for (k = 0; k < states.size(); ++k) {
                    if (states[k].defnext == j)
                        states[k].defnext = i;
                    if (states[k].defnext > j)
                        --states[k].defnext;
                    for (c = 0; c < 128; ++c) {
                        if (states[k].next[c] == j)
                            states[k].next[c] = i;
                        if (states[k].next[c] > j)
                            --states[k].next[c];
                    }
                }
                states.removeAt(j);
                --j;
            }
        }
    }
#endif
    printf("static const short %skeyword_trans[][128] = {\n",
           pre?"pp_":"");
    for (i = 0; i < states.size(); ++i) {
        if (i && !states[i].nextindex)
            continue;
        printf("%s    {", i?",\n":"");
        for (c = 0; c < 128; ++c)
            printf("%s%s%d",
                   c?",":"",
                   (!c || c%16)?"":"\n     ",
                   states[i].next[c]
                  );
        printf("}");
    }
    printf("\n};\n\n");

    printf("static const struct\n{\n"
           "   %sToken token;\n"
           "   short next;\n"
           "   char defchar;\n"
           "   short defnext;\n"
           "   %sToken ident;\n"
           "} %skeywords[] = {\n",
           pre ? "PP_":"",
           pre ? "PP_":"",
           pre ? "pp_":"");
    for (i = 0; i < states.size(); ++i) {
        printf("%s    {%s, %d, %d, %d, %s}",
               i?",\n":"",
               states[i].token.data(),
               states[i].nextindex,
               states[i].defchar,
               states[i].defnext,
               states[i].ident?states[i].ident:(pre?"PP_NOTOKEN":"NOTOKEN"));
    }
    printf("\n};\n");
}