Beispiel #1
0
        public GameDiscordPresence(Game.StartProperties properties, GameMode mode)
        {
            switch (mode)
            {
            case GameMode.Replay:
                _presence = new DiscordRichPresence(1000, "Preparing to race", "Watching replay");
                break;

            case GameMode.Benchmark:
                _presence = new DiscordRichPresence(1000, "Preparing to race", "Running benchmark");
                break;

            case GameMode.Race:
                if (properties.GetAdditional <RsrMark>() != null)
                {
                    _presence = new DiscordRichPresence(1000, "RSR", "Hotlap");
                }
                else if (properties.GetAdditional <SrsMark>() != null)
                {
                    _presence = new DiscordRichPresence(1000, "SRS", "In a race");
                }
                else if (properties.GetAdditional <WorldSimSeriesMark>() != null)
                {
                    _presence = new DiscordRichPresence(1000, "WSS", "In a race");
                }
                else if (properties.ModeProperties is Game.OnlineProperties online)
                {
                    _presence = new DiscordRichPresence(1000, "Online", "In a race");
                    WatchForOnlineDetails(online).Ignore();
                }
                else if (properties.GetAdditional <SpecialEventsManager.EventProperties>()?.EventId is string challengeId)
                {
                    var challenge = SpecialEventsManager.Instance.GetById(challengeId);
                    _presence = new DiscordRichPresence(1000, "Driving Solo", challenge != null ? $"Challenge | {challenge.DisplayName}" : "Challenge");
                }
                else
                {
                    _presence = new DiscordRichPresence(1000, "Driving Solo", GetSessionName(properties.ModeProperties));
                }
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(mode), mode, null);
            }

            _presence.Now()
            .Car(properties.BasicProperties?.CarId)
            .Track(properties.BasicProperties?.TrackId, properties.BasicProperties?.TrackConfigurationId);
        }
Beispiel #2
0
        private static void PrepareRaceModeRsr(Game.StartProperties properties)
        {
            var rsrMode = properties.GetAdditional <RsrMark>() != null;
            var form    = AcSettingsHolder.Forms.Entries.GetByIdOrDefault(RsrMark.FormId);

            if (form != null)
            {
                form.SetVisibility(rsrMode);
                AcSettingsHolder.Forms.SaveImmediately();
            }
        }
Beispiel #3
0
        public void AddNewResult([NotNull] Game.StartProperties startProperties, [NotNull] Game.Result result)
        {
            var directory = SessionsDirectory;

            FileUtils.EnsureDirectoryExists(directory);

            var fileName = DateTime.Now.ToString("yyMMdd-HHmmss") + ".json";
            var raceOut  = AcPaths.GetResultJsonFilename();

            JObject data = null;

            if (File.Exists(raceOut))
            {
                try {
                    // Let’s try to save original data instead in case we missed something during parsing.
                    // But let’s remove formatting just in case.
                    data = JObject.Parse(File.ReadAllText(raceOut));
                } catch (Exception e) {
                    Logging.Warning(e);
                }
            }

            if (data == null)
            {
                data = JObject.FromObject(result);
            }

            // Trying to keep race params as well…
            // TODO: Do it the other way around, from start params?

            var raceIni = AcPaths.GetRaceIniFilename();

            if (File.Exists(raceIni))
            {
                data[KeyRaceIni] = File.ReadAllText(raceIni);
            }

            var quickDrive = startProperties.GetAdditional <QuickDrivePresetProperty>();

            if (quickDrive?.SerializedData != null)
            {
                data[KeyQuickDrive] = quickDrive.SerializedData;
            }

            File.WriteAllText(FileUtils.EnsureUnique(Path.Combine(directory, fileName)), data.ToString(Formatting.None));
        }
Beispiel #4
0
        private static void StartAsync_Prepare(Game.StartProperties properties)
        {
            if (!_nationCodesProviderSet)
            {
                _nationCodesProviderSet = true;
                try {
                    Game.NationCodeProvider = NationCodeProvider.Instance;
                } catch (Exception e) {
                    Logging.Unexpected(e);
                }
            }

            AcSettingsHolder.Graphics.FixShadowMapBias();
            CarCustomDataHelper.Revert();

            if (SettingsHolder.Drive.CheckAndFixControlsOrder)
            {
                try {
                    AcSettingsHolder.Controls.FixControllersOrder();
                } catch (Exception e) {
                    VisualCppTool.OnException(e, null);
                }
            }

            if (SettingsHolder.Common.FixResolutionAutomatically)
            {
                Logging.Debug("Trying to fix resolution just in case…");
                AcSettingsHolder.Video.EnsureResolutionIsCorrect();
            }

            properties.SetAdditional(new TrackDetails());
            properties.SetAdditional(
                new WeatherProceduralHelper(properties.ConditionProperties != null && properties.ConditionProperties.RoadTemperature == null));
            properties.SetAdditional(new WeatherSpecificLightingHelper());

            if (SettingsHolder.Drive.WeatherSpecificClouds)
            {
                properties.SetAdditional(new WeatherSpecificCloudsHelper());
            }

            if (SettingsHolder.Drive.WeatherSpecificTyreSmoke)
            {
                properties.SetAdditional(new WeatherSpecificTyreSmokeHelper());
            }

            if (File.Exists(properties.GetAdditional <CustomTrackState>()?.Filename))
            {
                properties.SetAdditional(new CustomTrackPropertiesHelper(properties.GetAdditional <CustomTrackState>()?.Filename ?? string.Empty));
            }

            if (SettingsHolder.Live.RsrEnabled && SettingsHolder.Live.RsrDisableAppAutomatically)
            {
                PrepareRaceModeRsr(properties);
            }

            var carId = properties.BasicProperties?.CarId;

            if (carId != null)
            {
                if (SettingsHolder.Drive.CamberExtravaganzaIntegration)
                {
                    CamberExtravaganzaHelper.UpdateDatabase(carId);
                }

                if (SettingsHolder.Drive.SidekickIntegration)
                {
                    SidekickHelper.UpdateSidekickDatabase(carId);
                }

                if (SettingsHolder.Drive.SidekickOdometerExportValues)
                {
                    SidekickHelper.OdometerExport(carId);
                }

                if (SettingsHolder.Drive.RaceEssentialsIntegration)
                {
                    RaceEssentialsHelper.UpdateRaceEssentialsDatabase(carId, false);
                }

                if (SettingsHolder.Drive.StereoOdometerExportValues)
                {
                    StereoOdometerHelper.Export(carId);
                }

                if (PatchHelper.IsFeatureSupported(PatchHelper.FeatureNeedsOdometerValue))
                {
                    var car = CarsManager.Instance.GetById(carId);
                    if (car != null)
                    {
                        properties.SetAdditional(new DrivenDistance(car.TotalDrivenDistance));
                    }
                }
            }

            properties.SetAdditional(new ModeSpecificPresetsHelper());
            properties.SetAdditional(new WeatherSpecificVideoSettingsHelper());
            properties.SetAdditional(new CarSpecificControlsPresetHelper());
            properties.SetAdditional(new CarRaceTextures());

            if (PatchHelper.GetInstalledVersion() != null)
            {
                properties.SetAdditional(new AcPatchTrackOutline());
            }

            properties.SetAdditional(new ExtraHotkeysRaceHelper());

            if (SettingsHolder.Drive.CopyFilterToSystemForOculus &&
                (AcSettingsHolder.Video.CameraMode.Id == "OCULUS" || AcSettingsHolder.Video.CameraMode.Id == "OPENVR"))
            {
                properties.SetAdditional(new CopyFilterToSystemForOculusHelper());
            }
        }
Beispiel #5
0
        private async Task Join(object o)
        {
            var carEntry = SelectedCarEntry;

            if (carEntry == null || Cars == null)
            {
                return;
            }

            var correctId = GetCorrectId(carEntry.Id);

            if (correctId == null)
            {
                Logging.Error("Can’t find correct ID");
                return;
            }

            if (!IsBookedForPlayer && BookingMode && !ReferenceEquals(o, ActualJoin) && !ReferenceEquals(o, ForceJoin))
            {
                if (_factory == null)
                {
                    Logging.Error("Booking: UI factory is missing");
                    return;
                }

                PrepareBookingUi();
                ProcessBookingResponse(await Task.Run(() => KunosApiProvider.TryToBook(Ip, PortHttp, Password, correctId, carEntry.AvailableSkin?.Id,
                                                                                       DriverName.GetOnline(), "")));
                return;
            }

            DisposeHelper.Dispose(ref _ui);
            IsBooked            = false;
            BookingErrorMessage = null;

            var properties = new Game.StartProperties(new Game.BasicProperties {
                CarId                = carEntry.Id,
                CarSkinId            = carEntry.AvailableSkin?.Id,
                TrackId              = Track?.Id,
                TrackConfigurationId = Track?.LayoutId
            }, null, null, null, new Game.OnlineProperties {
                RequestedCar   = correctId,
                ServerIp       = Ip,
                ServerName     = DisplayName,
                ServerPort     = PortRace,
                ServerHttpPort = PortHttp,
                Guid           = SteamIdHelper.Instance.Value,
                Password       = Password
            });

            var now = DateTime.Now;
            await GameWrapper.StartAsync(properties);

            var whatsGoingOn = properties.GetAdditional <WhatsGoingOn>();

            WrongPassword = whatsGoingOn?.Type == WhatsGoingOnType.OnlineWrongPassword;

            if (whatsGoingOn == null)
            {
                LastConnected = now;
                FileBasedOnlineSources.AddRecent(this).Forget();
                UpdateStats();
            }
        }
Beispiel #6
0
        private static BaseFinishedData GetFinishedData(Game.StartProperties properties, Game.Result result)
        {
            var conditions = properties?.GetAdditional <PlaceConditions>();
            var takenPlace = conditions?.GetTakenPlace(result) ?? PlaceConditions.UnremarkablePlace;

            Logging.Debug($"Place conditions: {conditions?.GetDescription()}, result: {result.GetDescription()}");

            if (result.GetExtraByType <Game.ResultExtraDrift>(out var drift))
            {
                return(new DriftFinishedData {
                    Points = drift.Points,
                    MaxCombo = drift.MaxCombo,
                    MaxLevel = drift.MaxLevel,
                    TakenPlace = takenPlace
                });
            }

            if (result.GetExtraByType <Game.ResultExtraTimeAttack>(out var timeAttack))
            {
                var bestLapTime = result.Sessions?.SelectMany(x => from lap in x.BestLaps where lap.CarNumber == 0 select lap.Time).MinOrDefault();
                return(new TimeAttackFinishedData {
                    Points = timeAttack.Points,
                    Laps = result.Sessions?.Sum(x => x.LapsTotalPerCar?.FirstOrDefault() ?? 0) ?? 0,
                    BestLapTime = bestLapTime == TimeSpan.Zero ? null : bestLapTime,
                    TakenPlace = takenPlace
                });
            }

            if (result.GetExtraByType <Game.ResultExtraBestLap>(out var bestLap) && bestLap.IsNotCancelled && result.Sessions?.Length == 1 &&
                result.Players?.Length == 1)
            {
                var bestLapTime = result.Sessions.SelectMany(x => from lap in x.BestLaps where lap.CarNumber == 0 select lap.Time).MinOrDefault();

                var sectorsPerSections  = result.Sessions.SelectMany(x => from lap in x.Laps where lap.CarNumber == 0 select lap.SectorsTime).ToList();
                var theoreticallLapTime = sectorsPerSections.FirstOrDefault()?.Select((x, i) => sectorsPerSections.Select(y => y[i]).Min()).Sum();

                return(result.Sessions[0].Name == AppStrings.Rsr_SessionName ? new RsrFinishedData {
                    Laps = result.Sessions.Sum(x => x.LapsTotalPerCar?.FirstOrDefault() ?? 0),
                    BestLapTime = bestLapTime == TimeSpan.Zero ? (TimeSpan?)null : bestLapTime,
                    TheoreticallLapTime = theoreticallLapTime,
                    TakenPlace = takenPlace
                } : new HotlapFinishedData {
                    Laps = result.Sessions.Sum(x => x.LapsTotalPerCar?.FirstOrDefault() ?? 0),
                    BestLapTime = bestLapTime == TimeSpan.Zero ? (TimeSpan?)null : bestLapTime,
                    TheoreticallLapTime = theoreticallLapTime,
                    TakenPlace = takenPlace
                });
            }

            var isOnline   = properties?.ModeProperties is Game.OnlineProperties;
            var playerName = isOnline && SettingsHolder.Drive.DifferentPlayerNameOnline
                    ? SettingsHolder.Drive.PlayerNameOnline : SettingsHolder.Drive.PlayerName;

            if (result.Sessions?.Length == 1 && result.Sessions[0].Name == Game.TrackDaySessionName && result.Players?.Length > 1)
            {
                var session    = result.Sessions[0];
                var playerLaps = session.LapsTotalPerCar?[0] ?? 1;
                session.LapsTotalPerCar = session.LapsTotalPerCar?.Select(x => Math.Min(x, playerLaps)).ToArray();
                session.Laps            = session.Laps?.Where(x => x.LapId < playerLaps).ToArray();
                session.BestLaps        = session.BestLaps?.Select(x => {
                    if (x.LapId < playerLaps)
                    {
                        return(x);
                    }
                    var best = session.Laps?.Where(y => y.CarNumber == x.CarNumber).MinEntryOrDefault(y => y.Time);
                    if (best == null)
                    {
                        return(null);
                    }
                    return(new Game.ResultBestLap {
                        Time = best.Time,
                        LapId = best.LapId,
                        CarNumber = x.CarNumber
                    });
                }).NonNull().ToArray();
            }

            var dragExtra    = result.GetExtraByType <Game.ResultExtraDrag>();
            var sessionsData = result.Sessions?.Select(session => {
                int[] takenPlaces;
                SessionFinishedData data;

                if (dragExtra != null)
                {
                    data = new DragFinishedData {
                        BestReactionTime = dragExtra.ReactionTime,
                        Total            = dragExtra.Total,
                        Wins             = dragExtra.Wins,
                        Runs             = dragExtra.Runs,
                    };

                    var delta   = dragExtra.Wins * 2 - dragExtra.Runs;
                    takenPlaces = new[] {
                        delta >= 0 ? 0 : 1,
                        delta <= 0 ? 0 : 1
                    };
                }
                else
                {
                    data        = new SessionFinishedData(session.Name?.ApartFromLast(@" Session"));
                    takenPlaces = session.GetTakenPlacesPerCar();
                }

                var sessionBestLap = session.BestLaps?.MinEntryOrDefault(x => x.Time);
                var sessionBest    = sessionBestLap?.Time;

                data.PlayerEntries = (
                    from player in result.Players
                    let car = CarsManager.Instance.GetById(player.CarId ?? "")
                              let carSkin = car?.GetSkinById(player.CarSkinId ?? "")
                                            select new { Player = player, Car = car, CarSkin = carSkin }
                    ).Select((entry, i) => {
                    var bestLapTime = session.BestLaps?.Where(x => x.CarNumber == i).MinEntryOrDefault(x => x.Time)?.Time;
                    var laps        = session.Laps?.Where(x => x.CarNumber == i).Select(x => new SessionFinishedData.PlayerLapEntry {
                        LapNumber          = x.LapId + 1,
                        Sectors            = x.SectorsTime,
                        Cuts               = x.Cuts,
                        TyresShortName     = x.TyresShortName,
                        Total              = x.Time,
                        DeltaToBest        = bestLapTime.HasValue ? x.Time - bestLapTime.Value : (TimeSpan?)null,
                        DeltaToSessionBest = sessionBest.HasValue ? x.Time - sessionBest.Value : (TimeSpan?)null,
                    }).ToArray();

                    var lapTimes = laps?.Skip(1).Select(x => x.Total.TotalSeconds).Where(x => x > 10d).ToList();
                    double?progress, spread;
                    if (lapTimes == null || lapTimes.Count < 2)
                    {
                        progress = null;
                        spread   = null;
                    }
                    else
                    {
                        var firstHalf    = lapTimes.Count / 2;
                        var firstMedian  = lapTimes.Take(firstHalf).Median();
                        var secondMedian = lapTimes.Skip(firstHalf).Median();
                        progress         = 1d - secondMedian / firstMedian;
                        spread           = (lapTimes.Max() - lapTimes.Min()) / bestLapTime?.TotalSeconds;
                    }

                    return(new SessionFinishedData.PlayerEntry {
                        Name = i == 0 ? playerName : entry.Player.Name,
                        IsPlayer = i == 0,
                        Index = i,
                        Car = entry.Car,
                        CarSkin = entry.CarSkin,
                        TakenPlace = i < takenPlaces?.Length ? takenPlaces[i] + 1 : DefinitelyNonPrizePlace,
                        PrizePlace = takenPlaces?.Length > 1,
                        LapsCount = session.LapsTotalPerCar?.ArrayElementAtOrDefault(i) ?? 0,
                        BestLapTime = bestLapTime,
                        DeltaToSessionBest = sessionBestLap?.CarNumber == i ? null : bestLapTime - sessionBest,
                        TotalTime = session.Laps?.Where(x => x.CarNumber == i).Select(x => x.SectorsTime.Sum()).Sum(),
                        Laps = laps,
                        LapTimeProgress = progress,
                        LapTimeSpread = spread
                    });
                }).OrderBy(x => x.TakenPlace).ToList();

                if (data.PlayerEntries.Count > 0)
                {
                    var maxLaps       = data.PlayerEntries.Select(x => x.Laps.Length).Max();
                    var bestTotalTime = data.PlayerEntries.Where(x => x.Laps.Length == maxLaps).MinEntryOrDefault(x => x.TotalTime ?? TimeSpan.MaxValue);
                    foreach (var entry in data.PlayerEntries)
                    {
                        var lapsDelta = maxLaps - entry.Laps.Length;
                        if (bestTotalTime == entry)
                        {
                            entry.TotalTimeDelta = "-";
                        }
                        else if (lapsDelta > 0)
                        {
                            entry.TotalTimeDelta = $"+{lapsDelta} {PluralizingConverter.Pluralize(lapsDelta, "lap")}";
                        }
                        else
                        {
                            var t = entry.TotalTime - bestTotalTime?.TotalTime;
                            var v = t?.ToMillisecondsString();
                            entry.TotalTimeDelta = t == TimeSpan.Zero ? "" : v != null ? $"+{v}" : null;
                        }
                    }
                }

                var bestProgress = (from player in data.PlayerEntries
                                    where player.LapTimeProgress > 0.03
                                    orderby player.LapTimeProgress descending
                                    select player).FirstOrDefault();
                var bestConsistent = (from player in data.PlayerEntries
                                      where player.LapTimeSpread < 0.02
                                      orderby player.LapTimeSpread descending
                                      select player).FirstOrDefault();

                data.RemarkableNotes = new[] {
                    sessionBestLap == null ? null :
                    new SessionFinishedData.RemarkableNote("[b]Best lap[/b] made by ", data.PlayerEntries.GetByIdOrDefault(sessionBestLap.CarNumber),
                                                           null),
                    new SessionFinishedData.RemarkableNote("[b]The Best Off-roader Award[/b] goes to ", (from player in data.PlayerEntries
                                                                                                         let cuts =
                                                                                                             (double)player.Laps.Sum(x => x.Cuts)
                                                                                                             / player.Laps.Length
                                                                                                             where cuts > 1.5
                                                                                                             orderby cuts descending
                                                                                                             select player).FirstOrDefault(), null),
                    new SessionFinishedData.RemarkableNote("[b]Remarkable progress[/b] shown by ", bestProgress, null),
                    new SessionFinishedData.RemarkableNote("[b]The most consistent[/b] is ", bestConsistent, null),
                }.Where(x => x?.Player != null).ToList();
                return(data);
            }).ToList();

            return(sessionsData?.Count == 1 ? (BaseFinishedData)sessionsData.First() :
                   sessionsData?.Any() == true ? new SessionsFinishedData(sessionsData) : null);
        }
Beispiel #7
0
        private static BaseFinishedData GetFinishedData(Game.StartProperties properties, Game.Result result)
        {
            var conditions = properties?.GetAdditional <PlaceConditions>();
            var takenPlace = conditions?.GetTakenPlace(result) ?? PlaceConditions.UnremarkablePlace;

            Logging.Debug($"Place conditions: {conditions?.GetDescription()}, result: {result.GetDescription()}");

            {
                var extra = result.GetExtraByType <Game.ResultExtraDrift>();
                if (extra != null)
                {
                    return(new DriftFinishedData {
                        Points = extra.Points,
                        MaxCombo = extra.MaxCombo,
                        MaxLevel = extra.MaxLevel,
                        TakenPlace = takenPlace
                    });
                }
            }

            {
                var extra = result.GetExtraByType <Game.ResultExtraTimeAttack>();
                if (extra != null)
                {
                    var bestLapTime = result.Sessions.SelectMany(x => from lap in x.BestLaps where lap.CarNumber == 0 select lap.Time).MinOrDefault();
                    return(new TimeAttackFinishedData {
                        Points = extra.Points,
                        Laps = result.Sessions.Sum(x => x.LapsTotalPerCar.FirstOrDefault()),
                        BestLapTime = bestLapTime == TimeSpan.Zero ? (TimeSpan?)null : bestLapTime,
                        TakenPlace = takenPlace
                    });
                }
            }

            {
                var extra = result.GetExtraByType <Game.ResultExtraBestLap>();
                if (extra != null && extra.IsNotCancelled && result.Sessions.Length == 1 && result.Players.Length == 1)
                {
                    var bestLapTime = result.Sessions.SelectMany(x => from lap in x.BestLaps where lap.CarNumber == 0 select lap.Time).MinOrDefault();

                    var sectorsPerSections  = result.Sessions.SelectMany(x => from lap in x.Laps where lap.CarNumber == 0 select lap.SectorsTime).ToList();
                    var theoreticallLapTime = sectorsPerSections.FirstOrDefault()?.Select((x, i) => sectorsPerSections.Select(y => y[i]).Min()).Sum();

                    return(new HotlapFinishedData {
                        Laps = result.Sessions.Sum(x => x.LapsTotalPerCar.FirstOrDefault()),
                        BestLapTime = bestLapTime == TimeSpan.Zero ? (TimeSpan?)null : bestLapTime,
                        TheoreticallLapTime = theoreticallLapTime,
                        TakenPlace = takenPlace
                    });
                }
            }

            var isOnline   = properties?.ModeProperties is Game.OnlineProperties;
            var playerName = isOnline && SettingsHolder.Drive.DifferentPlayerNameOnline ? SettingsHolder.Drive.PlayerNameOnline : SettingsHolder.Drive.PlayerName;

            var dragExtra    = result.GetExtraByType <Game.ResultExtraDrag>();
            var sessionsData = result.Sessions.Select(session => {
                int[] takenPlaces;
                SessionFinishedData data;

                if (dragExtra != null)
                {
                    data = new DragFinishedData {
                        BestReactionTime = dragExtra.ReactionTime,
                        Total            = dragExtra.Total,
                        Wins             = dragExtra.Wins,
                        Runs             = dragExtra.Runs,
                    };

                    var delta   = dragExtra.Wins * 2 - dragExtra.Runs;
                    takenPlaces = new[] {
                        delta >= 0 ? 0 : 1,
                        delta <= 0 ? 0 : 1
                    };
                }
                else
                {
                    data        = new SessionFinishedData(session.Name.ApartFromLast(@" Session"));
                    takenPlaces = session.GetTakenPlacesPerCar();
                }

                var sessionBestLap = session.BestLaps.MinEntryOrDefault(x => x.Time);
                var sessionBest    = sessionBestLap?.Time;

                data.PlayerEntries = (
                    from player in result.Players
                    let car = CarsManager.Instance.GetById(player.CarId)
                              let carSkin = car.GetSkinById(player.CarSkinId)
                                            select new { Player = player, Car = car, CarSkin = carSkin }
                    ).Select((entry, i) => {
                    var bestLapTime = session.BestLaps.Where(x => x.CarNumber == i).MinEntryOrDefault(x => x.Time)?.Time;
                    return(new SessionFinishedData.PlayerEntry {
                        Name = i == 0 ? playerName : entry.Player.Name,
                        IsPlayer = i == 0,
                        Car = entry.Car,
                        CarSkin = entry.CarSkin,
                        TakenPlace = i < takenPlaces.Length ? takenPlaces[i] + 1 : DefinitelyNonPrizePlace,
                        PrizePlace = takenPlaces.Length > 1,
                        LapsCount = session.LapsTotalPerCar.ElementAtOrDefault(i),
                        BestLapTime = bestLapTime,
                        DeltaToSessionBest = sessionBestLap?.CarNumber == i ? null : bestLapTime - sessionBest,
                        Total = session.Laps.Where(x => x.CarNumber == i).Select(x => x.Time).Sum(),
                        Laps = session.Laps.Where(x => x.CarNumber == i).Select(x => new SessionFinishedData.PlayerLapEntry {
                            LapNumber = x.LapId + 1,
                            Sectors = x.SectorsTime,
                            Total = x.Time,
                            DeltaToBest = bestLapTime.HasValue ? x.Time - bestLapTime.Value : (TimeSpan?)null,
                            DeltaToSessionBest = sessionBest.HasValue ? x.Time - sessionBest.Value : (TimeSpan?)null,
                        }).ToArray()
                    });
                }).OrderBy(x => x.TakenPlace).ToList();
                return(data);
            }).ToList();

            return(sessionsData.Count == 1 ? (BaseFinishedData)sessionsData.First() :
                   sessionsData.Any() ? new SessionsFinishedData(sessionsData) : null);
        }
Beispiel #8
0
        void IGameUi.OnResult(Game.Result result, ReplayHelper replayHelper)
        {
            if (result != null && result.NumberOfSessions == 1 && result.Sessions.Length == 1 &&
                result.Sessions[0].Type == Game.SessionType.Practice && SettingsHolder.Drive.SkipPracticeResults ||
                _properties?.ReplayProperties != null || _properties?.BenchmarkProperties != null)
            {
                Close();
                return;
            }

            /* save replay button * /
             * Func<string> buttonText = () => replayHelper?.IsReplayRenamed == true ?
             *      AppStrings.RaceResult_UnsaveReplay : AppStrings.RaceResult_SaveReplay;
             *
             * var saveReplayButton = CreateExtraDialogButton(buttonText(), () => {
             *  if (replayHelper == null) {
             *      Logging.Warning("ReplayHelper=<NULL>");
             *      return;
             *  }
             *
             *  replayHelper.IsReplayRenamed = !replayHelper.IsReplayRenamed;
             * });
             *
             * if (replayHelper == null) {
             *  saveReplayButton.IsEnabled = false;
             * } else {
             *  replayHelper.PropertyChanged += (sender, args) => {
             *      if (args.PropertyName == nameof(ReplayHelper.IsReplayRenamed)) {
             *          saveReplayButton.Content = buttonText();
             *      }
             *  };
             * }
             *
             * /* save replay alt button */
            ButtonWithComboBox saveReplayButton;

            if (replayHelper != null)
            {
                Func <string> buttonText = () => replayHelper.IsRenamed ?
                                           AppStrings.RaceResult_UnsaveReplay : AppStrings.RaceResult_SaveReplay;
                Func <string> saveAsText = () => string.Format(replayHelper.IsRenamed ? "Saved as “{0}”" : "Save as “{0}”",
                                                               replayHelper.Name);

                saveReplayButton = new ButtonWithComboBox {
                    Margin    = new Thickness(4, 0, 0, 0),
                    MinHeight = 21,
                    MinWidth  = 65,
                    Content   = ToolsStrings.Shared_Replay,
                    Command   = new AsyncCommand(replayHelper.Play),
                    MenuItems =
                    {
                        new MenuItem {
                            Header = saveAsText(), Command = new DelegateCommand(() =>{
                                var newName = Prompt.Show("Save replay as:", "Replay Name", replayHelper.Name, "?", required: true);
                                if (!string.IsNullOrWhiteSpace(newName))
                                {
                                    replayHelper.Name = newName;
                                }

                                replayHelper.IsRenamed = true;
                            })
                        },
                        new MenuItem {
                            Header = buttonText(), Command = new DelegateCommand(replayHelper.Rename)
                        },
                        new Separator(),
                        new MenuItem {
                            Header  = "Share Replay",
                            Command = new AsyncCommand(() =>{
                                var car = _properties?.BasicProperties?.CarId == null ? null :
                                          CarsManager.Instance.GetById(_properties.BasicProperties.CarId);
                                var track = _properties?.BasicProperties?.TrackId == null ? null :
                                            TracksManager.Instance.GetById(_properties.BasicProperties.TrackId);
                                return(SelectedReplayPage.ShareReplay(replayHelper.Name, replayHelper.Filename, car, track));
                            })
                        },
                    }
                };

                replayHelper.PropertyChanged += (sender, args) => {
                    if (args.PropertyName == nameof(ReplayHelper.IsRenamed))
                    {
                        ((MenuItem)saveReplayButton.MenuItems[0]).Header = saveAsText();
                        ((MenuItem)saveReplayButton.MenuItems[1]).Header = buttonText();
                    }
                };
            }
            else
            {
                saveReplayButton = null;
            }

            var tryAgainButton = CreateExtraDialogButton(AppStrings.RaceResult_TryAgain, () => {
                CloseWithResult(MessageBoxResult.None);
                GameWrapper.StartAsync(_properties).Forget();
            });

            Button fixButton = null;

            if (result == null || !result.IsNotCancelled)
            {
                Model.CurrentState = ViewModel.State.Cancelled;

                var whatsGoingOn = _properties?.GetAdditional <WhatsGoingOn>();
                fixButton          = this.CreateFixItButton(whatsGoingOn?.Solution);
                Model.ErrorMessage = whatsGoingOn?.GetDescription();
            }
            else
            {
                try {
                    Model.CurrentState = ViewModel.State.Finished;
                    Model.FinishedData = GetFinishedData(_properties, result);
                } catch (Exception e) {
                    Logging.Warning(e);

                    Model.CurrentState = ViewModel.State.Error;
                    Model.ErrorMessage = AppStrings.RaceResult_ResultProcessingError;
                    Buttons            = new[] { CloseButton };
                    return;
                }
            }

            Buttons = new[] {
                fixButton,
                fixButton == null ? saveReplayButton : null,
                fixButton == null ? tryAgainButton : null,
                CloseButton
            };
        }
Beispiel #9
0
        private async Task Join(object o) {
            var carEntry = CarsView?.CurrentItem as CarEntry;
            if (carEntry == null) return;

            var carId = carEntry.CarObject.Id;
            var correctId = CarIds.FirstOrDefault(x => string.Equals(x, carId, StringComparison.OrdinalIgnoreCase));

            if (BookingMode && !ReferenceEquals(o, ActualJoin) && !ReferenceEquals(o, ForceJoin)) {
                if (_factory == null) {
                    Logging.Error("Booking: UI factory is missing");
                    return;
                }

                PrepareBookingUi();
                ProcessBookingResponse(await Task.Run(() => KunosApiProvider.TryToBook(Ip, PortC, Password, correctId, carEntry.AvailableSkin?.Id,
                        DriverName.GetOnline(), "")));
                return;
            }

            DisposeHelper.Dispose(ref _ui);
            IsBooked = false;
            BookingErrorMessage = null;

            var properties = new Game.StartProperties(new Game.BasicProperties {
                CarId = carId,
                CarSkinId = carEntry.AvailableSkin?.Id,
                TrackId = Track?.Id,
                TrackConfigurationId = Track?.LayoutId
            }, null, null, null, new Game.OnlineProperties {
                RequestedCar = correctId,
                ServerIp = Ip,
                ServerName = DisplayName,
                ServerPort = PortT,
                ServerHttpPort = PortC,
                Guid = SteamIdHelper.Instance.Value,
                Password = Password
            });

            await GameWrapper.StartAsync(properties);
            var whatsGoingOn = properties.GetAdditional<AcLogHelper.WhatsGoingOn>();
            WrongPassword = whatsGoingOn?.Type == AcLogHelper.WhatsGoingOnType.OnlineWrongPassword;
            if (whatsGoingOn == null) RecentManager.Instance.AddRecentServer(OriginalInformation);
        }