예제 #1
0
void Scheduler::printSchedule(Request _job, std::queue<Request> _resources){
	std::cout << "Scheduled job for " << _job.size << " resources: ";
	double resourceAvailability = 0;
	while (!_resources.empty()) {
		std::cout << _resources.front().size << ", ";
		resourceAvailability += waitTime(_resources.front());
		_resources.pop();
	}
	std::cout << " job wait time: " << waitTime(_job);
	std::cout << " . Resource available time: " << resourceAvailability;
	std::cout << std::endl;
}
int main(int argc, char *argv[]) {
	init_imgproc();
	Viewer *view = viewOpen(200, 200, "Sails");
	Image *img = imgFromBitmap(argv[1]);
	
	for (int x = 0; x < img -> width; x++) {
		for (int y = 0; y < img -> height; y++) {
			char * pixel = imgGetPixel(img, x, y);
			char red = pixel[2];
			char green = pixel[1];
			char blue = pixel[0];
			
			if (red > green && red > blue) {
				imgSetPixel(img, x, y, 255, 0, 0);
			} else if (green > red && green > blue) {
				imgSetPixel(img, x, y, 0, 255, 0);
			} else {
				imgSetPixel(img, x, y, 0, 0, 255);
		
			}
		}
	}

	viewDisplayImage(view, img);
	waitTime(5000); 
	imgDestroy(img);
	viewClose(view);
	quit_imgproc();
	return 0;
}
예제 #3
0
// ********************************************************************************************** //
//                                                                                                //
// ********************************************************************************************** //
int inputLib::waitScapeTime(int wait_period) {
	int now_time = 0;

	waitTime(50);
	now_time = timer.getTimer();
	wait_period = now_time + wait_period;

	while (now_time < wait_period) {
		readInput();
		if (p1_input[BTN_START] == 1 || p2_input[BTN_START] == 1) {
			return 1;
        } else if (p1_input[BTN_QUIT] == 1 || p2_input[BTN_QUIT] == 1) {
#if !defined(PLAYSTATION2) && !defined(PSP) && !defined(WII) && !defined(DREAMCAST)
            std::cout << "LEAVE #2" << std::endl;
            std::fflush(stdout);
            gameControl.leave_game();
#endif
		}
		now_time = timer.getTimer();
		#ifdef PLAYSTATION
			RotateThreadReadyQueue(_MIXER_THREAD_PRIORITY);
		#endif
        SDL_Delay(5);
	}
	return 0;
}
예제 #4
0
void RemoteUDPListener::run()
{
	poco_assert (_stopped);

	Poco::Buffer<char> buffer(BUFFER_SIZE);
	_stopped = false;
	Poco::Timespan waitTime(WAITTIME_MILLISEC* 1000);
	while (!_stopped)
	{
		try
		{
			if (_socket.poll(waitTime, Socket::SELECT_READ))
			{
				int byteCnt = _socket.receiveBytes(buffer.begin(), BUFFER_SIZE);
				if (byteCnt > 0)
				{
					_queue.enqueueNotification(new MessageNotification(std::string(buffer.begin(), byteCnt)));
				}
			}
		}
		catch (...)
		{
			// lazy exception catching
		}
	}
}
예제 #5
0
파일: z64viewer.c 프로젝트: wareya/gzrt
static void
draw(void)
{
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glEnable(GL_DEPTH_TEST);
  
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  gluLookAt(camera[3*4+0], camera[3*4+1], camera[3*4+2],
                camera[3*4+0]+camera[0*4+0],
                camera[3*4+1]+camera[0*4+1],
                camera[3*4+2]+camera[0*4+2],
                camera[2*4+0],
                camera[2*4+1],
                camera[2*4+2]);

  glPushMatrix();
  // draw z64 stuff
  RDRAM=databuffer;
  if(mode==0)
  {
      ProcessDisplayListSW(entrypoint);
  }
  else if(mode>0)
  {
      DrawLinks();
  }
     
  glPopMatrix();

  SDL_GL_SwapBuffers();
  waitTime(20);

  Frames++;
}
예제 #6
0
파일: rt_tmon.c 프로젝트: Strongc/proview
int
main (
  int			argc,
  char			**argv
)
{
  pwr_tStatus		sts;
  pwr_tTime		time;
  pwr_tTime		now;
  int			sec,nsec;

#ifdef OS_VMS
  sts = lib$get_ef(&timerFlag);
  if (EVEN(sts)) exit(sts);
#endif

  for (sec=0,nsec=10000000;;) {
    nowTime(&now);
#if 0    
    now.tv_sec = sec;
    now.tv_nsec = nsec;
#endif
    printf("%d:%d\n", now.tv_sec, now.tv_nsec);
    waitTime(&now);
    nsec += 10000000;
    sec += nsec / 1000000000;
    nsec %= 1000000000;
  }
}
예제 #7
0
bool timedWaitOnMutex(boost::condition_variable &waitCond, boost::mutex &waitMutex, int secs, int msecs)
{
	boost::posix_time::ptime waitTime(boost::posix_time::microsec_clock::universal_time());
	waitTime += boost::posix_time::seconds(secs);
	waitTime += boost::posix_time::millisec(msecs);

	boost::unique_lock<boost::mutex> lock(waitMutex);
	return waitCond.timed_wait(lock, waitTime) == false;
}
예제 #8
0
void EventsDispatcher::run_events_loop()
{
    boost::posix_time::milliseconds waitTime(5);   //5ms

    while (!stop_event_received())
    {
        if (pending_events())
            dispatch_next_event();
        else
            boost::this_thread::sleep(waitTime);
    }
}
예제 #9
0
파일: station2.c 프로젝트: FEx79/3eme
/**
 * Realise le parcourt avec la piece courante
 */
void processPiece()
{
    // Attend que la station 1 nous ai donne une piece
    printf("Attend que la station 1 nous ai donne une piece ...\n");
    while(!getPieceReceived())
        waitTime(500);
    
    printf("Attend que la piece soit en place ...\n");
    waitBit(PIECE, TRUE);
    waitTime(1000);
    
    // Regarde si c'est une piece metallique
    pieceMetal = getCapteur(PIECE_METAL);
    if(pieceMetal) {
        printf("--->>> Piece en métal\n");
        SendTo(station_3, ADDR_STATION_3, PORT_LISTEN_3_2, "PIECE_METAL", 11);
    }
    
    // Monte l'ascenseur
    printf("Monte l'ascensseur ...\n");
    setActuateur(ASC_DESCEND, OFF);
    setActuateur(ASC_MONTE, ON);
    waitBit(ASC_HAUT, TRUE);
    setActuateur(ASC_MONTE, OFF);
    
    waitTime(1000);
    
    // Piece noire
    pieceNoire = !getCapteur(HAUTEUR_PIECE);
    if(pieceNoire && !pieceMetal) {
        printf("--->>> Piece noire\n");
        SendTo(station_3, ADDR_STATION_3, PORT_LISTEN_3_2, "PIECE_NOIRE", 11);
    }
    else if(!pieceMetal) {
        printf("--->>> Piece rouge\n");
        SendTo(station_3, ADDR_STATION_3, PORT_LISTEN_3_2, "PIECE_ROUGE", 11);
    }
    
    // Attend que la station 3 soit en reception
    printf("Attend que la station 3 soit prete a recevoir une piece ...\n");
    while(!getCanGivePiece())
        waitTime(500);
    
    // Active le pousseur
    printf("Active le pousseur de piece ...\n");
    setActuateur(PP, ON);
    waitTime(1000);
    setActuateur(PP, OFF);
    
    // Active le coussin
    printf("Active le coussin d'air ...\n");
    setActuateur(COUSSIN_AIR, ON);
    waitTime(2000);
    setActuateur(COUSSIN_AIR, OFF);
    
    // Previens la station 3 qu'on lui donne une piece
    printf("Previens la station 3 qu'on lui donne une piece ...\n");
    SendTo(station_3, ADDR_STATION_3, PORT_LISTEN_3_2, "DONNE_PIECE", 11);
    setCanGivePiece(FALSE);
}
예제 #10
0
void inputLib::wait_keypress()
{
    bool fim = false;
    while (!fim) {
        readInput();
		if (p1_input[BTN_START] == 1 || p2_input[BTN_JUMP] == 1 || p1_input[BTN_JUMP] == 1 || p2_input[BTN_JUMP]) {
            fim = true;
        }
        graphLib.updateScreen();
        waitTime(50);
    }
    clean();
}
예제 #11
0
void inputLib::pick_key_or_button(INPUT_COMMANDS key)
{
    clean();
    waitTime(50);
    while (true) { // keep reading until a key is found
        while (SDL_PollEvent(&event)) {
            if (game_config.input_type == INPUT_TYPE_DOUBLE || game_config.input_type == INPUT_TYPE_KEYBOARD) {
                if (event.type == SDL_KEYDOWN) {
                    game_config.keys_codes[key] = event.key.keysym.sym;
                    return;
                }
                SDL_PumpEvents();
            }
            if (game_config.input_type == INPUT_TYPE_DOUBLE || game_config.input_type == INPUT_TYPE_JOYSTICK) {
                if (event.type == SDL_JOYBUTTONDOWN) {
                    game_config.button_codes[key] = event.jbutton.button;
                    return;
                }
            }
        }
        waitTime(5);
    }
}
예제 #12
0
float turnCreate(int velocity, int angle_max)
{
	int angle=0;

std::cout << "distance & angle init" << std::endl;
std::cout << getDistance() << std::endl;
std::cout << getAngle() << std::endl;

	waitTime(1.0);
	drive(velocity, 1);
	while(1)
	{
		angle += getAngle();
		if(fabs(angle) >= fabs(angle_max))
		{
			drive(0,0);
			break;
		}
	}
	waitTime(0.2);
	if(angle >0 )
	{
			std::cout <<"turn------------------------:" << P_TURN_A100 * angle * angle + P_TURN_B100 * angle + P_TURN_C100+ angle << std::endl;
			return P_TURN_A100 * angle * angle + P_TURN_B100 * angle + P_TURN_C100 + angle;
	}
	else if(angle == 0)
	{
			std::cout <<"turn------------------------:" << P_TURN_A100 * angle << std::endl;
			return P_TURN_A100 * angle;
	}
	else
	{
			std::cout <<"turn------------------------:" << N_TURN_A100*angle + N_TURN_B100 << std::endl;
			return N_TURN_A100 * angle * angle + N_TURN_B100 * angle + N_TURN_C100 + angle;
	}
}
예제 #13
0
int htThreadItf::Execute()
{
	// Notify that thread has started
	onStart();
	
	// Loop until termination requested
	while( !IsTerminating() ) {
		mMutex.Acquire();
		if( run() ) break;
		mMutex.Release();
		Sleep( waitTime() );
	}
	
	// Notify that thread is ending
	onStop();
}
예제 #14
0
bool EventValidator::waitUntilEvent(const char* szEvent, int iTimeoutInSecs)
{
   bool bFound = false;
   OsTime waitTime(iTimeoutInSecs == DEFAULT_TIMEOUT ? m_iDefaultTimeoutInSecs : iTimeoutInSecs, 0);
   OsTime now;
   OsTime start;
   OsDateTime::getCurTime(start);

   // Try to find message
   int i = 0;
   while (true)
   {
      m_mutLists.acquire();

      UtlString* pString = (UtlString*) m_unprocessedEvents.at(i);
      if (pString && pString->compareTo(szEvent) == 0)
      {
         m_processedEvents.append(pString);
         for (int j = 0; j < i+1; j++)
         {
            m_unprocessedEvents.removeAt(0);
         }
         bFound = true;
         m_mutLists.release();
         break;
      }
      if (pString)
      {
         i++;
      }
      m_mutLists.release();

      OsTask::delay(100);
      OsDateTime::getCurTime(now);
      OsTime diff = now - start;
      if (diff > waitTime)
      {
         break;
      }
   }

   m_mutLists.release();

   return bFound;
}
예제 #15
0
bool EventValidator::waitForEvent(const char* szEvent, bool bStrictOrderMatch, int iTimeoutInSecs)
{
   bool bFound = false;
   OsTime waitTime(iTimeoutInSecs == DEFAULT_TIMEOUT ? m_iDefaultTimeoutInSecs : iTimeoutInSecs, 0);
   int nMaxLookAhead = bStrictOrderMatch ? 1 : m_iMaxLookAhead;
   int nActualLookAhead = 0;
   bool bTimedOut = false;

   bFound = findEvent(szEvent, nMaxLookAhead, nActualLookAhead);
   while (!bFound && !bTimedOut && (nActualLookAhead < nMaxLookAhead))
   {            
      if (m_semUnprocessed.acquire(waitTime) != OS_SUCCESS)
      {
         bTimedOut = true;
      }            
      bFound = findEvent(szEvent, nMaxLookAhead, nActualLookAhead);
   }

   if (!bFound)
   {
      m_pUnfoundEvent = new UtlString(szEvent);
   }

   if (!bFound)            
   {
      if (bTimedOut)
      {
         m_eErrorType = EVENT_VALIDATOR_ERROR_TIMEOUT;
      }
      else
      {
         m_eErrorType = EVENT_VALIDATOR_ERROR_MISMATCH;
      }
   }


   // A Bit of a hack: In some of the unit tests, we have a race between the event matcher
   // and autoXXXX handlers. 
   OsTask::delay(20);

   return bFound;
}
예제 #16
0
//! Computes the spectrum
bool SpectrumRecorder::compute(string file)
{
    mOut.fill(0);
    mComputed = false;

    setUrl(file);
    play();

    boost::posix_time::seconds waitTime(1);

    //mSwitchLock.lock();
    while(!mComputed)
    {
        //mSwitchLock.unlock();
        boost::this_thread::sleep(waitTime);
        //mSwitchLock.lock();
    }
    //mSwitchLock.unlock();

    return true;
}
예제 #17
0
파일: main.cpp 프로젝트: intialonso/cmst
int main(int argc, char *argv[])
{
  QApplication::setApplicationName(LONG_NAME);
  QApplication::setApplicationVersion(VERSION);
  QApplication::setOrganizationName(ORG);
  QApplication::setDesktopSettingsAware(true);
  QApplication app(argc, argv);

  // make sure only one instance is running
  QLocalSocket* socket = new QLocalSocket();
  socket->connectToServer(SOCKET_NAME);
  bool b_connected = socket->waitForConnected(500);
  socket->abort();
  delete socket;
  if (b_connected) {
    qDebug() <<  QCoreApplication::translate("main.cpp", "Another running instance of CMST has been detected.  This instance is aborting");
    return 1;
  }

  // setup the command line parser
  QCommandLineParser parser;
  parser.setApplicationDescription(QApplication::translate("main.cpp", "Connman System Tray.") );

  QCommandLineOption bypassState(QStringList() << "b" << "bypass-restore-state",
		QCoreApplication::translate("main.cpp", "Bypass restoring the window state if restoring window state is specified in the settings file.") );
  parser.addOption(bypassState);

  QCommandLineOption bypassStartOptions(QStringList() << "B" << "bypass-start-options",
		QCoreApplication::translate("main.cpp", "Bypass restoring any start options in the settings file.") );
  parser.addOption(bypassStartOptions);

  QCommandLineOption disableCounters(QStringList() << "c" << "disable-counters",
		QCoreApplication::translate("main.cpp", "[Experimental] Disable data counters.  May be used to minimize load on your system.") );
  parser.addOption(disableCounters);

  QCommandLineOption disableTrayIcon(QStringList() << "d" << "disable-tray-icon",
		QCoreApplication::translate("main.cpp", "Disable the system tray icon.  May be needed for system trays not compliant with the Freedesktop.org system tray specification.") );
  parser.addOption(disableTrayIcon);

  parser.addHelpOption();

  QCommandLineOption useIconTheme(QStringList() << "i" << "icon-theme",
		QCoreApplication::translate("main.cpp", "Use an icon theme from your system."),
		QCoreApplication::translate("main.cpp", "Icon Theme Name"),
		QString() );
  parser.addOption(useIconTheme);

  QCommandLineOption logInputRequest(QStringList() << "l" << "log-input-request",
		QCoreApplication::translate("main.cpp", "Log the connman inputRequest for debugging purposes.") );
  parser.addOption(logInputRequest);

  QCommandLineOption startMinimized(QStringList() << "m" << "minimized",
		QCoreApplication::translate("main.cpp", "Start the GUI minimized in the system tray.") );
  parser.addOption(startMinimized);

  parser.addVersionOption();

  QCommandLineOption waitTime(QStringList() << "w" << "wait-time",
		QCoreApplication::translate("main.cpp", "Specify the wait time in seconds before starting the system tray icon."),
		QCoreApplication::translate("main.cpp", "seconds"),
		"0");
  parser.addOption(waitTime);

  QCommandLineOption counterUpdateKb (QStringList() << "counter-update-kb",
		QCoreApplication::translate("main.cpp", "[Experimental] The number of kb that have to be transmitted before the counter updates."),
		QCoreApplication::translate("main.cpp", "KB"),
		"1024" );
  parser.addOption(counterUpdateKb);

  QCommandLineOption counterUpdateRate (QStringList() << "counter-update-rate",
		QCoreApplication::translate("main.cpp", "[Experimental] The interval in seconds between counter updates."),
		QCoreApplication::translate("main.cpp", "seconds"),
		"10" );
  parser.addOption(counterUpdateRate);

	// Added on 2015.01.04 to work around QT5.4 bug with transparency not always working
  QCommandLineOption fakeTransparency(QStringList() << "fake-transparency",
		QCoreApplication::translate("main.cpp", "If tray icon fake transparency is required, specify the background color to use (format: 0xRRGGBB)"),
		QCoreApplication::translate("main.cpp", "RRGGBB"),
		"0x222222" );
  parser.addOption(fakeTransparency);

  // Added on 2014.11.24 to work around a bug where QT5.3 won't show an icon in XFCE,  My fix may not work, but keep it in for now.  If this gets fixed in
  // QT5.4 keep the command line option so users start up commands don't break, but make it a NOP.
  QCommandLineOption useXFCE(QStringList() << "use-xfce",
		QCoreApplication::translate("main.cpp", "Use XFCE specific code.") );
  parser.addOption(useXFCE);

  // Added on 2014.12.16 to work around a similar bug where QT5.3 won't show an icon in MATE.
  QCommandLineOption useMATE(QStringList() << "use-mate",
		QCoreApplication::translate("main.cpp", "Use MATE DE specific code.") );
  parser.addOption(useMATE);

  // Setup translations
  QTranslator qtTranslator;
  qtTranslator.load("qt_" + QLocale::system().name(),
  QLibraryInfo::location(QLibraryInfo::TranslationsPath));
  app.installTranslator(&qtTranslator);

  QTranslator cmstTranslator;
  if (cmstTranslator.load("cmst_" + QLocale::system().name(), ":/translations/translations" ) ) {
		app.installTranslator(&cmstTranslator);
	}
	// else use en_US as it contains Connman strings properized and some singular/plural strings
	else if (cmstTranslator.load("cmst_en_US", ":/translations/translations" ) ) {
		app.installTranslator(&cmstTranslator);
	}

  // Make sure all the command lines can be parsed
  // using parse() instead of process() as process stops on an error if an option needs a value
  // and it is not specified, even if we provide a default.  We're supposed to catch errors if we
  // use parse(), but parse.errorText() returns an empty string on this.  Bag the error checking
  // for now.
  parser.parse(QCoreApplication::arguments() );
  QStringList sl = parser.unknownOptionNames();
  if (sl.size() > 0 ) parser.showHelp(1);
  if (parser.isSet("help") ) parser.showHelp(1);
	if (parser.isSet("version") ) {
#if QT_VERSION >= 0x050400
		parser.showVersion();
#else
		QTextStream out(stdout);
		out << qPrintable(LONG_NAME) << " " << qPrintable(VERSION) << endl;
		return 0;
#endif
	}

  // signal handler
  signal(SIGINT, signalhandler);

  // Showing the dialog (or not) is controlled in the createSystemTrayIcon() function
  // called from the ControlBox constructor.  We don't show it from here.
  ControlBox ctlbox(parser);
  return app.exec();
}
void PetControlDeviceImplementation::callObject(CreatureObject* player) {
	if (player->isInCombat() || player->isDead() || player->isIncapacitated() || player->getPendingTask("tame_pet") != NULL) {
		player->sendSystemMessage("@pet/pet_menu:cant_call"); // You cannot call this pet right now.
		return;
	}

	if (player->isRidingMount()) {
		player->sendSystemMessage("@pet/pet_menu:mounted_call_warning"); // You cannot call a pet while mounted or riding a vehicle.
		return;
	}

	if (player->getParent() != NULL) {
		ManagedReference<SceneObject*> strongRef = player->getParentRecursively(SceneObjectType::BUILDING);
		ManagedReference<BuildingObject*> building;

		if (strongRef != NULL)
			building = strongRef.castTo<BuildingObject*>();

		if (building == NULL || building->isPrivateStructure()) {
			player->sendSystemMessage("@pet/pet_menu:private_house"); // You cannot call pets in a private building.
			return;
		}
	}

	if (!isASubChildOf(player))
		return;

	ManagedReference<TangibleObject*> controlledObject = this->controlledObject.get();

	if (controlledObject == NULL || !controlledObject->isAiAgent())
		return;

	ManagedReference<AiAgent*> pet = cast<AiAgent*>(controlledObject.get());
	ManagedReference<PlayerObject*> ghost = player->getPlayerObject();

	if (ghost->hasActivePet(pet))
		return;

	if (vitality <= 0) {
		player->sendSystemMessage("@pet/pet_menu:dead_pet"); // This pet is dead. Select DESTROY from the radial menu to delete this pet control device.
		return;
	}

	unsigned int petFaction = pet->getFaction();

	if (petFaction != 0) {
		if (player->getFaction() == 0) {
			StringIdChatParameter message("@faction_perk:prose_be_declared"); // You must be declared to a faction to use %TT.
			message.setTT(pet->getDisplayedName());
			player->sendSystemMessage(message);
			return;
		}

		if (player->getFaction() != petFaction || ghost->getFactionStatus() == FactionStatus::ONLEAVE) {
			StringIdChatParameter message("@faction_perk:prose_be_declared_faction"); // You must be a declared %TO to use %TT.
			message.setTO(pet->getFactionString());
			message.setTT(pet->getDisplayedName());
			player->sendSystemMessage(message);
			return;
		}
	}

	if(player->getPendingTask("call_pet") != NULL) {
		StringIdChatParameter waitTime("pet/pet_menu", "call_delay_finish_pet"); // Already calling a Pet: Call will be finished in %DI seconds.
		Time nextExecution;
		Core::getTaskManager()->getNextExecutionTime(player->getPendingTask("call_pet"), nextExecution);
		int timeLeft = (nextExecution.getMiliTime() / 1000) - System::getTime();
		waitTime.setDI(timeLeft);

		player->sendSystemMessage(waitTime);
		return;
	}

	if (!growPet(player))
		return;

	int currentlySpawned = 0;
	int spawnedLevel = 0;
	int maxPets = 1;
	int maxLevelofPets = 10;
	int level = pet->getLevel();

	if (petType == PetManager::CREATUREPET) {
		bool ch = player->hasSkill("outdoors_creaturehandler_novice");

		if (ch) {
			maxPets = player->getSkillMod("keep_creature");
			maxLevelofPets = player->getSkillMod("tame_level");
		}

		if (level > maxLevelofPets) {
			player->sendSystemMessage("@pet/pet_menu:control_exceeded"); // Calling this pet would exceed your Control Level ability.
			return;
		}

		ManagedReference<Creature*> creaturePet = cast<Creature*>(pet.get());
		if (creaturePet != NULL && creaturePet->isVicious() && (player->getSkillMod("tame_aggro") <= 0 || !ch)) {
			player->sendSystemMessage("@pet/pet_menu:lack_skill"); // You lack the skill to call a pet of this type.
			return;
		}

	} else if (petType == PetManager::FACTIONPET){
		maxPets = 3;
	}

	for (int i = 0; i < ghost->getActivePetsSize(); ++i) {
		ManagedReference<AiAgent*> object = ghost->getActivePet(i);

		if (object != NULL) {
			if (object->isCreature() && petType == PetManager::CREATUREPET) {
				if (++currentlySpawned >= maxPets) {
					player->sendSystemMessage("@pet/pet_menu:at_max"); // You already have the maximum number of pets of this type that you can call.
					return;
				}

				spawnedLevel += object->getLevel();

				if ((spawnedLevel + level) > maxLevelofPets) {
					player->sendSystemMessage("@pet/pet_menu:control_exceeded"); // Calling this pet would exceed your Control Level ability.
					return;
				}
			} else if (object->isNonPlayerCreatureObject() && petType == PetManager::FACTIONPET) {
				if (++currentlySpawned >= maxPets) {
					player->sendSystemMessage("@pet/pet_menu:at_max"); // You already have the maximum number of pets of this type that you can call.
					return;
				}
			} else if (object->isDroidObject() && petType == PetManager::DROIDPET) {
				if (++currentlySpawned >= maxPets) {
					player->sendSystemMessage("@pet/pet_menu:at_max"); // You already have the maximum number of pets of this type that you can call.
					return;
				}
			}

		}
	}

	ManagedReference<TradeSession*> tradeContainer = player->getActiveSession(SessionFacadeType::TRADE).castTo<TradeSession*>();

	if (tradeContainer != NULL) {
		server->getZoneServer()->getPlayerManager()->handleAbortTradeMessage(player);
	}

	if(player->getCurrentCamp() == NULL && player->getCityRegion() == NULL) {

		Reference<CallPetTask*> callPet = new CallPetTask(_this.get(), player, "call_pet");

		StringIdChatParameter message("pet/pet_menu", "call_pet_delay"); // Calling pet in %DI seconds. Combat will terminate pet call.
		message.setDI(15);
		player->sendSystemMessage(message);

		player->addPendingTask("call_pet", callPet, 15 * 1000);

		if (petControlObserver == NULL) {
			petControlObserver = new PetControlObserver(_this.get());
			petControlObserver->deploy();
		}

		player->registerObserver(ObserverEventType::STARTCOMBAT, petControlObserver);

	} else { // Player is in a city or camp, spawn pet immediately

		if( player->getCooldownTimerMap() == NULL )
			return;

		// Check cooldown
		if( !player->getCooldownTimerMap()->isPast("petCallOrStoreCooldown") ){
			player->sendSystemMessage("@pet/pet_menu:cant_call_1sec"); //"You cannot CALL for 1 second."
			return;
		}

		Locker clocker(controlledObject, player);
		spawnObject(player);

		// Set cooldown
		player->getCooldownTimerMap()->updateToCurrentAndAddMili("petCallOrStoreCooldown", 1000); // 1 sec
	}

}
void RequestGenerator::performCallback(NodeID proc, SubBlock& data)
{
  Address address = data.getAddress();
  assert(proc == m_node);
  assert(address == m_address);  

  DEBUG_EXPR(TESTER_COMP, LowPrio, proc);
  DEBUG_EXPR(TESTER_COMP, LowPrio, m_status);
  DEBUG_EXPR(TESTER_COMP, LowPrio, address);
  DEBUG_EXPR(TESTER_COMP, LowPrio, data);

  if (m_status == RequestGeneratorStatus_Test_Pending) { 
    //    m_driver.recordTestLatency(g_eventQueue_ptr->getTime() - m_last_transition);
    if (data.readByte() == LockStatus_Locked) {
      // Locked - keep spinning
      m_status = RequestGeneratorStatus_Thinking;
      m_last_transition = g_eventQueue_ptr->getTime();
      g_eventQueue_ptr->scheduleEvent(this, waitTime());
    } else {
      // Unlocked - try the swap
      m_driver.recordTestLatency(g_eventQueue_ptr->getTime() - m_last_transition);
      m_status = RequestGeneratorStatus_Before_Swap;
      m_last_transition = g_eventQueue_ptr->getTime();
      g_eventQueue_ptr->scheduleEvent(this, waitTime());
    }
  } else if (m_status == RequestGeneratorStatus_Swap_Pending) {
    m_driver.recordSwapLatency(g_eventQueue_ptr->getTime() - m_last_transition);
    if (data.readByte() == LockStatus_Locked) {
      // We failed to aquire the lock
      m_status = RequestGeneratorStatus_Thinking;
      m_last_transition = g_eventQueue_ptr->getTime();
      g_eventQueue_ptr->scheduleEvent(this, waitTime());
    } else {
      // We acquired the lock
      data.writeByte(LockStatus_Locked);
      m_status = RequestGeneratorStatus_Holding;
      m_last_transition = g_eventQueue_ptr->getTime();
      DEBUG_MSG(TESTER_COMP, HighPrio, "Acquired");
      DEBUG_EXPR(TESTER_COMP, HighPrio, proc);
      DEBUG_EXPR(TESTER_COMP, HighPrio, g_eventQueue_ptr->getTime());
      g_eventQueue_ptr->scheduleEvent(this, holdTime());
    }
  } else if (m_status == RequestGeneratorStatus_Release_Pending) {
    m_driver.recordReleaseLatency(g_eventQueue_ptr->getTime() - m_last_transition);
    // We're releasing the lock
    data.writeByte(LockStatus_Unlocked);

    m_counter++;
    if (m_counter < g_param_ptr->TESTER_LENGTH()) {
      m_status = RequestGeneratorStatus_Thinking;
      m_last_transition = g_eventQueue_ptr->getTime();
      pickAddress();
      g_eventQueue_ptr->scheduleEvent(this, thinkTime());
    } else {
      m_driver.reportDone();
      m_status = RequestGeneratorStatus_Done;
      m_last_transition = g_eventQueue_ptr->getTime();
    } 
  } else {
    WARN_EXPR(m_status);
    ERROR_MSG("Invalid status");
  }
}
void VehicleControlDeviceImplementation::generateObject(CreatureObject* player) {
	if (player->isDead() || player->isIncapacitated())
		return;

	if (!isASubChildOf(player))
		return;

	if (player->getParent() != NULL || player->isInCombat()) {
		player->sendSystemMessage("@pet/pet_menu:cant_call_vehicle"); // You can only unpack vehicles while Outside and not in Combat.
		return;
	}

	ManagedReference<TangibleObject*> controlledObject = this->controlledObject.get();

	if (controlledObject == NULL)
		return;

	if (controlledObject->isInQuadTree())
		return;

	ManagedReference<TradeSession*> tradeContainer = player->getActiveSession(SessionFacadeType::TRADE).castTo<TradeSession*>();

	if (tradeContainer != NULL) {
		server->getZoneServer()->getPlayerManager()->handleAbortTradeMessage(player);
	}

	if(player->getPendingTask("call_mount") != NULL) {
		StringIdChatParameter waitTime("pet/pet_menu", "call_delay_finish_vehicle");
		Time nextExecution;
		Core::getTaskManager()->getNextExecutionTime(player->getPendingTask("call_mount"), nextExecution);
		int timeLeft = (nextExecution.getMiliTime() / 1000) - System::getTime();
		waitTime.setDI(timeLeft);

		player->sendSystemMessage(waitTime);
		return;
	}

	ManagedReference<SceneObject*> datapad = player->getSlottedObject("datapad");

	if (datapad == NULL)
		return;

	int currentlySpawned = 0;

	for (int i = 0; i < datapad->getContainerObjectsSize(); ++i) {
		ManagedReference<SceneObject*> object = datapad->getContainerObject(i);

		if (object->isVehicleControlDevice()) {
			VehicleControlDevice* device = cast<VehicleControlDevice*>( object.get());

			ManagedReference<SceneObject*> vehicle = device->getControlledObject();

			if (vehicle != NULL && vehicle->isInQuadTree()) {
				if (++currentlySpawned > 2)
					player->sendSystemMessage("@pet/pet_menu:has_max_vehicle");

				return;
			}
		}
	}

	if(player->getCurrentCamp() == NULL && player->getCityRegion() == NULL) {

		Reference<CallMountTask*> callMount = new CallMountTask(_this.getReferenceUnsafeStaticCast(), player, "call_mount");

		StringIdChatParameter message("pet/pet_menu", "call_vehicle_delay");
		message.setDI(15);
		player->sendSystemMessage(message);

		player->addPendingTask("call_mount", callMount, 15 * 1000);

		if (vehicleControlObserver == NULL) {
			vehicleControlObserver = new VehicleControlObserver(_this.getReferenceUnsafeStaticCast());
			vehicleControlObserver->deploy();
		}

		player->registerObserver(ObserverEventType::STARTCOMBAT, vehicleControlObserver);

	} else {

		Locker clocker(controlledObject, player);
		spawnObject(player);
	}

}
예제 #21
0
/**
 * Process OI Op Codes passed by controller
 */
void OpenInterface::handleOpCode(byte oc)
{
#ifdef DEBUG_SERIAL
  switch (oc)
  {
    case ('s'):
        oc = OC_SAFE;
    break;
    case ('d'):
        oc = OC_DIRECT_DRIVE;
    break;
    case ('g'):
        oc = OC_SENSORS;
    break;
  }
#endif
  switch (oc)
  {

     case(OC_LOW_SIDE_DRIVERS):
       callCallbackWithOneByte(controlLsdOutputCallback);
     break;

     case(OC_LEDS):
       callCallbackWithThreeBytes(controlLedsCallback);
     break;

     case(OC_PWM_LOW_SIDE_DRIVERS):
       callCallbackWithThreeBytes(controlLsdPwmCallback);
     break;

     case(OC_DIGITAL_OUTPUTS):
       callCallbackWithOneByte(controlDigitalOutputCallback);
     break;

     case(OC_STREAM):
         stream();
     break;

     case(OC_PAUSE_RESUME_STREAM):
     break;

     case(OC_SEND_IR):
       callCallbackWithOneByte(sendIrCallback);
     break;

     case(OC_SHOW_SCRIPT):
       showScript();
     break;

     case(OC_WAIT_EVENT):
       callCallbackWithOneByte(waitEventCallback);
     break;

     case(OC_PLAY_SCRIPT):
        scriptPlay();
     break;

     case(OC_SCRIPT):
       scriptSet();
     break;

     case(OC_WAIT_ANGLE):
         if (waitAngleCallback)
         {
           waitAction(waitAngleCallback);
         }
     break;

     case(OC_WAIT_DISTANCE):
         if (waitDistanceCallback)
         {
           waitAction(waitDistanceCallback);
         }
     break;

     case(OC_WAIT_TIME):
       waitTime();
     break;

     case(OC_DEMO):
     case(OC_SPOT):
     case(OC_COVER):
     case(OC_COVER_AND_DOCK):
       // These are all demo codes. Implement?
     break;

     case(OC_QUERY_LIST):
       queryList();
     break;

     case (OC_START):
       sensor[OI_SENSOR_OI_MODE] = OI_MODE_PASSIVE;
     break;

     case (OC_BAUD):
     break;

     case (OC_CONTROL):
     case (OC_SAFE):
       sensor[OI_SENSOR_OI_MODE] = OI_MODE_SAFE;
     break;

     case (OC_SENSORS):
       getSensors();
     break;

     case (OC_SONG):
       song();
     break;

     case(OC_PLAY_SONG):
       songPlay();
     break;

     case (OC_DIRECT_DRIVE):
       driveDirect();
     break;

     case (OC_DRIVE):
       drive();
     break;

     case (OC_FULL):
       sensor[OI_SENSOR_OI_MODE] = OI_MODE_FULL;
     break;
  }
}
예제 #22
0
파일: z64viewer.c 프로젝트: wareya/gzrt
void draw_from_data ( struct Data * k )
{
  SDL_Surface *screen;
  int done;
  Uint8 *keys;
  int mousebutton,mouseX,mouseY;
  int grabbed=false;
  SDL_Init(SDL_INIT_VIDEO);

  screen = SDL_SetVideoMode(640, 480, 32, SDL_OPENGL|SDL_RESIZABLE);
  if ( ! screen ) {
    fprintf(stderr, "Couldn't set 300x300 GL video mode: %s\n", SDL_GetError());
    SDL_Quit();
    exit(2);
  }
  SDL_WM_SetCaption("Z64Viewer", "z64viewer");
  SDL_ShowCursor(SDL_DISABLE);
  SDL_WM_GrabInput(SDL_GRAB_ON);
  grabbed=true;
  
  
  GLenum err = glewInit();
  
  memset(databuffer,0, 8*1024*1024);
      
  entrypoint = k->ep;

  LoadResourceZ_bin(k->data, k->size, 0, 0);
  LoadResourceZ(
      "resources/gameplay_keep.zdata"
      
      , 1024*1024, 4);
  

    camera[0] = 1; camera[1]=0; camera[2]=0; camera[3]=0; // Forward
    camera[4] = 0; camera[5]=0; camera[6]=1; camera[7]=0; // Right
    camera[8] = 0; camera[9]=1; camera[10]=0; camera[11]=0; // Up
    camera[12] = -1000; camera[13]=0; camera[14]=0; camera[15]=0; // Position
  reshape(screen->w, screen->h);
  done = 0;
  while ( ! done ) {
    SDL_Event event;

    idle();
    while ( SDL_PollEvent(&event) ) {
      switch(event.type) {
        case SDL_VIDEORESIZE:
          screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 16,
                                    SDL_OPENGL|SDL_RESIZABLE);
          if ( screen ) {
            reshape(screen->w, screen->h);
          } else {
            printf("Problem...\n");
          }
          break;
      }
    }

    keys = SDL_GetKeyState(NULL);

    if ( keys[SDLK_ESCAPE] ) {
      if(grabbed)
      {
          SDL_WM_GrabInput(SDL_GRAB_OFF);
          SDL_ShowCursor(SDL_ENABLE);
          grabbed=false;          
          waitTime(200); // Wait a bit so we don't exit by mistake
      }
      else
      {      
      done = 1;
      }
    }

    mousebutton=SDL_GetRelativeMouseState(&mouseX,&mouseY);
    
    GLfloat viewMatrix[16] = { 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 };
    
    if(grabbed)
    {
        if((mousebutton&1) && (mousebutton&4))
        {
            matrixRotate(viewMatrix, mouseX/600.0f*360.0f, camera[0*4+0],camera[0*4+1],camera[0*4+2]);
            
            multM4Vect(&camera[0*4], viewMatrix, &camera[0*4]);
            multM4Vect(&camera[1*4], viewMatrix, &camera[1*4]);
            multM4Vect(&camera[2*4], viewMatrix, &camera[2*4]);
        }
        else
        {
            matrixRotate(viewMatrix, -mouseX/600.0f*360.0f, camera[2*4+0], camera[2*4+1],camera[2*4+2]);
            matrixRotate(viewMatrix, -mouseY/600.0f*360.0f, camera[1*4+0], camera[1*4+1],camera[1*4+2]);
            
            multM4Vect(&camera[0*4], viewMatrix, &camera[0*4]);
            multM4Vect(&camera[1*4], viewMatrix, &camera[1*4]);
        
            if(mousebutton&1)
            {
                camera[3*4+0]+=camera[0*4+0]*20;
                camera[3*4+1]+=camera[0*4+1]*20;
                camera[3*4+2]+=camera[0*4+2]*20;
                camera[3*4+3]+=camera[0*4+3]*20;
            }
    
          
            if(mousebutton&4)
            {
                camera[3*4+0]-=camera[0*4+0]*20;
                camera[3*4+1]-=camera[0*4+1]*20;
                camera[3*4+2]-=camera[0*4+2]*20;
                camera[3*4+3]-=camera[0*4+3]*20;
            }


            
            if(keys[SDLK_d])
            {
                camera[3*4+0]+=camera[1*4+0]*20;
                camera[3*4+1]+=camera[1*4+1]*20;
                camera[3*4+2]+=camera[1*4+2]*20;
                camera[3*4+3]+=camera[1*4+3]*20;
            }
            if(keys[SDLK_a])
            {
                camera[3*4+0]-=camera[1*4+0]*20;
                camera[3*4+1]-=camera[1*4+1]*20;
                camera[3*4+2]-=camera[1*4+2]*20;
                camera[3*4+3]-=camera[1*4+3]*20;
            }
            if(keys[SDLK_w])
            {
                camera[3*4+0]+=camera[2*4+0]*20;
                camera[3*4+1]+=camera[2*4+1]*20;
                camera[3*4+2]+=camera[2*4+2]*20;
                camera[3*4+3]+=camera[2*4+3]*20;
            }
            if(keys[SDLK_s])
            {
                camera[3*4+0]-=camera[2*4+0]*20;
                camera[3*4+1]-=camera[2*4+1]*20;
                camera[3*4+2]-=camera[2*4+2]*20;
                camera[3*4+3]-=camera[2*4+3]*20;
            }

//FASTER
            if(mousebutton&4 && mousebutton&2)
            {
                camera[3*4+0]-=camera[0*4+0]*200;
                camera[3*4+1]-=camera[0*4+1]*200;
                camera[3*4+2]-=camera[0*4+2]*200;
                camera[3*4+3]-=camera[0*4+3]*200;
            }
        if(mousebutton&1 && mousebutton&2)
            {
                camera[3*4+0]+=camera[0*4+0]*200;
                camera[3*4+1]+=camera[0*4+1]*200;
                camera[3*4+2]+=camera[0*4+2]*200;
                camera[3*4+3]+=camera[0*4+3]*200;
            }

            if(keys[SDLK_i])
            {
                camera[3*4+0]+=camera[2*4+0]*200;
                camera[3*4+1]+=camera[2*4+1]*200;
                camera[3*4+2]+=camera[2*4+2]*200;
                camera[3*4+3]+=camera[2*4+3]*200;
            }
        if(keys[SDLK_k])
            {
                camera[3*4+0]-=camera[2*4+0]*200;
                camera[3*4+1]-=camera[2*4+1]*200;
                camera[3*4+2]-=camera[2*4+2]*200;
                camera[3*4+3]-=camera[2*4+3]*200;
            }
        
            if(keys[SDLK_j])
            {
                camera[3*4+0]-=camera[1*4+0]*200;
                camera[3*4+1]-=camera[1*4+1]*200;
                camera[3*4+2]-=camera[1*4+2]*200;
                camera[3*4+3]-=camera[1*4+3]*200;
            }

            if(keys[SDLK_l])
            {
                camera[3*4+0]+=camera[1*4+0]*200;
                camera[3*4+1]+=camera[1*4+1]*200;
                camera[3*4+2]+=camera[1*4+2]*200;
                camera[3*4+3]+=camera[1*4+3]*200;
            }
//FASTER END 

        }            
    }
    else
    {
        if(mousebutton)
        {
            SDL_ShowCursor(SDL_DISABLE);
            SDL_WM_GrabInput(SDL_GRAB_ON);
            grabbed=true;
        }
    }    
    draw();
    
    if(__quit)
        break;
  }
  SDL_Quit();
  __quited=1;
  return;             /* ANSI C requires main to return int. */
}
TVerdict CDelayedGetSessionStep::doTestStepL()
	{
	TInt sessionDelay;
	sessionDelay = ReadGetSessionDelayL();
	
	// first we have to retrieve the available cipher suites
	TInt err = GetCipherSuitesL();  
	TInt sessionIdLength(0) ;
	
	CTlsCryptoAttributes* tlsCryptoAttributes = Provider()->Attributes();
				
	CX509Certificate* cert = NULL;
	err = VerifyServerCertificateL(cert);
	delete cert; // don't really need the cert
	
	err = CreateSessionL();
		
	// ensure we succeeded
	if (err != KErrNone)
		{
		INFO_PRINTF2(_L("Failed! Create Session failed! (Error %d)"), err);
		SetTestStepResult(EFail);
		}
	
	HBufC8* keyExMessage = NULL;
	err = ClientKeyExchange(keyExMessage);
	
	if (err != KErrNone)
		{
		INFO_PRINTF2(_L("Failed! Key exchange failed! (Error %d)"), err);
		SetTestStepResult(EFail);
		}
	CleanupStack::PushL(keyExMessage);	
	
	// Call ServerFinished to do the chache
	// derive the premaster secret from the key exchange method	
 	INFO_PRINTF1(_L("Deriving master secret."));
	HBufC8* premaster = DerivePreMasterSecretL(*keyExMessage);
	CleanupStack::PopAndDestroy(keyExMessage);  
	 
	// compute the master secret from the premaster.
	CleanupStack::PushL(premaster);
	HBufC8* master = ComputeMasterSecretL(*premaster);
	CleanupStack::PopAndDestroy(premaster);
	CleanupStack::PushL(master);  
	
	// do the caching 
	ValidateServerFinishL(*master);
	
	CleanupStack::PopAndDestroy(master);
	
	err = VerifyGetSessionL(tlsCryptoAttributes->iSessionNameAndID.iServerName, sessionIdLength);
	// case A			
	if (err != KErrNone || sessionIdLength == 0)
		{
		INFO_PRINTF1(_L("Case A Failed! GetSession failed!"));
		SetTestStepResult(EFail);
		return TestStepResult();
		}
	
	RTimer timer;
	TRequestStatus timerStatus;
	timer.CreateLocal();
	TTimeIntervalMicroSeconds32 waitTime( 1000000*(sessionDelay));
	timer.After( timerStatus, waitTime);
	User::WaitForRequest(timerStatus);
	timer.Close();  
	
	err = 0;
	sessionIdLength = 0;
	
	err = VerifyGetSessionL(tlsCryptoAttributes->iSessionNameAndID.iServerName, sessionIdLength);
	// case B, delay should have caused session to be cleared.
	if ( sessionIdLength != 0)
		{
		INFO_PRINTF1(_L("Case B Failed! GetSession failed!"));
		SetTestStepResult(EFail);
		}
						
	return TestStepResult();
	}
예제 #24
0
파일: micro.c 프로젝트: AndreaCensi/jAER
/*****************************************************************************
* Function:     xsvfShift
* Description:  Goes to the given starting TAP state.
*               Calls xsvfShiftOnly to shift in the given TDI data and
*               optionally capture the TDO data.
*               Compares the TDO captured data against the TDO expected
*               data.
*               If a data mismatch occurs, then executes the exception
*               handling loop upto ucMaxRepeat times.
* Parameters:   pucTapState     - Ptr to current TAP state.
*               ucStartState    - Starting shift state: Shift-DR or Shift-IR.
*               lNumBits        - number of bits to shift.
*               plvTdi          - ptr to lenval for TDI data.
*               plvTdoCaptured  - ptr to lenval for storing TDO data.
*               plvTdoExpected  - ptr to expected TDO data.
*               plvTdoMask      - ptr to TDO mask.
*               ucEndState      - state in which to end the shift.
*               lRunTestTime    - amount of time to wait after the shift.
*               ucMaxRepeat     - Maximum number of retries on TDO mismatch.
* Returns:      int             - 0 = success; otherwise TDO mismatch.
* Notes:        XC9500XL-only Optimization:
*               Skip the waitTime() if plvTdoMask->val[0:plvTdoMask->len-1]
*               is NOT all zeros and sMatch==1.
*****************************************************************************/
int xsvfShift( unsigned char*   pucTapState,
               unsigned char    ucStartState,
               long             lNumBits,
               lenVal*          plvTdi,
               lenVal*          plvTdoCaptured,
               lenVal*          plvTdoExpected,
               lenVal*          plvTdoMask,
               unsigned char    ucEndState,
               long             lRunTestTime,
               unsigned char    ucMaxRepeat )
{
    int   xdata          iErrorCode;
    int   xdata          iMismatch;
    unsigned char  xdata ucRepeat;
    int   xdata          iExitShift;

    iErrorCode  = XSVF_ERROR_NONE;
    iMismatch   = 0;
    ucRepeat    = 0;
    iExitShift  = ( ucStartState != ucEndState );



    if ( !lNumBits )
    {
        /* Compatibility with XSVF2.00:  XSDR 0 = no shift, but wait in RTI */
        if ( lRunTestTime )
        {
            /* Wait for prespecified XRUNTEST time */
            xsvfGotoTapState( pucTapState, XTAPSTATE_RUNTEST );
            XSVFDBG_PRINTF1( 3, "   Wait = %ld usec\n", lRunTestTime );
            waitTime( lRunTestTime );
        }
    }
    else
    {
        do
        {
            /* Goto Shift-DR or Shift-IR */
            xsvfGotoTapState( pucTapState, ucStartState );

            /* Shift TDI and capture TDO */
            xsvfShiftOnly( lNumBits, plvTdi, plvTdoCaptured, iExitShift );

            if ( plvTdoExpected )
            {
                /* Compare TDO data to expected TDO data */
                iMismatch   = !EqualLenVal( plvTdoExpected,
                                            plvTdoCaptured,
                                            plvTdoMask );
            }

            if ( iExitShift )
            {
                /* Update TAP state:  Shift->Exit */
                ++(*pucTapState);
                XSVFDBG_PRINTF1( 3, "   TAP State = %s\n",
                                 xsvf_pzTapState[ *pucTapState ] );

                if ( iMismatch && lRunTestTime && ( ucRepeat < ucMaxRepeat ) )
                {
                
                    /* Do exception handling retry - ShiftDR only */
                    xsvfGotoTapState( pucTapState, XTAPSTATE_PAUSEDR );
                    /* Shift 1 extra bit */
                    xsvfGotoTapState( pucTapState, XTAPSTATE_SHIFTDR );
                    /* Increment RUNTEST time by an additional 25% */
                    lRunTestTime    += ( lRunTestTime >> 2 );
                }
                else
                {
                    /* Do normal exit from Shift-XR */
                    xsvfGotoTapState( pucTapState, ucEndState );
                }

                if ( lRunTestTime )
                {
                    /* Wait for prespecified XRUNTEST time */
                    xsvfGotoTapState( pucTapState, XTAPSTATE_RUNTEST );
                    XSVFDBG_PRINTF1( 3, "   Wait = %ld usec\n", lRunTestTime );
                    waitTime( lRunTestTime );
                }
            }
        } while ( iMismatch && ( ucRepeat++ < ucMaxRepeat ) );
void PetControlDeviceImplementation::callObject(CreatureObject* player) {
	if (player->isInCombat() || player->isDead() || player->isIncapacitated() || player->getPendingTask("tame_pet") != NULL) {
		player->sendSystemMessage("@pet/pet_menu:cant_call"); // You cannot call this pet right now.
		return;
	}

	if (player->isRidingMount()) {
		player->sendSystemMessage("@pet/pet_menu:mounted_call_warning"); // You cannot call a pet while mounted or riding a vehicle.
		return;
	}

	if (player->getParent() != NULL) {
		ManagedReference<SceneObject*> strongRef = player->getRootParent().get();
		ManagedReference<BuildingObject*> building = NULL;

		if (strongRef != NULL)
			building = strongRef.castTo<BuildingObject*>();

		if (building == NULL || building->isPrivateStructure()) {
			player->sendSystemMessage("@pet/pet_menu:private_house"); // You cannot call pets in a private building.
			return;
		}
	}

	if (!isASubChildOf(player))
		return;

	ManagedReference<TangibleObject*> controlledObject = this->controlledObject.get();

	if (controlledObject == NULL || !controlledObject->isAiAgent())
		return;

	ManagedReference<AiAgent*> pet = cast<AiAgent*>(controlledObject.get());
	ManagedReference<PlayerObject*> ghost = player->getPlayerObject();

	if (ghost->hasActivePet(pet))
		return;

	if (vitality <= 0) {
		player->sendSystemMessage("@pet/pet_menu:dead_pet"); // This pet is dead. Select DESTROY from the radial menu to delete this pet control device.
		return;
	}

	if (!pet->getCooldownTimerMap()->isPast("call_cooldown")) {
		if (petType == PetManager::DROIDPET)
			player->sendSystemMessage("@pet/droid_modules:droid_maint_on_maint_run"); //You cannot call that droid. It is currently on a maintenance run.
		else
			player->sendSystemMessage("@pet/pet_menu:cant_call"); // cant call pet right now
		return;
	}
	assert(pet->isLockedByCurrentThread());

	unsigned int petFaction = pet->getFaction();

	if (petFaction != 0) {
		if (player->getFaction() == 0) {
			StringIdChatParameter message("@faction_perk:prose_be_declared"); // You must be declared to a faction to use %TT.
			message.setTT(pet->getDisplayedName());
			player->sendSystemMessage(message);
			return;
		}

		if (player->getFaction() != petFaction || ghost->getFactionStatus() == FactionStatus::ONLEAVE) {
			StringIdChatParameter message("@faction_perk:prose_be_declared_faction"); // You must be a declared %TO to use %TT.
			message.setTO(pet->getFactionString());
			message.setTT(pet->getDisplayedName());
			player->sendSystemMessage(message);
			return;
		}
	}

	if(player->getPendingTask("call_pet") != NULL) {
		StringIdChatParameter waitTime("pet/pet_menu", "call_delay_finish_pet"); // Already calling a Pet: Call will be finished in %DI seconds.
		Time nextExecution;
		Core::getTaskManager()->getNextExecutionTime(player->getPendingTask("call_pet"), nextExecution);
		int timeLeft = (nextExecution.getMiliTime() / 1000) - System::getTime();
		waitTime.setDI(timeLeft);

		player->sendSystemMessage(waitTime);
		return;
	}

	if (!growPet(player))
		return;

	if (petType == PetManager::CREATUREPET && !isValidPet(pet)) {
		ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player,SuiWindowType::PET_FIX_DIALOG);
		box->setCallback(new PetFixSuiCallback(player->getZoneServer(), _this.getReferenceUnsafeStaticCast()));
		box->setPromptText("@bio_engineer:pet_sui_text");
		box->setPromptTitle("@bio_engineer:pet_sui_title");
		box->setOkButton(true,"@bio_engineer:pet_sui_fix_stats");
		box->setCancelButton(true,"@bio_engineer:pet_sui_abort");
		box->setOtherButton(true,"@bio_engineer:pet_sui_fix_level");
		box->setUsingObject(_this.getReferenceUnsafeStaticCast());
		player->getPlayerObject()->addSuiBox(box);
		player->sendMessage(box->generateMessage());
		return;
	}

	int currentlySpawned = 0;
	int spawnedLevel = 0;
	int maxPets = 1;
	int maxLevelofPets = 10;
	int level = pet->getLevel();

	if (petType == PetManager::CREATUREPET) {
		ManagedReference<Creature*> creaturePet = cast<Creature*>(pet.get());
		if (creaturePet == NULL)
			return;

		bool ch = player->hasSkill("outdoors_creaturehandler_novice");

		if (ch) {
			maxPets = player->getSkillMod("keep_creature");
			maxLevelofPets = player->getSkillMod("tame_level");
		}

		if (creaturePet->getAdultLevel() > maxLevelofPets) {
			player->sendSystemMessage("@pet/pet_menu:control_exceeded"); // Calling this pet would exceed your Control Level ability.
			return;
		}

		if (creaturePet->isVicious() && (player->getSkillMod("tame_aggro") <= 0 || !ch)) {
			player->sendSystemMessage("@pet/pet_menu:lack_skill"); // You lack the skill to call a pet of this type.
			return;
		}

	} else if (petType == PetManager::FACTIONPET){
		maxPets = 3;
	}

	for (int i = 0; i < ghost->getActivePetsSize(); ++i) {
		ManagedReference<AiAgent*> object = ghost->getActivePet(i);

		if (object != NULL) {
			if (object->isCreature() && petType == PetManager::CREATUREPET) {
				ManagedReference<CreatureTemplate*> activePetTemplate = object->getCreatureTemplate();

				if (activePetTemplate == NULL || activePetTemplate->getTemplateName() == "at_st")
					continue;

				if (++currentlySpawned >= maxPets) {
					player->sendSystemMessage("@pet/pet_menu:at_max"); // You already have the maximum number of pets of this type that you can call.
					return;
				}

				spawnedLevel += object->getLevel();

				if ((spawnedLevel + level) > maxLevelofPets) {
					player->sendSystemMessage("@pet/pet_menu:control_exceeded"); // Calling this pet would exceed your Control Level ability.
					return;
				}
			} else if (object->isNonPlayerCreatureObject() && petType == PetManager::FACTIONPET) {
				if (++currentlySpawned >= maxPets) {
					player->sendSystemMessage("@pet/pet_menu:at_max"); // You already have the maximum number of pets of this type that you can call.
					return;
				}
			} else if (object->isCreature() && petType == PetManager::FACTIONPET) {
				ManagedReference<CreatureTemplate*> activePetTemplate = object->getCreatureTemplate();
				ManagedReference<CreatureTemplate*> callingPetTemplate = pet->getCreatureTemplate();

				if (activePetTemplate == NULL || callingPetTemplate == NULL || activePetTemplate->getTemplateName() != "at_st")
					continue;

				if (++currentlySpawned >= maxPets || (activePetTemplate->getTemplateName() == "at_st" && callingPetTemplate->getTemplateName() == "at_st")) {
					player->sendSystemMessage("@pet/pet_menu:at_max"); // You already have the maximum number of pets of this type that you can call.
					return;
				}
			} else if (object->isDroidObject() && petType == PetManager::DROIDPET) {
				if (++currentlySpawned >= maxPets) {
					player->sendSystemMessage("@pet/pet_menu:at_max"); // You already have the maximum number of pets of this type that you can call.
					return;
				}
			}

		}
	}

	ManagedReference<TradeSession*> tradeContainer = player->getActiveSession(SessionFacadeType::TRADE).castTo<TradeSession*>();

	if (tradeContainer != NULL) {
		server->getZoneServer()->getPlayerManager()->handleAbortTradeMessage(player);
	}

	if(player->getCurrentCamp() == NULL && player->getCityRegion() == NULL) {

		Reference<CallPetTask*> callPet = new CallPetTask(_this.getReferenceUnsafeStaticCast(), player, "call_pet");

		StringIdChatParameter message("pet/pet_menu", "call_pet_delay"); // Calling pet in %DI seconds. Combat will terminate pet call.
		message.setDI(15);
		player->sendSystemMessage(message);

		player->addPendingTask("call_pet", callPet, 15 * 1000);

		if (petControlObserver == NULL) {
			petControlObserver = new PetControlObserver(_this.getReferenceUnsafeStaticCast());
			petControlObserver->deploy();
		}

		player->registerObserver(ObserverEventType::STARTCOMBAT, petControlObserver);

	} else { // Player is in a city or camp, spawn pet immediately

		if( player->getCooldownTimerMap() == NULL )
			return;

		// Check cooldown
		if( !player->getCooldownTimerMap()->isPast("petCallOrStoreCooldown") ){
			player->sendSystemMessage("@pet/pet_menu:cant_call_1sec"); //"You cannot CALL for 1 second."
			return;
		}

		spawnObject(player);

		// Set cooldown
		player->getCooldownTimerMap()->updateToCurrentAndAddMili("petCallOrStoreCooldown", 1000); // 1 sec
	}

	EnqueuePetCommand* enqueueCommand = new EnqueuePetCommand(pet, String("petFollow").toLowerCase().hashCode(), String::valueOf(player->getObjectID()), player->getObjectID(), 1);
	enqueueCommand->execute();
}
예제 #26
0
파일: z64viewer.c 프로젝트: wareya/gzrt
int _main(int argc, char *argv[])
{
  SDL_Surface *screen;
  int done;
  Uint8 *keys;
  int mousebutton,mouseX,mouseY;
  int grabbed=false;
  SDL_Init(SDL_INIT_VIDEO);

  screen = SDL_SetVideoMode(640, 480, 32, SDL_OPENGL|SDL_RESIZABLE);
  if ( ! screen ) {
    fprintf(stderr, "Couldn't set 300x300 GL video mode: %s\n", SDL_GetError());
    SDL_Quit();
    exit(2);
  }
  SDL_WM_SetCaption("Z64Viewer", "z64viewer");
  SDL_ShowCursor(SDL_DISABLE);
  SDL_WM_GrabInput(SDL_GRAB_ON);
  grabbed=true;
  
  init(argc, argv);
  reshape(screen->w, screen->h);
  done = 0;
  while ( ! done ) {
    SDL_Event event;

    idle();
    while ( SDL_PollEvent(&event) ) {
      switch(event.type) {
        case SDL_VIDEORESIZE:
          screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 16,
                                    SDL_OPENGL|SDL_RESIZABLE);
          if ( screen ) {
            reshape(screen->w, screen->h);
          } else {
            printf("Problem...\n");
          }
          break;

        case SDL_QUIT:
          done = 1;
          break;
      }
    }
    keys = SDL_GetKeyState(NULL);

    if ( keys[SDLK_ESCAPE] ) {
      if(grabbed)
      {
          SDL_WM_GrabInput(SDL_GRAB_OFF);
          SDL_ShowCursor(SDL_ENABLE);
          grabbed=false;          
          waitTime(200); // Wait a bit so we don't exit by mistake
      }
      else
      {      
      done = 1;
      }
    }

    mousebutton=SDL_GetRelativeMouseState(&mouseX,&mouseY);
    
    GLfloat viewMatrix[16] = { 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 };
    
    if(grabbed)
    {
        if((mousebutton&1) && (mousebutton&4))
        {
            matrixRotate(viewMatrix, mouseX/600.0f*360.0f, camera[0*4+0],camera[0*4+1],camera[0*4+2]);
            
            multM4Vect(&camera[0*4], viewMatrix, &camera[0*4]);
            multM4Vect(&camera[1*4], viewMatrix, &camera[1*4]);
            multM4Vect(&camera[2*4], viewMatrix, &camera[2*4]);
        }
        else
        {
            matrixRotate(viewMatrix, -mouseX/600.0f*360.0f, camera[2*4+0], camera[2*4+1],camera[2*4+2]);
            matrixRotate(viewMatrix, -mouseY/600.0f*360.0f, camera[1*4+0], camera[1*4+1],camera[1*4+2]);
            
            multM4Vect(&camera[0*4], viewMatrix, &camera[0*4]);
            multM4Vect(&camera[1*4], viewMatrix, &camera[1*4]);
        
            if(mousebutton&1)
            {
                camera[3*4+0]+=camera[0*4+0]*20;
                camera[3*4+1]+=camera[0*4+1]*20;
                camera[3*4+2]+=camera[0*4+2]*20;
                camera[3*4+3]+=camera[0*4+3]*20;
            }
    
          
            if(mousebutton&4)
            {
                camera[3*4+0]-=camera[0*4+0]*20;
                camera[3*4+1]-=camera[0*4+1]*20;
                camera[3*4+2]-=camera[0*4+2]*20;
                camera[3*4+3]-=camera[0*4+3]*20;
            }


            
            if(keys[SDLK_d])
            {
                camera[3*4+0]+=camera[1*4+0]*20;
                camera[3*4+1]+=camera[1*4+1]*20;
                camera[3*4+2]+=camera[1*4+2]*20;
                camera[3*4+3]+=camera[1*4+3]*20;
            }
            if(keys[SDLK_a])
            {
                camera[3*4+0]-=camera[1*4+0]*20;
                camera[3*4+1]-=camera[1*4+1]*20;
                camera[3*4+2]-=camera[1*4+2]*20;
                camera[3*4+3]-=camera[1*4+3]*20;
            }
            if(keys[SDLK_w])
            {
                camera[3*4+0]+=camera[2*4+0]*20;
                camera[3*4+1]+=camera[2*4+1]*20;
                camera[3*4+2]+=camera[2*4+2]*20;
                camera[3*4+3]+=camera[2*4+3]*20;
            }
            if(keys[SDLK_s])
            {
                camera[3*4+0]-=camera[2*4+0]*20;
                camera[3*4+1]-=camera[2*4+1]*20;
                camera[3*4+2]-=camera[2*4+2]*20;
                camera[3*4+3]-=camera[2*4+3]*20;
            }

//FASTER
            if(mousebutton&4 && mousebutton&2)
            {
                camera[3*4+0]-=camera[0*4+0]*200;
                camera[3*4+1]-=camera[0*4+1]*200;
                camera[3*4+2]-=camera[0*4+2]*200;
                camera[3*4+3]-=camera[0*4+3]*200;
            }
        if(mousebutton&1 && mousebutton&2)
            {
                camera[3*4+0]+=camera[0*4+0]*200;
                camera[3*4+1]+=camera[0*4+1]*200;
                camera[3*4+2]+=camera[0*4+2]*200;
                camera[3*4+3]+=camera[0*4+3]*200;
            }

            if(keys[SDLK_i])
            {
                camera[3*4+0]+=camera[2*4+0]*200;
                camera[3*4+1]+=camera[2*4+1]*200;
                camera[3*4+2]+=camera[2*4+2]*200;
                camera[3*4+3]+=camera[2*4+3]*200;
            }
        if(keys[SDLK_k])
            {
                camera[3*4+0]-=camera[2*4+0]*200;
                camera[3*4+1]-=camera[2*4+1]*200;
                camera[3*4+2]-=camera[2*4+2]*200;
                camera[3*4+3]-=camera[2*4+3]*200;
            }
        
            if(keys[SDLK_j])
            {
                camera[3*4+0]-=camera[1*4+0]*200;
                camera[3*4+1]-=camera[1*4+1]*200;
                camera[3*4+2]-=camera[1*4+2]*200;
                camera[3*4+3]-=camera[1*4+3]*200;
            }

            if(keys[SDLK_l])
            {
                camera[3*4+0]+=camera[1*4+0]*200;
                camera[3*4+1]+=camera[1*4+1]*200;
                camera[3*4+2]+=camera[1*4+2]*200;
                camera[3*4+3]+=camera[1*4+3]*200;
            }
//FASTER END 

        }            
    }
    else
    {
        if(mousebutton)
        {
            SDL_ShowCursor(SDL_DISABLE);
            SDL_WM_GrabInput(SDL_GRAB_ON);
            grabbed=true;
        }
    }    
    draw();
  }
  SDL_Quit();
  return 0;             /* ANSI C requires main to return int. */
}