/
b3core.0.1.0.js
3139 lines (2757 loc) · 84.1 KB
/
b3core.0.1.0.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* b3
*
* Copyright (c) 2014 Renato de Pontes Pereira.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
**/
var b3 = b3 || {};
module.exports = b3;
/**
* Behavior3JS
* ===========
*
* * * *
*
* **Behavior3JS** is a Behavior Tree library written in JavaScript. It
* provides structures and algorithms that assist you in the task of creating
* intelligent agents for your game or application. Check it out some features
* of Behavior3JS:
*
* - Based on the work of (Marzinotto et al., 2014), in which they propose a
* **formal**, **consistent** and **general** definition of Behavior Trees;
* - **Optimized to control multiple agents**: you can use a single behavior
* tree instance to handle hundreds of agents;
* - It was **designed to load and save trees in a JSON format**, in order to
* use, edit and test it in multiple environments, tools and languages;
* - A **cool visual editor** which you can access online;
* - Several **composite, decorator and action nodes** available within the
* library. You still can define your own nodes, including composites and
* decorators;
* - **Completely free**, the core module and the visual editor are all published
* under the MIT License, which means that you can use them for your open source
* and commercial projects;
* - **Lightweight**, only 11.5KB!
*
* Visit http://behavior3js.guineashots.com to know more!
*
*
* Core Classes and Functions
* --------------------------
*
* This library include the following core structures...
*
* **Public:**
*
* - **BehaviorTree**: the structure that represents a Behavior Tree;
* - **Blackboard**: represents a "memory" in an agent and is required to to
* run a `BehaviorTree`;
* - **Composite**: base class for all composite nodes;
* - **Decorator**: base class for all decorator nodes;
* - **Action**: base class for all action nodes;
* - **Condition**: base class for all condition nodes;
*
* **Internal:**
*
*
* - **Tick**: used as container and tracking object through the tree during
* the tick signal;
* - **BaseNode**: the base class that provide all common node features;
*
* *Some classes are used internally on Behavior3JS, but you may need to access
* its functionalities eventually, specially the `Tick` object.*
*
*
* Nodes Included
* --------------
*
* **Composite Nodes**:
*
* - Sequence;
* - Priority;
* - MemSequence;
* - MemPriority;
*
*
* **Decorators**:
*
* - Inverter;
* - Limiter
* - MaxTime;
* - Repeater;
* - RepeaterUntilFailure;
* - RepeaterUntilSuccess;
*
*
* **Actions**:
*
* - Succeeder;
* - Failer;
* - Error;
* - Runner;
* - Wait.
*
* @module Behavior3JS
* @main Behavior3JS
**/
(function() {
"use strict";
/**
* List of all constants in Behavior3JS.
*
* @class Constants
**/
/**
* Version of the library.
*
* @property VERSION
* @type {String}
*/
b3.VERSION = '0.1.0';
/**
* Returned when a criterion has been met by a condition node or an action node
* has been completed successfully.
*
* @property SUCCESS
* @type {Integer}
*/
b3.SUCCESS = 1;
/**
* Returned when a criterion has not been met by a condition node or an action
* node could not finish its execution for any reason.
*
* @property FAILURE
* @type {Integer}
*/
b3.FAILURE = 2;
/**
* Returned when an action node has been initialized but is still waiting the
* its resolution.
*
* @property FAILURE
* @type {Integer}
*/
b3.RUNNING = 3;
/**
* Returned when some unexpected error happened in the tree, probably by a
* programming error (trying to verify an undefined variable). Its use depends
* on the final implementation of the leaf nodes.
*
* @property ERROR
* @type {Integer}
*/
b3.ERROR = 4;
/**
* Describes the node category as Composite.
*
* @property COMPOSITE
* @type {String}
*/
b3.COMPOSITE = 'composite';
/**
* Describes the node category as Decorator.
*
* @property DECORATOR
* @type {String}
*/
b3.DECORATOR = 'decorator';
/**
* Describes the node category as Action.
*
* @property ACTION
* @type {String}
*/
b3.ACTION = 'action';
/**
* Describes the node category as Condition.
*
* @property CONDITION
* @type {String}
*/
b3.CONDITION = 'condition';
/**
* List of internal and helper functions in Behavior3JS.
*
* @class Utils
**/
/**
* This function is used to create unique IDs for trees and nodes.
*
* (consult http://www.ietf.org/rfc/rfc4122.txt).
*
* @method createUUID
* @return {String} A unique ID.
**/
b3.createUUID = function() {
var s = [];
var hexDigits = "0123456789abcdef";
for (var i = 0; i < 36; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
// bits 12-15 of the time_hi_and_version field to 0010
s[14] = "4";
// bits 6-7 of the clock_seq_hi_and_reserved to 01
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
s[8] = s[13] = s[18] = s[23] = "-";
var uuid = s.join("");
return uuid;
}
/**
* Class is a meta-factory function to create classes in JavaScript. It is a
* shortcut for the CreateJS syntax style. By default, the class created by
* this function have an initialize function (the constructor). Optionally, you
* can specify the inheritance by passing another class as parameter.
*
* By default, all classes created using this function, may receives only a
* settings parameter as argument. This pattern is commonly used by jQuery and
* its plugins.
*
* Usage
* -----
*
* // Creating a simple class
* var BaseClass = b3.Class();
*
* // Using inheritance
* var ChildClass = b3.Class(BaseClass);
*
* // Defining the constructor
* ChildClass.prototype.initialize = function(settings) { ... }
*
* @method Class
* @param {Object} [baseClass] The super class.
* @return {Object} A new class.
**/
b3.Class = function(baseClass) {
// create a new class
var cls = function(params) {
this.initialize(params);
}
// if base class is provided, inherit
if (baseClass) {
cls.prototype = new baseClass();
cls.prototype.constructor = cls;
}
// create initialize if does not exist on baseClass
cls.prototype.initialize = cls.prototype.initialize || function() {};
return cls;
}
})();
/**
* Blackboard
*
* Copyright (c) 2014 Renato de Pontes Pereira.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
**/
/**
* @module Behavior3JS
**/
// namespace:
this.b3 = this.b3 || {};
(function() {
"use strict";
/**
* The Blackboard is the memory structure required by `BehaviorTree` and its
* nodes. It only have 2 public methods: `set` and `get`. These methods works
* in 3 different contexts: global, per tree, and per node per tree.
*
* Suppose you have two different trees controlling a single object with a
* single blackboard, then:
*
* - In the global context, all nodes will access the stored information.
* - In per tree context, only nodes sharing the same tree share the stored
* information.
* - In per node per tree context, the information stored in the blackboard can
* only be accessed by the same node that wrote the data.
*
* The context is selected indirectly by the parameters provided to these
* methods, for example:
*
* // getting/setting variable in global context
* blackboard.set('testKey', 'value');
* var value = blackboard.get('testKey');
*
* // getting/setting variable in per tree context
* blackboard.set('testKey', 'value', tree.id);
* var value = blackboard.get('testKey', tree.id);
*
* // getting/setting variable in per node per tree context
* blackboard.set('testKey', 'value', tree.id, node.id);
* var value = blackboard.get('testKey', tree.id, node.id);
*
* Note: Internally, the blackboard store these memories in different objects,
* being the global on `_baseMemory`, the per tree on `_treeMemory` and the
* per node per tree dynamically create inside the per tree memory (it is
* accessed via `_treeMemory[id].nodeMemory`). Avoid to use these variables
* manually, use `get` and `set` instead.
*
* @class Blackboard
**/
var Blackboard = b3.Class();
var p = Blackboard.prototype;
/**
* Initialization method.
*
* @method initialize
* @constructor
**/
p.initialize = function() {
this._baseMemory = {};
this._treeMemory = {};
}
/**
* Internal method to retrieve the tree context memory. If the memory does
* not exist, this method creates it.
*
* @method _getTreeMemory
* @param {string} treeScope The id of the tree in scope.
* @returns {Object} The tree memory.
* @protected
**/
p._getTreeMemory = function(treeScope) {
if (!this._treeMemory[treeScope]) {
this._treeMemory[treeScope] = {
'nodeMemory': {},
'openNodes': [],
'traversalDepth': 0,
'traversalCycle': 0,
};
}
return this._treeMemory[treeScope];
};
/**
* Internal method to retrieve the node context memory, given the tree
* memory. If the memory does not exist, this method creates is.
*
* @method _getNodeMemory
* @param {String} treeMemory the tree memory.
* @param {String} nodeScope The id of the node in scope.
* @returns {Object} The node memory.
* @protected
**/
p._getNodeMemory = function(treeMemory, nodeScope) {
var memory = treeMemory['nodeMemory'];
if (!memory[nodeScope]) {
memory[nodeScope] = {};
}
return memory[nodeScope];
};
/**
* Internal method to retrieve the context memory. If treeScope and
* nodeScope are provided, this method returns the per node per tree
* memory. If only the treeScope is provided, it returns the per tree
* memory. If no parameter is provided, it returns the global memory.
* Notice that, if only nodeScope is provided, this method will still
* return the global memory.
*
* @method _getMemory
* @param {String} treeScope The id of the tree scope.
* @param {String} nodeScope The id of the node scope.
* @returns {Object} A memory object.
* @protected
**/
p._getMemory = function(treeScope, nodeScope) {
var memory = this._baseMemory;
if (treeScope) {
memory = this._getTreeMemory(treeScope);
if (nodeScope) {
memory = this._getNodeMemory(memory, nodeScope);
}
}
return memory;
};
/**
* Stores a value in the blackboard. If treeScope and nodeScope are
* provided, this method will save the value into the per node per tree
* memory. If only the treeScope is provided, it will save the value into
* the per tree memory. If no parameter is provided, this method will save
* the value into the global memory. Notice that, if only nodeScope is
* provided (but treeScope not), this method will still save the value into
* the global memory.
*
* @method set
* @param {String} key The key to be stored.
* @param {String} value The value to be stored.
* @param {String} treeScope The tree id if accessing the tree or node
* memory.
* @param {String} nodeScope The node id if accessing the node memory.
**/
p.set = function(key, value, treeScope, nodeScope) {
var memory = this._getMemory(treeScope, nodeScope);
memory[key] = value;
};
/**
* Retrieves a value in the blackboard. If treeScope and nodeScope are
* provided, this method will retrieve the value from the per node per tree
* memory. If only the treeScope is provided, it will retrieve the value
* from the per tree memory. If no parameter is provided, this method will
* retrieve from the global memory. If only nodeScope is provided (but
* treeScope not), this method will still try to retrieve from the global
* memory.
*
* @method get
* @param {String} key The key to be retrieved.
* @param {String} treeScope The tree id if accessing the tree or node
* memory.
* @param {String} nodeScope The node id if accessing the node memory.
* @returns {Object} The value stored or undefined.
**/
p.get = function(key, treeScope, nodeScope) {
var memory = this._getMemory(treeScope, nodeScope);
return memory[key];
};
b3.Blackboard = Blackboard;
})();
/**
* Tick
*
* Copyright (c) 2014 Renato de Pontes Pereira.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
**/
/**
* @module Behavior3JS
**/
// namespace:
this.b3 = this.b3 || {};
(function() {
"use strict";
/**
* A new Tick object is instantiated every tick by BehaviorTree. It is passed
* as parameter to the nodes through the tree during the traversal.
*
* The role of the Tick class is to store the instances of tree, debug, target
* and blackboard. So, all nodes can access these informations.
*
* For internal uses, the Tick also is useful to store the open node after the
* tick signal, in order to let `BehaviorTree` to keep track and close them
* when necessary.
*
* This class also makes a bridge between nodes and the debug, passing the node
* state to the debug if the last is provided.
*
* @class Tick
**/
var Tick = b3.Class();
var p = Tick.prototype;
/**
* The tree reference.
*
* @property tree
* @type {b3.BehaviorTree}
* @readOnly
*/
/**
* The debug reference.
*
* @property debug
* @type {Object}
* @readOnly
*/
/**
* The target object reference.
*
* @property target
* @type {Object}
* @readOnly
*/
/**
* The blackboard reference.
*
* @property blackboard
* @type {Blackboard}
* @readOnly
*/
/**
* The list of open nodes. Update during the tree traversal.
*
* @property _openNodes
* @type {Array}
* @protected
* @readOnly
*/
/**
* The number of nodes entered during the tick. Update during the tree
* traversal.
*
* @property _nodeCount
* @type {Integer}
* @protected
* @readOnly
*/
/**
* Initialization method.
*
* @method initialize
* @constructor
**/
p.initialize = function() {
// set by BehaviorTree
this.tree = null;
this.debug = null;
this.target = null;
this.blackboard = null;
// updated during the tick signal
this._openNodes = [];
this._nodeCount = 0;
}
/**
* Called when entering a node (called by BaseNode).
*
* @method _enterNode
* @param {Object} node The node that called this method.
* @protected
**/
p._enterNode = function(node) {
this._nodeCount++;
this._openNodes.push(node);
// TODO: call debug here
}
/**
* Callback when opening a node (called by BaseNode).
*
* @method _openNode
* @param {Object} node The node that called this method.
* @protected
**/
p._openNode = function(node) {
// TODO: call debug here
}
/**
* Callback when ticking a node (called by BaseNode).
*
* @method _tickNode
* @param {Object} node The node that called this method.
* @protected
**/
p._tickNode = function(node) {
// TODO: call debug here
}
/**
* Callback when closing a node (called by BaseNode).
*
* @method _closeNode
* @param {Object} node The node that called this method.
* @protected
**/
p._closeNode = function(node) {
// TODO: call debug here
this._openNodes.pop();
}
/**
* Callback when exiting a node (called by BaseNode).
*
* @method _exitNode
* @param {Object} node The node that called this method.
* @protected
**/
p._exitNode = function(node) {
// TODO: call debug here
}
b3.Tick = Tick;
})();
/**
* BehaviorTree
*
* Copyright (c) 2014 Renato de Pontes Pereira.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
**/
/**
* @module Behavior3JS
**/
// namespace:
this.b3 = this.b3 || {};
(function() {
"use strict";
/**
* The BehaviorTree class, as the name implies, represents the Behavior Tree
* structure.
*
* There are two ways to construct a Behavior Tree: by manually setting the
* root node, or by loading it from a data structure (which can be loaded from
* a JSON). Both methods are shown in the examples below and better explained
* in the user guide.
*
* The tick method must be called periodically, in order to send the tick
* signal to all nodes in the tree, starting from the root. The method
* `BehaviorTree.tick` receives a target object and a blackboard as parameters.
* The target object can be anything: a game agent, a system, a DOM object,
* etc. This target is not used by any piece of Behavior3JS, i.e., the target
* object will only be used by custom nodes.
*
* The blackboard is obligatory and must be an instance of `Blackboard`. This
* requirement is necessary due to the fact that neither `BehaviorTree` or any
* node will store the execution variables in its own object (e.g., the BT does
* not store the target, information about opened nodes or number of times the
* tree was called). But because of this, you only need a single tree instance
* to control multiple (maybe hundreds) objects.
*
* Manual construction of a Behavior Tree
* --------------------------------------
*
* var tree = new b3.BehaviorTree();
*
* tree.root = new b3.Sequence({children:[
* new b3.Priority({children:[
* new MyCustomNode(),
* new MyCustomNode()
* ]}),
* ...
* ]});
*
*
* Loading a Behavior Tree from data structure
* -------------------------------------------
*
* var tree = new b3.BehaviorTree();
*
* tree.load({
* 'title' : 'Behavior Tree title'
* 'description' : 'My description'
* 'root' : 'node-id-1'
* 'nodes' : {
* 'node-id-1' : {
* 'name' : 'Priority', // this is the node type
* 'title' : 'Root Node',
* 'description' : 'Description',
* 'children' : ['node-id-2', 'node-id-3'],
* },
* ...
* }
* })
*
*
* @class BehaviorTree
**/
var BehaviorTree = b3.Class();
var p = BehaviorTree.prototype;
/**
* The tree id, must be unique. By default, created with `b3.createUUID`.
*
* @property id
* @type {String}
* @readOnly
*/
/**
* The tree title.
*
* @property title
* @type {String}
*/
/**
* Description of the tree.
*
* @property description
* @type {String}
*/
/**
* A dictionary with (key-value) properties. Useful to define custom
* variables in the visual editor.
*
* @property properties
* @type {Object}
*/
/**
* The reference to the root node. Must be an instance of `b3.BaseNode`.
*
* @property root
* @type {BaseNode}
*/
/**
* The reference to the debug instance.
*
* @property debug
* @type {Object}
*/
/**
* Initialization method.
*
* @method initialize
* @constructor
**/
p.initialize = function() {
this.id = b3.createUUID();
this.title = 'The behavior tree';
this.description = 'Default description';
this.properties = {};
this.root = null;
this.debug = null;
}
/**
* This method loads a Behavior Tree from a data structure, populating this
* object with the provided data. Notice that, the data structure must
* follow the format specified by Behavior3JS. Consult the guide to know
* more about this format.
*
* You probably want to use custom nodes in your BTs, thus, you need to
* provide the `names` object, in which this method can find the nodes by
* `names[NODE_NAME]`. This variable can be a namespace or a dictionary,
* as long as this method can find the node by its name, for example:
*
* //json
* ...
* 'node1': {
* 'name': MyCustomNode,
* 'title': ...
* }
* ...
*
* //code
* var bt = new b3.BehaviorTree();
* bt.load(data, {'MyCustomNode':MyCustomNode})
*
*
* @method load
* @param {Object} data The data structure representing a Behavior Tree.
* @param {Object} [names] A namespace or dict containing custom nodes.
**/
p.load = function(data, names) {
names = names || {};
this.title = data.title || this.title;
this.description = data.description || this.description;
this.properties = data.properties || this.properties;
var nodes = {};
// Create the node list (without connection between them)
for (var id in data.nodes) {
var spec = data.nodes[id];
if (spec.name in names) {
// Look for the name in custom nodes
var cls = names[spec.name];
}
else if (spec.name in b3) {
// Look for the name in default nodes
var cls = b3[spec.name];
}
else {
// Invalid node name
throw EvalError('BehaviorTree.load: Invalid node name + "' +
spec.name + '".');
}
var node = new cls(spec.parameters);
node.id = spec.id || node.id;
node.title = spec.title || node.title;
node.description = spec.description || node.description;
node.properties = spec.properties || node.properties;
node.parameters = spec.parameters || node.parameters;
nodes[id] = node;
}
// Connect the nodes
for (var id in data.nodes) {
var spec = data.nodes[id];
var node = nodes[id];
if (node.category === b3.COMPOSITE && spec.children) {
for (var i = 0; i < spec.children.length; i++) {
var cid = spec.children[i];
node.children.push(nodes[cid]);
}
}
else if (node.category === b3.DECORATOR && spec.child) {
node.child = nodes[spec.child];
}
}
this.root = nodes[data.root];
};
/**
* This method dump the current BT into a data structure.
*
* Note: This method does not record the current node parameters. Thus,
* it may not be compatible with load for now.
*
* @method dump
* @returns {Object} A data object representing this tree.
**/
p.dump = function() {
var data = {};
data.title = this.title;
data.description = this.description;
data.root = (this.root) ? this.root.id : null;
data.properties = this.properties;
data.nodes = {};
if (!this.root) return data;
var stack = [this.root];
while (stack.length > 0) {
var node = stack.pop();
var spec = {};
spec.id = node.id;
spec.name = node.name;
spec.title = node.title;
spec.description = node.description;
spec.properties = node.properties;
spec.parameters = node.parameters;
if (node.category === b3.COMPOSITE && node.children) {
var children = []
for (var i = node.children.length - 1; i >= 0; i--) {
children.push(node.children[i].id);
stack.push(node.children[i]);
}
spec.children = children;
}
else if (node.category === b3.DECORATOR && node.child) {
stack.push(node.child);
spec.child = node.child.id;
}
data.nodes[node.id] = spec;
}
return data;
};
/**
* Propagates the tick signal through the tree, starting from the root.
*
* This method receives a target object of any type (Object, Array,
* DOMElement, whatever) and a `Blackboard` instance. The target object has
* no use at all for all Behavior3JS components, but surely is important
* for custom nodes. The blackboard instance is used by the tree and nodes
* to store execution variables (e.g., last node running) and is obligatory
* to be a `Blackboard` instance (or an object with the same interface).
*
* Internally, this method creates a Tick object, which will store the
* target and the blackboard objects.
*
* Note: BehaviorTree stores a list of open nodes from last tick, if these
* nodes weren't called after the current tick, this method will close them
* automatically.
*
* @method tick
* @param {Object} target A target object.
* @param {Blackboard} blackboard An instance of blackboard object.
* @returns {Constant} The tick signal state.
**/
p.tick = function(target, blackboard) {
if (!blackboard) {
throw 'The blackboard parameter is obligatory and must be an ' +
'instance of b3.Blackboard';
}
/* CREATE A TICK OBJECT */
var tick = new b3.Tick();
tick.debug = this.debug;
tick.target = target;
tick.blackboard = blackboard;
tick.tree = this;
/* TICK NODE */
var state = this.root._execute(tick);
/* CLOSE NODES FROM LAST TICK, IF NEEDED */
var lastOpenNodes = blackboard.get('openNodes', this.id);
var currOpenNodes = tick._openNodes.slice(0);
// does not close if it is still open in this tick