void pgCamera::Update()
{
	if (ApConfig::IsWin())
	{
		static BtBool isLoaded = BtFalse;
		if (isLoaded == BtFalse)
		{
			// If we have a previously saved version of the camera then load
			FsFile file;
			BtChar filename[64];
			sprintf(filename, "%s%s", ApConfig::GetDocuments(), "camera.txt");
			file.Open(filename, FsMode_Read);
			if (file.IsOpen())
			{
				file.Read(m_cameraData);
				file.Close();
			}
			isLoaded = BtTrue;
		}
	}

	if (UiKeyboard::pInstance()->IsPressed(UiKeyCode_F3))
	{
		m_isFlyCam = !m_isFlyCam;
	}


	for (BtU32 i = 1; i < MaxTouches; i += 2)
	{
		if (ShTouch::IsHeld(i) || m_isFlyCam)
		{
			BtFloat speed = BtTime::GetTick() * 10.0f;

			if (UiKeyboard::pInstance()->IsHeld(UiKeyCode_LSHIFT))
			{
				speed = speed * 10.0f;
			}
			if (UiKeyboard::pInstance()->IsHeld(UiKeyCode_W))
			{
				MoveForward(speed);
			}
			if (UiKeyboard::pInstance()->IsHeld(UiKeyCode_S))
			{
				MoveBackward(speed);
			}
			if (UiKeyboard::pInstance()->IsHeld(UiKeyCode_D))
			{
				MoveRight(speed);
			}
			if (UiKeyboard::pInstance()->IsHeld(UiKeyCode_A))
			{
				MoveLeft(speed);
			}
		}
	}


	if (ShTouch::IsHeld(1))
	{
        BtBool onScreen = BtTrue;//ShTouch::OnScreen(1);
		if (onScreen)
		{
			for (BtU32 i = 0; i < MaxTouches; i += 2)
			{
				// Rotate the camera
				MtVector2 v2MouseDirection = ShTouch::GetMovement(i);
				BtFloat speed = BtTime::GetTick() * 0.1f;
				MtMatrix3 m3Rotate;
				m3Rotate.SetRotationY(v2MouseDirection.x * -speed);
				m_cameraData.m_m3Rotation = m3Rotate * m_cameraData.m_m3Rotation;
				m3Rotate.SetRotationX(v2MouseDirection.y * speed);
				m_cameraData.m_m3Rotation = m_cameraData.m_m3Rotation * m3Rotate;
			}
		}
	}

	static BtBool isCursorKeys = BtFalse;

	// Rotate the camera
	BtFloat speed = BtTime::GetTick();

	if (UiKeyboard::pInstance()->IsHeld(UiKeyCode_LSHIFT))
	{
		if (UiKeyboard::pInstance()->IsHeld(UiKeyCode_LEFT))
		{
			isCursorKeys = BtTrue;
			m_cameraData.m_yaw += speed;
		}
		if (UiKeyboard::pInstance()->IsHeld(UiKeyCode_RIGHT))
		{
			isCursorKeys = BtTrue;
			m_cameraData.m_yaw -= speed;
		}
		if (UiKeyboard::pInstance()->IsHeld(UiKeyCode_UP))
		{
			isCursorKeys = BtTrue;
			m_cameraData.m_pitch -= speed;
		}
		if (UiKeyboard::pInstance()->IsHeld(UiKeyCode_DOWN))
		{
			isCursorKeys = BtTrue;
			m_cameraData.m_pitch += speed;
		}
	}

	if (!ApConfig::IsWin())
	{
		// Support a landscape quaternion
		MtMatrix3 m_m3Rotation;
		MtQuaternion quaternion = ShIMU::GetQuaternion(0);
		quaternion.x = quaternion.x;
		quaternion.y = quaternion.y;
		quaternion.z = -quaternion.z;

		m_m3Rotation = MtMatrix3(quaternion);
		//m_m3Rotation = m_m3Rotation.GetInverse();

		MtMatrix3 m3RotateY;
		m3RotateY.SetRotationY(MtDegreesToRadians(90.0f));

		MtMatrix3 m3RotateZ;
		m3RotateZ.SetRotationZ(MtDegreesToRadians(-90.0f));

		m_m3Rotation = m3RotateY * m_m3Rotation;
		m_m3Rotation = m3RotateZ * m_m3Rotation;
		m_m3Rotation = m_m3Rotation * m3RotateZ;

		m_camera.SetRotation(m_m3Rotation);

	}
	else if (ShHMD::IsHMD())
	{
		MtMatrix3 m3RotateY;
		m3RotateY.SetRotationX(m_cameraData.m_pitch);
		MtMatrix3 m3RotateX;
		m3RotateX.SetRotationY(m_cameraData.m_yaw);
		m_cameraData.m_m3Rotation = m3RotateX * m3RotateY;

		// Cache the ShHMD rotation
		MtQuaternion quaternion = ShHMD::GetQuaternion();

		// Set the IMU rotation
		MtMatrix4 m4FinalRotation = m_cameraData.m_m3Rotation * MtMatrix3(quaternion);

		// Set the rotation
		m_camera.SetRotation(m4FinalRotation);
	}
	else
	{
		if (isCursorKeys)
		{
			MtMatrix3 m3RotateY;
			m3RotateY.SetRotationX(m_cameraData.m_pitch);
			MtMatrix3 m3RotateX;
			m3RotateX.SetRotationY(m_cameraData.m_yaw);
			m_cameraData.m_m3Rotation = m3RotateX * m3RotateY;
		}

		// Set the rotation
		m_camera.SetRotation(m_cameraData.m_m3Rotation);
	}

	// Set the position
	m_camera.SetPosition(m_cameraData.m_v3Position);

	// Update the camera
	m_camera.Update();

	if (UiKeyboard::pInstance()->IsPressed(SaveCameraKey))
	{
		FsFile file;
		BtChar filename[64];
		sprintf(filename, "%s%s", ApConfig::GetDocuments(), "camera.txt");
		file.Open(filename, FsMode_Write);
		if (file.IsOpen())
		{
			file.Write(m_cameraData);
			file.Close();
		}
	}
}
Exemple #2
0
//Scenario pour 0 capteurs activés---------------------------------------
void ScenarioFor0Sensors()
{
	MoveForward();
}
Exemple #3
0
//Scenario pour 2 capteurs activés---------------------------------------
void ScenarioFor2Sensors(int tab[])
{
	//On cherche à savoir quels capteurs ont été activés en parcourant la liste des elements de tab[]
	int ind1 = -1;
	int ind2 = -1;
	for (int i=0; i<NBR_CAPT;i++) {
		if (tab[i]==1) {
			if (ind1!=-1) ind2=i;		//Si ind1 n'a plus sa valeur par defaut, alors c'est qu'il a été alimenté, donc on peut alimenter ind2
			else ind1=i;		//Sinon on alimente ind1;
		}
	}
	/*
	 * cf. GetSensorValues()
	 * Indice 0 --> CAPT_A
	 * Indice 1 --> CAPT_B
	 * Indice 2 --> CAPT_C
	 * Indice 3 --> CAPT_D
	 * Indice 4 --> CAPT_E
	 * Indice 5 --> CAPT_F
	 * Indice 6 --> CAPT_G
	 * Indice 7 --> CAPT_H
	*/

	if ((ind1==0 && ind2==1) || (ind1==0 && ind2==2) || (ind1==1 && ind2==7)) {
		Stop();		//On stoppe le bateau
		TurnOnLeft(3*DELAY_ROT);		//On tourne à babord de 135°
		MoveForward(); _delay_ms(DELAY_ECHAP);		//On s'échappe pendant un temps
		Stop();		//On stoppe à nouveau le bateau
		TurnOnRight(3*DELAY_ROT);		//On se remet en position initiale
		MoveForward();		//Et on repart...
	}

	else if ((ind1==1 && ind2==2) || (ind1==1 && ind2==3)) {
		Stop();		//On stoppe le bateau
		TurnOnLeft(2*DELAY_ROT);		//On tourne à babord de 90°
		MoveForward(); _delay_ms(DELAY_ECHAP);		//On s'échappe pendant un temps
		Stop();		//On stoppe à nouveau le bateau
		TurnOnRight(2*DELAY_ROT);		//On se remet en position initiale
		MoveForward();		//Et on repart...
	}

	else if ((ind1==2 && ind2==3) || (ind1==2 && ind2==4)) {
		Stop();		//On stoppe le bateau
		TurnOnLeft(1*DELAY_ROT);		//On tourne à babord de 45°
		MoveForward(); _delay_ms(DELAY_ECHAP);		//On s'échappe pendant un temps
		Stop();		//On stoppe à nouveau le bateau
		TurnOnRight(1*DELAY_ROT);		//On se remet en position initiale
		MoveForward();		//Et on repart...
	}

	else if ((ind1==0 && ind2==7) || (ind1==0 && ind2==6)) {
		Stop();		//On stoppe le bateau
		TurnOnRight(3*DELAY_ROT);		//On tourne à tribord de 135°
		MoveForward(); _delay_ms(DELAY_ECHAP);		//On s'échappe pendant un temps
		Stop();		//On stoppe à nouveau le bateau
		TurnOnLeft(3*DELAY_ROT);		//On se remet en position initiale
		MoveForward();		//Et on repart...
	}

	else if ((ind1==5 && ind2==7) || (ind1==6 && ind2==7)) {
		Stop();		//On stoppe le bateau
		TurnOnRight(2*DELAY_ROT);		//On tourne à tribord de 90°
		MoveForward(); _delay_ms(DELAY_ECHAP);		//On s'échappe pendant un temps
		Stop();		//On stoppe à nouveau le bateau
		TurnOnLeft(2*DELAY_ROT);		//On se remet en position initiale
		MoveForward();		//Et on repart...
	}

	else if ((ind1==5 && ind2==6) || (ind1==4 && ind2==6)) {
		Stop();		//On stoppe le bateau
		TurnOnRight(1*DELAY_ROT);		//On tourne à tribord de 45°
		MoveForward(); _delay_ms(DELAY_ECHAP);		//On s'échappe pendant un temps
		Stop();		//On stoppe à nouveau le bateau
		TurnOnLeft(1*DELAY_ROT);		//On se remet en position initiale
		MoveForward();		//Et on repart...
	}
}
Exemple #4
0
int cCamera::Control()
{
    if(m_Number != CurrCamera) return -1;


#ifndef DIMENSION_3D // 2D
    /* 상하좌우 이동 */
    float Speed = VFR(0.05f);

    if(cCore::Input.KeyPress('W'))
    {
        AddEyePt(0.f, Speed, 0.f);
        AddLookAt(0.f, Speed, 0.f);
    }
    else if(cCore::Input.KeyPress('S'))
    {
        AddEyePt(0.f, -Speed, 0.f);
        AddLookAt(0.f, -Speed, 0.f);
    }

    if(cCore::Input.KeyPress('A'))
    {
        AddEyePt(-Speed, 0.f, 0.f);
        AddLookAt(-Speed, 0.f, 0.f);
    }
    else if(cCore::Input.KeyPress('D'))
    {
        AddEyePt(Speed, 0.f, 0.f);
        AddLookAt(Speed, 0.f, 0.f);
    }
#else
#ifdef VIEW_3D
    /* 마우스 좌클릭 드래그로 카메라 회전 */
    if(cCore::Input.MousePress(VK_LBUTTON))
    {
#ifdef NOTUSE_VFR
        Rotation(VFR(+0.2f));
#else
        Rotation(VFR(+0.2f));
#endif
    }


    /* 쉬프트키와 스페이스키로 위아래 이동 */
    if(cCore::Input.KeyPress(VK_LSHIFT))
    {
        AddEyePt(0, VFR(-0.2f), 0);
        AddLookAt(0, VFR(-0.2f), 0);
    }
    else if(cCore::Input.KeyPress(VK_SPACE))
    {
        AddEyePt(0, VFR(0.2f), 0);
        AddLookAt(0, VFR(0.2f), 0);
    }


    /* 카메라가 보는 방향을 기준으로 앞, 뒤, 옆으로 이동 */
    if(cCore::Input.KeyPress('W'))
    {
        MoveForward(VFR(+0.2f));
    }
    else if(cCore::Input.KeyPress('S'))
    {
        MoveBackward(VFR(0.2f));
    }

    if(cCore::Input.KeyPress('A'))
    {
        MoveSideward(VFR(-0.1f));
    }
    else if(cCore::Input.KeyPress('D'))
    {
        MoveSideward(VFR(+0.1f));
    }


    /* 카메라가 보는곳을 중심으로 회전 */
    if(cCore::Input.KeyPress('Q'))
    {
        MoveSideward(VFR(-0.2f), false);
    }
    else if(cCore::Input.KeyPress('E'))
    {
        MoveSideward(VFR(+0.2f), false);
    }
#else
    /* 상하좌우 이동 */
    float Speed = VFR(0.05f);

    if(cCore::Input.KeyPress('W'))
    {
        AddEyePt(Speed, 0.f, Speed);
        AddLookAt(Speed, 0.f, Speed);
    }
    else if(cCore::Input.KeyPress('S'))
    {
        AddEyePt(-Speed, 0.f, -Speed);
        AddLookAt(-Speed, 0.f, -Speed);
    }

    if(cCore::Input.KeyPress('A'))
    {
        AddEyePt(-Speed, 0.f, Speed);
        AddLookAt(-Speed, 0.f, Speed);
    }
    else if(cCore::Input.KeyPress('D'))
    {
        AddEyePt(Speed, 0.f, -Speed);
        AddLookAt(Speed, 0.f, -Speed);
    }
#endif
#endif


    return 0;
}
Exemple #5
0
	void Mouse::Explore()
	{
		std::unique_ptr<Path_new> * path_chosen;

		// Turn to face a direction where there's actually an opening
		// Start off going forward once, set previous to start
		MoveForward();

		maze->printClean();
		maze->printMaze(true);
		maze->printClean();
		
		while (true)
		{
			// Delay *******************************************************
			std::this_thread::sleep_until(
				std::chrono::system_clock::now() + std::chrono::seconds(1));
			// *************************************************************

			// Get sensor data
			this->sensor->sense(maze.get());

			// Check to see if there's more than one new path in the current physical room
			switch (CheckForOptions())
			{
			// dead end
			case 0:	
				TurnAround();
				// Reverse backtracking variable
				backtracking ? backtracking = false : backtracking = true;
				MoveForward();
				break;

			// only one option
			case 1:	
				// Get the next cell to turn to as there's only one option 
				Turn(currentRoom->get_children(previousRoom)->front());
				MoveForward();
				break;

			// 2 or 3 options in direction
			case 2:	
			case 3:
				if (!backtracking)
				{
					// Guess all the possible paths from the current "cross-roads"
					path_chosen = Evaluate();

					// Get the next room from the new completePathGuess, aka path_chosen
					delete(completePathGuess);
					completePathGuess = path_chosen->get();
					Room * nextr = completePathGuess->Rooms()->at(actualPath->Rooms()->size());

					// Start down the new path
					Turn(nextr);
					MoveForward();
				}
				else
				{
					// backtracking

					// Choose the room with the least visits, avoiding going back down the previous path
					Room * nextr = Filter::LeastVisited(currentRoom->get_children(previousRoom));
					
					if (!actualPath->Contains(nextr->Location().x, nextr->Location().y))
					{
						// change back to regular advancements
						backtracking = false;
					}
					
					// Start down path
					Turn(nextr);
					MoveForward();
				}
				break;
			}

			maze->printClean();
			maze->printMaze(true);
			maze->printClean();
		}

	}
Exemple #6
0
void Game_Character::MoveTypeCustom() {
	// Detect if custom movement or event overwrite
	const RPG::MoveRoute* active_route;
	int active_route_index;
	bool overwrite_changed = IsMoveRouteOverwritten();
	if (IsMoveRouteOverwritten()) {
		active_route = &GetMoveRoute();
		active_route_index = GetMoveRouteIndex();
	}
	else {
		active_route = &original_move_route;
		active_route_index = GetOriginalMoveRouteIndex();
	}

	if (IsStopping()) {
		move_failed = false;
		if ((size_t)active_route_index >= active_route->move_commands.size()) {
			// End of Move list
			if (active_route->repeat) {
				active_route_index = 0;
				SetMoveRouteRepeated(true);
			} else if (IsMoveRouteOverwritten()) {
				SetMoveRouteOverwritten(false);
				EndMoveRoute();
				stop_count = 0;
			}
		} else {
			do {
				const RPG::MoveCommand& move_command = active_route->move_commands[active_route_index];

				int command_id = move_command.command_id;
				if (!jumping && command_id == RPG::MoveCommand::Code::begin_jump) {
					active_route_index = BeginJump(active_route, active_route_index);
				}

				switch (move_command.command_id) {
				case RPG::MoveCommand::Code::move_up:
					MoveUp();
					break;
				case RPG::MoveCommand::Code::move_right:
					MoveRight();
					break;
				case RPG::MoveCommand::Code::move_down:
					MoveDown();
					break;
				case RPG::MoveCommand::Code::move_left:
					MoveLeft();
					break;
				case RPG::MoveCommand::Code::move_upright:
					MoveUpRight();
					break;
				case RPG::MoveCommand::Code::move_downright:
					MoveDownRight();
					break;
				case RPG::MoveCommand::Code::move_downleft:
					MoveDownLeft();
					break;
				case RPG::MoveCommand::Code::move_upleft:
					MoveUpLeft();
					break;
				case RPG::MoveCommand::Code::move_random:
					MoveRandom();
					break;
				case RPG::MoveCommand::Code::move_towards_hero:
					MoveTowardsPlayer();
					break;
				case RPG::MoveCommand::Code::move_away_from_hero:
					MoveAwayFromPlayer();
					break;
				case RPG::MoveCommand::Code::move_forward:
					MoveForward();
					break;
				case RPG::MoveCommand::Code::face_up:
					TurnUp();
					break;
				case RPG::MoveCommand::Code::face_right:
					TurnRight();
					break;
				case RPG::MoveCommand::Code::face_down:
					TurnDown();
					break;
				case RPG::MoveCommand::Code::face_left:
					TurnLeft();
					break;
				case RPG::MoveCommand::Code::turn_90_degree_right:
					Turn90DegreeRight();
					break;
				case RPG::MoveCommand::Code::turn_90_degree_left:
					Turn90DegreeLeft();
					break;
				case RPG::MoveCommand::Code::turn_180_degree:
					Turn180Degree();
					break;
				case RPG::MoveCommand::Code::turn_90_degree_random:
					Turn90DegreeLeftOrRight();
					break;
				case RPG::MoveCommand::Code::face_random_direction:
					FaceRandomDirection();
					break;
				case RPG::MoveCommand::Code::face_hero:
					TurnTowardHero();
					break;
				case RPG::MoveCommand::Code::face_away_from_hero:
					TurnAwayFromHero();
					break;
				case RPG::MoveCommand::Code::wait:
					Wait();
					break;
				case RPG::MoveCommand::Code::begin_jump:
					// Multiple BeginJumps are ignored
					break;
				case RPG::MoveCommand::Code::end_jump:
					active_route_index = EndJump(active_route, active_route_index);
					break;
				case RPG::MoveCommand::Code::lock_facing:
					SetFacingLocked(true);
					break;
				case RPG::MoveCommand::Code::unlock_facing:
					SetFacingLocked(false);
					break;
				case RPG::MoveCommand::Code::increase_movement_speed:
					SetMoveSpeed(min(GetMoveSpeed() + 1, 6));
					break;
				case RPG::MoveCommand::Code::decrease_movement_speed:
					SetMoveSpeed(max(GetMoveSpeed() - 1, 1));
					break;
				case RPG::MoveCommand::Code::increase_movement_frequence:
					SetMoveFrequency(min(GetMoveFrequency() + 1, 8));
					break;
				case RPG::MoveCommand::Code::decrease_movement_frequence:
					SetMoveFrequency(max(GetMoveFrequency() - 1, 1));
					break;
				case RPG::MoveCommand::Code::switch_on: // Parameter A: Switch to turn on
					Game_Switches[move_command.parameter_a] = true;
					Game_Map::SetNeedRefresh(true);
					break;
				case RPG::MoveCommand::Code::switch_off: // Parameter A: Switch to turn off
					Game_Switches[move_command.parameter_a] = false;
					Game_Map::SetNeedRefresh(true);
					break;
				case RPG::MoveCommand::Code::change_graphic: // String: File, Parameter A: index
					SetGraphic(move_command.parameter_string, move_command.parameter_a);
					break;
				case RPG::MoveCommand::Code::play_sound_effect: // String: File, Parameters: Volume, Tempo, Balance
					if (move_command.parameter_string != "(OFF)") {
						Audio().SE_Play(move_command.parameter_string,
							move_command.parameter_a, move_command.parameter_b);
					}
					break;
				case RPG::MoveCommand::Code::walk_everywhere_on:
					through = true;
					break;
				case RPG::MoveCommand::Code::walk_everywhere_off:
					through = false;
					break;
				case RPG::MoveCommand::Code::stop_animation:
					walk_animation = false;
					break;
				case RPG::MoveCommand::Code::start_animation:
					walk_animation = true;
					break;
				case RPG::MoveCommand::Code::increase_transp:
					SetOpacity(max(40, GetOpacity() - 45));
					break;
				case RPG::MoveCommand::Code::decrease_transp:
					SetOpacity(GetOpacity() + 45);
					break;
				}

				if (active_route->skippable || !move_failed) {
					++active_route_index;
				}
			} while (jumping);

			if ((size_t)active_route_index >= active_route->move_commands.size()) {
				stop_count = (active_route->repeat ? 0 : 256);
			}
		}
	}

	// When the overwrite status changed the active_index belongs to the
	// current non-active move route
	if (overwrite_changed != IsMoveRouteOverwritten()) {
		if (IsMoveRouteOverwritten()) {
			SetOriginalMoveRouteIndex(active_route_index);
		}
		else {
			SetMoveRouteIndex(active_route_index);
		}
	}
	else {
		if (IsMoveRouteOverwritten()) {
			SetMoveRouteIndex(active_route_index);
		}
		else {
			SetOriginalMoveRouteIndex(active_route_index);
		}
	}
}
Exemple #7
0
int main(int argc, char *argv[]) {

  static int selret;

  unsigned int recLen;
  static char* p;
  static char filebuffer[FILESIZE];
  static char directemp[BUFSIZE];
  static char filename[BUFSIZE];
  static struct timeval time;

  static fd_set readFDS;
  static frame frameArray[MAXSEQNUM];
  static int LB = 0, RB = 0; // static
  static char ackBuffer[100];
  static ack recvAck;
  static timeStruct timesArray[SWS];
  int lastSeqNum = -1;
  double t, timeout;
  int lastFrameCount = 0;

  //check command line args.
  if(argc < 6) {
    printf("usage : %s <server> <error rate> <random seed> <send_file> <send_log> \n", argv[0]);
    exit(1);
  }

  printf("argv4: %s\n",argv[4]);

  if(strcmp(argv[4],"0")){

    strcpy(directemp,argv[4]);
    p = strtok(directemp,DELM);
      
    while(p != NULL){
      strcpy(filename,p);
      p= strtok(NULL,DELM);
    }
      
    printf("Filename: %s\n",filename);
    fp = fopen(argv[4],"r");
    if(fp == NULL){
      printf("Error opening file: %s\n",strerror(errno));
    }
     
    //strcpy(msgbuffer,filebuffer);
  }

  
  
  printf("error rate : %f\n",atof(argv[2]));
  printf("%s: sending data to '%s' \n", argv[0], argv[1]);
    

  /* Note: you must initialize the network library first before calling
     sendto_().  The arguments are the <errorrate> and <random seed> */
  init_net_lib(atof(argv[2]), atoi(argv[3]));

  /* get server IP address (input must be IP address, not DNS name) */


  //setup socket structs
  /***************************************************/
  remoteServAddr.sin_family = AF_INET;
  remoteServAddr.sin_port = htons(REMOTE_SERVER_PORT);
  inet_pton(AF_INET, argv[1], &remoteServAddr.sin_addr);
  
  cliAddr.sin_family = AF_INET;
  cliAddr.sin_addr.s_addr = htonl(INADDR_ANY);
  cliAddr.sin_port = htons(0);
  /*************************************************/



  /* socket creation */
  if((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
    printf("Unable to connect socket!\n");
    exit(1);
  }
  int lastFrameSent = 0;
  while(1){
	  bzero(&ackBuffer, sizeof(ackBuffer));
    
	  int moveCount = MoveForward(&LB, &RB, frameArray, MAXSEQNUM);
	  if(lastFrameSent == 0){
		  lastFrameSent = SendNextFrames(moveCount, frameArray, MAXSEQNUM, LB, &fp,
				  	  	  &sock,(struct sockaddr *) &remoteServAddr, timesArray, SWS);
	  }

/*
    if((sendto_(sock,sendFrame, strlen(sendFrame),0, (struct sockaddr *) &remoteServAddr,
		sizeof(remoteServAddr)))< 0 ){
      printf("Error Sending\n");
      perror("sendto()");
      exit(1);
    }*/

	  gettimeofday(&time,NULL);
	  t = (time.tv_sec + (time.tv_usec/1000000.0));


	  timeout = (currentDeadline(timesArray,SWS) + DELAY) - t;
	  printf("Timeout: %f\n", timeout);
	  if(timeout < 0){timeout = 0;}

    selret = ballinselect(sock,&readFDS,timeout,0);

    
    if ((selret != -1) && (selret != 0)){
      
      if(recvfrom(sock, &ackBuffer, sizeof (ackBuffer), 0,(struct sockaddr *) &recAddr, (socklen_t*) &recLen) < 0){
    	  perror("recvfrom()");
    	  exit(1);
      }

      printf("Ack Buffer: %s\n",ackBuffer);

      makeackstruct(ackBuffer, &recvAck);
      if(lastSeqNum != recvAck.seqNum){
    	  frameArray[recvAck.seqNum].ack = 1;
    	  lastSeqNum = recvAck.seqNum;

    	  printf("============================\n");
    	  printf("Received Ack!\n");
    	  printf("Ack SeqNum: %d\n", recvAck.seqNum);
    	  printf("============================\n\n\n");

    	  removefromtimearray(recvAck.seqNum, timesArray,SWS);
      }

    }
    else if (selret == 0) {
      printf("timeout\n");
      bzero(&filebuffer,sizeof(filebuffer));

      int timeoutframe = FindTimeout(timesArray,SWS);



      if(frameArray[timeoutframe].lastFrame == 1){
    	  if(frameArray[timeoutframe].ack == 1){return EXIT_SUCCESS;}
    	  if(lastFrameCount == 10){return EXIT_SUCCESS;}
    	  lastFrameCount ++;
      }

      MakePacket(filebuffer,frameArray[timeoutframe]);

      printf("\nSending Timed out Frame: \n\n");
      printFrame(frameArray[timeoutframe]);

      if((sendto_(sock,filebuffer, strlen(filebuffer),0, (struct sockaddr *) &remoteServAddr,
      		sizeof(remoteServAddr)))< 0 ){
            printf("Error Sending\n");
            perror("sendto()");
            exit(1);
      }

      /*gettimeofday(&time,NULL);
      double t2= time.tv_sec + (time.tv_usec/1000000.0);
      printf("Time Out Time time: %f\n",t2);*/
    } else if (selret < 0) {printf("select() failed\n");}
  }

  fclose(fp);
    
  return EXIT_SUCCESS;
}
void CameraController::Update()
{
	if ( m_ZoomDirection == ZOOM_DIRECTION_NONE )
	{
		return;
	}

	float targetY = 0;
	float targetViewY = 0;

	switch ( m_ZoomStatus )
	{
		case ZOOM_STATUS_NEAREST:
			targetY = NEAREST_Y;
			targetViewY = NEAREST_VIEW_Y;
			break;
		case ZOOM_STATUS_DEGREE_1:
			targetY = DEGREE_1_Y;
			targetViewY = DEGREE_1_VIEW_Y;
			break;
		case ZOOM_STATUS_DEGREE_2:
			targetY = DEGREE_2_Y;
			targetViewY = DEGREE_2_VIEW_Y;
			break;
		case ZOOM_STATUS_DEGREE_3:
			targetY = DEGREE_3_Y;
			targetViewY = DEGREE_3_VIEW_Y;
			break;
		case ZOOM_STATUS_FARTHEST:
		default:
			targetY = FARTHEST_Y;
			targetViewY = FARTHEST_VIEW_Y;
			break;
	}

	float time = static_cast<float>( Timer::GetInstance()->GetElapsedTime() ) / 1000;
	float delta = time * 10.0f;

	D3DXVECTOR3 view = m_LookAtPoint - m_EyePoint;
	D3DXVec3Normalize( &view, &view );
	float	dotView = D3DXVec3Dot( &view, &( -m_UpVector ) );

	// Log( "%-8f도!!! %-8f \n", dotView, targetViewY );
	// Log( "목표 = %f, 현위치 = %f \n", targetY, m_EyePoint.y );

	// 카메라 업
	if ( m_ZoomDirection == ZOOM_DIRECTION_BACK )
	{
		if ( dotView < targetViewY )
		{
			RotateUp( delta * dotView / ( m_EyePoint.y / 10 ) );
		}

		MoveElevate( delta * 10 );
		MoveForward( -delta * 10, true );

		if ( targetY < m_EyePoint.y )
		{
			m_ZoomDirection = ZOOM_DIRECTION_NONE;
			return;
		}
	}
	// 카메라 다운
	else if ( m_ZoomDirection == ZOOM_DIRECTION_FOWARD )
	{
		if ( dotView > targetViewY )
		{
			RotateUp( -delta * dotView / ( m_EyePoint.y / 10 ) );
		}

		MoveElevate( -delta * 10 );
		MoveForward( delta * 10, true );

		if ( targetY > m_EyePoint.y )
		{
			m_ZoomDirection = ZOOM_DIRECTION_NONE;
			return;
		}
	}

	if ( m_ZoomPointX > 0 )
	{
		m_ZoomPointX = __min( m_ZoomPointX, 50 );
		m_ZoomPointX -= delta;
		MoveSide( delta );
	}
	else if ( m_ZoomPointX < 0 )
	{
		m_ZoomPointX = __max( m_ZoomPointX, -50 );
		m_ZoomPointX += delta;
		MoveSide( -delta );
	}

	if ( m_ZoomPointY > 0 )
	{
		m_ZoomPointY = __min( m_ZoomPointY, 50 );
		m_ZoomPointY -= delta;
		MoveForward( -delta );
	}
	else if ( m_ZoomPointY < 0 )
	{
		m_ZoomPointY = __max( m_ZoomPointY, -50 );
		m_ZoomPointY += delta;
		MoveForward( delta );
	}
}
void ControllerComponent::Update(double dt, GridMap * currMap)
{
	m_dInputDelay += dt;
	m_dMoveDelay += dt;

	EntityTest * thePlayer = dynamic_cast<EntityTest*>(this->getParent());
	auto infoC = this->getParent()->getComponent<InformationComponent>();
	if (infoC)
	{
		// CONTROL PLAYER
		if (!this->m_sMovement.m_bIsMoving)
		{

			if (m_dMoveDelay > MOVEMENT_DELAY)
			{
				if (m_cInputHandler->IsKeyPressed(GLFW_KEY_UP))
				{
					MoveForward(currMap);
				}
				else if (m_cInputHandler->IsKeyPressed(GLFW_KEY_LEFT))
				{
					MoveLeft(currMap);
				}
				else if (m_cInputHandler->IsKeyPressed(GLFW_KEY_DOWN))
				{
					MoveBackwards(currMap);
				}
				else if (m_cInputHandler->IsKeyPressed(GLFW_KEY_RIGHT))
				{
					MoveRight(currMap);
				}
			}

			if (m_dInputDelay > INTERACTION_DELAY)
			{
				if (m_cInputHandler->IsKeyPressed(GLFW_KEY_E))
				{
					Interact(currMap);
				}
			}
		}
		else
		{
			float newX, newY;
			int absX, absY;
			Vector3 prevPosition = infoC->getPosition();
			switch (this->m_sMovement.m_eMoveDirection)
			{
			case GridMap::DIRECTION_UP: // X does not Change
				newY = Math::SmoothDamp(infoC->getPosition().y, this->m_sMovement.m_v3NextPosition.y, 4096.f, 0.001f, 4096.f, dt);
				infoC->setPosition(Vector3(prevPosition.x, newY, 0.f));
				absY = (int)newY;
				if (m_sMovement.m_v3NextPosition.y == absY)
				{
					m_sMovement.m_bIsMoving = false;
					currMap->getGridMap()[m_sMovement.m_iPlayerIndexY - 1][m_sMovement.m_iPlayerIndexX]->addGridEntity(currMap->getGridMap()[m_sMovement.m_iPlayerIndexY][m_sMovement.m_iPlayerIndexX]->getGridEntity());
					currMap->getGridMap()[m_sMovement.m_iPlayerIndexY][m_sMovement.m_iPlayerIndexX]->removeEntity();
				}
				break;
			case GridMap::DIRECTION_DOWN: // X does not Change
				newY = Math::SmoothDamp(infoC->getPosition().y, this->m_sMovement.m_v3NextPosition.y, 4096.f, 0.001f, 4096.f, dt);
				infoC->setPosition(Vector3(prevPosition.x, newY, 0.f));
				absY = (int)newY;
				if (m_sMovement.m_v3NextPosition.y == absY)
				{
					m_sMovement.m_bIsMoving = false;
					currMap->getGridMap()[m_sMovement.m_iPlayerIndexY + 1][m_sMovement.m_iPlayerIndexX]->addGridEntity(currMap->getGridMap()[m_sMovement.m_iPlayerIndexY][m_sMovement.m_iPlayerIndexX]->getGridEntity());
					currMap->getGridMap()[m_sMovement.m_iPlayerIndexY][m_sMovement.m_iPlayerIndexX]->removeEntity();
				}
				break;
			case GridMap::DIRECTION_LEFT: // Y does not Change
				newX = Math::SmoothDamp(infoC->getPosition().x, this->m_sMovement.m_v3NextPosition.x, 4096.f, 0.001f, 4096.f, dt);
				infoC->setPosition(Vector3(newX, prevPosition.y, 0.f));
				absX = (int)newX;
				if (m_sMovement.m_v3NextPosition.x == absX)
				{
					m_sMovement.m_bIsMoving = false;
					currMap->getGridMap()[m_sMovement.m_iPlayerIndexY][m_sMovement.m_iPlayerIndexX - 1]->addGridEntity(currMap->getGridMap()[m_sMovement.m_iPlayerIndexY][m_sMovement.m_iPlayerIndexX]->getGridEntity());
					currMap->getGridMap()[m_sMovement.m_iPlayerIndexY][m_sMovement.m_iPlayerIndexX]->removeEntity();
				}
				break;
			case GridMap::DIRECTION_RIGHT: // Y does not Change
				newX = Math::SmoothDamp(infoC->getPosition().x, this->m_sMovement.m_v3NextPosition.x, 4096.f, 0.001f, 4096.f, dt);
				infoC->setPosition(Vector3(newX, prevPosition.y, 0.f));
				absX = (int)newX;
				if (m_sMovement.m_v3NextPosition.x == absX)
				{
					m_sMovement.m_bIsMoving = false;
					currMap->getGridMap()[m_sMovement.m_iPlayerIndexY][m_sMovement.m_iPlayerIndexX + 1]->addGridEntity(currMap->getGridMap()[m_sMovement.m_iPlayerIndexY][m_sMovement.m_iPlayerIndexX]->getGridEntity());
					currMap->getGridMap()[m_sMovement.m_iPlayerIndexY][m_sMovement.m_iPlayerIndexX]->removeEntity();
				}
				break;
			}
		}
	}
}
Exemple #10
0
//--------------------------------------------------------------
void testApp::bangFired(ofxTLBangEventArgs& bang){
	cout << "bang fired!" << bang.flag << endl;
	if (bang.flag == "fwd1")
	{
		cout << "Moving forward projector 1" << endl;
		MoveForward();
        //relayShield.PulseRelay3();
        //cout<< "Flash ON CC48" << endl;
	}
	if (bang.flag == "bck1")
	{
		cout << "Moving backward projector 1" << endl;
		MoveBackward();
	}
	if (bang.flag == "fwd2")
	{
		cout << "Moving forward projector 2" << endl;

        midiOut.sendControlChange(1, 48, 127);
		relayShield.PulseRelay3();
        cout<< "Flash ON CC48" << endl;
	}
    if (bang.flag == "bck2")
	{
		cout << "Moving forward projector 2" << endl;

        midiOut.sendControlChange(1, 48, 0);
        cout<< "Flash OFF CC48" << endl;

	}
	if (bang.flag == "AudioLocuraOn")
	{
		cout << "AudioLocuraOn" << endl;
		sublines[0]->play();
	}
	if (bang.flag == "AudioLocuraOff")
	{
		cout << "AudioLocuraOff" << endl;
		sublines[0]->stop();
	}
	if (bang.flag == "AudioSlideShowOn")
	{
		cout << "AudioSlideShowOn" << endl;
		sublines[1]->play();
	}
	if (bang.flag == "AudioSlideshowOff")
	{
		cout << "AudioSlideshowOff" << endl;
		sublines[1]->stop();
	}
	if (bang.flag == "AudioColadorOn")
	{
		cout << "AudioColadorOn" << endl;
		sublines[2]->play();
	}
	if (bang.flag == "AudioColadorOff")
	{
		cout << "AudioColadorOff" << endl;
		sublines[2]->stop();
	}
	if (bang.flag == "Projector1On")
	{
		cout << "Projector1On" << endl;
		relayShield.Relay5Off();
	}
	if (bang.flag == "Projector1Off")
	{
		cout << "Projector1Off" << endl;
		relayShield.Relay5On();
	}
	if (bang.flag == "Projector2On")
	{
		cout << "Projector2On" << endl;
		relayShield.Relay6Off();
	}
	if (bang.flag == "Projector2Off")
	{
		cout << "Projector2Off" << endl;
		relayShield.Relay6On();
	}
    if (bang.flag == "LightOn")
	{
		cout << "LightOn" << endl;
		relayShield.Relay4On();
	}
	if (bang.flag == "LightOff")
	{
		cout << "LightOff" << endl;
		relayShield.Relay4Off();
	}
		
}
Exemple #11
0
void testApp::AdvanceSlideShow(void){
	MoveForward();
	cout<<"Move slideshow on";

}
Exemple #12
0
void MasinaManager::moveNext_MasinaSport() {
    if (!areMasinaSport()) return;
    MoveForward();
     while (carList[currentCarIndex]->toName() != "MasinaSport")
            MoveForward();
}
Exemple #13
0
void MasinaManager::moveNext_SUV() {
    if (!areSUV()) return;
    MoveForward();
     while (carList[currentCarIndex]->toName() != "SUV")
            MoveForward();
}
Exemple #14
0
void MasinaManager::moveNext_Limuzina() {
    if (!areLimuzina()) return;
    MoveForward();
        while (carList[currentCarIndex]->toName() != "Limuzina")
            MoveForward();
}
Exemple #15
0
void Camera::MoveBackward(float speed)
{
    MoveForward(-speed);
}
Exemple #16
0
void Game_Character::MoveTypeCustom() {
	// Detect if custom movement or event overwrite
	const RPG::MoveRoute* active_route;
	int active_route_index;
	bool overwrite_changed = IsMoveRouteOverwritten();
	if (IsMoveRouteOverwritten()) {
		active_route = &GetMoveRoute();
		active_route_index = GetMoveRouteIndex();
	}
	else {
		active_route = &original_move_route;
		active_route_index = GetOriginalMoveRouteIndex();
	}

	if (IsStopping()) {
		move_failed = false;

		int original_index = active_route_index;
		bool looped_around = false;
		while (true) {
			if (!IsStopping() || wait_count > 0 || stop_count < max_stop_count)
				break;

			if (active_route_index == original_index && looped_around) {
				// We've gone around a full loop; stop here for now
				break;
			}

			if ((size_t)active_route_index >= active_route->move_commands.size()) {
				if (active_route->repeat && !active_route->move_commands.empty()) {
					looped_around = true;
					active_route_index = 0;
					SetMoveRouteRepeated(true);
					if (original_index == 0) {
						break;
					}
				} else {
					break;
				}
			}

			const RPG::MoveCommand& move_command = active_route->move_commands[active_route_index];

			switch (move_command.command_id) {
			case RPG::MoveCommand::Code::move_up:
			case RPG::MoveCommand::Code::move_right:
			case RPG::MoveCommand::Code::move_down:
			case RPG::MoveCommand::Code::move_left:
			case RPG::MoveCommand::Code::move_upright:
			case RPG::MoveCommand::Code::move_downright:
			case RPG::MoveCommand::Code::move_downleft:
			case RPG::MoveCommand::Code::move_upleft:
				Move(move_command.command_id);
				break;
			case RPG::MoveCommand::Code::move_random:
				MoveRandom();
				break;
			case RPG::MoveCommand::Code::move_towards_hero:
				MoveTowardsPlayer();
				break;
			case RPG::MoveCommand::Code::move_away_from_hero:
				MoveAwayFromPlayer();
				break;
			case RPG::MoveCommand::Code::move_forward:
				MoveForward();
				break;
			case RPG::MoveCommand::Code::face_up:
				Turn(Up);
				break;
			case RPG::MoveCommand::Code::face_right:
				Turn(Right);
				break;
			case RPG::MoveCommand::Code::face_down:
				Turn(Down);
				break;
			case RPG::MoveCommand::Code::face_left:
				Turn(Left);
				break;
			case RPG::MoveCommand::Code::turn_90_degree_right:
				Turn90DegreeRight();
				break;
			case RPG::MoveCommand::Code::turn_90_degree_left:
				Turn90DegreeLeft();
				break;
			case RPG::MoveCommand::Code::turn_180_degree:
				Turn180Degree();
				break;
			case RPG::MoveCommand::Code::turn_90_degree_random:
				Turn90DegreeLeftOrRight();
				break;
			case RPG::MoveCommand::Code::face_random_direction:
				FaceRandomDirection();
				break;
			case RPG::MoveCommand::Code::face_hero:
				TurnTowardHero();
				break;
			case RPG::MoveCommand::Code::face_away_from_hero:
				TurnAwayFromHero();
				break;
			case RPG::MoveCommand::Code::wait:
				Wait();
				break;
			case RPG::MoveCommand::Code::begin_jump:
				BeginJump(active_route, &active_route_index);
				break;
			case RPG::MoveCommand::Code::end_jump:
				// EndJump();
				break;
			case RPG::MoveCommand::Code::lock_facing:
				SetFacingLocked(true);
				break;
			case RPG::MoveCommand::Code::unlock_facing:
				SetFacingLocked(false);
				break;
			case RPG::MoveCommand::Code::increase_movement_speed:
				SetMoveSpeed(min(GetMoveSpeed() + 1, 6));
				break;
			case RPG::MoveCommand::Code::decrease_movement_speed:
				SetMoveSpeed(max(GetMoveSpeed() - 1, 1));
				break;
			case RPG::MoveCommand::Code::increase_movement_frequence:
				SetMoveFrequency(min(GetMoveFrequency() + 1, 8));
				break;
			case RPG::MoveCommand::Code::decrease_movement_frequence:
				SetMoveFrequency(max(GetMoveFrequency() - 1, 1));
				break;
			case RPG::MoveCommand::Code::switch_on: // Parameter A: Switch to turn on
				Game_Switches[move_command.parameter_a] = true;
				Game_Map::SetNeedRefresh(Game_Map::Refresh_All);
				break;
			case RPG::MoveCommand::Code::switch_off: // Parameter A: Switch to turn off
				Game_Switches[move_command.parameter_a] = false;
				Game_Map::SetNeedRefresh(Game_Map::Refresh_All);
				break;
			case RPG::MoveCommand::Code::change_graphic: // String: File, Parameter A: index
				SetGraphic(move_command.parameter_string, move_command.parameter_a);
				break;
			case RPG::MoveCommand::Code::play_sound_effect: // String: File, Parameters: Volume, Tempo, Balance
				if (move_command.parameter_string != "(OFF)" && move_command.parameter_string != "(Brak)") {
					RPG::Sound sound;
					sound.name = move_command.parameter_string;
					sound.volume = move_command.parameter_a;
					sound.tempo = move_command.parameter_b;
					sound.balance = move_command.parameter_c;

					Game_System::SePlay(sound);
				}
				break;
			case RPG::MoveCommand::Code::walk_everywhere_on:
				SetThrough(true);
				break;
			case RPG::MoveCommand::Code::walk_everywhere_off:
				SetThrough(false);
				break;
			case RPG::MoveCommand::Code::stop_animation:
				walk_animation = false;
				break;
			case RPG::MoveCommand::Code::start_animation:
				walk_animation = true;
				break;
			case RPG::MoveCommand::Code::increase_transp:
				SetOpacity(max(40, GetOpacity() - 45));
				break;
			case RPG::MoveCommand::Code::decrease_transp:
				SetOpacity(GetOpacity() + 45);
				break;
			}

			last_move_failed = move_failed;
			if (move_failed) {
				if (active_route->skippable) {
					last_move_failed = false;
				} else {
					break;
				}
			}

			++active_route_index;
		}

		if ((size_t)active_route_index >= active_route->move_commands.size() && IsStopping() && wait_count == 0) {
			if (IsMoveRouteOverwritten()) {
				CancelMoveRoute();
				Game_Map::RemovePendingMove(this);
				stop_count = 0;
			}
		}
	}

	// When the overwrite status changed the active_index belongs to the
	// current non-active move route
	if (overwrite_changed != IsMoveRouteOverwritten()) {
		if (IsMoveRouteOverwritten()) {
			SetOriginalMoveRouteIndex(active_route_index);
		}
		else {
			SetMoveRouteIndex(active_route_index);
		}
	}
	else {
		if (IsMoveRouteOverwritten()) {
			SetMoveRouteIndex(active_route_index);
		}
		else {
			SetOriginalMoveRouteIndex(active_route_index);
		}
	}
}
void UBerserkCameraComponent::UpdateCameraMovement(const APlayerController* playerController)
{
	auto const* const localPlayer = Cast<ULocalPlayer>(playerController->Player);
	if (localPlayer && localPlayer->ViewportClient && localPlayer->ViewportClient->Viewport)
	{
		FVector2D mousePosition;

		if (localPlayer->ViewportClient->GetMousePosition(mousePosition) == false) return;

		auto viewport = localPlayer->ViewportClient->Viewport;
		const float scrollSpeed = 60.0f;
		const FIntPoint viewportSize = viewport->GetSizeXY();
		const uint32 viewLeft = FMath::TruncToInt(localPlayer->Origin.X * viewportSize.X);
		const uint32 viewRight = viewLeft + FMath::TruncToInt(localPlayer->Size.X * viewportSize.X);
		const uint32 viewTop = FMath::TruncToInt(localPlayer->Origin.Y * viewportSize.Y);
		const uint32 viewBottom = viewTop + FMath::TruncToInt(localPlayer->Size.Y * viewportSize.Y);

		const float maxSpeed = CameraScrollSpeed * FMath::Clamp(ZoomAlpha, 0.3f, 1.0f);

		bool isNoScrollZone = false;
		const FVector mouseCoords(mousePosition, 0.0f);
		for (int iZone = 0; iZone < NoScrollZones.Num(); ++iZone)
		{
			const auto eachZone = NoScrollZones[iZone];
			if (eachZone.IsInsideXY(mouseCoords) == true)
				isNoScrollZone = true;
		}

		const uint32 mouseX = mousePosition.X;
		const uint32 mouseY = mousePosition.Y;
		float spectatorCameraSpeed = maxSpeed;
		ASpectatorPawn* spectatorPawn = nullptr;
		if (GetPlayerController() != nullptr)
		{
			spectatorPawn = GetPlayerController()->GetSpectatorPawn();
			if (spectatorPawn->GetMovementComponent() != nullptr)
				spectatorCameraSpeed = GetDefault<UBerserkSpectatorPawnMovement>(spectatorPawn->GetMovementComponent()->GetClass())->MaxSpeed;
		}

		if (!isNoScrollZone)
		{
			if (mouseX >= viewLeft && mouseX <= (viewLeft + CameraActiveBorder))
			{
				const float delta = 1.0f - float(mouseX - viewLeft) / CameraActiveBorder;
				spectatorCameraSpeed = delta * maxSpeed;
				MoveRight(-scrollSpeed * delta);
			}
			else if (mouseX >= (viewRight - CameraActiveBorder) && mouseX <= viewRight)
			{
				const float delta = float(mouseX - viewRight + CameraActiveBorder) / CameraActiveBorder;
				spectatorCameraSpeed = delta * maxSpeed;
				MoveRight(scrollSpeed * delta);
			}

			if (mouseY >= viewTop && mouseY <= (viewTop + CameraActiveBorder))
			{
				const float delta = 1.0f - float(mouseY - viewTop) / CameraActiveBorder;
				spectatorCameraSpeed = delta * maxSpeed;
				MoveForward(scrollSpeed * delta);
			}
			else if (mouseY >= (viewBottom - CameraActiveBorder) && mouseY <= viewBottom)
			{
				const float delta = float(mouseY - (viewBottom - CameraActiveBorder)) / CameraActiveBorder;
				spectatorCameraSpeed = delta * maxSpeed;
				MoveForward(-scrollSpeed * delta);
			}

			if (spectatorPawn != nullptr)
			{
				UFloatingPawnMovement* floatingMovementComponent = Cast<UFloatingPawnMovement>(spectatorPawn->GetMovementComponent());
				if (floatingMovementComponent)
					floatingMovementComponent->MaxSpeed = spectatorCameraSpeed;
			}
		}
	}

	NoScrollZones.Empty();
}
Exemple #18
0
void Game_Character::BeginJump(const RPG::MoveRoute* current_route, int* current_index) {
	jump_x = GetX();
	jump_y = GetY();
	jump_plus_x = 0;
	jump_plus_y = 0;
	jumping = true;

	bool end_found = false;
	unsigned int i;
	for (i = *current_index; i < current_route->move_commands.size(); ++i) {
		const RPG::MoveCommand& move_command = current_route->move_commands[i];
		switch (move_command.command_id) {
			case RPG::MoveCommand::Code::move_up:
			case RPG::MoveCommand::Code::move_right:
			case RPG::MoveCommand::Code::move_down:
			case RPG::MoveCommand::Code::move_left:
			case RPG::MoveCommand::Code::move_upright:
			case RPG::MoveCommand::Code::move_downright:
			case RPG::MoveCommand::Code::move_downleft:
			case RPG::MoveCommand::Code::move_upleft:
				Move(move_command.command_id);
				break;
			case RPG::MoveCommand::Code::move_random:
				MoveRandom();
				break;
			case RPG::MoveCommand::Code::move_towards_hero:
				MoveTowardsPlayer();
				break;
			case RPG::MoveCommand::Code::move_away_from_hero:
				MoveAwayFromPlayer();
				break;
			case RPG::MoveCommand::Code::move_forward:
				MoveForward();
				break;
			default:
				break;
		}

		if (move_command.command_id == RPG::MoveCommand::Code::end_jump) {
			end_found = true;
			break;
		}
	}

	if (!end_found) {
		// No EndJump found. Move route ends directly
		*current_index = i;
		jumping = false;
		return;
	}

	int new_x = jump_x + jump_plus_x;
	int new_y = jump_y + jump_plus_y;

	if (Game_Map::LoopHorizontal()) {
		int map_width = Game_Map::GetWidth();
		if (new_x < 0) {
			jump_x += map_width;
			new_x += map_width;
		} else if (new_x >= map_width) {
			jump_x -= map_width;
			new_x -= map_width;
		}
	}

	if (Game_Map::LoopVertical()) {
		int map_height = Game_Map::GetHeight();
		if (new_y < 0) {
			jump_y += map_height;
			new_y += map_height;
		} else if (new_y >= map_height) {
			jump_y -= map_height;
			new_y -= map_height;
		}
	}

	if (
		// A character can always land on a tile they were already standing on
		!(jump_plus_x == 0 && jump_plus_y == 0) &&
		!IsLandable(new_x, new_y)
	) {
		// Reset to begin jump command and try again...
		move_failed = true;
		jumping = false;

		if (current_route->skippable) {
			*current_index = i;
			return;
		}

		return;
	}

	SetX(new_x);
	SetY(new_y);
	*current_index = i;

	remaining_step = SCREEN_TILE_WIDTH;
	stop_count = 0;
	max_stop_count = (GetMoveFrequency() > 7) ? 0 : pow(2.0, 9 - GetMoveFrequency());
	move_failed = false;
}
// Navigate our current ladder. Return true if we are doing ladder navigation.
// TODO: Need Push() and Pop() for run/walk context to keep ladder speed contained.
bool CCSBot::UpdateLadderMovement()
{
	if (!m_pathLadder)
		return false;

	bool giveUp = false;

	// check for timeout
	const float ladderTimeoutDuration = 10.0f;
	if (gpGlobals->time - m_pathLadderTimestamp > ladderTimeoutDuration)
	{
		PrintIfWatched("Ladder timeout!\n");
		giveUp = true;
	}

	else if (m_pathLadderState == APPROACH_ASCENDING_LADDER
		|| m_pathLadderState == APPROACH_DESCENDING_LADDER
		|| m_pathLadderState == ASCEND_LADDER
		|| m_pathLadderState == DESCEND_LADDER
		|| m_pathLadderState == DISMOUNT_ASCENDING_LADDER
		|| m_pathLadderState == MOVE_TO_DESTINATION)
	{
		if (m_isStuck)
		{
			PrintIfWatched("Giving up ladder - stuck\n");
			giveUp = true;
		}
	}

	if (giveUp)
	{
		// jump off ladder and give up
		Jump(MUST_JUMP);
		Wiggle();
		ResetStuckMonitor();
		DestroyPath();
		Run();
		return false;
	}

	ResetStuckMonitor();

	// check if somehow we totally missed the ladder
	switch (m_pathLadderState)
	{
	case MOUNT_ASCENDING_LADDER:
	case MOUNT_DESCENDING_LADDER:
	case ASCEND_LADDER:
	case DESCEND_LADDER:
	{
		const float farAway = 200.0f;
		Vector2D d = (m_pathLadder->m_top - pev->origin).Make2D();
		if (d.IsLengthGreaterThan(farAway))
		{
			PrintIfWatched("Missed ladder\n");
			Jump(MUST_JUMP);
			DestroyPath();
			Run();
			return false;
		}
		break;
	}
	}

	m_areaEnteredTimestamp = gpGlobals->time;

	const float tolerance = 10.0f;
	const float closeToGoal = 25.0f;

	switch (m_pathLadderState)
	{
	case APPROACH_ASCENDING_LADDER:
	{
		bool approached = false;
		Vector2D d(pev->origin.x - m_goalPosition.x, pev->origin.y - m_goalPosition.y);

		if (d.x * m_pathLadder->m_dirVector.x + d.y * m_pathLadder->m_dirVector.y < 0.0f)
		{
			Vector2D perp(-m_pathLadder->m_dirVector.y, m_pathLadder->m_dirVector.x);

#ifdef REGAMEDLL_FIXES
			if (Q_abs(d.x * perp.x + d.y * perp.y) < tolerance && d.Length() < closeToGoal)
#else
			if (Q_abs(int64(d.x * perp.x + d.y * perp.y)) < tolerance && d.Length() < closeToGoal)
#endif
				approached = true;
		}

		// small radius will just slow them down a little for more accuracy in hitting their spot
		const float walkRange = 50.0f;
		if (d.IsLengthLessThan(walkRange))
		{
			Walk();
			StandUp();
		}

		// TODO: Check that we are on the ladder we think we are
		if (IsOnLadder())
		{
			m_pathLadderState = ASCEND_LADDER;
			PrintIfWatched("ASCEND_LADDER\n");

			// find actual top in case m_pathLadder penetrates the ceiling
			ComputeLadderEndpoint(true);
		}
		else if (approached)
		{
			// face the m_pathLadder
			m_pathLadderState = FACE_ASCENDING_LADDER;
			PrintIfWatched("FACE_ASCENDING_LADDER\n");
		}
		else
		{
			// move toward ladder mount point
			MoveTowardsPosition(&m_goalPosition);
		}
		break;
	}
	case APPROACH_DESCENDING_LADDER:
	{
		// fall check
		if (GetFeetZ() <= m_pathLadder->m_bottom.z + HalfHumanHeight)
		{
			PrintIfWatched("Fell from ladder.\n");

			m_pathLadderState = MOVE_TO_DESTINATION;
			m_path[m_pathIndex].area->GetClosestPointOnArea(&m_pathLadder->m_bottom, &m_goalPosition);

			AddDirectionVector(&m_goalPosition, m_pathLadder->m_dir, HalfHumanWidth);
			PrintIfWatched("MOVE_TO_DESTINATION\n");
		}
		else
		{
			bool approached = false;
			Vector2D d(pev->origin.x - m_goalPosition.x, pev->origin.y - m_goalPosition.y);

			if (d.x * m_pathLadder->m_dirVector.x + d.y * m_pathLadder->m_dirVector.y > 0.0f)
			{
				Vector2D perp(-m_pathLadder->m_dirVector.y, m_pathLadder->m_dirVector.x);

				if (Q_abs(int64(d.x * perp.x + d.y * perp.y)) < tolerance && d.Length() < closeToGoal)
					approached = true;
			}

			// if approaching ladder from the side or "ahead", walk
			if (m_pathLadder->m_topBehindArea != m_lastKnownArea)
			{
				const float walkRange = 150.0f;
				if (!IsCrouching() && d.IsLengthLessThan(walkRange))
					Walk();
			}

			// TODO: Check that we are on the ladder we think we are
			if (IsOnLadder())
			{
				// we slipped onto the ladder - climb it
				m_pathLadderState = DESCEND_LADDER;
				Run();
				PrintIfWatched("DESCEND_LADDER\n");

				// find actual bottom in case m_pathLadder penetrates the floor
				ComputeLadderEndpoint(false);
			}
			else if (approached)
			{
				// face the ladder
				m_pathLadderState = FACE_DESCENDING_LADDER;
				PrintIfWatched("FACE_DESCENDING_LADDER\n");
			}
			else
			{
				// move toward ladder mount point
				MoveTowardsPosition(&m_goalPosition);
			}
		}
		break;
	}
	case FACE_ASCENDING_LADDER:
	{
		// find yaw to directly aim at ladder
		Vector to = m_pathLadder->m_bottom - pev->origin;
		Vector idealAngle = UTIL_VecToAngles(to);

		const float angleTolerance = 5.0f;
		if (AnglesAreEqual(pev->v_angle.y, idealAngle.y, angleTolerance))
		{
			// move toward ladder until we become "on" it
			Run();
			ResetStuckMonitor();
			m_pathLadderState = MOUNT_ASCENDING_LADDER;
			PrintIfWatched("MOUNT_ASCENDING_LADDER\n");
		}
		break;
	}
	case FACE_DESCENDING_LADDER:
	{
		// find yaw to directly aim at ladder
		Vector to = m_pathLadder->m_top - pev->origin;
		Vector idealAngle = UTIL_VecToAngles(to);

		const float angleTolerance = 5.0f;
		if (AnglesAreEqual(pev->v_angle.y, idealAngle.y, angleTolerance))
		{
			// move toward ladder until we become "on" it
			m_pathLadderState = MOUNT_DESCENDING_LADDER;
			ResetStuckMonitor();
			PrintIfWatched("MOUNT_DESCENDING_LADDER\n");
		}
		break;
	}
	case MOUNT_ASCENDING_LADDER:
	{
		if (IsOnLadder())
		{
			m_pathLadderState = ASCEND_LADDER;
			PrintIfWatched("ASCEND_LADDER\n");

			// find actual top in case m_pathLadder penetrates the ceiling
			ComputeLadderEndpoint(true);
		}

		MoveForward();
		break;
	}
	case MOUNT_DESCENDING_LADDER:
	{
		// fall check
		if (GetFeetZ() <= m_pathLadder->m_bottom.z + HalfHumanHeight)
		{
			PrintIfWatched("Fell from ladder.\n");

			m_pathLadderState = MOVE_TO_DESTINATION;
			m_path[m_pathIndex].area->GetClosestPointOnArea(&m_pathLadder->m_bottom, &m_goalPosition);

			AddDirectionVector(&m_goalPosition, m_pathLadder->m_dir, HalfHumanWidth);
			PrintIfWatched("MOVE_TO_DESTINATION\n");
		}
		else
		{
			if (IsOnLadder())
			{
				m_pathLadderState = DESCEND_LADDER;
				PrintIfWatched("DESCEND_LADDER\n");

				// find actual bottom in case m_pathLadder penetrates the floor
				ComputeLadderEndpoint(false);
			}

			// move toward ladder mount point
			MoveForward();
		}
		break;
	}
	case ASCEND_LADDER:
	{
		// run, so we can make our dismount jump to the side, if necessary
		Run();

		// if our destination area requires us to crouch, do it
		if (m_path[m_pathIndex].area->GetAttributes() & NAV_CROUCH)
			Crouch();

		// did we reach the top?
		if (GetFeetZ() >= m_pathLadderEnd)
		{
			// we reached the top - dismount
			m_pathLadderState = DISMOUNT_ASCENDING_LADDER;
			PrintIfWatched("DISMOUNT_ASCENDING_LADDER\n");

			if (m_path[m_pathIndex].area == m_pathLadder->m_topForwardArea)
				m_pathLadderDismountDir = FORWARD;
			else if (m_path[m_pathIndex].area == m_pathLadder->m_topLeftArea)
				m_pathLadderDismountDir = LEFT;
			else if (m_path[m_pathIndex].area == m_pathLadder->m_topRightArea)
				m_pathLadderDismountDir = RIGHT;

			m_pathLadderDismountTimestamp = gpGlobals->time;
		}
		else if (!IsOnLadder())
		{
			// we fall off the ladder, repath
			DestroyPath();
			return false;
		}

		// move up ladder
		MoveForward();
		break;
	}
	case DESCEND_LADDER:
	{
		Run();

		float destHeight = m_pathLadderEnd + HalfHumanHeight;
		if (!IsOnLadder() || GetFeetZ() <= destHeight)
		{
			// we reached the bottom, or we fell off - dismount
			m_pathLadderState = MOVE_TO_DESTINATION;
			m_path[m_pathIndex].area->GetClosestPointOnArea(&m_pathLadder->m_bottom, &m_goalPosition);

			AddDirectionVector(&m_goalPosition, m_pathLadder->m_dir, HalfHumanWidth);
			PrintIfWatched("MOVE_TO_DESTINATION\n");
		}

		// Move down ladder
		MoveForward();
		break;
	}
	case DISMOUNT_ASCENDING_LADDER:
	{
		if (gpGlobals->time - m_pathLadderDismountTimestamp >= 0.4f)
		{
			m_pathLadderState = MOVE_TO_DESTINATION;
			m_path[m_pathIndex].area->GetClosestPointOnArea(&pev->origin, &m_goalPosition);
			PrintIfWatched("MOVE_TO_DESTINATION\n");
		}

		// We should already be facing the dismount point
		if (m_pathLadderFaceIn)
		{
			switch (m_pathLadderDismountDir)
			{
			case LEFT:    StrafeLeft(); break;
			case RIGHT:   StrafeRight(); break;
			case FORWARD: MoveForward(); break;
			}
		}
		else
		{
			switch (m_pathLadderDismountDir)
			{
			case LEFT:    StrafeRight();  break;
			case RIGHT:   StrafeLeft();   break;
			case FORWARD: MoveBackward(); break;
			}
		}
		break;
	}
	case MOVE_TO_DESTINATION:
	{
		if (m_path[m_pathIndex].area->Contains(&pev->origin))
		{
			// successfully traversed ladder and reached destination area
			// exit ladder state machine
			PrintIfWatched("Ladder traversed.\n");
			m_pathLadder = nullptr;

			// incrememnt path index to next step beyond this ladder
			SetPathIndex(m_pathIndex + 1);

			return false;
		}

		MoveTowardsPosition(&m_goalPosition);
		break;
	}
	}

	return true;
}
void CTrackingMissile::Update(void)
{
	CQuaternion q;
	float t;

	m_Age = g_time - m_CreationTime;

   if(m_Age > m_LifeTime)
   {
      Die();
      return;
   }

	if (!m_Tracking)
	{
		if (m_Age <= 0.4f)
		{
			if (m_FlyLeft)
				m_RenderObj.MoveRight(-20.0f * g_FrameTime, 0);
			else
				m_RenderObj.MoveRight(20.0f * g_FrameTime, 0);
	
			t = m_Age;
			QuatSlerp(&q, &m_Q0, &m_Q1, t * 2.5f);
			m_RenderObj.GetFrame(0)->SetOrientation(&q);
		}
		else if (m_Age <= 0.8f && !m_Target)
		{
			t = m_Age - 0.4f;
			QuatSlerp(&q, &m_Q1, &m_Q2, t * 2.5f);
			m_RenderObj.GetFrame(0)->SetOrientation(&q);
		}
		else
		{
			m_Tracking = true;
			m_RenderObj.GetFrame(0)->GetOrientation(&m_Q0);
			m_Q1 = m_Q0;
			m_Velocity = 120.0f;
			m_LastUpdate = g_time - m_UpdatePeriod;
		}
	}
	else
	{
		if (m_Target)
		{
			if (m_Target->IsActive())
			{
				t = g_time - m_LastUpdate;

				if (t >= m_UpdatePeriod)
				{
					CVector3f oldfwd, newfwd, tpos, pos, lead(0.0f, 0.0f, 0.0f);

					m_Q0 = m_Q1;

					// Find new orientation, lead target a little
					m_RenderObj.GetFrame(0)->GetForward(&oldfwd);
					m_Target->GetPosition(&tpos, 0);
					m_Target->GetVelocity(&lead);
					Vec3fScale(&lead, &lead, m_UpdatePeriod);
					Vec3fAdd(&tpos, &tpos, &lead);
					GetPosition(&pos, 0);
					Vec3fSubtract(&newfwd, &tpos, &pos);
					Vec3fNormalize(&newfwd, &newfwd);

					QuatRotationArc(&q, &oldfwd, &newfwd);
					QuatCrossProduct(&m_Q1, &q, &m_Q1);

					m_LastUpdate += m_UpdatePeriod;
					t = g_time - m_LastUpdate;
				}

				QuatSlerp(&q, &m_Q0, &m_Q1, t * m_SlerpScale);
				m_RenderObj.GetFrame(0)->SetOrientation(&q);
			}
			else
				m_Target = 0;
		}
	}

   // Move the shot forward
   MoveForward(m_Velocity * g_FrameTime, 0);

   // Update the ambient sound
   GetPosition(&m_CurPosition, 0);
   CVector3f Velocity;
   Velocity.x = (m_CurPosition.x - m_LastPosition.x) / g_FrameTime;
   Velocity.y = (m_CurPosition.y - m_LastPosition.y) / g_FrameTime;
   Velocity.z = (m_CurPosition.z - m_LastPosition.z) / g_FrameTime;
   m_MissileInAir->UpdateSound(m_CurPosition, Velocity);
   m_LastPosition = m_CurPosition;

   CGameObject::Update();
}