Full text
BhTSL, Behavior Trees Specification and Processing Miguel Oliveira Centro Algoritmi (CAlg-CTC), Department of Informatics, University of Minho, Braga, Portugal [email protected] Pedro Mimoso Silva Centro Algoritmi (CAlg-CTC), Department of Informatics, University of Minho, Braga, Portugal p[email protected] Pedro Moura Centro Algoritmi (CAlg-CTC), Department of Informatics, University of Minho, Braga, Portugal p[email protected] José João Almeida Centro Algoritmi (CAlg-CTC), Department of Informatics, University of Minho, Braga, Portugal [email protected] Pedro Rangel Henriques Centro Algoritmi (CAlg-CTC), Department of Informatics, University of Minho, Braga, Portugal p[email protected] Abstract In the context of game development, there is always the need for describing behaviors for various entities, whether NPCs or even the world itself. That need requires a formalism to describe properly such behaviors. As the gaming industry has been growing, many approaches were proposed. First, finite state machines were used and evolved to hierarchical state machines. As that formalism was not enough, a more powerful concept appeared. Instead of using states for describing behaviors, people started to use tasks. This concept was incorporated in behavior trees. This paper focuses in the specification and processing of Behavior Trees. A DSL designed for that purpose will be introduced. It will also be discussed a generator that produces L A T E X diagrams to document the trees, and a Python module to implement the behavior described. Additionally, a simulator will be presented. These achievements will be illustrated using a concrete game as a case study. 2012 ACM Subject Classification Theory of computation →Tree languages Keywords and phrases Game development, Behavior trees (BT), NPC, DSL, Code generation Digital Object Identifier 10.4230/OASIcs.SLATE.2020.4 Funding This work has been supported by FCT–Fundação para a Ciência e Tecnologia within the R&D Units Project Scope: UIDB/00319/2020. 1 Introduction At some point in the video-game history, NPCs (Non-Playable Characters) were introduced. With them came the need to describe behaviors. And with these behaviors came the need of the existence of a formalism so that they can be properly specified. As time passed by, various approaches were proposed and used, like finite and hierarchical state machines. These are state-based behaviors, that is, the behaviors are described through states. Altough this is a clear and simplistic way to represent and visualize small behaviors, it becomes unsustainable when dealing with bigger and more complex behaviors. Some time later, a new and more powerful concept was introduced: using tasks instead of states to describe behaviors. This concept is incorporated in what we call behavior trees. ©Miguel Oliveira, Pedro Mimoso Silva, Pedro Moura, José João Almeida, and Pedro Rangel Henriques; licensed under Creative Commons License CC-BY 9th Symposium on Languages, Applications and Technologies (SLATE 2020). Editors: Alberto Simões, Pedro Rangel Henriques, and Ricardo Queirós; Article No. 4; pp. 4:1–4:13 OpenAccess Series in Informatics Schloss Dagstuhl – Leibniz-Zentrum für Informatik, Dagstuhl Publishing, Germany
4:2 BhTSL, Behavior Trees Behavior Trees ( BT for short) were first used in the videogame industry in the development of the game Halo 2, released in 2004 [ 5 ]. The idea is that people create a complex behavior by only programming actions (or tasks) and then design a tree structure whose leaf nodes are actions and the inner nodes determine the NPC’s decision making. Not only these provide an easy and intuitive way of visualizing and designing behaviors, they also provide a good way to work with scalability through modularity, solving the biggest issue from state-based design. Since then, multiple gaming companies adopted this concept and, in recent years, behavior trees are also being used in different areas like Artificial Inteligence and Robotics. In this context, we felt that it could be useful to have a DSL to specify BTs independently of application area and the programming language chosen for the implementation. The language must be compact and easy to use but it should be expressive enough to be applied to real situations. In that sense a new kind of node was included, as will be described. This paper will introduce the DSL designed and the compiler implemented to translate it to a programming language, in this case Python. Additionally, the compiler also generates L A T EX diagrams to produce graphical documentation for each BT specified. A small example will be described in our language as a case study to illustrate all the achievements attained. The paper is organized as follow: Concepts and State of the Art frameworks are presented in Section 2. Architecture and language specification are proposed in Section 3. Compiler development is discussed in Section 4. An illustrative case study is presented in Section 5, before concluding the paper in Section 6. The paper also includes one appendix that contains the tokens table. 2 Concepts This section will be built based on references [1, 4, 3]. Formally, a BT is a tree whose internal nodes are called control flow nodes and leafs are called execution nodes. A behavior tree executes by peridiocally sending ticks to its children, in order to traverse the entire tree. Each node, upon a tick call, returns one of the following three states to its parent: SUCCESS if the node was executed with success; FAILURE if the execution failed; or RUNNING if it could not finish the execution by the end of the tick. In the last case, the next tick will traverse the tree until it reaches the running execution node, and will try again to run it. 2.1 Control Flow Nodes Control flow nodes are structural nodes, that is, they do not have any impact in the state of the system. They only control the way the subsequent tree is traversed. In the classical formulation, there are 4 types of control flow nodes: Sequence , Selector , Parallel and Decorator . Even if not standard we use decorators as control flow nodes, according to [ 1 ]. A sequence node (figure 1a) visits its children in order, starting with the first, and advancing for the next one if the previous succeeded. Returns: SUCCESS – if all children succeed; FAILURE – if a child fails; RUNNING – if a child returns RUNNING.
M. Oliveira, P. M. Silva, P. Moura, J. J. Almeida, and P. R. Henriques 4:3 Like the sequence, the selector node (figure 1c) also visits its children in order, but it only advances if the child that is being executed returns FAILURE. Returns: SUCCESS – if a child succeeds; FAILURE – if all children fails; RUNNING – if a child returns RUNNING. A parallel node (figure 1e), as the name implies, visits its children in parallel. Additionally, it has a parameter Mthat acts as a success rate. For Nchildren and M≤N, it returns: SUCCESS – if Mchildren succeed; FAILURE – if N−M+ 1 children fail; RUNNING – otherwise. A decorator (figure 1b) is a special node that has an only one child, and uses a policy (set of rules) to manipulate the return status of its child, or the way it ticks it. Some examples of decorator nodes are: 1. Inverter – inverts the SUCCESS/FAILURE return status of the child; 2. Max-N-Times – the child can only fail N times. After that it only returns FAILURE without ticking the child. 2.2 Execution Nodes Execution nodes are the simplest, yet the most powerful. They are the ones that have access to the state of the system, and can update it. There are two types of execution nodes: Action and Condition. Upon the execution of a tick, an action node (figure 1d) runs a chunk of code that can return either SUCCESS,FAILURE or RUNNING. The condition node (figure 1f) verifies a proposition, returning SUCCESS / FAILURE if the proposition is/is not valid. This node never returns RUNNING. 2.3 Control Flow Nodes with memory Sometimes, when a node returns RUNNING , we want it to remember which nodes he already executed, so that the next tick does not execute them again. We call this nodes with memory. And they are represented by adding a _∗ to the symbols mentioned previously. This is only syntactic sugar because we can also represent these nodes with a non-memory BT, but that will not be discussed here. Please note that, while we avoid the re-execution of nodes with this type of node, we also lose the reactivity that this re-execution provides. 2.4 State of The Art In the gaming industry there is some interesting projects that use tools based on Behavior trees as the main focus to describe NPCs behaviors. Unreal Engine [ 2 ] and Unity 1 are two examples of major game engines that use them. In their case, instead of a language, they offer a graphical user interface (GUI) to specify the BTs, through a drag and drop tactic. Upon the creation of an execution node, the programmer needs to specify the action or condition that will be executed. The nodes mentioned before are all implemented in these engines, along with some extensions. All the nodes that were mentioned before are implemented in both of these engines, along with some extensions. 1https://unity.com SLATE 2020
4:4 BhTSL, Behavior Trees → Child 1 ... Child N (a) Sequence node. δ Child (b) Decorator with policy δ. ? Child 1 ... Child N (c) Selector node. Action (d) Action node. ⇒M Child 1 ... Child N (e) Parallel node. Condition (f) Condition node. Figure 1 BT Nodes structure. In addition to game engines, there are also frameworks like Java Behavior Trees 2 for Java and Owyl3for Python that implement BTs. In this case, they work as a normal library. 3 Architecture and Specification In this section, it will be explained the general architecture of our system to process BTs, that is depicted in Figure 2. After introducing its modules, one subsection is devoted to the BhTSL domain specific language design. Figure 2 System Architecture. 2https://github.com/gaia-ucm/jbt 3https://github.com/eykd/owyl
M. Oliveira, P. M. Silva, P. Moura, J. J. Almeida, and P. R. Henriques 4:5 The input for our system, DSL - Specification , is a text file describing the behavior which should follow the language syntax. The compiler, which is represented as the green rounded rectangle in the diagram of Figure 2, is composed of the following modules: a Lexer , aParser and a Code Generator. This generator has two sub-generators. The Latex Generator , that is responsible for the generation of the L A T E X code to draw the tree diagram representing the behavior specified. And the Python Generator , that produces the fragment of Python code that implements the desired behavior according to a template predefined by us in the context of this project; that code fragment can be later imported by any Python application that aims to. 3.1 BhTSL Before we start describing the DSL, we will introduce a new node, called Probability Selector (Figure 3 depicts that concept), that provides us with a relevant extension to the standard formalism for a more powerful behavior specification. This extension improves the expressiveness of BhTSL language. A probability selector node is like a normal selector node, but instead of visiting its children from left to right, it visits them randomly, taking into account that each child has a probability, defined by the user, of being chosen first. ?P Child 1 Child 2 ... Child N P1 P2 PN Figure 3 Probability Selector node. Example Now that all nodes have been introduced, let us see an example of a specific behavior. Suppose that in some game, called TGame , it is intended to have a guard that patrols a house. The guard has the following behavior: while he is patrolling, if he sees the player, activates an alarm and then, depending on the level of courage he has, decides (based on probabilities) whether he runs away or fights the player. In case of running away, he constantly checks if he still sees the player, returning to patrolling in case he does not. If he still sees it, he keeps running. The same thing happens when he chooses to fight the player, only this time he checks if the player is already dead or not. In Figure 4, we can see a possible tree specification for this behavior. 3.1.1 Syntax In our language, each specification represents one and only one behavior. An input file, containing the behavior specification text, is divided into 3 components: Behavior – main behavior tree; Definitions (optional) – node definitions that can be referenced in other nodes or in the main BT; Code – Python block that contains the code fragments described the execution nodes, and other code that the programmer wishes to add. SLATE 2020
4:6 BhTSL, Behavior Trees ∅ ? →∗ sees player activate alarm ?∗ P → I player dead fight player → sees player run patrol e1 e2 Figure 4 Example: TGame behavior tree diagram automatically generated by our tool. To illustrate our idea about the DSL we plan to design (formally defined by a grammar in Section 4), we present below an example of a specification written in the intended language. behavior : [ sequence : [ condition : $cond1 , condition : $cond2 memory selector : [ parallel : $par1 , prob_selector : $prob1 ] ] ] parallel par1 : 10 [ action : $action1 , action : $action2 ] prob_selector prob1 : [
M. Oliveira, P. M. Silva, P. Moura, J. J. Almeida, and P. R. Henriques 4:7 $e1 -> decoraror : INVERTER [ action : $action1 ], $e2 -> action : $action2 ] %% def action1 ( entity ): pass def action2 ( entity ): pass def cond1 ( entity ): pass def cond2 ( entity ): pass def e1( entity ): pass def e2( entity ): pass 4 Tool development In the next subsection the implementation of the BhTSL processor will be detailed, as well as the language specification will be presented. 4.1 Lexical analysis The first step in the development of a compiler is the lexical analysis, that converts a char sequence into a token sequence. The tokens table can be seen in Appendix A. 4.2 Syntatic analysis Syntatic analysis, or parsing, it the process of analyzing a string of symbols conforming the rules of a grammar. Below we list the context free grammar that formally specifies BhTSL syntax: root : behavior CODE | behavior definitions CODE | definition behavior CODE behavior : BEHAVIOR ’:’ ’[’ node ’]’ node : SEQUENCE ’:’ ’[’ nodes ’]’ | SEQUENCE ’:’ VAR | MEMORY SEQUENCE ’:’ ’[’ nodes ’]’ | MEMORY SEQUENCE ’:’ VAR | SELECTOR ’:’ ’[’ nodes ’]’ SLATE 2020
4:8 BhTSL, Behavior Trees | SELECTOR ’:’ VAR | MEMORY SELECTOR ’:’ ’[’ nodes ’]’ | MEMORY SELECTOR ’:’ VAR | PROBSELECTOR ’:’ ’[’ prob_nodes ’]’ | PROBSELECTOR ’:’ VAR | MEMORY PROBSELECTOR ’:’ ’[’ prob_nodes ’]’ | MEMORY PROBSELECTOR ’:’ VAR | PARALLEL ’:’ INT ’[’ nodes ’]’ | PARALLEL ’:’ VAR | DECORATOR ’:’ INVERTER ’[’ node ’]’ | DECORATOR ’:’ VAR | CONDITION ’:’ VAR | ACTION ’:’ VAR nodes : nodes ’,’ node | node prob_nodes : prob_nodes ’,’ prob_node | prob_node prob_node : VAR RIGHTARROW node definitions : definitions definition | definition definition : SEQUENCE NODENAME ’:’ ’[’ nodes ’]’ | SELECTOR NODENAME ’:’ ’[’ nodes ’]’ | PROBSELECTOR NODENAME ’:’ ’[’ prob_nodes ’]’ | PARALLEL NODENAME ’:’ INT ’[’ nodes ’]’ | DECORATOR NODENAME ’:’ INVERTER ’[’ node ’]’ 4.3 Semantic analysis As usual, from a static semantics perspective, the compiler will check the source text for non-declared variables and variable redeclaration. A variable can only be accessed if it is declared, either in the definitions section (if it represents a control flow node), or in the code section (execution node). Additionally, a variable can only be declared once, to avoid ambiguity in the memory access by the processor. The dynamic semantics is discussed in the next subsection. 4.4 Code generator The compiler can generate two different outputs: a L A T E X file, that contains the L A T E X commands to draw a diagram for the BT specified; and a Python file, that contains the functions that implement the specified behavior. The Python file is built using a Template file which contains markers that the Code Generator will fill with the processed data. This file also contains the class Simulator which is capable of executing the processed BT. Due to the lack of time available, we have only been able to generate Python code, but we hope to be able to compile into different languages in the future.
M. Oliveira, P. M. Silva, P. Moura, J. J. Almeida, and P. R. Henriques 4:9 4.5 BT Simulator In order to test the Python code generated and to help the BT specifier to debug the behavior he is willing to describe, we also developed an interpreter that imports the Python behavior file and simulates its execution. This additional tool proved to be useful. 4.6 Implementation The project was developed using Python . We chose this language due to our previous experience with it, but also due to its simplicity, flexibility and its cutting edge technology; it is also relevant to be a reflective language. To automatically generate the compiler from the tokens and grammar specifications, we used the PLY (Python Lex-Yacc)4 library, which is an implementation of the lex and yacc lexer and parser generator tools for Python. We chose to use PLY because we had prior experience with Lex-Yacc which enabled us to save time to implement the project. Moreover, we realized that the specification is lighter than an equivalent using attribute grammars and because the code produced by those generators is really efficient. To implement the Code Generator module, we resorted to the well-known tree-traversal approach, that upon visiting every node of the parsed tree, produces the corresponding output. For that purpose, some standard libraries were used. Additionally, we created a L A T E X library, behaviortrees.sty , to draw the trees specified. This library is used in the L A T EX generator. 5 Case Study In order to test our tool, we designed a simple game that consists of an entity finding and grabbing a ball in a generated map. This entity has a range of vision that it is used to search the ball. When the entity finds it, it approaches the ball and, if it is within reach, grabs it. The following code is an example of a specification for this behavior in our DSL, and Figure 5 depicts the behavior tree automatically generated by our tool. behavior : [ selector : [ memory sequence : $seq1 , action : $search_ball ] ] sequence seq1 : [ condition : $ball_found , selector : [ sequence : [ condition : $ball_within_reach , action : $grab_ball ], action : $approach_ball ] ] 4https://www.dabeaz.com/ply/ SLATE 2020