### Install Mistreevous via NPM Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Command to install the Mistreevous package into your project dependencies. ```shell npm install --save mistreevous ``` -------------------------------- ### MDSL and JSON for Action Node with Until Guard and Numeric Argument Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Provides examples in MDSL and JSON for an action node using an 'until' guard with a numeric argument. This allows an action to proceed only after a specific condition involving a number is met. ```MDSL root { action [Gamble] until(HasGold, 1000) } ``` ```JSON { "type": "root", "child": { "type": "action", "call": "Gamble", "until": { "call": "HasGold", "args": [ 1000 ] } } } ``` -------------------------------- ### Sequence Node Example Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Demonstrates the Sequence composite node, which executes child nodes in order. It succeeds only if all children succeed and fails if any child fails. The MDSL and JSON representations show a basic sequence of actions. ```MDSL root { sequence { action [Walk] action [Fall] action [Laugh] } } ``` ```json { "type": "root", "child": { "type": "sequence", "children": [ { "type": "action", "call": "Walk" }, { "type": "action", "call": "Fall" }, { "type": "action", "call": "Laugh" } ] } } ``` -------------------------------- ### Define Branch Nodes and Named Roots in Javascript Source: https://context7.com/nikkorn/mistreevous/llms.txt Demonstrates how to define a behaviour tree with multiple root nodes and branch nodes that reference other named root nodes. This allows for modular and reusable behaviour definitions. The example shows a main 'root' that branches to 'FindFood', 'Rest', or 'Explore' subtrees, each with its own logic. ```javascript import { BehaviourTree, State } from "mistreevous"; // Multiple root nodes with branches const definition = ` root { selector { sequence { condition [IsHungry] branch [FindFood] } sequence { condition [IsTired] branch [Rest] } branch [Explore] } } root [FindFood] { sequence { action [LocateFood] action [MoveToFood] action [Eat] } } root [Rest] { sequence { action [FindSafeSpot] action [Sleep] } } root [Explore] { repeat [3] { action [Wander] } } `; const agent = { IsHungry: () => true, IsTired: () => false, LocateFood: () => { console.log("Found food!"); return State.SUCCEEDED; }, MoveToFood: () => { console.log("Moving to food"); return State.SUCCEEDED; }, Eat: () => { console.log("Eating"); return State.SUCCEEDED; }, FindSafeSpot: () => State.SUCCEEDED, Sleep: () => State.SUCCEEDED, Wander: () => State.SUCCEEDED }; const tree = new BehaviourTree(definition, agent); tree.step(); ``` -------------------------------- ### Selector Node Example Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Illustrates the Selector composite node, which executes child nodes in order until one succeeds. It fails only if all children fail and succeeds if any child succeeds. The MDSL and JSON examples show a selector with multiple action nodes. ```MDSL root { selector { action [TryThis] action [ThenTryThis] action [TryThisLast] } } ``` ```json { "type": "root", "child": { "type": "selector", "children": [ { "type": "action", "call": "TryThis" }, { "type": "action", "call": "ThenTryThis" }, { "type": "action", "call": "TryThisLast" } ] } } ``` -------------------------------- ### Mistreevous Callbacks: Entry, Exit, Step Source: https://context7.com/nikkorn/mistreevous/llms.txt Illustrates the use of lifecycle callbacks in Mistreevous behaviour trees. Entry callbacks are invoked when a node starts, exit callbacks when it completes or aborts, and step callbacks on every update. These allow for custom logic execution at different stages of a node's lifecycle. ```javascript import { BehaviourTree, State } from "mistreevous"; const definition = `root { sequence entry(OnSequenceStart) exit(OnSequenceEnd) step(OnSequenceStep) { action [GatherWood] entry(OnGatherStart) exit(OnGatherEnd) action [BuildFire] } }`; const agent = { OnSequenceStart: () => console.log("Starting sequence..."), OnSequenceEnd: (result) => console.log(`Sequence ended. Success: ${result.succeeded}, Aborted: ${result.aborted}`), OnSequenceStep: () => console.log("Sequence step"), OnGatherStart: () => console.log("Starting to gather wood..."), OnGatherEnd: (result) => console.log(`Gathering complete. Success: ${result.succeeded}`), GatherWood: () => State.SUCCEEDED, BuildFire: () => State.SUCCEEDED }; const tree = new BehaviourTree(definition, agent); tree.step(); // Output: // Starting sequence... // Sequence step // Starting to gather wood... // Gathering complete. Success: true // Sequence ended. Success: true, Aborted: false ``` -------------------------------- ### Define Condition Nodes with Arguments Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Pass parameters to condition functions to perform dynamic checks. This example shows how to pass a string argument to an inventory check function. ```MDSL root { sequence { condition [HasItem, "potion"] } } ``` ```JSON { "type": "root", "child": { "type": "sequence", "children": [ { "type": "condition", "call": "HasItem", "args": ["potion"] } ] } } ``` ```JavaScript const agent = { HasItem: (itemName) => this.inventory.includes(itemName) }; ``` -------------------------------- ### Mistreevous Exit Callback Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Illustrates the use of an 'exit' callback in MDSL, which is invoked when a node succeeds, fails, or is aborted. The example includes the JSON representation. ```MDSL root { sequence entry(StartWalkingAnimation) exit(StopWalkingAnimation) { action [WalkNorthOneSpace] action [WalkEastOneSpace] action [WalkSouthOneSpace] action [WalkWestOneSpace] } } ``` ```JSON { "type": "root", "child": { "type": "sequence", "entry": { "call": "StartWalkingAnimation" }, "exit": { "call": "StopWalkingAnimation" }, "children": [ { "type": "action", "call": "WalkNorthOneSpace" }, { "type": "action", "call": "WalkEastOneSpace" }, { "type": "action", "call": "WalkSouthOneSpace" }, { "type": "action", "call": "WalkWestOneSpace" } ] } } ``` -------------------------------- ### Repeat Node with Fixed Iterations (MDSL & JSON) Source: https://github.com/nikkorn/mistreevous/blob/master/README.md The Repeat decorator node executes its child node repeatedly until a maximum iteration count is met or the child fails. This example shows setting a fixed number of iterations. ```MDSL root { repeat [5] { action [SomeAction] } } ``` ```JSON { "type": "root", "child": { "type": "repeat", "iterations": 5, "child": { "type": "action", "call": "SomeAction" } } } ``` -------------------------------- ### Define and Execute a Behaviour Tree Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Demonstrates how to define a behaviour tree using MDSL, bind it to an agent object with action implementations, and execute the tree using the step method. ```javascript import { State, BehaviourTree } from "mistreevous"; const definition = `root { sequence { action [Walk] action [Fall] action [Laugh] } }`; const agent = { Walk: () => { console.log("walking!"); return State.SUCCEEDED; }, Fall: () => { console.log("falling!"); return State.SUCCEEDED; }, Laugh: () => { console.log("laughing!"); return State.SUCCEEDED; }, }; const behaviourTree = new BehaviourTree(definition, agent); behaviourTree.step(); ``` -------------------------------- ### Register and Use Global Subtrees in JavaScript Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Shows how to register a subtree globally using `BehaviourTree.register` and then reference it from any behavior tree definition using a 'branch' node. This promotes reusability of common behaviors across different agent instances. ```JavaScript /** Register the global subtree for some celebratory behaviour. We can also pass a JSON defintion here. */ BehaviourTree.register("Celebrate", `root { sequence { action [Jump] action [Say, "Yay!"] action [Jump] action [Say, "We did it!"] } }`); /** Define some behaviour for an agent that references our registered 'Celebrate' subtree. */ const definition = `root { sequence { action [AttemptDifficultTask] branch [Celebrate] } }`; /** Create our agent behaviour tree. */ const agentBehaviourTree = new BehaviourTree(definition, agent); ``` -------------------------------- ### Configure BehaviourTree Options in Javascript Source: https://context7.com/nikkorn/mistreevous/llms.txt Demonstrates how to provide an optional configuration object to the `BehaviourTree` constructor. This object allows customization of delta time calculation for nodes like 'wait', the random number generator for deterministic behaviour, and a callback function to monitor node state changes for debugging or visualization purposes. ```javascript import { BehaviourTree, State } from "mistreevous"; const definition = `root { lotto { action [Action1] action [Action2] } }`; const agent = { Action1: () => State.SUCCEEDED, Action2: () => State.SUCCEEDED }; const options = { // Custom delta time for wait nodes (useful in game loops) getDeltaTime: () => { return 1 / 60; // 60 FPS, returns seconds }, // Custom random function for deterministic behavior (seeded RNG) random: () => { // Use a seeded random for reproducible results return 0.3; // Always returns 0.3 for deterministic testing }, // Callback for node state changes (debugging/visualization) onNodeStateChange: (change) => { console.log(`Node ${change.id} (${change.type}) changed from ${change.previousState} to ${change.state}`); } }; const tree = new BehaviourTree(definition, agent, options); tree.step(); // Logs all state transitions as they occur ``` -------------------------------- ### Implement Synchronous Agent Actions Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Shows how to implement an action function in JavaScript that returns a state to control the behavior tree flow. ```JavaScript const agent = { Attack: () => { if (!this.isHoldingWeapon()) { return Mistreevous.State.FAILED; } return Mistreevous.State.SUCCEEDED; }, WalkToPosition: () => { if (this.isAtTargetPosition()) { return Mistreevous.State.SUCCEEDED; } return Mistreevous.State.RUNNING; } }; ``` -------------------------------- ### MDSL and JSON for Action Node with Optional Arguments Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Demonstrates how to define an action node in MDSL and its equivalent in JSON, including passing optional string arguments to the agent callback function. ```MDSL root { action [Walk] entry(OnMovementStart, "walking") } ``` ```JSON { "type": "root", "child": { "type": "action", "call": "Walk", "entry": { "call": "OnMovementStart", "args": [ "walking" ] } } } ``` -------------------------------- ### Initialize BehaviourTree with MDSL or JSON Source: https://context7.com/nikkorn/mistreevous/llms.txt Demonstrates how to instantiate a BehaviourTree using either an MDSL string or a JSON object. The agent object maps tree node identifiers to actual implementation functions. ```typescript import { BehaviourTree, State } from "mistreevous"; const mdslDefinition = `root { sequence { action [Walk] action [Attack] } }`; const agent = { Walk: () => { console.log("Walking..."); return State.SUCCEEDED; }, Attack: () => { console.log("Attacking!"); return State.SUCCEEDED; } }; const tree = new BehaviourTree(mdslDefinition, agent); const jsonDefinition = { type: "root", child: { type: "sequence", children: [ { type: "action", call: "Walk" }, { type: "action", call: "Attack" } ] } }; const treeFromJson = new BehaviourTree(jsonDefinition, agent); ``` -------------------------------- ### Register and Use Global Functions in JavaScript Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Illustrates how to register global functions using `BehaviourTree.register` that can be invoked from any agent tree definition. These global functions receive the invoking agent object as the first argument. Agent instance functions take precedence over global functions with the same name. ```JavaScript /** Register the 'speak' global function that any agent tree can invoke for an action. */ BehaviourTree.register("Speak", (agent, text) => { showInfoToast(`${agent.getName()}: ${text}`); return State.SUCCEEDED; }); /** Register the 'IsSimulationRunning' global function that any agent tree can invoke for a condition. */ BehaviourTree.register("IsSimulationRunning", (agent) => { return simulation.isRunning(); }); /** Define some behaviour for an agent that references our registered functions. */ const definition = `root { sequence { condition [IsSimulationRunning] action [Speak, "I still have work to do"] } }`; /** Create our agent behaviour tree. */ const agentBehaviourTree = new BehaviourTree(definition, agent); ``` -------------------------------- ### Pass Arguments to Action Functions Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Illustrates how to pass arguments to action functions using MDSL, JSON, and how to receive them in a JavaScript function. ```MDSL root { action [Say, "hello world", 5, true] } ``` ```JSON { "type": "root", "child": { "type": "action", "call": "Say", "args": ["hello world", 5, true] } } ``` ```JavaScript const agent = { Say: (dialog, times = 1, sayLoudly = false) => { for (var index = 0; index < times; index++) { showDialog(sayLoudly ? dialog.toUpperCase() + "!!!" : dialog); } return Mistreevous.State.SUCCEEDED; } }; ``` -------------------------------- ### Execute Tree Traversal with step() Source: https://context7.com/nikkorn/mistreevous/llms.txt Shows how to use the step() method to traverse the tree. This method handles state transitions, including long-running tasks that return RUNNING until completion. ```typescript import { BehaviourTree, State } from "mistreevous"; const definition = `root { sequence { action [PrepareWeapon] action [AimAtTarget] action [Fire] } }`; let currentAction = 0; const agent = { PrepareWeapon: () => { console.log("Preparing weapon..."); return State.SUCCEEDED; }, AimAtTarget: () => { console.log("Aiming at target..."); currentAction++; return currentAction >= 3 ? State.SUCCEEDED : State.RUNNING; }, Fire: () => { console.log("Firing!"); return State.SUCCEEDED; } }; const tree = new BehaviourTree(definition, agent); tree.step(); tree.step(); tree.step(); console.log(tree.getState()); ``` -------------------------------- ### MDSL and JSON for Aborting Node with Succeed on Guard Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Shows how to configure a node to succeed upon being aborted by a guard condition in MDSL and JSON. This allows for alternative execution paths when a guard fails. ```MDSL root { sequence { wait until(CanAttack) then succeed action [Attack] } } ``` ```JSON { "type": "root", "child": { "type": "sequence", "children": [ { "type": "wait", "until": { "call": "CanAttack", "succeedOnAbort": true } }, { "type": "action", "call": "Attack" } ] } } ``` -------------------------------- ### step() Method Source: https://context7.com/nikkorn/mistreevous/llms.txt Executes a single update of the behaviour tree, traversing from the root node outwards. Nodes in the RUNNING state will be revisited until they resolve. ```APIDOC ## step() Method ### Description Executes a single update of the behaviour tree, traversing from the root node outwards to child nodes. Nodes in the RUNNING state will be revisited on subsequent steps until they resolve to SUCCEEDED or FAILED. Calling step() on a completed tree automatically resets it before traversal. ### Method `tree.step()` ### Endpoint N/A (Instance method) ### Parameters None ### Request Example ```javascript import { BehaviourTree, State } from "mistreevous"; const definition = `root { sequence { action [PrepareWeapon] action [AimAtTarget] action [Fire] } }`; let currentAction = 0; const agent = { PrepareWeapon: () => { console.log("Preparing weapon..."); return State.SUCCEEDED; }, AimAtTarget: () => { console.log("Aiming at target..."); // Simulate long-running action that takes multiple steps currentAction++; return currentAction >= 3 ? State.SUCCEEDED : State.RUNNING; }, Fire: () => { console.log("Firing!"); return State.SUCCEEDED; } }; const tree = new BehaviourTree(definition, agent); // Step through the tree tree.step(); // PrepareWeapon succeeds, AimAtTarget starts (RUNNING) tree.step(); // AimAtTarget continues (RUNNING) tree.step(); // AimAtTarget succeeds, Fire succeeds console.log(tree.getState()); // State.SUCCEEDED ``` ### Response #### Success Response (200) - **void** - The method does not return a value, but updates the tree's internal state. ``` -------------------------------- ### BehaviourTree Constructor Options Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Configuration options for the BehaviourTree constructor. These include functions for delta time, random number generation, and node state change event handling. Defaults are provided if these functions are not defined. ```javascript const options = { getDeltaTime: () => number, random: () => number, onNodeStateChange: (change: NodeStateChange) => void }; ``` -------------------------------- ### MDSL and JSON for Action Node with While Guard and String Argument Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Shows how to define an action node in MDSL with a 'while' guard that takes a string argument, and its JSON equivalent. This is useful for conditional execution based on agent properties. ```MDSL root { action [Run] while(HasItemEquipped, "running-shoes") } ``` ```JSON { "type": "root", "child": { "type": "action", "call": "Run", "while": { "call": "HasItemEquipped", "args": [ "running-shoes" ] } } } ``` -------------------------------- ### BehaviourTree Options Source: https://context7.com/nikkorn/mistreevous/llms.txt Configuration options for the BehaviourTree constructor to customize delta time, random number generation, and state change tracking. ```APIDOC ## BehaviourTree Options ### Description Optional configuration object passed to the BehaviourTree constructor for customizing delta time calculation, random number generation, and state change event handling. ### Parameters #### Request Body - **getDeltaTime** (function) - Optional - Returns the delta time in seconds. - **random** (function) - Optional - Custom random number generator for deterministic behavior. - **onNodeStateChange** (function) - Optional - Callback triggered when a node changes state. ``` -------------------------------- ### Implement Asynchronous Promise-based Actions Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Demonstrates how to return a Promise from an action function to handle long-running tasks, keeping the node in a RUNNING state until resolution. ```JavaScript const agent = { SomeAsyncAction: () => { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(Mistreevous.State.SUCCEEDED); }, 5000); }); } }; ``` -------------------------------- ### Named Root Node and Branch Reference (MDSL & JSON) Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Demonstrates defining additional named root nodes that can be reused and referenced by other nodes using the 'branch' keyword. One root node must remain unnamed to serve as the main entry point. ```MDSL root { branch [SomeOtherTree] } root [SomeOtherTree] { action [Dance] } ``` ```JSON [ { "type": "root", "child": { "type": "branch", "ref": "SomeOtherTree" } }, { "type": "root", "id": "SomeOtherTree", "child": { "type": "action", "call": "Dance", "args": [] } } ] ``` -------------------------------- ### MDSL and JSON for Sequence Node with Until Guard Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Demonstrates a sequence node in MDSL that executes its children until a condition becomes false, and its JSON equivalent. This is useful for repeating actions until a specific state is reached. ```MDSL root { sequence until(CanSeePlayer) { action [LookLeft] wait [5000] action [LookRight] wait [5000] } } ``` ```JSON { "type": "root", "child": { "type": "sequence", "until": { "call": "CanSeePlayer" }, "children": [ { "type": "action", "call": "LookLeft" }, { "type": "wait", "duration": 5000 }, { "type": "action", "call": "LookRight" }, { "type": "wait", "duration": 5000 } ] } } ``` -------------------------------- ### Monitor Tree State with getState() and isRunning() Source: https://context7.com/nikkorn/mistreevous/llms.txt Illustrates how to check the current execution status of a behaviour tree using getState and isRunning. Useful for controlling loops or conditional logic based on task progress. ```typescript import { BehaviourTree, State } from "mistreevous"; const definition = `root { action [LongRunningTask] }`; let taskProgress = 0; const agent = { LongRunningTask: () => { taskProgress++; if (taskProgress >= 5) { return State.SUCCEEDED; } return State.RUNNING; } }; const tree = new BehaviourTree(definition, agent); console.log(tree.getState()); console.log(tree.isRunning()); tree.step(); while (tree.isRunning()) { tree.step(); } console.log(tree.getState()); console.log(tree.isRunning()); ``` -------------------------------- ### Reference Agent Properties in MDSL and JSON Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Demonstrates how to reference agent properties dynamically as arguments in both MDSL and JSON definitions. This allows argument values to be resolved from the agent instance at runtime. The referenced property must exist on the agent instance. ```MDSL root { action [SomeFunction, $someAgentProperty] } ``` ```JSON { "type": "root", "child": { "type": "action", "call": "SomeFunction", "args": [ { "$": "someAgentProperty" } ] } } ``` -------------------------------- ### getState() and isRunning() Methods Source: https://context7.com/nikkorn/mistreevous/llms.txt Retrieves the current state of the behaviour tree or checks if it is currently running. ```APIDOC ## getState() and isRunning() Methods ### Description Returns the current state of the tree (READY, RUNNING, SUCCEEDED, or FAILED). The isRunning() method provides a convenient boolean check for the RUNNING state. ### Method `tree.getState()` `tree.isRunning()` ### Endpoint N/A (Instance methods) ### Parameters None ### Request Example ```javascript import { BehaviourTree, State } from "mistreevous"; const definition = `root { action [LongRunningTask] }`; let taskProgress = 0; const agent = { LongRunningTask: () => { taskProgress++; if (taskProgress >= 5) { return State.SUCCEEDED; } return State.RUNNING; } }; const tree = new BehaviourTree(definition, agent); console.log(tree.getState()); // State.READY console.log(tree.isRunning()); // false tree.step(); console.log(tree.getState()); // State.RUNNING console.log(tree.isRunning()); // true // Continue stepping until complete while (tree.isRunning()) { tree.step(); } console.log(tree.getState()); // State.SUCCEEDED console.log(tree.isRunning()); // false ``` ### Response #### Success Response (200) - **getState()**: Returns one of the following `State` enum values: `READY`, `RUNNING`, `SUCCEEDED`, `FAILED`. - **isRunning()**: Returns a boolean (`true` if the tree is in the `RUNNING` state, `false` otherwise). ``` -------------------------------- ### Mistreevous Guards: While and Until Source: https://context7.com/nikkorn/mistreevous/llms.txt Demonstrates the use of 'while' and 'until' guards in Mistreevous behaviour trees. 'While' guards repeat nodes as long as a condition is true, while 'until' guards repeat until a condition becomes true. The 'then succeed' option allows aborted nodes to be marked as successful. ```javascript import { BehaviourTree, State } from "mistreevous"; // While guard - continues while condition is true const whileDefinition = `root { repeat while(HasStamina) { action [RunForward] } }`; // Until guard - continues until condition becomes true const untilDefinition = `root { sequence until(EnemyDefeated) { action [Attack] wait [500] } }`; // Guard with succeed on abort const succeedOnAbort = `root { sequence { wait until(CanAct) then succeed action [PerformAction] } }`; let stamina = 100; let enemyHealth = 50; const agent = { HasStamina: () => stamina > 0, RunForward: () => { stamina -= 10; console.log(`Running... stamina: ${stamina}`); return State.SUCCEEDED; }, EnemyDefeated: () => enemyHealth <= 0, Attack: () => { enemyHealth -= 15; console.log(`Attack! Enemy health: ${enemyHealth}`); return State.SUCCEEDED; }, CanAct: () => true, PerformAction: () => State.SUCCEEDED }; const tree = new BehaviourTree(whileDefinition, agent); while (tree.getState() !== State.FAILED) { tree.step(); } // Stops when stamina depleted ``` -------------------------------- ### BehaviourTree Constructor Source: https://context7.com/nikkorn/mistreevous/llms.txt Creates a new behaviour tree instance from a definition (MDSL string or JSON) and an agent object containing action and condition functions. ```APIDOC ## BehaviourTree Constructor ### Description Creates a new behaviour tree instance from a definition (MDSL string or JSON) and an agent object containing the action and condition functions. The agent object maps function names referenced in the tree definition to their implementations. ### Method `new BehaviourTree(definition: string | object, agent: object)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **definition** (string | object) - The behaviour tree definition in MDSL format or JSON. - **agent** (object) - An object mapping function names to their implementations (actions and conditions). ### Request Example ```javascript import { BehaviourTree, State } from "mistreevous"; // Using MDSL definition const mdslDefinition = `root { sequence { action [Walk] action [Attack] } }`; const agent = { Walk: () => { console.log("Walking..."); return State.SUCCEEDED; }, Attack: () => { console.log("Attacking!"); return State.SUCCEEDED; } }; const tree = new BehaviourTree(mdslDefinition, agent); // Using JSON definition const jsonDefinition = { type: "root", child: { type: "sequence", children: [ { type: "action", call: "Walk" }, { type: "action", call: "Attack" } ] } }; const treeFromJson = new BehaviourTree(jsonDefinition, agent); ``` ### Response #### Success Response (200) - **BehaviourTree instance** - A new instance of the BehaviourTree class. ``` -------------------------------- ### Mistreevous Entry Callback Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Shows how to define an 'entry' callback in MDSL, which triggers a function when a node enters the 'RUNNING' state. The corresponding JSON structure is provided. ```MDSL root { sequence entry(StartWalkingAnimation) { action [WalkNorthOneSpace] action [WalkEastOneSpace] action [WalkSouthOneSpace] action [WalkWestOneSpace] } } ``` ```JSON { "type": "root", "child": { "type": "sequence", "entry": { "call": "StartWalkingAnimation" }, "children": [ { "type": "action", "call": "WalkNorthOneSpace" }, { "type": "action", "call": "WalkEastOneSpace" }, { "type": "action", "call": "WalkSouthOneSpace" }, { "type": "action", "call": "WalkWestOneSpace" } ] } } ``` -------------------------------- ### Define Action Nodes in MDSL and JSON Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Demonstrates the syntax for declaring an action node within a behavior tree using both MDSL and JSON formats. ```MDSL root { action [Attack] } ``` ```JSON { "type": "root", "child": { "type": "action", "call": "Attack" } } ``` -------------------------------- ### Method: getTreeNodeDetails() Source: https://context7.com/nikkorn/mistreevous/llms.txt Retrieves the current execution state and configuration details for every node in the tree. ```APIDOC ## getTreeNodeDetails() ### Description Returns detailed information about every node in the tree including their current state, type, name, and any configured attributes. Useful for debugging and visualizing tree execution. ### Method Instance Method ### Response - **Object** (JSON) - A tree structure containing node IDs, types, names, states, and children arrays. ``` -------------------------------- ### Register Global Functions and Subtrees Source: https://context7.com/nikkorn/mistreevous/llms.txt Allows defining reusable global functions or subtrees that can be referenced across multiple behaviour tree instances. This promotes modularity and code reuse in complex AI systems. ```javascript import { BehaviourTree, State } from "mistreevous"; BehaviourTree.register("Log", (agent, message) => { console.log(`[${agent.name}]: ${message}`); return State.SUCCEEDED; }); BehaviourTree.register("Patrol", `root { sequence { action [MoveToWaypoint] wait [2000] action [LookAround] } }`); const definition = `root { sequence { action [Log, "Starting patrol"] branch [Patrol] action [Log, "Patrol complete"] } }`; const agent = { name: "Guard", MoveToWaypoint: () => State.SUCCEEDED, LookAround: () => State.SUCCEEDED }; const tree = new BehaviourTree(definition, agent); tree.step(); BehaviourTree.unregisterAll(); ``` -------------------------------- ### Mistreevous Agent Property References (MDSL and JSON) Source: https://context7.com/nikkorn/mistreevous/llms.txt Shows how to reference agent properties dynamically within Mistreevous behaviour trees using the '$' prefix in MDSL or object notation in JSON. This allows node arguments to be resolved from the agent's state at runtime. ```javascript import { BehaviourTree, State } from "mistreevous"; // MDSL with agent property reference const mdslDefinition = `root { sequence { action [MoveTo, $targetX, $targetY] action [Say, $greeting] } }`; // JSON with agent property reference const jsonDefinition = { type: "root", child: { type: "sequence", children: [ { type: "action", call: "MoveTo", args: [{ $: "targetX" }, { $: "targetY" }] }, { type: "action", call: "Say", args: [{ $: "greeting" }] } ] } }; const agent = { targetX: 150, targetY: 200, greeting: "Hello, friend!", MoveTo: (x, y) => { console.log(`Moving to (${x}, ${y})`); return State.SUCCEEDED; }, Say: (message) => { console.log(message); return State.SUCCEEDED; } }; const tree = new BehaviourTree(mdslDefinition, agent); tree.step(); // Output: // Moving to (150, 200) // Hello, friend! ``` -------------------------------- ### MDSL and JSON for Sequence Node with While Guard Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Illustrates a sequence node in MDSL that executes its children only while a condition is true, and its JSON representation. This enables conditional execution of a series of actions. ```MDSL root { sequence while(IsWandering) { action [Whistle] wait [5000] action [Yawn] wait [5000] } } ``` ```JSON { "type": "root", "child": { "type": "sequence", "while": { "call": "IsWandering" }, "children": [ { "type": "action", "call": "Whistle" }, { "type": "wait", "duration": 5000 }, { "type": "action", "call": "Yawn" }, { "type": "wait", "duration": 5000 } ] } } ``` -------------------------------- ### Implement Selector Composite Node Source: https://context7.com/nikkorn/mistreevous/llms.txt Demonstrates the Selector node, which acts as a fallback mechanism by executing children until one succeeds. It is useful for implementing priority-based decision making. ```javascript import { BehaviourTree, State } from "mistreevous"; const definition = `root { selector { sequence { condition [HasRangedWeapon] action [ShootEnemy] } sequence { condition [HasMeleeWeapon] action [StrikeEnemy] } action [RunAway] } }`; const agent = { HasRangedWeapon: () => false, ShootEnemy: () => State.SUCCEEDED, HasMeleeWeapon: () => true, StrikeEnemy: () => { console.log("Striking with melee weapon!"); return State.SUCCEEDED; }, RunAway: () => State.SUCCEEDED }; const tree = new BehaviourTree(definition, agent); tree.step(); ``` -------------------------------- ### Mistreevous Step Callback Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Demonstrates the 'step' callback in MDSL, which is executed on each tree update for a node. The corresponding JSON structure is provided. ```MDSL root { sequence step(OnMoving) { action [WalkNorthOneSpace] action [WalkEastOneSpace] action [WalkSouthOneSpace] action [WalkWestOneSpace] } } ``` ```JSON { "type": "root", "child": { "type": "sequence", "step": { "call": "OnMoving" }, "children": [ { "type": "action", "call": "WalkNorthOneSpace" }, { "type": "action", "call": "WalkEastOneSpace" }, { "type": "action", "call": "WalkSouthOneSpace" }, { "type": "action", "call": "WalkWestOneSpace" } ] } } ``` -------------------------------- ### Implement Sequence Composite Node Source: https://context7.com/nikkorn/mistreevous/llms.txt Demonstrates the Sequence node, which executes children in order and succeeds only if all children succeed. Supports both MDSL string definitions and JSON object structures. ```javascript import { BehaviourTree, State } from "mistreevous"; const mdslDefinition = `root { sequence { action [CheckEnergy] action [FindTarget] action [MoveToTarget] action [Attack] } }`; const jsonDefinition = { type: "root", child: { type: "sequence", children: [ { type: "action", call: "CheckEnergy" }, { type: "action", call: "FindTarget" }, { type: "action", call: "MoveToTarget" }, { type: "action", call: "Attack" } ] } }; const agent = { CheckEnergy: () => State.SUCCEEDED, FindTarget: () => State.SUCCEEDED, MoveToTarget: () => State.SUCCEEDED, Attack: () => State.SUCCEEDED }; const tree = new BehaviourTree(jsonDefinition, agent); tree.step(); console.log(tree.getState()); ``` -------------------------------- ### Static Method: BehaviourTree.register() Source: https://context7.com/nikkorn/mistreevous/llms.txt Registers global functions or subtrees that can be referenced by any behaviour tree instance. ```APIDOC ## BehaviourTree.register(name, definition) ### Description Registers global functions or subtrees that can be referenced by any behaviour tree instance. Global functions receive the agent as the first argument. ### Parameters - **name** (string) - Required - The identifier for the function or subtree. - **definition** (function|string) - Required - The function logic or MDSL string to register. ``` -------------------------------- ### Define All Composite Node Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Runs all children until completion. Succeeds if at least one child succeeds, otherwise fails. ```MDSL root { all { action [Reload] action [MoveToCover] } } ``` ```JSON { "type": "root", "child": { "type": "all", "children": [ { "type": "action", "call": "Reload" }, { "type": "action", "call": "MoveToCover" } ] } } ``` -------------------------------- ### Reset Behaviour Tree Execution Source: https://context7.com/nikkorn/mistreevous/llms.txt Resets the entire behaviour tree state to READY, allowing for a fresh execution cycle from the root node. This is useful for restarting logic after a tree has completed or failed. ```javascript import { BehaviourTree, State } from "mistreevous"; const definition = `root { sequence { action [GatherResources] action [BuildStructure] } }`; const agent = { GatherResources: () => State.SUCCEEDED, BuildStructure: () => State.SUCCEEDED }; const tree = new BehaviourTree(definition, agent); tree.step(); console.log(tree.getState()); tree.reset(); console.log(tree.getState()); tree.step(); console.log(tree.getState()); ``` -------------------------------- ### MDSL and JSON for Wait Node with Guard Condition Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Illustrates the definition of a wait node in MDSL that uses a guard condition, and its corresponding JSON representation. This allows the tree to pause execution until a specific condition is met. ```MDSL root { wait while(CanWait) } ``` ```JSON { "type": "root", "child": { "type": "wait", "while": { "call": "CanWait" } } } ``` -------------------------------- ### Method: reset() Source: https://context7.com/nikkorn/mistreevous/llms.txt Resets the behaviour tree state from the root node outwards to all nested nodes, setting their state back to READY. ```APIDOC ## reset() ### Description Resets the tree from the root node outwards to each nested node, setting each node's state back to READY. This allows restarting the tree execution from the beginning. ### Method Instance Method ### Parameters - None ### Request Example ```javascript tree.reset(); ``` ### Response - **State** (Enum) - Returns the tree to State.READY. ``` -------------------------------- ### Define Condition Nodes with MDSL, JSON, and JavaScript Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Condition nodes evaluate boolean results from agent functions. This snippet demonstrates how to define simple conditions and pass arguments using MDSL, JSON, and the corresponding JavaScript agent implementation. ```MDSL root { sequence { condition [HasWeapon] action [Attack] } } ``` ```JSON { "type": "root", "child": { "type": "sequence", "children": [ { "type": "condition", "call": "HasWeapon" }, { "type": "action", "call": "Attack" } ] } } ``` ```JavaScript const agent = { HasWeapon: () => this.isHoldingWeapon(), Attack: () => this.attackPlayer() }; ``` -------------------------------- ### Composite Node: Selector Source: https://context7.com/nikkorn/mistreevous/llms.txt Executes child nodes in order until one succeeds, acting as a fallback mechanism. ```APIDOC ## Selector Composite Node ### Description Executes child nodes in order until one succeeds. Succeeds if ANY child succeeds. Fails only if ALL children fail. Acts as a fallback mechanism. ``` -------------------------------- ### Repeat Node with Iteration Range (MDSL & JSON) Source: https://github.com/nikkorn/mistreevous/blob/master/README.md This configuration of the Repeat node allows for a random number of iterations within a specified lower and upper bound. The child node will execute a variable number of times within this range. ```MDSL root { repeat [1,5] { action [SomeAction] } } ``` ```JSON { "type": "root", "child": { "type": "repeat", "iterations": [1, 5], "child": { "type": "action", "call": "SomeAction" } } } ``` -------------------------------- ### Define Wait Nodes with Fixed and Random Durations Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Wait nodes pause execution for a set duration or a random range. This snippet shows how to configure fixed delays, randomized intervals, and indefinite waits. ```MDSL root { sequence { action [PickUpProjectile] wait [2000, 8000] action [ThrowProjectile] } } ``` ```JSON { "type": "root", "child": { "type": "sequence", "children": [ { "type": "action", "call": "PickUpProjectile" }, { "type": "wait", "duration": [2000, 8000] }, { "type": "action", "call": "ThrowProjectile" } ] } } ``` -------------------------------- ### Mistreevous Branch Node Definition Source: https://github.com/nikkorn/mistreevous/blob/master/README.md Demonstrates how to use the 'branch' node in MDSL to reference another root node. This allows for modular tree definitions. The equivalent JSON representation is also shown. ```MDSL root { branch [SomeOtherTree] } root [SomeOtherTree] { action [Dance] } ``` ```MDSL root { action [Dance] } ``` ```JSON [ { "type": "root", "child": { "type": "branch", "ref": "SomeOtherTree" } }, { "type": "root", "id": "SomeOtherTree", "child": { "type": "action", "call": "Dance" } } ] ``` ```JSON { "type": "root", "child": { "type": "action", "call": "Dance" } } ``` -------------------------------- ### Composite Node: Sequence Source: https://context7.com/nikkorn/mistreevous/llms.txt Executes child nodes in order, succeeding only if all children succeed. ```APIDOC ## Sequence Composite Node ### Description Executes child nodes in order. Succeeds only if ALL children succeed. Fails immediately if ANY child fails. Remains RUNNING if a child is RUNNING. ``` -------------------------------- ### Retrieve Tree Node Details for Debugging Source: https://context7.com/nikkorn/mistreevous/llms.txt Extracts the current state, type, and configuration of all nodes within the tree. This provides a hierarchical snapshot of the tree's execution status, ideal for visualization or logging. ```javascript import { BehaviourTree, State } from "mistreevous"; const definition = `root { selector { sequence { condition [HasWeapon] action [Attack] } action [Flee] } }`; const agent = { HasWeapon: () => true, Attack: () => State.SUCCEEDED, Flee: () => State.SUCCEEDED }; const tree = new BehaviourTree(definition, agent); tree.step(); const details = tree.getTreeNodeDetails(); console.log(JSON.stringify(details, null, 2)); ``` -------------------------------- ### Repeat Node with Infinite Iterations (MDSL & JSON) Source: https://github.com/nikkorn/mistreevous/blob/master/README.md When no iteration count is specified for the Repeat node, it will continue to execute its child node indefinitely until the child node itself fails. This is useful for continuous monitoring or looping behaviors. ```MDSL root { repeat { action [SomeAction] } } ``` ```JSON { "type": "root", "child": { "type": "repeat", "child": { "type": "action", "call": "SomeAction" } } } ``` -------------------------------- ### Validate Behaviour Tree Definitions in Javascript Source: https://context7.com/nikkorn/mistreevous/llms.txt Shows how to use the `validateDefinition` function to check the validity of behaviour tree definitions written in either MDSL or JSON format. It returns a result object indicating success or failure, along with error messages and the parsed JSON if validation passes. This is useful for pre-runtime checks. ```javascript import { validateDefinition } from "mistreevous"; // Validate MDSL const mdslResult = validateDefinition(`root { sequence { action [DoSomething] action [DoAnotherThing] } }`); console.log(mdslResult.succeeded); // true console.log(mdslResult.json); // Parsed JSON definition // Validate JSON const jsonResult = validateDefinition({ type: "root", child: { type: "action", call: "Test" } }); console.log(jsonResult.succeeded); // true // Invalid definition const invalidResult = validateDefinition(`root { sequence { // Missing children } }`); console.log(invalidResult.succeeded); // false console.log(invalidResult.errorMessage); // Error description ```