49 lines
1.5 KiB
C#
49 lines
1.5 KiB
C#
|
using System;
|
||
|
|
||
|
using Syntriax.Engine.Core;
|
||
|
|
||
|
using YamlDotNet.Core;
|
||
|
using YamlDotNet.Core.Events;
|
||
|
using YamlDotNet.Serialization;
|
||
|
|
||
|
namespace Engine.Serialization;
|
||
|
|
||
|
internal class Vector2DYamlConverter : IYamlTypeConverter
|
||
|
{
|
||
|
public bool Accepts(Type type) => type == typeof(Vector2D);
|
||
|
|
||
|
public object? ReadYaml(IParser parser, Type type)
|
||
|
{
|
||
|
if (parser.Current is not MappingStart)
|
||
|
throw new InvalidOperationException("Expected MappingStart");
|
||
|
|
||
|
parser.MoveNext();
|
||
|
float x = 0.0f;
|
||
|
float y = 0.0f;
|
||
|
|
||
|
while (parser.Current != null && parser.Current is not MappingEnd)
|
||
|
{
|
||
|
var propertyName = ((Scalar)parser.Current).Value;
|
||
|
parser.MoveNext();
|
||
|
switch (propertyName)
|
||
|
{
|
||
|
case nameof(Vector2D.X): x = float.Parse(((Scalar)parser.Current).Value); break;
|
||
|
case nameof(Vector2D.Y): y = float.Parse(((Scalar)parser.Current).Value); break;
|
||
|
}
|
||
|
parser.MoveNext();
|
||
|
}
|
||
|
return new Vector2D(x, y);
|
||
|
}
|
||
|
|
||
|
public void WriteYaml(IEmitter emitter, object? value, Type type)
|
||
|
{
|
||
|
var vector = (Vector2D)(value ?? throw new Exception());
|
||
|
emitter.Emit(new MappingStart());
|
||
|
emitter.Emit(new Scalar(nameof(Vector2D.X)));
|
||
|
emitter.Emit(new Scalar(vector.X.ToString()));
|
||
|
emitter.Emit(new Scalar(nameof(Vector2D.Y)));
|
||
|
emitter.Emit(new Scalar(vector.Y.ToString()));
|
||
|
emitter.Emit(new MappingEnd());
|
||
|
}
|
||
|
}
|