Exemple #1
0
        public static void ResetEverythingNewGame()
        {
            hashUseOnceID                          = new HashSet <int>();
            dictUseOnceID                          = new Dictionary <int, int>();
            iMaxDeathsAllowed                      = 0;
            iDeathsThisRun                         = 0;
            _hashsetItemStatsLookedAt              = new HashSet <string>();
            _hashsetItemPicksLookedAt              = new HashSet <string>();
            _hashsetItemFollowersIgnored           = new HashSet <string>();
            TownRun._dictItemStashAttempted        = new Dictionary <int, int>();
            hashRGUIDBlacklist60                   = new HashSet <int>();
            hashRGUIDBlacklist90                   = new HashSet <int>();
            hashRGUIDBlacklist15                   = new HashSet <int>();
            vBacktrackList                         = new SortedList <int, Vector3>();
            iTotalBacktracks                       = 0;
            HasMappedPlayerAbilities               = false;
            PlayerMover.iTotalAntiStuckAttempts    = 1;
            PlayerMover.vSafeMovementLocation      = Vector3.Zero;
            PlayerMover.vOldPosition               = Vector3.Zero;
            PlayerMover.iTimesReachedStuckPoint    = 0;
            PlayerMover.TimeLastRecordedPosition   = DateTime.Today;
            PlayerMover.LastGeneratedStuckPosition = DateTime.Today;
            PlayerMover.iTimesReachedMaxUnstucks   = 0;
            PlayerMover.iCancelUnstuckerForSeconds = 0;
            PlayerMover._lastCancelledUnstucker    = DateTime.Today;
            NavHelper.UsedStuckSpots               = new List <GridPoint>();

            // Reset all the caches
            dictGilesObjectTypeCache     = new Dictionary <int, GObjectType>();
            dictGilesMonsterAffixCache   = new Dictionary <int, MonsterAffixes>();
            dictGilesMaxHealthCache      = new Dictionary <int, double>();
            dictGilesLastHealthCache     = new Dictionary <int, double>();
            dictGilesLastHealthChecked   = new Dictionary <int, int>();
            dictGilesBurrowedCache       = new Dictionary <int, bool>();
            dictGilesActorSNOCache       = new Dictionary <int, int>();
            dictGilesACDGUIDCache        = new Dictionary <int, int>();
            dictGilesInternalNameCache   = new Dictionary <int, string>();
            dictGilesGameBalanceIDCache  = new Dictionary <int, int>();
            dictGilesDynamicIDCache      = new Dictionary <int, int>();
            dictGilesVectorCache         = new Dictionary <int, Vector3>();
            dictGilesGoldAmountCache     = new Dictionary <int, int>();
            dictGilesQualityCache        = new Dictionary <int, ItemQuality>();
            dictGilesPickupItem          = new Dictionary <int, bool>();
            dictSummonedByID             = new Dictionary <int, int>();
            dictTotalInteractionAttempts = new Dictionary <int, int>();
            listProfilesLoaded           = new List <string>();
            CurrentProfile = "";
            FirstProfile   = "";


            NavHelper.UpdateSearchGridProvider();
            GoldInactivity.ResetCheckGold();

            global::GilesTrinity.XmlTags.TrinityLoadOnce.UsedProfiles = new List <string>();

            GenericCache.ClearCache();
            GenericBlacklist.ClearBlacklist();
        }
Exemple #2
0
        /// <summary>
        /// Called when user Enable the plugin.
        /// </summary>
        public void OnEnabled()
        {
            BotMain.OnStart += TrinityBotStart;
            BotMain.OnStop  += TrinityBotStop;

            // Set up the pause button

            // rrrix: removing for next DB beta...
            //Application.Current.Dispatcher.Invoke(PaintMainWindowButtons());

            SetWindowTitle();

            if (!Directory.Exists(FileManager.PluginPath))
            {
                DbHelper.Log(TrinityLogLevel.Normal, LogCategory.UserInformation, "Fatal Error - cannot enable plugin. Invalid path: {0}", FileManager.PluginPath);
                DbHelper.Log(TrinityLogLevel.Normal, LogCategory.UserInformation, "Please check you have installed the plugin to the correct location, and then restart DemonBuddy and re-enable the plugin.");
                DbHelper.Log(TrinityLogLevel.Normal, LogCategory.UserInformation, @"Plugin should be installed to \<DemonBuddyFolder>\Plugins\Trinity\");
            }
            else
            {
                HasMappedPlayerAbilities = false;
                IsPluginEnabled          = true;

                // Settings are available after this...
                LoadConfiguration();

                Navigator.PlayerMover = new PlayerMover();
                SetUnstuckProvider();
                GameEvents.OnPlayerDied += TrinityOnDeath;
                GameEvents.OnGameJoined += TrinityOnJoinGame;
                GameEvents.OnGameLeft   += TrinityOnLeaveGame;

                GameEvents.OnItemSold     += TrinityOnItemSold;
                GameEvents.OnItemSalvaged += TrinityOnItemSalvaged;
                GameEvents.OnItemStashed  += TrinityOnItemStashed;

                GameEvents.OnGameChanged += GameEvents_OnGameChanged;

                if (NavProvider == null)
                {
                    NavProvider = new DefaultNavigationProvider();
                }

                // enable or disable process exit events
                //ZetaDia.Memory.Process.EnableRaisingEvents = false;



                CombatTargeting.Instance.Provider   = new BlankCombatProvider();
                LootTargeting.Instance.Provider     = new BlankLootProvider();
                ObstacleTargeting.Instance.Provider = new BlankObstacleProvider();

                if (Settings.Loot.ItemFilterMode != global::GilesTrinity.Settings.Loot.ItemFilterMode.DemonBuddy)
                {
                    ItemManager.Current = new TrinityItemManager();
                }
                NavHelper.UpdateSearchGridProvider();

                // Safety check incase DB "OnStart" event didn't fire properly
                if (BotMain.IsRunning)
                {
                    TrinityBotStart(null);
                    if (ZetaDia.IsInGame)
                    {
                        TrinityOnJoinGame(null, null);
                    }
                }

                SetBotTPS();

                TrinityPowerManager.LoadLegacyDelays();

                DbHelper.Log(TrinityLogLevel.Normal, LogCategory.UserInformation, "*******************TRINITY*****************", Description);;
                DbHelper.Log(TrinityLogLevel.Normal, LogCategory.UserInformation, "ATIVADO: {0} carregado - mod by WAR!", Description);;
                DbHelper.Log(TrinityLogLevel.Normal, LogCategory.UserInformation, "*******************TRINITY*****************", Description);;
            }

            if (StashRule != null)
            {
                // reseting stash rules
                StashRule.reset();
            }
        }
Exemple #3
0
        /// <summary>
        /// This method will add and update necessary information about all available actors. Determines GilesObjectType, sets ranges, updates blacklists, determines avoidance, kiting, target weighting
        /// and the result is we will have a new target for the Target Handler. Returns true if the cache was refreshed.
        /// </summary>
        /// <returns>True if the cache was updated</returns>
        public static bool RefreshDiaObjectCache(bool forceUpdate = false)
        {
            using (new PerformanceLogger("RefreshDiaObjectCache"))
            {
                if (DateTime.Now.Subtract(LastRefreshedCache).TotalMilliseconds < Settings.Advanced.CacheRefreshRate && !forceUpdate)
                {
                    if (!UpdateCurrentTarget())
                    {
                        return(false);
                    }
                }
                LastRefreshedCache = DateTime.Now;

                using (new PerformanceLogger("RefreshDiaObjectCache.UpdateBlock"))
                {
                    GenericCache.MaintainCache();
                    GenericBlacklist.MaintainBlacklist();

                    using (ZetaDia.Memory.AcquireFrame())
                    {
                        // Update player-data cache, including buffs
                        GilesPlayerCache.UpdateCachedPlayerData();

                        if (PlayerStatus.CurrentHealthPct <= 0)
                        {
                            return(false);
                        }

                        if (Settings.Combat.Misc.UseNavMeshTargeting && !gp.CanStandAt(gp.WorldToGrid(PlayerStatus.CurrentPosition.ToVector2())))
                        {
                            NavHelper.UpdateSearchGridProvider();
                        }


                        RefreshCacheInit();

                        // Now pull up all the data and store anything we want to handle in the super special cache list
                        // Also use many cache dictionaries to minimize DB<->D3 memory hits, and speed everything up a lot
                        RefreshCacheMainLoop();
                    }
                }

                // Reduce ignore-for-loops counter
                if (IgnoreTargetForLoops > 0)
                {
                    IgnoreTargetForLoops--;
                }
                // If we have an avoidance under our feet, then create a new object which contains a safety point to move to
                // But only if we aren't force-cancelling avoidance for XX time
                bool bFoundSafeSpot = false;

                using (new PerformanceLogger("RefreshDiaObjectCache.AvoidanceCheck"))
                {
                    // Note that if treasure goblin level is set to kamikaze, even avoidance moves are disabled to reach the goblin!
                    if (StandingInAvoidance && (!AnyTreasureGoblinsPresent || Settings.Combat.Misc.GoblinPriority <= GoblinPriority.Prioritize) &&
                        DateTime.Now.Subtract(timeCancelledEmergencyMove).TotalMilliseconds >= cancelledEmergencyMoveForMilliseconds)
                    {
                        Vector3 vAnySafePoint = NavHelper.FindSafeZone(false, 1, PlayerStatus.CurrentPosition, true);
                        // Ignore avoidance stuff if we're incapacitated or didn't find a safe spot we could reach
                        if (vAnySafePoint != vNullLocation)
                        {
                            if (Settings.Advanced.LogCategories.HasFlag(LogCategory.Movement))
                            {
                                DbHelper.Log(TrinityLogLevel.Verbose, LogCategory.Movement, "Kiting Avoidance: {0} Distance: {1:0} Direction: {2:0}, Health%={3:0.00}, KiteDistance: {4:0}",
                                             vAnySafePoint, vAnySafePoint.Distance(Me.Position), MathUtil.GetHeading(MathUtil.FindDirectionDegree(Me.Position, vAnySafePoint)),
                                             PlayerStatus.CurrentHealthPct, PlayerKiteDistance);
                            }

                            bFoundSafeSpot = true;
                            CurrentTarget  = new GilesObject()
                            {
                                Position       = vAnySafePoint,
                                Type           = GObjectType.Avoidance,
                                Weight         = 20000,
                                CentreDistance = Vector3.Distance(PlayerStatus.CurrentPosition, vAnySafePoint),
                                RadiusDistance = Vector3.Distance(PlayerStatus.CurrentPosition, vAnySafePoint),
                                InternalName   = "GilesSafePoint"
                            };;
                        }
                        //else
                        //{
                        //    // Didn't find any safe spot we could reach, so don't look for any more safe spots for at least 2.8 seconds
                        //    cancelledEmergencyMoveForMilliseconds = 2800;
                        //    timeCancelledEmergencyMove = DateTime.Now;
                        //    DbHelper.Log(TrinityLogLevel.Verbose, LogCategory.Movement, "Unable to find kite location, canceling emergency movement for {0}ms", cancelledEmergencyMoveForMilliseconds);
                        //}
                    }
                }

                /*
                 * Give weights to objects
                 */
                // Special flag for special whirlwind circumstances
                bAnyNonWWIgnoreMobsInRange = false;
                // Now give each object a weight *IF* we aren't skipping direcly to a safe-spot
                if (!bFoundSafeSpot)
                {
                    RefreshDiaGetWeights();
                    RefreshSetKiting(ref vKitePointAvoid, NeedToKite, ref TryToKite);
                }
                // Not heading straight for a safe-spot?
                // No valid targets but we were told to stay put?
                if (CurrentTarget == null && ShouldStayPutDuringAvoidance && !StandingInAvoidance)
                {
                    CurrentTarget = new GilesObject()
                    {
                        Position       = PlayerStatus.CurrentPosition,
                        Type           = GObjectType.Avoidance,
                        Weight         = 20000,
                        CentreDistance = 2f,
                        RadiusDistance = 2f,
                        InternalName   = "GilesStayPutPoint"
                    };
                    DbHelper.Log(TrinityLogLevel.Debug, LogCategory.CacheManagement, "Staying Put During Avoidance");
                }
                using (new PerformanceLogger("RefreshDiaObjectCache.FinalChecks"))
                {
                    // force to stay put if we want to town run and there's no target
                    if (CurrentTarget == null && ForceVendorRunASAP)
                    {
                        bDontMoveMeIAmDoingShit = true;
                    }

                    // Still no target, let's see if we should backtrack or wait for wrath to come off cooldown...
                    if (CurrentTarget == null)
                    {
                        RefreshDoBackTrack();
                    }
                    // Still no target, let's end it all!
                    if (CurrentTarget == null)
                    {
                        return(true);
                    }
                    // Ok record the time we last saw any unit at all
                    if (CurrentTarget.Type == GObjectType.Unit)
                    {
                        lastHadUnitInSights = DateTime.Now;
                        // And record when we last saw any form of elite
                        if (CurrentTarget.IsBoss || CurrentTarget.IsEliteRareUnique || CurrentTarget.IsTreasureGoblin)
                        {
                            lastHadEliteUnitInSights = DateTime.Now;
                        }
                    }
                    // Record the last time our target changed
                    if (CurrentTargetRactorGUID != CurrentTarget.RActorGuid)
                    {
                        RecordTargetHistory();
                        DbHelper.Log(TrinityLogLevel.Verbose, LogCategory.Weight, "Found New Target - {0} CurrentTargetRactorGUID: {1} CurrentTarget.RActorGuid: {2}",
                                     DateTime.Now, CurrentTargetRactorGUID, CurrentTarget.RActorGuid);
                        dateSincePickedTarget = DateTime.Now;
                        iTargetLastHealth     = 0f;
                    }
                    else
                    {
                        // We're sticking to the same target, so update the target's health cache to check for stucks
                        if (CurrentTarget.Type == GObjectType.Unit)
                        {
                            // Check if the health has changed, if so update the target-pick time before we blacklist them again
                            if (CurrentTarget.HitPointsPct != iTargetLastHealth)
                            {
                                DbHelper.Log(TrinityLogLevel.Verbose, LogCategory.Weight, "Keeping Target {0} - CurrentTarget.iHitPoints: {1:0.00}  iTargetLastHealth: {2:0.00} ",
                                             CurrentTarget.RActorGuid, CurrentTarget.HitPointsPct, iTargetLastHealth);
                                dateSincePickedTarget = DateTime.Now;
                            }
                            // Now store the target's last-known health
                            iTargetLastHealth = CurrentTarget.HitPointsPct;
                        }
                    }
                }
                // We have a target and the cached was refreshed
                return(true);
            }
        }
Exemple #4
0
        /// <summary>
        /// This is wired up by Plugin.OnEnabled, and called when the bot is started
        /// </summary>
        /// <param name="bot"></param>
        private static void TrinityBotStart(IBot bot)
        {
            // Recording of all the XML's in use this run
            try
            {
                string sThisProfile = Zeta.CommonBot.Settings.GlobalSettings.Instance.LastProfile;
                if (sThisProfile != CurrentProfile)
                {
                    listProfilesLoaded.Add(sThisProfile);
                    CurrentProfile = sThisProfile;
                    if (FirstProfile == "")
                    {
                        FirstProfile = sThisProfile;
                    }
                }
            }
            catch { }
            // Update actors if possible (if already in-game)
            if (ZetaDia.IsInGame && !ZetaDia.IsLoadingWorld && ZetaDia.Actors != null)
            {
                ZetaDia.Actors.Update();
                NavHelper.UpdateSearchGridProvider(true);
            }
            HasMappedPlayerAbilities = false;
            if (!bMaintainStatTracking)
            {
                ItemStatsWhenStartedBot   = DateTime.Now;
                ItemStatsLastPostedReport = DateTime.Now;
                bMaintainStatTracking     = true;
            }
            else
            {
                DbHelper.Log(TrinityLogLevel.Normal, LogCategory.UserInformation, "Note: Maintaining item stats from previous run. To reset stats fully, please restart DB.");
            }

            UsedProfileManager.RefreshProfileBlacklists();

            ReplaceTreeHooks();

            PlayerMover.TimeLastRecordedPosition = DateTime.Now;
            PlayerMover.timeLastRestartedGame    = DateTime.Now;
            GoldInactivity.ResetCheckGold();

            if (Zeta.CommonBot.Settings.CharacterSettings.Instance.KillRadius < 20)
            {
                DbHelper.Log(TrinityLogLevel.Normal, LogCategory.UserInformation, "WARNING: Low Kill Radius detected, currently set to: {0} (you can change this through Demonbuddy bot settings)",
                             Zeta.CommonBot.Settings.CharacterSettings.Instance.KillRadius);
            }

            if (Zeta.CommonBot.Settings.CharacterSettings.Instance.LootRadius < 50)
            {
                DbHelper.Log(TrinityLogLevel.Normal, LogCategory.UserInformation, "WARNING: Low Gold Loot Radius detected, currently set to: {0} (you can change this through Demonbuddy bot settings)",
                             Zeta.CommonBot.Settings.CharacterSettings.Instance.LootRadius);
            }

            if (StashRule == null)
            {
                StashRule = new ItemRules.Interpreter();
            }

            StashRule.readConfiguration();
        }
        /// <summary>
        /// Update the cached data on the player information, including buffs if needed
        /// </summary>
        internal static void UpdateCachedPlayerData()
        {
            using (new PerformanceLogger("UpdateCachedPlayerData"))
            {
                if (DateTime.Now.Subtract(PlayerStatus.LastUpdated).TotalMilliseconds <= 100)
                {
                    return;
                }
                // If we aren't in the game of a world is loading, don't do anything yet
                if (!ZetaDia.IsInGame || ZetaDia.IsLoadingWorld)
                {
                    return;
                }
                var me = ZetaDia.Me;
                if (me == null)
                {
                    return;
                }

                try
                {
                    PlayerStatus.LastUpdated    = DateTime.Now;
                    PlayerStatus.IsInTown       = me.IsInTown;
                    PlayerStatus.IsDead         = me.IsDead;
                    PlayerStatus.IsInGame       = ZetaDia.IsInGame;
                    PlayerStatus.IsLoadingWorld = ZetaDia.IsLoadingWorld;

                    PlayerStatus.IsIncapacitated = (me.IsFeared || me.IsStunned || me.IsFrozen || me.IsBlind);
                    PlayerStatus.IsRooted        = me.IsRooted;

                    PlayerStatus.CurrentHealthPct     = me.HitpointsCurrentPct;
                    PlayerStatus.PrimaryResource      = me.CurrentPrimaryResource;
                    PlayerStatus.PrimaryResourcePct   = PlayerStatus.PrimaryResource / me.MaxPrimaryResource;
                    PlayerStatus.SecondaryResource    = me.CurrentSecondaryResource;
                    PlayerStatus.SecondaryResourcePct = PlayerStatus.SecondaryResource / me.MaxSecondaryResource;
                    PlayerStatus.CurrentPosition      = me.Position;

                    PlayerStatus.GoldPickupRadius = me.GoldPickupRadius;
                    PlayerStatus.Coinage          = me.Inventory.Coinage;

                    if (PlayerStatus.PrimaryResource >= GilesTrinity.MinEnergyReserve)
                    {
                        PlayerStatus.WaitingForReserveEnergy = false;
                    }
                    if (PlayerStatus.PrimaryResource < 20)
                    {
                        PlayerStatus.WaitingForReserveEnergy = true;
                    }


                    PlayerStatus.MyDynamicID = me.CommonData.DynamicId;
                    PlayerStatus.Level       = me.Level;
                    PlayerStatus.ActorClass  = me.ActorClass;
                    PlayerStatus.BattleTag   = ZetaDia.Service.CurrentHero.BattleTagName;
                    PlayerStatus.LevelAreaId = ZetaDia.CurrentLevelAreaId;

                    if (PlayerStatus.ActorClass == ActorClass.WitchDoctor && HotbarSkills.AssignedSkills.Any(s => s.Power == SNOPower.Witchdoctor_Hex && s.RuneIndex == 1))
                    {
                        PlayerStatus.IsHidden = me.IsHidden;
                    }
                    else
                    {
                        PlayerStatus.IsHidden = false;
                    }

                    if (DateTime.Now.Subtract(PlayerStatus.Scene.LastUpdate).TotalMilliseconds > 1000 && GilesTrinity.Settings.Combat.Misc.UseNavMeshTargeting)
                    {
                        int CurrentSceneSNO = -1;
                        CurrentSceneSNO = (int)ZetaDia.Me.SceneId;
                        if (PlayerStatus.SceneId != CurrentSceneSNO)
                        {
                            PlayerStatus.SceneId = CurrentSceneSNO;
                            DbHelper.Log(TrinityLogLevel.Debug, LogCategory.CacheManagement, "Updating Grid Provider", true);
                            NavHelper.UpdateSearchGridProvider();
                        }
                    }

                    // World ID safety caching incase it's ever unavailable
                    GilesTrinity.CurrentWorldDynamicId = ZetaDia.CurrentWorldDynamicId;
                    PlayerStatus.WorldDynamicID        = ZetaDia.CurrentWorldDynamicId;
                    PlayerStatus.WorldID             = ZetaDia.CurrentWorldId;
                    GilesTrinity.cachedStaticWorldId = ZetaDia.CurrentWorldId;
                    // Game difficulty, used really for vault on DH's
                    GilesTrinity.iCurrentGameDifficulty = ZetaDia.Service.CurrentHero.CurrentDifficulty;

                    // Refresh player buffs (to check for archon)
                    RefreshBuffs();
                }
                catch (Exception ex)
                {
                    DbHelper.Log(TrinityLogLevel.Debug, LogCategory.CacheManagement, "Safely handled exception for grabbing player data.{0}{1}", Environment.NewLine, ex);
                }
            }
        }