From 59af00c89ae71e6ca2c35676cb176a2839536b7c Mon Sep 17 00:00:00 2001 From: Ellpeck Date: Wed, 15 Jun 2022 11:38:11 +0200 Subject: [PATCH] Code cleanup, and marked AStar.InfiniteCost as obsolete --- CHANGELOG.md | 3 + Demos.Android/Activity1.cs | 3 +- Demos/AnimationDemo.cs | 2 +- Demos/AutoTilingDemo.cs | 10 +- Demos/Content/Fonts/MonospacedFont.spritefont | 102 ++++++++-------- Demos/Content/Fonts/TestFont.spritefont | 102 ++++++++-------- Demos/Content/Fonts/TestFontBold.spritefont | 102 ++++++++-------- Demos/Content/Fonts/TestFontItalic.spritefont | 102 ++++++++-------- Demos/EasingsDemo.cs | 10 +- Demos/GameImpl.cs | 16 +-- Demos/PathfindingDemo.cs | 4 +- Demos/UiDemo.cs | 19 +-- MLEM.Data/Content/RawContentManager.cs | 6 +- MLEM.Data/ContentExtensions.cs | 8 +- MLEM.Data/CopyExtensions.cs | 18 +-- MLEM.Data/DynamicEnum.cs | 64 +++++----- MLEM.Data/Json/JsonConverters.cs | 2 +- MLEM.Data/Json/StaticJsonConverter.cs | 2 +- MLEM.Data/RuntimeTexturePacker.cs | 6 +- .../Tiled/IndividualTiledMapRenderer.cs | 4 +- MLEM.Extended/Tiled/LayerPosition.cs | 8 +- MLEM.Extended/Tiled/LayerPositionF.cs | 8 +- MLEM.Extended/Tiled/TiledExtensions.cs | 11 +- MLEM.Extended/Tiled/TiledMapCollisions.cs | 2 +- MLEM.Startup/MlemGame.cs | 6 +- MLEM.Ui/Elements/Element.cs | 4 +- MLEM.Ui/Elements/ElementHelper.cs | 6 +- MLEM.Ui/Elements/Panel.cs | 6 +- MLEM.Ui/Elements/Paragraph.cs | 4 +- MLEM.Ui/Elements/ScrollBar.cs | 4 +- MLEM.Ui/Elements/SquishingGroup.cs | 4 +- MLEM.Ui/Elements/TextField.cs | 2 +- MLEM.Ui/Parsers/UiMarkdownParser.cs | 8 +- MLEM/Cameras/Camera.cs | 2 +- MLEM/Extensions/CharExtensions.cs | 4 +- MLEM/Extensions/ColorExtensions.cs | 6 +- MLEM/Extensions/GraphicsExtensions.cs | 10 +- MLEM/Extensions/SpriteBatchExtensions.cs | 18 +-- MLEM/Font/GenericFont.cs | 12 +- MLEM/Font/GenericSpriteFont.cs | 6 +- MLEM/Formatting/TextFormatter.cs | 6 +- MLEM/Formatting/TokenizedString.cs | 6 +- MLEM/Graphics/AutoTiling.cs | 8 +- MLEM/Graphics/StaticSpriteBatch.cs | 20 ++-- MLEM/Input/GenericInput.cs | 2 +- MLEM/Input/InputHandler.cs | 4 +- MLEM/Input/Keybind.cs | 8 +- MLEM/Input/KeysExtensions.cs | 12 +- MLEM/Misc/Direction2.cs | 113 +++++++++--------- MLEM/Misc/Easings.cs | 4 +- MLEM/Misc/EnumHelper.cs | 4 +- MLEM/Misc/MlemPlatform.cs | 2 +- MLEM/Misc/Padding.cs | 6 +- MLEM/Misc/RectangleF.cs | 2 +- MLEM/Pathfinding/AStar.cs | 7 +- MLEM/Pathfinding/AStar2.cs | 2 +- MLEM/Pathfinding/AStar3.cs | 4 +- MLEM/Sound/SoundEffectInfo.cs | 2 +- Sandbox/Content/Fonts/TestFont.spritefont | 102 ++++++++-------- Sandbox/GameImpl.cs | 12 +- Tests/DataTests.cs | 41 ++++--- Tests/DirectionTests.cs | 53 ++++---- Tests/PathfindingTests.cs | 14 +-- Tests/TestGame.cs | 2 +- Tests/TexturePackerTests.cs | 12 +- 65 files changed, 584 insertions(+), 580 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c0bd88e..434a040 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,9 @@ Improvements - Allow comparing Keybind and Combination based on the amount of modifiers they have - Allow using multiple textures in a StaticSpriteBatch +Removals +- Marked AStar.InfiniteCost as obsolete + ### MLEM.Ui Additions - Added Element.AutoNavGroup which allows forming groups for auto-navigation diff --git a/Demos.Android/Activity1.cs b/Demos.Android/Activity1.cs index 4f4265c..d9d46b8 100644 --- a/Demos.Android/Activity1.cs +++ b/Demos.Android/Activity1.cs @@ -8,7 +8,6 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using MLEM.Extensions; using MLEM.Misc; -using static Android.Views.SystemUiFlags; namespace Demos.Android { [Activity( @@ -48,7 +47,7 @@ namespace Demos.Android { base.OnWindowFocusChanged(hasFocus); // hide the status bar if (hasFocus) - this.Window.DecorView.SystemUiVisibility = (StatusBarVisibility) (ImmersiveSticky | LayoutStable | LayoutHideNavigation | LayoutFullscreen | HideNavigation | Fullscreen); + this.Window.DecorView.SystemUiVisibility = (StatusBarVisibility) (SystemUiFlags.ImmersiveSticky | SystemUiFlags.LayoutStable | SystemUiFlags.LayoutHideNavigation | SystemUiFlags.LayoutFullscreen | SystemUiFlags.HideNavigation | SystemUiFlags.Fullscreen); } } diff --git a/Demos/AnimationDemo.cs b/Demos/AnimationDemo.cs index 0d35462..d8119a4 100644 --- a/Demos/AnimationDemo.cs +++ b/Demos/AnimationDemo.cs @@ -27,7 +27,7 @@ namespace Demos { // using it having wrong coordinates and/or sizes // the regions that are part of the atlas are then referenced by region coordinates rather than texture coordinates // (as seen below) - var atlas = new UniformTextureAtlas(LoadContent("Textures/Anim"), 4, 4); + var atlas = new UniformTextureAtlas(Demo.LoadContent("Textures/Anim"), 4, 4); // create the four animations by supplying the time per frame, and the four regions used // note that you don't need to use a texture atlas for this, you can also simply supply the texture and the regions manually here diff --git a/Demos/AutoTilingDemo.cs b/Demos/AutoTilingDemo.cs index b1cf759..a4811f2 100644 --- a/Demos/AutoTilingDemo.cs +++ b/Demos/AutoTilingDemo.cs @@ -20,7 +20,7 @@ namespace Demos { public override void LoadContent() { base.LoadContent(); // The layout of the texture is important for auto tiling to work correctly, and is explained in the XML docs for the methods used - this.texture = LoadContent("Textures/AutoTiling"); + this.texture = Demo.LoadContent("Textures/AutoTiling"); // in this example, a simple string array is used for layout purposes. As the AutoTiling method allows any kind of // comparison, the actual implementation can vary (for instance, based on a more in-depth tile map) @@ -59,12 +59,12 @@ namespace Demos { } // the texture region supplied to the AutoTiling method should only encompass the first filler tile's location and size - AutoTiling.DrawAutoTile(this.SpriteBatch, new Vector2(x + 1, y + 1) * TileSize, new TextureRegion(this.texture, 0, 0, TileSize, TileSize), ConnectsTo, Color.White); + AutoTiling.DrawAutoTile(this.SpriteBatch, new Vector2(x + 1, y + 1) * AutoTilingDemo.TileSize, new TextureRegion(this.texture, 0, 0, AutoTilingDemo.TileSize, AutoTilingDemo.TileSize), ConnectsTo, Color.White); // when drawing extended auto-tiles, the same rules apply, but the source texture layout is different - var background = new TextureRegion(this.texture, 0, TileSize * 2, TileSize, TileSize); - var overlay = new TextureRegion(this.texture, background.Area.OffsetCopy(new Point(TileSize, 0))); - AutoTiling.DrawExtendedAutoTile(this.SpriteBatch, new Vector2(x + 8, y + 1) * TileSize, background, overlay, ConnectsTo, Color.White, Color.White); + var background = new TextureRegion(this.texture, 0, AutoTilingDemo.TileSize * 2, AutoTilingDemo.TileSize, AutoTilingDemo.TileSize); + var overlay = new TextureRegion(this.texture, background.Area.OffsetCopy(new Point(AutoTilingDemo.TileSize, 0))); + AutoTiling.DrawExtendedAutoTile(this.SpriteBatch, new Vector2(x + 8, y + 1) * AutoTilingDemo.TileSize, background, overlay, ConnectsTo, Color.White, Color.White); } } this.SpriteBatch.End(); diff --git a/Demos/Content/Fonts/MonospacedFont.spritefont b/Demos/Content/Fonts/MonospacedFont.spritefont index 30c7588..008313f 100644 --- a/Demos/Content/Fonts/MonospacedFont.spritefont +++ b/Demos/Content/Fonts/MonospacedFont.spritefont @@ -6,55 +6,55 @@ of the font in your game, and to change the characters which are available to dr with. --> - - - - JetBrainsMono-Regular.ttf - - - 32 - - - 0 - - - true - - - - - - * - - - - - - ɏ - - - + + + + JetBrainsMono-Regular.ttf + + + 32 + + + 0 + + + true + + + + + + * + + + + + + ɏ + + + diff --git a/Demos/Content/Fonts/TestFont.spritefont b/Demos/Content/Fonts/TestFont.spritefont index 85713ad..1a71ef6 100644 --- a/Demos/Content/Fonts/TestFont.spritefont +++ b/Demos/Content/Fonts/TestFont.spritefont @@ -6,55 +6,55 @@ of the font in your game, and to change the characters which are available to dr with. --> - - - - CAYETANO.ttf - - - 32 - - - 0 - - - true - - - - - - * - - - - - - ɏ - - - + + + + CAYETANO.ttf + + + 32 + + + 0 + + + true + + + + + + * + + + + + + ɏ + + + diff --git a/Demos/Content/Fonts/TestFontBold.spritefont b/Demos/Content/Fonts/TestFontBold.spritefont index f7e7a1b..b9db902 100644 --- a/Demos/Content/Fonts/TestFontBold.spritefont +++ b/Demos/Content/Fonts/TestFontBold.spritefont @@ -6,55 +6,55 @@ of the font in your game, and to change the characters which are available to dr with. --> - - - - CAYTANOB - - - 32 - - - 0 - - - true - - - - - - * - - - - - - ɏ - - - + + + + CAYTANOB + + + 32 + + + 0 + + + true + + + + + + * + + + + + + ɏ + + + diff --git a/Demos/Content/Fonts/TestFontItalic.spritefont b/Demos/Content/Fonts/TestFontItalic.spritefont index 4048f51..b9ca1b2 100644 --- a/Demos/Content/Fonts/TestFontItalic.spritefont +++ b/Demos/Content/Fonts/TestFontItalic.spritefont @@ -6,55 +6,55 @@ of the font in your game, and to change the characters which are available to dr with. --> - - - - CAYETANI - - - 32 - - - 0 - - - true - - - - - - * - - - - - - ɏ - - - + + + + CAYETANI + + + 32 + + + 0 + + + true + + + + + + * + + + + + + ɏ + + + diff --git a/Demos/EasingsDemo.cs b/Demos/EasingsDemo.cs index 2b8005d..aa67a52 100644 --- a/Demos/EasingsDemo.cs +++ b/Demos/EasingsDemo.cs @@ -13,7 +13,7 @@ namespace Demos { private static readonly FieldInfo[] EasingFields = typeof(Easings) .GetFields(BindingFlags.Public | BindingFlags.Static).ToArray(); - private static readonly Easings.Easing[] Easings = EasingFields + private static readonly Easings.Easing[] Easings = EasingsDemo.EasingFields .Select(f => (Easings.Easing) f.GetValue(null)).ToArray(); private Group group; private int current; @@ -27,11 +27,11 @@ namespace Demos { this.group = new Group(Anchor.TopCenter, Vector2.One) {CanBeMoused = false}; this.group.AddChild(new Button(Anchor.AutoCenter, new Vector2(30, 10), "Next") { OnPressed = e => { - this.current = (this.current + 1) % Easings.Length; + this.current = (this.current + 1) % EasingsDemo.Easings.Length; this.progress = 0; } }); - this.group.AddChild(new Paragraph(Anchor.AutoCenter, 1, p => EasingFields[this.current].Name, true)); + this.group.AddChild(new Paragraph(Anchor.AutoCenter, 1, p => EasingsDemo.EasingFields[this.current].Name, true)); this.UiRoot.AddChild(this.group); } @@ -47,7 +47,7 @@ namespace Demos { var view = this.GraphicsDevice.Viewport; // graph the easing function - var graphEase = Easings[this.current].ScaleInput(0, view.Width).ScaleOutput(-view.Height / 3, view.Height / 3); + var graphEase = EasingsDemo.Easings[this.current].ScaleInput(0, view.Width).ScaleOutput(-view.Height / 3, view.Height / 3); for (var x = 0; x < view.Width; x++) { var area = new RectangleF(x - 2, view.Height / 2 - graphEase(x) - 2, 4, 4); this.SpriteBatch.Draw(this.SpriteBatch.GetBlankTexture(), area, Color.Green); @@ -55,7 +55,7 @@ namespace Demos { // draw a little dot to show what it would look like this.progress = (this.progress + (float) time.ElapsedGameTime.TotalSeconds / 2) % 1; - var dotEase = Easings[this.current].AndReverse().ScaleOutput(0, view.Height / 4); + var dotEase = EasingsDemo.Easings[this.current].AndReverse().ScaleOutput(0, view.Height / 4); var pos = new RectangleF(view.Width / 2 - 4, view.Height - 20 - dotEase(this.progress), 8, 8); this.SpriteBatch.Draw(this.SpriteBatch.GetBlankTexture(), pos, Color.Red); diff --git a/Demos/GameImpl.cs b/Demos/GameImpl.cs index 983113f..e62b9c4 100644 --- a/Demos/GameImpl.cs +++ b/Demos/GameImpl.cs @@ -23,11 +23,11 @@ namespace Demos { private TimeSpan secondCounter; static GameImpl() { - Demos.Add("Ui", ("An in-depth demonstration of the MLEM.Ui package and its abilities", game => new UiDemo(game))); - Demos.Add("Easings", ("An example of MLEM's Easings class, an adaptation of easings.net", game => new EasingsDemo(game))); - Demos.Add("Pathfinding", ("An example of MLEM's A* pathfinding implementation in 2D", game => new PathfindingDemo(game))); - Demos.Add("Animation and Texture Atlas", ("An example of UniformTextureAtlases, SpriteAnimations and SpriteAnimationGroups", game => new AnimationDemo(game))); - Demos.Add("Auto Tiling", ("A demonstration of the AutoTiling class that MLEM provides", game => new AutoTilingDemo(game))); + GameImpl.Demos.Add("Ui", ("An in-depth demonstration of the MLEM.Ui package and its abilities", game => new UiDemo(game))); + GameImpl.Demos.Add("Easings", ("An example of MLEM's Easings class, an adaptation of easings.net", game => new EasingsDemo(game))); + GameImpl.Demos.Add("Pathfinding", ("An example of MLEM's A* pathfinding implementation in 2D", game => new PathfindingDemo(game))); + GameImpl.Demos.Add("Animation and Texture Atlas", ("An example of UniformTextureAtlases, SpriteAnimations and SpriteAnimationGroups", game => new AnimationDemo(game))); + GameImpl.Demos.Add("Auto Tiling", ("A demonstration of the AutoTiling class that MLEM provides", game => new AutoTilingDemo(game))); } public GameImpl() { @@ -74,7 +74,7 @@ namespace Demos { selection.AddChild(new Paragraph(Anchor.AutoLeft, 1, "Select the demo you want to see below using your mouse, touch input, your keyboard or a controller. Check the demos' source code for more in-depth explanations of their functionality or the website for tutorials and API documentation.")); selection.AddChild(new VerticalSpace(5)); - foreach (var demo in Demos) { + foreach (var demo in GameImpl.Demos) { selection.AddChild(new Button(Anchor.AutoCenter, new Vector2(1, 10), demo.Key, demo.Value.Item1) { OnPressed = e => { selection.IsHidden = true; @@ -92,9 +92,9 @@ namespace Demos { } protected override UiStyle InitializeDefaultUiStyle(SpriteBatch batch) { - var tex = LoadContent("Textures/Test"); + var tex = MlemGame.LoadContent("Textures/Test"); return new UntexturedStyle(this.SpriteBatch) { - Font = new GenericSpriteFont(LoadContent("Fonts/TestFont")), + Font = new GenericSpriteFont(MlemGame.LoadContent("Fonts/TestFont")), TextScale = 0.1F, PanelTexture = new NinePatch(new TextureRegion(tex, 0, 8, 24, 24), 8), ButtonTexture = new NinePatch(new TextureRegion(tex, 24, 8, 16, 16), 4), diff --git a/Demos/PathfindingDemo.cs b/Demos/PathfindingDemo.cs index 04ba7ef..6b34441 100644 --- a/Demos/PathfindingDemo.cs +++ b/Demos/PathfindingDemo.cs @@ -41,8 +41,8 @@ namespace Demos { // pathfinder's constructor float Cost(Point pos, Point nextPos) { if (nextPos.X < 0 || nextPos.Y < 0 || nextPos.X >= 50 || nextPos.Y >= 50) - return AStar2.InfiniteCost; - return this.world[nextPos.X, nextPos.Y] ? 1 : AStar2.InfiniteCost; + return float.PositiveInfinity; + return this.world[nextPos.X, nextPos.Y] ? 1 : float.PositiveInfinity; } // Actually initialize the pathfinder with the cost function, as well as specify if moving diagonally between tiles should be diff --git a/Demos/UiDemo.cs b/Demos/UiDemo.cs index 861e621..0ac2573 100644 --- a/Demos/UiDemo.cs +++ b/Demos/UiDemo.cs @@ -28,7 +28,7 @@ namespace Demos { public UiDemo(MlemGame game) : base(game) {} public override void LoadContent() { - this.testTexture = LoadContent("Textures/Test"); + this.testTexture = Demo.LoadContent("Textures/Test"); this.testPatch = new NinePatch(new TextureRegion(this.testTexture, 0, 8, 24, 24), 8); base.LoadContent(); @@ -38,7 +38,10 @@ namespace Demos { // when using a SpriteFont, use GenericSpriteFont. When using a MonoGame.Extended BitmapFont, use GenericBitmapFont. // Wrapping fonts like this allows for both types to be usable within MLEM.Ui easily // Supplying a bold and an italic version is optional - Font = new GenericSpriteFont(LoadContent("Fonts/TestFont"), LoadContent("Fonts/TestFontBold"), LoadContent("Fonts/TestFontItalic")), + Font = new GenericSpriteFont( + Demo.LoadContent("Fonts/TestFont"), + Demo.LoadContent("Fonts/TestFontBold"), + Demo.LoadContent("Fonts/TestFontItalic")), TextScale = 0.1F, PanelTexture = this.testPatch, ButtonTexture = new NinePatch(new TextureRegion(this.testTexture, 24, 8, 16, 16), 4), @@ -49,7 +52,7 @@ namespace Demos { CheckboxCheckmark = new TextureRegion(this.testTexture, 24, 0, 8, 8), RadioTexture = new NinePatch(new TextureRegion(this.testTexture, 16, 0, 8, 8), 3), RadioCheckmark = new TextureRegion(this.testTexture, 32, 0, 8, 8), - AdditionalFonts = {{"Monospaced", new GenericSpriteFont(LoadContent("Fonts/MonospacedFont"))}}, + AdditionalFonts = {{"Monospaced", new GenericSpriteFont(Demo.LoadContent("Fonts/MonospacedFont"))}}, LinkColor = Color.CornflowerBlue }; var untexturedStyle = new UntexturedStyle(this.SpriteBatch) { @@ -158,7 +161,7 @@ namespace Demos { // Check the WobbleButton method for an explanation of how this button works this.root.AddChild(new Button(Anchor.AutoCenter, new Vector2(0.5F, 10), "Wobble Me", "This button wobbles around visually when clicked, but this doesn't affect its actual size and positioning") { - OnPressed = element => CoroutineHandler.Start(WobbleButton(element)), + OnPressed = element => CoroutineHandler.Start(UiDemo.WobbleButton(element)), PositionOffset = new Vector2(0, 1) }); // Another button that shows animations! @@ -191,13 +194,13 @@ namespace Demos { this.root.AddChild(new VerticalSpace(3)); this.root.AddChild(new Paragraph(Anchor.AutoLeft, 1, "Progress bars!")); var bar1 = this.root.AddChild(new ProgressBar(Anchor.AutoLeft, new Vector2(1, 8), Direction2.Right, 10) {PositionOffset = new Vector2(0, 1)}); - CoroutineHandler.Start(WobbleProgressBar(bar1)); + CoroutineHandler.Start(UiDemo.WobbleProgressBar(bar1)); var bar2 = this.root.AddChild(new ProgressBar(Anchor.AutoLeft, new Vector2(1, 8), Direction2.Left, 10) {PositionOffset = new Vector2(0, 1)}); - CoroutineHandler.Start(WobbleProgressBar(bar2)); + CoroutineHandler.Start(UiDemo.WobbleProgressBar(bar2)); var bar3 = this.root.AddChild(new ProgressBar(Anchor.AutoLeft, new Vector2(8, 30), Direction2.Down, 10) {PositionOffset = new Vector2(0, 1)}); - CoroutineHandler.Start(WobbleProgressBar(bar3)); + CoroutineHandler.Start(UiDemo.WobbleProgressBar(bar3)); var bar4 = this.root.AddChild(new ProgressBar(Anchor.AutoInline, new Vector2(8, 30), Direction2.Up, 10) {PositionOffset = new Vector2(1, 0)}); - CoroutineHandler.Start(WobbleProgressBar(bar4)); + CoroutineHandler.Start(UiDemo.WobbleProgressBar(bar4)); this.root.AddChild(new VerticalSpace(3)); var dropdown = this.root.AddChild(new Dropdown(Anchor.AutoLeft, new Vector2(1, 10), "Dropdown Menu")); diff --git a/MLEM.Data/Content/RawContentManager.cs b/MLEM.Data/Content/RawContentManager.cs index 0f8e38d..a4c8b63 100644 --- a/MLEM.Data/Content/RawContentManager.cs +++ b/MLEM.Data/Content/RawContentManager.cs @@ -56,9 +56,9 @@ namespace MLEM.Data.Content { private T Read(string assetName, T existing) { var triedFiles = new List(); - if (readers == null) - readers = CollectContentReaders(); - foreach (var reader in readers) { + if (RawContentManager.readers == null) + RawContentManager.readers = RawContentManager.CollectContentReaders(); + foreach (var reader in RawContentManager.readers) { if (!reader.CanRead(typeof(T))) continue; foreach (var ext in reader.GetFileExtensions()) { diff --git a/MLEM.Data/ContentExtensions.cs b/MLEM.Data/ContentExtensions.cs index 68fea1d..f4b2801 100644 --- a/MLEM.Data/ContentExtensions.cs +++ b/MLEM.Data/ContentExtensions.cs @@ -21,7 +21,7 @@ namespace MLEM.Data { /// The content manager to add the json serializer to /// The json serializer to add public static void SetJsonSerializer(this ContentManager content, JsonSerializer serializer) { - Serializers[content] = serializer; + ContentExtensions.Serializers[content] = serializer; } /// @@ -31,7 +31,7 @@ namespace MLEM.Data { /// The content manager whose serializer to get /// The content manager's serializer public static JsonSerializer GetJsonSerializer(this ContentManager content) { - if (!Serializers.TryGetValue(content, out var serializer)) { + if (!ContentExtensions.Serializers.TryGetValue(content, out var serializer)) { serializer = JsonConverters.AddAll(new JsonSerializer()); content.SetJsonSerializer(serializer); } @@ -44,7 +44,7 @@ namespace MLEM.Data { /// The content manager to add the converter to /// The converter to add public static void AddJsonConverter(this ContentManager content, JsonConverter converter) { - var serializer = GetJsonSerializer(content); + var serializer = content.GetJsonSerializer(); serializer.Converters.Add(converter); } @@ -60,7 +60,7 @@ namespace MLEM.Data { public static T LoadJson(this ContentManager content, string name, string[] extensions = null, JsonSerializer serializer = null) { var triedFiles = new List(); var serializerToUse = serializer ?? content.GetJsonSerializer(); - foreach (var extension in extensions ?? JsonExtensions) { + foreach (var extension in extensions ?? ContentExtensions.JsonExtensions) { var file = Path.Combine(content.RootDirectory, name + extension); triedFiles.Add(file); try { diff --git a/MLEM.Data/CopyExtensions.cs b/MLEM.Data/CopyExtensions.cs index 0ab79a4..0c28f8a 100644 --- a/MLEM.Data/CopyExtensions.cs +++ b/MLEM.Data/CopyExtensions.cs @@ -23,8 +23,8 @@ namespace MLEM.Data { /// The type of the object to copy /// A shallow copy of the object [Obsolete("CopyExtensions has major flaws and insufficient speed compared to other libraries specifically designed for copying objects.")] - public static T Copy(this T obj, BindingFlags flags = DefaultFlags, Predicate fieldInclusion = null) { - var copy = (T) Construct(typeof(T), flags); + public static T Copy(this T obj, BindingFlags flags = CopyExtensions.DefaultFlags, Predicate fieldInclusion = null) { + var copy = (T) CopyExtensions.Construct(typeof(T), flags); obj.CopyInto(copy, flags, fieldInclusion); return copy; } @@ -39,8 +39,8 @@ namespace MLEM.Data { /// The type of the object to copy /// A deep copy of the object [Obsolete("CopyExtensions has major flaws and insufficient speed compared to other libraries specifically designed for copying objects.")] - public static T DeepCopy(this T obj, BindingFlags flags = DefaultFlags, Predicate fieldInclusion = null) { - var copy = (T) Construct(typeof(T), flags); + public static T DeepCopy(this T obj, BindingFlags flags = CopyExtensions.DefaultFlags, Predicate fieldInclusion = null) { + var copy = (T) CopyExtensions.Construct(typeof(T), flags); obj.DeepCopyInto(copy, flags, fieldInclusion); return copy; } @@ -54,7 +54,7 @@ namespace MLEM.Data { /// A predicate that determines whether or not the given field should be copied. If null, all fields will be copied. /// The type of the object to copy [Obsolete("CopyExtensions has major flaws and insufficient speed compared to other libraries specifically designed for copying objects.")] - public static void CopyInto(this T obj, T otherObj, BindingFlags flags = DefaultFlags, Predicate fieldInclusion = null) { + public static void CopyInto(this T obj, T otherObj, BindingFlags flags = CopyExtensions.DefaultFlags, Predicate fieldInclusion = null) { foreach (var field in typeof(T).GetFields(flags)) { if (fieldInclusion == null || fieldInclusion(field)) field.SetValue(otherObj, field.GetValue(obj)); @@ -71,7 +71,7 @@ namespace MLEM.Data { /// A predicate that determines whether or not the given field should be copied. If null, all fields will be copied. /// The type of the object to copy [Obsolete("CopyExtensions has major flaws and insufficient speed compared to other libraries specifically designed for copying objects.")] - public static void DeepCopyInto(this T obj, T otherObj, BindingFlags flags = DefaultFlags, Predicate fieldInclusion = null) { + public static void DeepCopyInto(this T obj, T otherObj, BindingFlags flags = CopyExtensions.DefaultFlags, Predicate fieldInclusion = null) { foreach (var field in obj.GetType().GetFields(flags)) { if (fieldInclusion != null && !fieldInclusion(field)) continue; @@ -83,7 +83,7 @@ namespace MLEM.Data { var otherVal = field.GetValue(otherObj); // if the object we want to copy into doesn't have a value yet, we create one if (otherVal == null) { - otherVal = Construct(field.FieldType, flags); + otherVal = CopyExtensions.Construct(field.FieldType, flags); field.SetValue(otherObj, otherVal); } val.DeepCopyInto(otherVal, flags); @@ -92,7 +92,7 @@ namespace MLEM.Data { } private static object Construct(Type t, BindingFlags flags) { - if (!ConstructorCache.TryGetValue(t, out var constructor)) { + if (!CopyExtensions.ConstructorCache.TryGetValue(t, out var constructor)) { var constructors = t.GetConstructors(flags); // find a contructor with the correct attribute constructor = constructors.FirstOrDefault(c => c.GetCustomAttribute() != null); @@ -104,7 +104,7 @@ namespace MLEM.Data { constructor = constructors.FirstOrDefault(); if (constructor == null) throw new NullReferenceException($"Type {t} does not have a constructor with the required visibility"); - ConstructorCache.Add(t, constructor); + CopyExtensions.ConstructorCache.Add(t, constructor); } return constructor.Invoke(new object[constructor.GetParameters().Length]); } diff --git a/MLEM.Data/DynamicEnum.cs b/MLEM.Data/DynamicEnum.cs index e332881..789bfa8 100644 --- a/MLEM.Data/DynamicEnum.cs +++ b/MLEM.Data/DynamicEnum.cs @@ -60,7 +60,7 @@ namespace MLEM.Data { if (this.allFlagsCache == null) this.allFlagsCache = new Dictionary(); if (!this.allFlagsCache.TryGetValue(flags, out var ret)) { - ret = (GetValue(this) & GetValue(flags)) == GetValue(flags); + ret = (DynamicEnum.GetValue(this) & DynamicEnum.GetValue(flags)) == DynamicEnum.GetValue(flags); this.allFlagsCache.Add(flags, ret); } return ret; @@ -76,7 +76,7 @@ namespace MLEM.Data { if (this.anyFlagsCache == null) this.anyFlagsCache = new Dictionary(); if (!this.anyFlagsCache.TryGetValue(flags, out var ret)) { - ret = (GetValue(this) & GetValue(flags)) != 0; + ret = (DynamicEnum.GetValue(this) & DynamicEnum.GetValue(flags)) != 0; this.anyFlagsCache.Add(flags, ret); } return ret; @@ -87,13 +87,13 @@ namespace MLEM.Data { public override string ToString() { if (this.name == null) { var included = new List(); - if (GetValue(this) != 0) { - foreach (var v in GetValues(this.GetType())) { - if (this.HasFlag(v) && GetValue(v) != 0) + if (DynamicEnum.GetValue(this) != 0) { + foreach (var v in DynamicEnum.GetValues(this.GetType())) { + if (this.HasFlag(v) && DynamicEnum.GetValue(v) != 0) included.Add(v); } } - this.name = included.Count > 0 ? string.Join(" | ", included) : GetValue(this).ToString(); + this.name = included.Count > 0 ? string.Join(" | ", included) : DynamicEnum.GetValue(this).ToString(); } return this.name; } @@ -107,7 +107,7 @@ namespace MLEM.Data { /// The newly created enum value /// Thrown if the name or value passed are already present public static T Add(string name, BigInteger value) where T : DynamicEnum { - var storage = GetStorage(typeof(T)); + var storage = DynamicEnum.GetStorage(typeof(T)); // cached parsed values and names might be incomplete with new values storage.ClearCaches(); @@ -119,7 +119,7 @@ namespace MLEM.Data { throw new ArgumentException($"Duplicate name {name}", nameof(name)); } - var ret = Construct(typeof(T), name, value); + var ret = DynamicEnum.Construct(typeof(T), name, value); storage.Values.Add(value, ret); return (T) ret; } @@ -134,9 +134,9 @@ namespace MLEM.Data { /// The newly created enum value public static T AddValue(string name) where T : DynamicEnum { BigInteger value = 0; - while (GetStorage(typeof(T)).Values.ContainsKey(value)) + while (DynamicEnum.GetStorage(typeof(T)).Values.ContainsKey(value)) value++; - return Add(name, value); + return DynamicEnum.Add(name, value); } /// @@ -149,9 +149,9 @@ namespace MLEM.Data { /// The newly created enum value public static T AddFlag(string name) where T : DynamicEnum { BigInteger value = 1; - while (GetStorage(typeof(T)).Values.ContainsKey(value)) + while (DynamicEnum.GetStorage(typeof(T)).Values.ContainsKey(value)) value <<= 1; - return Add(name, value); + return DynamicEnum.Add(name, value); } /// @@ -161,7 +161,7 @@ namespace MLEM.Data { /// The type whose values to get /// The defined values for the given type public static IEnumerable GetValues() where T : DynamicEnum { - return GetValues(typeof(T)).Cast(); + return DynamicEnum.GetValues(typeof(T)).Cast(); } /// @@ -171,7 +171,7 @@ namespace MLEM.Data { /// The type whose values to get /// The defined values for the given type public static IEnumerable GetValues(Type type) { - return GetStorage(type).Values.Values; + return DynamicEnum.GetStorage(type).Values.Values; } /// @@ -182,9 +182,9 @@ namespace MLEM.Data { /// The type of the values /// The bitwise OR (|) combination public static T Or(T left, T right) where T : DynamicEnum { - var cache = GetStorage(typeof(T)).OrCache; + var cache = DynamicEnum.GetStorage(typeof(T)).OrCache; if (!cache.TryGetValue((left, right), out var ret)) { - ret = GetEnumValue(GetValue(left) | GetValue(right)); + ret = DynamicEnum.GetEnumValue(DynamicEnum.GetValue(left) | DynamicEnum.GetValue(right)); cache.Add((left, right), ret); } return (T) ret; @@ -198,9 +198,9 @@ namespace MLEM.Data { /// The type of the values /// The bitwise AND (&) combination public static T And(T left, T right) where T : DynamicEnum { - var cache = GetStorage(typeof(T)).AndCache; + var cache = DynamicEnum.GetStorage(typeof(T)).AndCache; if (!cache.TryGetValue((left, right), out var ret)) { - ret = GetEnumValue(GetValue(left) & GetValue(right)); + ret = DynamicEnum.GetEnumValue(DynamicEnum.GetValue(left) & DynamicEnum.GetValue(right)); cache.Add((left, right), ret); } return (T) ret; @@ -214,9 +214,9 @@ namespace MLEM.Data { /// The type of the values /// The bitwise XOR (^) combination public static T Xor(T left, T right) where T : DynamicEnum { - var cache = GetStorage(typeof(T)).XorCache; + var cache = DynamicEnum.GetStorage(typeof(T)).XorCache; if (!cache.TryGetValue((left, right), out var ret)) { - ret = GetEnumValue(GetValue(left) ^ GetValue(right)); + ret = DynamicEnum.GetEnumValue(DynamicEnum.GetValue(left) ^ DynamicEnum.GetValue(right)); cache.Add((left, right), ret); } return (T) ret; @@ -229,9 +229,9 @@ namespace MLEM.Data { /// The type of the values /// The bitwise NEG (~) value public static T Neg(T value) where T : DynamicEnum { - var cache = GetStorage(typeof(T)).NegCache; + var cache = DynamicEnum.GetStorage(typeof(T)).NegCache; if (!cache.TryGetValue(value, out var ret)) { - ret = GetEnumValue(~GetValue(value)); + ret = DynamicEnum.GetEnumValue(~DynamicEnum.GetValue(value)); cache.Add(value, ret); } return (T) ret; @@ -253,7 +253,7 @@ namespace MLEM.Data { /// The type that the returned dynamic enum should have /// The defined or combined dynamic enum value public static T GetEnumValue(BigInteger value) where T : DynamicEnum { - return (T) GetEnumValue(typeof(T), value); + return (T) DynamicEnum.GetEnumValue(typeof(T), value); } /// @@ -263,7 +263,7 @@ namespace MLEM.Data { /// The value whose dynamic enum value to get /// The defined or combined dynamic enum value public static DynamicEnum GetEnumValue(Type type, BigInteger value) { - var storage = GetStorage(type); + var storage = DynamicEnum.GetStorage(type); // get the defined value if it exists if (storage.Values.TryGetValue(value, out var defined)) @@ -271,7 +271,7 @@ namespace MLEM.Data { // otherwise, cache the combined value if (!storage.FlagCache.TryGetValue(value, out var combined)) { - combined = Construct(type, null, value); + combined = DynamicEnum.Construct(type, null, value); storage.FlagCache.Add(value, combined); } return combined; @@ -286,7 +286,7 @@ namespace MLEM.Data { /// The type of the dynamic enum value to parse /// The parsed enum value, or null if parsing fails public static T Parse(string strg) where T : DynamicEnum { - return (T) Parse(typeof(T), strg); + return (T) DynamicEnum.Parse(typeof(T), strg); } /// @@ -297,28 +297,28 @@ namespace MLEM.Data { /// The string to parse into a dynamic enum value /// The parsed enum value, or null if parsing fails public static DynamicEnum Parse(Type type, string strg) { - var cache = GetStorage(type).ParseCache; + var cache = DynamicEnum.GetStorage(type).ParseCache; if (!cache.TryGetValue(strg, out var cached)) { BigInteger? accum = null; foreach (var val in strg.Split('|')) { - foreach (var defined in GetValues(type)) { + foreach (var defined in DynamicEnum.GetValues(type)) { if (defined.name == val.Trim()) { - accum = (accum ?? 0) | GetValue(defined); + accum = (accum ?? 0) | DynamicEnum.GetValue(defined); break; } } } if (accum != null) - cached = GetEnumValue(type, accum.Value); + cached = DynamicEnum.GetEnumValue(type, accum.Value); cache.Add(strg, cached); } return cached; } private static Storage GetStorage(Type type) { - if (!Storages.TryGetValue(type, out var storage)) { + if (!DynamicEnum.Storages.TryGetValue(type, out var storage)) { storage = new Storage(); - Storages.Add(type, storage); + DynamicEnum.Storages.Add(type, storage); } return storage; } diff --git a/MLEM.Data/Json/JsonConverters.cs b/MLEM.Data/Json/JsonConverters.cs index 5706d2b..afff3fe 100644 --- a/MLEM.Data/Json/JsonConverters.cs +++ b/MLEM.Data/Json/JsonConverters.cs @@ -21,7 +21,7 @@ namespace MLEM.Data.Json { /// The serializer to add the converters to /// The given serializer, for chaining public static JsonSerializer AddAll(JsonSerializer serializer) { - foreach (var converter in Converters) + foreach (var converter in JsonConverters.Converters) serializer.Converters.Add(converter); return serializer; } diff --git a/MLEM.Data/Json/StaticJsonConverter.cs b/MLEM.Data/Json/StaticJsonConverter.cs index 66beb62..2124686 100644 --- a/MLEM.Data/Json/StaticJsonConverter.cs +++ b/MLEM.Data/Json/StaticJsonConverter.cs @@ -29,7 +29,7 @@ namespace MLEM.Data.Json { /// /// The type that the dictionary is declared in /// The name of the dictionary itself - public StaticJsonConverter(Type type, string memberName) : this(GetEntries(type, memberName)) {} + public StaticJsonConverter(Type type, string memberName) : this(StaticJsonConverter.GetEntries(type, memberName)) {} /// Writes the JSON representation of the object. /// The to write to. diff --git a/MLEM.Data/RuntimeTexturePacker.cs b/MLEM.Data/RuntimeTexturePacker.cs index 630e74c..32c0b9b 100644 --- a/MLEM.Data/RuntimeTexturePacker.cs +++ b/MLEM.Data/RuntimeTexturePacker.cs @@ -81,7 +81,7 @@ namespace MLEM.Data { var region = atlas[pos]; if (ignoreTransparent) { - if (IsTransparent(region)) + if (this.IsTransparent(region)) continue; } @@ -180,8 +180,8 @@ namespace MLEM.Data { var width = this.alreadyPackedTextures.Max(t => t.PackedArea.Right); var height = this.alreadyPackedTextures.Max(t => t.PackedArea.Bottom); if (this.forcePowerOfTwo) { - width = ToPowerOfTwo(width); - height = ToPowerOfTwo(height); + width = RuntimeTexturePacker.ToPowerOfTwo(width); + height = RuntimeTexturePacker.ToPowerOfTwo(height); } if (this.forceSquare) width = height = Math.Max(width, height); diff --git a/MLEM.Extended/Tiled/IndividualTiledMapRenderer.cs b/MLEM.Extended/Tiled/IndividualTiledMapRenderer.cs index 7ee601a..0674f5a 100644 --- a/MLEM.Extended/Tiled/IndividualTiledMapRenderer.cs +++ b/MLEM.Extended/Tiled/IndividualTiledMapRenderer.cs @@ -116,7 +116,7 @@ namespace MLEM.Extended.Tiled { /// The area that is visible, in pixel space. /// The draw function to use, or null to use public void DrawLayer(SpriteBatch batch, int layerIndex, RectangleF? frustum = null, DrawDelegate drawFunction = null) { - var draw = drawFunction ?? DefaultDraw; + var draw = drawFunction ?? IndividualTiledMapRenderer.DefaultDraw; var (minX, minY, maxX, maxY) = this.GetFrustum(frustum); for (var x = minX; x < maxX; x++) { for (var y = minY; y < maxY; y++) { @@ -136,7 +136,7 @@ namespace MLEM.Extended.Tiled { /// The area that is visible, in pixel space. /// The add function to use, or null to use . public void AddLayer(StaticSpriteBatch batch, int layerIndex, RectangleF? frustum = null, AddDelegate addFunction = null) { - var add = addFunction ?? DefaultAdd; + var add = addFunction ?? IndividualTiledMapRenderer.DefaultAdd; var (minX, minY, maxX, maxY) = this.GetFrustum(frustum); for (var x = minX; x < maxX; x++) { for (var y = minY; y < maxY; y++) { diff --git a/MLEM.Extended/Tiled/LayerPosition.cs b/MLEM.Extended/Tiled/LayerPosition.cs index 333ddd9..3fb7b89 100644 --- a/MLEM.Extended/Tiled/LayerPosition.cs +++ b/MLEM.Extended/Tiled/LayerPosition.cs @@ -54,8 +54,8 @@ namespace MLEM.Extended.Tiled { /// A 32-bit signed integer that is the hash code for this instance. public override int GetHashCode() { var hashCode = this.Layer.GetHashCode(); - hashCode = (hashCode * 397) ^ this.X; - hashCode = (hashCode * 397) ^ this.Y; + hashCode = hashCode * 397 ^ this.X; + hashCode = hashCode * 397 ^ this.Y; return hashCode; } @@ -105,7 +105,7 @@ namespace MLEM.Extended.Tiled { /// The right position. /// The sum of the positions. public static LayerPosition operator +(LayerPosition left, LayerPosition right) { - return Add(left, right); + return LayerPosition.Add(left, right); } /// @@ -115,7 +115,7 @@ namespace MLEM.Extended.Tiled { /// The right position. /// The difference of the positions. public static LayerPosition operator -(LayerPosition left, LayerPosition right) { - return Add(left, -right); + return LayerPosition.Add(left, -right); } /// diff --git a/MLEM.Extended/Tiled/LayerPositionF.cs b/MLEM.Extended/Tiled/LayerPositionF.cs index a84477e..80a3d3f 100644 --- a/MLEM.Extended/Tiled/LayerPositionF.cs +++ b/MLEM.Extended/Tiled/LayerPositionF.cs @@ -54,8 +54,8 @@ namespace MLEM.Extended.Tiled { /// A 32-bit signed integer that is the hash code for this instance. public override int GetHashCode() { var hashCode = this.Layer.GetHashCode(); - hashCode = (hashCode * 397) ^ this.X.GetHashCode(); - hashCode = (hashCode * 397) ^ this.Y.GetHashCode(); + hashCode = hashCode * 397 ^ this.X.GetHashCode(); + hashCode = hashCode * 397 ^ this.Y.GetHashCode(); return hashCode; } @@ -105,7 +105,7 @@ namespace MLEM.Extended.Tiled { /// The right position. /// The sum of the positions. public static LayerPositionF operator +(LayerPositionF left, LayerPositionF right) { - return Add(left, right); + return LayerPositionF.Add(left, right); } /// @@ -115,7 +115,7 @@ namespace MLEM.Extended.Tiled { /// The right position. /// The difference of the positions. public static LayerPositionF operator -(LayerPositionF left, LayerPositionF right) { - return Add(left, -right); + return LayerPositionF.Add(left, -right); } /// diff --git a/MLEM.Extended/Tiled/TiledExtensions.cs b/MLEM.Extended/Tiled/TiledExtensions.cs index 51b5830..3528fea 100644 --- a/MLEM.Extended/Tiled/TiledExtensions.cs +++ b/MLEM.Extended/Tiled/TiledExtensions.cs @@ -5,7 +5,6 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MonoGame.Extended; using MonoGame.Extended.Tiled; -using static MonoGame.Extended.Tiled.TiledMapTileFlipFlags; using ColorHelper = MLEM.Extensions.ColorHelper; namespace MLEM.Extended.Tiled { @@ -144,9 +143,9 @@ namespace MLEM.Extended.Tiled { public static TiledMapTilesetTile GetTilesetTile(this TiledMapTileset tileset, int localId, bool createStub = true) { var tilesetTile = tileset.Tiles.FirstOrDefault(t => t.LocalTileIdentifier == localId); if (tilesetTile == null && createStub) { - if (!StubTilesetTiles.TryGetValue(localId, out tilesetTile)) { + if (!TiledExtensions.StubTilesetTiles.TryGetValue(localId, out tilesetTile)) { tilesetTile = new TiledMapTilesetTile(localId); - StubTilesetTiles.Add(localId, tilesetTile); + TiledExtensions.StubTilesetTiles.Add(localId, tilesetTile); } } return tilesetTile; @@ -271,12 +270,12 @@ namespace MLEM.Extended.Tiled { /// The position to add to the object's position /// The flipping of the tile that this object belongs to. If set, the returned area will be "flipped" in the tile's space so that it matches the flip flags. /// The area that the tile covers - public static RectangleF GetArea(this TiledMapObject obj, TiledMap map, Vector2? position = null, TiledMapTileFlipFlags flipFlags = None) { + public static RectangleF GetArea(this TiledMapObject obj, TiledMap map, Vector2? position = null, TiledMapTileFlipFlags flipFlags = TiledMapTileFlipFlags.None) { var tileSize = map.GetTileSize(); var area = new RectangleF(obj.Position / tileSize, obj.Size / tileSize); - if (flipFlags.HasFlag(FlipHorizontally)) + if (flipFlags.HasFlag(TiledMapTileFlipFlags.FlipHorizontally)) area.X = 1 - area.X - area.Width; - if (flipFlags.HasFlag(FlipVertically)) + if (flipFlags.HasFlag(TiledMapTileFlipFlags.FlipVertically)) area.Y = 1 - area.Y - area.Height; if (position != null) area.Offset(position.Value); diff --git a/MLEM.Extended/Tiled/TiledMapCollisions.cs b/MLEM.Extended/Tiled/TiledMapCollisions.cs index 59a349b..10a9d1c 100644 --- a/MLEM.Extended/Tiled/TiledMapCollisions.cs +++ b/MLEM.Extended/Tiled/TiledMapCollisions.cs @@ -36,7 +36,7 @@ namespace MLEM.Extended.Tiled { /// The function used to collect the collision info of a tile, or null to use public void SetMap(TiledMap map, CollectCollisions collisionFunction = null) { this.map = map; - this.collisionFunction = collisionFunction ?? DefaultCollectCollisions; + this.collisionFunction = collisionFunction ?? TiledMapCollisions.DefaultCollectCollisions; this.collisionInfos = new TileCollisionInfo[map.Layers.Count, map.Width, map.Height]; for (var i = 0; i < map.TileLayers.Count; i++) { for (var x = 0; x < map.Width; x++) { diff --git a/MLEM.Startup/MlemGame.cs b/MLEM.Startup/MlemGame.cs index 5aff196..778e5f3 100644 --- a/MLEM.Startup/MlemGame.cs +++ b/MLEM.Startup/MlemGame.cs @@ -18,7 +18,7 @@ namespace MLEM.Startup { /// /// The static game instance's input handler /// - public static InputHandler Input => instance.InputHandler; + public static InputHandler Input => MlemGame.instance.InputHandler; /// /// This game's graphics device manager, initialized in the constructor @@ -64,7 +64,7 @@ namespace MLEM.Startup { /// The default window width /// The default window height public MlemGame(int windowWidth = 1280, int windowHeight = 720) { - instance = this; + MlemGame.instance = this; this.GraphicsDeviceManager = new GraphicsDeviceManager(this) { PreferredBackBufferWidth = windowWidth, @@ -160,7 +160,7 @@ namespace MLEM.Startup { /// The type of content to load /// The loaded content public static T LoadContent(string name) { - return instance.Content.Load(name); + return MlemGame.instance.Content.Load(name); } /// diff --git a/MLEM.Ui/Elements/Element.cs b/MLEM.Ui/Elements/Element.cs index 0d3fc54..6ea1ad0 100644 --- a/MLEM.Ui/Elements/Element.cs +++ b/MLEM.Ui/Elements/Element.cs @@ -652,7 +652,7 @@ namespace MLEM.Ui.Elements { var newX = prevArea.Right + this.ScaledOffset.X; // with awkward ui scale values, floating point rounding can cause an element that would usually // be positioned correctly to be pushed into the next line due to a very small deviation - if (newX + newSize.X <= parentArea.Right + Epsilon) { + if (newX + newSize.X <= parentArea.Right + Element.Epsilon) { pos.X = newX; pos.Y = prevArea.Y + this.ScaledOffset.Y; } else { @@ -715,7 +715,7 @@ namespace MLEM.Ui.Elements { } // we want to leave some leeway to prevent float rounding causing an infinite loop - if (!autoSize.Equals(this.UnscrolledArea.Size, Epsilon)) { + if (!autoSize.Equals(this.UnscrolledArea.Size, Element.Epsilon)) { recursion++; if (recursion >= 16) { throw new ArithmeticException($"The area of {this} with root {this.Root.Name} has recursively updated too often. Does its child {foundChild} contain any conflicting auto-sizing settings?"); diff --git a/MLEM.Ui/Elements/ElementHelper.cs b/MLEM.Ui/Elements/ElementHelper.cs index 011674f..b9f86ea 100644 --- a/MLEM.Ui/Elements/ElementHelper.cs +++ b/MLEM.Ui/Elements/ElementHelper.cs @@ -118,7 +118,7 @@ namespace MLEM.Ui.Elements { /// public static Button KeybindButton(Anchor anchor, Vector2 size, Keybind keybind, InputHandler inputHandler, string activePlaceholder, GenericInput unbindKey = default, string unboundPlaceholder = "", Func inputName = null, int index = 0, Func, bool> isKeybindAllowed = null) { - return KeybindButton(anchor, size, keybind, inputHandler, activePlaceholder, new Keybind(unbindKey), unboundPlaceholder, inputName, index, isKeybindAllowed); + return ElementHelper.KeybindButton(anchor, size, keybind, inputHandler, activePlaceholder, new Keybind(unbindKey), unboundPlaceholder, inputName, index, isKeybindAllowed); } /// @@ -139,7 +139,9 @@ namespace MLEM.Ui.Elements { /// A function that can optionally determine whether a given input and modifier combination is allowed. If this is null, all combinations are allowed. /// A keybind button with the given settings public static Button KeybindButton(Anchor anchor, Vector2 size, Keybind keybind, InputHandler inputHandler, string activePlaceholder, Keybind unbind = default, string unboundPlaceholder = "", Func inputName = null, int index = 0, Func, bool> isKeybindAllowed = null) { - string GetCurrentName() => keybind.TryGetCombination(index, out var combination) ? combination.ToString(" + ", inputName) : unboundPlaceholder; + string GetCurrentName() { + return keybind.TryGetCombination(index, out var combination) ? combination.ToString(" + ", inputName) : unboundPlaceholder; + } var button = new Button(anchor, size, GetCurrentName()); var activeNext = false; diff --git a/MLEM.Ui/Elements/Panel.cs b/MLEM.Ui/Elements/Panel.cs index 513cb1c..0f44685 100644 --- a/MLEM.Ui/Elements/Panel.cs +++ b/MLEM.Ui/Elements/Panel.cs @@ -121,7 +121,7 @@ namespace MLEM.Ui.Elements { var offset = new Vector2(0, -this.ScrollBar.CurrentValue); // we ignore false grandchildren so that the children of the scroll bar stay in place foreach (var child in this.GetChildren(c => c != this.ScrollBar, true, true)) { - if (!child.ScrollOffset.Equals(offset, Epsilon)) { + if (!child.ScrollOffset.Equals(offset, Element.Epsilon)) { child.ScrollOffset = offset; this.relevantChildrenDirty = true; } @@ -246,13 +246,13 @@ namespace MLEM.Ui.Elements { // the max value of the scrollbar is the amount of non-scaled pixels taken up by overflowing components var scrollBarMax = (childrenHeight - this.ChildPaddedArea.Height) / this.Scale; - if (!this.ScrollBar.MaxValue.Equals(scrollBarMax, Epsilon)) { + if (!this.ScrollBar.MaxValue.Equals(scrollBarMax, Element.Epsilon)) { this.ScrollBar.MaxValue = scrollBarMax; this.relevantChildrenDirty = true; // update child padding based on whether the scroll bar is visible var childOffset = this.ScrollBar.IsHidden ? 0 : this.ScrollerSize.Value.X + this.ScrollBarOffset; - if (!this.scrollBarChildOffset.Equals(childOffset, Epsilon)) { + if (!this.scrollBarChildOffset.Equals(childOffset, Element.Epsilon)) { this.ChildPadding += new Padding(0, -this.scrollBarChildOffset + childOffset, 0, 0); this.scrollBarChildOffset = childOffset; this.SetAreaDirty(); diff --git a/MLEM.Ui/Elements/Paragraph.cs b/MLEM.Ui/Elements/Paragraph.cs index 9c34142..34164cc 100644 --- a/MLEM.Ui/Elements/Paragraph.cs +++ b/MLEM.Ui/Elements/Paragraph.cs @@ -60,7 +60,7 @@ namespace MLEM.Ui.Elements { if (this.text != value) { this.text = value; this.SetTextDirty(); - + var force = string.IsNullOrWhiteSpace(this.text); if (this.forceHide != force) { this.forceHide = force; @@ -197,7 +197,7 @@ namespace MLEM.Ui.Elements { protected void SetTextDirty() { this.TokenizedText = null; // only set our area dirty if our size changed as a result of this action - if (!this.AreaDirty && !this.CalcActualSize(this.ParentArea).Equals(this.DisplayArea.Size, Epsilon)) + if (!this.AreaDirty && !this.CalcActualSize(this.ParentArea).Equals(this.DisplayArea.Size, Element.Epsilon)) this.SetAreaDirty(); } diff --git a/MLEM.Ui/Elements/ScrollBar.cs b/MLEM.Ui/Elements/ScrollBar.cs index 7ffa383..f4801bd 100644 --- a/MLEM.Ui/Elements/ScrollBar.cs +++ b/MLEM.Ui/Elements/ScrollBar.cs @@ -45,7 +45,7 @@ namespace MLEM.Ui.Elements { // force current value to be clamped this.CurrentValue = this.CurrentValue; // auto-hide if necessary - var shouldHide = this.maxValue <= Epsilon; + var shouldHide = this.maxValue <= Element.Epsilon; if (this.AutoHideWhenEmpty && this.IsHidden != shouldHide) { this.IsHidden = shouldHide; this.OnAutoHide?.Invoke(this); @@ -188,7 +188,7 @@ namespace MLEM.Ui.Elements { if (this.SmoothScrolling && this.scrollAdded != 0) { this.scrollAdded *= this.SmoothScrollFactor; - if (Math.Abs(this.scrollAdded) <= Epsilon) + if (Math.Abs(this.scrollAdded) <= Element.Epsilon) this.scrollAdded = 0; this.OnValueChanged?.Invoke(this, this.CurrentValue); } diff --git a/MLEM.Ui/Elements/SquishingGroup.cs b/MLEM.Ui/Elements/SquishingGroup.cs index 956b09d..efd21ef 100644 --- a/MLEM.Ui/Elements/SquishingGroup.cs +++ b/MLEM.Ui/Elements/SquishingGroup.cs @@ -24,7 +24,7 @@ namespace MLEM.Ui.Elements { // we squish children in order of priority, since auto-anchoring is based on addition order for (var i = 0; i < this.SortedChildren.Count; i++) { var child = this.SortedChildren[i]; - if (SquishChild(child, out var squished)) + if (SquishingGroup.SquishChild(child, out var squished)) child.SetAreaAndUpdateChildren(squished); } } @@ -66,7 +66,7 @@ namespace MLEM.Ui.Elements { } } } - if (!pos.Equals(element.Area.Location, Epsilon) || !size.Equals(element.Area.Size, Epsilon)) { + if (!pos.Equals(element.Area.Location, Element.Epsilon) || !size.Equals(element.Area.Size, Element.Epsilon)) { squishedArea = new RectangleF(pos, size); return true; } diff --git a/MLEM.Ui/Elements/TextField.cs b/MLEM.Ui/Elements/TextField.cs index 6557775..5df5598 100644 --- a/MLEM.Ui/Elements/TextField.cs +++ b/MLEM.Ui/Elements/TextField.cs @@ -209,7 +209,7 @@ namespace MLEM.Ui.Elements { /// The text that the text field should contain by default /// Whether the text field should support multi-line editing public TextField(Anchor anchor, Vector2 size, Rule rule = null, GenericFont font = null, string text = null, bool multiline = false) : base(anchor, size) { - this.InputRule = rule ?? DefaultRule; + this.InputRule = rule ?? TextField.DefaultRule; this.Multiline = multiline; if (font != null) this.Font = font; diff --git a/MLEM.Ui/Parsers/UiMarkdownParser.cs b/MLEM.Ui/Parsers/UiMarkdownParser.cs index 17b7951..da9fecd 100644 --- a/MLEM.Ui/Parsers/UiMarkdownParser.cs +++ b/MLEM.Ui/Parsers/UiMarkdownParser.cs @@ -62,7 +62,7 @@ namespace MLEM.Ui.Parsers { this.Style(ElementType.VerticalSpace, v => v.Size = new Vector2(1, 5)); for (var i = 0; i < 6; i++) { var level = i; - this.Style(ElementTypes[Array.IndexOf(ElementTypes, ElementType.Header1) + i], p => { + this.Style(UiMarkdownParser.ElementTypes[Array.IndexOf(UiMarkdownParser.ElementTypes, ElementType.Header1) + i], p => { p.Alignment = TextAlignment.Center; p.TextScaleMultiplier = 2 - level * 0.15F; }); @@ -107,7 +107,7 @@ namespace MLEM.Ui.Parsers { /// The type of elements that the given flags are expected to be. /// This parser, for chaining. public UiMarkdownParser Style(ElementType types, Action style, bool add = false) where T : Element { - foreach (var type in ElementTypes) { + foreach (var type in UiMarkdownParser.ElementTypes) { if (types.HasFlag(type)) { if (add && this.elementStyles.ContainsKey(type)) { this.elementStyles[type] += Action; @@ -193,7 +193,7 @@ namespace MLEM.Ui.Parsers { var parsedHeader = false; for (var h = 6; h >= 1; h--) { if (line.StartsWith(new string('#', h))) { - var type = ElementTypes[Array.IndexOf(ElementTypes, ElementType.Header1) + h - 1]; + var type = UiMarkdownParser.ElementTypes[Array.IndexOf(UiMarkdownParser.ElementTypes, ElementType.Header1) + h - 1]; yield return (type, new Paragraph(Anchor.AutoLeft, 1, line.Substring(h).Trim())); parsedHeader = true; break; @@ -275,7 +275,7 @@ namespace MLEM.Ui.Parsers { /// A combined flag that contains through . /// This element type is a . /// - Headers = Header1 | Header2 | Header3 | Header4 | Header5 | Header6, + Headers = ElementType.Header1 | ElementType.Header2 | ElementType.Header3 | ElementType.Header4 | ElementType.Header5 | ElementType.Header6, /// /// A paragraph, which is one line of markdown text. /// This element type is a . diff --git a/MLEM/Cameras/Camera.cs b/MLEM/Cameras/Camera.cs index a4341b7..3485e68 100644 --- a/MLEM/Cameras/Camera.cs +++ b/MLEM/Cameras/Camera.cs @@ -164,7 +164,7 @@ namespace MLEM.Cameras { if (this.Max.Y > max.Y) this.Max = new Vector2(this.Max.X, max.Y); } - return !this.Position.Equals(lastPos, Epsilon); + return !this.Position.Equals(lastPos, Camera.Epsilon); } /// diff --git a/MLEM/Extensions/CharExtensions.cs b/MLEM/Extensions/CharExtensions.cs index 78a0dbc..f6992d5 100644 --- a/MLEM/Extensions/CharExtensions.cs +++ b/MLEM/Extensions/CharExtensions.cs @@ -15,9 +15,9 @@ namespace MLEM.Extensions { /// The character to turn into a string /// A string representing the character public static string ToCachedString(this char c) { - if (!Cache.TryGetValue(c, out var ret)) { + if (!CharExtensions.Cache.TryGetValue(c, out var ret)) { ret = c.ToString(); - Cache.Add(c, ret); + CharExtensions.Cache.Add(c, ret); } return ret; } diff --git a/MLEM/Extensions/ColorExtensions.cs b/MLEM/Extensions/ColorExtensions.cs index 19f33f6..1384de7 100644 --- a/MLEM/Extensions/ColorExtensions.cs +++ b/MLEM/Extensions/ColorExtensions.cs @@ -50,7 +50,7 @@ namespace MLEM.Extensions { /// The number to parse. /// The resulting color. public static Color FromHexRgba(int value) { - return new Color((value >> 16) & 0xFF, (value >> 8) & 0xFF, (value >> 0) & 0xFF, (value >> 24) & 0xFF); + return new Color(value >> 16 & 0xFF, value >> 8 & 0xFF, value >> 0 & 0xFF, value >> 24 & 0xFF); } /// @@ -60,7 +60,7 @@ namespace MLEM.Extensions { /// The number to parse. /// The resulting color. public static Color FromHexRgb(int value) { - return new Color((value >> 16) & 0xFF, (value >> 8) & 0xFF, (value >> 0) & 0xFF); + return new Color(value >> 16 & 0xFF, value >> 8 & 0xFF, value >> 0 & 0xFF); } /// @@ -73,7 +73,7 @@ namespace MLEM.Extensions { if (value.StartsWith("#")) value = value.Substring(1); var val = int.Parse(value, NumberStyles.HexNumber); - return value.Length > 6 ? FromHexRgba(val) : FromHexRgb(val); + return value.Length > 6 ? ColorHelper.FromHexRgba(val) : ColorHelper.FromHexRgb(val); } } diff --git a/MLEM/Extensions/GraphicsExtensions.cs b/MLEM/Extensions/GraphicsExtensions.cs index 47bafeb..2c94d0f 100644 --- a/MLEM/Extensions/GraphicsExtensions.cs +++ b/MLEM/Extensions/GraphicsExtensions.cs @@ -21,18 +21,18 @@ namespace MLEM.Extensions { manager.IsFullScreen = fullscreen; if (fullscreen) { var view = manager.GraphicsDevice.Viewport; - lastWidth = view.Width; - lastHeight = view.Height; + GraphicsExtensions.lastWidth = view.Width; + GraphicsExtensions.lastHeight = view.Height; var curr = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode; manager.PreferredBackBufferWidth = curr.Width; manager.PreferredBackBufferHeight = curr.Height; } else { - if (lastWidth <= 0 || lastHeight <= 0) + if (GraphicsExtensions.lastWidth <= 0 || GraphicsExtensions.lastHeight <= 0) throw new InvalidOperationException("Can't call SetFullscreen to change out of fullscreen mode without going into fullscreen mode first"); - manager.PreferredBackBufferWidth = lastWidth; - manager.PreferredBackBufferHeight = lastHeight; + manager.PreferredBackBufferWidth = GraphicsExtensions.lastWidth; + manager.PreferredBackBufferHeight = GraphicsExtensions.lastHeight; } manager.ApplyChanges(); } diff --git a/MLEM/Extensions/SpriteBatchExtensions.cs b/MLEM/Extensions/SpriteBatchExtensions.cs index 9894977..ac50c80 100644 --- a/MLEM/Extensions/SpriteBatchExtensions.cs +++ b/MLEM/Extensions/SpriteBatchExtensions.cs @@ -19,12 +19,12 @@ namespace MLEM.Extensions { /// The sprite batch /// A 1x1 pixel white texture public static Texture2D GetBlankTexture(this SpriteBatch batch) { - if (blankTexture == null) { - blankTexture = new Texture2D(batch.GraphicsDevice, 1, 1); - blankTexture.SetData(new[] {Color.White}); - AutoDispose(batch, blankTexture); + if (SpriteBatchExtensions.blankTexture == null) { + SpriteBatchExtensions.blankTexture = new Texture2D(batch.GraphicsDevice, 1, 1); + SpriteBatchExtensions.blankTexture.SetData(new[] {Color.White}); + SpriteBatchExtensions.AutoDispose(batch, SpriteBatchExtensions.blankTexture); } - return blankTexture; + return SpriteBatchExtensions.blankTexture; } /// @@ -43,7 +43,7 @@ namespace MLEM.Extensions { outli, color, outli, outli, outli, outli }); - AutoDispose(batch, tex); + SpriteBatchExtensions.AutoDispose(batch, tex); return new NinePatch(tex, 1); } @@ -57,7 +57,7 @@ namespace MLEM.Extensions { public static Texture2D GenerateSquareTexture(this SpriteBatch batch, Color color) { var tex = new Texture2D(batch.GraphicsDevice, 1, 1); tex.SetData(new[] {color}); - AutoDispose(batch, tex); + SpriteBatchExtensions.AutoDispose(batch, tex); return tex; } @@ -80,7 +80,7 @@ namespace MLEM.Extensions { } } } - AutoDispose(batch, tex); + SpriteBatchExtensions.AutoDispose(batch, tex); return tex; } @@ -107,7 +107,7 @@ namespace MLEM.Extensions { data[x, y] = Color.Lerp(top, btm, y / (float) height); } } - AutoDispose(batch, tex); + SpriteBatchExtensions.AutoDispose(batch, tex); return tex; } diff --git a/MLEM/Font/GenericFont.cs b/MLEM/Font/GenericFont.cs index 4b82973..42dc2e3 100644 --- a/MLEM/Font/GenericFont.cs +++ b/MLEM/Font/GenericFont.cs @@ -21,7 +21,7 @@ namespace MLEM.Font { public const char Emsp = '\u2003'; /// [Obsolete("Use the Emsp field instead.")] - public const char OneEmSpace = Emsp; + public const char OneEmSpace = GenericFont.Emsp; /// /// This field holds the unicode representation of a non-breaking space. /// Whereas a regular would have to explicitly support this character for width calculations, generic fonts implicitly support it in . @@ -185,17 +185,17 @@ namespace MLEM.Font { xOffset = 0; size.Y += this.LineHeight; break; - case Emsp: + case GenericFont.Emsp: xOffset += this.LineHeight; break; - case Nbsp: + case GenericFont.Nbsp: xOffset += font.MeasureChar(' '); break; - case Zwsp: + case GenericFont.Zwsp: // don't add width for a zero-width space break; case ' ': - if (ignoreTrailingSpaces && IsTrailingSpace(text, i)) { + if (ignoreTrailingSpaces && GenericFont.IsTrailingSpace(text, i)) { // if this is a trailing space, we can skip remaining spaces too i = text.Length - 1; break; @@ -252,7 +252,7 @@ namespace MLEM.Font { } else { var font = fontFunction?.Invoke(i) ?? this; var cWidth = font.MeasureString(c.ToCachedString()).X * scale; - if (c == ' ' || c == Emsp || c == Zwsp) { + if (c == ' ' || c == GenericFont.Emsp || c == GenericFont.Zwsp) { // remember the location of this (breaking!) space lastSpaceIndex = curr.Length; widthSinceLastSpace = 0; diff --git a/MLEM/Font/GenericSpriteFont.cs b/MLEM/Font/GenericSpriteFont.cs index 64b69aa..a4db544 100644 --- a/MLEM/Font/GenericSpriteFont.cs +++ b/MLEM/Font/GenericSpriteFont.cs @@ -26,9 +26,9 @@ namespace MLEM.Font { /// A bold version of the font /// An italic version of the font public GenericSpriteFont(SpriteFont font, SpriteFont bold = null, SpriteFont italic = null) { - this.Font = SetDefaults(font); - this.Bold = bold != null ? new GenericSpriteFont(SetDefaults(bold)) : this; - this.Italic = italic != null ? new GenericSpriteFont(SetDefaults(italic)) : this; + this.Font = GenericSpriteFont.SetDefaults(font); + this.Bold = bold != null ? new GenericSpriteFont(GenericSpriteFont.SetDefaults(bold)) : this; + this.Italic = italic != null ? new GenericSpriteFont(GenericSpriteFont.SetDefaults(italic)) : this; } /// diff --git a/MLEM/Formatting/TextFormatter.cs b/MLEM/Formatting/TextFormatter.cs index 368dc97..1c41447 100644 --- a/MLEM/Formatting/TextFormatter.cs +++ b/MLEM/Formatting/TextFormatter.cs @@ -87,13 +87,13 @@ namespace MLEM.Formatting { // if we've reached the end of the string if (next == null) { var sub = s.Substring(rawIndex, s.Length - rawIndex); - tokens.Add(new Token(codes.ToArray(), index, rawIndex, StripFormatting(font, sub, codes), sub)); + tokens.Add(new Token(codes.ToArray(), index, rawIndex, TextFormatter.StripFormatting(font, sub, codes), sub)); break; } // create a new token for the content up to the next code var ret = s.Substring(rawIndex, next.Match.Index - rawIndex); - var strippedRet = StripFormatting(font, ret, codes); + var strippedRet = TextFormatter.StripFormatting(font, ret, codes); tokens.Add(new Token(codes.ToArray(), index, rawIndex, strippedRet, ret)); // move to the start of the next code @@ -104,7 +104,7 @@ namespace MLEM.Formatting { codes.RemoveAll(c => c.EndsHere(next)); codes.Add(next); } - return new TokenizedString(font, alignment, s, StripFormatting(font, s, tokens.SelectMany(t => t.AppliedCodes)), tokens.ToArray()); + return new TokenizedString(font, alignment, s, TextFormatter.StripFormatting(font, s, tokens.SelectMany(t => t.AppliedCodes)), tokens.ToArray()); } /// diff --git a/MLEM/Formatting/TokenizedString.cs b/MLEM/Formatting/TokenizedString.cs index c67b792..06b0305 100644 --- a/MLEM/Formatting/TokenizedString.cs +++ b/MLEM/Formatting/TokenizedString.cs @@ -123,12 +123,12 @@ namespace MLEM.Formatting { var token = this.Tokens[t]; var drawFont = token.GetFont(font); var drawColor = token.GetColor(color); - + var indexInToken = 0; for (var l = 0; l < token.SplitDisplayString.Length; l++) { foreach (var c in token.SplitDisplayString[l]) { var cString = c.ToCachedString(); - + if (indexInToken == 0) token.DrawSelf(time, batch, pos + innerOffset, drawFont, color, scale, depth); token.DrawCharacter(time, batch, c, cString, indexInToken, pos + innerOffset, drawFont, drawColor, scale, depth); @@ -136,7 +136,7 @@ namespace MLEM.Formatting { innerOffset.X += drawFont.MeasureString(cString).X * scale; indexInToken++; } - + // only split at a new line, not between tokens! if (l < token.SplitDisplayString.Length - 1) { innerOffset.X = token.InnerOffsets[l] * scale; diff --git a/MLEM/Graphics/AutoTiling.cs b/MLEM/Graphics/AutoTiling.cs index 03933b3..16cdd4f 100644 --- a/MLEM/Graphics/AutoTiling.cs +++ b/MLEM/Graphics/AutoTiling.cs @@ -35,7 +35,7 @@ namespace MLEM.Graphics { public static void DrawAutoTile(SpriteBatch batch, Vector2 pos, TextureRegion texture, ConnectsTo connectsTo, Color color, Vector2? origin = null, Vector2? scale = null, float layerDepth = 0) { var orig = origin ?? Vector2.Zero; var sc = scale ?? Vector2.One; - var (p1, r1, p2, r2, p3, r3, p4, r4) = CalculateAutoTile(pos, texture.Area, connectsTo, sc); + var (p1, r1, p2, r2, p3, r3, p4, r4) = AutoTiling.CalculateAutoTile(pos, texture.Area, connectsTo, sc); batch.Draw(texture.Texture, p1, r1, color, 0, orig, sc, SpriteEffects.None, layerDepth); batch.Draw(texture.Texture, p2, r2, color, 0, orig, sc, SpriteEffects.None, layerDepth); batch.Draw(texture.Texture, p3, r3, color, 0, orig, sc, SpriteEffects.None, layerDepth); @@ -46,7 +46,7 @@ namespace MLEM.Graphics { public static void AddAutoTile(StaticSpriteBatch batch, Vector2 pos, TextureRegion texture, ConnectsTo connectsTo, Color color, Vector2? origin = null, Vector2? scale = null, float layerDepth = 0, ICollection items = null) { var orig = origin ?? Vector2.Zero; var sc = scale ?? Vector2.One; - var (p1, r1, p2, r2, p3, r3, p4, r4) = CalculateAutoTile(pos, texture.Area, connectsTo, sc); + var (p1, r1, p2, r2, p3, r3, p4, r4) = AutoTiling.CalculateAutoTile(pos, texture.Area, connectsTo, sc); var a1 = batch.Add(texture.Texture, p1, r1, color, 0, orig, sc, SpriteEffects.None, layerDepth); var a2 = batch.Add(texture.Texture, p2, r2, color, 0, orig, sc, SpriteEffects.None, layerDepth); var a3 = batch.Add(texture.Texture, p3, r3, color, 0, orig, sc, SpriteEffects.None, layerDepth); @@ -88,7 +88,7 @@ namespace MLEM.Graphics { var orig = origin ?? Vector2.Zero; var sc = scale ?? Vector2.One; var od = layerDepth + overlayDepthOffset; - var (r1, r2, r3, r4) = CalculateExtendedAutoTile(pos, overlayTexture.Area, connectsTo, sc); + var (r1, r2, r3, r4) = AutoTiling.CalculateExtendedAutoTile(pos, overlayTexture.Area, connectsTo, sc); if (backgroundTexture != null) batch.Draw(backgroundTexture, pos, backgroundColor, 0, orig, sc, SpriteEffects.None, layerDepth); if (r1 != Rectangle.Empty) @@ -106,7 +106,7 @@ namespace MLEM.Graphics { var orig = origin ?? Vector2.Zero; var sc = scale ?? Vector2.One; var od = layerDepth + overlayDepthOffset; - var (r1, r2, r3, r4) = CalculateExtendedAutoTile(pos, overlayTexture.Area, connectsTo, sc); + var (r1, r2, r3, r4) = AutoTiling.CalculateExtendedAutoTile(pos, overlayTexture.Area, connectsTo, sc); if (backgroundTexture != null) { var background = batch.Add(backgroundTexture, pos, backgroundColor, 0, orig, sc, SpriteEffects.None, layerDepth); items?.Add(background); diff --git a/MLEM/Graphics/StaticSpriteBatch.cs b/MLEM/Graphics/StaticSpriteBatch.cs index 76da56a..bc25725 100644 --- a/MLEM/Graphics/StaticSpriteBatch.cs +++ b/MLEM/Graphics/StaticSpriteBatch.cs @@ -14,7 +14,7 @@ namespace MLEM.Graphics { // this maximum is limited by indices being a short private const int MaxBatchItems = short.MaxValue / 6; - private static readonly VertexPositionColorTexture[] Data = new VertexPositionColorTexture[MaxBatchItems * 4]; + private static readonly VertexPositionColorTexture[] Data = new VertexPositionColorTexture[StaticSpriteBatch.MaxBatchItems * 4]; /// /// The amount of vertices that are currently batched. @@ -106,21 +106,21 @@ namespace MLEM.Graphics { Texture2D texture = null; foreach (var item in ordered) { // if the texture changes, we also have to start a new buffer! - if (dataIndex > 0 && (item.Texture != texture || dataIndex >= Data.Length)) { - this.FillBuffer(this.FilledBuffers++, texture, Data); + if (dataIndex > 0 && (item.Texture != texture || dataIndex >= StaticSpriteBatch.Data.Length)) { + this.FillBuffer(this.FilledBuffers++, texture, StaticSpriteBatch.Data); dataIndex = 0; } - Data[dataIndex++] = item.TopLeft; - Data[dataIndex++] = item.TopRight; - Data[dataIndex++] = item.BottomLeft; - Data[dataIndex++] = item.BottomRight; + StaticSpriteBatch.Data[dataIndex++] = item.TopLeft; + StaticSpriteBatch.Data[dataIndex++] = item.TopRight; + StaticSpriteBatch.Data[dataIndex++] = item.BottomLeft; + StaticSpriteBatch.Data[dataIndex++] = item.BottomRight; texture = item.Texture; } if (dataIndex > 0) - this.FillBuffer(this.FilledBuffers++, texture, Data); + this.FillBuffer(this.FilledBuffers++, texture, StaticSpriteBatch.Data); // ensure we have enough indices - var maxItems = Math.Min(this.items.Count, MaxBatchItems); + var maxItems = Math.Min(this.items.Count, StaticSpriteBatch.MaxBatchItems); // each item has 2 triangles which each have 3 indices if (this.indices == null || this.indices.IndexCount < 6 * maxItems) { var newIndices = new short[6 * maxItems]; @@ -434,7 +434,7 @@ namespace MLEM.Graphics { private void FillBuffer(int index, Texture2D texture, VertexPositionColorTexture[] data) { if (this.vertexBuffers.Count <= index) - this.vertexBuffers.Add(new VertexBuffer(this.graphicsDevice, VertexPositionColorTexture.VertexDeclaration, MaxBatchItems * 4, BufferUsage.WriteOnly)); + this.vertexBuffers.Add(new VertexBuffer(this.graphicsDevice, VertexPositionColorTexture.VertexDeclaration, StaticSpriteBatch.MaxBatchItems * 4, BufferUsage.WriteOnly)); this.vertexBuffers[index].SetData(data); this.textures.Insert(index, texture); } diff --git a/MLEM/Input/GenericInput.cs b/MLEM/Input/GenericInput.cs index 761699d..47c40f9 100644 --- a/MLEM/Input/GenericInput.cs +++ b/MLEM/Input/GenericInput.cs @@ -107,7 +107,7 @@ namespace MLEM.Input { /// Returns the hash code for this instance. /// A 32-bit signed integer that is the hash code for this instance. public override int GetHashCode() { - return ((int) this.Type * 397) ^ this.value; + return (int) this.Type * 397 ^ this.value; } /// diff --git a/MLEM/Input/InputHandler.cs b/MLEM/Input/InputHandler.cs index 09d710f..370395c 100644 --- a/MLEM/Input/InputHandler.cs +++ b/MLEM/Input/InputHandler.cs @@ -829,9 +829,9 @@ namespace MLEM.Input { /// The gestures to enable or disable public static void SetGesturesEnabled(bool enabled, params GestureType[] gestures) { if (enabled) { - EnableGestures(gestures); + InputHandler.EnableGestures(gestures); } else { - DisableGestures(gestures); + InputHandler.DisableGestures(gestures); } } diff --git a/MLEM/Input/Keybind.cs b/MLEM/Input/Keybind.cs index 9ae014d..31d5968 100644 --- a/MLEM/Input/Keybind.cs +++ b/MLEM/Input/Keybind.cs @@ -231,9 +231,9 @@ namespace MLEM.Input { /// /// Value Meaning Less than zero This instance precedes in the sort order. Zero This instance occurs in the same position in the sort order as . Greater than zero This instance follows in the sort order. public int CompareTo(object obj) { - if (ReferenceEquals(null, obj)) + if (object.ReferenceEquals(null, obj)) return 1; - if (ReferenceEquals(this, obj)) + if (object.ReferenceEquals(this, obj)) return 0; if (!(obj is Keybind other)) throw new ArgumentException($"Object must be of type {nameof(Keybind)}"); @@ -369,9 +369,9 @@ namespace MLEM.Input { /// /// Value Meaning Less than zero This instance precedes in the sort order. Zero This instance occurs in the same position in the sort order as . Greater than zero This instance follows in the sort order. public int CompareTo(object obj) { - if (ReferenceEquals(null, obj)) + if (object.ReferenceEquals(null, obj)) return 1; - if (ReferenceEquals(this, obj)) + if (object.ReferenceEquals(this, obj)) return 0; if (!(obj is Combination other)) throw new ArgumentException($"Object must be of type {nameof(Combination)}"); diff --git a/MLEM/Input/KeysExtensions.cs b/MLEM/Input/KeysExtensions.cs index 29dc5ea..cf5a266 100644 --- a/MLEM/Input/KeysExtensions.cs +++ b/MLEM/Input/KeysExtensions.cs @@ -18,7 +18,7 @@ namespace MLEM.Input { {ModifierKey.Control, new[] {Keys.LeftControl, Keys.RightControl}}, {ModifierKey.Alt, new[] {Keys.LeftAlt, Keys.RightAlt}} }; - private static readonly Dictionary ModifiersLookup = KeysLookup + private static readonly Dictionary ModifiersLookup = KeysExtensions.KeysLookup .SelectMany(kv => kv.Value.Select(v => (kv.Key, v))) .ToDictionary(kv => kv.Item2, kv => kv.Item1); @@ -28,7 +28,7 @@ namespace MLEM.Input { /// The modifier key /// All of the keys the modifier key represents public static IEnumerable GetKeys(this ModifierKey modifier) { - return KeysLookup.TryGetValue(modifier, out var keys) ? keys : Enumerable.Empty(); + return KeysExtensions.KeysLookup.TryGetValue(modifier, out var keys) ? keys : Enumerable.Empty(); } /// @@ -38,12 +38,12 @@ namespace MLEM.Input { /// The key to convert to a modifier key /// The modifier key, or public static ModifierKey GetModifier(this Keys key) { - return ModifiersLookup.TryGetValue(key, out var mod) ? mod : ModifierKey.None; + return KeysExtensions.ModifiersLookup.TryGetValue(key, out var mod) ? mod : ModifierKey.None; } /// public static ModifierKey GetModifier(this GenericInput input) { - return input.Type == GenericInput.InputType.Keyboard ? GetModifier((Keys) input) : ModifierKey.None; + return input.Type == GenericInput.InputType.Keyboard ? ((Keys) input).GetModifier() : ModifierKey.None; } /// @@ -52,12 +52,12 @@ namespace MLEM.Input { /// The key /// If the key is a modifier key public static bool IsModifier(this Keys key) { - return GetModifier(key) != ModifierKey.None; + return key.GetModifier() != ModifierKey.None; } /// public static bool IsModifier(this GenericInput input) { - return GetModifier(input) != ModifierKey.None; + return input.GetModifier() != ModifierKey.None; } } diff --git a/MLEM/Misc/Direction2.cs b/MLEM/Misc/Direction2.cs index 29472e1..4406366 100644 --- a/MLEM/Misc/Direction2.cs +++ b/MLEM/Misc/Direction2.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using Microsoft.Xna.Framework; -using static MLEM.Misc.Direction2; namespace MLEM.Misc { /// @@ -45,22 +44,22 @@ namespace MLEM.Misc { /// The up and right direction, or +x, -y. /// [EnumMember] - UpRight = Up | Right, + UpRight = Direction2.Up | Direction2.Right, /// /// The down and right direction, or +x, +y. /// [EnumMember] - DownRight = Down | Right, + DownRight = Direction2.Down | Direction2.Right, /// /// The up and left direction, or -x, -y. /// [EnumMember] - UpLeft = Up | Left, + UpLeft = Direction2.Up | Direction2.Left, /// /// The down and left direction, or -x, +y. /// [EnumMember] - DownLeft = Down | Left + DownLeft = Direction2.Down | Direction2.Left } @@ -76,18 +75,18 @@ namespace MLEM.Misc { /// /// The through directions /// - public static readonly Direction2[] Adjacent = All.Where(IsAdjacent).ToArray(); + public static readonly Direction2[] Adjacent = Direction2Helper.All.Where(Direction2Helper.IsAdjacent).ToArray(); /// /// The through directions /// - public static readonly Direction2[] Diagonals = All.Where(IsDiagonal).ToArray(); + public static readonly Direction2[] Diagonals = Direction2Helper.All.Where(Direction2Helper.IsDiagonal).ToArray(); /// /// All directions except /// - public static readonly Direction2[] AllExceptNone = All.Where(dir => dir != None).ToArray(); + public static readonly Direction2[] AllExceptNone = Direction2Helper.All.Where(dir => dir != Direction2.None).ToArray(); - private static readonly Direction2[] Clockwise = {Up, UpRight, Right, DownRight, Down, DownLeft, Left, UpLeft}; - private static readonly Dictionary ClockwiseLookup = Clockwise.Select((d, i) => (d, i)).ToDictionary(kv => kv.d, kv => kv.i); + private static readonly Direction2[] Clockwise = {Direction2.Up, Direction2.UpRight, Direction2.Right, Direction2.DownRight, Direction2.Down, Direction2.DownLeft, Direction2.Left, Direction2.UpLeft}; + private static readonly Dictionary ClockwiseLookup = Direction2Helper.Clockwise.Select((d, i) => (d, i)).ToDictionary(kv => kv.d, kv => kv.i); /// /// Returns if the given direction is considered an "adjacent" direction. @@ -96,7 +95,7 @@ namespace MLEM.Misc { /// The direction to query /// Whether the direction is adjacent public static bool IsAdjacent(this Direction2 dir) { - return dir == Up || dir == Right || dir == Down || dir == Left; + return dir == Direction2.Up || dir == Direction2.Right || dir == Direction2.Down || dir == Direction2.Left; } /// @@ -105,7 +104,7 @@ namespace MLEM.Misc { /// The direction to query /// Whether the direction is diagonal public static bool IsDiagonal(this Direction2 dir) { - return dir == UpRight || dir == DownRight || dir == UpLeft || dir == DownLeft; + return dir == Direction2.UpRight || dir == Direction2.DownRight || dir == Direction2.UpLeft || dir == Direction2.DownLeft; } /// @@ -116,21 +115,21 @@ namespace MLEM.Misc { /// The direction's offset public static Point Offset(this Direction2 dir) { switch (dir) { - case Up: + case Direction2.Up: return new Point(0, -1); - case Right: + case Direction2.Right: return new Point(1, 0); - case Down: + case Direction2.Down: return new Point(0, 1); - case Left: + case Direction2.Left: return new Point(-1, 0); - case UpRight: + case Direction2.UpRight: return new Point(1, -1); - case DownRight: + case Direction2.DownRight: return new Point(1, 1); - case DownLeft: + case Direction2.DownLeft: return new Point(-1, 1); - case UpLeft: + case Direction2.UpLeft: return new Point(-1, -1); default: return Point.Zero; @@ -156,24 +155,24 @@ namespace MLEM.Misc { /// The opposite of the direction public static Direction2 Opposite(this Direction2 dir) { switch (dir) { - case Up: - return Down; - case Right: - return Left; - case Down: - return Up; - case Left: - return Right; - case UpRight: - return DownLeft; - case DownRight: - return UpLeft; - case DownLeft: - return UpRight; - case UpLeft: - return DownRight; + case Direction2.Up: + return Direction2.Down; + case Direction2.Right: + return Direction2.Left; + case Direction2.Down: + return Direction2.Up; + case Direction2.Left: + return Direction2.Right; + case Direction2.UpRight: + return Direction2.DownLeft; + case Direction2.DownRight: + return Direction2.UpLeft; + case Direction2.DownLeft: + return Direction2.UpRight; + case Direction2.UpLeft: + return Direction2.DownRight; default: - return None; + return Direction2.None; } } @@ -194,9 +193,9 @@ namespace MLEM.Misc { /// Whether to rotate by 45 degrees. If this is false, the rotation is 90 degrees instead. /// The rotated direction public static Direction2 RotateCw(this Direction2 dir, bool fortyFiveDegrees = false) { - if (!ClockwiseLookup.TryGetValue(dir, out var dirIndex)) - return None; - return Clockwise[(dirIndex + (fortyFiveDegrees ? 1 : 2)) % Clockwise.Length]; + if (!Direction2Helper.ClockwiseLookup.TryGetValue(dir, out var dirIndex)) + return Direction2.None; + return Direction2Helper.Clockwise[(dirIndex + (fortyFiveDegrees ? 1 : 2)) % Direction2Helper.Clockwise.Length]; } /// @@ -206,10 +205,10 @@ namespace MLEM.Misc { /// Whether to rotate by 45 degrees. If this is false, the rotation is 90 degrees instead. /// The rotated direction public static Direction2 RotateCcw(this Direction2 dir, bool fortyFiveDegrees = false) { - if (!ClockwiseLookup.TryGetValue(dir, out var dirIndex)) - return None; + if (!Direction2Helper.ClockwiseLookup.TryGetValue(dir, out var dirIndex)) + return Direction2.None; var index = dirIndex - (fortyFiveDegrees ? 1 : 2); - return Clockwise[index < 0 ? index + Clockwise.Length : index]; + return Direction2Helper.Clockwise[index < 0 ? index + Direction2Helper.Clockwise.Length : index]; } /// @@ -219,11 +218,11 @@ namespace MLEM.Misc { /// The vector's direction public static Direction2 ToDirection(this Vector2 offset) { var offsetAngle = (float) Math.Atan2(offset.Y, offset.X); - foreach (var dir in AllExceptNone) { + foreach (var dir in Direction2Helper.AllExceptNone) { if (Math.Abs(dir.Angle() - offsetAngle) <= MathHelper.PiOver4 / 2) return dir; } - return None; + return Direction2.None; } /// @@ -234,10 +233,10 @@ namespace MLEM.Misc { /// The vector's direction public static Direction2 To90Direction(this Vector2 offset) { if (offset.X == 0 && offset.Y == 0) - return None; + return Direction2.None; if (Math.Abs(offset.X) > Math.Abs(offset.Y)) - return offset.X > 0 ? Right : Left; - return offset.Y > 0 ? Down : Up; + return offset.X > 0 ? Direction2.Right : Direction2.Left; + return offset.Y > 0 ? Direction2.Down : Direction2.Up; } /// @@ -247,17 +246,17 @@ namespace MLEM.Misc { /// The direction to rotate by /// The direction to use as the default direction /// The direction, rotated by the reference direction - public static Direction2 RotateBy(this Direction2 dir, Direction2 reference, Direction2 start = Up) { - if (!ClockwiseLookup.TryGetValue(reference, out var refIndex)) - return None; - if (!ClockwiseLookup.TryGetValue(start, out var startIndex)) - return None; - if (!ClockwiseLookup.TryGetValue(dir, out var dirIndex)) - return None; + public static Direction2 RotateBy(this Direction2 dir, Direction2 reference, Direction2 start = Direction2.Up) { + if (!Direction2Helper.ClockwiseLookup.TryGetValue(reference, out var refIndex)) + return Direction2.None; + if (!Direction2Helper.ClockwiseLookup.TryGetValue(start, out var startIndex)) + return Direction2.None; + if (!Direction2Helper.ClockwiseLookup.TryGetValue(dir, out var dirIndex)) + return Direction2.None; var diff = refIndex - startIndex; if (diff < 0) - diff += Clockwise.Length; - return Clockwise[(dirIndex + diff) % Clockwise.Length]; + diff += Direction2Helper.Clockwise.Length; + return Direction2Helper.Clockwise[(dirIndex + diff) % Direction2Helper.Clockwise.Length]; } } diff --git a/MLEM/Misc/Easings.cs b/MLEM/Misc/Easings.cs index 2c7ccd9..a0317ce 100644 --- a/MLEM/Misc/Easings.cs +++ b/MLEM/Misc/Easings.cs @@ -72,7 +72,7 @@ namespace MLEM.Misc { public static readonly Easing InOutElastic = p => p == 0 ? 0 : p == 1 ? 1 : p < 0.5 ? -((float) Math.Pow(2, 20 * p - 10) * (float) Math.Sin((20 * p - 11.125) * 1.39626340159546F)) / 2 : (float) Math.Pow(2, -20 * p + 10) * (float) Math.Sin((20 * p - 11.125) * 1.39626340159546F) / 2 + 1; /// https://easings.net/#easeInBounce - public static readonly Easing InBounce = p => 1 - OutBounce(1 - p); + public static readonly Easing InBounce = p => 1 - Easings.OutBounce(1 - p); /// https://easings.net/#easeOutBounce public static readonly Easing OutBounce = p => { const float n1 = 7.5625F; @@ -88,7 +88,7 @@ namespace MLEM.Misc { } }; /// https://easings.net/#easeInOutBounce - public static readonly Easing InOutBounce = p => p < 0.5 ? (1 - OutBounce(1 - 2 * p)) / 2 : (1 + OutBounce(2 * p - 1)) / 2; + public static readonly Easing InOutBounce = p => p < 0.5 ? (1 - Easings.OutBounce(1 - 2 * p)) / 2 : (1 + Easings.OutBounce(2 * p - 1)) / 2; /// /// Scales the input of an easing function, which is usually between 0 and 1, to a given minimum and maximum. diff --git a/MLEM/Misc/EnumHelper.cs b/MLEM/Misc/EnumHelper.cs index a984b36..5d104be 100644 --- a/MLEM/Misc/EnumHelper.cs +++ b/MLEM/Misc/EnumHelper.cs @@ -12,11 +12,11 @@ namespace MLEM.Misc { /// /// All values of the enum. /// - public static readonly Buttons[] Buttons = GetValues().ToArray(); + public static readonly Buttons[] Buttons = EnumHelper.GetValues().ToArray(); /// /// All values of the enum. /// - public static readonly Keys[] Keys = GetValues().ToArray(); + public static readonly Keys[] Keys = EnumHelper.GetValues().ToArray(); /// /// Returns all of the values of the given enum type. diff --git a/MLEM/Misc/MlemPlatform.cs b/MLEM/Misc/MlemPlatform.cs index 8141104..26fab7a 100644 --- a/MLEM/Misc/MlemPlatform.cs +++ b/MLEM/Misc/MlemPlatform.cs @@ -50,7 +50,7 @@ namespace MLEM.Misc { /// /// If is null public static void EnsureExists() { - if (Current == null) + if (MlemPlatform.Current == null) throw new InvalidOperationException("MlemPlatform was not initialized. For more information, see the MlemPlatform class or https://mlem.ellpeck.de/api/MLEM.Misc.MlemPlatform"); } diff --git a/MLEM/Misc/Padding.cs b/MLEM/Misc/Padding.cs index 1dcd96b..c71103e 100644 --- a/MLEM/Misc/Padding.cs +++ b/MLEM/Misc/Padding.cs @@ -135,9 +135,9 @@ namespace MLEM.Misc { /// A 32-bit signed integer that is the hash code for this instance. public override int GetHashCode() { var hashCode = this.Left.GetHashCode(); - hashCode = (hashCode * 397) ^ this.Right.GetHashCode(); - hashCode = (hashCode * 397) ^ this.Top.GetHashCode(); - hashCode = (hashCode * 397) ^ this.Bottom.GetHashCode(); + hashCode = hashCode * 397 ^ this.Right.GetHashCode(); + hashCode = hashCode * 397 ^ this.Top.GetHashCode(); + hashCode = hashCode * 397 ^ this.Bottom.GetHashCode(); return hashCode; } diff --git a/MLEM/Misc/RectangleF.cs b/MLEM/Misc/RectangleF.cs index 7df4440..c10bad2 100644 --- a/MLEM/Misc/RectangleF.cs +++ b/MLEM/Misc/RectangleF.cs @@ -248,7 +248,7 @@ namespace MLEM.Misc { var num2 = Math.Min(value1.Y + value1.Height, value2.Y + value2.Height); return new RectangleF(x, y, num1 - x, num2 - y); } else { - return Empty; + return RectangleF.Empty; } } diff --git a/MLEM/Pathfinding/AStar.cs b/MLEM/Pathfinding/AStar.cs index bc719c3..24f21cf 100644 --- a/MLEM/Pathfinding/AStar.cs +++ b/MLEM/Pathfinding/AStar.cs @@ -14,6 +14,7 @@ namespace MLEM.Pathfinding { /// /// A value that represents an infinite path cost, or a cost for a location that cannot possibly be reached. /// + [Obsolete("This field is deprecated. Use float.PositiveInfinity or float.MaxValue instead.")] public const float InfiniteCost = float.PositiveInfinity; /// /// The array of all directions that will be checked for path finding. @@ -110,7 +111,7 @@ namespace MLEM.Pathfinding { closed.Add(current.Pos, current); if (current.Pos.Equals(goal)) { - ret = CompilePath(current); + ret = AStar.CompilePath(current); break; } @@ -167,7 +168,7 @@ namespace MLEM.Pathfinding { /// /// A cost function for a given path finding position. /// If a path point should have the default cost, should be returned. - /// If a path point should be unreachable, should be returned. + /// If a path point should be unreachable, or should be returned. /// /// The current position in the path /// The position we're trying to reach from the current position @@ -218,7 +219,7 @@ namespace MLEM.Pathfinding { /// An object to compare with this object. /// true if the current object is equal to the other parameter; otherwise, false. public bool Equals(PathPoint other) { - return ReferenceEquals(this, other) || EqualityComparer.Default.Equals(this.Pos, other.Pos); + return object.ReferenceEquals(this, other) || EqualityComparer.Default.Equals(this.Pos, other.Pos); } /// Indicates whether this instance and a specified object are equal. diff --git a/MLEM/Pathfinding/AStar2.cs b/MLEM/Pathfinding/AStar2.cs index a0772c6..d3fc0f4 100644 --- a/MLEM/Pathfinding/AStar2.cs +++ b/MLEM/Pathfinding/AStar2.cs @@ -14,7 +14,7 @@ namespace MLEM.Pathfinding { /// public AStar2(GetCost defaultCostFunction, bool defaultAllowDiagonals, float defaultCost = 1, int defaultMaxTries = 10000) : - base(AllDirs, AdjacentDirs, defaultCostFunction, defaultAllowDiagonals, defaultCost, defaultMaxTries) {} + base(AStar2.AllDirs, AStar2.AdjacentDirs, defaultCostFunction, defaultAllowDiagonals, defaultCost, defaultMaxTries) {} /// protected override Point AddPositions(Point first, Point second) { diff --git a/MLEM/Pathfinding/AStar3.cs b/MLEM/Pathfinding/AStar3.cs index 7c90908..8314796 100644 --- a/MLEM/Pathfinding/AStar3.cs +++ b/MLEM/Pathfinding/AStar3.cs @@ -30,12 +30,12 @@ namespace MLEM.Pathfinding { } } } - AllDirs = dirs.ToArray(); + AStar3.AllDirs = dirs.ToArray(); } /// public AStar3(GetCost defaultCostFunction, bool defaultAllowDiagonals, float defaultCost = 1, int defaultMaxTries = 10000) : - base(AllDirs, AdjacentDirs, defaultCostFunction, defaultAllowDiagonals, defaultCost, defaultMaxTries) {} + base(AStar3.AllDirs, AStar3.AdjacentDirs, defaultCostFunction, defaultAllowDiagonals, defaultCost, defaultMaxTries) {} /// protected override Vector3 AddPositions(Vector3 first, Vector3 second) { diff --git a/MLEM/Sound/SoundEffectInfo.cs b/MLEM/Sound/SoundEffectInfo.cs index 9ca9115..510f589 100644 --- a/MLEM/Sound/SoundEffectInfo.cs +++ b/MLEM/Sound/SoundEffectInfo.cs @@ -57,7 +57,7 @@ namespace MLEM.Sound { public float GetRandomPitch() { if (this.RandomPitchModifier == 0) return this.Pitch; - return this.Pitch + ((float) Random.NextDouble() * 2 - 1) * this.RandomPitchModifier; + return this.Pitch + ((float) SoundEffectInfo.Random.NextDouble() * 2 - 1) * this.RandomPitchModifier; } /// diff --git a/Sandbox/Content/Fonts/TestFont.spritefont b/Sandbox/Content/Fonts/TestFont.spritefont index b44bd5d..f4dd12f 100644 --- a/Sandbox/Content/Fonts/TestFont.spritefont +++ b/Sandbox/Content/Fonts/TestFont.spritefont @@ -6,55 +6,55 @@ of the font in your game, and to change the characters which are available to dr with. --> - - - - Cadman_Roman.otf - - - 32 - - - 0 - - - true - - - - - - * - - - - - - ɏ - - - + + + + Cadman_Roman.otf + + + 32 + + + 0 + + + true + + + + + + * + + + + + + ɏ + + + diff --git a/Sandbox/GameImpl.cs b/Sandbox/GameImpl.cs index 70fd655..aaa1ab0 100644 --- a/Sandbox/GameImpl.cs +++ b/Sandbox/GameImpl.cs @@ -54,7 +54,7 @@ namespace Sandbox { this.Components.Add(this.rawContent = new RawContentManager(this.Services)); - this.map = LoadContent("Tiled/Map"); + this.map = MlemGame.LoadContent("Tiled/Map"); this.mapRenderer = new IndividualTiledMapRenderer(this.map); this.collisions = new TiledMapCollisions(this.map); @@ -78,7 +78,7 @@ namespace Sandbox { //var font = new GenericSpriteFont(LoadContent("Fonts/TestFont")); //var font = new GenericBitmapFont(LoadContent("Fonts/Regular")); var font = new GenericStashFont(system.GetFont(32)); - var spriteFont = new GenericSpriteFont(LoadContent("Fonts/TestFont")); + var spriteFont = new GenericSpriteFont(MlemGame.LoadContent("Fonts/TestFont")); this.UiSystem.Style = new UntexturedStyle(this.SpriteBatch) { Font = font, TextScale = 0.5F, @@ -277,7 +277,7 @@ namespace Sandbox { this.OnDraw += (g, time) => { const string testString = "This is a\ntest string\n\twith long lines.\nLet's write some more stuff. Let's\r\nsplit lines weirdly."; - if (Input.IsKeyPressed(Keys.I)) { + if (MlemGame.Input.IsKeyPressed(Keys.I)) { index++; if (index == 1) { scale = 2; @@ -295,7 +295,7 @@ namespace Sandbox { } this.SpriteBatch.Begin(); - if (Input.IsKeyDown(Keys.LeftShift)) { + if (MlemGame.Input.IsKeyDown(Keys.LeftShift)) { this.SpriteBatch.DrawString(regularFont, testString, pos, Color.Red, rotation, origin, scale, effects, 0); } else { genericFont.DrawString(this.SpriteBatch, testString, pos, Color.Green, rotation, origin, scale, effects, 0); @@ -363,8 +363,8 @@ namespace Sandbox { /*if (Input.InputsDown.Length > 0) Console.WriteLine("Down: " + string.Join(", ", Input.InputsDown));*/ - if (Input.InputsPressed.Length > 0) - Console.WriteLine("Pressed: " + string.Join(", ", Input.InputsPressed)); + if (MlemGame.Input.InputsPressed.Length > 0) + Console.WriteLine("Pressed: " + string.Join(", ", MlemGame.Input.InputsPressed)); } protected override void DoDraw(GameTime gameTime) { diff --git a/Tests/DataTests.cs b/Tests/DataTests.cs index 7073ced..1bac8cc 100644 --- a/Tests/DataTests.cs +++ b/Tests/DataTests.cs @@ -7,7 +7,6 @@ using MLEM.Data.Json; using MLEM.Misc; using Newtonsoft.Json; using NUnit.Framework; -using static MLEM.Data.DynamicEnum; using Vector2 = Microsoft.Xna.Framework.Vector2; namespace Tests { @@ -41,27 +40,27 @@ namespace Tests { public void TestDynamicEnum() { var flags = new TestEnum[100]; for (var i = 0; i < flags.Length; i++) - flags[i] = AddFlag("Flag" + i); + flags[i] = DynamicEnum.AddFlag("Flag" + i); - Assert.AreEqual(GetValue(flags[7]), BigInteger.One << 7); - Assert.AreEqual(GetEnumValue(BigInteger.One << 75), flags[75]); + Assert.AreEqual(DynamicEnum.GetValue(flags[7]), BigInteger.One << 7); + Assert.AreEqual(DynamicEnum.GetEnumValue(BigInteger.One << 75), flags[75]); - Assert.AreEqual(GetValue(Or(flags[2], flags[17])), (BigInteger.One << 2) | (BigInteger.One << 17)); - Assert.AreEqual(GetValue(And(flags[2], flags[3])), BigInteger.Zero); - Assert.AreEqual(And(Or(flags[24], flags[52]), Or(flags[52], flags[75])), flags[52]); - Assert.AreEqual(Xor(Or(flags[85], flags[73]), flags[73]), flags[85]); - Assert.AreEqual(Xor(Or(flags[85], Or(flags[73], flags[12])), flags[73]), Or(flags[85], flags[12])); - Assert.AreEqual(GetValue(Neg(flags[74])), ~(BigInteger.One << 74)); + Assert.AreEqual(DynamicEnum.GetValue(DynamicEnum.Or(flags[2], flags[17])), BigInteger.One << 2 | BigInteger.One << 17); + Assert.AreEqual(DynamicEnum.GetValue(DynamicEnum.And(flags[2], flags[3])), BigInteger.Zero); + Assert.AreEqual(DynamicEnum.And(DynamicEnum.Or(flags[24], flags[52]), DynamicEnum.Or(flags[52], flags[75])), flags[52]); + Assert.AreEqual(DynamicEnum.Xor(DynamicEnum.Or(flags[85], flags[73]), flags[73]), flags[85]); + Assert.AreEqual(DynamicEnum.Xor(DynamicEnum.Or(flags[85], DynamicEnum.Or(flags[73], flags[12])), flags[73]), DynamicEnum.Or(flags[85], flags[12])); + Assert.AreEqual(DynamicEnum.GetValue(DynamicEnum.Neg(flags[74])), ~(BigInteger.One << 74)); - Assert.AreEqual(Or(flags[24], flags[52]).HasFlag(flags[24]), true); - Assert.AreEqual(Or(flags[24], flags[52]).HasAnyFlag(flags[24]), true); - Assert.AreEqual(Or(flags[24], flags[52]).HasFlag(Or(flags[24], flags[26])), false); - Assert.AreEqual(Or(flags[24], flags[52]).HasAnyFlag(Or(flags[24], flags[26])), true); + Assert.AreEqual(DynamicEnum.Or(flags[24], flags[52]).HasFlag(flags[24]), true); + Assert.AreEqual(DynamicEnum.Or(flags[24], flags[52]).HasAnyFlag(flags[24]), true); + Assert.AreEqual(DynamicEnum.Or(flags[24], flags[52]).HasFlag(DynamicEnum.Or(flags[24], flags[26])), false); + Assert.AreEqual(DynamicEnum.Or(flags[24], flags[52]).HasAnyFlag(DynamicEnum.Or(flags[24], flags[26])), true); - Assert.AreEqual(Parse("Flag24"), flags[24]); - Assert.AreEqual(Parse("Flag24 | Flag43"), Or(flags[24], flags[43])); + Assert.AreEqual(DynamicEnum.Parse("Flag24"), flags[24]); + Assert.AreEqual(DynamicEnum.Parse("Flag24 | Flag43"), DynamicEnum.Or(flags[24], flags[43])); Assert.AreEqual(flags[24].ToString(), "Flag24"); - Assert.AreEqual(Or(flags[24], flags[43]).ToString(), "Flag24 | Flag43"); + Assert.AreEqual(DynamicEnum.Or(flags[24], flags[43]).ToString(), "Flag24 | Flag43"); } [Test] @@ -71,14 +70,14 @@ namespace Tests { // normal generic data holder should crush the time span down to a string due to its custom serializer var data = new GenericDataHolder(); data.SetData("Time", TimeSpan.FromMinutes(5)); - var read = SerializeAndDeserialize(serializer, data); + var read = DataTests.SerializeAndDeserialize(serializer, data); Assert.IsNotInstanceOf(read.GetData("Time")); Assert.Throws(() => read.GetData("Time")); // json type safe generic data holder should wrap the time span to ensure that it stays a time span var safeData = new JsonTypeSafeGenericDataHolder(); safeData.SetData("Time", TimeSpan.FromMinutes(5)); - var safeRead = SerializeAndDeserialize(serializer, safeData); + var safeRead = DataTests.SerializeAndDeserialize(serializer, safeData); Assert.IsInstanceOf(safeRead.GetData("Time")); Assert.DoesNotThrow(() => safeRead.GetData("Time")); } @@ -99,11 +98,11 @@ namespace Tests { public TestObject(Vector2 test, string test2) {} protected bool Equals(TestObject other) { - return this.Vec.Equals(other.Vec) && this.Point.Equals(other.Point) && Equals(this.OtherTest, other.OtherTest) && this.Dir == other.Dir; + return this.Vec.Equals(other.Vec) && this.Point.Equals(other.Point) && object.Equals(this.OtherTest, other.OtherTest) && this.Dir == other.Dir; } public override bool Equals(object obj) { - return ReferenceEquals(this, obj) || obj is TestObject other && this.Equals(other); + return object.ReferenceEquals(this, obj) || obj is TestObject other && this.Equals(other); } public override int GetHashCode() { diff --git a/Tests/DirectionTests.cs b/Tests/DirectionTests.cs index 56240ac..bed22bf 100644 --- a/Tests/DirectionTests.cs +++ b/Tests/DirectionTests.cs @@ -1,58 +1,57 @@ using Microsoft.Xna.Framework; using MLEM.Misc; using NUnit.Framework; -using static MLEM.Misc.Direction2; namespace Tests { public class DirectionTests { [Test] public void TestDirections() { - Assert.AreEqual(new Vector2(0.5F, 0.5F).ToDirection(), DownRight); - Assert.AreEqual(new Vector2(0.25F, 0.5F).ToDirection(), DownRight); - Assert.AreEqual(new Vector2(0.15F, 0.5F).ToDirection(), Down); + Assert.AreEqual(new Vector2(0.5F, 0.5F).ToDirection(), Direction2.DownRight); + Assert.AreEqual(new Vector2(0.25F, 0.5F).ToDirection(), Direction2.DownRight); + Assert.AreEqual(new Vector2(0.15F, 0.5F).ToDirection(), Direction2.Down); } [Test] public void Test90Directions() { - Assert.AreEqual(new Vector2(0.75F, 0.5F).To90Direction(), Right); - Assert.AreEqual(new Vector2(0.5F, 0.5F).To90Direction(), Down); - Assert.AreEqual(new Vector2(0.25F, 0.5F).To90Direction(), Down); + Assert.AreEqual(new Vector2(0.75F, 0.5F).To90Direction(), Direction2.Right); + Assert.AreEqual(new Vector2(0.5F, 0.5F).To90Direction(), Direction2.Down); + Assert.AreEqual(new Vector2(0.25F, 0.5F).To90Direction(), Direction2.Down); } [Test] public void TestRotations() { // rotate cw - Assert.AreEqual(Up.RotateCw(), Right); - Assert.AreEqual(Up.RotateCw(true), UpRight); - Assert.AreEqual(Left.RotateCw(), Up); - Assert.AreEqual(UpLeft.RotateCw(), UpRight); + Assert.AreEqual(Direction2.Up.RotateCw(), Direction2.Right); + Assert.AreEqual(Direction2.Up.RotateCw(true), Direction2.UpRight); + Assert.AreEqual(Direction2.Left.RotateCw(), Direction2.Up); + Assert.AreEqual(Direction2.UpLeft.RotateCw(), Direction2.UpRight); // rotate ccw - Assert.AreEqual(Up.RotateCcw(), Left); - Assert.AreEqual(Up.RotateCcw(true), UpLeft); - Assert.AreEqual(Left.RotateCcw(), Down); - Assert.AreEqual(UpLeft.RotateCcw(), DownLeft); + Assert.AreEqual(Direction2.Up.RotateCcw(), Direction2.Left); + Assert.AreEqual(Direction2.Up.RotateCcw(true), Direction2.UpLeft); + Assert.AreEqual(Direction2.Left.RotateCcw(), Direction2.Down); + Assert.AreEqual(Direction2.UpLeft.RotateCcw(), Direction2.DownLeft); // rotate 360 degrees foreach (var dir in Direction2Helper.AllExceptNone) { - Assert.AreEqual(RotateMultipleTimes(dir, true, false, 4), dir); - Assert.AreEqual(RotateMultipleTimes(dir, true, true, 8), dir); - Assert.AreEqual(RotateMultipleTimes(dir, false, false, 4), dir); - Assert.AreEqual(RotateMultipleTimes(dir, false, true, 8), dir); + Assert.AreEqual(DirectionTests.RotateMultipleTimes(dir, true, false, 4), dir); + Assert.AreEqual(DirectionTests.RotateMultipleTimes(dir, true, true, 8), dir); + Assert.AreEqual(DirectionTests.RotateMultipleTimes(dir, false, false, 4), dir); + Assert.AreEqual(DirectionTests.RotateMultipleTimes(dir, false, true, 8), dir); } // rotate by with start Up - Assert.AreEqual(Right.RotateBy(Right), Down); - Assert.AreEqual(Right.RotateBy(Down), Left); - Assert.AreEqual(Right.RotateBy(Left), Up); - Assert.AreEqual(Right.RotateBy(Up), Right); + Assert.AreEqual(Direction2.Right.RotateBy(Direction2.Right), Direction2.Down); + Assert.AreEqual(Direction2.Right.RotateBy(Direction2.Down), Direction2.Left); + Assert.AreEqual(Direction2.Right.RotateBy(Direction2.Left), Direction2.Up); + Assert.AreEqual(Direction2.Right.RotateBy(Direction2.Up), Direction2.Right); // rotate by with start Left - Assert.AreEqual(Up.RotateBy(Right, Left), Down); - Assert.AreEqual(Up.RotateBy(Down, Left), Left); - Assert.AreEqual(Up.RotateBy(Left, Left), Up); - Assert.AreEqual(Up.RotateBy(Up, Left), Right); + Assert.AreEqual(Direction2.Up.RotateBy(Direction2.Right, Direction2.Left), Direction2.Down); + Assert.AreEqual(Direction2.Up.RotateBy(Direction2.Down, Direction2.Left), Direction2.Left); + Assert.AreEqual(Direction2.Up.RotateBy(Direction2.Left, Direction2.Left), Direction2.Up); + Assert.AreEqual(Direction2.Up.RotateBy(Direction2.Up, Direction2.Left), Direction2.Right); } private static Direction2 RotateMultipleTimes(Direction2 dir, bool clockwise, bool fortyFiveDegrees, int times) { diff --git a/Tests/PathfindingTests.cs b/Tests/PathfindingTests.cs index 343cde1..05b8ed5 100644 --- a/Tests/PathfindingTests.cs +++ b/Tests/PathfindingTests.cs @@ -16,12 +16,12 @@ namespace Tests { "XXXX" }; - var noDiagonals = FindPathInArea(new Point(1, 1), new Point(2, 2), area, false).ToArray(); + var noDiagonals = PathfindingTests.FindPathInArea(new Point(1, 1), new Point(2, 2), area, false).ToArray(); Assert.AreEqual(noDiagonals.Length, 3); Assert.AreEqual(noDiagonals[0], new Point(1, 1)); Assert.AreEqual(noDiagonals[2], new Point(2, 2)); - var diagonals = FindPathInArea(new Point(1, 1), new Point(2, 2), area, true).ToArray(); + var diagonals = PathfindingTests.FindPathInArea(new Point(1, 1), new Point(2, 2), area, true).ToArray(); Assert.AreEqual(diagonals.Length, 2); Assert.AreEqual(diagonals[0], new Point(1, 1)); Assert.AreEqual(diagonals[1], new Point(2, 2)); @@ -36,11 +36,11 @@ namespace Tests { "XXXXXXXX" }; - var firstPath = FindPathInArea(new Point(1, 1), new Point(3, 1), area, false).ToArray(); + var firstPath = PathfindingTests.FindPathInArea(new Point(1, 1), new Point(3, 1), area, false).ToArray(); var firstExpected = new[] {new Point(1, 1), new Point(1, 2), new Point(2, 2), new Point(3, 2), new Point(3, 1)}; Assert.AreEqual(firstPath, firstExpected); - var secondPath = FindPathInArea(new Point(1, 1), new Point(5, 2), area, false).ToArray(); + var secondPath = PathfindingTests.FindPathInArea(new Point(1, 1), new Point(5, 2), area, false).ToArray(); var secondExpected = firstExpected.Concat(new[] {new Point(4, 1), new Point(5, 1), new Point(5, 2)}).ToArray(); Assert.AreEqual(secondPath, secondExpected); } @@ -55,15 +55,15 @@ namespace Tests { "XXXX" }; // non-diagonal pathfinding should get stuck in the corner - Assert.IsNull(FindPathInArea(new Point(1, 1), new Point(2, 3), area, false)); + Assert.IsNull(PathfindingTests.FindPathInArea(new Point(1, 1), new Point(2, 3), area, false)); // diagonal pathfinding should be able to cross the diagonal gap - Assert.IsNotNull(FindPathInArea(new Point(1, 1), new Point(2, 3), area, true)); + Assert.IsNotNull(PathfindingTests.FindPathInArea(new Point(1, 1), new Point(2, 3), area, true)); } private static Stack FindPathInArea(Point start, Point end, IEnumerable area, bool allowDiagonals) { var costs = area.Select(s => s.Select(c => c switch { ' ' => 1, - 'X' => AStar2.InfiniteCost, + 'X' => float.PositiveInfinity, _ => (float) char.GetNumericValue(c) }).ToArray()).ToArray(); var pathFinder = new AStar2((p1, p2) => costs[p2.Y][p2.X], allowDiagonals); diff --git a/Tests/TestGame.cs b/Tests/TestGame.cs index 22c8a02..487febf 100644 --- a/Tests/TestGame.cs +++ b/Tests/TestGame.cs @@ -13,7 +13,7 @@ namespace Tests { protected override void LoadContent() { base.LoadContent(); this.RawContent = new RawContentManager(this.Services, this.Content.RootDirectory); - this.UiSystem.Style.Font = new GenericSpriteFont(LoadContent("TestFont")); + this.UiSystem.Style.Font = new GenericSpriteFont(MlemGame.LoadContent("TestFont")); } public static TestGame Create() { diff --git a/Tests/TexturePackerTests.cs b/Tests/TexturePackerTests.cs index e16006a..7a7683d 100644 --- a/Tests/TexturePackerTests.cs +++ b/Tests/TexturePackerTests.cs @@ -43,8 +43,8 @@ namespace Tests { [Test] public void TestDisposal() { using var packer = new RuntimeTexturePacker(128, disposeTextures: true); - packer.Add(new TextureRegion(this.disposedTestTexture), StubResult); - packer.Add(new TextureRegion(this.disposedTestTexture, 0, 0, 8, 8), StubResult); + packer.Add(new TextureRegion(this.disposedTestTexture), TexturePackerTests.StubResult); + packer.Add(new TextureRegion(this.disposedTestTexture, 0, 0, 8, 8), TexturePackerTests.StubResult); packer.Pack(this.game.GraphicsDevice); Assert.True(this.disposedTestTexture.IsDisposed); Assert.False(packer.PackedTexture.IsDisposed); @@ -55,26 +55,26 @@ namespace Tests { // test forced max width using var packer = new RuntimeTexturePacker(128); Assert.Throws(() => { - packer.Add(new TextureRegion(this.testTexture, 0, 0, 256, 128), StubResult); + packer.Add(new TextureRegion(this.testTexture, 0, 0, 256, 128), TexturePackerTests.StubResult); }); // test auto-expanding width using var packer2 = new RuntimeTexturePacker(128, true); Assert.DoesNotThrow(() => { - packer2.Add(new TextureRegion(this.testTexture, 0, 0, 256, 128), StubResult); + packer2.Add(new TextureRegion(this.testTexture, 0, 0, 256, 128), TexturePackerTests.StubResult); }); packer2.Pack(this.game.GraphicsDevice); // test power of two forcing using var packer3 = new RuntimeTexturePacker(128, forcePowerOfTwo: true); - packer3.Add(new TextureRegion(this.testTexture, 0, 0, 37, 170), StubResult); + packer3.Add(new TextureRegion(this.testTexture, 0, 0, 37, 170), TexturePackerTests.StubResult); packer3.Pack(this.game.GraphicsDevice); Assert.AreEqual(64, packer3.PackedTexture.Width); Assert.AreEqual(256, packer3.PackedTexture.Height); // test square forcing using var packer4 = new RuntimeTexturePacker(128, forceSquare: true); - packer4.Add(new TextureRegion(this.testTexture, 0, 0, 37, 170), StubResult); + packer4.Add(new TextureRegion(this.testTexture, 0, 0, 37, 170), TexturePackerTests.StubResult); packer4.Pack(this.game.GraphicsDevice); Assert.AreEqual(170, packer4.PackedTexture.Width); Assert.AreEqual(170, packer4.PackedTexture.Height);