Example #1
0
 public void t_Elapsed(object sender, ElapsedEventArgs e)
 {
     if (TimePassed >= int.Parse(PlayTime) || TimePassed < 0)
     {
         Cash = TotalValue;
         t.Stop();
         t.Close();
         OnStopCommand();
         return;
     }
     monitoringNumber++;
     TimeLeft         = (int.Parse(PlayTime) - monitoringNumber).ToString();
     TimePassed       = monitoringNumber;
     ProgressBarValue = monitoringNumber;
     Cash             = TimePassed * Math.Floor(CashForHour / 60);
     if (TimePassed >= int.Parse(PlayTime) || TimePassed < 0)
     {
         Cash = TotalValue;
         t.Stop();
         t.Close();
         OnStopCommand();
         return;
     }
     if (TimePassed % 5 == 0)
     {
         MainPageViewModel.SendMsg(TimePassed.ToString(), ID);
     }
     JsonUser.AddUserToWokingTimeHistory(this);
     OnPropertyChanged(nameof(TimeLeft));
     OnPropertyChanged(nameof(Cash));
     OnPropertyChanged(nameof(TimePassed));
     OnPropertyChanged(nameof(ProgressBarValue));
     t.Interval = 60_000;
     t.Start();
 }
        public void Execute(Entity ent, int index, [ReadOnly] ref PlayerShoot shoot,
                            [ReadOnly] ref Translation pos, [ReadOnly] ref Rotation rotation)
        {
            // getting the right TimePassed
            DynamicBuffer <TimePassed> buffer = data.timePassedBuffers[ent];
            TimePassed timePassed             = buffer[shoot.timeIdx];

            timePassed.time += data.dt;

            if (timePassed.time >= shoot.shotCooldown)
            {
                // get data to update the bubble with
                WaterShootData shootData = bubbleData[index];
                shootData.timeHeld              = math.min(timePassed.time - shoot.shotCooldown, maxChargeTime);
                shootData.maxChargeTime         = maxChargeTime;
                shootData.position              = pos.Value;
                shootData.initialScale          = shoot.initialScale;
                shootData.initialColliderRadius = shoot.initialColliderRadius;
                shootData.bullet   = shoot.bullet;
                shootData.topSpeed = bubbleBurstTopSpeed;

                if (data.shooting)
                {
                    // create a new bubble
                    if (shootData.state == WaterShootState.NotFired)
                    {
                        Entity bullet = data.CreateBullet(index, ref pos, ref rotation, shoot.bullet, 0);
                        data.commandBuffer.AddComponent(index, bullet,
                                                        new WaterShootIndex {
                            index = index
                        });
                        data.commandBuffer.AddComponent(index, bullet,
                                                        new Scale {
                            Value = .3f
                        });
                        shootData.state = WaterShootState.JustFired;
                    }
                    else
                    {
                        shootData.state = WaterShootState.Charging;
                    }
                }
                else
                {
                    timePassed.time = shoot.shotCooldown;

                    // bullet was updated last frame, so it exists and was charged,
                    // so create burst of bullets
                    if (shootData.state == WaterShootState.UpdatedCharging)
                    {
                        shootData.state = WaterShootState.Burst;
                    }
                }

                bubbleData[index] = shootData;
            }

            buffer[shoot.timeIdx] = timePassed;
        }
Example #3
0
 public static ICommand[] When(TimePassed @event, Transport[] transports)
 => transports
 .Where(x => x.EnRoute)
 .Where(x => x.ETA == @event.Time)
 .Select(x => new Unload {
     TransportId = x.TransportId, Location = x.Location, Time = @event.Time
 })
 .ToArray();
Example #4
0
        public void Run()
        {
            if (_timePassed >= _timeToPass)
            {
                TimePassed?.Invoke(this, new EventArgs());
                return;
            }

            _timePassed++;

            Run();
        }
Example #5
0
 /// <summary>
 /// Handles internal timer's <see cref="Timer.Tick"/> event.
 /// </summary>
 /// <param name="sender">Event source.</param>
 /// <param name="e">An EventArgs containing event data.</param>
 private void Timer_Tick(object sender, EventArgs e)
 {
     if (timeRemaining > 1)
     {
         --timeRemaining;
         Tick?.Invoke(this, EventArgs.Empty);
     }
     else
     {
         TimePassed?.Invoke(this, EventArgs.Empty);
         Restart();
     }
 }
 /// <see cref="ITimeSource.ReportTimeProgress">
 public void ReportTimeProgress()
 {
     lock (reportTimeProgressLock)
     {
         var currentCommonElapsedTime = handles.CommonElapsedTime;
         if (currentCommonElapsedTime > previousElapsedVirtualTime)
         {
             var timeDiff = currentCommonElapsedTime - previousElapsedVirtualTime;
             this.Trace($"Reporting time passed: {timeDiff}");
             TimePassed?.Invoke(timeDiff);
             previousElapsedVirtualTime = currentCommonElapsedTime;
         }
     }
 }
Example #7
0
 private void TimerEvent(object sender, ElapsedEventArgs e)
 {
     if (_timerOn)
     {
         if (_currentPlayer == 1)
         {
             _xTime++;
         }
         else
         {
             _oTime++;
         }
         TimePassed?.Invoke(this, new TimePassedEventArgs(_xTime, _oTime));
     }
 }
Example #8
0
 /// <summary>
 /// Implements <see cref="INetworkDataProcessor.Process(string, string)"/>.
 /// </summary>
 /// <param name="code">Operation code.</param>
 /// <param name="body">Additional information about operation.</param>
 void INetworkDataProcessor.Process(string code, string body)
 {
     if (code == TimeCode)
     {
         if (TimeSpan.TryParse(body, out TimeSpan syncTime))
         {
             TimeLeft = (int)syncTime.TotalSeconds;
             Tick?.Invoke(this, EventArgs.Empty);
         }
     }
     else if (code == TimePassedCode)
     {
         TimePassed?.Invoke(this, EventArgs.Empty);
         Restart();
     }
 }
        /// <see cref="ITimeSource.ReportTimeProgress">
        public void ReportTimeProgress(TimeHandle h, TimeInterval diff)
        {
            if (diff.Ticks == 0)
            {
                return;
            }

            var currentCommonElapsedTime = handles.CommonElapsedTime;

            if (currentCommonElapsedTime > previousElapsedVirtualTime)
            {
                var timeDiff = currentCommonElapsedTime - previousElapsedVirtualTime;
                this.Trace($"Reporting time passed: {timeDiff}");
                TimePassed?.Invoke(timeDiff);
                previousElapsedVirtualTime = currentCommonElapsedTime;
            }
        }
        public void Execute(Entity ent, int index, [ReadOnly] ref PlayerShoot shoot)
        {
            WaterShootData waterData = bubbleData[index];

            // failed to update or bullet will not exist anymore, reset
            if (waterData.state != WaterShootState.UpdatedCharging && waterData.state != WaterShootState.NotFired &&
                waterData.state != WaterShootState.JustFired)
            {
                waterData.state = WaterShootState.NotFired;

                DynamicBuffer <TimePassed> buffer = data.timePassedBuffers[ent];
                TimePassed timePassed             = buffer[shoot.timeIdx];
                timePassed.time       = 0;
                buffer[shoot.timeIdx] = timePassed;
                bubbleData[index]     = waterData;
            }
        }
        internal async Task <Location> GetCurrentLocation(TimePassed accuracy)
        {
            if (!this.CheckIfNewLocationRequired(accuracy))
            {
                return(this.cachedLocation.Location);
            }

            GeolocationRequest request  = new GeolocationRequest(GeolocationAccuracy.Medium);
            Location           location = await Geolocation.GetLocationAsync(request);

            this.cachedLocation = new LocationAndTime()
            {
                Location = location,
                DateTime = System.DateTime.Now
            };

            return(location);
        }
Example #12
0
        // mark args as ReadOnly as much as possible
        public void Execute(Entity ent, int index, [ReadOnly] ref Translation position,
                            [ReadOnly] ref Rotation rotation)
        {
            DynamicBuffer <AutoShootBuffer> shootBuffer = autoShootBuffers[ent];
            DynamicBuffer <TimePassed>      buffer      = timePassedBuffers[ent];

            for (int i = 0; i < shootBuffer.Length; ++i)
            {
                AutoShoot shoot = shootBuffer[i].val;

                // getting the right TimePassed
                TimePassed timePassed  = buffer[shoot.timeIdx];
                TimePassed volleyCount = buffer[shoot.volleyCountIdx];
                timePassed.time += dt;

                if (timePassed.time > shoot.startDelay)
                {
                    float actualTime = timePassed.time - shoot.startDelay;

                    // EXTRA: add recovery for bullets not fired exactly when they should
                    // fire if above period and not on cooldown
                    while (actualTime >= shoot.period && volleyCount.time < shoot.numVolleys)
                    {
                        // shoot the pattern
                        Fire(ent, index, ref position, ref rotation, ref shoot, actualTime);
                        volleyCount.time += 1;
                        timePassed.time  -= shoot.period;
                        actualTime        = timePassed.time - shoot.startDelay;
                    }

                    // on cooldown, wait for time to pass to reset
                    if (actualTime >= shoot.cooldownDuration && volleyCount.time == shoot.numVolleys)
                    {
                        volleyCount.time = 0;
                        timePassed.time -= shoot.cooldownDuration;
                    }
                }

                // writing updates out
                buffer[shoot.timeIdx]        = timePassed;
                buffer[shoot.volleyCountIdx] = volleyCount;
            }
        }
Example #13
0
        public void Execute(Entity ent, int idx, [ReadOnly] ref PathMovement pathData,
                            ref Translation pos)
        {
            DynamicBuffer <PathPoint> points = pointBuffers[ent];

            if (points.Length > 0)
            {
                DynamicBuffer <TimePassed> timeBuffer = timeBuffers[ent];

                // compute update
                TimePassed curScale = timeBuffer[pathData.timeIdx];
                float3     nextPos  = EvalConstantSpeed(ref points, ref curScale.time,
                                                        pathData.speed, pathData.loopIndex);

                // update components
                timeBuffer[pathData.timeIdx] = curScale;
                pos.Value = nextPos;
            }
        }
        public void Execute(Entity ent, int index, [ReadOnly] ref PlayerShoot shoot,
                            [ReadOnly] ref Translation pos, [ReadOnly] ref Rotation rotation)
        {
            // getting the right TimePassed
            DynamicBuffer <TimePassed> buffer = data.timePassedBuffers[ent];
            TimePassed timePassed             = buffer[shoot.timeIdx];

            timePassed.time += data.dt;

            // fire until below period
            if (data.shooting && timePassed.time > shoot.shotCooldown)
            {
                // shoot the pattern
                // buffers commands to do after thread completes
                data.CreateBullet(index, ref pos, ref rotation, shoot.bullet, 0);
                timePassed.time = 0;
            }

            buffer[shoot.timeIdx] = timePassed;
        }
        public bool CheckIfNewLocationRequired(TimePassed accuracy)
        {
            if (this.cachedLocation == null)
            {
                return(true);
            }

            DateTime now = System.DateTime.Now;

            switch (accuracy)
            {
            case TimePassed.JustNow:
                return(this.cachedLocation.DateTime + new TimeSpan(0, 1, 0) < now);

            case TimePassed.AMomentAgo:
                return(this.cachedLocation.DateTime + new TimeSpan(0, 10, 0) < now);

            default:
                throw new NotImplementedException();
            }
        }
        public void Execute(Entity ent, int index, [ReadOnly] ref PlayerShoot shoot,
                            [ReadOnly] ref Translation pos, [ReadOnly] ref Rotation rotation)
        {
            // getting the right TimePassed
            DynamicBuffer <TimePassed> buffer = data.timePassedBuffers[ent];
            TimePassed timePassed             = buffer[shoot.timeIdx];

            timePassed.time += data.dt;

            // fire until below period
            if (data.shooting && timePassed.time > shoot.shotCooldown)
            {
                for (float angle = 0; angle < 2 * math.PI; angle += rnd.NextFloat(.3f, .5f))
                {
                    data.CreateBullet(index, ref pos, ref rotation, shoot.bullet, angle);
                }
                timePassed.time = 0;
            }

            buffer[shoot.timeIdx] = timePassed;
        }
        public void Execute(Entity ent, int idx, [ReadOnly] ref ExitMovement exitMove)
        {
            // update time
            DynamicBuffer <TimePassed> timeBuffer = timeBuffers[ent];
            TimePassed time = timeBuffer[exitMove.timeIdx];

            time.time += dt;

            // time to exit
            if (time.time > exitMove.exitTime)
            {
                // remove old component
                switch (exitMove.originalMovement)
                {
                case MovementComponent.Simple:
                    buffer.RemoveComponent <BulletMovement>(idx, ent);
                    break;

                case MovementComponent.Path:
                    buffer.RemoveComponent <PathMovement>(idx, ent);
                    buffer.RemoveComponent <PathPoint>(idx, ent);
                    break;
                }

                // add new component
                buffer.AddComponent(idx, ent, new BulletMovement {
                    moveType    = BulletMovementSystem.MoveType.LINEAR,
                    moveSpeed   = exitMove.exitSpeed,
                    rotateSpeed = 0f
                });

                // remove this component
                buffer.RemoveComponent <ExitMovement>(idx, ent);
            }
            // not time to exit, write the new time to the buffer
            else
            {
                timeBuffer[exitMove.timeIdx] = time;
            }
        }
Example #18
0
        private void SynchronizeVirtualTime()
        {
            lock (virtualTimeSyncLock)
            {
                if (!handles.TryGetCommonElapsedTime(out var currentCommonElapsedTime))
                {
                    return;
                }

                if (currentCommonElapsedTime == ElapsedVirtualTime)
                {
                    return;
                }

                DebugHelper.Assert(currentCommonElapsedTime > ElapsedVirtualTime, $"A slave reports time from the past! The current virtual time is {ElapsedVirtualTime}, but {currentCommonElapsedTime} has been reported");

                var timeDiff = currentCommonElapsedTime - ElapsedVirtualTime;
                this.Trace($"Reporting time passed: {timeDiff}");
                // this will update ElapsedVirtualTime
                UpdateTime(timeDiff);
                TimePassed?.Invoke(timeDiff);
            }
        }
        /// <summary>
        /// Execute one iteration of time-granting loop.
        /// </summary>
        /// <remarks>
        /// The steps are as follows:
        /// (1) remove and forget all slave handles that requested detaching
        /// (2) check if there are any blocked slaves; if so DO NOT grant a time interval
        /// (2.1) if there are no blocked slaves grant a new time interval to every slave
        /// (3) wait for all slaves that are relevant in this execution (it can be either all slaves or just blocked ones) until they report back
        /// (4) (optional) sleep if the virtual time passed faster than a real one; this step is executed if <see cref="AdvanceImmediately"> is not set and <see cref="Performance"> is low enough
        /// (5) update elapsed virtual time
        /// (6) execute sync hook and delayed actions if any
        /// </remarks>
        /// <param name="virtualTimeElapsed">Contains the amount of virtual time that passed during execution of this method. It is the minimal value reported by a slave (i.e, some slaves can report higher/lower values).</param>
        /// <returns>
        /// True if sync point has just been reached or False if the execution has been blocked.
        /// </returns>
        protected bool InnerExecute(out TimeInterval virtualTimeElapsed)
        {
            DebugHelper.Assert(NearestSyncPoint.Ticks >= ElapsedVirtualTime.Ticks, "Nearest sync point set in the past");

            isBlocked = false;
            var quantum = NearestSyncPoint - ElapsedVirtualTime;

            this.Trace($"Starting a loop with #{quantum.Ticks} ticks");

            virtualTimeElapsed = TimeInterval.Empty;
            State = TimeSourceState.ReportingElapsedTime;
            using (sync.LowPriority)
            {
                if ((isPaused || !isStarted) && recentlyUnblockedSlaves.Count == 0)
                {
                    // the time source is not started and it has not acknowledged any unblocks - it means no one is currently working
                    DebugHelper.Assert(handles.All.All(x => !x.SourceSideActive), "No source side active slaves were expected at this point.");

                    State = TimeSourceState.Idle;
                    EnterBlockedState();
                    return(false);
                }

                handles.LatchAllAndCollectGarbage();
                var shouldGrantTime = handles.AreAllReadyForNewGrant;

                this.Trace($"Iteration start: slaves left {handles.ActiveCount}; will we try to grant time? {shouldGrantTime}");
                elapsedAtLastGrant = stopwatch.Elapsed;
                if (handles.ActiveCount > 0)
                {
                    if (shouldGrantTime && quantum != TimeInterval.Empty)
                    {
                        this.Trace($"Granting {quantum.Ticks} ticks");
                        // inform all slaves about elapsed time
                        foreach (var slave in handles)
                        {
                            slave.GrantTimeInterval(quantum);
                        }
                    }

                    // in case we did not grant any time due to quantum being empty, we must not call wait as well
                    if (!(shouldGrantTime && quantum == TimeInterval.Empty))
                    {
                        this.Trace("Waiting for slaves");
                        // wait for everyone to report back
                        State = TimeSourceState.WaitingForReportBack;
                        TimeInterval?minInterval = null;
                        foreach (var slave in handles.WithLinkedListNode)
                        {
                            var result = slave.Value.WaitUntilDone(out var usedInterval);
                            if (!result.IsDone)
                            {
                                EnterBlockedState();
                            }

                            handles.UpdateHandle(slave);

                            if (result.IsUnblockedRecently)
                            {
                                Antmicro.Renode.Debugging.DebugHelper.Assert(recentlyUnblockedSlaves.Contains(slave.Value), $"Expected slave to be in {nameof(recentlyUnblockedSlaves)} collection.");
                                recentlyUnblockedSlaves.Remove(slave.Value);
                                this.Trace($"Number of unblocked slaves set to {recentlyUnblockedSlaves.Count}");
                                if (recentlyUnblockedSlaves.Count == 0)
                                {
                                    sync.Pulse();
                                }
                            }
                            if (minInterval == null || minInterval > slave.Value.TotalElapsedTime)
                            {
                                minInterval = slave.Value.TotalElapsedTime;
                            }
                        }

                        if (minInterval != null)
                        {
                            virtualTimeElapsed = minInterval.Value - ElapsedVirtualTime;
                        }
                    }
                }
                else
                {
                    this.Trace($"There are no slaves, updating VTE by {quantum.Ticks}");
                    // if there are no slaves just make the time pass
                    virtualTimeElapsed = quantum;

                    TimePassed?.Invoke(quantum);
                }

                handles.UnlatchAll();

                State = TimeSourceState.Sleeping;
                var elapsedThisTime = stopwatch.Elapsed - elapsedAtLastGrant;
                if (!AdvanceImmediately)
                {
                    var scaledVirtualTicksElapsed = virtualTimeElapsed.WithScaledTicks(1 / Performance).ToTimeSpan() - elapsedThisTime;
                    sleeper.Sleep(scaledVirtualTicksElapsed);
                }

                lock (hostTicksElapsed)
                {
                    this.Trace($"Updating virtual time by {virtualTimeElapsed.InMicroseconds} us");
                    this.virtualTicksElapsed.Update(virtualTimeElapsed.InMicroseconds);
                    this.hostTicksElapsed.Update(elapsedThisTime.InMicroseconds());
                }
            }

            if (!isBlocked)
            {
                ExecuteSyncPhase();
            }
            else
            {
                BlockHook?.Invoke();
            }

            State = TimeSourceState.Idle;

            this.Trace($"The end of {nameof(InnerExecute)} with result={!isBlocked}");
            return(!isBlocked);
        }
        /// <summary>
        /// Execute one iteration of time-granting loop.
        /// </summary>
        /// <remarks>
        /// The steps are as follows:
        /// (1) remove and forget all slave handles that requested detaching
        /// (2) check if there are any blocked slaves; if so DO NOT grant a time interval
        /// (2.1) if there are no blocked slaves grant a new time interval to every slave
        /// (3) wait for all slaves that are relevant in this execution (it can be either all slaves or just blocked ones) until they report back
        /// (4) (optional) sleep if the virtual time passed faster than a real one; this step is executed if <see cref="AdvanceImmediately"> is not set and <see cref="Performance"> is low enough
        /// (5) update elapsed virtual time
        /// (6) execute sync hook and delayed actions if any
        /// </remarks>
        /// <param name="virtualTimeElapsed">Contains the amount of virtual time that passed during execution of this method. It is the minimal value reported by a slave (i.e, some slaves can report higher/lower values).</param>
        /// <param name="timeLimit">Maximum amount of virtual time that can pass during the execution of this method. If not set, current <see cref="Quantum"> is used.</param>
        /// <returns>
        /// True if sync point has just been reached or False if the execution has been blocked.
        /// </returns>
        protected bool InnerExecute(out TimeInterval virtualTimeElapsed, TimeInterval?timeLimit = null)
        {
            if (updateNearestSyncPoint)
            {
                NearestSyncPoint      += timeLimit.HasValue ? TimeInterval.Min(timeLimit.Value, Quantum) : Quantum;
                updateNearestSyncPoint = false;
                this.Trace($"Updated NearestSyncPoint to: {NearestSyncPoint}");
            }
            DebugHelper.Assert(NearestSyncPoint.Ticks >= ElapsedVirtualTime.Ticks, $"Nearest sync point set in the past: EVT={ElapsedVirtualTime} NSP={NearestSyncPoint}");

            isBlocked = false;
            var quantum = NearestSyncPoint - ElapsedVirtualTime;

            this.Trace($"Starting a loop with #{quantum.Ticks} ticks");

            virtualTimeElapsed = TimeInterval.Empty;
            using (sync.LowPriority)
            {
                handles.LatchAllAndCollectGarbage();
                var shouldGrantTime = handles.AreAllReadyForNewGrant;

                this.Trace($"Iteration start: slaves left {handles.ActiveCount}; will we try to grant time? {shouldGrantTime}");
                elapsedAtLastGrant = stopwatch.Elapsed;

                if (handles.ActiveCount > 0)
                {
                    var executor = new PhaseExecutor <LinkedListNode <TimeHandle> >();

                    if (!shouldGrantTime)
                    {
                        executor.RegisterPhase(ExecuteUnblockPhase);
                        executor.RegisterPhase(ExecuteWaitPhase);
                    }
                    else if (quantum != TimeInterval.Empty)
                    {
                        executor.RegisterPhase(s => ExecuteGrantPhase(s, quantum));
                        executor.RegisterPhase(ExecuteWaitPhase);
                    }

                    if (ExecuteInSerial)
                    {
                        executor.ExecuteInSerial(handles.WithLinkedListNode);
                    }
                    else
                    {
                        executor.ExecuteInParallel(handles.WithLinkedListNode);
                    }

                    var commonElapsedTime = handles.CommonElapsedTime;
                    DebugHelper.Assert(commonElapsedTime >= ElapsedVirtualTime, $"A slave reports time from the past! The current virtual time is {ElapsedVirtualTime}, but {commonElapsedTime} has been reported");
                    virtualTimeElapsed = commonElapsedTime - ElapsedVirtualTime;
                }
                else
                {
                    this.Trace($"There are no slaves, updating VTE by {quantum.Ticks}");
                    // if there are no slaves just make the time pass
                    virtualTimeElapsed = quantum;

                    // here we must trigger `TimePassed` manually as no handles has been updated so they won't reflect the passed time
                    TimePassed?.Invoke(quantum);
                }

                handles.UnlatchAll();

                State = TimeSourceState.Sleeping;
                var elapsedThisTime = stopwatch.Elapsed - elapsedAtLastGrant;
                if (!AdvanceImmediately)
                {
                    var scaledVirtualTicksElapsed = virtualTimeElapsed.WithScaledTicks(1 / Performance).ToTimeSpan() - elapsedThisTime;
                    sleeper.Sleep(scaledVirtualTicksElapsed);
                }

                lock (hostTicksElapsed)
                {
                    this.Trace($"Updating virtual time by {virtualTimeElapsed.InMicroseconds} us");
                    this.virtualTicksElapsed.Update(virtualTimeElapsed.Ticks);
                    this.hostTicksElapsed.Update(TimeInterval.FromTimeSpan(elapsedThisTime).Ticks);
                }
            }

            if (!isBlocked)
            {
                ExecuteSyncPhase();
                updateNearestSyncPoint = true;
            }
            else
            {
                BlockHook?.Invoke();
            }

            State = TimeSourceState.Idle;

            this.Trace($"The end of {nameof(InnerExecute)} with result={!isBlocked}");
            return(!isBlocked);
        }
Example #21
0
        /// <summary>
        /// Execute one iteration of time-granting loop.
        /// </summary>
        /// <remarks>
        /// The steps are as follows:
        /// (1) remove and forget all slave handles that requested detaching
        /// (2) check if there are any blocked slaves; if so DO NOT grant a time interval
        /// (2.1) if there are no blocked slaves grant a new time interval to every slave
        /// (3) wait for all slaves that are relevant in this execution (it can be either all slaves or just blocked ones) until they report back
        /// (4) (optional) sleep if the virtual time passed faster than a real one; this step is executed if <see cref="AdvanceImmediately"> is not set and <see cref="Performance"> is low enough
        /// (5) update elapsed virtual time
        /// (6) execute sync hook and delayed actions if any
        /// </remarks>
        /// <param name="virtualTimeElapsed">Contains the amount of virtual time that passed during execution of this method. It is the minimal value reported by a slave (i.e, some slaves can report higher/lower values).</param>
        /// <param name="timeLimit">Maximum amount of virtual time that can pass during the execution of this method. If not set, current <see cref="Quantum"> is used.</param>
        /// <returns>
        /// True if sync point has just been reached or False if the execution has been blocked.
        /// </returns>
        protected bool InnerExecute(out TimeInterval virtualTimeElapsed, TimeInterval?timeLimit = null)
        {
            if (updateNearestSyncPoint)
            {
                NearestSyncPoint      += timeLimit.HasValue ? TimeInterval.Min(timeLimit.Value, Quantum) : Quantum;
                updateNearestSyncPoint = false;
                this.Trace($"Updated NearestSyncPoint to: {NearestSyncPoint}");
            }
            DebugHelper.Assert(NearestSyncPoint.Ticks >= ElapsedVirtualTime.Ticks, $"Nearest sync point set in the past: EVT={ElapsedVirtualTime} NSP={NearestSyncPoint}");

            isBlocked = false;
            var quantum = NearestSyncPoint - ElapsedVirtualTime;

            this.Trace($"Starting a loop with #{quantum.Ticks} ticks");

            SynchronizeVirtualTime();
            var elapsedVirtualTimeAtStart = ElapsedVirtualTime;

            using (sync.LowPriority)
            {
                handles.LatchAllAndCollectGarbage();
                var shouldGrantTime = handles.AreAllReadyForNewGrant;

                this.Trace($"Iteration start: slaves left {handles.ActiveCount}; will we try to grant time? {shouldGrantTime}");

                if (handles.ActiveCount > 0)
                {
                    var executor = new PhaseExecutor <LinkedListNode <TimeHandle> >();

                    if (!shouldGrantTime)
                    {
                        executor.RegisterPhase(ExecuteUnblockPhase);
                        executor.RegisterPhase(ExecuteWaitPhase);
                    }
                    else if (quantum != TimeInterval.Empty)
                    {
                        executor.RegisterPhase(s => ExecuteGrantPhase(s, quantum));
                        executor.RegisterPhase(ExecuteWaitPhase);
                    }

                    if (ExecuteInSerial)
                    {
                        executor.ExecuteInSerial(handles.WithLinkedListNode);
                    }
                    else
                    {
                        executor.ExecuteInParallel(handles.WithLinkedListNode);
                    }

                    SynchronizeVirtualTime();
                    virtualTimeElapsed = ElapsedVirtualTime - elapsedVirtualTimeAtStart;
                }
                else
                {
                    this.Trace($"There are no slaves, updating VTE by {quantum.Ticks}");
                    // if there are no slaves just make the time pass
                    virtualTimeElapsed = quantum;

                    UpdateTime(quantum);
                    // here we must trigger `TimePassed` manually as no handles has been updated so they won't reflect the passed time
                    TimePassed?.Invoke(quantum);
                }

                handles.UnlatchAll();
            }

            SinksReportedkHook?.Invoke();
            if (!isBlocked)
            {
                ExecuteSyncPhase();
                updateNearestSyncPoint = true;
            }
            else
            {
                BlockHook?.Invoke();
            }

            State = TimeSourceState.Idle;

            this.Trace($"The end of {nameof(InnerExecute)} with result={!isBlocked}");
            return(!isBlocked);
        }
Example #22
0
 private void Invoke(object o)
 {
     TimePassed?.Invoke();
 }
 public StalenessTypes Staleness()
 {
     return(TimePassed.HowStale(TimeStamp));
 }
Example #24
0
 /// <summary>
 /// Informuje o obliczeniu zmian dla lokat i kredytow
 /// </summary>
 private void Timer_Elapsed(object sender, ElapsedEventArgs e)
 {
     TimePassed?.Invoke(this, EventArgs.Empty);
 }
Example #25
0
 private void OnTimePassed()
 {
     TimePassed?.Invoke(this, _time);
 }