blazing-console/Types/Location.cs

53 lines
No EOL
2 KiB
C#

/*
* Copyright 2024 Ivy Collective <sys@ivycollective.dev>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Text.Json;
using System.Text.Json.Serialization;
namespace blazingconsole.Types
{
[JsonConverter(typeof(LocationJsonConverter))]
public class Location(string worldName, double x, double y, double z, float yaw, float pitch)
{
public string WorldName { get; set; } = worldName;
public double X { get; set; } = x;
public double Y { get; set; } = y;
public double Z { get; set; } = z;
public float Yaw { get; set; } = yaw;
public float Pitch { get; set; } = pitch;
}
public class LocationJsonConverter : JsonConverter<Location>
{
public override void Write(Utf8JsonWriter writer, Location value, JsonSerializerOptions options)
{
if (value == null) {
writer.WriteNullValue();
} else {
writer.WriteStringValue($"{value.WorldName} {value.X} {value.Y} {value.Z} {value.Yaw} {value.Pitch}");
}
}
public override Location? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) {
var value = reader.GetString();
if (value == null) {
return null;
}
var parts = value.Split(' ');
return new Location(parts[0], double.Parse(parts[1]), double.Parse(parts[2]), double.Parse(parts[3]), float.Parse(parts[4]), float.Parse(parts[5]));
}
}
}