feat: Source generated Serialization/Deserialization (#550)

### Features
* Fully abstracts serialization by using compile-time attributes.
* Supports serializing the following:
  - Primitives (integers, strings, etc)
  - IP Addresses
  - BigDecimal
  - DateTime, Delta DateTimes
  - TimeSpan
  - Server.Race
  - Server.Map
  - Point2D, Point3D, Rect2D, Rect3D
  - Existing/New `ISerializable` references
  - Lists/Sets of serializable types
  - Type with a `Serialize` method and constructor that takes an `IGenericReader`
* Supports forward-only migration
* Supports existing RunUO deserialization for older versions by changing to the following signature:
  - `public void OldDeserialize(IGenericReader reader, int version)`
  - Must remove deserializing the version since this is already done
* Supports serializing from private fields or custom made properties.
* Types do not require inheriting Item/Mobile. Code gen will fully create `ISerializable` information.
  - This is not recommended yet, since it requires wiring to `Persistence` which will cause lots of unresolved symbol errors until code gen is built.

### Example
```cs
using System.Collections.Generic;

namespace Server.Items
{
    [Serializable(1)]
    public partial class TestItem1 : Item
    {
        [SerializableField(1)]
        [SerializableFieldAttr("[CommandProperty(AccessLevel.Administrator)]")]
        private List<Item> _someProperty;

        private void Deserialize(IGenericReader reader, int version)
        {
        }
    }
}
```

Generates this:
```cs
namespace Server.Items
{
    public partial class TestItem1
    {
#pragma warning disable 0414
        private const int _version = 1;
#pragma warning restore 0414

        [CommandProperty(AccessLevel.Administrator)]
        public System.Collections.Generic.List<Server.Item> SomeProperty
        {
            get => _someProperty;
            set
            {
                if (value != _someProperty)
                {
                    ((ISerializable)this).MarkDirty();
                    _someProperty = value;
                }
            }
        }

        public TestItem1(Serial serial) : base(serial)
        {
        }

        public override void Serialize(IGenericWriter writer)
        {
            var savePosition = ((Server.ISerializable)this).SavePosition;
            if (savePosition > -1)
            {
                writer.Seek(savePosition, System.IO.SeekOrigin.Begin);
                return;
            }
            writer.WriteEncodedInt(_version);
            writer.Write(_someProperty);
        }

        public override void Deserialize(IGenericReader reader)
        {
            var version = reader.ReadEncodedInt();
            if (version < 1)
            {
                OldDeserialize(reader, version);
                ((Server.ISerializable)this).MarkDirty();
                return;
            }
            SomeProperty = reader.ReadEntityList<Server.Item>();
        }
    }
}
```

And this:
```json
{
  "version": 1,
  "type": "TestItem1",
  "properties": [
    {
      "name": "SomeProperty",
      "type": "System.Collections.Generic.List\u003CServer.Item\u003E",
      "rule": "ListMigrationRule",
      "ruleArguments": [
        "Server.Item",
        "SerializableInterfaceMigrationRule"
      ]
    }
  ]
}
```
This commit is contained in:
Kamron Batman 2021-05-23 21:06:23 -07:00 • committed by GitHub
parent cb66bef0e5
commit 9afa4e4cab
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
61 changed files with 3203 additions and 142 deletions

View file

@ -1,8 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using Microsoft.Toolkit.HighPerformance;
using Server.Accounting;
using Server.Buffers;
@ -379,22 +377,6 @@ namespace Server
Cured
}
[Serializable]
public class MobileNotConnectedException : Exception
{
public MobileNotConnectedException(Mobile source, string message)
: base(message) =>
Source = source.ToString();
public MobileNotConnectedException(Mobile source, string message, Exception innerException)
: base(message, innerException) =>
Source = source.ToString();
protected MobileNotConnectedException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
public delegate bool SkillCheckTargetHandler(
Mobile from, SkillName skill, object target, double minSkill,
double maxSkill
@ -413,8 +395,7 @@ namespace Server
public delegate bool AllowHarmfulHandler(Mobile from, Mobile target);
public delegate Container CreateCorpseHandler(
Mobile from, HairInfo hair, FacialHairInfo facialhair,
List<Item> initialContent, List<Item> equippedItems
Mobile from, HairInfo hair, FacialHairInfo facialhair, List<Item> initialContent, List<Item> equippedItems
);
public delegate int AOSStatusHandler(Mobile from, int index);
@ -570,8 +551,17 @@ namespace Server
private bool m_YellowHealthbar;
// Position in the save buffer where serialization ends. -1 if dirty
private int _savePosition = -1;
public Mobile()
{
m_Region = Map.Internal.DefaultRegion;
Serial = World.NewMobile;
DefaultMobileInit();
World.AddEntity(this);
SetTypeRef(GetType());
}
public Mobile(Serial serial)
{
@ -582,31 +572,16 @@ namespace Server
NextSkillTime = Core.TickCount;
DamageEntries = new List<DamageEntry>();
var ourType = GetType();
TypeRef = World.MobileTypes.IndexOf(ourType);
if (TypeRef == -1)
{
World.MobileTypes.Add(ourType);
TypeRef = World.MobileTypes.Count - 1;
}
SetTypeRef(GetType());
}
public Mobile()
public void SetTypeRef(Type type)
{
m_Region = Map.Internal.DefaultRegion;
Serial = World.NewMobile;
DefaultMobileInit();
World.AddEntity(this);
var ourType = GetType();
TypeRef = World.MobileTypes.IndexOf(ourType);
TypeRef = World.MobileTypes.IndexOf(type);
if (TypeRef == -1)
{
World.MobileTypes.Add(ourType);
World.MobileTypes.Add(type);
TypeRef = World.MobileTypes.Count - 1;
}
}
@ -2547,22 +2522,17 @@ namespace Server
AddNameProperties(list);
}
long ISerializable.SavePosition { get; set; }
BufferWriter ISerializable.SaveBuffer { get; set; }
[CommandProperty(AccessLevel.Counselor)]
public Serial Serial { get; }
public int TypeRef { get; }
public int TypeRef { get; private set; }
public virtual void Serialize(IGenericWriter writer)
{
// The item is clean, so let's skip
if (_savePosition > -1)
{
writer.Seek(_savePosition, SeekOrigin.Begin);
return;
}
writer.Write(32); // version
writer.WriteDeltaTime(LastStrGain);
@ -8373,7 +8343,7 @@ namespace Server
public void Yell(int number, string args = "") =>
PublicOverheadMessage(MessageType.Yell, YellHue, number, args);
public bool SendHuePicker(HuePicker p, bool throwOnOffline = false)
public bool SendHuePicker(HuePicker p)
{
if (m_NetState != null)
{
@ -8381,11 +8351,6 @@ namespace Server
return true;
}
if (throwOnOffline)
{
throw new MobileNotConnectedException(this, "Hue picker could not be sent.");
}
return false;
}