Modular Database Tools

Extracted all inspector code for database inspector into a single class per supported field type and wrote reflection code to invoke them automatically
Removed all Aetheria-specific code from database tools
Database View editor is now abstract and supports arbitrary grouping of entry types; specific users must implement their own database view
This commit is contained in:
Reinier Vens 2021-03-31 04:07:11 +01:00
commit 526a737a4d
72 changed files with 1674 additions and 1624 deletions

View file

@ -0,0 +1,46 @@
using System;
using System.IO;
using UnityEditor;
using UnityEngine;
public class AetheriaDatabaseView : DatabaseListView
{
// Singleton to avoid multiple instances of window.
private static DatabaseListView _instance;
private string tableName;
public static DatabaseListView Instance => _instance ? _instance : GetWindow<AetheriaDatabaseView>();
[MenuItem("Window/Aetheria/Database Tools")]
static void Init() => Instance.Show();
private void Awake()
{
_instance = this;
}
protected override string DatabaseName => "Aetheria";
protected override string FilePath => Path.Combine(new DirectoryInfo(Application.dataPath).Parent.CreateSubdirectory("GameData").FullName, "AetherDB.msgpack");
protected override DatabaseEntryGroup[] Groupers => new DatabaseEntryGroup[]
{
new DatabaseEntryGroup<SimpleCommodityData,SimpleCommodityCategory>(
data => data.Category,
category => Enum.GetName(typeof(SimpleCommodityCategory), category),
(data, category) => data.Category = category ),
new DatabaseEntryGroup<CompoundCommodityData, CompoundCommodityCategory>(
data => data.Category,
category => Enum.GetName(typeof(CompoundCommodityCategory), category),
(data, category) => data.Category = category ),
new DatabaseEntryGroup<GearData, HardpointType>(
data => data.HardpointType,
type => Enum.GetName(typeof(HardpointType), type),
(data, type) => data.Hardpoint = type),
// new DatabaseEntryGroup<GearData, Guid>(
// data => data.Manufacturer,
// factionID => cultCache.Get<Faction>(factionID).ShortName,
// (data, faction) => data.Manufacturer = faction),
new DatabaseEntryGroup<HullData, HullType>(
data => data.HullType,
type => Enum.GetName(typeof(HullType), type),
(data, type) => data.HullType = type)
};
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 4016d25951e246a184441b2aae75eba0
timeCreated: 1617151686

View file

@ -0,0 +1,31 @@
using System;
public abstract class BaseInspector<T>
{
protected const int width = 150;
protected const int labelWidth = 20;
protected const int toggleWidth = 18;
protected const int arrowWidth = 22;
public abstract T Inspect(string label, T value, object parent, DatabaseInspector inspectorWindow);
}
public abstract class BaseInspector<T, A> where A : Attribute
{
protected const int width = 150;
protected const int labelWidth = 20;
protected const int toggleWidth = 18;
protected const int arrowWidth = 22;
public abstract T Inspect(string label, T value, object parent, DatabaseInspector inspectorWindow, A attribute);
}
public abstract class BaseInspector<T, A, B> where A : Attribute where B : Attribute
{
protected const int width = 150;
protected const int labelWidth = 20;
protected const int toggleWidth = 18;
protected const int arrowWidth = 22;
public abstract T Inspect(string label, T value, object parent, DatabaseInspector inspectorWindow, A attributeA, B attributeB);
}

File diff suppressed because it is too large Load diff

View file

@ -14,89 +14,119 @@ using UnityEditor;
using UnityEngine;
using static UnityEditor.EditorGUILayout;
public class DatabaseListView : EditorWindow
public abstract class DatabaseListView : EditorWindow
{
// Singleton to avoid multiple instances of window.
private static DatabaseListView _instance;
public static DatabaseListView Instance => _instance ? _instance : GetWindow<DatabaseListView>();
[MenuItem("Window/GameCult/Database Tools")]
static void Init() => Instance.Show();
private void Awake()
{
_instance = this;
}
public static GUIStyle ListStyleOdd;
public static GUIStyle ListStyleEven;
public Guid SelectedItem;
public GUIStyle SelectedStyle;
public static RethinkDB R = RethinkDB.R;
private DatabaseCache _databaseCache;
private bool[] _itemTypeFoldouts;
private bool _itemsFoldout;
private bool _compoundFoldout;
private bool _simpleFoldout;
private bool _commoditiesFoldout;
//private bool _consumablesFoldout;
private Type[] _itemTypes;
private bool _listItemStyle;
private GUIStyle _listStyleOdd;
private GUIStyle _listStyleEven;
protected CultCache cultCache;
private static DatabaseInspector _inspector;
private Type[] _entryTypes;
private bool[] _entryFoldouts;
private bool[] _typeFoldouts;
private string _connectionString;
private const float LineHeight = 20;
private Vector2 _view;
private RethinkQueryStatus _queryStatus;
private HashSet<string> _itemGroupFoldouts = new HashSet<string>();
private HashSet<Guid> _itemManufacturerFoldouts = new HashSet<Guid>();
private HashSet<(Guid, HardpointType)> _itemManufacturerTypeFoldouts = new HashSet<(Guid, HardpointType)>();
private string _filePath => Path.Combine(new DirectoryInfo(Application.dataPath).Parent.CreateSubdirectory("GameData").FullName, _fileName);
private string _fileName = "AetherDB.msgpack";
private HashSet<int> _groupFoldouts = new HashSet<int>();
protected abstract string DatabaseName { get; }
protected abstract string FilePath { get; }
protected virtual DatabaseEntryGroup[] Groupers => new DatabaseEntryGroup[] { };
protected class DatabaseEntryGroup<T, K> : DatabaseEntryGroup where T : DatabaseEntry
{
public Func<T,K> GroupSelector { get; }
public Func<K,string> GroupLabel { get; }
public Action<T, K> Activator { get; }
public DatabaseEntryGroup(Func<T, K> groupSelector, Func<K, string> groupLabel, Action<T, K> activator)
{
GroupSelector = groupSelector;
GroupLabel = groupLabel;
Activator = activator;
}
public override bool CanGroup(Type type)
{
return typeof(T) == type;
}
public override object SelectGroup(DatabaseEntry o)
{
if (o is T t) return GroupSelector(t);
return null;
}
public override string GetGroupName(object o)
{
if (o is K k) return GroupLabel(k);
return "ERROR";
}
public override int HashGroup(object o)
{
if (o is K k) return k.GetHashCode();
return 0;
}
public override void Activate(DatabaseEntry o, object g)
{
if(o is T t && g is K k) Activator(t, k);
throw new ArgumentException(
$"Entry group activation failed! Expected: object type {typeof(T)}, group type {typeof(K)}; received: object type {o.GetType()}, group type {g.GetType()}");
}
}
protected abstract class DatabaseEntryGroup
{
public abstract bool CanGroup(Type type);
public abstract object SelectGroup(DatabaseEntry o);
public abstract string GetGroupName(object o);
public abstract int HashGroup(object o);
public abstract void Activate(DatabaseEntry o, object g);
}
public Color LabelColor => EditorGUIUtility.isProSkin ? Color.white : Color.black;
private bool _listItemStyle;
public GUIStyle ListItemStyle =>
(_listItemStyle = !_listItemStyle) ? _listStyleEven : _listStyleOdd;
(_listItemStyle = !_listItemStyle) ? ListStyleEven : ListStyleOdd;
void OnEnable()
{
ListStyleOdd = new GUIStyle
{
normal = {background = EditorGUIUtility.isProSkin ? XKCDColors.DarkGrey.ToTexture() : XKCDColors.LightGrey.ToTexture()},
margin = new RectOffset(0, 0, 0, 0)
};
ListStyleEven = new GUIStyle
{
normal = {background = EditorGUIUtility.isProSkin ? Color.Lerp(XKCDColors.DarkGrey,Color.black,.5f).ToTexture() : Color.Lerp(XKCDColors.LightGrey,Color.white,.5f).ToTexture()},
margin = new RectOffset(0, 0, 0, 0)
};
//_filePath = ;
// Create database cache
_databaseCache = new DatabaseCache(_filePath);
cultCache = new CultCache(FilePath);
// var onInsert = new Action<DatabaseEntry>(entry =>
// {
// });
// _databaseCache.OnDataInsertLocal += onInsert;
// _databaseCache.OnDataInsertRemote += onInsert;
cultCache.OnDataUpdateLocal += _ => Repaint();
cultCache.OnDataInsertLocal += _ => Repaint();
cultCache.OnDataDeleteLocal += _ => Repaint();
cultCache.OnDataUpdateRemote += _ => EditorDispatcher.Dispatch(Repaint);
cultCache.OnDataInsertRemote += _ => EditorDispatcher.Dispatch(Repaint);
cultCache.OnDataDeleteRemote += _ => EditorDispatcher.Dispatch(Repaint);
// var onDelete = new Action<DatabaseEntry>(entry =>
// {
// });
// _databaseCache.OnDataDeleteLocal += onDelete;
// _databaseCache.OnDataDeleteRemote += onDelete;
_databaseCache.OnDataUpdateLocal += _ => Repaint();
_databaseCache.OnDataInsertLocal += _ => Repaint();
_databaseCache.OnDataDeleteLocal += _ => Repaint();
_databaseCache.OnDataUpdateRemote += _ => EditorDispatcher.Dispatch(Repaint);
_databaseCache.OnDataInsertRemote += _ => EditorDispatcher.Dispatch(Repaint);
_databaseCache.OnDataDeleteRemote += _ => EditorDispatcher.Dispatch(Repaint);
DatabaseInspector.DatabaseCache = _databaseCache;
DatabaseInspector.CultCache = cultCache;
_inspector = DatabaseInspector.Instance;
_inspector.Show();
_itemTypes = typeof(ItemData).GetAllChildClasses()
.Where(t => t.GetCustomAttribute<InspectableAttribute>() != null).ToArray();
_entryTypes = typeof(DatabaseEntry).GetAllChildClasses()
.Where(t => t.GetCustomAttribute<InspectableAttribute>() != null && !typeof(ItemData).IsAssignableFrom(t)).ToArray();
.Where(t => t.GetCustomAttribute<InspectableAttribute>() != null).ToArray();
_itemTypeFoldouts = new bool[_itemTypes.Length];
_entryFoldouts = new bool[_entryTypes.Length];
_typeFoldouts = new bool[_entryTypes.Length];
if (EditorPrefs.HasKey("RethinkDB.URL"))
_connectionString = EditorPrefs.GetString("RethinkDB.URL");
@ -108,20 +138,9 @@ public class DatabaseListView : EditorWindow
private void InitStyles()
{
var isDark = EditorGUIUtility.isProSkin;
_listStyleOdd = new GUIStyle
{
normal = {background = isDark ? XKCDColors.DarkGrey.ToTexture() : XKCDColors.LightGrey.ToTexture()},
margin = new RectOffset(0, 0, 0, 0)
};
_listStyleEven = new GUIStyle
{
normal = {background = isDark ? Color.Lerp(XKCDColors.DarkGrey,Color.black,.5f).ToTexture() : Color.Lerp(XKCDColors.LightGrey,Color.white,.5f).ToTexture()},
margin = new RectOffset(0, 0, 0, 0)
};
SelectedStyle = new GUIStyle
{
normal = {background = isDark ? XKCDColors.DarkGreyBlue.ToTexture() : XKCDColors.Greyblue.ToTexture()},
normal = {background = EditorGUIUtility.isProSkin ? XKCDColors.DarkGreyBlue.ToTexture() : XKCDColors.Greyblue.ToTexture()},
margin = new RectOffset(0, 0, 0, 0)
};
}
@ -142,7 +161,7 @@ public class DatabaseListView : EditorWindow
{
EditorPrefs.SetString("RethinkDB.URL", _connectionString);
JsonKnownTypesSettingsManager.RegisterTypeAssembly<ItemData>();
_queryStatus = RethinkConnection.RethinkConnect(_databaseCache, _connectionString);
_queryStatus = RethinkConnection.RethinkConnect(cultCache, _connectionString, DatabaseName);
}
// if (GUILayout.Button("Connect All"))
// {
@ -155,21 +174,21 @@ public class DatabaseListView : EditorWindow
//_fileName = TextField(_fileName);
if (GUILayout.Button("Save"))
{
_databaseCache.Save();
cultCache.Save();
Debug.Log("Local DB Cache Saved!");
}
if (GUILayout.Button("Load"))
{
_databaseCache.Load();
cultCache.Load();
Debug.Log("Loaded DB From Local Cache!");
}
}
if (_queryStatus != null && _queryStatus.RetrievedItems < _queryStatus.GalaxyEntries + _queryStatus.ItemsEntries)
if (_queryStatus != null && _queryStatus.RetrievedEntries < _queryStatus.TotalEntries)
{
var progressRect = GetControlRect(false, 20);
EditorGUI.ProgressBar(progressRect, (float)_queryStatus.RetrievedItems/(_queryStatus.GalaxyEntries + _queryStatus.ItemsEntries), "Sync Progress");
EditorGUI.ProgressBar(progressRect, (float)_queryStatus.RetrievedEntries/_queryStatus.TotalEntries, "Sync Progress");
}
GUILayout.Space(5);
@ -183,228 +202,100 @@ public class DatabaseListView : EditorWindow
GUILayout.Width(EditorGUIUtility.currentViewWidth),
GUILayout.ExpandHeight(true));
// if(GUILayout.Button("Log Cache Count"))
// Debug.Log($"Cache contains {_databaseCache.AllEntries.Count()} elements");
using (var h = new HorizontalScope(ListItemStyle))
{
_itemsFoldout = Foldout(_itemsFoldout, "Items", true);
}
if (_itemsFoldout)
{
var items = _databaseCache.AllEntries.Where(item => item is ItemData).Cast<ItemData>().ToArray();
for (var i = 0; i < _itemTypes.Length; i++)
{
using (var h = new HorizontalScope(ListItemStyle))
{
GUILayout.Space(10);
_itemTypeFoldouts[i] = Foldout(_itemTypeFoldouts[i],
((NameAttribute) _itemTypes[i].GetCustomAttribute(typeof(NameAttribute)))?.Name ?? FormatTypeName(_itemTypes[i].Name),
true);
}
if (_itemTypeFoldouts[i])
{
if (_itemTypes[i] == typeof(SimpleCommodityData) ||
_itemTypes[i] == typeof(CompoundCommodityData) ||
_itemTypes[i] == typeof(HullData))
{
var typedItems = items
.Where(e => e.GetType() == _itemTypes[i])
.OrderBy(item => item.Name);
IEnumerable<IGrouping<string, ItemData>> itemGroups = new List<IGrouping<string, ItemData>>();
if(_itemTypes[i] == typeof(SimpleCommodityData))
itemGroups = typedItems.GroupBy(item => Enum.GetName(typeof(SimpleCommodityCategory), (item as SimpleCommodityData).Category));
else if(_itemTypes[i] == typeof(CompoundCommodityData))
itemGroups = typedItems.GroupBy(item => Enum.GetName(typeof(CompoundCommodityCategory), (item as CompoundCommodityData).Category));
else if (_itemTypes[i] == typeof(HullData))
itemGroups = typedItems.GroupBy(item => Enum.GetName(typeof(HullType), (item as HullData).HullType));
else itemGroups = typedItems.GroupBy(item => "All");
foreach (var itemGroup in itemGroups)
{
using (var h = new HorizontalScope(ListItemStyle))
{
GUILayout.Space(20);
if (Foldout(_itemGroupFoldouts.Contains(itemGroup.Key), FormatTypeName(itemGroup.Key), true))
_itemGroupFoldouts.Add(itemGroup.Key);
else _itemGroupFoldouts.Remove(itemGroup.Key);
}
if (_itemGroupFoldouts.Contains(itemGroup.Key))
{
foreach (var item in itemGroup)
{
var style = ListItemStyle;
var selected = SelectedItem == item.ID;
using (new HorizontalScope(selected?SelectedStyle:style))
{
using (var h = new HorizontalScope())
{
if (h.rect.Contains(currentEvent.mousePosition))
{
if (currentEventType == EventType.MouseDrag)
{
DragAndDrop.PrepareStartDrag();
DragAndDrop.SetGenericData("Item", item.ID);
DragAndDrop.StartDrag("Database Item");
}
else if (currentEventType == EventType.MouseUp)
Select(item);
}
GUILayout.Space(30);
GUILayout.Label(item.Name, selected ? EditorStyles.whiteLabel : GUI.skin.label);
}
}
}
}
}
}
else
{
if (!typeof(EquippableItemData).IsAssignableFrom(_itemTypes[i]))
throw new InvalidCastException($"Type {_itemTypes[i].Name} is invalid! Expected equippable item.");
var typedItems = items
.Where(e => e.GetType() == _itemTypes[i])
.Cast<EquippableItemData>()
.OrderBy(item => item.Name);
var manufacturerGroups = typedItems.GroupBy(item => item.Manufacturer);
foreach (var manufacturerGroup in manufacturerGroups)
{
var manufacturer = _databaseCache.Get<Faction>(manufacturerGroup.Key);
var manufacturerName = manufacturer?.Name ?? "None";
using (var h = new HorizontalScope(ListItemStyle))
{
GUILayout.Space(20);
if (Foldout(_itemManufacturerFoldouts.Contains(manufacturerGroup.Key), manufacturerName, true))
_itemManufacturerFoldouts.Add(manufacturerGroup.Key);
else _itemManufacturerFoldouts.Remove(manufacturerGroup.Key);
}
if (_itemManufacturerFoldouts.Contains(manufacturerGroup.Key))
{
if (_itemTypes[i] == typeof(GearData) || _itemTypes[i] == typeof(WeaponItemData))
{
var itemGroups = manufacturerGroup.GroupBy(item => item.HardpointType);
foreach (var itemGroup in itemGroups)
{
using (var h = new HorizontalScope(ListItemStyle))
{
GUILayout.Space(30);
if (Foldout(_itemManufacturerTypeFoldouts.Contains((manufacturerGroup.Key, itemGroup.Key)), Enum.GetName(typeof(HardpointType), itemGroup.Key), true))
_itemManufacturerTypeFoldouts.Add((manufacturerGroup.Key, itemGroup.Key));
else _itemManufacturerTypeFoldouts.Remove((manufacturerGroup.Key, itemGroup.Key));
}
if (_itemManufacturerTypeFoldouts.Contains((manufacturerGroup.Key, itemGroup.Key)))
{
foreach (var item in itemGroup)
{
var style = ListItemStyle;
var selected = SelectedItem == item.ID;
using (new HorizontalScope(selected?SelectedStyle:style))
{
using (var h = new HorizontalScope())
{
if (h.rect.Contains(currentEvent.mousePosition))
{
if (currentEventType == EventType.MouseDrag)
{
DragAndDrop.PrepareStartDrag();
DragAndDrop.SetGenericData("Item", item.ID);
DragAndDrop.StartDrag("Database Item");
}
else if (currentEventType == EventType.MouseUp)
Select(item);
}
GUILayout.Space(40);
GUILayout.Label(item.Name, selected ? EditorStyles.whiteLabel : GUI.skin.label);
}
}
}
}
}
}
else
{
foreach (var item in manufacturerGroup)
{
var style = ListItemStyle;
var selected = SelectedItem == item.ID;
using (new HorizontalScope(selected?SelectedStyle:style))
{
using (var h = new HorizontalScope())
{
if (h.rect.Contains(currentEvent.mousePosition))
{
if (currentEventType == EventType.MouseDrag)
{
DragAndDrop.PrepareStartDrag();
DragAndDrop.SetGenericData("Item", item.ID);
DragAndDrop.StartDrag("Database Item");
}
else if (currentEventType == EventType.MouseUp)
Select(item);
}
GUILayout.Space(30);
GUILayout.Label(item.Name, selected ? EditorStyles.whiteLabel : GUI.skin.label);
}
}
}
}
}
}
}
using (var h = new HorizontalScope(ListItemStyle))
{
if(GUI.Button(h.rect, GUIContent.none, GUIStyle.none))
CreateItem(_itemTypes[i]);
GUILayout.Space(20);
GUILayout.Label("New " + FormatTypeName(_itemTypes[i].Name));
// var rect = GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
// GUI.DrawTexture(rect, Icons.Instance.plus, ScaleMode.StretchToFill, true, 1, LabelColor, 0, 0);
}
}
}
}
//var entries = _databaseCache.AllEntries.Where(item => !(item is ItemData)).ToArray();
for (var i = 0; i < _entryTypes.Length; i++)
{
using (var h = new HorizontalScope(ListItemStyle))
{
_entryFoldouts[i] = Foldout(_entryFoldouts[i],
_typeFoldouts[i] = Foldout(_typeFoldouts[i],
((NameAttribute) _entryTypes[i].GetCustomAttribute(typeof(NameAttribute)))?.Name ?? FormatTypeName(_entryTypes[i].Name),
true);
}
if (_entryFoldouts[i])
if (_typeFoldouts[i])
{
int index = 0;
foreach (var entry in _databaseCache.GetAll(_entryTypes[i]).OrderBy(entry=>entry is INamedEntry namedEntry ? namedEntry.EntryName : entry.ID.ToString()))
// TODO: NESTED GROUPS!
var entries = cultCache.GetAll(_entryTypes[i])
.OrderBy(entry => entry is INamedEntry namedEntry ? namedEntry.EntryName : entry.ID.ToString());
var grouper = Groupers.FirstOrDefault(g => g.CanGroup(_entryTypes[i]));
if (grouper != null)
{
index++;
var style = ListItemStyle;
var selected = SelectedItem == entry.ID;
using (var h = new HorizontalScope(selected?SelectedStyle:style))
var groups = entries.GroupBy(o => grouper.SelectGroup(o));
foreach (var group in groups)
{
if (h.rect.Contains(currentEvent.mousePosition))
var groupHash = grouper.HashGroup(group.Key);
var groupName = grouper.GetGroupName(group.Key);
using (var h = new HorizontalScope(ListItemStyle))
{
if (currentEventType == EventType.MouseDrag)
{
DragAndDrop.PrepareStartDrag();
DragAndDrop.SetGenericData("Item", entry.ID);
DragAndDrop.StartDrag("Database Item");
}
else if (currentEventType == EventType.MouseUp)
Select(entry);
GUILayout.Space(10);
if (Foldout(_groupFoldouts.Contains(groupHash), FormatTypeName(groupName), true))
_groupFoldouts.Add(groupHash);
else _groupFoldouts.Remove(groupHash);
}
if (_groupFoldouts.Contains(groupHash))
{
int index = 0;
foreach (var entry in group)
{
index++;
var style = ListItemStyle;
var selected = SelectedItem == entry.ID;
using (new HorizontalScope(selected?SelectedStyle:style))
{
using (var h = new HorizontalScope())
{
if (h.rect.Contains(currentEvent.mousePosition))
{
if (currentEventType == EventType.MouseDrag)
{
DragAndDrop.PrepareStartDrag();
DragAndDrop.SetGenericData("Item", entry.ID);
DragAndDrop.StartDrag("Database Item");
}
else if (currentEventType == EventType.MouseUp)
Select(entry);
}
GUILayout.Space(20);
GUILayout.Label((entry as INamedEntry)?.EntryName ?? index.ToString(), selected ? EditorStyles.whiteLabel : GUI.skin.label);
}
}
}
using (var h = new HorizontalScope(ListItemStyle))
{
if(GUI.Button(h.rect, GUIContent.none, GUIStyle.none))
CreateItem(_entryTypes[i], entry => grouper.Activate(entry, group.Key));
GUILayout.Space(20);
GUILayout.Label($"New {groupName}");
}
}
}
}
else
{
int index = 0;
foreach (var entry in entries)
{
index++;
var style = ListItemStyle;
var selected = SelectedItem == entry.ID;
using (var h = new HorizontalScope(selected?SelectedStyle:style))
{
if (h.rect.Contains(currentEvent.mousePosition))
{
if (currentEventType == EventType.MouseDrag)
{
DragAndDrop.PrepareStartDrag();
DragAndDrop.SetGenericData("Item", entry.ID);
DragAndDrop.StartDrag("Database Item");
}
else if (currentEventType == EventType.MouseUp)
Select(entry);
}
GUILayout.Space(10);
GUILayout.Label((entry as INamedEntry)?.EntryName ?? index.ToString(), selected ? EditorStyles.whiteLabel : GUI.skin.label);
}
GUILayout.Space(10);
GUILayout.Label((entry as INamedEntry)?.EntryName ?? index.ToString(), selected ? EditorStyles.whiteLabel : GUI.skin.label);
}
}
@ -413,9 +304,7 @@ public class DatabaseListView : EditorWindow
if(GUI.Button(h.rect, GUIContent.none, GUIStyle.none))
CreateItem(_entryTypes[i]);
GUILayout.Space(10);
GUILayout.Label("New " + _entryTypes[i].Name);
// var rect = GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
// GUI.DrawTexture(rect, Icons.Instance.plus, ScaleMode.StretchToFill, true, 1, LabelColor, 0, 0);
GUILayout.Label($"New {_entryTypes[i].Name}");
}
}
}
@ -434,7 +323,7 @@ public class DatabaseListView : EditorWindow
{
SelectedItem = item.ID;
Repaint();
_inspector.entry = _databaseCache.Get(SelectedItem);
_inspector.entry = cultCache.Get(SelectedItem);
_inspector.Repaint();
}
@ -444,7 +333,7 @@ public class DatabaseListView : EditorWindow
if(newEntry is INamedEntry entry)
entry.EntryName = $"New {FormatTypeName(type.Name)}";
onCreate?.Invoke(newEntry);
_databaseCache.Add(newEntry);
cultCache.Add(newEntry);
Select(newEntry);
return newEntry;
}

View file

@ -1,9 +0,0 @@
public abstract class InspectorBase<T>
{
protected const int width = 150;
protected const int labelWidth = 20;
protected const int toggleWidth = 18;
protected const int arrowWidth = 22;
public abstract T Inspect(string label, T value);
}

View file

@ -0,0 +1,183 @@
using System;
using System.Linq;
using Unity.Mathematics;
using UnityEditor;
using UnityEngine;
using static UnityEditor.EditorGUILayout;
using static Unity.Mathematics.math;
public class StatReferenceInspector : BaseInspector<StatReference>
{
public override StatReference Inspect(string label, StatReference value, object parent, DatabaseInspector inspectorWindow)
{
using (new HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
using (new VerticalScope())
{
var targetObjects = typeof(BehaviorData).GetAllChildClasses()
.Concat(typeof(EquippableItemData).GetAllChildClasses()).ToArray();
var objectNames = targetObjects.Select(b => b.Name).ToArray();
var selectedIndex = Array.IndexOf(objectNames, value.Target);
if (selectedIndex == -1)
{
selectedIndex = 0;
GUI.changed = true;
}
using (new HorizontalScope())
{
GUILayout.Label("Target", GUILayout.Width(width));
var newSelection = Popup(selectedIndex, objectNames);
if (newSelection != selectedIndex)
GUI.changed = true;
value.Target = objectNames[newSelection];
}
using (new HorizontalScope())
{
GUILayout.Label("Stat", GUILayout.Width(width));
var stats = targetObjects[selectedIndex].GetFields()
.Where(f => f.FieldType == typeof(PerformanceStat)).ToArray();
if(stats.Length==0)
GUILayout.Label("No Stats!");
else
{
var statNames = stats.Select(s => s.Name).ToArray();
var selectedStatIndex = Array.IndexOf(statNames, value.Stat);
if (selectedStatIndex == -1)
{
selectedStatIndex = 0;
GUI.changed = true;
}
var newSelection = Popup(selectedStatIndex, statNames);
if (newSelection != selectedStatIndex)
GUI.changed = true;
value.Stat = statNames[newSelection];
}
}
}
}
return value;
}
}
public class PerformanceStatInspector : BaseInspector<PerformanceStat>
{
public override PerformanceStat Inspect(string label, PerformanceStat value, object parent, DatabaseInspector inspectorWindow)
{
if(value == null)
value = new PerformanceStat();
using (new VerticalScope())
{
using (new HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
GUILayout.Label("Min", EditorStyles.miniLabel, GUILayout.Width(labelWidth));
value.Min = DelayedFloatField(value.Min);
GUILayout.Label("Max", EditorStyles.miniLabel, GUILayout.Width(labelWidth + 5));
value.Max = DelayedFloatField(value.Max);
}
// Only display heat, durability and quality effects if the stat actually varies
if (Math.Abs(value.Min - value.Max) > .0001f)
{
using (new HorizontalScope())
{
GUILayout.Label("", GUILayout.Width(width));
GUILayout.Label("H", EditorStyles.miniLabel, GUILayout.Width(labelWidth));
value.HeatExponentMultiplier = DelayedFloatField(value.HeatExponentMultiplier);
GUILayout.Label("D", EditorStyles.miniLabel, GUILayout.Width(labelWidth));
value.DurabilityExponentMultiplier = DelayedFloatField(value.DurabilityExponentMultiplier);
GUILayout.Label("Q", EditorStyles.miniLabel, GUILayout.Width(labelWidth));
value.QualityExponent = DelayedFloatField(value.QualityExponent);
}
}
Space();
}
return value;
}
}
public class ShapeInspector : BaseInspector<Shape>
{
private Material _schematicMat = new Material(Shader.Find("Legacy Shaders/Particles/Additive"));
public override Shape Inspect(string label, Shape value, object parent, DatabaseInspector inspectorWindow)
{
var hull = parent as HullData;
if(value == null)
{
value = new Shape(1, 1);
value[int2(0)] = true;
}
using (new VerticalScope())
{
Texture2D schematic = null;
if(hull != null && !string.IsNullOrEmpty(hull.Schematic))
schematic = AssetDatabase.LoadAssetAtPath<Texture2D>(hull.Schematic);
using (new HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
GUILayout.Label("Size", GUILayout.ExpandWidth(false));
if(schematic == null)
{
GUILayout.Label("X", GUILayout.Width(labelWidth));
value.Width = DelayedIntField(value.Width);
GUILayout.Label("Y", GUILayout.Width(labelWidth));
value.Height = DelayedIntField(value.Height);
}
else
{
GUILayout.Label("X", GUILayout.Width(labelWidth));
value.Width = DelayedIntField(value.Width);
value.Height = Mathf.RoundToInt(value.Width * ((float)schematic.height / schematic.width));
GUILayout.Label("Y", GUILayout.Width(labelWidth));
LabelField($"{value.Height}");
}
}
using (new HorizontalScope())
{
GUILayout.Label("", GUILayout.Width(width));
using (var a = new VerticalScope())
{
if(schematic != null)
{
EditorGUI.DrawPreviewTexture(a.rect, schematic, _schematicMat);
}
for (var y = value.Height - 1; y >= 0; y--)
{
using (new HorizontalScope())
{
for (var x = 0; x < value.Width; x++)
{
var oldColor = GUI.backgroundColor;
if(hull != null)
{
var hardpoint = hull.Hardpoints
.FirstOrDefault(hp =>
hp.Shape.Coordinates
.Select(v => v + hp.Position)
.Any(v => v.x == x && v.y == y));
if (hardpoint != null)
GUI.backgroundColor = hardpoint.TintColor.ToColor();
}
value[int2(x, y)] = Toggle(value[int2(x, y)], GUILayout.Width(toggleWidth));
GUI.backgroundColor = oldColor;
}
}
}
}
GUILayout.FlexibleSpace();
}
}
return value;
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 57d0bc090768458b9428efd7a8a33741
timeCreated: 1617069994

View file

@ -0,0 +1,39 @@
using System.Linq;
using Unity.Mathematics;
using UnityEditor;
using UnityEngine;
using static UnityEditor.EditorGUILayout;
using static Unity.Mathematics.math;
public class AnimationCurveFloat4Inspector : BaseInspector<float4[]>
{
public override float4[] Inspect(string label, float4[] value, object parent, DatabaseInspector inspectorWindow)
{
var val = value != null && value.Length > 0
? value.ToCurve()
: new AnimationCurve();
using (var h = new EditorGUILayout.HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
val = CurveField(val, Color.yellow, new Rect(0, 0, 1, 1));
}
return val.keys.Select(k => float4(k.time, k.value, k.inTangent, k.outTangent)).ToArray();
}
}
public class AnimationCurveInspect : BaseInspector<AnimationCurve>
{
public override AnimationCurve Inspect(string label, AnimationCurve value, object parent, DatabaseInspector inspectorWindow)
{
using (var h = new HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
if (value == null)
value = new AnimationCurve();
value = CurveField(value, Color.yellow, new Rect(0, 0, 1, 1));
}
return value;
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: c89e0e7eb9f243cbbce28df59f6fb1c9
timeCreated: 1617066399

View file

@ -0,0 +1,152 @@
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using static UnityEditor.EditorGUILayout;
public class DatabaseLinkInspector : BaseInspector<Guid, InspectableDatabaseLinkAttribute>
{
public override Guid Inspect(string label, Guid value, object parent, DatabaseInspector inspectorWindow, InspectableDatabaseLinkAttribute link)
{
LabelField(label, EditorStyles.boldLabel);
var valueEntry = DatabaseInspector.CultCache.Get(value);
using (var h = new HorizontalScope(GUI.skin.box))
{
GUILayout.Label((valueEntry as INamedEntry)?.EntryName ?? valueEntry?.ID.ToString() ?? $"Assign a {link.EntryType.Name} by dragging from the list panel.");
if (h.rect.Contains(Event.current.mousePosition) && (Event.current.type == EventType.DragUpdated || Event.current.type == EventType.DragPerform))
{
var guid = (Guid) DragAndDrop.GetGenericData("Item");
var dragEntry = DatabaseInspector.CultCache.Get(guid);
var dragValid = dragEntry != null && link.EntryType.IsInstanceOfType(dragEntry) && dragEntry != valueEntry;
if(Event.current.type == EventType.DragUpdated)
DragAndDrop.visualMode = dragValid ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Rejected;
else if(Event.current.type == EventType.DragPerform)
{
if (dragValid)
{
DragAndDrop.AcceptDrag();
GUI.changed = true;
return guid;
}
}
}
if (GUILayout.Button("-", GUILayout.Width((EditorGUIUtility.singleLineHeight - 3)*2), GUILayout.Height(EditorGUIUtility.singleLineHeight-3)))
{
return Guid.Empty;
}
}
return value;
}
}
public class DatabaseLinkObjectInspector<T> : BaseInspector<DatabaseLink<T>> where T : DatabaseEntry
{
public override DatabaseLink<T> Inspect(string label, DatabaseLink<T> value, object parent, DatabaseInspector inspectorWindow)
{
if (value == null)
value = new DatabaseLink<T>{Cache = DatabaseInspector.CultCache};
LabelField(label, EditorStyles.boldLabel);
var valueEntry = value.Value;
using (var h = new HorizontalScope(GUI.skin.box))
{
GUILayout.Label((valueEntry as INamedEntry)?.EntryName ?? valueEntry?.ID.ToString() ?? $"Assign a {typeof(T).Name} by dragging from the list panel.");
if (h.rect.Contains(Event.current.mousePosition) && (Event.current.type == EventType.DragUpdated || Event.current.type == EventType.DragPerform))
{
var guid = (Guid) DragAndDrop.GetGenericData("Item");
var dragEntry = DatabaseInspector.CultCache.Get(guid);
var dragValid = dragEntry is T && dragEntry != valueEntry;
if(Event.current.type == EventType.DragUpdated)
DragAndDrop.visualMode = dragValid ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Rejected;
else if(Event.current.type == EventType.DragPerform)
{
if (dragValid)
{
DragAndDrop.AcceptDrag();
value.LinkID = guid;
return value;
}
}
}
if (GUILayout.Button("-", GUILayout.Width((EditorGUIUtility.singleLineHeight - 3)*2), GUILayout.Height(EditorGUIUtility.singleLineHeight-3)))
{
value.LinkID = Guid.Empty;
}
}
return value;
}
}
public class DatabaseLinkListInspector : BaseInspector<List<Guid>, InspectableDatabaseLinkAttribute>
{
private bool _listItemStyle;
public GUIStyle ListItemStyle =>
(_listItemStyle = !_listItemStyle) ? DatabaseListView.ListStyleEven : DatabaseListView.ListStyleOdd;
public override List<Guid> Inspect(string label,
List<Guid> value,
object parent,
DatabaseInspector inspectorWindow,
InspectableDatabaseLinkAttribute link)
{
Space();
LabelField(label, EditorStyles.boldLabel);
using (var v = new VerticalScope(GUI.skin.box))
{
if (value.Count == 0)
{
using (new HorizontalScope(ListItemStyle))
{
GUILayout.Label($"Drag from list to add {link.EntryType.Name}");
}
}
foreach (var guid in value.ToArray())
{
using (new HorizontalScope(ListItemStyle))
{
var entry = DatabaseInspector.CultCache.Get(guid);
if (entry == null)
{
value.Remove(guid);
GUI.changed = true;
}
else
{
GUILayout.Label((entry as INamedEntry)?.EntryName ?? entry.ID.ToString());
// var rect = GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
// GUI.DrawTexture(rect, Icons.Instance.minus, ScaleMode.StretchToFill, true, 1, LabelColor, 0, 0);
if (GUILayout.Button("-", GUILayout.Width((EditorGUIUtility.singleLineHeight - 3)*2), GUILayout.Height(EditorGUIUtility.singleLineHeight-3)))
{
value.Remove(guid);
}
}
}
}
if (v.rect.Contains(Event.current.mousePosition))
{
var guid = DragAndDrop.GetGenericData("Item");
var dragObj = DragAndDrop.GetGenericData("Item") is Guid ? DatabaseInspector.CultCache.Get((Guid) guid) : null;
var dragValid = dragObj != null && link.EntryType.IsInstanceOfType(dragObj) && !value.Contains(dragObj.ID);
if(Event.current.type == EventType.DragUpdated)
DragAndDrop.visualMode = dragValid ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Rejected;
else if(Event.current.type == EventType.DragPerform)
{
if (dragValid)
{
DragAndDrop.AcceptDrag();
value.Add((Guid) guid);
GUI.changed = true;
}
}
}
}
return value;
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 5e08712ea4854536b130f82ad61db7a8
timeCreated: 1617069551

View file

@ -0,0 +1,223 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
using static UnityEditor.EditorGUILayout;
public class FloatDictionaryInspector : BaseInspector<Dictionary<Guid, float>, InspectableDatabaseLinkAttribute>
{
private bool _listItemStyle;
public GUIStyle ListItemStyle =>
(_listItemStyle = !_listItemStyle) ? DatabaseListView.ListStyleEven : DatabaseListView.ListStyleOdd;
public override Dictionary<Guid, float> Inspect(string label,
Dictionary<Guid, float> value,
object parent,
DatabaseInspector inspectorWindow,
InspectableDatabaseLinkAttribute attribute)
{
Space();
LabelField(label, EditorStyles.boldLabel);
using (var v = new VerticalScope(GUI.skin.box))
{
if (value.Count == 0)
{
using (new HorizontalScope(ListItemStyle))
{
GUILayout.Label("Drag from list to add item");
}
}
foreach (var ingredient in value.ToArray())
{
using (new HorizontalScope(ListItemStyle))
{
var entry = DatabaseInspector.CultCache.Get(ingredient.Key);
if (entry == null)
{
value.Remove(ingredient.Key);
GUI.changed = true;
return value;
}
if(entry is INamedEntry named)
GUILayout.Label(named.EntryName);
else GUILayout.Label(entry.ID.ToString());
value[ingredient.Key] = DelayedFloatField(value[ingredient.Key], GUILayout.Width(50));
// var rect = GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
// GUI.DrawTexture(rect, Icons.Instance.minus, ScaleMode.StretchToFill, true, 1, LabelColor, 0, 0);
if (GUILayout.Button("-", GUILayout.Width((EditorGUIUtility.singleLineHeight - 3)*2), GUILayout.Height(EditorGUIUtility.singleLineHeight-3)))
value.Remove(ingredient.Key);
}
}
if (v.rect.Contains(Event.current.mousePosition))
{
var dragData = DragAndDrop.GetGenericData("Item");
var isId = dragData is Guid guid;
var dragEntry = isId ? DatabaseInspector.CultCache.Get(guid) : null;
var correctType = attribute.EntryType.IsInstanceOfType(dragEntry);
if(Event.current.type == EventType.DragUpdated)
DragAndDrop.visualMode = correctType ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Rejected;
else if(Event.current.type == EventType.DragPerform)
{
if (isId && correctType)
{
DragAndDrop.AcceptDrag();
value[guid] = 1;
GUI.changed = true;
}
}
}
}
return value;
}
}
public class RangedFloatDictionaryInspector : BaseInspector<Dictionary<Guid, float>, InspectableDatabaseLinkAttribute, RangedFloatAttribute>
{
private bool _listItemStyle;
public GUIStyle ListItemStyle =>
(_listItemStyle = !_listItemStyle) ? DatabaseListView.ListStyleEven : DatabaseListView.ListStyleOdd;
public override Dictionary<Guid, float> Inspect(string label,
Dictionary<Guid, float> value,
object parent,
DatabaseInspector inspectorWindow,
InspectableDatabaseLinkAttribute link,
RangedFloatAttribute range)
{
Space();
LabelField(label, EditorStyles.boldLabel);
using (var v = new VerticalScope(GUI.skin.box))
{
if (value.Count == 0)
{
using (new HorizontalScope(ListItemStyle))
{
GUILayout.Label("Drag from list to add item");
}
}
foreach (var ingredient in value.ToArray())
{
using (new HorizontalScope(ListItemStyle))
{
var entry = DatabaseInspector.CultCache.Get(ingredient.Key);
if (entry == null)
{
value.Remove(ingredient.Key);
GUI.changed = true;
return value;
}
if(entry is INamedEntry named)
GUILayout.Label(named.EntryName);
else GUILayout.Label(entry.ID.ToString());
value[ingredient.Key] = Slider(value[ingredient.Key], range.Min, range.Max);
// var rect = GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
// GUI.DrawTexture(rect, Icons.Instance.minus, ScaleMode.StretchToFill, true, 1, LabelColor, 0, 0);
if (GUILayout.Button("-", GUILayout.Width((EditorGUIUtility.singleLineHeight - 3)*2), GUILayout.Height(EditorGUIUtility.singleLineHeight-3)))
value.Remove(ingredient.Key);
}
}
if (v.rect.Contains(Event.current.mousePosition))
{
var dragData = DragAndDrop.GetGenericData("Item");
var isId = dragData is Guid guid;
var dragEntry = isId ? DatabaseInspector.CultCache.Get(guid) : null;
var correctType = link.EntryType.IsInstanceOfType(dragEntry);
if(Event.current.type == EventType.DragUpdated)
DragAndDrop.visualMode = correctType ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Rejected;
else if(Event.current.type == EventType.DragPerform)
{
if (isId && correctType)
{
DragAndDrop.AcceptDrag();
value[guid] = range.Max;
GUI.changed = true;
}
}
}
}
return value;
}
}
public class IntDictionaryInspector : BaseInspector<Dictionary<Guid, int>, InspectableDatabaseLinkAttribute>
{
private bool _listItemStyle;
public GUIStyle ListItemStyle =>
(_listItemStyle = !_listItemStyle) ? DatabaseListView.ListStyleEven : DatabaseListView.ListStyleOdd;
public override Dictionary<Guid, int> Inspect(string label,
Dictionary<Guid, int> value,
object parent,
DatabaseInspector inspectorWindow,
InspectableDatabaseLinkAttribute attribute)
{
Space();
LabelField(label, EditorStyles.boldLabel);
using (var v = new VerticalScope(GUI.skin.box))
{
if (value.Count == 0)
{
using (var h = new HorizontalScope(ListItemStyle))
{
GUILayout.Label("Drag from list to add item");
}
}
foreach (var ingredient in value.ToArray())
{
using (var h = new HorizontalScope(ListItemStyle))
{
var entry = DatabaseInspector.CultCache.Get(ingredient.Key);
if (entry == null)
{
value.Remove(ingredient.Key);
GUI.changed = true;
return value;
}
if(entry is INamedEntry named)
GUILayout.Label(named.EntryName);
else GUILayout.Label(entry.ID.ToString());
value[ingredient.Key] = DelayedIntField(value[ingredient.Key], GUILayout.Width(50));
// var rect = GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
// GUI.DrawTexture(rect, Icons.Instance.minus, ScaleMode.StretchToFill, true, 1, LabelColor, 0, 0);
if (GUILayout.Button("-", GUILayout.Width((EditorGUIUtility.singleLineHeight - 3)*2), GUILayout.Height(EditorGUIUtility.singleLineHeight-3)) || value[ingredient.Key]==0)
value.Remove(ingredient.Key);
}
}
if (v.rect.Contains(Event.current.mousePosition))
{
var dragData = DragAndDrop.GetGenericData("Item");
var isId = dragData is Guid guid;
var dragEntry = isId ? DatabaseInspector.CultCache.Get(guid) : null;
var correctType = attribute.EntryType.IsInstanceOfType(dragEntry);
if(Event.current.type == EventType.DragUpdated)
DragAndDrop.visualMode = correctType ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Rejected;
else if(Event.current.type == EventType.DragPerform)
{
if (isId && correctType)
{
DragAndDrop.AcceptDrag();
value[guid] = 1;
GUI.changed = true;
}
}
}
}
return value;
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: a42620fd406045889578e2ad8d5fd8de
timeCreated: 1617067689

View file

@ -0,0 +1,54 @@
using UnityEditor;
using UnityEngine;
using static UnityEditor.EditorGUILayout;
public class FloatInspector : BaseInspector<float>
{
public override float Inspect(string label, float value, object parent, DatabaseInspector inspectorWindow)
{
using (new HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
return DelayedFloatField(value);
}
}
}
public class RangedFloatInspector : BaseInspector<float, RangedFloatInspectableAttribute>
{
public override float Inspect(string label,
float value,
object parent,
DatabaseInspector inspectorWindow,
RangedFloatInspectableAttribute attribute)
{
using (new HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
return Slider(value, attribute.Min, attribute.Max);
}
}
}
public class TemperatureFloatInspector : BaseInspector<float, InspectableTemperatureAttribute>
{
public override float Inspect(string label,
float value,
object parent,
DatabaseInspector inspectorWindow,
InspectableTemperatureAttribute attribute)
{
using (var h = new HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
GUILayout.Label("°K", EditorStyles.miniLabel, GUILayout.Width(labelWidth));
value = DelayedFloatField(value);
GUILayout.Label("°C", EditorStyles.miniLabel, GUILayout.Width(labelWidth));
value = DelayedFloatField(value - 273.15f) + 273.15f;
GUILayout.Label("°F", EditorStyles.miniLabel, GUILayout.Width(labelWidth));
value = (DelayedFloatField((value - 273.15f) * 1.8f + 32) - 32) / 1.8f + 273.15f;
return value;
}
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 47b8e5bc90714055881eb31baf2ab879
timeCreated: 1617065074

View file

@ -0,0 +1,27 @@
using UnityEditor;
using UnityEngine;
using static UnityEditor.EditorGUILayout;
public class IntInspector : BaseInspector<int>
{
public override int Inspect(string label, int value, object parent, DatabaseInspector inspectorWindow)
{
using (new HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
return DelayedIntField(value);
}
}
}
public class RangedIntInspector : BaseInspector<int, RangedIntInspectableAttribute>
{
public override int Inspect(string label, int value, object parent, DatabaseInspector inspectorWindow, RangedIntInspectableAttribute attribute)
{
using (new HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
return IntSlider(value, attribute.Min, attribute.Max);
}
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: ac7d3b8651964ce1a732a002447d6f69
timeCreated: 1617065365

View file

@ -0,0 +1,142 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using static UnityEditor.EditorGUILayout;
public class ListInspector<T> : BaseInspector<List<T>>
{
private bool _listItemStyle;
private static HashSet<int> _listItemFoldouts = new HashSet<int>();
public GUIStyle ListItemStyle =>
(_listItemStyle = !_listItemStyle) ? DatabaseListView.ListStyleEven : DatabaseListView.ListStyleOdd;
public override List<T> Inspect(string label, List<T> list, object parent, DatabaseInspector inspectorWindow)
{
var listType = typeof(T);
if (listType.GetCustomAttribute<InspectableAttribute>() != null)
{
Space();
using (new VerticalScope(GUI.skin.box))
{
if (list == null)
{
list = new List<T>();
}
else
{
var sorted = true;
var order = int.MinValue;
foreach(var element in list)
{
if (element == null)
{
list.Remove(element);
return list;
}
var elementType = element.GetType();
var elementOrder = elementType.GetCustomAttribute<OrderAttribute>()?.Order ?? 0;
if (elementOrder < order)
sorted = false;
order = elementOrder;
}
if (!sorted)
{
list.Sort((x, y) => (x.GetType().GetCustomAttribute<OrderAttribute>()?.Order ?? 0).CompareTo(y.GetType().GetCustomAttribute<OrderAttribute>()?.Order ?? 0));
}
}
foreach (var o in list)
{
if (o == null)
{
list.Remove(o);
break;
}
bool _tinted = false;
var originalColor = GUI.backgroundColor;
if (o is ITintInspector tint)
{
_tinted = true;
GUI.backgroundColor = tint.TintColor.ToColor();
}
using (new VerticalScope(ListItemStyle))
{
using (new HorizontalScope())
{
//if (listType.IsInterface)
if(Foldout(_listItemFoldouts.Contains(o.GetHashCode()), o.ToString(), true))
_listItemFoldouts.Add(o.GetHashCode());
else
_listItemFoldouts.Remove(o.GetHashCode());
// var rect = GetControlRect(false,
// GUILayout.Width(EditorGUIUtility.singleLineHeight));
// GUI.DrawTexture(rect, Icons.Instance.minus, ScaleMode.StretchToFill, true, 1,
// LabelColor, 0, 0);
if (GUILayout.Button("-", GUILayout.Width((EditorGUIUtility.singleLineHeight - 3)*2), GUILayout.Height(EditorGUIUtility.singleLineHeight-3)))
{
list.Remove(o);
break;
}
}
if(_listItemFoldouts.Contains(o.GetHashCode()))
{
Space();
inspectorWindow.Inspect(o, true);
}
}
if(_tinted)
GUI.backgroundColor = originalColor;
}
using (new HorizontalScope(ListItemStyle))
{
GUILayout.Label($"Add new {listType.Name}", GUILayout.ExpandWidth(true));
// var rect = GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
// GUI.DrawTexture(rect, Icons.Instance.plus, ScaleMode.StretchToFill, true, 1, LabelColor, 0, 0);
if (GUILayout.Button("+", GUILayout.Width((EditorGUIUtility.singleLineHeight - 3)*2), GUILayout.Height(EditorGUIUtility.singleLineHeight-3)))
{
if (listType.IsInterface)
{
var menu = new GenericMenu();
foreach (var childType in listType.GetAllInterfaceClasses())
{
menu.AddItem(new GUIContent(childType.Name), false, () =>
{
list.Add((T)Activator.CreateInstance(childType));
});
}
menu.ShowAsContext();
}
else if (listType.IsAbstract)
{
var menu = new GenericMenu();
foreach (var childType in listType.GetAllChildClasses().Where(t=>!t.IsAbstract))
{
menu.AddItem(new GUIContent(childType.Name), false, () =>
{
list.Add((T)Activator.CreateInstance(childType));
});
}
menu.ShowAsContext();
}
else
{
list.Add(Activator.CreateInstance<T>());
}
}
}
}
}
else Debug.Log($"Field \"{label}\" is a list of non-Inspectable type {listType.Name}. No inspector was generated.");
return list;
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 551335721057411d942b3317ae028546
timeCreated: 1617145746

View file

@ -3,11 +3,12 @@ using UnityEditor;
using UnityEngine;
using static UnityEditor.EditorGUILayout;
public class Float2Inspector : InspectorBase<float2>
public class Float2Inspector : BaseInspector<float2>
{
public override float2 Inspect(string label, float2 value)
public override float2 Inspect(string label, float2 value, object parent, DatabaseInspector inspectorWindow)
{
using (var h = new EditorGUILayout.HorizontalScope())
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
GUILayout.Label("X", GUILayout.Width(labelWidth));
@ -19,27 +20,49 @@ public class Float2Inspector : InspectorBase<float2>
}
}
public class Float3Inspector : InspectorBase<float3>
public class Float3Inspector : BaseInspector<float3>
{
public override float3 Inspect(string label, float3 value)
public override float3 Inspect(string label, float3 value, object parent, DatabaseInspector inspectorWindow)
{
using (var h = new EditorGUILayout.HorizontalScope())
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
GUILayout.Label("X", GUILayout.Width(labelWidth));
value.x = DelayedFloatField(value.x);
GUILayout.Label("Y", GUILayout.Width(labelWidth));
value.y = DelayedFloatField(value.y);
GUILayout.Label("Z", GUILayout.Width(labelWidth));
value.z = DelayedFloatField(value.z);
return value;
}
}
}
public class Int2Inspector : InspectorBase<int2>
public class Float4Inspector : BaseInspector<float4>
{
public override int2 Inspect(string label, int2 value)
public override float4 Inspect(string label, float4 value, object parent, DatabaseInspector inspectorWindow)
{
using (var h = new EditorGUILayout.HorizontalScope())
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
GUILayout.Label("X", GUILayout.Width(labelWidth));
value.x = DelayedFloatField(value.x);
GUILayout.Label("Y", GUILayout.Width(labelWidth));
value.y = DelayedFloatField(value.y);
GUILayout.Label("Z", GUILayout.Width(labelWidth));
value.z = DelayedFloatField(value.z);
GUILayout.Label("W", GUILayout.Width(labelWidth));
value.w = DelayedFloatField(value.w);
return value;
}
}
}
public class Int2Inspector : BaseInspector<int2>
{
public override int2 Inspect(string label, int2 value, object parent, DatabaseInspector inspectorWindow)
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
GUILayout.Label("X", GUILayout.Width(labelWidth));
@ -57,4 +80,42 @@ public class Int2Inspector : InspectorBase<int2>
return value;
}
}
}
public class Int3Inspector : BaseInspector<int3>
{
public override int3 Inspect(string label, int3 value, object parent, DatabaseInspector inspectorWindow)
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
GUILayout.Label("X", GUILayout.Width(labelWidth));
value.x = DelayedIntField(value.x);
GUILayout.Label("Y", GUILayout.Width(labelWidth));
value.y = DelayedIntField(value.y);
GUILayout.Label("Z", GUILayout.Width(labelWidth));
value.z = DelayedIntField(value.z);
return value;
}
}
}
public class Int4Inspector : BaseInspector<int4>
{
public override int4 Inspect(string label, int4 value, object parent, DatabaseInspector inspectorWindow)
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
GUILayout.Label("X", GUILayout.Width(labelWidth));
value.x = DelayedIntField(value.x);
GUILayout.Label("Y", GUILayout.Width(labelWidth));
value.y = DelayedIntField(value.y);
GUILayout.Label("Z", GUILayout.Width(labelWidth));
value.z = DelayedIntField(value.z);
GUILayout.Label("W", GUILayout.Width(labelWidth));
value.w = DelayedIntField(value.w);
return value;
}
}
}

View file

@ -0,0 +1,40 @@
using UnityEditor;
using UnityEngine;
using static UnityEditor.EditorGUILayout;
public class BoolInspector : BaseInspector<bool>
{
public override bool Inspect(string label, bool value, object parent, DatabaseInspector inspectorWindow)
{
using (var h = new EditorGUILayout.HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
return Toggle(value);
}
}
}
public class StringInspector : BaseInspector<string>
{
public override string Inspect(string label, string value, object parent, DatabaseInspector inspectorWindow)
{
using (var h = new HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
return DelayedTextField(value);
}
}
}
public class StringAreaInspector : BaseInspector<string, InspectableTextAttribute>
{
public override string Inspect(string label, string value, object parent, DatabaseInspector inspectorWindow, InspectableTextAttribute attribute)
{
using (new HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
EditorStyles.textArea.wordWrap = true;
return DelayedTextField(value, EditorStyles.textArea, GUILayout.Height(100));
}
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 91dcbfa1679e4be1944d6856ca63bf13
timeCreated: 1617065181

View file

@ -0,0 +1,23 @@
using System;
using System.Linq;
using UnityEditor;
using UnityEngine;
using static UnityEditor.EditorGUILayout;
public class TypeInspector : BaseInspector<Type, InspectableTypeAttribute>
{
public override Type Inspect(string label, Type value, object parent, DatabaseInspector inspectorWindow, InspectableTypeAttribute attribute)
{
var types = attribute.Type.GetAllChildClasses();
var enumOptions = new[] {"None"}.Concat(types.Select(t => t.Name)).ToArray();
var index = Array.IndexOf(types, value) + 1;
using (new HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
index = Popup(index, enumOptions);
}
return index == 0 ? null : types[index - 1];
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 4762384a61dc4d08a1ba4e7564a20081
timeCreated: 1617066802

View file

@ -0,0 +1,47 @@
using UnityEditor;
using UnityEngine;
using static UnityEditor.EditorGUILayout;
public class TextureInspector : BaseInspector<string, InspectableTextureAttribute>
{
public override string Inspect(string label,
string value,
object parent,
DatabaseInspector inspectorWindow,
InspectableTextureAttribute attribute)
{
using (new HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
return AssetDatabase.GetAssetPath(ObjectField(AssetDatabase.LoadAssetAtPath<Texture2D>(value), typeof(Texture2D), false));
}
}
}
public class GameObjectInspector : BaseInspector<string, InspectablePrefabAttribute>
{
public override string Inspect(string label, string value, object parent, DatabaseInspector inspectorWindow, InspectablePrefabAttribute attribute)
{
using (new HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
return AssetDatabase.GetAssetPath(ObjectField(AssetDatabase.LoadAssetAtPath<GameObject>(value), typeof(GameObject), false));
}
}
}
public class TextAssetInspector : BaseInspector<string, InspectableTextAssetAttribute>
{
public override string Inspect(string label,
string value,
object parent,
DatabaseInspector inspectorWindow,
InspectableTextAssetAttribute attribute)
{
using (new HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
return AssetDatabase.GetAssetPath(ObjectField(AssetDatabase.LoadAssetAtPath<TextAsset>(value), typeof(TextAsset), false));
}
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 8519fa7d4f06468bb9be151f053d1fcb
timeCreated: 1617067005

View file

@ -5,6 +5,7 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Newtonsoft.Json;
@ -17,10 +18,9 @@ public static class RethinkConnection
{
public static RethinkDB R = RethinkDB.R;
public static RethinkQueryStatus RethinkConnect(DatabaseCache cache, string connectionString, bool syncLocalChanges = true)
public static RethinkQueryStatus RethinkConnect(CultCache cache, string connectionString, string dbName, bool syncLocalChanges = true)
{
// Add Unity.Mathematics serialization support to RethinkDB Driver
//Converter.Serializer.Converters.Add(new MathJsonConverter());
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Converters = new List<JsonConverter>
@ -32,10 +32,28 @@ public static class RethinkConnection
Converter.PocoExprConverter
}
};
var syncTables = typeof(DatabaseEntry).GetAllChildClasses()
.Select(t => t.GetCustomAttribute<RethinkTableAttribute>()?.TableName ?? "Default").Distinct();
var connectionStringDomainLength = connectionString.IndexOf(':');
if (connectionStringDomainLength < 1)
throw new ArgumentException("Illegal Connection String: must include port!");
var connection = R.Connection().Hostname(connectionString).Port(RethinkDBConstants.DefaultPort+1).Timeout(60).Connect();
var portString = connectionString.Substring(connectionStringDomainLength + 1);
if (!int.TryParse(portString, out var port))
throw new ArgumentException($"Illegal connection string! \"{portString}\" is not a valid port number!");
var connection = R.Connection()
.Hostname(connectionString.Substring(0,connectionStringDomainLength))
.Port(port).Timeout(60).Connect();
Debug.Log("Connected to RethinkDB");
var tables = R.Db(dbName).TableList().RunAtom<string[]>(connection);
foreach (var st in syncTables.Where(st => !tables.Contains(st)))
R.Db(dbName).TableCreate(st).RunNoReply(connection);
if (syncLocalChanges)
{
// When entries are changed locally, push the changes to RethinkDB
@ -77,66 +95,51 @@ public static class RethinkConnection
var status = new RethinkQueryStatus();
// Get all item data from RethinkDB
Task.Run(async () =>
foreach (var table in syncTables)
{
status.ItemsEntries = R
.Db("Aetheria")
.Table("Items")
.Count().RunAtom<int>(connection);
// Get entries from RethinkDB
Task.Run(async () =>
{
status.TotalEntries += R
.Db("Aetheria")
.Table(table)
.Count().RunAtom<int>(connection);
var result = await R
.Db("Aetheria")
.Table("Items")
.RunCursorAsync<DatabaseEntry>(connection);
while (await result.MoveNextAsync())
{
var entry = result.Current;
//Debug.Log($"Received Items entry from RethinkDB: {entry.GetType()} {(entry as INamedEntry)?.EntryName ?? ""}:{entry.ID}");
cache.Add(entry, true);
status.RetrievedItems++;
}
}).WrapAwait();
// Get globaldata and all galaxy map layer data from RethinkDB
Task.Run(async () =>
{
ReqlAst operation = R
.Db("Aetheria")
.Table("Galaxy");
status.GalaxyEntries = ((Table) operation).Count().RunAtom<int>(connection);
var result = await R
.Db("Aetheria")
.Table(table)
.RunCursorAsync<DatabaseEntry>(connection);
while (await result.MoveNextAsync())
{
var entry = result.Current;
//Debug.Log($"Received Items entry from RethinkDB: {entry.GetType()} {(entry as INamedEntry)?.EntryName ?? ""}:{entry.ID}");
cache.Add(entry, true);
status.RetrievedEntries++;
}
}).WrapAwait();
var result = await operation
.RunCursorAsync<DatabaseEntry>(connection);
while (await result.MoveNextAsync())
// Subscribe to changes from RethinkDB
Task.Run(async () =>
{
var entry = result.Current;
//Debug.Log($"Received Galaxy entry from RethinkDB: {entry.GetType()} {(entry as INamedEntry)?.EntryName ?? ""}:{entry.ID}");
cache.Add(entry, true);
status.RetrievedItems++;
}
}).WrapAwait();
var result = await R
.Db("Aetheria")
.Table(table)
.Changes()
.RunChangesAsync<DatabaseEntry>(connection);
while (await result.MoveNextAsync())
{
var change = result.Current;
if(change.OldValue == null)
Debug.Log($"Received change from RethinkDB (Entry Created): {change.NewValue.ID}");
else if(change.NewValue == null)
Debug.Log($"Received change from RethinkDB (Entry Deleted): {change.OldValue.ID}");
else
Debug.Log($"Received change from RethinkDB: {change.NewValue.ID}");
cache.Add(change.NewValue, true);
}
}).WrapAwait();
}
// Subscribe to changes from RethinkDB
Task.Run(async () =>
{
var result = await R
.Db("Aetheria")
.Table("Items")
.Changes()
.RunChangesAsync<DatabaseEntry>(connection);
while (await result.MoveNextAsync())
{
var change = result.Current;
if(change.OldValue == null)
Debug.Log($"Received change from RethinkDB (Entry Created): {change.NewValue.ID}");
else if(change.NewValue == null)
Debug.Log($"Received change from RethinkDB (Entry Deleted): {change.OldValue.ID}");
else
Debug.Log($"Received change from RethinkDB: {change.NewValue.ID}");
cache.Add(change.NewValue, true);
}
}).WrapAwait();
// Observable.Timer(DateTimeOffset.Now, TimeSpan.FromSeconds(60)).Subscribe(_ =>
// {
@ -149,7 +152,6 @@ public static class RethinkConnection
public class RethinkQueryStatus
{
public int RetrievedItems;
public int GalaxyEntries;
public int ItemsEntries;
public int RetrievedEntries;
public int TotalEntries;
}