public override void Delete(LeagueDbContext dbContext)
 {
     SessionResult?.Delete(dbContext);
     Scorings?.ToList().ForEach(x => x.Sessions.Remove(this));
     Reviews?.ToList().ForEach(x => x.Delete(dbContext));
     base.Delete(dbContext);
 }
Ejemplo n.º 2
0
        public void TestEntitiesEquals()
        {
            Student std1 = new Student(2, "Igor", "Yeliseev", "Andreevich", 1, "male", new DateTime(1999, 5, 22));
            Student std2 = new Student(2, "Igor", "Yeliseev", "Andreevich", 1, "male", new DateTime(1999, 5, 22));

            Assert.AreEqual(std1, std2);

            Subject sbj1 = new Subject(2, "Geography");
            Subject sbj2 = new Subject(2, "Geography");

            Assert.AreEqual(sbj1, sbj2);

            Group group1 = new Group(1, "IS-21");
            Group group2 = new Group(1, "IS-21");

            Assert.AreEqual(group1, group2);

            SessionExam exam1 = new SessionExam(21, 1, 2, "exam", 2, new DateTime(2020, 1, 12));
            SessionExam exam2 = new SessionExam(21, 1, 2, "exam", 2, new DateTime(2020, 1, 12));

            Assert.AreEqual(exam1, exam2);

            SessionResult result1 = new SessionResult(1, 1, 3, 8);
            SessionResult result2 = new SessionResult(1, 1, 3, 8);

            Assert.AreEqual(result1, result2);
        }
Ejemplo n.º 3
0
        private void UpdateSector(ISimulation sim, SessionResult session, EntitySessionResult result, double curPos, double prevPos)
        {
            if (session.State != SessionState.Racing)
            {
                return;
            }

            var track = sim.Session.Track;

            if (track.SelectedSectors.Count <= 0)
            {
                return;
            }

            var i = 0;

            foreach (var location in track.SelectedSectors.OrderBy(s => s.Index).Select(s => s.Location))
            {
                if (curPos <= location || i <= result.CurrentLap.CurrentSector.Index)
                {
                    i++;
                    continue;
                }

                var now    = Updater.CurrentTime - (curPos - location) * (curPos - prevPos);
                var sector = new CompletedSector(result.CurrentLap.CurrentSector, now);
                result.CurrentLap.SectorsInt.Add(sector);

                result.CurrentLap.CurrentSector.BeginTime      = now;
                result.CurrentLap.CurrentSector.Index          = i;
                result.CurrentLap.CurrentSector.ReplayPosition = (int)(sim.Telemetry.SessionTime * 60 + Updater.TimeOffset);

                break;
            }
        }
Ejemplo n.º 4
0
        internal override void Parse(YamlMappingNode root, Simulation sim)
        {
            if (sim.Session.GetQualification() is SessionResult quali && quali.Results.Count > 0)
            {
                return;
            }

            var results = root.GetList("QualifyResultsInfo.Results");

            if (results?.Children == null || results.Children.Count == 0)
            {
                return;
            }

            var session = new SessionResult
            {
                Type           = SessionType.Qualify,
                Name           = "QUALIFY",
                FastestLapTime = float.MaxValue
            };

            foreach (var result in results.Children.OfType <YamlMappingNode>())
            {
                CreateResult(ref session, result, sim);
            }

            lock (sim.SharedCollectionLock)
            {
                ((Session.Session)sim.Session).SessionResultsInt.Add(session);
            }
        }
Ejemplo n.º 5
0
        private static void CreateResult(ref SessionResult session, YamlMappingNode result, ISimulation sim)
        {
            var carIdx = result.GetByte("CarIdx");
            var entity = sim.Session.Entities.FirstOrDefault(e => e.CarIdx == carIdx);

            if (entity == null)
            {
                return;
            }

            var sessionResult = new EntitySessionResult(session, entity);

            var pos = result.GetInt("Position") + 1;

            sessionResult.Position = pos > 0 ? pos : int.MaxValue;
            if (sessionResult.Position == 1)
            {
                session.Leader = entity;
            }

            sessionResult.ClassPosition  = result.GetInt("ClassPosition") + 1;
            sessionResult.FastestLapTime = result.GetFloat("FastestTime");

            session.ResultsInt.Add(sessionResult);
            if (sessionResult.FastestLapTime < session.FastestLapTime && sessionResult.FastestLapTime > 0)
            {
                session.FastestLapTime = sessionResult.FastestLapTime;
            }
        }
Ejemplo n.º 6
0
 private static void UpdateSession(Guid sessionId, SqliteConnection db, SessionResult results)
 {
     db.CreateCommand("UPDATE sessions SET meta = @meta WHERE session_id = @id",
                      new SqliteParameter("@meta", JsonConvert.SerializeObject(results.Metrics)),
                      new SqliteParameter("@id", sessionId.ToString("N"))
                      ).ExecuteNonQuery();
 }
Ejemplo n.º 7
0
        public void TestExcel2()
        {
            SessionResult sres    = new SessionResult(factory);
            var           results = sres.GetResult(2);

            sres.WriteToExcel(@"D:\", "rep2", results);
        }
Ejemplo n.º 8
0
 public void CloseSession(Session sessionP, SessionResult result, Exception exception = null)
 {
     using (var db = _ctxFactory())
     {
         var session = db.Sessions.Find(sessionP.Id);
         session.Result     = result;
         session.FinishedOn = DateTime.Now;
         if (exception != null)
         {
             session.Errors = JsonConvert.SerializeObject(exception, Formatting.Indented);
         }
         if (result == SessionResult.Success)
         {
             var cfg = db.ConfigTable.First();
             if (session.Direction == SyncDirection.Jira2TFS)
             {
                 cfg.JiraDateFrom    = session.FinishedOn;
                 Config.JiraDateFrom = session.StartedOn;
             }
             else
             {
                 cfg.TFSDateFrom    = session.FinishedOn;
                 Config.TFSDateFrom = session.StartedOn;
             }
         }
         db.SaveChanges();
     }
 }
Ejemplo n.º 9
0
 private void UpdateCurrentLap(EntitySessionResult result, SessionResult session)
 {
     result.CurrentLap.WasUnderCaution |= session.Flags.CheckBits(SessionFlags.Caution, SessionFlags.CautionWaving);
     result.CurrentLap.Position         = result.LivePosition;
     result.CurrentLap.ClassPosition    = result.LiveClassPosition;
     result.CurrentLap.Gap              = session.Type == SessionType.Race ? result.LiveGap : (result.CurrentLap.Time - session.FastestLapTime);
     result.CurrentLap.GapLaps          = session.Type == SessionType.Race ? result.LiveGapLaps : 0;
 }
Ejemplo n.º 10
0
        protected void btn_Click(object sender, EventArgs e)
        {
            string        sessionKey    = tb_sessionKey.Text;
            string        sessionSecret = tb_sessionSecret.Text;
            SessionResult result        = Client.GetSession(sessionKey);

            lb_result.Text = JsonConvert.SerializeObject(result);
        }
Ejemplo n.º 11
0
        private void InitSession(ActionExecutingContext filterContext)
        {
            SessionResult test = new SessionResult()
            {
                LoginUseID   = "17b2269a-0bc6-4a20-95ed-25b3386250b1",
                LoginUseName = "采购员01"
            };

            filterContext.HttpContext.Session.Set <SessionResult>(ConstantConfig._SessionKey, test);
        }
Ejemplo n.º 12
0
        private static void UpdateSession(YamlMappingNode session, Simulation sim, SessionResult sessionResult, int currentSessionNumber)
        {
            Debug.WriteLine($">> UpdateSession: {sessionResult.Id}");

            if (sessionResult.Id != session.GetInt("SessionNum"))
            {
                return;
            }

            sessionResult.HasStarted  = sessionResult.Id <= currentSessionNumber;
            sessionResult.HasFinished = sessionResult.Id < currentSessionNumber;
            sessionResult.IsCurrent   = sessionResult.Id == currentSessionNumber;

            if (sessionResult.State != SessionState.Racing && sessionResult.Type == SessionType.Race)
            {
                sessionResult.Cautions    = session.GetInt("ResultsNumCautionFlags");
                sessionResult.CautionLaps = session.GetInt("ResultsNumCautionLaps");
            }

            sessionResult.Skipped       = session.GetBool("SessionSkipped");
            sessionResult.RunGroupsUsed = session.GetBool("SessionRunGroupsUsed");

            sessionResult.LeadChanges   = session.GetInt("ResultsNumLeadChanges");
            sessionResult.LapsCompleted = session.GetInt("ResultsLapsComplete");
            sessionResult.LapsRemaining = sessionResult.LapsTotal - sessionResult.LapsCompleted;

            try
            {
                // Nick: this is suddenly a list of one item?
                //var fastestLap = session.GetMap("ResultsFastestLap");
                var fastestLap = session.GetList("ResultsFastestLap")?.FirstOrDefault() as YamlMappingNode;
                if (fastestLap?.Children?.Count > 0)
                {
                    var entity = sim.Session.Entities.FirstOrDefault(e => e.CarIdx == fastestLap.GetInt("CarIdx"));
                    if (entity != null)
                    {
                        sessionResult.FastestLapDriver = entity.CurrentDriver;
                        sessionResult.FastestLapNumber = fastestLap.GetInt("FastestLap");
                    }

                    var newFastestLapTime = fastestLap.GetFloat("FastestTime");
                    if (Math.Abs(sessionResult.FastestLapTime - newFastestLapTime) <= 10E-6)
                    {
                        return;
                    }

                    sessionResult.PrevFastestLapTime = sessionResult.FastestLapTime;
                    sessionResult.FastestLapTime     = newFastestLapTime;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }
Ejemplo n.º 13
0
        public void GetSessionById_where_sessionid_not_found()
        {
            // Arrange
            int sessionId = int.MaxValue;

            // Act
            SessionResult response = _service.GetSessionById(sessionId).Result;

            // Assert
            Assert.Null(response);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Provides a session based on it identifier
        /// </summary>
        /// <param name="sessionId">The session identifier</param>
        /// <returns></returns>
        public async Task <SessionResult> GetSessionById(int sessionId)
        {
            SessionResult session = null;

            // filter by sessionId
            session = (await GetAllSessions()).FirstOrDefault(x => x.SessionID.Equals(sessionId));

            if (session != null)
            {
                session.Desciption = await GetSessionByUrl(Config.GetSessionUrl(sessionId));
            }

            return(session);
        }
Ejemplo n.º 15
0
        public string GetResultRaw(long discordGuildId, long matchId)
        {
            using DBContext c = new DBContext();
            SeasonResult result = c.SeasonResult.FirstOrDefault(r => r.MatchId == matchId &&
                                                                r.DiscordGuildId == discordGuildId);

            if (result == null)
            {
                return(new ApiResponse(System.Net.HttpStatusCode.NotFound, "Match not found"));
            }

            SessionResult sr = SessionResult.FromResult(result);

            return(new ApiObject <SessionResult>(sr));
        }
Ejemplo n.º 16
0
        private static void UpdatePositions(ISession session, SessionResult results)
        {
            foreach (var entity in session.Entities)
            {
                if (!(results.Results.FirstOrDefault(e => e.Entity.CarIdx == entity.CarIdx) is EntitySessionResult result))
                {
                    continue;
                }

                if (result.Position == 1)
                {
                    results.Leader = result.Entity;
                }
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Determines whether the specified object is equal to the current object.
        /// </summary>
        /// <param name="obj"> The object to compare with the current object.</param>
        /// <returns></returns>
        public override bool Equals(object obj)
        {
            if (obj == null)
            {
                return(false);
            }

            SessionResult res = obj as SessionResult;

            if (res == null)
            {
                return(false);
            }

            return(ID.Equals(res.ID) && StudentID.Equals(res.StudentID) &&
                   ExamID.Equals(res.ExamID) && Grade.Equals(res.Grade));
        }
        internal void Update(SessionResult result, Simulation sim)
        {
            if (result.SessionStartTime < 0)
            {
                result.SessionStartTime      = result.SessionTime;
                result.CurrentReplayPosition = sim.Telemetry.ReplayFrameNum;
            }

            if (result.SessionTime < 0.5)
            {
                sim.TimeDelta = new TimeDelta(sim.Session.Track.Length, 300, 64);
            }

            result.SessionTimeRemaining = sim.Telemetry.SessionTimeRemain;

            UpdateRemainingEstimations(result, sim);
        }
Ejemplo n.º 19
0
        public List <SessionResult> GetSessionResults()
        {
            List <SessionResult> sessionResults = new List <SessionResult>();
            var sessions = _context.Sessions
                           .Include("Rooms")
                           .Include("Assignees")
                           .Include("ProctorCheckIns")
                           .Where(s => s.SessionType != "Static Session")
                           .ToList();

            foreach (var session in sessions)
            {
                var sessionResult = new SessionResult();

                sessionResult.Id = session.FeedSessionId ?? 0;
                sessionResult.SessionStartTime       = session.SessionStartTime;
                sessionResult.SessionEndTime         = session.SessionEndTime;
                sessionResult.Title                  = session.Title;
                sessionResult.SessionType            = session.SessionType;
                sessionResult.ActualSessionStartTime = session.ActualSessionStartTime;
                sessionResult.ActualSessionEndTime   = session.ActualSessionEndTime;
                sessionResult.Attendees10            = session.Attendees10;
                sessionResult.Attendees50            = session.Attendees50;
                sessionResult.Notes                  = session.Notes;

                if (session.ProctorCheckIns.Count > 0)
                {
                    sessionResult.ProctorCheckInTime = session.ProctorCheckIns.OrderBy(c => c.CheckInTime).FirstOrDefault().CheckInTime;
                }

                var rooms = "";
                session.Rooms.OrderBy(r => r.Name).ToList().ForEach(r => rooms += r.Name + ",");
                sessionResult.Rooms = rooms.Substring(0, rooms.Length - 1);

                if (session.Assignees.Count > 0)
                {
                    var assignees = "";
                    session.Assignees.ForEach(a => assignees += a.FirstName + " " + a.LastName + ";");
                    sessionResult.Assignees = assignees.Substring(0, assignees.Length - 1);
                }

                sessionResults.Add(sessionResult);
            }

            return(sessionResults);
        }
Ejemplo n.º 20
0
        public void GetSessionById_where_sessionid_found()
        {
            // Arrange
            int sessionId = 101;

            // Act
            SessionResult response = _service.GetSessionById(sessionId).Result;

            // Assert
            Assert.NotNull(response);
            Assert.Equal(sessionId, response.SessionID);
            Assert.NotNull(response.Title);
            Assert.NotNull(response.Desciption);
            Assert.NotNull(response.Href);
            Assert.NotNull(response.TimeSlot);
            Assert.NotNull(response.Speaker);
            Assert.True(response.Links.Count > 0);
        }
Ejemplo n.º 21
0
    public void saveSessionResult(SessionResult sr)
    {
        loadSessionResults();                        //TODO this ToList into ToArray is teribbbbbile
        List <SessionResult> list;

        if (results != null)
        {
            list = results.ToList();
        }
        else
        {
            list = new List <SessionResult>();
        }
        list.Add(sr);
        results = list.ToArray();
        string jsoned = JsonHelper.ToJson(results);

        PlayerPrefs.SetString(srkeyAndName, jsoned);
    }
Ejemplo n.º 22
0
        private static void CreateSession(YamlMappingNode root, YamlMappingNode session, Simulation sim, int number, int currentSessionNumber)
        {
            Debug.WriteLine($">> CreateSession: {number}");

            var sessionResult = new SessionResult {
                Id = number
            };

            var laps = session.GetString("SessionLaps");

            sessionResult.LapsTotal = laps == "unlimited" ? int.MaxValue : int.Parse(laps);
            var time = session.GetString("SessionTime");

            sessionResult.SessionLength = time == "unlimited" ? double.MaxValue : float.Parse(time.Substring(0, time.Length - 4), CultureInfo.InvariantCulture);

            sessionResult.Type = SessionTypeMap[session.GetString("SessionType")];
            var subType = session.GetString("SessionSubType");

            sessionResult.SubType = subType != null ? SessionSubTypeMap[subType.Trim()] : SessionSubType.Default;

            sessionResult.Name = session.GetString("SessionName");
            if (string.IsNullOrWhiteSpace(sessionResult.Name))
            {
                sessionResult.Name = sessionResult.Type.ToString();
            }

            sessionResult.FinishLine = sessionResult.Type == SessionType.Race ? sessionResult.LapsTotal : int.MaxValue;

            if (sessionResult.FinishLine <= 0)
            {
                sessionResult.FinishLine = int.MaxValue;
            }

            UpdateSession(session, sim, sessionResult, currentSessionNumber);
            UpdateEntitites(root, session, sim, sessionResult);

            lock (sim.SharedCollectionLock)
            {
                Debug.WriteLine($">>>> ADDING NEW SESSION: ID: {sessionResult.Id}, Name: {sessionResult.Name}");
                ((Session.Session)sim.Session).SessionResultsInt.Add(sessionResult);
            }
        }
Ejemplo n.º 23
0
        internal void Update(SessionResult result, Simulation sim)
        {
            var prevState = result.State;

            result.State = sim.Telemetry.SessionState;
            if (prevState == result.State)
            {
                return;
            }

            var ev = new SessionEvent((long)(sim.Telemetry.SessionTime * 60 + Updater.TimeOffset), "Session state changed to " + result.State.ToString(),
                                      sim.CameraManager.FollowedEntity, sim.CameraManager.CurrentGroup, result.Type, SessionEventType.State, result.LapsCompleted);

            lock (sim.SharedCollectionLock)
            {
                ((Session.Session)sim.Session).SessionEventsInt.Add(ev);
            }

            if (result.Type == SessionType.Race && result.FinishLine == int.MaxValue && prevState == SessionState.Racing && result.State == SessionState.Checkered)
            {
                result.FinishLine = (int)Math.Ceiling(result.Leader.Results.CurrentResult.CurrentTrackPct);
            }

            if (result.State == SessionState.Racing && result.Flags.CheckBit(SessionFlags.Green))
            {
                sim.Triggers.Push(EventType.FlagGreen);
            }
            else if (result.State == SessionState.Checkered || result.State == SessionState.CoolDown)
            {
                sim.Triggers.Push(EventType.FlagCheckered);
            }
            else if (result.State == SessionState.GetInCar || result.State == SessionState.ParadeLaps || result.State == SessionState.Warmup)
            {
                sim.Triggers.Push(EventType.FlagYellow);
            }

            if (result.State == SessionState.Racing && (prevState == SessionState.ParadeLaps || prevState == SessionState.GetInCar))
            {
                Updater.TimeOffset = sim.Telemetry.ReplayFrameNum - sim.Telemetry.SessionTime * 60;
            }
        }
Ejemplo n.º 24
0
        private async System.Threading.Tasks.Task AutcheticateWithWSAsync(string password)
        {
            Configuration.Default.Timeout = new TimeSpan(0, 1, 0);

            var creds = new Password(password); // Password | A password key

            try
            {
                System.Threading.Tasks.Task <SessionResult> task = new DefaultApi().AuthTokenGetPostAsync(creds);
                SessionResult result = await task;
                // Upadting session and Api Key for future api calls until session needs to be renewed
                SessionHelper.UpdateSession(result);
                SocketHelper.ConnectToWS();
                Configuration.Default.AddApiKey("X-API-Key", result.Token);
                // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
                // Configuration.Default.ApiKeyPrefix.Add("X-API-Key", "Bearer");
            }
            catch (Exception eerr)
            {
                Debug.WriteLine("Exception when calling DefaultApi.AuthTokenGetPost: " + eerr.Message);
            }
        }
        public void NewSessionReturnsSessionObject()
        {
            // Arrange
            const string dummyPartitionKey = "dummyPartitionKey";
            var          dummySession      = new SessionResult
            {
                Counter          = 123,
                EncodedSessionId = "EncodedSessionId",
            };

            A.CallTo(() => sessionIdGenerator.CreateSession(A <string> .Ignored, A <DateTime> .Ignored)).Returns(dummySession);
            A.CallTo(() => partitionKeyGenerator.GeneratePartitionKey(A <string> .Ignored, A <string> .Ignored)).Returns(dummyPartitionKey);

            // Act
            var session = sessionClient.NewSession();

            // Assert
            Assert.NotNull(session);
            Assert.Equal($"{config.Salt}|{dummySession.Counter}", session.Salt);
            Assert.Equal(dummySession.EncodedSessionId, session.SessionId);
            Assert.Equal(dummyPartitionKey, session.PartitionKey);
        }
Ejemplo n.º 26
0
        SessionResult IProjectLogic.GetAllRequestList(Guid sessionPlanId)
        {
            var requests = this.requestRepository.getRequestList(sessionPlanId).ToList();

            var result = new SessionResult();

            if (requests != null && requests.Count() > 0)
            {
                result.Id       = sessionPlanId;
                result.Requests = new List <RequestResult>();
                requests.ForEach(request => {
                    var requestResult     = new RequestResult();
                    requestResult.Id      = request.Id;
                    requestResult.Number  = request.Number;
                    var skillIdList       = request.RequestDetails.Select(detail => detail.SkillId).ToList();
                    requestResult.TitleId = request.RequestDetails.FirstOrDefault()?.TitleId;
                    requestResult.Skills  = String.Join(";#", skillIdList);
                    result.Requests.Add(requestResult);
                });
            }

            return(result);
        }
Ejemplo n.º 27
0
        public void TestEntitiesEquals()
        {
            Examinator examinator1 = new Examinator(1, "Петр Петрович Иванов");
            Examinator examinator2 = new Examinator(1, "Петр Петрович Иванов");

            Assert.AreEqual(examinator1, examinator2);

            Specialty specialty1 = new Specialty(2, "Экономист");
            Specialty specialty2 = new Specialty(2, "Экономист");

            Assert.AreEqual(specialty1, specialty2);

            Student std1 = new Student(2, "Igor", "Yeliseev", "Andreevich", 1, "male", new DateTime(1999, 5, 22));
            Student std2 = new Student(2, "Igor", "Yeliseev", "Andreevich", 1, "male", new DateTime(1999, 5, 22));

            Assert.AreEqual(std1, std2);

            Subject sbj1 = new Subject(2, "Geography");
            Subject sbj2 = new Subject(2, "Geography");

            Assert.AreEqual(sbj1, sbj2);

            Group group1 = new Group(1, "IS-21", 1);
            Group group2 = new Group(1, "IS-21", 1);

            Assert.AreEqual(group1, group2);

            SessionExam exam1 = new SessionExam(21, 1, 2, "exam", 2, new DateTime(2020, 1, 12));
            SessionExam exam2 = new SessionExam(21, 1, 2, "exam", 2, new DateTime(2020, 1, 12));

            Assert.AreEqual(exam1, exam2);

            SessionResult result1 = new SessionResult(1, 1, 3, 8);
            SessionResult result2 = new SessionResult(1, 1, 3, 8);

            Assert.AreEqual(result1, result2);
        }
Ejemplo n.º 28
0
        private void TriggerFastestLap(Simulation sim, SessionResult session)
        {
            if (session == null || Math.Abs(session.FastestLapTime - session.PrevFastestLapTime) < 10E-6 || session.FastestLapTime <= 0)
            {
                return;
            }

            session.PrevFastestLapTime = session.FastestLapTime;

            var ev = new SessionEvent((long)(sim.Telemetry.SessionTime * 60 + _updater.TimeOffset),
                                      "New session fastest lap (" + session.FastestLapTime.ConvertToTimeString() + ")", session.FastestLapDriver,
                                      sim.CameraManager.CurrentGroup, session.Type, SessionEventType.FastLap, session.FastestLapNumber);

            if (sim.Session.SessionEvents.Contains(ev))
            {
                return;
            }

            lock (sim.SharedCollectionLock)
            {
                ((Session.Session)sim.Session).SessionEventsInt.Add(ev);
                sim.Triggers.Push(EventType.FastestLap);
            }
        }
Ejemplo n.º 29
0
        private static EntitySessionResult InitResult(YamlMappingNode resultsInfo, Simulation sim, SessionResult session,
                                                      IEntity entity, int carIdx)
        {
            var result = new EntitySessionResult(session, entity)
            {
                FastestLapTime  = resultsInfo.GetFloat("FastestTime"),
                LapsLed         = resultsInfo.GetInt("LapsLed"),
                CurrentTrackPct = sim.Telemetry.CarIdxLap[carIdx] + sim.Telemetry.CarIdxLapDistPct[carIdx] - 1
            };

            var newLap = new CompletedLap(result)
            {
                Number        = resultsInfo.GetInt("LapsComplete"),
                Position      = resultsInfo.GetInt("Position"),
                ClassPosition = resultsInfo.GetInt("ClassPosition") + 1,
                Gap           = resultsInfo.GetFloat("Time"),
                GapLaps       = resultsInfo.GetInt("Lap")
            };

            newLap.SetExactLaptime(resultsInfo.GetFloat("LastTime"));

            result.PreviousLap = newLap;
            result.FastestLap  = newLap;
            result.Laps.AddLap(newLap);

            // Current lap is empty here, set all properties
            result.CurrentLap.Number        = newLap.Number + 1;
            result.CurrentLap.Position      = newLap.Position;
            result.CurrentLap.ClassPosition = newLap.ClassPosition;
            result.CurrentLap.Gap           = newLap.Gap;
            result.CurrentLap.GapLaps       = newLap.GapLaps;

            if (session.Flags.CheckBits(SessionFlags.Caution, SessionFlags.CautionWaving))
            {
                result.CurrentLap.WasUnderCaution = true;
            }

            lock (sim.SharedCollectionLock)
            {
                session.ResultsInt.Add(result);
                ((EntityResults)result.Entity.Results).SessionResultsInt.Add(result);
            }

            return(result);
        }
Ejemplo n.º 30
0
        private static void UpdateEntity(YamlMappingNode resultsInfo, Simulation sim, SessionResult session)
        {
            var carIdx = resultsInfo.GetInt("CarIdx");

            if (carIdx >= int.MaxValue || carIdx < 0)
            {
                return;
            }

            var entity = sim.Session.Entities.FirstOrDefault(e => e.CarIdx == carIdx);

            if (entity == null)
            {
                return;
            }

            if (!(session.ResultsInt.FirstOrDefault(r => r.Entity.CarIdx == carIdx) is EntitySessionResult result))
            {
                // First time update
                result = InitResult(resultsInfo, sim, session, entity, carIdx);
            }

            if (session.Type == SessionType.Race && result.StartPosition == 0 && result.ClassStartPosition == 0)
            {
                if (session.HasQualifyPositions)
                {
                    // Heat racing: heat session that has a separate QualifyPositions list
                    var qp = session.QualifyPositions.FirstOrDefault(q => q.CarIdx == result.Entity.CarIdx);
                    if (qp != null)
                    {
                        result.StartPosition      = qp.Position;
                        result.ClassStartPosition = qp.ClassPosition;
                    }
                }
                else
                {
                    // Non-heat racing, or practice/qualy in heat racing (no separate QualifyPositions list)
                    var qualiResult = sim.Session.GetQualification()?
                                      .Results
                                      .FirstOrDefault(e => e.Entity.CarIdx == result.Entity.CarIdx);
                    if (qualiResult != null)
                    {
                        result.StartPosition      = qualiResult.Position;
                        result.ClassStartPosition = qualiResult.ClassPosition;
                    }
                }
            }

            result.FastestLapTime  = resultsInfo.GetFloat("FastestTime");
            result.LapsLed         = resultsInfo.GetInt("LapsLed");
            result.ReasonOutString = resultsInfo.GetString("ReasonOutStr");
            if (session.Type == SessionType.Race)
            {
                result.Gap = resultsInfo.GetFloat("Time");
            }
            result.GapLaps = resultsInfo.GetInt("Lap");

            // Check for new lap
            var completed = resultsInfo.GetInt("LapsComplete");

            if (sim.Session.Current != null && session.Type == sim.Session.Current.Type &&
                result.PreviousLap != null &&
                result.PreviousLap.Number == completed &&
                !result.PreviousLap.HasExactLaptime)
            {
                // New lap, set time and add to list
                result.PreviousLap.SetExactLaptime(resultsInfo.GetFloat("LastTime"));
                result.LastLapTime = result.PreviousLap.Time;

                // Set positions etc to make sure we have the latest info from sdk
                result.PreviousLap.Number        = completed;
                result.PreviousLap.Position      = resultsInfo.GetInt("Position");
                result.PreviousLap.ClassPosition = resultsInfo.GetInt("ClassPosition") + 1;
                result.PreviousLap.Gap           = resultsInfo.GetFloat("Time");
                result.PreviousLap.GapLaps       = resultsInfo.GetInt("Lap");

                // Update fastest lap etc
                if (result.FastestLap == null || LapIsNewFastestLap(result.Laps, result.PreviousLap))
                {
                    result.FastestLap = result.PreviousLap;
                }

                if (result.Position < result.HighestPosition || result.HighestPosition == 0)
                {
                    result.HighestPosition = result.Position;
                }

                if (result.Position > result.LowestPosition || result.LowestPosition == 0)
                {
                    result.LowestPosition = result.Position;
                }

                if (result.ClassPosition < result.ClassHighestPosition || result.ClassHighestPosition == 0)
                {
                    result.ClassHighestPosition = result.ClassPosition;
                }

                if (result.ClassPosition > result.ClassLowestPosition || result.ClassLowestPosition == 0)
                {
                    result.ClassLowestPosition = result.ClassPosition;
                }

                if (session.Flags.CheckBits(SessionFlags.Caution, SessionFlags.CautionWaving) && result.Position == 1)
                {
                    session.CautionLaps++;
                }

                // ReSharper disable once PossibleNullReferenceException
                var classLeader = session.GetClassLeader(result.Entity.Car.Class.Name);
                if (classLeader != null && classLeader.Entity.CarIdx == result.Entity.CarIdx)
                {
                    result.ClassLapsLed++;
                }

                result.Laps.AddLap(result.PreviousLap);
            }

            if (sim.Session.Current != null && sim.Session.Current.State == SessionState.CoolDown)
            {
                result.CurrentLap.IsUnknownLaptime = true;
            }

            var pos = resultsInfo.GetInt("Position");

            result.Position = pos > 0
                ? pos
                : result.StartPosition > 0
                    ? result.StartPosition
                    : int.MaxValue;

            if (result.Position == 1)
            {
                session.Leader = result.Entity;
            }

            result.ClassPosition      = resultsInfo.GetInt("ClassPosition") + 1;
            result.Incidents          = resultsInfo.GetInt("Incidents");
            result.JokerLapsCompleted = resultsInfo.GetInt("JokerLapsComplete");
        }