public static TyresEntry ToTyresEntry([NotNull] this NeuralTyresEntry values, [CanBeNull] TyresEntry original, [CanBeNull] string name, [CanBeNull] string shortName) { var mainSection = original?.MainSection.Clone() ?? new IniFileSection(null); var thermalSection = original?.ThermalSection.Clone() ?? new IniFileSection(null); mainSection.Set("NAME", name.Or(values.Name)); mainSection.Set("SHORT_NAME", shortName.Or(values.ShortName)); foreach (var key in values.Keys.ApartFrom(NeuralTyresEntry.TemporaryKeys)) { if (key.StartsWith(ThermalPrefix)) { var actualKey = key.Substring(ThermalPrefix.Length); thermalSection.Set(actualKey, Fix(values[key], key)); } else { mainSection.Set(key, Fix(values[key], key)); } } return(new TyresEntry(original?.SourceCarId, values.Version, mainSection, thermalSection, original?.WearCurveData, original?.PerformanceCurveData, original?.RearTyres ?? false, null)); double Fix(double value, string key) { var digits = GetValueDigits(key); return(digits.HasValue ? FlexibleParser.ParseDouble(value.ToString($@"F{digits.Value}"), value) : value); } }
public async Task <WeatherDescription> GetWeatherAsync(GeoTagsEntry geoTags) { var requestUri = string.Format(RequestWeatherUri, geoTags.LatitudeValue, geoTags.LongitudeValue, InternalUtils.GetOpenWeatherApiCode()); #if DEBUG Logging.Write(requestUri); #endif using (var order = KillerOrder.Create(new WebClient(), 5000)) { var data = await order.Victim.DownloadStringTaskAsync(requestUri); XDocument doc; try { doc = XDocument.Parse(data); } catch (XmlException) { Logging.Warning("response: " + data); throw; } var temperatureValue = doc.Descendants(@"temperature").FirstOrDefault()?.Attribute(@"value")?.Value; var weatherNode = doc.Descendants(@"weather").FirstOrDefault(); if (temperatureValue == null || weatherNode == null) { throw new Exception("Invalid response"); } var temperature = FlexibleParser.ParseDouble(temperatureValue); var type = OpenWeatherTypeToCommonType((OpenWeatherType)int.Parse(weatherNode.Attribute(@"number")?.Value, NumberStyles.Any, CultureInfo.InvariantCulture)); var description = weatherNode.Attribute(@"value")?.Value; var icon = weatherNode.Attribute(@"icon")?.Value; var iconUri = icon == null ? null : string.Format(IconUri, icon); return(new WeatherDescription(type, temperature, description, iconUri)); } }
public static Color GetColor(this IniFileSection section, [LocalizationRequired(false)] string key, Color defaultValue, double defaultMultipler, out double multipler) { var strings = section.GetStrings(key); var result = strings.Select(x => FlexibleParser.ParseInt(x, 0).ClampToByte()).ToArray(); if (strings.Length != 4) { multipler = 1d; return(defaultValue); } multipler = FlexibleParser.ParseDouble(strings[3], 1d); return(Color.FromRgb(result[0], result[1], result[2])); }
private static TimeSpan Convert(string s) { var p = s?.Split(new[] { ':' }, 3).Select(x => FlexibleParser.ParseDouble(x)).ToList(); switch (p?.Count) { case 1: return(TimeSpan.FromMinutes((p[0] < 0 ? -1 : 1) * p[0].Abs())); case 2: return(TimeSpan.FromMinutes((p[0] < 0 ? -1 : 1) * (p[0].Abs() * 60 + p[1]))); default: return(default(TimeSpan)); } }
private async Task RunProcessAsync(string filename, IEnumerable <string> args, IProgress <double?> progress, CancellationToken cancellationToken) { var process = ProcessExtension.Start(filename, args, new ProcessStartInfo { UseShellExecute = false, RedirectStandardOutput = progress != null, RedirectStandardError = true, CreateNoWindow = true }); try { cancellationToken.ThrowIfCancellationRequested(); if (progress != null) { process.OutputDataReceived += (sender, eventArgs) => { if (!string.IsNullOrWhiteSpace(eventArgs.Data)) { progress.Report(FlexibleParser.ParseDouble(eventArgs.Data, 0d) / 100d); } }; } process.ErrorDataReceived += (sender, eventArgs) => { if (!string.IsNullOrWhiteSpace(eventArgs.Data)) { AcToolsLogging.Write(eventArgs.Data); } }; if (progress != null) { process.BeginOutputReadLine(); } process.BeginErrorReadLine(); await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false); if (process.ExitCode != 0) { throw new Exception("Failed to run process: " + process.ExitCode); } } finally { if (!process.HasExitedSafe()) { process.Kill(); } process.Dispose(); } }
public static Lut FromValue([NotNull, LocalizationRequired(false)] string value) { var capacity = 0; for (var i = 1; i < value.Length; i++) { if (value[i] == '=') { capacity++; } } var result = new Lut(capacity); if (value.Length > 2 && value[0] == '(' && value[value.Length - 1] == ')') { var j = 1; double?key = null; for (var i = 1; i < value.Length; i++) { switch (value[i]) { case '|': case ')': if (i > j && key.HasValue) { result.Add(new LutPoint(key.Value, FlexibleParser.ParseDouble(value.Substring(j, i - j), 0d))); key = null; } j = i + 1; break; case '=': if (i > j) { key = FlexibleParser.ParseDouble(value.Substring(j, i - j), 0d); } j = i + 1; break; } } } return(result); }
public static async Task <BookingResult> TryToBookAsync(string ip, int portC, string password, string carId, string skinId, string driverName, string teamName) { var steamId = SteamIdHelper.Instance.Value ?? @"-1"; var arguments = new[] { carId, skinId, driverName, teamName, steamId, password }.Select(x => x ?? "").JoinToString('|'); var requestUri = $@"http://{ip}:{portC}/SUB|{HttpUtility.UrlPathEncode(arguments)}"; try { Logging.Debug("Request: " + requestUri); var response = await LoadAsync(requestUri, OptionDirectRequestTimeout); Logging.Debug("Response: " + response); var split = response.Split(','); switch (split[0]) { case "OK": return(new BookingResult(TimeSpan.FromSeconds(FlexibleParser.ParseDouble(split[1])))); case "ILLEGAL CAR": return(new BookingResult(ToolsStrings.Online_BookingResult_IllegalCar)); case "INCORRECT PASSWORD": return(new BookingResult(ToolsStrings.Online_BookingResult_IncorrectPassword)); case "CLOSED": return(new BookingResult(ToolsStrings.Online_BookingResult_Closed)); case "BLACKLISTED": return(new BookingResult(ToolsStrings.Online_BookingResult_Blacklisted)); case "SERVER FULL": return(new BookingResult(ToolsStrings.Online_BookingResult_ServerFull)); default: return(new BookingResult(string.Format(ToolsStrings.Online_BookingResult_UnsupportedNonOkMessage, response))); } } catch (WebException e) { Logging.Warning($"Cannot book: {requestUri}, {e.Message}"); return(null); } catch (Exception e) { Logging.Warning($"Cannot book: {requestUri}\n{e}"); return(null); } }
public static async Task <GeoTagsEntry> LocateAsync([CanBeNull] string address) { var requestUri = string.Format(RequestLocationUri, HttpUtility.UrlEncode(CleanUpRegex.Replace(address ?? "", " "))); using (var order = KillerOrder.Create(new WebClient(), 5000)) { var data = await order.Victim.DownloadStringTaskAsync(requestUri); var ns = XNamespace.Get(@"http://where.yahooapis.com/v1/schema.rng"); var centroid = XDocument.Parse(data).Descendants(ns + @"centroid").FirstOrDefault(); var latitude = centroid?.Element(ns + @"latitude"); var longitude = centroid?.Element(ns + @"longitude"); if (latitude == null || longitude == null) { throw new Exception("Invalid response"); } return(new GeoTagsEntry(FlexibleParser.ParseDouble(latitude.Value), FlexibleParser.ParseDouble(longitude.Value))); } }
public float GetFloat([NotNull, LocalizationRequired(false)] string key, float defaultValue) { return((float)FlexibleParser.ParseDouble(GetPossiblyEmpty(key), defaultValue)); }
public double GetDouble([NotNull, LocalizationRequired(false)] string key, double defaultValue) { return(FlexibleParser.ParseDouble(GetPossiblyEmpty(key), defaultValue)); }
public float[] GetVector3F([NotNull, LocalizationRequired(false)] string key) { var result = GetStrings(key).Select(x => (float)FlexibleParser.ParseDouble(x, 0d)).ToArray(); return(result.Length == 3 ? result : new float[3]); }
public static int Main(string[] args) { try { Trace.Listeners.Add(new ConsoleTraceListener()); FileUtils.TryToDelete(Path.Combine(MainExecutingFile.Directory, "Log.txt")); Trace.Listeners.Add(new DefaultTraceListener { LogFileName = Path.Combine(MainExecutingFile.Directory, "Log.txt") }); var argsLoaded = false; if (args.Length > 0) { try { if (File.Exists(args[0])) { var extraFileArgs = Path.Combine(Path.GetDirectoryName(args[0]) ?? ".", "Baked Shadows Params.txt"); if (File.Exists(extraFileArgs)) { args = File.ReadAllLines(extraFileArgs).Where(x => !string.IsNullOrWhiteSpace(x) && !x.TrimStart().StartsWith("#")) .Union(args).ToArray(); argsLoaded = true; } else { extraFileArgs = Path.Combine(Path.GetDirectoryName(args[0]) ?? ".", "Baked_Shadows_Params.txt"); if (File.Exists(extraFileArgs)) { args = File.ReadAllLines(extraFileArgs).Where(x => !string.IsNullOrWhiteSpace(x) && !x.TrimStart().StartsWith("#")) .Union(args).ToArray(); argsLoaded = true; } } } } catch { // ignored } } if (!argsLoaded) { var extraArgs = Path.Combine(MainExecutingFile.Directory, "Arguments.txt"); if (File.Exists(extraArgs)) { args = File.ReadAllLines(extraArgs).Where(x => !string.IsNullOrWhiteSpace(x) && !x.TrimStart().StartsWith("#")) .Union(args).ToArray(); } } var options = new Options(); if (!Parser.Default.ParseArguments(args, options) || options.Items.Count == 0 || options.Help) { Trace.WriteLine(options.GetUsage()); return(options.Help ? 0 : 1); } string mainKn5 = null; string destination; var includeKn5 = new List <string>(); var occludersKn5 = new List <string>(); if (options.Items[0].EndsWith(".ini")) { var ini = new IniFile(options.Items[0]); var trackDirectory = Path.GetDirectoryName(ini.Filename) ?? "."; var first = true; includeKn5.Clear(); occludersKn5.Clear(); foreach (var model in ini.GetSections("MODEL").Select(x => x.GetNonEmpty("FILE")).NonNull() .Select(x => Path.Combine(trackDirectory, x)).Where(File.Exists)) { if (first) { first = false; mainKn5 = model; } else { includeKn5.Add(model); } } destination = Path.Combine(trackDirectory, Path.GetFileNameWithoutExtension(ini.Filename) + ".vao-patch"); } else { mainKn5 = options.Items[0]; destination = options.Destination ?? options.Items[0]; var trackDirectory = Path.GetDirectoryName(mainKn5) ?? "."; if (!options.ModifyKn5Directly) { if (!string.IsNullOrWhiteSpace(options.IncludeKn5Filter)) { var includeFilter = Filter.Create(StringTester.Instance, options.IncludeKn5Filter, new FilterParams { StringMatchMode = StringMatchMode.CompleteMatch }); foreach (var file in Directory.GetFiles(trackDirectory, "*.kn5").Where(x => includeFilter.Test(Path.GetFileName(x)) && !FileUtils.ArePathsEqual(x, mainKn5))) { includeKn5.Add(file); destination = Path.Combine(trackDirectory, Path.GetFileName(trackDirectory)) + ".kn5"; } } } if (!string.IsNullOrWhiteSpace(options.OccludersKn5Filter ?? options.CommonKn5Filter)) { var occludersFilter = Filter.Create(StringTester.Instance, options.OccludersKn5Filter ?? options.CommonKn5Filter, new FilterParams { StringMatchMode = StringMatchMode.CompleteMatch }); foreach (var file in Directory.GetFiles(trackDirectory, "*.kn5").Where(x => occludersFilter.Test(Path.GetFileName(x)) && !FileUtils.ArePathsEqual(x, mainKn5))) { occludersKn5.Add(file); } } } if (mainKn5 == null) { throw new Exception("Main KN5 not found"); } using (var bakery = new MainBakery(mainKn5, options.Filter, options.IgnoreFilter, !options.ModifyKn5Directly) { AoOpacity = options.AoOpacity, AoMultiplier = options.AoMultiplier, SaturationGain = options.SaturationGain, SaturationInputMultiplier = options.SaturationInputMultiplier, CameraFov = options.CameraFov, CameraNear = options.CameraNear, CameraFar = options.CameraFar, CameraNormalOffsetUp = options.CameraNormalOffsetUp, CameraOffsetAway = options.CameraOffsetAway, CameraOffsetUp = options.CameraOffsetUp, OccludersDistanceThreshold = options.OccludersDistanceThreshold, MergeVertices = options.MergeVertices, MergeThreshold = options.MergeThreshold, OccludersSplitThreshold = options.OccludersSplitThreshold, QueueSize = options.QueueSize, SampleResolution = options.SampleResolution, ExtraPassBrightnessGain = options.ExtraPassBrightnessGain, HdrSamples = options.HdrSamples, Ground = !options.NoGround, SyncNormalsFilter = options.SyncNormals, SyncNormalsPartiallyFilter = options.SyncNormalsPartially, SyncNormalsPartiallyValue = options.SyncNormalsPartiallyValue, ExtraPass = options.ExtraPass, TreeFilter = options.TreeFilter, GrassFilter = options.GrassFilter, RegularObjectsFilter = options.RegularObjectsFilter, SkipOccludersFilter = options.SkipOccludersFilter, SpecialGrassAmbient = !options.NoSpecialGrassAmbient, SurfacesFilter = options.Surfaces, SurfacesAoOpacity = options.SurfacesAoOpacity, SetMiltiplierForSkipped = options.SetMiltiplierForSkipped, }) { if (!string.IsNullOrWhiteSpace(options.DebugPos)) { bakery.DebugMode = true; bakery.DebugPoint = options.DebugPos.Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries) .Select(x => (float)FlexibleParser.ParseDouble(x)) .ToArray().ToVector3(); bakery.DebugRadius = options.DebugRange; Console.WriteLine("Debug mode: " + bakery.DebugPoint); } bakery.LoadExtraKn5(includeKn5, occludersKn5).Work(destination); } Trace.Listeners.Clear(); return(0); } catch (Exception e) { Trace.WriteLine(e.ToString()); return(2); } finally { if (ParentProcessUtilities.GetParentProcess().ProcessName == "explorer") { Console.ReadLine(); } } }
public static async Task <TimeZoneInfo> DetermineTimeZoneAsync(GeoTagsEntry geoTags) { var requestUri = string.Format(RequestTimeZoneUri, geoTags.LatitudeValue, geoTags.LongitudeValue, DateTime.Now.ToUnixTimestamp()); Logging.Debug(requestUri); using (var order = KillerOrder.Create(new WebClient(), 5000)) { var data = await order.Victim.DownloadStringTaskAsync(requestUri); var doc = XDocument.Parse(data); var zoneId = doc.Descendants(@"time_zone_id").FirstOrDefault()?.Value; if (zoneId == null) { throw new Exception("Invalid response"); } try { return(TimeZoneInfo.FindSystemTimeZoneById(zoneId)); } catch (TimeZoneNotFoundException) { var rawOffset = doc.Descendants(@"raw_offset").FirstOrDefault()?.Value; var zoneName = doc.Descendants(@"time_zone_name").FirstOrDefault()?.Value; if (rawOffset == null || zoneName == null) { throw new Exception("Invalid response"); } return(TimeZoneInfo.CreateCustomTimeZone(zoneId, TimeSpan.FromSeconds(FlexibleParser.ParseDouble(rawOffset)), zoneName, zoneName)); } } }
public static Color GetNormalizedColor(this IniFileSection section, [LocalizationRequired(false)] string key, Color defaultValue) { var result = section.GetStrings(key).Select(x => (FlexibleParser.ParseDouble(x, 0d) * 255).ClampToByte()).ToArray(); return(result.Length == 3 ? Color.FromRgb(result[0], result[1], result[2]) : defaultValue); }
private async Task LoadSpecs(CarObject value) { var acc = FlexibleParser.ParseDouble(value.SpecsAcceleration, 100); AccelerationValue = acc < 0.1 ? (double?)null : 1.0 - (acc - 2.0) / 10.0; TopSpeedValue = (FlexibleParser.TryParseDouble(value.SpecsTopSpeed) - 150) / 200; WeightValue = 1.0 - (FlexibleParser.TryParseDouble(value.SpecsWeight) - 600) / 1200; var tyres = await Task.Run(() => value.AcdData.GetIniFile("tyres.ini")); var tyresNames = tyres.Values.Select(x => x.GetNonEmpty("NAME")).Where(x => x != null).Distinct().ToList(); Tyres = tyresNames.JoinToString(", "); var handlingValue = 0d; foreach (var name in tyresNames) { switch (name.ToLowerInvariant()) { case "michelin xas": handlingValue = Math.Max(handlingValue, 0.1); break; case "street70s": case "street 70s": handlingValue = Math.Max(handlingValue, 0.2); break; case "cinturato": case "vintage": case "street90s": case "street 90s": handlingValue = Math.Max(handlingValue, 0.3); break; case "street": case "modern street": handlingValue = Math.Max(handlingValue, 0.4); break; case "semislick": case "semislicks": handlingValue = Math.Max(handlingValue, 0.5); break; case "slick hard": handlingValue = Math.Max(handlingValue, 0.6); break; case "slick medium": handlingValue = Math.Max(handlingValue, 0.7); break; case "slicks": case "slick soft": handlingValue = Math.Max(handlingValue, 0.8); break; case "hypercar trofeo": handlingValue = Math.Max(handlingValue, 0.9); break; } } HandlingValue = handlingValue * (0.8 + 0.4 * (WeightValue ?? 0d)); }
public static async Task <TimeZoneInfo> DetermineTimeZoneAsync(GeoTagsEntry geoTags) { var requestUri = string.Format(RequestTimeZoneUri, geoTags.LatitudeValue, geoTags.LongitudeValue, InternalUtils.GetTimeZoneDbApiCode()); #if DEBUG Logging.Debug(requestUri); #endif using (var order = KillerOrder.Create(new CookieAwareWebClient(), 15000)) { var data = await order.Victim.DownloadStringTaskAsync(requestUri); var doc = JObject.Parse(data); var zoneId = doc.GetStringValueOnly("zoneName"); if (zoneId == null) { throw new Exception("Invalid response"); } Logging.Write("Returned zone ID: " + zoneId); try { Logging.Write("Parsed as: " + TZConvert.GetTimeZoneInfo(zoneId).ToSerializedString()); return(TZConvert.GetTimeZoneInfo(zoneId)); } catch (TimeZoneNotFoundException) { var rawOffset = doc.GetStringValueOnly(@"gmtOffset"); return(TimeZoneInfo.CreateCustomTimeZone(zoneId, TimeSpan.FromSeconds(FlexibleParser.ParseDouble(rawOffset)), zoneId, zoneId)); } } /*var requestUri = string.Format(RequestTimeZoneUri, geoTags.LatitudeValue, geoTags.LongitudeValue, * DateTime.Now.ToUnixTimestamp(), InternalUtils.GetGoogleMapsApiCode()); * * using (var order = KillerOrder.Create(new WebClient(), 5000)) { * var data = await order.Victim.DownloadStringTaskAsync(requestUri); * var doc = XDocument.Parse(data); * var zoneId = doc.Descendants(@"time_zone_id").FirstOrDefault()?.Value; * if (zoneId == null) throw new Exception("Invalid response"); * * try { * return TZConvert.GetTimeZoneInfo(zoneId); * } catch (TimeZoneNotFoundException) { * var rawOffset = doc.Descendants(@"raw_offset").FirstOrDefault()?.Value; * var zoneName = doc.Descendants(@"time_zone_name").FirstOrDefault()?.Value; * if (rawOffset == null || zoneName == null) throw new Exception("Invalid response"); * return TimeZoneInfo.CreateCustomTimeZone(zoneId, TimeSpan.FromSeconds(FlexibleParser.ParseDouble(rawOffset)), zoneName, zoneName); * } * }*/ }