Unity.Mathematics Converters and Galaxy Upload
This commit is contained in:
parent
1df670351b
commit
433a7b4ae4
24 changed files with 910 additions and 351 deletions
|
|
@ -647,7 +647,7 @@ public class DatabaseInspector : EditorWindow
|
|||
|
||||
public void OnGUI()
|
||||
{
|
||||
_labelStyle = new GUIStyle(EditorStyles.centeredGreyMiniLabel) {normal = {textColor = Color.black}};
|
||||
_labelStyle = new GUIStyle(EditorStyles.centeredGreyMiniLabel) {normal = {textColor = EditorGUIUtility.isProSkin?Color.white:Color.black}};
|
||||
|
||||
Event current = Event.current;
|
||||
EventType currentEventType = current.type;
|
||||
|
|
@ -684,12 +684,12 @@ public class DatabaseInspector : EditorWindow
|
|||
// {
|
||||
// DatabaseCache.Duplicate(entry);
|
||||
// }
|
||||
// if (GUILayout.Button("Delete Entry"))
|
||||
// {
|
||||
// DatabaseCache.Delete(entry);
|
||||
// entry = null;
|
||||
// return;
|
||||
// }
|
||||
if (GUILayout.Button("Delete Entry"))
|
||||
{
|
||||
DatabaseCache.Delete(entry);
|
||||
entry = null;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
using (var h = new EditorGUILayout.HorizontalScope())
|
||||
|
|
|
|||
|
|
@ -78,6 +78,9 @@ public class DatabaseListView : EditorWindow
|
|||
|
||||
void OnEnable()
|
||||
{
|
||||
// Add Unity.Mathematics serialization support to RethinkDB Driver
|
||||
Converter.Serializer.Converters.Add(new MathJsonConverter());
|
||||
|
||||
// Create database cache
|
||||
_databaseCache = new DatabaseCache();
|
||||
_databaseCache.OnDataUpdateLocal += _ => Repaint();
|
||||
|
|
@ -141,12 +144,17 @@ public class DatabaseListView : EditorWindow
|
|||
Debug.Log("Connected to RethinkDB");
|
||||
|
||||
// When entries are changed locally, push the changes to RethinkDB
|
||||
_databaseCache.OnDataUpdateLocal +=
|
||||
entry =>
|
||||
{
|
||||
Debug.Log($"Uploading entry to RethinkDB: {entry.ID}");
|
||||
R.Db("Aetheria").Table("Items").Replace(entry).RunAsync(_connection);
|
||||
};
|
||||
_databaseCache.OnDataUpdateLocal += entry =>
|
||||
{
|
||||
Debug.Log($"Uploading entry to RethinkDB: {entry.ID}");
|
||||
R.Db("Aetheria").Table("Items").Replace(entry).RunAsync(_connection);
|
||||
};
|
||||
|
||||
_databaseCache.OnDataDeleteLocal += entry =>
|
||||
{
|
||||
Debug.Log($"Deleting entry from RethinkDB: {entry.ID}");
|
||||
R.Db("Aetheria").Table("Items").Get(entry).Delete().RunAsync(_connection);
|
||||
};
|
||||
|
||||
// Get all item data from RethinkDB
|
||||
Task.Run(async () =>
|
||||
|
|
@ -233,7 +241,7 @@ public class DatabaseListView : EditorWindow
|
|||
GUILayout.Space(20);
|
||||
GUILayout.Label("New " + _itemTypes[i].Name);
|
||||
var rect = EditorGUILayout.GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
|
||||
GUI.DrawTexture(rect, Icons.Instance.plus, ScaleMode.StretchToFill, true, 1, Color.black, 0, 0);
|
||||
GUI.DrawTexture(rect, Icons.Instance.plus, ScaleMode.StretchToFill, true, 1, EditorGUIUtility.isProSkin?Color.white:Color.black, 0, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -282,7 +290,7 @@ public class DatabaseListView : EditorWindow
|
|||
GUILayout.Space(10);
|
||||
GUILayout.Label("New " + _entryTypes[i].Name);
|
||||
var rect = EditorGUILayout.GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
|
||||
GUI.DrawTexture(rect, Icons.Instance.plus, ScaleMode.StretchToFill, true, 1, Color.black, 0, 0);
|
||||
GUI.DrawTexture(rect, Icons.Instance.plus, ScaleMode.StretchToFill, true, 1, EditorGUIUtility.isProSkin?Color.white:Color.black, 0, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,16 +1,22 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Remoting.Messaging;
|
||||
using MIConvexHull;
|
||||
using UniRx;
|
||||
using UnityEngine;
|
||||
using Microsoft.SqlServer.Types;
|
||||
using Newtonsoft.Json;
|
||||
using RethinkDb.Driver;
|
||||
using RethinkDb.Driver.Net;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using static UnityEditor.EditorGUILayout;
|
||||
using Random = UnityEngine.Random;
|
||||
|
||||
[CustomEditor(typeof(Galaxy))]
|
||||
public class GalaxyEditor : Editor
|
||||
{
|
||||
private int _width = 0;
|
||||
private static readonly RethinkDB R = RethinkDB.R;
|
||||
|
||||
private int _width;
|
||||
private bool _showResourceMaps;
|
||||
private GalaxyMapLayerData _currentLayer;
|
||||
private string _currentLayerName = "Star Density";
|
||||
|
|
@ -18,6 +24,7 @@ public class GalaxyEditor : Editor
|
|||
private int _hilbertOrder = 6;
|
||||
private ulong _hilbertIndex;
|
||||
private int _starCount = 1;
|
||||
private float _minStarDistance = .01f;
|
||||
private float _maxLinkLength = .1f;
|
||||
private float _linkFilter = .5f;
|
||||
private IEnumerable<Vector2> _stars = new Vector2[0];
|
||||
|
|
@ -31,6 +38,7 @@ public class GalaxyEditor : Editor
|
|||
private Texture2D _linkTex;
|
||||
private Material _galaxyMat;
|
||||
private Material _transparent;
|
||||
private Connection _connection;
|
||||
|
||||
private void OnEnable()
|
||||
{
|
||||
|
|
@ -40,6 +48,8 @@ public class GalaxyEditor : Editor
|
|||
_width = Screen.width;
|
||||
_starTex = new Texture2D(_width,_width, TextureFormat.ARGB32, false);
|
||||
_linkTex = new Texture2D(_width,_width, TextureFormat.ARGB32, false);
|
||||
// var galaxy = target as Galaxy;
|
||||
// _stars = galaxy.MapData.Stars.Select(s => s.Position);
|
||||
}
|
||||
|
||||
public override void OnInspectorGUI()
|
||||
|
|
@ -75,39 +85,39 @@ public class GalaxyEditor : Editor
|
|||
_galaxyMat.SetFloat("NoiseGain", _currentLayer.NoiseGain);
|
||||
_galaxyMat.SetFloat("NoiseLacunarity", _currentLayer.NoiseLacunarity);
|
||||
_galaxyMat.SetFloat("NoiseFrequency", _currentLayer.NoiseFrequency);
|
||||
var rect = EditorGUILayout.GetControlRect(false, _width);
|
||||
var rect = GetControlRect(false, _width);
|
||||
EditorGUI.DrawPreviewTexture(rect, _white, _galaxyMat);
|
||||
if(_drawLinks)
|
||||
EditorGUI.DrawPreviewTexture(rect, _linkTex, _transparent);
|
||||
if(_drawStars)
|
||||
EditorGUI.DrawPreviewTexture(rect, _starTex, _transparent);
|
||||
|
||||
_drawStars = EditorGUILayout.ToggleLeft($"Display {_stars.Count()} Stars", _drawStars);
|
||||
_drawResource = EditorGUILayout.ToggleLeft("Display Resources", _drawResource);
|
||||
_drawLinks = EditorGUILayout.ToggleLeft($"Display {_starLinks.Count} Links", _drawLinks);
|
||||
_drawStars = ToggleLeft($"Display {_stars.Count()} Stars", _drawStars);
|
||||
_drawResource = ToggleLeft("Display Resources", _drawResource);
|
||||
_drawLinks = ToggleLeft($"Display {_starLinks.Count} Links", _drawLinks);
|
||||
|
||||
GUILayout.Space(10);
|
||||
|
||||
// Show default inspector property editor
|
||||
DrawDefaultInspector ();
|
||||
|
||||
EditorGUILayout.BeginVertical("Box");
|
||||
BeginVertical("Box");
|
||||
EditorGUI.indentLevel++;
|
||||
GUILayout.Label(_currentLayerName);
|
||||
Inspect(_currentLayer);
|
||||
EditorGUI.indentLevel--;
|
||||
EditorGUILayout.EndVertical();
|
||||
EndVertical();
|
||||
|
||||
EditorGUILayout.BeginVertical("Box");
|
||||
BeginVertical("Box");
|
||||
EditorGUI.indentLevel++;
|
||||
_showResourceMaps = EditorGUILayout.Foldout(_showResourceMaps, "Resource Density Maps");
|
||||
_showResourceMaps = Foldout(_showResourceMaps, "Resource Density Maps");
|
||||
if (_showResourceMaps)
|
||||
{
|
||||
EditorGUI.indentLevel++;
|
||||
foreach (var resourceDensity in galaxy.MapData.ResourceDensities.ToArray())
|
||||
{
|
||||
EditorGUILayout.BeginHorizontal();
|
||||
var newName = EditorGUILayout.DelayedTextField(resourceDensity.Key);
|
||||
BeginHorizontal();
|
||||
var newName = DelayedTextField(resourceDensity.Key);
|
||||
if (newName != resourceDensity.Key)
|
||||
{
|
||||
galaxy.MapData.ResourceDensities.Remove(resourceDensity.Key);
|
||||
|
|
@ -118,7 +128,7 @@ public class GalaxyEditor : Editor
|
|||
_currentLayerName = resourceDensity.Key;
|
||||
_currentLayer = resourceDensity.Value;
|
||||
}
|
||||
EditorGUILayout.EndHorizontal();
|
||||
EndHorizontal();
|
||||
}
|
||||
EditorGUI.indentLevel--;
|
||||
if (GUILayout.Button("Add New Resource"))
|
||||
|
|
@ -132,21 +142,24 @@ public class GalaxyEditor : Editor
|
|||
_currentLayer = galaxy.MapData.StarDensity;
|
||||
}
|
||||
EditorGUI.indentLevel--;
|
||||
EditorGUILayout.EndVertical();
|
||||
EndVertical();
|
||||
|
||||
EditorGUILayout.BeginVertical("Box");
|
||||
BeginVertical("Box");
|
||||
EditorGUI.indentLevel++;
|
||||
_showStarEditor = EditorGUILayout.Foldout(_showStarEditor, "Star Tools");
|
||||
_showStarEditor = Foldout(_showStarEditor, "Star Tools");
|
||||
if (_showStarEditor)
|
||||
{
|
||||
_hilbertOrder = EditorGUILayout.IntField("Hilbert Order", _hilbertOrder);
|
||||
_starCount = EditorGUILayout.IntField("Star Count", _starCount);
|
||||
_hilbertOrder = IntField("Hilbert Order", _hilbertOrder);
|
||||
_starCount = IntField("Star Count", _starCount);
|
||||
//_hilbertIndex = (ulong) EditorGUILayout.IntField("Hilbert Index", (int) _hilbertIndex);
|
||||
if (GUILayout.Button("Evaluate Hilbert Curve"))
|
||||
{
|
||||
var points = EvaluateHilbert(_hilbertOrder,false);
|
||||
Debug.Log($"Hilbert curve has {points.Count()} points, resolution {Mathf.RoundToInt(points.Max(p=>p.x))+1}");
|
||||
}
|
||||
|
||||
_minStarDistance = FloatField("Minimum Star Distance", _minStarDistance);
|
||||
|
||||
if (GUILayout.Button("Generate Stars"))
|
||||
{
|
||||
var points = EvaluateHilbert(_hilbertOrder).ToArray();
|
||||
|
|
@ -155,14 +168,14 @@ public class GalaxyEditor : Editor
|
|||
while (stars.Count < _starCount && bail < 10)
|
||||
{
|
||||
var accum = 0f;
|
||||
foreach (var hp in points.Select(p=>p+UnityEngine.Random.insideUnitCircle * ((points[0]-points[1]).magnitude/2)))
|
||||
foreach (var hp in points.Select(p=>p+Random.insideUnitCircle * ((points[0]-points[1]).magnitude/2)))
|
||||
{
|
||||
var den = galaxy.MapData.StarDensity.Evaluate(hp, galaxy.MapData);
|
||||
if(!float.IsNaN(den))
|
||||
accum += den * UnityEngine.Random.value;
|
||||
accum += den * Random.value;
|
||||
// else
|
||||
// Debug.Log($"Density at ({hp.x},{hp.y}) is NaN");
|
||||
if (accum > 1)
|
||||
if (accum > 1 && (!stars.Any() || stars.Min(s=>(s-hp).magnitude) > _minStarDistance) )
|
||||
{
|
||||
stars.Add(hp);
|
||||
accum = 0;
|
||||
|
|
@ -177,7 +190,7 @@ public class GalaxyEditor : Editor
|
|||
}
|
||||
if (_stars.Any())
|
||||
{
|
||||
_maxLinkLength = EditorGUILayout.FloatField("Max Link Length", _maxLinkLength);
|
||||
_maxLinkLength = FloatField("Max Link Length", _maxLinkLength);
|
||||
if (GUILayout.Button("Generate Star Links"))
|
||||
{
|
||||
_voronoiMesh = VoronoiMesh<Vertex2, Cell2, VoronoiEdge<Vertex2, Cell2>>.Create(_stars.Select(s=>new Vertex2(s.x,s.y)).ToList());
|
||||
|
|
@ -195,7 +208,7 @@ public class GalaxyEditor : Editor
|
|||
}
|
||||
if (_starLinks.Any())
|
||||
{
|
||||
_linkFilter = EditorGUILayout.FloatField("Link Filter Percentage", _linkFilter);
|
||||
_linkFilter = FloatField("Link Filter Percentage", _linkFilter);
|
||||
if (GUILayout.Button("Filter Star Links"))
|
||||
{
|
||||
var bail = 0;
|
||||
|
|
@ -203,7 +216,7 @@ public class GalaxyEditor : Editor
|
|||
var deadLinks = new List<VoronoiLink>();
|
||||
for (int i = 0; i < count && bail < count*10; bail++)
|
||||
{
|
||||
var link = _starLinks.ElementAt(UnityEngine.Random.Range(0, _starLinks.Count));
|
||||
var link = _starLinks.ElementAt(Random.Range(0, _starLinks.Count));
|
||||
|
||||
if (deadLinks.Contains(link)) continue;
|
||||
|
||||
|
|
@ -231,11 +244,55 @@ public class GalaxyEditor : Editor
|
|||
.Select(sl => galaxy.MapData.Stars.IndexOf(galaxy.MapData.Stars.First(s => (sl.point1.ToVector2() - s.Position).sqrMagnitude < float.Epsilon))));
|
||||
}
|
||||
}
|
||||
|
||||
if (GUILayout.Button("Connect to RethinkDB"))
|
||||
_connection = R.Connection().Hostname(EditorPrefs.GetString("RethinkDB.URL")).Port(RethinkDBConstants.DefaultPort).Timeout(60).Connect();
|
||||
EditorGUI.BeginDisabledGroup(_connection == null);
|
||||
|
||||
if (GUILayout.Button("Drop Galaxy Table"))
|
||||
R.Db("Aetheria").TableDrop("Galaxy").Run(_connection);
|
||||
|
||||
if (GUILayout.Button("Create Galaxy Table"))
|
||||
R.Db("Aetheria").TableCreate("Galaxy").Run(_connection);
|
||||
|
||||
EditorGUI.BeginDisabledGroup(!galaxy.MapData.Stars.Any());
|
||||
|
||||
if (GUILayout.Button("Upload Star Data"))
|
||||
{
|
||||
Converter.Serializer.Converters.Add(new MathJsonConverter());
|
||||
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
|
||||
{
|
||||
Converters = new List<JsonConverter>
|
||||
{
|
||||
new MathJsonConverter(),
|
||||
Converter.DateTimeConverter,
|
||||
Converter.BinaryConverter,
|
||||
Converter.GroupingConverter,
|
||||
Converter.PocoExprConverter
|
||||
}
|
||||
};
|
||||
var starIDs = new Dictionary<StarData, Guid>();
|
||||
foreach (var star in galaxy.MapData.Stars)
|
||||
starIDs[star] = Guid.NewGuid();
|
||||
foreach (var star in galaxy.MapData.Stars)
|
||||
{
|
||||
R.Db("Aetheria").Table("Galaxy").Insert(new ZoneData
|
||||
{
|
||||
ID = starIDs[star],
|
||||
Name = starIDs[star].ToString().Substring(0, 8),
|
||||
Wormholes = star.Links.Select(i => starIDs[galaxy.MapData.Stars[i]]).ToList()
|
||||
}).Run(_connection);
|
||||
}
|
||||
}
|
||||
|
||||
EditorGUI.EndDisabledGroup();
|
||||
|
||||
EditorGUI.EndDisabledGroup();
|
||||
}
|
||||
}
|
||||
}
|
||||
EditorGUI.indentLevel--;
|
||||
EditorGUILayout.EndVertical();
|
||||
EndVertical();
|
||||
|
||||
|
||||
EditorUtility.SetDirty(target);
|
||||
|
|
@ -249,7 +306,7 @@ public class GalaxyEditor : Editor
|
|||
uint max = 0;
|
||||
while (x != 0 || y != 0)
|
||||
{
|
||||
Microsoft.SqlServer.Types.SpaceFillingCurve.ReverseHilbert(order, i, out x, out y);
|
||||
SpaceFillingCurve.ReverseHilbert(order, i, out x, out y);
|
||||
points.Add(new Vector2(x, y));
|
||||
if (x > max)
|
||||
max = x;
|
||||
|
|
@ -260,18 +317,18 @@ public class GalaxyEditor : Editor
|
|||
|
||||
void Inspect(GalaxyMapLayerData layer)
|
||||
{
|
||||
layer.EdgeReduction = EditorGUILayout.FloatField("Edge Reduction", layer.EdgeReduction);
|
||||
layer.CoreBoost = EditorGUILayout.FloatField("Core Boost", layer.CoreBoost);
|
||||
layer.CoreBoostOffset = EditorGUILayout.FloatField("Core Boost Offset", layer.CoreBoostOffset);
|
||||
layer.CoreBoostPower = EditorGUILayout.FloatField("Core Boost Power", layer.CoreBoostPower);
|
||||
layer.NoiseOffset = EditorGUILayout.FloatField("Noise Offset", layer.NoiseOffset);
|
||||
layer.NoiseAmplitude = EditorGUILayout.FloatField("Noise Amplitude", layer.NoiseAmplitude);
|
||||
layer.NoiseGain = EditorGUILayout.FloatField("Noise Gain", layer.NoiseGain);
|
||||
layer.NoiseLacunarity = EditorGUILayout.FloatField("Noise Lacunarity", layer.NoiseLacunarity);
|
||||
layer.NoiseOctaves = EditorGUILayout.IntField("Noise Octaves", layer.NoiseOctaves);
|
||||
layer.NoiseFrequency = EditorGUILayout.FloatField("Noise Frequency", layer.NoiseFrequency);
|
||||
layer.SpokeOffset = EditorGUILayout.FloatField("Spoke Offset", layer.SpokeOffset);
|
||||
layer.SpokeScale = EditorGUILayout.FloatField("Spoke Scale", layer.SpokeScale);
|
||||
layer.EdgeReduction = FloatField("Edge Reduction", layer.EdgeReduction);
|
||||
layer.CoreBoost = FloatField("Core Boost", layer.CoreBoost);
|
||||
layer.CoreBoostOffset = FloatField("Core Boost Offset", layer.CoreBoostOffset);
|
||||
layer.CoreBoostPower = FloatField("Core Boost Power", layer.CoreBoostPower);
|
||||
layer.NoiseOffset = FloatField("Noise Offset", layer.NoiseOffset);
|
||||
layer.NoiseAmplitude = FloatField("Noise Amplitude", layer.NoiseAmplitude);
|
||||
layer.NoiseGain = FloatField("Noise Gain", layer.NoiseGain);
|
||||
layer.NoiseLacunarity = FloatField("Noise Lacunarity", layer.NoiseLacunarity);
|
||||
layer.NoiseOctaves = IntField("Noise Octaves", layer.NoiseOctaves);
|
||||
layer.NoiseFrequency = FloatField("Noise Frequency", layer.NoiseFrequency);
|
||||
layer.SpokeOffset = FloatField("Spoke Offset", layer.SpokeOffset);
|
||||
layer.SpokeScale = FloatField("Spoke Scale", layer.SpokeScale);
|
||||
}
|
||||
|
||||
int UvToIndex(Vector2 v) => (int) (v.y * _width) * _width + (int) (v.x * _width);
|
||||
|
|
@ -285,7 +342,7 @@ public class GalaxyEditor : Editor
|
|||
}
|
||||
foreach (var l in _starLinks)
|
||||
{
|
||||
var pixelCount = Mathf.Max((int) (Mathf.Abs((float) (l.point1.x - l.point2.x)) * _width), (int) (Mathf.Abs((float) (l.point1.y - l.point2.y)) * _width));
|
||||
var pixelCount = Mathf.Max((int) (Mathf.Abs(l.point1.x - l.point2.x) * _width), (int) (Mathf.Abs(l.point1.y - l.point2.y) * _width));
|
||||
//Debug.Log($"Marching across {pixelCount} pixels!");
|
||||
for(int i=0;i<pixelCount;i++)
|
||||
pixels[UvToIndex(Vector2.Lerp(l.point1.ToVector2(),l.point2.ToVector2(),(float)i/pixelCount))] = XKCDColors.OrangeRed;
|
||||
|
|
|
|||
|
|
@ -1,13 +1,17 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using MessagePack;
|
||||
using MessagePack.Formatters;
|
||||
using MessagePack.Resolvers;
|
||||
using Newtonsoft.Json;
|
||||
using RethinkDb.Driver;
|
||||
using RethinkDb.Driver.Net;
|
||||
using Unity.Mathematics;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using Object = UnityEngine.Object;
|
||||
|
||||
using static Unity.Mathematics.math;
|
||||
|
||||
public class SerializerTestWindow : EditorWindow
|
||||
{
|
||||
|
|
@ -22,19 +26,52 @@ public class SerializerTestWindow : EditorWindow
|
|||
|
||||
private void OnEnable()
|
||||
{
|
||||
_connection = R.Connection().Hostname("asgard.gamecult.games").Port(RethinkDBConstants.DefaultPort).Timeout(60).Connect();
|
||||
_connection = R.Connection().Hostname(EditorPrefs.GetString("RethinkDB.URL")).Port(RethinkDBConstants.DefaultPort).Timeout(60).Connect();
|
||||
}
|
||||
|
||||
public void OnGUI()
|
||||
{
|
||||
var obj = new ShieldData() {ID = Guid.NewGuid(), Name = "Foo"} as DatabaseEntry;
|
||||
// This button serializes the texture reference and print the JSON representation
|
||||
var obj = new ShieldData() {ID = Guid.NewGuid(), Name = "Bar" , HeatPerformanceCurve = new []{float4(0,0,0,0), float4(1,1,1,1)}} as DatabaseEntry;
|
||||
|
||||
// JsonSerializer serializer = new JsonSerializer();
|
||||
// serializer.Converters.Add(new MathJsonConverter());
|
||||
// serializer.Converters.Add(Converter.DateTimeConverter);
|
||||
// serializer.Converters.Add(Converter.BinaryConverter);
|
||||
// serializer.Converters.Add(Converter.GroupingConverter);
|
||||
// serializer.Converters.Add(Converter.PocoExprConverter);
|
||||
|
||||
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
|
||||
{
|
||||
Converters = new List<JsonConverter>
|
||||
{
|
||||
new MathJsonConverter(),
|
||||
Converter.DateTimeConverter,
|
||||
Converter.BinaryConverter,
|
||||
Converter.GroupingConverter,
|
||||
Converter.PocoExprConverter
|
||||
}
|
||||
};
|
||||
|
||||
// Set extensions to default resolver.
|
||||
var resolver = CompositeResolver.Create(
|
||||
MathResolver.Instance,
|
||||
NativeGuidResolver.Instance,
|
||||
StandardResolver.Instance
|
||||
);
|
||||
var options = MessagePackSerializerOptions.Standard.WithResolver(resolver);
|
||||
MessagePackSerializer.DefaultOptions = options;
|
||||
|
||||
Converter.Serializer.Converters.Add(new MathJsonConverter());
|
||||
|
||||
if (GUILayout.Button("Print MsgPack JSON"))
|
||||
Debug.Log(MessagePackSerializer.SerializeToJson(obj));
|
||||
|
||||
Debug.Log(MessagePackSerializer.SerializeToJson(obj, options));
|
||||
|
||||
//var writer = new StringWriter();
|
||||
if (GUILayout.Button("Print Newtonsoft JSON"))
|
||||
{
|
||||
//serializer.Serialize(writer, obj);
|
||||
Debug.Log(JsonConvert.SerializeObject(obj));
|
||||
}
|
||||
|
||||
if (GUILayout.Button("Create Database"))
|
||||
R.DbCreate("Aetheria").Run(_connection);
|
||||
|
|
|
|||
|
|
@ -8,6 +8,8 @@ public class DatabaseCache
|
|||
{
|
||||
public event Action<DatabaseEntry> OnDataUpdateLocal;
|
||||
public event Action<DatabaseEntry> OnDataUpdateRemote;
|
||||
public event Action<DatabaseEntry> OnDataDeleteLocal;
|
||||
|
||||
|
||||
public Action<string> Logger = Console.WriteLine;
|
||||
|
||||
|
|
@ -65,4 +67,15 @@ public class DatabaseCache
|
|||
{
|
||||
return _types[typeof(T)].Values.Cast<T>();
|
||||
}
|
||||
|
||||
public void Delete(DatabaseEntry entry)
|
||||
{
|
||||
_entries.Remove(entry.ID);
|
||||
foreach (var type in _types.Values)
|
||||
{
|
||||
type.Remove(entry.ID);
|
||||
}
|
||||
|
||||
OnDataDeleteLocal?.Invoke(entry);
|
||||
}
|
||||
}
|
||||
147
Assets/Scripts/ServerShared/JsonConverters.cs
Normal file
147
Assets/Scripts/ServerShared/JsonConverters.cs
Normal file
|
|
@ -0,0 +1,147 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Unity.Mathematics;
|
||||
using UnityEngine;
|
||||
using static Unity.Mathematics.math;
|
||||
|
||||
public class MathJsonConverter : JsonConverter
|
||||
{
|
||||
|
||||
private readonly Dictionary<Type, Action<JsonWriter, object>> _writers;
|
||||
private readonly Dictionary<Type, Func<JArray, object>> _readers;
|
||||
|
||||
public MathJsonConverter()
|
||||
{
|
||||
_writers = GenerateWriters();
|
||||
_readers = GenerateReaders();
|
||||
}
|
||||
|
||||
private Dictionary<Type, Action<JsonWriter, object>> GenerateWriters()
|
||||
{
|
||||
var writers = new Dictionary<Type, Action<JsonWriter, object>>();
|
||||
|
||||
writers[typeof(float2)] = (writer, o) =>
|
||||
{
|
||||
if (!(o is float2 v))
|
||||
throw new JsonReaderException();
|
||||
|
||||
writer.WriteStartArray();
|
||||
writer.WriteValue(v.x);
|
||||
writer.WriteValue(v.y);
|
||||
writer.WriteEndArray();
|
||||
};
|
||||
|
||||
writers[typeof(float3)] = (writer, o) =>
|
||||
{
|
||||
if (!(o is float3 v))
|
||||
throw new JsonReaderException();
|
||||
|
||||
writer.WriteStartArray();
|
||||
writer.WriteValue(v.x);
|
||||
writer.WriteValue(v.y);
|
||||
writer.WriteValue(v.z);
|
||||
writer.WriteEndArray();
|
||||
};
|
||||
|
||||
writers[typeof(float4)] = (writer, o) =>
|
||||
{
|
||||
if (!(o is float4 v))
|
||||
throw new JsonReaderException();
|
||||
|
||||
writer.WriteStartArray();
|
||||
writer.WriteValue(v.x);
|
||||
writer.WriteValue(v.y);
|
||||
writer.WriteValue(v.z);
|
||||
writer.WriteValue(v.w);
|
||||
writer.WriteEndArray();
|
||||
};
|
||||
|
||||
return writers;
|
||||
}
|
||||
|
||||
private Dictionary<Type, Func<JArray, object>> GenerateReaders()
|
||||
{
|
||||
var readers = new Dictionary<Type, Func<JArray, object>>();
|
||||
|
||||
readers[typeof(float2)] = array =>
|
||||
{
|
||||
if (array.Count < 2)
|
||||
{
|
||||
throw new JsonReaderException(
|
||||
$"Could not read {typeof(float2)} from json, expected a json array with 2 elements");
|
||||
}
|
||||
|
||||
return float2(
|
||||
array[0].ToObject<float>(),
|
||||
array[1].ToObject<float>());
|
||||
};
|
||||
|
||||
readers[typeof(float3)] = array =>
|
||||
{
|
||||
if (array.Count < 3)
|
||||
{
|
||||
throw new JsonReaderException(
|
||||
$"Could not read {typeof(float3)} from json, expected a json array with 3 elements");
|
||||
}
|
||||
|
||||
return float3(
|
||||
array[0].ToObject<float>(),
|
||||
array[1].ToObject<float>(),
|
||||
array[2].ToObject<float>());
|
||||
};
|
||||
|
||||
readers[typeof(float4)] = array =>
|
||||
{
|
||||
if (array.Count < 4)
|
||||
{
|
||||
throw new JsonReaderException(
|
||||
$"Could not read {typeof(float4)} from json, expected a json array with 4 elements");
|
||||
}
|
||||
|
||||
return float4(
|
||||
array[0].ToObject<float>(),
|
||||
array[1].ToObject<float>(),
|
||||
array[2].ToObject<float>(),
|
||||
array[3].ToObject<float>());
|
||||
};
|
||||
|
||||
return readers;
|
||||
}
|
||||
|
||||
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
|
||||
{
|
||||
if (_writers.TryGetValue(value.GetType(), out var serializeAction))
|
||||
serializeAction(writer, value);
|
||||
else
|
||||
throw new JsonReaderException($"Invalid type for ValueConverter:{value.GetType()}");
|
||||
}
|
||||
|
||||
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
|
||||
{
|
||||
if (_readers.TryGetValue(objectType, out var deserializeFunc))
|
||||
{
|
||||
// Convert token from reader to array for deserialize function
|
||||
var token = JToken.ReadFrom(reader);
|
||||
if (!(token is JArray asArray))
|
||||
throw new JsonReaderException(
|
||||
$"Could not read {objectType} from json, expected a json array but got {token.Type}");
|
||||
|
||||
return deserializeFunc(asArray);
|
||||
}
|
||||
|
||||
throw new JsonReaderException($"Invalid type for ValueConverter:{objectType}");
|
||||
}
|
||||
|
||||
public override bool CanConvert(Type objectType)
|
||||
{
|
||||
//If the dictionary contains the key, the type can be handled by this class
|
||||
return _writers.ContainsKey(objectType);
|
||||
}
|
||||
|
||||
//Enable this JSON Converter for reading as well as writing values
|
||||
public override bool CanRead => true;
|
||||
public override bool CanWrite => true;
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/JsonConverters.cs.meta
Normal file
11
Assets/Scripts/ServerShared/JsonConverters.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: fafad9d553198e942a5501ea1472ec9c
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
144
Assets/Scripts/ServerShared/MathFormatters.cs
Normal file
144
Assets/Scripts/ServerShared/MathFormatters.cs
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using MessagePack;
|
||||
using Unity.Mathematics;
|
||||
using static Unity.Mathematics.math;
|
||||
|
||||
public class Float2Formatter : MessagePack.Formatters.IMessagePackFormatter<float2>
|
||||
{
|
||||
public void Serialize(ref MessagePackWriter writer, float2 value, MessagePackSerializerOptions options)
|
||||
{
|
||||
writer.WriteArrayHeader(2);
|
||||
writer.Write(value.x);
|
||||
writer.Write(value.y);
|
||||
}
|
||||
|
||||
public float2 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
|
||||
{
|
||||
if (reader.IsNil)
|
||||
{
|
||||
throw new InvalidOperationException("typecode is null, struct not supported");
|
||||
}
|
||||
|
||||
var length = reader.ReadArrayHeader();
|
||||
var x = default(float);
|
||||
var y = default(float);
|
||||
for (int i = 0; i < length; i++)
|
||||
{
|
||||
var key = i;
|
||||
switch (key)
|
||||
{
|
||||
case 0:
|
||||
x = reader.ReadSingle();
|
||||
break;
|
||||
case 1:
|
||||
y = reader.ReadSingle();
|
||||
break;
|
||||
default:
|
||||
reader.Skip();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var result = float2(x, y);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
public class Float3Formatter : MessagePack.Formatters.IMessagePackFormatter<float3>
|
||||
{
|
||||
public void Serialize(ref MessagePackWriter writer, float3 value, MessagePackSerializerOptions options)
|
||||
{
|
||||
writer.WriteArrayHeader(3);
|
||||
writer.Write(value.x);
|
||||
writer.Write(value.y);
|
||||
writer.Write(value.z);
|
||||
}
|
||||
|
||||
public float3 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
|
||||
{
|
||||
if (reader.IsNil)
|
||||
{
|
||||
throw new InvalidOperationException("typecode is null, struct not supported");
|
||||
}
|
||||
|
||||
var length = reader.ReadArrayHeader();
|
||||
var x = default(float);
|
||||
var y = default(float);
|
||||
var z = default(float);
|
||||
for (int i = 0; i < length; i++)
|
||||
{
|
||||
var key = i;
|
||||
switch (key)
|
||||
{
|
||||
case 0:
|
||||
x = reader.ReadSingle();
|
||||
break;
|
||||
case 1:
|
||||
y = reader.ReadSingle();
|
||||
break;
|
||||
case 2:
|
||||
z = reader.ReadSingle();
|
||||
break;
|
||||
default:
|
||||
reader.Skip();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var result = float3(x, y, z);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
public class Float4Formatter : MessagePack.Formatters.IMessagePackFormatter<float4>
|
||||
{
|
||||
public void Serialize(ref MessagePackWriter writer, float4 value, MessagePackSerializerOptions options)
|
||||
{
|
||||
writer.WriteArrayHeader(4);
|
||||
writer.Write(value.x);
|
||||
writer.Write(value.y);
|
||||
writer.Write(value.z);
|
||||
writer.Write(value.w);
|
||||
}
|
||||
|
||||
public float4 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
|
||||
{
|
||||
if (reader.IsNil)
|
||||
{
|
||||
throw new InvalidOperationException("typecode is null, struct not supported");
|
||||
}
|
||||
|
||||
var length = reader.ReadArrayHeader();
|
||||
var x = default(float);
|
||||
var y = default(float);
|
||||
var z = default(float);
|
||||
var w = default(float);
|
||||
for (int i = 0; i < length; i++)
|
||||
{
|
||||
var key = i;
|
||||
switch (key)
|
||||
{
|
||||
case 0:
|
||||
x = reader.ReadSingle();
|
||||
break;
|
||||
case 1:
|
||||
y = reader.ReadSingle();
|
||||
break;
|
||||
case 2:
|
||||
z = reader.ReadSingle();
|
||||
break;
|
||||
case 3:
|
||||
w = reader.ReadSingle();
|
||||
break;
|
||||
default:
|
||||
reader.Skip();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var result = float4(x, y, z, w);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/MathFormatters.cs.meta
Normal file
11
Assets/Scripts/ServerShared/MathFormatters.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 02bc8e83a7f1cf54d94ebebcd3272a0d
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
73
Assets/Scripts/ServerShared/MathResolver.cs
Normal file
73
Assets/Scripts/ServerShared/MathResolver.cs
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using MessagePack;
|
||||
using MessagePack.Formatters;
|
||||
using Unity.Mathematics;
|
||||
using static Unity.Mathematics.math;
|
||||
|
||||
|
||||
public class MathResolver : IFormatterResolver
|
||||
{
|
||||
public static readonly MathResolver Instance = new MathResolver();
|
||||
|
||||
private MathResolver()
|
||||
{
|
||||
}
|
||||
|
||||
public IMessagePackFormatter<T> GetFormatter<T>()
|
||||
{
|
||||
return FormatterCache<T>.Formatter;
|
||||
}
|
||||
|
||||
private static class FormatterCache<T>
|
||||
{
|
||||
public static readonly IMessagePackFormatter<T> Formatter;
|
||||
|
||||
static FormatterCache()
|
||||
{
|
||||
Formatter = (IMessagePackFormatter<T>)MathResolverResolverGetFormatterHelper.GetFormatter(typeof(T));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static class MathResolverResolverGetFormatterHelper
|
||||
{
|
||||
private static readonly Dictionary<Type, object> FormatterMap = new Dictionary<Type, object>()
|
||||
{
|
||||
// standard
|
||||
{ typeof(float2), new Float2Formatter() },
|
||||
{ typeof(float3), new Float3Formatter() },
|
||||
{ typeof(float4), new Float4Formatter() },
|
||||
{ typeof(float2?), new StaticNullableFormatter<float2>(new Float2Formatter()) },
|
||||
{ typeof(float3?), new StaticNullableFormatter<float3>(new Float3Formatter()) },
|
||||
{ typeof(float4?), new StaticNullableFormatter<float4>(new Float4Formatter()) },
|
||||
|
||||
// standard + array
|
||||
{ typeof(float2[]), new ArrayFormatter<float2>() },
|
||||
{ typeof(float3[]), new ArrayFormatter<float3>() },
|
||||
{ typeof(float4[]), new ArrayFormatter<float4>() },
|
||||
{ typeof(float2?[]), new ArrayFormatter<float2?>() },
|
||||
{ typeof(float3?[]), new ArrayFormatter<float3?>() },
|
||||
{ typeof(float4?[]), new ArrayFormatter<float4?>() },
|
||||
|
||||
// standard + list
|
||||
{ typeof(List<float2>), new ListFormatter<float2>() },
|
||||
{ typeof(List<float3>), new ListFormatter<float3>() },
|
||||
{ typeof(List<float4>), new ListFormatter<float4>() },
|
||||
{ typeof(List<float2?>), new ListFormatter<float2?>() },
|
||||
{ typeof(List<float3?>), new ListFormatter<float3?>() },
|
||||
{ typeof(List<float4?>), new ListFormatter<float4?>() },
|
||||
};
|
||||
|
||||
internal static object GetFormatter(Type t)
|
||||
{
|
||||
object formatter;
|
||||
if (FormatterMap.TryGetValue(t, out formatter))
|
||||
{
|
||||
return formatter;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/MathResolver.cs.meta
Normal file
11
Assets/Scripts/ServerShared/MathResolver.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 80366c67f842eaf4dba339ed553e447c
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -3,6 +3,7 @@ using System.Collections;
|
|||
using System.Collections.Generic;
|
||||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
using Unity.Mathematics;
|
||||
|
||||
[MessagePackObject]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
|
|
@ -11,19 +12,19 @@ public class ZoneData : DatabaseEntry, INamedEntry
|
|||
[JsonProperty("name")] [Key(1)]
|
||||
public string Name;
|
||||
|
||||
[JsonProperty("radius")] [Key(2)]
|
||||
public float Radius = 500;
|
||||
[JsonProperty("position")] [Key(2)]
|
||||
public float2 Position = 500;
|
||||
|
||||
[JsonProperty("wormholes")] [Key(4)]
|
||||
[JsonProperty("wormholes")] [Key(3)]
|
||||
public List<Guid> Wormholes = new List<Guid>();
|
||||
|
||||
[JsonProperty("stations")] [Key(3)]
|
||||
[JsonProperty("stations")] [Key(4)]
|
||||
public List<Guid> Stations = new List<Guid>();
|
||||
|
||||
[JsonProperty("planets")] [Key(4)]
|
||||
[JsonProperty("planets")] [Key(5)]
|
||||
public List<Guid> Planets = new List<Guid>();
|
||||
|
||||
[JsonProperty("orbits")] [Key(5)]
|
||||
[JsonProperty("orbits")] [Key(6)]
|
||||
public List<Guid> Orbits = new List<Guid>();
|
||||
|
||||
[IgnoreMember] public string EntryName
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ public class ZoneGenerator
|
|||
// public float GasGiantMass = 2000;
|
||||
// public float RadiusPower = 1.75f;
|
||||
|
||||
public static Planet[] GenerateEntities(GameContext context, ZoneData data, float mass)
|
||||
public static Planet[] GenerateEntities(GameContext context, ZoneData data, float mass, float radius)
|
||||
{
|
||||
var random = new Random();
|
||||
random.InitState(unchecked((uint)data.Name.GetHashCode()));
|
||||
|
|
@ -34,7 +34,7 @@ public class ZoneGenerator
|
|||
Random = random,
|
||||
Context = context,
|
||||
Mass = mass,
|
||||
ChildDistanceMaximum = data.Radius,
|
||||
ChildDistanceMaximum = radius,
|
||||
ChildDistanceMinimum = context.PlanetRadius(mass)
|
||||
};
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue