Skip to content

Commit

Permalink
Valkyrienyanko cleanup (#69)
Browse files Browse the repository at this point in the history
* Remove extra blank lines

* Simplify new() expressions

* Remove redundant ToString()'s

* Simplify using statements

* Mark methods that don't access instance as static

* Use Any() over Count() == 0 to improve performance

* Make .Where statement more readable

* Use Array.Empty for empty arrays (Performance)

* Simplify conditions

* Simplify default expressions

* Use char over string (Performance)

* Prefer explicit tuple names

* Simplify null checks

* update to 0.2.13 for code style updates

---------

Co-authored-by: valkyrienyanko <[email protected]>
  • Loading branch information
dogboydog and valkyrienyanko authored Sep 15, 2024
1 parent b12dac5 commit 526767b
Show file tree
Hide file tree
Showing 32 changed files with 181 additions and 245 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ 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/).

## [0.2.13] 2024-09-15
* General code cleanup by @valkyrienyanko. Make use of some C# language features such as target-typed `new()` to simplify code.
* Potential breaking change: DispatchCommandToNode on DialogueRunner has been marked static. Users generally do not need to call this method directly, so it shouldn't affect most or possibly any projects.

## [0.2.12] 2024-09-15
* Use file-scoped namespaces in all plugin scripts to reduce indentation, by @valkyrienyanko

Expand Down
4 changes: 2 additions & 2 deletions Samples/SQLiteVariableStorage/SQLVariableStorage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public override bool TryGetValue<T>(string variableName, out T result)
return true;
}

result = default(T);
result = default;
return false;
}

Expand Down Expand Up @@ -97,7 +97,7 @@ public override bool TryGetValue<T>(string variableName, out T result)
}

// otherwise TryGetValue has failed
result = default(T);
result = default;
return false;
}

Expand Down
12 changes: 6 additions & 6 deletions Samples/VisualNovel/Scripts/VisualNovelManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ private void OnDialogueComplete()
GD.Print("Visual novel sample has completed!");
}

private Dictionary<string, string> _bgShortNameToPath = new Dictionary<string, string>
private Dictionary<string, string> _bgShortNameToPath = new()
{
{
"bg_office", "res://Samples/VisualNovel/Sprites/bg_office.png"
Expand All @@ -97,7 +97,7 @@ public void Scene(string backgroundImage)
_background.Texture = texture;
}

private Dictionary<string, string> _audioShortNameToUuid = new Dictionary<string, string>
private Dictionary<string, string> _audioShortNameToUuid = new()
{
{
"music_funny", "res://Samples/VisualNovel/Sounds/music_funny.mp3"
Expand All @@ -110,7 +110,7 @@ public void Scene(string backgroundImage)
}
};

private List<AudioStreamPlayer2D> _audioPlayers = new List<AudioStreamPlayer2D>();
private List<AudioStreamPlayer2D> _audioPlayers = new();

private async void PlayAudio(string streamName, float volume = 1.0f, string doLoop = "loop")
{
Expand Down Expand Up @@ -141,9 +141,9 @@ private class Actor
public TextureRect Rect;
}

private Dictionary<string, Actor> _actors = new Dictionary<string, Actor>();
private Dictionary<string, Actor> _actors = new();

private Dictionary<string, string> _spriteShortNameToPath = new Dictionary<string, string>
private Dictionary<string, string> _spriteShortNameToPath = new()
{
{
"biz-guy", "res://Samples/VisualNovel/Sprites/biz-guy.png"
Expand All @@ -168,7 +168,7 @@ private Vector2 GetPosition(string coordinateX, string coordinateY)

// utility function to convert words like "left" or "right" into
// equivalent screen ratios, where 0 for an x coordinate is extreme left
private float GetCoordinate(string coordinate)
private static float GetCoordinate(string coordinate)
{
switch (coordinate)
{
Expand Down
11 changes: 4 additions & 7 deletions addons/YarnSpinner-Godot/Editor/YarnImporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public override Error _Import(
var saveErr = ResourceSaver.Save(importedMarkerResource, $"{savePath}.{_GetSaveExtension()}");
if (saveErr != Error.Ok)
{
GD.PrintErr($"Error saving yarn file import: {saveErr.ToString()}");
GD.PrintErr($"Error saving yarn file import: {saveErr}");
}

return (int) Error.Ok;
Expand All @@ -70,10 +70,8 @@ public override Error _Import(
/// <returns>The hash of <paramref name="inputString"/>.</returns>
private static byte[] GetHash(string inputString)
{
using (HashAlgorithm algorithm = SHA256.Create())
{
return algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString));
}
using HashAlgorithm algorithm = SHA256.Create();
return algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString));
}

/// <summary>
Expand Down Expand Up @@ -108,8 +106,7 @@ public static string GetHashString(string inputString, int limitCharacters = -1)
}
}


private void ImportYarn(string assetPath)
private static void ImportYarn(string assetPath)
{
GD.Print($"Importing Yarn script {assetPath}");
var projectPath = YarnProjectEditorUtility.GetDestinationProjectPath(assetPath);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using Godot;
using YarnSpinnerGodot.Editor.UI;


namespace YarnSpinnerGodot.Editor;

/// <summary>
Expand Down
36 changes: 15 additions & 21 deletions addons/YarnSpinner-Godot/Editor/YarnProjectEditorUtility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,10 @@ private static IEnumerable FindAllYarnProjects()
private const int PROJECT_UPDATE_TIMEOUT = 80; // ms

private static ConcurrentDictionary<string, DateTime> _projectPathToLastUpdateTime =
new ConcurrentDictionary<string, DateTime>();
new();

private static Dictionary<string, Task> _projectPathToUpdateTask = new Dictionary<string, Task>();
private static object _lastUpdateLock = new object();
private static Dictionary<string, Task> _projectPathToUpdateTask = new();
private static object _lastUpdateLock = new();

/// <summary>
/// Queue up a re-compile of scripts in a yarn project, add all associated data to the project,
Expand Down Expand Up @@ -412,7 +412,7 @@ public static void CompileAllScripts(YarnProject project)
{
lock (project)
{
List<FunctionInfo> newFunctionList = new List<FunctionInfo>();
List<FunctionInfo> newFunctionList = new();
var assetPath = project.ResourcePath;
GD.Print($"Compiling all scripts in {assetPath}");

Expand Down Expand Up @@ -447,7 +447,7 @@ public static void CompileAllScripts(YarnProject project)
errors = compilationResult.Value.Diagnostics.Where(d =>
d.Severity == Diagnostic.DiagnosticSeverity.Error);

if (errors.Count() > 0)
if (errors.Any())
{
var errorGroups = errors.GroupBy(e => e.FileName);
foreach (var errorGroup in errorGroups)
Expand Down Expand Up @@ -489,7 +489,7 @@ public static void CompileAllScripts(YarnProject project)
var newDeclarations = new List<Declaration>() //localDeclarations
.Concat(compilationResult.Value.Declarations)
.Where(decl => !decl.Name.StartsWith("$Yarn.Internal."))
.Where(decl => !(decl.Type is FunctionType))
.Where(decl => decl.Type is not FunctionType)
.Select(decl =>
{
SerializedDeclaration existingDeclaration = null;
Expand All @@ -514,15 +514,13 @@ public static void CompileAllScripts(YarnProject project)

CreateYarnInternalLocalizationAssets(project, compilationResult.Value);

using (var memoryStream = new MemoryStream())
using (var outputStream = new CodedOutputStream(memoryStream))
{
// Serialize the compiled program to memory
compilationResult.Value.Program.WriteTo(outputStream);
outputStream.Flush();
using var memoryStream = new MemoryStream();
using var outputStream = new CodedOutputStream(memoryStream);
// Serialize the compiled program to memory
compilationResult.Value.Program.WriteTo(outputStream);
outputStream.Flush();

compiledBytes = memoryStream.ToArray();
}
compiledBytes = memoryStream.ToArray();
}

project.ListOfFunctions = newFunctionList.ToArray();
Expand Down Expand Up @@ -614,7 +612,6 @@ public static FunctionInfo CreateFunctionInfoFromMethodGroup(MethodInfo method)
/// <seealso cref="assembliesToSearch"/>
public static bool searchAllAssembliesForActions = true;


private static void CreateYarnInternalLocalizationAssets(YarnProject project,
CompilationResult compilationResult)
{
Expand Down Expand Up @@ -678,7 +675,7 @@ public static IEnumerable<StringTableEntry> GenerateStringsTable(YarnProject pro
var errors =
compilationResult.Value.Diagnostics.Where(d => d.Severity == Diagnostic.DiagnosticSeverity.Error);

if (errors.Count() > 0)
if (errors.Any())
{
GD.PrintErr("Can't generate a strings table from a Yarn Project that contains compile errors", null);
return null;
Expand Down Expand Up @@ -755,15 +752,14 @@ private static string GenerateCommentWithLineMetadata(string[] metadata)
{
var cleanedMetadata = RemoveLineIDFromMetadata(metadata);

if (cleanedMetadata.Count() == 0)
if (!cleanedMetadata.Any())
{
return string.Empty;
}

return $"Line metadata: {string.Join(" ", cleanedMetadata)}";
}


/// <summary>
/// Removes any line ID entry from an array of line metadata.
/// Line metadata will always contain a line ID entry if it's set. For
Expand Down Expand Up @@ -823,9 +819,7 @@ public static void AddLineTagsToFilesInYarnProject(YarnProject project)
if (containsErrors)
{
GD.PrintErr($"Can't check for existing line tags in {path} because it contains errors.");
return new string[]
{
};
return Array.Empty<string>();
}

return result.StringTable.Where(i => i.Value.isImplicitTag == false).Select(i => i.Key);
Expand Down
2 changes: 1 addition & 1 deletion addons/YarnSpinner-Godot/Editor/YarnProjectImporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public override Error _Import(
var saveErr = ResourceSaver.Save(godotProject, godotProject.ImportPath);
if (saveErr != Error.Ok)
{
GD.PrintErr($"Error saving .yarnproject file import: {saveErr.ToString()}");
GD.PrintErr($"Error saving .yarnproject file import: {saveErr}");
}

YarnProjectEditorUtility.UpdateYarnProject(godotProject);
Expand Down
3 changes: 0 additions & 3 deletions addons/YarnSpinner-Godot/Editor/YarnProjectInspectorPlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
using Yarn.Compiler;
using YarnSpinnerGodot.Editor.UI;


namespace YarnSpinnerGodot.Editor;

[Tool]
Expand Down Expand Up @@ -251,7 +250,6 @@ public void CSVFileSelected(string savePath)
_project.SaveJSONProject();
}


private void LocaleAdded()
{
if (string.IsNullOrEmpty(_localeTextEntry.Text))
Expand Down Expand Up @@ -372,7 +370,6 @@ public override void _ParseBegin(GodotObject @object)
scriptPatternsGrid.AddChild(addPatternButton);
AddCustomControl(scriptPatternsGrid);


var numScriptsText = "None";
if (sourceScripts.Any())
{
Expand Down
22 changes: 6 additions & 16 deletions addons/YarnSpinner-Godot/Runtime/Commands/ActionManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
using Yarn;
using Node = Godot.Node;


namespace YarnSpinnerGodot;

using Injector = Func<string, object>;
Expand Down Expand Up @@ -228,20 +227,11 @@ private static string GetActionName(YarnActionAttribute metadata, MethodInfo met

private static void FindAllActions()
{
if (commands == null)
{
commands = new Dictionary<string, DispatchCommand>();
}
commands ??= new Dictionary<string, DispatchCommand>();

if (functions == null)
{
functions = new Dictionary<string, Delegate>();
}
functions ??= new Dictionary<string, Delegate>();

if (searchedAssemblyNames == null)
{
searchedAssemblyNames = new HashSet<string>();
}
searchedAssemblyNames ??= new HashSet<string>();
var injectorCache = new Dictionary<string, Injector>();

// Find the assemblies we're looking for
Expand Down Expand Up @@ -311,18 +301,18 @@ private static void FindAllActions()
/// <summary>
/// The Yarn commands that we have found.
/// </summary>
private static Dictionary<string, DispatchCommand> commands = new Dictionary<string, DispatchCommand>();
private static Dictionary<string, DispatchCommand> commands = new();

/// <summary>
/// The Yarn functions that we have found.
/// </summary>
private static Dictionary<string, Delegate> functions = new Dictionary<string, Delegate>();
private static Dictionary<string, Delegate> functions = new();

/// <summary>
/// A list of names of assemblies that we have searched for commands and
/// functions.
/// </summary>
private static HashSet<string> searchedAssemblyNames = new HashSet<string>();
private static HashSet<string> searchedAssemblyNames = new();

/// <summary>
/// Try to execute a command if it exists.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using System.Threading.Tasks;
using Godot;


namespace YarnSpinnerGodot;

public partial class DefaultActions : Godot.Node
Expand Down
3 changes: 1 addition & 2 deletions addons/YarnSpinner-Godot/Runtime/Commands/DispatchCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using System.Reflection;
using Godot;


namespace YarnSpinnerGodot;

using Injector = Func<string, object>;
Expand Down Expand Up @@ -33,7 +32,7 @@ public bool TryInvoke(string[] args, out object returnValue)
}
catch (Exception e) when (
e is ArgumentException // when arguments are invalid
|| e is TargetException // when a method is not static, but the instance ended up null
or TargetException // when a method is not static, but the instance ended up null
)
{
GD.PrintErr($"Can't run command {args[0]}: {e.Message}");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System;
#nullable disable


namespace YarnSpinnerGodot;

[AttributeUsage(AttributeTargets.Method, Inherited = false)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using System;
using Yarn;


namespace YarnSpinnerGodot;

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
#nullable disable
using System;


namespace YarnSpinnerGodot;

/// <summary>
Expand Down
Loading

0 comments on commit 526767b

Please sign in to comment.