Example #1
0
/** 以最快的方式跑到目标点
* Run to the destination point with the fastest method.
* \param agent the agent itself.
* \param pos the destination point.
* \param buffer point buffer, means the real destinantion is a cycle with the certer 
* 		of pos and radius of buffer.
* \param power the intend power to use.
* \param can_inverse true means can run in the inverse direction of the agent's body.
* \param turn_first true means that the agent should turn first to adjust the direction.
* \return true if the action excuted successfully.
*/
bool Dasher::GoToPoint(Agent & agent, Vector pos, double buffer, double power, bool can_inverse, bool turn_first)
{
	AtomicAction act;

	GoToPoint(agent, act, agent.GetStrategy().AdjustTargetForSetplay(pos), buffer, power, can_inverse, turn_first);
	return act.Execute(agent);
}
Example #2
0
static void readConfig(Agent& agent, string configFile) {
    pt::ptree properties;

    LOG(INFO) << "Reading configuration from " << configFile;
    pt::read_json(configFile, properties);
    agent.setProperties(properties);
}
int
main(int argc, char ** argv)
{
  int myid, numprocs;
  
  int n1, n2;
  n1 = atoi(argv[1]);
  n2 = atoi(argv[2]);
  
  if (n1 > 0){ ALL_N_AGENTS=n1; }
  if (n2 > 0){ N_TRIAL=n2; }
  Agent * agents = init(&argc, argv, &myid, &numprocs);

  if(myid == 0){
   printf("%d %d %d\n", ALL_N_AGENTS, N_AGENTS, N_TRIAL);
  }
  
  double new_price = 0;
  int t;
  for(t = 0; t < N_TRIAL; ++t)  {
    int i; 
    Agent * agent;
    
    for(agent = agents, i = N_AGENTS; i--; ++agent)
      agent->refresh(agent);

    double g_min_ask, g_max_bid;
    get_extreme_value(&g_min_ask, &g_max_bid, agents);

    if(myid == 0)
      if(g_max_bid > g_min_ask)
      {
        new_price = (g_min_ask + g_max_bid) / 2;
        printf("%d %lf\n", t, new_price);
//        fflush(stdout);
      }

    MPI_Bcast(&new_price, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);

    for(;new_price; new_price = 0)
      for(agent = agents, i = N_AGENTS; i--; ++agent)
        agent->set(agent, new_price);
  }

  MPI_Finalize();
  return 0;
}
Example #4
0
void EnvironmentCA2DMulti::update()
{
    Environment::update();
    
    if (settings.payoff_depletion_rate_arg)
    {
        for (agent_iterator it = mAgents.begin(); it != mAgents.end(); ++it)
        {
            Agent *agent = *it;
            int index = agent->get_index();
            Point2Di position = this->mPositions[index];
            this->mLandscape->deplete_at(position.x, position.y);
        }
    }

    this->mLandscape->regenerate();
}
Example #5
0
    void LocationModel::removeSource(AgentId aid)
    {
        if(mSources.erase(aid) > 0)
        {
            Agent *agent = mLocationModelMan->level()->agentMan()->getAgent(aid);

            if(nullptr == agent)
                return;

            LocationModel *model = agent->locationModel();

            if(nullptr == model)
                return;

            model->removeDestination(attachedAgent());
        }
    }
Example #6
0
//##ModelId=424BB6470067
void ACDX::logout(CString agent)
{
	std::list<Agent>::iterator aliasElement;
	Agent ag;
	for(aliasElement = aliasList.begin(); aliasElement != aliasList.end(); ++aliasElement ) 
	{
		ag = *aliasElement;
		if (agent==(H323Utils::extractAliasName(ag.getAlias()))) 
		{
			if (g_lock.lock()) {
				aliasElement->setBlocked(TRUE);
				Logger::log("Logout agent " + agent);
				g_lock.unlock();
			}// lock
		}// ==
	}// for
}
void CGameAIRecorder::RecordLuaComment(const Agent &agent, const char* szComment, ...) const
{
	assert(agent.IsValid());

	if (m_bIsRecording && agent.IsValid())
	{
		char szBuffer[1024] = {0};

		va_list args;
		va_start(args, szComment);
		vsnprintf(szBuffer, 1024, szComment, args);
		va_end(args);

		IAIRecordable::RecorderEventData data(szBuffer);
		agent.GetAIObject()->RecordEvent(IAIRecordable::E_LUACOMMENT, &data);
	}
}
Example #8
0
void ConfigTest::testIgnoreTimestampsOverride()
{
  istringstream str("Devices = ../samples/test_config.xml\n"
                    "IgnoreTimestamps = true\n"
                    "Adapters { LinuxCNC { \n"
                    "IgnoreTimestamps = false\n"
                    "} }\n");
  mConfig->loadConfig(str);
  
  Agent *agent = mConfig->getAgent();
  CPPUNIT_ASSERT(agent);
  Device *device = agent->getDevices()[0];
  Adapter *adapter = device->mAdapters[0];
  
  CPPUNIT_ASSERT(!adapter->isIgnoringTimestamps());
  
}
Agent* AgentManager::createAgent(AgentType type, Creature* character)
{
	SteeringVehicle* vehicle = NULL;
	if(type == AGENT_PLAYER)
	{
		vehicle = new PlayerVehicle(character->getActor());
	}
    Agent* agent = new Agent(character, vehicle);
	agent->setType(type);
	if(type == AGENT_PLAYER)
	{
		mPlayer = agent;
	}

	addAgent(agent);
    return agent;
}
Example #10
0
Agent* AgentList::addOrUpdateAgent(sockaddr* publicSocket, sockaddr* localSocket, char agentType, uint16_t agentId) {
    AgentList::iterator agent = end();
    
    if (publicSocket) {
        for (agent = begin(); agent != end(); agent++) {
            if (agent->matches(publicSocket, localSocket, agentType)) {
                // we already have this agent, stop checking
                break;
            }
        }
    } 
    
    if (agent == end()) {
        // we didn't have this agent, so add them
        Agent* newAgent = new Agent(publicSocket, localSocket, agentType, agentId);
        
        if (socketMatch(publicSocket, localSocket)) {
            // likely debugging scenario with two agents on local network
            // set the agent active right away
            newAgent->activatePublicSocket();
        }
   
        if (newAgent->getType() == AGENT_TYPE_VOXEL_SERVER ||
            newAgent->getType() == AGENT_TYPE_AVATAR_MIXER ||
            newAgent->getType() == AGENT_TYPE_AUDIO_MIXER) {
            // this is currently the cheat we use to talk directly to our test servers on EC2
            // to be removed when we have a proper identification strategy
            newAgent->activatePublicSocket();
        }
        
        addAgentToList(newAgent);
        
        return newAgent;
    } else {
        
        if (agent->getType() == AGENT_TYPE_AUDIO_MIXER ||
            agent->getType() == AGENT_TYPE_VOXEL_SERVER) {
            // until the Audio class also uses our agentList, we need to update
            // the lastRecvTimeUsecs for the audio mixer so it doesn't get killed and re-added continously
            agent->setLastHeardMicrostamp(usecTimestampNow());
        }
        
        // we had this agent already, do nothing for now
        return &*agent;
    }    
}
Example #11
0
int main(int argc, char *argv[]) {
    try {
        Agent agent {};

        try {
            agent.start();
        } catch (agent_error& e) {
            std::cout << "Failed to start the agent: " << e.what() << std::endl;
            return 2;
        }
    } catch (agent_error& e) {
        std::cout << "Failed to initialize the agent: " << e.what() << std::endl;
        return 1;
    }

    return 0;
}
int Goal_Attack_Region::Get_Totally_Complete(AiMain *ai)
{

	int i;
	int completely_there_count = 0;

    Agent *agent = NULL;
    ArmyAgent *aa=NULL;
	MapPointData army_pos;


	if (attacking_squad == NULL) return false;

	for (i=0; i < attacking_squad->my_agents.count; i++)
	{

		agent = (Agent *) attacking_squad->my_agents.Return_Data_By_Number(i);

		if (agent->GetType() == AGENT_TYPE_ARMY)
		{

			aa = (ArmyAgent *) agent;

            if (aa->GetState() == AGENT_STATE_MARKED_DEAD) {
                continue;
            }

			aa->GetPos(ai, army_pos);

			if ((m_pos->x == army_pos.x)  &&
				(m_pos->y == army_pos.y)  &&
				(m_pos->z == army_pos.z)  )
			{

				completely_there_count++;

			}

		}

	}

    Set_Totally_Complete(completely_there_count == attacking_squad->my_agents.count);

	return m_is_completed;
}
Example #13
0
void EnvironmentGraph::reproduce()
{
	/*--------------------------------------------------------------------*
	 * birth-death reproduction
	 *--------------------------------------------------------------------*/
	int parent_index = this->select_parent();
	Agent *parent = mAgents[parent_index];
	Agent *child = parent->replicate();

	vector <Agent *> neighbours = this->get_neighbours(parent);
	Agent *neighbour = neighbours[rng_randint(0, neighbours.size())];
	int child_index = neighbour->get_index();

	delete mAgents[child_index];
	mAgents[child_index] = child;
	mGraph->mNodes[child_index]->mData = child;
}
Example #14
0
// simulate a sequence of random actions, returning the accumulated reward.
static reward_t playout(Agent &agent, unsigned int playout_len) {
	reward_t r = 0;
	for (unsigned int i = 0; i < playout_len; ++i) {
	    // Pick a random action
	    action_t a = agent.genRandomAction();
	    agent.modelUpdate(a);
		
		// Generate a random percept distributed according to the agent's
		// internal model of the environment.
        percept_t rew;
        percept_t obs;
	    agent.genPerceptAndUpdate(obs, rew);
	    
	    r = r + rew;
    }
	return r;
}
Example #15
0
void VCardFormatImpl::addAgentValue( VCARD::VCard *vcard, const Agent &agent )
{
  if ( agent.isIntern() && !agent.addressee() )
    return;

  if ( !agent.isIntern() && agent.url().isEmpty() )
    return;

  ContentLine cl;
  cl.setName( EntityTypeToParamName( EntityAgent ) );

  ParamList params;
  if ( agent.isIntern() ) {
    QString vstr;
    Addressee *addr = agent.addressee();
    if ( addr ) {
      writeToString( (*addr), vstr );
      vstr.replace( ":", "\\:" );
      vstr.replace( ",", "\\," );
      vstr.replace( ";", "\\;" );
      vstr.replace( "\r\n", "\\n" );
      cl.setValue( new TextValue( vstr.utf8() ) );
    } else
      return;
  } else {
    cl.setValue( new TextValue( agent.url().utf8() ) );
    params.append( new Param( "VALUE", "uri" ) );
  }

  cl.setParamList( params );
  vcard->add( cl );
}
Example #16
0
std::vector<double> beatTrack(const AgentParameters &params,
                              const EventList &events,
                              const EventList &beats)
      {
      AgentList agents;
      int count = 0;
      double beatTime = -1;
      if (!beats.empty()) {
            count = beats.size() - 1;
            EventList::const_iterator itr = beats.end();
            --itr;
            beatTime = itr->time;
            }
      if (count > 0) {        // tempo given by mean of initial beats
            double ioi = (beatTime - beats.begin()->time) / count;
            agents.push_back(new Agent(params, ioi));
            }
      else            // tempo not given; use tempo induction
            agents = Induction::beatInduction(params, events);

      if (!beats.empty()) {
            for (AgentList::iterator itr = agents.begin(); itr != agents.end(); ++itr) {
                  (*itr)->beatTime = beatTime;
                  (*itr)->beatCount = count;
                  (*itr)->events = beats;
                  }
            }
      agents.beatTrack(events, params, -1);

      Agent *best = agents.bestAgent();
      std::vector<double> resultBeatTimes;

      if (best) {
            best->fillBeats(beatTime);
            for (EventList::const_iterator itr = best->events.begin();
                        itr != best->events.end(); ++itr) {
                  resultBeatTimes.push_back(itr->time);
                  }
            }
      for (AgentList::iterator ai = agents.begin(); ai != agents.end(); ++ai) {
            delete *ai;
            }

      return resultBeatTimes;
      }
Example #17
0
bool Env::sendMsg(long idSrc, long idDest, char *msg) {
    logMsg("SEND MSG : " + std::to_string(idSrc) + " -> " + std::to_string(idDest));
    // if (this->phy->getNeighbours(idSrc).count(idDest)) {
        this->agents.at(idDest)->addMsg(msg);

        // Display the sending message with dataAgents
        Agent * agentSrc = this->agents.at(idSrc);
        Agent * agentDest = this->agents.at(idDest);
        Vect posSrc = PosToCell(agentSrc->getPos().x, agentSrc->getPos().y);
        Vect posDest = PosToCell(agentDest->getPos().x, agentDest->getPos().y);
        if (posSrc != posDest) {
            float dist = ((724-Vect(posSrc - posDest).Length()) / 724.0) / 6.0;
            for (float n = 0; n < 1; n += dist) {
                Vect base = posDest + n * (posSrc - posDest);
                Vect dirSommet = Vect(posSrc - posDest);
                dirSommet.Normalize();
                Vect vectBase = Vect(dirSommet.y, -dirSommet.x);
                for (int j = 0; j < 20; j++) {
                    for (int i = -j*0.5; i <= j*0.5; i++) {
                        Vect point = base + j / 2.0 * dirSommet + i / 2.0 * vectBase;
                        if (point.x >= 0 && point.x < 512 && point.y >= 0 && point.y < 512) {
                            agentSrc->getVision(point.x, point.y)->dataAgent = 10 * (1 - n);
                        }
                    }
                }
            }
        }
        return true;
    //}
    //return false;
}
Example #18
0
bool AdaptiveLayer::handleGesture()
{
    bool gotSignal = false;
    string humanName = "partner";
    Agent* partner = dynamic_cast<Agent*>(iCub->opc->getEntity(humanName));
    if (partner->m_present)
    {

        //Check if the human did a particular gesture
        list<Relation> gestures = iCub->opc->getRelations();
        if (gestures.size() > 0)
        {
            iCub->look(partner->name());

            //take the first gesture that has been recognized on the current partner
            for(list<Relation>::iterator it = gestures.begin(); it != gestures.end() ; it++)
            {
                string subject = it->subject();
                string verb = it->verb();
                //cout<<"GESTURE : "<<it->toString()<<endl;
                if (subject == humanName && verb == "perform")
                {
                    gotSignal = true;
                    string gestureName = it->object();
                    cout<<"GESTURE : "<<gestureName<<endl;
                    //trigger the dance corresponding to this gesture

                    //If we have a stored reaction pattern to this tactile stimulus
                    if (gestureEffects.find(gestureName) != gestureEffects.end() )
                    {
                        iCub->say(gestureEffects[gestureName].getRandomSentence(), false);
                        //Apply each emotional effect
                        for(map<string, double>::iterator itEffects = gestureEffects[gestureName].m_emotionalEffect.begin() ; itEffects != gestureEffects[gestureName].m_emotionalEffect.end(); itEffects++)
                        {
                            iCub->icubAgent->m_emotions_intrinsic[itEffects->first] += itEffects->second;
                        }
                    }
                    iCub->commitAgent();
                    iCub->opc->removeRelation(*it);
                }
            }
        }
    }
    return gotSignal;
}
Example #19
0
bool Brain::priorize(Agent& agent) {
	bool there_is_something_there = false;
	map<pair<int, int>, Memory>::iterator it = objectives.begin();
	if (!this->objectives.empty()) {
		int x, y, orientation;
		pair<bool, bool> solved;
		getGoal(agent);
		deque<pair<int, int> > path;
		agent.GetCoord(y, x, orientation);
		pair<int, int> coords = pair<int, int>(x, y);
		map<pair<int, int>, Memory>::iterator it = this->objectives.begin();

		this->current_goal = (*it).first;
		bool iHaveItTouchingMaNose = (current_path.empty() && !this->objectives.empty()
				&& (agent.whatISeeThere(1).first == (*it).second.getItem() || agent.whatISeeThere(1).second == (*it).second.getItem()));
		bool iAmOnIt = (current_path.empty() && current_goal.first == x && current_goal.second == y);

		if (iAmOnIt) {
			//cout << "I AM ON IT" << endl;
			iAmOnSomething((*it).second.getItem(), agent);
		} else if (iHaveItTouchingMaNose) {
			//cout << "I HAVE IT IN NOSE" << endl;
			iHaveSomethingAhead((*it).second.getItem(), agent);
		} else {
			//yellWhatImDoing(agent.getCoord());
			Astar astar_alg = Astar(agent.mapa_entorno_, agent.mapa_objetos_, coords, current_goal, true); //Cuidado, movimiento forzado
			solved = astar_alg.solve();
			if (solved.second) {
				this->current_goal = astar_alg.getGoal();
			}
			if (!solved.first) {
				cout << "ERROR: no se me ocurre una forma de encontrar lo que buscas, ni puedo encontrar más mapa!" << endl;
				cout << "PASOS: " << steps << endl;
				//exit(0);
			}
			while (!current_path.empty()) {
				current_path.pop();
			}
			path = deque<pair<int, int> >(astar_alg.getSolution());
			translateToMoves(coords, orientation, path);
		}
		there_is_something_there = true;
	}
	return there_is_something_there;
}
Example #20
0
Agent* OutputAgentFactory::createAgent() {
	// create new output agent
	Agent *shakespeare  = new Agent();
	Database *db        = shakespeare->getDatabase();

	// add number of bugs and length of output interval to shakespeare's database
	IntegerData *nb = new IntegerData("number_bugs",number_bugs);
	db->addData(nb);

	DoubleData *oi = new DoubleData("output_interval", output_interval);
	db->addData(oi);

	// we just need to add the actions to the agents.
	// the output-agent does not possess any message generators or simulators.
	this->addActionsToAgentsActionSet(shakespeare);

	return shakespeare;
}
void MicroscopicDataDB::insert(Agent& data) {
    agentInsertWorker_->insertBuffer(data.sqlInsertValue());

    if ((!agentInsertWorker_->isRunning() && agentInsertWorker_->bufferSize() > MAX_BUFFER_SIZE)
        ||
        (agentInsertWorker_->isRunning() && agentInsertWorker_->bufferSize() > 4*MAX_BUFFER_SIZE)){
        insertAgentsToDB();
    }
}
Example #22
0
void
QmfObject::run_pending_calls(void)
{
	Agent a = _qmf_data.getAgent();
	for (list<QmfAsyncRequest*>::iterator it = _pending_jobs.begin();
		     it != _pending_jobs.end(); ++it) {
		QmfAsyncRequest* ar = *it;
		qb_loop_timer_handle th;
		uint32_t correlation_id = a.callMethodAsync(ar->method, ar->args, _qmf_data.getAddr());
		_outstanding_calls[correlation_id] = ar;
		g_timer_stop(ar->time_queued);
		g_timer_start(ar->time_execed);
		ar->state = QmfAsyncRequest::JOB_RUNNING;
		ar->ref();
		mainloop_timer_add(ar->timeout, ar,
				   method_call_tmo, &th);
	}
}
Example #23
0
// Process status change
bool AgentManager::childStatusChange()
{
    bool gotit = false;

    for (Agent *c = first; c != 0; c = c->next)
    {
	pid_t pid = c->pid();
	int status;

	if (pid > 0 && waitpid(pid, &status, WNOHANG) == pid)
	{
	    c->callHandlers(_Died, (void *)status);
	    gotit = true;
	}
    }

    return gotit;
}
Example #24
0
/**
 * Tackle ball.
 * \param agent.
 * \param angle_after_tackle direction you want the ball to go.
 * \param p_tackle_angle will be set to the angle to tackle at if valid.
 * \return true iff it is possible to tackle the ball to the given direction.
 */
bool Tackler::TackleToDir(Agent & agent, const AngleDeg & dir, bool foul)
{
    AngleDeg tackle_angle;
    if (GetTackleAngleToDir(agent, dir, &tackle_angle)){
        agent.Tackle(tackle_angle, foul);
        return true;
    }
    return false;
}
Example #25
0
void DebriefMenu::checkNewWeaponFound() {

    for (int i=0; i<4; i++) {
        if (g_Session.agents().squadMember(i)) {
            Agent *pAgent = g_Session.agents().squadMember(i);
            for (int wi=0; wi < pAgent->numWeapons(); wi++) {
                Weapon *pWeapon = pAgent->weapon(wi)->getWeaponClass();

                if (!g_App.weapons().isAvailable(pWeapon)) {
                    if (g_Session.researchManager().handleWeaponDiscovered(pWeapon)) {
                        getStatic(txtNewWeap1Id_)->setText("#DEBRIEF_WEAP_FOUND1");
                        getStatic(txtNewWeap2Id_)->setText("#DEBRIEF_WEAP_FOUND2");
                    }
                }
            }
        }
    }
}
Example #26
0
b2Vec2 MapController::steerTowards(Agent &agent, b2Vec2 direction)
{
	b2Vec2 desiredVelocity = direction * Agent::maxSpeed;

	//The velocity change we want
	b2Vec2 velocityChange = desiredVelocity - agent.getVelocity();
	//Convert to a force
	return velocityChange * (Agent::maxForce / Agent::maxSpeed);
}
Example #27
0
/**
* 将身体转向特定方向
* Turn body to a certain direction.
* @param agent the agent itself.
* @param ang the angle to turn to.
* @return an atomic action to turn the body.
*/
AtomicAction Dasher::GetTurnBodyToAngleAction(const Agent & agent, AngleDeg ang)
{
	AtomicAction action;
    action.mType = CT_Turn;

    double angle_turn = GetNormalizeAngleDeg(ang - agent.GetSelf().GetBodyDir());
    if (fabs(angle_turn) < agent.GetSelf().GetMaxTurnAngle())
    {
        action.mSucceed = true;
        action.mTurnAngle = angle_turn;
    }
    else
    {
        action.mSucceed = false;
        action.mTurnAngle = Sign(angle_turn) * agent.GetSelf().GetMaxTurnAngle();
    }
    return action;
}
void COpcAdapter::SetMTCTagValue(std::string tag, std::string value)
{
#if 1
	Agent * agent = _agentconfig->getAgent();
	Device *pDev = agent->getDeviceByName(_device);
	DataItem *di = pDev->getDeviceDataItem(tag);
	if (di != NULL)
	{
		std::string time = getCurrentTime(GMT_UV_SEC);
		agent->addToBuffer(di, value, time);
	}
	else
	{
		LOGONCE GLogger.LogMessage(StdStringFormat("(%s) Could not find data item: %s  \n",  _device.c_str(), tag.c_str()));
	}

#endif
}
Example #29
0
 // TODO FOR DANIEL: USE ICUBCLIENT!!!
 std::string getPartnerName()
 {
     string partnerName = "";
     list<Entity*> lEntities = opc.EntitiesCacheCopy();
     for (auto& entity : lEntities) {
         if (entity->entity_type() == "agent") {
             Agent* a = dynamic_cast<Agent*>(entity);
             //We assume kinect can only recognize one skeleton at a time
             if(a->m_present == 1.0 && a->name()!="icub") {
                 partnerName = a->name() ;
                 yInfo() << "Partner found: name = " << partnerName;
                 return partnerName;
             }
         }
     }
     yWarning() << "No partner present was found!";
     return partnerName;
 }
Example #30
0
void SWGraph::step(){
  
  Agent* a = NULL;
  set<Agent*>::iterator i;
 
  //cout << "antes del step. NAgs =" << agents.size() <<"\n";

  for (i = agents.begin(); i != agents.end(); ++i) {  
    a = *i;
    //cout << *a;
    a->step();
  }
  //this->print();
  reapAgents();

  //cout << "despues del step. NAgs =" << agents.size() <<"\n";

}