diff --git a/.editorconfig b/.editorconfig index 71746d2..8e747e9 100644 --- a/.editorconfig +++ b/.editorconfig @@ -235,6 +235,7 @@ dotnet_diagnostic.IDE0004.severity = silent dotnet_diagnostic.IDE0005.severity = error dotnet_diagnostic.IDE0008.severity = silent dotnet_diagnostic.IDE0055.severity = silent +dotnet_diagnostic.IDE0058.severity = silent dotnet_diagnostic.IDE0160.severity = none dotnet_diagnostic.CA1707.severity = silent dotnet_diagnostic.CA1852.severity = none @@ -243,7 +244,7 @@ dotnet_diagnostic.CA1720.severity = silent dotnet_diagnostic.CA1711.severity = silent dotnet_diagnostic.CA1716.severity = silent -[.github/**/*.yml] +[*.(yml|json|js)] charset = utf-8 end_of_line = lf indent_size = 2 diff --git a/Makefile b/Makefile index 601eda2..f7382f5 100644 --- a/Makefile +++ b/Makefile @@ -2,13 +2,15 @@ test: dotnet build src/DotTiled.sln dotnet test src/DotTiled.sln -docs-serve: +docs-serve: docs/index.md docfx docs/docfx.json --serve -docs-build: - cp README.md docs/index.md +docs-build: docs/index.md docfx docs/docfx.json +docs/index.md: + cp README.md docs/index.md + lint: dotnet format style --verify-no-changes src/DotTiled.sln dotnet format analyzers --verify-no-changes src/DotTiled.sln diff --git a/docs/docfx.json b/docs/docfx.json index 4c955cb..cb678c9 100644 --- a/docs/docfx.json +++ b/docs/docfx.json @@ -41,7 +41,7 @@ "_appName": "DotTiled", "_appTitle": "DotTiled", "_enableSearch": true, - "pdf": true + "pdf": false } } } \ No newline at end of file diff --git a/docs/docs/essentials/loading-maps.md b/docs/docs/essentials/loading-maps.md index b34b964..d262ec9 100644 --- a/docs/docs/essentials/loading-maps.md +++ b/docs/docs/essentials/loading-maps.md @@ -1,15 +1,92 @@ # Loading maps -Loading maps with DotTiled is straightforward and easy. The class is a representation of a Tiled map, mimicking the structure of a Tiled map file. Map files can either be in the [`.tmx`/XML](https://doc.mapeditor.org/en/stable/reference/tmx-map-format/) or [`.tmj`/json](https://doc.mapeditor.org/en/stable/reference/json-map-format/) format. DotTiled supports **both** formats fully. +Loading maps with DotTiled is very flexible and allows you as a developer to freely choose how you want to load your maps and tilesets. This guide will show you how to customize the loading process to fit your needs. As the tip below suggests, you can also use the quickstart guide if you just want to load maps from the filesystem without any particular customization. -> [!NOTE] -> Using the `.tmj` file format will result in not having the same amount of information as for the `.tmx` format. This is due to the fact that the `.tmj` format does not include the full information that the `.tmx` format does. This is not a problem with DotTiled, but rather a limitation of the `.tmj` format. +> [!TIP] +> For a quick and easy way to load maps from the filesystem, please refer to the [quickstart guide](../quickstart.md). -## External resolution +## File format caveats -Tiled maps may consist of several external files, such as tilesets or object templates. In Tiled map files, they are typically referenced by their path relative to the map file. It would be annoying to have to first load all these external resources before loading a map (which is how some other similar libraries work), so loading a map with DotTiled is designed in a way that you only have to provide a function that resolves these external resources. This way, DotTiled will figure out which external resources are needed and will invoke the corresponding resolver function to load them. +The class is a representation of a Tiled map, mimicking the structure of a Tiled XML map file. Map files can either be in the [`.tmx`/XML](https://doc.mapeditor.org/en/stable/reference/tmx-map-format/) or [`.tmj`/json](https://doc.mapeditor.org/en/stable/reference/json-map-format/) format. DotTiled supports **both** formats fully. -Loading a map, tileset, or template will require you to specify **three** resolver functions. We'll go through each of them below. +> [!WARNING] +> Using the `.tmj` file format will result in (the source image for image layers) not having the same amount of information as for the `.tmx` format. This is due to the fact that the `.tmj` format does not include the full information that the `.tmx` format does. This is not a problem with DotTiled, but rather a limitation of the `.tmj` format. + +## The process of loading a map + +Loading a map with DotTiled is not a complex process, but one that at least demands a basic understanding of how Tiled maps are structured. The process can be broken down into the following flow(-ish) chart: + +```mermaid +flowchart LR + Z{{Loading a map + with DotTiled}} --> A + + subgraph Parsing map + A[(Read map)] --> B(Parse map) + end + + subgraph Parsing tileset + B -.->|References + external tileset| C[(Read tileset)] + C --> D(Parse tileset) --o|Store in map| B + end + + subgraph Parsing template + B -.->|References external + template in object| E[(Read template)] + E --> F(Parse template) --o|Use as template + for object| B + end + + F -.-> |References + external tileset| C + F -.-> |References + external template| E +``` + +As you can see, the process is quite simple. You read the map, parse it, and then read and parse any external tilesets or templates that are referenced in the map. The tilesets and templates are then stored in the map object that is returned to you. + +However, because DotTiled works in the way that it does, you will need to provide a way to resolve these external resources. We'll go through how to do that in the next section. + +## Loading a map with + +When using , external resources like tilesets and templates will be resolved by the loader itself. Since Tiled saves the external resource paths relative to the map file, the loader will automatically resolve these paths and use the provided to read the external resources. Therefore, as long as the external resources are accessible in a "relative path" way using the provided , you don't have to worry about resolving them yourself. + +```xml + + + + + +1,1,0,0,7, +1,1,0,0,7, +0,0,1,0,7, +0,0,0,1,7, +21,21,21,21,1 + + + +``` + +A map like the one above that is loaded by the following code will result in the loader calling `IResourceReader.Read("path/to/tileset.tsx")` to read the external tileset, since it will use the path relative to the map file to resolve the tileset. + +```csharp +var loader = Loader.Default(); +var map = loader.LoadMap("path/to/map.tmx"); +``` + +Additionally, the loader will use an in-memory cache to avoid loading the same tileset or template multiple times. This is done using the that is provided to the loader. If you don't provide a cache, the loader will use the by default. + +## Loading a map manually with + +While it is recommended to use the class to perform the loading of maps and tilesets, you may have certain requirements that necessitate you to load maps in a more manual way. This section will guide you through how to load a map manually without the use of the provided loader. + +### , , and + +are the three classes that you will use to read the map, tileset, and template, respectively. They are designed to be used in a way that you can provide your own resolver functions to load external resources. + +> [!IMPORTANT] +> The resolving functions will get the source path of the external resource as a parameter, *in the exact way it is written in the map file*. You will have to perform your own path resolution to load the external resources. ### `Func` - Tileset resolver @@ -38,17 +115,17 @@ Tileset ResolveTileset(string source) ### `Func` - Template resolver -This function is used to resolve external object templates by their source path. The function should return a instance given the source path of the template. If you just want to load templates from the file system, you can use something very similar to the tileset resolver by replacing with . +This function is used to resolve external object templates by their source path. The function should return a instance given the source path of the template. If you just want to load templates from the file system, you can use something very similar to the example tileset resolver by replacing with . -### `Func` - Custom type resolver +### `Func` - Custom type resolver -This function is used to resolve custom types that are defined in Tiled maps. Please refer to the [custom properties](custom-properties.md) documentation for more information on custom types. The function should return a instance given the custom type's name. +This function is used to resolve custom types that are defined in your Tiled maps. Please refer to the [custom properties](custom-properties.md) documentation for more information on custom types. The function should return a instance given the custom type's name. ## Putting it all together The following classes are the readers that you will need to use to read the map, tileset, and template: , , and . -Here is an example of how you can load a map with DotTiled: +Here is an example of how you can load a map with DotTiled, and is very similar to how the class works: ```csharp string mapPath = "path/to/map.tmx"; diff --git a/docs/docs/quickstart.md b/docs/docs/quickstart.md index 8d067eb..c43031b 100644 --- a/docs/docs/quickstart.md +++ b/docs/docs/quickstart.md @@ -6,41 +6,64 @@ Install DotTiled from NuGet: dotnet add package DotTiled ``` -Load a map from file system: +Use the `DotTiled` namespace (if you want). ```csharp -string mapPath = "path/to/map.tmx"; -string mapDirectory = Path.GetDirectoryName(mapPath); - -Tileset ResolveTileset(string source) -{ - string tilesetPath = Path.Combine(mapDirectory, source); - using var tilesetFileReader = new StreamReader(tilesetPath); - var tilesetString = tilesetReader.ReadToEnd(); - using var tilesetReader = new TilesetReader(tilesetString, ResolveTileset, ResolveTemplate, ResolveCustomType); - return tilesetReader.ReadTileset(); -} - -Template ResolveTemplate(string source) -{ - string templatePath = Path.Combine(mapDirectory, source); - using var templateFileReader = new StreamReader(templatePath); - var templateString = templateReader.ReadToEnd(); - using var templateReader = new TemplateReader(templateString, ResolveTileset, ResolveTemplate, ResolveCustomType); - return templateReader.ReadTemplate(); -} - -ICustomTypeDefinition ResolveCustomType(string name) -{ - var allDefinedTypes = [ ... ]; - return allDefinedTypes.FirstOrDefault(type => type.Name == name); -} - -using var mapFileReader = new StreamReader(mapPath); -var mapString = mapFileReader.ReadToEnd(); -using var mapReader = new MapReader(mapString, ResolveTileset, ResolveTemplate, ResolveCustomType); - -var map = mapReader.ReadMap(); +using DotTiled; ``` -If the above looks intimidating, don't worry! DotTiled is designed to be flexible and allow you to load maps from any source, such as a database or a custom file format. The above example is just one way to load a map from a file system. Please look at [Loading Maps](essentials/loading-maps.md) for more information on how to load maps from different sources. \ No newline at end of file +Or fully qualify all `DotTiled` types e.g. `DotTiled.Loader`. + +## Loading a map from the file system + +This will create a loader that will load files from the underlying file system using . It will also be configured to use an in-memory cache to avoid loading the same tileset or template multiple times using . + +```csharp +var loader = Loader.Default(); +var map = loader.LoadMap("path/to/map.tmx"); +``` + +## Loading a map from a different source + +If you want to load resources (maps, tilesets, templates) from a different source than the underlying file system, you can override the that is being used with your own implementation of . + +```csharp +var loader = Loader.DefaultWith( + resourceReader: new MyCustomResourceReader()); +var map = loader.LoadMap("path/to/map.tmx"); +``` + +## Caching resources + +Similarly, you can override the that is being used with your own implementation of . + +```csharp +var loader = Loader.DefaultWith( + resourceReader: new MyCustomResourceReader(), + resourceCache: new MyCustomResourceCache()); +var map = loader.LoadMap("path/to/map.tmx"); +``` + +## Custom types + +If you have custom types in your map, you can provide any `IEnumerable` to the loader. This will allow the loader to deserialize the custom types in your map. + +```csharp +var monsterSpawnerDef = new CustomClassDefinition { ... }; +var chestDef = new CustomClassDefinition +{ + Name = "Chest", + UseAs = CustomClassUseAs.All, + Members = [ + new IntProperty { Name = "coins", Value = 0 }, + new BoolProperty { Name = "locked", Value = true } + ] +}; + +var loader = Loader.DefaultWith( + customTypeDefinitions: [monsterSpawnerDef, chestDef]); +var map = loader.LoadMap("path/to/map.tmx"); + +var chest = map.GetProperty("chest").Value; +var coinsToSpawn = chest.GetProperty("coins").Value; +``` \ No newline at end of file diff --git a/docs/template/public/main.js b/docs/template/public/main.js new file mode 100644 index 0000000..7ab60f9 --- /dev/null +++ b/docs/template/public/main.js @@ -0,0 +1,9 @@ +export default { + iconLinks: [ + { + icon: 'github', + href: 'https://github.com/dcronqvist/DotTiled', + title: 'GitHub' + } + ] +} \ No newline at end of file diff --git a/src/DotTiled.Tests/DotTiled.Tests.csproj b/src/DotTiled.Tests/DotTiled.Tests.csproj index eff4ec8..45d8f5a 100644 --- a/src/DotTiled.Tests/DotTiled.Tests.csproj +++ b/src/DotTiled.Tests/DotTiled.Tests.csproj @@ -11,6 +11,7 @@ + diff --git a/src/DotTiled.Tests/Serialization/DefaultResourceCacheTests.cs b/src/DotTiled.Tests/Serialization/DefaultResourceCacheTests.cs new file mode 100644 index 0000000..6108833 --- /dev/null +++ b/src/DotTiled.Tests/Serialization/DefaultResourceCacheTests.cs @@ -0,0 +1,78 @@ +using DotTiled.Serialization; + +namespace DotTiled.Tests; + +public class DefaultResourceCacheTests +{ + [Fact] + public void GetTemplate_TemplateDoesNotExist_ReturnsEmptyOptional() + { + // Arrange + var cache = new DefaultResourceCache(); + var path = "template.tsx"; + + // Act + var result = cache.GetTemplate(path); + + // Assert + Assert.False(result.HasValue); + } + + [Fact] + public void GetTemplate_TemplateHasBeenInserted_ReturnsTemplate() + { + // Arrange + var cache = new DefaultResourceCache(); + var path = "template.tsx"; + var template = new Template + { + Object = new EllipseObject { } + }; + + // Act + cache.InsertTemplate(path, template); + var result = cache.GetTemplate(path); + + // Assert + Assert.True(result.HasValue); + Assert.Same(template, result.Value); + } + + [Fact] + public void GetTileset_TilesetDoesNotExist_ReturnsEmptyOptional() + { + // Arrange + var cache = new DefaultResourceCache(); + var path = "tileset.tsx"; + + // Act + var result = cache.GetTileset(path); + + // Assert + Assert.False(result.HasValue); + } + + [Fact] + public void GetTileset_TilesetHasBeenInserted_ReturnsTileset() + { + // Arrange + var cache = new DefaultResourceCache(); + var path = "tileset.tsx"; + var tileset = new Tileset + { + Name = "Tileset", + TileWidth = 32, + TileHeight = 32, + TileCount = 1, + Columns = 1 + }; + + // Act + cache.InsertTileset(path, tileset); + var result = cache.GetTileset(path); + + // Assert + Assert.True(result.HasValue); + Assert.Same(tileset, result.Value); + } +} diff --git a/src/DotTiled.Tests/Serialization/LoaderTests.cs b/src/DotTiled.Tests/Serialization/LoaderTests.cs new file mode 100644 index 0000000..4706445 --- /dev/null +++ b/src/DotTiled.Tests/Serialization/LoaderTests.cs @@ -0,0 +1,259 @@ +using System.Numerics; +using System.Runtime.CompilerServices; +using DotTiled.Serialization; +using NSubstitute; + +namespace DotTiled.Tests; + +public class LoaderTests +{ + [Fact] + public void LoadMap_Always_ReadsFromResourceReader() + { + // Arrange + var resourceReader = Substitute.For(); + resourceReader.Read("map.tmx").Returns( + """ + + + + + 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 + + + + """); + + var resourceCache = Substitute.For(); + var customTypeDefinitions = Enumerable.Empty(); + var loader = new Loader(resourceReader, resourceCache, customTypeDefinitions); + + // Act + loader.LoadMap("map.tmx"); + + // Assert + resourceReader.Received(1).Read("map.tmx"); + } + + [Fact] + public void LoadMap_MapReferencesExternalTileset_ReadsTilesetFromResourceReaderAndAttemptsToRetrieveFromCache() + { + // Arrange + var resourceReader = Substitute.For(); + resourceReader.Read("map.tmx").Returns( + """ + + + + + + 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 + + + + """); + + resourceReader.Read("tileset.tsx").Returns( + """ + + + + + + + """); + + var resourceCache = Substitute.For(); + resourceCache.GetTileset(Arg.Any()).Returns(Optional.Empty); + resourceCache.GetTemplate(Arg.Any()).Returns(Optional