int calcDist(vector<int>& nums, unsigned int start)
 {
     got = costs.find (start);
     if(got != costs.end())
     {
         return costs[start];
     }
     
     if(start == nums.size()-1)
     {
         costs[start]=0;
         return 0;
     }
     int min = INT_MAX;
     for(int i=nums[start];i>0;--i)
     {
         if(start+i<nums.size())
         {
             int temp = 1+calcDist(nums,start+i);
             if(temp<min)
             {
                 min=temp;
             }
         }
     }
     costs[start]=min;
     return min;
 }
Example #2
0
void GameStatePlay::checkStash() {
	if (mapr->stash) {
		// If triggered, open the stash and inventory menus
		menu->closeAll();
		menu->inv->visible = true;
		menu->stash->visible = true;
		mapr->stash = false;
	}
	else if (menu->stash->visible) {
		// Close stash if inventory is closed
		if (!menu->inv->visible) {
			menu->resetDrag();
			menu->stash->visible = false;
		}

		// If the player walks away from the stash, close its menu
		float interact_distance = calcDist(pc->stats.pos, mapr->stash_pos);
		if (interact_distance > INTERACT_RANGE || !pc->stats.alive) {
			menu->resetDrag();
			menu->stash->visible = false;
		}

	}

	// If the stash has been updated, save the game
	if (menu->stash->updated) {
		menu->stash->updated = false;
		save_load->saveGame();
	}
}
Example #3
0
void OCSObserver::update(IOdomMeasurement* measurement)
{
  if(!_initialized)
  {
    _lastOdomMeasurement = measurement->getMeasurement();
    _initialized = true;
    return;
  }
  else
  {
    double dist = calcDist(measurement->getMeasurement(), _lastOdomMeasurement);

    for(unsigned int i = 0; i < _clientList.size(); i++)
    {
      // decrement dist buffer
      _actualDists.at(i) -= dist;

      // if dist buffer under 0 odom changed sigificantly for this client
      if(_actualDists.at(i) < 0.0)
      {
        _clientList.at(i)->setOCSFlagTrue();
        _actualDists.at(i) = _dists.at(i);
      }
    }
    // remember new value
    _lastOdomMeasurement = measurement->getMeasurement();
  }
}
Example #4
0
ItemStack LootManager::checkNearestPickup(const FPoint& hero_pos) {
	ItemStack loot_stack;

	float best_distance = std::numeric_limits<float>::max();

	std::vector<Loot>::iterator it;
	std::vector<Loot>::iterator nearest = loot.end();

	for (it = loot.end(); it != loot.begin(); ) {
		--it;

		float distance = calcDist(hero_pos, it->pos);
		if (distance < INTERACT_RANGE && distance < best_distance) {
			best_distance = distance;
			nearest = it;
		}
	}

	if (nearest != loot.end() && !nearest->stack.empty()) {
		loot_stack = nearest->stack;
		loot.erase(nearest);
		return loot_stack;
	}

	return loot_stack;
}
/**
 * One frame of logic for this behavior
 */
void BehaviorStandard::logic() {

	// skip all logic if the enemy is dead and no longer animating
	if (e->stats.corpse) {
		if (e->stats.corpse_ticks > 0)
			e->stats.corpse_ticks--;
		return;
	}

	if (!e->stats.hero_ally) {
		if (calcDist(e->stats.pos, pc->stats.pos) <= ENCOUNTER_DIST)
			e->stats.encountered = true;

		if (!e->stats.encountered)
			return;
	}

	doUpkeep();
	findTarget();
	checkPower();
	checkMove();
	updateState();

	fleeing = false;
}
int main(void) {
  calcDist();
  solve();
  printResult();
  printf("\nДиагонали от минималния разрез: ");
  writeCut(1, n-1);
  return 0;
}
Example #7
0
float graph::node_average(int node){
	calcDist();
	float sum = 0;
	for (int i = 0; i < nodes; i++){
		sum += dist[node][i];
	}
	return sum / (float)(nodes - 1);
}
Example #8
0
int graph::node_diameter(int node){
	calcDist();
	int d = 0;
	for (int i = 0; i < nodes; i++){
		if (dist[node][i] > d) d = dist[node][i];
	}
	return d;
}
Example #9
0
 int shortest(string word1, string word2) {
     if (!solutions.count(word1) || !solutions[word1].count(word2)) {
         int x = calcDist(word1, word2);
         solutions[word1][word2] = x;
         solutions[word2][word1] = x;
         return x;
     }
     return solutions[word1][word2];
 }
Example #10
0
void CCollider::Init(E_COLLIDER_TYPE type, CTransform & transform, E_X_START xStart,  E_Y_START yStart, bool active)
{
	this->m_type = type;
	this->m_xStart = xStart;
	this->m_yStart = yStart;
	this->m_active = active;
	calcAABB(transform);
	calcDist(transform);
}
Example #11
0
bool MsdEnabledLattEx::isNotPBCJump( lattIndex pos1, lattIndex pos2 ) 
{
    vectorDist dist( calcDist( pos1, pos2 ) );
    if ( dist.squareDisp() <= 2 )
    {
        return isNeighbor[ dist.col - 1 ][ dist.row - 1 ];
    }
    return false;
            
}
Example #12
0
void calcDistances(){

	int i,j;

	for(i=0;i<n;i++)
		for(j=i+1;j<n;j++){
			dist[i][j]=calcDist(places[i][0],places[i][1],places[j][0],places[j][1]);
			dist[j][i]=dist[i][j];
		}
}
Example #13
0
float graph::average(){
	calcDist();
	int sum = 0;
	for (int i = 0; i < nodes; i++){
		for (int j = 0; j < nodes; j++){
			sum += dist[i][j];
		}
	}
	return ((float)sum) / ((float)nodes) / ((float)nodes - 1);
}
Example #14
0
int graph::diameter(){
	calcDist();
	int d = 0;
	for (int i = 0; i < nodes; i++){
		for (int j = i; j < nodes; j++){
			if (dist[i][j] > d) d = dist[i][j];
		}
	}
	return d;
}
void SDLSoundManager::play(SoundManager::SoundID sid, std::string channel, FPoint pos, bool loop) {

	SoundMapIterator it;
	VirtualChannelMapIterator vcit = channels.end();

	if (!sid || !AUDIO || !SOUND_VOLUME)
		return;

	it = sounds.find(sid);
	if (it == sounds.end())
		return;

	/* create playback object and start playback of sound chunk */
	Playback p;
	p.sid = sid;
	p.location = pos;
	p.virtual_channel = channel;
	p.loop = loop;
	p.finished = false;

	if (p.virtual_channel != GLOBAL_VIRTUAL_CHANNEL) {

		/* if playback exists, stop it befor playin next sound */
		vcit = channels.find(p.virtual_channel);
		if (vcit != channels.end())
			Mix_HaltChannel(vcit->second);

		vcit = channels.insert(std::pair<std::string, int>(p.virtual_channel, -1)).first;
	}

	// Let playback own a reference to prevent unloading playbacked sound.
	if (!loop)
		it->second->refCnt++;

	Mix_ChannelFinished(&channel_finished);
	int c = Mix_PlayChannel(-1, it->second->chunk, (loop ? -1 : 0));

	if (c == -1)
		logError("SoundManager: Failed to play sound, no more channels available.");

	// precalculate mixing volume if sound has a location
	Uint8 d = 0;
	if (p.location.x != 0 || p.location.y != 0) {
		float v = 255.0f * (calcDist(lastPos, p.location) / (SOUND_FALLOFF));
		clamp(v, 0.f, 255.f);
		d = Uint8(v);
	}

	Mix_SetPosition(c, 0, d);

	if (vcit != channels.end())
		vcit->second = c;

	playback.insert(std::pair<int, Playback>(c, p));
}
Example #16
0
void TestEnv::stop()
{
   started = false;
   totalTime = timer->elapsed();
   update();
   emit TestEnv::emitHit(0);
   emit TestEnv::emitError(0);
	calcDist();
   emit TestEnv::retResults(totalTime, errors, distance);
   emit TestEnv::emitFinish();
}
Example #17
0
// Méthode qui affiche les cotes des murs
void Maison::drawCotes(Point p1, Point p2, float textFactor)
{
    char buf[10];
    double dist = calcDist(p1, p2);

    sprintf_s(buf, "%.2lf", dist);

    glLineWidth(1.0);
    glColor3ub(95, 95, 95);
    glut_drawText(((p1.getX()+p2.getX())/2.0)+0.1, ((p1.getY()+p2.getY())/2.0)+0.1, buf, textFactor);
}
Example #18
0
void MsdEnabledLattEx::calcStat( double & msd, double & protMsd )
{
    unsigned int count( 0 ), countProt( 0 );
    msd = 0;
    protMsd = 0;
    for ( lattIndex i = 0 ; i < mpLatt->getLatticeSize() ; ++i )
    {
        if (  !mWasProtein[ mTracking[i] ] )  // lipids
        {
            msd += ( calcDist( i, mTracking[i] ) - mPBCCorrection[ mTracking[i] ] ).squareDisp();
            ++count;
        }
        else //proteins
        {
            protMsd += ( calcDist( i, mTracking[i] ) - mPBCCorrection[ mTracking[i] ] ).squareDisp();
            ++countProt;
        }
    }
    msd /= count;
    protMsd /= ( countProt );
}
/* whether two points are within distance r */
bool Point::withinRadius(Point* pnt, double r){
	// we know for sure this is gonna be false
	if (!(calcDistY(pnt) < r) || !(calcDistX(pnt) < r)){
		return false;
	}
	// otherwise need more calcluation to determine
	double d = calcDist(pnt);
	if (d < r){
		return true;
	}
	else{
		return false;
	}
}
Example #20
0
void MapRenderer::checkNearestEvent() {
	if (NO_MOUSE) show_tooltip = false;

	std::vector<Event>::iterator it;
	std::vector<Event>::iterator nearest = events.end();
	float best_distance = std::numeric_limits<float>::max();

	// loop in reverse because we may erase elements
	for (it = events.end(); it != events.begin(); ) {
		--it;

		// skip inactive events
		if (!EventManager::isActive(*it)) continue;

		// skip events without hotspots
		if ((*it).hotspot.h == 0) continue;

		// skip events on cooldown
		if ((*it).cooldown_ticks != 0) continue;

		float distance = calcDist(cam, (*it).center);
		if ((((*it).reachable_from.w == 0 && (*it).reachable_from.h == 0) || isWithin((*it).reachable_from, floor(cam)))
				&& distance < INTERACT_RANGE && distance < best_distance) {
			best_distance = distance;
			nearest = it;
		}

	}

	if (nearest != events.end()) {
		if (NO_MOUSE || TOUCHSCREEN) {
			// new tooltip?
			createTooltip((*nearest).getComponent("tooltip"));
			tip_pos = map_to_screen((*nearest).center.x, (*nearest).center.y, shakycam.x, shakycam.y);
			if ((*nearest).getComponent("npc_hotspot")) {
				tip_pos.y -= npc_tooltip_margin;
			}
			else {
				tip_pos.y -= TILE_H;
			}
		}

		if (inpt->pressing[ACCEPT] && !inpt->lock[ACCEPT]) {
			if (inpt->pressing[ACCEPT]) inpt->lock[ACCEPT] = true;

			if(EventManager::executeEvent(*nearest))
				events.erase(nearest);
		}
	}
}
int BackProject( IplImage *src,IplImage *dst, CvScalar sclr, int thresh )
{
    int i,j;
    CvScalar pix;
    for( i=0;i<src->width;i++ )
        for( j=0;j<src->height;j++ )
        {
		uchar *ptr_src,*ptr_dst;
                ptr_src = (uchar *) src->imageData + j * src->widthStep + i * src->nChannels;
                ptr_dst = (uchar *) dst->imageData + j * dst->widthStep + i * dst->nChannels;
                pix = cvScalar( ptr_src[0],ptr_src[1],ptr_src[2],0 );
                if( calcDist(pix,sclr)<thresh )
                    *ptr_dst = 255;
        }
}
Example #22
0
void SLIC::generateSuperPixels(){
    for (int iter = 0; iter < max_iteration; iter++){
        distance = Scalar(FLT_MAX);
        
        for (int i=0; i<center.size(); i++) {
            ColorRep tmp_center = center[i];
            for (int y=tmp_center.y-S; y<tmp_center.y+S; y++) {
                
                Vec3b *ptr = image.ptr<Vec3b>(y);
                int *cluster_ptr = cluster.ptr<int>(y);
                double *dist_ptr = distance.ptr<double>(y);
                
                for (int x = tmp_center.x -S; x<tmp_center.x+S; x++){
                    if (withinRange(x, y)) {
                        Vec3b color = ptr[x];
                        //calculate the distance
                        double dist = calcDist(tmp_center, color, x,y);
                        if (dist < dist_ptr[x]){
                            dist_ptr[x] = dist;
                            cluster_ptr[x] = i;
                        }
                    }
                }
            }
        }
        
        center.assign(center.size(), ColorRep());
        count.assign(count.size(), 0);
        
        
        for (int y=0; y<image.rows; y++) {
            int *cluster_ptr = cluster.ptr<int>(y);
            for (int x=0; x<image.cols; x++){
                int cluster_id = cluster_ptr[x];
                if (cluster_id != -1){
                    Vec3b color = image.at<Vec3b>(y,x);
                    center[cluster_id].add(color, x, y);
                    count[cluster_id]++;
                }
            }
        }
        
        for (int i=0; i<center.size(); i++){
            center[i].div(count[i]);
        }
        
    }
}
Example #23
0
File: aidp.c Project: punu92/aidp
void findn(vertx *c,int *cnt,int i,int j,int dir,vertx end)//------------------Searches the neighbourhood of a point to get the next
{
int chng=0;
int cnt1,k;
*(cnt)=0;
cnt1=*(cnt);

while((i!=end.i || j!=end.j) && i<row && j<col)
	{
	
	c[cnt1].i=i;
	c[cnt1].j=j;
	
	chng=0;
	*(visited+i*col+j)=1;
	//printf("ver: row=%d col=%d\n",i,j);
	
	for(k=0;(k<cnt1 && cnt1<4) || k<4; k++)
		five[k]=five[k+1];
	five[k].i=i;   five[k].j=j;

	if(j>0 && *(mat+i*col+j-1)==0 && *(visited+i*col+j-1)==0 && *(taken+i*col+j-1) && chng==0){j=j-1;chng=1;}
   
	if(*(mat+i*col+j+1)==0 && *(visited+i*col+j+1)==0 && *(taken+i*col+j+1) && chng==0){j=j+1;chng=1;}

	if(i>0 && *(mat+(i-1)*col+j+1)==0 && *(visited+(i-1)*col+j+1)==0 && *(taken+(i-1)*col+j+1) && chng==0){i=i-1;j=j+1;chng=1;}

	if(i>0 && j>0 && *(mat+(i-1)*col+j-1)==0 && *(visited+(i-1)*col+j-1)==0 && *(taken+(i-1)*col+j-1) && chng==0){i=i-1;j=j-1;chng=1;}

	if(i>0 && *(mat+(i-1)*col+j)==0 && *(visited+(i-1)*col+j)==0 && *(taken+(i-1)*col+j) && chng==0){i=i-1;chng=1;}

	if(j>0 && *(mat+(i+1)*col+j-1)==0 && *(visited+(i+1)*col+j-1)==0 && *(taken+(i+1)*col+j-1) && chng==0){i=i+1;j=j-1;chng=1;}

	if(*(mat+(i+1)*col+j)==0 && *(visited+(i+1)*col+j)==0 && *(taken+(i+1)*col+j) && chng==0){i=i+1;chng=1;}

	if(*(mat+(i+1)*col+j+1)==0 && *(visited+(i+1)*col+j+1)==0 && *(taken+(i+1)*col+j+1) && chng==0){i=i+1;j=j+1;chng=1;}

	if(cnt1%2==0 && cnt1>=4 && chng==1)  calcDist();
	
	cnt1++;
	
	if(!chng) {printf("Breaking..\n");
	break;}
	}

*(cnt)=cnt1++;
}
Example #24
0
void graph::correct(){
	calcDist();
	int v1, v2, d;
	d = diameter();
	bool done = false;
	for (int i = 0; i < nodes; i++){
		for (int j = 0; j < nodes; j++){
			if (dist[i][j] = d){
				v1 = i;
				v2 = j;
				done = true;
				break;
			}
		}
		if (done) break;
	}
	vector<int> v1Neighbors, v2Neighbors;
	for (int i = 0; i < nodes; i++){
		if (adj[v1][i]) v1Neighbors.push_back(i);
		if (adj[v2][i]) v2Neighbors.push_back(i);
	}
	bool * x = new bool[nodes * nodes];
	bool * best = new bool[nodes * nodes];
	int best_d = 10000000;
	float best_a = 1000000.0f;
	for (vector<int>::iterator i = v1Neighbors.begin(); i != v1Neighbors.end(); i++){
		for (vector<int>::iterator j = v2Neighbors.begin(); j != v2Neighbors.end(); j++){
			for (int r = 0; r < nodes; r++) for (int c = 0; c < nodes; c++) x[r * nodes + c] = adj[r][c];
			das(x, v1, *j, *i, v2, nodes);
			graph g(x, nodes);
			if (g.diameter() <= best_d && g.average() < best_a){
				memcpy(best, x, nodes * nodes * sizeof(bool));
				best_d = g.diameter();
				best_a = g.average();
			}
		}
	}
	delete[] x;
	memcpy(&adj[0][0], best, nodes * nodes * sizeof(bool));
	delete[] best;
}
Example #25
0
File: aidp3.c Project: punu92/aidp
void findn(vertx *c,int *cnt,int i,int j,vertx end)//------------------Searches the neighbourhood of a point to get the next
{
int ch=0;
int cnt1,k,a,b;
*(cnt)=0;
cnt1=*(cnt);

for(a=0;a<mark && (v[a].i!=i || v[a].j!=j);a++);

printf("ver: a=%d row=%d col=%d\n",a,i,j);

while(v[a].i!=end.i || v[a].j!=end.j)
	{

	c[cnt1].i=i;
	c[cnt1].j=j;
	c[cnt1].yes=0;

	for(k=0;(k<cnt1 && cnt1<4) || k<4; k++)
		five[k]=five[k+1];
	five[k].i=i;   five[k].j=j;
	printf("ver in loop: a=%d row=%d col=%d\n",a,i,j);
	*(visited+i*col+j)=1;

	if(cnt1%2==0 && cnt1>=4)  calcDist();
	cnt1++;

	a=(a+1)%mark;//printf("a1=%d\n",a);
	i=v[a].i; j=v[a].j;
	if(*(visited+i*col+j)==1) 
		{a=(mark+a-2)%mark;/*printf("a2=%d\n",a);*/
		i=v[a].i; j=v[a].j;
		if(*(visited+i*col+j)==1) 
			{printf("Breaking, no choice\n");break;}
		}
	}


*(cnt)=cnt1;
}
Example #26
0
bool check_triggers()
{
	// it has halo so must check if within halo
	if ( config->halo )
	{
		// if distance is greater than range then return with false
		// else check rest of triggers
		double distance = calcDist( config->halo_info->lat, config->halo_info->lon, gps->lat, gps->lon );
#ifdef LOG
		snprintf(log_str, 100, "\r\nDistance from halo - %d (mm)\r\n", (int)(distance*1000));
		write_log();
#endif
		if ( distance >= config->halo_info->range)
			return false;
	}

	// after start time
	if ( gps->hour  >= config->start_hour && gps->minute >= config->start_min )
		// before stop time
		if ( gps->hour  <= config->stop_hour && gps->minute <= config->stop_min )
			return true;

	return false;
}
/**
 * Check state changes related to movement
 */
void BehaviorStandard::checkMove() {

	// dying enemies can't move
	if (e->stats.cur_state == ENEMY_DEAD || e->stats.cur_state == ENEMY_CRITDEAD) return;

	// stunned enemies can't act
	if (e->stats.effects.stun) return;

	// handle not being in combat and (not patrolling waypoints or waiting at waypoint)
	if (!e->stats.hero_ally && !e->stats.in_combat && (e->stats.waypoints.empty() || e->stats.waypoint_pause_ticks > 0)) {

		if (e->stats.cur_state == ENEMY_MOVE) {
			e->newState(ENEMY_STANCE);
		}

		// currently enemies only move while in combat or patrolling
		return;
	}

	// clear current space to allow correct movement
	mapr->collider.unblock(e->stats.pos.x, e->stats.pos.y);

	// update direction
	if (e->stats.facing) {
		if (++e->stats.turn_ticks > e->stats.turn_delay) {

			// if blocked, face in pathfinder direction instead
			if (!mapr->collider.line_of_movement(e->stats.pos.x, e->stats.pos.y, pursue_pos.x, pursue_pos.y, e->stats.movement_type)) {

				// if a path is returned, target first waypoint

				bool recalculate_path = false;

				//if theres no path, it needs to be calculated
				if(path.empty())
					recalculate_path = true;

				//if the target moved more than 1 tile away, recalculate
				if(calcDist(map_to_collision(prev_target), map_to_collision(pursue_pos)) > 1.f)
					recalculate_path = true;

				//if a collision ocurred then recalculate
				if(collided)
					recalculate_path = true;

				//add a 5% chance to recalculate on every frame. This prevents reclaulating lots of entities in the same frame
				chance_calc_path += 5;

				if(percentChance(chance_calc_path))
					recalculate_path = true;

				//dont recalculate if we were blocked and no path was found last time
				//this makes sure that pathfinding calculation is not spammed when the target is unreachable and the entity is as close as its going to get
				if(!path_found && collided && !percentChance(chance_calc_path))
					recalculate_path = false;
				else//reset the collision flag only if we dont want the cooldown in place
					collided = false;

				prev_target = pursue_pos;

				// target first waypoint
				if(recalculate_path) {
					chance_calc_path = -100;
					path.clear();
					path_found = mapr->collider.compute_path(e->stats.pos, pursue_pos, path, e->stats.movement_type);
				}

				if(!path.empty()) {
					pursue_pos = path.back();

					//if distance to node is lower than a tile size, the node is going to be passed and can be removed
					if(calcDist(e->stats.pos, pursue_pos) <= 1.f)
						path.pop_back();
				}
			}
			else {
				path.clear();
			}

			if(fleeing)
				e->stats.direction = calcDirection(pursue_pos, e->stats.pos);
			else
				e->stats.direction = calcDirection(e->stats.pos, pursue_pos);
			e->stats.turn_ticks = 0;
		}
	}

	// try to start moving
	if (e->stats.cur_state == ENEMY_STANCE) {
		checkMoveStateStance();
	}

	// already moving
	else if (e->stats.cur_state == ENEMY_MOVE) {
		checkMoveStateMove();
	}

	// if patrolling waypoints and has reached a waypoint, cycle to the next one
	if (!e->stats.waypoints.empty()) {
		FPoint waypoint = e->stats.waypoints.front();
		FPoint pos = e->stats.pos;
		// if the patroller is close to the waypoint
		if (fabs(waypoint.x - pos.x) <= 0.5f && fabs(waypoint.y - pos.y) <= 0.5f) {
			e->stats.waypoints.pop();
			// pick a new random point if we're wandering
			if (e->stats.wander) {
				waypoint = getWanderPoint();
			}
			e->stats.waypoints.push(waypoint);
			e->stats.waypoint_pause_ticks = e->stats.waypoint_pause;
		}
	}

	// re-block current space to allow correct movement
	mapr->collider.block(e->stats.pos.x, e->stats.pos.y, e->stats.hero_ally);

}
/**
 * Locate the player and set various targeting info
 */
void BehaviorStandard::findTarget() {
	float stealth_threat_range = (e->stats.threat_range * (100 - static_cast<float>(e->stats.hero_stealth))) / 100;

	// stunned enemies can't act
	if (e->stats.effects.stun) return;

	// check distance and line of sight between enemy and hero
	if (pc->stats.alive)
		hero_dist = calcDist(e->stats.pos, pc->stats.pos);
	else
		hero_dist = 0;


	// aggressive enemies are always in combat
	if (!e->stats.in_combat && e->stats.combat_style == COMBAT_AGGRESSIVE) {
		e->stats.in_combat = true;
		powers->activate(e->stats.power_index[BEACON], &e->stats, e->stats.pos); //emit beacon
	}

	// check entering combat (because the player hit the enemy)
	if (e->stats.join_combat) {
		if (hero_dist <= (stealth_threat_range *2)) {
			e->stats.join_combat = false;
		}
		else {
			e->stats.in_combat = true;
			powers->activate(e->stats.power_index[BEACON], &e->stats, e->stats.pos); //emit beacon
		}
	}

	// check entering combat (because the player got too close)
	if (!e->stats.in_combat && los && hero_dist < stealth_threat_range && e->stats.combat_style != COMBAT_PASSIVE) {
		e->stats.in_combat = true;
		powers->activate(e->stats.power_index[BEACON], &e->stats, e->stats.pos); //emit beacon
	}

	// check exiting combat (player died or got too far away)
	if (e->stats.in_combat && hero_dist > (e->stats.threat_range *2) && !e->stats.join_combat && e->stats.combat_style != COMBAT_AGGRESSIVE) {
		e->stats.in_combat = false;
	}

	// check exiting combat (player or enemy died)
	if ((!e->stats.alive || !pc->stats.alive) && e->stats.combat_style != COMBAT_AGGRESSIVE) {
		e->stats.in_combat = false;
	}

	// by default, the enemy pursues the hero directly
	pursue_pos.x = pc->stats.pos.x;
	pursue_pos.y = pc->stats.pos.y;
	target_dist = hero_dist;


	//if there are player allies closer than the hero, target an ally instead
	if(e->stats.in_combat) {
		for (unsigned int i=0; i < enemies->enemies.size(); i++) {
			if(!enemies->enemies[i]->stats.corpse && enemies->enemies[i]->stats.hero_ally) {
				//now work out the distance to the minion and compare it to the distance to the current targer (we want to target the closest ally)
				float ally_dist = calcDist(e->stats.pos, enemies->enemies[i]->stats.pos);
				if (ally_dist < target_dist) {
					pursue_pos.x = enemies->enemies[i]->stats.pos.x;
					pursue_pos.y = enemies->enemies[i]->stats.pos.y;
					target_dist = ally_dist;
				}
			}
		}
	}

	// if we just started wandering, set the first waypoint
	if (e->stats.wander && e->stats.waypoints.empty()) {
		FPoint waypoint = getWanderPoint();
		e->stats.waypoints.push(waypoint);
		e->stats.waypoint_pause_ticks = e->stats.waypoint_pause;
	}

	// if we're not in combat, pursue the next waypoint
	if (!(e->stats.in_combat || e->stats.waypoints.empty())) {
		FPoint waypoint = e->stats.waypoints.front();
		pursue_pos.x = waypoint.x;
		pursue_pos.y = waypoint.y;
	}

	// check line-of-sight
	if (target_dist < e->stats.threat_range && pc->stats.alive)
		los = mapr->collider.line_of_sight(e->stats.pos.x, e->stats.pos.y, pc->stats.pos.x, pc->stats.pos.y);
	else
		los = false;

	if(e->stats.effects.fear) fleeing = true;

	// If we have a successful chance_flee roll, try to move to a safe distance
	if (e->stats.cur_state == ENEMY_STANCE && !move_to_safe_dist && hero_dist < e->stats.threat_range/2 && hero_dist >= e->stats.melee_range && percentChance(e->stats.chance_flee))
		move_to_safe_dist = true;

	if (move_to_safe_dist) fleeing = true;
}
Example #29
0
/**
 * If the player has clicked on an NPC, the game mode might be changed.
 * If a player walks away from an NPC, end the interaction with that NPC
 * If an NPC is giving a reward, process it
 */
void GameStatePlay::checkNPCInteraction() {
	if (pc->stats.attacking) return;

	if (mapr->npc_id != -1)
		npc_id = mapr->npc_id;

	bool player_ok = pc->stats.alive && pc->stats.humanoid;
	float interact_distance = 0;
	// check distance to this npc
	if (npc_id != -1) {
		interact_distance = calcDist(pc->stats.pos, npcs->npcs[npc_id]->pos);
	}

	if (mapr->event_npc != "") {
		npc_id = mapr->npc_id = npcs->getID(mapr->event_npc);
		if (npc_id != -1) {
			eventDialogOngoing = true;
			eventPendingDialog = true;
		}
		mapr->event_npc = "";
	}

	// if close enough to the NPC, open the appropriate interaction screen

	if (npc_id != -1 && mapr->npc_id != -1 && ((interact_distance < INTERACT_RANGE && player_ok) || eventPendingDialog)) {

		if (inpt->pressing[MAIN1] && !NO_MOUSE) inpt->lock[MAIN1] = true;
		if (inpt->pressing[ACCEPT]) inpt->lock[ACCEPT] = true;

		menu->npc->setNPC(npcs->npcs[npc_id]);

		// only show npc action menu if multiple actions are available
		if (!menu->npc->empty() && !menu->npc->selection())
			menu->npc->visible = true;
	}

	mapr->npc_id = -1;

	// check if a NPC action selection is made
	if (npc_id != -1 && (menu->npc->selection() || eventPendingDialog)) {
		if (menu->npc->vendor_selected && !menu->vendor->visible) {
			// begin trading
			menu->closeAll();
			menu->vendor->setNPC(npcs->npcs[npc_id]);
			menu->inv->visible = true;
		}
		else if (menu->npc->dialog_selected && !menu->talker->visible) {
			// begin talking
			menu->closeAll();
			menu->talker->setNPC(npcs->npcs[npc_id]);
			menu->talker->chooseDialogNode(menu->npc->selected_dialog_node);
			pc->allow_movement = npcs->npcs[npc_id]->checkMovement(menu->npc->selected_dialog_node);
		}

		menu->npc->setNPC(NULL);
		eventPendingDialog = false;
	}

	if (npc_id != -1 && !eventDialogOngoing) {
		// check for walking away from an NPC
		if (interact_distance > INTERACT_RANGE || !player_ok) {
			menu->npc->setNPC(NULL);
			menu->vendor->setNPC(NULL);
			menu->talker->setNPC(NULL);
		}
	}
	else if (!menu->vendor->visible && !menu->talker->visible) {
		eventDialogOngoing = false;
	}

	// reset movement restrictions when we're not in dialog
	if (!menu->talker->visible) {
		pc->allow_movement = true;
	}

	if (npc_id != -1 && !menu->talker->visible && !menu->vendor->visible && !menu->npc->visible) {
		npc_id = -1;
	}

}
// if fwd, C,N,CA are C,N,CA, else assumed to be N,C,CA
void InformedPhipsiSampler::sample(
        vector<float>& curC, vector<float>& curN, vector<float>& curCA,
        float & phi, float & psi, float & omega, float & r, float & a, float & t) {
    float d0 = calcDist(target, curCA);

    float cisdist = 2.8, transdist = 3.81;

    bool cis = false, trans = false;
    if(cisdist > d0 - targetTol && cisdist < d0 + targetTol) cis = true;
    if(transdist > d0 - targetTol && transdist < d0 + targetTol) trans = true;

    if(cis && trans) { // if both cis and trans are possible, choose one
        if(ran01() > 0.95) trans = false;
    } else if(!cis && !trans) {
        cout << "target unreachable "
            <<curCA[0]<<" "<<curCA[1]<<" "<<curCA[2] << " : " << d0 <<" : "<< targetTol <<" : "<< target[0]<<" "<<target[1]<<" "<<target[2]
            << endl;
        exit(0);
    }
    // now either cis or trans is true

    float interCA;
    if(cis) { omega = 0; interCA = cisdist; }
    if(trans) { omega = -180; interCA = transdist; }

    phi = -999; psi = -999;

    // find a,t which take u into restraint sphere with this interCA
    vector<float> tar(3,0), noi(3,0);
    while(1) {
        // add some noise to target, proportional to noise
        randomNormalVector(noi);
        linear_combination(tar, 1, target, targetTol*ran01(), noi);
    
        // for this interCA, find a,t that takes you closest to target
        r = calcDist(curCA, tar);
        a = calcAngle(curN, curCA, tar);
        t = calcDihed(curC, curN, curCA, tar);
        find4thPoint(tar, curC, curN, curCA, interCA, a, t);
        if( calcDist(target, tar) <= targetTol ) break;
    }

    // return a phi-psi value for this a,t if available
    if(fwd) {
        RATdata & ratdata = RATdata::fwdinstance(RATdataPath.c_str());
        vector<PSO>::iterator bi, ei;
        ratdata.range(resn, interCA, a, t, bi, ei);
        int rs = ei - bi;
        assert(rs >= 0);
        if(rs == 0) { return; }
        int incr = (int) floor ( (0.+rs) * ran01() );
        bi += incr;
        phi = bi->r; psi = bi->a; omega = bi->t;
    } else {
        RATdata & ratdata = RATdata::bwdinstance(RATdataPath.c_str());
        vector<PSO>::iterator bi, ei;
        ratdata.range(resn, interCA, a, t, bi, ei);
        int rs = ei - bi;
        assert(rs >= 0);
        if(rs == 0) { return; }
        int incr = (int) floor ( (0.+rs) * ran01() );
        bi += incr;
        psi = bi->r; phi = bi->a; omega = bi->t;
    }
    //cout << phi <<" "<< psi <<" "<< omega << " shd take u from ("<< curCA[0]<<" "<< curCA[1]<<" "<< curCA[2] <<" ";
    //vector<float> exppt(3,0);
    //find4thPoint(exppt, curC, curN, curCA, interCA, a, t);
    //cout << ") to ("<< exppt[0]<<" "<< exppt[1]<<" "<< exppt[2] <<") " << endl;;
}