private void PauseWhileMouseDown() { if (Core.Settings.Advanced.LazyRaider && !BotMain.IsPaused && MouseLeft()) { BotMain.PauseWhile(MouseLeft); } }
private void LeaveGame() { ResetGold(); ResetXp(); ZetaDia.Service.Party.LeaveGame(); BotMain.PauseWhile(() => ZetaDia.IsInGame); }
/// ---------------------------------------------------------------------------------------------------- /// <summary> /// Called when the bot sends a "pulse". /// </summary> /// ---------------------------------------------------------------------------------------------------- void IPlugin.OnPulse() { if (this.isPluginEnabled) { bool PauseRequested = this.PauseRequested(); if ((PauseRequested && !BotMain.IsPaused)) { BotMain.PauseWhile(() => this.PauseRequested()); } } }
private void Send(ControlRequest notification, int timeout = 3000) { _acknowledged = false; // Pause bot until the time out is hit. BotMain.PauseWhile(() => _acknowledged, 0, TimeSpan.FromMilliseconds(timeout)); s_logger.Information("Control Request: {notification}", notification); while (BotMain.IsPaused) { Thread.Yield(); } }
private static void ReloadItemRulesEventHandler(object sender, RoutedEventArgs e) { try { if (Trinity.StashRule == null) { Trinity.StashRule = new Interpreter(); } if (Trinity.StashRule != null) { BotMain.PauseWhile(Trinity.StashRule.reloadFromUI); } } catch (Exception ex) { Logger.LogError("Error Reloading Item Rules:" + ex); } }
// Pause Button private static void buttonPause_Click(object sender, RoutedEventArgs e) { if (bMainBotPaused) { btnPauseBot.Content = "Pause Bot"; bMainBotPaused = false; HasMappedPlayerAbilities = false; IsAlreadyMoving = false; lastMovementCommand = DateTime.Today; } else { BotMain.PauseWhile(BotIsPaused); btnPauseBot.Content = "Unpause Bot"; bMainBotPaused = true; } GoldInactivity.ResetCheckGold(); }
private bool Send(string data, bool pause = false, bool xml = false, int retry = 1, int timeout = 3000) { var success = false; var tries = 0; if (!xml) { data = _bs.Pid + ":" + data; } else { data += "\nEND"; } // Pause bot if (pause) { _recieved = false; Func <bool> waitFor = Recieved; BotMain.PauseWhile(waitFor, 0, TimeSpan.FromMilliseconds((retry * timeout) + 3000)); } while (!success && tries < retry) { try { tries++; using (var client = new NamedPipeClientStream(".", "YetAnotherRelogger")) { client.Connect(timeout); if (client.IsConnected) { var sw = new StreamWriter(client) { AutoFlush = true }; var sr = new StreamReader(client); sw.WriteLine(data); var connectionTime = DateTime.Now; while (!success && client.IsConnected) { if (DateTime.Now.Subtract(connectionTime).TotalSeconds > 3) { client.Close(); break; } var responseText = sr.ReadLine(); if (string.IsNullOrWhiteSpace(responseText)) { Thread.Sleep(10); continue; } HandleResponse(responseText); success = true; } } else { // Failed to connect } } } catch (TimeoutException) { // YAR is not running, disable the plugin Log("TimeoutException - Disabling YAR Plugin"); PluginManager.Plugins.Where(p => p.Plugin.Name == this.Name).All(p => p.Enabled = false); Thread.CurrentThread.Abort(); } catch (Exception ex) { LogException(ex); OnShutdown(); } Thread.Sleep(100); } _recieved = true; return(success); }
/// <summary> /// Receive Pulse event from DemonBuddy. /// </summary> public void OnPulse() { using (new PerformanceLogger("OnPulse")) { try { // At Login screen, derp! var loginSubmitButton = Zeta.Game.Internals.UIElement.FromName("Root.NormalLayer.BattleNetLogin_main.LayoutRoot.LoginContainer.SubmitButton"); if (loginSubmitButton != null && loginSubmitButton.IsValid && loginSubmitButton.IsVisible && BotMain.IsRunning) { new Thread(() => { BotMain.Stop(); Thread.Sleep(1000); BotMain.Start(); }) { IsBackground = true, Name = "LoginScreenBouncer", }.Start(); return; } if (ZetaDia.Me == null) { return; } if (!ZetaDia.IsInGame || !ZetaDia.Me.IsValid || ZetaDia.IsLoadingWorld) { return; } GameUI.SafeClickUIButtons(); if (ZetaDia.Me.IsDead) { return; } using (new PerformanceLogger("LazyRaiderClickToPause")) { if (Settings.Advanced.LazyRaiderClickToPause && !BotMain.IsPaused) { BotMain.PauseWhile(MouseLeft); } } // See if we should update the stats file if (DateTime.UtcNow.Subtract(ItemStatsLastPostedReport).TotalSeconds > 10) { ItemStatsLastPostedReport = DateTime.UtcNow; OutputReport(); } // Recording of all the XML's in use this run UsedProfileManager.RecordProfile(); Monk_MaintainTempestRush(); } catch (AccessViolationException) { // woof! } catch (Exception ex) { Logger.Log(LogCategory.UserInformation, "Exception in Pulse: {0}", ex.ToString()); } } }
/// <summary> /// Clicks a UI Element after a random interval. /// </summary> /// <param name="uiElement"></param> /// <param name="name"></param> /// <returns></returns> internal static bool SafeClick(UIElement uiElement, ClickDelay delayOption, string name = "", int postClickThreadSleepDuration = 0, bool fireWorldTransferStart = false) { try { if (DateTime.UtcNow.Subtract(_lastClick).TotalMilliseconds < 500) { return(false); } if (ElementIsVisible(uiElement, name)) { if (!string.IsNullOrEmpty(name)) { Log.Debug("{0} button is visible", name); } else { Log.Debug("{0}={1} is visible", uiElement.Hash, uiElement.Name); } if (!clickTimer.IsRunning && delayOption == ClickDelay.Delay) { clickTimer.Start(); SetClickTimerRandomVal(); } else if ((ClickTimerRandomReady() && ElementIsVisible(uiElement, name)) || delayOption == ClickDelay.NoDelay) { if (!string.IsNullOrEmpty(name)) { Log.Info("Clicking {0} button", name); } else { Log.Info("Clicking {0}={1}", uiElement.Hash, uiElement.Name); } // sleep plugins for a bit if (ZetaDia.IsInGame && fireWorldTransferStart) { GameEvents.FireWorldTransferStart(); } _lastClick = DateTime.UtcNow; uiElement.Click(); BotMain.PauseFor(TimeSpan.FromMilliseconds(ClickThreadSleepInterval)); if (postClickThreadSleepDuration > 0) { BotMain.PauseFor(TimeSpan.FromMilliseconds(postClickThreadSleepDuration)); } clickTimer.Reset(); } else { Log.Debug("Pausing bot, waiting for {0}={1}", uiElement.Hash, uiElement.Name); BotMain.PauseWhile(ClickTimerRandomNotReady, 0, ClickTimerTimeout); } } return(true); } catch (Exception ex) { Log.Info("Error clicking UI button {0}: " + ex, name); return(false); } }
public void OnPulse() { if (!LastLoop.IsRunning) { LastLoop.Start(); } if (!LastFullEvaluation.IsRunning) { LastFullEvaluation.Start(); } if (!ZetaDia.IsInGame || !ZetaDia.Me.IsValid || ZetaDia.Me.IsDead || ZetaDia.IsLoadingWorld) { return; } AnimationState aState = ZetaDia.Me.CommonData.AnimationState; if (aState == AnimationState.Attacking || aState == AnimationState.Casting || aState == AnimationState.Channeling || aState == AnimationState.Dead || aState == AnimationState.TakingDamage) { return; } // FUGLY HACK // DB .302+ runs through the stashing routine like Flash Gordon... Can't use a soft hook like the Potion method... // TODO: Look into overloading the TownRun routine and appending stash checks on TownRuns... if (Zeta.Internals.UIElements.StashWindow.IsVisible) { // Stash Checks Diagnostic("UIElement Detected: StashWindow, Initiating Stash Checks..."); if (bCheckStash) { // Spam Prevention (Can not run more than once per 3 minutes) double _tempLastStashCheck = DateTime.Now.Subtract(_lastStashCheck).TotalSeconds; Diagnostic("Last potion was purchased " + _tempLastStashCheck + " seconds ago"); if (_tempLastStashCheck < 180) { Diagnostic("CheckPotions can not run again for another " + (180 - _tempLastStashCheck) + " seconds"); } else { BotMain.PauseWhile(CheckStash, 0, new TimeSpan?(TimeSpan.FromSeconds(30.0))); } } } // Spam Prevention (Can not run more than once per 3 Seconds) if (LastLoop.ElapsedMilliseconds > 3000) { LastLoop.Restart(); try { if (LastFullEvaluation.ElapsedMilliseconds > 300000) { LastFullEvaluation.Restart(); bNeedFullItemUpdate = true; } if (currentLevel != ZetaDia.Me.Level) { LastFullEvaluation.Restart(); bNeedFullItemUpdate = true; currentLevel = ZetaDia.Me.Level; } if (Zeta.Internals.UIElements.VendorWindow.IsVisible) { // Vendor Checks Diagnostic("UIElement Detected: VendorWindow, Initiating Potion Checks..."); if (bBuyPots) { // Spam Prevention (Can not run more than once per 1 minute) double _tempLastBuy = DateTime.Now.Subtract(_lastBuy).TotalSeconds; Diagnostic("Last potion was purchased " + _tempLastBuy + " seconds ago"); if (_tempLastBuy < 60) { Diagnostic("CheckPotions can not run again for another " + (60 - _tempLastBuy) + " seconds"); } else { BotMain.PauseWhile(CheckPotions, 0, new TimeSpan?(TimeSpan.FromSeconds(30.0))); } } } else if (Zeta.Internals.UIElements.StashWindow.IsVisible) { // Stash Checks // Moved outside of the spam prevention loop... So that it will check on every pulse.. } else { // Backpack Checks CheckBackpack(); } } catch (System.AccessViolationException ex) { // Maybe someday the DB core will stop throwing this error.... O_o throw; } catch (Exception ex) { Log("An exception occured: " + ex.ToString()); //throw; } } }
/// <summary> /// Find fresh targets, start main BehaviorTree if needed, cast any buffs needed etc. /// </summary> /// <param name="ret"></param> /// <returns></returns> internal static bool CheckHasTarget(object ret) { using (new PerformanceLogger("Trinity.CheckHasTarget")) { // If we aren't in the game or a world is loading, don't do anything yet if (!ZetaDia.IsInGame || !ZetaDia.Me.IsValid || ZetaDia.IsLoadingWorld) { return(false); } if (ZetaDia.Me.IsDead) { GoldInactivity.ResetCheckGold(); } else if (GoldInactivity.GoldInactive()) { BotMain.PauseWhile(GoldInactivity.GoldInactiveLeaveGame); return(false); } if (lastWorldId != PlayerStatus.WorldID) { ISearchAreaProvider mgp = Navigator.SearchGridProvider; } if (!HotbarRefreshTimer.IsRunning) { HotbarRefreshTimer.Start(); } if (!HasMappedPlayerAbilities || HotbarRefreshTimer.ElapsedMilliseconds > 10000 || ShouldRefreshHotbarAbilities) { // Update the cached player's cache ActorClass tempClass = ActorClass.Invalid; try { tempClass = PlayerStatus.ActorClass; } catch { DbHelper.Log(TrinityLogLevel.Verbose, LogCategory.GlobalHandler, "Safely handled exception trying to get character class."); } GilesPlayerCache.RefreshHotbar(); dictAbilityRepeatDelay = new Dictionary <SNOPower, int>(dictAbilityRepeatDefaults); if (ZetaDia.CPlayer.PassiveSkills.Contains(SNOPower.Wizard_Passive_CriticalMass) && PlayerStatus.ActorClass == ActorClass.Wizard) { dictAbilityRepeatDelay[SNOPower.Wizard_FrostNova] = 25; dictAbilityRepeatDelay[SNOPower.Wizard_ExplosiveBlast] = 25; dictAbilityRepeatDelay[SNOPower.Wizard_DiamondSkin] = 100; dictAbilityRepeatDelay[SNOPower.Wizard_SlowTime] = 6000; dictAbilityRepeatDelay[SNOPower.Wizard_WaveOfForce] = 1500; dictAbilityRepeatDelay[SNOPower.Wizard_MirrorImage] = 1500; dictAbilityRepeatDelay[SNOPower.Wizard_Archon_ArcaneBlast] = 1500; dictAbilityRepeatDelay[SNOPower.Wizard_Teleport] = 2700; dictAbilityRepeatDelay[SNOPower.Wizard_Archon_SlowTime] = 1500; dictAbilityRepeatDelay[SNOPower.Wizard_Archon_Teleport] = 2700; } if (PlayerStatus.ActorClass == ActorClass.WitchDoctor && ZetaDia.CPlayer.PassiveSkills.Contains(SNOPower.Witchdoctor_Passive_GraveInjustice)) { dictAbilityRepeatDelay[SNOPower.Witchdoctor_SoulHarvest] = 1000; dictAbilityRepeatDelay[SNOPower.Witchdoctor_SpiritWalk] = 1000; dictAbilityRepeatDelay[SNOPower.Witchdoctor_Horrify] = 1000; dictAbilityRepeatDelay[SNOPower.Witchdoctor_Gargantuan] = 20000; dictAbilityRepeatDelay[SNOPower.Witchdoctor_SummonZombieDog] = 20000; dictAbilityRepeatDelay[SNOPower.Witchdoctor_GraspOfTheDead] = 500; dictAbilityRepeatDelay[SNOPower.Witchdoctor_SpiritBarrage] = 2000; dictAbilityRepeatDelay[SNOPower.Witchdoctor_Locust_Swarm] = 2000; dictAbilityRepeatDelay[SNOPower.Witchdoctor_Haunt] = 2000; dictAbilityRepeatDelay[SNOPower.Witchdoctor_Hex] = 3000; dictAbilityRepeatDelay[SNOPower.Witchdoctor_MassConfusion] = 15000; dictAbilityRepeatDelay[SNOPower.Witchdoctor_FetishArmy] = 20000; dictAbilityRepeatDelay[SNOPower.Witchdoctor_BigBadVoodoo] = 20000; } if (PlayerStatus.ActorClass == ActorClass.Barbarian && ZetaDia.CPlayer.PassiveSkills.Contains(SNOPower.Barbarian_Passive_BoonOfBulKathos)) { dictAbilityRepeatDelay[SNOPower.Barbarian_Earthquake] = 90500; dictAbilityRepeatDelay[SNOPower.Barbarian_CallOfTheAncients] = 90500; dictAbilityRepeatDelay[SNOPower.Barbarian_WrathOfTheBerserker] = 90500; } // Pick an appropriate health set etc. based on class switch (PlayerStatus.ActorClass) { case ActorClass.Barbarian: // What health % should we use a potion, or look for a globe PlayerEmergencyHealthPotionLimit = Settings.Combat.Barbarian.PotionLevel; PlayerEmergencyHealthGlobeLimit = Settings.Combat.Barbarian.HealthGlobeLevel; PlayerKiteDistance = Settings.Combat.Barbarian.KiteLimit; break; case ActorClass.Monk: // What health % should we use a potion, or look for a globe PlayerEmergencyHealthPotionLimit = Settings.Combat.Monk.PotionLevel; PlayerEmergencyHealthGlobeLimit = Settings.Combat.Monk.HealthGlobeLevel; // Monks never kite :) PlayerKiteDistance = 0; break; case ActorClass.Wizard: // What health % should we use a potion, or look for a globe PlayerEmergencyHealthPotionLimit = Settings.Combat.Wizard.PotionLevel; PlayerEmergencyHealthGlobeLimit = Settings.Combat.Wizard.HealthGlobeLevel; PlayerKiteDistance = Settings.Combat.Wizard.KiteLimit; break; case ActorClass.WitchDoctor: // What health % should we use a potion, or look for a globe PlayerEmergencyHealthPotionLimit = Settings.Combat.WitchDoctor.PotionLevel; PlayerEmergencyHealthGlobeLimit = Settings.Combat.WitchDoctor.HealthGlobeLevel; PlayerKiteDistance = Settings.Combat.WitchDoctor.KiteLimit; break; case ActorClass.DemonHunter: // What health % should we use a potion, or look for a globe PlayerEmergencyHealthPotionLimit = Settings.Combat.DemonHunter.PotionLevel; PlayerEmergencyHealthGlobeLimit = Settings.Combat.DemonHunter.HealthGlobeLevel; PlayerKiteDistance = Settings.Combat.DemonHunter.KiteLimit; break; } } // Clear target current and reset key variables used during the target-handling function //CurrentTarget = null; bDontMoveMeIAmDoingShit = false; TimesBlockedMoving = 0; IsAlreadyMoving = false; lastMovementCommand = DateTime.Today; IsWaitingForPower = false; IsWaitingAfterPower = false; IsWaitingForPotion = false; wasRootedLastTick = false; ClearBlacklists(); using (new PerformanceLogger("CheckHasTarget.RefreshCache")) { // Refresh Cache if needed bool CacheWasRefreshed = RefreshDiaObjectCache(); } // We have a target, start the target handler! if (CurrentTarget != null) { IsWholeNewTarget = true; bDontMoveMeIAmDoingShit = true; ShouldPickNewAbilities = true; return(true); } //Monk_MaintainTempestRush(); // Pop a potion when necessary if (PlayerStatus.CurrentHealthPct <= PlayerEmergencyHealthPotionLimit) { if (!PlayerStatus.IsIncapacitated && GilesUseTimer(SNOPower.DrinkHealthPotion)) { ACDItem thisBestPotion = ZetaDia.Me.Inventory.Backpack.Where(i => i.IsPotion).OrderByDescending(p => p.HitpointsGranted).ThenBy(p => p.ItemStackQuantity).FirstOrDefault(); if (thisBestPotion != null) { WaitWhileAnimating(4, true); ZetaDia.Me.Inventory.UseItem((thisBestPotion.DynamicId)); } dictAbilityLastUse[SNOPower.DrinkHealthPotion] = DateTime.Now; WaitWhileAnimating(3, true); } } sStatusText = "[Trinity] No more targets - DemonBuddy/profile management is now in control"; if (Settings.Advanced.DebugInStatusBar && bResetStatusText) { bResetStatusText = false; BotMain.StatusText = sStatusText; } // Nothing to do... do we have some maintenance we can do instead, like out of combat buffing? if (DateTime.Now.Subtract(lastMaintenanceCheck).TotalMilliseconds > 150) { lastMaintenanceCheck = DateTime.Now; // Out of combat buffing etc. but only if we don't want to return to town etc. ACDAnimationInfo myAnimationState = ZetaDia.Me.CommonData.AnimationInfo; if (!PlayerStatus.IsInTown && !IsReadyToTownRun && !ForceVendorRunASAP && myAnimationState != null && myAnimationState.State != AnimationState.Attacking && myAnimationState.State != AnimationState.Casting && myAnimationState.State != AnimationState.Channeling) { bDontSpamOutofCombat = false; powerBuff = AbilitySelector(false, true, false); if (powerBuff.SNOPower != SNOPower.None) { WaitWhileAnimating(4, true); DbHelper.Log(TrinityLogLevel.Verbose, LogCategory.Behavior, "Using OOC Buff: {0}", powerBuff.SNOPower.ToString()); if (powerBuff.WaitTicksBeforeUse > 0) { BotMain.PauseFor(new TimeSpan(0, 0, 0, 0, (int)powerBuff.WaitBeforeUseDelay)); } ZetaDia.Me.UsePower(powerBuff.SNOPower, powerBuff.TargetPosition, powerBuff.TargetDynamicWorldId, powerBuff.TargetRActorGUID); LastPowerUsed = powerBuff.SNOPower; dictAbilityLastUse[powerBuff.SNOPower] = DateTime.Now; if (powerBuff.WaitTicksAfterUse > 0) { BotMain.PauseFor(new TimeSpan(0, 0, 0, 0, (int)powerBuff.WaitAfterUseDelay)); } WaitWhileAnimating(3, true); } } else if (myAnimationState != null) { // Check if we are portalling to town, if so increase our kill radius temporarily switch (myAnimationState.Current) { case SNOAnim.barbarian_male_HTH_Recall_Channel_01: case SNOAnim.Barbarian_Female_HTH_Recall_Channel_01: case SNOAnim.Monk_Male_recall_channel: case SNOAnim.Monk_Female_recall_channel: case SNOAnim.WitchDoctor_Male_recall_channel: case SNOAnim.WitchDoctor_Female_recall_channel: case SNOAnim.Wizard_Male_HTH_recall_channel: case SNOAnim.Wizard_Female_HTH_recall_channel: case SNOAnim.Demonhunter_Male_HTH_recall_channel: case SNOAnim.Demonhunter_Female_HTH_recall_channel: iKeepKillRadiusExtendedFor = 20; timeKeepKillRadiusExtendedUntil = DateTime.Now.AddSeconds(iKeepKillRadiusExtendedFor); break; } } } CurrentTarget = null; if ((GilesTrinity.ForceVendorRunASAP || GilesTrinity.IsReadyToTownRun) && TownRun.TownRunTimerRunning()) { DbHelper.Log(TrinityLogLevel.Normal, LogCategory.UserInformation, "Waiting for town run timer", true); return(true); } // Ok let DemonBuddy do stuff this loop, since we're done for the moment //DbHelper.Log(TrinityLogLevel.Verbose, LogCategory.GlobalHandler, sStatusText); return(false); } }
private void CheckBackpack() { // Call a Zeta update ZetaDia.Actors.Update(); // Exit if we have null data if (ZetaDia.Actors.Me == null) { return; } // Exit if our player level is already at 60 - don't want to mess with expert player backpacks and lose items! if (bDisable60 && (ZetaDia.Actors.Me.Level < 1 || ZetaDia.Actors.Me.Level > 59)) { return; } // See if we need to refresh all our equipment points if (bNeedFullItemUpdate) { iCurrentDamage = GearCheck.instance.GetDamage(); iCurrentEHP = GearCheck.instance.GetEHP(); Diagnostic("[**PACK**] Current points = " + getValue(iCurrentDamage, iCurrentEHP).ToString()); bNeedFullItemUpdate = false; _alreadyLookedAtBlacklist.Clear(); } // Do a full equipped items update? // Loop through anything in the backpack that we haven't already checked foreach (ACDItem thisitem in ZetaDia.Actors.Me.Inventory.Backpack) { if (thisitem.BaseAddress == IntPtr.Zero) { return; } // Check this item is of the necessary item level (if not don't blacklist it until it is!) if (thisitem.RequiredLevel <= currentLevel && !thisitem.IsUnidentified) { // Make sure we haven't already analysed this item previously if (!_alreadyLookedAtBlacklist.Contains(thisitem)) { // Prevent this item ever being looked at again _alreadyLookedAtBlacklist.Add(thisitem); Diagnostic(String.Format("[**PACK**] Evaluating item '{0}'", thisitem.Name)); Dictionary <GearCheck.RatoshInventorySlot, ACDItem> currentEquipped = GearCheck.instance.getPlayerEquipped(); Dictionary <GearCheck.RatoshInventorySlot, double> replaceDamage = GearCheck.instance.EvaluateDamage(thisitem, currentEquipped); Dictionary <GearCheck.RatoshInventorySlot, double> replaceEHP = GearCheck.instance.EvaluateEHP(thisitem, currentEquipped); GearCheck.RatoshInventorySlot bestReplacement = GearCheck.RatoshInventorySlot.Unknown; GearCheck.RatoshInventorySlot bestReplacement2 = GearCheck.RatoshInventorySlot.Unknown; ACDItem bestReplacement2Equip = null; double tempBestDamage = 0; double tempBestEHP = 0; foreach (GearCheck.RatoshInventorySlot key in replaceDamage.Keys) { double tempDamage; double tempEHP; if (replaceDamage.TryGetValue(key, out tempDamage) && replaceEHP.TryGetValue(key, out tempEHP)) { if (getValue(tempBestDamage, tempBestEHP) < getValue(tempDamage, tempEHP)) { bestReplacement = key; tempBestDamage = tempDamage; tempBestEHP = tempEHP; } } } if (bestReplacement != GearCheck.RatoshInventorySlot.Unknown) { if (((bestReplacement == GearCheck.RatoshInventorySlot.PlayerRightHand || bestReplacement == GearCheck.RatoshInventorySlot.PlayerLeftHand) && currentEquipped.ContainsKey(GearCheck.RatoshInventorySlot.PlayerTwoHand)) || (bestReplacement == GearCheck.RatoshInventorySlot.PlayerTwoHand || bestReplacement == GearCheck.RatoshInventorySlot.PlayerRightHandSpecial)) { Dictionary <GearCheck.RatoshInventorySlot, ACDItem> currentEquipped2 = GearCheck.instance.fakeEquip(currentEquipped, bestReplacement, thisitem); foreach (ACDItem otherItem in _alreadyLookedAtBlacklist) { Dictionary <GearCheck.RatoshInventorySlot, double> replaceDamage2 = GearCheck.instance.EvaluateDamage(otherItem, currentEquipped2); Dictionary <GearCheck.RatoshInventorySlot, double> replaceEHP2 = GearCheck.instance.EvaluateEHP(otherItem, currentEquipped2); foreach (GearCheck.RatoshInventorySlot key in replaceDamage.Keys) { double tempDamage2; double tempEHP2; if (bestReplacement == GearCheck.RatoshInventorySlot.PlayerRightHandSpecial) { if (key != GearCheck.RatoshInventorySlot.PlayerLeftHand || key != GearCheck.RatoshInventorySlot.PlayerTwoHand) { continue; } } if (bestReplacement == GearCheck.RatoshInventorySlot.PlayerTwoHand) { if (key != GearCheck.RatoshInventorySlot.PlayerRightHandSpecial) { continue; } } if (bestReplacement == GearCheck.RatoshInventorySlot.PlayerRightHand) { if (key != GearCheck.RatoshInventorySlot.PlayerLeftHand) { continue; } } if (bestReplacement == GearCheck.RatoshInventorySlot.PlayerLeftHand) { if (key != GearCheck.RatoshInventorySlot.PlayerRightHand || key != GearCheck.RatoshInventorySlot.PlayerRightHandSpecial) { continue; } } if (replaceDamage2.TryGetValue(key, out tempDamage2) && replaceEHP2.TryGetValue(key, out tempEHP2)) { Diagnostic(String.Format("[**PACK**] Eval points {0}", getValue(tempDamage2, tempEHP2))); if (getValue(tempBestDamage, tempBestEHP) < getValue(tempDamage2, tempEHP2)) { bestReplacement2Equip = otherItem; bestReplacement2 = key; tempBestDamage = tempDamage2; tempBestEHP = tempEHP2; } } } } } } Log(String.Format("[**PACK**] Evaluated item '{0}'[{1}] (points={2})", thisitem.Name, bestReplacement.ToString(), getValue(tempBestDamage, tempBestEHP).ToString())); if (getValue(iCurrentDamage, iCurrentEHP) < getValue(tempBestDamage, tempBestEHP)) { if (InventorySlotProtected(bestReplacement.ToString())) { Log(String.Format("[**PACK**] InvSlot: '{0}' is Protected. Can not equip item '{1}'.", bestReplacement, thisitem.Name)); return; } if (InventorySlotProtected(bestReplacement2.ToString())) { Log(String.Format("[**PACK**] InvSlot: '{0}' is Protected. Can not equip item '{1}'.", bestReplacement2, thisitem.Name)); return; } if (!Zeta.Internals.UIElements.InventoryWindow.IsVisible) { Diagnostic("[**PACK**] Opening UIElement: Inventory"); Zeta.Internals.UIElements.BackgroundScreenPCButtonInventory.Click(); } Log(String.Format("[**PACK**] Equip item '{0}' (old points={1}, new points={2})", thisitem.Name, getValue(iCurrentDamage, iCurrentEHP).ToString(), getValue(tempBestDamage, tempBestEHP).ToString())); iCurrentDamage = tempBestDamage; iCurrentEHP = tempBestEHP; GearCheck.instance.equip(bestReplacement, thisitem); if (bestReplacement2 != GearCheck.RatoshInventorySlot.Unknown) { GearCheck.instance.equip(bestReplacement2, bestReplacement2Equip); } if (Zeta.Internals.UIElements.InventoryWindow.IsVisible) { Diagnostic("[**PACK**] Closing UIElement: Inventory"); Zeta.Internals.UIElements.BackgroundScreenPCButtonInventory.Click(); } } } } } if (bIdentifyItems) { // Look for unidentified items if not in combat and not already identifying if (CombatTargeting.Instance.FirstNpc != null) { return; } if (ZetaDia.Me.LoopingAnimationEndTime != 0) { return; } if (GetUnidentifiedItems().Count() > 0) { Log("[**PACK**] Pausing bot while we identify items"); BotMain.PauseWhile(identifyItems, 0, GetBotPauseTimeSpan()); } else if (DateTime.Now.Subtract(lastIdentify).TotalMilliseconds < 5000 && Zeta.Internals.UIElements.InventoryWindow.IsVisible) { Zeta.Internals.UIElements.BackgroundScreenPCButtonInventory.Click(); Log("[**PACK**] Closing Inventory Window"); } } return; } // CheckBackpack
/// <summary> /// Receive Pulse event from DemonBuddy. /// </summary> public void OnPulse() { try { if (ZetaDia.Me == null) { return; } if (!ZetaDia.IsInGame || !ZetaDia.Me.IsValid || ZetaDia.IsLoadingWorld) { return; } //ScenesStorage.Update(); using (new PerformanceLogger("OnPulse")) { //if (IsMoveRequested) // NavServerReport(); GameUI.SafeClickUIButtons(); if (ZetaDia.Me.IsDead) { return; } using (new PerformanceLogger("LazyRaiderClickToPause")) { if (Settings.Advanced.LazyRaiderClickToPause && !BotMain.IsPaused) { BotMain.PauseWhile(MouseLeft); } } // See if we should update the stats file if (DateTime.UtcNow.Subtract(ItemDropStats.ItemStatsLastPostedReport).TotalSeconds > 10) { ItemDropStats.ItemStatsLastPostedReport = DateTime.UtcNow; ItemDropStats.OutputReport(); } // Recording of all the XML's in use this run UsedProfileManager.RecordProfile(); DebugUtil.LogOnPulse(); Gamble.CheckShouldTownRunForGambling(); MonkCombat.RunOngoingPowers(); } } catch (AccessViolationException) { // woof! } catch (Exception ex) { Logger.Log(LogCategory.UserInformation, "Exception in Pulse: {0}", ex.ToString()); } }
private void Send(string data, bool pause = false, bool xml = false, int retry = 1, int timeout = 3000) { var success = false; var tries = 0; if (!xml) { data = _bs.Pid + ":" + data; } else { data += "\nEND"; } // Pause bot if (pause) { _recieved = false; Func <bool> waitFor = Recieved; BotMain.PauseWhile(waitFor, 0, TimeSpan.FromMilliseconds((retry * timeout) + 3000)); } while (!success && tries < retry) { try { tries++; using (var client = new NamedPipeClientStream(".", "YetAnotherRelogger")) { client.Connect(timeout); if (client.IsConnected) { var sw = new StreamWriter(client) { AutoFlush = true }; var sr = new StreamReader(client); sw.WriteLine(data); var connectionTime = DateTime.Now; while (client.IsConnected) { if (DateTime.Now.Subtract(connectionTime).TotalSeconds > 10) { client.Close(); break; } var temp = sr.ReadLine(); if (temp == null) { continue; } HandleResponse(temp); success = true; client.Close(); } } else { // Failed to connect } } } catch (Exception ex) { LogException(ex); } } _recieved = true; }
/// <summary> /// Initializes the Reset commands. /// </summary> private void InitializeResetCommand() { try { ResetMiscCommand = new RelayCommand( (parameter) => { _Model.Combat.Misc.Reset(); }); ResetBarbCommand = new RelayCommand( (parameter) => { _Model.Combat.Barbarian.Reset(); _Model.Combat.AvoidanceRadius.Reset(); }); ResetCrusaderCommand = new RelayCommand( (parameter) => { _Model.Combat.Crusader.Reset(); _Model.Combat.AvoidanceRadius.Reset(); }); ResetMonkCommand = new RelayCommand( (parameter) => { _Model.Combat.Monk.Reset(); _Model.Combat.AvoidanceRadius.Reset(); }); ResetWizardCommand = new RelayCommand( (parameter) => { _Model.Combat.Wizard.Reset(); _Model.Combat.AvoidanceRadius.Reset(); }); ResetWitchDoctorCommand = new RelayCommand( (parameter) => { _Model.Combat.WitchDoctor.Reset(); _Model.Combat.AvoidanceRadius.Reset(); }); ResetDemonHunterCommand = new RelayCommand( (parameter) => { _Model.Combat.DemonHunter.Reset(); _Model.Combat.AvoidanceRadius.Reset(); }); ResetWorldObjectCommand = new RelayCommand( (parameter) => { _Model.WorldObject.Reset(); }); ResetItemCommand = new RelayCommand( (parameter) => { _Model.Loot.Pickup.Reset(); }); ResetItemRulesCommand = new RelayCommand( (parameter) => { _Model.Loot.ItemRules.Reset(); }); ReloadScriptRulesCommand = new RelayCommand( (parameter) => { try { _Model.CopyTo(_OriginalModel); _OriginalModel.Save(); if (Trinity.StashRule == null) { Trinity.StashRule = new ItemRules.Interpreter(); } if (Trinity.StashRule != null) { BotMain.PauseWhile(Trinity.StashRule.reloadFromUI); } } catch (Exception ex) { Logger.Log("Exception in ReloadScriptRulesCommand: {0}", ex); } } ); ResetTownRunCommand = new RelayCommand( (parameter) => { _Model.Loot.TownRun.Reset(); }); ResetAdvancedCommand = new RelayCommand( (parameter) => { _Model.Advanced.Reset(); }); ResetNotificationCommand = new RelayCommand( (parameter) => { _Model.Notification.Reset(); }); ResetAllCommand = new RelayCommand( (parameter) => { _Model.Reset(); }); } catch (Exception ex) { Logger.LogError("Exception initializing commands {0}", ex); } }
/// <summary> /// Find fresh targets, start main BehaviorTree if needed, cast any buffs needed etc. /// </summary> /// <param name="ret"></param> /// <returns></returns> internal static bool TargetCheck(object ret) { using (new PerformanceLogger("TargetCheck")) { // If we aren't in the game or a world is loading, don't do anything yet if (!ZetaDia.IsInGame || !ZetaDia.Me.IsValid || ZetaDia.IsLoadingWorld) { return(false); } // We keep dying because we're spawning in AoE and next to 50 elites and we need to just leave the game if (DateTime.UtcNow.Subtract(Trinity.LastDeathTime).TotalSeconds < 30 && ZetaDia.Me.Inventory.Equipped.Any() && ZetaDia.Me.Inventory.Equipped.Average(i => i.DurabilityPercent) < 0.05 && !ZetaDia.IsInTown) { Logger.Log("Durability is zero, emergency leave game"); ZetaDia.Service.Party.LeaveGame(true); Thread.Sleep(11000); return(false); } if (ZetaDia.Me.IsDead) { return(false); } if (GoldInactivity.Instance.GoldInactive()) { BotMain.PauseWhile(GoldInactivity.Instance.GoldInactiveLeaveGame); return(false); } if (!HotbarRefreshTimer.IsRunning) { HotbarRefreshTimer.Start(); } if (!HasMappedPlayerAbilities || HotbarRefreshTimer.ElapsedMilliseconds > 1000 || ShouldRefreshHotbarAbilities) { PlayerInfoCache.RefreshHotbar(); // Pick an appropriate health set etc. based on class switch (Player.ActorClass) { case ActorClass.Barbarian: PlayerEmergencyHealthPotionLimit = Settings.Combat.Barbarian.PotionLevel; _playerEmergencyHealthGlobeLimit = Settings.Combat.Barbarian.HealthGlobeLevel; CombatBase.PlayerKiteDistance = Settings.Combat.Barbarian.KiteLimit; CombatBase.PlayerKiteMode = Config.Combat.KiteMode.Never; break; case ActorClass.Crusader: PlayerEmergencyHealthPotionLimit = Settings.Combat.Crusader.PotionLevel; _playerEmergencyHealthGlobeLimit = Settings.Combat.Crusader.HealthGlobeLevel; CombatBase.PlayerKiteDistance = 0; CombatBase.PlayerKiteMode = Config.Combat.KiteMode.Never; break; case ActorClass.Monk: PlayerEmergencyHealthPotionLimit = Settings.Combat.Monk.PotionLevel; _playerEmergencyHealthGlobeLimit = Settings.Combat.Monk.HealthGlobeLevel; // Monks never kite :) CombatBase.PlayerKiteDistance = 0; CombatBase.PlayerKiteMode = Config.Combat.KiteMode.Never; break; case ActorClass.Wizard: PlayerEmergencyHealthPotionLimit = Settings.Combat.Wizard.PotionLevel; _playerEmergencyHealthGlobeLimit = Settings.Combat.Wizard.HealthGlobeLevel; CombatBase.PlayerKiteDistance = Settings.Combat.Wizard.KiteLimit; CombatBase.PlayerKiteMode = Config.Combat.KiteMode.Always; break; case ActorClass.Witchdoctor: PlayerEmergencyHealthPotionLimit = Settings.Combat.WitchDoctor.PotionLevel; _playerEmergencyHealthGlobeLimit = Settings.Combat.WitchDoctor.HealthGlobeLevel; CombatBase.PlayerKiteDistance = Settings.Combat.WitchDoctor.KiteLimit; CombatBase.PlayerKiteMode = Config.Combat.KiteMode.Always; break; case ActorClass.DemonHunter: PlayerEmergencyHealthPotionLimit = Settings.Combat.DemonHunter.PotionLevel; _playerEmergencyHealthGlobeLimit = Settings.Combat.DemonHunter.HealthGlobeLevel; CombatBase.PlayerKiteDistance = Settings.Combat.DemonHunter.KiteLimit; CombatBase.PlayerKiteMode = Settings.Combat.DemonHunter.KiteMode; break; } } // Clear target current and reset key variables used during the target-handling function //CurrentTarget = null; DontMoveMeIAmDoingShit = false; _timesBlockedMoving = 0; IsAlreadyMoving = false; lastMovementCommand = DateTime.MinValue; _isWaitingForPower = false; _isWaitingAfterPower = false; _isWaitingForPotion = false; wasRootedLastTick = false; ClearBlacklists(); using (new PerformanceLogger("TargetCheck.RefreshCache")) { // Refresh Cache if needed RefreshDiaObjectCache(); } // We have a target, start the target handler! if (CurrentTarget != null) { _isWholeNewTarget = true; DontMoveMeIAmDoingShit = true; _shouldPickNewAbilities = true; return(true); } // if we just opened a horadric cache, wait around to open it if (DateTime.UtcNow.Subtract(Composites.LastFoundHoradricCache).TotalSeconds < 5) { return(true); } using (new PerformanceLogger("TargetCheck.OOCPotion")) { // Pop a potion when necessary if (Player.CurrentHealthPct <= PlayerEmergencyHealthPotionLimit) { Trinity.UsePotionIfNeeded(); } } _statusText = "[Trinity] No more targets - DemonBuddy/profile management is now in control"; if (Settings.Advanced.DebugInStatusBar && _resetStatusText) { _resetStatusText = false; BotMain.StatusText = _statusText; } // Nothing to do... do we have some maintenance we can do instead, like out of combat buffing? if (DateTime.UtcNow.Subtract(lastMaintenanceCheck).TotalMilliseconds > 150) { using (new PerformanceLogger("TargetCheck.OOCBuff")) { lastMaintenanceCheck = DateTime.UtcNow; bool isLoopingAnimation = ZetaDia.Me.LoopingAnimationEndTime > 0; if (!isLoopingAnimation && !IsReadyToTownRun && !ForceVendorRunASAP) { BarbarianCombat.AllowSprintOOC = true; DisableOutofCombatSprint = false; powerBuff = AbilitySelector(false, true, false); if (powerBuff.SNOPower != SNOPower.None) { Logger.Log(TrinityLogLevel.Verbose, LogCategory.Behavior, "Using OOC Buff: {0}", powerBuff.SNOPower.ToString()); if (powerBuff.WaitTicksBeforeUse > 0) { BotMain.PauseFor(new TimeSpan(0, 0, 0, 0, (int)powerBuff.WaitBeforeUseDelay)); } ZetaDia.Me.UsePower(powerBuff.SNOPower, powerBuff.TargetPosition, powerBuff.TargetDynamicWorldId, powerBuff.TargetACDGUID); LastPowerUsed = powerBuff.SNOPower; CacheData.AbilityLastUsed[powerBuff.SNOPower] = DateTime.UtcNow; if (powerBuff.WaitTicksAfterUse > 0) { BotMain.PauseFor(new TimeSpan(0, 0, 0, 0, (int)powerBuff.WaitAfterUseDelay)); } } } else if (isLoopingAnimation) { _keepKillRadiusExtendedForSeconds = 20; _timeKeepKillRadiusExtendedUntil = DateTime.UtcNow.AddSeconds(_keepKillRadiusExtendedForSeconds); } } } CurrentTarget = null; if ((Trinity.ForceVendorRunASAP || Trinity.IsReadyToTownRun) && TownRun.TownRunTimerRunning()) { Logger.Log(TrinityLogLevel.Info, LogCategory.UserInformation, "Waiting for town run timer (Target Check)", true); return(true); } // Ok let DemonBuddy do stuff this loop, since we're done for the moment //DbHelper.Log(TrinityLogLevel.Verbose, LogCategory.GlobalHandler, sStatusText); return(false); } }
/// <summary> /// Initializes the Reset commands. /// </summary> private void InitializeResetCommand() { ResetMiscCommand = new RelayCommand( (parameter) => { _Model.Combat.Misc.Reset(); }); ResetBarbCommand = new RelayCommand( (parameter) => { _Model.Combat.Barbarian.Reset(); _Model.Combat.AvoidanceRadius.Reset(); }); ResetMonkCommand = new RelayCommand( (parameter) => { _Model.Combat.Monk.Reset(); _Model.Combat.AvoidanceRadius.Reset(); }); ResetWizardCommand = new RelayCommand( (parameter) => { _Model.Combat.Wizard.Reset(); _Model.Combat.AvoidanceRadius.Reset(); }); ResetWitchDoctorCommand = new RelayCommand( (parameter) => { _Model.Combat.WitchDoctor.Reset(); _Model.Combat.AvoidanceRadius.Reset(); }); ResetDemonHunterCommand = new RelayCommand( (parameter) => { _Model.Combat.DemonHunter.Reset(); _Model.Combat.AvoidanceRadius.Reset(); }); ResetWorldObjectCommand = new RelayCommand( (parameter) => { _Model.WorldObject.Reset(); }); ResetItemCommand = new RelayCommand( (parameter) => { _Model.Loot.Pickup.Reset(); }); ResetItemRulesCommand = new RelayCommand( (parameter) => { _Model.Loot.ItemRules.Reset(); }); ReloadScriptRulesCommand = new RelayCommand( (parameter) => { BotMain.PauseWhile(GilesTrinity.StashRule.reloadFromUI); } ); ResetTownRunCommand = new RelayCommand( (parameter) => { _Model.Loot.TownRun.Reset(); }); ResetAdvancedCommand = new RelayCommand( (parameter) => { _Model.Advanced.Reset(); }); ResetNotificationCommand = new RelayCommand( (parameter) => { _Model.Notification.Reset(); }); ResetAllCommand = new RelayCommand( (parameter) => { _Model.Reset(); }); }