Example #1
0
static int vidioc_s_fmt(struct file *file, void *prv, struct v4l2_format *f)
{
	struct g2d_ctx *ctx = prv;
	struct g2d_dev *dev = ctx->dev;
	struct vb2_queue *vq;
	struct g2d_frame *frm;
	struct g2d_fmt *fmt;
	int ret = 0;

	/* Adjust all values accordingly to the hardware capabilities
	 * and chosen format. */
	ret = vidioc_try_fmt(file, prv, f);
	if (ret)
		return ret;
	vq = v4l2_m2m_get_vq(ctx->m2m_ctx, f->type);
	if (vb2_is_busy(vq)) {
		v4l2_err(&dev->v4l2_dev, "queue (%d) bust\n", f->type);
		return -EBUSY;
	}
	frm = get_frame(ctx, f->type);
	if (IS_ERR(frm))
		return PTR_ERR(frm);
	fmt = find_fmt(f);
	if (!fmt)
		return -EINVAL;
	frm->width	= f->fmt.pix.width;
	frm->height	= f->fmt.pix.height;
	frm->size	= f->fmt.pix.sizeimage;
	/* Reset crop settings */
	frm->o_width	= 0;
	frm->o_height	= 0;
	frm->c_width	= frm->width;
	frm->c_height	= frm->height;
	frm->right	= frm->width;
	frm->bottom	= frm->height;
	frm->fmt	= fmt;
	frm->stride	= f->fmt.pix.bytesperline;
	return 0;
}
Example #2
0
void* SP_thread::Entry()
{
  auto sp = new quan::serial_port(m_filename.c_str());
  sp->init();
  

  auto frsky_sp = new frsky_serial_port(sp);
  
  while ( !this->TestDestroy()){

     unsigned char buffer[9];
     if(frsky_sp->get_frame(buffer) == true)
     {
         call(buffer); // exec the fn in the buffer
     }
  };
 
  delete frsky_sp;
  wxCriticalSectionLocker lock(m_frsky_dataDialog->m_sp_threadCS);
  m_frsky_dataDialog->m_sp_thread = nullptr;
  return 0;
}
Example #3
0
    void pipeline_processing_block::handle_frame(frame_holder frame, synthetic_source_interface* source)
    {
        std::lock_guard<std::mutex> lock(_mutex);
        auto comp = dynamic_cast<composite_frame*>(frame.frame);
        if (comp)
        {
            for (auto i = 0; i< comp->get_embedded_frames_count(); i++)
            {
                auto f = comp->get_frame(i);
                f->acquire();
                _last_set[f->get_stream()->get_unique_id()] = f;
            }

            for (int s : _streams_ids)
            {
                if (!_last_set[s])
                    return;
            }

            std::vector<frame_holder> set;
            for (auto&& s : _last_set)
            {
                set.push_back(s.second.clone());
            }
            auto fref = source->allocate_composite_frame(std::move(set));
            if (!fref)
            {
                LOG_ERROR("Failed to allocate composite frame");
                return;
            }
            _queue->enqueue(fref);
        }
        else
        {
            LOG_ERROR("Non composite frame arrived to pipeline::handle_frame");
            assert(false);
        }
    }
Example #4
0
void VideoDevice::sendData()
{
    char* frame;
    size_t frame_len;


    if(-1==open_device())
    {
        exit(EXIT_FAILURE);
    }
    qDebug("init device");
    if(-1==init_device())
    {
        exit(EXIT_FAILURE);
    }
    qDebug("start caping");
    if(-1 == start_capturing())
    {
        exit(EXIT_FAILURE);
    }

    if(-1 == get_frame((void**)&frame, &frame_len))
    {
        exit(EXIT_FAILURE);
    }

    //qDebug("addr: %u, len: %d",(unsigned int)frame, frame_len);

    udp->sendData((char *)frame, frame_len);


    if(-1 == unget_frame())
    {
        exit(EXIT_FAILURE);
    }


}
Example #5
0
/********************** *
 * Event handlers       *
 * *********************/
void event_key_special(int key, int x, int y) {
    if (active_window->state == STATE_LOADING) {
        return;
    }

    int step = 0, i;
    switch (key) {
    case GLUT_KEY_LEFT:
        step = -1;
        break;
    case GLUT_KEY_RIGHT:
        step = 1;
        break;
    case GLUT_KEY_UP:
        step = 10;
        break;
    case GLUT_KEY_DOWN:
        step = -10;
        break;
    case GLUT_KEY_HOME: // Perform match on all frames
        for (i = 1; i <= active_window->nfr; i++) {
            struct frame *fr = get_frame(active_window->frames, i);
            if (fr->flag & HAS_MATCH) {
                continue;
            }
            templateMatch(active_window, i, MARGIN, active_window->tmpl);
            fr->flag |= HAS_MATCH;
            calculate_speed(fr);
        }
        printf("Done matching\n");
    }

    // Update view
    if (active_window->cur+step > 0 && active_window->cur+step <= active_window->nfr) {
        active_window->cur += step;
        glutPostRedisplay();
    }
}
Example #6
0
ENV_type Environment_Extend_C(NIL_type)
  { ENV_type extended_environment;
    FRM_type frame;
    UNS_type scope,
             size;
    VEC_type extended_environment_vector;
    size = size_environment(Current_environment);
    size += 1;
    extended_environment_vector = Cache_Make_Vector_C(size);
    extended_environment = (ENV_type)extended_environment_vector;
    for (scope = 1;
         scope < size;
         scope += 1)
      { frame = get_frame(Current_environment,
                          scope);
        set_frame(extended_environment,
                  scope,
                  frame); }
    apply_MRK(Current_frame);
    set_frame(extended_environment,
              size,
              Current_frame);
    return extended_environment; }
Example #7
0
int ConvertPipeline::handle_frame(uvc_frame_t *frame) {
	ENTER();

	Mutex::Autolock lock(pipeline_mutex);

	if (next_pipeline) {
		uvc_frame_t *copy = frame;
		if (mFrameConvFunc) {
			copy = get_frame(frame->actual_bytes);
			if (LIKELY(copy)) {
				const uvc_error_t r = mFrameConvFunc(frame, copy);
				if (UNLIKELY(r)) {
					LOGW("failed to convert:%d", r);
					recycle_frame(copy);
					copy = frame;
				}
			}
		}
		next_pipeline->queueFrame(copy);
	}

	RETURN(1, int);
}
void vframe::print_on(JavaThread* thread, outputStream *st) const
{
  // RKANE: Do we need a ResourceMark object here?  
  ResourceMark rm;

  frame fr = get_frame();
  const char *frame_style = "UNKNOWN";
CodeBlob*cb=CodeCache::find_blob(fr.pc());
  if( fr.is_interpreted_frame() ) 
    frame_style = "INTERPRETER";
  else if( cb && cb->is_native_method() ) 
    frame_style = "NATIVE";
  else if( cb && cb->is_c1_method() )
    frame_style = "COMPILER1";
  else if( cb && cb->is_c2_method() )
    frame_style = "COMPILER2";

  if (!st) st=tty;
  st->print("====== %s: %s @ %d =======\n", frame_style, method()->name_and_sig_as_C_string(), bci() );
st->print_cr(" ### NOT printing any further information on tty.");
st->print_cr("Stop trying to print stacks to the tty or if so print it using its own functions.");
  return; 
}
Example #9
0
FramePool::FramePool(unsigned long _base_frame_no,
                     unsigned long _nframes,
                     unsigned long _info_frame_no)
{
    base_frame_number        = _base_frame_no;
    number_of_frames_managed = _nframes;
    managament_frame_number  = _info_frame_no;

   /* 
     * Add the physical addresses of free frames to the frame pool list. 
     * The get_frame routine will allocate frames from this list
     */
   if (_info_frame_no == 0)
   {
       /*
        * We initialize the bit map pointer here. Since it is static, 
        * it will be accessible to both the frame pools.
        */
        frame_map = reinterpret_cast <unsigned long*> (base_frame_number * FramePool::FRAME_SIZE);
        memset(frame_map, 0, FramePool::FRAME_SIZE);
        get_frame();
   }
}
Example #10
0
    syncer_proccess_unit::syncer_proccess_unit()
        : _matcher((new timestamp_composite_matcher({})))
    {
        _matcher->set_callback([this](frame_holder f, syncronization_environment env)
        {

            std::stringstream ss;
            ss << "SYNCED: ";
            auto composite = dynamic_cast<composite_frame*>(f.frame);
            for (int i = 0; i < composite->get_embedded_frames_count(); i++)
            {
                auto matched = composite->get_frame(i);
                ss << matched->get_stream()->get_stream_type() << " " << matched->get_frame_number() << ", "<<std::fixed<< matched->get_frame_timestamp()<<"\n";
            }

            LOG_DEBUG(ss.str());
            env.matches.enqueue(std::move(f));
        });

        auto f = [&](frame_holder frame, synthetic_source_interface* source)
        {
            single_consumer_queue<frame_holder> matches;

            {
                std::lock_guard<std::mutex> lock(_mutex);
                _matcher->dispatch(std::move(frame), { source, matches });
            }

            frame_holder f;
            while (matches.try_dequeue(&f))
            {
                get_source().frame_ready(std::move(f));
            }
        };
        set_processing_callback(std::shared_ptr<rs2_frame_processor_callback>(
            new internal_frame_processor_callback<decltype(f)>(f)));
    }
Example #11
0
/* Mouse position hook.  */
void
w32_console_mouse_position (FRAME_PTR *f,
			    int insist,
			    Lisp_Object *bar_window,
			    enum scroll_bar_part *part,
			    Lisp_Object *x,
			    Lisp_Object *y,
			    unsigned long *time)
{
  BLOCK_INPUT;

  insist = insist;

  *f = get_frame ();
  *bar_window = Qnil;
  *part = 0;
  SELECTED_FRAME ()->mouse_moved = 0;

  XSETINT (*x, movement_pos.X);
  XSETINT (*y, movement_pos.Y);
  *time = movement_time;

  UNBLOCK_INPUT;
}
Example #12
0
/* Mouse position hook.  */
void
w32_console_mouse_position (FRAME_PTR *f,
			    int insist,
			    Lisp_Object *bar_window,
			    enum scroll_bar_part *part,
			    Lisp_Object *x,
			    Lisp_Object *y,
			    Time *time)
{
  block_input ();

  insist = insist;

  *f = get_frame ();
  *bar_window = Qnil;
  *part = 0;
  SELECTED_FRAME ()->mouse_moved = 0;

  XSETINT (*x, movement_pos.X);
  XSETINT (*y, movement_pos.Y);
  *time = movement_time;

  unblock_input ();
}
Example #13
0
void Active::update_frame()
{
    Image * new_image = direction_data->frames[get_frame()];
    if (new_image == image)
        return;
    image = new_image;
    image->load();

#ifdef CHOWDREN_ACTIVE_REPLACE_COLOR
    if (!replacer.empty())
        image = replacer.apply_direct(image, image);
#endif

    sprite_col.set_image(image, image->hotspot_x, image->hotspot_y);
    update_action_point();

#ifdef CHOWDREN_DEFER_COLLISIONS
    // make sure the old AABB is not out of bounds
    if (sprite_col.type == SPRITE_COLLISION) {
        old_aabb[2] = old_aabb[0] + image->width;
        old_aabb[3] = old_aabb[1] + image->height;
    }
#endif
}
Example #14
0
/** Compute forces and update particles **/
void ParticleSystem::computeForcesAndUpdateParticles(float t)
{
	m_gravity[1] = -VAL(PS_GRAVITY);
#ifdef _DEBUG
#if 0 //just curious
	if (m_cache.find(t) == m_cache.end())
		printf("NEW time %f\n", t);
	else
		printf("OLD time %f\n", t);
	m_cache[t];
#endif
#endif
	//only handle unbaken situation
	if (m_cache.find(get_frame(t)) == m_cache.end()) { //no, not baken
		if (simulate) {
			//initialize
			//the last tick
			auto last_iter = m_cache.rbegin();
			if (last_iter == m_cache.rend()) { //the ticks are empty
				//this is the very first tick in history
				//add new particles
				for (auto particleSrc : m_particleSrcs) {
					particleSrc->newParticles(m_cache[get_frame(t)]);
				}
			}
			else { //there's a last tick
				float delta_t = 1.0f / bake_fps;
				int last_frame = last_iter->first;
				for (int frame = last_frame + 1; frame <= get_frame(t); ++frame) {
#ifdef _DEBUG
					printf("simulating frame %d\n", frame);
#endif
					m_cache[frame] = m_cache[frame-1]; //copy the last tick state

					//add new particles
					for (auto particleSrc : m_particleSrcs) {
						particleSrc->newParticles(m_cache[frame]);
					}

					//simulate the particles
					auto iter = m_cache[frame].begin();
					while (iter != m_cache[frame].end()) {
						Particle& particle = *iter;
						particle.life -= delta_t;

						//kill the ones that are dead
						if (particle.life < 0) {
							iter = m_cache[frame].erase(iter);
							continue;
						}
						else {
							++iter;
						}

						//evolve
						particle.position += particle.velocity * delta_t;
						if (ModelerApplication::Instance()->rb() && particle.position[1] < m_groundY) {
							particle.position[1] = 2 * m_groundY - particle.position[1];
							particle.velocity[1] = -particle.velocity[1];
						}
						else if (ModelerApplication::Instance()->flock()) {
							//steer towards the average of neighbors
							double radius = 1.5;
							Vec3d avgV;
							int count = 0;
							for (auto par : m_cache[frame]) {
								if ((par.position - particle.position).length2() < radius * radius) {
									++count;
									avgV += par.velocity;
								}
							}
							avgV /= count;
							particle.velocity = 0.5 * avgV + 0.5 * particle.velocity;
						} else {
							particle.velocity += m_gravity * delta_t;
						}
					}
				}	
			}
		}
	}
}
Example #15
0
int sys_fork()
{
  update_user_to_system();
  int PID=-1;
  int i;
  int j;
  // creates the child process
/*
 a) Get a free task_struct for the process. If there is no space for a new process, an error
   will be returned.
b) Inherit system data: copy the parent’s task_union to the child. Determine whether it is necessary to modify the page table of the parent to access the child’s system data. The
   copy_data function can be used to copy.
c) Initialize field dir_pages_baseAddr with a new directory to store the process address
   space using the allocate_DIR routine.
d) Search physical pages in which to map logical pages for data+stack of the child process
   (using the alloc_frames function). If there is no enough free pages, an error will be
   return.
*/

//a
  if(list_empty( &freequeue )){
    update_system_to_user(current());
    return -ENOMEM;
  }
  struct list_head * freequeue_head = list_first( &freequeue );
  struct task_struct * child_struct  = list_head_to_task_struct(freequeue_head);
  list_del(freequeue_head); // not in freequeue anymore
  
//b 
  struct task_struct * current_struct = current();
  union task_union * current_union = (union task_union *) current_struct;
  union task_union * child_union = (union task_union *) child_struct;
  copy_data(current_union, child_union, sizeof(union task_union));
  // TODO determine  whether it is necessary to modify the page table of the parent to access the child’s system data

//c 
  allocate_DIR(child_struct);

//d
  int physical_pages[NUM_PAG_DATA];
  for(i = 0; i < NUM_PAG_DATA; ++i)
  {
    physical_pages[i] = alloc_frame();
    if( physical_pages[i] < 0){
      for(j = i-1; j >= 0; j--)
      {
        free_frame((unsigned int)j);
      }
      update_system_to_user(current());
      return -EAGAIN;
    }
  }


/*
e) Inherit user data:
    i) Create new address space: Access page table of the child process through the direc-
       tory field in the task_struct to initialize it (get_PT routine can be used):
       A) Page table entries for the system code and data and for the user code can be a
          copy of the page table entries of the parent process (they will be shared)
*/
  page_table_entry * child_pt = get_PT(child_struct);
  page_table_entry * parent_pt = get_PT(current_struct);
  int child_logical_address;
  for(child_logical_address = 0; child_logical_address < NUM_PAG_KERNEL + NUM_PAG_CODE; child_logical_address++)
  {
    int physical_parent_frame = get_frame(parent_pt, child_logical_address);
    set_ss_pag( child_pt, child_logical_address, physical_parent_frame);
  }
/*     B) Page table entries for the user data+stack have to point to new allocated pages
          which hold this region*/

  for(; child_logical_address < NUM_PAG_KERNEL + NUM_PAG_CODE + NUM_PAG_DATA; child_logical_address++)
  {
    set_ss_pag(child_pt, child_logical_address, physical_pages[child_logical_address - (NUM_PAG_KERNEL + NUM_PAG_CODE)]);
  }



/*
   ii) Copy the user data+stack pages from the parent process to the child process. The
       child’s physical pages cannot be directly accessed because they are not mapped in
       the parent’s page table. In addition, they cannot be mapped directly because the
       logical parent process pages are the same. They must therefore be mapped in new
       entries of the page table temporally (only for the copy). Thus, both pages can be
       accessed simultaneously as follows:
       A) Use temporal free entries on the page table of the parent. Use the set_ss_pag and
          del_ss_pag functions.
       B) Copy data+stack pages.
       C) Free temporal entries in the page table and flush the TLB to really disable the
          parent process to access the child pages.
*/

  // direccion logica del systemcode+systemdata+usercode = direccion logica datos user
  



  
  int parent_log = NUM_PAG_KERNEL + NUM_PAG_CODE;  
  for(i = 0; i < NUM_PAG_DATA; ++i){
  	set_ss_pag(parent_pt, parent_log + NUM_PAG_DATA + i, physical_pages[i]);
  	copy_data( (void*) ((parent_log + i) * PAGE_SIZE), (void*) ((parent_log + NUM_PAG_DATA + i) * PAGE_SIZE), PAGE_SIZE );
	del_ss_pag(parent_pt, parent_log + NUM_PAG_DATA + i);
  }
  
  
  
  //set_cr3(parent_pt); // flush tlb fallaba, por que? TODO
  set_cr3(get_DIR(current_struct));

/*
f) Assign a new PID to the process. The PID must be different from its position in the
    task_array table.
g) Initialize the fields of the task_struct that are not common to the child.
     i) Think about the register or registers that will not be common in the returning of the
        child process and modify its content in the system stack so that each one receive its
        values when the context is restored.
h) Prepare the child stack emulating a call to context_switch and be able to restore its
    context in a known position. The stack of the new process must be forged so it can be
    restored at some point in the future by a task_switch. In fact the new process has to
    restore its hardware context and continue the execution of the user process, so you can
    create a routine ret_from_fork which does exactly this. And use it as the restore point
    like in the idle process initialization 4.4.
 i) Insert the new process into the ready list: readyqueue. This list will contain all processes
    that are ready to execute but there is no processor to run them.
 j) Return the pid of the child process.
*/
  if(_PID == INT_MAX){
    update_system_to_user(current());
    return -1; // please restart
  }
  child_struct->PID = _PID++;
  PID = child_struct->PID;

/* 
* 0		-19
* ret_from_fork	-18
* sys_call_handler // -17
* SAVEALL // -16	
* iret    // -5
*/	
 
  
  child_struct->kernel_esp = (unsigned long *)&child_union->stack[KERNEL_STACK_SIZE-19];
  child_union->stack[KERNEL_STACK_SIZE-19] = 0;
  child_union->stack[KERNEL_STACK_SIZE-18] = (int)ret_from_fork;

  list_add_tail(&child_struct->list, &readyqueue);
  child_struct->stats.elapsed_total_ticks = get_ticks();
  child_struct->stats.user_ticks = 0;
  child_struct->stats.system_ticks = 0;
  child_struct->stats.blocked_ticks = 0;
  child_struct->stats.ready_ticks = 0;
  child_struct->stats.total_trans = 0; 
  child_struct->stats.remaining_ticks = 0;
//  last_forked_child = child_struct = 0;
  update_system_to_user(current());
  return PID; 
}
Example #16
0
// Main
int main(int argc, char ** argv) {

	// Choose the best GPU in case there are multiple available
	choose_GPU();

	// Keep track of the start time of the program
	long long program_start_time = get_time();
	
	if (argc !=3){
	fprintf(stderr, "usage: %s <input file> <number of frames to process>", argv[0]);
	exit(1);
	}
	
	// Let the user specify the number of frames to process
	int num_frames = atoi(argv[2]);
	
	// Open video file
	char *video_file_name = argv[1];
	
	avi_t *cell_file = AVI_open_input_file(video_file_name, 1);
	if (cell_file == NULL)	{
		AVI_print_error("Error with AVI_open_input_file");
		return -1;
	}
	
	int i, j, *crow, *ccol, pair_counter = 0, x_result_len = 0, Iter = 20, ns = 4, k_count = 0, n;
	MAT *cellx, *celly, *A;
	double *GICOV_spots, *t, *G, *x_result, *y_result, *V, *QAX_CENTERS, *QAY_CENTERS;
	double threshold = 1.8, radius = 10.0, delta = 3.0, dt = 0.01, b = 5.0;
	
	// Extract a cropped version of the first frame from the video file
	MAT *image_chopped = get_frame(cell_file, 0, 1, 0);
	printf("Detecting cells in frame 0\n");
	
	// Get gradient matrices in x and y directions
	MAT *grad_x = gradient_x(image_chopped);
	MAT *grad_y = gradient_y(image_chopped);
	
	// Allocate for gicov_mem and strel
	gicov_mem = (float*) malloc(sizeof(float) * grad_x->m * grad_y->n);
	strel = (float*) malloc(sizeof(float) * strel_m * strel_n);

	m_free(image_chopped);

	int grad_m = grad_x->m;
	int grad_n = grad_y->n;
	
#pragma acc data create(sin_angle,cos_angle,theta,tX,tY) \
	create(gicov_mem[0:grad_x->m*grad_y->n])
{
	// Precomputed constants on GPU
	compute_constants();

	// Get GICOV matrices corresponding to image gradients
	long long GICOV_start_time = get_time();
	MAT *gicov = GICOV(grad_x, grad_y);
	long long GICOV_end_time = get_time();

	// Dilate the GICOV matrices
	long long dilate_start_time = get_time();
	MAT *img_dilated = dilate(gicov);
	long long dilate_end_time = get_time();
} /* end acc data */
	
	// Find possible matches for cell centers based on GICOV and record the rows/columns in which they are found
	pair_counter = 0;
	crow = (int *) malloc(gicov->m * gicov->n * sizeof(int));
	ccol = (int *) malloc(gicov->m * gicov->n * sizeof(int));
	for(i = 0; i < gicov->m; i++) {
		for(j = 0; j < gicov->n; j++) {
			if(!double_eq(m_get_val(gicov,i,j), 0.0) && double_eq(m_get_val(img_dilated,i,j), m_get_val(gicov,i,j)))
			{
				crow[pair_counter]=i;
				ccol[pair_counter]=j;
				pair_counter++;
			}
		}
	}

	GICOV_spots = (double *) malloc(sizeof(double) * pair_counter);
	for(i = 0; i < pair_counter; i++)
		GICOV_spots[i] = sqrt(m_get_val(gicov, crow[i], ccol[i]));
	
	G = (double *) calloc(pair_counter, sizeof(double));
	x_result = (double *) calloc(pair_counter, sizeof(double));
	y_result = (double *) calloc(pair_counter, sizeof(double));
	
	x_result_len = 0;
	for (i = 0; i < pair_counter; i++) {
		if ((crow[i] > 29) && (crow[i] < BOTTOM - TOP + 39)) {
			x_result[x_result_len] = ccol[i];
			y_result[x_result_len] = crow[i] - 40;
			G[x_result_len] = GICOV_spots[i];
			x_result_len++;
		}
	}
	
	// Make an array t which holds each "time step" for the possible cells
	t = (double *) malloc(sizeof(double) * 36);
	for (i = 0; i < 36; i++) {
		t[i] = (double)i * 2.0 * PI / 36.0;
	}
	
	// Store cell boundaries (as simple circles) for all cells
	cellx = m_get(x_result_len, 36);
	celly = m_get(x_result_len, 36);
	for(i = 0; i < x_result_len; i++) {
		for(j = 0; j < 36; j++) {
			m_set_val(cellx, i, j, x_result[i] + radius * cos(t[j]));
			m_set_val(celly, i, j, y_result[i] + radius * sin(t[j]));
		}
	}
	
	A = TMatrix(9,4);
	V = (double *) malloc(sizeof(double) * pair_counter);
	QAX_CENTERS = (double * )malloc(sizeof(double) * pair_counter);
	QAY_CENTERS = (double *) malloc(sizeof(double) * pair_counter);
	memset(V, 0, sizeof(double) * pair_counter);
	memset(QAX_CENTERS, 0, sizeof(double) * pair_counter);
	memset(QAY_CENTERS, 0, sizeof(double) * pair_counter);

	// For all possible results, find the ones that are feasibly leukocytes and store their centers
	k_count = 0;
	for (n = 0; n < x_result_len; n++) {
		if ((G[n] < -1 * threshold) || G[n] > threshold) {
			MAT * x, *y;
			VEC * x_row, * y_row;
			x = m_get(1, 36);
			y = m_get(1, 36);

			x_row = v_get(36);
			y_row = v_get(36);

			// Get current values of possible cells from cellx/celly matrices
			x_row = get_row(cellx, n, x_row);
			y_row = get_row(celly, n, y_row);
			uniformseg(x_row, y_row, x, y);

			// Make sure that the possible leukocytes are not too close to the edge of the frame
			if ((m_min(x) > b) && (m_min(y) > b) && (m_max(x) < cell_file->width - b) && (m_max(y) < cell_file->height - b)) {
				MAT * Cx, * Cy, *Cy_temp, * Ix1, * Iy1;
				VEC  *Xs, *Ys, *W, *Nx, *Ny, *X, *Y;
				Cx = m_get(1, 36);
				Cy = m_get(1, 36);
				Cx = mmtr_mlt(A, x, Cx);
				Cy = mmtr_mlt(A, y, Cy);
				
				Cy_temp = m_get(Cy->m, Cy->n);
				
				for (i = 0; i < 9; i++)
					m_set_val(Cy, i, 0, m_get_val(Cy, i, 0) + 40.0);
					
				// Iteratively refine the snake/spline
				for (i = 0; i < Iter; i++) {
					int typeofcell;
					
					if(G[n] > 0.0) typeofcell = 0;
					else typeofcell = 1;
					
					splineenergyform01(Cx, Cy, grad_x, grad_y, ns, delta, 2.0 * dt, typeofcell);
				}
				
				X = getsampling(Cx, ns);
				for (i = 0; i < Cy->m; i++)
					m_set_val(Cy_temp, i, 0, m_get_val(Cy, i, 0) - 40.0);
				Y = getsampling(Cy_temp, ns);
				
				Ix1 = linear_interp2(grad_x, X, Y);
				Iy1 = linear_interp2(grad_x, X, Y);
				Xs = getfdriv(Cx, ns);
				Ys = getfdriv(Cy, ns);
				
				Nx = v_get(Ys->dim);
				for (i = 0; i < Ys->dim; i++)
					v_set_val(Nx, i, v_get_val(Ys, i) / sqrt(v_get_val(Xs, i)*v_get_val(Xs, i) + v_get_val(Ys, i)*v_get_val(Ys, i)));
					
				Ny = v_get(Xs->dim);
				for (i = 0; i < Xs->dim; i++)
					v_set_val(Ny, i, -1.0 * v_get_val(Xs, i) / sqrt(v_get_val(Xs, i)*v_get_val(Xs, i) + v_get_val(Ys, i)*v_get_val(Ys, i)));
					
				W = v_get(Nx->dim);
				for (i = 0; i < Nx->dim; i++)
					v_set_val(W, i, m_get_val(Ix1, 0, i) * v_get_val(Nx, i) + m_get_val(Iy1, 0, i) * v_get_val(Ny, i));
					
				V[n] = mean(W) / std_dev(W);
				
				// Find the cell centers by computing the means of X and Y values for all snaxels of the spline contour
				QAX_CENTERS[k_count] = mean(X);
				QAY_CENTERS[k_count] = mean(Y) + TOP;
				
				k_count++;
				
				// Free memory
				v_free(W);
				v_free(Ny);
				v_free(Nx);
				v_free(Ys);
				v_free(Xs);
				m_free(Iy1);
				m_free(Ix1);
				v_free(Y);
				v_free(X);
				m_free(Cy_temp);
				m_free(Cy);
				m_free(Cx);				
			}

			// Free memory
			v_free(y_row);
			v_free(x_row);
			m_free(y);
			m_free(x);
		}
	}
	
	// Free memory
	free(gicov_mem);
	free(strel);
	free(V);
	free(ccol);
	free(crow);
	free(GICOV_spots);
	free(t);
	free(G);
	free(x_result);
	free(y_result);
	m_free(A);
	m_free(celly);
	m_free(cellx);
	m_free(img_dilated);
	m_free(gicov);
	m_free(grad_y);
	m_free(grad_x);
	
	// Report the total number of cells detected
	printf("Cells detected: %d\n\n", k_count);
	
	// Report the breakdown of the detection runtime
	printf("Detection runtime\n");
	printf("-----------------\n");
	printf("GICOV computation: %.5f seconds\n", ((float) (GICOV_end_time - GICOV_start_time)) / (1000*1000));
	printf("   GICOV dilation: %.5f seconds\n", ((float) (dilate_end_time - dilate_start_time)) / (1000*1000));
	printf("            Total: %.5f seconds\n", ((float) (get_time() - program_start_time)) / (1000*1000));
	
	// Now that the cells have been detected in the first frame,
	//  track the ellipses through subsequent frames
	if (num_frames > 1) printf("\nTracking cells across %d frames\n", num_frames);
	else                printf("\nTracking cells across 1 frame\n");
	long long tracking_start_time = get_time();
	int num_snaxels = 20;
	ellipsetrack(cell_file, QAX_CENTERS, QAY_CENTERS, k_count, radius, num_snaxels, num_frames);
	printf("           Total: %.5f seconds\n", ((float) (get_time() - tracking_start_time)) / (float) (1000*1000*num_frames));	
	
	// Report total program execution time
    printf("\nTotal application run time: %.5f seconds\n", ((float) (get_time() - program_start_time)) / (1000*1000));

	return 0;
}
Example #17
0
static int
do_mouse_event (MOUSE_EVENT_RECORD *event,
		struct input_event *emacs_ev)
{
  static DWORD button_state = 0;
  static Lisp_Object last_mouse_window;
  DWORD but_change, mask, flags = event->dwEventFlags;
  int i;

  switch (flags)
    {
    case MOUSE_MOVED:
      {
	struct frame *f = get_frame ();
	Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
	int mx = event->dwMousePosition.X, my = event->dwMousePosition.Y;

	mouse_moved_to (mx, my);

	if (f->mouse_moved)
	  {
	    if (hlinfo->mouse_face_hidden)
	      {
		hlinfo->mouse_face_hidden = 0;
		clear_mouse_face (hlinfo);
	      }

	    /* Generate SELECT_WINDOW_EVENTs when needed.  */
	    if (!NILP (Vmouse_autoselect_window))
	      {
		Lisp_Object mouse_window = window_from_coordinates (f, mx, my,
								    0, 0);
		/* A window will be selected only when it is not
		   selected now, and the last mouse movement event was
		   not in it.  A minibuffer window will be selected iff
		   it is active.  */
		if (WINDOWP (mouse_window)
		    && !EQ (mouse_window, last_mouse_window)
		    && !EQ (mouse_window, selected_window))
		  {
		    struct input_event event;

		    EVENT_INIT (event);
		    event.kind = SELECT_WINDOW_EVENT;
		    event.frame_or_window = mouse_window;
		    event.arg = Qnil;
		    event.timestamp = movement_time;
		    kbd_buffer_store_event (&event);
		  }
		last_mouse_window = mouse_window;
	      }
	    else
	      last_mouse_window = Qnil;

	    previous_help_echo_string = help_echo_string;
	    help_echo_string = help_echo_object = help_echo_window = Qnil;
	    help_echo_pos = -1;
	    note_mouse_highlight (f, mx, my);
	    /* If the contents of the global variable help_echo has
	       changed (inside note_mouse_highlight), generate a HELP_EVENT.  */
	    if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
	      gen_help_event (help_echo_string, selected_frame,
			      help_echo_window, help_echo_object,
			      help_echo_pos);
	  }
	/* We already called kbd_buffer_store_event, so indicate the
	   the caller it shouldn't.  */
	return 0;
      }
    case MOUSE_WHEELED:
    case MOUSE_HWHEELED:
      {
	struct frame *f = get_frame ();
	int mx = event->dwMousePosition.X, my = event->dwMousePosition.Y;
	bool down_p = (event->dwButtonState & 0x10000000) != 0;

	emacs_ev->kind =
	  flags == MOUSE_HWHEELED ? HORIZ_WHEEL_EVENT : WHEEL_EVENT;
	emacs_ev->code = 0;
	emacs_ev->modifiers = down_p ? down_modifier : up_modifier;
	emacs_ev->modifiers |=
	  w32_kbd_mods_to_emacs (event->dwControlKeyState, 0);
	XSETINT (emacs_ev->x, mx);
	XSETINT (emacs_ev->y, my);
	XSETFRAME (emacs_ev->frame_or_window, f);
	emacs_ev->arg = Qnil;
	emacs_ev->timestamp = GetTickCount ();
	return 1;
      }
    case DOUBLE_CLICK:
    default:	/* mouse pressed or released */
      /* It looks like the console code sends us a button-release
	 mouse event with dwButtonState == 0 when a window is
	 activated and when the mouse is first clicked.  Ignore this
	 case.  */
      if (event->dwButtonState == button_state)
	return 0;

      emacs_ev->kind = MOUSE_CLICK_EVENT;

      /* Find out what button has changed state since the last button
	 event.  */
      but_change = button_state ^ event->dwButtonState;
      mask = 1;
      for (i = 0; mask; i++, mask <<= 1)
	if (but_change & mask)
	  {
	    if (i < NUM_TRANSLATED_MOUSE_BUTTONS)
	      emacs_ev->code = emacs_button_translation[i];
	    else
	      emacs_ev->code = i;
	    break;
	  }

      button_state = event->dwButtonState;
      emacs_ev->modifiers =
	w32_kbd_mods_to_emacs (event->dwControlKeyState, 0)
	| ((event->dwButtonState & mask) ? down_modifier : up_modifier);

      XSETFASTINT (emacs_ev->x, event->dwMousePosition.X);
      XSETFASTINT (emacs_ev->y, event->dwMousePosition.Y);
      XSETFRAME (emacs_ev->frame_or_window, get_frame ());
      emacs_ev->arg = Qnil;
      emacs_ev->timestamp = GetTickCount ();

      return 1;
    }
}
Example #18
0
unsigned char *newframe()
{
    get_frame();
    process_image((unsigned char *)buffers[buf.index].start, buf.bytesused, w, h);
    return dst_buf;
}
Example #19
0
	int BowlingGame::score_spare(int num) const { 
		auto nextFrame = get_frame(num + 1);
		return 10 + nextFrame.first;
	}
Example #20
0
/***********
 * The voicecase has four 'options'
 * - difference is way off, reset
 * - diff > 0, we may need to grow
 * - diff < 0, we may need to shrink
 * - everything else
 */
static int get_voicecase(jitterbuffer *jb, void **data, long now, long interpl, long diff) 
{
  jb_frame *frame;
  int result;
  
   // * - difference is way off, reset
  if (diff > jb->settings.max_diff || -diff > jb->settings.max_diff) {
    jb_err("wakko diff in get_voicecase\n");
    reset(jb); //reset hist because the timestamps are wakko. 
    result = JB_NOFRAME;
  //- diff > 0, we may need to grow
  } else if ((diff > 0) && 
                   (now > (jb->last_adjustment + jb->settings.wait_grow) 
                    || (now + jb->current + interpl) < get_next_framets(jb) ) ) { //grow
    /* first try to grow */
    if (diff<interpl/2) {
      jb_dbg("ag");
      jb->current +=diff;
    } else {
      jb_dbg("aG");
      /* grow by interp frame len */
      jb->current += interpl;
    }
    jb->last_adjustment = now;
    result = get_voice(jb, data, now, interpl);
  //- diff < 0, we may need to shrink
  } else if ( (diff < 0) 
                && (now > (jb->last_adjustment + jb->settings.wait_shrink)) 
                && ((-diff) > jb->settings.extra_delay) ) {
    /* now try to shrink
     * if there is a frame shrink by frame length
     * otherwise shrink by interpl
     */
    jb->last_adjustment = now;
    
    frame = get_frame(jb, now - jb->current);
    if(frame) {
      jb_dbg("as");
      /* shrink by frame size we're throwing out */
      jb->info.frames_dropped++;
      jb->current -= frame->ms;
      frame_free(frame);
    } else {
      jb_dbg("aS");
      /* shrink by interpl */
      jb->current -= interpl;
    }
    result = get_voice(jb, data, now, interpl);
  } else  { 
    /* if it is not the time to play a result = JB_NOFRAME
     * else We try to play a frame if a frame is available
     * and not late it is played otherwise 
     * if available it is dropped and the next is tried
     * last option is interpolating
     */
    if (now - jb->current < jb->next_voice_time) {
      jb_dbg("aN");
      result = JB_NOFRAME;
    } else {
      frame = get_frame(jb, now - jb->current);
      if (frame) { //there is a frame
        /* voice frame is late */
        if(frame->ts < jb->next_voice_time) {   //late
          jb_dbg("aL");
          jb->info.frames_late++;
          frame_free(frame);
          result = get_voice(jb, data, now, interpl);
        } else {
          jb_dbg("aP");
          /* normal case; return the frame, increment stuff */
          *data = frame->data;
          frame->data = NULL;
          jb->next_voice_time = frame->ts + frame->ms;
          jb->cnt_successive_interp = 0;
          frame_free(frame);
          result = JB_OK;
        }
      } else { // no frame, thus interpolate
        jb->cnt_successive_interp++;
        /* assume silence instead of continuing to interpolate */
        if (jb->settings.max_successive_interp && jb->cnt_successive_interp >= jb->settings.max_successive_interp) {
          jb->info.silence = 1;
          jb->silence_begin_ts = jb->next_voice_time;
        }
        jb_dbg("aI");
        jb->next_voice_time += interpl;
        result = JB_INTERP;
      }
    }
  }
  return result;

}
Example #21
0
void c_scene_fx::func10()
{
    switch(get_seq())
    {
    case 1:
        if ( get_elaps_frames() == 0 )
        {
            angZ = scene_rand_rng(360);
            for (int8_t i = 0; i < 4; i++)
                scene_add_effect(parent, 101, x,y,dir,1);
        }
        if (process())
            active = false;
        break;
    case 2:
        if ( get_elaps_frames() == 0 )
        {
            angZ = scene_rand_rng(360);

            for (int8_t i = 0; i < 6; i++)
                scene_add_effect(parent, 101, x,y,dir,1);

            for (int8_t i = 0; i < 3; i++)
            {
                scene_add_effect(parent, 102, x,y,dir,1);
                scene_add_effect(parent, 103, x,y,dir,1);
            }
        }
        if (process())
            active = false;
        break;
    case 3:
        if ( get_elaps_frames() == 0 )
        {
            angZ = scene_rand_rng(360);
            scene_add_effect(parent, 100, x,y,dir,1);

            for (int8_t i = 0; i < 8; i++)
                scene_add_effect(parent, 101, x,y,dir,1);

            for (int8_t i = 0; i < 6; i++)
            {
                scene_add_effect(parent, 102, x,y,dir,1);
                scene_add_effect(parent, 103, x,y,dir,1);
            }
        }
        if (process())
            active = false;
        break;
    case 4:
        if ( get_elaps_frames() == 0)
        {
            angZ = scene_rand_rng(360);
            scene_add_effect(parent, 104, x,y,dir,1);

            for (int8_t i = 0; i < 10; i++)
                scene_add_effect(parent, 101, x,y,dir,1);

            for (int8_t i = 0; i < 6; i++)
            {
                scene_add_effect(parent, 102, x,y,dir,1);
                scene_add_effect(parent, 103, x,y,dir,1);
            }
        }
        if (process())
            active = false;
        break;
    case 5:
        if ( get_elaps_frames() == 0 )
        {
            angZ = scene_rand_rng(360);

            for (int8_t i = 0; i < 4; i++)
                scene_add_effect(parent, 101, x,y,dir,1);
        }
        if (process())
            active = false;
        break;
    case 6:
        if ( get_elaps_frames() == 0 )
        {
            angZ = scene_rand_rng(360);

            for (int8_t i = 0; i < 6; i++)
                scene_add_effect(parent, 101, x,y,dir,1);

            for (int8_t i = 0; i < 3; i++)
            {
                scene_add_effect(parent, 102, x,y,dir,1);
                scene_add_effect(parent, 103, x,y,dir,1);
            }
        }
        if (process())
            active = false;
        break;

    case 7:
        if ( get_elaps_frames() == 0 )
        {
            angZ = scene_rand_rng(360);

            scene_add_effect(parent, 100, x,y,dir,1);

            for (int8_t i = 0; i < 8; i++)
                scene_add_effect(parent, 101, x,y,dir,1);

            for (int8_t i = 0; i < 3; i++)
            {
                scene_add_effect(parent, 102, x,y,dir,1);
                scene_add_effect(parent, 103, x,y,dir,1);
            }
        }
        scaleY = scaleX += 0.1;

        if (process())
            active = false;
        break;
    case 8:
        if ( get_elaps_frames() == 0 )
        {
            angZ = scene_rand_rng(360);

            scene_add_effect(parent, 100, x,y,dir,1);

            for (int8_t i = 0; i < 10; i++)
                scene_add_effect(parent, 101, x,y,dir,1);

            for (int8_t i = 0; i < 5; i++)
            {
                scene_add_effect(parent, 102, x,y,dir,1);
                scene_add_effect(parent, 103, x,y,dir,1);
            }
        }
        scaleY = scaleX += 0.1;

        if (process())
            active = false;
        break;
    case 9:
    case 10:
    case 11:
    case 12:
        if ( get_elaps_frames() == 0 )
            angZ = scene_rand_rng(40) - 20;

        if (process())
            active = false;
        break;
    case 13:
        if ( get_elaps_frames() == 0 )
        {
            angZ = scene_rand_rng(360);

            scene_add_effect(parent, 105, x,y,dir,1);

            for (int8_t i = 0; i < 4; i++)
                scene_add_effect(parent, 102, x,y,dir,1);
        }
        if (process())
            active = false;
        break;
    case 14:
        if ( get_elaps_frames() == 0 )
        {
            angZ = scene_rand_rng(360);

            scene_add_effect(parent, 106, x,y,dir,1);

            for (int8_t i = 0; i < 6; i++)
                scene_add_effect(parent, 102, x,y,dir,1);
        }
        if (process())
            active = false;
        break;
    case 15:
    case 16:
    case 38:
        if ( get_elaps_frames() == 0 )
            angZ = scene_rand_rng(360);

        if (process())
            active = false;
        break;
    case 50:
        if ( get_elaps_frames() == 0 )
            for (int8_t i = 0; i < 4; i++)
                scene_add_effect(parent, 101, x,y,dir,1);

        if (process())
            active = false;
        break;
    case 51:
        if ( get_elaps_frames() == 0 )
            for (int8_t i = 0; i < 4; i++)
                scene_add_effect(parent, 103, x,y,dir,1);

        if (process())
            active = false;
        break;
    case 52:
        if ( get_elaps_frames() == 0 )
        {
            scene_play_sfx(37);
            for (int8_t i = 0; i < 3; i++)
                scene_add_effect(parent, 101, x,y,dir,1);
        }

        if (process())
            active = false;
        break;
    case 53:
        if ( get_elaps_frames() == 0 )
        {
            scene_play_sfx(38);
            scene_add_effect(parent, 104, x,y,dir,1);

            for (int8_t i = 0; i < 16; i++)
                scene_add_effect(parent, 101, x,y,dir,1);

            for (int8_t i = 0; i < 8; i++)
            {
                scene_add_effect(parent, 102, x,y,dir,1);
                scene_add_effect(parent, 103, x,y,dir,1);
            }

            for (int8_t i = 0; i < 6; i++)
                scene_add_effect(parent, 200, x,y,dir,1);

            for (int8_t i = 0; i < 10; i++)
                scene_add_effect(parent, 201, x,y,dir,1);
        }
        angZ += 5;
        scaleX += 0.3;
        scaleY += 0.3;

        if (c_A >= 10)
        {
            c_A -= 10;
            c_R -= 10;
            c_G -= 10;
            if (process())
                active = false;
        }
        else
            active = false;
        break;
    case 54:
        if ( get_elaps_frames() == 0 )
        {
            scene_play_sfx(25);
            scene_add_effect(parent, 104, x,y,dir,1);

            for (int8_t i = 0; i < 8; i++)
                scene_add_effect(parent, 101, x,y,dir,1);

            for (int8_t i = 0; i < 4; i++)
            {
                scene_add_effect(parent, 102, x,y,dir,1);
                scene_add_effect(parent, 103, x,y,dir,1);
            }
        }
        scaleX += 0.3;
        scaleY += 0.3;

        if (c_A >= 10)
        {
            c_A -= 10;
            if (process())
                active = false;
        }
        else
            active = false;
        break;
    case 58:
    case 59:
        scaleY = scaleX += 0.4;
        if (c_A >= 20)
        {
            c_A -= 20;
            if (process())
                active = false;
        }
        else
            active = false;
        break;
    case 61:
        if ( get_elaps_frames() == 0 )
            scene_play_sfx(43);

        scaleX += 0.3;
        scaleY += 0.3;

        if (c_A >= 20)
        {
            c_A -= 20;
            c_R -= 20;
            c_G -= 20;
            if (process())
                active = false;
        }
        else
            active = false;
        break;
    case 62:
        if (get_elaps_frames() == 0)
        {
            scene_play_sfx(45);
            scene_add_effect(parent, 113,x,y,dir,1);
        }
        scaleX+=0.2;
        scaleY+=0.2;

        if (c_A >= 25)
        {
            c_A -= 25;
            c_R -= 25;
            c_G -= 25;
            if (process())
                active = false;
        }
        else
            active = false;

        break;
    case 63:
        if ( get_elaps_frames() == 0 )
        {
            scene_play_sfx(43);
            scene_add_effect(parent,60,x,y,dir,-1);
        }
        scaleX += 0.1;
        scaleY += 0.15;
        if (process())
            active = false;
        break;
    case 64:
        if ( get_elaps_frames() == 0 )
        {
            scene_play_sfx(50);

            scene_add_effect(parent, 104, x,y,dir,1);

            for (int8_t i = 0; i < 16; i++)
                scene_add_effect(parent, 101, x,y,dir,1);

            for (int8_t i = 0; i < 8; i++)
            {
                scene_add_effect(parent, 102, x,y,dir,1);
                scene_add_effect(parent, 103, x,y,dir,1);
            }
        }
        scaleX += 0.3;
        scaleY += 0.3;

        if (c_A >= 10)
        {
            c_A -= 10;
            if (process())
                active = false;
        }
        else
            active = false;
        break;

    case 65:
    case 66:
    case 67:
    case 68:
        if ( get_elaps_frames() == 0 )
        {
            scene_add_effect(parent, 104, x,y,dir,1);

            for (int8_t i = 0; i < 16; i++)
                scene_add_effect(parent, 101, x,y,dir,1);

            for (int8_t i = 0; i < 8; i++)
            {
                scene_add_effect(parent, 102, x,y,dir,1);
                scene_add_effect(parent, 103, x,y,dir,1);
            }
        }
        scaleX += 0.3;
        scaleY += 0.3;

        if (c_A >= 10)
        {
            c_A -= 10;
            if (process())
                active = false;
        }
        else
            active = false;
        break;
    case 69:
        if ( get_elaps_frames() == 0 )
            scene_play_sfx(35);

        scaleX += 0.3;
        scaleY += 0.3;
        angZ -= 25;

        if (c_A >= 15)
        {
            c_A -= 15;
            c_R -= 15;
            c_G -= 15;
            if (process())
                active = false;
        }
        else
            active = false;

        break;
    case 70:
        if ( get_elaps_frames() == 0 )
            scene_play_sfx(53);

        scaleX += 0.3;
        scaleY += 0.3;
        angZ -= 25;

        if (c_A >= 15)
        {
            c_A -= 15;
            c_R -= 15;
            c_G -= 15;
            if (process())
                active = false;
        }
        else
            active = false;

        break;
    case 71:
        if ( get_elaps_frames() == 0 )
            scene_play_sfx(54);

        if ( get_frame() == 0 )
            scaleY = scaleX *= 0.8;
        else if (get_frame() == 1)
        {
            scaleY = scaleX += 0.3;
            angZ -= 25;

            if (c_A >= 15)
            {
                c_A -= 15;
                c_B -= 15;
            }
            else
            {
                active = false;
            }
        }

        if (active && process())
            active = false;

        break;
    case 100:
        scaleX += 0.5;
        scaleY += 0.5;

        if (c_A >= 20)
        {
            c_A -= 20;
            c_R -= 20;
            c_G -= 20;
            if (process())
                active = false;
        }
        else
            active = false;
        break;
    case 101:
        v_inerc--;
        y += v_inerc;
        x += h_inerc;

        if ( v_inerc < 0.0  &&  y < 0.0 )
            if ( scene_rand_rng(100) < 15 )
                v_inerc = (-v_inerc) * 0.5;

        if (c_A > 20)
        {
            scaleX *= 0.8;
            scaleY *= 0.8;
            c_A -= 20;
            c_R -= 20;
            c_G -= 20;

            if (scaleX <= 0 || process())
                active=false;
        }
        else
            active = false;
        break;
    case 102:
    case 103:
        x += h_inerc*dir;
        y += v_inerc;

        if (c_A > 10)
        {
            scaleY *= 0.98;
            scaleX += 0.05;
            c_A -= 10;
            if (process())
                active = false;
        }
        else
            active = false;

        break;
    case 104:
        scaleX += 1.25;
        scaleY += 1.25;

        if (c_A >= 20)
        {
            c_A -= 20;
            c_R -= 20;
            c_G -= 20;
            if (process())
                active = false;
        }
        else
            active = false;
        break;
    case 105:
        scaleY = scaleX += 0.15;
        if (c_A > 15)
        {
            c_A -= 15;
            c_R -= 15;
            c_G -= 15;
            if (process())
                active = false;
        }
        else
            active = false;
        break;
    case 60:
    case 106:
        scaleX += 0.4;
        scaleY += 0.4;

        if (c_A >= 20)
        {
            c_A -= 20;
            c_R -= 20;
            c_G -= 20;
            if (process())
                active = false;
        }
        else
            active = false;
        break;
    case 112:
    case 137:
    {
        c_meta *chr = parent;
        if ( chr )
        {
            x = chr->getX();
            y = chr->getY()+100;

            par1 -= 0.3;
            if (par1 < 1.0)
                par1 = 1.0;
            par2 += 3.0;
            if (get_seq() == 137)
            {
                angZ ++;
                scaleY = scaleX = (sin_deg(par2) * 0.1 + 1.1) * par1;
            }
            else
            {
                angZ --;
                scaleY = scaleX = (sin_deg(par2) * 0.1 + 1.0) * par1;
            }
            if (get_frame() == 0)
            {
                if (chr->chrt->damage_limit < 100 || chr->chrt->get_seq() == 99)
                    if ( chr->chrt->field_4C2 <= 0)
                    {
                        set_frame(1);
                        break;
                    }
            }

            if (get_frame() == 1)
            {
                if (c_A > 20)
                {
                    c_A -= 20;
                    c_R -= 20;
                    c_G -= 20;
                }
                else
                    active = false;
            }

            if (active && process() )
                active = false;

        }
        else
            active = false;
    }
    break;
    case 113:

        scaleX+=0.4;
        scaleY+=0.4;
        if (c_A >= 15)
        {
            c_A -= 15;
            c_R -= 15;
            c_G -= 15;
            if (process())
                active = false;
        }
        else
            active = false;

        break;
    case 115:
        if ( get_elaps_frames() == 0 )
        {
            angZ = scene_rand_rng(360);
            scaleX = 2.0;
            scaleY = 2.0;
        }
        angZ += 2;
        if (get_frame() == 41)
        {
            if (c_A >= 5)
                c_A -= 5;
            else
                active = false;
        }
        if (active && process())
            active = false;
        break;
    case 123:
        if ( get_elaps_frames() == 0 )
            v_inerc = -10;

        if (c_A >= 15)
        {
            y += v_inerc;
            c_A -= 15;
            c_R -= 15;
            c_G -= 15;
            if (process())
                active = false;
        }
        else
            active = false;
        break;
    case 124:
        if ( get_elaps_frames() == 0 )
            h_inerc = -10.0;

        if ( c_A >= 15 )
        {
            x += dir * h_inerc;
            c_A -= 15;
            c_R -= 15;
            c_G -= 15;
            if (process())
                active = false;
        }
        else
            active = false;

        break;
    case 125:
        scaleX += 0.2;
        scaleY += 0.2;

        if (c_A >= 25)
        {
            c_A -= 25;
            c_R -= 25;
            c_G -= 25;
            if (process())
                active = false;
        }
        else
            active = false;
        break;
    case 136:
        scaleX -= 0.005;
        scaleY += 0.02;
        y += 15;

        c_A = sin_deg(get_elaps_frames() * 6) * 255.0;
        if (get_elaps_frames() * 6 >= 180)
            active = false;

        if (active && process())
            active = false;

        break;
    case 131:
    case 132:
    case 133:
    case 134:
    case 139:
        if (get_elaps_frames() == 0)
            v_inerc = 20;

        v_inerc--;
        if (v_inerc < 1)
            v_inerc = 1;

        scaleX += 0.1;
        if (scaleX > 1)
            scaleX = 1;

        scaleY = scaleX;

        if (get_elaps_frames() >= 60)
        {
            if (c_A > 15)
                c_A -= 15;
            else
                active = false;
        }
        y += v_inerc;
        if (active && process())
            active = false;
        break;
    case 140:
        scaleX += par1 * 0.5;
        par1 *= 0.94;

        if (c_A >= 5)
        {
            c_A -= 5;
            c_R -= 5;
            c_G -= 5;
            if (process())
                active = false;
        }
        else
            active = false;
        break;
    case 141:
        scaleY = scaleX *= 0.85;
        if (c_A >= 15)
        {
            c_A -= 15;
            c_R -= 15;
            c_G -= 15;
            if (process())
                active = false;
        }
        else
            active = false;
        break;
    case 135:
    case 142:
        scaleY = scaleX += 0.3;
        if (c_A >= 15)
        {
            c_A -= 15;
            if (process())
                active = false;
        }
        else
            active = false;
        break;
    case 150:
    case 152:
    case 154:
        scaleY = scaleX += 0.15;
        if (c_A >= 15)
        {
            c_A -= 15;
            if (process())
                active = false;
        }
        else
            active = false;
        break;
    case 151:
    case 153:
    case 155:
        if (par1 == 0)
        {
            if (c_A >= 240)
            {
                c_A = 255;
                par1 = 1.0;
                y += 10;
                if (process())
                    active = false;
                break;
            }
            c_A += 15;
        }
        else
        {
            if (c_A < 15)
            {
                active = false;
                break;
            }
            c_A -= 15;
        }
        y += 10;

        if (active && process())
            active = false;
        break;
    case 160:
        if ( get_elaps_frames() >= 25 )
        {
            if (c_A >= 15 )
                c_A -= 15;
            else
            {
                active = false;
                break;
            }
        }
        if (get_elaps_frames() % 6 == 0)
            scene_add_effect(parent,161,x,y,dir,-1);

        angZ += 6;
        v_inerc -= 0.3;
        h_inerc *= 0.96;

        if ( v_inerc + y <= 0 && v_inerc < 0 )
            v_inerc = -v_inerc;

        x += h_inerc * dir;
        y += v_inerc;

        if ( process() )
            active = false;
        break;
    case 161:
        if ( c_A >= 15 )
        {
            c_A -= 15;
            v_inerc -= 0.005;
            y += v_inerc;

            if (process())
                active = false;
        }
        else
            active = false;
        break;
    case 162:
    case 163:
    case 164:
        if (c_A >= par1)
        {
            angZ += par2;
            c_A -= par1;

            v_inerc -= 0.3;
            h_inerc *= 0.92;

            if (y + v_inerc <= 0 && v_inerc < 0)
                v_inerc = -v_inerc;

            x += h_inerc * dir;
            y += v_inerc;

            if (process())
                active = false;
        }
        else
            active = false;
        break;
    case 165:
        if (c_A >= 15)
        {
            c_A -= 15;
            angZ -= 15;
            scaleY = scaleX += 0.3;

            if (process())
                active = false;
        }
        else
            active = false;
        break;
    case 200:
        if ( get_elaps_frames() == 0 )
            set_vec_speed(scene_rand_rng(180),scene_rand_rng(10) + 5);

        angZ += 6;
        v_inerc -= 0.5;

        if (scene_rand_rng(100) < 20)
            scene_add_effect(parent,202,x,y,dir,1);

        if (v_inerc < 0 && y < 0)
        {
            if (scene_rand_rng(100) < 20)
                v_inerc = (-v_inerc) * 0.5;
            set_elaps_frames(60);
        }

        if ( get_elaps_frames() <= 60 || c_A >= 15 )
        {
            if( get_elaps_frames() > 60 )
                c_A -= 15;
            x += h_inerc * dir;
            y += v_inerc;

            if ( process() )
                active = false;
        }
        else
        {
            //HACK
            /*if ( weather == 21 )
            {
                weather_time += 40;
                if ( weather_time > 999 )
                    weather_time = 999;
            }
            else if ( weather_time >= 41 )
            {
                weather_time -= 40;
            }
            else
            {
                weather_time = 1;
            }*/
            scene_play_sfx(26);
            active = false;
        }
        break;
    case 201:
        if ( get_elaps_frames() == 0 )
            set_vec_speed(scene_rand_rng(180),scene_rand_rng(8)+4);

        angZ -= 12;
        v_inerc -= 0.25;

        if (scene_rand_rng(100) < 10)
            scene_add_effect(parent, 202, x,y,dir,1);

        if ( v_inerc < 0.0 && y < 0.0 )
        {
            if ( scene_rand_rng(100) < 20 )
                v_inerc = (-v_inerc) * 0.5;
            set_elaps_frames(60);
        }

        if ( get_elaps_frames() <= 60 || c_A >= 15 )
        {
            if( get_elaps_frames() > 60 )
                c_A -= 15;
            x += h_inerc * dir;
            y += v_inerc;

            if ( process() )
                active = false;
        }
        else
        {
            //HACK
            /*if ( weather == 21 )
            {
                weather_time += 5;
                if ( weather_time > 999 )
                    weather_time = 999;
            }
            else if ( weather_time >= 6 )
            {
                weather_time -= 5;
            }
            else
            {
                weather_time = 1;
            }*/
            scene_play_sfx(26);
            active = false;
        }
        break;
    case 202:
        if ( get_elaps_frames() == 0 )
            set_vec_speed(scene_rand_rng(180),1.0);

        v_inerc -= 0.05;

        if ( scaleX > 0.0 )
        {
            scaleX -= 0.01;
            scaleY -= 0.01;
        }

        if ( c_A >= 15 )
        {
            c_A -= 15;
            c_B -= 10;
            c_G -= 10;

            y += v_inerc;
            x += h_inerc * dir;

            if ( process() )
                active = false;
        }
        else
            active = false;
        break;
    case 126:
    case 127:
    case 128:
    case 129:
    case 138:
        if (process())
            active = false;
        break;
    default:
        active = false;
    }
}
Example #22
0
// Constructor
gams::platforms::OscJoystickPlatform::OscJoystickPlatform(
  madara::knowledge::KnowledgeBase * knowledge,
  gams::variables::Sensors * sensors,
  gams::variables::Self * self,
  const std::string & type)        
: gams::platforms::BasePlatform(knowledge, sensors, self),
  type_(type), event_fd_("/dev/input/js0")
{
  // as an example of what to do here, create a coverage sensor
  if (knowledge && sensors)
  {
    xyz_velocity_.set_name(".xyz_velocity", *knowledge, 3);

    // create a coverage sensor
    gams::variables::Sensors::iterator it = sensors->find("coverage");
    if (it == sensors->end()) // create coverage sensor
    {
      // get origin
      gams::pose::Position origin(gams::pose::gps_frame());
      madara::knowledge::containers::NativeDoubleArray origin_container;
      origin_container.set_name("sensor.coverage.origin", *knowledge, 3);
      origin.from_container(origin_container);

      // establish sensor
      gams::variables::Sensor* coverage_sensor =
        new gams::variables::Sensor("coverage", knowledge, 2.5, origin);
    (*sensors)["coverage"] = coverage_sensor;
    }
  (*sensors_)["coverage"] =(*sensors)["coverage"];
    status_.init_vars(*knowledge, get_id());
    
    build_prefixes();

    madara::transport::QoSTransportSettings settings_;

    knowledge::KnowledgeRecord event_handle =
      knowledge->get(".osc.local.handle");

    if (event_handle)
    {
      event_fd_ = event_handle.to_string();
    }

    settings_.hosts.push_back(
      knowledge->get(".osc.local.endpoint").to_string());

    settings_.hosts.push_back(
      knowledge->get(".osc.server.endpoint").to_string());

    knowledge::KnowledgeRecord initial_pose = knowledge->get(".initial_pose");

    is_created_ = knowledge->get(".osc.is_created").is_true();

    if (!initial_pose.is_array_type())
    {
      // by default initialize agents to [.id, .id, .id]
      initial_pose.set_index(2, 200);
      initial_pose.set_index(1, *(self_->id) * 300);
      initial_pose.set_index(0, *(self_->id) * 300);
    }
    else
    {
      double value = initial_pose.retrieve_index(0).to_double() * 100;
      initial_pose.set_index(0, value);
      value = initial_pose.retrieve_index(1).to_double() * 100;
      initial_pose.set_index(1, value);
      value = initial_pose.retrieve_index(2).to_double() * 100;
      initial_pose.set_index(2, value);
    }
    
    loiter_timeout_ = knowledge->get(".osc.loiter_timeout").to_double();

    if (loiter_timeout_ >= 0 && loiter_timeout_ < 5)
    {
      loiter_timeout_ = 5;
    }


    settings_.type =
      knowledge->get(".osc.transport.type").to_integer();
    if (settings_.type == 0)
    {
      settings_.type = madara::transport::UDP;
    }

    if (settings_.hosts[0] == "")
    {
      std::stringstream buffer;
      buffer << "127.0.0.1:";
      buffer <<(*(self_->id) + 8000);
      settings_.hosts[0] = buffer.str();
    }

    if (settings_.hosts[1] == "")
    {
      settings_.hosts[1] = "127.0.0.1:5555";
    }

    madara_logger_ptr_log(gams::loggers::global_logger.get(),
      gams::loggers::LOG_MAJOR,
      "gams::platforms::OscJoystickPlatform::const: OSC settings:" \
      " %s: .osc.local.endpoint=%s, .osc.server.endpoint=%s,"
      " .osc.transport_type=%d\n",
      self_->agent.prefix.c_str(),
      settings_.hosts[0].c_str(),
      settings_.hosts[1].c_str(),
     (int)settings_.type);

    madara_logger_ptr_log(gams::loggers::global_logger.get(),
      gams::loggers::LOG_MAJOR,
      "gams::platforms::OscJoystickPlatform::const: OSC prefixes:" \
      " %s: xy_vel=%s, xy_z=%s,"
      " pos=%s, rot=%s\n",
      self_->agent.prefix.c_str(),
      xy_velocity_prefix_.c_str(),
      z_velocity_prefix_.c_str(),
      position_prefix_.c_str(),
      rotation_prefix_.c_str());

    std::stringstream json_buffer;
    json_buffer << "{\"id\":";
    json_buffer << *(self_->id);
    json_buffer << ",\"port\":";
    json_buffer <<(*(self_->id) + 8000);
    json_buffer << ",\"location\":{";
    json_buffer << "\"x\": " <<
      initial_pose.retrieve_index(0).to_double() << ",";
    json_buffer << "\"y\": " <<
      initial_pose.retrieve_index(1).to_double() << ",";
    json_buffer << "\"z\": " <<
      initial_pose.retrieve_index(2).to_double();
    json_buffer << "},\"rotation\":{\n";
    json_buffer << "\"x\":" <<
      initial_pose.retrieve_index(3).to_double() << ",";
    json_buffer << "\"y\":" <<
      initial_pose.retrieve_index(4).to_double() << ",";
    json_buffer << "\"z\":" <<
      initial_pose.retrieve_index(5).to_double();
    json_buffer << "}}";
    

    json_creation_ = json_buffer.str();

    
    madara_logger_ptr_log(gams::loggers::global_logger.get(),
      gams::loggers::LOG_MAJOR,
      "gams::platforms::OscJoystickPlatform::const: creation JSON:" \
      " %s:\n%s\n",
      self_->agent.prefix.c_str(),
      json_creation_.c_str());

    osc_.create_socket(settings_);


    last_move_.frame(get_frame());
    last_move_.x(0);
    last_move_.y(0);
    last_move_.z(0);

    last_orient_.frame(get_frame());
    last_orient_.rx(0);
    last_orient_.ry(0);
    last_orient_.rz(0);

    move_timer_.start();
    last_thrust_timer_.start();
    last_position_timer_.start();

    if (!is_created_)
    {
      utility::OscUdp::OscMap values;
      std::string address = "/spawn/" + type_;
      values[address] = KnowledgeRecord(json_creation_);

      osc_.send(values);
    }

    status_.movement_available = 1;

    inverted_y_ = knowledge->get(".osc.local.inverted_y").is_true();
    inverted_z_ = knowledge->get(".osc.local.inverted_z").is_true();
    flip_xy_ = knowledge->get(".osc.local.flip_xy").is_true();

    madara_logger_ptr_log(gams::loggers::global_logger.get(),
      gams::loggers::LOG_MAJOR,
      "gams::platforms::OscJoystickPlatform::const: " \
      "%s: mapping to joystick %s\n",
      self_->agent.prefix.c_str(),
      event_fd_.c_str());

    threader_.set_data_plane(*knowledge);

    threader_.run(20, "ReadInput", new ::SenseThread());
  }
}
Example #23
0
	bool BowlingGame::is_strike(int num) const {
		return get_frame(num).first == 10;
	}
Example #24
0
	int BowlingGame::score_strike(int num) const { 
		auto strike_bonus = is_strike(num+1) 
			? 10 + get_frame(num + 2).first
			: score_normal(num + 1);
		return 10 + strike_bonus;
	}
Example #25
0
// Polls the sensor environment for useful information. Required.
int
gams::platforms::OscJoystickPlatform::sense(void)
{
  utility::OscUdp::OscMap values;
  values[position_prefix_];
  values[rotation_prefix_];

  madara_logger_ptr_log(gams::loggers::global_logger.get(),
    gams::loggers::LOG_MINOR,
    "gams::platforms::OscJoystickPlatform::sense: " \
    "%s: entering receive on OSC UDP\n",
    self_->agent.prefix.c_str());

  osc_.receive(values);

  madara_logger_ptr_log(gams::loggers::global_logger.get(),
    gams::loggers::LOG_MINOR,
    "gams::platforms::OscJoystickPlatform::sense: " \
    "%s: leaving receive on OSC UDP with %zu values\n",
    self_->agent.prefix.c_str(), values.size());
  
  if (values[position_prefix_].size() != 3)
  {
    values.erase(position_prefix_);
  }

  if (values[rotation_prefix_].size() != 3)
  {
    values.erase(rotation_prefix_);
  }

  for (auto value: values)
  {
    if (value.first == position_prefix_)
    {
      madara_logger_ptr_log(gams::loggers::global_logger.get(),
        gams::loggers::LOG_MINOR,
        "gams::platforms::OscJoystickPlatform::sense: " \
        "%s: Processing %s => platform location with %d values\n",
        self_->agent.prefix.c_str(),
        value.first.c_str(),(int)value.second.size());

      
      // convert osc order to the frame order
      pose::Position loc(get_frame());
      loc.from_array(value.second.to_doubles());

      // The UnrealEngine provides us with centimeters. Convert to meters.
      loc.x(loc.x()/100);
      loc.y(loc.y()/100);
      loc.z(loc.z()/100);

      // save the location to the self container
      loc.to_container(self_->agent.location);

      madara_logger_ptr_log(gams::loggers::global_logger.get(),
        gams::loggers::LOG_MAJOR,
        "gams::platforms::OscJoystickPlatform::sense: " \
        "%s: Platform location is [%s]\n",
        self_->agent.prefix.c_str(),
        self_->agent.location.to_record().to_string().c_str());

      is_created_ = true;
      last_position_timer_.start();
    }
    else if (value.first == rotation_prefix_)
    {
      madara_logger_ptr_log(gams::loggers::global_logger.get(),
        gams::loggers::LOG_MINOR,
        "gams::platforms::OscJoystickPlatform::sense: " \
        " %s: Processing %s => platform orientation with %d values\n",
        self_->agent.prefix.c_str(),
        value.first.c_str(),(int)value.second.size());

      
      // convert osc order to the frame order
      pose::Orientation angles(get_frame());
      angles.from_array(value.second.to_doubles());

      // save the location to the self container
      angles.to_container(self_->agent.orientation);

      madara_logger_ptr_log(gams::loggers::global_logger.get(),
        gams::loggers::LOG_MAJOR,
        "gams::platforms::OscJoystickPlatform::sense: " \
        "%s: Platform orientation is [%s]\n",
        self_->agent.prefix.c_str(),
        self_->agent.orientation.to_record().to_string().c_str());

      is_created_ = true;
    }
    else
    {
      madara_logger_ptr_log(gams::loggers::global_logger.get(),
        gams::loggers::LOG_ALWAYS,
        "gams::platforms::OscJoystickPlatform::sense: " \
        "%s: Unable to map topic %s to platform info\n",
        self_->agent.prefix.c_str(),
        value.first.c_str());
    }
    
  }

  if (values.size() == 0)
  {
    madara_logger_ptr_log(gams::loggers::global_logger.get(),
      gams::loggers::LOG_MAJOR,
      "gams::platforms::OscJoystickPlatform::sense: " \
      "%s: No received values from UnrealGAMS\n",
      self_->agent.prefix.c_str());
  }
  else
  {
    madara_logger_ptr_log(gams::loggers::global_logger.get(),
      gams::loggers::LOG_MAJOR,
      "gams::platforms::OscJoystickPlatform::sense: " \
      "%s: finished processing updates from OSC\n",
      self_->agent.prefix.c_str());
  }

  // check for last position timeout(need to recreate agent in sim)
  last_position_timer_.stop();

  //if we've never received a server packet for this agent, recreate
  if (last_position_timer_.duration_ds() > 60)
  {
    if (!is_created_)
    {
      madara_logger_ptr_log(gams::loggers::global_logger.get(),
        gams::loggers::LOG_ALWAYS,
        "gams::platforms::OscJoystickPlatform::sense: " \
        "%s: haven't heard from simulator in %f seconds. Recreating agent.\n",
        self_->agent.prefix.c_str(),
        last_position_timer_.duration_ds());

      is_created_ = false;

      madara_logger_ptr_log(gams::loggers::global_logger.get(),
        gams::loggers::LOG_ALWAYS,
        "gams::platforms::OscJoystickPlatform::sense: recreating agent with JSON:" \
        " %s:\n%s\n",
        self_->agent.prefix.c_str(),
        json_creation_.c_str());

      last_position_timer_.start();

      utility::OscUdp::OscMap values;
      std::string address = "/spawn/" + type_;
      values[address] = KnowledgeRecord(json_creation_);

      osc_.send(values);
    }
  }

  {
    // update the velocities that the user input through joystick
    utility::OscUdp::OscMap values;
    std::vector<double> xy_velocity;
    std::vector<double> z_velocity;

    if (flip_xy_)
    {
      xy_velocity.push_back(xyz_velocity_[1]);
      xy_velocity.push_back(xyz_velocity_[0]);
    }
    else
    {
      xy_velocity.push_back(xyz_velocity_[0]);
      xy_velocity.push_back(xyz_velocity_[1]);
    }
    
    z_velocity.push_back(xyz_velocity_[2]);

    values[xy_velocity_prefix_] = xy_velocity;
    values[z_velocity_prefix_] = z_velocity;

    madara_logger_ptr_log(gams::loggers::global_logger.get(),
      gams::loggers::LOG_ALWAYS,
      "Sending xyz velocities [%f, %f, %f]\n",
      xyz_velocity_[0], xyz_velocity_[1], xyz_velocity_[2]);

    osc_.send(values);

  }

  return gams::platforms::PLATFORM_OK;
}
Example #26
0
File: emu.cpp Project: nealey/vera
// Emulate an operand.
static void handle_operand(op_t &op, bool write) {
    switch ( op.type ) {
        // Code address
        case o_near:
            {
                cref_t mode;
                ea_t ea = toEA(cmd.cs, op.addr);

                // call or jump ?
                if ( cmd.itype == st9_call || cmd.itype == st9_calls )
                {
                  if ( !func_does_return(ea) )
                    flow = false;
                  mode = fl_CN;
                }
                else
                {
                  mode = fl_JN;
                }
                ua_add_cref(op.offb, ea, mode);
            }
            break;

        // Memory address
        case o_mem:
            {
                enum dref_t mode;

                mode = write ? dr_W: dr_R;

                ua_add_dref(op.offb, toEA(cmd.cs, op.addr), mode);
                ua_dodata2(op.offb, op.addr, op.dtyp);
            }
            break;

        // Immediate value
        case o_imm:
            doImmd(cmd.ea);
            // create a comment if this immediate is represented in the .cfg file
            {
                const ioport_t * port = find_sym(op.value);

                if ( port != NULL && !has_cmt(uFlag) ) {
                    set_cmt(cmd.ea, port->cmt, false);
                }
            }
            // if the value was converted to an offset, then create a data xref:
            if ( isOff(uFlag, op.n) )
              ua_add_off_drefs2(op, dr_O, 0);
            break;

        // Displacement
        case o_displ:
            doImmd(cmd.ea);
            if ( isOff(uFlag, op.n) ) {
                ua_add_off_drefs2(op, dr_O, OOF_ADDR);
                ua_dodata2(op.offb, op.addr, op.dtyp);
            }

            // create stack variables if required
            if ( may_create_stkvars() && !isDefArg(uFlag, op.n) ) {
                func_t *pfn = get_func(cmd.ea);
                if ( pfn != NULL && pfn->flags & FUNC_FRAME ) {
                    if ( ua_stkvar2(op, op.addr, STKVAR_VALID_SIZE) ) {
                        op_stkvar(cmd.ea, op.n);
                        if ( cmd.Op2.type == o_reg ) {
                            regvar_t *r = find_regvar(pfn, cmd.ea, ph.regNames[cmd.Op2.reg]);
                            if ( r != NULL ) {
                                struc_t *s = get_frame(pfn);
                                member_t *m = get_stkvar(op, op.addr, NULL);
                                char b[20];
                                qsnprintf(b, sizeof b, "%scopy", r->user);
                                set_member_name(s, m->soff, b);
                            }
                        }
                    }
                }
            }
            break;

        // Register - Phrase - Void: do nothing
        case o_reg:
        case o_phrase:
        case o_void:
            break;

        default:
            IDA_ERROR("Invalid op.type in handle_operand()");
    }
}
Example #27
0
/* return code -1 means that event_queue_ptr won't be incremented.
   In other word, this event makes two key codes.   (by himi)       */
static int
key_event (KEY_EVENT_RECORD *event, struct input_event *emacs_ev, int *isdead)
{
  static int mod_key_state = 0;
  int wParam;

  *isdead = 0;

  /* Skip key-up events.  */
  if (!event->bKeyDown)
    {
      switch (event->wVirtualKeyCode)
	{
	case VK_LWIN:
	  mod_key_state &= ~LEFT_WIN_PRESSED;
	  break;
	case VK_RWIN:
	  mod_key_state &= ~RIGHT_WIN_PRESSED;
	  break;
	case VK_APPS:
	  mod_key_state &= ~APPS_PRESSED;
	  break;
	}
      return 0;
    }

  /* Ignore keystrokes we fake ourself; see below.  */
  if (faked_key == event->wVirtualKeyCode)
    {
      faked_key = 0;
      return 0;
    }

  /* To make it easier to debug this code, ignore modifier keys!  */
  switch (event->wVirtualKeyCode)
    {
    case VK_LWIN:
      if (NILP (Vw32_pass_lwindow_to_system))
	{
	  /* Prevent system from acting on keyup (which opens the Start
	     menu if no other key was pressed) by simulating a press of
	     Space which we will ignore.  */
	  if ((mod_key_state & LEFT_WIN_PRESSED) == 0)
	    {
	      if (NUMBERP (Vw32_phantom_key_code))
		faked_key = XUINT (Vw32_phantom_key_code) & 255;
	      else
		faked_key = VK_SPACE;
	      keybd_event (faked_key, (BYTE) MapVirtualKey (faked_key, 0), 0, 0);
	    }
	}
      mod_key_state |= LEFT_WIN_PRESSED;
      if (!NILP (Vw32_lwindow_modifier))
	return 0;
      break;
    case VK_RWIN:
      if (NILP (Vw32_pass_rwindow_to_system))
	{
	  if ((mod_key_state & RIGHT_WIN_PRESSED) == 0)
	    {
	      if (NUMBERP (Vw32_phantom_key_code))
		faked_key = XUINT (Vw32_phantom_key_code) & 255;
	      else
		faked_key = VK_SPACE;
	      keybd_event (faked_key, (BYTE) MapVirtualKey (faked_key, 0), 0, 0);
	    }
	}
      mod_key_state |= RIGHT_WIN_PRESSED;
      if (!NILP (Vw32_rwindow_modifier))
	return 0;
      break;
    case VK_APPS:
      mod_key_state |= APPS_PRESSED;
      if (!NILP (Vw32_apps_modifier))
	return 0;
      break;
    case VK_CAPITAL:
      /* Decide whether to treat as modifier or function key.  */
      if (NILP (Vw32_enable_caps_lock))
	goto disable_lock_key;
      return 0;
    case VK_NUMLOCK:
      /* Decide whether to treat as modifier or function key.  */
      if (NILP (Vw32_enable_num_lock))
	goto disable_lock_key;
      return 0;
    case VK_SCROLL:
      /* Decide whether to treat as modifier or function key.  */
      if (NILP (Vw32_scroll_lock_modifier))
	goto disable_lock_key;
      return 0;
    disable_lock_key:
      /* Ensure the appropriate lock key state is off (and the
	 indicator light as well).  */
      wParam = event->wVirtualKeyCode;
      if (GetAsyncKeyState (wParam) & 0x8000)
	{
	  /* Fake another press of the relevant key.  Apparently, this
	     really is the only way to turn off the indicator.  */
	  faked_key = wParam;
	  keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
		       KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
	  keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
		       KEYEVENTF_EXTENDEDKEY | 0, 0);
	  keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
		       KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
	}
      break;
    case VK_MENU:
    case VK_CONTROL:
    case VK_SHIFT:
      return 0;
    case VK_CANCEL:
      /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
	 which is confusing for purposes of key binding; convert
	 VK_CANCEL events into VK_PAUSE events.  */
      event->wVirtualKeyCode = VK_PAUSE;
      break;
    case VK_PAUSE:
      /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
	 for purposes of key binding; convert these back into
	 VK_NUMLOCK events, at least when we want to see NumLock key
	 presses.  (Note that there is never any possibility that
	 VK_PAUSE with Ctrl really is C-Pause as per above.)  */
      if (NILP (Vw32_enable_num_lock)
	  && (event->dwControlKeyState
	      & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0)
	event->wVirtualKeyCode = VK_NUMLOCK;
      break;
    }

  /* Recognize state of Windows and Apps keys.  */
  event->dwControlKeyState |= mod_key_state;

  /* Distinguish numeric keypad keys from extended keys.  */
  event->wVirtualKeyCode =
    map_keypad_keys (event->wVirtualKeyCode,
		     (event->dwControlKeyState & ENHANCED_KEY));

  if (lispy_function_keys[event->wVirtualKeyCode] == 0)
    {
      if (!NILP (Vw32_recognize_altgr)
	  && (event->dwControlKeyState & LEFT_CTRL_PRESSED)
	  && (event->dwControlKeyState & RIGHT_ALT_PRESSED))
	{
	  /* Don't try to interpret AltGr key chords; ToAscii seems not
	     to process them correctly.  */
	}
      /* Handle key chords including any modifiers other than shift
         directly, in order to preserve as much modifier information as
         possible.  */
      else if (event->dwControlKeyState
	       & (  RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED
		  | RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED
		  | (!NILP (Vw32_lwindow_modifier) ? LEFT_WIN_PRESSED : 0)
		  | (!NILP (Vw32_rwindow_modifier) ? RIGHT_WIN_PRESSED : 0)
		  | (!NILP (Vw32_apps_modifier) ? APPS_PRESSED : 0)
		  | (!NILP (Vw32_scroll_lock_modifier) ? SCROLLLOCK_ON : 0)))
	{
	  /* Don't translate modified alphabetic keystrokes, so the user
	     doesn't need to constantly switch layout to type control or
	     meta keystrokes when the normal layout translates
	     alphabetic characters to non-ascii characters.  */
	  if ('A' <= event->wVirtualKeyCode && event->wVirtualKeyCode <= 'Z')
	    {
	      event->uChar.AsciiChar = event->wVirtualKeyCode;
	      if ((event->dwControlKeyState & SHIFT_PRESSED) == 0)
		event->uChar.AsciiChar += ('a' - 'A');
	    }
	  /* Try to handle unrecognized keystrokes by determining the
             base character (ie. translating the base key plus shift
             modifier).  */
	  else if (event->uChar.AsciiChar == 0)
	    w32_kbd_patch_key (event, -1);
	}

      if (event->uChar.AsciiChar == 0)
	{
	  emacs_ev->kind = NO_EVENT;
	  return 0;
	}
      else if (event->uChar.AsciiChar > 0)
	{
	  /* Pure ASCII characters < 128.  */
	  emacs_ev->kind = ASCII_KEYSTROKE_EVENT;
	  emacs_ev->code = event->uChar.AsciiChar;
	}
      else if (event->uChar.UnicodeChar > 0
	       && w32_console_unicode_input)
	{
	  /* Unicode codepoint; only valid if we are using Unicode
	     console input mode.  */
	  emacs_ev->kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
	  emacs_ev->code = event->uChar.UnicodeChar;
	}
      else
	{
	  /* Fallback handling of non-ASCII characters for non-Unicode
	     versions of Windows, and for non-Unicode input on NT
	     family of Windows.  Only characters in the current
	     console codepage are supported by this fallback.  */
	  wchar_t code;
	  char dbcs[2];
          int cpId;

	  /* Get the current console input codepage to interpret this
	     key with.  Note that the system defaults for the OEM
	     codepage could have been changed by calling SetConsoleCP
	     or w32-set-console-codepage, so using GetLocaleInfo to
	     get LOCALE_IDEFAULTCODEPAGE is not TRT here.  */
          cpId = GetConsoleCP ();

	  dbcs[0] = dbcs_lead;
	  dbcs[1] = event->uChar.AsciiChar;
	  if (dbcs_lead)
	    {
	      dbcs_lead = 0;
	      if (!MultiByteToWideChar (cpId, 0, dbcs, 2, &code, 1))
		{
		  /* Garbage  */
		  DebPrint (("Invalid DBCS sequence: %d %d\n",
			     dbcs[0], dbcs[1]));
		  emacs_ev->kind = NO_EVENT;
		}
	    }
	  else if (IsDBCSLeadByteEx (cpId, dbcs[1]))
	    {
	      dbcs_lead = dbcs[1];
	      emacs_ev->kind = NO_EVENT;
	    }
	  else
	    {
	      if (!MultiByteToWideChar (cpId, 0, &dbcs[1], 1, &code, 1))
		{
		  /* Garbage  */
		  DebPrint (("Invalid character: %d\n", dbcs[1]));
		  emacs_ev->kind = NO_EVENT;
		}
	    }
	  emacs_ev->kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
	  emacs_ev->code = code;
	}
    }
  else
    {
      /* Function keys and other non-character keys.  */
      emacs_ev->kind = NON_ASCII_KEYSTROKE_EVENT;
      emacs_ev->code = event->wVirtualKeyCode;
    }

  XSETFRAME (emacs_ev->frame_or_window, get_frame ());
  emacs_ev->modifiers = w32_kbd_mods_to_emacs (event->dwControlKeyState,
					       event->wVirtualKeyCode);
  emacs_ev->timestamp = GetTickCount ();
  return 1;
}
Example #28
0
int
gams::platforms::OscJoystickPlatform::move(const pose::Position & target,
  const pose::PositionBounds & bounds)
{
  // update variables
  BasePlatform::move(target, bounds);
  int result = PLATFORM_MOVING;

  madara_logger_ptr_log(gams::loggers::global_logger.get(),
    gams::loggers::LOG_TRACE,
    "gams::platforms::OscJoystickPlatform::move:" \
    " %s: requested target \"%f,%f,%f\"\n",
    self_->agent.prefix.c_str(),
    target.x(), target.y(), target.z());

  // convert from input reference frame to vrep reference frame, if necessary
  pose::Position new_target(get_frame(), target);

  madara_logger_ptr_log(gams::loggers::global_logger.get(),
    gams::loggers::LOG_TRACE,
    "gams::platforms::OscJoystickPlatform::move:" \
    " %s: target \"%f,%f,%f\"\n",
    self_->agent.prefix.c_str(),
    new_target.x(), new_target.y(), new_target.z());

  // are we moving to a new location? If so, start an acceleration timer
  if (!last_move_.approximately_equal(new_target, 0.1))
  {
    move_timer_.start();
    last_move_ = new_target;
  }

  pose::Position cur_loc = get_location();

  utility::OscUdp::OscMap values;
  std::vector<double> xy_velocity;
  std::vector<double> z_velocity;

  // if (bounds.check_position(cur_loc, new_target))
  // quick hack to check position is within 0.5 meters

  bool finished = false;
  xy_velocity = calculate_thrust(cur_loc, new_target, finished);

  // if we have just started our movement, modify velocity to account
  // for acceleration. This will help animation be smooth in Unreal.
  move_timer_.stop();
  double move_time = move_timer_.duration_ds();
  if (move_time < 1.0)
  {
    // have acceleration ramp up over a second at .1 per 1/20 second
    for (size_t i = 0; i < xy_velocity.size(); ++i)
    {
      double abs_velocity = fabs(xy_velocity[i]);
      double signed_move_time = xy_velocity[i] < 0 ? -move_time : move_time;
      xy_velocity[i] = move_time < abs_velocity ?
        signed_move_time : xy_velocity[i];
    }

    madara_logger_ptr_log(gams::loggers::global_logger.get(),
      gams::loggers::LOG_MAJOR,
      "gams::platforms::OscJoystickPlatform::move:" \
      " %s: moving to new target at time %f with modified velocity "
      "[%f,%f,%f]\n",
      self_->agent.prefix.c_str(),
      move_time,
      xy_velocity[0], xy_velocity[1], xy_velocity[2]);

  }

  z_velocity.push_back(xy_velocity[2]);
  xy_velocity.resize(2);

  if (finished)
  {
    madara_logger_ptr_log(gams::loggers::global_logger.get(),
      gams::loggers::LOG_MINOR,
      "gams::platforms::OscJoystickPlatform::move:" \
      " %s: ARRIVED at target \"%f,%f,%f\"\n",
      self_->agent.prefix.c_str(),
      new_target.x(), new_target.y(), new_target.z());

    result = PLATFORM_ARRIVED;
  }
  
  values[xy_velocity_prefix_] = xy_velocity;
  values[z_velocity_prefix_] = z_velocity;

  osc_.send(values);

  // unlike other platforms, we do not send the velocities
  // Moving to the location is up to the user with the controller

  return result;
}
Example #29
0
static int
do_mouse_event (MOUSE_EVENT_RECORD *event,
		struct input_event *emacs_ev)
{
  static DWORD button_state = 0;
  static Lisp_Object last_mouse_window;
  DWORD but_change, mask;
  int i;

  if (event->dwEventFlags == MOUSE_MOVED)
    {
      FRAME_PTR f = SELECTED_FRAME ();
      Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
      int mx = event->dwMousePosition.X, my = event->dwMousePosition.Y;

      mouse_moved_to (mx, my);

      if (f->mouse_moved)
	{
	  if (hlinfo->mouse_face_hidden)
	    {
	      hlinfo->mouse_face_hidden = 0;
	      clear_mouse_face (hlinfo);
	    }

	  /* Generate SELECT_WINDOW_EVENTs when needed.  */
	  if (!NILP (Vmouse_autoselect_window))
	    {
	      Lisp_Object mouse_window = window_from_coordinates (f, mx, my,
								  0, 0);
	      /* A window will be selected only when it is not
		 selected now, and the last mouse movement event was
		 not in it.  A minibuffer window will be selected iff
		 it is active.  */
	      if (WINDOWP (mouse_window)
		  && !EQ (mouse_window, last_mouse_window)
		  && !EQ (mouse_window, selected_window))
		{
		  struct input_event event;

		  EVENT_INIT (event);
		  event.kind = SELECT_WINDOW_EVENT;
		  event.frame_or_window = mouse_window;
		  event.arg = Qnil;
		  event.timestamp = movement_time;
		  kbd_buffer_store_event (&event);
		}
	      last_mouse_window = mouse_window;
	    }
	  else
	    last_mouse_window = Qnil;

	  previous_help_echo_string = help_echo_string;
	  help_echo_string = help_echo_object = help_echo_window = Qnil;
	  help_echo_pos = -1;
	  note_mouse_highlight (f, mx, my);
	  /* If the contents of the global variable help_echo has
	     changed (inside note_mouse_highlight), generate a HELP_EVENT.  */
	  if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
	    gen_help_event (help_echo_string, selected_frame, help_echo_window,
			    help_echo_object, help_echo_pos);
	}
      return 0;
    }

  /* It looks like the console code sends us a mouse event with
     dwButtonState == 0 when a window is activated.  Ignore this case.  */
  if (event->dwButtonState == button_state)
    return 0;

  emacs_ev->kind = MOUSE_CLICK_EVENT;

  /* Find out what button has changed state since the last button event.  */
  but_change = button_state ^ event->dwButtonState;
  mask = 1;
  for (i = 0; mask; i++, mask <<= 1)
    if (but_change & mask)
      {
        if (i < NUM_TRANSLATED_MOUSE_BUTTONS)
          emacs_ev->code = emacs_button_translation[i];
        else
          emacs_ev->code = i;
	break;
      }

  button_state = event->dwButtonState;
  emacs_ev->timestamp = GetTickCount ();
  emacs_ev->modifiers = w32_kbd_mods_to_emacs (event->dwControlKeyState, 0) |
    ((event->dwButtonState & mask) ? down_modifier : up_modifier);

  XSETFASTINT (emacs_ev->x, event->dwMousePosition.X);
  XSETFASTINT (emacs_ev->y, event->dwMousePosition.Y);
/* for Mule 2.2 (Based on Emacs 19.28 */
#ifdef MULE
  XSET (emacs_ev->frame_or_window, Lisp_Frame, get_frame ());
#else
  XSETFRAME (emacs_ev->frame_or_window, get_frame ());
#endif

  return 1;
}
Example #30
0
/* We have a good packet(s), get it/them out of the buffers.
 */
static void
bionet_poll_rx(struct net_device *dev) {
    struct net_local *lp = netdev_priv(dev);
    int boguscount = 10;
    int pkt_len, status;
    unsigned long flags;

    local_irq_save(flags);
    /* ++roman: Take care at locking the ST-DMA... This must be done with ints
     * off, since otherwise an int could slip in between the question and the
     * locking itself, and then we'd go to sleep... And locking itself is
     * necessary to keep the floppy_change timer from working with ST-DMA
     * registers. */
    if (stdma_islocked()) {
        local_irq_restore(flags);
        return;
    }
    stdma_lock(bionet_intr, NULL);
    DISABLE_IRQ();
    local_irq_restore(flags);

    if( lp->poll_time < MAX_POLL_TIME ) lp->poll_time++;

    while(boguscount--) {
        status = get_frame((unsigned long)phys_nic_packet, 0);

        if( status == 0 ) break;

        /* Good packet... */

        dma_cache_maintenance((unsigned long)phys_nic_packet, 1520, 0);

        pkt_len = (nic_packet->l_hi << 8) | nic_packet->l_lo;

        lp->poll_time = bionet_min_poll_time;    /* fast poll */
        if( pkt_len >= 60 && pkt_len <= 1520 ) {
            /*	^^^^ war 1514  KHL */
            /* Malloc up new buffer.
             */
            struct sk_buff *skb = dev_alloc_skb( pkt_len + 2 );
            if (skb == NULL) {
                printk("%s: Memory squeeze, dropping packet.\n",
                       dev->name);
                lp->stats.rx_dropped++;
                break;
            }

            skb->dev = dev;
            skb_reserve( skb, 2 );		/* 16 Byte align  */
            skb_put( skb, pkt_len );	/* make room */

            /* 'skb->data' points to the start of sk_buff data area.
             */
            memcpy(skb->data, nic_packet->buffer, pkt_len);
            skb->protocol = eth_type_trans( skb, dev );
            netif_rx(skb);
            dev->last_rx = jiffies;
            lp->stats.rx_packets++;
            lp->stats.rx_bytes+=pkt_len;

            /* If any worth-while packets have been received, dev_rint()
               has done a mark_bh(INET_BH) for us and will work on them
               when we get to the bottom-half routine.
             */

            if (bionet_debug >1) {
                u_char *data = nic_packet->buffer, *p;
                int i;

                printk( "%s: RX pkt type 0x%4x from ", dev->name,
                        ((u_short *)data)[6]);


                for( p = &data[6], i = 0; i < 6; i++ )
                    printk("%02x%s", *p++,i != 5 ? ":" : "" );
                printk(" to ");
                for( p = data, i = 0; i < 6; i++ )
                    printk("%02x%s", *p++,i != 5 ? ":" : "" "\n" );

                printk( "%s: ", dev->name );
                printk(" data %02x%02x %02x%02x%02x%02x %02x%02x%02x%02x %02x%02x%02x%02x %02x%02x%02x%02x"
                       " %02x%02x%02x%02x len %d\n",
                       data[12], data[13], data[14], data[15], data[16], data[17], data[18], data[19],
                       data[20], data[21], data[22], data[23], data[24], data[25], data[26], data[27],
                       data[28], data[29], data[30], data[31], data[32], data[33],
                       pkt_len );
            }
        }
        else {
            printk(" Packet has wrong length: %04d bytes\n", pkt_len);
            lp->stats.rx_errors++;
        }
    }
    stdma_release();
    ENABLE_IRQ();
    return;
}