public static DebugWindow get() { if(DebugWindow.instance == null) { GameObject go = new GameObject("DebugWindow"); DebugWindow.instance = go.AddComponent<DebugWindow>(); DebugWindow.instance.create(); DontDestroyOnLoad(go); } return(DebugWindow.instance); }
public override void DrawSettings() { if (ImGui.Button("Dump preloads")) { Directory.CreateDirectory(Path.Combine(DirectoryFullName, "Dumps")); var path = Path.Combine(DirectoryFullName, "Dumps", $"{GameController.Area.CurrentArea.Name}.txt"); DebugWindow.LogMsg(path); File.WriteAllLines(path, PreloadDebug); } if (ImGui.Button("Dump grouped preloads")) { var groupBy = PreloadDebug.OrderBy(x => x).GroupBy(x => x.IndexOf('/')); var serializeObject = JsonConvert.SerializeObject(groupBy, Formatting.Indented); var path = Path.Combine(DirectoryFullName, "Dumps", $"{GameController.Area.CurrentArea.Name} ({DateTime.Now}).txt"); File.WriteAllText(path, serializeObject); } if (ImGui.Button("Show all preloads")) { var groupBy = PreloadDebug.OrderBy(x => x).GroupBy(x => x.IndexOf('/')).ToList(); var result = new Dictionary <string, List <string> >(groupBy.Count); foreach (var gr in groupBy) { var g = gr.ToList(); if (gr.Key != -1) { var list = new List <string>(g.Count); result[g.First().Substring(0, gr.Key)] = list; foreach (var str in g) { list.Add(str); } } else { var list = new List <string>(g.Count); var key = gr.Key.ToString(); result[key] = list; foreach (var str in g) { list.Add(str); } } } groupBy = null; PreloadDebugAction = () => { foreach (var res in result) { if (ImGui.TreeNode(res.Key)) { foreach (var str in res.Value) { ImGui.Text(str); } ImGui.TreePop(); } } ImGui.Separator(); if (Alerts.Count > 0) { if (ImGui.TreeNode("DrawAlerts")) { foreach (var alert in DrawAlerts) { ImGui.TextColored((alert.FastColor?.Invoke() ?? alert.Color ?? Settings.DefaultTextColor).ToImguiVec4(), $"{alert.Text}"); } ImGui.TreePop(); } } ImGui.Text($"Area Change Count: {GameController.Game.AreaChangeCount}"); if (ImGui.Button("Close")) { PreloadDebugAction = null; } }; } base.DrawSettings(); }
public static dbwin.Console console() { return(DebugWindow.get().console); }
public override void Render() { /*if (RenderDebugInformation.Tick >= 500) * { * Error += RenderDebugInformation.Tick; * if (Error >= 5000) * { * LogError("Reloaded because works more than 5 sec", 5); * InitObjects(); * Error = 0; * } * }*/ if (Settings.ToggleWindow) { if (Settings.ToggleWindowKey.PressedOnce()) { Settings.ToggleWindowState = !Settings.ToggleWindowState; } if (!Settings.ToggleWindowState) { return; } } if (Settings.DebugHoverItem.PressedOnce()) { var ingameStateUiHover = GameController.IngameState.UIHover; var hoverItemIcon = GameController.IngameState.UIHover.AsObject <HoverItemIcon>(); if (ingameStateUiHover.Address != 0) { AddObjects(new{ Hover = ingameStateUiHover, HoverLikeItem = hoverItemIcon }, "Stored UIHover"); } } windowState = Settings.Enable; ImGui.Begin($"{Name}", ref windowState); if (Settings.Enable != windowState) { if (!Settings.ToggleWindow) { Settings.Enable.Value = windowState; } else { Settings.ToggleWindowState = windowState; } } if (ImGui.Button("Reload")) { InitObjects(); } ImGui.SameLine(); ImGui.PushItemWidth(200); if (ImGui.InputText("Filter", ref inputFilter, 128)) { } ImGui.PopItemWidth(); ImGui.SameLine(); ImGui.PushItemWidth(128); if (ImGui.BeginCombo("Rarity", selectedRarityString)) { for (var index = 0; index < Rarities.Count; index++) { var rarity = Rarities[index]; var isSelected = selectedRarityString == rarity; if (ImGui.Selectable(rarity, isSelected)) { selectedRarityString = rarity; selectedRarity = (MonsterRarity)index; } if (isSelected) { ImGui.SetItemDefaultFocus(); } } ImGui.EndCombo(); } ImGui.PopItemWidth(); ImGui.SameLine(); if (ImGui.Button("Debug around entities")) { var entites = GameController.Entities; var player = GameController.Player; var playerGridPos = player.GridPos; if (!selectedRarityString.Equals("All", StringComparison.Ordinal)) { if (inputFilter.Length == 0) { DebugEntities = entites.Where(x => x.Rarity == selectedRarity && x.GridPos.Distance(playerGridPos) < Settings.NearestEntsRange) .OrderBy(x => x.GridPos.Distance(playerGridPos)).ToList(); } else { DebugEntities = entites .Where(x => (x.Path.Contains(inputFilter) || x.Address.ToString("x").ToLower().Contains(inputFilter.ToLower())) && x.GetComponent <ObjectMagicProperties>()?.Rarity == selectedRarity && x.GridPos.Distance(playerGridPos) < Settings.NearestEntsRange) .OrderBy(x => x.GridPos.Distance(playerGridPos)).ToList(); } } else { if (inputFilter.Length == 0) { DebugEntities = entites.Where(x => x.GridPos.Distance(playerGridPos) < Settings.NearestEntsRange) .OrderBy(x => x.GridPos.Distance(playerGridPos)).ToList(); } else { DebugEntities = entites .Where(x => (x.Path.Contains(inputFilter) || x.Address.ToString("x").ToLower().Contains(inputFilter.ToLower())) && x.GridPos.Distance(playerGridPos) < Settings.NearestEntsRange) .OrderBy(x => x.GridPos.Distance(playerGridPos)).ToList(); } } } ImGui.SameLine(); ImGui.PushItemWidth(128); if (ImGui.InputText("CheckAddressIsGuiObject", ref guiObjAddr, 128)) { if (long.TryParse(guiObjAddr, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out var objAddr)) { var queue = new Queue <Element>(); queue.Enqueue(GameController.Game.IngameState.UIRoot); var found = false; while (queue.Count > 0) { var element = queue.Dequeue(); if (element.Address == objAddr) { var indexPath = new List <int>(); var iterator = element; while (iterator != null && iterator.Address != 0) { if (iterator.Parent != null && iterator.Parent.Address != 0) { indexPath.Add(iterator.Parent.Children.ToList().FindIndex(x => x.Address == iterator.Address)); } iterator = iterator.Parent; } indexPath.Reverse(); LogMessage("IS gui element!" + $"Path from root: [{string.Join(", ", indexPath)}]", 3); found = true; break; } foreach (var elementChild in element.Children) { queue.Enqueue(elementChild); } } if (!found) { LogMessage("NOT a gui element!", 3); } } } foreach (var o in objects) { if (ImGui.TreeNode($"{o.Key}##{_version}")) { ImGui.Indent(); try { Debug(o.Value); } catch (Exception e) { DebugWindow.LogError($"{Name} -> {e}"); } finally { ImGui.Unindent(); ImGui.TreePop(); } } } if (ImGui.TreeNode("UIHover")) { ImGui.Indent(); try { Debug(GameController.IngameState.UIHover); } catch (Exception e) { DebugWindow.LogError($"UIHover -> {e}"); } finally { ImGui.Unindent(); ImGui.TreePop(); } } if (ImGui.TreeNode("UIHover as Item")) { ImGui.Indent(); try { Debug(GameController.IngameState.UIHover.AsObject <HoverItemIcon>()); } catch (Exception e) { DebugWindow.LogError($"UIHover -> {e}"); } finally { ImGui.Unindent(); ImGui.TreePop(); } } if (ImGui.TreeNode("Only visible InGameUi")) { ImGui.Indent(); var os = GameController.IngameState.IngameUi.Children.Where(x => x.IsVisibleLocal); var index = 0; foreach (var el in os) { try { if (ImGui.TreeNode($"{el.Address:X} - {el.X}:{el.Y},{el.Width}:{el.Height}##{el.GetHashCode()}")) { var keyForOffset = $"{el.Address}{el.GetHashCode()}"; if (OffsetFinder.TryGetValue(keyForOffset, out var offset)) { ImGui.Text($"Offset: {offset:X}"); } else { var IngameUi = GameController.IngameState.IngameUi; var pointers = IngameUi.M.ReadPointersArray(IngameUi.Address, IngameUi.Address + 10000); for (var i = 0; i < pointers.Count; i++) { var p = pointers[i]; if (p == el.Address) { OffsetFinder[keyForOffset] = i * 0x8; } } } Debug(el); ImGui.TreePop(); } if (ImGui.IsItemHovered()) { var clientRectCache = el.GetClientRectCache; Graphics.DrawFrame(clientRectCache, ColorSwaper.Value, 1); foreach (var element in el.Children) { clientRectCache = element.GetClientRectCache; Graphics.DrawFrame(clientRectCache, ColorSwaper.Value, 1); } } index++; } catch (Exception e) { DebugWindow.LogError($"UIHover -> {e}"); } } ImGui.Unindent(); ImGui.TreePop(); } if (DebugEntities.Count > 0 && ImGui.TreeNode($"Entities {DebugEntities.Count}")) { var camera = GameController.IngameState.Camera; for (var index = 0; index < DebugEntities.Count; index++) { var debugEntity = DebugEntities[index]; var worldtoscreen = camera.WorldToScreen(debugEntity.Pos); Graphics.DrawText($"{index}", worldtoscreen); if (ImGui.TreeNode($"[{index}] {debugEntity}")) { Debug(debugEntity); ImGui.TreePop(); } var borderColor = Color.Black; if (ImGui.IsItemHovered()) { borderColor = Color.DarkSlateGray; } Graphics.DrawBox(worldtoscreen.TranslateToNum(-9, -9), worldtoscreen.TranslateToNum(18, 18), borderColor); } } ImGui.End(); }
private void InitializeApplication(StartupEventArgs e) { #region DEBUG初始化 //debug LogHandler = new LogHandler(true); AggregateExceptionCatched += (a, b) => LogHandler.AppendFatal(b.AggregateException); if (e.Args.Contains("-debug")) { DebugWindow debugWindow = new DebugWindow(); debugWindow.Show(); LogHandler.OnLog += (s, log) => debugWindow?.AppendLog(s, log); } #endregion Config = new ConfigHandler(); #region DEBUG初始化(基于配置文件) if (Config.MainConfig.Launcher.Debug && !e.Args.Contains("-debug")) { DebugWindow debugWindow = new DebugWindow(); debugWindow.Show(); LogHandler.OnLog += (s, log) => debugWindow?.AppendLog(s, log); } #endregion #region Nsiso反馈API初始化 #if DEBUG NsisoAPIHandler = new NsisoLauncherCore.Net.PhalAPI.APIHandler(true); #else NsisoAPIHandler = new NsisoLauncherCore.Net.PhalAPI.APIHandler(Config.MainConfig.Launcher.NoTracking); #endif #endregion #region 数据初始化 Config.Environment env = Config.MainConfig.Environment; JavaList = Java.GetJavaList(); //设置版本路径 string gameroot = null; switch (env.GamePathType) { case GameDirEnum.ROOT: gameroot = Path.GetFullPath(".minecraft"); break; case GameDirEnum.APPDATA: gameroot = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\.minecraft"; break; case GameDirEnum.PROGRAMFILES: gameroot = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles) + "\\.minecraft"; break; case GameDirEnum.CUSTOM: gameroot = env.GamePath + "\\.minecraft"; break; default: throw new ArgumentException("判断游戏目录类型时出现异常,请检查配置文件中GamePathType节点"); } LogHandler.AppendInfo("核心初始化->游戏根目录(默认则为空):" + gameroot); //设置JAVA Java java = null; if (env.AutoJava) { java = Java.GetSuitableJava(JavaList); } else { java = JavaList.Find(x => x.Path == env.JavaPath); if (java == null) { java = Java.GetJavaInfo(env.JavaPath); } } if (java != null) { env.JavaPath = java.Path; LogHandler.AppendInfo("核心初始化->Java路径:" + java.Path); LogHandler.AppendInfo("核心初始化->Java版本:" + java.Version); LogHandler.AppendInfo("核心初始化->Java位数:" + java.Arch); } else { LogHandler.AppendWarn("核心初始化失败,当前电脑未匹配到JAVA"); } //设置版本独立 bool verIso = Config.MainConfig.Environment.VersionIsolation; #endregion #region 启动核心初始化 Handler = new LaunchHandler(gameroot, java, verIso); Handler.GameLog += (s, log) => LogHandler.AppendLog(s, new Log() { LogLevel = LogLevel.GAME, Message = log }); Handler.LaunchLog += (s, log) => LogHandler.AppendLog(s, log); #endregion #region 载核心初始化 ServicePointManager.DefaultConnectionLimit = 10; Download downloadCfg = Config.MainConfig.Download; Downloader = new MultiThreadDownloader(); if (!string.IsNullOrWhiteSpace(downloadCfg.DownloadProxyAddress)) { WebProxy proxy = new WebProxy(downloadCfg.DownloadProxyAddress, downloadCfg.DownloadProxyPort); if (!string.IsNullOrWhiteSpace(downloadCfg.ProxyUserName)) { NetworkCredential credential = new NetworkCredential(downloadCfg.ProxyUserName, downloadCfg.ProxyUserPassword); proxy.Credentials = credential; } Downloader.Proxy = proxy; } Downloader.ProcessorSize = App.Config.MainConfig.Download.DownloadThreadsSize; Downloader.CheckFileHash = App.Config.MainConfig.Download.CheckDownloadFileHash; Downloader.DownloadLog += (s, log) => LogHandler?.AppendLog(s, log); #endregion #region 自定义主题初始化 var custom = Config.MainConfig.Customize; if (!string.IsNullOrWhiteSpace(custom.AccentColor) && !string.IsNullOrWhiteSpace(custom.AppThme)) { LogHandler.AppendInfo("自定义->更改主题颜色:" + custom.AccentColor); LogHandler.AppendInfo("自定义->更改主题:" + custom.AppThme); ThemeManager.ChangeAppStyle(Current, ThemeManager.GetAccent(custom.AccentColor), ThemeManager.GetAppTheme(custom.AppThme)); } #endregion }
protected override void OnStartup(StartupEventArgs e) { DispatcherUnhandledException += (sender, ex) => { _logger.Error("DispatcherUnhandledException"); ShowError(ex.Exception); ex.Handled = true; }; AppDomain.CurrentDomain.UnhandledException += (sender, ex) => { _logger.Error("UnhandledException"); ShowError(ex.ExceptionObject as Exception ?? new ApplicationException($"{nameof(AppDomain.UnhandledException)}; {nameof(sender)}: {sender?.GetType()}; {nameof(ex.ExceptionObject)}: {ex.ExceptionObject?.GetType()}")); }; TaskScheduler.UnobservedTaskException += (sender, ex) => { _logger.Error("UnobservedTaskException"); ShowError(ex.Exception); ex.SetObserved(); }; try { const string mutexName = "Shmambilight_Mutex"; if (Mutex.TryOpenExisting(mutexName, out _)) { Shutdown(-2); return; } _mutex = new Mutex(true, mutexName); var mainViewModel = new MainViewModel(); mainViewModel.Start(); _debugWindow = new DebugWindow { DataContext = mainViewModel }; var notifyIcon = new NotifyIcon { Icon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location), Visible = true }; _debugWindow.IsVisibleChanged += (sender, args) => mainViewModel.IsDebug = _debugWindow.IsVisible; notifyIcon.DoubleClick += (sender, args) => { if (_debugWindow.IsVisible) { _debugWindow.Hide(); } else { _debugWindow.Show(); } }; _debugWindow.Closing += (sender, args) => { if (!mainViewModel.IsExiting) { mainViewModel.IsExiting = true; args.Cancel = true; _debugWindow.Hide(); Task.Run(() => { mainViewModel.Stop(); _debugWindow.Dispatcher?.Invoke(() => _debugWindow.Close()); }); } }; } catch (Exception exception) { ShowError(new ApplicationException("Startup failed", exception)); Shutdown(-1); } }
private bool InitPlugin(IPlugin plugin) { // lock (initLoadLocker) { try { if (plugin._Settings == null) { DebugWindow.LogError($"Cant load plugin ({plugin.Name}) because settings is null."); plugin._SaveSettings(); return(false); } if (plugin.Initialized) { return(true); } plugin._Settings.Enable.OnValueChanged += (obj, value) => { if (plugin.Initialized) { if (value) { plugin.AreaChange(_gameController.Area.CurrentArea); } else { return; } } if (value) { plugin.Initialized = plugin.Initialise(); if (plugin.Initialized) { plugin.AreaChange(_gameController.Area.CurrentArea); } } if (!plugin.Initialized) { plugin._Settings.Enable = new ToggleNode(false); } }; if (plugin._Settings.Enable) { if (plugin.Initialized) { return(true); } plugin.Initialized = plugin.Initialise(); if (PluginLoadTime.TryGetValue(plugin.DirectoryFullName, out var sw)) { DebugWindow.LogMsg($"{plugin.Name} loaded in {sw.Elapsed.TotalMilliseconds} ms.", 2); } else { DebugWindow.LogError($"{plugin.Name} problem with load timer."); } } } catch (Exception ex) { DebugWindow.LogError($"Plugin {plugin.Name} error init {ex}", 5); Logger.Log.Error($"Plugin {plugin.Name} error init {ex}"); return(false); } return(true); } }
private void BtnDebugWindow_OnClick(object sender, RoutedEventArgs e) { var debugWindow = new DebugWindow(); debugWindow.Show(); }
private static bool ProcessCommand(BaseFilter newFilter, string command) { command = command.Trim(); if (command.Contains(PARAMETER_AFFINITYACTIVE)) { var affinityActiveCommand = new AffinityActiveFilter { BAffinityActive = command[0] != SYMBOL_NOT }; newFilter.Filters.Add(affinityActiveCommand); return(true); } if (command.Contains(PARAMETER_IGNOREAFFINITY)) { var affinityIgnoreCommand = new AffinityIgnoreFilter { BAffinityIgnore = command[0] != SYMBOL_NOT }; newFilter.Filters.Add(affinityIgnoreCommand); return(true); } if (command.Contains(PARAMETER_IDENTIFIED)) { var identCommand = new IdentifiedItemFilter { BIdentified = command[0] != SYMBOL_NOT }; newFilter.Filters.Add(identCommand); return(true); } if (command.Contains(PARAMETER_ISCORRUPTED)) { var corruptedCommand = new CorruptedItemFilter { BCorrupted = command[0] != SYMBOL_NOT }; newFilter.Filters.Add(corruptedCommand); return(true); } if (command.Contains(PARAMETER_ISELDER)) { var elderCommand = new ElderItemFiler { isElder = command[0] != SYMBOL_NOT }; newFilter.Filters.Add(elderCommand); return(true); } if (command.Contains(PARAMETER_ISSHAPER)) { var shaperCommand = new ShaperItemFilter { isShaper = command[0] != SYMBOL_NOT }; newFilter.Filters.Add(shaperCommand); return(true); } if (command.Contains(PARAMETER_ISCRUSADER)) { var crusaderCommand = new CrusaderItemFilter { isCrusader = command[0] != SYMBOL_NOT }; newFilter.Filters.Add(crusaderCommand); return(true); } if (command.Contains(PARAMETER_ISHUNTER)) { var hunterCommand = new HunterItemFilter { isHunter = command[0] != SYMBOL_NOT }; newFilter.Filters.Add(hunterCommand); return(true); } if (command.Contains(PARAMETER_ISREDEEMER)) { var redeemerCommand = new RedeemerItemFilter { isRedeemer = command[0] != SYMBOL_NOT }; newFilter.Filters.Add(redeemerCommand); return(true); } if (command.Contains(PARAMETER_ISWARLORD)) { var warordCommand = new WarlordItemFilter { isWarlord = command[0] != SYMBOL_NOT }; newFilter.Filters.Add(warordCommand); return(true); } if (command.Contains(PARAMETER_ISINFLUENCED)) { var influencedCommand = new AnyInfluenceItemFilter { isInfluenced = command[0] != SYMBOL_NOT }; newFilter.Filters.Add(influencedCommand); return(true); } if (command.Contains(PARAMETER_ISBLIGHTEDMAP)) { var blightedMapCommand = new BlightedMapFilter { isBlightMap = command[0] != SYMBOL_NOT }; newFilter.Filters.Add(blightedMapCommand); return(true); } if (command.Contains(PARAMETER_ISELDERGUARDIANMAP)) { var elderGuardianMapCommand = new ElderGuardianMapFilter { isElderGuardianMap = command[0] != SYMBOL_NOT }; newFilter.Filters.Add(elderGuardianMapCommand); return(true); } string parameter; string operation; string value; if (!ParseCommand(command, out parameter, out operation, out value)) { DebugWindow.LogMsg($"Unknown operation: {command}", 5, Color.Red); return(false); } var stringComp = new FilterParameterCompare { CompareString = value }; switch (parameter.ToLower()) { case PARAMETER_CLASSNAME: stringComp.StringParameter = data => data.ClassName; break; case PARAMETER_BASENAME: stringComp.StringParameter = data => data.BaseName; break; case PARAMETER_NAME: stringComp.StringParameter = data => data.Name; break; case PARAMETER_PATH: stringComp.StringParameter = data => data.Path; break; case PARAMETER_DESCRIPTION: stringComp.StringParameter = data => data.Description; break; case PARAMETER_RARITY: stringComp.StringParameter = data => data.Rarity.ToString(); break; case PARAMETER_QUALITY: stringComp.IntParameter = data => data.ItemQuality; stringComp.CompareInt = int.Parse(value); stringComp.StringParameter = data => data.ItemQuality.ToString(); break; case PARAMETER_MapTier: stringComp.IntParameter = data => data.MapTier; stringComp.CompareInt = int.Parse(value); stringComp.StringParameter = data => data.MapTier.ToString(); break; case PARAMETER_ILVL: stringComp.IntParameter = data => data.ItemLevel; stringComp.CompareInt = int.Parse(value); stringComp.StringParameter = data => data.ItemLevel.ToString(); break; case PARAMETER_NUMBER_OF_SOCKETS: stringComp.IntParameter = data => data.NumberOfSockets; stringComp.CompareInt = int.Parse(value); stringComp.StringParameter = data => data.NumberOfSockets.ToString(); break; case PARAMETER_LARGEST_LINK_SIZE: stringComp.IntParameter = data => data.LargestLinkSize; stringComp.CompareInt = int.Parse(value); stringComp.StringParameter = data => data.LargestLinkSize.ToString(); break; case PARAMETER_VEILED: stringComp.IntParameter = data => data.Veiled; stringComp.CompareInt = int.Parse(value); stringComp.StringParameter = data => data.Veiled.ToString(); break; case PARAMETER_FRACTUREDMODS: stringComp.IntParameter = data => data.Fractured; stringComp.CompareInt = int.Parse(value); stringComp.StringParameter = data => data.Fractured.ToString(); break; case PARAMETER_DELIRIUMREWARDSAMOUNT: stringComp.IntParameter = data => data.DeliriumStacks; stringComp.CompareInt = int.Parse(value); stringComp.StringParameter = data => data.DeliriumStacks.ToString(); break; case PARAMETER_SCOURGETIER: stringComp.IntParameter = data => data.ScourgeTier; stringComp.CompareInt = int.Parse(value); stringComp.StringParameter = data => data.ScourgeTier.ToString(); break; case PARAMETER_SKILLGEMLEVEL: stringComp.IntParameter = data => data.SkillGemLevel; stringComp.CompareInt = int.Parse(value); stringComp.StringParameter = data => data.SkillGemLevel.ToString(); break; //case PARAMETER_METAMORPHREWARDSAMOUNT: // stringComp.IntParameter = data => data.MetamorphSampleRewardsAmount; // stringComp.CompareInt = int.Parse(value); // stringComp.StringParameter = data => data.MetamorphSampleRewardsAmount.ToString(); // break; //case PARAMETER_METAMORPHGOODREWARDSAMOUNT: // stringComp.IntParameter = data => data.MetamorphSampleGoodRewardsAmount; // stringComp.CompareInt = int.Parse(value); // stringComp.StringParameter = data => data.MetamorphSampleGoodRewardsAmount.ToString(); // break; //case PARAMETER_METAMORPHBADREWARDSAMOUNT: // stringComp.IntParameter = data => data.MetamorphSampleBadRewardsAmount; // stringComp.CompareInt = int.Parse(value); // stringComp.StringParameter = data => data.MetamorphSampleBadRewardsAmount.ToString(); // break; default: DebugWindow.LogMsg($"Filter parser: Parameter is not defined in code: {parameter}", 10); return(false); } try { switch (operation.ToLower()) { case OPERATION_EQUALITY: stringComp.CompDeleg = data => stringComp?.StringParameter(data)?.Equals(stringComp?.CompareString) ?? false; break; case OPERATION_NONEQUALITY: stringComp.CompDeleg = data => (!stringComp?.StringParameter(data)?.Equals(stringComp?.CompareString)) ?? false; break; case OPERATION_CONTAINS: stringComp.CompDeleg = data => stringComp?.StringParameter(data)?.Contains(stringComp?.CompareString) ?? false; break; case OPERATION_NOTCONTAINS: stringComp.CompDeleg = data => (!stringComp?.StringParameter(data)?.Contains(stringComp?.CompareString)) ?? false; break; case OPERATION_BIGGER: if (stringComp.IntParameter == null) { DebugWindow.LogMsg( $"Filter parser error: Can't compare string parameter with {OPERATION_BIGGER} (numerical) operation. Statement: {command}", 10); return(false); } stringComp.CompDeleg = data => stringComp.IntParameter(data) > stringComp.CompareInt; break; case OPERATION_LESS: if (stringComp.IntParameter == null) { DebugWindow.LogMsg( $"Filter parser error: Can't compare string parameter with {OPERATION_LESS} (numerical) operation. Statement: {command}", 10); return(false); } stringComp.CompDeleg = data => stringComp.IntParameter(data) < stringComp.CompareInt; break; case OPERATION_LESSEQUAL: if (stringComp.IntParameter == null) { DebugWindow.LogMsg( $"Filter parser error: Can't compare string parameter with {OPERATION_LESSEQUAL} (numerical) operation. Statement: {command}", 10); return(false); } stringComp.CompDeleg = data => stringComp.IntParameter(data) <= stringComp.CompareInt; break; case OPERATION_BIGGERQUAL: if (stringComp.IntParameter == null) { DebugWindow.LogMsg( $"Filter parser error: Can't compare string parameter with {OPERATION_BIGGERQUAL} (numerical) operation. Statement: {command}", 10); return(false); } stringComp.CompDeleg = data => stringComp.IntParameter(data) >= stringComp.CompareInt; break; default: DebugWindow.LogMsg($"Filter parser: Operation is not defined in code: {operation}", 10); return(false); } } catch (Exception ex) { } newFilter.Filters.Add(stringComp); return(true); }
private static bool ProcessCommand(BaseFilter newFilter, string command) { command = command.Trim(); if (command.Contains(PARAMETER_IDENTIFIED)) { var identCommand = new IdentifiedItemFilter { BIdentified = command[0] != CYMBOL_NOT }; newFilter.Filters.Add(identCommand); return(true); } if (command.Contains(PARAMETER_ISELDER)) { var elderCommand = new ElderItemFiler { isElder = command[0] != CYMBOL_NOT }; newFilter.Filters.Add(elderCommand); return(true); } if (command.Contains(PARAMETER_ISSHAPER)) { var shaperCommand = new ShaperItemFiler { isShaper = command[0] != CYMBOL_NOT }; newFilter.Filters.Add(shaperCommand); return(true); } if (command.Contains(PARAMETER_ISFRACTURED)) { var synthesisCommand = new FracturedItemFiler { isFractured = command[0] != CYMBOL_NOT }; newFilter.Filters.Add(synthesisCommand); return(true); } string parameter; string operation; string value; if (!ParseCommand(command, out parameter, out operation, out value)) { DebugWindow.LogMsg("Filter parser: Can't parse filter part: " + command, 5); return(false); } var stringComp = new FilterParameterCompare { CompareString = value }; switch (parameter.ToLower()) { case PARAMETER_CLASSNAME: stringComp.StringParameter = data => data.ClassName; break; case PARAMETER_BASENAME: stringComp.StringParameter = data => data.BaseName; break; case PARAMETER_PATH: stringComp.StringParameter = data => data.Path; break; case PARAMETER_RARITY: stringComp.StringParameter = data => data.Rarity.ToString(); break; case PARAMETER_QUALITY: stringComp.IntParameter = data => data.ItemQuality; stringComp.CompareInt = int.Parse(value); stringComp.StringParameter = data => data.ItemQuality.ToString(); break; case PARAMETER_MapTier: stringComp.IntParameter = data => data.MapTier; stringComp.CompareInt = int.Parse(value); stringComp.StringParameter = data => data.MapTier.ToString(); break; case PARAMETER_ILVL: stringComp.IntParameter = data => data.ItemLevel; stringComp.CompareInt = int.Parse(value); stringComp.StringParameter = data => data.ItemLevel.ToString(); break; default: DebugWindow.LogMsg($"Filter parser: Parameter is not defined in code: {parameter}", 10); return(false); } switch (operation.ToLower()) { case OPERATION_EQUALITY: stringComp.CompDeleg = data => stringComp.StringParameter(data).Equals(stringComp.CompareString); break; case OPERATION_NONEQUALITY: stringComp.CompDeleg = data => !stringComp.StringParameter(data).Equals(stringComp.CompareString); break; case OPERATION_CONTAINS: stringComp.CompDeleg = data => stringComp.StringParameter(data).Contains(stringComp.CompareString); break; case OPERATION_NOTCONTAINS: stringComp.CompDeleg = data => !stringComp.StringParameter(data).Contains(stringComp.CompareString); break; case OPERATION_BIGGER: if (stringComp.IntParameter == null) { DebugWindow.LogMsg( $"Filter parser error: Can't compare string parameter with {OPERATION_BIGGER} (numerical) operation. Statement: {command}", 10); return(false); } stringComp.CompDeleg = data => stringComp.IntParameter(data) > stringComp.CompareInt; break; case OPERATION_LESS: if (stringComp.IntParameter == null) { DebugWindow.LogMsg( $"Filter parser error: Can't compare string parameter with {OPERATION_LESS} (numerical) operation. Statement: {command}", 10); return(false); } stringComp.CompDeleg = data => stringComp.IntParameter(data) < stringComp.CompareInt; break; case OPERATION_LESSEQUAL: if (stringComp.IntParameter == null) { DebugWindow.LogMsg( $"Filter parser error: Can't compare string parameter with {OPERATION_LESSEQUAL} (numerical) operation. Statement: {command}", 10); return(false); } stringComp.CompDeleg = data => stringComp.IntParameter(data) <= stringComp.CompareInt; break; case OPERATION_BIGGERQUAL: if (stringComp.IntParameter == null) { DebugWindow.LogMsg( $"Filter parser error: Can't compare string parameter with {OPERATION_BIGGERQUAL} (numerical) operation. Statement: {command}", 10); return(false); } stringComp.CompDeleg = data => stringComp.IntParameter(data) >= stringComp.CompareInt; break; default: DebugWindow.LogMsg($"Filter parser: Operation is not defined in code: {operation}", 10); return(false); } newFilter.Filters.Add(stringComp); return(true); }
public CustomItem(LabelOnGround item, FilesContainer fs, float distance) { LabelOnGround = item; Distance = distance; var itemItemOnGround = item.ItemOnGround; var worldItem = itemItemOnGround?.GetComponent <WorldItem>(); if (worldItem == null) { return; } var groundItem = worldItem.ItemEntity; GroundItem = groundItem; Path = groundItem?.Path; if (GroundItem == null) { return; } if (Path != null && Path.Length < 1) { DebugWindow.LogMsg($"World: {worldItem.Address:X} P: {Path}", 2); DebugWindow.LogMsg($"Ground: {GroundItem.Address:X} P {Path}", 2); return; } IsTargeted = () => { var isTargeted = itemItemOnGround.GetComponent <Targetable>()?.isTargeted; return(isTargeted != null && (bool)isTargeted); }; var baseItemType = fs.BaseItemTypes.Translate(Path); if (baseItemType != null) { ClassName = baseItemType.ClassName; BaseName = baseItemType.BaseName; Width = baseItemType.Width; Height = baseItemType.Height; } var WeaponClass = new List <string> { "One Hand Mace", "Two Hand Mace", "One Hand Axe", "Two Hand Axe", "One Hand Sword", "Two Hand Sword", "Thrusting One Hand Sword", "Bow", "Claw", "Dagger", "Sceptre", "Staff", "Wand" }; if (GroundItem.HasComponent <Quality>()) { var quality = GroundItem.GetComponent <Quality>(); Quality = quality.ItemQuality; } if (GroundItem.HasComponent <Base>()) { var @base = GroundItem.GetComponent <Base>(); IsElder = @base.isElder; IsShaper = @base.isShaper; } if (GroundItem.HasComponent <Mods>()) { var mods = GroundItem.GetComponent <Mods>(); Rarity = mods.ItemRarity; IsIdentified = mods.Identified; ItemLevel = mods.ItemLevel; IsFractured = mods.HaveFractured; } if (GroundItem.HasComponent <Sockets>()) { var sockets = GroundItem.GetComponent <Sockets>(); IsRGB = sockets.IsRGB; Sockets = sockets.NumberOfSockets; LargestLink = sockets.LargestLinkSize; } if (WeaponClass.Any(ClassName.Equals)) { IsWeapon = true; } MapTier = GroundItem.HasComponent <Map>() ? GroundItem.GetComponent <Map>().Tier : 0; IsValid = true; }
private List <PluginWrapper> UpdateSinglePlugin( SinglePluginUpdateSettings plugin, PluginSourceDownloader pluginSourceDownloader, PluginFilter pluginFilter, IPluginCompiler pluginCompiler, string rootDirectory, PluginLoader pluginLoader ) { var sourcePluginDirectory = new DirectoryInfo(Path.Combine(SourcePluginsDirectory, plugin.Name?.Value)); var compiledPluginDirectory = new DirectoryInfo(Path.Combine(CompiledPluginsDirectory, plugin.Name?.Value)); try { pluginSourceDownloader.Update(plugin); if (!pluginFilter.ShouldCompilePlugin(sourcePluginDirectory, compiledPluginDirectory)) { return(null); } var dependencyTasks = PluginCopyFiles.CopyDependencies(sourcePluginDirectory, compiledPluginDirectory); var settingsTasks = PluginCopyFiles.CopySettings(sourcePluginDirectory, compiledPluginDirectory); var staticFilesTasks = PluginCopyFiles.CopyStaticFiles(sourcePluginDirectory, compiledPluginDirectory); var txtJsonFilesTask = PluginCopyFiles.CopyTxtAndJsonFromRoot(sourcePluginDirectory, compiledPluginDirectory); var txtJsonDefaultFilesTask = PluginCopyFiles.CopyTxtAndJsonDefaultFiles(sourcePluginDirectory, compiledPluginDirectory); if (dependencyTasks != null) { Task.WaitAll(dependencyTasks.ToArray()); } var csProjFiles = sourcePluginDirectory .GetFiles("*.csproj", SearchOption.AllDirectories) .Where(f => f.Extension == ".csproj"); foreach (var csProjFile in csProjFiles) { pluginCompiler.CompilePlugin( csProjFile, compiledPluginDirectory.FullName, new DirectoryInfo(rootDirectory) ); } var remainingTasks = new List <Task>(); remainingTasks.AddRange(settingsTasks); remainingTasks.AddRange(staticFilesTasks); remainingTasks.AddRange(txtJsonFilesTask); remainingTasks.AddRange(txtJsonDefaultFilesTask); if (remainingTasks != null) { Task.WaitAll(remainingTasks.ToArray()); } } catch (Exception e) { DebugWindow.LogError($"PluginUpdater -> {plugin} UpdateSinglePlugin failed."); DebugWindow.LogDebug($"PluginUpdater -> {e.Message}"); } var pluginWrapper = pluginLoader.Load(compiledPluginDirectory); return(pluginWrapper); }
public bool Initialize(SystemConfiguration configuration, IntPtr windowHandle) { try { #region Initialize System // Create the Direct3D object. D3D = new DX11(); // Initialize the Direct3D object. if (!D3D.Initialize(configuration, windowHandle)) { MessageBox.Show("Could not initialize Direct3D", "Error", MessageBoxButtons.OK); return(false); } #endregion #region Initialize Camera // Create the camera object Camera = new Camera(); #endregion #region Initialize Models // Create the model class. Model = new Model(); // Initialize the model object. if (!Model.Initialize(D3D.Device, "square.txt", new[] { "dirt01.dds" })) { MessageBox.Show("Could not initialize the model object", "Error", MessageBoxButtons.OK); return(false); } // Create the model class. Model2 = new Model(); // Initialize the model object. if (!Model2.Initialize(D3D.Device, "square.txt", new[] { "stone01.dds" })) { MessageBox.Show("Could not initialize the model object", "Error", MessageBoxButtons.OK); return(false); } #region Debug Model if (SystemConfiguration.DebugWindowOn) { // Create the render to texture object. RenderTexture = new RenderTexture(); // Initialize the render to texture object. if (!RenderTexture.Initialize(D3D.Device, configuration)) { return(false); } // Create the debug window object. DebugWindow = new DebugWindow(); // Initialize the debug window object. if (!DebugWindow.Initialize(D3D.Device, configuration.Width, configuration.Height, 100, 100 * configuration.Height / configuration.Width)) { MessageBox.Show("Could not initialize the debug window object.", "Error", MessageBoxButtons.OK); return(false); } // Create the texture shader object. TextureShader = new TextureShader(); // Initialize the texture shader object. if (!TextureShader.Initialize(D3D.Device, windowHandle)) { MessageBox.Show("Could not initialize the texture shader object.", "Error", MessageBoxButtons.OK); return(false); } } #endregion #endregion #region Initialize Textures // Create the shader object. TextureShader = new TextureShader(); // Initialize the shader object. if (!TextureShader.Initialize(D3D.Device, windowHandle)) { MessageBox.Show("Could not initialize the shader", "Error", MessageBoxButtons.OK); return(false); } // Create the shader object. TransparentShader = new TransparentShader(); // Initialize the shader object. if (!TransparentShader.Initialize(D3D.Device, windowHandle)) { MessageBox.Show("Could not initialize the shader", "Error", MessageBoxButtons.OK); return(false); } #endregion #region Initialize Data // Create the light object. Light = new Light(); // Initialize the light object. Light.SetAmbientColor(0.15f, 0.15f, 0.15f, 1.0f); Light.SetDiffuseColor(1, 1, 1, 1f); Light.SetDirection(0, 0, 1); Light.SetSpecularColor(0, 1, 1, 1); Light.SetSpecularPower(16); #endregion return(true); } catch (Exception ex) { MessageBox.Show("Could not initialize Direct3D\nError is '" + ex.Message + "'"); return(false); } }
public PluginManager(GameController gameController, Graphics graphics, MultiThreadManager multiThreadManager) { _gameController = gameController; _graphics = graphics; _multiThreadManager = multiThreadManager; RootDirectory = AppDomain.CurrentDomain.BaseDirectory; Directories["Temp"] = Path.Combine(RootDirectory, PluginsDirectory, "Temp"); Directories[PluginsDirectory] = Path.Combine(RootDirectory, PluginsDirectory); Directories[CompiledPluginsDirectory] = Path.Combine(Directories[PluginsDirectory], CompiledPluginsDirectory); Directories[SourcePluginsDirectory] = Path.Combine(Directories[PluginsDirectory], SourcePluginsDirectory); _gameController.EntityListWrapper.EntityAdded += EntityListWrapperOnEntityAdded; _gameController.EntityListWrapper.EntityRemoved += EntityListWrapperOnEntityRemoved; _gameController.EntityListWrapper.EntityAddedAny += EntityListWrapperOnEntityAddedAny; _gameController.EntityListWrapper.EntityIgnored += EntityListWrapperOnEntityIgnored; _gameController.Area.OnAreaChange += AreaOnOnAreaChange; parallelLoading = _gameController.Settings.CoreSettings.MultiThreadLoadPlugins; foreach (var directory in Directories) { if (!Directory.Exists(directory.Value)) { DebugWindow.LogMsg($"{directory.Value} doesn't exists, but don't worry i created it for you."); Directory.CreateDirectory(directory.Value); } } var(compiledPlugins, sourcePlugins) = SearchPlugins(); List <(Assembly asm, DirectoryInfo directoryInfo)> assemblies = new List <(Assembly, DirectoryInfo)>(); Task task = null; if (sourcePlugins.Length > 0) { task = Task.Run(() => { var compilePluginsFromSource = CompilePluginsFromSource(sourcePlugins); }); } var compiledAssemblies = GetCompiledAssemblies(compiledPlugins, parallelLoading); var devTree = Plugins.FirstOrDefault(x => x.Name.Equals("DevTree")); task?.Wait(); Plugins = Plugins.OrderBy(x => x.Order).ThenByDescending(x => x.CanBeMultiThreading).ThenBy(x => x.Name) .ToList(); if (devTree != null) { try { var fieldInfo = devTree.Plugin.GetType().GetField("Plugins"); List <PluginWrapper> devTreePlugins() => Plugins; fieldInfo.SetValue(devTree.Plugin, (Func <List <PluginWrapper> >)devTreePlugins); } catch (Exception e) { LogError(e.ToString()); } } if (parallelLoading) { //Pre init some general objects because with multi threading load they can null sometimes for some plugin var ingameStateIngameUi = gameController.IngameState.IngameUi; var ingameStateData = gameController.IngameState.Data; var ingameStateServerData = gameController.IngameState.ServerData; Parallel.ForEach(Plugins, wrapper => wrapper.Initialise(gameController)); } else { Plugins.ForEach(wrapper => wrapper.Initialise(gameController)); } AreaOnOnAreaChange(gameController.Area.CurrentArea); Plugins.ForEach(x => x.SubscrideOnFile(HotReloadDll)); AllPluginsLoaded = true; }
private void ShowDebugWindow() { if(DebugWindowVisible) return; var n=new DebugWindow(new DebugWindowViewModel(_eventAggregator)); n.Show(); SetDebugWindowVisibilityCheckMark(true); }
void Awake() { instance = this; DontDestroyOnLoad (this); }
public static List <CustomFilter> Parse(string[] filtersLines) { var allFilters = new List <CustomFilter>(); for (var i = 0; i < filtersLines.Length; ++i) { var filterLine = filtersLines[i]; filterLine = filterLine.Replace("\t", ""); if (filterLine.StartsWith(COMMENTSYMBOL)) { continue; } if (filterLine.StartsWith(COMMENTSYMBOLALT)) { continue; } if (filterLine.Replace(" ", "").Length == 0) { continue; } var nameIndex = filterLine.IndexOf(SYMBOL_NAMEDIVIDE); if (nameIndex == -1) { DebugWindow.LogMsg("Filter parser: Can't find filter name in line: " + (i + 1), 5); continue; } var newFilter = new CustomFilter { Name = filterLine.Substring(0, nameIndex).Trim(), Index = i + 1 }; var filterCommandsLine = filterLine.Substring(nameIndex + 1); var submenuIndex = filterCommandsLine.IndexOf(SYMBOL_SUBMENUNAME); if (submenuIndex != -1) { newFilter.SubmenuName = filterCommandsLine.Substring(submenuIndex + 1); filterCommandsLine = filterCommandsLine.Substring(0, submenuIndex); } var filterCommands = filterCommandsLine.Split(SYMBOL_COMMANDSDIVIDE); newFilter.Commands = filterCommandsLine; var filterErrorParse = false; foreach (var command in filterCommands) { if (string.IsNullOrEmpty(command.Replace(" ", ""))) { continue; } if (command.Contains(SYMBOL_COMMAND_FILTER_OR)) { var orFilterCommands = command.Split(SYMBOL_COMMAND_FILTER_OR); var newOrFilter = new BaseFilter { BAny = true }; newFilter.Filters.Add(newOrFilter); foreach (var t in orFilterCommands) { if (ProcessCommand(newOrFilter, t)) { continue; } filterErrorParse = true; break; } if (filterErrorParse) { break; } } else { if (ProcessCommand(newFilter, command)) { continue; } filterErrorParse = true; break; } } if (!filterErrorParse) { allFilters.Add(newFilter); } else { DebugWindow.LogMsg($"Line: {i + 1}", 5, Color.Red); } } return(allFilters); }
public PluginManager(GameController gameController, Graphics graphics, MultiThreadManager multiThreadManager) { _gameController = gameController; _graphics = graphics; _multiThreadManager = multiThreadManager; RootDirectory = AppDomain.CurrentDomain.BaseDirectory; Directories["Temp"] = Path.Combine(RootDirectory, PluginsDirectory, "Temp"); Directories[PluginsDirectory] = Path.Combine(RootDirectory, PluginsDirectory); Directories[CompiledPluginsDirectory] = Path.Combine(Directories[PluginsDirectory], CompiledPluginsDirectory); Directories[SourcePluginsDirectory] = Path.Combine(Directories[PluginsDirectory], SourcePluginsDirectory); _gameController.EntityListWrapper.EntityAdded += EntityListWrapperOnEntityAdded; _gameController.EntityListWrapper.EntityRemoved += EntityListWrapperOnEntityRemoved; _gameController.EntityListWrapper.EntityAddedAny += EntityListWrapperOnEntityAddedAny; _gameController.EntityListWrapper.EntityIgnored += EntityListWrapperOnEntityIgnored; _gameController.Area.OnAreaChange += AreaOnOnAreaChange; bool parallelLoading = _gameController.Settings.CoreSettings.MultiThreadLoadPlugins; foreach (var directory in Directories) { if (!Directory.Exists(directory.Value)) { DebugWindow.LogMsg($"{directory.Value} doesn't exists, but don't worry i created it for you."); Directory.CreateDirectory(directory.Value); } } var(compiledPlugins, sourcePlugins) = SearchPlugins(); List <(Assembly asm, bool source)> assemblies = new List <(Assembly, bool)>(); var locker = new object(); var task = Task.Run(() => { var compilePluginsFromSource = CompilePluginsFromSource(sourcePlugins); lock (locker) { compilePluginsFromSource.ForEach(assembly => assemblies.Add((assembly, true))); } }); var task2 = Task.Run(() => { var compiledAssemblies = GetCompiledAssemblies(compiledPlugins, parallelLoading); lock (locker) { compiledAssemblies.Where(x => x != null).ForEach(assembly => assemblies.Add((assembly, false))); } }); Task.WaitAll(task, task2); if (parallelLoading) { Parallel.ForEach(assemblies, tuple => TryLoadAssemble(tuple.asm, tuple.source)); } else { assemblies.ForEach(tuple => TryLoadAssemble(tuple.asm, tuple.source)); } Plugins = Plugins.OrderBy(x => x.Order).ThenByDescending(x => x.CanBeMultiThreading).ThenBy(x => x.Name) .ToList(); if (parallelLoading) { //Pre init some general objects because with multi threading load they can null sometimes for some plugin var ingameStateIngameUi = gameController.IngameState.IngameUi; var ingameStateData = gameController.IngameState.Data; var ingameStateServerData = gameController.IngameState.ServerData; Parallel.ForEach(Plugins, wrapper => InitPlugin(wrapper.Plugin)); } else { Plugins.ForEach(wrapper => InitPlugin(wrapper.Plugin)); } AreaOnOnAreaChange(gameController.Area.CurrentArea); AllPluginsLoaded = true; }
private void ScanInventory(IList <NormalInventoryItem> normalInventoryItems) { _goodItemsPos.Clear(); _allItemsPos.Clear(); _highItemsPos.Clear(); _veilItemsPos.Clear(); foreach (var normalInventoryItem in normalInventoryItems) { try { #region Start var highItemLevel = false; var item = normalInventoryItem.Item; if (item == null) { continue; } if (string.IsNullOrEmpty(item.Path)) { continue; } var modsComponent = item.GetComponent <Mods>(); var drawRect = normalInventoryItem.GetClientRect(); //fix star position drawRect.X -= 5; drawRect.Y -= 5; var bit = GameController.Files.BaseItemTypes.Translate(item.Path); #endregion #region Vendor for scrolls if (Settings.VendorForScrolls) { if (item.Path == @"Metadata/Items/Currency/CurrencyArmourQuality") { _allItemsPos.Add(drawRect); } if (item.Path == @"Metadata/Items/Currency/CurrencyUpgradeToMagic" && new Random().NextDouble() < 0.25f) { _allItemsPos.Add(drawRect); } } #endregion #region Vendor for alts if (Settings.VendorRareJewels && modsComponent?.ItemRarity == ItemRarity.Rare && modsComponent?.Identified == true && item.Path.Contains("Jewel")) { _allItemsPos.Add(drawRect); } if (Settings.VendorTalismans && modsComponent?.ItemRarity == ItemRarity.Rare && modsComponent?.Identified == true && item.Path.Contains("Talisman")) { _allItemsPos.Add(drawRect); } if (Settings.VendorBreachRings && modsComponent?.ItemRarity == ItemRarity.Rare && modsComponent?.Identified == true && item.Path.Contains("BreachRing")) { _allItemsPos.Add(drawRect); } #endregion #region Prophecy if (item.HasComponent <Prophecy>()) { var prop = item.GetComponent <Prophecy>(); if (_goodProphecies.Contains(prop?.DatProphecy?.Name)) { _goodItemsPos.Add(drawRect); } } #endregion #region Div Card if (bit.ClassName.Equals("DivinationCard")) { if (_shitDivCards.Contains(bit.BaseName)) { if (Settings.VendorShitDivCards) { _allItemsPos.Add(drawRect); } } else { _goodItemsPos.Add(drawRect); } } #endregion #region Filter trash uniques if (modsComponent?.ItemRarity == ItemRarity.Unique && _shitUniques.Contains(modsComponent.UniqueName) && !item.HasComponent <Map>() && item.GetComponent <Sockets>()?.LargestLinkSize != 6 ) { if (bit.ClassName.Contains("MetamorphosisDNA")) { continue; } LogMessage(modsComponent.UniqueName); _allItemsPos.Add(drawRect); continue; } #endregion #region Vendor 6socket (but not 6L) if (item.GetComponent <Sockets>()?.NumberOfSockets == 6 && item.GetComponent <Sockets>()?.LargestLinkSize <= 5) { _allItemsPos.Add(drawRect); } #endregion #region Vendor blue trash if (Settings.VendorBlueTrash && modsComponent?.ItemRarity == ItemRarity.Magic && item.GetComponent <Sockets>()?.LargestLinkSize <= 5) { var baseComponent = item.GetComponent <Base>(); if (!baseComponent.isElder && !baseComponent.isShaper && !baseComponent.isCrusader && !baseComponent.isHunter && !baseComponent.isRedeemer && !baseComponent.isWarlord) { _allItemsPos.Add(drawRect); } } #endregion if (modsComponent?.ItemRarity != ItemRarity.Rare || modsComponent.Identified == false) { continue; } _totalWeight = 0; var itemMods = modsComponent.ItemMods; _mods.Clear(); _mods = itemMods .Where(m => m?.RawName?.Length > 1) .Select(it => new ModValue(it, GameController.Files, modsComponent.ItemLevel, bit)).ToList(); _item = item; #region Influence { var baseComponent = item.GetComponent <Base>(); if (modsComponent.ItemLevel >= Settings.ItemLevelInfluence && (baseComponent.isElder || baseComponent.isShaper || baseComponent.isCrusader || baseComponent.isHunter || baseComponent.isRedeemer || baseComponent.isWarlord)) { highItemLevel = true; // dont vendor influenced continue; } } #endregion #region Item Level if (modsComponent.ItemLevel >= Settings.ItemLevelNoInfluence && _goodBaseTypes.Contains(bit.BaseName)) { highItemLevel = true; } #endregion //--------------------------------------------------------------------------------------------------------------------------- if (highItemLevel) { _highItemsPos.Add(drawRect); } // skip enchanted gear if (Settings.DontSellEnchantedHelmets && bit?.ClassName == "Helmet" && _mods.Any(mod => mod.Record.UserFriendlyName.ToLower().Contains("enchant"))) { continue; } if (!Settings.TreatVeiledAsRegularItem && IsVeiled()) { _veilItemsPos.Add(drawRect); continue; } switch (bit?.ClassName) { case "Body Armour": CheckLife(Settings.Ba_Life); CheckDefense(Settings.Ba_EnergyShield); CheckResist(Settings.Ba_TotalRes); CheckIntelligence(Settings.Ba_Intelligence); CheckDexterity(Settings.Ba_Dexterity); CheckStrength(Settings.Ba_Strength); CheckComboLife(Settings.Ba_LifeCombo); CheckGood(Settings.Ba_Affixes, drawRect); break; case "Quiver": CheckLife(Settings.Q_Life); CheckResist(Settings.Q_TotalRes); CheckAccuracy(Settings.Q_Accuracy); CheckFlatPhys(Settings.Q_PhysDamage); CheckWED(Settings.Q_WeaponElemDamage); CheckCritMultiGlobal(Settings.Q_CritMult); CheckGlobalCritChance(Settings.Q_CritChance); CheckGood(Settings.Q_Affixes, drawRect); break; case "Helmet": CheckLife(Settings.H_Life); CheckDefense(Settings.H_EnergyShield); CheckResist(Settings.H_TotalRes); CheckIntelligence(Settings.H_Dexterity); CheckDexterity(Settings.H_Dexterity); CheckStrength(Settings.H_Intelligence); CheckComboLife(Settings.H_LifeCombo); CheckAccuracy(Settings.H_Accuracy); CheckMana(Settings.H_Mana); CheckGood(Settings.H_Affixes, drawRect); break; case "Boots": CheckLife(Settings.B_Life); CheckDefense(Settings.B_EnergyShield); CheckMoveSpeed(Settings.B_MoveSpeed); CheckResist(Settings.B_TotalRes); CheckIntelligence(Settings.B_Intelligence); CheckDexterity(Settings.B_Dexterity); CheckStrength(Settings.B_Strength); CheckComboLife(Settings.B_LifeCombo); CheckMana(Settings.B_Mana); CheckGood(Settings.B_Affixes, drawRect); break; case "Gloves": CheckLife(Settings.G_Life); CheckDefense(Settings.G_EnergyShield); CheckResist(Settings.G_TotalRes); CheckAccuracy(Settings.G_Accuracy); CheckAttackSpeed(Settings.G_AttackSpeed); CheckFlatPhys(Settings.G_PhysDamage); CheckStrength(Settings.G_Strength); CheckIntelligence(Settings.G_Intelligence); CheckDexterity(Settings.G_Dexterity); CheckMana(Settings.G_Mana); CheckComboLife(Settings.G_LifeCombo); CheckGood(Settings.G_Affixes, drawRect); break; case "Shield": CheckLife(Settings.S_Life); CheckDefense(Settings.S_EnergyShield); CheckResist(Settings.S_TotalRes); CheckStrength(Settings.S_Strength); CheckDexterity(Settings.S_Dexterity); CheckIntelligence(Settings.S_Intelligence); CheckSpellElemDamage(Settings.S_SpellDamage); CheckSpellCrit(Settings.S_SpellCritChance); CheckComboLife(Settings.S_LifeCombo); CheckGood(Settings.S_Affixes, drawRect); break; case "Belt": CheckLife(Settings.Be_Life); CheckEnergyShieldJewel(Settings.Be_EnergyShield); CheckResist(Settings.Be_TotalRes); CheckStrength(Settings.Be_Strength); CheckWED(Settings.Be_WeaponElemDamage); CheckFlaskReduced(Settings.Be_FlaskReduced); CheckFlaskDuration(Settings.Be_FlaskDuration); CheckGood(Settings.Be_Affixes, drawRect); break; case "Ring": CheckLife(Settings.R_Life); CheckResist(Settings.R_TotalRes); CheckEnergyShieldJewel(Settings.R_EnergyShield); CheckAttackSpeed(Settings.R_AttackSpeed); CheckCastSpeed(Settings.R_CastSpped); CheckAccuracy(Settings.R_Accuracy); CheckFlatPhys(Settings.R_PhysDamage); CheckWED(Settings.R_WeaponElemDamage); CheckStrength(Settings.R_Strength); CheckIntelligence(Settings.R_Intelligence); CheckDexterity(Settings.R_Dexterity); CheckMana(Settings.R_Mana); CheckGood(Settings.R_Affixes, drawRect); break; case "Amulet": CheckLife(Settings.A_Life); CheckEnergyShieldJewel(Settings.A_EnergyShield); CheckResist(Settings.A_TotalRes); CheckAccuracy(Settings.A_Accuracy); CheckFlatPhys(Settings.A_PhysDamage); CheckWED(Settings.A_WeaponElemDamage); CheckGlobalCritChance(Settings.A_CritChance); CheckCritMultiGlobal(Settings.A_CritMult); CheckSpellElemDamage(Settings.A_TotalElemSpellDmg); CheckStrength(Settings.A_Strength); CheckIntelligence(Settings.A_Intelligence); CheckDexterity(Settings.A_Dexterity); CheckMana(Settings.A_Mana); CheckGood(Settings.A_Affixes, drawRect); break; case "Dagger": CheckAttackWeapon(); CheckGood(Settings.Wa_Affixes, drawRect); break; case "Rune Dagger": CheckCastWeapon(); CheckGood(Settings.Wc_Affixes, drawRect); break; case "Wand": CheckCastWeapon(); CheckGood(Settings.Wc_Affixes, drawRect); break; case "Sceptre": CheckCastWeapon(); CheckGood(Settings.Wc_Affixes, drawRect); break; case "Thrusting One Hand Sword": CheckAttackWeapon(); CheckGood(Settings.Wa_Affixes, drawRect); break; case "Staff": CheckCastWeapon(); CheckGood(Settings.Wa_Affixes, drawRect); break; case "Warstaff": CheckAttackWeapon(); CheckGood(Settings.Wa_Affixes, drawRect); break; case "Claw": CheckAttackWeapon(); CheckGood(Settings.Wa_Affixes, drawRect); break; case "One Hand Sword": CheckAttackWeapon(); CheckGood(Settings.Wa_Affixes, drawRect); break; case "Two Hand Sword": CheckAttackWeapon(); CheckGood(Settings.Wa_Affixes, drawRect); break; case "One Hand Axe": CheckAttackWeapon(); CheckGood(Settings.Wa_Affixes, drawRect); break; case "Two Hand Axe": CheckAttackWeapon(); CheckGood(Settings.Wa_Affixes, drawRect); break; case "One Hand Mace": CheckAttackWeapon(); CheckGood(Settings.Wa_Affixes, drawRect); break; case "Two Hand Mace": CheckAttackWeapon(); CheckGood(Settings.Wa_Affixes, drawRect); break; case "Bow": CheckAttackWeapon(); CheckGood(Settings.Wa_Affixes, drawRect); break; default: continue; } if (Settings.DebugMode) { foreach (var mod in _mods) { LogMessage(mod.Record.Group + " : " + mod.StatValue[0], 10f); } LogMessage(_totalWeight.ToString(), 10f); LogMessage("--------------------", 10f); } } catch (Exception e) { DebugWindow.LogMsg(e?.StackTrace, 1, Color.GreenYellow); } } }
private void LogError(string msg) { DebugWindow.LogError(msg, 5); }
private void ParsePoeNinja() { try { _shitUniques = new HashSet <string>(); _shitDivCards = new HashSet <string>(); _goodProphecies = new HashSet <string>(); IFormatProvider formatter = new NumberFormatInfo { NumberDecimalSeparator = "." }; float chaosValue; if (!Settings.Update.Value) { return; } #region Unique List <string> uniquesUrls; switch (Settings.League.Value) { case "Temp SC": uniquesUrls = new List <string> { @"https://poe.ninja/api/data/itemoverview?league=" + LEAGUE_NAME + @"&type=UniqueJewel&language=en", @"https://poe.ninja/api/data/itemoverview?league=" + LEAGUE_NAME + @"&type=UniqueFlask&language=en", @"https://poe.ninja/api/data/itemoverview?league=" + LEAGUE_NAME + @"&type=UniqueWeapon&language=en", @"https://poe.ninja/api/data/itemoverview?league=" + LEAGUE_NAME + @"&type=UniqueArmour&language=en", @"https://poe.ninja/api/data/itemoverview?league=" + LEAGUE_NAME + @"&type=UniqueAccessory&language=en" }; break; case "Temp HC": uniquesUrls = new List <string> { @"https://poe.ninja/api/data/itemoverview?league=Hardcore+" + LEAGUE_NAME + @"&type=UniqueJewel&language=en", @"https://poe.ninja/api/data/itemoverview?league=Hardcore+" + LEAGUE_NAME + @"&type=UniqueFlask&language=en", @"https://poe.ninja/api/data/itemoverview?league=Hardcore+" + LEAGUE_NAME + @"&type=UniqueWeapon&language=en", @"https://poe.ninja/api/data/itemoverview?league=Hardcore+" + LEAGUE_NAME + @"&type=UniqueArmour&language=en", @"https://poe.ninja/api/data/itemoverview?league=Hardcore+" + LEAGUE_NAME + @"&type=UniqueAccessory&language=en" }; break; default: uniquesUrls = new List <string>(); break; } var result = new List <string>(); foreach (var url in uniquesUrls) { using (var wc = new WebClient()) { var json = wc.DownloadString(url); var o = JObject.Parse(json); foreach (var line in o?["lines"]) { if (int.TryParse((string)line?["links"], out var links) && links == 6) { continue; } chaosValue = Convert.ToSingle((string)line?["chaosValue"], formatter); if (chaosValue < Settings.ChaosUnique.Value) { result.Add((string)line?["name"]); } } } } _shitUniques = result.ToHashSet(); #endregion #region DivCard string urlDiv; switch (Settings.League.Value) { case "Temp SC": urlDiv = @"https://poe.ninja/api/data/itemoverview?league=" + LEAGUE_NAME + @"&type=DivinationCard&language=en"; break; case "Temp HC": urlDiv = @"https://poe.ninja/api/data/itemoverview?league=Hardcore+" + LEAGUE_NAME + @"&type=DivinationCard&language=en"; break; default: urlDiv = ""; break; } result.Clear(); using (var wc = new WebClient()) { var json = wc.DownloadString(urlDiv); var o = JObject.Parse(json); foreach (var line in o?["lines"]) { chaosValue = Convert.ToSingle((string)line?["chaosValue"], formatter); if (chaosValue < Settings.ChaosDivCard.Value) { result.Add((string)line?["name"]); } } } _shitDivCards = result.ToHashSet(); #endregion #region Prophecy string urlProh; switch (Settings.League.Value) { case "Temp SC": urlProh = @"https://poe.ninja/api/data/itemoverview?league=" + LEAGUE_NAME + @"&type=Prophecy&language=en"; break; case "Temp HC": urlProh = @"https://poe.ninja/api/data/itemoverview?league=Hardcore+" + LEAGUE_NAME + @"&type=Prophecy&language=en"; break; default: urlProh = ""; break; } result.Clear(); using (var wc = new WebClient()) { var json = wc.DownloadString(urlProh); var o = JObject.Parse(json); foreach (var line in o?["lines"]) { chaosValue = Convert.ToSingle((string)line?["chaosValue"], formatter); if (chaosValue >= Settings.ChaosProphecy.Value) { result.Add((string)line?["name"]); } } } _goodProphecies = result.ToHashSet(); #endregion #region Test // string text = ""; // // foreach (var v in ShitUniques) // { // text += v + Environment.NewLine; // } // // string path = $"{DirectoryFullName}\\Test.txt"; // using (StreamWriter streamWriter = new StreamWriter(path, false)) // { // streamWriter.Write(text); // streamWriter.Close(); // } #endregion } catch (Exception e) { DebugWindow.LogMsg(e?.StackTrace, 1, Color.GreenYellow); _ninjaDelayMs *= 2; _poeNinjaInitialized = false; } finally { var n = _shitUniques.Count + _shitDivCards.Count; DebugWindow.LogMsg($"{n} shit items total loaded from ninja", 30, Color.GreenYellow); if (n > 200) { _poeNinjaInitialized = true; } else { _ninjaDelayMs *= 2; _poeNinjaInitialized = false; } } }
public CustomItem(LabelOnGround item, FilesContainer fs, float distance, Dictionary <string, int> weightsRules, bool isMetamorphItem = false) { if (isMetamorphItem) { IsMetaItem = true; LabelOnGround = item; Distance = distance; var itemItemOnGround = item.ItemOnGround; var worldIcon = itemItemOnGround?.GetComponent <MinimapIcon>(); if (worldIcon == null) { return; } //var groundItem = worldItem.ItemEntity; WorldIcon = worldIcon; GroundItem = itemItemOnGround; Path = GroundItem?.Path; if (Path != null && Path.Length < 1) { DebugWindow.LogMsg($"World2: {worldIcon.Address:X} P: {Path}", 2); DebugWindow.LogMsg($"Ground2: {GroundItem.Address:X} P {Path}", 2); return; } IsTargeted = () => { var isTargeted = itemItemOnGround.GetComponent <Targetable>()?.isTargeted; return(isTargeted != null && (bool)isTargeted); }; var baseItemType = fs.BaseItemTypes.Translate(Path); if (baseItemType != null) { ClassName = baseItemType.ClassName; BaseName = baseItemType.BaseName; Width = baseItemType.Width; Height = baseItemType.Height; if (weightsRules.TryGetValue(BaseName, out var w)) { Weight = w; } if (ClassName.StartsWith("Heist")) { IsHeist = true; } } IsValid = true; } else { isMetamorphItem = false; LabelOnGround = item; Distance = distance; var itemItemOnGround = item.ItemOnGround; var worldItem = itemItemOnGround?.GetComponent <WorldItem>(); if (worldItem == null) { return; } var groundItem = worldItem.ItemEntity; GroundItem = groundItem; Path = groundItem?.Path; if (GroundItem == null) { return; } if (Path != null && Path.Length < 1) { DebugWindow.LogMsg($"World: {worldItem.Address:X} P: {Path}", 2); DebugWindow.LogMsg($"Ground: {GroundItem.Address:X} P {Path}", 2); return; } IsTargeted = () => { var isTargeted = itemItemOnGround.GetComponent <Targetable>()?.isTargeted; return(isTargeted != null && (bool)isTargeted); }; var baseItemType = fs.BaseItemTypes.Translate(Path); if (baseItemType != null) { ClassName = baseItemType.ClassName; BaseName = baseItemType.BaseName; Width = baseItemType.Width; Height = baseItemType.Height; if (weightsRules.TryGetValue(BaseName, out var w)) { Weight = w; } if (ClassName.StartsWith("Heist")) { IsHeist = true; } } var WeaponClass = new List <string> { "One Hand Mace", "Two Hand Mace", "One Hand Axe", "Two Hand Axe", "One Hand Sword", "Two Hand Sword", "Thrusting One Hand Sword", "Bow", "Claw", "Dagger", "Rune Dagger", "Sceptre", "Staff", "Wand" }; if (GroundItem.HasComponent <Quality>()) { var quality = GroundItem.GetComponent <Quality>(); Quality = quality.ItemQuality; } if (GroundItem.HasComponent <Base>()) { var @base = GroundItem.GetComponent <Base>(); IsElder = @base.isElder; IsShaper = @base.isShaper; IsHunter = @base.isHunter; IsRedeemer = @base.isRedeemer; IsCrusader = @base.isCrusader; IsWarlord = @base.isWarlord; } if (GroundItem.HasComponent <Mods>()) { var mods = GroundItem.GetComponent <Mods>(); Rarity = mods.ItemRarity; IsIdentified = mods.Identified; ItemLevel = mods.ItemLevel; IsFractured = mods.HaveFractured; IsVeiled = mods.ItemMods.Any(m => m.DisplayName.Contains("Veil")); } if (GroundItem.HasComponent <Sockets>()) { var sockets = GroundItem.GetComponent <Sockets>(); IsRGB = sockets.IsRGB; Sockets = sockets.NumberOfSockets; LargestLink = sockets.LargestLinkSize; } if (GroundItem.HasComponent <Weapon>()) { IsWeapon = true; } MapTier = GroundItem.HasComponent <Map>() ? GroundItem.GetComponent <Map>().Tier : 0; IsValid = true; } }
public IEnumerator CollectEntities(EntityCollectSettingsContainer container) { if (Address == 0) { DebugWindow.LogError($"{nameof(EntityList)} -> Address is 0;"); yield return(new WaitTime(100)); } while (!container.NeedUpdate) { yield return(collectEntities); } sw.Restart(); var dataEntitiesCount = container.EntitiesCount(); var parseServerEntities = container.ParseServer(); double jobsTimeSum = 0; var addr = M.Read <long>(Address + 0x8); hashAddresses.Clear(); hashSet.Clear(); StoreIds.Clear(); queue.Enqueue(addr); var node = M.Read <EntityListOffsets>(addr); queue.Enqueue(node.FirstAddr); queue.Enqueue(node.SecondAddr); var loopcount = 0; while (queue.Count > 0 && loopcount < 10000) { try { loopcount++; var nextAddr = queue.Dequeue(); if (hashSet.Contains(nextAddr)) { continue; } hashSet.Add(nextAddr); if (nextAddr != addr && nextAddr != 0) { var entityAddress = node.Entity; if (entityAddress > 0x100000000 && entityAddress < 0x7F0000000000) { hashAddresses.Add(entityAddress); } node = M.Read <EntityListOffsets>(nextAddr); queue.Enqueue(node.FirstAddr); queue.Enqueue(node.SecondAddr); } } catch (Exception e) { DebugWindow.LogError($"Entitylist while loop: {e}"); } } EntitiesProcessed = hashAddresses.Count; if (dataEntitiesCount > 0 && EntitiesProcessed / dataEntitiesCount > 1.5f) { DebugWindow.LogError($"Something wrong we parse {EntitiesProcessed} when expect {dataEntitiesCount}"); TheGame.IngameState.UpdateData(); } if (container.ParseEntitiesInMultiThread() && container.CollectEntitiesInParallelWhenMoreThanX && container.MultiThreadManager != null && EntitiesProcessed / container.MultiThreadManager.ThreadsCount >= 100) { var hashAddressesCount = hashAddresses.Count / (container.MultiThreadManager.ThreadsCount); var jobs = new List <Job>(container.MultiThreadManager.ThreadsCount); var lastStart = container.MultiThreadManager.ThreadsCount * hashAddressesCount; for (var i = 1; i <= container.MultiThreadManager.ThreadsCount; i++) { var i1 = i; var job = container.MultiThreadManager.AddJob(() => { try { int addressesCount; if (i == container.MultiThreadManager.ThreadsCount) { addressesCount = hashAddresses.Count; } else { addressesCount = i1 * hashAddressesCount; } var start = (i1 - 1) * hashAddressesCount; Span <uint> stackIds = stackalloc uint[addressesCount - start]; var index = 0; for (var j = start; j < addressesCount; j++) { var addrEntity = hashAddresses[j]; stackIds[index] = ParseEntity(addrEntity, container.EntityCache, container.EntitiesVersion, container.Simple, parseServerEntities); index++; } lock (locker) { foreach (var u in stackIds) { StoreIds.Add(u); } } } catch (Exception e) { DebugWindow.LogError($"{e}"); } }, $"EntityCollection {i}"); jobs.Add(job); } /*try * { * Span<uint> stackIds = stackalloc uint[hashAddresses.Count-hashAddressesCount]; * var index = 0; * for (var j = lastStart; j < hashAddresses.Count; j++) * { * var addrEntity = hashAddresses[j]; * stackIds[index]= ParseEntity(addrEntity, entityCache, entitiesVersion, result); * index++; * * } * lock (locker) * { * foreach (var u in stackIds) * { * StoreIds.Add(u); * } * } * } * catch (Exception e) * { * DebugWindow.LogError($"{e}"); * }*/ while (!jobs.AllF(x => x.IsCompleted)) { sw.Stop(); yield return(collectEntities); sw.Start(); } jobsTimeSum = jobs.SumF(x => x.ElapsedMs); } else { foreach (var addrEntity in hashAddresses) { StoreIds.Add(ParseEntity(addrEntity, container.EntityCache, container.EntitiesVersion, container.Simple, parseServerEntities)); } } if (container.Break) { container.Break = false; container.EntitiesVersion++; container.NeedUpdate = false; container.DebugInformation.Tick = sw.Elapsed.TotalMilliseconds; yield break; } foreach (var entity in container.EntityCache) { var entityValue = entity.Value; if (StoreIds.Contains(entity.Key)) { entityValue.IsValid = true; continue; } entityValue.IsValid = false; var entityValueDistancePlayer = entityValue.DistancePlayer; if (entityValueDistancePlayer < 100) { if (entityValueDistancePlayer < 75) { if (entityValue.Type == EntityType.Chest && entityValue.League == LeagueType.Delve) { if (entityValueDistancePlayer < 30) { container.KeyForDelete.Enqueue(entity.Key); continue; } } else { container.KeyForDelete.Enqueue(entity.Key); continue; } } if (entityValue.Type == EntityType.Monster && entityValue.IsAlive) { container.KeyForDelete.Enqueue(entity.Key); continue; } } if (entityValueDistancePlayer > 300 && entity.Value.Metadata.Equals("Metadata/Monsters/Totems/HeiTikiSextant", StringComparison.Ordinal)) { container.KeyForDelete.Enqueue(entity.Key); continue; } if ((int)entityValue.Type < 100) { container.KeyForDelete.Enqueue(entity.Key); continue; } if (entityValueDistancePlayer > 1_000_000 || entity.Value.GridPos.IsZero) { container.KeyForDelete.Enqueue(entity.Key); continue; } } container.EntitiesVersion++; container.NeedUpdate = false; container.DebugInformation.Tick = (sw.Elapsed.TotalMilliseconds + jobsTimeSum); }
public void Dispose() { DebugWindow.Dispose(); }
private bool RenderGraphics() { // First render the scene to a texture. if (!RenderSceneToTexture()) { return(false); } // Clear the scene. D3D.BeginScene(0.0f, 0.0f, 0.0f, 1.0f); // Generate the view matrix based on the camera's position. Camera.Render(); //// Get the world, view, projection, ortho, and base view matrices from the camera and Direct3D objects. Matrix worldMatrix = D3D.WorldMatrix; Matrix cameraViewMatrix = Camera.ViewMatrix; Matrix projectionMatrix = D3D.ProjectionMatrix; Matrix orthoD3DMatrix = D3D.OrthoMatrix; Matrix baseViewMatrix = Camera.BaseViewMatrix; // Render the terrain buffers. TerrainModel.Render(D3D.DeviceContext); // Render the terrain using the terrain shader. if (!TerrainShader.Render(D3D.DeviceContext, TerrainModel.IndexCount, worldMatrix, cameraViewMatrix, projectionMatrix, Light.AmbientColor, Light.DiffuseColour, Light.Direction, TerrainModel.Texture.TextureResource, TerrainModel.DetailTexture.TextureResource)) { return(false); } ///// Turn off the Z buffer to begin all 2D rendering. D3D.TurnZBufferOff(); // Put the debug window on the graphics pipeline to prepare it for drawing. if (!DebugWindow.Render(D3D.DeviceContext, 100, 60)) { return(false); } // Render the bitmap model using the texture shader and the render to texture resource. if (!TextureShader.Render(D3D.DeviceContext, DebugWindow.IndexCount, worldMatrix, baseViewMatrix, orthoD3DMatrix, RenderTexture.ShaderResourceView)) { return(false); } // Turn on the alpha blending before rendering the text. D3D.TurnOnAlphaBlending(); // Render the text user interface elements. if (!Text.Render(D3D.DeviceContext, worldMatrix, orthoD3DMatrix)) { return(false); } // Turn off alpha blending after rendering the text. D3D.TurnOffAlphaBlending(); // Turn the Z buffer back on now that all 2D rendering has completed. D3D.TurnZBufferOn(); /// Present the rendered scene to the screen. D3D.EndScene(); return(true); }
// ================================================================ // public static DebugWindow root() { return(DebugWindow.get()); }
public bool Initialize(SystemConfiguration configuration, IntPtr windowHandle) { try { // Create the Direct3D object. D3D = new DX11(); // Initialize the Direct3D object. if (!D3D.Initialize(configuration, windowHandle)) { MessageBox.Show("Could not initialize Direct3D", "Error", MessageBoxButtons.OK); return(false); } // Create the camera object Camera = new Camera(); // Initialize a base view matrix the camera for 2D user interface rendering. Camera.SetPosition(0, 0, -10); Camera.Render(); var baseViewMatrix = Camera.ViewMatrix; // Create the model class. Model = new Model(); // Initialize the model object. if (!Model.Initialize(D3D.Device, "cube.txt", new[] { "seafloor.dds" })) { MessageBox.Show("Could not initialize the model object", "Error", MessageBoxButtons.OK); return(false); } // Create the shader object. LightShader = new LightShader(); // Initialize the shader object. if (!LightShader.Initialize(D3D.Device, windowHandle)) { MessageBox.Show("Could not initialize the light shader", "Error", MessageBoxButtons.OK); return(false); } // Create the light object. Light = new Light(); // Initialize the light object. Light.SetAmbientColor(0.15f, 0.15f, 0.15f, 1.0f); Light.SetDiffuseColor(1, 1, 1, 1f); Light.SetDirection(0, 0, 1); Light.SetSpecularColor(0, 1, 1, 1); Light.SetSpecularPower(16); // Create the render to texture object. RenderTexture = new RenderTexture(); // Initialize the render to texture object. if (!RenderTexture.Initialize(D3D.Device, configuration)) { return(false); } // Create the debug window object. DebugWindow = new DebugWindow(); // Initialize the debug window object. if (!DebugWindow.Initialize(D3D.Device, configuration.Width, configuration.Height, 100, 100 * configuration.Height / configuration.Width)) { MessageBox.Show("Could not initialize the debug window object.", "Error", MessageBoxButtons.OK); return(false); } // Create the texture shader object. TextureShader = new TextureShader(); // Initialize the texture shader object. if (!TextureShader.Initialize(D3D.Device, windowHandle)) { MessageBox.Show("Could not initialize the texture shader object.", "Error", MessageBoxButtons.OK); return(false); } return(true); } catch (Exception ex) { MessageBox.Show("Could not initialize Direct3D\nError is '" + ex.Message + "'"); return(false); } }
private void LogError(Exception e, [CallerMemberName] string methodName = null) { var msg = $"{Plugin.Name}, {methodName} -> {e}"; DebugWindow.LogError(msg, 3); }
public void Shutdown() { // Release the texture shader object. if (TextureShader != null) { TextureShader.Shuddown(); TextureShader = null; } // Release the debug window object. if (DebugWindow != null) { DebugWindow.Shutdown(); DebugWindow = null; } // Release the render to texture object. if (RenderTexture != null) { RenderTexture.Shutdown(); RenderTexture = null; } // Release the light object. Light = null; // Release the shader object. if (LightShader != null) { LightShader.Shuddown(); LightShader = null; } // Release the model object. if (Model != null) { Model.Shutdown(); Model = null; } // Release the light shader object. if (BumpMapShader != null) { BumpMapShader.Shuddown(); BumpMapShader = null; } // Release the model object. if (BumpMapModel != null) { BumpMapModel.Shutdown(); BumpMapModel = null; } // Release the text object. if (Text != null) { Text.Shutdown(); Text = null; } // Release the camera object. if (Camera != null) { Camera = null; } // Release the Direct3D object. if (D3D != null) { D3D.Shutdown(); D3D = null; } }
public static List <RefillProcessor> Parse(string pluginDir) { var refills = new List <RefillProcessor>(); var refillConfigPath = Path.Combine(pluginDir, REFILL_CONFIG); if (!File.Exists(refillConfigPath)) { return(refills); } var configLines = File.ReadAllLines(refillConfigPath); for (var i = 0; i < configLines.Length; i++) { var configLine = configLines[i]; configLine = configLine.Replace("\t", ""); if (configLine.Replace(" ", "").Length == 0) { continue; } if (configLine.StartsWith(SYMBOL_IGNORE) || configLine.StartsWith(SYMBOL_IGNORE2)) { continue; } var newRefill = new RefillProcessor(); var nameIndex = configLine.IndexOf(SYMBOL_NAMEDIVIDER, StringComparison.Ordinal); if (nameIndex == -1) { DebugWindow.LogMsg($"Refill parser: Can't find refill name in line: {configLine}. Name should have \":\" divider.", 10); continue; } newRefill.MenuName = configLine.Substring(0, nameIndex); TrimName(ref newRefill.MenuName); configLine = configLine.Substring(nameIndex + SYMBOL_NAMEDIVIDER.Length); var configLineParams = configLine.Split(SYMBOL_PARAMETERSDIVIDER); if (configLineParams.Length != 4) { DebugWindow.LogMsg( $"Refill parser: Config line should have 4 parameters (ClassName,StackSize,InventoryX,InventoryY): {configLine}, Ignoring refill..", 10); continue; } newRefill.CurrencyClass = configLineParams[0]; TrimName(ref newRefill.CurrencyClass); if (!int.TryParse(configLineParams[1], out newRefill.StackSize)) { DebugWindow.LogMsg( $"Refill parser: Can't parse StackSize from 2nd parameter in line: {configLine} (line num: {i + 1}), Ignoring refill..", 10); continue; } if (!int.TryParse(configLineParams[2], out newRefill.InventPos.X)) { DebugWindow.LogMsg( $"Refill parser: Can't parse InventoryX from 3rd parameter in line: {configLine} (line num: {i + 1}), Ignoring refill..", 10); continue; } if (newRefill.InventPos.X < 1 || newRefill.InventPos.X > 12) { DebugWindow.LogMsg( $"Refill parser: InventoryX should be in range 1-12, current value: {newRefill.InventPos.X} (line num: {i + 1}), Ignoring refill..", 10); continue; } if (!int.TryParse(configLineParams[3], out newRefill.InventPos.Y)) { DebugWindow.LogMsg( $"Refill parser: Can't parse InventoryY from 4th parameter in line: {configLine} (line num: {i + 1}), Ignoring refill..", 10); continue; } if (newRefill.InventPos.Y < 1 || newRefill.InventPos.Y > 5) { DebugWindow.LogMsg( $"Refill parser: InventPosY should be in range 1-5, current value: {newRefill.InventPos.Y} (line num: {i + 1}), Ignoring refill..", 10); continue; } // Convert to zero based index. newRefill.InventPos.X--; newRefill.InventPos.Y--; refills.Add(newRefill); } return(refills); }
public Dictionary <GameStat, int> ParseStats() { if (Address == 0) { return(testStatDictionary); } var statPtrStart = StatsComponent.Stats.First; var statPtrLast = StatsComponent.Stats.Last; var statPtrEnd = StatsComponent.Stats.End; if (StatsComponent.Stats.Size <= 0) { return(testStatDictionary); } var key = 0; var value = 0; var total_stats = statPtrLast - statPtrStart; var max_stats = statPtrEnd - statPtrStart; if (total_stats > max_stats || statPtrStart == 0) { return(testStatDictionary); } var bytes = M.ReadMem(statPtrStart, (int)total_stats); var capacity = max_stats / 8; if (max_stats > 9000) { DebugWindow.LogError( $"Stats over capped: {StatsComponent.Stats} Total Stats: {total_stats} Max Stats: {max_stats}"); return(testStatDictionary); } if (capacity < 0) { return(testStatDictionary); } if (testStatDictionary.Count < capacity) { testStatDictionary = new Dictionary <GameStat, int>((int)capacity); } testStatDictionary.Clear(); for (var i = 0; i < bytes.Length - 0x04; i += 8) { try { key = BitConverter.ToInt32(bytes, i); value = BitConverter.ToInt32(bytes, i + 0x04); testStatDictionary[(GameStat)key] = value; } catch (Exception e) { throw new Exception($"Stats parse {e}"); } } return(testStatDictionary); }
private void LogError(Exception e) { var msg = $"{Plugin.Name} -> {e}"; DebugWindow.LogError(msg, 3); }
private IEnumerator PopAStack(ServerInventory.InventSlotItem item) { //DebugWindow.LogError("Test in PopAStack", 5); var invSlot = item.InventoryPosition; //initial invslot var openSlotPos = Point.Zero; var stacksize = item.Item.GetComponent <Stack>()?.Size ?? 0; var slotRectCenter = item.GetClientRect().Center; var cursorInv = GameController.Game.IngameState.ServerData.PlayerInventories[12].Inventory; int latency = (int)GameController.IngameState.ServerData.Latency; int maxWaitTime = Settings.MaxWatitTime.Value; while (stacksize > 0) { //check profile requirements if (!Settings.DropToGround && !Settings.DropToDivTab && !_InventoryLayout.GetNextOpenSlot(ref openSlotPos)) { DebugWindow.LogError( "UnstackDecks => Inventory doesn't have space to place the next div card."); StopCoroutine(Name); yield break; } else if (!areRequirementsMet()) { LogError("Requirements not met!"); StopCoroutine(Name); yield break; } //click the stackdeck stack yield return(Input.SetCursorPositionAndClick(slotRectCenter, Settings.ReverseMouseButtons ? MouseButtons.Left : MouseButtons.Right, Settings.TimeBetweenClicks)); //check if MouseInventory contains an item and waits for it yield return(new WaitFunctionTimed(() => cursorInv.CountItems > 0, true, maxWaitTime)); if (cursorInv.TotalItemsCounts == 0) { //LogError("Cursorinventory not filled"); //StopCoroutine(); yield break; } //click at the dropoff location yield return(Input.SetCursorPositionAndClick(chooseDestination(openSlotPos), Settings.ReverseMouseButtons ? MouseButtons.Right : MouseButtons.Left, Settings.TimeBetweenClicks)); //wait for item on cursor to be dropped off yield return(new WaitFunctionTimed(() => cursorInv.CountItems == 0, true, maxWaitTime)); if (cursorInv.TotalItemsCounts != 0) { //LogError("Cursorinventory not empty"); //StopCoroutine(); yield break; } if (!Settings.DropToGround && !Settings.DropToDivTab) { yield return(MarkSlotUsed(openSlotPos)); } //update item and the stacksize more safely //find the item by invslot item = GameController.IngameState.ServerData.PlayerInventories[0].Inventory.InventorySlotItems.ToList().Find(x => x.InventoryPosition == invSlot); //the item object is rebuilt completely by the game after removing a card from the stack yield return(new WaitFunctionTimed(() => item.Item.HasComponent <Stack>(), true, maxWaitTime)); //the game doesnt seem to like it when you unstack too fast and gives ingame chat error messages. The caching of the stacksize and simply decrementing brought other problems if (!item.Item.HasComponent <Stack>()) { //LogError("No Stack component of current item found"); //StopCoroutine(); yield break; } stacksize = item.Item.GetComponent <Stack>().Size; } }