Skip to content

Commit

Permalink
Code refactoring release 2.1.5
Browse files Browse the repository at this point in the history
  • Loading branch information
Kiamo2 committed Dec 20, 2024
1 parent 69dd9c4 commit 7e09133
Show file tree
Hide file tree
Showing 45 changed files with 884 additions and 1,147 deletions.
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [2.1.5] - 2024-12-20

### Refactoring notes (no change in functionalitiy)

- All data loading from Tiled files is now amalgamated into a new module 'DataLoader'
This is especially beneficial for runtime version users to allow for easier customizing of data loading.
E.g. loading from Zip file basically only needs one additional line somewhere ahead from the TilsetCreator.create() call:
```py
DataLoader.zip_file = "<path-to-zip>/xyz.zip"
```
## [2.1.4] - 2024-12-16

### Fixed
Expand Down
7 changes: 5 additions & 2 deletions CSharp/addons/YATI/CommonUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ public static class CommonUtils
{
private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;

public static int ErrorCount { get; set; }
public static int WarningCount { get; set; }

public static uint GetBitmaskIntegerFromString(string maskString, int max)
{
uint ret = 0;
Expand All @@ -47,8 +50,8 @@ public static uint GetBitmaskIntegerFromString(string maskString, int max)
if (i <= max)
ret += (uint)Math.Pow(2, i - 1);
}
else if (int.TryParse(s1, out var i))
if (i <= max)
else if (int.TryParse(s1, out var i))
if (i <= max)
ret += (uint)Math.Pow(2, i - 1);
}

Expand Down
18 changes: 13 additions & 5 deletions CSharp/addons/YATI/CustomTypes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,17 @@ namespace YATI;
public class CustomTypes
{
private Array<Dictionary> _customTypes;

public void LoadCustomTypes(string projectFile)
{
var projFileAsDictionary = DictionaryBuilder.GetDictionary(projectFile);
var projFileContent = DataLoader.GetTiledFileContent(projectFile, "");
if (projFileContent == null)
{
GD.PrintErr($"ERROR: Tiled project file '{projectFile}' not found.");
CommonUtils.ErrorCount++;
return;
}
var projFileAsDictionary = DictionaryBuilder.GetDictionary(projFileContent, projectFile);
if (projFileAsDictionary.TryGetValue("propertyTypes", out var propTypes))
_customTypes = (Array<Dictionary>)propTypes;
}
Expand All @@ -44,7 +51,7 @@ public void UnloadCustomTypes()
{
_customTypes?.Clear();
}

public void MergeCustomProperties(Dictionary obj, string scope)
{
if (_customTypes == null) return;
Expand All @@ -62,7 +69,7 @@ public void MergeCustomProperties(Dictionary obj, string scope)
properties = new Array<Dictionary>();
newKey = true;
}

foreach (var ctProp in _customTypes)
{
var ptName = (string)ctProp.GetValueOrDefault("name", "");
Expand All @@ -80,8 +87,9 @@ public void MergeCustomProperties(Dictionary obj, string scope)
obj["properties"] = new Array<Dictionary>();
newKey = false;
}

((Array)obj["properties"]).Add(mem);
}
}
}
}
}
Expand Down
74 changes: 74 additions & 0 deletions CSharp/addons/YATI/DataLoader.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// MIT License
//
// Copyright (c) 2024 Roland Helmerichs
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#if TOOLS
using Godot;

namespace YATI;

[Tool]
public static class DataLoader
{
public static byte[] GetTiledFileContent(string fileName, string basePath)
{
var checkedFile = fileName;
if (!FileAccess.FileExists(checkedFile))
checkedFile = basePath.PathJoin(fileName);
if (!FileAccess.FileExists(checkedFile)) return null;

using var file = FileAccess.Open(checkedFile, FileAccess.ModeFlags.Read);
var ret = file.GetBuffer((long)file.GetLength());
return ret;
}

public static Texture2D LoadImage(string fileName, string basePath)
{
var checkedFile = fileName;
if (!FileAccess.FileExists(fileName))
checkedFile = basePath.PathJoin(fileName);
if (!FileAccess.FileExists(checkedFile))
{
GD.PrintErr($"ERROR: Image file '{fileName}' not found.");
CommonUtils.ErrorCount++;
return null;
}
var exists = ResourceLoader.Exists(checkedFile, "Image");
if (exists)
return (Texture2D)ResourceLoader.Load(checkedFile, "Image");

var image = Image.LoadFromFile(checkedFile);
return ImageTexture.CreateFromImage(image);
}

public static Resource LoadResourceFromFile(string resourceFile, string basePath)
{
var checkedFile = resourceFile;
if (!FileAccess.FileExists(checkedFile))
checkedFile = basePath.PathJoin(checkedFile);
if (FileAccess.FileExists(checkedFile))
return ResourceLoader.Load(checkedFile);

GD.PrintErr($"ERROR: Resource file '{resourceFile}' not found.");
CommonUtils.ErrorCount++;
return null;
}
}
#endif
26 changes: 7 additions & 19 deletions CSharp/addons/YATI/DictionaryBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,29 +37,18 @@ private enum FileType
Unknown
}

public static Dictionary GetDictionary(string sourceFile)
public static Dictionary GetDictionary(byte[] tiledFileContent, string sourceFile)
{
var checkedFile = sourceFile;
if (!FileAccess.FileExists(checkedFile))
{
checkedFile = sourceFile.GetBaseDir().PathJoin(sourceFile);
if (!FileAccess.FileExists(checkedFile))
{
GD.PrintErr($"ERROR: File '{sourceFile}' not found. -> Continuing but result may be unusable");
return null;
}
}


var type = FileType.Unknown;
var extension = sourceFile.GetFile().GetExtension();
var extension = sourceFile.GetFile().GetExtension().ToLower();
if (new[] { "tmx", "tsx", "xml", "tx" }.Contains(extension))
type = FileType.Xml;
else if (new[] { "tmj", "tsj", "json", "tj", "tiled-project" }.Contains(extension))
type = FileType.Json;
else
{
using var file = FileAccess.Open(checkedFile, FileAccess.ModeFlags.Read);
var chunk = System.Text.Encoding.UTF8.GetString(file.GetBuffer(12));
var chunk = System.Text.Encoding.UTF8.GetString(tiledFileContent, 0, 12);
if (chunk.StartsWith("<?xml "))
type = FileType.Xml;
else if (chunk.StartsWith("{ \""))
Expand All @@ -71,13 +60,12 @@ public static Dictionary GetDictionary(string sourceFile)
case FileType.Xml:
{
var dictBuilder = new DictionaryFromXml();
return dictBuilder.Create(checkedFile);
return dictBuilder.Create(tiledFileContent, sourceFile);
}
case FileType.Json:
{
var json = new Json();
using var file = FileAccess.Open(checkedFile, FileAccess.ModeFlags.Read);
if (json.Parse(file.GetAsText()) == Error.Ok)
if (json.Parse(System.Text.Encoding.UTF8.GetString(tiledFileContent)) == Error.Ok)
return (Dictionary)json.Data;
break;
}
Expand All @@ -89,4 +77,4 @@ public static Dictionary GetDictionary(string sourceFile)
return null;
}
}
#endif
#endif
6 changes: 3 additions & 3 deletions CSharp/addons/YATI/DictionaryFromXml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,13 @@ public class DictionaryFromXml
private bool _isMap;
private bool _inTileset;

public Dictionary Create(string sourceFileName)
public Dictionary Create(byte[] tiledFileContent, string sourceFileName)
{
_ci.NumberFormat.NumberDecimalSeparator = ".";

_xml = new XmlParserCtrl();

var err = _xml.Open(sourceFileName);
var err = _xml.Open(tiledFileContent, sourceFileName);
if (err != Error.Ok) return null;

_currentElement = _xml.NextElement();
Expand Down Expand Up @@ -284,4 +284,4 @@ private void InsertAttributes(Dictionary targetDictionary, Dictionary<string, st
}
}
}
#endif
#endif
18 changes: 12 additions & 6 deletions CSharp/addons/YATI/Importer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,14 @@ public partial class Importer: EditorImportPlugin

public override string _GetVisibleName() => "Import from Tiled";

public override string[] _GetRecognizedExtensions() => new [] { "tmx", "tmj" };
public override string[] _GetRecognizedExtensions() => new[] { "tmx", "tmj" };

public override string _GetResourceType() => "PackedScene";

public override string _GetSaveExtension() => "tscn";

public override float _GetPriority() => 0.1f;

public override int _GetPresetCount() => 0;

public override string _GetPresetName(int presetIndex) => "";
Expand All @@ -63,7 +63,7 @@ public override Array<Dictionary> _GetImportOptions(string path, int presetIndex
{ "property_hint", (int)PropertyHint.SaveFile }, { "hint_string", "*.tres;Resource File" } }
};
}

public override int _GetImportOrder() => 99;

public override bool _GetOptionVisibility(string path, StringName optionName, Dictionary options) => true;
Expand All @@ -83,6 +83,9 @@ Array<string> genFiles
return Error.FileNotFound;
}

CommonUtils.ErrorCount = 0;
CommonUtils.WarningCount = 0;

CustomTypes ct = null;
var tilemapCreator = new TilemapCreator();
if ((string)options["use_default_filter"] == "true")
Expand All @@ -103,6 +106,7 @@ Array<string> genFiles
ct.LoadCustomTypes((string)options["tiled_project_file"]);
tilemapCreator.SetCustomTypes(ct);
}

if (options.ContainsKey("save_tileset_to") && (string)options["save_tileset_to"] != "")
{
tilemapCreator.SetSaveTilesetTo((string)options["save_tileset_to"]);
Expand All @@ -112,8 +116,8 @@ Array<string> genFiles
if (node2D == null)
return Error.Failed;

var errors = tilemapCreator.GetErrorCount();
var warnings = tilemapCreator.GetWarningCount();
var errors = CommonUtils.ErrorCount;
var warnings = CommonUtils.WarningCount;

var postProcError = false;
if (options.ContainsKey("post_processor") && (string)options["post_processor"] != "")
Expand All @@ -122,7 +126,7 @@ Array<string> genFiles
node2D = postProc.CallPostProcess(node2D, (string)options["post_processor"]);
postProcError = postProc.GetError() != Error.Ok;
}

var packedScene = new PackedScene();
packedScene.Pack(node2D);
//return ResourceSaver.Save(packedScene, $"{sourceFile.GetBaseName()}.{_GetSaveExtension()}");
Expand Down Expand Up @@ -150,8 +154,10 @@ Array<string> genFiles
if (warnings > 1)
finalMessageString += "s";
}

finalMessageString += ".";
}

GD.Print(finalMessageString);
if (postProcError)
GD.Print("Postprocessing was skipped due to some error.");
Expand Down
7 changes: 5 additions & 2 deletions CSharp/addons/YATI/PostProcessing.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#if TOOLS
using System;
using Godot;

Expand All @@ -34,7 +35,7 @@ public Error GetError()
{
return _error;
}

public Node2D CallPostProcess(Node2D baseNode, string path)
{
var script = (CSharpScript)GD.Load(path);
Expand All @@ -44,6 +45,7 @@ public Node2D CallPostProcess(Node2D baseNode, string path)
_error = Error.FileUnrecognized;
return baseNode;
}

var scriptObj = (GodotObject)script.New();
try
{
Expand Down Expand Up @@ -75,4 +77,5 @@ public Node2D CallPostProcess(Node2D baseNode, string path)
return baseNode;
}
}
}
}
#endif
30 changes: 15 additions & 15 deletions CSharp/addons/YATI/TiledImport.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,22 +26,22 @@
namespace YATI;

[Tool]
public partial class TiledImport : EditorPlugin
public partial class TiledImport : EditorPlugin
{
private EditorImportPlugin _xmlImport;

public override string _GetPluginName() => "Yet another Tiled importer";

public override void _EnterTree()
{
_xmlImport = new Importer();
AddImportPlugin(_xmlImport);
}
private EditorImportPlugin _xmlImport;

public override void _ExitTree()
{
RemoveImportPlugin(_xmlImport);
_xmlImport = null;
}
public override string _GetPluginName() => "Yet another Tiled importer";

public override void _EnterTree()
{
_xmlImport = new Importer();
AddImportPlugin(_xmlImport);
}

public override void _ExitTree()
{
RemoveImportPlugin(_xmlImport);
_xmlImport = null;
}
}
#endif
Loading

0 comments on commit 7e09133

Please sign in to comment.