Current section

Files

Jump to
erlang_behaviour_trees src bt_engine util.erl
Raw

src/bt_engine/util.erl

-module(util).
-export([to_file/1, to_tree/1]).
-include("bt_node_behaviours/nodes.hrl").
%% Usage:
%% ---
%% util:to_tree(parser:parse("src/samples/trees/rackloop.yml", "single_rackloop", [{"BId", 3}])).
%% io:format("~s ~n", [jsx:encode(util:to_tree(parser:parse("src/samples/trees/rackloop.yml", "single_rackloop", [{"BId", 3}])))]).
to_tree({RootNode, _}) ->
node_to_tree({<<"null">>, 0}, RootNode).
to_file(ParseResult) ->
Data = jsx:encode(to_tree(ParseResult)),
{ok, F} = file:open("treedata.js", [write]),
file:write(F, "var treeData = ["),
file:write(F, Data),
file:write(F, "];"),
file:close(F).
node_to_tree({ParentName, Depth}, #sequence{name = SequenceName, children = Children, metadata = Metadata}) ->
%io:format("adding sequence with children ~p ~n", [Children]),
% Name = list_to_binary(lists:flatten(io_lib:format("(~p) ->", [Depth]))),
Name = list_to_binary(lists:flatten(SequenceName)),
Map = #{name => Name, parent => ParentName, status => get_status(Metadata)},
case length(Children) of
0 -> Map;
_ -> maps:put(children, lists:map(fun(X) -> node_to_tree({Name, Depth + 1}, X) end, Children), Map)
end;
node_to_tree({ParentName, Depth}, #decorator{name = DecoratorName, child = Child, metadata = Metadata}) ->
%io:format("adding decorator with children ~p ~n", [Children]),
Name = list_to_binary(lists:flatten(io_lib:format("(~p) ~p", [Depth, DecoratorName]))),
Map = #{name => Name, parent => ParentName, status => get_status(Metadata)},
maps:put(children, [node_to_tree({Name, Depth + 1}, Child)], Map);
%case length(Children) of
% 0 -> Map;
% _ -> maps:put(children, lists:map(fun(X) -> node_to_tree({Name, Depth + 1}, X) end, Children), Map)
%end;
node_to_tree({ParentName, Depth}, #task{name = TaskName, metadata = Metadata}) ->
%io:format("adding task with name ~p ~n", [TaskName]),
Name = list_to_binary(lists:flatten(io_lib:format("(~p) ~p", [Depth, TaskName]))),
#{name => Name, parent => ParentName, status => get_status(Metadata)}.
get_status(undefined) ->
unknown;
get_status(#metadata{status = Status}) ->
Status.