Exemplo n.º 1
0
 public PlanWork(IReGoapAgent agent, IReGoapGoal blacklistGoal, Queue <ReGoapActionState> actions, Action <IReGoapGoal> callback) : this()
 {
     Agent         = agent;
     BlacklistGoal = blacklistGoal;
     Actions       = actions;
     Callback      = callback;
 }
 public ReGoapPlanWork(IReGoapAgent <T, W> agent, IReGoapGoal <T, W> blacklistGoal, Queue <ReGoapActionState <T, W> > actions, Action <IReGoapGoal <T, W> > callback) : this()
 {
     Agent         = agent;
     BlacklistGoal = blacklistGoal;
     Actions       = actions;
     Callback      = callback;
 }
Exemplo n.º 3
0
    public override void Precalculations(IReGoapAgent goapAgent, ReGoapState goalState)
    {
        base.Precalculations(goapAgent, goalState);
        var bankPosition = agent.GetMemory().GetWorldState().Get <Vector3>("nearestBankPosition");

        preconditions.Clear();
        effects.Clear();
        preconditions.Set("isAtPosition", bankPosition);
        effects.Set("isAtPosition", Vector3.zero);

        foreach (var pair in goalState.GetValues())
        {
            if (pair.Key.StartsWith("collectedResource"))
            {
                var resourceName = pair.Key.Substring(17);
                preconditions.Set("hasResource" + resourceName, true);
                effects.Set("collectedResource" + resourceName, true);
                settings = new AddResourceToBankSettings
                {
                    ResourceName = resourceName
                };
                break;
            }
        }
    }
Exemplo n.º 4
0
        protected override void Awake()
        {
            agent = GetComponent <IReGoapAgent <string, object> >();

            base.Awake();
            goal.Set($"Has Role {type}", false);
        }
Exemplo n.º 5
0
    public override void Precalculations(IReGoapAgent goapAgent, ReGoapState goalState)
    {
        var newNeededResourceName = GetNeededResourceFromGoal(goalState);

        preconditions.Clear();
        effects.Clear();
        if (newNeededResourceName != null)
        {
            resource = agent.GetMemory().GetWorldState().Get <IResource>("nearest" + newNeededResourceName);
            if (resource != null)
            {
                resourcePosition =
                    agent.GetMemory()
                    .GetWorldState()
                    .Get <Vector3>(string.Format("nearest{0}Position", newNeededResourceName));
                preconditions.Set("isAtPosition", resourcePosition);
                // false preconditions are not supported
                //preconditions.Set("hasResource" + newNeededResourceName, false);
                effects.Set("hasResource" + newNeededResourceName, true);

                settings = new GatherResourceSettings
                {
                    ResourcePosition = resourcePosition,
                    Resource         = resource
                };
            }
        }
        base.Precalculations(goapAgent, goalState);
    }
Exemplo n.º 6
0
    public IReGoapGoal Plan(IReGoapAgent agent, IReGoapGoal blacklistGoal = null, Queue <ReGoapActionState> currentPlan = null, Action <IReGoapGoal> callback = null)
    {
        ReGoapLogger.Log("[ReGoalPlanner] Starting planning calculation for agent: " + agent);
        goapAgent   = agent;
        Calculated  = false;
        currentGoal = null;
        var possibleGoals = new List <IReGoapGoal>();

        foreach (var goal in goapAgent.GetGoalsSet())
        {
            if (goal == blacklistGoal)
            {
                continue;
            }
            goal.Precalculations(this);
            if (goal.IsGoalPossible()) //goal.GetPriority() > bestPriority &&
            {
                possibleGoals.Add(goal);
            }
        }
        possibleGoals.Sort((x, y) => x.GetPriority().CompareTo(y.GetPriority()));

        while (possibleGoals.Count > 0)
        {
            currentGoal = possibleGoals[possibleGoals.Count - 1];
            possibleGoals.RemoveAt(possibleGoals.Count - 1);
            var goalState = currentGoal.GetGoalState();

            var leaf = (BGoapNode)astar.Run(
                new BGoapNode(this, goalState, null, null), goapAgent.GetMemory().GetWorldState(), settings.MaxIterations, settings.PlanningEarlyExit);
            if (leaf == null)
            {
                currentGoal = null;
                continue;
            }
            var path = leaf.CalculatePath();
            if (currentPlan != null && currentPlan == path)
            {
                currentGoal = null;
                break;
            }
            currentGoal.SetPlan(path);
            break;
        }
        Calculated = true;

        if (callback != null)
        {
            callback(currentGoal);
        }
        if (currentGoal != null)
        {
            ReGoapLogger.Log(string.Format("[ReGoapPlanner] Calculated plan for goal '{0}', plan length: {1}", currentGoal, currentGoal.GetPlan().Count));
        }
        else
        {
            ReGoapLogger.LogWarning("[ReGoapPlanner] Error while calculating plan.");
        }
        return(currentGoal);
    }
Exemplo n.º 7
0
    private void OnGUI()
    {
        if (Selection.activeGameObject != null)
        {
            agent = Selection.activeGameObject.GetComponent <IReGoapAgent>();
            if (agent == null)
            {
                return;
            }
        }
        else
        {
            return;
        }

        DrawGrid(20, 0.2f, Color.gray);
        DrawGrid(100, 0.4f, Color.gray);

        UpdateGoapNodes(Selection.activeGameObject);
        DrawNodes();

        ProcessNodeEvents(Event.current);
        ProcessEvents(Event.current);

        Repaint();
    }
Exemplo n.º 8
0
    public override void Precalculations(IReGoapAgent goapAgent, ReGoapState goalState)
    {
        base.Precalculations(goapAgent, goalState);
        var workstationPosition = agent.GetMemory().GetWorldState().Get <Vector3>("nearestWorkstationPosition");

        preconditions.Set("isAtPosition", workstationPosition);
        //effects.Set("isAtPosition", Vector3.zero);
    }
Exemplo n.º 9
0
 void Awake()
 {
     agent = GetComponent <IReGoapAgent <string, object> >();
     foreach (var actionText in _actionTexts)
     {
         actionTexts.Add(actionText.actionName, actionText.text);
     }
 }
Exemplo n.º 10
0
 public override IReGoapActionSettings <string, object> GetSettings(IReGoapAgent <string, object> goapAgent, ReGoapState <string, object> goalState)
 {
     settings = new GenericGoToSettings
     {
         ObjectivePosition = GetWantedPositionFromState(goalState)
     };
     return(base.GetSettings(goapAgent, goalState));
 }
Exemplo n.º 11
0
 public override void Precalculations(IReGoapAgent goapAgent, ReGoapState goalState)
 {
     objectivePosition = goalState.Get <Vector3>("isAtPosition");
     settings          = new GenericGoToSettings
     {
         ObjectivePosition = objectivePosition
     };
     base.Precalculations(goapAgent, goalState);
 }
        public ReGoapPlanWork <T, W> Plan(IReGoapAgent <T, W> agent, IReGoapGoal <T, W> blacklistGoal, Queue <ReGoapActionState <T, W> > currentPlan, Action <IReGoapGoal <T, W> > callback)
        {
            var work = new ReGoapPlanWork <T, W>(agent, blacklistGoal, currentPlan, callback);

            lock (ReGoapPlannerThread <T, W> .WorksQueue)
            {
                ReGoapPlannerThread <T, W> .WorksQueue.Enqueue(work);
            }
            return(work);
        }
Exemplo n.º 13
0
    public PlanWork Plan(IReGoapAgent agent, IReGoapGoal blacklistGoal, Queue <ReGoapActionState> currentPlan, Action <IReGoapGoal> callback)
    {
        var work = new PlanWork(agent, blacklistGoal, currentPlan, callback);

        lock (worksQueue)
        {
            worksQueue.Enqueue(work);
        }
        threadEvents.Set();
        return(work);
    }
Exemplo n.º 14
0
 public override IReGoapActionSettings <string, object> GetSettings(IReGoapAgent <string, object> goapAgent, ReGoapState <string, object> goalState)
 {
     settings = null;
     foreach (var pair in goalState.GetValues())
     {
         if (pair.Key.StartsWith("collectedResource"))
         {
             var resourceName = pair.Key.Substring(17);
             settings = new AddResourceToBankSettings
             {
                 ResourceName = resourceName
             };
             break;
         }
     }
     return(settings);
 }
Exemplo n.º 15
0
        public override IReGoapActionSettings <string, object> GetSettings(IReGoapAgent <string, object> goapAgent, ReGoapState <string, object> goalState)
        {
            var newNeededResourceName             = GetNeededResourceFromGoal(goalState);
            GatherResourceSettings wantedSettings = null;

            if (newNeededResourceName != null)
            {
                var wantedResource = agent.GetMemory().GetWorldState().Get("nearest" + newNeededResourceName) as IResource;
                if (wantedResource != null)
                {
                    wantedSettings = new GatherResourceSettings
                    {
                        ResourcePosition = (Vector3)agent.GetMemory().GetWorldState()
                                           .Get(string.Format("nearest{0}Position", newNeededResourceName)),
                        Resource = wantedResource
                    };
                }
            }
            return(wantedSettings);
        }
Exemplo n.º 16
0
    /*
     * private IEnumerable<IReGoapActionSettings> GenerateAllPossibleActions(IReGoapAgent goapAgent, BGoapState goalState, BGoapState genericsAssignement) {
     *
     *  //this is not a real state, just a container for variables
     *  BGoapState lockedInValues = new BGoapState();
     *
     *  BGoapState effects = staticEffects.Clone() as BGoapState;
     *  List<IStateVarKey> freeEffects = new List<IStateVarKey>();
     *  //set effects
     *  foreach (IStateVarKey iteratorKey in parametrizedEffects.Keys)
     *  {
     *      IStateVarKey key;// if key is a template, use it's appropriate child instead
     *      if (iteratorKey is IGenericStateVarKeyTemplate)                 //appropriate child is such, that has generic argument in accordance with genericsAssignement
     *          key = (iteratorKey as IGenericStateVarKeyTemplate).MakeGenericInstance(genericsAssignement.Get(genericParameters[iteratorKey]));
     *      else
     *          key = iteratorKey;
     *
     *      IStateVarKey variableKey = parametrizedEffects[iteratorKey];
     *      if (goalState.HasKey(key))
     *      {
     *          //set locked in values
     *          if (lockedInValues.HasKey(variableKey))
     *          {
     *              if (lockedInValues.ValueEqualsUntyped(variableKey, key, goalState))
     *              { //clash on variable value
     *                  continue;
     *              }
     *          }
     *          else
     *          {
     *              lockedInValues.SetFromKeyUntyped(variableKey, key, goalState);
     *          }
     *          effects.SetFrom(key, goalState);
     *      }
     *      else
     *      {
     *          freeEffects.Add(key);
     *      }
     *  }
     *
     *  BGoapState preconditions = staticPreconditions.Clone() as BGoapState;
     *
     *  List<IStateVarKey> freePreconditions = new List<IStateVarKey>();
     *  foreach (IStateVarKey iteratorKey in parametrizedPreconditions.Keys)
     *  {
     *      IStateVarKey key;// if key is a template, use it's appropriate child instead
     *      if (iteratorKey is IGenericStateVarKeyTemplate)                 //appropriate child is such, that has generic argument in accordance with genericsAssignement
     *          key = (iteratorKey as IGenericStateVarKeyTemplate).MakeGenericInstance(genericsAssignement.Get(genericParameters[iteratorKey]));
     *      else
     *          key = iteratorKey;
     *
     *      IStateVarKey variableKey = parametrizedPreconditions[iteratorKey];
     *      if (lockedInValues.HasKey(variableKey))
     *      {
     *          preconditions.SetFromKeyUntyped(key, variableKey, lockedInValues);
     *      }
     *      else
     *      {
     *          freePreconditions.Add(key);
     *      }
     *  }
     *
     *  if (freeEffects.Count + freePreconditions.Count > 0) //some variables need to be searched
     *  {
     *      foreach (BGoapState assignment in GetPossibleVariableCombinations(lockedInValues, goapAgent))
     *      {
     *          BGoapState finalEffects = effects.Clone() as BGoapState;
     *          BGoapState finalPreconditions = preconditions.Clone() as BGoapState;
     *          foreach (IStateVarKey key in freeEffects)
     *          {
     *              IStateVarKey variableKey = parametrizedEffects[key];
     *              finalEffects.SetFromKeyUntyped(key, variableKey, assignment);
     *          }
     *          foreach (IStateVarKey key in freePreconditions)
     *          {
     *              IStateVarKey variableKey = parametrizedPreconditions[key];
     *              finalPreconditions.SetFromKeyUntyped(key, variableKey, assignment);
     *          }
     *          yield return new PrototypeActionSettings { effects = finalEffects, preconditions = finalPreconditions, agent = goapAgent };
     *      }
     *  }
     *  else
     *  { //all variables locked in
     *      yield return new PrototypeActionSettings { effects = effects, preconditions = preconditions, agent = goapAgent };
     *  }
     *
     * }
     */

    public override IEnumerable <IReGoapActionSettings> MultiPrecalculations(IReGoapAgent goapAgent, BGoapState goalState)
    {
        foreach (BGoapState genericAssignments in GetPossibleGenericVariableCombinations(goapAgent))
        {
            /// generate all possible generic assignemnts
            GoapStateEntry[] processedEffects       = effects.Select(x => x.GenNongenericVersion(genericAssignments)).ToArray();
            GoapStateEntry[] processedPreconditions = preconditions.Select(x => x.GenNongenericVersion(genericAssignments)).ToArray();

            //lock in values that are in goal
            BGoapState lockedInValues = new BGoapState();
            foreach (GoapStateEntry effect in processedEffects)
            {
                effect.LockInValues(lockedInValues, goalState);
            }

            //generate all actions available for given locked values
            foreach (BGoapState assignments in GetPossibleVariableCombinations(lockedInValues, goapAgent, genericAssignments))
            {
                BGoapState combined = new BGoapState(assignments).Union(lockedInValues); //union should work here, as lockedInValues and assignemets should be mutually exclusive

                BGoapState generatedPreconditions = new BGoapState();
                BGoapState generatedEffects       = new BGoapState();
                foreach (GoapStateEntry entry in processedPreconditions)
                {
                    entry.AddSelfToState(generatedPreconditions, combined);
                }
                foreach (GoapStateEntry entry in processedEffects)
                {
                    entry.AddSelfToState(generatedEffects, combined);
                }
                yield return(new PrototypeActionSettings {
                    effects = generatedEffects, preconditions = generatedPreconditions,
                    genericAssignments = genericAssignments, agent = goapAgent
                });
            }
        }
    }
Exemplo n.º 17
0
 public virtual void PostPlanCalculations(IReGoapAgent <T, W> goapAgent)
 {
     agent = goapAgent;
 }
    private void UpdateGoapNodes <T, W>(IReGoapAgent <T, W> agent)
    {
        if (nodes == null)
        {
            nodes = new List <ReGoapNodeEditor>();
        }
        if (agentHelper == null || agent == null || !agent.IsActive() || agent.GetMemory() == null)
        {
            return;
        }

        nodes.Clear();
        var width        = 300f;
        var height       = 70f;
        var nodePosition = new Vector2(0f, 60f);
        var nodeMiddleY  = new Vector2(0f, height * 0.5f);

        ReGoapNodeEditor?previousNode = null;

        foreach (var goal in agent.GetGoalsSet())
        {
            if (goal.GetGoalState() == null)
            {
                continue;
            }
            var text = string.Format("<b>GOAL</b> <i>{0}</i>\n", goal);
            foreach (var keyValue in goal.GetGoalState().GetValues())
            {
                text += string.Format("<b>'{0}'</b> = <i>'{1}'</i>", keyValue.Key, keyValue.Value);
            }
            var style = nodeStyle;
            if (agent.IsActive() && agent.GetCurrentGoal() == goal)
            {
                style = activeStyle;
            }
            var newNode = DrawGenericNode(text, width, height, style, ref nodePosition);
            if (previousNode.HasValue)
            {
                var startPosition = previousNode.Value.Rect.max - nodeMiddleY - new Vector2(10f, 0f);
                var endPosition   = newNode.Rect.min + nodeMiddleY + new Vector2(10f, 0f);
                Handles.DrawLine(startPosition, endPosition);
            }
            previousNode = newNode;
        }
        previousNode = null;

        nodePosition = new Vector2(0f, nodePosition.y + height + 10);
        height       = 66;
        var maxHeight = height;

        var emptyGoal = agent.InstantiateNewState();
        GoapActionStackData <T, W> stackData;

        stackData.agent        = agent;
        stackData.currentState = agent.GetMemory().GetWorldState();
        stackData.goalState    = emptyGoal;
        stackData.next         = null;
        stackData.settings     = null;

        foreach (var action in agent.GetActionsSet())
        {
            var curHeight = height;
            var text      = string.Format("<b>POSS.ACTION</b> <i>{0}</i>\n", action.GetName());
            text += "-<b>preconditions</b>-\n";
            var preconditionsDifferences = agent.InstantiateNewState();
            var preconditions            = action.GetPreconditions(stackData);
            if (preconditions == null)
            {
                continue;
            }
            preconditions.MissingDifference(stackData.currentState, ref preconditionsDifferences);
            foreach (var preconditionPair in preconditions.GetValues())
            {
                curHeight += 13;
                var color = "#004d00";
                if (preconditionsDifferences.GetValues().ContainsKey(preconditionPair.Key))
                {
                    color = "#800000";
                }
                text += string.Format("<color={2}>'<b>{0}</b>' = '<i>{1}</i>'</color>\n", preconditionPair.Key, preconditionPair.Value, color);
            }
            preconditionsDifferences.Recycle();

            text += "-<b>effects</b>-\n";
            foreach (var effectPair in action.GetEffects(stackData).GetValues())
            {
                curHeight += 13;
                text      += string.Format("'<b>{0}</b>' = '<i>{1}</i>'\n", effectPair.Key, effectPair.Value);
            }
            curHeight += 13;
            var proceduralCheck = action.CheckProceduralCondition(stackData);
            text += string.Format("<color={0}>-<b>proceduralCondition</b>: {1}</color>\n", proceduralCheck ? "#004d00" : "#800000", proceduralCheck);

            maxHeight = Mathf.Max(maxHeight, curHeight);

            nodeMiddleY = new Vector2(0f, curHeight * 0.5f);
            var newNode = DrawGenericNode(text, width, curHeight, possibleActionStyle, ref nodePosition);
            if (previousNode.HasValue)
            {
                var startPosition = previousNode.Value.Rect.max - nodeMiddleY - new Vector2(10f, 0f);
                var endPosition   = newNode.Rect.min + nodeMiddleY + new Vector2(10f, 0f);
                Handles.DrawLine(startPosition, endPosition);
            }
            previousNode = newNode;
        }
        previousNode = null;

        nodePosition.x  = 0;
        nodePosition.y += maxHeight + 10;
        height          = 40;
        nodeMiddleY     = new Vector2(0f, height * 0.5f);
        if (agent.GetCurrentGoal() != null)
        {
            foreach (var action in agent.GetStartingPlan().ToArray())
            {
                var style = actionNodeStyle;
                if (action.Action.IsActive())
                {
                    style = activeActionNodeStyle;
                }
                var text = string.Format("<b>ACTION</b> <i>{0}</i>\n", action.Action.GetName());

                var newNode = DrawGenericNode(text, width, height, style, ref nodePosition);
                if (previousNode.HasValue)
                {
                    var startPosition = previousNode.Value.Rect.max - nodeMiddleY - new Vector2(10f, 0f);
                    var endPosition   = newNode.Rect.min + nodeMiddleY + new Vector2(10f, 0f);
                    Handles.DrawLine(startPosition, endPosition);
                }
                previousNode = newNode;
            }
        }

        if (agent.GetMemory() != null)
        {
            nodePosition = new Vector2(0, nodePosition.y + height + 10);
            width        = 500;
            height       = 40;
            nodeMiddleY  = new Vector2(0f, height * 0.5f);
            var nodeText = "<b>WORLD STATE</b>\n";
            foreach (var pair in agent.GetMemory().GetWorldState().GetValues())
            {
                nodeText += string.Format("'<b>{0}</b>' = '<i>{1}</i>'\n", pair.Key, pair.Value);
                height   += 13;
            }
            DrawGenericNode(nodeText, width, height, worldStateStyle, ref nodePosition);
        }
    }
Exemplo n.º 19
0
    protected override IEnumerable <BGoapState> GetPossibleVariableCombinations(BGoapState lockInValues, IReGoapAgent goapAgent, BGoapState genericAssignments)
    {
        if (lockInValues.HasKey(itemVariable) && lockInValues.Get(itemVariable) == null) //this should be handled by place/drop item
        {
            yield break;
        }
        if (lockInValues.HasKey(itemVariable) && lockInValues.HasKey(itemTypeVariable))          //both item type and specific item are locked in
        {
            if (lockInValues.Get(itemVariable).sourceItem == lockInValues.Get(itemTypeVariable)) //check that this combination is valid
            {
                BGoapState assignment = new BGoapState();
                assignment.Set(locationVariable, lockInValues.Get(itemVariable).positionCache);
                yield return(assignment);
            }
        }
        else if (lockInValues.HasKey(itemVariable) && lockInValues.Get(itemVariable) != null) //specific item locked in, fill in it's values
        {
            BGoapState assignment = new BGoapState();
            assignment.Set(itemTypeVariable, lockInValues.Get(itemVariable).sourceItem);
            assignment.Set(locationVariable, lockInValues.Get(itemVariable).positionCache);
            yield return(assignment);
        }
        else if (lockInValues.HasKey(itemTypeVariable))   //item type locked in, fill in all possible items

        {
            DBItem requiredItemType = lockInValues.Get(itemTypeVariable);
            foreach (InGameItem item in (goapAgent.GetMemory() as GoapMemory).GetAvailableItemList())
            {
                if (item.sourceItem == requiredItemType)
                {
                    BGoapState assignment = new BGoapState();
                    assignment.Set(itemVariable, item);
                    assignment.Set(locationVariable, item.positionCache);
                    yield return(assignment);
                }
            }
        }
        yield break;
    }
Exemplo n.º 20
0
    public IReGoapGoal Plan(IReGoapAgent agent, IReGoapGoal blacklistGoal = null, Queue <ReGoapActionState> currentPlan = null, Action <IReGoapGoal> callback = null)
    {
        ReGoapLogger.Log("[ReGoalPlanner] Starting planning calculation for agent: " + agent);
        goapAgent   = agent;
        Calculated  = false;
        currentGoal = null;
        var possibleGoals = new List <IReGoapGoal>();

        foreach (var goal in goapAgent.GetGoalsSet())
        {
            if (goal == blacklistGoal)
            {
                continue;
            }
            goal.Precalculations(this);
            if (goal.IsGoalPossible()) //goal.GetPriority() > bestPriority &&
            {
                possibleGoals.Add(goal);
            }
        }
        possibleGoals.Sort((x, y) => x.GetPriority().CompareTo(y.GetPriority()));

        while (possibleGoals.Count > 0)
        {
            currentGoal = possibleGoals[possibleGoals.Count - 1];
            possibleGoals.RemoveAt(possibleGoals.Count - 1);
            var goalState = currentGoal.GetGoalState();

            // can't work with dynamic actions, of course
            if (!settings.UsingDynamicActions)
            {
                var wantedGoalCheck = currentGoal.GetGoalState();
                // we check if the goal can be archived through actions first, so we don't brute force it with A* if we can't
                foreach (var action in goapAgent.GetActionsSet())
                {
                    action.Precalculations(goapAgent, goalState);
                    if (!action.CheckProceduralCondition(goapAgent, wantedGoalCheck))
                    {
                        continue;
                    }
                    // check if the effects of all actions can archieve currentGoal
                    var previous = wantedGoalCheck;
                    wantedGoalCheck = new ReGoapState();
                    previous.MissingDifference(action.GetEffects(wantedGoalCheck), ref wantedGoalCheck);
                }
                // can't validate goal
                if (wantedGoalCheck.Count > 0)
                {
                    currentGoal = null;
                    continue;
                }
            }

            var leaf = (ReGoapNode)astar.Run(
                new ReGoapNode(this, goalState, null, null), goalState, settings.MaxIterations, settings.PlanningEarlyExit);
            if (leaf == null)
            {
                currentGoal = null;
                continue;
            }
            var path = leaf.CalculatePath();
            if (currentPlan != null && currentPlan == path)
            {
                currentGoal = null;
                break;
            }
            currentGoal.SetPlan(path);
            break;
        }
        Calculated = true;

        if (callback != null)
        {
            callback(currentGoal);
        }
        if (currentGoal != null)
        {
            ReGoapLogger.Log(string.Format("[ReGoapPlanner] Calculated plan for goal '{0}', plan length: {1}", currentGoal, currentGoal.GetPlan().Count));
        }
        else
        {
            ReGoapLogger.LogWarning("[ReGoapPlanner] Error while calculating plan.");
        }
        return(currentGoal);
    }
Exemplo n.º 21
0
        public IReGoapGoal <T, W> Plan(IReGoapAgent <T, W> agent, IReGoapGoal <T, W> blacklistGoal = null, Queue <ReGoapActionState <T, W> > currentPlan = null, Action <IReGoapGoal <T, W> > callback = null)
        {
            if (ReGoapLogger.Level == ReGoapLogger.DebugLevel.Full)
            {
                ReGoapLogger.Log("[ReGoalPlanner] Starting planning calculation for agent: " + agent);
            }
            goapAgent   = agent;
            Calculated  = false;
            currentGoal = null;
            var possibleGoals = new List <IReGoapGoal <T, W> >();

            foreach (var goal in goapAgent.GetGoalsSet())
            {
                if (goal == blacklistGoal)
                {
                    continue;
                }
                goal.Precalculations(this);
                if (goal.IsGoalPossible())
                {
                    possibleGoals.Add(goal);
                }
            }
            possibleGoals.Sort((x, y) => x.GetPriority().CompareTo(y.GetPriority()));

            while (possibleGoals.Count > 0)
            {
                currentGoal = possibleGoals[possibleGoals.Count - 1];
                possibleGoals.RemoveAt(possibleGoals.Count - 1);
                var goalState = currentGoal.GetGoalState();

                // can't work with dynamic actions, of course
                if (!settings.UsingDynamicActions)
                {
                    var wantedGoalCheck = currentGoal.GetGoalState();
                    // we check if the goal can be archived through actions first, so we don't brute force it with A* if we can't
                    foreach (var action in goapAgent.GetActionsSet())
                    {
                        action.Precalculations(goapAgent, goalState);
                        if (!action.CheckProceduralCondition(goapAgent, wantedGoalCheck))
                        {
                            continue;
                        }
                        // check if the effects of all actions can archieve currentGoal
                        var previous = wantedGoalCheck;
                        wantedGoalCheck = ReGoapState <T, W> .Instantiate();

                        previous.MissingDifference(action.GetEffects(wantedGoalCheck), ref wantedGoalCheck);
                    }
                    // can't validate goal
                    if (wantedGoalCheck.Count > 0)
                    {
                        currentGoal = null;
                        continue;
                    }
                }

                //Utilities.ReGoapLogger.Log(string.Format("**** Goal: {0}, Expected State = ({1})", currentGoal.GetName(), goalState));

                goalState = goalState.Clone();
                var leaf = (ReGoapNode <T, W>)astar.Run(
                    ReGoapNode <T, W> .Instantiate(this, goalState, null, null), goalState, settings.MaxIterations, settings.PlanningEarlyExit, debugPlan: agent.debugPlan);
                if (leaf == null)
                {
                    currentGoal = null;
                    continue;
                }

                var result = leaf.CalculatePath();
                if (currentPlan != null && currentPlan == result)
                {
                    currentGoal = null;
                    break;
                }
                if (result.Count == 0)
                {
                    currentGoal = null;
                    continue;
                }
                currentGoal.SetPlan(result);
                break;
            }
            Calculated = true;

            if (callback != null)
            {
                callback(currentGoal);
            }
            if (currentGoal != null)
            {
                ReGoapLogger.Log(string.Format("[ReGoapPlanner] Calculated plan for goal '{0}', plan length: {1}", currentGoal, currentGoal.GetPlan().Count));
                if (ReGoapLogger.Level == ReGoapLogger.DebugLevel.Full)
                {
                    int i = 0;
                    foreach (var action in currentGoal.GetPlan())
                    {
                        ReGoapLogger.Log(string.Format("[ReGoapPlanner] {0}) {1}", i++, action.Action));
                    }
                }
            }
            else
            {
                ReGoapLogger.LogWarning("[ReGoapPlanner] Error while calculating plan.");
            }
            return(currentGoal);
        }
Exemplo n.º 22
0
 public virtual IReGoapActionSettings <T, W> GetSettings(IReGoapAgent <T, W> goapAgent, ReGoapState <T, W> goalState)
 {
     return(settings);
 }
Exemplo n.º 23
0
 public override bool CheckProceduralCondition(IReGoapAgent goapAgent, ReGoapState goalState, IReGoapAction next = null)
 {
     return(base.CheckProceduralCondition(goapAgent, goalState) && bag != null);
 }
Exemplo n.º 24
0
    protected override IEnumerable <BGoapState> GetPossibleVariableCombinations(BGoapState lockInValues, IReGoapAgent goapAgent, BGoapState genericAssignments)
    {
        BGoapState assignment = new BGoapState();

        assignment.Set(locationVariable, genericAssignments.Get(table).positionCache);
        yield return(assignment);
    }
Exemplo n.º 25
0
 protected override IEnumerable <BGoapState> GetPossibleGenericVariableCombinations(IReGoapAgent goapAgent)
 {
     foreach (SmartObject so in (goapAgent.GetMemory() as GoapMemory).GetAvailableSoList())
     {
         if (so is RPGSOTable)
         {
             BGoapState resultState = new BGoapState();
             resultState.Set(table, so);
             yield return(resultState);
         }
     }
 }
Exemplo n.º 26
0
 public override void PostPlanCalculations(IReGoapAgent goapAgent)
 {
 }
Exemplo n.º 27
0
 public virtual bool CheckProceduralCondition(IReGoapAgent <T, W> goapAgent, ReGoapState <T, W> goalState, IReGoapAction <T, W> next = null)
 {
     return(true);
 }
Exemplo n.º 28
0
 public virtual void Precalculations(GoapActionStackData <T, W> stackData)
 {
     agent = stackData.agent;
 }
Exemplo n.º 29
0
 public override bool CheckProceduralCondition(IReGoapAgent <string, object> goapAgent, ReGoapState <string, object> goalState, IReGoapAction <string, object> next = null)
 {
     return(base.CheckProceduralCondition(goapAgent, goalState) && bag != null);
 }
Exemplo n.º 30
0
 public virtual void Precalculations(IReGoapAgent <T, W> goapAgent, ReGoapState <T, W> goalState)
 {
     agent = goapAgent;
 }