public static string GetFilenameSafe([NotNull] this Process process) { if (process == null) { throw new ArgumentNullException(nameof(process)); } try { var path = GetProcessPathUsingPsApi(process.Id); if (path != null) { AcToolsLogging.Write("PS API: " + path); return(path); } // very slow path = GetProcessPathUsingManagement(process.Id); if (path != null) { AcToolsLogging.Write("Management: " + path); return(path); } AcToolsLogging.Write("Management failed!"); // won’t work if processes were compiled for different architectures path = process.MainModule.FileName; AcToolsLogging.Write("MainModule.FileName: " + path); return(path); } catch (Exception e) { AcToolsLogging.Write(e); return(null); } }
public byte[] Shot(string textureName, [CanBeNull] string objectPath, [CanBeNull] IProgress <double> progress, CancellationToken cancellation) { if (!Initialized) { Initialize(); if (cancellation.IsCancellationRequested) { return(null); } } _filteredNodes = Flatten(Kn5, Scene, textureName, objectPath).OfType <TrianglesRenderableObject <InputLayouts.VerticePT> >() .Select(x => new UvProjectedObject(x)).ToArray(); AcToolsLogging.Write("Filtered nodes:\n" + _filteredNodes.Select(x => x.Name).JoinToString('\n')); PrepareBuffers(MapSize); SetBodyShadowCamera(); if (cancellation.IsCancellationRequested) { return(null); } Draw(1f, progress, cancellation); if (cancellation.IsCancellationRequested) { return(null); } using (var stream = new MemoryStream()) { Texture2D.ToStream(DeviceContext, RenderBuffer, ImageFileFormat.Png, stream); return(stream.ToArray()); } }
public void SetShowroom(string showroomKn5) { // TODO: errors handling! try { if (ShowroomNode != null) { ShowroomNode.Dispose(); Scene.Remove(ShowroomNode); ShowroomNode = null; GC.Collect(); } var node = LoadShowroom(showroomKn5); ShowroomNode = node; if (node != null) { Scene.Insert(0, node); } } catch (Exception e) { AcToolsLogging.Write(e); } finally { CubemapReflection = ShowroomNode != null; Scene.UpdateBoundingBox(); IsDirty = true; _sceneDirty = true; } }
protected static bool LoadLogitechSteeringWheelDll() { if (_logitechDllInitialized.HasValue) { return(_logitechDllInitialized.Value); } // Library is in PATH, next to executable, somewhere in system or in a list of libraries to load, nice. try { if (Kernel32.LoadLibrary(LogitechSteeringWheel) != IntPtr.Zero) { return((_logitechDllInitialized = true).Value); } } catch (Exception e) { AcToolsLogging.Write($"Failed to load: {e.Message}"); } // Trying to find the library in Logitech Gaming Software installation… AcToolsLogging.Write($"Trying to locate {LogitechSteeringWheel}…"); foreach (var location in LocateLogitechSteeringWheelDll().Where(File.Exists)) { AcToolsLogging.Write($"Found: {location}"); try { Kernel32.LoadLibrary(location); return((_logitechDllInitialized = true).Value); } catch (Exception e) { AcToolsLogging.Write($"Failed to load: {e.Message}"); } } AcToolsLogging.NonFatalErrorNotifyBackground($"Failed to find “{LogitechSteeringWheel}”", "Please, make sure you have Logitech Gaming Software installed, or simply put that library next to executable."); return((_logitechDllInitialized = false).Value); }
public static Matrix ToMatrixFixX(this float[] mat4x4) { var matrix = mat4x4.ToMatrix(); Vector3 translation, scale; Quaternion rotation; matrix.Decompose(out scale, out rotation, out translation); translation.X *= -1; var axis = rotation.Axis; var angle = rotation.Angle; if (angle.Abs() < 0.0001f) { return(Matrix.Scaling(scale) * Matrix.Translation(translation)); } axis.Y *= -1; axis.Z *= -1; rotation = Quaternion.RotationAxis(axis, angle); var result = Matrix.Scaling(scale) * Matrix.RotationQuaternion(rotation) * Matrix.Translation(translation); if (float.IsNaN(result[0, 0])) { AcToolsLogging.Write("CAN’T FIX MATRIX! PLEASE, SEND THE MODEL TO THE DEVELOPER"); return(matrix); } return(result); }
public static SuspensionsGroupBase Create(IniFile ini, bool front, float wheelRadius) { var basic = ini["BASIC"]; var section = ini[front ? "FRONT" : "REAR"]; var type = section.GetNonEmpty("TYPE"); switch (type) { case "DWB": return(new IndependentSuspensionsGroup( new DwbSuspension(basic, section, front, 1f, wheelRadius), new DwbSuspension(basic, section, front, -1f, wheelRadius))); case "STRUT": return(new IndependentSuspensionsGroup( new StrutSuspension(basic, section, front, 1f, wheelRadius), new StrutSuspension(basic, section, front, -1f, wheelRadius))); case "AXLE": return(new DependentSuspensionGroup( new AxleSuspension(basic, section, ini["AXLE"], front, wheelRadius))); default: AcToolsLogging.Write($"Unknown suspension type: “{type}”"); return(null); } }
protected async Task <byte[]> TryLoadBytes(string filename, bool magickMode, int attempts, bool initialDelay) { byte[] bytes = null; var second = false; while (attempts-- > 0) { try { if (initialDelay || second) { await Task.Delay(200).ConfigureAwait(false); } second = true; bytes = await FileUtils.ReadAllBytesAsync(filename).ConfigureAwait(false); if (magickMode) { var b = bytes; // bytes = await Task.Run(() => ImageUtils.LoadAsConventionalBuffer(b)); bytes = ImageUtils.LoadAsConventionalBuffer(b); } break; } catch (FileNotFoundException) { return(null); }catch (Exception e) { AcToolsLogging.Write(e); Logging.Warning("UpdateOverrideLater(): " + e.Message); } } return(bytes); }
public bool IsHdrTexture(ShaderResourceView view, Size size) { using (var maxColor = GetLimits(view, size, ((Texture2D)view.Resource).Description.Format)) { var texture = maxColor.Texture; using (var copy = new Texture2D(Device, new Texture2DDescription { SampleDescription = new SampleDescription(1, 0), Width = texture.Description.Width, Height = texture.Description.Height, ArraySize = texture.Description.ArraySize, MipLevels = texture.Description.MipLevels, Format = texture.Description.Format, Usage = ResourceUsage.Staging, BindFlags = BindFlags.None, CpuAccessFlags = CpuAccessFlags.Read })) { Device.ImmediateContext.CopyResource(texture, copy); var rect = Device.ImmediateContext.MapSubresource(copy, 0, MapMode.Read, SlimDX.Direct3D11.MapFlags.None); try { using (var b = new ReadAheadBinaryReader(rect.Data)) { var c = b.ReadSingle4D(); AcToolsLogging.Write("Values: " + c.JoinToString("; ") + "; format: " + texture.Description.Format); return(c.Any(x => x < 0f || x > 1f)); } } finally { Device.ImmediateContext.UnmapSubresource(texture, 0); } } } }
private static void Finish(Lut values, string data, int index, int line, ref double key, ref int started, ref int malformed) { if (started != -1) { if (double.IsNaN(key)) { if (malformed == -1) { AcToolsLogging.Write($@"Key is NaN at {line}"); malformed = line; } } else { if (FlexibleParser.TryParseDouble(data.Substring(started, index - started), out var value)) { values.Add(new LutPoint(key, value)); } else { if (malformed == -1) { AcToolsLogging.Write($@"Failed to parse key “{data.Substring(started, index - started)}” at {line}"); malformed = line; } } key = double.NaN; } started = -1; } else if (!double.IsNaN(key)) { key = double.NaN; } }
public void Dispose() { try { DisposeHelper.Dispose(ref _normalDepthState); DisposeHelper.Dispose(ref _shadowsDepthState); DisposeHelper.Dispose(ref _readOnlyDepthState); DisposeHelper.Dispose(ref _greaterReadOnlyDepthState); DisposeHelper.Dispose(ref _lessEqualDepthState); DisposeHelper.Dispose(ref _lessEqualReadOnlyDepthState); DisposeHelper.Dispose(ref _transparentBlendState); DisposeHelper.Dispose(ref _addBlendState); DisposeHelper.Dispose(ref _addState); DisposeHelper.Dispose(ref _maxState); DisposeHelper.Dispose(ref _minState); DisposeHelper.Dispose(ref _multiplyState); DisposeHelper.Dispose(ref _doubleSidedState); DisposeHelper.Dispose(ref _doubleSidedSmoothLinesState); DisposeHelper.Dispose(ref _invertedState); DisposeHelper.Dispose(ref _wireframeState); DisposeHelper.Dispose(ref _wireframeInvertedState); DisposeHelper.Dispose(ref _ambientShadowState); DisposeHelper.Dispose(ref _shadowsState); DisposeHelper.Dispose(ref _shadowsPointState); } catch (Exception e) { AcToolsLogging.Write(e); } }
public void Process(Pieces pieces, [NotNull] Stream stream) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } #if DEBUG AcToolsLogging.Write(pieces.CentralPiece); #endif var array = pieces.ToArray(); try { var textures = array.Select(LoadTexture).ToArray(); _effect.FxInputMaps.SetResourceArray(textures); _effect.FxTexMultiplier.Set(new Vector2(1f / _padding)); _effect.FxPaddingSize.Set(new Vector2(2f / (_padding - 1f))); Draw(); Texture2D.ToStream(DeviceContext, RenderBuffer, ImageFileFormat.Png, stream); } finally { foreach (var texture in array) { UnlockTexture(texture); } } }
private void UseEffect(Action <EffectSpecialPaintShop> fn, TargetResourceTexture tex) { if (_paintShopEffect == null) { _paintShopEffect = DeviceContextHolder.GetEffect <EffectSpecialPaintShop>(); var s = Stopwatch.StartNew(); _paintShopEffect.FxNoiseMap.SetResource(DeviceContextHolder.GetRandomTexture(OptionPaintShopRandomSize, OptionPaintShopRandomSize)); AcToolsLogging.Write($"Random texture: {s.Elapsed.TotalMilliseconds:F1} ms"); } using (DeviceContextHolder.SaveRenderTargetAndViewport()) { DeviceContextHolder.PrepareQuad(_paintShopEffect.LayoutPT); DeviceContext.Rasterizer.SetViewports(tex.Viewport); DeviceContext.OutputMerger.SetTargets(tex.TargetView); DeviceContext.ClearRenderTargetView(tex.TargetView, new Color4(0f, 0f, 0f, 0f)); DeviceContext.OutputMerger.BlendState = null; DeviceContext.OutputMerger.DepthStencilState = null; DeviceContext.Rasterizer.State = null; _paintShopEffect.FxNoiseMultipler.Set((float)Math.Max(tex.Width, tex.Height) / OptionPaintShopRandomSize); _paintShopEffect.FxSize.Set(new Vector4(tex.Width, tex.Height, 1f / tex.Width, 1f / tex.Height)); fn?.Invoke(_paintShopEffect); } }
private byte[] GetBytes([CanBeNull] PaintShopSource source) { if (source == null) { return(null); } if (!source.UseInput) { if (source.Data != null) { return(source.Data); } if (source.Name != null && MainSlot.Kn5?.TexturesData.ContainsKey(source.Name) == true) { return(MainSlot.Kn5.TexturesData[source.Name]); } if (source.Color != null) { using (var texture = DeviceContextHolder.CreateTexture(1, 1, (x, y) => source.Color.Value)) using (var stream = new MemoryStream()) { Texture2D.ToStream(DeviceContext, texture, ImageFileFormat.Dds, stream); return(stream.ToArray()); } } } AcToolsLogging.Write("Can’t get bytes: " + source); return(null); }
private static void SubscribeInner(KeyboardListener instance) { if (Subscribed.Contains(instance)) { return; } Subscribed.Add(instance); if (_hookHandle == 0) { // ReSharper disable once RedundantDelegateCreation _hookProc = new User32.HookProc(KeyboardHookProc); // var id = Kernel32.LoadLibrary("User32"); var id = Kernel32.GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName); var result = User32.SetWindowsHookEx(User32.WH_KEYBOARD_LL, _hookProc, id, 0); _hookHandle = result; AcToolsLogging.Write("Subscribed: " + result); if (result == 0) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } }
public IEnumerable <LapTimeEntry> Import(string sourceName) { var directory = new DirectoryInfo(Path.Combine(_sidekickDirectory, "personal_best")); if (!directory.Exists) { yield break; } foreach (var file in directory.GetFiles("*_pb.ini")) { TimeSpan time; var timeValue = 0L; try { if (file.Length > 1000 || !ReadPickle(file.FullName, out timeValue) || timeValue == 0) { continue; } time = TimeSpan.FromMilliseconds(timeValue); } catch (OverflowException e) { AcToolsLogging.Write($"Can’t read {file.Name}: {e.Message} (value: {timeValue})"); continue; } catch (Exception e) { AcToolsLogging.Write($"Can’t read {file.Name}: {e}"); continue; } if (TryToGuessCarAndTrack(file.FullName, out var carId, out var trackLayoutId)) { yield return(new LapTimeEntry(sourceName, carId, trackLayoutId, file.LastWriteTime, time)); } } }
public void Wrapper() { var rulesSet = Path.Combine(TestDir, "analyzer", "rules.txt"); var storage = Path.Combine(TestDir, "analyzer", "storage.data"); var ids = AcKunosContent.GetKunosCarIds(AcRoot).ToArray(); var wrapper = RulesWrapper.FromFile(AcRoot, rulesSet, storage, ids); wrapper.EnsureActual(); var d = ids.Where(x => Directory.Exists(FileUtils.GetCarDirectory(AcRoot, x))) .Select(x => new { Id = x, Data = DataWrapper.FromCarDirectory(AcRoot, x) }) .ToList(); var w = Stopwatch.StartNew(); var j = 0; foreach (var car in d) { foreach (var s in wrapper.FindSimular(car.Data, "aero", false, 0.85)) { AcToolsLogging.Write($"{car.Id} is similar to {s.CarId} by {s.Value * 100:F1}%"); j++; } } AcToolsLogging.Write($"Check time: {w.Elapsed.TotalMilliseconds / j:F2} ms"); }
public async Task LoadOverrideAsync([CanBeNull] IDeviceContextHolder holder, [CanBeNull] byte[] data) { var id = ++_overrideId; if (data == null) { Override = null; } else { try { var resource = await Task.Run(() => LoadSafe(holder?.Device, data)); if (id != _overrideId) { resource?.Dispose(); return; } Override = resource; } catch (Exception e) { if (id != _overrideId) { return; } AcToolsLogging.Write(e); Override = null; } } holder?.RaiseTexturesUpdated(); }
public Task RunAsync([CanBeNull] CarLodGeneratorExceptionCallback exceptionCallback, [CanBeNull] CarLodGeneratorResultCallback resultCallback, IProgress <CarLodGeneratorProgressUpdate> progress = null, CancellationToken cancellationToken = default) { return(Stages.Select(async(x, i) => { try { var generated = await GenerateLodStageAsync(i, x, CreateProgress(x.Id), cancellationToken).ConfigureAwait(false); if (generated != null) { resultCallback?.Invoke(x.Id, generated.Item1, generated.Item2); } } catch (Exception e) when(exceptionCallback != null) { if (!e.IsCancelled()) { AcToolsLogging.Write(e); exceptionCallback.Invoke(x.Id, e); } } }).WhenAll()); IProgress <double?> CreateProgress(string key) { return(progress == null ? null : new Progress <double?>(v => progress.Report(new CarLodGeneratorProgressUpdate { Key = key, Value = v }))); } }
public bool Apply(int steerLock, bool isReset, out int appliedValue) { appliedValue = Math.Min(Math.Max(steerLock, MinimumSteerLock), MaximumSteerLock); var packet = new CommandPacket { ReportId = ScReportId.Out, Command = ScCommand.SetTemporaryVariable, Value1 = isReset ? ScValue1.UnsetTemporarySteeringAngle : ScValue1.TemporarySteeringAngle, Value2 = (ushort)appliedValue }; var ptr = Marshal.AllocHGlobal(CommandPacket.Size); var data = new byte[60]; Marshal.StructureToPtr(packet, ptr, false); Marshal.Copy(ptr, data, 0, CommandPacket.Size); Marshal.FreeHGlobal(ptr); var result = HidDevices.Enumerate(0x16d0, 0x0d5a, 0x0d5f, 0x0d60, 0x0d61).Aggregate(false, (a, b) => { using (b) { AcToolsLogging.Write($"Set to {steerLock}: " + b.DevicePath); return(a | b.Write(data)); } }); return(result); }
public virtual IEnumerable <LapTimeEntry> Import(string sourceName) { var directory = new DirectoryInfo(Path.Combine(_sidekickDirectory, "personal_best")); if (!directory.Exists) { yield break; } foreach (var file in directory.GetFiles("*_pb.ini")) { long time; try { using (var stream = File.Open(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read)) using (var reader = new ReadAheadBinaryReader(stream)) { if (!ReadPickle(reader, out time) || time == 0) { continue; } } } catch (Exception e) { AcToolsLogging.Write($"Can’t read {file.Name}: {e}"); continue; } string carId, trackLayoutId; if (TryToGuessCarAndTrack(file.FullName, out carId, out trackLayoutId)) { yield return(new LapTimeEntry(sourceName, carId, trackLayoutId, file.LastWriteTime, TimeSpan.FromMilliseconds(time))); } } }
protected async void UpdateOverrideLater([NotNull] string filename) { if (CurrentDirectory == null) { return; } var local = FileUtils.TryToGetRelativePath(filename, CurrentDirectory)?.ToLowerInvariant(); if (string.IsNullOrEmpty(local)) { return; } if (_updateInProcess.Contains(local)) { return; } _updateInProcess.Add(local); try { await UpdateTexture(local).ConfigureAwait(false); } catch (Exception e) { AcToolsLogging.Write(e); } finally { _updateInProcess.Remove(local); } }
public static IRenderableObject Create(AiLane aiLane, float?fixedWidth) { // four vertices per sector const int verticesPerSector = 4; // actually, I think it’s 65535, but let’s not go there const int maxVertices = 30000; var aiPoints = aiLane.Points; var sectorsNumber = aiPoints.Length - 1; if (sectorsNumber < 1) { return(new InvisibleObject()); } if (sectorsNumber * verticesPerSector <= maxVertices) { return(Create(aiPoints, fixedWidth, 0, aiPoints.Length)); } var pointsPerObject = maxVertices / verticesPerSector + 1; var result = new RenderableList(); for (var i = 0; i < aiPoints.Length; i += pointsPerObject) { result.Add(Create(aiPoints, fixedWidth, i, Math.Min(i + pointsPerObject, aiPoints.Length))); } AcToolsLogging.Write("Objects: " + result.Count); return(result); }
public static LogiControllerPropertiesData Load([NotNull] string registryPath, [CanBeNull] string processFilename) { using (var regKey = Registry.CurrentUser.OpenSubKey(registryPath)) { object o = CreateNew(); if (regKey != null) { foreach (var f in typeof(LogiControllerPropertiesData).GetFields()) { f.SetValue(o, regKey.GetValue(f.Name).As(f.FieldType, f.GetValue(o))); } } else { AcToolsLogging.Write("Settings in registry not found"); } var result = (LogiControllerPropertiesData)o; if (processFilename != null) { result.ExtendWithPresets(processFilename); } return(result); } }
protected override void Initialize(IDeviceContextHolder contextHolder) { base.Initialize(contextHolder); var material = contextHolder.Get <SharedMaterials>().GetMaterial(OriginalNode.MaterialId); _material = material as ISkinnedMaterial; if (_material == null) { AcToolsLogging.Write("Error: ISkinnedMaterial required for Kn5SkinnedObject!"); material.Dispose(); _material = new InvisibleMaterial(); } _material.Initialize(contextHolder); var model = contextHolder.Get <IKn5Model>(); _bonesNodes = OriginalNode.Bones.Select(x => model.GetDummyByName(x.Name)).ToArray(); if (_debugMaterial != null && !_debugMaterialInitialized) { _debugMaterialInitialized = true; _debugMaterial.Initialize(contextHolder); } }
protected virtual async void UpdateSize() { if (!_updatedOnce) { _updatedOnce = true; AcToolsLogging.Write($"{Form.ClientSize.Width}×{Form.ClientSize.Height}"); Renderer.Width = Form.ClientSize.Width; Renderer.Height = Form.ClientSize.Height; return; } if (_updatingSize) { return; } _updatingSize = true; try { await Task.Yield(); AcToolsLogging.Write($"{Form.ClientSize.Width}×{Form.ClientSize.Height}"); Renderer.Width = Form.ClientSize.Width; Renderer.Height = Form.ClientSize.Height; } finally { _updatingSize = false; } }
public void SetDebugMode(IDeviceContextHolder holder, bool enabled) { if (enabled == (_debugMaterial != null)) { return; } if (enabled) { var material = holder.Get <SharedMaterials>().GetMaterial(new Tuple <object, uint>(BasicMaterials.DebugKey, OriginalNode.MaterialId)); _debugMaterial = material as ISkinnedMaterial; if (_debugMaterial == null) { AcToolsLogging.Write("Error: ISkinnedMaterial required for Kn5SkinnedObject!"); material.Dispose(); return; } if (IsInitialized) { _debugMaterial.Initialize(holder); _debugMaterialInitialized = true; } } else { _debugMaterialInitialized = false; DisposeHelper.Dispose(ref _debugMaterial); } }
public static IDisposable WatchFile(string filename, Action reloadAction) { var reloading = false; return(SetWatcher(Path.GetDirectoryName(filename), async s => { if (reloading || !FileUtils.ArePathsEqual(s, filename)) { return; } reloading = true; try { for (var i = 0; i < 3; i++) { try { await Task.Delay(300); reloadAction(); break; } catch (IOException e) { AcToolsLogging.Write(e); } } } finally { reloading = false; } })); }
public byte[] LoadTexture(string textureName, ReadAheadBinaryReader reader, int textureSize) { if (textureSize > 4e6) { AcToolsLogging.Write($"{textureName}: {(double)textureSize / 1024 / 1024:F1} MB"); } MemoryChunk.Bytes(textureSize).Execute(() => { var bytes = reader.ReadBytes(textureSize); // FromStream simply reads Stream to byte[] underneath, so we could just do it here in // a more controlled manner try { lock (_device) { if (OptionLoadView) { var view = ShaderResourceView.FromMemory(_device, bytes); // new ShaderResourceView(_device, texture); _ready[textureName] = new Tuple <Texture2D, ShaderResourceView>(null, view); } else { var texture = Texture2D.FromMemory(_device, bytes); var view = new ShaderResourceView(_device, texture); _ready[textureName] = new Tuple <Texture2D, ShaderResourceView>(texture, view); } } } catch (SEHException e) { AcToolsLogging.NonFatalErrorNotify("Can’t load texture", "Try again?", e); } }); return(null); }
private void ProcessConvertation([NotNull] Action action, [NotNull] Action disposal) { if (!_options.DelayedConvertation) { try { action.Invoke(); } finally { disposal.Invoke(); } return; } if (_convertationThreadPool == null) { _convertationThreadPool = new ThreadPool("Previews Convertation Thread", 4, ThreadPriority.BelowNormal); } Interlocked.Increment(ref _processingNow); _convertationThreadPool.QueueTask(() => { try { action.Invoke(); } catch (Exception e) { AcToolsLogging.Write(e); } finally { disposal.Invoke(); Interlocked.Decrement(ref _processingNow); } }); }
private static async Task WaitForExitAsyncDeeperFallback([NotNull] Process process, CancellationToken cancellationToken = default(CancellationToken)) { if (process == null) { throw new ArgumentNullException(nameof(process)); } AcToolsLogging.Write("Is there an issue?"); var processId = process.Id; while (true) { await Task.Delay(300, cancellationToken); if (cancellationToken.IsCancellationRequested) { return; } try { Process.GetProcessById(processId); } catch (ArgumentException) { return; } } }