Example #1
0
void HeapRegionDCTOC::walk_mem_region_with_cl(MemRegion mr,
                                              HeapWord* bottom,
                                              HeapWord* top,
                                              ExtendedOopClosure* cl) {
  G1CollectedHeap* g1h = _g1;
  int oop_size;
  ExtendedOopClosure* cl2 = NULL;

  FilterIntoCSClosure intoCSFilt(this, g1h, cl);
  FilterOutOfRegionClosure outOfRegionFilt(_hr, cl);

  switch (_fk) {
  case NoFilterKind:          cl2 = cl; break;
  case IntoCSFilterKind:      cl2 = &intoCSFilt; break;
  case OutOfRegionFilterKind: cl2 = &outOfRegionFilt; break;
  default:                    ShouldNotReachHere();
  }

  // Start filtering what we add to the remembered set. If the object is
  // not considered dead, either because it is marked (in the mark bitmap)
  // or it was allocated after marking finished, then we add it. Otherwise
  // we can safely ignore the object.
  if (!g1h->is_obj_dead(oop(bottom), _hr)) {
    oop_size = oop(bottom)->oop_iterate(cl2, mr);
  } else {
    oop_size = oop(bottom)->size();
  }

  bottom += oop_size;

  if (bottom < top) {
    // We replicate the loop below for several kinds of possible filters.
    switch (_fk) {
    case NoFilterKind:
      bottom = walk_mem_region_loop(cl, g1h, _hr, bottom, top);
      break;

    case IntoCSFilterKind: {
      FilterIntoCSClosure filt(this, g1h, cl);
      bottom = walk_mem_region_loop(&filt, g1h, _hr, bottom, top);
      break;
    }

    case OutOfRegionFilterKind: {
      FilterOutOfRegionClosure filt(_hr, cl);
      bottom = walk_mem_region_loop(&filt, g1h, _hr, bottom, top);
      break;
    }

    default:
      ShouldNotReachHere();
    }

    // Last object. Need to do dead-obj filtering here too.
    if (!g1h->is_obj_dead(oop(bottom), _hr)) {
      oop(bottom)->oop_iterate(cl2, mr);
    }
  }
}
TEST_CASE test_disable_filter()
{
    ProcessVariableContext ctx;
    ProcessVariable pv(ctx, "test");
    DemoProcessVariableListener pvl;
    DisableFilter filt(&pvl);     
    
    // Connect gets passed.
    epicsTime time = epicsTime::getCurrent();   
    TEST(pvl.values == 0);
    filt.pvConnected(pv, time);
    TEST(pvl.values == 0);
    TEST(pvl.connected == true);
    
    // Initial sample gets passed.
    time += 1; 
    DbrType type = DBR_TIME_DOUBLE;
    DbrCount count = 1;
    RawValueAutoPtr value(RawValue::allocate(type, count, 1));
    RawValue::setDouble(type, count, value, 3.14);
    RawValue::setTime(value, time);    
    filt.pvValue(pv, value);
    TEST(pvl.values == 1);
    
    // Disconnect gets passed.
    time += 1;   
    filt.pvDisconnected(pv, time);
    TEST(pvl.connected == false);

    // Disable
    puts (" --- Disable ---");
    {
        Guard guard(__FILE__, __LINE__, filt);
        filt.disable(guard);
    }
    // Re-connect
    filt.pvConnected(pv, time);
    TEST(pvl.values == 1);
    TEST(pvl.connected == true);
    
    // Sample doesn't pass.
    time += 1; 
    RawValue::setTime(value, time);    
    filt.pvValue(pv, value);
    TEST(pvl.values == 1);
    
    // Enable again.
    puts (" --- Enable ---");
    time += 1;
    {
        Guard guard(__FILE__, __LINE__, filt);
        filt.enable(guard, pv, time);
    }
    // Still connected
    TEST(pvl.connected == true);
    // And the last value
    TEST(pvl.values == 2);

    TEST_OK;
}
Example #3
0
    virtual bool filter(const Option& opt)
    {
      const bool ret = filt(opt);
      if (!ret)
	OPENVPN_LOG("Ignored due to route-nopull: " << opt.render(Option::RENDER_TRUNC_64|Option::RENDER_BRACKET));
      return ret;
    }
Example #4
0
int main(int cc, char **v)
{
  QApplication app(cc,v);

  QFuture<int> a= QtConcurrent::run(f,1,1,1);
  QFuture<int> b= QtConcurrent::run(f,2,2,2);
  QFuture<int> c= QtConcurrent::run(f,3,3,3);

  filt();


  qDebug() << a.result() << b.result() << c.result();


#if 0
  QStringList sl;

  sl << "first" << "second" << "third";

  QString name;
  foreach(name,sl)
  {
    Thread *t=new Thread(name);
    //QThreadPool::globalInstance()->start(t);
  }
Example #5
0
void StrucView::filterSelected( WWindow * )
//-----------------------------------------
{
    MethodFilter filt( 150, 150, false);

    if( filt.process() ) {
        _filter = filt.getCurrentFlags();
        reset();
    }
}
Example #6
0
InputParameters
validParams<NumElems>()
{
  InputParameters params = validParams<GeneralPostprocessor>();
  MooseEnum filt("active total", "active");
  params.addParam<MooseEnum>(
      "elem_filter",
      filt,
      "The type of elements to include in the count (active, total). Default == active");
  return params;
}
Example #7
0
void slist_partition_destructive( slist **xs
                                , slist **notmatch
                                , void  *cc
                                , bool (*filt)(void*, void*)
                                ) {

    if( !xs )
        return;

    if( !notmatch )
        return;

    slist *new_l = slist_nil();
    slist *phead = slist_nil();

    slist *new_l2 = slist_nil();
    slist *phead2 = slist_nil();

    while( xs ) {
        slist *i = slist_uncons(xs);

        if( i == NULL ) break;

        i->next = slist_nil();

        if( filt && filt(cc, i->value) ) {
            if( new_l == NULL ) {
                new_l = slist_cons(i, new_l);
                phead = new_l;
                continue;
            }

            phead->next = i;
            phead = phead->next;

        } else {
            if( new_l2 == NULL ) {
                new_l2 = slist_cons(i, new_l2);
                phead2 = new_l2;
                continue;
            }

            phead2->next = i;
            phead2 = phead2->next;
        }
    }

    *xs = new_l;
    *notmatch = new_l2;
}
Example #8
0
/*!*****************************************************************************
 *******************************************************************************
\note  process_sensors
\date  Feb 1999
   
\remarks 

    filtering and differentiation of the sensor readings

 *******************************************************************************
 Function Parameters: [in]=input,[out]=output

     none

 ******************************************************************************/
int
process_sensors(void)

{

  int i,j;
  double aux;

  /* first the joint variables */
  for (i=1; i<=n_dofs; ++i) {
    joint_state[i].th    = filt(joint_raw_state[i].th,&fth[i]);
    joint_state[i].thd   = filt(joint_raw_state[i].thd,&fthd[i]);
    aux = (fthd[i].raw[1]-fthd[i].raw[2])*(double)motor_servo_rate;
    joint_state[i].thdd  = filt(aux,&fthdd[i]);
    joint_state[i].load  = filt(joint_raw_state[i].load,&fload[i]);

    if (!filter_flag && !real_robot_flag) {
      joint_state[i].th    = joint_sim_state[i].th;
      joint_state[i].thd   = joint_sim_state[i].thd;
      joint_state[i].thdd  = joint_sim_state[i].thdd;
      joint_state[i].load  = joint_sim_state[i].u;
    }

  }


  /* second the misc sensors */
  for (i=1; i<=n_misc_sensors; ++i) {
    misc_sensor[i]    = filt(misc_raw_sensor[i],&fmisc_sensor[i]);
    if (!filter_flag && !real_robot_flag) {
      misc_sensor[i] = misc_sim_sensor[i];
    }
  }

  return TRUE;

}
Example #9
0
// wp_next
struct
window_pane *wp_next(
	struct	window_pane *cur_wp, int dir,
	bool	(*filt)(struct window_pane *, struct window_pane *),
	int	(*sort)(const void *a, const void *b))
{
	struct	window_pane *wp;
	struct	window_pane *tar_wp;

	ARRAY_INIT(&panes);
	TAILQ_FOREACH(wp, &cur_wp->window->panes, entry)
		if (filt(cur_wp, wp))
			ARRAY_ADD(&panes, wp);

	// bypass filter
	if (ARRAY_LENGTH(&panes) == 0)
		TAILQ_FOREACH(wp, &cur_wp->window->panes, entry)
			switch(dir) {
				case WP_L:
					if (wp->xoff < cur_wp->xoff)
						ARRAY_ADD(&panes, wp);
					break;
				case WP_R:
					if (wp->xoff > cur_wp->xoff)
						ARRAY_ADD(&panes, wp);
					break;
				case WP_U:
					if (wp->yoff < cur_wp->yoff)
						ARRAY_ADD(&panes, wp);
					break;
				case WP_D:
					if (wp->yoff > cur_wp->yoff)
						ARRAY_ADD(&panes, wp);
					break;
			}

	if (ARRAY_LENGTH(&panes) > 0)
		qsort(ARRAY_DATA(&panes), ARRAY_LENGTH(&panes),
				sizeof(struct window_pane *), sort);

	if (ARRAY_LENGTH(&panes) > 0)
		tar_wp = ARRAY_FIRST(&panes);

	ARRAY_FREE(&panes);
	return tar_wp;
}
Example #10
0
int ybs_get_vi_mean(void)
{
	int i, v, vf = 0;
	ybs_vi_filter.xn_1 = 0;
	ybs_vi_filter.yn_1 = 0;
	ybs_get_vi(); //old data, ignore
	for(i = 0; i < 2000; i ++) {
		//v += ybs_get_vi();
		//v >>= (i == 0) ? 0 : 1;
		v = ybs_get_vi();
		vf = v >> 6;
		vf = filt(&ybs_vi_filter, vf);

		//printf("vori = %d mv, vfil = %d mv\n", d2mv(v), d2mv(vf << 6));
	}
	vf <<= 6;
	return vf;
}
Example #11
0
/**
 * @brief filter the value of str according to a filter.
 * 	remove from str all the occurrence of chars that are filtered by filt
 *	(i.e. filt(char)==true)
 * @param str the MyString to filter
 * @param filt the filter
 * RETURN VALUE:
 *  @return MYSTRING_SUCCESS on success, MYSTRING_ERROR on failure. */
MyStringRetVal myStringFilter(MyString *str, bool (*filt)(const char *))
{
    if (str != NULL)
    {
        char* tempStr = malloc(sizeof(char) * C_STRING_LENGTH_FROM_MY_STRING);

        int j = 0;
        for (int i = 0; i < str->length; ++i)
        {
            if (filt(&str->charArr[i])) //todo check and also maybe negate
            {
                tempStr[j] = str->charArr[i];
                j++;
            }
        }
        tempStr[j + 1] = END_OF_STRING; // the last index will hold the \0 flag.

        unsigned long tempStrLen = getCStringLength(tempStr);

        if (mystringRealloc(str, tempStrLen) == MYSTRING_ERROR)
        {
            return MYSTRING_ERROR;
        }

        for (int i = 0; i < tempStrLen; ++i)
        {
            str->charArr[i] = tempStr[i];
        }


        free(tempStr);
        tempStr = NULL;

        return MYSTRING_SUCCESS;
    }
    return MYSTRING_ERROR;
}
Example #12
0
/*!*****************************************************************************
 *******************************************************************************
\note  process_blobs
\date  Feb 1999
   
\remarks 

    filtering and differentiation of the sensor readings

 *******************************************************************************
 Function Parameters: [in]=input,[out]=output

 \param[in]     raw   :  raw blobs as input
 \param[out]    blobs :  the processed blob information

 ******************************************************************************/
void
process_blobs(Blob2D raw[][2+1])

{

  int i,j,n;
  double pos,vel,acc;
  int rfID;
  static Blob3D *traw;
  static int firsttime = TRUE;
  double x[2+2+1], x1[2+1], x2[2+1];
  
  if (firsttime) {
    firsttime = FALSE;
    traw = (Blob3D *) my_calloc(max_blobs+1,sizeof(Blob3D),MY_STOP);
  }
  
  for (i=1; i<=max_blobs; ++i) {

    if (!raw_blob_overwrite_flag) {

      /* the status of a blob is the AND of the two components */
      traw[i].status = raw[i][1].status && raw[i][2].status;

      switch (stereo_mode) {
	case VISION_3D_MODE:
	  /* coordinate transformation */
	  if (traw[i].status) {
	      x[1] = raw[i][1].x[1];
	      x[2] = raw[i][1].x[2];
	      x[3] = raw[i][2].x[1];
	      x[4] = raw[i][2].x[2];
	      rfID = 0;
	      if (predictLWPROutput(BLOB2ROBOT, 
				    x, x, 0.0, TRUE, traw[i].x, &rfID) == 0) {
		  traw[i].status = FALSE;
	      }
	  }
	break;
	  
	case VISION_2D_MODE:
	  if (traw[i].status) {
	      x1[1] =  raw[i][1].x[1];
	      x1[2] =  raw[i][1].x[2];
	      x2[1] =  raw[i][2].x[1];
	      x2[2] =  raw[i][2].x[2];
#if 1
	      /* stereo calculation based on the calibration */
	      stereo (x1, x2, traw[i].x);
#endif
	  }
	break;
      }
	  
    } else {
      /* use the learning model for the coordinate transformation 
	 (but not in simulation) */
      traw[i] = raw_blobs[i];
      /* CGA: should be updated to use 2D blobs, not 3D blobs. */
    }

    /* post processing */

    /* if the status changed from FALSE to TRUE, it is important
       to re-initialize the filtering */
    if (traw[i].status && !blobs[i].status) {
      for (j= _X_; j<= _Z_; ++j) {
	for (n=0; n<=FILTER_ORDER; ++n) {
	  blobpp[i].fblob[_X_][j].filt[n] = traw[i].x[j];
	  blobpp[i].fblob[_Y_][j].filt[n] = 0;
	  blobpp[i].fblob[_Z_][j].filt[n] = 0;
	  blobpp[i].fblob[_X_][j].raw[n]  = traw[i].x[j];
	  blobpp[i].fblob[_Y_][j].raw[n]  = 0;
	  blobpp[i].fblob[_Z_][j].raw[n]  = 0;
	}
      }
    }

    if (blobpp[i].filter_type == KALMAN) {
      ;
    } else { /* default is butterworth filtering */

      for (j= _X_; j<= _Z_; ++j) {

	if (traw[i].status) {

	  blobpp[i].pending = FALSE;
	  blobs[i].status   = TRUE;

	  /* filter and differentiate */
	  pos = filt(traw[i].x[j],&(blobpp[i].fblob[_X_][j]));
	  vel = (pos - blobpp[i].fblob[_X_][j].filt[2])*(double) vision_servo_rate;
	  vel = filt(vel,&(blobpp[i].fblob[_Y_][j]));
	  acc = (vel - blobpp[i].fblob[_Y_][j].filt[2])*(double) vision_servo_rate;
	  acc = filt(acc,&(blobpp[i].fblob[_Z_][j]));
	  if (blobpp[i].acc[j] != NOT_USED) {
	    acc = blobpp[i].acc[j];
	  }

	} else {

	  if (++blobpp[i].pending <= MAX_PENDING) {
	    pos = blobpp[i].predicted_state.x[j];
	    vel = blobpp[i].predicted_state.xd[j];
	    acc = blobpp[i].predicted_state.xdd[j];
	    // Note: leave blobs[i].status as is, as we don't want 
	    // to set something true which was not true before
	  } else {
	    pos = blobs[i].blob.x[j];
	    vel = 0.0;
	    acc = 0.0;
	    blobs[i].status   = FALSE;
	  }

	  /* feed the filters with the "fake" data to avoid transients
	     when the target status becomes normal */
	  pos = filt(pos,&(blobpp[i].fblob[_X_][j]));
	  vel = filt(vel,&(blobpp[i].fblob[_Y_][j]));
	  acc = filt(acc,&(blobpp[i].fblob[_Z_][j]));

	}

	/* predict ahead */
	blobs[i].blob.x[j]   = pos;
	blobs[i].blob.xd[j]  = vel;
	blobs[i].blob.xdd[j] = acc;

	if (blobs[i].status) {
	  
	  predict_state(&(blobs[i].blob.x[j]),&(blobs[i].blob.xd[j]),
			&(blobs[i].blob.xdd[j]),predict);
	  
	  
	  /* predict the next state */
	  blobpp[i].predicted_state.x[j]   = pos;
	  blobpp[i].predicted_state.xd[j]  = vel;
	  blobpp[i].predicted_state.xdd[j] = acc;
	  
	  predict_state(&(blobpp[i].predicted_state.x[j]),
			&(blobpp[i].predicted_state.xd[j]),
			&(blobpp[i].predicted_state.xdd[j]),
			1./(double)vision_servo_rate);
	}


      }
    }
  }

}
Example #13
0
// data in is currently used for PASV FTP support
static
errno_t	ppfilter_data_in (__unused void *cookie, socket_t so, const struct sockaddr *from,
                          mbuf_t *data, __unused mbuf_t *control, __unused sflt_data_flag_t flags)
{
    in_addr_t ip4;
    in_port_t port;

    if (!from) {
        struct sockaddr_in6 local;
        if (0 != sock_getpeername(so, (struct sockaddr*)&local, sizeof(local)))
            bzero(&local, sizeof(local));
        from = (const struct sockaddr*)&local;
    }

    if (AF_INET == from->sa_family) {
        port = ntohs(((const struct sockaddr_in*)from)->sin_port);
    } else if (AF_INET6 == from->sa_family) {
        const struct sockaddr_in6* addr6 = (const struct sockaddr_in6*)from;
        if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr) || !IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr))
            return (0); // tables do not contain native ip6 addreses
        port = ntohs(addr6->sin6_port);
    } else
        return (0);

    // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    // Short-circuit optimization for ftp filter -- if any other filters are ever added,
    // this will have to be removed.
    if (21 != port)
        return (0);
    // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

    mbuf_t mdata = *data;
    while (mdata && MBUF_TYPE_DATA != mbuf_type(mdata)) {
        mdata = mbuf_next(mdata);
    }
    if (!mdata)
        return (0);

    char *pkt = mbuf_data(mdata);
    if (!pkt)
        return (0);
    size_t len = mbuf_len(mdata);

    ip4 = INADDR_NONE;
    int block, i;
    pp_data_filter_t filt = pp_data_filters[0];
    for (i = 1; filt; ++i) {
        block = filt(pkt, len, &ip4, &port);
        if (INADDR_NONE != ip4) {
            // add to dynamic list
            pp_dynentries_lock();
            pp_dyn_entry_t e = pp_dyn_entry_get();
            if (e) {
                e->addr = ip4;
                e->port = port;
                e->block = block;
            }
            pp_dynentries_unlock();
            break;
        }
        filt = pp_data_filters[i];
    }

    return (0);
}
Example #14
0
static bool cf(WStackingFilter *filt, void *filt_data, WStacking *st)
{
    return (filt==NULL || filt(st, filt_data));
}
Example #15
0
int dmpTask::initialize()
{
double freq;
int i;
int ans = 999;

  start_time_ = 0.0;
  
  // Make sure that everything is clear
  if (vnames_CBi != NULL)
  {
    for (i = 1; i <= dof_CBi; i++)
      free((void *) vnames_CBi[i]);
    free((void *) vnames_CBi);
    vnames_CBi = NULL;
  }
  if (units_CBi != NULL)
  {
    for (i = 1; i <= dof_CBi; i++)
      free((void *) units_CBi[i]);
    free((void *) units_CBi);
    units_CBi = NULL;
  }
  if (CBi_traj != NULL)
  {
    my_free_matrix(CBi_traj, 1, n_CBi, 1, dof_CBi);
    CBi_traj = NULL;
  }
  if (vnames_Kinect != NULL)
  {
    for (i = 1; i <= dof_Kinect; i++)
      free((void *) vnames_Kinect[i]);
    free((void *) vnames_Kinect);
    vnames_Kinect = NULL;
  }
  vnames_Kinect = NULL;
  if (units_Kinect != NULL)
  {
    for (i = 1; i <= dof_Kinect; i++)
      free((void *) units_Kinect[i]);
    free((void *) units_Kinect);
    units_Kinect = NULL;
  }
  if (Kinect_traj != NULL)
  {
    my_free_matrix(Kinect_traj, 1, n_Kinect, 1, dof_Kinect);
    Kinect_traj = NULL;
  }
  if (DMP_object != NULL)
  {
    delete DMP_object;
    DMP_object = NULL;
  }

  // Read robot trajectory
  // mrdplot_convert(CBi_traj_file, &CBi_traj, &vnames_CBi, &units_CBi, &freq, &dof_CBi, &n_CBi);
  mrdplot_read(CBi_traj_file, &CBi_traj, &vnames_CBi, &units_CBi, &freq, &dof_CBi, &n_CBi);
  if (!set_active_dofs(vnames_CBi, dof_CBi, active_dofs))
    return FALSE;

  printf("%d active DoFs:", active_dofs[0]);
  for (i = 2; i <= active_dofs[0]+1; i++)
  {
    if (!((i-2)%8))
      printf("\n");
    printf("%s, ", vnames_CBi[i]);
  }
  printf("\n\n");

  // Read Kinect trajectory
  // mrdplot_convert(Kinect_traj_file, &Kinect_traj, &vnames_Kinect, &units_Kinect, &freq, &dof_Kinect, &n_Kinect);
  mrdplot_read(Kinect_traj_file, &Kinect_traj, &vnames_Kinect, &units_Kinect, &freq, &dof_Kinect, &n_Kinect);

  // Filter Kinect trajectory if desired
  if (Kinect_traj != NULL && filter_Kinect_data)
  {
    if (!init_filters())
      return FALSE;
    for (int i = 1; i <= 19; i++)
      fth[i].cutoff = 9;
    for (int i = 1; i <= 19; i++)
    {
      fth[i].raw[0] = fth[i].raw[1] = fth[i].raw[2] = Kinect_traj[1][i+1];
      fth[i].filt[0] = fth[i].filt[1] = fth[i].filt[2] = Kinect_traj[1][i+1];
    }
    for (int j = 1; j <= n_Kinect; j++)
      for (int i = 1; i <= 19; i++)
        Kinect_traj[j][i+1] = filt(Kinect_traj[j][i+1], &fth[i]);
  }

  // Compute DMP for robot trajectory
  if (DMP_object != NULL)
    delete DMP_object;
  // DMP_object = new DMP_structure(DMP_file);
  DMP_object = new DMP_structure(active_dofs[0], 50, 2.0, 12.0, 3.0);
  printf("\n");
  if (!DMP_object->example_Matrix(CBi_traj, n_CBi, dof_CBi))
    return FALSE;
  DMP_object->DMP_estimate(0);
  // DMP_object->DMP_param_print();
  printf("\n");

  // Initialize DMP integration
  for (int i = 1; i <= active_dofs[0]; i++)
  {
    initial_positions[i] = CBi_traj[1][i+1];
    initial_velocities[i] = 0.0;
  }
  DMP_object->set_initial_DMP_state(&(initial_positions[1]), &(initial_velocities[1]));

  // include this file to define contact points (needed to compute center of pressure)
#include "LEKin_contact.h"
  
  // prepare going to the default posture
  bzero((char *)&(target_[1]),N_DOFS*sizeof(target_[1]));
  for (i = 1; i <= N_DOFS; i++)
    target_[i] = joint_default_state[i];
  target_[L_EB].th = target_[R_EB].th = 0.05;
  target_[B_TFE].th = 0.2;  

  for (int i = 1; i <= active_dofs[0]; i++)
  {
    target_[active_dofs[i]].th = initial_positions[i];
    target_[active_dofs[i]].thd = 0.0;
    target_[active_dofs[i]].thdd = 0.0;
    target_[active_dofs[i]].uff = 0.0;
  }

  bool there = true;
  for (int i = 1; i <= B_HR; i++)
    if (fabs(target_[i].th - joint_des_state[i].th) > 1.0e-3)
    {
      there = false;
      break;
    }
  // go to the target using inverse dynamics (ID)int SampleTask::changeParameters()
  if (!there)
  {
    if (!go_target_wait_ID(target_))
    {
      return FALSE;
    }
  }

  // ready to go
  while (ans == 999)
  {
    if (!get_int(const_cast<char*>("Enter 1 to start or anthing else to abort ..."), ans, &ans))
    {
      return FALSE;
    }
  }
  
  // only go when user really types the right thing
  if (ans != 1) 
  {
    return FALSE;
  }

  start_time_ = task_servo_time;
  printf("start time = %.3f, task_servo_time = %.3f\n", start_time_, task_servo_time);

  return TRUE;
}
Example #16
0
/*!*****************************************************************************
 *******************************************************************************
  \note  run_goto_task
  \date  Dec. 1997

  \remarks 

  run the task from the task servo: REAL TIME requirements!

 *******************************************************************************
 Function Parameters: [in]=input,[out]=output

  none

 ******************************************************************************/
static int 
run_goto_cart_task(void)
{
  int j, i;
  double sum=0;
  double aux;

  /* has the movement time expired? I intentially run 0.5 sec longer */
  if (tau <= -0.5 || (tau <= 0.0 && special_flag)) {
    freeze();
    return TRUE; 
  }

  /* progress by min jerk in cartesian space */
  calculate_min_jerk_next_step(cnext,ctarget,tau,time_step,cnext);
  tau -= time_step;
 

  /* shuffle the target for the inverse kinematics */
  for (i=1; i<=n_endeffs; ++i) {
    for (j=1; j<=N_CART; ++j) {
      aux  = cnext[i].x[j] - cart_des_state[i].x[j];
      cart[(i-1)*6+j] = cnext[i].xd[j] + 20.*aux;
    }
  }

  /* inverse kinematics */
  for (i=1; i<=n_dofs; ++i) {
    target[i].th = joint_des_state[i].th;
  }
  if (!inverseKinematics(target,endeff,joint_opt_state,
			 cart,cstatus,time_step)) {
    freeze();
    return FALSE;
  }

  /* prepare inverse dynamics */
  for (i=1; i<=n_dofs; ++i) {
    aux = (target[i].thd-joint_des_state[i].thd)*(double)task_servo_rate;
    target[i].thdd  = filt(aux,&(fthdd[i]));

    joint_des_state[i].thdd = target[i].thdd;
    joint_des_state[i].thd  = target[i].thd;
    joint_des_state[i].th   = target[i].th;

    if (joint_des_state[i].th > joint_range[i][MAX_THETA]) {
      joint_des_state[i].th = joint_range[i][MAX_THETA];
      joint_des_state[i].thd = 0.0;
      joint_des_state[i].thdd = 0.0;
    }
    if (joint_des_state[i].th < joint_range[i][MIN_THETA]) {
      joint_des_state[i].th = joint_range[i][MIN_THETA];
      joint_des_state[i].thd = 0.0;
      joint_des_state[i].thdd = 0.0;
    }
  }

  /* compute inverse dynamics */
  SL_InvDyn(joint_state,joint_des_state,endeff,&base_state,&base_orient);

  return TRUE;

}
Example #17
0
bool basic_unit_filter_impl::internal_matches_filter(const unit & u, const map_location& loc, const unit* u2) const
{
	if (!vcfg["name"].blank() && vcfg["name"].t_str() != u.name()) {
		return false;
	}

	if (!vcfg["id"].empty()) {
		std::vector<std::string> id_list = utils::split(vcfg["id"]);
		if (std::find(id_list.begin(), id_list.end(), u.id()) == id_list.end()) {
			return false;
		}
	}

	// Allow 'speaker' as an alternative to id, since people use it so often
	if (!vcfg["speaker"].blank() && vcfg["speaker"].str() != u.id()) {
		return false;
	}

	if (vcfg.has_child("filter_location")) {
		if (vcfg.count_children("filter_location") > 1) {
			FAIL("Encountered multiple [filter_location] children of a standard unit filter. "
				 "This is not currently supported and in all versions of wesnoth would have "
				 "resulted in the later children being ignored. You must use [and] or similar "
				 "to achieve the desired result.");
		}
		terrain_filter filt(vcfg.child("filter_location"), &fc_, use_flat_tod_);
		if (!filt.match(loc)) {
			return false;
		}
	}

	if(vcfg.has_child("filter_side")) {
		if (vcfg.count_children("filter_side") > 1) {
			FAIL("Encountered multiple [filter_side] children of a standard unit filter. "
				 "This is not currently supported and in all versions of wesnoth would have "
				 "resulted in the later children being ignored. You must use [and] or similar "
				 "to achieve the desired result.");
		}
		side_filter filt(vcfg.child("filter_side"), &fc_);
		if(!filt.match(u.side()))
			return false;
	}

	// Also allow filtering on location ranges outside of the location filter
	if (!vcfg["x"].blank() || !vcfg["y"].blank()){
		if(vcfg["x"] == "recall" && vcfg["y"] == "recall") {
			//locations on the map are considered to not be on a recall list
			if (fc_.get_disp_context().map().on_board(loc))
			{
				return false;
			}
		} else if(vcfg["x"].empty() && vcfg["y"].empty()) {
			return false;
		} else if(!loc.matches_range(vcfg["x"], vcfg["y"])) {
			return false;
		}
	}

	// The type could be a comma separated list of types
	if (!vcfg["type"].empty()) {
		std::vector<std::string> types = utils::split(vcfg["type"]);
		if (std::find(types.begin(), types.end(), u.type_id()) == types.end()) {
			return false;
		}
	}

	// Shorthand for all advancements of a given type
	if (!vcfg["type_tree"].empty()) {
		std::set<std::string> types;
		for(const std::string type : utils::split(vcfg["type_tree"])) {
			if(types.count(type)) {
				continue;
			}
			if(const unit_type* ut = unit_types.find(type)) {
				const auto& tree = ut->advancement_tree();
				types.insert(tree.begin(), tree.end());
				types.insert(type);
			}
		}
		if(types.find(u.type_id()) == types.end()) {
			return false;
		}
	}

	// The variation_type could be a comma separated list of types
	if (!vcfg["variation"].empty())
	{
		std::vector<std::string> types = utils::split(vcfg["variation"]);
		if (std::find(types.begin(), types.end(), u.variation()) == types.end()) {
			return false;
		}
	}

	// The has_variation_type could be a comma separated list of types
	if (!vcfg["has_variation"].empty())
	{
		bool match = false;
		// If this unit is a variation itself then search in the base unit's variations.
		const unit_type* const type = u.variation().empty() ? &u.type() : unit_types.find(u.type().base_id());
		assert(type);

		for (const std::string& variation_id : utils::split(vcfg["has_variation"])) {
			if (type->has_variation(variation_id)) {
				match = true;
				break;
			}
		}
		if (!match) return false;
	}

	if (!vcfg["ability"].empty())
	{
		bool match = false;

		for (const std::string& ability_id : utils::split(vcfg["ability"])) {
			if (u.has_ability_by_id(ability_id)) {
				match = true;
				break;
			}
		}
		if (!match) return false;
	}

	if (!vcfg["race"].empty()) {
		std::vector<std::string> races = utils::split(vcfg["race"]);
		if (std::find(races.begin(), races.end(), u.race()->id()) == races.end()) {
			return false;
		}
	}

	if (!vcfg["gender"].blank() && string_gender(vcfg["gender"]) != u.gender()) {
		return false;
	}

	if (!vcfg["side"].empty() && vcfg["side"].to_int(-999) != u.side()) {
		std::vector<std::string> sides = utils::split(vcfg["side"]);
		const std::string u_side = std::to_string(u.side());
		if (std::find(sides.begin(), sides.end(), u_side) == sides.end()) {
			return false;
		}
	}

	// handle statuses list
	if (!vcfg["status"].empty()) {
		bool status_found = false;

		for (const std::string status : utils::split(vcfg["status"])) {
			if(u.get_state(status)) {
				status_found = true;
				break;
			}
		}

		if(!status_found) {
			return false;
		}
	}

	if (vcfg.has_child("has_attack")) {
		const vconfig& weap_filter = vcfg.child("has_attack");
		bool has_weapon = false;
		for(const attack_type& a : u.attacks()) {
			if(a.matches_filter(weap_filter.get_parsed_config())) {
				has_weapon = true;
				break;
			}
		}
		if(!has_weapon) {
			return false;
		}
	} else if (!vcfg["has_weapon"].blank()) {
		std::string weapon = vcfg["has_weapon"];
		bool has_weapon = false;
		for(const attack_type& a : u.attacks()) {
			if(a.id() == weapon) {
				has_weapon = true;
				break;
			}
		}
		if(!has_weapon) {
			return false;
		}
	}

	if (!vcfg["role"].blank() && vcfg["role"].str() != u.get_role()) {
		return false;
	}

	if (!vcfg["ai_special"].blank() && ((vcfg["ai_special"].str() == "guardian") != u.get_state(unit::STATE_GUARDIAN))) {
		return false;
	}

	if (!vcfg["canrecruit"].blank() && vcfg["canrecruit"].to_bool() != u.can_recruit()) {
		return false;
	}

	if (!vcfg["recall_cost"].blank() && vcfg["recall_cost"].to_int(-1) != u.recall_cost()) {
		return false;
	}

	if (!vcfg["level"].blank() && vcfg["level"].to_int(-1) != u.level()) {
		return false;
	}

	if (!vcfg["defense"].blank() && vcfg["defense"].to_int(-1) != u.defense_modifier(fc_.get_disp_context().map().get_terrain(loc))) {
		return false;
	}

	if (!vcfg["movement_cost"].blank() && vcfg["movement_cost"].to_int(-1) != u.movement_cost(fc_.get_disp_context().map().get_terrain(loc))) {
		return false;
	}

	// Now start with the new WML based comparison.
	// If a key is in the unit and in the filter, they should match
	// filter only => not for us
	// unit only => not filtered
	config unit_cfg; // No point in serializing the unit once for each [filter_wml]!
	for (const vconfig& wmlcfg : vcfg.get_children("filter_wml")) {
			config fwml = wmlcfg.get_parsed_config();
			/* Check if the filter only cares about variables.
			   If so, no need to serialize the whole unit. */
			config::all_children_itors ci = fwml.all_children_range();
			if (fwml.all_children_count() == 1 && 
				fwml.attribute_count() == 1 &&
			    ci.front().key == "variables") {
				if (!u.variables().matches(ci.front().cfg))
					return false;
			} else {
				if (unit_cfg.empty())
					u.write(unit_cfg);
				if (!unit_cfg.matches(fwml))
					return false;
			}
	}

	for (const vconfig& vision : vcfg.get_children("filter_vision")) {
		std::set<int> viewers;

		// Use standard side filter
		side_filter ssf(vision, &fc_);
		std::vector<int> sides = ssf.get_teams();
		viewers.insert(sides.begin(), sides.end());

		bool found = false;
		for (const int viewer : viewers) {
			bool fogged = fc_.get_disp_context().teams()[viewer - 1].fogged(loc);
			bool hiding = u.invisible(loc, fc_.get_disp_context());
			bool unit_hidden = fogged || hiding;
			if (vision["visible"].to_bool(true) != unit_hidden) {
				found = true;
				break;
			}
		}
		if (!found) {return false;}
	}

	if (vcfg.has_child("filter_adjacent")) {
		const unit_map& units = fc_.get_disp_context().units();
		map_location adjacent[6];
		get_adjacent_tiles(loc, adjacent);

		for (const vconfig& adj_cfg : vcfg.get_children("filter_adjacent")) {
			int match_count=0;
			unit_filter filt(adj_cfg, &fc_, use_flat_tod_);

			config::attribute_value i_adjacent = adj_cfg["adjacent"];
			std::vector<map_location::DIRECTION> dirs;
			if (i_adjacent.blank()) {
				dirs = map_location::default_dirs();
			} else {
				dirs = map_location::parse_directions(i_adjacent);
			}

			std::vector<map_location::DIRECTION>::const_iterator j, j_end = dirs.end();
			for (j = dirs.begin(); j != j_end; ++j) {
				unit_map::const_iterator unit_itor = units.find(adjacent[*j]);
				if (unit_itor == units.end() || !filt(*unit_itor, u)) {
					continue;
				}
				boost::optional<bool> is_enemy;
				if (!adj_cfg["is_enemy"].blank()) {
					is_enemy = adj_cfg["is_enemy"].to_bool();
				}
				if (!is_enemy || *is_enemy ==
				    fc_.get_disp_context().teams()[u.side() - 1].is_enemy(unit_itor->side())) {
					++match_count;
				}
			}

			static std::vector<std::pair<int,int> > default_counts = utils::parse_ranges("1-6");
			config::attribute_value i_count = adj_cfg["count"];
			if(!in_ranges(match_count, !i_count.blank() ? utils::parse_ranges(i_count) : default_counts)) {
				return false;
			}
		}
	}

	if (!vcfg["find_in"].blank()) {
		// Allow filtering by searching a stored variable of units
		if (const game_data * gd = fc_.get_game_data()) {
			try
			{
				variable_access_const vi = gd->get_variable_access_read(vcfg["find_in"]);
				bool found_id = false;
				for (const config& c : vi.as_array())
				{
					if(c["id"] == u.id())
						found_id = true;
				}
				if(!found_id)
				{
					return false;
				}
			}
			catch(const invalid_variablename_exception&)
			{
				return false;
			}
		}
	}
	if (!vcfg["formula"].blank()) {
		try {
			const unit_callable main(loc,u);
			game_logic::map_formula_callable callable(&main);
			if (u2) {
				std::shared_ptr<unit_callable> secondary(new unit_callable(*u2));
				callable.add("other", variant(secondary.get()));
				// It's not destroyed upon scope exit because the variant holds a reference
			}
			const game_logic::formula form(vcfg["formula"]);
			if(!form.evaluate(callable).as_bool()) {
				return false;
			}
			return true;
		} catch(game_logic::formula_error& e) {
			lg::wml_error() << "Formula error in unit filter: " << e.type << " at " << e.filename << ':' << e.line << ")\n";
			// Formulae with syntax errors match nothing
			return false;
		}
	}

	if (!vcfg["lua_function"].blank()) {
		if (game_lua_kernel * lk = fc_.get_lua_kernel()) {
			bool b = lk->run_filter(vcfg["lua_function"].str().c_str(), u);
			if (!b) return false;
		}
	}

	return true;
}
Save_grid_dialog::Save_grid_dialog( const GsTL_project* project,
				    QWidget * parent, const char * name) 
  : QFileDialog( parent ) {

  if (name)
    setObjectName(name);
  
  setModal(true);
  setFileMode( QFileDialog::AnyFile );
  setLabelText(QFileDialog::Accept, "Save");

  QGridLayout * lo = dynamic_cast<QGridLayout*>(this->layout());
  
  grid_selector_ = new QComboBox( this);
  QLabel* label = new QLabel( "Grid to save", this );
  lo->addWidget(label, 4,0,Qt::AlignLeft);
  lo->addWidget(grid_selector_,4,1,Qt::AlignLeft);



  //TL modified
  propList_ = new QListWidget( this);
  propList_->setSelectionMode(QAbstractItemView::ExtendedSelection);
  QLabel* plabel = new QLabel( "Properties to save", this );
  lo->addWidget(plabel, 5,0,Qt::AlignLeft);
  lo->addWidget(propList_,5,1,Qt::AlignLeft);


  //TL + AB modified
  masked_as_regular_frame_ = new QFrame(this);
  saveRegular_ = new QCheckBox(masked_as_regular_frame_);
  //saveRegular_->setDisabled(true);
  QLabel* slabel = new QLabel( "Save masked grid as Cartesian", masked_as_regular_frame_ );
  QHBoxLayout* mgrid_to_cgrid_layout = new QHBoxLayout(masked_as_regular_frame_);
  mgrid_to_cgrid_layout->addWidget(slabel);
  mgrid_to_cgrid_layout->addWidget(saveRegular_);
  masked_as_regular_frame_->setLayout(mgrid_to_cgrid_layout);
  lo->addWidget(masked_as_regular_frame_,6,1,Qt::AlignLeft);
  masked_as_regular_frame_->setVisible(false);

 // lo->addWidget(slabel, 6,0,Qt::AlignLeft);
 // lo->addWidget(saveRegular_,6,1,Qt::AlignLeft);
  
  // search for available output filters

  QStringList filters;
  SmartPtr<Named_interface> ni_filter = 
    Root::instance()->interface( outfilters_manager );
  Manager* dir = dynamic_cast<Manager*>( ni_filter.raw_ptr() );
  appli_assert( dir );

  Manager::type_iterator begin = dir->begin();
  Manager::type_iterator end = dir->end();
  for( ; begin != end ; ++begin ) {
    SmartPtr<Output_filter> outf(dynamic_cast<Output_filter*>(dir->new_interface(*begin).raw_ptr() ));
    if( outf->type_data() != "Grid") continue;
    QString filt( begin->c_str() );
    filt += " (*.*)";
    filters.push_back( filt ) ;
  }

  setFilters( filters );

  
  // search for available grids

  const GsTL_project::String_list& grids = project->objects_list();
  typedef GsTL_project::String_list::const_iterator const_iterator;
  for( const_iterator it = grids.begin(); it != grids.end(); ++it ) {
    grid_selector_->addItem( it->c_str() );
  }

  QObject::connect( grid_selector_, SIGNAL( activated(const QString &) ),
	  this, SLOT( gridChanged(const QString &) ) );

  if (!grid_selector_->currentText().isEmpty())
	gridChanged(grid_selector_->currentText());
}
Example #19
0
static INT_PTR CALLBACK EngineDlgProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	WORD param;
	BOOL bTranslated = FALSE;
	static bool loading = true;
	static int changeCount = 0;
	switch (uMsg) {
	case WM_INITDIALOG:
		loading = true;
		TranslateDialogDefault(hwndDlg);
		CheckDlgButton(hwndDlg, IDC_ENGINE_SILENT, Config.EngineStaySilent ? BST_CHECKED : BST_UNCHECKED);
		CheckDlgButton(hwndDlg, IDC_ENGINE_LOWERCASE, Config.EngineMakeLowerCase ? BST_CHECKED : BST_UNCHECKED);
		CheckDlgButton(hwndDlg, IDC_ENGINE_UNDERSTAND_ALWAYS, Config.EngineUnderstandAlways ? BST_CHECKED : BST_UNCHECKED);
		SetDlgItemText(hwndDlg, IDC_MINDFILE, Config.MindFileName);
		EnableWindow(GetDlgItem(hwndDlg, IDC_BTNSAVE), blInit);
		UpdateUnderstandAlwaysCheckbox(hwndDlg);
		loading = false;
		return TRUE;
	
	case WM_COMMAND:
		param = LOWORD(wParam);
		if (param == IDC_ENGINE_SILENT && HIWORD(wParam) == BN_CLICKED)
			UpdateUnderstandAlwaysCheckbox(hwndDlg);

		switch (param) {
		case IDC_BTNPATH:
			{
				const size_t fileNameSize = 5000;
				TCHAR *filename = new TCHAR[fileNameSize];
				TCHAR *fullname = GetFullName(Config.MindFileName);
				mir_tstrcpy(filename, fullname);
				if (fullname != Config.MindFileName)
					delete[] fullname;

				OPENFILENAME ofn = { 0 };
				ofn.lStructSize = sizeof(OPENFILENAME);
				ofn.hwndOwner = GetParent(hwndDlg);

				TCHAR *mind = TranslateTS(MIND_FILE_DESC);
				TCHAR *anyfile = TranslateTS(ALL_FILES_DESC);
				CMString filt(FORMAT, MIND_DIALOG_FILTER, mind, anyfile);
				filt.Replace('\1', '\0');

				ofn.lpstrFilter = filt;
				ofn.lpstrFile = filename;
				ofn.nMaxFile = fileNameSize;
				ofn.Flags = OFN_FILEMUSTEXIST;
				ofn.lpstrInitialDir = tszPath;
				if (!GetOpenFileName(&ofn)) {
					delete[] filename;
					break;
				}

				TCHAR *origf = filename;
				TCHAR *f = filename;
				TCHAR *p = tszPath;
				while (*p && *f) {
					TCHAR p1 = (TCHAR)CharLower((TCHAR*)(long)*p++);
					TCHAR f1 = (TCHAR)CharLower((TCHAR*)(long)*f++);
					if (p1 != f1)
						break;
				}
				if (!*p)
					filename = f;
				Config.MindFileName = filename;
				SetDlgItemText(hwndDlg, IDC_MINDFILE, filename);
				delete[] origf;
			}

		case IDC_BTNRELOAD:
			{
				const TCHAR *c = Config.MindFileName;
				int line;
				bTranslated = blInit = LoadMind(c, line);
				if (!bTranslated) {
					TCHAR message[5000];
					mir_sntprintf(message, TranslateTS(FAILED_TO_LOAD_BASE), line, c);
					MessageBox(NULL, message, TranslateTS(BOLTUN_ERROR), MB_ICONERROR | MB_TASKMODAL | MB_OK);
				}
			}
			break;

		default:
			if (!loading) {
				if (param == IDC_MINDFILE/* && HIWORD(wParam) != EN_CHANGE*/)
					break;
				SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
			}
		}
		break;

	case WM_NOTIFY:
		NMHDR *nmhdr = (NMHDR*)lParam;
		switch (nmhdr->code) {
		case PSN_APPLY:
		case PSN_KILLACTIVE:
			Config.EngineStaySilent = IsDlgButtonChecked(hwndDlg, IDC_ENGINE_SILENT) == BST_CHECKED ? TRUE : FALSE;
			Config.EngineMakeLowerCase = IsDlgButtonChecked(hwndDlg, IDC_ENGINE_LOWERCASE) == BST_CHECKED ? TRUE : FALSE;
			Config.EngineUnderstandAlways = IsDlgButtonChecked(hwndDlg, IDC_ENGINE_UNDERSTAND_ALWAYS) == BST_CHECKED ? TRUE : FALSE;
			UpdateEngine();
			TCHAR c[MAX_MIND_FILE];
			bTranslated = GetDlgItemText(hwndDlg, IDC_MINDFILE, c, _countof(c));
			if (bTranslated)
				Config.MindFileName = c;
			else
				Config.MindFileName = DEFAULT_MIND_FILE;
			return TRUE;
		}
		break;
	}
	return 0;
}