88 lines
2.8 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using Syntriax.Engine.Core;
using Syntriax.Engine.Core.Serialization;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;
namespace Syntriax.Engine.Serializers.Yaml;
public class UniverseConverter : EngineTypeYamlSerializerBase<IUniverse>
{
public override IUniverse? Read(IParser parser, Type type, ObjectDeserializer rootDeserializer)
{
string id;
IUniverse universe;
IStateEnable stateEnable;
List<IUniverseObject> universeObjects;
parser.Consume<MappingStart>();
if (parser.Consume<Scalar>().Value.CompareTo(nameof(IUniverse.Id)) != 0)
throw new();
id = parser.Consume<Scalar>().Value;
if (parser.Consume<Scalar>().Value.CompareTo(SERIALIZED_SCALAR_NAME) != 0)
throw new();
SerializedClass instanceSerializedClass = (SerializedClass)rootDeserializer(typeof(SerializedClass))!;
universe = (IUniverse)instanceSerializedClass.CreateInstance(EntityRegistry);
if (parser.Consume<Scalar>().Value.CompareTo(nameof(IUniverse.StateEnable)) != 0)
throw new();
stateEnable = (IStateEnable)rootDeserializer(typeof(IStateEnable))!;
if (parser.Consume<Scalar>().Value.CompareTo(nameof(IUniverse.UniverseObjects)) != 0)
throw new();
universeObjects = (List<IUniverseObject>)rootDeserializer(typeof(List<IUniverseObject>))!;
parser.Consume<MappingEnd>();
universe.Id = id;
stateEnable.Assign(universe);
universe.Assign(stateEnable);
foreach (IUniverseObject uo in universeObjects)
universe.Register(uo);
return universe;
}
public override void WriteYaml(IEmitter emitter, object? value, Type type, ObjectSerializer serializer)
{
IUniverse universe = (IUniverse)value!;
IEnumerable<IUniverseObject> rootUniverseObjects = universe.UniverseObjects
.Select(uo =>
{
IUniverseObject root = uo;
while (root.Parent is IUniverseObject parent)
root = parent;
return root;
})
.Where(uo => !uo.GetType().HasAttribute<IgnoreSerializationAttribute>())
.Distinct();
emitter.Emit(new MappingStart());
emitter.Emit(new Scalar(nameof(IUniverse.Id)));
emitter.Emit(new Scalar(universe.Id));
emitter.Emit(new Scalar(SERIALIZED_SCALAR_NAME));
serializer(new SerializedClass(universe));
emitter.Emit(new Scalar(nameof(IUniverse.StateEnable)));
serializer(universe.StateEnable);
emitter.Emit(new Scalar(nameof(IUniverse.UniverseObjects)));
serializer(rootUniverseObjects);
emitter.Emit(new MappingEnd());
}
}