Ejemplo n.º 1
0
sequence_in_t TeacherBB::equivalenceQuery(const unique_ptr<DFSM>& conjecture) {
	_equivalenceQueryCounter++;
	auto tmp = _currState;
	auto model = FSMmodel::duplicateFSM(conjecture);
	if (!model->isReduced()) model->minimize();
	for (state_t extraStates = 0; extraStates < _maxExtraStates; extraStates++) {
		auto TS = _testingMethod(model, extraStates);
		for (const auto& test : TS) {
			auto bbOut = resetAndOutputQuery(test);
			_outputQueryCounter--;
			sequence_out_t modelOut;
			state_t state = 0;
			for (const auto& input : test) {
				auto ns = model->getNextState(state, input);
				if ((ns != NULL_STATE) && (ns != WRONG_STATE)) {
					modelOut.emplace_back(model->getOutput(state, input));
					state = ns;
				}
				else modelOut.emplace_back(WRONG_OUTPUT);
			}
			if (bbOut != modelOut) {
				_currState = tmp;
				return test;
			}
		}
	}
	_currState = tmp;
	return sequence_in_t();
}
Ejemplo n.º 2
0
bool PlaceableWindowProxy::handleMousePress(QMouseEvent *event)
{
  if (!visible_)
  {
    return false;
  }

  if (!rect_.contains(event->pos()))
  {
    // We don't care about anything outside the rect.
     return false;
  }

  if (state_ != INACTIVE)
  {
    // We're already doing something, so we don't want to enter
    // another state.  But we also don't want someone else to start
    // doing something, so we filter out the press.
    return true;
  }
  
  if (event->button() == Qt::LeftButton)
  {
    start_rect_ = rect_;
    start_point_ = event->pos();
    state_ = getNextState(event->localPos());
    qWarning("changing state to %d", state_);
    return true;
  }

  // Event if we're not doing anything, we want to present a
  // consistent interface that says "this region is belongs to me", so
  // we filter out events.
  return true;
}
Ejemplo n.º 3
0
void
Grammar::findStates( void )
{
	Symbol *startSym = getStartSymbol( true );

	if ( ! startSym )
	{
		Error::get()->add( "No rules to choose as start rule." );
		return;
	}

	if ( RuleTable::get()->isOnRightSide( startSym->getName() ) )
	{
		Error::get()->add( "The start symbol \"%s\" occurs on the "
						   "right-hand side of a rule. This will result "
						   "in a parser which does not work properly.",
						   startSym->getName().c_str() );
	}

	myCurConfigList.reset();

	Rule	*startRule = RuleTable::get()->findFirstRule( startSym->getName() );
	while ( startRule )
	{
		Config *tmpCfg = myCurConfigList.addWithBasis( startRule, 0 );

		// All start rules have the start symbol as their left hand side
//		tmpCfg->addFollowSet( startSym->getName() );
		tmpCfg->addFollowSet( SymbolTable::get()->getNthSymbol( 0 )->getName() );

		startRule = RuleTable::get()->getNextRule( startRule );
	}

	getNextState();
}
/* Add new entry to the table
 * Once a state is added here, we are the owners of the memory, so
 * we will destroy the States when this table is destroyed
 */
void MainTransitionFunction::addNewEntry(IMainState *from,
		MainMachineEvent event, IMainState *to)
{
	// check if exists?
	ASSERT(getNextState(from, event) == 0);
	mTable[from].insert(std::pair<MainMachineEvent, IMainState *>(event, to));
}
Ejemplo n.º 5
0
le_int32 ThaiShaping::compose(const LEUnicode *input, le_int32 offset, le_int32 charCount, le_uint8 glyphSet,
                          LEUnicode errorChar, LEUnicode *output, LEGlyphStorage &glyphStorage)
{
    le_uint8 state = 0;
    le_int32 inputIndex;
    le_int32 outputIndex = 0;
    le_uint8 conState = 0xFF;
    le_int32 conInput = -1;
    le_int32 conOutput = -1;

    for (inputIndex = 0; inputIndex < charCount; inputIndex += 1) {
        LEUnicode ch = input[inputIndex + offset];
        le_uint8 charClass;

        // Decompose SARA AM into NIKHAHIT + SARA AA
        if (ch == CH_SARA_AM && isLegalHere(ch, state)) {
            outputIndex = conOutput;
            state = getNextState(CH_NIKHAHIT, conState, inputIndex, glyphSet, errorChar, charClass,
                output, glyphStorage, outputIndex);

            for (int j = conInput + 1; j < inputIndex; j += 1) {
                ch = input[j + offset];
                state = getNextState(ch, state, j, glyphSet, errorChar, charClass,
                    output, glyphStorage, outputIndex);
            }

            ch = CH_SARA_AA;
        }

        state = getNextState(ch, state, inputIndex, glyphSet, errorChar, charClass,
            output, glyphStorage, outputIndex);

        if (charClass >= CON && charClass <= COD) {
            conState = state;
            conInput = inputIndex;
            conOutput = outputIndex;
        }
    }

    return outputIndex;
}
void CloudsTransitionController::update() {
	if(transitioning){
		
		transitionPercent = ofMap(ofGetElapsedTimef(), currentQueue.startTime, currentQueue.endTime, 0.0, 1.0, true);
		
		//started next state
		if(transitionPercent >= 1.0){
            transitionPercent = 0.0;
			getNextState();
		}
	}
}
Ejemplo n.º 7
0
void
Grammar::buildShifts( State *state )
{
	Config *cfp;

	// Each configuration becomes complete after it contibutes to a successor
	// state.  Initially, all configurations are incomplete
	for ( cfp = state->getConfig(); cfp; cfp = cfp->getNext() )
		cfp->setStatus( Config::INCOMPLETE );

	// Loop through all configs of state
	for ( cfp = state->getConfig(); cfp; cfp = cfp->getNext() )
	{
		if ( cfp->getStatus() == Config::COMPLETE )
			continue;

		const Rule::RHSList &rhs = cfp->getRule()->getRHS();

		if ( cfp->getDot() >= int( rhs.size() ) )
			continue;

		myCurConfigList.reset();

		// Symbol after the dot
		// for all configs in the state which have the symbol rhs[dot]
		// following it's dot, add the same config to the basis set under
		// construction but with the dot shifted one symbol to the right.
		for ( Config *bcfp = cfp; bcfp; bcfp = bcfp->getNext() )
		{
			if ( bcfp->getStatus() == Config::COMPLETE )
				continue;

			const Rule::RHSList &brhs = bcfp->getRule()->getRHS();
			if ( bcfp->getDot() >= int( brhs.size() ) )
				continue;

			if ( rhs[cfp->getDot()].first != brhs[bcfp->getDot()].first )
				continue;

			bcfp->setStatus( Config::COMPLETE );

			Config *cfg = myCurConfigList.addWithBasis( bcfp->getRule(),
														bcfp->getDot() + 1 );

			cfg->addBackwardPropLink( bcfp );
		}

		State *newstp = getNextState();

		// Add shift action to reach state newstp from state on symbol...
		state->addAction( Action::SHIFT, rhs[cfp->getDot()].first, newstp, 0 );
	}
}
CharacterState *CharacterState::playState(Character *character)
{
	/*TTODO:
	if(curWarmUpTime > warmUpTime && !actionDone) doAction();
	if(curExecutionTime < executionTime) {
		return false;
	} else {
		return true;
	}*/

	if (doAction(character)) {
		return getNextState();
	}

	return this;
}
Ejemplo n.º 9
0
int main(int argc, char* argv[]) {

    DDRC = 0x0f;
    DDRD = 0xf0;
    DDRB = 0xC3;
    PORTB = 0;
    PORTC = 0;
    PORTD = 0;
    serial_init();
    send_string_serial("Starting up...\n");
    _delay_ms(500);

    speed1 = 4000;
    speed2 = 4000;
    speed3 = 4000;
    speed4 = 1250;
    counter1 = 1;
    counter2 = 1;
    counter3 = 1;
    counter4 = 1;

    needState1 = FALSE;
    needState2 = FALSE;
    needState3 = FALSE;

    movingForward1 = FALSE;
    movingForward2 = FALSE;
    movingForward3 = FALSE;

    currentState1 = 0;
    currentState2 = 0;
    currentState3 = 0;

    motorState1 = getMotorState(currentState1);
    motorState2 = getMotorState(currentState2) << 4;
    unsigned char state = getMotorState(currentState3);
    motorState3 = ((state & 0x0C) << 4) | (state & 0x03);

    setupTimers();

	char index = 0;
	int speeds[3];
	char* buffer = (char*) speeds;

    while (1) {
		if  (UCSRA & (1<<RXC)) {
			buffer[index++] = UDR;
			
			if (index == 6) {
				// do something with the buffer
				setSpeed1(speeds[0]);
				setSpeed2(speeds[1]);
				setSpeed3(speeds[2]);
				index = 0;
				send_string_serial("Received full message\n\r");
			}
		}

        checkSerialSend();
        if (needState1) {
            currentState1 = getNextState(currentState1, movingForward1);
            motorState1 = getMotorState(currentState1);
            needState1 = FALSE;
        }
        if (needState2) {
            currentState2 = getNextState(currentState2, movingForward2);
            motorState2 = getMotorState(currentState2) << 4;
            needState2 = FALSE;
        }
        if (needState3) {
            currentState3 = getNextState(currentState3, movingForward3);
            state = getMotorState(currentState3);
            motorState3 = ((state & 0x0C) << 4) | (state & 0x03);
            needState3 = FALSE;
        }
/*
        if (needsNewSpeed) {
            currentSpeedIndex = (currentSpeedIndex + 1);
            if (currentSpeedIndex == 0x40) {
                currentSpeedIndex = 0;
                send_string_serial("Loop...\n");
            }
            setSpeed1(speed[0][currentSpeedIndex]);
            setSpeed2(speed[1][currentSpeedIndex]);
            setSpeed3(speed[2][currentSpeedIndex]);
            needsNewSpeed = FALSE;
        }
*/
    }

	return 0;
}
void CloudsTransitionController::startTransition(){
	transitioning = true;
	getNextState();
    update();
}
Ejemplo n.º 11
0
int main()
{
  int i; //for 'for' loops

  //level to stop splitting
  int L, L1; //this means each state has L leaves resulting from k splits
  cout << "Number of splits? ";
  cin >> L1;
  L = L1 + 1;

  //number of splits
  int k;

  //number of distinct states or Catalan number
  long double Csplit[L];

  //total number of possible paths to reach any state at level L
  unsigned long int totalPaths[L];

  //container for states
  States currStates, nextStates;
  States::iterator iterCurrStates;
  State currState, nextState;
  State::iterator iterCurrState;

  // a map for the Catalan Coefficients
  typedef map<State, int, LexicoSorting<State> > StatesMap;
  StatesMap StateCount;
  StatesMap::iterator iterStateCount;
  std::pair<StatesMap::iterator, bool> boolStateCount;

  //state space at 0 split
  State state0;
  state0.push_back(0);

  StateCount.insert(make_pair(state0,1));

  Csplit[0]=1;
  totalPaths[0]=1;

  //ofstream to output CatalanCoefficient and CatalanFrequencies to .txt.
  ofstream oss;

  clock_t start, end;
  double timeTaken;

  //Loop to get Catalan coefficients and frequencies using L-R leaf-depth encoding
  for (k=1; k < L; k++)  //for a given number of splits
  {
    //Set up string for filename to output the Catalan coefficients and frequencies
    string fileNameCC, fileNameCF;
    fileNameCC = "CatalanCoefficientSplit";
    fileNameCF = "CatalanFrequencySplit";
    std::ostringstream stm1;  //convert k to std::ostringstream

    start=clock();  //record the time taken to get the Catalan coefficient and frequencies 

    //Get number of nodes, Catalan number and total possible paths for each split
    Csplit[k] = Catalan(k); 
    totalPaths[k] = factorial(k);
    cout << "========================================" << endl;
    cout << "At " << k << " splits:" << endl;
    cout << Csplit[k] << " distinct states " << "\t" << totalPaths[k] << " possible paths " << endl;

    //Set up an empty map to store new states
    StatesMap newStateCount;
    StatesMap::iterator iterNewStateCount;
    std::pair<StatesMap::iterator, bool> boolNewStateCount;

    //for each state in current states map, StateCount
    for (iterStateCount=StateCount.begin(); iterStateCount != StateCount.end(); iterStateCount++)
    {
      currState = iterStateCount->first;  //current state in current states map
      //cout << "Current state:" << getStringState(currState) << endl;

      //for each node in current state
      for(int node = 0; node < currState.size(); node++)
      {
	//get state for each node in current state
	nextState = getNextState(currState, node);
	//cout << "Next state: " << getStringState(nextState) << endl;

	//insert the new state into newStateMap
	boolNewStateCount = newStateCount.insert(make_pair(nextState, 1));
	//Check if insertion is successful - a unique set will render a successful insertion.
	if(!(boolNewStateCount.second)) //if state is not unique
	{
	  //increment by the Catalan coefficient of the current state producing this next state
          newStateCount[nextState] += StateCount[currState];	
	  //cout << "this state already exist"  << endl;
	}  //end of "non-unique state"
	else
	{
          //set the count of this next state as the Catalan coefficient of current state
          newStateCount[nextState] = StateCount[currState];
          //cout << "this is a unique state" << endl;
	}  //end of "unique state"
      } //end of looping over node in current state
    } //end of looping through all Ck states in current states map

    cout << "There are " << newStateCount.size() << endl;
    //cout << " distinct states with the following breakdown:" << endl; 

    //Catalan Coefficients
    //Output states with corresponding counts in .txt.
    stm1 << k; //name file according to the number of splits k
    fileNameCC += stm1.str();
    fileNameCC += ".txt";
    oss.open(fileNameCC.c_str());

    //set up a vector for the number of paths leading to each state in newStateCount
    vector<int> StatePathVec;
    vector<int>::iterator iterStatePathVec;

    //set up a map for the frequencies corresponding to state paths
    map<int, int, less<int> > StateFreqMap;
    map<int, int, less<int> >::iterator iterStateFreqMap;
    std::pair<map<int, int, less<int> >::iterator, bool> boolStateFreqMap;
    int Path;

    for(iterNewStateCount=newStateCount.begin(); 
        iterNewStateCount != newStateCount.end(); iterNewStateCount++)
    {
      State thisState = iterNewStateCount->first;
      //cout << getStringState(thisState) << "\t\t" << iterNewStateCount->second << endl;
      oss << getStringState(thisState) << "\t" << (iterNewStateCount->second)<< "\n";

      //Find frequencies for state paths
      Path = iterNewStateCount->second;
      boolStateFreqMap = StateFreqMap.insert(make_pair(Path, 1));

      if (!(boolStateFreqMap.second)) //if there is more than one state with Path
      {
        StateFreqMap[Path] += 1;
      }
    }

    //close ostream for CatalanCoefficientSplitk.txt
    oss << flush;
    oss.close();
    cout << "State counts output to " << fileNameCC << endl;


    //output Catalan Frequencies to.txt
    fileNameCF += stm1.str();
    fileNameCF += ".txt";
    oss.open(fileNameCF.c_str());
    oss << "Paths" << "\t\t" << "States" << "\n";
    //Output to .txt
    for (iterStateFreqMap = StateFreqMap.begin(); iterStateFreqMap != StateFreqMap.end(); iterStateFreqMap++)
    {
      //cout << "There are " << iterStateFreqMap->second << " states with " 
      //     << iterStateFreqMap->first << " paths." << endl;
      oss << iterStateFreqMap->first << "\t\t" << iterStateFreqMap->second << "\n";
    }

    oss << flush;
    oss.close();
    cout << "State frequencies output to " << fileNameCF << endl;


    //Empty current states map
    StateCount.clear();

    if ( StateCount.empty())
    {
      //set nextStateCount map to be StateCount to continue loop
      //cout << "space emptied" << endl;
      StateCount = newStateCount;
    }
    else
    {
      cout << "space not emptied. Should not proceed." << endl;
      break;
    }

    end=clock();
    timeTaken = static_cast<double>(end-start)/CLOCKS_PER_SEC;
    cout << "Computing time : " <<timeTaken<< " s." << endl;
  }

  return 0;
}
status_t OMXCameraAdapter::doAutoFocus()
{
    status_t ret = NO_ERROR;
    OMX_ERRORTYPE eError = OMX_ErrorNone;
    OMX_IMAGE_CONFIG_FOCUSCONTROLTYPE focusControl;
    OMX_PARAM_FOCUSSTATUSTYPE focusStatus;
    OMX_CONFIG_BOOLEANTYPE bOMX;
    nsecs_t timeout = 0;

    LOG_FUNCTION_NAME;

    if ( OMX_StateInvalid == mComponentState )
      {
        CAMHAL_LOGEA("OMX component in Invalid state");
        returnFocusStatus(false);
        return -EINVAL;
      }

    if ( OMX_StateExecuting != mComponentState )
        {
        CAMHAL_LOGEA("OMX component not in executing state");
        returnFocusStatus(false);
        return NO_ERROR;
        }


    if( ((AF_ACTIVE & getState()) != AF_ACTIVE) && ((AF_ACTIVE & getNextState()) != AF_ACTIVE) ) {
       CAMHAL_LOGDA("Auto focus got canceled before doAutoFocus could be called");
       return NO_ERROR;
    }

    OMX_INIT_STRUCT_PTR (&focusStatus, OMX_PARAM_FOCUSSTATUSTYPE);

    // If the app calls autoFocus, the camera will stop sending face callbacks.
    pauseFaceDetection(true);

    // This is needed for applying FOCUS_REGION correctly
    if ( (!mFocusAreas.isEmpty()) && (!mFocusAreas.itemAt(0)->isZeroArea()))
    {
    //Disable face priority
    setAlgoPriority(FACE_PRIORITY, FOCUS_ALGO, false);

    //Enable region algorithm priority
    setAlgoPriority(REGION_PRIORITY, FOCUS_ALGO, true);
    }

    OMX_INIT_STRUCT_PTR (&focusControl, OMX_IMAGE_CONFIG_FOCUSCONTROLTYPE);
    focusControl.eFocusControl = ( OMX_IMAGE_FOCUSCONTROLTYPE ) mParameters3A.Focus;

    if (mParameters3A.FocusLock) {
        // this basically means user never called cancelAutoFocus after a scan...
        // if this is the case we need to unlock AF to ensure we will do a scan
        if (set3ALock(mUserSetExpLock, mUserSetWbLock, OMX_FALSE) != NO_ERROR) {
            CAMHAL_LOGEA("Error Unlocking 3A locks");
        } else {
            CAMHAL_LOGDA("AE/AWB unlocked successfully");
        }

    } else if ( mParameters3A.Focus == OMX_IMAGE_FocusControlAuto ) {
        // In case we have CAF running we should first check the AF status.
        // If it has managed to lock, then do as usual and return status
        // immediately.
        ret = checkFocus(&focusStatus);
        if ( NO_ERROR != ret ) {
            CAMHAL_LOGEB("Focus status check failed 0x%x!", ret);
            return ret;
        } else {
            CAMHAL_LOGDB("Focus status check 0x%x!", focusStatus.eFocusStatus);
        }
    }

    if ( (focusControl.eFocusControl == OMX_IMAGE_FocusControlAuto &&
         ( focusStatus.eFocusStatus == OMX_FocusStatusRequest ||
           focusStatus.eFocusStatus == OMX_FocusStatusUnableToReach ||
           focusStatus.eFocusStatus == OMX_FocusStatusLost ) ) ||
            (mParameters3A.Focus !=  (OMX_IMAGE_FOCUSCONTROLTYPE)OMX_IMAGE_FocusControlAuto) )
        {
        OMX_INIT_STRUCT_PTR (&bOMX, OMX_CONFIG_BOOLEANTYPE);
        bOMX.bEnabled = OMX_TRUE;

        //Enable focus scanning
        eError = OMX_SetConfig(mCameraAdapterParameters.mHandleComp,
                               (OMX_INDEXTYPE)OMX_TI_IndexConfigAutofocusEnable,
                               &bOMX);

        // force AF, Ducati will take care of whether CAF
        // or AF will be performed, depending on light conditions
        if ( focusControl.eFocusControl == OMX_IMAGE_FocusControlAuto &&
             ( focusStatus.eFocusStatus == OMX_FocusStatusUnableToReach ||
               focusStatus.eFocusStatus == OMX_FocusStatusLost ) ) {
            focusControl.eFocusControl = OMX_IMAGE_FocusControlAutoLock;
        }

        if ( focusControl.eFocusControl != OMX_IMAGE_FocusControlAuto )
            {
            eError =  OMX_SetConfig(mCameraAdapterParameters.mHandleComp,
                                    OMX_IndexConfigFocusControl,
                                    &focusControl);
            }

        if ( OMX_ErrorNone != eError ) {
            CAMHAL_LOGEB("Error while starting focus 0x%x", eError);
            return INVALID_OPERATION;
        } else {
            CAMHAL_LOGDA("Autofocus started successfully");
        }

        // configure focus timeout based on capture mode
        timeout = (mCapMode == VIDEO_MODE) ?
                        ( ( nsecs_t ) AF_VIDEO_CALLBACK_TIMEOUT * 1000 ) :
                        ( ( nsecs_t ) AF_IMAGE_CALLBACK_TIMEOUT * 1000 );

            {
            Mutex::Autolock lock(mDoAFMutex);
            ret = mDoAFCond.waitRelative(mDoAFMutex, timeout);
            }

        //If somethiing bad happened while we wait
        if (mComponentState == OMX_StateInvalid) {
          CAMHAL_LOGEA("Invalid State after Auto Focus Exitting!!!");
          return -EINVAL;
        }

        if(ret != NO_ERROR) {
            CAMHAL_LOGEA("Autofocus callback timeout expired");
            ret = returnFocusStatus(true);
        } else {
            ret = returnFocusStatus(false);
        }
    } else { // Focus mode in continuous
        if ( NO_ERROR == ret ) {
            ret = returnFocusStatus(true);
            mPending3Asettings |= SetFocus;
        }
    }

    LOG_FUNCTION_NAME_EXIT;

    return ret;
}
Ejemplo n.º 13
0
void LitResDataParser::endElementHandler(const char *tag) {
	processState(tag, true, 0);
	myState = getNextState(tag, true);
	myBuffer.clear();
}
Ejemplo n.º 14
0
void LitResDataParser::startElementHandler(const char *tag, const char **attributes) {
	processState(tag, false, attributes);
	myState = getNextState(tag, false);
	myBuffer.clear();
}
Ejemplo n.º 15
0
ArrowMap::ArrowMap(const std::string &networkFilePath)
{
    //Unpack information from file
    numNodes = 0;
    unsigned int *ancLengths;
    unsigned int **structure;
    unsigned int *lutLengths;
    bool **nodeLUTs;
    char buf[2]; 
    
    std::ifstream networkFile;
    networkFile.open(networkFilePath.c_str(), std::ios::binary);
    
    if (!networkFile.is_open())
        throw "File not found.";
    
    networkFile.read(buf, 2);
    numNodes = buf[0] << 8 | buf[1];
    ancLengths = new unsigned int[numNodes];
    structure = new unsigned int*[numNodes];
    nodeLUTs = new bool*[numNodes];
    lutLengths = new unsigned int[numNodes];
    for (int i = 0; i < numNodes; i++)
    {
        networkFile.read(buf, 1);
        ancLengths[i] = buf[0];
        //networkFile.read((char*)&ancLengths[i], 1);
        structure[i] = new unsigned int[ancLengths[i]];
        for (int j = 0; j < ancLengths[i]; j++)
        {
            networkFile.read(buf, 2);
            structure[i][j] = buf[0] << 8 | buf[1];
        }
        
        lutLengths[i] = 1 << ancLengths[i];
        nodeLUTs[i] = new bool[lutLengths[i]];
        for (int j = 0; j < lutLengths[i]; j++)
        {
            if (j % 8 == 0)
                networkFile.read(buf, 1);
            
            nodeLUTs[i][j] = buf[0] >> (7-j%8) & 1;
        }
    }
    
    /*std::cout << numNodes << "\n\n";
    for (int i = 0; i < numNodes; i++)
    {
        std::cout << ancLengths[i] << "\n";
        for (int j = 0; j < ancLengths[i]; j++)
            std::cout << structure[i][j] << "\n";
        std::cout << lutLengths[i] << "\n";
        for (int j = 0; j < lutLengths[i]; j++)
            std::cout << nodeLUTs[i][j] << " ";
        std::cout << "\n\n";
    }*/
    
    //Compute entire state space graph
    bool *states = new bool[numNodes];
    graphSize = 1 << numNodes;
    graph = new state[graphSize];
    for (unsigned int i = 0; i < graphSize; i++)
    {
        graph[i].attractor = false;
        
        for (int j = 0; j < numNodes; j++)
            states[numNodes - j - 1] = i >> j & 1;
        
        graph[i].id = 0;
        for (int j = 0; j < numNodes; j++)
        {
            int n = 0;
            for (int k = 0; k < ancLengths[j]; k++)
                n |= states[structure[j][k]] << k;
            graph[i].id <<= 1;
            graph[i].id |= nodeLUTs[j][n];
        }
    }
    
    delete [] states;
    for (int i = 0; i < numNodes; i++)
    {
        delete [] structure[i];
        delete [] nodeLUTs[i];
    }
    delete [] structure;
    delete [] nodeLUTs;
    delete [] ancLengths;
    delete [] lutLengths;
    
    
    //Determine which states are in attractors
    bool *done = new bool[graphSize];
    //bool *flipMap = new bool[graphSize];
    //bool lastFlip = false;
    unsigned int numRem = graphSize;
    unsigned int state = 0;
    //unsigned int numOn = 0;
    memset(done, false, graphSize * sizeof(bool));
    //memset(flipMap, false, graphSize * sizeof(bool));
    while (numRem > 0)
    {
        //Fall into attractor
        for (int i = 0; i < 100; i++) //DEBUG: Fix this later!!!
        {
            if (done[state] == false)
                numRem--;
            done[state] = true;
            state = getNextState(state);
        }
        /*while (true)
        {
            done[state] = true;
            numRem--;
            flipMap[state] = !flipMap[state];
            if (lastFlip != flipMap[state])
                break;
            
            lastFlip = flipMap[state];
            state = getNextState(state);
            //std::cout << state << std::endl;
            //std::cout << getNextState(state) << std::endl;
        }*/

        /*while (!done[state])
        {
            done[state] = true;
            numRem--;
            state = getNextState(state);
            std::cout << state << std::endl;
            std::cout << getNextState(state) << std::endl;
        }*/
        
        //Run around attractor once
        while(!graph[state].attractor)
        {
            graph[state].attractor = true;
            state = getNextState(state);
        }
        
        for (state = 0; state < graphSize-1 && done[state]; state++);
        
        //std::cout << "\n";
    }
    delete [] done;
    //delete [] flipMap;
}
Ejemplo n.º 16
0
bool PlaceableWindowProxy::handleMouseMove(QMouseEvent *event)
{
  if (!visible_)
  {
    return false;
  }

  if (state_ == INACTIVE)
  {
    if (!rect_.contains(event->localPos()))
    {
      if (has_cursor_)
      {
        QApplication::restoreOverrideCursor();
        has_cursor_ = false;
      }
      return false;
    }    

    // The mouse cursor is over the rect, so we're going to change the
    // cursor to indicate the state the user would enter by clicking.

    Qt::CursorShape shape;
    switch(getNextState(event->localPos())) 
    {
    case MOVE_TOP_LEFT:
    case MOVE_BOTTOM_RIGHT:
      shape = Qt::SizeFDiagCursor;
      break;
    case MOVE_TOP_RIGHT:
    case MOVE_BOTTOM_LEFT:
      shape = Qt::SizeBDiagCursor;
      break;
    default:
      shape = Qt::SizeAllCursor;
    }

    if (has_cursor_)
    {
      QApplication::changeOverrideCursor(QCursor(shape));
    }
    else
    {
      QApplication::setOverrideCursor(QCursor(shape));
      has_cursor_ = true;
    }

    return true;
  }

  QPointF dp = event->localPos() - start_point_;

  // todo: enforce minimum size & constrain aspect ratio for resizes.  
  if (state_ == MOVE_ALL)
  {
    rect_ = start_rect_.translated(dp);    
  }
  else if (state_ == MOVE_TOP_LEFT)
  {
    rect_= resizeHelper(start_rect_,
                        start_rect_.bottomRight(),
                        start_rect_.topLeft(),
                        event->localPos());
    rect_.moveBottomRight(start_rect_.bottomRight());      
  }
  else if (state_ == MOVE_BOTTOM_LEFT)
  {
    rect_= resizeHelper(start_rect_,
                        start_rect_.topRight(),
                        start_rect_.bottomLeft(),
                        event->localPos());
    rect_.moveTopRight(start_rect_.topRight());
  }
  else if (state_ == MOVE_BOTTOM_RIGHT)
  {
    rect_= resizeHelper(start_rect_,
                        start_rect_.topLeft(),
                        start_rect_.bottomRight(),
                        event->localPos());
    rect_.moveTopLeft(start_rect_.topLeft());      
  }
  else if (state_ == MOVE_TOP_RIGHT)
  {
    rect_= resizeHelper(start_rect_,
                        start_rect_.bottomLeft(),
                        start_rect_.topRight(),
                        event->localPos());
    rect_.moveBottomLeft(start_rect_.bottomLeft());      
  }
  else
  {
    qWarning("Unhandled state in PlaceableWindowProxy: %d", state_);
  }

  return true;
}
Ejemplo n.º 17
0
//===------------------------------===//
// Get the next terminal state
// Handle error input
//===------------------------------===//
int Scanner::getNextTerminalState()
{
    int current_state = 0;
    char current_char;
    
    do
    {
        current_char    = getCurrentChar();
		
		// Only add to lexeme one double quote that
		// immediately follows a double quote
		if ( current_char != '"' || current_state == 10 )
			current_lexeme  = current_lexeme + current_char;
        
        
        // Check whether we found a comment
        string bracket_comment  = current_lexeme.substr( 0, 1 );
        string slash_comment    = current_lexeme.substr( 0, 2 );
		
        if ( ( bracket_comment == "{" && current_char == '}' ) || ( slash_comment == "//" && current_char == '\n' ) )
            current_lexeme = "";
        
	
        // Erase all whitespaces if the whitespace
        // is the only thing in current lexeme
        if ( isspace( current_char ) )
            if ( current_lexeme.length() == 1 )
                current_lexeme.erase( current_lexeme.length() - 1, 1 );
        
        
        // Mark beginning line and column of lexeme
        if ( current_lexeme.length() == 1 )
        {
            token_line      = line_number;
            token_column    = column_number;
        }
		
        
        // Get the next state
        current_state = getNextState( current_state, current_char );
		
        
        // Advance to the next character
        // for use in the subsequent loop
        advance();
        
        
        switch ( current_state )
        {
            case IDENT_T:           return current_state;
            case SINGLE0_T:         return current_state;
            case INTEGER_T:         return current_state;
            case SETEQUAL_T:        return current_state;
			case ISEQUAL_ST:		return current_state;
			case NOTEQUAL_ST:		return current_state;
			case LESSER_ST:			return current_state;
			case LESSEQUAL_ST:		return current_state;
			case GREATER_ST:		return current_state;
			case GREQUAL_ST:		return current_state;
            case ADDITION_ST:       return current_state;
            case SUBTRACT_ST:       return current_state;
            case ASTERISK_ST:       return current_state;
			case COLON_T:			return current_state;
            case SEMICOLON_T:       return current_state;
			case COMMA_T:			return current_state;
            case PERIOD_T:          return current_state;
			case STRINGCONST_T:		return current_state;
			case CRERRORCONST_T:	return current_state;
			case EOFERRORCONST_T:	return current_state;
			case LEFTPARENTH_T:		return current_state;
			case RIGHTPARENTH_T:	return current_state;
            case SLASHERROR_T:      return current_state;
            case BRACKETERROR_T:    return current_state;
			case EOF_T:             return current_state;
            case OTHERERROR:        return current_state;
        }
        
    } while ( 1 );
    // Keep getting the next state until
    // found terminal state of the current lexeme
    
}
Ejemplo n.º 18
0
ActionChain* ActionFactory::atack(const model::World& w, const model::Trooper& trooper, std::list<Tactician::Tactic> tactics, bool isFirstMove){
	ActionChain* res = NULL;
	const model::Trooper* enemyToAttack = NULL;
	const std::vector<model::Trooper>& troopers = w.getTroopers();

	int curPoints = trooper.getActionPoints();
	int enemyHealth = 0;
	bool headShot = false;
	if (tactics.end() != std::find(tactics.begin(), tactics.end(), Tactician::ATTACK)){
		std::vector<model::Trooper>::const_iterator it = troopers.begin();
		float min = 1 << 20;
		for (; it != troopers.end(); ++it){
			if (!(*it).isTeammate()){

				int health = it->getHitpoints();
				if (w.isVisible(trooper.getShootingRange(), trooper.getX(), trooper.getY(), trooper.getStance(), it->getX(), it->getY(), it->getStance()))
					if (health <= (curPoints / trooper.getShootCost()) * trooperDamage(trooper, trooper.getStance())){
						enemyToAttack = &(*it);
						headShot = true;
						break;
					}
				
				float d = trooper.getDistanceTo(*it);
				if (d <= min ){
					min = d;
					enemyToAttack = &(*it);
					enemyHealth = health;
				}		
			}
		}
	}

	do{

		if (enemyToAttack == NULL)
			break;

		if (!headShot && trooper.getActionPoints() <= 4 && trooper.getActionPoints() > 1 && trooper.getStance() != model::PRONE &&
			!w.isVisible(trooper.getShootingRange(), enemyToAttack->getX(), enemyToAttack->getY(), enemyToAttack->getStance(), trooper.getX(), trooper.getY(), getNextState(trooper, false)))
		{
			res = new ActionChain();
			std::list<ActionChunk> c;
			ActionChunk chunk(model::LOWER_STANCE, Vector2d(-1, -1));
			c.push_back(chunk);
			res->executor = &trooper;
			res->chain = c;
			break;
		}

		if (!headShot && trooper.isHoldingGrenade() && trooper.getDistanceTo(*enemyToAttack) <= 5 && trooper.getActionPoints() >= 8){
			res = new ActionChain();
			std::list<ActionChunk> c;
			ActionChunk chunk(model::THROW_GRENADE, Vector2d(enemyToAttack->getX(), enemyToAttack->getY()));
			c.push_back(chunk);
			res->executor = &trooper;
			res->chain = c;
			break;
		}

		if (w.isVisible(trooper.getShootingRange(), trooper.getX(), trooper.getY(), trooper.getStance(), enemyToAttack->getX(), enemyToAttack->getY(), enemyToAttack->getStance())){
			res = new ActionChain();
			
			if (enemyHealth > (curPoints / trooper.getShootCost()) * trooperDamage(trooper, trooper.getStance()) &&
				trooper.getStance() != model::PRONE &&
				w.isVisible(trooper.getShootingRange(), trooper.getX(), trooper.getY(), getNextState(trooper, false), enemyToAttack->getX(), enemyToAttack->getY(), enemyToAttack->getStance())){
				std::list<ActionChunk> c;
				ActionChunk chunk(model::LOWER_STANCE, Vector2d(-1, -1));
				c.push_back(chunk);
				res->executor = &trooper;
				res->chain = c;	
			}else{
				std::list<ActionChunk> c;
				ActionChunk chunk(model::SHOOT, Vector2d(enemyToAttack->getX(), enemyToAttack->getY()));
				c.push_back(chunk);
				res->executor = &trooper;
				res->chain = c;
			}

		}else{//invisible
			//try to stand up first
			if (trooper.getStance() != model::STANDING && !w.isVisible(trooper.getShootingRange(), trooper.getX(), trooper.getY(), trooper.getStance(), enemyToAttack->getX(), enemyToAttack->getY(), enemyToAttack->getStance())){
				res = new ActionChain();
				std::list<ActionChunk> c;
				ActionChunk chunk(model::RAISE_STANCE, Vector2d(-1, -1));
				c.push_back(chunk);
				res->executor = &trooper;
				res->chain = c;
				break;
			}

			//try to move
			Vector2d dst = findBestPositionToAttack(w, trooper, *enemyToAttack);
			if (dst == Vector2d(-1,-1))
				break;


			PathFinder pf;

			std::list<Vector2d> path = pf.calcOptimalPath(w, Vector2d(trooper.getX(), trooper.getY()), dst);
			if (path.empty())//overchecking
				break;
			path.pop_front();
			
			res = new ActionChain();
			std::list<ActionChunk> c;
			
			std::list<Vector2d>::iterator it2 = path.begin();
			for (; it2 != path.end(); ++it2){
				ActionChunk chunk(model::MOVE, *it2);
				c.push_back(chunk);
			}
			res->executor = &trooper;
			res->chain = c;
			break;
		}
	}while(0);

	return res;
}