Пример #1
0
        public static async Task <bool> Execute()
        {
            if (Core.Settings.Items.StashTreasureBags)
            {
                return(false);
            }

            var bagsOpened = 0;

            if (Core.Player.IsInTown)
            {
                foreach (var item in InventoryManager.Backpack.ToList())
                {
                    if (item.GetRawItemType() == RawItemType.TreasureBag)
                    {
                        Core.Logger.Log($"Opening Treasure Bag {bagsOpened + 1}, Id={item.AnnId}");
                        InventoryManager.UseItem(item.AnnId);
                        bagsOpened++;
                        await Coroutine.Yield();
                    }
                }
                if (bagsOpened > 0)
                {
                    Core.Logger.Log($"Waiting for Treasure Bag loot");
                    await Coroutine.Yield();

                    BrainBehavior.ForceTownrun(nameof(OpenTreasureBags));
                    return(true);
                }
            }
            return(false);
        }
Пример #2
0
 private bool TownRun()
 {
     Logger.Debug("[TownRun] BrainBehavior.IsVendoring is {0}", BrainBehavior.IsVendoring);
     Logger.Debug("[TownRun] ZetaDia.Me.IsParticipatingInTieredLootRun is {0}", ZetaDia.Me.IsParticipatingInTieredLootRun);
     Logger.Debug("[TownRun] AdvDia.RiftQuest.State is {0}", AdvDia.RiftQuest.State);
     Logger.Debug("[TownRun] AdvDia.RiftQuest.Step is {0}", AdvDia.RiftQuest.Step);
     DisablePulse();
     if (BrainBehavior.IsVendoring)
     {
         return(false);
     }
     if (!_townRunInitiated)
     {
         _townRunInitiated = true;
         BrainBehavior.ForceTownrun(" We need it.", true);
         return(false);
     }
     _townRunInitiated = false;
     if (AdvDia.RiftQuest.Step == RiftStep.Completed)
     {
         State = States.WaitForRiftCountdown;
         Logger.Info("[Rift] Tick tock, tick tock...");
     }
     else
     {
         State = States.NotStarted;
         _moveToRiftStoneCoroutine.Reset();
     }
     return(false);
 }
Пример #3
0
 protected override Composite CreateBehavior()
 {
     return(new Action(ret =>
     {
         BrainBehavior.ForceTownrun("Town-run request received, will town-run at next possible moment.");
         m_IsDone = true;
     }));
 }
Пример #4
0
        private static void RecompilePlugins()
        {
            if (BotMain.IsRunning)
            {
                BotMain.Stop(false, "Recompiling Plugin!");
                while (BotMain.BotThread.IsAlive)
                {
                    Thread.Sleep(0);
                }
            }

            var EnabledPlugins = PluginManager.GetEnabledPlugins().ToArray();

            foreach (var p in PluginManager.Plugins)
            {
                p.Enabled = false;
            }

            PluginManager.ShutdownAllPlugins();

            Logger.DBLog.DebugFormat("Disposing All Routines");
            foreach (var r in RoutineManager.Routines)
            {
                r.Dispose();
            }



            string sDemonBuddyPath    = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            string sTrinityPluginPath = FolderPaths.PluginPath;

            CodeCompiler FunkyCode = new CodeCompiler(sTrinityPluginPath);

            //FunkyCode.ParseFilesForCompilerOptions();
            Logger.DBLog.DebugFormat("Recompiling Funky Bot");
            FunkyCode.Compile();
            Logger.DBLog.DebugFormat(FunkyCode.CompiledToLocation);

            Logger.DBLog.DebugFormat("Clearing all treehooks");
            TreeHooks.Instance.ClearAll();

            Logger.DBLog.DebugFormat("Disposing of current bot");
            BotMain.CurrentBot.Dispose();

            Logger.DBLog.DebugFormat("Removing old Assemblies");
            CodeCompiler.DeleteOldAssemblies();

            BrainBehavior.CreateBrain();

            Logger.DBLog.DebugFormat("Reloading Plugins");
            PluginManager.ReloadAllPlugins(sDemonBuddyPath + @"\Plugins\");

            Logger.DBLog.DebugFormat("Enabling Plugins");
            PluginManager.SetEnabledPlugins(EnabledPlugins);

            Logger.DBLog.DebugFormat("Reloading Routines");
            RoutineManager.Reload();
        }
Пример #5
0
 /// <summary>
 /// If the leader is currently vendoring, start a town run on this bot as well.
 /// </summary>
 public static async Task <bool> StartTownRunWithLeader()
 {
     if (AutoFollow.CurrentLeader.IsVendoring && !Player.IsVendoring)
     {
         BrainBehavior.ForceTownrun("Townrun with Leader");
         return(true);
     }
     return(false);
 }
Пример #6
0
        public static async Task <bool> RunRift(RiftType riftType,
                                                int maxLevel,
                                                int maxEmpowerLevel,
                                                bool shouldEmpower,
                                                bool runNormalUntilXP)
        {
            if (!ZetaDia.IsInGame ||
                ZetaDia.Globals.IsLoadingWorld ||
                ZetaDia.Globals.IsPlayingCutscene)
            {
                return(false);
            }

            CoroutineResult previousResult;

            if ((previousResult = await TurnInQuest()) == CoroutineResult.Running)
            {
                return(false);
            }

            if (BrainBehavior.IsVendoring &&
                previousResult != CoroutineResult.NoAction)
            {
                return(false);
            }

            // TODO: Decide if we want to run the cow level
            //if (!await ClearCowLevel())
            //    return false;

            if (!await OpenRift(
                    riftType,
                    maxLevel,
                    maxEmpowerLevel,
                    shouldEmpower,
                    runNormalUntilXP))
            {
                return(false);
            }

            if (!await ClearRift())
            {
                return(false);
            }

            if (await UpgradeGems() == CoroutineResult.Running)
            {
                return(false);
            }

            s_logger.Information("Rift done, let's force a town run...");
            BrainBehavior.ForceTownrun(nameof(RiftCoroutine));
            PreviousWorld = SNOWorld.Invalid;
            PreviousLevel = SNOLevelArea.Invalid;
            return(true);
        }
Пример #7
0
        public override RunStatus Interact()
        {
            //Only validate if we can pickup if slots are minimum
            if (Bot.Character.Data.FreeBackpackSlots <= 8)
            {
                if (ref_DiaItem != null && ref_DiaItem.BaseAddress != IntPtr.Zero)
                {
                    if (!BrainBehavior.CanPickUpItem(ref_DiaItem))
                    {
                        TownRunManager.bFailedToLootLastItem = true;
                        BrainBehavior.ForceTownrun("No more space to pickup item");
                        return(RunStatus.Success);
                    }
                }
                else
                {
                    return(RunStatus.Success);
                }
            }

            // Force waiting for global cooldown timer or long-animation abilities
            if (Bot.Character.Class.PowerPrime.WaitLoopsBefore >= 1)
            {
                //Logger.DBLog.DebugFormat("Debug: Force waiting BEFORE Ability " + powerPrime.powerThis.ToString() + "...");
                Bot.Targeting.Cache.bWaitingForPower = true;
                if (Bot.Character.Class.PowerPrime.WaitLoopsBefore >= 1)
                {
                    Bot.Character.Class.PowerPrime.WaitLoopsBefore--;
                }
                return(RunStatus.Running);
            }
            Bot.Targeting.Cache.bWaitingForPower = false;

            if (!Bot.Targeting.Cache.ShouldCheckItemLooted)
            {
                Bot.Targeting.Cache.ShouldCheckItemLooted = true;
                Bot.Character.Data.BackPack.Update();
                if (Bot.Character.Data.BackPack.CacheItemList.ContainsKey(AcdGuid.Value))
                {
                    Bot.Targeting.Cache.CheckItemLootStackCount = Bot.Character.Data.BackPack.CacheItemList[AcdGuid.Value].ThisItemStackQuantity;
                }
            }

            // Pick the item up the usepower way, and "blacklist" for a couple of loops
            Bot.Character.Data.WaitWhileAnimating(20);
            ZetaDia.Me.UsePower(SNOPower.Axe_Operate_Gizmo, Vector3.Zero, Bot.Character.Data.iCurrentWorldID, AcdGuid.Value);
            Bot.NavigationCache.lastChangedZigZag        = DateTime.Today;
            Bot.NavigationCache.vPositionLastZigZagCheck = Vector3.Zero;



            Bot.Character.Data.WaitWhileAnimating(5, true);
            return(RunStatus.Running);
        }
Пример #8
0
        internal static void ResetTreehooks()
        {
            Navigator.PlayerMover               = new DefaultPlayerMover();
            Navigator.StuckHandler              = new DefaultStuckHandler();
            CombatTargeting.Instance.Provider   = new DefaultCombatTargetingProvider();
            LootTargeting.Instance.Provider     = new DefaultLootTargetingProvider();
            ObstacleTargeting.Instance.Provider = new DefaultObstacleTargetingProvider();

            BrainBehavior.CreateCombatLogic();
            BrainBehavior.CreateLootBehavior();
            BrainBehavior.CreateVendorBehavior();
        }
Пример #9
0
        protected override Composite CreateBehavior()
        {
            return(new Action(ret =>
            {
                if (!BrainBehavior.IsVendoring && (ZetaDia.Me.Inventory.NumFreeBackpackSlots <= SlotsUnused || Backpack.ShouldRepairItems(MinimumDurability)))
                {
                    BrainBehavior.ForceTownrun("Forcing Town Run!");
                }

                m_IsDone = true;
            }));
        }
Пример #10
0
 /// <summary>
 /// If the leader is currently vendoring, start a town run on this bot as well.
 /// </summary>
 public static async Task <bool> StartTownRunWithLeader()
 {
     if (AutoFollow.CurrentLeader.IsVendoring && !Player.IsVendoring)
     {
         if (DateTime.UtcNow.Subtract(_lastTownRunWithLeaderTime).TotalSeconds > 5)
         {
             BrainBehavior.ForceTownrun("Townrun with Leader");
             _lastTownRunWithLeaderTime = DateTime.UtcNow;
             return(true);
         }
     }
     return(false);
 }
Пример #11
0
        private static void RecompilePlugins()
        {
            if (BotMain.IsRunning)
            {
                BotMain.Stop(false, "Recompiling Plugin!");
                while (BotMain.BotThread.IsAlive)
                {
                    Thread.Sleep(0);
                }
            }

            var EnabledPlugins = PluginManager.GetEnabledPlugins().ToArray();

            PluginManager.ShutdownAllPlugins();

            DBLog.DebugFormat("Removing Funky from plugins");
            while (PluginManager.Plugins.Any(p => p.Plugin.Name == "Funky"))
            {
                PluginManager.Plugins.Remove(PluginManager.Plugins.First(p => p.Plugin.Name == "Funky"));
            }

            DBLog.DebugFormat("Clearing all treehooks");
            TreeHooks.Instance.ClearAll();

            DBLog.DebugFormat("Disposing of current bot");
            BotMain.CurrentBot.Dispose();

            DBLog.DebugFormat("Removing old Assemblies");
            CodeCompiler.DeleteOldAssemblies();

            string sDemonBuddyPath    = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            string sTrinityPluginPath = sDemonBuddyPath + @"\Plugins\FunkyBot\";

            CodeCompiler FunkyCode = new CodeCompiler(sTrinityPluginPath);

            FunkyCode.ParseFilesForCompilerOptions();
            DBLog.DebugFormat("Recompiling Funky Plugin");
            FunkyCode.Compile();
            DBLog.DebugFormat(FunkyCode.CompiledToLocation);



            TreeHooks.Instance.ClearAll();
            BrainBehavior.CreateBrain();

            DBLog.DebugFormat("Reloading Plugins");
            PluginManager.ReloadAllPlugins(sDemonBuddyPath + @"\Plugins\");

            DBLog.DebugFormat("Enabling Plugins");
            PluginManager.SetEnabledPlugins(EnabledPlugins);
        }
Пример #12
0
        public static async Task <bool> Execute()
        {
            if (!ZetaDia.IsInTown)
            {
                IsDumpingShards = false;
            }

            try
            {
                while (CanRun() && (!ShouldSaveShards || IsDumpingShards))
                {
                    IsDumpingShards = true;

                    var distance = Town.Locations.Kadala.Distance(ZetaDia.Me.Position);
                    if (distance > 8f && !await MoveToAndInteract.Execute(Town.Locations.Kadala, Town.ActorIds.Kadala, 3f))
                    {
                        Logger.Log("[Gamble] Failed to move to Kadala, quite unfortunate.");
                        break;
                    }

                    if (CanBuyItems)
                    {
                        await BuyItem();
                    }
                    else
                    {
                        Resources.GameUI.CloseVendorWindow();
                    }

                    if (!TrinityItemManager.IsAnyTwoSlotBackpackLocation)
                    {
                        BrainBehavior.ForceTownrun();
                    }

                    await Coroutine.Sleep(100);

                    await Coroutine.Yield();
                }
            }
            catch (Exception ex)
            {
                Logger.LogError("Exception in Gamble.Execute, {0}", ex);

                if (ex is CoroutineStoppedException)
                {
                    throw;
                }
            }

            return(true);
        }
Пример #13
0
        public static async Task <bool> Execute()
        {
            if (!ZetaDia.IsInTown)
            {
                IsDumpingShards = false;
            }

            try
            {
                while (CanRun() && (!StillSavingShards || IsDumpingShards))
                {
                    IsDumpingShards = true;
                    if ((TownInfo.Kadala.Distance > 8f || !UIElements.VendorWindow.IsVisible) && !await MoveToAndInteract.Execute(TownInfo.Kadala))
                    {
                        Core.Logger.Log("[Gamble] Failed to move to Kadala, quite unfortunate.");
                        break;
                    }

                    if (CanBuyItems)
                    {
                        await BuyItem();
                    }
                    else
                    {
                        GameUI.CloseVendorWindow();
                    }

                    if (TrinityCombat.Loot.IsBackpackFull)
                    {
                        BrainBehavior.ForceTownrun();
                    }

                    await Coroutine.Sleep(100);

                    await Coroutine.Yield();
                }
            }
            catch (Exception ex)
            {
                Core.Logger.Error("Exception in Gamble.Execute, {0}", ex);

                if (ex is CoroutineStoppedException)
                {
                    throw;
                }
            }

            GameUI.CloseVendorWindow();

            return(true);
        }
Пример #14
0
        public override RunStatus Interact()
        {
            //Only validate if we can pickup if slots are minimum
            if (FunkyGame.Hero.FreeBackpackSlots <= 8)
            {
                if (ref_DiaItem != null && ref_DiaItem.BaseAddress != IntPtr.Zero)
                {
                    if (!Backpack.CanPickupItem(IsTwoSlot))//(!BrainBehavior.CanPickUpItem(ref_DiaItem))
                    {
                        FunkyGame.Targeting.Cache.bFailedToLootLastItem = true;
                        BrainBehavior.ForceTownrun("No more space to pickup item");
                        return(RunStatus.Success);
                    }
                }
                else
                {
                    return(RunStatus.Success);
                }
            }

            // Force waiting for global cooldown timer or long-animation abilities
            if (FunkyGame.Hero.Class.PowerPrime.WaitLoopsBefore >= 1)
            {
                //Logger.DBLog.DebugFormat("Debug: Force waiting BEFORE Ability " + powerPrime.powerThis.ToString() + "...");
                FunkyGame.Targeting.Cache.bWaitingForPower = true;
                if (FunkyGame.Hero.Class.PowerPrime.WaitLoopsBefore >= 1)
                {
                    FunkyGame.Hero.Class.PowerPrime.WaitLoopsBefore--;
                }
                return(RunStatus.Running);
            }
            FunkyGame.Targeting.Cache.bWaitingForPower = false;

            //This does the inital update of backpack so we can verify loot success during target handler
            if (!FunkyGame.Targeting.Cache.ShouldCheckItemLooted)
            {
                FunkyGame.Targeting.Cache.ShouldCheckItemLooted = true;
                Backpack.UpdateItemList();
            }

            // Pick the item up the usepower way, and "blacklist" for a couple of loops
            FunkyGame.Hero.WaitWhileAnimating(20);
            ZetaDia.Me.UsePower(SNOPower.Axe_Operate_Gizmo, Vector3.Zero, FunkyGame.Hero.CurrentWorldDynamicID, AcdGuid.Value);
            FunkyGame.Navigation.lastChangedZigZag        = DateTime.Today;
            FunkyGame.Navigation.vPositionLastZigZagCheck = Vector3.Zero;



            FunkyGame.Hero.WaitWhileAnimating(5, true);
            return(RunStatus.Running);
        }
Пример #15
0
        public static async Task <CoroutineResult> SalvageItems()
        {
            if (!ZetaDia.IsInTown)
            {
                return(CoroutineResult.NoAction);
            }

            var itemsToSalvage = InventoryManager.Backpack.Where(ShouldSalvage).ToList();

            s_logger.Debug($"[{nameof(SalvageItems)}] Starting salvage for {itemsToSalvage.Count} items");
            itemsToSalvage.ForEach(i => s_logger.Debug($"[{nameof(SalvageItems)}] Salvaging: {(SNOActor)i.ActorSnoId} ({i.ActorSnoId}) InternalName={i.InternalName} Ann={i.AnnId}"));

            return(await BrainBehavior.DoSalvage(itemsToSalvage));
        }
Пример #16
0
        public static void CheckShouldTownRunForGambling()
        {
            if (!ZetaDia.IsInTown)
            {
                IsDumpingShards = false;
            }

            if (Trinity.Trinity.Settings.Gambling.ShouldTownRun && ZetaDia.CPlayer.BloodshardCount >= Math.Min(Trinity.Trinity.Settings.Gambling.SaveShardsThreshold, Trinity.Trinity.Player.MaxBloodShards))
            {
                if (CanRun() && !ShouldSaveShards && !TownRun.IsTryingToTownPortal() && !BrainBehavior.IsVendoring)
                {
                    BrainBehavior.ForceTownrun("Bloodshard Spending Threshold");
                }
            }
        }
Пример #17
0
        public override void Start()
        {
            Navigator.PlayerMover                  = new SlideMover();
            Navigator.NavigationProvider           = new ServiceNavigationProvider();
            GameSettingsManager.FaceTargetOnAction = true;
            GameSettingsManager.FlightMode         = true;
            TreeHooks.Instance.ClearAll();
            this.composite = BrainBehavior.CreateBrain();
            CharacterSettings.Instance.AutoEquip = FatebotSettings.Instance.UseAutoEquip;
            TreeHooks.Instance.ReplaceHook("SelectPoiType", this.SelectPoiType());
            TreeHooks.Instance.AddHook("PoiAction", this.SetFatePoi());
            TreeHooks.Instance.AddHook("PoiAction2", this.SetRestPoi());
            TreeHooks.Instance.AddHook("TreeStart", this.BotLogic);

            CombatTargeting.Instance.Provider = new ExFateCombatTargetingProvider();             // TODO Make new targeting
            FateData = null;
        }
Пример #18
0
        public void Start()
        {
            Navigator.NavigationProvider      = new ServiceNavigationProvider();
            Navigator.PlayerMover             = new SlideMover();
            CombatTargeting.Instance.Provider = new OracleCombatTargetingProvider();

            playerFaceTargetOnAction = GameSettingsManager.FaceTargetOnAction;
            playerFlightMode         = GameSettingsManager.FlightMode;
            GameSettingsManager.FaceTargetOnAction = true;
            GameSettingsManager.FlightMode         = true;

            TreeHooks.Instance.ClearAll();
            root = BrainBehavior.CreateBrain();
            SetUpHooks();

            LogCurrentMode();
            WarnAboutPotentialIssues();
        }
Пример #19
0
        private bool TownRun()
        {
            Logger.Debug("[TownRun] BrainBehavior.IsVendoring is {0}", BrainBehavior.IsVendoring);
            Logger.Debug("[TownRun] ZetaDia.Me.IsParticipatingInTieredLootRun is {0}", ZetaDia.Me.IsParticipatingInTieredLootRun);
            Logger.Debug("[TownRun] AdvDia.RiftQuest.State is {0}", AdvDia.RiftQuest.State);
            Logger.Debug("[TownRun] AdvDia.RiftQuest.Step is {0}", AdvDia.RiftQuest.Step);
            DisablePulse();
            if (BrainBehavior.IsVendoring)
            {
                return(false);
            }
            if (!_townRunInitiated)
            {
                _townRunInitiated = true;
                BrainBehavior.ForceTownrun(" We need it.", true);
                return(false);
            }

            _riftCounter++;
            Logger.Info("Rifts Completed = {0}", _riftCounter);

            if (_options.RiftCount > 0 && _riftCounter >= _options.RiftCount)
            {
                Logger.Info("[Rift] Rift limit set on profile tag reached. ({0})", _options.RiftCount);
                State = States.Completed;
                return(Finished());
            }

            _townRunInitiated = false;
            if (AdvDia.RiftQuest.Step == RiftStep.Completed)
            {
                State = States.WaitForRiftCountdown;
                Logger.Info("[Rift] Tick tock, tick tock...");
            }
            else
            {
                State = States.NotStarted;
                _moveToRiftStoneCoroutine.Reset();
            }
            return(false);
        }
Пример #20
0
        private bool TownRun()
        {
            if (BrainBehavior.IsVendoring)
            {
                return(false);
            }
            if (!_townRunInitiated)
            {
                _townRunInitiated = true;
                BrainBehavior.ForceTownrun(" We need it.", true);
            }
            if (BrainBehavior.IsVendoring)
            {
                return(false);
            }
            _townRunInitiated = false;

            State = States.MovingToTyrael;

            return(false);
        }
Пример #21
0
        internal static void RecompileSelectedPlugin(Object sender, EventArgs e)
        {
            var    FBD             = new System.Windows.Forms.FolderBrowserDialog();
            string sDemonBuddyPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

            FBD.SelectedPath = sDemonBuddyPath + @"\Plugins\";
            System.Windows.Forms.DialogResult PluginLocationResult = FBD.ShowDialog();

            if (PluginLocationResult == System.Windows.Forms.DialogResult.OK && !String.IsNullOrEmpty(FBD.SelectedPath))
            {
                Logger.DBLog.DebugFormat(FBD.SelectedPath);

                if (BotMain.IsRunning)
                {
                    BotMain.Stop(false, "Recompiling Plugin!");
                    while (BotMain.BotThread.IsAlive)
                    {
                        Thread.Sleep(0);
                    }
                }

                var EnabledPlugins = PluginManager.GetEnabledPlugins().ToArray();

                foreach (var p in PluginManager.Plugins)
                {
                    p.Enabled = false;
                }

                PluginManager.ShutdownAllPlugins();

                //FunkyBot.Logger.DBLog.DebugFormat("Removing {0} from plugins", FunkyRoutine.lastSelectedPC.Plugin.Name);
                //while (PluginManager.Plugins.Any(p => p.Plugin.Name == FunkyRoutine.lastSelectedPC.Plugin.Name))
                //{
                //	PluginManager.Plugins.Remove(PluginManager.Plugins.First(p => p.Plugin.Name == FunkyRoutine.lastSelectedPC.Plugin.Name));
                //}

                Logger.DBLog.DebugFormat("Clearing all treehooks");
                TreeHooks.Instance.ClearAll();

                Logger.DBLog.DebugFormat("Disposing of current bot");
                BotMain.CurrentBot.Dispose();

                Logger.DBLog.DebugFormat("Removing old Assemblies");
                CodeCompiler.DeleteOldAssemblies();



                CodeCompiler FunkyCode = new CodeCompiler(FBD.SelectedPath);
                //FunkyCode.ParseFilesForCompilerOptions();
                Logger.DBLog.DebugFormat("Recompiling Plugin");
                FunkyCode.Compile();
                Logger.DBLog.DebugFormat(FunkyCode.CompiledToLocation);



                TreeHooks.Instance.ClearAll();
                BrainBehavior.CreateBrain();

                Logger.DBLog.DebugFormat("Reloading Plugins");
                PluginManager.ReloadAllPlugins(sDemonBuddyPath + @"\Plugins\");

                Logger.DBLog.DebugFormat("Enabling Plugins");
                PluginManager.SetEnabledPlugins(EnabledPlugins);
            }
        }
Пример #22
0
 public override async Task <bool> StartTask()
 {
     BrainBehavior.ForceTownrun(nameof(TownRunTag));
     return(true);
 }
Пример #23
0
    // Update is called once per frame
    void Update()
    {
        //if clicked
        //Raycast with cursor area
        //Get body
        //Check if there's a brain
        //Insert brain,
        //If there's a brain switch with current one

        if (Input.GetMouseButtonDown(0))
        {
            //raycast to see if it hits anything
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            RaycastHit2D hitInfo = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity, cursorClickableLayer);

            if (hitInfo.collider)
            {
                Debug.Log("hitinfo body name: " + hitInfo.collider.transform.ToString());

                //Find the body
                CharacterBody body = hitInfo.collider.GetComponent <CharacterBody> ();


                BrainBehavior backupTempBrain = null;

                bool playSound = false;

                //if the body has a brain, always take the brain
                if (body.brainBehavior)
                {
                    body.brainBehavior.enabled = false;
                    backupTempBrain            = body.brainBehavior;
                    body.brainBehavior         = null;
                    playSound = true;
                }

                //if we have a temp brain, always insert the brain
                if (tempBrain)
                {
                    body.brainBehavior         = tempBrain;
                    tempBrain                  = null;
                    body.brainBehavior.enabled = true;
                    body.brainBehavior.body    = body;
                    cursorBrainRender.enabled  = false;
                    playSound                  = true;
                }

                //If we have a backup that we grabbed early, insert into claw
                if (backupTempBrain)
                {
                    tempBrain = backupTempBrain;
                    cursorBrainRender.enabled = true;
                    cursorBrainRender.color   = tempBrain.brainColor;
                }

                if (playSound && grabSoundPrefab != null)
                {
                    Instantiate(grabSoundPrefab);
                }
            }
        }

        //Turn particle system on/off
        if (tempBrain)
        {
            ps.gameObject.SetActive(true);
        }
        else
        {
            if (ps.isPlaying)
            {
                ps.gameObject.SetActive(false);
            }
        }

        if (Input.GetMouseButton(0))
        {
            grabbyRender.sprite = clawClosed;
        }
        else
        {
            grabbyRender.sprite = clawOpen;
        }


        /*
         * if (tempBrain == null) {
         *      cursorBrainRender.enabled = false;
         * }
         * else{
         *      cursorBrainRender.enabled = true;
         *      cursorBrainRender.color = tempBrain.brainColor;
         * }*/
    }
Пример #24
0
        internal static void HookBehaviorTree()
        {
            bool townportal = false, idenify = false, stash = false, vendor = false, salvage = false, looting = true, combat = true;

            using (XmlReader reader = XmlReader.Create(FolderPaths.sTrinityPluginPath + "Treehooks.xml"))
            {
                // Parse the XML document.  ReadString is used to
                // read the text content of the elements.
                reader.Read();
                reader.ReadStartElement("Treehooks");
                reader.Read();
                while (reader.LocalName != "Treehooks")
                {
                    switch (reader.LocalName)
                    {
                    case "Townportal":
                        townportal = Convert.ToBoolean(reader.ReadInnerXml());
                        break;

                    case "Identification":
                        idenify = Convert.ToBoolean(reader.ReadInnerXml());
                        break;

                    case "Stash":
                        stash = Convert.ToBoolean(reader.ReadInnerXml());
                        break;

                    case "Vendor":
                        vendor = Convert.ToBoolean(reader.ReadInnerXml());
                        break;

                    case "Salvage":
                        salvage = Convert.ToBoolean(reader.ReadInnerXml());
                        break;

                    case "Looting":
                        looting = Convert.ToBoolean(reader.ReadInnerXml());
                        break;

                    case "Combat":
                        combat = Convert.ToBoolean(reader.ReadInnerXml());
                        break;
                    }

                    reader.Read();
                }
            }

            Logger.DBLog.InfoFormat("[Funky] Replacing Treehooks..");
            #region TreeHooks
            foreach (var hook in TreeHooks.Instance.Hooks)
            {
                // Replace the combat behavior tree, as that happens first and so gets done quicker!
                if (hook.Key.Contains("Combat"))
                {
                    if (combat)
                    {
                        // Replace the pause just after identify stuff to ensure we wait before trying to run to vendor etc.
                        CanRunDecoratorDelegate canRunDelegateCombatTargetCheck = GlobalOverlord;
                        ActionDelegate          actionDelegateCoreTarget        = HandleTarget;
                        Sequence sequencecombat = new Sequence(
                            new Action(actionDelegateCoreTarget)
                            );
                        hook.Value[0] = new Decorator(canRunDelegateCombatTargetCheck, sequencecombat);
                        Logger.DBLog.DebugFormat("Combat Tree replaced...");
                    }
                }                 // Vendor run hook
                // Wipe the vendorrun and loot behavior trees, since we no longer want them
                if (hook.Key.Contains("VendorRun"))
                {
                    Decorator GilesDecorator = hook.Value[0] as Decorator;
                    //PrioritySelector GilesReplacement = GilesDecorator.Children[0] as PrioritySelector;
                    PrioritySelector GilesReplacement = GilesDecorator.Children[0] as PrioritySelector;

                    //[1] == Return to town
                    if (townportal)
                    {
                        CanRunDecoratorDelegate canRunDelegateReturnToTown     = TownPortalBehavior.FunkyTPOverlord;
                        ActionDelegate          actionDelegateReturnTown       = TownPortalBehavior.FunkyTPBehavior;
                        ActionDelegate          actionDelegateTownPortalFinish = TownPortalBehavior.FunkyTownPortalTownRun;
                        Sequence sequenceReturnTown = new Sequence(
                            new Action(actionDelegateReturnTown),
                            new Action(actionDelegateTownPortalFinish)
                            );
                        GilesReplacement.Children[1] = new Decorator(canRunDelegateReturnToTown, sequenceReturnTown);
                        Logger.DBLog.DebugFormat("Town Run - Town Portal - hooked...");
                    }

                    ActionDelegate actionDelegatePrePause = TownRunManager.GilesStashPrePause;
                    ActionDelegate actionDelegatePause    = TownRunManager.GilesStashPause;

                    if (idenify)
                    {
                        //[2] == IDing items in inventory
                        CanRunDecoratorDelegate canRunDelegateFunkyIDBehavior = ItemIdentifyBehavior.FunkyIDOverlord;
                        ActionDelegate          actionDelegateID = ItemIdentifyBehavior.FunkyIDBehavior;
                        Sequence sequenceIDItems = new Sequence(
                            new Action(actionDelegateID),
                            new Sequence(
                                new Action(actionDelegatePrePause),
                                new Action(actionDelegatePause)
                                )
                            );
                        GilesReplacement.Children[2] = new Decorator(canRunDelegateFunkyIDBehavior, sequenceIDItems);
                        Logger.DBLog.DebugFormat("Town Run - Idenify Items - hooked...");
                    }


                    // Replace the pause just after identify stuff to ensure we wait before trying to run to vendor etc.
                    CanRunDecoratorDelegate canRunDelegateStashGilesPreStashPause = TownRunManager.GilesPreStashPauseOverlord;
                    Sequence sequencepause = new Sequence(
                        new Action(actionDelegatePrePause),
                        new Action(actionDelegatePause)
                        );

                    GilesReplacement.Children[3] = new Decorator(canRunDelegateStashGilesPreStashPause, sequencepause);


                    if (stash)
                    {
                        // Replace DB stashing behavior tree with my optimized version with loot rule replacement
                        CanRunDecoratorDelegate canRunDelegateStashGilesOverlord = TownRunManager.GilesStashOverlord;
                        ActionDelegate          actionDelegatePreStash           = TownRunManager.GilesOptimisedPreStash;
                        ActionDelegate          actionDelegateStashing           = TownRunManager.GilesOptimisedStash;
                        ActionDelegate          actionDelegatePostStash          = TownRunManager.GilesOptimisedPostStash;
                        Sequence sequencestash = new Sequence(
                            new Action(actionDelegatePreStash),
                            new Action(actionDelegateStashing),
                            new Action(actionDelegatePostStash),
                            new Sequence(
                                new Action(actionDelegatePrePause),
                                new Action(actionDelegatePause)
                                )
                            );
                        GilesReplacement.Children[4] = new Decorator(canRunDelegateStashGilesOverlord, sequencestash);
                        Logger.DBLog.DebugFormat("Town Run - Stash - hooked...");
                    }

                    if (vendor)
                    {
                        // Replace DB vendoring behavior tree with my optimized & "one-at-a-time" version
                        CanRunDecoratorDelegate canRunDelegateSellGilesOverlord = TownRunManager.GilesSellOverlord;
                        ActionDelegate          actionDelegatePreSell           = TownRunManager.GilesOptimisedPreSell;
                        ActionDelegate          actionDelegateSell     = TownRunManager.GilesOptimisedSell;
                        ActionDelegate          actionDelegatePostSell = TownRunManager.GilesOptimisedPostSell;
                        Sequence sequenceSell = new Sequence(
                            new Action(actionDelegatePreSell),
                            new Action(actionDelegateSell),
                            new Action(actionDelegatePostSell),
                            new Sequence(
                                new Action(actionDelegatePrePause),
                                new Action(actionDelegatePause)
                                )
                            );
                        GilesReplacement.Children[5] = new Decorator(canRunDelegateSellGilesOverlord, sequenceSell);
                        Logger.DBLog.DebugFormat("Town Run - Vendor - hooked...");
                    }

                    if (salvage)
                    {
                        // Replace DB salvaging behavior tree with my optimized & "one-at-a-time" version
                        CanRunDecoratorDelegate canRunDelegateSalvageGilesOverlord = TownRunManager.GilesSalvageOverlord;
                        ActionDelegate          actionDelegatePreSalvage           = TownRunManager.GilesOptimisedPreSalvage;
                        ActionDelegate          actionDelegateSalvage     = TownRunManager.GilesOptimisedSalvage;
                        ActionDelegate          actionDelegatePostSalvage = TownRunManager.GilesOptimisedPostSalvage;
                        Sequence sequenceSalvage = new Sequence(
                            new Action(actionDelegatePreSalvage),
                            new Action(actionDelegateSalvage),
                            new Action(actionDelegatePostSalvage),
                            new Sequence(
                                new Action(actionDelegatePrePause),
                                new Action(actionDelegatePause)
                                )
                            );
                        GilesReplacement.Children[6] = new Decorator(canRunDelegateSalvageGilesOverlord, sequenceSalvage);
                        Logger.DBLog.DebugFormat("Town Run - Salvage - hooked...");
                    }


                    //Decorator FinishTownRun=GilesReplacement.Children[7] as Decorator;
                    //Decorator FinishTownRunCheck=FinishTownRun.Children[0] as Decorator;
                    //PrioritySelector FinishTownRunPrioritySelector=FinishTownRunCheck.DecoratedChild as PrioritySelector;
                    //Decorator FinishTownRunPrioritySelectorDecorator=FinishTownRunPrioritySelector.Children[0] as Decorator;
                    //Zeta.TreeSharp.Action FinishTownRunAction=FinishTownRunPrioritySelectorDecorator.Children[0] as Zeta.TreeSharp.Action;

                    //[7] == Return to Townportal if there is one..

                    //Setup our movement back to townportal
                    //CanRunDecoratorDelegate canRunDelegateUseTownPortalReturn = TownRunManager.FinishTownRunOverlord;
                    //ActionDelegate actionDelegateFinishTownRun = TownRunManager.TownRunFinishBehavior;
                    //Sequence sequenceFinishTownRun = new Sequence(
                    //   new Action(actionDelegateFinishTownRun)
                    //);

                    //We insert this before the demonbuddy townportal finishing behavior..
                    //GilesReplacement.InsertChild(7, new Decorator(canRunDelegateUseTownPortalReturn, sequenceFinishTownRun));



                    CanRunDecoratorDelegate canRunUnidBehavior          = TownRunManager.UnidItemOverlord;
                    ActionDelegate          actionDelegatePreUnidStash  = TownRunManager.UnidStashOptimisedPreStash;
                    ActionDelegate          actionDelegatePostUnidStash = TownRunManager.UnidStashOptimisedPostStash;
                    ActionDelegate          actionDelegateUnidBehavior  = TownRunManager.UnidStashBehavior;
                    Sequence sequenceUnidStash = new Sequence(
                        new Action(actionDelegatePreUnidStash),
                        new Action(actionDelegateUnidBehavior),
                        new Action(actionDelegatePostUnidStash),
                        new Sequence(
                            new Action(actionDelegatePrePause),
                            new Action(actionDelegatePause)
                            )
                        );
                    GilesReplacement.InsertChild(2, new Decorator(canRunUnidBehavior, sequenceUnidStash));


                    CanRunDecoratorDelegate canRunDelegateGilesTownRunCheck = TownRunManager.GilesTownRunCheckOverlord;
                    hook.Value[0] = new Decorator(canRunDelegateGilesTownRunCheck, new PrioritySelector(GilesReplacement));

                    Logger.DBLog.DebugFormat("Vendor Run tree hooked...");
                }                 // Vendor run hook
                if (hook.Key.Contains("Loot"))
                {
                    if (looting)
                    {
                        // Replace the loot behavior tree with a blank one, as we no longer need it
                        CanRunDecoratorDelegate canRunDelegateBlank = BlankDecorator;
                        ActionDelegate          actionDelegateBlank = BlankAction;
                        Sequence sequenceblank = new Sequence(
                            new Action(actionDelegateBlank)
                            );
                        hook.Value[0] = new Decorator(canRunDelegateBlank, sequenceblank);
                        Logger.DBLog.DebugFormat("Loot tree replaced...");
                    }
                    else
                    {
                        CanRunDecoratorDelegate canRunDelegateBlank = BlankDecorator;
                        hook.Value[0] = new Decorator(canRunDelegateBlank, BrainBehavior.CreateLootBehavior());
                    }
                }                 // Vendor run hook
                if (hook.Key.Contains("OutOfGame"))
                {
                    PrioritySelector CompositeReplacement = hook.Value[0] as PrioritySelector;

                    CanRunDecoratorDelegate shouldPreformOutOfGameBehavior = OutOfGame.OutOfGameOverlord;
                    ActionDelegate          actionDelgateOOGBehavior       = OutOfGame.OutOfGameBehavior;
                    Sequence sequenceOOG = new Sequence(
                        new Action(actionDelgateOOGBehavior)
                        );
                    CompositeReplacement.Children.Insert(0, new Decorator(shouldPreformOutOfGameBehavior, sequenceOOG));
                    hook.Value[0] = CompositeReplacement;

                    Logger.DBLog.DebugFormat("Out of game tree hooked");
                }
                if (hook.Key.Contains("Death"))
                {
                    PrioritySelector DeathPrioritySelector = hook.Value[0] as PrioritySelector;

                    //CanRunDecoratorDelegate canRunDeathBehavior=new CanRunDecoratorDelegate(Death.DeathOverlord);

                    //Sequence sequenceDeath=new Sequence(
                    //	 new Zeta.TreeSharp.Action(actionDelgateDeath)
                    //);
                    //DeathPrioritySelector.Children[0]=new Zeta.TreeSharp.Decorator(canRunDeathBehavior, sequenceDeath);

                    Decorator      DeathDecorator     = DeathPrioritySelector.Children[0] as Decorator;
                    Sequence       DeathSequence      = DeathDecorator.Children[0] as Sequence;
                    ActionDelegate actionDelgateDeath = EventHandlers.DeathHandler;
                    DeathSequence.InsertChild(0, new Action(actionDelgateDeath));

                    /*
                     * 17:10:24.548 N] Zeta.TreeSharp.Action
                     * [17:10:24.548 N] Zeta.TreeSharp.DecoratorContinue
                     * [17:10:24.548 N] Zeta.TreeSharp.Action
                     * [17:10:24.548 N] Zeta.TreeSharp.Sleep
                     * [17:10:24.548 N] Zeta.TreeSharp.Action
                     */
                    // foreach (var item in DeathSequence.Children)
                    //{
                    //	 Logger.DBLog.InfoFormat(item.GetType().ToString());
                    //}
                }
            }
            #endregion
            initTreeHooks = true;
        }
Пример #25
0
        public static async Task <bool> Execute()
        {
            if (!ZetaDia.IsInGame || ZetaDia.Globals.IsLoadingWorld || !ZetaDia.Me.IsValid)
            {
                return(false);
            }

            if (Core.IsOutOfGame)
            {
                return(false);
            }

            var isDead = ZetaDia.Me.IsDead;

            if (_isDead != isDead)
            {
                if (isDead)
                {
                    _deathCounter            = LastDeathTime.Subtract(DateTime.UtcNow).TotalSeconds > 60 ? 0 : _deathCounter + 1;
                    _deathNeedRepairCounter  = LastDeathTime.Subtract(DateTime.UtcNow).TotalSeconds < 60 && EquipmentNeedsEmergencyRepair(5) ? _deathNeedRepairCounter + 1 : 0;
                    LastDeathTime            = DateTime.UtcNow;
                    _resButtonsVisibleStart  = DateTime.MinValue;
                    _resurrectButtonsVisible = false;
                    _deathLocation           = ZetaDia.Me.Position;
                    DeathsThisSession++;
                    DeathsThisSession++;

                    Core.Logger.Log("[Death] You died lol! RecentDeaths={0} RecentDeathsNeedingRepair={1}", _deathCounter, _deathNeedRepairCounter);
                }
                else
                {
                    Core.Logger.Log("[Death] No Longer Dead");

                    //if (Core.Settings.Combat.Misc.FleeInGhostMode)
                    //{
                    await MoveWhileGhosted();

                    //}

                    if (EquipmentNeedsEmergencyRepair(5))
                    {
                        BrainBehavior.ForceTownrun("[Death] Item Durability - Need to Repair");
                    }
                }
                _isDead = isDead;
            }

            if (!isDead)
            {
                return(false);
            }

            var reviveAtCorpseButton     = UIElement.FromHash(0xE3CBD66296A39588);
            var reviveAtCheckPointButton = UIElement.FromHash(0xBFAAF48BA9316742);
            var acceptRessurectionButton = UIElement.FromHash(0x712D458486D6F062);
            var reviveInTownButton       = UIElement.FromHash(0x7A2AF9C0F3045ADA);
            var needRepair            = EquipmentNeedsEmergencyRepair(5);
            var checkpointButtonReady = reviveAtCheckPointButton.IsVisible && reviveAtCheckPointButton.IsEnabled;
            var corpseButtonReady     = reviveAtCorpseButton.IsVisible && reviveAtCorpseButton.IsEnabled;
            var townButtonReady       = reviveInTownButton.IsVisible && reviveInTownButton.IsEnabled;
            var isInRift                  = GameData.RiftWorldIds.Contains(ZetaDia.Globals.WorldSnoId);
            var isInGreaterRift           = isInRift && ZetaDia.Storage.CurrentRiftType == RiftType.Greater;
            var noMoreCorpseRevives       = !isInGreaterRift && ZetaDia.Me.CommonData.CorpseResurrectionCharges == 0;
            var waitingForCorpseResurrect = ZetaDia.Globals.GameTick < ZetaDia.Me.CommonData.CorpseResurrectionAllowedGameTime;
            var deathCount                = ZetaDia.Me.CommonData.DeathCount;
            var corpseResurrectDisabled   = ZetaDia.Me.CommonData.CorpseResurrectionDisabled > 0;

            if (reviveAtCheckPointButton.IsVisible)
            {
                _resButtonsVisibleStart = DateTime.UtcNow;
            }

            var resurrectButtonsVisible = _resButtonsVisibleStart != DateTime.MinValue;

            if (resurrectButtonsVisible != _resurrectButtonsVisible)
            {
                if (resurrectButtonsVisible)
                {
                    Core.Logger.Verbose("[Death] Buttons are now visible");
                    var maxWaitTime = ZetaDia.Me.IsParticipatingInTieredLootRun ? Math.Min(deathCount * 5, 30) - 2 : 4;
                    _corpseReviveAvailableTime = new DateTime(_resButtonsVisibleStart.Ticks).Add(TimeSpan.FromSeconds(maxWaitTime));
                }
                _resurrectButtonsVisible = resurrectButtonsVisible;
            }

            var remainingTimeSecs = (_corpseReviveAvailableTime - DateTime.UtcNow).TotalSeconds;
            var resLimit          = isInGreaterRift ? 16 : 10;

            if (_deathCounter > resLimit && !ZetaDia.IsInTown && needRepair)
            {
                Core.Logger.Log("Durability is zero and {0} deaths within 60s of each other - emergency leave game", deathCount);
                ZetaDia.Service.Party.LeaveGame(true);
                await CommonCoroutines.LeaveGame("Durability is zero");

                _deathCounter = 0;
                return(true);
            }

            if (acceptRessurectionButton.IsVisible && acceptRessurectionButton.IsEnabled)
            {
                acceptRessurectionButton.Click();
            }
            else if (IsBeingRevived())
            {
                Core.Logger.Log("[Death] Waiting while being resurrected");
            }
            else if (ZetaDia.Me.IsInBossEncounter && !Core.Rift.IsInRift && IsAlivePlayerNearby)
            {
                Core.Logger.Log("[Death] Waiting because of boss fight");
            }
            else if (corpseButtonReady && !needRepair && !waitingForCorpseResurrect && !noMoreCorpseRevives && !corpseResurrectDisabled)
            {
                while (reviveAtCorpseButton.IsVisible && ZetaDia.Me.IsDead)
                {
                    Core.Logger.Log("[Death] Reviving at corpse");
                    reviveAtCorpseButton.Click();
                    await Coroutine.Sleep(1000);
                }
            }
            else if (townButtonReady && needRepair && _deathNeedRepairCounter > 4)
            {
                Core.Logger.Log("[Death] We've failed few times to resurrect at checkpoint to repair , now resurrecting in town.");
                reviveInTownButton.Click();
            }
            else if (checkpointButtonReady)
            {
                Core.Logger.Log("[Death] Reviving at checkpoint (NeedRepair={0})", needRepair);
                reviveAtCheckPointButton.Click();
            }
            else if (!corpseButtonReady && !checkpointButtonReady && townButtonReady && DateTime.UtcNow.Subtract(LastDeathTime).TotalSeconds > 45)
            {
                Core.Logger.Log("[Death] Reviving in town");
                reviveInTownButton.Click();
            }
            else
            {
                Core.Logger.Verbose("[Death] Waiting...");
            }

            await Coroutine.Sleep(250);

            return(true);
        }
Пример #26
0
	// Update is called once per frame
	void Update () {
	
		//if clicked
		//Raycast with cursor area
		//Get body
		//Check if there's a brain
		//Insert brain,
		//If there's a brain switch with current one

		if (Input.GetMouseButtonDown (0)) {
			

			//raycast to see if it hits anything
			Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);

			RaycastHit2D hitInfo = Physics2D.Raycast (ray.origin, ray.direction, Mathf.Infinity, cursorClickableLayer);

			if (hitInfo.collider) {
				Debug.Log ("hitinfo body name: " + hitInfo.collider.transform.ToString ());

				//Find the body
				CharacterBody body = hitInfo.collider.GetComponent<CharacterBody> ();


				BrainBehavior backupTempBrain = null;

				bool playSound = false;

				//if the body has a brain, always take the brain
				if (body.brainBehavior) {
					body.brainBehavior.enabled = false;
					backupTempBrain = body.brainBehavior;
					body.brainBehavior = null;
					playSound = true;
				}

				//if we have a temp brain, always insert the brain
				if (tempBrain) {
					body.brainBehavior = tempBrain;
					tempBrain = null;
					body.brainBehavior.enabled = true;
					body.brainBehavior.body = body;
					cursorBrainRender.enabled = false;
					playSound = true;
				}

				//If we have a backup that we grabbed early, insert into claw
				if (backupTempBrain) {
					tempBrain = backupTempBrain;
					cursorBrainRender.enabled = true;
					cursorBrainRender.color = tempBrain.brainColor;
				}

				if (playSound && grabSoundPrefab != null) {
					Instantiate (grabSoundPrefab);
				}

			}
		}

		//Turn particle system on/off
		if (tempBrain) {
			ps.gameObject.SetActive (true);

		} else {
			if (ps.isPlaying) {
				ps.gameObject.SetActive (false);
			}
		}

		if (Input.GetMouseButton (0)) {
			grabbyRender.sprite = clawClosed;
		} else {
			grabbyRender.sprite = clawOpen;
		}


		/*
		if (tempBrain == null) {
			cursorBrainRender.enabled = false;
		}
		else{
			cursorBrainRender.enabled = true;
			cursorBrainRender.color = tempBrain.brainColor;
		}*/
	}