fix: Drastically simplifies regions (#1400)
### Summary
- [X] Gets rid of the Dtos
- [X] Simplifies the json serializer registration
- [X] Adds a custom `RegionByName` JsonConverter that can look up other regions that have already been registered.
### BREAKING CHANGE
1. **Child regions must appear after their parents in the JSON file**
2. In the regions json file, _"Parent"_ can no longer be just a string. It must be an object that includes the map.
- ```json
"Parent": { "Name": "Britain", "Map": "Felucca" }
```
This commit is contained in:
parent
734d20cbaf
commit
0a9bfb0558
47 changed files with 542 additions and 470 deletions
85
Projects/Server/Json/Converters/RegionByNameConverter.cs
Normal file
85
Projects/Server/Json/Converters/RegionByNameConverter.cs
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
/*************************************************************************
|
||||
* ModernUO *
|
||||
* Copyright 2019-2023 - ModernUO Development Team *
|
||||
* Email: hi@modernuo.com *
|
||||
* File: RegionByNameConverter.cs *
|
||||
* *
|
||||
* This program is free software: you can redistribute it and/or modify *
|
||||
* it under the terms of the GNU General Public License as published by *
|
||||
* the Free Software Foundation, either version 3 of the License, or *
|
||||
* (at your option) any later version. *
|
||||
* *
|
||||
* You should have received a copy of the GNU General Public License *
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
|
||||
*************************************************************************/
|
||||
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Server.Json;
|
||||
|
||||
public class RegionByNameConverter : JsonConverter<Region>
|
||||
{
|
||||
public override Region Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
string name = null;
|
||||
Map map = null;
|
||||
|
||||
if (reader.TokenType != JsonTokenType.StartObject)
|
||||
{
|
||||
throw new JsonException("Invalid json for RegionByName");
|
||||
}
|
||||
|
||||
while (true)
|
||||
{
|
||||
reader.Read();
|
||||
if (reader.TokenType == JsonTokenType.EndObject)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (reader.TokenType != JsonTokenType.PropertyName)
|
||||
{
|
||||
throw new JsonException("Invalid json for RegionByName");
|
||||
}
|
||||
|
||||
string property = reader.GetString()?.ToLower();
|
||||
|
||||
if (property != "name" && property != "map")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
reader.Read();
|
||||
if (reader.TokenType != JsonTokenType.String)
|
||||
{
|
||||
throw new JsonException($"Value for {property} must be a string");
|
||||
}
|
||||
|
||||
if (property == "name")
|
||||
{
|
||||
name = reader.GetString();
|
||||
}
|
||||
else
|
||||
{
|
||||
map = Map.Parse(reader.GetString());
|
||||
}
|
||||
}
|
||||
|
||||
if (name == null || map == null)
|
||||
{
|
||||
throw new JsonException("Invalid json for RegionByName");
|
||||
}
|
||||
|
||||
return Region.Find(name, map);
|
||||
}
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, Region value, JsonSerializerOptions options)
|
||||
{
|
||||
writer.WriteStartObject();
|
||||
writer.WriteString("Name", value.Name);
|
||||
writer.WriteString("Map", value.Map.Name);
|
||||
writer.WriteEndObject();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
/*************************************************************************
|
||||
* ModernUO *
|
||||
* Copyright 2019-2023 - ModernUO Development Team *
|
||||
* Email: hi@modernuo.com *
|
||||
* File: RegionByNameConverterFactory.cs *
|
||||
* *
|
||||
* This program is free software: you can redistribute it and/or modify *
|
||||
* it under the terms of the GNU General Public License as published by *
|
||||
* the Free Software Foundation, either version 3 of the License, or *
|
||||
* (at your option) any later version. *
|
||||
* *
|
||||
* You should have received a copy of the GNU General Public License *
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
|
||||
*************************************************************************/
|
||||
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Server.Json;
|
||||
|
||||
public class RegionByNameConverterFactory : JsonConverterFactory
|
||||
{
|
||||
public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(Region);
|
||||
|
||||
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) =>
|
||||
new RegionByNameConverter();
|
||||
}
|
||||
|
|
@ -1,5 +1,8 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json.Serialization;
|
||||
using Server.Json;
|
||||
using Server.Logging;
|
||||
using Server.Network;
|
||||
using Server.Targeting;
|
||||
|
|
@ -136,6 +139,7 @@ public class Region : IComparable<Region>
|
|||
{
|
||||
}
|
||||
|
||||
[JsonConstructor] // Don't include parent, since it is special
|
||||
public Region(string name, Map map, int priority, params Rectangle3D[] area) : this(name, map, null, area) =>
|
||||
Priority = priority;
|
||||
|
||||
|
|
@ -173,10 +177,10 @@ public class Region : IComparable<Region>
|
|||
}
|
||||
|
||||
// Used during deserialization only
|
||||
public Expansion MinExpansion { get; set; }
|
||||
public Expansion MinExpansion { get; set; } = Expansion.None;
|
||||
|
||||
// Used during deserialization only
|
||||
public Expansion MaxExpansion { get; set; }
|
||||
public Expansion MaxExpansion { get; set; } = Expansion.EJ;
|
||||
|
||||
public static List<Region> Regions { get; } = new();
|
||||
|
||||
|
|
@ -188,7 +192,9 @@ public class Region : IComparable<Region>
|
|||
|
||||
public Map Map { get; }
|
||||
|
||||
public Region Parent { get; }
|
||||
[JsonInclude]
|
||||
[JsonConverter(typeof(RegionByNameConverter))]
|
||||
public Region Parent { get; private set; }
|
||||
|
||||
public List<Region> Children { get; } = new();
|
||||
|
||||
|
|
|
|||
|
|
@ -1,67 +0,0 @@
|
|||
/*************************************************************************
|
||||
* ModernUO *
|
||||
* Copyright 2019-2022 - ModernUO Development Team *
|
||||
* Email: hi@modernuo.com *
|
||||
* File: RegionJsonDto.cs *
|
||||
* *
|
||||
* This program is free software: you can redistribute it and/or modify *
|
||||
* it under the terms of the GNU General Public License as published by *
|
||||
* the Free Software Foundation, either version 3 of the License, or *
|
||||
* (at your option) any later version. *
|
||||
* *
|
||||
* You should have received a copy of the GNU General Public License *
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
|
||||
*************************************************************************/
|
||||
|
||||
using System;
|
||||
using System.Text.Json.Serialization;
|
||||
using Server.Utilities;
|
||||
|
||||
namespace Server;
|
||||
|
||||
public class RegionJsonDto
|
||||
{
|
||||
public Expansion MinExpansion { get; set; } = Expansion.None;
|
||||
|
||||
public Expansion? MaxExpansion { get; set; } = Expansion.EJ;
|
||||
|
||||
[JsonIgnore]
|
||||
public virtual Type RegionType => typeof(Region);
|
||||
|
||||
public Map Map { get; set; }
|
||||
public string? Parent { get; set; }
|
||||
public string Name { get; set; }
|
||||
public int? Priority { get; set; }
|
||||
public Rectangle3D[] Area { get; set; }
|
||||
public Point3D GoLocation { get; set; }
|
||||
public MusicName? Music { get; set; }
|
||||
|
||||
public virtual void FromRegion(Region region)
|
||||
{
|
||||
Map = region.Map;
|
||||
Parent = region.Parent?.Name;
|
||||
Name = region.Name;
|
||||
Priority = region.Priority;
|
||||
Area = region.Area;
|
||||
GoLocation = region.GoLocation;
|
||||
Music = region.Music != MusicName.Invalid && region.Music != region.DefaultMusic ? region.Music : null;
|
||||
MaxExpansion = region.MaxExpansion == Expansion.EJ ? null : region.MaxExpansion;
|
||||
MinExpansion = region.MinExpansion;
|
||||
}
|
||||
|
||||
public Region ToRegion()
|
||||
{
|
||||
var region = Priority != null
|
||||
? RegionType.CreateInstance<Region>(Name, Map, Region.Find(Parent, Map), Priority, Area)
|
||||
: RegionType.CreateInstance<Region>(Name, Map, Region.Find(Parent, Map), Area);
|
||||
|
||||
HydrateRegion(region);
|
||||
return region;
|
||||
}
|
||||
|
||||
protected virtual void HydrateRegion(Region region)
|
||||
{
|
||||
region.GoLocation = GoLocation;
|
||||
region.Music = Music ?? region.DefaultMusic;
|
||||
}
|
||||
}
|
||||
|
|
@ -22,7 +22,6 @@ using System.Text.Json.Serialization;
|
|||
using System.Text.Json.Serialization.Metadata;
|
||||
using Server.Json;
|
||||
using Server.Logging;
|
||||
using Server.Utilities;
|
||||
|
||||
namespace Server;
|
||||
|
||||
|
|
@ -30,10 +29,7 @@ public static class RegionJsonSerializer
|
|||
{
|
||||
private static readonly ILogger logger = LogFactory.GetLogger(typeof(RegionJsonSerializer));
|
||||
|
||||
// Note: This is filled during the `Configure` phase by RegisterRegionForSerialization,
|
||||
// so it is not available to a JsonConverter which might be used during earlier phases.
|
||||
private static Dictionary<Type, Type> _regionToDtoLookup = new() { { typeof(Region), typeof(RegionJsonDto) } };
|
||||
private static JsonDerivedType[] _derivedTypes = { new(typeof(RegionJsonDto), nameof(Region)) };
|
||||
private static JsonDerivedType[] _derivedTypes = { new(typeof(Region), nameof(Region)) };
|
||||
|
||||
private static JsonSerializerOptions _options = new(JsonConfig.DefaultOptions)
|
||||
{
|
||||
|
|
@ -44,7 +40,7 @@ public static class RegionJsonSerializer
|
|||
{
|
||||
static typeInfo =>
|
||||
{
|
||||
if (typeInfo.Type != typeof(RegionJsonDto))
|
||||
if (typeInfo.Type != typeof(Region))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
|
@ -55,26 +51,39 @@ public static class RegionJsonSerializer
|
|||
typeInfo.PolymorphismOptions.DerivedTypes.Add(_derivedTypes[i]);
|
||||
}
|
||||
},
|
||||
static typeInfo =>
|
||||
{
|
||||
if (!typeInfo.Type.IsAssignableTo(typeof(Region)))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
typeInfo.OnDeserialized = o =>
|
||||
{
|
||||
if (o is Region region && Core.Expansion >= region.MinExpansion && Core.Expansion <= region.MaxExpansion)
|
||||
{
|
||||
region.Register();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
public static void Register<TDto, TRegion>()
|
||||
where TDto : RegionJsonDto, new() where TRegion : Region
|
||||
public static void Register<TRegion>() where TRegion : Region
|
||||
{
|
||||
for (var i = 0; i < _derivedTypes.Length; i++)
|
||||
{
|
||||
if (_derivedTypes[i].DerivedType == typeof(TDto))
|
||||
if (_derivedTypes[i].DerivedType == typeof(TRegion))
|
||||
{
|
||||
throw new Exception(
|
||||
$"Type '{typeof(TDto)}' has already been registered for serialization with the region loader."
|
||||
$"Type '{typeof(TRegion)}' has already been registered for serialization with the region loader."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Array.Resize(ref _derivedTypes, _derivedTypes.Length + 1);
|
||||
_derivedTypes[^1] = new JsonDerivedType(typeof(TDto), typeof(TRegion).Name);
|
||||
_regionToDtoLookup[typeof(TRegion)] = typeof(TDto);
|
||||
_derivedTypes[^1] = new JsonDerivedType(typeof(TRegion), typeof(TRegion).Name);
|
||||
}
|
||||
|
||||
internal static void LoadRegions()
|
||||
|
|
@ -85,19 +94,17 @@ public static class RegionJsonSerializer
|
|||
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
|
||||
var regions = JsonConfig.Deserialize<List<RegionJsonDto>>(path, _options);
|
||||
var regions = JsonConfig.Deserialize<List<Region>>(path, _options);
|
||||
if (regions == null)
|
||||
{
|
||||
throw new JsonException($"Failed to deserialize {path}.");
|
||||
}
|
||||
|
||||
var count = 0;
|
||||
foreach (var dto in regions)
|
||||
foreach (var region in regions)
|
||||
{
|
||||
if (Core.Expansion >= dto.MinExpansion && Core.Expansion <= dto.MaxExpansion)
|
||||
if (Core.Expansion >= region.MinExpansion && Core.Expansion <= region.MaxExpansion)
|
||||
{
|
||||
var region = dto.ToRegion();
|
||||
region.Register();
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
|
@ -111,43 +118,4 @@ public static class RegionJsonSerializer
|
|||
stopwatch.Elapsed.TotalSeconds
|
||||
);
|
||||
}
|
||||
|
||||
// Note: This is not thread safe. To make `SerializeRegions` threadsafe, use `[ThreadStatic]` or just create the lists
|
||||
// in the function and take the GC hit.
|
||||
private static List<RegionJsonDto> _regionJsonDtos;
|
||||
|
||||
public static void SerializeRegions(string path, IEnumerable<Region> regions)
|
||||
{
|
||||
_regionJsonDtos ??= new List<RegionJsonDto>();
|
||||
foreach (var region in regions)
|
||||
{
|
||||
if (_regionToDtoLookup.TryGetValue(region.GetType(), out var dtoType))
|
||||
{
|
||||
var dto = dtoType.CreateInstance<RegionJsonDto>();
|
||||
dto.FromRegion(region);
|
||||
_regionJsonDtos.Add(dto);
|
||||
}
|
||||
}
|
||||
|
||||
JsonConfig.Serialize(path, _regionJsonDtos, _options);
|
||||
_regionJsonDtos.Clear();
|
||||
}
|
||||
|
||||
public static string SerializeRegions(IEnumerable<Region> regions)
|
||||
{
|
||||
_regionJsonDtos ??= new List<RegionJsonDto>();
|
||||
foreach (var region in regions)
|
||||
{
|
||||
if (_regionToDtoLookup.TryGetValue(region.GetType(), out var dtoType))
|
||||
{
|
||||
var dto = dtoType.CreateInstance<RegionJsonDto>();
|
||||
dto.FromRegion(region);
|
||||
_regionJsonDtos.Add(dto);
|
||||
}
|
||||
}
|
||||
|
||||
var output = JsonConfig.Serialize(_regionJsonDtos, _options);
|
||||
_regionJsonDtos.Clear();
|
||||
return output;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue