48 lines
1.5 KiB
C#
48 lines
1.5 KiB
C#
using Syntriax.Engine.Core;
|
|
|
|
using YamlDotNet.Core;
|
|
using YamlDotNet.Core.Events;
|
|
using YamlDotNet.Serialization;
|
|
|
|
namespace Syntriax.Engine.Serialization;
|
|
|
|
public class Shape2DConverter : IEngineTypeYamlConverter
|
|
{
|
|
public bool Accepts(Type type) => type == typeof(Shape2D);
|
|
|
|
public object? ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer)
|
|
{
|
|
parser.Consume<MappingStart>();
|
|
|
|
if (parser.Consume<Scalar>().Value.CompareTo(nameof(Shape2D.Vertices)) != 0)
|
|
throw new ArgumentException($"{nameof(Shape2D)} mapping have a {nameof(Shape2D.Vertices)}");
|
|
|
|
parser.Consume<SequenceStart>();
|
|
|
|
List<Vector2D> vertices = [];
|
|
|
|
while (!parser.TryConsume<SequenceEnd>(out _))
|
|
{
|
|
Vector2D vertex = (Vector2D)rootDeserializer(typeof(Vector2D))!;
|
|
vertices.Add(vertex);
|
|
}
|
|
|
|
parser.Consume<MappingEnd>();
|
|
|
|
return new Shape2D(vertices);
|
|
}
|
|
|
|
public void WriteYaml(IEmitter emitter, object? value, Type type, ObjectSerializer serializer)
|
|
{
|
|
Shape2D shape2D = (Shape2D)value!;
|
|
|
|
emitter.Emit(new MappingStart());
|
|
emitter.Emit(new Scalar(nameof(Shape2D.Vertices)));
|
|
emitter.Emit(new SequenceStart(anchor: null, tag: null, isImplicit: false, style: SequenceStyle.Block));
|
|
foreach (Vector2D vertex in shape2D.Vertices)
|
|
serializer(vertex, typeof(Vector2D));
|
|
emitter.Emit(new SequenceEnd());
|
|
emitter.Emit(new MappingEnd());
|
|
}
|
|
}
|