Exemplo n.º 1
0
int main(int argc,char** argv)
{
    Uint8 num_pictures;
    LoadedPicture* pictures;
    int i, j;
    SDL_PixelFormat* format = NULL;
    SDL_Window *window;
    SDL_Renderer *renderer;
    SDL_Color black = {0,0,0,0xff};
    SDL_Event event;
    int event_pending = 0;
    int should_exit = 0;
    unsigned int current_picture;
    int button_down;
    Uint32 pixelFormat = 0;
    int access = 0;
    SDL_Rect texture_dimensions;;

    /* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);

    if(argc < 2) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_Shape requires at least one bitmap file as argument.");
        exit(-1);
    }

    if(SDL_VideoInit(NULL) == -1) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Could not initialize SDL video.");
        exit(-2);
    }

    num_pictures = argc - 1;
    pictures = (LoadedPicture *)SDL_malloc(sizeof(LoadedPicture)*num_pictures);
    for(i=0;i<num_pictures;i++)
        pictures[i].surface = NULL;
    for(i=0;i<num_pictures;i++) {
        pictures[i].surface = SDL_LoadBMP(argv[i+1]);
        if(pictures[i].surface == NULL) {
            j = 0;
            for(j=0;j<num_pictures;j++)
                SDL_FreeSurface(pictures[j].surface);
            SDL_free(pictures);
            SDL_VideoQuit();
            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Could not load surface from named bitmap file.");
            exit(-3);
        }

        format = pictures[i].surface->format;
        if(format->Amask != 0) {
            pictures[i].mode.mode = ShapeModeBinarizeAlpha;
            pictures[i].mode.parameters.binarizationCutoff = 255;
        }
        else {
            pictures[i].mode.mode = ShapeModeColorKey;
            pictures[i].mode.parameters.colorKey = black;
        }
    }

    window = SDL_CreateShapedWindow("SDL_Shape test",SHAPED_WINDOW_X,SHAPED_WINDOW_Y,SHAPED_WINDOW_DIMENSION,SHAPED_WINDOW_DIMENSION,SDL_WINDOW_RESIZABLE);
    if(window == NULL) {
        for(i=0;i<num_pictures;i++)
            SDL_FreeSurface(pictures[i].surface);
        SDL_free(pictures);
        SDL_VideoQuit();
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Could not create shaped window for SDL_Shape.");
        exit(-4);
    }
    renderer = SDL_CreateRenderer(window,-1,0);
    if (!renderer) {
        SDL_DestroyWindow(window);
        for(i=0;i<num_pictures;i++)
            SDL_FreeSurface(pictures[i].surface);
        SDL_free(pictures);
        SDL_VideoQuit();
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Could not create rendering context for SDL_Shape window.");
        exit(-5);
    }

    for(i=0;i<num_pictures;i++)
        pictures[i].texture = NULL;
    for(i=0;i<num_pictures;i++) {
        pictures[i].texture = SDL_CreateTextureFromSurface(renderer,pictures[i].surface);
        if(pictures[i].texture == NULL) {
            j = 0;
            for(j=0;j<num_pictures;i++)
                if(pictures[i].texture != NULL)
                    SDL_DestroyTexture(pictures[i].texture);
            for(i=0;i<num_pictures;i++)
                SDL_FreeSurface(pictures[i].surface);
            SDL_free(pictures);
            SDL_DestroyRenderer(renderer);
            SDL_DestroyWindow(window);
            SDL_VideoQuit();
            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Could not create texture for SDL_shape.");
            exit(-6);
        }
    }

    event_pending = 0;
    should_exit = 0;
    event_pending = SDL_PollEvent(&event);
    current_picture = 0;
    button_down = 0;
    texture_dimensions.h = 0;
    texture_dimensions.w = 0;
    texture_dimensions.x = 0;
    texture_dimensions.y = 0;
    SDL_QueryTexture(pictures[current_picture].texture,(Uint32 *)&pixelFormat,(int *)&access,&texture_dimensions.w,&texture_dimensions.h);
    SDL_SetWindowSize(window,texture_dimensions.w,texture_dimensions.h);
    SDL_SetWindowShape(window,pictures[current_picture].surface,&pictures[current_picture].mode);
    next_time = SDL_GetTicks() + TICK_INTERVAL;
    while(should_exit == 0) {
        event_pending = SDL_PollEvent(&event);
        if(event_pending == 1) {
            if(event.type == SDL_KEYDOWN) {
                button_down = 1;
                if(event.key.keysym.sym == SDLK_ESCAPE)
                    should_exit = 1;
            }
            if(button_down && event.type == SDL_KEYUP) {
                button_down = 0;
                current_picture += 1;
                if(current_picture >= num_pictures)
                    current_picture = 0;
                SDL_QueryTexture(pictures[current_picture].texture,(Uint32 *)&pixelFormat,(int *)&access,&texture_dimensions.w,&texture_dimensions.h);
                SDL_SetWindowSize(window,texture_dimensions.w,texture_dimensions.h);
                SDL_SetWindowShape(window,pictures[current_picture].surface,&pictures[current_picture].mode);
            }
            if(event.type == SDL_QUIT)
                should_exit = 1;
            event_pending = 0;
        }
        render(renderer,pictures[current_picture].texture,texture_dimensions);
        SDL_Delay(time_left());
        next_time += TICK_INTERVAL;
    }

    /* Free the textures. */
    for(i=0;i<num_pictures;i++)
        SDL_DestroyTexture(pictures[i].texture);
    SDL_DestroyRenderer(renderer);
    /* Destroy the window. */
    SDL_DestroyWindow(window);
    /* Free the original surfaces backing the textures. */
    for(i=0;i<num_pictures;i++)
        SDL_FreeSurface(pictures[i].surface);
    SDL_free(pictures);
    /* Call SDL_VideoQuit() before quitting. */
    SDL_VideoQuit();

    return 0;
}
Exemplo n.º 2
0
/**********************************************************************
*%FUNCTION: waitForPADO
*%ARGUMENTS:
* conn -- PPPoEConnection structure
* timeout -- how long to wait (in seconds)
*%RETURNS:
* Nothing
*%DESCRIPTION:
* Waits for a PADO packet and copies useful information
***********************************************************************/
void
waitForPADO(PPPoEConnection *conn, int timeout)
{
    fd_set readable;
    int r;
    struct timeval tv;
    struct timeval expire_at;

    PPPoEPacket packet;
    int len;

    struct PacketCriteria pc;
    pc.conn          = conn;
    pc.acNameOK      = (conn->acName)      ? 0 : 1;
    pc.serviceNameOK = (conn->serviceName) ? 0 : 1;
    pc.seenACName    = 0;
    pc.seenServiceName = 0;
    conn->seenMaxPayload = 0;
    conn->error = 0;

    if (gettimeofday(&expire_at, NULL) < 0) {
	error("gettimeofday (waitForPADO): %m");
	return;
    }
    expire_at.tv_sec += timeout;

    do {
	if (BPF_BUFFER_IS_EMPTY) {
	    if (!time_left(&tv, &expire_at))
		return;		/* Timed out */

	    FD_ZERO(&readable);
	    FD_SET(conn->discoverySocket, &readable);

	    while(1) {
		r = select(conn->discoverySocket+1, &readable, NULL, NULL, &tv);
		if (r >= 0 || errno != EINTR) break;
	    }
	    if (r < 0) {
		error("select (waitForPADO): %m");
		return;
	    }
	    if (r == 0)
		return;		/* Timed out */
	}

	/* Get the packet */
	receivePacket(conn->discoverySocket, &packet, &len);

	/* Check length */
	if (ntohs(packet.length) + HDR_SIZE > len) {
	    error("Bogus PPPoE length field (%u)",
		   (unsigned int) ntohs(packet.length));
	    continue;
	}

#ifdef USE_BPF
	/* If it's not a Discovery packet, loop again */
	if (etherType(&packet) != Eth_PPPOE_Discovery) continue;
#endif

	/* If it's not for us, loop again */
	if (!packetIsForMe(conn, &packet)) continue;

	if (packet.code == CODE_PADO) {
	    if (NOT_UNICAST(packet.ethHdr.h_source)) {
		error("Ignoring PADO packet from non-unicast MAC address");
		continue;
	    }
	    if (conn->req_peer
		&& memcmp(packet.ethHdr.h_source, conn->req_peer_mac, ETH_ALEN) != 0) {
		warn("Ignoring PADO packet from wrong MAC address");
		continue;
	    }
	    if (parsePacket(&packet, parsePADOTags, &pc) < 0)
		return;
	    if (conn->error)
		return;
	    if (!pc.seenACName) {
		error("Ignoring PADO packet with no AC-Name tag");
		continue;
	    }
	    if (!pc.seenServiceName) {
		error("Ignoring PADO packet with no Service-Name tag");
		continue;
	    }
	    conn->numPADOs++;
	    if (pc.acNameOK && pc.serviceNameOK) {
		memcpy(conn->peerEth, packet.ethHdr.h_source, ETH_ALEN);
		conn->discoveryState = STATE_RECEIVED_PADO;
		break;
	    }
	}
    } while (conn->discoveryState != STATE_RECEIVED_PADO);
}
Exemplo n.º 3
0
/**********************************************************************
*%FUNCTION: waitForPADS
*%ARGUMENTS:
* conn -- PPPoE connection info
* timeout -- how long to wait (in seconds)
*%RETURNS:
* Nothing
*%DESCRIPTION:
* Waits for a PADS packet and copies useful information
***********************************************************************/
static void
waitForPADS(PPPoEConnection *conn, int timeout)
{
    fd_set readable;
    int r;
    struct timeval tv;
    struct timeval expire_at;

    PPPoEPacket packet;
    int len;

    if (gettimeofday(&expire_at, NULL) < 0) {
	error("gettimeofday (waitForPADS): %m");
	return;
    }
    expire_at.tv_sec += timeout;

    conn->error = 0;
    do {
	if (BPF_BUFFER_IS_EMPTY) {
	    if (!time_left(&tv, &expire_at))
		return;		/* Timed out */

	    FD_ZERO(&readable);
	    FD_SET(conn->discoverySocket, &readable);

	    while(1) {
		r = select(conn->discoverySocket+1, &readable, NULL, NULL, &tv);
		if (r >= 0 || errno != EINTR) break;
	    }
	    if (r < 0) {
		error("select (waitForPADS): %m");
		return;
	    }
	    if (r == 0)
		return;		/* Timed out */
	}

	/* Get the packet */
	receivePacket(conn->discoverySocket, &packet, &len);

	/* Check length */
	if (ntohs(packet.length) + HDR_SIZE > len) {
	    error("Bogus PPPoE length field (%u)",
		   (unsigned int) ntohs(packet.length));
	    continue;
	}

#ifdef USE_BPF
	/* If it's not a Discovery packet, loop again */
	if (etherType(&packet) != Eth_PPPOE_Discovery) continue;
#endif

	/* If it's not from the AC, it's not for me */
	if (memcmp(packet.ethHdr.h_source, conn->peerEth, ETH_ALEN)) continue;

	/* If it's not for us, loop again */
	if (!packetIsForMe(conn, &packet)) continue;

	/* Is it PADS?  */
	if (packet.code == CODE_PADS) {
	    /* Parse for goodies */
	    if (parsePacket(&packet, parsePADSTags, conn) < 0)
		return;
	    if (conn->error)
		return;
	    conn->discoveryState = STATE_SESSION;
	    break;
	}
    } while (conn->discoveryState != STATE_SESSION);

    /* Don't bother with ntohs; we'll just end up converting it back... */
    conn->session = packet.session;

    info("PPP session is %d", (int) ntohs(conn->session));

    /* RFC 2516 says session id MUST NOT be zero or 0xFFFF */
    if (ntohs(conn->session) == 0 || ntohs(conn->session) == 0xFFFF) {
	error("Access concentrator used a session value of %x -- the AC is violating RFC 2516", (unsigned int) ntohs(conn->session));
    }
}
Exemplo n.º 4
0
Arquivo: raft.c Projeto: jnpkrn/booth
int new_election(struct ticket_config *tk,
	struct booth_site *preference, int update_term, cmd_reason_t reason)
{
	struct booth_site *new_leader;

	if (local->type != SITE)
		return 0;

	if ((is_reason(OR_TKT_LOST, tk) || is_reason(OR_STEPDOWN, tk)) &&
			check_attr_prereq(tk, GRANT_AUTO)) {
		tk_log_info("attribute prerequisite not met, "
			"not starting elections");
		return 0;
	}

	/* elections were already started, but not yet finished/timed out */
	if (is_time_set(&tk->election_end) && !is_past(&tk->election_end))
		return 1;

	if (ANYDEBUG) {
		int tdiff;
		if (is_time_set(&tk->election_end)) {
			tdiff = -time_left(&tk->election_end);
			tk_log_debug("starting elections, previous finished since " intfmt(tdiff));
		} else {
			tk_log_debug("starting elections");
		}
		tk_log_debug("elections caused by %s %s",
				state_to_string(reason),
				reason == OR_AGAIN ? state_to_string(tk->election_reason) : "" );
	}

	/* §5.2 */
	/* If there was _no_ answer, don't keep incrementing the term number
	 * indefinitely. If there was no peer, there'll probably be no one
	 * listening now either. However, we don't know if we were
	 * invoked due to a timeout (caller does).
	 */
	/* increment the term only if either the current term was
	 * valid or if there was a tie (in that case update_term > 1)
	 */
	if ((update_term > 1) ||
		(update_term && tk->last_valid_tk &&
			tk->last_valid_tk->current_term >= tk->current_term)) {
		/* save the previous term, we may need to send out the
		 * MY_INDEX message */
		if (tk->state != ST_CANDIDATE) {
			save_committed_tkt(tk);
		}
		tk->current_term++;
	}

	set_future_time(&tk->election_end, tk->timeout);
	tk->in_election = 1;

	tk_log_info("starting new election (term=%d)",
			tk->current_term);
	clear_election(tk);

	if(preference)
		new_leader = preference;
	else
		new_leader = (local->type == SITE) ? local : NULL;
	record_vote(tk, local, new_leader);
	tk->voted_for = new_leader;

	set_state(tk, ST_CANDIDATE);

	/* some callers may want just to repeat on timeout */
	if (reason == OR_AGAIN) {
		reason = tk->election_reason;
	} else {
		tk->election_reason = reason;
	}

	ticket_broadcast(tk, OP_REQ_VOTE, OP_VOTE_FOR, RLT_SUCCESS, reason);
	add_random_delay(tk);
	return 0;
}
Exemplo n.º 5
0
int default_send(struct ir_remote *remote,struct ir_ncode *code)
{
	lirc_t remaining_gap;

	/* things are easy, because we only support one mode */
	if(hw.send_mode!=LIRC_MODE_PULSE)
		return(0);

#if !defined(SIM_SEND) || defined(DAEMONIZE)
	if(hw.features&LIRC_CAN_SET_SEND_CARRIER)
	{
		unsigned int freq;
		
		freq=remote->freq==0 ? 38000:remote->freq;
		if(ioctl(hw.fd,LIRC_SET_SEND_CARRIER,&freq)==-1)
		{
			logprintf(LOG_ERR,"could not set modulation "
				  "frequency");
			logperror(LOG_ERR,NULL);
			return(0);
		}
	}
	if(hw.features&LIRC_CAN_SET_SEND_DUTY_CYCLE)
	{
		unsigned int duty_cycle;
		
		duty_cycle=remote->duty_cycle==0 ? 50:remote->duty_cycle;
		if(ioctl(hw.fd,LIRC_SET_SEND_DUTY_CYCLE,&duty_cycle)==-1)
		{
			logprintf(LOG_ERR,"could not set duty cycle");
			logperror(LOG_ERR,NULL);
			return(0);
		}
	}
#endif
	remaining_gap=remote->remaining_gap;
	if(!init_send(remote,code)) return(0);
	
#if !defined(SIM_SEND) || defined(DAEMONIZE)
	if(remote->last_code!=NULL)
	{
		struct timeval current;
		unsigned long usecs;
		
		gettimeofday(&current,NULL);
		usecs=time_left(&current,&remote->last_send,remaining_gap*2);
		if(usecs>0) usleep(usecs);
	}
#endif

	if(write_send_buffer(hw.fd,code->length,code->signals)==-1)
	{
		logprintf(LOG_ERR,"write failed");
		logperror(LOG_ERR,NULL);
		return(0);
	}
	else
	{
		gettimeofday(&remote->last_send,NULL);
		remote->last_code=code;
#if defined(SIM_SEND) && !defined(DAEMONIZE)
		printf("space %lu\n",(unsigned long) remote->remaining_gap);
#endif
	}
	return(1);
}
Exemplo n.º 6
0
pid_t
ACE_Process::wait (const ACE_Time_Value &tv,
                   ACE_exitcode *status)
{
#if defined (ACE_WIN32)
  // Don't try to get the process exit status if wait failed so we can
  // keep the original error code intact.
  switch (::WaitForSingleObject (process_info_.hProcess,
                                 tv.msec ()))
    {
    case WAIT_OBJECT_0:
        // The error status of <GetExitCodeProcess> is nonetheless not
        // tested because we don't know how to return the value.
        ::GetExitCodeProcess (process_info_.hProcess,
                              &this->exit_code_);
      if (status != 0)
        *status = this->exit_code_;
      return this->getpid ();
    case WAIT_TIMEOUT:
      errno = ETIME;
      return 0;
    default:
      ACE_OS::set_errno_to_last_error ();
      return -1;
    }
#elif defined(ACE_LACKS_UNIX_SIGNALS)
  if (tv == ACE_Time_Value::zero)
    {
      pid_t retv =
        ACE_OS::waitpid (this->child_id_,
                         &this->exit_code_,
                         WNOHANG);
      if (status != 0)
        *status = this->exit_code_;

      return retv;
    }

  if (tv == ACE_Time_Value::max_time)
# if defined (ACE_VXWORKS)
    {
      pid_t retv;
      while ((retv = this->wait (status)) == ACE_INVALID_PID && errno == EINTR);
      return retv;
    }
# else
     return this->wait (status);
# endif

  pid_t pid = 0;
  ACE_Time_Value sleeptm (1);    // 1 msec
  if (sleeptm > tv)              // if sleeptime > waittime
      sleeptm = tv;
  ACE_Time_Value tmo (tv);       // Need one we can change
  for (ACE_Countdown_Time time_left (&tmo); tmo > ACE_Time_Value::zero ; time_left.update ())
    {
      pid = ACE_OS::waitpid (this->getpid (),
                             &this->exit_code_,
                             WNOHANG);
      if (status != 0)
        *status = this->exit_code_;

      if (pid > 0 || pid == ACE_INVALID_PID)
        break;          // Got a child or an error - all done

      // pid 0, nothing is ready yet, so wait.
      // Do a (very) short sleep (only this thread sleeps).
      ACE_OS::sleep (sleeptm);
    }

  return pid;
#else /* !ACE_WIN32 && !ACE_LACKS_UNIX_SIGNALS */
  if (tv == ACE_Time_Value::zero)
    {
      pid_t retv =
        ACE_OS::waitpid (this->child_id_,
                         &this->exit_code_,
                         WNOHANG);
      if (status != 0)
        *status = this->exit_code_;

      return retv;
    }

  if (tv == ACE_Time_Value::max_time)
    return this->wait (status);

  // Need to wait but limited to specified time.
  // Force generation of SIGCHLD, even though we don't want to
  // catch it - just need it to interrupt the sleep below.
  // If this object has a reactor set, assume it was given at
  // open(), and there's already a SIGCHLD action set, so no
  // action is needed here.
  ACE_Sig_Action old_action;
  ACE_Sig_Action do_sigchld ((ACE_SignalHandler)sigchld_nop);
  do_sigchld.register_action (SIGCHLD, &old_action);

  pid_t pid;
  ACE_Time_Value tmo (tv);       // Need one we can change
  for (ACE_Countdown_Time time_left (&tmo); ; time_left.update ())
    {
      pid = ACE_OS::waitpid (this->getpid (),
                             &this->exit_code_,
                             WNOHANG);
      if (status != 0)
        *status = this->exit_code_;

      if (pid > 0 || pid == ACE_INVALID_PID)
        break;          // Got a child or an error - all done

      // pid 0, nothing is ready yet, so wait.
      // Do a sleep (only this thread sleeps) til something
      // happens. This relies on SIGCHLD interrupting the sleep.
      // If SIGCHLD isn't delivered, we'll need to do something
      // with sigaction to force it.
      if (-1 == ACE_OS::sleep (tmo) && errno == EINTR)
        continue;
      // Timed out
      pid = 0;
      break;
    }

  // Restore the previous SIGCHLD action if it was changed.
  old_action.register_action (SIGCHLD);

  return pid;
#endif /* ACE_WIN32 */
}
Exemplo n.º 7
0
  void DensoArmNode::go_to_arm_pose(const denso_msgs::MoveArmPoseGoalConstPtr& goal)
  {
    int success = denso_msgs::MoveArmPoseResult::SUCCESS;

    //rate at which we'll send the demands to the arm
    ros::Rate move_arm_rate( goal->rate );

    //for checking the time out
    ros::Duration time_left( goal->time_out );
    ros::Time start_time = ros::Time::now();

    while( node_.ok() )
    {
      if( move_arm_pose_server_->isPreemptRequested() || !ros::ok() )
      {
        ROS_INFO("Move Denso arm to pose preempted.");
        move_arm_pose_server_->setPreempted();
        success = denso_msgs::MoveArmPoseResult::PREEMPTED;
        break;
      }

      //Compute pose from goal
      geometry_msgs::Pose pose_tmp( goal->goal );
      Pose pose_goal = geometry_pose_to_denso_pose( pose_tmp );

      ROS_DEBUG_STREAM(" RPY : " << pose_goal.roll << " / " << pose_goal.pitch << " / " << pose_goal.yaw);

      bool locked = false;
      for( unsigned int i=0; i < 1000; ++i)
      {
        if( denso_mutex.try_lock() )
        {
          locked = true;
          break;
        }
        usleep(10000);
      }

      if( locked )
      {
        if( !simulated )
        {
	  denso_arm_->set_speed( goal->speed );

          if( denso_arm_->send_cartesian_position( pose_goal ) )
          {
            denso_mutex.unlock();
            break; //We reached the target -> SUCCESS
          }
        }
        else
        {
          usleep( 500000 );
          denso_mutex.unlock();
          break;
        }
      }
      else
      {
        ROS_WARN("Couldn't send the target to the arm.");
      }

      //publish feedback
      time_left -= (ros::Time::now() - start_time);
      move_arm_pose_feedback_.time_left = time_left;
      move_arm_pose_server_->publishFeedback( move_arm_pose_feedback_ );

      //check if timedout
      if( time_left.toSec() <= 0.0 )
      {
        success = denso_msgs::MoveArmPoseResult::TIMED_OUT;
        break;
      }

      //loop at the rate the user asked for
      move_arm_rate.sleep();
    }

    if( success == denso_msgs::MoveArmPoseResult::SUCCESS)
    {
      move_arm_pose_result_.val = denso_msgs::MoveArmPoseResult::SUCCESS;
      move_arm_pose_server_->setSucceeded( move_arm_pose_result_ );
    }
    else
    {
      //failed
      move_arm_pose_result_.val = success;
      move_arm_pose_server_->setAborted( move_arm_pose_result_ );
    }
  }
Exemplo n.º 8
0
int main(int argc, char* argv[]) {
  SDL_Surface* screen;
  SDL_Event event;

  if(SDL_Init(SDL_INIT_VIDEO) == -1) {
    return 1;
  }
  SDL_WM_SetCaption("Game of Life", NULL);

  screen = SDL_SetVideoMode(SCR_WIDTH, SCR_HEIGHT, 32, SDL_SWSURFACE);
  Uint32 bg_color = SDL_MapRGB(screen->format, 0xFF, 0xFF, 0xFF);
  Uint32 live_color = SDL_MapRGB(screen->format, 0x33, 0x33, 0x33);

  int board1[BOARD_SIZE];
  int board2[BOARD_SIZE];

  initialize_board(board1);
  memcpy(board2, board1, BOARD_SIZE * sizeof(int));

  Uint64 generation = 0;

  next_time = SDL_GetTicks() + TICK_INTERVAL;
  while(1) {
    int quit = 0;
    int* current;
    int* next;

    if (generation++ % 2) {
      current = board2;
      next = board1;
    } else {
      current = board1;
      next = board2;
    }

    while (SDL_PollEvent(&event)) {
      switch (event.type) {
      case SDL_QUIT:
        quit = 1;
        break;
      case SDL_MOUSEBUTTONDOWN:
        if (event.button.button == SDL_BUTTON_LEFT) {
          if (event.button.y > (ROWS * CELL_SIZE)) break;
          int tx = floor(event.button.x / CELL_SIZE);
          int ty = floor(event.button.y / CELL_SIZE);
          add_glider(current, tx, ty);
        }
        break;
      default: continue;
      }
    }

    if (quit) {
      break;
    }

    draw_board(screen, current, bg_color, live_color);
    SDL_Delay(time_left());
    next_time += TICK_INTERVAL;
    tick(current, next);
  }

  SDL_Quit();
  return 0;
}
Exemplo n.º 9
0
static void TextRolloutProgress(float aarOutput[][NUM_ROLLOUT_OUTPUTS],
				float aarStdDev[][NUM_ROLLOUT_OUTPUTS], const rolloutcontext * prc,
				const cubeinfo aci[], unsigned int initial_game_count,
				const int iGame, const int iAlternative, const int nRank,
				const float rJsd, const int fStopped, const int fShowRanks,
				int fCubeRollout, rolloutprogress * prp)
{

	char *pch, *pc;
	time_t t;
	static unsigned int n_games_todo = 0;
	static unsigned int n_games_done = 0;
	static int min_games_done = 0;

	/* write progress 1/10th trial or just when called if mt */

	if (!iAlternative)
		outputl("");

	pch = OutputRolloutResult(NULL,
				  (char (*)[1024])prp->ppch[iAlternative],
				  (float (*)[NUM_ROLLOUT_OUTPUTS]) aarOutput[iAlternative],
				  (float (*)[NUM_ROLLOUT_OUTPUTS]) aarStdDev[iAlternative],
				  &aci[0], iAlternative, 1, prc->fCubeful);

	if (fShowRanks && iGame > 1) {

		pc = strrchr(pch, '\n');
		*pc = 0;

		if (fCubeRollout)
			sprintf(pc, " %c", fStopped ? 's' : 'r');
		else
			sprintf(pc, " %d%c", nRank, fStopped ? 's' : 'r');

		if (nRank != 1 || fCubeRollout)
			sprintf(strchr(pc, 0), " %5.3f\n", rJsd);
		else
			strcat(pc, "\n");

	}

	prp->iNextAlternative++;
	prp->iNextAlternative = (prp->iNextAlternative) % prp->n;
	if (iAlternative == (prp->n - 1))
		prp->iNextGame += prc->nTrials / 10;

	output(pch);

	output(OutputRolloutContext(NULL, prc));
	if (iAlternative == 0) {
		n_games_todo = 0;
		n_games_done = 0;
		min_games_done = prc->nTrials;
	}
	n_games_done += iGame + 1;
	if (!fStopped) {
		n_games_todo += prc->nTrials - (iGame + 1);
		if (iGame < min_games_done)
			min_games_done = iGame + 1;
	}
	if (iAlternative != (prp->n - 1))
		return;

	/* time elapsed and time left */

	t = time_left(n_games_todo, n_games_done, initial_game_count, prp->tStart);

	outputf(_("Time elapsed %s"), formatDelta(time(NULL) - prp->tStart));
	outputf(_(" Estimated time left %s\n"), formatDelta(t));

	/* estimated SE */

	/* calculate estimated SE */

	if (iGame <= 10)
		return;

	if (prc->fCubeful)
		pc = OutputMWC(estimatedSE
			       (aarStdDev[0][OUTPUT_CUBEFUL_EQUITY], iGame,
				prc->nTrials), &aci[0], FALSE);
	else
		pc = OutputEquityScale(estimatedSE
				       (aarStdDev[0][OUTPUT_EQUITY], iGame,
					prc->nTrials), &aci[0], &aci[0], FALSE);

	if (prp->ppch && prp->ppch[0] && *prp->ppch[0])
		outputf(_("Estimated SE for \"%s\" after %d trials %s\n"),
			prp->ppch[0], prc->nTrials, pc);
	else
		outputf(_("Estimated SE after %d trials %s\n"), prc->nTrials, pc);

}
Exemplo n.º 10
0
int main(int argc, char *argv[])
{

	char rc_file[255];
	char levelToLoad[] = "1";
    int i;
	SDL_Event event; // keyboard handling

	// default values
	inventory.redKeys = 0;
	inventory.greenKeys = 0;
	inventory.blueKeys = 0;
	inventory.yellowKeys = 0;

  vid.fullscreen = FULLSCREEN_DEFAULT;
	vid.videoflags = SDL_SWSURFACE;
	strcpy(level.theme, DEFAULTTHEME);
	sprintf(path.levels, "%s%s", DATAPATH_DEFAULT, LEVELPATH);
	sprintf(path.themes, "%s%s", DATAPATH_DEFAULT, THEMEPATH);
	animation[0].numphases = 4; // fire animation
	animation[0].tickcount = 1;
	animation[0].random = 1;

  // set up rcfile
  sprintf(rc_file, "%s/.blockmasterrc", getenv("HOME"));

	// check for arguments setting the configfile or requesting help
	for ( i=1; argv[i]; ++i ) {
		if ((strcmp(argv[i], "--config") == 0) || (strcmp(argv[i], "-c") == 0)) {
			// set new config file
			sprintf(rc_file, "%s", argv[i+1]);
		}

		if ((strcmp(argv[i], "--help") == 0 ) || (strcmp(argv[i], "-h") == 0)) {
			printf("\nBlockmaster v%d.%d%d\n-----------------\n", VERSION_MAJOR, VERSION_MINOR, VERSION_REV);
			printf("-h or --help             : display this message\n");
			printf("-f or --fullscreen       : select fullscreen display\n");
			printf("-w or --window           : select window display (default)\n");
			printf("-l # or --level #        : load level number #\n");
			printf("-c file or --config file : specify config file other than ~/.blockmasterrc\n");
			printf("\n");
			exit(1);
		}

	}

	// read config
	//ReadConfig(rc_file);

	// check command line for arguments that may override the config settings
	for ( i=1; argv[i]; ++i ) {
		if ((strcmp(argv[i], "--fullscreen") == 0) || (strcmp(argv[i], "-f") == 0))
			vid.fullscreen = TRUE;

		if ((strcmp(argv[i], "--window") == 0 ) || (strcmp(argv[i], "-w") == 0))
			vid.fullscreen = FALSE;

		if ((strcmp(argv[i], "--level") == 0) || (strcmp(argv[i], "-l") == 0)) {
			strcpy(levelToLoad, argv[i+1]);
		}

	}

	// initialize SDL

	// create surface
	if (SDL_Init (SDL_INIT_VIDEO) < 0) {
		fprintf(stdout, "*** Error: Init failed: %s\n", SDL_GetError());
		exit(1);
	}

	// clean up on exit
	atexit(SDL_Quit);

	// create screen
	if (vid.fullscreen == 1)
		vid.videoflags = SDL_FULLSCREEN;
	else
		vid.videoflags = SDL_SWSURFACE;

	screen = SDL_SetVideoMode(640, 480, 16, vid.videoflags);
	if ( screen == NULL) {
		fprintf(stdout, "*** Error: 640x480x16 not possible: %s\n", SDL_GetError());
		exit(1);
	}

	// ignore mouse / focus events
	SDL_EventState(SDL_ACTIVEEVENT, SDL_IGNORE);
	SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);

/* -- INITIALIZATION COMPLETE -- */

/* -- BEGIN MAIN PROGRAM LOOP -- */

	// will load level data and all graphics
	// (the theme according to the level)
	LoadLevel(levelToLoad);

	// enable unicode translation
	SDL_EnableUNICODE( 1 );

	SDL_SetAlpha(block[11], SDL_SRCALPHA, 100);
	SDL_SetAlpha(block[24], SDL_SRCALPHA, 100);

	// set window caption
	sprintf(string, "Blockmaster v0.00 - %s by %s", level.title, level.author);
	SDL_WM_SetCaption(string, NULL);

	// ticker
    next_time = SDL_GetTicks() + TICK_INTERVAL;

	while (running == 1) {

  // loop until SDL_Quit event is found
  // or escape key is pressed
    while( SDL_PollEvent( &event ) ) {
    switch( event.type ) {
        case SDL_KEYDOWN:
          switch( event.key.keysym.sym ) {
          case SDLK_LEFT:// || SDLK_h:
            player[chosenGuy].direction = LEFT;
            if(hasBlockBit(player[chosenGuy].coord_x-1, player[chosenGuy].coord_y, ISWALKABLE) == 1)
              movePlayer(chosenGuy,player[chosenGuy].direction);
            break;
          case SDLK_RIGHT: // || SDLK_l:
            player[chosenGuy].direction = RIGHT;
            if(hasBlockBit(player[chosenGuy].coord_x+1, player[chosenGuy].coord_y, ISWALKABLE) == 1)
              movePlayer(chosenGuy,player[chosenGuy].direction);
            break;
          case SDLK_UP: // || SDLK_k:
            player[chosenGuy].direction = UP;
            if(hasBlockBit(player[chosenGuy].coord_x, player[chosenGuy].coord_y-1, ISWALKABLE) == 1)
              movePlayer(chosenGuy,player[chosenGuy].direction);
            break;
          case SDLK_DOWN: // || SDLK_j:
            player[chosenGuy].direction = DOWN;
            if(hasBlockBit(player[chosenGuy].coord_x, player[chosenGuy].coord_y+1, ISWALKABLE) == 1)
              movePlayer(chosenGuy,player[chosenGuy].direction);
            break;
          case SDLK_SPACE:
            chosenGuy++;
            if (chosenGuy == playerCount) chosenGuy = 0;
            break;
          case SDLK_ESCAPE:
            running = 0;
            break;
          case SDLK_q:
            running = 0;
            break;
          default:
            break;
          }

          break;
        case SDL_KEYUP:
          break;
        case SDL_QUIT:
          running = 0;
          break;
        default:
          break;
       }
			}

			RenderLevel();

			// process animations
			for (i = 0; i<ANIMATIONCOUNT; i++) {
				// check for tick interval
				if (now % animation[i].tickcount == 0) {
					animation[i].currentphase++;
					if (animation[i].currentphase >= animation[i].numphases)
						animation[i].currentphase = 0;
				}
			}

			// not to forget our menu
			BlitImage(menu[0], screen, 539, 0);

			// print stuff
			PutString(screen,560,150,"Keys:");
			BlitImage(menu[1],screen,550,170);
			BlitImage(menu[2],screen,590,170);
			BlitImage(menu[3],screen,550,220);
			BlitImage(menu[4],screen,590,220);
			sprintf(string,"%d",inventory.greenKeys);
			PutString(screen,570,190,string);
			sprintf(string,"%d",inventory.blueKeys);
			PutString(screen,610,190,string);
			sprintf(string,"%d",inventory.yellowKeys);
			PutString(screen,570,240,string);
			sprintf(string,"%d",inventory.redKeys);
			PutString(screen,610,240,string);

			sprintf(string,"%d",now);
			PutString(screen,5,5,string);

			// update the whole screen
			SDL_UpdateRect(screen, 0, 0, 0, 0);

			// game delay
			SDL_Delay(time_left());
			next_time += TICK_INTERVAL;
        }
	quit(0);
}
RMS_Queue_Manager::RMS_Queue_Manager()
    : countdown_(DEFAULT_TRIAL),
      run_countdown(false)
{

  ros::NodeHandle n;

  //sent out queue
  ros::Publisher queue_pub = n.advertise<rms_queue_manager::RMSQueue>("rms_queue", 1000);

  //add user to queue when someone new visits the website
  ros::ServiceServer update_queue_serv = n.advertiseService("update_queue", &RMS_Queue_Manager::on_update_queue, this);

  //loop at the rate of LOOP_RATE, and publish queue
  ros::Rate r(RMS_Queue_Manager::LOOP_RATE);

  ROS_INFO("publishing queue...");

  while (ros::ok())
  {

    ROS_INFO("countdown: %i\n", countdown_);

    //only run the countdown when the queue isn't empty
    if (run_countdown)
    {
      //when you countdown has reached 0, reset it and remove the first/current user
      if (!countdown_)
      {
        queue_.pop_front(); //bye bye!
        //reset count down to next users trial time
        countdown_ = queue_.begin()->second;
      }

      //stop counting if the queue is now empty
      if (queue_.empty())
      {
        run_countdown = false;
      }

      countdown_--;
    }

    rms_queue_manager::RMSQueue rms_queue_message;

    std::deque<std::pair<int, int> >::iterator it = queue_.begin();
    int position = 0;
    int wait_t;
    int t_left;

    //create queue to publish
    while (it != queue_.end())
    {
      std::pair<int, int> user = *(it++);

      rms_queue_manager::UserStatus user_status;
      user_status.user_id = user.first;

      //calculate wait time in seconds

      if (position > 0)
      {
        wait_t = countdown_ + (position - 1) * user.second;
      }
      else if (position == 0)
      {
        wait_t = -1;
        t_left = countdown_;
      }

      ros::Duration wait_time(wait_t);
      ros::Duration time_left(t_left);
      user_status.wait_time = wait_time;
      user_status.time_left = time_left;
      rms_queue_message.queue.push_back(user_status);

      position++;

      ROS_INFO("user %i", user_status.user_id);
    }

    //publish the queue message
    queue_pub.publish(rms_queue_message);

    ros::spinOnce();
    r.sleep();
  }
}
Exemplo n.º 12
0
int
main ( int argc, char *argv[] )
{
    bool quit = false;
    int sprite_x = 0;
    int inc_val  = 0;
    char m[80];
    int u = 0;
    int bgX = 0;
    int bgY = 0;

    if( init() == false )
        return EXIT_FAILURE;
    if( load_files() == false )
        return EXIT_FAILURE;

    clip[0].x = 0;
    clip[0].y = 0;
    clip[0].w = 32;
    clip[0].h = 32;

    //apply_surface( 0, 0, background, screen );
    apply_surface( 10, 10, sprite_image, screen, &clip[0] );
    //apply_surface( 10, 10, sprite_image, screen );
    if( SDL_Flip( screen ) == -1 )
    {
        return EXIT_FAILURE;
    }

    next_time = SDL_GetTicks() + TICK_INTERVAL;

    while( quit == false ){

        SDL_Rect tmp;
        SDL_Rect tmp2;
        
        tmp.x = sprite_x;
        tmp.y = 0;
        tmp.w = 32;
        tmp.h = 32;

        quit = handle_events( &inc_val );

        tmp2.x = 210 + 150;
        tmp2.y = 0;
        tmp2.w = 16;
        tmp2.h = 16;

        if( rightdown )
            inc_val++;

        if( inc_val > 0 && leftdown )
            inc_val--;

        //rightdown = false;
        //leftdown = false;

        //
        //fprintf(stderr, "x = %d\n", sprite_x);

        sprintf( m, "%d", inc_val );

        message = TTF_RenderText_Solid( font, m, textColor );

        SDL_FillRect( screen, NULL, SDL_MapRGB( screen->format, 0, 0, 0 ) );
        //apply_surface( 10, 10, sprite_image, screen, &tmp );
        //apply_surface( 100, 100, sprite_image2, screen, &tmp2 );
        draw();

        bgX -= 2;

        if( bgX <= -background->w ){
            bgX = 0;
        }
        /*
        if( !updown && u != 50 ){
            u = 100;

        }
        */
        apply_surface( bgX, bgY, background, screen );
        apply_surface( bgX + background->w, bgY, background, screen );
        apply_surface( 50, 50, message, screen );
        //apply_surface( 10, 10, sprite_image, screen );
        if( SDL_Flip( screen ) == -1 )
        {
            return EXIT_FAILURE;
        }

        sprite_x = (sprite_x + 32) % 256;
        //SDL_Delay(30);
        SDL_Delay( time_left() );
        //SDL_free( tmp );
        next_time += TICK_INTERVAL;
    }

    //SDL_Delay(5000);

    return EXIT_SUCCESS;
}/* ----------  end of function main  ---------- */
Exemplo n.º 13
0
void game (gamedata &g){

  SDL_Event event;
  quit = false;

  // Set first tick interval
  Uint32 next_time = SDL_GetTicks() + TICK_INTERVAL;

  while (!quit){
	  if(g.winner){
		finish_game(g);
		setup_game(g);
		GameState = STATE_INTRO;
		CurrentMenu = MenuMainIntro;
		SelectedItem = menuSwitchItem(CurrentMenu, 0);
		demo = true;
	  }
	 else if (g.winner == 0){

	    Uint8 *keys = SDL_GetKeyState(NULL);

	    if (SDL_PollEvent(&event) == 1){
	      switch (event.type){

	      case SDL_QUIT: {
		printf("Quit requested, quitting.\n");
		quit = true;
	      }
	      break;
	      }
	    }

	    if(GameState == STATE_INTRO || GameState == STATE_MENU)
	    {
		    menuInput(g);
	    }
	    else if(GameState == STATE_MENU_PLANE_SELECT)
	    {
		    menuPlanes(g);
	    }
	    else if(GameState == STATE_MENU_PLAYER_CONTROL_SELECT)
	    {
		    menuSelectPlayer(g);
	    }
	    else if(GameState == STATE_GAME)
	    {
		    if ((keys[SDLK_ESCAPE] == SDL_PRESSED) || (keys[51] == SDL_PRESSED)){
			keys[SDLK_ESCAPE] = SDL_RELEASED;
			GameState = STATE_MENU;
			CurrentMenu = MenuMain;
			SelectedItem = menuSwitchItem(CurrentMenu, 0);
		      //quit = true;
		    }
	    }

	    // Go through each plane individually
	    g.p.reset();
	    while (g.p.next()){

	      // Setup virtual joystick
	      int jx = 0;

	      int jy = 0;
	      bool jb = false;

	      if (g.p().state < 2){
		control(g, keys, jx, jy, jb);
		controlJoy(g, jx, jy, jb);
	      }
	      // Then move the plane
	      act(g, jx, jy, jb);
	      // Remove expunged planes
	      if (g.p().state == 4){
		g.drakms.fighter[g.p().id-7] = false;
		g.drakms.fightersout--;
		g.dp.reset();
		while(g.dp.next()){
		  if (g.dp().id == g.p().id) g.dp.kill();
		}
		g.p.kill();
	      }

	    }

	    // Then do everything else
	    all(g);
	    drawall(g);

	    // Delay for time remaining in TICK_INTERVAL
	    SDL_Delay(time_left(next_time));
	    next_time = SDL_GetTicks() + TICK_INTERVAL;

	  }
  }
}
Exemplo n.º 14
0
void update_NPCs_frames( NPC** _NPCs, int _NPCCount )
{
    int i;
    for ( i = 0; i < _NPCCount; i++ )
    {
        if ( time_left( _NPCs[i]->frame_timer ) <= GC_NPC_frames_duration / 3.0 )  // 1st frame
        {
            switch( _NPCs[i]->direction )
            {
                case UP:
                {
                    _NPCs[i]->up_frame_index = 0;
                    break;
                }

                case RIGHT:
                {
                    _NPCs[i]->right_frame_index = 0;
                    break;
                }

                case DOWN:
                {
                    _NPCs[i]->down_frame_index = 0;
                    break;
                }

                case LEFT:
                {
                    _NPCs[i]->left_frame_index = 0;
                    break;
                }
            }
        }
        else if ( time_left( _NPCs[i]->frame_timer ) <= 2.0 * GC_NPC_frames_duration / 3.0 )   // 2nd frame
        {
            switch( _NPCs[i]->direction )
            {
                case UP:
                {
                    _NPCs[i]->up_frame_index = 1;
                    break;
                }

                case RIGHT:
                {
                    _NPCs[i]->right_frame_index = 1;
                    break;
                }

                case DOWN:
                {
                    _NPCs[i]->down_frame_index = 1;
                    break;
                }

                case LEFT:
                {
                    _NPCs[i]->left_frame_index = 1;
                    break;
                }
            }
        }
        else    // 3rd frame
        {
            switch( _NPCs[i]->direction )
            {
                case UP:
                {
                    _NPCs[i]->up_frame_index = 2;
                    break;
                }

                case RIGHT:
                {
                    _NPCs[i]->right_frame_index = 2;
                    break;
                }

                case DOWN:
                {
                    _NPCs[i]->down_frame_index = 2;
                    break;
                }

                case LEFT:
                {
                    _NPCs[i]->left_frame_index = 2;
                    break;
                }
            }
        }

        if ( time_is_up( _NPCs[i]->frame_timer ) )
            reset_timer( _NPCs[i]->frame_timer );
    }
}
Exemplo n.º 15
0
int main ( int argc, char** argv )
{

    for (int i=1;i<argc;i++) {
        if (!strcmp(argv[i],"--fullscreen"))
            fullscreen = 1;
        else if (!strcmp(argv[i],"--slow"))
            slow = 1;
        else if (!strcmp(argv[i],"--verbose"))
            quiet = 0;
        else if (!strcmp(argv[i],"--scale2x"))
            scale = 2;
        else {
            instructions();
            exit(0);
        }
    }

    // display current options
    if (!quiet) {
        printf("Options : %s %s scale : %d\n",fullscreen?"fullscreen":"windowed",slow?"slow":"normal speed",scale);
        instructions();
        printf(" - Starting\n");
    }

    gamepad_buttons[0] = 0; // all up
    gamepad_buttons[1] = 0;

    if (init()) return 1;
    game_init();

    // now start sound
    SDL_PauseAudio(0);

    // program main loop
    bool done = false;
    while (!done)
    {

        // message processing loop
        done = handle_events();
        kbd_emulate_gamepad();
        // update game
        game_frame();

        // update time
        vga_frame++;
        
        #if VGA_MODE!=NONE
        refresh_screen(screen);
        #endif

        SDL_Delay(time_left());
        next_time += slow ? TICK_INTERVAL*10:TICK_INTERVAL;

        SDL_Flip(screen);
    } // end main loop

    // all is well ;)
    if (!quiet)
        printf(" - Exited cleanly\n");
    return 0;
}
Exemplo n.º 16
0
static void
GTKRolloutProgress(float aarOutput[][NUM_ROLLOUT_OUTPUTS],
		   float aarStdDev[][NUM_ROLLOUT_OUTPUTS],
		   const rolloutcontext * prc,
		   const cubeinfo aci[],
		   unsigned int initial_game_count,
		   const int iGame,
		   const int iAlternative,
		   const int nRank,
		   const float rJsd,
		   const int fStopped,
		   const int fShowRanks, int fCubeRollout, rolloutprogress * prp)
{

	static unsigned int n_games_todo = 0;
	static unsigned int n_games_done = 0;
	static int min_games_done = 0;
	char sz[32];
	int i;
	gchar *gsz;
	double frac;
	GtkTreeIter iter;

	if (!prp || !prp->pwRolloutResult)
		return;

	gtk_tree_model_iter_nth_child(GTK_TREE_MODEL(prp->pwRolloutResultList), &iter, NULL, iAlternative);
	gtk_list_store_set(prp->pwRolloutResultList, &iter, TRIALS_C, iGame + 1, -1);
	for (i = 0; i < NUM_ROLLOUT_OUTPUTS; i++) {

		/* result */

		if (i < OUTPUT_EQUITY)
			strcpy(sz, OutputPercent(aarOutput[iAlternative][i]));
		else if (i == OUTPUT_EQUITY)
			strcpy(sz, OutputEquityScale(aarOutput[iAlternative][i],
						     &aci[iAlternative], &aci[0], TRUE));
		else
			strcpy(sz,
			       prc->fCubeful ? OutputMWC(aarOutput[iAlternative][i],
							 &aci[0], TRUE) : "n/a");

		gtk_list_store_set(prp->pwRolloutResultList, &iter, i + 3, sz, -1);

	}
	if (prc->fCubeful)
			strcpy(sz, OutputMWC(aarStdDev[iAlternative][OUTPUT_CUBEFUL_EQUITY], &aci[0], FALSE));
	else
			strcpy(sz, OutputEquityScale(aarStdDev[iAlternative][OUTPUT_EQUITY], &aci[iAlternative], &aci[0], FALSE));
	gtk_list_store_set(prp->pwRolloutResultList, &iter, i + 3, sz, -1);
	if (fShowRanks && iGame > 1) {
		gtk_list_store_set(prp->pwRolloutResultList, &iter, RANK_C, nRank, -1);
		if (nRank != 1 || fCubeRollout)
			sprintf(sz, "%5.3f", rJsd);
		else
			strcpy(sz, " ");
		gtk_list_store_set(prp->pwRolloutResultList, &iter, i + 4, sz, -1);
	}

	/* Update progress bar with highest number trials for all the alternatives */
	if (iAlternative == 0) {
		n_games_todo = 0;
		n_games_done = 0;
		min_games_done = prc->nTrials;
	}
	n_games_done += iGame + 1;
	if (!fStopped) {
		n_games_todo += prc->nTrials - (iGame + 1);
		if (iGame < min_games_done)
			min_games_done = iGame + 1;
	}
	if (iAlternative == (prp->n - 1)) {
		frac = ((float)min_games_done)/prc->nTrials;
		gsz = g_strdup_printf("%d/%d (%d%%)", min_games_done, prc->nTrials, (int)(100.0f * frac));
		gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(prp->pwRolloutProgress), frac);
		gtk_progress_bar_set_text(GTK_PROGRESS_BAR(prp->pwRolloutProgress), gsz);
		g_free(gsz);
		prp->nGamesDone = min_games_done;
	}

	/* calculate estimate time left */

	if ((iAlternative == (prp->n - 1)) && n_games_done > initial_game_count) {
		time_t t = time_left(n_games_todo, n_games_done, initial_game_count, prp->tStart);
		gtk_label_set_text(GTK_LABEL(prp->pwElapsed), formatDelta(time(NULL) - prp->tStart));
		gtk_label_set_text(GTK_LABEL(prp->pwLeft), formatDelta(t));

	}

	/* calculate estimated SE */

	if (!iAlternative && iGame > 10) {

		float r;

		if (prc->fCubeful) {
			r = estimatedSE(aarStdDev[0][OUTPUT_CUBEFUL_EQUITY], iGame, prc->nTrials);
			gtk_label_set_text(GTK_LABEL(prp->pwSE), OutputMWC(r, &aci[0], FALSE));
		} else {
			r = estimatedSE(aarStdDev[0][OUTPUT_EQUITY], iGame, prc->nTrials);
			gtk_label_set_text(GTK_LABEL(prp->pwSE),
					   OutputEquityScale(r, &aci[0], &aci[0], FALSE));
		}

	}

	return;
}
Exemplo n.º 17
0
pid_t
ACE_Process_Manager::wait (pid_t pid,
                           const ACE_Time_Value &timeout,
                           ACE_exitcode *status)
{
  ACE_TRACE ("ACE_Process_Manager::wait");

  ACE_exitcode local_stat = 0;
  if (status == 0)
    status = &local_stat;

  *status = 0;

  ssize_t idx = -1;
  ACE_Process *proc = 0;

  {
    // fake context after which the lock is released
    ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, this->lock_, -1));

    if (pid != 0)
      {
        idx = this->find_proc (pid);
        if (idx == -1)
          return ACE_INVALID_PID;
        else
          proc = process_table_[idx].process_;
      }
    // release the lock.
  }
  if (proc != 0)
    pid = proc->wait (timeout, status);
  else
    {
      ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, this->lock_, -1));
      // Wait for any Process spawned by this Process_Manager.
#if defined (ACE_WIN32)
      HANDLE *handles = 0;

      ACE_NEW_RETURN (handles,
                      HANDLE[this->current_count_],
                      ACE_INVALID_PID);

      for (size_t i = 0;
           i < this->current_count_;
           ++i)
        handles[i] =
          process_table_[i].process_->gethandle ();

      DWORD handle_count = static_cast<DWORD> (this->current_count_);
      DWORD result = ::WaitForMultipleObjects (handle_count,
                                               handles,
                                               FALSE,
                                               timeout == ACE_Time_Value::max_time
                                               ? INFINITE
                                               : timeout.msec ());
      if (result == WAIT_FAILED)
        pid = ACE_INVALID_PID;
      else if (result == WAIT_TIMEOUT)
        pid = 0;
      else
        {
          // Green Hills produces a warning that result >=
          // WAIT_OBJECT_0 is a pointless comparison because
          // WAIT_OBJECT_0 is zero and DWORD is unsigned long, so this
          // test is skipped for Green Hills.  Same for mingw.
# if defined (ghs) || defined (__MINGW32__) || defined (_MSC_VER)
          ACE_ASSERT (result < WAIT_OBJECT_0 + this->current_count_);
# else
          ACE_ASSERT (result >= WAIT_OBJECT_0
                      && result < WAIT_OBJECT_0 + this->current_count_);
# endif

          idx = this->find_proc (handles[result - WAIT_OBJECT_0]);

          if (idx != -1)
            {
              pid = process_table_[idx].process_->getpid ();
              result = ::GetExitCodeProcess (handles[result - WAIT_OBJECT_0],
                                             status);
              if (result == 0)
                {
                  // <GetExitCodeProcess> failed!
                  this->remove_proc (idx);
                  pid = ACE_INVALID_PID;
                }
            }
          else
            {
              // uh oh...handle removed from process_table_, even though
              // we're holding a lock!
              delete [] handles;
              ACE_ERROR_RETURN ((LM_ERROR,
                                 ACE_TEXT ("Process removed")
                                 ACE_TEXT (" -- somebody's ignoring the lock!\n")),
                                -1);
            }
        }

      delete [] handles;
#else /* !defined(ACE_WIN32) */
      if (timeout == ACE_Time_Value::max_time)
        pid = ACE_OS::waitpid (-1, status, 0);
      else if (timeout == ACE_Time_Value::zero)
        pid = ACE_OS::waitpid (-1, status, WNOHANG);
      else
        {
# if defined (ACE_LACKS_UNIX_SIGNALS)
          pid = 0;
          ACE_Time_Value sleeptm (1);    // 1 msec
          if (sleeptm > timeout)         // if sleeptime > waittime
            sleeptm = timeout;
          ACE_Time_Value tmo (timeout);  // Need one we can change
          for (ACE_Countdown_Time time_left (&tmo); tmo > ACE_Time_Value::zero ; time_left.update ())
            {
              pid = ACE_OS::waitpid (-1, status, WNOHANG);
              if (pid > 0 || pid == ACE_INVALID_PID)
                break;          // Got a child or an error - all done

              // pid 0, nothing is ready yet, so wait.
              // Do a (very) short sleep (only this thread sleeps).
              ACE_OS::sleep (sleeptm);
            }
# else
          // Force generation of SIGCHLD, even though we don't want to
          // catch it - just need it to interrupt the sleep below.
          // If this object has a reactor set, assume it was given at
          // open(), and there's already a SIGCHLD action set, so no
          // action is needed here.
          ACE_Sig_Action old_action;
          if (this->reactor () == 0)
            {
              ACE_Sig_Action do_sigchld ((ACE_SignalHandler)sigchld_nop);
              do_sigchld.register_action (SIGCHLD, &old_action);
            }

          ACE_Time_Value tmo (timeout);  // Need one we can change
          for (ACE_Countdown_Time time_left (&tmo); ; time_left.update ())
            {
              pid = ACE_OS::waitpid (-1, status, WNOHANG);
#   if defined (ACE_VXWORKS) && (ACE_VXWORKS >= 0x600)
              if (pid > 0 || (pid == ACE_INVALID_PID && errno != EINTR))
#   else
                if (pid > 0 || pid == ACE_INVALID_PID)
#   endif
                  break;          // Got a child or an error - all done

              // pid 0, nothing is ready yet, so wait.
              // Do a sleep (only this thread sleeps) til something
              // happens. This relies on SIGCHLD interrupting the sleep.
              // If SIGCHLD isn't delivered, we'll need to do something
              // with sigaction to force it.
              if (-1 == ACE_OS::sleep (tmo) && errno == EINTR)
                continue;
              // Timed out
              pid = 0;
              break;
            }

          // Restore the previous SIGCHLD action if it was changed.
          if (this->reactor () == 0)
            old_action.register_action (SIGCHLD);
# endif /* !ACE_LACKS_UNIX_SIGNALS */
        }
#endif /* !defined (ACE_WIN32) */
    }

  ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, this->lock_, -1));
  if (pid != ACE_INVALID_PID && pid != 0)
    {
      //we always need to get our id, because we could have been moved in the table meanwhile
      idx = this->find_proc (pid);
      if (idx == -1)
        {
          // oops, reaped an unmanaged process!
          ACE_DEBUG ((LM_DEBUG,
                      ACE_TEXT ("(%P|%t) oops, reaped unmanaged %d\n"),
                      pid));
          return pid;
        }
      else
        proc = process_table_[idx].process_;
      if (proc != 0)
        ACE_ASSERT (pid == proc->getpid ());

      this->notify_proc_handler (idx,
                                 *status);
      this->remove (pid);
    }

  return pid;
}
Exemplo n.º 18
0
Arquivo: motor.c Projeto: miaofng/ulp
void motor_Update(void)
{
	short speed, torque_ref, speed_pid;

	vsm_Update();
	smo_Update();
	speed = smo_GetSpeed();
	speed_pid = pid_GetRef(pid_speed);

	switch (stm) {
		case MOTOR_IDLE:
			break;

		case MOTOR_START_OP:
			led_flash(LED_RED);
			led_flash(LED_GREEN);
			smo_Start();
			vsm_Start();
			stm = MOTOR_START;

			//soft start???
			torque_ref = motor->start_torque;
			pid_SetRef(pid_flux, 0); /*Id = 0 control method*/
			pid_SetRef(pid_torque, torque_ref);
			break;
			
		case MOTOR_START:
			/*only for debug purpose*/
			pwm1_Set(smo_GetSpeed()*100);
			pwm2_Set(smo_GetAngle());
			
			if(smo_IsLocked()) {
				stm = MOTOR_RUN;
				led_off(LED_RED);
				led_flash(LED_GREEN);
			}
			if(speed_pid == 0) {
				stm = MOTOR_STOP_OP;
				led_on(LED_RED);
				led_on(LED_GREEN);
			}
			break;

		case MOTOR_RUN:
			/*only for debug purpose*/
			pwm1_Set(smo_GetSpeed()*100);
			pwm2_Set(smo_GetAngle());
			
			if((speed_pid == 0) && (speed < motor->start_speed)) {
				stm = MOTOR_STOP_OP;
				led_on(LED_RED);
				led_on(LED_GREEN);
				break;
			}

			/*speed pid*/
			torque_ref = pid_Calcu(pid_speed, speed);
			pid_SetRef(pid_flux, 0); /*Id = 0 control method*/
			pid_SetRef(pid_torque, torque_ref);
			break;

		case MOTOR_STOP_OP:
			vsm_Stop(); /*note: It's not a brake!!!*/
			stop_timer = time_get(MOTOR_STOP_PERIOD);
			stm = MOTOR_STOP;
			break;
			
		case MOTOR_STOP:
			if(time_left(stop_timer) < 0) {
				stm = MOTOR_IDLE;
				led_off(LED_RED);
				led_on(LED_GREEN);
			}
			break;

		default:
			led_on(LED_RED);
			led_off(LED_GREEN);
			printf("SYSTEM ERROR!!!\n");
	}
}
Exemplo n.º 19
0
Arquivo: Main.cpp Projeto: ethr/reflex
int main(int argc, char *argv[]) {
    int width = 640;
    int height = 480;
 
    if (SDL_Init(SDL_INIT_VIDEO) != 0) {
    	return 1;
    }
    if (TTF_Init() == -1) {
      printf("Unable to initialize SDL_ttf: %s \n", TTF_GetError());
      return 2;
    }
    atexit(SDL_Quit);

    const SDL_VideoInfo* videoInfo = SDL_GetVideoInfo();
    if (videoInfo) {
      width = videoInfo->current_w;
      height = videoInfo->current_h;
    }

    SDL_Surface* screen = SDL_SetVideoMode(width, height, 0,
        SDL_HWSURFACE | SDL_FULLSCREEN | SDL_DOUBLEBUF);
    reflexgame::Renderer renderer(screen);
    reflexgame::GameState gameState(width, height);
 
    if (screen == NULL)
        return 2;

    SDL_ShowCursor(0);
    SDL_WM_GrabInput(SDL_GRAB_ON);

    Uint32 nextTime = 0;
    time_left(nextTime);
    gameState.start();
    while(true) {
        gameState.handleTick();
        if (gameState.gameEnded()) {
          SDL_Event event; 
          while(SDL_PollEvent(&event)) {
            switch(event.type){
              case SDL_KEYDOWN:
                switch(event.key.keysym.sym){
                  case SDLK_ESCAPE:
                    return 0;
                    break;
                  default:
                    break;
                }
              case SDL_QUIT:
                return 0;
              default:
                break;
            }
          }
          renderer.drawEndGame(gameState);
        } else {
          SDL_Event event; 
          while(SDL_PollEvent(&event)) {
            switch(event.type){
              case SDL_MOUSEBUTTONDOWN:
                {
                  if (event.button.button == SDL_BUTTON_LEFT) {
                    int x = event.button.x;
                    int y = event.button.y;
                    printf("Click at (%d, %d)\n", x, y);
                    gameState.attackAt(x, y);
                  }
                  break;
                }
              case SDL_KEYDOWN:
                switch(event.key.keysym.sym){
                  case SDLK_ESCAPE:
                    return 0;
                    break;
                  default:
                    break;
                }
              case SDL_QUIT:
                return 0;
              default:
                break;
            }
          }
          renderer.draw(gameState);
        }
        SDL_Flip(screen);
        SDL_Delay(time_left(nextTime));
    }
 
    return 0;
}
Exemplo n.º 20
0
	operator DWORD() {
		return active ? time_left() : INFINITE;
	}