Example #1
0
    /// <summary>
    /// Return true if the root node is not a good type for being a root
    /// </summary>
    /// <param name="i"></param>
    /// <returns>The number of children <paramref name="paramNode"/> has</returns>
    public bool BadRootCheck(BehaviourNode paramNode = null)
    {
        BehaviourNode node;

        if (paramNode)
        {
            node = paramNode;
        }
        else
        {
            node = (BehaviourNode)nodes.Where(n => ((BehaviourNode)n).isRoot).FirstOrDefault();
            if (!node)
            {
                return(false);
            }
        }

        if (node.type == behaviourType.Leaf)
        {
            return(true);
        }

        if (node.type < behaviourType.Leaf)
        {
            return(false);
        }

        foreach (TransitionGUI transition in transitions.FindAll(t => !t.isExit && node.Equals(t.fromNode)))
        {
            return(BadRootCheck((BehaviourNode)transition.toNode));
        }

        return(false);
    }
Example #2
0
    /// <summary>
    /// Deletes the <paramref name="node"/> and its children
    /// </summary>
    /// <param name="node"></param>
    public void DeleteNode(BehaviourNode node, bool deleteTransitions = true)
    {
        if (nodes.Remove(node))
        {
            if (deleteTransitions)
            {
                foreach (TransitionGUI transition in transitions.FindAll(t => node.Equals(t.fromNode)))
                {
                    DeleteConnection(transition);
                    DeleteNode((BehaviourNode)transition.toNode);
                }
                foreach (TransitionGUI transition in transitions.FindAll(t => node.Equals(t.toNode)))
                {
                    DeleteConnection(transition);
                }
            }

            if (node.subElem == null)
            {
                elementNamer.RemoveName(node.identificator);
            }
            else
            {
                elementNamer.RemoveName(node.subElem.identificator);
            }
        }
    }
        private string GetNodePath(BossBehaviour behaviour, BehaviourNode node)
        {
            var arrayName  = node is ActionBehaviourNode ? "_actionBehaviours" : "_compoundBehaviours";
            var arrayField = behaviour.GetType().GetField(arrayName, BindingFlags.NonPublic | BindingFlags.Instance);

            if (arrayField == null)
            {
                throw new ApplicationException(string.Format("Cannot find field {0} in class {1}", arrayName,
                                                             behaviour.GetType()));
            }

            var dict      = arrayField.GetValue(behaviour);
            var keysField = FindFieldInHierarchy(dict.GetType(), "_keys");

            if (keysField == null)
            {
                throw new ApplicationException(string.Format("Cannot find field {0} in class {1}", "_keys",
                                                             dict.GetType()));
            }

            var list = (IList)keysField.GetValue(dict);

            var index = list.IndexOf(node.Guid);

            if (index < 0)
            {
                throw new ArgumentException(string.Format("Cannot find node {0}", node));
            }

            var path = string.Format("{0}._values.Array.data[{1}]", arrayName, index);

            return(path);
        }
Example #4
0
 public virtual void SetChild(BehaviourNode node)
 {
     if (child != null)
     {
         child = node;
     }
 }
Example #5
0
    /// <summary>
    /// Creates a copy of this <see cref="BehaviourNode"/>
    /// </summary>
    /// <param name="args"></param>
    /// <returns></returns>
    public override GUIElement CopyElement(params object[] args)
    {
        BehaviourTree parent = (BehaviourTree)args[0];

        BehaviourNode result = CreateInstance <BehaviourNode>();

        result.identificator = this.identificator;
        result.nodeName      = this.nodeName;
        result.parent        = parent;
        result.type          = this.type;
        result.windowRect    = new Rect(this.windowRect);
        result.isRoot        = this.isRoot;
        result.isRandom      = this.isRandom;
        result.isInfinite    = this.isInfinite;
        result.delayTime     = this.delayTime;
        result.Nloops        = this.Nloops;
        result.index         = this.index;

        if (this.subElem)
        {
            result.subElem = (ClickableElement)this.subElem.CopyElement(parent);
        }

        return(result);
    }
Example #6
0
        private static Vector2 GetNodeSize_Horz(BehaviourNode node)
        {
            string label = node.Title;

            if (node != null)
            {
                if (node is NodeGroup)
                {
                    return(m_nodeGroupStyle.GetSize_Horz(label));
                }
                else if (node is Composite)
                {
                    return(m_compositeStyle.GetSize_Horz(label));
                }
                else if (node is Decorator || node is NodeGroup)
                {
                    return(m_decoratorStyle.GetSize_Horz(label));
                }
                else if (node is BevTree.Action)
                {
                    return(m_actionStyle.GetSize_Horz(label));
                }
            }

            return(new Vector2(180, 40));
        }
 /// <summary>
 /// Inverts the child node result.
 /// </summary>
 /// <param name="child">The child node</param>
 public BehaviourInverter(BehaviourNode child) : base("Inverter", NodeType.DECORATOR)
 {
     AddChild(child);
     OnStarted.AddListener(OnStarted_Listener);
     OnStopping.AddListener(OnStopping_Listener);
     OnChildNodeStopped.AddListener(OnChildNodeStopped_Listener);
 }
Example #8
0
        public static GenericMenu CreateServiceContextMenu(BehaviourNode targetNode, int serviceIndex)
        {
            GenericMenu menu = new GenericMenu();

            menu.AddItem(new GUIContent("Move Up"), false, () =>
            {
                if (serviceIndex > 0)
                {
                    var temp = targetNode.Services[serviceIndex];
                    targetNode.Services[serviceIndex]     = targetNode.Services[serviceIndex - 1];
                    targetNode.Services[serviceIndex - 1] = temp;
                }
            });

            menu.AddItem(new GUIContent("Move Down"), false, () =>
            {
                if (serviceIndex < targetNode.Services.Count - 1)
                {
                    var temp = targetNode.Services[serviceIndex];
                    targetNode.Services[serviceIndex]     = targetNode.Services[serviceIndex + 1];
                    targetNode.Services[serviceIndex + 1] = temp;
                }
            });

            menu.AddSeparator("");
            menu.AddItem(new GUIContent("Remove"), false, () =>
            {
                targetNode.Services.RemoveAt(serviceIndex);
            });

            return(menu);
        }
Example #9
0
    //ramped half-and-half: grow method

    public BehaviourNode innerGrowTree(int maxDepth, List <System.Type> Functions, List <System.Type> terminals, bool isTerminal)
    {
        if (maxDepth < 0)
        {
            return(null);
        }

        if (maxDepth == 0)
        {
            isTerminal = true;
        }
        int nextNode                  = UnityEngine.Random.Range(0, (isTerminal == true? terminals.Count : Functions.Count));
        List <BehaviourNode> l        = new List <BehaviourNode>();
        BehaviourNode        rootNode = (BehaviourNode)System.Activator.CreateInstance(isTerminal == true? terminals[nextNode] : Functions[nextNode]);

        if (!isTerminal)
        {
            int numberOfBranches = ((IFunction)rootNode).parameters;
            for (int i = 0; i < Mathf.Max(numberOfBranches, 2); i++)
            {
                bool isTerm = UnityEngine.Random.Range(0, 100) > depthIncreaseProb;
                l.Add(innerGrowTree(maxDepth - 1, Functions, terminals, isTerm));
            }
        }
        rootNode.setNextNodes(l);
        return(rootNode);
    }
        private void onNodeSelectedForLinking(BehaviourNode node)
        {
            serializedObject.Update();

            var  refInter       = node as Interruptable;
            bool bAlreadyLinked = _interruptor.linkedInterruptables.Contains(refInter);

            // Works as a toggle, if already linked then unlink.
            if (bAlreadyLinked)
            {
                _interruptor.linkedInterruptables.Remove(refInter);
            }

            // If unlinked, then link.
            else
            {
                _interruptor.linkedInterruptables.Add(refInter);
            }

            serializedObject.ApplyModifiedProperties();

            // Update the referenced nodes in the editor.
            var refs = _interruptor.GetReferencedNodes();

            parentWindow.editor.SetReferencedNodes(refs);
        }
Example #11
0
    public void EvaluateTree()
    {
        if (companion == null)
        {
            companion = GetComponent <Companion>();
        }
        BehaviourNode currentNode = rootNode.childNode;

        while (currentNode is ControlNode)
        {
            ControlNode c = currentNode as ControlNode;

            MethodInfo method = this.GetType().GetMethod(c.methodName);
            bool       result = (bool)method.Invoke(this, null);

            if (result)
            {
                currentNode = c.positive;
            }
            else
            {
                currentNode = c.negative;
            }
        }
        if (currentNode is ExecutionNode)
        {
            ExecutionNode e = currentNode as ExecutionNode;

            if (e.methodName != current)
            {
                Invoke(e.methodName, 0);
                current = e.methodName;
            }
        }
    }
        private void OnClickAddNode(Vector2 mousePosition)
        {
            var behaviourNode = BehaviourNode.CreateActionBehaviourNode();

            _target.AddBehaviour(behaviourNode);
            CreateNode(mousePosition, behaviourNode);
        }
Example #13
0
        public BTEditorGraphNode OnInsertChild(int index, BehaviourNode node)
        {
            if (node != null && ((m_node is Composite) || (m_node is Decorator)))
            {
                BTEditorGraphNode graphNode = null;

                if (m_node is Composite)
                {
                    Composite composite = m_node as Composite;
                    composite.InsertChild(index, node);

                    graphNode = BTEditorGraphNode.CreateExistingNode(this, node);
                    m_children.Insert(index, graphNode);
                }
                else if (m_node is Decorator)
                {
                    Decorator decorator = m_node as Decorator;

                    DestroyChildren();
                    decorator.SetChild(node);

                    graphNode = BTEditorGraphNode.CreateExistingNode(this, node);
                    m_children.Add(graphNode);
                }

                BTEditorCanvas.Current.RecalculateSize(node.Position);
                return(graphNode);
            }

            return(null);
        }
        private void OnClickAddCoumpoudNode(Vector2 mousePosition)
        {
            var behaviourNode = BehaviourNode.CreateCompoundBehaviourNode();

            _target.AddBehaviour(behaviourNode);
            CreateCompoundNode(mousePosition, behaviourNode);
        }
Example #15
0
 private void OnChildNodeStopped_Listener(BehaviourNode child, bool success)
 {
     OnChildNodeStopped_Common(child, success);
     // OnStopped.Invoke(success);
     //StopNode(success);
     StopNodeOnNextTick(success);
 }
Example #16
0
//    double crossoverRate = 0.9;


    public override List <BotBehavior> crossOver(List <BotBehavior> individuals, int populationGoalSize)
    {
        int numberOfCrossovers      = populationGoalSize;   //(int)Mathf.Floor(individuals.Count * (float)crossoverRate);
        List <BotBehavior> children = new List <BotBehavior> ();

        for (int i = numberOfCrossovers / 2; i > 0; i--)
        {
            int parentx = UnityEngine.Random.Range(0, individuals.Count);
            int parenty = UnityEngine.Random.Range(0, individuals.Count);

            BotBehavior p1 = BotBehavior.deepClone <BotBehavior>(individuals[parentx]);
            BotBehavior p2 = BotBehavior.deepClone <BotBehavior>(individuals[parenty]);

            Tuple <BehaviourNode, int> firstPoint = selectNodeOf(p1);
            Tuple <BehaviourNode, int> secPoint   = selectNodeOf(p2);

            //doing the crossover

            //preventing swapping of root nodes --> pointless and undefined
            if (firstPoint.First != null && secPoint.First != null)
            {
                BehaviourNode temp = firstPoint.First.getNextNodes()[firstPoint.Second];
                firstPoint.First.getNextNodes()[firstPoint.Second] = secPoint.First.getNextNodes()[secPoint.Second];
                secPoint.First.getNextNodes()[secPoint.Second]     = temp;
            }


            children.Add(p1);
            children.Add(p2);
        }

        return(children);
    }
Example #17
0
        public static Vector2 GetNodeSize(BehaviourNode node)
        {
            string label = string.IsNullOrEmpty(node.Name) ? node.Title : node.Name;

            if (node != null)
            {
                if (node is NodeGroup)
                {
                    return(m_nodeGroupStyle.GetSize(label, TreeLayout));
                }
                else if (node is Composite)
                {
                    return(m_compositeStyle.GetSize(label, TreeLayout));
                }
                else if (node is Decorator || node is NodeGroup)
                {
                    return(m_decoratorStyle.GetSize(label, TreeLayout));
                }
                else if (node is Brainiac.Action)
                {
                    return(m_actionStyle.GetSize(label, TreeLayout));
                }
            }

            return(new Vector2(180, 40));
        }
	// Use this for initialization
	public override void Start () {
		base.Start ();
		if (NV != null&& NV.node is BehaviourNode) {
			BNode = (BehaviourNode)NV.node;
		}

	}
Example #19
0
        private void SetExistingNode(BehaviourNode node)
        {
            DestroyChildren();

            m_node       = node;
            m_isSelected = false;

            if (node is Composite)
            {
                Composite composite = node as Composite;
                for (int i = 0; i < composite.ChildCount; i++)
                {
                    BehaviourNode     childNode = composite.GetChild(i);
                    BTEditorGraphNode graphNode = BTEditorGraphNode.CreateExistingNode(this, childNode);
                    m_children.Add(graphNode);
                }
            }
            else if (node is Decorator)
            {
                Decorator     decorator = node as Decorator;
                BehaviourNode childNode = decorator.GetChild();
                if (childNode != null)
                {
                    BTEditorGraphNode graphNode = BTEditorGraphNode.CreateExistingNode(this, childNode);
                    m_children.Add(graphNode);
                }
            }
        }
Example #20
0
        public static Vector2 GetNodeSize(BehaviourNode node)
        {
            return(GetNodeSize_Horz(node));

            /*string label = node.Title;
             *
             * if(node != null)
             * {
             *      if(node is NodeGroup)
             *      {
             *              return m_nodeGroupStyle.GetSize(label, TreeLayout);
             *      }
             *      else if(node is Composite)
             *      {
             *              return m_compositeStyle.GetSize(label, TreeLayout);
             *      }
             *      else if(node is Decorator || node is NodeGroup)
             *      {
             *              return m_decoratorStyle.GetSize(label, TreeLayout);
             *      }
             *      else if(node is BevTree.Action)
             *      {
             *              return m_actionStyle.GetSize(label, TreeLayout);
             *      }
             * }
             *
             * return new Vector2(180, 40);*/
        }
        /// <summary>
        /// Create a node from an existing behaviour.
        /// </summary>
        /// <param name="behaviour"></param>
        /// <returns></returns>
        public BonsaiNode CreateNode(BehaviourNode behaviour)
        {
            var node = CreateEditorNode(behaviour.GetType());

            node.Behaviour = behaviour;
            return(node);
        }
Example #22
0
 void Start()
 {
     // Create a copy of the behaviour tree so we can indivudually set values
     behaviourTree = (BehaviourTree)behaviourTree.Copy();
     XNode.Node entry = ((BehaviourTree)behaviourTree.Copy()).FindEntryNode();
     behaviourTreeRoot = (BehaviourNode)entry.GetOutputPort("child").GetConnection(0).node;
     behaviourTreeRoot.Reset();
 }
Example #23
0
    /// <summary>
    /// Restarts the AI
    /// </summary>
    public void Restart()
    {
        Pause();

        currentNode = null;

        Resume();
    }
Example #24
0
 private void OnChildNodeStoppedSilent_Listener(BehaviourNode child, bool success)
 {
     if (success &&
         !(State == NodeState.STOPPING || !m_isConditionMetFunc()))
     {
         m_restartChildTimer = StartFirstChildNodeOnNextTick();
     }
 }
Example #25
0
 public Node(NodeBasedEditor editor, BehaviourNode behaviourNode, Vector2 position)
 {
     Editor        = editor;
     BehaviourNode = behaviourNode;
     Rect          = new Rect(position.x - defaultWidth / 2f, position.y, defaultWidth, defaultHeight);
     InPoint       = new ConnectionPoint(this, ConnectionPointType.In, Editor.InPointStyle, Editor.OnClickInPoint,
                                         null, null);
 }
 private void OnChildNodeStoppedSilent_Listener(BehaviourNode child, bool success)
 {
     if (success &&
         !(State == NodeState.STOPPING || (TotalLoops >= 0 && ++LoopCount >= TotalLoops)))
     {
         _restartChildTimer = AddTimer(0, 0, 0, RestartChild);
     }
 }
Example #27
0
        /*
         * public override bool RequestStopNode(bool silent = false){
         *  if(base.RequestStopNode(silent)){
         *      if(!silent){
         *          Children[0].StartNode();
         *      }
         *      return true;
         *  }
         *  return false;
         * }
         */

        private void OnChildNodeStopped_Common(BehaviourNode child, bool success)
        {
            if ((Parent.Type == NodeType.COMPOSITE && Parent.State != NodeState.ACTIVE) ||
                m_abortRule == AbortRule.NONE || m_abortRule == AbortRule.SELF)
            {
                StopActivelyObserving();
            }
        }
        private BonsaiNode ReconstructEditorNode(BehaviourNode behaviour)
        {
            BonsaiNode node = CreateNode(behaviour);

            node.Behaviour = behaviour;
            node.Position  = behaviour.bonsaiNodePosition;
            return(node);
        }
Example #29
0
        private void AddNodeCallback(object type, Vector2 mousePosition)
        {
            BehaviourNode node = (BehaviourNode)AddNode((Type)type);

            node.Position = (mousePosition - dragging_Position) - (node.GetDiamentions() * 0.5f);

            Repaint();
        }
Example #30
0
        public static GenericMenu CreateNodeInspectorContextMenu(BehaviourNode targetNode)
        {
            GenericMenu menu = new GenericMenu();

            BTConstraintFactory.AddConstraint(menu, targetNode);
            BTServiceFactory.AddService(menu, targetNode);

            return(menu);
        }
Example #31
0
 public void SetReferenced(BehaviourNode node)
 {
     referencedNodes.Clear();
     BehaviourNode[] refs = node.GetReferencedNodes();
     if (refs != null && refs.Length != 0)
     {
         referencedNodes.AddRange(refs);
     }
 }
Example #32
0
	private void loaded(LevelLoader obj){
		//obj.DontDelete = true;
		/*foreach(EmptyObjectIdentifier eoi in obj.rootObject.GetAllComponentsInChildren<EmptyObjectIdentifier>()){
			GameObject.Destroy(eoi);
		}*/
		GameObject go = (GameObject)GameObject.Instantiate (obj.rootObject);
		//obj.rootObject.SetActive (false);
		TreeRoot = go.GetComponent<BehaviourNode> ();
		TreeRoot.Tree = this;
		TreeRoot.ReCaptureChildsAndParents ();
	}
	// Update is called once per frame
	public override void Update () {
		base.Update ();
		if (Node == null) {
			if (NV != null&& NV.node is BehaviourNode) {
				BNode = (BehaviourNode)NV.node;
			}		
		}

		if (addTestClass) {
			addTestClass = false;
			AddNode(ClassName);
		}
	}
Example #34
0
            public bool AddChildNode(BehaviourNode childNode)
            {
                if(childNode == null)
                {
                    return false;
                }
                if(!this.IsLegalChildNodeIndex(this.numChildren))
                {
                    return false;
                }

                this.children[this.numChildren] = childNode;
                ++this.numChildren;

                return true;
            }
Example #35
0
	public virtual void LoadTree(string FileName){
		if (FileName.Length == 0)
			return;

		if (TreeRoot != null) {
			GameObject.DestroyImmediate (TreeRoot.gameObject);
			TreeRoot=null;
		}
		
		LevelSerializer.LoadObjectTreeFromFile(FileName,loaded);
		lastLoadedTree = FileName;
		TreeSaveManager.getTreeSaveManager ().AddObserver (FileName, this);

		//LevelSerializer.Collect ();
		//LevelSerializer.LoadObjectTreeFromFile("Pah.dat");
	}
	public void onChange(string value){
		if(!isEnabled) return;
		if(value.Equals("None")){
			EnableStuff();
			if(oldTree != null){
				oldTree.ReCaptureChildsAndParents();
				bteh.VisTree(oldTree);
				oldTree = null;
			}

			if(bteh.TreeRoot == null && TreeVis.getTreeVis().TreeRoot != null){
				TreeVis.getTreeVis().DestroyTree();
				TreeVis.getTreeVis().TreeRoot = null;
			}
		}else{
			DisableStuff();
			oldTree = bteh.TreeRoot;
			GameObject go = GameObject.Find(value);
			bool failed = false;
			if(go != null){
				BehaviourTree tree = go.GetComponent<BehaviourTree>();
				if(tree != null && tree.TreeRoot != null){
					bteh.VisTree(tree.TreeRoot);
				} else { failed = true;}
			}else { failed = true;}

			if(failed){
				oldTree = null;
				EnableStuff();
			}
		}
	}
	public void VisTree(BehaviourNode treeRoot){
		TreeVis.getTreeVis ().DestroyTree ();
		TreeVis.getTreeVis ().TreeRoot = treeRoot;
		TreeVis.getTreeVis ().LoadTree ();
	}