예제 #1
0
        public static async Task <bool> Interact(WoWObject selectedTarget, System.Action actionOnSuccessfulItemUseDelegate = null)
        {
            // Viable target?
            // NB: Since target may go invalid immediately upon interacting with it,
            // we cache its name for use in subsequent log entries.
            if (!Query.IsViable(selectedTarget))
            {
                QBCLog.Warning("Target is not viable!");
                return(false);
            }

            var targetName = selectedTarget.SafeName;

            // Need to be facing target...
            // NB: Not all items require this, but many do.
            Utility.Target(selectedTarget, true);

            // Notify user of intent...
            QBCLog.DeveloperInfo("Interacting with '{0}'", targetName);

            // Set up 'interrupted use' detection, and interact...
            using (var castMonitor = SpellCastMonitor.Start(null))
            {
                selectedTarget.Interact();

                // NB: The target may not be valid after this point...
                // Some targets will go 'invalid' immediately afer interacting with them.
                // Most of the time this happens, the target is immediately and invisibly replaced with
                // an identical looking target with a different script.
                // We must assume our target is no longer available for use after this point.
                await Coroutine.Sleep(Delay.AfterInteraction);

                // Wait for any casting to complete...
                // NB: Some interactions or item usages take time, and the WoWclient models this as spellcasting.
                // NB: We can't test for IsCasting or IsChanneling--we must instead look for a valid spell being cast.
                //      There are some quests that require actions where the WoWclient returns 'true' for IsCasting,
                //      but there is no valid spell being cast.  We want the behavior to move on immediately in these
                //      conditions.  An example of such an interaction is removing 'tangler' vines in the Tillers
                //      daily quest area.
                var castResult = await castMonitor.GetResult();

                if (castResult != SpellCastResult.Succeeded && castResult != SpellCastResult.NoCastStarted)
                {
                    string reason = castResult == SpellCastResult.UnknownFail
                        ? castMonitor.FailReason
                        : castResult.ToString();

                    QBCLog.DeveloperInfo("Interaction with {0} interrupted.", targetName);

                    QBCLog.Warning("Interaction with {0} interrupted. Reason: {1}", targetName, reason);
                    // Give whatever issue encountered a chance to settle...
                    // NB: --we want the Sequence to fail when delay completes.
                    if (castResult != SpellCastResult.LineOfSight &&
                        castResult != SpellCastResult.OutOfRange &&
                        castResult != SpellCastResult.TooClose)
                    {
                        await Coroutine.Sleep(1500);
                    }
                    return(false);
                }

                QBCLog.DeveloperInfo("Interact with '{0}' succeeded.", targetName);
                if (actionOnSuccessfulItemUseDelegate != null)
                {
                    actionOnSuccessfulItemUseDelegate();
                }

                return(true);
            }
        }
예제 #2
0
        public static async Task <SpellCastResult> CastSpell(
            int spellId,
            WoWObject target = null,
            System.Action actionOnSuccessfulSpellCastDelegate = null)
        {
            // Viable target?
            // If target is null, then assume 'self'.
            // NB: Since target may go invalid immediately upon casting the spell,
            // we cache its name for use in subsequent log entries.
            var selectedObject = target ?? Me;

            if (!Query.IsViable(selectedObject))
            {
                QBCLog.Warning("Target is not viable!");
                return(SpellCastResult.InvalidTarget);
            }

            var targetName = selectedObject.SafeName;

            // Target must be a WoWUnit for us to be able to cast a spell on it...
            var selectedTarget = selectedObject as WoWUnit;

            if (!Query.IsViable(selectedTarget))
            {
                QBCLog.Warning("Target {0} is not a WoWUnit--cannot cast spell on it.", targetName);
                return(SpellCastResult.InvalidTarget);
            }

            // Spell known?
            WoWSpell selectedSpell = WoWSpell.FromId(spellId);

            if (selectedSpell == null)
            {
                QBCLog.Warning("{0} is not known.", Utility.GetSpellNameFromId(spellId));
                return(SpellCastResult.SpellNotKnown);
            }
            var spellName = selectedSpell.Name;

            // Need to be facing target...
            // NB: Not all spells require this, but many do.
            Utility.Target(selectedTarget, true);

            // Wait for spell to become ready...
            if (!SpellManager.CanCast(selectedSpell))
            {
                QBCLog.Warning(
                    "{0} is not usable, yet.  (cooldown remaining: {1})",
                    spellName,
                    Utility.PrettyTime(selectedSpell.CooldownTimeLeft));
                return(SpellCastResult.NotReady);
            }

            // Notify user of intent...
            var message = string.Format("Attempting cast of '{0}' on '{1}'", spellName, targetName);

            message +=
                selectedTarget.IsDead
                    ? " (dead)"
                    : string.Format(" (health: {0:F1})", selectedTarget.HealthPercent);
            QBCLog.DeveloperInfo(message);

            // Set up 'interrupted use' detection, and cast spell...
            using (var castMonitor = SpellCastMonitor.Start(spellId))
            {
                SpellManager.Cast(selectedSpell, selectedTarget);

                // NB: The target or the spell may not be valid after this point...
                // Some targets will go 'invalid' immediately afer interacting with them.
                // Most of the time this happens, the target is immediately and invisibly replaced with
                // an identical looking target with a different script.
                // We must assume our target and spell is no longer available for use after this point.

                await Coroutine.Sleep((int)Delay.AfterItemUse.TotalMilliseconds);

                // If item use requires a second click on the target (e.g., item has a 'ground target' mechanic)...
                await CastPendingSpell(selectedTarget);

                // Wait for any casting to complete...
                // NB: Some interactions or item usages take time, and the WoWclient models this as spellcasting.

                var castResult = await castMonitor.GetResult();

                if (castResult != SpellCastResult.Succeeded)
                {
                    string reason = castResult == SpellCastResult.UnknownFail
                        ? castMonitor.FailReason
                        : castResult.ToString();

                    QBCLog.Warning("Cast of {0} failed. Reason: {1}", spellName, reason);
                    // Give whatever issue encountered a chance to settle...
                    // NB: --we want the Sequence to fail when delay completes.
                    if (castResult != SpellCastResult.LineOfSight &&
                        castResult != SpellCastResult.OutOfRange &&
                        castResult != SpellCastResult.TooClose)
                    {
                        await Coroutine.Sleep(1500);
                    }
                    return(castResult);
                }

                QBCLog.DeveloperInfo("Cast of '{0}' on '{1}' succeeded.", spellName, targetName);

                if (actionOnSuccessfulSpellCastDelegate != null)
                {
                    actionOnSuccessfulSpellCastDelegate();
                }

                return(SpellCastResult.Succeeded);
            }
        }
예제 #3
0
        /// <summary>
        ///     <para>Uses item defined by ITEMID.</para>
        ///     <para>
        ///         Notes:
        ///         <list type="bullet">
        ///             <item>
        ///                 <description>
        ///                     <para>
        ///                         * It is up to the caller to assure that all preconditions have been met for
        ///                         using the item (i.e., the item is off cooldown, etc).
        ///                     </para>
        ///                 </description>
        ///             </item>
        ///             <item>
        ///                 <description>
        ///                     <para>
        ///                         * If item use was successful, coroutine returns 'true';
        ///                         otherwise, 'false' is returned (e.g., item is not ready for use,
        ///                         item use was interrupted by combat, etc).
        ///                     </para>
        ///                 </description>
        ///             </item>
        ///         </list>
        ///     </para>
        /// </summary>
        /// <param name="itemId">The item provided should be viable, and ready for use.</param>
        /// <param name="actionOnMissingItemDelegate">This delegate will be called if the item
        /// is missing from our backpack.  This delegate may not be null.</param>
        /// <param name="actionOnFailedItemUseDelegate">If non-null, this delegate will be called
        /// if we attempted to use the item, and it was unsuccessful.  Examples include attemtping
        /// to use the item on an invalid target, or being interrupted or generally unable to use
        /// the item at this time.</param>
        /// <param name="actionOnSuccessfulItemUseDelegate">If non-null, this delegate will be called
        /// once the item has been used successfully.</param>
        /// <returns></returns>
        /// <remarks>20140305-19:01UTC, Highvoltz/chinajade</remarks>
        public static async Task <bool> UseItem(
            int itemId,
            System.Action actionOnMissingItemDelegate,
            System.Action actionOnFailedItemUseDelegate     = null,
            System.Action actionOnSuccessfulItemUseDelegate = null)
        {
            // Waits for global cooldown to end to successfully use the item
            await Coroutine.Wait(500, () => !SpellManager.GlobalCooldown);

            // Is item in our bags?
            var itemToUse = Me.CarriedItems.FirstOrDefault(i => (i.Entry == itemId));

            if (!Query.IsViable(itemToUse))
            {
                QBCLog.Error("{0} is not in our bags.", Utility.GetItemNameFromId(itemId));
                if (actionOnMissingItemDelegate != null)
                {
                    actionOnMissingItemDelegate();
                }
                return(false);
            }
            var itemName = itemToUse.SafeName;

            // Wait for Item to be usable...
            // NB: WoWItem.Usable does not account for cooldowns.
            if (!itemToUse.Usable || (itemToUse.Cooldown > 0))
            {
                TreeRoot.StatusText =
                    string.Format(
                        "{0} is not usable, yet. (cooldown remaining: {1})",
                        itemName,
                        Utility.PrettyTime(itemToUse.CooldownTimeLeft));
                return(false);
            }

            // Notify user of intent...
            QBCLog.DeveloperInfo("Attempting use of '{0}'", itemName);

            // Set up 'interrupted use' detection, and use item...
            using (var castMonitor = SpellCastMonitor.Start(null))
            {
                itemToUse.Use();
                // NB: The target or the item may not be valid after this point...
                // Some targets will go 'invalid' immediately afer interacting with them.
                // Most of the time this happens, the target is immediately and invisibly replaced with
                // an identical looking target with a different script.
                // Some items are consumed when used.
                // We must assume our target and item is no longer available for use after this point.
                await Coroutine.Sleep((int)Delay.AfterItemUse.TotalMilliseconds);

                // Wait for any casting to complete...
                // NB: Some interactions or item usages take time, and the WoWclient models this as spellcasting.
                // NB: We can't test for IsCasting or IsChanneling--we must instead look for a valid spell being cast.
                //      There are some quests that require actions where the WoWclient returns 'true' for IsCasting,
                //      but there is no valid spell being cast.  We want the behavior to move on immediately in these
                //      conditions.  An example of such an interaction is removing 'tangler' vines in the Tillers
                //      daily quest area.
                var castResult = await castMonitor.GetResult();

                if (castResult != SpellCastResult.Succeeded && castResult != SpellCastResult.NoCastStarted)
                {
                    string reason = castResult == SpellCastResult.UnknownFail ? castMonitor.FailReason : castResult.ToString();

                    QBCLog.Warning("Use of {0} interrupted. Reason: {1}", itemName, reason);
                    // Give whatever issue encountered a chance to settle...
                    // NB: --we want the Sequence to fail when delay completes.
                    if (castResult != SpellCastResult.LineOfSight &&
                        castResult != SpellCastResult.OutOfRange &&
                        castResult != SpellCastResult.TooClose)
                    {
                        await Coroutine.Sleep(1500);
                    }

                    if (actionOnFailedItemUseDelegate != null)
                    {
                        actionOnFailedItemUseDelegate();
                    }
                    return(false);
                }
            }

            QBCLog.DeveloperInfo("Use of '{0}' succeeded.", itemName);

            if (actionOnSuccessfulItemUseDelegate != null)
            {
                actionOnSuccessfulItemUseDelegate();
            }
            return(true);
        }
예제 #4
0
        /// <summary>
        /// <para>Uses the hearthstone.</para>
        /// <para>Dismounts if mounted and stops moving before attempting to cast hearthstone. </para>
        /// <para>Does not yield until hearthstone is casted unless it can't be casted, already in hearthstone area or cast failed. </para>
        /// </summary>
        /// <param name="useGarrisonHearthstone">Use garrison hearthstone if set to <c>true</c>.</param>
        /// <param name="inHearthAreaAction">The action to take if already in hearthstone area.</param>
        /// <param name="noHearthStoneInBagsAction">The action to take if no hearthstone is in bags.</param>
        /// <param name="hearthNotSetAction">The action to take if hearth is not set.</param>
        /// <param name="hearthOnCooldownAction">The action to take if hearth is on cooldown.</param>
        /// <param name="hearthCastedAction">The action to take if hearth is successfully casted.</param>
        /// <param name="hearthCastFailedAction">The action to take if hearth failed to cast. The reason string is passed in argument.</param>
        /// <returns>Returns <c>true</c> if hearth was casted</returns>
        /// <exception cref="Exception">A delegate callback throws an exception.</exception>
        public static async Task <bool> UseHearthStone(
            bool useGarrisonHearthstone            = false,
            Action inHearthAreaAction              = null,
            Action noHearthStoneInBagsAction       = null,
            Action hearthNotSetAction              = null,
            Action hearthOnCooldownAction          = null,
            Action hearthCastedAction              = null,
            Action <string> hearthCastFailedAction = null)
        {
            if (IsInHearthStoneArea(useGarrisonHearthstone))
            {
                if (inHearthAreaAction != null)
                {
                    inHearthAreaAction();
                }
                else
                {
                    QBCLog.DeveloperInfo("Already at hearthstone area");
                }

                return(false);
            }

            var hearthStones = useGarrisonHearthstone
                ? GetHearthStonesByIds(ItemId_GarrisonHearthStoneId)
                : GetHearthStonesByIds(ItemId_HearthStoneId, ItemId_TheInnkeepersDaughter);

            if (!hearthStones.Any())
            {
                if (noHearthStoneInBagsAction != null)
                {
                    noHearthStoneInBagsAction();
                }
                else
                {
                    QBCLog.DeveloperInfo("No hearthstone found in bag");
                }
                return(false);
            }

            if (!useGarrisonHearthstone && Me.HearthstoneAreaId == 0)
            {
                // I can only see this occurring if using the Innkeeper's Daughter hearthtone since the normal hearthstone
                // only shows up in bags if hearth has been set.
                if (hearthNotSetAction != null)
                {
                    hearthNotSetAction();
                }
                else
                {
                    QBCLog.DeveloperInfo("Hearth has not been set");
                }
                return(false);
            }

            var usableHearthstone = hearthStones.FirstOrDefault(i => !i.Effects.First().Spell.Cooldown);

            if (usableHearthstone == null)
            {
                if (hearthOnCooldownAction != null)
                {
                    hearthOnCooldownAction();
                }
                else
                {
                    QBCLog.DeveloperInfo("Hearth is on cooldown");
                }

                return(false);
            }

            // the following coroutines execute sequentially, they do not return until dismounted or movement has stopped.
            await CommonCoroutines.LandAndDismount();

            await CommonCoroutines.StopMoving();

            // Close any frame that can prevent hearthstone use...
            // For example WoW will try to sell to hearthstone if merchant frame is open when hearthstone is used
            await CloseFrames();

            var hearthstoneSpell = usableHearthstone.Effects.First().Spell;

            using (var castMonitor = SpellCastMonitor.Start(hearthstoneSpell.Id))
            {
                QBCLog.DeveloperInfo("Using hearthstone: {0}", hearthstoneSpell.Name);

                usableHearthstone.Use();
                var castResult = await castMonitor.GetResult(12000);

                if (castResult == SpellCastResult.Succeeded)
                {
                    await Coroutine.Wait(2000, () => IsInHearthStoneArea(useGarrisonHearthstone));

                    if (hearthCastedAction != null)
                    {
                        hearthCastedAction();
                    }
                    else
                    {
                        QBCLog.DeveloperInfo("Successfully used hearthstone");
                    }
                    return(true);
                }

                string reason = castResult == SpellCastResult.UnknownFail ? castMonitor.FailReason : castResult.ToString();

                if (hearthCastFailedAction != null)
                {
                    hearthCastFailedAction(reason);
                }
                else
                {
                    QBCLog.Warning("Cast of {0} failed. Reason: {1}", hearthstoneSpell.Name, reason);
                }
                return(false);
            }
        }
예제 #5
0
        /// <summary>
        ///     <para>Uses item defined by ITEMID on target defined by SELECTEDTARGET.</para>
        ///     <para>
        ///         Notes:
        ///         <list type="bullet">
        ///             <item>
        ///                 <description>
        ///                     <para>
        ///                         * It is up to the caller to assure that all preconditions have been met for
        ///                         using the item (i.e., the target is in range, the item is off cooldown, etc).
        ///                     </para>
        ///                 </description>
        ///             </item>
        ///             <item>
        ///                 <description>
        ///                     <para>
        ///                         * If item use was successful, coroutine returns 'true';
        ///                         otherwise, 'false' is returned (e.g., item is not ready for use,
        ///                         item use was interrupted by combat, etc).
        ///                     </para>
        ///                 </description>
        ///             </item>
        ///             <item>
        ///                 <description>
        ///                     <para>
        ///                         * It is up to the caller to blacklist the target, or select a new target
        ///                         after successful item use.  The actionOnFailedItemUseDelegate argument
        ///                         can facilitate these activities.
        ///                     </para>
        ///                 </description>
        ///             </item>
        ///         </list>
        ///     </para>
        /// </summary>
        /// <param name="selectedTarget">The target provided should be viable.</param>
        /// <param name="itemId">The item provided should be viable, and ready for use.</param>
        /// <param name="actionOnMissingItemDelegate">This delegate will be called if the item
        /// is missing from our backpack.  This delegate may not be null.</param>
        /// <param name="actionOnFailedItemUseDelegate">If non-null, this delegate will be called
        /// if we attempted to use the item, and it was unsuccessful.  Examples include attemtping
        /// to use the item on an invalid target, or being interrupted or generally unable to use
        /// the item at this time.</param>
        /// <param name="actionOnSuccessfulItemUseDelegate">If non-null, this delegate will be called
        /// once the item has been used successfully.</param>
        /// <returns></returns>
        /// <remarks>20140305-19:01UTC, Highvoltz/chinajade</remarks>
        public static async Task <bool> UseItemOnTarget(
            int itemId,
            WoWObject selectedTarget,
            System.Action actionOnMissingItemDelegate,
            System.Action actionOnFailedItemUseDelegate     = null,
            System.Action actionOnSuccessfulItemUseDelegate = null)
        {
            // Waits for global cooldown to end to successfully use the item
            await Coroutine.Wait(500, () => !SpellManager.GlobalCooldown);

            // qualify...
            // Viable target?
            // NB: Since target may go invalid immediately upon using the item,
            // we cache its name for use in subsequent log entries.;
            if (!Query.IsViable(selectedTarget))
            {
                QBCLog.Warning("Target is not viable!");
                if (actionOnFailedItemUseDelegate != null)
                {
                    actionOnFailedItemUseDelegate();
                }
                return(false);
            }
            var targetName = selectedTarget.SafeName;

            // Is item in our bags?
            var itemToUse = Me.CarriedItems.FirstOrDefault(i => (i.Entry == itemId));

            if (!Query.IsViable(itemToUse))
            {
                QBCLog.Error("{0} is not in our bags.", Utility.GetItemNameFromId(itemId));
                if (actionOnMissingItemDelegate != null)
                {
                    actionOnMissingItemDelegate();
                }
                return(false);
            }
            var itemName = itemToUse.SafeName;

            // Need to be facing target...
            // NB: Not all items require this, but many do.
            Utility.Target(selectedTarget, true);

            // Wait for Item to be usable...
            // NB: WoWItem.Usable does not account for cooldowns.
            if (!itemToUse.Usable || (itemToUse.Cooldown > 0))
            {
                TreeRoot.StatusText =
                    string.Format(
                        "{0} is not usable, yet. (cooldown remaining: {1})",
                        itemName,
                        Utility.PrettyTime(itemToUse.CooldownTimeLeft));
                return(false);
            }

            // Notify user of intent...
            var message = string.Format("Attempting use of '{0}' on '{1}'", itemName, targetName);

            var selectedTargetAsWoWUnit = selectedTarget as WoWUnit;

            if (selectedTargetAsWoWUnit != null)
            {
                if (selectedTargetAsWoWUnit.IsDead)
                {
                    message += " (dead)";
                }
                else
                {
                    message += string.Format(" (health: {0:F1})", selectedTargetAsWoWUnit.HealthPercent);
                }
            }
            QBCLog.DeveloperInfo(message);

            // Set up 'interrupted use' detection, and use item...
            // MAINTAINER'S NOTE: Once these handlers are installed, make sure all possible exit paths from the outer
            // Sequence unhook these handlers.  I.e., if you plan on returning RunStatus.Failure, be sure to call
            // UtilityBehaviorSeq_UseItemOn_HandlersUnhook() first.

            // Set up 'interrupted use' detection, and use item...
            using (var castMonitor = SpellCastMonitor.Start(null))
            {
                itemToUse.Use(selectedTarget.Guid);

                // NB: The target or the item may not be valid after this point...
                // Some targets will go 'invalid' immediately afer interacting with them.
                // Most of the time this happens, the target is immediately and invisibly replaced with
                // an identical looking target with a different script.
                // Some items are consumed when used.
                // We must assume our target and item is no longer available for use after this point.
                await Coroutine.Sleep((int)Delay.AfterItemUse.TotalMilliseconds);

                await CastPendingSpell(selectedTarget);


                // Wait for any casting to complete...
                // NB: Some interactions or item usages take time, and the WoWclient models this as spellcasting.
                // NB: We can't test for IsCasting or IsChanneling--we must instead look for a valid spell being cast.
                //      There are some quests that require actions where the WoWclient returns 'true' for IsCasting,
                //      but there is no valid spell being cast.  We want the behavior to move on immediately in these
                //      conditions.  An example of such an interaction is removing 'tangler' vines in the Tillers
                //      daily quest area.
                var castResult = await castMonitor.GetResult();

                if (castResult != SpellCastResult.Succeeded && castResult != SpellCastResult.NoCastStarted)
                {
                    string reason = castResult == SpellCastResult.UnknownFail ? castMonitor.FailReason : castResult.ToString();

                    QBCLog.Warning("Use of {0} interrupted. Reason: {1}", itemName, reason);
                    // Give whatever issue encountered a chance to settle...
                    // NB: --we want the Sequence to fail when delay completes.
                    if (castResult != SpellCastResult.LineOfSight &&
                        castResult != SpellCastResult.OutOfRange &&
                        castResult != SpellCastResult.TooClose)
                    {
                        await Coroutine.Sleep(1500);
                    }

                    if (actionOnFailedItemUseDelegate != null)
                    {
                        actionOnFailedItemUseDelegate();
                    }
                    return(false);
                }
            }

            QBCLog.DeveloperInfo("Use of '{0}' on '{1}' succeeded.", itemName, targetName);
            if (actionOnSuccessfulItemUseDelegate != null)
            {
                actionOnSuccessfulItemUseDelegate();
            }
            return(true);
        }