Skip to content

Commit

Permalink
Change serialization
Browse files Browse the repository at this point in the history
Add subtree function
  • Loading branch information
AkiKurisu committed Jul 5, 2024
1 parent 57dfc7e commit 1337482
Show file tree
Hide file tree
Showing 59 changed files with 940 additions and 693 deletions.
14 changes: 8 additions & 6 deletions Editor/Core/Drawer/BehaviorTreeSerializationPairDrawer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ public class BehaviorTreeSerializationPairDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var soProperty = property.FindPropertyRelative("behaviorTreeSO");
var soProperty = property.FindPropertyRelative("behaviorTreeAsset");
var textProperty = property.FindPropertyRelative("serializedData");
position.width /= 3;
GUI.enabled = false;
Expand All @@ -21,7 +21,8 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten
GUI.enabled = textProperty.objectReferenceValue != null;
if (GUI.Button(position, "Serialize"))
{
var serializedData = SerializeUtility.SerializeTree(soProperty.objectReferenceValue as BehaviorTreeSO, true, true);
var asset = soProperty.objectReferenceValue as BehaviorTreeAsset;
var serializedData = BehaviorTree.Serialize(asset.GetBehaviorTree(), true, true);
var textPath = Application.dataPath + AssetDatabase.GetAssetPath(textProperty.objectReferenceValue).Replace("Assets", string.Empty);
File.WriteAllText(textPath, serializedData);
AssetDatabase.SaveAssets();
Expand All @@ -30,10 +31,11 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten
position.x += position.width;
if (GUI.Button(position, "Deserialize"))
{
var treeSO = soProperty.objectReferenceValue as BehaviorTreeSO;
Undo.RecordObject(treeSO, "Deserialize from json file");
treeSO.Deserialize((textProperty.objectReferenceValue as TextAsset).text);
EditorUtility.SetDirty(treeSO);
var asset = soProperty.objectReferenceValue as BehaviorTreeAsset;
Undo.RecordObject(asset, "Deserialize from json file");
var data = BehaviorTreeData.Deserialize((textProperty.objectReferenceValue as TextAsset).text);
asset.SetBehaviorTreeData(data);
EditorUtility.SetDirty(asset);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
Expand Down
2 changes: 1 addition & 1 deletion Editor/Core/Editor/BehaviorTreeDebugButton.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ internal class BehaviorTreeDebugButton : Button
{
private const string ButtonText = "Edit BehaviorTree";
private const string DebugText = "Debug BehaviorTree";
public BehaviorTreeDebugButton(IBehaviorTree tree) : base(() => GraphEditorWindow.Show(tree))
public BehaviorTreeDebugButton(IBehaviorTreeContainer treeContainer) : base(() => GraphEditorWindow.Show(treeContainer))
{
style.fontSize = 15;
style.unityFontStyleAndWeight = FontStyle.Bold;
Expand Down
26 changes: 15 additions & 11 deletions Editor/Core/Editor/BehaviorTreeEditor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,16 @@
using System.Linq;
namespace Kurisu.AkiBT.Editor
{
[CustomEditor(typeof(BehaviorTree))]
public class BehaviorTreeEditor : UnityEditor.Editor
[CustomEditor(typeof(BehaviorTreeComponent))]
public class BehaviorTreeComponentEditor : UnityEditor.Editor
{
private static readonly string LabelText = $"AkiBT BehaviorTree <size=12>{BehaviorTreeSetting.Version}</size>";
public override VisualElement CreateInspectorGUI()
{
var myInspector = new VisualElement();
var tree = target as IBehaviorTree;
var tree = target as IBehaviorTreeContainer;
// create instance for edit
var instance = tree.GetBehaviorTree();
var label = new Label(LabelText);
label.style.fontSize = 20;
label.style.unityTextAlign = TextAnchor.MiddleCenter;
Expand All @@ -23,22 +25,24 @@ public override VisualElement CreateInspectorGUI()
var field = new PropertyField(serializedObject.FindProperty("externalBehaviorTree"), "External BehaviorTree");
field.SetEnabled(!Application.isPlaying);
myInspector.Add(field);
if (tree.SharedVariables.Count(x => x.IsExposed) != 0)
if (instance.SharedVariables.Count(x => x.IsExposed) != 0)
{
myInspector.Add(new SharedVariablesFoldout(tree, target, this));
myInspector.Add(new SharedVariablesFoldout(instance, target, this));
}
myInspector.Add(new BehaviorTreeDebugButton(tree));
return myInspector;
}
}
[CustomEditor(typeof(BehaviorTreeSO))]
public class BehaviorTreeSOEditor : UnityEditor.Editor
[CustomEditor(typeof(BehaviorTreeAsset))]
public class BehaviorTreeAssetEditor : UnityEditor.Editor
{
private static readonly string LabelText = $"AkiBT BehaviorTreeSO <size=12>{BehaviorTreeSetting.Version}</size>";
private static readonly string LabelText = $"AkiBT BehaviorTree <size=12>{BehaviorTreeSetting.Version}</size>";
public override VisualElement CreateInspectorGUI()
{
var myInspector = new VisualElement();
var tree = target as IBehaviorTree;
var tree = target as IBehaviorTreeContainer;
// create instance for edit
var instance = tree.GetBehaviorTree();
var label = new Label(LabelText);
label.style.fontSize = 20;
label.style.unityTextAlign = TextAnchor.MiddleCenter;
Expand All @@ -52,9 +56,9 @@ public override VisualElement CreateInspectorGUI()
description.style.minHeight = 60;
description.BindProperty(serializedObject.FindProperty("description"));
myInspector.Add(description);
if (tree.SharedVariables.Count(x => x.IsExposed) != 0)
if (instance.SharedVariables.Count(x => x.IsExposed) != 0)
{
myInspector.Add(new SharedVariablesFoldout(tree, target, this));
myInspector.Add(new SharedVariablesFoldout(instance, target, this));
}
myInspector.Add(new BehaviorTreeDebugButton(tree));
return myInspector;
Expand Down
57 changes: 29 additions & 28 deletions Editor/Core/Editor/GraphEditorWindow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public DefaultAssetTypeAttribute(Type type)
AssetType = type;
}
}
[DefaultAssetType(typeof(BehaviorTreeSO))]
[DefaultAssetType(typeof(BehaviorTreeAsset))]
public class GraphEditorWindow : EditorWindow, IHasCustomMenu
{
// GraphView window per UObject
Expand All @@ -39,7 +39,7 @@ private static BehaviorTreeSetting Setting
public Type GetAssetType()
{
var attribute = GetType().GetCustomAttribute<DefaultAssetTypeAttribute>();
return attribute?.AssetType ?? typeof(BehaviorTreeSO);
return attribute?.AssetType ?? typeof(BehaviorTreeAsset);
}
#pragma warning disable IDE0051
[OnOpenAsset]
Expand All @@ -52,24 +52,24 @@ private static bool OnOpenAsset(int instanceId, int _)
return true;
}
var asset = EditorUtility.InstanceIDToObject(instanceId);
if (asset.GetType() == typeof(BehaviorTreeSO))
if (asset.GetType() == typeof(BehaviorTreeAsset))
{
Show((IBehaviorTree)asset);
Show((IBehaviorTreeContainer)asset);
return true;
}
if (asset.GetType().IsSubclassOf(typeof(BehaviorTreeSO)))
if (asset.GetType().IsSubclassOf(typeof(BehaviorTreeAsset)))
{
var windowTypes = SubclassSearchUtility.FindSubClassTypes(typeof(GraphEditorWindow));
foreach (var windowType in windowTypes)
{
var attribute = windowType.GetCustomAttribute<DefaultAssetTypeAttribute>();
if (attribute != null && attribute.AssetType == asset.GetType())
{
var bt = (IBehaviorTree)asset;
var bt = (IBehaviorTreeContainer)asset;
var window = CreateInstance(windowType) as GraphEditorWindow;
window.RepaintGraphView(bt);
window.titleContent = new GUIContent($"{window.graphView.EditorName} ({bt._Object.name})");
window.Key = bt._Object;
window.titleContent = new GUIContent($"{window.graphView.EditorName} ({bt.Object.name})");
window.Key = bt.Object;
cache[instanceId] = window;
window.Show();
window.Focus();
Expand All @@ -86,7 +86,7 @@ private static void ShowEditorWindow()
string path = EditorUtility.SaveFilePanel("Select ScriptableObject save path", Application.dataPath, "BehaviorTreeSO", "asset");
if (string.IsNullOrEmpty(path)) return;
path = path.Replace(Application.dataPath, string.Empty);
var treeSO = CreateInstance<BehaviorTreeSO>();
var treeSO = CreateInstance<BehaviorTreeAsset>();
AssetDatabase.CreateAsset(treeSO, $"Assets/{path}");
AssetDatabase.SaveAssets();
Show(treeSO);
Expand All @@ -99,7 +99,7 @@ public static bool ContainsEditorWindow(int windowInstanceID)
}
return false;
}
public static void Show(IBehaviorTree bt)
public static void Show(IBehaviorTreeContainer bt)
{
var window = Create<GraphEditorWindow>(bt);
window.Show();
Expand All @@ -112,28 +112,28 @@ public static void Show(IBehaviorTree bt)
/// <typeparam name="T"></typeparam>
/// <typeparam name="K"></typeparam>
/// <returns></returns>
public static T Create<T>(IBehaviorTree bt) where T : GraphEditorWindow
public static T Create<T>(IBehaviorTreeContainer bt) where T : GraphEditorWindow
{
var key = bt._Object.GetHashCode();
var key = bt.Object.GetHashCode();
if (cache.ContainsKey(key))
{
return (T)cache[key];
}
var window = CreateInstance<T>();
window.RepaintGraphView(bt);
window.titleContent = new GUIContent($"{window.graphView.EditorName} ({bt._Object.name})");
window.Key = bt._Object;
window.titleContent = new GUIContent($"{window.graphView.EditorName} ({bt.Object.name})");
window.Key = bt.Object;
cache[key] = window;
return window;
}
private void RepaintGraphView(IBehaviorTree bt)
private void RepaintGraphView(IBehaviorTreeContainer bt)
{
rootVisualElement.Clear();
rootVisualElement.Add(CreateToolBar());
graphView = StructGraphView(bt);
rootVisualElement.Add(graphView);
}
protected virtual BehaviorTreeView StructGraphView(IBehaviorTree bt)
protected virtual BehaviorTreeView StructGraphView(IBehaviorTreeContainer bt)
{
var graphView = new BehaviorTreeView(bt, this);
var infoView = new InfoView(InfoText);
Expand All @@ -151,7 +151,7 @@ private void SaveToSO(string path)
Debug.LogWarning($"<color=#ff2f2f>{graphView.EditorName}</color>: Save failed, ScriptableObject wasn't created!\n{DateTime.Now}");
return;
}
graphView.Commit((IBehaviorTree)treeSO);
graphView.Commit((IBehaviorTreeContainer)treeSO);
string savePath = $"{path}/{Key.name}.asset";
AssetDatabase.CreateAsset(treeSO, savePath);
AssetDatabase.SaveAssets();
Expand All @@ -160,12 +160,13 @@ private void SaveToSO(string path)

private void OnDestroy()
{
int code;
if (Key != null && cache.ContainsKey(code = Key.GetHashCode()))
if (Key == null) return;
int code = Key.GetHashCode();
if (Key != null && cache.TryGetValue(code, out var editor))
{
if (Setting.AutoSave && !Application.isPlaying)
{
if (!cache[code].graphView.Save())
if (!editor.graphView.Save())
{
var msg = "Auto save failed, do you want to discard change?";
if (EditorUtility.DisplayDialog("Warning", msg, "Cancel", "Discard"))
Expand All @@ -179,13 +180,13 @@ private void OnDestroy()
}
return;
}
Debug.Log($"<color=#3aff48>{graphView.EditorName}</color>[{graphView.BehaviorTree._Object.name}] saved succeed! {DateTime.Now}");
Debug.Log($"<color=#3aff48>{graphView.EditorName}</color>[{graphView.Container.Object.name}] saved succeed! {DateTime.Now}");
}
cache.Remove(code);
}
}
/// <summary>
/// Clone the editor window for preventing data lossing when reloading or quitting
/// Clone the editor window for preventing data loss when reloading or quitting
/// </summary>
/// <returns></returns>
protected virtual GraphEditorWindow Clone()
Expand Down Expand Up @@ -237,8 +238,8 @@ private void Reload()
{
if (Key != null)
{
if (Key is GameObject) RepaintGraphView((Key as GameObject).GetComponent<IBehaviorTree>());
else RepaintGraphView(Key as IBehaviorTree);
if (Key is GameObject) RepaintGraphView((Key as GameObject).GetComponent<IBehaviorTreeContainer>());
else RepaintGraphView(Key as IBehaviorTreeContainer);
Repaint();
}
}
Expand Down Expand Up @@ -304,7 +305,7 @@ protected virtual void DrawLeftToolBar()
EditorUtility.SetDirty(setting);
AssetDatabase.SaveAssets();
ShowNotification(new GUIContent("Data Dropped Succeed!"));
graphView.CopyFromTree(data, new Vector3(400, 300));
graphView.CopyFromTree(data.GetBehaviorTree(), new Vector3(400, 300));
}
}
GUI.enabled = true;
Expand All @@ -321,7 +322,7 @@ protected virtual void DrawRightToolBar()
if (GUILayout.Button("Save To Json", EditorStyles.toolbarButton))
{
var serializedData = graphView.SerializeTreeToJson();
string path = EditorUtility.SaveFilePanel("Select json file save path", Setting.LastPath, graphView.BehaviorTree._Object.name, "json");
string path = EditorUtility.SaveFilePanel("Select json file save path", Setting.LastPath, graphView.Container.Object.name, "json");
if (!string.IsNullOrEmpty(path))
{
FileInfo info = new(path);
Expand Down Expand Up @@ -352,11 +353,11 @@ protected virtual void DrawRightToolBar()
}
GUI.enabled = true;
}
protected IBehaviorTree LoadDataFromFile(string path)
protected IBehaviorTreeContainer LoadDataFromFile(string path)
{
try
{
return AssetDatabase.LoadAssetAtPath<BehaviorTreeSO>(path);
return AssetDatabase.LoadAssetAtPath<BehaviorTreeAsset>(path);

}
catch
Expand Down
23 changes: 12 additions & 11 deletions Editor/Core/Editor/ServiceEditorWindow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ static BeginVerticalScrollViewFunc BeginVerticalScrollView
private void OnEnable()
{
searchCache = CreateInstance<BehaviorTreeSearchCache>();
searchCache.allBehaviorTreeSOCache = BehaviorTreeSearchUtility.GetAllBehaviorTreeSO();
searchCache.assetsCache = BehaviorTreeSearchUtility.GetAllBehaviorTreeAssets();
searchCacheSerializedObject = new SerializedObject(searchCache);
searchWindow = CreateInstance<NodeTypeSearchWindow>();
searchWindow.Initialize((T) => searchType = T);
Expand Down Expand Up @@ -85,10 +85,10 @@ private void DrawSerializationService()
{
foreach (var pair in serviceData.serializationCollection.serializationPairs)
{
if (pair.serializedData != null && pair.behaviorTreeSO != null)
if (pair.serializedData != null && pair.behaviorTreeAsset != null)
{
pair.behaviorTreeSO.Deserialize(pair.serializedData.text);
EditorUtility.SetDirty(pair.behaviorTreeSO);
// pair.behaviorTreeContainerAsset.Deserialize(pair.serializedData.text);
EditorUtility.SetDirty(pair.behaviorTreeAsset);
}
}
AssetDatabase.SaveAssets();
Expand Down Expand Up @@ -132,9 +132,9 @@ private void DrawSearchingService()
else
{
//Use cache for quick search
searchCache.searchResult = BehaviorTreeSearchUtility.SearchBehaviorTreeSO(searchType, serviceData, searchCache.allBehaviorTreeSOCache);
searchCache.searchResult = BehaviorTreeSearchUtility.SearchBehaviorTreeSO(searchType, serviceData, searchCache.assetsCache);
if (!string.IsNullOrEmpty(newName))
searchCache.searchResult = searchCache.searchResult.Where(x => x.behaviorTreeSO.name.Contains(newName)).ToList();
searchCache.searchResult = searchCache.searchResult.Where(x => x.behaviorTreeAsset.name.Contains(newName)).ToList();
}
searchCacheSerializedObject.ApplyModifiedProperties();
}
Expand All @@ -146,19 +146,20 @@ private void ExportAll()
string path = EditorUtility.OpenFolderPanel("Choose json files saving path", Application.dataPath, "");
if (string.IsNullOrEmpty(path)) return;
List<string> savePaths = new();
for (int i = 0; i < serviceData.serializationCollection.serializationPairs.Count; i++)
for (int i = 0; i < serviceData.serializationCollection.serializationPairs.Length; i++)
{
var pair = serviceData.serializationCollection.serializationPairs[i];
var serializedData = SerializeUtility.SerializeTree(pair.behaviorTreeSO, true, true);
string folderPath = path + $"/{pair.behaviorTreeSO.GetType().Name}";
var tree = pair.behaviorTreeAsset.GetBehaviorTree();
var serializedData = tree.Serialize(true, true);
string folderPath = path + $"/{pair.behaviorTreeAsset.GetType().Name}";
if (!Directory.Exists(folderPath)) Directory.CreateDirectory(folderPath);
string savePath = $"{folderPath}/{pair.behaviorTreeSO.name}_{serviceData.serializationCollection.guids[i]}.json";
string savePath = $"{folderPath}/{pair.behaviorTreeAsset.name}_{serviceData.serializationCollection.guids[i]}.json";
savePaths.Add(savePath);
File.WriteAllText(savePath, serializedData);
}
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
for (int i = 0; i < serviceData.serializationCollection.serializationPairs.Count; i++)
for (int i = 0; i < serviceData.serializationCollection.serializationPairs.Length; i++)
{
serviceData.serializationCollection.serializationPairs[i].serializedData = AssetDatabase.LoadAssetAtPath<TextAsset>(GetRelativePath(savePaths[i]));
}
Expand Down
Loading

0 comments on commit 1337482

Please sign in to comment.