Пример #1
0
int AsyncEventPoller::Poll(int timeout)
{
    if (fdEvents_.empty())
    {
        UpdateTimer();
        Sleep(timeout);
        return 0;
    }
    int count = 0;
    for (auto iter = eventFds_.begin(); iter != eventFds_.end(); ++iter)
    {
        events_[count++] = iter->first;
    }
    int nready = WSAWaitForMultipleEvents((DWORD)count, events_, FALSE, timeout, FALSE);
    if (nready == WSA_WAIT_FAILED)
    {
        LOG(ERROR) << "WSAWaitForMultipleEvents: " << LAST_ERROR_MSG;
        return 0;
    }
    else if (nready == WSA_WAIT_TIMEOUT)
    {
        UpdateTimer();
    }
    else if (nready == WSA_WAIT_IO_COMPLETION)
    {
        // Alertable I/O
    }
    else 
    {
        int index = nready - WSA_WAIT_EVENT_0;
        if (index >= WSA_MAXIMUM_WAIT_EVENTS)
        {
            LOG(ERROR) << "WSA wait events index out of range: " << index;
            return 0;
        }
        WSAEVENT hEvent = events_[index];
        FdEntry* entry = eventFds_[hEvent];
        WSANETWORKEVENTS events = {};

        // This will reset the event object and adjust the status of 
        // active FD events on the socket in an atomic fashion.
        int r = WSAEnumNetworkEvents(entry->fd, hEvent, &events);
        if (r == SOCKET_ERROR)
        {
            LOG(ERROR) << "WSAEnumNetworkEvents: " << LAST_ERROR_MSG;
            return 0;
        }
        HandleEvents(entry, &events);
        return 1;
    }
    return 0;
}
Пример #2
0
nsresult
EventTokenBucket::SubmitEvent(ATokenBucketEvent *event, nsICancelable **cancelable)
{
    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
    SOCKET_LOG(("EventTokenBucket::SubmitEvent %p\n", this));

    if (mStopped || !mTimer)
        return NS_ERROR_FAILURE;

    UpdateCredits();

    nsRefPtr<TokenBucketCancelable> cancelEvent = new TokenBucketCancelable(event);
    // When this function exits the cancelEvent needs 2 references, one for the
    // mEvents queue and one for the caller of SubmitEvent()

    NS_ADDREF(*cancelable = cancelEvent.get());

    if (mPaused || !TryImmediateDispatch(cancelEvent.get())) {
        // queue it
        SOCKET_LOG(("   queued\n"));
        mEvents.Push(cancelEvent.forget().take());
        UpdateTimer();
    }
    else {
        SOCKET_LOG(("   dispatched synchronously\n"));
    }

    return NS_OK;
}
void QmitkIGTTrackingSemiAutomaticMeasurementView::CreateQtPartControl(QWidget *parent)
{
  // build up qt view, unless already done
  if (!m_Controls)
  {
    // create GUI widgets from the Qt Designer's .ui file
    m_Controls = new Ui::QmitkIGTTrackingSemiAutomaticMeasurementViewControls;
    m_Controls->setupUi(parent);

    //buttons
    connect(m_Controls->m_LoadMeasurementToolStorage, SIGNAL(clicked()), this, SLOT(OnLoadMeasurementStorage()));
    connect(m_Controls->m_LoadReferenceToolStorage, SIGNAL(clicked()), this, SLOT(OnLoadReferenceStorage()));
    connect(m_Controls->m_StartTracking, SIGNAL(clicked()), this, SLOT(OnStartTracking()));
    connect(m_Controls->m_LoadList, SIGNAL(clicked()), this, SLOT(OnMeasurementLoadFile()));
    connect(m_Controls->m_StartNextMeasurement, SIGNAL(clicked()), this, SLOT(StartNextMeasurement()));
    connect(m_Controls->m_ReapeatLastMeasurement, SIGNAL(clicked()), this, SLOT(RepeatLastMeasurement()));
    connect(m_Controls->m_SetReference, SIGNAL(clicked()), this, SLOT(OnSetReference()));
    connect(m_Controls->m_UseReferenceTrackingSystem, SIGNAL(toggled(bool)), this, SLOT(OnUseReferenceToggled(bool)));
    connect(m_Controls->m_CreateResults, SIGNAL(clicked()), this, SLOT(CreateResults()));

    //event filter
    qApp->installEventFilter(this);

    //timers
    connect(m_Timer, SIGNAL(timeout()), this, SLOT(UpdateTimer()));
  }
Пример #4
0
void	Emulator::DoFrame()
{
  int	nbCycles = 0;
  int	curCycles;
 
  if (mPause)
    return ;
  while (nbCycles < CYCLE_BY_FRAME)
    {
      if (!mIsHalted && !mIsStop)
	curCycles = DoOpcode();
      else
	curCycles = 4;
      if (!mIsStop)
	UpdateLCD(curCycles);

      UpdateTimer(curCycles);
      HandleInterupt();
      nbCycles += curCycles;

      // DEBUG //
      mCyclesCounter += curCycles;
      mOpCounter++;
      if (mPause)
	break ;
    }
}
Пример #5
0
void CRollLabel::SetText(LPCTSTR lpszText, COLORREF crText)
{
	m_strText = lpszText;
	m_crText = TRUE;

	UpdateTimer();
}
Пример #6
0
int Game::start(void(*buildFunc)(), void(*destructFunc)())
{
	if (game == nullptr)
		return EXIT_FAILURE;

	this->destructFunc = destructFunc;

	if (!InitMainWindow())
	{
		delete game;
		return EXIT_FAILURE;
	}

	if (!InitDirect3D())
	{
		delete game;
		return EXIT_FAILURE;
	}

	deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
	initEngine();

	buildFunc();

	NetworkManager::networkManager->Initialize(2);
	NetworkManager::networkManager->AssignTask([]() { NetworkManager::networkManager->startClient(); });

	MSG msg = { 0 };

	while (msg.message != WM_QUIT)
	{
		// Peek at the next message (and remove it from the queue)
		if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
		{
			// Handle this message
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		else if (!minimized) // No message to handle
		{
			if (Input::wasControlPressed("quit"))
				PostQuitMessage(0);

			// Update the timer for this frame
			UpdateTimer();

			// Standard game loop type stuff
			CalculateFrameStats();
			update(deltaTime, totalTime);

			draw();// (deltaTime, totalTime);
			Input::updateControlStates();
		}
	}

	delete game;
	
	return (int)msg.wParam;
}
Пример #7
0
void CRollLabel::OnSize(UINT nType, int cx, int cy)
{
	CWnd::OnSize(nType, cx, cy);

	GetClientRect(&m_rcClient);

	UpdateTimer();
}
Пример #8
0
void GameTimeGauge::updateTimer()
{
	miTime++;
	UpdateTimer(miTime);

	if(miTime == 1 || miTime % 5 == 0){
		UpdateTimerGauge(miTimeGauge++);
	}
}
Пример #9
0
static AJ_Status GetTimerTimeLeft(const uint8_t index,  TS_Timer_Period* timeLeft) {

    UpdateTimer(NULL);

    *timeLeft = g_ts_timer_timeleft;

    printf("GetTimerTimeLeft Called on index %d\n", index);
    return AJ_OK;
}
Пример #10
0
bool Update(void)
{
	if(!UpdateTimer())
		return false;

	if(!UpdateGame())
		return false;

	return true;
}
Пример #11
0
PVR_ERROR cXVDRData::RenameTimer(const PVR_TIMER &timerinfo, const char *newname)
{
  PVR_TIMER timerinfo1;
  PVR_ERROR ret = GetTimerInfo(timerinfo.iClientIndex, timerinfo1);
  if (ret != PVR_ERROR_NO_ERROR)
    return ret;

  timerinfo1.strTitle = newname;
  return UpdateTimer(timerinfo1);
}
Пример #12
0
		void MusicRenderer::RenderToSpeaker()
		{
			SoundEvent currentSoundEvent;

			unsigned int duration = m_header.Duration[m_difficulty] * 1000 + 1000;
			std::vector<SoundEvent>::size_type eventCtr = 0, totalEvents = m_soundEvents->size();
			unsigned int elapsed = 0;
			int percentage = 0;

			printf("0%%");

			BeginTimer();
			while(elapsed < duration)
			{
				if(eventCtr < totalEvents)
				{
					currentSoundEvent = m_soundEvents->at(eventCtr);

					if(currentSoundEvent.Time <= elapsed)
					{
						if(currentSoundEvent.NoteType != 3)
						{
							int sampleIndex = -1;
							if(currentSoundEvent.NoteType == 4)
								sampleIndex = GetSample(currentSoundEvent.RefID + 1000);
							else
								sampleIndex = GetSample(currentSoundEvent.RefID);

							if(sampleIndex >= 0)
							{
								Sample sample = m_samples->at(sampleIndex);
								FMOD_RESULT result = m_fmod->playSound(FMOD_CHANNEL_FREE, sample.Data, false, 0);
							}
						}

						eventCtr++;
					}
				}

				m_fmod->update();
				UpdateTimer();
				elapsed = GetElapsedTime();

				if(percentage < 10)
					printf("\b\b");
				else if(percentage < 100)
					printf("\b\b\b");
				else printf("\b\b\b\b");

				percentage = (int)((float)elapsed / (float)duration * 100.f);
				printf("%d%%", percentage);
			}

			StopTimer();
		}
Пример #13
0
VOID SvcReminderEnable(BOOLEAN bEnable)
{
    if (bEnable)	// Reminder is on
    {
        if (myGlobals.ExtraIconsServiceExist && (ExtraIcon == INVALID_HANDLE_VALUE))
        {
            EXTRAICON_INFO ico = {0};
            ico.type = EXTRAICON_TYPE_ICOLIB;
            ico.cbSize=sizeof(ico);
            ico.name="Reminder";
            ico.description="Reminder (uinfoex)";
            ico.descIcon=ICO_COMMON_ANNIVERSARY;
            ExtraIcon=(HANDLE)CallService(MS_EXTRAICON_REGISTER, (WPARAM)&ico, 0);
            ZeroMemory(&ico,sizeof(ico));
        }
        // init hooks
        if (!ghCListIR)
        {
            ghCListIR = HookEvent(ME_CLIST_EXTRA_LIST_REBUILD, (MIRANDAHOOK)OnCListRebuildIcons);
        }

        if (!ghCListIA)
        {
            ghCListIA = HookEvent(ME_CLIST_EXTRA_IMAGE_APPLY, (MIRANDAHOOK)OnCListApplyIcon);
        }
        if (!ghSettingsChanged && !myGlobals.UseDbxTree)
        {
            ghSettingsChanged = HookEvent(ME_DB_CONTACT_SETTINGCHANGED, (MIRANDAHOOK)OnContactSettingChanged);
        }

        // reinit reminder options
        gRemindOpts.RemindState	= DB::Setting::GetByte(SET_REMIND_ENABLED, DEFVAL_REMIND_ENABLED);
        gRemindOpts.wDaysEarlier = DB::Setting::GetWord(SET_REMIND_OFFSET, DEFVAL_REMIND_OFFSET);
        gRemindOpts.bCListExtraIcon = DB::Setting::GetByte(SET_REMIND_EXTRAICON, 1);
        gRemindOpts.bCheckVisibleOnly = DB::Setting::GetByte(SET_REMIND_CHECKVISIBLE, DEFVAL_REMIND_CHECKVISIBLE);
        gRemindOpts.bFlashCList = DB::Setting::GetByte(SET_REMIND_FLASHICON, FALSE);
        gRemindOpts.bPopups = ServiceExists(MS_POPUP_ADDPOPUPT) && DB::Setting::GetByte(SET_POPUP_ENABLED, DEFVAL_POPUP_ENABLED);

        // init the timer
        UpdateTimer(TRUE);
    }
    else	// Reminder is off
    {
        HANDLE hContact;

        for (hContact = DB::Contact::FindFirst();
                hContact != NULL;
                hContact = DB::Contact::FindNext(hContact))
        {
            NotifyWithExtraIcon(hContact, CEvent());
        }
        gRemindOpts.RemindState	= REMIND_OFF;
        SvcReminderUnloadModule();
    }
}
Пример #14
0
void
EventTokenBucket::UnPause()
{
    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
    SOCKET_LOG(("EventTokenBucket::UnPause %p\n", this));
    if (!mPaused || mStopped)
        return;

    mPaused = false;
    DispatchEvents();
    UpdateTimer();
}
Пример #15
0
static GOS_ERROR_CODE tmr_TimerUpdate(void)
{
    UINT32  curTime;
    struct  timeval tv;

    VOS_Lock(gTmrTimerLock, 0);
    gettimeofday(&tv, NULL);
    curTime = (tv.tv_sec * 1000 + tv.tv_usec / 1000);

    if (curTime > gTmrTimerMsCounter) {
        if ((curTime - gTmrTimerMsCounter) > (10*1000)) {
            UpdateTimer(curTime);
        }
    } else {
        if ((gTmrTimerMsCounter - curTime) > (10*1000)) {
            UpdateTimer(curTime);
        }
    }
    gTmrTimerMsCounter = curTime;
    VOS_Unlock(gTmrTimerLock);
    return GOS_OK;
}
Пример #16
0
void GSTrailMakingTest::Update()
{
    GSCogTestBase::Update();
    UpdateHeartCount();
    UpdateTimer();
    UpdateCorrectIncorrect();

    Assert(m_currentCircle >= -1);
    if (m_currentCircle + 1 < (int)m_circles.size())
    {
        PointPracArrow(m_circles[m_currentCircle + 1].m_pos + Vec2f(0.05f, -0.05f));
    }
}
Пример #17
0
void UpdateShooter(uint16 diff)
{
    shooterTopSpeed = shooterTopFreq * 4.0f * (float)cShooterUpdateTimer / 1000000.0f;
    shooterBotSpeed = shooterBotFreq * 4.0f * (float)cShooterUpdateTimer / 1000000.0f;
    if (!activated)
        return;
    if (UpdateTimer(diff, shooterUpdateTimer, cShooterUpdateTimer))
    {
        int topCount = GetShootMotorCount(true, true);
        int botCount = GetShootMotorCount(true, false);

        float errorTop = shooterTopSpeed - topCount;
        float errorBot = shooterBotSpeed - botCount;

        shooterTopIntegral += errorTop * (float)cShooterUpdateTimer / 1000000.0f;
        shooterBotIntegral += errorBot * (float)cShooterUpdateTimer / 1000000.0f;

        if (shooterTopIntegral > 35)
            shooterTopIntegral = 35;
        if (shooterTopIntegral < -35)
            shooterTopIntegral = 35;
        if (shooterBotIntegral > 35)
            shooterBotIntegral = 35;
        if (shooterBotIntegral < -35)
            shooterBotIntegral = 35;

        int topSpeed = errorTop * cShooterGain + shooterTopIntegral * cShooterIntegral;
        int botSpeed = errorBot * cShooterGain + shooterBotIntegral * cShooterIntegral;

        if (errorTop < 0) topSpeed = 0;
        if (errorBot < 0) botSpeed = 0;
        if (topSpeed > hMaxMotorSpeed)
            topSpeed = hMaxMotorSpeed;
        if (botSpeed > hMaxMotorSpeed)
            botSpeed = hMaxMotorSpeed;

        ActivateShooter(topSpeed, botSpeed);

        shooterReady = (abs(errorTop) < 5 && abs(errorBot) < 5);
        
        /*LCD.clear(); LCD.home();
        LCD.print(topCount);
        LCD.print(" ");
        LCD.print(botCount);
        LCD.setCursor(0, 1);

        LCD.print(shooterTopIntegral);
        LCD.print(" ");
        LCD.print(shooterBotIntegral);*/
    }
}
Пример #18
0
bool CPVRTimers::UpdateTimer(const CFileItem &item)
{
  /* Check if a CPVRTimerInfoTag is inside file item */
  if (!item.IsPVRTimer())
  {
    CLog::Log(LOGERROR, "cPVRTimers: UpdateTimer no TimerInfoTag given!");
    return false;
  }

  const CPVRTimerInfoTag* tag = item.GetPVRTimerInfoTag();
  if (!tag)
    return false;

  return UpdateTimer(*tag);
}
Пример #19
0
BOOL CRollLabel::SetTextFont(CFont* pFont)
{
	if (!pFont || !pFont->GetSafeHandle())
		return FALSE;

	if (m_ftText.GetSafeHandle())
		m_ftText.DeleteObject();

	LOGFONT lf = {0};
	pFont->GetLogFont(&lf);

	if (!m_ftText.CreateFontIndirect(&lf))
	{
		return FALSE;
	}

	UpdateTimer();

	return TRUE;
}
	vector<GraphColoring::IdType> GenerateSyncColorings(const Graph& graph) {
		CreateTimestamp();

		vector<GraphColoring::IdType> syncColorings;
		int n = graph.VerticesCount();
		int k = graph.OutDegree();
		auto coloring = GraphColoring(n, k);
		auto syncChecker = SynchronizationChecker(n, k);
		GraphColoring::IdType id = 0;
		do {
			if (syncChecker.IsSynchronizing(graph, coloring)) {
				syncColorings.push_back(id);
			}
			++id;
		}
		while (coloring.NextColoring());

		UpdateTimer(SyncColoringsGenerationTime);

		return syncColorings;
	}
Пример #21
0
// --------------------------------------------------------
// The actual game loop, which processes the windows message queue
// and calls our Update & Draw methods
// --------------------------------------------------------
int DirectXGameCore::Run()
{
	// Grab the start time
	__int64 now;
	QueryPerformanceCounter((LARGE_INTEGER*)&now);
	startTime    = now;
	currentTime  = now;
	previousTime = now;

	// Create a variable to hold the current message
	MSG msg = {0};

	// Loop until we get a quit message from windows
	while(msg.message != WM_QUIT)
	{
		// Peek at the next message (and remove it from the queue)
		if(PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
		{
			// Handle this message
			TranslateMessage( &msg );
			DispatchMessage( &msg );
		}
		else // No message to handle
		{
			// Update the timer for this frame
			UpdateTimer();

			// Standard game loop type stuff
			Input::Update();
			CalculateFrameStats();
			UpdateScene(deltaTime, totalTime);
			DrawScene(deltaTime, totalTime);			
		}
	}

	// If we make it outside the game loop, return the most
	// recent message's exit code
	return (int)msg.wParam;
}
Пример #22
0
BOOL CALLBACK DlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	switch (uMsg)
	{
	case WM_INITDIALOG:
		// Set Class icon
		g_OldIcon = SetClassLong(hDlg, GCL_HICON, (LONG)LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_ICON)));

		SetTimer(hDlg, 1, 100, NULL);
		return TRUE;  // return FALSE if modeless and SetFocus is called

	case WM_TIMER:
		UpdateTimer(hDlg);
		return TRUE;

	case WM_MOUSEMOVE:
		UpdateCount(LOWORD(lParam), HIWORD(lParam));
		return TRUE;

	case WM_COMMAND:
		switch (LOWORD(wParam))
		{
		case IDCANCEL:
			// Quit program...

			KillTimer(hDlg, 1);

			// Remove Class icon
			SetClassLong(hDlg, GCL_HICON, g_OldIcon);

			EndDialog(hDlg, 0);  // Close dialogwindow
			return TRUE;
		}
		break;
	}

	return FALSE;
}
Пример #23
0
/**
 * This function checks all contacts.
 *
 * @param	notify			- notification type
 *
 * @return	nothing
 **/
VOID SvcReminderCheckAll(const ENotify notify)
{
    if (gRemindOpts.RemindState != REMIND_OFF)
    {
        HANDLE hContact;
        CEvent evt;
        MTime now;
        WORD a1 = 0;

        now.GetLocalTime();

        //walk through all the contacts stored in the DB
        for (hContact = DB::Contact::FindFirst();
                hContact != NULL;
                hContact = DB::Contact::FindNext(hContact))
        {
            CheckContact(hContact, now, evt, notify != NOTIFY_CLIST, &a1);
        }

        if (notify != NOTIFY_CLIST)
        {
            // play sound for the next anniversary
            NotifyWithSound(evt);

            // popup anniversary list
            if (DB::Setting::GetByte(SET_ANNIVLIST_POPUP, FALSE))
            {
                DlgAnniversaryListShow(0, 0);
            }

            if (evt._wDaysLeft > gRemindOpts.wDaysEarlier && notify == NOTIFY_NOANNIV)
            {
                NotifyWithPopup(NULL, CEvent::NONE, 0, NULL, TranslateT("No anniversaries to remind of"));
            }
        }
        UpdateTimer(FALSE);
    }
}
Пример #24
0
NS_IMETHODIMP
EventTokenBucket::Notify(nsITimer *timer)
{
    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);

#ifdef XP_WIN
    if (timer == mFineGrainResetTimer) {
        FineGrainResetTimerNotify();
        return NS_OK;
    }
#endif

    SOCKET_LOG(("EventTokenBucket::Notify() %p\n", this));
    mTimerArmed = false;
    if (mStopped)
        return NS_OK;

    UpdateCredits();
    DispatchEvents();
    UpdateTimer();

    return NS_OK;
}
Пример #25
0
void COggStream::Update() {
    if (!stopped) {
        UpdateTimer();

        if (!paused) {
            if (UpdateBuffers()) {
                if (!IsPlaying()) {
                    // source state changed
                    if (!StartPlaying()) {
                        // stream stopped
                        ReleaseBuffers();
                    } else {
                        // stream interrupted
                        ReleaseBuffers();
                    }
                }
            } else {
                // EOS, nothing left to do
                ReleaseBuffers();
            }
        }
    }
}
Пример #26
0
void AJTS_DoWork(AJ_BusAttachment* busAttachment)
{
    UpdateTime();

    if (g_alarm_enabled && g_isSet) {
        AJ_Time aj_alarm_time;

        int weekDay = TSDateTime2AJTime(&g_ts_date, &g_ts_alarm_time, &aj_alarm_time);

        uint8_t todayBitmap = (1 << (weekDay - 1));
        if ((g_alarm_weekdaysBitmap & todayBitmap) || (g_alarm_weekdaysBitmap == 0)) {
            if (aj_alarm_time.seconds < g_lastSavedTime.seconds) { // no check for milliseconds in sample

                AJ_AlwaysPrintf(("Emitting Alarm reached signal. aj_alarm_time.seconds:%u, g_lastSavedTime.seconds:%u\n", aj_alarm_time.seconds, g_lastSavedTime.seconds));
                //emit alarm
                AJTS_Server_AlarmReached(busAttachment, AJTS_ALARM_OBJECT_INDEX);

                g_alarm_weekdaysBitmap &= ~todayBitmap;     // note that in this sample we can only get alarms in the span of one week. every day the alarm is fired we take the day off the g_alarm_weekdaysBitmap variable.

                if (g_alarm_weekdaysBitmap == 0) {
                    g_alarm_enabled = FALSE;
                }
            }
        }
    }

    UpdateTimer(busAttachment);

//    t++;
//
//    t = t % 10;
//
//    if (!t) {
//        AJTS_Server_TimeAuthority_TimeSync(busAttachment, 1);
//    }
}
Пример #27
0
void LightManager::UpdateTime()
{
	m_sunTimer.Update();
	std::for_each(m_lightTimers.begin(), m_lightTimers.end(), UpdateTimer());
	std::for_each(m_extraTimers.begin(), m_extraTimers.end(), UpdateTimer());
}
Пример #28
0
void BattleGroundSA::Update(uint32 diff)
{
    BattleGround::Update(diff);

    if (GetStatus() == STATUS_WAIT_JOIN && !shipsStarted)
        if (Phase == SA_ROUND_ONE) // Round one not started yet
        {
            if (shipsTimer <= diff)
                StartShips();
            else
                shipsTimer -= diff;
        }

    if (GetStatus() == STATUS_IN_PROGRESS) // Battleground already in progress
    {
        if (Round_timer >= BG_SA_ROUNDLENGTH)
        {
            if (Phase == SA_ROUND_ONE) // Timeout of first round
            {
                PlaySoundToAll(BG_SA_SOUND_GYD_VICTORY);
                SendMessageToAll(defender == ALLIANCE ? LANG_BG_SA_ALLIANCE_TIMEOUT_END_1ROUND : LANG_BG_SA_HORDE_TIMEOUT_END_1ROUND, CHAT_MSG_BG_SYSTEM_NEUTRAL, NULL);
                SendWarningToAll(LANG_BG_SA_END_1ROUND);
                RoundScores[0].winner = GetDefender();
                RoundScores[0].time = BG_SA_ROUNDLENGTH;

                for (BattleGroundPlayerMap::const_iterator itr = GetPlayers().begin(); itr != GetPlayers().end(); ++itr)
                {
                    Player* plr = sObjectMgr.GetPlayer(itr->first);
                    if (plr)
                        plr->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, BG_SA_END_OF_ROUND);
                }

                ResetBattle(0, defender);
            }
            else // Timeout of second round
            {
                SendMessageToAll(defender == ALLIANCE ? LANG_BG_SA_ALLIANCE_TIMEOUT_END_2ROUND : LANG_BG_SA_HORDE_TIMEOUT_END_2ROUND, CHAT_MSG_BG_SYSTEM_NEUTRAL, NULL);
                RoundScores[1].winner = GetDefender();

                for (BattleGroundPlayerMap::const_iterator itr = GetPlayers().begin(); itr != GetPlayers().end(); ++itr)
                {
                    Player* plr = sObjectMgr.GetPlayer(itr->first);
                    if (plr)
                        plr->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, BG_SA_END_OF_ROUND);
                }

                if (RoundScores[0].winner == GetDefender())
                    EndBattleGround(GetDefender());
                else
                    EndBattleGround(TEAM_NONE);
                return;
            }
        }
        else
            Round_timer += diff;

        for (int gyd = 0; gyd < BG_SA_GRY_MAX; ++gyd)
        {
            // 3 sec delay to spawn new banner instead previous despawned one
            if (m_BannerTimers[gyd].timer)
            {
                if (m_BannerTimers[gyd].timer > diff)
                    m_BannerTimers[gyd].timer -= diff;
                else
                {
                    m_BannerTimers[gyd].timer = 0;
                    _CreateBanner(gyd, m_BannerTimers[gyd].type, m_BannerTimers[gyd].teamIndex, false);
                }
            }
        }
        UpdateTimer();
    }

    if (GetStatus() == STATUS_WAIT_JOIN && Phase == SA_ROUND_TWO) // Round two, not yet started
    {
        if (!shipsStarted)
        {
            if (shipsTimer <= diff)
            {
                SendMessageToAll(LANG_BG_SA_START_ONE_MINUTE, CHAT_MSG_BG_SYSTEM_NEUTRAL, NULL);
                StartShips();
            }
            else
                shipsTimer -= diff;
        }

        if (TimeST2Round < diff)
        {
            Phase = SA_ROUND_TWO;
            SpawnEvent(SA_EVENT_ADD_NPC, 0, true);
            SpawnEvent(SA_EVENT_ADD_BOMB_B, (GetDefender() == ALLIANCE ? BG_SA_GRAVE_STATUS_HORDE_OCCUPIED : BG_SA_GRAVE_STATUS_ALLY_OCCUPIED), true);
            ToggleTimer();
            SetStatus(STATUS_IN_PROGRESS); // Start round two
            PlaySoundToAll(SOUND_BG_START);
            SendWarningToAll(LANG_BG_SA_HAS_BEGUN);

            for (BattleGroundPlayerMap::const_iterator itr = GetPlayers().begin(); itr != GetPlayers().end(); ++itr)
            {
                Player* plr = sObjectMgr.GetPlayer(itr->first);
                if (plr)
                {
                    plr->RemoveAurasDueToSpell(SPELL_PREPARATION);
                    if(plr->GetTeam()!=GetDefender())
                    {
                        plr->GetAchievementMgr().StartTimedAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET,BG_SA_STORM_THE_BEACH_TIMER1);
                        plr->GetAchievementMgr().StartTimedAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET,BG_SA_STORM_THE_BEACH_TIMER2);
                    }
                }
            }
        }
        else
            TimeST2Round -= diff;
    }
}
Пример #29
0
void BattleGroundSA::Update(uint32 diff)
{
    BattleGround::Update(diff);

    if (GetStatus() == STATUS_WAIT_JOIN && !shipsStarted)
        if (Phase == SA_ROUND_ONE) // Round one not started yet
            if (shipsTimer <= diff)
                StartShips();
            else
                shipsTimer -= diff;

    if (GetStatus() == STATUS_IN_PROGRESS) // Battleground already in progress
    {
        if (Round_timer >= BG_SA_ROUNDLENGTH)
        {
            if(Phase == SA_ROUND_ONE) // Timeout of second round
            {
                PlaySoundToAll(BG_SA_SOUND_GYD_VICTORY);
                SendMessageToAll(defender == ALLIANCE ? LANG_BG_SA_ALLIANCE_TIMEOUT_END_1ROUND : LANG_BG_SA_HORDE_TIMEOUT_END_1ROUND, CHAT_MSG_BG_SYSTEM_NEUTRAL, NULL);
                RoundScores[0].winner = GetDefender();
                RoundScores[0].time = Round_timer;
				ResetBattle(0, defender);
            }
            else // Timeout of second round
            {
                SendMessageToAll(defender == ALLIANCE ? LANG_BG_SA_ALLIANCE_TIMEOUT_END_2ROUND : LANG_BG_SA_HORDE_TIMEOUT_END_2ROUND, CHAT_MSG_BG_SYSTEM_NEUTRAL, NULL);
                RoundScores[1].winner = GetDefender();
                RoundScores[1].time = Round_timer;
				EndBattleGround(TEAM_NONE);
                return;
            }
        } 
        else
            Round_timer += diff;

        for (int gyd = 0; gyd < BG_SA_GRY_MAX; ++gyd)
        {
            // 3 sec delay to spawn new banner instead previous despawned one
            if (m_BannerTimers[gyd].timer)
            {
                if (m_BannerTimers[gyd].timer > diff)
                    m_BannerTimers[gyd].timer -= diff;
                else
                {
                    m_BannerTimers[gyd].timer = 0;
                    _CreateBanner(gyd, m_BannerTimers[gyd].type, m_BannerTimers[gyd].teamIndex, false);
                }
            }
            // 1-minute to occupy a node from contested state
            if (m_GydTimers[gyd])
            {
                if (m_GydTimers[gyd] > diff)
                    m_GydTimers[gyd] -= diff;
                else
                {
                    m_GydTimers[gyd] = 0;
                    // Change from contested to occupied !
                    uint8 teamIndex = m_Gyd[gyd]-1;
                    m_prevGyd[gyd] = m_Gyd[gyd];
                    m_Gyd[gyd] += 2;
                    // create new occupied banner
                    _CreateBanner(gyd, BG_SA_GARVE_TYPE_OCCUPIED, teamIndex, true);
                    //_SendNodeUpdate(node);
                    _GydOccupied(gyd,(teamIndex == 0) ? ALLIANCE:HORDE);
                    // Message to chatlog
                    RewardHonorToTeam(85, (teamIndex == 0) ? ALLIANCE:HORDE);
                    RewardXpToTeam(0, 0.6f, (teamIndex == 0) ? ALLIANCE:HORDE);
                    RewardReputationToTeam((teamIndex == 0) ? 1050:1085, 65, (teamIndex == 0) ? ALLIANCE:HORDE);
                    switch(gyd)
                    {
                        case 0: SpawnEvent(SA_EVENT_ADD_VECH_W, 0, true);break;
                        case 1: SpawnEvent(SA_EVENT_ADD_VECH_E, 0, true);break;
                    }
                    if (teamIndex == 0)
                    {
                        // SendMessage2ToAll(LANG_BG_SA_AH_SEIZES_GRAVEYARD,CHAT_MSG_BG_SYSTEM_ALLIANCE,NULL,LANG_BG_ALLY,_GydName(gyd));
                        PlaySoundToAll(BG_SA_SOUND_GYD_CAPTURED_ALLIANCE);
                        SendWarningToAllSA(gyd, STATUS_CONQUESTED, ALLIANCE);
                    }
                    else
                    {
                        // SendMessage2ToAll(LANG_BG_SA_AH_SEIZES_GRAVEYARD,CHAT_MSG_BG_SYSTEM_HORDE,NULL,LANG_BG_HORDE,_GydName(gyd));
                        PlaySoundToAll(BG_SA_SOUND_GYD_CAPTURED_HORDE);
                        SendWarningToAllSA(gyd, STATUS_CONQUESTED, HORDE);
                    }
                }
            }
        }
        UpdateTimer();
    }
    if (GetStatus() == STATUS_WAIT_JOIN && Phase == SA_ROUND_TWO) // Round two, not yet started
    {
        if (!shipsStarted)
            if (shipsTimer <= diff)
            {
                SendMessageToAll(LANG_BG_SA_START_ONE_MINUTE, CHAT_MSG_BG_SYSTEM_NEUTRAL, NULL);
                StartShips();
            }
            else
                shipsTimer -= diff;
        if (TimeST2Round < diff)
        {
            Phase = 2;
            OpenDoorEvent(SA_EVENT_OP_DOOR, 0);
			SpawnEvent(SA_EVENT_ADD_NPC, 0, true);
            ToggleTimer();
            SetStatus(STATUS_IN_PROGRESS); // Start round two
            PlaySoundToAll(SOUND_BG_START);
            SendMessageToAll(LANG_BG_SA_HAS_BEGUN, CHAT_MSG_BG_SYSTEM_NEUTRAL, NULL);
            SendWarningToAll(LANG_BG_SA_HAS_BEGUN);
        }
        else
            TimeST2Round -= diff;
    }
}
Пример #30
0
/**
**  Game main loop.
**
**  Unit actions.
**  Missile actions.
**  Players (AI).
**  Cyclic events (color cycle,...)
**  Display update.
**  Input/Network/Sound.
*/
void GameMainLoop(void)
{
	int player;
	const EventCallback *old_callbacks;

	InitGameCallbacks();

	old_callbacks = GetCallbacks();
	SetCallbacks(&GameCallbacks);

	SetVideoSync();
	GameCursor = UI.Point.Cursor;
	GameRunning = true;

	CParticleManager::init();

	MultiPlayerReplayEachCycle();

	CclCommand("GameStarting()");

	std::ofstream output;
	std::wstring templ;
	firstClock = std::clock();
        templateClock = 0;
	int messageNumber = 1;
	std::ofstream outputEventsPerSec;
	std::ofstream outputNT;
	outputEventsPerSec.open("/tmp/boswarseventspersec.csv",std::ios::out);
   	outputNT.open("/tmp/boswarsclocksperevents.csv",std::ios::out);

	output.open("/tmp/beepbeep.fifo",std::ios::out);

	templ = templ = L"<message>\n"
				L"  <units>\n"
				    L"{% for unit in units.tabunits %}"
				    L"  <unit>\n"
				    L"    <id>{$unit.id}</id>\n"
				    L"    <type>{$unit.type}</type>\n"
				    L"    <isbuilding>{$unit.isbuilding}</isbuilding>\n"
				    L"    <player>{$unit.player}</player>\n"
				    L"    <order>\n"
				    L"      <action>{$unit.action}</action>\n"
				    L"      <goal>{$unit.goal}</goal>\n"
				    L"    </order>\n"
				    L"    <neworder>\n"
				    L"       <action>{$unit.neworder}</action>\n"
				    L"       <goal>{$unit.newgoal}</goal>\n"
				    L"    </neworder>\n"
				    L"  </unit>\n"
				    L"{% endfor %}"
             		   	L"  </units>\n"
				L"<overhead>{$overhead}</overhead>\n"
            		L"</message>\n"; 

	

	while (GameRunning) {

		// Can't find a better place.
		SaveGameLoading = false;
		//
		// Game logic part
		//
		if (!GamePaused && NetworkInSync && !SkipGameCycle) {
			SinglePlayerReplayEachCycle();
			++GameCycle;
			MultiPlayerReplayEachCycle();
			NetworkCommands();  // Get network commands
			UnitActions();      // handle units
			MissileActions();   // handle missiles
			PlayersEachCycle(); // handle players
			UpdateTimer();      // update game timer

			//
			// Work todo each second.
			// Split into different frames, to reduce cpu time.
			// Increment mana of magic units.
			// Update mini-map.
			// Update map fog of war.
			// Call AI.
			// Check game goals.
			// Check rescue of units.
			//
			switch (GameCycle % CYCLES_PER_SECOND) {
				case 0: // At cycle 0, start all ai players...
					if (GameCycle == 0) {
						for (player = 0; player < NumPlayers; ++player) {
							PlayersEachSecond(player);
						}
					}
					break;
				case 1:
					break;
				case 2:
					break;
				case 3: // minimap update
					UI.Minimap.Update();
					break;
				case 4:
					break;
				case 5:
					break;
				case 6: // overtaking units
					RescueUnits();
					break;
				default:
					// FIXME: assume that NumPlayers < (CYCLES_PER_SECOND - 7)
					player = (GameCycle % CYCLES_PER_SECOND) - 7;
					Assert(player >= 0);
					if (player < NumPlayers) {
						PlayersEachSecond(player);
					}
			}

			////////////GET INFORMATION FOR MONITORING!!!////////////////////
			
						

			if(NumUnits > 0)
			{
				std::clock_t littleClock = std::clock();
	
				cpptempl::data_list theUnits;
		    
		    		std::stringstream ss;

				for(int i = 0; i < NumUnits; i++)
				{
					cpptempl::data_map uni;

					/////////ID/////////
					ss.str("");
					ss << Units[i]->Slot;
					std::string theID = ss.str();
					std::wstring wTheID;
					wTheID.assign(theID.begin(),theID.end());
					uni[L"id"] = cpptempl::make_data(wTheID);

					//////UNITTYPE//////
					ss.str("");
					ss << Units[i]->Type->Name;
					std::string theType = ss.str();
					std::wstring wTheType;
					wTheType.assign(theType.begin(),theType.end());
					uni[L"type"] = cpptempl::make_data(wTheType);

					//////ISBUILDING//////
					ss.str("");
					if (Units[i]->Type->Building == 1)
						ss << "true";
					else
						ss << "false";
					std::string theIsBuilding = ss.str();
					std::wstring wTheIsBuilding;
					wTheIsBuilding.assign(theIsBuilding.begin(),theIsBuilding.end());
					uni[L"isbuilding"] = cpptempl::make_data(wTheIsBuilding);

					//////PLAYER//////
					ss.str("");
					ss << Units[i]->Player;
					std::string thePlayer = ss.str();
					std::wstring wThePlayer;
					wThePlayer.assign(thePlayer.begin(),thePlayer.end());
					uni[L"player"] = cpptempl::make_data(wThePlayer);

					//////UnitAction//////
					ss.str("");
					switch(Units[i]->Orders[0]->Action)
					{
					  	case UnitActionNone: ss << "UnitActionNone"; break;
						case UnitActionStill: ss << "UnitActionStill"; break;  
						case UnitActionStandGround: ss << "UnitActionStandGround"; break;
						case UnitActionFollow: ss << "UnitActionFollow"; break;    
						case UnitActionMove: ss << "UnitActionMove"; break;      
						case UnitActionAttack: ss << "UnitActionAttack"; break;   
						case UnitActionAttackGround: ss << "UnitActionAttackGround"; break;
						case UnitActionDie: ss << "UnitActionDie"; break;     

						case UnitActionSpellCast: ss << "UnitActionSpellCast"; break; 

						case UnitActionTrain: ss << "UnitActionTrain"; break;  
						case UnitActionBuilt: ss << "UnitActionBuilt"; break;   
						case UnitActionBoard: ss << "UnitActionBoard"; break;    
						case UnitActionUnload: ss << "UnitActionUnload"; break; 
						case UnitActionPatrol: ss << "UnitActionPatrol"; break; 
						case UnitActionBuild: ss << "UnitActionBuild"; break;

						case UnitActionRepair: ss << "UnitActionRepair"; break; 
						case UnitActionResource: ss << "UnitActionResource"; break;
						default: ss << "None";  
					}

					std::string theAction = ss.str();
					std::wstring wTheAction;
					wTheAction.assign(theAction.begin(),theAction.end());
					uni[L"action"] = cpptempl::make_data(wTheAction);

					//////UnitGoal//////
					ss.str("");
					if(Units[i]->Orders[0]->Goal != NULL)
						ss << Units[i]->Orders[0]->Goal->Slot;
					else
						ss << "None";
					std::string theGoal = ss.str();
					std::wstring wTheGoal;
					wTheGoal.assign(theGoal.begin(),theGoal.end());
					uni[L"goal"] = cpptempl::make_data(wTheGoal);

					///////NEW ORDER/////////
					ss.str("");
					switch(Units[i]->NewOrder.Action)
					{
					  	case UnitActionNone: ss << "UnitActionNone"; break;
						case UnitActionStill: ss << "UnitActionStill"; break;  
						case UnitActionStandGround: ss << "UnitActionStandGround"; break;
						case UnitActionFollow: ss << "UnitActionFollow"; break;    
						case UnitActionMove: ss << "UnitActionMove"; break;      
						case UnitActionAttack: ss << "UnitActionAttack"; break;   
						case UnitActionAttackGround: ss << "UnitActionAttackGround"; break;
						case UnitActionDie: ss << "UnitActionDie"; break;     

						case UnitActionSpellCast: ss << "UnitActionSpellCast"; break; 

						case UnitActionTrain: ss << "UnitActionTrain"; break;  
						case UnitActionBuilt: ss << "UnitActionBuilt"; break;   
						case UnitActionBoard: ss << "UnitActionBoard"; break;    
						case UnitActionUnload: ss << "UnitActionUnload"; break; 
						case UnitActionPatrol: ss << "UnitActionPatrol"; break; 
						case UnitActionBuild: ss << "UnitActionBuild"; break;

						case UnitActionRepair: ss << "UnitActionRepair"; break; 
						case UnitActionResource: ss << "UnitActionResource"; break;
						default: ss << "None";  
					}

					std::string theNewOrder = ss.str();
					std::wstring wTheNewOrder;
					wTheNewOrder.assign(theNewOrder.begin(),theNewOrder.end());
					uni[L"neworder"] = cpptempl::make_data(wTheNewOrder);

					//////NEW GOAL//////
					ss.str("");
					if(Units[i]->NewOrder.Goal != NULL)
						ss << Units[i]->NewOrder.Goal->Slot;
					else
						ss << "None";
					std::string theNewGoal = ss.str();
					std::wstring wTheNewGoal;
					wTheNewGoal.assign(theNewGoal.begin(),theNewGoal.end());
					uni[L"newgoal"] = cpptempl::make_data(wTheNewGoal);
			
					theUnits.push_back((cpptempl::make_data(uni)));
				}
				

				cpptempl::data_map lesUnits;
		    		lesUnits[L"tabunits"] = cpptempl::make_data(theUnits);

				// Now set this in the data map
				cpptempl::data_map data;
				data[L"units"] = cpptempl::make_data(lesUnits);

				//////////////////TIMESTAMP/////////////////////////
				std::clock_t t = std::clock() - firstClock;
				double timeStamp = ((double)t/(double)CLOCKS_PER_SEC);
				ss.str("");
				ss << std::setprecision(8) << timeStamp;
				std::string sTimeStamp = ss.str();
				std::string gnuPlotStringT = ss.str();
				std::wstring wTimeStamp;
				wTimeStamp.assign(sTimeStamp.begin(),sTimeStamp.end());
				data[L"timestamp"] = cpptempl::make_data(wTimeStamp);

				///OVERHEAD/////
				templateClock += std::clock()-littleClock;
				long double overhead = (long double)templateClock / ((long double)std::clock()-(long double)firstClock)*(long double)100.0;
				ss.str("");
				ss << std::setprecision(10) << overhead;
				std::string sOverhead = ss.str();
				std::wstring wOverhead;
				wOverhead.assign(sOverhead.begin(),sOverhead.end());
				data[L"overhead"] = cpptempl::make_data(wOverhead);
				std::cout << overhead << "% overhead\n";
				//std::cout << std::clock() << " clocl\n";

				/////////////////MESSAGENUMBER/////////////////////////<
			        ss.str("");
			        ss << messageNumber;
			        std::string gnuPlotStringN = ss.str();
			        std::string sMessageNumber = ss.str();
			        std::wstring wMessageNumber;
			        wMessageNumber.assign(sMessageNumber.begin(),sMessageNumber.end());
			        data[L"messagenumber"] = cpptempl::make_data(wMessageNumber);

				std::wstring result = cpptempl::parse(templ, data);
				
				ss.str("");
				
				double templateTime = ((double)templateClock/(double)CLOCKS_PER_SEC)*(double)1000;
				ss << std::setprecision(8) << templateTime;
				std::string templTime = ss.str();				
				
				double totalT = ((std::clock()-firstClock)/(double)CLOCKS_PER_SEC);
				std::cout << totalT << "totaltime\n";
				std::cout << CYCLES_PER_SECOND << "cycles\n";
				std::string s;
		    		s.assign(result.begin(), result.end());
				
				if (messageNumber == 1)
				{
					std::ofstream traceoutput;
					traceoutput.open("/tmp/traceout.xml",std::ios::out);
					traceoutput << s;
					traceoutput.close();
				}

				messageNumber++;

				/////STATS/////
								

				output << s;
		
				std::string out = gnuPlotStringN + "," + gnuPlotStringT + "\n";
				outputEventsPerSec << out;
		
				//OutputNT
				//std::string theT;
				out = "";
				//ss.str("");
				//ss << templTime;
				//theT = ss.str();
				out = templTime + "," + gnuPlotStringN + "\n";
				outputNT << out;
				
			}
			/////////////////////////////////////////////////////////////////
		}

		TriggersEachCycle();      // handle triggers
		UpdateMessages();         // update messages
		ParticleManager.update(); // handle particles

		CheckMusicFinished();     // Check for next song

		//
		// Map scrolling
		//
		DoScrollArea(MouseScrollState | KeyScrollState, (KeyModifiers & ModifierControl) != 0);

		if (FastForwardCycle <= GameCycle || GameCycle <= 10 || !(GameCycle & 0x3f)) {
			//FIXME: this might be better placed somewhere at front of the
			// program, as we now still have a game on the background and
			// need to go through the game-menu or supply a map file
			UpdateDisplay();

			//
			// If double-buffered mode, we will display the contains of
			// VideoMemory. If direct mode this does nothing. In X11 it does
			// XFlush
			//
			RealizeVideoMemory();
		}

		if (FastForwardCycle <= GameCycle || !(GameCycle & 0x3f)) {
			WaitEventsOneFrame();
		}
		if (!NetworkInSync) {
			NetworkRecover(); // recover network
		}

		
	}

	output.close();
	outputNT.close();
    	outputEventsPerSec.close();
	//
	// Game over
	//
	NetworkQuit();
	EndReplayLog();

	CParticleManager::exit();

	FlagRevealMap = 0;
	ReplayRevealMap = 0;
	GamePaused = false;
	GodMode = false;

	SetCallbacks(old_callbacks);
}