From 1d0aab9166c442ce7266238e7b56ff28204d4a92 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sat, 11 Aug 2018 20:01:32 +0300 Subject: [PATCH 01/80] vs --- .gitignore | 332 +++++++++++++++++++++++++++++++++++++ MagicStorage.csproj | 132 +++++++++++++++ MagicStorage.sln | 25 +++ Properties/AssemblyInfo.cs | 36 ++++ 4 files changed, 525 insertions(+) create mode 100644 .gitignore create mode 100644 MagicStorage.csproj create mode 100644 MagicStorage.sln create mode 100644 Properties/AssemblyInfo.cs diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..94b41b91 --- /dev/null +++ b/.gitignore @@ -0,0 +1,332 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ diff --git a/MagicStorage.csproj b/MagicStorage.csproj new file mode 100644 index 00000000..518109fc --- /dev/null +++ b/MagicStorage.csproj @@ -0,0 +1,132 @@ + + + + + Debug + AnyCPU + {162C8AA5-FF1C-4357-AEED-FAF522C56FEE} + Library + Properties + MagicStorage + MagicStorage + v4.7.1 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + C:\Program Files (x86)\Steam\steamapps\common\Terraria\References\ReLogic.dll + + + + + + + + + + + C:\Program Files (x86)\Steam\steamapps\common\Terraria\Terraria.exe + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + "C:\Program Files (x86)\Steam\steamapps\common\Terraria\tModLoaderServer.exe" -build "$(ProjectDir.TrimEnd('\'))" + + \ No newline at end of file diff --git a/MagicStorage.sln b/MagicStorage.sln new file mode 100644 index 00000000..bdc43f3c --- /dev/null +++ b/MagicStorage.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27703.2026 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MagicStorage", "MagicStorage.csproj", "{162C8AA5-FF1C-4357-AEED-FAF522C56FEE}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {162C8AA5-FF1C-4357-AEED-FAF522C56FEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {162C8AA5-FF1C-4357-AEED-FAF522C56FEE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {162C8AA5-FF1C-4357-AEED-FAF522C56FEE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {162C8AA5-FF1C-4357-AEED-FAF522C56FEE}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {BE578426-8436-495A-990A-62B26E41AEAB} + EndGlobalSection +EndGlobal diff --git a/Properties/AssemblyInfo.cs b/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..cbf5bf2b --- /dev/null +++ b/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("MagicStorage")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MagicStorage")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("162c8aa5-ff1c-4357-aeed-faf522c56fee")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] From 17fa9444681fd7e7b5f0f09e397f5e085a5cec60 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sat, 11 Aug 2018 20:08:15 +0300 Subject: [PATCH 02/80] lower prices --- Items/CraftingAccess.cs | 4 ++-- Items/Locator.cs | 2 +- Items/LocatorDisk.cs | 2 +- Items/PortableAccess.cs | 6 +++--- Items/RemoteAccess.cs | 4 ++-- Items/StorageAccess.cs | 4 ++-- Items/StorageHeart.cs | 4 ++-- 7 files changed, 13 insertions(+), 13 deletions(-) diff --git a/Items/CraftingAccess.cs b/Items/CraftingAccess.cs index 5ca35a73..0412490e 100644 --- a/Items/CraftingAccess.cs +++ b/Items/CraftingAccess.cs @@ -40,11 +40,11 @@ public override void AddRecipes() recipe.AddRecipeGroup("MagicStorage:AnyDiamond", 3); if (MagicStorage.legendMod == null) { - recipe.AddIngredient(ItemID.Sapphire, 7); + recipe.AddIngredient(ItemID.Sapphire, 3); } else { - recipe.AddRecipeGroup("MagicStorage:AnySapphire", 7); + recipe.AddRecipeGroup("MagicStorage:AnySapphire", 3); } recipe.AddTile(TileID.WorkBenches); recipe.SetResult(this); diff --git a/Items/Locator.cs b/Items/Locator.cs index fc19d515..6f459bfc 100644 --- a/Items/Locator.cs +++ b/Items/Locator.cs @@ -72,7 +72,7 @@ public override void AddRecipes() { ModRecipe recipe = new ModRecipe(mod); recipe.AddIngredient(ItemID.MeteoriteBar, 10); - recipe.AddIngredient(ItemID.Amber, 5); + recipe.AddIngredient(ItemID.Amber, 2); recipe.AddTile(TileID.Anvils); recipe.SetResult(this); recipe.AddRecipe(); diff --git a/Items/LocatorDisk.cs b/Items/LocatorDisk.cs index ae6c6474..90d2bd91 100644 --- a/Items/LocatorDisk.cs +++ b/Items/LocatorDisk.cs @@ -46,7 +46,7 @@ public override void AddRecipes() { ModRecipe recipe = new ModRecipe(mod); recipe.AddIngredient(ItemID.MartianConduitPlating, 25); - recipe.AddIngredient(ItemID.LunarBar, 5); + recipe.AddIngredient(ItemID.LunarBar, 2); recipe.AddTile(TileID.LunarCraftingStation); recipe.SetResult(this); recipe.AddRecipe(); diff --git a/Items/PortableAccess.cs b/Items/PortableAccess.cs index 67853f26..42a2cfa8 100644 --- a/Items/PortableAccess.cs +++ b/Items/PortableAccess.cs @@ -134,7 +134,7 @@ public override void AddRecipes() recipe.AddIngredient(mod, "LocatorDisk"); recipe.AddIngredient(mod, "RadiantJewel"); recipe.AddRecipeGroup("MagicStorage:AnyDiamond", 3); - recipe.AddIngredient(ItemID.Ruby, 7); + recipe.AddIngredient(ItemID.Ruby, 3); recipe.AddTile(TileID.LunarCraftingStation); recipe.SetResult(this); recipe.AddRecipe(); @@ -146,7 +146,7 @@ public override void AddRecipes() recipe.AddIngredient(mod, "LocatorDisk"); recipe.AddIngredient(otherMod, "InfinityCrystal"); recipe.AddRecipeGroup("MagicStorage:AnyDiamond", 3); - recipe.AddIngredient(ItemID.Ruby, 7); + recipe.AddIngredient(ItemID.Ruby, 3); recipe.AddTile(otherMod, "PuriumAnvil"); recipe.SetResult(this); recipe.AddRecipe(); @@ -159,7 +159,7 @@ public override void AddRecipes() recipe.AddIngredient(mod, "LocatorDisk"); recipe.AddIngredient(otherMod, "CosmiliteBar", 20); recipe.AddRecipeGroup("MagicStorage:AnyDiamond", 3); - recipe.AddIngredient(ItemID.Ruby, 7); + recipe.AddIngredient(ItemID.Ruby, 3); recipe.AddTile(TileID.LunarCraftingStation); recipe.SetResult(this); recipe.AddRecipe(); diff --git a/Items/RemoteAccess.cs b/Items/RemoteAccess.cs index 80ecc6f8..4a67f090 100644 --- a/Items/RemoteAccess.cs +++ b/Items/RemoteAccess.cs @@ -40,11 +40,11 @@ public override void AddRecipes() recipe.AddRecipeGroup("MagicStorage:AnyDiamond", 3); if (MagicStorage.legendMod == null) { - recipe.AddIngredient(ItemID.Ruby, 7); + recipe.AddIngredient(ItemID.Ruby, 3); } else { - recipe.AddRecipeGroup("MagicStorage:AnyRuby", 7); + recipe.AddRecipeGroup("MagicStorage:AnyRuby", 3); } recipe.AddTile(TileID.WorkBenches); recipe.SetResult(this); diff --git a/Items/StorageAccess.cs b/Items/StorageAccess.cs index dffcf601..208b01cc 100644 --- a/Items/StorageAccess.cs +++ b/Items/StorageAccess.cs @@ -39,11 +39,11 @@ public override void AddRecipes() recipe.AddRecipeGroup("MagicStorage:AnyDiamond", 1); if (MagicStorage.legendMod == null) { - recipe.AddIngredient(ItemID.Topaz, 7); + recipe.AddIngredient(ItemID.Topaz, 3); } else { - recipe.AddRecipeGroup("MagicStorage:AnyTopaz", 7); + recipe.AddRecipeGroup("MagicStorage:AnyTopaz", 3); } recipe.AddTile(TileID.WorkBenches); recipe.SetResult(this); diff --git a/Items/StorageHeart.cs b/Items/StorageHeart.cs index bb87de15..1f06451b 100644 --- a/Items/StorageHeart.cs +++ b/Items/StorageHeart.cs @@ -39,11 +39,11 @@ public override void AddRecipes() recipe.AddRecipeGroup("MagicStorage:AnyDiamond", 3); if (MagicStorage.legendMod == null) { - recipe.AddIngredient(ItemID.Emerald, 7); + recipe.AddIngredient(ItemID.Emerald, 3); } else { - recipe.AddRecipeGroup("MagicStorage:AnyEmerald", 7); + recipe.AddRecipeGroup("MagicStorage:AnyEmerald", 3); } recipe.AddTile(TileID.WorkBenches); recipe.SetResult(this); From cb84aa813cd1e558fa1b464f9c1e469216c4a67d Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sat, 11 Aug 2018 20:08:29 +0300 Subject: [PATCH 03/80] build obj --- build.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/build.txt b/build.txt index 57c143a4..ab94e496 100644 --- a/build.txt +++ b/build.txt @@ -5,4 +5,5 @@ homepage = https://forums.terraria.org/index.php?threads/magic-storage.56294/ hideCode = false hideResources = false includeSource = true -buildIgnore = OldArt\*, .git\* \ No newline at end of file +includePDB = true +buildIgnore = OldArt\*, .git\*, obj\* \ No newline at end of file From 358e4c1ad2d186c08130b10c477c28a79b1eadd9 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sat, 11 Aug 2018 20:16:44 +0300 Subject: [PATCH 04/80] 2 crafting list modes - new or all items, but only from known components, integration with ItemList mod, right click to blacklist recipe (hidden from all lists) --- CraftingGUI.cs | 3009 +++++++++++++++++++++++----------------------- ItemHideList.cs | 43 + MagicStorage.cs | 4 +- StoragePlayer.cs | 465 +++---- 4 files changed, 1830 insertions(+), 1691 deletions(-) create mode 100644 ItemHideList.cs diff --git a/CraftingGUI.cs b/CraftingGUI.cs index e39a3a86..8906960b 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -1,1474 +1,1537 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using Microsoft.Xna.Framework.Input; -using Terraria; -using Terraria.DataStructures; -using Terraria.GameContent.UI.Elements; -using Terraria.ID; -using Terraria.Localization; -using Terraria.Map; -using Terraria.ModLoader; -using Terraria.UI; -using MagicStorage.Components; -using MagicStorage.Sorting; - -namespace MagicStorage -{ - public static class CraftingGUI - { - private const int padding = 4; - private const int numColumns = 10; - private const int numColumns2 = 7; - private const float inventoryScale = 0.85f; - private const float smallScale = 0.7f; - - public static MouseState curMouse; - public static MouseState oldMouse; - public static bool MouseClicked - { - get - { - return curMouse.LeftButton == ButtonState.Pressed && oldMouse.LeftButton == ButtonState.Released; - } - } - - private static UIPanel basePanel = new UIPanel(); - private static float panelTop; - private static float panelLeft; - private static float panelWidth; - private static float panelHeight; - - private static UIElement topBar = new UIElement(); - internal static UISearchBar searchBar; - private static UIButtonChoice sortButtons; - private static UIButtonChoice recipeButtons; - private static UIElement topBar2 = new UIElement(); - private static UIButtonChoice filterButtons; - internal static UISearchBar searchBar2; - - private static UIText stationText; - private static UISlotZone stationZone = new UISlotZone(HoverStation, GetStation, inventoryScale); - private static UIText recipeText; - private static UISlotZone recipeZone = new UISlotZone(HoverRecipe, GetRecipe, inventoryScale); - - internal static UIScrollbar scrollBar = new UIScrollbar(); - private static int scrollBarFocus = 0; - private static int scrollBarFocusMouseStart; - private static float scrollBarFocusPositionStart; - private static float scrollBarViewSize = 1f; - private static float scrollBarMaxViewSize = 2f; - - private static List items = new List(); - private static Dictionary itemCounts = new Dictionary(); - private static bool[] adjTiles = new bool[TileLoader.TileCount]; - private static bool adjWater = false; - private static bool adjLava = false; - private static bool adjHoney = false; - private static bool zoneSnow = false; - private static bool alchemyTable = false; - private static List recipes = new List(); - private static List recipeAvailable = new List(); - private static Recipe selectedRecipe = null; - private static int numRows; - private static int displayRows; - private static bool slotFocus = false; - - private static UIElement bottomBar = new UIElement(); - private static UIText capacityText; - - private static UIPanel recipePanel = new UIPanel(); - private static float recipeTop; - private static float recipeLeft; - private static float recipeWidth; - private static float recipeHeight; - - private static UIText recipePanelHeader; - private static UIText ingredientText; - private static UISlotZone ingredientZone = new UISlotZone(HoverItem, GetIngredient, smallScale); - private static UIText reqObjText; - private static UIText reqObjText2; - private static UIText storedItemsText; - - private static UISlotZone storageZone = new UISlotZone(HoverStorage, GetStorage, smallScale); - private static int numRows2; - private static int displayRows2; - private static List storageItems = new List(); - private static List blockStorageItems = new List(); - - internal static UIScrollbar scrollBar2 = new UIScrollbar(); - private static float scrollBar2ViewSize = 1f; - private static float scrollBar2MaxViewSize = 2f; - - internal static UITextPanel craftButton; - private static Item result = null; - private static UISlotZone resultZone = new UISlotZone(HoverResult, GetResult, inventoryScale); - private static int craftTimer = 0; - private const int startMaxCraftTimer = 20; - private static int maxCraftTimer = startMaxCraftTimer; - private static int rightClickTimer = 0; - private const int startMaxRightClickTimer = 20; - private static int maxRightClickTimer = startMaxRightClickTimer; - - private static Object threadLock = new Object(); - private static Object recipeLock = new Object(); - private static Object itemsLock = new Object(); - private static bool threadRunning = false; - internal static bool threadNeedsRestart = false; - private static SortMode threadSortMode; - private static FilterMode threadFilterMode; - private static List threadRecipes = new List(); - private static List threadRecipeAvailable = new List(); - private static List nextRecipes = new List(); - private static List nextRecipeAvailable = new List(); - - public static void Initialize() - { - lock (recipeLock) - { - recipes = nextRecipes; - recipeAvailable = nextRecipeAvailable; - } - - InitLangStuff(); - float itemSlotWidth = Main.inventoryBackTexture.Width * inventoryScale; - float itemSlotHeight = Main.inventoryBackTexture.Height * inventoryScale; - float smallSlotWidth = Main.inventoryBackTexture.Width * smallScale; - float smallSlotHeight = Main.inventoryBackTexture.Height * smallScale; - - panelTop = Main.instance.invBottom + 60; - panelLeft = 20f; - float innerPanelLeft = panelLeft + basePanel.PaddingLeft; - float innerPanelWidth = numColumns * (itemSlotWidth + padding) + 20f + padding; - panelWidth = basePanel.PaddingLeft + innerPanelWidth + basePanel.PaddingRight; - panelHeight = Main.screenHeight - panelTop - 40f; - basePanel.Left.Set(panelLeft, 0f); - basePanel.Top.Set(panelTop, 0f); - basePanel.Width.Set(panelWidth, 0f); - basePanel.Height.Set(panelHeight, 0f); - basePanel.Recalculate(); - - recipeTop = panelTop; - recipeLeft = panelLeft + panelWidth; - recipeWidth = numColumns2 * (smallSlotWidth + padding) + 20f + padding; - recipeWidth += recipePanel.PaddingLeft + recipePanel.PaddingRight; - recipeHeight = panelHeight; - recipePanel.Left.Set(recipeLeft, 0f); - recipePanel.Top.Set(recipeTop, 0f); - recipePanel.Width.Set(recipeWidth, 0f); - recipePanel.Height.Set(recipeHeight, 0f); - recipePanel.Recalculate(); - - topBar.Width.Set(0f, 1f); - topBar.Height.Set(32f, 0f); - basePanel.Append(topBar); - - InitSortButtons(); - topBar.Append(sortButtons); - float sortButtonsRight = sortButtons.GetDimensions().Width + padding; - InitRecipeButtons(); - float recipeButtonsLeft = sortButtonsRight + 32f + 3 * padding; - recipeButtons.Left.Set(recipeButtonsLeft, 0f); - topBar.Append(recipeButtons); - float recipeButtonsRight = recipeButtonsLeft + recipeButtons.GetDimensions().Width + padding; - - searchBar.Left.Set(recipeButtonsRight + padding, 0f); - searchBar.Width.Set(-recipeButtonsRight - 2 * padding, 1f); - searchBar.Height.Set(0f, 1f); - topBar.Append(searchBar); - - topBar2.Width.Set(0f, 1f); - topBar2.Height.Set(32f, 0f); - topBar2.Top.Set(36f, 0f); - basePanel.Append(topBar2); - - InitFilterButtons(); - float filterButtonsRight = filterButtons.GetDimensions().Width + padding; - topBar2.Append(filterButtons); - searchBar2.Left.Set(filterButtonsRight + padding, 0f); - searchBar2.Width.Set(-filterButtonsRight - 2 * padding, 1f); - searchBar2.Height.Set(0f, 1f); - topBar2.Append(searchBar2); - - stationText.Top.Set(76f, 0f); - basePanel.Append(stationText); - - stationZone.Width.Set(0f, 1f); - stationZone.Top.Set(100f, 0f); - stationZone.Height.Set(70f, 0f); - stationZone.SetDimensions(numColumns, 1); - basePanel.Append(stationZone); - - recipeText.Top.Set(152f, 0f); - basePanel.Append(recipeText); - - recipeZone.Width.Set(0f, 1f); - recipeZone.Top.Set(176f, 0f); - recipeZone.Height.Set(-216f, 1f); - basePanel.Append(recipeZone); - - numRows = (recipes.Count + numColumns - 1) / numColumns; - displayRows = (int)recipeZone.GetDimensions().Height / ((int)itemSlotHeight + padding); - recipeZone.SetDimensions(numColumns, displayRows); - int noDisplayRows = numRows - displayRows; - if (noDisplayRows < 0) - { - noDisplayRows = 0; - } - scrollBarMaxViewSize = 1 + noDisplayRows; - scrollBar.Height.Set(displayRows * (itemSlotHeight + padding), 0f); - scrollBar.Left.Set(-20f, 1f); - scrollBar.SetView(scrollBarViewSize, scrollBarMaxViewSize); - recipeZone.Append(scrollBar); - - bottomBar.Width.Set(0f, 1f); - bottomBar.Height.Set(32f, 0f); - bottomBar.Top.Set(-32f, 1f); - basePanel.Append(bottomBar); - - capacityText.Left.Set(6f, 0f); - capacityText.Top.Set(6f, 0f); - TEStorageHeart heart = GetHeart(); - int numItems = 0; - int capacity = 0; - if (heart != null) - { - foreach (TEAbstractStorageUnit abstractStorageUnit in heart.GetStorageUnits()) - { - if (abstractStorageUnit is TEStorageUnit) - { - TEStorageUnit storageUnit = (TEStorageUnit)abstractStorageUnit; - numItems += storageUnit.NumItems; - capacity += storageUnit.Capacity; - } - } - } - capacityText.SetText(numItems + "/" + capacity + " Items"); - bottomBar.Append(capacityText); - - recipePanel.Append(recipePanelHeader); - ingredientText.Top.Set(30f, 0f); - recipePanel.Append(ingredientText); - - ingredientZone.SetDimensions(numColumns2, 2); - ingredientZone.Top.Set(54f, 0f); - ingredientZone.Width.Set(0f, 1f); - ingredientZone.Height.Set(60f, 0f); - recipePanel.Append(ingredientZone); - - reqObjText.Top.Set(136f, 0f); - recipePanel.Append(reqObjText); - reqObjText2.Top.Set(160f, 0f); - recipePanel.Append(reqObjText2); - storedItemsText.Top.Set(190f, 0f); - recipePanel.Append(storedItemsText); - - storageZone.Top.Set(214f, 0f); - storageZone.Width.Set(0f, 1f); - storageZone.Height.Set(-214f - 36, 1f); - recipePanel.Append(storageZone); - numRows2 = (storageItems.Count + numColumns2 - 1) / numColumns2; - displayRows2 = (int)storageZone.GetDimensions().Height / ((int)smallSlotHeight + padding); - storageZone.SetDimensions(numColumns2, displayRows2); - int noDisplayRows2 = numRows2 - displayRows2; - if (noDisplayRows2 < 0) - { - noDisplayRows2 = 0; - } - scrollBar2MaxViewSize = 1 + noDisplayRows2; - scrollBar2.Height.Set(displayRows2 * (smallSlotHeight + padding), 0f); - scrollBar2.Left.Set(-20f, 1f); - scrollBar2.SetView(scrollBar2ViewSize, scrollBar2MaxViewSize); - storageZone.Append(scrollBar2); - - craftButton.Top.Set(-32f, 1f); - craftButton.Width.Set(100f, 0f); - craftButton.Height.Set(24f, 0f); - craftButton.PaddingTop = 8f; - craftButton.PaddingBottom = 8f; - recipePanel.Append(craftButton); - - resultZone.SetDimensions(1, 1); - resultZone.Left.Set(-itemSlotWidth, 1f); - resultZone.Top.Set(-itemSlotHeight, 1f); - resultZone.Width.Set(itemSlotWidth, 0f); - resultZone.Height.Set(itemSlotHeight, 0f); - recipePanel.Append(resultZone); - } - - private static void InitLangStuff() - { - if (searchBar == null) - { - searchBar = new UISearchBar(Language.GetText("Mods.MagicStorage.SearchName")); - } - if (searchBar2 == null) - { - searchBar2 = new UISearchBar(Language.GetText("Mods.MagicStorage.SearchMod")); - } - if (stationText == null) - { - stationText = new UIText(Language.GetText("Mods.MagicStorage.CraftingStations")); - } - if (recipeText == null) - { - recipeText = new UIText(Language.GetText("Mods.MagicStorage.Recipes")); - } - if (capacityText == null) - { - capacityText = new UIText("Items"); - } - if (recipePanelHeader == null) - { - recipePanelHeader = new UIText(Language.GetText("Mods.MagicStorage.SelectedRecipe")); - } - if (ingredientText == null) - { - ingredientText = new UIText(Language.GetText("Mods.MagicStorage.Ingredients")); - } - if (reqObjText == null) - { - reqObjText = new UIText(Language.GetText("LegacyInterface.22")); - } - if (reqObjText2 == null) - { - reqObjText2 = new UIText(""); - } - if (storedItemsText == null) - { - storedItemsText = new UIText(Language.GetText("Mods.MagicStorage.StoredItems")); - } - if (craftButton == null) - { - craftButton = new UITextPanel(Language.GetText("LegacyMisc.72"), 1f); - } - } - - private static void InitSortButtons() - { - if (sortButtons == null) - { - sortButtons = new UIButtonChoice(new Texture2D[] - { - Main.inventorySortTexture[0], - MagicStorage.Instance.GetTexture("SortID"), - MagicStorage.Instance.GetTexture("SortName") - }, - new LocalizedText[] - { - Language.GetText("Mods.MagicStorage.SortDefault"), - Language.GetText("Mods.MagicStorage.SortID"), - Language.GetText("Mods.MagicStorage.SortName") - }); - } - } - - private static void InitRecipeButtons() - { - if (recipeButtons == null) - { - recipeButtons = new UIButtonChoice(new Texture2D[] - { - MagicStorage.Instance.GetTexture("RecipeAvailable"), - MagicStorage.Instance.GetTexture("RecipeAll") - }, - new LocalizedText[] - { - Language.GetText("Mods.MagicStorage.RecipeAvailable"), - Language.GetText("Mods.MagicStorage.RecipeAll") - }); - } - } - - private static void InitFilterButtons() - { - if (filterButtons == null) - { - filterButtons = new UIButtonChoice(new Texture2D[] - { - MagicStorage.Instance.GetTexture("FilterAll"), - MagicStorage.Instance.GetTexture("FilterMelee"), - MagicStorage.Instance.GetTexture("FilterPickaxe"), - MagicStorage.Instance.GetTexture("FilterArmor"), - MagicStorage.Instance.GetTexture("FilterPotion"), - MagicStorage.Instance.GetTexture("FilterTile"), - MagicStorage.Instance.GetTexture("FilterMisc"), - }, - new LocalizedText[] - { - Language.GetText("Mods.MagicStorage.FilterAll"), - Language.GetText("Mods.MagicStorage.FilterWeapons"), - Language.GetText("Mods.MagicStorage.FilterTools"), - Language.GetText("Mods.MagicStorage.FilterEquips"), - Language.GetText("Mods.MagicStorage.FilterPotions"), - Language.GetText("Mods.MagicStorage.FilterTiles"), - Language.GetText("Mods.MagicStorage.FilterMisc") - }); - } - } - - public static void Update(GameTime gameTime) - {try{ - oldMouse = StorageGUI.oldMouse; - curMouse = StorageGUI.curMouse; - if (Main.playerInventory && Main.player[Main.myPlayer].GetModPlayer(MagicStorage.Instance).ViewingStorage().X >= 0 && StoragePlayer.IsStorageCrafting()) - { - if (curMouse.RightButton == ButtonState.Released) - { - ResetSlotFocus(); - } - basePanel.Update(gameTime); - recipePanel.Update(gameTime); - UpdateRecipeText(); - UpdateScrollBar(); - UpdateCraftButton(); - } - else - { - scrollBarFocus = 0; - selectedRecipe = null; - craftTimer = 0; - maxCraftTimer = startMaxCraftTimer; - ResetSlotFocus(); - }}catch(Exception e){Main.NewTextMultiline(e.ToString());} - } - - public static void Draw(TEStorageHeart heart) - {try{ - Player player = Main.player[Main.myPlayer]; - StoragePlayer modPlayer = player.GetModPlayer(MagicStorage.Instance); - Initialize(); - if (Main.mouseX > panelLeft && Main.mouseX < recipeLeft + panelWidth && Main.mouseY > panelTop && Main.mouseY < panelTop + panelHeight) - { - player.mouseInterface = true; - player.showItemIcon = false; - InterfaceHelper.HideItemIconCache(); - } - basePanel.Draw(Main.spriteBatch); - recipePanel.Draw(Main.spriteBatch); - Vector2 pos = recipeZone.GetDimensions().Position(); - if (threadRunning) - { - Utils.DrawBorderString(Main.spriteBatch, "Loading", pos + new Vector2(8f, 8f), Color.White); - } - stationZone.DrawText(); - recipeZone.DrawText(); - ingredientZone.DrawText(); - storageZone.DrawText(); - resultZone.DrawText(); - sortButtons.DrawText(); - recipeButtons.DrawText(); - filterButtons.DrawText();}catch(Exception e){Main.NewTextMultiline(e.ToString());} - } - - private static Item GetStation(int slot, ref int context) - { - Item[] stations = GetCraftingStations(); - if (stations == null || slot >= stations.Length) - { - return new Item(); - } - return stations[slot]; - } - - private static Item GetRecipe(int slot, ref int context) - { - if (threadRunning) - { - return new Item(); - } - int index = slot + numColumns * (int)Math.Round(scrollBar.ViewPosition); - Item item = index < recipes.Count ? recipes[index].createItem : new Item(); - if (!item.IsAir && recipes[index] == selectedRecipe) - { - context = 6; - } - if (!item.IsAir && !recipeAvailable[index]) - { - context = recipes[index] == selectedRecipe ? 4 : 3; - } - return item; - } - - private static Item GetIngredient(int slot, ref int context) - { - if (selectedRecipe == null || slot >= selectedRecipe.requiredItem.Length) - { - return new Item(); - } - Item item = selectedRecipe.requiredItem[slot].Clone(); - if (selectedRecipe.anyWood && item.type == ItemID.Wood) - { - item.SetNameOverride(Lang.misc[37].Value + " " + Lang.GetItemNameValue(ItemID.Wood)); - } - if (selectedRecipe.anySand && item.type == ItemID.SandBlock) - { - item.SetNameOverride(Lang.misc[37].Value + " " + Lang.GetItemNameValue(ItemID.SandBlock)); - } - if (selectedRecipe.anyIronBar && item.type == ItemID.IronBar) - { - item.SetNameOverride(Lang.misc[37].Value + " " + Lang.GetItemNameValue(ItemID.IronBar)); - } - if (selectedRecipe.anyFragment && item.type == ItemID.FragmentSolar) - { - item.SetNameOverride(Lang.misc[37].Value + " " + Lang.misc[51].Value); - } - if (selectedRecipe.anyPressurePlate && item.type == ItemID.GrayPressurePlate) - { - item.SetNameOverride(Lang.misc[37].Value + " " + Lang.misc[38].Value); - } - string nameOverride; - if (selectedRecipe.ProcessGroupsForText(item.type, out nameOverride)) - { - item.SetNameOverride(nameOverride); - } - return item; - } - - private static Item GetStorage(int slot, ref int context) - { - int index = slot + numColumns2 * (int)Math.Round(scrollBar2.ViewPosition); - Item item = index < storageItems.Count ? storageItems[index] : new Item(); - if (blockStorageItems.Contains(new ItemData(item))) - { - context = 3; - } - return item; - } - - private static Item GetResult(int slot, ref int context) - { - return slot == 0 && result != null ? result : new Item(); - } - - private static void UpdateRecipeText() - { - if (selectedRecipe == null) - { - reqObjText2.SetText(""); - } - else - { - bool isEmpty = true; - string text = ""; - for (int k = 0; k < selectedRecipe.requiredTile.Length; k++) - { - if (selectedRecipe.requiredTile[k] == -1) - { - break; - } - if (!isEmpty) - { - text += ", "; - } - text += Lang.GetMapObjectName(MapHelper.TileToLookup(selectedRecipe.requiredTile[k], 0)); - isEmpty = false; - } - if (selectedRecipe.needWater) - { - if (!isEmpty) - { - text += ", "; - } - text += Language.GetTextValue("LegacyInterface.53"); - isEmpty = false; - } - if (selectedRecipe.needHoney) - { - if (!isEmpty) - { - text += ", "; - } - text += Language.GetTextValue("LegacyInterface.58"); - isEmpty = false; - } - if (selectedRecipe.needLava) - { - if (!isEmpty) - { - text += ", "; - } - text += Language.GetTextValue("LegacyInterface.56"); - isEmpty = false; - } - if (selectedRecipe.needSnowBiome) - { - if (!isEmpty) - { - text += ", "; - } - text += Language.GetTextValue("LegacyInterface.123"); - isEmpty = false; - } - if (isEmpty) - { - text = Language.GetTextValue("LegacyInterface.23"); - } - reqObjText2.SetText(text); - } - } - - private static void UpdateScrollBar() - { - if (slotFocus) - { - scrollBarFocus = 0; - return; - } - Rectangle dim = scrollBar.GetClippingRectangle(Main.spriteBatch); - Vector2 boxPos = new Vector2(dim.X, dim.Y + dim.Height * (scrollBar.ViewPosition / scrollBarMaxViewSize)); - float boxWidth = 20f * Main.UIScale; - float boxHeight = dim.Height * (scrollBarViewSize / scrollBarMaxViewSize); - Rectangle dim2 = scrollBar2.GetClippingRectangle(Main.spriteBatch); - Vector2 box2Pos = new Vector2(dim2.X, dim2.Y + dim2.Height * (scrollBar2.ViewPosition / scrollBar2MaxViewSize)); - float box2Height = dim2.Height * (scrollBar2ViewSize / scrollBar2MaxViewSize); - if (scrollBarFocus > 0) - { - if (curMouse.LeftButton == ButtonState.Released) - { - scrollBarFocus = 0; - } - else - { - int difference = curMouse.Y - scrollBarFocusMouseStart; - if (scrollBarFocus == 1) - { - scrollBar.ViewPosition = scrollBarFocusPositionStart + (float)difference / boxHeight; - } - else if (scrollBarFocus == 2) - { - scrollBar2.ViewPosition = scrollBarFocusPositionStart + (float)difference / box2Height; - } - } - } - else if (MouseClicked) - { - if (curMouse.X > boxPos.X && curMouse.X < boxPos.X + boxWidth && curMouse.Y > boxPos.Y - 3f && curMouse.Y < boxPos.Y + boxHeight + 4f) - { - scrollBarFocus = 1; - scrollBarFocusMouseStart = curMouse.Y; - scrollBarFocusPositionStart = scrollBar.ViewPosition; - } - else if (curMouse.X > box2Pos.X && curMouse.X < box2Pos.X + boxWidth && curMouse.Y > box2Pos.Y - 3f && curMouse.Y < box2Pos.Y + box2Height + 4f) - { - scrollBarFocus = 2; - scrollBarFocusMouseStart = curMouse.Y; - scrollBarFocusPositionStart = scrollBar2.ViewPosition; - } - } - if (scrollBarFocus == 0) - { - int difference = oldMouse.ScrollWheelValue / 250 - curMouse.ScrollWheelValue / 250; - scrollBar.ViewPosition += difference; - } - } - - private static void UpdateCraftButton() - { - Rectangle dim = InterfaceHelper.GetFullRectangle(craftButton); - bool flag = false; - if (curMouse.X > dim.X && curMouse.X < dim.X + dim.Width && curMouse.Y > dim.Y && curMouse.Y < dim.Y + dim.Height) - { - craftButton.BackgroundColor = new Color(73, 94, 171); - if (curMouse.LeftButton == ButtonState.Pressed) - { - if (selectedRecipe != null && IsAvailable(selectedRecipe) && PassesBlock(selectedRecipe)) - { - if (craftTimer <= 0) - { - craftTimer = maxCraftTimer; - maxCraftTimer = maxCraftTimer * 3 / 4; - if (maxCraftTimer <= 0) - { - maxCraftTimer = 1; - } - TryCraft(); - RefreshItems(); - Main.PlaySound(7, -1, -1, 1); - } - craftTimer--; - flag = true; - } - } - } - else - { - craftButton.BackgroundColor = new Color(63, 82, 151) * 0.7f; - } - if (selectedRecipe == null || !IsAvailable(selectedRecipe) || !PassesBlock(selectedRecipe)) - { - craftButton.BackgroundColor = new Color(30, 40, 100) * 0.7f; - } - if (!flag) - { - craftTimer = 0; - maxCraftTimer = startMaxCraftTimer; - } - } - - private static TEStorageHeart GetHeart() - { - Player player = Main.player[Main.myPlayer]; - StoragePlayer modPlayer = player.GetModPlayer(); - return modPlayer.GetStorageHeart(); - } - - private static TECraftingAccess GetCraftingEntity() - { - Player player = Main.player[Main.myPlayer]; - StoragePlayer modPlayer = player.GetModPlayer(); - return modPlayer.GetCraftingAccess(); - } - - private static Item[] GetCraftingStations() - { - TECraftingAccess ent = GetCraftingEntity(); - return ent == null ? null : ent.stations; - } - - public static void RefreshItems() - { - items.Clear(); - TEStorageHeart heart = GetHeart(); - if (heart == null) - { - return; - } - items.AddRange(ItemSorter.SortAndFilter(heart.GetStoredItems(), SortMode.Id, FilterMode.All, "", "")); - AnalyzeIngredients(); - InitLangStuff(); - InitSortButtons(); - InitRecipeButtons(); - InitFilterButtons(); - SortMode sortMode; - switch (sortButtons.Choice) - { - case 0: - sortMode = SortMode.Default; - break; - case 1: - sortMode = SortMode.Id; - break; - case 2: - sortMode = SortMode.Name; - break; - default: - sortMode = SortMode.Default; - break; - } - FilterMode filterMode; - switch (filterButtons.Choice) - { - case 0: - filterMode = FilterMode.All; - break; - case 1: - filterMode = FilterMode.Weapons; - break; - case 2: - filterMode = FilterMode.Tools; - break; - case 3: - filterMode = FilterMode.Equipment; - break; - case 4: - filterMode = FilterMode.Potions; - break; - case 5: - filterMode = FilterMode.Placeables; - break; - case 6: - filterMode = FilterMode.Misc; - break; - default: - filterMode = FilterMode.All; - break; - } - RefreshStorageItems(); - lock (threadLock) - { - threadNeedsRestart = true; - threadSortMode = sortMode; - threadFilterMode = filterMode; - if (!threadRunning) - { - threadRunning = true; - Thread thread = new Thread(RefreshRecipes); - thread.Start(); - } - } - } - - private static void RefreshRecipes() - { - while (true) - {try{ - SortMode sortMode; - FilterMode filterMode; - lock (threadLock) - { - threadNeedsRestart = false; - sortMode = threadSortMode; - filterMode = threadFilterMode; - } - var temp = ItemSorter.GetRecipes(sortMode, filterMode, searchBar2.Text, searchBar.Text); - threadRecipes.Clear(); - threadRecipeAvailable.Clear(); - try - { - if (recipeButtons.Choice == 0) - { - threadRecipes.AddRange(temp.Where(recipe => IsAvailable(recipe))); - threadRecipeAvailable.AddRange(threadRecipes.Select(recipe => true)); - } - else - { - threadRecipes.AddRange(temp); - threadRecipeAvailable.AddRange(threadRecipes.Select(recipe => IsAvailable(recipe))); - } - } - catch (InvalidOperationException) - { - } - catch (KeyNotFoundException) - { - } - lock (recipeLock) - { - nextRecipes = new List(); - nextRecipeAvailable = new List(); - nextRecipes.AddRange(threadRecipes); - nextRecipeAvailable.AddRange(threadRecipeAvailable); - - } - lock (threadLock) - { - if (!threadNeedsRestart) - { - threadRunning = false; - return; - } - }}catch(Exception e){Main.NewTextMultiline(e.ToString());} - } - } - - private static void AnalyzeIngredients() - { - Player player = Main.player[Main.myPlayer]; - itemCounts.Clear(); - if (adjTiles.Length != player.adjTile.Length) - { - Array.Resize(ref adjTiles, player.adjTile.Length); - } - for (int k = 0; k < adjTiles.Length; k++) - { - adjTiles[k] = false; - } - adjWater = false; - adjLava = false; - adjHoney = false; - zoneSnow = false; - alchemyTable = false; - - foreach (Item item in items) - { - if (itemCounts.ContainsKey(item.netID)) - { - itemCounts[item.netID] += item.stack; - } - else - { - itemCounts[item.netID] = item.stack; - } - } - foreach (Item item in GetCraftingStations()) - { - if (item.createTile >= 0) - { - adjTiles[item.createTile] = true; - if (item.createTile == TileID.GlassKiln || item.createTile == TileID.Hellforge || item.createTile == TileID.AdamantiteForge) - { - adjTiles[TileID.Furnaces] = true; - } - if (item.createTile == TileID.AdamantiteForge) - { - adjTiles[TileID.Hellforge] = true; - } - if (item.createTile == TileID.MythrilAnvil) - { - adjTiles[TileID.Anvils] = true; - } - if (item.createTile == TileID.BewitchingTable || item.createTile == TileID.Tables2) - { - adjTiles[TileID.Tables] = true; - } - if (item.createTile == TileID.AlchemyTable) - { - adjTiles[TileID.Bottles] = true; - adjTiles[TileID.Tables] = true; - alchemyTable = true; - } - bool[] oldAdjTile = player.adjTile; - bool oldAdjWater = adjWater; - bool oldAdjLava = adjLava; - bool oldAdjHoney = adjHoney; - bool oldAlchemyTable = alchemyTable; - player.adjTile = adjTiles; - player.adjWater = false; - player.adjLava = false; - player.adjHoney = false; - player.alchemyTable = false; - TileLoader.AdjTiles(player, item.createTile); - if (player.adjWater) - { - adjWater = true; - } - if (player.adjLava) - { - adjLava = true; - } - if (player.adjHoney) - { - adjHoney = true; - } - if (player.alchemyTable) - { - alchemyTable = true; - } - player.adjTile = oldAdjTile; - player.adjWater = oldAdjWater; - player.adjLava = oldAdjLava; - player.adjHoney = oldAdjHoney; - player.alchemyTable = oldAlchemyTable; - } - if (item.type == ItemID.WaterBucket || item.type == ItemID.BottomlessBucket) - { - adjWater = true; - } - if (item.type == ItemID.LavaBucket) - { - adjLava = true; - } - if (item.type == ItemID.HoneyBucket) - { - adjHoney = true; - } - if (item.type == MagicStorage.Instance.ItemType("SnowBiomeEmulator")) - { - zoneSnow = true; - } - } - adjTiles[MagicStorage.Instance.TileType("CraftingAccess")] = true; - } - - private static bool IsAvailable(Recipe recipe) - { - foreach (int tile in recipe.requiredTile) - { - if (tile == -1) - { - break; - } - if (!adjTiles[tile]) - { - return false; - } - } - foreach (Item ingredient in recipe.requiredItem) - { - if (ingredient.type == 0) - { - break; - } - int stack = ingredient.stack; - bool useRecipeGroup = false; - foreach (int type in itemCounts.Keys) - { - if (RecipeGroupMatch(recipe, type, ingredient.type)) - { - stack -= itemCounts[type]; - useRecipeGroup = true; - } - } - if (!useRecipeGroup && itemCounts.ContainsKey(ingredient.netID)) - { - stack -= itemCounts[ingredient.netID]; - } - if (stack > 0) - { - return false; - } - } - if (recipe.needWater && !adjWater && !adjTiles[TileID.Sinks]) - { - return false; - } - if (recipe.needLava && !adjLava) - { - return false; - } - if (recipe.needHoney && !adjHoney) - { - return false; - } - if (recipe.needSnowBiome && !zoneSnow) - { - return false; - } - try - { - BlockRecipes.active = false; - if (!RecipeHooks.RecipeAvailable(recipe)) - { - return false; - } - } - finally - { - BlockRecipes.active = true; - } - return true; - } - - private static bool PassesBlock(Recipe recipe) - { - foreach (Item ingredient in recipe.requiredItem) - { - if (ingredient.type == 0) - { - break; - } - int stack = ingredient.stack; - bool useRecipeGroup = false; - foreach (Item item in storageItems) - { - ItemData data = new ItemData(item); - if (!blockStorageItems.Contains(data) && RecipeGroupMatch(recipe, item.netID, ingredient.type)) - { - stack -= item.stack; - useRecipeGroup = true; - } - } - if (!useRecipeGroup) - { - foreach (Item item in storageItems) - { - ItemData data = new ItemData(item); - if (!blockStorageItems.Contains(data) && item.netID == ingredient.netID) - { - stack -= item.stack; - } - } - } - if (stack > 0) - { - return false; - } - } - return true; - } - - private static void RefreshStorageItems() - { - storageItems.Clear(); - result = null; - if (selectedRecipe != null) - { - foreach (Item item in items) - { - for (int k = 0; k < selectedRecipe.requiredItem.Length; k++) - { - if (selectedRecipe.requiredItem[k].type == 0) - { - break; - } - if (item.type == selectedRecipe.requiredItem[k].type || RecipeGroupMatch(selectedRecipe, selectedRecipe.requiredItem[k].type, item.type)) - { - storageItems.Add(item); - } - } - if (item.type == selectedRecipe.createItem.type) - { - result = item; - } - } - if (result == null) - { - result = new Item(); - result.SetDefaults(selectedRecipe.createItem.type); - result.stack = 0; - } - } - } - - private static bool RecipeGroupMatch(Recipe recipe, int type1, int type2) - { - return recipe.useWood(type1, type2) || recipe.useSand(type1, type2) || recipe.useIronBar(type1, type2) || recipe.useFragment(type1, type2) || recipe.AcceptedByItemGroups(type1, type2) || recipe.usePressurePlate(type1, type2); - } - - private static void HoverStation(int slot, ref int hoverSlot) - { - TECraftingAccess ent = GetCraftingEntity(); - if (ent == null || slot >= ent.stations.Length) - { - return; - } - - Player player = Main.player[Main.myPlayer]; - if (MouseClicked) - { - bool changed = false; - if (!ent.stations[slot].IsAir && ItemSlot.ShiftInUse) - { - Item result = player.GetItem(Main.myPlayer, DoWithdraw(slot), false, true); - if (!result.IsAir && Main.mouseItem.IsAir) - { - Main.mouseItem = result; - result = new Item(); - } - if (!result.IsAir && Main.mouseItem.type == result.type && Main.mouseItem.stack < Main.mouseItem.maxStack) - { - Main.mouseItem.stack += result.stack; - result = new Item(); - } - if (!result.IsAir) - { - player.QuickSpawnClonedItem(result); - } - changed = true; - } - else if (player.itemAnimation == 0 && player.itemTime == 0) - { - int oldType = Main.mouseItem.type; - int oldStack = Main.mouseItem.stack; - Main.mouseItem = DoStationSwap(Main.mouseItem, slot); - if (oldType != Main.mouseItem.type || oldStack != Main.mouseItem.stack) - { - changed = true; - } - } - if (changed) - { - RefreshItems(); - Main.PlaySound(7, -1, -1, 1); - } - } - - hoverSlot = slot; - } - - private static void HoverRecipe(int slot, ref int hoverSlot) - { - int visualSlot = slot; - slot += numColumns * (int)Math.Round(scrollBar.ViewPosition); - if (slot < recipes.Count) - { - if (MouseClicked) - { - selectedRecipe = recipes[slot]; - RefreshStorageItems(); - blockStorageItems.Clear(); - } - hoverSlot = visualSlot; - } - } - - private static void HoverItem(int slot, ref int hoverSlot) - { - hoverSlot = slot; - } - - private static void HoverStorage(int slot, ref int hoverSlot) - { - int visualSlot = slot; - slot += numColumns2 * (int)Math.Round(scrollBar2.ViewPosition); - if (slot < storageItems.Count) - { - if (MouseClicked) - { - ItemData data = new ItemData(storageItems[slot]); - if (blockStorageItems.Contains(data)) - { - blockStorageItems.Remove(data); - } - else - { - blockStorageItems.Add(data); - } - } - hoverSlot = visualSlot; - } - } - - private static void HoverResult(int slot, ref int hoverSlot) - { - if (slot != 0) - { - return; - } - - Player player = Main.player[Main.myPlayer]; - if (MouseClicked) - { - bool changed = false; - if (!Main.mouseItem.IsAir && player.itemAnimation == 0 && player.itemTime == 0 && result != null && Main.mouseItem.type == result.type) - { - if (TryDepositResult(Main.mouseItem)) - { - changed = true; - } - } - else if (Main.mouseItem.IsAir && result != null && !result.IsAir) - { - Item toWithdraw = result.Clone(); - if (toWithdraw.stack > toWithdraw.maxStack) - { - toWithdraw.stack = toWithdraw.maxStack; - } - Main.mouseItem = DoWithdrawResult(toWithdraw, ItemSlot.ShiftInUse); - if (ItemSlot.ShiftInUse) - { - Main.mouseItem = player.GetItem(Main.myPlayer, Main.mouseItem, false, true); - } - changed = true; - } - if (changed) - { - RefreshItems(); - Main.PlaySound(7, -1, -1, 1); - } - } - - if (curMouse.RightButton == ButtonState.Pressed && oldMouse.RightButton == ButtonState.Released && result != null && !result.IsAir && (Main.mouseItem.IsAir || ItemData.Matches(Main.mouseItem, items[slot]) && Main.mouseItem.stack < Main.mouseItem.maxStack)) - { - slotFocus = true; - } - - hoverSlot = slot; - - if (slotFocus) - { - SlotFocusLogic(); - } - } - - private static void SlotFocusLogic() - { - if (result == null || result.IsAir || (!Main.mouseItem.IsAir && (!ItemData.Matches(Main.mouseItem, result) || Main.mouseItem.stack >= Main.mouseItem.maxStack))) - { - ResetSlotFocus(); - } - else - { - if (rightClickTimer <= 0) - { - rightClickTimer = maxRightClickTimer; - maxRightClickTimer = maxRightClickTimer * 3 / 4; - if (maxRightClickTimer <= 0) - { - maxRightClickTimer = 1; - } - Item toWithdraw = result.Clone(); - toWithdraw.stack = 1; - Item withdrawn = DoWithdrawResult(toWithdraw); - if (Main.mouseItem.IsAir) - { - Main.mouseItem = withdrawn; - } - else - { - Main.mouseItem.stack += withdrawn.stack; - } - Main.soundInstanceMenuTick.Stop(); - Main.soundInstanceMenuTick = Main.soundMenuTick.CreateInstance(); - Main.PlaySound(12, -1, -1, 1); - RefreshItems(); - } - rightClickTimer--; - } - } - - private static void ResetSlotFocus() - { - slotFocus = false; - rightClickTimer = 0; - maxRightClickTimer = startMaxRightClickTimer; - } - - private static Item DoWithdraw(int slot) - { - TECraftingAccess access = GetCraftingEntity(); - if (Main.netMode == 0) - { - Item result = access.TryWithdrawStation(slot); - RefreshItems(); - return result; - } - else - { - NetHelper.SendWithdrawStation(access.ID, slot); - return new Item(); - } - } - - private static Item DoStationSwap(Item item, int slot) - { - TECraftingAccess access = GetCraftingEntity(); - if (Main.netMode == 0) - { - Item result = access.DoStationSwap(item, slot); - RefreshItems(); - return result; - } - else - { - NetHelper.SendStationSlotClick(access.ID, item, slot); - return new Item(); - } - } - - private static void TryCraft() - { - List availableItems = new List(storageItems.Where(item => !blockStorageItems.Contains(new ItemData(item))).Select(item => item.Clone())); - List toWithdraw = new List(); - for (int k = 0; k < selectedRecipe.requiredItem.Length; k++) - { - Item item = selectedRecipe.requiredItem[k]; - if (item.type == 0) - { - break; - } - int stack = item.stack; - ModRecipe modRecipe = selectedRecipe as ModRecipe; - if (modRecipe != null) - { - stack = modRecipe.ConsumeItem(item.type, item.stack); - } - if (selectedRecipe.alchemy && alchemyTable) - { - int save = 0; - for (int j = 0; j < stack; j++) - { - if (Main.rand.Next(3) == 0) - { - save++; - } - } - stack -= save; - } - if (stack > 0) - { - foreach (Item tryItem in availableItems) - { - if (item.type == tryItem.type || RecipeGroupMatch(selectedRecipe, item.type, tryItem.type)) - { - if (tryItem.stack > stack) - { - Item temp = tryItem.Clone(); - temp.stack = stack; - toWithdraw.Add(temp); - tryItem.stack -= stack; - stack = 0; - } - else - { - toWithdraw.Add(tryItem.Clone()); - stack -= tryItem.stack; - tryItem.stack = 0; - tryItem.type = 0; - } - } - } - } - } - Item resultItem = selectedRecipe.createItem.Clone(); - resultItem.Prefix(-1); - - RecipeHooks.OnCraft(resultItem, selectedRecipe); - ItemLoader.OnCraft(resultItem, selectedRecipe); - - if (Main.netMode == 0) - { - foreach (Item item in DoCraft(GetHeart(), toWithdraw, resultItem)) - { - Main.player[Main.myPlayer].QuickSpawnClonedItem(item, item.stack); - } - } - else if (Main.netMode == 1) - { - NetHelper.SendCraftRequest(GetHeart().ID, toWithdraw, resultItem); - } - } - - internal static List DoCraft(TEStorageHeart heart, List toWithdraw, Item result) - { - List items = new List(); - foreach (Item tryWithdraw in toWithdraw) - { - Item withdrawn = heart.TryWithdraw(tryWithdraw); - if (!withdrawn.IsAir) - { - items.Add(withdrawn); - } - if (withdrawn.stack < tryWithdraw.stack) - { - for (int k = 0; k < items.Count; k++) - { - heart.DepositItem(items[k]); - if (items[k].IsAir) - { - items.RemoveAt(k); - k--; - } - } - return items; - } - } - items.Clear(); - heart.DepositItem(result); - if (!result.IsAir) - { - items.Add(result); - } - return items; - } - - private static bool TryDepositResult(Item item) - { - int oldStack = item.stack; - DoDepositResult(item); - return oldStack != item.stack; - } - - private static void DoDepositResult(Item item) - { - TEStorageHeart heart = GetHeart(); - if (Main.netMode == 0) - { - heart.DepositItem(item); - } - else - { - NetHelper.SendDeposit(heart.ID, item); - item.SetDefaults(0, true); - } - } - - private static Item DoWithdrawResult(Item item, bool toInventory = false) - { - TEStorageHeart heart = GetHeart(); - if (Main.netMode == 0) - { - return heart.TryWithdraw(item); - } - else - { - NetHelper.SendWithdraw(heart.ID, item, toInventory); - return new Item(); - } - } - } +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Input; +using Terraria; +using Terraria.DataStructures; +using Terraria.GameContent.UI.Elements; +using Terraria.ID; +using Terraria.Localization; +using Terraria.Map; +using Terraria.ModLoader; +using Terraria.UI; +using MagicStorage.Components; +using MagicStorage.Sorting; + +namespace MagicStorage +{ + public static class CraftingGUI + { + private const int padding = 4; + private const int numColumns = 10; + private const int numColumns2 = 7; + private const float inventoryScale = 0.85f; + private const float smallScale = 0.7f; + + static bool[] threadCheckListFoundItems; + static Mod _checkListMod; + + public static MouseState curMouse; + public static MouseState oldMouse; + public static bool MouseClicked + { + get + { + return curMouse.LeftButton == ButtonState.Pressed && oldMouse.LeftButton == ButtonState.Released; + } + } + + public static bool RightMouseClicked + { + get + { + return curMouse.RightButton == ButtonState.Pressed && oldMouse.RightButton == ButtonState.Released; + } + } + + private static UIPanel basePanel = new UIPanel(); + private static float panelTop; + private static float panelLeft; + private static float panelWidth; + private static float panelHeight; + + private static UIElement topBar = new UIElement(); + internal static UISearchBar searchBar; + private static UIButtonChoice sortButtons; + private static UIButtonChoice recipeButtons; + private static UIElement topBar2 = new UIElement(); + private static UIButtonChoice filterButtons; + internal static UISearchBar searchBar2; + + private static UIText stationText; + private static UISlotZone stationZone = new UISlotZone(HoverStation, GetStation, inventoryScale); + private static UIText recipeText; + private static UISlotZone recipeZone = new UISlotZone(HoverRecipe, GetRecipe, inventoryScale); + + internal static UIScrollbar scrollBar = new UIScrollbar(); + private static int scrollBarFocus = 0; + private static int scrollBarFocusMouseStart; + private static float scrollBarFocusPositionStart; + private static float scrollBarViewSize = 1f; + private static float scrollBarMaxViewSize = 2f; + + private static List items = new List(); + private static Dictionary itemCounts = new Dictionary(); + private static bool[] adjTiles = new bool[TileLoader.TileCount]; + private static bool adjWater = false; + private static bool adjLava = false; + private static bool adjHoney = false; + private static bool zoneSnow = false; + private static bool alchemyTable = false; + private static List recipes = new List(); + private static List recipeAvailable = new List(); + private static Recipe selectedRecipe = null; + private static int numRows; + private static int displayRows; + private static bool slotFocus = false; + + private static UIElement bottomBar = new UIElement(); + private static UIText capacityText; + + private static UIPanel recipePanel = new UIPanel(); + private static float recipeTop; + private static float recipeLeft; + private static float recipeWidth; + private static float recipeHeight; + + private static UIText recipePanelHeader; + private static UIText ingredientText; + private static UISlotZone ingredientZone = new UISlotZone(HoverItem, GetIngredient, smallScale); + private static UIText reqObjText; + private static UIText reqObjText2; + private static UIText storedItemsText; + + private static UISlotZone storageZone = new UISlotZone(HoverStorage, GetStorage, smallScale); + private static int numRows2; + private static int displayRows2; + private static List storageItems = new List(); + private static List blockStorageItems = new List(); + + internal static UIScrollbar scrollBar2 = new UIScrollbar(); + private static float scrollBar2ViewSize = 1f; + private static float scrollBar2MaxViewSize = 2f; + + internal static UITextPanel craftButton; + private static Item result = null; + private static UISlotZone resultZone = new UISlotZone(HoverResult, GetResult, inventoryScale); + private static int craftTimer = 0; + private const int startMaxCraftTimer = 20; + private static int maxCraftTimer = startMaxCraftTimer; + private static int rightClickTimer = 0; + private const int startMaxRightClickTimer = 20; + private static int maxRightClickTimer = startMaxRightClickTimer; + + private static Object threadLock = new Object(); + private static Object recipeLock = new Object(); + private static Object itemsLock = new Object(); + private static bool threadRunning = false; + internal static bool threadNeedsRestart = false; + private static SortMode threadSortMode; + private static FilterMode threadFilterMode; + private static List threadRecipes = new List(); + private static List threadRecipeAvailable = new List(); + private static List nextRecipes = new List(); + private static List nextRecipeAvailable = new List(); + + public static void Initialize() + { + lock (recipeLock) + { + recipes = nextRecipes; + recipeAvailable = nextRecipeAvailable; + } + + InitLangStuff(); + float itemSlotWidth = Main.inventoryBackTexture.Width * inventoryScale; + float itemSlotHeight = Main.inventoryBackTexture.Height * inventoryScale; + float smallSlotWidth = Main.inventoryBackTexture.Width * smallScale; + float smallSlotHeight = Main.inventoryBackTexture.Height * smallScale; + + panelTop = Main.instance.invBottom + 60; + panelLeft = 20f; + float innerPanelLeft = panelLeft + basePanel.PaddingLeft; + float innerPanelWidth = numColumns * (itemSlotWidth + padding) + 20f + padding; + panelWidth = basePanel.PaddingLeft + innerPanelWidth + basePanel.PaddingRight; + panelHeight = Main.screenHeight - panelTop - 40f; + basePanel.Left.Set(panelLeft, 0f); + basePanel.Top.Set(panelTop, 0f); + basePanel.Width.Set(panelWidth, 0f); + basePanel.Height.Set(panelHeight, 0f); + basePanel.Recalculate(); + + recipeTop = panelTop; + recipeLeft = panelLeft + panelWidth; + recipeWidth = numColumns2 * (smallSlotWidth + padding) + 20f + padding; + recipeWidth += recipePanel.PaddingLeft + recipePanel.PaddingRight; + recipeHeight = panelHeight; + recipePanel.Left.Set(recipeLeft, 0f); + recipePanel.Top.Set(recipeTop, 0f); + recipePanel.Width.Set(recipeWidth, 0f); + recipePanel.Height.Set(recipeHeight, 0f); + recipePanel.Recalculate(); + + topBar.Width.Set(0f, 1f); + topBar.Height.Set(32f, 0f); + basePanel.Append(topBar); + + InitSortButtons(); + topBar.Append(sortButtons); + float sortButtonsRight = sortButtons.GetDimensions().Width + padding; + InitRecipeButtons(); + float recipeButtonsLeft = sortButtonsRight + 32f + 3 * padding; + recipeButtons.Left.Set(recipeButtonsLeft, 0f); + topBar.Append(recipeButtons); + float recipeButtonsRight = recipeButtonsLeft + recipeButtons.GetDimensions().Width + padding; + + searchBar.Left.Set(recipeButtonsRight + padding, 0f); + searchBar.Width.Set(-recipeButtonsRight - 2 * padding, 1f); + searchBar.Height.Set(0f, 1f); + topBar.Append(searchBar); + + topBar2.Width.Set(0f, 1f); + topBar2.Height.Set(32f, 0f); + topBar2.Top.Set(36f, 0f); + basePanel.Append(topBar2); + + InitFilterButtons(); + float filterButtonsRight = filterButtons.GetDimensions().Width + padding; + topBar2.Append(filterButtons); + searchBar2.Left.Set(filterButtonsRight + padding, 0f); + searchBar2.Width.Set(-filterButtonsRight - 2 * padding, 1f); + searchBar2.Height.Set(0f, 1f); + topBar2.Append(searchBar2); + + stationText.Top.Set(76f, 0f); + basePanel.Append(stationText); + + stationZone.Width.Set(0f, 1f); + stationZone.Top.Set(100f, 0f); + stationZone.Height.Set(70f, 0f); + stationZone.SetDimensions(numColumns, 1); + basePanel.Append(stationZone); + + recipeText.Top.Set(152f, 0f); + basePanel.Append(recipeText); + + recipeZone.Width.Set(0f, 1f); + recipeZone.Top.Set(176f, 0f); + recipeZone.Height.Set(-216f, 1f); + basePanel.Append(recipeZone); + + numRows = (recipes.Count + numColumns - 1) / numColumns; + displayRows = (int)recipeZone.GetDimensions().Height / ((int)itemSlotHeight + padding); + recipeZone.SetDimensions(numColumns, displayRows); + int noDisplayRows = numRows - displayRows; + if (noDisplayRows < 0) + { + noDisplayRows = 0; + } + scrollBarMaxViewSize = 1 + noDisplayRows; + scrollBar.Height.Set(displayRows * (itemSlotHeight + padding), 0f); + scrollBar.Left.Set(-20f, 1f); + scrollBar.SetView(scrollBarViewSize, scrollBarMaxViewSize); + recipeZone.Append(scrollBar); + + bottomBar.Width.Set(0f, 1f); + bottomBar.Height.Set(32f, 0f); + bottomBar.Top.Set(-32f, 1f); + basePanel.Append(bottomBar); + + capacityText.Left.Set(6f, 0f); + capacityText.Top.Set(6f, 0f); + TEStorageHeart heart = GetHeart(); + int numItems = 0; + int capacity = 0; + if (heart != null) + { + foreach (TEAbstractStorageUnit abstractStorageUnit in heart.GetStorageUnits()) + { + if (abstractStorageUnit is TEStorageUnit) + { + TEStorageUnit storageUnit = (TEStorageUnit)abstractStorageUnit; + numItems += storageUnit.NumItems; + capacity += storageUnit.Capacity; + } + } + } + capacityText.SetText(numItems + "/" + capacity + " Items"); + bottomBar.Append(capacityText); + + recipePanel.Append(recipePanelHeader); + ingredientText.Top.Set(30f, 0f); + recipePanel.Append(ingredientText); + + ingredientZone.SetDimensions(numColumns2, 2); + ingredientZone.Top.Set(54f, 0f); + ingredientZone.Width.Set(0f, 1f); + ingredientZone.Height.Set(60f, 0f); + recipePanel.Append(ingredientZone); + + reqObjText.Top.Set(136f, 0f); + recipePanel.Append(reqObjText); + reqObjText2.Top.Set(160f, 0f); + recipePanel.Append(reqObjText2); + storedItemsText.Top.Set(190f, 0f); + recipePanel.Append(storedItemsText); + + storageZone.Top.Set(214f, 0f); + storageZone.Width.Set(0f, 1f); + storageZone.Height.Set(-214f - 36, 1f); + recipePanel.Append(storageZone); + numRows2 = (storageItems.Count + numColumns2 - 1) / numColumns2; + displayRows2 = (int)storageZone.GetDimensions().Height / ((int)smallSlotHeight + padding); + storageZone.SetDimensions(numColumns2, displayRows2); + int noDisplayRows2 = numRows2 - displayRows2; + if (noDisplayRows2 < 0) + { + noDisplayRows2 = 0; + } + scrollBar2MaxViewSize = 1 + noDisplayRows2; + scrollBar2.Height.Set(displayRows2 * (smallSlotHeight + padding), 0f); + scrollBar2.Left.Set(-20f, 1f); + scrollBar2.SetView(scrollBar2ViewSize, scrollBar2MaxViewSize); + storageZone.Append(scrollBar2); + + craftButton.Top.Set(-32f, 1f); + craftButton.Width.Set(100f, 0f); + craftButton.Height.Set(24f, 0f); + craftButton.PaddingTop = 8f; + craftButton.PaddingBottom = 8f; + recipePanel.Append(craftButton); + + resultZone.SetDimensions(1, 1); + resultZone.Left.Set(-itemSlotWidth, 1f); + resultZone.Top.Set(-itemSlotHeight, 1f); + resultZone.Width.Set(itemSlotWidth, 0f); + resultZone.Height.Set(itemSlotHeight, 0f); + recipePanel.Append(resultZone); + } + + private static void InitLangStuff() + { + if (searchBar == null) + { + searchBar = new UISearchBar(Language.GetText("Mods.MagicStorage.SearchName")); + } + if (searchBar2 == null) + { + searchBar2 = new UISearchBar(Language.GetText("Mods.MagicStorage.SearchMod")); + } + if (stationText == null) + { + stationText = new UIText(Language.GetText("Mods.MagicStorage.CraftingStations")); + } + if (recipeText == null) + { + recipeText = new UIText(Language.GetText("Mods.MagicStorage.Recipes")); + } + if (capacityText == null) + { + capacityText = new UIText("Items"); + } + if (recipePanelHeader == null) + { + recipePanelHeader = new UIText(Language.GetText("Mods.MagicStorage.SelectedRecipe")); + } + if (ingredientText == null) + { + ingredientText = new UIText(Language.GetText("Mods.MagicStorage.Ingredients")); + } + if (reqObjText == null) + { + reqObjText = new UIText(Language.GetText("LegacyInterface.22")); + } + if (reqObjText2 == null) + { + reqObjText2 = new UIText(""); + } + if (storedItemsText == null) + { + storedItemsText = new UIText(Language.GetText("Mods.MagicStorage.StoredItems")); + } + if (craftButton == null) + { + craftButton = new UITextPanel(Language.GetText("LegacyMisc.72"), 1f); + } + } + + private static void InitSortButtons() + { + if (sortButtons == null) + { + sortButtons = new UIButtonChoice(new Texture2D[] + { + Main.inventorySortTexture[0], + MagicStorage.Instance.GetTexture("SortID"), + MagicStorage.Instance.GetTexture("SortName") + }, + new LocalizedText[] + { + Language.GetText("Mods.MagicStorage.SortDefault"), + Language.GetText("Mods.MagicStorage.SortID"), + Language.GetText("Mods.MagicStorage.SortName") + }); + } + } + + private static void InitRecipeButtons() + { + if (recipeButtons == null) + { + recipeButtons = new UIButtonChoice(new Texture2D[] + { + MagicStorage.Instance.GetTexture("RecipeAvailable"), + MagicStorage.Instance.GetTexture("RecipeAll") + }, + new LocalizedText[] + { + Language.GetText("Mods.MagicStorage.RecipeAvailable"), + Language.GetText("Mods.MagicStorage.RecipeAll") + }); + } + } + + private static void InitFilterButtons() + { + if (filterButtons == null) + { + filterButtons = new UIButtonChoice(new Texture2D[] + { + MagicStorage.Instance.GetTexture("FilterAll"), + MagicStorage.Instance.GetTexture("FilterMelee"), + MagicStorage.Instance.GetTexture("FilterPickaxe"), + MagicStorage.Instance.GetTexture("FilterArmor"), + MagicStorage.Instance.GetTexture("FilterPotion"), + MagicStorage.Instance.GetTexture("FilterTile"), + MagicStorage.Instance.GetTexture("FilterMisc"), + }, + new LocalizedText[] + { + Language.GetText("Mods.MagicStorage.FilterAll"), + Language.GetText("Mods.MagicStorage.FilterWeapons"), + Language.GetText("Mods.MagicStorage.FilterTools"), + Language.GetText("Mods.MagicStorage.FilterEquips"), + Language.GetText("Mods.MagicStorage.FilterPotions"), + Language.GetText("Mods.MagicStorage.FilterTiles"), + Language.GetText("Mods.MagicStorage.FilterMisc") + }); + } + } + + public static void Update(GameTime gameTime) + {try{ + oldMouse = StorageGUI.oldMouse; + curMouse = StorageGUI.curMouse; + if (Main.playerInventory && Main.player[Main.myPlayer].GetModPlayer(MagicStorage.Instance).ViewingStorage().X >= 0 && StoragePlayer.IsStorageCrafting()) + { + if (curMouse.RightButton == ButtonState.Released) + { + ResetSlotFocus(); + } + basePanel.Update(gameTime); + recipePanel.Update(gameTime); + UpdateRecipeText(); + UpdateScrollBar(); + UpdateCraftButton(); + } + else + { + scrollBarFocus = 0; + selectedRecipe = null; + craftTimer = 0; + maxCraftTimer = startMaxCraftTimer; + ResetSlotFocus(); + }}catch(Exception e){Main.NewTextMultiline(e.ToString());} + } + + public static void Draw(TEStorageHeart heart) + {try{ + Player player = Main.player[Main.myPlayer]; + StoragePlayer modPlayer = player.GetModPlayer(MagicStorage.Instance); + Initialize(); + if (Main.mouseX > panelLeft && Main.mouseX < recipeLeft + panelWidth && Main.mouseY > panelTop && Main.mouseY < panelTop + panelHeight) + { + player.mouseInterface = true; + player.showItemIcon = false; + InterfaceHelper.HideItemIconCache(); + } + basePanel.Draw(Main.spriteBatch); + recipePanel.Draw(Main.spriteBatch); + Vector2 pos = recipeZone.GetDimensions().Position(); + if (threadRunning) + { + Utils.DrawBorderString(Main.spriteBatch, "Loading", pos + new Vector2(8f, 8f), Color.White); + } + stationZone.DrawText(); + recipeZone.DrawText(); + ingredientZone.DrawText(); + storageZone.DrawText(); + resultZone.DrawText(); + sortButtons.DrawText(); + recipeButtons.DrawText(); + filterButtons.DrawText();}catch(Exception e){Main.NewTextMultiline(e.ToString());} + } + + private static Item GetStation(int slot, ref int context) + { + Item[] stations = GetCraftingStations(); + if (stations == null || slot >= stations.Length) + { + return new Item(); + } + return stations[slot]; + } + + private static Item GetRecipe(int slot, ref int context) + { + if (threadRunning) + { + return new Item(); + } + int index = slot + numColumns * (int)Math.Round(scrollBar.ViewPosition); + Item item = index < recipes.Count ? recipes[index].createItem : new Item(); + if (!item.IsAir && recipes[index] == selectedRecipe) + { + context = 6; + } + if (!item.IsAir && !recipeAvailable[index]) + { + context = recipes[index] == selectedRecipe ? 4 : 3; + } + return item; + } + + private static Item GetIngredient(int slot, ref int context) + { + if (selectedRecipe == null || slot >= selectedRecipe.requiredItem.Length) + { + return new Item(); + } + Item item = selectedRecipe.requiredItem[slot].Clone(); + if (selectedRecipe.anyWood && item.type == ItemID.Wood) + { + item.SetNameOverride(Lang.misc[37].Value + " " + Lang.GetItemNameValue(ItemID.Wood)); + } + if (selectedRecipe.anySand && item.type == ItemID.SandBlock) + { + item.SetNameOverride(Lang.misc[37].Value + " " + Lang.GetItemNameValue(ItemID.SandBlock)); + } + if (selectedRecipe.anyIronBar && item.type == ItemID.IronBar) + { + item.SetNameOverride(Lang.misc[37].Value + " " + Lang.GetItemNameValue(ItemID.IronBar)); + } + if (selectedRecipe.anyFragment && item.type == ItemID.FragmentSolar) + { + item.SetNameOverride(Lang.misc[37].Value + " " + Lang.misc[51].Value); + } + if (selectedRecipe.anyPressurePlate && item.type == ItemID.GrayPressurePlate) + { + item.SetNameOverride(Lang.misc[37].Value + " " + Lang.misc[38].Value); + } + string nameOverride; + if (selectedRecipe.ProcessGroupsForText(item.type, out nameOverride)) + { + item.SetNameOverride(nameOverride); + } + return item; + } + + private static Item GetStorage(int slot, ref int context) + { + int index = slot + numColumns2 * (int)Math.Round(scrollBar2.ViewPosition); + Item item = index < storageItems.Count ? storageItems[index] : new Item(); + if (blockStorageItems.Contains(new ItemData(item))) + { + context = 3; + } + return item; + } + + private static Item GetResult(int slot, ref int context) + { + return slot == 0 && result != null ? result : new Item(); + } + + private static void UpdateRecipeText() + { + if (selectedRecipe == null) + { + reqObjText2.SetText(""); + } + else + { + bool isEmpty = true; + string text = ""; + for (int k = 0; k < selectedRecipe.requiredTile.Length; k++) + { + if (selectedRecipe.requiredTile[k] == -1) + { + break; + } + if (!isEmpty) + { + text += ", "; + } + text += Lang.GetMapObjectName(MapHelper.TileToLookup(selectedRecipe.requiredTile[k], 0)); + isEmpty = false; + } + if (selectedRecipe.needWater) + { + if (!isEmpty) + { + text += ", "; + } + text += Language.GetTextValue("LegacyInterface.53"); + isEmpty = false; + } + if (selectedRecipe.needHoney) + { + if (!isEmpty) + { + text += ", "; + } + text += Language.GetTextValue("LegacyInterface.58"); + isEmpty = false; + } + if (selectedRecipe.needLava) + { + if (!isEmpty) + { + text += ", "; + } + text += Language.GetTextValue("LegacyInterface.56"); + isEmpty = false; + } + if (selectedRecipe.needSnowBiome) + { + if (!isEmpty) + { + text += ", "; + } + text += Language.GetTextValue("LegacyInterface.123"); + isEmpty = false; + } + if (isEmpty) + { + text = Language.GetTextValue("LegacyInterface.23"); + } + reqObjText2.SetText(text); + } + } + + private static void UpdateScrollBar() + { + if (slotFocus) + { + scrollBarFocus = 0; + return; + } + Rectangle dim = scrollBar.GetClippingRectangle(Main.spriteBatch); + Vector2 boxPos = new Vector2(dim.X, dim.Y + dim.Height * (scrollBar.ViewPosition / scrollBarMaxViewSize)); + float boxWidth = 20f * Main.UIScale; + float boxHeight = dim.Height * (scrollBarViewSize / scrollBarMaxViewSize); + Rectangle dim2 = scrollBar2.GetClippingRectangle(Main.spriteBatch); + Vector2 box2Pos = new Vector2(dim2.X, dim2.Y + dim2.Height * (scrollBar2.ViewPosition / scrollBar2MaxViewSize)); + float box2Height = dim2.Height * (scrollBar2ViewSize / scrollBar2MaxViewSize); + if (scrollBarFocus > 0) + { + if (curMouse.LeftButton == ButtonState.Released) + { + scrollBarFocus = 0; + } + else + { + int difference = curMouse.Y - scrollBarFocusMouseStart; + if (scrollBarFocus == 1) + { + scrollBar.ViewPosition = scrollBarFocusPositionStart + (float)difference / boxHeight; + } + else if (scrollBarFocus == 2) + { + scrollBar2.ViewPosition = scrollBarFocusPositionStart + (float)difference / box2Height; + } + } + } + else if (MouseClicked) + { + if (curMouse.X > boxPos.X && curMouse.X < boxPos.X + boxWidth && curMouse.Y > boxPos.Y - 3f && curMouse.Y < boxPos.Y + boxHeight + 4f) + { + scrollBarFocus = 1; + scrollBarFocusMouseStart = curMouse.Y; + scrollBarFocusPositionStart = scrollBar.ViewPosition; + } + else if (curMouse.X > box2Pos.X && curMouse.X < box2Pos.X + boxWidth && curMouse.Y > box2Pos.Y - 3f && curMouse.Y < box2Pos.Y + box2Height + 4f) + { + scrollBarFocus = 2; + scrollBarFocusMouseStart = curMouse.Y; + scrollBarFocusPositionStart = scrollBar2.ViewPosition; + } + } + if (scrollBarFocus == 0) + { + int difference = oldMouse.ScrollWheelValue / 250 - curMouse.ScrollWheelValue / 250; + scrollBar.ViewPosition += difference; + } + } + + private static void UpdateCraftButton() + { + Rectangle dim = InterfaceHelper.GetFullRectangle(craftButton); + bool flag = false; + if (curMouse.X > dim.X && curMouse.X < dim.X + dim.Width && curMouse.Y > dim.Y && curMouse.Y < dim.Y + dim.Height) + { + craftButton.BackgroundColor = new Color(73, 94, 171); + if (curMouse.LeftButton == ButtonState.Pressed) + { + if (selectedRecipe != null && IsAvailable(selectedRecipe) && PassesBlock(selectedRecipe)) + { + if (craftTimer <= 0) + { + craftTimer = maxCraftTimer; + maxCraftTimer = maxCraftTimer * 3 / 4; + if (maxCraftTimer <= 0) + { + maxCraftTimer = 1; + } + TryCraft(); + RefreshItems(); + Main.PlaySound(7, -1, -1, 1); + } + craftTimer--; + flag = true; + StoragePlayer modPlayer = Main.player[Main.myPlayer].GetModPlayer(); + if (modPlayer.AddToCraftedRecipes(selectedRecipe.createItem)) + RefreshItems(); + } + } + } + else + { + craftButton.BackgroundColor = new Color(63, 82, 151) * 0.7f; + } + if (selectedRecipe == null || !IsAvailable(selectedRecipe) || !PassesBlock(selectedRecipe)) + { + craftButton.BackgroundColor = new Color(30, 40, 100) * 0.7f; + } + if (!flag) + { + craftTimer = 0; + maxCraftTimer = startMaxCraftTimer; + } + } + + private static TEStorageHeart GetHeart() + { + Player player = Main.player[Main.myPlayer]; + StoragePlayer modPlayer = player.GetModPlayer(); + return modPlayer.GetStorageHeart(); + } + + private static TECraftingAccess GetCraftingEntity() + { + Player player = Main.player[Main.myPlayer]; + StoragePlayer modPlayer = player.GetModPlayer(); + return modPlayer.GetCraftingAccess(); + } + + private static Item[] GetCraftingStations() + { + TECraftingAccess ent = GetCraftingEntity(); + return ent == null ? null : ent.stations; + } + + public static void RefreshItems() + { + items.Clear(); + TEStorageHeart heart = GetHeart(); + if (heart == null) + { + return; + } + items.AddRange(ItemSorter.SortAndFilter(heart.GetStoredItems(), SortMode.Id, FilterMode.All, "", "")); + AnalyzeIngredients(); + InitLangStuff(); + InitSortButtons(); + InitRecipeButtons(); + InitFilterButtons(); + SortMode sortMode; + switch (sortButtons.Choice) + { + case 0: + sortMode = SortMode.Default; + break; + case 1: + sortMode = SortMode.Id; + break; + case 2: + sortMode = SortMode.Name; + break; + default: + sortMode = SortMode.Default; + break; + } + FilterMode filterMode; + switch (filterButtons.Choice) + { + case 0: + filterMode = FilterMode.All; + break; + case 1: + filterMode = FilterMode.Weapons; + break; + case 2: + filterMode = FilterMode.Tools; + break; + case 3: + filterMode = FilterMode.Equipment; + break; + case 4: + filterMode = FilterMode.Potions; + break; + case 5: + filterMode = FilterMode.Placeables; + break; + case 6: + filterMode = FilterMode.Misc; + break; + default: + filterMode = FilterMode.All; + break; + } + RefreshStorageItems(); + + if (_checkListMod == null) + _checkListMod = ModLoader.GetMod("ItemChecklist"); + + var foundItems = _checkListMod != null ? _checkListMod.Call("RequestFoundItems") as bool[] : null; + + StoragePlayer modPlayer = Main.player[Main.myPlayer].GetModPlayer(); + var hiddenRecipes = new HashSet(modPlayer.HiddenRecipes.Select(x => x.type)); + var craftedRecipes = new HashSet(modPlayer.CraftedRecipes.Select(x => x.type)); + + lock (threadLock) + { + threadNeedsRestart = true; + threadSortMode = sortMode; + threadFilterMode = filterMode; + threadCheckListFoundItems = foundItems; + if (!threadRunning) + { + threadRunning = true; + Thread thread = new Thread(_ => RefreshRecipes(hiddenRecipes, craftedRecipes)); + thread.Start(); + } + } + } + + private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craftedRecipes) + { + while (true) + { + try + { + SortMode sortMode; + FilterMode filterMode; + lock (threadLock) + { + threadNeedsRestart = false; + sortMode = threadSortMode; + filterMode = threadFilterMode; + } + + + var temp = ItemSorter.GetRecipes(sortMode, filterMode, searchBar2.Text, searchBar.Text) + .Where(x => x != null) + .Where(x => (recipeButtons.Choice != 0) || !craftedRecipes.Contains(x.createItem.type)) + .Where(x => !hiddenRecipes.Contains(x.createItem.type)) + .Where(x => RecipeFilterMethod(x, craftedRecipes)); + + threadRecipes.Clear(); + threadRecipeAvailable.Clear(); + try + { + threadRecipes.AddRange(temp); + threadRecipeAvailable.AddRange(threadRecipes.Select(recipe => IsAvailable(recipe))); + } + catch (InvalidOperationException) + { + } + catch (KeyNotFoundException) + { + } + lock (recipeLock) + { + nextRecipes = new List(); + nextRecipeAvailable = new List(); + nextRecipes.AddRange(threadRecipes); + nextRecipeAvailable.AddRange(threadRecipeAvailable); + + } + lock (threadLock) + { + if (!threadNeedsRestart) + { + threadRunning = false; + return; + } + } + } + catch (Exception e) { Main.NewTextMultiline(e.ToString()); } + } + + + + } + + static bool RecipeFilterMethod(Recipe recipe, HashSet craftedSet) + { + if (threadCheckListFoundItems == null) return true; + if (recipeButtons.Choice == 0) + { + // first - only new + var t = recipe.createItem.type; + if (threadCheckListFoundItems[t] || craftedSet.Contains(t)) + { + // already encountered + return false; + } + } + else + { + // second button + } + for (int i = 0; i < Recipe.maxRequirements; i++) + { + var t = recipe.requiredItem[i].type; + if (t > 0 && !threadCheckListFoundItems[t] && !craftedSet.Contains(t)) + return false; + } + return true; + } + + private static void AnalyzeIngredients() + { + Player player = Main.player[Main.myPlayer]; + itemCounts.Clear(); + if (adjTiles.Length != player.adjTile.Length) + { + Array.Resize(ref adjTiles, player.adjTile.Length); + } + for (int k = 0; k < adjTiles.Length; k++) + { + adjTiles[k] = false; + } + adjWater = false; + adjLava = false; + adjHoney = false; + zoneSnow = false; + alchemyTable = false; + + foreach (Item item in items) + { + if (itemCounts.ContainsKey(item.netID)) + { + itemCounts[item.netID] += item.stack; + } + else + { + itemCounts[item.netID] = item.stack; + } + } + foreach (Item item in GetCraftingStations()) + { + if (item.createTile >= 0) + { + adjTiles[item.createTile] = true; + if (item.createTile == TileID.GlassKiln || item.createTile == TileID.Hellforge || item.createTile == TileID.AdamantiteForge) + { + adjTiles[TileID.Furnaces] = true; + } + if (item.createTile == TileID.AdamantiteForge) + { + adjTiles[TileID.Hellforge] = true; + } + if (item.createTile == TileID.MythrilAnvil) + { + adjTiles[TileID.Anvils] = true; + } + if (item.createTile == TileID.BewitchingTable || item.createTile == TileID.Tables2) + { + adjTiles[TileID.Tables] = true; + } + if (item.createTile == TileID.AlchemyTable) + { + adjTiles[TileID.Bottles] = true; + adjTiles[TileID.Tables] = true; + alchemyTable = true; + } + bool[] oldAdjTile = player.adjTile; + bool oldAdjWater = adjWater; + bool oldAdjLava = adjLava; + bool oldAdjHoney = adjHoney; + bool oldAlchemyTable = alchemyTable; + player.adjTile = adjTiles; + player.adjWater = false; + player.adjLava = false; + player.adjHoney = false; + player.alchemyTable = false; + TileLoader.AdjTiles(player, item.createTile); + if (player.adjWater) + { + adjWater = true; + } + if (player.adjLava) + { + adjLava = true; + } + if (player.adjHoney) + { + adjHoney = true; + } + if (player.alchemyTable) + { + alchemyTable = true; + } + player.adjTile = oldAdjTile; + player.adjWater = oldAdjWater; + player.adjLava = oldAdjLava; + player.adjHoney = oldAdjHoney; + player.alchemyTable = oldAlchemyTable; + } + if (item.type == ItemID.WaterBucket || item.type == ItemID.BottomlessBucket) + { + adjWater = true; + } + if (item.type == ItemID.LavaBucket) + { + adjLava = true; + } + if (item.type == ItemID.HoneyBucket) + { + adjHoney = true; + } + if (item.type == MagicStorage.Instance.ItemType("SnowBiomeEmulator")) + { + zoneSnow = true; + } + } + adjTiles[MagicStorage.Instance.TileType("CraftingAccess")] = true; + } + + private static bool IsAvailable(Recipe recipe) + { + foreach (int tile in recipe.requiredTile) + { + if (tile == -1) + { + break; + } + if (!adjTiles[tile]) + { + return false; + } + } + foreach (Item ingredient in recipe.requiredItem) + { + if (ingredient.type == 0) + { + break; + } + int stack = ingredient.stack; + bool useRecipeGroup = false; + foreach (int type in itemCounts.Keys) + { + if (RecipeGroupMatch(recipe, type, ingredient.type)) + { + stack -= itemCounts[type]; + useRecipeGroup = true; + } + } + if (!useRecipeGroup && itemCounts.ContainsKey(ingredient.netID)) + { + stack -= itemCounts[ingredient.netID]; + } + if (stack > 0) + { + return false; + } + } + if (recipe.needWater && !adjWater && !adjTiles[TileID.Sinks]) + { + return false; + } + if (recipe.needLava && !adjLava) + { + return false; + } + if (recipe.needHoney && !adjHoney) + { + return false; + } + if (recipe.needSnowBiome && !zoneSnow) + { + return false; + } + try + { + BlockRecipes.active = false; + if (!RecipeHooks.RecipeAvailable(recipe)) + { + return false; + } + } + finally + { + BlockRecipes.active = true; + } + return true; + } + + private static bool PassesBlock(Recipe recipe) + { + foreach (Item ingredient in recipe.requiredItem) + { + if (ingredient.type == 0) + { + break; + } + int stack = ingredient.stack; + bool useRecipeGroup = false; + foreach (Item item in storageItems) + { + ItemData data = new ItemData(item); + if (!blockStorageItems.Contains(data) && RecipeGroupMatch(recipe, item.netID, ingredient.type)) + { + stack -= item.stack; + useRecipeGroup = true; + } + } + if (!useRecipeGroup) + { + foreach (Item item in storageItems) + { + ItemData data = new ItemData(item); + if (!blockStorageItems.Contains(data) && item.netID == ingredient.netID) + { + stack -= item.stack; + } + } + } + if (stack > 0) + { + return false; + } + } + return true; + } + + private static void RefreshStorageItems() + { + storageItems.Clear(); + result = null; + if (selectedRecipe != null) + { + foreach (Item item in items) + { + for (int k = 0; k < selectedRecipe.requiredItem.Length; k++) + { + if (selectedRecipe.requiredItem[k].type == 0) + { + break; + } + if (item.type == selectedRecipe.requiredItem[k].type || RecipeGroupMatch(selectedRecipe, selectedRecipe.requiredItem[k].type, item.type)) + { + storageItems.Add(item); + } + } + if (item.type == selectedRecipe.createItem.type) + { + result = item; + } + } + if (result == null) + { + result = new Item(); + result.SetDefaults(selectedRecipe.createItem.type); + result.stack = 0; + } + } + } + + private static bool RecipeGroupMatch(Recipe recipe, int type1, int type2) + { + return recipe.useWood(type1, type2) || recipe.useSand(type1, type2) || recipe.useIronBar(type1, type2) || recipe.useFragment(type1, type2) || recipe.AcceptedByItemGroups(type1, type2) || recipe.usePressurePlate(type1, type2); + } + + private static void HoverStation(int slot, ref int hoverSlot) + { + TECraftingAccess ent = GetCraftingEntity(); + if (ent == null || slot >= ent.stations.Length) + { + return; + } + + Player player = Main.player[Main.myPlayer]; + if (MouseClicked) + { + bool changed = false; + if (!ent.stations[slot].IsAir && ItemSlot.ShiftInUse) + { + Item result = player.GetItem(Main.myPlayer, DoWithdraw(slot), false, true); + if (!result.IsAir && Main.mouseItem.IsAir) + { + Main.mouseItem = result; + result = new Item(); + } + if (!result.IsAir && Main.mouseItem.type == result.type && Main.mouseItem.stack < Main.mouseItem.maxStack) + { + Main.mouseItem.stack += result.stack; + result = new Item(); + } + if (!result.IsAir) + { + player.QuickSpawnClonedItem(result); + } + changed = true; + } + else if (player.itemAnimation == 0 && player.itemTime == 0) + { + int oldType = Main.mouseItem.type; + int oldStack = Main.mouseItem.stack; + Main.mouseItem = DoStationSwap(Main.mouseItem, slot); + if (oldType != Main.mouseItem.type || oldStack != Main.mouseItem.stack) + { + changed = true; + } + } + if (changed) + { + RefreshItems(); + Main.PlaySound(7, -1, -1, 1); + } + } + + hoverSlot = slot; + } + + private static void HoverRecipe(int slot, ref int hoverSlot) + { + int visualSlot = slot; + slot += numColumns * (int)Math.Round(scrollBar.ViewPosition); + if (slot < recipes.Count) + { + if (MouseClicked) + { + selectedRecipe = recipes[slot]; + RefreshStorageItems(); + blockStorageItems.Clear(); + } + else if (RightMouseClicked) + { + StoragePlayer modPlayer = Main.player[Main.myPlayer].GetModPlayer(); + if (modPlayer.AddToHiddenRecipes(recipes[slot].createItem)) + RefreshItems(); + } + hoverSlot = visualSlot; + } + } + + private static void HoverItem(int slot, ref int hoverSlot) + { + hoverSlot = slot; + } + + private static void HoverStorage(int slot, ref int hoverSlot) + { + int visualSlot = slot; + slot += numColumns2 * (int)Math.Round(scrollBar2.ViewPosition); + if (slot < storageItems.Count) + { + if (MouseClicked) + { + ItemData data = new ItemData(storageItems[slot]); + if (blockStorageItems.Contains(data)) + { + blockStorageItems.Remove(data); + } + else + { + blockStorageItems.Add(data); + } + } + hoverSlot = visualSlot; + } + } + + private static void HoverResult(int slot, ref int hoverSlot) + { + if (slot != 0) + { + return; + } + + Player player = Main.player[Main.myPlayer]; + if (MouseClicked) + { + bool changed = false; + if (!Main.mouseItem.IsAir && player.itemAnimation == 0 && player.itemTime == 0 && result != null && Main.mouseItem.type == result.type) + { + if (TryDepositResult(Main.mouseItem)) + { + changed = true; + } + } + else if (Main.mouseItem.IsAir && result != null && !result.IsAir) + { + Item toWithdraw = result.Clone(); + if (toWithdraw.stack > toWithdraw.maxStack) + { + toWithdraw.stack = toWithdraw.maxStack; + } + Main.mouseItem = DoWithdrawResult(toWithdraw, ItemSlot.ShiftInUse); + if (ItemSlot.ShiftInUse) + { + Main.mouseItem = player.GetItem(Main.myPlayer, Main.mouseItem, false, true); + } + changed = true; + } + if (changed) + { + RefreshItems(); + Main.PlaySound(7, -1, -1, 1); + } + } + + if (curMouse.RightButton == ButtonState.Pressed && oldMouse.RightButton == ButtonState.Released && result != null && !result.IsAir && (Main.mouseItem.IsAir || ItemData.Matches(Main.mouseItem, items[slot]) && Main.mouseItem.stack < Main.mouseItem.maxStack)) + { + slotFocus = true; + } + + hoverSlot = slot; + + if (slotFocus) + { + SlotFocusLogic(); + } + } + + private static void SlotFocusLogic() + { + if (result == null || result.IsAir || (!Main.mouseItem.IsAir && (!ItemData.Matches(Main.mouseItem, result) || Main.mouseItem.stack >= Main.mouseItem.maxStack))) + { + ResetSlotFocus(); + } + else + { + if (rightClickTimer <= 0) + { + rightClickTimer = maxRightClickTimer; + maxRightClickTimer = maxRightClickTimer * 3 / 4; + if (maxRightClickTimer <= 0) + { + maxRightClickTimer = 1; + } + Item toWithdraw = result.Clone(); + toWithdraw.stack = 1; + Item withdrawn = DoWithdrawResult(toWithdraw); + if (Main.mouseItem.IsAir) + { + Main.mouseItem = withdrawn; + } + else + { + Main.mouseItem.stack += withdrawn.stack; + } + Main.soundInstanceMenuTick.Stop(); + Main.soundInstanceMenuTick = Main.soundMenuTick.CreateInstance(); + Main.PlaySound(12, -1, -1, 1); + RefreshItems(); + } + rightClickTimer--; + } + } + + private static void ResetSlotFocus() + { + slotFocus = false; + rightClickTimer = 0; + maxRightClickTimer = startMaxRightClickTimer; + } + + private static Item DoWithdraw(int slot) + { + TECraftingAccess access = GetCraftingEntity(); + if (Main.netMode == 0) + { + Item result = access.TryWithdrawStation(slot); + RefreshItems(); + return result; + } + else + { + NetHelper.SendWithdrawStation(access.ID, slot); + return new Item(); + } + } + + private static Item DoStationSwap(Item item, int slot) + { + TECraftingAccess access = GetCraftingEntity(); + if (Main.netMode == 0) + { + Item result = access.DoStationSwap(item, slot); + RefreshItems(); + return result; + } + else + { + NetHelper.SendStationSlotClick(access.ID, item, slot); + return new Item(); + } + } + + private static void TryCraft() + { + List availableItems = new List(storageItems.Where(item => !blockStorageItems.Contains(new ItemData(item))).Select(item => item.Clone())); + List toWithdraw = new List(); + for (int k = 0; k < selectedRecipe.requiredItem.Length; k++) + { + Item item = selectedRecipe.requiredItem[k]; + if (item.type == 0) + { + break; + } + int stack = item.stack; + ModRecipe modRecipe = selectedRecipe as ModRecipe; + if (modRecipe != null) + { + stack = modRecipe.ConsumeItem(item.type, item.stack); + } + if (selectedRecipe.alchemy && alchemyTable) + { + int save = 0; + for (int j = 0; j < stack; j++) + { + if (Main.rand.Next(3) == 0) + { + save++; + } + } + stack -= save; + } + if (stack > 0) + { + foreach (Item tryItem in availableItems) + { + if (item.type == tryItem.type || RecipeGroupMatch(selectedRecipe, item.type, tryItem.type)) + { + if (tryItem.stack > stack) + { + Item temp = tryItem.Clone(); + temp.stack = stack; + toWithdraw.Add(temp); + tryItem.stack -= stack; + stack = 0; + } + else + { + toWithdraw.Add(tryItem.Clone()); + stack -= tryItem.stack; + tryItem.stack = 0; + tryItem.type = 0; + } + } + } + } + } + Item resultItem = selectedRecipe.createItem.Clone(); + resultItem.Prefix(-1); + + RecipeHooks.OnCraft(resultItem, selectedRecipe); + ItemLoader.OnCraft(resultItem, selectedRecipe); + + if (Main.netMode == 0) + { + foreach (Item item in DoCraft(GetHeart(), toWithdraw, resultItem)) + { + Main.player[Main.myPlayer].QuickSpawnClonedItem(item, item.stack); + } + } + else if (Main.netMode == 1) + { + NetHelper.SendCraftRequest(GetHeart().ID, toWithdraw, resultItem); + } + } + + internal static List DoCraft(TEStorageHeart heart, List toWithdraw, Item result) + { + List items = new List(); + foreach (Item tryWithdraw in toWithdraw) + { + Item withdrawn = heart.TryWithdraw(tryWithdraw); + if (!withdrawn.IsAir) + { + items.Add(withdrawn); + } + if (withdrawn.stack < tryWithdraw.stack) + { + for (int k = 0; k < items.Count; k++) + { + heart.DepositItem(items[k]); + if (items[k].IsAir) + { + items.RemoveAt(k); + k--; + } + } + return items; + } + } + items.Clear(); + heart.DepositItem(result); + if (!result.IsAir) + { + items.Add(result); + } + return items; + } + + private static bool TryDepositResult(Item item) + { + int oldStack = item.stack; + DoDepositResult(item); + return oldStack != item.stack; + } + + private static void DoDepositResult(Item item) + { + TEStorageHeart heart = GetHeart(); + if (Main.netMode == 0) + { + heart.DepositItem(item); + } + else + { + NetHelper.SendDeposit(heart.ID, item); + item.SetDefaults(0, true); + } + } + + private static Item DoWithdrawResult(Item item, bool toInventory = false) + { + TEStorageHeart heart = GetHeart(); + if (Main.netMode == 0) + { + return heart.TryWithdraw(item); + } + else + { + NetHelper.SendWithdraw(heart.ID, item, toInventory); + return new Item(); + } + } + } } \ No newline at end of file diff --git a/ItemHideList.cs b/ItemHideList.cs new file mode 100644 index 00000000..cb95c8ef --- /dev/null +++ b/ItemHideList.cs @@ -0,0 +1,43 @@ +using System.Collections.Generic; +using System.Linq; +using Terraria; +using Terraria.ModLoader.IO; + +namespace MagicStorage +{ + public class ItemHideList + { + readonly string _name; + List _items = new List(); + HashSet _set = new HashSet(); + + public ItemHideList(string name) + { + _name = name; + } + + public IEnumerable Items { get { return _items; } } + + public bool Add(Item item) + { + if (_set.Add(item.type)) + { + _items.Add(item); + return true; + } + return false; + } + + public void Save(TagCompound c) + { + c.Add(_name, _items.Select(ItemIO.Save).ToList()); + } + + public void Load(TagCompound tag) + { + var list = tag.GetList(_name); + _items = list != null ? list.Select(ItemIO.Load).ToList() : new List(); + _set = new HashSet(_items.Select(x => x.type)); + } + } +} \ No newline at end of file diff --git a/MagicStorage.cs b/MagicStorage.cs index 7e5754f0..855ea136 100644 --- a/MagicStorage.cs +++ b/MagicStorage.cs @@ -192,13 +192,13 @@ private void AddTranslations() AddTranslation(text); text = CreateTranslation("RecipeAvailable"); - text.SetDefault("Show available recipes"); + text.SetDefault("Show new recipes"); text.AddTranslation(GameCulture.French, "Afficher les recettes disponibles"); text.AddTranslation(GameCulture.Spanish, "Mostrar recetas disponibles"); AddTranslation(text); text = CreateTranslation("RecipeAll"); - text.SetDefault("Show all recipes"); + text.SetDefault("Show all known recipes"); text.AddTranslation(GameCulture.French, "Afficher toutes les recettes"); text.AddTranslation(GameCulture.Spanish, "Mostrar todas las recetas"); AddTranslation(text); diff --git a/StoragePlayer.cs b/StoragePlayer.cs index aa6d8112..eadfe542 100644 --- a/StoragePlayer.cs +++ b/StoragePlayer.cs @@ -1,217 +1,250 @@ -using System; -using System.Collections.Generic; -using Terraria; -using Terraria.DataStructures; -using Terraria.ModLoader; -using Terraria.UI; -using MagicStorage.Components; - -namespace MagicStorage -{ - public class StoragePlayer : ModPlayer - { - public int timeSinceOpen = 1; - private Point16 storageAccess = new Point16(-1, -1); - public bool remoteAccess = false; - - public override void UpdateDead() - { - if (player.whoAmI == Main.myPlayer) - { - CloseStorage(); - } - } - - public override void ResetEffects() - { - if (player.whoAmI != Main.myPlayer) - { - return; - } - if (timeSinceOpen < 1) - { - player.talkNPC = -1; - Main.playerInventory = true; - timeSinceOpen++; - } - if (storageAccess.X >= 0 && storageAccess.Y >= 0 && (player.chest != -1 || !Main.playerInventory || player.sign > -1 || player.talkNPC > -1)) - { - CloseStorage(); - Recipe.FindRecipes(); - } - else if (storageAccess.X >= 0 && storageAccess.Y >= 0) - { - int playerX = (int)(player.Center.X / 16f); - int playerY = (int)(player.Center.Y / 16f); - if (!remoteAccess && (playerX < storageAccess.X - Player.tileRangeX || playerX > storageAccess.X + Player.tileRangeX + 1 || playerY < storageAccess.Y - Player.tileRangeY || playerY > storageAccess.Y + Player.tileRangeY + 1)) - { - Main.PlaySound(11, -1, -1, 1); - CloseStorage(); - Recipe.FindRecipes(); - } - else if (!(TileLoader.GetTile(Main.tile[storageAccess.X, storageAccess.Y].type) is StorageAccess)) - { - Main.PlaySound(11, -1, -1, 1); - CloseStorage(); - Recipe.FindRecipes(); - } - } - } - - public void OpenStorage(Point16 point, bool remote = false) - { - storageAccess = point; - remoteAccess = remote; - StorageGUI.RefreshItems(); - } - - public void CloseStorage() - { - storageAccess = new Point16(-1, -1); - Main.blockInput = false; - if (StorageGUI.searchBar != null) - { - StorageGUI.searchBar.Reset(); - } - if (StorageGUI.searchBar2 != null) - { - StorageGUI.searchBar2.Reset(); - } - if (CraftingGUI.searchBar != null) - { - CraftingGUI.searchBar.Reset(); - } - if (CraftingGUI.searchBar2 != null) - { - CraftingGUI.searchBar2.Reset(); - } - } - - public Point16 ViewingStorage() - { - return storageAccess; - } - - public static void GetItem(Item item, bool toMouse) - { - Player player = Main.player[Main.myPlayer]; - if (toMouse && Main.playerInventory && Main.mouseItem.IsAir) - { - Main.mouseItem = item; - item = new Item(); - } - else if (toMouse && Main.playerInventory && Main.mouseItem.type == item.type) - { - int total = Main.mouseItem.stack + item.stack; - if (total > Main.mouseItem.maxStack) - { - total = Main.mouseItem.maxStack; - } - int difference = total - Main.mouseItem.stack; - Main.mouseItem.stack = total; - item.stack -= difference; - } - if (!item.IsAir) - { - item = player.GetItem(Main.myPlayer, item, false, true); - if (!item.IsAir) - { - player.QuickSpawnClonedItem(item, item.stack); - } - } - } - - public override bool ShiftClickSlot(Item[] inventory, int context, int slot) - { - if (context != ItemSlot.Context.InventoryItem && context != ItemSlot.Context.InventoryCoin && context != ItemSlot.Context.InventoryAmmo) - { - return false; - } - if (storageAccess.X < 0 || storageAccess.Y < 0) - { - return false; - } - Item item = inventory[slot]; - if (item.favorited || item.IsAir) - { - return false; - } - int oldType = item.type; - int oldStack = item.stack; - if (StorageCrafting()) - { - if (Main.netMode == 0) - { - GetCraftingAccess().TryDepositStation(item); - } - else - { - NetHelper.SendDepositStation(GetCraftingAccess().ID, item); - item.SetDefaults(0, true); - } - } - else - { - if (Main.netMode == 0) - { - GetStorageHeart().DepositItem(item); - } - else - { - NetHelper.SendDeposit(GetStorageHeart().ID, item); - item.SetDefaults(0, true); - } - } - if (item.type != oldType || item.stack != oldStack) - { - Main.PlaySound(7, -1, -1, 1, 1f, 0f); - StorageGUI.RefreshItems(); - } - return true; - } - - public TEStorageHeart GetStorageHeart() - { - if (storageAccess.X < 0 || storageAccess.Y < 0) - { - return null; - } - Tile tile = Main.tile[storageAccess.X, storageAccess.Y]; - if (tile == null) - { - return null; - } - int tileType = tile.type; - ModTile modTile = TileLoader.GetTile(tileType); - if (modTile == null || !(modTile is StorageAccess)) - { - return null; - } - return ((StorageAccess)modTile).GetHeart(storageAccess.X, storageAccess.Y); - } - - public TECraftingAccess GetCraftingAccess() - { - if (storageAccess.X < 0 || storageAccess.Y < 0 || !TileEntity.ByPosition.ContainsKey(storageAccess)) - { - return null; - } - return TileEntity.ByPosition[storageAccess] as TECraftingAccess; - } - - public bool StorageCrafting() - { - if (storageAccess.X < 0 || storageAccess.Y < 0) - { - return false; - } - Tile tile = Main.tile[storageAccess.X, storageAccess.Y]; - return tile != null && tile.type == mod.TileType("CraftingAccess"); - } - - public static bool IsStorageCrafting() - { - return Main.player[Main.myPlayer].GetModPlayer().StorageCrafting(); - } - } +using System; +using System.Collections.Generic; +using System.Linq; +using Terraria; +using Terraria.DataStructures; +using Terraria.ModLoader; +using Terraria.UI; +using MagicStorage.Components; +using Terraria.ModLoader.IO; + +namespace MagicStorage +{ + public class StoragePlayer : ModPlayer + { + public int timeSinceOpen = 1; + private Point16 storageAccess = new Point16(-1, -1); + public bool remoteAccess = false; + + ItemHideList _hiddenRecipes = new ItemHideList("HiddenItems"); + ItemHideList _craftedRecipes = new ItemHideList("CraftedRecipes"); + + public IEnumerable HiddenRecipes { get { return _hiddenRecipes.Items; } } + public IEnumerable CraftedRecipes { get { return _craftedRecipes.Items; } } + + public bool AddToHiddenRecipes(Item item) + { + return _hiddenRecipes.Add(item); + } + + public bool AddToCraftedRecipes(Item item) + { + return _craftedRecipes.Add(item); + } + + public override TagCompound Save() + { + var c = new TagCompound(); + _hiddenRecipes.Save(c); + _craftedRecipes.Save(c); + return c; + } + + public override void Load(TagCompound tag) + { + _hiddenRecipes.Load(tag); + _craftedRecipes.Load(tag); + + } + + public override void UpdateDead() + { + if (player.whoAmI == Main.myPlayer) + { + CloseStorage(); + } + } + + public override void ResetEffects() + { + if (player.whoAmI != Main.myPlayer) + { + return; + } + if (timeSinceOpen < 1) + { + player.talkNPC = -1; + Main.playerInventory = true; + timeSinceOpen++; + } + if (storageAccess.X >= 0 && storageAccess.Y >= 0 && (player.chest != -1 || !Main.playerInventory || player.sign > -1 || player.talkNPC > -1)) + { + CloseStorage(); + Recipe.FindRecipes(); + } + else if (storageAccess.X >= 0 && storageAccess.Y >= 0) + { + int playerX = (int)(player.Center.X / 16f); + int playerY = (int)(player.Center.Y / 16f); + if (!remoteAccess && (playerX < storageAccess.X - Player.tileRangeX || playerX > storageAccess.X + Player.tileRangeX + 1 || playerY < storageAccess.Y - Player.tileRangeY || playerY > storageAccess.Y + Player.tileRangeY + 1)) + { + Main.PlaySound(11, -1, -1, 1); + CloseStorage(); + Recipe.FindRecipes(); + } + else if (!(TileLoader.GetTile(Main.tile[storageAccess.X, storageAccess.Y].type) is StorageAccess)) + { + Main.PlaySound(11, -1, -1, 1); + CloseStorage(); + Recipe.FindRecipes(); + } + } + } + + public void OpenStorage(Point16 point, bool remote = false) + { + storageAccess = point; + remoteAccess = remote; + StorageGUI.RefreshItems(); + } + + public void CloseStorage() + { + storageAccess = new Point16(-1, -1); + Main.blockInput = false; + if (StorageGUI.searchBar != null) + { + StorageGUI.searchBar.Reset(); + } + if (StorageGUI.searchBar2 != null) + { + StorageGUI.searchBar2.Reset(); + } + if (CraftingGUI.searchBar != null) + { + CraftingGUI.searchBar.Reset(); + } + if (CraftingGUI.searchBar2 != null) + { + CraftingGUI.searchBar2.Reset(); + } + } + + public Point16 ViewingStorage() + { + return storageAccess; + } + + public static void GetItem(Item item, bool toMouse) + { + Player player = Main.player[Main.myPlayer]; + if (toMouse && Main.playerInventory && Main.mouseItem.IsAir) + { + Main.mouseItem = item; + item = new Item(); + } + else if (toMouse && Main.playerInventory && Main.mouseItem.type == item.type) + { + int total = Main.mouseItem.stack + item.stack; + if (total > Main.mouseItem.maxStack) + { + total = Main.mouseItem.maxStack; + } + int difference = total - Main.mouseItem.stack; + Main.mouseItem.stack = total; + item.stack -= difference; + } + if (!item.IsAir) + { + item = player.GetItem(Main.myPlayer, item, false, true); + if (!item.IsAir) + { + player.QuickSpawnClonedItem(item, item.stack); + } + } + } + + public override bool ShiftClickSlot(Item[] inventory, int context, int slot) + { + if (context != ItemSlot.Context.InventoryItem && context != ItemSlot.Context.InventoryCoin && context != ItemSlot.Context.InventoryAmmo) + { + return false; + } + if (storageAccess.X < 0 || storageAccess.Y < 0) + { + return false; + } + Item item = inventory[slot]; + if (item.favorited || item.IsAir) + { + return false; + } + int oldType = item.type; + int oldStack = item.stack; + if (StorageCrafting()) + { + if (Main.netMode == 0) + { + GetCraftingAccess().TryDepositStation(item); + } + else + { + NetHelper.SendDepositStation(GetCraftingAccess().ID, item); + item.SetDefaults(0, true); + } + } + else + { + if (Main.netMode == 0) + { + GetStorageHeart().DepositItem(item); + } + else + { + NetHelper.SendDeposit(GetStorageHeart().ID, item); + item.SetDefaults(0, true); + } + } + if (item.type != oldType || item.stack != oldStack) + { + Main.PlaySound(7, -1, -1, 1, 1f, 0f); + StorageGUI.RefreshItems(); + } + return true; + } + + public TEStorageHeart GetStorageHeart() + { + if (storageAccess.X < 0 || storageAccess.Y < 0) + { + return null; + } + Tile tile = Main.tile[storageAccess.X, storageAccess.Y]; + if (tile == null) + { + return null; + } + int tileType = tile.type; + ModTile modTile = TileLoader.GetTile(tileType); + if (modTile == null || !(modTile is StorageAccess)) + { + return null; + } + return ((StorageAccess)modTile).GetHeart(storageAccess.X, storageAccess.Y); + } + + public TECraftingAccess GetCraftingAccess() + { + if (storageAccess.X < 0 || storageAccess.Y < 0 || !TileEntity.ByPosition.ContainsKey(storageAccess)) + { + return null; + } + return TileEntity.ByPosition[storageAccess] as TECraftingAccess; + } + + public bool StorageCrafting() + { + if (storageAccess.X < 0 || storageAccess.Y < 0) + { + return false; + } + Tile tile = Main.tile[storageAccess.X, storageAccess.Y]; + return tile != null && tile.type == mod.TileType("CraftingAccess"); + } + + public static bool IsStorageCrafting() + { + return Main.player[Main.myPlayer].GetModPlayer().StorageCrafting(); + } + } } \ No newline at end of file From 79230f2296e8da25350296e70071b91f2e443b97 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sat, 11 Aug 2018 20:37:07 +0300 Subject: [PATCH 05/80] button to show blacklist and right click to remove from it --- CraftingGUI.cs | 43 +++++++++++++++++++++++++++++-------------- ItemHideList.cs | 10 ++++++++++ MagicStorage.cs | 8 ++++---- StoragePlayer.cs | 5 +++++ 4 files changed, 48 insertions(+), 18 deletions(-) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 8906960b..c33a0af3 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -20,7 +20,9 @@ namespace MagicStorage { public static class CraftingGUI { - private const int padding = 4; + const int RecipeButtonsNewChoice = 0; + const int RecipeButtonsBlacklistChoice = 2; + private const int padding = 4; private const int numColumns = 10; private const int numColumns2 = 7; private const float inventoryScale = 0.85f; @@ -122,7 +124,8 @@ public static bool RightMouseClicked private static int maxCraftTimer = startMaxCraftTimer; private static int rightClickTimer = 0; private const int startMaxRightClickTimer = 20; - private static int maxRightClickTimer = startMaxRightClickTimer; + + private static int maxRightClickTimer = startMaxRightClickTimer; private static Object threadLock = new Object(); private static Object recipeLock = new Object(); @@ -181,7 +184,7 @@ public static void Initialize() topBar.Append(sortButtons); float sortButtonsRight = sortButtons.GetDimensions().Width + padding; InitRecipeButtons(); - float recipeButtonsLeft = sortButtonsRight + 32f + 3 * padding; + float recipeButtonsLeft = sortButtonsRight + 3 * padding; recipeButtons.Left.Set(recipeButtonsLeft, 0f); topBar.Append(recipeButtons); float recipeButtonsRight = recipeButtonsLeft + recipeButtons.GetDimensions().Width + padding; @@ -384,13 +387,15 @@ private static void InitRecipeButtons() recipeButtons = new UIButtonChoice(new Texture2D[] { MagicStorage.Instance.GetTexture("RecipeAvailable"), - MagicStorage.Instance.GetTexture("RecipeAll") + MagicStorage.Instance.GetTexture("RecipeAll"), + MagicStorage.Instance.GetTexture("RecipeAll"), }, new LocalizedText[] { Language.GetText("Mods.MagicStorage.RecipeAvailable"), - Language.GetText("Mods.MagicStorage.RecipeAll") - }); + Language.GetText("Mods.MagicStorage.RecipeAll"), + Language.GetText("Mods.MagicStorage.RecipeBlacklist") + }); } } @@ -844,10 +849,12 @@ private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craf var temp = ItemSorter.GetRecipes(sortMode, filterMode, searchBar2.Text, searchBar.Text) - .Where(x => x != null) - .Where(x => (recipeButtons.Choice != 0) || !craftedRecipes.Contains(x.createItem.type)) - .Where(x => !hiddenRecipes.Contains(x.createItem.type)) - .Where(x => RecipeFilterMethod(x, craftedRecipes)); + .Where(x => x != null) + // only new recipes (not crafted previously) filter (new - button choice = 0) + .Where(x => (recipeButtons.Choice != RecipeButtonsNewChoice) || !craftedRecipes.Contains(x.createItem.type)) + // show only blacklisted recipes only if choice = 2, otherwise show all other + .Where(x => (recipeButtons.Choice == RecipeButtonsBlacklistChoice) == hiddenRecipes.Contains(x.createItem.type)) + .Where(x => FilterKnownRecipesMethod(x, craftedRecipes)); threadRecipes.Clear(); threadRecipeAvailable.Clear(); @@ -886,10 +893,10 @@ private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craf } - static bool RecipeFilterMethod(Recipe recipe, HashSet craftedSet) + static bool FilterKnownRecipesMethod(Recipe recipe, HashSet craftedSet) { if (threadCheckListFoundItems == null) return true; - if (recipeButtons.Choice == 0) + if (recipeButtons.Choice == RecipeButtonsNewChoice) { // first - only new var t = recipe.createItem.type; @@ -1232,8 +1239,16 @@ private static void HoverRecipe(int slot, ref int hoverSlot) else if (RightMouseClicked) { StoragePlayer modPlayer = Main.player[Main.myPlayer].GetModPlayer(); - if (modPlayer.AddToHiddenRecipes(recipes[slot].createItem)) - RefreshItems(); + if (recipeButtons.Choice == RecipeButtonsBlacklistChoice) + { + if (modPlayer.RemoveFromHiddenRecipes(recipes[slot].createItem)) + RefreshItems(); + } + else + { + if (modPlayer.AddToHiddenRecipes(recipes[slot].createItem)) + RefreshItems(); + } } hoverSlot = visualSlot; } diff --git a/ItemHideList.cs b/ItemHideList.cs index cb95c8ef..f8df613d 100644 --- a/ItemHideList.cs +++ b/ItemHideList.cs @@ -28,6 +28,16 @@ public bool Add(Item item) return false; } + public bool Remove(Item item) + { + if (_set.Remove(item.type)) + { + _items.RemoveAll(x => x.type == item.type); + return true; + } + return false; + } + public void Save(TagCompound c) { c.Add(_name, _items.Select(ItemIO.Save).ToList()); diff --git a/MagicStorage.cs b/MagicStorage.cs index 855ea136..7b44469d 100644 --- a/MagicStorage.cs +++ b/MagicStorage.cs @@ -193,14 +193,14 @@ private void AddTranslations() text = CreateTranslation("RecipeAvailable"); text.SetDefault("Show new recipes"); - text.AddTranslation(GameCulture.French, "Afficher les recettes disponibles"); - text.AddTranslation(GameCulture.Spanish, "Mostrar recetas disponibles"); AddTranslation(text); text = CreateTranslation("RecipeAll"); text.SetDefault("Show all known recipes"); - text.AddTranslation(GameCulture.French, "Afficher toutes les recettes"); - text.AddTranslation(GameCulture.Spanish, "Mostrar todas las recetas"); + AddTranslation(text); + + text = CreateTranslation("RecipeBlacklist"); + text.SetDefault("Show hidden recipes"); AddTranslation(text); } diff --git a/StoragePlayer.cs b/StoragePlayer.cs index eadfe542..27261f15 100644 --- a/StoragePlayer.cs +++ b/StoragePlayer.cs @@ -27,6 +27,11 @@ public bool AddToHiddenRecipes(Item item) return _hiddenRecipes.Add(item); } + public bool RemoveFromHiddenRecipes(Item item) + { + return _hiddenRecipes.Remove(item); + } + public bool AddToCraftedRecipes(Item item) { return _craftedRecipes.Add(item); From 6d53e341665cdf256f08e4df3f56448b29cf0ca9 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sat, 11 Aug 2018 21:25:52 +0300 Subject: [PATCH 06/80] sorting by value --- CraftingGUI.cs | 12 +- MagicStorage.cs | 5 +- MagicStorage.csproj | 261 ++++++++++++++++---------------- Sorting/BTree.cs | 298 ------------------------------------- Sorting/CompareFunction.cs | 10 +- Sorting/DefaultSorting.cs | 2 +- Sorting/ItemSorter.cs | 42 ++---- Sorting/SortMode.cs | 2 +- StorageGUI.cs | 2 +- 9 files changed, 163 insertions(+), 471 deletions(-) delete mode 100644 Sorting/BTree.cs diff --git a/CraftingGUI.cs b/CraftingGUI.cs index c33a0af3..5abf0025 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -369,14 +369,17 @@ private static void InitSortButtons() { Main.inventorySortTexture[0], MagicStorage.Instance.GetTexture("SortID"), - MagicStorage.Instance.GetTexture("SortName") + MagicStorage.Instance.GetTexture("SortName"), + MagicStorage.Instance.GetTexture("SortNumber") }, new LocalizedText[] { Language.GetText("Mods.MagicStorage.SortDefault"), Language.GetText("Mods.MagicStorage.SortID"), - Language.GetText("Mods.MagicStorage.SortName") - }); + Language.GetText("Mods.MagicStorage.SortName"), + Language.GetText("Mods.MagicStorage.SortStack"), + + }); } } @@ -774,6 +777,9 @@ public static void RefreshItems() case 2: sortMode = SortMode.Name; break; + case 3: + sortMode = SortMode.Value; + break; default: sortMode = SortMode.Default; break; diff --git a/MagicStorage.cs b/MagicStorage.cs index 7b44469d..20e7b3b2 100644 --- a/MagicStorage.cs +++ b/MagicStorage.cs @@ -104,10 +104,7 @@ private void AddTranslations() AddTranslation(text); text = CreateTranslation("SortStack"); - text.SetDefault("Sort by Stacks"); - text.AddTranslation(GameCulture.Russian, "Сортировка по стакам"); - text.AddTranslation(GameCulture.French, "Trier par piles"); - text.AddTranslation(GameCulture.Spanish, "Ordenar por pilas"); + text.SetDefault("Sort by Value"); AddTranslation(text); text = CreateTranslation("FilterAll"); diff --git a/MagicStorage.csproj b/MagicStorage.csproj index 518109fc..324fb803 100644 --- a/MagicStorage.csproj +++ b/MagicStorage.csproj @@ -1,132 +1,131 @@ - - - - - Debug - AnyCPU - {162C8AA5-FF1C-4357-AEED-FAF522C56FEE} - Library - Properties - MagicStorage - MagicStorage - v4.7.1 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - C:\Program Files (x86)\Steam\steamapps\common\Terraria\References\ReLogic.dll - - - - - - - - - - - C:\Program Files (x86)\Steam\steamapps\common\Terraria\Terraria.exe - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "C:\Program Files (x86)\Steam\steamapps\common\Terraria\tModLoaderServer.exe" -build "$(ProjectDir.TrimEnd('\'))" - + + + + + Debug + AnyCPU + {162C8AA5-FF1C-4357-AEED-FAF522C56FEE} + Library + Properties + MagicStorage + MagicStorage + v4.7.1 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + C:\Program Files (x86)\Steam\steamapps\common\Terraria\References\ReLogic.dll + + + + + + + + + + + C:\Program Files (x86)\Steam\steamapps\common\Terraria\Terraria.exe + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + "C:\Program Files (x86)\Steam\steamapps\common\Terraria\tModLoaderServer.exe" -build "$(ProjectDir.TrimEnd('\'))" + \ No newline at end of file diff --git a/Sorting/BTree.cs b/Sorting/BTree.cs deleted file mode 100644 index b861e95b..00000000 --- a/Sorting/BTree.cs +++ /dev/null @@ -1,298 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using Terraria; - -namespace MagicStorage.Sorting -{ - public class BTree - { - private BTreeNode root; - private CompareFunction func; - - public BTree(CompareFunction func) - { - this.root = new BTreeNode(func, true); - this.func = func; - } - - public void Insert(T item) - { - T pushedItem; - BTreeNode pushedBranch; - if (root.Insert(item, out pushedItem, out pushedBranch)) - { - BTreeNode newRoot = new BTreeNode(func, root, pushedItem, pushedBranch); - root = newRoot; - } - } - - public IEnumerable GetSortedItems() - { - return root.GetSortedItems(); - } - } - - class BTreeNode - { - private const int branchFactor = 32; - private CompareFunction func; - private List elements = new List(branchFactor); - private List> branches = new List>(branchFactor + 1); - private bool isLeaf; - - internal BTreeNode(CompareFunction func, bool isLeaf) - { - this.func = func; - this.isLeaf = isLeaf; - } - - internal BTreeNode(CompareFunction func, BTreeNode branch1, T element, BTreeNode branch2) - { - this.func = func; - this.isLeaf = false; - this.branches.Add(branch1); - this.elements.Add(element); - this.branches.Add(branch2); - } - - internal bool Insert(T item, out T pushItem, out BTreeNode pushBranch) - { - if (isLeaf) - { - InsertIntoElements(item); - if (elements.Count == branchFactor) - { - Split(out pushItem, out pushBranch); - return true; - } - pushItem = default(T); - pushBranch = null; - return false; - } - else - { - T pushedItem; - BTreeNode pushedBranch; - int splitBranch = InsertIntoBranch(item, out pushedItem, out pushedBranch); - if (splitBranch >= 0) - { - branches.Insert(splitBranch + 1, pushedBranch); - elements.Insert(splitBranch, pushedItem); - if (elements.Count == branchFactor) - { - Split(out pushItem, out pushBranch); - return true; - } - } - pushItem = default(T); - pushBranch = null; - return false; - } - } - - private int InsertIntoElements(T item) - { - int min = 0; - int max = elements.Count; - while (min < max) - { - int check = (min + max) / 2; - int result = func.Compare(item, elements[check]); - if (result < 0) - { - max = check; - } - else if (result > 0) - { - min = check + 1; - } - else if (item is Item) - { - result = ItemData.Compare((Item)(object)item, (Item)(object)elements[check]); - if (result < 0) - { - max = check; - } - else if (result > 0) - { - min = check + 1; - } - else - { - ((Item)(object)elements[check]).stack += ((Item)(object)item).stack; - return -1; - } - } - else - { - min = check + 1; - } - } - elements.Insert(min, item is Item ? (T)(object)((Item)(object)item).Clone() : item); - return min; - } - - private int InsertIntoBranch(T item, out T pushItem, out BTreeNode pushNode) - { - int min = 0; - int max = elements.Count; - while (min < max) - { - int check = (min + max) / 2; - int result = func.Compare(item, elements[check]); - if (result < 0) - { - max = check; - } - else if (result > 0) - { - min = check + 1; - } - else if (item is Item) - { - result = ItemData.Compare((Item)(object)item, (Item)(object)elements[check]); - if (result < 0) - { - max = check; - } - else if (result > 0) - { - min = check + 1; - } - else - { - ((Item)(object)elements[check]).stack += ((Item)(object)item).stack; - pushItem = default(T); - pushNode = null; - return -1; - } - } - else - { - min = check + 1; - } - } - if (branches[min].Insert(item, out pushItem, out pushNode)) - { - return min; - } - return -1; - } - - private void Split(out T pushItem, out BTreeNode pushBranch) - { - BTreeNode newNeighbor = new BTreeNode(func, isLeaf); - newNeighbor.elements.AddRange(elements.GetRange(branchFactor / 2 + 1, branchFactor / 2 - 1)); - pushItem = elements[branchFactor / 2]; - elements.RemoveRange(branchFactor / 2, branchFactor / 2); - if (!isLeaf) - { - newNeighbor.branches.AddRange(branches.GetRange(branchFactor / 2 + 1, branchFactor / 2)); - branches.RemoveRange(branchFactor / 2 + 1, branchFactor / 2); - } - pushBranch = newNeighbor; - } - - internal IEnumerable GetSortedItems() - { - if (isLeaf) - { - return elements; - } - else - { - return elements.SelectMany((element, index) => new AppendEnumerable(branches[index].GetSortedItems(), element)).Concat(branches[elements.Count].GetSortedItems()); - } - } - } - - public class AppendEnumerable : IEnumerable - { - private IEnumerable enumerable; - private T element; - - public AppendEnumerable(IEnumerable enumerable, T element) - { - this.enumerable = enumerable; - this.element = element; - } - - public IEnumerator GetEnumerator() - { - return new AppendEnumerator(enumerable, element); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - } - - public class AppendEnumerator : IEnumerator - { - private IEnumerator enumerator; - private T element; - private bool enumeratorFinished; - private bool finished; - - public AppendEnumerator(IEnumerable enumerable, T element) - { - this.enumerator = enumerable.GetEnumerator(); - this.element = element; - this.finished = false; - } - - public T Current - { - get - { - if (!enumeratorFinished) - { - return enumerator.Current; - } - if (!finished) - { - return element; - } - throw new InvalidOperationException(); - } - } - - object IEnumerator.Current - { - get - { - return Current; - } - } - - public bool MoveNext() - { - if (!enumerator.MoveNext()) - { - if (enumeratorFinished) - { - finished = true; - return false; - } - enumeratorFinished = true; - return true; - } - return true; - } - - public void Reset() - { - enumerator.Reset(); - finished = false; - enumeratorFinished = false; - } - - public void Dispose() - { - enumerator.Dispose(); - } - } -} \ No newline at end of file diff --git a/Sorting/CompareFunction.cs b/Sorting/CompareFunction.cs index 478543de..f0ba2d83 100644 --- a/Sorting/CompareFunction.cs +++ b/Sorting/CompareFunction.cs @@ -4,7 +4,7 @@ namespace MagicStorage.Sorting { - public abstract class CompareFunction + public abstract class CompareFunction : IComparer { public abstract int Compare(Item item1, Item item2); @@ -45,4 +45,12 @@ public override int Compare(Item item1, Item item2) return (int)Math.Ceiling((float)item2.stack / (float)item2.maxStack) - (int)Math.Ceiling((float)item1.stack / (float)item1.maxStack); } } + + public class CompareValue : CompareFunction + { + public override int Compare(Item item1, Item item2) + { + return item2.value - item1.value; + } + } } \ No newline at end of file diff --git a/Sorting/DefaultSorting.cs b/Sorting/DefaultSorting.cs index 049a1ab2..ae8559e1 100644 --- a/Sorting/DefaultSorting.cs +++ b/Sorting/DefaultSorting.cs @@ -415,7 +415,7 @@ private static int CompareExtractible(Item item1, Item item2) return ItemID.Sets.SortingPriorityExtractibles[item2.type] - ItemID.Sets.SortingPriorityExtractibles[item1.type]; } - private static int CompareMisc(Item item1, Item item2) + public static int CompareMisc(Item item1, Item item2) { int result = CompareRarity(item1, item2); if (result == 0) diff --git a/Sorting/ItemSorter.cs b/Sorting/ItemSorter.cs index 9ce16eea..f30635d3 100644 --- a/Sorting/ItemSorter.cs +++ b/Sorting/ItemSorter.cs @@ -50,27 +50,13 @@ public static IEnumerable SortAndFilter(IEnumerable items, SortMode case SortMode.Name: func = new CompareName(); break; - case SortMode.Quantity: - func = new CompareID(); - break; + case SortMode.Value: + func = new CompareValue(); + break; default: return filteredItems; } - BTree sortedTree = new BTree(func); - foreach (Item item in filteredItems) - { - sortedTree.Insert(item); - } - if (sortMode == SortMode.Quantity) - { - BTree oldTree = sortedTree; - sortedTree = new BTree(new CompareQuantity()); - foreach (Item item in oldTree.GetSortedItems()) - { - sortedTree.Insert(item); - } - } - return sortedTree.GetSortedItems(); + return filteredItems.OrderBy(x => x, func); } public static IEnumerable GetRecipes(SortMode sortMode, FilterMode filterMode, string modFilter, string nameFilter) @@ -116,20 +102,14 @@ public static IEnumerable GetRecipes(SortMode sortMode, FilterMode filte case SortMode.Name: func = new CompareName(); break; - default: + case SortMode.Value: + func = new CompareValue(); + break; + default: return filteredRecipes; - } - BTree sortedTree = new BTree(func); - foreach (Recipe recipe in filteredRecipes) - { - sortedTree.Insert(recipe); - if (CraftingGUI.threadNeedsRestart) - { - return new List(); - } - } - return sortedTree.GetSortedItems(); - } + } + return filteredRecipes.OrderBy(x => x.createItem, func); + } private static bool FilterName(Item item, string modFilter, string filter) { diff --git a/Sorting/SortMode.cs b/Sorting/SortMode.cs index 3f222aa8..0203e935 100644 --- a/Sorting/SortMode.cs +++ b/Sorting/SortMode.cs @@ -7,6 +7,6 @@ public enum SortMode Default, Id, Name, - Quantity + Value } } \ No newline at end of file diff --git a/StorageGUI.cs b/StorageGUI.cs index 4d4d0aea..95e9f7b3 100644 --- a/StorageGUI.cs +++ b/StorageGUI.cs @@ -355,7 +355,7 @@ public static void RefreshItems() sortMode = SortMode.Name; break; case 3: - sortMode = SortMode.Quantity; + sortMode = SortMode.Value; break; default: sortMode = SortMode.Default; From 7be47a028b5a12d818172ac65b21b4434b0f7dd0 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sat, 11 Aug 2018 22:15:26 +0300 Subject: [PATCH 07/80] reversed Value sort order - from small to big now --- Sorting/CompareFunction.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sorting/CompareFunction.cs b/Sorting/CompareFunction.cs index f0ba2d83..c2cad0e9 100644 --- a/Sorting/CompareFunction.cs +++ b/Sorting/CompareFunction.cs @@ -50,7 +50,7 @@ public class CompareValue : CompareFunction { public override int Compare(Item item1, Item item2) { - return item2.value - item1.value; + return item1.value - item2.value; } } } \ No newline at end of file From 6a63358002567cadab1635e07a2a1e88c1f531db Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sat, 11 Aug 2018 22:22:27 +0300 Subject: [PATCH 08/80] 30 crafting stations instead of 10 --- Components/TECraftingAccess.cs | 313 +++++++++++++++++---------------- CraftingGUI.cs | 6 +- 2 files changed, 161 insertions(+), 158 deletions(-) diff --git a/Components/TECraftingAccess.cs b/Components/TECraftingAccess.cs index c078c68b..fc29e202 100644 --- a/Components/TECraftingAccess.cs +++ b/Components/TECraftingAccess.cs @@ -1,156 +1,159 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using Microsoft.Xna.Framework; -using Terraria; -using Terraria.DataStructures; -using Terraria.ID; -using Terraria.ModLoader; -using Terraria.ModLoader.IO; - -namespace MagicStorage.Components -{ - public class TECraftingAccess : TEStorageComponent - { - public Item[] stations = new Item[10]; - - public TECraftingAccess() - { - for (int k = 0; k < 10; k++) - { - stations[k] = new Item(); - } - } - - public override bool ValidTile(Tile tile) - { - return tile.type == mod.TileType("CraftingAccess") && tile.frameX == 0 && tile.frameY == 0; - } - - public void TryDepositStation(Item item) - { - if (Main.netMode == 1) - { - return; - } - foreach (Item station in stations) - { - if (station.type == item.type) - { - return; - } - } - for (int k = 0; k < stations.Length; k++) - { - if (stations[k].IsAir) - { - stations[k] = item.Clone(); - stations[k].stack = 1; - item.stack--; - if (item.stack <= 0) - { - item.SetDefaults(0); - } - NetHelper.SendTEUpdate(ID, Position); - return; - } - } - } - - public Item TryWithdrawStation(int slot) - { - if (Main.netMode == 1) - { - return new Item(); - } - if (!stations[slot].IsAir) - { - Item item = stations[slot]; - stations[slot] = new Item(); - NetHelper.SendTEUpdate(ID, Position); - return item; - } - return new Item(); - } - - public Item DoStationSwap(Item item, int slot) - { - if (Main.netMode == 1) - { - return new Item(); - } - if (!item.IsAir) - { - for (int k = 0; k < stations.Length; k++) - { - if (k != slot && stations[k].type == item.type) - { - return item; - } - } - } - if ((item.IsAir || item.stack == 1) && !stations[slot].IsAir) - { - Item temp = item; - item = stations[slot]; - stations[slot] = temp; - NetHelper.SendTEUpdate(ID, Position); - return item; - } - else if (!item.IsAir && stations[slot].IsAir) - { - stations[slot] = item.Clone(); - stations[slot].stack = 1; - item.stack--; - if (item.stack <= 0) - { - item.SetDefaults(0); - } - NetHelper.SendTEUpdate(ID, Position); - return item; - } - return item; - } - - public override TagCompound Save() - { - TagCompound tag = new TagCompound(); - IList listStations = new List(); - foreach (Item item in stations) - { - listStations.Add(ItemIO.Save(item)); - } - tag["Stations"] = listStations; - return tag; - } - - public override void Load(TagCompound tag) - { - IList listStations = tag.GetList("Stations"); - if (listStations != null && listStations.Count > 0) - { - for (int k = 0; k < stations.Length; k++) - { - stations[k] = ItemIO.Load(listStations[k]); - } - } - } - - public override void NetSend(BinaryWriter writer, bool lightSend) - { - foreach (Item item in stations) - { - ItemIO.Send(item, writer, true, false); - } - } - - public override void NetReceive(BinaryReader reader, bool lightReceive) - { - for (int k = 0; k < stations.Length; k++) - { - stations[k] = ItemIO.Receive(reader, true, false); - } - } - } +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using Microsoft.Xna.Framework; +using Terraria; +using Terraria.DataStructures; +using Terraria.ID; +using Terraria.ModLoader; +using Terraria.ModLoader.IO; + +namespace MagicStorage.Components +{ + public class TECraftingAccess : TEStorageComponent + { + public Item[] stations = new Item[30]; + + public TECraftingAccess() + { + for (int k = 0; k < 30; k++) + { + stations[k] = new Item(); + } + } + + public override bool ValidTile(Tile tile) + { + return tile.type == mod.TileType("CraftingAccess") && tile.frameX == 0 && tile.frameY == 0; + } + + public void TryDepositStation(Item item) + { + if (Main.netMode == 1) + { + return; + } + foreach (Item station in stations) + { + if (station.type == item.type) + { + return; + } + } + for (int k = 0; k < stations.Length; k++) + { + if (stations[k].IsAir) + { + stations[k] = item.Clone(); + stations[k].stack = 1; + item.stack--; + if (item.stack <= 0) + { + item.SetDefaults(0); + } + NetHelper.SendTEUpdate(ID, Position); + return; + } + } + } + + public Item TryWithdrawStation(int slot) + { + if (Main.netMode == 1) + { + return new Item(); + } + if (!stations[slot].IsAir) + { + Item item = stations[slot]; + stations[slot] = new Item(); + NetHelper.SendTEUpdate(ID, Position); + return item; + } + return new Item(); + } + + public Item DoStationSwap(Item item, int slot) + { + if (Main.netMode == 1) + { + return new Item(); + } + if (!item.IsAir) + { + for (int k = 0; k < stations.Length; k++) + { + if (k != slot && stations[k].type == item.type) + { + return item; + } + } + } + if ((item.IsAir || item.stack == 1) && !stations[slot].IsAir) + { + Item temp = item; + item = stations[slot]; + stations[slot] = temp; + NetHelper.SendTEUpdate(ID, Position); + return item; + } + else if (!item.IsAir && stations[slot].IsAir) + { + stations[slot] = item.Clone(); + stations[slot].stack = 1; + item.stack--; + if (item.stack <= 0) + { + item.SetDefaults(0); + } + NetHelper.SendTEUpdate(ID, Position); + return item; + } + return item; + } + + public override TagCompound Save() + { + TagCompound tag = new TagCompound(); + IList listStations = new List(); + foreach (Item item in stations) + { + listStations.Add(ItemIO.Save(item)); + } + tag["Stations"] = listStations; + return tag; + } + + public override void Load(TagCompound tag) + { + IList listStations = tag.GetList("Stations"); + if (listStations != null && listStations.Count > 0) + { + for (int k = 0; k < stations.Length; k++) + { + if (k < listStations.Count) + stations[k] = ItemIO.Load(listStations[k]); + else + stations[k] = new Item(); + } + } + } + + public override void NetSend(BinaryWriter writer, bool lightSend) + { + foreach (Item item in stations) + { + ItemIO.Send(item, writer, true, false); + } + } + + public override void NetReceive(BinaryReader reader, bool lightReceive) + { + for (int k = 0; k < stations.Length; k++) + { + stations[k] = ItemIO.Receive(reader, true, false); + } + } + } } \ No newline at end of file diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 5abf0025..39b9b847 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -64,7 +64,7 @@ public static bool RightMouseClicked internal static UISearchBar searchBar2; private static UIText stationText; - private static UISlotZone stationZone = new UISlotZone(HoverStation, GetStation, inventoryScale); + private static UISlotZone stationZone = new UISlotZone(HoverStation, GetStation, inventoryScale / 1.55f); private static UIText recipeText; private static UISlotZone recipeZone = new UISlotZone(HoverRecipe, GetRecipe, inventoryScale); @@ -212,8 +212,8 @@ public static void Initialize() stationZone.Width.Set(0f, 1f); stationZone.Top.Set(100f, 0f); - stationZone.Height.Set(70f, 0f); - stationZone.SetDimensions(numColumns, 1); + stationZone.Height.Set(90f, 0f); + stationZone.SetDimensions(15, 2); basePanel.Append(stationZone); recipeText.Top.Set(152f, 0f); From e80d3233a1869b47be891a771cfa5a07d6387530 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sat, 11 Aug 2018 22:41:56 +0300 Subject: [PATCH 09/80] hidden items are considered known --- CraftingGUI.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 39b9b847..d8934412 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -860,7 +860,7 @@ private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craf .Where(x => (recipeButtons.Choice != RecipeButtonsNewChoice) || !craftedRecipes.Contains(x.createItem.type)) // show only blacklisted recipes only if choice = 2, otherwise show all other .Where(x => (recipeButtons.Choice == RecipeButtonsBlacklistChoice) == hiddenRecipes.Contains(x.createItem.type)) - .Where(x => FilterKnownRecipesMethod(x, craftedRecipes)); + .Where(x => FilterKnownRecipesMethod(x, hiddenRecipes, craftedRecipes)); threadRecipes.Clear(); threadRecipeAvailable.Clear(); @@ -899,7 +899,7 @@ private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craf } - static bool FilterKnownRecipesMethod(Recipe recipe, HashSet craftedSet) + static bool FilterKnownRecipesMethod(Recipe recipe, HashSet hiddenSet, HashSet craftedSet) { if (threadCheckListFoundItems == null) return true; if (recipeButtons.Choice == RecipeButtonsNewChoice) @@ -919,7 +919,7 @@ static bool FilterKnownRecipesMethod(Recipe recipe, HashSet craftedSet) for (int i = 0; i < Recipe.maxRequirements; i++) { var t = recipe.requiredItem[i].type; - if (t > 0 && !threadCheckListFoundItems[t] && !craftedSet.Contains(t)) + if (t > 0 && !threadCheckListFoundItems[t] && !craftedSet.Contains(t) && !hiddenSet.Contains(t)) return false; } return true; From 51123e45e0823b61bf74bda558ceb3786e44d3cb Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sat, 11 Aug 2018 23:31:49 +0300 Subject: [PATCH 10/80] added recursive search for items that can be non-directly crafted from known items --- CraftingGUI.cs | 90 +++++++++++++++++++++++++++++++------------------- 1 file changed, 56 insertions(+), 34 deletions(-) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index d8934412..f07f3ccf 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -823,6 +823,12 @@ public static void RefreshItems() var hiddenRecipes = new HashSet(modPlayer.HiddenRecipes.Select(x => x.type)); var craftedRecipes = new HashSet(modPlayer.CraftedRecipes.Select(x => x.type)); + if (_productToRecipes == null) + { + var allRecipes = ItemSorter.GetRecipes(SortMode.Id, FilterMode.All, "", "").Where(x => x != null && x.createItem != null && x.createItem.type > 0).ToArray(); + _productToRecipes = allRecipes.GroupBy(x => x.createItem.type).ToDictionary(x => x.Key, x => x.ToList()); + } + lock (threadLock) { threadNeedsRestart = true; @@ -838,6 +844,38 @@ public static void RefreshItems() } } + static Dictionary> _productToRecipes; + + /// + /// Checks all crafting tree until it finds already available ingredients + /// + static bool IsAvailableRecursively(Recipe recipe, HashSet availableSet, HashSet recursionTree) + { + if (availableSet.Contains(recipe.createItem.type)) return true; + for (int i = 0; i < Recipe.maxRequirements; i++) + { + var t = recipe.requiredItem[i].type; + if (t <= 0) continue; + if (!availableSet.Contains(t)) + { + if (recursionTree.Contains(t)) return false; + recursionTree.Add(t); + try + { + List ingredientRecipes; + if (!_productToRecipes.TryGetValue(t, out ingredientRecipes)) return false; + if (ingredientRecipes.Count == 0 || ingredientRecipes.All(x => !IsAvailableRecursively(x, availableSet, recursionTree))) return false; + } + finally + { + recursionTree.Remove(t); + } + } + } + availableSet.Add(recipe.createItem.type); + return true; + } + private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craftedRecipes) { while (true) @@ -846,27 +884,40 @@ private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craf { SortMode sortMode; FilterMode filterMode; + bool[] foundItems; lock (threadLock) { threadNeedsRestart = false; sortMode = threadSortMode; filterMode = threadFilterMode; + foundItems = threadCheckListFoundItems; } - - var temp = ItemSorter.GetRecipes(sortMode, filterMode, searchBar2.Text, searchBar.Text) - .Where(x => x != null) + if (foundItems == null) foundItems = new bool[0]; + + var availableItemsMutable = new HashSet(hiddenRecipes + .Concat(craftedRecipes) + .Concat(foundItems.Select((v, type) => new {WasFound = v, type}).Where(x => x.WasFound).Select(x => x.type))); + + var availableItemsOriginal = new HashSet(availableItemsMutable); + + var temp = new HashSet(); + + var recipes = ItemSorter.GetRecipes(sortMode, filterMode, searchBar2.Text, searchBar.Text).Where(x => x != null) // only new recipes (not crafted previously) filter (new - button choice = 0) .Where(x => (recipeButtons.Choice != RecipeButtonsNewChoice) || !craftedRecipes.Contains(x.createItem.type)) // show only blacklisted recipes only if choice = 2, otherwise show all other .Where(x => (recipeButtons.Choice == RecipeButtonsBlacklistChoice) == hiddenRecipes.Contains(x.createItem.type)) - .Where(x => FilterKnownRecipesMethod(x, hiddenRecipes, craftedRecipes)); + // show only new items if selected + .Where(x => (recipeButtons.Choice != RecipeButtonsNewChoice) || !availableItemsOriginal.Contains(x.createItem.type)) + // hard check if this item can be crafted from available items and their recursive products + .Where(x => IsAvailableRecursively(x, availableItemsMutable, temp)); threadRecipes.Clear(); threadRecipeAvailable.Clear(); try { - threadRecipes.AddRange(temp); + threadRecipes.AddRange(recipes); threadRecipeAvailable.AddRange(threadRecipes.Select(recipe => IsAvailable(recipe))); } catch (InvalidOperationException) @@ -894,36 +945,7 @@ private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craf } catch (Exception e) { Main.NewTextMultiline(e.ToString()); } } - - - } - - static bool FilterKnownRecipesMethod(Recipe recipe, HashSet hiddenSet, HashSet craftedSet) - { - if (threadCheckListFoundItems == null) return true; - if (recipeButtons.Choice == RecipeButtonsNewChoice) - { - // first - only new - var t = recipe.createItem.type; - if (threadCheckListFoundItems[t] || craftedSet.Contains(t)) - { - // already encountered - return false; - } - } - else - { - // second button - } - for (int i = 0; i < Recipe.maxRequirements; i++) - { - var t = recipe.requiredItem[i].type; - if (t > 0 && !threadCheckListFoundItems[t] && !craftedSet.Contains(t) && !hiddenSet.Contains(t)) - return false; - } - return true; - } private static void AnalyzeIngredients() { From a04800be214f041d9d708cb20d5464efba2a29c6 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sat, 11 Aug 2018 23:35:15 +0300 Subject: [PATCH 11/80] potion filter fix --- Sorting/ItemFilter.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sorting/ItemFilter.cs b/Sorting/ItemFilter.cs index 000237f2..6df3aa39 100644 --- a/Sorting/ItemFilter.cs +++ b/Sorting/ItemFilter.cs @@ -130,7 +130,7 @@ public class FilterPotion : ItemFilter { public override bool Passes(Item item) { - return item.consumable && (item.healLife > 0 || item.healMana > 0 || item.buffType > 0); + return item.consumable && (item.healLife > 0 || item.healMana > 0 || item.buffType > 0 || item.potion); } } From 86c421cf919d513b26cb605cd70d54266ca6be9d Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 12 Aug 2018 00:33:06 +0300 Subject: [PATCH 12/80] more filters --- CraftingGUI.cs | 53 ++---------------- MagicStorage.cs | 35 +++++++++++- Sorting/FilterMode.cs | 15 ++++-- Sorting/ItemFilter.cs | 58 +++++++++++++++----- Sorting/ItemSorter.cs | 121 +++++++++++++++++++++--------------------- StorageGUI.cs | 95 +++++++++++++++------------------ UIButtonChoice.cs | 2 +- 7 files changed, 201 insertions(+), 178 deletions(-) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index f07f3ccf..331821b7 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -201,7 +201,7 @@ public static void Initialize() InitFilterButtons(); float filterButtonsRight = filterButtons.GetDimensions().Width + padding; - topBar2.Append(filterButtons); + topBar2.Append(filterButtons); searchBar2.Left.Set(filterButtonsRight + padding, 0f); searchBar2.Width.Set(-filterButtonsRight - 2 * padding, 1f); searchBar2.Height.Set(0f, 1f); @@ -406,26 +406,7 @@ private static void InitFilterButtons() { if (filterButtons == null) { - filterButtons = new UIButtonChoice(new Texture2D[] - { - MagicStorage.Instance.GetTexture("FilterAll"), - MagicStorage.Instance.GetTexture("FilterMelee"), - MagicStorage.Instance.GetTexture("FilterPickaxe"), - MagicStorage.Instance.GetTexture("FilterArmor"), - MagicStorage.Instance.GetTexture("FilterPotion"), - MagicStorage.Instance.GetTexture("FilterTile"), - MagicStorage.Instance.GetTexture("FilterMisc"), - }, - new LocalizedText[] - { - Language.GetText("Mods.MagicStorage.FilterAll"), - Language.GetText("Mods.MagicStorage.FilterWeapons"), - Language.GetText("Mods.MagicStorage.FilterTools"), - Language.GetText("Mods.MagicStorage.FilterEquips"), - Language.GetText("Mods.MagicStorage.FilterPotions"), - Language.GetText("Mods.MagicStorage.FilterTiles"), - Language.GetText("Mods.MagicStorage.FilterMisc") - }); + filterButtons = StorageGUI.MakeFilterButtons(); } } @@ -784,34 +765,8 @@ public static void RefreshItems() sortMode = SortMode.Default; break; } - FilterMode filterMode; - switch (filterButtons.Choice) - { - case 0: - filterMode = FilterMode.All; - break; - case 1: - filterMode = FilterMode.Weapons; - break; - case 2: - filterMode = FilterMode.Tools; - break; - case 3: - filterMode = FilterMode.Equipment; - break; - case 4: - filterMode = FilterMode.Potions; - break; - case 5: - filterMode = FilterMode.Placeables; - break; - case 6: - filterMode = FilterMode.Misc; - break; - default: - filterMode = FilterMode.All; - break; - } + FilterMode filterMode = (FilterMode)filterButtons.Choice; + RefreshStorageItems(); if (_checkListMod == null) diff --git a/MagicStorage.cs b/MagicStorage.cs index 20e7b3b2..76cf7b0a 100644 --- a/MagicStorage.cs +++ b/MagicStorage.cs @@ -135,7 +135,40 @@ private void AddTranslations() text.AddTranslation(GameCulture.Spanish, "Filtrar por equipamiento"); AddTranslation(text); - text = CreateTranslation("FilterPotions"); + text = CreateTranslation("FilterWeaponsMelee"); + text.SetDefault("Filter Melee Weapons"); + AddTranslation(text); + + text = CreateTranslation("FilterWeaponsRanged"); + text.SetDefault("Filter Ranged Weapons"); + AddTranslation(text); + + text = CreateTranslation("FilterWeaponsMagic"); + text.SetDefault("Filter Magic Weapons"); + AddTranslation(text); + + text = CreateTranslation("FilterWeaponsSummon"); + text.SetDefault("Filter Summons"); + AddTranslation(text); + + text = CreateTranslation("FilterWeaponsThrown"); + text.SetDefault("Filter Throwing Weapons"); + AddTranslation(text); + + text = CreateTranslation("FilterAmmo"); + text.SetDefault("Filter Ammo"); + AddTranslation(text); + + text = CreateTranslation("FilterArmor"); + text.SetDefault("Filter Armor"); + AddTranslation(text); + + text = CreateTranslation("FilterVanity"); + text.SetDefault("Filter Vanity Items"); + AddTranslation(text); + + + text = CreateTranslation("FilterPotions"); text.SetDefault("Filter Potions"); text.AddTranslation(GameCulture.Russian, "Фильтр (Зелья)"); text.AddTranslation(GameCulture.French, "Filtrer par potions"); diff --git a/Sorting/FilterMode.cs b/Sorting/FilterMode.cs index 93cb978e..61609b84 100644 --- a/Sorting/FilterMode.cs +++ b/Sorting/FilterMode.cs @@ -4,11 +4,18 @@ namespace MagicStorage.Sorting { public enum FilterMode { - All, - Weapons, - Tools, + All = 0, + WeaponsMelee, + WeaponsRanged, + WeaponsMagic, + WeaponsSummon, + WeaponsThrown, + Ammo, + Tools, + Armor, Equipment, - Potions, + Vanity, + Potions, Placeables, Misc } diff --git a/Sorting/ItemFilter.cs b/Sorting/ItemFilter.cs index 6df3aa39..de6b12e8 100644 --- a/Sorting/ItemFilter.cs +++ b/Sorting/ItemFilter.cs @@ -30,31 +30,33 @@ public override bool Passes(Item item) } } - public class FilterMelee : ItemFilter + public class FilterWeaponMelee : ItemFilter { public override bool Passes(Item item) { - return item.melee && item.pick == 0 && item.axe == 0 && item.hammer == 0; + return item.melee && item.pick == 0 && item.axe == 0 && item.hammer == 0 && item.damage > 0; } } - public class FilterRanged : ItemFilter + public class FilterWeaponRanged : ItemFilter { + readonly FilterWeaponThrown _thrown = new FilterWeaponThrown(); + public override bool Passes(Item item) { - return item.ranged; + return item.ranged && item.damage > 0 && !_thrown.Passes(item); } } - public class FilterMagic : ItemFilter + public class FilterWeaponMagic : ItemFilter { public override bool Passes(Item item) { - return item.magic; + return item.magic && item.damage > 0; } } - public class FilterSummon : ItemFilter + public class FilterWeaponSummon : ItemFilter { public override bool Passes(Item item) { @@ -62,11 +64,27 @@ public override bool Passes(Item item) } } - public class FilterThrown : ItemFilter + public class FilterWeaponThrown : ItemFilter + { + public override bool Passes(Item item) + { + return item.thrown && item.consumable && item.damage > 0; + } + } + + public class FilterAmmo : ItemFilter { public override bool Passes(Item item) { - return item.thrown; + return item.ammo > 0; + } + } + + public class FilterVanity : ItemFilter + { + public override bool Passes(Item item) + { + return item.vanity; } } @@ -82,7 +100,7 @@ public class FilterWeapon : ItemFilter { public override bool Passes(Item item) { - return item.damage > 0 && item.pick == 0 && item.axe == 0 && item.hammer == 0; + return !(item.consumable && item.thrown) && item.damage > 0 && item.pick == 0 && item.axe == 0 && item.hammer == 0; } } @@ -118,11 +136,19 @@ public override bool Passes(Item item) } } + public class FilterArmor : ItemFilter + { + public override bool Passes(Item item) + { + return !item.vanity && (item.headSlot >= 0 || item.bodySlot >= 0 || item.legSlot >= 0); + } + } + public class FilterEquipment : ItemFilter { public override bool Passes(Item item) { - return item.headSlot >= 0 || item.bodySlot >= 0 || item.legSlot >= 0 || item.accessory || Main.projHook[item.shoot] || item.mountType >= 0 || (item.buffType > 0 && (Main.lightPet[item.buffType] || Main.vanityPet[item.buffType])); + return !item.vanity && (item.accessory || Main.projHook[item.shoot] || item.mountType >= 0 || (item.buffType > 0 && (Main.lightPet[item.buffType] || Main.vanityPet[item.buffType]))); } } @@ -145,8 +171,16 @@ public override bool Passes(Item item) public class FilterMisc : ItemFilter { private static List blacklist = new List { - new FilterWeapon(), + new FilterWeaponMelee(), + new FilterWeaponRanged(), + new FilterWeaponMagic(), + new FilterWeaponSummon(), + new FilterWeaponThrown(), + new FilterAmmo(), + new FilterWeaponThrown(), + new FilterVanity(), new FilterTool(), + new FilterArmor(), new FilterEquipment(), new FilterPotion(), new FilterPlaceable() diff --git a/Sorting/ItemSorter.cs b/Sorting/ItemSorter.cs index f30635d3..83d5d7a3 100644 --- a/Sorting/ItemSorter.cs +++ b/Sorting/ItemSorter.cs @@ -8,35 +8,8 @@ namespace MagicStorage.Sorting public static class ItemSorter { public static IEnumerable SortAndFilter(IEnumerable items, SortMode sortMode, FilterMode filterMode, string modFilter, string nameFilter) - { - ItemFilter filter; - switch (filterMode) - { - case FilterMode.All: - filter = new FilterAll(); - break; - case FilterMode.Weapons: - filter = new FilterWeapon(); - break; - case FilterMode.Tools: - filter = new FilterTool(); - break; - case FilterMode.Equipment: - filter = new FilterEquipment(); - break; - case FilterMode.Potions: - filter = new FilterPotion(); - break; - case FilterMode.Placeables: - filter = new FilterPlaceable(); - break; - case FilterMode.Misc: - filter = new FilterMisc(); - break; - default: - filter = new FilterAll(); - break; - } + { + ItemFilter filter = MakeFilter(filterMode); IEnumerable filteredItems = items.Where((item) => filter.Passes(item) && FilterName(item, modFilter, nameFilter)); CompareFunction func; switch (sortMode) @@ -61,35 +34,8 @@ public static IEnumerable SortAndFilter(IEnumerable items, SortMode public static IEnumerable GetRecipes(SortMode sortMode, FilterMode filterMode, string modFilter, string nameFilter) { - ItemFilter filter; - switch (filterMode) - { - case FilterMode.All: - filter = new FilterAll(); - break; - case FilterMode.Weapons: - filter = new FilterWeapon(); - break; - case FilterMode.Tools: - filter = new FilterTool(); - break; - case FilterMode.Equipment: - filter = new FilterEquipment(); - break; - case FilterMode.Potions: - filter = new FilterPotion(); - break; - case FilterMode.Placeables: - filter = new FilterPlaceable(); - break; - case FilterMode.Misc: - filter = new FilterMisc(); - break; - default: - filter = new FilterAll(); - break; - } - IEnumerable filteredRecipes = Main.recipe.Where((recipe, index) => index < Recipe.numRecipes && filter.Passes(recipe) && FilterName(recipe.createItem, modFilter, nameFilter)); + var filter = MakeFilter(filterMode); + IEnumerable filteredRecipes = Main.recipe.Where((recipe, index) => index < Recipe.numRecipes && filter.Passes(recipe) && FilterName(recipe.createItem, modFilter, nameFilter)); CompareFunction func; switch (sortMode) { @@ -108,10 +54,65 @@ public static IEnumerable GetRecipes(SortMode sortMode, FilterMode filte default: return filteredRecipes; } - return filteredRecipes.OrderBy(x => x.createItem, func); + return filteredRecipes.OrderBy(x => x.createItem, func); } - private static bool FilterName(Item item, string modFilter, string filter) + static ItemFilter MakeFilter(FilterMode filterMode) + { + ItemFilter filter; + switch (filterMode) + { + case FilterMode.All: + filter = new FilterAll(); + break; + case FilterMode.WeaponsMelee: + filter = new FilterWeaponMelee(); + break; + case FilterMode.WeaponsRanged: + filter = new FilterWeaponRanged(); + break; + case FilterMode.WeaponsMagic: + filter = new FilterWeaponMagic(); + break; + case FilterMode.WeaponsSummon: + filter = new FilterWeaponSummon(); + break; + case FilterMode.Ammo: + filter = new FilterAmmo(); + break; + case FilterMode.WeaponsThrown: + filter = new FilterWeaponThrown(); + break; + case FilterMode.Tools: + filter = new FilterTool(); + break; + case FilterMode.Armor: + filter = new FilterArmor(); + break; + case FilterMode.Vanity: + filter = new FilterVanity(); + break; + case FilterMode.Equipment: + filter = new FilterEquipment(); + break; + case FilterMode.Potions: + filter = new FilterPotion(); + break; + case FilterMode.Placeables: + filter = new FilterPlaceable(); + break; + case FilterMode.Misc: + filter = new FilterMisc(); + break; + default: + filter = new FilterAll(); + break; + } + + return filter; + } + + private static bool FilterName(Item item, string modFilter, string filter) { string modName = "Terraria"; if (item.modItem != null) diff --git a/StorageGUI.cs b/StorageGUI.cs index 95e9f7b3..39566191 100644 --- a/StorageGUI.cs +++ b/StorageGUI.cs @@ -205,30 +205,49 @@ private static void InitFilterButtons() { if (filterButtons == null) { - filterButtons = new UIButtonChoice(new Texture2D[] - { - MagicStorage.Instance.GetTexture("FilterAll"), - MagicStorage.Instance.GetTexture("FilterMelee"), - MagicStorage.Instance.GetTexture("FilterPickaxe"), - MagicStorage.Instance.GetTexture("FilterArmor"), - MagicStorage.Instance.GetTexture("FilterPotion"), - MagicStorage.Instance.GetTexture("FilterTile"), - MagicStorage.Instance.GetTexture("FilterMisc"), - }, - new LocalizedText[] - { - Language.GetText("Mods.MagicStorage.FilterAll"), - Language.GetText("Mods.MagicStorage.FilterWeapons"), - Language.GetText("Mods.MagicStorage.FilterTools"), - Language.GetText("Mods.MagicStorage.FilterEquips"), - Language.GetText("Mods.MagicStorage.FilterPotions"), - Language.GetText("Mods.MagicStorage.FilterTiles"), - Language.GetText("Mods.MagicStorage.FilterMisc") - }); + filterButtons = MakeFilterButtons(); } } - public static void Update(GameTime gameTime) + public static UIButtonChoice MakeFilterButtons() + { + return new UIButtonChoice(new Texture2D[] + { + MagicStorage.Instance.GetTexture("FilterAll"), + MagicStorage.Instance.GetTexture("FilterMelee"), + MagicStorage.Instance.GetTexture("FilterRanged"), + MagicStorage.Instance.GetTexture("FilterMagic"), + MagicStorage.Instance.GetTexture("FilterSummon"), + MagicStorage.Instance.GetTexture("FilterThrowing"), + MagicStorage.Instance.GetTexture("FilterThrowing"), + MagicStorage.Instance.GetTexture("FilterPickaxe"), + MagicStorage.Instance.GetTexture("FilterArmor"), + MagicStorage.Instance.GetTexture("FilterArmor"), + MagicStorage.Instance.GetTexture("FilterArmor"), + MagicStorage.Instance.GetTexture("FilterPotion"), + MagicStorage.Instance.GetTexture("FilterTile"), + MagicStorage.Instance.GetTexture("FilterMisc"), + }, + new LocalizedText[] + { + Language.GetText("Mods.MagicStorage.FilterAll"), + Language.GetText("Mods.MagicStorage.FilterWeaponsMelee"), + Language.GetText("Mods.MagicStorage.FilterWeaponsRanged"), + Language.GetText("Mods.MagicStorage.FilterWeaponsMagic"), + Language.GetText("Mods.MagicStorage.FilterWeaponsSummon"), + Language.GetText("Mods.MagicStorage.FilterWeaponsThrown"), + Language.GetText("Mods.MagicStorage.FilterAmmo"), + Language.GetText("Mods.MagicStorage.FilterTools"), + Language.GetText("Mods.MagicStorage.FilterArmor"), + Language.GetText("Mods.MagicStorage.FilterEquips"), + Language.GetText("Mods.MagicStorage.FilterVanity"), + Language.GetText("Mods.MagicStorage.FilterPotions"), + Language.GetText("Mods.MagicStorage.FilterTiles"), + Language.GetText("Mods.MagicStorage.FilterMisc") + }, 15); + } + + public static void Update(GameTime gameTime) { oldMouse = curMouse; curMouse = Mouse.GetState(); @@ -360,36 +379,10 @@ public static void RefreshItems() default: sortMode = SortMode.Default; break; - } - FilterMode filterMode; - switch (filterButtons.Choice) - { - case 0: - filterMode = FilterMode.All; - break; - case 1: - filterMode = FilterMode.Weapons; - break; - case 2: - filterMode = FilterMode.Tools; - break; - case 3: - filterMode = FilterMode.Equipment; - break; - case 4: - filterMode = FilterMode.Potions; - break; - case 5: - filterMode = FilterMode.Placeables; - break; - case 6: - filterMode = FilterMode.Misc; - break; - default: - filterMode = FilterMode.All; - break; - } - items.AddRange(ItemSorter.SortAndFilter(heart.GetStoredItems(), sortMode, filterMode, searchBar2.Text, searchBar.Text)); + } + + FilterMode filterMode = (FilterMode)filterButtons.Choice; + items.AddRange(ItemSorter.SortAndFilter(heart.GetStoredItems(), sortMode, filterMode, searchBar2.Text, searchBar.Text)); for (int k = 0; k < items.Count; k++) { didMatCheck.Add(false); diff --git a/UIButtonChoice.cs b/UIButtonChoice.cs index aa923105..e0f6d0c1 100644 --- a/UIButtonChoice.cs +++ b/UIButtonChoice.cs @@ -27,7 +27,7 @@ public int Choice } } - public UIButtonChoice(Texture2D[] buttons, LocalizedText[] names) + public UIButtonChoice(Texture2D[] buttons, LocalizedText[] names, int buttonSize = buttonSize) { if (buttons.Length != names.Length || buttons.Length == 0) { From 185160c3350e1a8f602193445c4461b8a7473403 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 12 Aug 2018 00:43:41 +0300 Subject: [PATCH 13/80] sorting by dps --- CraftingGUI.cs | 38 ++------------------- MagicStorage.cs | 4 +++ Sorting/CompareFunction.cs | 13 ++++++++ Sorting/ItemSorter.cs | 68 ++++++++++++++++++-------------------- Sorting/SortMode.cs | 3 +- StorageGUI.cs | 59 ++++++++++++++------------------- 6 files changed, 78 insertions(+), 107 deletions(-) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 331821b7..c5acd944 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -365,21 +365,7 @@ private static void InitSortButtons() { if (sortButtons == null) { - sortButtons = new UIButtonChoice(new Texture2D[] - { - Main.inventorySortTexture[0], - MagicStorage.Instance.GetTexture("SortID"), - MagicStorage.Instance.GetTexture("SortName"), - MagicStorage.Instance.GetTexture("SortNumber") - }, - new LocalizedText[] - { - Language.GetText("Mods.MagicStorage.SortDefault"), - Language.GetText("Mods.MagicStorage.SortID"), - Language.GetText("Mods.MagicStorage.SortName"), - Language.GetText("Mods.MagicStorage.SortStack"), - - }); + sortButtons = StorageGUI.MakeSortButtons(); } } @@ -746,26 +732,8 @@ public static void RefreshItems() InitSortButtons(); InitRecipeButtons(); InitFilterButtons(); - SortMode sortMode; - switch (sortButtons.Choice) - { - case 0: - sortMode = SortMode.Default; - break; - case 1: - sortMode = SortMode.Id; - break; - case 2: - sortMode = SortMode.Name; - break; - case 3: - sortMode = SortMode.Value; - break; - default: - sortMode = SortMode.Default; - break; - } - FilterMode filterMode = (FilterMode)filterButtons.Choice; + SortMode sortMode = (SortMode)sortButtons.Choice; + FilterMode filterMode = (FilterMode)filterButtons.Choice; RefreshStorageItems(); diff --git a/MagicStorage.cs b/MagicStorage.cs index 76cf7b0a..1bdb9f10 100644 --- a/MagicStorage.cs +++ b/MagicStorage.cs @@ -232,6 +232,10 @@ private void AddTranslations() text = CreateTranslation("RecipeBlacklist"); text.SetDefault("Show hidden recipes"); AddTranslation(text); + + text = CreateTranslation("SortDps"); + text.SetDefault("Sort by DPS"); + AddTranslation(text); } public override void PostSetupContent() diff --git a/Sorting/CompareFunction.cs b/Sorting/CompareFunction.cs index c2cad0e9..a3851852 100644 --- a/Sorting/CompareFunction.cs +++ b/Sorting/CompareFunction.cs @@ -53,4 +53,17 @@ public override int Compare(Item item1, Item item2) return item1.value - item2.value; } } + + public class CompareDps : CompareFunction + { + public override int Compare(Item item1, Item item2) + { + return (int)((GetDps(item1) - GetDps(item2)) * 100); + } + + static float GetDps(Item item1) + { + return item1.damage / (float)Math.Max(item1.useTime, 1); + } + } } \ No newline at end of file diff --git a/Sorting/ItemSorter.cs b/Sorting/ItemSorter.cs index 83d5d7a3..7998c569 100644 --- a/Sorting/ItemSorter.cs +++ b/Sorting/ItemSorter.cs @@ -11,24 +11,8 @@ public static IEnumerable SortAndFilter(IEnumerable items, SortMode { ItemFilter filter = MakeFilter(filterMode); IEnumerable filteredItems = items.Where((item) => filter.Passes(item) && FilterName(item, modFilter, nameFilter)); - CompareFunction func; - switch (sortMode) - { - case SortMode.Default: - func = new CompareDefault(); - break; - case SortMode.Id: - func = new CompareID(); - break; - case SortMode.Name: - func = new CompareName(); - break; - case SortMode.Value: - func = new CompareValue(); - break; - default: - return filteredItems; - } + var func = MakeSortFunction(sortMode); + if (func == null) return filteredItems; return filteredItems.OrderBy(x => x, func); } @@ -36,27 +20,39 @@ public static IEnumerable GetRecipes(SortMode sortMode, FilterMode filte { var filter = MakeFilter(filterMode); IEnumerable filteredRecipes = Main.recipe.Where((recipe, index) => index < Recipe.numRecipes && filter.Passes(recipe) && FilterName(recipe.createItem, modFilter, nameFilter)); - CompareFunction func; - switch (sortMode) - { - case SortMode.Default: - func = new CompareDefault(); - break; - case SortMode.Id: - func = new CompareID(); - break; - case SortMode.Name: - func = new CompareName(); - break; - case SortMode.Value: - func = new CompareValue(); - break; - default: - return filteredRecipes; - } + var func = MakeSortFunction(sortMode); + if (func == null) return filteredRecipes; return filteredRecipes.OrderBy(x => x.createItem, func); } + static CompareFunction MakeSortFunction(SortMode sortMode) + { + CompareFunction func; + switch (sortMode) + { + case SortMode.Default: + func = new CompareDefault(); + break; + case SortMode.Id: + func = new CompareID(); + break; + case SortMode.Name: + func = new CompareName(); + break; + case SortMode.Value: + func = new CompareValue(); + break; + case SortMode.Dps: + func = new CompareDps(); + break; + default: + func = null; + break; + } + + return func; + } + static ItemFilter MakeFilter(FilterMode filterMode) { ItemFilter filter; diff --git a/Sorting/SortMode.cs b/Sorting/SortMode.cs index 0203e935..2b46019a 100644 --- a/Sorting/SortMode.cs +++ b/Sorting/SortMode.cs @@ -7,6 +7,7 @@ public enum SortMode Default, Id, Name, - Value + Value, + Dps } } \ No newline at end of file diff --git a/StorageGUI.cs b/StorageGUI.cs index 39566191..4c0615ce 100644 --- a/StorageGUI.cs +++ b/StorageGUI.cs @@ -184,24 +184,31 @@ private static void InitSortButtons() { if (sortButtons == null) { - sortButtons = new UIButtonChoice(new Texture2D[] - { - Main.inventorySortTexture[0], - MagicStorage.Instance.GetTexture("SortID"), - MagicStorage.Instance.GetTexture("SortName"), - MagicStorage.Instance.GetTexture("SortNumber") - }, - new LocalizedText[] - { - Language.GetText("Mods.MagicStorage.SortDefault"), - Language.GetText("Mods.MagicStorage.SortID"), - Language.GetText("Mods.MagicStorage.SortName"), - Language.GetText("Mods.MagicStorage.SortStack") - }); + sortButtons = MakeSortButtons(); } } - private static void InitFilterButtons() + public static UIButtonChoice MakeSortButtons() + { + return new UIButtonChoice(new Texture2D[] + { + Main.inventorySortTexture[0], + MagicStorage.Instance.GetTexture("SortID"), + MagicStorage.Instance.GetTexture("SortName"), + MagicStorage.Instance.GetTexture("SortNumber"), + MagicStorage.Instance.GetTexture("SortNumber") + }, + new LocalizedText[] + { + Language.GetText("Mods.MagicStorage.SortDefault"), + Language.GetText("Mods.MagicStorage.SortID"), + Language.GetText("Mods.MagicStorage.SortName"), + Language.GetText("Mods.MagicStorage.SortStack"), + Language.GetText("Mods.MagicStorage.SortDps") + },20); + } + + private static void InitFilterButtons() { if (filterButtons == null) { @@ -361,27 +368,9 @@ public static void RefreshItems() InitLangStuff(); InitSortButtons(); InitFilterButtons(); - SortMode sortMode; - switch (sortButtons.Choice) - { - case 0: - sortMode = SortMode.Default; - break; - case 1: - sortMode = SortMode.Id; - break; - case 2: - sortMode = SortMode.Name; - break; - case 3: - sortMode = SortMode.Value; - break; - default: - sortMode = SortMode.Default; - break; - } + SortMode sortMode = (SortMode)sortButtons.Choice; - FilterMode filterMode = (FilterMode)filterButtons.Choice; + FilterMode filterMode = (FilterMode)filterButtons.Choice; items.AddRange(ItemSorter.SortAndFilter(heart.GetStoredItems(), sortMode, filterMode, searchBar2.Text, searchBar.Text)); for (int k = 0; k < items.Count; k++) { From 91cc835a0a6b08cbd4c2ecf9a3e5b10c4e46818b Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 12 Aug 2018 00:53:52 +0300 Subject: [PATCH 14/80] clearing text box on right click, added handling for arrow keys, home, end, delete --- UISearchBar.cs | 99 ++++++++++++++++++++++++++++++-------------------- 1 file changed, 60 insertions(+), 39 deletions(-) diff --git a/UISearchBar.cs b/UISearchBar.cs index bf32262d..615fe81e 100644 --- a/UISearchBar.cs +++ b/UISearchBar.cs @@ -55,37 +55,36 @@ public override void Update(GameTime gameTime) cursorTimer++; cursorTimer %= 60; - if (StorageGUI.MouseClicked && Parent != null) - { - Rectangle dim = InterfaceHelper.GetFullRectangle(this); - MouseState mouse = StorageGUI.curMouse; - bool mouseOver = mouse.X > dim.X && mouse.X < dim.X + dim.Width && mouse.Y > dim.Y && mouse.Y < dim.Y + dim.Height; - if (!hasFocus && mouseOver) - { - hasFocus = true; - CheckBlockInput(); - } - else if (hasFocus && !mouseOver) - { - hasFocus = false; - CheckBlockInput(); - cursorPosition = text.Length; - } - } - else if (StorageGUI.curMouse.RightButton == ButtonState.Pressed && StorageGUI.oldMouse.RightButton == ButtonState.Released && Parent != null && hasFocus) - { - Rectangle dim = InterfaceHelper.GetFullRectangle(this); - MouseState mouse = StorageGUI.curMouse; - bool mouseOver = mouse.X > dim.X && mouse.X < dim.X + dim.Width && mouse.Y > dim.Y && mouse.Y < dim.Y + dim.Height; - if (!mouseOver) - { - hasFocus = false; - cursorPosition = text.Length; - CheckBlockInput(); - } - } - - if (hasFocus) + Rectangle dim = InterfaceHelper.GetFullRectangle(this); + MouseState mouse = StorageGUI.curMouse; + bool mouseOver = mouse.X > dim.X && mouse.X < dim.X + dim.Width && mouse.Y > dim.Y && mouse.Y < dim.Y + dim.Height; + if (StorageGUI.MouseClicked && Parent != null) + { + if (!hasFocus && mouseOver) + { + hasFocus = true; + CheckBlockInput(); + } + else if (hasFocus && !mouseOver) + { + hasFocus = false; + CheckBlockInput(); + cursorPosition = text.Length; + } + } + else if (StorageGUI.curMouse.RightButton == ButtonState.Pressed && StorageGUI.oldMouse.RightButton == ButtonState.Released && Parent != null && hasFocus && !mouseOver) + { + hasFocus = false; + cursorPosition = text.Length; + CheckBlockInput(); + } + else if (StorageGUI.curMouse.RightButton == ButtonState.Pressed && StorageGUI.oldMouse.RightButton == ButtonState.Released && mouseOver) + { + text = string.Empty; + cursorPosition = 0; + } + + if (hasFocus) { PlayerInput.WritingText = true; Main.instance.HandleIME(); @@ -95,14 +94,36 @@ public override void Update(GameTime gameTime) text = newString; cursorPosition = text.Length; StorageGUI.RefreshItems(); - } - if (KeyTyped(Keys.Enter) || KeyTyped(Keys.Tab) || KeyTyped(Keys.Escape)) - { - hasFocus = false; - CheckBlockInput(); - } - } - base.Update(gameTime); + } + if (KeyTyped(Keys.Delete)) + { + if (text.Length > 0 && cursorPosition < text.Length - 1) + text = text.Remove(cursorPosition, 1); + } + if (KeyTyped(Keys.Left)) + { + if (cursorPosition > 0) cursorPosition--; + } + if (KeyTyped(Keys.Right)) + { + if (cursorPosition < text.Length) cursorPosition++; + } + if (KeyTyped(Keys.Home)) + { + cursorPosition = 0; + } + if (KeyTyped(Keys.End)) + { + cursorPosition = text.Length; + } + if (KeyTyped(Keys.Enter) || KeyTyped(Keys.Tab) || KeyTyped(Keys.Escape)) + { + hasFocus = false; + CheckBlockInput(); + } + +} + base.Update(gameTime); } protected override void DrawSelf(SpriteBatch spriteBatch) From 59c332bda266d41be5ca9404232298d04acc06bd Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 12 Aug 2018 01:44:37 +0300 Subject: [PATCH 15/80] filtering new 30 items --- Components/TEStorageHeart.cs | 38 +++++++++- CraftingGUI.cs | 15 ++-- ItemHideList.cs => ItemTypeOrderedSet.cs | 16 +++- MagicStorage.csproj | 2 +- Sorting/CompareFunction.cs | 8 ++ Sorting/FilterMode.cs | 3 +- Sorting/ItemFilter.cs | 1 + Sorting/ItemSorter.cs | 5 ++ Sorting/SortMode.cs | 3 +- StorageGUI.cs | 93 ++++++++++++++---------- StoragePlayer.cs | 5 +- 11 files changed, 132 insertions(+), 57 deletions(-) rename ItemHideList.cs => ItemTypeOrderedSet.cs (72%) diff --git a/Components/TEStorageHeart.cs b/Components/TEStorageHeart.cs index bc19a849..fb198507 100644 --- a/Components/TEStorageHeart.cs +++ b/Components/TEStorageHeart.cs @@ -256,7 +256,10 @@ public void ResetCompactStage(int stage = 0) } } - public void DepositItem(Item toDeposit) + ItemTypeOrderedSet _uniqueItemsPutHistory = new ItemTypeOrderedSet("UniqueItemsPutHistory "); + public IEnumerable UniqueItemsPutHistory { get { return _uniqueItemsPutHistory.Items; } } + + public void DepositItem(Item toDeposit) { if (Main.netMode == 2) { @@ -276,14 +279,15 @@ public void DepositItem(Item toDeposit) } } } - foreach (TEAbstractStorageUnit storageUnit in GetStorageUnits()) + foreach (TEAbstractStorageUnit storageUnit in GetStorageUnits()) { if (!storageUnit.Inactive && !storageUnit.IsFull) { storageUnit.DepositItem(toDeposit, true); if (toDeposit.IsAir) - { - return; + { + _uniqueItemsPutHistory.Add(toDeposit); + return; } } } @@ -352,6 +356,30 @@ public Item TryWithdraw(Item lookFor) } } + public bool HasItem(Item lookFor) + { + if (Main.netMode == 2) + { + EnterReadLock(); + } + try + { + foreach (TEAbstractStorageUnit storageUnit in GetStorageUnits()) + { + if (storageUnit.HasItem(lookFor, true)) + return true; + } + return false; + } + finally + { + if (Main.netMode == 2) + { + ExitReadLock(); + } + } + } + public override TagCompound Save() { TagCompound tag = base.Save(); @@ -364,6 +392,7 @@ public override TagCompound Save() tagRemotes.Add(tagRemote); } tag.Set("RemoteAccesses", tagRemotes); + _uniqueItemsPutHistory.Save(tag); return tag; } @@ -374,6 +403,7 @@ public override void Load(TagCompound tag) { remoteAccesses.Add(new Point16(tagRemote.GetShort("X"), tagRemote.GetShort("Y"))); } + _uniqueItemsPutHistory.Load(tag); } public override void NetSend(BinaryWriter writer, bool lightSend) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index c5acd944..72f28735 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -94,6 +94,7 @@ public static bool RightMouseClicked private static UIText capacityText; private static UIPanel recipePanel = new UIPanel(); + private static float recipeTop; private static float recipeLeft; private static float recipeWidth; @@ -263,7 +264,7 @@ public static void Initialize() capacityText.SetText(numItems + "/" + capacity + " Items"); bottomBar.Append(capacityText); - recipePanel.Append(recipePanelHeader); + recipePanel.Append(recipePanelHeader); ingredientText.Top.Set(30f, 0f); recipePanel.Append(ingredientText); @@ -392,7 +393,7 @@ private static void InitFilterButtons() { if (filterButtons == null) { - filterButtons = StorageGUI.MakeFilterButtons(); + filterButtons = StorageGUI.MakeFilterButtons(false); } } @@ -416,6 +417,7 @@ public static void Update(GameTime gameTime) { scrollBarFocus = 0; selectedRecipe = null; + UpdateRecipeText(); craftTimer = 0; maxCraftTimer = startMaxCraftTimer; ResetSlotFocus(); @@ -535,10 +537,12 @@ private static void UpdateRecipeText() if (selectedRecipe == null) { reqObjText2.SetText(""); - } + + recipePanelHeader.SetText(Language.GetText("Mods.MagicStorage.SelectedRecipe").Value); + } else { - bool isEmpty = true; + bool isEmpty = true; string text = ""; for (int k = 0; k < selectedRecipe.requiredTile.Length; k++) { @@ -594,7 +598,8 @@ private static void UpdateRecipeText() text = Language.GetTextValue("LegacyInterface.23"); } reqObjText2.SetText(text); - } + recipePanelHeader.SetText(selectedRecipe.createItem.Name); + } } private static void UpdateScrollBar() diff --git a/ItemHideList.cs b/ItemTypeOrderedSet.cs similarity index 72% rename from ItemHideList.cs rename to ItemTypeOrderedSet.cs index f8df613d..d7635fd8 100644 --- a/ItemHideList.cs +++ b/ItemTypeOrderedSet.cs @@ -5,13 +5,14 @@ namespace MagicStorage { - public class ItemHideList + public class ItemTypeOrderedSet { readonly string _name; List _items = new List(); HashSet _set = new HashSet(); + public int Count { get { return _items.Count; } } - public ItemHideList(string name) + public ItemTypeOrderedSet(string name) { _name = name; } @@ -37,6 +38,17 @@ public bool Remove(Item item) } return false; } + + public bool RemoveAt(int index) + { + var item = _items[index]; + if (_set.Remove(item.type)) + { + _items.RemoveAt(index); + return true; + } + return false; + } public void Save(TagCompound c) { diff --git a/MagicStorage.csproj b/MagicStorage.csproj index 324fb803..a20aa3d7 100644 --- a/MagicStorage.csproj +++ b/MagicStorage.csproj @@ -106,7 +106,7 @@ - + diff --git a/Sorting/CompareFunction.cs b/Sorting/CompareFunction.cs index a3851852..d1eb154d 100644 --- a/Sorting/CompareFunction.cs +++ b/Sorting/CompareFunction.cs @@ -66,4 +66,12 @@ static float GetDps(Item item1) return item1.damage / (float)Math.Max(item1.useTime, 1); } } + + public class AsIs : CompareFunction + { + public override int Compare(Item item1, Item item2) + { + return 0; + } + } } \ No newline at end of file diff --git a/Sorting/FilterMode.cs b/Sorting/FilterMode.cs index 61609b84..be9e1f86 100644 --- a/Sorting/FilterMode.cs +++ b/Sorting/FilterMode.cs @@ -17,6 +17,7 @@ public enum FilterMode Vanity, Potions, Placeables, - Misc + Misc, + Recent } } \ No newline at end of file diff --git a/Sorting/ItemFilter.cs b/Sorting/ItemFilter.cs index de6b12e8..f9b3980f 100644 --- a/Sorting/ItemFilter.cs +++ b/Sorting/ItemFilter.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using MagicStorage.Components; using Terraria; namespace MagicStorage.Sorting diff --git a/Sorting/ItemSorter.cs b/Sorting/ItemSorter.cs index 7998c569..4676d096 100644 --- a/Sorting/ItemSorter.cs +++ b/Sorting/ItemSorter.cs @@ -45,6 +45,9 @@ static CompareFunction MakeSortFunction(SortMode sortMode) case SortMode.Dps: func = new CompareDps(); break; + case SortMode.AsIs: + func = new AsIs(); + break; default: func = null; break; @@ -100,6 +103,8 @@ static ItemFilter MakeFilter(FilterMode filterMode) case FilterMode.Misc: filter = new FilterMisc(); break; + case FilterMode.Recent: + throw new NotSupportedException(); default: filter = new FilterAll(); break; diff --git a/Sorting/SortMode.cs b/Sorting/SortMode.cs index 2b46019a..311809eb 100644 --- a/Sorting/SortMode.cs +++ b/Sorting/SortMode.cs @@ -8,6 +8,7 @@ public enum SortMode Id, Name, Value, - Dps + Dps, + AsIs } } \ No newline at end of file diff --git a/StorageGUI.cs b/StorageGUI.cs index 4c0615ce..d0bdc08d 100644 --- a/StorageGUI.cs +++ b/StorageGUI.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; @@ -212,46 +213,52 @@ private static void InitFilterButtons() { if (filterButtons == null) { - filterButtons = MakeFilterButtons(); + filterButtons = MakeFilterButtons(true); } } - public static UIButtonChoice MakeFilterButtons() + public static UIButtonChoice MakeFilterButtons(bool withHistory) { - return new UIButtonChoice(new Texture2D[] - { - MagicStorage.Instance.GetTexture("FilterAll"), - MagicStorage.Instance.GetTexture("FilterMelee"), - MagicStorage.Instance.GetTexture("FilterRanged"), - MagicStorage.Instance.GetTexture("FilterMagic"), - MagicStorage.Instance.GetTexture("FilterSummon"), - MagicStorage.Instance.GetTexture("FilterThrowing"), - MagicStorage.Instance.GetTexture("FilterThrowing"), - MagicStorage.Instance.GetTexture("FilterPickaxe"), - MagicStorage.Instance.GetTexture("FilterArmor"), - MagicStorage.Instance.GetTexture("FilterArmor"), - MagicStorage.Instance.GetTexture("FilterArmor"), - MagicStorage.Instance.GetTexture("FilterPotion"), - MagicStorage.Instance.GetTexture("FilterTile"), - MagicStorage.Instance.GetTexture("FilterMisc"), - }, - new LocalizedText[] - { - Language.GetText("Mods.MagicStorage.FilterAll"), - Language.GetText("Mods.MagicStorage.FilterWeaponsMelee"), - Language.GetText("Mods.MagicStorage.FilterWeaponsRanged"), - Language.GetText("Mods.MagicStorage.FilterWeaponsMagic"), - Language.GetText("Mods.MagicStorage.FilterWeaponsSummon"), - Language.GetText("Mods.MagicStorage.FilterWeaponsThrown"), - Language.GetText("Mods.MagicStorage.FilterAmmo"), - Language.GetText("Mods.MagicStorage.FilterTools"), - Language.GetText("Mods.MagicStorage.FilterArmor"), - Language.GetText("Mods.MagicStorage.FilterEquips"), - Language.GetText("Mods.MagicStorage.FilterVanity"), - Language.GetText("Mods.MagicStorage.FilterPotions"), - Language.GetText("Mods.MagicStorage.FilterTiles"), - Language.GetText("Mods.MagicStorage.FilterMisc") - }, 15); + var textures = new List + { + MagicStorage.Instance.GetTexture("FilterAll"), + MagicStorage.Instance.GetTexture("FilterMelee"), + MagicStorage.Instance.GetTexture("FilterRanged"), + MagicStorage.Instance.GetTexture("FilterMagic"), + MagicStorage.Instance.GetTexture("FilterSummon"), + MagicStorage.Instance.GetTexture("FilterThrowing"), + MagicStorage.Instance.GetTexture("FilterThrowing"), + MagicStorage.Instance.GetTexture("FilterPickaxe"), + MagicStorage.Instance.GetTexture("FilterArmor"), + MagicStorage.Instance.GetTexture("FilterArmor"), + MagicStorage.Instance.GetTexture("FilterArmor"), + MagicStorage.Instance.GetTexture("FilterPotion"), + MagicStorage.Instance.GetTexture("FilterTile"), + MagicStorage.Instance.GetTexture("FilterMisc"), + }; + var texts = new List + { + Language.GetText("Mods.MagicStorage.FilterAll"), + Language.GetText("Mods.MagicStorage.FilterWeaponsMelee"), + Language.GetText("Mods.MagicStorage.FilterWeaponsRanged"), + Language.GetText("Mods.MagicStorage.FilterWeaponsMagic"), + Language.GetText("Mods.MagicStorage.FilterWeaponsSummon"), + Language.GetText("Mods.MagicStorage.FilterWeaponsThrown"), + Language.GetText("Mods.MagicStorage.FilterAmmo"), + Language.GetText("Mods.MagicStorage.FilterTools"), + Language.GetText("Mods.MagicStorage.FilterArmor"), + Language.GetText("Mods.MagicStorage.FilterEquips"), + Language.GetText("Mods.MagicStorage.FilterVanity"), + Language.GetText("Mods.MagicStorage.FilterPotions"), + Language.GetText("Mods.MagicStorage.FilterTiles"), + Language.GetText("Mods.MagicStorage.FilterMisc") + }; + if (withHistory) + { + textures.Add(MagicStorage.Instance.GetTexture("FilterAll")); + texts.Add(Language.GetText("Mods.MagicStorage.FilterRecent")); + } + return new UIButtonChoice(textures.ToArray(), texts.ToArray(), 15); } public static void Update(GameTime gameTime) @@ -368,10 +375,16 @@ public static void RefreshItems() InitLangStuff(); InitSortButtons(); InitFilterButtons(); - SortMode sortMode = (SortMode)sortButtons.Choice; - - FilterMode filterMode = (FilterMode)filterButtons.Choice; - items.AddRange(ItemSorter.SortAndFilter(heart.GetStoredItems(), sortMode, filterMode, searchBar2.Text, searchBar.Text)); + SortMode sortMode = (SortMode)sortButtons.Choice; + + FilterMode filterMode = (FilterMode) filterButtons.Choice; + IEnumerable itemsLocal; + if (filterMode == FilterMode.Recent) + itemsLocal = ItemSorter.SortAndFilter(heart.UniqueItemsPutHistory.Where(x => heart.HasItem(x)).Take(30).ToArray(), sortMode == SortMode.Default ? SortMode.AsIs : sortMode, + FilterMode.All, searchBar2.Text, searchBar.Text); + else + itemsLocal = ItemSorter.SortAndFilter(heart.GetStoredItems(), sortMode, filterMode, searchBar2.Text, searchBar.Text); + items.AddRange(itemsLocal); for (int k = 0; k < items.Count; k++) { didMatCheck.Add(false); diff --git a/StoragePlayer.cs b/StoragePlayer.cs index 27261f15..43f05a5a 100644 --- a/StoragePlayer.cs +++ b/StoragePlayer.cs @@ -16,8 +16,8 @@ public class StoragePlayer : ModPlayer private Point16 storageAccess = new Point16(-1, -1); public bool remoteAccess = false; - ItemHideList _hiddenRecipes = new ItemHideList("HiddenItems"); - ItemHideList _craftedRecipes = new ItemHideList("CraftedRecipes"); + ItemTypeOrderedSet _hiddenRecipes = new ItemTypeOrderedSet("HiddenItems"); + ItemTypeOrderedSet _craftedRecipes = new ItemTypeOrderedSet("CraftedRecipes"); public IEnumerable HiddenRecipes { get { return _hiddenRecipes.Items; } } public IEnumerable CraftedRecipes { get { return _craftedRecipes.Items; } } @@ -49,7 +49,6 @@ public override void Load(TagCompound tag) { _hiddenRecipes.Load(tag); _craftedRecipes.Load(tag); - } public override void UpdateDead() From db6464bb2965b4ce110bd913f44742fa5d90b980 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 12 Aug 2018 01:53:01 +0300 Subject: [PATCH 16/80] hopely fixed filter icon size --- StorageGUI.cs | 4 ++-- UIButtonChoice.cs | 8 +++++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/StorageGUI.cs b/StorageGUI.cs index d0bdc08d..9b83a57f 100644 --- a/StorageGUI.cs +++ b/StorageGUI.cs @@ -206,7 +206,7 @@ public static UIButtonChoice MakeSortButtons() Language.GetText("Mods.MagicStorage.SortName"), Language.GetText("Mods.MagicStorage.SortStack"), Language.GetText("Mods.MagicStorage.SortDps") - },20); + }); } private static void InitFilterButtons() @@ -258,7 +258,7 @@ public static UIButtonChoice MakeFilterButtons(bool withHistory) textures.Add(MagicStorage.Instance.GetTexture("FilterAll")); texts.Add(Language.GetText("Mods.MagicStorage.FilterRecent")); } - return new UIButtonChoice(textures.ToArray(), texts.ToArray(), 15); + return new UIButtonChoice(textures.ToArray(), texts.ToArray()); } public static void Update(GameTime gameTime) diff --git a/UIButtonChoice.cs b/UIButtonChoice.cs index e0f6d0c1..01d7ecb4 100644 --- a/UIButtonChoice.cs +++ b/UIButtonChoice.cs @@ -12,8 +12,8 @@ namespace MagicStorage { public class UIButtonChoice : UIElement { - private const int buttonSize = 32; - private const int buttonPadding = 8; + private int buttonSize; + private int buttonPadding; private Texture2D[] buttons; private LocalizedText[] names; @@ -27,12 +27,14 @@ public int Choice } } - public UIButtonChoice(Texture2D[] buttons, LocalizedText[] names, int buttonSize = buttonSize) + public UIButtonChoice(Texture2D[] buttons, LocalizedText[] names, int buttonSize = 16, int buttonPadding = 4) { if (buttons.Length != names.Length || buttons.Length == 0) { throw new ArgumentException(); } + this.buttonSize = buttonSize; + this.buttonPadding = buttonPadding; this.buttons = buttons; this.names = names; int width = buttonSize * buttons.Length + buttonPadding * (buttons.Length - 1); From 4c23f7eef843ec3c4708e70bc1f3b6831e569811 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 12 Aug 2018 02:46:14 +0300 Subject: [PATCH 17/80] fixes to make it all work, added DPS counter in craft menu --- Components/TEStorageHeart.cs | 5 +- CraftingGUI.cs | 18 ++++--- GUIHelpers.cs | 76 ++++++++++++++++++++++++++ MagicStorage.cs | 4 ++ MagicStorage.csproj | 1 + Sorting/CompareFunction.cs | 6 +-- Sorting/ItemFilter.cs | 6 +-- Sorting/ItemSorter.cs | 3 +- StorageGUI.cs | 102 ++++++++--------------------------- UIButtonChoice.cs | 6 +-- 10 files changed, 129 insertions(+), 98 deletions(-) create mode 100644 GUIHelpers.cs diff --git a/Components/TEStorageHeart.cs b/Components/TEStorageHeart.cs index fb198507..d57e2fd5 100644 --- a/Components/TEStorageHeart.cs +++ b/Components/TEStorageHeart.cs @@ -256,7 +256,7 @@ public void ResetCompactStage(int stage = 0) } } - ItemTypeOrderedSet _uniqueItemsPutHistory = new ItemTypeOrderedSet("UniqueItemsPutHistory "); + ItemTypeOrderedSet _uniqueItemsPutHistory = new ItemTypeOrderedSet("UniqueItemsPutHistory"); public IEnumerable UniqueItemsPutHistory { get { return _uniqueItemsPutHistory.Items; } } public void DepositItem(Item toDeposit) @@ -268,6 +268,7 @@ public void DepositItem(Item toDeposit) int oldStack = toDeposit.stack; try { + var remember = toDeposit.Clone(); foreach (TEAbstractStorageUnit storageUnit in GetStorageUnits()) { if (!storageUnit.Inactive && storageUnit.HasSpaceInStackFor(toDeposit, true)) @@ -286,7 +287,7 @@ public void DepositItem(Item toDeposit) storageUnit.DepositItem(toDeposit, true); if (toDeposit.IsAir) { - _uniqueItemsPutHistory.Add(toDeposit); + _uniqueItemsPutHistory.Add(remember); return; } } diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 72f28735..0570bd7f 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -139,7 +139,7 @@ public static bool RightMouseClicked private static List threadRecipeAvailable = new List(); private static List nextRecipes = new List(); private static List nextRecipeAvailable = new List(); - + public static void Initialize() { lock (recipeLock) @@ -366,7 +366,7 @@ private static void InitSortButtons() { if (sortButtons == null) { - sortButtons = StorageGUI.MakeSortButtons(); + sortButtons = GUIHelpers.MakeSortButtons(); } } @@ -393,12 +393,13 @@ private static void InitFilterButtons() { if (filterButtons == null) { - filterButtons = StorageGUI.MakeFilterButtons(false); + filterButtons = GUIHelpers.MakeFilterButtons(false); } } public static void Update(GameTime gameTime) - {try{ + { + try { oldMouse = StorageGUI.oldMouse; curMouse = StorageGUI.curMouse; if (Main.playerInventory && Main.player[Main.myPlayer].GetModPlayer(MagicStorage.Instance).ViewingStorage().X >= 0 && StoragePlayer.IsStorageCrafting()) @@ -417,7 +418,6 @@ public static void Update(GameTime gameTime) { scrollBarFocus = 0; selectedRecipe = null; - UpdateRecipeText(); craftTimer = 0; maxCraftTimer = startMaxCraftTimer; ResetSlotFocus(); @@ -537,7 +537,6 @@ private static void UpdateRecipeText() if (selectedRecipe == null) { reqObjText2.SetText(""); - recipePanelHeader.SetText(Language.GetText("Mods.MagicStorage.SelectedRecipe").Value); } else @@ -598,7 +597,12 @@ private static void UpdateRecipeText() text = Language.GetTextValue("LegacyInterface.23"); } reqObjText2.SetText(text); - recipePanelHeader.SetText(selectedRecipe.createItem.Name); + var item = selectedRecipe.createItem; + var headerText = selectedRecipe.createItem.Name; + var dps = CompareDps.GetDps(item); + if (dps >= 1f) + headerText += " (" + dps.ToString("F0") + " DPS)"; + recipePanelHeader.SetText(headerText); } } diff --git a/GUIHelpers.cs b/GUIHelpers.cs new file mode 100644 index 00000000..58dfad09 --- /dev/null +++ b/GUIHelpers.cs @@ -0,0 +1,76 @@ +using System.Collections.Generic; +using Microsoft.Xna.Framework.Graphics; +using Terraria; +using Terraria.Localization; + +namespace MagicStorage +{ + public class GUIHelpers + { + + public static UIButtonChoice MakeSortButtons() + { + return new UIButtonChoice(new Texture2D[] + { + Main.inventorySortTexture[0], + MagicStorage.Instance.GetTexture("SortID"), + MagicStorage.Instance.GetTexture("SortName"), + MagicStorage.Instance.GetTexture("SortNumber"), + MagicStorage.Instance.GetTexture("SortNumber") + }, + new LocalizedText[] + { + Language.GetText("Mods.MagicStorage.SortDefault"), + Language.GetText("Mods.MagicStorage.SortID"), + Language.GetText("Mods.MagicStorage.SortName"), + Language.GetText("Mods.MagicStorage.SortStack"), + Language.GetText("Mods.MagicStorage.SortDps") + }); + } + + public static UIButtonChoice MakeFilterButtons(bool withHistory) + { + var textures = new List + { + MagicStorage.Instance.GetTexture("FilterAll"), + MagicStorage.Instance.GetTexture("FilterMelee"), + MagicStorage.Instance.GetTexture("FilterRanged"), + MagicStorage.Instance.GetTexture("FilterMagic"), + MagicStorage.Instance.GetTexture("FilterSummon"), + MagicStorage.Instance.GetTexture("FilterThrowing"), + MagicStorage.Instance.GetTexture("FilterThrowing"), + MagicStorage.Instance.GetTexture("FilterPickaxe"), + MagicStorage.Instance.GetTexture("FilterArmor"), + MagicStorage.Instance.GetTexture("FilterArmor"), + MagicStorage.Instance.GetTexture("FilterArmor"), + MagicStorage.Instance.GetTexture("FilterPotion"), + MagicStorage.Instance.GetTexture("FilterTile"), + MagicStorage.Instance.GetTexture("FilterMisc"), + }; + var texts = new List + { + Language.GetText("Mods.MagicStorage.FilterAll"), + Language.GetText("Mods.MagicStorage.FilterWeaponsMelee"), + Language.GetText("Mods.MagicStorage.FilterWeaponsRanged"), + Language.GetText("Mods.MagicStorage.FilterWeaponsMagic"), + Language.GetText("Mods.MagicStorage.FilterWeaponsSummon"), + Language.GetText("Mods.MagicStorage.FilterWeaponsThrown"), + Language.GetText("Mods.MagicStorage.FilterAmmo"), + Language.GetText("Mods.MagicStorage.FilterTools"), + Language.GetText("Mods.MagicStorage.FilterArmor"), + Language.GetText("Mods.MagicStorage.FilterEquips"), + Language.GetText("Mods.MagicStorage.FilterVanity"), + Language.GetText("Mods.MagicStorage.FilterPotions"), + Language.GetText("Mods.MagicStorage.FilterTiles"), + Language.GetText("Mods.MagicStorage.FilterMisc") + }; + if (withHistory) + { + textures.Add(MagicStorage.Instance.GetTexture("FilterAll")); + texts.Add(Language.GetText("Mods.MagicStorage.FilterRecent")); + } + return new UIButtonChoice(textures.ToArray(), texts.ToArray()); + } + + } +} \ No newline at end of file diff --git a/MagicStorage.cs b/MagicStorage.cs index 1bdb9f10..bd18648e 100644 --- a/MagicStorage.cs +++ b/MagicStorage.cs @@ -189,6 +189,10 @@ private void AddTranslations() text.AddTranslation(GameCulture.Spanish, "Filtrar por otros"); AddTranslation(text); + text = CreateTranslation("FilterRecent"); + text.SetDefault("Filter New Recently Added Items"); + AddTranslation(text); + text = CreateTranslation("CraftingStations"); text.SetDefault("Crafting Stations"); text.AddTranslation(GameCulture.Russian, "Станции создания"); diff --git a/MagicStorage.csproj b/MagicStorage.csproj index a20aa3d7..1d848828 100644 --- a/MagicStorage.csproj +++ b/MagicStorage.csproj @@ -69,6 +69,7 @@ + diff --git a/Sorting/CompareFunction.cs b/Sorting/CompareFunction.cs index d1eb154d..9a7dde4d 100644 --- a/Sorting/CompareFunction.cs +++ b/Sorting/CompareFunction.cs @@ -61,9 +61,9 @@ public override int Compare(Item item1, Item item2) return (int)((GetDps(item1) - GetDps(item2)) * 100); } - static float GetDps(Item item1) - { - return item1.damage / (float)Math.Max(item1.useTime, 1); + public static float GetDps(Item item) + { + return item.damage / Math.Max((item.useTime + item.reuseDelay) / 60f, 1f); } } diff --git a/Sorting/ItemFilter.cs b/Sorting/ItemFilter.cs index f9b3980f..db863452 100644 --- a/Sorting/ItemFilter.cs +++ b/Sorting/ItemFilter.cs @@ -42,10 +42,10 @@ public override bool Passes(Item item) public class FilterWeaponRanged : ItemFilter { readonly FilterWeaponThrown _thrown = new FilterWeaponThrown(); - + public override bool Passes(Item item) { - return item.ranged && item.damage > 0 && !_thrown.Passes(item); + return item.ranged && item.damage > 0 && item.ammo <= 0 && !_thrown.Passes(item); } } @@ -77,7 +77,7 @@ public class FilterAmmo : ItemFilter { public override bool Passes(Item item) { - return item.ammo > 0; + return item.ammo > 0 && item.damage > 0; } } diff --git a/Sorting/ItemSorter.cs b/Sorting/ItemSorter.cs index 4676d096..18d59bac 100644 --- a/Sorting/ItemSorter.cs +++ b/Sorting/ItemSorter.cs @@ -7,10 +7,11 @@ namespace MagicStorage.Sorting { public static class ItemSorter { - public static IEnumerable SortAndFilter(IEnumerable items, SortMode sortMode, FilterMode filterMode, string modFilter, string nameFilter) + public static IEnumerable SortAndFilter(IEnumerable items, SortMode sortMode, FilterMode filterMode, string modFilter, string nameFilter, int? takeCount = null) { ItemFilter filter = MakeFilter(filterMode); IEnumerable filteredItems = items.Where((item) => filter.Passes(item) && FilterName(item, modFilter, nameFilter)); + if (takeCount != null) filteredItems = filteredItems.Take(takeCount.Value); var func = MakeSortFunction(sortMode); if (func == null) return filteredItems; return filteredItems.OrderBy(x => x, func); diff --git a/StorageGUI.cs b/StorageGUI.cs index 9b83a57f..be676e35 100644 --- a/StorageGUI.cs +++ b/StorageGUI.cs @@ -65,7 +65,7 @@ public static bool MouseClicked private static UIElement bottomBar = new UIElement(); private static UIText capacityText; - + public static void Initialize() { InitLangStuff(); @@ -110,12 +110,14 @@ public static void Initialize() basePanel.Append(topBar2); InitFilterButtons(); - topBar2.Append(filterButtons); - searchBar2.Left.Set(depositButtonRight + padding, 0f); - searchBar2.Width.Set(-depositButtonRight - 2 * padding, 1f); - searchBar2.Height.Set(0f, 1f); - topBar2.Append(searchBar2); + float filterButtonsRight = filterButtons.GetDimensions().Width + padding; + topBar2.Append(filterButtons); + searchBar2.Left.Set(filterButtonsRight + padding, 0f); + searchBar2.Width.Set(-filterButtonsRight - 2 * padding, 1f); + searchBar2.Height.Set(0f, 1f); + topBar2.Append(searchBar2); + slotZone.Width.Set(0f, 1f); slotZone.Top.Set(76f, 0f); slotZone.Height.Set(-116f, 1f); @@ -159,7 +161,8 @@ public static void Initialize() } capacityText.SetText(numItems + "/" + capacity + " Items"); bottomBar.Append(capacityText); - } + + } private static void InitLangStuff() { @@ -185,82 +188,18 @@ private static void InitSortButtons() { if (sortButtons == null) { - sortButtons = MakeSortButtons(); + sortButtons = GUIHelpers.MakeSortButtons(); } } - public static UIButtonChoice MakeSortButtons() - { - return new UIButtonChoice(new Texture2D[] - { - Main.inventorySortTexture[0], - MagicStorage.Instance.GetTexture("SortID"), - MagicStorage.Instance.GetTexture("SortName"), - MagicStorage.Instance.GetTexture("SortNumber"), - MagicStorage.Instance.GetTexture("SortNumber") - }, - new LocalizedText[] - { - Language.GetText("Mods.MagicStorage.SortDefault"), - Language.GetText("Mods.MagicStorage.SortID"), - Language.GetText("Mods.MagicStorage.SortName"), - Language.GetText("Mods.MagicStorage.SortStack"), - Language.GetText("Mods.MagicStorage.SortDps") - }); - } - private static void InitFilterButtons() { if (filterButtons == null) { - filterButtons = MakeFilterButtons(true); + filterButtons = GUIHelpers.MakeFilterButtons(true); } } - public static UIButtonChoice MakeFilterButtons(bool withHistory) - { - var textures = new List - { - MagicStorage.Instance.GetTexture("FilterAll"), - MagicStorage.Instance.GetTexture("FilterMelee"), - MagicStorage.Instance.GetTexture("FilterRanged"), - MagicStorage.Instance.GetTexture("FilterMagic"), - MagicStorage.Instance.GetTexture("FilterSummon"), - MagicStorage.Instance.GetTexture("FilterThrowing"), - MagicStorage.Instance.GetTexture("FilterThrowing"), - MagicStorage.Instance.GetTexture("FilterPickaxe"), - MagicStorage.Instance.GetTexture("FilterArmor"), - MagicStorage.Instance.GetTexture("FilterArmor"), - MagicStorage.Instance.GetTexture("FilterArmor"), - MagicStorage.Instance.GetTexture("FilterPotion"), - MagicStorage.Instance.GetTexture("FilterTile"), - MagicStorage.Instance.GetTexture("FilterMisc"), - }; - var texts = new List - { - Language.GetText("Mods.MagicStorage.FilterAll"), - Language.GetText("Mods.MagicStorage.FilterWeaponsMelee"), - Language.GetText("Mods.MagicStorage.FilterWeaponsRanged"), - Language.GetText("Mods.MagicStorage.FilterWeaponsMagic"), - Language.GetText("Mods.MagicStorage.FilterWeaponsSummon"), - Language.GetText("Mods.MagicStorage.FilterWeaponsThrown"), - Language.GetText("Mods.MagicStorage.FilterAmmo"), - Language.GetText("Mods.MagicStorage.FilterTools"), - Language.GetText("Mods.MagicStorage.FilterArmor"), - Language.GetText("Mods.MagicStorage.FilterEquips"), - Language.GetText("Mods.MagicStorage.FilterVanity"), - Language.GetText("Mods.MagicStorage.FilterPotions"), - Language.GetText("Mods.MagicStorage.FilterTiles"), - Language.GetText("Mods.MagicStorage.FilterMisc") - }; - if (withHistory) - { - textures.Add(MagicStorage.Instance.GetTexture("FilterAll")); - texts.Add(Language.GetText("Mods.MagicStorage.FilterRecent")); - } - return new UIButtonChoice(textures.ToArray(), texts.ToArray()); - } - public static void Update(GameTime gameTime) { oldMouse = curMouse; @@ -378,12 +317,17 @@ public static void RefreshItems() SortMode sortMode = (SortMode)sortButtons.Choice; FilterMode filterMode = (FilterMode) filterButtons.Choice; - IEnumerable itemsLocal; - if (filterMode == FilterMode.Recent) - itemsLocal = ItemSorter.SortAndFilter(heart.UniqueItemsPutHistory.Where(x => heart.HasItem(x)).Take(30).ToArray(), sortMode == SortMode.Default ? SortMode.AsIs : sortMode, - FilterMode.All, searchBar2.Text, searchBar.Text); - else - itemsLocal = ItemSorter.SortAndFilter(heart.GetStoredItems(), sortMode, filterMode, searchBar2.Text, searchBar.Text); + IEnumerable itemsLocal; + if (filterMode == FilterMode.Recent) + { + var stored = heart.GetStoredItems().GroupBy(x => x.type).ToDictionary(x => x.Key, x => x.First()); + + var toFilter = heart.UniqueItemsPutHistory.Reverse().Where(x => stored.ContainsKey(x.type)).Select(x => stored[x.type]); + itemsLocal = ItemSorter.SortAndFilter(toFilter, sortMode == SortMode.Default ? SortMode.AsIs : sortMode, + FilterMode.All, searchBar2.Text, searchBar.Text, 30); + } + else + itemsLocal = ItemSorter.SortAndFilter(heart.GetStoredItems(), sortMode, filterMode, searchBar2.Text, searchBar.Text); items.AddRange(itemsLocal); for (int k = 0; k < items.Count; k++) { diff --git a/UIButtonChoice.cs b/UIButtonChoice.cs index 01d7ecb4..e2e4e777 100644 --- a/UIButtonChoice.cs +++ b/UIButtonChoice.cs @@ -27,7 +27,7 @@ public int Choice } } - public UIButtonChoice(Texture2D[] buttons, LocalizedText[] names, int buttonSize = 16, int buttonPadding = 4) + public UIButtonChoice(Texture2D[] buttons, LocalizedText[] names, int buttonSize = 21, int buttonPadding = 1) { if (buttons.Length != names.Length || buttons.Length == 0) { @@ -84,8 +84,8 @@ protected override void DrawSelf(SpriteBatch spriteBatch) Texture2D texture = k == choice ? backTextureActive : backTexture; Vector2 drawPos = new Vector2(dim.X + k * (buttonSize + buttonPadding), dim.Y); Color color = MouseOverButton(StorageGUI.curMouse.X, StorageGUI.curMouse.Y, k) ? Color.Silver : Color.White; - Main.spriteBatch.Draw(texture, drawPos, color); - Main.spriteBatch.Draw(buttons[k], drawPos + new Vector2(1f), Color.White); + Main.spriteBatch.Draw(texture, new Rectangle((int)drawPos.X,(int)drawPos.Y,buttonSize,buttonSize), color); + Main.spriteBatch.Draw(buttons[k], new Rectangle((int)drawPos.X + 1, (int)drawPos.Y + 1, buttonSize - 1, buttonSize - 1), Color.White); } } From d98f39e03f3676b6f9bcd07043eceeb559ac63b7 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 12 Aug 2018 04:15:58 +0300 Subject: [PATCH 18/80] dps fix --- Sorting/CompareFunction.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sorting/CompareFunction.cs b/Sorting/CompareFunction.cs index 9a7dde4d..9dce4e25 100644 --- a/Sorting/CompareFunction.cs +++ b/Sorting/CompareFunction.cs @@ -63,7 +63,7 @@ public override int Compare(Item item1, Item item2) public static float GetDps(Item item) { - return item.damage / Math.Max((item.useTime + item.reuseDelay) / 60f, 1f); + return item.damage / Math.Max((item.useTime + item.reuseDelay) / 60f, 0.001f); } } From 7a326fbab6757e02906351e93ca2e2d405dcb8ad Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 12 Aug 2018 12:00:53 +0300 Subject: [PATCH 19/80] C# 6, mods are selected with left-right click instead of typing, recipe item icon is displayed on top, you can go into an ingredient recipe by right clicking it --- CraftingGUI.cs | 228 +++++++++++++++++++++++++++++++----------- MagicStorage.cs | 20 ++-- MagicStorage.csproj | 1 + ModSearchBox.cs | 91 +++++++++++++++++ Sorting/ItemSorter.cs | 30 ++++-- StorageGUI.cs | 31 +++--- StoragePlayer.cs | 10 +- build.txt | 1 + 8 files changed, 313 insertions(+), 99 deletions(-) create mode 100644 ModSearchBox.cs diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 0570bd7f..0be48688 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Reflection; using System.Threading; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; @@ -18,7 +19,7 @@ namespace MagicStorage { - public static class CraftingGUI + public static class CraftingGUI { const int RecipeButtonsNewChoice = 0; const int RecipeButtonsBlacklistChoice = 2; @@ -28,7 +29,7 @@ public static class CraftingGUI private const float inventoryScale = 0.85f; private const float smallScale = 0.7f; - static bool[] threadCheckListFoundItems; + static HashSet threadCheckListFoundItems; static Mod _checkListMod; public static MouseState curMouse; @@ -61,8 +62,7 @@ public static bool RightMouseClicked private static UIButtonChoice recipeButtons; private static UIElement topBar2 = new UIElement(); private static UIButtonChoice filterButtons; - internal static UISearchBar searchBar2; - + private static UIText stationText; private static UISlotZone stationZone = new UISlotZone(HoverStation, GetStation, inventoryScale / 1.55f); private static UIText recipeText; @@ -100,9 +100,10 @@ public static bool RightMouseClicked private static float recipeWidth; private static float recipeHeight; - private static UIText recipePanelHeader; + private static UIText recipePanelHeader; private static UIText ingredientText; private static UISlotZone ingredientZone = new UISlotZone(HoverItem, GetIngredient, smallScale); + private static UISlotZone recipeHeaderZone = new UISlotZone(HoverHeader, GetHeader, smallScale); private static UIText reqObjText; private static UIText reqObjText2; private static UIText storedItemsText; @@ -118,6 +119,8 @@ public static bool RightMouseClicked private static float scrollBar2MaxViewSize = 2f; internal static UITextPanel craftButton; + public static readonly ModSearchBox modSearchBox = new ModSearchBox(RefreshItems); + private static Item result = null; private static UISlotZone resultZone = new UISlotZone(HoverResult, GetResult, inventoryScale); private static int craftTimer = 0; @@ -203,10 +206,12 @@ public static void Initialize() InitFilterButtons(); float filterButtonsRight = filterButtons.GetDimensions().Width + padding; topBar2.Append(filterButtons); - searchBar2.Left.Set(filterButtonsRight + padding, 0f); - searchBar2.Width.Set(-filterButtonsRight - 2 * padding, 1f); - searchBar2.Height.Set(0f, 1f); - topBar2.Append(searchBar2); + + modSearchBox.Button.Left.Set(filterButtonsRight + padding, 0f); + modSearchBox.Button.Width.Set(-filterButtonsRight - 2 * padding, 1f); + modSearchBox.Button.Height.Set(0f, 1f); + modSearchBox.Button.OverflowHidden = true; + topBar2.Append(modSearchBox.Button); stationText.Top.Set(76f, 0f); basePanel.Append(stationText); @@ -264,9 +269,16 @@ public static void Initialize() capacityText.SetText(numItems + "/" + capacity + " Items"); bottomBar.Append(capacityText); + recipePanelHeader.Left.Set(60, 0f); recipePanel.Append(recipePanelHeader); - ingredientText.Top.Set(30f, 0f); - recipePanel.Append(ingredientText); + + ingredientText.Top.Set(30f, 0f); + ingredientText.Left.Set(60, 0f); + + recipeHeaderZone.SetDimensions(1, 1); + recipePanel.Append(recipeHeaderZone); + + recipePanel.Append(ingredientText); ingredientZone.SetDimensions(numColumns2, 2); ingredientZone.Top.Set(54f, 0f); @@ -320,10 +332,6 @@ private static void InitLangStuff() { searchBar = new UISearchBar(Language.GetText("Mods.MagicStorage.SearchName")); } - if (searchBar2 == null) - { - searchBar2 = new UISearchBar(Language.GetText("Mods.MagicStorage.SearchMod")); - } if (stationText == null) { stationText = new UIText(Language.GetText("Mods.MagicStorage.CraftingStations")); @@ -360,6 +368,7 @@ private static void InitLangStuff() { craftButton = new UITextPanel(Language.GetText("LegacyMisc.72"), 1f); } + modSearchBox.InitLangStuff(); } private static void InitSortButtons() @@ -413,6 +422,7 @@ public static void Update(GameTime gameTime) UpdateRecipeText(); UpdateScrollBar(); UpdateCraftButton(); + modSearchBox.Update(curMouse, oldMouse); } else { @@ -445,6 +455,7 @@ public static void Draw(TEStorageHeart heart) stationZone.DrawText(); recipeZone.DrawText(); ingredientZone.DrawText(); + recipeHeaderZone.DrawText(); storageZone.DrawText(); resultZone.DrawText(); sortButtons.DrawText(); @@ -481,13 +492,28 @@ private static Item GetRecipe(int slot, ref int context) return item; } - private static Item GetIngredient(int slot, ref int context) + private static Item GetHeader(int slot, ref int context) + { + if (selectedRecipe == null) + return new Item(); + + var item = selectedRecipe.createItem; + if (item.IsAir) + { + int t = item.type; + item = new Item(); + item.SetDefaults(t); + item.stack = 0; + } + return item; + } + + private static Item GetIngredient(int slot, ref int context) { - if (selectedRecipe == null || slot >= selectedRecipe.requiredItem.Length) - { - return new Item(); - } - Item item = selectedRecipe.requiredItem[slot].Clone(); + if (selectedRecipe == null || slot >= selectedRecipe.requiredItem.Length) + return new Item(); + + Item item = selectedRecipe.requiredItem[slot].Clone(); if (selectedRecipe.anyWood && item.type == ItemID.Wood) { item.SetNameOverride(Lang.misc[37].Value + " " + Lang.GetItemNameValue(ItemID.Wood)); @@ -598,11 +624,11 @@ private static void UpdateRecipeText() } reqObjText2.SetText(text); var item = selectedRecipe.createItem; - var headerText = selectedRecipe.createItem.Name; - var dps = CompareDps.GetDps(item); + var dps = CompareDps.GetDps(item); if (dps >= 1f) - headerText += " (" + dps.ToString("F0") + " DPS)"; - recipePanelHeader.SetText(headerText); + recipePanelHeader.SetText("DPS = " + dps.ToString("F0")); + else + recipePanelHeader.SetText(""); } } @@ -707,7 +733,7 @@ private static void UpdateCraftButton() } } - private static TEStorageHeart GetHeart() + private static TEStorageHeart GetHeart() { Player player = Main.player[Main.myPlayer]; StoragePlayer modPlayer = player.GetModPlayer(); @@ -735,7 +761,7 @@ public static void RefreshItems() { return; } - items.AddRange(ItemSorter.SortAndFilter(heart.GetStoredItems(), SortMode.Id, FilterMode.All, "", "")); + items.AddRange(ItemSorter.SortAndFilter(heart.GetStoredItems(), SortMode.Id, FilterMode.All, ModSearchBox.ModIndexAll, "")); AnalyzeIngredients(); InitLangStuff(); InitSortButtons(); @@ -746,20 +772,12 @@ public static void RefreshItems() RefreshStorageItems(); - if (_checkListMod == null) - _checkListMod = ModLoader.GetMod("ItemChecklist"); + HashSet foundItems; + HashSet hiddenRecipes; + HashSet craftedRecipes; + GetKnownItems(out foundItems, out hiddenRecipes, out craftedRecipes); - var foundItems = _checkListMod != null ? _checkListMod.Call("RequestFoundItems") as bool[] : null; - - StoragePlayer modPlayer = Main.player[Main.myPlayer].GetModPlayer(); - var hiddenRecipes = new HashSet(modPlayer.HiddenRecipes.Select(x => x.type)); - var craftedRecipes = new HashSet(modPlayer.CraftedRecipes.Select(x => x.type)); - - if (_productToRecipes == null) - { - var allRecipes = ItemSorter.GetRecipes(SortMode.Id, FilterMode.All, "", "").Where(x => x != null && x.createItem != null && x.createItem.type > 0).ToArray(); - _productToRecipes = allRecipes.GroupBy(x => x.createItem.type).ToDictionary(x => x.Key, x => x.ToList()); - } + EnsureProductToRecipesInited(); lock (threadLock) { @@ -776,12 +794,58 @@ public static void RefreshItems() } } - static Dictionary> _productToRecipes; + static HashSet GetKnownItems() + { + HashSet a, b, c; + GetKnownItems(out a, out b, out c); + a.UnionWith(b); + a.UnionWith(c); + return a; + } + + static void GetKnownItems(out HashSet foundItems, out HashSet hiddenRecipes, out HashSet craftedRecipes) + { + foundItems = new HashSet(RetrieveFoundItemsCheckList()); + + StoragePlayer modPlayer = ModPlayer; + hiddenRecipes = new HashSet(modPlayer.HiddenRecipes.Select(x => x.type)); + craftedRecipes = new HashSet(modPlayer.CraftedRecipes.Select(x => x.type)); + } + + static StoragePlayer ModPlayer { get { return Main.player[Main.myPlayer].GetModPlayer(); } } - /// + static IEnumerable RetrieveFoundItemsCheckList() + { + if (_checkListMod == null) + _checkListMod = ModLoader.GetMod("ItemChecklist"); + + var foundItems = _checkListMod != null ? _checkListMod.Call("RequestFoundItems") as bool[] : new bool[0]; + return foundItems.Select((v, type) => new { WasFound = v, type }).Where(x => x.WasFound).Select(x => x.type); + } + + static void EnsureProductToRecipesInited() + { + if (_productToRecipes == null) + { + var allRecipes = ItemSorter.GetRecipes(SortMode.Id, FilterMode.All, ModSearchBox.ModIndexAll, "").Where(x => x != null && x.createItem != null && x.createItem.type > 0).ToArray(); + _productToRecipes = allRecipes.GroupBy(x => x.createItem.type).ToDictionary(x => x.Key, x => x.ToList()); + } + } + + static Dictionary> _productToRecipes; + + /// + /// Checks all crafting tree until it finds already available ingredients + /// + static bool IsKnownRecursively(Recipe recipe, HashSet availableSet) + { + return IsKnownRecursively(recipe, availableSet, new HashSet()); + } + + /// /// Checks all crafting tree until it finds already available ingredients /// - static bool IsAvailableRecursively(Recipe recipe, HashSet availableSet, HashSet recursionTree) + static bool IsKnownRecursively(Recipe recipe, HashSet availableSet, HashSet recursionTree) { if (availableSet.Contains(recipe.createItem.type)) return true; for (int i = 0; i < Recipe.maxRequirements; i++) @@ -796,7 +860,7 @@ static bool IsAvailableRecursively(Recipe recipe, HashSet availableSet, Has { List ingredientRecipes; if (!_productToRecipes.TryGetValue(t, out ingredientRecipes)) return false; - if (ingredientRecipes.Count == 0 || ingredientRecipes.All(x => !IsAvailableRecursively(x, availableSet, recursionTree))) return false; + if (ingredientRecipes.Count == 0 || ingredientRecipes.All(x => !IsKnownRecursively(x, availableSet, recursionTree))) return false; } finally { @@ -816,7 +880,7 @@ private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craf { SortMode sortMode; FilterMode filterMode; - bool[] foundItems; + HashSet foundItems; lock (threadLock) { threadNeedsRestart = false; @@ -825,17 +889,15 @@ private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craf foundItems = threadCheckListFoundItems; } - if (foundItems == null) foundItems = new bool[0]; - var availableItemsMutable = new HashSet(hiddenRecipes .Concat(craftedRecipes) - .Concat(foundItems.Select((v, type) => new {WasFound = v, type}).Where(x => x.WasFound).Select(x => x.type))); + .Concat(foundItems)); var availableItemsOriginal = new HashSet(availableItemsMutable); var temp = new HashSet(); - var recipes = ItemSorter.GetRecipes(sortMode, filterMode, searchBar2.Text, searchBar.Text).Where(x => x != null) + var filteredRecipes = ItemSorter.GetRecipes(sortMode, filterMode, modSearchBox.ModIndex, searchBar.Text).Where(x => x != null) // only new recipes (not crafted previously) filter (new - button choice = 0) .Where(x => (recipeButtons.Choice != RecipeButtonsNewChoice) || !craftedRecipes.Contains(x.createItem.type)) // show only blacklisted recipes only if choice = 2, otherwise show all other @@ -843,14 +905,14 @@ private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craf // show only new items if selected .Where(x => (recipeButtons.Choice != RecipeButtonsNewChoice) || !availableItemsOriginal.Contains(x.createItem.type)) // hard check if this item can be crafted from available items and their recursive products - .Where(x => IsAvailableRecursively(x, availableItemsMutable, temp)); + .Where(x => IsKnownRecursively(x, availableItemsMutable, temp)); threadRecipes.Clear(); threadRecipeAvailable.Clear(); try { - threadRecipes.AddRange(recipes); - threadRecipeAvailable.AddRange(threadRecipes.Select(recipe => IsAvailable(recipe))); + threadRecipes.AddRange(filteredRecipes); + threadRecipeAvailable.AddRange(threadRecipes.Select(IsAvailable)); } catch (InvalidOperationException) { @@ -1192,9 +1254,8 @@ private static void HoverRecipe(int slot, ref int hoverSlot) { if (MouseClicked) { - selectedRecipe = recipes[slot]; - RefreshStorageItems(); - blockStorageItems.Clear(); + var recipe = recipes[slot]; + SetSelectedRecipe(recipe); } else if (RightMouseClicked) { @@ -1214,10 +1275,59 @@ private static void HoverRecipe(int slot, ref int hoverSlot) } } - private static void HoverItem(int slot, ref int hoverSlot) - { - hoverSlot = slot; - } + static void SetSelectedRecipe(Recipe recipe) + { + selectedRecipe = recipe; + RefreshStorageItems(); + blockStorageItems.Clear(); + } + + private static void HoverHeader(int slot, ref int hoverSlot) + { + hoverSlot = slot; + } + + private static void HoverItem(int slot, ref int hoverSlot) + { + if (selectedRecipe == null) + { + hoverSlot = slot; + return; + } + int visualSlot = slot; + slot += numColumns2 * (int)Math.Round(scrollBar2.ViewPosition); + var count = selectedRecipe.requiredItem.Select((x, i) => new { x, i }).First(x => x.x.type == 0).i + 1; + + if (slot < count) + { + // select ingredient recipe by right clicking + if (RightMouseClicked) + { + var item = selectedRecipe.requiredItem[slot]; + EnsureProductToRecipesInited(); + List itemRecipes; + if (_productToRecipes.TryGetValue(item.type, out itemRecipes)) + { + var knownItems = GetKnownItems(); + var dummy = new HashSet(); + + Recipe selected = null; + + foreach (var r in itemRecipes.Where(x => IsKnownRecursively(x, knownItems, dummy))) + { + if (selected == null) selected = r; + if (IsAvailable(r)) + { + selected = r; + break; + } + } + if (selected != null) SetSelectedRecipe(selected); + } + } + hoverSlot = visualSlot; + } + } private static void HoverStorage(int slot, ref int hoverSlot) { diff --git a/MagicStorage.cs b/MagicStorage.cs index bd18648e..8b3b5764 100644 --- a/MagicStorage.cs +++ b/MagicStorage.cs @@ -1,6 +1,8 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; +using System.Reflection; using Terraria; using Terraria.ID; using Terraria.ModLoader; @@ -166,8 +168,8 @@ private void AddTranslations() text = CreateTranslation("FilterVanity"); text.SetDefault("Filter Vanity Items"); AddTranslation(text); - - + + text = CreateTranslation("FilterPotions"); text.SetDefault("Filter Potions"); text.AddTranslation(GameCulture.Russian, "Фильтр (Зелья)"); @@ -241,11 +243,17 @@ private void AddTranslations() text.SetDefault("Sort by DPS"); AddTranslation(text); } - - public override void PostSetupContent() + + public override void PostSetupContent() { - - } + + var type = Assembly.GetAssembly(typeof(Mod)).GetType("Terraria.ModLoader.Mod"); + FieldInfo loadModsField = type.GetField("items", BindingFlags.Instance | BindingFlags.NonPublic); + + AllMods = ModLoader.GetLoadedMods().Where(x => ((Dictionary)loadModsField.GetValue(ModLoader.GetMod(x))).Count > 0).ToArray(); + } + + public string[] AllMods { get; private set; } public override void AddRecipeGroups() { diff --git a/MagicStorage.csproj b/MagicStorage.csproj index 1d848828..e1284cf2 100644 --- a/MagicStorage.csproj +++ b/MagicStorage.csproj @@ -106,6 +106,7 @@ + diff --git a/ModSearchBox.cs b/ModSearchBox.cs new file mode 100644 index 00000000..9298241b --- /dev/null +++ b/ModSearchBox.cs @@ -0,0 +1,91 @@ +using System; +using Microsoft.Win32.SafeHandles; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Input; +using Terraria.GameContent.UI.Elements; + +namespace MagicStorage +{ + public class ModSearchBox + { + UITextPanel _modButton; + public int ModIndex { get; private set; } = ModIndexAll; + public string ModName { get; private set; } + public Action OnChanged; + + public ModSearchBox(Action onChanged) + { + OnChanged = onChanged; + } + + public UIPanel Button => _modButton; + + public void InitLangStuff() + { + if (_modButton == null) + { + _modButton = new UITextPanel(MakeModButtonText(), 0.8f); + } + } + + void SetSearchMod(int index, bool silent) + { + if (ModIndex == index) return; + var allMods = MagicStorage.Instance.AllMods; + ModIndex = index; + if (_modButton != null) + _modButton.SetText(MakeModButtonText()); + ModName = index == -1 ? "" : ModName; + if (!silent) OnChanged?.Invoke(); + } + + public void Reset(bool silent) + { + SetSearchMod(ModIndexAll, silent); + } + + public const int ModIndexBaseGame = -2; + public const int ModIndexAll = -1; + + string MakeModButtonText() + { + if (ModIndex == -2) + return "All mods"; + else if (ModIndex == -1) + { + return "Terraria"; + } + else + return MagicStorage.Instance.AllMods[ModIndex]; + } + + public void Update(MouseState curMouse, MouseState oldMouse) + { + Rectangle dim = InterfaceHelper.GetFullRectangle(_modButton); + if (curMouse.X > dim.X && curMouse.X < dim.X + dim.Width && curMouse.Y > dim.Y && curMouse.Y < dim.Y + dim.Height) + { + _modButton.BackgroundColor = new Color(73, 94, 171); + var allMods = MagicStorage.Instance.AllMods; + int index = ModIndex; + if (curMouse.LeftButton == ButtonState.Pressed && oldMouse.LeftButton == ButtonState.Released) + { + index++; + if (index >= allMods.Length) + index = -2; + } + else if (curMouse.RightButton == ButtonState.Pressed && oldMouse.RightButton == ButtonState.Released) + { + index--; + if (index < -2) + index = allMods.Length - 1; + } + + SetSearchMod(index, false); + } + else + { + _modButton.BackgroundColor = new Color(63, 82, 151) * 0.7f; + } + } + } +} \ No newline at end of file diff --git a/Sorting/ItemSorter.cs b/Sorting/ItemSorter.cs index 18d59bac..91ac6b3c 100644 --- a/Sorting/ItemSorter.cs +++ b/Sorting/ItemSorter.cs @@ -7,20 +7,20 @@ namespace MagicStorage.Sorting { public static class ItemSorter { - public static IEnumerable SortAndFilter(IEnumerable items, SortMode sortMode, FilterMode filterMode, string modFilter, string nameFilter, int? takeCount = null) + public static IEnumerable SortAndFilter(IEnumerable items, SortMode sortMode, FilterMode filterMode, int modFilterIndex, string nameFilter, int? takeCount = null) { ItemFilter filter = MakeFilter(filterMode); - IEnumerable filteredItems = items.Where((item) => filter.Passes(item) && FilterName(item, modFilter, nameFilter)); + IEnumerable filteredItems = items.Where((item) => filter.Passes(item) && FilterName(item, nameFilter) && FilterMod(item, modFilterIndex)); if (takeCount != null) filteredItems = filteredItems.Take(takeCount.Value); var func = MakeSortFunction(sortMode); if (func == null) return filteredItems; return filteredItems.OrderBy(x => x, func); } - public static IEnumerable GetRecipes(SortMode sortMode, FilterMode filterMode, string modFilter, string nameFilter) + public static IEnumerable GetRecipes(SortMode sortMode, FilterMode filterMode, int modFilterIndex, string nameFilter) { var filter = MakeFilter(filterMode); - IEnumerable filteredRecipes = Main.recipe.Where((recipe, index) => index < Recipe.numRecipes && filter.Passes(recipe) && FilterName(recipe.createItem, modFilter, nameFilter)); + IEnumerable filteredRecipes = Main.recipe.Where((recipe, index) => index < Recipe.numRecipes && filter.Passes(recipe) && FilterName(recipe.createItem, nameFilter) && FilterMod(recipe.createItem, modFilterIndex)); var func = MakeSortFunction(sortMode); if (func == null) return filteredRecipes; return filteredRecipes.OrderBy(x => x.createItem, func); @@ -112,16 +112,24 @@ static ItemFilter MakeFilter(FilterMode filterMode) } return filter; - } - - private static bool FilterName(Item item, string modFilter, string filter) + } + + + static bool FilterName(Item item, string filter) + { + return item.Name.ToLowerInvariant().IndexOf(filter.ToLowerInvariant()) >= 0; + } + + static bool FilterMod(Item item, int modFilterIndex) { - string modName = "Terraria"; + if (modFilterIndex == ModSearchBox.ModIndexAll) return true; + var allMods = MagicStorage.Instance.AllMods; + int index = ModSearchBox.ModIndexBaseGame; if (item.modItem != null) - { - modName = item.modItem.mod.DisplayName; + { + index = Array.IndexOf(allMods, item.modItem.mod.Name); } - return modName.ToLowerInvariant().IndexOf(modFilter.ToLowerInvariant()) >= 0 && item.Name.ToLowerInvariant().IndexOf(filter.ToLowerInvariant()) >= 0; + return index == modFilterIndex; } } } diff --git a/StorageGUI.cs b/StorageGUI.cs index be676e35..58d0bef5 100644 --- a/StorageGUI.cs +++ b/StorageGUI.cs @@ -42,10 +42,11 @@ public static bool MouseClicked private static UIButtonChoice sortButtons; internal static UITextPanel depositButton; private static UIElement topBar2 = new UIElement(); - private static UIButtonChoice filterButtons; - internal static UISearchBar searchBar2; - - private static UISlotZone slotZone = new UISlotZone(HoverItemSlot, GetItem, inventoryScale); + private static UIButtonChoice filterButtons; + + public static readonly ModSearchBox modSearchBox = new ModSearchBox(RefreshItems); + + private static UISlotZone slotZone = new UISlotZone(HoverItemSlot, GetItem, inventoryScale); private static int slotFocus = -1; private static int rightClickTimer = 0; private const int startMaxRightClickTimer = 20; @@ -113,11 +114,13 @@ public static void Initialize() float filterButtonsRight = filterButtons.GetDimensions().Width + padding; topBar2.Append(filterButtons); - searchBar2.Left.Set(filterButtonsRight + padding, 0f); - searchBar2.Width.Set(-filterButtonsRight - 2 * padding, 1f); - searchBar2.Height.Set(0f, 1f); - topBar2.Append(searchBar2); - + + modSearchBox.Button.Left.Set(filterButtonsRight + padding, 0f); + modSearchBox.Button.Width.Set(-filterButtonsRight - 2 * padding, 1f); + modSearchBox.Button.Height.Set(0f, 1f); + modSearchBox.Button.OverflowHidden = true; + topBar2.Append(modSearchBox.Button); + slotZone.Width.Set(0f, 1f); slotZone.Top.Set(76f, 0f); slotZone.Height.Set(-116f, 1f); @@ -174,10 +177,7 @@ private static void InitLangStuff() { searchBar = new UISearchBar(Language.GetText("Mods.MagicStorage.SearchName")); } - if (searchBar2 == null) - { - searchBar2 = new UISearchBar(Language.GetText("Mods.MagicStorage.SearchMod")); - } + modSearchBox.InitLangStuff(); if (capacityText == null) { capacityText = new UIText("Items"); @@ -213,6 +213,7 @@ public static void Update(GameTime gameTime) basePanel.Update(gameTime); UpdateScrollBar(); UpdateDepositButton(); + modSearchBox.Update(curMouse, oldMouse); } else { @@ -324,10 +325,10 @@ public static void RefreshItems() var toFilter = heart.UniqueItemsPutHistory.Reverse().Where(x => stored.ContainsKey(x.type)).Select(x => stored[x.type]); itemsLocal = ItemSorter.SortAndFilter(toFilter, sortMode == SortMode.Default ? SortMode.AsIs : sortMode, - FilterMode.All, searchBar2.Text, searchBar.Text, 30); + FilterMode.All, modSearchBox.ModIndex, searchBar.Text, 30); } else - itemsLocal = ItemSorter.SortAndFilter(heart.GetStoredItems(), sortMode, filterMode, searchBar2.Text, searchBar.Text); + itemsLocal = ItemSorter.SortAndFilter(heart.GetStoredItems(), sortMode, filterMode, modSearchBox.ModIndex, searchBar.Text); items.AddRange(itemsLocal); for (int k = 0; k < items.Count; k++) { diff --git a/StoragePlayer.cs b/StoragePlayer.cs index 43f05a5a..ee80fea6 100644 --- a/StoragePlayer.cs +++ b/StoragePlayer.cs @@ -110,18 +110,12 @@ public void CloseStorage() { StorageGUI.searchBar.Reset(); } - if (StorageGUI.searchBar2 != null) - { - StorageGUI.searchBar2.Reset(); - } if (CraftingGUI.searchBar != null) { CraftingGUI.searchBar.Reset(); } - if (CraftingGUI.searchBar2 != null) - { - CraftingGUI.searchBar2.Reset(); - } + CraftingGUI.modSearchBox.Reset(true); + StorageGUI.modSearchBox.Reset(true); } public Point16 ViewingStorage() diff --git a/build.txt b/build.txt index ab94e496..4536a0f5 100644 --- a/build.txt +++ b/build.txt @@ -6,4 +6,5 @@ hideCode = false hideResources = false includeSource = true includePDB = true +languageVersion = 6 buildIgnore = OldArt\*, .git\*, obj\* \ No newline at end of file From bafd8f9a54c6e31d44b6eeea9131a054c33e606f Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 12 Aug 2018 12:08:43 +0300 Subject: [PATCH 20/80] authors and version --- build.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.txt b/build.txt index 4536a0f5..9553df57 100644 --- a/build.txt +++ b/build.txt @@ -1,5 +1,5 @@ -author = blushiemagic -version = 0.4.3.1 +author = blushiemagic and wvlad +version = 0.4.100.0 displayName = Magic Storage homepage = https://forums.terraria.org/index.php?threads/magic-storage.56294/ hideCode = false From fa082889f76cc6effc9e2f56c5fb0bde95a16782 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 12 Aug 2018 12:21:02 +0300 Subject: [PATCH 21/80] more fixes --- ModSearchBox.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/ModSearchBox.cs b/ModSearchBox.cs index 9298241b..4eefbd7e 100644 --- a/ModSearchBox.cs +++ b/ModSearchBox.cs @@ -31,11 +31,11 @@ public void InitLangStuff() void SetSearchMod(int index, bool silent) { if (ModIndex == index) return; - var allMods = MagicStorage.Instance.AllMods; ModIndex = index; if (_modButton != null) _modButton.SetText(MakeModButtonText()); - ModName = index == -1 ? "" : ModName; + ModName = ""; + if (index > -1) ModName = MagicStorage.Instance.AllMods[index]; if (!silent) OnChanged?.Invoke(); } @@ -44,14 +44,14 @@ public void Reset(bool silent) SetSearchMod(ModIndexAll, silent); } - public const int ModIndexBaseGame = -2; - public const int ModIndexAll = -1; + public const int ModIndexBaseGame = -1; + public const int ModIndexAll = -2; string MakeModButtonText() { - if (ModIndex == -2) + if (ModIndex == ModIndexAll) return "All mods"; - else if (ModIndex == -1) + else if (ModIndex == ModIndexBaseGame) { return "Terraria"; } @@ -71,7 +71,7 @@ public void Update(MouseState curMouse, MouseState oldMouse) { index++; if (index >= allMods.Length) - index = -2; + index = ModIndexAll; } else if (curMouse.RightButton == ButtonState.Pressed && oldMouse.RightButton == ButtonState.Released) { From 9f80d29067506d4090f59b1e496e2dc52cf270fc Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 12 Aug 2018 14:03:26 +0300 Subject: [PATCH 22/80] and more filtering and search box input fixes --- Sorting/DefaultSorting.cs | 14 +++++++------- Sorting/ItemFilter.cs | 20 +++++++++++--------- UISearchBar.cs | 13 +++++++++---- 3 files changed, 27 insertions(+), 20 deletions(-) diff --git a/Sorting/DefaultSorting.cs b/Sorting/DefaultSorting.cs index ae8559e1..e9b92fd8 100644 --- a/Sorting/DefaultSorting.cs +++ b/Sorting/DefaultSorting.cs @@ -185,32 +185,32 @@ private static bool Grapple(Item item) return Main.projHook[item.shoot]; } - private static bool Mount(Item item) + public static bool Mount(Item item) { return item.mountType != -1 && !MountID.Sets.Cart[item.mountType]; } - private static bool Cart(Item item) + public static bool Cart(Item item) { return item.mountType != -1 && MountID.Sets.Cart[item.mountType]; } - private static bool LightPet(Item item) + public static bool LightPet(Item item) { return item.buffType > 0 && Main.lightPet[item.buffType]; } - private static bool VanityPet(Item item) + public static bool VanityPet(Item item) { return item.buffType > 0 && Main.vanityPet[item.buffType]; } - private static bool Dye(Item item) + public static bool Dye(Item item) { return item.dye > 0; } - private static bool HairDye(Item item) + public static bool HairDye(Item item) { return item.hairDye >= 0; } @@ -235,7 +235,7 @@ private static bool BuffPotion(Item item) return item.consumable && item.buffType > 0; } - private static bool BossSpawn(Item item) + public static bool BossSpawn(Item item) { return ItemID.Sets.SortingPriorityBossSpawns[item.type] >= 0; } diff --git a/Sorting/ItemFilter.cs b/Sorting/ItemFilter.cs index db863452..ae96c96a 100644 --- a/Sorting/ItemFilter.cs +++ b/Sorting/ItemFilter.cs @@ -2,6 +2,8 @@ using System.Collections.Generic; using MagicStorage.Components; using Terraria; +using Terraria.ID; +using Terraria.UI; namespace MagicStorage.Sorting { @@ -35,7 +37,7 @@ public class FilterWeaponMelee : ItemFilter { public override bool Passes(Item item) { - return item.melee && item.pick == 0 && item.axe == 0 && item.hammer == 0 && item.damage > 0; + return (item.melee || (item.thrown && !item.consumable)) && item.pick == 0 && item.axe == 0 && item.hammer == 0 && item.damage > 0; } } @@ -53,7 +55,7 @@ public class FilterWeaponMagic : ItemFilter { public override bool Passes(Item item) { - return item.magic && item.damage > 0; + return item.magic && (item.damage > 0 || (item.healLife > 0 && item.mana > 0)) && !item.consumable; } } @@ -61,7 +63,7 @@ public class FilterWeaponSummon : ItemFilter { public override bool Passes(Item item) { - return item.summon; + return item.summon || SortClassList.BossSpawn(item) || SortClassList.Cart(item) || SortClassList.LightPet(item) || SortClassList.Mount(item); } } @@ -77,7 +79,7 @@ public class FilterAmmo : ItemFilter { public override bool Passes(Item item) { - return item.ammo > 0 && item.damage > 0; + return item.ammo > 0 && item.damage > 0 && item.ammo != AmmoID.Coin; } } @@ -85,7 +87,7 @@ public class FilterVanity : ItemFilter { public override bool Passes(Item item) { - return item.vanity; + return item.vanity || SortClassList.Dye(item) || SortClassList.HairDye(item) || SortClassList.VanityPet(item); } } @@ -100,9 +102,9 @@ public override bool Passes(Item item) public class FilterWeapon : ItemFilter { public override bool Passes(Item item) - { - return !(item.consumable && item.thrown) && item.damage > 0 && item.pick == 0 && item.axe == 0 && item.hammer == 0; - } + { + return !(item.consumable && item.thrown) && (item.damage > 0 || (item.magic && item.healLife > 0 && item.mana > 0)) && item.pick == 0 && item.axe == 0 && item.hammer == 0; + } } public class FilterPickaxe : ItemFilter @@ -157,7 +159,7 @@ public class FilterPotion : ItemFilter { public override bool Passes(Item item) { - return item.consumable && (item.healLife > 0 || item.healMana > 0 || item.buffType > 0 || item.potion); + return item.consumable && (item.healLife > 0 || item.healMana > 0 || item.buffType > 0 || item.potion || item.Name.ToLowerInvariant().Contains("potion") || item.Name.ToLowerInvariant().Contains("elixit")); } } diff --git a/UISearchBar.cs b/UISearchBar.cs index 615fe81e..ceb61f05 100644 --- a/UISearchBar.cs +++ b/UISearchBar.cs @@ -88,11 +88,16 @@ public override void Update(GameTime gameTime) { PlayerInput.WritingText = true; Main.instance.HandleIME(); - string newString = Main.GetInputText(text); - if (!newString.Equals(text)) + string prev = text; + if (cursorPosition < text.Length && text.Length > 0) + prev = prev.Remove(cursorPosition); + string newString = Main.GetInputText(prev); + if (!newString.Equals(prev)) { - text = newString; - cursorPosition = text.Length; + int newStringLength = newString.Length; + if (prev != text) newString += text.Substring(cursorPosition); + text = newString; + cursorPosition = newStringLength; StorageGUI.RefreshItems(); } if (KeyTyped(Keys.Delete)) From 121cebd8b4b21c7d1982aadbad6a64bb7077baa7 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 12 Aug 2018 16:32:00 +0300 Subject: [PATCH 23/80] support for accepted groups when searching for known recipes, 30 recent items expanded to 100, if nothing found with search some filters are toggled off, more fixes --- CraftingGUI.cs | 133 +++++++++++++++++++++++++++++++----------- Sorting/ItemFilter.cs | 15 ++++- StorageGUI.cs | 4 +- UISearchBar.cs | 20 ++++--- 4 files changed, 127 insertions(+), 45 deletions(-) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 0be48688..7f5a26ae 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -330,7 +330,7 @@ private static void InitLangStuff() { if (searchBar == null) { - searchBar = new UISearchBar(Language.GetText("Mods.MagicStorage.SearchName")); + searchBar = new UISearchBar(Language.GetText("Mods.MagicStorage.SearchName"), RefreshItems); } if (stationText == null) { @@ -852,27 +852,52 @@ static bool IsKnownRecursively(Recipe recipe, HashSet availableSet, HashSet { var t = recipe.requiredItem[i].type; if (t <= 0) continue; - if (!availableSet.Contains(t)) - { - if (recursionTree.Contains(t)) return false; - recursionTree.Add(t); - try - { - List ingredientRecipes; - if (!_productToRecipes.TryGetValue(t, out ingredientRecipes)) return false; - if (ingredientRecipes.Count == 0 || ingredientRecipes.All(x => !IsKnownRecursively(x, availableSet, recursionTree))) return false; - } - finally - { - recursionTree.Remove(t); - } - } + if (IsKnownRecursively_CheckIngredient(availableSet, recursionTree, t)) continue; + if (IsKnownRecursively_CheckAcceptedGroupsForIngredient(recipe, availableSet, recursionTree, t)) continue; + return false; } availableSet.Add(recipe.createItem.type); return true; } - private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craftedRecipes) + static bool IsKnownRecursively_CheckAcceptedGroupsForIngredient(Recipe recipe, HashSet availableSet, HashSet recursionTree, int t) + { + foreach (var g in recipe.acceptedGroups.Select(j => RecipeGroup.recipeGroups[j])) + { + if (g.ContainsItem(t)) + { + foreach (var groupItemType in g.ValidItems) + { + if (groupItemType != t && IsKnownRecursively_CheckIngredient(availableSet, recursionTree, groupItemType)) + { + return true; + } + } + } + } + return false; + } + + static bool IsKnownRecursively_CheckIngredient(HashSet availableSet, HashSet recursionTree, int t) + { + if (availableSet.Contains(t)) return true; + if (recursionTree.Contains(t)) return false; + recursionTree.Add(t); + try + { + List ingredientRecipes; + if (!_productToRecipes.TryGetValue(t, out ingredientRecipes)) return false; + if (ingredientRecipes.Count == 0 || ingredientRecipes.All(x => !IsKnownRecursively(x, availableSet, recursionTree))) return false; + } + finally + { + recursionTree.Remove(t); + } + + return true; + } + + private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craftedRecipes) { while (true) { @@ -897,29 +922,69 @@ private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craf var temp = new HashSet(); - var filteredRecipes = ItemSorter.GetRecipes(sortMode, filterMode, modSearchBox.ModIndex, searchBar.Text).Where(x => x != null) - // only new recipes (not crafted previously) filter (new - button choice = 0) - .Where(x => (recipeButtons.Choice != RecipeButtonsNewChoice) || !craftedRecipes.Contains(x.createItem.type)) - // show only blacklisted recipes only if choice = 2, otherwise show all other - .Where(x => (recipeButtons.Choice == RecipeButtonsBlacklistChoice) == hiddenRecipes.Contains(x.createItem.type)) - // show only new items if selected - .Where(x => (recipeButtons.Choice != RecipeButtonsNewChoice) || !availableItemsOriginal.Contains(x.createItem.type)) - // hard check if this item can be crafted from available items and their recursive products - .Where(x => IsKnownRecursively(x, availableItemsMutable, temp)); - - threadRecipes.Clear(); - threadRecipeAvailable.Clear(); - try + var modFilterIndex = modSearchBox.ModIndex; + + IEnumerable filteredRecipes = null; + + Action doFiltering = () => + { + filteredRecipes = ItemSorter.GetRecipes(sortMode, filterMode, modFilterIndex, searchBar.Text).Where(x => x != null) + // only new recipes (not crafted previously) filter (new - button choice = 0) + .Where(x => (recipeButtons.Choice != RecipeButtonsNewChoice) || !craftedRecipes.Contains(x.createItem.type)) + // show only blacklisted recipes only if choice = 2, otherwise show all other + .Where(x => (recipeButtons.Choice == RecipeButtonsBlacklistChoice) == hiddenRecipes.Contains(x.createItem.type)) + // show only new items if selected + .Where(x => (recipeButtons.Choice != RecipeButtonsNewChoice) || !availableItemsOriginal.Contains(x.createItem.type)) + // hard check if this item can be crafted from available items and their recursive products + .Where(x => IsKnownRecursively(x, availableItemsMutable, temp)); + + threadRecipes.Clear(); + threadRecipeAvailable.Clear(); + try + { + threadRecipes.AddRange(filteredRecipes); + threadRecipeAvailable.AddRange(threadRecipes.Select(IsAvailable)); + } + catch (InvalidOperationException) + { + } + catch (KeyNotFoundException) + { + } + }; + + doFiltering(); + + // now if nothing found we disable filters one by one + + if (threadRecipes.Count == 0 && searchBar.Text.Length > 0) { - threadRecipes.AddRange(filteredRecipes); - threadRecipeAvailable.AddRange(threadRecipes.Select(IsAvailable)); + // search hidden recipes too + hiddenRecipes = new HashSet(); + doFiltering(); } - catch (InvalidOperationException) + + if (threadRecipes.Count == 0 && recipeButtons.Choice == RecipeButtonsNewChoice) { + // search old recipes too + craftedRecipes = new HashSet(); + doFiltering(); } - catch (KeyNotFoundException) + + if (threadRecipes.Count == 0 && filterMode != FilterMode.All) { + // any category + filterMode = FilterMode.All; + doFiltering(); } + + if (threadRecipes.Count == 0 && modFilterIndex != ModSearchBox.ModIndexAll) + { + // search all mods + modFilterIndex = ModSearchBox.ModIndexAll; + doFiltering(); + } + lock (recipeLock) { nextRecipes = new List(); diff --git a/Sorting/ItemFilter.cs b/Sorting/ItemFilter.cs index ae96c96a..a2cb2147 100644 --- a/Sorting/ItemFilter.cs +++ b/Sorting/ItemFilter.cs @@ -63,6 +63,7 @@ public class FilterWeaponSummon : ItemFilter { public override bool Passes(Item item) { + if (item.type == 109 || item.type == 29) return false; // mana or heart crystal return item.summon || SortClassList.BossSpawn(item) || SortClassList.Cart(item) || SortClassList.LightPet(item) || SortClassList.Mount(item); } } @@ -71,7 +72,17 @@ public class FilterWeaponThrown : ItemFilter { public override bool Passes(Item item) { - return item.thrown && item.consumable && item.damage > 0; + switch (item.type) + { + case 167: // dynamite + case 3547: + case 2896: + case 166: // bomb + case 235: + case 3115: + return true; + } + return (item.thrown && item.damage > 0) || (item.consumable && item.Name.ToLowerInvariant().EndsWith(" coating")); } } @@ -159,7 +170,7 @@ public class FilterPotion : ItemFilter { public override bool Passes(Item item) { - return item.consumable && (item.healLife > 0 || item.healMana > 0 || item.buffType > 0 || item.potion || item.Name.ToLowerInvariant().Contains("potion") || item.Name.ToLowerInvariant().Contains("elixit")); + return item.consumable && (item.healLife > 0 || item.healMana > 0 || item.buffType > 0 || item.potion || item.Name.ToLowerInvariant().Contains("potion") || item.Name.ToLowerInvariant().Contains("elixir")); } } diff --git a/StorageGUI.cs b/StorageGUI.cs index 58d0bef5..db016fcf 100644 --- a/StorageGUI.cs +++ b/StorageGUI.cs @@ -175,7 +175,7 @@ private static void InitLangStuff() } if (searchBar == null) { - searchBar = new UISearchBar(Language.GetText("Mods.MagicStorage.SearchName")); + searchBar = new UISearchBar(Language.GetText("Mods.MagicStorage.SearchName"), RefreshItems); } modSearchBox.InitLangStuff(); if (capacityText == null) @@ -325,7 +325,7 @@ public static void RefreshItems() var toFilter = heart.UniqueItemsPutHistory.Reverse().Where(x => stored.ContainsKey(x.type)).Select(x => stored[x.type]); itemsLocal = ItemSorter.SortAndFilter(toFilter, sortMode == SortMode.Default ? SortMode.AsIs : sortMode, - FilterMode.All, modSearchBox.ModIndex, searchBar.Text, 30); + FilterMode.All, modSearchBox.ModIndex, searchBar.Text, 100); } else itemsLocal = ItemSorter.SortAndFilter(heart.GetStoredItems(), sortMode, filterMode, modSearchBox.ModIndex, searchBar.Text); diff --git a/UISearchBar.cs b/UISearchBar.cs index ceb61f05..1163f149 100644 --- a/UISearchBar.cs +++ b/UISearchBar.cs @@ -18,7 +18,8 @@ public class UISearchBar : UIElement private const int padding = 4; private LocalizedText defaultText = Language.GetText("Mods.MagicStorage.Search"); - private string text = string.Empty; + readonly Action _clearedEvent; + private string text = string.Empty; private int cursorPosition = 0; private bool hasFocus = false; private int cursorTimer = 0; @@ -29,9 +30,10 @@ public UISearchBar() searchBars.Add(this); } - public UISearchBar(LocalizedText defaultText) : this() + public UISearchBar(LocalizedText defaultText, Action clearedEvent) : this() { - this.defaultText = defaultText; + this.defaultText = defaultText; + _clearedEvent = clearedEvent; } public string Text @@ -79,9 +81,13 @@ public override void Update(GameTime gameTime) CheckBlockInput(); } else if (StorageGUI.curMouse.RightButton == ButtonState.Pressed && StorageGUI.oldMouse.RightButton == ButtonState.Released && mouseOver) - { - text = string.Empty; - cursorPosition = 0; + { + if (text.Length > 0) + { + text = string.Empty; + cursorPosition = 0; + _clearedEvent?.Invoke(); + } } if (hasFocus) @@ -102,7 +108,7 @@ public override void Update(GameTime gameTime) } if (KeyTyped(Keys.Delete)) { - if (text.Length > 0 && cursorPosition < text.Length - 1) + if (text.Length > 0 && cursorPosition < text.Length) text = text.Remove(cursorPosition, 1); } if (KeyTyped(Keys.Left)) From 2384e656b82523fd84036bee6f850eba938b0734 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Mon, 13 Aug 2018 01:49:53 +0300 Subject: [PATCH 24/80] magic filter fix --- Sorting/ItemFilter.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sorting/ItemFilter.cs b/Sorting/ItemFilter.cs index a2cb2147..8d674a32 100644 --- a/Sorting/ItemFilter.cs +++ b/Sorting/ItemFilter.cs @@ -55,7 +55,7 @@ public class FilterWeaponMagic : ItemFilter { public override bool Passes(Item item) { - return item.magic && (item.damage > 0 || (item.healLife > 0 && item.mana > 0)) && !item.consumable; + return (item.magic || item.mana > 0) && !item.summon && !item.consumable; } } From 266e0e3429c7d40c2cc03ff8d13d71e670dc69dc Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Mon, 13 Aug 2018 01:51:11 +0300 Subject: [PATCH 25/80] fixed disabling filters when searching with no results --- CraftingGUI.cs | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 7f5a26ae..993d3ad9 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -918,7 +918,7 @@ private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craf .Concat(craftedRecipes) .Concat(foundItems)); - var availableItemsOriginal = new HashSet(availableItemsMutable); + var notNewItems = new HashSet(availableItemsMutable); var temp = new HashSet(); @@ -929,12 +929,10 @@ private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craf Action doFiltering = () => { filteredRecipes = ItemSorter.GetRecipes(sortMode, filterMode, modFilterIndex, searchBar.Text).Where(x => x != null) - // only new recipes (not crafted previously) filter (new - button choice = 0) - .Where(x => (recipeButtons.Choice != RecipeButtonsNewChoice) || !craftedRecipes.Contains(x.createItem.type)) // show only blacklisted recipes only if choice = 2, otherwise show all other .Where(x => (recipeButtons.Choice == RecipeButtonsBlacklistChoice) == hiddenRecipes.Contains(x.createItem.type)) // show only new items if selected - .Where(x => (recipeButtons.Choice != RecipeButtonsNewChoice) || !availableItemsOriginal.Contains(x.createItem.type)) + .Where(x => (recipeButtons.Choice != RecipeButtonsNewChoice) || !notNewItems.Contains(x.createItem.type)) // hard check if this item can be crafted from available items and their recursive products .Where(x => IsKnownRecursively(x, availableItemsMutable, temp)); @@ -957,17 +955,17 @@ private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craf // now if nothing found we disable filters one by one - if (threadRecipes.Count == 0 && searchBar.Text.Length > 0) + if (threadRecipes.Count == 0 && recipeButtons.Choice == RecipeButtonsNewChoice) { - // search hidden recipes too - hiddenRecipes = new HashSet(); + // search old recipes too + notNewItems = new HashSet(); doFiltering(); } - if (threadRecipes.Count == 0 && recipeButtons.Choice == RecipeButtonsNewChoice) + if (threadRecipes.Count == 0 && searchBar.Text.Length > 0) { - // search old recipes too - craftedRecipes = new HashSet(); + // search hidden recipes too + hiddenRecipes = new HashSet(); doFiltering(); } From be0ea9263e1b181cda0cf705be223f9c463f04fa Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Mon, 13 Aug 2018 01:53:36 +0300 Subject: [PATCH 26/80] item types set more compact save --- ItemTypeOrderedSet.cs | 57 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 52 insertions(+), 5 deletions(-) diff --git a/ItemTypeOrderedSet.cs b/ItemTypeOrderedSet.cs index d7635fd8..21770db1 100644 --- a/ItemTypeOrderedSet.cs +++ b/ItemTypeOrderedSet.cs @@ -21,24 +21,49 @@ public ItemTypeOrderedSet(string name) public bool Add(Item item) { + return Add(item.type); + } + + public bool Add(int type) + { + var item = new Item(); + item.SetDefaults(type); if (_set.Add(item.type)) { _items.Add(item); return true; } + return false; } + public bool Contains(int type) + { + return _set.Contains(type); + } + + public bool Contains(Item item) + { + return _set.Contains(item.type); + } + public bool Remove(Item item) { - if (_set.Remove(item.type)) + var type = item.type; + return Remove(type); + } + + public bool Remove(int type) + { + if (_set.Remove(type)) { - _items.RemoveAll(x => x.type == item.type); + _items.RemoveAll(x => x.type == type); return true; } + return false; } - + public bool RemoveAt(int index) { var item = _items[index]; @@ -47,18 +72,40 @@ public bool RemoveAt(int index) _items.RemoveAt(index); return true; } + return false; } + const string Suffix = "~v2"; + public void Save(TagCompound c) { - c.Add(_name, _items.Select(ItemIO.Save).ToList()); + c.Add(_name + Suffix, _items.Select(x => (int) x.type).ToList()); } public void Load(TagCompound tag) { var list = tag.GetList(_name); - _items = list != null ? list.Select(ItemIO.Load).ToList() : new List(); + if (list != null && list.Count > 0) + _items = list.Select(ItemIO.Load).ToList(); + else + { + var listV2 = tag.GetList(_name + Suffix); + if (listV2 != null) + { + _items = listV2 + .Select(x => + { + var item = new Item(); + item.SetDefaults(x); + item.type = x; + return item; + }).ToList(); + } + else + _items = new List(); + } + _set = new HashSet(_items.Select(x => x.type)); } } From 8da56a0ec143784e64ecd8d762125c0cb025e740 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Mon, 13 Aug 2018 02:32:49 +0300 Subject: [PATCH 27/80] Restock button, favorites in storage (alt+click), toggle to show only favorited, new items are shown with "shinyAndNew" --- Components/TEAbstractStorageUnit.cs | 2 +- Components/TECreativeStorageUnit.cs | 2 +- Components/TEStorageHeart.cs | 19 ++-- Components/TEStorageUnit.cs | 18 ++-- CraftingGUI.cs | 10 +- GUIHelpers.cs | 11 ++- MagicStorage.cs | 10 +- MagicStorage.csproj | 1 + NetHelper.cs | 8 +- StorageGUI.cs | 139 +++++++++++++++++++++------- UIButtonChoice.cs | 20 ++-- UIToggleButton.cs | 92 ++++++++++++++++++ 12 files changed, 258 insertions(+), 74 deletions(-) create mode 100644 UIToggleButton.cs diff --git a/Components/TEAbstractStorageUnit.cs b/Components/TEAbstractStorageUnit.cs index d5dc7f85..67227d67 100644 --- a/Components/TEAbstractStorageUnit.cs +++ b/Components/TEAbstractStorageUnit.cs @@ -62,7 +62,7 @@ public TEStorageHeart GetHeart() public abstract void DepositItem(Item toDeposit, bool locked = false); - public abstract Item TryWithdraw(Item lookFor, bool locked = false); + public abstract Item TryWithdraw(Item lookFor, bool locked = false, bool keepOneIfFavorite = false); public override TagCompound Save() { diff --git a/Components/TECreativeStorageUnit.cs b/Components/TECreativeStorageUnit.cs index f9f503b9..af2fccf9 100644 --- a/Components/TECreativeStorageUnit.cs +++ b/Components/TECreativeStorageUnit.cs @@ -43,7 +43,7 @@ public override void DepositItem(Item toDeposit, bool locked = false) { } - public override Item TryWithdraw(Item lookFor, bool locked = false) + public override Item TryWithdraw(Item lookFor, bool locked = false, bool keepOneIfFavorite = false) { if (Inactive) { diff --git a/Components/TEStorageHeart.cs b/Components/TEStorageHeart.cs index d57e2fd5..a5c3403e 100644 --- a/Components/TEStorageHeart.cs +++ b/Components/TEStorageHeart.cs @@ -268,7 +268,7 @@ public void DepositItem(Item toDeposit) int oldStack = toDeposit.stack; try { - var remember = toDeposit.Clone(); + var remember = toDeposit.type; foreach (TEAbstractStorageUnit storageUnit in GetStorageUnits()) { if (!storageUnit.Inactive && storageUnit.HasSpaceInStackFor(toDeposit, true)) @@ -280,18 +280,21 @@ public void DepositItem(Item toDeposit) } } } + var prevNewAndShiny = toDeposit.newAndShiny; + toDeposit.newAndShiny = !_uniqueItemsPutHistory.Contains(toDeposit); foreach (TEAbstractStorageUnit storageUnit in GetStorageUnits()) { if (!storageUnit.Inactive && !storageUnit.IsFull) { - storageUnit.DepositItem(toDeposit, true); - if (toDeposit.IsAir) - { + storageUnit.DepositItem(toDeposit, true); + if (toDeposit.IsAir) + { _uniqueItemsPutHistory.Add(remember); - return; - } + return; + } } } + toDeposit.newAndShiny = prevNewAndShiny; } finally { @@ -306,7 +309,7 @@ public void DepositItem(Item toDeposit) } } - public Item TryWithdraw(Item lookFor) + public Item TryWithdraw(Item lookFor, bool keepOneIfFavorite) { if (Main.netMode == 1) { @@ -323,7 +326,7 @@ public Item TryWithdraw(Item lookFor) { if (storageUnit.HasItem(lookFor, true)) { - Item withdrawn = storageUnit.TryWithdraw(lookFor, true); + Item withdrawn = storageUnit.TryWithdraw(lookFor, true, keepOneIfFavorite); if (!withdrawn.IsAir) { if (result.IsAir) diff --git a/Components/TEStorageUnit.cs b/Components/TEStorageUnit.cs index b20d34d7..9a934b4c 100644 --- a/Components/TEStorageUnit.cs +++ b/Components/TEStorageUnit.cs @@ -156,7 +156,11 @@ public override void DepositItem(Item toDeposit, bool locked = false) { newStack = item.maxStack; } - item.stack = newStack; + item.stack = newStack; + + if (toDeposit.favorited) item.favorited = true; + if (toDeposit.newAndShiny) item.newAndShiny = true; + hasChange = true; toDeposit.stack = total - newStack; if (toDeposit.stack <= 0) @@ -170,8 +174,6 @@ public override void DepositItem(Item toDeposit, bool locked = false) if (!finished && !IsFull) { Item item = toDeposit.Clone(); - item.newAndShiny = false; - item.favorited = false; items.Add(item); toDeposit.SetDefaults(0, true); hasChange = true; @@ -195,7 +197,7 @@ public override void DepositItem(Item toDeposit, bool locked = false) } } - public override Item TryWithdraw(Item lookFor, bool locked = false) + public override Item TryWithdraw(Item lookFor, bool locked = false, bool keepOneIfFavorite = false) { if (Main.netMode == 1 && !receiving) { @@ -215,7 +217,10 @@ public override Item TryWithdraw(Item lookFor, bool locked = false) Item item = items[k]; if (ItemData.Matches(lookFor, item)) { - int withdraw = Math.Min(lookFor.stack, item.stack); + int maxToTake = item.stack; + if (item.stack > 0 && item.favorited && keepOneIfFavorite) + maxToTake -= 1; + int withdraw = Math.Min(lookFor.stack, maxToTake); item.stack -= withdraw; if (item.stack <= 0) { @@ -606,7 +611,8 @@ protected override void SendData(BinaryWriter writer, TEStorageUnit unit) protected override bool ReceiveData(BinaryReader reader, TEStorageUnit unit) { - unit.TryWithdraw(ItemIO.Receive(reader, true, false)); + bool keepOneIfFavorite = reader.ReadBoolean(); + unit.TryWithdraw(ItemIO.Receive(reader, true, false), keepOneIfFavorite: keepOneIfFavorite); return true; } } diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 993d3ad9..e6250319 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -375,7 +375,7 @@ private static void InitSortButtons() { if (sortButtons == null) { - sortButtons = GUIHelpers.MakeSortButtons(); + sortButtons = GUIHelpers.MakeSortButtons(CraftingGUI.RefreshItems); } } @@ -383,7 +383,7 @@ private static void InitRecipeButtons() { if (recipeButtons == null) { - recipeButtons = new UIButtonChoice(new Texture2D[] + recipeButtons = new UIButtonChoice(CraftingGUI.RefreshItems, new Texture2D[] { MagicStorage.Instance.GetTexture("RecipeAvailable"), MagicStorage.Instance.GetTexture("RecipeAll"), @@ -402,7 +402,7 @@ private static void InitFilterButtons() { if (filterButtons == null) { - filterButtons = GUIHelpers.MakeFilterButtons(false); + filterButtons = GUIHelpers.MakeFilterButtons(false, CraftingGUI.RefreshItems); } } @@ -1619,7 +1619,7 @@ internal static List DoCraft(TEStorageHeart heart, List toWithdraw, List items = new List(); foreach (Item tryWithdraw in toWithdraw) { - Item withdrawn = heart.TryWithdraw(tryWithdraw); + Item withdrawn = heart.TryWithdraw(tryWithdraw, false); if (!withdrawn.IsAir) { items.Add(withdrawn); @@ -1673,7 +1673,7 @@ private static Item DoWithdrawResult(Item item, bool toInventory = false) TEStorageHeart heart = GetHeart(); if (Main.netMode == 0) { - return heart.TryWithdraw(item); + return heart.TryWithdraw(item, false); } else { diff --git a/GUIHelpers.cs b/GUIHelpers.cs index 58dfad09..9e5fd142 100644 --- a/GUIHelpers.cs +++ b/GUIHelpers.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.Localization; @@ -8,9 +9,9 @@ namespace MagicStorage public class GUIHelpers { - public static UIButtonChoice MakeSortButtons() + public static UIButtonChoice MakeSortButtons(Action onChanged) { - return new UIButtonChoice(new Texture2D[] + return new UIButtonChoice(onChanged, new Texture2D[] { Main.inventorySortTexture[0], MagicStorage.Instance.GetTexture("SortID"), @@ -28,7 +29,7 @@ public static UIButtonChoice MakeSortButtons() }); } - public static UIButtonChoice MakeFilterButtons(bool withHistory) + public static UIButtonChoice MakeFilterButtons(bool withHistory, Action onChanged) { var textures = new List { @@ -69,7 +70,7 @@ public static UIButtonChoice MakeFilterButtons(bool withHistory) textures.Add(MagicStorage.Instance.GetTexture("FilterAll")); texts.Add(Language.GetText("Mods.MagicStorage.FilterRecent")); } - return new UIButtonChoice(textures.ToArray(), texts.ToArray()); + return new UIButtonChoice(onChanged, textures.ToArray(), texts.ToArray()); } } diff --git a/MagicStorage.cs b/MagicStorage.cs index 8b3b5764..5b3f44b7 100644 --- a/MagicStorage.cs +++ b/MagicStorage.cs @@ -57,7 +57,7 @@ private void AddTranslations() AddTranslation(text); text = CreateTranslation("DepositAll"); - text.SetDefault("Deposit All"); + text.SetDefault("Transfer All"); text.AddTranslation(GameCulture.Russian, "Переместить всё"); text.AddTranslation(GameCulture.French, "Déposer tout"); text.AddTranslation(GameCulture.Spanish, "Depositar todo"); @@ -242,6 +242,14 @@ private void AddTranslations() text = CreateTranslation("SortDps"); text.SetDefault("Sort by DPS"); AddTranslation(text); + + text = CreateTranslation("ShowOnlyFavorited"); + text.SetDefault("Only Favorited"); + AddTranslation(text); + + text = CreateTranslation("DepositTooltip"); + text.SetDefault("Left click to Deposit All non favorited items, right click to Restock from storage"); + AddTranslation(text); } public override void PostSetupContent() diff --git a/MagicStorage.csproj b/MagicStorage.csproj index e1284cf2..3a4d2d22 100644 --- a/MagicStorage.csproj +++ b/MagicStorage.csproj @@ -122,6 +122,7 @@ + diff --git a/NetHelper.cs b/NetHelper.cs index 20bf7fc9..fba93dc9 100644 --- a/NetHelper.cs +++ b/NetHelper.cs @@ -153,11 +153,12 @@ public static void SendDeposit(int ent, Item item) } } - public static void SendWithdraw(int ent, Item item, bool toInventory = false) + public static void SendWithdraw(int ent, Item item, bool toInventory = false, bool keepOneIfFavorite = false) { if (Main.netMode == 1) { ModPacket packet = PrepareStorageOperation(ent, (byte)(toInventory ? 3 : 1)); + packet.Write(keepOneIfFavorite); ItemIO.Send(item, packet, true); packet.Send(); } @@ -203,9 +204,10 @@ public static void ReceiveStorageOperation(BinaryReader reader, int sender) } else if (op == 1 || op == 3) { + var keepOneIfFavorite = reader.ReadBoolean(); Item item = ItemIO.Receive(reader, true); - item = heart.TryWithdraw(item); - if (!item.IsAir) + item = heart.TryWithdraw(item, keepOneIfFavorite); + if (!item.IsAir) { ModPacket packet = PrepareOperationResult(op); ItemIO.Send(item, packet, true); diff --git a/StorageGUI.cs b/StorageGUI.cs index db016fcf..c69b0929 100644 --- a/StorageGUI.cs +++ b/StorageGUI.cs @@ -40,7 +40,9 @@ public static bool MouseClicked private static UIElement topBar = new UIElement(); internal static UISearchBar searchBar; private static UIButtonChoice sortButtons; + private static UIToggleButton favoritedOnlyButton; internal static UITextPanel depositButton; + internal static UITextPanel restockButton; private static UIElement topBar2 = new UIElement(); private static UIButtonChoice filterButtons; @@ -92,14 +94,22 @@ public static void Initialize() InitSortButtons(); topBar.Append(sortButtons); - depositButton.Left.Set(sortButtons.GetDimensions().Width + 2 * padding, 0f); + var x = sortButtons.GetDimensions().Width + 2 * padding; + favoritedOnlyButton.Left.Set(x, 0f); + topBar.Append(favoritedOnlyButton); + + x += favoritedOnlyButton.GetDimensions().Width + 2 * padding; + + depositButton.Left.Set(x, 0f); depositButton.Width.Set(128f, 0f); depositButton.Height.Set(-2 * padding, 1f); depositButton.PaddingTop = 8f; depositButton.PaddingBottom = 8f; - topBar.Append(depositButton); - - float depositButtonRight = sortButtons.GetDimensions().Width + 2 * padding + depositButton.GetDimensions().Width; + topBar.Append(depositButton); + + x += depositButton.GetDimensions().Width; + + float depositButtonRight = x; searchBar.Left.Set(depositButtonRight + padding, 0f); searchBar.Width.Set(-depositButtonRight - 2 * padding, 1f); searchBar.Height.Set(0f, 1f); @@ -188,7 +198,11 @@ private static void InitSortButtons() { if (sortButtons == null) { - sortButtons = GUIHelpers.MakeSortButtons(); + sortButtons = GUIHelpers.MakeSortButtons(StorageGUI.RefreshItems); + } + if (favoritedOnlyButton == null) + { + favoritedOnlyButton = new UIToggleButton(RefreshItems, MagicStorage.Instance.GetTexture("FilterMisc"), Language.GetText("Mods.MagicStorage.ShowOnlyFavorited")); } } @@ -196,7 +210,7 @@ private static void InitFilterButtons() { if (filterButtons == null) { - filterButtons = GUIHelpers.MakeFilterButtons(true); + filterButtons = GUIHelpers.MakeFilterButtons(true, StorageGUI.RefreshItems); } } @@ -237,7 +251,9 @@ public static void Draw(TEStorageHeart heart) basePanel.Draw(Main.spriteBatch); slotZone.DrawText(); sortButtons.DrawText(); + favoritedOnlyButton.DrawText(); filterButtons.DrawText(); + DrawDepositButton(); } private static Item GetItem(int slot, ref int context) @@ -319,17 +335,17 @@ public static void RefreshItems() FilterMode filterMode = (FilterMode) filterButtons.Choice; IEnumerable itemsLocal; - if (filterMode == FilterMode.Recent) + if (filterMode == FilterMode.Recent) { - var stored = heart.GetStoredItems().GroupBy(x => x.type).ToDictionary(x => x.Key, x => x.First()); - - var toFilter = heart.UniqueItemsPutHistory.Reverse().Where(x => stored.ContainsKey(x.type)).Select(x => stored[x.type]); - itemsLocal = ItemSorter.SortAndFilter(toFilter, sortMode == SortMode.Default ? SortMode.AsIs : sortMode, - FilterMode.All, modSearchBox.ModIndex, searchBar.Text, 100); - } - else - itemsLocal = ItemSorter.SortAndFilter(heart.GetStoredItems(), sortMode, filterMode, modSearchBox.ModIndex, searchBar.Text); - items.AddRange(itemsLocal); + var stored = heart.GetStoredItems().GroupBy(x => x.type).ToDictionary(x => x.Key, x => x.First()); + + var toFilter = heart.UniqueItemsPutHistory.Reverse().Where(x => stored.ContainsKey(x.type)).Select(x => stored[x.type]); + itemsLocal = ItemSorter.SortAndFilter(toFilter, sortMode == SortMode.Default ? SortMode.AsIs : sortMode, + FilterMode.All, modSearchBox.ModIndex, searchBar.Text, 100); + } + else + itemsLocal = ItemSorter.SortAndFilter(heart.GetStoredItems(), sortMode, filterMode, modSearchBox.ModIndex, searchBar.Text); + items.AddRange(itemsLocal.Where(x => !favoritedOnlyButton.Value || x.favorited)); for (int k = 0; k < items.Count; k++) { didMatCheck.Add(false); @@ -350,12 +366,29 @@ private static void UpdateDepositButton() Main.PlaySound(7, -1, -1, 1); } } + else if (CraftingGUI.RightMouseClicked) + { + if (TryRestock()) + { + RefreshItems(); + Main.PlaySound(7, -1, -1, 1); + } + } } else { depositButton.BackgroundColor = new Color(63, 82, 151) * 0.7f; } } + + private static void DrawDepositButton() + { + Rectangle dim = InterfaceHelper.GetFullRectangle(depositButton); + if (curMouse.X > dim.X && curMouse.X < dim.X + dim.Width && curMouse.Y > dim.Y && curMouse.Y < dim.Y + dim.Height) + { + Main.instance.MouseText(Language.GetText("Mods.MagicStorage.DepositTooltip").Value); + } + } private static void ResetSlotFocus() { @@ -368,8 +401,9 @@ private static void HoverItemSlot(int slot, ref int hoverSlot) { Player player = Main.player[Main.myPlayer]; int visualSlot = slot; - slot += numColumns * (int)Math.Round(scrollBar.ViewPosition); - if (MouseClicked) + slot += numColumns * (int)Math.Round(scrollBar.ViewPosition); + + if (MouseClicked) { bool changed = false; if (!Main.mouseItem.IsAir && (player.itemAnimation == 0 && player.itemTime == 0)) @@ -380,18 +414,23 @@ private static void HoverItemSlot(int slot, ref int hoverSlot) } } else if (Main.mouseItem.IsAir && slot < items.Count && !items[slot].IsAir) - { - Item toWithdraw = items[slot].Clone(); - if (toWithdraw.stack > toWithdraw.maxStack) - { - toWithdraw.stack = toWithdraw.maxStack; - } - Main.mouseItem = DoWithdraw(toWithdraw, ItemSlot.ShiftInUse); - if (ItemSlot.ShiftInUse) - { - Main.mouseItem = player.GetItem(Main.myPlayer, Main.mouseItem, false, true); - } - changed = true; + { + if (Main.keyState.IsKeyDown(Keys.LeftAlt)) + items[slot].favorited = !items[slot].favorited; + else + { + Item toWithdraw = items[slot].Clone(); + if (toWithdraw.stack > toWithdraw.maxStack) + { + toWithdraw.stack = toWithdraw.maxStack; + } + Main.mouseItem = DoWithdraw(toWithdraw, ItemSlot.ShiftInUse); + if (ItemSlot.ShiftInUse) + { + Main.mouseItem = player.GetItem(Main.myPlayer, Main.mouseItem, false, true); + } + changed = true; + } } if (changed) { @@ -407,8 +446,10 @@ private static void HoverItemSlot(int slot, ref int hoverSlot) if (slot < items.Count && !items[slot].IsAir) { - hoverSlot = visualSlot; - } + hoverSlot = visualSlot; + items[slot].newAndShiny = false; + + } if (slotFocus >= 0) { @@ -511,18 +552,44 @@ private static bool TryDepositAll() changed = true; } return changed; - } + } + + private static bool TryRestock() + { + Player player = Main.player[Main.myPlayer]; + TEStorageHeart heart = GetHeart(); + bool changed = false; + + for (int k = 10; k < 50; k++) + { + var item = player.inventory[k]; + if (!item.IsAir && item.stack < item.maxStack) + { + var toWithdraw = item.Clone(); + toWithdraw.stack = item.maxStack - item.stack; + toWithdraw = DoWithdraw(toWithdraw, true, true); + if (!toWithdraw.IsAir) + { + item.stack += toWithdraw.stack; + toWithdraw.TurnToAir(); + changed = true; + } + } + + } + return changed; + } - private static Item DoWithdraw(Item item, bool toInventory = false) + private static Item DoWithdraw(Item item, bool toInventory = false, bool keepOneIfFavorite = false) { TEStorageHeart heart = GetHeart(); if (Main.netMode == 0) { - return heart.TryWithdraw(item); + return heart.TryWithdraw(item, keepOneIfFavorite); } else { - NetHelper.SendWithdraw(heart.ID, item, toInventory); + NetHelper.SendWithdraw(heart.ID, item, toInventory, keepOneIfFavorite); return new Item(); } } diff --git a/UIButtonChoice.cs b/UIButtonChoice.cs index e2e4e777..655df92f 100644 --- a/UIButtonChoice.cs +++ b/UIButtonChoice.cs @@ -12,13 +12,15 @@ namespace MagicStorage { public class UIButtonChoice : UIElement { - private int buttonSize; + readonly Action _onChanged; + private int buttonSize; private int buttonPadding; private Texture2D[] buttons; - private LocalizedText[] names; - private int choice = 0; - + private LocalizedText[] names; + + private int choice = 0; + public int Choice { get @@ -27,13 +29,15 @@ public int Choice } } - public UIButtonChoice(Texture2D[] buttons, LocalizedText[] names, int buttonSize = 21, int buttonPadding = 1) + public UIButtonChoice(Action onChanged, Texture2D[] buttons, LocalizedText[] names, int buttonSize = 21, int buttonPadding = 1) { if (buttons.Length != names.Length || buttons.Length == 0) { throw new ArgumentException(); } - this.buttonSize = buttonSize; + + _onChanged = onChanged; + this.buttonSize = buttonSize; this.buttonPadding = buttonPadding; this.buttons = buttons; this.names = names; @@ -59,8 +63,8 @@ public override void Update(GameTime gameTime) } } if (oldChoice != choice) - { - StorageGUI.RefreshItems(); + { + _onChanged?.Invoke(); } } diff --git a/UIToggleButton.cs b/UIToggleButton.cs new file mode 100644 index 00000000..4a3958e3 --- /dev/null +++ b/UIToggleButton.cs @@ -0,0 +1,92 @@ +using System; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Terraria; +using Terraria.Localization; +using Terraria.UI; + +namespace MagicStorage +{ + public class UIToggleButton : UIElement + { + private int buttonSize; + private int buttonPadding; + private readonly Action onChanged; + private Texture2D _button; + private LocalizedText _name; + + private bool _value; + + public bool Value + { + get + { + return _value; + } + set + { + _value = value; + } + } + + public UIToggleButton(Action onChanged, Texture2D button, LocalizedText name, int buttonSize = 21, int buttonPadding = 1) + { + this.buttonSize = buttonSize; + this.buttonPadding = buttonPadding; + this.onChanged = onChanged; + this._button = button; + this._name = name; + this.Width.Set(buttonSize, 0f); + this.MinWidth.Set(buttonSize, 0f); + this.Height.Set(buttonSize, 0f); + this.MinHeight.Set(buttonSize, 0f); + } + + public override void Update(GameTime gameTime) + { + var oldValue = _value; + if (StorageGUI.MouseClicked && Parent != null) + { + if (MouseOverButton(StorageGUI.curMouse.X, StorageGUI.curMouse.Y)) + { + _value = !_value; + } + } + + if (oldValue != _value) + { + onChanged?.Invoke(); + } + } + + private bool MouseOverButton(int mouseX, int mouseY) + { + Rectangle dim = InterfaceHelper.GetFullRectangle(this); + float left = dim.X; + float right = left + buttonSize * Main.UIScale; + float top = dim.Y; + float bottom = top + buttonSize * Main.UIScale; + return mouseX > left && mouseX < right && mouseY > top && mouseY < bottom; + } + + protected override void DrawSelf(SpriteBatch spriteBatch) + { + Texture2D backTexture = MagicStorage.Instance.GetTexture("SortButtonBackground"); + Texture2D backTextureActive = MagicStorage.Instance.GetTexture("SortButtonBackgroundActive"); + CalculatedStyle dim = GetDimensions(); + Texture2D texture = _value ? backTextureActive : backTexture; + Vector2 drawPos = new Vector2(dim.X, dim.Y); + Color color = MouseOverButton(StorageGUI.curMouse.X, StorageGUI.curMouse.Y) ? Color.Silver : Color.White; + Main.spriteBatch.Draw(texture, new Rectangle((int) drawPos.X, (int) drawPos.Y, buttonSize, buttonSize), color); + Main.spriteBatch.Draw(_button, new Rectangle((int) drawPos.X + 1, (int) drawPos.Y + 1, buttonSize - 1, buttonSize - 1), Color.White); + } + + public void DrawText() + { + if (MouseOverButton(StorageGUI.curMouse.X, StorageGUI.curMouse.Y)) + { + Main.instance.MouseText(_name.Value); + } + } + } +} \ No newline at end of file From 10559feff58f0511ca6e02e3ddc118d7b57fbf32 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Mon, 13 Aug 2018 11:07:20 +0300 Subject: [PATCH 28/80] amend --- CraftingGUI.cs | 38 ++++++++++++++++++++++++-------------- 1 file changed, 24 insertions(+), 14 deletions(-) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index e6250319..2fbcaa4c 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -1398,9 +1398,11 @@ private static void HoverStorage(int slot, ref int hoverSlot) slot += numColumns2 * (int)Math.Round(scrollBar2.ViewPosition); if (slot < storageItems.Count) { - if (MouseClicked) + var item = storageItems[slot]; + item.newAndShiny = false; + if (MouseClicked) { - ItemData data = new ItemData(storageItems[slot]); + ItemData data = new ItemData(item); if (blockStorageItems.Contains(data)) { blockStorageItems.Remove(data); @@ -1421,7 +1423,10 @@ private static void HoverResult(int slot, ref int hoverSlot) return; } - Player player = Main.player[Main.myPlayer]; + if (Main.mouseItem.IsAir && result != null && !result.IsAir) + result.newAndShiny = false; + + Player player = Main.player[Main.myPlayer]; if (MouseClicked) { bool changed = false; @@ -1434,17 +1439,22 @@ private static void HoverResult(int slot, ref int hoverSlot) } else if (Main.mouseItem.IsAir && result != null && !result.IsAir) { - Item toWithdraw = result.Clone(); - if (toWithdraw.stack > toWithdraw.maxStack) - { - toWithdraw.stack = toWithdraw.maxStack; - } - Main.mouseItem = DoWithdrawResult(toWithdraw, ItemSlot.ShiftInUse); - if (ItemSlot.ShiftInUse) - { - Main.mouseItem = player.GetItem(Main.myPlayer, Main.mouseItem, false, true); - } - changed = true; + if (Main.keyState.IsKeyDown(Keys.LeftAlt)) + result.favorited = !result.favorited; + else + { + Item toWithdraw = result.Clone(); + if (toWithdraw.stack > toWithdraw.maxStack) + { + toWithdraw.stack = toWithdraw.maxStack; + } + Main.mouseItem = DoWithdrawResult(toWithdraw, ItemSlot.ShiftInUse); + if (ItemSlot.ShiftInUse) + { + Main.mouseItem = player.GetItem(Main.myPlayer, Main.mouseItem, false, true); + } + changed = true; + } } if (changed) { From a7b4c8d9ddbcd9db7abb92f8fa58b7525b4bc086 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Mon, 13 Aug 2018 11:32:13 +0300 Subject: [PATCH 29/80] favorites in recipes --- CraftingGUI.cs | 71 ++++++++++++++++++++++++++++++++---------------- MagicStorage.cs | 2 +- StoragePlayer.cs | 4 +++ 3 files changed, 53 insertions(+), 24 deletions(-) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 2fbcaa4c..8be4cebe 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -22,7 +22,8 @@ namespace MagicStorage public static class CraftingGUI { const int RecipeButtonsNewChoice = 0; - const int RecipeButtonsBlacklistChoice = 2; + const int RecipeButtonsBlacklistChoice = 3; + const int RecipeButtonsFavoritesChoice = 2; private const int padding = 4; private const int numColumns = 10; private const int numColumns2 = 7; @@ -387,13 +388,16 @@ private static void InitRecipeButtons() { MagicStorage.Instance.GetTexture("RecipeAvailable"), MagicStorage.Instance.GetTexture("RecipeAll"), - MagicStorage.Instance.GetTexture("RecipeAll"), - }, + MagicStorage.Instance.GetTexture("FilterMisc"), + MagicStorage.Instance.GetTexture("RecipeAll"), + }, new LocalizedText[] { Language.GetText("Mods.MagicStorage.RecipeAvailable"), Language.GetText("Mods.MagicStorage.RecipeAll"), - Language.GetText("Mods.MagicStorage.RecipeBlacklist") + Language.GetText("Mods.MagicStorage.ShowOnlyFavorited"), + Language.GetText("Mods.MagicStorage.RecipeBlacklist"), + }); } } @@ -489,6 +493,11 @@ private static Item GetRecipe(int slot, ref int context) { context = recipes[index] == selectedRecipe ? 4 : 3; } + if (!item.IsAir && ModPlayer.FavoritedRecipes.Contains(item)) + { + item = item.Clone(); + item.favorited = true; + } return item; } @@ -777,6 +786,8 @@ public static void RefreshItems() HashSet craftedRecipes; GetKnownItems(out foundItems, out hiddenRecipes, out craftedRecipes); + var favoritesCopy = new HashSet(ModPlayer.FavoritedRecipes.Items.Select(x => x.type)); + EnsureProductToRecipesInited(); lock (threadLock) @@ -785,12 +796,12 @@ public static void RefreshItems() threadSortMode = sortMode; threadFilterMode = filterMode; threadCheckListFoundItems = foundItems; - if (!threadRunning) - { - threadRunning = true; - Thread thread = new Thread(_ => RefreshRecipes(hiddenRecipes, craftedRecipes)); - thread.Start(); - } + if (!threadRunning) + { + threadRunning = true; + Thread thread = new Thread(_ => RefreshRecipes(hiddenRecipes, craftedRecipes, favoritesCopy)); + thread.Start(); + } } } @@ -897,7 +908,7 @@ static bool IsKnownRecursively_CheckIngredient(HashSet availableSet, HashSe return true; } - private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craftedRecipes) + private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craftedRecipes, HashSet favorited) { while (true) { @@ -933,6 +944,8 @@ private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craf .Where(x => (recipeButtons.Choice == RecipeButtonsBlacklistChoice) == hiddenRecipes.Contains(x.createItem.type)) // show only new items if selected .Where(x => (recipeButtons.Choice != RecipeButtonsNewChoice) || !notNewItems.Contains(x.createItem.type)) + // show only favorited items if selected + .Where(x => (recipeButtons.Choice != RecipeButtonsFavoritesChoice) || favorited.Contains(x.createItem.type)) // hard check if this item can be crafted from available items and their recursive products .Where(x => IsKnownRecursively(x, availableItemsMutable, temp)); @@ -962,6 +975,13 @@ private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craf doFiltering(); } + if (threadRecipes.Count == 0 && recipeButtons.Choice == RecipeButtonsFavoritesChoice) + { + // search non favorited recipes too + favorited = new HashSet(); + doFiltering(); + } + if (threadRecipes.Count == 0 && searchBar.Text.Length > 0) { // search hidden recipes too @@ -1315,24 +1335,29 @@ private static void HoverRecipe(int slot, ref int hoverSlot) slot += numColumns * (int)Math.Round(scrollBar.ViewPosition); if (slot < recipes.Count) { - if (MouseClicked) + if (MouseClicked || RightMouseClicked) { var recipe = recipes[slot]; - SetSelectedRecipe(recipe); - } - else if (RightMouseClicked) - { - StoragePlayer modPlayer = Main.player[Main.myPlayer].GetModPlayer(); - if (recipeButtons.Choice == RecipeButtonsBlacklistChoice) + if (Main.keyState.IsKeyDown(Keys.LeftAlt)) { - if (modPlayer.RemoveFromHiddenRecipes(recipes[slot].createItem)) - RefreshItems(); + if (!ModPlayer.FavoritedRecipes.Add(recipe.createItem)) + ModPlayer.FavoritedRecipes.Remove(recipe.createItem); } - else + else if (Main.keyState.IsKeyDown(Keys.LeftControl)) { - if (modPlayer.AddToHiddenRecipes(recipes[slot].createItem)) - RefreshItems(); + if (recipeButtons.Choice == RecipeButtonsBlacklistChoice) + { + if (ModPlayer.RemoveFromHiddenRecipes(recipes[slot].createItem)) + RefreshItems(); + } + else + { + if (ModPlayer.AddToHiddenRecipes(recipes[slot].createItem)) + RefreshItems(); + } } + else + SetSelectedRecipe(recipe); } hoverSlot = visualSlot; } diff --git a/MagicStorage.cs b/MagicStorage.cs index 5b3f44b7..c3f63ddf 100644 --- a/MagicStorage.cs +++ b/MagicStorage.cs @@ -236,7 +236,7 @@ private void AddTranslations() AddTranslation(text); text = CreateTranslation("RecipeBlacklist"); - text.SetDefault("Show hidden recipes"); + text.SetDefault("Show hidden recipes (ctrl+click on recipe to (un)hide)"); AddTranslation(text); text = CreateTranslation("SortDps"); diff --git a/StoragePlayer.cs b/StoragePlayer.cs index ee80fea6..791d169a 100644 --- a/StoragePlayer.cs +++ b/StoragePlayer.cs @@ -22,6 +22,8 @@ public class StoragePlayer : ModPlayer public IEnumerable HiddenRecipes { get { return _hiddenRecipes.Items; } } public IEnumerable CraftedRecipes { get { return _craftedRecipes.Items; } } + public ItemTypeOrderedSet FavoritedRecipes { get; private set; } = new ItemTypeOrderedSet("FavoritedRecipes"); + public bool AddToHiddenRecipes(Item item) { return _hiddenRecipes.Add(item); @@ -42,6 +44,7 @@ public override TagCompound Save() var c = new TagCompound(); _hiddenRecipes.Save(c); _craftedRecipes.Save(c); + FavoritedRecipes.Save(c); return c; } @@ -49,6 +52,7 @@ public override void Load(TagCompound tag) { _hiddenRecipes.Load(tag); _craftedRecipes.Load(tag); + FavoritedRecipes.Load(tag); } public override void UpdateDead() From a46e96a963c2f465fcdac160ea065d36528e1af9 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Mon, 13 Aug 2018 13:32:30 +0300 Subject: [PATCH 30/80] Restock fix --- StorageGUI.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/StorageGUI.cs b/StorageGUI.cs index c69b0929..3748002c 100644 --- a/StorageGUI.cs +++ b/StorageGUI.cs @@ -560,10 +560,9 @@ private static bool TryRestock() TEStorageHeart heart = GetHeart(); bool changed = false; - for (int k = 10; k < 50; k++) + foreach (var item in player.inventory) { - var item = player.inventory[k]; - if (!item.IsAir && item.stack < item.maxStack) + if (item != null && !item.IsAir && item.stack < item.maxStack) { var toWithdraw = item.Clone(); toWithdraw.stack = item.maxStack - item.stack; From 136b8aae2d7fa99512302ba0c4b7232abb0c05b0 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Mon, 13 Aug 2018 15:04:01 +0300 Subject: [PATCH 31/80] 1. use Ctrl+Left Click for black listing items instead of Right Click; 2. You can get new items for testing purpose only one time until respawn and having it with you will cause 5x more incoming damage. --- Components/TEStorageUnit.cs | 1 + CraftingGUI.cs | 153 ++++++++++++++++++++++++------------ ItemSaveLoadHook.cs | 32 ++++++++ MagicStorage.cs | 9 +++ MagicStorage.csproj | 1 + Sorting/ItemFilter.cs | 2 +- StoragePlayer.cs | 37 ++++++++- 7 files changed, 183 insertions(+), 52 deletions(-) create mode 100644 ItemSaveLoadHook.cs diff --git a/Components/TEStorageUnit.cs b/Components/TEStorageUnit.cs index 9a934b4c..1e0247e9 100644 --- a/Components/TEStorageUnit.cs +++ b/Components/TEStorageUnit.cs @@ -143,6 +143,7 @@ public override void DepositItem(Item toDeposit, bool locked = false) } try { + if (CraftingGUI.IsTestItem(toDeposit)) return; Item original = toDeposit.Clone(); bool finished = false; bool hasChange = false; diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 8be4cebe..88718c7a 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -438,36 +438,54 @@ public static void Update(GameTime gameTime) }}catch(Exception e){Main.NewTextMultiline(e.ToString());} } - public static void Draw(TEStorageHeart heart) - {try{ - Player player = Main.player[Main.myPlayer]; - StoragePlayer modPlayer = player.GetModPlayer(MagicStorage.Instance); - Initialize(); - if (Main.mouseX > panelLeft && Main.mouseX < recipeLeft + panelWidth && Main.mouseY > panelTop && Main.mouseY < panelTop + panelHeight) - { - player.mouseInterface = true; - player.showItemIcon = false; - InterfaceHelper.HideItemIconCache(); - } - basePanel.Draw(Main.spriteBatch); - recipePanel.Draw(Main.spriteBatch); - Vector2 pos = recipeZone.GetDimensions().Position(); - if (threadRunning) - { - Utils.DrawBorderString(Main.spriteBatch, "Loading", pos + new Vector2(8f, 8f), Color.White); - } - stationZone.DrawText(); - recipeZone.DrawText(); - ingredientZone.DrawText(); - recipeHeaderZone.DrawText(); - storageZone.DrawText(); - resultZone.DrawText(); - sortButtons.DrawText(); - recipeButtons.DrawText(); - filterButtons.DrawText();}catch(Exception e){Main.NewTextMultiline(e.ToString());} - } + public static void Draw(TEStorageHeart heart) + { + try + { + Player player = Main.player[Main.myPlayer]; + Initialize(); + if (Main.mouseX > panelLeft && Main.mouseX < recipeLeft + panelWidth && Main.mouseY > panelTop && Main.mouseY < panelTop + panelHeight) + { + player.mouseInterface = true; + player.showItemIcon = false; + InterfaceHelper.HideItemIconCache(); + } + + basePanel.Draw(Main.spriteBatch); + recipePanel.Draw(Main.spriteBatch); + Vector2 pos = recipeZone.GetDimensions().Position(); + if (threadRunning) + { + Utils.DrawBorderString(Main.spriteBatch, "Loading", pos + new Vector2(8f, 8f), Color.White); + } + + stationZone.DrawText(); + recipeZone.DrawText(); + ingredientZone.DrawText(); + recipeHeaderZone.DrawText(); + storageZone.DrawText(); + resultZone.DrawText(); + sortButtons.DrawText(); + recipeButtons.DrawText(); + filterButtons.DrawText(); + DrawCraftButton(); + } + catch (Exception e) + { + Main.NewTextMultiline(e.ToString()); + } + } - private static Item GetStation(int slot, ref int context) + private static void DrawCraftButton() + { + Rectangle dim = InterfaceHelper.GetFullRectangle(craftButton); + if (Main.netMode == NetmodeID.SinglePlayer && curMouse.X > dim.X && curMouse.X < dim.X + dim.Width && curMouse.Y > dim.Y && curMouse.Y < dim.Y + dim.Height) + { + Main.instance.MouseText(Language.GetText("Mods.MagicStorage.CraftTooltip").Value); + } + } + + private static Item GetStation(int slot, ref int context) { Item[] stations = GetCraftingStations(); if (stations == null || slot >= stations.Length) @@ -703,28 +721,49 @@ private static void UpdateCraftButton() if (curMouse.X > dim.X && curMouse.X < dim.X + dim.Width && curMouse.Y > dim.Y && curMouse.Y < dim.Y + dim.Height) { craftButton.BackgroundColor = new Color(73, 94, 171); - if (curMouse.LeftButton == ButtonState.Pressed) + if (RightMouseClicked && selectedRecipe != null && Main.mouseItem.IsAir) + { + var item = selectedRecipe.createItem; + if (Main.netMode == NetmodeID.SinglePlayer + && !item.consumable && (item.mana > 0 || item.magic || item.ranged || item.thrown || item.melee + || item.headSlot >= 0 || item.bodySlot >= 0 || item.legSlot >= 0 || item.accessory || Main.projHook[item.shoot] + || item.pick > 0 || item.axe > 0 || item.hammer > 0) + && !item.summon && item.createTile < 0 && item.createWall < 0 && !item.potion && item.fishingPole <= 1 && item.ammo == AmmoID.None) + { + HashSet found; + HashSet hidden; + HashSet crafted; + GetKnownItems(out found,out hidden, out crafted); + var type = item.type; + if (!found.Contains(type) && !crafted.Contains(type)) + { + var testItem = new Item(); + testItem.SetDefaults(type, true); + MarkAsTestItem(testItem); + Main.mouseItem = testItem; + ModPlayer.AddToCraftedRecipes(selectedRecipe.createItem); + } + } + } + else if (curMouse.LeftButton == ButtonState.Pressed && selectedRecipe != null && IsAvailable(selectedRecipe) && PassesBlock(selectedRecipe)) { - if (selectedRecipe != null && IsAvailable(selectedRecipe) && PassesBlock(selectedRecipe)) - { - if (craftTimer <= 0) - { - craftTimer = maxCraftTimer; - maxCraftTimer = maxCraftTimer * 3 / 4; - if (maxCraftTimer <= 0) - { - maxCraftTimer = 1; - } - TryCraft(); - RefreshItems(); - Main.PlaySound(7, -1, -1, 1); - } - craftTimer--; - flag = true; - StoragePlayer modPlayer = Main.player[Main.myPlayer].GetModPlayer(); - if (modPlayer.AddToCraftedRecipes(selectedRecipe.createItem)) - RefreshItems(); - } + if (craftTimer <= 0) + { + craftTimer = maxCraftTimer; + maxCraftTimer = maxCraftTimer * 3 / 4; + if (maxCraftTimer <= 0) + { + maxCraftTimer = 1; + } + TryCraft(); + RefreshItems(); + Main.PlaySound(7, -1, -1, 1); + } + craftTimer--; + flag = true; + StoragePlayer modPlayer = Main.player[Main.myPlayer].GetModPlayer(); + if (modPlayer.AddToCraftedRecipes(selectedRecipe.createItem)) + RefreshItems(); } } else @@ -742,6 +781,20 @@ private static void UpdateCraftButton() } } + public static void MarkAsTestItem(Item testItem) + { + testItem.value = 0; + testItem.shopCustomPrice = 0; + testItem.material = false; + testItem.rare = -11; + testItem.SetNameOverride(Lang.GetItemNameValue(testItem.type) + Language.GetTextValue("Mods.MagicStorage.TestItemSuffix")); + } + + public static bool IsTestItem(Item item) + { + return item.Name.EndsWith(Language.GetTextValue("Mods.MagicStorage.TestItemSuffix")); + } + private static TEStorageHeart GetHeart() { Player player = Main.player[Main.myPlayer]; diff --git a/ItemSaveLoadHook.cs b/ItemSaveLoadHook.cs new file mode 100644 index 00000000..ada96e9e --- /dev/null +++ b/ItemSaveLoadHook.cs @@ -0,0 +1,32 @@ +using Terraria; +using Terraria.ModLoader; +using Terraria.ModLoader.IO; + +namespace MagicStorage +{ + public class ItemSaveLoadHook : GlobalItem + { + public override TagCompound Save(Item item) + { + if (CraftingGUI.IsTestItem(item)) + { + return new TagCompound() {{"TestItem", true}}; + } + + return null; + } + + public override void Load(Item item, TagCompound tag) + { + if (tag != null && tag.ContainsKey("TestItem")) + CraftingGUI.MarkAsTestItem(item); + + base.Load(item, tag); + } + + public override bool NeedsSaving(Item item) + { + return CraftingGUI.IsTestItem(item); + } + } +} \ No newline at end of file diff --git a/MagicStorage.cs b/MagicStorage.cs index c3f63ddf..b7537509 100644 --- a/MagicStorage.cs +++ b/MagicStorage.cs @@ -31,6 +31,7 @@ public override void Load() legendMod = ModLoader.GetMod("LegendOfTerraria3"); bluemagicMod = ModLoader.GetMod("Bluemagic"); AddTranslations(); + AddGlobalItem("MagicStorageItemSaveLoadHook", new ItemSaveLoadHook()); } public override void Unload() @@ -250,6 +251,14 @@ private void AddTranslations() text = CreateTranslation("DepositTooltip"); text.SetDefault("Left click to Deposit All non favorited items, right click to Restock from storage"); AddTranslation(text); + + text = CreateTranslation("CraftTooltip"); + text.SetDefault("Left click to Craft, Right click to get item for a test (only for new items)"); + AddTranslation(text); + + text = CreateTranslation("TestItemSuffix"); + text.SetDefault(" !UNTIL RESPAWN!"); + AddTranslation(text); } public override void PostSetupContent() diff --git a/MagicStorage.csproj b/MagicStorage.csproj index 3a4d2d22..50aab7e3 100644 --- a/MagicStorage.csproj +++ b/MagicStorage.csproj @@ -72,6 +72,7 @@ + diff --git a/Sorting/ItemFilter.cs b/Sorting/ItemFilter.cs index 8d674a32..6ab49abd 100644 --- a/Sorting/ItemFilter.cs +++ b/Sorting/ItemFilter.cs @@ -64,7 +64,7 @@ public class FilterWeaponSummon : ItemFilter public override bool Passes(Item item) { if (item.type == 109 || item.type == 29) return false; // mana or heart crystal - return item.summon || SortClassList.BossSpawn(item) || SortClassList.Cart(item) || SortClassList.LightPet(item) || SortClassList.Mount(item); + return item.summon || SortClassList.BossSpawn(item) || SortClassList.Cart(item) || SortClassList.LightPet(item) || SortClassList.Mount(item) || item.sentry; } } diff --git a/StoragePlayer.cs b/StoragePlayer.cs index 791d169a..60a24311 100644 --- a/StoragePlayer.cs +++ b/StoragePlayer.cs @@ -6,6 +6,7 @@ using Terraria.ModLoader; using Terraria.UI; using MagicStorage.Components; +using Terraria.ID; using Terraria.ModLoader.IO; namespace MagicStorage @@ -22,7 +23,7 @@ public class StoragePlayer : ModPlayer public IEnumerable HiddenRecipes { get { return _hiddenRecipes.Items; } } public IEnumerable CraftedRecipes { get { return _craftedRecipes.Items; } } - public ItemTypeOrderedSet FavoritedRecipes { get; private set; } = new ItemTypeOrderedSet("FavoritedRecipes"); + public ItemTypeOrderedSet FavoritedRecipes { get; private set; } = new ItemTypeOrderedSet("FavoritedRecipes"); public bool AddToHiddenRecipes(Item item) { @@ -248,5 +249,39 @@ public static bool IsStorageCrafting() { return Main.player[Main.myPlayer].GetModPlayer().StorageCrafting(); } + + public override void ModifyHitByNPC(NPC npc, ref int damage, ref bool crit) + { + foreach (var item in player.inventory.Concat(player.armor).Concat(player.dye).Concat(player.miscDyes).Concat(player.miscEquips)) + { + if (item != null && !item.IsAir && CraftingGUI.IsTestItem(item)) + { + damage *= 5; + break; + } + } + } + + public override bool CanHitPvp(Item item, Player target) + { + if (CraftingGUI.IsTestItem(item)) return false; + return base.CanHitPvp(item, target); + } + + public override void OnRespawn(Player player) + { + foreach (var item in player.inventory.Concat(player.armor).Concat(player.dye).Concat(player.miscDyes).Concat(player.miscEquips)) + { + if (item != null && !item.IsAir && CraftingGUI.IsTestItem(item)) + item.TurnToAir(); + } + + { + var item = player.trashItem; + if (item != null && !item.IsAir && CraftingGUI.IsTestItem(item)) + item.TurnToAir(); + } + base.OnRespawn(player); + } } } \ No newline at end of file From c9e0a47280b1e28221cf49ccb56c3cf9df739cbc Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Mon, 13 Aug 2018 15:32:30 +0300 Subject: [PATCH 32/80] search bar fix --- CraftingGUI.cs | 62 ++++++++++++++++++++++++++------------------------ 1 file changed, 32 insertions(+), 30 deletions(-) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 88718c7a..3bef8513 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -1018,42 +1018,44 @@ private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craf }; doFiltering(); - + // now if nothing found we disable filters one by one - - if (threadRecipes.Count == 0 && recipeButtons.Choice == RecipeButtonsNewChoice) + if (searchBar.Text.Length > 0) { - // search old recipes too - notNewItems = new HashSet(); - doFiltering(); - } + if (threadRecipes.Count == 0 && recipeButtons.Choice == RecipeButtonsNewChoice) + { + // search old recipes too + notNewItems = new HashSet(); + doFiltering(); + } - if (threadRecipes.Count == 0 && recipeButtons.Choice == RecipeButtonsFavoritesChoice) - { - // search non favorited recipes too - favorited = new HashSet(); - doFiltering(); - } + if (threadRecipes.Count == 0 && recipeButtons.Choice == RecipeButtonsFavoritesChoice) + { + // search non favorited recipes too + favorited = new HashSet(); + doFiltering(); + } - if (threadRecipes.Count == 0 && searchBar.Text.Length > 0) - { - // search hidden recipes too - hiddenRecipes = new HashSet(); - doFiltering(); - } + if (threadRecipes.Count == 0 && hiddenRecipes.Count > 0) + { + // search hidden recipes too + hiddenRecipes = new HashSet(); + doFiltering(); + } - if (threadRecipes.Count == 0 && filterMode != FilterMode.All) - { - // any category - filterMode = FilterMode.All; - doFiltering(); - } + if (threadRecipes.Count == 0 && filterMode != FilterMode.All) + { + // any category + filterMode = FilterMode.All; + doFiltering(); + } - if (threadRecipes.Count == 0 && modFilterIndex != ModSearchBox.ModIndexAll) - { - // search all mods - modFilterIndex = ModSearchBox.ModIndexAll; - doFiltering(); + if (threadRecipes.Count == 0 && modFilterIndex != ModSearchBox.ModIndexAll) + { + // search all mods + modFilterIndex = ModSearchBox.ModIndexAll; + doFiltering(); + } } lock (recipeLock) From f08df7056601f4624999fe5926813dddf32b6f8c Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Mon, 13 Aug 2018 18:16:04 +0300 Subject: [PATCH 33/80] right click to mark item as not new --- CraftingGUI.cs | 13 +++++++++---- MagicStorage.cs | 2 +- StoragePlayer.cs | 5 +++++ 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 3bef8513..6571a13d 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -1390,9 +1390,9 @@ private static void HoverRecipe(int slot, ref int hoverSlot) slot += numColumns * (int)Math.Round(scrollBar.ViewPosition); if (slot < recipes.Count) { - if (MouseClicked || RightMouseClicked) + var recipe = recipes[slot]; + if (MouseClicked) { - var recipe = recipes[slot]; if (Main.keyState.IsKeyDown(Keys.LeftAlt)) { if (!ModPlayer.FavoritedRecipes.Add(recipe.createItem)) @@ -1402,17 +1402,22 @@ private static void HoverRecipe(int slot, ref int hoverSlot) { if (recipeButtons.Choice == RecipeButtonsBlacklistChoice) { - if (ModPlayer.RemoveFromHiddenRecipes(recipes[slot].createItem)) + if (ModPlayer.RemoveFromHiddenRecipes(recipe.createItem)) RefreshItems(); } else { - if (ModPlayer.AddToHiddenRecipes(recipes[slot].createItem)) + if (ModPlayer.AddToHiddenRecipes(recipe.createItem)) RefreshItems(); } } else SetSelectedRecipe(recipe); + } + else if (RightMouseClicked && recipeButtons.Choice == RecipeButtonsNewChoice && !ModPlayer.IsRecipeHidden(recipe.createItem)) + { + if (ModPlayer.AddToCraftedRecipes(recipe.createItem)) + RefreshItems(); } hoverSlot = visualSlot; } diff --git a/MagicStorage.cs b/MagicStorage.cs index b7537509..ae508746 100644 --- a/MagicStorage.cs +++ b/MagicStorage.cs @@ -229,7 +229,7 @@ private void AddTranslations() AddTranslation(text); text = CreateTranslation("RecipeAvailable"); - text.SetDefault("Show new recipes"); + text.SetDefault("Show new recipes (right click to remove \"new\" flag)"); AddTranslation(text); text = CreateTranslation("RecipeAll"); diff --git a/StoragePlayer.cs b/StoragePlayer.cs index 60a24311..1af21a00 100644 --- a/StoragePlayer.cs +++ b/StoragePlayer.cs @@ -25,6 +25,11 @@ public class StoragePlayer : ModPlayer public ItemTypeOrderedSet FavoritedRecipes { get; private set; } = new ItemTypeOrderedSet("FavoritedRecipes"); + public bool IsRecipeHidden(Item item) + { + return _hiddenRecipes.Contains(item); + } + public bool AddToHiddenRecipes(Item item) { return _hiddenRecipes.Add(item); From 1013c61fef1534f8ff3b4eb6be51981ca3ae0cd7 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Wed, 15 Aug 2018 22:52:27 +0300 Subject: [PATCH 34/80] newAndShiny recipes --- CraftingGUI.cs | 35 +++++++++++++++++++++++------------ StoragePlayer.cs | 3 +++ 2 files changed, 26 insertions(+), 12 deletions(-) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 6571a13d..32530445 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -503,19 +503,29 @@ private static Item GetRecipe(int slot, ref int context) } int index = slot + numColumns * (int)Math.Round(scrollBar.ViewPosition); Item item = index < recipes.Count ? recipes[index].createItem : new Item(); - if (!item.IsAir && recipes[index] == selectedRecipe) + if (!item.IsAir) { - context = 6; - } - if (!item.IsAir && !recipeAvailable[index]) - { - context = recipes[index] == selectedRecipe ? 4 : 3; + if (recipes[index] == selectedRecipe) + { + context = 6; + } + if (!recipeAvailable[index]) + { + context = recipes[index] == selectedRecipe ? 4 : 3; + } + if (ModPlayer.FavoritedRecipes.Contains(item)) + { + item = item.Clone(); + item.favorited = true; + } + + if (!ModPlayer.SeenRecipes.Contains(item)) + { + item = item.Clone(); + item.newAndShiny = true; + } } - if (!item.IsAir && ModPlayer.FavoritedRecipes.Contains(item)) - { - item = item.Clone(); - item.favorited = true; - } + return item; } @@ -1391,7 +1401,7 @@ private static void HoverRecipe(int slot, ref int hoverSlot) if (slot < recipes.Count) { var recipe = recipes[slot]; - if (MouseClicked) + if (MouseClicked) { if (Main.keyState.IsKeyDown(Keys.LeftAlt)) { @@ -1425,6 +1435,7 @@ private static void HoverRecipe(int slot, ref int hoverSlot) static void SetSelectedRecipe(Recipe recipe) { + if (recipe != null) ModPlayer.SeenRecipes.Add(recipe.createItem); selectedRecipe = recipe; RefreshStorageItems(); blockStorageItems.Clear(); diff --git a/StoragePlayer.cs b/StoragePlayer.cs index 1af21a00..fc9e05a5 100644 --- a/StoragePlayer.cs +++ b/StoragePlayer.cs @@ -24,6 +24,7 @@ public class StoragePlayer : ModPlayer public IEnumerable CraftedRecipes { get { return _craftedRecipes.Items; } } public ItemTypeOrderedSet FavoritedRecipes { get; private set; } = new ItemTypeOrderedSet("FavoritedRecipes"); + public ItemTypeOrderedSet SeenRecipes { get; private set; } = new ItemTypeOrderedSet("SeenRecipes"); public bool IsRecipeHidden(Item item) { @@ -51,6 +52,7 @@ public override TagCompound Save() _hiddenRecipes.Save(c); _craftedRecipes.Save(c); FavoritedRecipes.Save(c); + SeenRecipes.Save(c); return c; } @@ -59,6 +61,7 @@ public override void Load(TagCompound tag) _hiddenRecipes.Load(tag); _craftedRecipes.Load(tag); FavoritedRecipes.Load(tag); + SeenRecipes.Load(tag); } public override void UpdateDead() From e8e19356f8b5ed924eb27aaaa658e926fbb9f8c8 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Wed, 15 Aug 2018 23:09:42 +0300 Subject: [PATCH 35/80] known but not crafted recipes can be unmarked - back to new - with right click --- CraftingGUI.cs | 48 ++++++++++++++++++++++++++++++------------------ StoragePlayer.cs | 8 +++++++- 2 files changed, 37 insertions(+), 19 deletions(-) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 32530445..390667f3 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -479,10 +479,12 @@ public static void Draw(TEStorageHeart heart) private static void DrawCraftButton() { Rectangle dim = InterfaceHelper.GetFullRectangle(craftButton); - if (Main.netMode == NetmodeID.SinglePlayer && curMouse.X > dim.X && curMouse.X < dim.X + dim.Width && curMouse.Y > dim.Y && curMouse.Y < dim.Y + dim.Height) - { - Main.instance.MouseText(Language.GetText("Mods.MagicStorage.CraftTooltip").Value); - } + + if (Main.netMode == NetmodeID.SinglePlayer && curMouse.X > dim.X && curMouse.X < dim.X + dim.Width && curMouse.Y > dim.Y && curMouse.Y < dim.Y + dim.Height + && selectedRecipe != null && Main.mouseItem.IsAir && CanItemBeTakenForTest(selectedRecipe.createItem)) + { + Main.instance.MouseText(Language.GetText("Mods.MagicStorage.CraftTooltip").Value); + } } private static Item GetStation(int slot, ref int context) @@ -734,16 +736,13 @@ private static void UpdateCraftButton() if (RightMouseClicked && selectedRecipe != null && Main.mouseItem.IsAir) { var item = selectedRecipe.createItem; - if (Main.netMode == NetmodeID.SinglePlayer - && !item.consumable && (item.mana > 0 || item.magic || item.ranged || item.thrown || item.melee - || item.headSlot >= 0 || item.bodySlot >= 0 || item.legSlot >= 0 || item.accessory || Main.projHook[item.shoot] - || item.pick > 0 || item.axe > 0 || item.hammer > 0) - && !item.summon && item.createTile < 0 && item.createWall < 0 && !item.potion && item.fishingPole <= 1 && item.ammo == AmmoID.None) + if (CanItemBeTakenForTest(item)) { HashSet found; HashSet hidden; HashSet crafted; - GetKnownItems(out found,out hidden, out crafted); + HashSet asKnownRecipes; + GetKnownItems(out found, out hidden, out crafted, out asKnownRecipes); var type = item.type; if (!found.Contains(type) && !crafted.Contains(type)) { @@ -791,6 +790,15 @@ private static void UpdateCraftButton() } } + static bool CanItemBeTakenForTest(Item item) + { + return Main.netMode == NetmodeID.SinglePlayer + && !item.consumable && (item.mana > 0 || item.magic || item.ranged || item.thrown || item.melee + || item.headSlot >= 0 || item.bodySlot >= 0 || item.legSlot >= 0 || item.accessory || Main.projHook[item.shoot] + || item.pick > 0 || item.axe > 0 || item.hammer > 0) + && !item.summon && item.createTile < 0 && item.createWall < 0 && !item.potion && item.fishingPole <= 1 && item.ammo == AmmoID.None; + } + public static void MarkAsTestItem(Item testItem) { testItem.value = 0; @@ -847,7 +855,9 @@ public static void RefreshItems() HashSet foundItems; HashSet hiddenRecipes; HashSet craftedRecipes; - GetKnownItems(out foundItems, out hiddenRecipes, out craftedRecipes); + HashSet asKnownRecipes; + GetKnownItems(out foundItems, out hiddenRecipes, out craftedRecipes, out asKnownRecipes); + foundItems.UnionWith(asKnownRecipes); var favoritesCopy = new HashSet(ModPlayer.FavoritedRecipes.Items.Select(x => x.type)); @@ -870,20 +880,22 @@ public static void RefreshItems() static HashSet GetKnownItems() { - HashSet a, b, c; - GetKnownItems(out a, out b, out c); + HashSet a, b, c, d; + GetKnownItems(out a, out b, out c, out d); a.UnionWith(b); a.UnionWith(c); + a.UnionWith(d); return a; } - static void GetKnownItems(out HashSet foundItems, out HashSet hiddenRecipes, out HashSet craftedRecipes) + static void GetKnownItems(out HashSet foundItems, out HashSet hiddenRecipes, out HashSet craftedRecipes, out HashSet asKnownRecipes) { foundItems = new HashSet(RetrieveFoundItemsCheckList()); StoragePlayer modPlayer = ModPlayer; hiddenRecipes = new HashSet(modPlayer.HiddenRecipes.Select(x => x.type)); craftedRecipes = new HashSet(modPlayer.CraftedRecipes.Select(x => x.type)); + asKnownRecipes = new HashSet(modPlayer.AsKnownRecipes.Items.Select(x => x.type)); } static StoragePlayer ModPlayer { get { return Main.player[Main.myPlayer].GetModPlayer(); } } @@ -1424,10 +1436,10 @@ private static void HoverRecipe(int slot, ref int hoverSlot) else SetSelectedRecipe(recipe); } - else if (RightMouseClicked && recipeButtons.Choice == RecipeButtonsNewChoice && !ModPlayer.IsRecipeHidden(recipe.createItem)) - { - if (ModPlayer.AddToCraftedRecipes(recipe.createItem)) - RefreshItems(); + else if (RightMouseClicked) + { + if (!ModPlayer.AsKnownRecipes.Add(recipe.createItem)) ModPlayer.AsKnownRecipes.Remove(recipe.createItem); + RefreshItems(); } hoverSlot = visualSlot; } diff --git a/StoragePlayer.cs b/StoragePlayer.cs index fc9e05a5..2999db11 100644 --- a/StoragePlayer.cs +++ b/StoragePlayer.cs @@ -22,9 +22,11 @@ public class StoragePlayer : ModPlayer public IEnumerable HiddenRecipes { get { return _hiddenRecipes.Items; } } public IEnumerable CraftedRecipes { get { return _craftedRecipes.Items; } } - + public ItemTypeOrderedSet FavoritedRecipes { get; private set; } = new ItemTypeOrderedSet("FavoritedRecipes"); public ItemTypeOrderedSet SeenRecipes { get; private set; } = new ItemTypeOrderedSet("SeenRecipes"); + public ItemTypeOrderedSet TestedRecipes { get; private set; } = new ItemTypeOrderedSet("TestedRecipes"); + public ItemTypeOrderedSet AsKnownRecipes { get; private set; } = new ItemTypeOrderedSet("AsKnownRecipes"); public bool IsRecipeHidden(Item item) { @@ -53,6 +55,8 @@ public override TagCompound Save() _craftedRecipes.Save(c); FavoritedRecipes.Save(c); SeenRecipes.Save(c); + TestedRecipes.Save(c); + AsKnownRecipes.Save(c); return c; } @@ -62,6 +66,8 @@ public override void Load(TagCompound tag) _craftedRecipes.Load(tag); FavoritedRecipes.Load(tag); SeenRecipes.Load(tag); + TestedRecipes.Load(tag); + AsKnownRecipes.Load(tag); } public override void UpdateDead() From 19b3e6818ef4ba1e2fe64d11e801c9375182b839 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Thu, 16 Aug 2018 00:30:54 +0300 Subject: [PATCH 36/80] improved strategy to determine known recipes now will not show all other not available recipes when one of them is available --- CraftingGUI.cs | 89 ++++++++++++++++++++++++++++++-------------------- 1 file changed, 53 insertions(+), 36 deletions(-) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 390667f3..7166cdeb 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -151,7 +151,7 @@ public static void Initialize() recipes = nextRecipes; recipeAvailable = nextRecipeAvailable; } - + InitLangStuff(); float itemSlotWidth = Main.inventoryBackTexture.Width * inventoryScale; float itemSlotHeight = Main.inventoryBackTexture.Height * inventoryScale; @@ -738,20 +738,12 @@ private static void UpdateCraftButton() var item = selectedRecipe.createItem; if (CanItemBeTakenForTest(item)) { - HashSet found; - HashSet hidden; - HashSet crafted; - HashSet asKnownRecipes; - GetKnownItems(out found, out hidden, out crafted, out asKnownRecipes); var type = item.type; - if (!found.Contains(type) && !crafted.Contains(type)) - { - var testItem = new Item(); - testItem.SetDefaults(type, true); - MarkAsTestItem(testItem); - Main.mouseItem = testItem; - ModPlayer.AddToCraftedRecipes(selectedRecipe.createItem); - } + var testItem = new Item(); + testItem.SetDefaults(type, true); + MarkAsTestItem(testItem); + Main.mouseItem = testItem; + ModPlayer.TestedRecipes.Add(selectedRecipe.createItem); } } else if (curMouse.LeftButton == ButtonState.Pressed && selectedRecipe != null && IsAvailable(selectedRecipe) && PassesBlock(selectedRecipe)) @@ -796,7 +788,8 @@ static bool CanItemBeTakenForTest(Item item) && !item.consumable && (item.mana > 0 || item.magic || item.ranged || item.thrown || item.melee || item.headSlot >= 0 || item.bodySlot >= 0 || item.legSlot >= 0 || item.accessory || Main.projHook[item.shoot] || item.pick > 0 || item.axe > 0 || item.hammer > 0) - && !item.summon && item.createTile < 0 && item.createWall < 0 && !item.potion && item.fishingPole <= 1 && item.ammo == AmmoID.None; + && !item.summon && item.createTile < 0 && item.createWall < 0 && !item.potion && item.fishingPole <= 1 && item.ammo == AmmoID.None + && !ModPlayer.TestedRecipes.Contains(item); } public static void MarkAsTestItem(Item testItem) @@ -835,6 +828,11 @@ private static Item[] GetCraftingStations() public static void RefreshItems() { + if (ModPlayer.SeenRecipes.Count == 0) + { + foreach (var item in GetKnownItems()) + ModPlayer.SeenRecipes.Add(item); + } items.Clear(); TEStorageHeart heart = GetHeart(); if (heart == null) @@ -925,28 +923,39 @@ static void EnsureProductToRecipesInited() /// static bool IsKnownRecursively(Recipe recipe, HashSet availableSet) { - return IsKnownRecursively(recipe, availableSet, new HashSet()); + return IsKnownRecursively(recipe, availableSet, new HashSet(), new Dictionary()); } /// /// Checks all crafting tree until it finds already available ingredients /// - static bool IsKnownRecursively(Recipe recipe, HashSet availableSet, HashSet recursionTree) + static bool IsKnownRecursively(Recipe recipe, HashSet availableSet, HashSet recursionTree, Dictionary cache) { - if (availableSet.Contains(recipe.createItem.type)) return true; + bool v; + if (cache.TryGetValue(recipe, out v)) return v; + int ingredients = 0; for (int i = 0; i < Recipe.maxRequirements; i++) { var t = recipe.requiredItem[i].type; if (t <= 0) continue; - if (IsKnownRecursively_CheckIngredient(availableSet, recursionTree, t)) continue; - if (IsKnownRecursively_CheckAcceptedGroupsForIngredient(recipe, availableSet, recursionTree, t)) continue; + ingredients++; + if (IsKnownRecursively_CheckIngredient(t, availableSet, recursionTree, cache)) continue; + if (IsKnownRecursively_CheckAcceptedGroupsForIngredient(recipe, availableSet, recursionTree, cache, t)) continue; + cache[recipe] = false; return false; } - availableSet.Add(recipe.createItem.type); - return true; + + if (ingredients > 0) + { + cache[recipe] = true; + return true; + } + + cache[recipe] = false; + return false; } - static bool IsKnownRecursively_CheckAcceptedGroupsForIngredient(Recipe recipe, HashSet availableSet, HashSet recursionTree, int t) + static bool IsKnownRecursively_CheckAcceptedGroupsForIngredient(Recipe recipe, HashSet availableSet, HashSet recursionTree, Dictionary cache, int t) { foreach (var g in recipe.acceptedGroups.Select(j => RecipeGroup.recipeGroups[j])) { @@ -954,7 +963,7 @@ static bool IsKnownRecursively_CheckAcceptedGroupsForIngredient(Recipe recipe, H { foreach (var groupItemType in g.ValidItems) { - if (groupItemType != t && IsKnownRecursively_CheckIngredient(availableSet, recursionTree, groupItemType)) + if (groupItemType != t && IsKnownRecursively_CheckIngredient(groupItemType, availableSet, recursionTree, cache)) { return true; } @@ -964,16 +973,15 @@ static bool IsKnownRecursively_CheckAcceptedGroupsForIngredient(Recipe recipe, H return false; } - static bool IsKnownRecursively_CheckIngredient(HashSet availableSet, HashSet recursionTree, int t) + static bool IsKnownRecursively_CheckIngredient(int t, HashSet availableSet, HashSet recursionTree, Dictionary cache) { if (availableSet.Contains(t)) return true; - if (recursionTree.Contains(t)) return false; - recursionTree.Add(t); + if (!recursionTree.Add(t)) return false; try { List ingredientRecipes; if (!_productToRecipes.TryGetValue(t, out ingredientRecipes)) return false; - if (ingredientRecipes.Count == 0 || ingredientRecipes.All(x => !IsKnownRecursively(x, availableSet, recursionTree))) return false; + if (ingredientRecipes.Count == 0 || ingredientRecipes.All(x => !IsKnownRecursively(x, availableSet, recursionTree, cache))) return false; } finally { @@ -1007,6 +1015,7 @@ private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craf var notNewItems = new HashSet(availableItemsMutable); var temp = new HashSet(); + var tempCache = new Dictionary(); var modFilterIndex = modSearchBox.ModIndex; @@ -1022,7 +1031,7 @@ private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craf // show only favorited items if selected .Where(x => (recipeButtons.Choice != RecipeButtonsFavoritesChoice) || favorited.Contains(x.createItem.type)) // hard check if this item can be crafted from available items and their recursive products - .Where(x => IsKnownRecursively(x, availableItemsMutable, temp)); + .Where(x => IsKnownRecursively(x, availableItemsMutable, temp, tempCache)); threadRecipes.Clear(); threadRecipeAvailable.Clear(); @@ -1436,12 +1445,18 @@ private static void HoverRecipe(int slot, ref int hoverSlot) else SetSelectedRecipe(recipe); } - else if (RightMouseClicked) + else if (RightMouseClicked && (recipe == selectedRecipe || recipeButtons.Choice != RecipeButtonsNewChoice)) { - if (!ModPlayer.AsKnownRecipes.Add(recipe.createItem)) ModPlayer.AsKnownRecipes.Remove(recipe.createItem); - RefreshItems(); - } - hoverSlot = visualSlot; + if (recipeButtons.Choice == RecipeButtonsNewChoice) + { + ModPlayer.AsKnownRecipes.Add(recipe.createItem); + RefreshItems(); + } + else + ModPlayer.AsKnownRecipes.Remove(recipe.createItem); + } + + hoverSlot = visualSlot; } } @@ -1480,11 +1495,13 @@ private static void HoverItem(int slot, ref int hoverSlot) if (_productToRecipes.TryGetValue(item.type, out itemRecipes)) { var knownItems = GetKnownItems(); - var dummy = new HashSet(); + + var recursionTree = new HashSet(); + var cache = new Dictionary(); Recipe selected = null; - foreach (var r in itemRecipes.Where(x => IsKnownRecursively(x, knownItems, dummy))) + foreach (var r in itemRecipes.Where(x => IsKnownRecursively(x, knownItems, recursionTree, cache))) { if (selected == null) selected = r; if (IsAvailable(r)) From 5c98044ac440f4500e07e0b71adca98572e1628b Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Thu, 16 Aug 2018 02:25:42 +0300 Subject: [PATCH 37/80] for weapons and accesory rarity comparison replaced by dps and value comparison in default sorting because rarity is affected by modifier (item prefix) --- Sorting/DefaultSorting.cs | 33 +++++++++++++++++++++++---------- Sorting/ItemSorter.cs | 6 +++--- 2 files changed, 26 insertions(+), 13 deletions(-) diff --git a/Sorting/DefaultSorting.cs b/Sorting/DefaultSorting.cs index e9b92fd8..4efbf5ea 100644 --- a/Sorting/DefaultSorting.cs +++ b/Sorting/DefaultSorting.cs @@ -56,13 +56,13 @@ public static void Initialize() { return; } - classes.Add(new DefaultSortClass(MeleeWeapon, CompareRarity)); - classes.Add(new DefaultSortClass(RangedWeapon, CompareRarity)); - classes.Add(new DefaultSortClass(MagicWeapon, CompareRarity)); - classes.Add(new DefaultSortClass(SummonWeapon, CompareRarity)); - classes.Add(new DefaultSortClass(ThrownWeapon, CompareRarity)); - classes.Add(new DefaultSortClass(Weapon, CompareRarity)); - classes.Add(new DefaultSortClass(Ammo, CompareRarity)); + classes.Add(new DefaultSortClass(MeleeWeapon, CompareDps)); + classes.Add(new DefaultSortClass(RangedWeapon, CompareDps)); + classes.Add(new DefaultSortClass(MagicWeapon, CompareDps)); + classes.Add(new DefaultSortClass(SummonWeapon, CompareValue)); + classes.Add(new DefaultSortClass(ThrownWeapon, CompareDps)); + classes.Add(new DefaultSortClass(Weapon, CompareDps)); + classes.Add(new DefaultSortClass(Ammo, CompareValue)); classes.Add(new DefaultSortClass(Picksaw, ComparePicksaw)); classes.Add(new DefaultSortClass(Hamaxe, CompareHamaxe)); classes.Add(new DefaultSortClass(Pickaxe, ComparePickaxe)); @@ -282,10 +282,23 @@ private static bool CommonTile(Item item) private static int CompareRarity(Item item1, Item item2) { - return item2.rare - item1.rare; + return item1.rare - item2.rare; } - private static int ComparePicksaw(Item item1, Item item2) + private static int CompareValue(Item item1, Item item2) + { + return item1.value - item2.value; + } + + static readonly CompareDps _dps = new Sorting.CompareDps(); + + private static int CompareDps(Item item1, Item item2) + { + int r = _dps.Compare(item1, item2); + return r != 0 ? r : CompareValue(item1, item2); + } + + private static int ComparePicksaw(Item item1, Item item2) { int result = item1.pick - item2.pick; if (result == 0) @@ -330,7 +343,7 @@ private static int CompareAccessory(Item item1, Item item2) int result = item1.vanity.CompareTo(item2.vanity); if (result == 0) { - result = CompareRarity(item1, item2); + result = CompareValue(item1, item2); } return result; } diff --git a/Sorting/ItemSorter.cs b/Sorting/ItemSorter.cs index 91ac6b3c..bcf9f7fd 100644 --- a/Sorting/ItemSorter.cs +++ b/Sorting/ItemSorter.cs @@ -14,7 +14,7 @@ public static IEnumerable SortAndFilter(IEnumerable items, SortMode if (takeCount != null) filteredItems = filteredItems.Take(takeCount.Value); var func = MakeSortFunction(sortMode); if (func == null) return filteredItems; - return filteredItems.OrderBy(x => x, func); + return filteredItems.OrderBy(x => x, func).ThenBy(x => x.type).ThenBy(x => x.value); } public static IEnumerable GetRecipes(SortMode sortMode, FilterMode filterMode, int modFilterIndex, string nameFilter) @@ -23,8 +23,8 @@ public static IEnumerable GetRecipes(SortMode sortMode, FilterMode filte IEnumerable filteredRecipes = Main.recipe.Where((recipe, index) => index < Recipe.numRecipes && filter.Passes(recipe) && FilterName(recipe.createItem, nameFilter) && FilterMod(recipe.createItem, modFilterIndex)); var func = MakeSortFunction(sortMode); if (func == null) return filteredRecipes; - return filteredRecipes.OrderBy(x => x.createItem, func); - } + return filteredRecipes.OrderBy(x => x.createItem, func).ThenBy(x => x.createItem.type).ThenBy(x => x.createItem.value); + } static CompareFunction MakeSortFunction(SortMode sortMode) { From 2d35cff768474dec7ac681843d809c8de46bb124 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Thu, 16 Aug 2018 23:34:22 +0300 Subject: [PATCH 38/80] fixed sorting of recent items --- Sorting/CompareFunction.cs | 8 -------- Sorting/ItemSorter.cs | 3 --- 2 files changed, 11 deletions(-) diff --git a/Sorting/CompareFunction.cs b/Sorting/CompareFunction.cs index 9dce4e25..ff1c4a5c 100644 --- a/Sorting/CompareFunction.cs +++ b/Sorting/CompareFunction.cs @@ -66,12 +66,4 @@ public static float GetDps(Item item) return item.damage / Math.Max((item.useTime + item.reuseDelay) / 60f, 0.001f); } } - - public class AsIs : CompareFunction - { - public override int Compare(Item item1, Item item2) - { - return 0; - } - } } \ No newline at end of file diff --git a/Sorting/ItemSorter.cs b/Sorting/ItemSorter.cs index bcf9f7fd..da26f0f6 100644 --- a/Sorting/ItemSorter.cs +++ b/Sorting/ItemSorter.cs @@ -46,9 +46,6 @@ static CompareFunction MakeSortFunction(SortMode sortMode) case SortMode.Dps: func = new CompareDps(); break; - case SortMode.AsIs: - func = new AsIs(); - break; default: func = null; break; From a26238011f293bd4e5fd25ef6f0ab8a5732cbb14 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Thu, 16 Aug 2018 23:39:22 +0300 Subject: [PATCH 39/80] favorites first --- CraftingGUI.cs | 11 +++++++---- StorageGUI.cs | 2 +- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 7166cdeb..67200180 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -828,10 +828,11 @@ private static Item[] GetCraftingStations() public static void RefreshItems() { - if (ModPlayer.SeenRecipes.Count == 0) + var modPlayer = ModPlayer; + if (modPlayer.SeenRecipes.Count == 0) { foreach (var item in GetKnownItems()) - ModPlayer.SeenRecipes.Add(item); + modPlayer.SeenRecipes.Add(item); } items.Clear(); TEStorageHeart heart = GetHeart(); @@ -839,7 +840,9 @@ public static void RefreshItems() { return; } - items.AddRange(ItemSorter.SortAndFilter(heart.GetStoredItems(), SortMode.Id, FilterMode.All, ModSearchBox.ModIndexAll, "")); + + items.AddRange(ItemSorter.SortAndFilter(heart.GetStoredItems(), SortMode.Id, FilterMode.All, ModSearchBox.ModIndexAll, "") + .OrderBy(x => modPlayer.FavoritedRecipes.Contains(x.type) ? 0 : 1)); AnalyzeIngredients(); InitLangStuff(); InitSortButtons(); @@ -857,7 +860,7 @@ public static void RefreshItems() GetKnownItems(out foundItems, out hiddenRecipes, out craftedRecipes, out asKnownRecipes); foundItems.UnionWith(asKnownRecipes); - var favoritesCopy = new HashSet(ModPlayer.FavoritedRecipes.Items.Select(x => x.type)); + var favoritesCopy = new HashSet(modPlayer.FavoritedRecipes.Items.Select(x => x.type)); EnsureProductToRecipesInited(); diff --git a/StorageGUI.cs b/StorageGUI.cs index 3748002c..a2a18fca 100644 --- a/StorageGUI.cs +++ b/StorageGUI.cs @@ -344,7 +344,7 @@ public static void RefreshItems() FilterMode.All, modSearchBox.ModIndex, searchBar.Text, 100); } else - itemsLocal = ItemSorter.SortAndFilter(heart.GetStoredItems(), sortMode, filterMode, modSearchBox.ModIndex, searchBar.Text); + itemsLocal = ItemSorter.SortAndFilter(heart.GetStoredItems(), sortMode, filterMode, modSearchBox.ModIndex, searchBar.Text).OrderBy(x => x.favorited ? 0 : 1); items.AddRange(itemsLocal.Where(x => !favoritedOnlyButton.Value || x.favorited)); for (int k = 0; k < items.Count; k++) { From 37e77aac63b7dd801b622edf3920933ecbc34a54 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Thu, 16 Aug 2018 23:49:38 +0300 Subject: [PATCH 40/80] searching may disable filtering when no results, favorites choice is never disabled --- CraftingGUI.cs | 7 --- Sorting/ItemSorter.cs | 7 +-- StorageGUI.cs | 108 +++++++++++++++++++++++++++--------------- 3 files changed, 73 insertions(+), 49 deletions(-) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 67200180..e900036e 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -1063,13 +1063,6 @@ private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craf doFiltering(); } - if (threadRecipes.Count == 0 && recipeButtons.Choice == RecipeButtonsFavoritesChoice) - { - // search non favorited recipes too - favorited = new HashSet(); - doFiltering(); - } - if (threadRecipes.Count == 0 && hiddenRecipes.Count > 0) { // search hidden recipes too diff --git a/Sorting/ItemSorter.cs b/Sorting/ItemSorter.cs index da26f0f6..5771aa77 100644 --- a/Sorting/ItemSorter.cs +++ b/Sorting/ItemSorter.cs @@ -8,8 +8,8 @@ namespace MagicStorage.Sorting public static class ItemSorter { public static IEnumerable SortAndFilter(IEnumerable items, SortMode sortMode, FilterMode filterMode, int modFilterIndex, string nameFilter, int? takeCount = null) - { - ItemFilter filter = MakeFilter(filterMode); + { + ItemFilter filter = MakeFilter(filterMode); IEnumerable filteredItems = items.Where((item) => filter.Passes(item) && FilterName(item, nameFilter) && FilterMod(item, modFilterIndex)); if (takeCount != null) filteredItems = filteredItems.Take(takeCount.Value); var func = MakeSortFunction(sortMode); @@ -114,7 +114,8 @@ static ItemFilter MakeFilter(FilterMode filterMode) static bool FilterName(Item item, string filter) { - return item.Name.ToLowerInvariant().IndexOf(filter.ToLowerInvariant()) >= 0; + if (filter.Trim().Length == 0) filter = string.Empty; + return item.Name.ToLowerInvariant().IndexOf(filter.Trim().ToLowerInvariant()) >= 0; } static bool FilterMod(Item item, int modFilterIndex) diff --git a/StorageGUI.cs b/StorageGUI.cs index a2a18fca..451f4677 100644 --- a/StorageGUI.cs +++ b/StorageGUI.cs @@ -314,45 +314,75 @@ private static TEStorageHeart GetHeart() return modPlayer.GetStorageHeart(); } - public static void RefreshItems() - { - if (StoragePlayer.IsStorageCrafting()) - { - CraftingGUI.RefreshItems(); - return; - } - items.Clear(); - didMatCheck.Clear(); - TEStorageHeart heart = GetHeart(); - if (heart == null) - { - return; - } - InitLangStuff(); - InitSortButtons(); - InitFilterButtons(); - SortMode sortMode = (SortMode)sortButtons.Choice; - - FilterMode filterMode = (FilterMode) filterButtons.Choice; - IEnumerable itemsLocal; - if (filterMode == FilterMode.Recent) - { - var stored = heart.GetStoredItems().GroupBy(x => x.type).ToDictionary(x => x.Key, x => x.First()); - - var toFilter = heart.UniqueItemsPutHistory.Reverse().Where(x => stored.ContainsKey(x.type)).Select(x => stored[x.type]); - itemsLocal = ItemSorter.SortAndFilter(toFilter, sortMode == SortMode.Default ? SortMode.AsIs : sortMode, - FilterMode.All, modSearchBox.ModIndex, searchBar.Text, 100); - } - else - itemsLocal = ItemSorter.SortAndFilter(heart.GetStoredItems(), sortMode, filterMode, modSearchBox.ModIndex, searchBar.Text).OrderBy(x => x.favorited ? 0 : 1); - items.AddRange(itemsLocal.Where(x => !favoritedOnlyButton.Value || x.favorited)); - for (int k = 0; k < items.Count; k++) - { - didMatCheck.Add(false); - } - } - - private static void UpdateDepositButton() + public static void RefreshItems() + { + if (StoragePlayer.IsStorageCrafting()) + { + CraftingGUI.RefreshItems(); + return; + } + + items.Clear(); + didMatCheck.Clear(); + TEStorageHeart heart = GetHeart(); + if (heart == null) + { + return; + } + + InitLangStuff(); + InitSortButtons(); + InitFilterButtons(); + SortMode sortMode = (SortMode) sortButtons.Choice; + + FilterMode filterMode = (FilterMode) filterButtons.Choice; + var modFilterIndex = modSearchBox.ModIndex; + + Action doFiltering = () => + { + IEnumerable itemsLocal; + if (filterMode == FilterMode.Recent) + { + var stored = heart.GetStoredItems().GroupBy(x => x.type).ToDictionary(x => x.Key, x => x.First()); + + var toFilter = heart.UniqueItemsPutHistory.Reverse().Where(x => stored.ContainsKey(x.type)).Select(x => stored[x.type]); + itemsLocal = ItemSorter.SortAndFilter(toFilter, sortMode == SortMode.Default ? SortMode.AsIs : sortMode, + FilterMode.All, modFilterIndex, searchBar.Text, 100); + } + else + itemsLocal = ItemSorter.SortAndFilter(heart.GetStoredItems(), sortMode, filterMode, modFilterIndex, searchBar.Text) + .OrderBy(x => x.favorited ? 0 : 1); + + items.AddRange(itemsLocal.Where(x => !favoritedOnlyButton.Value || x.favorited)); + }; + + doFiltering(); + + // now if nothing found we disable filters one by one + if (searchBar.Text.Trim().Length > 0) + { + if (items.Count == 0 && filterMode != FilterMode.All) + { + // search all categories + filterMode = FilterMode.All; + doFiltering(); + } + + if (items.Count == 0 && modFilterIndex != ModSearchBox.ModIndexAll) + { + // search all mods + modFilterIndex = ModSearchBox.ModIndexAll; + doFiltering(); + } + } + + for (int k = 0; k < items.Count; k++) + { + didMatCheck.Add(false); + } + } + + private static void UpdateDepositButton() { Rectangle dim = InterfaceHelper.GetFullRectangle(depositButton); if (curMouse.X > dim.X && curMouse.X < dim.X + dim.Width && curMouse.Y > dim.Y && curMouse.Y < dim.Y + dim.Height) From dbd6a307fcc1229da462f2a3e59abc73b4c61892 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Thu, 16 Aug 2018 23:58:52 +0300 Subject: [PATCH 41/80] Transfer button now uses Quick Stack, hold Ctrl to Deposit All --- MagicStorage.cs | 2 +- StorageGUI.cs | 19 +++++++++++-------- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/MagicStorage.cs b/MagicStorage.cs index ae508746..12a1f2da 100644 --- a/MagicStorage.cs +++ b/MagicStorage.cs @@ -249,7 +249,7 @@ private void AddTranslations() AddTranslation(text); text = CreateTranslation("DepositTooltip"); - text.SetDefault("Left click to Deposit All non favorited items, right click to Restock from storage"); + text.SetDefault("Quick Stack - click, Deposit All - ctrl+click, Restock - right click"); AddTranslation(text); text = CreateTranslation("CraftTooltip"); diff --git a/StorageGUI.cs b/StorageGUI.cs index 451f4677..f8331e5f 100644 --- a/StorageGUI.cs +++ b/StorageGUI.cs @@ -390,7 +390,7 @@ private static void UpdateDepositButton() depositButton.BackgroundColor = new Color(73, 94, 171); if (MouseClicked) { - if (TryDepositAll()) + if (TryDepositAll(!Main.keyState.IsKeyDown(Keys.LeftControl) && !Main.keyState.IsKeyDown(Keys.RightControl))) { RefreshItems(); Main.PlaySound(7, -1, -1, 1); @@ -544,20 +544,22 @@ private static void DoDeposit(Item item) } } - private static bool TryDepositAll() + private static bool TryDepositAll(bool quickStack) { Player player = Main.player[Main.myPlayer]; TEStorageHeart heart = GetHeart(); bool changed = false; + Predicate filter = item => !item.IsAir && !item.favorited && (!quickStack || heart.HasItem(item)); if (Main.netMode == 0) { for (int k = 10; k < 50; k++) { - if (!player.inventory[k].IsAir && !player.inventory[k].favorited) + var item = player.inventory[k]; + if (filter(item)) { - int oldStack = player.inventory[k].stack; - heart.DepositItem(player.inventory[k]); - if (oldStack != player.inventory[k].stack) + int oldStack = item.stack; + heart.DepositItem(item); + if (oldStack != item.stack) { changed = true; } @@ -569,9 +571,10 @@ private static bool TryDepositAll() List items = new List(); for (int k = 10; k < 50; k++) { - if (!player.inventory[k].IsAir && !player.inventory[k].favorited) + var item = player.inventory[k]; + if (filter(item)) { - items.Add(player.inventory[k]); + items.Add(item); } } NetHelper.SendDepositAll(heart.ID, items); From 2c0b6dae1fff21964fb659d18054efc55a888fae Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Fri, 17 Aug 2018 01:36:13 +0300 Subject: [PATCH 42/80] favorites first - fix --- CraftingGUI.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index e900036e..31b9d426 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -841,8 +841,7 @@ public static void RefreshItems() return; } - items.AddRange(ItemSorter.SortAndFilter(heart.GetStoredItems(), SortMode.Id, FilterMode.All, ModSearchBox.ModIndexAll, "") - .OrderBy(x => modPlayer.FavoritedRecipes.Contains(x.type) ? 0 : 1)); + items.AddRange(ItemSorter.SortAndFilter(heart.GetStoredItems(), SortMode.Id, FilterMode.All, ModSearchBox.ModIndexAll, "")); AnalyzeIngredients(); InitLangStuff(); InitSortButtons(); @@ -1034,7 +1033,8 @@ private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craf // show only favorited items if selected .Where(x => (recipeButtons.Choice != RecipeButtonsFavoritesChoice) || favorited.Contains(x.createItem.type)) // hard check if this item can be crafted from available items and their recursive products - .Where(x => IsKnownRecursively(x, availableItemsMutable, temp, tempCache)); + .Where(x => IsKnownRecursively(x, availableItemsMutable, temp, tempCache)) + .OrderBy(x => favorited.Contains(x.createItem.type) ? 0 : 1); threadRecipes.Clear(); threadRecipeAvailable.Clear(); From 538426f0746ef152ed9a877bcf288470ce5343ab Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Fri, 17 Aug 2018 13:01:52 +0300 Subject: [PATCH 43/80] dps is now calculated according with respect to defence according to current game progress, added dps item tooltips --- DpsTooltips.cs | 17 +++++++++++++++++ MagicStorage.csproj | 1 + Sorting/CompareFunction.cs | 28 ++++++++++++++++++++++++++-- 3 files changed, 44 insertions(+), 2 deletions(-) create mode 100644 DpsTooltips.cs diff --git a/DpsTooltips.cs b/DpsTooltips.cs new file mode 100644 index 00000000..575dc019 --- /dev/null +++ b/DpsTooltips.cs @@ -0,0 +1,17 @@ +using System.Collections.Generic; +using MagicStorage.Sorting; +using Terraria; +using Terraria.ModLoader; + +namespace MagicStorage +{ + public class DpsTooltips : GlobalItem + { + public override void ModifyTooltips(Item item, List tooltips) + { + var dps = CompareDps.GetDps(item); + if (dps > 1f) + tooltips.Add(new TooltipLine(MagicStorage.Instance, "DPS", dps.ToString("F0") + " DPS")); + } + } +} \ No newline at end of file diff --git a/MagicStorage.csproj b/MagicStorage.csproj index 50aab7e3..d837a8b9 100644 --- a/MagicStorage.csproj +++ b/MagicStorage.csproj @@ -69,6 +69,7 @@ + diff --git a/Sorting/CompareFunction.cs b/Sorting/CompareFunction.cs index ff1c4a5c..d422ccee 100644 --- a/Sorting/CompareFunction.cs +++ b/Sorting/CompareFunction.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using Terraria; +using Terraria.ModLoader; namespace MagicStorage.Sorting { @@ -61,9 +62,32 @@ public override int Compare(Item item1, Item item2) return (int)((GetDps(item1) - GetDps(item2)) * 100); } - public static float GetDps(Item item) + public static float GetDps(Item item) { - return item.damage / Math.Max((item.useTime + item.reuseDelay) / 60f, 0.001f); + if (item.damage <= 0) return 0f; + int defence; + if (NPC.downedMoonlord) + defence = 50; + else if (NPC.downedAncientCultist) + defence = 43; + else if (NPC.downedGolemBoss) + defence = 38; + else if (NPC.downedPlantBoss) + defence = 32; + else if (NPC.downedMechBossAny) + defence = 26; + else if (Main.hardMode) + defence = 22; + else if (NPC.downedBoss3) + defence = 16; + else if (NPC.downedBoss2) + defence = 14; + else if (NPC.downedBoss1) + defence = 10; + else + defence = 8; + + return Math.Max(item.damage - defence * 0.5f, 1) / Math.Max((item.useTime + item.reuseDelay) / 60f, 0.001f); } } } \ No newline at end of file From 4a75dcb2c3d35c77ccd584a3826b2de445bc2f26 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Fri, 17 Aug 2018 13:39:33 +0300 Subject: [PATCH 44/80] crit chance is also taken into account --- Sorting/CompareFunction.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sorting/CompareFunction.cs b/Sorting/CompareFunction.cs index d422ccee..f0600323 100644 --- a/Sorting/CompareFunction.cs +++ b/Sorting/CompareFunction.cs @@ -87,7 +87,7 @@ public static float GetDps(Item item) else defence = 8; - return Math.Max(item.damage - defence * 0.5f, 1) / Math.Max((item.useTime + item.reuseDelay) / 60f, 0.001f); + return Math.Max(item.damage - defence * 0.5f, 1) / Math.Max((item.useTime + item.reuseDelay) / 60f, 0.001f) * (1f + item.crit / 100f); } } } \ No newline at end of file From e5bc69364232498a37b0403e90a55ebfa3666e82 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Wed, 22 Aug 2018 01:21:41 +0300 Subject: [PATCH 45/80] quick stack improvement to ignore prefixes --- Components/TEAbstractStorageUnit.cs | 2 +- Components/TECreativeStorageUnit.cs | 2 +- Components/TEStorageHeart.cs | 4 ++-- Components/TEStorageUnit.cs | 19 +++++++++++++++---- StorageGUI.cs | 2 +- 5 files changed, 20 insertions(+), 9 deletions(-) diff --git a/Components/TEAbstractStorageUnit.cs b/Components/TEAbstractStorageUnit.cs index 67227d67..50a14922 100644 --- a/Components/TEAbstractStorageUnit.cs +++ b/Components/TEAbstractStorageUnit.cs @@ -56,7 +56,7 @@ public TEStorageHeart GetHeart() public abstract bool HasSpaceInStackFor(Item check, bool locked = false); - public abstract bool HasItem(Item check, bool locked = false); + public abstract bool HasItem(Item check, bool locked = false, bool ignorePrefix = false); public abstract IEnumerable GetItems(); diff --git a/Components/TECreativeStorageUnit.cs b/Components/TECreativeStorageUnit.cs index af2fccf9..f6cf3902 100644 --- a/Components/TECreativeStorageUnit.cs +++ b/Components/TECreativeStorageUnit.cs @@ -29,7 +29,7 @@ public override bool HasSpaceInStackFor(Item check, bool locked = false) return false; } - public override bool HasItem(Item check, bool locked = false) + public override bool HasItem(Item check, bool locked = false, bool ignorePrefix = false) { return !Inactive; } diff --git a/Components/TEStorageHeart.cs b/Components/TEStorageHeart.cs index a5c3403e..7fb11969 100644 --- a/Components/TEStorageHeart.cs +++ b/Components/TEStorageHeart.cs @@ -360,7 +360,7 @@ public Item TryWithdraw(Item lookFor, bool keepOneIfFavorite) } } - public bool HasItem(Item lookFor) + public bool HasItem(Item lookFor, bool ignorePrefix = false) { if (Main.netMode == 2) { @@ -370,7 +370,7 @@ public bool HasItem(Item lookFor) { foreach (TEAbstractStorageUnit storageUnit in GetStorageUnits()) { - if (storageUnit.HasItem(lookFor, true)) + if (storageUnit.HasItem(lookFor, true, ignorePrefix)) return true; } return false; diff --git a/Components/TEStorageUnit.cs b/Components/TEStorageUnit.cs index 1e0247e9..1a9abb04 100644 --- a/Components/TEStorageUnit.cs +++ b/Components/TEStorageUnit.cs @@ -21,6 +21,7 @@ public class TEStorageUnit : TEAbstractStorageUnit //metadata private HashSet hasSpaceInStack = new HashSet(); private HashSet hasItem = new HashSet(); + private HashSet hasItemNoPrefix = new HashSet(); public int Capacity { @@ -106,7 +107,7 @@ public bool HasSpaceFor(Item check, bool locked = false) return !IsFull || HasSpaceInStackFor(check, locked); } - public override bool HasItem(Item check, bool locked = false) + public override bool HasItem(Item check, bool locked = false, bool ignorePrefix = false) { if (Main.netMode == 2 && !locked) { @@ -114,8 +115,9 @@ public override bool HasItem(Item check, bool locked = false) } try { + if (ignorePrefix) return hasItemNoPrefix.Contains(check.type); ItemData data = new ItemData(check); - return hasItem.Contains(data); + return hasItem.Contains(data); } finally { @@ -322,8 +324,11 @@ internal static void SwapItems(TEStorageUnit unit1, TEStorageUnit unit2) unit1.hasSpaceInStack = unit2.hasSpaceInStack; unit2.hasSpaceInStack = dict; dict = unit1.hasItem; - unit1.hasItem = unit2.hasItem; - unit2.hasItem = dict; + unit1.hasItem = unit2.hasItem; + unit2.hasItem = dict; + var temp = unit1.hasItemNoPrefix; + unit1.hasItemNoPrefix = unit2.hasItemNoPrefix; + unit2.hasItemNoPrefix = temp; if (Main.netMode == 2) { unit1.netQueue.Clear(); @@ -381,6 +386,7 @@ public override void Load(TagCompound tag) hasSpaceInStack.Add(data); } hasItem.Add(data); + hasItemNoPrefix.Add(data.Type); } if (Main.netMode == 2) { @@ -453,6 +459,7 @@ public override void NetReceive(BinaryReader trueReader, bool lightReceive) items = other.items; hasSpaceInStack = other.hasSpaceInStack; hasItem = other.hasItem; + hasItemNoPrefix = other.hasItemNoPrefix; } receiving = true; int count = reader.ReadUInt16(); @@ -479,12 +486,14 @@ private void ClearItemsData() items.Clear(); hasSpaceInStack.Clear(); hasItem.Clear(); + hasItemNoPrefix.Clear(); } private void RepairMetadata() { hasSpaceInStack.Clear(); hasItem.Clear(); + hasItemNoPrefix.Clear(); foreach (Item item in items) { ItemData data = new ItemData(item); @@ -493,6 +502,7 @@ private void RepairMetadata() hasSpaceInStack.Add(data); } hasItem.Add(data); + hasItemNoPrefix.Add(data.Type); } } @@ -584,6 +594,7 @@ protected override bool ReceiveData(BinaryReader reader, TEStorageUnit unit) unit.hasSpaceInStack.Add(data); } unit.hasItem.Add(data); + unit.hasItemNoPrefix.Add(data.Type); } return false; } diff --git a/StorageGUI.cs b/StorageGUI.cs index f8331e5f..e66655a9 100644 --- a/StorageGUI.cs +++ b/StorageGUI.cs @@ -549,7 +549,7 @@ private static bool TryDepositAll(bool quickStack) Player player = Main.player[Main.myPlayer]; TEStorageHeart heart = GetHeart(); bool changed = false; - Predicate filter = item => !item.IsAir && !item.favorited && (!quickStack || heart.HasItem(item)); + Predicate filter = item => !item.IsAir && !item.favorited && (!quickStack || heart.HasItem(item, true)); if (Main.netMode == 0) { for (int k = 10; k < 50; k++) From 280eb6b8f4a3697bcce427361c4d9d16df6c5bd7 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Wed, 22 Aug 2018 01:31:24 +0300 Subject: [PATCH 46/80] path for when can't retrieve items from item check list --- CraftingGUI.cs | 8 +++++--- UIButtonChoice.cs | 4 ++++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 31b9d426..0d86cc33 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -32,6 +32,7 @@ public static class CraftingGUI static HashSet threadCheckListFoundItems; static Mod _checkListMod; + static volatile bool wasItemChecklistRetrieved; public static MouseState curMouse; public static MouseState oldMouse; @@ -398,7 +399,7 @@ private static void InitRecipeButtons() Language.GetText("Mods.MagicStorage.ShowOnlyFavorited"), Language.GetText("Mods.MagicStorage.RecipeBlacklist"), - }); + }) { Choice = 1 }; } } @@ -906,7 +907,8 @@ static IEnumerable RetrieveFoundItemsCheckList() _checkListMod = ModLoader.GetMod("ItemChecklist"); var foundItems = _checkListMod != null ? _checkListMod.Call("RequestFoundItems") as bool[] : new bool[0]; - return foundItems.Select((v, type) => new { WasFound = v, type }).Where(x => x.WasFound).Select(x => x.type); + if (foundItems.Length > 0) wasItemChecklistRetrieved = true; + return foundItems.Select((v, type) => new { WasFound = v, type }).Where(x => x.WasFound).Select(x => x.type); } static void EnsureProductToRecipesInited() @@ -1033,7 +1035,7 @@ private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craf // show only favorited items if selected .Where(x => (recipeButtons.Choice != RecipeButtonsFavoritesChoice) || favorited.Contains(x.createItem.type)) // hard check if this item can be crafted from available items and their recursive products - .Where(x => IsKnownRecursively(x, availableItemsMutable, temp, tempCache)) + .Where(x => !wasItemChecklistRetrieved || IsKnownRecursively(x, availableItemsMutable, temp, tempCache)) .OrderBy(x => favorited.Contains(x.createItem.type) ? 0 : 1); threadRecipes.Clear(); diff --git a/UIButtonChoice.cs b/UIButtonChoice.cs index 655df92f..f541cd13 100644 --- a/UIButtonChoice.cs +++ b/UIButtonChoice.cs @@ -27,6 +27,10 @@ public int Choice { return choice; } + set + { + choice = value; + } } public UIButtonChoice(Action onChanged, Texture2D[] buttons, LocalizedText[] names, int buttonSize = 21, int buttonPadding = 1) From 484dc6b5ffe22bfb25d10fbc694ffb915b3b97fb Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Wed, 22 Aug 2018 01:32:45 +0300 Subject: [PATCH 47/80] don't reset search settings when closing --- StoragePlayer.cs | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/StoragePlayer.cs b/StoragePlayer.cs index 2999db11..9b401ddf 100644 --- a/StoragePlayer.cs +++ b/StoragePlayer.cs @@ -125,16 +125,6 @@ public void CloseStorage() { storageAccess = new Point16(-1, -1); Main.blockInput = false; - if (StorageGUI.searchBar != null) - { - StorageGUI.searchBar.Reset(); - } - if (CraftingGUI.searchBar != null) - { - CraftingGUI.searchBar.Reset(); - } - CraftingGUI.modSearchBox.Reset(true); - StorageGUI.modSearchBox.Reset(true); } public Point16 ViewingStorage() From 5f91687ecb99bef406fa3232e035241efe9208aa Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Wed, 22 Aug 2018 01:52:30 +0300 Subject: [PATCH 48/80] and again more crafting station as I already reached limit :)... also disabled shift+clicking to deposit crafting station because I sometimes misuse it when I want to deposit to storage --- Components/TECraftingAccess.cs | 8 ++++++-- CraftingGUI.cs | 18 +++++------------- StoragePlayer.cs | 21 ++++++++++++--------- 3 files changed, 23 insertions(+), 24 deletions(-) diff --git a/Components/TECraftingAccess.cs b/Components/TECraftingAccess.cs index fc29e202..979c4f76 100644 --- a/Components/TECraftingAccess.cs +++ b/Components/TECraftingAccess.cs @@ -13,11 +13,15 @@ namespace MagicStorage.Components { public class TECraftingAccess : TEStorageComponent { - public Item[] stations = new Item[30]; + public const int Rows = 3; + public const int ItemsPerRow = 15; + public const int ItemsTotal = Rows * ItemsPerRow; + + public Item[] stations = new Item[ItemsTotal]; public TECraftingAccess() { - for (int k = 0; k < 30; k++) + for (int k = 0; k < ItemsTotal; k++) { stations[k] = new Item(); } diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 0d86cc33..5e616269 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -67,7 +67,6 @@ public static bool RightMouseClicked private static UIText stationText; private static UISlotZone stationZone = new UISlotZone(HoverStation, GetStation, inventoryScale / 1.55f); - private static UIText recipeText; private static UISlotZone recipeZone = new UISlotZone(HoverRecipe, GetRecipe, inventoryScale); internal static UIScrollbar scrollBar = new UIScrollbar(); @@ -220,16 +219,13 @@ public static void Initialize() stationZone.Width.Set(0f, 1f); stationZone.Top.Set(100f, 0f); - stationZone.Height.Set(90f, 0f); - stationZone.SetDimensions(15, 2); + stationZone.Height.Set(110f, 0f); + stationZone.SetDimensions(15, 3); basePanel.Append(stationZone); - - recipeText.Top.Set(152f, 0f); - basePanel.Append(recipeText); - + recipeZone.Width.Set(0f, 1f); - recipeZone.Top.Set(176f, 0f); - recipeZone.Height.Set(-216f, 1f); + recipeZone.Top.Set(196f, 0f); + recipeZone.Height.Set(-196f, 1f); basePanel.Append(recipeZone); numRows = (recipes.Count + numColumns - 1) / numColumns; @@ -338,10 +334,6 @@ private static void InitLangStuff() { stationText = new UIText(Language.GetText("Mods.MagicStorage.CraftingStations")); } - if (recipeText == null) - { - recipeText = new UIText(Language.GetText("Mods.MagicStorage.Recipes")); - } if (capacityText == null) { capacityText = new UIText("Items"); diff --git a/StoragePlayer.cs b/StoragePlayer.cs index 9b401ddf..e7e58a38 100644 --- a/StoragePlayer.cs +++ b/StoragePlayer.cs @@ -180,15 +180,18 @@ public override bool ShiftClickSlot(Item[] inventory, int context, int slot) int oldStack = item.stack; if (StorageCrafting()) { - if (Main.netMode == 0) - { - GetCraftingAccess().TryDepositStation(item); - } - else - { - NetHelper.SendDepositStation(GetCraftingAccess().ID, item); - item.SetDefaults(0, true); - } + if (false) + { + if (Main.netMode == 0) + { + GetCraftingAccess().TryDepositStation(item); + } + else + { + NetHelper.SendDepositStation(GetCraftingAccess().ID, item); + item.SetDefaults(0, true); + } + } } else { From 0ad1fb525b6ed94823db8f235e5f5278d74baa59 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Wed, 22 Aug 2018 02:26:10 +0300 Subject: [PATCH 49/80] version --- build.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.txt b/build.txt index 9553df57..30f9257d 100644 --- a/build.txt +++ b/build.txt @@ -1,5 +1,5 @@ author = blushiemagic and wvlad -version = 0.4.100.0 +version = 0.4.100.1 displayName = Magic Storage homepage = https://forums.terraria.org/index.php?threads/magic-storage.56294/ hideCode = false From b1e5db259572a9d3f276bf56690a96a9f4b28b13 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Wed, 22 Aug 2018 13:20:12 +0300 Subject: [PATCH 50/80] recipes that require unknown crafting stations are considered unknown too --- CraftingGUI.cs | 18 ++++++++++++ MagicStorage.cs | 2 +- StorageWorld.cs | 75 +++++++++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 92 insertions(+), 3 deletions(-) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 5e616269..f05c7a0f 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -929,6 +929,24 @@ static bool IsKnownRecursively(Recipe recipe, HashSet availableSet, HashSet { bool v; if (cache.TryGetValue(recipe, out v)) return v; + + + foreach (int tile in recipe.requiredTile) + { + if (tile == -1) + break; + + List possibleItems; + if (!StorageWorld.TileToCreatingItem.TryGetValue(tile, out possibleItems)) + continue; + + if (!possibleItems.Any(x => IsKnownRecursively_CheckIngredient(x, availableSet, recursionTree, cache))) + { + cache[recipe] = false; + return false; + } + } + int ingredients = 0; for (int i = 0; i < Recipe.maxRequirements; i++) { diff --git a/MagicStorage.cs b/MagicStorage.cs index 12a1f2da..95b0eb65 100644 --- a/MagicStorage.cs +++ b/MagicStorage.cs @@ -260,7 +260,7 @@ private void AddTranslations() text.SetDefault(" !UNTIL RESPAWN!"); AddTranslation(text); } - + public override void PostSetupContent() { diff --git a/StorageWorld.cs b/StorageWorld.cs index 7d78f467..1a945be9 100644 --- a/StorageWorld.cs +++ b/StorageWorld.cs @@ -1,5 +1,8 @@ using System.IO; using System.Collections.Generic; +using System.Linq; +using System.Threading; +using MagicStorage.Items; using Terraria; using Terraria.ID; using Terraria.ModLoader; @@ -24,6 +27,7 @@ public class StorageWorld : ModWorld public static bool fishronDiamond = false; public static bool ancientCultistDiamond = false; public static bool moonlordDiamond = false; + public static Dictionary> TileToCreatingItem = new Dictionary>(); public override void Initialize() { @@ -63,8 +67,8 @@ public override TagCompound Save() tag["moonlordDiamond"] = moonlordDiamond; return tag; } - - public override void Load(TagCompound tag) + + public override void Load(TagCompound tag) { kingSlimeDiamond = tag.GetBool("kingSlimeDiamond"); boss1Diamond = tag.GetBool("boss1Diamond"); @@ -80,6 +84,73 @@ public override void Load(TagCompound tag) fishronDiamond = tag.GetBool("fishronDiamond"); ancientCultistDiamond = tag.GetBool("ancientCultistDiamond"); moonlordDiamond = tag.GetBool("moonlordDiamond"); + + Volatile.Write(ref TileToCreatingItem, new Dictionary>()); // used from threaded RefreshRecipes } + + public override void PostUpdate() + { + if (TileToCreatingItem.Count == 0) + { + #region Initialize TileToCreatingItem + + var tileToCreatingItem = Enumerable.Range(0, 10000 + MagicStorage.Instance.ItemType()).Select((x, i) => + { + var item = new Item(); + // provide items + try + { + item.SetDefaults(i, true); + } + catch + { + item.SetDefaults(); + } + + return item; + }) + .Where(x => x.type > 0 && x.createTile >= 0) + .Select(x => + { + // provide item and its tiles + var tiles = new List { x.createTile }; + if (x.createTile == TileID.GlassKiln || x.createTile == TileID.Hellforge || x.createTile == TileID.AdamantiteForge) + { + tiles.Add(TileID.Furnaces); + } + + if (x.createTile == TileID.AdamantiteForge) + { + tiles.Add(TileID.Hellforge); + } + + if (x.createTile == TileID.MythrilAnvil) + { + tiles.Add(TileID.Anvils); + } + + if (x.createTile == TileID.BewitchingTable || x.createTile == TileID.Tables2) + { + tiles.Add(TileID.Tables); + } + + if (x.createTile == TileID.AlchemyTable) + { + tiles.Add(TileID.Bottles); + tiles.Add(TileID.Tables); + } + + return new { item = x, tiles = tiles }; + }) + // flatten - tile, item + .SelectMany(x => x.tiles.Select(t => new { tile = t, x.item })) + .GroupBy(x => x.tile) + .ToDictionary(x => x.Key, x => x.Select(y => y.item.type).ToList()); + + Volatile.Write(ref TileToCreatingItem, tileToCreatingItem); + + #endregion + } + } } } From f197a308a8fe81381696f0d5d922deca78b2560f Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Wed, 22 Aug 2018 13:21:49 +0300 Subject: [PATCH 51/80] removed mirror from summon category --- Sorting/ItemFilter.cs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/Sorting/ItemFilter.cs b/Sorting/ItemFilter.cs index 6ab49abd..6b010498 100644 --- a/Sorting/ItemFilter.cs +++ b/Sorting/ItemFilter.cs @@ -63,7 +63,17 @@ public class FilterWeaponSummon : ItemFilter { public override bool Passes(Item item) { - if (item.type == 109 || item.type == 29) return false; // mana or heart crystal + switch (item.type) + { + case 109:// mana or heart crystal + case 29: + case ItemID.CellPhone: + case ItemID.PDA: + case ItemID.MagicMirror: + case ItemID.IceMirror: + return false; + } + return item.summon || SortClassList.BossSpawn(item) || SortClassList.Cart(item) || SortClassList.LightPet(item) || SortClassList.Mount(item) || item.sentry; } } From 642cec46e5dd19933719548234f62011f464e284 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Thu, 23 Aug 2018 11:31:33 +0300 Subject: [PATCH 52/80] added hot key to check whether hovered item is known or new (I want to buy all new materials from npc) --- CraftingGUI.cs | 12 +++++++++++- MagicStorage.cs | 12 +++++++----- StoragePlayer.cs | 1 + 3 files changed, 19 insertions(+), 6 deletions(-) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index f05c7a0f..05213e60 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -405,6 +405,16 @@ private static void InitFilterButtons() public static void Update(GameTime gameTime) { + try + { + if (MagicStorage.IsItemKnownHotKey != null && MagicStorage.IsItemKnownHotKey.JustPressed && Main.HoverItem != null && !Main.HoverItem.IsAir) + Main.NewTextMultiline(Main.HoverItem.Name + " is " + (CraftingGUI.GetKnownItems().Contains(Main.HoverItem.type) ? "known" : "new")); + } + catch (KeyNotFoundException) + { + // ignore + } + try { oldMouse = StorageGUI.oldMouse; curMouse = StorageGUI.curMouse; @@ -871,7 +881,7 @@ public static void RefreshItems() } } - static HashSet GetKnownItems() + public static HashSet GetKnownItems() { HashSet a, b, c, d; GetKnownItems(out a, out b, out c, out d); diff --git a/MagicStorage.cs b/MagicStorage.cs index 95b0eb65..e12cda10 100644 --- a/MagicStorage.cs +++ b/MagicStorage.cs @@ -17,6 +17,7 @@ public class MagicStorage : Mod public static MagicStorage Instance; public static Mod bluemagicMod; public static Mod legendMod; + public static ModHotKey IsItemKnownHotKey { get; private set; } public static readonly Version requiredVersion = new Version(0, 9, 2, 2); @@ -32,6 +33,7 @@ public override void Load() bluemagicMod = ModLoader.GetMod("Bluemagic"); AddTranslations(); AddGlobalItem("MagicStorageItemSaveLoadHook", new ItemSaveLoadHook()); + IsItemKnownHotKey = RegisterHotKey("Is This Item Known?", ""); } public override void Unload() @@ -354,11 +356,11 @@ public override void ModifyInterfaceLayers(List layers) InterfaceHelper.ModifyInterfaceLayers(layers); } - public override void PostUpdateInput() - { - StorageGUI.Update(null); - CraftingGUI.Update(null); - } + public override void PostUpdateInput() + { + StorageGUI.Update(null); + CraftingGUI.Update(null); + } } } diff --git a/StoragePlayer.cs b/StoragePlayer.cs index e7e58a38..64df8e93 100644 --- a/StoragePlayer.cs +++ b/StoragePlayer.cs @@ -6,6 +6,7 @@ using Terraria.ModLoader; using Terraria.UI; using MagicStorage.Components; +using Terraria.GameInput; using Terraria.ID; using Terraria.ModLoader.IO; From e77025be7039147a7ee1403e6675c09b18720cab Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Thu, 23 Aug 2018 12:26:14 +0300 Subject: [PATCH 53/80] don't reset selected recipe on close --- CraftingGUI.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 05213e60..7c3d11ce 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -434,7 +434,6 @@ public static void Update(GameTime gameTime) else { scrollBarFocus = 0; - selectedRecipe = null; craftTimer = 0; maxCraftTimer = startMaxCraftTimer; ResetSlotFocus(); From 768d1b38a641ead51379504ae63eebbf268aaafe Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Thu, 23 Aug 2018 12:58:33 +0300 Subject: [PATCH 54/80] don't reset scroll bar in storage --- StorageGUI.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/StorageGUI.cs b/StorageGUI.cs index e66655a9..862e98cc 100644 --- a/StorageGUI.cs +++ b/StorageGUI.cs @@ -232,7 +232,6 @@ public static void Update(GameTime gameTime) else { scrollBarFocus = false; - scrollBar.ViewPosition = 0f; ResetSlotFocus(); } } From 57069b41c8a4e6ab155184d9ef6077339092631f Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Thu, 23 Aug 2018 20:17:31 +0300 Subject: [PATCH 55/80] multiplayer fix --- Components/TECraftingAccess.cs | 4 +-- Components/TEStorageUnit.cs | 23 ++++++++++------ NetHelper.cs | 50 +++++++++++++++++----------------- StorageGUI.cs | 17 +++++++++--- 4 files changed, 55 insertions(+), 39 deletions(-) diff --git a/Components/TECraftingAccess.cs b/Components/TECraftingAccess.cs index 979c4f76..18c15bcd 100644 --- a/Components/TECraftingAccess.cs +++ b/Components/TECraftingAccess.cs @@ -148,7 +148,7 @@ public override void NetSend(BinaryWriter writer, bool lightSend) { foreach (Item item in stations) { - ItemIO.Send(item, writer, true, false); + ItemIO.Send(item, writer, true, true); } } @@ -156,7 +156,7 @@ public override void NetReceive(BinaryReader reader, bool lightReceive) { for (int k = 0; k < stations.Length; k++) { - stations[k] = ItemIO.Receive(reader, true, false); + stations[k] = ItemIO.Receive(reader, true, true); } } } diff --git a/Components/TEStorageUnit.cs b/Components/TEStorageUnit.cs index 1a9abb04..2dde376a 100644 --- a/Components/TEStorageUnit.cs +++ b/Components/TEStorageUnit.cs @@ -238,7 +238,9 @@ public override Item TryWithdraw(Item lookFor, bool locked = false, bool keepOne { if (Main.netMode == 2) { - netQueue.Enqueue(UnitOperation.Withdraw.Create(original)); + var op = (WithdrawOperation)UnitOperation.Withdraw.Create(original); + op.SendKeepOneIfFavorite = keepOneIfFavorite; + netQueue.Enqueue(op); } PostChangeContents(); } @@ -254,7 +256,9 @@ public override Item TryWithdraw(Item lookFor, bool locked = false, bool keepOne { if (Main.netMode == 2) { - netQueue.Enqueue(UnitOperation.Withdraw.Create(original)); + var op = (WithdrawOperation)UnitOperation.Withdraw.Create(original); + op.SendKeepOneIfFavorite = keepOneIfFavorite; + netQueue.Enqueue(op); } PostChangeContents(); } @@ -576,7 +580,7 @@ protected override void SendData(BinaryWriter writer, TEStorageUnit unit) writer.Write(unit.items.Count); foreach (Item item in unit.items) { - ItemIO.Send(item, writer, true, false); + ItemIO.Send(item, writer, true, true); } } @@ -586,7 +590,7 @@ protected override bool ReceiveData(BinaryReader reader, TEStorageUnit unit) int count = reader.ReadInt32(); for (int k = 0; k < count; k++) { - Item item = ItemIO.Receive(reader, true, false); + Item item = ItemIO.Receive(reader, true, true); unit.items.Add(item); ItemData data = new ItemData(item); if (item.stack < item.maxStack) @@ -604,27 +608,30 @@ class DepositOperation : UnitOperation { protected override void SendData(BinaryWriter writer, TEStorageUnit unit) { - ItemIO.Send(data, writer, true, false); + ItemIO.Send(data, writer, true, true); } protected override bool ReceiveData(BinaryReader reader, TEStorageUnit unit) { - unit.DepositItem(ItemIO.Receive(reader, true, false)); + unit.DepositItem(ItemIO.Receive(reader, true, true)); return true; } } class WithdrawOperation : UnitOperation { + public bool SendKeepOneIfFavorite { get; set; } + protected override void SendData(BinaryWriter writer, TEStorageUnit unit) { - ItemIO.Send(data, writer, true, false); + writer.Write(SendKeepOneIfFavorite); + ItemIO.Send(data, writer, true, true); } protected override bool ReceiveData(BinaryReader reader, TEStorageUnit unit) { bool keepOneIfFavorite = reader.ReadBoolean(); - unit.TryWithdraw(ItemIO.Receive(reader, true, false), keepOneIfFavorite: keepOneIfFavorite); + unit.TryWithdraw(ItemIO.Receive(reader, true, true), keepOneIfFavorite: keepOneIfFavorite); return true; } } diff --git a/NetHelper.cs b/NetHelper.cs index fba93dc9..3b152b8e 100644 --- a/NetHelper.cs +++ b/NetHelper.cs @@ -148,7 +148,7 @@ public static void SendDeposit(int ent, Item item) if (Main.netMode == 1) { ModPacket packet = PrepareStorageOperation(ent, 0); - ItemIO.Send(item, packet, true); + ItemIO.Send(item, packet, true, true); packet.Send(); } } @@ -159,7 +159,7 @@ public static void SendWithdraw(int ent, Item item, bool toInventory = false, bo { ModPacket packet = PrepareStorageOperation(ent, (byte)(toInventory ? 3 : 1)); packet.Write(keepOneIfFavorite); - ItemIO.Send(item, packet, true); + ItemIO.Send(item, packet, true, true); packet.Send(); } } @@ -172,7 +172,7 @@ public static void SendDepositAll(int ent, List items) packet.Write((byte)items.Count); foreach (Item item in items) { - ItemIO.Send(item, packet, true); + ItemIO.Send(item, packet, true, true); } packet.Send(); } @@ -193,24 +193,24 @@ public static void ReceiveStorageOperation(BinaryReader reader, int sender) byte op = reader.ReadByte(); if (op == 0) { - Item item = ItemIO.Receive(reader, true); + Item item = ItemIO.Receive(reader, true, true); heart.DepositItem(item); if (!item.IsAir) { ModPacket packet = PrepareOperationResult(op); - ItemIO.Send(item, packet, true); + ItemIO.Send(item, packet, true, true); packet.Send(sender); } } else if (op == 1 || op == 3) { var keepOneIfFavorite = reader.ReadBoolean(); - Item item = ItemIO.Receive(reader, true); + Item item = ItemIO.Receive(reader, true, true); item = heart.TryWithdraw(item, keepOneIfFavorite); if (!item.IsAir) { ModPacket packet = PrepareOperationResult(op); - ItemIO.Send(item, packet, true); + ItemIO.Send(item, packet, true, true); packet.Send(sender); } } @@ -221,7 +221,7 @@ public static void ReceiveStorageOperation(BinaryReader reader, int sender) StartUpdateQueue(); for (int k = 0; k < count; k++) { - Item item = ItemIO.Receive(reader, true); + Item item = ItemIO.Receive(reader, true, true); heart.DepositItem(item); if (!item.IsAir) { @@ -235,7 +235,7 @@ public static void ReceiveStorageOperation(BinaryReader reader, int sender) packet.Write((byte)items.Count); foreach (Item item in items) { - ItemIO.Send(item, packet, true); + ItemIO.Send(item, packet, true, true); } packet.Send(sender); } @@ -253,7 +253,7 @@ public static void ReceiveOperationResult(BinaryReader reader) byte op = reader.ReadByte(); if (op == 0 || op == 1 || op == 3) { - Item item = ItemIO.Receive(reader, true); + Item item = ItemIO.Receive(reader, true, true); StoragePlayer.GetItem(item, op != 3); } else if (op == 2) @@ -261,7 +261,7 @@ public static void ReceiveOperationResult(BinaryReader reader) int count = reader.ReadByte(); for (int k = 0; k < count; k++) { - Item item = ItemIO.Receive(reader, true); + Item item = ItemIO.Receive(reader, true, true); StoragePlayer.GetItem(item, false); } } @@ -333,7 +333,7 @@ public static void SendDepositStation(int ent, Item item) if (Main.netMode == 1) { ModPacket packet = PrepareStationOperation(ent, 0); - ItemIO.Send(item, packet, true); + ItemIO.Send(item, packet, true, true); packet.Send(); } } @@ -353,7 +353,7 @@ public static void SendStationSlotClick(int ent, Item item, int slot) if (Main.netMode == 1) { ModPacket packet = PrepareStationOperation(ent, 2); - ItemIO.Send(item, packet, true); + ItemIO.Send(item, packet, true, true); packet.Write((byte)slot); packet.Send(); } @@ -375,12 +375,12 @@ public static void ReceiveStationOperation(BinaryReader reader, int sender) byte op = reader.ReadByte(); if (op == 0) { - Item item = ItemIO.Receive(reader, true); + Item item = ItemIO.Receive(reader, true, true); access.TryDepositStation(item); if (item.stack > 0) { ModPacket packet = PrepareStationResult(op); - ItemIO.Send(item, packet, true); + ItemIO.Send(item, packet, true, true); packet.Send(sender); } } @@ -391,19 +391,19 @@ public static void ReceiveStationOperation(BinaryReader reader, int sender) if (!item.IsAir) { ModPacket packet = PrepareStationResult(op); - ItemIO.Send(item, packet, true); + ItemIO.Send(item, packet, true, true); packet.Send(sender); } } else if (op == 2) { - Item item = ItemIO.Receive(reader, true); + Item item = ItemIO.Receive(reader, true, true); int slot = reader.ReadByte(); item = access.DoStationSwap(item, slot); if (!item.IsAir) { ModPacket packet = PrepareStationResult(op); - ItemIO.Send(item, packet, true); + ItemIO.Send(item, packet, true, true); packet.Send(sender); } } @@ -427,7 +427,7 @@ public static void ReceiveStationResult(BinaryReader reader) } Player player = Main.player[Main.myPlayer]; byte op = reader.ReadByte(); - Item item = ItemIO.Receive(reader, true); + Item item = ItemIO.Receive(reader, true, true); if (op == 2 && Main.playerInventory && Main.mouseItem.IsAir) { Main.mouseItem = item; @@ -487,9 +487,9 @@ public static void SendCraftRequest(int heart, List toWithdraw, Item resul packet.Write(toWithdraw.Count); foreach (Item item in toWithdraw) { - ItemIO.Send(item, packet, true); + ItemIO.Send(item, packet, true, true); } - ItemIO.Send(result, packet, true); + ItemIO.Send(result, packet, true, true); packet.Send(); } } @@ -510,9 +510,9 @@ public static void ReceiveCraftRequest(BinaryReader reader, int sender) List toWithdraw = new List(); for (int k = 0; k < count; k++) { - toWithdraw.Add(ItemIO.Receive(reader, true)); + toWithdraw.Add(ItemIO.Receive(reader, true, true)); } - Item result = ItemIO.Receive(reader, true); + Item result = ItemIO.Receive(reader, true, true); List items = CraftingGUI.DoCraft(heart, toWithdraw, result); if (items.Count > 0) { @@ -521,7 +521,7 @@ public static void ReceiveCraftRequest(BinaryReader reader, int sender) packet.Write(items.Count); foreach (Item item in items) { - ItemIO.Send(item, packet, true); + ItemIO.Send(item, packet, true, true); } packet.Send(sender); } @@ -534,7 +534,7 @@ public static void ReceiveCraftResult(BinaryReader reader) int count = reader.ReadInt32(); for (int k = 0; k < count; k++) { - Item item = ItemIO.Receive(reader, true); + Item item = ItemIO.Receive(reader, true, true); player.QuickSpawnClonedItem(item, item.stack); } } diff --git a/StorageGUI.cs b/StorageGUI.cs index 862e98cc..750179c7 100644 --- a/StorageGUI.cs +++ b/StorageGUI.cs @@ -12,6 +12,7 @@ using Terraria.UI; using MagicStorage.Components; using MagicStorage.Sorting; +using Terraria.ID; namespace MagicStorage { @@ -443,10 +444,18 @@ private static void HoverItemSlot(int slot, ref int hoverSlot) } } else if (Main.mouseItem.IsAir && slot < items.Count && !items[slot].IsAir) - { - if (Main.keyState.IsKeyDown(Keys.LeftAlt)) - items[slot].favorited = !items[slot].favorited; - else + { + if (Main.keyState.IsKeyDown(Keys.LeftAlt)) + { + if (Main.netMode == NetmodeID.SinglePlayer) + items[slot].favorited = !items[slot].favorited; + else + Main.NewTextMultiline("TOggling item as favorite is not implemented in multiplayer but you can withdraw this item, toggle it in inventory and deposit again"); + // there is no item instance id and there is no concept of slot # in heart so we can't send this in operation + // a workaropund would be to withdraw and deposit it back with changed favorite flag + // but it still might look ugly for the player that initiates operation + } + else { Item toWithdraw = items[slot].Clone(); if (toWithdraw.stack > toWithdraw.maxStack) From 4d9c29731299c4b61a012f32caa84b6c613d4d18 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Thu, 23 Aug 2018 20:32:32 +0300 Subject: [PATCH 56/80] Fixes #53 (#58) (reverted from commit 2f468406bc88fc04a3b5aebe78c786b397334c6f) --- CraftingGUI.cs | 19 ++++--------------- MagicStorage.cs | 2 -- StorageGUI.cs | 15 +++------------ 3 files changed, 7 insertions(+), 29 deletions(-) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 6baf4aa6..3f287ba6 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -36,17 +36,17 @@ public static bool MouseClicked } } - private static UIPanel basePanel; + private static UIPanel basePanel = new UIPanel(); private static float panelTop; private static float panelLeft; private static float panelWidth; private static float panelHeight; - private static UIElement topBar; + private static UIElement topBar = new UIElement(); internal static UISearchBar searchBar; private static UIButtonChoice sortButtons; private static UIButtonChoice recipeButtons; - private static UIElement topBar2; + private static UIElement topBar2 = new UIElement(); private static UIButtonChoice filterButtons; internal static UISearchBar searchBar2; @@ -80,7 +80,7 @@ public static bool MouseClicked private static UIElement bottomBar = new UIElement(); private static UIText capacityText; - private static UIPanel recipePanel; + private static UIPanel recipePanel = new UIPanel(); private static float recipeTop; private static float recipeLeft; private static float recipeWidth; @@ -141,7 +141,6 @@ public static void Initialize() panelTop = Main.instance.invBottom + 60; panelLeft = 20f; - basePanel = new UIPanel(); float innerPanelLeft = panelLeft + basePanel.PaddingLeft; float innerPanelWidth = numColumns * (itemSlotWidth + padding) + 20f + padding; panelWidth = basePanel.PaddingLeft + innerPanelWidth + basePanel.PaddingRight; @@ -152,7 +151,6 @@ public static void Initialize() basePanel.Height.Set(panelHeight, 0f); basePanel.Recalculate(); - recipePanel = new UIPanel(); recipeTop = panelTop; recipeLeft = panelLeft + panelWidth; recipeWidth = numColumns2 * (smallSlotWidth + padding) + 20f + padding; @@ -164,7 +162,6 @@ public static void Initialize() recipePanel.Height.Set(recipeHeight, 0f); recipePanel.Recalculate(); - topBar = new UIElement(); topBar.Width.Set(0f, 1f); topBar.Height.Set(32f, 0f); basePanel.Append(topBar); @@ -183,7 +180,6 @@ public static void Initialize() searchBar.Height.Set(0f, 1f); topBar.Append(searchBar); - topBar2 = new UIElement(); topBar2.Width.Set(0f, 1f); topBar2.Height.Set(32f, 0f); topBar2.Top.Set(36f, 0f); @@ -351,13 +347,6 @@ private static void InitLangStuff() } } - internal static void Unload() - { - sortButtons = null; - filterButtons = null; - recipeButtons = null; - } - private static void InitSortButtons() { if (sortButtons == null) diff --git a/MagicStorage.cs b/MagicStorage.cs index 9dff4b75..82915e78 100644 --- a/MagicStorage.cs +++ b/MagicStorage.cs @@ -36,8 +36,6 @@ public override void Unload() Instance = null; bluemagicMod = null; legendMod = null; - StorageGUI.Unload(); - CraftingGUI.Unload(); } private void AddTranslations() diff --git a/StorageGUI.cs b/StorageGUI.cs index 8896ad12..54e27558 100644 --- a/StorageGUI.cs +++ b/StorageGUI.cs @@ -30,17 +30,17 @@ public static bool MouseClicked } } - private static UIPanel basePanel; + private static UIPanel basePanel = new UIPanel(); private static float panelTop; private static float panelLeft; private static float panelWidth; private static float panelHeight; - private static UIElement topBar; + private static UIElement topBar = new UIElement(); internal static UISearchBar searchBar; private static UIButtonChoice sortButtons; internal static UITextPanel depositButton; - private static UIElement topBar2; + private static UIElement topBar2 = new UIElement(); private static UIButtonChoice filterButtons; internal static UISearchBar searchBar2; @@ -73,7 +73,6 @@ public static void Initialize() panelTop = Main.instance.invBottom + 60; panelLeft = 20f; - basePanel = new UIPanel(); float innerPanelLeft = panelLeft + basePanel.PaddingLeft; float innerPanelWidth = numColumns * (itemSlotWidth + padding) + 20f + padding; panelWidth = basePanel.PaddingLeft + innerPanelWidth + basePanel.PaddingRight; @@ -84,7 +83,6 @@ public static void Initialize() basePanel.Height.Set(panelHeight, 0f); basePanel.Recalculate(); - topBar = new UIElement(); topBar.Width.Set(0f, 1f); topBar.Height.Set(32f, 0f); basePanel.Append(topBar); @@ -105,7 +103,6 @@ public static void Initialize() searchBar.Height.Set(0f, 1f); topBar.Append(searchBar); - topBar2 = new UIElement(); topBar2.Width.Set(0f, 1f); topBar2.Height.Set(32f, 0f); topBar2.Top.Set(36f, 0f); @@ -183,12 +180,6 @@ private static void InitLangStuff() } } - internal static void Unload() - { - sortButtons = null; - filterButtons = null; - } - private static void InitSortButtons() { if (sortButtons == null) From a4f5aa5dde7ecb5a4a98e05cbf969a2873fc4ee4 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Thu, 23 Aug 2018 23:06:12 +0300 Subject: [PATCH 57/80] showing stored count when quering for known item --- Components/TEStorageHeart.cs | 9 ++++++++- CraftingGUI.cs | 15 ++++++++++++++- StoragePlayer.cs | 13 ++++++++----- 3 files changed, 30 insertions(+), 7 deletions(-) diff --git a/Components/TEStorageHeart.cs b/Components/TEStorageHeart.cs index 7fb11969..4a7b9bf1 100644 --- a/Components/TEStorageHeart.cs +++ b/Components/TEStorageHeart.cs @@ -20,7 +20,14 @@ public class TEStorageHeart : TEStorageCenter private int updateTimer = 60; private int compactStage = 0; - public override bool ValidTile(Tile tile) + public bool IsAlive { get; private set; } = true; + + public override void OnKill() + { + IsAlive = false; + } + + public override bool ValidTile(Tile tile) { return tile.type == mod.TileType("StorageHeart") && tile.frameX == 0 && tile.frameY == 0; } diff --git a/CraftingGUI.cs b/CraftingGUI.cs index b7b1fbc5..a9b96d6e 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -408,7 +408,20 @@ public static void Update(GameTime gameTime) try { if (MagicStorage.IsItemKnownHotKey != null && MagicStorage.IsItemKnownHotKey.JustPressed && Main.HoverItem != null && !Main.HoverItem.IsAir) - Main.NewTextMultiline(Main.HoverItem.Name + " is " + (CraftingGUI.GetKnownItems().Contains(Main.HoverItem.type) ? "known" : "new")); + { + var s = Main.HoverItem.Name + " is "; + var t = Main.HoverItem.type; + if (GetKnownItems().Contains(t)) + { + s += "known"; + var sum = ModPlayer.LatestAccessedStorage?.GetStoredItems().Where(x => x.type == t).Select(x => x.stack).DefaultIfEmpty().Sum() ?? 0; + if (sum > 0) + s += $" ({sum} in l.a.s.)"; + } + else + s += "new"; + Main.NewTextMultiline(s); + } } catch (KeyNotFoundException) { diff --git a/StoragePlayer.cs b/StoragePlayer.cs index 64df8e93..dde62dce 100644 --- a/StoragePlayer.cs +++ b/StoragePlayer.cs @@ -20,8 +20,8 @@ public class StoragePlayer : ModPlayer ItemTypeOrderedSet _hiddenRecipes = new ItemTypeOrderedSet("HiddenItems"); ItemTypeOrderedSet _craftedRecipes = new ItemTypeOrderedSet("CraftedRecipes"); - - public IEnumerable HiddenRecipes { get { return _hiddenRecipes.Items; } } + + public IEnumerable HiddenRecipes { get { return _hiddenRecipes.Items; } } public IEnumerable CraftedRecipes { get { return _craftedRecipes.Items; } } public ItemTypeOrderedSet FavoritedRecipes { get; private set; } = new ItemTypeOrderedSet("FavoritedRecipes"); @@ -114,11 +114,14 @@ public override void ResetEffects() } } } + + TEStorageHeart _latestAccessedStorage; + public TEStorageHeart LatestAccessedStorage => _latestAccessedStorage != null && _latestAccessedStorage.IsAlive ? _latestAccessedStorage : null; - public void OpenStorage(Point16 point, bool remote = false) + public void OpenStorage(Point16 point, bool remote = false) { - storageAccess = point; - remoteAccess = remote; + storageAccess = point;remoteAccess = remote; + _latestAccessedStorage = GetStorageHeart(); StorageGUI.RefreshItems(); } From 8e999c6b4bf5561fc4bae576a367f066a6617f19 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Fri, 24 Aug 2018 00:56:32 +0300 Subject: [PATCH 58/80] 0.4.100.2 --- build.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.txt b/build.txt index 30f9257d..712c68ca 100644 --- a/build.txt +++ b/build.txt @@ -1,5 +1,5 @@ author = blushiemagic and wvlad -version = 0.4.100.1 +version = 0.4.100.2 displayName = Magic Storage homepage = https://forums.terraria.org/index.php?threads/magic-storage.56294/ hideCode = false From 567a607bf46ea5f332b51a7cb1e0b40f16df90ca Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 26 Aug 2018 11:36:21 +0300 Subject: [PATCH 59/80] converting line endings to LF --- CraftingGUI.cs | 2 +- StorageGUI.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index a9b96d6e..f0206190 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -1851,4 +1851,4 @@ private static Item DoWithdrawResult(Item item, bool toInventory = false) } } } -} \ No newline at end of file +} \ No newline at end of file diff --git a/StorageGUI.cs b/StorageGUI.cs index de5a7dfd..477e9b6f 100644 --- a/StorageGUI.cs +++ b/StorageGUI.cs @@ -635,4 +635,4 @@ private static Item DoWithdraw(Item item, bool toInventory = false, bool keepOne } } } -} \ No newline at end of file +} \ No newline at end of file From 9594ceec9cbeec4d64e3109fb6a39d94d53afdce Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 26 Aug 2018 11:48:00 +0300 Subject: [PATCH 60/80] next attempts --- .gitattributes | 2 ++ StorageGUI.cs | 79 +++++++++++++++++++++++++------------------------- 2 files changed, 42 insertions(+), 39 deletions(-) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..18f23676 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +[code] +* text=auto diff --git a/StorageGUI.cs b/StorageGUI.cs index 477e9b6f..e3d85212 100644 --- a/StorageGUI.cs +++ b/StorageGUI.cs @@ -45,10 +45,10 @@ public static bool MouseClicked internal static UITextPanel depositButton; internal static UITextPanel restockButton; private static UIElement topBar2 = new UIElement(); - private static UIButtonChoice filterButtons; - - public static readonly ModSearchBox modSearchBox = new ModSearchBox(RefreshItems); - + private static UIButtonChoice filterButtons; + + public static readonly ModSearchBox modSearchBox = new ModSearchBox(RefreshItems); + private static UISlotZone slotZone = new UISlotZone(HoverItemSlot, GetItem, inventoryScale); private static int slotFocus = -1; private static int rightClickTimer = 0; @@ -106,10 +106,10 @@ public static void Initialize() depositButton.Height.Set(-2 * padding, 1f); depositButton.PaddingTop = 8f; depositButton.PaddingBottom = 8f; - topBar.Append(depositButton); - + topBar.Append(depositButton); + x += depositButton.GetDimensions().Width; - + float depositButtonRight = x; searchBar.Left.Set(depositButtonRight + padding, 0f); searchBar.Width.Set(-depositButtonRight - 2 * padding, 1f); @@ -175,7 +175,7 @@ public static void Initialize() } capacityText.SetText(numItems + "/" + capacity + " Items"); bottomBar.Append(capacityText); - + } private static void InitLangStuff() @@ -403,7 +403,7 @@ private static void UpdateDepositButton() { RefreshItems(); Main.PlaySound(7, -1, -1, 1); - } + } } } else @@ -414,10 +414,10 @@ private static void UpdateDepositButton() private static void DrawDepositButton() { - Rectangle dim = InterfaceHelper.GetFullRectangle(depositButton); - if (curMouse.X > dim.X && curMouse.X < dim.X + dim.Width && curMouse.Y > dim.Y && curMouse.Y < dim.Y + dim.Height) + Rectangle dim = InterfaceHelper.GetFullRectangle(depositButton); + if (curMouse.X > dim.X && curMouse.X < dim.X + dim.Width && curMouse.Y > dim.Y && curMouse.Y < dim.Y + dim.Height) { - Main.instance.MouseText(Language.GetText("Mods.MagicStorage.DepositTooltip").Value); + Main.instance.MouseText(Language.GetText("Mods.MagicStorage.DepositTooltip").Value); } } @@ -432,8 +432,8 @@ private static void HoverItemSlot(int slot, ref int hoverSlot) { Player player = Main.player[Main.myPlayer]; int visualSlot = slot; - slot += numColumns * (int)Math.Round(scrollBar.ViewPosition); - + slot += numColumns * (int)Math.Round(scrollBar.ViewPosition); + if (MouseClicked) { bool changed = false; @@ -456,19 +456,19 @@ private static void HoverItemSlot(int slot, ref int hoverSlot) // a workaropund would be to withdraw and deposit it back with changed favorite flag // but it still might look ugly for the player that initiates operation } - else - { - Item toWithdraw = items[slot].Clone(); - if (toWithdraw.stack > toWithdraw.maxStack) - { - toWithdraw.stack = toWithdraw.maxStack; - } - Main.mouseItem = DoWithdraw(toWithdraw, ItemSlot.ShiftInUse); - if (ItemSlot.ShiftInUse) - { - Main.mouseItem = player.GetItem(Main.myPlayer, Main.mouseItem, false, true); - } - changed = true; + else + { + Item toWithdraw = items[slot].Clone(); + if (toWithdraw.stack > toWithdraw.maxStack) + { + toWithdraw.stack = toWithdraw.maxStack; + } + Main.mouseItem = DoWithdraw(toWithdraw, ItemSlot.ShiftInUse); + if (ItemSlot.ShiftInUse) + { + Main.mouseItem = player.GetItem(Main.myPlayer, Main.mouseItem, false, true); + } + changed = true; } } if (changed) @@ -485,9 +485,9 @@ private static void HoverItemSlot(int slot, ref int hoverSlot) if (slot < items.Count && !items[slot].IsAir) { - hoverSlot = visualSlot; + hoverSlot = visualSlot; items[slot].newAndShiny = false; - + } if (slotFocus >= 0) @@ -594,14 +594,14 @@ private static bool TryDepositAll(bool quickStack) changed = true; } return changed; - } - - private static bool TryRestock() - { - Player player = Main.player[Main.myPlayer]; - TEStorageHeart heart = GetHeart(); - bool changed = false; - + } + + private static bool TryRestock() + { + Player player = Main.player[Main.myPlayer]; + TEStorageHeart heart = GetHeart(); + bool changed = false; + foreach (var item in player.inventory) { if (item != null && !item.IsAir && item.stack < item.maxStack) @@ -618,7 +618,7 @@ private static bool TryRestock() } } - return changed; + return changed; } private static Item DoWithdraw(Item item, bool toInventory = false, bool keepOneIfFavorite = false) @@ -634,5 +634,6 @@ private static Item DoWithdraw(Item item, bool toInventory = false, bool keepOne return new Item(); } } + } -} \ No newline at end of file +} \ No newline at end of file From 971bffb449e69db093372d9b19977868b2f9764f Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 26 Aug 2018 11:57:56 +0300 Subject: [PATCH 61/80] next attempt --- Components/CraftingAccess.cs | 2 +- Components/CreativeStorageUnit.cs | 2 +- Components/TEAbstractStorageUnit.cs | 2 +- Components/TECraftingAccess.cs | 326 +-- Components/TECreativeStorageUnit.cs | 2 +- Components/TEStorageHeart.cs | 16 +- Components/TEStorageUnit.cs | 5 +- CraftingGUI.cs | 3708 +++++++++++++-------------- DpsTooltips.cs | 34 +- GUIHelpers.cs | 148 +- ItemSaveLoadHook.cs | 64 +- ItemTypeOrderedSet.cs | 224 +- Items/CraftingAccess.cs | 1 + Items/Locator.cs | 1 + Items/LocatorDisk.cs | 1 + Items/PortableAccess.cs | 1 + Items/RemoteAccess.cs | 1 + Items/StorageAccess.cs | 1 + MagicStorage.cs | 741 +++--- ModSearchBox.cs | 182 +- NetHelper.cs | 4 +- Properties/AssemblyInfo.cs | 1 + Sorting/CompareFunction.cs | 16 +- Sorting/DefaultSorting.cs | 2 +- Sorting/FilterMode.cs | 10 +- Sorting/ItemFilter.cs | 6 +- Sorting/ItemSorter.cs | 17 +- Sorting/SortMode.cs | 2 +- StorageGUI.cs | 2 +- StoragePlayer.cs | 596 ++--- StorageWorld.cs | 1 + UIButtonChoice.cs | 8 +- UISearchBar.cs | 38 +- UIToggleButton.cs | 184 +- 34 files changed, 3180 insertions(+), 3169 deletions(-) diff --git a/Components/CraftingAccess.cs b/Components/CraftingAccess.cs index f47354d4..c8901449 100644 --- a/Components/CraftingAccess.cs +++ b/Components/CraftingAccess.cs @@ -72,4 +72,4 @@ public override void KillTile(int i, int j, ref bool fail, ref bool effectOnly, } } } -} \ No newline at end of file +} diff --git a/Components/CreativeStorageUnit.cs b/Components/CreativeStorageUnit.cs index 3c7f7c86..6b7fdd6f 100644 --- a/Components/CreativeStorageUnit.cs +++ b/Components/CreativeStorageUnit.cs @@ -32,4 +32,4 @@ public override void PostDraw(int i, int j, SpriteBatch spriteBatch) spriteBatch.Draw(mod.GetTexture("Components/CreativeStorageUnit_Glow"), drawPos, frame, color); } } -} \ No newline at end of file +} diff --git a/Components/TEAbstractStorageUnit.cs b/Components/TEAbstractStorageUnit.cs index 50a14922..b2858dba 100644 --- a/Components/TEAbstractStorageUnit.cs +++ b/Components/TEAbstractStorageUnit.cs @@ -95,4 +95,4 @@ public override void NetReceive(BinaryReader reader, bool lightReceive) center = new Point16(reader.ReadInt16(), reader.ReadInt16()); } } -} \ No newline at end of file +} diff --git a/Components/TECraftingAccess.cs b/Components/TECraftingAccess.cs index 18c15bcd..76a14577 100644 --- a/Components/TECraftingAccess.cs +++ b/Components/TECraftingAccess.cs @@ -1,163 +1,163 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using Microsoft.Xna.Framework; -using Terraria; -using Terraria.DataStructures; -using Terraria.ID; -using Terraria.ModLoader; -using Terraria.ModLoader.IO; - -namespace MagicStorage.Components -{ - public class TECraftingAccess : TEStorageComponent - { - public const int Rows = 3; - public const int ItemsPerRow = 15; - public const int ItemsTotal = Rows * ItemsPerRow; - - public Item[] stations = new Item[ItemsTotal]; - - public TECraftingAccess() - { - for (int k = 0; k < ItemsTotal; k++) - { - stations[k] = new Item(); - } - } - - public override bool ValidTile(Tile tile) - { - return tile.type == mod.TileType("CraftingAccess") && tile.frameX == 0 && tile.frameY == 0; - } - - public void TryDepositStation(Item item) - { - if (Main.netMode == 1) - { - return; - } - foreach (Item station in stations) - { - if (station.type == item.type) - { - return; - } - } - for (int k = 0; k < stations.Length; k++) - { - if (stations[k].IsAir) - { - stations[k] = item.Clone(); - stations[k].stack = 1; - item.stack--; - if (item.stack <= 0) - { - item.SetDefaults(0); - } - NetHelper.SendTEUpdate(ID, Position); - return; - } - } - } - - public Item TryWithdrawStation(int slot) - { - if (Main.netMode == 1) - { - return new Item(); - } - if (!stations[slot].IsAir) - { - Item item = stations[slot]; - stations[slot] = new Item(); - NetHelper.SendTEUpdate(ID, Position); - return item; - } - return new Item(); - } - - public Item DoStationSwap(Item item, int slot) - { - if (Main.netMode == 1) - { - return new Item(); - } - if (!item.IsAir) - { - for (int k = 0; k < stations.Length; k++) - { - if (k != slot && stations[k].type == item.type) - { - return item; - } - } - } - if ((item.IsAir || item.stack == 1) && !stations[slot].IsAir) - { - Item temp = item; - item = stations[slot]; - stations[slot] = temp; - NetHelper.SendTEUpdate(ID, Position); - return item; - } - else if (!item.IsAir && stations[slot].IsAir) - { - stations[slot] = item.Clone(); - stations[slot].stack = 1; - item.stack--; - if (item.stack <= 0) - { - item.SetDefaults(0); - } - NetHelper.SendTEUpdate(ID, Position); - return item; - } - return item; - } - - public override TagCompound Save() - { - TagCompound tag = new TagCompound(); - IList listStations = new List(); - foreach (Item item in stations) - { - listStations.Add(ItemIO.Save(item)); - } - tag["Stations"] = listStations; - return tag; - } - - public override void Load(TagCompound tag) - { - IList listStations = tag.GetList("Stations"); - if (listStations != null && listStations.Count > 0) - { - for (int k = 0; k < stations.Length; k++) - { - if (k < listStations.Count) - stations[k] = ItemIO.Load(listStations[k]); - else - stations[k] = new Item(); - } - } - } - - public override void NetSend(BinaryWriter writer, bool lightSend) - { - foreach (Item item in stations) - { - ItemIO.Send(item, writer, true, true); - } - } - - public override void NetReceive(BinaryReader reader, bool lightReceive) - { - for (int k = 0; k < stations.Length; k++) - { - stations[k] = ItemIO.Receive(reader, true, true); - } - } - } -} \ No newline at end of file +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using Microsoft.Xna.Framework; +using Terraria; +using Terraria.DataStructures; +using Terraria.ID; +using Terraria.ModLoader; +using Terraria.ModLoader.IO; + +namespace MagicStorage.Components +{ + public class TECraftingAccess : TEStorageComponent + { + public const int Rows = 3; + public const int ItemsPerRow = 15; + public const int ItemsTotal = Rows * ItemsPerRow; + + public Item[] stations = new Item[ItemsTotal]; + + public TECraftingAccess() + { + for (int k = 0; k < ItemsTotal; k++) + { + stations[k] = new Item(); + } + } + + public override bool ValidTile(Tile tile) + { + return tile.type == mod.TileType("CraftingAccess") && tile.frameX == 0 && tile.frameY == 0; + } + + public void TryDepositStation(Item item) + { + if (Main.netMode == 1) + { + return; + } + foreach (Item station in stations) + { + if (station.type == item.type) + { + return; + } + } + for (int k = 0; k < stations.Length; k++) + { + if (stations[k].IsAir) + { + stations[k] = item.Clone(); + stations[k].stack = 1; + item.stack--; + if (item.stack <= 0) + { + item.SetDefaults(0); + } + NetHelper.SendTEUpdate(ID, Position); + return; + } + } + } + + public Item TryWithdrawStation(int slot) + { + if (Main.netMode == 1) + { + return new Item(); + } + if (!stations[slot].IsAir) + { + Item item = stations[slot]; + stations[slot] = new Item(); + NetHelper.SendTEUpdate(ID, Position); + return item; + } + return new Item(); + } + + public Item DoStationSwap(Item item, int slot) + { + if (Main.netMode == 1) + { + return new Item(); + } + if (!item.IsAir) + { + for (int k = 0; k < stations.Length; k++) + { + if (k != slot && stations[k].type == item.type) + { + return item; + } + } + } + if ((item.IsAir || item.stack == 1) && !stations[slot].IsAir) + { + Item temp = item; + item = stations[slot]; + stations[slot] = temp; + NetHelper.SendTEUpdate(ID, Position); + return item; + } + else if (!item.IsAir && stations[slot].IsAir) + { + stations[slot] = item.Clone(); + stations[slot].stack = 1; + item.stack--; + if (item.stack <= 0) + { + item.SetDefaults(0); + } + NetHelper.SendTEUpdate(ID, Position); + return item; + } + return item; + } + + public override TagCompound Save() + { + TagCompound tag = new TagCompound(); + IList listStations = new List(); + foreach (Item item in stations) + { + listStations.Add(ItemIO.Save(item)); + } + tag["Stations"] = listStations; + return tag; + } + + public override void Load(TagCompound tag) + { + IList listStations = tag.GetList("Stations"); + if (listStations != null && listStations.Count > 0) + { + for (int k = 0; k < stations.Length; k++) + { + if (k < listStations.Count) + stations[k] = ItemIO.Load(listStations[k]); + else + stations[k] = new Item(); + } + } + } + + public override void NetSend(BinaryWriter writer, bool lightSend) + { + foreach (Item item in stations) + { + ItemIO.Send(item, writer, true, true); + } + } + + public override void NetReceive(BinaryReader reader, bool lightReceive) + { + for (int k = 0; k < stations.Length; k++) + { + stations[k] = ItemIO.Receive(reader, true, true); + } + } + } +} diff --git a/Components/TECreativeStorageUnit.cs b/Components/TECreativeStorageUnit.cs index f6cf3902..79be71d8 100644 --- a/Components/TECreativeStorageUnit.cs +++ b/Components/TECreativeStorageUnit.cs @@ -125,4 +125,4 @@ public void Dispose() { } } -} \ No newline at end of file +} diff --git a/Components/TEStorageHeart.cs b/Components/TEStorageHeart.cs index 4a7b9bf1..ec8fff0a 100644 --- a/Components/TEStorageHeart.cs +++ b/Components/TEStorageHeart.cs @@ -265,7 +265,7 @@ public void ResetCompactStage(int stage = 0) ItemTypeOrderedSet _uniqueItemsPutHistory = new ItemTypeOrderedSet("UniqueItemsPutHistory"); public IEnumerable UniqueItemsPutHistory { get { return _uniqueItemsPutHistory.Items; } } - + public void DepositItem(Item toDeposit) { if (Main.netMode == 2) @@ -293,11 +293,11 @@ public void DepositItem(Item toDeposit) { if (!storageUnit.Inactive && !storageUnit.IsFull) { - storageUnit.DepositItem(toDeposit, true); - if (toDeposit.IsAir) - { - _uniqueItemsPutHistory.Add(remember); - return; + storageUnit.DepositItem(toDeposit, true); + if (toDeposit.IsAir) + { + _uniqueItemsPutHistory.Add(remember); + return; } } } @@ -385,7 +385,7 @@ public bool HasItem(Item lookFor, bool ignorePrefix = false) finally { if (Main.netMode == 2) - { + { ExitReadLock(); } } @@ -438,4 +438,4 @@ public override void NetReceive(BinaryReader reader, bool lightReceive) } } } -} \ No newline at end of file +} diff --git a/Components/TEStorageUnit.cs b/Components/TEStorageUnit.cs index 2dde376a..2f1be0e0 100644 --- a/Components/TEStorageUnit.cs +++ b/Components/TEStorageUnit.cs @@ -159,8 +159,8 @@ public override void DepositItem(Item toDeposit, bool locked = false) { newStack = item.maxStack; } - item.stack = newStack; - + item.stack = newStack; + if (toDeposit.favorited) item.favorited = true; if (toDeposit.newAndShiny) item.newAndShiny = true; @@ -650,3 +650,4 @@ protected override bool ReceiveData(BinaryReader reader, TEStorageUnit unit) } } } + diff --git a/CraftingGUI.cs b/CraftingGUI.cs index f0206190..2694ca8a 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -1,1854 +1,1854 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Threading; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using Microsoft.Xna.Framework.Input; -using Terraria; -using Terraria.DataStructures; -using Terraria.GameContent.UI.Elements; -using Terraria.ID; -using Terraria.Localization; -using Terraria.Map; -using Terraria.ModLoader; -using Terraria.UI; -using MagicStorage.Components; -using MagicStorage.Sorting; - -namespace MagicStorage -{ - public static class CraftingGUI - { - const int RecipeButtonsNewChoice = 0; - const int RecipeButtonsBlacklistChoice = 3; - const int RecipeButtonsFavoritesChoice = 2; - private const int padding = 4; - private const int numColumns = 10; - private const int numColumns2 = 7; - private const float inventoryScale = 0.85f; - private const float smallScale = 0.7f; - - static HashSet threadCheckListFoundItems; - static Mod _checkListMod; - static volatile bool wasItemChecklistRetrieved; - - public static MouseState curMouse; - public static MouseState oldMouse; - public static bool MouseClicked - { - get - { - return curMouse.LeftButton == ButtonState.Pressed && oldMouse.LeftButton == ButtonState.Released; - } - } - - public static bool RightMouseClicked - { - get - { - return curMouse.RightButton == ButtonState.Pressed && oldMouse.RightButton == ButtonState.Released; - } - } - - private static UIPanel basePanel = new UIPanel(); - private static float panelTop; - private static float panelLeft; - private static float panelWidth; - private static float panelHeight; - - private static UIElement topBar = new UIElement(); - internal static UISearchBar searchBar; - private static UIButtonChoice sortButtons; - private static UIButtonChoice recipeButtons; - private static UIElement topBar2 = new UIElement(); - private static UIButtonChoice filterButtons; - - private static UIText stationText; - private static UISlotZone stationZone = new UISlotZone(HoverStation, GetStation, inventoryScale / 1.55f); - private static UISlotZone recipeZone = new UISlotZone(HoverRecipe, GetRecipe, inventoryScale); - - internal static UIScrollbar scrollBar = new UIScrollbar(); - private static int scrollBarFocus = 0; - private static int scrollBarFocusMouseStart; - private static float scrollBarFocusPositionStart; - private static float scrollBarViewSize = 1f; - private static float scrollBarMaxViewSize = 2f; - - private static List items = new List(); - private static Dictionary itemCounts = new Dictionary(); - private static bool[] adjTiles = new bool[TileLoader.TileCount]; - private static bool adjWater = false; - private static bool adjLava = false; - private static bool adjHoney = false; - private static bool zoneSnow = false; - private static bool alchemyTable = false; - private static List recipes = new List(); - private static List recipeAvailable = new List(); - private static Recipe selectedRecipe = null; - private static int numRows; - private static int displayRows; - private static bool slotFocus = false; - - private static UIElement bottomBar = new UIElement(); - private static UIText capacityText; - - private static UIPanel recipePanel = new UIPanel(); - - private static float recipeTop; - private static float recipeLeft; - private static float recipeWidth; - private static float recipeHeight; - - private static UIText recipePanelHeader; - private static UIText ingredientText; - private static UISlotZone ingredientZone = new UISlotZone(HoverItem, GetIngredient, smallScale); - private static UISlotZone recipeHeaderZone = new UISlotZone(HoverHeader, GetHeader, smallScale); - private static UIText reqObjText; - private static UIText reqObjText2; - private static UIText storedItemsText; - - private static UISlotZone storageZone = new UISlotZone(HoverStorage, GetStorage, smallScale); - private static int numRows2; - private static int displayRows2; - private static List storageItems = new List(); - private static List blockStorageItems = new List(); - - internal static UIScrollbar scrollBar2 = new UIScrollbar(); - private static float scrollBar2ViewSize = 1f; - private static float scrollBar2MaxViewSize = 2f; - - internal static UITextPanel craftButton; - public static readonly ModSearchBox modSearchBox = new ModSearchBox(RefreshItems); - - private static Item result = null; - private static UISlotZone resultZone = new UISlotZone(HoverResult, GetResult, inventoryScale); - private static int craftTimer = 0; - private const int startMaxCraftTimer = 20; - private static int maxCraftTimer = startMaxCraftTimer; - private static int rightClickTimer = 0; - private const int startMaxRightClickTimer = 20; - - private static int maxRightClickTimer = startMaxRightClickTimer; - - private static Object threadLock = new Object(); - private static Object recipeLock = new Object(); - private static Object itemsLock = new Object(); - private static bool threadRunning = false; - internal static bool threadNeedsRestart = false; - private static SortMode threadSortMode; - private static FilterMode threadFilterMode; - private static List threadRecipes = new List(); - private static List threadRecipeAvailable = new List(); - private static List nextRecipes = new List(); - private static List nextRecipeAvailable = new List(); - - public static void Initialize() - { - lock (recipeLock) - { - recipes = nextRecipes; - recipeAvailable = nextRecipeAvailable; - } - - InitLangStuff(); - float itemSlotWidth = Main.inventoryBackTexture.Width * inventoryScale; - float itemSlotHeight = Main.inventoryBackTexture.Height * inventoryScale; - float smallSlotWidth = Main.inventoryBackTexture.Width * smallScale; - float smallSlotHeight = Main.inventoryBackTexture.Height * smallScale; - - panelTop = Main.instance.invBottom + 60; - panelLeft = 20f; - float innerPanelLeft = panelLeft + basePanel.PaddingLeft; - float innerPanelWidth = numColumns * (itemSlotWidth + padding) + 20f + padding; - panelWidth = basePanel.PaddingLeft + innerPanelWidth + basePanel.PaddingRight; - panelHeight = Main.screenHeight - panelTop - 40f; - basePanel.Left.Set(panelLeft, 0f); - basePanel.Top.Set(panelTop, 0f); - basePanel.Width.Set(panelWidth, 0f); - basePanel.Height.Set(panelHeight, 0f); - basePanel.Recalculate(); - - recipeTop = panelTop; - recipeLeft = panelLeft + panelWidth; - recipeWidth = numColumns2 * (smallSlotWidth + padding) + 20f + padding; - recipeWidth += recipePanel.PaddingLeft + recipePanel.PaddingRight; - recipeHeight = panelHeight; - recipePanel.Left.Set(recipeLeft, 0f); - recipePanel.Top.Set(recipeTop, 0f); - recipePanel.Width.Set(recipeWidth, 0f); - recipePanel.Height.Set(recipeHeight, 0f); - recipePanel.Recalculate(); - - topBar.Width.Set(0f, 1f); - topBar.Height.Set(32f, 0f); - basePanel.Append(topBar); - - InitSortButtons(); - topBar.Append(sortButtons); - float sortButtonsRight = sortButtons.GetDimensions().Width + padding; - InitRecipeButtons(); - float recipeButtonsLeft = sortButtonsRight + 3 * padding; - recipeButtons.Left.Set(recipeButtonsLeft, 0f); - topBar.Append(recipeButtons); - float recipeButtonsRight = recipeButtonsLeft + recipeButtons.GetDimensions().Width + padding; - - searchBar.Left.Set(recipeButtonsRight + padding, 0f); - searchBar.Width.Set(-recipeButtonsRight - 2 * padding, 1f); - searchBar.Height.Set(0f, 1f); - topBar.Append(searchBar); - - topBar2.Width.Set(0f, 1f); - topBar2.Height.Set(32f, 0f); - topBar2.Top.Set(36f, 0f); - basePanel.Append(topBar2); - - InitFilterButtons(); - float filterButtonsRight = filterButtons.GetDimensions().Width + padding; - topBar2.Append(filterButtons); - - modSearchBox.Button.Left.Set(filterButtonsRight + padding, 0f); - modSearchBox.Button.Width.Set(-filterButtonsRight - 2 * padding, 1f); - modSearchBox.Button.Height.Set(0f, 1f); - modSearchBox.Button.OverflowHidden = true; - topBar2.Append(modSearchBox.Button); - - stationText.Top.Set(76f, 0f); - basePanel.Append(stationText); - - stationZone.Width.Set(0f, 1f); - stationZone.Top.Set(100f, 0f); - stationZone.Height.Set(110f, 0f); - stationZone.SetDimensions(15, 3); - basePanel.Append(stationZone); - - recipeZone.Width.Set(0f, 1f); - recipeZone.Top.Set(196f, 0f); - recipeZone.Height.Set(-196f, 1f); - basePanel.Append(recipeZone); - - numRows = (recipes.Count + numColumns - 1) / numColumns; - displayRows = (int)recipeZone.GetDimensions().Height / ((int)itemSlotHeight + padding); - recipeZone.SetDimensions(numColumns, displayRows); - int noDisplayRows = numRows - displayRows; - if (noDisplayRows < 0) - { - noDisplayRows = 0; - } - scrollBarMaxViewSize = 1 + noDisplayRows; - scrollBar.Height.Set(displayRows * (itemSlotHeight + padding), 0f); - scrollBar.Left.Set(-20f, 1f); - scrollBar.SetView(scrollBarViewSize, scrollBarMaxViewSize); - recipeZone.Append(scrollBar); - - bottomBar.Width.Set(0f, 1f); - bottomBar.Height.Set(32f, 0f); - bottomBar.Top.Set(-32f, 1f); - basePanel.Append(bottomBar); - - capacityText.Left.Set(6f, 0f); - capacityText.Top.Set(6f, 0f); - TEStorageHeart heart = GetHeart(); - int numItems = 0; - int capacity = 0; - if (heart != null) - { - foreach (TEAbstractStorageUnit abstractStorageUnit in heart.GetStorageUnits()) - { - if (abstractStorageUnit is TEStorageUnit) - { - TEStorageUnit storageUnit = (TEStorageUnit)abstractStorageUnit; - numItems += storageUnit.NumItems; - capacity += storageUnit.Capacity; - } - } - } - capacityText.SetText(numItems + "/" + capacity + " Items"); - bottomBar.Append(capacityText); - - recipePanelHeader.Left.Set(60, 0f); - recipePanel.Append(recipePanelHeader); - - ingredientText.Top.Set(30f, 0f); - ingredientText.Left.Set(60, 0f); - - recipeHeaderZone.SetDimensions(1, 1); - recipePanel.Append(recipeHeaderZone); - - recipePanel.Append(ingredientText); - - ingredientZone.SetDimensions(numColumns2, 2); - ingredientZone.Top.Set(54f, 0f); - ingredientZone.Width.Set(0f, 1f); - ingredientZone.Height.Set(60f, 0f); - recipePanel.Append(ingredientZone); - - reqObjText.Top.Set(136f, 0f); - recipePanel.Append(reqObjText); - reqObjText2.Top.Set(160f, 0f); - recipePanel.Append(reqObjText2); - storedItemsText.Top.Set(190f, 0f); - recipePanel.Append(storedItemsText); - - storageZone.Top.Set(214f, 0f); - storageZone.Width.Set(0f, 1f); - storageZone.Height.Set(-214f - 36, 1f); - recipePanel.Append(storageZone); - numRows2 = (storageItems.Count + numColumns2 - 1) / numColumns2; - displayRows2 = (int)storageZone.GetDimensions().Height / ((int)smallSlotHeight + padding); - storageZone.SetDimensions(numColumns2, displayRows2); - int noDisplayRows2 = numRows2 - displayRows2; - if (noDisplayRows2 < 0) - { - noDisplayRows2 = 0; - } - scrollBar2MaxViewSize = 1 + noDisplayRows2; - scrollBar2.Height.Set(displayRows2 * (smallSlotHeight + padding), 0f); - scrollBar2.Left.Set(-20f, 1f); - scrollBar2.SetView(scrollBar2ViewSize, scrollBar2MaxViewSize); - storageZone.Append(scrollBar2); - - craftButton.Top.Set(-32f, 1f); - craftButton.Width.Set(100f, 0f); - craftButton.Height.Set(24f, 0f); - craftButton.PaddingTop = 8f; - craftButton.PaddingBottom = 8f; - recipePanel.Append(craftButton); - - resultZone.SetDimensions(1, 1); - resultZone.Left.Set(-itemSlotWidth, 1f); - resultZone.Top.Set(-itemSlotHeight, 1f); - resultZone.Width.Set(itemSlotWidth, 0f); - resultZone.Height.Set(itemSlotHeight, 0f); - recipePanel.Append(resultZone); - } - - private static void InitLangStuff() - { - if (searchBar == null) - { - searchBar = new UISearchBar(Language.GetText("Mods.MagicStorage.SearchName"), RefreshItems); - } - if (stationText == null) - { - stationText = new UIText(Language.GetText("Mods.MagicStorage.CraftingStations")); - } - if (capacityText == null) - { - capacityText = new UIText("Items"); - } - if (recipePanelHeader == null) - { - recipePanelHeader = new UIText(Language.GetText("Mods.MagicStorage.SelectedRecipe")); - } - if (ingredientText == null) - { - ingredientText = new UIText(Language.GetText("Mods.MagicStorage.Ingredients")); - } - if (reqObjText == null) - { - reqObjText = new UIText(Language.GetText("LegacyInterface.22")); - } - if (reqObjText2 == null) - { - reqObjText2 = new UIText(""); - } - if (storedItemsText == null) - { - storedItemsText = new UIText(Language.GetText("Mods.MagicStorage.StoredItems")); - } - if (craftButton == null) - { - craftButton = new UITextPanel(Language.GetText("LegacyMisc.72"), 1f); - } - modSearchBox.InitLangStuff(); - } - - private static void InitSortButtons() - { - if (sortButtons == null) - { - sortButtons = GUIHelpers.MakeSortButtons(CraftingGUI.RefreshItems); - } - } - - private static void InitRecipeButtons() - { - if (recipeButtons == null) - { - recipeButtons = new UIButtonChoice(CraftingGUI.RefreshItems, new Texture2D[] - { - MagicStorage.Instance.GetTexture("RecipeAvailable"), - MagicStorage.Instance.GetTexture("RecipeAll"), - MagicStorage.Instance.GetTexture("FilterMisc"), - MagicStorage.Instance.GetTexture("RecipeAll"), - }, - new LocalizedText[] - { - Language.GetText("Mods.MagicStorage.RecipeAvailable"), - Language.GetText("Mods.MagicStorage.RecipeAll"), - Language.GetText("Mods.MagicStorage.ShowOnlyFavorited"), - Language.GetText("Mods.MagicStorage.RecipeBlacklist"), - - }) { Choice = 1 }; - } - } - - private static void InitFilterButtons() - { - if (filterButtons == null) - { - filterButtons = GUIHelpers.MakeFilterButtons(false, CraftingGUI.RefreshItems); - } - } - - public static void Update(GameTime gameTime) - { - try - { - if (MagicStorage.IsItemKnownHotKey != null && MagicStorage.IsItemKnownHotKey.JustPressed && Main.HoverItem != null && !Main.HoverItem.IsAir) - { - var s = Main.HoverItem.Name + " is "; - var t = Main.HoverItem.type; - if (GetKnownItems().Contains(t)) - { - s += "known"; - var sum = ModPlayer.LatestAccessedStorage?.GetStoredItems().Where(x => x.type == t).Select(x => x.stack).DefaultIfEmpty().Sum() ?? 0; - if (sum > 0) - s += $" ({sum} in l.a.s.)"; - } - else - s += "new"; - Main.NewTextMultiline(s); - } - } - catch (KeyNotFoundException) - { - // ignore - } - - try { - oldMouse = StorageGUI.oldMouse; - curMouse = StorageGUI.curMouse; - if (Main.playerInventory && Main.player[Main.myPlayer].GetModPlayer(MagicStorage.Instance).ViewingStorage().X >= 0 && StoragePlayer.IsStorageCrafting()) - { - if (curMouse.RightButton == ButtonState.Released) - { - ResetSlotFocus(); - } - - if (basePanel != null) - { - basePanel.Update(gameTime); - } - recipePanel.Update(gameTime); - UpdateRecipeText(); - UpdateScrollBar(); - UpdateCraftButton(); - modSearchBox.Update(curMouse, oldMouse); - } - else - { - scrollBarFocus = 0; - craftTimer = 0; - maxCraftTimer = startMaxCraftTimer; - ResetSlotFocus(); - }}catch(Exception e){Main.NewTextMultiline(e.ToString());} - } - - public static void Draw(TEStorageHeart heart) - { - try - { - Player player = Main.player[Main.myPlayer]; - Initialize(); - if (Main.mouseX > panelLeft && Main.mouseX < recipeLeft + panelWidth && Main.mouseY > panelTop && Main.mouseY < panelTop + panelHeight) - { - player.mouseInterface = true; - player.showItemIcon = false; - InterfaceHelper.HideItemIconCache(); - } - - basePanel.Draw(Main.spriteBatch); - recipePanel.Draw(Main.spriteBatch); - Vector2 pos = recipeZone.GetDimensions().Position(); - if (threadRunning) - { - Utils.DrawBorderString(Main.spriteBatch, "Loading", pos + new Vector2(8f, 8f), Color.White); - } - - stationZone.DrawText(); - recipeZone.DrawText(); - ingredientZone.DrawText(); - recipeHeaderZone.DrawText(); - storageZone.DrawText(); - resultZone.DrawText(); - sortButtons.DrawText(); - recipeButtons.DrawText(); - filterButtons.DrawText(); - DrawCraftButton(); - } - catch (Exception e) - { - Main.NewTextMultiline(e.ToString()); - } - } - - private static void DrawCraftButton() - { - Rectangle dim = InterfaceHelper.GetFullRectangle(craftButton); - - if (Main.netMode == NetmodeID.SinglePlayer && curMouse.X > dim.X && curMouse.X < dim.X + dim.Width && curMouse.Y > dim.Y && curMouse.Y < dim.Y + dim.Height - && selectedRecipe != null && Main.mouseItem.IsAir && CanItemBeTakenForTest(selectedRecipe.createItem)) - { - Main.instance.MouseText(Language.GetText("Mods.MagicStorage.CraftTooltip").Value); - } - } - - private static Item GetStation(int slot, ref int context) - { - Item[] stations = GetCraftingStations(); - if (stations == null || slot >= stations.Length) - { - return new Item(); - } - return stations[slot]; - } - - private static Item GetRecipe(int slot, ref int context) - { - if (threadRunning) - { - return new Item(); - } - int index = slot + numColumns * (int)Math.Round(scrollBar.ViewPosition); - Item item = index < recipes.Count ? recipes[index].createItem : new Item(); - if (!item.IsAir) - { - if (recipes[index] == selectedRecipe) - { - context = 6; - } - if (!recipeAvailable[index]) - { - context = recipes[index] == selectedRecipe ? 4 : 3; - } - if (ModPlayer.FavoritedRecipes.Contains(item)) - { - item = item.Clone(); - item.favorited = true; - } - - if (!ModPlayer.SeenRecipes.Contains(item)) - { - item = item.Clone(); - item.newAndShiny = true; - } - } - - return item; - } - - private static Item GetHeader(int slot, ref int context) - { - if (selectedRecipe == null) - return new Item(); - - var item = selectedRecipe.createItem; - if (item.IsAir) - { - int t = item.type; - item = new Item(); - item.SetDefaults(t); - item.stack = 0; - } - return item; - } - - private static Item GetIngredient(int slot, ref int context) - { - if (selectedRecipe == null || slot >= selectedRecipe.requiredItem.Length) - return new Item(); - - Item item = selectedRecipe.requiredItem[slot].Clone(); - if (selectedRecipe.anyWood && item.type == ItemID.Wood) - { - item.SetNameOverride(Lang.misc[37].Value + " " + Lang.GetItemNameValue(ItemID.Wood)); - } - if (selectedRecipe.anySand && item.type == ItemID.SandBlock) - { - item.SetNameOverride(Lang.misc[37].Value + " " + Lang.GetItemNameValue(ItemID.SandBlock)); - } - if (selectedRecipe.anyIronBar && item.type == ItemID.IronBar) - { - item.SetNameOverride(Lang.misc[37].Value + " " + Lang.GetItemNameValue(ItemID.IronBar)); - } - if (selectedRecipe.anyFragment && item.type == ItemID.FragmentSolar) - { - item.SetNameOverride(Lang.misc[37].Value + " " + Lang.misc[51].Value); - } - if (selectedRecipe.anyPressurePlate && item.type == ItemID.GrayPressurePlate) - { - item.SetNameOverride(Lang.misc[37].Value + " " + Lang.misc[38].Value); - } - string nameOverride; - if (selectedRecipe.ProcessGroupsForText(item.type, out nameOverride)) - { - item.SetNameOverride(nameOverride); - } - return item; - } - - private static Item GetStorage(int slot, ref int context) - { - int index = slot + numColumns2 * (int)Math.Round(scrollBar2.ViewPosition); - Item item = index < storageItems.Count ? storageItems[index] : new Item(); - if (blockStorageItems.Contains(new ItemData(item))) - { - context = 3; - } - return item; - } - - private static Item GetResult(int slot, ref int context) - { - return slot == 0 && result != null ? result : new Item(); - } - - private static void UpdateRecipeText() - { - if (selectedRecipe == null) - { - reqObjText2.SetText(""); - recipePanelHeader.SetText(Language.GetText("Mods.MagicStorage.SelectedRecipe").Value); - } - else - { - bool isEmpty = true; - string text = ""; - for (int k = 0; k < selectedRecipe.requiredTile.Length; k++) - { - if (selectedRecipe.requiredTile[k] == -1) - { - break; - } - if (!isEmpty) - { - text += ", "; - } - text += Lang.GetMapObjectName(MapHelper.TileToLookup(selectedRecipe.requiredTile[k], 0)); - isEmpty = false; - } - if (selectedRecipe.needWater) - { - if (!isEmpty) - { - text += ", "; - } - text += Language.GetTextValue("LegacyInterface.53"); - isEmpty = false; - } - if (selectedRecipe.needHoney) - { - if (!isEmpty) - { - text += ", "; - } - text += Language.GetTextValue("LegacyInterface.58"); - isEmpty = false; - } - if (selectedRecipe.needLava) - { - if (!isEmpty) - { - text += ", "; - } - text += Language.GetTextValue("LegacyInterface.56"); - isEmpty = false; - } - if (selectedRecipe.needSnowBiome) - { - if (!isEmpty) - { - text += ", "; - } - text += Language.GetTextValue("LegacyInterface.123"); - isEmpty = false; - } - if (isEmpty) - { - text = Language.GetTextValue("LegacyInterface.23"); - } - reqObjText2.SetText(text); - var item = selectedRecipe.createItem; - var dps = CompareDps.GetDps(item); - if (dps >= 1f) - recipePanelHeader.SetText("DPS = " + dps.ToString("F0")); - else - recipePanelHeader.SetText(""); - } - } - - private static void UpdateScrollBar() - { - if (slotFocus) - { - scrollBarFocus = 0; - return; - } - Rectangle dim = scrollBar.GetClippingRectangle(Main.spriteBatch); - Vector2 boxPos = new Vector2(dim.X, dim.Y + dim.Height * (scrollBar.ViewPosition / scrollBarMaxViewSize)); - float boxWidth = 20f * Main.UIScale; - float boxHeight = dim.Height * (scrollBarViewSize / scrollBarMaxViewSize); - Rectangle dim2 = scrollBar2.GetClippingRectangle(Main.spriteBatch); - Vector2 box2Pos = new Vector2(dim2.X, dim2.Y + dim2.Height * (scrollBar2.ViewPosition / scrollBar2MaxViewSize)); - float box2Height = dim2.Height * (scrollBar2ViewSize / scrollBar2MaxViewSize); - if (scrollBarFocus > 0) - { - if (curMouse.LeftButton == ButtonState.Released) - { - scrollBarFocus = 0; - } - else - { - int difference = curMouse.Y - scrollBarFocusMouseStart; - if (scrollBarFocus == 1) - { - scrollBar.ViewPosition = scrollBarFocusPositionStart + (float)difference / boxHeight; - } - else if (scrollBarFocus == 2) - { - scrollBar2.ViewPosition = scrollBarFocusPositionStart + (float)difference / box2Height; - } - } - } - else if (MouseClicked) - { - if (curMouse.X > boxPos.X && curMouse.X < boxPos.X + boxWidth && curMouse.Y > boxPos.Y - 3f && curMouse.Y < boxPos.Y + boxHeight + 4f) - { - scrollBarFocus = 1; - scrollBarFocusMouseStart = curMouse.Y; - scrollBarFocusPositionStart = scrollBar.ViewPosition; - } - else if (curMouse.X > box2Pos.X && curMouse.X < box2Pos.X + boxWidth && curMouse.Y > box2Pos.Y - 3f && curMouse.Y < box2Pos.Y + box2Height + 4f) - { - scrollBarFocus = 2; - scrollBarFocusMouseStart = curMouse.Y; - scrollBarFocusPositionStart = scrollBar2.ViewPosition; - } - } - if (scrollBarFocus == 0) - { - int difference = oldMouse.ScrollWheelValue / 250 - curMouse.ScrollWheelValue / 250; - scrollBar.ViewPosition += difference; - } - } - - private static void UpdateCraftButton() - { - Rectangle dim = InterfaceHelper.GetFullRectangle(craftButton); - bool flag = false; - if (curMouse.X > dim.X && curMouse.X < dim.X + dim.Width && curMouse.Y > dim.Y && curMouse.Y < dim.Y + dim.Height) - { - craftButton.BackgroundColor = new Color(73, 94, 171); - if (RightMouseClicked && selectedRecipe != null && Main.mouseItem.IsAir) - { - var item = selectedRecipe.createItem; - if (CanItemBeTakenForTest(item)) - { - var type = item.type; - var testItem = new Item(); - testItem.SetDefaults(type, true); - MarkAsTestItem(testItem); - Main.mouseItem = testItem; - ModPlayer.TestedRecipes.Add(selectedRecipe.createItem); - } - } - else if (curMouse.LeftButton == ButtonState.Pressed && selectedRecipe != null && IsAvailable(selectedRecipe) && PassesBlock(selectedRecipe)) - { - if (craftTimer <= 0) - { - craftTimer = maxCraftTimer; - maxCraftTimer = maxCraftTimer * 3 / 4; - if (maxCraftTimer <= 0) - { - maxCraftTimer = 1; - } - TryCraft(); - RefreshItems(); - Main.PlaySound(7, -1, -1, 1); - } - craftTimer--; - flag = true; - StoragePlayer modPlayer = Main.player[Main.myPlayer].GetModPlayer(); - if (modPlayer.AddToCraftedRecipes(selectedRecipe.createItem)) - RefreshItems(); - } - } - else - { - craftButton.BackgroundColor = new Color(63, 82, 151) * 0.7f; - } - if (selectedRecipe == null || !IsAvailable(selectedRecipe) || !PassesBlock(selectedRecipe)) - { - craftButton.BackgroundColor = new Color(30, 40, 100) * 0.7f; - } - if (!flag) - { - craftTimer = 0; - maxCraftTimer = startMaxCraftTimer; - } - } - - static bool CanItemBeTakenForTest(Item item) - { - return Main.netMode == NetmodeID.SinglePlayer - && !item.consumable && (item.mana > 0 || item.magic || item.ranged || item.thrown || item.melee - || item.headSlot >= 0 || item.bodySlot >= 0 || item.legSlot >= 0 || item.accessory || Main.projHook[item.shoot] - || item.pick > 0 || item.axe > 0 || item.hammer > 0) - && !item.summon && item.createTile < 0 && item.createWall < 0 && !item.potion && item.fishingPole <= 1 && item.ammo == AmmoID.None - && !ModPlayer.TestedRecipes.Contains(item); - } - - public static void MarkAsTestItem(Item testItem) - { - testItem.value = 0; - testItem.shopCustomPrice = 0; - testItem.material = false; - testItem.rare = -11; - testItem.SetNameOverride(Lang.GetItemNameValue(testItem.type) + Language.GetTextValue("Mods.MagicStorage.TestItemSuffix")); - } - - public static bool IsTestItem(Item item) - { - return item.Name.EndsWith(Language.GetTextValue("Mods.MagicStorage.TestItemSuffix")); - } - - private static TEStorageHeart GetHeart() - { - Player player = Main.player[Main.myPlayer]; - StoragePlayer modPlayer = player.GetModPlayer(); - return modPlayer.GetStorageHeart(); - } - - private static TECraftingAccess GetCraftingEntity() - { - Player player = Main.player[Main.myPlayer]; - StoragePlayer modPlayer = player.GetModPlayer(); - return modPlayer.GetCraftingAccess(); - } - - private static Item[] GetCraftingStations() - { - TECraftingAccess ent = GetCraftingEntity(); - return ent == null ? null : ent.stations; - } - - public static void RefreshItems() - { - var modPlayer = ModPlayer; - if (modPlayer.SeenRecipes.Count == 0) - { - foreach (var item in GetKnownItems()) - modPlayer.SeenRecipes.Add(item); - } - items.Clear(); - TEStorageHeart heart = GetHeart(); - if (heart == null) - { - return; - } - - items.AddRange(ItemSorter.SortAndFilter(heart.GetStoredItems(), SortMode.Id, FilterMode.All, ModSearchBox.ModIndexAll, "")); - AnalyzeIngredients(); - InitLangStuff(); - InitSortButtons(); - InitRecipeButtons(); - InitFilterButtons(); - SortMode sortMode = (SortMode)sortButtons.Choice; - FilterMode filterMode = (FilterMode)filterButtons.Choice; - - RefreshStorageItems(); - - HashSet foundItems; - HashSet hiddenRecipes; - HashSet craftedRecipes; - HashSet asKnownRecipes; - GetKnownItems(out foundItems, out hiddenRecipes, out craftedRecipes, out asKnownRecipes); - foundItems.UnionWith(asKnownRecipes); - - var favoritesCopy = new HashSet(modPlayer.FavoritedRecipes.Items.Select(x => x.type)); - - EnsureProductToRecipesInited(); - - lock (threadLock) - { - threadNeedsRestart = true; - threadSortMode = sortMode; - threadFilterMode = filterMode; - threadCheckListFoundItems = foundItems; - if (!threadRunning) - { - threadRunning = true; - Thread thread = new Thread(_ => RefreshRecipes(hiddenRecipes, craftedRecipes, favoritesCopy)); - thread.Start(); - } - } - } - - public static HashSet GetKnownItems() - { - HashSet a, b, c, d; - GetKnownItems(out a, out b, out c, out d); - a.UnionWith(b); - a.UnionWith(c); - a.UnionWith(d); - return a; - } - - static void GetKnownItems(out HashSet foundItems, out HashSet hiddenRecipes, out HashSet craftedRecipes, out HashSet asKnownRecipes) - { - foundItems = new HashSet(RetrieveFoundItemsCheckList()); - - StoragePlayer modPlayer = ModPlayer; - hiddenRecipes = new HashSet(modPlayer.HiddenRecipes.Select(x => x.type)); - craftedRecipes = new HashSet(modPlayer.CraftedRecipes.Select(x => x.type)); - asKnownRecipes = new HashSet(modPlayer.AsKnownRecipes.Items.Select(x => x.type)); - } - - static StoragePlayer ModPlayer { get { return Main.player[Main.myPlayer].GetModPlayer(); } } - - static IEnumerable RetrieveFoundItemsCheckList() - { - if (_checkListMod == null) - _checkListMod = ModLoader.GetMod("ItemChecklist"); - - var foundItems = _checkListMod != null ? _checkListMod.Call("RequestFoundItems") as bool[] : new bool[0]; - if (foundItems.Length > 0) wasItemChecklistRetrieved = true; - return foundItems.Select((v, type) => new { WasFound = v, type }).Where(x => x.WasFound).Select(x => x.type); - } - - static void EnsureProductToRecipesInited() - { - if (_productToRecipes == null) - { - var allRecipes = ItemSorter.GetRecipes(SortMode.Id, FilterMode.All, ModSearchBox.ModIndexAll, "").Where(x => x != null && x.createItem != null && x.createItem.type > 0).ToArray(); - _productToRecipes = allRecipes.GroupBy(x => x.createItem.type).ToDictionary(x => x.Key, x => x.ToList()); - } - } - - static Dictionary> _productToRecipes; - - /// - /// Checks all crafting tree until it finds already available ingredients - /// - static bool IsKnownRecursively(Recipe recipe, HashSet availableSet) - { - return IsKnownRecursively(recipe, availableSet, new HashSet(), new Dictionary()); - } - - /// - /// Checks all crafting tree until it finds already available ingredients - /// - static bool IsKnownRecursively(Recipe recipe, HashSet availableSet, HashSet recursionTree, Dictionary cache) - { - bool v; - if (cache.TryGetValue(recipe, out v)) return v; - - - foreach (int tile in recipe.requiredTile) - { - if (tile == -1) - break; - - List possibleItems; - if (!StorageWorld.TileToCreatingItem.TryGetValue(tile, out possibleItems)) - continue; - - if (!possibleItems.Any(x => IsKnownRecursively_CheckIngredient(x, availableSet, recursionTree, cache))) - { - cache[recipe] = false; - return false; - } - } - - int ingredients = 0; - for (int i = 0; i < Recipe.maxRequirements; i++) - { - var t = recipe.requiredItem[i].type; - if (t <= 0) continue; - ingredients++; - if (IsKnownRecursively_CheckIngredient(t, availableSet, recursionTree, cache)) continue; - if (IsKnownRecursively_CheckAcceptedGroupsForIngredient(recipe, availableSet, recursionTree, cache, t)) continue; - cache[recipe] = false; - return false; - } - - if (ingredients > 0) - { - cache[recipe] = true; - return true; - } - - cache[recipe] = false; - return false; - } - - static bool IsKnownRecursively_CheckAcceptedGroupsForIngredient(Recipe recipe, HashSet availableSet, HashSet recursionTree, Dictionary cache, int t) - { - foreach (var g in recipe.acceptedGroups.Select(j => RecipeGroup.recipeGroups[j])) - { - if (g.ContainsItem(t)) - { - foreach (var groupItemType in g.ValidItems) - { - if (groupItemType != t && IsKnownRecursively_CheckIngredient(groupItemType, availableSet, recursionTree, cache)) - { - return true; - } - } - } - } - return false; - } - - static bool IsKnownRecursively_CheckIngredient(int t, HashSet availableSet, HashSet recursionTree, Dictionary cache) - { - if (availableSet.Contains(t)) return true; - if (!recursionTree.Add(t)) return false; - try - { - List ingredientRecipes; - if (!_productToRecipes.TryGetValue(t, out ingredientRecipes)) return false; - if (ingredientRecipes.Count == 0 || ingredientRecipes.All(x => !IsKnownRecursively(x, availableSet, recursionTree, cache))) return false; - } - finally - { - recursionTree.Remove(t); - } - - return true; - } - - private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craftedRecipes, HashSet favorited) - { - while (true) - { - try - { - SortMode sortMode; - FilterMode filterMode; - HashSet foundItems; - lock (threadLock) - { - threadNeedsRestart = false; - sortMode = threadSortMode; - filterMode = threadFilterMode; - foundItems = threadCheckListFoundItems; - } - - var availableItemsMutable = new HashSet(hiddenRecipes - .Concat(craftedRecipes) - .Concat(foundItems)); - - var notNewItems = new HashSet(availableItemsMutable); - - var temp = new HashSet(); - var tempCache = new Dictionary(); - - var modFilterIndex = modSearchBox.ModIndex; - - IEnumerable filteredRecipes = null; - - Action doFiltering = () => - { - filteredRecipes = ItemSorter.GetRecipes(sortMode, filterMode, modFilterIndex, searchBar.Text).Where(x => x != null) - // show only blacklisted recipes only if choice = 2, otherwise show all other - .Where(x => (recipeButtons.Choice == RecipeButtonsBlacklistChoice) == hiddenRecipes.Contains(x.createItem.type)) - // show only new items if selected - .Where(x => (recipeButtons.Choice != RecipeButtonsNewChoice) || !notNewItems.Contains(x.createItem.type)) - // show only favorited items if selected - .Where(x => (recipeButtons.Choice != RecipeButtonsFavoritesChoice) || favorited.Contains(x.createItem.type)) - // hard check if this item can be crafted from available items and their recursive products - .Where(x => !wasItemChecklistRetrieved || IsKnownRecursively(x, availableItemsMutable, temp, tempCache)) - .OrderBy(x => favorited.Contains(x.createItem.type) ? 0 : 1); - - threadRecipes.Clear(); - threadRecipeAvailable.Clear(); - try - { - threadRecipes.AddRange(filteredRecipes); - threadRecipeAvailable.AddRange(threadRecipes.Select(IsAvailable)); - } - catch (InvalidOperationException) - { - } - catch (KeyNotFoundException) - { - } - }; - - doFiltering(); - - // now if nothing found we disable filters one by one - if (searchBar.Text.Length > 0) - { - if (threadRecipes.Count == 0 && recipeButtons.Choice == RecipeButtonsNewChoice) - { - // search old recipes too - notNewItems = new HashSet(); - doFiltering(); - } - - if (threadRecipes.Count == 0 && hiddenRecipes.Count > 0) - { - // search hidden recipes too - hiddenRecipes = new HashSet(); - doFiltering(); - } - - if (threadRecipes.Count == 0 && filterMode != FilterMode.All) - { - // any category - filterMode = FilterMode.All; - doFiltering(); - } - - if (threadRecipes.Count == 0 && modFilterIndex != ModSearchBox.ModIndexAll) - { - // search all mods - modFilterIndex = ModSearchBox.ModIndexAll; - doFiltering(); - } - } - - lock (recipeLock) - { - nextRecipes = new List(); - nextRecipeAvailable = new List(); - nextRecipes.AddRange(threadRecipes); - nextRecipeAvailable.AddRange(threadRecipeAvailable); - - } - lock (threadLock) - { - if (!threadNeedsRestart) - { - threadRunning = false; - return; - } - } - } - catch (Exception e) { Main.NewTextMultiline(e.ToString()); } - } - } - - private static void AnalyzeIngredients() - { - Player player = Main.player[Main.myPlayer]; - itemCounts.Clear(); - if (adjTiles.Length != player.adjTile.Length) - { - Array.Resize(ref adjTiles, player.adjTile.Length); - } - for (int k = 0; k < adjTiles.Length; k++) - { - adjTiles[k] = false; - } - adjWater = false; - adjLava = false; - adjHoney = false; - zoneSnow = false; - alchemyTable = false; - - foreach (Item item in items) - { - if (itemCounts.ContainsKey(item.netID)) - { - itemCounts[item.netID] += item.stack; - } - else - { - itemCounts[item.netID] = item.stack; - } - } - foreach (Item item in GetCraftingStations()) - { - if (item.createTile >= 0) - { - adjTiles[item.createTile] = true; - if (item.createTile == TileID.GlassKiln || item.createTile == TileID.Hellforge || item.createTile == TileID.AdamantiteForge) - { - adjTiles[TileID.Furnaces] = true; - } - if (item.createTile == TileID.AdamantiteForge) - { - adjTiles[TileID.Hellforge] = true; - } - if (item.createTile == TileID.MythrilAnvil) - { - adjTiles[TileID.Anvils] = true; - } - if (item.createTile == TileID.BewitchingTable || item.createTile == TileID.Tables2) - { - adjTiles[TileID.Tables] = true; - } - if (item.createTile == TileID.AlchemyTable) - { - adjTiles[TileID.Bottles] = true; - adjTiles[TileID.Tables] = true; - alchemyTable = true; - } - bool[] oldAdjTile = player.adjTile; - bool oldAdjWater = adjWater; - bool oldAdjLava = adjLava; - bool oldAdjHoney = adjHoney; - bool oldAlchemyTable = alchemyTable; - player.adjTile = adjTiles; - player.adjWater = false; - player.adjLava = false; - player.adjHoney = false; - player.alchemyTable = false; - TileLoader.AdjTiles(player, item.createTile); - if (player.adjWater) - { - adjWater = true; - } - if (player.adjLava) - { - adjLava = true; - } - if (player.adjHoney) - { - adjHoney = true; - } - if (player.alchemyTable) - { - alchemyTable = true; - } - player.adjTile = oldAdjTile; - player.adjWater = oldAdjWater; - player.adjLava = oldAdjLava; - player.adjHoney = oldAdjHoney; - player.alchemyTable = oldAlchemyTable; - } - if (item.type == ItemID.WaterBucket || item.type == ItemID.BottomlessBucket) - { - adjWater = true; - } - if (item.type == ItemID.LavaBucket) - { - adjLava = true; - } - if (item.type == ItemID.HoneyBucket) - { - adjHoney = true; - } - if (item.type == MagicStorage.Instance.ItemType("SnowBiomeEmulator")) - { - zoneSnow = true; - } - } - adjTiles[MagicStorage.Instance.TileType("CraftingAccess")] = true; - } - - private static bool IsAvailable(Recipe recipe) - { - foreach (int tile in recipe.requiredTile) - { - if (tile == -1) - { - break; - } - if (!adjTiles[tile]) - { - return false; - } - } - foreach (Item ingredient in recipe.requiredItem) - { - if (ingredient.type == 0) - { - break; - } - int stack = ingredient.stack; - bool useRecipeGroup = false; - foreach (int type in itemCounts.Keys) - { - if (RecipeGroupMatch(recipe, type, ingredient.type)) - { - stack -= itemCounts[type]; - useRecipeGroup = true; - } - } - if (!useRecipeGroup && itemCounts.ContainsKey(ingredient.netID)) - { - stack -= itemCounts[ingredient.netID]; - } - if (stack > 0) - { - return false; - } - } - if (recipe.needWater && !adjWater && !adjTiles[TileID.Sinks]) - { - return false; - } - if (recipe.needLava && !adjLava) - { - return false; - } - if (recipe.needHoney && !adjHoney) - { - return false; - } - if (recipe.needSnowBiome && !zoneSnow) - { - return false; - } - try - { - BlockRecipes.active = false; - if (!RecipeHooks.RecipeAvailable(recipe)) - { - return false; - } - } - finally - { - BlockRecipes.active = true; - } - return true; - } - - private static bool PassesBlock(Recipe recipe) - { - foreach (Item ingredient in recipe.requiredItem) - { - if (ingredient.type == 0) - { - break; - } - int stack = ingredient.stack; - bool useRecipeGroup = false; - foreach (Item item in storageItems) - { - ItemData data = new ItemData(item); - if (!blockStorageItems.Contains(data) && RecipeGroupMatch(recipe, item.netID, ingredient.type)) - { - stack -= item.stack; - useRecipeGroup = true; - } - } - if (!useRecipeGroup) - { - foreach (Item item in storageItems) - { - ItemData data = new ItemData(item); - if (!blockStorageItems.Contains(data) && item.netID == ingredient.netID) - { - stack -= item.stack; - } - } - } - if (stack > 0) - { - return false; - } - } - return true; - } - - private static void RefreshStorageItems() - { - storageItems.Clear(); - result = null; - if (selectedRecipe != null) - { - foreach (Item item in items) - { - for (int k = 0; k < selectedRecipe.requiredItem.Length; k++) - { - if (selectedRecipe.requiredItem[k].type == 0) - { - break; - } - if (item.type == selectedRecipe.requiredItem[k].type || RecipeGroupMatch(selectedRecipe, selectedRecipe.requiredItem[k].type, item.type)) - { - storageItems.Add(item); - } - } - if (item.type == selectedRecipe.createItem.type) - { - result = item; - } - } - if (result == null) - { - result = new Item(); - result.SetDefaults(selectedRecipe.createItem.type); - result.stack = 0; - } - } - } - - private static bool RecipeGroupMatch(Recipe recipe, int type1, int type2) - { - return recipe.useWood(type1, type2) || recipe.useSand(type1, type2) || recipe.useIronBar(type1, type2) || recipe.useFragment(type1, type2) || recipe.AcceptedByItemGroups(type1, type2) || recipe.usePressurePlate(type1, type2); - } - - private static void HoverStation(int slot, ref int hoverSlot) - { - TECraftingAccess ent = GetCraftingEntity(); - if (ent == null || slot >= ent.stations.Length) - { - return; - } - - Player player = Main.player[Main.myPlayer]; - if (MouseClicked) - { - bool changed = false; - if (!ent.stations[slot].IsAir && ItemSlot.ShiftInUse) - { - Item result = player.GetItem(Main.myPlayer, DoWithdraw(slot), false, true); - if (!result.IsAir && Main.mouseItem.IsAir) - { - Main.mouseItem = result; - result = new Item(); - } - if (!result.IsAir && Main.mouseItem.type == result.type && Main.mouseItem.stack < Main.mouseItem.maxStack) - { - Main.mouseItem.stack += result.stack; - result = new Item(); - } - if (!result.IsAir) - { - player.QuickSpawnClonedItem(result); - } - changed = true; - } - else if (player.itemAnimation == 0 && player.itemTime == 0) - { - int oldType = Main.mouseItem.type; - int oldStack = Main.mouseItem.stack; - Main.mouseItem = DoStationSwap(Main.mouseItem, slot); - if (oldType != Main.mouseItem.type || oldStack != Main.mouseItem.stack) - { - changed = true; - } - } - if (changed) - { - RefreshItems(); - Main.PlaySound(7, -1, -1, 1); - } - } - - hoverSlot = slot; - } - - private static void HoverRecipe(int slot, ref int hoverSlot) - { - int visualSlot = slot; - slot += numColumns * (int)Math.Round(scrollBar.ViewPosition); - if (slot < recipes.Count) - { - var recipe = recipes[slot]; - if (MouseClicked) - { - if (Main.keyState.IsKeyDown(Keys.LeftAlt)) - { - if (!ModPlayer.FavoritedRecipes.Add(recipe.createItem)) - ModPlayer.FavoritedRecipes.Remove(recipe.createItem); - } - else if (Main.keyState.IsKeyDown(Keys.LeftControl)) - { - if (recipeButtons.Choice == RecipeButtonsBlacklistChoice) - { - if (ModPlayer.RemoveFromHiddenRecipes(recipe.createItem)) - RefreshItems(); - } - else - { - if (ModPlayer.AddToHiddenRecipes(recipe.createItem)) - RefreshItems(); - } - } - else - SetSelectedRecipe(recipe); - } - else if (RightMouseClicked && (recipe == selectedRecipe || recipeButtons.Choice != RecipeButtonsNewChoice)) - { - if (recipeButtons.Choice == RecipeButtonsNewChoice) - { - ModPlayer.AsKnownRecipes.Add(recipe.createItem); - RefreshItems(); - } - else - ModPlayer.AsKnownRecipes.Remove(recipe.createItem); - } - - hoverSlot = visualSlot; - } - } - - static void SetSelectedRecipe(Recipe recipe) - { - if (recipe != null) ModPlayer.SeenRecipes.Add(recipe.createItem); - selectedRecipe = recipe; - RefreshStorageItems(); - blockStorageItems.Clear(); - } - - private static void HoverHeader(int slot, ref int hoverSlot) - { - hoverSlot = slot; - } - - private static void HoverItem(int slot, ref int hoverSlot) - { - if (selectedRecipe == null) - { - hoverSlot = slot; - return; - } - int visualSlot = slot; - slot += numColumns2 * (int)Math.Round(scrollBar2.ViewPosition); - var count = selectedRecipe.requiredItem.Select((x, i) => new { x, i }).First(x => x.x.type == 0).i + 1; - - if (slot < count) - { - // select ingredient recipe by right clicking - if (RightMouseClicked) - { - var item = selectedRecipe.requiredItem[slot]; - EnsureProductToRecipesInited(); - List itemRecipes; - if (_productToRecipes.TryGetValue(item.type, out itemRecipes)) - { - var knownItems = GetKnownItems(); - - var recursionTree = new HashSet(); - var cache = new Dictionary(); - - Recipe selected = null; - - foreach (var r in itemRecipes.Where(x => IsKnownRecursively(x, knownItems, recursionTree, cache))) - { - if (selected == null) selected = r; - if (IsAvailable(r)) - { - selected = r; - break; - } - } - if (selected != null) SetSelectedRecipe(selected); - } - } - hoverSlot = visualSlot; - } - } - - private static void HoverStorage(int slot, ref int hoverSlot) - { - int visualSlot = slot; - slot += numColumns2 * (int)Math.Round(scrollBar2.ViewPosition); - if (slot < storageItems.Count) - { - var item = storageItems[slot]; - item.newAndShiny = false; - if (MouseClicked) - { - ItemData data = new ItemData(item); - if (blockStorageItems.Contains(data)) - { - blockStorageItems.Remove(data); - } - else - { - blockStorageItems.Add(data); - } - } - hoverSlot = visualSlot; - } - } - - private static void HoverResult(int slot, ref int hoverSlot) - { - if (slot != 0) - { - return; - } - - if (Main.mouseItem.IsAir && result != null && !result.IsAir) - result.newAndShiny = false; - - Player player = Main.player[Main.myPlayer]; - if (MouseClicked) - { - bool changed = false; - if (!Main.mouseItem.IsAir && player.itemAnimation == 0 && player.itemTime == 0 && result != null && Main.mouseItem.type == result.type) - { - if (TryDepositResult(Main.mouseItem)) - { - changed = true; - } - } - else if (Main.mouseItem.IsAir && result != null && !result.IsAir) - { - if (Main.keyState.IsKeyDown(Keys.LeftAlt)) - result.favorited = !result.favorited; - else - { - Item toWithdraw = result.Clone(); - if (toWithdraw.stack > toWithdraw.maxStack) - { - toWithdraw.stack = toWithdraw.maxStack; - } - Main.mouseItem = DoWithdrawResult(toWithdraw, ItemSlot.ShiftInUse); - if (ItemSlot.ShiftInUse) - { - Main.mouseItem = player.GetItem(Main.myPlayer, Main.mouseItem, false, true); - } - changed = true; - } - } - if (changed) - { - RefreshItems(); - Main.PlaySound(7, -1, -1, 1); - } - } - - if (curMouse.RightButton == ButtonState.Pressed && oldMouse.RightButton == ButtonState.Released && result != null && !result.IsAir && (Main.mouseItem.IsAir || ItemData.Matches(Main.mouseItem, items[slot]) && Main.mouseItem.stack < Main.mouseItem.maxStack)) - { - slotFocus = true; - } - - hoverSlot = slot; - - if (slotFocus) - { - SlotFocusLogic(); - } - } - - private static void SlotFocusLogic() - { - if (result == null || result.IsAir || (!Main.mouseItem.IsAir && (!ItemData.Matches(Main.mouseItem, result) || Main.mouseItem.stack >= Main.mouseItem.maxStack))) - { - ResetSlotFocus(); - } - else - { - if (rightClickTimer <= 0) - { - rightClickTimer = maxRightClickTimer; - maxRightClickTimer = maxRightClickTimer * 3 / 4; - if (maxRightClickTimer <= 0) - { - maxRightClickTimer = 1; - } - Item toWithdraw = result.Clone(); - toWithdraw.stack = 1; - Item withdrawn = DoWithdrawResult(toWithdraw); - if (Main.mouseItem.IsAir) - { - Main.mouseItem = withdrawn; - } - else - { - Main.mouseItem.stack += withdrawn.stack; - } - Main.soundInstanceMenuTick.Stop(); - Main.soundInstanceMenuTick = Main.soundMenuTick.CreateInstance(); - Main.PlaySound(12, -1, -1, 1); - RefreshItems(); - } - rightClickTimer--; - } - } - - private static void ResetSlotFocus() - { - slotFocus = false; - rightClickTimer = 0; - maxRightClickTimer = startMaxRightClickTimer; - } - - private static Item DoWithdraw(int slot) - { - TECraftingAccess access = GetCraftingEntity(); - if (Main.netMode == 0) - { - Item result = access.TryWithdrawStation(slot); - RefreshItems(); - return result; - } - else - { - NetHelper.SendWithdrawStation(access.ID, slot); - return new Item(); - } - } - - private static Item DoStationSwap(Item item, int slot) - { - TECraftingAccess access = GetCraftingEntity(); - if (Main.netMode == 0) - { - Item result = access.DoStationSwap(item, slot); - RefreshItems(); - return result; - } - else - { - NetHelper.SendStationSlotClick(access.ID, item, slot); - return new Item(); - } - } - - private static void TryCraft() - { - List availableItems = new List(storageItems.Where(item => !blockStorageItems.Contains(new ItemData(item))).Select(item => item.Clone())); - List toWithdraw = new List(); - for (int k = 0; k < selectedRecipe.requiredItem.Length; k++) - { - Item item = selectedRecipe.requiredItem[k]; - if (item.type == 0) - { - break; - } - int stack = item.stack; - ModRecipe modRecipe = selectedRecipe as ModRecipe; - if (modRecipe != null) - { - stack = modRecipe.ConsumeItem(item.type, item.stack); - } - if (selectedRecipe.alchemy && alchemyTable) - { - int save = 0; - for (int j = 0; j < stack; j++) - { - if (Main.rand.Next(3) == 0) - { - save++; - } - } - stack -= save; - } - if (stack > 0) - { - foreach (Item tryItem in availableItems) - { - if (item.type == tryItem.type || RecipeGroupMatch(selectedRecipe, item.type, tryItem.type)) - { - if (tryItem.stack > stack) - { - Item temp = tryItem.Clone(); - temp.stack = stack; - toWithdraw.Add(temp); - tryItem.stack -= stack; - stack = 0; - } - else - { - toWithdraw.Add(tryItem.Clone()); - stack -= tryItem.stack; - tryItem.stack = 0; - tryItem.type = 0; - } - } - } - } - } - Item resultItem = selectedRecipe.createItem.Clone(); - resultItem.Prefix(-1); - - RecipeHooks.OnCraft(resultItem, selectedRecipe); - ItemLoader.OnCraft(resultItem, selectedRecipe); - - if (Main.netMode == 0) - { - foreach (Item item in DoCraft(GetHeart(), toWithdraw, resultItem)) - { - Main.player[Main.myPlayer].QuickSpawnClonedItem(item, item.stack); - } - } - else if (Main.netMode == 1) - { - NetHelper.SendCraftRequest(GetHeart().ID, toWithdraw, resultItem); - } - } - - internal static List DoCraft(TEStorageHeart heart, List toWithdraw, Item result) - { - List items = new List(); - foreach (Item tryWithdraw in toWithdraw) - { - Item withdrawn = heart.TryWithdraw(tryWithdraw, false); - if (!withdrawn.IsAir) - { - items.Add(withdrawn); - } - if (withdrawn.stack < tryWithdraw.stack) - { - for (int k = 0; k < items.Count; k++) - { - heart.DepositItem(items[k]); - if (items[k].IsAir) - { - items.RemoveAt(k); - k--; - } - } - return items; - } - } - items.Clear(); - heart.DepositItem(result); - if (!result.IsAir) - { - items.Add(result); - } - return items; - } - - private static bool TryDepositResult(Item item) - { - int oldStack = item.stack; - DoDepositResult(item); - return oldStack != item.stack; - } - - private static void DoDepositResult(Item item) - { - TEStorageHeart heart = GetHeart(); - if (Main.netMode == 0) - { - heart.DepositItem(item); - } - else - { - NetHelper.SendDeposit(heart.ID, item); - item.SetDefaults(0, true); - } - } - - private static Item DoWithdrawResult(Item item, bool toInventory = false) - { - TEStorageHeart heart = GetHeart(); - if (Main.netMode == 0) - { - return heart.TryWithdraw(item, false); - } - else - { - NetHelper.SendWithdraw(heart.ID, item, toInventory); - return new Item(); - } - } - } -} \ No newline at end of file +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Threading; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Input; +using Terraria; +using Terraria.DataStructures; +using Terraria.GameContent.UI.Elements; +using Terraria.ID; +using Terraria.Localization; +using Terraria.Map; +using Terraria.ModLoader; +using Terraria.UI; +using MagicStorage.Components; +using MagicStorage.Sorting; + +namespace MagicStorage +{ + public static class CraftingGUI + { + const int RecipeButtonsNewChoice = 0; + const int RecipeButtonsBlacklistChoice = 3; + const int RecipeButtonsFavoritesChoice = 2; + private const int padding = 4; + private const int numColumns = 10; + private const int numColumns2 = 7; + private const float inventoryScale = 0.85f; + private const float smallScale = 0.7f; + + static HashSet threadCheckListFoundItems; + static Mod _checkListMod; + static volatile bool wasItemChecklistRetrieved; + + public static MouseState curMouse; + public static MouseState oldMouse; + public static bool MouseClicked + { + get + { + return curMouse.LeftButton == ButtonState.Pressed && oldMouse.LeftButton == ButtonState.Released; + } + } + + public static bool RightMouseClicked + { + get + { + return curMouse.RightButton == ButtonState.Pressed && oldMouse.RightButton == ButtonState.Released; + } + } + + private static UIPanel basePanel = new UIPanel(); + private static float panelTop; + private static float panelLeft; + private static float panelWidth; + private static float panelHeight; + + private static UIElement topBar = new UIElement(); + internal static UISearchBar searchBar; + private static UIButtonChoice sortButtons; + private static UIButtonChoice recipeButtons; + private static UIElement topBar2 = new UIElement(); + private static UIButtonChoice filterButtons; + + private static UIText stationText; + private static UISlotZone stationZone = new UISlotZone(HoverStation, GetStation, inventoryScale / 1.55f); + private static UISlotZone recipeZone = new UISlotZone(HoverRecipe, GetRecipe, inventoryScale); + + internal static UIScrollbar scrollBar = new UIScrollbar(); + private static int scrollBarFocus = 0; + private static int scrollBarFocusMouseStart; + private static float scrollBarFocusPositionStart; + private static float scrollBarViewSize = 1f; + private static float scrollBarMaxViewSize = 2f; + + private static List items = new List(); + private static Dictionary itemCounts = new Dictionary(); + private static bool[] adjTiles = new bool[TileLoader.TileCount]; + private static bool adjWater = false; + private static bool adjLava = false; + private static bool adjHoney = false; + private static bool zoneSnow = false; + private static bool alchemyTable = false; + private static List recipes = new List(); + private static List recipeAvailable = new List(); + private static Recipe selectedRecipe = null; + private static int numRows; + private static int displayRows; + private static bool slotFocus = false; + + private static UIElement bottomBar = new UIElement(); + private static UIText capacityText; + + private static UIPanel recipePanel = new UIPanel(); + + private static float recipeTop; + private static float recipeLeft; + private static float recipeWidth; + private static float recipeHeight; + + private static UIText recipePanelHeader; + private static UIText ingredientText; + private static UISlotZone ingredientZone = new UISlotZone(HoverItem, GetIngredient, smallScale); + private static UISlotZone recipeHeaderZone = new UISlotZone(HoverHeader, GetHeader, smallScale); + private static UIText reqObjText; + private static UIText reqObjText2; + private static UIText storedItemsText; + + private static UISlotZone storageZone = new UISlotZone(HoverStorage, GetStorage, smallScale); + private static int numRows2; + private static int displayRows2; + private static List storageItems = new List(); + private static List blockStorageItems = new List(); + + internal static UIScrollbar scrollBar2 = new UIScrollbar(); + private static float scrollBar2ViewSize = 1f; + private static float scrollBar2MaxViewSize = 2f; + + internal static UITextPanel craftButton; + public static readonly ModSearchBox modSearchBox = new ModSearchBox(RefreshItems); + + private static Item result = null; + private static UISlotZone resultZone = new UISlotZone(HoverResult, GetResult, inventoryScale); + private static int craftTimer = 0; + private const int startMaxCraftTimer = 20; + private static int maxCraftTimer = startMaxCraftTimer; + private static int rightClickTimer = 0; + private const int startMaxRightClickTimer = 20; + + private static int maxRightClickTimer = startMaxRightClickTimer; + + private static Object threadLock = new Object(); + private static Object recipeLock = new Object(); + private static Object itemsLock = new Object(); + private static bool threadRunning = false; + internal static bool threadNeedsRestart = false; + private static SortMode threadSortMode; + private static FilterMode threadFilterMode; + private static List threadRecipes = new List(); + private static List threadRecipeAvailable = new List(); + private static List nextRecipes = new List(); + private static List nextRecipeAvailable = new List(); + + public static void Initialize() + { + lock (recipeLock) + { + recipes = nextRecipes; + recipeAvailable = nextRecipeAvailable; + } + + InitLangStuff(); + float itemSlotWidth = Main.inventoryBackTexture.Width * inventoryScale; + float itemSlotHeight = Main.inventoryBackTexture.Height * inventoryScale; + float smallSlotWidth = Main.inventoryBackTexture.Width * smallScale; + float smallSlotHeight = Main.inventoryBackTexture.Height * smallScale; + + panelTop = Main.instance.invBottom + 60; + panelLeft = 20f; + float innerPanelLeft = panelLeft + basePanel.PaddingLeft; + float innerPanelWidth = numColumns * (itemSlotWidth + padding) + 20f + padding; + panelWidth = basePanel.PaddingLeft + innerPanelWidth + basePanel.PaddingRight; + panelHeight = Main.screenHeight - panelTop - 40f; + basePanel.Left.Set(panelLeft, 0f); + basePanel.Top.Set(panelTop, 0f); + basePanel.Width.Set(panelWidth, 0f); + basePanel.Height.Set(panelHeight, 0f); + basePanel.Recalculate(); + + recipeTop = panelTop; + recipeLeft = panelLeft + panelWidth; + recipeWidth = numColumns2 * (smallSlotWidth + padding) + 20f + padding; + recipeWidth += recipePanel.PaddingLeft + recipePanel.PaddingRight; + recipeHeight = panelHeight; + recipePanel.Left.Set(recipeLeft, 0f); + recipePanel.Top.Set(recipeTop, 0f); + recipePanel.Width.Set(recipeWidth, 0f); + recipePanel.Height.Set(recipeHeight, 0f); + recipePanel.Recalculate(); + + topBar.Width.Set(0f, 1f); + topBar.Height.Set(32f, 0f); + basePanel.Append(topBar); + + InitSortButtons(); + topBar.Append(sortButtons); + float sortButtonsRight = sortButtons.GetDimensions().Width + padding; + InitRecipeButtons(); + float recipeButtonsLeft = sortButtonsRight + 3 * padding; + recipeButtons.Left.Set(recipeButtonsLeft, 0f); + topBar.Append(recipeButtons); + float recipeButtonsRight = recipeButtonsLeft + recipeButtons.GetDimensions().Width + padding; + + searchBar.Left.Set(recipeButtonsRight + padding, 0f); + searchBar.Width.Set(-recipeButtonsRight - 2 * padding, 1f); + searchBar.Height.Set(0f, 1f); + topBar.Append(searchBar); + + topBar2.Width.Set(0f, 1f); + topBar2.Height.Set(32f, 0f); + topBar2.Top.Set(36f, 0f); + basePanel.Append(topBar2); + + InitFilterButtons(); + float filterButtonsRight = filterButtons.GetDimensions().Width + padding; + topBar2.Append(filterButtons); + + modSearchBox.Button.Left.Set(filterButtonsRight + padding, 0f); + modSearchBox.Button.Width.Set(-filterButtonsRight - 2 * padding, 1f); + modSearchBox.Button.Height.Set(0f, 1f); + modSearchBox.Button.OverflowHidden = true; + topBar2.Append(modSearchBox.Button); + + stationText.Top.Set(76f, 0f); + basePanel.Append(stationText); + + stationZone.Width.Set(0f, 1f); + stationZone.Top.Set(100f, 0f); + stationZone.Height.Set(110f, 0f); + stationZone.SetDimensions(15, 3); + basePanel.Append(stationZone); + + recipeZone.Width.Set(0f, 1f); + recipeZone.Top.Set(196f, 0f); + recipeZone.Height.Set(-196f, 1f); + basePanel.Append(recipeZone); + + numRows = (recipes.Count + numColumns - 1) / numColumns; + displayRows = (int)recipeZone.GetDimensions().Height / ((int)itemSlotHeight + padding); + recipeZone.SetDimensions(numColumns, displayRows); + int noDisplayRows = numRows - displayRows; + if (noDisplayRows < 0) + { + noDisplayRows = 0; + } + scrollBarMaxViewSize = 1 + noDisplayRows; + scrollBar.Height.Set(displayRows * (itemSlotHeight + padding), 0f); + scrollBar.Left.Set(-20f, 1f); + scrollBar.SetView(scrollBarViewSize, scrollBarMaxViewSize); + recipeZone.Append(scrollBar); + + bottomBar.Width.Set(0f, 1f); + bottomBar.Height.Set(32f, 0f); + bottomBar.Top.Set(-32f, 1f); + basePanel.Append(bottomBar); + + capacityText.Left.Set(6f, 0f); + capacityText.Top.Set(6f, 0f); + TEStorageHeart heart = GetHeart(); + int numItems = 0; + int capacity = 0; + if (heart != null) + { + foreach (TEAbstractStorageUnit abstractStorageUnit in heart.GetStorageUnits()) + { + if (abstractStorageUnit is TEStorageUnit) + { + TEStorageUnit storageUnit = (TEStorageUnit)abstractStorageUnit; + numItems += storageUnit.NumItems; + capacity += storageUnit.Capacity; + } + } + } + capacityText.SetText(numItems + "/" + capacity + " Items"); + bottomBar.Append(capacityText); + + recipePanelHeader.Left.Set(60, 0f); + recipePanel.Append(recipePanelHeader); + + ingredientText.Top.Set(30f, 0f); + ingredientText.Left.Set(60, 0f); + + recipeHeaderZone.SetDimensions(1, 1); + recipePanel.Append(recipeHeaderZone); + + recipePanel.Append(ingredientText); + + ingredientZone.SetDimensions(numColumns2, 2); + ingredientZone.Top.Set(54f, 0f); + ingredientZone.Width.Set(0f, 1f); + ingredientZone.Height.Set(60f, 0f); + recipePanel.Append(ingredientZone); + + reqObjText.Top.Set(136f, 0f); + recipePanel.Append(reqObjText); + reqObjText2.Top.Set(160f, 0f); + recipePanel.Append(reqObjText2); + storedItemsText.Top.Set(190f, 0f); + recipePanel.Append(storedItemsText); + + storageZone.Top.Set(214f, 0f); + storageZone.Width.Set(0f, 1f); + storageZone.Height.Set(-214f - 36, 1f); + recipePanel.Append(storageZone); + numRows2 = (storageItems.Count + numColumns2 - 1) / numColumns2; + displayRows2 = (int)storageZone.GetDimensions().Height / ((int)smallSlotHeight + padding); + storageZone.SetDimensions(numColumns2, displayRows2); + int noDisplayRows2 = numRows2 - displayRows2; + if (noDisplayRows2 < 0) + { + noDisplayRows2 = 0; + } + scrollBar2MaxViewSize = 1 + noDisplayRows2; + scrollBar2.Height.Set(displayRows2 * (smallSlotHeight + padding), 0f); + scrollBar2.Left.Set(-20f, 1f); + scrollBar2.SetView(scrollBar2ViewSize, scrollBar2MaxViewSize); + storageZone.Append(scrollBar2); + + craftButton.Top.Set(-32f, 1f); + craftButton.Width.Set(100f, 0f); + craftButton.Height.Set(24f, 0f); + craftButton.PaddingTop = 8f; + craftButton.PaddingBottom = 8f; + recipePanel.Append(craftButton); + + resultZone.SetDimensions(1, 1); + resultZone.Left.Set(-itemSlotWidth, 1f); + resultZone.Top.Set(-itemSlotHeight, 1f); + resultZone.Width.Set(itemSlotWidth, 0f); + resultZone.Height.Set(itemSlotHeight, 0f); + recipePanel.Append(resultZone); + } + + private static void InitLangStuff() + { + if (searchBar == null) + { + searchBar = new UISearchBar(Language.GetText("Mods.MagicStorage.SearchName"), RefreshItems); + } + if (stationText == null) + { + stationText = new UIText(Language.GetText("Mods.MagicStorage.CraftingStations")); + } + if (capacityText == null) + { + capacityText = new UIText("Items"); + } + if (recipePanelHeader == null) + { + recipePanelHeader = new UIText(Language.GetText("Mods.MagicStorage.SelectedRecipe")); + } + if (ingredientText == null) + { + ingredientText = new UIText(Language.GetText("Mods.MagicStorage.Ingredients")); + } + if (reqObjText == null) + { + reqObjText = new UIText(Language.GetText("LegacyInterface.22")); + } + if (reqObjText2 == null) + { + reqObjText2 = new UIText(""); + } + if (storedItemsText == null) + { + storedItemsText = new UIText(Language.GetText("Mods.MagicStorage.StoredItems")); + } + if (craftButton == null) + { + craftButton = new UITextPanel(Language.GetText("LegacyMisc.72"), 1f); + } + modSearchBox.InitLangStuff(); + } + + private static void InitSortButtons() + { + if (sortButtons == null) + { + sortButtons = GUIHelpers.MakeSortButtons(CraftingGUI.RefreshItems); + } + } + + private static void InitRecipeButtons() + { + if (recipeButtons == null) + { + recipeButtons = new UIButtonChoice(CraftingGUI.RefreshItems, new Texture2D[] + { + MagicStorage.Instance.GetTexture("RecipeAvailable"), + MagicStorage.Instance.GetTexture("RecipeAll"), + MagicStorage.Instance.GetTexture("FilterMisc"), + MagicStorage.Instance.GetTexture("RecipeAll"), + }, + new LocalizedText[] + { + Language.GetText("Mods.MagicStorage.RecipeAvailable"), + Language.GetText("Mods.MagicStorage.RecipeAll"), + Language.GetText("Mods.MagicStorage.ShowOnlyFavorited"), + Language.GetText("Mods.MagicStorage.RecipeBlacklist"), + + }) { Choice = 1 }; + } + } + + private static void InitFilterButtons() + { + if (filterButtons == null) + { + filterButtons = GUIHelpers.MakeFilterButtons(false, CraftingGUI.RefreshItems); + } + } + + public static void Update(GameTime gameTime) + { + try + { + if (MagicStorage.IsItemKnownHotKey != null && MagicStorage.IsItemKnownHotKey.JustPressed && Main.HoverItem != null && !Main.HoverItem.IsAir) + { + var s = Main.HoverItem.Name + " is "; + var t = Main.HoverItem.type; + if (GetKnownItems().Contains(t)) + { + s += "known"; + var sum = ModPlayer.LatestAccessedStorage?.GetStoredItems().Where(x => x.type == t).Select(x => x.stack).DefaultIfEmpty().Sum() ?? 0; + if (sum > 0) + s += $" ({sum} in l.a.s.)"; + } + else + s += "new"; + Main.NewTextMultiline(s); + } + } + catch (KeyNotFoundException) + { + // ignore + } + + try { + oldMouse = StorageGUI.oldMouse; + curMouse = StorageGUI.curMouse; + if (Main.playerInventory && Main.player[Main.myPlayer].GetModPlayer(MagicStorage.Instance).ViewingStorage().X >= 0 && StoragePlayer.IsStorageCrafting()) + { + if (curMouse.RightButton == ButtonState.Released) + { + ResetSlotFocus(); + } + + if (basePanel != null) + { + basePanel.Update(gameTime); + } + recipePanel.Update(gameTime); + UpdateRecipeText(); + UpdateScrollBar(); + UpdateCraftButton(); + modSearchBox.Update(curMouse, oldMouse); + } + else + { + scrollBarFocus = 0; + craftTimer = 0; + maxCraftTimer = startMaxCraftTimer; + ResetSlotFocus(); + }}catch(Exception e){Main.NewTextMultiline(e.ToString());} + } + + public static void Draw(TEStorageHeart heart) + { + try + { + Player player = Main.player[Main.myPlayer]; + Initialize(); + if (Main.mouseX > panelLeft && Main.mouseX < recipeLeft + panelWidth && Main.mouseY > panelTop && Main.mouseY < panelTop + panelHeight) + { + player.mouseInterface = true; + player.showItemIcon = false; + InterfaceHelper.HideItemIconCache(); + } + + basePanel.Draw(Main.spriteBatch); + recipePanel.Draw(Main.spriteBatch); + Vector2 pos = recipeZone.GetDimensions().Position(); + if (threadRunning) + { + Utils.DrawBorderString(Main.spriteBatch, "Loading", pos + new Vector2(8f, 8f), Color.White); + } + + stationZone.DrawText(); + recipeZone.DrawText(); + ingredientZone.DrawText(); + recipeHeaderZone.DrawText(); + storageZone.DrawText(); + resultZone.DrawText(); + sortButtons.DrawText(); + recipeButtons.DrawText(); + filterButtons.DrawText(); + DrawCraftButton(); + } + catch (Exception e) + { + Main.NewTextMultiline(e.ToString()); + } + } + + private static void DrawCraftButton() + { + Rectangle dim = InterfaceHelper.GetFullRectangle(craftButton); + + if (Main.netMode == NetmodeID.SinglePlayer && curMouse.X > dim.X && curMouse.X < dim.X + dim.Width && curMouse.Y > dim.Y && curMouse.Y < dim.Y + dim.Height + && selectedRecipe != null && Main.mouseItem.IsAir && CanItemBeTakenForTest(selectedRecipe.createItem)) + { + Main.instance.MouseText(Language.GetText("Mods.MagicStorage.CraftTooltip").Value); + } + } + + private static Item GetStation(int slot, ref int context) + { + Item[] stations = GetCraftingStations(); + if (stations == null || slot >= stations.Length) + { + return new Item(); + } + return stations[slot]; + } + + private static Item GetRecipe(int slot, ref int context) + { + if (threadRunning) + { + return new Item(); + } + int index = slot + numColumns * (int)Math.Round(scrollBar.ViewPosition); + Item item = index < recipes.Count ? recipes[index].createItem : new Item(); + if (!item.IsAir) + { + if (recipes[index] == selectedRecipe) + { + context = 6; + } + if (!recipeAvailable[index]) + { + context = recipes[index] == selectedRecipe ? 4 : 3; + } + if (ModPlayer.FavoritedRecipes.Contains(item)) + { + item = item.Clone(); + item.favorited = true; + } + + if (!ModPlayer.SeenRecipes.Contains(item)) + { + item = item.Clone(); + item.newAndShiny = true; + } + } + + return item; + } + + private static Item GetHeader(int slot, ref int context) + { + if (selectedRecipe == null) + return new Item(); + + var item = selectedRecipe.createItem; + if (item.IsAir) + { + int t = item.type; + item = new Item(); + item.SetDefaults(t); + item.stack = 0; + } + return item; + } + + private static Item GetIngredient(int slot, ref int context) + { + if (selectedRecipe == null || slot >= selectedRecipe.requiredItem.Length) + return new Item(); + + Item item = selectedRecipe.requiredItem[slot].Clone(); + if (selectedRecipe.anyWood && item.type == ItemID.Wood) + { + item.SetNameOverride(Lang.misc[37].Value + " " + Lang.GetItemNameValue(ItemID.Wood)); + } + if (selectedRecipe.anySand && item.type == ItemID.SandBlock) + { + item.SetNameOverride(Lang.misc[37].Value + " " + Lang.GetItemNameValue(ItemID.SandBlock)); + } + if (selectedRecipe.anyIronBar && item.type == ItemID.IronBar) + { + item.SetNameOverride(Lang.misc[37].Value + " " + Lang.GetItemNameValue(ItemID.IronBar)); + } + if (selectedRecipe.anyFragment && item.type == ItemID.FragmentSolar) + { + item.SetNameOverride(Lang.misc[37].Value + " " + Lang.misc[51].Value); + } + if (selectedRecipe.anyPressurePlate && item.type == ItemID.GrayPressurePlate) + { + item.SetNameOverride(Lang.misc[37].Value + " " + Lang.misc[38].Value); + } + string nameOverride; + if (selectedRecipe.ProcessGroupsForText(item.type, out nameOverride)) + { + item.SetNameOverride(nameOverride); + } + return item; + } + + private static Item GetStorage(int slot, ref int context) + { + int index = slot + numColumns2 * (int)Math.Round(scrollBar2.ViewPosition); + Item item = index < storageItems.Count ? storageItems[index] : new Item(); + if (blockStorageItems.Contains(new ItemData(item))) + { + context = 3; + } + return item; + } + + private static Item GetResult(int slot, ref int context) + { + return slot == 0 && result != null ? result : new Item(); + } + + private static void UpdateRecipeText() + { + if (selectedRecipe == null) + { + reqObjText2.SetText(""); + recipePanelHeader.SetText(Language.GetText("Mods.MagicStorage.SelectedRecipe").Value); + } + else + { + bool isEmpty = true; + string text = ""; + for (int k = 0; k < selectedRecipe.requiredTile.Length; k++) + { + if (selectedRecipe.requiredTile[k] == -1) + { + break; + } + if (!isEmpty) + { + text += ", "; + } + text += Lang.GetMapObjectName(MapHelper.TileToLookup(selectedRecipe.requiredTile[k], 0)); + isEmpty = false; + } + if (selectedRecipe.needWater) + { + if (!isEmpty) + { + text += ", "; + } + text += Language.GetTextValue("LegacyInterface.53"); + isEmpty = false; + } + if (selectedRecipe.needHoney) + { + if (!isEmpty) + { + text += ", "; + } + text += Language.GetTextValue("LegacyInterface.58"); + isEmpty = false; + } + if (selectedRecipe.needLava) + { + if (!isEmpty) + { + text += ", "; + } + text += Language.GetTextValue("LegacyInterface.56"); + isEmpty = false; + } + if (selectedRecipe.needSnowBiome) + { + if (!isEmpty) + { + text += ", "; + } + text += Language.GetTextValue("LegacyInterface.123"); + isEmpty = false; + } + if (isEmpty) + { + text = Language.GetTextValue("LegacyInterface.23"); + } + reqObjText2.SetText(text); + var item = selectedRecipe.createItem; + var dps = CompareDps.GetDps(item); + if (dps >= 1f) + recipePanelHeader.SetText("DPS = " + dps.ToString("F0")); + else + recipePanelHeader.SetText(""); + } + } + + private static void UpdateScrollBar() + { + if (slotFocus) + { + scrollBarFocus = 0; + return; + } + Rectangle dim = scrollBar.GetClippingRectangle(Main.spriteBatch); + Vector2 boxPos = new Vector2(dim.X, dim.Y + dim.Height * (scrollBar.ViewPosition / scrollBarMaxViewSize)); + float boxWidth = 20f * Main.UIScale; + float boxHeight = dim.Height * (scrollBarViewSize / scrollBarMaxViewSize); + Rectangle dim2 = scrollBar2.GetClippingRectangle(Main.spriteBatch); + Vector2 box2Pos = new Vector2(dim2.X, dim2.Y + dim2.Height * (scrollBar2.ViewPosition / scrollBar2MaxViewSize)); + float box2Height = dim2.Height * (scrollBar2ViewSize / scrollBar2MaxViewSize); + if (scrollBarFocus > 0) + { + if (curMouse.LeftButton == ButtonState.Released) + { + scrollBarFocus = 0; + } + else + { + int difference = curMouse.Y - scrollBarFocusMouseStart; + if (scrollBarFocus == 1) + { + scrollBar.ViewPosition = scrollBarFocusPositionStart + (float)difference / boxHeight; + } + else if (scrollBarFocus == 2) + { + scrollBar2.ViewPosition = scrollBarFocusPositionStart + (float)difference / box2Height; + } + } + } + else if (MouseClicked) + { + if (curMouse.X > boxPos.X && curMouse.X < boxPos.X + boxWidth && curMouse.Y > boxPos.Y - 3f && curMouse.Y < boxPos.Y + boxHeight + 4f) + { + scrollBarFocus = 1; + scrollBarFocusMouseStart = curMouse.Y; + scrollBarFocusPositionStart = scrollBar.ViewPosition; + } + else if (curMouse.X > box2Pos.X && curMouse.X < box2Pos.X + boxWidth && curMouse.Y > box2Pos.Y - 3f && curMouse.Y < box2Pos.Y + box2Height + 4f) + { + scrollBarFocus = 2; + scrollBarFocusMouseStart = curMouse.Y; + scrollBarFocusPositionStart = scrollBar2.ViewPosition; + } + } + if (scrollBarFocus == 0) + { + int difference = oldMouse.ScrollWheelValue / 250 - curMouse.ScrollWheelValue / 250; + scrollBar.ViewPosition += difference; + } + } + + private static void UpdateCraftButton() + { + Rectangle dim = InterfaceHelper.GetFullRectangle(craftButton); + bool flag = false; + if (curMouse.X > dim.X && curMouse.X < dim.X + dim.Width && curMouse.Y > dim.Y && curMouse.Y < dim.Y + dim.Height) + { + craftButton.BackgroundColor = new Color(73, 94, 171); + if (RightMouseClicked && selectedRecipe != null && Main.mouseItem.IsAir) + { + var item = selectedRecipe.createItem; + if (CanItemBeTakenForTest(item)) + { + var type = item.type; + var testItem = new Item(); + testItem.SetDefaults(type, true); + MarkAsTestItem(testItem); + Main.mouseItem = testItem; + ModPlayer.TestedRecipes.Add(selectedRecipe.createItem); + } + } + else if (curMouse.LeftButton == ButtonState.Pressed && selectedRecipe != null && IsAvailable(selectedRecipe) && PassesBlock(selectedRecipe)) + { + if (craftTimer <= 0) + { + craftTimer = maxCraftTimer; + maxCraftTimer = maxCraftTimer * 3 / 4; + if (maxCraftTimer <= 0) + { + maxCraftTimer = 1; + } + TryCraft(); + RefreshItems(); + Main.PlaySound(7, -1, -1, 1); + } + craftTimer--; + flag = true; + StoragePlayer modPlayer = Main.player[Main.myPlayer].GetModPlayer(); + if (modPlayer.AddToCraftedRecipes(selectedRecipe.createItem)) + RefreshItems(); + } + } + else + { + craftButton.BackgroundColor = new Color(63, 82, 151) * 0.7f; + } + if (selectedRecipe == null || !IsAvailable(selectedRecipe) || !PassesBlock(selectedRecipe)) + { + craftButton.BackgroundColor = new Color(30, 40, 100) * 0.7f; + } + if (!flag) + { + craftTimer = 0; + maxCraftTimer = startMaxCraftTimer; + } + } + + static bool CanItemBeTakenForTest(Item item) + { + return Main.netMode == NetmodeID.SinglePlayer + && !item.consumable && (item.mana > 0 || item.magic || item.ranged || item.thrown || item.melee + || item.headSlot >= 0 || item.bodySlot >= 0 || item.legSlot >= 0 || item.accessory || Main.projHook[item.shoot] + || item.pick > 0 || item.axe > 0 || item.hammer > 0) + && !item.summon && item.createTile < 0 && item.createWall < 0 && !item.potion && item.fishingPole <= 1 && item.ammo == AmmoID.None + && !ModPlayer.TestedRecipes.Contains(item); + } + + public static void MarkAsTestItem(Item testItem) + { + testItem.value = 0; + testItem.shopCustomPrice = 0; + testItem.material = false; + testItem.rare = -11; + testItem.SetNameOverride(Lang.GetItemNameValue(testItem.type) + Language.GetTextValue("Mods.MagicStorage.TestItemSuffix")); + } + + public static bool IsTestItem(Item item) + { + return item.Name.EndsWith(Language.GetTextValue("Mods.MagicStorage.TestItemSuffix")); + } + + private static TEStorageHeart GetHeart() + { + Player player = Main.player[Main.myPlayer]; + StoragePlayer modPlayer = player.GetModPlayer(); + return modPlayer.GetStorageHeart(); + } + + private static TECraftingAccess GetCraftingEntity() + { + Player player = Main.player[Main.myPlayer]; + StoragePlayer modPlayer = player.GetModPlayer(); + return modPlayer.GetCraftingAccess(); + } + + private static Item[] GetCraftingStations() + { + TECraftingAccess ent = GetCraftingEntity(); + return ent == null ? null : ent.stations; + } + + public static void RefreshItems() + { + var modPlayer = ModPlayer; + if (modPlayer.SeenRecipes.Count == 0) + { + foreach (var item in GetKnownItems()) + modPlayer.SeenRecipes.Add(item); + } + items.Clear(); + TEStorageHeart heart = GetHeart(); + if (heart == null) + { + return; + } + + items.AddRange(ItemSorter.SortAndFilter(heart.GetStoredItems(), SortMode.Id, FilterMode.All, ModSearchBox.ModIndexAll, "")); + AnalyzeIngredients(); + InitLangStuff(); + InitSortButtons(); + InitRecipeButtons(); + InitFilterButtons(); + SortMode sortMode = (SortMode)sortButtons.Choice; + FilterMode filterMode = (FilterMode)filterButtons.Choice; + + RefreshStorageItems(); + + HashSet foundItems; + HashSet hiddenRecipes; + HashSet craftedRecipes; + HashSet asKnownRecipes; + GetKnownItems(out foundItems, out hiddenRecipes, out craftedRecipes, out asKnownRecipes); + foundItems.UnionWith(asKnownRecipes); + + var favoritesCopy = new HashSet(modPlayer.FavoritedRecipes.Items.Select(x => x.type)); + + EnsureProductToRecipesInited(); + + lock (threadLock) + { + threadNeedsRestart = true; + threadSortMode = sortMode; + threadFilterMode = filterMode; + threadCheckListFoundItems = foundItems; + if (!threadRunning) + { + threadRunning = true; + Thread thread = new Thread(_ => RefreshRecipes(hiddenRecipes, craftedRecipes, favoritesCopy)); + thread.Start(); + } + } + } + + public static HashSet GetKnownItems() + { + HashSet a, b, c, d; + GetKnownItems(out a, out b, out c, out d); + a.UnionWith(b); + a.UnionWith(c); + a.UnionWith(d); + return a; + } + + static void GetKnownItems(out HashSet foundItems, out HashSet hiddenRecipes, out HashSet craftedRecipes, out HashSet asKnownRecipes) + { + foundItems = new HashSet(RetrieveFoundItemsCheckList()); + + StoragePlayer modPlayer = ModPlayer; + hiddenRecipes = new HashSet(modPlayer.HiddenRecipes.Select(x => x.type)); + craftedRecipes = new HashSet(modPlayer.CraftedRecipes.Select(x => x.type)); + asKnownRecipes = new HashSet(modPlayer.AsKnownRecipes.Items.Select(x => x.type)); + } + + static StoragePlayer ModPlayer { get { return Main.player[Main.myPlayer].GetModPlayer(); } } + + static IEnumerable RetrieveFoundItemsCheckList() + { + if (_checkListMod == null) + _checkListMod = ModLoader.GetMod("ItemChecklist"); + + var foundItems = _checkListMod != null ? _checkListMod.Call("RequestFoundItems") as bool[] : new bool[0]; + if (foundItems.Length > 0) wasItemChecklistRetrieved = true; + return foundItems.Select((v, type) => new { WasFound = v, type }).Where(x => x.WasFound).Select(x => x.type); + } + + static void EnsureProductToRecipesInited() + { + if (_productToRecipes == null) + { + var allRecipes = ItemSorter.GetRecipes(SortMode.Id, FilterMode.All, ModSearchBox.ModIndexAll, "").Where(x => x != null && x.createItem != null && x.createItem.type > 0).ToArray(); + _productToRecipes = allRecipes.GroupBy(x => x.createItem.type).ToDictionary(x => x.Key, x => x.ToList()); + } + } + + static Dictionary> _productToRecipes; + + /// + /// Checks all crafting tree until it finds already available ingredients + /// + static bool IsKnownRecursively(Recipe recipe, HashSet availableSet) + { + return IsKnownRecursively(recipe, availableSet, new HashSet(), new Dictionary()); + } + + /// + /// Checks all crafting tree until it finds already available ingredients + /// + static bool IsKnownRecursively(Recipe recipe, HashSet availableSet, HashSet recursionTree, Dictionary cache) + { + bool v; + if (cache.TryGetValue(recipe, out v)) return v; + + + foreach (int tile in recipe.requiredTile) + { + if (tile == -1) + break; + + List possibleItems; + if (!StorageWorld.TileToCreatingItem.TryGetValue(tile, out possibleItems)) + continue; + + if (!possibleItems.Any(x => IsKnownRecursively_CheckIngredient(x, availableSet, recursionTree, cache))) + { + cache[recipe] = false; + return false; + } + } + + int ingredients = 0; + for (int i = 0; i < Recipe.maxRequirements; i++) + { + var t = recipe.requiredItem[i].type; + if (t <= 0) continue; + ingredients++; + if (IsKnownRecursively_CheckIngredient(t, availableSet, recursionTree, cache)) continue; + if (IsKnownRecursively_CheckAcceptedGroupsForIngredient(recipe, availableSet, recursionTree, cache, t)) continue; + cache[recipe] = false; + return false; + } + + if (ingredients > 0) + { + cache[recipe] = true; + return true; + } + + cache[recipe] = false; + return false; + } + + static bool IsKnownRecursively_CheckAcceptedGroupsForIngredient(Recipe recipe, HashSet availableSet, HashSet recursionTree, Dictionary cache, int t) + { + foreach (var g in recipe.acceptedGroups.Select(j => RecipeGroup.recipeGroups[j])) + { + if (g.ContainsItem(t)) + { + foreach (var groupItemType in g.ValidItems) + { + if (groupItemType != t && IsKnownRecursively_CheckIngredient(groupItemType, availableSet, recursionTree, cache)) + { + return true; + } + } + } + } + return false; + } + + static bool IsKnownRecursively_CheckIngredient(int t, HashSet availableSet, HashSet recursionTree, Dictionary cache) + { + if (availableSet.Contains(t)) return true; + if (!recursionTree.Add(t)) return false; + try + { + List ingredientRecipes; + if (!_productToRecipes.TryGetValue(t, out ingredientRecipes)) return false; + if (ingredientRecipes.Count == 0 || ingredientRecipes.All(x => !IsKnownRecursively(x, availableSet, recursionTree, cache))) return false; + } + finally + { + recursionTree.Remove(t); + } + + return true; + } + + private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craftedRecipes, HashSet favorited) + { + while (true) + { + try + { + SortMode sortMode; + FilterMode filterMode; + HashSet foundItems; + lock (threadLock) + { + threadNeedsRestart = false; + sortMode = threadSortMode; + filterMode = threadFilterMode; + foundItems = threadCheckListFoundItems; + } + + var availableItemsMutable = new HashSet(hiddenRecipes + .Concat(craftedRecipes) + .Concat(foundItems)); + + var notNewItems = new HashSet(availableItemsMutable); + + var temp = new HashSet(); + var tempCache = new Dictionary(); + + var modFilterIndex = modSearchBox.ModIndex; + + IEnumerable filteredRecipes = null; + + Action doFiltering = () => + { + filteredRecipes = ItemSorter.GetRecipes(sortMode, filterMode, modFilterIndex, searchBar.Text).Where(x => x != null) + // show only blacklisted recipes only if choice = 2, otherwise show all other + .Where(x => (recipeButtons.Choice == RecipeButtonsBlacklistChoice) == hiddenRecipes.Contains(x.createItem.type)) + // show only new items if selected + .Where(x => (recipeButtons.Choice != RecipeButtonsNewChoice) || !notNewItems.Contains(x.createItem.type)) + // show only favorited items if selected + .Where(x => (recipeButtons.Choice != RecipeButtonsFavoritesChoice) || favorited.Contains(x.createItem.type)) + // hard check if this item can be crafted from available items and their recursive products + .Where(x => !wasItemChecklistRetrieved || IsKnownRecursively(x, availableItemsMutable, temp, tempCache)) + .OrderBy(x => favorited.Contains(x.createItem.type) ? 0 : 1); + + threadRecipes.Clear(); + threadRecipeAvailable.Clear(); + try + { + threadRecipes.AddRange(filteredRecipes); + threadRecipeAvailable.AddRange(threadRecipes.Select(IsAvailable)); + } + catch (InvalidOperationException) + { + } + catch (KeyNotFoundException) + { + } + }; + + doFiltering(); + + // now if nothing found we disable filters one by one + if (searchBar.Text.Length > 0) + { + if (threadRecipes.Count == 0 && recipeButtons.Choice == RecipeButtonsNewChoice) + { + // search old recipes too + notNewItems = new HashSet(); + doFiltering(); + } + + if (threadRecipes.Count == 0 && hiddenRecipes.Count > 0) + { + // search hidden recipes too + hiddenRecipes = new HashSet(); + doFiltering(); + } + + if (threadRecipes.Count == 0 && filterMode != FilterMode.All) + { + // any category + filterMode = FilterMode.All; + doFiltering(); + } + + if (threadRecipes.Count == 0 && modFilterIndex != ModSearchBox.ModIndexAll) + { + // search all mods + modFilterIndex = ModSearchBox.ModIndexAll; + doFiltering(); + } + } + + lock (recipeLock) + { + nextRecipes = new List(); + nextRecipeAvailable = new List(); + nextRecipes.AddRange(threadRecipes); + nextRecipeAvailable.AddRange(threadRecipeAvailable); + + } + lock (threadLock) + { + if (!threadNeedsRestart) + { + threadRunning = false; + return; + } + } + } + catch (Exception e) { Main.NewTextMultiline(e.ToString()); } + } + } + + private static void AnalyzeIngredients() + { + Player player = Main.player[Main.myPlayer]; + itemCounts.Clear(); + if (adjTiles.Length != player.adjTile.Length) + { + Array.Resize(ref adjTiles, player.adjTile.Length); + } + for (int k = 0; k < adjTiles.Length; k++) + { + adjTiles[k] = false; + } + adjWater = false; + adjLava = false; + adjHoney = false; + zoneSnow = false; + alchemyTable = false; + + foreach (Item item in items) + { + if (itemCounts.ContainsKey(item.netID)) + { + itemCounts[item.netID] += item.stack; + } + else + { + itemCounts[item.netID] = item.stack; + } + } + foreach (Item item in GetCraftingStations()) + { + if (item.createTile >= 0) + { + adjTiles[item.createTile] = true; + if (item.createTile == TileID.GlassKiln || item.createTile == TileID.Hellforge || item.createTile == TileID.AdamantiteForge) + { + adjTiles[TileID.Furnaces] = true; + } + if (item.createTile == TileID.AdamantiteForge) + { + adjTiles[TileID.Hellforge] = true; + } + if (item.createTile == TileID.MythrilAnvil) + { + adjTiles[TileID.Anvils] = true; + } + if (item.createTile == TileID.BewitchingTable || item.createTile == TileID.Tables2) + { + adjTiles[TileID.Tables] = true; + } + if (item.createTile == TileID.AlchemyTable) + { + adjTiles[TileID.Bottles] = true; + adjTiles[TileID.Tables] = true; + alchemyTable = true; + } + bool[] oldAdjTile = player.adjTile; + bool oldAdjWater = adjWater; + bool oldAdjLava = adjLava; + bool oldAdjHoney = adjHoney; + bool oldAlchemyTable = alchemyTable; + player.adjTile = adjTiles; + player.adjWater = false; + player.adjLava = false; + player.adjHoney = false; + player.alchemyTable = false; + TileLoader.AdjTiles(player, item.createTile); + if (player.adjWater) + { + adjWater = true; + } + if (player.adjLava) + { + adjLava = true; + } + if (player.adjHoney) + { + adjHoney = true; + } + if (player.alchemyTable) + { + alchemyTable = true; + } + player.adjTile = oldAdjTile; + player.adjWater = oldAdjWater; + player.adjLava = oldAdjLava; + player.adjHoney = oldAdjHoney; + player.alchemyTable = oldAlchemyTable; + } + if (item.type == ItemID.WaterBucket || item.type == ItemID.BottomlessBucket) + { + adjWater = true; + } + if (item.type == ItemID.LavaBucket) + { + adjLava = true; + } + if (item.type == ItemID.HoneyBucket) + { + adjHoney = true; + } + if (item.type == MagicStorage.Instance.ItemType("SnowBiomeEmulator")) + { + zoneSnow = true; + } + } + adjTiles[MagicStorage.Instance.TileType("CraftingAccess")] = true; + } + + private static bool IsAvailable(Recipe recipe) + { + foreach (int tile in recipe.requiredTile) + { + if (tile == -1) + { + break; + } + if (!adjTiles[tile]) + { + return false; + } + } + foreach (Item ingredient in recipe.requiredItem) + { + if (ingredient.type == 0) + { + break; + } + int stack = ingredient.stack; + bool useRecipeGroup = false; + foreach (int type in itemCounts.Keys) + { + if (RecipeGroupMatch(recipe, type, ingredient.type)) + { + stack -= itemCounts[type]; + useRecipeGroup = true; + } + } + if (!useRecipeGroup && itemCounts.ContainsKey(ingredient.netID)) + { + stack -= itemCounts[ingredient.netID]; + } + if (stack > 0) + { + return false; + } + } + if (recipe.needWater && !adjWater && !adjTiles[TileID.Sinks]) + { + return false; + } + if (recipe.needLava && !adjLava) + { + return false; + } + if (recipe.needHoney && !adjHoney) + { + return false; + } + if (recipe.needSnowBiome && !zoneSnow) + { + return false; + } + try + { + BlockRecipes.active = false; + if (!RecipeHooks.RecipeAvailable(recipe)) + { + return false; + } + } + finally + { + BlockRecipes.active = true; + } + return true; + } + + private static bool PassesBlock(Recipe recipe) + { + foreach (Item ingredient in recipe.requiredItem) + { + if (ingredient.type == 0) + { + break; + } + int stack = ingredient.stack; + bool useRecipeGroup = false; + foreach (Item item in storageItems) + { + ItemData data = new ItemData(item); + if (!blockStorageItems.Contains(data) && RecipeGroupMatch(recipe, item.netID, ingredient.type)) + { + stack -= item.stack; + useRecipeGroup = true; + } + } + if (!useRecipeGroup) + { + foreach (Item item in storageItems) + { + ItemData data = new ItemData(item); + if (!blockStorageItems.Contains(data) && item.netID == ingredient.netID) + { + stack -= item.stack; + } + } + } + if (stack > 0) + { + return false; + } + } + return true; + } + + private static void RefreshStorageItems() + { + storageItems.Clear(); + result = null; + if (selectedRecipe != null) + { + foreach (Item item in items) + { + for (int k = 0; k < selectedRecipe.requiredItem.Length; k++) + { + if (selectedRecipe.requiredItem[k].type == 0) + { + break; + } + if (item.type == selectedRecipe.requiredItem[k].type || RecipeGroupMatch(selectedRecipe, selectedRecipe.requiredItem[k].type, item.type)) + { + storageItems.Add(item); + } + } + if (item.type == selectedRecipe.createItem.type) + { + result = item; + } + } + if (result == null) + { + result = new Item(); + result.SetDefaults(selectedRecipe.createItem.type); + result.stack = 0; + } + } + } + + private static bool RecipeGroupMatch(Recipe recipe, int type1, int type2) + { + return recipe.useWood(type1, type2) || recipe.useSand(type1, type2) || recipe.useIronBar(type1, type2) || recipe.useFragment(type1, type2) || recipe.AcceptedByItemGroups(type1, type2) || recipe.usePressurePlate(type1, type2); + } + + private static void HoverStation(int slot, ref int hoverSlot) + { + TECraftingAccess ent = GetCraftingEntity(); + if (ent == null || slot >= ent.stations.Length) + { + return; + } + + Player player = Main.player[Main.myPlayer]; + if (MouseClicked) + { + bool changed = false; + if (!ent.stations[slot].IsAir && ItemSlot.ShiftInUse) + { + Item result = player.GetItem(Main.myPlayer, DoWithdraw(slot), false, true); + if (!result.IsAir && Main.mouseItem.IsAir) + { + Main.mouseItem = result; + result = new Item(); + } + if (!result.IsAir && Main.mouseItem.type == result.type && Main.mouseItem.stack < Main.mouseItem.maxStack) + { + Main.mouseItem.stack += result.stack; + result = new Item(); + } + if (!result.IsAir) + { + player.QuickSpawnClonedItem(result); + } + changed = true; + } + else if (player.itemAnimation == 0 && player.itemTime == 0) + { + int oldType = Main.mouseItem.type; + int oldStack = Main.mouseItem.stack; + Main.mouseItem = DoStationSwap(Main.mouseItem, slot); + if (oldType != Main.mouseItem.type || oldStack != Main.mouseItem.stack) + { + changed = true; + } + } + if (changed) + { + RefreshItems(); + Main.PlaySound(7, -1, -1, 1); + } + } + + hoverSlot = slot; + } + + private static void HoverRecipe(int slot, ref int hoverSlot) + { + int visualSlot = slot; + slot += numColumns * (int)Math.Round(scrollBar.ViewPosition); + if (slot < recipes.Count) + { + var recipe = recipes[slot]; + if (MouseClicked) + { + if (Main.keyState.IsKeyDown(Keys.LeftAlt)) + { + if (!ModPlayer.FavoritedRecipes.Add(recipe.createItem)) + ModPlayer.FavoritedRecipes.Remove(recipe.createItem); + } + else if (Main.keyState.IsKeyDown(Keys.LeftControl)) + { + if (recipeButtons.Choice == RecipeButtonsBlacklistChoice) + { + if (ModPlayer.RemoveFromHiddenRecipes(recipe.createItem)) + RefreshItems(); + } + else + { + if (ModPlayer.AddToHiddenRecipes(recipe.createItem)) + RefreshItems(); + } + } + else + SetSelectedRecipe(recipe); + } + else if (RightMouseClicked && (recipe == selectedRecipe || recipeButtons.Choice != RecipeButtonsNewChoice)) + { + if (recipeButtons.Choice == RecipeButtonsNewChoice) + { + ModPlayer.AsKnownRecipes.Add(recipe.createItem); + RefreshItems(); + } + else + ModPlayer.AsKnownRecipes.Remove(recipe.createItem); + } + + hoverSlot = visualSlot; + } + } + + static void SetSelectedRecipe(Recipe recipe) + { + if (recipe != null) ModPlayer.SeenRecipes.Add(recipe.createItem); + selectedRecipe = recipe; + RefreshStorageItems(); + blockStorageItems.Clear(); + } + + private static void HoverHeader(int slot, ref int hoverSlot) + { + hoverSlot = slot; + } + + private static void HoverItem(int slot, ref int hoverSlot) + { + if (selectedRecipe == null) + { + hoverSlot = slot; + return; + } + int visualSlot = slot; + slot += numColumns2 * (int)Math.Round(scrollBar2.ViewPosition); + var count = selectedRecipe.requiredItem.Select((x, i) => new { x, i }).First(x => x.x.type == 0).i + 1; + + if (slot < count) + { + // select ingredient recipe by right clicking + if (RightMouseClicked) + { + var item = selectedRecipe.requiredItem[slot]; + EnsureProductToRecipesInited(); + List itemRecipes; + if (_productToRecipes.TryGetValue(item.type, out itemRecipes)) + { + var knownItems = GetKnownItems(); + + var recursionTree = new HashSet(); + var cache = new Dictionary(); + + Recipe selected = null; + + foreach (var r in itemRecipes.Where(x => IsKnownRecursively(x, knownItems, recursionTree, cache))) + { + if (selected == null) selected = r; + if (IsAvailable(r)) + { + selected = r; + break; + } + } + if (selected != null) SetSelectedRecipe(selected); + } + } + hoverSlot = visualSlot; + } + } + + private static void HoverStorage(int slot, ref int hoverSlot) + { + int visualSlot = slot; + slot += numColumns2 * (int)Math.Round(scrollBar2.ViewPosition); + if (slot < storageItems.Count) + { + var item = storageItems[slot]; + item.newAndShiny = false; + if (MouseClicked) + { + ItemData data = new ItemData(item); + if (blockStorageItems.Contains(data)) + { + blockStorageItems.Remove(data); + } + else + { + blockStorageItems.Add(data); + } + } + hoverSlot = visualSlot; + } + } + + private static void HoverResult(int slot, ref int hoverSlot) + { + if (slot != 0) + { + return; + } + + if (Main.mouseItem.IsAir && result != null && !result.IsAir) + result.newAndShiny = false; + + Player player = Main.player[Main.myPlayer]; + if (MouseClicked) + { + bool changed = false; + if (!Main.mouseItem.IsAir && player.itemAnimation == 0 && player.itemTime == 0 && result != null && Main.mouseItem.type == result.type) + { + if (TryDepositResult(Main.mouseItem)) + { + changed = true; + } + } + else if (Main.mouseItem.IsAir && result != null && !result.IsAir) + { + if (Main.keyState.IsKeyDown(Keys.LeftAlt)) + result.favorited = !result.favorited; + else + { + Item toWithdraw = result.Clone(); + if (toWithdraw.stack > toWithdraw.maxStack) + { + toWithdraw.stack = toWithdraw.maxStack; + } + Main.mouseItem = DoWithdrawResult(toWithdraw, ItemSlot.ShiftInUse); + if (ItemSlot.ShiftInUse) + { + Main.mouseItem = player.GetItem(Main.myPlayer, Main.mouseItem, false, true); + } + changed = true; + } + } + if (changed) + { + RefreshItems(); + Main.PlaySound(7, -1, -1, 1); + } + } + + if (curMouse.RightButton == ButtonState.Pressed && oldMouse.RightButton == ButtonState.Released && result != null && !result.IsAir && (Main.mouseItem.IsAir || ItemData.Matches(Main.mouseItem, items[slot]) && Main.mouseItem.stack < Main.mouseItem.maxStack)) + { + slotFocus = true; + } + + hoverSlot = slot; + + if (slotFocus) + { + SlotFocusLogic(); + } + } + + private static void SlotFocusLogic() + { + if (result == null || result.IsAir || (!Main.mouseItem.IsAir && (!ItemData.Matches(Main.mouseItem, result) || Main.mouseItem.stack >= Main.mouseItem.maxStack))) + { + ResetSlotFocus(); + } + else + { + if (rightClickTimer <= 0) + { + rightClickTimer = maxRightClickTimer; + maxRightClickTimer = maxRightClickTimer * 3 / 4; + if (maxRightClickTimer <= 0) + { + maxRightClickTimer = 1; + } + Item toWithdraw = result.Clone(); + toWithdraw.stack = 1; + Item withdrawn = DoWithdrawResult(toWithdraw); + if (Main.mouseItem.IsAir) + { + Main.mouseItem = withdrawn; + } + else + { + Main.mouseItem.stack += withdrawn.stack; + } + Main.soundInstanceMenuTick.Stop(); + Main.soundInstanceMenuTick = Main.soundMenuTick.CreateInstance(); + Main.PlaySound(12, -1, -1, 1); + RefreshItems(); + } + rightClickTimer--; + } + } + + private static void ResetSlotFocus() + { + slotFocus = false; + rightClickTimer = 0; + maxRightClickTimer = startMaxRightClickTimer; + } + + private static Item DoWithdraw(int slot) + { + TECraftingAccess access = GetCraftingEntity(); + if (Main.netMode == 0) + { + Item result = access.TryWithdrawStation(slot); + RefreshItems(); + return result; + } + else + { + NetHelper.SendWithdrawStation(access.ID, slot); + return new Item(); + } + } + + private static Item DoStationSwap(Item item, int slot) + { + TECraftingAccess access = GetCraftingEntity(); + if (Main.netMode == 0) + { + Item result = access.DoStationSwap(item, slot); + RefreshItems(); + return result; + } + else + { + NetHelper.SendStationSlotClick(access.ID, item, slot); + return new Item(); + } + } + + private static void TryCraft() + { + List availableItems = new List(storageItems.Where(item => !blockStorageItems.Contains(new ItemData(item))).Select(item => item.Clone())); + List toWithdraw = new List(); + for (int k = 0; k < selectedRecipe.requiredItem.Length; k++) + { + Item item = selectedRecipe.requiredItem[k]; + if (item.type == 0) + { + break; + } + int stack = item.stack; + ModRecipe modRecipe = selectedRecipe as ModRecipe; + if (modRecipe != null) + { + stack = modRecipe.ConsumeItem(item.type, item.stack); + } + if (selectedRecipe.alchemy && alchemyTable) + { + int save = 0; + for (int j = 0; j < stack; j++) + { + if (Main.rand.Next(3) == 0) + { + save++; + } + } + stack -= save; + } + if (stack > 0) + { + foreach (Item tryItem in availableItems) + { + if (item.type == tryItem.type || RecipeGroupMatch(selectedRecipe, item.type, tryItem.type)) + { + if (tryItem.stack > stack) + { + Item temp = tryItem.Clone(); + temp.stack = stack; + toWithdraw.Add(temp); + tryItem.stack -= stack; + stack = 0; + } + else + { + toWithdraw.Add(tryItem.Clone()); + stack -= tryItem.stack; + tryItem.stack = 0; + tryItem.type = 0; + } + } + } + } + } + Item resultItem = selectedRecipe.createItem.Clone(); + resultItem.Prefix(-1); + + RecipeHooks.OnCraft(resultItem, selectedRecipe); + ItemLoader.OnCraft(resultItem, selectedRecipe); + + if (Main.netMode == 0) + { + foreach (Item item in DoCraft(GetHeart(), toWithdraw, resultItem)) + { + Main.player[Main.myPlayer].QuickSpawnClonedItem(item, item.stack); + } + } + else if (Main.netMode == 1) + { + NetHelper.SendCraftRequest(GetHeart().ID, toWithdraw, resultItem); + } + } + + internal static List DoCraft(TEStorageHeart heart, List toWithdraw, Item result) + { + List items = new List(); + foreach (Item tryWithdraw in toWithdraw) + { + Item withdrawn = heart.TryWithdraw(tryWithdraw, false); + if (!withdrawn.IsAir) + { + items.Add(withdrawn); + } + if (withdrawn.stack < tryWithdraw.stack) + { + for (int k = 0; k < items.Count; k++) + { + heart.DepositItem(items[k]); + if (items[k].IsAir) + { + items.RemoveAt(k); + k--; + } + } + return items; + } + } + items.Clear(); + heart.DepositItem(result); + if (!result.IsAir) + { + items.Add(result); + } + return items; + } + + private static bool TryDepositResult(Item item) + { + int oldStack = item.stack; + DoDepositResult(item); + return oldStack != item.stack; + } + + private static void DoDepositResult(Item item) + { + TEStorageHeart heart = GetHeart(); + if (Main.netMode == 0) + { + heart.DepositItem(item); + } + else + { + NetHelper.SendDeposit(heart.ID, item); + item.SetDefaults(0, true); + } + } + + private static Item DoWithdrawResult(Item item, bool toInventory = false) + { + TEStorageHeart heart = GetHeart(); + if (Main.netMode == 0) + { + return heart.TryWithdraw(item, false); + } + else + { + NetHelper.SendWithdraw(heart.ID, item, toInventory); + return new Item(); + } + } + } +} \ No newline at end of file diff --git a/DpsTooltips.cs b/DpsTooltips.cs index 575dc019..f2997369 100644 --- a/DpsTooltips.cs +++ b/DpsTooltips.cs @@ -1,17 +1,17 @@ -using System.Collections.Generic; -using MagicStorage.Sorting; -using Terraria; -using Terraria.ModLoader; - -namespace MagicStorage -{ - public class DpsTooltips : GlobalItem - { - public override void ModifyTooltips(Item item, List tooltips) - { - var dps = CompareDps.GetDps(item); - if (dps > 1f) - tooltips.Add(new TooltipLine(MagicStorage.Instance, "DPS", dps.ToString("F0") + " DPS")); - } - } -} \ No newline at end of file +using System.Collections.Generic; +using MagicStorage.Sorting; +using Terraria; +using Terraria.ModLoader; + +namespace MagicStorage +{ + public class DpsTooltips : GlobalItem + { + public override void ModifyTooltips(Item item, List tooltips) + { + var dps = CompareDps.GetDps(item); + if (dps > 1f) + tooltips.Add(new TooltipLine(MagicStorage.Instance, "DPS", dps.ToString("F0") + " DPS")); + } + } +} diff --git a/GUIHelpers.cs b/GUIHelpers.cs index 9e5fd142..b0245f0c 100644 --- a/GUIHelpers.cs +++ b/GUIHelpers.cs @@ -1,77 +1,77 @@ -using System; -using System.Collections.Generic; -using Microsoft.Xna.Framework.Graphics; -using Terraria; -using Terraria.Localization; - -namespace MagicStorage -{ - public class GUIHelpers - { - - public static UIButtonChoice MakeSortButtons(Action onChanged) - { - return new UIButtonChoice(onChanged, new Texture2D[] - { - Main.inventorySortTexture[0], - MagicStorage.Instance.GetTexture("SortID"), - MagicStorage.Instance.GetTexture("SortName"), - MagicStorage.Instance.GetTexture("SortNumber"), - MagicStorage.Instance.GetTexture("SortNumber") - }, - new LocalizedText[] - { - Language.GetText("Mods.MagicStorage.SortDefault"), - Language.GetText("Mods.MagicStorage.SortID"), - Language.GetText("Mods.MagicStorage.SortName"), - Language.GetText("Mods.MagicStorage.SortStack"), - Language.GetText("Mods.MagicStorage.SortDps") - }); - } - - public static UIButtonChoice MakeFilterButtons(bool withHistory, Action onChanged) - { - var textures = new List - { - MagicStorage.Instance.GetTexture("FilterAll"), - MagicStorage.Instance.GetTexture("FilterMelee"), - MagicStorage.Instance.GetTexture("FilterRanged"), - MagicStorage.Instance.GetTexture("FilterMagic"), - MagicStorage.Instance.GetTexture("FilterSummon"), - MagicStorage.Instance.GetTexture("FilterThrowing"), - MagicStorage.Instance.GetTexture("FilterThrowing"), - MagicStorage.Instance.GetTexture("FilterPickaxe"), - MagicStorage.Instance.GetTexture("FilterArmor"), - MagicStorage.Instance.GetTexture("FilterArmor"), - MagicStorage.Instance.GetTexture("FilterArmor"), - MagicStorage.Instance.GetTexture("FilterPotion"), - MagicStorage.Instance.GetTexture("FilterTile"), - MagicStorage.Instance.GetTexture("FilterMisc"), - }; - var texts = new List - { - Language.GetText("Mods.MagicStorage.FilterAll"), - Language.GetText("Mods.MagicStorage.FilterWeaponsMelee"), - Language.GetText("Mods.MagicStorage.FilterWeaponsRanged"), - Language.GetText("Mods.MagicStorage.FilterWeaponsMagic"), - Language.GetText("Mods.MagicStorage.FilterWeaponsSummon"), - Language.GetText("Mods.MagicStorage.FilterWeaponsThrown"), - Language.GetText("Mods.MagicStorage.FilterAmmo"), - Language.GetText("Mods.MagicStorage.FilterTools"), - Language.GetText("Mods.MagicStorage.FilterArmor"), - Language.GetText("Mods.MagicStorage.FilterEquips"), - Language.GetText("Mods.MagicStorage.FilterVanity"), - Language.GetText("Mods.MagicStorage.FilterPotions"), - Language.GetText("Mods.MagicStorage.FilterTiles"), - Language.GetText("Mods.MagicStorage.FilterMisc") +using System; +using System.Collections.Generic; +using Microsoft.Xna.Framework.Graphics; +using Terraria; +using Terraria.Localization; + +namespace MagicStorage +{ + public class GUIHelpers + { + + public static UIButtonChoice MakeSortButtons(Action onChanged) + { + return new UIButtonChoice(onChanged, new Texture2D[] + { + Main.inventorySortTexture[0], + MagicStorage.Instance.GetTexture("SortID"), + MagicStorage.Instance.GetTexture("SortName"), + MagicStorage.Instance.GetTexture("SortNumber"), + MagicStorage.Instance.GetTexture("SortNumber") + }, + new LocalizedText[] + { + Language.GetText("Mods.MagicStorage.SortDefault"), + Language.GetText("Mods.MagicStorage.SortID"), + Language.GetText("Mods.MagicStorage.SortName"), + Language.GetText("Mods.MagicStorage.SortStack"), + Language.GetText("Mods.MagicStorage.SortDps") + }); + } + + public static UIButtonChoice MakeFilterButtons(bool withHistory, Action onChanged) + { + var textures = new List + { + MagicStorage.Instance.GetTexture("FilterAll"), + MagicStorage.Instance.GetTexture("FilterMelee"), + MagicStorage.Instance.GetTexture("FilterRanged"), + MagicStorage.Instance.GetTexture("FilterMagic"), + MagicStorage.Instance.GetTexture("FilterSummon"), + MagicStorage.Instance.GetTexture("FilterThrowing"), + MagicStorage.Instance.GetTexture("FilterThrowing"), + MagicStorage.Instance.GetTexture("FilterPickaxe"), + MagicStorage.Instance.GetTexture("FilterArmor"), + MagicStorage.Instance.GetTexture("FilterArmor"), + MagicStorage.Instance.GetTexture("FilterArmor"), + MagicStorage.Instance.GetTexture("FilterPotion"), + MagicStorage.Instance.GetTexture("FilterTile"), + MagicStorage.Instance.GetTexture("FilterMisc"), + }; + var texts = new List + { + Language.GetText("Mods.MagicStorage.FilterAll"), + Language.GetText("Mods.MagicStorage.FilterWeaponsMelee"), + Language.GetText("Mods.MagicStorage.FilterWeaponsRanged"), + Language.GetText("Mods.MagicStorage.FilterWeaponsMagic"), + Language.GetText("Mods.MagicStorage.FilterWeaponsSummon"), + Language.GetText("Mods.MagicStorage.FilterWeaponsThrown"), + Language.GetText("Mods.MagicStorage.FilterAmmo"), + Language.GetText("Mods.MagicStorage.FilterTools"), + Language.GetText("Mods.MagicStorage.FilterArmor"), + Language.GetText("Mods.MagicStorage.FilterEquips"), + Language.GetText("Mods.MagicStorage.FilterVanity"), + Language.GetText("Mods.MagicStorage.FilterPotions"), + Language.GetText("Mods.MagicStorage.FilterTiles"), + Language.GetText("Mods.MagicStorage.FilterMisc") }; - if (withHistory) - { + if (withHistory) + { textures.Add(MagicStorage.Instance.GetTexture("FilterAll")); - texts.Add(Language.GetText("Mods.MagicStorage.FilterRecent")); - } - return new UIButtonChoice(onChanged, textures.ToArray(), texts.ToArray()); + texts.Add(Language.GetText("Mods.MagicStorage.FilterRecent")); + } + return new UIButtonChoice(onChanged, textures.ToArray(), texts.ToArray()); } - - } -} \ No newline at end of file + + } +} diff --git a/ItemSaveLoadHook.cs b/ItemSaveLoadHook.cs index ada96e9e..cc0e6a85 100644 --- a/ItemSaveLoadHook.cs +++ b/ItemSaveLoadHook.cs @@ -1,32 +1,32 @@ -using Terraria; -using Terraria.ModLoader; -using Terraria.ModLoader.IO; - -namespace MagicStorage -{ - public class ItemSaveLoadHook : GlobalItem - { - public override TagCompound Save(Item item) - { - if (CraftingGUI.IsTestItem(item)) - { - return new TagCompound() {{"TestItem", true}}; - } - - return null; - } - - public override void Load(Item item, TagCompound tag) - { - if (tag != null && tag.ContainsKey("TestItem")) - CraftingGUI.MarkAsTestItem(item); - - base.Load(item, tag); - } - - public override bool NeedsSaving(Item item) - { - return CraftingGUI.IsTestItem(item); - } - } -} \ No newline at end of file +using Terraria; +using Terraria.ModLoader; +using Terraria.ModLoader.IO; + +namespace MagicStorage +{ + public class ItemSaveLoadHook : GlobalItem + { + public override TagCompound Save(Item item) + { + if (CraftingGUI.IsTestItem(item)) + { + return new TagCompound() {{"TestItem", true}}; + } + + return null; + } + + public override void Load(Item item, TagCompound tag) + { + if (tag != null && tag.ContainsKey("TestItem")) + CraftingGUI.MarkAsTestItem(item); + + base.Load(item, tag); + } + + public override bool NeedsSaving(Item item) + { + return CraftingGUI.IsTestItem(item); + } + } +} diff --git a/ItemTypeOrderedSet.cs b/ItemTypeOrderedSet.cs index 21770db1..98b9b357 100644 --- a/ItemTypeOrderedSet.cs +++ b/ItemTypeOrderedSet.cs @@ -1,112 +1,112 @@ -using System.Collections.Generic; -using System.Linq; -using Terraria; -using Terraria.ModLoader.IO; - -namespace MagicStorage -{ - public class ItemTypeOrderedSet - { - readonly string _name; - List _items = new List(); - HashSet _set = new HashSet(); - public int Count { get { return _items.Count; } } - - public ItemTypeOrderedSet(string name) - { - _name = name; - } - - public IEnumerable Items { get { return _items; } } - - public bool Add(Item item) - { - return Add(item.type); - } - - public bool Add(int type) - { - var item = new Item(); - item.SetDefaults(type); - if (_set.Add(item.type)) - { - _items.Add(item); - return true; - } - - return false; - } - - public bool Contains(int type) - { - return _set.Contains(type); - } - - public bool Contains(Item item) - { - return _set.Contains(item.type); - } - - public bool Remove(Item item) - { - var type = item.type; - return Remove(type); - } - - public bool Remove(int type) - { - if (_set.Remove(type)) - { - _items.RemoveAll(x => x.type == type); - return true; - } - - return false; - } - - public bool RemoveAt(int index) - { - var item = _items[index]; - if (_set.Remove(item.type)) - { - _items.RemoveAt(index); - return true; - } - - return false; - } - - const string Suffix = "~v2"; - - public void Save(TagCompound c) - { - c.Add(_name + Suffix, _items.Select(x => (int) x.type).ToList()); - } - - public void Load(TagCompound tag) - { - var list = tag.GetList(_name); - if (list != null && list.Count > 0) - _items = list.Select(ItemIO.Load).ToList(); - else - { - var listV2 = tag.GetList(_name + Suffix); - if (listV2 != null) - { - _items = listV2 - .Select(x => - { - var item = new Item(); - item.SetDefaults(x); - item.type = x; - return item; - }).ToList(); - } - else - _items = new List(); - } - - _set = new HashSet(_items.Select(x => x.type)); - } - } -} \ No newline at end of file +using System.Collections.Generic; +using System.Linq; +using Terraria; +using Terraria.ModLoader.IO; + +namespace MagicStorage +{ + public class ItemTypeOrderedSet + { + readonly string _name; + List _items = new List(); + HashSet _set = new HashSet(); + public int Count { get { return _items.Count; } } + + public ItemTypeOrderedSet(string name) + { + _name = name; + } + + public IEnumerable Items { get { return _items; } } + + public bool Add(Item item) + { + return Add(item.type); + } + + public bool Add(int type) + { + var item = new Item(); + item.SetDefaults(type); + if (_set.Add(item.type)) + { + _items.Add(item); + return true; + } + + return false; + } + + public bool Contains(int type) + { + return _set.Contains(type); + } + + public bool Contains(Item item) + { + return _set.Contains(item.type); + } + + public bool Remove(Item item) + { + var type = item.type; + return Remove(type); + } + + public bool Remove(int type) + { + if (_set.Remove(type)) + { + _items.RemoveAll(x => x.type == type); + return true; + } + + return false; + } + + public bool RemoveAt(int index) + { + var item = _items[index]; + if (_set.Remove(item.type)) + { + _items.RemoveAt(index); + return true; + } + + return false; + } + + const string Suffix = "~v2"; + + public void Save(TagCompound c) + { + c.Add(_name + Suffix, _items.Select(x => (int) x.type).ToList()); + } + + public void Load(TagCompound tag) + { + var list = tag.GetList(_name); + if (list != null && list.Count > 0) + _items = list.Select(ItemIO.Load).ToList(); + else + { + var listV2 = tag.GetList(_name + Suffix); + if (listV2 != null) + { + _items = listV2 + .Select(x => + { + var item = new Item(); + item.SetDefaults(x); + item.type = x; + return item; + }).ToList(); + } + else + _items = new List(); + } + + _set = new HashSet(_items.Select(x => x.type)); + } + } +} diff --git a/Items/CraftingAccess.cs b/Items/CraftingAccess.cs index 0412490e..71871034 100644 --- a/Items/CraftingAccess.cs +++ b/Items/CraftingAccess.cs @@ -52,3 +52,4 @@ public override void AddRecipes() } } } + diff --git a/Items/Locator.cs b/Items/Locator.cs index 6f459bfc..e6bec2ee 100644 --- a/Items/Locator.cs +++ b/Items/Locator.cs @@ -103,3 +103,4 @@ public override void NetRecieve(BinaryReader reader) } } } + diff --git a/Items/LocatorDisk.cs b/Items/LocatorDisk.cs index 90d2bd91..da7a14b9 100644 --- a/Items/LocatorDisk.cs +++ b/Items/LocatorDisk.cs @@ -53,3 +53,4 @@ public override void AddRecipes() } } } + diff --git a/Items/PortableAccess.cs b/Items/PortableAccess.cs index 42a2cfa8..64353e73 100644 --- a/Items/PortableAccess.cs +++ b/Items/PortableAccess.cs @@ -167,3 +167,4 @@ public override void AddRecipes() } } } + diff --git a/Items/RemoteAccess.cs b/Items/RemoteAccess.cs index 4a67f090..96fc7177 100644 --- a/Items/RemoteAccess.cs +++ b/Items/RemoteAccess.cs @@ -52,3 +52,4 @@ public override void AddRecipes() } } } + diff --git a/Items/StorageAccess.cs b/Items/StorageAccess.cs index 208b01cc..932cb7bd 100644 --- a/Items/StorageAccess.cs +++ b/Items/StorageAccess.cs @@ -51,3 +51,4 @@ public override void AddRecipes() } } } + diff --git a/MagicStorage.cs b/MagicStorage.cs index 4608a6db..a8c80d30 100644 --- a/MagicStorage.cs +++ b/MagicStorage.cs @@ -1,370 +1,371 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using Terraria; -using Terraria.ID; -using Terraria.ModLoader; -using Terraria.UI; -using Microsoft.Xna.Framework; -using Terraria.Localization; - -namespace MagicStorage -{ - public class MagicStorage : Mod - { - public static MagicStorage Instance; - public static Mod bluemagicMod; - public static Mod legendMod; - public static ModHotKey IsItemKnownHotKey { get; private set; } - - public static readonly Version requiredVersion = new Version(0, 9, 2, 2); - - public override void Load() - { - if (ModLoader.version < requiredVersion) - { - throw new Exception("Magic storage requires a tModLoader version of at least " + requiredVersion); - } - Instance = this; - InterfaceHelper.Initialize(); - legendMod = ModLoader.GetMod("LegendOfTerraria3"); - bluemagicMod = ModLoader.GetMod("Bluemagic"); - AddTranslations(); - AddGlobalItem("MagicStorageItemSaveLoadHook", new ItemSaveLoadHook()); - IsItemKnownHotKey = RegisterHotKey("Is This Item Known?", ""); - } - - public override void Unload() - { - Instance = null; - bluemagicMod = null; - legendMod = null; - } - - private void AddTranslations() - { - ModTranslation text = CreateTranslation("SetTo"); - text.SetDefault("Set to: X={0}, Y={1}"); - text.AddTranslation(GameCulture.Polish, "Ustawione na: X={0}, Y={1}"); - text.AddTranslation(GameCulture.French, "Mis à: X={0}, Y={1}"); - text.AddTranslation(GameCulture.Spanish, "Ajustado a: X={0}, Y={1}"); - - AddTranslation(text); - - text = CreateTranslation("SnowBiomeBlock"); - text.SetDefault("Snow Biome Block"); - text.AddTranslation(GameCulture.French, "Bloc de biome de neige"); - text.AddTranslation(GameCulture.Spanish, "Bloque de Biomas de la Nieve"); - AddTranslation(text); - - text = CreateTranslation("DepositAll"); - text.SetDefault("Transfer All"); - text.AddTranslation(GameCulture.Russian, "Переместить всё"); - text.AddTranslation(GameCulture.French, "Déposer tout"); - text.AddTranslation(GameCulture.Spanish, "Depositar todo"); - AddTranslation(text); - - text = CreateTranslation("Search"); - text.SetDefault("Search"); - text.AddTranslation(GameCulture.Russian, "Поиск"); - text.AddTranslation(GameCulture.French, "Rechercher"); - text.AddTranslation(GameCulture.Spanish, "Buscar"); - AddTranslation(text); - - text = CreateTranslation("SearchName"); - text.SetDefault("Search Name"); - text.AddTranslation(GameCulture.Russian, "Поиск по имени"); - text.AddTranslation(GameCulture.French, "Recherche par nom"); - text.AddTranslation(GameCulture.Spanish, "búsqueda por nombre"); - AddTranslation(text); - - text = CreateTranslation("SearchMod"); - text.SetDefault("Search Mod"); - text.AddTranslation(GameCulture.Russian, "Поиск по моду"); - text.AddTranslation(GameCulture.French, "Recherche par mod"); - text.AddTranslation(GameCulture.Spanish, "búsqueda por mod"); - AddTranslation(text); - - text = CreateTranslation("SortDefault"); - text.SetDefault("Default Sorting"); - text.AddTranslation(GameCulture.Russian, "Стандартная сортировка"); - text.AddTranslation(GameCulture.French, "Tri Standard"); - text.AddTranslation(GameCulture.Spanish, "Clasificación por defecto"); - AddTranslation(text); - - text = CreateTranslation("SortID"); - text.SetDefault("Sort by ID"); - text.AddTranslation(GameCulture.Russian, "Сортировка по ID"); - text.AddTranslation(GameCulture.French, "Trier par ID"); - text.AddTranslation(GameCulture.Spanish, "Ordenar por ID"); - AddTranslation(text); - - text = CreateTranslation("SortName"); - text.SetDefault("Sort by Name"); - text.AddTranslation(GameCulture.Russian, "Сортировка по имени"); - text.AddTranslation(GameCulture.French, "Trier par nom"); - text.AddTranslation(GameCulture.Spanish, "Ordenar por nombre"); - AddTranslation(text); - - text = CreateTranslation("SortStack"); - text.SetDefault("Sort by Value"); - AddTranslation(text); - - text = CreateTranslation("FilterAll"); - text.SetDefault("Filter All"); - text.AddTranslation(GameCulture.Russian, "Фильтр (Всё)"); - text.AddTranslation(GameCulture.French, "Filtrer tout"); - text.AddTranslation(GameCulture.Spanish, "Filtrar todo"); - AddTranslation(text); - - text = CreateTranslation("FilterWeapons"); - text.SetDefault("Filter Weapons"); - text.AddTranslation(GameCulture.Russian, "Фильтр (Оружия)"); - text.AddTranslation(GameCulture.French, "Filtrer par armes"); - text.AddTranslation(GameCulture.Spanish, "Filtrar por armas"); - AddTranslation(text); - - text = CreateTranslation("FilterTools"); - text.SetDefault("Filter Tools"); - text.AddTranslation(GameCulture.Russian, "Фильтр (Инструменты)"); - text.AddTranslation(GameCulture.French, "Filtrer par outils"); - text.AddTranslation(GameCulture.Spanish, "Filtrar por herramientas"); - AddTranslation(text); - - text = CreateTranslation("FilterEquips"); - text.SetDefault("Filter Equipment"); - text.AddTranslation(GameCulture.Russian, "Фильтр (Снаряжения)"); - text.AddTranslation(GameCulture.French, "Filtrer par Équipement"); - text.AddTranslation(GameCulture.Spanish, "Filtrar por equipamiento"); - AddTranslation(text); - - text = CreateTranslation("FilterWeaponsMelee"); - text.SetDefault("Filter Melee Weapons"); - AddTranslation(text); - - text = CreateTranslation("FilterWeaponsRanged"); - text.SetDefault("Filter Ranged Weapons"); - AddTranslation(text); - - text = CreateTranslation("FilterWeaponsMagic"); - text.SetDefault("Filter Magic Weapons"); - AddTranslation(text); - - text = CreateTranslation("FilterWeaponsSummon"); - text.SetDefault("Filter Summons"); - AddTranslation(text); - - text = CreateTranslation("FilterWeaponsThrown"); - text.SetDefault("Filter Throwing Weapons"); - AddTranslation(text); - - text = CreateTranslation("FilterAmmo"); - text.SetDefault("Filter Ammo"); - AddTranslation(text); - - text = CreateTranslation("FilterArmor"); - text.SetDefault("Filter Armor"); - AddTranslation(text); - - text = CreateTranslation("FilterVanity"); - text.SetDefault("Filter Vanity Items"); - AddTranslation(text); - - - text = CreateTranslation("FilterPotions"); - text.SetDefault("Filter Potions"); - text.AddTranslation(GameCulture.Russian, "Фильтр (Зелья)"); - text.AddTranslation(GameCulture.French, "Filtrer par potions"); - text.AddTranslation(GameCulture.Spanish, "Filtrar por poción"); - AddTranslation(text); - - text = CreateTranslation("FilterTiles"); - text.SetDefault("Filter Placeables"); - text.AddTranslation(GameCulture.Russian, "Фильтр (Размещаемое)"); - text.AddTranslation(GameCulture.French, "Filtrer par placeable"); - text.AddTranslation(GameCulture.Spanish, "Filtrar por metido"); - AddTranslation(text); - - text = CreateTranslation("FilterMisc"); - text.SetDefault("Filter Misc"); - text.AddTranslation(GameCulture.Russian, "Фильтр (Разное)"); - text.AddTranslation(GameCulture.French, "Filtrer par miscellanées"); - text.AddTranslation(GameCulture.Spanish, "Filtrar por otros"); - AddTranslation(text); - - text = CreateTranslation("FilterRecent"); - text.SetDefault("Filter New Recently Added Items"); - AddTranslation(text); - - text = CreateTranslation("CraftingStations"); - text.SetDefault("Crafting Stations"); - text.AddTranslation(GameCulture.Russian, "Станции создания"); - text.AddTranslation(GameCulture.French, "Stations d'artisanat"); - text.AddTranslation(GameCulture.Spanish, "Estaciones de elaboración"); - AddTranslation(text); - - text = CreateTranslation("Recipes"); - text.SetDefault("Recipes"); - text.AddTranslation(GameCulture.Russian, "Рецепты"); - text.AddTranslation(GameCulture.French, "Recettes"); - text.AddTranslation(GameCulture.Spanish, "Recetas"); - AddTranslation(text); - - text = CreateTranslation("SelectedRecipe"); - text.SetDefault("Selected Recipe"); - text.AddTranslation(GameCulture.French, "Recette sélectionnée"); - text.AddTranslation(GameCulture.Spanish, "Receta seleccionada"); - AddTranslation(text); - - text = CreateTranslation("Ingredients"); - text.SetDefault("Ingredients"); - text.AddTranslation(GameCulture.French, "Ingrédients"); - text.AddTranslation(GameCulture.Spanish, "Ingredientes"); - AddTranslation(text); - - text = CreateTranslation("StoredItems"); - text.SetDefault("Stored Ingredients"); - text.AddTranslation(GameCulture.French, "Ingrédients Stockés"); - text.AddTranslation(GameCulture.Spanish, "Ingredientes almacenados"); - AddTranslation(text); - - text = CreateTranslation("RecipeAvailable"); - text.SetDefault("Show new recipes (right click to remove \"new\" flag)"); - AddTranslation(text); - - text = CreateTranslation("RecipeAll"); - text.SetDefault("Show all known recipes"); - AddTranslation(text); - - text = CreateTranslation("RecipeBlacklist"); - text.SetDefault("Show hidden recipes (ctrl+click on recipe to (un)hide)"); - AddTranslation(text); - - text = CreateTranslation("SortDps"); - text.SetDefault("Sort by DPS"); - AddTranslation(text); - - text = CreateTranslation("ShowOnlyFavorited"); - text.SetDefault("Only Favorited"); - AddTranslation(text); - - text = CreateTranslation("DepositTooltip"); - text.SetDefault("Quick Stack - click, Deposit All - ctrl+click, Restock - right click"); - AddTranslation(text); - - text = CreateTranslation("CraftTooltip"); - text.SetDefault("Left click to Craft, Right click to get item for a test (only for new items)"); - AddTranslation(text); - - text = CreateTranslation("TestItemSuffix"); - text.SetDefault(" !UNTIL RESPAWN!"); - AddTranslation(text); - } - - public override void PostSetupContent() - { - - var type = Assembly.GetAssembly(typeof(Mod)).GetType("Terraria.ModLoader.Mod"); - FieldInfo loadModsField = type.GetField("items", BindingFlags.Instance | BindingFlags.NonPublic); - - AllMods = ModLoader.GetLoadedMods().Where(x => ((Dictionary)loadModsField.GetValue(ModLoader.GetMod(x))).Count > 0).ToArray(); - } - - public string[] AllMods { get; private set; } - - public override void AddRecipeGroups() - { - RecipeGroup group = new RecipeGroup(() => Lang.misc[37] + " Chest", - ItemID.Chest, - ItemID.GoldChest, - ItemID.ShadowChest, - ItemID.EbonwoodChest, - ItemID.RichMahoganyChest, - ItemID.PearlwoodChest, - ItemID.IvyChest, - ItemID.IceChest, - ItemID.LivingWoodChest, - ItemID.SkywareChest, - ItemID.ShadewoodChest, - ItemID.WebCoveredChest, - ItemID.LihzahrdChest, - ItemID.WaterChest, - ItemID.JungleChest, - ItemID.CorruptionChest, - ItemID.CrimsonChest, - ItemID.HallowedChest, - ItemID.FrozenChest, - ItemID.DynastyChest, - ItemID.HoneyChest, - ItemID.SteampunkChest, - ItemID.PalmWoodChest, - ItemID.MushroomChest, - ItemID.BorealWoodChest, - ItemID.SlimeChest, - ItemID.GreenDungeonChest, - ItemID.PinkDungeonChest, - ItemID.BlueDungeonChest, - ItemID.BoneChest, - ItemID.CactusChest, - ItemID.FleshChest, - ItemID.ObsidianChest, - ItemID.PumpkinChest, - ItemID.SpookyChest, - ItemID.GlassChest, - ItemID.MartianChest, - ItemID.GraniteChest, - ItemID.MeteoriteChest, - ItemID.MarbleChest); - RecipeGroup.RegisterGroup("MagicStorage:AnyChest", group); - group = new RecipeGroup(() => Lang.misc[37].Value + " " + Language.GetTextValue("Mods.MagicStorage.SnowBiomeBlock"), ItemID.SnowBlock, ItemID.IceBlock, ItemID.PurpleIceBlock, ItemID.PinkIceBlock); - if (bluemagicMod != null) - { - group.ValidItems.Add(bluemagicMod.ItemType("DarkBlueIce")); - } - RecipeGroup.RegisterGroup("MagicStorage:AnySnowBiomeBlock", group); - group = new RecipeGroup(() => Lang.misc[37].Value + " " + Lang.GetItemNameValue(ItemID.Diamond), ItemID.Diamond, ItemType("ShadowDiamond")); - if (legendMod != null) - { - group.ValidItems.Add(legendMod.ItemType("GemChrysoberyl")); - group.ValidItems.Add(legendMod.ItemType("GemAlexandrite")); - } - RecipeGroup.RegisterGroup("MagicStorage:AnyDiamond", group); - if (legendMod != null) - { - group = new RecipeGroup(() => Lang.misc[37].Value + " " + Lang.GetItemNameValue(ItemID.Amethyst), ItemID.Amethyst, legendMod.ItemType("GemOnyx"), legendMod.ItemType("GemSpinel")); - RecipeGroup.RegisterGroup("MagicStorage:AnyAmethyst", group); - group = new RecipeGroup(() => Lang.misc[37].Value + " " + Lang.GetItemNameValue(ItemID.Topaz), ItemID.Topaz, legendMod.ItemType("GemGarnet")); - RecipeGroup.RegisterGroup("MagicStorage:AnyTopaz", group); - group = new RecipeGroup(() => Lang.misc[37].Value + " " + Lang.GetItemNameValue(ItemID.Sapphire), ItemID.Sapphire, legendMod.ItemType("GemCharoite")); - RecipeGroup.RegisterGroup("MagicStorage:AnySapphire", group); - group = new RecipeGroup(() => Lang.misc[37].Value + " " + Lang.GetItemNameValue(ItemID.Emerald), legendMod.ItemType("GemPeridot")); - RecipeGroup.RegisterGroup("MagicStorage:AnyEmerald", group); - group = new RecipeGroup(() => Lang.misc[37].Value + " " + Lang.GetItemNameValue(ItemID.Ruby), ItemID.Ruby, legendMod.ItemType("GemOpal")); - RecipeGroup.RegisterGroup("MagicStorage:AnyRuby", group); - } - } - - public override void HandlePacket(BinaryReader reader, int whoAmI) - { - NetHelper.HandlePacket(reader, whoAmI); - } - - public override void ModifyInterfaceLayers(List layers) - { - InterfaceHelper.ModifyInterfaceLayers(layers); - } - - public override void PostUpdateInput() - { - if (!Main.instance.IsActive) - { - return; - } - StorageGUI.Update(null); - CraftingGUI.Update(null); - } - } -} - +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using Terraria; +using Terraria.ID; +using Terraria.ModLoader; +using Terraria.UI; +using Microsoft.Xna.Framework; +using Terraria.Localization; + +namespace MagicStorage +{ + public class MagicStorage : Mod + { + public static MagicStorage Instance; + public static Mod bluemagicMod; + public static Mod legendMod; + public static ModHotKey IsItemKnownHotKey { get; private set; } + + public static readonly Version requiredVersion = new Version(0, 9, 2, 2); + + public override void Load() + { + if (ModLoader.version < requiredVersion) + { + throw new Exception("Magic storage requires a tModLoader version of at least " + requiredVersion); + } + Instance = this; + InterfaceHelper.Initialize(); + legendMod = ModLoader.GetMod("LegendOfTerraria3"); + bluemagicMod = ModLoader.GetMod("Bluemagic"); + AddTranslations(); + AddGlobalItem("MagicStorageItemSaveLoadHook", new ItemSaveLoadHook()); + IsItemKnownHotKey = RegisterHotKey("Is This Item Known?", ""); + } + + public override void Unload() + { + Instance = null; + bluemagicMod = null; + legendMod = null; + } + + private void AddTranslations() + { + ModTranslation text = CreateTranslation("SetTo"); + text.SetDefault("Set to: X={0}, Y={1}"); + text.AddTranslation(GameCulture.Polish, "Ustawione na: X={0}, Y={1}"); + text.AddTranslation(GameCulture.French, "Mis à: X={0}, Y={1}"); + text.AddTranslation(GameCulture.Spanish, "Ajustado a: X={0}, Y={1}"); + + AddTranslation(text); + + text = CreateTranslation("SnowBiomeBlock"); + text.SetDefault("Snow Biome Block"); + text.AddTranslation(GameCulture.French, "Bloc de biome de neige"); + text.AddTranslation(GameCulture.Spanish, "Bloque de Biomas de la Nieve"); + AddTranslation(text); + + text = CreateTranslation("DepositAll"); + text.SetDefault("Transfer All"); + text.AddTranslation(GameCulture.Russian, "Переместить всё"); + text.AddTranslation(GameCulture.French, "Déposer tout"); + text.AddTranslation(GameCulture.Spanish, "Depositar todo"); + AddTranslation(text); + + text = CreateTranslation("Search"); + text.SetDefault("Search"); + text.AddTranslation(GameCulture.Russian, "Поиск"); + text.AddTranslation(GameCulture.French, "Rechercher"); + text.AddTranslation(GameCulture.Spanish, "Buscar"); + AddTranslation(text); + + text = CreateTranslation("SearchName"); + text.SetDefault("Search Name"); + text.AddTranslation(GameCulture.Russian, "Поиск по имени"); + text.AddTranslation(GameCulture.French, "Recherche par nom"); + text.AddTranslation(GameCulture.Spanish, "búsqueda por nombre"); + AddTranslation(text); + + text = CreateTranslation("SearchMod"); + text.SetDefault("Search Mod"); + text.AddTranslation(GameCulture.Russian, "Поиск по моду"); + text.AddTranslation(GameCulture.French, "Recherche par mod"); + text.AddTranslation(GameCulture.Spanish, "búsqueda por mod"); + AddTranslation(text); + + text = CreateTranslation("SortDefault"); + text.SetDefault("Default Sorting"); + text.AddTranslation(GameCulture.Russian, "Стандартная сортировка"); + text.AddTranslation(GameCulture.French, "Tri Standard"); + text.AddTranslation(GameCulture.Spanish, "Clasificación por defecto"); + AddTranslation(text); + + text = CreateTranslation("SortID"); + text.SetDefault("Sort by ID"); + text.AddTranslation(GameCulture.Russian, "Сортировка по ID"); + text.AddTranslation(GameCulture.French, "Trier par ID"); + text.AddTranslation(GameCulture.Spanish, "Ordenar por ID"); + AddTranslation(text); + + text = CreateTranslation("SortName"); + text.SetDefault("Sort by Name"); + text.AddTranslation(GameCulture.Russian, "Сортировка по имени"); + text.AddTranslation(GameCulture.French, "Trier par nom"); + text.AddTranslation(GameCulture.Spanish, "Ordenar por nombre"); + AddTranslation(text); + + text = CreateTranslation("SortStack"); + text.SetDefault("Sort by Value"); + AddTranslation(text); + + text = CreateTranslation("FilterAll"); + text.SetDefault("Filter All"); + text.AddTranslation(GameCulture.Russian, "Фильтр (Всё)"); + text.AddTranslation(GameCulture.French, "Filtrer tout"); + text.AddTranslation(GameCulture.Spanish, "Filtrar todo"); + AddTranslation(text); + + text = CreateTranslation("FilterWeapons"); + text.SetDefault("Filter Weapons"); + text.AddTranslation(GameCulture.Russian, "Фильтр (Оружия)"); + text.AddTranslation(GameCulture.French, "Filtrer par armes"); + text.AddTranslation(GameCulture.Spanish, "Filtrar por armas"); + AddTranslation(text); + + text = CreateTranslation("FilterTools"); + text.SetDefault("Filter Tools"); + text.AddTranslation(GameCulture.Russian, "Фильтр (Инструменты)"); + text.AddTranslation(GameCulture.French, "Filtrer par outils"); + text.AddTranslation(GameCulture.Spanish, "Filtrar por herramientas"); + AddTranslation(text); + + text = CreateTranslation("FilterEquips"); + text.SetDefault("Filter Equipment"); + text.AddTranslation(GameCulture.Russian, "Фильтр (Снаряжения)"); + text.AddTranslation(GameCulture.French, "Filtrer par Équipement"); + text.AddTranslation(GameCulture.Spanish, "Filtrar por equipamiento"); + AddTranslation(text); + + text = CreateTranslation("FilterWeaponsMelee"); + text.SetDefault("Filter Melee Weapons"); + AddTranslation(text); + + text = CreateTranslation("FilterWeaponsRanged"); + text.SetDefault("Filter Ranged Weapons"); + AddTranslation(text); + + text = CreateTranslation("FilterWeaponsMagic"); + text.SetDefault("Filter Magic Weapons"); + AddTranslation(text); + + text = CreateTranslation("FilterWeaponsSummon"); + text.SetDefault("Filter Summons"); + AddTranslation(text); + + text = CreateTranslation("FilterWeaponsThrown"); + text.SetDefault("Filter Throwing Weapons"); + AddTranslation(text); + + text = CreateTranslation("FilterAmmo"); + text.SetDefault("Filter Ammo"); + AddTranslation(text); + + text = CreateTranslation("FilterArmor"); + text.SetDefault("Filter Armor"); + AddTranslation(text); + + text = CreateTranslation("FilterVanity"); + text.SetDefault("Filter Vanity Items"); + AddTranslation(text); + + + text = CreateTranslation("FilterPotions"); + text.SetDefault("Filter Potions"); + text.AddTranslation(GameCulture.Russian, "Фильтр (Зелья)"); + text.AddTranslation(GameCulture.French, "Filtrer par potions"); + text.AddTranslation(GameCulture.Spanish, "Filtrar por poción"); + AddTranslation(text); + + text = CreateTranslation("FilterTiles"); + text.SetDefault("Filter Placeables"); + text.AddTranslation(GameCulture.Russian, "Фильтр (Размещаемое)"); + text.AddTranslation(GameCulture.French, "Filtrer par placeable"); + text.AddTranslation(GameCulture.Spanish, "Filtrar por metido"); + AddTranslation(text); + + text = CreateTranslation("FilterMisc"); + text.SetDefault("Filter Misc"); + text.AddTranslation(GameCulture.Russian, "Фильтр (Разное)"); + text.AddTranslation(GameCulture.French, "Filtrer par miscellanées"); + text.AddTranslation(GameCulture.Spanish, "Filtrar por otros"); + AddTranslation(text); + + text = CreateTranslation("FilterRecent"); + text.SetDefault("Filter New Recently Added Items"); + AddTranslation(text); + + text = CreateTranslation("CraftingStations"); + text.SetDefault("Crafting Stations"); + text.AddTranslation(GameCulture.Russian, "Станции создания"); + text.AddTranslation(GameCulture.French, "Stations d'artisanat"); + text.AddTranslation(GameCulture.Spanish, "Estaciones de elaboración"); + AddTranslation(text); + + text = CreateTranslation("Recipes"); + text.SetDefault("Recipes"); + text.AddTranslation(GameCulture.Russian, "Рецепты"); + text.AddTranslation(GameCulture.French, "Recettes"); + text.AddTranslation(GameCulture.Spanish, "Recetas"); + AddTranslation(text); + + text = CreateTranslation("SelectedRecipe"); + text.SetDefault("Selected Recipe"); + text.AddTranslation(GameCulture.French, "Recette sélectionnée"); + text.AddTranslation(GameCulture.Spanish, "Receta seleccionada"); + AddTranslation(text); + + text = CreateTranslation("Ingredients"); + text.SetDefault("Ingredients"); + text.AddTranslation(GameCulture.French, "Ingrédients"); + text.AddTranslation(GameCulture.Spanish, "Ingredientes"); + AddTranslation(text); + + text = CreateTranslation("StoredItems"); + text.SetDefault("Stored Ingredients"); + text.AddTranslation(GameCulture.French, "Ingrédients Stockés"); + text.AddTranslation(GameCulture.Spanish, "Ingredientes almacenados"); + AddTranslation(text); + + text = CreateTranslation("RecipeAvailable"); + text.SetDefault("Show new recipes (right click to remove \"new\" flag)"); + AddTranslation(text); + + text = CreateTranslation("RecipeAll"); + text.SetDefault("Show all known recipes"); + AddTranslation(text); + + text = CreateTranslation("RecipeBlacklist"); + text.SetDefault("Show hidden recipes (ctrl+click on recipe to (un)hide)"); + AddTranslation(text); + + text = CreateTranslation("SortDps"); + text.SetDefault("Sort by DPS"); + AddTranslation(text); + + text = CreateTranslation("ShowOnlyFavorited"); + text.SetDefault("Only Favorited"); + AddTranslation(text); + + text = CreateTranslation("DepositTooltip"); + text.SetDefault("Quick Stack - click, Deposit All - ctrl+click, Restock - right click"); + AddTranslation(text); + + text = CreateTranslation("CraftTooltip"); + text.SetDefault("Left click to Craft, Right click to get item for a test (only for new items)"); + AddTranslation(text); + + text = CreateTranslation("TestItemSuffix"); + text.SetDefault(" !UNTIL RESPAWN!"); + AddTranslation(text); + } + + public override void PostSetupContent() + { + + var type = Assembly.GetAssembly(typeof(Mod)).GetType("Terraria.ModLoader.Mod"); + FieldInfo loadModsField = type.GetField("items", BindingFlags.Instance | BindingFlags.NonPublic); + + AllMods = ModLoader.GetLoadedMods().Where(x => ((Dictionary)loadModsField.GetValue(ModLoader.GetMod(x))).Count > 0).ToArray(); + } + + public string[] AllMods { get; private set; } + + public override void AddRecipeGroups() + { + RecipeGroup group = new RecipeGroup(() => Lang.misc[37] + " Chest", + ItemID.Chest, + ItemID.GoldChest, + ItemID.ShadowChest, + ItemID.EbonwoodChest, + ItemID.RichMahoganyChest, + ItemID.PearlwoodChest, + ItemID.IvyChest, + ItemID.IceChest, + ItemID.LivingWoodChest, + ItemID.SkywareChest, + ItemID.ShadewoodChest, + ItemID.WebCoveredChest, + ItemID.LihzahrdChest, + ItemID.WaterChest, + ItemID.JungleChest, + ItemID.CorruptionChest, + ItemID.CrimsonChest, + ItemID.HallowedChest, + ItemID.FrozenChest, + ItemID.DynastyChest, + ItemID.HoneyChest, + ItemID.SteampunkChest, + ItemID.PalmWoodChest, + ItemID.MushroomChest, + ItemID.BorealWoodChest, + ItemID.SlimeChest, + ItemID.GreenDungeonChest, + ItemID.PinkDungeonChest, + ItemID.BlueDungeonChest, + ItemID.BoneChest, + ItemID.CactusChest, + ItemID.FleshChest, + ItemID.ObsidianChest, + ItemID.PumpkinChest, + ItemID.SpookyChest, + ItemID.GlassChest, + ItemID.MartianChest, + ItemID.GraniteChest, + ItemID.MeteoriteChest, + ItemID.MarbleChest); + RecipeGroup.RegisterGroup("MagicStorage:AnyChest", group); + group = new RecipeGroup(() => Lang.misc[37].Value + " " + Language.GetTextValue("Mods.MagicStorage.SnowBiomeBlock"), ItemID.SnowBlock, ItemID.IceBlock, ItemID.PurpleIceBlock, ItemID.PinkIceBlock); + if (bluemagicMod != null) + { + group.ValidItems.Add(bluemagicMod.ItemType("DarkBlueIce")); + } + RecipeGroup.RegisterGroup("MagicStorage:AnySnowBiomeBlock", group); + group = new RecipeGroup(() => Lang.misc[37].Value + " " + Lang.GetItemNameValue(ItemID.Diamond), ItemID.Diamond, ItemType("ShadowDiamond")); + if (legendMod != null) + { + group.ValidItems.Add(legendMod.ItemType("GemChrysoberyl")); + group.ValidItems.Add(legendMod.ItemType("GemAlexandrite")); + } + RecipeGroup.RegisterGroup("MagicStorage:AnyDiamond", group); + if (legendMod != null) + { + group = new RecipeGroup(() => Lang.misc[37].Value + " " + Lang.GetItemNameValue(ItemID.Amethyst), ItemID.Amethyst, legendMod.ItemType("GemOnyx"), legendMod.ItemType("GemSpinel")); + RecipeGroup.RegisterGroup("MagicStorage:AnyAmethyst", group); + group = new RecipeGroup(() => Lang.misc[37].Value + " " + Lang.GetItemNameValue(ItemID.Topaz), ItemID.Topaz, legendMod.ItemType("GemGarnet")); + RecipeGroup.RegisterGroup("MagicStorage:AnyTopaz", group); + group = new RecipeGroup(() => Lang.misc[37].Value + " " + Lang.GetItemNameValue(ItemID.Sapphire), ItemID.Sapphire, legendMod.ItemType("GemCharoite")); + RecipeGroup.RegisterGroup("MagicStorage:AnySapphire", group); + group = new RecipeGroup(() => Lang.misc[37].Value + " " + Lang.GetItemNameValue(ItemID.Emerald), legendMod.ItemType("GemPeridot")); + RecipeGroup.RegisterGroup("MagicStorage:AnyEmerald", group); + group = new RecipeGroup(() => Lang.misc[37].Value + " " + Lang.GetItemNameValue(ItemID.Ruby), ItemID.Ruby, legendMod.ItemType("GemOpal")); + RecipeGroup.RegisterGroup("MagicStorage:AnyRuby", group); + } + } + + public override void HandlePacket(BinaryReader reader, int whoAmI) + { + NetHelper.HandlePacket(reader, whoAmI); + } + + public override void ModifyInterfaceLayers(List layers) + { + InterfaceHelper.ModifyInterfaceLayers(layers); + } + + public override void PostUpdateInput() + { + if (!Main.instance.IsActive) + { + return; + } + StorageGUI.Update(null); + CraftingGUI.Update(null); + } + } +} + + diff --git a/ModSearchBox.cs b/ModSearchBox.cs index 4eefbd7e..b1072372 100644 --- a/ModSearchBox.cs +++ b/ModSearchBox.cs @@ -1,91 +1,91 @@ -using System; -using Microsoft.Win32.SafeHandles; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Input; -using Terraria.GameContent.UI.Elements; - -namespace MagicStorage -{ - public class ModSearchBox - { - UITextPanel _modButton; - public int ModIndex { get; private set; } = ModIndexAll; - public string ModName { get; private set; } - public Action OnChanged; - - public ModSearchBox(Action onChanged) - { - OnChanged = onChanged; - } - - public UIPanel Button => _modButton; - - public void InitLangStuff() - { - if (_modButton == null) - { - _modButton = new UITextPanel(MakeModButtonText(), 0.8f); - } - } - - void SetSearchMod(int index, bool silent) - { - if (ModIndex == index) return; - ModIndex = index; - if (_modButton != null) - _modButton.SetText(MakeModButtonText()); - ModName = ""; - if (index > -1) ModName = MagicStorage.Instance.AllMods[index]; - if (!silent) OnChanged?.Invoke(); - } - - public void Reset(bool silent) - { - SetSearchMod(ModIndexAll, silent); - } - - public const int ModIndexBaseGame = -1; - public const int ModIndexAll = -2; - - string MakeModButtonText() - { - if (ModIndex == ModIndexAll) - return "All mods"; - else if (ModIndex == ModIndexBaseGame) - { - return "Terraria"; - } - else - return MagicStorage.Instance.AllMods[ModIndex]; - } - - public void Update(MouseState curMouse, MouseState oldMouse) - { - Rectangle dim = InterfaceHelper.GetFullRectangle(_modButton); - if (curMouse.X > dim.X && curMouse.X < dim.X + dim.Width && curMouse.Y > dim.Y && curMouse.Y < dim.Y + dim.Height) - { - _modButton.BackgroundColor = new Color(73, 94, 171); - var allMods = MagicStorage.Instance.AllMods; - int index = ModIndex; - if (curMouse.LeftButton == ButtonState.Pressed && oldMouse.LeftButton == ButtonState.Released) - { - index++; - if (index >= allMods.Length) - index = ModIndexAll; - } - else if (curMouse.RightButton == ButtonState.Pressed && oldMouse.RightButton == ButtonState.Released) - { - index--; - if (index < -2) - index = allMods.Length - 1; - } - - SetSearchMod(index, false); - } - else - { - _modButton.BackgroundColor = new Color(63, 82, 151) * 0.7f; - } - } - } -} \ No newline at end of file +using System; +using Microsoft.Win32.SafeHandles; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Input; +using Terraria.GameContent.UI.Elements; + +namespace MagicStorage +{ + public class ModSearchBox + { + UITextPanel _modButton; + public int ModIndex { get; private set; } = ModIndexAll; + public string ModName { get; private set; } + public Action OnChanged; + + public ModSearchBox(Action onChanged) + { + OnChanged = onChanged; + } + + public UIPanel Button => _modButton; + + public void InitLangStuff() + { + if (_modButton == null) + { + _modButton = new UITextPanel(MakeModButtonText(), 0.8f); + } + } + + void SetSearchMod(int index, bool silent) + { + if (ModIndex == index) return; + ModIndex = index; + if (_modButton != null) + _modButton.SetText(MakeModButtonText()); + ModName = ""; + if (index > -1) ModName = MagicStorage.Instance.AllMods[index]; + if (!silent) OnChanged?.Invoke(); + } + + public void Reset(bool silent) + { + SetSearchMod(ModIndexAll, silent); + } + + public const int ModIndexBaseGame = -1; + public const int ModIndexAll = -2; + + string MakeModButtonText() + { + if (ModIndex == ModIndexAll) + return "All mods"; + else if (ModIndex == ModIndexBaseGame) + { + return "Terraria"; + } + else + return MagicStorage.Instance.AllMods[ModIndex]; + } + + public void Update(MouseState curMouse, MouseState oldMouse) + { + Rectangle dim = InterfaceHelper.GetFullRectangle(_modButton); + if (curMouse.X > dim.X && curMouse.X < dim.X + dim.Width && curMouse.Y > dim.Y && curMouse.Y < dim.Y + dim.Height) + { + _modButton.BackgroundColor = new Color(73, 94, 171); + var allMods = MagicStorage.Instance.AllMods; + int index = ModIndex; + if (curMouse.LeftButton == ButtonState.Pressed && oldMouse.LeftButton == ButtonState.Released) + { + index++; + if (index >= allMods.Length) + index = ModIndexAll; + } + else if (curMouse.RightButton == ButtonState.Pressed && oldMouse.RightButton == ButtonState.Released) + { + index--; + if (index < -2) + index = allMods.Length - 1; + } + + SetSearchMod(index, false); + } + else + { + _modButton.BackgroundColor = new Color(63, 82, 151) * 0.7f; + } + } + } +} diff --git a/NetHelper.cs b/NetHelper.cs index 3b152b8e..65e024f4 100644 --- a/NetHelper.cs +++ b/NetHelper.cs @@ -206,7 +206,7 @@ public static void ReceiveStorageOperation(BinaryReader reader, int sender) { var keepOneIfFavorite = reader.ReadBoolean(); Item item = ItemIO.Receive(reader, true, true); - item = heart.TryWithdraw(item, keepOneIfFavorite); + item = heart.TryWithdraw(item, keepOneIfFavorite); if (!item.IsAir) { ModPacket packet = PrepareOperationResult(op); @@ -553,4 +553,4 @@ enum MessageType : byte CraftRequest, CraftResult } -} \ No newline at end of file +} diff --git a/Properties/AssemblyInfo.cs b/Properties/AssemblyInfo.cs index cbf5bf2b..8c06682d 100644 --- a/Properties/AssemblyInfo.cs +++ b/Properties/AssemblyInfo.cs @@ -34,3 +34,4 @@ // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] + diff --git a/Sorting/CompareFunction.cs b/Sorting/CompareFunction.cs index f0600323..48b9f628 100644 --- a/Sorting/CompareFunction.cs +++ b/Sorting/CompareFunction.cs @@ -50,18 +50,18 @@ public override int Compare(Item item1, Item item2) public class CompareValue : CompareFunction { public override int Compare(Item item1, Item item2) - { + { return item1.value - item2.value; } } public class CompareDps : CompareFunction - { - public override int Compare(Item item1, Item item2) + { + public override int Compare(Item item1, Item item2) { - return (int)((GetDps(item1) - GetDps(item2)) * 100); - } - + return (int)((GetDps(item1) - GetDps(item2)) * 100); + } + public static float GetDps(Item item) { if (item.damage <= 0) return 0f; @@ -87,7 +87,7 @@ public static float GetDps(Item item) else defence = 8; - return Math.Max(item.damage - defence * 0.5f, 1) / Math.Max((item.useTime + item.reuseDelay) / 60f, 0.001f) * (1f + item.crit / 100f); + return Math.Max(item.damage - defence * 0.5f, 1) / Math.Max((item.useTime + item.reuseDelay) / 60f, 0.001f) * (1f + item.crit / 100f); } } -} \ No newline at end of file +} diff --git a/Sorting/DefaultSorting.cs b/Sorting/DefaultSorting.cs index 4efbf5ea..80ed29fc 100644 --- a/Sorting/DefaultSorting.cs +++ b/Sorting/DefaultSorting.cs @@ -465,4 +465,4 @@ public int Compare(Item item1, Item item2) return compareFunc(item1, item2); } } -} \ No newline at end of file +} diff --git a/Sorting/FilterMode.cs b/Sorting/FilterMode.cs index be9e1f86..842a217c 100644 --- a/Sorting/FilterMode.cs +++ b/Sorting/FilterMode.cs @@ -8,16 +8,16 @@ public enum FilterMode WeaponsMelee, WeaponsRanged, WeaponsMagic, - WeaponsSummon, - WeaponsThrown, - Ammo, + WeaponsSummon, + WeaponsThrown, + Ammo, Tools, Armor, Equipment, - Vanity, + Vanity, Potions, Placeables, Misc, Recent } -} \ No newline at end of file +} diff --git a/Sorting/ItemFilter.cs b/Sorting/ItemFilter.cs index 6b010498..889d3514 100644 --- a/Sorting/ItemFilter.cs +++ b/Sorting/ItemFilter.cs @@ -83,13 +83,13 @@ public class FilterWeaponThrown : ItemFilter public override bool Passes(Item item) { switch (item.type) - { + { case 167: // dynamite case 3547: case 2896: case 166: // bomb case 235: - case 3115: + case 3115: return true; } return (item.thrown && item.damage > 0) || (item.consumable && item.Name.ToLowerInvariant().EndsWith(" coating")); @@ -222,4 +222,4 @@ public override bool Passes(Item item) return true; } } -} \ No newline at end of file +} diff --git a/Sorting/ItemSorter.cs b/Sorting/ItemSorter.cs index 5771aa77..10c5d6a4 100644 --- a/Sorting/ItemSorter.cs +++ b/Sorting/ItemSorter.cs @@ -101,7 +101,7 @@ static ItemFilter MakeFilter(FilterMode filterMode) case FilterMode.Misc: filter = new FilterMisc(); break; - case FilterMode.Recent: + case FilterMode.Recent: throw new NotSupportedException(); default: filter = new FilterAll(); @@ -109,25 +109,26 @@ static ItemFilter MakeFilter(FilterMode filterMode) } return filter; - } - - + } + + static bool FilterName(Item item, string filter) { if (filter.Trim().Length == 0) filter = string.Empty; return item.Name.ToLowerInvariant().IndexOf(filter.Trim().ToLowerInvariant()) >= 0; - } - + } + static bool FilterMod(Item item, int modFilterIndex) { if (modFilterIndex == ModSearchBox.ModIndexAll) return true; - var allMods = MagicStorage.Instance.AllMods; + var allMods = MagicStorage.Instance.AllMods; int index = ModSearchBox.ModIndexBaseGame; if (item.modItem != null) - { + { index = Array.IndexOf(allMods, item.modItem.mod.Name); } return index == modFilterIndex; } } } + diff --git a/Sorting/SortMode.cs b/Sorting/SortMode.cs index 311809eb..6066f7d0 100644 --- a/Sorting/SortMode.cs +++ b/Sorting/SortMode.cs @@ -11,4 +11,4 @@ public enum SortMode Dps, AsIs } -} \ No newline at end of file +} diff --git a/StorageGUI.cs b/StorageGUI.cs index e3d85212..41570745 100644 --- a/StorageGUI.cs +++ b/StorageGUI.cs @@ -636,4 +636,4 @@ private static Item DoWithdraw(Item item, bool toInventory = false, bool keepOne } } -} \ No newline at end of file +} diff --git a/StoragePlayer.cs b/StoragePlayer.cs index dde62dce..8d88570d 100644 --- a/StoragePlayer.cs +++ b/StoragePlayer.cs @@ -1,298 +1,298 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Terraria; -using Terraria.DataStructures; -using Terraria.ModLoader; -using Terraria.UI; -using MagicStorage.Components; -using Terraria.GameInput; -using Terraria.ID; -using Terraria.ModLoader.IO; - -namespace MagicStorage -{ - public class StoragePlayer : ModPlayer - { - public int timeSinceOpen = 1; - private Point16 storageAccess = new Point16(-1, -1); - public bool remoteAccess = false; - - ItemTypeOrderedSet _hiddenRecipes = new ItemTypeOrderedSet("HiddenItems"); - ItemTypeOrderedSet _craftedRecipes = new ItemTypeOrderedSet("CraftedRecipes"); - - public IEnumerable HiddenRecipes { get { return _hiddenRecipes.Items; } } - public IEnumerable CraftedRecipes { get { return _craftedRecipes.Items; } } - - public ItemTypeOrderedSet FavoritedRecipes { get; private set; } = new ItemTypeOrderedSet("FavoritedRecipes"); - public ItemTypeOrderedSet SeenRecipes { get; private set; } = new ItemTypeOrderedSet("SeenRecipes"); - public ItemTypeOrderedSet TestedRecipes { get; private set; } = new ItemTypeOrderedSet("TestedRecipes"); - public ItemTypeOrderedSet AsKnownRecipes { get; private set; } = new ItemTypeOrderedSet("AsKnownRecipes"); - - public bool IsRecipeHidden(Item item) - { - return _hiddenRecipes.Contains(item); - } - - public bool AddToHiddenRecipes(Item item) - { - return _hiddenRecipes.Add(item); - } - - public bool RemoveFromHiddenRecipes(Item item) - { - return _hiddenRecipes.Remove(item); - } - - public bool AddToCraftedRecipes(Item item) - { - return _craftedRecipes.Add(item); - } - - public override TagCompound Save() - { - var c = new TagCompound(); - _hiddenRecipes.Save(c); - _craftedRecipes.Save(c); - FavoritedRecipes.Save(c); - SeenRecipes.Save(c); - TestedRecipes.Save(c); - AsKnownRecipes.Save(c); - return c; - } - - public override void Load(TagCompound tag) - { - _hiddenRecipes.Load(tag); - _craftedRecipes.Load(tag); - FavoritedRecipes.Load(tag); - SeenRecipes.Load(tag); - TestedRecipes.Load(tag); - AsKnownRecipes.Load(tag); - } - - public override void UpdateDead() - { - if (player.whoAmI == Main.myPlayer) - { - CloseStorage(); - } - } - - public override void ResetEffects() - { - if (player.whoAmI != Main.myPlayer) - { - return; - } - if (timeSinceOpen < 1) - { - player.talkNPC = -1; - Main.playerInventory = true; - timeSinceOpen++; - } - if (storageAccess.X >= 0 && storageAccess.Y >= 0 && (player.chest != -1 || !Main.playerInventory || player.sign > -1 || player.talkNPC > -1)) - { - CloseStorage(); - Recipe.FindRecipes(); - } - else if (storageAccess.X >= 0 && storageAccess.Y >= 0) - { - int playerX = (int)(player.Center.X / 16f); - int playerY = (int)(player.Center.Y / 16f); - if (!remoteAccess && (playerX < storageAccess.X - Player.tileRangeX || playerX > storageAccess.X + Player.tileRangeX + 1 || playerY < storageAccess.Y - Player.tileRangeY || playerY > storageAccess.Y + Player.tileRangeY + 1)) - { - Main.PlaySound(11, -1, -1, 1); - CloseStorage(); - Recipe.FindRecipes(); - } - else if (!(TileLoader.GetTile(Main.tile[storageAccess.X, storageAccess.Y].type) is StorageAccess)) - { - Main.PlaySound(11, -1, -1, 1); - CloseStorage(); - Recipe.FindRecipes(); - } - } - } - - TEStorageHeart _latestAccessedStorage; - public TEStorageHeart LatestAccessedStorage => _latestAccessedStorage != null && _latestAccessedStorage.IsAlive ? _latestAccessedStorage : null; - - public void OpenStorage(Point16 point, bool remote = false) - { - storageAccess = point;remoteAccess = remote; - _latestAccessedStorage = GetStorageHeart(); - StorageGUI.RefreshItems(); - } - - public void CloseStorage() - { - storageAccess = new Point16(-1, -1); - Main.blockInput = false; - } - - public Point16 ViewingStorage() - { - return storageAccess; - } - - public static void GetItem(Item item, bool toMouse) - { - Player player = Main.player[Main.myPlayer]; - if (toMouse && Main.playerInventory && Main.mouseItem.IsAir) - { - Main.mouseItem = item; - item = new Item(); - } - else if (toMouse && Main.playerInventory && Main.mouseItem.type == item.type) - { - int total = Main.mouseItem.stack + item.stack; - if (total > Main.mouseItem.maxStack) - { - total = Main.mouseItem.maxStack; - } - int difference = total - Main.mouseItem.stack; - Main.mouseItem.stack = total; - item.stack -= difference; - } - if (!item.IsAir) - { - item = player.GetItem(Main.myPlayer, item, false, true); - if (!item.IsAir) - { - player.QuickSpawnClonedItem(item, item.stack); - } - } - } - - public override bool ShiftClickSlot(Item[] inventory, int context, int slot) - { - if (context != ItemSlot.Context.InventoryItem && context != ItemSlot.Context.InventoryCoin && context != ItemSlot.Context.InventoryAmmo) - { - return false; - } - if (storageAccess.X < 0 || storageAccess.Y < 0) - { - return false; - } - Item item = inventory[slot]; - if (item.favorited || item.IsAir) - { - return false; - } - int oldType = item.type; - int oldStack = item.stack; - if (StorageCrafting()) - { - if (false) - { - if (Main.netMode == 0) - { - GetCraftingAccess().TryDepositStation(item); - } - else - { - NetHelper.SendDepositStation(GetCraftingAccess().ID, item); - item.SetDefaults(0, true); - } - } - } - else - { - if (Main.netMode == 0) - { - GetStorageHeart().DepositItem(item); - } - else - { - NetHelper.SendDeposit(GetStorageHeart().ID, item); - item.SetDefaults(0, true); - } - } - if (item.type != oldType || item.stack != oldStack) - { - Main.PlaySound(7, -1, -1, 1, 1f, 0f); - StorageGUI.RefreshItems(); - } - return true; - } - - public TEStorageHeart GetStorageHeart() - { - if (storageAccess.X < 0 || storageAccess.Y < 0) - { - return null; - } - Tile tile = Main.tile[storageAccess.X, storageAccess.Y]; - if (tile == null) - { - return null; - } - int tileType = tile.type; - ModTile modTile = TileLoader.GetTile(tileType); - if (modTile == null || !(modTile is StorageAccess)) - { - return null; - } - return ((StorageAccess)modTile).GetHeart(storageAccess.X, storageAccess.Y); - } - - public TECraftingAccess GetCraftingAccess() - { - if (storageAccess.X < 0 || storageAccess.Y < 0 || !TileEntity.ByPosition.ContainsKey(storageAccess)) - { - return null; - } - return TileEntity.ByPosition[storageAccess] as TECraftingAccess; - } - - public bool StorageCrafting() - { - if (storageAccess.X < 0 || storageAccess.Y < 0) - { - return false; - } - Tile tile = Main.tile[storageAccess.X, storageAccess.Y]; - return tile != null && tile.type == mod.TileType("CraftingAccess"); - } - - public static bool IsStorageCrafting() - { - return Main.player[Main.myPlayer].GetModPlayer().StorageCrafting(); - } - - public override void ModifyHitByNPC(NPC npc, ref int damage, ref bool crit) - { - foreach (var item in player.inventory.Concat(player.armor).Concat(player.dye).Concat(player.miscDyes).Concat(player.miscEquips)) - { - if (item != null && !item.IsAir && CraftingGUI.IsTestItem(item)) - { - damage *= 5; - break; - } - } - } - - public override bool CanHitPvp(Item item, Player target) - { - if (CraftingGUI.IsTestItem(item)) return false; - return base.CanHitPvp(item, target); - } - - public override void OnRespawn(Player player) - { - foreach (var item in player.inventory.Concat(player.armor).Concat(player.dye).Concat(player.miscDyes).Concat(player.miscEquips)) - { - if (item != null && !item.IsAir && CraftingGUI.IsTestItem(item)) - item.TurnToAir(); - } - - { - var item = player.trashItem; - if (item != null && !item.IsAir && CraftingGUI.IsTestItem(item)) - item.TurnToAir(); - } - base.OnRespawn(player); - } - } -} \ No newline at end of file +using System; +using System.Collections.Generic; +using System.Linq; +using Terraria; +using Terraria.DataStructures; +using Terraria.ModLoader; +using Terraria.UI; +using MagicStorage.Components; +using Terraria.GameInput; +using Terraria.ID; +using Terraria.ModLoader.IO; + +namespace MagicStorage +{ + public class StoragePlayer : ModPlayer + { + public int timeSinceOpen = 1; + private Point16 storageAccess = new Point16(-1, -1); + public bool remoteAccess = false; + + ItemTypeOrderedSet _hiddenRecipes = new ItemTypeOrderedSet("HiddenItems"); + ItemTypeOrderedSet _craftedRecipes = new ItemTypeOrderedSet("CraftedRecipes"); + + public IEnumerable HiddenRecipes { get { return _hiddenRecipes.Items; } } + public IEnumerable CraftedRecipes { get { return _craftedRecipes.Items; } } + + public ItemTypeOrderedSet FavoritedRecipes { get; private set; } = new ItemTypeOrderedSet("FavoritedRecipes"); + public ItemTypeOrderedSet SeenRecipes { get; private set; } = new ItemTypeOrderedSet("SeenRecipes"); + public ItemTypeOrderedSet TestedRecipes { get; private set; } = new ItemTypeOrderedSet("TestedRecipes"); + public ItemTypeOrderedSet AsKnownRecipes { get; private set; } = new ItemTypeOrderedSet("AsKnownRecipes"); + + public bool IsRecipeHidden(Item item) + { + return _hiddenRecipes.Contains(item); + } + + public bool AddToHiddenRecipes(Item item) + { + return _hiddenRecipes.Add(item); + } + + public bool RemoveFromHiddenRecipes(Item item) + { + return _hiddenRecipes.Remove(item); + } + + public bool AddToCraftedRecipes(Item item) + { + return _craftedRecipes.Add(item); + } + + public override TagCompound Save() + { + var c = new TagCompound(); + _hiddenRecipes.Save(c); + _craftedRecipes.Save(c); + FavoritedRecipes.Save(c); + SeenRecipes.Save(c); + TestedRecipes.Save(c); + AsKnownRecipes.Save(c); + return c; + } + + public override void Load(TagCompound tag) + { + _hiddenRecipes.Load(tag); + _craftedRecipes.Load(tag); + FavoritedRecipes.Load(tag); + SeenRecipes.Load(tag); + TestedRecipes.Load(tag); + AsKnownRecipes.Load(tag); + } + + public override void UpdateDead() + { + if (player.whoAmI == Main.myPlayer) + { + CloseStorage(); + } + } + + public override void ResetEffects() + { + if (player.whoAmI != Main.myPlayer) + { + return; + } + if (timeSinceOpen < 1) + { + player.talkNPC = -1; + Main.playerInventory = true; + timeSinceOpen++; + } + if (storageAccess.X >= 0 && storageAccess.Y >= 0 && (player.chest != -1 || !Main.playerInventory || player.sign > -1 || player.talkNPC > -1)) + { + CloseStorage(); + Recipe.FindRecipes(); + } + else if (storageAccess.X >= 0 && storageAccess.Y >= 0) + { + int playerX = (int)(player.Center.X / 16f); + int playerY = (int)(player.Center.Y / 16f); + if (!remoteAccess && (playerX < storageAccess.X - Player.tileRangeX || playerX > storageAccess.X + Player.tileRangeX + 1 || playerY < storageAccess.Y - Player.tileRangeY || playerY > storageAccess.Y + Player.tileRangeY + 1)) + { + Main.PlaySound(11, -1, -1, 1); + CloseStorage(); + Recipe.FindRecipes(); + } + else if (!(TileLoader.GetTile(Main.tile[storageAccess.X, storageAccess.Y].type) is StorageAccess)) + { + Main.PlaySound(11, -1, -1, 1); + CloseStorage(); + Recipe.FindRecipes(); + } + } + } + + TEStorageHeart _latestAccessedStorage; + public TEStorageHeart LatestAccessedStorage => _latestAccessedStorage != null && _latestAccessedStorage.IsAlive ? _latestAccessedStorage : null; + + public void OpenStorage(Point16 point, bool remote = false) + { + storageAccess = point;remoteAccess = remote; + _latestAccessedStorage = GetStorageHeart(); + StorageGUI.RefreshItems(); + } + + public void CloseStorage() + { + storageAccess = new Point16(-1, -1); + Main.blockInput = false; + } + + public Point16 ViewingStorage() + { + return storageAccess; + } + + public static void GetItem(Item item, bool toMouse) + { + Player player = Main.player[Main.myPlayer]; + if (toMouse && Main.playerInventory && Main.mouseItem.IsAir) + { + Main.mouseItem = item; + item = new Item(); + } + else if (toMouse && Main.playerInventory && Main.mouseItem.type == item.type) + { + int total = Main.mouseItem.stack + item.stack; + if (total > Main.mouseItem.maxStack) + { + total = Main.mouseItem.maxStack; + } + int difference = total - Main.mouseItem.stack; + Main.mouseItem.stack = total; + item.stack -= difference; + } + if (!item.IsAir) + { + item = player.GetItem(Main.myPlayer, item, false, true); + if (!item.IsAir) + { + player.QuickSpawnClonedItem(item, item.stack); + } + } + } + + public override bool ShiftClickSlot(Item[] inventory, int context, int slot) + { + if (context != ItemSlot.Context.InventoryItem && context != ItemSlot.Context.InventoryCoin && context != ItemSlot.Context.InventoryAmmo) + { + return false; + } + if (storageAccess.X < 0 || storageAccess.Y < 0) + { + return false; + } + Item item = inventory[slot]; + if (item.favorited || item.IsAir) + { + return false; + } + int oldType = item.type; + int oldStack = item.stack; + if (StorageCrafting()) + { + if (false) + { + if (Main.netMode == 0) + { + GetCraftingAccess().TryDepositStation(item); + } + else + { + NetHelper.SendDepositStation(GetCraftingAccess().ID, item); + item.SetDefaults(0, true); + } + } + } + else + { + if (Main.netMode == 0) + { + GetStorageHeart().DepositItem(item); + } + else + { + NetHelper.SendDeposit(GetStorageHeart().ID, item); + item.SetDefaults(0, true); + } + } + if (item.type != oldType || item.stack != oldStack) + { + Main.PlaySound(7, -1, -1, 1, 1f, 0f); + StorageGUI.RefreshItems(); + } + return true; + } + + public TEStorageHeart GetStorageHeart() + { + if (storageAccess.X < 0 || storageAccess.Y < 0) + { + return null; + } + Tile tile = Main.tile[storageAccess.X, storageAccess.Y]; + if (tile == null) + { + return null; + } + int tileType = tile.type; + ModTile modTile = TileLoader.GetTile(tileType); + if (modTile == null || !(modTile is StorageAccess)) + { + return null; + } + return ((StorageAccess)modTile).GetHeart(storageAccess.X, storageAccess.Y); + } + + public TECraftingAccess GetCraftingAccess() + { + if (storageAccess.X < 0 || storageAccess.Y < 0 || !TileEntity.ByPosition.ContainsKey(storageAccess)) + { + return null; + } + return TileEntity.ByPosition[storageAccess] as TECraftingAccess; + } + + public bool StorageCrafting() + { + if (storageAccess.X < 0 || storageAccess.Y < 0) + { + return false; + } + Tile tile = Main.tile[storageAccess.X, storageAccess.Y]; + return tile != null && tile.type == mod.TileType("CraftingAccess"); + } + + public static bool IsStorageCrafting() + { + return Main.player[Main.myPlayer].GetModPlayer().StorageCrafting(); + } + + public override void ModifyHitByNPC(NPC npc, ref int damage, ref bool crit) + { + foreach (var item in player.inventory.Concat(player.armor).Concat(player.dye).Concat(player.miscDyes).Concat(player.miscEquips)) + { + if (item != null && !item.IsAir && CraftingGUI.IsTestItem(item)) + { + damage *= 5; + break; + } + } + } + + public override bool CanHitPvp(Item item, Player target) + { + if (CraftingGUI.IsTestItem(item)) return false; + return base.CanHitPvp(item, target); + } + + public override void OnRespawn(Player player) + { + foreach (var item in player.inventory.Concat(player.armor).Concat(player.dye).Concat(player.miscDyes).Concat(player.miscEquips)) + { + if (item != null && !item.IsAir && CraftingGUI.IsTestItem(item)) + item.TurnToAir(); + } + + { + var item = player.trashItem; + if (item != null && !item.IsAir && CraftingGUI.IsTestItem(item)) + item.TurnToAir(); + } + base.OnRespawn(player); + } + } +} diff --git a/StorageWorld.cs b/StorageWorld.cs index 1a945be9..43212f97 100644 --- a/StorageWorld.cs +++ b/StorageWorld.cs @@ -154,3 +154,4 @@ public override void PostUpdate() } } } + diff --git a/UIButtonChoice.cs b/UIButtonChoice.cs index f541cd13..10a01e83 100644 --- a/UIButtonChoice.cs +++ b/UIButtonChoice.cs @@ -17,8 +17,8 @@ public class UIButtonChoice : UIElement private int buttonPadding; private Texture2D[] buttons; - private LocalizedText[] names; - + private LocalizedText[] names; + private int choice = 0; public int Choice @@ -67,7 +67,7 @@ public override void Update(GameTime gameTime) } } if (oldChoice != choice) - { + { _onChanged?.Invoke(); } } @@ -108,4 +108,4 @@ public void DrawText() } } } -} \ No newline at end of file +} diff --git a/UISearchBar.cs b/UISearchBar.cs index 1163f149..2cc8197d 100644 --- a/UISearchBar.cs +++ b/UISearchBar.cs @@ -58,8 +58,8 @@ public override void Update(GameTime gameTime) cursorTimer %= 60; Rectangle dim = InterfaceHelper.GetFullRectangle(this); - MouseState mouse = StorageGUI.curMouse; - bool mouseOver = mouse.X > dim.X && mouse.X < dim.X + dim.Width && mouse.Y > dim.Y && mouse.Y < dim.Y + dim.Height; + MouseState mouse = StorageGUI.curMouse; + bool mouseOver = mouse.X > dim.X && mouse.X < dim.X + dim.Width && mouse.Y > dim.Y && mouse.Y < dim.Y + dim.Height; if (StorageGUI.MouseClicked && Parent != null) { if (!hasFocus && mouseOver) @@ -80,16 +80,16 @@ public override void Update(GameTime gameTime) cursorPosition = text.Length; CheckBlockInput(); } - else if (StorageGUI.curMouse.RightButton == ButtonState.Pressed && StorageGUI.oldMouse.RightButton == ButtonState.Released && mouseOver) - { - if (text.Length > 0) - { - text = string.Empty; + else if (StorageGUI.curMouse.RightButton == ButtonState.Pressed && StorageGUI.oldMouse.RightButton == ButtonState.Released && mouseOver) + { + if (text.Length > 0) + { + text = string.Empty; cursorPosition = 0; - _clearedEvent?.Invoke(); - } - } - + _clearedEvent?.Invoke(); + } + } + if (hasFocus) { PlayerInput.WritingText = true; @@ -105,15 +105,15 @@ public override void Update(GameTime gameTime) text = newString; cursorPosition = newStringLength; StorageGUI.RefreshItems(); - } - if (KeyTyped(Keys.Delete)) - { - if (text.Length > 0 && cursorPosition < text.Length) + } + if (KeyTyped(Keys.Delete)) + { + if (text.Length > 0 && cursorPosition < text.Length) text = text.Remove(cursorPosition, 1); } - if (KeyTyped(Keys.Left)) + if (KeyTyped(Keys.Left)) { - if (cursorPosition > 0) cursorPosition--; + if (cursorPosition > 0) cursorPosition--; } if (KeyTyped(Keys.Right)) { @@ -133,7 +133,7 @@ public override void Update(GameTime gameTime) CheckBlockInput(); } -} +} base.Update(gameTime); } @@ -194,4 +194,4 @@ private static void CheckBlockInput() } } } -} \ No newline at end of file +} diff --git a/UIToggleButton.cs b/UIToggleButton.cs index 4a3958e3..c7581675 100644 --- a/UIToggleButton.cs +++ b/UIToggleButton.cs @@ -1,92 +1,92 @@ -using System; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using Terraria; -using Terraria.Localization; -using Terraria.UI; - -namespace MagicStorage -{ - public class UIToggleButton : UIElement - { - private int buttonSize; - private int buttonPadding; - private readonly Action onChanged; - private Texture2D _button; - private LocalizedText _name; - - private bool _value; - - public bool Value - { - get - { - return _value; - } - set - { - _value = value; - } - } - - public UIToggleButton(Action onChanged, Texture2D button, LocalizedText name, int buttonSize = 21, int buttonPadding = 1) - { - this.buttonSize = buttonSize; - this.buttonPadding = buttonPadding; - this.onChanged = onChanged; - this._button = button; - this._name = name; - this.Width.Set(buttonSize, 0f); - this.MinWidth.Set(buttonSize, 0f); - this.Height.Set(buttonSize, 0f); - this.MinHeight.Set(buttonSize, 0f); - } - - public override void Update(GameTime gameTime) - { - var oldValue = _value; - if (StorageGUI.MouseClicked && Parent != null) - { - if (MouseOverButton(StorageGUI.curMouse.X, StorageGUI.curMouse.Y)) - { - _value = !_value; - } - } - - if (oldValue != _value) - { - onChanged?.Invoke(); - } - } - - private bool MouseOverButton(int mouseX, int mouseY) - { - Rectangle dim = InterfaceHelper.GetFullRectangle(this); - float left = dim.X; - float right = left + buttonSize * Main.UIScale; - float top = dim.Y; - float bottom = top + buttonSize * Main.UIScale; - return mouseX > left && mouseX < right && mouseY > top && mouseY < bottom; - } - - protected override void DrawSelf(SpriteBatch spriteBatch) - { - Texture2D backTexture = MagicStorage.Instance.GetTexture("SortButtonBackground"); - Texture2D backTextureActive = MagicStorage.Instance.GetTexture("SortButtonBackgroundActive"); - CalculatedStyle dim = GetDimensions(); - Texture2D texture = _value ? backTextureActive : backTexture; - Vector2 drawPos = new Vector2(dim.X, dim.Y); - Color color = MouseOverButton(StorageGUI.curMouse.X, StorageGUI.curMouse.Y) ? Color.Silver : Color.White; - Main.spriteBatch.Draw(texture, new Rectangle((int) drawPos.X, (int) drawPos.Y, buttonSize, buttonSize), color); - Main.spriteBatch.Draw(_button, new Rectangle((int) drawPos.X + 1, (int) drawPos.Y + 1, buttonSize - 1, buttonSize - 1), Color.White); - } - - public void DrawText() - { - if (MouseOverButton(StorageGUI.curMouse.X, StorageGUI.curMouse.Y)) - { - Main.instance.MouseText(_name.Value); - } - } - } -} \ No newline at end of file +using System; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Terraria; +using Terraria.Localization; +using Terraria.UI; + +namespace MagicStorage +{ + public class UIToggleButton : UIElement + { + private int buttonSize; + private int buttonPadding; + private readonly Action onChanged; + private Texture2D _button; + private LocalizedText _name; + + private bool _value; + + public bool Value + { + get + { + return _value; + } + set + { + _value = value; + } + } + + public UIToggleButton(Action onChanged, Texture2D button, LocalizedText name, int buttonSize = 21, int buttonPadding = 1) + { + this.buttonSize = buttonSize; + this.buttonPadding = buttonPadding; + this.onChanged = onChanged; + this._button = button; + this._name = name; + this.Width.Set(buttonSize, 0f); + this.MinWidth.Set(buttonSize, 0f); + this.Height.Set(buttonSize, 0f); + this.MinHeight.Set(buttonSize, 0f); + } + + public override void Update(GameTime gameTime) + { + var oldValue = _value; + if (StorageGUI.MouseClicked && Parent != null) + { + if (MouseOverButton(StorageGUI.curMouse.X, StorageGUI.curMouse.Y)) + { + _value = !_value; + } + } + + if (oldValue != _value) + { + onChanged?.Invoke(); + } + } + + private bool MouseOverButton(int mouseX, int mouseY) + { + Rectangle dim = InterfaceHelper.GetFullRectangle(this); + float left = dim.X; + float right = left + buttonSize * Main.UIScale; + float top = dim.Y; + float bottom = top + buttonSize * Main.UIScale; + return mouseX > left && mouseX < right && mouseY > top && mouseY < bottom; + } + + protected override void DrawSelf(SpriteBatch spriteBatch) + { + Texture2D backTexture = MagicStorage.Instance.GetTexture("SortButtonBackground"); + Texture2D backTextureActive = MagicStorage.Instance.GetTexture("SortButtonBackgroundActive"); + CalculatedStyle dim = GetDimensions(); + Texture2D texture = _value ? backTextureActive : backTexture; + Vector2 drawPos = new Vector2(dim.X, dim.Y); + Color color = MouseOverButton(StorageGUI.curMouse.X, StorageGUI.curMouse.Y) ? Color.Silver : Color.White; + Main.spriteBatch.Draw(texture, new Rectangle((int) drawPos.X, (int) drawPos.Y, buttonSize, buttonSize), color); + Main.spriteBatch.Draw(_button, new Rectangle((int) drawPos.X + 1, (int) drawPos.Y + 1, buttonSize - 1, buttonSize - 1), Color.White); + } + + public void DrawText() + { + if (MouseOverButton(StorageGUI.curMouse.X, StorageGUI.curMouse.Y)) + { + Main.instance.MouseText(_name.Value); + } + } + } +} From 9cc10ed0da817592b962d79453ece02dae1e27ed Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 26 Aug 2018 12:01:51 +0300 Subject: [PATCH 62/80] reverting TestItem mode. if you want to keep it stick to the wvlad-fork branch. --- Components/TEStorageUnit.cs | 3 +- CraftingGUI.cs | 51 +------ ItemSaveLoadHook.cs | 32 ----- MagicStorage.cs | 1 - MagicStorage.csproj | 269 ++++++++++++++++++------------------ StoragePlayer.cs | 37 ----- 6 files changed, 136 insertions(+), 257 deletions(-) delete mode 100644 ItemSaveLoadHook.cs diff --git a/Components/TEStorageUnit.cs b/Components/TEStorageUnit.cs index 2f1be0e0..885a565b 100644 --- a/Components/TEStorageUnit.cs +++ b/Components/TEStorageUnit.cs @@ -145,8 +145,7 @@ public override void DepositItem(Item toDeposit, bool locked = false) } try { - if (CraftingGUI.IsTestItem(toDeposit)) return; - Item original = toDeposit.Clone(); + Item original = toDeposit.Clone(); bool finished = false; bool hasChange = false; foreach (Item item in items) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 2694ca8a..8bb794ef 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -487,7 +487,6 @@ public static void Draw(TEStorageHeart heart) sortButtons.DrawText(); recipeButtons.DrawText(); filterButtons.DrawText(); - DrawCraftButton(); } catch (Exception e) { @@ -495,17 +494,6 @@ public static void Draw(TEStorageHeart heart) } } - private static void DrawCraftButton() - { - Rectangle dim = InterfaceHelper.GetFullRectangle(craftButton); - - if (Main.netMode == NetmodeID.SinglePlayer && curMouse.X > dim.X && curMouse.X < dim.X + dim.Width && curMouse.Y > dim.Y && curMouse.Y < dim.Y + dim.Height - && selectedRecipe != null && Main.mouseItem.IsAir && CanItemBeTakenForTest(selectedRecipe.createItem)) - { - Main.instance.MouseText(Language.GetText("Mods.MagicStorage.CraftTooltip").Value); - } - } - private static Item GetStation(int slot, ref int context) { Item[] stations = GetCraftingStations(); @@ -752,20 +740,7 @@ private static void UpdateCraftButton() if (curMouse.X > dim.X && curMouse.X < dim.X + dim.Width && curMouse.Y > dim.Y && curMouse.Y < dim.Y + dim.Height) { craftButton.BackgroundColor = new Color(73, 94, 171); - if (RightMouseClicked && selectedRecipe != null && Main.mouseItem.IsAir) - { - var item = selectedRecipe.createItem; - if (CanItemBeTakenForTest(item)) - { - var type = item.type; - var testItem = new Item(); - testItem.SetDefaults(type, true); - MarkAsTestItem(testItem); - Main.mouseItem = testItem; - ModPlayer.TestedRecipes.Add(selectedRecipe.createItem); - } - } - else if (curMouse.LeftButton == ButtonState.Pressed && selectedRecipe != null && IsAvailable(selectedRecipe) && PassesBlock(selectedRecipe)) + if (curMouse.LeftButton == ButtonState.Pressed && selectedRecipe != null && IsAvailable(selectedRecipe) && PassesBlock(selectedRecipe)) { if (craftTimer <= 0) { @@ -801,30 +776,6 @@ private static void UpdateCraftButton() } } - static bool CanItemBeTakenForTest(Item item) - { - return Main.netMode == NetmodeID.SinglePlayer - && !item.consumable && (item.mana > 0 || item.magic || item.ranged || item.thrown || item.melee - || item.headSlot >= 0 || item.bodySlot >= 0 || item.legSlot >= 0 || item.accessory || Main.projHook[item.shoot] - || item.pick > 0 || item.axe > 0 || item.hammer > 0) - && !item.summon && item.createTile < 0 && item.createWall < 0 && !item.potion && item.fishingPole <= 1 && item.ammo == AmmoID.None - && !ModPlayer.TestedRecipes.Contains(item); - } - - public static void MarkAsTestItem(Item testItem) - { - testItem.value = 0; - testItem.shopCustomPrice = 0; - testItem.material = false; - testItem.rare = -11; - testItem.SetNameOverride(Lang.GetItemNameValue(testItem.type) + Language.GetTextValue("Mods.MagicStorage.TestItemSuffix")); - } - - public static bool IsTestItem(Item item) - { - return item.Name.EndsWith(Language.GetTextValue("Mods.MagicStorage.TestItemSuffix")); - } - private static TEStorageHeart GetHeart() { Player player = Main.player[Main.myPlayer]; diff --git a/ItemSaveLoadHook.cs b/ItemSaveLoadHook.cs deleted file mode 100644 index cc0e6a85..00000000 --- a/ItemSaveLoadHook.cs +++ /dev/null @@ -1,32 +0,0 @@ -using Terraria; -using Terraria.ModLoader; -using Terraria.ModLoader.IO; - -namespace MagicStorage -{ - public class ItemSaveLoadHook : GlobalItem - { - public override TagCompound Save(Item item) - { - if (CraftingGUI.IsTestItem(item)) - { - return new TagCompound() {{"TestItem", true}}; - } - - return null; - } - - public override void Load(Item item, TagCompound tag) - { - if (tag != null && tag.ContainsKey("TestItem")) - CraftingGUI.MarkAsTestItem(item); - - base.Load(item, tag); - } - - public override bool NeedsSaving(Item item) - { - return CraftingGUI.IsTestItem(item); - } - } -} diff --git a/MagicStorage.cs b/MagicStorage.cs index a8c80d30..d3a2857c 100644 --- a/MagicStorage.cs +++ b/MagicStorage.cs @@ -32,7 +32,6 @@ public override void Load() legendMod = ModLoader.GetMod("LegendOfTerraria3"); bluemagicMod = ModLoader.GetMod("Bluemagic"); AddTranslations(); - AddGlobalItem("MagicStorageItemSaveLoadHook", new ItemSaveLoadHook()); IsItemKnownHotKey = RegisterHotKey("Is This Item Known?", ""); } diff --git a/MagicStorage.csproj b/MagicStorage.csproj index d837a8b9..72ea9fe0 100644 --- a/MagicStorage.csproj +++ b/MagicStorage.csproj @@ -1,136 +1,135 @@ - - - - - Debug - AnyCPU - {162C8AA5-FF1C-4357-AEED-FAF522C56FEE} - Library - Properties - MagicStorage - MagicStorage - v4.7.1 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - C:\Program Files (x86)\Steam\steamapps\common\Terraria\References\ReLogic.dll - - - - - - - - - - - C:\Program Files (x86)\Steam\steamapps\common\Terraria\Terraria.exe - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "C:\Program Files (x86)\Steam\steamapps\common\Terraria\tModLoaderServer.exe" -build "$(ProjectDir.TrimEnd('\'))" - + + + + + Debug + AnyCPU + {162C8AA5-FF1C-4357-AEED-FAF522C56FEE} + Library + Properties + MagicStorage + MagicStorage + v4.7.1 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + C:\Program Files (x86)\Steam\steamapps\common\Terraria\References\ReLogic.dll + + + + + + + + + + + C:\Program Files (x86)\Steam\steamapps\common\Terraria\Terraria.exe + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + "C:\Program Files (x86)\Steam\steamapps\common\Terraria\tModLoaderServer.exe" -build "$(ProjectDir.TrimEnd('\'))" + \ No newline at end of file diff --git a/StoragePlayer.cs b/StoragePlayer.cs index 8d88570d..3cfe3d05 100644 --- a/StoragePlayer.cs +++ b/StoragePlayer.cs @@ -26,7 +26,6 @@ public class StoragePlayer : ModPlayer public ItemTypeOrderedSet FavoritedRecipes { get; private set; } = new ItemTypeOrderedSet("FavoritedRecipes"); public ItemTypeOrderedSet SeenRecipes { get; private set; } = new ItemTypeOrderedSet("SeenRecipes"); - public ItemTypeOrderedSet TestedRecipes { get; private set; } = new ItemTypeOrderedSet("TestedRecipes"); public ItemTypeOrderedSet AsKnownRecipes { get; private set; } = new ItemTypeOrderedSet("AsKnownRecipes"); public bool IsRecipeHidden(Item item) @@ -56,7 +55,6 @@ public override TagCompound Save() _craftedRecipes.Save(c); FavoritedRecipes.Save(c); SeenRecipes.Save(c); - TestedRecipes.Save(c); AsKnownRecipes.Save(c); return c; } @@ -67,7 +65,6 @@ public override void Load(TagCompound tag) _craftedRecipes.Load(tag); FavoritedRecipes.Load(tag); SeenRecipes.Load(tag); - TestedRecipes.Load(tag); AsKnownRecipes.Load(tag); } @@ -260,39 +257,5 @@ public static bool IsStorageCrafting() { return Main.player[Main.myPlayer].GetModPlayer().StorageCrafting(); } - - public override void ModifyHitByNPC(NPC npc, ref int damage, ref bool crit) - { - foreach (var item in player.inventory.Concat(player.armor).Concat(player.dye).Concat(player.miscDyes).Concat(player.miscEquips)) - { - if (item != null && !item.IsAir && CraftingGUI.IsTestItem(item)) - { - damage *= 5; - break; - } - } - } - - public override bool CanHitPvp(Item item, Player target) - { - if (CraftingGUI.IsTestItem(item)) return false; - return base.CanHitPvp(item, target); - } - - public override void OnRespawn(Player player) - { - foreach (var item in player.inventory.Concat(player.armor).Concat(player.dye).Concat(player.miscDyes).Concat(player.miscEquips)) - { - if (item != null && !item.IsAir && CraftingGUI.IsTestItem(item)) - item.TurnToAir(); - } - - { - var item = player.trashItem; - if (item != null && !item.IsAir && CraftingGUI.IsTestItem(item)) - item.TurnToAir(); - } - base.OnRespawn(player); - } } } From 298a33d7d825ecc01403d8de9eb6b108b621c30e Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 26 Aug 2018 12:03:51 +0300 Subject: [PATCH 63/80] reverting prices change, if you want to keep it stick to the wvlad-fork branch --- Items/CraftingAccess.cs | 5 ++--- Items/Locator.cs | 3 +-- Items/LocatorDisk.cs | 3 +-- Items/PortableAccess.cs | 7 +++---- Items/RemoteAccess.cs | 5 ++--- Items/StorageAccess.cs | 5 ++--- Items/StorageHeart.cs | 4 ++-- 7 files changed, 13 insertions(+), 19 deletions(-) diff --git a/Items/CraftingAccess.cs b/Items/CraftingAccess.cs index 71871034..5ca35a73 100644 --- a/Items/CraftingAccess.cs +++ b/Items/CraftingAccess.cs @@ -40,11 +40,11 @@ public override void AddRecipes() recipe.AddRecipeGroup("MagicStorage:AnyDiamond", 3); if (MagicStorage.legendMod == null) { - recipe.AddIngredient(ItemID.Sapphire, 3); + recipe.AddIngredient(ItemID.Sapphire, 7); } else { - recipe.AddRecipeGroup("MagicStorage:AnySapphire", 3); + recipe.AddRecipeGroup("MagicStorage:AnySapphire", 7); } recipe.AddTile(TileID.WorkBenches); recipe.SetResult(this); @@ -52,4 +52,3 @@ public override void AddRecipes() } } } - diff --git a/Items/Locator.cs b/Items/Locator.cs index e6bec2ee..fc19d515 100644 --- a/Items/Locator.cs +++ b/Items/Locator.cs @@ -72,7 +72,7 @@ public override void AddRecipes() { ModRecipe recipe = new ModRecipe(mod); recipe.AddIngredient(ItemID.MeteoriteBar, 10); - recipe.AddIngredient(ItemID.Amber, 2); + recipe.AddIngredient(ItemID.Amber, 5); recipe.AddTile(TileID.Anvils); recipe.SetResult(this); recipe.AddRecipe(); @@ -103,4 +103,3 @@ public override void NetRecieve(BinaryReader reader) } } } - diff --git a/Items/LocatorDisk.cs b/Items/LocatorDisk.cs index da7a14b9..ae6c6474 100644 --- a/Items/LocatorDisk.cs +++ b/Items/LocatorDisk.cs @@ -46,11 +46,10 @@ public override void AddRecipes() { ModRecipe recipe = new ModRecipe(mod); recipe.AddIngredient(ItemID.MartianConduitPlating, 25); - recipe.AddIngredient(ItemID.LunarBar, 2); + recipe.AddIngredient(ItemID.LunarBar, 5); recipe.AddTile(TileID.LunarCraftingStation); recipe.SetResult(this); recipe.AddRecipe(); } } } - diff --git a/Items/PortableAccess.cs b/Items/PortableAccess.cs index 64353e73..67853f26 100644 --- a/Items/PortableAccess.cs +++ b/Items/PortableAccess.cs @@ -134,7 +134,7 @@ public override void AddRecipes() recipe.AddIngredient(mod, "LocatorDisk"); recipe.AddIngredient(mod, "RadiantJewel"); recipe.AddRecipeGroup("MagicStorage:AnyDiamond", 3); - recipe.AddIngredient(ItemID.Ruby, 3); + recipe.AddIngredient(ItemID.Ruby, 7); recipe.AddTile(TileID.LunarCraftingStation); recipe.SetResult(this); recipe.AddRecipe(); @@ -146,7 +146,7 @@ public override void AddRecipes() recipe.AddIngredient(mod, "LocatorDisk"); recipe.AddIngredient(otherMod, "InfinityCrystal"); recipe.AddRecipeGroup("MagicStorage:AnyDiamond", 3); - recipe.AddIngredient(ItemID.Ruby, 3); + recipe.AddIngredient(ItemID.Ruby, 7); recipe.AddTile(otherMod, "PuriumAnvil"); recipe.SetResult(this); recipe.AddRecipe(); @@ -159,7 +159,7 @@ public override void AddRecipes() recipe.AddIngredient(mod, "LocatorDisk"); recipe.AddIngredient(otherMod, "CosmiliteBar", 20); recipe.AddRecipeGroup("MagicStorage:AnyDiamond", 3); - recipe.AddIngredient(ItemID.Ruby, 3); + recipe.AddIngredient(ItemID.Ruby, 7); recipe.AddTile(TileID.LunarCraftingStation); recipe.SetResult(this); recipe.AddRecipe(); @@ -167,4 +167,3 @@ public override void AddRecipes() } } } - diff --git a/Items/RemoteAccess.cs b/Items/RemoteAccess.cs index 96fc7177..80ecc6f8 100644 --- a/Items/RemoteAccess.cs +++ b/Items/RemoteAccess.cs @@ -40,11 +40,11 @@ public override void AddRecipes() recipe.AddRecipeGroup("MagicStorage:AnyDiamond", 3); if (MagicStorage.legendMod == null) { - recipe.AddIngredient(ItemID.Ruby, 3); + recipe.AddIngredient(ItemID.Ruby, 7); } else { - recipe.AddRecipeGroup("MagicStorage:AnyRuby", 3); + recipe.AddRecipeGroup("MagicStorage:AnyRuby", 7); } recipe.AddTile(TileID.WorkBenches); recipe.SetResult(this); @@ -52,4 +52,3 @@ public override void AddRecipes() } } } - diff --git a/Items/StorageAccess.cs b/Items/StorageAccess.cs index 932cb7bd..dffcf601 100644 --- a/Items/StorageAccess.cs +++ b/Items/StorageAccess.cs @@ -39,11 +39,11 @@ public override void AddRecipes() recipe.AddRecipeGroup("MagicStorage:AnyDiamond", 1); if (MagicStorage.legendMod == null) { - recipe.AddIngredient(ItemID.Topaz, 3); + recipe.AddIngredient(ItemID.Topaz, 7); } else { - recipe.AddRecipeGroup("MagicStorage:AnyTopaz", 3); + recipe.AddRecipeGroup("MagicStorage:AnyTopaz", 7); } recipe.AddTile(TileID.WorkBenches); recipe.SetResult(this); @@ -51,4 +51,3 @@ public override void AddRecipes() } } } - diff --git a/Items/StorageHeart.cs b/Items/StorageHeart.cs index 1f06451b..bb87de15 100644 --- a/Items/StorageHeart.cs +++ b/Items/StorageHeart.cs @@ -39,11 +39,11 @@ public override void AddRecipes() recipe.AddRecipeGroup("MagicStorage:AnyDiamond", 3); if (MagicStorage.legendMod == null) { - recipe.AddIngredient(ItemID.Emerald, 3); + recipe.AddIngredient(ItemID.Emerald, 7); } else { - recipe.AddRecipeGroup("MagicStorage:AnyEmerald", 3); + recipe.AddRecipeGroup("MagicStorage:AnyEmerald", 7); } recipe.AddTile(TileID.WorkBenches); recipe.SetResult(this); From 723e688ff7f45274d34653bc9d98624f203df680 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 26 Aug 2018 12:17:11 +0300 Subject: [PATCH 64/80] reverted more crafting stations - use different crafting interfaces for this. if you want to keep it stick to the wvlad-fork branch. --- Components/TECraftingAccess.cs | 9 ++------- CraftingGUI.cs | 18 +++++++++++++----- StoragePlayer.cs | 1 + 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/Components/TECraftingAccess.cs b/Components/TECraftingAccess.cs index 76a14577..1024a67b 100644 --- a/Components/TECraftingAccess.cs +++ b/Components/TECraftingAccess.cs @@ -13,9 +13,7 @@ namespace MagicStorage.Components { public class TECraftingAccess : TEStorageComponent { - public const int Rows = 3; - public const int ItemsPerRow = 15; - public const int ItemsTotal = Rows * ItemsPerRow; + public const int ItemsTotal = 10; public Item[] stations = new Item[ItemsTotal]; @@ -136,10 +134,7 @@ public override void Load(TagCompound tag) { for (int k = 0; k < stations.Length; k++) { - if (k < listStations.Count) - stations[k] = ItemIO.Load(listStations[k]); - else - stations[k] = new Item(); + stations[k] = ItemIO.Load(listStations[k]); } } } diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 8bb794ef..086de545 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -66,7 +66,8 @@ public static bool RightMouseClicked private static UIButtonChoice filterButtons; private static UIText stationText; - private static UISlotZone stationZone = new UISlotZone(HoverStation, GetStation, inventoryScale / 1.55f); + private static UISlotZone stationZone = new UISlotZone(HoverStation, GetStation, inventoryScale); + private static UIText recipeText; private static UISlotZone recipeZone = new UISlotZone(HoverRecipe, GetRecipe, inventoryScale); internal static UIScrollbar scrollBar = new UIScrollbar(); @@ -219,13 +220,16 @@ public static void Initialize() stationZone.Width.Set(0f, 1f); stationZone.Top.Set(100f, 0f); - stationZone.Height.Set(110f, 0f); - stationZone.SetDimensions(15, 3); + stationZone.Height.Set(90f, 0f); + stationZone.SetDimensions(numColumns, 1); basePanel.Append(stationZone); + recipeText.Top.Set(152f, 0f); + basePanel.Append(recipeText); + recipeZone.Width.Set(0f, 1f); - recipeZone.Top.Set(196f, 0f); - recipeZone.Height.Set(-196f, 1f); + recipeZone.Top.Set(176f, 0f); + recipeZone.Height.Set(-216f, 1f); basePanel.Append(recipeZone); numRows = (recipes.Count + numColumns - 1) / numColumns; @@ -334,6 +338,10 @@ private static void InitLangStuff() { stationText = new UIText(Language.GetText("Mods.MagicStorage.CraftingStations")); } + if (recipeText == null) + { + recipeText = new UIText(Language.GetText("Mods.MagicStorage.Recipes")); + } if (capacityText == null) { capacityText = new UIText("Items"); diff --git a/StoragePlayer.cs b/StoragePlayer.cs index 3cfe3d05..a406c64a 100644 --- a/StoragePlayer.cs +++ b/StoragePlayer.cs @@ -181,6 +181,7 @@ public override bool ShiftClickSlot(Item[] inventory, int context, int slot) int oldStack = item.stack; if (StorageCrafting()) { + // I suggest to not use shift clicking for this because I often misused it trying to put things into a storage while crafting window is open if (false) { if (Main.netMode == 0) From 8a35283245d7051fa495715a82cb219d9bf92f0c Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 26 Aug 2018 12:20:20 +0300 Subject: [PATCH 65/80] reverted isItemKnown hotkey, if you want to keep it stick to the wvlad-fork branch. --- CraftingGUI.cs | 23 ----------------------- MagicStorage.cs | 6 ++---- 2 files changed, 2 insertions(+), 27 deletions(-) diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 086de545..dcfca6c9 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -413,29 +413,6 @@ private static void InitFilterButtons() public static void Update(GameTime gameTime) { - try - { - if (MagicStorage.IsItemKnownHotKey != null && MagicStorage.IsItemKnownHotKey.JustPressed && Main.HoverItem != null && !Main.HoverItem.IsAir) - { - var s = Main.HoverItem.Name + " is "; - var t = Main.HoverItem.type; - if (GetKnownItems().Contains(t)) - { - s += "known"; - var sum = ModPlayer.LatestAccessedStorage?.GetStoredItems().Where(x => x.type == t).Select(x => x.stack).DefaultIfEmpty().Sum() ?? 0; - if (sum > 0) - s += $" ({sum} in l.a.s.)"; - } - else - s += "new"; - Main.NewTextMultiline(s); - } - } - catch (KeyNotFoundException) - { - // ignore - } - try { oldMouse = StorageGUI.oldMouse; curMouse = StorageGUI.curMouse; diff --git a/MagicStorage.cs b/MagicStorage.cs index d3a2857c..5f3a702d 100644 --- a/MagicStorage.cs +++ b/MagicStorage.cs @@ -17,8 +17,7 @@ public class MagicStorage : Mod public static MagicStorage Instance; public static Mod bluemagicMod; public static Mod legendMod; - public static ModHotKey IsItemKnownHotKey { get; private set; } - + public static readonly Version requiredVersion = new Version(0, 9, 2, 2); public override void Load() @@ -31,8 +30,7 @@ public override void Load() InterfaceHelper.Initialize(); legendMod = ModLoader.GetMod("LegendOfTerraria3"); bluemagicMod = ModLoader.GetMod("Bluemagic"); - AddTranslations(); - IsItemKnownHotKey = RegisterHotKey("Is This Item Known?", ""); + AddTranslations(); } public override void Unload() From 33e457adad982591b9b3a07ce8394614d6cbbc16 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 26 Aug 2018 12:32:18 +0300 Subject: [PATCH 66/80] reverted mod search button, if you want to keep it stick to the wvlad-fork branch. --- CraftingGUI.cs | 34 ++++++++-------- MagicStorage.cs | 13 +------ MagicStorage.csproj | 1 - ModSearchBox.cs | 91 ------------------------------------------- Sorting/ItemSorter.cs | 30 +++++++------- StorageGUI.cs | 31 +++++++-------- 6 files changed, 46 insertions(+), 154 deletions(-) delete mode 100644 ModSearchBox.cs diff --git a/CraftingGUI.cs b/CraftingGUI.cs index dcfca6c9..ec3053e4 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Reflection; using System.Threading; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; @@ -64,6 +63,7 @@ public static bool RightMouseClicked private static UIButtonChoice recipeButtons; private static UIElement topBar2 = new UIElement(); private static UIButtonChoice filterButtons; + internal static UISearchBar searchBar2; private static UIText stationText; private static UISlotZone stationZone = new UISlotZone(HoverStation, GetStation, inventoryScale); @@ -121,9 +121,7 @@ public static bool RightMouseClicked private static float scrollBar2MaxViewSize = 2f; internal static UITextPanel craftButton; - public static readonly ModSearchBox modSearchBox = new ModSearchBox(RefreshItems); - - private static Item result = null; + private static Item result = null; private static UISlotZone resultZone = new UISlotZone(HoverResult, GetResult, inventoryScale); private static int craftTimer = 0; private const int startMaxCraftTimer = 20; @@ -208,12 +206,10 @@ public static void Initialize() InitFilterButtons(); float filterButtonsRight = filterButtons.GetDimensions().Width + padding; topBar2.Append(filterButtons); - - modSearchBox.Button.Left.Set(filterButtonsRight + padding, 0f); - modSearchBox.Button.Width.Set(-filterButtonsRight - 2 * padding, 1f); - modSearchBox.Button.Height.Set(0f, 1f); - modSearchBox.Button.OverflowHidden = true; - topBar2.Append(modSearchBox.Button); + searchBar2.Left.Set(filterButtonsRight + padding, 0f); + searchBar2.Width.Set(-filterButtonsRight - 2 * padding, 1f); + searchBar2.Height.Set(0f, 1f); + topBar2.Append(searchBar2); stationText.Top.Set(76f, 0f); basePanel.Append(stationText); @@ -334,6 +330,10 @@ private static void InitLangStuff() { searchBar = new UISearchBar(Language.GetText("Mods.MagicStorage.SearchName"), RefreshItems); } + if (searchBar2 == null) + { + searchBar2 = new UISearchBar(Language.GetText("Mods.MagicStorage.SearchMod"), RefreshItems); + } if (stationText == null) { stationText = new UIText(Language.GetText("Mods.MagicStorage.CraftingStations")); @@ -370,7 +370,6 @@ private static void InitLangStuff() { craftButton = new UITextPanel(Language.GetText("LegacyMisc.72"), 1f); } - modSearchBox.InitLangStuff(); } private static void InitSortButtons() @@ -431,7 +430,6 @@ public static void Update(GameTime gameTime) UpdateRecipeText(); UpdateScrollBar(); UpdateCraftButton(); - modSearchBox.Update(curMouse, oldMouse); } else { @@ -796,7 +794,7 @@ public static void RefreshItems() return; } - items.AddRange(ItemSorter.SortAndFilter(heart.GetStoredItems(), SortMode.Id, FilterMode.All, ModSearchBox.ModIndexAll, "")); + items.AddRange(ItemSorter.SortAndFilter(heart.GetStoredItems(), SortMode.Id, FilterMode.All, searchBar2.Text, "")); AnalyzeIngredients(); InitLangStuff(); InitSortButtons(); @@ -869,7 +867,7 @@ static void EnsureProductToRecipesInited() { if (_productToRecipes == null) { - var allRecipes = ItemSorter.GetRecipes(SortMode.Id, FilterMode.All, ModSearchBox.ModIndexAll, "").Where(x => x != null && x.createItem != null && x.createItem.type > 0).ToArray(); + var allRecipes = ItemSorter.GetRecipes(SortMode.Id, FilterMode.All, "", "").Where(x => x != null && x.createItem != null && x.createItem.type > 0).ToArray(); _productToRecipes = allRecipes.GroupBy(x => x.createItem.type).ToDictionary(x => x.Key, x => x.ToList()); } } @@ -993,13 +991,13 @@ private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craf var temp = new HashSet(); var tempCache = new Dictionary(); - var modFilterIndex = modSearchBox.ModIndex; + var modFilter = searchBar2.Text; IEnumerable filteredRecipes = null; Action doFiltering = () => { - filteredRecipes = ItemSorter.GetRecipes(sortMode, filterMode, modFilterIndex, searchBar.Text).Where(x => x != null) + filteredRecipes = ItemSorter.GetRecipes(sortMode, filterMode, modFilter, searchBar.Text).Where(x => x != null) // show only blacklisted recipes only if choice = 2, otherwise show all other .Where(x => (recipeButtons.Choice == RecipeButtonsBlacklistChoice) == hiddenRecipes.Contains(x.createItem.type)) // show only new items if selected @@ -1051,10 +1049,10 @@ private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craf doFiltering(); } - if (threadRecipes.Count == 0 && modFilterIndex != ModSearchBox.ModIndexAll) + if (threadRecipes.Count == 0 && modFilter != "") { // search all mods - modFilterIndex = ModSearchBox.ModIndexAll; + modFilter = ""; doFiltering(); } } diff --git a/MagicStorage.cs b/MagicStorage.cs index 5f3a702d..c7ad3ee2 100644 --- a/MagicStorage.cs +++ b/MagicStorage.cs @@ -260,18 +260,7 @@ private void AddTranslations() AddTranslation(text); } - public override void PostSetupContent() - { - - var type = Assembly.GetAssembly(typeof(Mod)).GetType("Terraria.ModLoader.Mod"); - FieldInfo loadModsField = type.GetField("items", BindingFlags.Instance | BindingFlags.NonPublic); - - AllMods = ModLoader.GetLoadedMods().Where(x => ((Dictionary)loadModsField.GetValue(ModLoader.GetMod(x))).Count > 0).ToArray(); - } - - public string[] AllMods { get; private set; } - - public override void AddRecipeGroups() + public override void AddRecipeGroups() { RecipeGroup group = new RecipeGroup(() => Lang.misc[37] + " Chest", ItemID.Chest, diff --git a/MagicStorage.csproj b/MagicStorage.csproj index 72ea9fe0..25f57ee1 100644 --- a/MagicStorage.csproj +++ b/MagicStorage.csproj @@ -107,7 +107,6 @@ - diff --git a/ModSearchBox.cs b/ModSearchBox.cs deleted file mode 100644 index b1072372..00000000 --- a/ModSearchBox.cs +++ /dev/null @@ -1,91 +0,0 @@ -using System; -using Microsoft.Win32.SafeHandles; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Input; -using Terraria.GameContent.UI.Elements; - -namespace MagicStorage -{ - public class ModSearchBox - { - UITextPanel _modButton; - public int ModIndex { get; private set; } = ModIndexAll; - public string ModName { get; private set; } - public Action OnChanged; - - public ModSearchBox(Action onChanged) - { - OnChanged = onChanged; - } - - public UIPanel Button => _modButton; - - public void InitLangStuff() - { - if (_modButton == null) - { - _modButton = new UITextPanel(MakeModButtonText(), 0.8f); - } - } - - void SetSearchMod(int index, bool silent) - { - if (ModIndex == index) return; - ModIndex = index; - if (_modButton != null) - _modButton.SetText(MakeModButtonText()); - ModName = ""; - if (index > -1) ModName = MagicStorage.Instance.AllMods[index]; - if (!silent) OnChanged?.Invoke(); - } - - public void Reset(bool silent) - { - SetSearchMod(ModIndexAll, silent); - } - - public const int ModIndexBaseGame = -1; - public const int ModIndexAll = -2; - - string MakeModButtonText() - { - if (ModIndex == ModIndexAll) - return "All mods"; - else if (ModIndex == ModIndexBaseGame) - { - return "Terraria"; - } - else - return MagicStorage.Instance.AllMods[ModIndex]; - } - - public void Update(MouseState curMouse, MouseState oldMouse) - { - Rectangle dim = InterfaceHelper.GetFullRectangle(_modButton); - if (curMouse.X > dim.X && curMouse.X < dim.X + dim.Width && curMouse.Y > dim.Y && curMouse.Y < dim.Y + dim.Height) - { - _modButton.BackgroundColor = new Color(73, 94, 171); - var allMods = MagicStorage.Instance.AllMods; - int index = ModIndex; - if (curMouse.LeftButton == ButtonState.Pressed && oldMouse.LeftButton == ButtonState.Released) - { - index++; - if (index >= allMods.Length) - index = ModIndexAll; - } - else if (curMouse.RightButton == ButtonState.Pressed && oldMouse.RightButton == ButtonState.Released) - { - index--; - if (index < -2) - index = allMods.Length - 1; - } - - SetSearchMod(index, false); - } - else - { - _modButton.BackgroundColor = new Color(63, 82, 151) * 0.7f; - } - } - } -} diff --git a/Sorting/ItemSorter.cs b/Sorting/ItemSorter.cs index 10c5d6a4..130259e9 100644 --- a/Sorting/ItemSorter.cs +++ b/Sorting/ItemSorter.cs @@ -7,20 +7,20 @@ namespace MagicStorage.Sorting { public static class ItemSorter { - public static IEnumerable SortAndFilter(IEnumerable items, SortMode sortMode, FilterMode filterMode, int modFilterIndex, string nameFilter, int? takeCount = null) + public static IEnumerable SortAndFilter(IEnumerable items, SortMode sortMode, FilterMode filterMode, string modFilter, string nameFilter, int? takeCount = null) { ItemFilter filter = MakeFilter(filterMode); - IEnumerable filteredItems = items.Where((item) => filter.Passes(item) && FilterName(item, nameFilter) && FilterMod(item, modFilterIndex)); + IEnumerable filteredItems = items.Where((item) => filter.Passes(item) && FilterName(item, modFilter, nameFilter)); if (takeCount != null) filteredItems = filteredItems.Take(takeCount.Value); var func = MakeSortFunction(sortMode); if (func == null) return filteredItems; return filteredItems.OrderBy(x => x, func).ThenBy(x => x.type).ThenBy(x => x.value); } - public static IEnumerable GetRecipes(SortMode sortMode, FilterMode filterMode, int modFilterIndex, string nameFilter) + public static IEnumerable GetRecipes(SortMode sortMode, FilterMode filterMode, string modFilter, string nameFilter) { var filter = MakeFilter(filterMode); - IEnumerable filteredRecipes = Main.recipe.Where((recipe, index) => index < Recipe.numRecipes && filter.Passes(recipe) && FilterName(recipe.createItem, nameFilter) && FilterMod(recipe.createItem, modFilterIndex)); + IEnumerable filteredRecipes = Main.recipe.Where((recipe, index) => index < Recipe.numRecipes && filter.Passes(recipe) && FilterName(recipe.createItem, modFilter, nameFilter)); var func = MakeSortFunction(sortMode); if (func == null) return filteredRecipes; return filteredRecipes.OrderBy(x => x.createItem, func).ThenBy(x => x.createItem.type).ThenBy(x => x.createItem.value); @@ -117,18 +117,16 @@ static bool FilterName(Item item, string filter) if (filter.Trim().Length == 0) filter = string.Empty; return item.Name.ToLowerInvariant().IndexOf(filter.Trim().ToLowerInvariant()) >= 0; } - - static bool FilterMod(Item item, int modFilterIndex) - { - if (modFilterIndex == ModSearchBox.ModIndexAll) return true; - var allMods = MagicStorage.Instance.AllMods; - int index = ModSearchBox.ModIndexBaseGame; - if (item.modItem != null) - { - index = Array.IndexOf(allMods, item.modItem.mod.Name); - } - return index == modFilterIndex; - } + + private static bool FilterName(Item item, string modFilter, string filter) + { + string modName = "Terraria"; + if (item.modItem != null) + { + modName = item.modItem.mod.DisplayName; + } + return modName.ToLowerInvariant().IndexOf(modFilter.ToLowerInvariant()) >= 0 && item.Name.ToLowerInvariant().IndexOf(filter.ToLowerInvariant()) >= 0; + } } } diff --git a/StorageGUI.cs b/StorageGUI.cs index 41570745..3fd2ba1b 100644 --- a/StorageGUI.cs +++ b/StorageGUI.cs @@ -46,9 +46,8 @@ public static bool MouseClicked internal static UITextPanel restockButton; private static UIElement topBar2 = new UIElement(); private static UIButtonChoice filterButtons; - - public static readonly ModSearchBox modSearchBox = new ModSearchBox(RefreshItems); - + internal static UISearchBar searchBar2; + private static UISlotZone slotZone = new UISlotZone(HoverItemSlot, GetItem, inventoryScale); private static int slotFocus = -1; private static int rightClickTimer = 0; @@ -125,12 +124,10 @@ public static void Initialize() float filterButtonsRight = filterButtons.GetDimensions().Width + padding; topBar2.Append(filterButtons); - - modSearchBox.Button.Left.Set(filterButtonsRight + padding, 0f); - modSearchBox.Button.Width.Set(-filterButtonsRight - 2 * padding, 1f); - modSearchBox.Button.Height.Set(0f, 1f); - modSearchBox.Button.OverflowHidden = true; - topBar2.Append(modSearchBox.Button); + searchBar2.Left.Set(filterButtonsRight + padding, 0f); + searchBar2.Width.Set(-filterButtonsRight - 2 * padding, 1f); + searchBar2.Height.Set(0f, 1f); + topBar2.Append(searchBar2); slotZone.Width.Set(0f, 1f); slotZone.Top.Set(76f, 0f); @@ -188,7 +185,10 @@ private static void InitLangStuff() { searchBar = new UISearchBar(Language.GetText("Mods.MagicStorage.SearchName"), RefreshItems); } - modSearchBox.InitLangStuff(); + if (searchBar2 == null) + { + searchBar2 = new UISearchBar(Language.GetText("Mods.MagicStorage.SearchMod"), RefreshItems); + } if (capacityText == null) { capacityText = new UIText("Items"); @@ -229,7 +229,6 @@ public static void Update(GameTime gameTime) basePanel.Update(gameTime); UpdateScrollBar(); UpdateDepositButton(); - modSearchBox.Update(curMouse, oldMouse); } else { @@ -337,7 +336,7 @@ public static void RefreshItems() SortMode sortMode = (SortMode) sortButtons.Choice; FilterMode filterMode = (FilterMode) filterButtons.Choice; - var modFilterIndex = modSearchBox.ModIndex; + var modFilter = searchBar2.Text; Action doFiltering = () => { @@ -348,10 +347,10 @@ public static void RefreshItems() var toFilter = heart.UniqueItemsPutHistory.Reverse().Where(x => stored.ContainsKey(x.type)).Select(x => stored[x.type]); itemsLocal = ItemSorter.SortAndFilter(toFilter, sortMode == SortMode.Default ? SortMode.AsIs : sortMode, - FilterMode.All, modFilterIndex, searchBar.Text, 100); + FilterMode.All, modFilter, searchBar.Text, 100); } else - itemsLocal = ItemSorter.SortAndFilter(heart.GetStoredItems(), sortMode, filterMode, modFilterIndex, searchBar.Text) + itemsLocal = ItemSorter.SortAndFilter(heart.GetStoredItems(), sortMode, filterMode, modFilter, searchBar.Text) .OrderBy(x => x.favorited ? 0 : 1); items.AddRange(itemsLocal.Where(x => !favoritedOnlyButton.Value || x.favorited)); @@ -369,10 +368,10 @@ public static void RefreshItems() doFiltering(); } - if (items.Count == 0 && modFilterIndex != ModSearchBox.ModIndexAll) + if (items.Count == 0 && modFilter != "") { // search all mods - modFilterIndex = ModSearchBox.ModIndexAll; + modFilter = ""; doFiltering(); } } From a2a5224d82b5a42657376f69f4d92289f2c241a6 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 26 Aug 2018 12:41:29 +0300 Subject: [PATCH 67/80] reverted adding visual studio project --- .gitignore | 5 ++ MagicStorage.csproj | 134 ------------------------------------- MagicStorage.sln | 25 ------- Properties/AssemblyInfo.cs | 37 ---------- build.txt | 11 ++- 5 files changed, 13 insertions(+), 199 deletions(-) delete mode 100644 MagicStorage.csproj delete mode 100644 MagicStorage.sln delete mode 100644 Properties/AssemblyInfo.cs diff --git a/.gitignore b/.gitignore index 94b41b91..bf9eddd4 100644 --- a/.gitignore +++ b/.gitignore @@ -330,3 +330,8 @@ ASALocalRun/ # Local History for Visual Studio .localhistory/ + +.gitignore +*.sln +*.csproj +Properties/AssemblyInfo.cs \ No newline at end of file diff --git a/MagicStorage.csproj b/MagicStorage.csproj deleted file mode 100644 index 25f57ee1..00000000 --- a/MagicStorage.csproj +++ /dev/null @@ -1,134 +0,0 @@ - - - - - Debug - AnyCPU - {162C8AA5-FF1C-4357-AEED-FAF522C56FEE} - Library - Properties - MagicStorage - MagicStorage - v4.7.1 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - C:\Program Files (x86)\Steam\steamapps\common\Terraria\References\ReLogic.dll - - - - - - - - - - - C:\Program Files (x86)\Steam\steamapps\common\Terraria\Terraria.exe - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "C:\Program Files (x86)\Steam\steamapps\common\Terraria\tModLoaderServer.exe" -build "$(ProjectDir.TrimEnd('\'))" - - \ No newline at end of file diff --git a/MagicStorage.sln b/MagicStorage.sln deleted file mode 100644 index bdc43f3c..00000000 --- a/MagicStorage.sln +++ /dev/null @@ -1,25 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27703.2026 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MagicStorage", "MagicStorage.csproj", "{162C8AA5-FF1C-4357-AEED-FAF522C56FEE}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {162C8AA5-FF1C-4357-AEED-FAF522C56FEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {162C8AA5-FF1C-4357-AEED-FAF522C56FEE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {162C8AA5-FF1C-4357-AEED-FAF522C56FEE}.Release|Any CPU.ActiveCfg = Release|Any CPU - {162C8AA5-FF1C-4357-AEED-FAF522C56FEE}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {BE578426-8436-495A-990A-62B26E41AEAB} - EndGlobalSection -EndGlobal diff --git a/Properties/AssemblyInfo.cs b/Properties/AssemblyInfo.cs deleted file mode 100644 index 8c06682d..00000000 --- a/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("MagicStorage")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("MagicStorage")] -[assembly: AssemblyCopyright("Copyright © 2018")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("162c8aa5-ff1c-4357-aeed-faf522c56fee")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] - diff --git a/build.txt b/build.txt index 712c68ca..483624f2 100644 --- a/build.txt +++ b/build.txt @@ -1,10 +1,15 @@ +author = blushiemagic author = blushiemagic and wvlad +version = 0.4.3.3 version = 0.4.100.2 displayName = Magic Storage +displayName = Magic Storage +homepage = https://forums.terraria.org/index.php?threads/magic-storage.56294/ homepage = https://forums.terraria.org/index.php?threads/magic-storage.56294/ hideCode = false +hideCode = false hideResources = false +hideResources = false +includeSource = true includeSource = true -includePDB = true -languageVersion = 6 -buildIgnore = OldArt\*, .git\*, obj\* \ No newline at end of file +buildIgnore = OldArt\*, .git\* \ No newline at end of file From 0bf47fbd849338c3ef4609bdee2bcde64481cdda Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 26 Aug 2018 12:42:19 +0300 Subject: [PATCH 68/80] amend --- .gitignore | 337 ----------------------------------------------------- 1 file changed, 337 deletions(-) delete mode 100644 .gitignore diff --git a/.gitignore b/.gitignore deleted file mode 100644 index bf9eddd4..00000000 --- a/.gitignore +++ /dev/null @@ -1,337 +0,0 @@ -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. -## -## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore - -# User-specific files -*.suo -*.user -*.userosscache -*.sln.docstates - -# User-specific files (MonoDevelop/Xamarin Studio) -*.userprefs - -# Build results -[Dd]ebug/ -[Dd]ebugPublic/ -[Rr]elease/ -[Rr]eleases/ -x64/ -x86/ -bld/ -[Bb]in/ -[Oo]bj/ -[Ll]og/ - -# Visual Studio 2015/2017 cache/options directory -.vs/ -# Uncomment if you have tasks that create the project's static files in wwwroot -#wwwroot/ - -# Visual Studio 2017 auto generated files -Generated\ Files/ - -# MSTest test Results -[Tt]est[Rr]esult*/ -[Bb]uild[Ll]og.* - -# NUNIT -*.VisualState.xml -TestResult.xml - -# Build Results of an ATL Project -[Dd]ebugPS/ -[Rr]eleasePS/ -dlldata.c - -# Benchmark Results -BenchmarkDotNet.Artifacts/ - -# .NET Core -project.lock.json -project.fragment.lock.json -artifacts/ - -# StyleCop -StyleCopReport.xml - -# Files built by Visual Studio -*_i.c -*_p.c -*_h.h -*.ilk -*.meta -*.obj -*.iobj -*.pch -*.pdb -*.ipdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.tmp_proj -*.log -*.vspscc -*.vssscc -.builds -*.pidb -*.svclog -*.scc - -# Chutzpah Test files -_Chutzpah* - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opendb -*.opensdf -*.sdf -*.cachefile -*.VC.db -*.VC.VC.opendb - -# Visual Studio profiler -*.psess -*.vsp -*.vspx -*.sap - -# Visual Studio Trace Files -*.e2e - -# TFS 2012 Local Workspace -$tf/ - -# Guidance Automation Toolkit -*.gpState - -# ReSharper is a .NET coding add-in -_ReSharper*/ -*.[Rr]e[Ss]harper -*.DotSettings.user - -# JustCode is a .NET coding add-in -.JustCode - -# TeamCity is a build add-in -_TeamCity* - -# DotCover is a Code Coverage Tool -*.dotCover - -# AxoCover is a Code Coverage Tool -.axoCover/* -!.axoCover/settings.json - -# Visual Studio code coverage results -*.coverage -*.coveragexml - -# NCrunch -_NCrunch_* -.*crunch*.local.xml -nCrunchTemp_* - -# MightyMoose -*.mm.* -AutoTest.Net/ - -# Web workbench (sass) -.sass-cache/ - -# Installshield output folder -[Ee]xpress/ - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish/ - -# Publish Web Output -*.[Pp]ublish.xml -*.azurePubxml -# Note: Comment the next line if you want to checkin your web deploy settings, -# but database connection strings (with potential passwords) will be unencrypted -*.pubxml -*.publishproj - -# Microsoft Azure Web App publish settings. Comment the next line if you want to -# checkin your Azure Web App publish settings, but sensitive information contained -# in these scripts will be unencrypted -PublishScripts/ - -# NuGet Packages -*.nupkg -# The packages folder can be ignored because of Package Restore -**/[Pp]ackages/* -# except build/, which is used as an MSBuild target. -!**/[Pp]ackages/build/ -# Uncomment if necessary however generally it will be regenerated when needed -#!**/[Pp]ackages/repositories.config -# NuGet v3's project.json files produces more ignorable files -*.nuget.props -*.nuget.targets - -# Microsoft Azure Build Output -csx/ -*.build.csdef - -# Microsoft Azure Emulator -ecf/ -rcf/ - -# Windows Store app package directories and files -AppPackages/ -BundleArtifacts/ -Package.StoreAssociation.xml -_pkginfo.txt -*.appx - -# Visual Studio cache files -# files ending in .cache can be ignored -*.[Cc]ache -# but keep track of directories ending in .cache -!*.[Cc]ache/ - -# Others -ClientBin/ -~$* -*~ -*.dbmdl -*.dbproj.schemaview -*.jfm -*.pfx -*.publishsettings -orleans.codegen.cs - -# Including strong name files can present a security risk -# (https://github.com/github/gitignore/pull/2483#issue-259490424) -#*.snk - -# Since there are multiple workflows, uncomment next line to ignore bower_components -# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) -#bower_components/ - -# RIA/Silverlight projects -Generated_Code/ - -# Backup & report files from converting an old project file -# to a newer Visual Studio version. Backup files are not needed, -# because we have git ;-) -_UpgradeReport_Files/ -Backup*/ -UpgradeLog*.XML -UpgradeLog*.htm -ServiceFabricBackup/ -*.rptproj.bak - -# SQL Server files -*.mdf -*.ldf -*.ndf - -# Business Intelligence projects -*.rdl.data -*.bim.layout -*.bim_*.settings -*.rptproj.rsuser - -# Microsoft Fakes -FakesAssemblies/ - -# GhostDoc plugin setting file -*.GhostDoc.xml - -# Node.js Tools for Visual Studio -.ntvs_analysis.dat -node_modules/ - -# Visual Studio 6 build log -*.plg - -# Visual Studio 6 workspace options file -*.opt - -# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) -*.vbw - -# Visual Studio LightSwitch build output -**/*.HTMLClient/GeneratedArtifacts -**/*.DesktopClient/GeneratedArtifacts -**/*.DesktopClient/ModelManifest.xml -**/*.Server/GeneratedArtifacts -**/*.Server/ModelManifest.xml -_Pvt_Extensions - -# Paket dependency manager -.paket/paket.exe -paket-files/ - -# FAKE - F# Make -.fake/ - -# JetBrains Rider -.idea/ -*.sln.iml - -# CodeRush -.cr/ - -# Python Tools for Visual Studio (PTVS) -__pycache__/ -*.pyc - -# Cake - Uncomment if you are using it -# tools/** -# !tools/packages.config - -# Tabs Studio -*.tss - -# Telerik's JustMock configuration file -*.jmconfig - -# BizTalk build output -*.btp.cs -*.btm.cs -*.odx.cs -*.xsd.cs - -# OpenCover UI analysis results -OpenCover/ - -# Azure Stream Analytics local run output -ASALocalRun/ - -# MSBuild Binary and Structured Log -*.binlog - -# NVidia Nsight GPU debugger configuration file -*.nvuser - -# MFractors (Xamarin productivity tool) working folder -.mfractor/ - -# Local History for Visual Studio -.localhistory/ - -.gitignore -*.sln -*.csproj -Properties/AssemblyInfo.cs \ No newline at end of file From 1e618d628028594740040c623dfd06715a60c245 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 26 Aug 2018 12:44:08 +0300 Subject: [PATCH 69/80] reverted build.txt changes --- build.txt | 7 ------- 1 file changed, 7 deletions(-) diff --git a/build.txt b/build.txt index 483624f2..6c650742 100644 --- a/build.txt +++ b/build.txt @@ -1,15 +1,8 @@ author = blushiemagic -author = blushiemagic and wvlad version = 0.4.3.3 -version = 0.4.100.2 displayName = Magic Storage -displayName = Magic Storage -homepage = https://forums.terraria.org/index.php?threads/magic-storage.56294/ homepage = https://forums.terraria.org/index.php?threads/magic-storage.56294/ hideCode = false -hideCode = false hideResources = false -hideResources = false -includeSource = true includeSource = true buildIgnore = OldArt\*, .git\* \ No newline at end of file From dd0ce5e8060b96404dbbe0dcc2e65f586ecb7ec9 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 26 Aug 2018 12:50:50 +0300 Subject: [PATCH 70/80] gitignore --- .gitignore | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..cb7d9c23 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +*.csproj +*.sln +*.user +obj/ +bin/ +.vs/ \ No newline at end of file From 433e4b471215f0c7bb436f673cb1950e8dba8a47 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 26 Aug 2018 12:57:05 +0300 Subject: [PATCH 71/80] no changes --- MagicStorage.csproj | 270 ++++++++++++++++++++++---------------------- 1 file changed, 135 insertions(+), 135 deletions(-) diff --git a/MagicStorage.csproj b/MagicStorage.csproj index d837a8b9..38177dca 100644 --- a/MagicStorage.csproj +++ b/MagicStorage.csproj @@ -1,136 +1,136 @@ - - - - - Debug - AnyCPU - {162C8AA5-FF1C-4357-AEED-FAF522C56FEE} - Library - Properties - MagicStorage - MagicStorage - v4.7.1 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - C:\Program Files (x86)\Steam\steamapps\common\Terraria\References\ReLogic.dll - - - - - - - - - - - C:\Program Files (x86)\Steam\steamapps\common\Terraria\Terraria.exe - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "C:\Program Files (x86)\Steam\steamapps\common\Terraria\tModLoaderServer.exe" -build "$(ProjectDir.TrimEnd('\'))" - + + + + + Debug + AnyCPU + {162C8AA5-FF1C-4357-AEED-FAF522C56FEE} + Library + Properties + MagicStorage + MagicStorage + v4.7.1 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + C:\Program Files (x86)\Steam\steamapps\common\Terraria\References\ReLogic.dll + + + + + + + + + + + C:\Program Files (x86)\Steam\steamapps\common\Terraria\Terraria.exe + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + "C:\Program Files (x86)\Steam\steamapps\common\Terraria\tModLoaderServer.exe" -build "$(ProjectDir.TrimEnd('\'))" + \ No newline at end of file From 2a312f6328f19f6b735c25eae2f7d53657a5428b Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 26 Aug 2018 12:59:32 +0300 Subject: [PATCH 72/80] C#6 --- build.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/build.txt b/build.txt index 6c650742..45c20a9f 100644 --- a/build.txt +++ b/build.txt @@ -5,4 +5,5 @@ homepage = https://forums.terraria.org/index.php?threads/magic-storage.56294/ hideCode = false hideResources = false includeSource = true -buildIgnore = OldArt\*, .git\* \ No newline at end of file +buildIgnore = OldArt\*, .git\* +languageVersion = 6 \ No newline at end of file From 648612267bebb79a69e7f70143c465a48535b0f0 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 26 Aug 2018 13:04:06 +0300 Subject: [PATCH 73/80] reverted DPS tooltips, if you want to keep it stick to the wvlad-fork branch. --- CraftingGUI.cs | 7 ------- DpsTooltips.cs | 17 ----------------- MagicStorage.csproj | 1 - 3 files changed, 25 deletions(-) delete mode 100644 DpsTooltips.cs diff --git a/CraftingGUI.cs b/CraftingGUI.cs index ec3053e4..3a82f5a9 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -592,7 +592,6 @@ private static void UpdateRecipeText() if (selectedRecipe == null) { reqObjText2.SetText(""); - recipePanelHeader.SetText(Language.GetText("Mods.MagicStorage.SelectedRecipe").Value); } else { @@ -652,12 +651,6 @@ private static void UpdateRecipeText() text = Language.GetTextValue("LegacyInterface.23"); } reqObjText2.SetText(text); - var item = selectedRecipe.createItem; - var dps = CompareDps.GetDps(item); - if (dps >= 1f) - recipePanelHeader.SetText("DPS = " + dps.ToString("F0")); - else - recipePanelHeader.SetText(""); } } diff --git a/DpsTooltips.cs b/DpsTooltips.cs deleted file mode 100644 index f2997369..00000000 --- a/DpsTooltips.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Collections.Generic; -using MagicStorage.Sorting; -using Terraria; -using Terraria.ModLoader; - -namespace MagicStorage -{ - public class DpsTooltips : GlobalItem - { - public override void ModifyTooltips(Item item, List tooltips) - { - var dps = CompareDps.GetDps(item); - if (dps > 1f) - tooltips.Add(new TooltipLine(MagicStorage.Instance, "DPS", dps.ToString("F0") + " DPS")); - } - } -} diff --git a/MagicStorage.csproj b/MagicStorage.csproj index 25f57ee1..13a9c0e2 100644 --- a/MagicStorage.csproj +++ b/MagicStorage.csproj @@ -69,7 +69,6 @@ - From a2590c76db53698778e532f86e55a598a061594b Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 26 Aug 2018 13:09:46 +0300 Subject: [PATCH 74/80] added back sort by quantity --- GUIHelpers.cs | 4 +++- Sorting/ItemSorter.cs | 3 +++ Sorting/SortMode.cs | 1 + 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/GUIHelpers.cs b/GUIHelpers.cs index b0245f0c..2ecc6a88 100644 --- a/GUIHelpers.cs +++ b/GUIHelpers.cs @@ -17,6 +17,7 @@ public static UIButtonChoice MakeSortButtons(Action onChanged) MagicStorage.Instance.GetTexture("SortID"), MagicStorage.Instance.GetTexture("SortName"), MagicStorage.Instance.GetTexture("SortNumber"), + MagicStorage.Instance.GetTexture("SortNumber"), MagicStorage.Instance.GetTexture("SortNumber") }, new LocalizedText[] @@ -25,7 +26,8 @@ public static UIButtonChoice MakeSortButtons(Action onChanged) Language.GetText("Mods.MagicStorage.SortID"), Language.GetText("Mods.MagicStorage.SortName"), Language.GetText("Mods.MagicStorage.SortStack"), - Language.GetText("Mods.MagicStorage.SortDps") + Language.GetText("Mods.MagicStorage.SortStack"), + Language.GetText("Mods.MagicStorage.SortDps"), }); } diff --git a/Sorting/ItemSorter.cs b/Sorting/ItemSorter.cs index 130259e9..e63421d2 100644 --- a/Sorting/ItemSorter.cs +++ b/Sorting/ItemSorter.cs @@ -43,6 +43,9 @@ static CompareFunction MakeSortFunction(SortMode sortMode) case SortMode.Value: func = new CompareValue(); break; + case SortMode.Quantity: + func = new CompareQuantity(); + break; case SortMode.Dps: func = new CompareDps(); break; diff --git a/Sorting/SortMode.cs b/Sorting/SortMode.cs index 6066f7d0..d9212ce2 100644 --- a/Sorting/SortMode.cs +++ b/Sorting/SortMode.cs @@ -8,6 +8,7 @@ public enum SortMode Id, Name, Value, + Quantity, Dps, AsIs } From 5b0f03ec58588e93bb5af1ef7eff350f7346d75b Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Sun, 26 Aug 2018 13:19:27 +0300 Subject: [PATCH 75/80] amend --- GUIHelpers.cs | 2 +- MagicStorage.cs | 13 ++++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/GUIHelpers.cs b/GUIHelpers.cs index 2ecc6a88..0510049d 100644 --- a/GUIHelpers.cs +++ b/GUIHelpers.cs @@ -25,7 +25,7 @@ public static UIButtonChoice MakeSortButtons(Action onChanged) Language.GetText("Mods.MagicStorage.SortDefault"), Language.GetText("Mods.MagicStorage.SortID"), Language.GetText("Mods.MagicStorage.SortName"), - Language.GetText("Mods.MagicStorage.SortStack"), + Language.GetText("Mods.MagicStorage.SortValue"), Language.GetText("Mods.MagicStorage.SortStack"), Language.GetText("Mods.MagicStorage.SortDps"), }); diff --git a/MagicStorage.cs b/MagicStorage.cs index c7ad3ee2..58e09fd5 100644 --- a/MagicStorage.cs +++ b/MagicStorage.cs @@ -104,9 +104,16 @@ private void AddTranslations() text.AddTranslation(GameCulture.French, "Trier par nom"); text.AddTranslation(GameCulture.Spanish, "Ordenar por nombre"); AddTranslation(text); - - text = CreateTranslation("SortStack"); - text.SetDefault("Sort by Value"); + + text = CreateTranslation("SortStack"); + text.SetDefault("Sort by Stacks"); + text.AddTranslation(GameCulture.Russian, "Сортировка по стакам"); + text.AddTranslation(GameCulture.French, "Trier par piles"); + text.AddTranslation(GameCulture.Spanish, "Ordenar por pilas"); + AddTranslation(text); + + text = CreateTranslation("SortValue"); + text.SetDefault("Sort by Price"); AddTranslation(text); text = CreateTranslation("FilterAll"); From 577cfa060581aa790ad21c4b7dc3f827cf108e84 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Mon, 27 Aug 2018 09:43:38 +0300 Subject: [PATCH 76/80] reverted empty changes --- Components/CraftingAccess.cs | 2 +- Components/CreativeStorageUnit.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Components/CraftingAccess.cs b/Components/CraftingAccess.cs index c8901449..f47354d4 100644 --- a/Components/CraftingAccess.cs +++ b/Components/CraftingAccess.cs @@ -72,4 +72,4 @@ public override void KillTile(int i, int j, ref bool fail, ref bool effectOnly, } } } -} +} \ No newline at end of file diff --git a/Components/CreativeStorageUnit.cs b/Components/CreativeStorageUnit.cs index 6b7fdd6f..3c7f7c86 100644 --- a/Components/CreativeStorageUnit.cs +++ b/Components/CreativeStorageUnit.cs @@ -32,4 +32,4 @@ public override void PostDraw(int i, int j, SpriteBatch spriteBatch) spriteBatch.Draw(mod.GetTexture("Components/CreativeStorageUnit_Glow"), drawPos, frame, color); } } -} +} \ No newline at end of file From 877b0ffa2332b2e02dbc1ea9438998fee2a28c1e Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Mon, 27 Aug 2018 09:50:57 +0300 Subject: [PATCH 77/80] revert favorites --- Components/TEAbstractStorageUnit.cs | 2 +- Components/TECraftingAccess.cs | 8 ++--- Components/TECreativeStorageUnit.cs | 2 +- Components/TEStorageHeart.cs | 12 +++---- Components/TEStorageUnit.cs | 36 +++++++------------ CraftingGUI.cs | 7 ++-- MagicStorage.cs | 8 ----- NetHelper.cs | 56 ++++++++++++++--------------- StorageGUI.cs | 47 ++++++------------------ 9 files changed, 65 insertions(+), 113 deletions(-) diff --git a/Components/TEAbstractStorageUnit.cs b/Components/TEAbstractStorageUnit.cs index b2858dba..41ea38e7 100644 --- a/Components/TEAbstractStorageUnit.cs +++ b/Components/TEAbstractStorageUnit.cs @@ -62,7 +62,7 @@ public TEStorageHeart GetHeart() public abstract void DepositItem(Item toDeposit, bool locked = false); - public abstract Item TryWithdraw(Item lookFor, bool locked = false, bool keepOneIfFavorite = false); + public abstract Item TryWithdraw(Item lookFor, bool locked = false); public override TagCompound Save() { diff --git a/Components/TECraftingAccess.cs b/Components/TECraftingAccess.cs index 1024a67b..b04d1ac5 100644 --- a/Components/TECraftingAccess.cs +++ b/Components/TECraftingAccess.cs @@ -134,7 +134,7 @@ public override void Load(TagCompound tag) { for (int k = 0; k < stations.Length; k++) { - stations[k] = ItemIO.Load(listStations[k]); + stations[k] = ItemIO.Load(listStations[k]); } } } @@ -143,7 +143,7 @@ public override void NetSend(BinaryWriter writer, bool lightSend) { foreach (Item item in stations) { - ItemIO.Send(item, writer, true, true); + ItemIO.Send(item, writer, true, false); } } @@ -151,8 +151,8 @@ public override void NetReceive(BinaryReader reader, bool lightReceive) { for (int k = 0; k < stations.Length; k++) { - stations[k] = ItemIO.Receive(reader, true, true); + stations[k] = ItemIO.Receive(reader, true, false); } } } -} +} \ No newline at end of file diff --git a/Components/TECreativeStorageUnit.cs b/Components/TECreativeStorageUnit.cs index 79be71d8..ac37895f 100644 --- a/Components/TECreativeStorageUnit.cs +++ b/Components/TECreativeStorageUnit.cs @@ -43,7 +43,7 @@ public override void DepositItem(Item toDeposit, bool locked = false) { } - public override Item TryWithdraw(Item lookFor, bool locked = false, bool keepOneIfFavorite = false) + public override Item TryWithdraw(Item lookFor, bool locked = false) { if (Inactive) { diff --git a/Components/TEStorageHeart.cs b/Components/TEStorageHeart.cs index ec8fff0a..b8242c5b 100644 --- a/Components/TEStorageHeart.cs +++ b/Components/TEStorageHeart.cs @@ -293,12 +293,12 @@ public void DepositItem(Item toDeposit) { if (!storageUnit.Inactive && !storageUnit.IsFull) { - storageUnit.DepositItem(toDeposit, true); - if (toDeposit.IsAir) - { + storageUnit.DepositItem(toDeposit, true); + if (toDeposit.IsAir) + { _uniqueItemsPutHistory.Add(remember); return; - } + } } } toDeposit.newAndShiny = prevNewAndShiny; @@ -316,7 +316,7 @@ public void DepositItem(Item toDeposit) } } - public Item TryWithdraw(Item lookFor, bool keepOneIfFavorite) + public Item TryWithdraw(Item lookFor) { if (Main.netMode == 1) { @@ -333,7 +333,7 @@ public Item TryWithdraw(Item lookFor, bool keepOneIfFavorite) { if (storageUnit.HasItem(lookFor, true)) { - Item withdrawn = storageUnit.TryWithdraw(lookFor, true, keepOneIfFavorite); + Item withdrawn = storageUnit.TryWithdraw(lookFor, true); if (!withdrawn.IsAir) { if (result.IsAir) diff --git a/Components/TEStorageUnit.cs b/Components/TEStorageUnit.cs index 885a565b..e5434263 100644 --- a/Components/TEStorageUnit.cs +++ b/Components/TEStorageUnit.cs @@ -159,10 +159,7 @@ public override void DepositItem(Item toDeposit, bool locked = false) newStack = item.maxStack; } item.stack = newStack; - - if (toDeposit.favorited) item.favorited = true; if (toDeposit.newAndShiny) item.newAndShiny = true; - hasChange = true; toDeposit.stack = total - newStack; if (toDeposit.stack <= 0) @@ -176,6 +173,8 @@ public override void DepositItem(Item toDeposit, bool locked = false) if (!finished && !IsFull) { Item item = toDeposit.Clone(); + item.newAndShiny = false; + item.favorited = false; items.Add(item); toDeposit.SetDefaults(0, true); hasChange = true; @@ -199,7 +198,7 @@ public override void DepositItem(Item toDeposit, bool locked = false) } } - public override Item TryWithdraw(Item lookFor, bool locked = false, bool keepOneIfFavorite = false) + public override Item TryWithdraw(Item lookFor, bool locked = false) { if (Main.netMode == 1 && !receiving) { @@ -219,10 +218,7 @@ public override Item TryWithdraw(Item lookFor, bool locked = false, bool keepOne Item item = items[k]; if (ItemData.Matches(lookFor, item)) { - int maxToTake = item.stack; - if (item.stack > 0 && item.favorited && keepOneIfFavorite) - maxToTake -= 1; - int withdraw = Math.Min(lookFor.stack, maxToTake); + int withdraw = Math.Min(lookFor.stack, item.stack); item.stack -= withdraw; if (item.stack <= 0) { @@ -237,9 +233,7 @@ public override Item TryWithdraw(Item lookFor, bool locked = false, bool keepOne { if (Main.netMode == 2) { - var op = (WithdrawOperation)UnitOperation.Withdraw.Create(original); - op.SendKeepOneIfFavorite = keepOneIfFavorite; - netQueue.Enqueue(op); + netQueue.Enqueue(UnitOperation.Withdraw.Create(original)); } PostChangeContents(); } @@ -255,9 +249,7 @@ public override Item TryWithdraw(Item lookFor, bool locked = false, bool keepOne { if (Main.netMode == 2) { - var op = (WithdrawOperation)UnitOperation.Withdraw.Create(original); - op.SendKeepOneIfFavorite = keepOneIfFavorite; - netQueue.Enqueue(op); + netQueue.Enqueue(UnitOperation.Withdraw.Create(original)); } PostChangeContents(); } @@ -579,7 +571,7 @@ protected override void SendData(BinaryWriter writer, TEStorageUnit unit) writer.Write(unit.items.Count); foreach (Item item in unit.items) { - ItemIO.Send(item, writer, true, true); + ItemIO.Send(item, writer, true, false); } } @@ -589,7 +581,7 @@ protected override bool ReceiveData(BinaryReader reader, TEStorageUnit unit) int count = reader.ReadInt32(); for (int k = 0; k < count; k++) { - Item item = ItemIO.Receive(reader, true, true); + Item item = ItemIO.Receive(reader, true, false); unit.items.Add(item); ItemData data = new ItemData(item); if (item.stack < item.maxStack) @@ -607,30 +599,26 @@ class DepositOperation : UnitOperation { protected override void SendData(BinaryWriter writer, TEStorageUnit unit) { - ItemIO.Send(data, writer, true, true); + ItemIO.Send(data, writer, true, false); } protected override bool ReceiveData(BinaryReader reader, TEStorageUnit unit) { - unit.DepositItem(ItemIO.Receive(reader, true, true)); + unit.DepositItem(ItemIO.Receive(reader, true, false)); return true; } } class WithdrawOperation : UnitOperation { - public bool SendKeepOneIfFavorite { get; set; } - protected override void SendData(BinaryWriter writer, TEStorageUnit unit) { - writer.Write(SendKeepOneIfFavorite); - ItemIO.Send(data, writer, true, true); + ItemIO.Send(data, writer, true, false); } protected override bool ReceiveData(BinaryReader reader, TEStorageUnit unit) { - bool keepOneIfFavorite = reader.ReadBoolean(); - unit.TryWithdraw(ItemIO.Receive(reader, true, true), keepOneIfFavorite: keepOneIfFavorite); + unit.TryWithdraw(ItemIO.Receive(reader, true, false)); return true; } } diff --git a/CraftingGUI.cs b/CraftingGUI.cs index 3a82f5a9..eeca7bbc 100644 --- a/CraftingGUI.cs +++ b/CraftingGUI.cs @@ -998,8 +998,7 @@ private static void RefreshRecipes(HashSet hiddenRecipes, HashSet craf // show only favorited items if selected .Where(x => (recipeButtons.Choice != RecipeButtonsFavoritesChoice) || favorited.Contains(x.createItem.type)) // hard check if this item can be crafted from available items and their recursive products - .Where(x => !wasItemChecklistRetrieved || IsKnownRecursively(x, availableItemsMutable, temp, tempCache)) - .OrderBy(x => favorited.Contains(x.createItem.type) ? 0 : 1); + .Where(x => !wasItemChecklistRetrieved || IsKnownRecursively(x, availableItemsMutable, temp, tempCache)); threadRecipes.Clear(); threadRecipeAvailable.Clear(); @@ -1715,7 +1714,7 @@ internal static List DoCraft(TEStorageHeart heart, List toWithdraw, List items = new List(); foreach (Item tryWithdraw in toWithdraw) { - Item withdrawn = heart.TryWithdraw(tryWithdraw, false); + Item withdrawn = heart.TryWithdraw(tryWithdraw); if (!withdrawn.IsAir) { items.Add(withdrawn); @@ -1769,7 +1768,7 @@ private static Item DoWithdrawResult(Item item, bool toInventory = false) TEStorageHeart heart = GetHeart(); if (Main.netMode == 0) { - return heart.TryWithdraw(item, false); + return heart.TryWithdraw(item); } else { diff --git a/MagicStorage.cs b/MagicStorage.cs index 58e09fd5..ff9cc64c 100644 --- a/MagicStorage.cs +++ b/MagicStorage.cs @@ -257,14 +257,6 @@ private void AddTranslations() text = CreateTranslation("DepositTooltip"); text.SetDefault("Quick Stack - click, Deposit All - ctrl+click, Restock - right click"); AddTranslation(text); - - text = CreateTranslation("CraftTooltip"); - text.SetDefault("Left click to Craft, Right click to get item for a test (only for new items)"); - AddTranslation(text); - - text = CreateTranslation("TestItemSuffix"); - text.SetDefault(" !UNTIL RESPAWN!"); - AddTranslation(text); } public override void AddRecipeGroups() diff --git a/NetHelper.cs b/NetHelper.cs index 65e024f4..7fb1816a 100644 --- a/NetHelper.cs +++ b/NetHelper.cs @@ -148,18 +148,17 @@ public static void SendDeposit(int ent, Item item) if (Main.netMode == 1) { ModPacket packet = PrepareStorageOperation(ent, 0); - ItemIO.Send(item, packet, true, true); + ItemIO.Send(item, packet, true); packet.Send(); } } - public static void SendWithdraw(int ent, Item item, bool toInventory = false, bool keepOneIfFavorite = false) + public static void SendWithdraw(int ent, Item item, bool toInventory = false) { if (Main.netMode == 1) { ModPacket packet = PrepareStorageOperation(ent, (byte)(toInventory ? 3 : 1)); - packet.Write(keepOneIfFavorite); - ItemIO.Send(item, packet, true, true); + ItemIO.Send(item, packet, true); packet.Send(); } } @@ -172,7 +171,7 @@ public static void SendDepositAll(int ent, List items) packet.Write((byte)items.Count); foreach (Item item in items) { - ItemIO.Send(item, packet, true, true); + ItemIO.Send(item, packet, true); } packet.Send(); } @@ -193,24 +192,23 @@ public static void ReceiveStorageOperation(BinaryReader reader, int sender) byte op = reader.ReadByte(); if (op == 0) { - Item item = ItemIO.Receive(reader, true, true); + Item item = ItemIO.Receive(reader, true); heart.DepositItem(item); if (!item.IsAir) { ModPacket packet = PrepareOperationResult(op); - ItemIO.Send(item, packet, true, true); + ItemIO.Send(item, packet, true); packet.Send(sender); } } else if (op == 1 || op == 3) { - var keepOneIfFavorite = reader.ReadBoolean(); - Item item = ItemIO.Receive(reader, true, true); - item = heart.TryWithdraw(item, keepOneIfFavorite); + Item item = ItemIO.Receive(reader, true); + item = heart.TryWithdraw(item); if (!item.IsAir) { ModPacket packet = PrepareOperationResult(op); - ItemIO.Send(item, packet, true, true); + ItemIO.Send(item, packet, true); packet.Send(sender); } } @@ -221,7 +219,7 @@ public static void ReceiveStorageOperation(BinaryReader reader, int sender) StartUpdateQueue(); for (int k = 0; k < count; k++) { - Item item = ItemIO.Receive(reader, true, true); + Item item = ItemIO.Receive(reader, true); heart.DepositItem(item); if (!item.IsAir) { @@ -235,7 +233,7 @@ public static void ReceiveStorageOperation(BinaryReader reader, int sender) packet.Write((byte)items.Count); foreach (Item item in items) { - ItemIO.Send(item, packet, true, true); + ItemIO.Send(item, packet, true); } packet.Send(sender); } @@ -253,7 +251,7 @@ public static void ReceiveOperationResult(BinaryReader reader) byte op = reader.ReadByte(); if (op == 0 || op == 1 || op == 3) { - Item item = ItemIO.Receive(reader, true, true); + Item item = ItemIO.Receive(reader, true); StoragePlayer.GetItem(item, op != 3); } else if (op == 2) @@ -261,7 +259,7 @@ public static void ReceiveOperationResult(BinaryReader reader) int count = reader.ReadByte(); for (int k = 0; k < count; k++) { - Item item = ItemIO.Receive(reader, true, true); + Item item = ItemIO.Receive(reader, true); StoragePlayer.GetItem(item, false); } } @@ -333,7 +331,7 @@ public static void SendDepositStation(int ent, Item item) if (Main.netMode == 1) { ModPacket packet = PrepareStationOperation(ent, 0); - ItemIO.Send(item, packet, true, true); + ItemIO.Send(item, packet, true); packet.Send(); } } @@ -353,7 +351,7 @@ public static void SendStationSlotClick(int ent, Item item, int slot) if (Main.netMode == 1) { ModPacket packet = PrepareStationOperation(ent, 2); - ItemIO.Send(item, packet, true, true); + ItemIO.Send(item, packet, true); packet.Write((byte)slot); packet.Send(); } @@ -375,12 +373,12 @@ public static void ReceiveStationOperation(BinaryReader reader, int sender) byte op = reader.ReadByte(); if (op == 0) { - Item item = ItemIO.Receive(reader, true, true); + Item item = ItemIO.Receive(reader, true); access.TryDepositStation(item); if (item.stack > 0) { ModPacket packet = PrepareStationResult(op); - ItemIO.Send(item, packet, true, true); + ItemIO.Send(item, packet, true); packet.Send(sender); } } @@ -391,19 +389,19 @@ public static void ReceiveStationOperation(BinaryReader reader, int sender) if (!item.IsAir) { ModPacket packet = PrepareStationResult(op); - ItemIO.Send(item, packet, true, true); + ItemIO.Send(item, packet, true); packet.Send(sender); } } else if (op == 2) { - Item item = ItemIO.Receive(reader, true, true); + Item item = ItemIO.Receive(reader, true); int slot = reader.ReadByte(); item = access.DoStationSwap(item, slot); if (!item.IsAir) { ModPacket packet = PrepareStationResult(op); - ItemIO.Send(item, packet, true, true); + ItemIO.Send(item, packet, true); packet.Send(sender); } } @@ -427,7 +425,7 @@ public static void ReceiveStationResult(BinaryReader reader) } Player player = Main.player[Main.myPlayer]; byte op = reader.ReadByte(); - Item item = ItemIO.Receive(reader, true, true); + Item item = ItemIO.Receive(reader, true); if (op == 2 && Main.playerInventory && Main.mouseItem.IsAir) { Main.mouseItem = item; @@ -487,9 +485,9 @@ public static void SendCraftRequest(int heart, List toWithdraw, Item resul packet.Write(toWithdraw.Count); foreach (Item item in toWithdraw) { - ItemIO.Send(item, packet, true, true); + ItemIO.Send(item, packet, true); } - ItemIO.Send(result, packet, true, true); + ItemIO.Send(result, packet, true); packet.Send(); } } @@ -510,9 +508,9 @@ public static void ReceiveCraftRequest(BinaryReader reader, int sender) List toWithdraw = new List(); for (int k = 0; k < count; k++) { - toWithdraw.Add(ItemIO.Receive(reader, true, true)); + toWithdraw.Add(ItemIO.Receive(reader, true)); } - Item result = ItemIO.Receive(reader, true, true); + Item result = ItemIO.Receive(reader, true); List items = CraftingGUI.DoCraft(heart, toWithdraw, result); if (items.Count > 0) { @@ -521,7 +519,7 @@ public static void ReceiveCraftRequest(BinaryReader reader, int sender) packet.Write(items.Count); foreach (Item item in items) { - ItemIO.Send(item, packet, true, true); + ItemIO.Send(item, packet, true); } packet.Send(sender); } @@ -534,7 +532,7 @@ public static void ReceiveCraftResult(BinaryReader reader) int count = reader.ReadInt32(); for (int k = 0; k < count; k++) { - Item item = ItemIO.Receive(reader, true, true); + Item item = ItemIO.Receive(reader, true); player.QuickSpawnClonedItem(item, item.stack); } } diff --git a/StorageGUI.cs b/StorageGUI.cs index 3fd2ba1b..a67afdfc 100644 --- a/StorageGUI.cs +++ b/StorageGUI.cs @@ -12,7 +12,6 @@ using Terraria.UI; using MagicStorage.Components; using MagicStorage.Sorting; -using Terraria.ID; namespace MagicStorage { @@ -41,7 +40,6 @@ public static bool MouseClicked private static UIElement topBar = new UIElement(); internal static UISearchBar searchBar; private static UIButtonChoice sortButtons; - private static UIToggleButton favoritedOnlyButton; internal static UITextPanel depositButton; internal static UITextPanel restockButton; private static UIElement topBar2 = new UIElement(); @@ -94,11 +92,7 @@ public static void Initialize() InitSortButtons(); topBar.Append(sortButtons); - var x = sortButtons.GetDimensions().Width + 2 * padding; - favoritedOnlyButton.Left.Set(x, 0f); - topBar.Append(favoritedOnlyButton); - - x += favoritedOnlyButton.GetDimensions().Width + 2 * padding; + var x = sortButtons.GetDimensions().Width + 2 * padding; depositButton.Left.Set(x, 0f); depositButton.Width.Set(128f, 0f); @@ -107,8 +101,8 @@ public static void Initialize() depositButton.PaddingBottom = 8f; topBar.Append(depositButton); - x += depositButton.GetDimensions().Width; - + x += depositButton.GetDimensions().Width; + float depositButtonRight = x; searchBar.Left.Set(depositButtonRight + padding, 0f); searchBar.Width.Set(-depositButtonRight - 2 * padding, 1f); @@ -199,11 +193,7 @@ private static void InitSortButtons() { if (sortButtons == null) { - sortButtons = GUIHelpers.MakeSortButtons(StorageGUI.RefreshItems); - } - if (favoritedOnlyButton == null) - { - favoritedOnlyButton = new UIToggleButton(RefreshItems, MagicStorage.Instance.GetTexture("FilterMisc"), Language.GetText("Mods.MagicStorage.ShowOnlyFavorited")); + sortButtons = GUIHelpers.MakeSortButtons(RefreshItems); } } @@ -211,7 +201,7 @@ private static void InitFilterButtons() { if (filterButtons == null) { - filterButtons = GUIHelpers.MakeFilterButtons(true, StorageGUI.RefreshItems); + filterButtons = GUIHelpers.MakeFilterButtons(true, RefreshItems); } } @@ -251,7 +241,6 @@ public static void Draw(TEStorageHeart heart) basePanel.Draw(Main.spriteBatch); slotZone.DrawText(); sortButtons.DrawText(); - favoritedOnlyButton.DrawText(); filterButtons.DrawText(); DrawDepositButton(); } @@ -350,10 +339,9 @@ public static void RefreshItems() FilterMode.All, modFilter, searchBar.Text, 100); } else - itemsLocal = ItemSorter.SortAndFilter(heart.GetStoredItems(), sortMode, filterMode, modFilter, searchBar.Text) - .OrderBy(x => x.favorited ? 0 : 1); + itemsLocal = ItemSorter.SortAndFilter(heart.GetStoredItems(), sortMode, filterMode, modFilter, searchBar.Text); - items.AddRange(itemsLocal.Where(x => !favoritedOnlyButton.Value || x.favorited)); + items.AddRange(itemsLocal); }; doFiltering(); @@ -445,18 +433,6 @@ private static void HoverItemSlot(int slot, ref int hoverSlot) } else if (Main.mouseItem.IsAir && slot < items.Count && !items[slot].IsAir) { - if (Main.keyState.IsKeyDown(Keys.LeftAlt)) - { - if (Main.netMode == NetmodeID.SinglePlayer) - items[slot].favorited = !items[slot].favorited; - else - Main.NewTextMultiline("TOggling item as favorite is not implemented in multiplayer but you can withdraw this item, toggle it in inventory and deposit again"); - // there is no item instance id and there is no concept of slot # in heart so we can't send this in operation - // a workaropund would be to withdraw and deposit it back with changed favorite flag - // but it still might look ugly for the player that initiates operation - } - else - { Item toWithdraw = items[slot].Clone(); if (toWithdraw.stack > toWithdraw.maxStack) { @@ -468,7 +444,6 @@ private static void HoverItemSlot(int slot, ref int hoverSlot) Main.mouseItem = player.GetItem(Main.myPlayer, Main.mouseItem, false, true); } changed = true; - } } if (changed) { @@ -607,7 +582,7 @@ private static bool TryRestock() { var toWithdraw = item.Clone(); toWithdraw.stack = item.maxStack - item.stack; - toWithdraw = DoWithdraw(toWithdraw, true, true); + toWithdraw = DoWithdraw(toWithdraw, true); if (!toWithdraw.IsAir) { item.stack += toWithdraw.stack; @@ -620,16 +595,16 @@ private static bool TryRestock() return changed; } - private static Item DoWithdraw(Item item, bool toInventory = false, bool keepOneIfFavorite = false) + private static Item DoWithdraw(Item item, bool toInventory = false) { TEStorageHeart heart = GetHeart(); if (Main.netMode == 0) { - return heart.TryWithdraw(item, keepOneIfFavorite); + return heart.TryWithdraw(item); } else { - NetHelper.SendWithdraw(heart.ID, item, toInventory, keepOneIfFavorite); + NetHelper.SendWithdraw(heart.ID, item, toInventory); return new Item(); } } From 31ecb781926bae92da902393b7b88718eda94139 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Mon, 27 Aug 2018 14:58:52 +0300 Subject: [PATCH 78/80] reverted (not real changes) --- Components/TECraftingAccess.cs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/Components/TECraftingAccess.cs b/Components/TECraftingAccess.cs index b04d1ac5..c078c68b 100644 --- a/Components/TECraftingAccess.cs +++ b/Components/TECraftingAccess.cs @@ -13,13 +13,11 @@ namespace MagicStorage.Components { public class TECraftingAccess : TEStorageComponent { - public const int ItemsTotal = 10; - - public Item[] stations = new Item[ItemsTotal]; + public Item[] stations = new Item[10]; public TECraftingAccess() { - for (int k = 0; k < ItemsTotal; k++) + for (int k = 0; k < 10; k++) { stations[k] = new Item(); } @@ -134,8 +132,8 @@ public override void Load(TagCompound tag) { for (int k = 0; k < stations.Length; k++) { - stations[k] = ItemIO.Load(listStations[k]); - } + stations[k] = ItemIO.Load(listStations[k]); + } } } From 80490543371f4e499661c01cbd7c83de69825dbe Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Mon, 27 Aug 2018 15:01:30 +0300 Subject: [PATCH 79/80] small fix for search bar --- UISearchBar.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/UISearchBar.cs b/UISearchBar.cs index 2cc8197d..4fd3f4ca 100644 --- a/UISearchBar.cs +++ b/UISearchBar.cs @@ -98,18 +98,22 @@ public override void Update(GameTime gameTime) if (cursorPosition < text.Length && text.Length > 0) prev = prev.Remove(cursorPosition); string newString = Main.GetInputText(prev); + bool changed = false; if (!newString.Equals(prev)) { int newStringLength = newString.Length; if (prev != text) newString += text.Substring(cursorPosition); text = newString; cursorPosition = newStringLength; - StorageGUI.RefreshItems(); + changed = true; } if (KeyTyped(Keys.Delete)) { if (text.Length > 0 && cursorPosition < text.Length) + { text = text.Remove(cursorPosition, 1); + changed = true; + } } if (KeyTyped(Keys.Left)) { @@ -127,6 +131,7 @@ public override void Update(GameTime gameTime) { cursorPosition = text.Length; } + if (changed) StorageGUI.RefreshItems(); if (KeyTyped(Keys.Enter) || KeyTyped(Keys.Tab) || KeyTyped(Keys.Escape)) { hasFocus = false; From fad5cf478d6316d8754ce53c2873c6011bd32947 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Mon, 27 Aug 2018 15:04:53 +0300 Subject: [PATCH 80/80] reverted empty changes --- NetHelper.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/NetHelper.cs b/NetHelper.cs index 7fb1816a..20bf7fc9 100644 --- a/NetHelper.cs +++ b/NetHelper.cs @@ -205,7 +205,7 @@ public static void ReceiveStorageOperation(BinaryReader reader, int sender) { Item item = ItemIO.Receive(reader, true); item = heart.TryWithdraw(item); - if (!item.IsAir) + if (!item.IsAir) { ModPacket packet = PrepareOperationResult(op); ItemIO.Send(item, packet, true); @@ -551,4 +551,4 @@ enum MessageType : byte CraftRequest, CraftResult } -} +} \ No newline at end of file