Merge pull request #28 from dcronqvist/map-custom-types
Add custom types generation and mapping API
|
@ -42,6 +42,9 @@
|
||||||
"_appTitle": "DotTiled",
|
"_appTitle": "DotTiled",
|
||||||
"_enableSearch": true,
|
"_enableSearch": true,
|
||||||
"pdf": false
|
"pdf": false
|
||||||
}
|
},
|
||||||
|
"xref": [
|
||||||
|
"https://learn.microsoft.com/en-us/dotnet/.xrefmap.json"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -66,11 +66,14 @@ Tiled supports a variety of property types, which are represented in the DotTile
|
||||||
- `object` - <xref:DotTiled.ObjectProperty>
|
- `object` - <xref:DotTiled.ObjectProperty>
|
||||||
- `string` - <xref:DotTiled.StringProperty>
|
- `string` - <xref:DotTiled.StringProperty>
|
||||||
|
|
||||||
In addition to these primitive property types, [Tiled also supports more complex property types](https://doc.mapeditor.org/en/stable/manual/custom-properties/#custom-types). These custom property types are defined in Tiled according to the linked documentation, and to work with them in DotTiled, you *must* define their equivalences as a <xref:DotTiled.ICustomTypeDefinition>. You must then provide a resolving function to a defined type given a custom type name, as it is defined in Tiled.
|
In addition to these primitive property types, [Tiled also supports more complex property types](https://doc.mapeditor.org/en/stable/manual/custom-properties/#custom-types). These custom property types are defined in Tiled according to the linked documentation, and to work with them in DotTiled, you *must* define their equivalences as a <xref:DotTiled.ICustomTypeDefinition>. This is because of how Tiled handles default values for custom property types, and DotTiled needs to know these defaults to be able to populate the properties correctly.
|
||||||
|
|
||||||
## Custom types
|
## Custom types
|
||||||
|
|
||||||
Tiled allows you to define custom property types that can be used in your maps. These custom property types can be of type `class` or `enum`. DotTiled supports custom property types by allowing you to define the equivalent in C# and then providing a custom type resolver function that will return the equivalent definition given a custom type name.
|
Tiled allows you to define custom property types that can be used in your maps. These custom property types can be of type `class` or `enum`. DotTiled supports custom property types by allowing you to define the equivalent in C#. This section will guide you through how to define custom property types in DotTiled and how to map properties in loaded maps to C# classes or enums.
|
||||||
|
|
||||||
|
> [!NOTE]
|
||||||
|
> In the future, DotTiled could provide a way to configure the use of custom property types such that they aren't necessary to be defined, given that you have set the `Resolve object types and properties` setting in Tiled.
|
||||||
|
|
||||||
### Class properties
|
### Class properties
|
||||||
|
|
||||||
|
@ -88,14 +91,39 @@ var monsterSpawnerDefinition = new CustomClassDefinition
|
||||||
Name = "MonsterSpawner",
|
Name = "MonsterSpawner",
|
||||||
UseAs = CustomClassUseAs.All, // Not really validated by DotTiled
|
UseAs = CustomClassUseAs.All, // Not really validated by DotTiled
|
||||||
Members = [ // Make sure that the default values match the Tiled UI
|
Members = [ // Make sure that the default values match the Tiled UI
|
||||||
new BoolProperty { Name = "enabled", Value = true },
|
new BoolProperty { Name = "Enabled", Value = true },
|
||||||
new IntProperty { Name = "maxSpawnAmount", Value = 10 },
|
new IntProperty { Name = "MaxSpawnAmount", Value = 10 },
|
||||||
new IntProperty { Name = "minSpawnAmount", Value = 0 },
|
new IntProperty { Name = "MinSpawnAmount", Value = 0 },
|
||||||
new StringProperty { Name = "monsterNames", Value = "" }
|
new StringProperty { Name = "MonsterNames", Value = "" }
|
||||||
]
|
]
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Luckily, you don't have to manually define these custom class definitions, even though you most definitively can for scenarios that require it. DotTiled provides a way to automatically generate these definitions for you from a C# class. This is done by using the <xref:DotTiled.CustomClassDefinition.FromClass``1> method, or one of its overloads. This method will generate a <xref:DotTiled.CustomClassDefinition> from a given C# class, and you can then use this definition when loading your maps.
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
class MonsterSpawner
|
||||||
|
{
|
||||||
|
public bool Enabled { get; set; } = true;
|
||||||
|
public int MaxSpawnAmount { get; set; } = 10;
|
||||||
|
public int MinSpawnAmount { get; set; } = 0;
|
||||||
|
public string MonsterNames { get; set; } = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
// ...
|
||||||
|
|
||||||
|
// These are all valid ways to create your custom class definitions from a C# class
|
||||||
|
// The first two require the class to have a default, parameterless constructor
|
||||||
|
var monsterSpawnerDefinition1 = CustomClassDefinition.FromClass<MonsterSpawner>();
|
||||||
|
var monsterSpawnerDefinition2 = CustomClassDefinition.FromClass(typeof(MonsterSpawner));
|
||||||
|
var monsterSpawnerDefinition3 = CustomClassDefinition.FromClass(() => new MonsterSpawner
|
||||||
|
{
|
||||||
|
Enabled = false // This will use the property values in the instance created by a factory method as the default values
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
The last one is especially useful if you have classes that may not have parameterless constructors, or if you want to provide custom default values for the properties. Finally, the generated custom class definition will be identical to the one defined manually in the first example.
|
||||||
|
|
||||||
### Enum properties
|
### Enum properties
|
||||||
|
|
||||||
Tiled also allows you to define custom property types that work as enums. Similarly to `class` properties, you must define the equivalent in DotTiled as a <xref:DotTiled.CustomEnumDefinition>. You can then return the corresponding definition in the resolving function.
|
Tiled also allows you to define custom property types that work as enums. Similarly to `class` properties, you must define the equivalent in DotTiled as a <xref:DotTiled.CustomEnumDefinition>. You can then return the corresponding definition in the resolving function.
|
||||||
|
@ -110,7 +138,7 @@ The equivalent definition in DotTiled would look like the following:
|
||||||
var entityTypeDefinition = new CustomEnumDefinition
|
var entityTypeDefinition = new CustomEnumDefinition
|
||||||
{
|
{
|
||||||
Name = "EntityType",
|
Name = "EntityType",
|
||||||
StorageType = CustomEnumStorageType.String,
|
StorageType = CustomEnumStorageType.Int,
|
||||||
ValueAsFlags = false,
|
ValueAsFlags = false,
|
||||||
Values = [
|
Values = [
|
||||||
"Bomb",
|
"Bomb",
|
||||||
|
@ -121,23 +149,9 @@ var entityTypeDefinition = new CustomEnumDefinition
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
### [Future] Automatically map custom property `class` types to C# classes
|
Similarly to custom class definitions, you can also automatically generate custom enum definitions from C# enums. This is done by using the <xref:DotTiled.CustomEnumDefinition.FromEnum``1> method, or one of its overloads. This method will generate a <xref:DotTiled.CustomEnumDefinition> from a given C# enum, and you can then use this definition when loading your maps.
|
||||||
|
|
||||||
In the future, DotTiled will support automatically mapping custom property `class` types to C# classes. This will allow you to define a C# class that matches the structure of the `class` property in Tiled, and DotTiled will automatically map the properties of the `class` property to the properties of the C# class. This will make working with `class` properties much easier and more intuitive.
|
|
||||||
|
|
||||||
The idea is to expand on the <xref:DotTiled.IHasProperties> interface with a method like `GetMappedProperty<T>(string propertyName)`, where `T` is a class that matches the structure of the `class` property in Tiled.
|
|
||||||
|
|
||||||
This functionality would be accompanied by a way to automatically create a matching <xref:DotTiled.ICustomTypeDefinition> given a C# class or enum. Something like this would then be possible:
|
|
||||||
|
|
||||||
```csharp
|
```csharp
|
||||||
class MonsterSpawner
|
|
||||||
{
|
|
||||||
public bool Enabled { get; set; } = true;
|
|
||||||
public int MaxSpawnAmount { get; set; } = 10;
|
|
||||||
public int MinSpawnAmount { get; set; } = 0;
|
|
||||||
public string MonsterNames { get; set; } = "";
|
|
||||||
}
|
|
||||||
|
|
||||||
enum EntityType
|
enum EntityType
|
||||||
{
|
{
|
||||||
Bomb,
|
Bomb,
|
||||||
|
@ -146,16 +160,89 @@ enum EntityType
|
||||||
Chair
|
Chair
|
||||||
}
|
}
|
||||||
|
|
||||||
var monsterSpawnerDefinition = CustomClassDefinition.FromClass<MonsterSpawner>();
|
|
||||||
var entityTypeDefinition = CustomEnumDefinition.FromEnum<EntityType>();
|
|
||||||
|
|
||||||
// ...
|
// ...
|
||||||
|
|
||||||
var map = LoadMap();
|
// These are both valid ways to create your custom enum definitions from a C# enum
|
||||||
var monsterSpawner = map.GetMappedProperty<MonsterSpawner>("monsterSpawnerPropertyInMap");
|
var entityTypeDefinition1 = CustomEnumDefinition.FromEnum<EntityType>();
|
||||||
var entityType = map.GetMappedProperty<EntityType>("entityTypePropertyInMap");
|
var entityTypeDefinition2 = CustomEnumDefinition.FromEnum(typeof(EntityType));
|
||||||
```
|
```
|
||||||
|
|
||||||
Finally, it might be possible to also make some kind of exporting functionality for <xref:DotTiled.ICustomTypeDefinition>. Given a collection of custom type definitions, DotTiled could generate a corresponding `propertytypes.json` file that you then can import into Tiled. This would make it so that you only have to define your custom property types once (in C#) and then import them into Tiled to use them in your maps.
|
The generated custom enum definition will be identical to the one defined manually in the first example.
|
||||||
|
|
||||||
Depending on implementation this might become something that can inhibit native AOT compilation due to potential reflection usage. Source generators could be used to mitigate this, but it is not yet clear how this will be implemented.
|
For enum definitions, the <xref:System.FlagsAttribute> can be used to indicate that the enum should be treated as a flags enum. This will make it so the enum definition will have `ValueAsFlags = true` and the enum values will be treated as flags when working with them in DotTiled.
|
||||||
|
|
||||||
|
## Mapping properties to C# classes or enums
|
||||||
|
|
||||||
|
So far, we have only discussed how to define custom property types in DotTiled, and why they are needed. However, the most important part is how you can map properties inside your maps to their corresponding C# classes or enums.
|
||||||
|
|
||||||
|
The interface <xref:DotTiled.IHasProperties> has two overloads of the <xref:DotTiled.IHasProperties.MapPropertiesTo``1> method. These methods allow you to map a collection of properties to a given C# class. Let's look at an example:
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
// Define a few Tiled compatible custom types
|
||||||
|
enum EntityType
|
||||||
|
{
|
||||||
|
Player,
|
||||||
|
Enemy,
|
||||||
|
Collectible,
|
||||||
|
Explosive
|
||||||
|
}
|
||||||
|
|
||||||
|
class EntityData
|
||||||
|
{
|
||||||
|
public EntityType Type { get; set; } = EntityType.Player;
|
||||||
|
public int Health { get; set; } = 100;
|
||||||
|
public string Name { get; set; } = "Unnamed Entity";
|
||||||
|
}
|
||||||
|
|
||||||
|
var entityTypeDef = CustomEnumDefinition.FromEnum<EntityType>();
|
||||||
|
var entityDataDef = CustomClassDefinition.FromClass<EntityData>();
|
||||||
|
```
|
||||||
|
|
||||||
|
The above gives us two custom type definitions that we can supply to our map loader. Given a map that looks like this:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<map version="1.10" tiledversion="1.11.0" orientation="orthogonal" renderorder="right-down" width="5" height="5" tilewidth="32" tileheight="32" infinite="0" nextlayerid="8" nextobjectid="7">
|
||||||
|
<tileset firstgid="1" source="tileset.tsx"/>
|
||||||
|
<layer id="1" name="Tile Layer 1" width="5" height="5">
|
||||||
|
<data encoding="csv">
|
||||||
|
1,1,1,1,1,
|
||||||
|
0,0,0,0,0,
|
||||||
|
0,0,0,0,0,
|
||||||
|
0,0,0,0,0,
|
||||||
|
0,0,0,0,0
|
||||||
|
</data>
|
||||||
|
</layer>
|
||||||
|
<objectgroup id="3" name="Objects">
|
||||||
|
<object id="4" name="Circle1" type="EntityData" x="77" y="72.3333" width="34.6667" height="34.6667">
|
||||||
|
<properties>
|
||||||
|
<property name="Health" type="int" value="1"/>
|
||||||
|
<property name="Name" value="Bomb Chest"/>
|
||||||
|
<property name="Type" type="int" propertytype="EntityType" value="3"/>
|
||||||
|
</properties>
|
||||||
|
<ellipse/>
|
||||||
|
</object>
|
||||||
|
</objectgroup>
|
||||||
|
</map>
|
||||||
|
```
|
||||||
|
|
||||||
|
We can see that there is an ellipse object in the map that has the type `EntityData` and it has set the three properties to some value other than their defaults. After having loaded this map, we can map the properties of the object to the `EntityData` class like this:
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
var map = LoadMap([entityTypeDef, entityDataDef]); // Load the map somehow, using DotTiled.Loader or similar
|
||||||
|
|
||||||
|
// Retrieve the object layer from the map in some way
|
||||||
|
var objectLayer = map.Layers.Skip(1).First() as ObjectLayer;
|
||||||
|
|
||||||
|
// Retrieve the object from the object layer
|
||||||
|
var entityObject = objectLayer.Objects.First();
|
||||||
|
|
||||||
|
// Map the properties of the object to the EntityData class
|
||||||
|
var entityData = entityObject.MapPropertiesTo<EntityData>();
|
||||||
|
```
|
||||||
|
|
||||||
|
The above snippet will map the properties of the object to the `EntityData` class using reflection based on the property names. The `entityData` object will now have the properties set to the values found in the object in the map. If a property is not found in the object, the default value of the property in the `EntityData` class will be used. It will even map the nested enum to its corresponding value in C#. This will work for several levels of depth as it performs this kind of mapping recursively. <xref:DotTiled.IHasProperties.MapPropertiesTo``1> only supports mapping to classes that have a default, parameterless constructor.
|
||||||
|
|
||||||
|
### [Future] Exporting custom types
|
||||||
|
|
||||||
|
It might be possible to also make some kind of exporting functionality for <xref:DotTiled.ICustomTypeDefinition>. Given a collection of custom type definitions, DotTiled could generate a corresponding `propertytypes.json` file that you then can import into Tiled. This would make it so that you only have to define your custom property types once (in C#) and then import them into Tiled to use them in your maps.
|
23
src/DotTiled.Tests/Assert/AssertCustomTypes.cs
Normal file
|
@ -0,0 +1,23 @@
|
||||||
|
namespace DotTiled.Tests;
|
||||||
|
|
||||||
|
public static partial class DotTiledAssert
|
||||||
|
{
|
||||||
|
internal static void AssertCustomClassDefinitionEqual(CustomClassDefinition expected, CustomClassDefinition actual)
|
||||||
|
{
|
||||||
|
AssertEqual(expected.ID, actual.ID, nameof(CustomClassDefinition.ID));
|
||||||
|
AssertEqual(expected.Name, actual.Name, nameof(CustomClassDefinition.Name));
|
||||||
|
AssertEqual(expected.Color, actual.Color, nameof(CustomClassDefinition.Color));
|
||||||
|
AssertEqual(expected.DrawFill, actual.DrawFill, nameof(CustomClassDefinition.DrawFill));
|
||||||
|
AssertEqual(expected.UseAs, actual.UseAs, nameof(CustomClassDefinition.UseAs));
|
||||||
|
AssertProperties(expected.Members, actual.Members);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static void AssertCustomEnumDefinitionEqual(CustomEnumDefinition expected, CustomEnumDefinition actual)
|
||||||
|
{
|
||||||
|
AssertEqual(expected.ID, actual.ID, nameof(CustomEnumDefinition.ID));
|
||||||
|
AssertEqual(expected.Name, actual.Name, nameof(CustomEnumDefinition.Name));
|
||||||
|
AssertEqual(expected.StorageType, actual.StorageType, nameof(CustomEnumDefinition.StorageType));
|
||||||
|
AssertEqual(expected.ValueAsFlags, actual.ValueAsFlags, nameof(CustomEnumDefinition.ValueAsFlags));
|
||||||
|
AssertListOrdered(expected.Values, actual.Values, nameof(CustomEnumDefinition.Values));
|
||||||
|
}
|
||||||
|
}
|
|
@ -5,7 +5,7 @@ namespace DotTiled.Tests;
|
||||||
|
|
||||||
public static partial class DotTiledAssert
|
public static partial class DotTiledAssert
|
||||||
{
|
{
|
||||||
private static void AssertListOrdered<T>(IList<T> expected, IList<T> actual, string nameof, Action<T, T> assertEqual = null)
|
internal static void AssertListOrdered<T>(IList<T> expected, IList<T> actual, string nameof, Action<T, T> assertEqual = null)
|
||||||
{
|
{
|
||||||
if (expected is null)
|
if (expected is null)
|
||||||
{
|
{
|
||||||
|
@ -27,7 +27,7 @@ public static partial class DotTiledAssert
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void AssertOptionalsEqual<T>(
|
internal static void AssertOptionalsEqual<T>(
|
||||||
Optional<T> expected,
|
Optional<T> expected,
|
||||||
Optional<T> actual,
|
Optional<T> actual,
|
||||||
string nameof,
|
string nameof,
|
||||||
|
@ -49,7 +49,7 @@ public static partial class DotTiledAssert
|
||||||
Assert.False(actual.HasValue, $"Expected {nameof} to not have a value");
|
Assert.False(actual.HasValue, $"Expected {nameof} to not have a value");
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void AssertEqual<T>(Optional<T> expected, Optional<T> actual, string nameof)
|
internal static void AssertEqual<T>(Optional<T> expected, Optional<T> actual, string nameof)
|
||||||
{
|
{
|
||||||
if (expected is null)
|
if (expected is null)
|
||||||
{
|
{
|
||||||
|
@ -67,7 +67,7 @@ public static partial class DotTiledAssert
|
||||||
Assert.False(actual.HasValue, $"Expected {nameof} to not have a value");
|
Assert.False(actual.HasValue, $"Expected {nameof} to not have a value");
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void AssertEqual<T>(T expected, T actual, string nameof)
|
internal static void AssertEqual<T>(T expected, T actual, string nameof)
|
||||||
{
|
{
|
||||||
if (expected == null)
|
if (expected == null)
|
||||||
{
|
{
|
||||||
|
|
|
@ -26,7 +26,12 @@
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<!-- Test data -->
|
<!-- Test data -->
|
||||||
<EmbeddedResource Include="Serialization/TestData/**/*" />
|
<EmbeddedResource Include="TestData/**/*.tmx" />
|
||||||
|
<EmbeddedResource Include="TestData/**/*.tmj" />
|
||||||
|
<EmbeddedResource Include="TestData/**/*.tsx" />
|
||||||
|
<EmbeddedResource Include="TestData/**/*.tsj" />
|
||||||
|
<EmbeddedResource Include="TestData/**/*.tx" />
|
||||||
|
<EmbeddedResource Include="TestData/**/*.tj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|
|
@ -0,0 +1,180 @@
|
||||||
|
using DotTiled.Serialization;
|
||||||
|
using NSubstitute;
|
||||||
|
|
||||||
|
namespace DotTiled.Tests;
|
||||||
|
|
||||||
|
public class FromTypeUsedInLoaderTests
|
||||||
|
{
|
||||||
|
private sealed class TestClass
|
||||||
|
{
|
||||||
|
public string Name { get; set; } = "John Doe";
|
||||||
|
public int Age { get; set; } = 42;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void LoadMap_MapHasClassAndClassIsDefined_ReturnsCorrectMap()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var resourceReader = Substitute.For<IResourceReader>();
|
||||||
|
resourceReader.Read("map.tmx").Returns(
|
||||||
|
"""
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<map version="1.10" tiledversion="1.11.0" class="TestClass" orientation="orthogonal" renderorder="right-down" width="5" height="5" tilewidth="32" tileheight="32" infinite="0" nextlayerid="2" nextobjectid="1">
|
||||||
|
<layer id="1" name="Tile Layer 1" width="5" height="5">
|
||||||
|
<data encoding="csv">
|
||||||
|
0,0,0,0,0,
|
||||||
|
0,0,0,0,0,
|
||||||
|
0,0,0,0,0,
|
||||||
|
0,0,0,0,0,
|
||||||
|
0,0,0,0,0
|
||||||
|
</data>
|
||||||
|
</layer>
|
||||||
|
</map>
|
||||||
|
""");
|
||||||
|
var classDefinition = CustomClassDefinition.FromClass<TestClass>();
|
||||||
|
var loader = Loader.DefaultWith(
|
||||||
|
resourceReader: resourceReader,
|
||||||
|
customTypeDefinitions: [classDefinition]);
|
||||||
|
var expectedMap = new Map
|
||||||
|
{
|
||||||
|
Class = "TestClass",
|
||||||
|
Orientation = MapOrientation.Orthogonal,
|
||||||
|
Width = 5,
|
||||||
|
Height = 5,
|
||||||
|
TileWidth = 32,
|
||||||
|
TileHeight = 32,
|
||||||
|
Infinite = false,
|
||||||
|
ParallaxOriginX = 0,
|
||||||
|
ParallaxOriginY = 0,
|
||||||
|
RenderOrder = RenderOrder.RightDown,
|
||||||
|
CompressionLevel = -1,
|
||||||
|
BackgroundColor = new Color { R = 0, G = 0, B = 0, A = 0 },
|
||||||
|
Version = "1.10",
|
||||||
|
TiledVersion = "1.11.0",
|
||||||
|
NextLayerID = 2,
|
||||||
|
NextObjectID = 1,
|
||||||
|
Layers = [
|
||||||
|
new TileLayer
|
||||||
|
{
|
||||||
|
ID = 1,
|
||||||
|
Name = "Tile Layer 1",
|
||||||
|
Width = 5,
|
||||||
|
Height = 5,
|
||||||
|
Data = new Data
|
||||||
|
{
|
||||||
|
Encoding = DataEncoding.Csv,
|
||||||
|
GlobalTileIDs = new Optional<uint[]>([
|
||||||
|
0, 0, 0, 0, 0,
|
||||||
|
0, 0, 0, 0, 0,
|
||||||
|
0, 0, 0, 0, 0,
|
||||||
|
0, 0, 0, 0, 0,
|
||||||
|
0, 0, 0, 0, 0
|
||||||
|
]),
|
||||||
|
FlippingFlags = new Optional<FlippingFlags[]>([
|
||||||
|
FlippingFlags.None, FlippingFlags.None, FlippingFlags.None, FlippingFlags.None, FlippingFlags.None,
|
||||||
|
FlippingFlags.None, FlippingFlags.None, FlippingFlags.None, FlippingFlags.None, FlippingFlags.None,
|
||||||
|
FlippingFlags.None, FlippingFlags.None, FlippingFlags.None, FlippingFlags.None, FlippingFlags.None,
|
||||||
|
FlippingFlags.None, FlippingFlags.None, FlippingFlags.None, FlippingFlags.None, FlippingFlags.None,
|
||||||
|
FlippingFlags.None, FlippingFlags.None, FlippingFlags.None, FlippingFlags.None, FlippingFlags.None
|
||||||
|
])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
Properties = [
|
||||||
|
new StringProperty { Name = "Name", Value = "John Doe" },
|
||||||
|
new IntProperty { Name = "Age", Value = 42 }
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = loader.LoadMap("map.tmx");
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
DotTiledAssert.AssertMap(expectedMap, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void LoadMap_MapHasClassAndClassIsDefinedAndFieldIsOverridenFromDefault_ReturnsCorrectMap()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var resourceReader = Substitute.For<IResourceReader>();
|
||||||
|
resourceReader.Read("map.tmx").Returns(
|
||||||
|
"""
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<map version="1.10" tiledversion="1.11.0" class="TestClass" orientation="orthogonal" renderorder="right-down" width="5" height="5" tilewidth="32" tileheight="32" infinite="0" nextlayerid="2" nextobjectid="1">
|
||||||
|
<properties>
|
||||||
|
<property name="Name" value="John Doe"/>
|
||||||
|
</properties>
|
||||||
|
<layer id="1" name="Tile Layer 1" width="5" height="5">
|
||||||
|
<data encoding="csv">
|
||||||
|
0,0,0,0,0,
|
||||||
|
0,0,0,0,0,
|
||||||
|
0,0,0,0,0,
|
||||||
|
0,0,0,0,0,
|
||||||
|
0,0,0,0,0
|
||||||
|
</data>
|
||||||
|
</layer>
|
||||||
|
</map>
|
||||||
|
""");
|
||||||
|
var classDefinition = CustomClassDefinition.FromClass<TestClass>();
|
||||||
|
var loader = Loader.DefaultWith(
|
||||||
|
resourceReader: resourceReader,
|
||||||
|
customTypeDefinitions: [classDefinition]);
|
||||||
|
var expectedMap = new Map
|
||||||
|
{
|
||||||
|
Class = "TestClass",
|
||||||
|
Orientation = MapOrientation.Orthogonal,
|
||||||
|
Width = 5,
|
||||||
|
Height = 5,
|
||||||
|
TileWidth = 32,
|
||||||
|
TileHeight = 32,
|
||||||
|
Infinite = false,
|
||||||
|
ParallaxOriginX = 0,
|
||||||
|
ParallaxOriginY = 0,
|
||||||
|
RenderOrder = RenderOrder.RightDown,
|
||||||
|
CompressionLevel = -1,
|
||||||
|
BackgroundColor = new Color { R = 0, G = 0, B = 0, A = 0 },
|
||||||
|
Version = "1.10",
|
||||||
|
TiledVersion = "1.11.0",
|
||||||
|
NextLayerID = 2,
|
||||||
|
NextObjectID = 1,
|
||||||
|
Layers = [
|
||||||
|
new TileLayer
|
||||||
|
{
|
||||||
|
ID = 1,
|
||||||
|
Name = "Tile Layer 1",
|
||||||
|
Width = 5,
|
||||||
|
Height = 5,
|
||||||
|
Data = new Data
|
||||||
|
{
|
||||||
|
Encoding = DataEncoding.Csv,
|
||||||
|
GlobalTileIDs = new Optional<uint[]>([
|
||||||
|
0, 0, 0, 0, 0,
|
||||||
|
0, 0, 0, 0, 0,
|
||||||
|
0, 0, 0, 0, 0,
|
||||||
|
0, 0, 0, 0, 0,
|
||||||
|
0, 0, 0, 0, 0
|
||||||
|
]),
|
||||||
|
FlippingFlags = new Optional<FlippingFlags[]>([
|
||||||
|
FlippingFlags.None, FlippingFlags.None, FlippingFlags.None, FlippingFlags.None, FlippingFlags.None,
|
||||||
|
FlippingFlags.None, FlippingFlags.None, FlippingFlags.None, FlippingFlags.None, FlippingFlags.None,
|
||||||
|
FlippingFlags.None, FlippingFlags.None, FlippingFlags.None, FlippingFlags.None, FlippingFlags.None,
|
||||||
|
FlippingFlags.None, FlippingFlags.None, FlippingFlags.None, FlippingFlags.None, FlippingFlags.None,
|
||||||
|
FlippingFlags.None, FlippingFlags.None, FlippingFlags.None, FlippingFlags.None, FlippingFlags.None
|
||||||
|
])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
Properties = [
|
||||||
|
new StringProperty { Name = "Name", Value = "John Doe" },
|
||||||
|
new IntProperty { Name = "Age", Value = 42 }
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = loader.LoadMap("map.tmx");
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
DotTiledAssert.AssertMap(expectedMap, result);
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,47 +0,0 @@
|
||||||
using System.Xml;
|
|
||||||
|
|
||||||
namespace DotTiled.Tests;
|
|
||||||
|
|
||||||
public static partial class TestData
|
|
||||||
{
|
|
||||||
public static XmlReader GetXmlReaderFor(string testDataFile)
|
|
||||||
{
|
|
||||||
var fullyQualifiedTestDataFile = $"DotTiled.Tests.{ConvertPathToAssemblyResourcePath(testDataFile)}";
|
|
||||||
using var stream = typeof(TestData).Assembly.GetManifestResourceStream(fullyQualifiedTestDataFile)
|
|
||||||
?? throw new ArgumentException($"Test data file '{fullyQualifiedTestDataFile}' not found");
|
|
||||||
|
|
||||||
using var stringReader = new StreamReader(stream);
|
|
||||||
var xml = stringReader.ReadToEnd();
|
|
||||||
var xmlStringReader = new StringReader(xml);
|
|
||||||
return XmlReader.Create(xmlStringReader);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static string GetRawStringFor(string testDataFile)
|
|
||||||
{
|
|
||||||
var fullyQualifiedTestDataFile = $"DotTiled.Tests.{ConvertPathToAssemblyResourcePath(testDataFile)}";
|
|
||||||
using var stream = typeof(TestData).Assembly.GetManifestResourceStream(fullyQualifiedTestDataFile)
|
|
||||||
?? throw new ArgumentException($"Test data file '{fullyQualifiedTestDataFile}' not found");
|
|
||||||
|
|
||||||
using var stringReader = new StreamReader(stream);
|
|
||||||
return stringReader.ReadToEnd();
|
|
||||||
}
|
|
||||||
|
|
||||||
private static string ConvertPathToAssemblyResourcePath(string path) =>
|
|
||||||
path.Replace("/", ".").Replace("\\", ".").Replace(" ", "_");
|
|
||||||
|
|
||||||
public static IEnumerable<object[]> MapTests =>
|
|
||||||
[
|
|
||||||
["Serialization/TestData/Map/default_map/default-map", (string f) => DefaultMap(), Array.Empty<ICustomTypeDefinition>()],
|
|
||||||
["Serialization/TestData/Map/map_with_common_props/map-with-common-props", (string f) => MapWithCommonProps(), Array.Empty<ICustomTypeDefinition>()],
|
|
||||||
["Serialization/TestData/Map/map_with_custom_type_props/map-with-custom-type-props", (string f) => MapWithCustomTypeProps(), MapWithCustomTypePropsCustomTypeDefinitions()],
|
|
||||||
["Serialization/TestData/Map/map_with_embedded_tileset/map-with-embedded-tileset", (string f) => MapWithEmbeddedTileset(), Array.Empty<ICustomTypeDefinition>()],
|
|
||||||
["Serialization/TestData/Map/map_with_external_tileset/map-with-external-tileset", (string f) => MapWithExternalTileset(f), Array.Empty<ICustomTypeDefinition>()],
|
|
||||||
["Serialization/TestData/Map/map_with_flippingflags/map-with-flippingflags", (string f) => MapWithFlippingFlags(f), Array.Empty<ICustomTypeDefinition>()],
|
|
||||||
["Serialization/TestData/Map/map_external_tileset_multi/map-external-tileset-multi", (string f) => MapExternalTilesetMulti(f), Array.Empty<ICustomTypeDefinition>()],
|
|
||||||
["Serialization/TestData/Map/map_external_tileset_wangset/map-external-tileset-wangset", (string f) => MapExternalTilesetWangset(f), Array.Empty<ICustomTypeDefinition>()],
|
|
||||||
["Serialization/TestData/Map/map_with_many_layers/map-with-many-layers", (string f) => MapWithManyLayers(f), Array.Empty<ICustomTypeDefinition>()],
|
|
||||||
["Serialization/TestData/Map/map_with_deep_props/map-with-deep-props", (string f) => MapWithDeepProps(), MapWithDeepPropsCustomTypeDefinitions()],
|
|
||||||
["Serialization/TestData/Map/map_with_class/map-with-class", (string f) => MapWithClass(), MapWithClassCustomTypeDefinitions()],
|
|
||||||
["Serialization/TestData/Map/map_with_class_and_props/map-with-class-and-props", (string f) => MapWithClassAndProps(), MapWithClassAndPropsCustomTypeDefinitions()],
|
|
||||||
];
|
|
||||||
}
|
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 12 KiB |
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 12 KiB |
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 12 KiB |
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 12 KiB |
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 12 KiB |
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 12 KiB |
|
@ -1,208 +1,5 @@
|
||||||
namespace DotTiled.Tests;
|
namespace DotTiled.Tests;
|
||||||
|
|
||||||
// public class OptionalTests
|
|
||||||
// {
|
|
||||||
// [Fact]
|
|
||||||
// public void HasValue_WhenValueIsSet_ReturnsTrue()
|
|
||||||
// {
|
|
||||||
// // Arrange
|
|
||||||
// var optional = new Optional<int>(42);
|
|
||||||
|
|
||||||
// // Act & Assert
|
|
||||||
// Assert.True(optional.HasValue);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// [Fact]
|
|
||||||
// public void HasValue_WhenValueIsNotSet_ReturnsFalse()
|
|
||||||
// {
|
|
||||||
// // Arrange
|
|
||||||
// var optional = new Optional<int>();
|
|
||||||
|
|
||||||
// // Act & Assert
|
|
||||||
// Assert.False(optional.HasValue);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// [Fact]
|
|
||||||
// public void Value_WhenValueIsSet_ReturnsValue()
|
|
||||||
// {
|
|
||||||
// // Arrange
|
|
||||||
// var optional = new Optional<int>(42);
|
|
||||||
|
|
||||||
// // Act
|
|
||||||
// var value = optional.Value;
|
|
||||||
|
|
||||||
// // Assert
|
|
||||||
// Assert.Equal(42, value);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// [Fact]
|
|
||||||
// public void Value_WhenValueIsNotSet_ThrowsInvalidOperationException()
|
|
||||||
// {
|
|
||||||
// // Arrange
|
|
||||||
// var optional = new Optional<int>();
|
|
||||||
|
|
||||||
// // Act & Assert
|
|
||||||
// _ = Assert.Throws<InvalidOperationException>(() => optional.Value);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// [Fact]
|
|
||||||
// public void ImplicitConversionFromValue_CreatesOptionalWithValue()
|
|
||||||
// {
|
|
||||||
// // Arrange
|
|
||||||
// Optional<int> optional = 42;
|
|
||||||
|
|
||||||
// // Act & Assert
|
|
||||||
// Assert.True(optional.HasValue);
|
|
||||||
// Assert.Equal(42, optional.Value);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// [Fact]
|
|
||||||
// public void ImplicitConversionToValue_ReturnsValue()
|
|
||||||
// {
|
|
||||||
// // Arrange
|
|
||||||
// var optional = new Optional<int>(42);
|
|
||||||
|
|
||||||
// // Act
|
|
||||||
// int value = optional;
|
|
||||||
|
|
||||||
// // Assert
|
|
||||||
// Assert.Equal(42, value);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// [Fact]
|
|
||||||
// public void ToString_WhenValueIsSet_ReturnsValueToString()
|
|
||||||
// {
|
|
||||||
// // Arrange
|
|
||||||
// var optional = new Optional<int>(42);
|
|
||||||
|
|
||||||
// // Act
|
|
||||||
// var result = optional.ToString();
|
|
||||||
|
|
||||||
// // Assert
|
|
||||||
// Assert.Equal("42", result);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// [Fact]
|
|
||||||
// public void ToString_WhenValueIsNotSet_ReturnsEmpty()
|
|
||||||
// {
|
|
||||||
// // Arrange
|
|
||||||
// var optional = new Optional<int>();
|
|
||||||
|
|
||||||
// // Act
|
|
||||||
// var result = optional.ToString();
|
|
||||||
|
|
||||||
// // Assert
|
|
||||||
// Assert.Equal("Empty", result);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// [Fact]
|
|
||||||
// public void Equals_WithObject_ReturnsTrueWhenValueIsEqual()
|
|
||||||
// {
|
|
||||||
// // Arrange
|
|
||||||
// var optional = new Optional<int>(42);
|
|
||||||
|
|
||||||
// // Act
|
|
||||||
// var result = optional.Equals(42);
|
|
||||||
|
|
||||||
// // Assert
|
|
||||||
// Assert.True(result);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// [Fact]
|
|
||||||
// public void Equals_WithObject_ReturnsFalseWhenValueIsNotEqual()
|
|
||||||
// {
|
|
||||||
// // Arrange
|
|
||||||
// var optional = new Optional<int>(42);
|
|
||||||
|
|
||||||
// // Act
|
|
||||||
// var result = optional.Equals(43);
|
|
||||||
|
|
||||||
// // Assert
|
|
||||||
// Assert.False(result);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// [Fact]
|
|
||||||
// public void Equals_WithObject_ReturnsFalseWhenValueIsNotSet()
|
|
||||||
// {
|
|
||||||
// // Arrange
|
|
||||||
// var optional = new Optional<int>();
|
|
||||||
|
|
||||||
// // Act
|
|
||||||
// var result = optional.Equals(42);
|
|
||||||
|
|
||||||
// // Assert
|
|
||||||
// Assert.False(result);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// [Fact]
|
|
||||||
// public void Equals_WithOptional_ReturnsTrueWhenValueIsEqual()
|
|
||||||
// {
|
|
||||||
// // Arrange
|
|
||||||
// var optional1 = new Optional<int>(42);
|
|
||||||
// var optional2 = new Optional<int>(42);
|
|
||||||
|
|
||||||
// // Act
|
|
||||||
// var result = optional1.Equals(optional2);
|
|
||||||
|
|
||||||
// // Assert
|
|
||||||
// Assert.True(result);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// [Fact]
|
|
||||||
// public void Equals_WithOptional_ReturnsFalseWhenValueIsNotEqual()
|
|
||||||
// {
|
|
||||||
// // Arrange
|
|
||||||
// var optional1 = new Optional<int>(42);
|
|
||||||
// var optional2 = new Optional<int>(43);
|
|
||||||
|
|
||||||
// // Act
|
|
||||||
// var result = optional1.Equals(optional2);
|
|
||||||
|
|
||||||
// // Assert
|
|
||||||
// Assert.False(result);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// [Fact]
|
|
||||||
// public void Equals_WithOptional_ReturnsFalseWhenValueIsNotSet()
|
|
||||||
// {
|
|
||||||
// // Arrange
|
|
||||||
// var optional1 = new Optional<int>();
|
|
||||||
// var optional2 = new Optional<int>(42);
|
|
||||||
|
|
||||||
// // Act
|
|
||||||
// var result = optional1.Equals(optional2);
|
|
||||||
|
|
||||||
// // Assert
|
|
||||||
// Assert.False(result);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// [Fact]
|
|
||||||
// public void GetHashCode_WhenValueIsSet_ReturnsValueHashCode()
|
|
||||||
// {
|
|
||||||
// // Arrange
|
|
||||||
// var optional = new Optional<int>(42);
|
|
||||||
|
|
||||||
// // Act
|
|
||||||
// var result = optional.GetHashCode();
|
|
||||||
|
|
||||||
// // Assert
|
|
||||||
// Assert.Equal(42.GetHashCode(), result);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// [Fact]
|
|
||||||
// public void GetHashCode_WhenValueIsNotSet_ReturnsZero()
|
|
||||||
// {
|
|
||||||
// // Arrange
|
|
||||||
// var optional = new Optional<int>();
|
|
||||||
|
|
||||||
// // Act
|
|
||||||
// var result = optional.GetHashCode();
|
|
||||||
|
|
||||||
// // Assert
|
|
||||||
// Assert.Equal(0, result);
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
public class OptionalTests
|
public class OptionalTests
|
||||||
{
|
{
|
||||||
// Constructor Tests
|
// Constructor Tests
|
|
@ -0,0 +1,122 @@
|
||||||
|
namespace DotTiled.Tests;
|
||||||
|
|
||||||
|
public class CustomClassDefinitionTests
|
||||||
|
{
|
||||||
|
private sealed class TestClass1
|
||||||
|
{
|
||||||
|
public string Name { get; set; } = "John Doe";
|
||||||
|
public int Age { get; set; } = 42;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static CustomClassDefinition ExpectedTestClass1Definition => new CustomClassDefinition
|
||||||
|
{
|
||||||
|
Name = "TestClass1",
|
||||||
|
UseAs = CustomClassUseAs.All,
|
||||||
|
Members = new List<IProperty>
|
||||||
|
{
|
||||||
|
new StringProperty { Name = "Name", Value = "John Doe" },
|
||||||
|
new IntProperty { Name = "Age", Value = 42 }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
private sealed class TestClass2WithNestedClass
|
||||||
|
{
|
||||||
|
public string Name { get; set; } = "John Doe";
|
||||||
|
public int Age { get; set; } = 42;
|
||||||
|
public TestClass1 Nested { get; set; } = new TestClass1();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static CustomClassDefinition ExpectedTestClass2WithNestedClassDefinition => new CustomClassDefinition
|
||||||
|
{
|
||||||
|
Name = "TestClass2WithNestedClass",
|
||||||
|
UseAs = CustomClassUseAs.All,
|
||||||
|
Members = [
|
||||||
|
new StringProperty { Name = "Name", Value = "John Doe" },
|
||||||
|
new IntProperty { Name = "Age", Value = 42 },
|
||||||
|
new ClassProperty
|
||||||
|
{
|
||||||
|
Name = "Nested",
|
||||||
|
PropertyType = "TestClass1",
|
||||||
|
Value = []
|
||||||
|
}
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
private sealed class TestClass3WithOverridenNestedClass
|
||||||
|
{
|
||||||
|
public string Name { get; set; } = "John Doe";
|
||||||
|
public int Age { get; set; } = 42;
|
||||||
|
public TestClass1 Nested { get; set; } = new TestClass1
|
||||||
|
{
|
||||||
|
Name = "Jane Doe"
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static CustomClassDefinition ExpectedTestClass3WithOverridenNestedClassDefinition => new CustomClassDefinition
|
||||||
|
{
|
||||||
|
Name = "TestClass3WithOverridenNestedClass",
|
||||||
|
UseAs = CustomClassUseAs.All,
|
||||||
|
Members = [
|
||||||
|
new StringProperty { Name = "Name", Value = "John Doe" },
|
||||||
|
new IntProperty { Name = "Age", Value = 42 },
|
||||||
|
new ClassProperty
|
||||||
|
{
|
||||||
|
Name = "Nested",
|
||||||
|
PropertyType = "TestClass1",
|
||||||
|
Value = [
|
||||||
|
new StringProperty { Name = "Name", Value = "Jane Doe" },
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
private static IEnumerable<(Type, CustomClassDefinition)> GetCustomClassDefinitionTestData()
|
||||||
|
{
|
||||||
|
yield return (typeof(TestClass1), ExpectedTestClass1Definition);
|
||||||
|
yield return (typeof(TestClass2WithNestedClass), ExpectedTestClass2WithNestedClassDefinition);
|
||||||
|
yield return (typeof(TestClass3WithOverridenNestedClass), ExpectedTestClass3WithOverridenNestedClassDefinition);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IEnumerable<object[]> CustomClassDefinitionTestData =>
|
||||||
|
GetCustomClassDefinitionTestData().Select(data => new object[] { data.Item1, data.Item2 });
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(CustomClassDefinitionTestData))]
|
||||||
|
public void FromClass_Type_WhenTypeIsCustomClass_ReturnsCustomClassDefinition(Type type, CustomClassDefinition expected)
|
||||||
|
{
|
||||||
|
// Arrange & Act
|
||||||
|
var result = CustomClassDefinition.FromClass(type);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
DotTiledAssert.AssertCustomClassDefinitionEqual(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void FromClass_Type_WhenTypeIsNull_ThrowsArgumentNullException()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
Type type = null;
|
||||||
|
|
||||||
|
// Act & Assert
|
||||||
|
Assert.Throws<ArgumentNullException>(() => CustomClassDefinition.FromClass(type));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void FromClass_Type_WhenTypeIsString_ThrowsArgumentException()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
Type type = typeof(string);
|
||||||
|
|
||||||
|
// Act & Assert
|
||||||
|
Assert.Throws<ArgumentException>(() => CustomClassDefinition.FromClass(type));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void FromClass_Type_WhenTypeIsNotClass_ThrowsArgumentException()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
Type type = typeof(int);
|
||||||
|
|
||||||
|
// Act & Assert
|
||||||
|
Assert.Throws<ArgumentException>(() => CustomClassDefinition.FromClass(type));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,101 @@
|
||||||
|
namespace DotTiled.Tests;
|
||||||
|
|
||||||
|
public class CustomEnumDefinitionTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void FromEnum_Type_WhenTypeIsNotEnum_ThrowsArgumentException()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var type = typeof(string);
|
||||||
|
|
||||||
|
// Act & Assert
|
||||||
|
Assert.Throws<ArgumentException>(() => CustomEnumDefinition.FromEnum(type));
|
||||||
|
}
|
||||||
|
|
||||||
|
private enum TestEnum1 { Value1, Value2, Value3 }
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void FromEnum_Type_WhenTypeIsEnum_ReturnsCustomEnumDefinition()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var type = typeof(TestEnum1);
|
||||||
|
var expected = new CustomEnumDefinition
|
||||||
|
{
|
||||||
|
ID = 0,
|
||||||
|
Name = "TestEnum1",
|
||||||
|
StorageType = CustomEnumStorageType.Int,
|
||||||
|
Values = ["Value1", "Value2", "Value3"],
|
||||||
|
ValueAsFlags = false
|
||||||
|
};
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = CustomEnumDefinition.FromEnum(type);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
DotTiledAssert.AssertCustomEnumDefinitionEqual(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Flags]
|
||||||
|
private enum TestEnum2 { Value1, Value2, Value3 }
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void FromEnum_Type_WhenEnumIsFlags_ReturnsCustomEnumDefinition()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var type = typeof(TestEnum2);
|
||||||
|
var expected = new CustomEnumDefinition
|
||||||
|
{
|
||||||
|
ID = 0,
|
||||||
|
Name = "TestEnum2",
|
||||||
|
StorageType = CustomEnumStorageType.Int,
|
||||||
|
Values = ["Value1", "Value2", "Value3"],
|
||||||
|
ValueAsFlags = true
|
||||||
|
};
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = CustomEnumDefinition.FromEnum(type);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
DotTiledAssert.AssertCustomEnumDefinitionEqual(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void FromEnum_T_WhenTypeIsEnum_ReturnsCustomEnumDefinition()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var expected = new CustomEnumDefinition
|
||||||
|
{
|
||||||
|
ID = 0,
|
||||||
|
Name = "TestEnum1",
|
||||||
|
StorageType = CustomEnumStorageType.Int,
|
||||||
|
Values = ["Value1", "Value2", "Value3"],
|
||||||
|
ValueAsFlags = false
|
||||||
|
};
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = CustomEnumDefinition.FromEnum<TestEnum1>();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
DotTiledAssert.AssertCustomEnumDefinitionEqual(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void FromEnum_T_WhenEnumIsFlags_ReturnsCustomEnumDefinition()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var expected = new CustomEnumDefinition
|
||||||
|
{
|
||||||
|
ID = 0,
|
||||||
|
Name = "TestEnum2",
|
||||||
|
StorageType = CustomEnumStorageType.Int,
|
||||||
|
Values = ["Value1", "Value2", "Value3"],
|
||||||
|
ValueAsFlags = true
|
||||||
|
};
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = CustomEnumDefinition.FromEnum<TestEnum2>();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
DotTiledAssert.AssertCustomEnumDefinitionEqual(expected, result);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,300 @@
|
||||||
|
using System.Globalization;
|
||||||
|
|
||||||
|
namespace DotTiled.Tests;
|
||||||
|
|
||||||
|
public class HasPropertiesBaseTests
|
||||||
|
{
|
||||||
|
private sealed class TestHasProperties(IList<IProperty> props) : HasPropertiesBase
|
||||||
|
{
|
||||||
|
public override IList<IProperty> GetProperties() => props;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TryGetProperty_PropertyNotFound_ReturnsFalseAndOutIsNull()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var hasProperties = new TestHasProperties([]);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = hasProperties.TryGetProperty<BoolProperty>("Test", out var property);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.False(result);
|
||||||
|
Assert.Null(property);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TryGetProperty_PropertyFound_ReturnsTrueAndOutIsProperty()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
List<IProperty> props = [new BoolProperty { Name = "Test", Value = true }];
|
||||||
|
var hasProperties = new TestHasProperties(props);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = hasProperties.TryGetProperty<BoolProperty>("Test", out var property);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.True(result);
|
||||||
|
Assert.NotNull(property);
|
||||||
|
Assert.Equal("Test", property.Name);
|
||||||
|
Assert.True(property.Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetProperty_PropertyNotFound_ThrowsKeyNotFoundException()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var hasProperties = new TestHasProperties([]);
|
||||||
|
|
||||||
|
// Act & Assert
|
||||||
|
_ = Assert.Throws<KeyNotFoundException>(() => hasProperties.GetProperty<BoolProperty>("Test"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetProperty_PropertyFound_ReturnsProperty()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
List<IProperty> props = [new BoolProperty { Name = "Test", Value = true }];
|
||||||
|
var hasProperties = new TestHasProperties(props);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var property = hasProperties.GetProperty<BoolProperty>("Test");
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.NotNull(property);
|
||||||
|
Assert.Equal("Test", property.Name);
|
||||||
|
Assert.True(property.Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetProperty_PropertyIsWrongType_ThrowsInvalidCastException()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
List<IProperty> props = [new BoolProperty { Name = "Test", Value = true }];
|
||||||
|
var hasProperties = new TestHasProperties(props);
|
||||||
|
|
||||||
|
// Act & Assert
|
||||||
|
_ = Assert.Throws<InvalidCastException>(() => hasProperties.GetProperty<IntProperty>("Test"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class MapTo
|
||||||
|
{
|
||||||
|
public bool MapToBool { get; set; } = false;
|
||||||
|
public Color MapToColor { get; set; } = Color.Parse("#00000000", CultureInfo.InvariantCulture);
|
||||||
|
public float MapToFloat { get; set; } = 0.0f;
|
||||||
|
public string MapToFile { get; set; } = "";
|
||||||
|
public int MapToInt { get; set; } = 0;
|
||||||
|
public int MapToObject { get; set; } = 0;
|
||||||
|
public string MapToString { get; set; } = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MapPropertiesTo_NestedPropertyNotFound_ThrowsKeyNotFoundException()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
List<IProperty> props = [
|
||||||
|
new ClassProperty {
|
||||||
|
Name = "ClassInObject",
|
||||||
|
PropertyType = "MapTo",
|
||||||
|
Value = [
|
||||||
|
new StringProperty { Name = "PropertyThatDoesNotExistInMapTo", Value = "Test" }
|
||||||
|
],
|
||||||
|
}
|
||||||
|
];
|
||||||
|
var hasProperties = new TestHasProperties(props);
|
||||||
|
|
||||||
|
// Act & Assert
|
||||||
|
_ = Assert.Throws<KeyNotFoundException>(() => hasProperties.GetProperty<ClassProperty>("ClassInObject").MapPropertiesTo<MapTo>());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MapPropertiesTo_NestedPropertyIsNotClassProperty_ThrowsInvalidCastException()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
List<IProperty> props = [
|
||||||
|
new StringProperty { Name = "ClassInObject", Value = "Test" }
|
||||||
|
];
|
||||||
|
var hasProperties = new TestHasProperties(props);
|
||||||
|
|
||||||
|
// Act & Assert
|
||||||
|
_ = Assert.Throws<InvalidCastException>(() => hasProperties.GetProperty<ClassProperty>("ClassInObject").MapPropertiesTo<MapTo>());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MapPropertiesTo_NestedAllBasicValidProperties_ReturnsMappedProperty()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
List<IProperty> props = [
|
||||||
|
new ClassProperty {
|
||||||
|
Name = "ClassInObject",
|
||||||
|
PropertyType = "MapTo",
|
||||||
|
Value = [
|
||||||
|
new BoolProperty { Name = "MapToBool", Value = true },
|
||||||
|
new ColorProperty { Name = "MapToColor", Value = Color.Parse("#FF0000FF", CultureInfo.InvariantCulture) },
|
||||||
|
new FloatProperty { Name = "MapToFloat", Value = 1.0f },
|
||||||
|
new StringProperty { Name = "MapToFile", Value = "Test" },
|
||||||
|
new IntProperty { Name = "MapToInt", Value = 1 },
|
||||||
|
new IntProperty { Name = "MapToObject", Value = 1 },
|
||||||
|
new StringProperty { Name = "MapToString", Value = "Test" },
|
||||||
|
],
|
||||||
|
}
|
||||||
|
];
|
||||||
|
var hasProperties = new TestHasProperties(props);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var mappedProperty = hasProperties.GetProperty<ClassProperty>("ClassInObject").MapPropertiesTo<MapTo>();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.True(mappedProperty.MapToBool);
|
||||||
|
Assert.Equal(Color.Parse("#FF0000FF", CultureInfo.InvariantCulture), mappedProperty.MapToColor);
|
||||||
|
Assert.Equal(1.0f, mappedProperty.MapToFloat);
|
||||||
|
Assert.Equal("Test", mappedProperty.MapToFile);
|
||||||
|
Assert.Equal(1, mappedProperty.MapToInt);
|
||||||
|
Assert.Equal(1, mappedProperty.MapToObject);
|
||||||
|
Assert.Equal("Test", mappedProperty.MapToString);
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class NestedMapTo
|
||||||
|
{
|
||||||
|
public string NestedMapToString { get; set; } = "";
|
||||||
|
public MapTo MapToInNested { get; set; } = new MapTo();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MapPropertiesTo_NestedNestedMapTo_ReturnsMappedProperty()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
List<IProperty> props = [
|
||||||
|
new ClassProperty {
|
||||||
|
Name = "ClassInObject",
|
||||||
|
PropertyType = "NestedMapTo",
|
||||||
|
Value = [
|
||||||
|
new StringProperty { Name = "NestedMapToString", Value = "Test" },
|
||||||
|
new ClassProperty {
|
||||||
|
Name = "MapToInNested",
|
||||||
|
PropertyType = "MapTo",
|
||||||
|
Value = [
|
||||||
|
new BoolProperty { Name = "MapToBool", Value = true },
|
||||||
|
new ColorProperty { Name = "MapToColor", Value = Color.Parse("#FF0000FF", CultureInfo.InvariantCulture) },
|
||||||
|
new FloatProperty { Name = "MapToFloat", Value = 1.0f },
|
||||||
|
new StringProperty { Name = "MapToFile", Value = "Test" },
|
||||||
|
new IntProperty { Name = "MapToInt", Value = 1 },
|
||||||
|
new IntProperty { Name = "MapToObject", Value = 1 },
|
||||||
|
new StringProperty { Name = "MapToString", Value = "Test" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
];
|
||||||
|
var hasProperties = new TestHasProperties(props);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var mappedProperty = hasProperties.GetProperty<ClassProperty>("ClassInObject").MapPropertiesTo<NestedMapTo>();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.Equal("Test", mappedProperty.NestedMapToString);
|
||||||
|
Assert.True(mappedProperty.MapToInNested.MapToBool);
|
||||||
|
Assert.Equal(Color.Parse("#FF0000FF", CultureInfo.InvariantCulture), mappedProperty.MapToInNested.MapToColor);
|
||||||
|
Assert.Equal(1.0f, mappedProperty.MapToInNested.MapToFloat);
|
||||||
|
Assert.Equal("Test", mappedProperty.MapToInNested.MapToFile);
|
||||||
|
Assert.Equal(1, mappedProperty.MapToInNested.MapToInt);
|
||||||
|
Assert.Equal(1, mappedProperty.MapToInNested.MapToObject);
|
||||||
|
Assert.Equal("Test", mappedProperty.MapToInNested.MapToString);
|
||||||
|
}
|
||||||
|
|
||||||
|
private enum TestEnum
|
||||||
|
{
|
||||||
|
TestValue1,
|
||||||
|
TestValue2,
|
||||||
|
TestValue3
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class EnumMapTo
|
||||||
|
{
|
||||||
|
public TestEnum EnumMapToEnum { get; set; } = TestEnum.TestValue1;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MapPropertiesTo_NestedEnumProperty_ReturnsMappedProperty()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
List<IProperty> props = [
|
||||||
|
new ClassProperty {
|
||||||
|
Name = "ClassInObject",
|
||||||
|
PropertyType = "EnumMapTo",
|
||||||
|
Value = [
|
||||||
|
new EnumProperty { Name = "EnumMapToEnum", PropertyType = "TestEnum", Value = new HashSet<string> { "TestValue1" } },
|
||||||
|
],
|
||||||
|
}
|
||||||
|
];
|
||||||
|
var hasProperties = new TestHasProperties(props);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var mappedProperty = hasProperties.GetProperty<ClassProperty>("ClassInObject").MapPropertiesTo<EnumMapTo>();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.Equal(TestEnum.TestValue1, mappedProperty.EnumMapToEnum);
|
||||||
|
}
|
||||||
|
|
||||||
|
private enum TestEnumWithFlags
|
||||||
|
{
|
||||||
|
TestValue1 = 1,
|
||||||
|
TestValue2 = 2,
|
||||||
|
TestValue3 = 4
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class EnumWithFlagsMapTo
|
||||||
|
{
|
||||||
|
public TestEnumWithFlags EnumWithFlagsMapToEnum { get; set; } = TestEnumWithFlags.TestValue1;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MapPropertiesTo_NestedEnumWithFlagsProperty_ReturnsMappedProperty()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
List<IProperty> props = [
|
||||||
|
new ClassProperty {
|
||||||
|
Name = "ClassInObject",
|
||||||
|
PropertyType = "EnumWithFlagsMapTo",
|
||||||
|
Value = [
|
||||||
|
new EnumProperty { Name = "EnumWithFlagsMapToEnum", PropertyType = "TestEnumWithFlags", Value = new HashSet<string> { "TestValue1", "TestValue2" } },
|
||||||
|
],
|
||||||
|
}
|
||||||
|
];
|
||||||
|
var hasProperties = new TestHasProperties(props);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var mappedProperty = hasProperties.GetProperty<ClassProperty>("ClassInObject").MapPropertiesTo<EnumWithFlagsMapTo>();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.Equal(TestEnumWithFlags.TestValue1 | TestEnumWithFlags.TestValue2, mappedProperty.EnumWithFlagsMapToEnum);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MapPropertiesTo_WithProperties_ReturnsMappedProperty()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
List<IProperty> props = [
|
||||||
|
new BoolProperty { Name = "MapToBool", Value = true },
|
||||||
|
new ColorProperty { Name = "MapToColor", Value = Color.Parse("#FF0000FF", CultureInfo.InvariantCulture) },
|
||||||
|
new FloatProperty { Name = "MapToFloat", Value = 1.0f },
|
||||||
|
new StringProperty { Name = "MapToFile", Value = "Test" },
|
||||||
|
new IntProperty { Name = "MapToInt", Value = 1 },
|
||||||
|
new IntProperty { Name = "MapToObject", Value = 1 },
|
||||||
|
new StringProperty { Name = "MapToString", Value = "Test" },
|
||||||
|
];
|
||||||
|
var hasProperties = new TestHasProperties(props);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var mappedProperty = hasProperties.MapPropertiesTo<MapTo>();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.True(mappedProperty.MapToBool);
|
||||||
|
Assert.Equal(Color.Parse("#FF0000FF", CultureInfo.InvariantCulture), mappedProperty.MapToColor);
|
||||||
|
Assert.Equal(1.0f, mappedProperty.MapToFloat);
|
||||||
|
Assert.Equal("Test", mappedProperty.MapToFile);
|
||||||
|
Assert.Equal(1, mappedProperty.MapToInt);
|
||||||
|
Assert.Equal(1, mappedProperty.MapToObject);
|
||||||
|
Assert.Equal("Test", mappedProperty.MapToString);
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,5 +1,4 @@
|
||||||
using System.Numerics;
|
using System.Numerics;
|
||||||
using System.Runtime.CompilerServices;
|
|
||||||
using DotTiled.Serialization;
|
using DotTiled.Serialization;
|
||||||
using NSubstitute;
|
using NSubstitute;
|
||||||
|
|
||||||
|
@ -246,14 +245,71 @@ public class LoaderTests
|
||||||
resourceReader.DidNotReceive().Read("template.tx");
|
resourceReader.DidNotReceive().Read("template.tx");
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string WhereAmI([CallerFilePath] string callerFilePath = "") => callerFilePath;
|
[Fact]
|
||||||
|
public void LoadMap_MapHasClassAndLoaderHasNoCustomTypes_ThrowsException()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var resourceReader = Substitute.For<IResourceReader>();
|
||||||
|
resourceReader.Read("map.tmx").Returns(
|
||||||
|
"""
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<map version="1.10" tiledversion="1.11.0" class="TestClass" orientation="orthogonal" renderorder="right-down" width="5" height="5" tilewidth="32" tileheight="32" infinite="0" nextlayerid="2" nextobjectid="1">
|
||||||
|
<layer id="1" name="Tile Layer 1" width="5" height="5">
|
||||||
|
<data encoding="csv">
|
||||||
|
0,0,0,0,0,
|
||||||
|
0,0,0,0,0,
|
||||||
|
0,0,0,0,0,
|
||||||
|
0,0,0,0,0,
|
||||||
|
0,0,0,0,0
|
||||||
|
</data>
|
||||||
|
</layer>
|
||||||
|
</map>
|
||||||
|
""");
|
||||||
|
|
||||||
|
var resourceCache = Substitute.For<IResourceCache>();
|
||||||
|
var customTypeDefinitions = Enumerable.Empty<ICustomTypeDefinition>();
|
||||||
|
var loader = new Loader(resourceReader, resourceCache, customTypeDefinitions);
|
||||||
|
|
||||||
|
// Act & Assert
|
||||||
|
Assert.Throws<KeyNotFoundException>(() => loader.LoadMap("map.tmx"));
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Test1()
|
public void LoadMap_MapHasClassAndLoaderHasCustomTypeWithSameName_ReturnsMapWithPropertiesFromCustomClass()
|
||||||
{
|
{
|
||||||
var basePath = Path.GetDirectoryName(WhereAmI())!;
|
// Arrange
|
||||||
var mapPath = Path.Combine(basePath, "TestData/Map/map-with-external-tileset/map-with-external-tileset.tmx");
|
var resourceReader = Substitute.For<IResourceReader>();
|
||||||
var loader = Loader.Default();
|
resourceReader.Read("map.tmx").Returns(
|
||||||
loader.LoadMap(mapPath);
|
"""
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<map version="1.10" tiledversion="1.11.0" class="TestClass" orientation="orthogonal" renderorder="right-down" width="5" height="5" tilewidth="32" tileheight="32" infinite="0" nextlayerid="2" nextobjectid="1">
|
||||||
|
<layer id="1" name="Tile Layer 1" width="5" height="5">
|
||||||
|
<data encoding="csv">
|
||||||
|
0,0,0,0,0,
|
||||||
|
0,0,0,0,0,
|
||||||
|
0,0,0,0,0,
|
||||||
|
0,0,0,0,0,
|
||||||
|
0,0,0,0,0
|
||||||
|
</data>
|
||||||
|
</layer>
|
||||||
|
</map>
|
||||||
|
""");
|
||||||
|
var resourceCache = Substitute.For<IResourceCache>();
|
||||||
|
var customClassDefinition = new CustomClassDefinition
|
||||||
|
{
|
||||||
|
Name = "TestClass",
|
||||||
|
UseAs = CustomClassUseAs.All,
|
||||||
|
Members = [
|
||||||
|
new StringProperty { Name = "Test1", Value = "Hello" },
|
||||||
|
new IntProperty { Name = "Test2", Value = 42 }
|
||||||
|
]
|
||||||
|
};
|
||||||
|
var loader = new Loader(resourceReader, resourceCache, [customClassDefinition]);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = loader.LoadMap("map.tmx");
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
DotTiledAssert.AssertProperties(customClassDefinition.Members, result.Properties);
|
||||||
}
|
}
|
||||||
}
|
}
|
49
src/DotTiled.Tests/UnitTests/Serialization/TestData.cs
Normal file
|
@ -0,0 +1,49 @@
|
||||||
|
using System.Xml;
|
||||||
|
|
||||||
|
namespace DotTiled.Tests;
|
||||||
|
|
||||||
|
public static partial class TestData
|
||||||
|
{
|
||||||
|
public static XmlReader GetXmlReaderFor(string testDataFile)
|
||||||
|
{
|
||||||
|
var fullyQualifiedTestDataFile = $"DotTiled.Tests.{ConvertPathToAssemblyResourcePath(testDataFile)}";
|
||||||
|
using var stream = typeof(TestData).Assembly.GetManifestResourceStream(fullyQualifiedTestDataFile)
|
||||||
|
?? throw new ArgumentException($"Test data file '{fullyQualifiedTestDataFile}' not found");
|
||||||
|
|
||||||
|
using var stringReader = new StreamReader(stream);
|
||||||
|
var xml = stringReader.ReadToEnd();
|
||||||
|
var xmlStringReader = new StringReader(xml);
|
||||||
|
return XmlReader.Create(xmlStringReader);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string GetRawStringFor(string testDataFile)
|
||||||
|
{
|
||||||
|
var fullyQualifiedTestDataFile = $"DotTiled.Tests.{ConvertPathToAssemblyResourcePath(testDataFile)}";
|
||||||
|
using var stream = typeof(TestData).Assembly.GetManifestResourceStream(fullyQualifiedTestDataFile)
|
||||||
|
?? throw new ArgumentException($"Test data file '{fullyQualifiedTestDataFile}' not found");
|
||||||
|
|
||||||
|
using var stringReader = new StreamReader(stream);
|
||||||
|
return stringReader.ReadToEnd();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string ConvertPathToAssemblyResourcePath(string path) =>
|
||||||
|
path.Replace("/", ".").Replace("\\", ".").Replace(" ", "_");
|
||||||
|
|
||||||
|
private static string GetMapPath(string mapName) => $"TestData/Maps/{mapName.Replace('-', '_')}/{mapName}";
|
||||||
|
|
||||||
|
public static IEnumerable<object[]> MapTests =>
|
||||||
|
[
|
||||||
|
[GetMapPath("default-map"), (string f) => DefaultMap(), Array.Empty<ICustomTypeDefinition>()],
|
||||||
|
[GetMapPath("map-with-common-props"), (string f) => MapWithCommonProps(), Array.Empty<ICustomTypeDefinition>()],
|
||||||
|
[GetMapPath("map-with-custom-type-props"), (string f) => MapWithCustomTypeProps(), MapWithCustomTypePropsCustomTypeDefinitions()],
|
||||||
|
[GetMapPath("map-with-embedded-tileset"), (string f) => MapWithEmbeddedTileset(), Array.Empty<ICustomTypeDefinition>()],
|
||||||
|
[GetMapPath("map-with-external-tileset"), (string f) => MapWithExternalTileset(f), Array.Empty<ICustomTypeDefinition>()],
|
||||||
|
[GetMapPath("map-with-flippingflags"), (string f) => MapWithFlippingFlags(f), Array.Empty<ICustomTypeDefinition>()],
|
||||||
|
[GetMapPath("map-external-tileset-multi"), (string f) => MapExternalTilesetMulti(f), Array.Empty<ICustomTypeDefinition>()],
|
||||||
|
[GetMapPath("map-external-tileset-wangset"), (string f) => MapExternalTilesetWangset(f), Array.Empty<ICustomTypeDefinition>()],
|
||||||
|
[GetMapPath("map-with-many-layers"), (string f) => MapWithManyLayers(f), Array.Empty<ICustomTypeDefinition>()],
|
||||||
|
[GetMapPath("map-with-deep-props"), (string f) => MapWithDeepProps(), MapWithDeepPropsCustomTypeDefinitions()],
|
||||||
|
[GetMapPath("map-with-class"), (string f) => MapWithClass(), MapWithClassCustomTypeDefinitions()],
|
||||||
|
[GetMapPath("map-with-class-and-props"), (string f) => MapWithClassAndProps(), MapWithClassAndPropsCustomTypeDefinitions()],
|
||||||
|
];
|
||||||
|
}
|
|
@ -1,6 +1,4 @@
|
||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Diagnostics.CodeAnalysis;
|
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
|
||||||
namespace DotTiled;
|
namespace DotTiled;
|
||||||
|
@ -8,7 +6,7 @@ namespace DotTiled;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Represents a class property.
|
/// Represents a class property.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class ClassProperty : IHasProperties, IProperty<IList<IProperty>>
|
public class ClassProperty : HasPropertiesBase, IProperty<IList<IProperty>>
|
||||||
{
|
{
|
||||||
/// <inheritdoc/>
|
/// <inheritdoc/>
|
||||||
public required string Name { get; set; }
|
public required string Name { get; set; }
|
||||||
|
@ -36,30 +34,5 @@ public class ClassProperty : IHasProperties, IProperty<IList<IProperty>>
|
||||||
};
|
};
|
||||||
|
|
||||||
/// <inheritdoc/>
|
/// <inheritdoc/>
|
||||||
public IList<IProperty> GetProperties() => Value;
|
public override IList<IProperty> GetProperties() => Value;
|
||||||
|
|
||||||
/// <inheritdoc/>
|
|
||||||
public T GetProperty<T>(string name) where T : IProperty
|
|
||||||
{
|
|
||||||
var property = Value.FirstOrDefault(_properties => _properties.Name == name) ?? throw new InvalidOperationException($"Property '{name}' not found.");
|
|
||||||
if (property is T prop)
|
|
||||||
{
|
|
||||||
return prop;
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new InvalidOperationException($"Property '{name}' is not of type '{typeof(T).Name}'.");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <inheritdoc/>
|
|
||||||
public bool TryGetProperty<T>(string name, [NotNullWhen(true)] out T property) where T : IProperty
|
|
||||||
{
|
|
||||||
if (Value.FirstOrDefault(_properties => _properties.Name == name) is T prop)
|
|
||||||
{
|
|
||||||
property = prop;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
property = default;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,5 +1,7 @@
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Reflection;
|
||||||
|
|
||||||
namespace DotTiled;
|
namespace DotTiled;
|
||||||
|
|
||||||
|
@ -95,4 +97,95 @@ public class CustomClassDefinition : HasPropertiesBase, ICustomTypeDefinition
|
||||||
|
|
||||||
/// <inheritdoc/>
|
/// <inheritdoc/>
|
||||||
public override IList<IProperty> GetProperties() => Members;
|
public override IList<IProperty> GetProperties() => Members;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Creates a new <see cref="CustomClassDefinition"/> from the specified class type.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="type">The type of the class to create a custom class definition from.</param>
|
||||||
|
/// <returns>A new <see cref="CustomClassDefinition"/> instance.</returns>
|
||||||
|
/// <exception cref="ArgumentException">Thrown when the specified type is not a class.</exception>
|
||||||
|
public static CustomClassDefinition FromClass(Type type)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(type, nameof(type));
|
||||||
|
|
||||||
|
if (type == typeof(string) || !type.IsClass)
|
||||||
|
throw new ArgumentException("Type must be a class.", nameof(type));
|
||||||
|
|
||||||
|
var instance = Activator.CreateInstance(type);
|
||||||
|
var properties = type.GetProperties();
|
||||||
|
|
||||||
|
return new CustomClassDefinition
|
||||||
|
{
|
||||||
|
Name = type.Name,
|
||||||
|
UseAs = CustomClassUseAs.All,
|
||||||
|
Members = properties.Select(p => ConvertPropertyInfoToIProperty(instance, p)).ToList()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Creates a new <see cref="CustomClassDefinition"/> from the specified constructible class type.
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T">The type of the class to create a custom class definition from.</typeparam>
|
||||||
|
/// <returns>A new <see cref="CustomClassDefinition"/> instance.</returns>
|
||||||
|
public static CustomClassDefinition FromClass<T>() where T : class, new() => FromClass(() => new T());
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Creates a new <see cref="CustomClassDefinition"/> from the specified factory function of a class instance.
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T">The type of the class to create a custom class definition from.</typeparam>
|
||||||
|
/// <param name="factory">The factory function that creates an instance of the class.</param>
|
||||||
|
/// <returns>A new <see cref="CustomClassDefinition"/> instance.</returns>
|
||||||
|
public static CustomClassDefinition FromClass<T>(Func<T> factory) where T : class
|
||||||
|
{
|
||||||
|
var instance = factory();
|
||||||
|
var type = typeof(T);
|
||||||
|
var properties = type.GetProperties();
|
||||||
|
|
||||||
|
return new CustomClassDefinition
|
||||||
|
{
|
||||||
|
Name = type.Name,
|
||||||
|
UseAs = CustomClassUseAs.All,
|
||||||
|
Members = properties.Select(p => ConvertPropertyInfoToIProperty(instance, p)).ToList()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IProperty ConvertPropertyInfoToIProperty(object instance, PropertyInfo propertyInfo)
|
||||||
|
{
|
||||||
|
switch (propertyInfo.PropertyType)
|
||||||
|
{
|
||||||
|
case Type t when t == typeof(bool):
|
||||||
|
return new BoolProperty { Name = propertyInfo.Name, Value = (bool)propertyInfo.GetValue(instance) };
|
||||||
|
case Type t when t == typeof(Color):
|
||||||
|
return new ColorProperty { Name = propertyInfo.Name, Value = (Color)propertyInfo.GetValue(instance) };
|
||||||
|
case Type t when t == typeof(float):
|
||||||
|
return new FloatProperty { Name = propertyInfo.Name, Value = (float)propertyInfo.GetValue(instance) };
|
||||||
|
case Type t when t == typeof(string):
|
||||||
|
return new StringProperty { Name = propertyInfo.Name, Value = (string)propertyInfo.GetValue(instance) };
|
||||||
|
case Type t when t == typeof(int):
|
||||||
|
return new IntProperty { Name = propertyInfo.Name, Value = (int)propertyInfo.GetValue(instance) };
|
||||||
|
case Type t when t.IsClass:
|
||||||
|
return new ClassProperty { Name = propertyInfo.Name, PropertyType = t.Name, Value = GetNestedProperties(propertyInfo.PropertyType, propertyInfo.GetValue(instance)) };
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new NotSupportedException($"Type '{propertyInfo.PropertyType.Name}' is not supported in custom classes.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<IProperty> GetNestedProperties(Type type, object instance)
|
||||||
|
{
|
||||||
|
var defaultInstance = Activator.CreateInstance(type);
|
||||||
|
var properties = type.GetProperties();
|
||||||
|
|
||||||
|
bool IsPropertyDefaultValue(PropertyInfo propertyInfo)
|
||||||
|
{
|
||||||
|
var defaultValue = propertyInfo.GetValue(defaultInstance);
|
||||||
|
var value = propertyInfo.GetValue(instance);
|
||||||
|
return value.Equals(defaultValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
return properties
|
||||||
|
.Where(p => !IsPropertyDefaultValue(p))
|
||||||
|
.Select(p => ConvertPropertyInfoToIProperty(instance, p)).ToList();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,6 @@
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
|
||||||
namespace DotTiled;
|
namespace DotTiled;
|
||||||
|
|
||||||
|
@ -44,4 +46,43 @@ public class CustomEnumDefinition : ICustomTypeDefinition
|
||||||
/// Whether the value should be treated as flags.
|
/// Whether the value should be treated as flags.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool ValueAsFlags { get; set; }
|
public bool ValueAsFlags { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Creates a custom enum definition from the specified enum type.
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static CustomEnumDefinition FromEnum<T>() where T : Enum
|
||||||
|
{
|
||||||
|
var type = typeof(T);
|
||||||
|
var isFlags = type.GetCustomAttributes(typeof(FlagsAttribute), false).Length != 0;
|
||||||
|
|
||||||
|
return new CustomEnumDefinition
|
||||||
|
{
|
||||||
|
Name = type.Name,
|
||||||
|
StorageType = CustomEnumStorageType.Int,
|
||||||
|
Values = Enum.GetNames(type).ToList(),
|
||||||
|
ValueAsFlags = isFlags
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Creates a custom enum definition from the specified enum type.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static CustomEnumDefinition FromEnum(Type type)
|
||||||
|
{
|
||||||
|
if (!type.IsEnum)
|
||||||
|
throw new ArgumentException("Type must be an enum.", nameof(type));
|
||||||
|
|
||||||
|
var isFlags = type.GetCustomAttributes(typeof(FlagsAttribute), false).Length != 0;
|
||||||
|
|
||||||
|
return new CustomEnumDefinition
|
||||||
|
{
|
||||||
|
Name = type.Name,
|
||||||
|
StorageType = CustomEnumStorageType.Int,
|
||||||
|
Values = Enum.GetNames(type).ToList(),
|
||||||
|
ValueAsFlags = isFlags
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Diagnostics.CodeAnalysis;
|
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
|
||||||
namespace DotTiled;
|
namespace DotTiled;
|
||||||
|
@ -31,6 +30,21 @@ public interface IHasProperties
|
||||||
/// <param name="name">The name of the property to get.</param>
|
/// <param name="name">The name of the property to get.</param>
|
||||||
/// <returns>The property with the specified name.</returns>
|
/// <returns>The property with the specified name.</returns>
|
||||||
T GetProperty<T>(string name) where T : IProperty;
|
T GetProperty<T>(string name) where T : IProperty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Maps all properties in this object to a new instance of the specified type using reflection.
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <returns></returns>
|
||||||
|
T MapPropertiesTo<T>() where T : new();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Maps all properties in this object to a new instance of the specified type using reflection.
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <param name="initializer"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
T MapPropertiesTo<T>(Func<T> initializer);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
@ -57,7 +71,7 @@ public abstract class HasPropertiesBase : IHasProperties
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc/>
|
/// <inheritdoc/>
|
||||||
public bool TryGetProperty<T>(string name, [NotNullWhen(true)] out T property) where T : IProperty
|
public bool TryGetProperty<T>(string name, out T property) where T : IProperty
|
||||||
{
|
{
|
||||||
var properties = GetProperties();
|
var properties = GetProperties();
|
||||||
if (properties.FirstOrDefault(_properties => _properties.Name == name) is T prop)
|
if (properties.FirstOrDefault(_properties => _properties.Name == name) is T prop)
|
||||||
|
@ -69,4 +83,64 @@ public abstract class HasPropertiesBase : IHasProperties
|
||||||
property = default;
|
property = default;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc/>
|
||||||
|
public T MapPropertiesTo<T>() where T : new() => CreateMappedInstance<T>(GetProperties());
|
||||||
|
|
||||||
|
/// <inheritdoc/>
|
||||||
|
public T MapPropertiesTo<T>(Func<T> initializer) => CreateMappedInstance(GetProperties(), initializer);
|
||||||
|
|
||||||
|
private static object CreatedMappedInstance(object instance, IList<IProperty> properties)
|
||||||
|
{
|
||||||
|
var type = instance.GetType();
|
||||||
|
|
||||||
|
foreach (var prop in properties)
|
||||||
|
{
|
||||||
|
if (type.GetProperty(prop.Name) == null)
|
||||||
|
throw new KeyNotFoundException($"Property '{prop.Name}' not found in '{type.Name}'.");
|
||||||
|
|
||||||
|
switch (prop)
|
||||||
|
{
|
||||||
|
case BoolProperty boolProp:
|
||||||
|
type.GetProperty(prop.Name)?.SetValue(instance, boolProp.Value);
|
||||||
|
break;
|
||||||
|
case ColorProperty colorProp:
|
||||||
|
type.GetProperty(prop.Name)?.SetValue(instance, colorProp.Value);
|
||||||
|
break;
|
||||||
|
case FloatProperty floatProp:
|
||||||
|
type.GetProperty(prop.Name)?.SetValue(instance, floatProp.Value);
|
||||||
|
break;
|
||||||
|
case FileProperty fileProp:
|
||||||
|
type.GetProperty(prop.Name)?.SetValue(instance, fileProp.Value);
|
||||||
|
break;
|
||||||
|
case IntProperty intProp:
|
||||||
|
type.GetProperty(prop.Name)?.SetValue(instance, intProp.Value);
|
||||||
|
break;
|
||||||
|
case ObjectProperty objectProp:
|
||||||
|
type.GetProperty(prop.Name)?.SetValue(instance, objectProp.Value);
|
||||||
|
break;
|
||||||
|
case StringProperty stringProp:
|
||||||
|
type.GetProperty(prop.Name)?.SetValue(instance, stringProp.Value);
|
||||||
|
break;
|
||||||
|
case ClassProperty classProp:
|
||||||
|
var subClassProp = type.GetProperty(prop.Name);
|
||||||
|
subClassProp?.SetValue(instance, CreatedMappedInstance(Activator.CreateInstance(subClassProp.PropertyType), classProp.GetProperties()));
|
||||||
|
break;
|
||||||
|
case EnumProperty enumProp:
|
||||||
|
var enumPropInClass = type.GetProperty(prop.Name);
|
||||||
|
var enumType = enumPropInClass?.PropertyType;
|
||||||
|
enumPropInClass?.SetValue(instance, Enum.Parse(enumType!, string.Join(", ", enumProp.Value)));
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw new ArgumentOutOfRangeException($"Unknown property type {prop.GetType().Name}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static T CreateMappedInstance<T>(IList<IProperty> properties) where T : new() =>
|
||||||
|
(T)CreatedMappedInstance(Activator.CreateInstance<T>() ?? throw new InvalidOperationException($"Failed to create instance of '{typeof(T).Name}'."), properties);
|
||||||
|
|
||||||
|
private static T CreateMappedInstance<T>(IList<IProperty> properties, Func<T> initializer) => (T)CreatedMappedInstance(initializer(), properties);
|
||||||
}
|
}
|
||||||
|
|