Exemple #1
0
/* *** External visible functions *** */
void elect()
{
	// Delete current if terminated (so a terminated process does not wait at the end of list)
	if (current_process->status == TERMINATED)
	{
		terminate_if_last_process();

		current_process->previous->next = current_process->next;
		current_process->next->previous = current_process->previous;
		
		struct pcb_s* process_to_delete = current_process;
		
		choose_next_process();
		
		free_process(process_to_delete);
	}
	else if (current_process->status  == BLOCKED)
	{
		choose_next_process();
	}
	else
	{
		current_process->status = READY;
		choose_next_process();
	}
	
	#if DEBUG
	#if FB
		fb_print_char('\n');
		fb_print_text("The process with PID ");
		fb_print_int(current_process->pid);
		fb_print_text(" chosen with priority ");
		fb_print_int(current_process->priority);
		fb_print_char('\n');
		
	#else
		
		log_str("\n The process with PID ");
		log_int(current_process->pid);
		log_str(" chosen with priority ");
		log_int(current_process->priority);
		log_str("\n");
		
	#endif	
	#endif
	
	if (current_process->status == TERMINATED || current_process->status  == BLOCKED)
		elect(); // Elect the next one, and delete the current one
	else
		current_process->status = RUNNING; // Else, this one is now running
}
Exemple #2
0
int		words_are_valid(char *line, int line_number)
{
	log_int("starting words validation for line: ", line_number);
	if (names_are_valid(line, line_number) == 0)
	{
		log_simple("words validation ended unsuccesfully");
		return (0);
	}
	if (email_is_valid(get_word_number(line, 3), line_number) == 0)
	{
		log_simple("words validation ended unsuccesfully");
		return (0);
	}
	if (grade_is_valid(get_word_number(line, 4), line_number) == 0)
	{
		log_simple("words validation ended unsuccesfully");
		return (0);
	}
	if (county_is_valid(get_word_number(line, 5), line_number) == 0)
	{
		log_simple("words validation ended unsuccesfully");
		return (0);
	}
	return (1);
	log_simple("words validation ended succesfully");
}
/*	Write a byte of data to the serial link or set it up to be sent later (QR-side)
 *	Returns 1 if data was written directly, 0 if placed in buffer, -1 otherwise
 *	Author: Maurijn Neumann
 */
int serial_write(unsigned char c) {
	//Check if data can be written immediately
	if ((serial_buffer_send_top == serial_buffer_send_base) &&
		(X32_serial_status & 0x01)) {

		//Write to buffer, and done
//		X32_display = c;
		X32_serial_data = c;
		return 1;
	} else {
		//Place data in buffer, update, *critical section due to top/base comparison*
		DISABLE_INTERRUPT(INTERRUPT_GLOBAL);
		serial_buffer_send[serial_buffer_send_top] = c;
		serial_buffer_send_top++;
		if (serial_buffer_send_top >= SERIAL_BUFFER_SIZE)
			serial_buffer_send_top = 0;
		if (serial_buffer_send_top == serial_buffer_send_base) {
			log_msg("Serial output buffer full; discarding");
			log_int(serial_buffer_send_top);
			log_data(LOG_COMM_DISCARD_BUFFER, serial_buffer_send, SERIAL_BUFFER_SIZE);
			return -1;
		}
		ENABLE_INTERRUPT(INTERRUPT_GLOBAL);
		return 0;
	}
}
void MFLogger::log(const wchar_t* szText){
	size_t len = wcslen(szText) + 1;
	wchar_t* buffer = new wchar_t[(PREFIX_SIZE + len) * sizeof(wchar_t)];
	memcpy(buffer, m_prefix, PREFIX_SIZE * sizeof(m_prefix[0]));
	memcpy(buffer + PREFIX_SIZE , szText, len * sizeof(wchar_t));
	log_int(buffer);
	delete[] buffer;
}
void MFLogger::log_p(const wchar_t* szText, ...){
	va_list args;
	va_start(args, szText);
	int len = (PREFIX_SIZE + _vscwprintf(szText, args ) + 1); // _vscprintf doesn't count terminating '\0'
	wchar_t* buffer = new wchar_t[len * sizeof(wchar_t)];
	vswprintf_s(buffer + PREFIX_SIZE, len, szText, args);
	va_end(args);
	memcpy(buffer, m_prefix, PREFIX_SIZE * sizeof(m_prefix[0]));
	log_int(buffer);
	delete[] buffer;
}
/*	ISR for incoming serial data on the QR-side
 *	Author: Maurijn Neumann
 */
void isr_serial_rx(void) {
	//Keep reading while flag is raised
	while (X32_serial_status & 0x02) {
		//Read into buffer, update
		serial_buffer_recv[serial_buffer_recv_top] = X32_serial_data;
		//Update and circle index
		serial_buffer_recv_top++;
		if (serial_buffer_recv_top >= SERIAL_BUFFER_SIZE)
			serial_buffer_recv_top = 0;
		if (serial_buffer_recv_top == serial_buffer_recv_base) {
			log_msg("Serial input buffer full; discarding");
			log_int(serial_buffer_recv_top);
			log_data(LOG_COMM_DISCARD_BUFFER, serial_buffer_recv, SERIAL_BUFFER_SIZE);
		}
	}
}
int		count_char_in_string(char *string, char character)
{
	int		index;
	int		count;

	log_string("counting specific chars in string: ", string);
	count = 0;
	index = 0;
	while (string[index] != '\0')
	{
		if (string[index] == character)
			count++;
		index++;
	}
	log_int("counted chars: ", count);
	return (count);
}
int		choose_and_open_database(int *fd, int ac, char **av)
{
	log_int("choosing database to open. arguments: ", ac);
	if (ac == 2)
	{
		if (open_file(fd, av[1]) == -1)
		{
			log_string("could not open database: ", av[1]);
			return (-1);
		}
	}
	else
	{
		if (open_file(fd, STANDARD_CSV) == -1)
		{
			log_string("could not open database: ", STANDARD_CSV);
			return (-1);
		}
	}
	log_simple("succesfully opened database");
	return (1);
}
Exemple #9
0
 void manage_heater()
 {

  //Temperatur Monitor for repetier
  if((millis() - previous_millis_monitor) > 250 )
  {
    previous_millis_monitor = millis();
    if(manage_monitor <= 1)
    {
      showString(PSTR("MTEMP:"));
      Serial.print(millis());
      if(manage_monitor<1)
      {
        showString(PSTR(" "));
        Serial.print(analog2temp(current_raw));
        showString(PSTR(" "));
        Serial.print(target_temp);
        showString(PSTR(" "));
        #ifdef PIDTEMP
        Serial.println(heater_duty);
        #else 
          #if (HEATER_0_PIN > -1)
          if(READ(HEATER_0_PIN))
            Serial.println(255);
          else
            Serial.println(0);
          #else
          Serial.println(0);
          #endif
        #endif
      }
      #if THERMISTORBED!=0
      else
      {
        showString(PSTR(" "));
        Serial.print(analog2tempBed(current_bed_raw));
        showString(PSTR(" "));
        Serial.print(analog2tempBed(target_bed_raw));
        showString(PSTR(" "));
        #if (HEATER_1_PIN > -1)
          if(READ(HEATER_1_PIN))
            Serial.println(255);
          else
            Serial.println(0);
        #else
          Serial.println(0);
        #endif  
      }
      #endif
      
    }
  
  }
  // ENDE Temperatur Monitor for repetier
 
  if((millis() - previous_millis_heater) < HEATER_CHECK_INTERVAL )
    return;
    
  previous_millis_heater = millis();
  
  #ifdef HEATER_USES_THERMISTOR
    current_raw = analogRead(TEMP_0_PIN); 
    #ifdef DEBUG_HEAT_MGMT
      log_int("_HEAT_MGMT - analogRead(TEMP_0_PIN)", current_raw);
      log_int("_HEAT_MGMT - NUMTEMPS", NUMTEMPS);
    #endif
    // When using thermistor, when the heater is colder than targer temp, we get a higher analog reading than target, 
    // this switches it up so that the reading appears lower than target for the control logic.
    current_raw = 1023 - current_raw;
  #elif defined HEATER_USES_AD595
    current_raw = analogRead(TEMP_0_PIN);    
  #elif defined HEATER_USES_MAX6675
    current_raw = read_max6675();
  #endif
  
  //MIN / MAX save to display the jitter of Heaterbarrel
  if(current_raw > current_raw_maxval)
    current_raw_maxval = current_raw;
    
  if(current_raw < current_raw_minval)
    current_raw_minval = current_raw;
 
  #ifdef SMOOTHING
    if (!nma) nma = SMOOTHFACTOR * current_raw;
    nma = (nma + current_raw) - (nma / SMOOTHFACTOR);
    current_raw = nma / SMOOTHFACTOR;
  #endif
  
  #ifdef WATCHPERIOD
    if(watchmillis && millis() - watchmillis > WATCHPERIOD)
    {
        if(watch_raw + 1 >= current_raw)
        {
            target_temp = target_raw = 0;
            WRITE(HEATER_0_PIN,LOW);

            #ifdef PID_SOFT_PWM
              g_heater_pwm_val = 0;           
            #else
              analogWrite(HEATER_0_PIN, 0);
              #if LED_PIN>-1
                WRITE(LED_PIN,LOW);
              #endif
            #endif
        }
        else
        {
            watchmillis = 0;
        }
    }
  #endif
  
  //If tmp is lower then MINTEMP stop the Heater
  //or it os better to deaktivate the uutput PIN or PWM ?
  #ifdef MINTEMP
    if(current_raw <= minttemp)
        target_temp = target_raw = 0;
  #endif
  
  #ifdef MAXTEMP
    if(current_raw >= maxttemp)
    {
        target_temp = target_raw = 0;
    
        #if (ALARM_PIN > -1) 
          WRITE(ALARM_PIN,HIGH);
        #endif
    }
  #endif

  #if (TEMP_0_PIN > -1) || defined (HEATER_USES_MAX6675) || defined (HEATER_USES_AD595)
    #ifdef PIDTEMP
      
      int current_temp = analog2temp(current_raw);
      error = target_temp - current_temp;
      int delta_temp = current_temp - prev_temp;
      
      prev_temp = current_temp;
      pTerm = ((long)PID_PGAIN * error) / 256;
      const int H0 = min(HEATER_DUTY_FOR_SETPOINT(target_temp),HEATER_CURRENT);
      heater_duty = H0 + pTerm;
      
      if(error < 30)
      {
        temp_iState += error;
        temp_iState = constrain(temp_iState, temp_iState_min, temp_iState_max);
        iTerm = ((long)PID_IGAIN * temp_iState) / 256;
        heater_duty += iTerm;
      }
      
      int prev_error = abs(target_temp - prev_temp);
      int log3 = 1; // discrete logarithm base 3, plus 1
      
      if(prev_error > 81){ prev_error /= 81; log3 += 4; }
      if(prev_error >  9){ prev_error /=  9; log3 += 2; }
      if(prev_error >  3){ prev_error /=  3; log3 ++;   }
      
      dTerm = ((long)PID_DGAIN * delta_temp) / (256*log3);
      heater_duty += dTerm;
      heater_duty = constrain(heater_duty, 0, HEATER_CURRENT);

      #ifdef PID_SOFT_PWM
        g_heater_pwm_val = (unsigned char)heater_duty;
      #else
        analogWrite(HEATER_0_PIN, heater_duty);
    
        #if LED_PIN>-1
          analogWrite(LED_PIN, constrain(LED_PWM_FOR_BRIGHTNESS(heater_duty),0,255));
        #endif
      #endif
  
    #else
    
      if(current_raw >= target_raw)
      {
        WRITE(HEATER_0_PIN,LOW);
        #if LED_PIN>-1
            WRITE(LED_PIN,LOW);
        #endif
      }
      else 
      {
        WRITE(HEATER_0_PIN,HIGH);
        #if LED_PIN > -1
            WRITE(LED_PIN,HIGH);
        #endif
      }
    #endif
  #endif
    
  if(millis() - previous_millis_bed_heater < BED_CHECK_INTERVAL)
    return;
  
  previous_millis_bed_heater = millis();

  #ifndef TEMP_1_PIN
    return;
  #endif

  #if TEMP_1_PIN == -1
    return;
  #else
  
  #ifdef BED_USES_THERMISTOR
  
    current_bed_raw = analogRead(TEMP_1_PIN);   
  
    #ifdef DEBUG_HEAT_MGMT
      log_int("_HEAT_MGMT - analogRead(TEMP_1_PIN)", current_bed_raw);
      log_int("_HEAT_MGMT - BNUMTEMPS", BNUMTEMPS);
    #endif               
  
    // If using thermistor, when the heater is colder than targer temp, we get a higher analog reading than target, 
    // this switches it up so that the reading appears lower than target for the control logic.
    current_bed_raw = 1023 - current_bed_raw;
  #elif defined BED_USES_AD595
    current_bed_raw = analogRead(TEMP_1_PIN);                  

  #endif
  
  
  #ifdef MINTEMP
    if(current_bed_raw >= target_bed_raw || current_bed_raw < minttemp)
  #else
    if(current_bed_raw >= target_bed_raw)
  #endif
    {
      WRITE(HEATER_1_PIN,LOW);
    }
    else 
    {
      WRITE(HEATER_1_PIN,HIGH);
    }
    #endif
    
#ifdef CONTROLLERFAN_PIN
  controllerFan(); //Check if fan should be turned on to cool stepper drivers down
#endif

}
Exemple #10
0
void GobGame::init(Log *_log)
{
	STACKTRACE;
	int i;
	/*	switch(_log->type) {
	//		case Log::log_net1server:
	//		case Log::log_net1client: {
	//			error("unsupported game/log type");
	//		}
	//		break;
			default: {
			}
			break;
		}/**/
	Game::init(_log);

	log_file(home_ini_full_path("server.ini"));
	max_enemies = get_config_int("Gob", "MaxEnemies", 32);
	int starting_starbucks, starting_buckazoids;
	starting_starbucks = get_config_int("Gob", "StartingStarbucks", 0);
	starting_buckazoids = get_config_int("Gob", "StartingBuckazoids", 0);
	gobenemy = (GobEnemy**) malloc(sizeof(GobEnemy*) * max_enemies);

	size = Vector2(24000, 24000);

	enemy_team = new_team();
	station_team = new_team();

	//	set_resolution(videosystem.width, videosystem.height);

	TW_DATAFILE *tmpdata;
	tmpdata = tw_load_datafile_object(data_full_path("gob.dat").c_str(), "station0sprite");
	if (!tmpdata)
		tw_error( "couldn't find gob.dat#station0sprite");
	stationSprite[0] = new SpaceSprite(tmpdata, 1, SpaceSprite::MASKED | SpaceSprite::MIPMAPED, 64);
	tw_unload_datafile_object(tmpdata);
	stationSprite[0]->permanent_phase_shift(8);

	tmpdata = tw_load_datafile_object(data_full_path("gob.dat").c_str(), "station1sprite");
	if (!tmpdata)
		tw_error ("couldn't find gob.dat#station1sprite");
	stationSprite[1] = new SpaceSprite(tmpdata, 1, SpaceSprite::MASKED | SpaceSprite::MIPMAPED, 64);
	tw_unload_datafile_object(tmpdata);
	stationSprite[1]->permanent_phase_shift(8);

	tmpdata = tw_load_datafile_object(data_full_path("gob.dat").c_str(), "station2sprite");
	if (!tmpdata)
		tw_error ("couldn't find gob.dat#station2sprite");
	stationSprite[2] = new SpaceSprite(tmpdata, 1, SpaceSprite::MASKED | SpaceSprite::MIPMAPED, 64);
	tw_unload_datafile_object(tmpdata);
	stationSprite[2]->permanent_phase_shift(8);

	tmpdata = tw_load_datafile_object(data_full_path("gob.dat").c_str(), "defender");
	if (!tmpdata)
		tw_error ("couldn't find gob.dat#defender");
	defenderSprite = new SpaceSprite(tmpdata, 1, SpaceSprite::MASKED | SpaceSprite::MIPMAPED);
	tw_unload_datafile_object(tmpdata);

	station_pic_name[0] = "gob.dat#station0picture.bmp";
	station_pic_name[1] = "gob.dat#station1picture.bmp";
	station_pic_name[2] = "gob.dat#station2picture.bmp";
	station_build_name[0] = "supbl";
	station_build_name[1] = "orzne";
	station_build_name[2] = "kohma";

	prepare();

	add(new Stars());

	num_planets = 0;
	i = 0;
	add_planet_and_station(meleedata.planetSprite, i, stationSprite[i], station_build_name[i], station_pic_name[i]);
	i = 1;
	add_planet_and_station(meleedata.planetSprite, i, stationSprite[i], station_build_name[i], station_pic_name[i]);
	i = 2;
	add_planet_and_station(meleedata.planetSprite, i, stationSprite[i], station_build_name[i], station_pic_name[i]);
	i = random() % 3;
	add_planet_and_station(meleedata.planetSprite, i, stationSprite[i], "utwju", station_pic_name[i]);

	for (i = 0; i < 42; i += 1) add(new GobAsteroid());

	int server_players, client_players;
	set_config_file("client.ini");
	server_players = client_players = get_config_int("Gob", "NumPlayers", 1);
	if (!lag_frames) client_players = 0;
	log_int(channel_server, server_players);
	log_int(channel_client, client_players);
	for (i = 0; i < server_players; i += 1) {
		char buffy[256];
		sprintf(buffy, "Config%d", i);
		add_gobplayer(create_control(channel_server, "Human", buffy));
		gobplayer[i]->new_ship(shiptype("supbl"));
		gobplayer[i]->starbucks = starting_starbucks+0;
		gobplayer[i]->buckazoids = starting_buckazoids+0;
		Ship *s = gobplayer[i]->ship;
		s->translate(size/2-s->normal_pos());
		double angle = PI2 * i / (client_players + server_players);
		s->translate(rotate(Vector2(260, 120), angle));
		s->accelerate(s, PI2/3 + angle, 0.17, MAX_SPEED);
	}
	for (i = server_players; i < client_players + server_players; i += 1) {
		char buffy[256];
		sprintf(buffy, "Config%d", i - server_players);
		add_gobplayer(create_control(channel_client, "Human", buffy));
		gobplayer[i]->new_ship(shiptype("supbl"));
		gobplayer[i]->starbucks = starting_starbucks;
		gobplayer[i]->buckazoids = starting_buckazoids;
		Ship *s = gobplayer[i]->ship;
		s->translate(size/2-s->normal_pos());
		double angle = PI2 * i / (client_players + server_players);
		s->translate(rotate(Vector2(260, 120), angle));
		s->accelerate(s, PI2/3 + angle, 0.17, MAX_SPEED);
	}

	for (i = 0; i < gobplayers+0; i += 1) add ( new RainbowRift() );

	next_add_new_enemy_time = 1000;
	this->change_view("Hero");
	//view = get_view ( "Hero", NULL );
	view_locked = true;
	view->window->locate(
		0,0,
		0,0,
		0,0.9,
		0,1
		);

	add_new_enemy();
	add_new_enemy();
	return;
}
Exemple #11
0
void NormalGame::init_players()
{
	STACKTRACE;
	switch (log->type) {
		case Log::log_normal:
		{
			for (int i = 0; true; i += 1) {
				char buffy[64];
				sprintf(buffy, "Player%d", i + 1);
				tw_set_config_file("scp.ini");
				const char *type = get_config_string(buffy, "Type", NULL);
				if (!type) break;
				if (strcmp(type, "none") == 0) continue;
				const char *name = get_config_string(buffy, "Name", buffy);
				char config[64];
				sprintf(config, "Config%d", get_config_int(buffy, "Config", 0));
				//int channel = channel_server;
				//if (strcmp(type, "WussieBot") == 0) channel = channel_none;
				//if (strcmp(type, "MoronBot") == 0) channel = channel_none;
				int ti = get_config_int(buffy, "Team", 0);
				add_player(create_control(channel_server, type, config), ti, name, buffy);
			}
		}
		break;
		case Log::log_net1client:
		case Log::log_net1server:
		{
			log_file(home_ini_full_path("server.ini"));
			//int use_teams_menu = get_config_int("Network", "NetworkMeleeUseTeams", 0);
			//if (use_teams_menu) {
			if (1) {
				int j;
				for (j = 0; j < 2; j += 1) {
					int ch;
					if (j == 0) ch = channel_server;
					else ch = channel_client;
					if (is_local(ch)) {
								 //each side determines whether they are using manually specified teams
						tw_set_config_file("client.ini");
						int use_teams_menu = get_config_int("Network", "NetworkMeleeUseTeams", 0);
						const char *simple_config =
							"[Player1]\nType=Human\nConfig=0\nTeam=0\n";
						for (int i = 0; true; i += 1) {
							char buffy[64];
							sprintf(buffy, "Player%d", i + 1);
							if (use_teams_menu) tw_set_config_file("scp.ini");
							else set_config_data(simple_config, strlen(simple_config));
							const char *type = get_config_string(buffy, "Type", NULL);
							if (!type) {
								int tmp = 0;
								log_int(ch, tmp);
								break;
							}
							if (strcmp(type, "none") == 0) continue;
							const char *name = get_config_string(buffy, "Name", buffy);
							char config[64];
							sprintf(config, "Config%d", get_config_int(buffy, "Config", 0));
							//int channel = channel_server;
							//if (strcmp(type, "WussieBot") == 0) channel = channel_none;
							//if (strcmp(type, "MoronBot") == 0) channel = channel_none;
							int ti = get_config_int(buffy, "Team", 0);
							{int tmp = 1; log_int(ch, tmp);}
							log_int(ch, ti);
							int name_length = strlen(name);
							log_int(ch, name_length);
							log_data(ch, (char*)name, name_length);
							add_player(create_control(ch, type, config), ti, name, buffy);
						}
					} else {
						for (int i = 0; true; i += 1) {
							int tmp;
							log_int(ch, tmp);
							if (tmp == 0) break;
							int team;
							char *name;
							log_int(ch, team);
							int name_length;
							log_int(ch, name_length);
							name = (char*)malloc((name_length+1)*sizeof(char));
							log_data(ch, name, name_length);
							name[name_length] = 0;
							add_player(create_control(ch, "Whatever"), team, name, NULL);
						}
					}
				}
			}
		}
		break;
	}
	return;
}
bool is_power_of_2(long long n)
{
  return (n == ((long long)(1) << log_int(n)));
}
Exemple #13
0
void NormalGame::choose_new_ships()
{
	STACKTRACE;
	char tmp[40];
	int i;
	pause();
	message.out("Selecting ships...", 1000);
	int *slot = new int[num_players];
	//choose ships and send them across network
	for (i = 0; i < num_players; i += 1) {
		slot[i] = -2;
		if (player_control[i]->ship) {
		} else {
			//			if (player_panel[i]) player_panel[i]->window->hide();
			//			player_panel[i] = NULL;
			sprintf (tmp, "Player%d", i+1);
			Fleet *fleet = player_fleet[i];
			if (fleet->getSize() == 0) continue;
			char buffy[512];

			if (strlen(fleet->getTitle()) != 0)
				sprintf(buffy, "%s\n%s\n", player_name[i], fleet->getTitle());
			else
				sprintf(buffy, "%s\n", player_name[i]);

			slot[i] = player_control[i]->choose_ship(window, buffy, fleet);
			if (player_control[i]->channel != channel_none) {
				slot[i] = intel_ordering(slot[i]);
				log->buffer(player_control[i]->channel, &slot[i], sizeof(int));
				log->flush();
				//slot[i] = intel_ordering(slot[i]);
			}
		}
	}
	//recieve the ships that were chosen
	log->listen();
	for (i = 0; i < num_players; i += 1) {
		if (slot[i] == -2) continue;
		if (player_control[i]->channel != channel_none) {
			log->unbuffer(player_control[i]->channel, &slot[i], sizeof(int));
			slot[i] = intel_ordering(slot[i]);
		}
	}
	//create the ships that were chosen
	for (i = 0; i < num_players; i += 1) {
		if (slot[i] == -2) continue;
		sprintf (tmp, "Player%d", i+1);
		//fleet->load("./fleets.tmp", tmp);
		Fleet *fleet = player_fleet[i];
		if (slot[i] == -1) slot[i] = random() % fleet->getSize();
		if (slot[i] < 0 || slot[i] >= fleet->getSize()) {tw_error("trying to load invalid ship");}
		Ship *s = create_ship(fleet->getShipType(slot[i])->id, player_control[i], random(size), random(PI2), player_team[i]);
		if (!s) {tw_error("unable to create ship");}
		fleet->clear_slot(slot[i]);
		fleet->Sort();
		//fleet->save("./fleets.tmp", tmp);
		s->locate();
		add ( new WedgeIndicator ( s, 30, i+1 ) );
		ShipPanel *panel = new ShipPanel(s);
		panel->window->init(window);
		panel->window->locate(
			0, 0.9,
			0, i * (100.0/480),
			0, 0.1,
			0, (100.0/480)
			);
		add(panel);
		add(s->get_ship_phaser());

		// add a healthbar for the ship, and also a team indicator.
		add(new HealthBar(s, &indhealthtoggle));
		add(new TeamIndicator(s, &indteamtoggle));

		// CHECK FILE SIZES !! to intercept desynch before they happen.
		int myfsize, otherfsize;

		myfsize = file_size_ex(s->type->data->file);
		otherfsize = myfsize;
		if (player_control[i]->channel != channel_none) {
			log_int(player_control[i]->channel, otherfsize);
		}

		if (otherfsize != myfsize) {
			// the player who loads the ship doesn't get this message, cause his own file is identical by default
			tw_error("DAT files have different size! This may cause a desynch. Press Retry to continue");
		}

	}
	delete[] slot;
	message.out("Finished selecting ships...", 1500);
	unpause();
	return;
}
Exemple #14
0
do_ORBIT_command ()
{
    int		i, found, specified_planet_number;

    char	*original_line_pointer;


    /* Get the ship. */
    original_line_pointer = input_line_pointer;
    found = get_ship ();
    if (! found)
    {
	/* Check for missing comma or tab after ship name. */
	input_line_pointer = original_line_pointer;
	fix_separator ();
	found = get_ship ();
	if (! found)
	{
	    fprintf (log_file, "!!! Order ignored:\n");
	    fprintf (log_file, "!!! %s", original_line);
	    fprintf (log_file, "!!! Invalid ship name in ORBIT command.\n");
	    return;
	}
    }

    if (ship->status == UNDER_CONSTRUCTION)
    {
	fprintf (log_file, "!!! Order ignored:\n");
	fprintf (log_file, "!!! %s", original_line);
	fprintf (log_file, "!!! Ship is still under construction.\n");
	return;
    }

    if (ship->status == FORCED_JUMP  ||  ship->status == JUMPED_IN_COMBAT)
    {
	fprintf (log_file, "!!! Order ignored:\n");
	fprintf (log_file, "!!! %s", original_line);
	fprintf (log_file, "!!! Ship jumped during combat and is still in transit.\n");
	return;
    }

    /* Make sure this ship didn't just arrive via a MOVE command. */
    if (ship->just_jumped == 50)
    {
	fprintf (log_file, "!!! Order ignored:\n");
	fprintf (log_file, "!!! %s", original_line);
	fprintf (log_file, "!!! ORBIT not allowed immediately after a MOVE!\n");
	return;
    }

    /* Make sure ship is not salvage of a disbanded colony. */
    if (disbanded_ship (ship))
    {
	fprintf (log_file, "!!! Order ignored:\n");
	fprintf (log_file, "!!! %s", original_line);
	fprintf (log_file, "!!! This ship is salvage of a disbanded colony!\n");
	return;
    }

    /* Get the planet. */
    specified_planet_number = get_value ();

get_planet:

    if (specified_planet_number)
    {
	found = FALSE;
	specified_planet_number = value;
	for (i = 0; i < num_stars; i++)
	{
	    star = star_base + i;

	    if (star->x != ship->x) continue;
	    if (star->y != ship->y) continue;
	    if (star->z != ship->z) continue;

	    if (specified_planet_number >= 1
		&&  specified_planet_number <= star->num_planets)
			found = TRUE;

	    break;
	}

	if (! found)
	{
	    fprintf (log_file, "!!! Order ignored:\n");
	    fprintf (log_file, "!!! %s", original_line);
	    fprintf (log_file, "!!! Invalid planet in ORBIT command.\n");
	    return;
	}

	ship->pn = specified_planet_number;

	goto finish_up;
    }

    found = get_location ();
    if (! found  ||  nampla == NULL)
    {
	if (ship->status == IN_ORBIT  || ship->status == ON_SURFACE)
	{
	    /* Player forgot to specify planet. Use the one it's already at. */
	    specified_planet_number = ship->pn;
	    value = specified_planet_number;
	    goto get_planet;
	}

	fprintf (log_file, "!!! Order ignored:\n");
	fprintf (log_file, "!!! %s", original_line);
	fprintf (log_file, "!!! Invalid or missing planet in ORBIT command.\n");
	return;
    }

    /* Make sure the ship and the planet are in the same star system. */
    if (ship->x != nampla->x  ||  ship->y != nampla->y  ||  ship->z != nampla->z)
    {
	fprintf (log_file, "!!! Order ignored:\n");
	fprintf (log_file, "!!! %s", original_line);
	fprintf (log_file, "!!! Ship and planet are not in the same sector.\n");
	return;
    }

    /* Move the ship. */
    ship->pn = nampla->pn;

finish_up:

    ship->status = IN_ORBIT;

    /* If a planet number is being used, see if it has a name.  If so,
	use the name. */
    if (specified_planet_number)
    {
	for (i = 0; i < species->num_namplas; i++)
	{
	    nampla = nampla_base + i;

	    if (nampla->x != ship->x) continue;
	    if (nampla->y != ship->y) continue;
	    if (nampla->z != ship->z) continue;
	    if (nampla->pn != specified_planet_number) continue;

	    specified_planet_number = 0;
	    break;
	}
    }

    /* Log result. */
    log_string ("    ");
    log_string (ship_name (ship));
    if (first_pass)
	log_string (" will enter orbit around ");
    else
	log_string (" entered orbit around ");

    if (specified_planet_number)
    {
	log_string ("planet number ");
	log_int (specified_planet_number);
    }
    else
    {
	log_string ("PL ");
	log_string (nampla->name);
    }

    log_string (".\n");
}
Exemple #15
0
do_ESTIMATE_command ()

{
    int		i, max_error, estimate[6], contact_word_number,
		contact_bit_number;

    long	cost, contact_mask;

    struct species_data		*alien;


    /* Check if this order was preceded by a PRODUCTION order. */
    if (!doing_production)
    {
	fprintf (log_file, "!!! Order ignored:\n");
	fprintf (log_file, "!!! %s", input_line);
	fprintf (log_file, "!!! Missing PRODUCTION order!\n");
	return;
    }

    /* Get name of alien species. */
    if (! get_species_name())
    {
	fprintf (log_file, "!!! Order ignored:\n");
	fprintf (log_file, "!!! %s", input_line);
	fprintf (log_file, "!!! Invalid species name in ESTIMATE command.\n");
	return;
    }

    /* Check if we've met this species. */
    contact_word_number = (g_spec_number - 1) / 32;
    contact_bit_number = (g_spec_number - 1) % 32;
    contact_mask = 1 << contact_bit_number;
    if ((species->contact[contact_word_number] & contact_mask)  ==  0)
    {
	fprintf (log_file, "!!! Order ignored:\n");
	fprintf (log_file, "!!! %s", input_line);
	fprintf (log_file, "!!! You can't do an estimate of a species you haven't met.\n");
	return;
    }

    /* Check if sufficient funds are available. */
    cost = 25;
    if (check_bounced (cost))
    {
	fprintf (log_file, "!!! Order ignored:\n");
	fprintf (log_file, "!!! %s", input_line);
	fprintf (log_file, "!!! Insufficient funds to execute order.\n");
	return;
    }

    /* Log the result. */
    if (first_pass)
    {
	log_string ("    An estimate of the technology of SP ");
	log_string (g_spec_name);
	log_string (" was made at a cost of ");
	log_long (cost);
	log_string (".\n");
	return;
    }

    /* Make the estimates. */
    alien = &spec_data[g_spec_number - 1];
    for (i = 0; i < 6; i++)
    {
	max_error = (int) alien->tech_level[i] - (int) species->tech_level[i];
	if (max_error < 1) max_error = 1;
	estimate[i] = (int) alien->tech_level[i] + rnd((2 * max_error) + 1)
		- (max_error + 1);
	if (alien->tech_level[i] == 0) estimate[i] = 0;
	if (estimate[i] < 0) estimate[i] = 0;
    }

    log_string ("    Estimate of the technology of SP ");
    log_string (alien->name);
    log_string (" (government name '");
    log_string (alien->govt_name);
    log_string ("', government type '");
    log_string (alien->govt_type);
    log_string ("'):\n      MI = ");   log_int (estimate[MI]);
    log_string (", MA = ");   log_int (estimate[MA]);
    log_string (", ML = ");   log_int (estimate[ML]);
    log_string (", GV = ");   log_int (estimate[GV]);
    log_string (", LS = ");   log_int (estimate[LS]);
    log_string (", BI = ");   log_int (estimate[BI]);
    log_string (".\n");
}
Exemple #16
0
void RubyConfig::init()
{
  // MemoryControl:
  CHECK_NON_ZERO(MEM_BUS_CYCLE_MULTIPLIER);
  CHECK_NON_ZERO(BANKS_PER_RANK);
  CHECK_NON_ZERO(RANKS_PER_DIMM);
  CHECK_NON_ZERO(DIMMS_PER_CHANNEL);
  CHECK_NON_ZERO(BANK_QUEUE_SIZE);
  CHECK_NON_ZERO(BANK_BUSY_TIME);
  CHECK_NON_ZERO(MEM_CTL_LATENCY);
  CHECK_NON_ZERO(REFRESH_PERIOD);
  CHECK_NON_ZERO(BASIC_BUS_BUSY_TIME);

  CHECK_POWER_OF_2(BANKS_PER_RANK);
  CHECK_POWER_OF_2(RANKS_PER_DIMM);
  CHECK_POWER_OF_2(DIMMS_PER_CHANNEL);

  CHECK_NON_ZERO(g_MEMORY_SIZE_BYTES);
  CHECK_NON_ZERO(g_DATA_BLOCK_BYTES);
  CHECK_NON_ZERO(g_PAGE_SIZE_BYTES);
  CHECK_NON_ZERO(g_NUM_PROCESSORS);
  CHECK_NON_ZERO(g_PROCS_PER_CHIP);
  if(g_NUM_SMT_THREADS == 0){ //defaults to single-threaded
    g_NUM_SMT_THREADS = 1;
  }
  if (g_NUM_L2_BANKS == 0) {  // defaults to number of ruby nodes
    g_NUM_L2_BANKS = g_NUM_PROCESSORS;
  }
  if (g_NUM_MEMORIES == 0) {  // defaults to number of ruby nodes
    g_NUM_MEMORIES = g_NUM_PROCESSORS;
  }

  CHECK_ZERO(g_MEMORY_SIZE_BITS);
  CHECK_ZERO(g_DATA_BLOCK_BITS);
  CHECK_ZERO(g_PAGE_SIZE_BITS);
  CHECK_ZERO(g_NUM_PROCESSORS_BITS);
  CHECK_ZERO(g_NUM_CHIP_BITS);
  CHECK_ZERO(g_NUM_L2_BANKS_BITS);
  CHECK_ZERO(g_NUM_MEMORIES_BITS);
  CHECK_ZERO(g_PROCS_PER_CHIP_BITS);
  CHECK_ZERO(g_NUM_L2_BANKS_PER_CHIP);
  CHECK_ZERO(g_NUM_L2_BANKS_PER_CHIP_BITS);
  CHECK_ZERO(g_NUM_MEMORIES_BITS);
  CHECK_ZERO(g_MEMORY_MODULE_BLOCKS);
  CHECK_ZERO(g_MEMORY_MODULE_BITS);
  CHECK_ZERO(g_NUM_MEMORIES_PER_CHIP);

  CHECK_POWER_OF_2(g_MEMORY_SIZE_BYTES);
  CHECK_POWER_OF_2(g_DATA_BLOCK_BYTES);
  CHECK_POWER_OF_2(g_NUM_PROCESSORS);
  CHECK_POWER_OF_2(g_NUM_L2_BANKS);
  CHECK_POWER_OF_2(g_NUM_MEMORIES);
  CHECK_POWER_OF_2(g_PROCS_PER_CHIP);

  ASSERT(g_NUM_PROCESSORS >= g_PROCS_PER_CHIP);  // obviously can't have less processors than procs/chip
  g_NUM_CHIPS = g_NUM_PROCESSORS/g_PROCS_PER_CHIP;
  ASSERT(g_NUM_L2_BANKS >= g_NUM_CHIPS);  // cannot have a single L2cache across multiple chips
  
  g_NUM_L2_BANKS_PER_CHIP = g_NUM_L2_BANKS/g_NUM_CHIPS;

  ASSERT(L2_CACHE_NUM_SETS_BITS > log_int(g_NUM_L2_BANKS_PER_CHIP));  // cannot have less than one set per bank
  L2_CACHE_NUM_SETS_BITS = L2_CACHE_NUM_SETS_BITS - log_int(g_NUM_L2_BANKS_PER_CHIP);

  if (g_NUM_CHIPS > g_NUM_MEMORIES) {
    g_NUM_MEMORIES_PER_CHIP = 1;  // some chips have a memory, others don't
  } else {
    g_NUM_MEMORIES_PER_CHIP = g_NUM_MEMORIES/g_NUM_CHIPS;
  }

  g_NUM_CHIP_BITS = log_int(g_NUM_CHIPS);
  g_MEMORY_SIZE_BITS = log_int(g_MEMORY_SIZE_BYTES);
  g_DATA_BLOCK_BITS = log_int(g_DATA_BLOCK_BYTES);
  g_PAGE_SIZE_BITS = log_int(g_PAGE_SIZE_BYTES);
  g_NUM_PROCESSORS_BITS = log_int(g_NUM_PROCESSORS);
  g_NUM_L2_BANKS_BITS = log_int(g_NUM_L2_BANKS);
  g_NUM_L2_BANKS_PER_CHIP_BITS = log_int(g_NUM_L2_BANKS_PER_CHIP);  
  g_NUM_MEMORIES_BITS = log_int(g_NUM_MEMORIES);
  g_PROCS_PER_CHIP_BITS = log_int(g_PROCS_PER_CHIP);

  g_MEMORY_MODULE_BITS = g_MEMORY_SIZE_BITS - g_DATA_BLOCK_BITS - g_NUM_MEMORIES_BITS;
  g_MEMORY_MODULE_BLOCKS = (int64(1) << g_MEMORY_MODULE_BITS);

  if ((!Protocol::m_CMP) && (g_PROCS_PER_CHIP > 1)) {
    ERROR_MSG("Non-CMP protocol should set g_PROCS_PER_CHIP to 1");
  }

  // Randomize the execution
  srandom(g_RANDOM_SEED);
}
Exemple #17
0
void TopologyFatTree::buildTopology(int num_way)
{
    assert(is_power2(g_cfg.core_num));
    assert(is_power2(num_way));

    m_num_way = num_way;
    m_max_level = log_int(g_cfg.core_num, m_num_way);
  
    m_num_router_per_level = g_cfg.core_num/m_num_way;
    fprintf(stderr, "[Fat Tree] m_num_way=%d m_max_level=%d\n", m_num_way, m_max_level);
    fprintf(stderr, "[Fat Tree] m_num_router_per_level=%d\n", m_num_router_per_level);

    // check relationship between #cores and #routers.
    if (g_cfg.router_num != m_num_router_per_level*m_max_level) {
        fprintf(stderr, "[Fat Tree] g_cfg.core_num=%d g_cfg.router_num=%d #routers_required=%d\n",
               g_cfg.core_num, g_cfg.router_num, m_num_router_per_level*m_max_level);
        g_cfg.router_num = m_num_router_per_level*m_max_level;
        fprintf(stderr, "[Fat Tree] We changed g_cfg.router_num=%d.\n", g_cfg.router_num);
    }

    // topology name
    m_topology_name = int2str(m_num_way) + "-way Fat Tree";

    // create cores
    for (int n=0; n<g_cfg.core_num; n++) {
        Core* p_Core = new Core(n, g_cfg.core_num_NIs);
        g_Core_vec.push_back(p_Core);
    }

    // create routers
    unsigned int router_id = 0;
    for (int l=0; l<m_max_level; l++) {
        for (int w=0; w<m_num_router_per_level; w++) {
            int router_num_pc;
            int router_num_ipc, router_num_epc;

            if (l == 0) {	// 0-level(external) router
                router_num_epc = router_num_ipc = (m_num_way * g_cfg.core_num_NIs);
                router_num_pc = m_num_way + router_num_epc;
            } else {	// internal-level router
                router_num_epc = router_num_ipc = 0;
                router_num_pc = m_num_way * 2;
            }

            Router* pRouter = new Router(router_id, router_num_pc, g_cfg.router_num_vc,
                                         router_num_ipc, router_num_epc, g_cfg.router_inbuf_depth);
#ifdef  _DEBUG_TOPOLOGY_FTREE
printf("[Fat Tree] router=%d level=%d num_pc=%d num_ipc=%d num_epc=%d\n", pRouter->id(), l, router_num_pc, router_num_ipc, router_num_epc);
#endif
            g_Router_vec.push_back(pRouter);
            router_id++;
        }
    }
#ifdef  _DEBUG_TOPOLOGY_FTREE
printf("[Fat Tree] # of created routers=%d\n", g_Router_vec.size());
#endif

    // core and router connection
    int num_cores_in_dim = (int)sqrt(g_cfg.core_num);
    int num_routers_in_dim = (int)sqrt(m_num_router_per_level);
    // printf("num_cores_in_dim = %d, num_routers_in_dim = %d.\n", num_cores_in_dim, num_routers_in_dim);
    for(int n=0; n<m_num_router_per_level; n++){
        int router_x_coord = n % num_routers_in_dim;
        int router_y_coord = n / num_routers_in_dim;

        // FIXME: support only 4-way fat-trees
        vector< int > core_id_vec;
        core_id_vec.resize(m_num_way);
        core_id_vec[0] = 2 * router_x_coord + 2 * num_cores_in_dim * router_y_coord;
        core_id_vec[1] = core_id_vec[0] + 1;
        core_id_vec[2] = core_id_vec[0] + num_cores_in_dim;
        core_id_vec[3] = core_id_vec[2] + 1;

        // core to router map: core_id -> (router_id, port_pos (relative))
        m_core2router_map[core_id_vec[0]] = make_pair(n, 0);
        m_core2router_map[core_id_vec[1]] = make_pair(n, 1);
        m_core2router_map[core_id_vec[2]] = make_pair(n, 2);
        m_core2router_map[core_id_vec[3]] = make_pair(n, 3);

        // router to core map: (router_id, port_pos (relative)) -> core_id
        m_router2core_map[make_pair(n, 0)] = core_id_vec[0];
        m_router2core_map[make_pair(n, 1)] = core_id_vec[1];
        m_router2core_map[make_pair(n, 2)] = core_id_vec[2];
        m_router2core_map[make_pair(n, 3)] = core_id_vec[3];

#ifdef  _DEBUG_TOPOLOGY_FTREE
printf(" router_id=%d first_core=%d second_core=%d third_core=%d fourth_core=%d\n", n, core_id_vec[0], core_id_vec[1], core_id_vec[2], core_id_vec[3]); 
#endif

        for (int w=0; w<m_num_way; w++) {
            Core * p_Core = g_Core_vec[core_id_vec[w]];
            Router * p_Router = g_Router_vec[n];

            // map PCs between input-NI and router
            for (int ipc=0; ipc<g_cfg.core_num_NIs; ipc++) {
                int router_in_pc = p_Router->num_internal_pc() + w * g_cfg.core_num_NIs + ipc;
                p_Core->getNIInput(ipc)->attachRouter(p_Router, router_in_pc);
                p_Router->appendNIInput(p_Core->getNIInput(ipc));
            }
            // map PCs between output-NI and router
            for (int epc=0; epc<g_cfg.core_num_NIs; epc++) {
                int router_out_pc = p_Router->num_internal_pc() + w * g_cfg.core_num_NIs + epc;
                p_Core->getNIOutput(epc)->attachRouter(p_Router, router_out_pc);
                p_Router->appendNIOutput(p_Core->getNIOutput(epc)); 
            }
        }
    }

    // setup link configuration
    for (unsigned int i=0; i<g_Router_vec.size(); i++) {
        Router* p_router = g_Router_vec[i];
        int router_tree_level = getTreeLevel(p_router);

        for (int out_pc=0; out_pc<p_router->num_pc(); out_pc++) {
            Link& link = p_router->getLink(out_pc);
            link.m_valid = true;

            if (router_tree_level == 0) {	// external routers
                if (out_pc < p_router->num_internal_pc()) {
                    // up link
                    link.m_link_name = "U" + int2str(out_pc);
                    link.m_length_mm *= pow(2.0, (double) (router_tree_level+1));
                    link.m_delay_factor *= 2;
                } else {
                    // link for core
                    int attached_core_id = p_router->id() * m_num_way + (out_pc - p_router->num_internal_pc())/g_cfg.core_num_NIs;
                    link.m_link_name = "C" + int2str(attached_core_id) + "-P" + int2str((out_pc - p_router->num_internal_pc())%g_cfg.core_num_NIs);
                    link.m_length_mm = 0.0;
                }
            } else {	// internal routers
                if (out_pc < p_router->num_pc()/2) {
                    // up link
                    if (router_tree_level < m_max_level-1) {
                        link.m_link_name = "U" + int2str(out_pc);
                        link.m_length_mm *= pow(2.0, (double) (router_tree_level+1));
                        link.m_delay_factor *= pow_int(2, router_tree_level+1);
                    } else {
                        link.m_valid = false;
                    }
                } else {
                    // down link
                    link.m_link_name = "D" + int2str(out_pc - p_router->num_pc()/2);
                    link.m_length_mm *= pow(2.0, (double) (router_tree_level+0));
                    link.m_delay_factor *= pow_int(2, router_tree_level);
                }
            }
        }
    }

    // setup routers
    for (int r=0; r<g_cfg.router_num; r++) {
        Router * p_router = g_Router_vec[r];
        int num_pc = p_router->num_pc();
        int num_internal_pc = p_router->num_internal_pc();
        int level = getTreeLevel(p_router);
        if (level == 0) {//level 0, only need to setup UP connection
            vector< pair< int, int > > connNextRouter_vec;
            connNextRouter_vec.resize(num_pc);
            vector< pair< int, int > > connPrevRouter_vec;
            connPrevRouter_vec.resize(num_pc);
            //UP
            for (int out_pc=0; out_pc<num_pc; out_pc++) {
                int next_router_id;
                int next_in_pc;

                if (out_pc >= num_internal_pc) { // ejection pc ?
                    next_router_id = INVALID_ROUTER_ID;
                    next_in_pc = DIR_INVALID;
                } else { // internal pc
                    int up_router_id_scale = (int)pow((double)m_num_way,(double)(level+1));
                    int up_router_id_base = ((p_router->id() % m_num_router_per_level) / up_router_id_scale) * up_router_id_scale + m_num_router_per_level * (level+1);

                    next_router_id = m_num_router_per_level + p_router->id() + out_pc*(int)pow((double)m_num_way, (double)level);
                    if (next_router_id >= (up_router_id_base + up_router_id_scale))
                        next_router_id -= up_router_id_scale;
                    next_in_pc = g_Router_vec[next_router_id]->num_internal_pc()/2 + out_pc;
                }
                connNextRouter_vec[out_pc] = make_pair(next_router_id, next_in_pc);
                connPrevRouter_vec[out_pc] = make_pair(next_router_id, next_in_pc);
            }//pc
            g_Router_vec[r]->setNextRouters(connNextRouter_vec);
            g_Router_vec[r]->setPrevRouters(connPrevRouter_vec);
        } else if (level>0 && level< m_max_level-1) {// need to setup UP and DOWN connection
            //for internal router, num_pc = num_internal_pc
            //don't need to separate set ejection pc connection
            vector< pair< int, int > > connNextRouter_vec;
            connNextRouter_vec.resize(num_pc);
            vector< pair< int, int > > connPrevRouter_vec;
            connPrevRouter_vec.resize(num_pc);
            //UP 
            for (int out_pc=0; out_pc<num_internal_pc/2; out_pc++){
                int next_router_id;
                int next_in_pc;

                int up_router_id_scale = (int)pow((double)m_num_way,(double)(level+1));
                int up_router_id_base = ((p_router->id() % m_num_router_per_level) / up_router_id_scale) * up_router_id_scale + m_num_router_per_level * (level+1);

                next_router_id = m_num_router_per_level + p_router->id() + out_pc*(int)pow((double)m_num_way, (double)level);
                if (next_router_id >= (up_router_id_base + up_router_id_scale))
                    next_router_id -= up_router_id_scale;
                next_in_pc = g_Router_vec[next_router_id]->num_internal_pc()/2 + out_pc;
                connNextRouter_vec[out_pc] = make_pair(next_router_id, next_in_pc);
                connPrevRouter_vec[out_pc] = make_pair(next_router_id, next_in_pc);
            }//pc
            //DOWN
            for (int out_pc=num_internal_pc/2; out_pc<num_internal_pc; out_pc++){
                // out_pc in for in just used for index, not the real out pc which will be set.
                int next_router_id = INVALID_ROUTER_ID;
                int next_in_pc = INVALID_PC;
                int real_out_pc = INVALID_PC;//this is the real out pc which will be set.
 
                int down_router_id_scale = (int)pow((double)m_num_way,(double)level);
                int down_router_id_base = ((p_router->id() % m_num_router_per_level) / down_router_id_scale) * down_router_id_scale + m_num_router_per_level * (level-1);

                next_router_id = p_router->id() - m_num_router_per_level + (out_pc - num_internal_pc/2) * (int)pow((double)m_num_way, (double)(level-1));
                if (next_router_id >= (down_router_id_base + down_router_id_scale))
                    next_router_id -= down_router_id_scale;
             
                Router * p_next_router = g_Router_vec[next_router_id];
             
                for ( vector< pair< int, int > >::iterator iter= p_next_router->nextRouters().begin(); iter<p_next_router->nextRouters().begin()+num_internal_pc/2; iter++){//find the proper down_router_id and in_pc
                    if((*iter).first == p_router->id()){//find the correct one
                        real_out_pc = (*iter).second;
                        next_in_pc = real_out_pc - num_internal_pc/2;
                        break;
                    }
                }  

                connNextRouter_vec[real_out_pc] = make_pair(next_router_id, next_in_pc);
                connPrevRouter_vec[real_out_pc] = make_pair(next_router_id, next_in_pc);
            }//pc
            g_Router_vec[r]->setNextRouters(connNextRouter_vec);
            g_Router_vec[r]->setPrevRouters(connPrevRouter_vec);
        }// internal level 
        else {
            vector< pair< int, int > > connNextRouter_vec;
            connNextRouter_vec.resize(num_internal_pc);
            vector< pair< int, int > > connPrevRouter_vec;
            connPrevRouter_vec.resize(num_internal_pc);
            //DOWN
            //UP set as invalid 
            for (int out_pc=0; out_pc<num_internal_pc; out_pc++) {
                int next_router_id = INVALID_ROUTER_ID;
                int next_in_pc = INVALID_PC;
                if ( out_pc < num_internal_pc/2){//up
                    next_router_id = INVALID_ROUTER_ID;
                    next_in_pc = DIR_INVALID;
                    connNextRouter_vec[out_pc] = make_pair(next_router_id, next_in_pc);
                    connPrevRouter_vec[out_pc] = make_pair(next_router_id, next_in_pc);
                } else{//down
                    int real_out_pc = INVALID_PC;//this is the real out pc which will be set.

                    int down_router_id_scale = (int)pow((double)m_num_way,(double)level);
                    int down_router_id_base = ((p_router->id() % m_num_router_per_level) / down_router_id_scale) * down_router_id_scale + m_num_router_per_level * (level-1);

                    next_router_id = p_router->id() - m_num_router_per_level + (out_pc - num_internal_pc/2) * (int)pow((double)m_num_way, (double)(level-1));
                    if (next_router_id >= (down_router_id_base + down_router_id_scale))
                        next_router_id -= down_router_id_scale;

                    Router * p_next_router = g_Router_vec[next_router_id];

                    for ( vector< pair< int, int > >::iterator iter= p_next_router->nextRouters().begin(); iter<p_next_router->nextRouters().begin()+num_internal_pc/2; iter++){//find the proper down_router_id and in_pc
                        if((*iter).first == p_router->id()){//find the correct one
                            real_out_pc = (*iter).second;
                            next_in_pc = real_out_pc - num_internal_pc/2;
                            break;
                        }
                    }

                    connNextRouter_vec[real_out_pc] = make_pair(next_router_id, next_in_pc);
                    connPrevRouter_vec[real_out_pc] = make_pair(next_router_id, next_in_pc);
                }
            }//pc
            g_Router_vec[r]->setNextRouters(connNextRouter_vec);
            g_Router_vec[r]->setPrevRouters(connPrevRouter_vec);
        }// top level 
    }//router 
}