Example #1
0
        internal void InitializeBeforeRun()
        {
            try
            {
                using (var profile = Profiler.Begin(GameProfilingKeys.GameInitialize))
                {
                    // Make sure that the device is already created
                    graphicsDeviceManager.CreateDevice();

                    // Gets the graphics device service
                    graphicsDeviceService = Services.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
                    if (graphicsDeviceService == null)
                    {
                        throw new InvalidOperationException("No GraphicsDeviceService found");
                    }

                    // Checks the graphics device
                    if (graphicsDeviceService.GraphicsDevice == null)
                    {
                        throw new InvalidOperationException("No GraphicsDevice found");
                    }

                    // Bind Graphics Context enabling initialize to use GL API eg. SetData to texture ...etc
                    BeginDraw();

                    // Initialize this instance and all game systems
                    Initialize();

                    LoadContentInternal();

                    IsRunning = true;

                    BeginRun();

                    timer.Reset();
                    updateTime.Reset(totalUpdateTime);

                    // Run the first time an update
                    updateTimer.Reset();
                    using (Profiler.Begin(GameProfilingKeys.GameUpdate))
                    {
                        Update(updateTime);
                    }
                    updateTimer.Tick();
                    singleFrameUpdateTime += updateTimer.ElapsedTime;

                    // Reset PlayTime
                    playTimer.Reset();

                    // Unbind Graphics Context without presenting
                    EndDraw(false);
                }
            }
            catch (Exception ex)
            {
                Log.Error("Unexpected exception", ex);
                throw;
            }
        }
Example #2
0
 public void Render()
 {
     if (Renderer == null || IsInDesignMode)
     {
         return;
     }
     ++fpsFrameCounter;
     renderTimer.Tick();
     if (renderTimer.TotalTime - lastFpsUpdate > TimeSpan.FromSeconds(1.0))
     {
         FPS             = fpsFrameCounter / (renderTimer.TotalTime - lastFpsUpdate).TotalSeconds;
         lastFpsUpdate   = renderTimer.TotalTime;
         fpsFrameCounter = 0;
     }
     Renderer.Render(GetDrawEventArgs());
     InvalidateVisual();
 }
Example #3
0
 private void Update()
 {
     uiManager.Update();
     timerTick.Tick();
     applicationTime.Update(totalTime, timerTick.ElapsedTime, false);
     overlay.Update(applicationTime);
     totalTime += timerTick.ElapsedTime;
 }
Example #4
0
        public override void Update()
        {
            if (m_FirstRun)
            {
                FirstTime();
            }

            if (!m_Pause)
            {
                m_FlameTimer.Tick();

                if (!m_Hit && !m_GameOver)
                {
                    base.Update();
                    GetInput();
                    CheckForEdge();
                }

                if (m_Hit)
                {
                    if (m_Spawn && !b_Exploding)
                    {
                        Reset();
                    }

                    if (b_Exploding)
                    {
                        bool active = false;

                        foreach (Line line in m_Explosion)
                        {
                            if (line.Active())
                            {
                                active = true;
                                break;
                            }
                        }

                        if (!active)
                        {
                            b_Exploding = false;
                        }
                    }
                }
            }

            if (m_GameOver && !b_Exploding)
            {
                m_Hit = false;
                GameOver();

                if (m_NewHighScore)
                {
                    HideHighScoreList();
                    NewHighScore();
                }
            }
        }
Example #5
0
        public override void Update()
        {
            if (IsActive())
            {
                base.Update();
                lifeTimer.Tick();

                if (lifeTimer.TotalTime.TotalSeconds > timerAmount)
                {
                    Destroy();
                }
            }
        }
Example #6
0
        protected virtual void RawTickProducer()
        {
            try
            {
                // Update the timer
                autoTickTimer.Tick();

                var elapsedAdjustedTime = autoTickTimer.ElapsedTimeWithPause;

                if (forceElapsedTimeToZero)
                {
                    elapsedAdjustedTime    = TimeSpan.Zero;
                    forceElapsedTimeToZero = false;
                }

                if (elapsedAdjustedTime > maximumElapsedTime)
                {
                    elapsedAdjustedTime = maximumElapsedTime;
                }

                int updateCount            = 1;
                var singleFrameElapsedTime = elapsedAdjustedTime;

                if (IsFixedTimeStep)
                {
                    // If the rounded TargetElapsedTime is equivalent to current ElapsedAdjustedTime
                    // then make ElapsedAdjustedTime = TargetElapsedTime. We take the same internal rules as XNA
                    if (Math.Abs(elapsedAdjustedTime.Ticks - TargetElapsedTime.Ticks) < (TargetElapsedTime.Ticks >> 6))
                    {
                        elapsedAdjustedTime = TargetElapsedTime;
                    }

                    // Update the accumulated time
                    accumulatedElapsedGameTime += elapsedAdjustedTime;

                    // Calculate the number of update to issue
                    updateCount = (int)(accumulatedElapsedGameTime.Ticks / TargetElapsedTime.Ticks);

                    // We are going to call Update updateCount times, so we can subtract this from accumulated elapsed game time
                    accumulatedElapsedGameTime = new TimeSpan(accumulatedElapsedGameTime.Ticks - (updateCount * TargetElapsedTime.Ticks));
                    singleFrameElapsedTime     = TargetElapsedTime;
                }

                RawTick(singleFrameElapsedTime, updateCount);
            }
            catch (Exception ex)
            {
                Log.Error("Unexpected exception", ex);
                throw;
            }
        }
Example #7
0
        public override void Update()
        {
            base.Update();

            if (IsActive() && !hit)
            {
                base.Update();

                if (!Main.instance.gameOver)
                {
                    if (type == UFOType.Large)
                    {
                        if (largeUFOSoundInstance.PlayState != PlayState.Playing)
                        {
                            largeUFOSoundInstance.Play();
                        }
                    }
                    else
                    {
                        if (smallUFOSoundInstance.PlayState != PlayState.Playing)
                        {
                            smallUFOSoundInstance.Play();
                        }
                    }
                }

                CheckForCollusion();

                if (position.X > edge.X || position.X < -edge.X)
                {
                    Disable();
                }

                CheckForEdge();
                vectorTimer.Tick();
                fireTimer.Tick();

                if (vectorTimer.TotalTime.Seconds > vectorAmount)
                {
                    vectorTimer.Reset();
                    ChangeVector();
                }

                if (fireTimer.TotalTime.Seconds > fireAmount)
                {
                    fireTimer.Reset();
                    Fire();
                }
            }
        }
Example #8
0
        public override void Update()
        {
            if (m_DotMesh.Enabled && !m_Pause)
            {
                base.Update();

                if (m_Timer.TotalTime.TotalSeconds > m_TimerAmount)
                {
                    Destroy();
                }

                m_Timer.Tick();
            }
        }
Example #9
0
        public override void Update()
        {
            if (shotMesh.Enabled)
            {
                base.Update();
                CheckForEdge();

                if (timer.TotalTime.TotalSeconds > timerAmount)
                {
                    Disable();
                }

                timer.Tick();
            }
        }
Example #10
0
        public override void Update()
        {
            spawnTimer.Tick();

            if (spawnTimer.TotalTime.Seconds > spawnAmount + spawnAdj)
            {
                ResetTimer();

                if (UFOScript.IsActive())
                {
                    return;
                }

                SpawnUFO();
            }
        }
Example #11
0
        void CompositionTarget_Rendering(object sender, EventArgs _e)
        {
            var e = (System.Windows.Media.RenderingEventArgs)_e;

            var diff = e.RenderingTime - m_lastRender;

            if (diff == TimeSpan.Zero)
            {
                return;
            }

            m_lastRender = e.RenderingTime;

            m_timer.Tick();

            this.Time.Update(m_timer.TotalTime, m_timer.ElapsedTime);

            var time = m_timer.TotalTime;

            // Setup surfaces
            foreach (var surfaces in this.Surfaces)
            {
                surfaces.ResizePresenter();
            }

            // UPDATE
            foreach (var updatable in this.Updatables)
            {
                updatable.Update();
            }

            // DRAW
            foreach (var target in this.Surfaces)
            {
                target.Draw();
            }
        }
Example #12
0
        // <inheritdoc />
        protected override void Update(GameTime gameTime)
        {
            // Keep going only if last exception has been "resolved"
            if (Faulted)
            {
                return;
            }

            if (IsEditorHidden)
            {
                gameHiddenUpdateTimer.Tick();
                gameHiddenUpdateTimeElapsed += gameHiddenUpdateTimer.ElapsedTime;
                if (gameHiddenUpdateTimeElapsed < GameHiddenNextUpdateTime)
                {
                    return;
                }
                else
                {
                    gameHiddenUpdateTimeElapsed = TimeSpan.Zero;    // It doesn't matter how much it exceeded the threshold, taking longer than one second is ok since it's hidden
                }
            }

            try
            {
                base.Update(gameTime);
            }
            catch (Exception ex)
            {
                if (!OnFault(ex))
                {
                    // Exception was no handled, rethrow
                    throw;
                }
                // Caught exception, turning game into faulted state
                Faulted = true;
            }
        }
Example #13
0
        private void DoTick()
        {
            try
            {
                // Update the timer
                _autoTickTimer.Tick();

                var elapsedTime = _autoTickTimer.ElapsedTimeWithPause;
                using (Profiler.Begin(GameProfilingKeys.GameUpdate))
                {
                    _updateTime.Update(_updateTime.Total + elapsedTime, elapsedTime, incrementFrameCount: true);
                    _gameEngine.Update();
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Unexpected exception.", ex);
                throw;
            }
            finally
            {
                CheckEndRun();
            }
        }
Example #14
0
        public override void Update()
        {
            if (!m_Pause)
            {
                if (m_Hit = CheckCollisions())
                {
                    Explode();
                }

                if (Active() && !m_Hit && !b_Done)
                {
                    base.Update();

                    if (!m_GameOver)
                    {
                        if (m_Large)
                        {
                            m_LargeUFOSoundInstance.Play();
                        }
                        else
                        {
                            m_SmallUFOSoundInstance.Play();
                        }
                    }

                    if (m_Position.X > m_Edge.X || m_Position.X < -m_Edge.X)
                    {
                        b_Done = true;
                    }
                    else
                    {
                        CheckForEdge();
                    }

                    if (m_ShotTimer.TotalTime.Seconds > m_ShotTimerAmount)
                    {
                        m_FireSoundInstance.Stop();

                        if (!m_GameOver)
                        {
                            m_FireSoundInstance.Play();
                        }

                        m_ShotTimer.Reset();
                        float speed = 30;
                        float rad   = 0;

                        if (m_Large)
                        {
                            rad = RandomRadian();
                        }
                        else
                        {
                            rad = (float)Math.Atan2(m_Player.m_Position.Y - m_Position.Y,
                                                    m_Player.m_Position.X - m_Position.X);

                            rad += (float)m_Random.NextDouble() * 0.1f - 0.1f;
                        }

                        Vector3 dir    = new Vector3((float)Math.Cos(rad) * speed, (float)Math.Sin(rad) * speed, 0);
                        Vector3 offset = new Vector3((float)Math.Cos(rad) * m_Radius, (float)Math.Sin(rad) * m_Radius, 0);
                        m_Shot.Spawn(m_Position + offset, dir + m_Velocity * 0.25f, 1.05f);
                    }

                    if (m_VectorTimer.TotalTime.Seconds > m_VectorTimerAmount)
                    {
                        m_VectorTimer.Reset();
                        float vChange = (float)m_Random.NextDouble() * 10;

                        if (vChange < 5)
                        {
                            if ((int)m_Velocity.Y == 0 && vChange < 2.5)
                            {
                                m_Velocity.Y = m_Speed;
                            }
                            else if ((int)m_Velocity.Y == 0)
                            {
                                m_Velocity.Y = -m_Speed;
                            }
                            else
                            {
                                m_Velocity.Y = 0;
                            }
                        }
                    }

                    m_ShotTimer.Tick();
                    m_VectorTimer.Tick();
                }
            }
        }
Example #15
0
        private void TickInternal()
        {
            try
            {
                // If this instance is existing, then don't make any further update/draw
                if (isExiting)
                {
                    CheckEndRun();
                    return;
                }

                // If this instance is not active, sleep for an inactive sleep time
                if (!IsActive)
                {
                    Utilities.Sleep(InactiveSleepTime);
                    return;
                }

                // Update the timer
                timer.Tick();

                // Update the playTimer timer
                playTimer.Tick();

                // Measure updateTimer
                updateTimer.Reset();

                var elapsedAdjustedTime = timer.ElapsedTimeWithPause;

                if (forceElapsedTimeToZero)
                {
                    elapsedAdjustedTime    = TimeSpan.Zero;
                    forceElapsedTimeToZero = false;
                }

                if (elapsedAdjustedTime > maximumElapsedTime)
                {
                    elapsedAdjustedTime = maximumElapsedTime;
                }

                bool suppressNextDraw       = true;
                int  updateCount            = 1;
                var  singleFrameElapsedTime = elapsedAdjustedTime;
                var  drawLag = 0L;

                if (IsFixedTimeStep)
                {
                    // If the rounded TargetElapsedTime is equivalent to current ElapsedAdjustedTime
                    // then make ElapsedAdjustedTime = TargetElapsedTime. We take the same internal rules as XNA
                    if (Math.Abs(elapsedAdjustedTime.Ticks - TargetElapsedTime.Ticks) < (TargetElapsedTime.Ticks >> 6))
                    {
                        elapsedAdjustedTime = TargetElapsedTime;
                    }

                    // Update the accumulated time
                    accumulatedElapsedGameTime += elapsedAdjustedTime;

                    // Calculate the number of update to issue
                    if (ForceOneUpdatePerDraw)
                    {
                        updateCount = 1;
                    }
                    else
                    {
                        updateCount = (int)(accumulatedElapsedGameTime.Ticks / TargetElapsedTime.Ticks);
                    }

                    if (IsDrawDesynchronized)
                    {
                        drawLag          = accumulatedElapsedGameTime.Ticks % TargetElapsedTime.Ticks;
                        suppressNextDraw = false;
                    }
                    else if (updateCount == 0)
                    {
                        // If there is no need for update, then exit
                        return;
                    }

                    // Calculate a moving average on updateCount
                    lastUpdateCount[nextLastUpdateCountIndex] = updateCount;
                    float updateCountMean = 0;
                    for (int i = 0; i < lastUpdateCount.Length; i++)
                    {
                        updateCountMean += lastUpdateCount[i];
                    }

                    updateCountMean         /= lastUpdateCount.Length;
                    nextLastUpdateCountIndex = (nextLastUpdateCountIndex + 1) % lastUpdateCount.Length;

                    // Test when we are running slowly
                    drawRunningSlowly = updateCountMean > updateCountAverageSlowLimit;

                    // We are going to call Update updateCount times, so we can substract this from accumulated elapsed game time
                    accumulatedElapsedGameTime = new TimeSpan(accumulatedElapsedGameTime.Ticks - (updateCount * TargetElapsedTime.Ticks));
                    singleFrameElapsedTime     = TargetElapsedTime;
                }
                else
                {
                    Array.Clear(lastUpdateCount, 0, lastUpdateCount.Length);
                    nextLastUpdateCountIndex = 0;
                    drawRunningSlowly        = false;
                }

                bool beginDrawSuccessful = false;
                try
                {
                    beginDrawSuccessful = BeginDraw();

                    // Reset the time of the next frame
                    for (lastFrameElapsedGameTime = TimeSpan.Zero; updateCount > 0 && !isExiting; updateCount--)
                    {
                        updateTime.Update(totalUpdateTime, singleFrameElapsedTime, singleFrameUpdateTime, drawRunningSlowly, true);
                        try
                        {
                            UpdateAndProfile(updateTime);
                            if (EarlyExit)
                            {
                                return;
                            }

                            // If there is no exception, then we can draw the frame
                            suppressNextDraw &= suppressDraw;
                            suppressDraw      = false;
                        }
                        finally
                        {
                            lastFrameElapsedGameTime += singleFrameElapsedTime;
                            totalUpdateTime          += singleFrameElapsedTime;
                        }
                    }

                    // End measuring update time
                    updateTimer.Tick();
                    singleFrameUpdateTime += updateTimer.ElapsedTime;

                    // Update game time just before calling draw
                    //updateTime.Update(totalUpdateTime, singleFrameElapsedTime, singleFrameUpdateTime, drawRunningSlowly, true);

                    if (!suppressNextDraw)
                    {
                        totalDrawTime           = TimeSpan.FromTicks(totalUpdateTime.Ticks + drawLag);
                        DrawInterpolationFactor = drawLag / (float)TargetElapsedTime.Ticks;
                        DrawFrame();
                    }

                    singleFrameUpdateTime = TimeSpan.Zero;
                }
                finally
                {
                    if (beginDrawSuccessful)
                    {
                        using (Profiler.Begin(GameProfilingKeys.GameEndDraw))
                        {
                            EndDraw(true);
                            if (gamePlatform.MainWindow.IsMinimized || gamePlatform.MainWindow.Visible == false || (gamePlatform.MainWindow.Focused == false && TreatNotFocusedLikeMinimized))
                            {
                                MinimizedMinimumUpdateRate.Throttle(out _);
                            }
                            else
                            {
                                WindowMinimumUpdateRate.Throttle(out _);
                            }
                        }
                    }

                    CheckEndRun();
                }
            }
            catch (Exception ex)
            {
                Log.Error("Unexpected exception", ex);
                throw;
            }
        }
Example #16
0
        /// <summary>
        /// Calls <see cref="RawTick"/> automatically based on this game's setup, override it to implement your own system.
        /// </summary>
        protected virtual void RawTickProducer()
        {
            try
            {
                // Update the timer
                autoTickTimer.Tick();

                var elapsedAdjustedTime = autoTickTimer.ElapsedTimeWithPause;

                if (forceElapsedTimeToZero)
                {
                    elapsedAdjustedTime    = TimeSpan.Zero;
                    forceElapsedTimeToZero = false;
                }

                if (elapsedAdjustedTime > maximumElapsedTime)
                {
                    elapsedAdjustedTime = maximumElapsedTime;
                }

                bool drawFrame              = true;
                int  updateCount            = 1;
                var  singleFrameElapsedTime = elapsedAdjustedTime;
                var  drawLag = 0L;

                if (suppressDraw || Window.IsMinimized && DrawWhileMinimized == false)
                {
                    drawFrame    = false;
                    suppressDraw = false;
                }

                if (IsFixedTimeStep)
                {
                    // If the rounded TargetElapsedTime is equivalent to current ElapsedAdjustedTime
                    // then make ElapsedAdjustedTime = TargetElapsedTime. We take the same internal rules as XNA
                    if (Math.Abs(elapsedAdjustedTime.Ticks - TargetElapsedTime.Ticks) < (TargetElapsedTime.Ticks >> 6))
                    {
                        elapsedAdjustedTime = TargetElapsedTime;
                    }

                    // Update the accumulated time
                    accumulatedElapsedGameTime += elapsedAdjustedTime;

                    // Calculate the number of update to issue
                    if (ForceOneUpdatePerDraw)
                    {
                        updateCount = 1;
                    }
                    else
                    {
                        updateCount = (int)(accumulatedElapsedGameTime.Ticks / TargetElapsedTime.Ticks);
                    }

                    if (IsDrawDesynchronized)
                    {
                        drawLag = accumulatedElapsedGameTime.Ticks % TargetElapsedTime.Ticks;
                    }
                    else if (updateCount == 0)
                    {
                        drawFrame = false;
                        // If there is no need for update, then exit
                        return;
                    }

                    // We are going to call Update updateCount times, so we can substract this from accumulated elapsed game time
                    accumulatedElapsedGameTime = new TimeSpan(accumulatedElapsedGameTime.Ticks - (updateCount * TargetElapsedTime.Ticks));
                    singleFrameElapsedTime     = TargetElapsedTime;
                }

                RawTick(singleFrameElapsedTime, updateCount, drawLag / (float)TargetElapsedTime.Ticks, drawFrame);

                var window = gamePlatform.MainWindow;
                if (gamePlatform.IsBlockingRun) // throttle fps if Game.Tick() called from internal main loop
                {
                    if (window.IsMinimized || window.Visible == false || (window.Focused == false && TreatNotFocusedLikeMinimized))
                    {
                        MinimizedMinimumUpdateRate.Throttle(out _);
                    }
                    else
                    {
                        WindowMinimumUpdateRate.Throttle(out _);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("Unexpected exception", ex);
                throw;
            }
        }
Example #17
0
        public void Tick()
        {
            if (timer == null)
            {
                return;
            }

            // Update the timer
            timer.Tick();

            var elapsedAdjustedTime = timer.ElapsedAdjustedTime;

            if (forceElapsedTimeToZero)
            {
                elapsedAdjustedTime    = TimeSpan.Zero;
                forceElapsedTimeToZero = false;
            }

            if (elapsedAdjustedTime > maximumElapsedTime)
            {
                elapsedAdjustedTime = maximumElapsedTime;
            }

            bool suppressNextDraw       = true;
            int  updateCount            = 1;
            var  singleFrameElapsedTime = elapsedAdjustedTime;

            if (IsFixedTimeStep)
            {
                // If the rounded TargetElapsedTime is equivalent to current ElapsedAdjustedTime
                // then make ElapsedAdjustedTime = TargetElapsedTime. We take the same internal rules as XNA
                if (Math.Abs(elapsedAdjustedTime.Ticks - TargetElapsedTime.Ticks) < (TargetElapsedTime.Ticks >> 6))
                {
                    elapsedAdjustedTime = TargetElapsedTime;
                }

                // Update the accumulated time
                accumulatedElapsedGameTime += elapsedAdjustedTime;

                // Calculate the number of update to issue
                updateCount = (int)(accumulatedElapsedGameTime.Ticks / TargetElapsedTime.Ticks);

                // If there is no need for update, then exit
                if (updateCount == 0)
                {
                    return;
                }

                // Calculate a moving average on updateCount
                lastUpdateCount[nextLastUpdateCountIndex] = updateCount;
                float updateCountMean = 0;
                for (int i = 0; i < lastUpdateCount.Length; i++)
                {
                    updateCountMean += lastUpdateCount[i];
                }

                updateCountMean         /= lastUpdateCount.Length;
                nextLastUpdateCountIndex = (nextLastUpdateCountIndex + 1) % lastUpdateCount.Length;

                // Test when we are running slowly
                drawRunningSlowly = updateCountMean > updateCountAverageSlowLimit;

                // We are going to call Update updateCount times, so we can substract this from accumulated elapsed game time
                accumulatedElapsedGameTime = new TimeSpan(accumulatedElapsedGameTime.Ticks - (updateCount * TargetElapsedTime.Ticks));
                singleFrameElapsedTime     = TargetElapsedTime;
            }
            else
            {
                Array.Clear(lastUpdateCount, 0, lastUpdateCount.Length);
                nextLastUpdateCountIndex = 0;
                drawRunningSlowly        = false;
            }

            // Reset the time of the next frame
            for (lastFrameElapsedGameTime = TimeSpan.Zero; updateCount > 0 && !isExiting; updateCount--)
            {
                gameTime.Update(totalGameTime, singleFrameElapsedTime, drawRunningSlowly);

                try
                {
                    //Update(gameTime);

                    // If there is no exception, then we can draw the frame
                    suppressNextDraw &= suppressDraw;
                    suppressDraw      = false;
                }
                finally
                {
                    lastFrameElapsedGameTime += singleFrameElapsedTime;
                    totalGameTime            += singleFrameElapsedTime;
                }
            }

            if (!suppressNextDraw)
            {
                //DrawFrame();
                gameTime.FrameCount++;
            }
        }
Example #18
0
        /// <summary>
        /// Updates the game's clock and calls Update and Draw.
        /// </summary>
        public void Tick()
        {
            // If this instance is existing, then don't make any further update/draw
            if (isExiting)
            {
                return;
            }

            // If this instance is not active, sleep for an inactive sleep time
            if (!IsActive)
            {
                SharpDX.Utilities.Sleep(InactiveSleepTime);
            }

            // Update the timer
            timer.Tick();

            var elapsedAdjustedTime = timer.ElapsedAdjustedTime;

            if (forceElapsedTimeToZero)
            {
                elapsedAdjustedTime    = TimeSpan.Zero;
                forceElapsedTimeToZero = false;
            }

            if (elapsedAdjustedTime > maximumElapsedTime)
            {
                elapsedAdjustedTime = maximumElapsedTime;
            }

            bool suppressNextDraw       = true;
            int  updateCount            = 1;
            var  singleFrameElapsedTime = elapsedAdjustedTime;

            if (IsFixedTimeStep)
            {
                // If the rounded TargetElapsedTime is equivalent to current ElapsedAdjustedTime
                // then make ElapsedAdjustedTime = TargetElapsedTime. We take the same internal rules as XNA
                if (Math.Abs(elapsedAdjustedTime.Ticks - TargetElapsedTime.Ticks) < (TargetElapsedTime.Ticks >> 6))
                {
                    elapsedAdjustedTime = TargetElapsedTime;
                }

                // Update the accumulated time
                accumulatedElapsedGameTime += elapsedAdjustedTime;

                // Calculate the number of update to issue
                updateCount = (int)(accumulatedElapsedGameTime.Ticks / TargetElapsedTime.Ticks);

                // If there is no need for update, then exit
                if (updateCount == 0)
                {
                    // check if we can sleep the thread to free CPU resources
                    var sleepTime = TargetElapsedTime - accumulatedElapsedGameTime;
                    if (sleepTime > TimeSpan.Zero)
                    {
                        SharpDX.Utilities.Sleep(sleepTime);
                    }
                    return;
                }

                // Calculate a moving average on updateCount
                lastUpdateCount[nextLastUpdateCountIndex] = updateCount;
                float updateCountMean = 0;
                for (int i = 0; i < lastUpdateCount.Length; i++)
                {
                    updateCountMean += lastUpdateCount[i];
                }

                updateCountMean         /= lastUpdateCount.Length;
                nextLastUpdateCountIndex = (nextLastUpdateCountIndex + 1) % lastUpdateCount.Length;

                // Test when we are running slowly
                drawRunningSlowly = updateCountMean > updateCountAverageSlowLimit;

                // We are going to call Update updateCount times, so we can subtract this from accumulated elapsed game time
                accumulatedElapsedGameTime = new TimeSpan(accumulatedElapsedGameTime.Ticks - (updateCount * TargetElapsedTime.Ticks));
                singleFrameElapsedTime     = TargetElapsedTime;
            }
            else
            {
                Array.Clear(lastUpdateCount, 0, lastUpdateCount.Length);
                nextLastUpdateCountIndex = 0;
                drawRunningSlowly        = false;
            }

            // Reset the time of the next frame
            for (lastFrameElapsedAppTime = TimeSpan.Zero; updateCount > 0 && !isExiting; updateCount--)
            {
                appTime.Update(totalTime, singleFrameElapsedTime, drawRunningSlowly);
                try
                {
                    updateCallback.Update(appTime);

                    // If there is no exception, then we can draw the frame
                    suppressNextDraw &= suppressDraw;
                    suppressDraw      = false;
                }
                finally
                {
                    lastFrameElapsedAppTime += singleFrameElapsedTime;
                    totalTime += singleFrameElapsedTime;
                }
            }

            if (!suppressNextDraw)
            {
                RenderFrame();
            }
        }
Example #19
0
        public void Update()
        {
            try
            {
                // Update the timer
                _autoTickTimer.Tick();

                var elapsedAdjustedTime = _autoTickTimer.ElapsedTimeWithPause;
                if (GameClockManager.NetworkServerSimulationClock.IsEnabled)
                {
                    // Network clock uses the full elapsed time
                    GameClockManager.NetworkServerSimulationClock.CurrentTickTimeElapsed += elapsedAdjustedTime;
                    GameClockManager.NetworkServerSimulationClock.TargetTotalTime        += elapsedAdjustedTime;

                    var nextSimTotalTime = GameClockManager.SimulationClock.TotalTime + elapsedAdjustedTime;
                    var targetTimeDiff   = GameClockManager.NetworkServerSimulationClock.TargetTotalTime - nextSimTotalTime;
                    // If targetTimeDiff > 0, our clock is too slow (ie. we're behind the target)
                    // If targetTimeDiff < 0, our clock is too fast (ie. we're ahead of the target)
                    var timeOffsetTicks = targetTimeDiff.Ticks;
                    if (Math.Abs(timeOffsetTicks) > _targetTimeDriftAdjustmentThreshold)
                    {
                        timeOffsetTicks /= 10;                                                               // Only take 10% of the diff to reduce it jumping too much
                    }
                    var elapsedAdjustedTimeTicks = Math.Max(0, elapsedAdjustedTime.Ticks + timeOffsetTicks); // Ensure elapsed time is never negative/backwards
                    elapsedAdjustedTime = TimeSpan.FromTicks(elapsedAdjustedTimeTicks);
                }
                if (_forceElapsedTimeToZero)
                {
                    elapsedAdjustedTime     = TimeSpan.Zero;
                    _forceElapsedTimeToZero = false;
                }
                if (elapsedAdjustedTime > MaximumElapsedTime)
                {
                    elapsedAdjustedTime = MaximumElapsedTime;
                }

                // If the rounded targetElapsedTime is equivalent to current ElapsedAdjustedTime
                // then make ElapsedAdjustedTime = TargetElapsedTime. We take the same internal rules as XNA
                var targetElapsedTime      = GameClockManager.SimulationDeltaTime;
                var targetElapsedTimeTicks = targetElapsedTime.Ticks;
                if (Math.Abs(elapsedAdjustedTime.Ticks - targetElapsedTimeTicks) < (targetElapsedTimeTicks >> 6))
                {
                    elapsedAdjustedTime = targetElapsedTime;
                }

                var  updatableElapsedTimeRemaining = elapsedAdjustedTime + _previousUpdatedNonSimulationElapsedGameTime;    // Technically we are allowing to go a little over the constrained limit...
                int  simUpdateCount               = (int)(updatableElapsedTimeRemaining.Ticks / targetElapsedTimeTicks);
                int  simUpdateCountRemaining      = simUpdateCount;
                var  singleFrameElapsedTime       = GameClockManager.SimulationDeltaTime;
                bool updateSingleCallSystems      = true;
                var  singleCallSystemsElapsedTime = elapsedAdjustedTime;
                SingleCallSystemsGameTime.Update(SingleCallSystemsGameTime.Total + singleCallSystemsElapsedTime, singleCallSystemsElapsedTime, incrementFrameCount: true);
                if (_previousUpdatedNonSimulationElapsedGameTime > TimeSpan.Zero && simUpdateCountRemaining > 0)
                {
                    // Special case update - There was a partial (non-simulated) update in the previous Update call,
                    // this update is the remainder of the update which is also simulation update.
                    var prevFrameSimElapsedTime = singleFrameElapsedTime - _previousUpdatedNonSimulationElapsedGameTime;
                    Debug.Assert(prevFrameSimElapsedTime.Ticks > 0);
                    UpdateForTimeElapsed(prevFrameSimElapsedTime, currentTickTimeElapsed: TimeSpan.Zero, updatePhysicsSimulation: true, ref updateSingleCallSystems);
                    updatableElapsedTimeRemaining -= singleFrameElapsedTime;        // Remove a full update's worth because this was added from _previousUpdatedNonSimulationElapsedGameTime
                    _previousUpdatedNonSimulationElapsedGameTime = TimeSpan.Zero;
                    simUpdateCountRemaining--;
                }
                if (simUpdateCountRemaining > 0)
                {
                    // Additional full simulation update(s). Multiple updates may occur if the engine needs to
                    // catch up to the target time, or the game froze for some reason.
                    UpdateForTimeElapsed(singleFrameElapsedTime, currentTickTimeElapsed: TimeSpan.Zero, updatePhysicsSimulation: true, ref updateSingleCallSystems, updateCount: simUpdateCountRemaining);
                    updatableElapsedTimeRemaining -= TimeSpan.FromTicks(singleFrameElapsedTime.Ticks * simUpdateCountRemaining);
                }
                else if (simUpdateCountRemaining == 0 && _previousUpdatedNonSimulationElapsedGameTime > TimeSpan.Zero)
                {
                    // Remove the previous updated time, otherwise we double up on the update
                    updatableElapsedTimeRemaining -= _previousUpdatedNonSimulationElapsedGameTime;
                }
                //if (updatableElapsedTimeRemaining > GameUpdateMinimumNonSimulationElapsedTime || simUpdateCount == 0)
                if (updatableElapsedTimeRemaining > TimeSpan.Zero)
                {
                    // Do a non-simulation update because this Update call isn't hasn't
                    // elapsed enough for a simulation, or there is still some time remaining.
                    // The purpose of this is to make the rendering time closer to the actual time elapsed,
                    // or ensure at least one engine update call is done per Update call.
                    var currentTickTimeElapsed = updatableElapsedTimeRemaining + _previousUpdatedNonSimulationElapsedGameTime;
                    UpdateForTimeElapsed(updatableElapsedTimeRemaining, currentTickTimeElapsed, updatePhysicsSimulation: false, ref updateSingleCallSystems);
                    _previousUpdatedNonSimulationElapsedGameTime = currentTickTimeElapsed;
                }

                GameSystemsPostUpdate();
            }
            catch (Exception ex)
            {
                Logger.Error("Unexpected exception.", ex);
                throw;
            }
        }
Example #20
0
        public override void Update()
        {
            m_NumberOfRocksLastFrame = m_NumberOfRocksThisFrame;
            int  rockCount   = 0;
            int  smrockCount = 0;
            int  mdrockCount = 0;
            int  lgrockCount = 0;
            bool playerClear = true;

            foreach (Rock rock in m_LargeRocks)
            {
                if (rock.m_Hit)
                {
                    rock.Destroy();
                    SpawnMedRocks(rock.m_Position);
                }

                if (rock.Active())
                {
                    rockCount++;
                    lgrockCount++;
                }
            }

            foreach (Rock rock in m_MedRocks)
            {
                if (rock.m_Hit)
                {
                    rock.Destroy();
                    SpawnSmallRocks(rock.m_Position);
                }

                if (rock.Active())
                {
                    rockCount++;
                    mdrockCount++;
                }
            }

            foreach (Rock rock in m_SmallRocks)
            {
                if (rock.m_Hit)
                {
                    rock.Destroy();
                }

                if (rock.Active())
                {
                    rockCount++;
                    smrockCount++;
                }
            }

            m_NumberOfRocksThisFrame = rockCount;

            if (m_NumberOfRocksLastFrame != m_NumberOfRocksThisFrame) //If([size]rockCount  < 4) {pitch = 1.2f + (0.05f × ( 4 - mdrockCount))}
            {
                float pitch = 1;

                if (lgrockCount == 0)
                {
                    if (mdrockCount > 3)
                    {
                        pitch = 1.2f;
                    }
                    else if (mdrockCount == 3)
                    {
                        pitch = 1.25f;
                    }
                    else if (mdrockCount == 2)
                    {
                        pitch = 1.3f;
                    }
                    else if (mdrockCount == 1)
                    {
                        pitch = 1.35f;
                    }

                    if (mdrockCount == 0)
                    {
                        if (smrockCount > 3)
                        {
                            pitch = 1.4f;
                        }
                        else if (smrockCount == 3)
                        {
                            pitch = 1.45f;
                        }
                        else if (smrockCount == 2)
                        {
                            pitch = 1.5f;
                        }
                        else if (smrockCount == 1)
                        {
                            pitch = 1.55f;
                        }
                    }
                }
                else if (lgrockCount > 3)
                {
                    pitch = 1;
                }
                else if (lgrockCount == 3)
                {
                    pitch = 1.05f;
                }
                else if (lgrockCount == 2)
                {
                    pitch = 1.1f;
                }
                else if (lgrockCount == 1)
                {
                    pitch = 1.15f;
                }

                m_Background.Pitch = pitch;
            }

            if (rockCount == 0)
            {
                m_LargeRockCount += 2;
                SpawnLargeRocks(m_LargeRockCount);
            }

            if (m_UFOTimer.TotalTime.TotalSeconds > m_UFOTimerSet && !m_UFO.Active())
            {
                m_UFOTimerSet = (float)m_Random.NextDouble() * m_UFOTimerAmount + ((m_UFOTimerAmount - m_Wave) * 0.5f);
                m_UFOTimer.Reset();
                m_UFO.Spawn(m_UFOCount, m_Wave);
                m_UFOCount++;
            }

            if (m_UFO.m_Done || m_UFO.m_Hit)
            {
                m_UFOTimer.Reset();
                m_UFO.Destroy();
            }

            if (m_Player.m_Hit)
            {
                foreach (Rock rock in m_LargeRocks)
                {
                    if (rock.Active())
                    {
                        if (m_Player.m_Hit)
                        {
                            if (!rock.CheckPlayerCLear())
                            {
                                playerClear = false;
                                break;
                            }
                        }
                    }
                }

                foreach (Rock rock in m_MedRocks)
                {
                    if (rock.Active())
                    {
                        if (m_Player.m_Hit)
                        {
                            if (!playerClear)
                            {
                                break;
                            }

                            if (!rock.CheckPlayerCLear())
                            {
                                playerClear = false;
                                break;
                            }
                        }
                    }
                }

                foreach (Rock rock in m_SmallRocks)
                {
                    if (rock.Active())
                    {
                        if (m_Player.m_Hit)
                        {
                            if (!playerClear)
                            {
                                break;
                            }

                            if (!rock.CheckPlayerCLear())
                            {
                                playerClear = false;
                                break;
                            }
                        }
                    }
                }

                if (playerClear)
                {
                    m_Player.m_Spawn = true;
                }

                if (m_UFO.Active())
                {
                    if (!m_UFO.CheckPlayerClear())
                    {
                        m_Player.m_Spawn = false;
                    }
                }

                if (m_UFO.m_Shot.Active())
                {
                    if (!m_UFO.m_Shot.CheckPlayerClear())
                    {
                        m_Player.m_Spawn = false;
                    }
                }
            }

            m_UFOTimer.Tick();

            if (m_Player.m_GameOver)
            {
                if (!m_Player.m_NewHighScore)
                {
                    if (Input.IsKeyPressed(Keys.N) || Input.IsKeyPressed(Keys.S) || Input.IsKeyPressed(Keys.Return))
                    {
                        NewGame();
                    }
                }

                if (!m_UFO.m_GameOver)
                {
                    m_Background.Stop();

                    foreach (Rock rock in m_LargeRocks)
                    {
                        rock.m_GameOver = true;
                    }

                    foreach (Rock rock in m_MedRocks)
                    {
                        rock.m_GameOver = true;
                    }

                    foreach (Rock rock in m_SmallRocks)
                    {
                        rock.m_GameOver = true;
                    }

                    m_UFO.m_GameOver = true;
                }
            }
            else
            {
                m_UFO.m_GameOver = false;

                if (m_Player.m_Pause)
                {
                    if (Input.IsKeyPressed(Keys.P))
                    {
                        m_Background.Play();

                        foreach (Rock rock in m_LargeRocks)
                        {
                            rock.Pause(false);
                        }

                        foreach (Rock rock in m_MedRocks)
                        {
                            rock.Pause(false);
                        }

                        foreach (Rock rock in m_SmallRocks)
                        {
                            rock.Pause(false);
                        }

                        m_UFO.Pause(false);
                        m_Player.Pause(false);

                        foreach (Shot shot in m_Player.m_Shots)
                        {
                            shot.Pause(false);
                        }
                    }
                }
                else
                {
                    m_Background.Play();

                    if (Input.IsKeyPressed(Keys.P))
                    {
                        m_Background.Stop();

                        foreach (Rock rock in m_LargeRocks)
                        {
                            rock.Pause(true);
                        }

                        foreach (Rock rock in m_MedRocks)
                        {
                            rock.Pause(true);
                        }

                        foreach (Rock rock in m_SmallRocks)
                        {
                            rock.Pause(true);
                        }

                        m_UFO.Pause(true);
                        m_Player.Pause(true);

                        foreach (Shot shot in m_Player.m_Shots)
                        {
                            shot.Pause(true);
                        }
                    }
                }
            }
        }