External Database Entries + Name File Cleaning + Faction Allegiance

DatabaseCache now reads and stores entry types marked ExternalEntry from separate files in their own folder
Updated name file cleaning code and re-cleaned name files
Disabled planet generation (very slow)
Fixed wormhole traversal - can now explore galaxy
Added faction allegiance matrix and slider inspector code
This commit is contained in:
Reinier Vens 2021-03-16 11:06:54 +00:00
commit d8127c2240
84 changed files with 411 additions and 843 deletions

View file

@ -199,7 +199,10 @@ public class DatabaseInspector : EditorWindow
else if (type == typeof(Dictionary<Guid, float>))
{
var dict = (Dictionary<Guid, float>) field.GetValue(obj);
Inspect(field.Name.SplitCamelCase(), ref dict, link.EntryType);
var ranged = field.GetCustomAttribute<RangedFloatAttribute>();
if(ranged != null)
Inspect(field.Name.SplitCamelCase(), ref dict, link.EntryType, ranged.Min, ranged.Max);
else Inspect(field.Name.SplitCamelCase(), ref dict, link.EntryType);
}
else if (type == typeof(List<BlueprintStatEffect>))
{
@ -851,6 +854,65 @@ public class DatabaseInspector : EditorWindow
}
}
public void Inspect(string label, ref Dictionary<Guid,float> value, Type referenceType, float min, float max)
{
Space();
LabelField(label, EditorStyles.boldLabel);
using (var v = new VerticalScope(GUI.skin.box))
{
if (value.Count == 0)
{
using (var h = new HorizontalScope(_list.ListItemStyle))
{
GUILayout.Label("Drag from list to add item");
}
}
foreach (var ingredient in value.ToArray())
{
using (var h = new HorizontalScope(_list.ListItemStyle))
{
var entry = DatabaseCache.Get(ingredient.Key);
if (entry == null)
{
value.Remove(ingredient.Key);
GUI.changed = true;
return;
}
if(entry is INamedEntry named)
GUILayout.Label(named.EntryName);
else GUILayout.Label(entry.ID.ToString());
value[ingredient.Key] = Slider(value[ingredient.Key], min, max);
var rect = GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
GUI.DrawTexture(rect, Icons.Instance.minus, ScaleMode.StretchToFill, true, 1, LabelColor, 0, 0);
if (GUI.Button(rect, GUIContent.none, GUIStyle.none))
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 ? DatabaseCache.Get(guid) : null;
var correctType = referenceType.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] = max;
GUI.changed = true;
}
}
}
}
}
public void Inspect(string label, ref List<Guid> value, Type entryType)
{
Space();

View file

@ -63,7 +63,7 @@ public class DatabaseListView : EditorWindow
{
//_filePath = ;
// Create database cache
_databaseCache = new DatabaseCache();
_databaseCache = new DatabaseCache(_filePath);
var onInsert = new Action<DatabaseEntry>(entry =>
{
@ -162,16 +162,16 @@ public class DatabaseListView : EditorWindow
}
using (var h = new HorizontalScope())
{
_fileName = TextField(_fileName);
//_fileName = TextField(_fileName);
if (GUILayout.Button("Save"))
{
_databaseCache.Save(_filePath);
_databaseCache.Save();
Debug.Log("Local DB Cache Saved!");
}
if (GUILayout.Button("Load"))
{
_databaseCache.Load(_filePath);
_databaseCache.Load();
Debug.Log("Loaded DB From Local Cache!");
}
}
@ -411,7 +411,7 @@ public class DatabaseListView : EditorWindow
}
}
var entries = _databaseCache.AllEntries.Where(item => !(item is ItemData)).ToArray();
//var entries = _databaseCache.AllEntries.Where(item => !(item is ItemData)).ToArray();
for (var i = 0; i < _entryTypes.Length; i++)
{
using (var h = new HorizontalScope(ListItemStyle))
@ -424,7 +424,7 @@ public class DatabaseListView : EditorWindow
if (_entryFoldouts[i])
{
int index = 0;
foreach (var entry in entries.Where(e=>e.GetType()==_entryTypes[i]).OrderBy(entry=>entry is INamedEntry namedEntry ? namedEntry.EntryName : entry.ID.ToString()))
foreach (var entry in _databaseCache.GetAll(_entryTypes[i]).OrderBy(entry=>entry is INamedEntry namedEntry ? namedEntry.EntryName : entry.ID.ToString()))
{
index++;
var style = ListItemStyle;

View file

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using MessagePack;
using Unity.Mathematics;
using UnityEngine;
using UnityEditor;
@ -28,6 +29,11 @@ public class NameTools : EditorWindow
NameTools window = (NameTools)EditorWindow.GetWindow(typeof(NameTools));
window.Show();
}
bool HasNonASCIIChars(string str)
{
return (System.Text.Encoding.UTF8.GetByteCount(str) != str.Length);
}
void OnGUI()
{
@ -40,14 +46,17 @@ public class NameTools : EditorWindow
if (GUILayout.Button("Save Name Files"))
{
var database = new DatabaseCache();
RegisterResolver.Register();
var nameFilesDirectory = ActionGameManager.GameDataDirectory.CreateSubdirectory("NameFile");
foreach (var nameFile in NameFiles)
{
var entry = new NameFile();
entry.Names = nameFile.text.Split('\n');
database.Add(entry);
var entry = new NameFile
{
Name = nameFile.name,
Names = nameFile.text.Split('\n')
};
File.WriteAllBytes(Path.Combine(nameFilesDirectory.FullName, $"{entry.ID.ToString()}.msgpack"), MessagePackSerializer.Serialize((DatabaseEntry) entry));
}
database.Save(Path.Combine(ActionGameManager.GameDataDirectory.FullName, "Names.msgpack"));
}
nameFile = (TextAsset) EditorGUILayout.ObjectField("Name File", nameFile, typeof(TextAsset), false);
@ -61,22 +70,20 @@ public class NameTools : EditorWindow
{
var lines = nameFile.text.Split('\n');
using StreamWriter outputFile = new StreamWriter(Path.Combine(Application.dataPath, nameFile.name + ".csv"));
var names = new HashSet<string>();
foreach (var line in lines)
{
if (!_stripNumberTokens)
var tokens = line.Split(',', ' ');
foreach (var t in tokens)
{
if (!string.IsNullOrEmpty(line) && Regex.IsMatch(line, "^[\\x00-\\x7F]+$") && !char.IsDigit(line[0]))
if (!HasNonASCIIChars(t))
{
outputFile.WriteLine(line.Trim());
}
}
else
{
var tokens = line.Split('_', '-', ' ');
if(!(tokens.Any(t => t.Length == 2 && char.IsUpper(t[0]) && char.IsUpper(t[1]))))
//if (Regex.IsMatch(line, "^[\\x00-\\x7F]+$") && !tokens.Any(t=>int.TryParse(t, out _)) && !tokens.Any(t=>t=="AM"||t=="FM"||t=="TV"))
{
outputFile.WriteLine(line.Trim());
var s = new string(t.Where(c => char.IsLetter(c) || c == '-' || c == '`' || c == '\'').ToArray()).Trim().Trim('`','-');
if(s.Length >= minWordLength && !names.Contains(s))
{
names.Add(s);
outputFile.WriteLine(s);
}
}
}
}

View file

@ -38,8 +38,8 @@ public class ActionGameManager : MonoBehaviour
{
if (_database != null) return _database;
_database = new DatabaseCache();
_database.Load(Path.Combine(GameDataDirectory.FullName, "AetherDB.msgpack"));
_database = new DatabaseCache(Path.Combine(GameDataDirectory.FullName, "AetherDB.msgpack"));
_database.Load();
return _database;
}

View file

@ -18,7 +18,7 @@ public static class RethinkConnection
{
public static RethinkDB R = RethinkDB.R;
public static RethinkQueryStatus RethinkConnect(DatabaseCache cache, string connectionString, bool syncLocalChanges = true, bool filterGalaxyData = true)
public static RethinkQueryStatus RethinkConnect(DatabaseCache cache, string connectionString, bool syncLocalChanges = true)
{
// Add Unity.Mathematics serialization support to RethinkDB Driver
//Converter.Serializer.Converters.Add(new MathJsonConverter());
@ -105,15 +105,7 @@ public static class RethinkConnection
ReqlAst operation = R
.Db("Aetheria")
.Table("Galaxy");
if (filterGalaxyData)
{
var filter = ((Table) operation).Filter(o =>
o["$type"] == typeof(GalaxyMapLayerData).Name ||
o["$type"] == typeof(MegaCorporation).Name);
status.GalaxyEntries = filter.Count().RunAtom<int>(connection);
operation = filter;
}
else status.GalaxyEntries = ((Table) operation).Count().RunAtom<int>(connection);
status.GalaxyEntries = ((Table) operation).Count().RunAtom<int>(connection);
var result = await operation
.RunCursorAsync<DatabaseEntry>(connection);

View file

@ -193,7 +193,11 @@ public class ZoneRenderer : MonoBehaviour
foreach (var adjacentZone in zone.SectorZone.AdjacentZones)
{
var dir = normalize(adjacentZone.Position - zone.SectorZone.Position);
AddWormhole(new Wormhole {Position = dir * Settings.DefaultZoneRadius * Settings.WormholeDistanceRatio});
AddWormhole(new Wormhole
{
Target = adjacentZone,
Position = dir * Settings.DefaultZoneRadius * Settings.WormholeDistanceRatio
});
}
}
}

View file

@ -51,6 +51,9 @@ public class RuntimeInspectable : Attribute { }
[AttributeUsage(AttributeTargets.Class)]
public class InspectableAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Class)]
public class ExternalEntryAttribute : Attribute { }
public class InspectableFieldAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Field)]
@ -108,6 +111,18 @@ public class RangedFloatInspectableAttribute : InspectableFieldAttribute
}
}
[AttributeUsage(AttributeTargets.Field)]
public class RangedFloatAttribute : Attribute
{
public readonly float Min, Max;
public RangedFloatAttribute(float min, float max)
{
Min = min;
Max = max;
}
}
[AttributeUsage(AttributeTargets.Field)]
public class RangedIntInspectableAttribute : InspectableFieldAttribute
{

View file

@ -71,6 +71,9 @@ public class MegaCorporation : DatabaseEntry, INamedEntry
[InspectableField, JsonProperty("influence"), Key(11)]
public int InfluenceDistance = 4;
[InspectableDatabaseLink(typeof(MegaCorporation)), RangedFloat(0, 1), JsonProperty("allegiance"), Key(12)]
public Dictionary<Guid, float> Allegiance = new Dictionary<Guid, float>();
[IgnoreMember] public string EntryName
{
get => Name;
@ -78,9 +81,16 @@ public class MegaCorporation : DatabaseEntry, INamedEntry
}
}
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class NameFile : DatabaseEntry
[Inspectable, MessagePackObject, ExternalEntry]
public class NameFile : DatabaseEntry, INamedEntry
{
[JsonProperty("names"), Key(1)]
public string[] Names;
[Key(1)] public string Name;
[Key(2)] public string[] Names;
[IgnoreMember]
public string EntryName
{
get => Name;
set => Name = value;
}
}

View file

@ -7,6 +7,7 @@ using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using MessagePack;
public class DatabaseCache
@ -20,44 +21,107 @@ public class DatabaseCache
private readonly object addLock = new object();
public Action<string> Logger = Console.WriteLine;
//public Action<string> Logger = Console.WriteLine;
private string _filePath;
private readonly Dictionary<Guid, DatabaseEntry> _entries = new Dictionary<Guid, DatabaseEntry>();
private readonly Dictionary<Type, Dictionary<Guid, DatabaseEntry>> _types = new Dictionary<Type, Dictionary<Guid, DatabaseEntry>>();
private readonly Dictionary<Type, HashSet<DatabaseEntry>> _types = new Dictionary<Type, HashSet<DatabaseEntry>>();
private readonly Dictionary<Type, (DirectoryInfo directory, List<Guid> entries)> _externalTypes = new Dictionary<Type, (DirectoryInfo directory, List<Guid> entries)>();
private class ExternalEntry
{
public string FilePath;
public DatabaseEntry Entry;
public ExternalEntry(string filePath, DatabaseEntry entry)
{
FilePath = filePath;
Entry = entry;
}
}
private readonly Dictionary<Guid, ExternalEntry> _externalEntries = new Dictionary<Guid, ExternalEntry>();
public IEnumerable<DatabaseEntry> AllEntries => _entries.Values;
public DatabaseCache(string filePath)
{
RegisterResolver.Register();
_filePath = filePath;
var fileInfo = new FileInfo(filePath);
var dataDirectory = fileInfo.Directory;
// Entry types can be marked external
// External entries are stored individually and loaded on demand
// This is mainly to accomodate large files like datasets
foreach (var type in typeof(DatabaseEntry).GetAllChildClasses())
{
if (type.GetCustomAttribute<ExternalEntryAttribute>() != null)
{
var typeDirectory = dataDirectory.CreateSubdirectory(type.Name);
_externalTypes[type] = (typeDirectory, new List<Guid>());
// Cache the GUIDs for all available external entries for querying
// Initially set values to null to indicate they haven't been loaded yet
foreach (var file in typeDirectory.EnumerateFiles("*.msgpack"))
{
Guid id;
if (Guid.TryParse(file.Name.Substring(0, file.Name.IndexOf('.')), out id))
{
_externalEntries.Add(id, new ExternalEntry(file.FullName, null));
_externalTypes[type].entries.Add(id);
}
}
}
else _types[type] = new HashSet<DatabaseEntry>();
}
}
public void Add(DatabaseEntry entry, bool remote = false)
{
lock(addLock)
{
if (entry != null)
{
entry.Database = this;
var exists = _entries.ContainsKey(entry.ID);
_entries[entry.ID] = entry;
// If an external entry is added, store it separately
var type = entry.GetType();
var types = type.GetParentTypes();
foreach (var t in types)
if (_externalTypes.ContainsKey(type))
{
if (!_types.ContainsKey(t))
_types[t] = new Dictionary<Guid, DatabaseEntry>();
_types[t][entry.ID] = entry;
}
if (remote)
{
if (exists)
OnDataUpdateRemote?.Invoke(entry);
if (_externalEntries.ContainsKey(entry.ID))
{
_externalEntries[entry.ID].Entry = entry;
}
else
OnDataInsertRemote?.Invoke(entry);
{
_externalTypes[type].entries.Add(entry.ID);
_externalEntries[entry.ID] = new ExternalEntry(
Path.Combine(_externalTypes[type].directory.FullName, $"{entry.ID.ToString()}.msgpack"),
entry);
}
}
else
{
if (exists)
OnDataUpdateLocal?.Invoke(entry);
_entries[entry.ID] = entry;
_types[type].Add(entry);
if (remote)
{
if (exists)
OnDataUpdateRemote?.Invoke(entry);
else
OnDataInsertRemote?.Invoke(entry);
}
else
OnDataInsertLocal?.Invoke(entry);
{
if (exists)
OnDataUpdateLocal?.Invoke(entry);
else
OnDataInsertLocal?.Invoke(entry);
}
}
}
}
@ -73,6 +137,19 @@ public class DatabaseCache
public DatabaseEntry Get(Guid guid)
{
if (_externalEntries.ContainsKey(guid))
{
if(_externalEntries[guid].Entry == null)
{
var bytes = File.ReadAllBytes(_externalEntries[guid].FilePath);
var e = MessagePackSerializer.Deserialize<DatabaseEntry>(bytes);
e.Database = this;
_externalEntries[guid].Entry = e;
}
return _externalEntries[guid].Entry;
}
DatabaseEntry entry;
_entries.TryGetValue(guid, out entry);
return entry;
@ -80,25 +157,31 @@ public class DatabaseCache
public T Get<T>(Guid guid) where T : DatabaseEntry
{
if (!_types.ContainsKey(typeof(T)))
return null;
DatabaseEntry entry;
_types[typeof(T)].TryGetValue(guid, out entry);
return (T) entry;
return Get(guid) as T;
}
public IEnumerable<T> GetAll<T>()
public IEnumerable<DatabaseEntry> GetAll(Type type)
{
return !_types.ContainsKey(typeof(T)) ? Enumerable.Empty<T>() : _types[typeof(T)].Values.Cast<T>();
if (_externalTypes.ContainsKey(type))
{
return _externalTypes[type].entries.Select(Get);
}
return !_types.ContainsKey(type) ? Enumerable.Empty<DatabaseEntry>() : _types[type];
}
public IEnumerable<T> GetAll<T>() where T : DatabaseEntry
{
var type = typeof(T);
if (_externalTypes.ContainsKey(type))
{
return _externalTypes[type].entries.Select(Get<T>);
}
return !_types.ContainsKey(type) ? Enumerable.Empty<T>() : _types[type].Cast<T>();
}
public void Delete(DatabaseEntry entry, bool remote = false)
{
_entries.Remove(entry.ID);
foreach (var type in _types.Values)
{
type.Remove(entry.ID);
}
if (remote)
OnDataDeleteRemote?.Invoke(entry);
@ -106,18 +189,25 @@ public class DatabaseCache
OnDataDeleteLocal?.Invoke(entry);
}
public void Load(string path)
public void Load()
{
RegisterResolver.Register();
var bytes = File.ReadAllBytes(path);
var bytes = File.ReadAllBytes(_filePath);
var entries = MessagePackSerializer.Deserialize<DatabaseEntry[]>(bytes);
foreach (var entry in entries) entry.Database = this;
AddAll(entries);
}
public void Save(string path)
public void Save()
{
RegisterResolver.Register();
var entries = AllEntries.ToArray();
File.WriteAllBytes(path, MessagePackSerializer.Serialize(entries));
File.WriteAllBytes(_filePath, MessagePackSerializer.Serialize(entries));
foreach (var external in _externalEntries.Values)
{
if (external.Entry != null)
{
File.WriteAllBytes(external.FilePath, MessagePackSerializer.Serialize(external.Entry));
}
}
}
}

View file

@ -62,7 +62,7 @@ public class ConsoleView : MonoBehaviour {
ConsoleController.Instance.AppendLogLine("<color=" + (type == LogType.Error ? "red" : type == LogType.Warning ? "yellow" : "white") + ">" + condition + "</color>");
}
~ConsoleView() {
private void OnDestroy() {
Application.logMessageReceived -= OnLogCallback;
ConsoleController.Instance.VisibilityChanged -= OnVisibilityChanged;
ConsoleController.Instance.LogChanged -= OnLogChanged;