Exemple #1
0
        /// <summary>
        /// Returns a RunStatus, if appropriate. Throws an exception if not.
        /// </summary>
        /// <param name="rs"></param>
        /// <returns></returns>
        private static RunStatus GetRunStatus(RunStatus status, string location)
        {
            MonkCombat.RunOngoingPowers();

            string extras = "";
            if (_isWaitingForPower)
                extras += " IsWaitingForPower";
            if (_isWaitingAfterPower)
                extras += " IsWaitingAfterPower";
            if (_isWaitingForPotion)
                extras += " IsWaitingForPotion";
            if (TownRun.IsTryingToTownPortal())
                extras += " IsTryingToTownPortal";
            if (TownRun.TownRunTimerRunning())
                extras += " TownRunTimerRunning";
            if (TownRun.TownRunTimerFinished())
                extras += " TownRunTimerFinished";
            if (_forceTargetUpdate)
                extras += " ForceTargetUpdate";
            if (CurrentTarget == null)
                extras += " CurrentTargetIsNull";
            if (CombatBase.CurrentPower != null && CombatBase.CurrentPower.ShouldWaitBeforeUse)
                extras += " CPowerShouldWaitBefore=" + (CombatBase.CurrentPower.WaitBeforeUseDelay - CombatBase.CurrentPower.TimeSinceAssigned);
            if (CombatBase.CurrentPower != null && CombatBase.CurrentPower.ShouldWaitAfterUse)
                extras += " CPowerShouldWaitAfter=" + (CombatBase.CurrentPower.WaitAfterUseDelay - CombatBase.CurrentPower.TimeSinceUse);
            if (CombatBase.CurrentPower != null && (CombatBase.CurrentPower.ShouldWaitBeforeUse || CombatBase.CurrentPower.ShouldWaitAfterUse))
                extras += " " + CombatBase.CurrentPower;

            Logger.Log(TrinityLogLevel.Debug, LogCategory.Behavior, "HandleTarget returning {0} to tree from " + location + " " + extras, status);

            return status;

        }
Exemple #2
0
        /// <summary>
        ///   Creates a 'throttle' composite. This composite limits the number of times the child 
        ///   returns RunStatus.Success within a given time span.  Returns cappedStatus if limit reached, 
        ///   otherwise returns result of child
        /// </summary>
        /// <param name = "limit">max number of occurrences</param>
        /// <param name = "timeFrame">time span for occurrences</param>
        /// <param name="limitStatus">RunStatus to return when limit reached</param>
        /// <param name = "child">composite children to tick (run)</param>
        public Throttle(int limit, TimeSpan timeFrame, RunStatus limitStatus, Composite child)
            : base(child)
        {
            TimeFrame = timeFrame;
            Limit = limit;

            _end = DateTime.MinValue;
            _count = 0;
            _limitStatus = limitStatus;
        }
Exemple #3
0
        /// <summary>
        /// Run the object and change state to Complete
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        protected override RunStatus Run(object context)
        {
            if (this.Complete)
            {
                return this.CompletionStatus;
            }

            this.Complete = true;

            return this.CompletionStatus = base.Run(context);
        }
Exemple #4
0
 public Split(String runTitle, String runGoal, int attemptsCount, List<Segment> segments)
 {
     this.liveIndex = -1;
     this.runTitle = runTitle;
     this.runGoal = runGoal;
     this.attemptsCount = attemptsCount;
     this.segments = new List<Segment>();
     foreach (Segment segment in segments)
     {
         this.segments.Add(segment);
     }
     this.runStatus = RunStatus.STOPPED;
 }
Exemple #5
0
        //This is the 2nd step in handling.. we recheck target, get a new Ability if needed, and check potion/special movement avoidance here.
        public virtual bool Refresh()
        {
            // Make sure we reset unstucker stuff here
            PlayerMover.iTimesReachedStuckPoint = 0;
            PlayerMover.vSafeMovementLocation = Vector3.Zero;
            PlayerMover.timeLastRecordedPosition = DateTime.Now;

            // Let's calculate whether or not we want a new target list...
            #region NewtargetChecks
            // Whether we should refresh the target list or not
            bool bShouldRefreshDiaObjects = false;

            if (!Cache.bWholeNewTarget && !Cache.bWaitingForPower && !Cache.bWaitingForPotion)
            {
                // Update targets at least once every 80 milliseconds
                if (Cache.bForceTargetUpdate
                    || Cache.TravellingAvoidance
                    || ((DateTime.Now.Subtract(Cache.lastRefreshedObjects).TotalMilliseconds >= 80 && !ObjectCache.CheckFlag(Cache.CurrentTarget.targetType.Value, TargetType.AvoidanceMovements | TargetType.NoMovement))
                    || DateTime.Now.Subtract(Cache.lastRefreshedObjects).TotalMilliseconds >= 1200))
                {
                    bShouldRefreshDiaObjects = true;
                }

                // If we AREN'T getting new targets - find out if we SHOULD because the current unit has died etc.
                if (!bShouldRefreshDiaObjects && Cache.CurrentTarget.targetType.Value == TargetType.Unit && !Cache.CurrentTarget.IsStillValid())
                    bShouldRefreshDiaObjects = true;

            }

            // So, after all that, do we actually want a new target list?
            if (!Cache.bWholeNewTarget && !Cache.bWaitingForPower && !Cache.bWaitingForPotion)
            {
                // If we *DO* want a new target list, do this...
                if (bShouldRefreshDiaObjects)
                {
                    // Now call the function that refreshes targets
                    Cache.Refresh();

                    // No target, return success
                    if (Cache.CurrentTarget == null)
                    {
                        CurrentState = RunStatus.Success;
                        return false;
                    }

                    // Been trying to handle the same target for more than 30 seconds without damaging/reaching it? Blacklist it!
                    if (!ObjectCache.CheckFlag(Cache.CurrentTarget.targetType.Value, TargetType.AvoidanceMovements | TargetType.NoMovement | TargetType.LineOfSight | TargetType.Backtrack)
                          && ((Cache.CurrentTarget.targetType.Value != TargetType.Unit && DateTime.Now.Subtract(Cache.LastChangeOfTarget).TotalSeconds > 12)
                          || (Cache.CurrentTarget.targetType.Value == TargetType.Unit &&
                              Cache.CurrentUnitTarget != null &&
                              !Cache.CurrentTarget.IsBoss &&
                              DateTime.Now.Subtract(Cache.LastChangeOfTarget).TotalSeconds > 20)))
                    {
                        bool bBlacklistThis = true;
                        if (Cache.CurrentTarget.targetType.Value == TargetType.Unit)
                        {
                            if (Cache.CurrentTarget.IsTreasureGoblin && FunkyBaseExtension.Settings.Targeting.GoblinPriority >= 3)
                                bBlacklistThis = false;

                            //Do not ignore when..
                            //A Health changed occured less than 10 secs ago..
                            //or we have not used a combat skill in at least 10 secs
                            if (DateTime.Now.Subtract(Cache.CurrentUnitTarget.LastHealthChange).TotalSeconds < 10 ||
                                DateTime.Now.Subtract(FunkyGame.Hero.Class.LastUsedACombatAbility).TotalSeconds > 10)
                            {
                                bBlacklistThis = false;
                            }

                        }

                        if (bBlacklistThis)
                        {
                            if (Cache.CurrentTarget.targetType.Value == TargetType.Unit && Cache.CurrentUnitTarget != null)
                            {

                                Logger.DBLog.DebugFormat("[Funky] Blacklisting Unit after 20 seconds of no new target! {0}",
                                    Cache.CurrentUnitTarget.DebugString);

                                Logger.DBLog.DebugFormat("{0}", FunkyGame.Targeting.DebugString());

                            }
                            else
                            {
                                Logger.DBLog.DebugFormat("[Funky] Blacklisting Object after no new target! {0}", Cache.CurrentTarget.DebugStringSimple);
                            }

                            Cache.CurrentTarget.NeedsRemoved = true;
                            Cache.CurrentTarget.BlacklistLoops = -1;
                            Cache.CurrentTarget.BlacklistFlag = BlacklistType.Temporary;
                        }
                    }
                    // Make sure we start trying to move again should we need to!
                    Cache.bPickNewAbilities = true;

                    cMovement.NewTargetResetVars();
                }
            }
            #endregion

            // This variable just prevents an instant 2-target update after coming here from the main decorator function above
            Cache.bWholeNewTarget = false;

            //Update CurrentUnitTarget
            if (Cache.CurrentTarget.targetType.Value == TargetType.Unit)
            {
                //Update CurrentUnitTarget Variable.
                if (Cache.CurrentUnitTarget == null) Cache.CurrentUnitTarget = (CacheUnit)Cache.CurrentTarget;

                Cache.CurrentTarget.UpdatePosition(true);

                if (!Cache.CurrentUnitTarget.CurrentHealthPct.HasValue || Cache.CurrentUnitTarget.CurrentHealthPct.Value > 1d)
                {
                    Logger.DBLog.DebugFormat("Current Unit Target health exceedes 100%! {0}",
                        Cache.CurrentTarget.DebugStringSimple);
                }

            }

            //Make sure we are not incapacitated..
            if (FunkyGame.Hero.bIsIncapacitated)
            {
                CurrentState = RunStatus.Running;
                return false;
            }

            //We are ready for the specific object type interaction
            return true;
        }
 public static bool IsFinished(this RunStatus status) => status >= RunStatus.Applied;
Exemple #7
0
        public virtual bool CombatLogic()
        {
            //Check if we can cast any combat buff-type abilities while channeling
            if (Bot.Character.Class.LastUsedAbility.IsChanneling)
            {
                Skill buff;
                if (Bot.Character.Class.FindCombatBuffPower(out buff))
                {
                    Skill.UsePower(ref buff);
                    buff.OnSuccessfullyUsed(false);
                }
            }

            // Find a valid Ability if the target is a monster
            #region AbilityPick
            if (Bot.Targeting.Cache.bPickNewAbilities && !Bot.Targeting.Cache.bWaitingForPower && !Bot.Targeting.Cache.bWaitingForPotion)
            {
                Bot.Targeting.Cache.bPickNewAbilities = false;
                if (Bot.Targeting.Cache.CurrentTarget.targetType.Value == TargetType.Unit && Bot.Targeting.Cache.CurrentTarget.AcdGuid.HasValue)
                {
                    // Pick an Ability
                    Skill nextAbility = Bot.Character.Class.AbilitySelector(Bot.Targeting.Cache.CurrentUnitTarget);

                    // Did we get default attack?
                    if (nextAbility.Equals(Bot.Character.Class.DefaultAttack) && !Bot.Character.Class.CanUseDefaultAttack && !Bot.Settings.Class.AllowDefaultAttackAlways)
                    {//TODO:: Fix issue when nothing keeps returning (possibly due to bad ability setup)
                        Logger.Write(LogLevel.Ability, "Default Attack not usable -- Failed to find a valid Ability to use -- Target: {0}", Bot.Targeting.Cache.CurrentTarget.InternalName);
                        Bot.Targeting.Cache.bForceTargetUpdate = true;
                        CurrentState = RunStatus.Running;
                        Bot.Targeting.Cache.CurrentTarget.BlacklistLoops = 10;
                        return false;
                    }

                    Bot.Character.Class.PowerPrime = nextAbility;
                }

                // Select an Ability for destroying a destructible with in advance
                if (Bot.Targeting.Cache.CurrentTarget.targetType.Value == TargetType.Destructible || Bot.Targeting.Cache.CurrentTarget.targetType == TargetType.Barricade)
                    Bot.Character.Class.PowerPrime = Bot.Character.Class.DestructibleAbility();
            }
            #endregion

            #region PotionCheck
            if (Bot.Character.Data.dCurrentHealthPct <= Bot.Settings.Combat.PotionHealthPercent
                 && !Bot.Targeting.Cache.bWaitingForPower
                 && !Bot.Targeting.Cache.bWaitingForPotion
                 && !Bot.Character.Data.bIsIncapacitated
                 && Bot.Character.Class.HealthPotionAbility.AbilityUseTimer())
            {
                Bot.Targeting.Cache.bWaitingForPotion = true;
                CurrentState = RunStatus.Running;
                return false;
            }
            if (Bot.Targeting.Cache.bWaitingForPotion)
            {
                Bot.Targeting.Cache.bWaitingForPotion = false;
                if (Bot.Character.Class.HealthPotionAbility.CheckCustomCombatMethod())
                {
                    Bot.Character.Class.HealthPotionAbility.AttemptToUseHealthPotion();
                    CurrentState = RunStatus.Running;
                    return false;
                }
            }
            #endregion

            // See if we can use any special buffs etc. while in avoidance
            if (ObjectCache.CheckTargetTypeFlag(Bot.Targeting.Cache.CurrentTarget.targetType.Value, TargetType.Gold | TargetType.Globe | TargetType.AvoidanceMovements | TargetType.NoMovement))
            {
                Skill buff;
                if (Bot.Character.Class.FindBuffPower(out buff))
                {
                    Skill.UsePower(ref buff);
                    buff.OnSuccessfullyUsed();
                }
            }

            return true;
        }
Exemple #8
0
        private void SetStatus(RunStatus status)
        {
            _runStatus = status;

            switch (status)
            {
                case RunStatus.Ready:
                    tssStatus.Text = "Ready. Press any state behavior key to launch run.";
                    break;
                case RunStatus.Running:
                    tssStatus.Text = "Run is in progress.";
                    break;
                case RunStatus.Stopped:
                    tssStatus.Text = "Run is complete.";
                    break;
            }
        }
Exemple #9
0
 /// <summary>
 /// Set the run status to resetted.
 /// </summary>
 public void ResetRun()
 {
     this.runStatus = RunStatus.STOPPED;
     foreach (Segment segment in this.segments)
     {
         segment.ResetTimes(false);
         segment.SaveTimes(true);
         segment.PreviousWasSkipped = false;
     }
     this.liveIndex = -1;
 }
        protected Composite CreateMoveToAndFacePvP(float maxRange, float coneDegrees, UnitSelectionDelegate unit, bool noMovement, RunStatus result)
        {
            return new Decorator(
                ret => unit(ret) != null,
                new Action(
                    ret =>
                    {
                        if (!SingularSettings.Instance.DisableAllMovement &&
                            (!unit(ret).InLineOfSightOCD || (!noMovement && unit(ret).DistanceSqr > maxRange * maxRange)))
                        {
                            Navigator.MoveTo(unit(ret).Location);
                            return result;
                            //return RunStatus.Success;
                        }
                        else if (!SingularSettings.Instance.DisableAllMovement && Me.IsMoving &&
                            unit(ret).DistanceSqr <= maxRange * maxRange)
                        {
                            Navigator.PlayerMover.MoveStop();
                            return RunStatus.Failure;
                            //StyxWoW.SleepForLagDuration();
                        }
                        else if (Me.CurrentTarget != null && Me.CurrentTarget.IsAlive &&
                                !Me.IsSafelyFacing(Me.CurrentTarget, coneDegrees))
                        {
                            Me.CurrentTarget.Face();
                            return result;
                            // StyxWoW.SleepForLagDuration();
                            //return RunStatus.Success;
                        }

                        return RunStatus.Failure;
                    }));
        }
Exemple #11
0
 public virtual void Terminate()
 {
     switch (Status) {
         case RunStatus.Running:
             Log.Trace("Terminating Message Manager", "Terminate");
             UnregisterAll();
             Status = RunStatus.Terminated;
             break;
         case RunStatus.NotInitialized:
             Log.Warning("Can't terminate, not initialized", "Initialize");
             break;
         case RunStatus.Terminated:
             Log.Warning("Already terminated", "Initialize");
             break;
     }
 }
        protected override void ProcessRecord()
        {
            string     paramFileName = string.Empty, resultsFileName;
            RunManager runMgr = null;

            try
            {
                Dictionary <string, string> properties;
                try
                {
                    properties = GetTaskProperties();
                    if (properties == null || !properties.Any())
                    {
                        throw new AlmException("Invalid or missing properties!", ErrorCategory.InvalidData);
                    }
                }
                catch (Exception e)
                {
                    ThrowTerminatingError(new ErrorRecord(e, nameof(GetTaskProperties), ErrorCategory.ParserError, nameof(ProcessRecord)));
                    return;
                }

                string ufttfsdir = Environment.GetEnvironmentVariable(UFT_LAUNCHER);
                string propdir   = Path.GetFullPath(Path.Combine(ufttfsdir, PROPS));

                if (!Directory.Exists(propdir))
                {
                    Directory.CreateDirectory(propdir);
                }

                string resdir = Path.GetFullPath(Path.Combine(ufttfsdir, $@"res\Report_{properties[BUILD_NUMBER]}"));

                if (!Directory.Exists(resdir))
                {
                    Directory.CreateDirectory(resdir);
                }

                string timeSign = DateTime.Now.ToString(DDMMYYYYHHMMSSSSS);

                paramFileName   = Path.Combine(propdir, $"Props{timeSign}.txt");
                resultsFileName = Path.Combine(resdir, $"Results{timeSign}.xml");

                properties.Add(RESULTS_FILENAME, resultsFileName.Replace(@"\", @"\\")); // double backslashes are expected by HpToolsLauncher.exe (JavaProperties.cs, in LoadInternal method)

                if (!SaveProperties(paramFileName, properties))
                {
                    return;
                }

                //run the build task
                runMgr = GetRunManager(resdir);
                bool hasResults = Run(resultsFileName, runMgr).Result;

                RunStatus runStatus = RunStatus.FAILED;
                if (hasResults)
                {
                    var listReport = H.ReadReportFromXMLFile(resultsFileName, false, out _);
                    H.CreateSummaryReport(resdir, RunType.AlmLabManagement, listReport);
                    //get task return code
                    runStatus = H.GetRunStatus(listReport);
                    int totalTests = H.GetNumberOfTests(listReport, out IDictionary <string, int> nrOfTests);
                    if (totalTests > 0)
                    {
                        H.CreateRunSummary(runStatus, totalTests, nrOfTests, resdir);
                    }
                }
                CollateRetCode(resdir, (int)runStatus);
            }
            catch (AlmException ae)
            {
                LogError(ae, ae.Category);
                runMgr?.Stop();
            }
            catch (IOException ioe)
            {
                LogError(ioe, ErrorCategory.ResourceExists);
                runMgr?.Stop();
            }
            catch (ThreadInterruptedException e)
            {
                LogError(e, ErrorCategory.OperationStopped);
                runMgr?.Stop();
            }
        }
        /// <summary>
        /// 执行
        /// </summary>
        /// <param name="image">图像</param>
        /// <param name="outputs">输出结果</param>
        /// <returns>执行结果</returns>
        public void Execute(object image, out ItemCollection outputs)
        {
            HObject hImage = image as HObject;

            outputs = new ItemCollection();

            stopwatch.Restart();

            // Local iconic variables

            HObject ho_GrayImage, ho_ImageMean, ho_RegionDynThresh;
            HObject ho_RegionFillUp, ho_ConnectedRegions, ho_SelectedRegions1;
            HObject ho_SelectedRegions2, ho_Regions1 = null, ho_Regions2 = null;
            HObject ho_Circle1 = null, ho_Circle2 = null, ho_Cross1 = null;
            HObject ho_Arrow = null;

            // Local control variables

            HTuple hv_Number1 = null, hv_Number2 = null, hv_Row1 = new HTuple();
            HTuple hv_Column1 = new HTuple(), hv_Radius1 = new HTuple();
            HTuple hv_Row2 = new HTuple(), hv_Column2 = new HTuple();
            HTuple hv_Radius2 = new HTuple(), hv_RowArray1 = new HTuple();
            HTuple hv_ColumnArray1 = new HTuple(), hv_RowArray2 = new HTuple();
            HTuple hv_ColumnArray2 = new HTuple(), hv_ResultRow1 = new HTuple();
            HTuple hv_ResultColumn1 = new HTuple(), hv_ArcType1 = new HTuple();
            HTuple hv_ResultRow2 = new HTuple(), hv_ResultColumn2 = new HTuple();
            HTuple hv_ArcType2 = new HTuple(), hv_RowCenter1 = new HTuple();
            HTuple hv_ColCenter1 = new HTuple(), hv_StartPhi1 = new HTuple();
            HTuple hv_EndPhi1 = new HTuple(), hv_PointOrder1 = new HTuple();
            HTuple hv_ArcAngle1 = new HTuple(), hv_RowCenter2 = new HTuple();
            HTuple hv_ColCenter2 = new HTuple(), hv_StartPhi2 = new HTuple();
            HTuple hv_EndPhi2 = new HTuple(), hv_PointOrder2 = new HTuple();
            HTuple hv_ArcAngle2 = new HTuple(), hv_Angle = new HTuple();
            HTuple hv_HomMat2D = new HTuple(), hv_Qy = new HTuple();
            HTuple hv_Qx = new HTuple();

            // Initialize local and output iconic variables
            HOperatorSet.GenEmptyObj(out ho_GrayImage);
            HOperatorSet.GenEmptyObj(out ho_ImageMean);
            HOperatorSet.GenEmptyObj(out ho_RegionDynThresh);
            HOperatorSet.GenEmptyObj(out ho_RegionFillUp);
            HOperatorSet.GenEmptyObj(out ho_ConnectedRegions);
            HOperatorSet.GenEmptyObj(out ho_SelectedRegions1);
            HOperatorSet.GenEmptyObj(out ho_SelectedRegions2);
            HOperatorSet.GenEmptyObj(out ho_Regions1);
            HOperatorSet.GenEmptyObj(out ho_Regions2);
            HOperatorSet.GenEmptyObj(out ho_Circle1);
            HOperatorSet.GenEmptyObj(out ho_Circle2);
            HOperatorSet.GenEmptyObj(out ho_Cross1);
            HOperatorSet.GenEmptyObj(out ho_Arrow);

            try
            {
                HTuple width, height;
                HOperatorSet.GetImageSize(hImage, out width, out height);

                //若未初始化,则进行初始化
                if (!isInit)
                {
                    isInit = true;
                }

                if (runningWindow == null)
                {
                    try
                    {
                        runningWindow = (RunningWindow as HSmartWindowControlWPF).HalconWindow;
                    }
                    catch (Exception)
                    {
                    }
                }

                if (configWindow == null)
                {
                    try
                    {
                        configWindow = (ConfigWindow as HSmartWindowControlWPF).HalconWindow;
                    }
                    catch (Exception)
                    {
                    }
                }

                if (runningWindow != null)
                {
                    HOperatorSet.ClearWindow(runningWindow);
                    HOperatorSet.DispObj(hImage, runningWindow);
                    UpdatePart(runningWindow);
                }

                if (configWindow != null)
                {
                    HOperatorSet.ClearWindow(configWindow);
                    HOperatorSet.DispObj(hImage, configWindow);
                    UpdatePart(runningWindow);
                }

                //执行主任务
                //转为灰度图
                ho_GrayImage.Dispose();
                HOperatorSet.Rgb1ToGray(hImage, out ho_GrayImage);

                //动态阈值分割
                ho_ImageMean.Dispose();
                HOperatorSet.MeanImage(ho_GrayImage, out ho_ImageMean, new HTuple(Inputs["MeanImageMaskHeight"].Value), new HTuple(Inputs["MeanImageMaskWidth"].Value));
                ho_RegionDynThresh.Dispose();
                HOperatorSet.DynThreshold(ho_GrayImage, ho_ImageMean, out ho_RegionDynThresh,
                                          new HTuple(Inputs["DynThresholdOffset"].Value), "dark");

                //填充并获取圆
                ho_RegionFillUp.Dispose();
                HOperatorSet.FillUp(ho_RegionDynThresh, out ho_RegionFillUp);
                ho_ConnectedRegions.Dispose();
                HOperatorSet.Connection(ho_RegionFillUp, out ho_ConnectedRegions);
                ho_SelectedRegions1.Dispose();
                HOperatorSet.SelectShape(ho_ConnectedRegions, out ho_SelectedRegions1, (new HTuple("circularity")).TupleConcat(
                                             "area"), "and", (new HTuple(Inputs["Blob1MincirCularity"].Value)).TupleConcat(new HTuple(Inputs["Blob1MinArea"].Value)), (new HTuple(1.2)).TupleConcat(
                                             new HTuple(Inputs["Blob1MaxArea"].Value)));
                ho_SelectedRegions2.Dispose();
                HOperatorSet.SelectShape(ho_ConnectedRegions, out ho_SelectedRegions2, (new HTuple("circularity")).TupleConcat(
                                             "area"), "and", (new HTuple(Inputs["Blob2MincirCularity"].Value)).TupleConcat(new HTuple(Inputs["Blob2MinArea"].Value)), (new HTuple(1.2)).TupleConcat(
                                             new HTuple(Inputs["Blob2MaxArea"].Value)));

                HOperatorSet.CountObj(ho_SelectedRegions1, out hv_Number1);
                HOperatorSet.CountObj(ho_SelectedRegions2, out hv_Number2);

                if ((hv_Number1.I == 1) && (hv_Number2.I == 1))
                {
                    //产生最小外接圆
                    HOperatorSet.SmallestCircle(ho_SelectedRegions1, out hv_Row1, out hv_Column1,
                                                out hv_Radius1);
                    HOperatorSet.SmallestCircle(ho_SelectedRegions2, out hv_Row2, out hv_Column2,
                                                out hv_Radius2);

                    hv_RowArray1    = new HTuple(new double[] { hv_Row1 + hv_Radius1, hv_Row1, hv_Row1 - hv_Radius1, hv_Row1, hv_Row1 + hv_Radius1 });
                    hv_ColumnArray1 = new HTuple(new double[] { hv_Column1, hv_Column1 + hv_Radius1, hv_Column1, hv_Column1 - hv_Radius1, hv_Column1 });
                    hv_RowArray2    = new HTuple(new double[] { hv_Row2 + hv_Radius2, hv_Row2, hv_Row2 - hv_Radius2, hv_Row2, hv_Row2 + hv_Radius2 });
                    hv_ColumnArray2 = new HTuple(new double[] { hv_Column2, hv_Column2 + hv_Radius2, hv_Column2, hv_Column2 - hv_Radius2, hv_Column2 });

                    //对最小外接圆的位置进行圆拟合
                    ho_Regions1.Dispose();
                    spoke(ho_GrayImage, out ho_Regions1, (new HTuple(Inputs["Elements"].Value)), (new HTuple(Inputs["DetectHeight"].Value)), (new HTuple(Inputs["DetectWidth"].Value)), (new HTuple(Inputs["Sigma"].Value)), (new HTuple(Inputs["Threshold"].Value)), (new HTuple(Inputs["Transition"].Value)), (new HTuple(Inputs["Select"].Value)),
                          hv_RowArray1, hv_ColumnArray1, "outer", out hv_ResultRow1, out hv_ResultColumn1,
                          out hv_ArcType1);
                    ho_Regions2.Dispose();
                    spoke(ho_GrayImage, out ho_Regions2, (new HTuple(Inputs["Elements"].Value)), (new HTuple(Inputs["DetectHeight"].Value)), (new HTuple(Inputs["DetectWidth"].Value)), (new HTuple(Inputs["Sigma"].Value)), (new HTuple(Inputs["Threshold"].Value)), (new HTuple(Inputs["Transition"].Value)), (new HTuple(Inputs["Select"].Value)),
                          hv_RowArray2, hv_ColumnArray2, "outer", out hv_ResultRow2, out hv_ResultColumn2,
                          out hv_ArcType2);
                    ho_Circle1.Dispose();
                    pts_to_best_circle(out ho_Circle1, hv_ResultRow1, hv_ResultColumn1, (new HTuple(Inputs["ActiveNum"].Value)), "circle",
                                       out hv_RowCenter1, out hv_ColCenter1, out hv_Radius1, out hv_StartPhi1,
                                       out hv_EndPhi1, out hv_PointOrder1, out hv_ArcAngle1);
                    ho_Circle2.Dispose();
                    pts_to_best_circle(out ho_Circle2, hv_ResultRow2, hv_ResultColumn2, (new HTuple(Inputs["ActiveNum"].Value)), "circle",
                                       out hv_RowCenter2, out hv_ColCenter2, out hv_Radius2, out hv_StartPhi2,
                                       out hv_EndPhi2, out hv_PointOrder2, out hv_ArcAngle2);

                    //计算角度
                    HOperatorSet.AngleLx(hv_RowCenter1, hv_ColCenter1, hv_RowCenter2, hv_ColCenter2,
                                         out hv_Angle);

                    ho_Cross1.Dispose();
                    HOperatorSet.GenCrossContourXld(out ho_Cross1, hv_RowCenter1, hv_ColCenter1,
                                                    32, hv_Angle + ((new HTuple(45)).TupleRad()));
                    ho_Arrow.Dispose();
                    gen_arrow_contour_xld(out ho_Arrow, hv_RowCenter1, hv_ColCenter1, hv_RowCenter2,
                                          hv_ColCenter2, 25, 25);

                    //计算仿射变换矩阵
                    HOperatorSet.VectorAngleToRigid((new HTuple(Inputs["BaseY"].Value)), (new HTuple(Inputs["BaseX"].Value)), (new HTuple(Inputs["BaseAngle"].Value)), hv_RowCenter1,
                                                    hv_ColCenter1, hv_Angle, out hv_HomMat2D);

                    //计算仿射变换结果
                    HOperatorSet.AffineTransPoint2d(hv_HomMat2D, (new HTuple(Inputs["LocationY1"].Value)), (new HTuple(Inputs["LocationX1"].Value)),
                                                    out hv_Qy, out hv_Qx);
                    Outputs["LocationX1"].Value = hv_Qx.D;
                    Outputs["LocationY1"].Value = hv_Qy.D;

                    HOperatorSet.AffineTransPoint2d(hv_HomMat2D, (new HTuple(Inputs["LocationY2"].Value)), (new HTuple(Inputs["LocationX2"].Value)),
                                                    out hv_Qy, out hv_Qx);
                    Outputs["LocationX2"].Value = hv_Qx.D;
                    Outputs["LocationY2"].Value = hv_Qy.D;

                    HOperatorSet.AffineTransPoint2d(hv_HomMat2D, (new HTuple(Inputs["LocationY3"].Value)), (new HTuple(Inputs["LocationX3"].Value)),
                                                    out hv_Qy, out hv_Qx);
                    Outputs["LocationX3"].Value = hv_Qx.D;
                    Outputs["LocationY3"].Value = hv_Qy.D;

                    //显示结果
                    //HOperatorSet.DispObj(ho_Image, hv_ExpDefaultWinHandle);
                    //HOperatorSet.DispObj(ho_SelectedRegions1, hv_ExpDefaultWinHandle);
                    //HOperatorSet.DispObj(ho_SelectedRegions2, hv_ExpDefaultWinHandle);
                    //HOperatorSet.DispObj(ho_Arrow, hv_ExpDefaultWinHandle);
                    //HOperatorSet.DispObj(ho_Cross1, hv_ExpDefaultWinHandle);
                }

                //显示结果
                if (runningWindow != null)
                {
                    UpdatePart(runningWindow);
                }

                if (configWindow != null)
                {
                    UpdatePart(runningWindow);
                }

                stopwatch.Stop();
                RunStatus = new RunStatus(stopwatch.Elapsed.TotalMilliseconds);

                outputs = new ItemCollection(Outputs);
            }
            catch (Exception ex)
            {
                stopwatch.Stop();
                RunStatus = new RunStatus(stopwatch.Elapsed.TotalMilliseconds, EResult.Error, ex.Message, ex);
                throw;
            }
            finally
            {
                hImage.Dispose();

                ho_GrayImage.Dispose();
                ho_ImageMean.Dispose();
                ho_RegionDynThresh.Dispose();
                ho_RegionFillUp.Dispose();
                ho_ConnectedRegions.Dispose();
                ho_SelectedRegions1.Dispose();
                ho_SelectedRegions2.Dispose();
                ho_Regions1.Dispose();
                ho_Regions2.Dispose();
                ho_Circle1.Dispose();
                ho_Circle2.Dispose();
                ho_Cross1.Dispose();
                ho_Arrow.Dispose();
            }
        }
Exemple #14
0
 /// <summary>
 /// Set the Stop flag.  The various threads will monitor this flag
 /// And stop
 /// </summary>
 public void Stop()
 {
     _runStatus     = RunStatus.Stopped;
     _executedquery = 0;
 }
Exemple #15
0
        public static Dictionary <string, object> LoadAnalysisResults(int RunID, int ParametricRunID = 0, bool enable = false)
        {
            // Initiate the Revit Auth
            Helper.InitRevitAuthProvider();

            if (!enable) // don't block the dynamo solution
            {
                // Defense for 'bad request', check status of RunId
                string requestGetRunStatusUri = GBSUri.GBSAPIUri +
                                                string.Format(APIV1Uri.GetRunStatus, RunID, ParametricRunID, "json");
                HttpWebResponse response       = (HttpWebResponse)Helper._CallGetApi(requestGetRunStatusUri);
                Stream          responseStream = response.GetResponseStream();
                StreamReader    reader         = new StreamReader(responseStream);
                string          result         = reader.ReadToEnd();
                RunStatus       runStatus      = Helper.DataContractJsonDeserialize <RunStatus>(result);
                int             percentStatus  = runStatus.StatusPercentDone;

                if (percentStatus < 100)
                {
                    throw new Exception(System.String.Format("Run Status: {0}% - {1}", percentStatus, runStatus.DetailedStatus));
                }
            }
            else // true, blocks the dynamo solution until simulation being completed
            {
                int percentStatus = 0;
                while (percentStatus < 100)
                {
                    string requestGetRunStatusUri = GBSUri.GBSAPIUri +
                                                    string.Format(APIV1Uri.GetRunStatus, RunID, ParametricRunID, "json");
                    HttpWebResponse response       = (HttpWebResponse)Helper._CallGetApi(requestGetRunStatusUri);
                    Stream          responseStream = response.GetResponseStream();
                    StreamReader    reader         = new StreamReader(responseStream);
                    string          result         = reader.ReadToEnd();
                    RunStatus       runStatus      = Helper.DataContractJsonDeserialize <RunStatus>(result);
                    percentStatus = runStatus.StatusPercentDone;
                }
            }

            //Get results Summary of given RunID & AltRunID
            string requestGetRunSummaryResultsUri = GBSUri.GBSAPIUri +
                                                    string.Format(APIV1Uri.GetRunSummaryResultsUri, RunID, ParametricRunID, "json");
            HttpWebResponse  response2        = (HttpWebResponse)Helper._CallGetApi(requestGetRunSummaryResultsUri);
            Stream           responseStream2  = response2.GetResponseStream();
            StreamReader     reader2          = new StreamReader(responseStream2);
            string           resultSummary    = reader2.ReadToEnd();
            RunResultSummary runResultSummary = Helper.DataContractJsonDeserialize <RunResultSummary>(resultSummary);

            string buildingsummary = "Number of People : " + runResultSummary.BuildingSummary.NumberOfPeople.Value + " " + runResultSummary.BuildingSummary.NumberOfPeople.Units + "\n" +
                                     "Average Lighting Power Density : " + runResultSummary.BuildingSummary.AvgLightingPowerDensity.Value + " " + runResultSummary.BuildingSummary.AvgLightingPowerDensity.Units + "\n" +
                                     "Average Equipment Power Density : " + runResultSummary.BuildingSummary.AvgEquipmentPowerDensity.Value + " " + runResultSummary.BuildingSummary.AvgEquipmentPowerDensity.Units + "\n" +
                                     "Specific Fan Flow : " + runResultSummary.BuildingSummary.SpecificFanFlow.Value + " " + runResultSummary.BuildingSummary.SpecificFanFlow.Units + "\n" +
                                     "Specific Fan Power : " + runResultSummary.BuildingSummary.SpecificFanPower.Value + " " + runResultSummary.BuildingSummary.SpecificFanPower.Units + "\n" +
                                     "Specific Cooling : " + runResultSummary.BuildingSummary.SpecificCooling.Value + " " + runResultSummary.BuildingSummary.SpecificCooling.Units + "\n" +
                                     "Specific Heating : " + runResultSummary.BuildingSummary.SpecificHeating.Value + " " + runResultSummary.BuildingSummary.SpecificHeating.Units + "\n" +
                                     "Total Fan Flow : " + runResultSummary.BuildingSummary.TotalFanFlow.Value + " " + runResultSummary.BuildingSummary.TotalFanFlow.Units + "\n" +
                                     "Total Cooling Capacity : " + runResultSummary.BuildingSummary.TotalCoolingCapacity.Value + " " + runResultSummary.BuildingSummary.TotalCoolingCapacity.Units + "\n" +
                                     "Total Heating Capacity : " + runResultSummary.BuildingSummary.TotalHeatingCapacity.Value + " " + runResultSummary.BuildingSummary.TotalHeatingCapacity.Units + "\n";

            List <object> floorarea = new List <object>();

            floorarea.Add((double)runResultSummary.FloorArea.Value);
            floorarea.Add(runResultSummary.FloorArea.Units);

            //Populate outputs
            return(new Dictionary <string, object>
            {
                { "Results", runResultSummary },
                { "BuildingType", runResultSummary.BuildingType },
                { "Location", runResultSummary.Location },
                { "FloorArea", floorarea },
                { "BuildingSummary", buildingsummary }
            });
        }
        /// <summary>
        /// 执行
        /// </summary>
        /// <param name="image">图像</param>
        /// <param name="outputs">输出结果</param>
        /// <returns>执行结果</returns>
        public void Execute(object image, out ItemCollection outputs)
        {
            HObject hImage = image as HObject;

            outputs = new ItemCollection();

            stopwatch.Restart();

            HObject ho_ImageReduced = null;
            HObject ho_R = null, ho_G = null, ho_B = null, ho_Hue = null, ho_Saturation = null;
            HObject ho_Intensity = null, ho_Regions = null, ho_RegionOpening = null;
            HObject ho_RegionClosing = null, ho_ImageReduced2 = null, ho_Regions1 = null;
            HObject ho_RegionOpening1 = null, ho_RegionClosing1 = null;
            HObject ho_ImageReduced3 = null, ho_Regions2 = null, ho_RegionOpening2 = null;
            HObject ho_RegionClosing2 = null, ho_RegionDifference = null;
            HObject ho_RegionOpening3 = null, ho_ConnectedRegions = null;
            HObject ho_RegionFillUp = null, ho_SelectedRegions = null, ho_Skeleton = null, ho_EndPoints = null;
            HObject ho_JuncPoints = null, ho_RegionDifference1 = null, ho_ConnectedRegions1 = null;
            HObject ho_SelectedRegions1 = null, ho_Rectangle = null, ho_Contours = null;
            HObject ho_SelectedXLD = null, ho_UnionContours = null, ho_SelectedXLD1 = null;
            HObject ho_Cross = null, ho_ObjectSelected = null;

            HTuple hv_Number = new HTuple();
            HTuple hv_Row = new HTuple(), hv_Column = new HTuple();
            HTuple hv_Phi = new HTuple(), hv_Length1 = new HTuple();
            HTuple hv_Length2 = new HTuple(), hv_Row1 = new HTuple();
            HTuple hv_Col1 = new HTuple(), hv_RowMedian = new HTuple();
            HTuple hv_ColMedian = new HTuple(), hv_Exception = new HTuple();
            HTuple hv_Length = new HTuple();

            HOperatorSet.GenEmptyObj(out ho_ImageReduced);
            HOperatorSet.GenEmptyObj(out ho_R);
            HOperatorSet.GenEmptyObj(out ho_G);
            HOperatorSet.GenEmptyObj(out ho_B);
            HOperatorSet.GenEmptyObj(out ho_Hue);
            HOperatorSet.GenEmptyObj(out ho_Saturation);
            HOperatorSet.GenEmptyObj(out ho_Intensity);
            HOperatorSet.GenEmptyObj(out ho_Regions);
            HOperatorSet.GenEmptyObj(out ho_RegionOpening);
            HOperatorSet.GenEmptyObj(out ho_RegionClosing);
            HOperatorSet.GenEmptyObj(out ho_ImageReduced2);
            HOperatorSet.GenEmptyObj(out ho_Regions1);
            HOperatorSet.GenEmptyObj(out ho_RegionOpening1);
            HOperatorSet.GenEmptyObj(out ho_RegionClosing1);
            HOperatorSet.GenEmptyObj(out ho_ImageReduced3);
            HOperatorSet.GenEmptyObj(out ho_Regions2);
            HOperatorSet.GenEmptyObj(out ho_RegionOpening2);
            HOperatorSet.GenEmptyObj(out ho_RegionClosing2);
            HOperatorSet.GenEmptyObj(out ho_RegionDifference);
            HOperatorSet.GenEmptyObj(out ho_RegionOpening3);
            HOperatorSet.GenEmptyObj(out ho_ConnectedRegions);
            HOperatorSet.GenEmptyObj(out ho_RegionFillUp);
            HOperatorSet.GenEmptyObj(out ho_SelectedRegions);
            HOperatorSet.GenEmptyObj(out ho_Skeleton);
            HOperatorSet.GenEmptyObj(out ho_EndPoints);
            HOperatorSet.GenEmptyObj(out ho_JuncPoints);
            HOperatorSet.GenEmptyObj(out ho_RegionDifference1);
            HOperatorSet.GenEmptyObj(out ho_ConnectedRegions1);
            HOperatorSet.GenEmptyObj(out ho_SelectedRegions1);
            HOperatorSet.GenEmptyObj(out ho_Rectangle);
            HOperatorSet.GenEmptyObj(out ho_Contours);
            HOperatorSet.GenEmptyObj(out ho_SelectedXLD);
            HOperatorSet.GenEmptyObj(out ho_UnionContours);
            HOperatorSet.GenEmptyObj(out ho_SelectedXLD1);
            HOperatorSet.GenEmptyObj(out ho_Cross);
            HOperatorSet.GenEmptyObj(out ho_ObjectSelected);

            try
            {
                HTuple width, height;
                HOperatorSet.GetImageSize(hImage, out width, out height);

                //若未初始化,则进行初始化
                if (!isInit)
                {
                    isInit = true;

                    ho_ROI_0?.Dispose();
                    HOperatorSet.GenRectangle1(out ho_ROI_0, 0, 0, height, width);
                }

                if (runningWindow == null)
                {
                    try
                    {
                        runningWindow = (RunningWindow as HSmartWindowControlWPF).HalconWindow;
                    }
                    catch (Exception)
                    {
                    }
                }

                if (configWindow == null)
                {
                    try
                    {
                        configWindow = (ConfigWindow as HSmartWindowControlWPF).HalconWindow;
                    }
                    catch (Exception)
                    {
                    }
                }

                if (runningWindow != null)
                {
                    SetWindowPart(runningWindow, width, height);
                    HOperatorSet.ClearWindow(runningWindow);
                    HOperatorSet.DispObj(hImage, runningWindow);
                }

                if (configWindow != null)
                {
                    SetWindowPart(configWindow, width, height);
                    HOperatorSet.ClearWindow(configWindow);
                    HOperatorSet.DispObj(hImage, configWindow);
                }

                //执行主任务
                HOperatorSet.ReduceDomain(hImage, ho_ROI_0, out ho_ImageReduced);

                //转成HSV格式
                ho_R.Dispose(); ho_G.Dispose(); ho_B.Dispose();
                HOperatorSet.Decompose3(ho_ImageReduced, out ho_R, out ho_G, out ho_B);
                ho_Hue.Dispose(); ho_Saturation.Dispose(); ho_Intensity.Dispose();
                HOperatorSet.TransFromRgb(ho_R, ho_G, ho_B, out ho_Hue, out ho_Saturation,
                                          out ho_Intensity, "hsv");

                //提取背景区域
                ho_Regions.Dispose();
                HOperatorSet.Threshold(ho_Hue, out ho_Regions, new HTuple(Inputs["HMinThreshold"].Value), new HTuple(Inputs["HMaxThreshold"].Value));
                ho_RegionOpening.Dispose();
                HOperatorSet.OpeningCircle(ho_Regions, out ho_RegionOpening, new HTuple(Inputs["OpenRadius"].Value));
                ho_RegionClosing.Dispose();
                HOperatorSet.ClosingCircle(ho_RegionOpening, out ho_RegionClosing, new HTuple(Inputs["CloseRadius"].Value));
                ho_ImageReduced2.Dispose();
                HOperatorSet.ReduceDomain(ho_Saturation, ho_RegionClosing, out ho_ImageReduced2
                                          );
                ho_Regions1.Dispose();
                HOperatorSet.Threshold(ho_ImageReduced2, out ho_Regions1, new HTuple(Inputs["SMinThreshold"].Value), new HTuple(Inputs["SMaxThreshold"].Value));
                ho_RegionOpening1.Dispose();
                HOperatorSet.OpeningCircle(ho_Regions1, out ho_RegionOpening1, new HTuple(Inputs["OpenRadius"].Value));
                ho_RegionClosing1.Dispose();
                HOperatorSet.ClosingCircle(ho_RegionOpening1, out ho_RegionClosing1, new HTuple(Inputs["CloseRadius"].Value));
                ho_ImageReduced3.Dispose();
                HOperatorSet.ReduceDomain(ho_Intensity, ho_RegionClosing1, out ho_ImageReduced3
                                          );
                ho_Regions2.Dispose();
                HOperatorSet.Threshold(ho_ImageReduced3, out ho_Regions2, new HTuple(Inputs["IMinThreshold"].Value), new HTuple(Inputs["IMaxThreshold"].Value));
                ho_RegionOpening2.Dispose();
                HOperatorSet.OpeningCircle(ho_Regions2, out ho_RegionOpening2, new HTuple(Inputs["OpenRadius"].Value));
                ho_RegionClosing2.Dispose();
                HOperatorSet.ClosingCircle(ho_RegionOpening2, out ho_RegionClosing2, new HTuple(Inputs["CloseRadius"].Value));

                //求出眼镜腿区域
                ho_RegionDifference.Dispose();
                HOperatorSet.Difference(ho_ROI_0, ho_RegionClosing2, out ho_RegionDifference
                                        );
                ho_RegionOpening3.Dispose();
                HOperatorSet.OpeningCircle(ho_RegionDifference, out ho_RegionOpening3,
                                           8);
                ho_ConnectedRegions.Dispose();
                HOperatorSet.Connection(ho_RegionOpening3, out ho_ConnectedRegions);
                ho_RegionFillUp.Dispose();
                HOperatorSet.FillUp(ho_ConnectedRegions, out ho_RegionFillUp);
                ho_SelectedRegions.Dispose();
                HOperatorSet.SelectShape(ho_RegionFillUp, out ho_SelectedRegions, (
                                             (new HTuple("area")).TupleConcat("rect2_len1")).TupleConcat("rect2_len2"),
                                         "and", ((new HTuple(Inputs["MinArea"].Value)).TupleConcat(new HTuple(Inputs["MinLen1"].Value))).TupleConcat(new HTuple(Inputs["MinLen2"].Value)), ((new HTuple(Inputs["MaxArea"].Value)).TupleConcat(
                                                                                                                                                                                                new HTuple(Inputs["MaxLen1"].Value))).TupleConcat(new HTuple(Inputs["MaxLen2"].Value)));

                //校验模板结果
                HOperatorSet.CountObj(ho_SelectedRegions, out hv_Number);
                if (hv_Number.I > 0)
                {
                    Location[] locations = new Location[hv_Number.I];

                    for (int i = 0; i < hv_Number.I; i++)
                    {
                        ho_ObjectSelected.Dispose();
                        HOperatorSet.SelectObj(ho_SelectedRegions, out ho_ObjectSelected, i + 1);

                        //产生骨骼
                        ho_Skeleton.Dispose();
                        HOperatorSet.Skeleton(ho_ObjectSelected, out ho_Skeleton);

                        //计算骨骼端点和关节点
                        ho_EndPoints.Dispose(); ho_JuncPoints.Dispose();
                        HOperatorSet.JunctionsSkeleton(ho_Skeleton, out ho_EndPoints, out ho_JuncPoints
                                                       );

                        //从骨骼中去除关节点
                        ho_RegionDifference1.Dispose();
                        HOperatorSet.Difference(ho_Skeleton, ho_JuncPoints, out ho_RegionDifference1
                                                );

                        //提取最长的骨骼
                        ho_ConnectedRegions1.Dispose();
                        HOperatorSet.Connection(ho_RegionDifference1, out ho_ConnectedRegions1
                                                );
                        ho_SelectedRegions1.Dispose();
                        HOperatorSet.SelectShapeStd(ho_ConnectedRegions1, out ho_SelectedRegions1,
                                                    "max_area", 70);

                        HOperatorSet.SmallestRectangle2(ho_SelectedRegions1, out hv_Row, out hv_Column,
                                                        out hv_Phi, out hv_Length1, out hv_Length2);
                        ho_Rectangle.Dispose();
                        HOperatorSet.GenRectangle2(out ho_Rectangle, hv_Row, hv_Column, hv_Phi,
                                                   hv_Length1, hv_Length2);

                        //转成xld
                        ho_Contours.Dispose();
                        HOperatorSet.GenContoursSkeletonXld(ho_Skeleton, out ho_Contours, 1,
                                                            "filter");

                        ho_SelectedXLD.Dispose();
                        HOperatorSet.SelectShapeXld(ho_Contours, out ho_SelectedXLD, (new HTuple("rect2_phi")).TupleConcat(
                                                        "rect2_phi"), "or", (((((hv_Phi.TupleDeg()) - new HTuple(Inputs["XLDPhi"].Value))).TupleRad())).TupleConcat(
                                                        ((((hv_Phi.TupleDeg()) + 180) - new HTuple(Inputs["XLDPhi"].Value))).TupleRad()), (((((hv_Phi.TupleDeg()
                                                                                                                                               ) + new HTuple(Inputs["XLDPhi"].Value))).TupleRad())).TupleConcat(((((hv_Phi.TupleDeg()) + 180) + new HTuple(Inputs["XLDPhi"].Value))).TupleRad()
                                                                                                                                                                                                                 ));
                        ho_UnionContours.Dispose();
                        HOperatorSet.UnionAdjacentContoursXld(ho_SelectedXLD, out ho_UnionContours,
                                                              30, 1, "attr_keep");

                        //选择最长的xlds
                        HTuple hv_SortIndex = new HTuple();
                        HOperatorSet.LengthXld(ho_UnionContours, out hv_Length);
                        HOperatorSet.TupleSortIndex(hv_Length, out hv_SortIndex);
                        ho_SelectedXLD1.Dispose();
                        HOperatorSet.SelectObj(ho_UnionContours, out ho_SelectedXLD1, hv_SortIndex[hv_SortIndex.Length - 1].I + 1);
                        HOperatorSet.GetContourXld(ho_SelectedXLD1, out hv_Row1, out hv_Col1);


                        ho_Cross.Dispose();
                        HOperatorSet.GenCrossContourXld(out ho_Cross, hv_Row1[hv_Row1.Length / 2], hv_Col1[hv_Col1.Length / 2],
                                                        100, ((new HTuple(45)).TupleRad()) + hv_Phi);

                        if (runningWindow != null)
                        {
                            HOperatorSet.DispObj(ho_SelectedXLD1, runningWindow);
                            HOperatorSet.DispObj(ho_Cross, runningWindow);
                        }

                        if (configWindow != null)
                        {
                            HOperatorSet.DispObj(ho_SelectedXLD1, configWindow);
                            HOperatorSet.DispObj(ho_Cross, configWindow);
                        }

                        locations[i] = new Location(hv_Col1[hv_Col1.Length / 2].D, hv_Row1[hv_Row1.Length / 2].D, hv_Phi[0].D);
                    }

                    if ((bool)Inputs["AutoSave"].Value == true)
                    {
                        //保存文件到本地
                        HOperatorSet.WriteImage(hImage, "bmp", 0, new HTuple(Inputs["ImagePath"].Value));
                    }

                    //封装有效结果
                    Outputs["ItemLocation"].Value = locations;

                    stopwatch.Stop();
                    RunStatus = new RunStatus(stopwatch.Elapsed.TotalMilliseconds);
                }
                else
                {
                    //没有有效的结果
                    Outputs["ItemLocation"].Value = new Location[0];

                    stopwatch.Stop();
                    RunStatus = new RunStatus(stopwatch.Elapsed.TotalMilliseconds, EResult.Warning, "没找到有效目标");
                }

                outputs = new ItemCollection(Outputs);
            }
            catch (Exception ex)
            {
                stopwatch.Stop();
                RunStatus = new RunStatus(stopwatch.Elapsed.TotalMilliseconds, EResult.Error, ex.Message, ex);
                throw;
            }
            finally
            {
                hImage.Dispose();

                ho_ImageReduced.Dispose();
                ho_R.Dispose();
                ho_G.Dispose();
                ho_B.Dispose();
                ho_Hue.Dispose();
                ho_Saturation.Dispose();
                ho_Intensity.Dispose();
                ho_Regions.Dispose();
                ho_RegionOpening.Dispose();
                ho_RegionClosing.Dispose();
                ho_ImageReduced2.Dispose();
                ho_Regions1.Dispose();
                ho_RegionOpening1.Dispose();
                ho_RegionClosing1.Dispose();
                ho_ImageReduced3.Dispose();
                ho_Regions2.Dispose();
                ho_RegionOpening2.Dispose();
                ho_RegionClosing2.Dispose();
                ho_RegionDifference.Dispose();
                ho_RegionOpening3.Dispose();
                ho_ConnectedRegions.Dispose();
                ho_RegionFillUp.Dispose();
                ho_SelectedRegions.Dispose();
                ho_Skeleton.Dispose();
                ho_EndPoints.Dispose();
                ho_JuncPoints.Dispose();
                ho_RegionDifference1.Dispose();
                ho_ConnectedRegions1.Dispose();
                ho_SelectedRegions1.Dispose();
                ho_Rectangle.Dispose();
                ho_Contours.Dispose();
                ho_SelectedXLD.Dispose();
                ho_UnionContours.Dispose();
                ho_SelectedXLD1.Dispose();
                ho_Cross.Dispose();
                ho_ObjectSelected.Dispose();
            }
        }
Exemple #17
0
        public static RunStatus OutOfGameBehavior(object ret)
        {
            if (CharacterControl.GamblingCharacterSwitch)
            {
                return(CharacterControl.GamblingCharacterSwitchBehavior());
            }


            if (MuleBehavior)
            {
                if (!InitMuleBehavior)
                {
                    Finished                 = false;
                    InitMuleBehavior         = true;
                    NewMuleGame.BotHeroName  = ZetaDia.Service.Hero.Name;
                    NewMuleGame.BotHeroIndex = 0;
                    NewMuleGame.LastProfile  = ProfileManager.CurrentProfile.Path;
                    NewMuleGame.LastHandicap = CharacterSettings.Instance.MonsterPowerLevel;
                }

                if (!CreatedCharacter)
                {
                    RunStatus NewHeroStatus = CreateNewHero();

                    if (NewHeroStatus == RunStatus.Success)
                    {
                        CreatedCharacter = true;
                        //Setup Settings
                        //Bot.Character.Account.UpdateCurrentAccountDetails();
                        Settings.PluginSettings.LoadSettings();
                    }
                    return(RunStatus.Running);
                }

                if (!RanProfile)
                {
                    RunStatus NewGameStatus = NewMuleGame.BeginNewGameProfile();
                    if (NewGameStatus == RunStatus.Success)
                    {
                        RanProfile = true;
                        return(RunStatus.Success);
                    }
                    return(RunStatus.Running);
                }

                RunStatus FinishStatus = NewMuleGame.FinishMuleBehavior();
                if (FinishStatus == RunStatus.Success)
                {
                    Finished         = true;
                    RanProfile       = false;
                    CreatedCharacter = false;
                    InitMuleBehavior = false;
                    MuleBehavior     = false;
                    //Load Settings
                    //Bot.Character.Account.UpdateCurrentAccountDetails();
                    Settings.PluginSettings.LoadSettings();

                    return(RunStatus.Success);
                }
                return(RunStatus.Running);
            }


            if (ExitGameBehavior.BehaviorEngaged)
            {
                //Get First or Last Used Profile..
                TrackedProfile firstProfile = FunkyGame.CurrentStats.GetFirstProfile();

                string profile = firstProfile != null ? firstProfile.ProfileName :
                                 GlobalSettings.Instance.LastProfile;

                //Load Profile and Fire our left game handler
                ProfileManager.Load(profile);
                //EventHandlers.FunkyOnLeaveGame(null, null);

                //Finally disable this..
                ExitGameBehavior.BehaviorEngaged = false;
                ExitGameBehavior.ShouldExitGame  = false;
            }

            //Custom Hero Setting Game Difficulty
            if (!CharacterControl.GameDifficultyChanged)
            {
                CharacterControl.GameDifficultyChanged = true;
                var customdifficulty = (GameDifficulty)Enum.Parse(typeof(GameDifficulty), FunkyBaseExtension.Settings.General.CustomDifficulty);
                CharacterSettings.Instance.GameDifficulty = customdifficulty;
            }

            return(RunStatus.Success);
        }
        private RunStatus RunVerifierExecutable(string fullExePath, StringLineReceived stdoutLineReceived, string args = null)
        {
            var outStatus = new RunStatus();
            using (var proc = new Process())
            {
                var startInfo = new ProcessStartInfo(fullExePath);
                if (!String.IsNullOrEmpty(args))
                    startInfo.Arguments = args;

                startInfo.CreateNoWindow = true;
                startInfo.UseShellExecute = false;

                if (stdoutLineReceived != null)
                {
                    startInfo.RedirectStandardOutput = true;
                    startInfo.StandardOutputEncoding = Encoding.UTF8;
                    proc.OutputDataReceived += (sender, dataArgs) => { stdoutLineReceived(sender, dataArgs.Data); };
                }
                else
                    startInfo.RedirectStandardOutput = false;

                startInfo.RedirectStandardError = true;
                startInfo.StandardErrorEncoding = Encoding.UTF8;
                proc.ErrorDataReceived += (sender, evt) =>
                {
                    if (outStatus.ErrorString == null)
                        outStatus.ErrorString = "";

                    if (evt.Data == null)
                    {
                        outStatus.ErrorString.TrimEnd('\r', '\n');
                        return;
                    }

                    outStatus.ErrorString += evt.Data;
                };

                proc.StartInfo = startInfo;
                proc.Start();

                if (startInfo.RedirectStandardOutput)
                    proc.BeginOutputReadLine();
                if (startInfo.RedirectStandardError)
                    proc.BeginErrorReadLine();

                proc.WaitForExit();

                if (startInfo.RedirectStandardError)
                    WaitForProcessEOF(proc, "error");
                if (startInfo.RedirectStandardOutput)
                    WaitForProcessEOF(proc, "output");

                outStatus.ExitCode = proc.ExitCode;
            }
            return outStatus;
        }
        public override void OnStart()
        {
            // This reports problems, and stops BT processing if there was a problem with attributes...
            // We had to defer this action, as the 'profile line number' is not available during the element's
            // constructor call.
            OnStart_HandleAttributeProblem();

            // If the quest is complete, this behavior is already done...
            // So we don't want to falsely inform the user of things that will be skipped.
            if (!IsDone)
            {
                PlayerQuest quest = StyxWoW.Me.QuestLog.GetQuestById((uint)QuestId);

                ParsePath();        // refresh the list of points

                // find the closest point in path
                WoWPoint closePt = Path.Peek();
                double minDist = Me.Location.Distance(closePt);

                foreach (WoWPoint pt in Path)
                {
                    if (Me.Location.Distance(pt) < minDist )
                    {
                        minDist = Me.Location.Distance(pt);
                        closePt = pt;
                    }
                }

                // set closest point as current
                while (Path.Any() && closePt != Path.Peek())
                {
                    Path.Dequeue();
                }

                Counter = 1;

                TreeRoot.GoalText = this.GetType().Name + ": " + ((quest != null) ? ("\"" + quest.Name + "\"") : "In Progress");

                if (TreeRoot.Current == null)
                    UtilLogMessage("fatal", "TreeRoot.Current == null");
                else if (TreeRoot.Current.Root == null)
                    UtilLogMessage("fatal", "TreeRoot.Current.Root == null");
                else if (TreeRoot.Current.Root.LastStatus == RunStatus.Running)
                    UtilLogMessage("fatal", "TreeRoot.Current.Root.LastStatus == RunStatus.Running");
                else
                {
                    var currentRoot = TreeRoot.Current.Root;
                    if (!(currentRoot is GroupComposite))
                        UtilLogMessage("fatal", "!(currentRoot is GroupComposite)");
                    else
                    {
                        if (currentRoot is Sequence)
                            _lastStateReturn = RunStatus.Failure;
                        else if (currentRoot is PrioritySelector)
                            _lastStateReturn = RunStatus.Success;
                        else
                        {
                            UtilLogMessage("debug", "Unknown type of Group Composite at root");
                            _lastStateReturn = RunStatus.Success;
                        }

                        var root = (GroupComposite)currentRoot;
                        root.InsertChild(0, CreateBehavior());
                        UtilLogMessage("debug", "Disabled Combat");
                    }
                }
            }
        }
Exemple #20
0
        public RunStatus Tick()
        {
#if VERBOSE
            if (LastStatus.HasValue && LastStatus != RunStatus.Running)
            {
                throw new ApplicationException(
                          this
                          + ".Tick(): Tick on non-running node \nTrace:\n"
                          + this.stackTrace);
            }
            if (this.IsTerminating == true)
            {
                throw new ApplicationException(
                          this
                          + ".Tick(): Tick on terminating node \nTrace:\n"
                          + this.stackTrace);
            }
            if (_current == null)
            {
                throw new ApplicationException(
                          this
                          + ".Tick(): Tick on uninitialized node \nTrace:\n"
                          + this.stackTrace);
            }

            if (_current.MoveNext())
            {
                LastStatus = _current.Current;
            }
            else
            {
                throw new ApplicationException(
                          this
                          + ".Tick(): Unexpected iterator termination \nTrace:\n"
                          + this.stackTrace
                          + "\n\n"
                          + PrintTree(this));
            }
#else
            if (LastStatus.HasValue && LastStatus != RunStatus.Running)
            {
                throw new ApplicationException(
                          this
                          + ".Tick(): Tick on non-running node");
            }
            if (this.IsTerminating == true)
            {
                throw new ApplicationException(
                          this
                          + ".Tick(): Tick on terminating node");
            }
            if (_current == null)
            {
                throw new ApplicationException(
                          this
                          + ".Tick(): Tick on uninitialized node");
            }

            if (_current.MoveNext())
            {
                LastStatus = _current.Current;
            }
            else
            {
                throw new ApplicationException(
                          this
                          + ".Tick(): Unexpected iterator termination");
            }
#endif

            RunStatus result = this.LastStatus.Value;
            if (result != RunStatus.Running)
            {
                this.Stop();
            }
            return(result);
        }
Exemple #21
0
 internal Run(PipelinesAgentManager.Models.Terraform.Run run)
 {
     Id     = run.Data.Id;
     Status = run.Data.Attributes.Status;
 }
Exemple #22
0
 internal Thens(RunStatus runStatus)
 {
     RunStatus = runStatus;
 }
Exemple #23
0
 /// <summary>
 /// When you split on the last split, the run is complete.
 /// </summary>
 public void CompleteRun()
 {
     this.runStatus = RunStatus.DONE;
 }
Exemple #24
0
 internal static Thens Then(RunStatus runStatus)
 {
     return(new Thens(runStatus));
 }
Exemple #25
0
        /// <summary>
        /// 执行
        /// </summary>
        /// <param name="image">图像</param>
        /// <param name="outputs">输出结果</param>
        /// <returns>执行结果</returns>
        public void Execute(object image, out ItemCollection outputs)
        {
            HObject hImage = image as HObject;

            outputs = new ItemCollection();

            stopwatch.Restart();


            HObject ho_Image20190904144527, ho_GrayImage;
            HObject ho_Regions, ho_ConnectedRegions, ho_SelectedRegions;
            HObject ho_ContCircle;

            // Local control variables
            HTuple hv_Number = new HTuple();
            HTuple hv_Row = null, hv_Column = null, hv_Radius = null;

            // Initialize local and output iconic variables
            HOperatorSet.GenEmptyObj(out ho_Image20190904144527);
            HOperatorSet.GenEmptyObj(out ho_GrayImage);
            HOperatorSet.GenEmptyObj(out ho_Regions);
            HOperatorSet.GenEmptyObj(out ho_ConnectedRegions);
            HOperatorSet.GenEmptyObj(out ho_SelectedRegions);
            HOperatorSet.GenEmptyObj(out ho_ContCircle);

            try
            {
                HTuple width, height;
                HOperatorSet.GetImageSize(hImage, out width, out height);

                //若未初始化,则进行初始化
                if (!isInit)
                {
                    isInit = true;
                }

                if (runningWindow == null)
                {
                    try
                    {
                        runningWindow = (RunningWindow as HSmartWindowControlWPF).HalconWindow;
                    }
                    catch (Exception)
                    {
                    }
                }

                if (configWindow == null)
                {
                    try
                    {
                        configWindow = (ConfigWindow as HSmartWindowControlWPF).HalconWindow;
                    }
                    catch (Exception)
                    {
                    }
                }

                if (runningWindow != null)
                {
                    SetWindowPart(runningWindow, width, height);
                    HOperatorSet.ClearWindow(runningWindow);
                    HOperatorSet.DispObj(hImage, runningWindow);
                }

                if (configWindow != null)
                {
                    SetWindowPart(configWindow, width, height);
                    HOperatorSet.ClearWindow(configWindow);
                    HOperatorSet.DispObj(hImage, configWindow);
                }

                //执行主任务
                //转灰度图
                ho_GrayImage.Dispose();
                HOperatorSet.Rgb1ToGray(hImage, out ho_GrayImage);

                //阈值分割
                ho_Regions.Dispose();
                HOperatorSet.Threshold(ho_GrayImage, out ho_Regions, new HTuple(Inputs["MinThreshold"].Value), new HTuple(Inputs["MaxThreshold"].Value));

                //提取有效区域
                ho_ConnectedRegions.Dispose();
                HOperatorSet.Connection(ho_Regions, out ho_ConnectedRegions);
                ho_SelectedRegions.Dispose();
                HOperatorSet.SelectShape(ho_ConnectedRegions, out ho_SelectedRegions, "area",
                                         "and", new HTuple(Inputs["BlobArea"].Value), 999999999);

                HOperatorSet.CountObj(ho_SelectedRegions, out hv_Number);
                if (hv_Number.I > 0)
                {
                    //提取有效区域
                    HOperatorSet.SmallestCircle(ho_SelectedRegions, out hv_Row, out hv_Column, out hv_Radius);
                    ho_ContCircle.Dispose();
                    HOperatorSet.GenCircleContourXld(out ho_ContCircle, hv_Row, hv_Column, hv_Radius + 20,
                                                     0, 6.28318, "positive", 1);

                    var locations = new Location[hv_Column.Length];
                    for (int i = 0; i < hv_Column.Length; i++)
                    {
                        locations[i] = new Location(hv_Column[i].D, hv_Row[i].D, 0);
                    }
                    Outputs["ItemLocation"].Value = locations;

                    //显示结果
                    if (runningWindow != null)
                    {
                        HOperatorSet.DispObj(ho_GrayImage, runningWindow);
                        HOperatorSet.DispObj(ho_ContCircle, runningWindow);
                        disp_message(runningWindow, (hv_Column + new HTuple(",")) + hv_Row, "image",
                                     hv_Row - 100, hv_Column + 100, "black", "true");
                    }

                    if (configWindow != null)
                    {
                        HOperatorSet.DispObj(ho_GrayImage, configWindow);
                        HOperatorSet.DispObj(ho_ContCircle, configWindow);
                        disp_message(configWindow, (hv_Column + new HTuple(",")) + hv_Row, "image",
                                     hv_Row - 100, hv_Column + 100, "black", "true");
                    }

                    stopwatch.Stop();
                    RunStatus = new RunStatus(stopwatch.Elapsed.TotalMilliseconds);
                }
                else
                {
                    //没有有效的结果
                    Outputs["ItemLocation"].Value = new Location[0];

                    stopwatch.Stop();
                    RunStatus = new RunStatus(stopwatch.Elapsed.TotalMilliseconds, EResult.Warning, "没找到有效目标");
                }


                outputs = new ItemCollection(Outputs);
            }
            catch (Exception ex)
            {
                stopwatch.Stop();
                RunStatus = new RunStatus(stopwatch.Elapsed.TotalMilliseconds, EResult.Error, ex.Message, ex);
                throw;
            }
            finally
            {
                hImage.Dispose();

                ho_GrayImage.Dispose();
                ho_Regions.Dispose();
                ho_ConnectedRegions.Dispose();
                ho_SelectedRegions.Dispose();
                ho_ContCircle.Dispose();
            }
        }
Exemple #26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OriginalRunResult"/> class.
 /// </summary>
 /// <param name="status">The status of the target algorithm run.</param>
 /// <param name="runtime">The runtime of the target algorithm.</param>
 /// <param name="quality">A domain specific measure of the quality of the solution.</param>
 public OriginalRunResult(RunStatus status, TimeSpan runtime, double quality)
 {
     this.Status  = status;
     this.Runtime = runtime;
     this.Quality = quality;
 }
Exemple #27
0
        //This is the final step in handling.. here we actually switch to a specific method based upon the target object we are handling.
        public virtual bool ObjectInteraction()
        {
            #region DebugInfo
            if (Bot.Settings.Debug.DebugStatusBar)
            {
                Funky.sStatusText = "[Interact- ";
                switch (Bot.Targeting.Cache.CurrentTarget.targetType.Value)
                {
                    case TargetType.Avoidance:
                        Funky.sStatusText += "Avoid] ";
                        break;
                    case TargetType.Fleeing:
                        Funky.sStatusText += "Flee] ";
                        break;
                    case TargetType.NoMovement:
                        Funky.sStatusText += "NoMovement] ";
                        break;
                    case TargetType.Unit:
                        Funky.sStatusText += "Combat] ";
                        break;
                    case TargetType.Item:
                    case TargetType.Gold:
                    case TargetType.Globe:
                        Funky.sStatusText += "Pickup] ";
                        break;
                    case TargetType.Interactable:
                        Funky.sStatusText += "Interact] ";
                        break;
                    case TargetType.Container:
                        Funky.sStatusText += "Open] ";
                        break;
                    case TargetType.Destructible:
                    case TargetType.Barricade:
                        Funky.sStatusText += "Destroy] ";
                        break;
                    case TargetType.Shrine:
                        Funky.sStatusText += "Click] ";
                        break;
                    case TargetType.LineOfSight:
                        Funky.sStatusText += "LOS] ";
                        break;
                }
                Funky.sStatusText += "Target=" + Bot.Targeting.Cache.CurrentTarget.InternalName + " C-Dist=" + Math.Round(Bot.Targeting.Cache.CurrentTarget.CentreDistance, 2) + ". " +
                        "R-Dist=" + Math.Round(Bot.Targeting.Cache.CurrentTarget.RadiusDistance, 2) + ". ";

                if (Bot.Targeting.Cache.CurrentTarget.targetType.Value == TargetType.Unit && Bot.Character.Class.PowerPrime.Power != SNOPower.None)
                    Funky.sStatusText += "Power=" + Bot.Character.Class.PowerPrime.Power + " (range " + Bot.Character.Class.PowerPrime.MinimumRange + ") ";

                Funky.sStatusText += "Weight=" + Bot.Targeting.Cache.CurrentTarget.Weight;
                BotMain.StatusText = Funky.sStatusText;
                Funky.bResetStatusText = true;
            }
            #endregion

            switch (Bot.Targeting.Cache.CurrentTarget.targetType.Value)
            {
                case TargetType.Unit:
                case TargetType.Item:
                case TargetType.Gold:
                case TargetType.Globe:
                case TargetType.Shrine:
                case TargetType.Interactable:
                case TargetType.Container:
                case TargetType.Door:
                case TargetType.Destructible:
                case TargetType.Barricade:
                case TargetType.CursedShrine:
                    CurrentState = Bot.Targeting.Cache.CurrentTarget.Interact();
                    break;
                case TargetType.AvoidanceMovements:
                    CurrentState = RunStatus.Running;
                    break;
                case TargetType.Backtrack:
                    //Last position.. since we are interacting, we are within range.
                    if (Navigation.NP.CurrentPath.Count <= 1)
                    {
                        Bot.Targeting.Cache.Backtracking = false;
                        Bot.Targeting.Cache.StartingLocation = Vector3.Zero;
                    }
                    CurrentState = RunStatus.Running;
                    break;
                case TargetType.NoMovement:
                    CurrentState = RunStatus.Running;
                    break;
                case TargetType.LineOfSight:
                    //Last position.. since we are interacting, we are within range.
                    //if (Navigation.NP.CurrentPath.Count <= 1)
                    //{
                    Logger.DBLog.InfoFormat("Ending LOS Movement from Interaction");
                    Navigation.NP.Clear();
                    Bot.NavigationCache.LOSmovementObject = null;
                    //}
                    CurrentState = RunStatus.Running;
                    break;
            }

            // Now tell Trinity to get a new target!
            Bot.NavigationCache.lastChangedZigZag = DateTime.Today;
            Bot.NavigationCache.vPositionLastZigZagCheck = Vector3.Zero;
            //Bot.Targeting.bForceTargetUpdate=true;

            return false;
        }
Exemple #28
0
        /// <summary>
        /// 点赞
        /// </summary>
        /// <param name="scrapingBrowser"></param>
        /// <param name="htmlStr"></param>
        private void Praise(ScrapingBrowser scrapingBrowser, string htmlStr)
        {
            var cookie = scrapingBrowser.GetCookie(new Uri(IndexPage), "skey");

            if (cookie == null)
            {
                RunStatus = RunStatus.Fail;
                QqProvider.Instance.UpdateRunStatus(Id, RunStatus.Fail);

                CodeStatus = CodeStatus.NeedCode;
                QqProvider.Instance.UpdateCodeStatus(Id, CodeStatus.NeedCode);

                Log4Logger.Error(UserName + ":skey为空了");
                QqMsgLogger.LogError(UserName + ":skey为空了");
                return;
            }
            var gtk = Gtk.GetGtk(cookie.Value);

            PraiseUrl = string.Format(PraiseUrl, gtk);

            var document = new HtmlDocument();

            document.LoadHtml(htmlStr);

            var list = document.DocumentNode.CssSelect("li.f-single");

            if (!list.Any())
            {
                QqMsgLogger.LogInfo(UserName + " :li.f-single 找不到点赞的模块");
                Log4Logger.Info(UserName + " :li.f-single 找不到点赞的模块.\r\n" + htmlStr);
                if (document.DocumentNode.CssSelect("i.ico_login").Any())
                {
                    RunStatus = RunStatus.Fail;
                    QqProvider.Instance.UpdateRunStatus(Id, RunStatus.Fail);

                    CodeStatus = CodeStatus.NeedCode;
                    QqProvider.Instance.UpdateCodeStatus(Id, CodeStatus.NeedCode);
                }
                return;
            }
            else
            {
                var isContinue = htmlStr.Contains("g_ic_fpfeedsType='friend',");
                if (!isContinue)
                {
                    //其它角色对用户进行点赞评论后会跳转到与我相关页面,这时候再请求一次
                    //QqMsgLogger.LogInfo(UserName + " 有人关注,需要重新定位到主页.");
                    //_miniBrowser.DownloadString(IndexPage, Praise);
                    return;
                }
            }
            foreach (var htmlNode in list)
            {
                if (htmlNode == null || string.IsNullOrWhiteSpace(htmlNode.InnerHtml))
                {
                    continue;
                }
                try
                {
                    var nameNode   = htmlNode.CssSelect("a.f-name");
                    var praiseNode = htmlNode.CssSelect("a.qz_like_btn_v3").FirstOrDefault();
                    if (praiseNode != null && praiseNode.Attributes["data-clicklog"] != null &&
                        praiseNode.Attributes["data-clicklog"].Value == "like")
                    {
                        Thread.Sleep(1000);
                        Log4Logger.Info(UserName + "为《" + nameNode.First().InnerHtml + "》点赞!");
                        var unikey   = praiseNode.Attributes["data-unikey"].Value;
                        var curkey   = praiseNode.Attributes["data-curkey"].Value;
                        var postForm = new NameValueCollection();
                        postForm["qzreferrer"] = IndexPage;
                        postForm["opuin"]      = UserName;
                        postForm["unikey"]     = unikey;
                        postForm["curkey"]     = curkey;
                        postForm["from"]       = "1";
                        postForm["appid"]      = "311";
                        postForm["typeid"]     = "0";
                        postForm["abstime"]    = "1423372434";
                        postForm["fid"]        = "3611d32392f0d654e5a20900";
                        postForm["active"]     = "0";
                        postForm["fupdate"]    = "1";
                        scrapingBrowser.NavigateTo(PraiseUrl, postForm, Success, HttpVerb.Post);
                    }
                    else if (praiseNode == null)
                    {
                        QqMsgLogger.LogInfo(UserName + " :a.qz_like_btn_v3 没有找到点赞的按钮");
                        //Log4Logger.Info(UserName + " :a.qz_like_btn_v3 没有找到点赞的按钮.\r\n" + htmlStr);
                    }
                    else if (praiseNode.Attributes["data-clicklog"] == null)
                    {
                        QqMsgLogger.LogInfo(UserName + " :data-clicklog 没有找到点赞的按钮");
                        Log4Logger.Info(UserName + " :data-clicklog 没有找到点赞的按钮.\r\n" + htmlStr);
                    }
                }
                catch (Exception ex)
                {
                    Log4Logger.Error(UserName + " 点赞失败!\r\n" + htmlStr, ex);
                    QqMsgLogger.LogError(UserName + " 点赞失败!" + ex.Message, ex);
                }
            }
            RunStatus = RunStatus.Sucess;
            QqProvider.Instance.UpdateRunStatus(Id, RunStatus.Sucess);
        }
Exemple #29
0
 public StatusEntity(string _forum, RunStatus _status)
 {
     Forum = _forum;
     Status = _status;
     Message = getStatus();
 }
Exemple #30
0
        public override IEnumerable <RunStatus> Execute()
        {
            while (true)
            {
                for (int i = 0; i < this.Children.Count; i++)
                {
                    if (this.childStatus[i] == RunStatus.Running)
                    {
                        Node      node       = this.Children[i];
                        RunStatus tickResult = node.Tick();

                        // Check to see if anything finished
                        if (tickResult != RunStatus.Running)
                        {
                            // Clean up the node
                            node.Stop();
                            this.childStatus[i] = tickResult;
                            this.runningNodes--;

                            // If the node failed
                            if (tickResult == RunStatus.Failure)
                            {
                                // We may be stopping nodes in progress, so it's best
                                // to do a clean terminate and give them time to end
                                while (this.TerminateChildren() == RunStatus.Running)
                                {
                                    yield return(RunStatus.Running);
                                }
                                // TODO: Timeout? - AS
                                // TODO: What if Terminate() fails? - AS

                                // Clear out the LastStatus trail for all other nodes.
                                foreach (Node n in this.Children)
                                {
                                    if (n != node)
                                    {
                                        n.ClearLastStatus();
                                    }
                                }

                                // Report failure
                                yield return(RunStatus.Failure);

                                yield break;
                            }
                        }
                    }
                }

                // If we're out of running nodes, we're done
                if (this.runningNodes == 0)
                {
                    yield return(RunStatus.Success);

                    yield break;
                }

                // For forked ticking
                yield return(RunStatus.Running);
            }
        }
Exemple #31
0
        public virtual bool CombatLogic()
        {
            //Check if we can cast any combat buff-type abilities while channeling
            if (FunkyGame.Hero.Class.LastUsedAbility.IsChanneling && FunkyGame.Targeting.Cache.CurrentUnitTarget!=null)
            {
                Skill buff;
                if (FunkyGame.Hero.Class.FindCombatBuffPower(FunkyGame.Targeting.Cache.CurrentUnitTarget, out buff))
                {
                    Skill.UsePower(ref buff);
                    buff.OnSuccessfullyUsed(false);
                }
            }

            // Find a valid skill
            #region AbilityPick
            if (Cache.bPickNewAbilities && !Cache.bWaitingForPower && !Cache.bWaitingForPotion)
            {
                Cache.bPickNewAbilities = false;
                if (Cache.CurrentTarget.targetType.Value == TargetType.Unit && Cache.CurrentTarget.AcdGuid.HasValue)
                {
                    // Pick an Ability
                    Skill nextAbility = FunkyGame.Hero.Class.AbilitySelector(Cache.CurrentUnitTarget);

                    // Did we get default attack?
                    if (nextAbility.Equals(FunkyGame.Hero.Class.DefaultAttack) && !FunkyGame.Hero.Class.CanUseDefaultAttack && !FunkyBaseExtension.Settings.Combat.AllowDefaultAttackAlways)
                    {//TODO:: Fix issue when nothing keeps returning (possibly due to bad ability setup)
                        Helpers.Logger.Write(Helpers.LogLevel.Ability, "Default Attack not usable -- Failed to find a valid Ability to use -- Target: {0}", Cache.CurrentTarget.InternalName);
                        Cache.bForceTargetUpdate = true;
                        CurrentState = RunStatus.Running;
                        Cache.CurrentTarget.BlacklistLoops = 10;
                        return false;
                    }

                    FunkyGame.Hero.Class.PowerPrime = nextAbility;
                }

                // Select an Ability for destroying a destructible with in advance
                if (Cache.CurrentTarget.targetType.Value == TargetType.Destructible || Cache.CurrentTarget.targetType == TargetType.Barricade)
                {
                    Skill nextAbility = FunkyGame.Hero.Class.DestructibleAbility();
                    if (nextAbility.Equals(FunkyGame.Hero.Class.DefaultAttack) && !FunkyGame.Hero.Class.CanUseDefaultAttack && !FunkyBaseExtension.Settings.Combat.AllowDefaultAttackAlways)
                    {
                        Helpers.Logger.Write(Helpers.LogLevel.Ability, "Default Attack not usable -- Failed to find a valid Ability to use -- Target: {0}", Cache.CurrentTarget.InternalName);
                        Cache.bForceTargetUpdate = true;
                        CurrentState = RunStatus.Running;
                        Cache.CurrentTarget.BlacklistLoops = 10;
                        return false;
                    }

                    FunkyGame.Hero.Class.PowerPrime = FunkyGame.Hero.Class.DestructibleAbility();
                }

                //Interactables (for pre and post waits)
                //if (ObjectCache.CheckFlag(Cache.CurrentTarget.targetType.Value, TargetType.Item | TargetType.Interactables | TargetType.Interaction))
                //{
                //    Skill.SetupAbilityForUse(ref Cache.InteractionSkill);
                //    FunkyGame.Hero.Class.PowerPrime = Cache.InteractionSkill;
                //    Cache.bWaitingAfterPower = false;
                //}
            }
            #endregion

            #region PotionCheck
            if (FunkyGame.Hero.dCurrentHealthPct <= FunkyBaseExtension.Settings.Combat.PotionHealthPercent
                 && !Cache.bWaitingForPower
                 && !Cache.bWaitingForPotion
                 && !FunkyGame.Hero.bIsIncapacitated
                 && FunkyGame.Hero.Class.HealthPotionAbility.AbilityUseTimer())
            {
                Cache.bWaitingForPotion = true;
                CurrentState = RunStatus.Running;
                return false;
            }
            if (Cache.bWaitingForPotion)
            {
                Cache.bWaitingForPotion = false;
                if (FunkyGame.Hero.Class.HealthPotionAbility.CheckCustomCombatMethod(null))
                {

                    FunkyGame.Hero.Class.HealthPotionAbility.AttemptToUseHealthPotion();
                    CurrentState = RunStatus.Running;
                    return false;
                }
            }
            #endregion

            // See if we can use any special buffs etc. while in avoidance
            if (ObjectCache.CheckFlag(Cache.CurrentTarget.targetType.Value, TargetType.Globe | TargetType.AvoidanceMovements))
            {
                Skill buff;
                if (FunkyGame.Hero.Class.FindBuffPower(out buff))
                {
                    Skill.UsePower(ref buff);
                    buff.OnSuccessfullyUsed();
                }
            }

            return true;
        }
Exemple #32
0
        /// <summary>
        /// 执行
        /// </summary>
        /// <param name="timeout">处理超时时间,若小于等于0,则无限等待.单位:毫秒</param>
        /// <param name="outputs">输出结果</param>
        public void Execute(int timeout, out ItemCollection outputs)
        {
            outputs = new ItemCollection();

            //全局线程锁(静态),避免不同线程间同时调用VisionPro的资源
            lock (globalThreadLock)
            {
                try
                {
                    //线程锁,避免在不同线程中分别调用init和run,导致isInit变量冲突
                    lock (threadLock)
                    {
                        if (!IsInit)
                        {
                            throw new ArgumentException("VisionFrame is uninit");
                        }
                    }

                    if (cogToolBlock != null)
                    {
                        cogToolBlock.Run();

                        Outputs.Clear();
                        for (int i = 0; i < cogToolBlock.Outputs.Count; i++)
                        {
                            Outputs.Add(new ItemBase(cogToolBlock.Outputs[i].Name, cogToolBlock.Outputs[i].Value, cogToolBlock.Outputs[i].ValueType, string.IsNullOrEmpty(cogToolBlock.Outputs[i].Description) ? cogToolBlock.Outputs[i].Name : cogToolBlock.Outputs[i].Description));
                        }
                        outputs = new ItemCollection(Outputs);

                        EResult result = EResult.Accept;
                        switch (cogToolBlock.RunStatus.Result)
                        {
                        case CogToolResultConstants.Accept:
                            result = EResult.Accept;
                            break;

                        case CogToolResultConstants.Warning:
                            result = EResult.Warning;
                            break;

                        case CogToolResultConstants.Reject:
                            result = EResult.Reject;
                            break;

                        case CogToolResultConstants.Error:
                            result = EResult.Error;
                            break;

                        default:
                            break;
                        }

                        RunStatus = new RunStatus(cogToolBlock.RunStatus.ProcessingTime, result, cogToolBlock.RunStatus.Message, cogToolBlock.RunStatus.Exception);

                        GC.Collect();
                        GC.WaitForPendingFinalizers();
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
        private RunStatus RunCopierExecutable(string fullExePath, StringLineReceived stdoutLineReceived,
			IEnumerable<string> executableInput = null, bool runAsAdmin = false)
        {
            var outStatus = new RunStatus();
            using (var proc = new Process())
            {
                string clientGuidStr = Guid.NewGuid().ToString();
                ;
                var stdPipeSvr = new NamedPipeServerStream("Copier_" + clientGuidStr + "_data",
                    PipeDirection.InOut, 1, PipeTransmissionMode.Byte);
                var errPipeSvr = new NamedPipeServerStream("Copier_" + clientGuidStr + "_error",
                    PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);

                proc.StartInfo = new ProcessStartInfo(fullExePath, clientGuidStr);
                proc.StartInfo.UseShellExecute = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                if (runAsAdmin)
                    proc.StartInfo.Verb = "runas";

                proc.Start();
                var endEvent = new AutoResetEvent(false);
                errPipeSvr.BeginWaitForConnection(iar =>
                {
                    var pipSvr = (NamedPipeServerStream) iar.AsyncState;
                    try
                    {
                        pipSvr.EndWaitForConnection(iar);
                        var errSb = new StringBuilder();

                        var readBuffer = new byte[4096];
                        pipSvr.BeginRead(readBuffer, 0, readBuffer.Length, iar2 =>
                        {
                            var pipeStr = (NamedPipeServerStream) iar2.AsyncState;
                            int numBytes = pipeStr.EndRead(iar2);

                            if (numBytes > 0)
                            {
                                string recvStr = Encoding.UTF8.GetString(readBuffer, 0, numBytes);
                                errSb.Append(recvStr);
                            }
                            else //EOF
                            {
                                outStatus.ErrorString = errSb.ToString().TrimEnd('\r', '\n');
                                pipeStr.Close();
                                endEvent.Set();
                            }
                        }, pipSvr);
                    }
                    catch (ObjectDisposedException)
                    {
                    } //happens if no connection happened
                }, errPipeSvr);

                stdPipeSvr.WaitForConnection();
                if (executableInput != null)
                {
                    var sw = new StreamWriter(stdPipeSvr, Encoding.UTF8);
                    foreach (string line in executableInput)
                        sw.WriteLine(line);

                    //last one to indicate no more input
                    sw.WriteLine();
                    sw.Flush();
                }
                stdPipeSvr.WaitForPipeDrain(); //wait for process to read all bytes we sent it

                using (var sr = new StreamReader(stdPipeSvr, Encoding.UTF8, false))
                {
                    while (stdPipeSvr.IsConnected)
                    {
                        string recvLine = sr.ReadLine();
                        if (stdoutLineReceived != null)
                            stdoutLineReceived(stdPipeSvr, recvLine);

                        if (recvLine == null)
                            break; //EOF
                    }

                    sr.Close(); //closes the underlying named pipe as well
                }

                proc.WaitForExit();
                outStatus.ExitCode = proc.ExitCode;
                if (outStatus.ExitCode != 0)
                    endEvent.WaitOne(); //wait for stderr to be read
            }
            return outStatus;
        }
Exemple #34
0
        /// <summary>
        /// 执行
        /// </summary>
        /// <param name="image">图像</param>
        /// <param name="outputs">输出结果</param>
        /// <returns>执行结果</returns>
        public void Execute(object image, out ItemCollection outputs)
        {
            HObject hImage = image as HObject;

            outputs = new ItemCollection();

            stopwatch.Restart();

            try
            {
                HTuple width, height;
                HOperatorSet.GetImageSize(hImage, out width, out height);

                //若未初始化,则进行初始化
                if (!isInit)
                {
                    isInit = true;
                }

                if (runningWindow == null)
                {
                    try
                    {
                        runningWindow = (RunningWindow as HSmartWindowControlWPF).HalconWindow;
                    }
                    catch (Exception)
                    {
                    }
                }

                if (configWindow == null)
                {
                    try
                    {
                        configWindow = (ConfigWindow as HSmartWindowControlWPF).HalconWindow;
                    }
                    catch (Exception)
                    {
                    }
                }

                if (runningWindow != null)
                {
                    HOperatorSet.ClearWindow(runningWindow);
                    HOperatorSet.DispObj(hImage, runningWindow);
                    UpdatePart(runningWindow);
                }

                if (configWindow != null)
                {
                    HOperatorSet.ClearWindow(configWindow);
                    HOperatorSet.DispObj(hImage, configWindow);
                    UpdatePart(runningWindow);
                }

                //执行主任务

                //显示结果
                if (runningWindow != null)
                {
                    UpdatePart(runningWindow);
                }

                if (configWindow != null)
                {
                    UpdatePart(runningWindow);
                }

                stopwatch.Stop();
                RunStatus = new RunStatus(stopwatch.Elapsed.TotalMilliseconds);

                outputs = new ItemCollection(Outputs);
            }
            catch (Exception ex)
            {
                stopwatch.Stop();
                RunStatus = new RunStatus(stopwatch.Elapsed.TotalMilliseconds, EResult.Error, ex.Message, ex);
                throw;
            }
            finally
            {
                hImage.Dispose();
            }
        }
Exemple #35
0
        /// <summary>
        ///   Implements a 'throttle' composite. This composite limits the number of times the child 
        ///   will be run within a given time span.  Returns cappedStatus for attempts after limit reached, 
        ///   otherwise returns result of child
        /// </summary>
        /// <param name = "limit">max number of occurrences</param>
        /// <param name = "timeFrame">time span for occurrences</param>
        /// <param name="limitStatus">RunStatus to return when limit reached</param>
        /// <param name = "child">composite children to tick (run)</param>
        public ThrottlePasses(int limit, TimeSpan timeFrame, RunStatus limitStatus, params Composite[] children)
            : base(ChildComposite(children))
        {
            TimeFrame = timeFrame;
            Limit = limit;

            _end = DateTime.MinValue;
            _count = 0;
            _limitStatus = limitStatus;
        }
Exemple #36
0
        private static bool AvoidanceLock(out RunStatus handleTarget)
        {
            var criticalAvoidances = new HashSet<AvoidanceType>
            {
                AvoidanceType.MoltenCore,
            };

            // Make the bot continue moving towards safespots 
            if (AvoidanceManager.IsLockedMovingToSafeSpot)
            {
                if (AvoidanceManager.CurrentSafeSpot != CurrentTarget && Player.IsTakingDamage)
                {
                    Logger.Log(LogCategory.Avoidance, "Forcing Target back to locked SafeSpot");
                    CurrentTarget = AvoidanceManager.CurrentSafeSpot;
                }

                var isCloseEnoughToSafeSpot = AvoidanceManager.CurrentSafeSpot.Distance <= 2f;
                var isFarEnoughFromAvoidance = _currentAvoidance.Distance >= _currentAvoidance.AvoidanceRadius;

                if (isCloseEnoughToSafeSpot || isFarEnoughFromAvoidance || PlayerMover.IsBlocked || Navigator.StuckHandler.IsStuck)
                {
                    Logger.Log(LogCategory.Avoidance, "Breaking from Safespot Movement Lock DistanceToSafeSpot={0} DistanceToAvoidance={0}",
                        AvoidanceManager.CurrentSafeSpot.Distance, _currentAvoidance.Distance);

                    AvoidanceManager.IsLockedMovingToSafeSpot = false;
                    {
                        handleTarget = GetRunStatus(RunStatus.Success, "BreakFromSafeSpotLock");
                        return true;
                    }
                }
            }

            var isTooCloseToMonster = CurrentTarget.IsBoss && CurrentTarget.Distance <= CombatBase.KiteDistance;
            var isTooCloseToAvoidance = ObjectCache.Any(o => criticalAvoidances.Contains(o.AvoidanceType) && o.Distance < GetAvoidanceRadius(o.ActorSNO, 30f) && Player.CurrentHealthPct < GetAvoidanceHealth(o.ActorSNO));

            // If we're standing in an avoidance. We're not messing around anymore, hijack this train and move now.
            if (_standingInAvoidance || Player.IsRanged && isTooCloseToMonster || isTooCloseToAvoidance)
            {
                if (isTooCloseToMonster && Player.IsRanged)
                {
                    Logger.LogVerbose(LogCategory.Behavior, "Too close to boss, Kiting! DistanceToTarget={0} KiteTriggerRange={1} KiteMode={2}",
                        CurrentTarget.Distance, CombatBase.KiteDistance, CombatBase.KiteMode);
                }

                var safespot = CurrentTarget.IsSafeSpot && CurrentTarget.Distance > 3f ? CurrentTarget : ObjectCache.Where(o => o.IsSafeSpot).OrderByDescending(o => o.Distance).FirstOrDefault();
                if (safespot == null || safespot.Position == Vector3.Zero || safespot.Distance > 200f)
                {
                    var monstersToAvoid = isTooCloseToMonster ? new List<TrinityCacheObject>() {CurrentTarget} : new List<TrinityCacheObject>();
                    var minDistance = Math.Max(CombatBase.KiteDistance, _currentAvoidance.AvoidanceRadius);
                    var newSafeSpotPosition = NavHelper.MainFindSafeZone(Player.Position, false, false, monstersToAvoid, false, minDistance);
                    var distance = newSafeSpotPosition.Distance(Player.Position);
                    if (newSafeSpotPosition != null && newSafeSpotPosition != Vector3.Zero && distance < 200f)
                    {
                        Logger.Log(LogCategory.Avoidance, "Creating new safe spot Distance={0}", distance);
                        safespot = new TrinityCacheObject()
                        {
                            Position = newSafeSpotPosition,
                            Type = TrinityObjectType.Avoidance,
                            Weight = 90000,
                            Distance = distance,
                            Radius = 2f,
                            InternalName = "SafePoint",
                            IsSafeSpot = true
                        };
                        _currentAvoidance = CurrentTarget;
                        _currentAvoidanceName = CurrentTarget.InternalName;
                        //AvoidanceManager.CurrentSafeSpot = safespot;
                        //AvoidanceManager.IsLockedMovingToSafeSpot = true;
                    }
                    else
                    {
                        Logger.Log(LogCategory.Avoidance, "Unable to find a place to move to :(");
                    }
                }

                if (safespot != null && safespot.Distance > 1f)
                {
                    Logger.LogVerbose(LogCategory.Behavior, "Emergency Avoidance DistanceToTarget={0}, DistanceToAvoidance={1} Avoidance={2} ({3})",
                        CurrentTarget.Distance, _currentAvoidance != null ? _currentAvoidance.Distance : -1, _currentAvoidance != null ? _currentAvoidance.InternalName : "Null", _currentAvoidance != null ? _currentAvoidance.ActorSNO : -1);

                    AvoidanceManager.IsLockedMovingToSafeSpot = true;
                    AvoidanceManager.CurrentSafeSpot = safespot;

                    RunStatus specialMovementResult;
                    if (TrySpecialMovement(out specialMovementResult))
                    {
                        handleTarget = specialMovementResult;
                        return true;
                    }

                    Logger.LogVerbose(LogCategory.Avoidance, "Safespot found, Emergency moving! Distance={0}", safespot.Distance);
                    PlayerMover.NavigateTo(safespot.Position, "EmergencySafeSpot");
                    {
                        handleTarget = RunStatus.Running;
                        return true;
                    }
                }
            }

            handleTarget = RunStatus.Failure;
            return false;
        }
Exemple #37
0
 public virtual void Initialize()
 {
     switch (Status) {
         case RunStatus.NotInitialized:
             Log.Trace("Initializing Message Manager", "Initialize");
             RegisterForDelayedDomains();
             Status = RunStatus.Running;
             break;
         case RunStatus.Running:
             Log.Warning("Already initialized", "Initialize");
             break;
         case RunStatus.Terminated:
             Log.Error("Can't initialize, terminated", "Initialize");
             break;
     }
 }
 public static bool IsErrored(this RunStatus status) => status == RunStatus.Errored || status == RunStatus.PolicySoftFailed;
Exemple #39
0
 public DecoratorForceStatus(RunStatus forced, Node child)
     : base(child)
 {
     this.forced = forced;
 }
Exemple #40
0
        public async Task <JsonResult> Compiler(string code, string language, string input)
        {
            if (language == "CPP")
            {
                language = "1";
            }

            if (language == "CSHARP")
            {
                language = "27";
            }

            if (language == "C")
            {
                language = "11";
            }

            if (language == "CLOJURE")
            {
                language = "111";
            }

            if (language == "JAVA")
            {
                language = "10";
            }

            if (language == "JAVASCRIPT")
            {
                language = "35";
            }

            if (language == "HASKELL")
            {
                language = "21";
            }

            if (language == "PERL")
            {
                language = "54";
            }

            if (language == "PHP")
            {
                language = "29";
            }

            if (language == "PYTHON")
            {
                language = "99";
            }

            if (language == "RUBY")
            {
                language = "17";
            }


            code = code.Replace("&gt;", ">").Replace("&lt;", "<");
            try
            {
                string token = "2e899925328c3e5340a0ed23af34ad30";

                HttpClient client = new HttpClient();

                string postData = "access_token=" + token
                                  + "&sourceCode=" + Uri.EscapeDataString(code)
                                  + "&language=" + language
                                  + "&input=" + Uri.EscapeDataString(input);

                string url = "http://e855a150.compilers.sphere-engine.com/api/v3/submissions/?" + postData;

                var response = await client.PostAsync(url, null);


                var submissionId = await response.Content.ReadAsStringAsync();

                int pFrom = submissionId.IndexOf("id\":\"") + "id\":\"".Length;
                int pTo   = submissionId.LastIndexOf("\"}");

                submissionId = submissionId.Substring(pFrom, pTo - pFrom);
                //Debug.WriteLine("result: " + submissionId);


                url = "http://e855a150.compilers.sphere-engine.com/api/v3/submissions/" + submissionId + "?access_token=2e899925328c3e5340a0ed23af34ad30&withSource=1&withInput=1&withOutput=1&withStderr=1&withCmpinfo=1";

                RunStatus rs = new RunStatus();

                int tried  = 0;
                var result = "";
                while (string.IsNullOrEmpty(rs.output) && string.IsNullOrEmpty(rs.cmpinfo) && string.IsNullOrEmpty(rs.stderr))
                {
                    await Task.Delay(1000);

                    response = await client.GetAsync(url);

                    result = await response.Content.ReadAsStringAsync();

                    rs = new JavaScriptSerializer().Deserialize <RunStatus>(result);
                    tried++;

                    if (tried == 6)
                    {
                        rs.output = "no output...";
                        return(Json(rs));
                    }
                }



                // Debug.WriteLine("\n-------------------------------------------\n" + result);
                // Debug.WriteLine("\n" + rs.output);

                return(Json(rs));
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }

            return(Json(false));
        }
Exemple #41
0
        /// <summary>
        /// Try to use a special movement skill like Monk Dashing Strike or Wizard Teleport
        /// </summary>
        private static bool TrySpecialMovement(out RunStatus statusResult)
        {
            if (!CombatBase.IsInCombat && !Settings.Combat.Misc.AllowOOCMovement)
            {
                statusResult = default(RunStatus);
                return false;
            }

            using (new PerformanceLogger("HandleTarget.SpecialMovement"))
            {
                bool Monk_SpecialMovement = ((CurrentTarget.Type == TrinityObjectType.Gold ||
                                              CurrentTarget.IsUnit || CurrentTarget.IsDestroyable) && MonkCombat.IsTempestRushReady());

                // If we're doing avoidance, globes or backtracking, try to use special abilities to move quicker
                if ((CurrentTarget.Type == TrinityObjectType.Avoidance ||
                     CurrentTarget.Type == TrinityObjectType.HealthGlobe ||
                     CurrentTarget.Type == TrinityObjectType.PowerGlobe ||
                     CurrentTarget.Type == TrinityObjectType.ProgressionGlobe ||
                     CurrentTarget.Type == TrinityObjectType.Shrine ||
                     Monk_SpecialMovement)
                    && NavHelper.CanRayCast(Player.Position, CurrentDestination)
                    )
                {
                    bool usedSpecialMovement = UsedSpecialMovement();

                    if (usedSpecialMovement)
                    {
                        // Store the current destination for comparison incase of changes next loop
                        LastMoveToTarget = CurrentDestination;
                        // Reset total body-block count, since we should have moved
                        if (DateTime.UtcNow.Subtract(_lastForcedKeepCloseRange).TotalMilliseconds >= 2000)
                            _timesBlockedMoving = 0;

                        {
                            statusResult = GetRunStatus(RunStatus.Running, "UsedSpecialMovement");
                            return true;
                        }
                    }
                }
            }

            // DemonHunter Strafe
            if (Skills.DemonHunter.Strafe.IsActive && Player.PrimaryResource > 12 && TargetUtil.AnyMobsInRange(30f, false))
            {
                Skills.DemonHunter.Strafe.Cast(CurrentDestination);
                {
                    statusResult = GetRunStatus(RunStatus.Running, "Strafe");
                    return true;
                }
            }

            //Monk DashingStrike                      
            if (Player.ActorClass == ActorClass.Monk && CombatBase.CanCast(SNOPower.X1_Monk_DashingStrike) &&
                !CombatBase.WasUsedWithinMilliseconds(SNOPower.X1_Monk_DashingStrike, Settings.Combat.Monk.DashingStrikeDelay) &&
                !ShouldWaitForLootDrop && ((Skills.Monk.DashingStrike.Charges > 1 &&
                (!Sets.ThousandStorms.IsSecondBonusActive || ZetaDia.Me.CurrentPrimaryResource > 75)) || CacheData.Buffs.HasCastingShrine))
            {
                Logger.Log("Dash towards: {0}, charges={1}", GetTargetName(), Skills.Monk.DashingStrike.Charges);
                Skills.Monk.DashingStrike.Cast(CurrentDestination);

                {
                    statusResult = GetRunStatus(RunStatus.Running, "Dash");
                    return true;
                }
            }

            //Barb Whirlwind
            if (Player.ActorClass == ActorClass.Barbarian)
            {
                // Whirlwind against everything within range
                if (Player.PrimaryResource >= 10 && CombatBase.CanCast(SNOPower.Barbarian_Whirlwind) && NavHelper.CanRayCast(CurrentTarget.Position) &&
                    (TargetUtil.AnyMobsInRange(20, false) || Sets.BulKathossOath.IsFullyEquipped) && !IsWaitingForSpecial &&
                    (CurrentTarget.Type != TrinityObjectType.Item || (CurrentTarget.Type == TrinityObjectType.Item && CurrentTarget.Distance > 10f)))
                {
                    Skills.Barbarian.Whirlwind.Cast(CurrentDestination);
                    LastMoveToTarget = CurrentDestination;
                    {
                        statusResult = GetRunStatus(RunStatus.Running, "Whirlwind");
                        return true;
                    }
                }
            }

            statusResult = RunStatus.Failure;
            return false;
        }
Exemple #42
0
 public void ResumeRun()
 {
     this.runStatus = RunStatus.ON_GOING;
 }
        public override void OnStart()
        {
            PlayerQuest quest = StyxWoW.Me.QuestLog.GetQuestById(QuestId);

            if (quest != null)
            {
                TreeRoot.GoalText = "Doing: " + quest.Name;
            }
            else
            {
                TreeRoot.GoalText = "GreaterOfTwoEvils - ";
            }

            if (TreeRoot.Current == null)
                Log("ERROR - TreeRoot.Current == null");
            else if (TreeRoot.Current.Root == null )
                Log("ERROR - TreeRoot.Current.Root == null");
            else if (TreeRoot.Current.Root.LastStatus == RunStatus.Running)
                Log("ERROR - TreeRoot.Current.Root.LastStatus == RunStatus.Running");
            else
            {
                var currentRoot = TreeRoot.Current.Root;
                if (!(currentRoot is GroupComposite))
                    Log("ERROR - !(currentRoot is GroupComposite)");
                else 
                {
                    if (currentRoot is Sequence)
                        lastStateReturn = RunStatus.Failure ;
                    else if (currentRoot is PrioritySelector)
                        lastStateReturn = RunStatus.Success;
                    else
                    {
                        DLog("unknown type of Group Composite at root");
                        lastStateReturn = RunStatus.Success;
                    }

                    var root = (GroupComposite)currentRoot;
                    root.InsertChild(0, CreateBehavior());
                }
            }
        }
Exemple #44
0
 public Split()
 {
     this.segments  = new List <Segment>();
     this.liveIndex = -1;
     this.runStatus = RunStatus.STOPPED;
 }
 public DecoratorForceStatus(RunStatus forced, Node child)
     : base(child)
 {
     this.forced = forced;
 }
Exemple #46
0
 /// <summary>
 /// When you split on the last split, the run is complete.
 /// </summary>
 public void CompleteRun()
 {
     this.runStatus = RunStatus.DONE;
 }
Exemple #47
0
 public Split()
 {
     this.segments = new List<Segment>();
     this.liveIndex = -1;
     this.runStatus = RunStatus.STOPPED;
 }
Exemple #48
0
 /// <summary>
 /// Star the run by incresing indexes and run attempts.
 /// </summary>
 public void StartRun()
 {
     this.liveIndex = 0;
     this.attemptsCount++;
     this.runStatus = RunStatus.ON_GOING;
 }
Exemple #49
0
 public void ResumeRun()
 {
     this.runStatus = RunStatus.ON_GOING;
 }
Exemple #50
0
 public override void Halt(int code)
 {
     Status = RunStatus.Idle;
     AddLogLine(new LogLine(ModuleName, Severity.Info, ProgramCounter, "Halt requested", "Halting Mix"));
     mMix.Halt(code);
 }
Exemple #51
0
 /// <summary>
 /// Star the run by incresing indexes and run attempts.
 /// </summary>
 public void StartRun()
 {
     this.liveIndex = 0;
     this.attemptsCount++;
     this.runStatus = RunStatus.ON_GOING;
 }
Exemple #52
0
 public static void Exit()
 {
     state = RunStatus.Success;
 }
Exemple #53
0
        public virtual bool Movement()
        {
            //Set the target location for the Target Movement class..
            Bot.Targeting.Movement.CurrentTargetLocation = Bot.Targeting.Cache.CurrentTarget.Position;

            //Instead of using target position we use the navigator pathing as CurrentTargetLocation
            if (ObjectCache.CheckTargetTypeFlag(Bot.Targeting.Cache.CurrentTarget.targetType.Value, TargetType.LineOfSight | TargetType.Backtrack))
            {

                //Navigation.NP.MoveTo(Bot.NavigationCache.LOSmovementObject.Position, "02 LOS:" + Bot.NavigationCache.LOSmovementObject.InternalName, true);

                if (Navigation.NP.CurrentPath.Count > 0)
                {
                    //No more points to navigate..
                    if (Navigation.NP.CurrentPath.Count == 1 && Bot.Character.Data.Position.Distance(Navigation.NP.CurrentPath.Current) <= Bot.Targeting.Cache.CurrentTarget.Radius)
                    {
                        Logger.Write(LogLevel.Movement, "Ending Line of Sight Movement");
                        if (Bot.Targeting.Cache.CurrentTarget.targetType.Value == TargetType.LineOfSight)
                        {
                            Bot.NavigationCache.LOSmovementObject = null;
                        }
                        else
                        {
                            //Ending backtracking behavior!
                            Bot.Targeting.Cache.Backtracking = false;
                            Bot.Targeting.Cache.StartingLocation = Vector3.Zero;
                        }
                    }
                    else
                    {
                        Bot.Targeting.Movement.CurrentTargetLocation = Navigation.NP.CurrentPath.Current;
                    }

                    CurrentState = Bot.Targeting.Movement.TargetMoveTo(Bot.Targeting.Cache.CurrentTarget);
                    return false;
                }
            }

            //Check if we are in range for interaction..
            if (Bot.Targeting.Cache.CurrentTarget.WithinInteractionRange())
                return true;
            //Movement required..
            CurrentState = Bot.Targeting.Movement.TargetMoveTo(Bot.Targeting.Cache.CurrentTarget);
            return false;
        }
Exemple #54
0
 public static void Restart()
 {
     state = RunStatus.Restart;
 }
Exemple #55
0
        //Prechecks are things prior to target checks and actual target handling.. This is always called first.
        public virtual bool PreChecks()
        {
            // If we aren't in the game of a world is loading, don't do anything yet
            if (!ZetaDia.IsInGame || ZetaDia.IsLoadingWorld)
            {
                CurrentState = RunStatus.Success;
                return false;
            }

            // See if we should update hotbar abilities
            Bot.Character.Class.SecondaryHotbarBuffPresent();

            // Special pausing *AFTER* using certain powers
            #region PauseCheck
            if (Bot.Targeting.Cache.bWaitingAfterPower && Bot.Character.Class.PowerPrime.WaitLoopsAfter >= 1)
            {
                if (Bot.Character.Class.PowerPrime.WaitLoopsAfter >= 1) Bot.Character.Class.PowerPrime.WaitLoopsAfter--;
                if (Bot.Character.Class.PowerPrime.WaitLoopsAfter <= 0) Bot.Targeting.Cache.bWaitingAfterPower = false;

                CurrentState = RunStatus.Running;
                return false;
            }
            #endregion

            // Update player-data cache -- Special combat call
            Bot.Character.Data.Update(true);

            // Check for death / player being dead
            #region DeadCheck
            if (Bot.Character.Data.dCurrentHealthPct <= 0)
            {
                //Disable OOC IDing behavior if dead!
                if (ItemIdentifyBehavior.shouldPreformOOCItemIDing) ItemIdentifyBehavior.shouldPreformOOCItemIDing = false;

                CurrentState = RunStatus.Success;
                return false;
            }
            #endregion

            //Herbfunk
            //Confirmation of item looted
            #region ItemLootedConfirmationCheck
            if (Bot.Targeting.Cache.ShouldCheckItemLooted)
            {
                //Reset?
                if (Bot.Targeting.Cache.CurrentTarget == null || Bot.Targeting.Cache.CurrentTarget.targetType.HasValue && Bot.Targeting.Cache.CurrentTarget.targetType.Value != TargetType.Item)
                {
                    Bot.Targeting.Cache.ShouldCheckItemLooted = false;
                    return false;
                }

                //Vendor Behavior
                if (BrainBehavior.IsVendoring)
                {
                    CurrentState = RunStatus.Success;
                    return false;
                }
                if (Bot.Character.Data.bIsIncapacitated)
                {
                    CurrentState = RunStatus.Running;
                    return false;
                }

                //Count each attempt to confirm.
                Bot.Targeting.Cache.recheckCount++;
                string statusText = "[Item Confirmation] Current recheck count " + Bot.Targeting.Cache.recheckCount;
                bool LootedSuccess = Bot.Character.Data.BackPack.ContainsItem(Bot.Targeting.Cache.CurrentTarget.AcdGuid.Value, Bot.Targeting.Cache.CheckItemLootStackCount);
                //Verify item is non-stackable!

                statusText += " [ItemFound=" + LootedSuccess + "]";
                if (LootedSuccess)
                {
                    GameEvents.FireItemLooted(Bot.Targeting.Cache.CurrentTarget.AcdGuid.Value);

                    if (Bot.Settings.Debug.DebugStatusBar) BotMain.StatusText = statusText;

                    //This is where we should manipulate information of both what dropped and what was looted.
                    Logger.LogItemInformation();

                    //Reset if we reach here..
                    Bot.Targeting.Cache.reCheckedFinished = false;
                    Bot.Targeting.Cache.recheckCount = 0;
                    Bot.Targeting.Cache.CheckItemLootStackCount = 0;
                    Bot.Targeting.Cache.ShouldCheckItemLooted = false;
                    Bot.Targeting.Cache.bForceTargetUpdate = true;

                    //Remove..
                    Bot.Targeting.Cache.CurrentTarget.NeedsRemoved = true;
                }
                else
                {
                    CacheItem thisObjItem = (CacheItem)Bot.Targeting.Cache.CurrentTarget;

                    statusText += " [Quality";
                    //Quality of the item determines the recheck attempts.
                    ItemQuality curQuality = thisObjItem.Itemquality.Value;
                    #region QualityRecheckSwitch
                    switch (curQuality)
                    {
                        case ItemQuality.Inferior:
                        case ItemQuality.Invalid:
                        case ItemQuality.Special:
                        case ItemQuality.Superior:
                        case ItemQuality.Normal:
                        case ItemQuality.Magic1:
                        case ItemQuality.Magic2:
                        case ItemQuality.Magic3:
                            statusText += "<=Magical]";
                            //Non-Quality items get skipped quickly.
                            if (Bot.Targeting.Cache.recheckCount > 1)
                                Bot.Targeting.Cache.reCheckedFinished = true;
                            break;

                        case ItemQuality.Rare4:
                        case ItemQuality.Rare5:
                        case ItemQuality.Rare6:
                            statusText += "=Rare]";
                            if (Bot.Targeting.Cache.recheckCount > 2)
                                Bot.Targeting.Cache.reCheckedFinished = true;
                            //else
                            //bItemForcedMovement = true;

                            break;

                        case ItemQuality.Legendary:
                            statusText += "=Legendary]";
                            if (Bot.Targeting.Cache.recheckCount > 3)
                                Bot.Targeting.Cache.reCheckedFinished = true;
                            //else
                            //bItemForcedMovement = true;

                            break;
                    }
                    #endregion

                    //If we are still rechecking then use the waitAfter (powerprime Ability related) to wait a few loops.
                    if (!Bot.Targeting.Cache.reCheckedFinished)
                    {
                        statusText += " RECHECKING";
                        if (Bot.Settings.Debug.DebugStatusBar)
                        {
                            BotMain.StatusText = statusText;
                        }
                        Bot.Targeting.Cache.bWaitingAfterPower = true;
                        Bot.Character.Class.PowerPrime.WaitLoopsAfter = 3;
                        CurrentState = RunStatus.Running;
                        return false;
                    }
                    //We Rechecked Max Confirmation Checking Count, now we check if we want to retry confirmation, or simply try once more then ignore for a few.
                    bool stackableItem = (ItemType.Potion | ItemType.CraftingPage | ItemType.CraftingPlan | ItemType.CraftingReagent).HasFlag(thisObjItem.BalanceData.thisItemType);
                    if (thisObjItem.Itemquality.Value > ItemQuality.Magic3 || stackableItem)
                    {
                        //Items above rare quality don't get blacklisted, just ignored for a few loops.
                        //This will force a movement if stuck.. but 5 loops is only 750ms
                        Bot.Targeting.Cache.CurrentTarget.BlacklistLoops = 5;
                    }
                    else
                    {
                        //Blacklist items below rare quality!
                        Bot.Targeting.Cache.CurrentTarget.BlacklistFlag = BlacklistType.Temporary;
                        Bot.Targeting.Cache.CurrentTarget.NeedsRemoved = true;
                    }

                    // Now tell Trinity to get a new target!
                    Bot.Targeting.Cache.bForceTargetUpdate = true;
                }

                //Reset flag, and continue..
                Bot.Targeting.Cache.ShouldCheckItemLooted = false;
            }
            #endregion

            // See if we have been "newly rooted", to force target updates
            if (Bot.Character.Data.bIsRooted && !Bot.Targeting.Cache.bWasRootedLastTick)
            {
                Bot.Targeting.Cache.bWasRootedLastTick = true;
                Bot.Targeting.Cache.bForceTargetUpdate = true;
            }

            if (!Bot.Character.Data.bIsRooted) Bot.Targeting.Cache.bWasRootedLastTick = false;

            return true;
        }
Exemple #56
0
        object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            RunStatus runStatus = (RunStatus)value;

            return(runStatus == RunStatus.闲置 ? true : false);
        }
Exemple #57
0
        //This is the 2nd step in handling.. we recheck target, get a new Ability if needed, and check potion/special movement avoidance here.
        public virtual bool Refresh()
        {
            // Make sure we reset unstucker stuff here
            Funky.PlayerMover.iTimesReachedStuckPoint = 0;
            Funky.PlayerMover.vSafeMovementLocation = Vector3.Zero;
            Funky.PlayerMover.timeLastRecordedPosition = DateTime.Now;

            // Let's calculate whether or not we want a new target list...
            #region NewtargetChecks
            // Whether we should refresh the target list or not
            bool bShouldRefreshDiaObjects = false;

            if (!Bot.Targeting.Cache.bWholeNewTarget && !Bot.Targeting.Cache.bWaitingForPower && !Bot.Targeting.Cache.bWaitingForPotion)
            {
                // Update targets at least once every 80 milliseconds
                if (Bot.Targeting.Cache.bForceTargetUpdate
                    || Bot.Targeting.Cache.TravellingAvoidance
                    || ((DateTime.Now.Subtract(Bot.Targeting.Cache.lastRefreshedObjects).TotalMilliseconds >= 80 && !ObjectCache.CheckTargetTypeFlag(Bot.Targeting.Cache.CurrentTarget.targetType.Value, TargetType.AvoidanceMovements | TargetType.NoMovement))
                    || DateTime.Now.Subtract(Bot.Targeting.Cache.lastRefreshedObjects).TotalMilliseconds >= 1200))
                {
                    bShouldRefreshDiaObjects = true;
                }

                // If we AREN'T getting new targets - find out if we SHOULD because the current unit has died etc.
                if (!bShouldRefreshDiaObjects && Bot.Targeting.Cache.CurrentTarget.targetType.Value == TargetType.Unit && !Bot.Targeting.Cache.CurrentTarget.IsStillValid())
                    bShouldRefreshDiaObjects = true;

            }

            // So, after all that, do we actually want a new target list?
            if (!Bot.Targeting.Cache.bWholeNewTarget && !Bot.Targeting.Cache.bWaitingForPower && !Bot.Targeting.Cache.bWaitingForPotion)
            {
                // If we *DO* want a new target list, do this...
                if (bShouldRefreshDiaObjects)
                {
                    // Now call the function that refreshes targets
                    Bot.Targeting.Cache.Refresh();

                    // No target, return success
                    if (Bot.Targeting.Cache.CurrentTarget == null)
                    {
                        CurrentState = RunStatus.Success;
                        return false;
                    }
                    else if (Bot.Targeting.Cache.LastCachedTarget != null &&
                          Bot.Targeting.Cache.LastCachedTarget.RAGUID != Bot.Targeting.Cache.CurrentTarget.RAGUID && Bot.Targeting.Cache.CurrentTarget.targetType.Value == TargetType.Item)
                    {
                        //Reset Item Vars
                        Bot.Targeting.Cache.recheckCount = 0;
                        Bot.Targeting.Cache.reCheckedFinished = false;
                        Bot.Targeting.Cache.CheckItemLootStackCount = 0;
                    }

                    // Been trying to handle the same target for more than 30 seconds without damaging/reaching it? Blacklist it!
                    // Note: The time since target picked updates every time the current target loses health, if it's a monster-target
                    if (!ObjectCache.CheckTargetTypeFlag(Bot.Targeting.Cache.CurrentTarget.targetType.Value, TargetType.AvoidanceMovements | TargetType.NoMovement | TargetType.LineOfSight | TargetType.Backtrack)
                          && ((Bot.Targeting.Cache.CurrentTarget.targetType.Value != TargetType.Unit && DateTime.Now.Subtract(Bot.Targeting.Cache.LastChangeOfTarget).TotalSeconds > 12)
                          || (Bot.Targeting.Cache.CurrentTarget.targetType.Value == TargetType.Unit && !Bot.Targeting.Cache.CurrentTarget.IsBoss && DateTime.Now.Subtract(Bot.Targeting.Cache.LastChangeOfTarget).TotalSeconds > 40)))
                    {
                        // NOTE: This only blacklists if it's remained the PRIMARY TARGET that we are trying to actually directly attack!
                        // So it won't blacklist a monster "on the edge of the screen" who isn't even being targetted
                        // Don't blacklist monsters on <= 50% health though, as they can't be in a stuck location... can they!? Maybe give them some extra time!
                        bool bBlacklistThis = true;
                        // PREVENT blacklisting a monster on less than 90% health unless we haven't damaged it for more than 2 minutes
                        if (Bot.Targeting.Cache.CurrentTarget.targetType.Value == TargetType.Unit)
                        {
                            if (Bot.Targeting.Cache.CurrentTarget.IsTreasureGoblin && Bot.Settings.Targeting.GoblinPriority >= 3) bBlacklistThis = false;
                            if (DateTime.Now.Subtract(Bot.Targeting.Cache.LastChangeOfTarget).TotalSeconds <= 120) bBlacklistThis = false;
                        }

                        if (bBlacklistThis)
                        {
                            if (Bot.Targeting.Cache.CurrentTarget.targetType.Value == TargetType.Unit)
                            {
                                //Logger.DBLog.DebugFormat("[Funky] Blacklisting a monster because of possible stuck issues. Monster="+ObjectData.InternalName+" {"+
                                //ObjectData.SNOID.ToString()+"}. Range="+ObjectData.CentreDistance.ToString()+", health %="+ObjectData.CurrentHealthPct.ToString());
                            }

                            Bot.Targeting.Cache.CurrentTarget.NeedsRemoved = true;
                            Bot.Targeting.Cache.CurrentTarget.BlacklistFlag = BlacklistType.Temporary;
                        }
                    }
                    // Make sure we start trying to move again should we need to!
                    Bot.Targeting.Cache.bPickNewAbilities = true;

                    Bot.Targeting.Movement.NewTargetResetVars();
                }
                // Ok we didn't want a new target list, should we at least update the position of the current target, if it's a monster?
                else if (Bot.Targeting.Cache.CurrentTarget.targetType.Value == TargetType.Unit && Bot.Targeting.Cache.CurrentTarget.IsStillValid())
                {
                    Bot.Targeting.Cache.CurrentTarget.UpdatePosition();
                }
            }
            #endregion

            // This variable just prevents an instant 2-target update after coming here from the main decorator function above
            Bot.Targeting.Cache.bWholeNewTarget = false;

            //Update CurrentUnitTarget
            if (Bot.Targeting.Cache.CurrentTarget.targetType.Value == TargetType.Unit)
            {
                //Update CurrentUnitTarget Variable.
                if (Bot.Targeting.Cache.CurrentUnitTarget == null) Bot.Targeting.Cache.CurrentUnitTarget = (CacheUnit)Bot.Targeting.Cache.CurrentTarget;
            }

            //Make sure we are not incapacitated..
            if (Bot.Character.Data.bIsIncapacitated)
            {
                CurrentState = RunStatus.Running;
                return false;
            }

            //We are ready for the specific object type interaction
            return true;
        }
Exemple #58
0
        public static RunStatus FunkyTPBehavior(object ret)
        {
            //Init
            if (!initizedTPBehavior)
            {
                InitTPBehavior();
                return(RunStatus.Running);
            }

            double ElapsedTime = DateTime.Now.Subtract(FunkyTP_LastCastAttempt).TotalSeconds;

            //Check world transfer start
            if (worldtransferStarted)
            {
                if (ElapsedTime < 10 || worldChanged)
                {
                    //Logger.Write(LogLevel.OutOfCombat,"Waiting for world change!");

                    if (!Bot.Character.Data.bIsInTown)
                    {
                        return(RunStatus.Running);
                    }
                    Logger.Write(LogLevel.OutOfCombat, "Casting Behavior Finished, we are in town!", true);
                    ResetTPBehavior();
                    //UpdateSearchGridProvider(true);
                    return(RunStatus.Success);
                }
                if (ElapsedTime >= 10 && !Bot.Character.Data.bIsInTown)
                {
                    //Retry?
                    worldtransferStarted = false;
                    CastAttempted        = false;
                    Vector3 UnstuckPos;
                    if (Bot.NavigationCache.AttemptFindSafeSpot(out UnstuckPos, Vector3.Zero, Bot.Settings.Plugin.AvoidanceFlags))
                    {
                        Logger.Write(LogLevel.OutOfCombat, "Generated Unstuck Position at {0}", UnstuckPos.ToString());
                        ZetaDia.Me.UsePower(SNOPower.Walk, UnstuckPos, Bot.Character.Data.iCurrentWorldID);
                    }
                }

                return(RunStatus.Running);
            }

            //Precheck - Ingame, not dead..
            if (!TPActionIsValid())
            {
                ResetTPBehavior();
                return(RunStatus.Success);
            }
            if (ZetaDia.IsLoadingWorld)             //Loading.. we just wait!
            {
                return(RunStatus.Running);
            }
            if (!CanCastTP())             //Not loading but is valid.. see if we can cast?
            {
                ResetTPBehavior();
                return(RunStatus.Success);
            }

            //Set our flag which is used to setup the refreshing specific for this/similar behaviors.
            FunkyTPBehaviorFlag = true;

            //Refresh?
            if (Bot.Targeting.Cache.ShouldRefreshObjectList)
            {
                Bot.Targeting.Cache.Refresh();
            }

            //Check if we have any NEW targets to deal with..
            //Note: Refresh will filter targets to units and avoidance ONLY.
            if (Bot.Targeting.Cache.CurrentTarget != null)
            {
                Bot.Targeting.Movement.RestartTracking();

                //Directly Handle Target..
                RunStatus targetHandler = Bot.Targeting.Handler.HandleThis();

                //Only return failure if handling failed..
                if (targetHandler == RunStatus.Failure)
                {
                    ResetTPBehavior();
                    return(RunStatus.Success);
                }
                if (targetHandler == RunStatus.Success)
                {
                    Bot.Targeting.ResetTargetHandling();
                }

                return(RunStatus.Running);
            }
            if (MovementOccured)
            {
                //Backtrack to orginal location...

                bool isMoving = false;
                try
                {
                    isMoving = ZetaDia.Me.Movement.IsMoving;
                }
                catch (NullReferenceException) { }

                //Use simple checking of movement, with UsePower on our last location.
                if (!isMoving)
                {
                    double DistanceFromStart = StartingPosition.Distance(Bot.Character.Data.Position);

                    if (DistanceFromStart > 15f && DistanceFromStart < 50f)
                    {
                        //Logger.DBLog.InfoFormat("[FunkyTP] Backtracking!");
                        //Move back to starting position..
                        //ZetaDia.Me.UsePower(SNOPower.Walk, StartingPosition);
                        //return RunStatus.Running;
                    }
                    else if (DistanceFromStart >= 50f)
                    {
                        //Logger.DBLog.InfoFormat("[FunkyTP] Range from our starting position is {0}. Now using Navigator to move.", DistanceFromStart);
                        //Navigator.MoveTo(StartingPosition, "Backtracking to Orginal Position", true);
                    }
                }
                else
                {
                    return(RunStatus.Running);
                }

                MovementOccured = false;
            }

            //Update Movement Data
            Bot.NavigationCache.RefreshMovementCache();

            //Make sure we are not moving..
            if (Bot.NavigationCache.IsMoving)
            {
                return(RunStatus.Running);
            }

            //Check if we are casting, if not cast, else if casting but time has elapsed then cancel cast.

            if (!CastingRecall())
            {
                //Check last time cast..
                if (ElapsedTime > 5 && CastAttempted)
                {
                    worldtransferStarted = true;
                    return(RunStatus.Running);
                }
                if (ElapsedTime > 8 || !CastAttempted)
                {
                    //Recast
                    Logger.Write(LogLevel.OutOfCombat, "Casting TP..");
                    ZetaDia.Me.UseTownPortal();
                    CastAttempted           = true;
                    FunkyTP_LastCastAttempt = DateTime.Now;
                }

                return(RunStatus.Running);
            }
            if (ElapsedTime > 8)
            {
                //Void Cast?
                Logger.Write(LogLevel.OutOfCombat, "Attempting to void cast with movement..");
                Vector3 V3loc;
                bool    success = Bot.NavigationCache.AttemptFindSafeSpot(out V3loc, Vector3.Zero, Bot.Settings.Plugin.AvoidanceFlags);
                if (success)
                {
                    Navigator.MoveTo(V3loc, "Void Cast Movement", false);
                }

                return(RunStatus.Running);
            }

            return(RunStatus.Running);
        }
Exemple #59
0
 public StatusEntity(string _forum, RunStatus _status, string _message)
 {
     Forum = _forum;
     Status = _status;
     Message = _message;
 }
Exemple #60
0
 public virtual bool Leave(object input)
 {
     status_ = RunStatus.Completed;
     return(true);
 }